@@ -2437,6 +2441,14 @@ function updateUserList(){
},200);
}
+
+function resetCanvas(){
+ session.streamSrc.getVideoTracks().forEach((track) => {
+ session.canvasSource.width = track.getSettings().width || 1280;
+ session.canvasSource.height = track.getSettings().height || 720;
+ });
+}
+
var LaunchTFWorkerCallback = false;
function TFLiteWorker(){
if (session.tfliteModule==false){
@@ -2471,6 +2483,8 @@ function TFLiteWorker(){
function process(){
if (session.tfliteModule.activelyProcessing){return;}
session.tfliteModule.activelyProcessing=true;
+
+
try{
segmentationMaskCtx.drawImage(
session.canvasSource,
@@ -3441,7 +3455,7 @@ function directorSendMessage(ele) {
inputField.style.margin = "5px 10px 5px 10px";
inputField.style.padding = "5px";
- target.appendChild(inputField);
+
var sendButton = document.createElement("button");
sendButton.innerHTML = "
send message ";
@@ -3501,6 +3515,7 @@ function directorSendMessage(ele) {
target.appendChild(closeButton);
target.appendChild(sendButton);
target.appendChild(overlayMsg);
+ target.appendChild(inputField);
ele.parentNode.appendChild(target);
inputField.focus();
inputField.select();
@@ -4661,7 +4676,7 @@ session.publishIFrame = function(iframeURL){
container.id = "container";
var iframe = document.createElement("iframe");
- iframe.allow = "autoplay;camera;microphone;fullscreen;picture-in-picture;transparency;";
+ iframe.allow = "autoplay;camera;microphone;fullscreen;picture-in-picture;";
iframe.src = session.iframeSrc;
iframe.id = "iframe_source"
session.iframeEle = iframe;
@@ -7706,17 +7721,17 @@ function resetupAudioOut() {
function obfuscateURL(input) {
if (input.startsWith("https://obs.ninja/")) {
- input = input.replace('https://obs.ninja/', '');
+ input = input.replace('https://obs.ninja/', 'obs.ninja/');
} else if (input.startsWith("http://obs.ninja/")) {
- input = input.replace('http://obs.ninja/', '');
+ input = input.replace('http://obs.ninja/', 'obs.ninja/');
} else if (input.startsWith("obs.ninja/")) {
- input = input.replace('obs.ninja/', '');
+ input = input.replace('obs.ninja/', 'obs.ninja/');
} else if (input.startsWith("https://vdo.ninja/")) {
- input = input.replace('https://vdo.ninja/', '');
+ input = input.replace('https://vdo.ninja/', 'vdo.ninja/');
} else if (input.startsWith("http://vdo.ninja/")) {
- input = input.replace('http://vdo.ninja/', '');
+ input = input.replace('http://vdo.ninja/', 'vdo.ninja/');
} else if (input.startsWith("vdo.ninja/")) {
- input = input.replace('vdo.ninja/', '');
+ input = input.replace('vdo.ninja/', 'vdo.ninja/');
}
input = input.replace('&view=', '&v=');
@@ -7902,25 +7917,66 @@ if (navigator.userAgent.toLowerCase().indexOf(' electron/') > -1) { // this ena
window.navigator.mediaDevices.getDisplayMedia = () => {
return new Promise(async (resolve, reject) => {
try {
-
if (session.autostart){
- var sscid = 0
- if (typeof session.screenshare === "number"){
- sscid = session.screenshare-1;
- if (sscid<0){sscid=0;}
+ if (parseInt(session.screenshare)+"" === session.screenshare){
+ var sscid = parseInt(session.screenshare)-1;
+ if (sscid<0){sscid=0;}
+ const sources = await desktopCapturer.getSources({ types: ['screen'] });
+ const stream = await window.navigator.mediaDevices.getUserMedia({
+ audio: false,
+ video: {
+ mandatory: {
+ chromeMediaSource: 'desktop',
+ chromeMediaSourceId: sources[sscid].id,
+ maxFrameRate: 60
+ }
+ }
+ });
+ resolve(stream);
+ } else if (session.screenshare!==true){
+ var sscid=null;
+ const sources = await desktopCapturer.getSources({ types: ['window'] });
+ for (var i=0; i
-1) { // this ena
}
ElectronDesktopCapture = true;
} catch(e){
- warnlog("couldn't load electron's screen capture; you might need to decrease security permissions a bit.");
+ warnlog("Couldn't load electron's screen capture. Elevate the app's permission to allow it (right-click?)");
}
}
@@ -10387,7 +10443,7 @@ function dragElement(elmnt) {
function previewIframe(iframesrc) { // this is pretty important if you want to avoid camera permission popup problems. You can also call it automatically via: loadIframe();"> , but don't call it before the page loads.
var iframe = document.createElement("iframe");
- iframe.allow = "autoplay;camera;microphone;fullscreen;transparency;picture-in-picture;";
+ iframe.allow = "autoplay;camera;microphone;fullscreen;picture-in-picture;";
iframe.style.width = "100%";
iframe.style.height = "100%";
iframe.style.border = "10px dashed rgb(64 65 62)";
@@ -10437,7 +10493,7 @@ function previewIframe(iframesrc) { // this is pretty important if you want to a
function loadIframe(iframesrc) { // this is pretty important if you want to avoid camera permission popup problems. You can also call it automatically via: loadIframe();"> , but don't call it before the page loads.
var iframe = document.createElement("iframe");
- iframe.allow = "autoplay;camera;microphone;fullscreen;transparency;picture-in-picture;";
+ iframe.allow = "autoplay;camera;microphone;fullscreen;picture-in-picture;";
iframe.style.width = "100%";
iframe.style.height = "100%";
iframe.style.border = "10px dashed rgb(64 65 62)";
@@ -12268,8 +12324,7 @@ function createIframePopup() {
}
var iframe = document.createElement("iframe");
- iframe.allow = "autoplay;camera;microphone;fullscreen;picture-in-picture;transparency;";
- iframe.allowtransparency = "true";
+ iframe.allow = "autoplay;camera;microphone;fullscreen;picture-in-picture;";
var extras = "";
if (session.password){
@@ -13391,11 +13446,18 @@ function getChatMessage(msg, label = false, director = false, overlay = false) {
function updateClosedCaptions(msg, label, UUID) {
msg.counter = parseInt(msg.counter);
- var transcript = sanitizeChat(msg.transcript); // keep it clean.
+ var temp = document.createElement('div');
+ temp.innerText = msg.transcript;
+ temp.innerText = temp.innerHTML;
+ var transcript = temp.textContent || temp.innerText || "";
+
if (transcript == "") {
return;
}
- transcript = transcript.toUpperCase();
+
+ transcript = transcript.charAt(0).toUpperCase() + transcript.slice(1);
+ //transcript = transcript.substr(-1, 5000); // keep it from being too long
+
if (label) {
label = sanitizeLabel(label);
@@ -14653,6 +14715,7 @@ function attemptTFLiteJsFileLoad(){
if (session.tfliteModule!==false){
return true;
}
+ warnUser("Loading effects model...");
TFLITELOADING=true;
session.tfliteModule={};
@@ -14685,7 +14748,8 @@ async function changeTFLiteImage(ev, ele){
async function loadTFLiteModel(){
- try{
+ try {
+
if (session.tfliteModule && (session.tfliteModule.img)){
var img = session.tfliteModule.img;
session.tfliteModule = await createTFLiteSIMDModule();
@@ -14702,6 +14766,7 @@ async function loadTFLiteModel(){
}
} catch(e){
warnlog("TF-LITE FAILED TO LOAD");
+ closeModal();
return;
}
const modelResponse = await fetch("./thirdparty/tflite/segm_full_v679.tflite");
@@ -14711,6 +14776,7 @@ async function loadTFLiteModel(){
session.tfliteModule._loadModel(session.tfliteModule.model.byteLength);
session.tfliteModule.activelyProcessing = false;
TFLITELOADING = false;
+ closeModal();
if ((session.effects>=3) && (session.effects<=5)){
if (document.getElementById("videosource")){
activatedPreview=false;
diff --git a/main.css b/main.css
index 09903b1..d7b1557 100644
--- a/main.css
+++ b/main.css
@@ -368,9 +368,6 @@ hr {
padding: 0;
overflow: hidden;
margin: var(--video-margin);
- transition-property: all;
- transition-duration: 1s;
- transition-timing-function: ease-in;
}
#gridlayout {
diff --git a/main.js b/main.js
index 0779613..cef400b 100644
--- a/main.js
+++ b/main.js
@@ -286,7 +286,7 @@ async function main(){ // main asyncronous thread; mostly initializes the user s
} else if (urlParams.has('screenshare') || urlParams.has('ss')) {
session.screenshare = true;
if (urlParams.get('screenshare') || urlParams.get('ss')){
- session.screenshare = parseInt(urlParams.get('screenshare'));
+ session.screenshare = urlParams.get('screenshare') || urlParams.get('ss');
}
} else if (urlParams.has('fileshare') || urlParams.has('fs')) {
getById("container-5").classList.remove('advanced');
@@ -2362,16 +2362,18 @@ async function main(){ // main asyncronous thread; mostly initializes the user s
document.head.appendChild(script4);
}
script4.onload = function() {
+ closeModal();
async function loadModel(){
model = await faceLandmarksDetection.load(faceLandmarksDetection.SupportedPackages.mediapipeFacemesh);
}
loadModel();
}
- script.src = "https://unpkg.com/@tensorflow/tfjs-core@2.4.0/dist/tf-core.js";
- script2.src = "https://unpkg.com/@tensorflow/tfjs-converter@2.4.0/dist/tf-converter.js";
- script3.src = "https://unpkg.com/@tensorflow/tfjs-backend-webgl@2.4.0/dist/tf-backend-webgl.js";
- script4.src = "https://unpkg.com/@tensorflow-models/face-landmarks-detection@0.0.1/dist/face-landmarks-detection.js";
+ script.src = "./thirdparty/tfjs/tf-core.js";
+ script2.src = "./thirdparty/tfjs/tf-converter.js";
+ script3.src = "./thirdparty/tfjs/tf-backend-webgl.js";
+ script4.src = "./thirdparty/tfjs/face-landmarks-detection.js";
+ warnUser("Loading effects model...");
script.type = 'text/javascript';script2.type = 'text/javascript';script3.type = 'text/javascript';script4.type = 'text/javascript';
document.head.appendChild(script);
diff --git a/thirdparty/ffmpeg.min.js b/thirdparty/ffmpeg.min.js
new file mode 100644
index 0000000..ce1a48c
--- /dev/null
+++ b/thirdparty/ffmpeg.min.js
@@ -0,0 +1,5 @@
+// https://unpkg.com/@ffmpeg/ffmpeg@0.10.1/dist/ffmpeg.min.js
+// MIT License - https://github.com/ffmpegwasm/ffmpeg.wasm
+// Copyright (c) 2019 Jerome Wu
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FFmpeg=t():e.FFmpeg=t()}(self,(function(){return e={497:(e,t,r)=>{r(72);var n=r(306).devDependencies;e.exports={corePath:"https://unpkg.com/@ffmpeg/core@".concat(n["@ffmpeg/core"].substring(1),"/dist/ffmpeg-core.js")}},663:(e,t,r)=>{function n(e,t,r,n,o,i,a){try{var c=e[i](a),s=c.value}catch(e){return void r(e)}c.done?t(s):Promise.resolve(s).then(n,o)}var o=r(72),i=function(e){return new Promise((function(t,r){var n=new FileReader;n.onload=function(){t(n.result)},n.onerror=function(e){var t=e.target.error.code;r(Error("File could not be read! Code=".concat(t)))},n.readAsArrayBuffer(e)}))};e.exports=function(){var e,t=(e=regeneratorRuntime.mark((function e(t){var r,n;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t,void 0!==t){e.next=3;break}return e.abrupt("return",new Uint8Array);case 3:if("string"!=typeof t){e.next=16;break}if(!/data:_data\/([a-zA-Z]*);base64,([^"]*)/.test(t)){e.next=8;break}r=atob(t.split(",")[1]).split("").map((function(e){return e.charCodeAt(0)})),e.next=14;break;case 8:return e.next=10,fetch(o(t));case 10:return n=e.sent,e.next=13,n.arrayBuffer();case 13:r=e.sent;case 14:e.next=20;break;case 16:if(!(t instanceof File||t instanceof Blob)){e.next=20;break}return e.next=19,i(t);case 19:r=e.sent;case 20:return e.abrupt("return",new Uint8Array(r));case 21:case"end":return e.stop()}}),e)})),function(){var t=this,r=arguments;return new Promise((function(o,i){var a=e.apply(t,r);function c(e){n(a,o,i,c,s,"next",e)}function s(e){n(a,o,i,c,s,"throw",e)}c(void 0)}))});return function(e){return t.apply(this,arguments)}}()},452:(e,t,r)=>{function n(e,t,r,n,o,i,a){try{var c=e[i](a),s=c.value}catch(e){return void r(e)}c.done?t(s):Promise.resolve(s).then(n,o)}function o(e){return function(){var t=this,r=arguments;return new Promise((function(o,i){var a=e.apply(t,r);function c(e){n(a,o,i,c,s,"next",e)}function s(e){n(a,o,i,c,s,"throw",e)}c(void 0)}))}}var i=r(72),a=r(185).log,c=function(){var e=o(regeneratorRuntime.mark((function e(t,r){var n,o,i;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a("info","fetch ".concat(t)),e.next=3,fetch(t);case 3:return e.next=5,e.sent.arrayBuffer();case 5:return n=e.sent,a("info","".concat(t," file size = ").concat(n.byteLength," bytes")),o=new Blob([n],{type:r}),i=URL.createObjectURL(o),a("info","".concat(t," blob URL = ").concat(i)),e.abrupt("return",i);case 11:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();e.exports=function(){var e=o(regeneratorRuntime.mark((function e(t){var r,n,o,s,u;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("string"==typeof(r=t.corePath)){e.next=3;break}throw Error("corePath should be a string!");case 3:return n=i(r),e.next=6,c(n,"application/javascript");case 6:return o=e.sent,e.next=9,c(n.replace("ffmpeg-core.js","ffmpeg-core.wasm"),"application/wasm");case 9:return s=e.sent,e.next=12,c(n.replace("ffmpeg-core.js","ffmpeg-core.worker.js"),"application/javascript");case 12:if(u=e.sent,"undefined"!=typeof createFFmpegCore){e.next=15;break}return e.abrupt("return",new Promise((function(e){var t=document.createElement("script");t.src=o,t.type="text/javascript",t.addEventListener("load",(function r(){t.removeEventListener("load",r),a("info","ffmpeg-core.js script loaded"),e({createFFmpegCore,corePath:o,wasmPath:s,workerPath:u})})),document.getElementsByTagName("head")[0].appendChild(t)})));case 15:return a("info","ffmpeg-core.js script is loaded already"),e.abrupt("return",Promise.resolve({createFFmpegCore,corePath:o,wasmPath:s,workerPath:u}));case 17:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()},698:(e,t,r)=>{var n=r(497),o=r(452),i=r(663);e.exports={defaultOptions:n,getCreateFFmpegCore:o,fetchFile:i}},500:e=>{e.exports={defaultArgs:["./ffmpeg","-nostdin","-y"],baseOptions:{log:!1,logger:function(){},progress:function(){},corePath:""}}},906:(e,t,r)=>{function n(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}var l=r(500),p=l.defaultArgs,h=l.baseOptions,m=r(185),g=m.setLogging,d=m.setCustomLogger,y=m.log,v=r(583),b=r(319),w=r(698),x=w.defaultOptions,j=w.getCreateFFmpegCore,E=r(306).version,O=Error("ffmpeg.wasm is not ready, make sure you have completed load().");e.exports=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=s(s(s({},h),x),e),r=t.log,o=t.logger,i=t.progress,c=f(t,["log","logger","progress"]),u=null,l=null,m=null,w=!1,F=i,L=function(e){"FFMPEG_END"===e&&null!==m&&(m(),m=null,w=!1)},P=function(e){var t=e.type,r=e.message;y(t,r),v(r,F),L(r)},k=function(){var e=a(regeneratorRuntime.mark((function e(){var t,r,n,o,i;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(y("info","load ffmpeg-core"),null!==u){e.next=17;break}return y("info","loading ffmpeg-core"),e.next=5,j(c);case 5:return t=e.sent,r=t.createFFmpegCore,n=t.corePath,o=t.workerPath,i=t.wasmPath,e.next=12,r({mainScriptUrlOrBlob:n,printErr:function(e){return P({type:"fferr",message:e})},print:function(e){return P({type:"ffout",message:e})},locateFile:function(e,t){if("undefined"!=typeof window){if(void 0!==i&&e.endsWith("ffmpeg-core.wasm"))return i;if(void 0!==o&&e.endsWith("ffmpeg-core.worker.js"))return o}return t+e}});case 12:u=e.sent,l=u.cwrap("proxy_main","number",["number","number"]),y("info","ffmpeg-core loaded"),e.next=18;break;case 17:throw Error("ffmpeg.wasm was loaded, you should not load it again, use ffmpeg.isLoaded() to check next time.");case 18:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),S=function(){return null!==u},A=function(){for(var e=arguments.length,t=new Array(e),r=0;r1?t-1:0),n=1;n")})).join(" "))),null===u)throw O;var o=null;try{var i;o=(i=u.FS)[e].apply(i,r)}catch(t){throw"readdir"===e?Error("ffmpeg.FS('readdir', '".concat(r[0],"') error. Check if the path exists, ex: ffmpeg.FS('readdir', '/')")):"readFile"===e?Error("ffmpeg.FS('readFile', '".concat(r[0],"') error. Check if the path exists")):Error("Oops, something went wrong in FS operation.")}return o},C=function(){if(null===u)throw O;w=!1,u.exit(1),u=null,l=null,m=null},R=function(e){F=e},T=function(e){d(e)};return g(r),d(o),y("info","use ffmpeg.wasm v".concat(E)),{setProgress:R,setLogger:T,setLogging:g,load:k,isLoaded:S,run:A,exit:C,FS:_}}},352:(e,t,r)=>{r(666);var n=r(906),o=r(698).fetchFile;e.exports={createFFmpeg:n,fetchFile:o}},185:e=>{var t=!1,r=function(){};e.exports={logging:t,setLogging:function(e){t=e},setCustomLogger:function(e){r=e},log:function(e,n){r({type:e,message:n}),t&&console.log("[".concat(e,"] ").concat(n))}}},319:e=>{e.exports=function(e,t){var r=e._malloc(t.length*Uint32Array.BYTES_PER_ELEMENT);return t.forEach((function(t,n){var o=e._malloc(t.length+1);e.writeAsciiToMemory(t,o),e.setValue(r+Uint32Array.BYTES_PER_ELEMENT*n,o,"i32")})),[t.length,r]}},583:e=>{function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);ra)&&(r=a)}else if(e.startsWith("frame")||e.startsWith("size")){var c=e.split("time=")[1].split(" ")[0],s=o(c);t({ratio:n=s/r,time:s})}else e.startsWith("video:")&&(t({ratio:1}),r=0)}},666:e=>{var t=function(e){"use strict";var t,r=Object.prototype,n=r.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",c=o.toStringTag||"@@toStringTag";function s(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,r){return e[t]=r}}function u(e,t,r,n){var o=t&&t.prototype instanceof d?t:d,i=Object.create(o.prototype),a=new k(n||[]);return i._invoke=function(e,t,r){var n=l;return function(o,i){if(n===h)throw new Error("Generator is already running");if(n===m){if("throw"===o)throw i;return A()}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var c=F(a,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===l)throw n=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=h;var s=f(e,t,r);if("normal"===s.type){if(n=r.done?m:p,s.arg===g)continue;return{value:s.arg,done:r.done}}"throw"===s.type&&(n=m,r.method="throw",r.arg=s.arg)}}}(e,r,a),i}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=u;var l="suspendedStart",p="suspendedYield",h="executing",m="completed",g={};function d(){}function y(){}function v(){}var b={};b[i]=function(){return this};var w=Object.getPrototypeOf,x=w&&w(w(S([])));x&&x!==r&&n.call(x,i)&&(b=x);var j=v.prototype=d.prototype=Object.create(b);function E(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function O(e,t){function r(o,i,a,c){var s=f(e[o],e,i);if("throw"!==s.type){var u=s.arg,l=u.value;return l&&"object"==typeof l&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,a,c)}),(function(e){r("throw",e,a,c)})):t.resolve(l).then((function(e){u.value=e,a(u)}),(function(e){return r("throw",e,a,c)}))}c(s.arg)}var o;this._invoke=function(e,n){function i(){return new t((function(t,o){r(e,n,t,o)}))}return o=o?o.then(i,i):i()}}function F(e,r){var n=e.iterator[r.method];if(n===t){if(r.delegate=null,"throw"===r.method){if(e.iterator.return&&(r.method="return",r.arg=t,F(e,r),"throw"===r.method))return g;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var o=f(n,e.iterator,r.arg);if("throw"===o.type)return r.method="throw",r.arg=o.arg,r.delegate=null,g;var i=o.arg;return i?i.done?(r[e.resultName]=i.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,g):i:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function L(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function P(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function k(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(L,this),this.reset(!0)}function S(e){if(e){var r=e[i];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,a=function r(){for(;++o=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),u=n.call(a,"finallyLoc");if(s&&u){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),P(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;P(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:S(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),g}},e}(e.exports);try{regeneratorRuntime=t}catch(e){Function("r","regeneratorRuntime = r")(t)}},72:function(e,t,r){var n,o;void 0===(o="function"==typeof(n=function(){return function(){var e=arguments.length;if(0===e)throw new Error("resolveUrl requires at least one argument; got none.");var t=document.createElement("base");if(t.href=arguments[0],1===e)return t.href;var r=document.getElementsByTagName("head")[0];r.insertBefore(t,r.firstChild);for(var n,o=document.createElement("a"),i=1;i{"use strict";e.exports=JSON.parse('{"name":"@ffmpeg/ffmpeg","version":"0.10.1","description":"FFmpeg WebAssembly version","main":"src/index.js","types":"src/index.d.ts","directories":{"example":"examples"},"scripts":{"start":"node scripts/server.js","build":"rimraf dist && webpack --config scripts/webpack.config.prod.js","prepublishOnly":"npm run build","lint":"eslint src","wait":"rimraf dist && wait-on http://localhost:3000/dist/ffmpeg.dev.js","test":"npm-run-all -p -r start test:all","test:all":"npm-run-all wait test:browser:ffmpeg test:node:all","test:node":"node --experimental-wasm-threads --experimental-wasm-bulk-memory node_modules/.bin/_mocha --exit --bail --require ./scripts/test-helper.js","test:node:all":"npm run test:node -- ./tests/*.test.js","test:browser":"mocha-headless-chrome -a allow-file-access-from-files -a incognito -a no-sandbox -a disable-setuid-sandbox -a disable-logging -t 300000","test:browser:ffmpeg":"npm run test:browser -- -f ./tests/ffmpeg.test.html"},"browser":{"./src/node/index.js":"./src/browser/index.js"},"repository":{"type":"git","url":"git+https://github.com/ffmpegwasm/ffmpeg.wasm.git"},"keywords":["ffmpeg","WebAssembly","video"],"author":"Jerome Wu ","license":"MIT","bugs":{"url":"https://github.com/ffmpegwasm/ffmpeg.wasm/issues"},"engines":{"node":">=12.16.1"},"homepage":"https://github.com/ffmpegwasm/ffmpeg.wasm#readme","dependencies":{"is-url":"^1.2.4","node-fetch":"^2.6.1","regenerator-runtime":"^0.13.7","resolve-url":"^0.2.1"},"devDependencies":{"@babel/core":"^7.12.3","@babel/preset-env":"^7.12.1","@ffmpeg/core":"^0.10.0","@types/emscripten":"^1.39.4","babel-loader":"^8.1.0","chai":"^4.2.0","cors":"^2.8.5","eslint":"^7.12.1","eslint-config-airbnb-base":"^14.1.0","eslint-plugin-import":"^2.22.1","express":"^4.17.1","mocha":"^8.2.1","mocha-headless-chrome":"^2.0.3","npm-run-all":"^4.1.5","wait-on":"^5.3.0","webpack":"^5.3.2","webpack-cli":"^4.1.0","webpack-dev-middleware":"^4.0.0"}}')}},t={},function r(n){if(t[n])return t[n].exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}(352);var e,t}));
+//# sourceMappingURL=ffmpeg.min.js.map
\ No newline at end of file
diff --git a/thirdparty/tfjs/face-landmarks-detection.js b/thirdparty/tfjs/face-landmarks-detection.js
new file mode 100644
index 0000000..cb2f93d
--- /dev/null
+++ b/thirdparty/tfjs/face-landmarks-detection.js
@@ -0,0 +1,1497 @@
+/**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tensorflow/tfjs-core'), require('@tensorflow/tfjs-converter')) :
+ typeof define === 'function' && define.amd ? define(['exports', '@tensorflow/tfjs-core', '@tensorflow/tfjs-converter'], factory) :
+ (global = global || self, factory(global.faceLandmarksDetection = {}, global.tf, global.tf));
+}(this, (function (exports, tf, tfconv) { 'use strict';
+
+ /*! *****************************************************************************
+ Copyright (c) Microsoft Corporation.
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ PERFORMANCE OF THIS SOFTWARE.
+ ***************************************************************************** */
+
+ var __assign = function() {
+ __assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+ };
+
+ function __awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ }
+
+ function __generator(thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (_) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+ }
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function __awaiter$1(e,t,n,r){return new(n||(n=Promise))(function(o,i){function a(e){try{c(r.next(e));}catch(e){i(e);}}function s(e){try{c(r.throw(e));}catch(e){i(e);}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t);})).then(a,s);}c((r=r.apply(e,t||[])).next());})}function __generator$1(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=(o=a.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]= LANDMARKS_COUNT;
+ var indexOfMouth = MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES[0], indexOfForehead = MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES[1];
+ if (boxLandmarksFromMeshModel === false) {
+ indexOfMouth = BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES[0], indexOfForehead = BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES[1];
+ }
+ angle = computeRotation(box.landmarks[indexOfMouth], box.landmarks[indexOfForehead]);
+ var faceCenter = getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint });
+ var faceCenterNormalized = [faceCenter[0] / input.shape[2], faceCenter[1] / input.shape[1]];
+ var rotatedImage = input;
+ var rotationMatrix = IDENTITY_MATRIX;
+ if (angle !== 0) {
+ rotatedImage =
+ tf.image.rotateWithOffset(input, angle, 0, faceCenterNormalized);
+ rotationMatrix = buildRotationMatrix(-angle, faceCenter);
+ }
+ var boxCPU = { startPoint: box.startPoint, endPoint: box.endPoint };
+ var face = tf.div(cutBoxFromImageAndResize(boxCPU, rotatedImage, [
+ _this.meshHeight, _this.meshWidth
+ ]), 255);
+ // The first returned tensor represents facial contours, which are
+ // included in the coordinates.
+ var _a = _this.meshDetector.predict(face), flag = _a[1], coords = _a[2];
+ var coordsReshaped = tf.reshape(coords, [-1, 3]);
+ var rawCoords = coordsReshaped.arraySync();
+ if (predictIrises) {
+ var _b = _this.getEyeBox(rawCoords, face, LEFT_EYE_BOUNDS[0], LEFT_EYE_BOUNDS[1], true), leftEyeBox = _b.box, leftEyeBoxSize = _b.boxSize, leftEyeCrop = _b.crop;
+ var _c = _this.getEyeBox(rawCoords, face, RIGHT_EYE_BOUNDS[0], RIGHT_EYE_BOUNDS[1]), rightEyeBox = _c.box, rightEyeBoxSize = _c.boxSize, rightEyeCrop = _c.crop;
+ var eyePredictions = (_this.irisModel.predict(tf.concat([leftEyeCrop, rightEyeCrop])));
+ var eyePredictionsData = eyePredictions.dataSync();
+ var leftEyeData = eyePredictionsData.slice(0, IRIS_NUM_COORDINATES * 3);
+ var _d = _this.getEyeCoords(leftEyeData, leftEyeBox, leftEyeBoxSize, true), leftEyeRawCoords = _d.rawCoords, leftIrisRawCoords = _d.iris;
+ var rightEyeData = eyePredictionsData.slice(IRIS_NUM_COORDINATES * 3);
+ var _e = _this.getEyeCoords(rightEyeData, rightEyeBox, rightEyeBoxSize), rightEyeRawCoords = _e.rawCoords, rightIrisRawCoords = _e.iris;
+ var leftToRightEyeDepthDifference = _this.getLeftToRightEyeDepthDifference(rawCoords);
+ if (Math.abs(leftToRightEyeDepthDifference) <
+ 30) { // User is looking straight ahead.
+ replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left');
+ replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right');
+ }
+ else if (leftToRightEyeDepthDifference < 1) { // User is looking
+ // towards the
+ // right.
+ // If the user is looking to the left or to the right, the iris
+ // coordinates tend to diverge too much from the mesh coordinates
+ // for them to be merged. So we only update a single contour line
+ // above and below the eye.
+ replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left', ['EyeUpper0', 'EyeLower0']);
+ }
+ else { // User is looking towards the left.
+ replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right', ['EyeUpper0', 'EyeLower0']);
+ }
+ var adjustedLeftIrisCoords = _this.getAdjustedIrisCoords(rawCoords, leftIrisRawCoords, 'left');
+ var adjustedRightIrisCoords = _this.getAdjustedIrisCoords(rawCoords, rightIrisRawCoords, 'right');
+ rawCoords = rawCoords.concat(adjustedLeftIrisCoords)
+ .concat(adjustedRightIrisCoords);
+ }
+ var transformedCoordsData = _this.transformRawCoords(rawCoords, box, angle, rotationMatrix);
+ var transformedCoords = tf.tensor2d(transformedCoordsData);
+ var landmarksBox = enlargeBox(_this.calculateLandmarksBoundingBox(transformedCoordsData));
+ var squarifiedLandmarksBox = squarifyBox(landmarksBox);
+ _this.regionsOfInterest[i] = __assign({}, squarifiedLandmarksBox, { landmarks: transformedCoords.arraySync() });
+ var prediction = {
+ coords: tf.tensor2d(rawCoords, [rawCoords.length, 3]),
+ scaledCoords: transformedCoords,
+ box: landmarksBox,
+ flag: tf.squeeze(flag)
+ };
+ return prediction;
+ });
+ })];
+ }
+ });
+ });
+ };
+ // Updates regions of interest if the intersection over union between
+ // the incoming and previous regions falls below a threshold.
+ Pipeline.prototype.updateRegionsOfInterest = function (boxes) {
+ for (var i = 0; i < boxes.length; i++) {
+ var box = boxes[i];
+ var previousBox = this.regionsOfInterest[i];
+ var iou = 0;
+ if (previousBox && previousBox.startPoint) {
+ var _a = box.startPoint, boxStartX = _a[0], boxStartY = _a[1];
+ var _b = box.endPoint, boxEndX = _b[0], boxEndY = _b[1];
+ var _c = previousBox.startPoint, previousBoxStartX = _c[0], previousBoxStartY = _c[1];
+ var _d = previousBox.endPoint, previousBoxEndX = _d[0], previousBoxEndY = _d[1];
+ var xStartMax = Math.max(boxStartX, previousBoxStartX);
+ var yStartMax = Math.max(boxStartY, previousBoxStartY);
+ var xEndMin = Math.min(boxEndX, previousBoxEndX);
+ var yEndMin = Math.min(boxEndY, previousBoxEndY);
+ var intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);
+ var boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);
+ var previousBoxArea = (previousBoxEndX - previousBoxStartX) *
+ (previousBoxEndY - boxStartY);
+ iou = intersection / (boxArea + previousBoxArea - intersection);
+ }
+ if (iou < UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD) {
+ this.regionsOfInterest[i] = box;
+ }
+ }
+ this.regionsOfInterest = this.regionsOfInterest.slice(0, boxes.length);
+ };
+ Pipeline.prototype.clearRegionOfInterest = function (index) {
+ if (this.regionsOfInterest[index] != null) {
+ this.regionsOfInterest = this.regionsOfInterest.slice(0, index).concat(this.regionsOfInterest.slice(index + 1));
+ }
+ };
+ Pipeline.prototype.shouldUpdateRegionsOfInterest = function () {
+ var roisCount = this.regionsOfInterest.length;
+ var noROIs = roisCount === 0;
+ if (this.maxFaces === 1 || noROIs) {
+ return noROIs;
+ }
+ return roisCount !== this.maxFaces &&
+ this.runsWithoutFaceDetector >= this.maxContinuousChecks;
+ };
+ Pipeline.prototype.calculateLandmarksBoundingBox = function (landmarks) {
+ var xs = landmarks.map(function (d) { return d[0]; });
+ var ys = landmarks.map(function (d) { return d[1]; });
+ var startPoint = [Math.min.apply(Math, xs), Math.min.apply(Math, ys)];
+ var endPoint = [Math.max.apply(Math, xs), Math.max.apply(Math, ys)];
+ return { startPoint: startPoint, endPoint: endPoint };
+ };
+ return Pipeline;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var UV_COORDS = [
+ [0.499976992607117, 0.652534008026123],
+ [0.500025987625122, 0.547487020492554],
+ [0.499974012374878, 0.602371990680695],
+ [0.482113003730774, 0.471979022026062],
+ [0.500150978565216, 0.527155995368958],
+ [0.499909996986389, 0.498252987861633],
+ [0.499523013830185, 0.40106201171875],
+ [0.289712011814117, 0.380764007568359],
+ [0.499954998493195, 0.312398016452789],
+ [0.499987006187439, 0.269918978214264],
+ [0.500023007392883, 0.107050001621246],
+ [0.500023007392883, 0.666234016418457],
+ [0.5000159740448, 0.679224014282227],
+ [0.500023007392883, 0.692348003387451],
+ [0.499976992607117, 0.695277988910675],
+ [0.499976992607117, 0.70593398809433],
+ [0.499976992607117, 0.719385027885437],
+ [0.499976992607117, 0.737019002437592],
+ [0.499967992305756, 0.781370997428894],
+ [0.499816000461578, 0.562981009483337],
+ [0.473773002624512, 0.573909997940063],
+ [0.104906998574734, 0.254140973091125],
+ [0.365929991006851, 0.409575998783112],
+ [0.338757991790771, 0.41302502155304],
+ [0.311120003461838, 0.409460008144379],
+ [0.274657994508743, 0.389131009578705],
+ [0.393361985683441, 0.403706014156342],
+ [0.345234006643295, 0.344011008739471],
+ [0.370094001293182, 0.346076011657715],
+ [0.319321990013123, 0.347265005111694],
+ [0.297903001308441, 0.353591024875641],
+ [0.24779200553894, 0.410809993743896],
+ [0.396889001131058, 0.842755019664764],
+ [0.280097991228104, 0.375599980354309],
+ [0.106310002505779, 0.399955987930298],
+ [0.2099249958992, 0.391353011131287],
+ [0.355807989835739, 0.534406006336212],
+ [0.471751004457474, 0.65040397644043],
+ [0.474155008792877, 0.680191993713379],
+ [0.439785003662109, 0.657229006290436],
+ [0.414617002010345, 0.66654098033905],
+ [0.450374007225037, 0.680860996246338],
+ [0.428770989179611, 0.682690978050232],
+ [0.374971002340317, 0.727805018424988],
+ [0.486716985702515, 0.547628998756409],
+ [0.485300987958908, 0.527395009994507],
+ [0.257764995098114, 0.314490020275116],
+ [0.401223003864288, 0.455172002315521],
+ [0.429818987846375, 0.548614978790283],
+ [0.421351999044418, 0.533740997314453],
+ [0.276895999908447, 0.532056987285614],
+ [0.483370006084442, 0.499586999416351],
+ [0.33721199631691, 0.282882988452911],
+ [0.296391993761063, 0.293242990970612],
+ [0.169294998049736, 0.193813979625702],
+ [0.447580009698868, 0.302609980106354],
+ [0.392390012741089, 0.353887975215912],
+ [0.354490011930466, 0.696784019470215],
+ [0.067304998636246, 0.730105042457581],
+ [0.442739009857178, 0.572826027870178],
+ [0.457098007202148, 0.584792017936707],
+ [0.381974011659622, 0.694710969924927],
+ [0.392388999462128, 0.694203019142151],
+ [0.277076005935669, 0.271932005882263],
+ [0.422551989555359, 0.563233017921448],
+ [0.385919004678726, 0.281364023685455],
+ [0.383103013038635, 0.255840003490448],
+ [0.331431001424789, 0.119714021682739],
+ [0.229923993349075, 0.232002973556519],
+ [0.364500999450684, 0.189113974571228],
+ [0.229622006416321, 0.299540996551514],
+ [0.173287004232407, 0.278747975826263],
+ [0.472878992557526, 0.666198015213013],
+ [0.446828007698059, 0.668527007102966],
+ [0.422762006521225, 0.673889994621277],
+ [0.445307999849319, 0.580065965652466],
+ [0.388103008270264, 0.693961024284363],
+ [0.403039008378983, 0.706539988517761],
+ [0.403629004955292, 0.693953037261963],
+ [0.460041999816895, 0.557139039039612],
+ [0.431158006191254, 0.692366003990173],
+ [0.452181994915009, 0.692366003990173],
+ [0.475387006998062, 0.692366003990173],
+ [0.465828001499176, 0.779190003871918],
+ [0.472328990697861, 0.736225962638855],
+ [0.473087012767792, 0.717857003211975],
+ [0.473122000694275, 0.704625964164734],
+ [0.473033010959625, 0.695277988910675],
+ [0.427942007780075, 0.695277988910675],
+ [0.426479011774063, 0.703539967536926],
+ [0.423162013292313, 0.711845993995667],
+ [0.4183090031147, 0.720062971115112],
+ [0.390094995498657, 0.639572978019714],
+ [0.013953999616206, 0.560034036636353],
+ [0.499913990497589, 0.58014702796936],
+ [0.413199990987778, 0.69539999961853],
+ [0.409626007080078, 0.701822996139526],
+ [0.468080013990402, 0.601534962654114],
+ [0.422728985548019, 0.585985004901886],
+ [0.463079988956451, 0.593783974647522],
+ [0.37211999297142, 0.47341400384903],
+ [0.334562003612518, 0.496073007583618],
+ [0.411671012639999, 0.546965003013611],
+ [0.242175996303558, 0.14767599105835],
+ [0.290776997804642, 0.201445996761322],
+ [0.327338010072708, 0.256527006626129],
+ [0.399509996175766, 0.748921036720276],
+ [0.441727995872498, 0.261676013469696],
+ [0.429764986038208, 0.187834024429321],
+ [0.412198007106781, 0.108901023864746],
+ [0.288955003023148, 0.398952007293701],
+ [0.218936994671822, 0.435410976409912],
+ [0.41278201341629, 0.398970007896423],
+ [0.257135003805161, 0.355440020561218],
+ [0.427684992551804, 0.437960982322693],
+ [0.448339998722076, 0.536936044692993],
+ [0.178560003638268, 0.45755398273468],
+ [0.247308000922203, 0.457193970680237],
+ [0.286267012357712, 0.467674970626831],
+ [0.332827985286713, 0.460712015628815],
+ [0.368755996227264, 0.447206974029541],
+ [0.398963987827301, 0.432654976844788],
+ [0.476410001516342, 0.405806005001068],
+ [0.189241006970406, 0.523923993110657],
+ [0.228962004184723, 0.348950982093811],
+ [0.490725994110107, 0.562400996685028],
+ [0.404670000076294, 0.485132992267609],
+ [0.019469000399113, 0.401564002037048],
+ [0.426243007183075, 0.420431017875671],
+ [0.396993011236191, 0.548797011375427],
+ [0.266469985246658, 0.376977026462555],
+ [0.439121007919312, 0.51895797252655],
+ [0.032313998788595, 0.644356966018677],
+ [0.419054001569748, 0.387154996395111],
+ [0.462783008813858, 0.505746960639954],
+ [0.238978996872902, 0.779744982719421],
+ [0.198220998048782, 0.831938028335571],
+ [0.107550002634525, 0.540755033493042],
+ [0.183610007166862, 0.740257024765015],
+ [0.134409993886948, 0.333683013916016],
+ [0.385764002799988, 0.883153975009918],
+ [0.490967005491257, 0.579378008842468],
+ [0.382384985685349, 0.508572995662689],
+ [0.174399003386497, 0.397670984268188],
+ [0.318785011768341, 0.39623498916626],
+ [0.343364000320435, 0.400596976280212],
+ [0.396100014448166, 0.710216999053955],
+ [0.187885001301765, 0.588537991046906],
+ [0.430987000465393, 0.944064974784851],
+ [0.318993002176285, 0.898285031318665],
+ [0.266247987747192, 0.869701027870178],
+ [0.500023007392883, 0.190576016902924],
+ [0.499976992607117, 0.954452991485596],
+ [0.366169989109039, 0.398822009563446],
+ [0.393207013607025, 0.39553701877594],
+ [0.410373002290726, 0.391080021858215],
+ [0.194993004202843, 0.342101991176605],
+ [0.388664990663528, 0.362284004688263],
+ [0.365961998701096, 0.355970978736877],
+ [0.343364000320435, 0.355356991291046],
+ [0.318785011768341, 0.35834002494812],
+ [0.301414996385574, 0.363156020641327],
+ [0.058132998645306, 0.319076001644135],
+ [0.301414996385574, 0.387449026107788],
+ [0.499987989664078, 0.618434011936188],
+ [0.415838003158569, 0.624195992946625],
+ [0.445681989192963, 0.566076993942261],
+ [0.465844005346298, 0.620640993118286],
+ [0.49992299079895, 0.351523995399475],
+ [0.288718998432159, 0.819945991039276],
+ [0.335278987884521, 0.852819979190826],
+ [0.440512001514435, 0.902418971061707],
+ [0.128294005990028, 0.791940987110138],
+ [0.408771991729736, 0.373893976211548],
+ [0.455606997013092, 0.451801002025604],
+ [0.499877005815506, 0.908990025520325],
+ [0.375436991453171, 0.924192011356354],
+ [0.11421000212431, 0.615022003650665],
+ [0.448662012815475, 0.695277988910675],
+ [0.4480200111866, 0.704632043838501],
+ [0.447111994028091, 0.715808033943176],
+ [0.444831997156143, 0.730794012546539],
+ [0.430011987686157, 0.766808986663818],
+ [0.406787008047104, 0.685672998428345],
+ [0.400738000869751, 0.681069016456604],
+ [0.392399996519089, 0.677703022956848],
+ [0.367855995893478, 0.663918972015381],
+ [0.247923001646996, 0.601333022117615],
+ [0.452769994735718, 0.420849978923798],
+ [0.43639200925827, 0.359887003898621],
+ [0.416164010763168, 0.368713974952698],
+ [0.413385987281799, 0.692366003990173],
+ [0.228018000721931, 0.683571994304657],
+ [0.468268007040024, 0.352671027183533],
+ [0.411361992359161, 0.804327011108398],
+ [0.499989002943039, 0.469825029373169],
+ [0.479153990745544, 0.442654013633728],
+ [0.499974012374878, 0.439637005329132],
+ [0.432112008333206, 0.493588984012604],
+ [0.499886006116867, 0.866917014122009],
+ [0.49991300702095, 0.821729004383087],
+ [0.456548988819122, 0.819200992584229],
+ [0.344549000263214, 0.745438992977142],
+ [0.37890899181366, 0.574010014533997],
+ [0.374292999505997, 0.780184984207153],
+ [0.319687992334366, 0.570737957954407],
+ [0.357154995203018, 0.604269981384277],
+ [0.295284003019333, 0.621580958366394],
+ [0.447750002145767, 0.862477004528046],
+ [0.410986006259918, 0.508723020553589],
+ [0.31395098567009, 0.775308012962341],
+ [0.354128003120422, 0.812552988529205],
+ [0.324548006057739, 0.703992962837219],
+ [0.189096003770828, 0.646299958229065],
+ [0.279776990413666, 0.71465802192688],
+ [0.1338230073452, 0.682700991630554],
+ [0.336768001317978, 0.644733011722565],
+ [0.429883986711502, 0.466521978378296],
+ [0.455527991056442, 0.548622965812683],
+ [0.437114000320435, 0.558896005153656],
+ [0.467287987470627, 0.529924988746643],
+ [0.414712011814117, 0.335219979286194],
+ [0.37704598903656, 0.322777986526489],
+ [0.344107985496521, 0.320150971412659],
+ [0.312875986099243, 0.32233202457428],
+ [0.283526003360748, 0.333190023899078],
+ [0.241245999932289, 0.382785975933075],
+ [0.102986000478268, 0.468762993812561],
+ [0.267612010240555, 0.424560010433197],
+ [0.297879010438919, 0.433175981044769],
+ [0.333433985710144, 0.433878004550934],
+ [0.366427004337311, 0.426115989685059],
+ [0.396012008190155, 0.416696012020111],
+ [0.420121014118195, 0.41022801399231],
+ [0.007561000064015, 0.480777025222778],
+ [0.432949006557465, 0.569517970085144],
+ [0.458638995885849, 0.479089021682739],
+ [0.473466008901596, 0.545744001865387],
+ [0.476087987422943, 0.563830018043518],
+ [0.468472003936768, 0.555056989192963],
+ [0.433990985155106, 0.582361996173859],
+ [0.483518004417419, 0.562983989715576],
+ [0.482482999563217, 0.57784903049469],
+ [0.42645001411438, 0.389798998832703],
+ [0.438998997211456, 0.39649498462677],
+ [0.450067013502121, 0.400434017181396],
+ [0.289712011814117, 0.368252992630005],
+ [0.276670008897781, 0.363372981548309],
+ [0.517862021923065, 0.471948027610779],
+ [0.710287988185883, 0.380764007568359],
+ [0.526226997375488, 0.573909997940063],
+ [0.895093023777008, 0.254140973091125],
+ [0.634069979190826, 0.409575998783112],
+ [0.661242008209229, 0.41302502155304],
+ [0.688880026340485, 0.409460008144379],
+ [0.725341975688934, 0.389131009578705],
+ [0.606630027294159, 0.40370500087738],
+ [0.654766023159027, 0.344011008739471],
+ [0.629905998706818, 0.346076011657715],
+ [0.680678009986877, 0.347265005111694],
+ [0.702096998691559, 0.353591024875641],
+ [0.75221198797226, 0.410804986953735],
+ [0.602918028831482, 0.842862963676453],
+ [0.719901978969574, 0.375599980354309],
+ [0.893692970275879, 0.399959981441498],
+ [0.790081977844238, 0.391354024410248],
+ [0.643998026847839, 0.534487962722778],
+ [0.528249025344849, 0.65040397644043],
+ [0.525849997997284, 0.680191040039062],
+ [0.560214996337891, 0.657229006290436],
+ [0.585384011268616, 0.66654098033905],
+ [0.549625992774963, 0.680860996246338],
+ [0.57122802734375, 0.682691991329193],
+ [0.624852001667023, 0.72809898853302],
+ [0.513050019741058, 0.547281980514526],
+ [0.51509702205658, 0.527251958847046],
+ [0.742246985435486, 0.314507007598877],
+ [0.598631024360657, 0.454979002475739],
+ [0.570338010787964, 0.548575043678284],
+ [0.578631997108459, 0.533622980117798],
+ [0.723087012767792, 0.532054007053375],
+ [0.516445994377136, 0.499638974666595],
+ [0.662801027297974, 0.282917976379395],
+ [0.70362401008606, 0.293271005153656],
+ [0.830704987049103, 0.193813979625702],
+ [0.552385985851288, 0.302568018436432],
+ [0.607609987258911, 0.353887975215912],
+ [0.645429015159607, 0.696707010269165],
+ [0.932694971561432, 0.730105042457581],
+ [0.557260990142822, 0.572826027870178],
+ [0.542901992797852, 0.584792017936707],
+ [0.6180260181427, 0.694710969924927],
+ [0.607590973377228, 0.694203019142151],
+ [0.722943007946014, 0.271963000297546],
+ [0.577413976192474, 0.563166975975037],
+ [0.614082992076874, 0.281386971473694],
+ [0.616907000541687, 0.255886018276215],
+ [0.668509006500244, 0.119913995265961],
+ [0.770092010498047, 0.232020974159241],
+ [0.635536015033722, 0.189248979091644],
+ [0.77039098739624, 0.299556016921997],
+ [0.826722025871277, 0.278755009174347],
+ [0.527121007442474, 0.666198015213013],
+ [0.553171992301941, 0.668527007102966],
+ [0.577238023281097, 0.673889994621277],
+ [0.554691970348358, 0.580065965652466],
+ [0.611896991729736, 0.693961024284363],
+ [0.59696102142334, 0.706539988517761],
+ [0.596370995044708, 0.693953037261963],
+ [0.539958000183105, 0.557139039039612],
+ [0.568841993808746, 0.692366003990173],
+ [0.547818005084991, 0.692366003990173],
+ [0.52461302280426, 0.692366003990173],
+ [0.534089982509613, 0.779141008853912],
+ [0.527670979499817, 0.736225962638855],
+ [0.526912987232208, 0.717857003211975],
+ [0.526877999305725, 0.704625964164734],
+ [0.526966989040375, 0.695277988910675],
+ [0.572058022022247, 0.695277988910675],
+ [0.573521018028259, 0.703539967536926],
+ [0.57683801651001, 0.711845993995667],
+ [0.581691026687622, 0.720062971115112],
+ [0.609944999217987, 0.639909982681274],
+ [0.986046016216278, 0.560034036636353],
+ [0.5867999792099, 0.69539999961853],
+ [0.590372025966644, 0.701822996139526],
+ [0.531915009021759, 0.601536989212036],
+ [0.577268004417419, 0.585934996604919],
+ [0.536915004253387, 0.593786001205444],
+ [0.627542972564697, 0.473352015018463],
+ [0.665585994720459, 0.495950996875763],
+ [0.588353991508484, 0.546862006187439],
+ [0.757824003696442, 0.14767599105835],
+ [0.709249973297119, 0.201507985591888],
+ [0.672684013843536, 0.256581008434296],
+ [0.600408971309662, 0.74900496006012],
+ [0.55826598405838, 0.261672019958496],
+ [0.570303976535797, 0.187870979309082],
+ [0.588165998458862, 0.109044015407562],
+ [0.711045026779175, 0.398952007293701],
+ [0.781069993972778, 0.435405015945435],
+ [0.587247014045715, 0.398931980133057],
+ [0.742869973182678, 0.355445981025696],
+ [0.572156012058258, 0.437651991844177],
+ [0.55186802148819, 0.536570012569427],
+ [0.821442008018494, 0.457556009292603],
+ [0.752701997756958, 0.457181990146637],
+ [0.71375697851181, 0.467626988887787],
+ [0.66711300611496, 0.460672974586487],
+ [0.631101012229919, 0.447153985500336],
+ [0.6008620262146, 0.432473003864288],
+ [0.523481011390686, 0.405627012252808],
+ [0.810747981071472, 0.523926019668579],
+ [0.771045982837677, 0.348959028720856],
+ [0.509127020835876, 0.562718033790588],
+ [0.595292985439301, 0.485023975372314],
+ [0.980530977249146, 0.401564002037048],
+ [0.573499977588654, 0.420000016689301],
+ [0.602994978427887, 0.548687994480133],
+ [0.733529984951019, 0.376977026462555],
+ [0.560611009597778, 0.519016981124878],
+ [0.967685997486115, 0.644356966018677],
+ [0.580985009670258, 0.387160003185272],
+ [0.537728011608124, 0.505385041236877],
+ [0.760966002941132, 0.779752969741821],
+ [0.801778972148895, 0.831938028335571],
+ [0.892440974712372, 0.54076099395752],
+ [0.816350996494293, 0.740260004997253],
+ [0.865594983100891, 0.333687007427216],
+ [0.614073991775513, 0.883246004581451],
+ [0.508952975273132, 0.579437971115112],
+ [0.617941975593567, 0.508316040039062],
+ [0.825608015060425, 0.397674977779388],
+ [0.681214988231659, 0.39623498916626],
+ [0.656635999679565, 0.400596976280212],
+ [0.603900015354156, 0.710216999053955],
+ [0.81208598613739, 0.588539004325867],
+ [0.56801301240921, 0.944564998149872],
+ [0.681007981300354, 0.898285031318665],
+ [0.733752012252808, 0.869701027870178],
+ [0.633830010890961, 0.398822009563446],
+ [0.606792986392975, 0.39553701877594],
+ [0.589659988880157, 0.391062021255493],
+ [0.805015981197357, 0.342108011245728],
+ [0.611334979534149, 0.362284004688263],
+ [0.634037971496582, 0.355970978736877],
+ [0.656635999679565, 0.355356991291046],
+ [0.681214988231659, 0.35834002494812],
+ [0.698584973812103, 0.363156020641327],
+ [0.941866993904114, 0.319076001644135],
+ [0.698584973812103, 0.387449026107788],
+ [0.584177017211914, 0.624107003211975],
+ [0.554318010807037, 0.566076993942261],
+ [0.534153997898102, 0.62064003944397],
+ [0.711217999458313, 0.819975018501282],
+ [0.664629995822906, 0.852871000766754],
+ [0.559099972248077, 0.902631998062134],
+ [0.871706008911133, 0.791940987110138],
+ [0.591234028339386, 0.373893976211548],
+ [0.544341027736664, 0.451583981513977],
+ [0.624562978744507, 0.924192011356354],
+ [0.88577002286911, 0.615028977394104],
+ [0.551338016986847, 0.695277988910675],
+ [0.551980018615723, 0.704632043838501],
+ [0.552887976169586, 0.715808033943176],
+ [0.555167973041534, 0.730794012546539],
+ [0.569944024085999, 0.767035007476807],
+ [0.593203008174896, 0.685675978660583],
+ [0.599261999130249, 0.681069016456604],
+ [0.607599973678589, 0.677703022956848],
+ [0.631937980651855, 0.663500010967255],
+ [0.752032995223999, 0.601315021514893],
+ [0.547226011753082, 0.420395016670227],
+ [0.563543975353241, 0.359827995300293],
+ [0.583841025829315, 0.368713974952698],
+ [0.586614012718201, 0.692366003990173],
+ [0.771915018558502, 0.683578014373779],
+ [0.531597018241882, 0.352482974529266],
+ [0.588370978832245, 0.804440975189209],
+ [0.52079701423645, 0.442565023899078],
+ [0.567984998226166, 0.493479013442993],
+ [0.543282985687256, 0.819254994392395],
+ [0.655317008495331, 0.745514988899231],
+ [0.621008992195129, 0.574018001556396],
+ [0.625559985637665, 0.78031200170517],
+ [0.680198013782501, 0.570719003677368],
+ [0.64276397228241, 0.604337990283966],
+ [0.704662978649139, 0.621529996395111],
+ [0.552012026309967, 0.862591981887817],
+ [0.589071989059448, 0.508637011051178],
+ [0.685944974422455, 0.775357007980347],
+ [0.645735025405884, 0.812640011310577],
+ [0.675342977046967, 0.703978002071381],
+ [0.810858011245728, 0.646304965019226],
+ [0.72012197971344, 0.714666962623596],
+ [0.866151988506317, 0.682704985141754],
+ [0.663187026977539, 0.644596993923187],
+ [0.570082008838654, 0.466325998306274],
+ [0.544561982154846, 0.548375964164734],
+ [0.562758982181549, 0.558784961700439],
+ [0.531987011432648, 0.530140042304993],
+ [0.585271000862122, 0.335177004337311],
+ [0.622952997684479, 0.32277899980545],
+ [0.655896008014679, 0.320163011550903],
+ [0.687132000923157, 0.322345972061157],
+ [0.716481983661652, 0.333200991153717],
+ [0.758756995201111, 0.382786989212036],
+ [0.897013008594513, 0.468769013881683],
+ [0.732392013072968, 0.424547016620636],
+ [0.70211398601532, 0.433162987232208],
+ [0.66652500629425, 0.433866024017334],
+ [0.633504986763, 0.426087975502014],
+ [0.603875994682312, 0.416586995124817],
+ [0.579657971858978, 0.409945011138916],
+ [0.992439985275269, 0.480777025222778],
+ [0.567192018032074, 0.569419980049133],
+ [0.54136598110199, 0.478899002075195],
+ [0.526564002037048, 0.546118021011353],
+ [0.523913025856018, 0.563830018043518],
+ [0.531529009342194, 0.555056989192963],
+ [0.566035985946655, 0.582329034805298],
+ [0.51631098985672, 0.563053965568542],
+ [0.5174720287323, 0.577877044677734],
+ [0.573594987392426, 0.389806985855103],
+ [0.560697972774506, 0.395331978797913],
+ [0.549755990505219, 0.399751007556915],
+ [0.710287988185883, 0.368252992630005],
+ [0.723330020904541, 0.363372981548309]
+ ];
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var FACEMESH_GRAPHMODEL_PATH = 'https://tfhub.dev/mediapipe/tfjs-model/facemesh/1/default/1';
+ var IRIS_GRAPHMODEL_PATH = 'https://tfhub.dev/mediapipe/tfjs-model/iris/1/default/2';
+ var MESH_MODEL_INPUT_WIDTH = 192;
+ var MESH_MODEL_INPUT_HEIGHT = 192;
+ var PREDICTION_VALUES = 'MediaPipePredictionValues';
+ var PREDICTION_TENSORS = 'MediaPipePredictionTensors';
+ /**
+ * Load the model.
+ *
+ * @param options - a configuration object with the following properties:
+ * - `maxContinuousChecks` How many frames to go without running the bounding
+ * box detector. Only relevant if maxFaces > 1. Defaults to 5.
+ * - `detectionConfidence` Threshold for discarding a prediction. Defaults to
+ * 0.9.
+ * - `maxFaces` The maximum number of faces detected in the input. Should be
+ * set to the minimum number for performance. Defaults to 10.
+ * - `iouThreshold` A float representing the threshold for deciding whether
+ * boxes overlap too much in non-maximum suppression. Must be between [0, 1].
+ * Defaults to 0.3.
+ * - `scoreThreshold` A threshold for deciding when to remove boxes based
+ * on score in non-maximum suppression. Defaults to 0.75.
+ * - `shouldLoadIrisModel` Whether to also load the iris detection model.
+ * Defaults to true.
+ * - `modelUrl` Optional param for specifying a custom facemesh model url or
+ * a `tf.io.IOHandler` object.
+ * - `detectorModelUrl` Optional param for specifying a custom blazeface model
+ * url or a `tf.io.IOHandler` object.
+ * - `irisModelUrl` Optional param for specifying a custom iris model url or
+ * a `tf.io.IOHandler` object.
+ */
+ function load$1(config) {
+ return __awaiter(this, void 0, void 0, function () {
+ var _a, maxContinuousChecks, _b, detectionConfidence, _c, maxFaces, _d, iouThreshold, _e, scoreThreshold, _f, shouldLoadIrisModel, modelUrl, detectorModelUrl, irisModelUrl, models, faceMesh;
+ return __generator(this, function (_g) {
+ switch (_g.label) {
+ case 0:
+ _a = config.maxContinuousChecks, maxContinuousChecks = _a === void 0 ? 5 : _a, _b = config.detectionConfidence, detectionConfidence = _b === void 0 ? 0.9 : _b, _c = config.maxFaces, maxFaces = _c === void 0 ? 10 : _c, _d = config.iouThreshold, iouThreshold = _d === void 0 ? 0.3 : _d, _e = config.scoreThreshold, scoreThreshold = _e === void 0 ? 0.75 : _e, _f = config.shouldLoadIrisModel, shouldLoadIrisModel = _f === void 0 ? true : _f, modelUrl = config.modelUrl, detectorModelUrl = config.detectorModelUrl, irisModelUrl = config.irisModelUrl;
+ if (!shouldLoadIrisModel) return [3 /*break*/, 2];
+ return [4 /*yield*/, Promise.all([
+ loadDetectorModel(detectorModelUrl, maxFaces, iouThreshold, scoreThreshold),
+ loadMeshModel(modelUrl),
+ loadIrisModel(irisModelUrl)
+ ])];
+ case 1:
+ models = _g.sent();
+ return [3 /*break*/, 4];
+ case 2: return [4 /*yield*/, Promise.all([
+ loadDetectorModel(detectorModelUrl, maxFaces, iouThreshold, scoreThreshold),
+ loadMeshModel(modelUrl)
+ ])];
+ case 3:
+ models = _g.sent();
+ _g.label = 4;
+ case 4:
+ faceMesh = new FaceMesh(models[0], models[1], maxContinuousChecks, detectionConfidence, maxFaces, shouldLoadIrisModel ? models[2] : null);
+ return [2 /*return*/, faceMesh];
+ }
+ });
+ });
+ }
+ function loadDetectorModel(modelUrl, maxFaces, iouThreshold, scoreThreshold) {
+ return __awaiter(this, void 0, void 0, function () {
+ return __generator(this, function (_a) {
+ return [2 /*return*/, load({ modelUrl: modelUrl, maxFaces: maxFaces, iouThreshold: iouThreshold, scoreThreshold: scoreThreshold })];
+ });
+ });
+ }
+ function loadMeshModel(modelUrl) {
+ return __awaiter(this, void 0, void 0, function () {
+ return __generator(this, function (_a) {
+ if (modelUrl != null) {
+ return [2 /*return*/, tfconv.loadGraphModel(modelUrl)];
+ }
+ return [2 /*return*/, tfconv.loadGraphModel(FACEMESH_GRAPHMODEL_PATH, { fromTFHub: true })];
+ });
+ });
+ }
+ function loadIrisModel(modelUrl) {
+ return __awaiter(this, void 0, void 0, function () {
+ return __generator(this, function (_a) {
+ if (modelUrl != null) {
+ return [2 /*return*/, tfconv.loadGraphModel(modelUrl)];
+ }
+ return [2 /*return*/, tfconv.loadGraphModel(IRIS_GRAPHMODEL_PATH, { fromTFHub: true })];
+ });
+ });
+ }
+ function getInputTensorDimensions$1(input) {
+ return input instanceof tf.Tensor ? [input.shape[0], input.shape[1]] :
+ [input.height, input.width];
+ }
+ function flipFaceHorizontal$1(face, imageWidth) {
+ if (face.mesh instanceof tf.Tensor) {
+ var _a = tf.tidy(function () {
+ var subtractBasis = tf.tensor1d([imageWidth - 1, 0, 0]);
+ var multiplyBasis = tf.tensor1d([1, -1, 1]);
+ return tf.tidy(function () {
+ return [
+ tf.concat([
+ tf.sub(imageWidth - 1, tf.slice(face.boundingBox.topLeft, 0, 1)),
+ tf.slice(face.boundingBox.topLeft, 1, 1)
+ ]),
+ tf.concat([
+ tf.sub(imageWidth - 1, tf.slice(face.boundingBox.bottomRight, 0, 1)),
+ tf.slice(face.boundingBox.bottomRight, 1, 1)
+ ]),
+ tf.mul(tf.sub(subtractBasis, face.mesh), multiplyBasis),
+ tf.mul(tf.sub(subtractBasis, face.scaledMesh), multiplyBasis)
+ ];
+ });
+ }), topLeft = _a[0], bottomRight = _a[1], mesh = _a[2], scaledMesh = _a[3];
+ return Object.assign({}, face, { boundingBox: { topLeft: topLeft, bottomRight: bottomRight }, mesh: mesh, scaledMesh: scaledMesh });
+ }
+ return Object.assign({}, face, {
+ boundingBox: {
+ topLeft: [
+ imageWidth - 1 - face.boundingBox.topLeft[0],
+ face.boundingBox.topLeft[1]
+ ],
+ bottomRight: [
+ imageWidth - 1 - face.boundingBox.bottomRight[0],
+ face.boundingBox.bottomRight[1]
+ ]
+ },
+ mesh: (face.mesh).map(function (coord) {
+ var flippedCoord = coord.slice(0);
+ flippedCoord[0] = imageWidth - 1 - coord[0];
+ return flippedCoord;
+ }),
+ scaledMesh: face.scaledMesh.map(function (coord) {
+ var flippedCoord = coord.slice(0);
+ flippedCoord[0] = imageWidth - 1 - coord[0];
+ return flippedCoord;
+ })
+ });
+ }
+ var FaceMesh = /** @class */ (function () {
+ function FaceMesh(blazeFace, blazeMeshModel, maxContinuousChecks, detectionConfidence, maxFaces, irisModel) {
+ this.kind = 'MediaPipeFaceMesh';
+ this.pipeline = new Pipeline(blazeFace, blazeMeshModel, MESH_MODEL_INPUT_WIDTH, MESH_MODEL_INPUT_HEIGHT, maxContinuousChecks, maxFaces, irisModel);
+ this.detectionConfidence = detectionConfidence;
+ }
+ FaceMesh.getAnnotations = function () {
+ return MESH_ANNOTATIONS;
+ };
+ /**
+ * Returns an array of UV coordinates for the 468 facial keypoint vertices in
+ * mesh_map.jpg. Can be used to map textures to the facial mesh.
+ */
+ FaceMesh.getUVCoords = function () {
+ return UV_COORDS;
+ };
+ /**
+ * Returns an array of faces in an image.
+ *
+ * @param input The image to classify. Can be a tensor, DOM element image,
+ * video, or canvas.
+ * @param returnTensors (defaults to `false`) Whether to return tensors as
+ * opposed to values.
+ * @param flipHorizontal Whether to flip/mirror the facial keypoints
+ * horizontally. Should be true for videos that are flipped by default (e.g.
+ * webcams).
+ * @param predictIrises
+ *
+ * @return An array of AnnotatedPrediction objects.
+ */
+ FaceMesh.prototype.estimateFaces = function (config) {
+ return __awaiter(this, void 0, void 0, function () {
+ var _a, returnTensors, _b, flipHorizontal, _c, predictIrises, input, _d, width, image, predictions, savedWebglPackDepthwiseConvFlag;
+ var _this = this;
+ return __generator(this, function (_e) {
+ switch (_e.label) {
+ case 0:
+ _a = config.returnTensors, returnTensors = _a === void 0 ? false : _a, _b = config.flipHorizontal, flipHorizontal = _b === void 0 ? false : _b, _c = config.predictIrises, predictIrises = _c === void 0 ? true : _c;
+ input = config.input;
+ if (predictIrises && this.pipeline.irisModel == null) {
+ throw new Error('The iris model was not loaded as part of facemesh. ' +
+ 'Please initialize the model with ' +
+ 'facemesh.load({shouldLoadIrisModel: true}).');
+ }
+ _d = getInputTensorDimensions$1(input), width = _d[1];
+ image = tf.tidy(function () {
+ if (!(input instanceof tf.Tensor)) {
+ input = tf.browser.fromPixels(input);
+ }
+ return tf.expandDims(tf.cast(input, 'float32'), 0);
+ });
+ if (!(tf.getBackend() === 'webgl')) return [3 /*break*/, 2];
+ savedWebglPackDepthwiseConvFlag = tf.env().get('WEBGL_PACK_DEPTHWISECONV');
+ tf.env().set('WEBGL_PACK_DEPTHWISECONV', true);
+ return [4 /*yield*/, this.pipeline.predict(image, predictIrises)];
+ case 1:
+ predictions = _e.sent();
+ tf.env().set('WEBGL_PACK_DEPTHWISECONV', savedWebglPackDepthwiseConvFlag);
+ return [3 /*break*/, 4];
+ case 2: return [4 /*yield*/, this.pipeline.predict(image, predictIrises)];
+ case 3:
+ predictions = _e.sent();
+ _e.label = 4;
+ case 4:
+ image.dispose();
+ if (predictions != null && predictions.length > 0) {
+ return [2 /*return*/, Promise.all(predictions.map(function (prediction, i) { return __awaiter(_this, void 0, void 0, function () {
+ var coords, scaledCoords, box, flag, tensorsToRead, tensorValues, flagValue, annotatedPrediction_1, _a, coordsArr, coordsArrScaled, annotatedPrediction, annotations, key;
+ var _this = this;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ coords = prediction.coords, scaledCoords = prediction.scaledCoords, box = prediction.box, flag = prediction.flag;
+ tensorsToRead = [flag];
+ if (!returnTensors) {
+ tensorsToRead = tensorsToRead.concat([coords, scaledCoords]);
+ }
+ return [4 /*yield*/, Promise.all(tensorsToRead.map(function (d) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
+ return [2 /*return*/, d.array()];
+ }); }); }))];
+ case 1:
+ tensorValues = _b.sent();
+ flagValue = tensorValues[0];
+ flag.dispose();
+ if (flagValue < this.detectionConfidence) {
+ this.pipeline.clearRegionOfInterest(i);
+ }
+ if (returnTensors) {
+ annotatedPrediction_1 = {
+ kind: PREDICTION_TENSORS,
+ faceInViewConfidence: flagValue,
+ mesh: coords,
+ scaledMesh: scaledCoords,
+ boundingBox: {
+ topLeft: tf.tensor1d(box.startPoint),
+ bottomRight: tf.tensor1d(box.endPoint)
+ }
+ };
+ if (flipHorizontal) {
+ return [2 /*return*/, flipFaceHorizontal$1(annotatedPrediction_1, width)];
+ }
+ return [2 /*return*/, annotatedPrediction_1];
+ }
+ _a = tensorValues.slice(1), coordsArr = _a[0], coordsArrScaled = _a[1];
+ scaledCoords.dispose();
+ coords.dispose();
+ annotatedPrediction = {
+ kind: PREDICTION_VALUES,
+ faceInViewConfidence: flagValue,
+ boundingBox: { topLeft: box.startPoint, bottomRight: box.endPoint },
+ mesh: coordsArr,
+ scaledMesh: coordsArrScaled
+ };
+ if (flipHorizontal) {
+ annotatedPrediction =
+ flipFaceHorizontal$1(annotatedPrediction, width);
+ }
+ annotations = {};
+ for (key in MESH_ANNOTATIONS) {
+ if (predictIrises || key.includes('Iris') === false) {
+ annotations[key] = MESH_ANNOTATIONS[key].map(function (index) { return annotatedPrediction.scaledMesh[index]; });
+ }
+ }
+ annotatedPrediction['annotations'] = annotations;
+ return [2 /*return*/, annotatedPrediction];
+ }
+ });
+ }); }))];
+ }
+ return [2 /*return*/, []];
+ }
+ });
+ });
+ };
+ return FaceMesh;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ (function (SupportedPackages) {
+ SupportedPackages["mediapipeFacemesh"] = "mediapipe-facemesh";
+ })(exports.SupportedPackages || (exports.SupportedPackages = {}));
+ /**
+ * Load face-landmarks-detection.
+ *
+ * @param pkg - The name of the package to load, e.g. 'mediapipe-facemesh'.
+ * @param config - a configuration object with the following properties:
+ * - `maxContinuousChecks` How many frames to go without running the bounding
+ * box detector. Only relevant if maxFaces > 1. Defaults to 5.
+ * - `detectionConfidence` Threshold for discarding a prediction. Defaults to
+ * 0.9.
+ * - `maxFaces` The maximum number of faces detected in the input. Should be
+ * set to the minimum number for performance. Defaults to 10.
+ * - `iouThreshold` A float representing the threshold for deciding whether
+ * boxes overlap too much in non-maximum suppression. Must be between [0, 1].
+ * Defaults to 0.3.
+ * - `scoreThreshold` A threshold for deciding when to remove boxes based
+ * on score in non-maximum suppression. Defaults to 0.75.
+ * - `shouldLoadIrisModel` Whether to also load the iris detection model.
+ * Defaults to true.
+ */
+ function load$2(pkg, config) {
+ if (pkg === void 0) { pkg = exports.SupportedPackages.mediapipeFacemesh; }
+ if (config === void 0) { config = {}; }
+ return __awaiter(this, void 0, void 0, function () {
+ return __generator(this, function (_a) {
+ if (pkg === exports.SupportedPackages.mediapipeFacemesh) {
+ return [2 /*return*/, load$1(config)];
+ }
+ else {
+ throw new Error(pkg + " is not a valid package name.");
+ }
+ });
+ });
+ }
+
+ exports.load = load$2;
+
+ Object.defineProperty(exports, '__esModule', { value: true });
+
+})));
diff --git a/thirdparty/tfjs/tf-backend-webgl.js b/thirdparty/tfjs/tf-backend-webgl.js
new file mode 100644
index 0000000..7d7611e
--- /dev/null
+++ b/thirdparty/tfjs/tf-backend-webgl.js
@@ -0,0 +1,16300 @@
+/**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tensorflow/tfjs-core')) :
+ typeof define === 'function' && define.amd ? define(['exports', '@tensorflow/tfjs-core'], factory) :
+ (global = global || self, factory(global.tf = global.tf || {}, global.tf));
+}(this, (function (exports, tf) { 'use strict';
+
+ /*! *****************************************************************************
+ Copyright (c) Microsoft Corporation.
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ PERFORMANCE OF THIS SOFTWARE.
+ ***************************************************************************** */
+ /* global Reflect, Promise */
+
+ var extendStatics = function(d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ };
+
+ function __extends(d, b) {
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ }
+
+ function __awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ }
+
+ function __generator(thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (_) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var contexts = {};
+ var WEBGL_ATTRIBUTES = {
+ alpha: false,
+ antialias: false,
+ premultipliedAlpha: false,
+ preserveDrawingBuffer: false,
+ depth: false,
+ stencil: false,
+ failIfMajorPerformanceCaveat: true
+ };
+ function setWebGLContext(webGLVersion, gl) {
+ contexts[webGLVersion] = gl;
+ }
+ function getWebGLContext(webGLVersion) {
+ if (!(webGLVersion in contexts)) {
+ var newCtx = getWebGLRenderingContext(webGLVersion);
+ if (newCtx !== null) {
+ contexts[webGLVersion] = newCtx;
+ }
+ else {
+ console.log('Could not get context for WebGL version', webGLVersion);
+ return null;
+ }
+ }
+ var gl = contexts[webGLVersion];
+ if (gl.isContextLost()) {
+ delete contexts[webGLVersion];
+ return getWebGLContext(webGLVersion);
+ }
+ gl.disable(gl.DEPTH_TEST);
+ gl.disable(gl.STENCIL_TEST);
+ gl.disable(gl.BLEND);
+ gl.disable(gl.DITHER);
+ gl.disable(gl.POLYGON_OFFSET_FILL);
+ gl.disable(gl.SAMPLE_COVERAGE);
+ gl.enable(gl.SCISSOR_TEST);
+ gl.enable(gl.CULL_FACE);
+ gl.cullFace(gl.BACK);
+ return contexts[webGLVersion];
+ }
+ function createCanvas(webGLVersion) {
+ if (typeof OffscreenCanvas !== 'undefined' && webGLVersion === 2) {
+ return new OffscreenCanvas(300, 150);
+ }
+ else if (typeof document !== 'undefined') {
+ return document.createElement('canvas');
+ }
+ else {
+ throw new Error('Cannot create a canvas in this context');
+ }
+ }
+ function getWebGLRenderingContext(webGLVersion) {
+ if (webGLVersion !== 1 && webGLVersion !== 2) {
+ throw new Error('Cannot get WebGL rendering context, WebGL is disabled.');
+ }
+ var canvas = createCanvas(webGLVersion);
+ canvas.addEventListener('webglcontextlost', function (ev) {
+ ev.preventDefault();
+ delete contexts[webGLVersion];
+ }, false);
+ if (webGLVersion === 1) {
+ return (canvas.getContext('webgl', WEBGL_ATTRIBUTES) ||
+ canvas.getContext('experimental-webgl', WEBGL_ATTRIBUTES));
+ }
+ return canvas.getContext('webgl2', WEBGL_ATTRIBUTES);
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var PackingScheme;
+ (function (PackingScheme) {
+ /**
+ * All values in a single texel are densely packed without any constraints.
+ *
+ * This is how the shader encodes a tensor with shape = [2, 3, 4]
+ * (indices are [batch, row, col]).
+ *
+ * 000|001 010|011 020|021
+ * ------- ------- -------
+ * 002|003 012|013 022|023
+ *
+ * 100|101 110|111 120|121
+ * ------- ------- -------
+ * 102|103 112|113 122|123
+ *
+ */
+ PackingScheme[PackingScheme["DENSE"] = 0] = "DENSE";
+ /**
+ * Single texels contain only values from the same batch, and from adjacent
+ * rows and columns.
+ *
+ * This is how the shader encodes a tensor with shape = [2, 3, 5]
+ * (indices are [batch, row, col]).
+ *
+ * 000|001 002|003 004|xxx 020|021 022|023 024|xxx
+ * ------- ------- ------- ------- ------- -------
+ * 010|011 012|013 014|xxx xxx|xxx xxx|xxx xxx|xxx
+ *
+ * 100|101 102|103 104|xxx 120|121 122|123 124|xxx
+ * ------- ------- ------- ------- ------- -------
+ * 110|111 112|113 114|xxx xxx|xxx xxx|xxx xxx|xxx
+ *
+ */
+ PackingScheme[PackingScheme["SHARED_BATCH"] = 1] = "SHARED_BATCH";
+ })(PackingScheme || (PackingScheme = {}));
+ var TextureUsage;
+ (function (TextureUsage) {
+ TextureUsage[TextureUsage["RENDER"] = 0] = "RENDER";
+ TextureUsage[TextureUsage["UPLOAD"] = 1] = "UPLOAD";
+ TextureUsage[TextureUsage["PIXELS"] = 2] = "PIXELS";
+ TextureUsage[TextureUsage["DOWNLOAD"] = 3] = "DOWNLOAD";
+ })(TextureUsage || (TextureUsage = {}));
+ var PhysicalTextureType;
+ (function (PhysicalTextureType) {
+ PhysicalTextureType[PhysicalTextureType["UNPACKED_FLOAT16"] = 0] = "UNPACKED_FLOAT16";
+ PhysicalTextureType[PhysicalTextureType["UNPACKED_FLOAT32"] = 1] = "UNPACKED_FLOAT32";
+ PhysicalTextureType[PhysicalTextureType["PACKED_4X1_UNSIGNED_BYTE"] = 2] = "PACKED_4X1_UNSIGNED_BYTE";
+ PhysicalTextureType[PhysicalTextureType["PACKED_2X2_FLOAT32"] = 3] = "PACKED_2X2_FLOAT32";
+ PhysicalTextureType[PhysicalTextureType["PACKED_2X2_FLOAT16"] = 4] = "PACKED_2X2_FLOAT16";
+ })(PhysicalTextureType || (PhysicalTextureType = {}));
+ function getUnpackedMatrixTextureShapeWidthHeight(rows, columns) {
+ return [columns, rows];
+ }
+ function getUnpackedArraySizeFromMatrixSize(matrixSize, channelsPerTexture) {
+ return matrixSize * channelsPerTexture;
+ }
+ /**
+ * Get shape for densely packed RGBA texture.
+ */
+ function getDenseTexShape(shape) {
+ var size = tf.util.sizeFromShape(shape);
+ var texelsNeeded = Math.ceil(size / 4);
+ return tf.util.sizeToSquarishShape(texelsNeeded);
+ }
+ function getPackedMatrixTextureShapeWidthHeight(rows, columns) {
+ return [
+ Math.max(1, Math.ceil(columns / 2)), Math.max(1, Math.ceil(rows / 2))
+ ];
+ }
+ function getPackedRGBAArraySizeFromMatrixShape(rows, columns) {
+ var _a = getPackedMatrixTextureShapeWidthHeight(rows, columns), w = _a[0], h = _a[1];
+ return w * h * 4;
+ }
+ function getTextureConfig(
+ // tslint:disable-next-line:no-any
+ gl, textureHalfFloatExtension) {
+ // tslint:disable-next-line:no-any
+ var glany = gl;
+ var internalFormatFloat;
+ var internalFormatHalfFloat;
+ var internalFormatPackedHalfFloat;
+ var internalFormatPackedFloat;
+ var textureFormatFloat;
+ var downloadTextureFormat;
+ var downloadUnpackNumChannels;
+ var defaultNumChannels;
+ var textureTypeHalfFloat;
+ var textureTypeFloat;
+ if (tf.env().getNumber('WEBGL_VERSION') === 2) {
+ internalFormatFloat = glany.R32F;
+ internalFormatHalfFloat = glany.R16F;
+ internalFormatPackedHalfFloat = glany.RGBA16F;
+ internalFormatPackedFloat = glany.RGBA32F;
+ textureFormatFloat = glany.RED;
+ downloadUnpackNumChannels = 4;
+ defaultNumChannels = 1;
+ textureTypeHalfFloat = glany.HALF_FLOAT;
+ textureTypeFloat = glany.FLOAT;
+ }
+ else {
+ internalFormatFloat = gl.RGBA;
+ internalFormatHalfFloat = gl.RGBA;
+ internalFormatPackedHalfFloat = gl.RGBA;
+ internalFormatPackedFloat = glany.RGBA;
+ textureFormatFloat = gl.RGBA;
+ downloadUnpackNumChannels = 4;
+ defaultNumChannels = 4;
+ textureTypeHalfFloat = textureHalfFloatExtension != null ?
+ textureHalfFloatExtension.HALF_FLOAT_OES :
+ null;
+ textureTypeFloat = gl.FLOAT;
+ }
+ downloadTextureFormat = gl.RGBA;
+ return {
+ internalFormatFloat: internalFormatFloat,
+ internalFormatHalfFloat: internalFormatHalfFloat,
+ internalFormatPackedHalfFloat: internalFormatPackedHalfFloat,
+ internalFormatPackedFloat: internalFormatPackedFloat,
+ textureFormatFloat: textureFormatFloat,
+ downloadTextureFormat: downloadTextureFormat,
+ downloadUnpackNumChannels: downloadUnpackNumChannels,
+ defaultNumChannels: defaultNumChannels,
+ textureTypeHalfFloat: textureTypeHalfFloat,
+ textureTypeFloat: textureTypeFloat
+ };
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function callAndCheck(gl, func) {
+ var returnValue = func();
+ if (tf.env().getBool('DEBUG')) {
+ checkWebGLError(gl);
+ }
+ return returnValue;
+ }
+ function checkWebGLError(gl) {
+ var error = gl.getError();
+ if (error !== gl.NO_ERROR) {
+ throw new Error('WebGL Error: ' + getWebGLErrorMessage(gl, error));
+ }
+ }
+ // https://en.wikipedia.org/wiki/Half-precision_floating-point_format
+ var MIN_FLOAT16 = 5.96e-8;
+ var MAX_FLOAT16 = 65504;
+ function canBeRepresented(num) {
+ if (tf.env().getBool('WEBGL_RENDER_FLOAT32_ENABLED') || num === 0 ||
+ (MIN_FLOAT16 < Math.abs(num) && Math.abs(num) < MAX_FLOAT16)) {
+ return true;
+ }
+ return false;
+ }
+ function getWebGLErrorMessage(gl, status) {
+ switch (status) {
+ case gl.NO_ERROR:
+ return 'NO_ERROR';
+ case gl.INVALID_ENUM:
+ return 'INVALID_ENUM';
+ case gl.INVALID_VALUE:
+ return 'INVALID_VALUE';
+ case gl.INVALID_OPERATION:
+ return 'INVALID_OPERATION';
+ case gl.INVALID_FRAMEBUFFER_OPERATION:
+ return 'INVALID_FRAMEBUFFER_OPERATION';
+ case gl.OUT_OF_MEMORY:
+ return 'OUT_OF_MEMORY';
+ case gl.CONTEXT_LOST_WEBGL:
+ return 'CONTEXT_LOST_WEBGL';
+ default:
+ return "Unknown error code " + status;
+ }
+ }
+ function getExtensionOrThrow(gl, extensionName) {
+ return throwIfNull(gl, function () { return gl.getExtension(extensionName); }, 'Extension "' + extensionName + '" not supported on this browser.');
+ }
+ function createVertexShader(gl, vertexShaderSource) {
+ var vertexShader = throwIfNull(gl, function () { return gl.createShader(gl.VERTEX_SHADER); }, 'Unable to create vertex WebGLShader.');
+ callAndCheck(gl, function () { return gl.shaderSource(vertexShader, vertexShaderSource); });
+ callAndCheck(gl, function () { return gl.compileShader(vertexShader); });
+ if (gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS) === false) {
+ console.log(gl.getShaderInfoLog(vertexShader));
+ throw new Error('Failed to compile vertex shader.');
+ }
+ return vertexShader;
+ }
+ function createFragmentShader(gl, fragmentShaderSource) {
+ var fragmentShader = throwIfNull(gl, function () { return gl.createShader(gl.FRAGMENT_SHADER); }, 'Unable to create fragment WebGLShader.');
+ callAndCheck(gl, function () { return gl.shaderSource(fragmentShader, fragmentShaderSource); });
+ callAndCheck(gl, function () { return gl.compileShader(fragmentShader); });
+ if (gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS) === false) {
+ logShaderSourceAndInfoLog(fragmentShaderSource, gl.getShaderInfoLog(fragmentShader));
+ throw new Error('Failed to compile fragment shader.');
+ }
+ return fragmentShader;
+ }
+ var lineNumberRegex = /ERROR: [0-9]+:([0-9]+):/g;
+ function logShaderSourceAndInfoLog(shaderSource, shaderInfoLog) {
+ var lineNumberRegexResult = lineNumberRegex.exec(shaderInfoLog);
+ if (lineNumberRegexResult == null) {
+ console.log("Couldn't parse line number in error: " + shaderInfoLog);
+ console.log(shaderSource);
+ return;
+ }
+ var lineNumber = +lineNumberRegexResult[1];
+ var shaderLines = shaderSource.split('\n');
+ var pad = shaderLines.length.toString().length + 2;
+ var linesWithLineNumbers = shaderLines.map(function (line, lineNumber) {
+ return tf.util.rightPad((lineNumber + 1).toString(), pad) + line;
+ });
+ var maxLineLength = 0;
+ for (var i = 0; i < linesWithLineNumbers.length; i++) {
+ maxLineLength = Math.max(linesWithLineNumbers[i].length, maxLineLength);
+ }
+ var beforeErrorLines = linesWithLineNumbers.slice(0, lineNumber - 1);
+ var errorLine = linesWithLineNumbers.slice(lineNumber - 1, lineNumber);
+ var afterErrorLines = linesWithLineNumbers.slice(lineNumber);
+ console.log(beforeErrorLines.join('\n'));
+ console.log(shaderInfoLog.split('\n')[0]);
+ console.log("%c " + tf.util.rightPad(errorLine[0], maxLineLength), 'border:1px solid red; background-color:#e3d2d2; color:#a61717');
+ console.log(afterErrorLines.join('\n'));
+ }
+ function createProgram(gl) {
+ return throwIfNull(gl, function () { return gl.createProgram(); }, 'Unable to create WebGLProgram.');
+ }
+ function linkProgram(gl, program) {
+ callAndCheck(gl, function () { return gl.linkProgram(program); });
+ if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
+ console.log(gl.getProgramInfoLog(program));
+ throw new Error('Failed to link vertex and fragment shaders.');
+ }
+ }
+ function validateProgram(gl, program) {
+ callAndCheck(gl, function () { return gl.validateProgram(program); });
+ if (gl.getProgramParameter(program, gl.VALIDATE_STATUS) === false) {
+ console.log(gl.getProgramInfoLog(program));
+ throw new Error('Shader program validation failed.');
+ }
+ }
+ function createStaticVertexBuffer(gl, data) {
+ var buffer = throwIfNull(gl, function () { return gl.createBuffer(); }, 'Unable to create WebGLBuffer');
+ callAndCheck(gl, function () { return gl.bindBuffer(gl.ARRAY_BUFFER, buffer); });
+ callAndCheck(gl, function () { return gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); });
+ return buffer;
+ }
+ function createStaticIndexBuffer(gl, data) {
+ var buffer = throwIfNull(gl, function () { return gl.createBuffer(); }, 'Unable to create WebGLBuffer');
+ callAndCheck(gl, function () { return gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer); });
+ callAndCheck(gl, function () { return gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW); });
+ return buffer;
+ }
+ function getNumChannels() {
+ if (tf.env().getNumber('WEBGL_VERSION') === 2) {
+ return 1;
+ }
+ return 4;
+ }
+ function createTexture(gl) {
+ return throwIfNull(gl, function () { return gl.createTexture(); }, 'Unable to create WebGLTexture.');
+ }
+ function validateTextureSize(width, height) {
+ var maxTextureSize = tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE');
+ if ((width <= 0) || (height <= 0)) {
+ var requested = "[" + width + "x" + height + "]";
+ throw new Error('Requested texture size ' + requested + ' is invalid.');
+ }
+ if ((width > maxTextureSize) || (height > maxTextureSize)) {
+ var requested = "[" + width + "x" + height + "]";
+ var max = "[" + maxTextureSize + "x" + maxTextureSize + "]";
+ throw new Error('Requested texture size ' + requested +
+ ' greater than WebGL maximum on this browser / GPU ' + max + '.');
+ }
+ }
+ function createFramebuffer(gl) {
+ return throwIfNull(gl, function () { return gl.createFramebuffer(); }, 'Unable to create WebGLFramebuffer.');
+ }
+ function bindVertexBufferToProgramAttribute(gl, program, attribute, buffer, arrayEntriesPerItem, itemStrideInBytes, itemOffsetInBytes) {
+ var loc = gl.getAttribLocation(program, attribute);
+ if (loc === -1) {
+ // The GPU compiler decided to strip out this attribute because it's unused,
+ // thus no need to bind.
+ return false;
+ }
+ callAndCheck(gl, function () { return gl.bindBuffer(gl.ARRAY_BUFFER, buffer); });
+ callAndCheck(gl, function () { return gl.vertexAttribPointer(loc, arrayEntriesPerItem, gl.FLOAT, false, itemStrideInBytes, itemOffsetInBytes); });
+ callAndCheck(gl, function () { return gl.enableVertexAttribArray(loc); });
+ return true;
+ }
+ function bindTextureUnit(gl, texture, textureUnit) {
+ validateTextureUnit(gl, textureUnit);
+ callAndCheck(gl, function () { return gl.activeTexture(gl.TEXTURE0 + textureUnit); });
+ callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, texture); });
+ }
+ function unbindTextureUnit(gl, textureUnit) {
+ validateTextureUnit(gl, textureUnit);
+ callAndCheck(gl, function () { return gl.activeTexture(gl.TEXTURE0 + textureUnit); });
+ callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, null); });
+ }
+ function getProgramUniformLocationOrThrow(gl, program, uniformName) {
+ return throwIfNull(gl, function () { return gl.getUniformLocation(program, uniformName); }, 'uniform "' + uniformName + '" not present in program.');
+ }
+ function getProgramUniformLocation(gl, program, uniformName) {
+ return gl.getUniformLocation(program, uniformName);
+ }
+ function bindTextureToProgramUniformSampler(gl, texture, uniformSamplerLocation, textureUnit) {
+ callAndCheck(gl, function () { return bindTextureUnit(gl, texture, textureUnit); });
+ callAndCheck(gl, function () { return gl.uniform1i(uniformSamplerLocation, textureUnit); });
+ }
+ function bindCanvasToFramebuffer(gl) {
+ callAndCheck(gl, function () { return gl.bindFramebuffer(gl.FRAMEBUFFER, null); });
+ callAndCheck(gl, function () { return gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); });
+ callAndCheck(gl, function () { return gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); });
+ }
+ function bindColorTextureToFramebuffer(gl, texture, framebuffer) {
+ callAndCheck(gl, function () { return gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); });
+ callAndCheck(gl, function () { return gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); });
+ }
+ function unbindColorTextureFromFramebuffer(gl, framebuffer) {
+ callAndCheck(gl, function () { return gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); });
+ callAndCheck(gl, function () { return gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0); });
+ }
+ function validateFramebuffer(gl) {
+ var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
+ if (status !== gl.FRAMEBUFFER_COMPLETE) {
+ throw new Error('Error binding framebuffer: ' + getFramebufferErrorMessage(gl, status));
+ }
+ }
+ function getFramebufferErrorMessage(gl, status) {
+ switch (status) {
+ case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
+ return 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT';
+ case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
+ return 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT';
+ case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
+ return 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS';
+ case gl.FRAMEBUFFER_UNSUPPORTED:
+ return 'FRAMEBUFFER_UNSUPPORTED';
+ default:
+ return "unknown error " + status;
+ }
+ }
+ function throwIfNull(gl, returnTOrNull, failureMessage) {
+ var tOrNull = callAndCheck(gl, function () { return returnTOrNull(); });
+ if (tOrNull == null) {
+ throw new Error(failureMessage);
+ }
+ return tOrNull;
+ }
+ function validateTextureUnit(gl, textureUnit) {
+ var maxTextureUnit = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1;
+ var glTextureUnit = textureUnit + gl.TEXTURE0;
+ if (glTextureUnit < gl.TEXTURE0 || glTextureUnit > maxTextureUnit) {
+ var textureUnitRange = "[gl.TEXTURE0, gl.TEXTURE" + maxTextureUnit + "]";
+ throw new Error("textureUnit must be in " + textureUnitRange + ".");
+ }
+ }
+ function getBatchDim(shape, dimsToSkip) {
+ if (dimsToSkip === void 0) { dimsToSkip = 2; }
+ return tf.util.sizeFromShape(shape.slice(0, shape.length - dimsToSkip));
+ }
+ function getRowsCols(shape) {
+ if (shape.length === 0) {
+ throw Error('Cannot get rows and columns of an empty shape array.');
+ }
+ return [
+ shape.length > 1 ? shape[shape.length - 2] : 1, shape[shape.length - 1]
+ ];
+ }
+ function getShapeAs3D(shape) {
+ var shapeAs3D = [1, 1, 1];
+ var isScalar = shape.length === 0 || (shape.length === 1 && shape[0] === 1);
+ if (!isScalar) {
+ shapeAs3D =
+ [getBatchDim(shape)].concat(getRowsCols(shape));
+ }
+ return shapeAs3D;
+ }
+ function getTextureShapeFromLogicalShape(logShape, isPacked) {
+ var _a;
+ if (isPacked === void 0) { isPacked = false; }
+ var maxTexSize = tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE');
+ if (isPacked) {
+ maxTexSize = maxTexSize * 2;
+ // This logic ensures we accurately count the number of packed texels needed
+ // to accommodate the tensor. We can only pack values in the same texel if
+ // they are from adjacent pairs of rows/cols within the same batch. So if a
+ // tensor has 3 rows, we pretend it has 4 rows in order to account for the
+ // fact that the texels containing the third row are half empty.
+ logShape = logShape.map(function (d, i) { return i >= logShape.length - 2 ?
+ tf.util.nearestLargerEven(logShape[i]) :
+ logShape[i]; });
+ // Packed texture height is at least 2 (the channel height of a single
+ // texel).
+ if (logShape.length === 1) {
+ logShape = [2, logShape[0]];
+ }
+ }
+ // If logical shape is 2, we don't squeeze, since we want to match physical.
+ if (logShape.length !== 2) {
+ var squeezeResult = tf.util.squeezeShape(logShape);
+ logShape = squeezeResult.newShape;
+ }
+ var size = tf.util.sizeFromShape(logShape);
+ if (logShape.length <= 1 && size <= maxTexSize) {
+ return [1, size];
+ }
+ else if (logShape.length === 2 && logShape[0] <= maxTexSize &&
+ logShape[1] <= maxTexSize) {
+ return logShape;
+ }
+ else if (logShape.length === 3 && logShape[0] * logShape[1] <= maxTexSize &&
+ logShape[2] <= maxTexSize) {
+ return [logShape[0] * logShape[1], logShape[2]];
+ }
+ else if (logShape.length === 3 && logShape[0] <= maxTexSize &&
+ logShape[1] * logShape[2] <= maxTexSize) {
+ return [logShape[0], logShape[1] * logShape[2]];
+ }
+ else if (logShape.length === 4 &&
+ logShape[0] * logShape[1] * logShape[2] <= maxTexSize &&
+ logShape[3] <= maxTexSize) {
+ return [logShape[0] * logShape[1] * logShape[2], logShape[3]];
+ }
+ else if (logShape.length === 4 && logShape[0] <= maxTexSize &&
+ logShape[1] * logShape[2] * logShape[3] <= maxTexSize) {
+ return [logShape[0], logShape[1] * logShape[2] * logShape[3]];
+ }
+ else {
+ if (isPacked) {
+ // For packed textures size equals the number of channels required to
+ // accommodate the texture data. However in order to squarify such that
+ // inner dimensions stay even, we rewrite size to equal the number of
+ // texels. Then in the return statement we rehydrate the squarified
+ // dimensions to channel units.
+ var batchDim = getBatchDim(logShape);
+ var rows = 2, cols = 2;
+ if (logShape.length) {
+ _a = getRowsCols(logShape), rows = _a[0], cols = _a[1];
+ }
+ size = batchDim * (rows / 2) * (cols / 2);
+ return tf.util.sizeToSquarishShape(size).map(function (d) { return d * 2; });
+ }
+ return tf.util.sizeToSquarishShape(size);
+ }
+ }
+ function isEven(n) {
+ return n % 2 === 0;
+ }
+ /**
+ * This determines whether reshaping a packed texture requires rearranging
+ * the data within the texture, assuming 2x2 packing.
+ */
+ function isReshapeFree(shape1, shape2) {
+ shape1 = shape1.slice(-2);
+ shape2 = shape2.slice(-2);
+ if (tf.util.arraysEqual(shape1, shape2)) {
+ return true;
+ }
+ if (!shape1.length || !shape2.length) { // One of the shapes is a scalar.
+ return true;
+ }
+ if (shape1[0] === 0 || shape1[1] === 0 || shape2[0] === 0 ||
+ shape2[1] === 0) {
+ return true;
+ }
+ if (shape1.length !== shape2.length) { // One of the shapes is a vector.
+ var shape1Cols = shape1.slice(-1)[0];
+ var shape2Cols = shape2.slice(-1)[0];
+ if (shape1Cols === shape2Cols) {
+ return true;
+ }
+ if (isEven(shape1Cols) && isEven(shape2Cols) &&
+ (shape1[0] === 1 || shape2[0] === 1)) {
+ return true;
+ }
+ }
+ return shape1[1] === shape2[1] && isEven(shape1[0]) && isEven(shape2[0]);
+ }
+ // We cache webgl params because the environment gets reset between
+ // unit tests and we don't want to constantly query the WebGLContext for
+ // MAX_TEXTURE_SIZE.
+ var MAX_TEXTURE_SIZE;
+ var MAX_TEXTURES_IN_SHADER;
+ function getWebGLMaxTextureSize(webGLVersion) {
+ if (MAX_TEXTURE_SIZE == null) {
+ var gl = getWebGLContext(webGLVersion);
+ MAX_TEXTURE_SIZE = gl.getParameter(gl.MAX_TEXTURE_SIZE);
+ }
+ return MAX_TEXTURE_SIZE;
+ }
+ function resetMaxTextureSize() {
+ MAX_TEXTURE_SIZE = null;
+ }
+ function resetMaxTexturesInShader() {
+ MAX_TEXTURES_IN_SHADER = null;
+ }
+ function getMaxTexturesInShader(webGLVersion) {
+ if (MAX_TEXTURES_IN_SHADER == null) {
+ var gl = getWebGLContext(webGLVersion);
+ MAX_TEXTURES_IN_SHADER = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
+ }
+ // We cap at 16 to avoid spurious runtime "memory exhausted" error.
+ return Math.min(16, MAX_TEXTURES_IN_SHADER);
+ }
+ function getWebGLDisjointQueryTimerVersion(webGLVersion) {
+ if (webGLVersion === 0) {
+ return 0;
+ }
+ var queryTimerVersion;
+ var gl = getWebGLContext(webGLVersion);
+ if (hasExtension(gl, 'EXT_disjoint_timer_query_webgl2') &&
+ webGLVersion === 2) {
+ queryTimerVersion = 2;
+ }
+ else if (hasExtension(gl, 'EXT_disjoint_timer_query')) {
+ queryTimerVersion = 1;
+ }
+ else {
+ queryTimerVersion = 0;
+ }
+ return queryTimerVersion;
+ }
+ function hasExtension(gl, extensionName) {
+ var ext = gl.getExtension(extensionName);
+ return ext != null;
+ }
+ function isWebGLVersionEnabled(webGLVersion) {
+ try {
+ var gl = getWebGLContext(webGLVersion);
+ if (gl != null) {
+ return true;
+ }
+ }
+ catch (e) {
+ console.log('Error when getting WebGL context: ', e);
+ return false;
+ }
+ return false;
+ }
+ function isCapableOfRenderingToFloatTexture(webGLVersion) {
+ if (webGLVersion === 0) {
+ return false;
+ }
+ var gl = getWebGLContext(webGLVersion);
+ if (webGLVersion === 1) {
+ if (!hasExtension(gl, 'OES_texture_float')) {
+ return false;
+ }
+ }
+ else {
+ if (!hasExtension(gl, 'EXT_color_buffer_float')) {
+ return false;
+ }
+ }
+ var isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);
+ return isFrameBufferComplete;
+ }
+ /**
+ * Check if we can download values from a float/half-float texture.
+ *
+ * Note that for performance reasons we use binding a texture to a framebuffer
+ * as a proxy for ability to download float values later using readPixels. The
+ * texture params of this texture will not match those in readPixels exactly
+ * but if we are unable to bind some kind of float texture to the frameBuffer
+ * then we definitely will not be able to read float values from it.
+ */
+ function isDownloadFloatTextureEnabled(webGLVersion) {
+ if (webGLVersion === 0) {
+ return false;
+ }
+ var gl = getWebGLContext(webGLVersion);
+ if (webGLVersion === 1) {
+ if (!hasExtension(gl, 'OES_texture_float')) {
+ return false;
+ }
+ if (!hasExtension(gl, 'WEBGL_color_buffer_float')) {
+ return false;
+ }
+ }
+ else {
+ if (hasExtension(gl, 'EXT_color_buffer_float')) {
+ return createFloatTextureAndBindToFramebuffer(gl);
+ }
+ var COLOR_BUFFER_HALF_FLOAT = 'EXT_color_buffer_half_float';
+ if (hasExtension(gl, COLOR_BUFFER_HALF_FLOAT)) {
+ var textureHalfFloatExtension = gl.getExtension(COLOR_BUFFER_HALF_FLOAT);
+ return createHalfFloatTextureAndBindToFramebuffer(gl, textureHalfFloatExtension);
+ }
+ return false;
+ }
+ var isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);
+ return isFrameBufferComplete;
+ }
+ function createFloatTextureAndBindToFramebuffer(gl) {
+ var texConfig = getTextureConfig(gl);
+ var texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ var width = 1;
+ var height = 1;
+ gl.texImage2D(gl.TEXTURE_2D, 0, texConfig.internalFormatFloat, width, height, 0, texConfig.textureFormatFloat, texConfig.textureTypeFloat, null);
+ var frameBuffer = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ var isFrameBufferComplete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.deleteTexture(texture);
+ gl.deleteFramebuffer(frameBuffer);
+ return isFrameBufferComplete;
+ }
+ function createHalfFloatTextureAndBindToFramebuffer(
+ // tslint:disable-next-line:no-any
+ gl, textureHalfFloatExtension) {
+ var texConfig = getTextureConfig(gl, textureHalfFloatExtension);
+ var texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ var width = 1;
+ var height = 1;
+ gl.texImage2D(gl.TEXTURE_2D, 0, texConfig.internalFormatHalfFloat, width, height, 0, texConfig.textureFormatFloat, texConfig.textureTypeHalfFloat, null);
+ var frameBuffer = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ var isFrameBufferComplete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.deleteTexture(texture);
+ gl.deleteFramebuffer(frameBuffer);
+ return isFrameBufferComplete;
+ }
+ function isWebGLFenceEnabled(webGLVersion) {
+ if (webGLVersion !== 2) {
+ return false;
+ }
+ var gl = getWebGLContext(webGLVersion);
+ // tslint:disable-next-line:no-any
+ var isEnabled = gl.fenceSync != null;
+ return isEnabled;
+ }
+ function assertNotComplex(tensor, opName) {
+ if (!Array.isArray(tensor)) {
+ tensor = [tensor];
+ }
+ tensor.forEach(function (t) {
+ if (t != null) {
+ tf.util.assert(t.dtype !== 'complex64', function () { return opName + " does not support complex64 tensors " +
+ 'in the WebGL backend.'; });
+ }
+ });
+ }
+
+ var webgl_util = {
+ __proto__: null,
+ callAndCheck: callAndCheck,
+ canBeRepresented: canBeRepresented,
+ getWebGLErrorMessage: getWebGLErrorMessage,
+ getExtensionOrThrow: getExtensionOrThrow,
+ createVertexShader: createVertexShader,
+ createFragmentShader: createFragmentShader,
+ createProgram: createProgram,
+ linkProgram: linkProgram,
+ validateProgram: validateProgram,
+ createStaticVertexBuffer: createStaticVertexBuffer,
+ createStaticIndexBuffer: createStaticIndexBuffer,
+ getNumChannels: getNumChannels,
+ createTexture: createTexture,
+ validateTextureSize: validateTextureSize,
+ createFramebuffer: createFramebuffer,
+ bindVertexBufferToProgramAttribute: bindVertexBufferToProgramAttribute,
+ bindTextureUnit: bindTextureUnit,
+ unbindTextureUnit: unbindTextureUnit,
+ getProgramUniformLocationOrThrow: getProgramUniformLocationOrThrow,
+ getProgramUniformLocation: getProgramUniformLocation,
+ bindTextureToProgramUniformSampler: bindTextureToProgramUniformSampler,
+ bindCanvasToFramebuffer: bindCanvasToFramebuffer,
+ bindColorTextureToFramebuffer: bindColorTextureToFramebuffer,
+ unbindColorTextureFromFramebuffer: unbindColorTextureFromFramebuffer,
+ validateFramebuffer: validateFramebuffer,
+ getFramebufferErrorMessage: getFramebufferErrorMessage,
+ getBatchDim: getBatchDim,
+ getRowsCols: getRowsCols,
+ getShapeAs3D: getShapeAs3D,
+ getTextureShapeFromLogicalShape: getTextureShapeFromLogicalShape,
+ isReshapeFree: isReshapeFree,
+ getWebGLMaxTextureSize: getWebGLMaxTextureSize,
+ resetMaxTextureSize: resetMaxTextureSize,
+ resetMaxTexturesInShader: resetMaxTexturesInShader,
+ getMaxTexturesInShader: getMaxTexturesInShader,
+ getWebGLDisjointQueryTimerVersion: getWebGLDisjointQueryTimerVersion,
+ hasExtension: hasExtension,
+ isWebGLVersionEnabled: isWebGLVersionEnabled,
+ isCapableOfRenderingToFloatTexture: isCapableOfRenderingToFloatTexture,
+ isDownloadFloatTextureEnabled: isDownloadFloatTextureEnabled,
+ isWebGLFenceEnabled: isWebGLFenceEnabled,
+ assertNotComplex: assertNotComplex
+ };
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ENV = tf.env();
+ /**
+ * This file contains WebGL-specific flag registrations.
+ */
+ /**
+ * True if WebGL is supported.
+ */
+ ENV.registerFlag('HAS_WEBGL', function () { return ENV.getNumber('WEBGL_VERSION') > 0; });
+ /** 0: No WebGL, 1: WebGL 1.0, 2: WebGL 2.0. */
+ ENV.registerFlag('WEBGL_VERSION', function () {
+ if (isWebGLVersionEnabled(2)) {
+ return 2;
+ }
+ else if (isWebGLVersionEnabled(1)) {
+ return 1;
+ }
+ return 0;
+ });
+ /** Whether to check for numerical representation problems. */
+ ENV.registerFlag('WEBGL_CHECK_NUMERICAL_PROBLEMS', function () { return false; });
+ ENV.registerFlag('WEBGL_BUFFER_SUPPORTED', function () { return ENV.get('WEBGL_VERSION') === 2; });
+ /** Whether the WebGL backend will sometimes forward ops to the CPU. */
+ ENV.registerFlag('WEBGL_CPU_FORWARD', function () { return true; });
+ /** Whether the WebGL backend will always use f16 textures for rendering. */
+ ENV.registerFlag('WEBGL_FORCE_F16_TEXTURES', function () { return false; });
+ /** Whether to turn all packing related flags on. */
+ ENV.registerFlag('WEBGL_PACK', function () { return ENV.getBool('HAS_WEBGL'); });
+ /** Whether we will pack the batchnormalization op. */
+ ENV.registerFlag('WEBGL_PACK_NORMALIZATION', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** Whether we will pack the clip op. */
+ ENV.registerFlag('WEBGL_PACK_CLIP', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** Whether we will pack the depthwise conv op. */
+ ENV.registerFlag('WEBGL_PACK_DEPTHWISECONV', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** Whether we will pack binary ops. */
+ ENV.registerFlag('WEBGL_PACK_BINARY_OPERATIONS', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** Whether we will pack unary ops. */
+ ENV.registerFlag('WEBGL_PACK_UNARY_OPERATIONS', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** Whether we will pack array ops. */
+ ENV.registerFlag('WEBGL_PACK_ARRAY_OPERATIONS', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** Whether we will pack image ops. */
+ ENV.registerFlag('WEBGL_PACK_IMAGE_OPERATIONS', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** Whether we will pack reduce ops. */
+ ENV.registerFlag('WEBGL_PACK_REDUCE', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** Whether packed WebGL kernels lazily unpack their outputs. */
+ ENV.registerFlag('WEBGL_LAZILY_UNPACK', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** Whether we will use the im2col algorithm to speed up convolutions. */
+ ENV.registerFlag('WEBGL_CONV_IM2COL', function () { return ENV.getBool('WEBGL_PACK'); });
+ /** The maximum texture dimension. */
+ ENV.registerFlag('WEBGL_MAX_TEXTURE_SIZE', function () { return getWebGLMaxTextureSize(ENV.getNumber('WEBGL_VERSION')); });
+ /** The maximum texture dimension. */
+ ENV.registerFlag('WEBGL_MAX_TEXTURES_IN_SHADER', function () { return getMaxTexturesInShader(ENV.getNumber('WEBGL_VERSION')); });
+ /**
+ * The disjoint_query_timer extension version.
+ * 0: disabled, 1: EXT_disjoint_timer_query, 2:
+ * EXT_disjoint_timer_query_webgl2.
+ * In Firefox with WebGL 2.0,
+ * EXT_disjoint_timer_query_webgl2 is not available, so we must use the
+ * WebGL 1.0 extension.
+ */
+ ENV.registerFlag('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION', function () {
+ var webGLVersion = ENV.getNumber('WEBGL_VERSION');
+ if (webGLVersion === 0) {
+ return 0;
+ }
+ return getWebGLDisjointQueryTimerVersion(webGLVersion);
+ });
+ /**
+ * Whether the timer object from the disjoint_query_timer extension gives
+ * timing information that is reliable.
+ */
+ ENV.registerFlag('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE', function () { return ENV.getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0 &&
+ !tf.device_util.isMobile(); });
+ /**
+ * Whether the device is physically capable of rendering to float32 textures.
+ */
+ ENV.registerFlag('WEBGL_RENDER_FLOAT32_CAPABLE', function () { return isCapableOfRenderingToFloatTexture(ENV.getNumber('WEBGL_VERSION')); });
+ /**
+ * Whether rendering to float32 textures is enabled. If disabled, renders to
+ * float16 textures.
+ */
+ ENV.registerFlag('WEBGL_RENDER_FLOAT32_ENABLED', function () {
+ return ENV.getBool('WEBGL_FORCE_F16_TEXTURES') ?
+ false :
+ ENV.getBool('WEBGL_RENDER_FLOAT32_CAPABLE');
+ });
+ /**
+ * Whether downloading float textures is enabled (16 or 32 bit). If disabled,
+ * uses IEEE 754 encoding of the float32 values to 4 uint8 when downloading.
+ */
+ ENV.registerFlag('WEBGL_DOWNLOAD_FLOAT_ENABLED', function () { return isDownloadFloatTextureEnabled(ENV.getNumber('WEBGL_VERSION')); });
+ /** Whether the fence API is available. */
+ ENV.registerFlag('WEBGL_FENCE_API_ENABLED', function () { return isWebGLFenceEnabled(ENV.getNumber('WEBGL_VERSION')); });
+ /**
+ * Tensors with size <= than this will be uploaded as uniforms, not textures.
+ */
+ ENV.registerFlag('WEBGL_SIZE_UPLOAD_UNIFORM', function () {
+ // Use uniform uploads only when 32bit floats are supported. In
+ // 16bit
+ // environments there are problems with comparing a 16bit texture value
+ // with a 32bit uniform value.
+ var useUniforms = ENV.getBool('WEBGL_RENDER_FLOAT32_ENABLED');
+ return useUniforms ? 4 : 0;
+ });
+ /**
+ * If the total number of bytes allocated on the GPU is greater than this
+ * number, we will aggressively delete textures upon disposal with
+ * gl.deleteMatrixTexture, rather than making them available for reuse.
+ *
+ * Default value -1 indicates that we will never aggressively delete textures.
+ */
+ ENV.registerFlag('WEBGL_DELETE_TEXTURE_THRESHOLD', function () {
+ return -1;
+ }, function (threshold) {
+ if (threshold < 0 && threshold !== -1) {
+ throw new Error("WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never " +
+ ("delete) or at least 0, but got " + threshold + "."));
+ }
+ });
+ /**
+ * Trigger a manual GL command flush if the threshold of time has passed since
+ * previous Kernel execution. This can be useful for Andorid device where GL
+ * command flush are delayed un til the end of javascript task. This value is
+ * measured in millisecond. Typically you want to set this value to close to 1.
+ *
+ * Default value 1 for mobile chrome, and -1 for rest cases. -1 indicates that
+ * we will not enforce manual flush and depend on system default flush schedule.
+ */
+ ENV.registerFlag('WEBGL_FLUSH_THRESHOLD', function () {
+ return tf.device_util.isMobile() && ENV.getBool('IS_CHROME') ? 1 : -1;
+ }, function (threshold) {
+ if (threshold < 0 && threshold !== -1) {
+ throw new Error("WEBGL_FLUSH_THRESHOLD must be -1 (indicating never " +
+ ("manual flush) or at least 0, but got " + threshold + "."));
+ }
+ });
+ /**
+ * Threshold for input tensor size that determines whether WebGL backend will
+ * delegate computation to CPU.
+ *
+ * Default value is 128.
+ */
+ ENV.registerFlag('CPU_HANDOFF_SIZE_THRESHOLD', function () { return 128; });
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function getGlslDifferences() {
+ var version;
+ var attribute;
+ var varyingVs;
+ var varyingFs;
+ var texture2D;
+ var output;
+ var defineOutput;
+ var defineSpecialNaN;
+ var defineSpecialInf;
+ var defineRound;
+ if (tf.env().getNumber('WEBGL_VERSION') === 2) {
+ version = '#version 300 es';
+ attribute = 'in';
+ varyingVs = 'out';
+ varyingFs = 'in';
+ texture2D = 'texture';
+ output = 'outputColor';
+ defineOutput = 'out vec4 outputColor;';
+ // Use custom isnan definition to work across differences between
+ // implementations on various platforms. While this should happen in ANGLE
+ // we still see differences between android and windows (on chrome) when
+ // using isnan directly.
+ defineSpecialNaN = "\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 ";
+ // In webgl 2 we do not need to specify a custom isinf so there is no
+ // need for a special INFINITY constant.
+ defineSpecialInf = "";
+ defineRound = "\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 ";
+ }
+ else {
+ version = '';
+ attribute = 'attribute';
+ varyingVs = 'varying';
+ varyingFs = 'varying';
+ texture2D = 'texture2D';
+ output = 'gl_FragColor';
+ defineOutput = '';
+ // WebGL1 has no built in isnan so we define one here.
+ defineSpecialNaN = "\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 ";
+ defineSpecialInf = "\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 ";
+ defineRound = "\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 ";
+ }
+ return {
+ version: version,
+ attribute: attribute,
+ varyingVs: varyingVs,
+ varyingFs: varyingFs,
+ texture2D: texture2D,
+ output: output,
+ defineOutput: defineOutput,
+ defineSpecialNaN: defineSpecialNaN,
+ defineSpecialInf: defineSpecialInf,
+ defineRound: defineRound
+ };
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Produces GLSL code that derives logical coordinates from a flat
+ * index. The code performs integer division with each stride and decrements
+ * the index until the index equals the final dimension coordinate.
+ */
+ function getLogicalCoordinatesFromFlatIndex(coords, shape, index) {
+ if (index === void 0) { index = 'index'; }
+ var strides = tf.util.computeStrides(shape);
+ return strides
+ .map(function (stride, i) {
+ var line1 = "int " + coords[i] + " = " + index + " / " + stride;
+ var line2 = i === strides.length - 1 ?
+ "int " + coords[i + 1] + " = " + index + " - " + coords[i] + " * " + stride :
+ "index -= " + coords[i] + " * " + stride;
+ return line1 + "; " + line2 + ";";
+ })
+ .join('');
+ }
+ /**
+ * Produces GLSL that computes the flat index from 3D coordinates.
+ */
+ function getFlatIndexFrom3D(shape) {
+ var strides = tf.util.computeStrides(shape).map(function (d) { return d.toString(); });
+ return "\n int getFlatIndex(ivec3 coords) {\n return coords.x * " + strides[0] + " + coords.y * " + strides[1] + " + coords.z;\n }\n";
+ }
+ var ENCODE_FLOAT_SNIPPET = "\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";
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var DecodeMatrixProgram = /** @class */ (function () {
+ function DecodeMatrixProgram(outputShape) {
+ this.variableNames = ['A'];
+ this.packedInputs = false;
+ this.packedOutput = true;
+ this.outPackingScheme = PackingScheme.DENSE;
+ var texShape = getDenseTexShape(outputShape);
+ var glsl = getGlslDifferences();
+ this.outputShape = outputShape;
+ this.userCode = "\n ivec3 outCoordsFromFlatIndex(int index) {\n " + getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd'], outputShape) + "\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = 4 * (resTexRC.x * " + texShape[1] + " + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n " + glsl.output + " = result;\n }\n ";
+ }
+ return DecodeMatrixProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var DecodeMatrixPackedProgram = /** @class */ (function () {
+ function DecodeMatrixPackedProgram(outputShape) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outPackingScheme = PackingScheme.DENSE;
+ var texShape = getDenseTexShape(outputShape);
+ var glsl = getGlslDifferences();
+ this.outputShape = outputShape;
+ this.userCode = "\n ivec3 outCoordsFromFlatIndex(int index) {\n " + getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd'], outputShape) + "\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = 4 * (resTexRC.x * " + texShape[1] + " + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n " + glsl.output + " = result;\n }\n ";
+ }
+ return DecodeMatrixPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var EncodeFloatProgram = /** @class */ (function () {
+ function EncodeFloatProgram(outputShape) {
+ this.variableNames = ['A'];
+ this.outTexUsage = TextureUsage.DOWNLOAD;
+ var glsl = getGlslDifferences();
+ this.outputShape = outputShape;
+ this.userCode = "\n " + ENCODE_FLOAT_SNIPPET + "\n\n void main() {\n float x = getAAtOutCoords();\n " + glsl.output + " = encode_float(x);\n }\n ";
+ }
+ return EncodeFloatProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var EncodeFloatPackedProgram = /** @class */ (function () {
+ function EncodeFloatPackedProgram(outputShape) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = false;
+ this.outTexUsage = TextureUsage.DOWNLOAD;
+ var glsl = getGlslDifferences();
+ this.outputShape = outputShape;
+ this.userCode = "\n " + ENCODE_FLOAT_SNIPPET + "\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n " + glsl.output + " = encode_float(x);\n }\n ";
+ }
+ return EncodeFloatPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var EncodeMatrixProgram = /** @class */ (function () {
+ function EncodeMatrixProgram(outputShape, texShape, inputIsUnsignedByte) {
+ if (inputIsUnsignedByte === void 0) { inputIsUnsignedByte = false; }
+ this.variableNames = ['A'];
+ var glsl = getGlslDifferences();
+ var height = texShape[0], width = texShape[1];
+ this.outputShape = outputShape;
+ var output = "result";
+ if (inputIsUnsignedByte) {
+ output = "floor(result * 255. + 0.5)";
+ }
+ this.userCode = "\n " + getFlatIndexFrom3D(outputShape) + "\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 / " + width + ";\n int c = imod(flatIndex, " + width + ");\n vec2 uv = (vec2(c, r) + halfCR) / vec2(" + width + ".0, " + height + ".0);\n vec4 values = " + glsl.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 " + glsl.output + " = vec4(" + output + ", 0., 0., 0.);\n }\n ";
+ }
+ return EncodeMatrixProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /*
+ This is how the shader encodes a tensor with shape = [2, 3, 5]
+ (indices are [batch, row, col]).
+
+ 000|001 002|003 004|xxx 020|021 022|023 024|xxx
+ ------- ------- ------- ------- ------- -------
+ 010|011 012|013 014|xxx xxx|xxx xxx|xxx xxx|xxx
+
+ 100|101 102|103 104|xxx 120|121 122|123 124|xxx
+ ------- ------- ------- ------- ------- -------
+ 110|111 112|113 114|xxx xxx|xxx xxx|xxx xxx|xxx
+
+ Single texels contain only values from the same batch, and from adjacent rows
+ and columns.
+ */
+ var EncodeMatrixPackedProgram = /** @class */ (function () {
+ function EncodeMatrixPackedProgram(outputShape, texShape, inputIsUnsignedByte) {
+ if (inputIsUnsignedByte === void 0) { inputIsUnsignedByte = false; }
+ this.variableNames = ['A'];
+ this.packedInputs = false;
+ this.packedOutput = true;
+ var glsl = getGlslDifferences();
+ var height = texShape[0], width = texShape[1];
+ this.outputShape = outputShape;
+ var mainLoop = '';
+ var output = 'result';
+ if (inputIsUnsignedByte) {
+ output = 'floor(result * 255. + 0.5)';
+ }
+ for (var row = 0; row <= 1; row++) {
+ for (var col = 0; col <= 1; col++) {
+ var channel = row * 2 + col;
+ mainLoop += "\n localCoords = coords;\n if(localCoords[2] + " + col + " < " + outputShape[2] + ") {\n localCoords[2] += " + col + ";\n if(localCoords[1] + " + row + " < " + outputShape[1] + ") {\n localCoords[1] += " + row + ";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / " + width + ";\n c = imod(flatIndex, " + width + ");\n uv = (vec2(c, r) + halfCR) / vec2(" + width + ".0, " + height + ".0);\n values = " + glsl.texture2D + "(A, uv);\n\n if(offset == 0) {\n result[" + channel + "] = values[0];\n } else if(offset == 1) {\n result[" + channel + "] = values[1];\n } else if(offset == 2) {\n result[" + channel + "] = values[2];\n } else {\n result[" + channel + "] = values[3];\n }\n }\n }\n ";
+ }
+ }
+ this.userCode = "\n " + getFlatIndexFrom3D(outputShape) + "\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 " + mainLoop + "\n\n " + glsl.output + " = " + output + ";\n }\n ";
+ }
+ return EncodeMatrixPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function createVertexShader$1(gl) {
+ var glsl = getGlslDifferences();
+ var vertexShaderSource = glsl.version + "\n precision highp float;\n " + glsl.attribute + " vec3 clipSpacePos;\n " + glsl.attribute + " vec2 uv;\n " + glsl.varyingVs + " vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }";
+ return createVertexShader(gl, vertexShaderSource);
+ }
+ function createVertexBuffer(gl) {
+ // [x y z u v] * [upper-left, lower-left, upper-right, lower-right]
+ var vertexArray = new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);
+ return createStaticVertexBuffer(gl, vertexArray);
+ }
+ function createIndexBuffer(gl) {
+ // OpenGL (and WebGL) have "CCW == front" winding
+ var triangleVertexIndices = new Uint16Array([0, 1, 2, 2, 1, 3]);
+ return createStaticIndexBuffer(gl, triangleVertexIndices);
+ }
+ function createAndConfigureTexture(gl, width, height, internalFormat, textureFormat, textureType) {
+ validateTextureSize(width, height);
+ var texture = createTexture(gl);
+ var tex2d = gl.TEXTURE_2D;
+ callAndCheck(gl, function () { return gl.bindTexture(tex2d, texture); });
+ callAndCheck(gl, function () { return gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); });
+ callAndCheck(gl, function () { return gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); });
+ callAndCheck(gl, function () { return gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST); });
+ callAndCheck(gl, function () { return gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST); });
+ callAndCheck(gl, function () { return gl.texImage2D(tex2d, 0, internalFormat, width, height, 0, textureFormat, textureType, null); });
+ callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, null); });
+ return texture;
+ }
+ function getInternalFormatForFloat32MatrixTexture(textureConfig) {
+ return textureConfig.internalFormatFloat;
+ }
+ function createFloat32MatrixTexture(gl, rows, columns, textureConfig) {
+ var _a = getUnpackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
+ return createAndConfigureTexture(gl, width, height, getInternalFormatForFloat32MatrixTexture(textureConfig), textureConfig.textureFormatFloat, gl.FLOAT);
+ }
+ function getInternalFormatForFloat16MatrixTexture(textureConfig) {
+ return textureConfig.internalFormatHalfFloat;
+ }
+ function createFloat16MatrixTexture(gl, rows, columns, textureConfig) {
+ var _a = getUnpackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
+ return createAndConfigureTexture(gl, width, height, getInternalFormatForFloat16MatrixTexture(textureConfig), textureConfig.textureFormatFloat, textureConfig.textureTypeHalfFloat);
+ }
+ function getInternalFormatForUnsignedBytesMatrixTexture(textureConfig) {
+ return textureConfig.downloadTextureFormat;
+ }
+ function createUnsignedBytesMatrixTexture(gl, rows, columns, textureConfig) {
+ var _a = getUnpackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
+ return createAndConfigureTexture(gl, width, height, getInternalFormatForUnsignedBytesMatrixTexture(textureConfig), gl.RGBA, gl.UNSIGNED_BYTE);
+ }
+ function getInternalFormatForPackedMatrixTexture(textureConfig) {
+ return textureConfig.internalFormatPackedFloat;
+ }
+ function createPackedMatrixTexture(gl, rows, columns, textureConfig) {
+ var _a = getPackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
+ return createAndConfigureTexture(gl, width, height, getInternalFormatForPackedMatrixTexture(textureConfig), gl.RGBA, gl.FLOAT);
+ }
+ function getInternalFormatForFloat16PackedMatrixTexture(textureConfig) {
+ return textureConfig.internalFormatPackedHalfFloat;
+ }
+ function createFloat16PackedMatrixTexture(gl, rows, columns, textureConfig) {
+ var _a = getPackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
+ return createAndConfigureTexture(gl, width, height, getInternalFormatForFloat16PackedMatrixTexture(textureConfig), gl.RGBA, textureConfig.textureTypeHalfFloat);
+ }
+ function bindVertexProgramAttributeStreams(gl, program, vertexBuffer) {
+ var posOffset = 0; // x is the first buffer element
+ var uvOffset = 3 * 4; // uv comes after [x y z]
+ var stride = (3 * 4) + (2 * 4); // xyz + uv, each entry is 4-byte float.
+ callAndCheck(gl, function () { return gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); });
+ var success = bindVertexBufferToProgramAttribute(gl, program, 'clipSpacePos', vertexBuffer, 3, stride, posOffset);
+ return success &&
+ bindVertexBufferToProgramAttribute(gl, program, 'uv', vertexBuffer, 2, stride, uvOffset);
+ }
+ function uploadDenseMatrixToTexture(gl, texture, width, height, data, textureConfig) {
+ callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, texture); });
+ var dataForUpload, texelDataType, internalFormat;
+ if (data instanceof Uint8Array) {
+ dataForUpload = new Uint8Array(width * height * 4);
+ texelDataType = gl.UNSIGNED_BYTE;
+ internalFormat = gl.RGBA;
+ }
+ else {
+ dataForUpload = new Float32Array(width * height * 4);
+ texelDataType = gl.FLOAT;
+ internalFormat = textureConfig.internalFormatPackedFloat;
+ }
+ dataForUpload.set(data);
+ callAndCheck(gl, function () { return gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA, texelDataType, dataForUpload); });
+ callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, null); });
+ }
+ function uploadPixelDataToTexture(gl, texture, pixels) {
+ callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, texture); });
+ if (pixels.data instanceof Uint8Array) {
+ callAndCheck(gl, function () { return gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixels.width, pixels.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixels.data); });
+ }
+ else {
+ callAndCheck(gl, function () { return gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, pixels); });
+ }
+ callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, null); });
+ }
+ function createBufferFromOutputTexture(gl2, rows, columns, textureConfig) {
+ // Create and bind the buffer.
+ var buffer = gl2.createBuffer();
+ callAndCheck(gl2, function () { return gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer); });
+ // Initialize the buffer to the size of the texture in bytes.
+ var bytesPerFloat = 4;
+ var valuesPerTexel = 4;
+ var bufferSizeBytes = bytesPerFloat * valuesPerTexel * rows * columns;
+ callAndCheck(gl2, function () { return gl2.bufferData(gl2.PIXEL_PACK_BUFFER, bufferSizeBytes, gl2.STREAM_READ); });
+ // Enqueue a command on the GPU command queue to copy of texture into the
+ // buffer.
+ callAndCheck(gl2, function () { return gl2.readPixels(0, 0, columns, rows, gl2.RGBA, gl2.FLOAT, 0); });
+ callAndCheck(gl2, function () { return gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null); });
+ return buffer;
+ }
+ function downloadFloat32MatrixFromBuffer(gl, buffer, size) {
+ var gl2 = gl;
+ var downloadTarget = new Float32Array(size);
+ gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);
+ gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);
+ gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);
+ return downloadTarget;
+ }
+ function downloadByteEncodedFloatMatrixFromOutputTexture(gl, rows, columns, textureConfig) {
+ var _a = getUnpackedMatrixTextureShapeWidthHeight(rows, columns), w = _a[0], h = _a[1];
+ var numChannels = 4;
+ var downloadTarget = new Uint8Array(getUnpackedArraySizeFromMatrixSize(rows * columns, numChannels));
+ callAndCheck(gl, function () { return gl.readPixels(0, 0, w, h, textureConfig.downloadTextureFormat, gl.UNSIGNED_BYTE, downloadTarget); });
+ // By wrapping the buffer in a Float32Array, we use native browser IEEE 754
+ // decoding of the 4 bytes that back each 32 bit float.
+ return new Float32Array(downloadTarget.buffer);
+ }
+ function downloadPackedMatrixFromBuffer(gl, buffer, batch, rows, cols, physicalRows, physicalCols, textureConfig) {
+ var gl2 = gl;
+ var downloadTarget = new Float32Array(getPackedRGBAArraySizeFromMatrixShape(physicalRows, physicalCols));
+ gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);
+ gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);
+ gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);
+ return downloadTarget;
+ }
+ function downloadMatrixFromPackedOutputTexture(gl, physicalRows, physicalCols) {
+ var packedRGBA = new Float32Array(physicalRows * physicalCols * 4);
+ callAndCheck(gl, function () { return gl.readPixels(0, 0, physicalCols, physicalRows, gl.RGBA, gl.FLOAT, packedRGBA); });
+ return packedRGBA;
+ }
+
+ var gpgpu_util = {
+ __proto__: null,
+ createVertexShader: createVertexShader$1,
+ createVertexBuffer: createVertexBuffer,
+ createIndexBuffer: createIndexBuffer,
+ getInternalFormatForFloat32MatrixTexture: getInternalFormatForFloat32MatrixTexture,
+ createFloat32MatrixTexture: createFloat32MatrixTexture,
+ getInternalFormatForFloat16MatrixTexture: getInternalFormatForFloat16MatrixTexture,
+ createFloat16MatrixTexture: createFloat16MatrixTexture,
+ getInternalFormatForUnsignedBytesMatrixTexture: getInternalFormatForUnsignedBytesMatrixTexture,
+ createUnsignedBytesMatrixTexture: createUnsignedBytesMatrixTexture,
+ getInternalFormatForPackedMatrixTexture: getInternalFormatForPackedMatrixTexture,
+ createPackedMatrixTexture: createPackedMatrixTexture,
+ getInternalFormatForFloat16PackedMatrixTexture: getInternalFormatForFloat16PackedMatrixTexture,
+ createFloat16PackedMatrixTexture: createFloat16PackedMatrixTexture,
+ bindVertexProgramAttributeStreams: bindVertexProgramAttributeStreams,
+ uploadDenseMatrixToTexture: uploadDenseMatrixToTexture,
+ uploadPixelDataToTexture: uploadPixelDataToTexture,
+ createBufferFromOutputTexture: createBufferFromOutputTexture,
+ downloadFloat32MatrixFromBuffer: downloadFloat32MatrixFromBuffer,
+ downloadByteEncodedFloatMatrixFromOutputTexture: downloadByteEncodedFloatMatrixFromOutputTexture,
+ downloadPackedMatrixFromBuffer: downloadPackedMatrixFromBuffer,
+ downloadMatrixFromPackedOutputTexture: downloadMatrixFromPackedOutputTexture
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var GPGPUContext = /** @class */ (function () {
+ function GPGPUContext(gl) {
+ this.outputTexture = null;
+ this.program = null;
+ this.disposed = false;
+ this.vertexAttrsAreBound = false;
+ this.itemsToPoll = [];
+ var glVersion = tf.env().getNumber('WEBGL_VERSION');
+ if (gl != null) {
+ this.gl = gl;
+ setWebGLContext(glVersion, gl);
+ }
+ else {
+ this.gl = getWebGLContext(glVersion);
+ }
+ // WebGL 2.0 enables texture floats without an extension.
+ var COLOR_BUFFER_FLOAT = 'WEBGL_color_buffer_float';
+ var COLOR_BUFFER_HALF_FLOAT = 'EXT_color_buffer_half_float';
+ if (tf.env().getNumber('WEBGL_VERSION') === 1) {
+ var TEXTURE_FLOAT = 'OES_texture_float';
+ var TEXTURE_HALF_FLOAT = 'OES_texture_half_float';
+ this.textureFloatExtension =
+ getExtensionOrThrow(this.gl, TEXTURE_FLOAT);
+ if (hasExtension(this.gl, TEXTURE_HALF_FLOAT)) {
+ this.textureHalfFloatExtension =
+ getExtensionOrThrow(this.gl, TEXTURE_HALF_FLOAT);
+ }
+ else if (tf.env().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.');
+ }
+ this.colorBufferFloatExtension = this.gl.getExtension(COLOR_BUFFER_FLOAT);
+ if (hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {
+ this.colorBufferHalfFloatExtension =
+ getExtensionOrThrow(this.gl, COLOR_BUFFER_HALF_FLOAT);
+ }
+ else if (tf.env().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 {
+ COLOR_BUFFER_FLOAT = 'EXT_color_buffer_float';
+ if (hasExtension(this.gl, COLOR_BUFFER_FLOAT)) {
+ this.colorBufferFloatExtension =
+ this.gl.getExtension(COLOR_BUFFER_FLOAT);
+ }
+ else if (hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {
+ this.colorBufferHalfFloatExtension =
+ this.gl.getExtension(COLOR_BUFFER_HALF_FLOAT);
+ }
+ else {
+ throw new Error('GL context does not support color renderable floats');
+ }
+ }
+ this.vertexBuffer = createVertexBuffer(this.gl);
+ this.indexBuffer = createIndexBuffer(this.gl);
+ this.framebuffer = createFramebuffer(this.gl);
+ this.textureConfig =
+ getTextureConfig(this.gl, this.textureHalfFloatExtension);
+ }
+ Object.defineProperty(GPGPUContext.prototype, "debug", {
+ get: function () {
+ return tf.env().getBool('DEBUG');
+ },
+ enumerable: true,
+ configurable: true
+ });
+ GPGPUContext.prototype.dispose = function () {
+ var _this = this;
+ if (this.disposed) {
+ return;
+ }
+ if (this.program != null) {
+ console.warn('Disposing a GPGPUContext that still has a bound WebGLProgram.' +
+ ' This is probably a resource leak, delete the program with ' +
+ 'GPGPUContext.deleteProgram before disposing.');
+ }
+ if (this.outputTexture != null) {
+ console.warn('Disposing a GPGPUContext that still has a bound output matrix ' +
+ 'texture. This is probably a resource leak, delete the output ' +
+ 'matrix texture with GPGPUContext.deleteMatrixTexture before ' +
+ 'disposing.');
+ }
+ var gl = this.gl;
+ callAndCheck(gl, function () { return gl.finish(); });
+ callAndCheck(gl, function () { return gl.bindFramebuffer(gl.FRAMEBUFFER, null); });
+ callAndCheck(gl, function () { return gl.deleteFramebuffer(_this.framebuffer); });
+ callAndCheck(gl, function () { return gl.bindBuffer(gl.ARRAY_BUFFER, null); });
+ callAndCheck(gl, function () { return gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); });
+ callAndCheck(gl, function () { return gl.deleteBuffer(_this.indexBuffer); });
+ this.disposed = true;
+ };
+ GPGPUContext.prototype.createFloat32MatrixTexture = function (rows, columns) {
+ this.throwIfDisposed();
+ return createFloat32MatrixTexture(this.gl, rows, columns, this.textureConfig);
+ };
+ GPGPUContext.prototype.createFloat16MatrixTexture = function (rows, columns) {
+ this.throwIfDisposed();
+ return createFloat16MatrixTexture(this.gl, rows, columns, this.textureConfig);
+ };
+ GPGPUContext.prototype.createUnsignedBytesMatrixTexture = function (rows, columns) {
+ this.throwIfDisposed();
+ return createUnsignedBytesMatrixTexture(this.gl, rows, columns, this.textureConfig);
+ };
+ GPGPUContext.prototype.uploadPixelDataToTexture = function (texture, pixels) {
+ this.throwIfDisposed();
+ uploadPixelDataToTexture(this.gl, texture, pixels);
+ };
+ GPGPUContext.prototype.uploadDenseMatrixToTexture = function (texture, width, height, data) {
+ this.throwIfDisposed();
+ uploadDenseMatrixToTexture(this.gl, texture, width, height, data, this.textureConfig);
+ };
+ GPGPUContext.prototype.createFloat16PackedMatrixTexture = function (rows, columns) {
+ this.throwIfDisposed();
+ return createFloat16PackedMatrixTexture(this.gl, rows, columns, this.textureConfig);
+ };
+ GPGPUContext.prototype.createPackedMatrixTexture = function (rows, columns) {
+ this.throwIfDisposed();
+ return createPackedMatrixTexture(this.gl, rows, columns, this.textureConfig);
+ };
+ GPGPUContext.prototype.deleteMatrixTexture = function (texture) {
+ var _this = this;
+ this.throwIfDisposed();
+ if (this.outputTexture === texture) {
+ unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);
+ this.outputTexture = null;
+ }
+ callAndCheck(this.gl, function () { return _this.gl.deleteTexture(texture); });
+ };
+ GPGPUContext.prototype.downloadByteEncodedFloatMatrixFromOutputTexture = function (texture, rows, columns) {
+ var _this = this;
+ return this.downloadMatrixDriver(texture, function () { return downloadByteEncodedFloatMatrixFromOutputTexture(_this.gl, rows, columns, _this.textureConfig); });
+ };
+ GPGPUContext.prototype.downloadPackedMatrixFromBuffer = function (buffer, batch, rows, columns, physicalRows, physicalCols) {
+ return downloadPackedMatrixFromBuffer(this.gl, buffer, batch, rows, columns, physicalRows, physicalCols, this.textureConfig);
+ };
+ GPGPUContext.prototype.downloadFloat32MatrixFromBuffer = function (buffer, size) {
+ return downloadFloat32MatrixFromBuffer(this.gl, buffer, size);
+ };
+ GPGPUContext.prototype.createBufferFromTexture = function (texture, rows, columns) {
+ this.bindTextureToFrameBuffer(texture);
+ var result = createBufferFromOutputTexture(this.gl, rows, columns, this.textureConfig);
+ this.unbindTextureToFrameBuffer();
+ return result;
+ };
+ GPGPUContext.prototype.createAndWaitForFence = function () {
+ var fenceContext = this.createFence(this.gl);
+ return this.pollFence(fenceContext);
+ };
+ GPGPUContext.prototype.createFence = function (gl) {
+ var _this = this;
+ var query;
+ var isFencePassed;
+ if (tf.env().getBool('WEBGL_FENCE_API_ENABLED')) {
+ var gl2_1 = gl;
+ var sync_1 = gl2_1.fenceSync(gl2_1.SYNC_GPU_COMMANDS_COMPLETE, 0);
+ gl.flush();
+ isFencePassed = function () {
+ var status = gl2_1.clientWaitSync(sync_1, 0, 0);
+ return status === gl2_1.ALREADY_SIGNALED ||
+ status === gl2_1.CONDITION_SATISFIED;
+ };
+ query = sync_1;
+ }
+ else if (tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0) {
+ query = this.beginQuery();
+ this.endQuery();
+ isFencePassed = function () { return _this.isQueryAvailable(query, tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION')); };
+ }
+ else {
+ // If we have no way to fence, return true immediately. This will fire in
+ // WebGL 1.0 when there is no disjoint query timer. In this case, because
+ // the fence passes immediately, we'll immediately ask for a download of
+ // the texture, which will cause the UI thread to hang.
+ isFencePassed = function () { return true; };
+ }
+ return { query: query, isFencePassed: isFencePassed };
+ };
+ GPGPUContext.prototype.downloadMatrixFromPackedTexture = function (texture, physicalRows, physicalCols) {
+ var _this = this;
+ return this.downloadMatrixDriver(texture, function () { return downloadMatrixFromPackedOutputTexture(_this.gl, physicalRows, physicalCols); });
+ };
+ GPGPUContext.prototype.createProgram = function (fragmentShaderSource) {
+ var _this = this;
+ this.throwIfDisposed();
+ var gl = this.gl;
+ var fragmentShader = createFragmentShader(gl, fragmentShaderSource);
+ if (this.vertexShader == null) {
+ this.vertexShader = createVertexShader$1(gl);
+ }
+ var program = createProgram(gl);
+ callAndCheck(gl, function () { return gl.attachShader(program, _this.vertexShader); });
+ callAndCheck(gl, function () { return gl.attachShader(program, fragmentShader); });
+ linkProgram(gl, program);
+ if (this.debug) {
+ validateProgram(gl, program);
+ }
+ if (!this.vertexAttrsAreBound) {
+ this.setProgram(program);
+ this.vertexAttrsAreBound = bindVertexProgramAttributeStreams(gl, this.program, this.vertexBuffer);
+ }
+ return program;
+ };
+ GPGPUContext.prototype.deleteProgram = function (program) {
+ var _this = this;
+ this.throwIfDisposed();
+ if (program === this.program) {
+ this.program = null;
+ }
+ if (program != null) {
+ callAndCheck(this.gl, function () { return _this.gl.deleteProgram(program); });
+ }
+ };
+ GPGPUContext.prototype.setProgram = function (program) {
+ var _this = this;
+ this.throwIfDisposed();
+ this.program = program;
+ if ((this.program != null) && this.debug) {
+ validateProgram(this.gl, this.program);
+ }
+ callAndCheck(this.gl, function () { return _this.gl.useProgram(program); });
+ };
+ GPGPUContext.prototype.getUniformLocation = function (program, uniformName, shouldThrow) {
+ if (shouldThrow === void 0) { shouldThrow = true; }
+ this.throwIfDisposed();
+ if (shouldThrow) {
+ return getProgramUniformLocationOrThrow(this.gl, program, uniformName);
+ }
+ else {
+ return getProgramUniformLocation(this.gl, program, uniformName);
+ }
+ };
+ GPGPUContext.prototype.getAttributeLocation = function (program, attribute) {
+ var _this = this;
+ this.throwIfDisposed();
+ return callAndCheck(this.gl, function () { return _this.gl.getAttribLocation(program, attribute); });
+ };
+ GPGPUContext.prototype.getUniformLocationNoThrow = function (program, uniformName) {
+ this.throwIfDisposed();
+ return this.gl.getUniformLocation(program, uniformName);
+ };
+ GPGPUContext.prototype.setInputMatrixTexture = function (inputMatrixTexture, uniformLocation, textureUnit) {
+ this.throwIfDisposed();
+ this.throwIfNoProgram();
+ bindTextureToProgramUniformSampler(this.gl, inputMatrixTexture, uniformLocation, textureUnit);
+ };
+ GPGPUContext.prototype.setOutputMatrixTexture = function (outputMatrixTexture, rows, columns) {
+ this.setOutputMatrixTextureDriver(outputMatrixTexture, columns, rows);
+ };
+ GPGPUContext.prototype.setOutputPackedMatrixTexture = function (outputPackedMatrixTexture, rows, columns) {
+ this.throwIfDisposed();
+ var _a = getPackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
+ this.setOutputMatrixTextureDriver(outputPackedMatrixTexture, width, height);
+ };
+ GPGPUContext.prototype.setOutputMatrixWriteRegion = function (startRow, numRows, startColumn, numColumns) {
+ this.setOutputMatrixWriteRegionDriver(startColumn, startRow, numColumns, numRows);
+ };
+ GPGPUContext.prototype.setOutputPackedMatrixWriteRegion = function (startRow, numRows, startColumn, numColumns) {
+ throw new Error('setOutputPackedMatrixWriteRegion not implemented.');
+ };
+ GPGPUContext.prototype.debugValidate = function () {
+ if (this.program != null) {
+ validateProgram(this.gl, this.program);
+ }
+ validateFramebuffer(this.gl);
+ };
+ GPGPUContext.prototype.executeProgram = function () {
+ this.throwIfDisposed();
+ this.throwIfNoProgram();
+ var gl = this.gl;
+ if (this.debug) {
+ this.debugValidate();
+ }
+ callAndCheck(gl, function () { return gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0); });
+ };
+ GPGPUContext.prototype.blockUntilAllProgramsCompleted = function () {
+ var _this = this;
+ this.throwIfDisposed();
+ callAndCheck(this.gl, function () { return _this.gl.finish(); });
+ };
+ GPGPUContext.prototype.getQueryTimerExtension = function () {
+ if (this.disjointQueryTimerExtension == null) {
+ this.disjointQueryTimerExtension =
+ getExtensionOrThrow(this.gl, tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2 ?
+ 'EXT_disjoint_timer_query_webgl2' :
+ 'EXT_disjoint_timer_query');
+ }
+ return this.disjointQueryTimerExtension;
+ };
+ GPGPUContext.prototype.getQueryTimerExtensionWebGL2 = function () {
+ return this.getQueryTimerExtension();
+ };
+ GPGPUContext.prototype.getQueryTimerExtensionWebGL1 = function () {
+ return this.getQueryTimerExtension();
+ };
+ GPGPUContext.prototype.beginQuery = function () {
+ if (tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2) {
+ var gl2 = this.gl;
+ var ext_1 = this.getQueryTimerExtensionWebGL2();
+ var query_1 = gl2.createQuery();
+ gl2.beginQuery(ext_1.TIME_ELAPSED_EXT, query_1);
+ return query_1;
+ }
+ var ext = this.getQueryTimerExtensionWebGL1();
+ var query = ext.createQueryEXT();
+ ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, query);
+ return query;
+ };
+ GPGPUContext.prototype.endQuery = function () {
+ if (tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2) {
+ var gl2 = this.gl;
+ var ext_2 = this.getQueryTimerExtensionWebGL2();
+ gl2.endQuery(ext_2.TIME_ELAPSED_EXT);
+ return;
+ }
+ var ext = this.getQueryTimerExtensionWebGL1();
+ ext.endQueryEXT(ext.TIME_ELAPSED_EXT);
+ };
+ GPGPUContext.prototype.waitForQueryAndGetTime = function (query) {
+ return __awaiter(this, void 0, void 0, function () {
+ var _this = this;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0: return [4 /*yield*/, tf.util.repeatedTry(function () { return _this.disposed || // while testing contexts are created / disposed
+ // in rapid succession, so without this check we
+ // may poll for the query timer indefinitely
+ _this.isQueryAvailable(query, tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION')); })];
+ case 1:
+ _a.sent();
+ return [2 /*return*/, this.getQueryTime(query, tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION'))];
+ }
+ });
+ });
+ };
+ GPGPUContext.prototype.getQueryTime = function (query, queryTimerVersion) {
+ if (queryTimerVersion === 0) {
+ return null;
+ }
+ if (queryTimerVersion === 2) {
+ var gl2 = this.gl;
+ var timeElapsedNanos = gl2.getQueryParameter(query, gl2.QUERY_RESULT);
+ // Return milliseconds.
+ return timeElapsedNanos / 1000000;
+ }
+ else {
+ var ext = this.getQueryTimerExtensionWebGL1();
+ var timeElapsedNanos = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_EXT);
+ // Return milliseconds.
+ return timeElapsedNanos / 1000000;
+ }
+ };
+ GPGPUContext.prototype.isQueryAvailable = function (query, queryTimerVersion) {
+ if (queryTimerVersion === 0) {
+ return true;
+ }
+ if (queryTimerVersion === 2) {
+ var gl2 = this.gl;
+ var ext = this.getQueryTimerExtensionWebGL2();
+ var available = gl2.getQueryParameter(query, gl2.QUERY_RESULT_AVAILABLE);
+ if (this.disjoint == null) {
+ this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);
+ }
+ return available && !this.disjoint;
+ }
+ else {
+ var ext = this.getQueryTimerExtensionWebGL1();
+ var available = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_AVAILABLE_EXT);
+ if (this.disjoint == null) {
+ this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);
+ }
+ return available && !this.disjoint;
+ }
+ };
+ GPGPUContext.prototype.pollFence = function (fenceContext) {
+ var _this = this;
+ return new Promise(function (resolve) {
+ _this.addItemToPoll(function () { return fenceContext.isFencePassed(); }, function () { return resolve(); });
+ });
+ };
+ GPGPUContext.prototype.pollItems = function () {
+ // Find the last query that has finished.
+ var index = linearSearchLastTrue(this.itemsToPoll.map(function (x) { return x.isDoneFn; }));
+ for (var i = 0; i <= index; ++i) {
+ var resolveFn = this.itemsToPoll[i].resolveFn;
+ resolveFn();
+ }
+ this.itemsToPoll = this.itemsToPoll.slice(index + 1);
+ };
+ GPGPUContext.prototype.addItemToPoll = function (isDoneFn, resolveFn) {
+ var _this = this;
+ this.itemsToPoll.push({ isDoneFn: isDoneFn, resolveFn: resolveFn });
+ if (this.itemsToPoll.length > 1) {
+ // We already have a running loop that polls.
+ return;
+ }
+ // Start a new loop that polls.
+ tf.util.repeatedTry(function () {
+ _this.pollItems();
+ // End the loop if no more items to poll.
+ return _this.itemsToPoll.length === 0;
+ });
+ };
+ GPGPUContext.prototype.bindTextureToFrameBuffer = function (texture) {
+ this.throwIfDisposed();
+ bindColorTextureToFramebuffer(this.gl, texture, this.framebuffer);
+ if (this.debug) {
+ validateFramebuffer(this.gl);
+ }
+ };
+ GPGPUContext.prototype.unbindTextureToFrameBuffer = function () {
+ if (this.outputTexture != null) {
+ bindColorTextureToFramebuffer(this.gl, this.outputTexture, this.framebuffer);
+ if (this.debug) {
+ validateFramebuffer(this.gl);
+ }
+ }
+ else {
+ unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);
+ }
+ };
+ GPGPUContext.prototype.downloadMatrixDriver = function (texture, downloadAndDecode) {
+ this.bindTextureToFrameBuffer(texture);
+ var result = downloadAndDecode();
+ this.unbindTextureToFrameBuffer();
+ return result;
+ };
+ GPGPUContext.prototype.setOutputMatrixTextureDriver = function (outputMatrixTextureMaybePacked, width, height) {
+ this.throwIfDisposed();
+ var gl = this.gl;
+ bindColorTextureToFramebuffer(gl, outputMatrixTextureMaybePacked, this.framebuffer);
+ if (this.debug) {
+ validateFramebuffer(gl);
+ }
+ this.outputTexture = outputMatrixTextureMaybePacked;
+ callAndCheck(gl, function () { return gl.viewport(0, 0, width, height); });
+ callAndCheck(gl, function () { return gl.scissor(0, 0, width, height); });
+ };
+ GPGPUContext.prototype.setOutputMatrixWriteRegionDriver = function (x, y, width, height) {
+ var _this = this;
+ this.throwIfDisposed();
+ callAndCheck(this.gl, function () { return _this.gl.scissor(x, y, width, height); });
+ };
+ GPGPUContext.prototype.throwIfDisposed = function () {
+ if (this.disposed) {
+ throw new Error('Attempted to use disposed GPGPUContext.');
+ }
+ };
+ GPGPUContext.prototype.throwIfNoProgram = function () {
+ if (this.program == null) {
+ throw new Error('No GPU program is currently set.');
+ }
+ };
+ return GPGPUContext;
+ }());
+ /**
+ * Finds the index of the last true element using linear search.
+ * Note: We can't do binary search because Chrome expects us to explicitly
+ * test all fences before download:
+ * https://github.com/tensorflow/tfjs/issues/1145
+ */
+ function linearSearchLastTrue(arr) {
+ var i = 0;
+ for (; i < arr.length; ++i) {
+ var isDone = arr[i]();
+ if (!isDone) {
+ break;
+ }
+ }
+ return i - 1;
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var getBroadcastDims = tf.backend_util.getBroadcastDims;
+ function makeShader(inputsInfo, outputShape, userCode, usesPackedTextures) {
+ var prefixSnippets = [];
+ inputsInfo.forEach(function (x) {
+ var size = tf.util.sizeFromShape(x.shapeInfo.logicalShape);
+ // Snippet when we decided to upload the values as uniform.
+ if (x.shapeInfo.isUniform) {
+ prefixSnippets.push("uniform float " + x.name + (size > 1 ? "[" + size + "]" : '') + ";");
+ }
+ else {
+ prefixSnippets.push("uniform sampler2D " + x.name + ";");
+ prefixSnippets.push("uniform int offset" + x.name + ";");
+ }
+ });
+ var inputPrefixSnippet = prefixSnippets.join('\n');
+ var inputSamplingSnippet = inputsInfo
+ .map(function (x) { return getInputSamplingSnippet(x, outputShape, usesPackedTextures); })
+ .join('\n');
+ var outTexShape = outputShape.texShape;
+ var glsl = getGlslDifferences();
+ var floatTextureSampleSnippet = getFloatTextureSampleSnippet(glsl);
+ var outputSamplingSnippet;
+ var floatTextureSetOutputSnippet;
+ var shaderPrefix = getShaderPrefix(glsl);
+ if (outputShape.isPacked) {
+ outputSamplingSnippet =
+ getPackedOutputSamplingSnippet(outputShape.logicalShape, outTexShape);
+ floatTextureSetOutputSnippet = getFloatTextureSetRGBASnippet(glsl);
+ }
+ else {
+ outputSamplingSnippet =
+ getOutputSamplingSnippet(outputShape.logicalShape, outTexShape);
+ floatTextureSetOutputSnippet = getFloatTextureSetRSnippet(glsl);
+ }
+ if (usesPackedTextures) {
+ shaderPrefix += SHADER_PACKED_PREFIX;
+ }
+ var source = [
+ shaderPrefix, floatTextureSampleSnippet, floatTextureSetOutputSnippet,
+ inputPrefixSnippet, outputSamplingSnippet, inputSamplingSnippet, userCode
+ ].join('\n');
+ return source;
+ }
+ function getSamplerFromInInfo(inInfo) {
+ var shape = inInfo.shapeInfo.logicalShape;
+ switch (shape.length) {
+ case 0:
+ return getSamplerScalar(inInfo);
+ case 1:
+ return getSampler1D(inInfo);
+ case 2:
+ return getSampler2D(inInfo);
+ case 3:
+ return getSampler3D(inInfo);
+ case 4:
+ return getSampler4D(inInfo);
+ case 5:
+ return getSampler5D(inInfo);
+ case 6:
+ return getSampler6D(inInfo);
+ default:
+ throw new Error(shape.length + "-D input sampling" +
+ " is not yet supported");
+ }
+ }
+ function getPackedSamplerFromInInfo(inInfo) {
+ var shape = inInfo.shapeInfo.logicalShape;
+ switch (shape.length) {
+ case 0:
+ return getPackedSamplerScalar(inInfo);
+ case 1:
+ return getPackedSampler1D(inInfo);
+ case 2:
+ return getPackedSampler2D(inInfo);
+ case 3:
+ return getPackedSampler3D(inInfo);
+ default:
+ return getPackedSamplerND(inInfo);
+ }
+ }
+ function getInputSamplingSnippet(inInfo, outShapeInfo, usesPackedTextures) {
+ if (usesPackedTextures === void 0) { usesPackedTextures = false; }
+ var res = '';
+ if (usesPackedTextures) {
+ res += getPackedSamplerFromInInfo(inInfo);
+ }
+ else {
+ res += getSamplerFromInInfo(inInfo);
+ }
+ var inShape = inInfo.shapeInfo.logicalShape;
+ var outShape = outShapeInfo.logicalShape;
+ if (inShape.length <= outShape.length) {
+ if (usesPackedTextures) {
+ res += getPackedSamplerAtOutputCoords(inInfo, outShapeInfo);
+ }
+ else {
+ res += getSamplerAtOutputCoords(inInfo, outShapeInfo);
+ }
+ }
+ return res;
+ }
+ function getPackedOutputSamplingSnippet(outShape, outTexShape) {
+ switch (outShape.length) {
+ case 0:
+ return getOutputScalarCoords();
+ case 1:
+ return getOutputPacked1DCoords(outShape, outTexShape);
+ case 2:
+ return getOutputPacked2DCoords(outShape, outTexShape);
+ case 3:
+ return getOutputPacked3DCoords(outShape, outTexShape);
+ default:
+ return getOutputPackedNDCoords(outShape, outTexShape);
+ }
+ }
+ function getOutputSamplingSnippet(outShape, outTexShape) {
+ switch (outShape.length) {
+ case 0:
+ return getOutputScalarCoords();
+ case 1:
+ return getOutput1DCoords(outShape, outTexShape);
+ case 2:
+ return getOutput2DCoords(outShape, outTexShape);
+ case 3:
+ return getOutput3DCoords(outShape, outTexShape);
+ case 4:
+ return getOutput4DCoords(outShape, outTexShape);
+ case 5:
+ return getOutput5DCoords(outShape, outTexShape);
+ case 6:
+ return getOutput6DCoords(outShape, outTexShape);
+ default:
+ throw new Error(outShape.length + "-D output sampling is not yet supported");
+ }
+ }
+ function getFloatTextureSampleSnippet(glsl) {
+ return "\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return " + glsl.texture2D + "(textureSampler, uv).r;\n }\n ";
+ }
+ function getFloatTextureSetRSnippet(glsl) {
+ return "\n void setOutput(float val) {\n " + glsl.output + " = vec4(val, 0, 0, 0);\n }\n ";
+ }
+ function getFloatTextureSetRGBASnippet(glsl) {
+ return "\n void setOutput(vec4 val) {\n " + glsl.output + " = val;\n }\n ";
+ }
+ function getShaderPrefix(glsl) {
+ var SHADER_PREFIX = glsl.version + "\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n " + glsl.varyingFs + " vec2 resultUV;\n " + glsl.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 " + glsl.defineSpecialNaN + "\n " + glsl.defineSpecialInf + "\n " + glsl.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 " + SAMPLE_1D_SNIPPET + "\n " + SAMPLE_2D_SNIPPET + "\n " + SAMPLE_3D_SNIPPET + "\n ";
+ return SHADER_PREFIX;
+ }
+ var SAMPLE_1D_SNIPPET = "\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";
+ var SAMPLE_2D_SNIPPET = "\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";
+ var SAMPLE_3D_SNIPPET = "\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";
+ var SHADER_PACKED_PREFIX = "\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";
+ function getOutputScalarCoords() {
+ return "\n int getOutputCoords() {\n return 0;\n }\n ";
+ }
+ function getOutputPacked1DCoords(shape, texShape) {
+ var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
+ if (packedTexShape[0] === 1) {
+ return "\n int getOutputCoords() {\n return 2 * int(resultUV.x * " + packedTexShape[1] + ".0);\n }\n ";
+ }
+ if (packedTexShape[1] === 1) {
+ return "\n int getOutputCoords() {\n return 2 * int(resultUV.y * " + packedTexShape[0] + ".0);\n }\n ";
+ }
+ return "\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + packedTexShape[0] + ", " + packedTexShape[1] + "));\n return 2 * (resTexRC.x * " + packedTexShape[1] + " + resTexRC.y);\n }\n ";
+ }
+ function getOutput1DCoords(shape, texShape) {
+ if (texShape[0] === 1) {
+ return "\n int getOutputCoords() {\n return int(resultUV.x * " + texShape[1] + ".0);\n }\n ";
+ }
+ if (texShape[1] === 1) {
+ return "\n int getOutputCoords() {\n return int(resultUV.y * " + texShape[0] + ".0);\n }\n ";
+ }
+ return "\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n return resTexRC.x * " + texShape[1] + " + resTexRC.y;\n }\n ";
+ }
+ function getOutputPacked3DCoords(shape, texShape) {
+ var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
+ var texelsInLogicalRow = Math.ceil(shape[2] / 2);
+ var texelsInBatch = texelsInLogicalRow * Math.ceil(shape[1] / 2);
+ return "\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + packedTexShape[0] + ", " + packedTexShape[1] + "));\n int index = resTexRC.x * " + packedTexShape[1] + " + resTexRC.y;\n\n int b = index / " + texelsInBatch + ";\n index -= b * " + texelsInBatch + ";\n\n int r = 2 * (index / " + texelsInLogicalRow + ");\n int c = imod(index, " + texelsInLogicalRow + ") * 2;\n\n return ivec3(b, r, c);\n }\n ";
+ }
+ function getOutput3DCoords(shape, texShape) {
+ var coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd'], shape);
+ return "\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n " + coordsFromIndexSnippet + "\n return ivec3(r, c, d);\n }\n ";
+ }
+ function getOutputPackedNDCoords(shape, texShape) {
+ var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
+ var texelsInLogicalRow = Math.ceil(shape[shape.length - 1] / 2);
+ var texelsInBatch = texelsInLogicalRow * Math.ceil(shape[shape.length - 2] / 2);
+ var texelsInBatchN = texelsInBatch;
+ var batches = "";
+ var coords = 'b, r, c';
+ for (var b = 2; b < shape.length - 1; b++) {
+ texelsInBatchN *= shape[shape.length - b - 1];
+ batches = "\n int b" + b + " = index / " + texelsInBatchN + ";\n index -= b" + b + " * " + texelsInBatchN + ";\n " + batches;
+ coords = "b" + b + ", " + coords;
+ }
+ return "\n ivec" + shape.length + " getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + packedTexShape[0] + ", " + packedTexShape[1] + "));\n int index = resTexRC.x * " + packedTexShape[1] + " + resTexRC.y;\n\n " + batches + "\n\n int b = index / " + texelsInBatch + ";\n index -= b * " + texelsInBatch + ";\n\n int r = 2 * (index / " + texelsInLogicalRow + ");\n int c = imod(index, " + texelsInLogicalRow + ") * 2;\n\n return ivec" + shape.length + "(" + coords + ");\n }\n ";
+ }
+ function getOutput4DCoords(shape, texShape) {
+ var coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd', 'd2'], shape);
+ return "\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n " + coordsFromIndexSnippet + "\n return ivec4(r, c, d, d2);\n }\n ";
+ }
+ function getOutput5DCoords(shape, texShape) {
+ var coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd', 'd2', 'd3'], shape);
+ return "\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(" + texShape[0] + ",\n " + texShape[1] + "));\n\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n\n " + coordsFromIndexSnippet + "\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n ";
+ }
+ function getOutput6DCoords(shape, texShape) {
+ var coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd', 'd2', 'd3', 'd4'], shape);
+ return "\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n\n " + coordsFromIndexSnippet + "\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n ";
+ }
+ function getOutputPacked2DCoords(shape, texShape) {
+ var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
+ if (tf.util.arraysEqual(shape, texShape)) {
+ return "\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(" + packedTexShape[0] + ", " + packedTexShape[1] + "));\n }\n ";
+ }
+ // texels needed to accommodate a logical row
+ var texelsInLogicalRow = Math.ceil(shape[1] / 2);
+ /**
+ * getOutputCoords
+ *
+ * resTexRC: The rows and columns of the texels. If you move over one
+ * texel to the right in the packed texture, you are moving over one column
+ * (not two).
+ *
+ * index: The texel index
+ */
+ return "\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + packedTexShape[0] + ", " + packedTexShape[1] + "));\n\n int index = resTexRC.x * " + packedTexShape[1] + " + resTexRC.y;\n int r = 2 * (index / " + texelsInLogicalRow + ");\n int c = imod(index, " + texelsInLogicalRow + ") * 2;\n\n return ivec2(r, c);\n }\n ";
+ }
+ function getOutput2DCoords(shape, texShape) {
+ if (tf.util.arraysEqual(shape, texShape)) {
+ return "\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(" + texShape[0] + ", " + texShape[1] + "));\n }\n ";
+ }
+ if (shape[1] === 1) {
+ return "\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n return ivec2(index, 0);\n }\n ";
+ }
+ if (shape[0] === 1) {
+ return "\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n return ivec2(0, index);\n }\n ";
+ }
+ return "\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n int r = index / " + shape[1] + ";\n int c = index - r * " + shape[1] + ";\n return ivec2(r, c);\n }\n ";
+ }
+ function getFlatOffsetUniformName(texName) {
+ return "offset" + texName;
+ }
+ function getPackedSamplerScalar(inputInfo) {
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var glsl = getGlslDifferences();
+ return "\n vec4 " + funcName + "() {\n return " + glsl.texture2D + "(" + texName + ", halfCR);\n }\n ";
+ }
+ function getSamplerScalar(inputInfo) {
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ if (inputInfo.shapeInfo.isUniform) {
+ return "float " + funcName + "() {return " + texName + ";}";
+ }
+ var _a = inputInfo.shapeInfo.texShape, texNumR = _a[0], texNumC = _a[1];
+ if (texNumR === 1 && texNumC === 1) {
+ return "\n float " + funcName + "() {\n return sampleTexture(" + texName + ", halfCR);\n }\n ";
+ }
+ var _b = inputInfo.shapeInfo.texShape, tNumR = _b[0], tNumC = _b[1];
+ var offset = getFlatOffsetUniformName(texName);
+ return "\n float " + funcName + "() {\n vec2 uv = uvFromFlat(" + tNumR + ", " + tNumC + ", " + offset + ");\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ function getPackedSampler1D(inputInfo) {
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var texShape = inputInfo.shapeInfo.texShape;
+ var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
+ var glsl = getGlslDifferences();
+ return "\n vec4 " + funcName + "(int index) {\n vec2 uv = packedUVfrom1D(\n " + packedTexShape[0] + ", " + packedTexShape[1] + ", index);\n return " + glsl.texture2D + "(" + texName + ", uv);\n }\n ";
+ }
+ function getSampler1D(inputInfo) {
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ if (inputInfo.shapeInfo.isUniform) {
+ // Uniform arrays will be less than 65505 (no risk of float16 overflow).
+ return "\n float " + funcName + "(int index) {\n " + getUniformSampler(inputInfo) + "\n }\n ";
+ }
+ var texShape = inputInfo.shapeInfo.texShape;
+ var tNumR = texShape[0];
+ var tNumC = texShape[1];
+ if (tNumC === 1 && tNumR === 1) {
+ return "\n float " + funcName + "(int index) {\n return sampleTexture(" + texName + ", halfCR);\n }\n ";
+ }
+ var offset = getFlatOffsetUniformName(texName);
+ if (tNumC === 1) {
+ return "\n float " + funcName + "(int index) {\n vec2 uv = vec2(0.5, (float(index + " + offset + ") + 0.5) / " + tNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ if (tNumR === 1) {
+ return "\n float " + funcName + "(int index) {\n vec2 uv = vec2((float(index + " + offset + ") + 0.5) / " + tNumC + ".0, 0.5);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ return "\n float " + funcName + "(int index) {\n vec2 uv = uvFromFlat(" + tNumR + ", " + tNumC + ", index + " + offset + ");\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ function getPackedSampler2D(inputInfo) {
+ var shape = inputInfo.shapeInfo.logicalShape;
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var texShape = inputInfo.shapeInfo.texShape;
+ var texNumR = texShape[0];
+ var texNumC = texShape[1];
+ var glsl = getGlslDifferences();
+ if (texShape != null && tf.util.arraysEqual(shape, texShape)) {
+ return "\n vec4 " + funcName + "(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(" + texNumC + ".0, " + texNumR + ".0);\n\n return " + glsl.texture2D + "(" + texName + ", uv);\n }\n ";
+ }
+ var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
+ var valuesPerRow = Math.ceil(shape[1] / 2);
+ return "\n vec4 " + funcName + "(int row, int col) {\n vec2 uv = packedUVfrom2D(" + valuesPerRow + ", " + packedTexShape[0] + ", " + packedTexShape[1] + ", row, col);\n return " + glsl.texture2D + "(" + texName + ", uv);\n }\n ";
+ }
+ function getSampler2D(inputInfo) {
+ var shape = inputInfo.shapeInfo.logicalShape;
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var texShape = inputInfo.shapeInfo.texShape;
+ if (texShape != null && tf.util.arraysEqual(shape, texShape)) {
+ var texNumR_1 = texShape[0];
+ var texNumC_1 = texShape[1];
+ return "\n float " + funcName + "(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(" + texNumC_1 + ".0, " + texNumR_1 + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ var _a = tf.util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
+ var squeezedShape = newShape;
+ if (squeezedShape.length < shape.length) {
+ var newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
+ var params = ['row', 'col'];
+ return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
+ }
+ if (inputInfo.shapeInfo.isUniform) {
+ // Uniform arrays will be less than 65505 (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col) {\n int index = round(dot(vec2(row, col), vec2(" + shape[1] + ", 1)));\n " + getUniformSampler(inputInfo) + "\n }\n ";
+ }
+ var texNumR = texShape[0];
+ var texNumC = texShape[1];
+ var offset = getFlatOffsetUniformName(texName);
+ if (texNumC === 1) {
+ // index is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col) {\n float index = dot(vec3(row, col, " + offset + "), vec3(" + shape[1] + ", 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ if (texNumR === 1) {
+ // index is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col) {\n float index = dot(vec3(row, col, " + offset + "), vec3(" + shape[1] + ", 1, 1));\n vec2 uv = vec2((index + 0.5) / " + texNumC + ".0, 0.5);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ return "\n float " + funcName + "(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * " + shape[1] + " + col + " + offset + ";\n vec2 uv = uvFromFlat(" + texNumR + ", " + texNumC + ", index);\n return sampleTexture(" + texName + ", uv);\n }\n";
+ }
+ function getPackedSampler3D(inputInfo) {
+ var shape = inputInfo.shapeInfo.logicalShape;
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var texShape = inputInfo.shapeInfo.texShape;
+ var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
+ if (shape[0] === 1) {
+ var squeezedShape = shape.slice(1);
+ var keptDims = [1, 2];
+ var newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
+ var params = ['b', 'row', 'col'];
+ return "\n " + getPackedSamplerFromInInfo(newInputInfo) + "\n vec4 " + funcName + "(int b, int row, int col) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
+ }
+ var texNumR = packedTexShape[0];
+ var texNumC = packedTexShape[1];
+ var valuesPerRow = Math.ceil(shape[2] / 2);
+ var texelsInBatch = valuesPerRow * Math.ceil(shape[1] / 2);
+ var glsl = getGlslDifferences();
+ return "\n vec4 " + funcName + "(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n " + texNumR + ", " + texNumC + ", " + texelsInBatch + ", " + valuesPerRow + ", b, row, col);\n return " + glsl.texture2D + "(" + texName + ", uv);\n }\n ";
+ }
+ function getSampler3D(inputInfo) {
+ var shape = inputInfo.shapeInfo.logicalShape;
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var stride0 = shape[1] * shape[2];
+ var stride1 = shape[2];
+ var _a = tf.util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
+ var squeezedShape = newShape;
+ if (squeezedShape.length < shape.length) {
+ var newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
+ var params = ['row', 'col', 'depth'];
+ return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col, int depth) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
+ }
+ if (inputInfo.shapeInfo.isUniform) {
+ // Uniform arrays will be less than 65505 (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3(" + stride0 + ", " + stride1 + ", 1)));\n " + getUniformSampler(inputInfo) + "\n }\n ";
+ }
+ var texShape = inputInfo.shapeInfo.texShape;
+ var texNumR = texShape[0];
+ var texNumC = texShape[1];
+ var flatOffset = inputInfo.shapeInfo.flatOffset;
+ if (texNumC === stride0 && flatOffset == null) {
+ // texC is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(" + stride1 + ", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ if (texNumC === stride1 && flatOffset == null) {
+ // texR is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(" + shape[1] + ", 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ var offset = getFlatOffsetUniformName(texName);
+ return "\n float " + funcName + "(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * " + stride0 + " + col * " + stride1 + " + depth + " + offset + ";\n vec2 uv = uvFromFlat(" + texNumR + ", " + texNumC + ", index);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ function getPackedSamplerND(inputInfo) {
+ var shape = inputInfo.shapeInfo.logicalShape;
+ var rank = shape.length;
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var texShape = inputInfo.shapeInfo.texShape;
+ var packedTexShape = [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];
+ var texNumR = packedTexShape[0];
+ var texNumC = packedTexShape[1];
+ var valuesPerRow = Math.ceil(shape[rank - 1] / 2);
+ var texelsInBatch = valuesPerRow * Math.ceil(shape[rank - 2] / 2);
+ var params = "int b, int row, int col";
+ var index = "b * " + texelsInBatch + " + (row / 2) * " + valuesPerRow + " + (col / 2)";
+ for (var b = 2; b < rank - 1; b++) {
+ params = "int b" + b + ", " + params;
+ texelsInBatch *= shape[rank - b - 1];
+ index = "b" + b + " * " + texelsInBatch + " + " + index;
+ }
+ var glsl = getGlslDifferences();
+ return "\n vec4 " + funcName + "(" + params + ") {\n int index = " + index + ";\n int texR = index / " + texNumC + ";\n int texC = index - texR * " + texNumC + ";\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(" + texNumC + ", " + texNumR + ");\n return " + glsl.texture2D + "(" + texName + ", uv);\n }\n ";
+ }
+ function getSampler4D(inputInfo) {
+ var shape = inputInfo.shapeInfo.logicalShape;
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var stride2 = shape[3];
+ var stride1 = shape[2] * stride2;
+ var stride0 = shape[1] * stride1;
+ var _a = tf.util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
+ if (newShape.length < shape.length) {
+ var newInputInfo = squeezeInputInfo(inputInfo, newShape);
+ var params = ['row', 'col', 'depth', 'depth2'];
+ return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
+ }
+ if (inputInfo.shapeInfo.isUniform) {
+ // Uniform arrays will be less than 65505 (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4(" + stride0 + ", " + stride1 + ", " + stride2 + ", 1)));\n " + getUniformSampler(inputInfo) + "\n }\n ";
+ }
+ var flatOffset = inputInfo.shapeInfo.flatOffset;
+ var texShape = inputInfo.shapeInfo.texShape;
+ var texNumR = texShape[0];
+ var texNumC = texShape[1];
+ if (texNumC === stride0 && flatOffset == null) {
+ // texC is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(" + stride1 + ", " + stride2 + ", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ if (texNumC === stride2 && flatOffset == null) {
+ // texR is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(" + shape[1] * shape[2] + ", " + shape[2] + ", 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ var offset = getFlatOffsetUniformName(texName);
+ return "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * " + stride0 + " + col * " + stride1 + " +\n depth * " + stride2 + " + depth2;\n vec2 uv = uvFromFlat(" + texNumR + ", " + texNumC + ", index + " + offset + ");\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ function getSampler5D(inputInfo) {
+ var shape = inputInfo.shapeInfo.logicalShape;
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var stride3 = shape[4];
+ var stride2 = shape[3] * stride3;
+ var stride1 = shape[2] * stride2;
+ var stride0 = shape[1] * stride1;
+ var _a = tf.util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
+ if (newShape.length < shape.length) {
+ var newInputInfo = squeezeInputInfo(inputInfo, newShape);
+ var params = ['row', 'col', 'depth', 'depth2', 'depth3'];
+ return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
+ }
+ if (inputInfo.shapeInfo.isUniform) {
+ // Uniform arrays will be less than 65505 (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4(" + stride0 + ", " + stride1 + ", " + stride2 + ", " + stride3 + ")) +\n depth3;\n " + getUniformSampler(inputInfo) + "\n }\n ";
+ }
+ var flatOffset = inputInfo.shapeInfo.flatOffset;
+ var texShape = inputInfo.shapeInfo.texShape;
+ var texNumR = texShape[0];
+ var texNumC = texShape[1];
+ if (texNumC === stride0 && flatOffset == null) {
+ // texC is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(" + stride1 + ", " + stride2 + ", " + stride3 + ", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ if (texNumC === stride3 && flatOffset == null) {
+ // texR is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4(" + shape[1] * shape[2] * shape[3] + ",\n " + shape[2] * shape[3] + ", " + shape[3] + ", 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ var offset = getFlatOffsetUniformName(texName);
+ return "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * " + stride0 + " + col * " + stride1 + " + depth * " + stride2 + " +\n depth2 * " + stride3 + " + depth3 + " + offset + ";\n vec2 uv = uvFromFlat(" + texNumR + ", " + texNumC + ", index);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ function getSampler6D(inputInfo) {
+ var shape = inputInfo.shapeInfo.logicalShape;
+ var texName = inputInfo.name;
+ var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
+ var _a = tf.util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
+ if (newShape.length < shape.length) {
+ var newInputInfo = squeezeInputInfo(inputInfo, newShape);
+ var params = ['row', 'col', 'depth', 'depth2', 'depth3', 'depth4'];
+ return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
+ }
+ var stride4 = shape[5];
+ var stride3 = shape[4] * stride4;
+ var stride2 = shape[3] * stride3;
+ var stride1 = shape[2] * stride2;
+ var stride0 = shape[1] * stride1;
+ if (inputInfo.shapeInfo.isUniform) {
+ // Uniform arrays will be less than 65505 (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4(" + stride0 + ", " + stride1 + ", " + stride2 + ", " + stride3 + ")) +\n dot(\n vec2(depth3, depth4),\n vec2(" + stride4 + ", 1)));\n " + getUniformSampler(inputInfo) + "\n }\n ";
+ }
+ var flatOffset = inputInfo.shapeInfo.flatOffset;
+ var texShape = inputInfo.shapeInfo.texShape;
+ var texNumR = texShape[0];
+ var texNumC = texShape[1];
+ if (texNumC === stride0 && flatOffset == null) {
+ // texC is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(" + stride1 + ", " + stride2 + ", " + stride3 + ", " + stride4 + ")) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ if (texNumC === stride4 && flatOffset == null) {
+ // texR is used directly as physical (no risk of float16 overflow).
+ return "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4(" + shape[1] * shape[2] * shape[3] * shape[4] + ",\n " + shape[2] * shape[3] * shape[4] + ",\n " + shape[3] * shape[4] + ",\n " + shape[4] + ")) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ var offset = getFlatOffsetUniformName(texName);
+ return "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * " + stride0 + " + col * " + stride1 + " + depth * " + stride2 + " +\n depth2 * " + stride3 + " + depth3 * " + stride4 + " + depth4 + " + offset + ";\n vec2 uv = uvFromFlat(" + texNumR + ", " + texNumC + ", index);\n return sampleTexture(" + texName + ", uv);\n }\n ";
+ }
+ function getUniformSampler(inputInfo) {
+ var texName = inputInfo.name;
+ var inSize = tf.util.sizeFromShape(inputInfo.shapeInfo.logicalShape);
+ if (inSize < 2) {
+ return "return " + texName + ";";
+ }
+ return "\n for (int i = 0; i < " + inSize + "; i++) {\n if (i == index) {\n return " + texName + "[i];\n }\n }\n ";
+ }
+ function getPackedSamplerAtOutputCoords(inputInfo, outShapeInfo) {
+ var texName = inputInfo.name;
+ var texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);
+ var funcName = 'get' + texFuncSnippet + 'AtOutCoords';
+ var inRank = inputInfo.shapeInfo.logicalShape.length;
+ var outRank = outShapeInfo.logicalShape.length;
+ var broadcastDims = getBroadcastDims(inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);
+ var type = getCoordsDataType(outRank);
+ var rankDiff = outRank - inRank;
+ var coordsSnippet;
+ var fields = ['x', 'y', 'z', 'w', 'u', 'v'];
+ if (inRank === 0) {
+ coordsSnippet = '';
+ }
+ else if (outRank < 2 && broadcastDims.length >= 1) {
+ coordsSnippet = 'coords = 0;';
+ }
+ else {
+ coordsSnippet =
+ broadcastDims.map(function (d) { return "coords." + fields[d + rankDiff] + " = 0;"; })
+ .join('\n');
+ }
+ var unpackedCoordsSnippet = '';
+ if (outRank < 2 && inRank > 0) {
+ unpackedCoordsSnippet = 'coords';
+ }
+ else {
+ unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape
+ .map(function (s, i) { return "coords." + fields[i + rankDiff]; })
+ .join(', ');
+ }
+ var output = "return outputValue;";
+ var inSize = tf.util.sizeFromShape(inputInfo.shapeInfo.logicalShape);
+ var isInputScalar = inSize === 1;
+ var outSize = tf.util.sizeFromShape(outShapeInfo.logicalShape);
+ var isOutputScalar = outSize === 1;
+ if (inRank === 1 && !isInputScalar && !isOutputScalar) {
+ output = "\n return vec4(outputValue.xy, outputValue.xy);\n ";
+ }
+ else if (isInputScalar && !isOutputScalar) {
+ if (outRank === 1) {
+ output = "\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ";
+ }
+ else {
+ output = "\n return vec4(outputValue.x);\n ";
+ }
+ }
+ else if (broadcastDims.length) {
+ var rows = inRank - 2;
+ var cols = inRank - 1;
+ if (broadcastDims.indexOf(rows) > -1 && broadcastDims.indexOf(cols) > -1) {
+ output = "return vec4(outputValue.x);";
+ }
+ else if (broadcastDims.indexOf(rows) > -1) {
+ output = "return vec4(outputValue.x, outputValue.y, " +
+ "outputValue.x, outputValue.y);";
+ }
+ else if (broadcastDims.indexOf(cols) > -1) {
+ output = "return vec4(outputValue.xx, outputValue.zz);";
+ }
+ }
+ return "\n vec4 " + funcName + "() {\n " + type + " coords = getOutputCoords();\n " + coordsSnippet + "\n vec4 outputValue = get" + texFuncSnippet + "(" + unpackedCoordsSnippet + ");\n " + output + "\n }\n ";
+ }
+ function getSamplerAtOutputCoords(inputInfo, outShapeInfo) {
+ var texName = inputInfo.name;
+ var texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);
+ var funcName = 'get' + texFuncSnippet + 'AtOutCoords';
+ var outTexShape = outShapeInfo.texShape;
+ var inTexShape = inputInfo.shapeInfo.texShape;
+ var inRank = inputInfo.shapeInfo.logicalShape.length;
+ var outRank = outShapeInfo.logicalShape.length;
+ if (!inputInfo.shapeInfo.isUniform && inRank === outRank &&
+ inputInfo.shapeInfo.flatOffset == null &&
+ tf.util.arraysEqual(inTexShape, outTexShape)) {
+ return "\n float " + funcName + "() {\n return sampleTexture(" + texName + ", resultUV);\n }\n ";
+ }
+ var type = getCoordsDataType(outRank);
+ var broadcastDims = getBroadcastDims(inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);
+ var rankDiff = outRank - inRank;
+ var coordsSnippet;
+ var fields = ['x', 'y', 'z', 'w', 'u', 'v'];
+ if (inRank === 0) {
+ coordsSnippet = '';
+ }
+ else if (outRank < 2 && broadcastDims.length >= 1) {
+ coordsSnippet = 'coords = 0;';
+ }
+ else {
+ coordsSnippet =
+ broadcastDims.map(function (d) { return "coords." + fields[d + rankDiff] + " = 0;"; })
+ .join('\n');
+ }
+ var unpackedCoordsSnippet = '';
+ if (outRank < 2 && inRank > 0) {
+ unpackedCoordsSnippet = 'coords';
+ }
+ else {
+ unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape
+ .map(function (s, i) { return "coords." + fields[i + rankDiff]; })
+ .join(', ');
+ }
+ return "\n float " + funcName + "() {\n " + type + " coords = getOutputCoords();\n " + coordsSnippet + "\n return get" + texFuncSnippet + "(" + unpackedCoordsSnippet + ");\n }\n ";
+ }
+ function getCoordsDataType(rank) {
+ if (rank <= 1) {
+ return 'int';
+ }
+ else if (rank === 2) {
+ return 'ivec2';
+ }
+ else if (rank === 3) {
+ return 'ivec3';
+ }
+ else if (rank === 4) {
+ return 'ivec4';
+ }
+ else if (rank === 5) {
+ return 'ivec5';
+ }
+ else if (rank === 6) {
+ return 'ivec6';
+ }
+ else {
+ throw Error("GPU for rank " + rank + " is not yet supported");
+ }
+ }
+ /** Returns a new input info (a copy) that has a squeezed logical shape. */
+ function squeezeInputInfo(inInfo, squeezedShape) {
+ // Deep copy.
+ var newInputInfo = JSON.parse(JSON.stringify(inInfo));
+ newInputInfo.shapeInfo.logicalShape = squeezedShape;
+ return newInputInfo;
+ }
+ function getSqueezedParams(params, keptDims) {
+ return keptDims.map(function (d) { return params[d]; }).join(', ');
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function compileProgram(gpgpu, program, inputs, output) {
+ var userCode = program.userCode;
+ var inputInfos = inputs.map(function (input, i) {
+ var shapeInfo = {
+ logicalShape: input.shape,
+ texShape: input.isUniform ? null : input.texData.texShape,
+ isUniform: input.isUniform,
+ isPacked: input.isUniform ? false : input.texData.isPacked,
+ flatOffset: null
+ };
+ if (input.texData != null && input.texData.slice != null &&
+ input.texData.slice.flatOffset > 0) {
+ shapeInfo.flatOffset = input.texData.slice.flatOffset;
+ }
+ return { name: program.variableNames[i], shapeInfo: shapeInfo };
+ });
+ var inShapeInfos = inputInfos.map(function (x) { return x.shapeInfo; });
+ var outShapeInfo = {
+ logicalShape: output.shape,
+ texShape: output.texData.texShape,
+ isUniform: false,
+ isPacked: output.texData.isPacked,
+ flatOffset: null
+ };
+ var source = makeShader(inputInfos, outShapeInfo, userCode, program.packedInputs);
+ var webGLProgram = gpgpu.createProgram(source);
+ // Add special uniforms (NAN, INFINITY)
+ var infLoc = null;
+ var nanLoc = gpgpu.getUniformLocation(webGLProgram, 'NAN', false);
+ if (tf.env().getNumber('WEBGL_VERSION') === 1) {
+ infLoc = gpgpu.getUniformLocation(webGLProgram, 'INFINITY', false);
+ }
+ // Add user-defined uniforms
+ var uniformLocations = {};
+ for (var i = 0; i < program.variableNames.length; i++) {
+ var varName = program.variableNames[i];
+ var shouldThrow = false;
+ uniformLocations[varName] =
+ gpgpu.getUniformLocation(webGLProgram, varName, shouldThrow);
+ uniformLocations["offset" + varName] =
+ gpgpu.getUniformLocation(webGLProgram, "offset" + varName, shouldThrow);
+ }
+ return {
+ program: program,
+ source: source,
+ webGLProgram: webGLProgram,
+ uniformLocations: uniformLocations,
+ inShapeInfos: inShapeInfos,
+ outShapeInfo: outShapeInfo,
+ infLoc: infLoc,
+ nanLoc: nanLoc,
+ };
+ }
+ function validateBinaryAndProgram(shapeInfos, inputs) {
+ if (shapeInfos.length !== inputs.length) {
+ throw Error("Binary was compiled with " + shapeInfos.length + " inputs, but " +
+ ("was executed with " + inputs.length + " inputs"));
+ }
+ shapeInfos.forEach(function (s, i) {
+ var shapeA = s.logicalShape;
+ var input = inputs[i];
+ var shapeB = input.shape;
+ if (!tf.util.arraysEqual(shapeA, shapeB)) {
+ throw Error("Binary was compiled with different shapes than " +
+ ("the current args. Shapes " + shapeA + " and " + shapeB + " must match"));
+ }
+ // The input is uploaded as uniform.
+ if (s.isUniform && input.isUniform) {
+ return;
+ }
+ var texShapeA = s.texShape;
+ var texShapeB = input.isUniform ? null : input.texData.texShape;
+ if (!tf.util.arraysEqual(texShapeA, texShapeB)) {
+ throw Error("Binary was compiled with different texture shapes than the" +
+ (" current args. Shape " + texShapeA + " and " + texShapeB + " must match"));
+ }
+ });
+ }
+ function runProgram(gpgpu, binary, inputs, output, customSetup) {
+ validateBinaryAndProgram(binary.inShapeInfos, inputs);
+ validateBinaryAndProgram([binary.outShapeInfo], [output]);
+ var outTex = output.texData.texture;
+ var outTexShape = output.texData.texShape;
+ if (output.texData.isPacked) {
+ gpgpu.setOutputPackedMatrixTexture(outTex, outTexShape[0], outTexShape[1]);
+ }
+ else {
+ gpgpu.setOutputMatrixTexture(outTex, outTexShape[0], outTexShape[1]);
+ }
+ gpgpu.setProgram(binary.webGLProgram);
+ // Set special uniforms (NAN, INFINITY)
+ if (tf.env().getNumber('WEBGL_VERSION') === 1) {
+ if (binary.infLoc !== null) {
+ gpgpu.gl.uniform1f(binary.infLoc, Infinity);
+ }
+ }
+ if (binary.nanLoc !== null) {
+ gpgpu.gl.uniform1f(binary.nanLoc, NaN);
+ }
+ // Set user-defined inputs
+ inputs.forEach(function (input, i) {
+ var varName = binary.program.variableNames[i];
+ var varLoc = binary.uniformLocations[varName];
+ var varOffsetLoc = binary.uniformLocations["offset" + varName];
+ if (varLoc == null) {
+ // The compiler inferred that this variable is not used in this shader.
+ return;
+ }
+ if (input.isUniform) {
+ // Upload the values of the tensor as uniform.
+ if (tf.util.sizeFromShape(input.shape) < 2) {
+ gpgpu.gl.uniform1f(varLoc, input.uniformValues[0]);
+ }
+ else {
+ var vals = input.uniformValues;
+ if (!(vals instanceof Float32Array)) {
+ vals = new Float32Array(vals);
+ }
+ gpgpu.gl.uniform1fv(varLoc, vals);
+ }
+ return;
+ }
+ // If the input was sliced, upload the flat offset index.
+ if (input.texData.slice != null && varOffsetLoc != null) {
+ gpgpu.gl.uniform1i(varOffsetLoc, input.texData.slice.flatOffset);
+ }
+ gpgpu.setInputMatrixTexture(input.texData.texture, varLoc, i);
+ });
+ if (customSetup != null) {
+ customSetup(gpgpu, binary.webGLProgram);
+ }
+ gpgpu.executeProgram();
+ }
+ function makeShaderKey(program, inputs, output) {
+ var keyInputs = '';
+ inputs.concat(output).forEach(function (x) {
+ var hasOffset = x.texData != null && x.texData.slice != null &&
+ x.texData.slice.flatOffset > 0;
+ var texShape = x.isUniform ? 'uniform' : x.texData.texShape;
+ keyInputs += x.shape + "_" + texShape + "_" + hasOffset;
+ });
+ var keyUserCode = program.userCode;
+ var key = program.constructor.name;
+ // Fast string concat. See https://jsperf.com/string-concatenation/14.
+ key += '_' + keyInputs + '_' + keyUserCode;
+ return key;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function simpleAbsImpl(vals) {
+ const resultValues = new Float32Array(vals.length);
+ for (let i = 0; i < vals.length; ++i) {
+ resultValues[i] = Math.abs(vals[i]);
+ }
+ return resultValues;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Template that creates implementation for binary ops. Supports broadcast.
+ */
+ function createSimpleBinaryKernelImpl(op) {
+ return (aShape, bShape, aVals, bVals, dtype) => {
+ const newShape = tf.backend_util.assertAndGetBroadcastShape(aShape, bShape);
+ const resultRank = newShape.length;
+ const resultStrides = tf.util.computeStrides(newShape);
+ const resultSize = tf.util.sizeFromShape(newShape);
+ const result = tf.util.getTypedArrayFromDType(dtype, resultSize);
+ const aRank = aShape.length;
+ const bRank = bShape.length;
+ const aStrides = tf.util.computeStrides(aShape);
+ const bStrides = tf.util.computeStrides(bShape);
+ const aBroadcastDims = tf.backend_util.getBroadcastDims(aShape, newShape);
+ const bBroadcastDims = tf.backend_util.getBroadcastDims(bShape, newShape);
+ if (aBroadcastDims.length + bBroadcastDims.length === 0) {
+ for (let i = 0; i < result.length; ++i) {
+ result[i] = op(aVals[i % aVals.length], bVals[i % bVals.length]);
+ }
+ }
+ else {
+ for (let i = 0; i < result.length; ++i) {
+ const loc = tf.util.indexToLoc(i, resultRank, resultStrides);
+ const aLoc = loc.slice(-aRank);
+ aBroadcastDims.forEach(d => aLoc[d] = 0);
+ const aIndex = tf.util.locToIndex(aLoc, aRank, aStrides);
+ const bLoc = loc.slice(-bRank);
+ bBroadcastDims.forEach(d => bLoc[d] = 0);
+ const bIndex = tf.util.locToIndex(bLoc, bRank, bStrides);
+ result[i] = op(aVals[aIndex], bVals[bIndex]);
+ }
+ }
+ return [result, newShape];
+ };
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const addImpl = createSimpleBinaryKernelImpl(((a, b) => a + b));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function bincountImpl(xVals, weightsVals, weightsDtype, weightsShape, size) {
+ const weightsSize = tf.util.sizeFromShape(weightsShape);
+ const outVals = tf.util.makeZerosTypedArray(size, weightsDtype);
+ for (let i = 0; i < xVals.length; i++) {
+ const value = xVals[i];
+ if (value < 0) {
+ throw new Error('Input x must be non-negative!');
+ }
+ if (value >= size) {
+ continue;
+ }
+ if (weightsSize > 0) {
+ outVals[value] += weightsVals[i];
+ }
+ else {
+ outVals[value] += 1;
+ }
+ }
+ return outVals;
+ }
+ function bincountReduceImpl(xBuf, weightsBuf, size, binaryOutput = false) {
+ const numRows = xBuf.shape[0];
+ const numCols = xBuf.shape[1];
+ const outBuf = tf.buffer([numRows, size], weightsBuf.dtype);
+ for (let i = 0; i < numRows; i++) {
+ for (let j = 0; j < numCols; j++) {
+ const value = xBuf.get(i, j);
+ if (value < 0) {
+ throw new Error('Input x must be non-negative!');
+ }
+ if (value >= size) {
+ continue;
+ }
+ if (binaryOutput) {
+ outBuf.set(1, i, value);
+ }
+ else {
+ if (weightsBuf.size > 0) {
+ outBuf.set(outBuf.get(i, value) + weightsBuf.get(i, j), i, value);
+ }
+ else {
+ outBuf.set(outBuf.get(i, value) + 1, i, value);
+ }
+ }
+ }
+ }
+ return outBuf;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Template that creates implementation for unary op.
+ */
+ function createSimpleUnaryImpl(op) {
+ return (values, dtype, attrs) => {
+ const newValues = tf.util.getTypedArrayFromDType(dtype, values.length);
+ for (let i = 0; i < values.length; ++i) {
+ newValues[i] = op(values[i], attrs);
+ }
+ return newValues;
+ };
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const ceilImpl = createSimpleUnaryImpl((xi) => Math.ceil(xi));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function concatImpl(inputs, outShape, dtype, simplyConcat) {
+ const outVals = tf.util.getArrayFromDType(dtype, tf.util.sizeFromShape(outShape));
+ if (simplyConcat && dtype !== 'string') {
+ // Use built-in TypedArray.set() method for speed.
+ let offset = 0;
+ inputs.forEach(input => {
+ const size = tf.util.sizeFromShape(input.shape);
+ outVals.set(input.vals, offset);
+ offset += size;
+ });
+ }
+ else {
+ let colOffset = 0;
+ inputs.forEach(input => {
+ const decodedData = dtype === 'string' ?
+ tf.backend_util.fromUint8ToStringArray(input.vals) :
+ input.vals;
+ let tIdx = 0;
+ for (let row = 0; row < input.shape[0]; ++row) {
+ const resIdx = row * outShape[1] + colOffset;
+ for (let col = 0; col < input.shape[1]; ++col) {
+ outVals[resIdx + col] = decodedData[tIdx++];
+ }
+ }
+ colOffset += input.shape[1];
+ });
+ }
+ return outVals;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const equalImpl = createSimpleBinaryKernelImpl((a, b) => (a === b) ? 1 : 0);
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const expImpl = createSimpleUnaryImpl((xi) => Math.exp(xi));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const expm1Impl = createSimpleUnaryImpl((xi) => Math.expm1(xi));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const floorImpl = createSimpleUnaryImpl((xi) => Math.floor(xi));
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function gatherNdImpl(indicesData, paramsBuf, dtype, numSlices, sliceRank, sliceSize, strides, paramsShape, paramsSize) {
+ const outBuf = tf.buffer([numSlices, sliceSize], dtype);
+ for (let i = 0; i < numSlices; i++) {
+ const index = [];
+ let flattenIndex = 0;
+ for (let j = 0; j < sliceRank; j++) {
+ const dim = indicesData[i * sliceRank + j];
+ flattenIndex += dim * strides[j];
+ index.push(dim);
+ }
+ if (flattenIndex < 0 || flattenIndex >= paramsSize / sliceSize) {
+ throw new Error(`Invalid indices: ${index} does not index into ${paramsShape}`);
+ }
+ for (let k = 0; k < sliceSize; k++) {
+ outBuf.values[i * sliceSize + k] =
+ paramsBuf.get(...paramsBuf.indexToLoc(flattenIndex * sliceSize + k));
+ }
+ }
+ return outBuf;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function gatherV2Impl(xBuf, indicesBuf, flattenOutputShape) {
+ const outBuf = tf.buffer(flattenOutputShape, xBuf.dtype);
+ for (let i = 0; i < outBuf.size; ++i) {
+ const newLoc = outBuf.indexToLoc(i);
+ const originalLoc = newLoc.slice();
+ const batchIdx = originalLoc[0];
+ const indicesIdx = originalLoc[2];
+ const indicesIndex = indicesBuf.locToIndex([batchIdx, indicesIdx]);
+ originalLoc[2] = indicesBuf.values[indicesIndex];
+ const originalIndex = xBuf.locToIndex(originalLoc);
+ outBuf.values[i] = xBuf.values[originalIndex];
+ }
+ return outBuf;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const greaterImpl = createSimpleBinaryKernelImpl((a, b) => (a > b) ? 1 : 0);
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const greaterEqualImpl = createSimpleBinaryKernelImpl((a, b) => (a >= b) ? 1 : 0);
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const lessImpl = createSimpleBinaryKernelImpl((a, b) => (a < b) ? 1 : 0);
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const lessEqualImpl = createSimpleBinaryKernelImpl((a, b) => (a <= b) ? 1 : 0);
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function linSpaceImpl(start, stop, num) {
+ const step = (stop - start) / (num - 1);
+ const values = tf.util.makeZerosTypedArray(num, 'float32');
+ values[0] = start;
+ for (let i = 1; i < values.length; i++) {
+ values[i] = values[i - 1] + step;
+ }
+ return values;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const logImpl = createSimpleUnaryImpl((xi) => Math.log(xi));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function maxImpl(aVals, reduceSize, outShape, dtype) {
+ const vals = tf.util.getTypedArrayFromDType(dtype, tf.util.sizeFromShape(outShape));
+ for (let i = 0; i < vals.length; ++i) {
+ const offset = i * reduceSize;
+ let max = aVals[offset];
+ for (let j = 0; j < reduceSize; ++j) {
+ const value = aVals[offset + j];
+ if (Number.isNaN(value) ||
+ value > max) { // comparison with NaN always return false
+ max = value;
+ }
+ }
+ vals[i] = max;
+ }
+ return vals;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const maximumImpl = createSimpleBinaryKernelImpl(((aValue, bValue) => Math.max(aValue, bValue)));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const minimumImpl = createSimpleBinaryKernelImpl(((aValue, bValue) => Math.min(aValue, bValue)));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const multiplyImpl = createSimpleBinaryKernelImpl(((aValue, bValue) => aValue * bValue));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function negImpl(xVals, xShape, xDtype) {
+ const minusOne = tf.util.createScalarValue(-1, xDtype);
+ return multiplyImpl([], xShape, minusOne, xVals, xDtype);
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const notEqualImpl = createSimpleBinaryKernelImpl(((a, b) => (a !== b) ? 1 : 0));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function transposeImpl(xVals, xShape, dtype, perm, newShape) {
+ const xRank = xShape.length;
+ const xSize = tf.util.sizeFromShape(xShape);
+ const xStrides = tf.util.computeStrides(xShape);
+ const newStrides = tf.util.computeStrides(newShape);
+ const result = tf.util.getTypedArrayFromDType(dtype, tf.util.sizeFromShape(newShape));
+ for (let i = 0; i < xSize; ++i) {
+ const loc = tf.util.indexToLoc(i, xRank, xStrides);
+ // Permute location.
+ const newLoc = new Array(loc.length);
+ for (let i = 0; i < newLoc.length; i++) {
+ newLoc[i] = loc[perm[i]];
+ }
+ const newIndex = tf.util.locToIndex(newLoc, xRank, newStrides);
+ result[newIndex] = xVals[i];
+ }
+ return result;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function prodImpl(xShape, xDtype, xVals, reductionAxes) {
+ const [outShape, reduceShape] = tf.backend_util.computeOutAndReduceShapes(xShape, reductionAxes);
+ const outDtype = tf.upcastType(xDtype, 'int32');
+ const outVals = tf.util.makeZerosTypedArray(tf.util.sizeFromShape(outShape), outDtype);
+ const reduceSize = tf.util.sizeFromShape(reduceShape);
+ for (let i = 0; i < outVals.length; ++i) {
+ const offset = i * reduceSize;
+ let prod = 1;
+ for (let j = 0; j < reduceSize; ++j) {
+ prod *= xVals[offset + j];
+ }
+ outVals[i] = prod;
+ }
+ return { outVals, outShape, outDtype };
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function rangeImpl(start, stop, step, dtype) {
+ const sameStartStop = start === stop;
+ const increasingRangeNegativeStep = start < stop && step < 0;
+ const decreasingRangePositiveStep = stop < start && step > 1;
+ if (sameStartStop || increasingRangeNegativeStep ||
+ decreasingRangePositiveStep) {
+ return tf.util.makeZerosTypedArray(0, dtype);
+ }
+ const numElements = Math.abs(Math.ceil((stop - start) / step));
+ const values = tf.util.makeZerosTypedArray(numElements, dtype);
+ if (stop < start && step === 1) {
+ // Auto adjust the step's sign if it hasn't been set
+ // (or was set to 1)
+ step = -1;
+ }
+ values[0] = start;
+ for (let i = 1; i < values.length; i++) {
+ values[i] = values[i - 1] + step;
+ }
+ return values;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const rsqrtImpl = createSimpleUnaryImpl((xi) => 1 / Math.sqrt(xi));
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sliceImpl(vals, begin, size, shape, dtype) {
+ const isContinous = tf.slice_util.isSliceContinous(shape, begin, size);
+ const length = tf.util.sizeFromShape(size);
+ const xStrides = tf.util.computeStrides(shape);
+ if (isContinous) {
+ const flatOffset = tf.slice_util.computeFlatOffset(begin, xStrides);
+ if (dtype === 'string') {
+ return vals.slice(flatOffset, flatOffset + length);
+ }
+ return vals.subarray(flatOffset, flatOffset + length);
+ }
+ const decodedData = dtype === 'string' ?
+ tf.backend_util.fromUint8ToStringArray(vals) :
+ vals;
+ const inBuf = tf.buffer(shape, dtype, decodedData);
+ const outBuf = tf.buffer(size, dtype);
+ for (let i = 0; i < outBuf.size; ++i) {
+ const outLoc = outBuf.indexToLoc(i);
+ const inLoc = outLoc.map((idx, j) => idx + begin[j]);
+ outBuf.set(inBuf.get(...inLoc), ...outLoc);
+ }
+ if (dtype === 'string') {
+ return tf.backend_util.fromStringArrayToUint8(outBuf.values);
+ }
+ return outBuf.values;
+ }
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sparseFillEmptyRowsImpl(indices, indicesShape, indicesDType, values, valuesDType, denseShape, defaultValue) {
+ const indicesCount = indicesShape[0];
+ const denseRows = denseShape[0];
+ const emptyRowIndicator = new Array(denseRows);
+ const reverseIndexMap = new Array(indicesCount);
+ const rank = indicesShape[1];
+ if (denseRows === 0) {
+ if (indicesCount !== 0) {
+ throw new Error(`Received SparseTensor with denseShape[0] = 0 but
+ indices.shape[0] = ${indicesCount}`);
+ }
+ const outputIndices = tf.util.getArrayFromDType(indicesDType, 0);
+ const outputValues = tf.util.getArrayFromDType(valuesDType, 0);
+ return [
+ outputIndices, [0, rank], outputValues, emptyRowIndicator, reverseIndexMap
+ ];
+ }
+ let rowsAreOrdered = true;
+ let lastIndicesRow = 0;
+ const csrOffset = new Array(denseRows).fill(0);
+ for (let i = 0; i < indicesCount; ++i) {
+ // indices is a 2d tensor with shape of [N, rank]
+ const row = indices[i * rank];
+ if (row < 0) {
+ throw new Error(`indices(${i}, 0) is invalid: ${row} < 0`);
+ }
+ if (row >= denseRows) {
+ throw new Error(`indices(${i}, 0) is invalid: ${row} >= ${denseRows}`);
+ }
+ ++csrOffset[row];
+ rowsAreOrdered = rowsAreOrdered && (row >= lastIndicesRow);
+ lastIndicesRow = row;
+ }
+ let allRowsFull = true;
+ for (let row = 0; row < denseRows; ++row) {
+ // csrOffset here describes the number of elements in this dense row
+ const rowEmpty = (csrOffset[row] === 0);
+ emptyRowIndicator[row] = rowEmpty;
+ allRowsFull = allRowsFull && !rowEmpty;
+ // In filled version, each row has at least one element.
+ csrOffset[row] = Math.max(csrOffset[row], 1);
+ // Update csrOffset to represent the number of elements up to and
+ // including denseRows + 1:
+ // csrOffset[0] == #{elements of row 0}
+ // csrOffset[1] == #{elements of row 1} + #{elements of row 0}
+ // ..
+ // csrOffset[i] == starting index for elements in row i + 1.
+ if (row > 0) {
+ csrOffset[row] += csrOffset[row - 1];
+ }
+ }
+ if (allRowsFull && rowsAreOrdered) {
+ const outputIndices = indices;
+ const outputValues = values;
+ for (let i = 0; i < indicesCount; ++i) {
+ reverseIndexMap[i] = i;
+ }
+ return [
+ outputIndices, [indicesCount, rank], outputValues, emptyRowIndicator,
+ reverseIndexMap
+ ];
+ }
+ else {
+ const fullIndicesCount = csrOffset[denseRows - 1];
+ const outputIndices = tf.util.getArrayFromDType(indicesDType, fullIndicesCount * rank);
+ const outputValues = tf.util.getArrayFromDType(valuesDType, fullIndicesCount);
+ const filledCount = new Array(denseRows).fill(0);
+ // Fill in values for rows that are not missing
+ for (let i = 0; i < indicesCount; ++i) {
+ // indices is a 2d tensor with shape of [N, rank]
+ const row = indices[i * rank];
+ const offset = filledCount[row];
+ const outputI = ((row === 0) ? 0 : csrOffset[row - 1]) + offset;
+ filledCount[row]++; // Increment the filled count for this row.
+ for (let j = 0; j < rank; ++j) {
+ // indices and outputIndices are 2d tensors with shape of [N, rank]
+ outputIndices[outputI * rank + j] = indices[i * rank + j];
+ }
+ outputValues[outputI] = values[i];
+ // We'll need this reverse index map to backprop correctly.
+ reverseIndexMap[i] = outputI;
+ }
+ // Fill in values for rows that are missing
+ for (let row = 0; row < denseRows; ++row) {
+ const rowCount = filledCount[row];
+ if (rowCount === 0) { // We haven't filled this row
+ const startingIndex = (row === 0) ? 0 : csrOffset[row - 1];
+ // Remaining index values were set to zero already.
+ // Just need to set the row index in the right location.
+ // outputIndices is a 2d tensor with shape of [N, rank]
+ outputIndices[startingIndex * rank + 0] = row;
+ for (let col = 1; col < rank; ++col) {
+ outputIndices[startingIndex * rank + col] = 0;
+ }
+ outputValues[startingIndex] = defaultValue;
+ }
+ }
+ return [
+ outputIndices, [fullIndicesCount, rank], outputValues, emptyRowIndicator,
+ reverseIndexMap
+ ];
+ }
+ }
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sparseReshapeImpl(inputIndices, inputIndicesShape, inputDType, inputShape, targetShape) {
+ const denseSize = tf.util.sizeFromShape(inputShape);
+ const nnz = inputIndicesShape[0];
+ const outputRank = targetShape.length;
+ // Compute the output shape. Determine product of specified dimensions, and
+ // find the index of the unspecified one.
+ const outputShape = [];
+ let product = 1;
+ let unknownIndex = -1;
+ for (let d = 0; d < outputRank; ++d) {
+ const size = targetShape[d];
+ if (size === -1) {
+ if (unknownIndex !== -1) {
+ throw new Error(`only one output dimension may be -1, not both ${unknownIndex} and ${d}`);
+ }
+ unknownIndex = d;
+ outputShape.push(1);
+ }
+ else {
+ if (size < 0) {
+ throw new Error(`size ${d} must be non-negative, not ${size}`);
+ }
+ product *= size;
+ outputShape.push(size);
+ }
+ }
+ if (unknownIndex !== -1) {
+ if (product <= 0) {
+ throw new Error('reshape cannot infer the missing ' +
+ 'input size for an empty tensor unless all ' +
+ 'specified input sizes are non-zero');
+ }
+ const missing = Math.trunc(denseSize / product);
+ if (product * missing !== denseSize) {
+ throw new Error(`Input to reshape is a SparseTensor with ${denseSize}
+ dense values, but the requested shape requires a multiple of ${product}. inputShape=${inputShape} outputShape= ${outputShape}`);
+ }
+ outputShape[unknownIndex] = missing;
+ }
+ const outputSize = tf.util.sizeFromShape(outputShape);
+ if (outputSize !== denseSize) {
+ throw new Error(`Input to reshape is a tensor with ${denseSize} dense values, but the requested shape has ${outputSize}. inputShape=${inputShape} outputShape=${outputShape}`);
+ }
+ const inputRank = inputShape.length;
+ const inputStrides = [];
+ if (inputRank > 0) {
+ inputStrides[inputRank - 1] = 1;
+ for (let d = inputRank - 2; d >= 0; --d) {
+ inputStrides[d] = inputStrides[d + 1] * inputShape[d + 1];
+ }
+ }
+ const outputStrides = [];
+ if (outputRank > 0) {
+ outputStrides[outputRank - 1] = 1;
+ for (let d = outputRank - 2; d >= 0; --d) {
+ outputStrides[d] = outputStrides[d + 1] * outputShape[d + 1];
+ }
+ }
+ const newIndices = tf.util.getArrayFromDType(inputDType, nnz * outputRank);
+ for (let i = 0; i < nnz; ++i) {
+ let id = 0;
+ for (let j = 0; j < inputRank; ++j) {
+ // inputIndices is a 2d tensor with shape of [nnz, inputRank]
+ id += inputIndices[i * inputRank + j] * inputStrides[j];
+ }
+ for (let j = 0; j < outputRank; ++j) {
+ // newIndices is a 2d tensor with shape of [nnz, outputRank]
+ newIndices[i * outputRank + j] = Math.trunc(id / outputStrides[j]);
+ id %= outputStrides[j];
+ }
+ }
+ return [newIndices, [nnz, outputRank], outputShape];
+ }
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sparseSegmentReductionImpl(input, inputShape, inputDType, indices, segmentIds, isMean = false, defaultValue = 0) {
+ const numIndices = indices.length;
+ if (numIndices !== segmentIds.length) {
+ throw new Error(`segmentIds and indices should have same size.`);
+ }
+ // Flatten the array to two dimensions
+ const inputFlat = [inputShape[0], input.length / inputShape[0]];
+ const numCol = inputFlat[1];
+ // Note that the current implementation assumes that segmentIds values are
+ // sorted.
+ const lastSegmentIdPlusOne = numIndices > 0 ? segmentIds[numIndices - 1] + 1 : 0;
+ const outputRows = lastSegmentIdPlusOne;
+ if (outputRows < 0) {
+ throw new Error(`segment ids must be >= 0`);
+ }
+ const outputShape = inputShape.slice();
+ outputShape[0] = outputRows;
+ const outputLength = outputShape.reduce((product, value) => product * value, 1);
+ // Output array is initialized with the value 0 by default.
+ const output = tf.util.getArrayFromDType(inputDType, outputLength);
+ // Note that we do not initialize the output buffer with a default value, so
+ // we need to explicitly set missing indices to the default value.
+ if (numIndices === 0) {
+ if (outputRows > 0) {
+ output.fill(defaultValue);
+ }
+ return [output, outputShape];
+ }
+ if (outputRows <= 0) {
+ throw new Error(`segment ids must be >= 0`);
+ }
+ let start = 0, end = 1;
+ // Index from which the output is not initialized.
+ let uninitializedIndex = 0;
+ let outIndex = segmentIds[start];
+ while (true) {
+ // We initialize nextIndex to 0 to avoid may be uninitialized warning
+ let nextIndex = 0;
+ if (end < numIndices) {
+ nextIndex = segmentIds[end];
+ if (outIndex === nextIndex) {
+ ++end;
+ continue;
+ }
+ // We have a new segment here. Verify that the segment ids are growing.
+ if (outIndex >= nextIndex) {
+ throw new Error(`segment ids are not increasing`);
+ }
+ }
+ if (outIndex < 0 || outIndex >= outputRows) {
+ throw new Error(`Segment id ${outIndex} out of range [0, ${outputRows}), possibly because segmentIds input is not sorted.`);
+ }
+ // If there is a gap between two indices, we need to set that gap to the
+ // default value.
+ if (outIndex > uninitializedIndex) {
+ output.fill(defaultValue, uninitializedIndex * numCol, outIndex * numCol);
+ }
+ for (let i = start; i < end; ++i) {
+ const index = indices[i];
+ if (index < 0 || index >= inputFlat[0]) {
+ throw new Error(`Bad: indices[${i}] == ${indices[i]} out of range [0, ${inputFlat[0]})`);
+ }
+ for (let j = 0; j < numCol; j++) {
+ output[outIndex * numCol + j] += input[index * numCol + j];
+ }
+ }
+ if (isMean) {
+ for (let j = 0; j < numCol; j++) {
+ output[outIndex * numCol + j] /= end - start;
+ }
+ }
+ start = end;
+ ++end;
+ uninitializedIndex = outIndex + 1;
+ outIndex = nextIndex;
+ if (end > numIndices) {
+ break;
+ }
+ }
+ // Fill the gap at the end with the default value.
+ if (uninitializedIndex < outputRows) {
+ output.fill(defaultValue, uninitializedIndex * numCol, outputRows * numCol);
+ }
+ return [output, outputShape];
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function stridedSliceImpl(outShape, xBuf, strides, begin) {
+ const outBuf = tf.buffer(outShape, xBuf.dtype);
+ for (let i = 0; i < outBuf.size; i++) {
+ const loc = outBuf.indexToLoc(i);
+ const newLoc = new Array(loc.length);
+ for (let j = 0; j < newLoc.length; j++) {
+ newLoc[j] = loc[j] * strides[j] + begin[j];
+ }
+ outBuf.set(xBuf.get(...newLoc), ...loc);
+ }
+ return outBuf;
+ }
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * The StringNGramsOp class creates ngrams from ragged string data.
+ * The constructor contains all attributes related to the operation such as
+ * padding widths and strings, and the compute function can be used to
+ * compute the ngrams for different ragged tensor inputs.
+ */
+ class StringNGramsOp {
+ constructor(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {
+ this.separator = tf.util.encodeString(separator);
+ this.nGramWidths = nGramWidths;
+ this.leftPad = tf.util.encodeString(leftPad);
+ this.rightPad = tf.util.encodeString(rightPad);
+ this.padWidth = padWidth;
+ this.preserveShort = preserveShortSequences;
+ }
+ getPadWidth(nGramWidth) {
+ // Ngrams can be padded with either a fixed pad width or a dynamic pad
+ // width depending on the 'padWidth' arg, but in no case should the padding
+ // ever be wider than 'nGramWidth' - 1.
+ return Math.min(this.padWidth < 0 ? nGramWidth - 1 : this.padWidth, nGramWidth - 1);
+ }
+ getNumNGrams(length, nGramWidth) {
+ const padWidth = this.getPadWidth(nGramWidth);
+ return Math.max(0, ((length + 2 * padWidth) - nGramWidth) + 1);
+ }
+ createNGrams(data, splitIndex, output, outputStartIndex, numNGrams, nGramWidth) {
+ for (let nGramIndex = 0; nGramIndex < numNGrams; ++nGramIndex) {
+ const padWidth = this.getPadWidth(nGramWidth);
+ const leftPadding = Math.max(0, padWidth - nGramIndex);
+ const rightPadding = Math.max(0, padWidth - (numNGrams - (nGramIndex + 1)));
+ const numTokens = nGramWidth - (leftPadding + rightPadding);
+ const dataStartIndex = splitIndex + (leftPadding > 0 ? 0 : nGramIndex - padWidth);
+ // Calculate the total expected size of the nGram so we can reserve the
+ // correct amount of space in the string.
+ let nGramSize = 0;
+ // Size of the left padding.
+ nGramSize += leftPadding * this.leftPad.length;
+ // Size of the tokens.
+ for (let n = 0; n < numTokens; ++n) {
+ nGramSize += data[dataStartIndex + n].length;
+ }
+ // Size of the right padding.
+ nGramSize += rightPadding * this.rightPad.length;
+ // Size of the separators.
+ const numSeparators = leftPadding + rightPadding + numTokens - 1;
+ nGramSize += numSeparators * this.separator.length;
+ // Build the nGram.
+ output[outputStartIndex + nGramIndex] = new Uint8Array(nGramSize);
+ const nGram = output[outputStartIndex + nGramIndex];
+ let nextNGramIndex = 0;
+ const appendToNGram = (str) => str.forEach((value) => nGram[nextNGramIndex++] = value);
+ for (let n = 0; n < leftPadding; ++n) {
+ appendToNGram(this.leftPad);
+ appendToNGram(this.separator);
+ }
+ // Only output first numTokens - 1 pairs of data and separator
+ for (let n = 0; n < numTokens - 1; ++n) {
+ appendToNGram(data[dataStartIndex + n]);
+ appendToNGram(this.separator);
+ }
+ // Handle case when there are no tokens or no right padding as these
+ // can result in consecutive separators.
+ if (numTokens > 0) {
+ // If we have tokens, then output last and then pair each separator
+ // with the right padding that follows, to ensure nGram ends either with
+ // the token or with the right pad.
+ appendToNGram(data[dataStartIndex + numTokens - 1]);
+ for (let n = 0; n < rightPadding; ++n) {
+ appendToNGram(this.separator);
+ appendToNGram(this.rightPad);
+ }
+ }
+ else {
+ // If we don't have tokens, then the last item inserted into the nGram
+ // has been the separator from the left padding loop above. Hence,
+ // output right pad and separator and make sure to finish with a
+ // padding, not a separator.
+ for (let n = 0; n < rightPadding - 1; ++n) {
+ appendToNGram(this.rightPad);
+ appendToNGram(this.separator);
+ }
+ appendToNGram(this.rightPad);
+ }
+ }
+ }
+ // Data and splits together form the definition of the ragged tensor,
+ // where data is 1 dimensional and contains the values of the tensor
+ // and splits denotes the indices at which each row starts.
+ compute(data, splits) {
+ // Validate that the splits are valid indices into data, only if there are
+ // splits specified.
+ const inputDataSize = data.length;
+ const splitsSize = splits.length;
+ if (splitsSize > 0) {
+ let prevSplit = splits[0];
+ if (prevSplit !== 0) {
+ throw new Error(`First split value must be 0, got ${prevSplit}`);
+ }
+ for (let i = 1; i < splitsSize; ++i) {
+ let validSplits = splits[i] >= prevSplit;
+ validSplits = validSplits && (splits[i] <= inputDataSize);
+ if (!validSplits) {
+ throw new Error(`Invalid split value ${splits[i]}, must be in [${prevSplit}, ${inputDataSize}]`);
+ }
+ prevSplit = splits[i];
+ }
+ if (prevSplit !== inputDataSize) {
+ throw new Error(`Last split value must be data size. Expected ${inputDataSize}, got ${prevSplit}`);
+ }
+ }
+ const numBatchItems = splitsSize - 1;
+ const nGramsSplits = tf.util.getArrayFromDType('int32', splitsSize);
+ // If there is no data or size, return an empty ragged tensor.
+ if (inputDataSize === 0 || splitsSize === 0) {
+ const empty = new Array(inputDataSize);
+ for (let i = 0; i <= numBatchItems; ++i) {
+ nGramsSplits[i] = 0;
+ }
+ return [empty, nGramsSplits];
+ }
+ nGramsSplits[0] = 0;
+ for (let i = 1; i <= numBatchItems; ++i) {
+ const length = splits[i] - splits[i - 1];
+ let numNGrams = 0;
+ this.nGramWidths.forEach((nGramWidth) => {
+ numNGrams += this.getNumNGrams(length, nGramWidth);
+ });
+ if (this.preserveShort && length > 0 && numNGrams === 0) {
+ numNGrams = 1;
+ }
+ nGramsSplits[i] = nGramsSplits[i - 1] + numNGrams;
+ }
+ const nGrams = new Array(nGramsSplits[numBatchItems]);
+ for (let i = 0; i < numBatchItems; ++i) {
+ const splitIndex = splits[i];
+ let outputStartIdx = nGramsSplits[i];
+ this.nGramWidths.forEach((nGramWidth) => {
+ const length = splits[i + 1] - splits[i];
+ const numNGrams = this.getNumNGrams(length, nGramWidth);
+ this.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);
+ outputStartIdx += numNGrams;
+ });
+ // If we're preserving short sequences, check to see if no sequence was
+ // generated by comparing the current output start idx to the original
+ // one (nGramSplitsdata). If no ngrams were generated, then they will
+ // be equal (since we increment outputStartIdx by numNGrams every
+ // time we create a set of ngrams.)
+ if (this.preserveShort && outputStartIdx === nGramsSplits[i]) {
+ const dataLength = splits[i + 1] - splits[i];
+ // One legitimate reason to not have any ngrams when this.preserveShort
+ // is true is if the sequence itself is empty. In that case, move on.
+ if (dataLength === 0) {
+ continue;
+ }
+ // We don't have to worry about dynamic padding sizes here: if padding
+ // was dynamic, every sequence would have had sufficient padding to
+ // generate at least one nGram.
+ const nGramWidth = dataLength + 2 * this.padWidth;
+ const numNGrams = 1;
+ this.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);
+ }
+ }
+ return [nGrams, nGramsSplits];
+ }
+ }
+ function stringNGramsImpl(data, dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {
+ return new StringNGramsOp(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences)
+ .compute(data, dataSplits);
+ }
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function split(str, delimiters, skipEmpty) {
+ if (!str.length) {
+ return [];
+ }
+ // When the delimiter is empty, the input is split into individual characters.
+ if (delimiters.length === 0) {
+ const result = new Array(str.length);
+ for (let i = 0; i < str.length; ++i) {
+ result[i] = str.subarray(i, i + 1);
+ }
+ return result;
+ }
+ // When there is one delimiter, the input is split only at that delimiter.
+ if (delimiters.length === 1) {
+ const delimiter = delimiters[0];
+ const result = [];
+ let f = str.indexOf(delimiter);
+ while (f !== -1) {
+ const token = str.subarray(0, f);
+ if (!skipEmpty || token.length !== 0) {
+ result.push(token);
+ }
+ str = str.subarray(f + 1);
+ f = str.indexOf(delimiter);
+ }
+ if (!skipEmpty || str.length !== 0) {
+ result.push(str);
+ }
+ return result;
+ }
+ // When there are multiple delimiters, the input is split at every instance
+ // one of the delimiters appears.
+ const result = [];
+ let tokenStart = 0;
+ for (let i = 0; i < str.length + 1; i++) {
+ if ((i === str.length) || (delimiters.indexOf(str[i]) !== -1)) {
+ const token = str.subarray(tokenStart, i);
+ if (!skipEmpty || token.length !== 0) {
+ result.push(token);
+ }
+ tokenStart = i + 1;
+ }
+ }
+ return result;
+ }
+ function stringSplitImpl(input, delimiter, skipEmpty) {
+ const batchSize = input.length;
+ // Empty delimiter means split the input character by character.
+ const tokens = [];
+ let outputSize = 0;
+ let maxNumEntries = 0;
+ const numIndices = new Array(batchSize);
+ for (let i = 0; i < batchSize; ++i) {
+ const parts = split(input[i], delimiter, skipEmpty);
+ const nEntries = parts.length;
+ numIndices[i] = nEntries;
+ outputSize += nEntries;
+ maxNumEntries = Math.max(maxNumEntries, nEntries);
+ tokens.push(...parts);
+ }
+ const indices = tf.util.getArrayFromDType('int32', outputSize * 2);
+ const values = new Array(outputSize);
+ const shape = [batchSize, maxNumEntries];
+ let c = 0;
+ for (let i = 0; i < batchSize; ++i) {
+ for (let j = 0; j < numIndices[i]; ++j) {
+ // indices is a 2d tensor with shape of [outputSize, 2]
+ indices[c * 2] = i;
+ indices[c * 2 + 1] = j;
+ values[c] = tokens[c];
+ ++c;
+ }
+ }
+ return [indices, values, shape];
+ }
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function stringToHashBucketFastImpl(input, numBuckets) {
+ const output = tf.util.getArrayFromDType('int32', input.length);
+ for (let i = 0; i < input.length; ++i) {
+ output[i] =
+ tf.util.fingerPrint64(input[i]).modulo(numBuckets).getLowBitsUnsigned();
+ }
+ return output;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ const subImpl = createSimpleBinaryKernelImpl(((aValue, bValue) => aValue - bValue));
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * An implementation of the tile kernel shared between webgl and cpu for string
+ * tensors only.
+ */
+ function tileImpl(xBuf, reps) {
+ const newShape = new Array(xBuf.rank);
+ for (let i = 0; i < newShape.length; i++) {
+ newShape[i] = xBuf.shape[i] * reps[i];
+ }
+ const result = tf.buffer(newShape, xBuf.dtype);
+ for (let i = 0; i < result.values.length; ++i) {
+ const newLoc = result.indexToLoc(i);
+ const originalLoc = new Array(xBuf.rank);
+ for (let j = 0; j < originalLoc.length; j++) {
+ originalLoc[j] = newLoc[j] % xBuf.shape[j];
+ }
+ const originalIndex = xBuf.locToIndex(originalLoc);
+ result.values[i] = xBuf.values[originalIndex];
+ }
+ return result;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function topKImpl(x, xShape, xDtype, k, sorted) {
+ // Reshape into a 2d tensor [batch, lastDim] and compute topk along lastDim.
+ const lastDim = xShape[xShape.length - 1];
+ const [batch, size] = [x.length / lastDim, lastDim];
+ const allTopKVals = tf.util.getTypedArrayFromDType(xDtype, batch * k);
+ const allTopKIndices = tf.util.getTypedArrayFromDType('int32', batch * k);
+ for (let b = 0; b < batch; b++) {
+ const offset = b * size;
+ const vals = x.subarray(offset, offset + size);
+ const valAndInd = [];
+ for (let i = 0; i < vals.length; i++) {
+ valAndInd.push({ value: vals[i], index: i });
+ }
+ valAndInd.sort((a, b) => b.value - a.value);
+ const outOffset = b * k;
+ const topKVals = allTopKVals.subarray(outOffset, outOffset + k);
+ const topKIndices = allTopKIndices.subarray(outOffset, outOffset + k);
+ for (let i = 0; i < k; i++) {
+ topKVals[i] = valAndInd[i].value;
+ topKIndices[i] = valAndInd[i].index;
+ }
+ }
+ // Reshape back to the original input shape, except that the last
+ // dimension is k.
+ const outputShape = xShape.slice();
+ outputShape[outputShape.length - 1] = k;
+ return [
+ tf.buffer(outputShape, xDtype, allTopKVals),
+ tf.buffer(outputShape, 'int32', allTopKIndices)
+ ];
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function uniqueImpl(values, axis, shape, dtype) {
+ // Normalize and validate axis.
+ const $axis = tf.util.parseAxisParam(axis, shape)[0];
+ // Calculate the new shape that is suitable for extracting data along the
+ // given axis.
+ //
+ // The rank is 3.
+ // The size of the 1st dimension is the size of all the axes < the given axis.
+ // The size of the 2nd dimension is the same as the size of the given axis.
+ // The size of the 3rd dimension is the size of all the axes > the given axis.
+ //
+ // For example, for a 4D tensor with shape=[2, 3, 5, 4] and axis=2, the
+ // newShape would be: [2*3, 5, 4].
+ //
+ // Note that this is not the final output shape. This will be the shape for an
+ // intermediate TensorBuffer (see inputBuffer below) to allow us to extract
+ // values along the given axis. To demonstrate how it works, consider the
+ // following example:
+ //
+ // Input: a 3D tensor, with shape [1, 2, 3]
+ // [
+ // [
+ // [1,2,3],
+ // [4,5,6]
+ // ]
+ // ]
+ // Axis: 2 (the last axis).
+ // Along axis 2, we expect to extract 3 tensors: [1,4], [2,5], [3,6].
+ //
+ // For this example, newShape would be: [2, 3, 1], where 2 is calculated from
+ // 1*2. The re-shaped data would look like:
+ //
+ // [
+ // [
+ // [1], [2], [3]
+ // ],
+ // [
+ // [4], [5], [6]
+ // ]
+ // ]
+ //
+ // Then, we can construct a 3-level nested loop by the following dimension
+ // order to extract the values along the axis (dimension1):
+ // i: dimension1 // 0,1,2 (newShape[1])
+ // m: dimension0 // 0,1 (newShape[0])
+ // n: dimension2 // 0 (newShape[2])
+ //
+ // m, i, n
+ // ---------
+ // Iteration 0: data at [0, 0, 0] => "1"
+ // Iteration 1: data at [1, 0, 0] => "4"
+ // We got [1,4].
+ // Iteration 2: data at [0, 1, 0] => "2"
+ // Iteration 3: data at [1, 1, 0] => "5"
+ // We got [2,5].
+ // Iteration 4: data at [0, 2, 0] => "3"
+ // Iteration 5: data at [1, 2, 0] => "6"
+ // We got [3,6].
+ const newShape = [1, shape[0], 1];
+ for (let i = 0; i < $axis; i++) {
+ newShape[0] *= shape[i];
+ }
+ newShape[1] = shape[$axis];
+ for (let i = $axis + 1; i < shape.length; i++) {
+ newShape[2] *= shape[i];
+ }
+ // A map from unique elements (their string representations) to their values
+ // in "indices" (below).
+ const uniqueElements = {};
+ // The indices of each unique element in the original tensor along the given
+ // axis. It is 1D and has the same size as the given axis.
+ const indices = new Int32Array(shape[$axis]);
+ // Create a buffer so we can easily extract value at a given location.
+ const inputBuffer = new tf.TensorBuffer(newShape, dtype, values);
+ // The indices along the given axis that have unique elements. This is a
+ // de-duped version of "indices" above.
+ const uniqueIndices = [];
+ const is1DTensor = newShape[0] === 1 && newShape[2] === 1;
+ for (let i = 0; i < shape[$axis]; i++) {
+ // Extract values along the axis.
+ let element;
+ if (is1DTensor) {
+ // Fast path for 1D tensor input.
+ element = values[i].toString();
+ }
+ else {
+ const axisValues = [];
+ for (let m = 0; m < newShape[0]; m++) {
+ for (let n = 0; n < newShape[2]; n++) {
+ axisValues.push(inputBuffer.get(m, i, n));
+ }
+ }
+ element = axisValues.join(',');
+ }
+ // Dedup and update various indices.
+ if (uniqueElements[element] !== undefined) {
+ indices[i] = uniqueElements[element];
+ }
+ else {
+ const uniqueIndex = Object.keys(uniqueElements).length;
+ uniqueElements[element] = uniqueIndex;
+ indices[i] = uniqueIndex;
+ uniqueIndices.push(i);
+ }
+ }
+ // Now we know where each of the unique elements are located along the axis
+ // (uniqueIndices). Extract them from input buffer and store them in the
+ // output buffer.
+ const outputTmpShape = newShape.slice();
+ outputTmpShape[1] = Object.keys(uniqueElements).length;
+ const outputBuffer = new tf.TensorBuffer(outputTmpShape, dtype);
+ uniqueIndices.forEach((uniqueElementIndex, i) => {
+ for (let m = 0; m < newShape[0]; m++) {
+ for (let n = 0; n < newShape[2]; n++) {
+ outputBuffer.set(inputBuffer.get(m, uniqueElementIndex, n), m, i, n);
+ }
+ }
+ });
+ // The output shape can be calculated from the input shape with the size of
+ // the given axis replaced by the number of unique elements along that axis.
+ const outputShape = shape.slice();
+ outputShape[$axis] = outputTmpShape[1];
+ return {
+ outputValues: outputBuffer.values,
+ outputShape,
+ indices,
+ };
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var addImplCPU = addImpl, bincountImplCPU = bincountImpl, bincountReduceImplCPU = bincountReduceImpl, ceilImplCPU = ceilImpl, concatImplCPU = concatImpl, equalImplCPU = equalImpl, expImplCPU = expImpl, expm1ImplCPU = expm1Impl, floorImplCPU = floorImpl, gatherNdImplCPU = gatherNdImpl, gatherV2ImplCPU = gatherV2Impl, greaterImplCPU = greaterImpl, greaterEqualImplCPU = greaterEqualImpl, lessImplCPU = lessImpl, lessEqualImplCPU = lessEqualImpl, linSpaceImplCPU = linSpaceImpl, logImplCPU = logImpl, maxImplCPU = maxImpl, maximumImplCPU = maximumImpl, minimumImplCPU = minimumImpl, multiplyImplCPU = multiplyImpl, negImplCPU = negImpl, notEqualImplCPU = notEqualImpl, prodImplCPU = prodImpl, rangeImplCPU = rangeImpl, rsqrtImplCPU = rsqrtImpl, simpleAbsImplCPU = simpleAbsImpl, sliceImplCPU = sliceImpl, sparseFillEmptyRowsImplCPU = sparseFillEmptyRowsImpl, sparseReshapeImplCPU = sparseReshapeImpl, sparseSegmentReductionImplCPU = sparseSegmentReductionImpl, stridedSliceImplCPU = stridedSliceImpl, stringNGramsImplCPU = stringNGramsImpl, stringSplitImplCPU = stringSplitImpl, stringToHashBucketFastImplCPU = stringToHashBucketFastImpl, subImplCPU = subImpl, tileImplCPU = tileImpl, topKImplCPU = topKImpl, transposeImplCPU = transposeImpl, uniqueImplCPU = uniqueImpl;
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function getVecChannels(name, rank) {
+ return ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, rank).map(function (d) { return name + "." + d; });
+ }
+ function getChannels(name, rank) {
+ if (rank === 1) {
+ return [name];
+ }
+ return getVecChannels(name, rank);
+ }
+ function getSourceCoords(rank, dims) {
+ if (rank === 1) {
+ return 'rc';
+ }
+ var coords = '';
+ for (var i = 0; i < rank; i++) {
+ coords += dims[i];
+ if (i < rank - 1) {
+ coords += ',';
+ }
+ }
+ return coords;
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var PackProgram = /** @class */ (function () {
+ function PackProgram(outputShape) {
+ this.variableNames = ['A'];
+ this.packedInputs = false;
+ this.packedOutput = true;
+ // Only input / output 3D tensors.
+ this.outputShape = outputShape;
+ var rank = outputShape.length;
+ if (rank === 0) {
+ this.userCode = "\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";
+ }
+ else {
+ var channels = getChannels('rc', rank);
+ var dtype = getCoordsDataType(rank);
+ var outOfBoundsCondition = getOutOfBoundsCondition(rank, outputShape, channels);
+ var setup = getSetup(rank, outputShape[outputShape.length - 1], outputShape[outputShape.length - 2], channels);
+ var output = getOutput(outputShape, channels);
+ this.userCode = "\n void main() {\n " + dtype + " rc = getOutputCoords();\n\n if(" + outOfBoundsCondition + ") {\n setOutput(vec4(0));\n } else {\n " + setup + "\n\n setOutput(vec4(" + output + "));\n }\n }\n ";
+ }
+ }
+ return PackProgram;
+ }());
+ function getSourceCoordsArr(rank, dims) {
+ var coords = [];
+ for (var row = 0; row <= 1; row++) {
+ for (var col = 0; col <= 1; col++) {
+ var coord = (row === 0 ? 'r' : 'rp1') + ", " + (col === 0 ? 'c' : 'cp1');
+ for (var d = 2; d < rank; d++) {
+ coord = dims[dims.length - 1 - d] + "," + coord;
+ }
+ coords.push(coord);
+ }
+ }
+ return coords;
+ }
+ function getOutOfBoundsCondition(rank, shape, dims) {
+ if (rank === 1) {
+ return "rc > " + shape[0];
+ }
+ var cond = '';
+ for (var i = rank - 2; i < rank; i++) {
+ cond += dims[i] + " >= " + shape[i];
+ if (i < rank - 1) {
+ cond += '||';
+ }
+ }
+ return cond;
+ }
+ function getSetup(rank, cols, rows, dims) {
+ if (rank === 1) {
+ return '';
+ }
+ var innerDims = dims.slice(-2);
+ return "\n int r = " + innerDims[0] + ";\n int c = " + innerDims[1] + ";\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= " + cols + ";\n bool rEdge = rp1 >= " + rows + ";\n ";
+ }
+ function getOutput(shape, dims) {
+ var rank = shape.length;
+ var sourceCoords = getSourceCoordsArr(rank, dims);
+ if (rank === 1) {
+ return "getA(rc),\n rc + 1 >= " + shape[0] + " ? 0. : getA(rc + 1),\n 0, 0";
+ }
+ return "getA(" + sourceCoords[0] + "),\n cEdge ? 0. : getA(" + sourceCoords[1] + "),\n rEdge ? 0. : getA(" + sourceCoords[2] + "),\n rEdge || cEdge ? 0. : getA(" + sourceCoords[3] + ")";
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ReshapePackedProgram = /** @class */ (function () {
+ function ReshapePackedProgram(outputShape, inputShape) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = outputShape;
+ var mainLoop = "";
+ for (var i = 0; i < 4; i++) {
+ var thisRC = "thisRC = rc;";
+ if (i % 2 === 1) {
+ thisRC += "thisRC.z += 1;";
+ }
+ if (i > 1) {
+ thisRC += "thisRC.y += 1;";
+ }
+ mainLoop += "\n " + thisRC + "\n " + (i > 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[" + i + "] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n " + (i > 0 ? '}' : '') + "\n ";
+ }
+ this.userCode = "\n " + getReshapedInputCoords(inputShape) + "\n " + getFlatIndexFrom3D(outputShape) + "\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = " + outputShape[1] + ";\n int cols = " + outputShape[2] + ";\n\n " + mainLoop + "\n\n setOutput(result);\n }\n ";
+ }
+ return ReshapePackedProgram;
+ }());
+ function getReshapedInputCoords(shape) {
+ var coordsFromIndexSnippet = getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd'], shape);
+ return "\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n " + coordsFromIndexSnippet + "\n return ivec3(r, c, d);\n }\n ";
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var TextureManager = /** @class */ (function () {
+ function TextureManager(gpgpu) {
+ this.gpgpu = gpgpu;
+ this.numUsedTextures = 0;
+ this.numFreeTextures = 0;
+ this._numBytesAllocated = 0;
+ this._numBytesFree = 0; // How many bytes that have been allocated
+ // are available for reuse.
+ this.freeTextures = {};
+ this.logEnabled = false;
+ this.usedTextures = {};
+ }
+ TextureManager.prototype.acquireTexture = function (shapeRC, usage, isPacked) {
+ var physicalTexType = getPhysicalFromLogicalTextureType(usage, isPacked);
+ var shapeKey = getKeyFromTextureShape(shapeRC, physicalTexType, isPacked);
+ if (!(shapeKey in this.freeTextures)) {
+ this.freeTextures[shapeKey] = [];
+ }
+ if (!(shapeKey in this.usedTextures)) {
+ this.usedTextures[shapeKey] = [];
+ }
+ var texBytes = computeBytes(shapeRC, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig, isPacked);
+ if (this.freeTextures[shapeKey].length > 0) {
+ this.numFreeTextures--;
+ this.numUsedTextures++;
+ this._numBytesFree -= texBytes;
+ this.log();
+ var newTexture_1 = this.freeTextures[shapeKey].shift();
+ this.usedTextures[shapeKey].push(newTexture_1);
+ return newTexture_1;
+ }
+ var newTexture;
+ if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT32) {
+ newTexture = this.gpgpu.createPackedMatrixTexture(shapeRC[0], shapeRC[1]);
+ }
+ else if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT16) {
+ newTexture =
+ this.gpgpu.createFloat16PackedMatrixTexture(shapeRC[0], shapeRC[1]);
+ }
+ else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT32) {
+ newTexture =
+ this.gpgpu.createFloat32MatrixTexture(shapeRC[0], shapeRC[1]);
+ }
+ else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT16) {
+ newTexture =
+ this.gpgpu.createFloat16MatrixTexture(shapeRC[0], shapeRC[1]);
+ }
+ else if (physicalTexType === PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE) {
+ newTexture =
+ this.gpgpu.createUnsignedBytesMatrixTexture(shapeRC[0], shapeRC[1]);
+ }
+ this.usedTextures[shapeKey].push(newTexture);
+ this.numUsedTextures++;
+ this._numBytesAllocated += texBytes;
+ this.log();
+ return newTexture;
+ };
+ TextureManager.prototype.releaseTexture = function (texture, shape, logicalTexType, isPacked) {
+ if (this.freeTextures == null) {
+ // Already disposed.
+ return;
+ }
+ var physicalTexType = getPhysicalFromLogicalTextureType(logicalTexType, isPacked);
+ var shapeKey = getKeyFromTextureShape(shape, physicalTexType, isPacked);
+ if (!(shapeKey in this.freeTextures)) {
+ this.freeTextures[shapeKey] = [];
+ }
+ var texBytes = computeBytes(shape, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig, isPacked);
+ var deleteTexThreshold = tf.env().get('WEBGL_DELETE_TEXTURE_THRESHOLD');
+ if (deleteTexThreshold !== -1 &&
+ this._numBytesAllocated > deleteTexThreshold) {
+ this.gpgpu.deleteMatrixTexture(texture);
+ this._numBytesAllocated -= texBytes;
+ }
+ else {
+ this.freeTextures[shapeKey].push(texture);
+ this.numFreeTextures++;
+ this._numBytesFree += texBytes;
+ }
+ this.numUsedTextures--;
+ var texList = this.usedTextures[shapeKey];
+ var texIndex = texList.indexOf(texture);
+ if (texIndex < 0) {
+ throw new Error('Cannot release a texture that was never provided by this ' +
+ 'texture manager');
+ }
+ texList.splice(texIndex, 1);
+ this.log();
+ };
+ TextureManager.prototype.log = function () {
+ if (!this.logEnabled) {
+ return;
+ }
+ var total = this.numFreeTextures + this.numUsedTextures;
+ console.log('Free/Used', this.numFreeTextures + " / " + this.numUsedTextures, "(" + total + ")");
+ var freeRatio = this._numBytesFree / this._numBytesAllocated;
+ console.log("Bytes allocated: " + this._numBytesAllocated);
+ console.log("Bytes unused: " + this._numBytesFree + " (" + Math.round(100 * freeRatio) + "%)");
+ };
+ Object.defineProperty(TextureManager.prototype, "numBytesAllocated", {
+ get: function () {
+ return this._numBytesAllocated;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(TextureManager.prototype, "numBytesFree", {
+ get: function () {
+ return this._numBytesFree;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ TextureManager.prototype.getNumUsedTextures = function () {
+ return this.numUsedTextures;
+ };
+ TextureManager.prototype.getNumFreeTextures = function () {
+ return this.numFreeTextures;
+ };
+ TextureManager.prototype.dispose = function () {
+ var _this = this;
+ if (this.freeTextures == null) {
+ // Already disposed.
+ return;
+ }
+ for (var texShape in this.freeTextures) {
+ this.freeTextures[texShape].forEach(function (tex) {
+ _this.gpgpu.deleteMatrixTexture(tex);
+ });
+ }
+ for (var texShape in this.usedTextures) {
+ this.usedTextures[texShape].forEach(function (tex) {
+ _this.gpgpu.deleteMatrixTexture(tex);
+ });
+ }
+ this.freeTextures = null;
+ this.usedTextures = null;
+ this.numUsedTextures = 0;
+ this.numFreeTextures = 0;
+ this._numBytesAllocated = 0;
+ this._numBytesFree = 0;
+ };
+ return TextureManager;
+ }());
+ function numBytesForInternalFormat(gl, internalFormat) {
+ // tslint:disable-next-line:no-any
+ var glany = gl;
+ if (internalFormat === glany.R32F) {
+ return 4;
+ }
+ else if (internalFormat === glany.R16F) {
+ return 2;
+ }
+ else if (internalFormat === glany.RGBA32F) {
+ return 16;
+ }
+ else if (internalFormat === gl.RGBA) {
+ return 16;
+ }
+ else if (internalFormat === glany.RGBA16F) {
+ return 8;
+ }
+ throw new Error("Unknown internal format " + internalFormat);
+ }
+ function computeBytes(shape, physicalTexType, gl, textureConfig, isPacked) {
+ // It is not possible to infer packed status from the texture type because
+ // depending on the textureConfig, different texture types may resolve to the
+ // same internal format (e.g. in WebGL1, the internal format for
+ // UNPACKED_FLOAT16 textures is gl.RGBA). Therefore we pass in `isPacked`
+ // explicitly.
+ var internalFormat = internalFormatForPhysicalTexType(physicalTexType, textureConfig);
+ var numElements;
+ if (isPacked) {
+ var _a = getPackedMatrixTextureShapeWidthHeight(shape[0], shape[1]), packedWidth = _a[0], packedHeight = _a[1];
+ numElements = packedWidth * packedHeight;
+ }
+ else {
+ var _b = getUnpackedMatrixTextureShapeWidthHeight(shape[0], shape[1]), width = _b[0], height = _b[1];
+ numElements = width * height;
+ }
+ var bytesPerElement = numBytesForInternalFormat(gl, internalFormat);
+ return numElements * bytesPerElement;
+ }
+ function internalFormatForPhysicalTexType(physicalTexType, textureConfig) {
+ switch (physicalTexType) {
+ case PhysicalTextureType.PACKED_2X2_FLOAT32:
+ return getInternalFormatForPackedMatrixTexture(textureConfig);
+ case PhysicalTextureType.PACKED_2X2_FLOAT16:
+ return getInternalFormatForFloat16PackedMatrixTexture(textureConfig);
+ case PhysicalTextureType.UNPACKED_FLOAT32:
+ return getInternalFormatForFloat32MatrixTexture(textureConfig);
+ case PhysicalTextureType.UNPACKED_FLOAT16:
+ return getInternalFormatForFloat16MatrixTexture(textureConfig);
+ case PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE:
+ return getInternalFormatForUnsignedBytesMatrixTexture(textureConfig);
+ default:
+ throw new Error("Unknown physical texture type " + physicalTexType);
+ }
+ }
+ function getPhysicalTextureForRendering(isPacked) {
+ if (tf.env().getBool('WEBGL_RENDER_FLOAT32_ENABLED')) {
+ if (isPacked) {
+ return PhysicalTextureType.PACKED_2X2_FLOAT32;
+ }
+ return PhysicalTextureType.UNPACKED_FLOAT32;
+ }
+ if (isPacked) {
+ return PhysicalTextureType.PACKED_2X2_FLOAT16;
+ }
+ return PhysicalTextureType.UNPACKED_FLOAT16;
+ }
+ function getPhysicalFromLogicalTextureType(logicalTexType, isPacked) {
+ if (logicalTexType === TextureUsage.UPLOAD) {
+ return PhysicalTextureType.PACKED_2X2_FLOAT32;
+ }
+ else if (logicalTexType === TextureUsage.RENDER || logicalTexType == null) {
+ return getPhysicalTextureForRendering(isPacked);
+ }
+ else if (logicalTexType === TextureUsage.DOWNLOAD ||
+ logicalTexType === TextureUsage.PIXELS) {
+ return PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE;
+ }
+ throw new Error("Unknown logical texture type " + logicalTexType);
+ }
+ function getKeyFromTextureShape(shapeRowsCol, physicalTexType, isPacked) {
+ return shapeRowsCol[0] + "_" + shapeRowsCol[1] + "_" + physicalTexType + "_" + isPacked;
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var UnaryOpProgram = /** @class */ (function () {
+ function UnaryOpProgram(aShape, opSnippet) {
+ this.variableNames = ['A'];
+ this.outputShape = aShape;
+ this.userCode = "\n float unaryOperation(float x) {\n " + opSnippet + "\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n ";
+ }
+ return UnaryOpProgram;
+ }());
+ var CHECK_NAN_SNIPPET = "if (isnan(x)) return x;";
+ var LINEAR = "return x;";
+ var ABS = "return abs(x);";
+ var ELU = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
+ var RELU = CHECK_NAN_SNIPPET + "\n return (x < 0.0) ? 0.0 : x;\n";
+ var RELU6 = CHECK_NAN_SNIPPET + "\n return (x < 0.0) ? 0.0 : min(6.0, x);\n";
+ var CLONE = 'return x;';
+ var SIGMOID = "return 1.0 / (1.0 + exp(-1.0 * x));";
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LINEAR$1 = "return x;";
+ var ELU$1 = "\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n";
+ var RELU$1 = "\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n";
+ var RELU6$1 = "\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n";
+ var SIGMOID$1 = "return 1.0 / (1.0 + exp(-1.0 * x));";
+ var UnaryOpPackedProgram = /** @class */ (function () {
+ function UnaryOpPackedProgram(aShape, opSnippet) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = aShape;
+ this.userCode = "\n vec4 unaryOperation(vec4 x) {\n " + opSnippet + "\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n ";
+ }
+ return UnaryOpPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var UnpackProgram = /** @class */ (function () {
+ function UnpackProgram(outputShape) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = false;
+ this.outputShape = outputShape;
+ var rank = outputShape.length;
+ var channels = getChannels('rc', rank);
+ var dtype = getCoordsDataType(rank);
+ var sourceCoords = getSourceCoords(rank, channels);
+ var innerDims = channels.slice(-2);
+ var coords = rank <= 1 ? 'rc' : "vec2(" + innerDims.join(',') + ")";
+ this.userCode = "\n void main() {\n " + dtype + " rc = getOutputCoords();\n vec4 packedInput = getA(" + sourceCoords + ");\n\n setOutput(getChannel(packedInput, " + coords + "));\n }\n ";
+ }
+ return UnpackProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var whereImpl = tf.kernel_impls.whereImpl;
+ var EPSILON_FLOAT32 = 1e-7;
+ var EPSILON_FLOAT16 = 1e-4;
+ var binaryCaches = {};
+ function getBinaryCache(webGLVersion) {
+ if (webGLVersion in binaryCaches) {
+ return binaryCaches[webGLVersion];
+ }
+ binaryCaches[webGLVersion] = {};
+ return binaryCaches[webGLVersion];
+ }
+ // Empirically determined constant used to determine size threshold for handing
+ // off execution to the CPU.
+ var CPU_HANDOFF_SIZE_THRESHOLD = tf.env().getNumber('CPU_HANDOFF_SIZE_THRESHOLD');
+ // Empirically determined constant used to decide the number of MB on GPU
+ // before we warn about high memory use. The MB are this constant * screen area
+ // * dpi / 1024 / 1024.
+ var BEFORE_PAGING_CONSTANT = 600;
+ function numMBBeforeWarning() {
+ if (tf.env().global.screen == null) {
+ return 1024; // 1 GB.
+ }
+ return (tf.env().global.screen.height * tf.env().global.screen.width *
+ window.devicePixelRatio) *
+ BEFORE_PAGING_CONSTANT / 1024 / 1024;
+ }
+ var MathBackendWebGL = /** @class */ (function (_super) {
+ __extends(MathBackendWebGL, _super);
+ function MathBackendWebGL(gpgpu) {
+ var _this = _super.call(this) || this;
+ // Maps data ids that have a pending read operation, to list of subscribers.
+ _this.pendingRead = new WeakMap();
+ // List of data ids that are scheduled for disposal, but are waiting on a
+ // pending read operation.
+ _this.pendingDisposal = new WeakSet();
+ // Used to count the number of 'shallow' sliced tensors that point to the
+ // same data id.
+ _this.dataRefCount = new WeakMap();
+ _this.numBytesInGPU = 0;
+ // Accumulated time spent (including blocking) in uploading data to webgl.
+ _this.uploadWaitMs = 0;
+ // Accumulated time spent (including blocking in downloading data from webgl.
+ _this.downloadWaitMs = 0;
+ // record the last manual GL Flush time.
+ _this.lastGlFlushTime = 0;
+ _this.warnedAboutMemory = false;
+ _this.pendingDeletes = 0;
+ _this.disposed = false;
+ if (!tf.env().getBool('HAS_WEBGL')) {
+ throw new Error('WebGL is not supported on this device');
+ }
+ if (gpgpu == null) {
+ var gl = getWebGLContext(tf.env().getNumber('WEBGL_VERSION'));
+ _this.binaryCache = getBinaryCache(tf.env().getNumber('WEBGL_VERSION'));
+ _this.gpgpu = new GPGPUContext(gl);
+ _this.canvas = gl.canvas;
+ _this.gpgpuCreatedLocally = true;
+ }
+ else {
+ _this.gpgpu = gpgpu;
+ _this.binaryCache = {};
+ _this.gpgpuCreatedLocally = false;
+ _this.canvas = gpgpu.gl.canvas;
+ }
+ _this.textureManager = new TextureManager(_this.gpgpu);
+ _this.numMBBeforeWarning = numMBBeforeWarning();
+ _this.texData = new tf.DataStorage(_this, tf.engine());
+ return _this;
+ }
+ MathBackendWebGL.prototype.nextDataId = function () {
+ return MathBackendWebGL.nextDataId++;
+ };
+ MathBackendWebGL.prototype.numDataIds = function () {
+ return this.texData.numDataIds() - this.pendingDeletes;
+ };
+ MathBackendWebGL.prototype.write = function (values, shape, dtype) {
+ if (tf.env().getBool('WEBGL_CHECK_NUMERICAL_PROBLEMS') ||
+ tf.env().getBool('DEBUG')) {
+ this.checkNumericalProblems(values);
+ }
+ if (dtype === 'complex64' && values != null) {
+ throw new Error("Cannot write to a complex64 dtype. " +
+ "Please use tf.complex(real, imag).");
+ }
+ var dataId = { id: this.nextDataId() };
+ this.texData.set(dataId, { shape: shape, dtype: dtype, values: values, usage: TextureUsage.UPLOAD, refCount: 1 });
+ return dataId;
+ };
+ /** Return refCount of a `TensorData`. */
+ MathBackendWebGL.prototype.refCount = function (dataId) {
+ if (this.texData.has(dataId)) {
+ var tensorData = this.texData.get(dataId);
+ return tensorData.refCount;
+ }
+ return 0;
+ };
+ /** Increase refCount of a `TextureData`. */
+ MathBackendWebGL.prototype.incRef = function (dataId) {
+ var texData = this.texData.get(dataId);
+ texData.refCount++;
+ };
+ /** Decrease refCount of a `TextureData`. */
+ MathBackendWebGL.prototype.decRef = function (dataId) {
+ if (this.texData.has(dataId)) {
+ var texData = this.texData.get(dataId);
+ texData.refCount--;
+ }
+ };
+ MathBackendWebGL.prototype.move = function (dataId, values, shape, dtype, refCount) {
+ if (tf.env().getBool('DEBUG')) {
+ this.checkNumericalProblems(values);
+ }
+ if (dtype === 'complex64') {
+ throw new Error("Cannot write to a complex64 dtype. " +
+ "Please use tf.complex(real, imag).");
+ }
+ this.texData.set(dataId, { shape: shape, dtype: dtype, values: values, usage: TextureUsage.UPLOAD, refCount: refCount });
+ };
+ MathBackendWebGL.prototype.disposeIntermediateTensorInfo = function (tensorInfo) {
+ this.disposeData(tensorInfo.dataId);
+ };
+ MathBackendWebGL.prototype.readSync = function (dataId) {
+ var texData = this.texData.get(dataId);
+ var values = texData.values, dtype = texData.dtype, complexTensorInfos = texData.complexTensorInfos, slice = texData.slice, shape = texData.shape, isPacked = texData.isPacked;
+ // The presence of `slice` indicates this tensor is a shallow slice of a
+ // different tensor, and is using that original tensor's texture. Run
+ // `clone` in order to copy that texture and read from it.
+ if (slice != null) {
+ var program = void 0;
+ if (isPacked) {
+ program = new UnaryOpPackedProgram(shape, CLONE);
+ }
+ else {
+ program = new UnaryOpProgram(shape, CLONE);
+ }
+ var res = this.runWebGLProgram(program, [{ dataId: dataId, shape: shape, dtype: dtype }], dtype);
+ var data = this.readSync(res.dataId);
+ this.disposeIntermediateTensorInfo(res);
+ return data;
+ }
+ if (values != null) {
+ return this.convertAndCacheOnCPU(dataId);
+ }
+ if (dtype === 'string') {
+ return values;
+ }
+ var shouldTimeProgram = this.activeTimers != null;
+ var start;
+ if (shouldTimeProgram) {
+ start = tf.util.now();
+ }
+ var result;
+ if (dtype === 'complex64') {
+ var realValues = this.readSync(complexTensorInfos.real.dataId);
+ var imagValues = this.readSync(complexTensorInfos.imag.dataId);
+ result = tf.backend_util.mergeRealAndImagArrays(realValues, imagValues);
+ }
+ else {
+ result = this.getValuesFromTexture(dataId);
+ }
+ if (shouldTimeProgram) {
+ this.downloadWaitMs += tf.util.now() - start;
+ }
+ return this.convertAndCacheOnCPU(dataId, result);
+ };
+ MathBackendWebGL.prototype.read = function (dataId) {
+ return __awaiter(this, void 0, void 0, function () {
+ var subscribers_1, texData, values, shape, slice, dtype, complexTensorInfos, isPacked, program, res, data, buffer, tmpDownloadTarget, tmpData, vals, ps, realValues, imagValues, size, dTypeVals, subscribers;
+ var _a;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ if (this.pendingRead.has(dataId)) {
+ subscribers_1 = this.pendingRead.get(dataId);
+ return [2 /*return*/, new Promise(function (resolve) { return subscribers_1.push(resolve); })];
+ }
+ texData = this.texData.get(dataId);
+ values = texData.values, shape = texData.shape, slice = texData.slice, dtype = texData.dtype, complexTensorInfos = texData.complexTensorInfos, isPacked = texData.isPacked;
+ // The presence of `slice` indicates this tensor is a shallow slice of a
+ // different tensor, and is using that original tensor's texture. Run
+ // `clone` in order to copy that texture and read from it.
+ if (slice != null) {
+ program = void 0;
+ if (isPacked) {
+ program = new UnaryOpPackedProgram(shape, CLONE);
+ }
+ else {
+ program = new UnaryOpProgram(shape, CLONE);
+ }
+ res = this.runWebGLProgram(program, [{ dataId: dataId, shape: shape, dtype: dtype }], dtype);
+ data = this.read(res.dataId);
+ this.disposeIntermediateTensorInfo(res);
+ return [2 /*return*/, data];
+ }
+ if (values != null) {
+ return [2 /*return*/, this.convertAndCacheOnCPU(dataId)];
+ }
+ if (!tf.env().getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED') &&
+ tf.env().getNumber('WEBGL_VERSION') === 2) {
+ throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and " +
+ "WEBGL_VERSION=2 not yet supported.");
+ }
+ buffer = null;
+ if (dtype !== 'complex64' && tf.env().get('WEBGL_BUFFER_SUPPORTED')) {
+ // Possibly copy the texture into a buffer before inserting a fence.
+ tmpDownloadTarget = this.decode(dataId);
+ tmpData = this.texData.get(tmpDownloadTarget.dataId);
+ buffer = (_a = this.gpgpu).createBufferFromTexture.apply(_a, [tmpData.texture].concat(getDenseTexShape(shape)));
+ }
+ this.pendingRead.set(dataId, []);
+ if (!(dtype !== 'complex64')) return [3 /*break*/, 2];
+ // Create a fence and wait for it to resolve.
+ return [4 /*yield*/, this.gpgpu.createAndWaitForFence()];
+ case 1:
+ // Create a fence and wait for it to resolve.
+ _b.sent();
+ _b.label = 2;
+ case 2:
+ if (!(dtype === 'complex64')) return [3 /*break*/, 4];
+ return [4 /*yield*/, Promise.all([
+ this.read(complexTensorInfos.real.dataId),
+ this.read(complexTensorInfos.imag.dataId)
+ ])];
+ case 3:
+ ps = _b.sent();
+ realValues = ps[0];
+ imagValues = ps[1];
+ vals = tf.backend_util.mergeRealAndImagArrays(realValues, imagValues);
+ return [3 /*break*/, 5];
+ case 4:
+ if (buffer == null) {
+ vals = this.getValuesFromTexture(dataId);
+ }
+ else {
+ size = tf.util.sizeFromShape(shape);
+ vals = this.gpgpu.downloadFloat32MatrixFromBuffer(buffer, size);
+ }
+ _b.label = 5;
+ case 5:
+ if (tmpDownloadTarget != null) {
+ this.disposeIntermediateTensorInfo(tmpDownloadTarget);
+ }
+ dTypeVals = this.convertAndCacheOnCPU(dataId, vals);
+ subscribers = this.pendingRead.get(dataId);
+ this.pendingRead.delete(dataId);
+ // Notify all pending reads.
+ subscribers.forEach(function (resolve) { return resolve(dTypeVals); });
+ if (this.pendingDisposal.has(dataId)) {
+ this.pendingDisposal.delete(dataId);
+ if (this.disposeData(dataId)) {
+ tf.engine().removeDataId(dataId, this);
+ }
+ this.pendingDeletes--;
+ }
+ return [2 /*return*/, dTypeVals];
+ }
+ });
+ });
+ };
+ MathBackendWebGL.prototype.bufferSync = function (t) {
+ var data = this.readSync(t.dataId);
+ var decodedData = data;
+ if (t.dtype === 'string') {
+ try {
+ // Decode the bytes into string.
+ decodedData = data.map(function (d) { return tf.util.decodeString(d); });
+ }
+ catch (_a) {
+ throw new Error('Failed to decode encoded string bytes into utf-8');
+ }
+ }
+ return tf.buffer(t.shape, t.dtype, decodedData);
+ };
+ MathBackendWebGL.prototype.checkNumericalProblems = function (values) {
+ if (values == null) {
+ return;
+ }
+ for (var i = 0; i < values.length; i++) {
+ var num = values[i];
+ if (!canBeRepresented(num)) {
+ if (tf.env().getBool('WEBGL_RENDER_FLOAT32_CAPABLE')) {
+ throw Error("The value " + num + " cannot be represented with your " +
+ "current settings. Consider enabling float32 rendering: " +
+ "'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");
+ }
+ throw Error("The value " + num + " cannot be represented on this device.");
+ }
+ }
+ };
+ MathBackendWebGL.prototype.getValuesFromTexture = function (dataId) {
+ var _a;
+ var _b = this.texData.get(dataId), shape = _b.shape, dtype = _b.dtype, isPacked = _b.isPacked;
+ var size = tf.util.sizeFromShape(shape);
+ if (tf.env().getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED')) {
+ var tmpTarget = this.decode(dataId);
+ var tmpData_1 = this.texData.get(tmpTarget.dataId);
+ var vals_1 = (_a = this.gpgpu).downloadMatrixFromPackedTexture.apply(_a, [tmpData_1.texture].concat(getDenseTexShape(shape))).subarray(0, size);
+ this.disposeIntermediateTensorInfo(tmpTarget);
+ return vals_1;
+ }
+ var shouldUsePackedProgram = tf.env().getBool('WEBGL_PACK') && isPacked === true;
+ var outputShape = shouldUsePackedProgram ? getShapeAs3D(shape) : shape;
+ var program = shouldUsePackedProgram ?
+ new EncodeFloatPackedProgram(outputShape) :
+ new EncodeFloatProgram(outputShape);
+ var output = this.runWebGLProgram(program, [{ shape: outputShape, dtype: dtype, dataId: dataId }], 'float32');
+ var tmpData = this.texData.get(output.dataId);
+ var vals = this.gpgpu
+ .downloadByteEncodedFloatMatrixFromOutputTexture(tmpData.texture, tmpData.texShape[0], tmpData.texShape[1])
+ .subarray(0, size);
+ this.disposeIntermediateTensorInfo(output);
+ return vals;
+ };
+ MathBackendWebGL.prototype.timerAvailable = function () {
+ return tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0;
+ };
+ MathBackendWebGL.prototype.time = function (f) {
+ return __awaiter(this, void 0, void 0, function () {
+ var oldActiveTimers, newActiveTimers, outerMostTime, flattenedActiveTimerQueries, flattenedActiveTimerNames, res, kernelMs_1;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ oldActiveTimers = this.activeTimers;
+ newActiveTimers = [];
+ outerMostTime = false;
+ if (this.programTimersStack == null) {
+ this.programTimersStack = newActiveTimers;
+ outerMostTime = true;
+ }
+ else {
+ this.activeTimers.push(newActiveTimers);
+ }
+ this.activeTimers = newActiveTimers;
+ f();
+ flattenedActiveTimerQueries = tf.util.flatten(this.activeTimers.map(function (d) { return d.query; }))
+ .filter(function (d) { return d != null; });
+ flattenedActiveTimerNames = tf.util.flatten(this.activeTimers.map(function (d) { return d.name; }))
+ .filter(function (d) { return d != null; });
+ this.activeTimers = oldActiveTimers;
+ if (outerMostTime) {
+ this.programTimersStack = null;
+ }
+ res = {
+ uploadWaitMs: this.uploadWaitMs,
+ downloadWaitMs: this.downloadWaitMs,
+ kernelMs: null,
+ wallMs: null // will be filled by the engine
+ };
+ if (!(tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0)) return [3 /*break*/, 2];
+ return [4 /*yield*/, Promise.all(flattenedActiveTimerQueries)];
+ case 1:
+ kernelMs_1 = _a.sent();
+ res['kernelMs'] = tf.util.sum(kernelMs_1);
+ res['getExtraProfileInfo'] = function () {
+ return kernelMs_1.map(function (d, i) { return ({ name: flattenedActiveTimerNames[i], ms: d }); })
+ .map(function (d) { return d.name + ": " + d.ms; })
+ .join(', ');
+ };
+ return [3 /*break*/, 3];
+ case 2:
+ res['kernelMs'] = {
+ error: 'WebGL query timers are not supported in this environment.'
+ };
+ _a.label = 3;
+ case 3:
+ this.uploadWaitMs = 0;
+ this.downloadWaitMs = 0;
+ return [2 /*return*/, res];
+ }
+ });
+ });
+ };
+ MathBackendWebGL.prototype.memory = function () {
+ return {
+ unreliable: false,
+ numBytesInGPU: this.numBytesInGPU,
+ numBytesInGPUAllocated: this.textureManager.numBytesAllocated,
+ numBytesInGPUFree: this.textureManager.numBytesFree
+ };
+ };
+ MathBackendWebGL.prototype.startTimer = function () {
+ if (tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {
+ return this.gpgpu.beginQuery();
+ }
+ return { startMs: tf.util.now(), endMs: null };
+ };
+ MathBackendWebGL.prototype.endTimer = function (query) {
+ if (tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {
+ this.gpgpu.endQuery();
+ return query;
+ }
+ query.endMs = tf.util.now();
+ return query;
+ };
+ MathBackendWebGL.prototype.getQueryTime = function (query) {
+ return __awaiter(this, void 0, void 0, function () {
+ var timerQuery;
+ return __generator(this, function (_a) {
+ if (tf.env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {
+ return [2 /*return*/, this.gpgpu.waitForQueryAndGetTime(query)];
+ }
+ timerQuery = query;
+ return [2 /*return*/, timerQuery.endMs - timerQuery.startMs];
+ });
+ });
+ };
+ /**
+ * Decrease the RefCount on the dataId and dispose the memory if the dataId
+ * has 0 refCount. If there are pending read on the data, the disposal would
+ * added to the pending delete queue. Return true if the dataId is removed
+ * from backend or the backend does not contain the dataId, false if the
+ * dataId is not removed. Memory may or may not be released even when dataId
+ * is removed, which also depends on dataRefCount, see `releaseGPU`.
+ * @param dataId
+ * @oaram force Optional, remove the data regardless of refCount
+ */
+ MathBackendWebGL.prototype.disposeData = function (dataId, force) {
+ if (force === void 0) { force = false; }
+ if (this.pendingDisposal.has(dataId)) {
+ return false;
+ }
+ // No-op if already disposed.
+ if (!this.texData.has(dataId)) {
+ return true;
+ }
+ // if force flag is set, change refCount to 0, this would ensure disposal
+ // when added to the pendingDisposal queue. Memory may or may not be
+ // released, which also depends on dataRefCount, see `releaseGPU`.
+ if (force) {
+ this.texData.get(dataId).refCount = 0;
+ }
+ else {
+ this.texData.get(dataId).refCount--;
+ }
+ if (!force && this.texData.get(dataId).refCount > 0) {
+ return false;
+ }
+ if (this.pendingRead.has(dataId)) {
+ this.pendingDisposal.add(dataId);
+ this.pendingDeletes++;
+ return false;
+ }
+ this.releaseGPUData(dataId);
+ var complexTensorInfos = this.texData.get(dataId).complexTensorInfos;
+ if (complexTensorInfos != null) {
+ this.disposeData(complexTensorInfos.real.dataId, force);
+ this.disposeData(complexTensorInfos.imag.dataId, force);
+ }
+ this.texData.delete(dataId);
+ return true;
+ };
+ MathBackendWebGL.prototype.releaseGPUData = function (dataId) {
+ var _a = this.texData.get(dataId), texture = _a.texture, dtype = _a.dtype, texShape = _a.texShape, usage = _a.usage, isPacked = _a.isPacked, slice = _a.slice;
+ var key = slice && slice.origDataId || dataId;
+ var refCount = this.dataRefCount.get(key);
+ if (refCount > 1) {
+ this.dataRefCount.set(key, refCount - 1);
+ }
+ else {
+ this.dataRefCount.delete(key);
+ if (texture != null) {
+ this.numBytesInGPU -= this.computeBytes(texShape, dtype);
+ this.textureManager.releaseTexture(texture, texShape, usage, isPacked);
+ }
+ }
+ var texData = this.texData.get(dataId);
+ texData.texture = null;
+ texData.texShape = null;
+ texData.isPacked = false;
+ texData.slice = null;
+ };
+ MathBackendWebGL.prototype.getTexture = function (dataId) {
+ this.uploadToGPU(dataId);
+ return this.texData.get(dataId).texture;
+ };
+ /**
+ * Returns internal information for the specific data bucket. Used in unit
+ * tests.
+ */
+ MathBackendWebGL.prototype.getDataInfo = function (dataId) {
+ return this.texData.get(dataId);
+ };
+ /*
+ Tests whether all the inputs to an op are small and on the CPU. This heuristic
+ determines when it would be faster to execute a kernel on the CPU. WebGL
+ kernels opt into running this check and forwarding when appropriate.
+ TODO(https://github.com/tensorflow/tfjs/issues/872): Develop a more
+ sustainable strategy for optimizing backend execution of ops.
+ */
+ MathBackendWebGL.prototype.shouldExecuteOnCPU = function (inputs, sizeThreshold) {
+ var _this = this;
+ if (sizeThreshold === void 0) { sizeThreshold = CPU_HANDOFF_SIZE_THRESHOLD; }
+ return tf.env().getBool('WEBGL_CPU_FORWARD') &&
+ inputs.every(function (input) { return _this.texData.get(input.dataId).texture == null &&
+ tf.util.sizeFromShape(input.shape) < sizeThreshold; });
+ };
+ MathBackendWebGL.prototype.getGPGPUContext = function () {
+ return this.gpgpu;
+ };
+ MathBackendWebGL.prototype.where = function (condition) {
+ tf.backend_util.warn('tf.where() in webgl locks the UI thread. ' +
+ 'Call tf.whereAsync() instead');
+ var condVals = condition.dataSync();
+ return whereImpl(condition.shape, condVals);
+ };
+ MathBackendWebGL.prototype.packedUnaryOp = function (x, op, dtype) {
+ var program = new UnaryOpPackedProgram(x.shape, op);
+ var outInfo = this.compileAndRun(program, [x], dtype);
+ return tf.engine().makeTensorFromDataId(outInfo.dataId, outInfo.shape, outInfo.dtype);
+ };
+ // TODO(msoulanille) remove this once the backend has been modularized
+ // a copy is needed here to break a circular dependency.
+ // Also remove the op from unary_op.
+ MathBackendWebGL.prototype.abs = function (x) {
+ // TODO: handle cases when x is complex.
+ if (this.shouldExecuteOnCPU([x]) && x.dtype !== 'complex64') {
+ var outValues = simpleAbsImplCPU(this.texData.get(x.dataId).values);
+ return this.makeOutput(x.shape, x.dtype, outValues);
+ }
+ if (tf.env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {
+ return this.packedUnaryOp(x, ABS, x.dtype);
+ }
+ var program = new UnaryOpProgram(x.shape, ABS);
+ var outInfo = this.compileAndRun(program, [x]);
+ return tf.engine().makeTensorFromDataId(outInfo.dataId, outInfo.shape, outInfo.dtype);
+ };
+ MathBackendWebGL.prototype.makeTensorInfo = function (shape, dtype, values) {
+ var dataId;
+ if (dtype === 'string' && values != null && values.length > 0 &&
+ tf.util.isString(values[0])) {
+ var encodedValues = values.map(function (d) { return tf.util.encodeString(d); });
+ dataId = this.write(encodedValues, shape, dtype);
+ }
+ else {
+ dataId = this.write(values, shape, dtype);
+ }
+ this.texData.get(dataId).usage = null;
+ return { dataId: dataId, shape: shape, dtype: dtype };
+ };
+ MathBackendWebGL.prototype.makeOutput = function (shape, dtype, values) {
+ var dataId = this.makeTensorInfo(shape, dtype, values).dataId;
+ return tf.engine().makeTensorFromDataId(dataId, shape, dtype, this);
+ };
+ MathBackendWebGL.prototype.unpackTensor = function (input) {
+ var program = new UnpackProgram(input.shape);
+ return this.runWebGLProgram(program, [input], input.dtype);
+ };
+ MathBackendWebGL.prototype.packTensor = function (input) {
+ var program = new PackProgram(input.shape);
+ var preventEagerUnpackingOutput = true;
+ return this.runWebGLProgram(program, [input], input.dtype, null /* customSetup */, preventEagerUnpackingOutput);
+ };
+ MathBackendWebGL.prototype.packedReshape = function (input, afterShape) {
+ var input3DShape = [
+ getBatchDim(input.shape)
+ ].concat(getRowsCols(input.shape));
+ var input3D = {
+ dtype: input.dtype,
+ shape: input3DShape,
+ dataId: input.dataId
+ };
+ var afterShapeAs3D = [
+ getBatchDim(afterShape)
+ ].concat(getRowsCols(afterShape));
+ var program = new ReshapePackedProgram(afterShapeAs3D, input3DShape);
+ var preventEagerUnpackingOfOutput = true;
+ var output = this.runWebGLProgram(program, [input3D], input.dtype, null /* customSetup */, preventEagerUnpackingOfOutput);
+ return { dataId: output.dataId, shape: afterShape, dtype: output.dtype };
+ };
+ MathBackendWebGL.prototype.decode = function (dataId) {
+ var texData = this.texData.get(dataId);
+ var isPacked = texData.isPacked, shape = texData.shape, dtype = texData.dtype;
+ var shapeAs3D = getShapeAs3D(shape);
+ var program;
+ if (isPacked) {
+ program = new DecodeMatrixPackedProgram(shapeAs3D);
+ }
+ else {
+ program = new DecodeMatrixProgram(shapeAs3D);
+ }
+ var preventEagerUnpackingOfOutput = true;
+ var out = this.runWebGLProgram(program, [{ shape: shapeAs3D, dtype: dtype, dataId: dataId }], dtype, null /* customSetup */, preventEagerUnpackingOfOutput);
+ return { dtype: dtype, shape: shape, dataId: out.dataId };
+ };
+ MathBackendWebGL.prototype.runWebGLProgram = function (program, inputs, outputDtype, customSetup, preventEagerUnpackingOfOutput) {
+ var _this = this;
+ if (preventEagerUnpackingOfOutput === void 0) { preventEagerUnpackingOfOutput = false; }
+ var output = this.makeTensorInfo(program.outputShape, outputDtype);
+ var outData = this.texData.get(output.dataId);
+ if (program.packedOutput) {
+ outData.isPacked = true;
+ }
+ if (program.outPackingScheme === PackingScheme.DENSE) {
+ var texelShape = getDenseTexShape(program.outputShape);
+ // For a densely packed output, we explicitly set texShape
+ // so it doesn't get assigned later according to our typical packing
+ // scheme wherein a single texel can only contain values from adjacent
+ // rows/cols.
+ outData.texShape = texelShape.map(function (d) { return d * 2; });
+ }
+ if (program.outTexUsage != null) {
+ outData.usage = program.outTexUsage;
+ }
+ if (tf.util.sizeFromShape(output.shape) === 0) {
+ // Short-circuit the computation since the result is empty (has 0 in its
+ // shape).
+ outData.values =
+ tf.util.getTypedArrayFromDType(output.dtype, 0);
+ return output;
+ }
+ var dataToDispose = [];
+ var inputsData = inputs.map(function (input) {
+ if (input.dtype === 'complex64') {
+ throw new Error("GPGPUProgram does not support complex64 input. For complex64 " +
+ "dtypes, please separate the program into real and imaginary " +
+ "parts.");
+ }
+ var texData = _this.texData.get(input.dataId);
+ if (texData.texture == null) {
+ if (!program.packedInputs &&
+ tf.util.sizeFromShape(input.shape) <=
+ tf.env().getNumber('WEBGL_SIZE_UPLOAD_UNIFORM')) {
+ // Upload small tensors that live on the CPU as uniforms, not as
+ // textures. Do this only when the environment supports 32bit floats
+ // due to problems when comparing 16bit floats with 32bit floats.
+ // TODO(https://github.com/tensorflow/tfjs/issues/821): Make it
+ // possible for packed shaders to sample from uniforms.
+ return {
+ shape: input.shape,
+ texData: null,
+ isUniform: true,
+ uniformValues: texData.values
+ };
+ }
+ // This ensures that if a packed program's inputs have not yet been
+ // uploaded to the GPU, they get uploaded as packed right off the bat.
+ if (program.packedInputs) {
+ texData.isPacked = true;
+ texData.shape = input.shape;
+ }
+ }
+ else if (!!texData.isPacked !== !!program.packedInputs) {
+ input = texData.isPacked ? _this.unpackTensor(input) :
+ _this.packTensor(input);
+ dataToDispose.push(input);
+ texData = _this.texData.get(input.dataId);
+ }
+ else if (texData.isPacked &&
+ !isReshapeFree(texData.shape, input.shape)) {
+ // This is a special case where a texture exists for a tensor
+ // but the shapes are incompatible (due to packing constraints) because
+ // the tensor did not have a chance to go through the packed reshape
+ // shader. This only happens when we reshape the *same* tensor to form
+ // *distinct* inputs to an op, e.g. dotting a vector with itself. This
+ // case will disappear once packed uploading is the default.
+ var savedInput = input;
+ var targetShape = input.shape;
+ input.shape = texData.shape;
+ input = _this.packedReshape(input, targetShape);
+ dataToDispose.push(input);
+ texData = _this.texData.get(input.dataId);
+ savedInput.shape = targetShape;
+ }
+ _this.uploadToGPU(input.dataId);
+ return { shape: input.shape, texData: texData, isUniform: false };
+ });
+ this.uploadToGPU(output.dataId);
+ var outputData = { shape: output.shape, texData: outData, isUniform: false };
+ var key = makeShaderKey(program, inputsData, outputData);
+ var binary = this.getAndSaveBinary(key, function () {
+ return compileProgram(_this.gpgpu, program, inputsData, outputData);
+ });
+ var shouldTimeProgram = this.activeTimers != null;
+ var query;
+ if (shouldTimeProgram) {
+ query = this.startTimer();
+ }
+ runProgram(this.gpgpu, binary, inputsData, outputData, customSetup);
+ dataToDispose.forEach(function (info) { return _this.disposeIntermediateTensorInfo(info); });
+ if (shouldTimeProgram) {
+ query = this.endTimer(query);
+ this.activeTimers.push({ name: program.constructor.name, query: this.getQueryTime(query) });
+ }
+ var glFlushThreshold = tf.env().get('WEBGL_FLUSH_THRESHOLD');
+ // Manually GL flush requested
+ if (glFlushThreshold > 0) {
+ var time = tf.util.now();
+ if ((time - this.lastGlFlushTime) > glFlushThreshold) {
+ this.gpgpu.gl.flush();
+ this.lastGlFlushTime = time;
+ }
+ }
+ if (!tf.env().getBool('WEBGL_LAZILY_UNPACK') && outData.isPacked &&
+ preventEagerUnpackingOfOutput === false) {
+ var unpacked = this.unpackTensor(output);
+ this.disposeIntermediateTensorInfo(output);
+ return unpacked;
+ }
+ return output;
+ };
+ MathBackendWebGL.prototype.compileAndRun = function (program, inputs, outputDtype, customSetup, preventEagerUnpackingOfOutput) {
+ if (preventEagerUnpackingOfOutput === void 0) { preventEagerUnpackingOfOutput = false; }
+ outputDtype = outputDtype || inputs[0].dtype;
+ var outInfo = this.runWebGLProgram(program, inputs, outputDtype, customSetup, preventEagerUnpackingOfOutput);
+ return outInfo;
+ };
+ MathBackendWebGL.prototype.getAndSaveBinary = function (key, getBinary) {
+ if (!(key in this.binaryCache)) {
+ this.binaryCache[key] = getBinary();
+ }
+ return this.binaryCache[key];
+ };
+ MathBackendWebGL.prototype.getTextureManager = function () {
+ return this.textureManager;
+ };
+ MathBackendWebGL.prototype.dispose = function () {
+ var _this = this;
+ if (this.disposed) {
+ return;
+ }
+ // Avoid disposing the compiled webgl programs during unit testing because
+ // it slows down test execution.
+ if (!tf.env().getBool('IS_TEST')) {
+ var allKeys = Object.keys(this.binaryCache);
+ allKeys.forEach(function (key) {
+ _this.gpgpu.deleteProgram(_this.binaryCache[key].webGLProgram);
+ delete _this.binaryCache[key];
+ });
+ }
+ this.textureManager.dispose();
+ if (this.canvas != null &&
+ (typeof (HTMLCanvasElement) !== 'undefined' &&
+ this.canvas instanceof HTMLCanvasElement)) {
+ this.canvas.remove();
+ }
+ else {
+ this.canvas = null;
+ }
+ if (this.gpgpuCreatedLocally) {
+ this.gpgpu.program = null;
+ this.gpgpu.dispose();
+ }
+ this.disposed = true;
+ };
+ MathBackendWebGL.prototype.floatPrecision = function () {
+ var _this = this;
+ if (this.floatPrecisionValue == null) {
+ this.floatPrecisionValue = tf.tidy(function () {
+ if (!tf.env().get('WEBGL_RENDER_FLOAT32_ENABLED')) {
+ // Momentarily switching DEBUG flag to false so we don't throw an
+ // error trying to upload a small value.
+ var debugFlag = tf.env().getBool('DEBUG');
+ tf.env().set('DEBUG', false);
+ var underflowCheckValue = _this.abs(tf.scalar(1e-8)).dataSync()[0];
+ tf.env().set('DEBUG', debugFlag);
+ if (underflowCheckValue > 0) {
+ return 32;
+ }
+ }
+ return 16;
+ });
+ }
+ return this.floatPrecisionValue;
+ };
+ /** Returns the smallest representable number. */
+ MathBackendWebGL.prototype.epsilon = function () {
+ return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
+ };
+ MathBackendWebGL.prototype.uploadToGPU = function (dataId) {
+ var _a;
+ var texData = this.texData.get(dataId);
+ var shape = texData.shape, dtype = texData.dtype, values = texData.values, texture = texData.texture, usage = texData.usage, isPacked = texData.isPacked;
+ if (texture != null) {
+ // Array is already on GPU. No-op.
+ return;
+ }
+ var shouldTimeProgram = this.activeTimers != null;
+ var start;
+ if (shouldTimeProgram) {
+ start = tf.util.now();
+ }
+ var texShape = texData.texShape;
+ if (texShape == null) {
+ texShape = getTextureShapeFromLogicalShape(shape, isPacked);
+ texData.texShape = texShape;
+ }
+ if (values != null) {
+ var shapeAs3D = getShapeAs3D(shape);
+ var program = void 0;
+ var width = texShape[1], height = texShape[0];
+ var isByteArray = values instanceof Uint8Array;
+ if (isPacked) {
+ _a = getPackedMatrixTextureShapeWidthHeight(texShape[0], texShape[1]), width = _a[0], height = _a[1];
+ program = new EncodeMatrixPackedProgram(shapeAs3D, [height, width], isByteArray);
+ }
+ else {
+ program =
+ new EncodeMatrixProgram(shapeAs3D, [height, width], isByteArray);
+ }
+ var tempDenseInputHandle = this.makeTensorInfo([height, width], dtype);
+ if (isByteArray) {
+ this.texData.get(tempDenseInputHandle.dataId).usage =
+ TextureUsage.PIXELS;
+ }
+ else {
+ this.texData.get(tempDenseInputHandle.dataId).usage =
+ TextureUsage.UPLOAD;
+ }
+ this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(tempDenseInputHandle.dataId), width, height, values);
+ // We want the output to remain packed regardless of the value of
+ // WEBGL_PACK.
+ var preventEagerUnpacking = true;
+ var encodedOutputTarget = this.runWebGLProgram(program, [tempDenseInputHandle], dtype, null, preventEagerUnpacking);
+ // Have the original texture assume the identity of the encoded output.
+ var outputTexData = this.texData.get(encodedOutputTarget.dataId);
+ texData.texture = outputTexData.texture;
+ texData.texShape = outputTexData.texShape;
+ texData.isPacked = outputTexData.isPacked;
+ texData.usage = outputTexData.usage;
+ this.disposeIntermediateTensorInfo(tempDenseInputHandle);
+ this.texData.delete(encodedOutputTarget.dataId);
+ // Once uploaded, don't store the values on cpu.
+ texData.values = null;
+ if (shouldTimeProgram) {
+ this.uploadWaitMs += tf.util.now() - start;
+ }
+ }
+ else {
+ var newTexture = this.acquireTexture(texShape, usage, dtype, isPacked);
+ texData.texture = newTexture;
+ }
+ };
+ MathBackendWebGL.prototype.convertAndCacheOnCPU = function (dataId, float32Values) {
+ var texData = this.texData.get(dataId);
+ var dtype = texData.dtype;
+ this.releaseGPUData(dataId);
+ if (float32Values != null) {
+ texData.values = float32ToTypedArray(float32Values, dtype);
+ }
+ return texData.values;
+ };
+ MathBackendWebGL.prototype.acquireTexture = function (texShape, texType, dtype, isPacked) {
+ this.numBytesInGPU += this.computeBytes(texShape, dtype);
+ if (!this.warnedAboutMemory &&
+ this.numBytesInGPU > this.numMBBeforeWarning * 1024 * 1024) {
+ var mb = (this.numBytesInGPU / 1024 / 1024).toFixed(2);
+ this.warnedAboutMemory = true;
+ console.warn("High memory usage in GPU: " + mb + " MB, " +
+ "most likely due to a memory leak");
+ }
+ return this.textureManager.acquireTexture(texShape, texType, isPacked);
+ };
+ MathBackendWebGL.prototype.computeBytes = function (shape, dtype) {
+ return shape[0] * shape[1] * tf.util.bytesPerElement(dtype);
+ };
+ MathBackendWebGL.nextDataId = 0;
+ return MathBackendWebGL;
+ }(tf.KernelBackend));
+ function float32ToTypedArray(a, dtype) {
+ if (dtype === 'float32' || dtype === 'complex64') {
+ return a;
+ }
+ else if (dtype === 'int32' || dtype === 'bool') {
+ var result = (dtype === 'int32') ? new Int32Array(a.length) :
+ new Uint8Array(a.length);
+ for (var i = 0; i < result.length; ++i) {
+ result[i] = Math.round(a[i]);
+ }
+ return result;
+ }
+ else {
+ throw new Error("Unknown dtype " + dtype);
+ }
+ }
+
+ /** @license See the LICENSE file. */
+ // This code is auto-generated, do not modify this file!
+ var version = '3.7.0';
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Enforce use of half precision textures if available on the platform.
+ *
+ * @doc {heading: 'Environment', namespace: 'webgl'}
+ */
+ function forceHalfFloat() {
+ tf.env().set('WEBGL_FORCE_F16_TEXTURES', true);
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google Inc. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ if (tf.device_util.isBrowser()) {
+ tf.registerBackend('webgl', function () { return new MathBackendWebGL(); }, 2 /* priority */);
+ }
+ var webgl = { forceHalfFloat: forceHalfFloat };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var CHECK_NAN_SNIPPET$1 = "\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n";
+ var BinaryOpProgram = /** @class */ (function () {
+ function BinaryOpProgram(op, aShape, bShape) {
+ this.variableNames = ['A', 'B'];
+ this.outputShape = tf.backend_util.assertAndGetBroadcastShape(aShape, bShape);
+ this.userCode = "\n float binaryOperation(float a, float b) {\n " + op + "\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n ";
+ }
+ return BinaryOpProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var CHECK_NAN_SNIPPET$2 = "\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";
+ var BinaryOpPackedProgram = /** @class */ (function () {
+ function BinaryOpPackedProgram(op, aShape, bShape, checkOutOfBounds) {
+ if (checkOutOfBounds === void 0) { checkOutOfBounds = false; }
+ this.variableNames = ['A', 'B'];
+ this.supportsBroadcasting = true;
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = tf.backend_util.assertAndGetBroadcastShape(aShape, bShape);
+ var rank = this.outputShape.length;
+ var checkOutOfBoundsString = '';
+ if (checkOutOfBounds) {
+ if (rank === 0 || tf.util.sizeFromShape(this.outputShape) === 1) {
+ checkOutOfBoundsString = "\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";
+ }
+ else {
+ var dtype = getCoordsDataType(rank);
+ checkOutOfBoundsString = "\n " + dtype + " coords = getOutputCoords();\n ";
+ if (rank === 1) {
+ checkOutOfBoundsString += "\n result.y = (coords + 1) >= " + this.outputShape[0] + " ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";
+ }
+ else {
+ var channels = getChannels('coords', rank);
+ checkOutOfBoundsString += "\n bool nextRowOutOfBounds =\n (" + channels[rank - 2] + " + 1) >= " + this.outputShape[rank - 2] + ";\n bool nextColOutOfBounds =\n (" + channels[rank - 1] + " + 1) >= " + this.outputShape[rank - 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 " + op + "\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n " + checkOutOfBoundsString + "\n\n setOutput(result);\n }\n ";
+ }
+ return BinaryOpPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function identity(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var x = inputs.x;
+ backend.incRef(x.dataId);
+ return { dataId: x.dataId, shape: x.shape, dtype: x.dtype };
+ }
+ var identityConfig = {
+ kernelName: tf.Identity,
+ backendName: 'webgl',
+ kernelFunc: identity
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * In WebGL data is stored in GPU textures which can't be efficiently copied, so
+ * complex tensors share data with their real and imaginary components. Complex
+ * tensors' reference to the components is tracked by refCount on the individual
+ * component. The refCounts are increased by the identity call.
+ *
+ * When a complex tensor is disposed, it will reduce the refCount on the
+ * components by calling disposeData on each.
+ */
+ function complex(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var real = inputs.real, imag = inputs.imag;
+ var complexInfo = backend.makeTensorInfo(real.shape, 'complex64');
+ var complex = backend.texData.get(complexInfo.dataId);
+ var realTensorInfo = identity({ inputs: { x: real }, backend: backend });
+ var imagTensorInfo = identity({ inputs: { x: imag }, backend: backend });
+ complex.complexTensorInfos = { real: realTensorInfo, imag: imagTensorInfo };
+ return complexInfo;
+ }
+ var complexConfig = {
+ kernelName: tf.Complex,
+ backendName: 'webgl',
+ kernelFunc: complex
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LEAKYRELU = "return (a < 0.) ? b * a : a;";
+ var LEAKYRELU_PACKED = "\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";
+ function leakyRelu(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var alpha = attrs.alpha;
+ var $alpha = backend.makeTensorInfo([], 'float32', tf.util.createScalarValue(alpha, 'float32'));
+ var program = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ?
+ new BinaryOpPackedProgram(LEAKYRELU_PACKED, x.shape, $alpha.shape) :
+ new BinaryOpProgram(LEAKYRELU, x.shape, $alpha.shape);
+ var result = backend.runWebGLProgram(program, [x, $alpha], x.dtype);
+ backend.disposeIntermediateTensorInfo($alpha);
+ return result;
+ }
+ var leakyReluConfig = {
+ kernelName: tf.LeakyRelu,
+ backendName: 'webgl',
+ kernelFunc: leakyRelu
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var PRELU = "return (a < 0.) ? b * a : a;";
+ var PRELU_PACKED = "\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";
+ function prelu(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var x = inputs.x, alpha = inputs.alpha;
+ var program = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ?
+ new BinaryOpPackedProgram(PRELU_PACKED, x.shape, alpha.shape) :
+ new BinaryOpProgram(PRELU, x.shape, alpha.shape);
+ return backend.runWebGLProgram(program, [x, alpha], x.dtype);
+ }
+ var preluConfig = {
+ kernelName: tf.Prelu,
+ backendName: 'webgl',
+ kernelFunc: prelu
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var CHECK_NAN_SNIPPET_UNARY = "if (isnan(x)) return x;";
+ var CHECK_NAN_SNIPPET_BINARY = "\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n";
+ var CHECK_NAN_SNIPPET_BINARY_PACKED = "\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";
+ /**
+ * Template that creates a `KernelFunc` for unary ops.
+ * @param opSnippet Op snippet to create `UnaryOpProgram`.
+ * @param packedOpSnippet Op snippet to create `UnaryOpPackedProgram`.
+ * @param dtype Optional. If set, the result has this dtype. Otherwise, the
+ * result has the same dtype as the first input. This is mainly used in
+ * comparison kernels, such as Equal, Less, Greater, etc.
+ */
+ function unaryKernelFunc(_a) {
+ var opSnippet = _a.opSnippet, packedOpSnippet = _a.packedOpSnippet, cpuKernelImpl = _a.cpuKernelImpl, dtype = _a.dtype;
+ return function (_a) {
+ var inputs = _a.inputs, backend = _a.backend;
+ var x = inputs.x;
+ var webglBackend = backend;
+ var $dtype = dtype || x.dtype;
+ if (webglBackend.shouldExecuteOnCPU([x]) && cpuKernelImpl != null) {
+ var xData = webglBackend.texData.get(x.dataId);
+ var outValues = cpuKernelImpl(xData.values, $dtype);
+ return webglBackend.makeTensorInfo(x.shape, $dtype, outValues);
+ }
+ var shouldUsePackedProgram = tf.env().getBool('WEBGL_PACK_UNARY_OPERATIONS') && packedOpSnippet != null;
+ var program;
+ if (shouldUsePackedProgram) {
+ program = new UnaryOpPackedProgram(x.shape, packedOpSnippet);
+ }
+ else {
+ program = new UnaryOpProgram(x.shape, opSnippet);
+ }
+ return webglBackend.runWebGLProgram(program, [x], $dtype);
+ };
+ }
+ /**
+ * Template that creates a `KernelFunc` for binary ops.
+ * @param opSnippet Op snippet to create `BinaryOpProgram`.
+ * @param packedOpSnippet Op snippet to create `BinaryOpPackedProgram`.
+ * @param checkOutOfBoundsForPackedProgram Whether to set checkOutOfBounds=true
+ * when creating BinaryOpPackedProgram.
+ * @param dtype Optional. If set, the result has this dtype. Otherwise, the
+ * result has the same dtype as the first input. This is mainly used in
+ * comparison kernels, such as Equal, Less, Greater, etc.
+ */
+ function binaryKernelFunc(_a) {
+ var opSnippet = _a.opSnippet, packedOpSnippet = _a.packedOpSnippet, _b = _a.checkOutOfBounds, checkOutOfBounds = _b === void 0 ? false : _b, _c = _a.supportsComplex, supportsComplex = _c === void 0 ? false : _c, cpuKernelImpl = _a.cpuKernelImpl, dtype = _a.dtype;
+ return function (_a) {
+ var inputs = _a.inputs, backend = _a.backend;
+ var _b = inputs, a = _b.a, b = _b.b;
+ var webglBackend = backend;
+ if (supportsComplex && a.dtype === 'complex64') {
+ var aData = webglBackend.texData.get(a.dataId);
+ var bData = webglBackend.texData.get(b.dataId);
+ var _c = [
+ [aData.complexTensorInfos.real, bData.complexTensorInfos.real],
+ [aData.complexTensorInfos.imag, bData.complexTensorInfos.imag]
+ ].map(function (complexParts) {
+ var aPart = complexParts[0], bPart = complexParts[1];
+ var aHandle = {
+ dataId: aPart.dataId,
+ dtype: aPart.dtype,
+ shape: a.shape
+ };
+ var bHandle = {
+ dataId: bPart.dataId,
+ dtype: bPart.dtype,
+ shape: b.shape
+ };
+ var program = new BinaryOpProgram(opSnippet, a.shape, b.shape);
+ return webglBackend.runWebGLProgram(program, [aHandle, bHandle], tf.upcastType(aPart.dtype, bPart.dtype));
+ }), real = _c[0], imag = _c[1];
+ var complexOutput = complex({ inputs: { real: real, imag: imag }, backend: webglBackend });
+ webglBackend.disposeIntermediateTensorInfo(real);
+ webglBackend.disposeIntermediateTensorInfo(imag);
+ // TODO(annxingyuan): Implement CPU forwarding for complex inputs.
+ return complexOutput;
+ }
+ var $dtype = dtype || tf.upcastType(a.dtype, b.dtype);
+ if ((a.dtype === 'string' || b.dtype === 'string' ||
+ webglBackend.shouldExecuteOnCPU([a, b])) &&
+ cpuKernelImpl != null) {
+ var aVals = webglBackend.texData.get(a.dataId).values;
+ var bVals = webglBackend.texData.get(b.dataId).values;
+ var decodedAVals = a.dtype === 'string' ?
+ // tslint:disable-next-line: no-any
+ tf.backend_util.fromUint8ToStringArray(aVals) :
+ aVals;
+ var decodedBVals = a.dtype === 'string' ?
+ // tslint:disable-next-line: no-any
+ tf.backend_util.fromUint8ToStringArray(bVals) :
+ bVals;
+ var _d = cpuKernelImpl(a.shape, b.shape, decodedAVals, decodedBVals, $dtype), outValues = _d[0], outShape = _d[1];
+ var out = webglBackend.makeTensorInfo(outShape, $dtype);
+ var outData = webglBackend.texData.get(out.dataId);
+ outData.values = outValues;
+ return out;
+ }
+ var shouldUsePackedProgram = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS') &&
+ packedOpSnippet != null;
+ var program;
+ if (shouldUsePackedProgram) {
+ program = new BinaryOpPackedProgram(packedOpSnippet, a.shape, b.shape, checkOutOfBounds);
+ }
+ else {
+ program = new BinaryOpProgram(opSnippet, a.shape, b.shape);
+ }
+ return webglBackend.runWebGLProgram(program, [a, b], $dtype);
+ };
+ }
+ function mapActivationToShaderProgram(activation, packed) {
+ if (packed === void 0) { packed = false; }
+ if (activation === 'linear') {
+ if (packed) {
+ return LINEAR$1;
+ }
+ return LINEAR;
+ }
+ else if (activation === 'relu') {
+ if (packed) {
+ return RELU$1;
+ }
+ return RELU;
+ }
+ else if (activation === 'elu') {
+ if (packed) {
+ return ELU$1;
+ }
+ return ELU;
+ }
+ else if (activation === 'relu6') {
+ if (packed) {
+ return RELU6$1;
+ }
+ return RELU6;
+ }
+ else if (activation === 'prelu') {
+ if (packed) {
+ return PRELU_PACKED;
+ }
+ return PRELU;
+ }
+ else if (activation === 'leakyrelu') {
+ if (packed) {
+ return LEAKYRELU_PACKED;
+ }
+ return LEAKYRELU;
+ }
+ else if (activation === 'sigmoid') {
+ if (packed) {
+ return SIGMOID$1;
+ }
+ return SIGMOID;
+ }
+ throw new Error("Activation " + activation + " has not been implemented for the WebGL backend.");
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var MatMulPackedProgram = /** @class */ (function () {
+ function MatMulPackedProgram(aShape, bShape, outputShape, transposeA, transposeB, addBias, activation, hasPreluActivation, hasLeakyreluActivation) {
+ if (transposeA === void 0) { transposeA = false; }
+ if (transposeB === void 0) { transposeB = false; }
+ if (addBias === void 0) { addBias = false; }
+ if (activation === void 0) { activation = null; }
+ if (hasPreluActivation === void 0) { hasPreluActivation = false; }
+ if (hasLeakyreluActivation === void 0) { hasLeakyreluActivation = false; }
+ this.variableNames = ['matrixA', 'matrixB'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = outputShape;
+ var sharedDim = transposeA ? aShape[1] : aShape[2];
+ var sharedDimensionPacked = Math.ceil(sharedDim / 2);
+ var aSample = transposeA ? 'i * 2, rc.y' : 'rc.y, i * 2';
+ var bSample = transposeB ? 'rc.z, i * 2' : 'i * 2, rc.z';
+ var aSwizzle = transposeA ? ['a.xxyy', 'a.zzww'] : ['a.xxzz', 'a.yyww'];
+ var bSwizzle = transposeB ? ['b.xzxz', 'b.ywyw'] : ['b.xyxy', 'b.zwzw'];
+ var activationSnippet = '', applyActivationSnippet = '';
+ if (activation) {
+ if (hasPreluActivation) {
+ activationSnippet = "vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n " + activation + "\n }";
+ }
+ else if (hasLeakyreluActivation) {
+ activationSnippet = "vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n " + activation + "\n }";
+ }
+ else {
+ activationSnippet = "vec4 activation(vec4 x) {\n " + activation + "\n }";
+ }
+ applyActivationSnippet = "result = activation(result);";
+ }
+ var addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';
+ if (addBias) {
+ this.variableNames.push('bias');
+ }
+ if (hasPreluActivation) {
+ this.variableNames.push('preluActivationWeights');
+ }
+ if (hasLeakyreluActivation) {
+ this.variableNames.push('leakyreluAlpha');
+ }
+ var batchASnippet = 'rc.x';
+ var batchBSnippet = 'rc.x';
+ if (aShape[0] < bShape[0]) {
+ batchASnippet = "int(min(float(rc.x), " + (aShape[0] - 1) + ".))";
+ }
+ else if (bShape[0] < aShape[0]) {
+ batchBSnippet = "int(min(float(rc.x), " + (bShape[0] - 1) + ".))";
+ }
+ this.userCode = "\n " + activationSnippet + "\n\n const float sharedDimension = " + sharedDimensionPacked + ".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < " + sharedDimensionPacked + "; i++) {\n int batchA = " + batchASnippet + ";\n int batchB = " + batchBSnippet + ";\n vec4 a = getMatrixA(batchA, " + aSample + ");\n vec4 b = getMatrixB(batchB, " + bSample + ");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += (" + aSwizzle[0] + " * " + bSwizzle[0] + ");\n result += (" + aSwizzle[1] + " * " + bSwizzle[1] + ");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n " + addBiasSnippet + "\n\n " + applyActivationSnippet + "\n\n setOutput(result);\n }\n ";
+ }
+ return MatMulPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // (Ar + Ai)(Br + Bi) =
+ // ArBr + ArBi + AiBr + AiBi = ArBr - AB + ArBi + AiBr
+ // Yr = ArBr - AB
+ // Yi = ArBi + AiBr
+ var COMPLEX_MULTIPLY = {
+ REAL: 'return areal * breal - aimag * bimag;',
+ IMAG: 'return areal * bimag + aimag * breal;'
+ };
+ var BinaryOpComplexProgram = /** @class */ (function () {
+ function BinaryOpComplexProgram(op, aShape, bShape) {
+ this.variableNames = ['AReal', 'AImag', 'BReal', 'BImag'];
+ this.outputShape = tf.backend_util.assertAndGetBroadcastShape(aShape, bShape);
+ this.userCode = "\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n " + op + "\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 ";
+ }
+ return BinaryOpComplexProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var MUL = 'return a * b;';
+ function multiply(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var a = inputs.a, b = inputs.b;
+ var dtype = tf.backend_util.upcastType(a.dtype, b.dtype);
+ if (a.dtype === 'complex64') {
+ var aData = backend.texData.get(a.dataId);
+ var bData = backend.texData.get(b.dataId);
+ var realProgram = new BinaryOpComplexProgram(COMPLEX_MULTIPLY.REAL, a.shape, b.shape);
+ var imagProgram = new BinaryOpComplexProgram(COMPLEX_MULTIPLY.IMAG, a.shape, b.shape);
+ var inputs_1 = [
+ {
+ dataId: aData.complexTensorInfos.real.dataId,
+ dtype: aData.complexTensorInfos.real.dtype,
+ shape: a.shape
+ },
+ {
+ dataId: aData.complexTensorInfos.imag.dataId,
+ dtype: aData.complexTensorInfos.imag.dtype,
+ shape: a.shape
+ },
+ {
+ dataId: bData.complexTensorInfos.real.dataId,
+ dtype: bData.complexTensorInfos.real.dtype,
+ shape: b.shape
+ },
+ {
+ dataId: bData.complexTensorInfos.imag.dataId,
+ dtype: bData.complexTensorInfos.imag.dtype,
+ shape: b.shape
+ }
+ ];
+ var realPart = backend.runWebGLProgram(realProgram, inputs_1, 'float32');
+ var imagPart = backend.runWebGLProgram(imagProgram, inputs_1, 'float32');
+ var complexOutput = complex({ inputs: { real: realPart, imag: imagPart }, backend: backend });
+ backend.disposeIntermediateTensorInfo(realPart);
+ backend.disposeIntermediateTensorInfo(imagPart);
+ // TODO(annxingyuan): CPU forwarding for complex inputs.
+ return complexOutput;
+ }
+ if (backend.shouldExecuteOnCPU([a, b])) {
+ var aData = backend.texData.get(a.dataId);
+ var bData = backend.texData.get(b.dataId);
+ var _a = multiplyImplCPU(a.shape, b.shape, aData.values, bData.values, dtype), outValues = _a[0], outShape = _a[1];
+ var out = backend.makeTensorInfo(outShape, dtype);
+ var outData = backend.texData.get(out.dataId);
+ outData.values = outValues;
+ return out;
+ }
+ var program;
+ if (tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS')) {
+ program = new BinaryOpPackedProgram(MUL, a.shape, b.shape);
+ }
+ else {
+ program = new BinaryOpProgram(MUL, a.shape, b.shape);
+ }
+ return backend.runWebGLProgram(program, [a, b], dtype);
+ }
+ var multiplyConfig = {
+ kernelName: tf.Multiply,
+ backendName: 'webgl',
+ kernelFunc: multiply
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function packedReshape(input, afterShape, backend) {
+ var input3DShape = [getBatchDim(input.shape)].concat(getRowsCols(input.shape));
+ var input3D = {
+ dtype: input.dtype,
+ shape: input3DShape,
+ dataId: input.dataId
+ };
+ var afterShapeAs3D = [getBatchDim(afterShape)].concat(getRowsCols(afterShape));
+ var program = new ReshapePackedProgram(afterShapeAs3D, input3DShape);
+ var preventEagerUnpackingOfOutput = true;
+ var output = backend.runWebGLProgram(program, [input3D], input.dtype, null /* customSetup */, preventEagerUnpackingOfOutput);
+ return { dataId: output.dataId, shape: afterShape, dtype: output.dtype };
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function reshape(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var shape = attrs.shape;
+ var webglBackend = backend;
+ var xSize = tf.util.sizeFromShape(x.shape);
+ var $shape = tf.util.inferFromImplicitShape(shape, xSize);
+ var $xSize = tf.util.sizeFromShape($shape);
+ tf.util.assert(xSize === $xSize, function () { return "The new shape (" + $shape + ") has " + $xSize + " elements and the old " +
+ ("shape (" + x.shape + ") has " + xSize + " elements. The new shape and old ") +
+ "shape must have the same number of elements."; });
+ var xTexData = webglBackend.texData.get(x.dataId);
+ if (xTexData.isPacked && !isReshapeFree(x.shape, $shape) &&
+ !(xTexData.texture !== null && isReshapeFree(xTexData.shape, $shape))) {
+ return packedReshape(x, $shape, webglBackend);
+ }
+ webglBackend.incRef(x.dataId);
+ return { dataId: x.dataId, shape: $shape, dtype: x.dtype };
+ }
+ var reshapeConfig = {
+ kernelName: tf.Reshape,
+ backendName: 'webgl',
+ kernelFunc: reshape
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var MeanProgram = /** @class */ (function () {
+ function MeanProgram(reduceInfo, divisor) {
+ this.variableNames = ['x'];
+ var windowSize = reduceInfo.windowSize, batchSize = reduceInfo.batchSize, inSize = reduceInfo.inSize, outSize = reduceInfo.outSize;
+ this.outputShape = [batchSize, outSize];
+ var windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
+ var windowSizeVec4Remainder = windowSize % 4;
+ var updateSnippet = "sumValue += dot(values, ones);";
+ if (divisor != null) {
+ var denominator = 1 / divisor;
+ updateSnippet = "sumValue += dot(values * " + (tf.util.isInt(denominator) ? denominator.toPrecision(2) :
+ denominator) + ", ones);";
+ }
+ var checkOutOfBounds = '';
+ if (inSize % windowSize > 0) {
+ checkOutOfBounds = "\n if (inIdx < 0 || inIdx >= " + inSize + ") {\n return 0.0;\n }\n ";
+ }
+ this.userCode = "\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n " + checkOutOfBounds + "\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 * " + windowSize + ";\n\n float sumValue = 0.0;\n\n for (int i = 0; i < " + windowSizeNearestVec4 + "; 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 " + updateSnippet + "\n }\n\n int inIdx = inOffset + " + windowSizeNearestVec4 + ";\n if (" + (windowSizeVec4Remainder === 1) + ") {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 2) + ") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 3) + ") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n " + updateSnippet + "\n }\n setOutput(sumValue);\n }\n ";
+ }
+ return MeanProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ReduceProgram = /** @class */ (function () {
+ function ReduceProgram(reduceInfo, reduceType) {
+ this.variableNames = ['x'];
+ var windowSize = reduceInfo.windowSize, batchSize = reduceInfo.batchSize, inSize = reduceInfo.inSize, outSize = reduceInfo.outSize;
+ this.outputShape = [batchSize, outSize];
+ var initializationValue = '0.0';
+ var compareOp = "";
+ if (reduceType === 'prod') {
+ initializationValue = '1.0';
+ }
+ else if (reduceType === 'min') {
+ // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.
+ initializationValue = '1.0 / 1e-20';
+ compareOp = "min";
+ }
+ else if (reduceType === 'max') {
+ // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.
+ initializationValue = '-1.0 / 1e-20';
+ compareOp = "max";
+ }
+ var returnValue = reduceType + "(" + reduceType + "(" + reduceType + "(" +
+ 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';
+ if (reduceType === 'sum') {
+ returnValue = "sumValue";
+ }
+ else if (reduceType === 'prod') {
+ returnValue = "prodValue";
+ }
+ else if (reduceType === 'all') {
+ returnValue = "allValue";
+ }
+ else if (reduceType === 'any') {
+ returnValue = "anyValue";
+ }
+ var windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
+ var windowSizeVec4Remainder = windowSize % 4;
+ var updateSnippet = "\n if (" + (reduceType === 'sum') + ") {\n sumValue += dot(values, ones);\n } else if (" + (reduceType === 'prod') + ") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = " + compareOp + "(values, minMaxValue);\n if (" + (reduceType === 'min') + " || " + (reduceType === 'max') + ") {\n minMaxValue = " + compareOp + "(values, minMaxValue);\n bvec4 isNaN = isnan(values);\n if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n minMaxValue = vec4(NAN);\n }\n }\n }\n ";
+ var vecType = "vec4";
+ if (reduceType === 'all') {
+ initializationValue = '1.0';
+ updateSnippet = "\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ";
+ vecType = "bvec4";
+ }
+ else if (reduceType === 'any') {
+ initializationValue = '0.0';
+ updateSnippet = "\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ";
+ vecType = "bvec4";
+ }
+ var checkOutOfBounds = '';
+ if (inSize % windowSize > 0) {
+ checkOutOfBounds = "\n if (inIdx < 0 || inIdx >= " + inSize + ") {\n return initializationValue;\n }\n ";
+ }
+ this.userCode = "\n const float initializationValue = " + initializationValue + ";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n " + checkOutOfBounds + "\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 * " + windowSize + ";\n\n vec4 minMaxValue = vec4(" + initializationValue + ");\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 < " + windowSizeNearestVec4 + "; i += 4) {\n int inIdx = inOffset + i;\n " + vecType + " values = " + vecType + "(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n " + updateSnippet + "\n }\n\n int inIdx = inOffset + " + windowSizeNearestVec4 + ";\n if (" + (windowSizeVec4Remainder === 1) + ") {\n " + vecType + " values = " + vecType + "(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 2) + ") {\n " + vecType + " values = " + vecType + "(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 3) + ") {\n " + vecType + " values = " + vecType + "(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n " + updateSnippet + "\n }\n setOutput(" + returnValue + ");\n }\n ";
+ }
+ return ReduceProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // Returns an array of configuration objects that describe each stage of the
+ // reduction.
+ function getReductionStages(inShape) {
+ var stages = [];
+ while (stages.length === 0 || stages[stages.length - 1].outSize !== 1) {
+ var outSize = stages.length ? stages[stages.length - 1].outSize : inShape[1];
+ var windowSize = tf.backend_util.computeOptimalWindowSize(outSize);
+ stages.push({
+ inSize: outSize,
+ windowSize: windowSize,
+ outSize: Math.ceil(outSize / windowSize)
+ });
+ }
+ return stages;
+ }
+ function reduce(x, dtype, reductionType, backend) {
+ var reductionStages = getReductionStages(x.shape);
+ var result = x;
+ for (var i = 0; i < reductionStages.length; i++) {
+ var _a = reductionStages[i], inSize = _a.inSize, windowSize = _a.windowSize, outSize = _a.outSize;
+ var program = void 0;
+ var previousResult = void 0;
+ if (reductionType === 'mean') {
+ program = i === 0 ?
+ new MeanProgram({ windowSize: windowSize, inSize: inSize, batchSize: x.shape[0], outSize: outSize }, inSize) :
+ new MeanProgram({ windowSize: windowSize, inSize: inSize, batchSize: x.shape[0], outSize: outSize });
+ }
+ else {
+ program = new ReduceProgram({ windowSize: windowSize, inSize: inSize, batchSize: x.shape[0], outSize: outSize }, reductionType);
+ }
+ previousResult = result;
+ result = backend.runWebGLProgram(program, [result], dtype);
+ if (previousResult.dataId !== x.dataId) {
+ backend.disposeIntermediateTensorInfo(previousResult);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var TransposeProgram = /** @class */ (function () {
+ function TransposeProgram(aShape, newDim) {
+ this.variableNames = ['A'];
+ var outputShape = new Array(aShape.length);
+ for (var i = 0; i < outputShape.length; i++) {
+ outputShape[i] = aShape[newDim[i]];
+ }
+ this.outputShape = outputShape;
+ this.rank = outputShape.length;
+ var dtype = getCoordsDataType(this.rank);
+ var switched = getSwitchedCoords(newDim);
+ this.userCode = "\n void main() {\n " + dtype + " resRC = getOutputCoords();\n setOutput(getA(" + switched + "));\n }\n ";
+ }
+ return TransposeProgram;
+ }());
+ function getSwitchedCoords(newDim) {
+ var rank = newDim.length;
+ if (rank > 6) {
+ throw Error("Transpose for rank " + rank + " is not yet supported");
+ }
+ var originalOrder = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u', 'resRC.v'];
+ var switchedCoords = new Array(rank);
+ for (var i = 0; i < newDim.length; i++) {
+ switchedCoords[newDim[i]] = originalOrder[i];
+ }
+ return switchedCoords.join();
+ }
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var TransposePackedProgram = /** @class */ (function () {
+ function TransposePackedProgram(aShape, newDim) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ var outputShape = new Array(aShape.length);
+ for (var i = 0; i < outputShape.length; i++) {
+ outputShape[i] = aShape[newDim[i]];
+ }
+ this.outputShape = outputShape;
+ this.rank = outputShape.length;
+ if (this.rank > 6) {
+ throw Error("Packed transpose for rank " + this.rank + " is not yet supported.");
+ }
+ var dtype = getCoordsDataType(this.rank);
+ var outputOrder = getVecChannels('rc', this.rank);
+ var switchedOrder = new Array(this.rank);
+ for (var i = 0; i < newDim.length; i++) {
+ switchedOrder[newDim[i]] = outputOrder[i];
+ }
+ var innerDims = "vec2(" + switchedOrder.slice(-2).join() + ")";
+ var nextColumn = "++" + outputOrder[this.rank - 1] + " < " + outputShape[this.rank - 1];
+ var getc = "getChannel(getA(" + switchedOrder.join() + "), " + innerDims + ")";
+ this.userCode = "\n void main() {\n " + dtype + " rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = " + getc + ";\n if(" + nextColumn + ") {\n result[1] = " + getc + ";\n }\n --" + outputOrder[this.rank - 1] + ";\n if(++" + outputOrder[this.rank - 2] + " < " + outputShape[this.rank - 2] + ") {\n result[2] = " + getc + ";\n if(" + nextColumn + ") {\n result[3] = " + getc + ";\n }\n }\n setOutput(result);\n }\n ";
+ }
+ return TransposePackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function transposeImpl$1(x, perm, backend) {
+ var program = tf.env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?
+ new TransposePackedProgram(x.shape, perm) :
+ new TransposeProgram(x.shape, perm);
+ return backend.runWebGLProgram(program, [x], x.dtype);
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sumImpl(x, axis, keepDims, backend) {
+ var reductionIndices = axis;
+ var xRank = x.shape.length;
+ var origAxes = tf.util.parseAxisParam(reductionIndices, x.shape);
+ var axes = origAxes;
+ var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
+ var sumInputIsTransposed = permutedAxes != null;
+ var sumInput = x;
+ if (sumInputIsTransposed) {
+ sumInput = transposeImpl$1(x, permutedAxes, backend);
+ axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
+ }
+ tf.backend_util.assertAxesAreInnerMostDims('sum', axes, xRank);
+ var _a = tf.backend_util.computeOutAndReduceShapes(sumInput.shape, axes), sumOutShape = _a[0], reduceShape = _a[1];
+ var outShape = sumOutShape;
+ if (keepDims) {
+ // rather than reshape at the end, set the target shape here.
+ outShape = tf.backend_util.expandShapeToKeepDim(sumOutShape, origAxes);
+ }
+ var inSize = tf.util.sizeFromShape(reduceShape);
+ var xSize = tf.util.sizeFromShape(x.shape);
+ var batchSize = xSize / inSize;
+ var reshapedInput = reshape({ inputs: { x: sumInput }, attrs: { shape: [batchSize, inSize] }, backend: backend });
+ var outType = tf.sumOutType(x.dtype);
+ var reduced = reduce(reshapedInput, outType, 'sum', backend);
+ var out = reshape({ inputs: { x: reduced }, attrs: { shape: outShape }, backend: backend });
+ backend.disposeIntermediateTensorInfo(reshapedInput);
+ backend.disposeIntermediateTensorInfo(reduced);
+ if (sumInputIsTransposed) {
+ backend.disposeIntermediateTensorInfo(sumInput);
+ }
+ return out;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sum(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var axis = attrs.axis, keepDims = attrs.keepDims;
+ return sumImpl(x, axis, keepDims, backend);
+ }
+ var sumConfig = {
+ kernelName: tf.Sum,
+ backendName: 'webgl',
+ kernelFunc: sum
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function transpose(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var perm = attrs.perm;
+ var webglBackend = backend;
+ var xRank = x.shape.length;
+ var newShape = new Array(xRank);
+ for (var i = 0; i < newShape.length; i++) {
+ newShape[i] = x.shape[perm[i]];
+ }
+ var out;
+ if (webglBackend.shouldExecuteOnCPU([x])) {
+ var xTexData = webglBackend.texData.get(x.dataId);
+ var values = xTexData.values;
+ var outValues = transposeImplCPU(values, x.shape, x.dtype, perm, newShape);
+ out = webglBackend.makeTensorInfo(newShape, x.dtype);
+ var outData = webglBackend.texData.get(out.dataId);
+ outData.values = outValues;
+ }
+ else {
+ out = transposeImpl$1(x, perm, webglBackend);
+ }
+ return out;
+ }
+ var transposeConfig = {
+ kernelName: tf.Transpose,
+ backendName: 'webgl',
+ kernelFunc: transpose
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // Empirically determined minimal shared dimension in matmul before we forward
+ // to a.mul(b).sum() in order to take advantage of GPU parallelism. See
+ // https://github.com/tensorflow/tfjs-core/pull/1379 for benchmarks.
+ var MATMUL_SHARED_DIM_THRESHOLD = 1000;
+ function batchMatMulImpl(_a) {
+ var a = _a.a, b = _a.b, transposeA = _a.transposeA, transposeB = _a.transposeB, backend = _a.backend, _b = _a.bias, bias = _b === void 0 ? null : _b, _c = _a.preluActivationWeights, preluActivationWeights = _c === void 0 ? null : _c, _d = _a.leakyreluAlpha, leakyreluAlpha = _d === void 0 ? 0 : _d, _e = _a.activation, activation = _e === void 0 ? null : _e;
+ var aRank = a.shape.length;
+ var bRank = b.shape.length;
+ var innerShapeA = transposeA ? a.shape[aRank - 2] : a.shape[aRank - 1];
+ var innerShapeB = transposeB ? b.shape[bRank - 1] : b.shape[bRank - 2];
+ var outerShapeA = transposeA ? a.shape[aRank - 1] : a.shape[aRank - 2];
+ var outerShapeB = transposeB ? b.shape[bRank - 2] : b.shape[bRank - 1];
+ var outerDimsA = a.shape.slice(0, -2);
+ var outerDimsB = b.shape.slice(0, -2);
+ var batchDimA = tf.util.sizeFromShape(outerDimsA);
+ var batchDimB = tf.util.sizeFromShape(outerDimsB);
+ var batchDimsCompatible = batchDimA === batchDimB || batchDimA === 1 || batchDimB === 1;
+ tf.util.assert(aRank >= 2 && bRank >= 2 && batchDimsCompatible, function () { return "Error in matMul: the input batch dimensions must either be the " +
+ "same or at least one input batch dimension must be 1. Got input " +
+ ("batch dimensions of (" + outerDimsA + ") and (" + outerDimsB + ")."); });
+ var outShapeOuterDims = batchDimA > batchDimB ? a.shape.slice(0, -2) : b.shape.slice(0, -2);
+ var outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);
+ tf.util.assert(innerShapeA === innerShapeB, function () { return "Error in matMul: inner shapes (" + innerShapeA + ") and (" +
+ (innerShapeB + ") of Tensors with shapes " + a.shape + " and ") +
+ (b.shape + " and transposeA=" + transposeA) +
+ (" and transposeB=" + transposeB + " must match."); });
+ var a3dShape = transposeA ?
+ [batchDimA, innerShapeA, outerShapeA] :
+ [batchDimA, outerShapeA, innerShapeA];
+ var b3dShape = transposeB ?
+ [batchDimB, outerShapeB, innerShapeB] :
+ [batchDimB, innerShapeB, outerShapeB];
+ // The rest of the implementation is designed to operate on rank-3 tensors
+ var a3d = reshape({ inputs: { x: a }, backend: backend, attrs: { shape: a3dShape } });
+ var b3d = reshape({ inputs: { x: b }, backend: backend, attrs: { shape: b3dShape } });
+ var intermediates = [a3d, b3d];
+ var batchDim = Math.max(batchDimA, batchDimB);
+ var sharedDim = transposeA ? a3d.shape[1] : a3d.shape[2];
+ var hasBias = bias != null;
+ var hasPreluActivationWeights = preluActivationWeights != null;
+ var hasLeakyreluAlpha = activation === 'leakyrelu';
+ var fusedActivation = activation != null ?
+ mapActivationToShaderProgram(activation, true) :
+ null;
+ var containsFusedOps = hasBias || hasPreluActivationWeights ||
+ hasLeakyreluAlpha || fusedActivation != null;
+ var out;
+ // Since the matrices are vectors, it is faster to call mul().sum()
+ // because sum() is O(sqrt(N)) due to divide-and-conquer.
+ if ((outerShapeA === 1 || outerShapeB === 1) &&
+ sharedDim > MATMUL_SHARED_DIM_THRESHOLD && containsFusedOps === false) {
+ var aVec = a3d;
+ var bVec = b3d;
+ if (transposeA) {
+ aVec = transpose({ inputs: { x: a3d }, backend: backend, attrs: { perm: [0, 2, 1] } });
+ intermediates.push(aVec);
+ }
+ if (transposeB) {
+ bVec = transpose({ inputs: { x: b3d }, backend: backend, attrs: { perm: [0, 2, 1] } });
+ intermediates.push(bVec);
+ }
+ var shouldReshapeA = outerShapeB !== 1;
+ var shouldReshapeB = outerShapeB === 1;
+ var aVec3d = aVec;
+ if (shouldReshapeA) {
+ aVec3d = reshape({
+ inputs: { x: aVec },
+ backend: backend,
+ attrs: { shape: [batchDim, sharedDim, 1] }
+ });
+ intermediates.push(aVec3d);
+ }
+ var axis = outerShapeB === 1 ? 2 : 1;
+ var bVec3d = bVec;
+ if (shouldReshapeB) {
+ bVec3d = reshape({
+ inputs: { x: bVec },
+ backend: backend,
+ attrs: { shape: [batchDim, 1, sharedDim] }
+ });
+ intermediates.push(bVec3d);
+ }
+ var product = multiply({ inputs: { a: aVec3d, b: bVec3d }, backend: backend });
+ out = sum({ inputs: { x: product }, backend: backend, attrs: { axis: axis, keepDims: true } });
+ intermediates.push(product);
+ }
+ else {
+ var dtype = tf.upcastType(a.dtype, b.dtype);
+ var program = new MatMulPackedProgram(a3dShape, b3dShape, [batchDim, outerShapeA, outerShapeB], transposeA, transposeB, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
+ var inputs = [a3d, b3d];
+ if (bias != null) {
+ inputs.push(bias);
+ }
+ if (hasPreluActivationWeights) {
+ inputs.push(preluActivationWeights);
+ }
+ if (hasLeakyreluAlpha) {
+ var $leakyreluAlpha = backend.makeTensorInfo([], 'float32', tf.util.createScalarValue(leakyreluAlpha, 'float32'));
+ inputs.push($leakyreluAlpha);
+ intermediates.push($leakyreluAlpha);
+ }
+ out = backend.runWebGLProgram(program, inputs, dtype);
+ }
+ var outReshaped = reshape({ inputs: { x: out }, backend: backend, attrs: { shape: outShape } });
+ intermediates.push(out);
+ for (var _i = 0, intermediates_1 = intermediates; _i < intermediates_1.length; _i++) {
+ var i = intermediates_1[_i];
+ backend.disposeIntermediateTensorInfo(i);
+ }
+ return outReshaped;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function _fusedMatMul(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var a = inputs.a, b = inputs.b, bias = inputs.bias, preluActivationWeights = inputs.preluActivationWeights;
+ var transposeA = attrs.transposeA, transposeB = attrs.transposeB, activation = attrs.activation, leakyreluAlpha = attrs.leakyreluAlpha;
+ return batchMatMulImpl({
+ a: a,
+ b: b,
+ transposeA: transposeA,
+ transposeB: transposeB,
+ backend: backend,
+ bias: bias,
+ preluActivationWeights: preluActivationWeights,
+ leakyreluAlpha: leakyreluAlpha,
+ activation: activation
+ });
+ }
+ var _fusedMatMulConfig = {
+ kernelName: tf._FusedMatMul,
+ backendName: 'webgl',
+ kernelFunc: _fusedMatMul,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ABS$1 = "return abs(x);";
+ function abs(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var x = inputs.x;
+ // TODO: handle cases when x is complex. Once the cpu implementation
+ // can handle complex values, refactor to use unaryKernelFunc.
+ if (backend.shouldExecuteOnCPU([x]) && x.dtype !== 'complex64') {
+ var xData = backend.texData.get(x.dataId);
+ var outValues = simpleAbsImplCPU(xData.values);
+ return backend.makeTensorInfo(x.shape, x.dtype, outValues);
+ }
+ var program;
+ if (tf.env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {
+ program = new UnaryOpPackedProgram(x.shape, ABS$1);
+ }
+ else {
+ program = new UnaryOpProgram(x.shape, ABS$1);
+ }
+ return backend.runWebGLProgram(program, [x], x.dtype);
+ }
+ var absConfig = {
+ kernelName: tf.Abs,
+ backendName: 'webgl',
+ kernelFunc: abs
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ACOS = CHECK_NAN_SNIPPET + "\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n";
+ var acos = unaryKernelFunc({ opSnippet: ACOS });
+ var acosConfig = {
+ kernelName: tf.Acos,
+ backendName: 'webgl',
+ kernelFunc: acos,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ACOSH = CHECK_NAN_SNIPPET + "\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));";
+ var acosh = unaryKernelFunc({ opSnippet: ACOSH });
+ var acoshConfig = {
+ kernelName: tf.Acosh,
+ backendName: 'webgl',
+ kernelFunc: acosh,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ADD = 'return a + b;';
+ var addKernelFunc = binaryKernelFunc({
+ opSnippet: ADD,
+ packedOpSnippet: ADD,
+ supportsComplex: true,
+ cpuKernelImpl: addImplCPU
+ });
+ var addConfig = {
+ kernelName: tf.Add,
+ backendName: 'webgl',
+ kernelFunc: addKernelFunc
+ };
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var AddNProgram = /** @class */ (function () {
+ function AddNProgram(outputShape, shapes) {
+ this.outputShape = [];
+ this.outputShape = outputShape;
+ this.variableNames = shapes.map(function (_, i) { return "T" + i; });
+ var snippets = [];
+ // Get target elements from every input tensor.
+ this.variableNames.forEach(function (variable) {
+ snippets.push("float v" + variable + " = get" + variable + "AtOutCoords();");
+ });
+ // Calculate the sum of all elements.
+ var operation = this.variableNames
+ .map(function (variable) {
+ return "v" + variable;
+ })
+ .join(' + ');
+ this.userCode = "\n void main() {\n " + snippets.join('\n ') + "\n\n float result = " + operation + ";\n setOutput(result);\n }\n ";
+ }
+ return AddNProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var AddNPackedProgram = /** @class */ (function () {
+ function AddNPackedProgram(outputShape, shapes) {
+ this.outputShape = [];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = outputShape;
+ this.variableNames = shapes.map(function (_, i) { return "T" + i; });
+ var snippets = [];
+ // Get target elements from every input tensor.
+ this.variableNames.forEach(function (variable) {
+ snippets.push("vec4 v" + variable + " = get" + variable + "AtOutCoords();");
+ });
+ // Calculate the sum of all elements.
+ var operation = this.variableNames
+ .map(function (variable) {
+ return "v" + variable;
+ })
+ .join(' + ');
+ this.userCode = "\n void main() {\n " + snippets.join('\n ') + "\n\n vec4 result = " + operation + ";\n setOutput(result);\n }\n ";
+ }
+ return AddNPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function addN(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var tensors = inputs;
+ if (tensors.length === 1) {
+ return identity({ inputs: { x: tensors[0] }, backend: backend });
+ }
+ // Limit the number of uploaded textures for optimization.
+ if (tensors.length > tf.env().get('WEBGL_MAX_TEXTURES_IN_SHADER')) {
+ var midIndex = Math.floor(tensors.length / 2);
+ var leftSide = addN({ inputs: tensors.slice(0, midIndex), backend: backend });
+ var rightSide = addN({ inputs: tensors.slice(midIndex), backend: backend });
+ return addN({ inputs: [leftSide, rightSide], backend: backend });
+ }
+ var dtype = tensors.map(function (t) { return t.dtype; }).reduce(function (d1, d2) { return tf.upcastType(d1, d2); });
+ var shapes = tensors.map(function (t) { return t.shape; });
+ // We can make sure shapes are identical in op level.
+ var usePackedOp = tf.env().getBool('WEBGL_PACK');
+ var program = usePackedOp ?
+ new AddNPackedProgram(tensors[0].shape, shapes) :
+ new AddNProgram(tensors[0].shape, shapes);
+ return backend.runWebGLProgram(program, tensors, dtype);
+ }
+ var addNConfig = {
+ kernelName: tf.AddN,
+ backendName: 'webgl',
+ kernelFunc: addN
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function all(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var axis = attrs.axis, keepDims = attrs.keepDims;
+ var xRank = x.shape.length;
+ var origAxes = tf.util.parseAxisParam(axis, x.shape);
+ var axes = origAxes;
+ var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
+ var permutedX = x;
+ if (permutedAxes != null) {
+ permutedX = transpose({ inputs: { x: x }, backend: backend, attrs: { perm: permutedAxes } });
+ axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
+ }
+ tf.backend_util.assertAxesAreInnerMostDims('all', axes, xRank);
+ var _a = tf.backend_util.computeOutAndReduceShapes(permutedX.shape, axes), outShape = _a[0], reduceShape = _a[1];
+ var inSize = tf.util.sizeFromShape(reduceShape);
+ var a2D = reshape({ inputs: { x: permutedX }, backend: backend, attrs: { shape: [-1, inSize] } });
+ var reduced = reduce(a2D, a2D.dtype, 'all', backend);
+ var res;
+ if (keepDims) {
+ var newShape = tf.backend_util.expandShapeToKeepDim(outShape, origAxes);
+ res = reshape({ inputs: { x: reduced }, backend: backend, attrs: { shape: newShape } });
+ }
+ else {
+ res = reshape({ inputs: { x: reduced }, backend: backend, attrs: { shape: outShape } });
+ }
+ backend.disposeIntermediateTensorInfo(a2D);
+ backend.disposeIntermediateTensorInfo(reduced);
+ if (permutedAxes != null) {
+ backend.disposeIntermediateTensorInfo(permutedX);
+ }
+ return res;
+ }
+ var allConfig = {
+ kernelName: tf.All,
+ backendName: 'webgl',
+ kernelFunc: all
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function any(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var axis = attrs.axis, keepDims = attrs.keepDims;
+ var xRank = x.shape.length;
+ var origAxes = tf.util.parseAxisParam(axis, x.shape);
+ var axes = origAxes;
+ var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
+ var permutedX = x;
+ if (permutedAxes != null) {
+ permutedX = transpose({ inputs: { x: x }, backend: backend, attrs: { perm: permutedAxes } });
+ axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
+ }
+ tf.backend_util.assertAxesAreInnerMostDims('any', axes, xRank);
+ var _a = tf.backend_util.computeOutAndReduceShapes(permutedX.shape, axes), outShape = _a[0], reduceShape = _a[1];
+ var inSize = tf.util.sizeFromShape(reduceShape);
+ var a2D = reshape({ inputs: { x: permutedX }, backend: backend, attrs: { shape: [-1, inSize] } });
+ var reduced = reduce(a2D, a2D.dtype, 'any', backend);
+ var res;
+ if (keepDims) {
+ var newShape = tf.backend_util.expandShapeToKeepDim(outShape, origAxes);
+ res = reshape({ inputs: { x: reduced }, backend: backend, attrs: { shape: newShape } });
+ }
+ else {
+ res = reshape({ inputs: { x: reduced }, backend: backend, attrs: { shape: outShape } });
+ }
+ backend.disposeIntermediateTensorInfo(a2D);
+ backend.disposeIntermediateTensorInfo(reduced);
+ if (permutedAxes != null) {
+ backend.disposeIntermediateTensorInfo(permutedX);
+ }
+ return res;
+ }
+ var anyConfig = {
+ kernelName: tf.Any,
+ backendName: 'webgl',
+ kernelFunc: any
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ArgMinMaxProgram = /** @class */ (function () {
+ function ArgMinMaxProgram(reduceInfo, op, firstPass) {
+ this.variableNames = ['A'];
+ var windowSize = reduceInfo.windowSize, batchSize = reduceInfo.batchSize, outSize = reduceInfo.outSize;
+ if (!firstPass) {
+ this.variableNames.push('bestIndicesA');
+ }
+ this.outputShape = [batchSize, outSize];
+ var compOp = (op === 'max') ? '>' : '<';
+ var indexSnippet = firstPass ?
+ '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 * " + windowSize + ";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < " + windowSize + "; i++) {\n int inIdx = " + indexSnippet + ";\n float candidate = getA(batch, inIdx);\n if (candidate " + compOp + " bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n ";
+ }
+ return ArgMinMaxProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ArgMinMaxPackedProgram = /** @class */ (function () {
+ function ArgMinMaxPackedProgram(shape, windowSize, op, firstPass) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ tf.util.assert(shape.length > 2, function () { return "Packed arg" + (op.charAt(0).toUpperCase() +
+ op.slice(1)) + " supports only inputs with rank above 2."; });
+ var inSize = shape[shape.length - 1];
+ var outSize = Math.ceil(inSize / windowSize);
+ this.outputShape = shape.slice(0, -1);
+ if (outSize > 1) {
+ this.outputShape.push(outSize);
+ }
+ if (!firstPass) {
+ this.variableNames.push('bestIndicesA');
+ }
+ var outShape = this.outputShape;
+ var rank = outShape.length;
+ var dtype = getCoordsDataType(rank);
+ var coords = getChannels('coords', rank);
+ var sourceLocSetup;
+ var sourceRank;
+ if (outSize === 1) {
+ sourceRank = rank + 1;
+ var sourceLocDType = getCoordsDataType(sourceRank);
+ sourceLocSetup = "\n " + sourceLocDType + " sourceLocR = " + sourceLocDType + "(" + coords.join() + ", 0);\n ++" + coords[rank - 1] + ";\n " + sourceLocDType + " sourceLocG = " + sourceLocDType + "(" + coords.join() + ", 0);\n ++" + coords[rank - 2] + ";\n " + sourceLocDType + " sourceLocA = " + sourceLocDType + "(" + coords.join() + ", 0);\n --" + coords[rank - 1] + ";\n " + sourceLocDType + " sourceLocB = " + sourceLocDType + "(" + coords.join() + ", 0);\n --" + coords[rank - 2] + ";";
+ }
+ else {
+ sourceRank = rank;
+ sourceLocSetup = "\n " + dtype + " sourceLocR = coords;\n ++" + coords[rank - 1] + ";\n " + dtype + " sourceLocG = coords;\n ++" + coords[rank - 2] + ";\n " + dtype + " sourceLocA = coords;\n --" + coords[rank - 1] + ";\n " + dtype + " sourceLocB = coords;\n --" + coords[rank - 2] + ";";
+ }
+ var channels = ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, sourceRank);
+ var inChannel = '.' + channels[sourceRank - 1]; // e.g. ".b" for rank 3.
+ var intChannels = channels.map(function (x) { return 'int ' + x; });
+ var srcRCoords = getChannels('sourceLocR', sourceRank - 1).concat('inIdx.r');
+ var srcGCoords = getChannels('sourceLocG', sourceRank - 1).concat('inIdx.g');
+ var srcBCoords = getChannels('sourceLocB', sourceRank - 1).concat('inIdx.b');
+ var srcACoords = getChannels('sourceLocA', sourceRank - 1).concat('inIdx.a');
+ var compOp = (op === 'max') ? 'greaterThan' : 'lessThan';
+ var fetchCandidateIdx = firstPass ? '' : "\n inIdx = round(vec4(getBestIndicesAChannel(" + srcRCoords.join() + "),\n getBestIndicesAChannel(" + srcGCoords.join() + "),\n getBestIndicesAChannel(" + srcBCoords.join() + "),\n getBestIndicesAChannel(" + srcACoords.join() + ")));";
+ var fetchValue = "vec4(\n getAChannel(" + srcRCoords.join() + "),\n hasNextCol ? getAChannel(" + srcGCoords.join() + ") : 0.,\n hasNextRow ? getAChannel(" + srcBCoords.join() + ") : 0.,\n hasNextRow && hasNextCol ? getAChannel(" + srcACoords.join() + ") : 0.)";
+ var getBestIndicesAChannelSnippet = firstPass ? '' : "\n float getBestIndicesAChannel(" + intChannels.join() + ") {\n return getChannel(getBestIndicesA(" + channels.join() + "),\n vec2(" + channels.slice(-2).join() + "));\n }";
+ this.userCode = "\n float getAChannel(" + intChannels.join() + ") {\n return getChannel(getA(" + channels.join() + "),\n vec2(" + channels.slice(-2).join() + "));\n }\n " + getBestIndicesAChannelSnippet + "\n void main() {\n " + dtype + " coords = getOutputCoords();\n bool hasNextCol = " + coords[rank - 1] + " < " + (outShape[rank - 1] - 1) + ";\n bool hasNextRow = " + coords[rank - 2] + " < " + (outShape[rank - 2] - 1) + ";\n " + sourceLocSetup + "\n ivec4 srcIdx = ivec4(sourceLocR" + inChannel + ", sourceLocG" + inChannel + ",\n sourceLocB" + inChannel + ", sourceLocA" + inChannel + ") * " + windowSize + ";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = " + fetchValue + ";\n\n for (int i = 0; i < " + windowSize + "; i++) {\n inIdx = srcIdx;\n " + fetchCandidateIdx + "\n vec4 candidate = " + fetchValue + ";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(" + compOp + "(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 ";
+ }
+ return ArgMinMaxPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function argReduce(backend, x, reduceType, bestIndicesA) {
+ if (bestIndicesA === void 0) { bestIndicesA = null; }
+ var batchSize = x.shape[0];
+ var inSize = x.shape[1];
+ if (bestIndicesA != null) {
+ batchSize = bestIndicesA.shape[0];
+ inSize = bestIndicesA.shape[1];
+ }
+ var windowSize = tf.backend_util.computeOptimalWindowSize(inSize);
+ var reduceInfo = { windowSize: windowSize, inSize: inSize, batchSize: batchSize, outSize: Math.ceil(inSize / windowSize) };
+ var program = new ArgMinMaxProgram(reduceInfo, reduceType, bestIndicesA == null);
+ var inputs = [x];
+ if (bestIndicesA != null) {
+ inputs.push(bestIndicesA);
+ }
+ var output = backend.runWebGLProgram(program, inputs, 'int32');
+ // No need to run another GPGPU program.
+ if (output.shape[1] === 1) {
+ return output;
+ }
+ var result = argReduce(backend, x, reduceType, output);
+ backend.disposeIntermediateTensorInfo(output);
+ return result;
+ }
+ function argReducePacked(backend, x, reduceType, bestIndicesA) {
+ if (bestIndicesA === void 0) { bestIndicesA = null; }
+ var inShape = bestIndicesA != null ? bestIndicesA.shape : x.shape;
+ var inSize = inShape[inShape.length - 1];
+ var windowSize = tf.backend_util.computeOptimalWindowSize(inSize);
+ var program = new ArgMinMaxPackedProgram(inShape, windowSize, reduceType, bestIndicesA == null);
+ var inputs = bestIndicesA == null ? [x] : [x, bestIndicesA];
+ var output = backend.runWebGLProgram(program, inputs, 'int32');
+ if (output.shape.length === x.shape.length) {
+ var result = argReducePacked(backend, x, reduceType, output);
+ backend.disposeIntermediateTensorInfo(output);
+ return result;
+ }
+ return output;
+ }
+ function argMinMaxReduce(backend, x, axis, reduceType) {
+ var axes = [axis];
+ tf.backend_util.assertAxesAreInnerMostDims('arg' + reduceType.charAt(0).toUpperCase() + reduceType.slice(1), axes, x.shape.length);
+ if (!tf.env().getBool('WEBGL_PACK_REDUCE') || x.shape.length <= 2) {
+ var intermediateTensorInfos = [];
+ var _a = tf.backend_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
+ var inSize = tf.util.sizeFromShape(reduceShape);
+ var a2D = reshape({ inputs: { x: x }, backend: backend, attrs: { shape: [-1, inSize] } });
+ intermediateTensorInfos.push(a2D);
+ var reduced = argReduce(backend, a2D, reduceType);
+ intermediateTensorInfos.push(reduced);
+ var reshaped = reshape({ inputs: { x: reduced }, backend: backend, attrs: { shape: outShape } });
+ intermediateTensorInfos.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return reshaped;
+ }
+ return argReducePacked(backend, x, reduceType);
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function argMax(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var axis = attrs.axis;
+ var axes = tf.util.parseAxisParam(axis, x.shape);
+ var permutedAxes = tf.backend_util.getAxesPermutation(axes, x.shape.length);
+ var $x = x;
+ var intermediateTensorInfos = [];
+ if (permutedAxes != null) {
+ $x = transpose({ inputs: { x: x }, backend: backend, attrs: { perm: permutedAxes } });
+ intermediateTensorInfos.push($x);
+ axes = tf.backend_util.getInnerMostAxes(axes.length, $x.shape.length);
+ }
+ tf.backend_util.assertAxesAreInnerMostDims('argMax', [axes[0]], $x.shape.length);
+ var out = argMinMaxReduce(backend, $x, axes[0], 'max');
+ intermediateTensorInfos.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return out;
+ }
+ var argMaxConfig = {
+ kernelName: tf.ArgMax,
+ backendName: 'webgl',
+ kernelFunc: argMax
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function argMin(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var axis = attrs.axis;
+ var axes = tf.util.parseAxisParam(axis, x.shape);
+ var permutedAxes = tf.backend_util.getAxesPermutation(axes, x.shape.length);
+ var $x = x;
+ var intermediateTensorInfos = [];
+ if (permutedAxes != null) {
+ $x = transpose({ inputs: { x: x }, backend: backend, attrs: { perm: permutedAxes } });
+ intermediateTensorInfos.push($x);
+ axes = tf.backend_util.getInnerMostAxes(axes.length, $x.shape.length);
+ }
+ tf.backend_util.assertAxesAreInnerMostDims('argMin', [axes[0]], $x.shape.length);
+ var out = argMinMaxReduce(backend, $x, axes[0], 'min');
+ intermediateTensorInfos.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return out;
+ }
+ var argMinConfig = {
+ kernelName: tf.ArgMin,
+ backendName: 'webgl',
+ kernelFunc: argMin
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ASIN = CHECK_NAN_SNIPPET + "\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n";
+ var asin = unaryKernelFunc({ opSnippet: ASIN });
+ var asinConfig = {
+ kernelName: tf.Asin,
+ backendName: 'webgl',
+ kernelFunc: asin,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ASINH = CHECK_NAN_SNIPPET + "return log(x + sqrt(x * x + 1.0));";
+ var asinh = unaryKernelFunc({ opSnippet: ASINH });
+ var asinhConfig = {
+ kernelName: tf.Asinh,
+ backendName: 'webgl',
+ kernelFunc: asinh,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ATAN = CHECK_NAN_SNIPPET + "\n return atan(x);\n";
+ var atan = unaryKernelFunc({ opSnippet: ATAN });
+ var atanConfig = {
+ kernelName: tf.Atan,
+ backendName: 'webgl',
+ kernelFunc: atan,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ATAN2 = CHECK_NAN_SNIPPET_BINARY + "\n return atan(a, b);\n";
+ var ATAN2_PACKED = "\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n " +
+ CHECK_NAN_SNIPPET_BINARY_PACKED + "\n return result;\n";
+ var atan2 = binaryKernelFunc({ opSnippet: ATAN2, packedOpSnippet: ATAN2_PACKED });
+ var atan2Config = {
+ kernelName: tf.Atan2,
+ backendName: 'webgl',
+ kernelFunc: atan2,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ATANH = CHECK_NAN_SNIPPET + "\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;";
+ var atanh = unaryKernelFunc({ opSnippet: ATANH });
+ var atanhConfig = {
+ kernelName: tf.Atanh,
+ backendName: 'webgl',
+ kernelFunc: atanh,
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var Pool2DProgram = /** @class */ (function () {
+ function Pool2DProgram(convInfo, poolType, computePositions, flattenPositions, includeBatchInIndex) {
+ if (flattenPositions === void 0) { flattenPositions = false; }
+ if (includeBatchInIndex === void 0) { includeBatchInIndex = false; }
+ this.variableNames = ['x'];
+ if (poolType === 'avg' && computePositions) {
+ throw new Error('Cannot compute positions for average pool.');
+ }
+ var filterWidth = convInfo.filterWidth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationHeight = convInfo.dilationHeight;
+ var dilationWidth = convInfo.dilationWidth;
+ var effectiveFilterHeight = convInfo.effectiveFilterHeight;
+ var effectiveFilterWidth = convInfo.effectiveFilterWidth;
+ var padTop = convInfo.padInfo.top;
+ var padLeft = convInfo.padInfo.left;
+ this.outputShape = convInfo.outShape;
+ var isAvgPool = poolType === 'avg';
+ var batchFlattenPositionStr = "((batch * " + convInfo.inHeight + " + xR) * " + convInfo.inWidth + " + xC) * " + convInfo.inChannels + " + d";
+ var flattenPositionStr = "(xR * " + convInfo.inWidth + " + xC) * " + convInfo.inChannels + " + d";
+ var initializationValue = '0.0';
+ if (!isAvgPool) {
+ // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.
+ initializationValue = '-1.0 / 1e-20';
+ }
+ if (computePositions) {
+ var compareOp_1 = '>=';
+ this.userCode = "\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < " + effectiveFilterHeight + ";\n wR += " + dilationHeight + ") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + effectiveFilterWidth + ";\n wC += " + dilationWidth + ") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= " + convInfo.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 " + compareOp_1 + " currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = " + (flattenPositions ? (includeBatchInIndex ? batchFlattenPositionStr :
+ flattenPositionStr) :
+ "wR * " + effectiveFilterWidth + " + wC") + ";\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";
+ return;
+ }
+ var compareOp = 'max';
+ var returnValue = poolType + "(" + poolType + "(" + poolType + "(" +
+ 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';
+ if (poolType === 'avg') {
+ returnValue = "avgValue / count";
+ }
+ var filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;
+ var filterWidthVec4Remainder = filterWidth % 4;
+ var updateSnippet = "\n if (" + isAvgPool + ") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = " + compareOp + "(values, minMaxValue);\n }\n ";
+ this.userCode = "\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n const float initializationValue = " + 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 >= " + convInfo.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(" + initializationValue + ");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < " + effectiveFilterHeight + ";\n wR += " + dilationHeight + ") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + filterWidthNearestVec4 + "; wC += 4) {\n int xC = xCCorner + wC * " + dilationWidth + ";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + " + dilationWidth + ", d),\n getValue(batch, xR, xC + 2 * " + dilationWidth + ", d),\n getValue(batch, xR, xC + 3 * " + dilationWidth + ", d)\n );\n\n " + updateSnippet + "\n }\n\n int xC = xCCorner + " + filterWidthNearestVec4 + ";\n if (" + (filterWidthVec4Remainder === 1) + ") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (filterWidthVec4Remainder === 2) + ") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + " + dilationWidth + ", d),\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (filterWidthVec4Remainder === 3) + ") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + " + dilationWidth + ", d),\n getValue(batch, xR, xC + 2 * " + dilationWidth + ", d),\n initializationValue\n );\n\n " + updateSnippet + "\n }\n }\n setOutput(" + returnValue + ");\n }\n ";
+ }
+ return Pool2DProgram;
+ }());
+ var Pool3DProgram = /** @class */ (function () {
+ function Pool3DProgram(convInfo, poolType, computePositions, flattenPositions, includeBatchInIndex) {
+ if (flattenPositions === void 0) { flattenPositions = false; }
+ if (includeBatchInIndex === void 0) { includeBatchInIndex = false; }
+ this.variableNames = ['x'];
+ if (poolType === 'avg' && computePositions) {
+ throw new Error('Cannot compute positions for average pool.');
+ }
+ var filterWidth = convInfo.filterWidth;
+ var strideDepth = convInfo.strideDepth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationDepth = convInfo.dilationDepth;
+ var dilationHeight = convInfo.dilationHeight;
+ var dilationWidth = convInfo.dilationWidth;
+ var effectiveFilterDepth = convInfo.effectiveFilterDepth;
+ var effectiveFilterHeight = convInfo.effectiveFilterHeight;
+ var effectiveFilterWidth = convInfo.effectiveFilterWidth;
+ var padFront = convInfo.padInfo.front;
+ var padTop = convInfo.padInfo.top;
+ var padLeft = convInfo.padInfo.left;
+ this.outputShape = convInfo.outShape;
+ var isAvgPool = poolType === 'avg';
+ var initializationValue = '0.0';
+ if (!isAvgPool) {
+ // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.
+ initializationValue = '-1.0 / 1e-20';
+ }
+ if (computePositions) {
+ var compareOp_2 = '>=';
+ this.userCode = "\n const ivec3 strides =\n ivec3(" + strideDepth + ", " + strideHeight + ", " + strideWidth + ");\n const ivec3 pads = ivec3(" + padFront + ", " + padTop + ", " + padLeft + ");\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 < " + effectiveFilterDepth + ";\n wD += " + dilationDepth + ") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= " + convInfo.inDepth + ") {\n continue;\n }\n\n for (int wR = 0; wR < " + effectiveFilterHeight + ";\n wR += " + dilationHeight + ") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + effectiveFilterWidth + ";\n wC += " + dilationWidth + ") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= " + convInfo.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 " + compareOp_2 + " currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = " + (flattenPositions ?
+ (includeBatchInIndex ?
+ "(((batch * " + convInfo.inDepth + " + xD) * " + convInfo.inHeight + " + xR) * " + convInfo.inWidth + " + xC) * " + convInfo.inChannels + " + ch" :
+ "((xD * " + convInfo.inHeight + " + xR) * " + convInfo.inWidth + " + xC) * " + convInfo.inChannels + " + ch") :
+ "wD * " + effectiveFilterHeight + " * " + effectiveFilterWidth + " +\n wR * " + effectiveFilterWidth + " + wC") + ";\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";
+ return;
+ }
+ var compareOp = 'max';
+ var returnValue = poolType + "(" + poolType + "(" + poolType + "(" +
+ 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';
+ if (poolType === 'avg') {
+ returnValue = "avgValue / count";
+ }
+ var filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;
+ var filterWidthVec4Remainder = filterWidth % 4;
+ var updateSnippet = "\n if (" + isAvgPool + ") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = " + compareOp + "(values, minMaxValue);\n }\n ";
+ this.userCode = "\n const ivec3 strides =\n ivec3(" + strideDepth + ", " + strideHeight + ", " + strideWidth + ");\n const ivec3 pads = ivec3(" + padFront + ", " + padTop + ", " + padLeft + ");\n const float initializationValue = " + 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 xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= " + convInfo.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(" + initializationValue + ");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < " + effectiveFilterDepth + ";\n wD += " + dilationDepth + ") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= " + convInfo.inDepth + ") {\n continue;\n }\n\n for (int wR = 0; wR < " + effectiveFilterHeight + ";\n wR += " + dilationHeight + ") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + filterWidthNearestVec4 + "; wC += 4) {\n int xC = xCCorner + wC * " + dilationWidth + ";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + " + dilationWidth + ", ch),\n getValue(batch, xD, xR, xC + 2 * " + dilationWidth + ", ch),\n getValue(batch, xD, xR, xC + 3 * " + dilationWidth + ", ch)\n );\n\n " + updateSnippet + "\n }\n\n int xC = xCCorner + " + filterWidthNearestVec4 + ";\n if (" + (filterWidthVec4Remainder === 1) + ") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (filterWidthVec4Remainder === 2) + ") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + " + dilationWidth + ", ch),\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (filterWidthVec4Remainder === 3) + ") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + " + dilationWidth + ", ch),\n getValue(batch, xD, xR, xC + 2 * " + dilationWidth + ", ch),\n initializationValue\n );\n\n " + updateSnippet + "\n }\n }\n setOutput(" + returnValue + ");\n }\n }\n ";
+ }
+ return Pool3DProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function avgPool(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ assertNotComplex(x, 'avgPool');
+ var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
+ var dilations = 1;
+ tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, dilations), function () { return 'Error in avgPool: Either strides or dilations must be 1. ' +
+ ("Got strides " + strides + " and dilations '" + dilations + "'"); });
+ var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
+ if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&
+ tf.util.arraysEqual(convInfo.inShape, convInfo.outShape)) {
+ return identity({ inputs: { x: x }, backend: backend });
+ }
+ var avgPoolProgram = new Pool2DProgram(convInfo, 'avg', false);
+ return backend.runWebGLProgram(avgPoolProgram, [x], 'float32');
+ }
+ var avgPoolConfig = {
+ kernelName: tf.AvgPool,
+ backendName: 'webgl',
+ kernelFunc: avgPool
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function avgPool3D(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, dataFormat = attrs.dataFormat;
+ var dilations = [1, 1, 1];
+ var convInfo = tf.backend_util.computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode, dataFormat);
+ var avgPoolProgram = new Pool3DProgram(convInfo, 'avg', false);
+ return backend.runWebGLProgram(avgPoolProgram, [x], 'float32');
+ }
+ var avgPool3DConfig = {
+ kernelName: tf.AvgPool3D,
+ backendName: 'webgl',
+ kernelFunc: avgPool3D
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var AvgPool2DBackpropProgram = /** @class */ (function () {
+ function AvgPool2DBackpropProgram(convInfo) {
+ this.variableNames = ['dy'];
+ this.outputShape = convInfo.inShape;
+ var filterHeight = convInfo.filterHeight;
+ var filterWidth = convInfo.filterWidth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationHeight = convInfo.dilationHeight;
+ var dilationWidth = convInfo.dilationWidth;
+ var effectiveFilterHeight = convInfo.effectiveFilterHeight;
+ var effectiveFilterWidth = convInfo.effectiveFilterWidth;
+ var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
+ var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
+ var avgMultiplier = 1 / (filterHeight * filterWidth);
+ this.userCode = "\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n const float avgMultiplier = float(" + avgMultiplier + ");\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 < " + effectiveFilterHeight + ";\n wR += " + dilationHeight + ") {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < " + effectiveFilterWidth + ";\n wC+= " + dilationWidth + ") {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.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 ";
+ }
+ return AvgPool2DBackpropProgram;
+ }());
+ var AvgPool3DBackpropProgram = /** @class */ (function () {
+ function AvgPool3DBackpropProgram(convInfo) {
+ this.variableNames = ['dy'];
+ this.outputShape = convInfo.inShape;
+ var filterDepth = convInfo.filterDepth;
+ var filterHeight = convInfo.filterHeight;
+ var filterWidth = convInfo.filterWidth;
+ var strideDepth = convInfo.strideDepth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationDepth = convInfo.dilationDepth;
+ var dilationHeight = convInfo.dilationHeight;
+ var dilationWidth = convInfo.dilationWidth;
+ var effectiveFilterDepth = convInfo.effectiveFilterDepth;
+ var effectiveFilterHeight = convInfo.effectiveFilterHeight;
+ var effectiveFilterWidth = convInfo.effectiveFilterWidth;
+ var padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
+ var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
+ var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
+ var avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);
+ this.userCode = "\n const ivec3 pads = ivec3(" + padFront + ", " + padTop + ", " + padLeft + ");\n const float avgMultiplier = float(" + avgMultiplier + ");\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 < " + effectiveFilterDepth + ";\n wD += " + dilationDepth + ") {\n float dyD = float(dyDCorner + wD) / " + strideDepth + ".0;\n\n if (dyD < 0.0 || dyD >= " + convInfo.outDepth + ".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < " + effectiveFilterHeight + ";\n wR += " + dilationHeight + ") {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < " + effectiveFilterWidth + ";\n wC += " + dilationWidth + ") {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.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 ";
+ }
+ return AvgPool3DBackpropProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function avgPool3DGrad(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var dy = inputs.dy, input = inputs.input;
+ var x = input;
+ var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
+ var dilations = [1, 1, 1];
+ var convInfo = tf.backend_util.computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
+ var avgPoolBackpropProgram = new AvgPool3DBackpropProgram(convInfo);
+ return backend.runWebGLProgram(avgPoolBackpropProgram, [dy], x.dtype);
+ }
+ var avgPoolGrad3DConfig = {
+ kernelName: tf.AvgPool3DGrad,
+ backendName: 'webgl',
+ kernelFunc: avgPool3DGrad
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function avgPoolGrad(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var dy = inputs.dy, input = inputs.input;
+ var x = input;
+ assertNotComplex([dy, input], 'avgPoolGrad');
+ var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad;
+ var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, 1 /* dilations */, pad);
+ var avgPoolBackpropProgram = new AvgPool2DBackpropProgram(convInfo);
+ return backend.runWebGLProgram(avgPoolBackpropProgram, [dy], x.dtype);
+ }
+ var avgPoolGradConfig = {
+ kernelName: tf.AvgPoolGrad,
+ backendName: 'webgl',
+ kernelFunc: avgPoolGrad
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function batchMatMul(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var a = inputs.a, b = inputs.b;
+ var transposeA = attrs.transposeA, transposeB = attrs.transposeB;
+ return batchMatMulImpl({ a: a, b: b, transposeA: transposeA, transposeB: transposeB, backend: backend });
+ }
+ var batchMatMulConfig = {
+ kernelName: tf.BatchMatMul,
+ backendName: 'webgl',
+ kernelFunc: batchMatMul,
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var BatchNormProgram = /** @class */ (function () {
+ function BatchNormProgram(xShape, meanShape, varianceShape, offsetShape, scaleShape, varianceEpsilon) {
+ this.outputShape = [];
+ this.variableNames = ['x', 'mean', 'variance'];
+ tf.backend_util.assertAndGetBroadcastShape(xShape, meanShape);
+ tf.backend_util.assertAndGetBroadcastShape(xShape, varianceShape);
+ var offsetSnippet = '0.0';
+ if (offsetShape != null) {
+ tf.backend_util.assertAndGetBroadcastShape(xShape, offsetShape);
+ this.variableNames.push('offset');
+ offsetSnippet = 'getOffsetAtOutCoords()';
+ }
+ var scaleSnippet = '1.0';
+ if (scaleShape != null) {
+ tf.backend_util.assertAndGetBroadcastShape(xShape, scaleShape);
+ this.variableNames.push('scale');
+ scaleSnippet = 'getScaleAtOutCoords()';
+ }
+ this.outputShape = xShape;
+ this.userCode = "\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = " + offsetSnippet + ";\n float scale = " + scaleSnippet + ";\n float inv = scale * inversesqrt(variance + float(" + varianceEpsilon + "));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n ";
+ }
+ return BatchNormProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var BatchNormPackedProgram = /** @class */ (function () {
+ function BatchNormPackedProgram(xShape, meanShape, varianceShape, offsetShape, scaleShape, varianceEpsilon) {
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.variableNames = ['x', 'mean', 'variance'];
+ tf.backend_util.assertAndGetBroadcastShape(xShape, meanShape);
+ tf.backend_util.assertAndGetBroadcastShape(xShape, varianceShape);
+ var offsetSnippet = 'vec4(0.0)';
+ if (offsetShape != null) {
+ tf.backend_util.assertAndGetBroadcastShape(xShape, offsetShape);
+ this.variableNames.push('offset');
+ offsetSnippet = 'getOffsetAtOutCoords()';
+ }
+ var scaleSnippet = 'vec4(1.0)';
+ if (scaleShape != null) {
+ tf.backend_util.assertAndGetBroadcastShape(xShape, scaleShape);
+ this.variableNames.push('scale');
+ scaleSnippet = 'getScaleAtOutCoords()';
+ }
+ this.outputShape = xShape;
+ this.userCode = "\n void main() {\n vec4 offset = " + offsetSnippet + ";\n vec4 scale = " + scaleSnippet + ";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(" + varianceEpsilon + "));\n\n setOutput((x - mean) * inv + offset);\n }\n ";
+ }
+ return BatchNormPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var batchNorm = function (_a) {
+ var inputs = _a.inputs, backend = _a.backend, attrs = _a.attrs;
+ var x = inputs.x, mean = inputs.mean, variance = inputs.variance, offset = inputs.offset, scale = inputs.scale;
+ tf.util.assert(mean.shape.length === variance.shape.length, function () { return 'Batch normalization gradient requires mean and variance to have ' +
+ 'equal ranks.'; });
+ tf.util.assert(offset == null || mean.shape.length === offset.shape.length, function () { return 'Batch normalization gradient requires mean and offset to have ' +
+ 'equal ranks.'; });
+ tf.util.assert(scale == null || mean.shape.length === scale.shape.length, function () { return 'Batch normalization gradient requires mean and scale to have ' +
+ 'equal ranks.'; });
+ var varianceEpsilon = attrs.varianceEpsilon;
+ if (varianceEpsilon == null) {
+ varianceEpsilon = 0.001;
+ }
+ var finalInputs = [x, mean, variance];
+ var offsetShape = null;
+ if (offset != null) {
+ offsetShape = offset.shape;
+ finalInputs.push(offset);
+ }
+ var scaleShape = null;
+ if (scale != null) {
+ scaleShape = scale.shape;
+ finalInputs.push(scale);
+ }
+ var program = tf.env().getBool('WEBGL_PACK_NORMALIZATION') ?
+ new BatchNormPackedProgram(x.shape, mean.shape, variance.shape, offsetShape, scaleShape, varianceEpsilon) :
+ new BatchNormProgram(x.shape, mean.shape, variance.shape, offsetShape, scaleShape, varianceEpsilon);
+ var output = backend.runWebGLProgram(program, finalInputs, finalInputs[0].dtype);
+ return output;
+ };
+ var batchNormConfig = {
+ kernelName: tf.FusedBatchNorm,
+ backendName: 'webgl',
+ kernelFunc: batchNorm,
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SliceProgram = /** @class */ (function () {
+ function SliceProgram(destSize) {
+ this.variableNames = ['source'];
+ this.outputShape = destSize;
+ this.rank = destSize.length;
+ var dtype = getCoordsDataType(this.rank);
+ var uniformPart = "uniform int start[" + this.rank + "];";
+ var sourceCoords = getCoords(this.rank);
+ var body;
+ var coordSum = destSize.map(function (_, i) {
+ return "sourceLoc." + coords[i] + " = start[" + i + "] + coords." + coords[i] + ";";
+ });
+ body = "\n " + dtype + " sourceLoc;\n " + dtype + " coords = getOutputCoords();\n " + coordSum.join('\n') + "\n ";
+ this.userCode = "\n " + uniformPart + "\n void main() {\n " + body + "\n setOutput(getSource(" + sourceCoords + "));\n }\n ";
+ }
+ SliceProgram.prototype.getCustomSetupFunc = function (start) {
+ var _this = this;
+ if (start.length !== this.rank) {
+ throw Error("The rank (" + this.rank + ") of the program must match the " +
+ ("length of start (" + start.length + ")"));
+ }
+ return function (gpgpu, webGLProgram) {
+ if (_this.startLoc == null) {
+ _this.startLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'start');
+ if (_this.startLoc == null) {
+ // This means the compiler has optimized and realized it doesn't need
+ // the uniform.
+ return;
+ }
+ }
+ gpgpu.gl.uniform1iv(_this.startLoc, start);
+ };
+ };
+ return SliceProgram;
+ }());
+ var coords = ['x', 'y', 'z', 'w', 'u', 'v'];
+ function getCoords(rank) {
+ if (rank === 1) {
+ return 'sourceLoc';
+ }
+ else if (rank <= 6) {
+ return coords.slice(0, rank).map(function (x) { return 'sourceLoc.' + x; }).join(',');
+ }
+ else {
+ throw Error("Slicing for rank " + rank + " is not yet supported");
+ }
+ }
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SlicePackedProgram = /** @class */ (function () {
+ function SlicePackedProgram(destSize) {
+ this.variableNames = ['source'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = destSize;
+ this.rank = destSize.length;
+ var dtype = getCoordsDataType(this.rank);
+ var coords = getChannels('coords', this.rank);
+ var sourceLoc = getChannels('sourceLoc', this.rank);
+ var innerDims = this.rank === 1 ? 'sourceLoc' : "vec2(" + sourceLoc.slice(-2).join() + ")";
+ var getChannel = "getChannel(getSource(" + sourceLoc.join() + "), " + innerDims + ")";
+ var upperRow = "\n result.x = " + getChannel + ";\n if (++" + coords[this.rank - 1] + " < " + destSize[this.rank - 1] + ") {\n ++" + sourceLoc[this.rank - 1] + ";\n result.y = " + getChannel + ";\n --" + sourceLoc[this.rank - 1] + ";\n }\n ";
+ var lowerRow = this.rank === 1 ? '' : "\n --" + coords[this.rank - 1] + ";\n if (++" + coords[this.rank - 2] + " < " + destSize[this.rank - 2] + ") {\n ++" + sourceLoc[this.rank - 2] + ";\n result.z = " + getChannel + ";\n if (++" + coords[this.rank - 1] + " < " + destSize[this.rank - 1] + ") {\n ++" + sourceLoc[this.rank - 1] + ";\n result.w = " + getChannel + ";\n }\n }\n ";
+ var sourceLocSetup = this.rank <= 4 ?
+ "sourceLoc = coords +\n " + dtype + "(" + destSize.map(function (_, i) { return "start[" + i + "]"; }).join() + ");" :
+ destSize.map(function (_, i) { return sourceLoc[i] + " = " + coords[i] + " + start[" + i + "];"; })
+ .join('\n');
+ this.userCode = "\n uniform int start[" + this.rank + "];\n void main() {\n " + dtype + " coords = getOutputCoords();\n " + dtype + " sourceLoc;\n " + sourceLocSetup + "\n vec4 result = vec4(0.);\n " + upperRow + "\n " + lowerRow + "\n setOutput(result);\n }\n ";
+ }
+ SlicePackedProgram.prototype.getCustomSetupFunc = function (start) {
+ var _this = this;
+ if (start.length !== this.rank) {
+ throw Error("The rank (" + this.rank + ") of the program must match the " +
+ ("length of start (" + start.length + ")"));
+ }
+ return function (gpgpu, webGLProgram) {
+ if (_this.startLoc == null) {
+ _this.startLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'start');
+ if (_this.startLoc == null) {
+ // This means the compiler has optimized and realized it doesn't need
+ // the uniform.
+ return;
+ }
+ }
+ gpgpu.gl.uniform1iv(_this.startLoc, start);
+ };
+ };
+ return SlicePackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function shallowSlice(x, begin, size, backend) {
+ var xTexData = backend.texData.get(x.dataId);
+ var t = backend.makeTensorInfo(size, x.dtype);
+ var newTexData = backend.texData.get(t.dataId);
+ // Copy texture data from the original tensor.
+ Object.assign(newTexData, xTexData);
+ newTexData.refCount = 1;
+ newTexData.shape = size;
+ newTexData.dtype = x.dtype;
+ var flatOffset = tf.slice_util.computeFlatOffset(begin, tf.util.computeStrides(x.shape));
+ if (xTexData.slice) {
+ // We are slicing an already sliced tensor, so we have to accumulate
+ // the offset.
+ flatOffset += xTexData.slice.flatOffset;
+ }
+ newTexData.slice = {
+ flatOffset: flatOffset,
+ // Point to the original dataId, which is used to do ref counting.
+ origDataId: xTexData.slice && xTexData.slice.origDataId || x.dataId
+ };
+ // Increase the ref count for that data bucket.
+ var refCount = backend.dataRefCount.get(newTexData.slice.origDataId) || 1;
+ backend.dataRefCount.set(newTexData.slice.origDataId, refCount + 1);
+ return t;
+ }
+ function slice(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var begin = attrs.begin, size = attrs.size;
+ var _a = tf.slice_util.parseSliceParams(x, begin, size), $begin = _a[0], $size = _a[1];
+ tf.slice_util.assertParamsValid(x, $begin, $size);
+ if (tf.util.sizeFromShape($size) === 0) {
+ return backend.makeTensorInfo($size, x.dtype, []);
+ }
+ // Run on cpu if dtype is string. For string, the backend represents it
+ // as Uint8Array[], where each Uint8Array is a character. Given that the
+ // computation is only on the outer array, uploading the whole data onto
+ // gpu is wasteful. Also, currently webgl doesn't have a design to
+ // upload and retrieve Uint8Array[] between cpu and gpu. Therefore, we
+ // just run the kernel on cpu if dtype is string.
+ if (backend.shouldExecuteOnCPU([x]) || x.dtype === 'string') {
+ var xTexData = backend.texData.get(x.dataId);
+ var outValues = sliceImplCPU(xTexData.values, $begin, $size, x.shape, x.dtype);
+ return backend.makeTensorInfo($size, x.dtype, outValues);
+ }
+ var isPacked = backend.texData.get(x.dataId).isPacked;
+ var isContinous = tf.slice_util.isSliceContinous(x.shape, $begin, $size);
+ if (isPacked || !isContinous) {
+ var program = tf.env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?
+ new SlicePackedProgram($size) :
+ new SliceProgram($size);
+ var customSetup = program.getCustomSetupFunc($begin);
+ return backend.runWebGLProgram(program, [x], x.dtype, customSetup);
+ }
+ backend.uploadToGPU(x.dataId);
+ return shallowSlice(x, $begin, $size, backend);
+ }
+ var sliceConfig = {
+ kernelName: tf.Slice,
+ backendName: 'webgl',
+ kernelFunc: slice
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var batchToSpaceND = function (args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var blockShape = attrs.blockShape, crops = attrs.crops;
+ tf.util.assert(x.shape.length <= 4, function () { return 'batchToSpaceND for rank > 4 with a WebGL backend not ' +
+ 'implemented yet'; });
+ var prod = blockShape.reduce(function (a, b) { return a * b; });
+ var reshaped = tf.backend_util.getReshaped(x.shape, blockShape, prod);
+ var permuted = tf.backend_util.getPermuted(reshaped.length, blockShape.length);
+ var reshapedPermuted = tf.backend_util.getReshapedPermuted(x.shape, blockShape, prod);
+ var sliceBeginCoords = tf.backend_util.getSliceBeginCoords(crops, blockShape.length);
+ var sliceSize = tf.backend_util.getSliceSize(reshapedPermuted, crops, blockShape.length);
+ var toDispose = [];
+ var reshapedIntermediate = reshape({ inputs: { x: x }, backend: backend, attrs: { shape: reshaped } });
+ var transposedIntermediate = transpose({ inputs: { x: reshapedIntermediate }, backend: backend, attrs: { perm: permuted } });
+ var reshapedIntermediate2 = reshape({
+ inputs: { x: transposedIntermediate },
+ backend: backend,
+ attrs: { shape: reshapedPermuted }
+ });
+ var sliced = slice({
+ inputs: { x: reshapedIntermediate2 },
+ backend: backend,
+ attrs: { begin: sliceBeginCoords, size: sliceSize }
+ });
+ toDispose.push(reshapedIntermediate);
+ toDispose.push(transposedIntermediate);
+ toDispose.push(reshapedIntermediate2);
+ toDispose.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return sliced;
+ };
+ var batchToSpaceNDConfig = {
+ kernelName: tf.BatchToSpaceND,
+ backendName: 'webgl',
+ kernelFunc: batchToSpaceND
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function bincount(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, weights = inputs.weights;
+ var size = attrs.size;
+ var xVals = backend.readSync(x.dataId);
+ var weightsVals = backend.readSync(weights.dataId);
+ var outVals = bincountImplCPU(xVals, weightsVals, weights.dtype, weights.shape, size);
+ return backend.makeTensorInfo([size], weights.dtype, outVals);
+ }
+ var bincountConfig = {
+ kernelName: tf.Bincount,
+ backendName: 'webgl',
+ kernelFunc: bincount
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var NOT_EQUAL = "return float(a != b);";
+ var notEqual = binaryKernelFunc({ opSnippet: NOT_EQUAL, cpuKernelImpl: notEqualImplCPU, dtype: 'bool' });
+ var notEqualConfig = {
+ kernelName: tf.NotEqual,
+ backendName: 'webgl',
+ kernelFunc: notEqual,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function real(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var input = inputs.input;
+ var inputData = backend.texData.get(input.dataId);
+ return identity({ inputs: { x: inputData.complexTensorInfos.real }, backend: backend });
+ }
+ var realConfig = {
+ kernelName: tf.Real,
+ backendName: 'webgl',
+ kernelFunc: real
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var TO_INT = "return float(int(x));";
+ function int(input, backend) {
+ var program = new UnaryOpProgram(input.shape, TO_INT);
+ var output = backend.runWebGLProgram(program, [input], 'int32');
+ return { dataId: output.dataId, shape: output.shape, dtype: output.dtype };
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function cast(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var dtype = attrs.dtype;
+ // Casting to complex64.
+ if (dtype === 'complex64') {
+ if (x.dtype === 'complex64') {
+ return identity({ inputs: { x: x }, backend: backend });
+ }
+ // TODO(annxingyuan): Import kernel function once zeros is modularized.
+ var zerosTensor = tf.zeros(x.shape);
+ var floatX = cast({ inputs: { x: x }, backend: backend, attrs: { dtype: 'float32' } });
+ var result = complex({ inputs: { real: floatX, imag: zerosTensor }, backend: backend });
+ zerosTensor.dispose();
+ backend.disposeIntermediateTensorInfo(floatX);
+ return result;
+ }
+ // Casting from complex64
+ if (x.dtype === 'complex64') {
+ var realPart = real({ inputs: { input: x }, backend: backend });
+ var result = cast({ inputs: { x: realPart }, backend: backend, attrs: { dtype: dtype } });
+ backend.disposeIntermediateTensorInfo(realPart);
+ return result;
+ }
+ if (!tf.util.hasEncodingLoss(x.dtype, dtype)) {
+ // We don't change the underlying data, since we cast to higher
+ // precision.
+ var result = identity({ inputs: { x: x }, backend: backend });
+ return { dataId: result.dataId, shape: result.shape, dtype: dtype };
+ }
+ if (dtype === 'int32') {
+ return int(x, backend);
+ }
+ if (dtype === 'bool') {
+ var zerosTensorInfo = backend.makeTensorInfo([], 'bool', tf.util.getTypedArrayFromDType('bool', 1));
+ var binaryInputs = { a: x, b: zerosTensorInfo };
+ var result = notEqual({ inputs: binaryInputs, backend: backend });
+ backend.disposeIntermediateTensorInfo(zerosTensorInfo);
+ return result;
+ }
+ throw new Error("Error in Cast: failed to cast " + x.dtype + " to " + dtype);
+ }
+ var castConfig = {
+ kernelName: tf.Cast,
+ backendName: 'webgl',
+ kernelFunc: cast
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var CEIL = "return ceil(x);";
+ var ceil = unaryKernelFunc({ opSnippet: CEIL, packedOpSnippet: CEIL, cpuKernelImpl: ceilImplCPU });
+ var ceilConfig = {
+ kernelName: tf.Ceil,
+ backendName: 'webgl',
+ kernelFunc: ceil
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ClipProgram = /** @class */ (function () {
+ function ClipProgram(aShape) {
+ this.variableNames = ['A'];
+ this.outputShape = aShape;
+ 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 ";
+ }
+ ClipProgram.prototype.getCustomSetupFunc = function (min, max) {
+ var _this = this;
+ return function (gpgpu, webGLProgram) {
+ if (_this.minLoc == null) {
+ _this.minLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'minVal');
+ _this.maxLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'maxVal');
+ }
+ gpgpu.gl.uniform1f(_this.minLoc, min);
+ gpgpu.gl.uniform1f(_this.maxLoc, max);
+ };
+ };
+ return ClipProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ClipPackedProgram = /** @class */ (function () {
+ function ClipPackedProgram(aShape) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = aShape;
+ 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 ";
+ }
+ ClipPackedProgram.prototype.getCustomSetupFunc = function (min, max) {
+ var _this = this;
+ return function (gpgpu, webGLProgram) {
+ if (_this.minLoc == null) {
+ _this.minLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'minVal');
+ _this.maxLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'maxVal');
+ }
+ gpgpu.gl.uniform1f(_this.minLoc, min);
+ gpgpu.gl.uniform1f(_this.maxLoc, max);
+ };
+ };
+ return ClipPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function clipByValue(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var clipValueMin = attrs.clipValueMin, clipValueMax = attrs.clipValueMax;
+ var program;
+ if (tf.env().getBool('WEBGL_PACK_CLIP')) {
+ program = new ClipPackedProgram(x.shape);
+ }
+ else {
+ program = new ClipProgram(x.shape);
+ }
+ var customSetup = program.getCustomSetupFunc(clipValueMin, clipValueMax);
+ return backend.runWebGLProgram(program, [x], x.dtype, customSetup);
+ }
+ var clipByValueConfig = {
+ kernelName: tf.ClipByValue,
+ backendName: 'webgl',
+ kernelFunc: clipByValue
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ComplexAbsProgram = /** @class */ (function () {
+ function ComplexAbsProgram(shape) {
+ this.variableNames = ['real', 'imag'];
+ this.outputShape = shape;
+ 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 ";
+ }
+ return ComplexAbsProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // Returns a TensorInfo with the complex shape and the dataId of the
+ // underlying part. We need to do this because a reshaped complex tensor is
+ // not reflected in its parts.
+ function makeComplexComponentTensorInfo(complexTensor, complexPart) {
+ return {
+ dataId: complexPart.dataId,
+ dtype: complexPart.dtype,
+ shape: complexTensor.shape
+ };
+ }
+ function complexAbs(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var x = inputs.x;
+ var xData = backend.texData.get(x.dataId);
+ var program = new ComplexAbsProgram(x.shape);
+ var programInputs = [
+ makeComplexComponentTensorInfo(x, xData.complexTensorInfos.real),
+ makeComplexComponentTensorInfo(x, xData.complexTensorInfos.imag),
+ ];
+ return backend.runWebGLProgram(program, programInputs, programInputs[0].dtype);
+ }
+ var complexAbsConfig = {
+ kernelName: tf.ComplexAbs,
+ backendName: 'webgl',
+ kernelFunc: complexAbs
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ConcatProgram = /** @class */ (function () {
+ // Concats 2d tensors along axis=1. See comments in MathBackendWebGL.concat().
+ function ConcatProgram(shapes) {
+ this.outputShape = [];
+ this.outputShape = tf.backend_util.computeOutShape(shapes, 1 /* axis */);
+ this.variableNames = shapes.map(function (_, i) { return "T" + i; });
+ var offsets = new Array(shapes.length - 1);
+ offsets[0] = shapes[0][1];
+ for (var i = 1; i < offsets.length; i++) {
+ offsets[i] = offsets[i - 1] + shapes[i][1];
+ }
+ var snippets = ["if (yC < " + offsets[0] + ") setOutput(getT0(yR, yC));"];
+ for (var i = 1; i < offsets.length; i++) {
+ var shift = offsets[i - 1];
+ snippets.push("else if (yC < " + offsets[i] + ") " +
+ ("setOutput(getT" + i + "(yR, yC-" + shift + "));"));
+ }
+ var lastIndex = offsets.length;
+ var lastShift = offsets[offsets.length - 1];
+ snippets.push("else setOutput(getT" + lastIndex + "(yR, yC-" + lastShift + "));");
+ this.userCode = "\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n " + snippets.join('\n ') + "\n }\n ";
+ }
+ return ConcatProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ConcatPackedProgram = /** @class */ (function () {
+ function ConcatPackedProgram(shapes, axis) {
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = [];
+ this.outputShape = tf.backend_util.computeOutShape(shapes, axis);
+ var shape = this.outputShape;
+ var rank = shape.length;
+ var dtype = getCoordsDataType(rank);
+ var coords = getChannels('coords', rank);
+ var channels = ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, rank);
+ this.variableNames = shapes.map(function (_, i) { return "T" + i; });
+ var offsets = new Array(shapes.length - 1);
+ offsets[0] = shapes[0][axis];
+ for (var i = 1; i < offsets.length; i++) {
+ offsets[i] = offsets[i - 1] + shapes[i][axis];
+ }
+ var channel = channels[axis];
+ var lastChannels = channels.slice(-2);
+ var allChannels = channels.join();
+ var getValueSnippet = "if (" + channel + " < " + offsets[0] + ") {\n return getChannel(\n getT0(" + allChannels + "), vec2(" + lastChannels.join() + "));\n }";
+ for (var i = 1; i < offsets.length; i++) {
+ var shift_1 = offsets[i - 1];
+ // Note: the >= comparison below may seem unnecessary given the check
+ // above but is needed to workaround branch execution issues on some
+ // devices. It makes all the conditions exclusive without relying on
+ // execution order.
+ getValueSnippet += "\n if (" + channel + " < " + offsets[i] + " && " + channel + " >= " + offsets[i - 1] + ") {\n return getChannel(\n getT" + i + "(" + shiftedChannels(channels, channel, shift_1) + "),\n vec2(" + shiftedChannels(lastChannels, channel, shift_1) + "));\n }";
+ }
+ var lastIndex = offsets.length;
+ var shift = offsets[offsets.length - 1];
+ getValueSnippet += "\n return getChannel(\n getT" + lastIndex + "(" + shiftedChannels(channels, channel, shift) + "),\n vec2(" + shiftedChannels(lastChannels, channel, shift) + "));";
+ this.userCode = "\n float getValue(" + channels.map(function (x) { return 'int ' + x; }) + ") {\n " + getValueSnippet + "\n }\n\n void main() {\n " + dtype + " coords = getOutputCoords();\n vec4 result = vec4(getValue(" + coords + "), 0., 0., 0.);\n\n " + coords[rank - 1] + " = " + coords[rank - 1] + " + 1;\n if (" + coords[rank - 1] + " < " + shape[rank - 1] + ") {\n result.g = getValue(" + coords + ");\n }\n\n " + coords[rank - 2] + " = " + coords[rank - 2] + " + 1;\n if (" + coords[rank - 2] + " < " + shape[rank - 2] + ") {\n result.a = getValue(" + coords + ");\n }\n\n " + coords[rank - 1] + " = " + coords[rank - 1] + " - 1;\n if (" + coords[rank - 2] + " < " + shape[rank - 2] + " &&\n " + coords[rank - 1] + " < " + shape[rank - 1] + ") {\n result.b = getValue(" + coords + ");\n }\n setOutput(result);\n }\n ";
+ }
+ return ConcatPackedProgram;
+ }());
+ /**
+ * Return an expression for coordinates into a vector where a given channel
+ * will be offset by [shift].
+ *
+ * @param channels the channels to consider
+ * @param channel the channel we want shifted
+ * @param shift the amount to subtract from the channel.
+ *
+ * @returns a string of the form 'x, y-[shift], z' where any one channel can
+ * have the shift applied.
+ */
+ function shiftedChannels(channels, channel, shift) {
+ var channelIdx = channels.indexOf(channel);
+ var res = channels.map(function (c, idx) {
+ if (idx === channelIdx) {
+ return c + " - " + shift;
+ }
+ else {
+ return c;
+ }
+ });
+ return res.join();
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function imag(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var input = inputs.input;
+ var inputData = backend.texData.get(input.dataId);
+ return identity({ inputs: { x: inputData.complexTensorInfos.imag }, backend: backend });
+ }
+ var imagConfig = {
+ kernelName: tf.Imag,
+ backendName: 'webgl',
+ kernelFunc: imag
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function concatImpl$1(inputs, axis, backend) {
+ var dtype = inputs[0].dtype;
+ if (dtype === 'complex64') {
+ var reals = inputs.map(function (t) { return real({ inputs: { input: t }, backend: backend }); });
+ var imags = inputs.map(function (t) { return imag({ inputs: { input: t }, backend: backend }); });
+ var realConcated = concatImpl$1(reals, axis, backend);
+ var imagConcated = concatImpl$1(imags, axis, backend);
+ var result_1 = complex({ inputs: { real: realConcated, imag: imagConcated }, backend: backend });
+ reals.forEach(function (r) { return backend.disposeIntermediateTensorInfo(r); });
+ imags.forEach(function (i) { return backend.disposeIntermediateTensorInfo(i); });
+ backend.disposeIntermediateTensorInfo(realConcated);
+ backend.disposeIntermediateTensorInfo(imagConcated);
+ return result_1;
+ }
+ var runOnCpu = backend.shouldExecuteOnCPU(inputs);
+ // Run on cpu if dtype is string. For string, the backend represents it
+ // as Uint8Array[], where each Uint8Array is a character. Given that the
+ // computation is only on the outer array, uploading the whole data onto
+ // gpu is wasteful. Also, currently webgl doesn't have a design to
+ // upload and retrieve Uint8Array[] between cpu and gpu. Therefore, we
+ // just run the kernel on cpu if dtype is string.
+ if (dtype === 'string') {
+ runOnCpu = true;
+ }
+ if (runOnCpu) {
+ // Any concat of n-dimensional tensors across any axis can be reduced to
+ // a concatenation of two-dimensional tensors across the axis 1 by first
+ // partitioning the axes of the original tensors into those less than the
+ // axis to be concatenated and the rest. Then reshape the tensors
+ // into a two-dimensional tensor by collapsing these two sets of axes and
+ // concatenate the resulting matrices across the axis 1, finally reshaping
+ // the result to have the proper shape.
+ var tensors2D_1 = inputs.map(function (t) {
+ var innerSize = tf.util.sizeFromShape(t.shape.slice(axis));
+ var shape = [-1, innerSize];
+ return reshape({ inputs: { x: t }, backend: backend, attrs: { shape: shape } });
+ });
+ var inputsValShapes = tensors2D_1.map(function (t) {
+ return { vals: backend.readSync(t.dataId), shape: t.shape };
+ });
+ // Concats 2d tensors along axis=1.
+ var outShape_1 = tf.backend_util.computeOutShape(tensors2D_1.map(function (t) { return t.shape; }), 1 /* axis */);
+ var simplyConcat = tensors2D_1[0].shape[0] === 1;
+ var outVals = concatImplCPU(inputsValShapes, outShape_1, dtype, simplyConcat);
+ var finalOutShape = tf.backend_util.computeOutShape(inputs.map(function (t) { return t.shape; }), axis);
+ var outInfo = backend.makeTensorInfo(finalOutShape, dtype, outVals);
+ tensors2D_1.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return outInfo;
+ }
+ if (inputs.length > tf.env().getNumber('WEBGL_MAX_TEXTURES_IN_SHADER')) {
+ var midIndex = Math.floor(inputs.length / 2);
+ var leftSide = concatImpl$1(inputs.slice(0, midIndex), axis, backend);
+ var rightSide = concatImpl$1(inputs.slice(midIndex), axis, backend);
+ var result_2 = concatImpl$1([leftSide, rightSide], axis, backend);
+ backend.disposeIntermediateTensorInfo(leftSide);
+ backend.disposeIntermediateTensorInfo(rightSide);
+ return result_2;
+ }
+ if (tf.env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') &&
+ inputs[0].shape.length > 1) {
+ var program_1 = new ConcatPackedProgram(inputs.map(function (t) { return t.shape; }), axis);
+ return backend.runWebGLProgram(program_1, inputs, dtype);
+ }
+ var _a = computeTensors2D(inputs, axis, backend), tensors2D = _a.tensors2D, outShape = _a.outShape;
+ var program = new ConcatProgram(tensors2D.map(function (t) { return t.shape; }));
+ var result = backend.runWebGLProgram(program, tensors2D, dtype);
+ tensors2D.forEach(function (r) { return backend.disposeIntermediateTensorInfo(r); });
+ var reshapedResult = reshape({ inputs: { x: result }, attrs: { shape: outShape }, backend: backend });
+ backend.disposeIntermediateTensorInfo(result);
+ return reshapedResult;
+ }
+ function computeTensors2D(inputs, axis, backend) {
+ // Any concat of n-dimensional tensors across any axis can be reduced to
+ // a concatenation of two-dimensional tensors across the axis 1 by first
+ // partitioning the axes of the original tensors into those less than the
+ // axis to be concatenated and the rest. Then reshape the tensors
+ // into a two-dimensional tensor by collapsing these two sets of axes and
+ // concatenate the resulting matrices across the axis 1, finally reshaping
+ // the result to have the proper shape.
+ var outShape = tf.backend_util.computeOutShape(inputs.map(function (t) { return t.shape; }), axis);
+ var tensors2D = inputs.map(function (x) { return reshape({
+ inputs: { x: x },
+ attrs: { shape: [-1, tf.util.sizeFromShape(x.shape.slice(axis))] },
+ backend: backend
+ }); });
+ return { tensors2D: tensors2D, outShape: outShape };
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function concat(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var axis = attrs.axis;
+ var $axis = tf.util.parseAxisParam(axis, inputs[0].shape)[0];
+ var outShape = tf.backend_util.computeOutShape(inputs.map(function (t) { return t.shape; }), $axis);
+ if (tf.util.sizeFromShape(outShape) === 0) {
+ return backend.makeTensorInfo(outShape, inputs[0].dtype, []);
+ }
+ // Keep only non-empty tensors (ignore tensors with 0 in their shape).
+ var $inputs = inputs.filter(function (t) { return tf.util.sizeFromShape(t.shape) > 0; });
+ if ($inputs.length === 1) {
+ return identity({ inputs: { x: $inputs[0] }, backend: backend });
+ }
+ var shapes = $inputs.map(function (t) { return t.shape; });
+ tf.backend_util.assertParamsConsistent(shapes, $axis);
+ return concatImpl$1($inputs, $axis, backend);
+ }
+ var concatConfig = {
+ kernelName: tf.Concat,
+ backendName: 'webgl',
+ kernelFunc: concat
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var Conv2DProgram = /** @class */ (function () {
+ function Conv2DProgram(convInfo, addBias, activation, hasPreluActivationWeights, hasLeakyreluAlpha) {
+ if (addBias === void 0) { addBias = false; }
+ if (activation === void 0) { activation = null; }
+ if (hasPreluActivationWeights === void 0) { hasPreluActivationWeights = false; }
+ if (hasLeakyreluAlpha === void 0) { hasLeakyreluAlpha = false; }
+ this.variableNames = ['x', 'W'];
+ this.outputShape = convInfo.outShape;
+ var padTop = convInfo.padInfo.top;
+ var padLeft = convInfo.padInfo.left;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationHeight = convInfo.dilationHeight;
+ var dilationWidth = convInfo.dilationWidth;
+ var filterHeight = convInfo.filterHeight;
+ var filterWidth = convInfo.filterWidth;
+ var inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;
+ var inputDepthVec4Remainder = convInfo.inChannels % 4;
+ var isChannelsLast = convInfo.dataFormat === 'channelsLast';
+ var rowDim = isChannelsLast ? 1 : 2;
+ var colDim = isChannelsLast ? 2 : 3;
+ var channelDim = isChannelsLast ? 3 : 1;
+ var activationSnippet = '', applyActivationSnippet = '';
+ if (activation) {
+ if (hasPreluActivationWeights) {
+ activationSnippet = "float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n " + activation + "\n }";
+ }
+ else if (hasLeakyreluAlpha) {
+ activationSnippet = "float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n " + activation + "\n }";
+ }
+ else {
+ activationSnippet = "\n float activation(float x) {\n " + activation + "\n }\n ";
+ }
+ applyActivationSnippet = "result = activation(result);";
+ }
+ var addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';
+ if (addBias) {
+ this.variableNames.push('bias');
+ }
+ if (hasPreluActivationWeights) {
+ this.variableNames.push('preluActivationWeights');
+ }
+ if (hasLeakyreluAlpha) {
+ this.variableNames.push('leakyreluAlpha');
+ }
+ this.userCode = "\n " + activationSnippet + "\n\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[" + channelDim + "];\n\n ivec2 xRCCorner =\n ivec2(coords[" + rowDim + "], coords[" + colDim + "]) * 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 < " + filterHeight + "; wR++) {\n int xR = xRCorner + wR * " + dilationHeight + ";\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n int xC = xCCorner + wC * " + dilationWidth + ";\n\n if (xC < 0 || xC >= " + convInfo.inWidth + ") {\n continue;\n }\n\n for (int d1 = 0; d1 < " + inputDepthNearestVec4 + "; 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 (" + isChannelsLast + ") {\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 (" + (inputDepthVec4Remainder === 1) + ") {\n\n if (" + isChannelsLast + ") {\n dotProd +=\n getX(batch, xR, xC, " + inputDepthNearestVec4 + ") *\n getW(wR, wC, " + inputDepthNearestVec4 + ", d2);\n } else {\n dotProd +=\n getX(batch, " + inputDepthNearestVec4 + ", xR, xC) *\n getW(wR, wC, " + inputDepthNearestVec4 + ", d2);\n }\n\n } else if (" + (inputDepthVec4Remainder === 2) + ") {\n vec2 wValues = vec2(\n getW(wR, wC, " + inputDepthNearestVec4 + ", d2),\n getW(wR, wC, " + inputDepthNearestVec4 + " + 1, d2)\n );\n\n if (" + isChannelsLast + ") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, " + inputDepthNearestVec4 + "),\n getX(batch, xR, xC, " + inputDepthNearestVec4 + " + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, " + inputDepthNearestVec4 + ", xR, xC),\n getX(batch, " + inputDepthNearestVec4 + " + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (" + (inputDepthVec4Remainder === 3) + ") {\n vec3 wValues = vec3(\n getW(wR, wC, " + inputDepthNearestVec4 + ", d2),\n getW(wR, wC, " + inputDepthNearestVec4 + " + 1, d2),\n getW(wR, wC, " + inputDepthNearestVec4 + " + 2, d2)\n );\n\n if (" + isChannelsLast + ") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, " + inputDepthNearestVec4 + "),\n getX(batch, xR, xC, " + inputDepthNearestVec4 + " + 1),\n getX(batch, xR, xC, " + inputDepthNearestVec4 + " + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, " + inputDepthNearestVec4 + ", xR, xC),\n getX(batch, " + inputDepthNearestVec4 + " + 1, xR, xC),\n getX(batch, " + inputDepthNearestVec4 + " + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n " + addBiasSnippet + "\n " + applyActivationSnippet + "\n setOutput(result);\n }\n ";
+ }
+ return Conv2DProgram;
+ }());
+ var Conv3DProgram = /** @class */ (function () {
+ function Conv3DProgram(convInfo) {
+ this.variableNames = ['x', 'W'];
+ this.outputShape = convInfo.outShape;
+ var padFront = convInfo.padInfo.front;
+ var padTop = convInfo.padInfo.top;
+ var padLeft = convInfo.padInfo.left;
+ var strideDepth = convInfo.strideDepth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationDepth = convInfo.dilationDepth;
+ var dilationHeight = convInfo.dilationHeight;
+ var dilationWidth = convInfo.dilationWidth;
+ var filterDepth = convInfo.filterDepth;
+ var filterHeight = convInfo.filterHeight;
+ var filterWidth = convInfo.filterWidth;
+ var inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;
+ var inputDepthVec4Remainder = convInfo.inChannels % 4;
+ this.userCode = "\n const ivec3 strides = ivec3(" + strideDepth + ", " + strideHeight + ", " + strideWidth + ");\n const ivec3 pads = ivec3(" + padFront + ", " + padTop + ", " + padLeft + ");\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 < " + filterDepth + "; wF++) {\n int xF = xFCorner + wF * " + dilationDepth + ";\n\n if (xF < 0 || xF >= " + convInfo.inDepth + ") {\n continue;\n }\n\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n int xR = xRCorner + wR * " + dilationHeight + ";\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n int xC = xCCorner + wC * " + dilationWidth + ";\n\n if (xC < 0 || xC >= " + convInfo.inWidth + ") {\n continue;\n }\n\n for (int d1 = 0; d1 < " + inputDepthNearestVec4 + "; 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 (" + (inputDepthVec4Remainder === 1) + ") {\n dotProd +=\n getX(batch, xF, xR, xC, " + inputDepthNearestVec4 + ") *\n getW(wF, wR, wC, " + inputDepthNearestVec4 + ", d2);\n } else if (" + (inputDepthVec4Remainder === 2) + ") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, " + inputDepthNearestVec4 + "),\n getX(batch, xF, xR, xC, " + inputDepthNearestVec4 + " + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, " + inputDepthNearestVec4 + ", d2),\n getW(wF, wR, wC, " + inputDepthNearestVec4 + " + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (" + (inputDepthVec4Remainder === 3) + ") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, " + inputDepthNearestVec4 + "),\n getX(batch, xF, xR, xC, " + inputDepthNearestVec4 + " + 1),\n getX(batch, xF, xR, xC, " + inputDepthNearestVec4 + " + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, " + inputDepthNearestVec4 + ", d2),\n getW(wF, wR, wC, " + inputDepthNearestVec4 + " + 1, d2),\n getW(wF, wR, wC, " + inputDepthNearestVec4 + " + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n ";
+ }
+ return Conv3DProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var Im2ColPackedProgram = /** @class */ (function () {
+ function Im2ColPackedProgram(outputShape, inputShape, convInfo) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = outputShape;
+ var filterWidth = convInfo.filterWidth, inChannels = convInfo.inChannels, strideWidth = convInfo.strideWidth, strideHeight = convInfo.strideHeight, padInfo = convInfo.padInfo, outWidth = convInfo.outWidth, dilationWidth = convInfo.dilationWidth, dilationHeight = convInfo.dilationHeight, dataFormat = convInfo.dataFormat;
+ var left = padInfo.left, top = padInfo.top;
+ var itemsPerBlockRow = inChannels * filterWidth;
+ var glsl = getGlslDifferences();
+ var isChannelsLast = dataFormat === 'channelsLast';
+ var rowDim = isChannelsLast ? 0 : 1;
+ var colDim = isChannelsLast ? 1 : 2;
+ var unrolled = "";
+ for (var row = 0; row <= 1; row++) {
+ for (var col = 0; col <= 1; col++) {
+ unrolled += "\n blockIndex = rc.y + " + col + ";\n pos = rc.x + " + row + ";\n\n if(blockIndex < " + outputShape[1] + " && pos < " + outputShape[0] + ") {\n offsetY = int(blockIndex / (" + outWidth + ")) * " + strideHeight + " - " + top + ";\n d0 = offsetY + " + dilationHeight + " * (pos / " + itemsPerBlockRow + ");\n\n if(d0 < " + inputShape[rowDim] + " && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), " + outWidth + ".) * " + strideWidth + ". - " + left + ".);\n d1 = offsetX + " + dilationWidth + " * (int(mod(float(pos), " + itemsPerBlockRow + ".) / " + inChannels + ".));\n\n if(d1 < " + inputShape[colDim] + " && d1 >= 0) {\n\n ch = int(mod(float(pos), " + inChannels + ".));\n\n if (" + isChannelsLast + ") {\n innerDims = vec2(d1, ch);\n result[" + (row * 2 + col) + "] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[" + (row * 2 + col) + "] = 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 " + unrolled + "\n\n " + glsl.output + " = result;\n }\n ";
+ }
+ return Im2ColPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // For 1x1 kernels that iterate through every point in the input, convolution
+ // can be expressed as matrix multiplication (without need for memory
+ // remapping).
+ function conv2dByMatMul(_a) {
+ var x = _a.x, filter = _a.filter, convInfo = _a.convInfo, backend = _a.backend, _b = _a.bias, bias = _b === void 0 ? null : _b, _c = _a.preluActivationWeights, preluActivationWeights = _c === void 0 ? null : _c, _d = _a.leakyreluAlpha, leakyreluAlpha = _d === void 0 ? 0 : _d, _e = _a.activation, activation = _e === void 0 ? null : _e;
+ // Reshapes conv2D input to 2D tensors, uses matMul and then reshape the
+ // result from 2D to 4D.
+ var xShape = x.shape;
+ var xTexData = backend.texData.get(x.dataId);
+ var sharedMatMulDim = convInfo.inChannels;
+ var outerShapeX = xShape[0] * xShape[1] * xShape[2];
+ var outerShapeFilter = convInfo.outChannels;
+ var isChannelsLast = convInfo.dataFormat === 'channelsLast';
+ var transposeA = false;
+ var transposeB = false;
+ var out;
+ var intermediates = [];
+ // TODO: Once reduction ops are packed, batchMatMul will always be packed
+ // and we can remove this condition.
+ var batchMatMulWillBeUnpacked = (outerShapeX === 1 || outerShapeFilter === 1) &&
+ sharedMatMulDim > MATMUL_SHARED_DIM_THRESHOLD;
+ var reshapeWillBeExpensive = xShape[2] % 2 !== 0 && !!xTexData.isPacked;
+ if (batchMatMulWillBeUnpacked || !tf.env().getBool('WEBGL_LAZILY_UNPACK') ||
+ !tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ||
+ !reshapeWillBeExpensive) {
+ var targetShape = isChannelsLast ? xShape[0] * xShape[1] * xShape[2] :
+ xShape[0] * xShape[2] * xShape[3];
+ var xReshaped = reshape({
+ inputs: { x: x },
+ backend: backend,
+ attrs: { shape: [1, targetShape, convInfo.inChannels] }
+ });
+ var filterReshaped = reshape({
+ inputs: { x: filter },
+ backend: backend,
+ attrs: { shape: [1, convInfo.inChannels, convInfo.outChannels] }
+ });
+ var result = batchMatMulImpl({
+ a: xReshaped,
+ b: filterReshaped,
+ transposeA: transposeA,
+ transposeB: transposeB,
+ backend: backend,
+ bias: bias,
+ activation: activation,
+ preluActivationWeights: preluActivationWeights,
+ leakyreluAlpha: leakyreluAlpha
+ });
+ out = reshape({ inputs: { x: result }, backend: backend, attrs: { shape: convInfo.outShape } });
+ intermediates.push(xReshaped);
+ intermediates.push(filterReshaped);
+ intermediates.push(result);
+ }
+ else {
+ // Following optimization is specific to packed |x| with odd row count
+ // (For example, in channelLast mode, 'row count' refers to x.shape[2]):
+ // we avoid expensive packed 2x2 reshape by padding row count to next,
+ // even number. When x.shape[2] is odd, the result of packed batchMatMul is
+ // the same (has the same texture layout and and values in the texture) as
+ // it is for even x.shape[2] + 1. We make the odd-rows tensor to look like
+ // even-rows tensor before the operation and, after the batchMatMul,
+ // fix the even-rows result to have odd number of rows.
+ var targetShape = isChannelsLast ?
+ xShape[0] * xShape[1] * (xShape[2] + 1) :
+ xShape[0] * xShape[2] * (xShape[3] + 1);
+ var xReshaped_1 = {
+ dataId: x.dataId,
+ shape: [1, targetShape, convInfo.inChannels],
+ dtype: x.dtype
+ };
+ // xTexData.shape gets referenced from GPGPUBinary.inShapeInfos.
+ // Decrementing row count, after batchMatMul->...->compileProgram leads to
+ // invalid row count within the reference in GPGPUBinary.inShapeInfos.
+ // Alternative fix would be to provide a copy to GPGPUBinary.inShapeInfos
+ // in compileProgram method, but that would affect compilation of all
+ // programs - instead, provide a copy here, with even row count, before
+ // calling batchMatMul->...->compileProgram and after that, the original
+ // xTexData.shape is restored.
+ var originalXTexDataShape = xTexData.shape;
+ xTexData.shape = xTexData.shape.slice();
+ xTexData.shape[xTexData.shape.length - 2]++;
+ tf.util.assert(isReshapeFree(xTexData.shape, xReshaped_1.shape), function () { return "packed reshape " + xTexData.shape + " to " + xReshaped_1.shape + " isn't free"; });
+ var filterReshaped = reshape({
+ inputs: { x: filter },
+ backend: backend,
+ attrs: { shape: [1, convInfo.inChannels, convInfo.outChannels] }
+ });
+ intermediates.push(filterReshaped);
+ var pointwiseConv = batchMatMulImpl({
+ a: xReshaped_1,
+ b: filterReshaped,
+ backend: backend,
+ transposeA: transposeA,
+ transposeB: transposeB,
+ bias: bias,
+ activation: activation,
+ preluActivationWeights: preluActivationWeights,
+ leakyreluAlpha: leakyreluAlpha
+ });
+ var pointwiseConvTexData = backend.texData.get(pointwiseConv.dataId);
+ tf.util.assert(pointwiseConvTexData.isPacked, function () { return 'batchMatMul result is expected to be packed'; });
+ // Restore the input shape to original.
+ xTexData.shape = originalXTexDataShape;
+ // Set the output shape - there is no need for expensive reshape as data
+ // layout is already correct.
+ pointwiseConvTexData.shape = convInfo.outShape;
+ out = identity({ inputs: { x: pointwiseConv }, backend: backend });
+ out.shape = convInfo.outShape;
+ intermediates.push(pointwiseConv);
+ }
+ for (var _i = 0, intermediates_1 = intermediates; _i < intermediates_1.length; _i++) {
+ var i = intermediates_1[_i];
+ backend.disposeIntermediateTensorInfo(i);
+ }
+ return out;
+ }
+ // Implements the im2row algorithm as outlined in "High Performance
+ // Convolutional Neural Networks for Document Processing" (Suvisoft, 2006)
+ function conv2dWithIm2Row(_a) {
+ var x = _a.x, filter = _a.filter, convInfo = _a.convInfo, backend = _a.backend, _b = _a.bias, bias = _b === void 0 ? null : _b, _c = _a.preluActivationWeights, preluActivationWeights = _c === void 0 ? null : _c, _d = _a.leakyreluAlpha, leakyreluAlpha = _d === void 0 ? 0 : _d, _e = _a.activation, activation = _e === void 0 ? null : _e;
+ // Rearranges conv2d input so each block to be convolved over forms the
+ // column of a new matrix with shape [filterWidth * filterHeight *
+ // inChannels, outHeight * outWidth]. The filter is also rearranged so each
+ // output channel forms a row of a new matrix with shape [outChannels,
+ // filterWidth * filterHeight * inChannels]. The convolution is then
+ // computed by multiplying these matrices and reshaping the result.
+ var filterWidth = convInfo.filterWidth, filterHeight = convInfo.filterHeight, inChannels = convInfo.inChannels, outWidth = convInfo.outWidth, outHeight = convInfo.outHeight, dataFormat = convInfo.dataFormat;
+ var isChannelsLast = dataFormat === 'channelsLast';
+ var sharedDim = filterWidth * filterHeight * inChannels;
+ var numCols = outHeight * outWidth;
+ var x2ColShape = [sharedDim, numCols];
+ var transposeA = true;
+ var transposeB = false;
+ var intermediates = [];
+ var xSqueezed = reshape({ inputs: { x: x }, backend: backend, attrs: { shape: x.shape.slice(1) } });
+ var w2Row = reshape({
+ inputs: { x: filter },
+ backend: backend,
+ attrs: { shape: [1, sharedDim, tf.util.sizeFromShape(filter.shape) / sharedDim] }
+ });
+ intermediates.push(xSqueezed);
+ intermediates.push(w2Row);
+ var im2ColProgram = new Im2ColPackedProgram(x2ColShape, xSqueezed.shape, convInfo);
+ var im2Col = backend.runWebGLProgram(im2ColProgram, [xSqueezed], 'float32');
+ var im2ColReshaped = reshape({
+ inputs: { x: im2Col },
+ backend: backend,
+ attrs: { shape: [1, x2ColShape[0], x2ColShape[1]] }
+ });
+ intermediates.push(im2Col);
+ intermediates.push(im2ColReshaped);
+ var hasBias = bias != null;
+ var hasPreluActivationWeights = preluActivationWeights != null;
+ var hasLeakyreluAlpha = activation === 'leakyrelu';
+ var fusedActivation = activation ? mapActivationToShaderProgram(activation, true) : null;
+ var matmulProgram = new MatMulPackedProgram(im2ColReshaped.shape, w2Row.shape, [1, numCols, convInfo.outChannels], transposeA, transposeB, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
+ var inputs = [im2ColReshaped, w2Row];
+ if (bias) {
+ inputs.push(bias);
+ }
+ if (hasPreluActivationWeights) {
+ inputs.push(preluActivationWeights);
+ }
+ if (hasLeakyreluAlpha) {
+ var $leakyreluAlpha = backend.makeTensorInfo([], 'float32', tf.util.createScalarValue(leakyreluAlpha, 'float32'));
+ inputs.push($leakyreluAlpha);
+ intermediates.push($leakyreluAlpha);
+ }
+ var product = backend.runWebGLProgram(matmulProgram, inputs, 'float32');
+ var outShape = isChannelsLast ?
+ [1, outHeight, outWidth, convInfo.outChannels] :
+ [1, convInfo.outChannels, outHeight, outWidth];
+ var out = reshape({ inputs: { x: product }, backend: backend, attrs: { shape: outShape } });
+ intermediates.push(product);
+ for (var _i = 0, intermediates_2 = intermediates; _i < intermediates_2.length; _i++) {
+ var i = intermediates_2[_i];
+ backend.disposeIntermediateTensorInfo(i);
+ }
+ return out;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function conv2d(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, filter = inputs.filter;
+ var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode;
+ var $dataFormat = tf.backend_util.convertConv2DDataFormat(dataFormat);
+ var convInfo = tf.backend_util.computeConv2DInfo(x.shape, filter.shape, strides, dilations, pad, dimRoundingMode, false /* depthwise */, $dataFormat);
+ var out;
+ if (convInfo.filterHeight === 1 && convInfo.filterWidth === 1 &&
+ convInfo.dilationHeight === 1 && convInfo.dilationWidth === 1 &&
+ convInfo.strideHeight === 1 && convInfo.strideWidth === 1 &&
+ (convInfo.padInfo.type === 'SAME' || convInfo.padInfo.type === 'VALID')) {
+ out = conv2dByMatMul({ x: x, filter: filter, convInfo: convInfo, backend: backend });
+ }
+ else if (tf.env().getBool('WEBGL_CONV_IM2COL') && x.shape[0] === 1) {
+ out = conv2dWithIm2Row({ x: x, filter: filter, convInfo: convInfo, backend: backend });
+ }
+ else {
+ var program = new Conv2DProgram(convInfo);
+ out = backend.runWebGLProgram(program, [x, filter], 'float32');
+ }
+ var outReshaped = reshape({ inputs: { x: out }, backend: backend, attrs: { shape: convInfo.outShape } });
+ backend.disposeIntermediateTensorInfo(out);
+ return outReshaped;
+ }
+ var conv2DConfig = {
+ kernelName: tf.Conv2D,
+ backendName: 'webgl',
+ kernelFunc: conv2d,
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var Conv2DDerFilterProgram = /** @class */ (function () {
+ function Conv2DDerFilterProgram(convInfo) {
+ this.variableNames = ['x', 'dy'];
+ this.outputShape = convInfo.filterShape;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var padTop = convInfo.padInfo.top;
+ var padLeft = convInfo.padInfo.left;
+ var isChannelsLast = convInfo.dataFormat === 'channelsLast';
+ 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 < " + convInfo.batchSize + "; b++) {\n for (int yR = 0; yR < " + convInfo.outHeight + "; yR++) {\n int xR = wR + yR * " + strideHeight + " - " + padTop + ";\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int yC = 0; yC < " + convInfo.outWidth + "; yC++) {\n int xC = wC + yC * " + strideWidth + " - " + padLeft + ";\n\n if (xC < 0 || xC >= " + convInfo.inWidth + ") {\n continue;\n }\n\n if (" + isChannelsLast + ") {\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 ";
+ }
+ return Conv2DDerFilterProgram;
+ }());
+ var Conv2DDerInputProgram = /** @class */ (function () {
+ function Conv2DDerInputProgram(convInfo) {
+ this.variableNames = ['dy', 'W'];
+ this.outputShape = convInfo.inShape;
+ var filterHeight = convInfo.filterHeight;
+ var filterWidth = convInfo.filterWidth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var isChannelsLast = convInfo.dataFormat === 'channelsLast';
+ var padTop = filterHeight - 1 - convInfo.padInfo.top;
+ var padLeft = filterWidth - 1 - convInfo.padInfo.left;
+ var rowDim = isChannelsLast ? 1 : 2;
+ var colDim = isChannelsLast ? 2 : 3;
+ var channelDim = isChannelsLast ? 3 : 1;
+ this.userCode = "\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[" + channelDim + "];\n\n ivec2 dyCorner = ivec2(coords[" + rowDim + "], coords[" + colDim + "]) - 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 < " + filterHeight + "; wR++) {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = " + filterHeight + " - 1 - wR;\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.outWidth + ".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = " + filterWidth + " - 1 - wC;\n\n for (int d2 = 0; d2 < " + convInfo.outChannels + "; d2++) {\n\n if (" + isChannelsLast + ") {\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 ";
+ }
+ return Conv2DDerInputProgram;
+ }());
+ var Conv3DDerFilterProgram = /** @class */ (function () {
+ function Conv3DDerFilterProgram(convInfo) {
+ this.variableNames = ['x', 'dy'];
+ this.outputShape = convInfo.filterShape;
+ var strideDepth = convInfo.strideDepth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var padFront = convInfo.padInfo.front;
+ var padTop = convInfo.padInfo.top;
+ var padLeft = convInfo.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 < " + convInfo.batchSize + "; b++) {\n for (int yF = 0; yF < " + convInfo.outDepth + "; yF++) {\n int xF = wF + yF * " + strideDepth + " - " + padFront + ";\n\n if (xF < 0 || xF >= " + convInfo.inDepth + ") {\n continue;\n }\n\n for (int yR = 0; yR < " + convInfo.outHeight + "; yR++) {\n int xR = wR + yR * " + strideHeight + " - " + padTop + ";\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int yC = 0; yC < " + convInfo.outWidth + "; yC++) {\n int xC = wC + yC * " + strideWidth + " - " + padLeft + ";\n\n if (xC < 0 || xC >= " + convInfo.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 ";
+ }
+ return Conv3DDerFilterProgram;
+ }());
+ var Conv3DDerInputProgram = /** @class */ (function () {
+ function Conv3DDerInputProgram(convInfo) {
+ this.variableNames = ['dy', 'W'];
+ this.outputShape = convInfo.inShape;
+ var filterDepth = convInfo.filterDepth;
+ var filterHeight = convInfo.filterHeight;
+ var filterWidth = convInfo.filterWidth;
+ var strideDepth = convInfo.strideDepth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var padFront = filterDepth - 1 - convInfo.padInfo.front;
+ var padTop = filterHeight - 1 - convInfo.padInfo.top;
+ var padLeft = filterWidth - 1 - convInfo.padInfo.left;
+ this.userCode = "\n const ivec3 pads = ivec3(" + padFront + ", " + padTop + ", " + padLeft + ");\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 < " + filterDepth + "; wF++) {\n float dyF = float(dyFCorner + wF) / " + strideDepth + ".0;\n\n if (dyF < 0.0 || dyF >= " + convInfo.outDepth + ".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = " + filterDepth + " - 1 - wF;\n\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = " + filterHeight + " - 1 - wR;\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.outWidth + ".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = " + filterWidth + " - 1 - wC;\n\n for (int d2 = 0; d2 < " + convInfo.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 ";
+ }
+ return Conv3DDerInputProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function conv2DBackpropFilter(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, dy = inputs.dy;
+ var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dimRoundingMode = attrs.dimRoundingMode, filterShape = attrs.filterShape;
+ var $dataFormat = tf.backend_util.convertConv2DDataFormat(dataFormat);
+ var convInfo = tf.backend_util.computeConv2DInfo(x.shape, filterShape, strides, 1 /* dilations */, pad, dimRoundingMode, false /* depthwise */, $dataFormat);
+ var program = new Conv2DDerFilterProgram(convInfo);
+ return backend.runWebGLProgram(program, [x, dy], 'float32');
+ }
+ var conv2DBackpropFilterConfig = {
+ kernelName: tf.Conv2DBackpropFilter,
+ backendName: 'webgl',
+ kernelFunc: conv2DBackpropFilter,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function conv2DBackpropInput(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var dy = inputs.dy, filter = inputs.filter;
+ var inputShape = attrs.inputShape, strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dimRoundingMode = attrs.dimRoundingMode;
+ var $dataFormat = tf.backend_util.convertConv2DDataFormat(dataFormat);
+ var convInfo = tf.backend_util.computeConv2DInfo(inputShape, filter.shape, strides, 1 /* dilations */, pad, dimRoundingMode, false, $dataFormat);
+ var program = new Conv2DDerInputProgram(convInfo);
+ return backend.runWebGLProgram(program, [dy, filter], 'float32');
+ }
+ var conv2DBackpropInputConfig = {
+ kernelName: tf.Conv2DBackpropInput,
+ backendName: 'webgl',
+ kernelFunc: conv2DBackpropInput,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function conv3D(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, filter = inputs.filter;
+ var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations;
+ var convInfo = tf.backend_util.computeConv3DInfo(x.shape, filter.shape, strides, dilations, pad);
+ var program = new Conv3DProgram(convInfo);
+ return backend.runWebGLProgram(program, [x, filter], 'float32');
+ }
+ var conv3DConfig = {
+ kernelName: tf.Conv3D,
+ backendName: 'webgl',
+ kernelFunc: conv3D,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function conv3DBackpropFilterV2(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, dy = inputs.dy;
+ var strides = attrs.strides, pad = attrs.pad, filterShape = attrs.filterShape;
+ var convInfo = tf.backend_util.computeConv3DInfo(x.shape, filterShape, strides, 1 /* dilations */, pad);
+ var program = new Conv3DDerFilterProgram(convInfo);
+ return backend.runWebGLProgram(program, [x, dy], 'float32');
+ }
+ var conv3DBackpropFilterV2Config = {
+ kernelName: tf.Conv3DBackpropFilterV2,
+ backendName: 'webgl',
+ kernelFunc: conv3DBackpropFilterV2
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function conv3DBackpropInput(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var dy = inputs.dy, filter = inputs.filter;
+ var pad = attrs.pad, strides = attrs.strides, inputShape = attrs.inputShape;
+ var convInfo = tf.backend_util.computeConv3DInfo(inputShape, filter.shape, strides, 1 /* dilations */, pad);
+ var program = new Conv3DDerInputProgram(convInfo);
+ return backend.runWebGLProgram(program, [dy, filter], 'float32');
+ }
+ var conv3DBackpropInputConfig = {
+ kernelName: tf.Conv3DBackpropInputV2,
+ backendName: 'webgl',
+ kernelFunc: conv3DBackpropInput,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var COS = CHECK_NAN_SNIPPET_UNARY + "\n return cos(x);\n";
+ var cos = unaryKernelFunc({ opSnippet: COS });
+ var cosConfig = {
+ kernelName: tf.Cos,
+ backendName: 'webgl',
+ kernelFunc: cos,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var COSH = "\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n";
+ var cosh = unaryKernelFunc({ opSnippet: COSH });
+ var coshConfig = {
+ kernelName: tf.Cosh,
+ backendName: 'webgl',
+ kernelFunc: cosh,
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var CropAndResizeProgram = /** @class */ (function () {
+ function CropAndResizeProgram(imageShape, boxShape, cropSize, method, extrapolationValue) {
+ this.variableNames = ['Image', 'Boxes', 'BoxInd'];
+ this.outputShape = [];
+ var batch = imageShape[0], imageHeight = imageShape[1], imageWidth = imageShape[2], depth = imageShape[3];
+ var numBoxes = boxShape[0];
+ var cropHeight = cropSize[0], cropWidth = cropSize[1];
+ this.outputShape = [numBoxes, cropHeight, cropWidth, depth];
+ var methodId = method === 'bilinear' ? 1 : 0;
+ var _a = [imageHeight - 1 + ".0", imageWidth - 1 + ".0"], inputHeightFloat = _a[0], inputWidthFloat = _a[1];
+ var _b = cropHeight > 1 ?
+ [
+ "" + (imageHeight - 1) / (cropHeight - 1),
+ '(y2-y1) * height_ratio',
+ "y1*" + inputHeightFloat + " + float(y)*(height_scale)",
+ ] :
+ [
+ '0.0',
+ '0.0',
+ "0.5 * (y1+y2) * " + inputHeightFloat,
+ ], heightRatio = _b[0], heightScale = _b[1], inY = _b[2];
+ var _c = cropWidth > 1 ?
+ [
+ "" + (imageWidth - 1) / (cropWidth - 1),
+ '(x2-x1) * width_ratio',
+ "x1*" + inputWidthFloat + " + float(x)*(width_scale)",
+ ] :
+ [
+ '0.0',
+ '0.0',
+ "0.5 * (x1+x2) * " + inputWidthFloat,
+ ], widthRatio = _c[0], widthScale = _c[1], inX = _c[2];
+ // Reference implementation
+ // tslint:disable-next-line:max-line-length
+ // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/crop_and_resize_op_gpu.cu.cc
+ this.userCode = "\n const float height_ratio = float(" + heightRatio + ");\n const float width_ratio = float(" + widthRatio + ");\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 >= " + batch + ") {\n return;\n }\n\n float height_scale = " + heightScale + ";\n float width_scale = " + widthScale + ";\n\n float in_y = " + inY + ";\n if( in_y < 0.0 || in_y > " + inputHeightFloat + " ) {\n setOutput(float(" + extrapolationValue + "));\n return;\n }\n float in_x = " + inX + ";\n if( in_x < 0.0 || in_x > " + inputWidthFloat + " ) {\n setOutput(float(" + extrapolationValue + "));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(" + methodId + " == 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 ";
+ }
+ return CropAndResizeProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var cropAndResize = function (args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var image = inputs.image, boxes = inputs.boxes, boxInd = inputs.boxInd;
+ var cropSize = attrs.cropSize, method = attrs.method, extrapolationValue = attrs.extrapolationValue;
+ var program = new CropAndResizeProgram(image.shape, boxes.shape, cropSize, method, extrapolationValue);
+ return backend.runWebGLProgram(program, [image, boxes, boxInd], 'float32');
+ };
+ var cropAndResizeConfig = {
+ kernelName: tf.CropAndResize,
+ backendName: 'webgl',
+ kernelFunc: cropAndResize
+ };
+
+ var CumSumProgram = /** @class */ (function () {
+ function CumSumProgram(shape, exclusive, reverse) {
+ this.variableNames = ['x'];
+ this.outputShape = shape;
+ var rank = shape.length;
+ var val = exclusive ? '0.0' : "getX(" + getCoords$1(rank, 'coords') + ")";
+ var length = shape[shape.length - 1];
+ var condition = '';
+ var idxString = '';
+ // When exclusive is set, the cumsum op becomes roll op that copies the
+ // value from the previous index based on the direction specified by the
+ // reverse flag.
+ if (exclusive) {
+ condition = reverse ? "end != " + (length - 1) : 'end != 0';
+ idxString = reverse ? 'end + 1' : 'end - 1';
+ }
+ else {
+ condition = reverse ? "end + pow2 < " + length : 'end >= pow2';
+ idxString = (reverse ? 'end + pow2' : 'end - pow2');
+ }
+ this.userCode = "\n uniform float index;\n void main() {\n " + getCoordsDataType(rank) + " coords = getOutputCoords();\n int end = " + getFinalCoord(rank, 'coords') + ";\n float val = " + val + ";\n int pow2 = int(pow(2.0, index));\n if (" + condition + ") {\n int idx = " + idxString + ";\n " + getFinalCoord(rank, 'coords') + " = idx;\n val += getX(" + getCoords$1(rank, 'coords') + ");\n }\n setOutput(val);\n }\n ";
+ }
+ CumSumProgram.prototype.getCustomSetupFunc = function (index) {
+ var _this = this;
+ return function (gpgpu, webGLProgram) {
+ if (_this.index == null) {
+ _this.index = gpgpu.getUniformLocation(webGLProgram, 'index');
+ }
+ gpgpu.gl.uniform1f(_this.index, index);
+ };
+ };
+ return CumSumProgram;
+ }());
+ function getCoords$1(rank, name) {
+ if (rank === 1) {
+ return "" + name;
+ }
+ else if (rank === 2) {
+ return name + ".x, " + name + ".y";
+ }
+ else if (rank === 3) {
+ return name + ".x, " + name + ".y, " + name + ".z";
+ }
+ else if (rank === 4) {
+ return name + ".x, " + name + ".y, " + name + ".z, " + name + ".w";
+ }
+ else {
+ throw Error("Cumulative sum for rank " + rank + " is not yet supported");
+ }
+ }
+ function getFinalCoord(rank, name) {
+ if (rank === 1) {
+ return "" + name;
+ }
+ else if (rank === 2) {
+ return name + ".y";
+ }
+ else if (rank === 3) {
+ return name + ".z";
+ }
+ else if (rank === 4) {
+ return name + ".w";
+ }
+ else {
+ throw Error("Cumulative sum for rank " + rank + " is not yet supported");
+ }
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function cumsum(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var axis = attrs.axis, exclusive = attrs.exclusive, reverse = attrs.reverse;
+ var xRank = x.shape.length;
+ var permutation = tf.backend_util.getAxesPermutation([axis], xRank);
+ var permutedX = x;
+ if (permutation != null) {
+ permutedX = transpose({ inputs: { x: x }, backend: backend, attrs: { perm: permutation } });
+ }
+ var permutedAxis = tf.backend_util.getInnerMostAxes(1, xRank)[0];
+ if (permutedAxis !== xRank - 1) {
+ throw new Error("WebGL cumsum shader expects an inner-most axis=" + (x.shape.length - 1) + " " +
+ ("but got axis=" + axis));
+ }
+ var size = permutedX.shape[permutedAxis];
+ var result = identity({ inputs: { x: permutedX }, backend: backend });
+ // Use cumsum parallel algorithm, ref:
+ // https://developer.nvidia.com/gpugems/gpugems3/part-vi-gpu-computing/chapter-39-parallel-prefix-sum-scan-cuda
+ for (var i = 0; i <= Math.ceil(Math.log2(size)) - 1; i++) {
+ var program = new CumSumProgram(permutedX.shape, false, reverse);
+ var customSetup = program.getCustomSetupFunc(i);
+ var prevResult = result;
+ result =
+ backend.runWebGLProgram(program, [result], result.dtype, customSetup);
+ backend.disposeIntermediateTensorInfo(prevResult);
+ }
+ // For exclusive cumsum, shift the end result in the direction of sum
+ // and add 0 to the front index.
+ if (exclusive) {
+ var program = new CumSumProgram(permutedX.shape, exclusive, reverse);
+ var prevResult = result;
+ result = backend.runWebGLProgram(program, [result], result.dtype);
+ backend.disposeIntermediateTensorInfo(prevResult);
+ }
+ if (permutation != null) {
+ var reversePermutation = tf.backend_util.getUndoAxesPermutation(permutation);
+ var reverseTransposedResult = transpose({ inputs: { x: result }, backend: backend, attrs: { perm: reversePermutation } });
+ backend.disposeIntermediateTensorInfo(result);
+ backend.disposeIntermediateTensorInfo(permutedX);
+ return reverseTransposedResult;
+ }
+ return result;
+ }
+ var cumsumConfig = {
+ kernelName: tf.Cumsum,
+ backendName: 'webgl',
+ kernelFunc: cumsum
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function denseBincount(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, weights = inputs.weights;
+ var size = attrs.size, binaryOutput = attrs.binaryOutput;
+ if (x.shape.length === 1) {
+ var xVals = backend.readSync(x.dataId);
+ var weightsVals = backend.readSync(weights.dataId);
+ var outVals = bincountImplCPU(xVals, weightsVals, weights.dtype, weights.shape, size);
+ return backend.makeTensorInfo([size], weights.dtype, outVals);
+ }
+ else if (x.shape.length === 2) {
+ var xBuf = backend.bufferSync(x);
+ var weightsBuf = backend.bufferSync(weights);
+ var outBuf = bincountReduceImplCPU(xBuf, weightsBuf, size, binaryOutput);
+ return backend.makeTensorInfo(outBuf.shape, weights.dtype, outBuf.values);
+ }
+ throw new Error("Error in denseBincount: input must be at most rank 2, but got rank" +
+ (x.shape.length + "."));
+ }
+ var denseBincountConfig = {
+ kernelName: tf.DenseBincount,
+ backendName: 'webgl',
+ kernelFunc: denseBincount
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var DepthToSpaceProgram = /** @class */ (function () {
+ function DepthToSpaceProgram(outputShape, blockSize, dataFormat) {
+ this.variableNames = ['x'];
+ this.outputShape = [];
+ this.outputShape = outputShape;
+ this.blockSize = blockSize;
+ this.dataFormat = dataFormat;
+ 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 / " + blockSize + ";\n int offset_h = imod(h, " + blockSize + ");\n int in_w = w / " + blockSize + ";\n int offset_w = imod(w, " + blockSize + ");\n int offset_d = (offset_h * " + blockSize + " + offset_w) *\n " + this.getOutputDepthSize() + ";\n int in_d = d + offset_d;\n\n float result = " + this.getInputSamplingString() + ";\n setOutput(result);\n }\n ";
+ }
+ DepthToSpaceProgram.prototype.getHeightCoordString = function () {
+ if (this.dataFormat === 'NHWC') {
+ return "coords[1]";
+ }
+ else {
+ return "coords[2]";
+ }
+ };
+ DepthToSpaceProgram.prototype.getWidthCoordString = function () {
+ if (this.dataFormat === 'NHWC') {
+ return "coords[2]";
+ }
+ else {
+ return "coords[3]";
+ }
+ };
+ DepthToSpaceProgram.prototype.getDepthCoordString = function () {
+ if (this.dataFormat === 'NHWC') {
+ return "coords[3]";
+ }
+ else {
+ return "coords[1]";
+ }
+ };
+ DepthToSpaceProgram.prototype.getOutputDepthSize = function () {
+ if (this.dataFormat === 'NHWC') {
+ return this.outputShape[3];
+ }
+ else {
+ return this.outputShape[1];
+ }
+ };
+ DepthToSpaceProgram.prototype.getInputSamplingString = function () {
+ if (this.dataFormat === 'NHWC') {
+ return "getX(b, in_h, in_w, in_d)";
+ }
+ else {
+ return "getX(b, in_d, in_h, in_w)";
+ }
+ };
+ return DepthToSpaceProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function depthToSpace(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var blockSize = attrs.blockSize, dataFormat = attrs.dataFormat;
+ tf.util.assert(blockSize > 1, function () { return "blockSize should be > 1 for depthToSpace, but was: " + blockSize; });
+ var batchSize = x.shape[0];
+ var inputHeight = (dataFormat === 'NHWC') ? x.shape[1] : x.shape[2];
+ var inputWidth = (dataFormat === 'NHWC') ? x.shape[2] : x.shape[3];
+ var inputDepth = (dataFormat === 'NHWC') ? x.shape[3] : x.shape[1];
+ var outputHeight = inputHeight * blockSize;
+ var outputWidth = inputWidth * blockSize;
+ var outputDepth = inputDepth / (blockSize * blockSize);
+ var outputShape = (dataFormat === 'NHWC') ?
+ [batchSize, outputHeight, outputWidth, outputDepth] :
+ [batchSize, outputDepth, outputHeight, outputWidth];
+ var program = new DepthToSpaceProgram(outputShape, blockSize, dataFormat);
+ return backend.runWebGLProgram(program, [x], x.dtype);
+ }
+ var depthToSpaceConfig = {
+ kernelName: tf.DepthToSpace,
+ backendName: 'webgl',
+ kernelFunc: depthToSpace
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var DepthwiseConv2DProgram = /** @class */ (function () {
+ function DepthwiseConv2DProgram(convInfo, addBias, activation, hasPreluActivation, hasLeakyReluAlpha) {
+ if (addBias === void 0) { addBias = false; }
+ if (activation === void 0) { activation = null; }
+ if (hasPreluActivation === void 0) { hasPreluActivation = false; }
+ if (hasLeakyReluAlpha === void 0) { hasLeakyReluAlpha = false; }
+ this.variableNames = ['x', 'W'];
+ this.outputShape = convInfo.outShape;
+ var xNumRows = convInfo.inHeight;
+ var xNumCols = convInfo.inWidth;
+ var padTop = convInfo.padInfo.top;
+ var padLeft = convInfo.padInfo.left;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationHeight = convInfo.dilationHeight;
+ var dilationWidth = convInfo.dilationWidth;
+ var filterHeight = convInfo.filterHeight;
+ var filterWidth = convInfo.filterWidth;
+ var channelMul = convInfo.outChannels / convInfo.inChannels;
+ var activationSnippet = '', applyActivationSnippet = '';
+ if (activation) {
+ if (hasPreluActivation) {
+ activationSnippet = "float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n " + activation + "\n }";
+ }
+ else if (hasLeakyReluAlpha) {
+ activationSnippet = "float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n " + activation + "\n }";
+ }
+ else {
+ activationSnippet = "\n float activation(float x) {\n " + activation + "\n }\n ";
+ }
+ applyActivationSnippet = "result = activation(result);";
+ }
+ var addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';
+ if (addBias) {
+ this.variableNames.push('bias');
+ }
+ if (hasPreluActivation) {
+ this.variableNames.push('preluActivationWeights');
+ }
+ if (hasLeakyReluAlpha) {
+ this.variableNames.push('leakyreluAlpha');
+ }
+ this.userCode = "\n " + activationSnippet + "\n\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\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 / " + channelMul + ";\n int q = d2 - d1 * " + channelMul + ";\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 < " + filterHeight + "; wR++) {\n int xR = xRCorner + wR * " + dilationHeight + ";\n\n if (xR < 0 || xR >= " + xNumRows + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n int xC = xCCorner + wC * " + dilationWidth + ";\n\n if (xC < 0 || xC >= " + xNumCols + ") {\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 " + addBiasSnippet + "\n " + applyActivationSnippet + "\n setOutput(result);\n }\n ";
+ }
+ return DepthwiseConv2DProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var DepthwiseConvPacked2DProgram = /** @class */ (function () {
+ function DepthwiseConvPacked2DProgram(convInfo, addBias, activation, hasPreluActivation, hasLeakyReluAlpha) {
+ if (addBias === void 0) { addBias = false; }
+ if (activation === void 0) { activation = null; }
+ if (hasPreluActivation === void 0) { hasPreluActivation = false; }
+ if (hasLeakyReluAlpha === void 0) { hasLeakyReluAlpha = false; }
+ this.variableNames = ['x', 'W'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = convInfo.outShape;
+ var channelMul = convInfo.outChannels / convInfo.inChannels;
+ var xNumRows = convInfo.inHeight;
+ var xNumCols = convInfo.inWidth;
+ var padTop = convInfo.padInfo.top;
+ var padLeft = convInfo.padInfo.left;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationHeight = convInfo.dilationHeight;
+ var dilationWidth = convInfo.dilationWidth;
+ var filterHeight = convInfo.filterHeight;
+ var filterWidth = convInfo.filterWidth;
+ var texelsAcross = filterWidth;
+ var mainLoop = "\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";
+ for (var c = 0; c < filterWidth; c++) {
+ mainLoop += "\n vec4 xTexelC" + c * 2 + ";\n int xTexelC" + c * 2 + "Ready;\n vec4 xC" + c + ";";
+ }
+ /**
+ * This vectorized implementation works by gathering the values needed for
+ * each output channel's dot product into vec4's and then multiplying them
+ * all together (this happens in the final double for-loop below). Most of
+ * the main loop consists of constructing these vec4's with the minimum
+ * number of texture2D calls, which means making use of all four returned
+ * values from a texture2D call at once.
+ */
+ for (var r = 0; r < filterHeight; r++) {
+ for (var c = 0; c < filterWidth; c++) {
+ mainLoop += "\n xTexelC" + c * 2 + " = vec4(0.0);\n xTexelC" + c * 2 + "Ready = 0;\n xC" + c + " = vec4(0.0);";
+ }
+ mainLoop += "\n xR = xRCorner + " + r * dilationHeight + ";\n if (xR >=0 && xR < " + xNumRows + ") {\n ";
+ for (var texelC = 0; texelC < (texelsAcross + 1) / 2; texelC++) {
+ var colIndex = texelC * 2;
+ var c = colIndex * dilationWidth;
+ mainLoop += "\n xC = xCCorner + " + c + ";\n ";
+ if (strideWidth === 1) {
+ if (colIndex < filterWidth) {
+ // If padding is odd, the outer texels have to be composed.
+ if (padLeft % 2 === 1) {
+ // TODO: Ensure vec4 previous does not result in redundant sample,
+ // and avoid setting xTexelRC's that exceed the boundary in the
+ // first place rather than resetting them to vec4(0)).
+ // To compute xCOffset:
+ // - If padding is odd, we must add 1 to ensure we ask for an
+ // even-numbered row.
+ // - We subtract 2 to access the previous texel.
+ mainLoop += "\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < " + xNumCols + " && xTexelC" + c + "Ready == 0) {\n xTexelC" + c + " = 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 >= " + xNumCols + ") {\n xTexelC" + c + ".zw = vec2(0.0);\n }\n xTexelC" + c + "Ready = 1;\n }\n ";
+ // This texel has been read in previous iteration if the dilation
+ // is 1.
+ if (dilationWidth === 1 && c > 0) {
+ mainLoop += "\n xC" + colIndex + " = vec4(xTexelC" + (c - 2) + ".zw, xTexelC" + c + ".xy);\n ";
+ }
+ else {
+ mainLoop += "\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < " + xNumCols + ") {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= " + xNumCols + ") {\n previous.zw = vec2(0.0);\n }\n\n xC" + colIndex + " = vec4(previous.zw, xTexelC" + c + ".xy);\n } else {\n xC" + colIndex + " = vec4(0.0, 0.0, xTexelC" + c + ".xy);\n }\n ";
+ }
+ }
+ else {
+ // Padding is even, so xRC corresponds to a single texel.
+ mainLoop += "\n if (xC >= 0 && xC < " + xNumCols + " && xTexelC" + c + "Ready == 0) {\n xTexelC" + c + " = getX(batch, xR, xC, d1);\n if (xC + 1 >= " + xNumCols + ") {\n xTexelC" + c + ".zw = vec2(0.0);\n }\n xTexelC" + c + "Ready = 1;\n }\n\n xC" + colIndex + " = xTexelC" + c + ";\n ";
+ }
+ if (c + 1 < filterWidth) {
+ // If dilation is even, the second entry should match the first
+ // (either both are composed or both are single samples). But if
+ // dilation is odd, then the second entry should be the opposite
+ // of the first (if the first is composed, the second is a single
+ // sample, and vice versa.)
+ var nextTexelOffset = padLeft % 2 === 0 ?
+ tf.util.nearestLargerEven(dilationWidth) :
+ dilationWidth;
+ if ((dilationWidth % 2 === 0 && padLeft % 2 === 1) ||
+ (dilationWidth % 2 !== 0 && padLeft % 2 !== 1)) {
+ mainLoop += "\n xCOffset = xC + " + padLeft % 2 + " + " + nextTexelOffset + ";\n\n if (xCOffset >= 0 && xCOffset < " + xNumCols + " && xTexelC" + (c + 2) + "Ready == 0) {\n xTexelC" + (c + 2) + " = 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 >= " + xNumCols + ") {\n xTexelC" + (c + 2) + ".zw = vec2(0.0);\n }\n xTexelC" + (c + 2) + "Ready = 1;\n }\n ";
+ // If dilation > 1 then the xRC's will not be able to share any
+ // values, so each xRC will require two unique calls to getX.
+ if (dilationWidth > 1) {
+ mainLoop += "\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < " + xNumCols + " && xTexelC" + c + "Ready == 0) {\n xTexelC" + c + " = getX(batch, xR, xCOffset, d1);\n xTexelC" + c + "Ready = 1;\n }\n ";
+ }
+ mainLoop += "\n xC" + (colIndex + 1) + " = vec4(xTexelC" + c + ".zw, xTexelC" + (c + 2) + ".xy);\n ";
+ }
+ else {
+ // If dilation is 1 and padding is odd, we have already read the
+ // texel when constructing the previous x value. Here we can
+ // simply skip the texture read.
+ if (nextTexelOffset === 1) {
+ mainLoop += "\n xC" + (colIndex + 1) + " = xTexelC" + c + ";\n ";
+ }
+ else {
+ mainLoop += "\n xCOffset = xC + " + nextTexelOffset + ";\n\n if (xCOffset >= 0 && xCOffset < " + xNumCols + " && xTexelC" + (c + 2) + "Ready == 0) {\n xTexelC" + (c + 2) + " = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= " + xNumCols + ") {\n xTexelC" + (c + 2) + ".zw = vec2(0.0);\n }\n xTexelC" + (c + 2) + "Ready = 1;\n }\n\n xC" + (colIndex + 1) + " = xTexelC" + (c + 2) + ";\n ";
+ }
+ }
+ }
+ }
+ }
+ else { // stride === 2
+ if (c < filterWidth) {
+ // Depending on whether padLeft is even or odd, we want either the
+ // xy or zw channels from X texels for xC${colIndex}. If padLeft is
+ // even, xC${colIndex +1} is simply the zw channels of texels we've
+ // already sampled. But if padLeft is odd, xC{$c + 1}.zw will
+ // need to come from the xy channels of a new texel, hence the `
+ // vec4
+ // final` initialized below.
+ if (padLeft % 2 === 1) {
+ mainLoop += "\n xCOffset = xC + 1 - " + strideWidth + ";\n if(xCOffset >= 0 && xCOffset < " + xNumCols + " && xTexelC" + c + "Ready == 0) {\n xTexelC" + c + " = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= " + xNumCols + ") {\n xTexelC" + c + ".zw = vec2(0.0);\n }\n xTexelC" + c + "Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < " + xNumCols + " && xTexelC" + (c + 2) + "Ready == 0) {\n xTexelC" + (c + 2) + " = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= " + xNumCols + ") {\n xTexelC" + (c + 2) + ".zw = vec2(0.0);\n }\n xTexelC" + (c + 2) + "Ready = 1;\n }\n\n xC" + colIndex + " = vec4(xTexelC" + c + ".zw, xTexelC" + (c + 2) + ".zw);\n ";
+ if (c + 1 < filterWidth) {
+ mainLoop += "\n final = vec4(0.0);\n xCOffset = xC + 1 + " + strideWidth + ";\n if(xCOffset >= 0 && xCOffset < " + xNumCols + ") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC" + (colIndex + 1) + " = vec4(xTexelC" + (c + 2) + ".xy, final.xy);\n ";
+ }
+ }
+ else {
+ mainLoop += "\n if(xC >= 0 && xC < " + xNumCols + " && xTexelC" + c + "Ready == 0) {\n xTexelC" + c + " = getX(batch, xR, xC, d1);\n if (xC + 1 >= " + xNumCols + ") {\n xTexelC" + c + ".zw = vec2(0.0);\n }\n xTexelC" + c + "Ready = 1;\n }\n\n xCOffset = xC + " + strideWidth + ";\n if(xCOffset >= 0 && xCOffset < " + xNumCols + " && xTexelC" + (c + 2) + "Ready == 0) {\n xTexelC" + (c + 2) + " = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= " + xNumCols + ") {\n xTexelC" + (c + 2) + ".zw = vec2(0.);\n }\n xTexelC" + (c + 2) + "Ready = 1;\n }\n\n xC" + colIndex + " = vec4(\n xTexelC" + c + ".xy, xTexelC" + (c + 2) + ".xy);\n ";
+ if (c + 1 < filterWidth) {
+ mainLoop += "\n xC" + (colIndex + 1) + " = vec4(xTexelC" + c + ".zw, xTexelC" + (c + 2) + ".zw);\n ";
+ }
+ }
+ }
+ }
+ // localize the dotProd accumulation within the loop, the theory is for
+ // GPU with limited cache, accumulate sum across large amount of
+ // veriables will cause lots of cache misses. (i.e. 5x5 filter will have
+ // 50 variables)
+ if (colIndex < filterWidth) {
+ mainLoop += "\n wTexel = getW(" + r + ", " + c + ", d1, q);\n dotProd += xC" + colIndex + " * vec4(wTexel.xz, wTexel.xz);\n ";
+ if (c + 1 < filterWidth) {
+ mainLoop += "\n wTexel = getW(" + r + ", " + (c + 1) + ", d1, q);\n dotProd += xC" + (colIndex + 1) + " * vec4(wTexel.xz, wTexel.xz);\n ";
+ }
+ }
+ }
+ mainLoop += "\n }\n ";
+ }
+ var activationSnippet = '', applyActivationSnippet = '';
+ if (activation) {
+ if (hasPreluActivation) {
+ activationSnippet = "vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n " + activation + "\n }";
+ }
+ else if (hasLeakyReluAlpha) {
+ activationSnippet = "vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n " + activation + "\n }";
+ }
+ else {
+ activationSnippet = "vec4 activation(vec4 x) {\n " + activation + "\n }";
+ }
+ applyActivationSnippet = "result = activation(result);";
+ }
+ var addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';
+ if (addBias) {
+ this.variableNames.push('bias');
+ }
+ if (hasPreluActivation) {
+ this.variableNames.push('preluActivationWeights');
+ }
+ if (hasLeakyReluAlpha) {
+ this.variableNames.push('leakyreluAlpha');
+ }
+ this.userCode = "\n " + activationSnippet + "\n\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n\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 / " + channelMul + ";\n int q = d2 - d1 * " + channelMul + ";\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n " + mainLoop + "\n\n vec4 result = dotProd - vec4(0.000000000000001);\n " + addBiasSnippet + "\n " + applyActivationSnippet + "\n setOutput(result);\n }\n ";
+ }
+ return DepthwiseConvPacked2DProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function depthwiseConv2dNative(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, filter = inputs.filter;
+ var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode;
+ var $dilations = dilations;
+ if ($dilations == null) {
+ $dilations = [1, 1];
+ }
+ tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, $dilations), function () { return 'Error in depthwiseConv2d: Either strides or dilations must be ' +
+ ("1. Got strides " + strides + " and dilations '" + $dilations + "'"); });
+ var convInfo = tf.backend_util.computeConv2DInfo(x.shape, filter.shape, strides, $dilations, pad, dimRoundingMode, true /* depthwise */);
+ var program;
+ if (tf.env().getBool('WEBGL_PACK_DEPTHWISECONV') && convInfo.strideWidth <= 2 &&
+ convInfo.outChannels / convInfo.inChannels === 1) {
+ program = new DepthwiseConvPacked2DProgram(convInfo);
+ }
+ else {
+ program = new DepthwiseConv2DProgram(convInfo);
+ }
+ return backend.runWebGLProgram(program, [x, filter], 'float32');
+ }
+ var depthwiseConv2dNativeConfig = {
+ kernelName: tf.DepthwiseConv2dNative,
+ backendName: 'webgl',
+ kernelFunc: depthwiseConv2dNative,
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var DepthwiseConv2DDerFilterProgram = /** @class */ (function () {
+ function DepthwiseConv2DDerFilterProgram(convInfo) {
+ this.variableNames = ['x', 'dy'];
+ this.outputShape = convInfo.filterShape;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var padTop = convInfo.padInfo.top;
+ var padLeft = convInfo.padInfo.left;
+ var channelMul = convInfo.outChannels / convInfo.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 * " + channelMul + " + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < " + convInfo.batchSize + "; b++) {\n for (int yR = 0; yR < " + convInfo.outHeight + "; yR++) {\n int xR = wR + yR * " + strideHeight + " - " + padTop + ";\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int yC = 0; yC < " + convInfo.outWidth + "; yC++) {\n int xC = wC + yC * " + strideWidth + " - " + padLeft + ";\n\n if (xC < 0 || xC >= " + convInfo.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 ";
+ }
+ return DepthwiseConv2DDerFilterProgram;
+ }());
+ var DepthwiseConv2DDerInputProgram = /** @class */ (function () {
+ function DepthwiseConv2DDerInputProgram(convInfo) {
+ this.variableNames = ['dy', 'W'];
+ this.outputShape = convInfo.inShape;
+ var filterHeight = convInfo.filterHeight;
+ var filterWidth = convInfo.filterWidth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var padTop = filterHeight - 1 - convInfo.padInfo.top;
+ var padLeft = filterWidth - 1 - convInfo.padInfo.left;
+ var channelMul = convInfo.outChannels / convInfo.inChannels;
+ this.userCode = "\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\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 < " + filterHeight + "; wR++) {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = " + filterHeight + " - 1 - wR;\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.outWidth + ".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = " + filterWidth + " - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < " + channelMul + "; dm++) {\n int d2 = d1 * " + channelMul + " + 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 ";
+ }
+ return DepthwiseConv2DDerInputProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function depthwiseConv2dNativeBackpropFilter(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, dy = inputs.dy;
+ var strides = attrs.strides, dilations = attrs.dilations, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, filterShape = attrs.filterShape;
+ var convInfo = tf.backend_util.computeConv2DInfo(x.shape, filterShape, strides, dilations, pad, dimRoundingMode, true /* depthwise */);
+ var program = new DepthwiseConv2DDerFilterProgram(convInfo);
+ return backend.runWebGLProgram(program, [x, dy], 'float32');
+ }
+ var depthwiseConv2dNativeBackpropFilterConfig = {
+ kernelName: tf.DepthwiseConv2dNativeBackpropFilter,
+ backendName: 'webgl',
+ kernelFunc: depthwiseConv2dNativeBackpropFilter
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function depthwiseConv2dNativeBackpropInput(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var dy = inputs.dy, filter = inputs.filter;
+ var strides = attrs.strides, dilations = attrs.dilations, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode, inputShape = attrs.inputShape;
+ var convInfo = tf.backend_util.computeConv2DInfo(inputShape, filter.shape, strides, dilations, pad, dimRoundingMode, true /* depthwise */);
+ var program = new DepthwiseConv2DDerInputProgram(convInfo);
+ return backend.runWebGLProgram(program, [dy, filter], 'float32');
+ }
+ var depthwiseConv2dNativeBackpropInputConfig = {
+ kernelName: tf.DepthwiseConv2dNativeBackpropInput,
+ backendName: 'webgl',
+ kernelFunc: depthwiseConv2dNativeBackpropInput
+ };
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var DiagProgram = /** @class */ (function () {
+ function DiagProgram(size) {
+ this.variableNames = ['X'];
+ this.outputShape = [size, size];
+ 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 ";
+ }
+ return DiagProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function diag(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var x = inputs.x;
+ var outShape = x.shape.concat(x.shape);
+ var xSize = tf.util.sizeFromShape(x.shape);
+ var flat = reshape({ inputs: { x: x }, backend: backend, attrs: { shape: [xSize] } });
+ var program = new DiagProgram(xSize);
+ var res = backend.runWebGLProgram(program, [flat], flat.dtype);
+ var out = reshape({ inputs: { x: res }, backend: backend, attrs: { shape: outShape } });
+ backend.disposeIntermediateTensorInfo(flat);
+ backend.disposeIntermediateTensorInfo(res);
+ return out;
+ }
+ var diagConfig = {
+ kernelName: tf.Diag,
+ backendName: 'webgl',
+ kernelFunc: diag
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var Dilation2DProgram = /** @class */ (function () {
+ function Dilation2DProgram(convInfo) {
+ this.variableNames = ['x', 'W'];
+ this.outputShape = convInfo.outShape;
+ var inHeight = convInfo.inHeight, inWidth = convInfo.inWidth, padInfo = convInfo.padInfo, strideHeight = convInfo.strideHeight, strideWidth = convInfo.strideWidth, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth, dilationHeight = convInfo.dilationHeight, dilationWidth = convInfo.dilationWidth;
+ var padTop = padInfo.top, padLeft = padInfo.left;
+ this.userCode = "\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < " + filterHeight + "; h++) {\n int hIn = hBeg + h * " + dilationHeight + ";\n\n if (hIn >= 0 && hIn < " + inHeight + ") {\n for (int w = 0; w < " + filterWidth + "; w++) {\n int wIn = wBeg + w * " + dilationWidth + ";\n\n if (wIn >= 0 && wIn < " + inWidth + ") {\n float xVal = getX(batch, hIn, wIn, d1);\n float wVal = getW(h, w, d1);\n\n float val = xVal + wVal;\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n\n float result = curVal;\n setOutput(result);\n }\n ";
+ }
+ return Dilation2DProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function dilation2D(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, filter = inputs.filter;
+ var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations;
+ var convInfo = tf.backend_util.computeDilation2DInfo(x.shape, filter.shape, strides, pad, 'NHWC' /* dataFormat */, dilations);
+ var out;
+ var program = new Dilation2DProgram(convInfo);
+ out = backend.runWebGLProgram(program, [x, filter], 'float32');
+ var outReshaped = reshape({ inputs: { x: out }, backend: backend, attrs: { shape: convInfo.outShape } });
+ backend.disposeIntermediateTensorInfo(out);
+ return outReshaped;
+ }
+ var dilation2DConfig = {
+ kernelName: tf.Dilation2D,
+ backendName: 'webgl',
+ kernelFunc: dilation2D,
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function einsum(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var equation = attrs.equation;
+ var tensors = inputs;
+ var _a = tf.backend_util.decodeEinsumEquation(equation, tensors.length), allDims = _a.allDims, summedDims = _a.summedDims, idDims = _a.idDims;
+ tf.backend_util.checkEinsumDimSizes(allDims.length, idDims, tensors);
+ var _b = tf.backend_util.getEinsumComputePath(summedDims, idDims), path = _b.path, steps = _b.steps;
+ var nSteps = steps.length;
+ var out = null;
+ var numDimsRemaining = allDims.length;
+ var tensorsToDispose = [];
+ for (var i = 0; i < nSteps; ++i) {
+ for (var _i = 0, _c = steps[i]; _i < _c.length; _i++) {
+ var idTerm = _c[_i];
+ var _d = tf.backend_util.getEinsumPermutation(numDimsRemaining, idDims[idTerm]), perm = _d.permutationIndices, dimsToExpand = _d.expandDims;
+ var x = void 0;
+ if (tf.backend_util.isIdentityPermutation(perm)) {
+ x = tensors[idTerm];
+ }
+ else {
+ x = transpose({ inputs: { x: tensors[idTerm] }, backend: backend, attrs: { perm: perm } });
+ tensorsToDispose.push(x);
+ }
+ var targetShape = x.shape.slice();
+ for (var k = 0; k < dimsToExpand.length; ++k) {
+ targetShape.splice(dimsToExpand[k], 0, 1);
+ }
+ if (!tf.util.arraysEqual(x.shape, targetShape)) {
+ x = reshape({ inputs: { x: x }, backend: backend, attrs: { shape: targetShape } });
+ tensorsToDispose.push(x);
+ }
+ if (out === null) {
+ out = x;
+ }
+ else {
+ // tslint:disable-next-line: no-unnecessary-type-assertion
+ out = multiply({ inputs: { a: x, b: out }, backend: backend });
+ tensorsToDispose.push(out);
+ }
+ }
+ if (i < nSteps - 1) {
+ if (path[i] >= 0) {
+ out = sum({
+ inputs: { x: out },
+ backend: backend,
+ attrs: {
+ axis: path[i] - (allDims.length - numDimsRemaining),
+ keepDims: false
+ }
+ });
+ tensorsToDispose.push(out);
+ }
+ numDimsRemaining--;
+ }
+ }
+ // Clean up intermediate tensors.
+ for (var _e = 0, tensorsToDispose_1 = tensorsToDispose; _e < tensorsToDispose_1.length; _e++) {
+ var tensorInfo = tensorsToDispose_1[_e];
+ if (tensorInfo === out) {
+ continue;
+ }
+ backend.disposeIntermediateTensorInfo(tensorInfo);
+ }
+ return out;
+ }
+ var einsumConfig = {
+ kernelName: tf.Einsum,
+ backendName: 'webgl',
+ kernelFunc: einsum
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ELU$2 = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
+ var ELU_PACKED = "\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n";
+ var elu = unaryKernelFunc({ opSnippet: ELU$2, packedOpSnippet: ELU_PACKED });
+ var eluConfig = {
+ kernelName: tf.Elu,
+ backendName: 'webgl',
+ kernelFunc: elu
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ELU_DER = "return (b >= 1.0) ? a : a * (b + 1.0);";
+ var ELU_DER_PACKED = "\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n";
+ var eluGrad = function (args) {
+ var inputs = args.inputs, backend = args.backend;
+ var dy = inputs.dy, y = inputs.y;
+ var program = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ?
+ new BinaryOpPackedProgram(ELU_DER_PACKED, dy.shape, y.shape) :
+ new BinaryOpProgram(ELU_DER, dy.shape, y.shape);
+ return backend.runWebGLProgram(program, [dy, y], dy.dtype);
+ };
+ var eluGradConfig = {
+ kernelName: tf.EluGrad,
+ backendName: 'webgl',
+ kernelFunc: eluGrad
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var PACKED_EQUAL = "\n return vec4(equal(a, b));\n";
+ var EQUAL = "return float(a == b);";
+ var equal = binaryKernelFunc({
+ opSnippet: EQUAL,
+ packedOpSnippet: PACKED_EQUAL,
+ dtype: 'bool',
+ cpuKernelImpl: equalImplCPU,
+ });
+ var equalConfig = {
+ kernelName: tf.Equal,
+ backendName: 'webgl',
+ kernelFunc: equal
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ERF = "\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 = " + tf.backend_util.ERF_P + ";\n float a1 = " + tf.backend_util.ERF_A1 + ";\n float a2 = " + tf.backend_util.ERF_A2 + ";\n float a3 = " + tf.backend_util.ERF_A3 + ";\n float a4 = " + tf.backend_util.ERF_A4 + ";\n float a5 = " + tf.backend_util.ERF_A5 + ";\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";
+ var erf = unaryKernelFunc({ opSnippet: ERF });
+ var erfConfig = {
+ kernelName: tf.Erf,
+ backendName: 'webgl',
+ kernelFunc: erf,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var EXP = "return exp(x);";
+ var exp = unaryKernelFunc({ opSnippet: EXP, packedOpSnippet: EXP, cpuKernelImpl: expImplCPU });
+ var expConfig = {
+ kernelName: tf.Exp,
+ backendName: 'webgl',
+ kernelFunc: exp
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function expandDims(args) {
+ var inputs = args.inputs, attrs = args.attrs, backend = args.backend;
+ var dim = attrs.dim;
+ var input = inputs.input;
+ var inputRank = input.shape.length;
+ var newShape = input.shape.slice();
+ var $dim = dim;
+ if (dim < 0) {
+ // Negative value is counted from the tail of rank.
+ tf.util.assert(-(inputRank + 1) <= dim, function () { return "Axis must be in the interval [" + -(inputRank + 1) + ", " + inputRank + "]"; });
+ $dim = inputRank + dim + 1;
+ }
+ newShape.splice($dim, 0, 1);
+ return reshape({ inputs: { x: input }, backend: backend, attrs: { shape: newShape } });
+ }
+ var expandDimsConfig = {
+ kernelName: tf.ExpandDims,
+ backendName: 'webgl',
+ kernelFunc: expandDims,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var EXPM1 = "return exp(x) - 1.0;";
+ var expm1 = unaryKernelFunc({ opSnippet: EXPM1, packedOpSnippet: EXPM1, cpuKernelImpl: expm1ImplCPU });
+ var expm1Config = {
+ kernelName: tf.Expm1,
+ backendName: 'webgl',
+ kernelFunc: expm1
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var FFTProgram = /** @class */ (function () {
+ function FFTProgram(component, inputShape, inverse) {
+ this.variableNames = ['real', 'imag'];
+ var innerDim = inputShape[1];
+ this.outputShape = inputShape;
+ var exponentMultiplierSnippet = inverse ? "2.0 * " + Math.PI : "-2.0 * " + Math.PI;
+ var resultDenominator = inverse ? innerDim + ".0" : '1.0';
+ var opString;
+ if (component === 'real') {
+ opString = 'return real * expR - imag * expI;';
+ }
+ else if (component === 'imag') {
+ opString = 'return real * expI + imag * expR;';
+ }
+ else {
+ throw new Error("FFT component must be either \"real\" or \"imag\", got " + component + ".");
+ }
+ this.userCode = "\n const float exponentMultiplier = " + exponentMultiplierSnippet + ";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n " + opString + "\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(" + innerDim + ");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < " + innerDim + "; 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) / " + resultDenominator + ";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n ";
+ }
+ return FFTProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function fftImpl(x, inverse, backend) {
+ var xData = backend.texData.get(x.dataId);
+ var inputSize = tf.util.sizeFromShape(x.shape);
+ // Collapse all outer dimensions to a single batch dimension.
+ var innerDimensionSize = x.shape[x.shape.length - 1];
+ var batch = inputSize / innerDimensionSize;
+ var input2D = reshape({ inputs: { x: x }, backend: backend, attrs: { shape: [batch, innerDimensionSize] } });
+ var xShape = input2D.shape;
+ var realProgram = new FFTProgram('real', xShape, inverse);
+ var imagProgram = new FFTProgram('imag', xShape, inverse);
+ var inputs = [
+ {
+ dataId: xData.complexTensorInfos.real.dataId,
+ dtype: xData.complexTensorInfos.real.dtype,
+ shape: xShape
+ },
+ {
+ dataId: xData.complexTensorInfos.imag.dataId,
+ dtype: xData.complexTensorInfos.imag.dtype,
+ shape: xShape
+ }
+ ];
+ var realPart = backend.runWebGLProgram(realProgram, inputs, 'float32');
+ var imagPart = backend.runWebGLProgram(imagProgram, inputs, 'float32');
+ var complexOutput = complex({ inputs: { real: realPart, imag: imagPart }, backend: backend });
+ backend.disposeIntermediateTensorInfo(realPart);
+ backend.disposeIntermediateTensorInfo(imagPart);
+ var complexOutputReshaped = reshape({ inputs: { x: complexOutput }, backend: backend, attrs: { shape: x.shape } });
+ backend.disposeIntermediateTensorInfo(input2D);
+ backend.disposeIntermediateTensorInfo(complexOutput);
+ return complexOutputReshaped;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function fft(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var input = inputs.input;
+ return fftImpl(input, false /* inverse */, backend);
+ }
+ var fftConfig = {
+ kernelName: tf.FFT,
+ backendName: 'webgl',
+ kernelFunc: fft
+ };
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var FillProgram = /** @class */ (function () {
+ function FillProgram(shape, value) {
+ this.outputShape = [];
+ this.variableNames = ['x'];
+ this.outputShape = shape;
+ this.userCode = "\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n ";
+ }
+ FillProgram.prototype.getCustomSetupFunc = function (value) {
+ var _this = this;
+ return function (gpgpu, webGLProgram) {
+ if (_this.valueLoc == null) {
+ _this.valueLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'value');
+ }
+ gpgpu.gl.uniform1f(_this.valueLoc, value);
+ };
+ };
+ return FillProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function fill(args) {
+ var backend = args.backend, attrs = args.attrs;
+ var shape = attrs.shape, value = attrs.value;
+ var dtype = attrs.dtype;
+ dtype = dtype || tf.util.inferDtype(value);
+ if (dtype === 'string') {
+ // String type should be handled in CPU memory.
+ var values = tf.util.getArrayFromDType(dtype, tf.util.sizeFromShape(shape));
+ values.fill(value);
+ return backend.makeTensorInfo(shape, dtype, values);
+ }
+ else {
+ var program = new FillProgram(shape, value);
+ var customSetup = program.getCustomSetupFunc(value);
+ return backend.runWebGLProgram(program, [], dtype, customSetup);
+ }
+ }
+ var fillConfig = {
+ kernelName: tf.Fill,
+ backendName: 'webgl',
+ kernelFunc: fill
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var FlipLeftRightProgram = /** @class */ (function () {
+ function FlipLeftRightProgram(imageShape) {
+ this.variableNames = ['Image'];
+ this.outputShape = [];
+ var imageWidth = imageShape[2];
+ this.outputShape = imageShape;
+ this.userCode = "\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = " + imageWidth + " - x;\n float outputValue;\n if(coordX >= 0 && coordX < " + imageWidth + ") {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\n }\n ";
+ }
+ return FlipLeftRightProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var flipLeftRightConfig = {
+ kernelName: tf.FlipLeftRight,
+ backendName: 'webgl',
+ kernelFunc: function (_a) {
+ var inputs = _a.inputs, backend = _a.backend;
+ var image = inputs.image;
+ var webglBackend = backend;
+ var program = new FlipLeftRightProgram(image.shape);
+ var output = webglBackend.runWebGLProgram(program, [image], image.dtype);
+ return output;
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var FLOOR = "return floor(x);";
+ var floor = unaryKernelFunc({ opSnippet: FLOOR, packedOpSnippet: FLOOR, cpuKernelImpl: floorImplCPU });
+ var floorConfig = {
+ kernelName: tf.Floor,
+ backendName: 'webgl',
+ kernelFunc: floor,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // We use native integer division to deal with floating point imprecision. Since
+ // we implement floor division and glsl implements truncated division, we
+ // correct for this by subtracting 1 from result when the result is negative and
+ // there is a remainder.
+ var INT_DIV = "\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";
+ var INT_DIV_PACKED = "\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";
+ var floorDiv = binaryKernelFunc({ opSnippet: INT_DIV, packedOpSnippet: INT_DIV_PACKED, dtype: 'int32' });
+ var floorDivConfig = {
+ kernelName: tf.FloorDiv,
+ backendName: 'webgl',
+ kernelFunc: floorDiv
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var FromPixelsProgram = /** @class */ (function () {
+ function FromPixelsProgram(outputShape) {
+ this.variableNames = ['A'];
+ var glsl = getGlslDifferences();
+ var height = outputShape[0], width = outputShape[1];
+ this.outputShape = outputShape;
+ this.userCode = "\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(" + width + ".0, " + height + ".0);\n\n vec4 values = " + glsl.texture2D + "(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n ";
+ }
+ return FromPixelsProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var FromPixelsPackedProgram = /** @class */ (function () {
+ function FromPixelsPackedProgram(outputShape) {
+ this.variableNames = ['A'];
+ this.packedInputs = false;
+ this.packedOutput = true;
+ var glsl = getGlslDifferences();
+ var height = outputShape[0], width = outputShape[1];
+ this.outputShape = outputShape;
+ this.userCode = "\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + width + ".0, " + height + ".0);\n vec4 values = " + glsl.texture2D + "(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n " + glsl.output + " = result;\n }\n ";
+ }
+ return FromPixelsPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var fromPixelsConfig = {
+ kernelName: tf.FromPixels,
+ backendName: 'webgl',
+ kernelFunc: fromPixels,
+ };
+ var fromPixels2DContext;
+ function fromPixels(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var pixels = inputs.pixels;
+ var numChannels = attrs.numChannels;
+ var isVideo = typeof (HTMLVideoElement) !== 'undefined' &&
+ pixels instanceof HTMLVideoElement;
+ var isImage = typeof (HTMLImageElement) !== 'undefined' &&
+ pixels instanceof HTMLImageElement;
+ var _a = isVideo ?
+ [
+ pixels.videoWidth,
+ pixels.videoHeight
+ ] :
+ [pixels.width, pixels.height], width = _a[0], height = _a[1];
+ var texShape = [height, width];
+ var outShape = [height, width, numChannels];
+ if (isImage || isVideo) {
+ if (fromPixels2DContext == null) {
+ fromPixels2DContext = document.createElement('canvas').getContext('2d');
+ }
+ fromPixels2DContext.canvas.width = width;
+ fromPixels2DContext.canvas.height = height;
+ fromPixels2DContext.drawImage(pixels, 0, 0, width, height);
+ pixels = fromPixels2DContext.canvas;
+ }
+ var tempPixelHandle = backend.makeTensorInfo(texShape, 'int32');
+ // This is a byte texture with pixels.
+ backend.texData.get(tempPixelHandle.dataId).usage = TextureUsage.PIXELS;
+ backend.gpgpu.uploadPixelDataToTexture(backend.getTexture(tempPixelHandle.dataId), pixels);
+ var program = tf.env().getBool('WEBGL_PACK') ?
+ new FromPixelsPackedProgram(outShape) :
+ new FromPixelsProgram(outShape);
+ var res = backend.runWebGLProgram(program, [tempPixelHandle], 'int32');
+ backend.disposeData(tempPixelHandle.dataId);
+ return res;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function fusedConv2d(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, filter = inputs.filter, bias = inputs.bias, preluActivationWeights = inputs.preluActivationWeights;
+ var strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode, activation = attrs.activation, leakyreluAlpha = attrs.leakyreluAlpha;
+ var $dataFormat = tf.backend_util.convertConv2DDataFormat(dataFormat);
+ var convInfo = tf.backend_util.computeConv2DInfo(x.shape, filter.shape, strides, dilations, pad, dimRoundingMode, false /* depthwise */, $dataFormat);
+ var out;
+ var intermediates = [];
+ if (convInfo.filterHeight === 1 && convInfo.filterWidth === 1 &&
+ convInfo.dilationHeight === 1 && convInfo.dilationWidth === 1 &&
+ convInfo.strideHeight === 1 && convInfo.strideWidth === 1 &&
+ (convInfo.padInfo.type === 'SAME' || convInfo.padInfo.type === 'VALID')) {
+ out = conv2dByMatMul({
+ x: x,
+ filter: filter,
+ convInfo: convInfo,
+ backend: backend,
+ bias: bias,
+ activation: activation,
+ preluActivationWeights: preluActivationWeights,
+ leakyreluAlpha: leakyreluAlpha
+ });
+ }
+ else if (tf.env().getBool('WEBGL_CONV_IM2COL') && x.shape[0] === 1) {
+ out = conv2dWithIm2Row({
+ x: x,
+ filter: filter,
+ convInfo: convInfo,
+ backend: backend,
+ bias: bias,
+ activation: activation,
+ preluActivationWeights: preluActivationWeights,
+ leakyreluAlpha: leakyreluAlpha
+ });
+ }
+ else {
+ var hasBias = bias != null;
+ var hasPreluActivationWeights = preluActivationWeights != null;
+ var hasLeakyreluAlpha = activation === 'leakyrelu';
+ var fusedActivation = activation ? mapActivationToShaderProgram(activation, false) : null;
+ var program = new Conv2DProgram(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
+ var inputs_1 = [x, filter];
+ if (bias) {
+ inputs_1.push(bias);
+ }
+ if (preluActivationWeights) {
+ inputs_1.push(preluActivationWeights);
+ }
+ if (hasLeakyreluAlpha) {
+ var $leakyreluAlpha = backend.makeTensorInfo([], 'float32', tf.util.createScalarValue(leakyreluAlpha, 'float32'));
+ inputs_1.push($leakyreluAlpha);
+ intermediates.push($leakyreluAlpha);
+ }
+ out = backend.runWebGLProgram(program, inputs_1, 'float32');
+ }
+ var outReshaped = reshape({ inputs: { x: out }, backend: backend, attrs: { shape: convInfo.outShape } });
+ intermediates.push(out);
+ intermediates.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return outReshaped;
+ }
+ var fusedConv2DConfig = {
+ kernelName: tf.FusedConv2D,
+ backendName: 'webgl',
+ kernelFunc: fusedConv2d,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function fusedDepthwiseConv2D(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, filter = inputs.filter, bias = inputs.bias, preluActivationWeights = inputs.preluActivationWeights;
+ var strides = attrs.strides, pad = attrs.pad, dilations = attrs.dilations, dimRoundingMode = attrs.dimRoundingMode, activation = attrs.activation, leakyreluAlpha = attrs.leakyreluAlpha;
+ var intermediates = [];
+ var $dilations = dilations;
+ if ($dilations == null) {
+ $dilations = [1, 1];
+ }
+ tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, $dilations), function () { return 'Error in depthwiseConv2d: Either strides or dilations must be ' +
+ ("1. Got strides " + strides + " and dilations '" + $dilations + "'"); });
+ var convInfo = tf.backend_util.computeConv2DInfo(x.shape, filter.shape, strides, $dilations, pad, dimRoundingMode, true /* depthwise */);
+ var shouldPackDepthwiseConv = tf.env().getBool('WEBGL_PACK_DEPTHWISECONV') &&
+ convInfo.strideWidth <= 2 &&
+ convInfo.outChannels / convInfo.inChannels === 1;
+ var fusedActivation = activation ?
+ mapActivationToShaderProgram(activation, shouldPackDepthwiseConv) :
+ null;
+ var programInputs = [x, filter];
+ var hasBias = bias != null;
+ var hasPreluActivationWeights = preluActivationWeights != null;
+ var hasLeakyreluAlpha = activation === 'leakyrelu';
+ if (hasBias) {
+ programInputs.push(bias);
+ }
+ if (hasPreluActivationWeights) {
+ programInputs.push(preluActivationWeights);
+ }
+ if (hasLeakyreluAlpha) {
+ var $leakyreluAlpha = backend.makeTensorInfo([], 'float32', tf.util.createScalarValue(leakyreluAlpha, 'float32'));
+ programInputs.push($leakyreluAlpha);
+ intermediates.push($leakyreluAlpha);
+ }
+ var program;
+ if (shouldPackDepthwiseConv) {
+ program = new DepthwiseConvPacked2DProgram(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
+ }
+ else {
+ program = new DepthwiseConv2DProgram(convInfo, hasBias, fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);
+ }
+ var result = backend.runWebGLProgram(program, programInputs, 'float32');
+ intermediates.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return result;
+ }
+ var fusedDepthwiseConv2DConfig = {
+ kernelName: tf.FusedDepthwiseConv2D,
+ backendName: 'webgl',
+ kernelFunc: fusedDepthwiseConv2D,
+ };
+
+ var GatherNDProgram = /** @class */ (function () {
+ function GatherNDProgram(sliceDim, strides, shape) {
+ this.sliceDim = sliceDim;
+ this.strides = strides;
+ this.variableNames = ['x', 'indices'];
+ this.outputShape = shape;
+ var stridesType = getCoordsDataType(strides.length);
+ var dtype = getCoordsDataType(shape.length);
+ var strideString = this.sliceDim > 1 ? 'strides[j]' : 'strides';
+ this.userCode = "\n " + stridesType + " strides = " + stridesType + "(" + this.strides + ");\n void main() {\n " + dtype + " 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 * " + strideString + ";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n ";
+ }
+ return GatherNDProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function gatherNd(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var params = inputs.params, indices = inputs.indices;
+ var indicesShape = indices.shape;
+ var sliceRank = indicesShape[indicesShape.length - 1];
+ var paramsSize = tf.util.sizeFromShape(params.shape);
+ var _a = tf.backend_util.prepareAndValidate(params, indices), resultShape = _a[0], numSlices = _a[1], sliceSize = _a[2], strides = _a[3];
+ var flattenIndices = reshape({ inputs: { x: indices }, backend: backend, attrs: { shape: [numSlices, sliceRank] } });
+ var flattenX = reshape({
+ inputs: { x: params },
+ backend: backend,
+ attrs: { shape: [(tf.util.sizeFromShape(params.shape) / sliceSize), sliceSize] }
+ });
+ if (backend.shouldExecuteOnCPU([params, indices]) ||
+ params.dtype === 'string') {
+ var indicesData = backend.readSync(indices.dataId);
+ var paramsBuf = backend.bufferSync(params);
+ var outValue = gatherNdImplCPU(indicesData, paramsBuf, params.dtype, numSlices, sliceRank, sliceSize, strides, params.shape, paramsSize);
+ return backend.makeTensorInfo(resultShape, params.dtype, outValue.values);
+ }
+ var program = new GatherNDProgram(sliceRank, strides, [numSlices, sliceSize]);
+ var res = backend.runWebGLProgram(program, [flattenX, flattenIndices], flattenX.dtype);
+ var reshaped = reshape({ inputs: { x: res }, backend: backend, attrs: { shape: resultShape } });
+ backend.disposeIntermediateTensorInfo(flattenIndices);
+ backend.disposeIntermediateTensorInfo(flattenX);
+ backend.disposeIntermediateTensorInfo(res);
+ return reshaped;
+ }
+ var gatherNdConfig = {
+ kernelName: tf.GatherNd,
+ backendName: 'webgl',
+ kernelFunc: gatherNd
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var GatherProgram = /** @class */ (function () {
+ function GatherProgram(aShape, outputShape) {
+ this.variableNames = ['A', 'indices'];
+ this.outputShape = outputShape;
+ this.rank = outputShape.length;
+ var dtype = getCoordsDataType(this.rank);
+ var sourceCoords = getSourceCoords$1(aShape);
+ this.userCode = "\n void main() {\n " + dtype + " resRC = getOutputCoords();\n setOutput(getA(" + sourceCoords + "));\n }\n ";
+ }
+ return GatherProgram;
+ }());
+ // The input and output are always flattened into rank 4 tensors.
+ function getSourceCoords$1(aShape, axis) {
+ var currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w'];
+ var sourceCoords = [];
+ for (var i = 0; i < aShape.length; i++) {
+ if (i === 2) {
+ sourceCoords.push('int(getIndices(resRC.x, resRC.z))');
+ }
+ else {
+ sourceCoords.push("" + currentCoords[i]);
+ }
+ }
+ return sourceCoords.join();
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function gatherV2(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, indices = inputs.indices;
+ var axis = attrs.axis, batchDims = attrs.batchDims;
+ var parsedAxis = tf.util.parseAxisParam(axis, x.shape)[0];
+ var shapeInfo = tf.backend_util.segment_util.collectGatherOpShapeInfo(x, indices, parsedAxis, batchDims);
+ var indicesSize = tf.util.sizeFromShape(indices.shape);
+ var toDispose = [];
+ var flattenX = reshape({
+ inputs: { x: x },
+ backend: backend,
+ attrs: {
+ shape: [
+ shapeInfo.batchSize, shapeInfo.outerSize, shapeInfo.dimSize,
+ shapeInfo.sliceSize
+ ]
+ }
+ });
+ var flattenIndex = reshape({
+ inputs: { x: indices },
+ backend: backend,
+ attrs: { shape: [shapeInfo.batchSize, indicesSize / shapeInfo.batchSize] }
+ });
+ toDispose.push(flattenX);
+ toDispose.push(flattenIndex);
+ var flattenOutputShape = [
+ shapeInfo.batchSize, shapeInfo.outerSize, indicesSize / shapeInfo.batchSize,
+ shapeInfo.sliceSize
+ ];
+ if (backend.shouldExecuteOnCPU([x, indices]) || x.dtype === 'string') {
+ var indicesBuf = backend.bufferSync(flattenIndex);
+ var xBuf = backend.bufferSync(flattenX);
+ var outBuf = gatherV2ImplCPU(xBuf, indicesBuf, flattenOutputShape);
+ toDispose.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return backend.makeTensorInfo(shapeInfo.outputShape, outBuf.dtype, outBuf.values);
+ }
+ var program = new GatherProgram(flattenX.shape, flattenOutputShape);
+ var res = backend.runWebGLProgram(program, [flattenX, flattenIndex], flattenX.dtype);
+ toDispose.push(res);
+ var reshaped = reshape({ inputs: { x: res }, backend: backend, attrs: { shape: shapeInfo.outputShape } });
+ toDispose.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return reshaped;
+ }
+ var gatherV2Config = {
+ kernelName: tf.GatherV2,
+ backendName: 'webgl',
+ kernelFunc: gatherV2
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var GREATER = "return float(a > b);";
+ var GREATER_PACKED = "\n return vec4(greaterThan(a, b));\n";
+ var greater = binaryKernelFunc({
+ opSnippet: GREATER,
+ packedOpSnippet: GREATER_PACKED,
+ cpuKernelImpl: greaterImplCPU,
+ dtype: 'bool'
+ });
+ var greaterConfig = {
+ kernelName: tf.Greater,
+ backendName: 'webgl',
+ kernelFunc: greater
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var GREATER_EQUAL = "return float(a >= b);";
+ var GREATER_EQUAL_PACKED = "\n return vec4(greaterThanEqual(a, b));\n";
+ var greaterEqual = binaryKernelFunc({
+ opSnippet: GREATER_EQUAL,
+ packedOpSnippet: GREATER_EQUAL_PACKED,
+ dtype: 'bool',
+ cpuKernelImpl: greaterEqualImplCPU
+ });
+ var greaterEqualConfig = {
+ kernelName: tf.GreaterEqual,
+ backendName: 'webgl',
+ kernelFunc: greaterEqual
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function ifft(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var input = inputs.input;
+ return fftImpl(input, true /* inverse */, backend);
+ }
+ var ifftConfig = {
+ kernelName: tf.IFFT,
+ backendName: 'webgl',
+ kernelFunc: ifft
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var IS_FINITE = "return float(!isnan(x) && !isinf(x));";
+ var isFinite = unaryKernelFunc({ opSnippet: IS_FINITE, dtype: 'bool' });
+ var isFiniteConfig = {
+ kernelName: tf.IsFinite,
+ backendName: 'webgl',
+ kernelFunc: isFinite,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var IS_INF = "return float(isinf(x));";
+ var isInf = unaryKernelFunc({ opSnippet: IS_INF, dtype: 'bool' });
+ var isInfConfig = {
+ kernelName: tf.IsInf,
+ backendName: 'webgl',
+ kernelFunc: isInf,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var IS_NAN = "return float(isnan(x));";
+ var isNaN = unaryKernelFunc({ opSnippet: IS_NAN, dtype: 'bool' });
+ var isNaNConfig = {
+ kernelName: tf.IsNan,
+ backendName: 'webgl',
+ kernelFunc: isNaN,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LESS = "return float(a < b);";
+ var LESS_PACKED = "\n return vec4(lessThan(a, b));\n";
+ var less = binaryKernelFunc({
+ opSnippet: LESS,
+ packedOpSnippet: LESS_PACKED,
+ cpuKernelImpl: lessImplCPU,
+ dtype: 'bool'
+ });
+ var lessConfig = {
+ kernelName: tf.Less,
+ backendName: 'webgl',
+ kernelFunc: less
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LESS_EQUAL = "return float(a <= b);";
+ var LESS_EQUAL_PACKED = "\n return vec4(lessThanEqual(a, b));\n";
+ var lessEqual = binaryKernelFunc({
+ opSnippet: LESS_EQUAL,
+ packedOpSnippet: LESS_EQUAL_PACKED,
+ cpuKernelImpl: lessEqualImplCPU,
+ dtype: 'bool'
+ });
+ var lessEqualConfig = {
+ kernelName: tf.LessEqual,
+ backendName: 'webgl',
+ kernelFunc: lessEqual
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function linSpace(args) {
+ var backend = args.backend, attrs = args.attrs;
+ var start = attrs.start, stop = attrs.stop, num = attrs.num;
+ // TODO: Use CPU implementation due to the precision problem in Safari.
+ var outVals = linSpaceImplCPU(start, stop, num);
+ return backend.makeTensorInfo([outVals.length], 'float32', outVals);
+ }
+ var linSpaceConfig = {
+ kernelName: tf.LinSpace,
+ backendName: 'webgl',
+ kernelFunc: linSpace
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LOG = "if (x < 0.0) return NAN;\n return log(x);";
+ var LOG_PACKED = "\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";
+ var log = unaryKernelFunc({ opSnippet: LOG, packedOpSnippet: LOG_PACKED, cpuKernelImpl: logImplCPU });
+ var logConfig = {
+ kernelName: tf.Log,
+ backendName: 'webgl',
+ kernelFunc: log
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LOG1P = "return log(1.0 + x);";
+ var log1p = unaryKernelFunc({ opSnippet: LOG1P });
+ var log1pConfig = {
+ kernelName: tf.Log1p,
+ backendName: 'webgl',
+ kernelFunc: log1p,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LOGICAL_AND = "return float(a >= 1.0 && b >= 1.0);";
+ var LOGICAL_AND_PACKED = "\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n";
+ var logicalAnd = binaryKernelFunc({
+ opSnippet: LOGICAL_AND,
+ packedOpSnippet: LOGICAL_AND_PACKED,
+ dtype: 'bool'
+ });
+ var logicalAndConfig = {
+ kernelName: tf.LogicalAnd,
+ backendName: 'webgl',
+ kernelFunc: logicalAnd
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LOGICAL_NOT = "return float(!(x >= 1.0));";
+ var logicalNot = unaryKernelFunc({ opSnippet: LOGICAL_NOT });
+ var logicalNotConfig = {
+ kernelName: tf.LogicalNot,
+ backendName: 'webgl',
+ kernelFunc: logicalNot,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LOGICAL_OR = "return float(a >= 1.0 || b >= 1.0);";
+ var LOGICAL_OR_PACKED = "\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n";
+ var logicalOr = binaryKernelFunc({ opSnippet: LOGICAL_OR, packedOpSnippet: LOGICAL_OR_PACKED, dtype: 'bool' });
+ var logicalOrConfig = {
+ kernelName: tf.LogicalOr,
+ backendName: 'webgl',
+ kernelFunc: logicalOr
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LRNProgram = /** @class */ (function () {
+ function LRNProgram(xShape, radius, bias, alpha, beta) {
+ this.variableNames = ['x'];
+ this.outputShape = [];
+ var rad = radius;
+ var maxD = xShape[3] - 1;
+ this.outputShape = xShape;
+ // optimize pow(bias + alpha * sum, -beta)
+ // src: https://github.com/tensorflow/tensorflow/..
+ // blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..
+ // tensorflow/core/kernels/mkl_lrn_op.cc#L320
+ var powOperator;
+ var basis = "float(" + bias + ") + float(" + alpha + ") * sum";
+ if (beta === 0.5) {
+ powOperator = "inversesqrt(" + basis + ")";
+ }
+ else if (beta === 1.0) {
+ powOperator = "1.0/(" + basis + ")";
+ }
+ else {
+ powOperator = "exp(log(" + basis + ") * float(-" + beta + "));";
+ }
+ 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 = -" + rad + "; j <= " + rad + "; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= " + maxD + ") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * " + powOperator + ";\n setOutput(val);\n }\n ";
+ }
+ return LRNProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LRNPackedProgram = /** @class */ (function () {
+ function LRNPackedProgram(xShape, radius, bias, alpha, beta) {
+ this.variableNames = ['x'];
+ this.outputShape = [];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ var rad = radius;
+ var maxD = xShape[3] - 1;
+ this.outputShape = xShape;
+ // optimize pow(bias + alpha * sum, -beta)
+ // src: https://github.com/tensorflow/tensorflow/..
+ // blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..
+ // tensorflow/core/kernels/mkl_lrn_op.cc#L320
+ var powOperator;
+ var basis = "float(" + bias + ") + float(" + alpha + ") * sum";
+ if (beta === 0.5) {
+ powOperator = "inversesqrt(" + basis + ")";
+ }
+ else if (beta === 1.0) {
+ powOperator = "1.0/(" + basis + ")";
+ }
+ else {
+ powOperator = "exp(log(" + basis + ") * float(-" + beta + "));";
+ }
+ 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 - " + rad + ";\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 = - " + rad + "; j <= " + rad + "; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(" + maxD + "));\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 * " + powOperator + ";\n setOutput(result);\n }\n ";
+ }
+ return LRNPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var lrn = function (args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var depthRadius = attrs.depthRadius, bias = attrs.bias, alpha = attrs.alpha, beta = attrs.beta;
+ var program = tf.env().getBool('WEBGL_PACK_NORMALIZATION') ?
+ new LRNPackedProgram(x.shape, depthRadius, bias, alpha, beta) :
+ new LRNProgram(x.shape, depthRadius, bias, alpha, beta);
+ return backend.runWebGLProgram(program, [x], x.dtype);
+ };
+ // tslint:disable-next-line: variable-name
+ var LRNConfig = {
+ kernelName: tf.LRN,
+ backendName: 'webgl',
+ kernelFunc: lrn
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var LRNGradProgram = /** @class */ (function () {
+ function LRNGradProgram(inputShape, depthRadius, bias, alpha, beta) {
+ this.variableNames = ['inputImage', 'outputImage', 'dy'];
+ this.outputShape = [];
+ this.outputShape = inputShape;
+ this.depth = inputShape[3];
+ this.depthRadius = depthRadius;
+ this.bias = bias;
+ this.alpha = alpha;
+ this.beta = beta;
+ 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 - " + depthRadius + ")));\n int depthEnd = int(min(float(" + this.depth + "),\n float(d + " + depthRadius + " + 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(" + alpha + ") * norm + float(" + bias + ");\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(" + alpha + ")\n * float(" + beta + ")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * " + beta + ");\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 ";
+ }
+ return LRNGradProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var lrnGrad = function (args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, y = inputs.y, dy = inputs.dy;
+ var depthRadius = attrs.depthRadius, bias = attrs.bias, alpha = attrs.alpha, beta = attrs.beta;
+ var program = new LRNGradProgram(x.shape, depthRadius, bias, alpha, beta);
+ return backend.runWebGLProgram(program, [x, y, dy], x.dtype);
+ };
+ // tslint:disable-next-line: variable-name
+ var LRNGradConfig = {
+ kernelName: tf.LRNGrad,
+ backendName: 'webgl',
+ kernelFunc: lrnGrad
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function maxImpl$1(x, reduceShape, outShape, backend) {
+ var inSize = tf.util.sizeFromShape(reduceShape);
+ var xSize = tf.util.sizeFromShape(x.shape);
+ var batchSize = xSize / inSize;
+ var reshapedInput = reshape({ inputs: { x: x }, attrs: { shape: [batchSize, inSize] }, backend: backend });
+ var reduced = reduce(reshapedInput, x.dtype, 'max', backend);
+ var reshapedOutput = reshape({ inputs: { x: reduced }, attrs: { shape: outShape }, backend: backend });
+ backend.disposeIntermediateTensorInfo(reshapedInput);
+ backend.disposeIntermediateTensorInfo(reduced);
+ return reshapedOutput;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function max(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var reductionIndices = attrs.reductionIndices, keepDims = attrs.keepDims;
+ var xRank = x.shape.length;
+ var origAxes = tf.util.parseAxisParam(reductionIndices, x.shape);
+ var axes = origAxes;
+ var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
+ var maxInputIsTransposed = permutedAxes != null;
+ var shouldExecuteOnCPU = backend.shouldExecuteOnCPU([x]);
+ var maxInput = x;
+ if (maxInputIsTransposed) {
+ if (shouldExecuteOnCPU) {
+ var xTexData = backend.texData.get(maxInput.dataId);
+ var values = xTexData.values;
+ var newShape = new Array(xRank);
+ for (var i = 0; i < newShape.length; i++) {
+ newShape[i] = x.shape[permutedAxes[i]];
+ }
+ var maxInputValues = transposeImplCPU(values, x.shape, x.dtype, permutedAxes, newShape);
+ maxInput = backend.makeTensorInfo(newShape, x.dtype);
+ var maxInputData = backend.texData.get(maxInput.dataId);
+ maxInputData.values = maxInputValues;
+ }
+ else {
+ maxInput = transposeImpl$1(x, permutedAxes, backend);
+ }
+ axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
+ }
+ tf.backend_util.assertAxesAreInnerMostDims('max', axes, xRank);
+ var _a = tf.backend_util.computeOutAndReduceShapes(maxInput.shape, axes), maxOutShape = _a[0], reduceShape = _a[1];
+ var outShape = maxOutShape;
+ if (keepDims) {
+ // rather than reshape at the end, set the target shape here.
+ outShape = tf.backend_util.expandShapeToKeepDim(maxOutShape, origAxes);
+ }
+ var out;
+ if (shouldExecuteOnCPU) {
+ var xTexData = backend.texData.get(maxInput.dataId);
+ var values = xTexData.values;
+ var outValues = maxImplCPU(values, tf.util.sizeFromShape(reduceShape), outShape, x.dtype);
+ out = backend.makeTensorInfo(outShape, x.dtype);
+ var outData = backend.texData.get(out.dataId);
+ outData.values = outValues;
+ }
+ else {
+ out = maxImpl$1(maxInput, reduceShape, outShape, backend);
+ }
+ if (maxInputIsTransposed) {
+ backend.disposeIntermediateTensorInfo(maxInput);
+ }
+ return out;
+ }
+ var maxConfig = {
+ kernelName: tf.Max,
+ backendName: 'webgl',
+ kernelFunc: max
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var MAXIMUM = CHECK_NAN_SNIPPET$1 + "\n return max(a, b);\n";
+ var MAXIMUM_PACKED = "\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n " +
+ CHECK_NAN_SNIPPET$2 + "\n return result;\n";
+ var maximum = binaryKernelFunc({
+ opSnippet: MAXIMUM,
+ packedOpSnippet: MAXIMUM_PACKED,
+ cpuKernelImpl: maximumImplCPU
+ });
+ var maximumConfig = {
+ kernelName: tf.Maximum,
+ backendName: 'webgl',
+ kernelFunc: maximum
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function maxPool(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ assertNotComplex(x, 'maxPool');
+ var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
+ var dilations = 1;
+ tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, dilations), function () { return 'Error in maxPool: Either strides or dilations must be 1. ' +
+ ("Got strides " + strides + " and dilations '" + dilations + "'"); });
+ var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
+ if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&
+ tf.util.arraysEqual(convInfo.inShape, convInfo.outShape)) {
+ return identity({ inputs: { x: x }, backend: backend });
+ }
+ var maxPoolProgram = new Pool2DProgram(convInfo, 'max', false);
+ return backend.runWebGLProgram(maxPoolProgram, [x], x.dtype);
+ }
+ var maxPoolConfig = {
+ kernelName: tf.MaxPool,
+ backendName: 'webgl',
+ kernelFunc: maxPool
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function maxPool3d(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dataFormat = attrs.dataFormat, dimRoundingMode = attrs.dimRoundingMode;
+ var dilations = [1, 1, 1];
+ var convInfo = tf.backend_util.computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode, dataFormat);
+ var maxPoolProgram = new Pool3DProgram(convInfo, 'max', false);
+ return backend.runWebGLProgram(maxPoolProgram, [x], x.dtype);
+ }
+ var maxPool3DConfig = {
+ kernelName: tf.MaxPool3D,
+ backendName: 'webgl',
+ kernelFunc: maxPool3d
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var MaxPool2DBackpropProgram = /** @class */ (function () {
+ function MaxPool2DBackpropProgram(convInfo) {
+ this.variableNames = ['dy', 'maxPos'];
+ this.outputShape = convInfo.inShape;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationHeight = convInfo.dilationHeight;
+ var effectiveFilterHeight = convInfo.effectiveFilterHeight;
+ var effectiveFilterWidth = convInfo.effectiveFilterWidth;
+ var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
+ var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
+ var lastIndex = effectiveFilterHeight * effectiveFilterWidth - 1;
+ this.userCode = "\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\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 < " + effectiveFilterHeight + ";\n wR += " + dilationHeight + ") {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < " + effectiveFilterWidth + "; wC++) {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.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 = " + lastIndex + " - 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 * " + effectiveFilterWidth + " + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n ";
+ }
+ return MaxPool2DBackpropProgram;
+ }());
+ var MaxPool3DBackpropProgram = /** @class */ (function () {
+ function MaxPool3DBackpropProgram(convInfo) {
+ this.variableNames = ['dy', 'maxPos'];
+ this.outputShape = convInfo.inShape;
+ var strideDepth = convInfo.strideDepth;
+ var strideHeight = convInfo.strideHeight;
+ var strideWidth = convInfo.strideWidth;
+ var dilationDepth = convInfo.dilationDepth;
+ var dilationHeight = convInfo.dilationHeight;
+ var dilationWidth = convInfo.dilationWidth;
+ var effectiveFilterDepth = convInfo.effectiveFilterDepth;
+ var effectiveFilterHeight = convInfo.effectiveFilterHeight;
+ var effectiveFilterWidth = convInfo.effectiveFilterWidth;
+ var padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;
+ var padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
+ var padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
+ var lastIndex = effectiveFilterDepth * effectiveFilterHeight * effectiveFilterWidth - 1;
+ this.userCode = "\n const ivec3 pads = ivec3(" + padFront + ", " + padTop + ", " + padLeft + ");\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 < " + effectiveFilterDepth + ";\n wD += " + dilationDepth + ") {\n float dyD = float(dyDCorner + wD) / " + strideDepth + ".0;\n\n if (dyD < 0.0 || dyD >= " + convInfo.outDepth + ".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < " + effectiveFilterHeight + ";\n wR += " + dilationHeight + ") {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < " + effectiveFilterWidth + ";\n wC += " + dilationWidth + ") {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.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 = " + lastIndex + " -\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 * " + effectiveFilterHeight + " * " + effectiveFilterWidth + " +\n wR * " + effectiveFilterWidth + " + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n ";
+ }
+ return MaxPool3DBackpropProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function maxPool3DGrad(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var dy = inputs.dy, input = inputs.input;
+ var x = input;
+ var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
+ var dilations = [1, 1, 1];
+ var convInfo = tf.backend_util.computePool3DInfo(x.shape, filterSize, strides, dilations, pad, dimRoundingMode);
+ var maxPool3dPositionsProgram = new Pool3DProgram(convInfo, 'max', true /* get positions */);
+ var maxPool3dPositions = backend.runWebGLProgram(maxPool3dPositionsProgram, [x], x.dtype);
+ var maxPoolBackpropProgram = new MaxPool3DBackpropProgram(convInfo);
+ var result = backend.runWebGLProgram(maxPoolBackpropProgram, [dy, maxPool3dPositions], x.dtype);
+ backend.disposeIntermediateTensorInfo(maxPool3dPositions);
+ return result;
+ }
+ var maxPoolGrad3DConfig = {
+ kernelName: tf.MaxPool3DGrad,
+ backendName: 'webgl',
+ kernelFunc: maxPool3DGrad
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function maxPoolGrad(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var dy = inputs.dy, input = inputs.input, output = inputs.output;
+ var x = input;
+ assertNotComplex([input, output], 'maxPoolGrad');
+ var filterSize = attrs.filterSize, strides = attrs.strides, pad = attrs.pad, dimRoundingMode = attrs.dimRoundingMode;
+ var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, 1 /* dilations */, pad, dimRoundingMode);
+ var getPositions = true;
+ var maxPoolPositionsProgram = new Pool2DProgram(convInfo, 'max', getPositions);
+ var maxPoolPositions = backend.runWebGLProgram(maxPoolPositionsProgram, [x], x.dtype);
+ var maxPoolBackPropProgram = new MaxPool2DBackpropProgram(convInfo);
+ var result = backend.runWebGLProgram(maxPoolBackPropProgram, [dy, maxPoolPositions], x.dtype);
+ backend.disposeIntermediateTensorInfo(maxPoolPositions);
+ return result;
+ }
+ var maxPoolGradConfig = {
+ kernelName: tf.MaxPoolGrad,
+ backendName: 'webgl',
+ kernelFunc: maxPoolGrad
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function maxPoolWithArgmaxImpl(x, includeBatchInIndex, convInfo, backend) {
+ var program = new Pool2DProgram(convInfo, 'max', false);
+ var poolOutput = backend.runWebGLProgram(program, [x], 'float32');
+ program = new Pool2DProgram(convInfo, 'max', true, true, includeBatchInIndex);
+ var indexOutput = backend.runWebGLProgram(program, [x], 'float32');
+ return [poolOutput, indexOutput];
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var maxPoolWithArgmaxConfig = {
+ kernelName: tf.MaxPoolWithArgmax,
+ backendName: 'webgl',
+ kernelFunc: function (_a) {
+ var inputs = _a.inputs, attrs = _a.attrs, backend = _a.backend;
+ var x = inputs.x;
+ var _b = attrs, filterSize = _b.filterSize, strides = _b.strides, pad = _b.pad, includeBatchInIndex = _b.includeBatchInIndex;
+ var webglBackend = backend;
+ tf.util.assert(x.shape.length === 4, function () { return "Error in maxPool: input must be rank 4 but got rank " + x.shape.length + "."; });
+ var dilations = [1, 1];
+ tf.util.assert(tf.backend_util.eitherStridesOrDilationsAreOne(strides, dilations), function () { return 'Error in maxPool: Either strides or dilations must be 1. ' +
+ ("Got strides " + strides + " and dilations '" + dilations + "'"); });
+ var convInfo = tf.backend_util.computePool2DInfo(x.shape, filterSize, strides, dilations, pad);
+ var _c = maxPoolWithArgmaxImpl(x, includeBatchInIndex, convInfo, webglBackend), result = _c[0], indexes = _c[1];
+ return [result, indexes];
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function meanImpl(x, reduceShape, outShape, backend) {
+ var inSize = tf.util.sizeFromShape(reduceShape);
+ var xSize = tf.util.sizeFromShape(x.shape);
+ var batchSize = xSize / inSize;
+ var reshapedInput = reshape({ inputs: { x: x }, attrs: { shape: [batchSize, inSize] }, backend: backend });
+ var reduced = reduce(reshapedInput, 'float32', 'mean', backend);
+ var reshapedOutput = reshape({ inputs: { x: reduced }, attrs: { shape: outShape }, backend: backend });
+ backend.disposeIntermediateTensorInfo(reshapedInput);
+ backend.disposeIntermediateTensorInfo(reduced);
+ return reshapedOutput;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var meanConfig = {
+ kernelName: tf.Mean,
+ backendName: 'webgl',
+ kernelFunc: function (_a) {
+ var inputs = _a.inputs, attrs = _a.attrs, backend = _a.backend;
+ var x = inputs.x;
+ var _b = attrs, keepDims = _b.keepDims, axis = _b.axis;
+ var webglBackend = backend;
+ var xRank = x.shape.length;
+ var origAxes = tf.util.parseAxisParam(axis, x.shape);
+ var axes = origAxes;
+ var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
+ var meanInputIsTransposed = permutedAxes != null;
+ var shouldExecuteOnCPU = webglBackend.shouldExecuteOnCPU([x]);
+ var intermediates = [];
+ var meanInput = x;
+ if (meanInputIsTransposed) {
+ if (shouldExecuteOnCPU) {
+ var xTexData = webglBackend.texData.get(meanInput.dataId);
+ var values = xTexData.values;
+ var newShape = new Array(xRank);
+ for (var i = 0; i < newShape.length; i++) {
+ newShape[i] = x.shape[permutedAxes[i]];
+ }
+ var meanInputValues = transposeImplCPU(values, x.shape, x.dtype, permutedAxes, newShape);
+ meanInput = webglBackend.makeTensorInfo(newShape, x.dtype);
+ var meanInputData = webglBackend.texData.get(meanInput.dataId);
+ meanInputData.values = meanInputValues;
+ }
+ else {
+ meanInput = transposeImpl$1(x, permutedAxes, webglBackend);
+ }
+ intermediates.push(meanInput);
+ axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
+ }
+ tf.backend_util.assertAxesAreInnerMostDims('sum', axes, xRank);
+ var _c = tf.backend_util.computeOutAndReduceShapes(meanInput.shape, axes), meanOutShape = _c[0], reduceShape = _c[1];
+ var outShape = meanOutShape;
+ if (keepDims) {
+ // rather than reshape at the end, set the target shape here.
+ outShape = tf.backend_util.expandShapeToKeepDim(meanOutShape, origAxes);
+ }
+ var out = meanImpl(meanInput, reduceShape, outShape, webglBackend);
+ for (var _i = 0, intermediates_1 = intermediates; _i < intermediates_1.length; _i++) {
+ var i = intermediates_1[_i];
+ webglBackend.disposeIntermediateTensorInfo(i);
+ }
+ return out;
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function min(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var axis = attrs.axis, keepDims = attrs.keepDims;
+ var xRank = x.shape.length;
+ var origAxes = tf.util.parseAxisParam(axis, x.shape);
+ var axes = origAxes;
+ var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
+ var permutedX = x;
+ if (permutedAxes != null) {
+ permutedX = transpose({ inputs: { x: x }, backend: backend, attrs: { perm: permutedAxes } });
+ axes = tf.backend_util.getInnerMostAxes(axes.length, x.shape.length);
+ }
+ tf.backend_util.assertAxesAreInnerMostDims('min', axes, xRank);
+ var _a = tf.backend_util.computeOutAndReduceShapes(permutedX.shape, axes), outShape = _a[0], reduceShape = _a[1];
+ var inSize = tf.util.sizeFromShape(reduceShape);
+ var a2D = reshape({ inputs: { x: permutedX }, backend: backend, attrs: { shape: [-1, inSize] } });
+ var reduced = reduce(a2D, a2D.dtype, 'min', backend);
+ var res;
+ if (keepDims) {
+ var newShape = tf.backend_util.expandShapeToKeepDim(outShape, origAxes);
+ res = reshape({ inputs: { x: reduced }, backend: backend, attrs: { shape: newShape } });
+ }
+ else {
+ res = reshape({ inputs: { x: reduced }, backend: backend, attrs: { shape: outShape } });
+ }
+ backend.disposeIntermediateTensorInfo(a2D);
+ backend.disposeIntermediateTensorInfo(reduced);
+ if (permutedAxes != null) {
+ backend.disposeIntermediateTensorInfo(permutedX);
+ }
+ return res;
+ }
+ var minConfig = {
+ kernelName: tf.Min,
+ backendName: 'webgl',
+ kernelFunc: min
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var MINIMUM = CHECK_NAN_SNIPPET$1 + "\n return min(a, b);\n";
+ var MINIMUM_PACKED = "\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n " +
+ CHECK_NAN_SNIPPET$2 + "\n return result;\n";
+ var minimum = binaryKernelFunc({
+ opSnippet: MINIMUM,
+ packedOpSnippet: MINIMUM_PACKED,
+ cpuKernelImpl: minimumImplCPU
+ });
+ var minimumConfig = {
+ kernelName: tf.Minimum,
+ backendName: 'webgl',
+ kernelFunc: minimum
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var MirrorPadProgram = /** @class */ (function () {
+ function MirrorPadProgram(xShape, paddings, mode) {
+ this.variableNames = ['x'];
+ this.outputShape = paddings.map(function (p, i) { return p[0] /* beforePad */ + xShape[i] + p[1]; } /* afterPad */);
+ var rank = xShape.length;
+ var dtype = getCoordsDataType(rank);
+ var start = paddings.map(function (p) { return p[0]; }).join(',');
+ var end = paddings.map(function (p, i) { return p[0] + xShape[i]; }).join(',');
+ var unpackedCoords = ['coords[0]', 'coords[1]', 'coords[2]', 'coords[3]'].slice(0, rank);
+ var offset = mode === 'reflect' ? 0 : 1;
+ if (rank === 1) {
+ this.userCode = "\n int start = " + start + ";\n int end = " + end + ";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - " + offset + ";\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + " + offset + ";\n }\n setOutput(getX(outC - start));\n }\n ";
+ return;
+ }
+ this.userCode = "\n " + dtype + " start = " + dtype + "(" + start + ");\n " + dtype + " end = " + dtype + "(" + end + ");\n\n void main() {\n " + dtype + " outC = getOutputCoords();\n for (int i = 0; i < " + rank + "; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - " + offset + ";\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + " + offset + ";\n }\n }\n " + dtype + " coords = outC - start;\n setOutput(getX(" + unpackedCoords + "));\n }\n ";
+ }
+ return MirrorPadProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Example shader code for
+ * `mirrorPad(tf.tensor1d([1, 2, 3], 'int32'), [[2, 2]], 'reflect')`
+ * ```
+ * const int start = int(2);
+ * const int end = int(5);
+ *
+ * void main() {
+ * int outputLoc = getOutputCoords();
+ * vec4 result = vec4(0.);
+ *
+ * int rc = outputLoc;
+ *
+ * int source = rc;
+ * if (source < start) {
+ * source = start * 2 - source - 0;
+ * } else if (source >= end) {
+ * source = (end - 1) * 2 - source + 0;
+ * }
+ * source -= start;
+ *
+ * result[0] = getChannel(getX(source), source);
+ * rc += 1;
+ * if(rc < 6) {
+ * int source = rc;
+ * if (source < start) {
+ * source = start * 2 - source - 0;
+ * } else if (source >= end) {
+ * source = (end - 1) * 2 - source + 0;
+ * }
+ * source -= start;
+ *
+ * result[1] = getChannel(getX(source), source);
+ * }
+ *
+ * setOutput(result);
+ * }
+ * ```
+ */
+ var MirrorPadPackedProgram = /** @class */ (function () {
+ function MirrorPadPackedProgram(xShape, paddings, mode) {
+ this.variableNames = ['x'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = paddings.map(function (p, i) { return p[0] /* beforePad */ + xShape[i] + p[1]; } /* afterPad */);
+ var rank = xShape.length;
+ var dtype = getCoordsDataType(rank);
+ var start = paddings.map(function (p) { return p[0]; }).join(',');
+ var end = paddings.map(function (p, i) { return p[0] + xShape[i]; }).join(',');
+ var coords = getChannels('rc', rank);
+ var source = getChannels('source', rank);
+ var cLimit = coords[rank - 1] + " < " + this.outputShape[rank - 1];
+ var innerDims = rank === 1 ? 'source' : "vec2(" + source.slice(-2).join() + ")";
+ var offset = mode === 'reflect' ? 0 : 1;
+ var mainLoop = '';
+ if (rank === 1) {
+ var padSetup = "\n " + dtype + " source = rc;\n if (source < start) {\n source = start * 2 - source - " + offset + ";\n } else if (source >= end) {\n source = (end - 1) * 2 - source + " + offset + ";\n }\n source -= start;\n ";
+ mainLoop = "\n " + dtype + " rc = outputLoc;\n " + padSetup + "\n result[0] = getChannel(getX(" + source.join() + "), " + innerDims + ");\n " + coords[rank - 1] + " += 1;\n if(" + cLimit + ") {\n " + padSetup + "\n result[1] = getChannel(getX(" + source.join() + "), " + innerDims + ");\n }\n ";
+ }
+ else {
+ var padSetup = "\n " + dtype + " source = rc;\n " + dtype + " lt = " + dtype + "(lessThan(source, start));\n " + dtype + " gte = " + dtype + "(greaterThanEqual(source, end));\n " + dtype + " orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - " + offset + ") +\n gte * ((end - 1) * 2 - source + " + offset + ");\n source -= start;\n ";
+ mainLoop = "\n " + dtype + " rc = outputLoc;\n " + padSetup + "\n result[0] = getChannel(getX(" + source.join() + "), " + innerDims + ");\n " + coords[rank - 1] + " += 1;\n if(" + cLimit + ") {\n " + padSetup + "\n result[1] = getChannel(getX(" + source.join() + "), " + innerDims + ");\n }\n rc = outputLoc;\n " + coords[rank - 2] + " += 1;\n if(" + coords[rank - 2] + " < " + this.outputShape[rank - 2] + ") {\n " + padSetup + "\n result[2] = getChannel(getX(" + source.join() + "), " + innerDims + ");\n " + coords[rank - 1] + " += 1;\n if(" + cLimit + ") {\n " + padSetup + "\n result[3] = getChannel(getX(" + source.join() + "), " + innerDims + ");\n }\n }\n ";
+ }
+ this.userCode = "\n const " + dtype + " start = " + dtype + "(" + start + ");\n const " + dtype + " end = " + dtype + "(" + end + ");\n\n void main() {\n " + dtype + " outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n " + mainLoop + "\n setOutput(result);\n }\n ";
+ }
+ return MirrorPadPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var mirrorPadKernelFunc = function (_a) {
+ var inputs = _a.inputs, backend = _a.backend, attrs = _a.attrs;
+ var x = inputs.x;
+ var paddings = attrs.paddings, mode = attrs.mode;
+ var program = tf.env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?
+ new MirrorPadPackedProgram(x.shape, paddings, mode) :
+ new MirrorPadProgram(x.shape, paddings, mode);
+ var output = backend.runWebGLProgram(program, [x], x.dtype);
+ return output;
+ };
+ var mirrorPadConfig = {
+ kernelName: tf.MirrorPad,
+ backendName: 'webgl',
+ kernelFunc: mirrorPadKernelFunc,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var MOD = "if (b == 0.0) return NAN;\n return mod(a, b);";
+ var MOD_PACKED = "\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n " +
+ CHECK_NAN_SNIPPET$2 + "\n return result;\n";
+ var mod = binaryKernelFunc({
+ opSnippet: MOD,
+ packedOpSnippet: MOD_PACKED,
+ });
+ var modConfig = {
+ kernelName: tf.Mod,
+ backendName: 'webgl',
+ kernelFunc: mod
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var MultinomialProgram = /** @class */ (function () {
+ function MultinomialProgram(batchSize, numOutcomes, numSamples) {
+ this.variableNames = ['probs'];
+ this.outputShape = [batchSize, numSamples];
+ 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 < " + (numOutcomes - 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(" + (numOutcomes - 1) + "));\n }\n ";
+ }
+ MultinomialProgram.prototype.getCustomSetupFunc = function (seed) {
+ var _this = this;
+ return function (gpgpu, webGLProgram) {
+ if (_this.seedLoc == null) {
+ _this.seedLoc = gpgpu.getUniformLocation(webGLProgram, 'seed');
+ }
+ gpgpu.gl.uniform1f(_this.seedLoc, seed);
+ };
+ };
+ return MultinomialProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // Without the equality check div produces 0.9999 for a = b, which when
+ // floored can cause errors.
+ var DIV = "\nif (a == b) {\n return 1.0;\n};\nreturn a / b;";
+ // We do the same as in ./binaryop_gpu, with vec4 and ivec4.
+ // On Linux, the vectorized implementation produces NaNs when a and b are 0.
+ var DIV_PACKED = "\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";
+ var realDiv = binaryKernelFunc({ opSnippet: DIV, packedOpSnippet: DIV_PACKED, checkOutOfBounds: true });
+ var realDivConfig = {
+ kernelName: tf.RealDiv,
+ backendName: 'webgl',
+ kernelFunc: realDiv,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SUB = 'return a - b;';
+ var sub = binaryKernelFunc({
+ opSnippet: SUB,
+ packedOpSnippet: SUB,
+ supportsComplex: true,
+ cpuKernelImpl: subImplCPU
+ });
+ var subConfig = {
+ kernelName: tf.Sub,
+ backendName: 'webgl',
+ kernelFunc: sub
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function softmax(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var logits = inputs.logits;
+ var dim = attrs.dim;
+ var axes = tf.util.parseAxisParam([dim], logits.shape);
+ var maxLogit = max({
+ inputs: { x: logits },
+ backend: backend,
+ attrs: { reductionIndices: axes, keepDims: false }
+ });
+ var expandedShape = tf.backend_util.expandShapeToKeepDim(maxLogit.shape, axes);
+ var maxLogitsReshaped = reshape({ inputs: { x: maxLogit }, backend: backend, attrs: { shape: expandedShape } });
+ var a = sub({ inputs: { a: logits, b: maxLogitsReshaped }, backend: backend });
+ var b = exp({ inputs: { x: a }, backend: backend });
+ var sumExp = sum({ inputs: { x: b }, backend: backend, attrs: { axis: axes, keepDims: false } });
+ var sumExpReshaped = reshape({ inputs: { x: sumExp }, backend: backend, attrs: { shape: expandedShape } });
+ var res = realDiv({ inputs: { a: b, b: sumExpReshaped }, backend: backend });
+ backend.disposeIntermediateTensorInfo(maxLogit);
+ backend.disposeIntermediateTensorInfo(maxLogitsReshaped);
+ backend.disposeIntermediateTensorInfo(a);
+ backend.disposeIntermediateTensorInfo(b);
+ backend.disposeIntermediateTensorInfo(sumExp);
+ backend.disposeIntermediateTensorInfo(sumExpReshaped);
+ return res;
+ }
+ var softmaxConfig = {
+ kernelName: tf.Softmax,
+ backendName: 'webgl',
+ kernelFunc: softmax
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function multinomial(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var logits = inputs.logits;
+ var numSamples = attrs.numSamples, seed = attrs.seed, normalized = attrs.normalized;
+ var probs = normalized ?
+ logits :
+ softmax({ inputs: { logits: logits }, backend: backend, attrs: { dim: logits.shape.length - 1 } });
+ var batchSize = probs.shape[0];
+ var numOutcomes = probs.shape[1];
+ var program = new MultinomialProgram(batchSize, numOutcomes, numSamples);
+ var customSetup = program.getCustomSetupFunc(seed);
+ var res = backend.runWebGLProgram(program, [probs], 'int32', customSetup);
+ if (!normalized) {
+ backend.disposeIntermediateTensorInfo(probs);
+ }
+ return res;
+ }
+ var multinomialConfig = {
+ kernelName: tf.Multinomial,
+ backendName: 'webgl',
+ kernelFunc: multinomial
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var NEG = "return -x;";
+ // This doesn't use unaryKernelFunc because negImplCPU is not of type
+ // SimpleUnaryKernelImplCPU.
+ function neg(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var x = inputs.x;
+ if (backend.shouldExecuteOnCPU([x])) {
+ var xData = backend.texData.get(x.dataId);
+ var _a = negImplCPU(xData.values, x.shape, x.dtype), outValues = _a[0], newShape = _a[1];
+ return backend.makeTensorInfo(newShape, x.dtype, outValues);
+ }
+ var program;
+ if (tf.env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {
+ program = new UnaryOpPackedProgram(x.shape, NEG);
+ }
+ else {
+ program = new UnaryOpProgram(x.shape, NEG);
+ }
+ return backend.runWebGLProgram(program, [x], x.dtype);
+ }
+ var negConfig = {
+ kernelName: tf.Neg,
+ backendName: 'webgl',
+ kernelFunc: neg
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var nonMaxSuppressionV3Impl = tf.kernel_impls.nonMaxSuppressionV3Impl;
+ function nonMaxSuppressionV3(args) {
+ tf.backend_util.warn('tf.nonMaxSuppression() in webgl locks the UI thread. ' +
+ 'Call tf.nonMaxSuppressionAsync() instead');
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var boxes = inputs.boxes, scores = inputs.scores;
+ var maxOutputSize = attrs.maxOutputSize, iouThreshold = attrs.iouThreshold, scoreThreshold = attrs.scoreThreshold;
+ var boxesVals = backend.readSync(boxes.dataId);
+ var scoresVals = backend.readSync(scores.dataId);
+ var selectedIndices = nonMaxSuppressionV3Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold).selectedIndices;
+ return backend.makeTensorInfo([selectedIndices.length], 'int32', new Int32Array(selectedIndices));
+ }
+ var nonMaxSuppressionV3Config = {
+ kernelName: tf.NonMaxSuppressionV3,
+ backendName: 'webgl',
+ kernelFunc: nonMaxSuppressionV3
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var nonMaxSuppressionV4Impl = tf.kernel_impls.nonMaxSuppressionV4Impl;
+ function nonMaxSuppressionV4(args) {
+ tf.backend_util.warn('tf.nonMaxSuppression() in webgl locks the UI thread. ' +
+ 'Call tf.nonMaxSuppressionAsync() instead');
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var boxes = inputs.boxes, scores = inputs.scores;
+ var maxOutputSize = attrs.maxOutputSize, iouThreshold = attrs.iouThreshold, scoreThreshold = attrs.scoreThreshold, padToMaxOutputSize = attrs.padToMaxOutputSize;
+ var boxesVals = backend.readSync(boxes.dataId);
+ var scoresVals = backend.readSync(scores.dataId);
+ var _a = nonMaxSuppressionV4Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize), selectedIndices = _a.selectedIndices, validOutputs = _a.validOutputs;
+ return [
+ backend.makeTensorInfo([selectedIndices.length], 'int32', new Int32Array(selectedIndices)),
+ backend.makeTensorInfo([], 'int32', new Int32Array([validOutputs]))
+ ];
+ }
+ var nonMaxSuppressionV4Config = {
+ kernelName: tf.NonMaxSuppressionV4,
+ backendName: 'webgl',
+ kernelFunc: nonMaxSuppressionV4
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var nonMaxSuppressionV5Impl = tf.kernel_impls.nonMaxSuppressionV5Impl;
+ function nonMaxSuppressionV5(args) {
+ tf.backend_util.warn('tf.nonMaxSuppression() in webgl locks the UI thread. ' +
+ 'Call tf.nonMaxSuppressionAsync() instead');
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var boxes = inputs.boxes, scores = inputs.scores;
+ var maxOutputSize = attrs.maxOutputSize, iouThreshold = attrs.iouThreshold, scoreThreshold = attrs.scoreThreshold, softNmsSigma = attrs.softNmsSigma;
+ var boxesVals = backend.readSync(boxes.dataId);
+ var scoresVals = backend.readSync(scores.dataId);
+ var maxOutputSizeVal = maxOutputSize;
+ var iouThresholdVal = iouThreshold;
+ var scoreThresholdVal = scoreThreshold;
+ var softNmsSigmaVal = softNmsSigma;
+ var _a = nonMaxSuppressionV5Impl(boxesVals, scoresVals, maxOutputSizeVal, iouThresholdVal, scoreThresholdVal, softNmsSigmaVal), selectedIndices = _a.selectedIndices, selectedScores = _a.selectedScores;
+ return [
+ backend.makeTensorInfo([selectedIndices.length], 'int32', new Int32Array(selectedIndices)),
+ backend.makeTensorInfo([selectedScores.length], 'float32', new Float32Array(selectedScores))
+ ];
+ }
+ var nonMaxSuppressionV5Config = {
+ kernelName: tf.NonMaxSuppressionV5,
+ backendName: 'webgl',
+ kernelFunc: nonMaxSuppressionV5
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var OneHotProgram = /** @class */ (function () {
+ function OneHotProgram(numIndices, depth, onValue, offValue) {
+ this.variableNames = ['indices'];
+ this.outputShape = [numIndices, depth];
+ this.userCode = "\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(" + offValue + "), float(" + onValue + "),\n float(index == coords.y)));\n }\n ";
+ }
+ return OneHotProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var oneHot = function (args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var indices = inputs.indices;
+ var depth = attrs.depth, onValue = attrs.onValue, offValue = attrs.offValue;
+ var indicesSize = tf.util.sizeFromShape(indices.shape);
+ var program = new OneHotProgram(indicesSize, depth, onValue, offValue);
+ var reshaped = reshape({ inputs: { x: indices }, backend: backend, attrs: { shape: [indicesSize] } });
+ var result = backend.runWebGLProgram(program, [reshaped], indices.dtype);
+ backend.disposeIntermediateTensorInfo(reshaped);
+ var outShape = indices.shape.concat([depth]);
+ var out = reshape({ inputs: { x: result }, backend: backend, attrs: { shape: outShape } });
+ backend.disposeIntermediateTensorInfo(result);
+ return out;
+ };
+ var oneHotConfig = {
+ kernelName: tf.OneHot,
+ backendName: 'webgl',
+ kernelFunc: oneHot
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function zerosLike(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var x = inputs.x;
+ if (x.dtype === 'complex64') {
+ var realPart = real({ inputs: { input: x }, backend: backend });
+ var r = zerosLike({ inputs: { x: realPart }, backend: backend });
+ var imagPart = imag({ inputs: { input: x }, backend: backend });
+ var i = zerosLike({ inputs: { x: imagPart }, backend: backend });
+ var result = complex({ inputs: { real: r, imag: i }, backend: backend });
+ backend.disposeIntermediateTensorInfo(realPart);
+ backend.disposeIntermediateTensorInfo(r);
+ backend.disposeIntermediateTensorInfo(imagPart);
+ backend.disposeIntermediateTensorInfo(i);
+ return result;
+ }
+ else {
+ return fill({
+ attrs: {
+ shape: x.shape,
+ dtype: x.dtype,
+ value: x.dtype === 'string' ? '' : 0
+ },
+ backend: backend
+ });
+ }
+ }
+ var zerosLikeConfig = {
+ kernelName: tf.ZerosLike,
+ backendName: 'webgl',
+ kernelFunc: zerosLike
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function onesLike(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var x = inputs.x;
+ if (x.dtype === 'string') {
+ throw new Error('onesLike is not supported under string dtype');
+ }
+ else if (x.dtype === 'complex64') {
+ var realPart = real({ inputs: { input: x }, backend: backend });
+ var r = onesLike({ inputs: { x: realPart }, backend: backend });
+ var imagPart = imag({ inputs: { input: x }, backend: backend });
+ var i = zerosLike({ inputs: { x: imagPart }, backend: backend });
+ var result = complex({ inputs: { real: r, imag: i }, backend: backend });
+ backend.disposeIntermediateTensorInfo(realPart);
+ backend.disposeIntermediateTensorInfo(r);
+ backend.disposeIntermediateTensorInfo(imagPart);
+ backend.disposeIntermediateTensorInfo(i);
+ return result;
+ }
+ else {
+ // TODO(cais, smilkov): Add WebGL shader for onesLike:
+ // https://github.com/tensorflow/tfjs/issues/1293
+ return fill({ attrs: { shape: x.shape, dtype: x.dtype, value: 1 }, backend: backend });
+ }
+ }
+ var onesLikeConfig = {
+ kernelName: tf.OnesLike,
+ backendName: 'webgl',
+ kernelFunc: onesLike
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function pack(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var axis = attrs.axis;
+ if (inputs.length === 1) {
+ return expandDims({ inputs: { input: inputs[0] }, backend: backend, attrs: { dim: axis } });
+ }
+ var shape = inputs[0].shape;
+ var dtype = inputs[0].dtype;
+ inputs.forEach(function (t) {
+ tf.util.assertShapesMatch(shape, t.shape, 'All tensors passed to stack must have matching shapes');
+ tf.util.assert(dtype === t.dtype, function () { return 'All tensors passed to stack must have matching dtypes'; });
+ });
+ var intermediateTensorInfos = [];
+ var expandedTensors = inputs.map(function (t) {
+ var expandedT = expandDims({ inputs: { input: t }, backend: backend, attrs: { dim: axis } });
+ intermediateTensorInfos.push(expandedT);
+ return expandedT;
+ });
+ var result = concat({ inputs: expandedTensors, backend: backend, attrs: { axis: axis } });
+ intermediateTensorInfos.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return result;
+ }
+ var packConfig = {
+ kernelName: tf.Pack,
+ backendName: 'webgl',
+ kernelFunc: pack
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var PadProgram = /** @class */ (function () {
+ function PadProgram(xShape, paddings, constantValue) {
+ this.variableNames = ['x'];
+ this.outputShape = paddings.map(function (p, i) { return p[0] /* beforePad */ + xShape[i] + p[1]; } /* afterPad */);
+ var rank = xShape.length;
+ var type = getCoordsDataType(rank);
+ var start = paddings.map(function (p) { return p[0]; }).join(',');
+ var end = paddings.map(function (p, i) { return p[0] + xShape[i]; }).join(',');
+ var unpackedCoords = ['coords[0]', 'coords[1]', 'coords[2]', 'coords[3]'].slice(0, rank);
+ if (rank === 1) {
+ this.userCode = "\n int start = " + start + ";\n int end = " + end + ";\n uniform float value;\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n ";
+ return;
+ }
+ this.userCode = "\n " + type + " start = " + type + "(" + start + ");\n " + type + " end = " + type + "(" + end + ");\n uniform float value;\n\n void main() {\n " + type + " outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n " + type + " coords = outC - start;\n setOutput(getX(" + unpackedCoords + "));\n }\n }\n ";
+ }
+ PadProgram.prototype.getCustomSetupFunc = function (value) {
+ var _this = this;
+ return function (gpgpu, webGLProgram) {
+ if (_this.valueLoc == null) {
+ _this.valueLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'value');
+ }
+ gpgpu.gl.uniform1f(_this.valueLoc, value);
+ };
+ };
+ return PadProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var PadPackedProgram = /** @class */ (function () {
+ function PadPackedProgram(xShape, paddings, constantValue) {
+ this.variableNames = ['x'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = paddings.map(function (p, i) { return p[0] /* beforePad */ + xShape[i] + p[1]; } /* afterPad */);
+ var rank = xShape.length;
+ var dtype = getCoordsDataType(rank);
+ var start = paddings.map(function (p) { return p[0]; }).join(',');
+ var end = paddings.map(function (p, i) { return p[0] + xShape[i]; }).join(',');
+ var coords = getChannels('rc', rank);
+ var source = getChannels('source', rank);
+ var cLimit = coords[rank - 1] + " < " + this.outputShape[rank - 1];
+ var innerDims = rank === 1 ? 'source' : "vec2(" + source.slice(-2).join() + ")";
+ var componentSetup = [
+ dtype + " rc = outputLoc;", coords[rank - 1] + " += 1;\n if(" + cLimit + ") {\n ",
+ rank === 1 ? '' : "}\n rc = outputLoc;\n " + coords[rank - 2] + " += 1;\n if(" + coords[rank - 2] + " < " + this.outputShape[rank - 2] + ") {",
+ rank === 1 ? '' : " " + coords[rank - 1] + " += 1;\n if(" + cLimit + ") {"
+ ];
+ var paddingArea = rank === 1 ?
+ 'rc < start || rc >= end' :
+ 'any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))';
+ var mainLoop = '';
+ for (var i = 0, j = rank === 1 ? 2 : 4; i < j; i++) {
+ mainLoop += "\n " + componentSetup[i] + "\n if (" + paddingArea + ") {\n result[" + i + "] = float(value);\n } else {\n " + dtype + " source = rc - start;\n result[" + i + "] = getChannel(getX(" + source.join() + "), " + innerDims + ");\n }\n ";
+ }
+ mainLoop += (rank === 1 ? "} " : "}}");
+ this.userCode = "\n const " + dtype + " start = " + dtype + "(" + start + ");\n const " + dtype + " end = " + dtype + "(" + end + ");\n uniform float value;\n\n void main() {\n " + dtype + " outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n " + mainLoop + "\n setOutput(result);\n }\n ";
+ }
+ PadPackedProgram.prototype.getCustomSetupFunc = function (value) {
+ var _this = this;
+ return function (gpgpu, webGLProgram) {
+ if (_this.valueLoc == null) {
+ _this.valueLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'value');
+ }
+ gpgpu.gl.uniform1f(_this.valueLoc, value);
+ };
+ };
+ return PadPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var padV2 = function (args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var paddings = attrs.paddings, constantValue = attrs.constantValue;
+ var program = tf.env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?
+ new PadPackedProgram(x.shape, paddings, constantValue) :
+ new PadProgram(x.shape, paddings, constantValue);
+ var customSetup = program.getCustomSetupFunc(constantValue);
+ return backend.runWebGLProgram(program, [x], x.dtype, customSetup);
+ };
+ var padV2Config = {
+ kernelName: tf.PadV2,
+ backendName: 'webgl',
+ kernelFunc: padV2
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var POW = "\n if(a < 0.0 && floor(b) < b){\n return NAN;\n }\n if (b == 0.0) {\n return 1.0;\n }\n return (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n";
+ var POW_PACKED = "\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 " +
+ CHECK_NAN_SNIPPET$2 + "\n return result;\n";
+ var pow = binaryKernelFunc({ opSnippet: POW, packedOpSnippet: POW_PACKED });
+ var powConfig = {
+ kernelName: tf.Pow,
+ backendName: 'webgl',
+ kernelFunc: pow
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function prod(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var axis = attrs.axis, keepDims = attrs.keepDims;
+ var xRank = x.shape.length;
+ var toDispose = [];
+ var origAxes = tf.util.parseAxisParam(axis, x.shape);
+ var axes = origAxes;
+ var permutedAxes = tf.backend_util.getAxesPermutation(axes, xRank);
+ var permutedX = x;
+ if (permutedAxes != null) {
+ permutedX = transpose({ inputs: { x: x }, backend: backend, attrs: { perm: permutedAxes } });
+ axes = tf.backend_util.getInnerMostAxes(axes.length, xRank);
+ toDispose.push(permutedX);
+ }
+ tf.backend_util.assertAxesAreInnerMostDims('prod', axes, xRank);
+ var res;
+ if (backend.shouldExecuteOnCPU([permutedX])) {
+ var xVals = backend.texData.get(permutedX.dataId).values;
+ var _a = prodImplCPU(permutedX.shape, permutedX.dtype, xVals, axes), outVals = _a.outVals, outShape = _a.outShape, outDtype = _a.outDtype;
+ res = backend.makeTensorInfo(outShape, outDtype, outVals);
+ }
+ else {
+ var _b = tf.backend_util.computeOutAndReduceShapes(permutedX.shape, axes), outShape = _b[0], reduceShape = _b[1];
+ var inSize = tf.util.sizeFromShape(reduceShape);
+ var a2D = reshape({ inputs: { x: permutedX }, backend: backend, attrs: { shape: [-1, inSize] } });
+ var outputDType = tf.sumOutType(x.dtype);
+ var reduced = reduce(a2D, outputDType, 'prod', backend);
+ res = reshape({ inputs: { x: reduced }, backend: backend, attrs: { shape: outShape } });
+ toDispose.push(a2D);
+ toDispose.push(reduced);
+ }
+ if (keepDims) {
+ toDispose.push(res);
+ var newShape = tf.backend_util.expandShapeToKeepDim(res.shape, origAxes);
+ res = reshape({ inputs: { x: res }, backend: backend, attrs: { shape: newShape } });
+ }
+ toDispose.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return res;
+ }
+ var prodConfig = {
+ kernelName: tf.Prod,
+ backendName: 'webgl',
+ kernelFunc: prod
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var range = function (args) {
+ var backend = args.backend, attrs = args.attrs;
+ var start = attrs.start, stop = attrs.stop, step = attrs.step, dtype = attrs.dtype;
+ var values = rangeImplCPU(start, stop, step, dtype);
+ return backend.makeTensorInfo([values.length], dtype, values);
+ };
+ var rangeConfig = {
+ kernelName: tf.Range,
+ backendName: 'webgl',
+ kernelFunc: range
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var RECIPROCAL = "return 1.0 / x;";
+ var reciprocal = unaryKernelFunc({ opSnippet: RECIPROCAL });
+ var reciprocalConfig = {
+ kernelName: tf.Reciprocal,
+ backendName: 'webgl',
+ kernelFunc: reciprocal,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var RELU$2 = CHECK_NAN_SNIPPET + "\n return (x < 0.0) ? 0.0 : x;\n";
+ var RELU_PACKED = "\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n";
+ var relu = unaryKernelFunc({ opSnippet: RELU$2, packedOpSnippet: RELU_PACKED });
+ var reluConfig = {
+ kernelName: tf.Relu,
+ backendName: 'webgl',
+ kernelFunc: relu
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var RELU6$2 = CHECK_NAN_SNIPPET + "\n return (x < 0.0) ? 0.0 : min(6.0, x);\n";
+ var RELU6_PACKED = "\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n";
+ var relu6 = unaryKernelFunc({ opSnippet: RELU6$2, packedOpSnippet: RELU6_PACKED });
+ var relu6Config = {
+ kernelName: tf.Relu6,
+ backendName: 'webgl',
+ kernelFunc: relu6
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ResizeBilinearProgram = /** @class */ (function () {
+ function ResizeBilinearProgram(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters) {
+ this.variableNames = ['A'];
+ this.outputShape = [];
+ var batch = inputShape[0], oldHeight = inputShape[1], oldWidth = inputShape[2], depth = inputShape[3];
+ this.outputShape = [batch, newHeight, newWidth, depth];
+ var effectiveInSize = [
+ (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,
+ (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth
+ ];
+ var effectiveOutSize = [
+ (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,
+ (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth
+ ];
+ var sourceFracIndexRC;
+ if (halfPixelCenters) {
+ sourceFracIndexRC =
+ "(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC" +
+ " - vec2(0.5)";
+ }
+ else {
+ sourceFracIndexRC = "vec2(yRC) * effectiveInputOverOutputRatioRC";
+ }
+ this.userCode = "\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n " + effectiveInSize[0] / effectiveOutSize[0] + ",\n " + effectiveInSize[1] / effectiveOutSize[1] + ");\n const vec2 inputShapeRC = vec2(" + oldHeight + ".0, " + oldWidth + ".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 = " + sourceFracIndexRC + ";\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n ";
+ }
+ return ResizeBilinearProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ResizeBilinearPackedProgram = /** @class */ (function () {
+ function ResizeBilinearPackedProgram(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = [];
+ var batch = inputShape[0], oldHeight = inputShape[1], oldWidth = inputShape[2], depth = inputShape[3];
+ this.outputShape = [batch, newHeight, newWidth, depth];
+ var effectiveInSize = [
+ (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,
+ (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth
+ ];
+ var effectiveOutSize = [
+ (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,
+ (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth
+ ];
+ var sourceFracIndexRC;
+ if (halfPixelCenters) {
+ sourceFracIndexRC = "(vec3(yRC) + vec3(0.5)) * " +
+ "effectiveInputOverOutputRatioRC - vec3(0.5)";
+ }
+ else {
+ sourceFracIndexRC = "vec3(yRC) * effectiveInputOverOutputRatioRC";
+ }
+ this.userCode = "\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n " + effectiveInSize[0] / effectiveOutSize[0] + ",\n " + effectiveInSize[1] / effectiveOutSize[1] + ",\n " + effectiveInSize[1] / effectiveOutSize[1] + ");\n const vec3 inputShapeRC = vec3(" + oldHeight + ".0, " + oldWidth + ".0,\n " + oldWidth + ".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 = " + sourceFracIndexRC + ";\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < " + (depth - 1) + ";\n bool hasNextRow = coords.z < " + (newWidth - 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 ";
+ }
+ return ResizeBilinearPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function resizeBilinear(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var images = inputs.images;
+ var alignCorners = attrs.alignCorners, halfPixelCenters = attrs.halfPixelCenters, size = attrs.size;
+ var newHeight = size[0], newWidth = size[1];
+ var program = tf.env().getBool('WEBGL_PACK_IMAGE_OPERATIONS') ?
+ new ResizeBilinearPackedProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters) :
+ new ResizeBilinearProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters);
+ return backend.runWebGLProgram(program, [images], 'float32');
+ }
+ var resizeBilinearConfig = {
+ kernelName: tf.ResizeBilinear,
+ backendName: 'webgl',
+ kernelFunc: resizeBilinear
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ResizeBilinearBackpropProgram = /** @class */ (function () {
+ function ResizeBilinearBackpropProgram(dyShape, inputShape, alignCorners) {
+ this.variableNames = ['dy'];
+ this.outputShape = [];
+ this.outputShape = inputShape;
+ var xHeight = inputShape[1], xWidth = inputShape[2];
+ var yHeight = dyShape[1], yWidth = dyShape[2];
+ // In the backwards pass, we want to find the pixels that were generated for
+ // each pixel in the input image the forward pass and add the corresponding
+ // coefficient from dy to the gradient (with some interpolation).
+ var effectiveXSize = [
+ (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,
+ (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth
+ ];
+ var effectiveYSize = [
+ (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,
+ (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth
+ ];
+ var heightScale = effectiveXSize[0] / effectiveYSize[0];
+ var widthScale = effectiveXSize[1] / effectiveYSize[1];
+ var invHeightScale = 1 / heightScale;
+ var invWidthScale = 1 / widthScale;
+ // This defines the size of the window of values around a particular
+ // index in dy that we want to search for contributions to dx.
+ var winHeight = (Math.ceil(invHeightScale) * 2) + 2;
+ var winWidth = (Math.ceil(invWidthScale) * 2) + 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(" + heightScale + ");\n const float widthScale = float(" + widthScale + ");\n\n const float invHeightScale = float(" + invHeightScale + ");\n const float invWidthScale = float(" + invWidthScale + ");\n\n const int winHeight = int(" + winHeight + ");\n const int winWidth = int(" + winWidth + ");\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 >= " + yHeight + ") {\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 >= " + yWidth + ") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), " + (xHeight - 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), " + (xWidth - 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 ";
+ }
+ return ResizeBilinearBackpropProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function resizeBilinearGrad(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var images = inputs.images, dy = inputs.dy;
+ var alignCorners = attrs.alignCorners;
+ var program = new ResizeBilinearBackpropProgram(dy.shape, images.shape, alignCorners);
+ return backend.runWebGLProgram(program, [dy], dy.dtype);
+ }
+ var resizeBilinearGradConfig = {
+ kernelName: tf.ResizeBilinearGrad,
+ backendName: 'webgl',
+ kernelFunc: resizeBilinearGrad
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ResizeNearestNeighborProgram = /** @class */ (function () {
+ function ResizeNearestNeighborProgram(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters) {
+ this.variableNames = ['A'];
+ this.outputShape = [];
+ var batch = inputShape[0], oldHeight = inputShape[1], oldWidth = inputShape[2], depth = inputShape[3];
+ this.outputShape = [batch, newHeight, newWidth, depth];
+ var effectiveInSize = [
+ (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,
+ (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth
+ ];
+ var effectiveOutSize = [
+ (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,
+ (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth
+ ];
+ // When align corners is false, we rounds the value with floor.
+ var roundBase = alignCorners ? '0.5' : '0.0';
+ var sourceFracIndexRC;
+ if (halfPixelCenters) {
+ sourceFracIndexRC =
+ "max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC" +
+ ", vec2(0.0))";
+ }
+ else {
+ sourceFracIndexRC = "vec2(yRC) * effectiveInputOverOutputRatioRC";
+ }
+ this.userCode = "\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n " + effectiveInSize[0] / effectiveOutSize[0] + ",\n " + effectiveInSize[1] / effectiveOutSize[1] + ");\n const vec2 inputShapeRC = vec2(" + oldHeight + ".0, " + oldWidth + ".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 = " + sourceFracIndexRC + ";\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + " + roundBase + ")));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n ";
+ }
+ return ResizeNearestNeighborProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ResizeNearestNeighborPackedProgram = /** @class */ (function () {
+ function ResizeNearestNeighborPackedProgram(inputShape, newHeight, newWidth, alignCorners, halfPixelCenters) {
+ this.variableNames = ['A'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ this.outputShape = [];
+ var batch = inputShape[0], oldHeight = inputShape[1], oldWidth = inputShape[2], depth = inputShape[3];
+ this.outputShape = [batch, newHeight, newWidth, depth];
+ var effectiveInSize = [
+ (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,
+ (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth
+ ];
+ var effectiveOutSize = [
+ (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,
+ (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth
+ ];
+ // When align corners is false, we rounds the value with floor.
+ var roundBase = alignCorners ? '0.5' : '0.0';
+ var sourceFracIndexRC;
+ if (halfPixelCenters) {
+ sourceFracIndexRC = "max((vec3(yRC) + vec3(0.5)) * " +
+ "effectiveInputOverOutputRatioRC, vec3(0.0))";
+ }
+ else {
+ sourceFracIndexRC = "vec3(yRC) * effectiveInputOverOutputRatioRC";
+ }
+ this.userCode = "\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n " + effectiveInSize[0] / effectiveOutSize[0] + ",\n " + effectiveInSize[1] / effectiveOutSize[1] + ",\n " + effectiveInSize[1] / effectiveOutSize[1] + ");\n const vec3 inputShapeRC = vec3(" + oldHeight + ".0, " + oldWidth + ".0,\n " + oldWidth + ".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 = " + sourceFracIndexRC + ";\n\n // Compute the coordinators of nearest neighbor point.\n ivec3 sourceNearestRC = ivec3(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + " + roundBase + ")));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < " + (depth - 1) + ";\n bool hasNextRow = coords.z < " + (newWidth - 1) + ";\n\n vec4 newValue = vec4(\n getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\n hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\n\n setOutput(newValue);\n }\n ";
+ }
+ return ResizeNearestNeighborPackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function resizeNearestNeighbor(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var images = inputs.images;
+ var alignCorners = attrs.alignCorners, halfPixelCenters = attrs.halfPixelCenters, size = attrs.size;
+ var newHeight = size[0], newWidth = size[1];
+ var program = tf.env().getBool('WEBGL_PACK_IMAGE_OPERATIONS') ?
+ new ResizeNearestNeighborPackedProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters) :
+ new ResizeNearestNeighborProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters);
+ return backend.runWebGLProgram(program, [images], images.dtype);
+ }
+ var resizeNearestNeighborConfig = {
+ kernelName: tf.ResizeNearestNeighbor,
+ backendName: 'webgl',
+ kernelFunc: resizeNearestNeighbor
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ResizeNearestNeigborBackpropProgram = /** @class */ (function () {
+ function ResizeNearestNeigborBackpropProgram(dyShape, inputShape, alignCorners) {
+ this.variableNames = ['dy'];
+ this.outputShape = [];
+ this.outputShape = inputShape;
+ var xHeight = inputShape[1], xWidth = inputShape[2];
+ var yHeight = dyShape[1], yWidth = dyShape[2];
+ // In the backwards pass, we want to find the pixels that were generated for
+ // each pixel in the input image the forward pass and add the corresponding
+ // coefficient from dy to the gradient (with some interpolation).
+ var effectiveXSize = [
+ (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,
+ (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth
+ ];
+ var effectiveYSize = [
+ (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,
+ (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth
+ ];
+ var heightScale = effectiveXSize[0] / effectiveYSize[0];
+ var widthScale = effectiveXSize[1] / effectiveYSize[1];
+ var invHeightScale = 1 / heightScale;
+ var invWidthScale = 1 / widthScale;
+ // This defines the size of the window of values around a particular
+ // index in dy that we want to search for contributions to dx.
+ var winHeight = (Math.ceil(invHeightScale) * 2) + 2;
+ var winWidth = (Math.ceil(invWidthScale) * 2) + 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(" + heightScale + ");\n const float widthScale = float(" + widthScale + ");\n\n const float invHeightScale = float(" + invHeightScale + ");\n const float invWidthScale = float(" + invWidthScale + ");\n\n const int winHeight = int(" + winHeight + ");\n const int winWidth = int(" + winWidth + ");\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 >= " + yHeight + ") {\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 >= " + yWidth + ") {\n continue;\n }\n\n float sourceFracRow =\n float(" + effectiveXSize[0] + ") *\n (float(dyR) / float(" + effectiveYSize[0] + "));\n\n float sourceFracCol =\n float(" + effectiveXSize[1] + ") *\n (float(dyC) / float(" + effectiveYSize[1] + "));\n\n int sourceNearestRow = int(min(\n float(int(" + xHeight + ") - 1),\n " + alignCorners + " ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(" + xWidth + ") - 1),\n " + alignCorners + " ? 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 ";
+ }
+ return ResizeNearestNeigborBackpropProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function resizeNearestNeighborGrad(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var images = inputs.images, dy = inputs.dy;
+ var alignCorners = attrs.alignCorners;
+ var program = new ResizeNearestNeigborBackpropProgram(dy.shape, images.shape, alignCorners);
+ return backend.runWebGLProgram(program, [dy], dy.dtype);
+ }
+ var resizeNearestNeighborGradConfig = {
+ kernelName: tf.ResizeNearestNeighborGrad,
+ backendName: 'webgl',
+ kernelFunc: resizeNearestNeighborGrad
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ReverseProgram = /** @class */ (function () {
+ function ReverseProgram(xShape, axis) {
+ this.variableNames = ['x'];
+ var rank = xShape.length;
+ if (rank > 4) {
+ throw new Error("WebGL backend: Reverse of rank-" + rank + " tensor is not yet supported");
+ }
+ this.outputShape = xShape;
+ if (rank === 1) {
+ this.userCode = "\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(" + xShape[0] + " - coord - 1));\n }\n ";
+ return;
+ }
+ var getInCoord = function (i) {
+ if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {
+ return xShape[i] + " - coords[" + i + "] - 1";
+ }
+ return "coords[" + i + "]";
+ };
+ var inCoords = xShape.map(function (_, i) { return getInCoord(i); }).join(',');
+ var type = getCoordsDataType(rank);
+ this.userCode = "\n void main() {\n " + type + " coords = getOutputCoords();\n setOutput(getX(" + inCoords + "));\n }\n ";
+ }
+ return ReverseProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ReversePackedProgram = /** @class */ (function () {
+ function ReversePackedProgram(xShape, axis) {
+ this.variableNames = ['x'];
+ this.packedInputs = true;
+ this.packedOutput = true;
+ var rank = xShape.length;
+ if (rank > 4) {
+ throw new Error("WebGL backend: Reverse of rank-" + rank + " tensor is not yet supported");
+ }
+ this.outputShape = xShape;
+ var channels = getChannels('rc', rank);
+ var nextColumn = channels[rank - 1] + " + 1 < " + this.outputShape[rank - 1];
+ var nextRow = channels[rank - 2] + " + 1 < " + this.outputShape[rank - 2];
+ var type = getCoordsDataType(rank);
+ if (rank === 1) {
+ this.userCode = "\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(" + xShape[0] + " - rc - 1),\n " + xShape[0] + " - rc - 1);\n if(" + nextColumn + "){\n result.g = getChannel(getX(" + xShape[0] + " - (rc + 1) - 1),\n " + xShape[0] + " - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ";
+ }
+ else {
+ this.userCode = "\n void main() {\n " + type + " rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = " + getR(channels.slice()) + ";\n if(" + nextColumn + "){\n result.g = " + getG(channels.slice()) + ";\n }\n if(" + nextRow + ") {\n result.b = " + getB(channels.slice()) + ";\n if(" + nextColumn + ") {\n result.a = " + getA(channels.slice()) + ";\n }\n }\n setOutput(result);\n }\n ";
+ }
+ function getR(channels) {
+ return getChannel(channels);
+ }
+ function getG(channels) {
+ channels[rank - 1] = '(' + channels[rank - 1] + " + 1)";
+ return getChannel(channels);
+ }
+ function getB(channels) {
+ channels[rank - 2] = '(' + channels[rank - 2] + " + 1)";
+ return getChannel(channels);
+ }
+ function getA(channels) {
+ channels[rank - 1] = '(' + channels[rank - 1] + " + 1)";
+ channels[rank - 2] = '(' + channels[rank - 2] + " + 1)";
+ return getChannel(channels);
+ }
+ function getChannel(channels) {
+ var inCoordsArray = xShape.map(function (_, i) { return getInCoord(i, channels); });
+ var inCoords = inCoordsArray.join(',');
+ var innerDims = inCoordsArray.slice(-2).join(',');
+ return "getChannel(getX(" + inCoords + "), vec2(" + innerDims + "))";
+ }
+ function getInCoord(i, channels1) {
+ if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {
+ return xShape[i] + " - " + channels1[i] + " - 1";
+ }
+ else {
+ return "" + channels1[i];
+ }
+ }
+ }
+ return ReversePackedProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function reverse(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var dims = attrs.dims;
+ var xRank = x.shape.length;
+ var $dims = tf.util.parseAxisParam(dims, x.shape);
+ if (xRank === 0) {
+ return identity({ inputs: { x: x }, backend: backend });
+ }
+ var program = tf.env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?
+ new ReversePackedProgram(x.shape, $dims) :
+ new ReverseProgram(x.shape, $dims);
+ return backend.runWebGLProgram(program, [x], x.dtype);
+ }
+ var reverseConfig = {
+ kernelName: tf.Reverse,
+ backendName: 'webgl',
+ kernelFunc: reverse
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var RotateProgram = /** @class */ (function () {
+ function RotateProgram(imageShape, fillValue) {
+ this.variableNames = ['Image'];
+ this.outputShape = [];
+ var imageHeight = imageShape[1];
+ var imageWidth = imageShape[2];
+ this.outputShape = imageShape;
+ var fillSnippet = '';
+ if (typeof fillValue === 'number') {
+ fillSnippet = "float outputValue = " + fillValue.toFixed(2) + ";";
+ }
+ else {
+ fillSnippet = "\n vec3 fill = vec3(" + fillValue.join(',') + ");\n float outputValue = fill[coords[3]];";
+ }
+ this.userCode = "\n uniform vec4 params;\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - params[0]) * params[3] -\n (float(y) - params[1]) * params[2];\n float coordYFloat = (float(x) - params[0]) * params[2] +\n (float(y) - params[1]) * params[3];\n int coordX = int(round(coordXFloat + params[0]));\n int coordY = int(round(coordYFloat + params[1]));\n " + fillSnippet + "\n if(coordX >= 0 && coordX < " + imageWidth + " && coordY >= 0 && coordY < " + imageHeight + ") {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n ";
+ }
+ RotateProgram.prototype.getCustomSetupFunc = function (centerX, centerY, sinFactor, cosFactor) {
+ var _this = this;
+ return function (gpgpu, webGLProgram) {
+ if (_this.paramsLoc == null) {
+ _this.paramsLoc =
+ gpgpu.getUniformLocationNoThrow(webGLProgram, 'params');
+ }
+ gpgpu.gl.uniform4f(_this.paramsLoc, centerX, centerY, sinFactor, cosFactor);
+ };
+ };
+ return RotateProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var rotateWithOffsetConfig = {
+ kernelName: tf.RotateWithOffset,
+ backendName: 'webgl',
+ kernelFunc: function (_a) {
+ var inputs = _a.inputs, attrs = _a.attrs, backend = _a.backend;
+ var image = inputs.image;
+ var _b = attrs, radians = _b.radians, fillValue = _b.fillValue, center = _b.center;
+ var webglBackend = backend;
+ var program = new RotateProgram(image.shape, fillValue);
+ var _c = tf.backend_util.getImageCenter(center, image.shape[1], image.shape[2]), centerX = _c[0], centerY = _c[1];
+ var customSetup = program.getCustomSetupFunc(centerX, centerY, Math.sin(radians), Math.cos(radians));
+ var output = webglBackend.runWebGLProgram(program, [image], image.dtype, customSetup);
+ return output;
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ROUND = "\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";
+ var round = unaryKernelFunc({ opSnippet: ROUND });
+ var roundConfig = {
+ kernelName: tf.Round,
+ backendName: 'webgl',
+ kernelFunc: round,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var RSQRT = "return inversesqrt(x);";
+ var rsqrt = unaryKernelFunc({ opSnippet: RSQRT, cpuKernelImpl: rsqrtImplCPU });
+ var rsqrtConfig = {
+ kernelName: tf.Rsqrt,
+ backendName: 'webgl',
+ kernelFunc: rsqrt
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ScatterProgram = /** @class */ (function () {
+ function ScatterProgram(updateSize, sliceDim, indicesRank, updatesRank, strides, shape, summingDupeIndex) {
+ this.variableNames = ['updates', 'indices', 'defaultValue'];
+ this.outputShape = shape;
+ var stridesType = getCoordsDataType(strides.length);
+ var dtype = getCoordsDataType(shape.length);
+ var indicesString = '';
+ if (indicesRank === 1) {
+ indicesString = 'i';
+ }
+ else if (indicesRank === 2) {
+ indicesString = 'i, j';
+ }
+ var indicesSnippet = "getIndices(" + indicesString + ")";
+ var updatesString = '';
+ if (updatesRank === 1) {
+ updatesString = 'i';
+ }
+ else if (updatesRank === 2) {
+ updatesString = 'i, coords[1]';
+ }
+ var updatesSnippet = "getUpdates(" + updatesString + ")";
+ var strideString = sliceDim > 1 ? 'strides[j]' : 'strides';
+ this.userCode = "\n " + stridesType + " strides = " + stridesType + "(" + strides + ");\n\n void main() {\n " + dtype + " coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < " + updateSize + "; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < " + sliceDim + "; j++) {\n int index = round(" + indicesSnippet + ");\n flattenedIndex += index * " + strideString + ";\n }\n if (flattenedIndex == coords[0]) {\n sum += " + updatesSnippet + ";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n ";
+ }
+ return ScatterProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function scatterNd(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var indices = inputs.indices, updates = inputs.updates;
+ var shape = attrs.shape;
+ var _a = tf.backend_util.calculateShapes(updates, indices, shape), sliceRank = _a.sliceRank, numUpdates = _a.numUpdates, sliceSize = _a.sliceSize, strides = _a.strides, outputSize = _a.outputSize;
+ var flattenShape = [outputSize / sliceSize, sliceSize];
+ if (outputSize === 0) {
+ return backend.makeTensorInfo(shape, indices.dtype);
+ }
+ var flattenIndices = reshape({ inputs: { x: indices }, backend: backend, attrs: { shape: [numUpdates, sliceRank] } });
+ var flattenX = reshape({ inputs: { x: updates }, backend: backend, attrs: { shape: [numUpdates, sliceSize] } });
+ var defaultValue = backend.makeTensorInfo([], 'float32', new Float32Array([0])); // scalar(0)
+ var program = new ScatterProgram(numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length, strides, flattenShape);
+ var res = backend.runWebGLProgram(program, [flattenX, flattenIndices, defaultValue], flattenX.dtype);
+ var reshaped = reshape({ inputs: { x: res }, backend: backend, attrs: { shape: shape } });
+ backend.disposeIntermediateTensorInfo(flattenIndices);
+ backend.disposeIntermediateTensorInfo(flattenX);
+ backend.disposeIntermediateTensorInfo(res);
+ backend.disposeIntermediateTensorInfo(defaultValue);
+ return reshaped;
+ }
+ var scatterNdConfig = {
+ kernelName: tf.ScatterNd,
+ backendName: 'webgl',
+ kernelFunc: scatterNd
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SelectProgram = /** @class */ (function () {
+ function SelectProgram(cRank, shape, rank) {
+ this.variableNames = ['c', 'a', 'b'];
+ this.outputShape = shape;
+ var cCoords;
+ var abCoords;
+ if (rank > 4) {
+ throw Error("Where for rank " + rank + " is not yet supported");
+ }
+ if (rank === 1) {
+ abCoords = "resRC";
+ cCoords = "resRC";
+ }
+ else {
+ var currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w'];
+ var cCoordVars = [];
+ var abCoordVars = [];
+ for (var i = 0; i < shape.length; i++) {
+ abCoordVars.push("" + currentCoords[i]);
+ if (i < cRank) {
+ cCoordVars.push("" + currentCoords[i]);
+ }
+ }
+ cCoords = cCoordVars.join();
+ abCoords = abCoordVars.join();
+ }
+ var dtype = getCoordsDataType(rank);
+ this.userCode = "\n void main() {\n " + dtype + " resRC = getOutputCoords();\n float cVal = getC(" + cCoords + ");\n if (cVal >= 1.0) {\n setOutput(getA(" + abCoords + "));\n } else {\n setOutput(getB(" + abCoords + "));\n }\n }\n ";
+ }
+ return SelectProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function select(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var condition = inputs.condition, t = inputs.t, e = inputs.e;
+ var program = new SelectProgram(condition.shape.length, t.shape, t.shape.length);
+ return backend.runWebGLProgram(program, [condition, t, e], tf.upcastType(t.dtype, e.dtype));
+ }
+ var selectConfig = {
+ kernelName: tf.Select,
+ backendName: 'webgl',
+ kernelFunc: select
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SELU = "\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = " + tf.backend_util.SELU_SCALEALPHA + ";\n float scale = " + tf.backend_util.SELU_SCALE + ";\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";
+ var selu = unaryKernelFunc({ opSnippet: SELU });
+ var seluConfig = {
+ kernelName: tf.Selu,
+ backendName: 'webgl',
+ kernelFunc: selu,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SIGMOID$2 = "return 1.0 / (1.0 + exp(-1.0 * x));";
+ var sigmoid = unaryKernelFunc({ opSnippet: SIGMOID$2 });
+ var sigmoidConfig = {
+ kernelName: tf.Sigmoid,
+ backendName: 'webgl',
+ kernelFunc: sigmoid,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // Sign does not propagate NANs.
+ var SIGN = "\n if (isnan(x)) { return 0.0; }\n return sign(x);\n";
+ var sign = unaryKernelFunc({ opSnippet: SIGN });
+ var signConfig = {
+ kernelName: tf.Sign,
+ backendName: 'webgl',
+ kernelFunc: sign,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SIN = CHECK_NAN_SNIPPET_UNARY + "\n return sin(x);\n";
+ var sin = unaryKernelFunc({ opSnippet: SIN });
+ var sinConfig = {
+ kernelName: tf.Sin,
+ backendName: 'webgl',
+ kernelFunc: sin,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SINH = "\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n";
+ var sinh = unaryKernelFunc({ opSnippet: SINH });
+ var sinhConfig = {
+ kernelName: tf.Sinh,
+ backendName: 'webgl',
+ kernelFunc: sinh,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SOFTPLUS = "\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";
+ var softplus = unaryKernelFunc({ opSnippet: SOFTPLUS });
+ var softplusConfig = {
+ kernelName: tf.Softplus,
+ backendName: 'webgl',
+ kernelFunc: softplus,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var spaceToBatchND = function (args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var blockShape = attrs.blockShape, paddings = attrs.paddings;
+ tf.util.assert(x.shape.length <= 4, function () { return 'spaceToBatchND for rank > 4 with a WebGL backend not ' +
+ 'implemented yet'; });
+ var prod = blockShape.reduce(function (a, b) { return a * b; });
+ var completePaddings = [[0, 0]];
+ completePaddings.push.apply(completePaddings, paddings);
+ for (var i = 1 + blockShape.length; i < x.shape.length; ++i) {
+ completePaddings.push([0, 0]);
+ }
+ var toDispose = [];
+ var paddedX = padV2({
+ inputs: { x: x },
+ backend: backend,
+ attrs: { paddings: completePaddings, constantValue: 0 }
+ });
+ var reshapedPaddedShape = tf.backend_util.getReshaped(paddedX.shape, blockShape, prod, false);
+ var permutedReshapedPaddedPermutation = tf.backend_util.getPermuted(reshapedPaddedShape.length, blockShape.length, false);
+ var flattenShape = tf.backend_util.getReshapedPermuted(paddedX.shape, blockShape, prod, false);
+ var reshapedPaddedX = reshape({ inputs: { x: paddedX }, backend: backend, attrs: { shape: reshapedPaddedShape } });
+ var paddedXT = transpose({
+ inputs: { x: reshapedPaddedX },
+ backend: backend,
+ attrs: { perm: permutedReshapedPaddedPermutation }
+ });
+ var result = reshape({ inputs: { x: paddedXT }, backend: backend, attrs: { shape: flattenShape } });
+ toDispose.push(paddedX);
+ toDispose.push(reshapedPaddedX);
+ toDispose.push(paddedXT);
+ toDispose.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return result;
+ };
+ var spaceToBatchNDConfig = {
+ kernelName: tf.SpaceToBatchND,
+ backendName: 'webgl',
+ kernelFunc: spaceToBatchND
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sparseFillEmptyRows(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var indices = inputs.indices, values = inputs.values, denseShape = inputs.denseShape, defaultValue = inputs.defaultValue;
+ if (denseShape.shape.length !== 1) {
+ throw new Error("Dense shape must be a vector, saw:\n " + denseShape.shape);
+ }
+ if (indices.shape.length !== 2) {
+ throw new Error("Indices must be a matrix, saw:\n " + indices.shape);
+ }
+ if (values.shape.length !== 1) {
+ throw new Error("Values must be a vector, saw:\n " + values.shape);
+ }
+ if (defaultValue.shape.length !== 0) {
+ throw new Error("Default value must be a scalar, saw:\n " + defaultValue.shape);
+ }
+ var $indices = backend.readSync(indices.dataId);
+ var $values = backend.readSync(values.dataId);
+ var $denseShape = backend.readSync(denseShape.dataId);
+ var $defaultValue = backend.readSync(defaultValue.dataId)[0];
+ var _a = sparseFillEmptyRowsImplCPU($indices, indices.shape, indices.dtype, $values, values.dtype, $denseShape, $defaultValue), outputIndices = _a[0], outputIndicesShape = _a[1], outputValues = _a[2], emptyRowIndicator = _a[3], reverseIndexMap = _a[4];
+ return [
+ backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),
+ backend.makeTensorInfo([outputIndicesShape[0]], values.dtype, outputValues),
+ backend.makeTensorInfo([emptyRowIndicator.length], 'bool', new Uint8Array(emptyRowIndicator.map(function (value) { return Number(value); }))),
+ backend.makeTensorInfo([reverseIndexMap.length], indices.dtype, new Int32Array(reverseIndexMap)),
+ ];
+ }
+ var sparseFillEmptyRowsConfig = {
+ kernelName: tf.SparseFillEmptyRows,
+ backendName: 'webgl',
+ kernelFunc: sparseFillEmptyRows,
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sparseReshape(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var inputIndices = inputs.inputIndices, inputShape = inputs.inputShape, newShape = inputs.newShape;
+ if (inputIndices.shape.length !== 2) {
+ throw new Error("Input indices should be a matrix but received shape " + inputIndices.shape);
+ }
+ if (inputShape.shape.length !== 1) {
+ throw new Error("Input shape should be a vector but received shape " + inputShape.shape);
+ }
+ if (newShape.shape.length !== 1) {
+ throw new Error("Target shape should be a vector but received shape " + newShape.shape);
+ }
+ var $inputShape = Array.from(backend.readSync(inputShape.dataId));
+ var $inputIndices = backend.readSync(inputIndices.dataId);
+ var targetShape = Array.from(backend.readSync(newShape.dataId));
+ var _a = sparseReshapeImplCPU($inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape, targetShape), newIndices = _a[0], indicesShape = _a[1], outputShape = _a[2];
+ return [
+ backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),
+ backend.makeTensorInfo([outputShape.length], newShape.dtype, new Int32Array(outputShape)),
+ ];
+ }
+ var sparseReshapeConfig = {
+ kernelName: tf.SparseReshape,
+ backendName: 'webgl',
+ kernelFunc: sparseReshape,
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sparseSegmentMean(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var data = inputs.data, indices = inputs.indices, segmentIds = inputs.segmentIds;
+ if (data.shape.length < 1) {
+ throw new Error("Data should be at least 1 dimensional but received scalar");
+ }
+ if (indices.shape.length !== 1) {
+ throw new Error("Indices should be a vector but received shape\n " + indices.shape);
+ }
+ if (segmentIds.shape.length !== 1) {
+ throw new Error("Segment ids should be a vector but received shape\n " + segmentIds.shape);
+ }
+ var $data = backend.readSync(data.dataId);
+ var $indices = backend.readSync(indices.dataId);
+ var $segmentIds = backend.readSync(segmentIds.dataId);
+ var _a = sparseSegmentReductionImplCPU($data, data.shape, data.dtype, $indices, $segmentIds, true), outputData = _a[0], outputDataShape = _a[1];
+ return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
+ }
+ var sparseSegmentMeanConfig = {
+ kernelName: tf.SparseSegmentMean,
+ backendName: 'webgl',
+ kernelFunc: sparseSegmentMean,
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sparseSegmentSum(args) {
+ var inputs = args.inputs, backend = args.backend;
+ var data = inputs.data, indices = inputs.indices, segmentIds = inputs.segmentIds;
+ if (data.shape.length < 1) {
+ throw new Error("Data should be at least 1 dimensional but received scalar");
+ }
+ if (indices.shape.length !== 1) {
+ throw new Error("Indices should be a vector but received shape\n " + indices.shape);
+ }
+ if (segmentIds.shape.length !== 1) {
+ throw new Error("Segment ids should be a vector but received shape\n " + segmentIds.shape);
+ }
+ var $data = backend.readSync(data.dataId);
+ var $indices = backend.readSync(indices.dataId);
+ var $segmentIds = backend.readSync(segmentIds.dataId);
+ var _a = sparseSegmentReductionImplCPU($data, data.shape, data.dtype, $indices, $segmentIds), outputData = _a[0], outputDataShape = _a[1];
+ return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);
+ }
+ var sparseSegmentSumConfig = {
+ kernelName: tf.SparseSegmentSum,
+ backendName: 'webgl',
+ kernelFunc: sparseSegmentSum,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function sparseToDense(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var sparseIndices = inputs.sparseIndices, sparseValues = inputs.sparseValues, defaultValue = inputs.defaultValue;
+ var outputShape = attrs.outputShape;
+ var _a = tf.backend_util.calculateShapes(sparseValues, sparseIndices, outputShape), sliceRank = _a.sliceRank, numUpdates = _a.numUpdates, strides = _a.strides, outputSize = _a.outputSize;
+ var sumDupeIndices = false;
+ var program = new ScatterProgram(numUpdates, sliceRank, sparseIndices.shape.length, sparseValues.shape.length, strides, [outputSize, 1], sumDupeIndices);
+ var res = backend.runWebGLProgram(program, [sparseValues, sparseIndices, defaultValue], sparseValues.dtype);
+ var reshaped = reshape({ inputs: { x: res }, backend: backend, attrs: { shape: outputShape } });
+ backend.disposeIntermediateTensorInfo(res);
+ return reshaped;
+ }
+ var sparseToDenseConfig = {
+ kernelName: tf.SparseToDense,
+ backendName: 'webgl',
+ kernelFunc: sparseToDense
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function splitV(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var numOrSizeSplits = attrs.numOrSizeSplits, axis = attrs.axis;
+ var $axis = tf.util.parseAxisParam(axis, x.shape)[0];
+ var splitSizes = tf.backend_util.prepareSplitSize(x, numOrSizeSplits, $axis);
+ var xRank = x.shape.length;
+ var begin = new Array(xRank).fill(0);
+ var size = x.shape.slice();
+ return splitSizes.map(function (s) {
+ var sliceSize = size.slice();
+ sliceSize[$axis] = s;
+ var sliceT = slice({ inputs: { x: x }, backend: backend, attrs: { begin: begin, size: sliceSize } });
+ begin[$axis] += s;
+ return sliceT;
+ });
+ }
+ var splitVConfig = {
+ kernelName: tf.SplitV,
+ backendName: 'webgl',
+ kernelFunc: splitV
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SQRT = "return sqrt(x);";
+ var sqrt = unaryKernelFunc({ opSnippet: SQRT });
+ var sqrtConfig = {
+ kernelName: tf.Sqrt,
+ backendName: 'webgl',
+ kernelFunc: sqrt
+ };
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SQUARE = "return x * x;";
+ var square = unaryKernelFunc({ opSnippet: SQUARE });
+ var squareConfig = {
+ kernelName: tf.Square,
+ backendName: 'webgl',
+ kernelFunc: square,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SQUARED_DIFFERENCE = 'return (a - b) * (a - b);';
+ var squaredDifference = binaryKernelFunc({ opSnippet: SQUARED_DIFFERENCE, packedOpSnippet: SQUARED_DIFFERENCE });
+ var squaredDifferenceConfig = {
+ kernelName: tf.SquaredDifference,
+ backendName: 'webgl',
+ kernelFunc: squaredDifference,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function step(_a) {
+ var inputs = _a.inputs, attrs = _a.attrs, backend = _a.backend;
+ var x = inputs.x;
+ var opSnippet = CHECK_NAN_SNIPPET + ("\n return x > 0.0 ? 1.0 : float(" + attrs.alpha + ");\n ");
+ var program = new UnaryOpProgram(x.shape, opSnippet);
+ return backend.runWebGLProgram(program, [x], x.dtype);
+ }
+ var stepConfig = {
+ kernelName: tf.Step,
+ backendName: 'webgl',
+ kernelFunc: step,
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var StridedSliceProgram = /** @class */ (function () {
+ function StridedSliceProgram(begin, strides, size) {
+ this.variableNames = ['x'];
+ this.outputShape = size;
+ var rank = size.length;
+ var inputDtype = getCoordsDataType(size.length);
+ var dtype = getCoordsDataType(size.length);
+ var newCoords = '';
+ if (rank === 1) {
+ newCoords = 'coords * strides + begin';
+ }
+ else {
+ var outputAxis_1 = 0;
+ newCoords =
+ size.map(function (_, i) {
+ outputAxis_1++;
+ return size.length === 1 ?
+ "coords * strides[" + i + "] + begin[" + i + "]" :
+ "coords[" + (outputAxis_1 - 1) + "] * strides[" + i + "] + begin[" + i + "]";
+ })
+ .join(',');
+ }
+ this.userCode = "\n " + inputDtype + " begin = " + inputDtype + "(" + begin + ");\n " + inputDtype + " strides = " + inputDtype + "(" + strides + ");\n\n void main() {\n " + dtype + " coords = getOutputCoords();\n setOutput(getX(" + newCoords + "));\n }\n ";
+ }
+ return StridedSliceProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function stridedSlice(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var begin = attrs.begin, end = attrs.end, strides = attrs.strides, beginMask = attrs.beginMask, endMask = attrs.endMask, ellipsisMask = attrs.ellipsisMask, newAxisMask = attrs.newAxisMask, shrinkAxisMask = attrs.shrinkAxisMask;
+ var _a = tf.slice_util.sliceInfo(x.shape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask), nonStrided = _a.nonStrided, $begin = _a.$begin, $strides = _a.$strides, size = _a.size, newShape = _a.newShape, outShape = _a.outShape;
+ var $x = reshape({ inputs: { x: x }, backend: backend, attrs: { shape: newShape } });
+ var result;
+ if (nonStrided) {
+ var sliced = slice({ inputs: { x: $x }, backend: backend, attrs: { begin: $begin, size: size } });
+ result = reshape({ inputs: { x: sliced }, backend: backend, attrs: { shape: outShape } });
+ backend.disposeIntermediateTensorInfo(sliced);
+ }
+ else if (outShape.some(function (axis) { return axis === 0; })) {
+ result = backend.makeTensorInfo(outShape, x.dtype, []);
+ }
+ else {
+ var shouldExecuteOnCPU = backend.shouldExecuteOnCPU([$x]);
+ if (shouldExecuteOnCPU) {
+ var xTexData = backend.texData.get($x.dataId);
+ var values = xTexData.values;
+ var xBuf = tf.buffer($x.shape, $x.dtype, values);
+ var resultValues = stridedSliceImplCPU(outShape, xBuf, $strides, $begin);
+ result = backend.makeTensorInfo(outShape, $x.dtype, resultValues.values);
+ }
+ else {
+ var program = new StridedSliceProgram($begin, $strides, outShape);
+ result = backend.runWebGLProgram(program, [$x], $x.dtype);
+ }
+ }
+ var resultReshaped = reshape({ inputs: { x: result }, backend: backend, attrs: { shape: outShape } });
+ backend.disposeIntermediateTensorInfo($x);
+ backend.disposeIntermediateTensorInfo(result);
+ return resultReshaped;
+ }
+ var stridedSliceConfig = {
+ kernelName: tf.StridedSlice,
+ backendName: 'webgl',
+ kernelFunc: stridedSlice
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function stringNGrams(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var separator = attrs.separator, nGramWidths = attrs.nGramWidths, leftPad = attrs.leftPad, rightPad = attrs.rightPad, padWidth = attrs.padWidth, preserveShortSequences = attrs.preserveShortSequences;
+ var data = inputs.data, dataSplits = inputs.dataSplits;
+ var $data = backend.readSync(data.dataId);
+ var $dataSplits = backend.readSync(dataSplits.dataId);
+ var _a = stringNGramsImplCPU($data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences), nGrams = _a[0], nGramsSplits = _a[1];
+ return [
+ backend.makeTensorInfo([nGrams.length], 'string', nGrams),
+ backend.makeTensorInfo(dataSplits.shape, 'int32', nGramsSplits),
+ ];
+ }
+ var stringNGramsConfig = {
+ kernelName: tf.StringNGrams,
+ backendName: 'webgl',
+ kernelFunc: stringNGrams,
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function stringSplit(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var skipEmpty = attrs.skipEmpty;
+ var input = inputs.input, delimiter = inputs.delimiter;
+ if (input.dtype !== 'string') {
+ throw new Error('Input must be of datatype string');
+ }
+ if (input.shape.length !== 1) {
+ throw new Error("Input must be a vector, got shape: " + input.shape);
+ }
+ if (delimiter.shape.length !== 0) {
+ throw new Error("Delimiter must be a scalar, got shape: " + delimiter.shape);
+ }
+ var $input = backend.readSync(input.dataId);
+ var $delimiter = backend.readSync(delimiter.dataId)[0];
+ var _a = stringSplitImplCPU($input, $delimiter, skipEmpty), indices = _a[0], values = _a[1], shape = _a[2];
+ var outputSize = values.length;
+ return [
+ backend.makeTensorInfo([outputSize, 2], 'int32', indices),
+ backend.makeTensorInfo([outputSize], 'string', values),
+ backend.makeTensorInfo([2], 'int32', new Int32Array(shape))
+ ];
+ }
+ var stringSplitConfig = {
+ kernelName: tf.StringSplit,
+ backendName: 'webgl',
+ kernelFunc: stringSplit,
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function stringToHashBucketFast(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var numBuckets = attrs.numBuckets;
+ var input = inputs.input;
+ if (input.dtype !== 'string') {
+ throw new Error('Input must be of datatype string');
+ }
+ if (numBuckets <= 0) {
+ throw new Error("Number of buckets must be at least 1");
+ }
+ var $input = backend.readSync(input.dataId);
+ var output = stringToHashBucketFastImplCPU($input, numBuckets);
+ return backend.makeTensorInfo(input.shape, 'int32', output);
+ }
+ var stringToHashBucketFastConfig = {
+ kernelName: tf.StringToHashBucketFast,
+ backendName: 'webgl',
+ kernelFunc: stringToHashBucketFast,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var TAN = "return tan(x);";
+ var tan = unaryKernelFunc({ opSnippet: TAN });
+ var tanConfig = {
+ kernelName: tf.Tan,
+ backendName: 'webgl',
+ kernelFunc: tan,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var TANH = "\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n";
+ var tanh = unaryKernelFunc({ opSnippet: TANH });
+ var tanhConfig = {
+ kernelName: tf.Tanh,
+ backendName: 'webgl',
+ kernelFunc: tanh,
+ };
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var TileProgram = /** @class */ (function () {
+ function TileProgram(aShape, reps) {
+ this.variableNames = ['A'];
+ var outputShape = new Array(aShape.length);
+ for (var i = 0; i < outputShape.length; i++) {
+ outputShape[i] = aShape[i] * reps[i];
+ }
+ this.outputShape = outputShape;
+ this.rank = outputShape.length;
+ var dtype = getCoordsDataType(this.rank);
+ var sourceCoords = getSourceCoords$2(aShape);
+ this.userCode = "\n void main() {\n " + dtype + " resRC = getOutputCoords();\n setOutput(getA(" + sourceCoords + "));\n }\n ";
+ }
+ return TileProgram;
+ }());
+ function getSourceCoords$2(aShape) {
+ var rank = aShape.length;
+ if (rank > 5) {
+ throw Error("Tile for rank " + rank + " is not yet supported");
+ }
+ if (rank === 1) {
+ return "imod(resRC, " + aShape[0] + ")";
+ }
+ var currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u'];
+ var sourceCoords = [];
+ for (var i = 0; i < aShape.length; i++) {
+ sourceCoords.push("imod(" + currentCoords[i] + ", " + aShape[i] + ")");
+ }
+ return sourceCoords.join();
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function tile(params) {
+ var inputs = params.inputs, backend = params.backend, attrs = params.attrs;
+ var x = inputs.x;
+ var reps = attrs.reps;
+ // tile gpu program cannot handle rank > 5 case.
+ if (x.dtype === 'string' || x.shape.length > 5) {
+ // Even thought string tensor is always on CPU, just to be consistent on how
+ // to access tensor data.
+ var data = backend.readSync(x.dataId);
+ var value = x.dtype === 'string' ?
+ data.map(function (d) { return tf.util.decodeString(d); }) :
+ data;
+ var buf = tf.buffer(x.shape, x.dtype, value);
+ var outBuf = tileImplCPU(buf, reps);
+ return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);
+ }
+ var program = new TileProgram(x.shape, reps);
+ var output = backend.runWebGLProgram(program, [x], x.dtype);
+ return output;
+ }
+ var tileConfig = {
+ kernelName: tf.Tile,
+ backendName: 'webgl',
+ kernelFunc: tile,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function topK(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x;
+ var k = attrs.k, sorted = attrs.sorted;
+ var xVals = backend.readSync(x.dataId);
+ var _a = topKImplCPU(xVals, x.shape, x.dtype, k), allTopKVals = _a[0], allTopKIndices = _a[1];
+ return [
+ backend.makeTensorInfo(allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),
+ backend.makeTensorInfo(allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)
+ ];
+ }
+ var topKConfig = {
+ kernelName: tf.TopK,
+ backendName: 'webgl',
+ kernelFunc: topK
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var TransformProgram = /** @class */ (function () {
+ function TransformProgram(imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape) {
+ this.variableNames = ['Image', 'Transforms'];
+ this.outputShape = outShape;
+ var interpolationModeId = interpolation === 'nearest' ? 1 : 2;
+ var fillModeId;
+ switch (fillMode) {
+ case 'constant':
+ fillModeId = 1;
+ break;
+ case 'reflect':
+ fillModeId = 2;
+ break;
+ case 'wrap':
+ fillModeId = 3;
+ break;
+ case 'nearest':
+ fillModeId = 4;
+ break;
+ default:
+ fillModeId = 1;
+ break;
+ }
+ this.userCode = "\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(" + fillModeId + " == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n inCoord -= sz2 * float(int(float(inCoord / sz2)));\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1.0;\n }\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (" + fillModeId + " == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord -= len * float(int(float(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (" + fillModeId + " == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n } else {\n return outCoord;\n }\n }\n\n float readWithFillValue(int batch, int coordY, int coordX,\n int channel) {\n float outputValue;\n if (0 <= coordY && coordY < " + imageHeight + " && 0 <= coordX && coordX < " + imageWidth + ") {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(" + fillValue + ");\n }\n return outputValue;\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n float outputValue;\n int batch = coords[0];\n int x = coords[2];\n int y = coords[1];\n int channel = coords[3];\n float xf = float(x);\n float yf = float(y);\n float a1 = getTransforms(batch, 0);\n float a2 = getTransforms(batch, 1);\n float a3 = getTransforms(batch, 2);\n float b1 = getTransforms(batch, 3);\n float b2 = getTransforms(batch, 4);\n float b3 = getTransforms(batch, 5);\n float c1 = getTransforms(batch, 6);\n float c2 = getTransforms(batch, 7);\n float projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = float(" + fillValue + ");\n } else {\n float inX = (a1 * xf + a2 * yf + a3) / projection;\n float inY = (b1 * xf + b2 * yf + b3) / projection;\n float mapX = mapCoord(inX, float(" + imageWidth + "));\n float mapY = mapCoord(inY, float(" + imageHeight + "));\n\n if (" + interpolationModeId + " == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n ";
+ }
+ return TransformProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function transform(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var image = inputs.image, transforms = inputs.transforms;
+ var interpolation = attrs.interpolation, fillMode = attrs.fillMode, fillValue = attrs.fillValue, outputShape = attrs.outputShape;
+ var _a = image.shape, batch = _a[0], imageHeight = _a[1], imageWidth = _a[2], numChannels = _a[3];
+ var _b = outputShape != null ? outputShape : [imageHeight, imageWidth], outHeight = _b[0], outWidth = _b[1];
+ var outShape = [batch, outHeight, outWidth,
+ numChannels];
+ var program = new TransformProgram(imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape);
+ return backend.runWebGLProgram(program, [image, transforms], 'float32');
+ }
+ var transformConfig = {
+ kernelName: tf.Transform,
+ backendName: 'webgl',
+ kernelFunc: transform
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function unique(args) {
+ var inputs = args.inputs, attrs = args.attrs, backend = args.backend;
+ var axis = attrs.axis;
+ var x = inputs.x;
+ assertNotComplex(x, 'unique');
+ // For now, always forward calculation to the CPU backend.
+ console.warn('WARNING: ', 'UI might be locked temporarily as data is being downloaded');
+ var values = backend.readSync(x.dataId);
+ var _a = uniqueImplCPU(values, axis, x.shape, x.dtype), outputValues = _a.outputValues, outputShape = _a.outputShape, indices = _a.indices;
+ return [
+ backend.makeTensorInfo(outputShape, x.dtype, outputValues),
+ backend.makeTensorInfo([indices.length], 'int32', indices),
+ ];
+ }
+ var uniqueConfig = {
+ kernelName: tf.Unique,
+ backendName: 'webgl',
+ kernelFunc: unique,
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function unpack(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var value = inputs.value;
+ var axis = attrs.axis;
+ if (axis < 0) {
+ axis += value.shape.length;
+ }
+ var x = value;
+ var xRank = x.shape.length;
+ var num = value.shape[axis];
+ var outShape = new Array(xRank - 1);
+ var outIndex = 0;
+ for (var i = 0; i < xRank; i++) {
+ if (i !== axis) {
+ outShape[outIndex++] = x.shape[i];
+ }
+ }
+ var toDispose = [];
+ var begin = new Array(xRank).fill(0);
+ var size = x.shape.slice();
+ size[axis] = 1;
+ var res = new Array(num);
+ for (var i = 0; i < res.length; i++) {
+ begin[axis] = i;
+ var sliced = slice({ inputs: { x: x }, backend: backend, attrs: { begin: begin, size: size } });
+ var reshaped = reshape({ inputs: { x: sliced }, backend: backend, attrs: { shape: outShape } });
+ res[i] = reshaped;
+ toDispose.push(sliced);
+ }
+ toDispose.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return res;
+ }
+ var unpackConfig = {
+ kernelName: tf.Unpack,
+ backendName: 'webgl',
+ kernelFunc: unpack
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var SegmentOpProgram = /** @class */ (function () {
+ function SegmentOpProgram(segOpInfo, segOpType) {
+ this.variableNames = ['x', 'segmentIds'];
+ var windowSize = segOpInfo.windowSize;
+ var batchSize = segOpInfo.batchSize;
+ var inSize = segOpInfo.inSize;
+ var numSegments = segOpInfo.numSegments;
+ var outSize = numSegments * Math.ceil(inSize / windowSize);
+ this.outputShape = [batchSize, outSize];
+ var initializationValue = '0.0';
+ var returnValue = "sumValue";
+ var windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
+ var windowSizeVec4Remainder = windowSize % 4;
+ var updateSnippet = "\n sumValue += dot(values, segFilter);\n ";
+ var checkValueOutOfBounds = '';
+ if (inSize % windowSize > 0) {
+ checkValueOutOfBounds = "\n if (inIdx < 0 || inIdx >= " + inSize + ") {\n return initializationValue;\n }\n ";
+ }
+ var checkSegmentIdOutOfBounds = '';
+ if (inSize % windowSize > 0) {
+ checkSegmentIdOutOfBounds = "\n if (inIdx < 0 || inIdx >= " + inSize + ") {\n return -1.0;\n }\n ";
+ }
+ this.userCode = "\n const float initializationValue = " + initializationValue + ";\n\n float getValue(int batch, int inIdx) {\n " + checkValueOutOfBounds + "\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n " + checkSegmentIdOutOfBounds + "\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 " + numSegments + ")) * float(" + windowSize + "));\n int currentSeg = int(mod(float(outIdx), float(" + numSegments + ")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < " + windowSizeNearestVec4 + "; 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 " + updateSnippet + "\n }\n\n int inIdx = inOffset + " + windowSizeNearestVec4 + ";\n if (" + (windowSizeVec4Remainder === 1) + ") {\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 " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 2) + ") {\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 " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 3) + ") {\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 " + updateSnippet + "\n }\n setOutput(" + returnValue + ");\n }\n ";
+ }
+ return SegmentOpProgram;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function unsortedSegmentSum(args) {
+ var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
+ var x = inputs.x, segmentIds = inputs.segmentIds;
+ var numSegments = attrs.numSegments;
+ var xRank = x.shape.length;
+ var toDispose = [];
+ var axis = 0;
+ var permutation = tf.backend_util.getAxesPermutation([axis], xRank);
+ var permutedX = x;
+ if (permutation != null) {
+ permutedX = transpose({ inputs: { x: x }, backend: backend, attrs: { perm: permutation } });
+ toDispose.push(permutedX);
+ axis = tf.backend_util.getInnerMostAxes(1, xRank)[0];
+ }
+ var outShape = tf.backend_util.segment_util.computeOutShape(permutedX.shape, axis, numSegments);
+ var inSize = tf.util.sizeFromShape([permutedX.shape[axis]]);
+ var a2D = reshape({ inputs: { x: permutedX }, backend: backend, attrs: { shape: [-1, inSize] } });
+ toDispose.push(a2D);
+ var outputDType = tf.sumOutType(x.dtype);
+ var segOpCompute = function (x, segOpType, segmentIds, dtype, numSegments) {
+ var batchSize = x.shape[0];
+ var inSize = x.shape[1];
+ var windowSize = tf.backend_util.segment_util.segOpComputeOptimalWindowSize(inSize, numSegments);
+ var segOpInfo = { windowSize: windowSize, inSize: inSize, batchSize: batchSize, numSegments: numSegments };
+ var program = new SegmentOpProgram(segOpInfo, segOpType);
+ var output = backend.compileAndRun(program, [x, segmentIds], dtype);
+ toDispose.push(output);
+ // No need to run another GPGPU program.
+ if (output.shape[1] === numSegments) {
+ return output;
+ }
+ var rangeInfo = range({
+ backend: backend,
+ attrs: { start: 0, stop: numSegments, step: 1, dtype: 'float32' }
+ });
+ var tileInfo = tile({
+ inputs: { x: rangeInfo },
+ backend: backend,
+ attrs: { reps: [inSize / windowSize] }
+ });
+ toDispose.push(rangeInfo);
+ toDispose.push(tileInfo);
+ var result = segOpCompute(output, segOpType, tileInfo, dtype, numSegments);
+ return result;
+ };
+ var segOpResult = segOpCompute(a2D, 'unsortedSegmentSum', segmentIds, outputDType, numSegments);
+ var reshaped = reshape({ inputs: { x: segOpResult }, backend: backend, attrs: { shape: outShape } });
+ var result = reshaped;
+ if (permutation != null) {
+ toDispose.push(reshaped);
+ var perm = tf.backend_util.getUndoAxesPermutation(permutation);
+ result = transpose({ inputs: { x: result }, backend: backend, attrs: { perm: perm } });
+ }
+ toDispose.forEach(function (t) { return backend.disposeIntermediateTensorInfo(t); });
+ return result;
+ }
+ var unsortedSegmentSumConfig = {
+ kernelName: tf.UnsortedSegmentSum,
+ backendName: 'webgl',
+ kernelFunc: unsortedSegmentSum
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // List all kernel configs here
+ var kernelConfigs = [
+ LRNConfig,
+ LRNGradConfig,
+ _fusedMatMulConfig,
+ absConfig,
+ acosConfig,
+ acoshConfig,
+ addConfig,
+ addNConfig,
+ allConfig,
+ anyConfig,
+ argMaxConfig,
+ argMinConfig,
+ asinConfig,
+ asinhConfig,
+ atan2Config,
+ atanConfig,
+ atanhConfig,
+ avgPool3DConfig,
+ avgPoolConfig,
+ avgPoolGrad3DConfig,
+ avgPoolGradConfig,
+ batchMatMulConfig,
+ batchNormConfig,
+ batchToSpaceNDConfig,
+ bincountConfig,
+ castConfig,
+ ceilConfig,
+ clipByValueConfig,
+ complexAbsConfig,
+ complexConfig,
+ concatConfig,
+ conv2DBackpropFilterConfig,
+ conv2DBackpropInputConfig,
+ conv2DConfig,
+ conv3DBackpropFilterV2Config,
+ conv3DBackpropInputConfig,
+ conv3DConfig,
+ cosConfig,
+ coshConfig,
+ cropAndResizeConfig,
+ cumsumConfig,
+ denseBincountConfig,
+ depthToSpaceConfig,
+ depthwiseConv2dNativeBackpropFilterConfig,
+ depthwiseConv2dNativeBackpropInputConfig,
+ depthwiseConv2dNativeConfig,
+ diagConfig,
+ dilation2DConfig,
+ einsumConfig,
+ eluConfig,
+ eluGradConfig,
+ equalConfig,
+ erfConfig,
+ expConfig,
+ expandDimsConfig,
+ expm1Config,
+ fftConfig,
+ fillConfig,
+ flipLeftRightConfig,
+ floorConfig,
+ floorDivConfig,
+ fromPixelsConfig,
+ fusedConv2DConfig,
+ fusedDepthwiseConv2DConfig,
+ gatherNdConfig,
+ gatherV2Config,
+ greaterConfig,
+ greaterEqualConfig,
+ identityConfig,
+ ifftConfig,
+ imagConfig,
+ isFiniteConfig,
+ isInfConfig,
+ isNaNConfig,
+ leakyReluConfig,
+ lessConfig,
+ lessEqualConfig,
+ linSpaceConfig,
+ log1pConfig,
+ logConfig,
+ logicalAndConfig,
+ logicalNotConfig,
+ logicalOrConfig,
+ maxConfig,
+ maxPool3DConfig,
+ maxPoolConfig,
+ maxPoolGrad3DConfig,
+ maxPoolGradConfig,
+ maxPoolWithArgmaxConfig,
+ maximumConfig,
+ meanConfig,
+ minConfig,
+ minimumConfig,
+ mirrorPadConfig,
+ modConfig,
+ multinomialConfig,
+ multiplyConfig,
+ negConfig,
+ nonMaxSuppressionV3Config,
+ nonMaxSuppressionV4Config,
+ nonMaxSuppressionV5Config,
+ notEqualConfig,
+ oneHotConfig,
+ onesLikeConfig,
+ packConfig,
+ padV2Config,
+ powConfig,
+ preluConfig,
+ prodConfig,
+ rangeConfig,
+ realConfig,
+ realDivConfig,
+ reciprocalConfig,
+ relu6Config,
+ reluConfig,
+ reshapeConfig,
+ resizeBilinearConfig,
+ resizeBilinearGradConfig,
+ resizeNearestNeighborConfig,
+ resizeNearestNeighborGradConfig,
+ reverseConfig,
+ rotateWithOffsetConfig,
+ roundConfig,
+ rsqrtConfig,
+ scatterNdConfig,
+ selectConfig,
+ seluConfig,
+ sigmoidConfig,
+ signConfig,
+ sinConfig,
+ sinhConfig,
+ sliceConfig,
+ softmaxConfig,
+ softplusConfig,
+ spaceToBatchNDConfig,
+ sparseFillEmptyRowsConfig,
+ sparseReshapeConfig,
+ sparseSegmentMeanConfig,
+ sparseSegmentSumConfig,
+ sparseToDenseConfig,
+ splitVConfig,
+ sqrtConfig,
+ squareConfig,
+ squaredDifferenceConfig,
+ stepConfig,
+ stridedSliceConfig,
+ stringNGramsConfig,
+ stringSplitConfig,
+ stringToHashBucketFastConfig,
+ subConfig,
+ sumConfig,
+ tanConfig,
+ tanhConfig,
+ tileConfig,
+ topKConfig,
+ transformConfig,
+ transposeConfig,
+ uniqueConfig,
+ unpackConfig,
+ unsortedSegmentSumConfig,
+ zerosLikeConfig
+ ];
+ for (var _i = 0, kernelConfigs_1 = kernelConfigs; _i < kernelConfigs_1.length; _i++) {
+ var kernelConfig = kernelConfigs_1[_i];
+ tf.registerKernel(kernelConfig);
+ }
+
+ exports.GPGPUContext = GPGPUContext;
+ exports.MathBackendWebGL = MathBackendWebGL;
+ exports.forceHalfFloat = forceHalfFloat;
+ exports.gpgpu_util = gpgpu_util;
+ exports.setWebGLContext = setWebGLContext;
+ exports.version_webgl = version;
+ exports.webgl = webgl;
+ exports.webgl_util = webgl_util;
+
+ Object.defineProperty(exports, '__esModule', { value: true });
+
+})));
+//# sourceMappingURL=tf-backend-webgl.js.map
diff --git a/thirdparty/tfjs/tf-backend-webgl.js.map b/thirdparty/tfjs/tf-backend-webgl.js.map
new file mode 100644
index 0000000..7c77dd0
--- /dev/null
+++ b/thirdparty/tfjs/tf-backend-webgl.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"tf-backend-webgl.js","sources":["../src/canvas_util.ts","../src/tex_util.ts","../src/webgl_util.ts","../src/flags_webgl.ts","../src/glsl_version.ts","../src/shader_compiler_util.ts","../src/decode_matrix_gpu.ts","../src/decode_matrix_packed_gpu.ts","../src/encode_float_gpu.ts","../src/encode_float_packed_gpu.ts","../src/encode_matrix_gpu.ts","../src/encode_matrix_packed_gpu.ts","../src/gpgpu_util.ts","../src/gpgpu_context.ts","../src/shader_compiler.ts","../src/gpgpu_math.ts","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Abs.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/utils/binary_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Add.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Bincount_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/utils/unary_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Ceil.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Concat_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Equal.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Exp.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Expm1.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Floor.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/GatherNd_Impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/GatherV2_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Greater.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/GreaterEqual.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Less.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/LessEqual.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/LinSpace_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Log.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Max_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Maximum.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Minimum.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Multiply.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Neg.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/NotEqual.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Transpose_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Prod.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Range_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Rsqrt.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Slice.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/SparseFillEmptyRows_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/SparseReshape_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/SparseSegmentReduction_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/StridedSlice_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/StringNGrams_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/StringSplit_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/StringToHashBucketFast_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Sub.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Tile_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/TopK_impl.js","../node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Unique_impl.js","../src/kernel_utils/shared.ts","../src/packing_util.ts","../src/pack_gpu.ts","../src/reshape_packed_gpu.ts","../src/texture_manager.ts","../src/unaryop_gpu.ts","../src/unaryop_packed_gpu.ts","../src/unpack_gpu.ts","../src/backend_webgl.ts","../src/version.ts","../src/webgl.ts","../src/base.ts","../src/binaryop_gpu.ts","../src/binaryop_packed_gpu.ts","../src/kernels/Identity.ts","../src/kernels/Complex.ts","../src/kernels/LeakyRelu.ts","../src/kernels/Prelu.ts","../src/kernel_utils/kernel_funcs_utils.ts","../src/mulmat_packed_gpu.ts","../src/binaryop_complex_gpu.ts","../src/kernels/Multiply.ts","../src/kernel_utils/reshape.ts","../src/kernels/Reshape.ts","../src/mean_gpu.ts","../src/reduce_gpu.ts","../src/kernel_utils/reduce.ts","../src/transpose_gpu.ts","../src/transpose_packed_gpu.ts","../src/kernels/Transpose_impl.ts","../src/kernels/Sum_impl.ts","../src/kernels/Sum.ts","../src/kernels/Transpose.ts","../src/kernels/BatchMatMul_impl.ts","../src/kernels/_FusedMatMul.ts","../src/kernels/Abs.ts","../src/kernels/Acos.ts","../src/kernels/Acosh.ts","../src/kernels/Add.ts","../src/addn_gpu.ts","../src/addn_packed_gpu.ts","../src/kernels/AddN.ts","../src/kernels/All.ts","../src/kernels/Any.ts","../src/argminmax_gpu.ts","../src/argminmax_packed_gpu.ts","../src/kernel_utils/arg_min_max.ts","../src/kernels/ArgMax.ts","../src/kernels/ArgMin.ts","../src/kernels/Asin.ts","../src/kernels/Asinh.ts","../src/kernels/Atan.ts","../src/kernels/Atan2.ts","../src/kernels/Atanh.ts","../src/pool_gpu.ts","../src/kernels/AvgPool.ts","../src/kernels/AvgPool3D.ts","../src/avg_pool_backprop_gpu.ts","../src/kernels/AvgPool3DGrad.ts","../src/kernels/AvgPoolGrad.ts","../src/kernels/BatchMatMul.ts","../src/batchnorm_gpu.ts","../src/batchnorm_packed_gpu.ts","../src/kernels/BatchNorm.ts","../src/slice_gpu.ts","../src/slice_packed_gpu.ts","../src/kernels/Slice.ts","../src/kernels/BatchToSpaceND.ts","../src/kernels/Bincount.ts","../src/kernels/NotEqual.ts","../src/kernels/Real.ts","../src/kernel_utils/int.ts","../src/kernels/Cast.ts","../src/kernels/Ceil.ts","../src/clip_gpu.ts","../src/clip_packed_gpu.ts","../src/kernels/ClipByValue.ts","../src/complex_abs_gpu.ts","../src/kernels/ComplexAbs.ts","../src/concat_gpu.ts","../src/concat_packed_gpu.ts","../src/kernels/Imag.ts","../src/kernels/Concat_impl.ts","../src/kernels/Concat.ts","../src/conv_gpu.ts","../src/im2col_packed_gpu.ts","../src/kernels/Conv2D_impl.ts","../src/kernels/Conv2D.ts","../src/conv_backprop_gpu.ts","../src/kernels/Conv2DBackpropFilter.ts","../src/kernels/Conv2DBackpropInput.ts","../src/kernels/Conv3D.ts","../src/kernels/Conv3DBackpropFilterV2.ts","../src/kernels/Conv3DBackpropInputV2.ts","../src/kernels/Cos.ts","../src/kernels/Cosh.ts","../src/crop_and_resize_gpu.ts","../src/kernels/CropAndResize.ts","../src/cumsum_gpu.ts","../src/kernels/Cumsum.ts","../src/kernels/DenseBincount.ts","../src/depth_to_space_gpu.ts","../src/kernels/DepthToSpace.ts","../src/conv_gpu_depthwise.ts","../src/conv_packed_gpu_depthwise.ts","../src/kernels/DepthwiseConv2dNative.ts","../src/conv_backprop_gpu_depthwise.ts","../src/kernels/DepthwiseConv2dNativeBackpropFilter.ts","../src/kernels/DepthwiseConv2dNativeBackpropInput.ts","../src/diag_gpu.ts","../src/kernels/Diag.ts","../src/dilation_gpu.ts","../src/kernels/Dilation2D.ts","../src/kernels/Einsum.ts","../src/kernels/Elu.ts","../src/kernels/EluGrad.ts","../src/kernels/Equal.ts","../src/kernels/Erf.ts","../src/kernels/Exp.ts","../src/kernels/ExpandDims.ts","../src/kernels/Expm1.ts","../src/fft_gpu.ts","../src/kernels/FFT_impl.ts","../src/kernels/FFT.ts","../src/fill_gpu.ts","../src/kernels/Fill.ts","../src/flip_left_right_gpu.ts","../src/kernels/FlipLeftRight.ts","../src/kernels/Floor.ts","../src/kernels/FloorDiv.ts","../src/kernels/FromPixels_utils/from_pixels_gpu.ts","../src/kernels/FromPixels_utils/from_pixels_packed_gpu.ts","../src/kernels/FromPixels.ts","../src/kernels/FusedConv2D.ts","../src/kernels/FusedDepthwiseConv2D.ts","../src/gather_nd_gpu.ts","../src/kernels/GatherNd.ts","../src/gather_gpu.ts","../src/kernels/GatherV2.ts","../src/kernels/Greater.ts","../src/kernels/GreaterEqual.ts","../src/kernels/IFFT.ts","../src/kernels/IsFinite.ts","../src/kernels/IsInf.ts","../src/kernels/IsNaN.ts","../src/kernels/Less.ts","../src/kernels/LessEqual.ts","../src/kernels/LinSpace.ts","../src/kernels/Log.ts","../src/kernels/Log1p.ts","../src/kernels/LogicalAnd.ts","../src/kernels/LogicalNot.ts","../src/kernels/LogicalOr.ts","../src/lrn_gpu.ts","../src/lrn_packed_gpu.ts","../src/kernels/LRN.ts","../src/lrn_grad_gpu.ts","../src/kernels/LRNGrad.ts","../src/kernels/Max_impl.ts","../src/kernels/Max.ts","../src/kernels/Maximum.ts","../src/kernels/MaxPool.ts","../src/kernels/MaxPool3D.ts","../src/max_pool_backprop_gpu.ts","../src/kernels/MaxPool3DGrad.ts","../src/kernels/MaxPoolGrad.ts","../src/kernels/MaxPoolWithArgmax_impl.ts","../src/kernels/MaxPoolWithArgmax.ts","../src/kernels/Mean_impl.ts","../src/kernels/Mean.ts","../src/kernels/Min.ts","../src/kernels/Minimum.ts","../src/mirror_pad_gpu.ts","../src/mirror_pad_packed_gpu.ts","../src/kernels/MirrorPad.ts","../src/kernels/Mod.ts","../src/multinomial_gpu.ts","../src/kernels/RealDiv.ts","../src/kernels/Sub.ts","../src/kernels/Softmax.ts","../src/kernels/Multinomial.ts","../src/kernels/Neg.ts","../src/kernels/NonMaxSuppressionV3.ts","../src/kernels/NonMaxSuppressionV4.ts","../src/kernels/NonMaxSuppressionV5.ts","../src/onehot_gpu.ts","../src/kernels/OneHot.ts","../src/kernels/ZerosLike.ts","../src/kernels/OnesLike.ts","../src/kernels/Pack.ts","../src/pad_gpu.ts","../src/pad_packed_gpu.ts","../src/kernels/PadV2.ts","../src/kernels/Pow.ts","../src/kernels/Prod.ts","../src/kernels/Range.ts","../src/kernels/Reciprocal.ts","../src/kernels/Relu.ts","../src/kernels/Relu6.ts","../src/resize_bilinear_gpu.ts","../src/resize_bilinear_packed_gpu.ts","../src/kernels/ResizeBilinear.ts","../src/resize_bilinear_backprop_gpu.ts","../src/kernels/ResizeBilinearGrad.ts","../src/resize_nearest_neighbor_gpu.ts","../src/resize_nearest_neighbor_packed_gpu.ts","../src/kernels/ResizeNearestNeighbor.ts","../src/resize_nearest_neighbor_backprop_gpu.ts","../src/kernels/ResizeNearestNeighborGrad.ts","../src/reverse_gpu.ts","../src/reverse_packed_gpu.ts","../src/kernels/Reverse.ts","../src/rotate_gpu.ts","../src/kernels/RotateWithOffset.ts","../src/kernels/Round.ts","../src/kernels/Rsqrt.ts","../src/scatter_gpu.ts","../src/kernels/ScatterNd.ts","../src/select_gpu.ts","../src/kernels/Select.ts","../src/kernels/Selu.ts","../src/kernels/Sigmoid.ts","../src/kernels/Sign.ts","../src/kernels/Sin.ts","../src/kernels/Sinh.ts","../src/kernels/Softplus.ts","../src/kernels/SpaceToBatchND.ts","../src/kernels/SparseFillEmptyRows.ts","../src/kernels/SparseReshape.ts","../src/kernels/SparseSegmentMean.ts","../src/kernels/SparseSegmentSum.ts","../src/kernels/SparseToDense.ts","../src/kernels/SplitV.ts","../src/kernels/Sqrt.ts","../src/kernels/Square.ts","../src/kernels/SquaredDifference.ts","../src/kernels/Step.ts","../src/strided_slice_gpu.ts","../src/kernels/StridedSlice.ts","../src/kernels/StringNGrams.ts","../src/kernels/StringSplit.ts","../src/kernels/StringToHashBucketFast.ts","../src/kernels/Tan.ts","../src/kernels/Tanh.ts","../src/tile_gpu.ts","../src/kernels/Tile.ts","../src/kernels/TopK.ts","../src/transform_gpu.ts","../src/kernels/Transform.ts","../src/kernels/Unique.ts","../src/kernels/Unpack.ts","../src/segment_gpu.ts","../src/kernels/UnsortedSegmentSum.ts","../src/register_all_kernels.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nconst contexts: {[key: string]: WebGLRenderingContext} = {};\n\nconst WEBGL_ATTRIBUTES: WebGLContextAttributes = {\n alpha: false,\n antialias: false,\n premultipliedAlpha: false,\n preserveDrawingBuffer: false,\n depth: false,\n stencil: false,\n failIfMajorPerformanceCaveat: true\n};\n\nexport function clearWebGLContext(webGLVersion: number) {\n delete contexts[webGLVersion];\n}\n\nexport function setWebGLContext(\n webGLVersion: number, gl: WebGLRenderingContext) {\n contexts[webGLVersion] = gl;\n}\n\nexport function getWebGLContext(webGLVersion: number): WebGLRenderingContext {\n if (!(webGLVersion in contexts)) {\n const newCtx = getWebGLRenderingContext(webGLVersion);\n if (newCtx !== null) {\n contexts[webGLVersion] = newCtx;\n } else {\n console.log('Could not get context for WebGL version', webGLVersion);\n return null;\n }\n }\n const gl = contexts[webGLVersion];\n if (gl.isContextLost()) {\n delete contexts[webGLVersion];\n return getWebGLContext(webGLVersion);\n }\n\n gl.disable(gl.DEPTH_TEST);\n gl.disable(gl.STENCIL_TEST);\n gl.disable(gl.BLEND);\n gl.disable(gl.DITHER);\n gl.disable(gl.POLYGON_OFFSET_FILL);\n gl.disable(gl.SAMPLE_COVERAGE);\n gl.enable(gl.SCISSOR_TEST);\n gl.enable(gl.CULL_FACE);\n gl.cullFace(gl.BACK);\n\n return contexts[webGLVersion];\n}\n\nfunction createCanvas(webGLVersion: number) {\n if (typeof OffscreenCanvas !== 'undefined' && webGLVersion === 2) {\n return new OffscreenCanvas(300, 150);\n } else if (typeof document !== 'undefined') {\n return document.createElement('canvas');\n } else {\n throw new Error('Cannot create a canvas in this context');\n }\n}\n\nfunction getWebGLRenderingContext(webGLVersion: number): WebGLRenderingContext {\n if (webGLVersion !== 1 && webGLVersion !== 2) {\n throw new Error('Cannot get WebGL rendering context, WebGL is disabled.');\n }\n const canvas = createCanvas(webGLVersion);\n\n canvas.addEventListener('webglcontextlost', (ev: Event) => {\n ev.preventDefault();\n delete contexts[webGLVersion];\n }, false);\n if (webGLVersion === 1) {\n return (canvas.getContext('webgl', WEBGL_ATTRIBUTES) ||\n canvas.getContext('experimental-webgl', WEBGL_ATTRIBUTES)) as\n WebGLRenderingContext;\n }\n return canvas.getContext('webgl2', WEBGL_ATTRIBUTES) as WebGLRenderingContext;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataId, DataType, env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nexport enum PackingScheme {\n /**\n * All values in a single texel are densely packed without any constraints.\n *\n * This is how the shader encodes a tensor with shape = [2, 3, 4]\n * (indices are [batch, row, col]).\n *\n * 000|001 010|011 020|021\n * ------- ------- -------\n * 002|003 012|013 022|023\n *\n * 100|101 110|111 120|121\n * ------- ------- -------\n * 102|103 112|113 122|123\n *\n */\n DENSE,\n\n /**\n * Single texels contain only values from the same batch, and from adjacent\n * rows and columns.\n *\n * This is how the shader encodes a tensor with shape = [2, 3, 5]\n * (indices are [batch, row, col]).\n *\n * 000|001 002|003 004|xxx 020|021 022|023 024|xxx\n * ------- ------- ------- ------- ------- -------\n * 010|011 012|013 014|xxx xxx|xxx xxx|xxx xxx|xxx\n *\n * 100|101 102|103 104|xxx 120|121 122|123 124|xxx\n * ------- ------- ------- ------- ------- -------\n * 110|111 112|113 114|xxx xxx|xxx xxx|xxx xxx|xxx\n *\n */\n SHARED_BATCH\n}\n\nexport enum TextureUsage {\n RENDER,\n UPLOAD,\n PIXELS,\n DOWNLOAD\n}\n\nexport enum PhysicalTextureType {\n UNPACKED_FLOAT16,\n UNPACKED_FLOAT32,\n PACKED_4X1_UNSIGNED_BYTE,\n PACKED_2X2_FLOAT32,\n PACKED_2X2_FLOAT16\n}\n\nexport interface TextureData {\n // Required.\n shape: number[];\n dtype: DataType;\n\n // Optional.\n values?: backend_util.BackendValues;\n texture?: WebGLTexture;\n // For complex numbers, the real and imaginary parts are stored as their own\n // individual tensorInfos, with a parent joining the two with the\n // complexTensors field. When this is defined, texture will be null.\n complexTensorInfos?: {real: TensorInfo, imag: TensorInfo};\n /** [rows, columns] shape of the texture. */\n texShape?: [number, number];\n usage?: TextureUsage;\n isPacked?: boolean;\n\n refCount: number;\n\n // Available when the tensor has been sliced.\n slice?: {\n // Offset in the 'flat index' space.\n flatOffset: number;\n // Used for counting how many sliced tensors point to the same texture.\n origDataId: DataId;\n };\n}\n\nexport function getUnpackedMatrixTextureShapeWidthHeight(\n rows: number, columns: number): [number, number] {\n return [columns, rows];\n}\n\nexport function getUnpackedArraySizeFromMatrixSize(\n matrixSize: number, channelsPerTexture: number): number {\n return matrixSize * channelsPerTexture;\n}\n\nexport function getColorMatrixTextureShapeWidthHeight(\n rows: number, columns: number): [number, number] {\n return [columns * 4, rows];\n}\n\n/**\n * Get shape for densely packed RGBA texture.\n */\nexport function getDenseTexShape(shape: number[]): [number, number] {\n const size = util.sizeFromShape(shape);\n const texelsNeeded = Math.ceil(size / 4);\n return util.sizeToSquarishShape(texelsNeeded);\n}\n\nexport function getMatrixSizeFromUnpackedArraySize(\n unpackedSize: number, channelsPerTexture: number): number {\n if (unpackedSize % channelsPerTexture !== 0) {\n throw new Error(\n `unpackedSize (${unpackedSize}) must be a multiple of ` +\n `${channelsPerTexture}`);\n }\n return unpackedSize / channelsPerTexture;\n}\n\nexport function decodeMatrixFromUnpackedColorRGBAArray(\n unpackedArray: Float32Array, matrix: Float32Array, channels: number) {\n const requiredSize = unpackedArray.length * channels / 4;\n if (matrix.length < requiredSize) {\n throw new Error(\n `matrix length (${matrix.length}) must be >= ${requiredSize}`);\n }\n let dst = 0;\n for (let src = 0; src < unpackedArray.length; src += 4) {\n for (let c = 0; c < channels; c++) {\n matrix[dst++] = unpackedArray[src + c];\n }\n }\n}\n\nexport function getPackedMatrixTextureShapeWidthHeight(\n rows: number, columns: number): [number, number] {\n return [\n Math.max(1, Math.ceil(columns / 2)), Math.max(1, Math.ceil(rows / 2))\n ];\n}\n\nexport function getPackedRGBAArraySizeFromMatrixShape(\n rows: number, columns: number): number {\n const [w, h] = getPackedMatrixTextureShapeWidthHeight(rows, columns);\n return w * h * 4;\n}\n\nexport interface TextureConfig {\n internalFormatFloat: number;\n textureFormatFloat: number;\n internalFormatPackedHalfFloat: number;\n internalFormatHalfFloat: number;\n internalFormatPackedFloat: number;\n\n // The format to use during a gl.readPixels call.\n downloadTextureFormat: number;\n // How many channels need to be unpacked after a gl.readPixels call.\n downloadUnpackNumChannels: number;\n\n defaultNumChannels: number;\n textureTypeHalfFloat: number;\n textureTypeFloat: number;\n}\n\nexport function getTextureConfig(\n // tslint:disable-next-line:no-any\n gl: WebGLRenderingContext, textureHalfFloatExtension?: any): TextureConfig {\n // tslint:disable-next-line:no-any\n const glany = gl as any;\n\n let internalFormatFloat: number;\n let internalFormatHalfFloat: number;\n let internalFormatPackedHalfFloat: number;\n let internalFormatPackedFloat: number;\n let textureFormatFloat: number;\n\n let downloadTextureFormat: number;\n let downloadUnpackNumChannels: number;\n\n let defaultNumChannels: number;\n let textureTypeHalfFloat: number;\n let textureTypeFloat: number;\n\n if (env().getNumber('WEBGL_VERSION') === 2) {\n internalFormatFloat = glany.R32F;\n internalFormatHalfFloat = glany.R16F;\n internalFormatPackedHalfFloat = glany.RGBA16F;\n internalFormatPackedFloat = glany.RGBA32F;\n textureFormatFloat = glany.RED;\n downloadUnpackNumChannels = 4;\n defaultNumChannels = 1;\n textureTypeHalfFloat = glany.HALF_FLOAT;\n textureTypeFloat = glany.FLOAT;\n } else {\n internalFormatFloat = gl.RGBA;\n internalFormatHalfFloat = gl.RGBA;\n internalFormatPackedHalfFloat = gl.RGBA;\n internalFormatPackedFloat = glany.RGBA;\n textureFormatFloat = gl.RGBA;\n downloadUnpackNumChannels = 4;\n defaultNumChannels = 4;\n textureTypeHalfFloat = textureHalfFloatExtension != null ?\n textureHalfFloatExtension.HALF_FLOAT_OES :\n null;\n textureTypeFloat = gl.FLOAT;\n }\n downloadTextureFormat = gl.RGBA;\n\n return {\n internalFormatFloat,\n internalFormatHalfFloat,\n internalFormatPackedHalfFloat,\n internalFormatPackedFloat,\n textureFormatFloat,\n downloadTextureFormat,\n downloadUnpackNumChannels,\n defaultNumChannels,\n textureTypeHalfFloat,\n textureTypeFloat\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {getWebGLContext} from './canvas_util';\nimport {getTextureConfig} from './tex_util';\n\nexport function callAndCheck(gl: WebGLRenderingContext, func: () => T): T {\n const returnValue = func();\n if (env().getBool('DEBUG')) {\n checkWebGLError(gl);\n }\n return returnValue;\n}\n\nfunction checkWebGLError(gl: WebGLRenderingContext) {\n const error = gl.getError();\n if (error !== gl.NO_ERROR) {\n throw new Error('WebGL Error: ' + getWebGLErrorMessage(gl, error));\n }\n}\n\n// https://en.wikipedia.org/wiki/Half-precision_floating-point_format\nconst MIN_FLOAT16 = 5.96e-8;\nconst MAX_FLOAT16 = 65504;\n\nexport function canBeRepresented(num: number): boolean {\n if (env().getBool('WEBGL_RENDER_FLOAT32_ENABLED') || num === 0 ||\n (MIN_FLOAT16 < Math.abs(num) && Math.abs(num) < MAX_FLOAT16)) {\n return true;\n }\n return false;\n}\n\nexport function getWebGLErrorMessage(\n gl: WebGLRenderingContext, status: number): string {\n switch (status) {\n case gl.NO_ERROR:\n return 'NO_ERROR';\n case gl.INVALID_ENUM:\n return 'INVALID_ENUM';\n case gl.INVALID_VALUE:\n return 'INVALID_VALUE';\n case gl.INVALID_OPERATION:\n return 'INVALID_OPERATION';\n case gl.INVALID_FRAMEBUFFER_OPERATION:\n return 'INVALID_FRAMEBUFFER_OPERATION';\n case gl.OUT_OF_MEMORY:\n return 'OUT_OF_MEMORY';\n case gl.CONTEXT_LOST_WEBGL:\n return 'CONTEXT_LOST_WEBGL';\n default:\n return `Unknown error code ${status}`;\n }\n}\n\nexport function getExtensionOrThrow(\n gl: WebGLRenderingContext, extensionName: string): {} {\n return throwIfNull<{}>(\n gl, () => gl.getExtension(extensionName),\n 'Extension \"' + extensionName + '\" not supported on this browser.');\n}\n\nexport function createVertexShader(\n gl: WebGLRenderingContext, vertexShaderSource: string): WebGLShader {\n const vertexShader: WebGLShader = throwIfNull(\n gl, () => gl.createShader(gl.VERTEX_SHADER),\n 'Unable to create vertex WebGLShader.');\n callAndCheck(gl, () => gl.shaderSource(vertexShader, vertexShaderSource));\n callAndCheck(gl, () => gl.compileShader(vertexShader));\n if (gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS) === false) {\n console.log(gl.getShaderInfoLog(vertexShader));\n throw new Error('Failed to compile vertex shader.');\n }\n return vertexShader;\n}\n\nexport function createFragmentShader(\n gl: WebGLRenderingContext, fragmentShaderSource: string): WebGLShader {\n const fragmentShader: WebGLShader = throwIfNull(\n gl, () => gl.createShader(gl.FRAGMENT_SHADER),\n 'Unable to create fragment WebGLShader.');\n callAndCheck(gl, () => gl.shaderSource(fragmentShader, fragmentShaderSource));\n callAndCheck(gl, () => gl.compileShader(fragmentShader));\n if (gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS) === false) {\n logShaderSourceAndInfoLog(\n fragmentShaderSource, gl.getShaderInfoLog(fragmentShader));\n throw new Error('Failed to compile fragment shader.');\n }\n return fragmentShader;\n}\n\nconst lineNumberRegex = /ERROR: [0-9]+:([0-9]+):/g;\nfunction logShaderSourceAndInfoLog(\n shaderSource: string, shaderInfoLog: string) {\n const lineNumberRegexResult = lineNumberRegex.exec(shaderInfoLog);\n if (lineNumberRegexResult == null) {\n console.log(`Couldn't parse line number in error: ${shaderInfoLog}`);\n console.log(shaderSource);\n return;\n }\n\n const lineNumber = +lineNumberRegexResult[1];\n\n const shaderLines = shaderSource.split('\\n');\n const pad = shaderLines.length.toString().length + 2;\n const linesWithLineNumbers = shaderLines.map(\n (line, lineNumber) =>\n util.rightPad((lineNumber + 1).toString(), pad) + line);\n let maxLineLength = 0;\n for (let i = 0; i < linesWithLineNumbers.length; i++) {\n maxLineLength = Math.max(linesWithLineNumbers[i].length, maxLineLength);\n }\n\n const beforeErrorLines = linesWithLineNumbers.slice(0, lineNumber - 1);\n const errorLine = linesWithLineNumbers.slice(lineNumber - 1, lineNumber);\n const afterErrorLines = linesWithLineNumbers.slice(lineNumber);\n\n console.log(beforeErrorLines.join('\\n'));\n console.log(shaderInfoLog.split('\\n')[0]);\n console.log(\n `%c ${util.rightPad(errorLine[0], maxLineLength)}`,\n 'border:1px solid red; background-color:#e3d2d2; color:#a61717');\n console.log(afterErrorLines.join('\\n'));\n}\n\nexport function createProgram(gl: WebGLRenderingContext): WebGLProgram {\n return throwIfNull(\n gl, () => gl.createProgram(), 'Unable to create WebGLProgram.');\n}\n\nexport function linkProgram(gl: WebGLRenderingContext, program: WebGLProgram) {\n callAndCheck(gl, () => gl.linkProgram(program));\n if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {\n console.log(gl.getProgramInfoLog(program));\n throw new Error('Failed to link vertex and fragment shaders.');\n }\n}\n\nexport function validateProgram(\n gl: WebGLRenderingContext, program: WebGLProgram) {\n callAndCheck(gl, () => gl.validateProgram(program));\n if (gl.getProgramParameter(program, gl.VALIDATE_STATUS) === false) {\n console.log(gl.getProgramInfoLog(program));\n throw new Error('Shader program validation failed.');\n }\n}\n\nexport function createStaticVertexBuffer(\n gl: WebGLRenderingContext, data: Float32Array): WebGLBuffer {\n const buffer: WebGLBuffer = throwIfNull(\n gl, () => gl.createBuffer(), 'Unable to create WebGLBuffer');\n callAndCheck(gl, () => gl.bindBuffer(gl.ARRAY_BUFFER, buffer));\n callAndCheck(gl, () => gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW));\n return buffer;\n}\n\nexport function createStaticIndexBuffer(\n gl: WebGLRenderingContext, data: Uint16Array): WebGLBuffer {\n const buffer: WebGLBuffer = throwIfNull(\n gl, () => gl.createBuffer(), 'Unable to create WebGLBuffer');\n callAndCheck(gl, () => gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer));\n callAndCheck(\n gl, () => gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW));\n return buffer;\n}\n\nexport function getNumChannels(): number {\n if (env().getNumber('WEBGL_VERSION') === 2) {\n return 1;\n }\n return 4;\n}\n\nexport function createTexture(gl: WebGLRenderingContext): WebGLTexture {\n return throwIfNull(\n gl, () => gl.createTexture(), 'Unable to create WebGLTexture.');\n}\n\nexport function validateTextureSize(width: number, height: number) {\n const maxTextureSize = env().getNumber('WEBGL_MAX_TEXTURE_SIZE');\n if ((width <= 0) || (height <= 0)) {\n const requested = `[${width}x${height}]`;\n throw new Error('Requested texture size ' + requested + ' is invalid.');\n }\n if ((width > maxTextureSize) || (height > maxTextureSize)) {\n const requested = `[${width}x${height}]`;\n const max = `[${maxTextureSize}x${maxTextureSize}]`;\n throw new Error(\n 'Requested texture size ' + requested +\n ' greater than WebGL maximum on this browser / GPU ' + max + '.');\n }\n}\n\nexport function createFramebuffer(gl: WebGLRenderingContext): WebGLFramebuffer {\n return throwIfNull(\n gl, () => gl.createFramebuffer(), 'Unable to create WebGLFramebuffer.');\n}\n\nexport function bindVertexBufferToProgramAttribute(\n gl: WebGLRenderingContext, program: WebGLProgram, attribute: string,\n buffer: WebGLBuffer, arrayEntriesPerItem: number, itemStrideInBytes: number,\n itemOffsetInBytes: number): boolean {\n const loc = gl.getAttribLocation(program, attribute);\n if (loc === -1) {\n // The GPU compiler decided to strip out this attribute because it's unused,\n // thus no need to bind.\n return false;\n }\n callAndCheck(gl, () => gl.bindBuffer(gl.ARRAY_BUFFER, buffer));\n callAndCheck(\n gl,\n () => gl.vertexAttribPointer(\n loc, arrayEntriesPerItem, gl.FLOAT, false, itemStrideInBytes,\n itemOffsetInBytes));\n callAndCheck(gl, () => gl.enableVertexAttribArray(loc));\n return true;\n}\n\nexport function bindTextureUnit(\n gl: WebGLRenderingContext, texture: WebGLTexture, textureUnit: number) {\n validateTextureUnit(gl, textureUnit);\n callAndCheck(gl, () => gl.activeTexture(gl.TEXTURE0 + textureUnit));\n callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, texture));\n}\n\nexport function unbindTextureUnit(\n gl: WebGLRenderingContext, textureUnit: number) {\n validateTextureUnit(gl, textureUnit);\n callAndCheck(gl, () => gl.activeTexture(gl.TEXTURE0 + textureUnit));\n callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, null));\n}\n\nexport function getProgramUniformLocationOrThrow(\n gl: WebGLRenderingContext, program: WebGLProgram,\n uniformName: string): WebGLUniformLocation {\n return throwIfNull(\n gl, () => gl.getUniformLocation(program, uniformName),\n 'uniform \"' + uniformName + '\" not present in program.');\n}\n\nexport function getProgramUniformLocation(\n gl: WebGLRenderingContext, program: WebGLProgram,\n uniformName: string): WebGLUniformLocation {\n return gl.getUniformLocation(program, uniformName);\n}\n\nexport function bindTextureToProgramUniformSampler(\n gl: WebGLRenderingContext, texture: WebGLTexture,\n uniformSamplerLocation: WebGLUniformLocation, textureUnit: number) {\n callAndCheck(gl, () => bindTextureUnit(gl, texture, textureUnit));\n callAndCheck(gl, () => gl.uniform1i(uniformSamplerLocation, textureUnit));\n}\n\nexport function bindCanvasToFramebuffer(gl: WebGLRenderingContext) {\n callAndCheck(gl, () => gl.bindFramebuffer(gl.FRAMEBUFFER, null));\n callAndCheck(gl, () => gl.viewport(0, 0, gl.canvas.width, gl.canvas.height));\n callAndCheck(gl, () => gl.scissor(0, 0, gl.canvas.width, gl.canvas.height));\n}\n\nexport function bindColorTextureToFramebuffer(\n gl: WebGLRenderingContext, texture: WebGLTexture,\n framebuffer: WebGLFramebuffer) {\n callAndCheck(gl, () => gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer));\n callAndCheck(\n gl,\n () => gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0));\n}\n\nexport function unbindColorTextureFromFramebuffer(\n gl: WebGLRenderingContext, framebuffer: WebGLFramebuffer) {\n callAndCheck(gl, () => gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer));\n callAndCheck(\n gl,\n () => gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0));\n}\n\nexport function validateFramebuffer(gl: WebGLRenderingContext) {\n const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);\n if (status !== gl.FRAMEBUFFER_COMPLETE) {\n throw new Error(\n 'Error binding framebuffer: ' + getFramebufferErrorMessage(gl, status));\n }\n}\n\nexport function getFramebufferErrorMessage(\n gl: WebGLRenderingContext, status: number): string {\n switch (status) {\n case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n return 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT';\n case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n return 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT';\n case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:\n return 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS';\n case gl.FRAMEBUFFER_UNSUPPORTED:\n return 'FRAMEBUFFER_UNSUPPORTED';\n default:\n return `unknown error ${status}`;\n }\n}\n\nfunction throwIfNull(\n gl: WebGLRenderingContext, returnTOrNull: () => T | null,\n failureMessage: string): T {\n const tOrNull: T|null = callAndCheck(gl, () => returnTOrNull());\n if (tOrNull == null) {\n throw new Error(failureMessage);\n }\n return tOrNull;\n}\n\nfunction validateTextureUnit(gl: WebGLRenderingContext, textureUnit: number) {\n const maxTextureUnit = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1;\n const glTextureUnit = textureUnit + gl.TEXTURE0;\n if (glTextureUnit < gl.TEXTURE0 || glTextureUnit > maxTextureUnit) {\n const textureUnitRange = `[gl.TEXTURE0, gl.TEXTURE${maxTextureUnit}]`;\n throw new Error(`textureUnit must be in ${textureUnitRange}.`);\n }\n}\n\nexport function getBatchDim(shape: number[], dimsToSkip = 2): number {\n return util.sizeFromShape(shape.slice(0, shape.length - dimsToSkip));\n}\n\nexport function getRowsCols(shape: number[]): [number, number] {\n if (shape.length === 0) {\n throw Error('Cannot get rows and columns of an empty shape array.');\n }\n\n return [\n shape.length > 1 ? shape[shape.length - 2] : 1, shape[shape.length - 1]\n ];\n}\n\nexport function getShapeAs3D(shape: number[]): [number, number, number] {\n let shapeAs3D: [number, number, number] = [1, 1, 1];\n const isScalar = shape.length === 0 || (shape.length === 1 && shape[0] === 1);\n if (!isScalar) {\n shapeAs3D =\n [getBatchDim(shape), ...getRowsCols(shape)] as [number, number, number];\n }\n return shapeAs3D;\n}\n\nexport function getTextureShapeFromLogicalShape(\n logShape: number[], isPacked = false): [number, number] {\n let maxTexSize = env().getNumber('WEBGL_MAX_TEXTURE_SIZE');\n if (isPacked) {\n maxTexSize = maxTexSize * 2;\n\n // This logic ensures we accurately count the number of packed texels needed\n // to accommodate the tensor. We can only pack values in the same texel if\n // they are from adjacent pairs of rows/cols within the same batch. So if a\n // tensor has 3 rows, we pretend it has 4 rows in order to account for the\n // fact that the texels containing the third row are half empty.\n logShape = logShape.map(\n (d, i) => i >= logShape.length - 2 ?\n util.nearestLargerEven(logShape[i]) :\n logShape[i]);\n\n // Packed texture height is at least 2 (the channel height of a single\n // texel).\n if (logShape.length === 1) {\n logShape = [2, logShape[0]];\n }\n }\n\n // If logical shape is 2, we don't squeeze, since we want to match physical.\n if (logShape.length !== 2) {\n const squeezeResult = util.squeezeShape(logShape);\n logShape = squeezeResult.newShape;\n }\n\n let size = util.sizeFromShape(logShape);\n if (logShape.length <= 1 && size <= maxTexSize) {\n return [1, size];\n } else if (\n logShape.length === 2 && logShape[0] <= maxTexSize &&\n logShape[1] <= maxTexSize) {\n return logShape as [number, number];\n } else if (\n logShape.length === 3 && logShape[0] * logShape[1] <= maxTexSize &&\n logShape[2] <= maxTexSize) {\n return [logShape[0] * logShape[1], logShape[2]];\n } else if (\n logShape.length === 3 && logShape[0] <= maxTexSize &&\n logShape[1] * logShape[2] <= maxTexSize) {\n return [logShape[0], logShape[1] * logShape[2]];\n } else if (\n logShape.length === 4 &&\n logShape[0] * logShape[1] * logShape[2] <= maxTexSize &&\n logShape[3] <= maxTexSize) {\n return [logShape[0] * logShape[1] * logShape[2], logShape[3]];\n } else if (\n logShape.length === 4 && logShape[0] <= maxTexSize &&\n logShape[1] * logShape[2] * logShape[3] <= maxTexSize) {\n return [logShape[0], logShape[1] * logShape[2] * logShape[3]];\n } else {\n if (isPacked) {\n // For packed textures size equals the number of channels required to\n // accommodate the texture data. However in order to squarify such that\n // inner dimensions stay even, we rewrite size to equal the number of\n // texels. Then in the return statement we rehydrate the squarified\n // dimensions to channel units.\n\n const batchDim = getBatchDim(logShape);\n let rows = 2, cols = 2;\n if (logShape.length) {\n [rows, cols] = getRowsCols(logShape);\n }\n size = batchDim * (rows / 2) * (cols / 2);\n return util.sizeToSquarishShape(size).map(d => d * 2) as [number, number];\n }\n return util.sizeToSquarishShape(size);\n }\n}\n\nfunction isEven(n: number): boolean {\n return n % 2 === 0;\n}\n\n/**\n * This determines whether reshaping a packed texture requires rearranging\n * the data within the texture, assuming 2x2 packing.\n */\nexport function isReshapeFree(shape1: number[], shape2: number[]): boolean {\n shape1 = shape1.slice(-2);\n shape2 = shape2.slice(-2);\n\n if (util.arraysEqual(shape1, shape2)) {\n return true;\n }\n\n if (!shape1.length || !shape2.length) { // One of the shapes is a scalar.\n return true;\n }\n\n if (shape1[0] === 0 || shape1[1] === 0 || shape2[0] === 0 ||\n shape2[1] === 0) {\n return true;\n }\n\n if (shape1.length !== shape2.length) { // One of the shapes is a vector.\n const shape1Cols = shape1.slice(-1)[0];\n const shape2Cols = shape2.slice(-1)[0];\n if (shape1Cols === shape2Cols) {\n return true;\n }\n\n if (isEven(shape1Cols) && isEven(shape2Cols) &&\n (shape1[0] === 1 || shape2[0] === 1)) {\n return true;\n }\n }\n return shape1[1] === shape2[1] && isEven(shape1[0]) && isEven(shape2[0]);\n}\n\n// We cache webgl params because the environment gets reset between\n// unit tests and we don't want to constantly query the WebGLContext for\n// MAX_TEXTURE_SIZE.\nlet MAX_TEXTURE_SIZE: number;\nlet MAX_TEXTURES_IN_SHADER: number;\n\nexport function getWebGLMaxTextureSize(webGLVersion: number): number {\n if (MAX_TEXTURE_SIZE == null) {\n const gl = getWebGLContext(webGLVersion);\n MAX_TEXTURE_SIZE = gl.getParameter(gl.MAX_TEXTURE_SIZE);\n }\n return MAX_TEXTURE_SIZE;\n}\n\nexport function resetMaxTextureSize() {\n MAX_TEXTURE_SIZE = null;\n}\nexport function resetMaxTexturesInShader() {\n MAX_TEXTURES_IN_SHADER = null;\n}\n\nexport function getMaxTexturesInShader(webGLVersion: number): number {\n if (MAX_TEXTURES_IN_SHADER == null) {\n const gl = getWebGLContext(webGLVersion);\n MAX_TEXTURES_IN_SHADER = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);\n }\n // We cap at 16 to avoid spurious runtime \"memory exhausted\" error.\n return Math.min(16, MAX_TEXTURES_IN_SHADER);\n}\n\nexport function getWebGLDisjointQueryTimerVersion(webGLVersion: number):\n number {\n if (webGLVersion === 0) {\n return 0;\n }\n\n let queryTimerVersion: number;\n const gl = getWebGLContext(webGLVersion);\n\n if (hasExtension(gl, 'EXT_disjoint_timer_query_webgl2') &&\n webGLVersion === 2) {\n queryTimerVersion = 2;\n } else if (hasExtension(gl, 'EXT_disjoint_timer_query')) {\n queryTimerVersion = 1;\n } else {\n queryTimerVersion = 0;\n }\n return queryTimerVersion;\n}\n\nexport function hasExtension(gl: WebGLRenderingContext, extensionName: string) {\n const ext = gl.getExtension(extensionName);\n return ext != null;\n}\n\nexport function isWebGLVersionEnabled(webGLVersion: 1|2) {\n try {\n const gl = getWebGLContext(webGLVersion);\n if (gl != null) {\n return true;\n }\n } catch (e) {\n console.log('Error when getting WebGL context: ', e);\n return false;\n }\n return false;\n}\n\nexport function isCapableOfRenderingToFloatTexture(webGLVersion: number):\n boolean {\n if (webGLVersion === 0) {\n return false;\n }\n\n const gl = getWebGLContext(webGLVersion);\n\n if (webGLVersion === 1) {\n if (!hasExtension(gl, 'OES_texture_float')) {\n return false;\n }\n } else {\n if (!hasExtension(gl, 'EXT_color_buffer_float')) {\n return false;\n }\n }\n\n const isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);\n return isFrameBufferComplete;\n}\n\n/**\n * Check if we can download values from a float/half-float texture.\n *\n * Note that for performance reasons we use binding a texture to a framebuffer\n * as a proxy for ability to download float values later using readPixels. The\n * texture params of this texture will not match those in readPixels exactly\n * but if we are unable to bind some kind of float texture to the frameBuffer\n * then we definitely will not be able to read float values from it.\n */\nexport function isDownloadFloatTextureEnabled(webGLVersion: number): boolean {\n if (webGLVersion === 0) {\n return false;\n }\n\n const gl = getWebGLContext(webGLVersion);\n\n if (webGLVersion === 1) {\n if (!hasExtension(gl, 'OES_texture_float')) {\n return false;\n }\n if (!hasExtension(gl, 'WEBGL_color_buffer_float')) {\n return false;\n }\n } else {\n if (hasExtension(gl, 'EXT_color_buffer_float')) {\n return createFloatTextureAndBindToFramebuffer(gl);\n }\n\n const COLOR_BUFFER_HALF_FLOAT = 'EXT_color_buffer_half_float';\n if (hasExtension(gl, COLOR_BUFFER_HALF_FLOAT)) {\n const textureHalfFloatExtension =\n gl.getExtension(COLOR_BUFFER_HALF_FLOAT);\n return createHalfFloatTextureAndBindToFramebuffer(\n gl, textureHalfFloatExtension);\n }\n\n return false;\n }\n\n const isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);\n return isFrameBufferComplete;\n}\n\nfunction createFloatTextureAndBindToFramebuffer(gl: WebGLRenderingContext):\n boolean {\n const texConfig = getTextureConfig(gl);\n\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n const width = 1;\n const height = 1;\n gl.texImage2D(\n gl.TEXTURE_2D, 0, texConfig.internalFormatFloat, width, height, 0,\n texConfig.textureFormatFloat, texConfig.textureTypeFloat, null);\n\n const frameBuffer = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n\n const isFrameBufferComplete =\n gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.deleteTexture(texture);\n gl.deleteFramebuffer(frameBuffer);\n\n return isFrameBufferComplete;\n}\n\nfunction createHalfFloatTextureAndBindToFramebuffer(\n // tslint:disable-next-line:no-any\n gl: WebGLRenderingContext, textureHalfFloatExtension: any): boolean {\n const texConfig = getTextureConfig(gl, textureHalfFloatExtension);\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n const width = 1;\n const height = 1;\n gl.texImage2D(\n gl.TEXTURE_2D, 0, texConfig.internalFormatHalfFloat, width, height, 0,\n texConfig.textureFormatFloat, texConfig.textureTypeHalfFloat, null);\n\n const frameBuffer = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n\n const isFrameBufferComplete =\n gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.deleteTexture(texture);\n gl.deleteFramebuffer(frameBuffer);\n\n return isFrameBufferComplete;\n}\n\nexport function isWebGLFenceEnabled(webGLVersion: number) {\n if (webGLVersion !== 2) {\n return false;\n }\n const gl = getWebGLContext(webGLVersion);\n\n // tslint:disable-next-line:no-any\n const isEnabled = (gl as any).fenceSync != null;\n return isEnabled;\n}\n\nexport function assertNotComplex(\n tensor: TensorInfo|TensorInfo[], opName: string): void {\n if (!Array.isArray(tensor)) {\n tensor = [tensor];\n }\n tensor.forEach(t => {\n if (t != null) {\n util.assert(\n t.dtype !== 'complex64',\n () => `${opName} does not support complex64 tensors ` +\n 'in the WebGL backend.');\n }\n });\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {device_util, env} from '@tensorflow/tfjs-core';\n\nimport {getMaxTexturesInShader, getWebGLDisjointQueryTimerVersion, getWebGLMaxTextureSize, isCapableOfRenderingToFloatTexture, isDownloadFloatTextureEnabled, isWebGLFenceEnabled, isWebGLVersionEnabled} from './webgl_util';\n\nconst ENV = env();\n\n/**\n * This file contains WebGL-specific flag registrations.\n */\n\n/**\n * True if WebGL is supported.\n */\nENV.registerFlag('HAS_WEBGL', () => ENV.getNumber('WEBGL_VERSION') > 0);\n\n/** 0: No WebGL, 1: WebGL 1.0, 2: WebGL 2.0. */\nENV.registerFlag('WEBGL_VERSION', () => {\n if (isWebGLVersionEnabled(2)) {\n return 2;\n } else if (isWebGLVersionEnabled(1)) {\n return 1;\n }\n return 0;\n});\n\n/** Whether to check for numerical representation problems. */\nENV.registerFlag('WEBGL_CHECK_NUMERICAL_PROBLEMS', () => false);\n\nENV.registerFlag(\n 'WEBGL_BUFFER_SUPPORTED', () => ENV.get('WEBGL_VERSION') === 2);\n\n/** Whether the WebGL backend will sometimes forward ops to the CPU. */\nENV.registerFlag('WEBGL_CPU_FORWARD', () => true);\n\n/** Whether the WebGL backend will always use f16 textures for rendering. */\nENV.registerFlag('WEBGL_FORCE_F16_TEXTURES', () => false);\n\n/** Whether to turn all packing related flags on. */\nENV.registerFlag('WEBGL_PACK', () => ENV.getBool('HAS_WEBGL'));\n\n/** Whether we will pack the batchnormalization op. */\nENV.registerFlag('WEBGL_PACK_NORMALIZATION', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack the clip op. */\nENV.registerFlag('WEBGL_PACK_CLIP', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack the depthwise conv op. */\nENV.registerFlag('WEBGL_PACK_DEPTHWISECONV', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack binary ops. */\nENV.registerFlag(\n 'WEBGL_PACK_BINARY_OPERATIONS', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack unary ops. */\nENV.registerFlag(\n 'WEBGL_PACK_UNARY_OPERATIONS', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack array ops. */\nENV.registerFlag(\n 'WEBGL_PACK_ARRAY_OPERATIONS', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack image ops. */\nENV.registerFlag(\n 'WEBGL_PACK_IMAGE_OPERATIONS', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack reduce ops. */\nENV.registerFlag('WEBGL_PACK_REDUCE', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether packed WebGL kernels lazily unpack their outputs. */\nENV.registerFlag('WEBGL_LAZILY_UNPACK', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will use the im2col algorithm to speed up convolutions. */\nENV.registerFlag('WEBGL_CONV_IM2COL', () => ENV.getBool('WEBGL_PACK'));\n\n/** The maximum texture dimension. */\nENV.registerFlag(\n 'WEBGL_MAX_TEXTURE_SIZE',\n () => getWebGLMaxTextureSize(ENV.getNumber('WEBGL_VERSION')));\n\n/** The maximum texture dimension. */\nENV.registerFlag(\n 'WEBGL_MAX_TEXTURES_IN_SHADER',\n () => getMaxTexturesInShader(ENV.getNumber('WEBGL_VERSION')));\n\n/**\n * The disjoint_query_timer extension version.\n * 0: disabled, 1: EXT_disjoint_timer_query, 2:\n * EXT_disjoint_timer_query_webgl2.\n * In Firefox with WebGL 2.0,\n * EXT_disjoint_timer_query_webgl2 is not available, so we must use the\n * WebGL 1.0 extension.\n */\nENV.registerFlag('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION', () => {\n const webGLVersion = ENV.getNumber('WEBGL_VERSION');\n\n if (webGLVersion === 0) {\n return 0;\n }\n return getWebGLDisjointQueryTimerVersion(webGLVersion);\n});\n\n/**\n * Whether the timer object from the disjoint_query_timer extension gives\n * timing information that is reliable.\n */\nENV.registerFlag(\n 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE',\n () => ENV.getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0 &&\n !device_util.isMobile());\n\n/**\n * Whether the device is physically capable of rendering to float32 textures.\n */\nENV.registerFlag(\n 'WEBGL_RENDER_FLOAT32_CAPABLE',\n () => isCapableOfRenderingToFloatTexture(ENV.getNumber('WEBGL_VERSION')));\n\n/**\n * Whether rendering to float32 textures is enabled. If disabled, renders to\n * float16 textures.\n */\nENV.registerFlag('WEBGL_RENDER_FLOAT32_ENABLED', () => {\n return ENV.getBool('WEBGL_FORCE_F16_TEXTURES') ?\n false :\n ENV.getBool('WEBGL_RENDER_FLOAT32_CAPABLE');\n});\n\n/**\n * Whether downloading float textures is enabled (16 or 32 bit). If disabled,\n * uses IEEE 754 encoding of the float32 values to 4 uint8 when downloading.\n */\nENV.registerFlag(\n 'WEBGL_DOWNLOAD_FLOAT_ENABLED',\n () => isDownloadFloatTextureEnabled(ENV.getNumber('WEBGL_VERSION')));\n\n/** Whether the fence API is available. */\nENV.registerFlag(\n 'WEBGL_FENCE_API_ENABLED',\n () => isWebGLFenceEnabled(ENV.getNumber('WEBGL_VERSION')));\n\n/**\n * Tensors with size <= than this will be uploaded as uniforms, not textures.\n */\nENV.registerFlag('WEBGL_SIZE_UPLOAD_UNIFORM', () => {\n // Use uniform uploads only when 32bit floats are supported. In\n // 16bit\n // environments there are problems with comparing a 16bit texture value\n // with a 32bit uniform value.\n const useUniforms = ENV.getBool('WEBGL_RENDER_FLOAT32_ENABLED');\n return useUniforms ? 4 : 0;\n});\n\n/**\n * If the total number of bytes allocated on the GPU is greater than this\n * number, we will aggressively delete textures upon disposal with\n * gl.deleteMatrixTexture, rather than making them available for reuse.\n *\n * Default value -1 indicates that we will never aggressively delete textures.\n */\nENV.registerFlag(\n 'WEBGL_DELETE_TEXTURE_THRESHOLD',\n () => {\n return -1;\n },\n threshold => {\n if (threshold < 0 && threshold !== -1) {\n throw new Error(\n `WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never ` +\n `delete) or at least 0, but got ${threshold}.`);\n }\n });\n\n/**\n * Trigger a manual GL command flush if the threshold of time has passed since\n * previous Kernel execution. This can be useful for Andorid device where GL\n * command flush are delayed un til the end of javascript task. This value is\n * measured in millisecond. Typically you want to set this value to close to 1.\n *\n * Default value 1 for mobile chrome, and -1 for rest cases. -1 indicates that\n * we will not enforce manual flush and depend on system default flush schedule.\n */\nENV.registerFlag(\n 'WEBGL_FLUSH_THRESHOLD',\n () => {\n return device_util.isMobile() && ENV.getBool('IS_CHROME') ? 1 : -1;\n },\n threshold => {\n if (threshold < 0 && threshold !== -1) {\n throw new Error(\n `WEBGL_FLUSH_THRESHOLD must be -1 (indicating never ` +\n `manual flush) or at least 0, but got ${threshold}.`);\n }\n });\n\n/**\n * Threshold for input tensor size that determines whether WebGL backend will\n * delegate computation to CPU.\n *\n * Default value is 128.\n */\nENV.registerFlag('CPU_HANDOFF_SIZE_THRESHOLD', () => 128);\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from '@tensorflow/tfjs-core';\n\nexport type GLSL = {\n version: string,\n attribute: string,\n varyingVs: string,\n varyingFs: string,\n texture2D: string,\n output: string,\n defineOutput: string,\n defineSpecialNaN: string,\n defineSpecialInf: string,\n defineRound: string\n};\n\nexport function getGlslDifferences(): GLSL {\n let version: string;\n let attribute: string;\n let varyingVs: string;\n let varyingFs: string;\n let texture2D: string;\n let output: string;\n let defineOutput: string;\n let defineSpecialNaN: string;\n let defineSpecialInf: string;\n let defineRound: string;\n\n if (env().getNumber('WEBGL_VERSION') === 2) {\n version = '#version 300 es';\n attribute = 'in';\n varyingVs = 'out';\n varyingFs = 'in';\n texture2D = 'texture';\n output = 'outputColor';\n defineOutput = 'out vec4 outputColor;';\n\n // Use custom isnan definition to work across differences between\n // implementations on various platforms. While this should happen in ANGLE\n // we still see differences between android and windows (on chrome) when\n // using isnan directly.\n defineSpecialNaN = `\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 `;\n // In webgl 2 we do not need to specify a custom isinf so there is no\n // need for a special INFINITY constant.\n defineSpecialInf = ``;\n defineRound = `\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 `;\n } else {\n version = '';\n attribute = 'attribute';\n varyingVs = 'varying';\n varyingFs = 'varying';\n texture2D = 'texture2D';\n output = 'gl_FragColor';\n defineOutput = '';\n // WebGL1 has no built in isnan so we define one here.\n defineSpecialNaN = `\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 `;\n defineSpecialInf = `\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 `;\n defineRound = `\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 `;\n }\n\n return {\n version,\n attribute,\n varyingVs,\n varyingFs,\n texture2D,\n output,\n defineOutput,\n defineSpecialNaN,\n defineSpecialInf,\n defineRound\n };\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {util} from '@tensorflow/tfjs-core';\n\n/**\n * Produces GLSL code that derives logical coordinates from a flat\n * index. The code performs integer division with each stride and decrements\n * the index until the index equals the final dimension coordinate.\n */\nexport function getLogicalCoordinatesFromFlatIndex(\n coords: string[], shape: number[], index = 'index'): string {\n const strides = util.computeStrides(shape);\n return strides\n .map((stride, i) => {\n const line1 = `int ${coords[i]} = ${index} / ${stride}`;\n const line2 = i === strides.length - 1 ?\n `int ${coords[i + 1]} = ${index} - ${coords[i]} * ${stride}` :\n `index -= ${coords[i]} * ${stride}`;\n return `${line1}; ${line2};`;\n })\n .join('');\n}\n\nfunction buildVec(x: string[]): string {\n if (x.length === 1) {\n return `${x[0]}`;\n }\n return `vec${x.length}(${x.join(',')})`;\n}\n\n/**\n * Produces GLSL code that computes the dot product of the input x and y\n * vectors. Handles splitting inputs into increments of vec4s when necessary.\n */\nexport function dotify(x: string[], y: string[]): string {\n if (x.length !== y.length) {\n throw new Error(\n `Vectors to be dotted must be of the same length -` +\n `got ${x.length} and ${y.length}`);\n }\n\n const slices: string[] = [];\n const nearestVec4 = Math.floor(x.length / 4);\n const nearestVec4Remainder = x.length % 4;\n\n for (let i = 0; i < nearestVec4; i++) {\n const xSlice = x.slice(i * 4, i * 4 + 4);\n const ySlice = y.slice(i * 4, i * 4 + 4);\n slices.push(`${buildVec(xSlice)}, ${buildVec(ySlice)}`);\n }\n\n if (nearestVec4Remainder !== 0) {\n let xSlice = x.slice(nearestVec4 * 4);\n let ySlice = y.slice(nearestVec4 * 4);\n if (xSlice.length === 1) {\n xSlice = xSlice.map(d => `float(${d})`);\n ySlice = ySlice.map(d => `float(${d})`);\n }\n slices.push(`${buildVec(xSlice)}, ${buildVec(ySlice)}`);\n }\n\n return slices.map((d, i) => `dot(${d})`).join('+');\n}\n\n/**\n * Produces GLSL that computes the flat index from 3D coordinates.\n */\nexport function getFlatIndexFrom3D(shape: [number, number, number]): string {\n const strides = util.computeStrides(shape).map(d => d.toString());\n\n return `\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${strides[0]} + coords.y * ${strides[1]} + coords.z;\n }\n`;\n}\n\nexport const ENCODE_FLOAT_SNIPPET = `\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`;\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\nimport {getDenseTexShape, PackingScheme} from './tex_util';\n\nexport class DecodeMatrixProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: [number, number, number];\n packedInputs = false;\n packedOutput = true;\n outPackingScheme = PackingScheme.DENSE;\n\n constructor(outputShape: [number, number, number]) {\n const texShape = getDenseTexShape(outputShape);\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n\n this.userCode = `\n ivec3 outCoordsFromFlatIndex(int index) {\n ${\n shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd'], outputShape)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = 4 * (resTexRC.x * ${texShape[1]} + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n ${glsl.output} = result;\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\nimport {getDenseTexShape, PackingScheme} from './tex_util';\n\nexport class DecodeMatrixPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n outputShape: [number, number, number];\n outPackingScheme = PackingScheme.DENSE;\n\n constructor(outputShape: [number, number, number]) {\n const texShape = getDenseTexShape(outputShape);\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n\n this.userCode = `\n ivec3 outCoordsFromFlatIndex(int index) {\n ${\n shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd'], outputShape)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = 4 * (resTexRC.x * ${texShape[1]} + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n ${glsl.output} = result;\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {ENCODE_FLOAT_SNIPPET} from './shader_compiler_util';\nimport {TextureUsage} from './tex_util';\n\nexport class EncodeFloatProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n outTexUsage = TextureUsage.DOWNLOAD;\n\n constructor(outputShape: number[]) {\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n this.userCode = `\n ${ENCODE_FLOAT_SNIPPET}\n\n void main() {\n float x = getAAtOutCoords();\n ${glsl.output} = encode_float(x);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {ENCODE_FLOAT_SNIPPET} from './shader_compiler_util';\nimport {TextureUsage} from './tex_util';\n\nexport class EncodeFloatPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n packedInputs = true;\n packedOutput = false;\n outTexUsage = TextureUsage.DOWNLOAD;\n\n constructor(outputShape: [number, number, number]) {\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n this.userCode = `\n ${ENCODE_FLOAT_SNIPPET}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${glsl.output} = encode_float(x);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\n\nexport class EncodeMatrixProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n\n constructor(\n outputShape: [number, number, number], texShape: [number, number],\n inputIsUnsignedByte = false) {\n const glsl = getGlslDifferences();\n const [height, width] = texShape;\n this.outputShape = outputShape;\n\n let output = `result`;\n if (inputIsUnsignedByte) {\n output = `floor(result * 255. + 0.5)`;\n }\n\n this.userCode = `\n ${shader_util.getFlatIndexFrom3D(outputShape)}\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 / ${width};\n int c = imod(flatIndex, ${width});\n vec2 uv = (vec2(c, r) + halfCR) / vec2(${width}.0, ${height}.0);\n vec4 values = ${glsl.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 ${glsl.output} = vec4(${output}, 0., 0., 0.);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\n\n/*\nThis is how the shader encodes a tensor with shape = [2, 3, 5]\n(indices are [batch, row, col]).\n\n000|001 002|003 004|xxx 020|021 022|023 024|xxx\n------- ------- ------- ------- ------- -------\n010|011 012|013 014|xxx xxx|xxx xxx|xxx xxx|xxx\n\n100|101 102|103 104|xxx 120|121 122|123 124|xxx\n------- ------- ------- ------- ------- -------\n110|111 112|113 114|xxx xxx|xxx xxx|xxx xxx|xxx\n\nSingle texels contain only values from the same batch, and from adjacent rows\nand columns.\n */\n\nexport class EncodeMatrixPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n packedInputs = false;\n packedOutput = true;\n\n constructor(\n outputShape: [number, number, number], texShape: [number, number],\n inputIsUnsignedByte = false) {\n const glsl = getGlslDifferences();\n const [height, width] = texShape;\n this.outputShape = outputShape;\n\n let mainLoop = '';\n let output = 'result';\n if (inputIsUnsignedByte) {\n output = 'floor(result * 255. + 0.5)';\n }\n\n for (let row = 0; row <= 1; row++) {\n for (let col = 0; col <= 1; col++) {\n const channel = row * 2 + col;\n\n mainLoop += `\n localCoords = coords;\n if(localCoords[2] + ${col} < ${outputShape[2]}) {\n localCoords[2] += ${col};\n if(localCoords[1] + ${row} < ${outputShape[1]}) {\n localCoords[1] += ${row};\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / ${width};\n c = imod(flatIndex, ${width});\n uv = (vec2(c, r) + halfCR) / vec2(${width}.0, ${height}.0);\n values = ${glsl.texture2D}(A, uv);\n\n if(offset == 0) {\n result[${channel}] = values[0];\n } else if(offset == 1) {\n result[${channel}] = values[1];\n } else if(offset == 2) {\n result[${channel}] = values[2];\n } else {\n result[${channel}] = values[3];\n }\n }\n }\n `;\n }\n }\n\n this.userCode = `\n ${shader_util.getFlatIndexFrom3D(outputShape)}\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 ${mainLoop}\n\n ${glsl.output} = ${output};\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {PixelData, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {getGlslDifferences} from './glsl_version';\nimport * as tex_util from './tex_util';\nimport {TextureConfig} from './tex_util';\nimport * as webgl_util from './webgl_util';\n\nexport function createVertexShader(gl: WebGLRenderingContext): WebGLShader {\n const glsl = getGlslDifferences();\n const vertexShaderSource = `${glsl.version}\n precision highp float;\n ${glsl.attribute} vec3 clipSpacePos;\n ${glsl.attribute} vec2 uv;\n ${glsl.varyingVs} vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }`;\n return webgl_util.createVertexShader(gl, vertexShaderSource);\n}\n\nexport function createVertexBuffer(gl: WebGLRenderingContext): WebGLBuffer {\n // [x y z u v] * [upper-left, lower-left, upper-right, lower-right]\n const vertexArray = new Float32Array(\n [-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);\n return webgl_util.createStaticVertexBuffer(gl, vertexArray);\n}\n\nexport function createIndexBuffer(gl: WebGLRenderingContext): WebGLBuffer {\n // OpenGL (and WebGL) have \"CCW == front\" winding\n const triangleVertexIndices = new Uint16Array([0, 1, 2, 2, 1, 3]);\n return webgl_util.createStaticIndexBuffer(gl, triangleVertexIndices);\n}\n\nfunction createAndConfigureTexture(\n gl: WebGLRenderingContext, width: number, height: number,\n internalFormat: number, textureFormat: number,\n textureType: number): WebGLTexture {\n webgl_util.validateTextureSize(width, height);\n const texture = webgl_util.createTexture(gl);\n\n const tex2d = gl.TEXTURE_2D;\n webgl_util.callAndCheck(gl, () => gl.bindTexture(tex2d, texture));\n webgl_util.callAndCheck(\n gl, () => gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE));\n webgl_util.callAndCheck(\n gl, () => gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE));\n webgl_util.callAndCheck(\n gl, () => gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST));\n webgl_util.callAndCheck(\n gl, () => gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST));\n webgl_util.callAndCheck(\n gl,\n () => gl.texImage2D(\n tex2d, 0, internalFormat, width, height, 0, textureFormat,\n textureType, null));\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, null));\n return texture;\n}\n\nexport function getInternalFormatForFloat32MatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.internalFormatFloat;\n}\n\nexport function createFloat32MatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height,\n getInternalFormatForFloat32MatrixTexture(textureConfig),\n textureConfig.textureFormatFloat, gl.FLOAT);\n}\n\nexport function getInternalFormatForFloat16MatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.internalFormatHalfFloat;\n}\n\nexport function createFloat16MatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height,\n getInternalFormatForFloat16MatrixTexture(textureConfig),\n textureConfig.textureFormatFloat, textureConfig.textureTypeHalfFloat);\n}\n\nexport function getInternalFormatForUnsignedBytesMatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.downloadTextureFormat;\n}\n\nexport function createUnsignedBytesMatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height,\n getInternalFormatForUnsignedBytesMatrixTexture(textureConfig), gl.RGBA,\n gl.UNSIGNED_BYTE);\n}\n\nexport function getInternalFormatForPackedMatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.internalFormatPackedFloat;\n}\n\nexport function createPackedMatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height, getInternalFormatForPackedMatrixTexture(textureConfig),\n gl.RGBA, gl.FLOAT);\n}\n\nexport function getInternalFormatForFloat16PackedMatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.internalFormatPackedHalfFloat;\n}\n\nexport function createFloat16PackedMatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height,\n getInternalFormatForFloat16PackedMatrixTexture(textureConfig), gl.RGBA,\n textureConfig.textureTypeHalfFloat);\n}\n\nexport function bindVertexProgramAttributeStreams(\n gl: WebGLRenderingContext, program: WebGLProgram,\n vertexBuffer: WebGLBuffer): boolean {\n const posOffset = 0; // x is the first buffer element\n const uvOffset = 3 * 4; // uv comes after [x y z]\n const stride = (3 * 4) + (2 * 4); // xyz + uv, each entry is 4-byte float.\n webgl_util.callAndCheck(\n gl, () => gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer));\n const success = webgl_util.bindVertexBufferToProgramAttribute(\n gl, program, 'clipSpacePos', vertexBuffer, 3, stride, posOffset);\n return success &&\n webgl_util.bindVertexBufferToProgramAttribute(\n gl, program, 'uv', vertexBuffer, 2, stride, uvOffset);\n}\n\nexport function uploadDenseMatrixToTexture(\n gl: WebGLRenderingContext, texture: WebGLTexture, width: number,\n height: number, data: TypedArray, textureConfig: TextureConfig) {\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, texture));\n\n let dataForUpload: TypedArray, texelDataType: number, internalFormat: number;\n if (data instanceof Uint8Array) {\n dataForUpload = new Uint8Array(width * height * 4);\n texelDataType = gl.UNSIGNED_BYTE;\n internalFormat = gl.RGBA;\n } else {\n dataForUpload = new Float32Array(width * height * 4);\n texelDataType = gl.FLOAT;\n internalFormat = textureConfig.internalFormatPackedFloat;\n }\n\n dataForUpload.set(data);\n\n webgl_util.callAndCheck(\n gl,\n () => gl.texImage2D(\n gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA,\n texelDataType, dataForUpload));\n\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, null));\n}\n\nexport function uploadPixelDataToTexture(\n gl: WebGLRenderingContext, texture: WebGLTexture,\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap) {\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, texture));\n if ((pixels as PixelData).data instanceof Uint8Array) {\n webgl_util.callAndCheck(\n gl,\n () => gl.texImage2D(\n gl.TEXTURE_2D, 0, gl.RGBA, pixels.width, pixels.height, 0, gl.RGBA,\n gl.UNSIGNED_BYTE, (pixels as PixelData).data));\n } else {\n webgl_util.callAndCheck(\n gl,\n () => gl.texImage2D(\n gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,\n pixels as ImageData | HTMLImageElement | HTMLCanvasElement |\n HTMLVideoElement|ImageBitmap));\n }\n\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, null));\n}\n\nexport function createBufferFromOutputTexture(\n gl2: WebGL2RenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLBuffer {\n // Create and bind the buffer.\n const buffer = gl2.createBuffer();\n webgl_util.callAndCheck(\n gl2, () => gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer));\n\n // Initialize the buffer to the size of the texture in bytes.\n const bytesPerFloat = 4;\n const valuesPerTexel = 4;\n const bufferSizeBytes = bytesPerFloat * valuesPerTexel * rows * columns;\n\n webgl_util.callAndCheck(\n gl2,\n () => gl2.bufferData(\n gl2.PIXEL_PACK_BUFFER, bufferSizeBytes, gl2.STREAM_READ));\n\n // Enqueue a command on the GPU command queue to copy of texture into the\n // buffer.\n webgl_util.callAndCheck(\n gl2, () => gl2.readPixels(0, 0, columns, rows, gl2.RGBA, gl2.FLOAT, 0));\n\n webgl_util.callAndCheck(\n gl2, () => gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null));\n\n return buffer;\n}\n\nexport function downloadFloat32MatrixFromBuffer(\n gl: WebGLRenderingContext, buffer: WebGLBuffer,\n size: number): Float32Array {\n const gl2 = gl as WebGL2RenderingContext;\n\n const downloadTarget = new Float32Array(size);\n\n gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);\n gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);\n gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);\n\n return downloadTarget;\n}\n\nexport function downloadByteEncodedFloatMatrixFromOutputTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig) {\n const [w, h] =\n tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);\n\n const numChannels = 4;\n const downloadTarget = new Uint8Array(\n tex_util.getUnpackedArraySizeFromMatrixSize(rows * columns, numChannels));\n\n webgl_util.callAndCheck(\n gl,\n () => gl.readPixels(\n 0, 0, w, h, textureConfig.downloadTextureFormat, gl.UNSIGNED_BYTE,\n downloadTarget));\n\n // By wrapping the buffer in a Float32Array, we use native browser IEEE 754\n // decoding of the 4 bytes that back each 32 bit float.\n return new Float32Array(downloadTarget.buffer);\n}\n\nexport function downloadPackedMatrixFromBuffer(\n gl: WebGLRenderingContext, buffer: WebGLBuffer, batch: number, rows: number,\n cols: number, physicalRows: number, physicalCols: number,\n textureConfig: TextureConfig): Float32Array {\n const gl2 = gl as WebGL2RenderingContext;\n\n const downloadTarget =\n new Float32Array(tex_util.getPackedRGBAArraySizeFromMatrixShape(\n physicalRows, physicalCols));\n\n gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);\n gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);\n gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);\n\n return downloadTarget;\n}\n\nexport function downloadMatrixFromPackedOutputTexture(\n gl: WebGLRenderingContext, physicalRows: number,\n physicalCols: number): Float32Array {\n const packedRGBA = new Float32Array(physicalRows * physicalCols * 4);\n webgl_util.callAndCheck(\n gl,\n () => gl.readPixels(\n 0, 0, physicalCols, physicalRows, gl.RGBA, gl.FLOAT, packedRGBA));\n\n return packedRGBA;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, PixelData, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {getWebGLContext, setWebGLContext} from './canvas_util';\nimport * as gpgpu_util from './gpgpu_util';\nimport * as tex_util from './tex_util';\nimport {TextureConfig} from './tex_util';\nimport {WebGL1DisjointQueryTimerExtension, WebGL2DisjointQueryTimerExtension} from './webgl_types';\nimport * as webgl_util from './webgl_util';\n\nexport interface FenceContext {\n query: WebGLQuery|WebGLSync;\n isFencePassed(): boolean;\n}\n\nexport class GPGPUContext {\n gl: WebGLRenderingContext;\n textureFloatExtension: {};\n textureHalfFloatExtension: {};\n colorBufferFloatExtension: {};\n colorBufferHalfFloatExtension: {};\n disjointQueryTimerExtension: WebGL2DisjointQueryTimerExtension|\n WebGL1DisjointQueryTimerExtension;\n vertexBuffer: WebGLBuffer;\n indexBuffer: WebGLBuffer;\n framebuffer: WebGLFramebuffer;\n outputTexture: WebGLTexture|null = null;\n program: WebGLProgram|null = null;\n private disposed = false;\n private disjoint: boolean;\n private vertexShader: WebGLShader;\n textureConfig: TextureConfig;\n\n constructor(gl?: WebGLRenderingContext) {\n const glVersion = env().getNumber('WEBGL_VERSION');\n if (gl != null) {\n this.gl = gl;\n setWebGLContext(glVersion, gl);\n } else {\n this.gl = getWebGLContext(glVersion);\n }\n // WebGL 2.0 enables texture floats without an extension.\n let COLOR_BUFFER_FLOAT = 'WEBGL_color_buffer_float';\n const COLOR_BUFFER_HALF_FLOAT = 'EXT_color_buffer_half_float';\n if (env().getNumber('WEBGL_VERSION') === 1) {\n const TEXTURE_FLOAT = 'OES_texture_float';\n const TEXTURE_HALF_FLOAT = 'OES_texture_half_float';\n\n this.textureFloatExtension =\n webgl_util.getExtensionOrThrow(this.gl, TEXTURE_FLOAT);\n if (webgl_util.hasExtension(this.gl, TEXTURE_HALF_FLOAT)) {\n this.textureHalfFloatExtension =\n webgl_util.getExtensionOrThrow(this.gl, TEXTURE_HALF_FLOAT);\n } else if (env().get('WEBGL_FORCE_F16_TEXTURES')) {\n throw new Error(\n 'GL context does not support half float textures, yet the ' +\n 'environment flag WEBGL_FORCE_F16_TEXTURES is set to true.');\n }\n\n this.colorBufferFloatExtension = this.gl.getExtension(COLOR_BUFFER_FLOAT);\n if (webgl_util.hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {\n this.colorBufferHalfFloatExtension =\n webgl_util.getExtensionOrThrow(this.gl, COLOR_BUFFER_HALF_FLOAT);\n } else if (env().get('WEBGL_FORCE_F16_TEXTURES')) {\n throw new Error(\n 'GL context does not support color renderable half floats, yet ' +\n 'the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.');\n }\n } else {\n COLOR_BUFFER_FLOAT = 'EXT_color_buffer_float';\n if (webgl_util.hasExtension(this.gl, COLOR_BUFFER_FLOAT)) {\n this.colorBufferFloatExtension =\n this.gl.getExtension(COLOR_BUFFER_FLOAT);\n } else if (webgl_util.hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {\n this.colorBufferHalfFloatExtension =\n this.gl.getExtension(COLOR_BUFFER_HALF_FLOAT);\n } else {\n throw new Error('GL context does not support color renderable floats');\n }\n }\n\n this.vertexBuffer = gpgpu_util.createVertexBuffer(this.gl);\n this.indexBuffer = gpgpu_util.createIndexBuffer(this.gl);\n this.framebuffer = webgl_util.createFramebuffer(this.gl);\n\n this.textureConfig =\n tex_util.getTextureConfig(this.gl, this.textureHalfFloatExtension);\n }\n\n private get debug(): boolean {\n return env().getBool('DEBUG');\n }\n\n public dispose() {\n if (this.disposed) {\n return;\n }\n if (this.program != null) {\n console.warn(\n 'Disposing a GPGPUContext that still has a bound WebGLProgram.' +\n ' This is probably a resource leak, delete the program with ' +\n 'GPGPUContext.deleteProgram before disposing.');\n }\n if (this.outputTexture != null) {\n console.warn(\n 'Disposing a GPGPUContext that still has a bound output matrix ' +\n 'texture. This is probably a resource leak, delete the output ' +\n 'matrix texture with GPGPUContext.deleteMatrixTexture before ' +\n 'disposing.');\n }\n const gl = this.gl;\n webgl_util.callAndCheck(gl, () => gl.finish());\n webgl_util.callAndCheck(gl, () => gl.bindFramebuffer(gl.FRAMEBUFFER, null));\n webgl_util.callAndCheck(gl, () => gl.deleteFramebuffer(this.framebuffer));\n webgl_util.callAndCheck(gl, () => gl.bindBuffer(gl.ARRAY_BUFFER, null));\n webgl_util.callAndCheck(\n gl, () => gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null));\n webgl_util.callAndCheck(gl, () => gl.deleteBuffer(this.indexBuffer));\n this.disposed = true;\n }\n\n public createFloat32MatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createFloat32MatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public createFloat16MatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createFloat16MatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public createUnsignedBytesMatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createUnsignedBytesMatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public uploadPixelDataToTexture(\n texture: WebGLTexture,\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n ImageBitmap) {\n this.throwIfDisposed();\n gpgpu_util.uploadPixelDataToTexture(this.gl, texture, pixels);\n }\n\n public uploadDenseMatrixToTexture(\n texture: WebGLTexture, width: number, height: number, data: TypedArray) {\n this.throwIfDisposed();\n gpgpu_util.uploadDenseMatrixToTexture(\n this.gl, texture, width, height, data, this.textureConfig);\n }\n\n public createFloat16PackedMatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createFloat16PackedMatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public createPackedMatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createPackedMatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public deleteMatrixTexture(texture: WebGLTexture) {\n this.throwIfDisposed();\n if (this.outputTexture === texture) {\n webgl_util.unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);\n this.outputTexture = null;\n }\n webgl_util.callAndCheck(this.gl, () => this.gl.deleteTexture(texture));\n }\n\n public downloadByteEncodedFloatMatrixFromOutputTexture(\n texture: WebGLTexture, rows: number, columns: number): Float32Array {\n return this.downloadMatrixDriver(\n texture,\n () => gpgpu_util.downloadByteEncodedFloatMatrixFromOutputTexture(\n this.gl, rows, columns, this.textureConfig));\n }\n\n public downloadPackedMatrixFromBuffer(\n buffer: WebGLBuffer, batch: number, rows: number, columns: number,\n physicalRows: number, physicalCols: number): Float32Array {\n return gpgpu_util.downloadPackedMatrixFromBuffer(\n this.gl, buffer, batch, rows, columns, physicalRows, physicalCols,\n this.textureConfig);\n }\n\n public downloadFloat32MatrixFromBuffer(buffer: WebGLBuffer, size: number):\n Float32Array {\n return gpgpu_util.downloadFloat32MatrixFromBuffer(this.gl, buffer, size);\n }\n\n public createBufferFromTexture(\n texture: WebGLTexture, rows: number, columns: number): WebGLBuffer {\n this.bindTextureToFrameBuffer(texture);\n const result = gpgpu_util.createBufferFromOutputTexture(\n this.gl as WebGL2RenderingContext, rows, columns, this.textureConfig);\n this.unbindTextureToFrameBuffer();\n return result;\n }\n\n public createAndWaitForFence(): Promise {\n const fenceContext = this.createFence(this.gl);\n return this.pollFence(fenceContext);\n }\n\n private createFence(gl: WebGLRenderingContext): FenceContext {\n let query: WebGLQuery|WebGLSync;\n let isFencePassed: () => boolean;\n\n if (env().getBool('WEBGL_FENCE_API_ENABLED')) {\n const gl2 = gl as WebGL2RenderingContext;\n\n const sync = gl2.fenceSync(gl2.SYNC_GPU_COMMANDS_COMPLETE, 0);\n gl.flush();\n\n isFencePassed = () => {\n const status = gl2.clientWaitSync(sync, 0, 0);\n return status === gl2.ALREADY_SIGNALED ||\n status === gl2.CONDITION_SATISFIED;\n };\n\n query = sync;\n } else if (\n env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0) {\n query = this.beginQuery();\n this.endQuery();\n isFencePassed = () => this.isQueryAvailable(\n query,\n env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION'));\n } else {\n // If we have no way to fence, return true immediately. This will fire in\n // WebGL 1.0 when there is no disjoint query timer. In this case, because\n // the fence passes immediately, we'll immediately ask for a download of\n // the texture, which will cause the UI thread to hang.\n isFencePassed = () => true;\n }\n\n return {query, isFencePassed};\n }\n\n public downloadMatrixFromPackedTexture(\n texture: WebGLTexture, physicalRows: number,\n physicalCols: number): Float32Array {\n return this.downloadMatrixDriver(\n texture,\n () => gpgpu_util.downloadMatrixFromPackedOutputTexture(\n this.gl, physicalRows, physicalCols));\n }\n\n private vertexAttrsAreBound = false;\n\n public createProgram(fragmentShaderSource: string): WebGLProgram {\n this.throwIfDisposed();\n const gl = this.gl;\n const fragmentShader: WebGLShader =\n webgl_util.createFragmentShader(gl, fragmentShaderSource);\n if (this.vertexShader == null) {\n this.vertexShader = gpgpu_util.createVertexShader(gl);\n }\n const program: WebGLProgram = webgl_util.createProgram(gl);\n webgl_util.callAndCheck(\n gl, () => gl.attachShader(program, this.vertexShader));\n webgl_util.callAndCheck(gl, () => gl.attachShader(program, fragmentShader));\n webgl_util.linkProgram(gl, program);\n if (this.debug) {\n webgl_util.validateProgram(gl, program);\n }\n if (!this.vertexAttrsAreBound) {\n this.setProgram(program);\n this.vertexAttrsAreBound = gpgpu_util.bindVertexProgramAttributeStreams(\n gl, this.program, this.vertexBuffer);\n }\n return program;\n }\n\n public deleteProgram(program: WebGLProgram) {\n this.throwIfDisposed();\n if (program === this.program) {\n this.program = null;\n }\n if (program != null) {\n webgl_util.callAndCheck(this.gl, () => this.gl.deleteProgram(program));\n }\n }\n\n public setProgram(program: WebGLProgram|null) {\n this.throwIfDisposed();\n this.program = program;\n if ((this.program != null) && this.debug) {\n webgl_util.validateProgram(this.gl, this.program);\n }\n webgl_util.callAndCheck(this.gl, () => this.gl.useProgram(program));\n }\n\n public getUniformLocation(\n program: WebGLProgram, uniformName: string,\n shouldThrow = true): WebGLUniformLocation {\n this.throwIfDisposed();\n if (shouldThrow) {\n return webgl_util.getProgramUniformLocationOrThrow(\n this.gl, program, uniformName);\n } else {\n return webgl_util.getProgramUniformLocation(\n this.gl, program, uniformName);\n }\n }\n\n public getAttributeLocation(program: WebGLProgram, attribute: string):\n number {\n this.throwIfDisposed();\n return webgl_util.callAndCheck(\n this.gl, () => this.gl.getAttribLocation(program, attribute));\n }\n\n public getUniformLocationNoThrow(program: WebGLProgram, uniformName: string):\n WebGLUniformLocation {\n this.throwIfDisposed();\n return this.gl.getUniformLocation(program, uniformName);\n }\n\n public setInputMatrixTexture(\n inputMatrixTexture: WebGLTexture, uniformLocation: WebGLUniformLocation,\n textureUnit: number) {\n this.throwIfDisposed();\n this.throwIfNoProgram();\n webgl_util.bindTextureToProgramUniformSampler(\n this.gl, inputMatrixTexture, uniformLocation, textureUnit);\n }\n\n public setOutputMatrixTexture(\n outputMatrixTexture: WebGLTexture, rows: number, columns: number) {\n this.setOutputMatrixTextureDriver(outputMatrixTexture, columns, rows);\n }\n\n public setOutputPackedMatrixTexture(\n outputPackedMatrixTexture: WebGLTexture, rows: number, columns: number) {\n this.throwIfDisposed();\n const [width, height] =\n tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns);\n this.setOutputMatrixTextureDriver(outputPackedMatrixTexture, width, height);\n }\n\n public setOutputMatrixWriteRegion(\n startRow: number, numRows: number, startColumn: number,\n numColumns: number) {\n this.setOutputMatrixWriteRegionDriver(\n startColumn, startRow, numColumns, numRows);\n }\n\n public setOutputPackedMatrixWriteRegion(\n startRow: number, numRows: number, startColumn: number,\n numColumns: number) {\n throw new Error('setOutputPackedMatrixWriteRegion not implemented.');\n }\n\n public debugValidate() {\n if (this.program != null) {\n webgl_util.validateProgram(this.gl, this.program);\n }\n webgl_util.validateFramebuffer(this.gl);\n }\n\n public executeProgram() {\n this.throwIfDisposed();\n this.throwIfNoProgram();\n const gl = this.gl;\n if (this.debug) {\n this.debugValidate();\n }\n webgl_util.callAndCheck(\n gl, () => gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0));\n }\n\n public blockUntilAllProgramsCompleted() {\n this.throwIfDisposed();\n webgl_util.callAndCheck(this.gl, () => this.gl.finish());\n }\n\n private getQueryTimerExtension(): WebGL1DisjointQueryTimerExtension\n |WebGL2DisjointQueryTimerExtension {\n if (this.disjointQueryTimerExtension == null) {\n this.disjointQueryTimerExtension =\n webgl_util.getExtensionOrThrow(\n this.gl,\n env().getNumber(\n 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2 ?\n 'EXT_disjoint_timer_query_webgl2' :\n 'EXT_disjoint_timer_query') as\n WebGL1DisjointQueryTimerExtension |\n WebGL2DisjointQueryTimerExtension;\n }\n return this.disjointQueryTimerExtension;\n }\n\n private getQueryTimerExtensionWebGL2(): WebGL2DisjointQueryTimerExtension {\n return this.getQueryTimerExtension();\n }\n\n private getQueryTimerExtensionWebGL1(): WebGL1DisjointQueryTimerExtension {\n return this.getQueryTimerExtension() as WebGL1DisjointQueryTimerExtension;\n }\n\n beginQuery(): WebGLQuery {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2) {\n const gl2 = this.gl as WebGL2RenderingContext;\n const ext = this.getQueryTimerExtensionWebGL2();\n\n const query = gl2.createQuery();\n gl2.beginQuery(ext.TIME_ELAPSED_EXT, query);\n return query;\n }\n const ext = this.getQueryTimerExtensionWebGL1();\n const query = ext.createQueryEXT() as WebGLQuery;\n ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, query);\n return query;\n }\n\n endQuery() {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2) {\n const gl2 = this.gl as WebGL2RenderingContext;\n const ext = this.getQueryTimerExtensionWebGL2();\n gl2.endQuery(ext.TIME_ELAPSED_EXT);\n return;\n }\n const ext = this.getQueryTimerExtensionWebGL1();\n ext.endQueryEXT(ext.TIME_ELAPSED_EXT);\n }\n\n public async waitForQueryAndGetTime(query: WebGLQuery): Promise {\n await util.repeatedTry(\n () => this.disposed || // while testing contexts are created / disposed\n // in rapid succession, so without this check we\n // may poll for the query timer indefinitely\n this.isQueryAvailable(\n query,\n env().getNumber(\n 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION')));\n return this.getQueryTime(\n query, env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION'));\n }\n\n private getQueryTime(query: WebGLQuery, queryTimerVersion: number): number {\n if (queryTimerVersion === 0) {\n return null;\n }\n\n if (queryTimerVersion === 2) {\n const gl2 = this.gl as WebGL2RenderingContext;\n\n const timeElapsedNanos = gl2.getQueryParameter(query, gl2.QUERY_RESULT);\n // Return milliseconds.\n return timeElapsedNanos / 1000000;\n } else {\n const ext = this.getQueryTimerExtensionWebGL1();\n\n const timeElapsedNanos =\n ext.getQueryObjectEXT(query, ext.QUERY_RESULT_EXT);\n // Return milliseconds.\n return timeElapsedNanos / 1000000;\n }\n }\n\n private isQueryAvailable(query: WebGLQuery, queryTimerVersion: number):\n boolean {\n if (queryTimerVersion === 0) {\n return true;\n }\n\n if (queryTimerVersion === 2) {\n const gl2 = this.gl as WebGL2RenderingContext;\n const ext = this.getQueryTimerExtensionWebGL2();\n\n const available =\n gl2.getQueryParameter(query, gl2.QUERY_RESULT_AVAILABLE);\n if (this.disjoint == null) {\n this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);\n }\n\n return available && !this.disjoint;\n } else {\n const ext = this.getQueryTimerExtensionWebGL1();\n\n const available =\n ext.getQueryObjectEXT(query, ext.QUERY_RESULT_AVAILABLE_EXT);\n if (this.disjoint == null) {\n this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);\n }\n\n return available && !this.disjoint;\n }\n }\n\n pollFence(fenceContext: FenceContext) {\n return new Promise(resolve => {\n this.addItemToPoll(() => fenceContext.isFencePassed(), () => resolve());\n });\n }\n\n private itemsToPoll: PollItem[] = [];\n\n pollItems(): void {\n // Find the last query that has finished.\n const index = linearSearchLastTrue(this.itemsToPoll.map(x => x.isDoneFn));\n for (let i = 0; i <= index; ++i) {\n const {resolveFn} = this.itemsToPoll[i];\n resolveFn();\n }\n this.itemsToPoll = this.itemsToPoll.slice(index + 1);\n }\n\n private addItemToPoll(isDoneFn: () => boolean, resolveFn: () => void) {\n this.itemsToPoll.push({isDoneFn, resolveFn});\n if (this.itemsToPoll.length > 1) {\n // We already have a running loop that polls.\n return;\n }\n // Start a new loop that polls.\n util.repeatedTry(() => {\n this.pollItems();\n // End the loop if no more items to poll.\n return this.itemsToPoll.length === 0;\n });\n }\n\n private bindTextureToFrameBuffer(texture: WebGLTexture) {\n this.throwIfDisposed();\n webgl_util.bindColorTextureToFramebuffer(\n this.gl, texture, this.framebuffer);\n if (this.debug) {\n webgl_util.validateFramebuffer(this.gl);\n }\n }\n\n private unbindTextureToFrameBuffer() {\n if (this.outputTexture != null) {\n webgl_util.bindColorTextureToFramebuffer(\n this.gl, this.outputTexture, this.framebuffer);\n if (this.debug) {\n webgl_util.validateFramebuffer(this.gl);\n }\n } else {\n webgl_util.unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);\n }\n }\n\n private downloadMatrixDriver(\n texture: WebGLTexture,\n downloadAndDecode: () => Float32Array): Float32Array {\n this.bindTextureToFrameBuffer(texture);\n const result = downloadAndDecode();\n this.unbindTextureToFrameBuffer();\n\n return result;\n }\n\n private setOutputMatrixTextureDriver(\n outputMatrixTextureMaybePacked: WebGLTexture, width: number,\n height: number) {\n this.throwIfDisposed();\n const gl = this.gl;\n webgl_util.bindColorTextureToFramebuffer(\n gl, outputMatrixTextureMaybePacked, this.framebuffer);\n if (this.debug) {\n webgl_util.validateFramebuffer(gl);\n }\n this.outputTexture = outputMatrixTextureMaybePacked;\n webgl_util.callAndCheck(gl, () => gl.viewport(0, 0, width, height));\n webgl_util.callAndCheck(gl, () => gl.scissor(0, 0, width, height));\n }\n\n private setOutputMatrixWriteRegionDriver(\n x: number, y: number, width: number, height: number) {\n this.throwIfDisposed();\n webgl_util.callAndCheck(\n this.gl, () => this.gl.scissor(x, y, width, height));\n }\n\n private throwIfDisposed() {\n if (this.disposed) {\n throw new Error('Attempted to use disposed GPGPUContext.');\n }\n }\n\n private throwIfNoProgram() {\n if (this.program == null) {\n throw new Error('No GPU program is currently set.');\n }\n }\n}\n\ntype PollItem = {\n isDoneFn: () => boolean,\n resolveFn: () => void\n};\n\n/**\n * Finds the index of the last true element using linear search.\n * Note: We can't do binary search because Chrome expects us to explicitly\n * test all fences before download:\n * https://github.com/tensorflow/tfjs/issues/1145\n */\nexport function linearSearchLastTrue(arr: Array<() => boolean>): number {\n let i = 0;\n for (; i < arr.length; ++i) {\n const isDone = arr[i]();\n if (!isDone) {\n break;\n }\n }\n return i - 1;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, util} from '@tensorflow/tfjs-core';\nconst {getBroadcastDims} = backend_util;\nimport {getGlslDifferences, GLSL} from './glsl_version';\nimport * as shader_util from './shader_compiler_util';\n\nexport type ShapeInfo = {\n logicalShape: number[],\n texShape: [number, number],\n isUniform: boolean,\n isPacked: boolean,\n flatOffset: number\n};\n\nexport type InputInfo = {\n name: string,\n shapeInfo: ShapeInfo\n};\n\nexport function makeShader(\n inputsInfo: InputInfo[], outputShape: ShapeInfo, userCode: string,\n usesPackedTextures: boolean): string {\n const prefixSnippets: string[] = [];\n inputsInfo.forEach(x => {\n const size = util.sizeFromShape(x.shapeInfo.logicalShape);\n\n // Snippet when we decided to upload the values as uniform.\n if (x.shapeInfo.isUniform) {\n prefixSnippets.push(\n `uniform float ${x.name}${size > 1 ? `[${size}]` : ''};`);\n } else {\n prefixSnippets.push(`uniform sampler2D ${x.name};`);\n prefixSnippets.push(`uniform int offset${x.name};`);\n }\n });\n const inputPrefixSnippet = prefixSnippets.join('\\n');\n\n const inputSamplingSnippet =\n inputsInfo\n .map(x => getInputSamplingSnippet(x, outputShape, usesPackedTextures))\n .join('\\n');\n const outTexShape = outputShape.texShape;\n const glsl = getGlslDifferences();\n const floatTextureSampleSnippet = getFloatTextureSampleSnippet(glsl);\n let outputSamplingSnippet: string;\n let floatTextureSetOutputSnippet: string;\n let shaderPrefix = getShaderPrefix(glsl);\n\n if (outputShape.isPacked) {\n outputSamplingSnippet =\n getPackedOutputSamplingSnippet(outputShape.logicalShape, outTexShape);\n floatTextureSetOutputSnippet = getFloatTextureSetRGBASnippet(glsl);\n } else {\n outputSamplingSnippet =\n getOutputSamplingSnippet(outputShape.logicalShape, outTexShape);\n floatTextureSetOutputSnippet = getFloatTextureSetRSnippet(glsl);\n }\n\n if (usesPackedTextures) {\n shaderPrefix += SHADER_PACKED_PREFIX;\n }\n\n const source = [\n shaderPrefix, floatTextureSampleSnippet, floatTextureSetOutputSnippet,\n inputPrefixSnippet, outputSamplingSnippet, inputSamplingSnippet, userCode\n ].join('\\n');\n return source;\n}\n\nfunction getSamplerFromInInfo(inInfo: InputInfo): string {\n const shape = inInfo.shapeInfo.logicalShape;\n switch (shape.length) {\n case 0:\n return getSamplerScalar(inInfo);\n case 1:\n return getSampler1D(inInfo);\n case 2:\n return getSampler2D(inInfo);\n case 3:\n return getSampler3D(inInfo);\n case 4:\n return getSampler4D(inInfo);\n case 5:\n return getSampler5D(inInfo);\n case 6:\n return getSampler6D(inInfo);\n default:\n throw new Error(\n `${shape.length}-D input sampling` +\n ` is not yet supported`);\n }\n}\n\nfunction getPackedSamplerFromInInfo(inInfo: InputInfo): string {\n const shape = inInfo.shapeInfo.logicalShape;\n switch (shape.length) {\n case 0:\n return getPackedSamplerScalar(inInfo);\n case 1:\n return getPackedSampler1D(inInfo);\n case 2:\n return getPackedSampler2D(inInfo);\n case 3:\n return getPackedSampler3D(inInfo);\n default:\n return getPackedSamplerND(inInfo);\n }\n}\n\nfunction getInputSamplingSnippet(\n inInfo: InputInfo, outShapeInfo: ShapeInfo,\n usesPackedTextures = false): string {\n let res = '';\n if (usesPackedTextures) {\n res += getPackedSamplerFromInInfo(inInfo);\n } else {\n res += getSamplerFromInInfo(inInfo);\n }\n\n const inShape = inInfo.shapeInfo.logicalShape;\n const outShape = outShapeInfo.logicalShape;\n if (inShape.length <= outShape.length) {\n if (usesPackedTextures) {\n res += getPackedSamplerAtOutputCoords(inInfo, outShapeInfo);\n } else {\n res += getSamplerAtOutputCoords(inInfo, outShapeInfo);\n }\n }\n return res;\n}\n\nfunction getPackedOutputSamplingSnippet(\n outShape: number[], outTexShape: [number, number]): string {\n switch (outShape.length) {\n case 0:\n return getOutputScalarCoords();\n case 1:\n return getOutputPacked1DCoords(outShape as [number], outTexShape);\n case 2:\n return getOutputPacked2DCoords(outShape as [number, number], outTexShape);\n case 3:\n return getOutputPacked3DCoords(\n outShape as [number, number, number], outTexShape);\n default:\n return getOutputPackedNDCoords(outShape, outTexShape);\n }\n}\n\nfunction getOutputSamplingSnippet(\n outShape: number[], outTexShape: [number, number]): string {\n switch (outShape.length) {\n case 0:\n return getOutputScalarCoords();\n case 1:\n return getOutput1DCoords(outShape as [number], outTexShape);\n case 2:\n return getOutput2DCoords(outShape as [number, number], outTexShape);\n case 3:\n return getOutput3DCoords(\n outShape as [number, number, number], outTexShape);\n case 4:\n return getOutput4DCoords(\n outShape as [number, number, number, number], outTexShape);\n case 5:\n return getOutput5DCoords(\n outShape as [number, number, number, number, number], outTexShape);\n case 6:\n return getOutput6DCoords(\n outShape as [number, number, number, number, number, number],\n outTexShape);\n default:\n throw new Error(\n `${outShape.length}-D output sampling is not yet supported`);\n }\n}\n\nfunction getFloatTextureSampleSnippet(glsl: GLSL): string {\n return `\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${glsl.texture2D}(textureSampler, uv).r;\n }\n `;\n}\n\nfunction getFloatTextureSetRSnippet(glsl: GLSL): string {\n return `\n void setOutput(float val) {\n ${glsl.output} = vec4(val, 0, 0, 0);\n }\n `;\n}\n\nfunction getFloatTextureSetRGBASnippet(glsl: GLSL): string {\n return `\n void setOutput(vec4 val) {\n ${glsl.output} = val;\n }\n `;\n}\n\nfunction getShaderPrefix(glsl: GLSL): string {\n const SHADER_PREFIX = `${glsl.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${glsl.varyingFs} vec2 resultUV;\n ${glsl.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 ${glsl.defineSpecialNaN}\n ${glsl.defineSpecialInf}\n ${glsl.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 ${SAMPLE_1D_SNIPPET}\n ${SAMPLE_2D_SNIPPET}\n ${SAMPLE_3D_SNIPPET}\n `;\n\n return SHADER_PREFIX;\n}\n\nconst SAMPLE_1D_SNIPPET = `\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n`;\n\nconst SAMPLE_2D_SNIPPET = `\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n`;\n\nconst SAMPLE_3D_SNIPPET = `\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n`;\n\nconst SHADER_PACKED_PREFIX = `\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n`;\n\nfunction getOutputScalarCoords() {\n return `\n int getOutputCoords() {\n return 0;\n }\n `;\n}\n\nfunction getOutputPacked1DCoords(\n shape: [number], texShape: [number, number]): string {\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n if (packedTexShape[0] === 1) {\n return `\n int getOutputCoords() {\n return 2 * int(resultUV.x * ${packedTexShape[1]}.0);\n }\n `;\n }\n\n if (packedTexShape[1] === 1) {\n return `\n int getOutputCoords() {\n return 2 * int(resultUV.y * ${packedTexShape[0]}.0);\n }\n `;\n }\n\n return `\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${packedTexShape[0]}, ${packedTexShape[1]}));\n return 2 * (resTexRC.x * ${packedTexShape[1]} + resTexRC.y);\n }\n `;\n}\n\nfunction getOutput1DCoords(\n shape: [number], texShape: [number, number]): string {\n if (texShape[0] === 1) {\n return `\n int getOutputCoords() {\n return int(resultUV.x * ${texShape[1]}.0);\n }\n `;\n }\n if (texShape[1] === 1) {\n return `\n int getOutputCoords() {\n return int(resultUV.y * ${texShape[0]}.0);\n }\n `;\n }\n return `\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n return resTexRC.x * ${texShape[1]} + resTexRC.y;\n }\n `;\n}\n\nfunction getOutputPacked3DCoords(\n shape: [number, number, number], texShape: [number, number]): string {\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n const texelsInLogicalRow = Math.ceil(shape[2] / 2);\n const texelsInBatch = texelsInLogicalRow * Math.ceil(shape[1] / 2);\n\n return `\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${packedTexShape[0]}, ${packedTexShape[1]}));\n int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;\n\n int b = index / ${texelsInBatch};\n index -= b * ${texelsInBatch};\n\n int r = 2 * (index / ${texelsInLogicalRow});\n int c = imod(index, ${texelsInLogicalRow}) * 2;\n\n return ivec3(b, r, c);\n }\n `;\n}\n\nfunction getOutput3DCoords(\n shape: [number, number, number], texShape: [number, number]): string {\n const coordsFromIndexSnippet =\n shader_util.getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd'], shape);\n\n return `\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n ${coordsFromIndexSnippet}\n return ivec3(r, c, d);\n }\n `;\n}\n\nfunction getOutputPackedNDCoords(\n shape: number[], texShape: [number, number]): string {\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n\n const texelsInLogicalRow = Math.ceil(shape[shape.length - 1] / 2);\n const texelsInBatch =\n texelsInLogicalRow * Math.ceil(shape[shape.length - 2] / 2);\n let texelsInBatchN = texelsInBatch;\n let batches = ``;\n let coords = 'b, r, c';\n\n for (let b = 2; b < shape.length - 1; b++) {\n texelsInBatchN *= shape[shape.length - b - 1];\n batches = `\n int b${b} = index / ${texelsInBatchN};\n index -= b${b} * ${texelsInBatchN};\n ` + batches;\n coords = `b${b}, ` + coords;\n }\n\n return `\n ivec${shape.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${packedTexShape[0]}, ${packedTexShape[1]}));\n int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;\n\n ${batches}\n\n int b = index / ${texelsInBatch};\n index -= b * ${texelsInBatch};\n\n int r = 2 * (index / ${texelsInLogicalRow});\n int c = imod(index, ${texelsInLogicalRow}) * 2;\n\n return ivec${shape.length}(${coords});\n }\n `;\n}\n\nfunction getOutput4DCoords(\n shape: [number, number, number, number],\n texShape: [number, number]): string {\n const coordsFromIndexSnippet = shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd', 'd2'], shape);\n\n return `\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n ${coordsFromIndexSnippet}\n return ivec4(r, c, d, d2);\n }\n `;\n}\n\nfunction getOutput5DCoords(\n shape: [number, number, number, number, number],\n texShape: [number, number]): string {\n const coordsFromIndexSnippet = shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd', 'd2', 'd3'], shape);\n\n return `\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(${texShape[0]},\n ${texShape[1]}));\n\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n\n ${coordsFromIndexSnippet}\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n `;\n}\n\nfunction getOutput6DCoords(\n shape: [number, number, number, number, number, number],\n texShape: [number, number]): string {\n const coordsFromIndexSnippet = shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd', 'd2', 'd3', 'd4'], shape);\n\n return `\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n\n ${coordsFromIndexSnippet}\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n `;\n}\n\nfunction getOutputPacked2DCoords(\n shape: [number, number], texShape: [number, number]): string {\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n if (util.arraysEqual(shape, texShape)) {\n return `\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(${packedTexShape[0]}, ${\n packedTexShape[1]}));\n }\n `;\n }\n\n // texels needed to accommodate a logical row\n const texelsInLogicalRow = Math.ceil(shape[1] / 2);\n\n /**\n * getOutputCoords\n *\n * resTexRC: The rows and columns of the texels. If you move over one\n * texel to the right in the packed texture, you are moving over one column\n * (not two).\n *\n * index: The texel index\n */\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${packedTexShape[0]}, ${packedTexShape[1]}));\n\n int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;\n int r = 2 * (index / ${texelsInLogicalRow});\n int c = imod(index, ${texelsInLogicalRow}) * 2;\n\n return ivec2(r, c);\n }\n `;\n}\n\nfunction getOutput2DCoords(\n shape: [number, number], texShape: [number, number]): string {\n if (util.arraysEqual(shape, texShape)) {\n return `\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(${texShape[0]}, ${texShape[1]}));\n }\n `;\n }\n if (shape[1] === 1) {\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n return ivec2(index, 0);\n }\n `;\n }\n if (shape[0] === 1) {\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n return ivec2(0, index);\n }\n `;\n }\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n int r = index / ${shape[1]};\n int c = index - r * ${shape[1]};\n return ivec2(r, c);\n }\n `;\n}\n\nfunction getFlatOffsetUniformName(texName: string): string {\n return `offset${texName}`;\n}\n\nfunction getPackedSamplerScalar(inputInfo: InputInfo): string {\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const glsl = getGlslDifferences();\n return `\n vec4 ${funcName}() {\n return ${glsl.texture2D}(${texName}, halfCR);\n }\n `;\n}\n\nfunction getSamplerScalar(inputInfo: InputInfo): string {\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n if (inputInfo.shapeInfo.isUniform) {\n return `float ${funcName}() {return ${texName};}`;\n }\n const [texNumR, texNumC] = inputInfo.shapeInfo.texShape;\n if (texNumR === 1 && texNumC === 1) {\n return `\n float ${funcName}() {\n return sampleTexture(${texName}, halfCR);\n }\n `;\n }\n\n const [tNumR, tNumC] = inputInfo.shapeInfo.texShape;\n const offset = getFlatOffsetUniformName(texName);\n return `\n float ${funcName}() {\n vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, ${offset});\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getPackedSampler1D(inputInfo: InputInfo): string {\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const texShape = inputInfo.shapeInfo.texShape;\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n const glsl = getGlslDifferences();\n\n return `\n vec4 ${funcName}(int index) {\n vec2 uv = packedUVfrom1D(\n ${packedTexShape[0]}, ${packedTexShape[1]}, index);\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler1D(inputInfo: InputInfo): string {\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int index) {\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const texShape = inputInfo.shapeInfo.texShape;\n const tNumR = texShape[0];\n const tNumC = texShape[1];\n\n if (tNumC === 1 && tNumR === 1) {\n return `\n float ${funcName}(int index) {\n return sampleTexture(${texName}, halfCR);\n }\n `;\n }\n const offset = getFlatOffsetUniformName(texName);\n if (tNumC === 1) {\n return `\n float ${funcName}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${offset}) + 0.5) / ${tNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n if (tNumR === 1) {\n return `\n float ${funcName}(int index) {\n vec2 uv = vec2((float(index + ${offset}) + 0.5) / ${tNumC}.0, 0.5);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int index) {\n vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, index + ${offset});\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getPackedSampler2D(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const texShape = inputInfo.shapeInfo.texShape;\n\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n const glsl = getGlslDifferences();\n if (texShape != null && util.arraysEqual(shape, texShape)) {\n return `\n vec4 ${funcName}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);\n\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n }\n\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n const valuesPerRow = Math.ceil(shape[1] / 2);\n\n return `\n vec4 ${funcName}(int row, int col) {\n vec2 uv = packedUVfrom2D(${valuesPerRow}, ${packedTexShape[0]}, ${\n packedTexShape[1]}, row, col);\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler2D(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const texShape = inputInfo.shapeInfo.texShape;\n\n if (texShape != null && util.arraysEqual(shape, texShape)) {\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n return `\n float ${funcName}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n const squeezedShape = newShape;\n if (squeezedShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);\n const params = ['row', 'col'];\n return `\n ${getSamplerFromInInfo(newInputInfo)}\n float ${funcName}(int row, int col) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col) {\n int index = round(dot(vec2(row, col), vec2(${shape[1]}, 1)));\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n const offset = getFlatOffsetUniformName(texName);\n if (texNumC === 1) {\n // index is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col) {\n float index = dot(vec3(row, col, ${offset}), vec3(${shape[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n if (texNumR === 1) {\n // index is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col) {\n float index = dot(vec3(row, col, ${offset}), vec3(${shape[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${texNumC}.0, 0.5);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n return `\n float ${funcName}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${shape[1]} + col + ${offset};\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);\n return sampleTexture(${texName}, uv);\n }\n`;\n}\n\nfunction getPackedSampler3D(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const texShape = inputInfo.shapeInfo.texShape;\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n\n if (shape[0] === 1) {\n const squeezedShape = shape.slice(1);\n const keptDims = [1, 2];\n const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);\n const params = ['b', 'row', 'col'];\n return `\n ${getPackedSamplerFromInInfo(newInputInfo)}\n vec4 ${funcName}(int b, int row, int col) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n const texNumR = packedTexShape[0];\n const texNumC = packedTexShape[1];\n\n const valuesPerRow = Math.ceil(shape[2] / 2);\n const texelsInBatch = valuesPerRow * Math.ceil(shape[1] / 2);\n const glsl = getGlslDifferences();\n\n return `\n vec4 ${funcName}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${texNumR}, ${texNumC}, ${texelsInBatch}, ${valuesPerRow}, b, row, col);\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler3D(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const stride0 = shape[1] * shape[2];\n const stride1 = shape[2];\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n const squeezedShape = newShape;\n if (squeezedShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);\n const params = ['row', 'col', 'depth'];\n return `\n ${getSamplerFromInInfo(newInputInfo)}\n float ${funcName}(int row, int col, int depth) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3(${stride0}, ${stride1}, 1)));\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const texShape = inputInfo.shapeInfo.texShape;\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n const flatOffset = inputInfo.shapeInfo.flatOffset;\n if (texNumC === stride0 && flatOffset == null) {\n // texC is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(${stride1}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n if (texNumC === stride1 && flatOffset == null) {\n // texR is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${shape[1]}, 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const offset = getFlatOffsetUniformName(texName);\n return `\n float ${funcName}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${stride0} + col * ${stride1} + depth + ${offset};\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getPackedSamplerND(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const rank = shape.length;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const texShape = inputInfo.shapeInfo.texShape;\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n const texNumR = packedTexShape[0];\n const texNumC = packedTexShape[1];\n\n const valuesPerRow = Math.ceil(shape[rank - 1] / 2);\n let texelsInBatch = valuesPerRow * Math.ceil(shape[rank - 2] / 2);\n let params = `int b, int row, int col`;\n let index = `b * ${texelsInBatch} + (row / 2) * ${valuesPerRow} + (col / 2)`;\n for (let b = 2; b < rank - 1; b++) {\n params = `int b${b}, ` + params;\n texelsInBatch *= shape[rank - b - 1];\n index = `b${b} * ${texelsInBatch} + ` + index;\n }\n const glsl = getGlslDifferences();\n return `\n vec4 ${funcName}(${params}) {\n int index = ${index};\n int texR = index / ${texNumC};\n int texC = index - texR * ${texNumC};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}, ${texNumR});\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler4D(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const stride2 = shape[3];\n const stride1 = shape[2] * stride2;\n const stride0 = shape[1] * stride1;\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n if (newShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, newShape);\n const params = ['row', 'col', 'depth', 'depth2'];\n return `\n ${getSamplerFromInInfo(newInputInfo)}\n float ${funcName}(int row, int col, int depth, int depth2) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4(${stride0}, ${stride1}, ${stride2}, 1)));\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const flatOffset = inputInfo.shapeInfo.flatOffset;\n const texShape = inputInfo.shapeInfo.texShape;\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n\n if (texNumC === stride0 && flatOffset == null) {\n // texC is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(${stride1}, ${stride2}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n if (texNumC === stride2 && flatOffset == null) {\n // texR is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${shape[1] * shape[2]}, ${shape[2]}, 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const offset = getFlatOffsetUniformName(texName);\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${stride0} + col * ${stride1} +\n depth * ${stride2} + depth2;\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index + ${offset});\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler5D(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const stride3 = shape[4];\n const stride2 = shape[3] * stride3;\n const stride1 = shape[2] * stride2;\n const stride0 = shape[1] * stride1;\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n if (newShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, newShape);\n const params = ['row', 'col', 'depth', 'depth2', 'depth3'];\n return `\n ${getSamplerFromInInfo(newInputInfo)}\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4(${stride0}, ${stride1}, ${stride2}, ${stride3})) +\n depth3;\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const flatOffset = inputInfo.shapeInfo.flatOffset;\n const texShape = inputInfo.shapeInfo.texShape;\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n\n if (texNumC === stride0 && flatOffset == null) {\n // texC is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${stride1}, ${stride2}, ${stride3}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n if (texNumC === stride3 && flatOffset == null) {\n // texR is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4(${shape[1] * shape[2] * shape[3]},\n ${shape[2] * shape[3]}, ${shape[3]}, 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const offset = getFlatOffsetUniformName(texName);\n return `\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +\n depth2 * ${stride3} + depth3 + ${offset};\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler6D(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n if (newShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, newShape);\n const params = ['row', 'col', 'depth', 'depth2', 'depth3', 'depth4'];\n return `\n ${getSamplerFromInInfo(newInputInfo)}\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n const stride4 = shape[5];\n const stride3 = shape[4] * stride4;\n const stride2 = shape[3] * stride3;\n const stride1 = shape[2] * stride2;\n const stride0 = shape[1] * stride1;\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4(${stride0}, ${stride1}, ${stride2}, ${stride3})) +\n dot(\n vec2(depth3, depth4),\n vec2(${stride4}, 1)));\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const flatOffset = inputInfo.shapeInfo.flatOffset;\n const texShape = inputInfo.shapeInfo.texShape;\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n if (texNumC === stride0 && flatOffset == null) {\n // texC is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${stride1}, ${stride2}, ${stride3}, ${stride4})) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n if (texNumC === stride4 && flatOffset == null) {\n // texR is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4(${shape[1] * shape[2] * shape[3] * shape[4]},\n ${shape[2] * shape[3] * shape[4]},\n ${shape[3] * shape[4]},\n ${shape[4]})) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n const offset = getFlatOffsetUniformName(texName);\n return `\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +\n depth2 * ${stride3} + depth3 * ${stride4} + depth4 + ${offset};\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getUniformSampler(inputInfo: InputInfo): string {\n const texName = inputInfo.name;\n const inSize = util.sizeFromShape(inputInfo.shapeInfo.logicalShape);\n\n if (inSize < 2) {\n return `return ${texName};`;\n }\n return `\n for (int i = 0; i < ${inSize}; i++) {\n if (i == index) {\n return ${texName}[i];\n }\n }\n `;\n}\n\nfunction getPackedSamplerAtOutputCoords(\n inputInfo: InputInfo, outShapeInfo: ShapeInfo) {\n const texName = inputInfo.name;\n const texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);\n const funcName = 'get' + texFuncSnippet + 'AtOutCoords';\n const inRank = inputInfo.shapeInfo.logicalShape.length;\n const outRank = outShapeInfo.logicalShape.length;\n\n const broadcastDims = getBroadcastDims(\n inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);\n\n const type = getCoordsDataType(outRank);\n const rankDiff = outRank - inRank;\n let coordsSnippet: string;\n const fields = ['x', 'y', 'z', 'w', 'u', 'v'];\n\n if (inRank === 0) {\n coordsSnippet = '';\n } else if (outRank < 2 && broadcastDims.length >= 1) {\n coordsSnippet = 'coords = 0;';\n } else {\n coordsSnippet =\n broadcastDims.map(d => `coords.${fields[d + rankDiff]} = 0;`)\n .join('\\n');\n }\n let unpackedCoordsSnippet = '';\n if (outRank < 2 && inRank > 0) {\n unpackedCoordsSnippet = 'coords';\n } else {\n unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape\n .map((s, i) => `coords.${fields[i + rankDiff]}`)\n .join(', ');\n }\n\n let output = `return outputValue;`;\n const inSize = util.sizeFromShape(inputInfo.shapeInfo.logicalShape);\n const isInputScalar = inSize === 1;\n const outSize = util.sizeFromShape(outShapeInfo.logicalShape);\n const isOutputScalar = outSize === 1;\n\n if (inRank === 1 && !isInputScalar && !isOutputScalar) {\n output = `\n return vec4(outputValue.xy, outputValue.xy);\n `;\n } else if (isInputScalar && !isOutputScalar) {\n if (outRank === 1) {\n output = `\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n `;\n } else {\n output = `\n return vec4(outputValue.x);\n `;\n }\n } else if (broadcastDims.length) {\n const rows = inRank - 2;\n const cols = inRank - 1;\n\n if (broadcastDims.indexOf(rows) > -1 && broadcastDims.indexOf(cols) > -1) {\n output = `return vec4(outputValue.x);`;\n } else if (broadcastDims.indexOf(rows) > -1) {\n output = `return vec4(outputValue.x, outputValue.y, ` +\n `outputValue.x, outputValue.y);`;\n } else if (broadcastDims.indexOf(cols) > -1) {\n output = `return vec4(outputValue.xx, outputValue.zz);`;\n }\n }\n\n return `\n vec4 ${funcName}() {\n ${type} coords = getOutputCoords();\n ${coordsSnippet}\n vec4 outputValue = get${texFuncSnippet}(${unpackedCoordsSnippet});\n ${output}\n }\n `;\n}\n\nfunction getSamplerAtOutputCoords(\n inputInfo: InputInfo, outShapeInfo: ShapeInfo) {\n const texName = inputInfo.name;\n const texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);\n const funcName = 'get' + texFuncSnippet + 'AtOutCoords';\n const outTexShape = outShapeInfo.texShape;\n const inTexShape = inputInfo.shapeInfo.texShape;\n const inRank = inputInfo.shapeInfo.logicalShape.length;\n const outRank = outShapeInfo.logicalShape.length;\n\n if (!inputInfo.shapeInfo.isUniform && inRank === outRank &&\n inputInfo.shapeInfo.flatOffset == null &&\n util.arraysEqual(inTexShape, outTexShape)) {\n return `\n float ${funcName}() {\n return sampleTexture(${texName}, resultUV);\n }\n `;\n }\n\n const type = getCoordsDataType(outRank);\n const broadcastDims = getBroadcastDims(\n inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);\n const rankDiff = outRank - inRank;\n let coordsSnippet: string;\n const fields = ['x', 'y', 'z', 'w', 'u', 'v'];\n\n if (inRank === 0) {\n coordsSnippet = '';\n } else if (outRank < 2 && broadcastDims.length >= 1) {\n coordsSnippet = 'coords = 0;';\n } else {\n coordsSnippet =\n broadcastDims.map(d => `coords.${fields[d + rankDiff]} = 0;`)\n .join('\\n');\n }\n let unpackedCoordsSnippet = '';\n if (outRank < 2 && inRank > 0) {\n unpackedCoordsSnippet = 'coords';\n } else {\n unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape\n .map((s, i) => `coords.${fields[i + rankDiff]}`)\n .join(', ');\n }\n\n return `\n float ${funcName}() {\n ${type} coords = getOutputCoords();\n ${coordsSnippet}\n return get${texFuncSnippet}(${unpackedCoordsSnippet});\n }\n `;\n}\n\nexport function getCoordsDataType(rank: number): string {\n if (rank <= 1) {\n return 'int';\n } else if (rank === 2) {\n return 'ivec2';\n } else if (rank === 3) {\n return 'ivec3';\n } else if (rank === 4) {\n return 'ivec4';\n } else if (rank === 5) {\n return 'ivec5';\n } else if (rank === 6) {\n return 'ivec6';\n } else {\n throw Error(`GPU for rank ${rank} is not yet supported`);\n }\n}\n\n/** Returns a new input info (a copy) that has a squeezed logical shape. */\nfunction squeezeInputInfo(\n inInfo: InputInfo, squeezedShape: number[]): InputInfo {\n // Deep copy.\n const newInputInfo: InputInfo = JSON.parse(JSON.stringify(inInfo));\n newInputInfo.shapeInfo.logicalShape = squeezedShape;\n return newInputInfo;\n}\n\nfunction getSqueezedParams(params: string[], keptDims: number[]): string {\n return keptDims.map(d => params[d]).join(', ');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, Tensor, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUContext} from './gpgpu_context';\nimport * as shader_compiler from './shader_compiler';\nimport {InputInfo, ShapeInfo} from './shader_compiler';\nimport {PackingScheme, TextureData, TextureUsage} from './tex_util';\n\nexport interface GPGPUProgram {\n variableNames: string[];\n outputShape: number[];\n userCode: string;\n /** If true, this program expects packed input textures. Defaults to false. */\n packedInputs?: boolean;\n /** If true, this program produces a packed texture. Defaults to false. */\n packedOutput?: boolean;\n /**\n * Affects what type of texture we allocate for the output. Defaults to\n * `TextureUsage.RENDER`.\n */\n outTexUsage?: TextureUsage;\n /**\n * The type of scheme to use when packing texels for the output values.\n * See `PackingScheme` for details. Defaults to `PackingScheme.SHARED_BATCH`.\n */\n outPackingScheme?: PackingScheme;\n}\n\nexport interface GPGPUBinary {\n webGLProgram: WebGLProgram;\n program: GPGPUProgram;\n uniformLocations: {[name: string]: WebGLUniformLocation};\n source: string;\n inShapeInfos: ShapeInfo[];\n outShapeInfo: ShapeInfo;\n infLoc: WebGLUniformLocation;\n nanLoc: WebGLUniformLocation;\n}\n\nexport interface TensorData {\n shape: number[];\n texData: TextureData;\n isUniform: boolean;\n // Available when we decide to upload as uniform instead of texture.\n uniformValues?: TypedArray;\n}\n\nexport function compileProgram(\n gpgpu: GPGPUContext, program: GPGPUProgram, inputs: TensorData[],\n output: TensorData): GPGPUBinary {\n const userCode = program.userCode;\n const inputInfos: InputInfo[] = inputs.map((input, i) => {\n const shapeInfo: ShapeInfo = {\n logicalShape: input.shape,\n texShape: input.isUniform ? null : input.texData.texShape,\n isUniform: input.isUniform,\n isPacked: input.isUniform ? false : input.texData.isPacked,\n flatOffset: null\n };\n if (input.texData != null && input.texData.slice != null &&\n input.texData.slice.flatOffset > 0) {\n shapeInfo.flatOffset = input.texData.slice.flatOffset;\n }\n return {name: program.variableNames[i], shapeInfo};\n });\n const inShapeInfos = inputInfos.map(x => x.shapeInfo);\n const outShapeInfo: ShapeInfo = {\n logicalShape: output.shape,\n texShape: output.texData.texShape,\n isUniform: false,\n isPacked: output.texData.isPacked,\n flatOffset: null\n };\n const source = shader_compiler.makeShader(\n inputInfos, outShapeInfo, userCode, program.packedInputs);\n\n const webGLProgram = gpgpu.createProgram(source);\n\n // Add special uniforms (NAN, INFINITY)\n let infLoc: WebGLUniformLocation = null;\n const nanLoc = gpgpu.getUniformLocation(webGLProgram, 'NAN', false);\n if (env().getNumber('WEBGL_VERSION') === 1) {\n infLoc = gpgpu.getUniformLocation(webGLProgram, 'INFINITY', false);\n }\n\n // Add user-defined uniforms\n const uniformLocations: {[name: string]: WebGLUniformLocation} = {};\n for (let i = 0; i < program.variableNames.length; i++) {\n const varName = program.variableNames[i];\n const shouldThrow = false;\n uniformLocations[varName] =\n gpgpu.getUniformLocation(webGLProgram, varName, shouldThrow);\n uniformLocations[`offset${varName}`] =\n gpgpu.getUniformLocation(webGLProgram, `offset${varName}`, shouldThrow);\n }\n\n return {\n program,\n source,\n webGLProgram,\n uniformLocations,\n inShapeInfos,\n outShapeInfo,\n infLoc,\n nanLoc,\n };\n}\n\nfunction validateBinaryAndProgram(\n shapeInfos: ShapeInfo[], inputs: TensorData[]) {\n if (shapeInfos.length !== inputs.length) {\n throw Error(\n `Binary was compiled with ${shapeInfos.length} inputs, but ` +\n `was executed with ${inputs.length} inputs`);\n }\n\n shapeInfos.forEach((s, i) => {\n const shapeA = s.logicalShape;\n const input = inputs[i];\n const shapeB = input.shape;\n\n if (!util.arraysEqual(shapeA, shapeB)) {\n throw Error(\n `Binary was compiled with different shapes than ` +\n `the current args. Shapes ${shapeA} and ${shapeB} must match`);\n }\n // The input is uploaded as uniform.\n if (s.isUniform && input.isUniform) {\n return;\n }\n\n const texShapeA = s.texShape;\n const texShapeB = input.isUniform ? null : input.texData.texShape;\n if (!util.arraysEqual(texShapeA, texShapeB)) {\n throw Error(\n `Binary was compiled with different texture shapes than the` +\n ` current args. Shape ${texShapeA} and ${texShapeB} must match`);\n }\n });\n}\n\nexport function runProgram(\n gpgpu: GPGPUContext, binary: GPGPUBinary, inputs: TensorData[],\n output: TensorData,\n customSetup?: (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) =>\n void): void {\n validateBinaryAndProgram(binary.inShapeInfos, inputs);\n validateBinaryAndProgram([binary.outShapeInfo], [output]);\n\n const outTex = output.texData.texture;\n const outTexShape = output.texData.texShape;\n if (output.texData.isPacked) {\n gpgpu.setOutputPackedMatrixTexture(outTex, outTexShape[0], outTexShape[1]);\n } else {\n gpgpu.setOutputMatrixTexture(outTex, outTexShape[0], outTexShape[1]);\n }\n gpgpu.setProgram(binary.webGLProgram);\n\n // Set special uniforms (NAN, INFINITY)\n if (env().getNumber('WEBGL_VERSION') === 1) {\n if (binary.infLoc !== null) {\n gpgpu.gl.uniform1f(binary.infLoc, Infinity);\n }\n }\n if (binary.nanLoc !== null) {\n gpgpu.gl.uniform1f(binary.nanLoc, NaN);\n }\n\n // Set user-defined inputs\n inputs.forEach((input, i) => {\n const varName = binary.program.variableNames[i];\n const varLoc = binary.uniformLocations[varName];\n const varOffsetLoc = binary.uniformLocations[`offset${varName}`];\n\n if (varLoc == null) {\n // The compiler inferred that this variable is not used in this shader.\n return;\n }\n\n if (input.isUniform) {\n // Upload the values of the tensor as uniform.\n if (util.sizeFromShape(input.shape) < 2) {\n gpgpu.gl.uniform1f(varLoc, input.uniformValues[0]);\n } else {\n let vals = input.uniformValues;\n if (!(vals instanceof Float32Array)) {\n vals = new Float32Array(vals);\n }\n gpgpu.gl.uniform1fv(varLoc, vals);\n }\n return;\n }\n\n // If the input was sliced, upload the flat offset index.\n if (input.texData.slice != null && varOffsetLoc != null) {\n gpgpu.gl.uniform1i(varOffsetLoc, input.texData.slice.flatOffset);\n }\n\n gpgpu.setInputMatrixTexture(input.texData.texture, varLoc, i);\n });\n\n if (customSetup != null) {\n customSetup(gpgpu, binary.webGLProgram);\n }\n gpgpu.executeProgram();\n}\n\nexport function makeShaderKey(\n program: GPGPUProgram, inputs: TensorData[], output: TensorData): string {\n let keyInputs = '';\n inputs.concat(output).forEach(x => {\n const hasOffset = x.texData != null && x.texData.slice != null &&\n x.texData.slice.flatOffset > 0;\n const texShape = x.isUniform ? 'uniform' : x.texData.texShape;\n keyInputs += `${x.shape}_${texShape}_${hasOffset}`;\n });\n const keyUserCode = program.userCode;\n let key = program.constructor.name;\n // Fast string concat. See https://jsperf.com/string-concatenation/14.\n key += '_' + keyInputs + '_' + keyUserCode;\n return key;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Abs, util } from '@tensorflow/tfjs-core';\nimport { assertNotComplex } from '../cpu_util';\nexport function simpleAbsImpl(vals) {\n const resultValues = new Float32Array(vals.length);\n for (let i = 0; i < vals.length; ++i) {\n resultValues[i] = Math.abs(vals[i]);\n }\n return resultValues;\n}\nexport const abs = (args) => {\n const { x } = args.inputs;\n const cpuBackend = args.backend;\n assertNotComplex(x, 'abs');\n let resultValues = new Float32Array(util.sizeFromShape(x.shape));\n const values = cpuBackend.data.get(x.dataId).values;\n resultValues = simpleAbsImpl(values);\n return cpuBackend.makeOutput(resultValues, x.shape, 'float32');\n};\nexport const absConfig = {\n kernelName: Abs,\n backendName: 'cpu',\n kernelFunc: abs,\n};\n//# sourceMappingURL=Abs.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { backend_util, util } from '@tensorflow/tfjs-core';\n/**\n * Template that creates implementation for binary ops. Supports broadcast.\n */\nexport function createSimpleBinaryKernelImpl(op) {\n return (aShape, bShape, aVals, bVals, dtype) => {\n const newShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n const resultRank = newShape.length;\n const resultStrides = util.computeStrides(newShape);\n const resultSize = util.sizeFromShape(newShape);\n const result = util.getTypedArrayFromDType(dtype, resultSize);\n const aRank = aShape.length;\n const bRank = bShape.length;\n const aStrides = util.computeStrides(aShape);\n const bStrides = util.computeStrides(bShape);\n const aBroadcastDims = backend_util.getBroadcastDims(aShape, newShape);\n const bBroadcastDims = backend_util.getBroadcastDims(bShape, newShape);\n if (aBroadcastDims.length + bBroadcastDims.length === 0) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = op(aVals[i % aVals.length], bVals[i % bVals.length]);\n }\n }\n else {\n for (let i = 0; i < result.length; ++i) {\n const loc = util.indexToLoc(i, resultRank, resultStrides);\n const aLoc = loc.slice(-aRank);\n aBroadcastDims.forEach(d => aLoc[d] = 0);\n const aIndex = util.locToIndex(aLoc, aRank, aStrides);\n const bLoc = loc.slice(-bRank);\n bBroadcastDims.forEach(d => bLoc[d] = 0);\n const bIndex = util.locToIndex(bLoc, bRank, bStrides);\n result[i] = op(aVals[aIndex], bVals[bIndex]);\n }\n }\n return [result, newShape];\n };\n}\n//# sourceMappingURL=binary_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Add } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc, createComplexBinaryKernelImpl } from '../utils/binary_utils';\nexport const addImpl = createSimpleBinaryKernelImpl(((a, b) => a + b));\nexport const addComplexImpl = createComplexBinaryKernelImpl(((aReal, aImag, bReal, bImag) => {\n return { real: aReal + bReal, imag: aImag + bImag };\n}));\nexport const add = binaryKernelFunc(Add, addImpl, addComplexImpl);\nexport const addConfig = {\n kernelName: Add,\n backendName: 'cpu',\n kernelFunc: add\n};\n//# sourceMappingURL=Add.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { buffer, util } from '@tensorflow/tfjs-core';\nexport function bincountImpl(xVals, weightsVals, weightsDtype, weightsShape, size) {\n const weightsSize = util.sizeFromShape(weightsShape);\n const outVals = util.makeZerosTypedArray(size, weightsDtype);\n for (let i = 0; i < xVals.length; i++) {\n const value = xVals[i];\n if (value < 0) {\n throw new Error('Input x must be non-negative!');\n }\n if (value >= size) {\n continue;\n }\n if (weightsSize > 0) {\n outVals[value] += weightsVals[i];\n }\n else {\n outVals[value] += 1;\n }\n }\n return outVals;\n}\nexport function bincountReduceImpl(xBuf, weightsBuf, size, binaryOutput = false) {\n const numRows = xBuf.shape[0];\n const numCols = xBuf.shape[1];\n const outBuf = buffer([numRows, size], weightsBuf.dtype);\n for (let i = 0; i < numRows; i++) {\n for (let j = 0; j < numCols; j++) {\n const value = xBuf.get(i, j);\n if (value < 0) {\n throw new Error('Input x must be non-negative!');\n }\n if (value >= size) {\n continue;\n }\n if (binaryOutput) {\n outBuf.set(1, i, value);\n }\n else {\n if (weightsBuf.size > 0) {\n outBuf.set(outBuf.get(i, value) + weightsBuf.get(i, j), i, value);\n }\n else {\n outBuf.set(outBuf.get(i, value) + 1, i, value);\n }\n }\n }\n }\n return outBuf;\n}\n//# sourceMappingURL=Bincount_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\n/**\n * Template that creates implementation for unary op.\n */\nexport function createSimpleUnaryImpl(op) {\n return (values, dtype, attrs) => {\n const newValues = util.getTypedArrayFromDType(dtype, values.length);\n for (let i = 0; i < values.length; ++i) {\n newValues[i] = op(values[i], attrs);\n }\n return newValues;\n };\n}\n//# sourceMappingURL=unary_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Ceil } from '@tensorflow/tfjs-core';\nimport { createSimpleUnaryImpl } from '../utils/unary_impl';\nimport { unaryKernelFuncFromImpl } from '../utils/unary_utils';\nexport const ceilImpl = createSimpleUnaryImpl((xi) => Math.ceil(xi));\nexport const ceil = unaryKernelFuncFromImpl(Ceil, ceilImpl);\nexport const ceilConfig = {\n kernelName: Ceil,\n backendName: 'cpu',\n kernelFunc: ceil,\n};\n//# sourceMappingURL=Ceil.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { backend_util, util } from '@tensorflow/tfjs-core';\nexport function concatImpl(inputs, outShape, dtype, simplyConcat) {\n const outVals = util.getArrayFromDType(dtype, util.sizeFromShape(outShape));\n if (simplyConcat && dtype !== 'string') {\n // Use built-in TypedArray.set() method for speed.\n let offset = 0;\n inputs.forEach(input => {\n const size = util.sizeFromShape(input.shape);\n outVals.set(input.vals, offset);\n offset += size;\n });\n }\n else {\n let colOffset = 0;\n inputs.forEach(input => {\n const decodedData = dtype === 'string' ?\n backend_util.fromUint8ToStringArray(input.vals) :\n input.vals;\n let tIdx = 0;\n for (let row = 0; row < input.shape[0]; ++row) {\n const resIdx = row * outShape[1] + colOffset;\n for (let col = 0; col < input.shape[1]; ++col) {\n outVals[resIdx + col] = decodedData[tIdx++];\n }\n }\n colOffset += input.shape[1];\n });\n }\n return outVals;\n}\n//# sourceMappingURL=Concat_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Equal } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc } from '../utils/binary_utils';\nexport const equalImpl = createSimpleBinaryKernelImpl((a, b) => (a === b) ? 1 : 0);\nexport const equal = binaryKernelFunc(Equal, equalImpl, null /* complexImpl */, 'bool');\nexport const equalConfig = {\n kernelName: Equal,\n backendName: 'cpu',\n kernelFunc: equal\n};\n//# sourceMappingURL=Equal.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Exp } from '@tensorflow/tfjs-core';\nimport { createSimpleUnaryImpl } from '../utils/unary_impl';\nimport { unaryKernelFuncFromImpl } from '../utils/unary_utils';\nexport const expImpl = createSimpleUnaryImpl((xi) => Math.exp(xi));\nexport const exp = unaryKernelFuncFromImpl(Exp, expImpl);\nexport const expConfig = {\n kernelName: Exp,\n backendName: 'cpu',\n kernelFunc: exp,\n};\n//# sourceMappingURL=Exp.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Expm1 } from '@tensorflow/tfjs-core';\nimport { createSimpleUnaryImpl } from '../utils/unary_impl';\nimport { unaryKernelFuncFromImpl } from '../utils/unary_utils';\nexport const expm1Impl = createSimpleUnaryImpl((xi) => Math.expm1(xi));\nexport const expm1 = unaryKernelFuncFromImpl(Expm1, expm1Impl);\nexport const expm1Config = {\n kernelName: Expm1,\n backendName: 'cpu',\n kernelFunc: expm1,\n};\n//# sourceMappingURL=Expm1.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Floor } from '@tensorflow/tfjs-core';\nimport { createSimpleUnaryImpl } from '../utils/unary_impl';\nimport { unaryKernelFuncFromImpl } from '../utils/unary_utils';\nexport const floorImpl = createSimpleUnaryImpl((xi) => Math.floor(xi));\nexport const floor = unaryKernelFuncFromImpl(Floor, floorImpl);\nexport const floorConfig = {\n kernelName: Floor,\n backendName: 'cpu',\n kernelFunc: floor,\n};\n//# sourceMappingURL=Floor.js.map","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { buffer } from '@tensorflow/tfjs-core';\nexport function gatherNdImpl(indicesData, paramsBuf, dtype, numSlices, sliceRank, sliceSize, strides, paramsShape, paramsSize) {\n const outBuf = buffer([numSlices, sliceSize], dtype);\n for (let i = 0; i < numSlices; i++) {\n const index = [];\n let flattenIndex = 0;\n for (let j = 0; j < sliceRank; j++) {\n const dim = indicesData[i * sliceRank + j];\n flattenIndex += dim * strides[j];\n index.push(dim);\n }\n if (flattenIndex < 0 || flattenIndex >= paramsSize / sliceSize) {\n throw new Error(`Invalid indices: ${index} does not index into ${paramsShape}`);\n }\n for (let k = 0; k < sliceSize; k++) {\n outBuf.values[i * sliceSize + k] =\n paramsBuf.get(...paramsBuf.indexToLoc(flattenIndex * sliceSize + k));\n }\n }\n return outBuf;\n}\n//# sourceMappingURL=GatherNd_Impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { buffer } from '@tensorflow/tfjs-core';\nexport function gatherV2Impl(xBuf, indicesBuf, flattenOutputShape) {\n const outBuf = buffer(flattenOutputShape, xBuf.dtype);\n for (let i = 0; i < outBuf.size; ++i) {\n const newLoc = outBuf.indexToLoc(i);\n const originalLoc = newLoc.slice();\n const batchIdx = originalLoc[0];\n const indicesIdx = originalLoc[2];\n const indicesIndex = indicesBuf.locToIndex([batchIdx, indicesIdx]);\n originalLoc[2] = indicesBuf.values[indicesIndex];\n const originalIndex = xBuf.locToIndex(originalLoc);\n outBuf.values[i] = xBuf.values[originalIndex];\n }\n return outBuf;\n}\n//# sourceMappingURL=GatherV2_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Greater } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc } from '../utils/binary_utils';\nexport const greaterImpl = createSimpleBinaryKernelImpl((a, b) => (a > b) ? 1 : 0);\nexport const greater = binaryKernelFunc(Greater, greaterImpl, null /* complexImpl */, 'bool');\nexport const greaterConfig = {\n kernelName: Greater,\n backendName: 'cpu',\n kernelFunc: greater\n};\n//# sourceMappingURL=Greater.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { GreaterEqual } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc } from '../utils/binary_utils';\nexport const greaterEqualImpl = createSimpleBinaryKernelImpl((a, b) => (a >= b) ? 1 : 0);\nexport const greaterEqual = binaryKernelFunc(GreaterEqual, greaterEqualImpl, null /* complexImpl */, 'bool');\nexport const greaterEqualConfig = {\n kernelName: GreaterEqual,\n backendName: 'cpu',\n kernelFunc: greaterEqual\n};\n//# sourceMappingURL=GreaterEqual.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Less } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc } from '../utils/binary_utils';\nexport const lessImpl = createSimpleBinaryKernelImpl((a, b) => (a < b) ? 1 : 0);\nexport const less = binaryKernelFunc(Less, lessImpl, null /* complexImpl */, 'bool');\nexport const lessConfig = {\n kernelName: Less,\n backendName: 'cpu',\n kernelFunc: less\n};\n//# sourceMappingURL=Less.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { LessEqual } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc } from '../utils/binary_utils';\nexport const lessEqualImpl = createSimpleBinaryKernelImpl((a, b) => (a <= b) ? 1 : 0);\nexport const lessEqual = binaryKernelFunc(LessEqual, lessEqualImpl, null /* complexImpl */, 'bool');\nexport const lessEqualConfig = {\n kernelName: LessEqual,\n backendName: 'cpu',\n kernelFunc: lessEqual\n};\n//# sourceMappingURL=LessEqual.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\nexport function linSpaceImpl(start, stop, num) {\n const step = (stop - start) / (num - 1);\n const values = util.makeZerosTypedArray(num, 'float32');\n values[0] = start;\n for (let i = 1; i < values.length; i++) {\n values[i] = values[i - 1] + step;\n }\n return values;\n}\n//# sourceMappingURL=LinSpace_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Log } from '@tensorflow/tfjs-core';\nimport { createSimpleUnaryImpl } from '../utils/unary_impl';\nimport { unaryKernelFuncFromImpl } from '../utils/unary_utils';\nexport const logImpl = createSimpleUnaryImpl((xi) => Math.log(xi));\nexport const log = unaryKernelFuncFromImpl(Log, logImpl);\nexport const logConfig = {\n kernelName: Log,\n backendName: 'cpu',\n kernelFunc: log,\n};\n//# sourceMappingURL=Log.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\nexport function maxImpl(aVals, reduceSize, outShape, dtype) {\n const vals = util.getTypedArrayFromDType(dtype, util.sizeFromShape(outShape));\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let max = aVals[offset];\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n if (Number.isNaN(value) ||\n value > max) { // comparison with NaN always return false\n max = value;\n }\n }\n vals[i] = max;\n }\n return vals;\n}\n//# sourceMappingURL=Max_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Maximum } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc } from '../utils/binary_utils';\nexport const maximumImpl = createSimpleBinaryKernelImpl(((aValue, bValue) => Math.max(aValue, bValue)));\nexport const maximum = binaryKernelFunc(Maximum, maximumImpl);\nexport const maximumConfig = {\n kernelName: Maximum,\n backendName: 'cpu',\n kernelFunc: maximum\n};\n//# sourceMappingURL=Maximum.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Minimum } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc } from '../utils/binary_utils';\nexport const minimumImpl = createSimpleBinaryKernelImpl(((aValue, bValue) => Math.min(aValue, bValue)));\nexport const minimum = binaryKernelFunc(Minimum, minimumImpl);\nexport const minimumConfig = {\n kernelName: Minimum,\n backendName: 'cpu',\n kernelFunc: minimum\n};\n//# sourceMappingURL=Minimum.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Multiply } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc, createComplexBinaryKernelImpl } from '../utils/binary_utils';\nexport const multiplyImpl = createSimpleBinaryKernelImpl(((aValue, bValue) => aValue * bValue));\nexport const multiplyComplexImpl = createComplexBinaryKernelImpl(((aReal, aImag, bReal, bImag) => {\n return {\n real: aReal * bReal - aImag * bImag,\n imag: aReal * bImag + aImag * bReal\n };\n}));\nexport const multiply = binaryKernelFunc(Multiply, multiplyImpl, multiplyComplexImpl);\nexport const multiplyConfig = {\n kernelName: Multiply,\n backendName: 'cpu',\n kernelFunc: multiply\n};\n//# sourceMappingURL=Multiply.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Neg, util } from '@tensorflow/tfjs-core';\nimport { assertNotComplex } from '../cpu_util';\nimport { multiplyImpl } from './Multiply';\nexport function negImpl(xVals, xShape, xDtype) {\n const minusOne = util.createScalarValue(-1, xDtype);\n return multiplyImpl([], xShape, minusOne, xVals, xDtype);\n}\nexport function neg(args) {\n const { inputs, backend } = args;\n const { x } = inputs;\n assertNotComplex(x, 'neg');\n const xVals = backend.data.get(x.dataId).values;\n const [res, newShape] = negImpl(xVals, x.shape, x.dtype);\n return backend.makeTensorInfo(newShape, x.dtype, res);\n}\nexport const negConfig = {\n kernelName: Neg,\n backendName: 'cpu',\n kernelFunc: neg\n};\n//# sourceMappingURL=Neg.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { NotEqual } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc } from '../utils/binary_utils';\nexport const notEqualImpl = createSimpleBinaryKernelImpl(((a, b) => (a !== b) ? 1 : 0));\nexport const notEqual = binaryKernelFunc(NotEqual, notEqualImpl, null /* complexOp */, 'bool');\nexport const notEqualConfig = {\n kernelName: NotEqual,\n backendName: 'cpu',\n kernelFunc: notEqual\n};\n//# sourceMappingURL=NotEqual.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\nexport function transposeImpl(xVals, xShape, dtype, perm, newShape) {\n const xRank = xShape.length;\n const xSize = util.sizeFromShape(xShape);\n const xStrides = util.computeStrides(xShape);\n const newStrides = util.computeStrides(newShape);\n const result = util.getTypedArrayFromDType(dtype, util.sizeFromShape(newShape));\n for (let i = 0; i < xSize; ++i) {\n const loc = util.indexToLoc(i, xRank, xStrides);\n // Permute location.\n const newLoc = new Array(loc.length);\n for (let i = 0; i < newLoc.length; i++) {\n newLoc[i] = loc[perm[i]];\n }\n const newIndex = util.locToIndex(newLoc, xRank, newStrides);\n result[newIndex] = xVals[i];\n }\n return result;\n}\n//# sourceMappingURL=Transpose_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { backend_util, Prod, upcastType, util } from '@tensorflow/tfjs-core';\nimport { assertNotComplex } from '../cpu_util';\nimport { transpose } from './Transpose';\nexport function prodImpl(xShape, xDtype, xVals, reductionAxes) {\n const [outShape, reduceShape] = backend_util.computeOutAndReduceShapes(xShape, reductionAxes);\n const outDtype = upcastType(xDtype, 'int32');\n const outVals = util.makeZerosTypedArray(util.sizeFromShape(outShape), outDtype);\n const reduceSize = util.sizeFromShape(reduceShape);\n for (let i = 0; i < outVals.length; ++i) {\n const offset = i * reduceSize;\n let prod = 1;\n for (let j = 0; j < reduceSize; ++j) {\n prod *= xVals[offset + j];\n }\n outVals[i] = prod;\n }\n return { outVals, outShape, outDtype };\n}\nexport function prod(args) {\n const { inputs, backend, attrs } = args;\n const { x } = inputs;\n const { axis, keepDims } = attrs;\n assertNotComplex(x, 'prod');\n const xRank = x.shape.length;\n const axes = util.parseAxisParam(axis, x.shape);\n const permutation = backend_util.getAxesPermutation(axes, xRank);\n let reductionAxes = axes;\n let permutedX = x;\n const intermediateTensorInfos = [];\n if (permutation != null) {\n permutedX = transpose({ inputs: { x }, backend, attrs: { perm: permutation } });\n intermediateTensorInfos.push(permutedX);\n reductionAxes = backend_util.getInnerMostAxes(reductionAxes.length, xRank);\n }\n const xVals = backend.data.get(permutedX.dataId).values;\n const { outVals, outShape, outDtype } = prodImpl(permutedX.shape, permutedX.dtype, xVals, reductionAxes);\n let resultShape = outShape;\n if (keepDims) {\n resultShape = backend_util.expandShapeToKeepDim(outShape, axes);\n }\n intermediateTensorInfos.forEach(t => backend.disposeIntermediateTensorInfo(t));\n return backend.makeTensorInfo(resultShape, outDtype, outVals);\n}\nexport const prodConfig = {\n kernelName: Prod,\n backendName: 'cpu',\n kernelFunc: prod\n};\n//# sourceMappingURL=Prod.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\nexport function rangeImpl(start, stop, step, dtype) {\n const sameStartStop = start === stop;\n const increasingRangeNegativeStep = start < stop && step < 0;\n const decreasingRangePositiveStep = stop < start && step > 1;\n if (sameStartStop || increasingRangeNegativeStep ||\n decreasingRangePositiveStep) {\n return util.makeZerosTypedArray(0, dtype);\n }\n const numElements = Math.abs(Math.ceil((stop - start) / step));\n const values = util.makeZerosTypedArray(numElements, dtype);\n if (stop < start && step === 1) {\n // Auto adjust the step's sign if it hasn't been set\n // (or was set to 1)\n step = -1;\n }\n values[0] = start;\n for (let i = 1; i < values.length; i++) {\n values[i] = values[i - 1] + step;\n }\n return values;\n}\n//# sourceMappingURL=Range_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Rsqrt } from '@tensorflow/tfjs-core';\nimport { createSimpleUnaryImpl } from '../utils/unary_impl';\nimport { unaryKernelFuncFromImpl } from '../utils/unary_utils';\nexport const rsqrtImpl = createSimpleUnaryImpl((xi) => 1 / Math.sqrt(xi));\nexport const rsqrt = unaryKernelFuncFromImpl(Rsqrt, rsqrtImpl);\nexport const rsqrtConfig = {\n kernelName: Rsqrt,\n backendName: 'cpu',\n kernelFunc: rsqrt,\n};\n//# sourceMappingURL=Rsqrt.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { backend_util, buffer, Slice, slice_util, util } from '@tensorflow/tfjs-core';\nimport { assertNotComplex } from '../cpu_util';\nexport function sliceImpl(vals, begin, size, shape, dtype) {\n const isContinous = slice_util.isSliceContinous(shape, begin, size);\n const length = util.sizeFromShape(size);\n const xStrides = util.computeStrides(shape);\n if (isContinous) {\n const flatOffset = slice_util.computeFlatOffset(begin, xStrides);\n if (dtype === 'string') {\n return vals.slice(flatOffset, flatOffset + length);\n }\n return vals.subarray(flatOffset, flatOffset + length);\n }\n const decodedData = dtype === 'string' ?\n backend_util.fromUint8ToStringArray(vals) :\n vals;\n const inBuf = buffer(shape, dtype, decodedData);\n const outBuf = buffer(size, dtype);\n for (let i = 0; i < outBuf.size; ++i) {\n const outLoc = outBuf.indexToLoc(i);\n const inLoc = outLoc.map((idx, j) => idx + begin[j]);\n outBuf.set(inBuf.get(...inLoc), ...outLoc);\n }\n if (dtype === 'string') {\n return backend_util.fromStringArrayToUint8(outBuf.values);\n }\n return outBuf.values;\n}\nexport function slice(args) {\n const { inputs, backend, attrs } = args;\n const { x } = inputs;\n const { begin, size } = attrs;\n assertNotComplex(x, 'slice');\n const [$begin, $size] = slice_util.parseSliceParams(x, begin, size);\n slice_util.assertParamsValid(x, $begin, $size);\n const vals = backend.data.get(x.dataId).values;\n const outVals = sliceImpl(vals, $begin, $size, x.shape, x.dtype);\n return backend.makeTensorInfo($size, x.dtype, outVals);\n}\nexport const sliceConfig = {\n kernelName: Slice,\n backendName: 'cpu',\n kernelFunc: slice\n};\n//# sourceMappingURL=Slice.js.map","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\nexport function sparseFillEmptyRowsImpl(indices, indicesShape, indicesDType, values, valuesDType, denseShape, defaultValue) {\n const indicesCount = indicesShape[0];\n const denseRows = denseShape[0];\n const emptyRowIndicator = new Array(denseRows);\n const reverseIndexMap = new Array(indicesCount);\n const rank = indicesShape[1];\n if (denseRows === 0) {\n if (indicesCount !== 0) {\n throw new Error(`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${indicesCount}`);\n }\n const outputIndices = util.getArrayFromDType(indicesDType, 0);\n const outputValues = util.getArrayFromDType(valuesDType, 0);\n return [\n outputIndices, [0, rank], outputValues, emptyRowIndicator, reverseIndexMap\n ];\n }\n let rowsAreOrdered = true;\n let lastIndicesRow = 0;\n const csrOffset = new Array(denseRows).fill(0);\n for (let i = 0; i < indicesCount; ++i) {\n // indices is a 2d tensor with shape of [N, rank]\n const row = indices[i * rank];\n if (row < 0) {\n throw new Error(`indices(${i}, 0) is invalid: ${row} < 0`);\n }\n if (row >= denseRows) {\n throw new Error(`indices(${i}, 0) is invalid: ${row} >= ${denseRows}`);\n }\n ++csrOffset[row];\n rowsAreOrdered = rowsAreOrdered && (row >= lastIndicesRow);\n lastIndicesRow = row;\n }\n let allRowsFull = true;\n for (let row = 0; row < denseRows; ++row) {\n // csrOffset here describes the number of elements in this dense row\n const rowEmpty = (csrOffset[row] === 0);\n emptyRowIndicator[row] = rowEmpty;\n allRowsFull = allRowsFull && !rowEmpty;\n // In filled version, each row has at least one element.\n csrOffset[row] = Math.max(csrOffset[row], 1);\n // Update csrOffset to represent the number of elements up to and\n // including denseRows + 1:\n // csrOffset[0] == #{elements of row 0}\n // csrOffset[1] == #{elements of row 1} + #{elements of row 0}\n // ..\n // csrOffset[i] == starting index for elements in row i + 1.\n if (row > 0) {\n csrOffset[row] += csrOffset[row - 1];\n }\n }\n if (allRowsFull && rowsAreOrdered) {\n const outputIndices = indices;\n const outputValues = values;\n for (let i = 0; i < indicesCount; ++i) {\n reverseIndexMap[i] = i;\n }\n return [\n outputIndices, [indicesCount, rank], outputValues, emptyRowIndicator,\n reverseIndexMap\n ];\n }\n else {\n const fullIndicesCount = csrOffset[denseRows - 1];\n const outputIndices = util.getArrayFromDType(indicesDType, fullIndicesCount * rank);\n const outputValues = util.getArrayFromDType(valuesDType, fullIndicesCount);\n const filledCount = new Array(denseRows).fill(0);\n // Fill in values for rows that are not missing\n for (let i = 0; i < indicesCount; ++i) {\n // indices is a 2d tensor with shape of [N, rank]\n const row = indices[i * rank];\n const offset = filledCount[row];\n const outputI = ((row === 0) ? 0 : csrOffset[row - 1]) + offset;\n filledCount[row]++; // Increment the filled count for this row.\n for (let j = 0; j < rank; ++j) {\n // indices and outputIndices are 2d tensors with shape of [N, rank]\n outputIndices[outputI * rank + j] = indices[i * rank + j];\n }\n outputValues[outputI] = values[i];\n // We'll need this reverse index map to backprop correctly.\n reverseIndexMap[i] = outputI;\n }\n // Fill in values for rows that are missing\n for (let row = 0; row < denseRows; ++row) {\n const rowCount = filledCount[row];\n if (rowCount === 0) { // We haven't filled this row\n const startingIndex = (row === 0) ? 0 : csrOffset[row - 1];\n // Remaining index values were set to zero already.\n // Just need to set the row index in the right location.\n // outputIndices is a 2d tensor with shape of [N, rank]\n outputIndices[startingIndex * rank + 0] = row;\n for (let col = 1; col < rank; ++col) {\n outputIndices[startingIndex * rank + col] = 0;\n }\n outputValues[startingIndex] = defaultValue;\n }\n }\n return [\n outputIndices, [fullIndicesCount, rank], outputValues, emptyRowIndicator,\n reverseIndexMap\n ];\n }\n}\n//# sourceMappingURL=SparseFillEmptyRows_impl.js.map","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\nexport function sparseReshapeImpl(inputIndices, inputIndicesShape, inputDType, inputShape, targetShape) {\n const denseSize = util.sizeFromShape(inputShape);\n const nnz = inputIndicesShape[0];\n const outputRank = targetShape.length;\n // Compute the output shape. Determine product of specified dimensions, and\n // find the index of the unspecified one.\n const outputShape = [];\n let product = 1;\n let unknownIndex = -1;\n for (let d = 0; d < outputRank; ++d) {\n const size = targetShape[d];\n if (size === -1) {\n if (unknownIndex !== -1) {\n throw new Error(`only one output dimension may be -1, not both ${unknownIndex} and ${d}`);\n }\n unknownIndex = d;\n outputShape.push(1);\n }\n else {\n if (size < 0) {\n throw new Error(`size ${d} must be non-negative, not ${size}`);\n }\n product *= size;\n outputShape.push(size);\n }\n }\n if (unknownIndex !== -1) {\n if (product <= 0) {\n throw new Error('reshape cannot infer the missing ' +\n 'input size for an empty tensor unless all ' +\n 'specified input sizes are non-zero');\n }\n const missing = Math.trunc(denseSize / product);\n if (product * missing !== denseSize) {\n throw new Error(`Input to reshape is a SparseTensor with ${denseSize}\n dense values, but the requested shape requires a multiple of ${product}. inputShape=${inputShape} outputShape= ${outputShape}`);\n }\n outputShape[unknownIndex] = missing;\n }\n const outputSize = util.sizeFromShape(outputShape);\n if (outputSize !== denseSize) {\n throw new Error(`Input to reshape is a tensor with ${denseSize} dense values, but the requested shape has ${outputSize}. inputShape=${inputShape} outputShape=${outputShape}`);\n }\n const inputRank = inputShape.length;\n const inputStrides = [];\n if (inputRank > 0) {\n inputStrides[inputRank - 1] = 1;\n for (let d = inputRank - 2; d >= 0; --d) {\n inputStrides[d] = inputStrides[d + 1] * inputShape[d + 1];\n }\n }\n const outputStrides = [];\n if (outputRank > 0) {\n outputStrides[outputRank - 1] = 1;\n for (let d = outputRank - 2; d >= 0; --d) {\n outputStrides[d] = outputStrides[d + 1] * outputShape[d + 1];\n }\n }\n const newIndices = util.getArrayFromDType(inputDType, nnz * outputRank);\n for (let i = 0; i < nnz; ++i) {\n let id = 0;\n for (let j = 0; j < inputRank; ++j) {\n // inputIndices is a 2d tensor with shape of [nnz, inputRank]\n id += inputIndices[i * inputRank + j] * inputStrides[j];\n }\n for (let j = 0; j < outputRank; ++j) {\n // newIndices is a 2d tensor with shape of [nnz, outputRank]\n newIndices[i * outputRank + j] = Math.trunc(id / outputStrides[j]);\n id %= outputStrides[j];\n }\n }\n return [newIndices, [nnz, outputRank], outputShape];\n}\n//# sourceMappingURL=SparseReshape_impl.js.map","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\nexport function sparseSegmentReductionImpl(input, inputShape, inputDType, indices, segmentIds, isMean = false, defaultValue = 0) {\n const numIndices = indices.length;\n if (numIndices !== segmentIds.length) {\n throw new Error(`segmentIds and indices should have same size.`);\n }\n // Flatten the array to two dimensions\n const inputFlat = [inputShape[0], input.length / inputShape[0]];\n const numCol = inputFlat[1];\n // Note that the current implementation assumes that segmentIds values are\n // sorted.\n const lastSegmentIdPlusOne = numIndices > 0 ? segmentIds[numIndices - 1] + 1 : 0;\n const outputRows = lastSegmentIdPlusOne;\n if (outputRows < 0) {\n throw new Error(`segment ids must be >= 0`);\n }\n const outputShape = inputShape.slice();\n outputShape[0] = outputRows;\n const outputLength = outputShape.reduce((product, value) => product * value, 1);\n // Output array is initialized with the value 0 by default.\n const output = util.getArrayFromDType(inputDType, outputLength);\n // Note that we do not initialize the output buffer with a default value, so\n // we need to explicitly set missing indices to the default value.\n if (numIndices === 0) {\n if (outputRows > 0) {\n output.fill(defaultValue);\n }\n return [output, outputShape];\n }\n if (outputRows <= 0) {\n throw new Error(`segment ids must be >= 0`);\n }\n let start = 0, end = 1;\n // Index from which the output is not initialized.\n let uninitializedIndex = 0;\n let outIndex = segmentIds[start];\n while (true) {\n // We initialize nextIndex to 0 to avoid may be uninitialized warning\n let nextIndex = 0;\n if (end < numIndices) {\n nextIndex = segmentIds[end];\n if (outIndex === nextIndex) {\n ++end;\n continue;\n }\n // We have a new segment here. Verify that the segment ids are growing.\n if (outIndex >= nextIndex) {\n throw new Error(`segment ids are not increasing`);\n }\n }\n if (outIndex < 0 || outIndex >= outputRows) {\n throw new Error(`Segment id ${outIndex} out of range [0, ${outputRows}), possibly because segmentIds input is not sorted.`);\n }\n // If there is a gap between two indices, we need to set that gap to the\n // default value.\n if (outIndex > uninitializedIndex) {\n output.fill(defaultValue, uninitializedIndex * numCol, outIndex * numCol);\n }\n for (let i = start; i < end; ++i) {\n const index = indices[i];\n if (index < 0 || index >= inputFlat[0]) {\n throw new Error(`Bad: indices[${i}] == ${indices[i]} out of range [0, ${inputFlat[0]})`);\n }\n for (let j = 0; j < numCol; j++) {\n output[outIndex * numCol + j] += input[index * numCol + j];\n }\n }\n if (isMean) {\n for (let j = 0; j < numCol; j++) {\n output[outIndex * numCol + j] /= end - start;\n }\n }\n start = end;\n ++end;\n uninitializedIndex = outIndex + 1;\n outIndex = nextIndex;\n if (end > numIndices) {\n break;\n }\n }\n // Fill the gap at the end with the default value.\n if (uninitializedIndex < outputRows) {\n output.fill(defaultValue, uninitializedIndex * numCol, outputRows * numCol);\n }\n return [output, outputShape];\n}\n//# sourceMappingURL=SparseSegmentReduction_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { buffer } from '@tensorflow/tfjs-core';\nexport function stridedSliceImpl(outShape, xBuf, strides, begin) {\n const outBuf = buffer(outShape, xBuf.dtype);\n for (let i = 0; i < outBuf.size; i++) {\n const loc = outBuf.indexToLoc(i);\n const newLoc = new Array(loc.length);\n for (let j = 0; j < newLoc.length; j++) {\n newLoc[j] = loc[j] * strides[j] + begin[j];\n }\n outBuf.set(xBuf.get(...newLoc), ...loc);\n }\n return outBuf;\n}\n//# sourceMappingURL=StridedSlice_impl.js.map","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\n/**\n * The StringNGramsOp class creates ngrams from ragged string data.\n * The constructor contains all attributes related to the operation such as\n * padding widths and strings, and the compute function can be used to\n * compute the ngrams for different ragged tensor inputs.\n */\nclass StringNGramsOp {\n constructor(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {\n this.separator = util.encodeString(separator);\n this.nGramWidths = nGramWidths;\n this.leftPad = util.encodeString(leftPad);\n this.rightPad = util.encodeString(rightPad);\n this.padWidth = padWidth;\n this.preserveShort = preserveShortSequences;\n }\n getPadWidth(nGramWidth) {\n // Ngrams can be padded with either a fixed pad width or a dynamic pad\n // width depending on the 'padWidth' arg, but in no case should the padding\n // ever be wider than 'nGramWidth' - 1.\n return Math.min(this.padWidth < 0 ? nGramWidth - 1 : this.padWidth, nGramWidth - 1);\n }\n getNumNGrams(length, nGramWidth) {\n const padWidth = this.getPadWidth(nGramWidth);\n return Math.max(0, ((length + 2 * padWidth) - nGramWidth) + 1);\n }\n createNGrams(data, splitIndex, output, outputStartIndex, numNGrams, nGramWidth) {\n for (let nGramIndex = 0; nGramIndex < numNGrams; ++nGramIndex) {\n const padWidth = this.getPadWidth(nGramWidth);\n const leftPadding = Math.max(0, padWidth - nGramIndex);\n const rightPadding = Math.max(0, padWidth - (numNGrams - (nGramIndex + 1)));\n const numTokens = nGramWidth - (leftPadding + rightPadding);\n const dataStartIndex = splitIndex + (leftPadding > 0 ? 0 : nGramIndex - padWidth);\n // Calculate the total expected size of the nGram so we can reserve the\n // correct amount of space in the string.\n let nGramSize = 0;\n // Size of the left padding.\n nGramSize += leftPadding * this.leftPad.length;\n // Size of the tokens.\n for (let n = 0; n < numTokens; ++n) {\n nGramSize += data[dataStartIndex + n].length;\n }\n // Size of the right padding.\n nGramSize += rightPadding * this.rightPad.length;\n // Size of the separators.\n const numSeparators = leftPadding + rightPadding + numTokens - 1;\n nGramSize += numSeparators * this.separator.length;\n // Build the nGram.\n output[outputStartIndex + nGramIndex] = new Uint8Array(nGramSize);\n const nGram = output[outputStartIndex + nGramIndex];\n let nextNGramIndex = 0;\n const appendToNGram = (str) => str.forEach((value) => nGram[nextNGramIndex++] = value);\n for (let n = 0; n < leftPadding; ++n) {\n appendToNGram(this.leftPad);\n appendToNGram(this.separator);\n }\n // Only output first numTokens - 1 pairs of data and separator\n for (let n = 0; n < numTokens - 1; ++n) {\n appendToNGram(data[dataStartIndex + n]);\n appendToNGram(this.separator);\n }\n // Handle case when there are no tokens or no right padding as these\n // can result in consecutive separators.\n if (numTokens > 0) {\n // If we have tokens, then output last and then pair each separator\n // with the right padding that follows, to ensure nGram ends either with\n // the token or with the right pad.\n appendToNGram(data[dataStartIndex + numTokens - 1]);\n for (let n = 0; n < rightPadding; ++n) {\n appendToNGram(this.separator);\n appendToNGram(this.rightPad);\n }\n }\n else {\n // If we don't have tokens, then the last item inserted into the nGram\n // has been the separator from the left padding loop above. Hence,\n // output right pad and separator and make sure to finish with a\n // padding, not a separator.\n for (let n = 0; n < rightPadding - 1; ++n) {\n appendToNGram(this.rightPad);\n appendToNGram(this.separator);\n }\n appendToNGram(this.rightPad);\n }\n }\n }\n // Data and splits together form the definition of the ragged tensor,\n // where data is 1 dimensional and contains the values of the tensor\n // and splits denotes the indices at which each row starts.\n compute(data, splits) {\n // Validate that the splits are valid indices into data, only if there are\n // splits specified.\n const inputDataSize = data.length;\n const splitsSize = splits.length;\n if (splitsSize > 0) {\n let prevSplit = splits[0];\n if (prevSplit !== 0) {\n throw new Error(`First split value must be 0, got ${prevSplit}`);\n }\n for (let i = 1; i < splitsSize; ++i) {\n let validSplits = splits[i] >= prevSplit;\n validSplits = validSplits && (splits[i] <= inputDataSize);\n if (!validSplits) {\n throw new Error(`Invalid split value ${splits[i]}, must be in [${prevSplit}, ${inputDataSize}]`);\n }\n prevSplit = splits[i];\n }\n if (prevSplit !== inputDataSize) {\n throw new Error(`Last split value must be data size. Expected ${inputDataSize}, got ${prevSplit}`);\n }\n }\n const numBatchItems = splitsSize - 1;\n const nGramsSplits = util.getArrayFromDType('int32', splitsSize);\n // If there is no data or size, return an empty ragged tensor.\n if (inputDataSize === 0 || splitsSize === 0) {\n const empty = new Array(inputDataSize);\n for (let i = 0; i <= numBatchItems; ++i) {\n nGramsSplits[i] = 0;\n }\n return [empty, nGramsSplits];\n }\n nGramsSplits[0] = 0;\n for (let i = 1; i <= numBatchItems; ++i) {\n const length = splits[i] - splits[i - 1];\n let numNGrams = 0;\n this.nGramWidths.forEach((nGramWidth) => {\n numNGrams += this.getNumNGrams(length, nGramWidth);\n });\n if (this.preserveShort && length > 0 && numNGrams === 0) {\n numNGrams = 1;\n }\n nGramsSplits[i] = nGramsSplits[i - 1] + numNGrams;\n }\n const nGrams = new Array(nGramsSplits[numBatchItems]);\n for (let i = 0; i < numBatchItems; ++i) {\n const splitIndex = splits[i];\n let outputStartIdx = nGramsSplits[i];\n this.nGramWidths.forEach((nGramWidth) => {\n const length = splits[i + 1] - splits[i];\n const numNGrams = this.getNumNGrams(length, nGramWidth);\n this.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);\n outputStartIdx += numNGrams;\n });\n // If we're preserving short sequences, check to see if no sequence was\n // generated by comparing the current output start idx to the original\n // one (nGramSplitsdata). If no ngrams were generated, then they will\n // be equal (since we increment outputStartIdx by numNGrams every\n // time we create a set of ngrams.)\n if (this.preserveShort && outputStartIdx === nGramsSplits[i]) {\n const dataLength = splits[i + 1] - splits[i];\n // One legitimate reason to not have any ngrams when this.preserveShort\n // is true is if the sequence itself is empty. In that case, move on.\n if (dataLength === 0) {\n continue;\n }\n // We don't have to worry about dynamic padding sizes here: if padding\n // was dynamic, every sequence would have had sufficient padding to\n // generate at least one nGram.\n const nGramWidth = dataLength + 2 * this.padWidth;\n const numNGrams = 1;\n this.createNGrams(data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);\n }\n }\n return [nGrams, nGramsSplits];\n }\n}\nexport function stringNGramsImpl(data, dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {\n return new StringNGramsOp(separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences)\n .compute(data, dataSplits);\n}\n//# sourceMappingURL=StringNGrams_impl.js.map","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\nfunction split(str, delimiters, skipEmpty) {\n if (!str.length) {\n return [];\n }\n // When the delimiter is empty, the input is split into individual characters.\n if (delimiters.length === 0) {\n const result = new Array(str.length);\n for (let i = 0; i < str.length; ++i) {\n result[i] = str.subarray(i, i + 1);\n }\n return result;\n }\n // When there is one delimiter, the input is split only at that delimiter.\n if (delimiters.length === 1) {\n const delimiter = delimiters[0];\n const result = [];\n let f = str.indexOf(delimiter);\n while (f !== -1) {\n const token = str.subarray(0, f);\n if (!skipEmpty || token.length !== 0) {\n result.push(token);\n }\n str = str.subarray(f + 1);\n f = str.indexOf(delimiter);\n }\n if (!skipEmpty || str.length !== 0) {\n result.push(str);\n }\n return result;\n }\n // When there are multiple delimiters, the input is split at every instance\n // one of the delimiters appears.\n const result = [];\n let tokenStart = 0;\n for (let i = 0; i < str.length + 1; i++) {\n if ((i === str.length) || (delimiters.indexOf(str[i]) !== -1)) {\n const token = str.subarray(tokenStart, i);\n if (!skipEmpty || token.length !== 0) {\n result.push(token);\n }\n tokenStart = i + 1;\n }\n }\n return result;\n}\nexport function stringSplitImpl(input, delimiter, skipEmpty) {\n const batchSize = input.length;\n // Empty delimiter means split the input character by character.\n const tokens = [];\n let outputSize = 0;\n let maxNumEntries = 0;\n const numIndices = new Array(batchSize);\n for (let i = 0; i < batchSize; ++i) {\n const parts = split(input[i], delimiter, skipEmpty);\n const nEntries = parts.length;\n numIndices[i] = nEntries;\n outputSize += nEntries;\n maxNumEntries = Math.max(maxNumEntries, nEntries);\n tokens.push(...parts);\n }\n const indices = util.getArrayFromDType('int32', outputSize * 2);\n const values = new Array(outputSize);\n const shape = [batchSize, maxNumEntries];\n let c = 0;\n for (let i = 0; i < batchSize; ++i) {\n for (let j = 0; j < numIndices[i]; ++j) {\n // indices is a 2d tensor with shape of [outputSize, 2]\n indices[c * 2] = i;\n indices[c * 2 + 1] = j;\n values[c] = tokens[c];\n ++c;\n }\n }\n return [indices, values, shape];\n}\n//# sourceMappingURL=StringSplit_impl.js.map","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { util } from '@tensorflow/tfjs-core';\nexport function stringToHashBucketFastImpl(input, numBuckets) {\n const output = util.getArrayFromDType('int32', input.length);\n for (let i = 0; i < input.length; ++i) {\n output[i] =\n util.fingerPrint64(input[i]).modulo(numBuckets).getLowBitsUnsigned();\n }\n return output;\n}\n//# sourceMappingURL=StringToHashBucketFast_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { Sub } from '@tensorflow/tfjs-core';\nimport { createSimpleBinaryKernelImpl } from '../utils/binary_impl';\nimport { binaryKernelFunc, createComplexBinaryKernelImpl } from '../utils/binary_utils';\nexport const subImpl = createSimpleBinaryKernelImpl(((aValue, bValue) => aValue - bValue));\nexport const subComplexImpl = createComplexBinaryKernelImpl(((aReal, aImag, bReal, bImag) => {\n return { real: aReal - bReal, imag: aImag - bImag };\n}));\nexport const sub = binaryKernelFunc(Sub, subImpl, subComplexImpl);\nexport const subConfig = {\n kernelName: Sub,\n backendName: 'cpu',\n kernelFunc: sub\n};\n//# sourceMappingURL=Sub.js.map","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { buffer } from '@tensorflow/tfjs-core';\n/**\n * An implementation of the tile kernel shared between webgl and cpu for string\n * tensors only.\n */\nexport function tileImpl(xBuf, reps) {\n const newShape = new Array(xBuf.rank);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = xBuf.shape[i] * reps[i];\n }\n const result = buffer(newShape, xBuf.dtype);\n for (let i = 0; i < result.values.length; ++i) {\n const newLoc = result.indexToLoc(i);\n const originalLoc = new Array(xBuf.rank);\n for (let j = 0; j < originalLoc.length; j++) {\n originalLoc[j] = newLoc[j] % xBuf.shape[j];\n }\n const originalIndex = xBuf.locToIndex(originalLoc);\n result.values[i] = xBuf.values[originalIndex];\n }\n return result;\n}\n//# sourceMappingURL=Tile_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/** An implementation of the TopK kernel shared between webgl and cpu. */\nimport { buffer, util } from '@tensorflow/tfjs-core';\nexport function topKImpl(x, xShape, xDtype, k, sorted) {\n // Reshape into a 2d tensor [batch, lastDim] and compute topk along lastDim.\n const lastDim = xShape[xShape.length - 1];\n const [batch, size] = [x.length / lastDim, lastDim];\n const allTopKVals = util.getTypedArrayFromDType(xDtype, batch * k);\n const allTopKIndices = util.getTypedArrayFromDType('int32', batch * k);\n for (let b = 0; b < batch; b++) {\n const offset = b * size;\n const vals = x.subarray(offset, offset + size);\n const valAndInd = [];\n for (let i = 0; i < vals.length; i++) {\n valAndInd.push({ value: vals[i], index: i });\n }\n valAndInd.sort((a, b) => b.value - a.value);\n const outOffset = b * k;\n const topKVals = allTopKVals.subarray(outOffset, outOffset + k);\n const topKIndices = allTopKIndices.subarray(outOffset, outOffset + k);\n for (let i = 0; i < k; i++) {\n topKVals[i] = valAndInd[i].value;\n topKIndices[i] = valAndInd[i].index;\n }\n }\n // Reshape back to the original input shape, except that the last\n // dimension is k.\n const outputShape = xShape.slice();\n outputShape[outputShape.length - 1] = k;\n return [\n buffer(outputShape, xDtype, allTopKVals),\n buffer(outputShape, 'int32', allTopKIndices)\n ];\n}\n//# sourceMappingURL=TopK_impl.js.map","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { TensorBuffer, util } from '@tensorflow/tfjs-core';\nexport function uniqueImpl(values, axis, shape, dtype) {\n // Normalize and validate axis.\n const $axis = util.parseAxisParam(axis, shape)[0];\n // Calculate the new shape that is suitable for extracting data along the\n // given axis.\n //\n // The rank is 3.\n // The size of the 1st dimension is the size of all the axes < the given axis.\n // The size of the 2nd dimension is the same as the size of the given axis.\n // The size of the 3rd dimension is the size of all the axes > the given axis.\n //\n // For example, for a 4D tensor with shape=[2, 3, 5, 4] and axis=2, the\n // newShape would be: [2*3, 5, 4].\n //\n // Note that this is not the final output shape. This will be the shape for an\n // intermediate TensorBuffer (see inputBuffer below) to allow us to extract\n // values along the given axis. To demonstrate how it works, consider the\n // following example:\n //\n // Input: a 3D tensor, with shape [1, 2, 3]\n // [\n // [\n // [1,2,3],\n // [4,5,6]\n // ]\n // ]\n // Axis: 2 (the last axis).\n // Along axis 2, we expect to extract 3 tensors: [1,4], [2,5], [3,6].\n //\n // For this example, newShape would be: [2, 3, 1], where 2 is calculated from\n // 1*2. The re-shaped data would look like:\n //\n // [\n // [\n // [1], [2], [3]\n // ],\n // [\n // [4], [5], [6]\n // ]\n // ]\n //\n // Then, we can construct a 3-level nested loop by the following dimension\n // order to extract the values along the axis (dimension1):\n // i: dimension1 // 0,1,2 (newShape[1])\n // m: dimension0 // 0,1 (newShape[0])\n // n: dimension2 // 0 (newShape[2])\n //\n // m, i, n\n // ---------\n // Iteration 0: data at [0, 0, 0] => \"1\"\n // Iteration 1: data at [1, 0, 0] => \"4\"\n // We got [1,4].\n // Iteration 2: data at [0, 1, 0] => \"2\"\n // Iteration 3: data at [1, 1, 0] => \"5\"\n // We got [2,5].\n // Iteration 4: data at [0, 2, 0] => \"3\"\n // Iteration 5: data at [1, 2, 0] => \"6\"\n // We got [3,6].\n const newShape = [1, shape[0], 1];\n for (let i = 0; i < $axis; i++) {\n newShape[0] *= shape[i];\n }\n newShape[1] = shape[$axis];\n for (let i = $axis + 1; i < shape.length; i++) {\n newShape[2] *= shape[i];\n }\n // A map from unique elements (their string representations) to their values\n // in \"indices\" (below).\n const uniqueElements = {};\n // The indices of each unique element in the original tensor along the given\n // axis. It is 1D and has the same size as the given axis.\n const indices = new Int32Array(shape[$axis]);\n // Create a buffer so we can easily extract value at a given location.\n const inputBuffer = new TensorBuffer(newShape, dtype, values);\n // The indices along the given axis that have unique elements. This is a\n // de-duped version of \"indices\" above.\n const uniqueIndices = [];\n const is1DTensor = newShape[0] === 1 && newShape[2] === 1;\n for (let i = 0; i < shape[$axis]; i++) {\n // Extract values along the axis.\n let element;\n if (is1DTensor) {\n // Fast path for 1D tensor input.\n element = values[i].toString();\n }\n else {\n const axisValues = [];\n for (let m = 0; m < newShape[0]; m++) {\n for (let n = 0; n < newShape[2]; n++) {\n axisValues.push(inputBuffer.get(m, i, n));\n }\n }\n element = axisValues.join(',');\n }\n // Dedup and update various indices.\n if (uniqueElements[element] !== undefined) {\n indices[i] = uniqueElements[element];\n }\n else {\n const uniqueIndex = Object.keys(uniqueElements).length;\n uniqueElements[element] = uniqueIndex;\n indices[i] = uniqueIndex;\n uniqueIndices.push(i);\n }\n }\n // Now we know where each of the unique elements are located along the axis\n // (uniqueIndices). Extract them from input buffer and store them in the\n // output buffer.\n const outputTmpShape = newShape.slice();\n outputTmpShape[1] = Object.keys(uniqueElements).length;\n const outputBuffer = new TensorBuffer(outputTmpShape, dtype);\n uniqueIndices.forEach((uniqueElementIndex, i) => {\n for (let m = 0; m < newShape[0]; m++) {\n for (let n = 0; n < newShape[2]; n++) {\n outputBuffer.set(inputBuffer.get(m, uniqueElementIndex, n), m, i, n);\n }\n }\n });\n // The output shape can be calculated from the input shape with the size of\n // the given axis replaced by the number of unique elements along that axis.\n const outputShape = shape.slice();\n outputShape[$axis] = outputTmpShape[1];\n return {\n outputValues: outputBuffer.values,\n outputShape,\n indices,\n };\n}\n//# sourceMappingURL=Unique_impl.js.map","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Import shared functionality from tfjs-backend-cpu without triggering\n// side effects.\n// tslint:disable-next-line: no-imports-from-dist\nimport * as shared from '@tensorflow/tfjs-backend-cpu/dist/shared';\n// tslint:disable-next-line: no-imports-from-dist\nimport {SimpleBinaryKernelImpl} from '@tensorflow/tfjs-backend-cpu/dist/shared';\n// tslint:disable-next-line: no-imports-from-dist\nimport {SimpleUnaryImpl} from '@tensorflow/tfjs-backend-cpu/dist/utils/unary_types';\n\nexport type SimpleBinaryKernelImplCPU = SimpleBinaryKernelImpl;\nexport type SimpleUnaryKernelImplCPU = SimpleUnaryImpl;\nconst {\n addImpl: addImplCPU,\n bincountImpl: bincountImplCPU,\n bincountReduceImpl: bincountReduceImplCPU,\n ceilImpl: ceilImplCPU,\n concatImpl: concatImplCPU,\n equalImpl: equalImplCPU,\n expImpl: expImplCPU,\n expm1Impl: expm1ImplCPU,\n floorImpl: floorImplCPU,\n gatherNdImpl: gatherNdImplCPU,\n gatherV2Impl: gatherV2ImplCPU,\n greaterImpl: greaterImplCPU,\n greaterEqualImpl: greaterEqualImplCPU,\n lessImpl: lessImplCPU,\n lessEqualImpl: lessEqualImplCPU,\n linSpaceImpl: linSpaceImplCPU,\n logImpl: logImplCPU,\n maxImpl: maxImplCPU,\n maximumImpl: maximumImplCPU,\n minimumImpl: minimumImplCPU,\n multiplyImpl: multiplyImplCPU,\n negImpl: negImplCPU,\n notEqualImpl: notEqualImplCPU,\n prodImpl: prodImplCPU,\n rangeImpl: rangeImplCPU,\n rsqrtImpl: rsqrtImplCPU,\n simpleAbsImpl: simpleAbsImplCPU,\n sliceImpl: sliceImplCPU,\n sparseFillEmptyRowsImpl: sparseFillEmptyRowsImplCPU,\n sparseReshapeImpl: sparseReshapeImplCPU,\n sparseSegmentReductionImpl: sparseSegmentReductionImplCPU,\n stridedSliceImpl: stridedSliceImplCPU,\n stringNGramsImpl: stringNGramsImplCPU,\n stringSplitImpl: stringSplitImplCPU,\n stringToHashBucketFastImpl: stringToHashBucketFastImplCPU,\n subImpl: subImplCPU,\n tileImpl: tileImplCPU,\n topKImpl: topKImplCPU,\n transposeImpl: transposeImplCPU,\n uniqueImpl: uniqueImplCPU,\n} = shared;\n\nexport {\n addImplCPU,\n bincountImplCPU,\n bincountReduceImplCPU,\n ceilImplCPU,\n concatImplCPU,\n equalImplCPU,\n expImplCPU,\n expm1ImplCPU,\n floorImplCPU,\n gatherNdImplCPU,\n gatherV2ImplCPU,\n greaterEqualImplCPU,\n greaterImplCPU,\n lessEqualImplCPU,\n lessImplCPU,\n linSpaceImplCPU,\n logImplCPU,\n maxImplCPU,\n maximumImplCPU,\n minimumImplCPU,\n multiplyImplCPU,\n negImplCPU,\n notEqualImplCPU,\n prodImplCPU,\n simpleAbsImplCPU,\n sliceImplCPU,\n sparseFillEmptyRowsImplCPU,\n sparseReshapeImplCPU,\n sparseSegmentReductionImplCPU,\n stridedSliceImplCPU,\n stringNGramsImplCPU,\n stringSplitImplCPU,\n stringToHashBucketFastImplCPU,\n subImplCPU,\n rangeImplCPU,\n rsqrtImplCPU,\n tileImplCPU,\n topKImplCPU,\n transposeImplCPU,\n uniqueImplCPU,\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport function getVecChannels(name: string, rank: number): string[] {\n return ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, rank).map(d => `${name}.${d}`);\n}\n\nexport function getChannels(name: string, rank: number): string[] {\n if (rank === 1) {\n return [name];\n }\n return getVecChannels(name, rank);\n}\n\nexport function getSourceCoords(rank: number, dims: string[]): string {\n if (rank === 1) {\n return 'rc';\n }\n\n let coords = '';\n for (let i = 0; i < rank; i++) {\n coords += dims[i];\n if (i < rank - 1) {\n coords += ',';\n }\n }\n return coords;\n}","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class PackProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n packedInputs = false;\n packedOutput = true;\n\n constructor(\n outputShape:\n number[]) { // TODO(https://github.com/tensorflow/tfjs/issues/893):\n // Only input / output 3D tensors.\n this.outputShape = outputShape;\n const rank = outputShape.length;\n\n if (rank === 0) {\n this.userCode = `\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n `;\n } else {\n const channels = getChannels('rc', rank);\n const dtype = getCoordsDataType(rank);\n const outOfBoundsCondition =\n getOutOfBoundsCondition(rank, outputShape, channels);\n const setup = getSetup(\n rank, outputShape[outputShape.length - 1],\n outputShape[outputShape.length - 2], channels);\n const output = getOutput(outputShape, channels);\n\n this.userCode = `\n void main() {\n ${dtype} rc = getOutputCoords();\n\n if(${outOfBoundsCondition}) {\n setOutput(vec4(0));\n } else {\n ${setup}\n\n setOutput(vec4(${output}));\n }\n }\n `;\n }\n }\n}\n\nfunction getSourceCoordsArr(rank: number, dims: string[]): string[] {\n const coords = [];\n\n for (let row = 0; row <= 1; row++) {\n for (let col = 0; col <= 1; col++) {\n let coord = `${row === 0 ? 'r' : 'rp1'}, ${col === 0 ? 'c' : 'cp1'}`;\n\n for (let d = 2; d < rank; d++) {\n coord = `${dims[dims.length - 1 - d]},` + coord;\n }\n\n coords.push(coord);\n }\n }\n return coords;\n}\n\nfunction getOutOfBoundsCondition(\n rank: number, shape: number[], dims: string[]): string {\n if (rank === 1) {\n return `rc > ${shape[0]}`;\n }\n\n let cond = '';\n for (let i = rank - 2; i < rank; i++) {\n cond += `${dims[i]} >= ${shape[i]}`;\n if (i < rank - 1) {\n cond += '||';\n }\n }\n\n return cond;\n}\n\nfunction getSetup(\n rank: number, cols: number, rows: number, dims: string[]): string {\n if (rank === 1) {\n return '';\n }\n\n const innerDims = dims.slice(-2);\n\n return `\n int r = ${innerDims[0]};\n int c = ${innerDims[1]};\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= ${cols};\n bool rEdge = rp1 >= ${rows};\n `;\n}\n\nfunction getOutput(shape: number[], dims: string[]): string {\n const rank = shape.length;\n const sourceCoords = getSourceCoordsArr(rank, dims);\n if (rank === 1) {\n return `getA(rc),\n rc + 1 >= ${shape[0]} ? 0. : getA(rc + 1),\n 0, 0`;\n }\n\n return `getA(${sourceCoords[0]}),\n cEdge ? 0. : getA(${sourceCoords[1]}),\n rEdge ? 0. : getA(${sourceCoords[2]}),\n rEdge || cEdge ? 0. : getA(${sourceCoords[3]})`;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\n\nexport class ReshapePackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(outputShape: [number, number, number], inputShape: [\n number, number, number\n ]) {\n this.outputShape = outputShape;\n\n let mainLoop = ``;\n for (let i = 0; i < 4; i++) {\n let thisRC = `thisRC = rc;`;\n if (i % 2 === 1) {\n thisRC += `thisRC.z += 1;`;\n }\n if (i > 1) {\n thisRC += `thisRC.y += 1;`;\n }\n\n mainLoop += `\n ${thisRC}\n ${i > 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[${i}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${i > 0 ? '}' : ''}\n `;\n }\n\n this.userCode = `\n ${getReshapedInputCoords(inputShape)}\n ${shader_util.getFlatIndexFrom3D(outputShape)}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = ${outputShape[1]};\n int cols = ${outputShape[2]};\n\n ${mainLoop}\n\n setOutput(result);\n }\n `;\n }\n}\n\nfunction getReshapedInputCoords(shape: [number, number, number]): string {\n const coordsFromIndexSnippet =\n shader_util.getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd'], shape);\n\n return `\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${coordsFromIndexSnippet}\n return ivec3(r, c, d);\n }\n `;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {getInternalFormatForFloat16MatrixTexture, getInternalFormatForFloat16PackedMatrixTexture, getInternalFormatForFloat32MatrixTexture, getInternalFormatForPackedMatrixTexture, getInternalFormatForUnsignedBytesMatrixTexture} from './gpgpu_util';\nimport {getPackedMatrixTextureShapeWidthHeight, getUnpackedMatrixTextureShapeWidthHeight, PhysicalTextureType, TextureConfig, TextureUsage} from './tex_util';\n\nexport class TextureManager {\n private numUsedTextures = 0;\n private numFreeTextures = 0;\n private _numBytesAllocated = 0;\n private _numBytesFree = 0; // How many bytes that have been allocated\n // are available for reuse.\n private freeTextures: {[shape: string]: WebGLTexture[]} = {};\n private logEnabled = false;\n private usedTextures: {[shape: string]: WebGLTexture[]} = {};\n\n constructor(private gpgpu: GPGPUContext) {}\n\n acquireTexture(\n shapeRC: [number, number], usage: TextureUsage,\n isPacked: boolean): WebGLTexture {\n const physicalTexType = getPhysicalFromLogicalTextureType(usage, isPacked);\n\n const shapeKey = getKeyFromTextureShape(shapeRC, physicalTexType, isPacked);\n if (!(shapeKey in this.freeTextures)) {\n this.freeTextures[shapeKey] = [];\n }\n if (!(shapeKey in this.usedTextures)) {\n this.usedTextures[shapeKey] = [];\n }\n\n const texBytes = computeBytes(\n shapeRC, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig,\n isPacked);\n\n if (this.freeTextures[shapeKey].length > 0) {\n this.numFreeTextures--;\n this.numUsedTextures++;\n this._numBytesFree -= texBytes;\n this.log();\n const newTexture = this.freeTextures[shapeKey].shift();\n this.usedTextures[shapeKey].push(newTexture);\n return newTexture;\n }\n\n let newTexture: WebGLTexture;\n if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT32) {\n newTexture = this.gpgpu.createPackedMatrixTexture(shapeRC[0], shapeRC[1]);\n } else if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT16) {\n newTexture =\n this.gpgpu.createFloat16PackedMatrixTexture(shapeRC[0], shapeRC[1]);\n } else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT32) {\n newTexture =\n this.gpgpu.createFloat32MatrixTexture(shapeRC[0], shapeRC[1]);\n } else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT16) {\n newTexture =\n this.gpgpu.createFloat16MatrixTexture(shapeRC[0], shapeRC[1]);\n } else if (\n physicalTexType === PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE) {\n newTexture =\n this.gpgpu.createUnsignedBytesMatrixTexture(shapeRC[0], shapeRC[1]);\n }\n this.usedTextures[shapeKey].push(newTexture);\n\n this.numUsedTextures++;\n this._numBytesAllocated += texBytes;\n this.log();\n\n return newTexture;\n }\n\n releaseTexture(\n texture: WebGLTexture, shape: [number, number],\n logicalTexType: TextureUsage, isPacked: boolean): void {\n if (this.freeTextures == null) {\n // Already disposed.\n return;\n }\n const physicalTexType =\n getPhysicalFromLogicalTextureType(logicalTexType, isPacked);\n const shapeKey = getKeyFromTextureShape(shape, physicalTexType, isPacked);\n if (!(shapeKey in this.freeTextures)) {\n this.freeTextures[shapeKey] = [];\n }\n\n const texBytes = computeBytes(\n shape, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig,\n isPacked);\n const deleteTexThreshold = env().get('WEBGL_DELETE_TEXTURE_THRESHOLD');\n if (deleteTexThreshold !== -1 &&\n this._numBytesAllocated > deleteTexThreshold) {\n this.gpgpu.deleteMatrixTexture(texture);\n this._numBytesAllocated -= texBytes;\n } else {\n this.freeTextures[shapeKey].push(texture);\n this.numFreeTextures++;\n this._numBytesFree += texBytes;\n }\n\n this.numUsedTextures--;\n\n const texList = this.usedTextures[shapeKey];\n const texIndex = texList.indexOf(texture);\n if (texIndex < 0) {\n throw new Error(\n 'Cannot release a texture that was never provided by this ' +\n 'texture manager');\n }\n texList.splice(texIndex, 1);\n this.log();\n }\n\n private log() {\n if (!this.logEnabled) {\n return;\n }\n const total = this.numFreeTextures + this.numUsedTextures;\n console.log(\n 'Free/Used', `${this.numFreeTextures} / ${this.numUsedTextures}`,\n `(${total})`);\n const freeRatio = this._numBytesFree / this._numBytesAllocated;\n console.log(`Bytes allocated: ${this._numBytesAllocated}`);\n console.log(`Bytes unused: ${this._numBytesFree} (${\n Math.round(100 * freeRatio)}%)`);\n }\n\n get numBytesAllocated(): number {\n return this._numBytesAllocated;\n }\n\n get numBytesFree(): number {\n return this._numBytesFree;\n }\n\n getNumUsedTextures(): number {\n return this.numUsedTextures;\n }\n\n getNumFreeTextures(): number {\n return this.numFreeTextures;\n }\n\n dispose() {\n if (this.freeTextures == null) {\n // Already disposed.\n return;\n }\n for (const texShape in this.freeTextures) {\n this.freeTextures[texShape].forEach(tex => {\n this.gpgpu.deleteMatrixTexture(tex);\n });\n }\n for (const texShape in this.usedTextures) {\n this.usedTextures[texShape].forEach(tex => {\n this.gpgpu.deleteMatrixTexture(tex);\n });\n }\n this.freeTextures = null;\n this.usedTextures = null;\n this.numUsedTextures = 0;\n this.numFreeTextures = 0;\n this._numBytesAllocated = 0;\n this._numBytesFree = 0;\n }\n}\n\nfunction numBytesForInternalFormat(\n gl: WebGLRenderingContext, internalFormat: number): number {\n // tslint:disable-next-line:no-any\n const glany = gl as any;\n if (internalFormat === glany.R32F) {\n return 4;\n } else if (internalFormat === glany.R16F) {\n return 2;\n } else if (internalFormat === glany.RGBA32F) {\n return 16;\n } else if (internalFormat === gl.RGBA) {\n return 16;\n } else if (internalFormat === glany.RGBA16F) {\n return 8;\n }\n throw new Error(`Unknown internal format ${internalFormat}`);\n}\n\nexport function computeBytes(\n shape: [number, number], physicalTexType: PhysicalTextureType,\n gl: WebGLRenderingContext, textureConfig: TextureConfig,\n isPacked: boolean): number {\n // It is not possible to infer packed status from the texture type because\n // depending on the textureConfig, different texture types may resolve to the\n // same internal format (e.g. in WebGL1, the internal format for\n // UNPACKED_FLOAT16 textures is gl.RGBA). Therefore we pass in `isPacked`\n // explicitly.\n const internalFormat =\n internalFormatForPhysicalTexType(physicalTexType, textureConfig);\n\n let numElements: number;\n if (isPacked) {\n const [packedWidth, packedHeight] =\n getPackedMatrixTextureShapeWidthHeight(shape[0], shape[1]);\n numElements = packedWidth * packedHeight;\n\n } else {\n const [width, height] =\n getUnpackedMatrixTextureShapeWidthHeight(shape[0], shape[1]);\n numElements = width * height;\n }\n\n const bytesPerElement = numBytesForInternalFormat(gl, internalFormat);\n return numElements * bytesPerElement;\n}\n\nfunction internalFormatForPhysicalTexType(\n physicalTexType: PhysicalTextureType,\n textureConfig: TextureConfig): number {\n switch (physicalTexType) {\n case PhysicalTextureType.PACKED_2X2_FLOAT32:\n return getInternalFormatForPackedMatrixTexture(textureConfig);\n case PhysicalTextureType.PACKED_2X2_FLOAT16:\n return getInternalFormatForFloat16PackedMatrixTexture(textureConfig);\n case PhysicalTextureType.UNPACKED_FLOAT32:\n return getInternalFormatForFloat32MatrixTexture(textureConfig);\n case PhysicalTextureType.UNPACKED_FLOAT16:\n return getInternalFormatForFloat16MatrixTexture(textureConfig);\n case PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE:\n return getInternalFormatForUnsignedBytesMatrixTexture(textureConfig);\n default:\n throw new Error(`Unknown physical texture type ${physicalTexType}`);\n }\n}\n\nfunction getPhysicalTextureForRendering(isPacked: boolean):\n PhysicalTextureType {\n if (env().getBool('WEBGL_RENDER_FLOAT32_ENABLED')) {\n if (isPacked) {\n return PhysicalTextureType.PACKED_2X2_FLOAT32;\n }\n return PhysicalTextureType.UNPACKED_FLOAT32;\n }\n\n if (isPacked) {\n return PhysicalTextureType.PACKED_2X2_FLOAT16;\n }\n return PhysicalTextureType.UNPACKED_FLOAT16;\n}\n\nfunction getPhysicalFromLogicalTextureType(\n logicalTexType: TextureUsage, isPacked: boolean): PhysicalTextureType {\n if (logicalTexType === TextureUsage.UPLOAD) {\n return PhysicalTextureType.PACKED_2X2_FLOAT32;\n } else if (logicalTexType === TextureUsage.RENDER || logicalTexType == null) {\n return getPhysicalTextureForRendering(isPacked);\n } else if (\n logicalTexType === TextureUsage.DOWNLOAD ||\n logicalTexType === TextureUsage.PIXELS) {\n return PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE;\n }\n throw new Error(`Unknown logical texture type ${logicalTexType}`);\n}\n\nfunction getKeyFromTextureShape(\n shapeRowsCol: [number, number], physicalTexType: PhysicalTextureType,\n isPacked: boolean): string {\n return `${shapeRowsCol[0]}_${shapeRowsCol[1]}_${physicalTexType}_${isPacked}`;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class UnaryOpProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n\n constructor(aShape: number[], opSnippet: string) {\n this.outputShape = aShape;\n this.userCode = `\n float unaryOperation(float x) {\n ${opSnippet}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `;\n }\n}\n\nexport const CHECK_NAN_SNIPPET = `if (isnan(x)) return x;`;\n\nexport const LINEAR = `return x;`;\n\nexport const ABS = `return abs(x);`;\n\nexport function STEP(alpha = 0.0) {\n return CHECK_NAN_SNIPPET + `\n return x > 0.0 ? 1.0 : float(${alpha});\n `;\n}\n\nexport const ELU = `return (x >= 0.0) ? x : (exp(x) - 1.0);`;\nexport const RELU = CHECK_NAN_SNIPPET + `\n return (x < 0.0) ? 0.0 : x;\n`;\n\nexport const RELU6 = CHECK_NAN_SNIPPET + `\n return (x < 0.0) ? 0.0 : min(6.0, x);\n`;\n\nexport const CLONE = 'return x;';\n\nexport const SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * x));`;\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport const LINEAR = `return x;`;\n\nexport const ELU = `\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n`;\n\nexport const RELU = `\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n`;\n\nexport const RELU6 = `\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n`;\n\nexport const SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * x));`;\n\nexport class UnaryOpPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n packedInputs = true;\n packedOutput = true;\n\n constructor(aShape: number[], opSnippet: string) {\n this.outputShape = aShape;\n this.userCode = `\n vec4 unaryOperation(vec4 x) {\n ${opSnippet}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels, getSourceCoords} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class UnpackProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = false;\n outputShape: number[];\n userCode: string;\n\n constructor(outputShape: number[]) {\n this.outputShape = outputShape;\n const rank = outputShape.length;\n\n const channels = getChannels('rc', rank);\n const dtype = getCoordsDataType(rank);\n const sourceCoords = getSourceCoords(rank, channels);\n const innerDims = channels.slice(-2);\n const coords = rank <= 1 ? 'rc' : `vec2(${innerDims.join(',')})`;\n\n this.userCode = `\n void main() {\n ${dtype} rc = getOutputCoords();\n vec4 packedInput = getA(${sourceCoords});\n\n setOutput(getChannel(packedInput, ${coords}));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Import webgl flags.\nimport './flags_webgl';\n\nimport * as tf from '@tensorflow/tfjs-core';\nimport {backend_util, BackendValues, buffer, DataId, DataStorage, DataType, DataValues, engine, env, kernel_impls, KernelBackend, MemoryInfo, NumericDataType, Rank, RecursiveArray, scalar, ShapeMap, Tensor, Tensor2D, TensorBuffer, TensorInfo, tidy, TimingInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {getWebGLContext} from './canvas_util';\nimport {DecodeMatrixProgram} from './decode_matrix_gpu';\nimport {DecodeMatrixPackedProgram} from './decode_matrix_packed_gpu';\nimport {EncodeFloatProgram} from './encode_float_gpu';\nimport {EncodeFloatPackedProgram} from './encode_float_packed_gpu';\nimport {EncodeMatrixProgram} from './encode_matrix_gpu';\nimport {EncodeMatrixPackedProgram} from './encode_matrix_packed_gpu';\nimport {GPGPUContext} from './gpgpu_context';\nimport * as gpgpu_math from './gpgpu_math';\nimport {GPGPUBinary, GPGPUProgram, TensorData} from './gpgpu_math';\nimport {simpleAbsImplCPU} from './kernel_utils/shared';\nimport {PackProgram} from './pack_gpu';\nimport {ReshapePackedProgram} from './reshape_packed_gpu';\nimport * as tex_util from './tex_util';\nimport {TextureData, TextureUsage} from './tex_util';\nimport {TextureManager} from './texture_manager';\nimport * as unary_op from './unaryop_gpu';\nimport {UnaryOpProgram} from './unaryop_gpu';\nimport {UnaryOpPackedProgram} from './unaryop_packed_gpu';\nimport {UnpackProgram} from './unpack_gpu';\nimport * as webgl_util from './webgl_util';\n\nconst whereImpl = kernel_impls.whereImpl;\n\nexport const EPSILON_FLOAT32 = 1e-7;\nexport const EPSILON_FLOAT16 = 1e-4;\n\ntype KernelInfo = {\n name: string; query: Promise;\n};\n\nexport type TimerNode = RecursiveArray|KernelInfo;\nexport interface CPUTimerQuery {\n startMs: number;\n endMs?: number;\n}\n\nexport interface WebGLMemoryInfo extends MemoryInfo {\n numBytesInGPU: number;\n // Tracks the total number of bytes allocated on the GPU, accounting for the\n // physical texture type.\n numBytesInGPUAllocated: number;\n // Tracks byte size of textures that were created and then made available for\n // reuse (disposed).\n numBytesInGPUFree: number;\n unreliable: boolean;\n}\n\nexport interface WebGLTimingInfo extends TimingInfo {\n uploadWaitMs: number;\n downloadWaitMs: number;\n}\n\nconst binaryCaches: {[webGLVersion: string]: {[key: string]: GPGPUBinary}} = {};\n\nexport function getBinaryCache(webGLVersion: number) {\n if (webGLVersion in binaryCaches) {\n return binaryCaches[webGLVersion];\n }\n binaryCaches[webGLVersion] = {};\n return binaryCaches[webGLVersion];\n}\n\n// Empirically determined constant used to determine size threshold for handing\n// off execution to the CPU.\nconst CPU_HANDOFF_SIZE_THRESHOLD =\n env().getNumber('CPU_HANDOFF_SIZE_THRESHOLD');\n\n// Empirically determined constant used to decide the number of MB on GPU\n// before we warn about high memory use. The MB are this constant * screen area\n// * dpi / 1024 / 1024.\nconst BEFORE_PAGING_CONSTANT = 600;\nfunction numMBBeforeWarning(): number {\n if (env().global.screen == null) {\n return 1024; // 1 GB.\n }\n return (env().global.screen.height * env().global.screen.width *\n window.devicePixelRatio) *\n BEFORE_PAGING_CONSTANT / 1024 / 1024;\n}\n\nexport class MathBackendWebGL extends KernelBackend {\n texData: DataStorage;\n gpgpu: GPGPUContext;\n\n private static nextDataId = 0;\n private nextDataId(): number {\n return MathBackendWebGL.nextDataId++;\n }\n // Maps data ids that have a pending read operation, to list of subscribers.\n private pendingRead = new WeakMap void>>();\n // List of data ids that are scheduled for disposal, but are waiting on a\n // pending read operation.\n private pendingDisposal = new WeakSet();\n\n // Used to count the number of 'shallow' sliced tensors that point to the\n // same data id.\n dataRefCount = new WeakMap();\n private numBytesInGPU = 0;\n\n private canvas: HTMLCanvasElement|OffscreenCanvas;\n\n private programTimersStack: TimerNode[];\n private activeTimers: TimerNode[];\n // Accumulated time spent (including blocking) in uploading data to webgl.\n private uploadWaitMs = 0;\n // Accumulated time spent (including blocking in downloading data from webgl.\n private downloadWaitMs = 0;\n\n // record the last manual GL Flush time.\n private lastGlFlushTime = 0;\n\n // Number of bits of precision of this backend.\n private floatPrecisionValue: 32|16;\n\n private textureManager: TextureManager;\n private binaryCache: {[key: string]: GPGPUBinary};\n private gpgpuCreatedLocally: boolean;\n private numMBBeforeWarning: number;\n private warnedAboutMemory = false;\n\n constructor(gpgpu?: GPGPUContext) {\n super();\n if (!env().getBool('HAS_WEBGL')) {\n throw new Error('WebGL is not supported on this device');\n }\n\n if (gpgpu == null) {\n const gl = getWebGLContext(env().getNumber('WEBGL_VERSION'));\n this.binaryCache = getBinaryCache(env().getNumber('WEBGL_VERSION'));\n this.gpgpu = new GPGPUContext(gl);\n this.canvas = gl.canvas;\n this.gpgpuCreatedLocally = true;\n } else {\n this.gpgpu = gpgpu;\n this.binaryCache = {};\n this.gpgpuCreatedLocally = false;\n this.canvas = gpgpu.gl.canvas;\n }\n this.textureManager = new TextureManager(this.gpgpu);\n this.numMBBeforeWarning = numMBBeforeWarning();\n\n this.texData = new DataStorage(this, engine());\n }\n\n numDataIds() {\n return this.texData.numDataIds() - this.pendingDeletes;\n }\n\n write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n if (env().getBool('WEBGL_CHECK_NUMERICAL_PROBLEMS') ||\n env().getBool('DEBUG')) {\n this.checkNumericalProblems(values);\n }\n if (dtype === 'complex64' && values != null) {\n throw new Error(\n `Cannot write to a complex64 dtype. ` +\n `Please use tf.complex(real, imag).`);\n }\n const dataId = {id: this.nextDataId()};\n this.texData.set(\n dataId,\n {shape, dtype, values, usage: TextureUsage.UPLOAD, refCount: 1});\n return dataId;\n }\n\n /** Return refCount of a `TensorData`. */\n refCount(dataId: DataId): number {\n if (this.texData.has(dataId)) {\n const tensorData = this.texData.get(dataId);\n return tensorData.refCount;\n }\n return 0;\n }\n\n /** Increase refCount of a `TextureData`. */\n incRef(dataId: DataId): void {\n const texData = this.texData.get(dataId);\n texData.refCount++;\n }\n\n /** Decrease refCount of a `TextureData`. */\n decRef(dataId: DataId): void {\n if (this.texData.has(dataId)) {\n const texData = this.texData.get(dataId);\n texData.refCount--;\n }\n }\n\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void {\n if (env().getBool('DEBUG')) {\n this.checkNumericalProblems(values);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `Cannot write to a complex64 dtype. ` +\n `Please use tf.complex(real, imag).`);\n }\n this.texData.set(\n dataId, {shape, dtype, values, usage: TextureUsage.UPLOAD, refCount});\n }\n\n disposeIntermediateTensorInfo(tensorInfo: TensorInfo): void {\n this.disposeData(tensorInfo.dataId);\n }\n\n readSync(dataId: DataId): BackendValues {\n const texData = this.texData.get(dataId);\n const {values, dtype, complexTensorInfos, slice, shape, isPacked} = texData;\n\n // The presence of `slice` indicates this tensor is a shallow slice of a\n // different tensor, and is using that original tensor's texture. Run\n // `clone` in order to copy that texture and read from it.\n if (slice != null) {\n let program;\n if (isPacked) {\n program = new UnaryOpPackedProgram(shape, unary_op.CLONE);\n } else {\n program = new UnaryOpProgram(shape, unary_op.CLONE);\n }\n const res =\n this.runWebGLProgram(program, [{dataId, shape, dtype}], dtype);\n const data = this.readSync(res.dataId);\n this.disposeIntermediateTensorInfo(res);\n return data;\n }\n if (values != null) {\n return this.convertAndCacheOnCPU(dataId);\n }\n if (dtype === 'string') {\n return values;\n }\n const shouldTimeProgram = this.activeTimers != null;\n let start: number;\n if (shouldTimeProgram) {\n start = util.now();\n }\n\n let result: Float32Array;\n if (dtype === 'complex64') {\n const realValues =\n this.readSync(complexTensorInfos.real.dataId) as Float32Array;\n const imagValues =\n this.readSync(complexTensorInfos.imag.dataId) as Float32Array;\n result = backend_util.mergeRealAndImagArrays(realValues, imagValues);\n } else {\n result = this.getValuesFromTexture(dataId);\n }\n\n if (shouldTimeProgram) {\n this.downloadWaitMs += util.now() - start;\n }\n return this.convertAndCacheOnCPU(dataId, result);\n }\n\n async read(dataId: DataId): Promise {\n if (this.pendingRead.has(dataId)) {\n const subscribers = this.pendingRead.get(dataId);\n return new Promise(resolve => subscribers.push(resolve));\n }\n const texData = this.texData.get(dataId);\n const {values, shape, slice, dtype, complexTensorInfos, isPacked} = texData;\n\n // The presence of `slice` indicates this tensor is a shallow slice of a\n // different tensor, and is using that original tensor's texture. Run\n // `clone` in order to copy that texture and read from it.\n if (slice != null) {\n let program;\n if (isPacked) {\n program = new UnaryOpPackedProgram(shape, unary_op.CLONE);\n } else {\n program = new UnaryOpProgram(shape, unary_op.CLONE);\n }\n const res =\n this.runWebGLProgram(program, [{dataId, shape, dtype}], dtype);\n const data = this.read(res.dataId);\n this.disposeIntermediateTensorInfo(res);\n return data;\n }\n\n if (values != null) {\n return this.convertAndCacheOnCPU(dataId);\n }\n\n if (!env().getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED') &&\n env().getNumber('WEBGL_VERSION') === 2) {\n throw new Error(\n `tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and ` +\n `WEBGL_VERSION=2 not yet supported.`);\n }\n\n let buffer = null;\n let tmpDownloadTarget: TensorInfo;\n\n if (dtype !== 'complex64' && env().get('WEBGL_BUFFER_SUPPORTED')) {\n // Possibly copy the texture into a buffer before inserting a fence.\n tmpDownloadTarget = this.decode(dataId);\n const tmpData = this.texData.get(tmpDownloadTarget.dataId);\n\n buffer = this.gpgpu.createBufferFromTexture(\n tmpData.texture, ...tex_util.getDenseTexShape(shape));\n }\n\n this.pendingRead.set(dataId, []);\n\n if (dtype !== 'complex64') {\n // Create a fence and wait for it to resolve.\n await this.gpgpu.createAndWaitForFence();\n }\n\n // Download the values from the GPU.\n let vals: Float32Array;\n if (dtype === 'complex64') {\n const ps = await Promise.all([\n this.read(complexTensorInfos.real.dataId),\n this.read(complexTensorInfos.imag.dataId)\n ]);\n\n const realValues = ps[0];\n const imagValues = ps[1];\n vals = backend_util.mergeRealAndImagArrays(\n realValues as Float32Array, imagValues as Float32Array);\n } else if (buffer == null) {\n vals = this.getValuesFromTexture(dataId);\n } else {\n const size = util.sizeFromShape(shape);\n vals = this.gpgpu.downloadFloat32MatrixFromBuffer(buffer, size);\n }\n if (tmpDownloadTarget != null) {\n this.disposeIntermediateTensorInfo(tmpDownloadTarget);\n }\n const dTypeVals = this.convertAndCacheOnCPU(dataId, vals);\n\n const subscribers = this.pendingRead.get(dataId);\n this.pendingRead.delete(dataId);\n\n // Notify all pending reads.\n subscribers.forEach(resolve => resolve(dTypeVals));\n if (this.pendingDisposal.has(dataId)) {\n this.pendingDisposal.delete(dataId);\n if (this.disposeData(dataId)) {\n engine().removeDataId(dataId, this);\n }\n this.pendingDeletes--;\n }\n return dTypeVals;\n }\n\n bufferSync(t: TensorInfo): TensorBuffer {\n const data = this.readSync(t.dataId);\n let decodedData = data as DataValues;\n if (t.dtype === 'string') {\n try {\n // Decode the bytes into string.\n decodedData = (data as Uint8Array[]).map(d => util.decodeString(d));\n } catch {\n throw new Error('Failed to decode encoded string bytes into utf-8');\n }\n }\n return buffer(t.shape as ShapeMap[R], t.dtype, decodedData) as\n TensorBuffer;\n }\n\n private checkNumericalProblems(values: BackendValues): void {\n if (values == null) {\n return;\n }\n for (let i = 0; i < values.length; i++) {\n const num = values[i] as number;\n if (!webgl_util.canBeRepresented(num)) {\n if (env().getBool('WEBGL_RENDER_FLOAT32_CAPABLE')) {\n throw Error(\n `The value ${num} cannot be represented with your ` +\n `current settings. Consider enabling float32 rendering: ` +\n `'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);\n }\n throw Error(`The value ${num} cannot be represented on this device.`);\n }\n }\n }\n\n private getValuesFromTexture(dataId: DataId): Float32Array {\n const {shape, dtype, isPacked} = this.texData.get(dataId);\n const size = util.sizeFromShape(shape);\n if (env().getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED')) {\n const tmpTarget = this.decode(dataId);\n const tmpData = this.texData.get(tmpTarget.dataId);\n const vals = this.gpgpu\n .downloadMatrixFromPackedTexture(\n tmpData.texture, ...tex_util.getDenseTexShape(shape))\n .subarray(0, size);\n\n this.disposeIntermediateTensorInfo(tmpTarget);\n\n return vals;\n }\n\n const shouldUsePackedProgram =\n env().getBool('WEBGL_PACK') && isPacked === true;\n const outputShape =\n shouldUsePackedProgram ? webgl_util.getShapeAs3D(shape) : shape;\n const program = shouldUsePackedProgram ?\n new EncodeFloatPackedProgram(outputShape as [number, number, number]) :\n new EncodeFloatProgram(outputShape);\n const output = this.runWebGLProgram(\n program, [{shape: outputShape, dtype, dataId}], 'float32');\n const tmpData = this.texData.get(output.dataId);\n const vals =\n this.gpgpu\n .downloadByteEncodedFloatMatrixFromOutputTexture(\n tmpData.texture, tmpData.texShape[0], tmpData.texShape[1])\n .subarray(0, size);\n this.disposeIntermediateTensorInfo(output);\n\n return vals;\n }\n\n timerAvailable(): boolean {\n return env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0;\n }\n\n async time(f: () => void): Promise {\n const oldActiveTimers = this.activeTimers;\n const newActiveTimers: TimerNode[] = [];\n\n let outerMostTime = false;\n if (this.programTimersStack == null) {\n this.programTimersStack = newActiveTimers;\n outerMostTime = true;\n } else {\n this.activeTimers.push(newActiveTimers);\n }\n this.activeTimers = newActiveTimers;\n\n f();\n\n // needing to split these up because util.flatten only accepts certain types\n const flattenedActiveTimerQueries =\n util.flatten(this.activeTimers.map((d: KernelInfo) => d.query))\n .filter(d => d != null);\n const flattenedActiveTimerNames =\n util.flatten(this.activeTimers.map((d: KernelInfo) => d.name))\n .filter(d => d != null);\n\n this.activeTimers = oldActiveTimers;\n\n if (outerMostTime) {\n this.programTimersStack = null;\n }\n\n const res: WebGLTimingInfo = {\n uploadWaitMs: this.uploadWaitMs,\n downloadWaitMs: this.downloadWaitMs,\n kernelMs: null,\n wallMs: null // will be filled by the engine\n };\n\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {\n const kernelMs = await Promise.all(flattenedActiveTimerQueries);\n\n res['kernelMs'] = util.sum(kernelMs);\n res['getExtraProfileInfo'] = () =>\n kernelMs.map((d, i) => ({name: flattenedActiveTimerNames[i], ms: d}))\n .map(d => `${d.name}: ${d.ms}`)\n .join(', ');\n } else {\n res['kernelMs'] = {\n error: 'WebGL query timers are not supported in this environment.'\n };\n }\n\n this.uploadWaitMs = 0;\n this.downloadWaitMs = 0;\n return res;\n }\n memory(): WebGLMemoryInfo {\n return {\n unreliable: false,\n numBytesInGPU: this.numBytesInGPU,\n numBytesInGPUAllocated: this.textureManager.numBytesAllocated,\n numBytesInGPUFree: this.textureManager.numBytesFree\n } as WebGLMemoryInfo;\n }\n\n private startTimer(): WebGLQuery|CPUTimerQuery {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {\n return this.gpgpu.beginQuery();\n }\n return {startMs: util.now(), endMs: null};\n }\n\n private endTimer(query: WebGLQuery|CPUTimerQuery): WebGLQuery|CPUTimerQuery {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {\n this.gpgpu.endQuery();\n return query;\n }\n (query as CPUTimerQuery).endMs = util.now();\n return query;\n }\n\n private async getQueryTime(query: WebGLQuery|CPUTimerQuery): Promise {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {\n return this.gpgpu.waitForQueryAndGetTime(query as WebGLQuery);\n }\n const timerQuery = query as CPUTimerQuery;\n return timerQuery.endMs - timerQuery.startMs;\n }\n\n private pendingDeletes = 0;\n\n /**\n * Decrease the RefCount on the dataId and dispose the memory if the dataId\n * has 0 refCount. If there are pending read on the data, the disposal would\n * added to the pending delete queue. Return true if the dataId is removed\n * from backend or the backend does not contain the dataId, false if the\n * dataId is not removed. Memory may or may not be released even when dataId\n * is removed, which also depends on dataRefCount, see `releaseGPU`.\n * @param dataId\n * @oaram force Optional, remove the data regardless of refCount\n */\n disposeData(dataId: DataId, force = false): boolean {\n if (this.pendingDisposal.has(dataId)) {\n return false;\n }\n\n // No-op if already disposed.\n if (!this.texData.has(dataId)) {\n return true;\n }\n\n // if force flag is set, change refCount to 0, this would ensure disposal\n // when added to the pendingDisposal queue. Memory may or may not be\n // released, which also depends on dataRefCount, see `releaseGPU`.\n if (force) {\n this.texData.get(dataId).refCount = 0;\n } else {\n this.texData.get(dataId).refCount--;\n }\n\n if (!force && this.texData.get(dataId).refCount > 0) {\n return false;\n }\n\n if (this.pendingRead.has(dataId)) {\n this.pendingDisposal.add(dataId);\n this.pendingDeletes++;\n return false;\n }\n\n this.releaseGPUData(dataId);\n const {complexTensorInfos} = this.texData.get(dataId);\n if (complexTensorInfos != null) {\n this.disposeData(complexTensorInfos.real.dataId, force);\n this.disposeData(complexTensorInfos.imag.dataId, force);\n }\n\n this.texData.delete(dataId);\n\n return true;\n }\n\n private releaseGPUData(dataId: DataId): void {\n const {texture, dtype, texShape, usage, isPacked, slice} =\n this.texData.get(dataId);\n const key = slice && slice.origDataId || dataId;\n const refCount = this.dataRefCount.get(key);\n\n if (refCount > 1) {\n this.dataRefCount.set(key, refCount - 1);\n } else {\n this.dataRefCount.delete(key);\n if (texture != null) {\n this.numBytesInGPU -= this.computeBytes(texShape, dtype);\n this.textureManager.releaseTexture(texture, texShape, usage, isPacked);\n }\n }\n\n const texData = this.texData.get(dataId);\n texData.texture = null;\n texData.texShape = null;\n texData.isPacked = false;\n texData.slice = null;\n }\n\n getTexture(dataId: DataId): WebGLTexture {\n this.uploadToGPU(dataId);\n return this.texData.get(dataId).texture;\n }\n\n /**\n * Returns internal information for the specific data bucket. Used in unit\n * tests.\n */\n getDataInfo(dataId: DataId): TextureData {\n return this.texData.get(dataId);\n }\n\n /*\n Tests whether all the inputs to an op are small and on the CPU. This heuristic\n determines when it would be faster to execute a kernel on the CPU. WebGL\n kernels opt into running this check and forwarding when appropriate.\n TODO(https://github.com/tensorflow/tfjs/issues/872): Develop a more\n sustainable strategy for optimizing backend execution of ops.\n */\n shouldExecuteOnCPU(\n inputs: TensorInfo[],\n sizeThreshold = CPU_HANDOFF_SIZE_THRESHOLD): boolean {\n return env().getBool('WEBGL_CPU_FORWARD') &&\n inputs.every(\n input => this.texData.get(input.dataId).texture == null &&\n util.sizeFromShape(input.shape) < sizeThreshold);\n }\n\n getGPGPUContext(): GPGPUContext {\n return this.gpgpu;\n }\n\n where(condition: Tensor): Tensor2D {\n backend_util.warn(\n 'tf.where() in webgl locks the UI thread. ' +\n 'Call tf.whereAsync() instead');\n const condVals = condition.dataSync();\n return whereImpl(condition.shape, condVals);\n }\n\n private packedUnaryOp(x: TensorInfo, op: string, dtype: DataType) {\n const program = new UnaryOpPackedProgram(x.shape, op);\n const outInfo = this.compileAndRun(program, [x], dtype);\n return engine().makeTensorFromDataId(\n outInfo.dataId, outInfo.shape, outInfo.dtype);\n }\n\n // TODO(msoulanille) remove this once the backend has been modularized\n // a copy is needed here to break a circular dependency.\n // Also remove the op from unary_op.\n abs(x: T): T {\n // TODO: handle cases when x is complex.\n if (this.shouldExecuteOnCPU([x]) && x.dtype !== 'complex64') {\n const outValues =\n simpleAbsImplCPU(this.texData.get(x.dataId).values as TypedArray);\n return this.makeOutput(x.shape, x.dtype, outValues);\n }\n\n if (env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {\n return this.packedUnaryOp(x, unary_op.ABS, x.dtype) as T;\n }\n\n const program = new UnaryOpProgram(x.shape, unary_op.ABS);\n const outInfo = this.compileAndRun(program, [x]);\n return engine().makeTensorFromDataId(\n outInfo.dataId, outInfo.shape, outInfo.dtype) as T;\n }\n\n makeTensorInfo(\n shape: number[], dtype: DataType,\n values?: BackendValues|string[]): TensorInfo {\n let dataId;\n if (dtype === 'string' && values != null && values.length > 0 &&\n util.isString(values[0])) {\n const encodedValues =\n (values as {} as string[]).map(d => util.encodeString(d));\n\n dataId = this.write(encodedValues, shape, dtype);\n } else {\n dataId = this.write(values as TypedArray, shape, dtype);\n }\n\n this.texData.get(dataId).usage = null;\n return {dataId, shape, dtype};\n }\n\n private makeOutput(\n shape: number[], dtype: DataType, values?: BackendValues): T {\n const {dataId} = this.makeTensorInfo(shape, dtype, values);\n return engine().makeTensorFromDataId(dataId, shape, dtype, this) as T;\n }\n\n private unpackTensor(input: TensorInfo): TensorInfo {\n const program = new UnpackProgram(input.shape);\n return this.runWebGLProgram(program, [input], input.dtype);\n }\n\n private packTensor(input: TensorInfo): TensorInfo {\n const program = new PackProgram(input.shape);\n const preventEagerUnpackingOutput = true;\n return this.runWebGLProgram(\n program, [input], input.dtype, null /* customSetup */,\n preventEagerUnpackingOutput);\n }\n\n private packedReshape(input: TensorInfo, afterShape: number[]): TensorInfo {\n const input3DShape = [\n webgl_util.getBatchDim(input.shape),\n ...webgl_util.getRowsCols(input.shape)\n ] as [number, number, number];\n const input3D: TensorInfo = {\n dtype: input.dtype,\n shape: input3DShape,\n dataId: input.dataId\n };\n const afterShapeAs3D = [\n webgl_util.getBatchDim(afterShape), ...webgl_util.getRowsCols(afterShape)\n ] as [number, number, number];\n\n const program = new ReshapePackedProgram(afterShapeAs3D, input3DShape);\n const preventEagerUnpackingOfOutput = true;\n const output = this.runWebGLProgram(\n program, [input3D], input.dtype, null /* customSetup */,\n preventEagerUnpackingOfOutput);\n return {dataId: output.dataId, shape: afterShape, dtype: output.dtype};\n }\n\n private decode(dataId: DataId): TensorInfo {\n const texData = this.texData.get(dataId);\n const {isPacked, shape, dtype} = texData;\n const shapeAs3D =\n webgl_util.getShapeAs3D(shape) as [number, number, number];\n let program;\n if (isPacked) {\n program = new DecodeMatrixPackedProgram(shapeAs3D);\n } else {\n program = new DecodeMatrixProgram(shapeAs3D);\n }\n const preventEagerUnpackingOfOutput = true;\n const out = this.runWebGLProgram(\n program, [{shape: shapeAs3D, dtype, dataId}], dtype,\n null /* customSetup */, preventEagerUnpackingOfOutput);\n return {dtype, shape, dataId: out.dataId};\n }\n\n runWebGLProgram(\n program: GPGPUProgram, inputs: TensorInfo[], outputDtype: DataType,\n customSetup?: (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => void,\n preventEagerUnpackingOfOutput = false): TensorInfo {\n const output = this.makeTensorInfo(program.outputShape, outputDtype);\n const outData = this.texData.get(output.dataId);\n if (program.packedOutput) {\n outData.isPacked = true;\n }\n if (program.outPackingScheme === tex_util.PackingScheme.DENSE) {\n const texelShape = tex_util.getDenseTexShape(program.outputShape);\n // For a densely packed output, we explicitly set texShape\n // so it doesn't get assigned later according to our typical packing\n // scheme wherein a single texel can only contain values from adjacent\n // rows/cols.\n outData.texShape = texelShape.map(d => d * 2) as [number, number];\n }\n if (program.outTexUsage != null) {\n outData.usage = program.outTexUsage;\n }\n if (util.sizeFromShape(output.shape) === 0) {\n // Short-circuit the computation since the result is empty (has 0 in its\n // shape).\n outData.values =\n util.getTypedArrayFromDType(output.dtype as 'float32', 0);\n return output;\n }\n\n const dataToDispose: TensorInfo[] = [];\n const inputsData: TensorData[] = inputs.map(input => {\n if (input.dtype === 'complex64') {\n throw new Error(\n `GPGPUProgram does not support complex64 input. For complex64 ` +\n `dtypes, please separate the program into real and imaginary ` +\n `parts.`);\n }\n\n let texData = this.texData.get(input.dataId);\n\n if (texData.texture == null) {\n if (!program.packedInputs &&\n util.sizeFromShape(input.shape) <=\n env().getNumber('WEBGL_SIZE_UPLOAD_UNIFORM')) {\n // Upload small tensors that live on the CPU as uniforms, not as\n // textures. Do this only when the environment supports 32bit floats\n // due to problems when comparing 16bit floats with 32bit floats.\n // TODO(https://github.com/tensorflow/tfjs/issues/821): Make it\n // possible for packed shaders to sample from uniforms.\n return {\n shape: input.shape,\n texData: null,\n isUniform: true,\n uniformValues: texData.values as TypedArray\n };\n }\n\n // This ensures that if a packed program's inputs have not yet been\n // uploaded to the GPU, they get uploaded as packed right off the bat.\n if (program.packedInputs) {\n texData.isPacked = true;\n texData.shape = input.shape;\n }\n } else if (!!texData.isPacked !== !!program.packedInputs) {\n input = texData.isPacked ? this.unpackTensor(input) :\n this.packTensor(input);\n dataToDispose.push(input);\n texData = this.texData.get(input.dataId);\n } else if (\n texData.isPacked &&\n !webgl_util.isReshapeFree(texData.shape, input.shape)) {\n // This is a special case where a texture exists for a tensor\n // but the shapes are incompatible (due to packing constraints) because\n // the tensor did not have a chance to go through the packed reshape\n // shader. This only happens when we reshape the *same* tensor to form\n // *distinct* inputs to an op, e.g. dotting a vector with itself. This\n // case will disappear once packed uploading is the default.\n\n const savedInput = input;\n const targetShape = input.shape;\n\n input.shape = texData.shape;\n input = this.packedReshape(input as Tensor, targetShape);\n dataToDispose.push(input);\n texData = this.texData.get(input.dataId);\n\n savedInput.shape = targetShape;\n }\n\n this.uploadToGPU(input.dataId);\n return {shape: input.shape, texData, isUniform: false};\n });\n\n this.uploadToGPU(output.dataId);\n const outputData:\n TensorData = {shape: output.shape, texData: outData, isUniform: false};\n const key = gpgpu_math.makeShaderKey(program, inputsData, outputData);\n const binary = this.getAndSaveBinary(key, () => {\n return gpgpu_math.compileProgram(\n this.gpgpu, program, inputsData, outputData);\n });\n const shouldTimeProgram = this.activeTimers != null;\n let query: WebGLQuery|CPUTimerQuery;\n if (shouldTimeProgram) {\n query = this.startTimer();\n }\n\n gpgpu_math.runProgram(\n this.gpgpu, binary, inputsData, outputData, customSetup);\n\n dataToDispose.forEach(info => this.disposeIntermediateTensorInfo(info));\n\n if (shouldTimeProgram) {\n query = this.endTimer(query);\n this.activeTimers.push(\n {name: program.constructor.name, query: this.getQueryTime(query)});\n }\n\n const glFlushThreshold = env().get('WEBGL_FLUSH_THRESHOLD');\n // Manually GL flush requested\n if (glFlushThreshold > 0) {\n const time = util.now();\n if ((time - this.lastGlFlushTime) > glFlushThreshold) {\n this.gpgpu.gl.flush();\n this.lastGlFlushTime = time;\n }\n }\n\n if (!env().getBool('WEBGL_LAZILY_UNPACK') && outData.isPacked &&\n preventEagerUnpackingOfOutput === false) {\n const unpacked = this.unpackTensor(output);\n this.disposeIntermediateTensorInfo(output);\n return unpacked;\n }\n return output;\n }\n\n compileAndRun(\n program: GPGPUProgram, inputs: TensorInfo[], outputDtype?: DataType,\n customSetup?: (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => void,\n preventEagerUnpackingOfOutput = false): TensorInfo {\n outputDtype = outputDtype || inputs[0].dtype;\n const outInfo = this.runWebGLProgram(\n program, inputs, outputDtype, customSetup,\n preventEagerUnpackingOfOutput);\n return outInfo;\n }\n\n private getAndSaveBinary(key: string, getBinary: () => GPGPUBinary):\n GPGPUBinary {\n if (!(key in this.binaryCache)) {\n this.binaryCache[key] = getBinary();\n }\n return this.binaryCache[key];\n }\n\n getTextureManager(): TextureManager {\n return this.textureManager;\n }\n\n private disposed = false;\n\n dispose() {\n if (this.disposed) {\n return;\n }\n // Avoid disposing the compiled webgl programs during unit testing because\n // it slows down test execution.\n if (!env().getBool('IS_TEST')) {\n const allKeys = Object.keys(this.binaryCache);\n allKeys.forEach(key => {\n this.gpgpu.deleteProgram(this.binaryCache[key].webGLProgram);\n delete this.binaryCache[key];\n });\n }\n this.textureManager.dispose();\n if (this.canvas != null &&\n (typeof (HTMLCanvasElement) !== 'undefined' &&\n this.canvas instanceof HTMLCanvasElement)) {\n this.canvas.remove();\n } else {\n this.canvas = null;\n }\n if (this.gpgpuCreatedLocally) {\n this.gpgpu.program = null;\n this.gpgpu.dispose();\n }\n this.disposed = true;\n }\n\n floatPrecision(): 16|32 {\n if (this.floatPrecisionValue == null) {\n this.floatPrecisionValue = tidy(() => {\n if (!env().get('WEBGL_RENDER_FLOAT32_ENABLED')) {\n // Momentarily switching DEBUG flag to false so we don't throw an\n // error trying to upload a small value.\n const debugFlag = env().getBool('DEBUG');\n env().set('DEBUG', false);\n const underflowCheckValue = this.abs(scalar(1e-8)).dataSync()[0];\n env().set('DEBUG', debugFlag);\n\n if (underflowCheckValue > 0) {\n return 32;\n }\n }\n return 16;\n });\n }\n return this.floatPrecisionValue;\n }\n\n /** Returns the smallest representable number. */\n epsilon(): number {\n return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n }\n\n uploadToGPU(dataId: DataId): void {\n const texData = this.texData.get(dataId);\n const {shape, dtype, values, texture, usage, isPacked} = texData;\n\n if (texture != null) {\n // Array is already on GPU. No-op.\n return;\n }\n const shouldTimeProgram = this.activeTimers != null;\n let start: number;\n if (shouldTimeProgram) {\n start = util.now();\n }\n\n let texShape = texData.texShape;\n if (texShape == null) {\n texShape = webgl_util.getTextureShapeFromLogicalShape(shape, isPacked);\n texData.texShape = texShape;\n }\n\n if (values != null) {\n const shapeAs3D = webgl_util.getShapeAs3D(shape);\n\n let program;\n let width = texShape[1], height = texShape[0];\n const isByteArray = values instanceof Uint8Array;\n\n if (isPacked) {\n [width, height] = tex_util.getPackedMatrixTextureShapeWidthHeight(\n texShape[0], texShape[1]);\n program = new EncodeMatrixPackedProgram(\n shapeAs3D, [height, width], isByteArray);\n } else {\n program =\n new EncodeMatrixProgram(shapeAs3D, [height, width], isByteArray);\n }\n\n const tempDenseInputHandle = this.makeTensorInfo([height, width], dtype);\n if (isByteArray) {\n this.texData.get(tempDenseInputHandle.dataId).usage =\n TextureUsage.PIXELS;\n } else {\n this.texData.get(tempDenseInputHandle.dataId).usage =\n TextureUsage.UPLOAD;\n }\n this.gpgpu.uploadDenseMatrixToTexture(\n this.getTexture(tempDenseInputHandle.dataId), width, height,\n values as TypedArray);\n\n // We want the output to remain packed regardless of the value of\n // WEBGL_PACK.\n const preventEagerUnpacking = true;\n const encodedOutputTarget = this.runWebGLProgram(\n program, [tempDenseInputHandle], dtype, null, preventEagerUnpacking);\n\n // Have the original texture assume the identity of the encoded output.\n const outputTexData = this.texData.get(encodedOutputTarget.dataId);\n texData.texture = outputTexData.texture;\n texData.texShape = outputTexData.texShape;\n texData.isPacked = outputTexData.isPacked;\n texData.usage = outputTexData.usage;\n\n this.disposeIntermediateTensorInfo(tempDenseInputHandle);\n this.texData.delete(encodedOutputTarget.dataId);\n\n // Once uploaded, don't store the values on cpu.\n texData.values = null;\n if (shouldTimeProgram) {\n this.uploadWaitMs += util.now() - start;\n }\n } else {\n const newTexture = this.acquireTexture(texShape, usage, dtype, isPacked);\n texData.texture = newTexture;\n }\n }\n\n private convertAndCacheOnCPU(dataId: DataId, float32Values?: Float32Array):\n TypedArray {\n const texData = this.texData.get(dataId);\n const {dtype} = texData;\n\n this.releaseGPUData(dataId);\n\n if (float32Values != null) {\n texData.values = float32ToTypedArray(float32Values, dtype as 'float32');\n }\n return texData.values as TypedArray;\n }\n\n private acquireTexture(\n texShape: [number, number], texType: TextureUsage, dtype: DataType,\n isPacked: boolean): WebGLTexture {\n this.numBytesInGPU += this.computeBytes(texShape, dtype);\n if (!this.warnedAboutMemory &&\n this.numBytesInGPU > this.numMBBeforeWarning * 1024 * 1024) {\n const mb = (this.numBytesInGPU / 1024 / 1024).toFixed(2);\n this.warnedAboutMemory = true;\n console.warn(\n `High memory usage in GPU: ${mb} MB, ` +\n `most likely due to a memory leak`);\n }\n return this.textureManager.acquireTexture(texShape, texType, isPacked);\n }\n\n private computeBytes(shape: [number, number], dtype: DataType) {\n return shape[0] * shape[1] * util.bytesPerElement(dtype);\n }\n}\n\nfunction float32ToTypedArray(\n a: Float32Array, dtype: D): tf.DataTypeMap[D] {\n if (dtype === 'float32' || dtype === 'complex64') {\n return a as tf.DataTypeMap[D];\n } else if (dtype === 'int32' || dtype === 'bool') {\n const result = (dtype === 'int32') ? new Int32Array(a.length) :\n new Uint8Array(a.length);\n for (let i = 0; i < result.length; ++i) {\n result[i] = Math.round(a[i]);\n }\n return result as tf.DataTypeMap[D];\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n","/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '3.7.0';\nexport {version};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nimport * as gpgpu_util from './gpgpu_util';\nimport * as webgl_util from './webgl_util';\n\nexport {MathBackendWebGL, WebGLMemoryInfo, WebGLTimingInfo} from './backend_webgl';\nexport {setWebGLContext} from './canvas_util';\nexport {GPGPUContext} from './gpgpu_context';\nexport {GPGPUProgram} from './gpgpu_math';\n// WebGL specific utils.\nexport {gpgpu_util, webgl_util};\n\n/**\n * Enforce use of half precision textures if available on the platform.\n *\n * @doc {heading: 'Environment', namespace: 'webgl'}\n */\nexport function forceHalfFloat(): void {\n env().set('WEBGL_FORCE_F16_TEXTURES', true);\n}\n","/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// base.ts is the webgl backend without auto kernel registration.\n\nimport {device_util, registerBackend} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from './backend_webgl';\nexport {version as version_webgl} from './version';\n\nif (device_util.isBrowser()) {\n registerBackend('webgl', () => new MathBackendWebGL(), 2 /* priority */);\n}\n\n// Export webgl utilities\nexport * from './webgl';\n\n// Export forceHalfFlost under webgl namespace for the union bundle.\nimport {forceHalfFloat} from './webgl';\nexport const webgl = {forceHalfFloat};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport const CHECK_NAN_SNIPPET = `\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n`;\n\nexport const SQUARED_DIFFERENCE = 'return (a - b) * (a - b);';\nexport class BinaryOpProgram implements GPGPUProgram {\n variableNames = ['A', 'B'];\n outputShape: number[];\n userCode: string;\n\n constructor(op: string, aShape: number[], bShape: number[]) {\n this.outputShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n this.userCode = `\n float binaryOperation(float a, float b) {\n ${op}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport const CHECK_NAN_SNIPPET = `\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\nexport const ELU_DER = `\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n`;\n\nexport const NOT_EQUAL = `\n return vec4(notEqual(a, b));\n`;\n\nexport class BinaryOpPackedProgram implements GPGPUProgram {\n variableNames = ['A', 'B'];\n outputShape: number[];\n userCode: string;\n supportsBroadcasting = true;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n op: string, aShape: number[], bShape: number[],\n checkOutOfBounds = false) {\n this.outputShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n const rank = this.outputShape.length;\n let checkOutOfBoundsString = '';\n if (checkOutOfBounds) {\n if (rank === 0 || util.sizeFromShape(this.outputShape) === 1) {\n checkOutOfBoundsString = `\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n `;\n } else {\n const dtype = getCoordsDataType(rank);\n checkOutOfBoundsString = `\n ${dtype} coords = getOutputCoords();\n `;\n if (rank === 1) {\n checkOutOfBoundsString += `\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;\n } else {\n const channels = getChannels('coords', rank);\n checkOutOfBoundsString += `\n bool nextRowOutOfBounds =\n (${channels[rank - 2]} + 1) >= ${this.outputShape[rank - 2]};\n bool nextColOutOfBounds =\n (${channels[rank - 1]} + 1) >= ${this.outputShape[rank - 1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `;\n }\n }\n }\n\n this.userCode = `\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${op}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${checkOutOfBoundsString}\n\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Identity, IdentityInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function identity(\n args: {inputs: IdentityInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n backend.incRef(x.dataId);\n\n return {dataId: x.dataId, shape: x.shape, dtype: x.dtype};\n}\n\nexport const identityConfig: KernelConfig = {\n kernelName: Identity,\n backendName: 'webgl',\n kernelFunc: identity as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Complex, ComplexInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\n/**\n * In WebGL data is stored in GPU textures which can't be efficiently copied, so\n * complex tensors share data with their real and imaginary components. Complex\n * tensors' reference to the components is tracked by refCount on the individual\n * component. The refCounts are increased by the identity call.\n *\n * When a complex tensor is disposed, it will reduce the refCount on the\n * components by calling disposeData on each.\n */\nexport function complex(\n args: {inputs: ComplexInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {real, imag} = inputs;\n\n const complexInfo = backend.makeTensorInfo(real.shape, 'complex64');\n const complex = backend.texData.get(complexInfo.dataId);\n\n const realTensorInfo = identity({inputs: {x: real}, backend});\n\n const imagTensorInfo = identity({inputs: {x: imag}, backend});\n\n complex.complexTensorInfos = {real: realTensorInfo, imag: imagTensorInfo};\n\n return complexInfo;\n}\n\nexport const complexConfig: KernelConfig = {\n kernelName: Complex,\n backendName: 'webgl',\n kernelFunc: complex as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, LeakyRelu, LeakyReluAttrs, LeakyReluInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\n\nexport const LEAKYRELU = `return (a < 0.) ? b * a : a;`;\nexport const LEAKYRELU_PACKED = `\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n`;\n\nexport function leakyRelu(args: {\n inputs: LeakyReluInputs,\n backend: MathBackendWebGL,\n attrs: LeakyReluAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {alpha} = attrs;\n\n const $alpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(alpha as {} as 'float32', 'float32'));\n\n const program = env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ?\n new BinaryOpPackedProgram(LEAKYRELU_PACKED, x.shape, $alpha.shape) :\n new BinaryOpProgram(LEAKYRELU, x.shape, $alpha.shape);\n const result = backend.runWebGLProgram(program, [x, $alpha], x.dtype);\n\n backend.disposeIntermediateTensorInfo($alpha);\n\n return result;\n}\n\nexport const leakyReluConfig: KernelConfig = {\n kernelName: LeakyRelu,\n backendName: 'webgl',\n kernelFunc: leakyRelu as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, Prelu, PreluInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\n\nexport const PRELU = `return (a < 0.) ? b * a : a;`;\nexport const PRELU_PACKED = `\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n`;\n\nexport function prelu(args: {inputs: PreluInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x, alpha} = inputs;\n\n const program = env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ?\n new BinaryOpPackedProgram(PRELU_PACKED, x.shape, alpha.shape) :\n new BinaryOpProgram(PRELU, x.shape, alpha.shape);\n return backend.runWebGLProgram(program, [x, alpha], x.dtype);\n}\n\nexport const preluConfig: KernelConfig = {\n kernelName: Prelu,\n backendName: 'webgl',\n kernelFunc: prelu as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BinaryInputs, DataType, env, KernelFunc, TypedArray, UnaryInputs, upcastType} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\nimport {complex} from '../kernels/Complex';\nimport {LEAKYRELU, LEAKYRELU_PACKED} from '../kernels/LeakyRelu';\nimport {PRELU, PRELU_PACKED} from '../kernels/Prelu';\nimport * as unary_op from '../unaryop_gpu';\nimport {UnaryOpProgram} from '../unaryop_gpu';\nimport * as unary_packed_op from '../unaryop_packed_gpu';\nimport {UnaryOpPackedProgram} from '../unaryop_packed_gpu';\n\nimport {SimpleBinaryKernelImplCPU, SimpleUnaryKernelImplCPU} from './shared';\n\nexport const CHECK_NAN_SNIPPET_UNARY = `if (isnan(x)) return x;`;\n\nexport const CHECK_NAN_SNIPPET_BINARY = `\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n`;\n\nexport const CHECK_NAN_SNIPPET_BINARY_PACKED = `\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\ntype UnaryKernelFuncConfig = {\n opSnippet: string,\n packedOpSnippet?: string,\n cpuKernelImpl?: SimpleUnaryKernelImplCPU,\n dtype?: DataType\n};\n\n/**\n * Template that creates a `KernelFunc` for unary ops.\n * @param opSnippet Op snippet to create `UnaryOpProgram`.\n * @param packedOpSnippet Op snippet to create `UnaryOpPackedProgram`.\n * @param dtype Optional. If set, the result has this dtype. Otherwise, the\n * result has the same dtype as the first input. This is mainly used in\n * comparison kernels, such as Equal, Less, Greater, etc.\n */\nexport function unaryKernelFunc(\n {opSnippet, packedOpSnippet, cpuKernelImpl, dtype}: UnaryKernelFuncConfig):\n KernelFunc {\n return ({inputs, backend}) => {\n const {x} = inputs as UnaryInputs;\n const webglBackend = backend as MathBackendWebGL;\n\n const $dtype = dtype || x.dtype;\n if (webglBackend.shouldExecuteOnCPU([x]) && cpuKernelImpl != null) {\n const xData = webglBackend.texData.get(x.dataId);\n const outValues = cpuKernelImpl(xData.values as TypedArray, $dtype);\n return webglBackend.makeTensorInfo(x.shape, $dtype, outValues);\n }\n\n const shouldUsePackedProgram =\n env().getBool('WEBGL_PACK_UNARY_OPERATIONS') && packedOpSnippet != null;\n let program: UnaryOpProgram|UnaryOpPackedProgram;\n if (shouldUsePackedProgram) {\n program = new UnaryOpPackedProgram(x.shape, packedOpSnippet);\n } else {\n program = new UnaryOpProgram(x.shape, opSnippet);\n }\n\n return webglBackend.runWebGLProgram(program, [x], $dtype);\n };\n}\n\ntype BinaryKernelFuncConfig = {\n opSnippet: string,\n packedOpSnippet?: string,\n checkOutOfBounds?: boolean,\n supportsComplex?: boolean,\n cpuKernelImpl?: SimpleBinaryKernelImplCPU,\n dtype?: DataType\n};\n\n/**\n * Template that creates a `KernelFunc` for binary ops.\n * @param opSnippet Op snippet to create `BinaryOpProgram`.\n * @param packedOpSnippet Op snippet to create `BinaryOpPackedProgram`.\n * @param checkOutOfBoundsForPackedProgram Whether to set checkOutOfBounds=true\n * when creating BinaryOpPackedProgram.\n * @param dtype Optional. If set, the result has this dtype. Otherwise, the\n * result has the same dtype as the first input. This is mainly used in\n * comparison kernels, such as Equal, Less, Greater, etc.\n */\nexport function binaryKernelFunc({\n opSnippet,\n packedOpSnippet,\n checkOutOfBounds = false,\n supportsComplex = false,\n cpuKernelImpl,\n dtype\n}: BinaryKernelFuncConfig): KernelFunc {\n return ({inputs, backend}) => {\n const {a, b} = inputs as BinaryInputs;\n const webglBackend = backend as MathBackendWebGL;\n\n if (supportsComplex && a.dtype === 'complex64') {\n const aData = webglBackend.texData.get(a.dataId);\n const bData = webglBackend.texData.get(b.dataId);\n\n const [real, imag] = [\n [aData.complexTensorInfos.real, bData.complexTensorInfos.real],\n [aData.complexTensorInfos.imag, bData.complexTensorInfos.imag]\n ].map(complexParts => {\n const [aPart, bPart] = complexParts;\n\n const aHandle = {\n dataId: aPart.dataId,\n dtype: aPart.dtype,\n shape: a.shape\n };\n const bHandle = {\n dataId: bPart.dataId,\n dtype: bPart.dtype,\n shape: b.shape\n };\n\n const program = new BinaryOpProgram(opSnippet, a.shape, b.shape);\n return webglBackend.runWebGLProgram(\n program, [aHandle, bHandle], upcastType(aPart.dtype, bPart.dtype));\n });\n\n const complexOutput =\n complex({inputs: {real, imag}, backend: webglBackend});\n\n webglBackend.disposeIntermediateTensorInfo(real);\n webglBackend.disposeIntermediateTensorInfo(imag);\n\n // TODO(annxingyuan): Implement CPU forwarding for complex inputs.\n\n return complexOutput;\n }\n\n const $dtype = dtype || upcastType(a.dtype, b.dtype);\n if ((a.dtype === 'string' || b.dtype === 'string' ||\n webglBackend.shouldExecuteOnCPU([a, b])) &&\n cpuKernelImpl != null) {\n const aVals = webglBackend.texData.get(a.dataId).values as TypedArray;\n const bVals = webglBackend.texData.get(b.dataId).values as TypedArray;\n\n const decodedAVals = a.dtype === 'string' ?\n // tslint:disable-next-line: no-any\n backend_util.fromUint8ToStringArray(aVals as any as Uint8Array[]) :\n aVals;\n const decodedBVals = a.dtype === 'string' ?\n // tslint:disable-next-line: no-any\n backend_util.fromUint8ToStringArray(bVals as any as Uint8Array[]) :\n bVals;\n const [outValues, outShape] =\n cpuKernelImpl(a.shape, b.shape, decodedAVals, decodedBVals, $dtype);\n\n const out = webglBackend.makeTensorInfo(outShape, $dtype);\n const outData = webglBackend.texData.get(out.dataId);\n outData.values = outValues;\n return out;\n }\n\n const shouldUsePackedProgram =\n env().getBool('WEBGL_PACK_BINARY_OPERATIONS') &&\n packedOpSnippet != null;\n let program: BinaryOpProgram|BinaryOpPackedProgram;\n if (shouldUsePackedProgram) {\n program = new BinaryOpPackedProgram(\n packedOpSnippet, a.shape, b.shape, checkOutOfBounds);\n } else {\n program = new BinaryOpProgram(opSnippet, a.shape, b.shape);\n }\n\n return webglBackend.runWebGLProgram(program, [a, b], $dtype);\n };\n}\n\nexport function mapActivationToShaderProgram(\n activation: backend_util.Activation, packed = false): string {\n if (activation === 'linear') {\n if (packed) {\n return unary_packed_op.LINEAR;\n }\n return unary_op.LINEAR;\n } else if (activation === 'relu') {\n if (packed) {\n return unary_packed_op.RELU;\n }\n return unary_op.RELU;\n } else if (activation === 'elu') {\n if (packed) {\n return unary_packed_op.ELU;\n }\n return unary_op.ELU;\n } else if (activation === 'relu6') {\n if (packed) {\n return unary_packed_op.RELU6;\n }\n return unary_op.RELU6;\n } else if (activation === 'prelu') {\n if (packed) {\n return PRELU_PACKED;\n }\n return PRELU;\n } else if (activation === 'leakyrelu') {\n if (packed) {\n return LEAKYRELU_PACKED;\n }\n return LEAKYRELU;\n } else if (activation === 'sigmoid') {\n if (packed) {\n return unary_packed_op.SIGMOID;\n }\n return unary_op.SIGMOID;\n }\n throw new Error(`Activation ${\n activation} has not been implemented for the WebGL backend.`);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class MatMulPackedProgram implements GPGPUProgram {\n variableNames = ['matrixA', 'matrixB'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(\n aShape: [number, number, number], bShape: [number, number, number],\n outputShape: [number, number, number], transposeA = false,\n transposeB = false, addBias = false, activation: string = null,\n hasPreluActivation = false, hasLeakyreluActivation = false) {\n this.outputShape = outputShape;\n\n const sharedDim = transposeA ? aShape[1] : aShape[2];\n const sharedDimensionPacked = Math.ceil(sharedDim / 2);\n\n const aSample = transposeA ? 'i * 2, rc.y' : 'rc.y, i * 2';\n const bSample = transposeB ? 'rc.z, i * 2' : 'i * 2, rc.z';\n const aSwizzle = transposeA ? ['a.xxyy', 'a.zzww'] : ['a.xxzz', 'a.yyww'];\n const bSwizzle = transposeB ? ['b.xzxz', 'b.ywyw'] : ['b.xyxy', 'b.zwzw'];\n\n let activationSnippet = '', applyActivationSnippet = '';\n if (activation) {\n if (hasPreluActivation) {\n activationSnippet = `vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${activation}\n }`;\n } else if (hasLeakyreluActivation) {\n activationSnippet = `vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${activation}\n }`;\n } else {\n activationSnippet = `vec4 activation(vec4 x) {\n ${activation}\n }`;\n }\n\n applyActivationSnippet = `result = activation(result);`;\n }\n\n const addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';\n if (addBias) {\n this.variableNames.push('bias');\n }\n\n if (hasPreluActivation) {\n this.variableNames.push('preluActivationWeights');\n }\n\n if (hasLeakyreluActivation) {\n this.variableNames.push('leakyreluAlpha');\n }\n\n let batchASnippet = 'rc.x';\n let batchBSnippet = 'rc.x';\n if (aShape[0] < bShape[0]) {\n batchASnippet = `int(min(float(rc.x), ${aShape[0] - 1}.))`;\n } else if (bShape[0] < aShape[0]) {\n batchBSnippet = `int(min(float(rc.x), ${bShape[0] - 1}.))`;\n }\n\n this.userCode = `\n ${activationSnippet}\n\n const float sharedDimension = ${sharedDimensionPacked}.0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < ${sharedDimensionPacked}; i++) {\n int batchA = ${batchASnippet};\n int batchB = ${batchBSnippet};\n vec4 a = getMatrixA(batchA, ${aSample});\n vec4 b = getMatrixB(batchB, ${bSample});\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += (${aSwizzle[0]} * ${bSwizzle[0]});\n result += (${aSwizzle[1]} * ${bSwizzle[1]});\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n ${addBiasSnippet}\n\n ${applyActivationSnippet}\n\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\n// (Ar + Ai)(Br + Bi) =\n// ArBr + ArBi + AiBr + AiBi = ArBr - AB + ArBi + AiBr\n// Yr = ArBr - AB\n// Yi = ArBi + AiBr\nexport const COMPLEX_MULTIPLY = {\n REAL: 'return areal * breal - aimag * bimag;',\n IMAG: 'return areal * bimag + aimag * breal;'\n};\n\nexport class BinaryOpComplexProgram implements GPGPUProgram {\n variableNames = ['AReal', 'AImag', 'BReal', 'BImag'];\n userCode: string;\n outputShape: number[];\n\n constructor(op: string, aShape: number[], bShape: number[]) {\n this.outputShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n\n this.userCode = `\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n ${op}\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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BinaryInputs, env, KernelConfig, Multiply, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport * as binaryop_complex_gpu from '../binaryop_complex_gpu';\nimport {BinaryOpComplexProgram} from '../binaryop_complex_gpu';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\nimport {multiplyImplCPU as cpuMultiply} from '../kernel_utils/shared';\n\nimport {complex} from './Complex';\n\nconst MUL = 'return a * b;';\n\nexport function multiply(\n args: {inputs: BinaryInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {a, b} = inputs;\n const dtype = backend_util.upcastType(a.dtype, b.dtype);\n\n if (a.dtype === 'complex64') {\n const aData = backend.texData.get(a.dataId);\n const bData = backend.texData.get(b.dataId);\n\n const realProgram = new BinaryOpComplexProgram(\n binaryop_complex_gpu.COMPLEX_MULTIPLY.REAL, a.shape, b.shape);\n const imagProgram = new BinaryOpComplexProgram(\n binaryop_complex_gpu.COMPLEX_MULTIPLY.IMAG, a.shape, b.shape);\n\n const inputs = [\n {\n dataId: aData.complexTensorInfos.real.dataId,\n dtype: aData.complexTensorInfos.real.dtype,\n shape: a.shape\n },\n {\n dataId: aData.complexTensorInfos.imag.dataId,\n dtype: aData.complexTensorInfos.imag.dtype,\n shape: a.shape\n },\n {\n dataId: bData.complexTensorInfos.real.dataId,\n dtype: bData.complexTensorInfos.real.dtype,\n shape: b.shape\n },\n {\n dataId: bData.complexTensorInfos.imag.dataId,\n dtype: bData.complexTensorInfos.imag.dtype,\n shape: b.shape\n }\n ];\n\n const realPart = backend.runWebGLProgram(realProgram, inputs, 'float32');\n const imagPart = backend.runWebGLProgram(imagProgram, inputs, 'float32');\n\n const complexOutput =\n complex({inputs: {real: realPart, imag: imagPart}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(imagPart);\n\n // TODO(annxingyuan): CPU forwarding for complex inputs.\n return complexOutput;\n }\n\n if (backend.shouldExecuteOnCPU([a, b])) {\n const aData = backend.texData.get(a.dataId);\n const bData = backend.texData.get(b.dataId);\n const [outValues, outShape] = cpuMultiply(\n a.shape, b.shape, aData.values as TypedArray,\n bData.values as TypedArray, dtype);\n\n const out = backend.makeTensorInfo(outShape, dtype);\n const outData = backend.texData.get(out.dataId);\n outData.values = outValues;\n return out;\n }\n\n let program: BinaryOpProgram|BinaryOpPackedProgram;\n if (env().getBool('WEBGL_PACK_BINARY_OPERATIONS')) {\n program = new BinaryOpPackedProgram(MUL, a.shape, b.shape);\n } else {\n program = new BinaryOpProgram(MUL, a.shape, b.shape);\n }\n\n return backend.runWebGLProgram(program, [a, b], dtype);\n}\n\nexport const multiplyConfig: KernelConfig = {\n kernelName: Multiply,\n backendName: 'webgl',\n kernelFunc: multiply\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ReshapePackedProgram} from '../reshape_packed_gpu';\nimport {getBatchDim, getRowsCols} from '../webgl_util';\n\nexport function packedReshape(\n input: TensorInfo, afterShape: number[],\n backend: MathBackendWebGL): TensorInfo {\n const input3DShape =\n [getBatchDim(input.shape),\n ...getRowsCols(input.shape)] as [number, number, number];\n const input3D: TensorInfo = {\n dtype: input.dtype,\n shape: input3DShape,\n dataId: input.dataId\n };\n const afterShapeAs3D =\n [getBatchDim(afterShape),\n ...getRowsCols(afterShape)] as [number, number, number];\n\n const program = new ReshapePackedProgram(afterShapeAs3D, input3DShape);\n const preventEagerUnpackingOfOutput = true;\n const output = backend.runWebGLProgram(\n program, [input3D], input.dtype, null /* customSetup */,\n preventEagerUnpackingOfOutput);\n return {dataId: output.dataId, shape: afterShape, dtype: output.dtype};\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Reshape, ReshapeAttrs, ReshapeInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {packedReshape} from '../kernel_utils/reshape';\nimport {isReshapeFree} from '../webgl_util';\n\nexport function reshape(args: {\n inputs: ReshapeInputs,\n backend: MathBackendWebGL,\n attrs: ReshapeAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {shape} = attrs;\n const webglBackend = backend;\n\n const xSize = util.sizeFromShape(x.shape);\n const $shape = util.inferFromImplicitShape(shape, xSize);\n const $xSize = util.sizeFromShape($shape);\n\n util.assert(\n xSize === $xSize,\n () => `The new shape (${$shape}) has ${$xSize} elements and the old ` +\n `shape (${x.shape}) has ${xSize} elements. The new shape and old ` +\n `shape must have the same number of elements.`);\n\n const xTexData = webglBackend.texData.get(x.dataId);\n if (xTexData.isPacked && !isReshapeFree(x.shape, $shape) &&\n !(xTexData.texture !== null && isReshapeFree(xTexData.shape, $shape))) {\n return packedReshape(x, $shape, webglBackend);\n }\n\n webglBackend.incRef(x.dataId);\n\n return {dataId: x.dataId, shape: $shape, dtype: x.dtype};\n}\n\nexport const reshapeConfig: KernelConfig = {\n kernelName: Reshape,\n backendName: 'webgl',\n kernelFunc: reshape as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class MeanProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(reduceInfo: backend_util.ReduceInfo, divisor?: number) {\n const {windowSize, batchSize, inSize, outSize} = reduceInfo;\n this.outputShape = [batchSize, outSize];\n\n const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;\n const windowSizeVec4Remainder = windowSize % 4;\n\n let updateSnippet = `sumValue += dot(values, ones);`;\n if (divisor != null) {\n const denominator = 1 / divisor;\n updateSnippet = `sumValue += dot(values * ${\n util.isInt(denominator) ? denominator.toPrecision(2) :\n denominator}, ones);`;\n }\n\n let checkOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return 0.0;\n }\n `;\n }\n\n this.userCode = `\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${checkOutOfBounds}\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 * ${windowSize};\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${windowSizeNearestVec4}; 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 ${updateSnippet}\n }\n\n int inIdx = inOffset + ${windowSizeNearestVec4};\n if (${windowSizeVec4Remainder === 1}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 2}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 3}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${updateSnippet}\n }\n setOutput(sumValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ReduceProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n reduceInfo: backend_util.ReduceInfo,\n reduceType: 'all'|'any'|'max'|'min'|'sum'|'prod') {\n const {windowSize, batchSize, inSize, outSize} = reduceInfo;\n this.outputShape = [batchSize, outSize];\n\n let initializationValue = '0.0';\n let compareOp = ``;\n\n if (reduceType === 'prod') {\n initializationValue = '1.0';\n } else if (reduceType === 'min') {\n // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.\n initializationValue = '1.0 / 1e-20';\n compareOp = `min`;\n } else if (reduceType === 'max') {\n // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.\n initializationValue = '-1.0 / 1e-20';\n compareOp = `max`;\n }\n\n let returnValue = `${reduceType}(${reduceType}(${reduceType}(` +\n 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';\n\n if (reduceType === 'sum') {\n returnValue = `sumValue`;\n } else if (reduceType === 'prod') {\n returnValue = `prodValue`;\n } else if (reduceType === 'all') {\n returnValue = `allValue`;\n } else if (reduceType === 'any') {\n returnValue = `anyValue`;\n }\n\n const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;\n const windowSizeVec4Remainder = windowSize % 4;\n\n let updateSnippet = `\n if (${reduceType === 'sum'}) {\n sumValue += dot(values, ones);\n } else if (${reduceType === 'prod'}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${compareOp}(values, minMaxValue);\n if (${reduceType === 'min'} || ${reduceType === 'max'}) {\n minMaxValue = ${compareOp}(values, minMaxValue);\n bvec4 isNaN = isnan(values);\n if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n minMaxValue = vec4(NAN);\n }\n }\n }\n `;\n\n let vecType = `vec4`;\n\n if (reduceType === 'all') {\n initializationValue = '1.0';\n updateSnippet = `\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n `;\n vecType = `bvec4`;\n } else if (reduceType === 'any') {\n initializationValue = '0.0';\n updateSnippet = `\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n `;\n vecType = `bvec4`;\n }\n\n let checkOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return initializationValue;\n }\n `;\n }\n this.userCode = `\n const float initializationValue = ${initializationValue};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${checkOutOfBounds}\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 * ${windowSize};\n\n vec4 minMaxValue = vec4(${initializationValue});\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 < ${windowSizeNearestVec4}; i += 4) {\n int inIdx = inOffset + i;\n ${vecType} values = ${vecType}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${updateSnippet}\n }\n\n int inIdx = inOffset + ${windowSizeNearestVec4};\n if (${windowSizeVec4Remainder === 1}) {\n ${vecType} values = ${vecType}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 2}) {\n ${vecType} values = ${vecType}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 3}) {\n ${vecType} values = ${vecType}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${updateSnippet}\n }\n setOutput(${returnValue});\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataType, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MeanProgram} from '../mean_gpu';\nimport {ReduceProgram} from '../reduce_gpu';\n\ntype ReduceTypes = 'all'|'any'|'max'|'min'|'sum'|'prod'|'mean';\n\n// Returns an array of configuration objects that describe each stage of the\n// reduction.\nfunction getReductionStages(inShape: number[]):\n Array<{inSize: number, windowSize: number, outSize: number}> {\n const stages = [];\n\n while (stages.length === 0 || stages[stages.length - 1].outSize !== 1) {\n const outSize: number =\n stages.length ? stages[stages.length - 1].outSize : inShape[1];\n const windowSize = backend_util.computeOptimalWindowSize(outSize);\n stages.push({\n inSize: outSize,\n windowSize,\n outSize: Math.ceil(outSize / windowSize)\n });\n }\n\n return stages;\n}\n\nexport function reduce(\n x: TensorInfo, dtype: DataType, reductionType: ReduceTypes,\n backend: MathBackendWebGL): TensorInfo {\n const reductionStages = getReductionStages(x.shape);\n\n let result = x;\n for (let i = 0; i < reductionStages.length; i++) {\n const {inSize, windowSize, outSize} = reductionStages[i];\n\n let program: ReduceProgram|MeanProgram;\n let previousResult: TensorInfo;\n if (reductionType === 'mean') {\n program = i === 0 ?\n new MeanProgram(\n {windowSize, inSize, batchSize: x.shape[0], outSize}, inSize) :\n new MeanProgram({windowSize, inSize, batchSize: x.shape[0], outSize});\n } else {\n program = new ReduceProgram(\n {windowSize, inSize, batchSize: x.shape[0], outSize}, reductionType);\n }\n\n previousResult = result;\n result = backend.runWebGLProgram(program, [result], dtype);\n\n if (previousResult.dataId !== x.dataId) {\n backend.disposeIntermediateTensorInfo(previousResult);\n }\n }\n\n return result;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class TransposeProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n rank: number;\n\n constructor(aShape: number[], newDim: number[]) {\n const outputShape: number[] = new Array(aShape.length);\n for (let i = 0; i < outputShape.length; i++) {\n outputShape[i] = aShape[newDim[i]];\n }\n this.outputShape = outputShape;\n this.rank = outputShape.length;\n const dtype = getCoordsDataType(this.rank);\n const switched = getSwitchedCoords(newDim);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n setOutput(getA(${switched}));\n }\n `;\n }\n}\n\nfunction getSwitchedCoords(newDim: number[]): string {\n const rank = newDim.length;\n if (rank > 6) {\n throw Error(`Transpose for rank ${rank} is not yet supported`);\n }\n const originalOrder =\n ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u', 'resRC.v'];\n const switchedCoords = new Array(rank);\n for (let i = 0; i < newDim.length; i++) {\n switchedCoords[newDim[i]] = originalOrder[i];\n }\n return switchedCoords.join();\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getVecChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class TransposePackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n rank: number;\n packedInputs = true;\n packedOutput = true;\n\n constructor(aShape: number[], newDim: number[]) {\n const outputShape: number[] = new Array(aShape.length);\n for (let i = 0; i < outputShape.length; i++) {\n outputShape[i] = aShape[newDim[i]];\n }\n this.outputShape = outputShape;\n this.rank = outputShape.length;\n if (this.rank > 6) {\n throw Error(\n `Packed transpose for rank ${this.rank} is not yet supported.`);\n }\n const dtype = getCoordsDataType(this.rank);\n\n const outputOrder = getVecChannels('rc', this.rank);\n const switchedOrder = new Array(this.rank);\n for (let i = 0; i < newDim.length; i++) {\n switchedOrder[newDim[i]] = outputOrder[i];\n }\n const innerDims = `vec2(${switchedOrder.slice(-2).join()})`;\n const nextColumn =\n `++${outputOrder[this.rank - 1]} < ${outputShape[this.rank - 1]}`;\n const getc = `getChannel(getA(${switchedOrder.join()}), ${innerDims})`;\n\n this.userCode = `\n void main() {\n ${dtype} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = ${getc};\n if(${nextColumn}) {\n result[1] = ${getc};\n }\n --${outputOrder[this.rank - 1]};\n if(++${outputOrder[this.rank - 2]} < ${outputShape[this.rank - 2]}) {\n result[2] = ${getc};\n if(${nextColumn}) {\n result[3] = ${getc};\n }\n }\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {transposeImplCPU} from '../kernel_utils/shared';\nimport {TransposeProgram} from '../transpose_gpu';\nimport {TransposePackedProgram} from '../transpose_packed_gpu';\n\nexport function transposeImpl(\n x: TensorInfo, perm: number[], backend: MathBackendWebGL): TensorInfo {\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new TransposePackedProgram(x.shape, perm) :\n new TransposeProgram(x.shape, perm);\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport {transposeImplCPU};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, sumOutType, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from './Reshape';\n\nimport {transposeImpl} from './Transpose_impl';\n\nexport function sumImpl(\n x: TensorInfo, axis: number|number[], keepDims: boolean,\n backend: MathBackendWebGL): TensorInfo {\n const reductionIndices = axis;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(reductionIndices, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n const sumInputIsTransposed = permutedAxes != null;\n\n let sumInput = x;\n if (sumInputIsTransposed) {\n sumInput = transposeImpl(x, permutedAxes, backend);\n\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('sum', axes, xRank);\n const [sumOutShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(sumInput.shape, axes);\n\n let outShape = sumOutShape;\n if (keepDims) {\n // rather than reshape at the end, set the target shape here.\n outShape = backend_util.expandShapeToKeepDim(sumOutShape, origAxes);\n }\n\n const inSize = util.sizeFromShape(reduceShape);\n const xSize = util.sizeFromShape(x.shape);\n const batchSize = xSize / inSize;\n const reshapedInput = reshape(\n {inputs: {x: sumInput}, attrs: {shape: [batchSize, inSize]}, backend});\n\n const outType = sumOutType(x.dtype);\n\n const reduced = reduce(reshapedInput, outType, 'sum', backend);\n const out =\n reshape({inputs: {x: reduced}, attrs: {shape: outShape}, backend});\n\n backend.disposeIntermediateTensorInfo(reshapedInput);\n backend.disposeIntermediateTensorInfo(reduced);\n if (sumInputIsTransposed) {\n backend.disposeIntermediateTensorInfo(sumInput);\n }\n\n return out;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Sum, SumAttrs, SumInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {sumImpl} from './Sum_impl';\n\nexport function sum(\n args: {inputs: SumInputs, attrs: SumAttrs, backend: MathBackendWebGL}) {\n const {inputs, backend, attrs} = args;\n\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n return sumImpl(x, axis, keepDims, backend);\n}\n\nexport const sumConfig: KernelConfig = {\n kernelName: Sum,\n backendName: 'webgl',\n kernelFunc: sum as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Transpose, TransposeAttrs, TransposeInputs, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {transposeImpl} from './Transpose_impl';\nimport {transposeImplCPU as cpuTranspose} from './Transpose_impl';\n\nexport function transpose(args: {\n inputs: TransposeInputs,\n attrs: TransposeAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {perm} = attrs;\n const webglBackend = backend;\n\n const xRank = x.shape.length;\n\n const newShape: number[] = new Array(xRank);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = x.shape[perm[i]];\n }\n\n let out: TensorInfo;\n if (webglBackend.shouldExecuteOnCPU([x])) {\n const xTexData = webglBackend.texData.get(x.dataId);\n const values = xTexData.values as TypedArray;\n const outValues = cpuTranspose(values, x.shape, x.dtype, perm, newShape);\n\n out = webglBackend.makeTensorInfo(newShape, x.dtype);\n const outData = webglBackend.texData.get(out.dataId);\n outData.values = outValues;\n } else {\n out = transposeImpl(x, perm, webglBackend);\n }\n return out;\n}\n\nexport const transposeConfig: KernelConfig = {\n kernelName: Transpose,\n backendName: 'webgl',\n kernelFunc: transpose as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, TensorInfo, upcastType, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {mapActivationToShaderProgram} from '../kernel_utils/kernel_funcs_utils';\nimport {MatMulPackedProgram} from '../mulmat_packed_gpu';\n\nimport {multiply} from './Multiply';\nimport {reshape} from './Reshape';\nimport {sum} from './Sum';\nimport {transpose} from './Transpose';\n\n// Empirically determined minimal shared dimension in matmul before we forward\n// to a.mul(b).sum() in order to take advantage of GPU parallelism. See\n// https://github.com/tensorflow/tfjs-core/pull/1379 for benchmarks.\nexport const MATMUL_SHARED_DIM_THRESHOLD = 1000;\n\ntype BatchMatMulConfig = {\n a: TensorInfo,\n b: TensorInfo,\n transposeA: boolean,\n transposeB: boolean,\n backend: MathBackendWebGL,\n bias?: TensorInfo,\n preluActivationWeights?: TensorInfo,\n leakyreluAlpha?: number,\n activation?: backend_util.Activation\n};\n\nexport function batchMatMulImpl({\n a,\n b,\n transposeA,\n transposeB,\n backend,\n bias = null,\n preluActivationWeights = null,\n leakyreluAlpha = 0,\n activation = null\n}: BatchMatMulConfig): TensorInfo {\n const aRank = a.shape.length;\n const bRank = b.shape.length;\n\n const innerShapeA = transposeA ? a.shape[aRank - 2] : a.shape[aRank - 1];\n const innerShapeB = transposeB ? b.shape[bRank - 1] : b.shape[bRank - 2];\n\n const outerShapeA = transposeA ? a.shape[aRank - 1] : a.shape[aRank - 2];\n const outerShapeB = transposeB ? b.shape[bRank - 2] : b.shape[bRank - 1];\n\n const outerDimsA = a.shape.slice(0, -2);\n const outerDimsB = b.shape.slice(0, -2);\n\n const batchDimA = util.sizeFromShape(outerDimsA);\n const batchDimB = util.sizeFromShape(outerDimsB);\n\n const batchDimsCompatible =\n batchDimA === batchDimB || batchDimA === 1 || batchDimB === 1;\n\n util.assert(\n aRank >= 2 && bRank >= 2 && batchDimsCompatible,\n () => `Error in matMul: the input batch dimensions must either be the ` +\n `same or at least one input batch dimension must be 1. Got input ` +\n `batch dimensions of (${outerDimsA}) and (${outerDimsB}).`);\n\n const outShapeOuterDims =\n batchDimA > batchDimB ? a.shape.slice(0, -2) : b.shape.slice(0, -2);\n const outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);\n\n util.assert(\n innerShapeA === innerShapeB,\n () => `Error in matMul: inner shapes (${innerShapeA}) and (` +\n `${innerShapeB}) of Tensors with shapes ${a.shape} and ` +\n `${b.shape} and transposeA=${transposeA}` +\n ` and transposeB=${transposeB} must match.`);\n\n const a3dShape: [number, number, number] = transposeA ?\n [batchDimA, innerShapeA, outerShapeA] :\n [batchDimA, outerShapeA, innerShapeA];\n const b3dShape: [number, number, number] = transposeB ?\n [batchDimB, outerShapeB, innerShapeB] :\n [batchDimB, innerShapeB, outerShapeB];\n\n // The rest of the implementation is designed to operate on rank-3 tensors\n const a3d = reshape({inputs: {x: a}, backend, attrs: {shape: a3dShape}});\n const b3d = reshape({inputs: {x: b}, backend, attrs: {shape: b3dShape}});\n\n const intermediates: TensorInfo[] = [a3d, b3d];\n\n const batchDim = Math.max(batchDimA, batchDimB);\n const sharedDim = transposeA ? a3d.shape[1] : a3d.shape[2];\n\n const hasBias = bias != null;\n const hasPreluActivationWeights = preluActivationWeights != null;\n const hasLeakyreluAlpha = activation === 'leakyrelu';\n const fusedActivation = activation != null ?\n mapActivationToShaderProgram(activation, true) :\n null;\n const containsFusedOps = hasBias || hasPreluActivationWeights ||\n hasLeakyreluAlpha || fusedActivation != null;\n let out: TensorInfo;\n\n // Since the matrices are vectors, it is faster to call mul().sum()\n // because sum() is O(sqrt(N)) due to divide-and-conquer.\n if ((outerShapeA === 1 || outerShapeB === 1) &&\n sharedDim > MATMUL_SHARED_DIM_THRESHOLD && containsFusedOps === false) {\n let aVec = a3d;\n let bVec = b3d;\n if (transposeA) {\n aVec = transpose({inputs: {x: a3d}, backend, attrs: {perm: [0, 2, 1]}});\n intermediates.push(aVec);\n }\n if (transposeB) {\n bVec = transpose({inputs: {x: b3d}, backend, attrs: {perm: [0, 2, 1]}});\n intermediates.push(bVec);\n }\n\n const shouldReshapeA = outerShapeB !== 1;\n const shouldReshapeB = outerShapeB === 1;\n\n let aVec3d = aVec;\n if (shouldReshapeA) {\n aVec3d = reshape({\n inputs: {x: aVec},\n backend,\n attrs: {shape: [batchDim, sharedDim, 1]}\n });\n\n intermediates.push(aVec3d);\n }\n\n const axis = outerShapeB === 1 ? 2 : 1;\n\n let bVec3d = bVec;\n if (shouldReshapeB) {\n bVec3d = reshape({\n inputs: {x: bVec},\n backend,\n attrs: {shape: [batchDim, 1, sharedDim]}\n });\n\n intermediates.push(bVec3d);\n }\n\n const product = multiply({inputs: {a: aVec3d, b: bVec3d}, backend});\n out = sum({inputs: {x: product}, backend, attrs: {axis, keepDims: true}});\n intermediates.push(product);\n } else {\n const dtype = upcastType(a.dtype, b.dtype);\n\n const program = new MatMulPackedProgram(\n a3dShape, b3dShape, [batchDim, outerShapeA, outerShapeB], transposeA,\n transposeB, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n\n const inputs: TensorInfo[] = [a3d, b3d];\n if (bias != null) {\n inputs.push(bias);\n }\n if (hasPreluActivationWeights) {\n inputs.push(preluActivationWeights);\n }\n if (hasLeakyreluAlpha) {\n const $leakyreluAlpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(leakyreluAlpha as {} as 'float32', 'float32'));\n inputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n\n out = backend.runWebGLProgram(program, inputs, dtype);\n }\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: outShape}});\n intermediates.push(out);\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n return outReshaped;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {batchMatMulImpl} from './BatchMatMul_impl';\n\nexport function _fusedMatMul(args: {\n inputs: _FusedMatMulInputs,\n attrs: _FusedMatMulAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b, bias, preluActivationWeights} = inputs;\n const {transposeA, transposeB, activation, leakyreluAlpha} = attrs;\n\n return batchMatMulImpl({\n a,\n b,\n transposeA,\n transposeB,\n backend,\n bias,\n preluActivationWeights,\n leakyreluAlpha,\n activation\n });\n}\n\nexport const _fusedMatMulConfig: KernelConfig = {\n kernelName: _FusedMatMul,\n backendName: 'webgl',\n kernelFunc: _fusedMatMul as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Abs, AbsInputs, env, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {simpleAbsImplCPU} from '../kernel_utils/shared';\nimport {UnaryOpProgram} from '../unaryop_gpu';\nimport {UnaryOpPackedProgram} from '../unaryop_packed_gpu';\n\nconst ABS = `return abs(x);`;\n\nexport function abs(args: {inputs: AbsInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n // TODO: handle cases when x is complex. Once the cpu implementation\n // can handle complex values, refactor to use unaryKernelFunc.\n if (backend.shouldExecuteOnCPU([x]) && x.dtype !== 'complex64') {\n const xData = backend.texData.get(x.dataId);\n const outValues = simpleAbsImplCPU(xData.values as TypedArray);\n return backend.makeTensorInfo(x.shape, x.dtype, outValues);\n }\n\n let program: UnaryOpProgram|UnaryOpPackedProgram;\n if (env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {\n program = new UnaryOpPackedProgram(x.shape, ABS);\n } else {\n program = new UnaryOpProgram(x.shape, ABS);\n }\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const absConfig: KernelConfig = {\n kernelName: Abs,\n backendName: 'webgl',\n kernelFunc: abs as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Acos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ACOS = CHECK_NAN_SNIPPET + `\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n`;\n\nexport const acos = unaryKernelFunc({opSnippet: ACOS});\n\nexport const acosConfig: KernelConfig = {\n kernelName: Acos,\n backendName: 'webgl',\n kernelFunc: acos,\n};\n","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Acosh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ACOSH = CHECK_NAN_SNIPPET + `\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));`;\n\nexport const acosh = unaryKernelFunc({opSnippet: ACOSH});\n\nexport const acoshConfig: KernelConfig = {\n kernelName: Acosh,\n backendName: 'webgl',\n kernelFunc: acosh,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Add, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {addImplCPU as cpuAdd} from '../kernel_utils/shared';\n\nconst ADD = 'return a + b;';\n\nexport const addKernelFunc = binaryKernelFunc({\n opSnippet: ADD,\n packedOpSnippet: ADD,\n supportsComplex: true,\n cpuKernelImpl: cpuAdd\n});\n\nexport const addConfig: KernelConfig = {\n kernelName: Add,\n backendName: 'webgl',\n kernelFunc: addKernelFunc\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class AddNProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(outputShape: number[], shapes: number[][]) {\n this.outputShape = outputShape;\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const snippets: string[] = [];\n // Get target elements from every input tensor.\n this.variableNames.forEach(variable => {\n snippets.push(`float v${variable} = get${variable}AtOutCoords();`);\n });\n\n // Calculate the sum of all elements.\n const operation = this.variableNames\n .map(variable => {\n return `v${variable}`;\n })\n .join(' + ');\n\n this.userCode = `\n void main() {\n ${snippets.join('\\n ')}\n\n float result = ${operation};\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class AddNPackedProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(outputShape: number[], shapes: number[][]) {\n this.outputShape = outputShape;\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const snippets: string[] = [];\n // Get target elements from every input tensor.\n this.variableNames.forEach(variable => {\n snippets.push(`vec4 v${variable} = get${variable}AtOutCoords();`);\n });\n\n // Calculate the sum of all elements.\n const operation = this.variableNames\n .map(variable => {\n return `v${variable}`;\n })\n .join(' + ');\n\n this.userCode = `\n void main() {\n ${snippets.join('\\n ')}\n\n vec4 result = ${operation};\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AddN, AddNInputs, env, KernelConfig, KernelFunc, TensorInfo, upcastType} from '@tensorflow/tfjs-core';\n\nimport {AddNProgram} from '../addn_gpu';\nimport {AddNPackedProgram} from '../addn_packed_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\nexport function addN(args: {inputs: AddNInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n\n const tensors = inputs;\n if (tensors.length === 1) {\n return identity({inputs: {x: tensors[0]}, backend});\n }\n\n // Limit the number of uploaded textures for optimization.\n if (tensors.length > env().get('WEBGL_MAX_TEXTURES_IN_SHADER')) {\n const midIndex = Math.floor(tensors.length / 2);\n const leftSide = addN({inputs: tensors.slice(0, midIndex), backend});\n const rightSide = addN({inputs: tensors.slice(midIndex), backend});\n return addN({inputs: [leftSide, rightSide], backend});\n }\n\n const dtype =\n tensors.map(t => t.dtype).reduce((d1, d2) => upcastType(d1, d2));\n const shapes = tensors.map(t => t.shape);\n // We can make sure shapes are identical in op level.\n const usePackedOp = env().getBool('WEBGL_PACK');\n const program = usePackedOp ?\n new AddNPackedProgram(tensors[0].shape, shapes) :\n new AddNProgram(tensors[0].shape, shapes);\n return backend.runWebGLProgram(program, tensors, dtype);\n}\n\nexport const addNConfig: KernelConfig = {\n kernelName: AddN,\n backendName: 'webgl',\n kernelFunc: addN as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {All, AllAttrs, AllInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\n\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function all(\n args: {inputs: AllInputs, backend: MathBackendWebGL, attrs: AllAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let permutedX = x;\n if (permutedAxes != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('all', axes, xRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(permutedX.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n\n const a2D =\n reshape({inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n const reduced = reduce(a2D, a2D.dtype, 'all', backend);\n\n let res;\n if (keepDims) {\n const newShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: newShape}});\n } else {\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n }\n\n backend.disposeIntermediateTensorInfo(a2D);\n backend.disposeIntermediateTensorInfo(reduced);\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo(permutedX);\n }\n\n return res;\n}\n\nexport const allConfig: KernelConfig = {\n kernelName: All,\n backendName: 'webgl',\n kernelFunc: all as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Any, AnyAttrs, AnyInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function any(\n args: {inputs: AnyInputs, backend: MathBackendWebGL, attrs: AnyAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let permutedX = x;\n if (permutedAxes != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('any', axes, xRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(permutedX.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n\n const a2D =\n reshape({inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n const reduced = reduce(a2D, a2D.dtype, 'any', backend);\n\n let res;\n if (keepDims) {\n const newShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: newShape}});\n } else {\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n }\n\n backend.disposeIntermediateTensorInfo(a2D);\n backend.disposeIntermediateTensorInfo(reduced);\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo(permutedX);\n }\n\n return res;\n}\n\nexport const anyConfig: KernelConfig = {\n kernelName: Any,\n backendName: 'webgl',\n kernelFunc: any as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ArgMinMaxProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n reduceInfo: backend_util.ReduceInfo, op: 'max'|'min',\n firstPass: boolean) {\n const {windowSize, batchSize, outSize} = reduceInfo;\n if (!firstPass) {\n this.variableNames.push('bestIndicesA');\n }\n this.outputShape = [batchSize, outSize];\n const compOp = (op === 'max') ? '>' : '<';\n const indexSnippet = firstPass ?\n 'inOffset + i;' :\n 'round(getBestIndicesA(batch, inOffset + i));';\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${windowSize};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${windowSize}; i++) {\n int inIdx = ${indexSnippet};\n float candidate = getA(batch, inIdx);\n if (candidate ${compOp} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ArgMinMaxPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n shape: number[], windowSize: number, op: 'max'|'min',\n firstPass: boolean) {\n util.assert(\n shape.length > 2,\n () => `Packed arg${\n op.charAt(0).toUpperCase() +\n op.slice(1)} supports only inputs with rank above 2.`);\n const inSize = shape[shape.length - 1];\n const outSize = Math.ceil(inSize / windowSize);\n this.outputShape = shape.slice(0, -1);\n if (outSize > 1) {\n this.outputShape.push(outSize);\n }\n if (!firstPass) {\n this.variableNames.push('bestIndicesA');\n }\n const outShape = this.outputShape;\n const rank = outShape.length;\n const dtype = getCoordsDataType(rank);\n const coords = getChannels('coords', rank);\n\n let sourceLocSetup;\n let sourceRank;\n if (outSize === 1) {\n sourceRank = rank + 1;\n const sourceLocDType = getCoordsDataType(sourceRank);\n sourceLocSetup = `\n ${sourceLocDType} sourceLocR = ${sourceLocDType}(${coords.join()}, 0);\n ++${coords[rank - 1]};\n ${sourceLocDType} sourceLocG = ${sourceLocDType}(${coords.join()}, 0);\n ++${coords[rank - 2]};\n ${sourceLocDType} sourceLocA = ${sourceLocDType}(${coords.join()}, 0);\n --${coords[rank - 1]};\n ${sourceLocDType} sourceLocB = ${sourceLocDType}(${coords.join()}, 0);\n --${coords[rank - 2]};`;\n } else {\n sourceRank = rank;\n sourceLocSetup = `\n ${dtype} sourceLocR = coords;\n ++${coords[rank - 1]};\n ${dtype} sourceLocG = coords;\n ++${coords[rank - 2]};\n ${dtype} sourceLocA = coords;\n --${coords[rank - 1]};\n ${dtype} sourceLocB = coords;\n --${coords[rank - 2]};`;\n }\n const channels = ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, sourceRank);\n const inChannel = '.' + channels[sourceRank - 1]; // e.g. \".b\" for rank 3.\n const intChannels = channels.map(x => 'int ' + x);\n const srcRCoords =\n getChannels('sourceLocR', sourceRank - 1).concat('inIdx.r');\n const srcGCoords =\n getChannels('sourceLocG', sourceRank - 1).concat('inIdx.g');\n const srcBCoords =\n getChannels('sourceLocB', sourceRank - 1).concat('inIdx.b');\n const srcACoords =\n getChannels('sourceLocA', sourceRank - 1).concat('inIdx.a');\n\n const compOp = (op === 'max') ? 'greaterThan' : 'lessThan';\n const fetchCandidateIdx = firstPass ? '' : `\n inIdx = round(vec4(getBestIndicesAChannel(${srcRCoords.join()}),\n getBestIndicesAChannel(${srcGCoords.join()}),\n getBestIndicesAChannel(${srcBCoords.join()}),\n getBestIndicesAChannel(${srcACoords.join()})));`;\n\n const fetchValue = `vec4(\n getAChannel(${srcRCoords.join()}),\n hasNextCol ? getAChannel(${srcGCoords.join()}) : 0.,\n hasNextRow ? getAChannel(${srcBCoords.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${srcACoords.join()}) : 0.)`;\n\n const getBestIndicesAChannelSnippet = firstPass ? '' : `\n float getBestIndicesAChannel(${intChannels.join()}) {\n return getChannel(getBestIndicesA(${channels.join()}),\n vec2(${channels.slice(-2).join()}));\n }`;\n\n this.userCode = `\n float getAChannel(${intChannels.join()}) {\n return getChannel(getA(${channels.join()}),\n vec2(${channels.slice(-2).join()}));\n }\n ${getBestIndicesAChannelSnippet}\n void main() {\n ${dtype} coords = getOutputCoords();\n bool hasNextCol = ${coords[rank - 1]} < ${outShape[rank - 1] - 1};\n bool hasNextRow = ${coords[rank - 2]} < ${outShape[rank - 2] - 1};\n ${sourceLocSetup}\n ivec4 srcIdx = ivec4(sourceLocR${inChannel}, sourceLocG${inChannel},\n sourceLocB${inChannel}, sourceLocA${inChannel}) * ${windowSize};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${fetchValue};\n\n for (int i = 0; i < ${windowSize}; i++) {\n inIdx = srcIdx;\n ${fetchCandidateIdx}\n vec4 candidate = ${fetchValue};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${compOp}(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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {ArgMinMaxProgram} from '../argminmax_gpu';\nimport {ArgMinMaxPackedProgram} from '../argminmax_packed_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reshape} from '../kernels/Reshape';\n\nfunction argReduce(\n backend: MathBackendWebGL, x: TensorInfo, reduceType: 'max'|'min',\n bestIndicesA: TensorInfo = null): TensorInfo {\n let batchSize = x.shape[0];\n let inSize = x.shape[1];\n if (bestIndicesA != null) {\n batchSize = bestIndicesA.shape[0];\n inSize = bestIndicesA.shape[1];\n }\n const windowSize = backend_util.computeOptimalWindowSize(inSize);\n const reduceInfo =\n {windowSize, inSize, batchSize, outSize: Math.ceil(inSize / windowSize)};\n const program =\n new ArgMinMaxProgram(reduceInfo, reduceType, bestIndicesA == null);\n const inputs = [x];\n if (bestIndicesA != null) {\n inputs.push(bestIndicesA);\n }\n const output = backend.runWebGLProgram(program, inputs, 'int32');\n // No need to run another GPGPU program.\n if (output.shape[1] === 1) {\n return output;\n }\n const result = argReduce(backend, x, reduceType, output);\n backend.disposeIntermediateTensorInfo(output);\n return result;\n}\n\nfunction argReducePacked(\n backend: MathBackendWebGL, x: TensorInfo, reduceType: 'max'|'min',\n bestIndicesA: TensorInfo = null): TensorInfo {\n const inShape = bestIndicesA != null ? bestIndicesA.shape : x.shape;\n const inSize = inShape[inShape.length - 1];\n const windowSize = backend_util.computeOptimalWindowSize(inSize);\n const program = new ArgMinMaxPackedProgram(\n inShape, windowSize, reduceType, bestIndicesA == null);\n const inputs = bestIndicesA == null ? [x] : [x, bestIndicesA];\n const output = backend.runWebGLProgram(program, inputs, 'int32');\n if (output.shape.length === x.shape.length) {\n const result = argReducePacked(backend, x, reduceType, output);\n backend.disposeIntermediateTensorInfo(output);\n return result;\n }\n return output;\n}\n\nexport function argMinMaxReduce(\n backend: MathBackendWebGL, x: TensorInfo, axis: number,\n reduceType: 'min'|'max'): TensorInfo {\n const axes = [axis];\n backend_util.assertAxesAreInnerMostDims(\n 'arg' + reduceType.charAt(0).toUpperCase() + reduceType.slice(1), axes,\n x.shape.length);\n if (!env().getBool('WEBGL_PACK_REDUCE') || x.shape.length <= 2) {\n const intermediateTensorInfos = [];\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(x.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n const a2D = reshape({inputs: {x}, backend, attrs: {shape: [-1, inSize]}});\n intermediateTensorInfos.push(a2D);\n\n const reduced = argReduce(backend, a2D, reduceType);\n intermediateTensorInfos.push(reduced);\n const reshaped =\n reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n return reshaped;\n }\n return argReducePacked(backend, x, reduceType);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ArgMax, ArgMaxAttrs, ArgMaxInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {argMinMaxReduce} from '../kernel_utils/arg_min_max';\n\nimport {transpose} from './Transpose';\n\nexport function argMax(\n args:\n {inputs: ArgMaxInputs, backend: MathBackendWebGL, attrs: ArgMaxAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis} = attrs;\n\n let axes = util.parseAxisParam(axis, x.shape);\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n const intermediateTensorInfos = [];\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n intermediateTensorInfos.push($x);\n axes = backend_util.getInnerMostAxes(axes.length, $x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('argMax', [axes[0]], $x.shape.length);\n const out = argMinMaxReduce(backend, $x, axes[0], 'max');\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n return out;\n}\n\nexport const argMaxConfig: KernelConfig = {\n kernelName: ArgMax,\n backendName: 'webgl',\n kernelFunc: argMax as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ArgMin, ArgMinAttrs, ArgMinInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {argMinMaxReduce} from '../kernel_utils/arg_min_max';\nimport {transpose} from './Transpose';\n\nexport function argMin(\n args:\n {inputs: ArgMinInputs, backend: MathBackendWebGL, attrs: ArgMinAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis} = attrs;\n\n let axes = util.parseAxisParam(axis, x.shape);\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n const intermediateTensorInfos = [];\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n intermediateTensorInfos.push($x);\n axes = backend_util.getInnerMostAxes(axes.length, $x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('argMin', [axes[0]], $x.shape.length);\n\n const out = argMinMaxReduce(backend, $x, axes[0], 'min');\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n return out;\n}\n\nexport const argMinConfig: KernelConfig = {\n kernelName: ArgMin,\n backendName: 'webgl',\n kernelFunc: argMin as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Asin, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ASIN = CHECK_NAN_SNIPPET + `\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n`;\n\nexport const asin = unaryKernelFunc({opSnippet: ASIN});\n\nexport const asinConfig: KernelConfig = {\n kernelName: Asin,\n backendName: 'webgl',\n kernelFunc: asin,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Asinh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ASINH = CHECK_NAN_SNIPPET + `return log(x + sqrt(x * x + 1.0));`;\n\nexport const asinh = unaryKernelFunc({opSnippet: ASINH});\n\nexport const asinhConfig: KernelConfig = {\n kernelName: Asinh,\n backendName: 'webgl',\n kernelFunc: asinh,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Atan, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ATAN = CHECK_NAN_SNIPPET + `\n return atan(x);\n`;\n\nexport const atan = unaryKernelFunc({opSnippet: ATAN});\n\nexport const atanConfig: KernelConfig = {\n kernelName: Atan,\n backendName: 'webgl',\n kernelFunc: atan,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Atan2} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc, CHECK_NAN_SNIPPET_BINARY, CHECK_NAN_SNIPPET_BINARY_PACKED} from '../kernel_utils/kernel_funcs_utils';\n\nconst ATAN2 = CHECK_NAN_SNIPPET_BINARY + `\n return atan(a, b);\n`;\n\nconst ATAN2_PACKED = `\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n ` +\n CHECK_NAN_SNIPPET_BINARY_PACKED + `\n return result;\n`;\n\nexport const atan2 =\n binaryKernelFunc({opSnippet: ATAN2, packedOpSnippet: ATAN2_PACKED});\n\nexport const atan2Config: KernelConfig = {\n kernelName: Atan2,\n backendName: 'webgl',\n kernelFunc: atan2,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Atanh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ATANH = CHECK_NAN_SNIPPET + `\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;`;\n\nexport const atanh = unaryKernelFunc({opSnippet: ATANH});\n\nexport const atanhConfig: KernelConfig = {\n kernelName: Atanh,\n backendName: 'webgl',\n kernelFunc: atanh,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Pool2DProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, poolType: 'max'|'avg',\n computePositions: boolean, flattenPositions = false,\n includeBatchInIndex = false) {\n if (poolType === 'avg' && computePositions) {\n throw new Error('Cannot compute positions for average pool.');\n }\n\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n this.outputShape = convInfo.outShape;\n\n const isAvgPool = poolType === 'avg';\n const batchFlattenPositionStr = `((batch * ${convInfo.inHeight} + xR) * ${\n convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`;\n const flattenPositionStr =\n `(xR * ${convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`;\n\n let initializationValue = '0.0';\n if (!isAvgPool) {\n // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.\n initializationValue = '-1.0 / 1e-20';\n }\n\n if (computePositions) {\n const compareOp = '>=';\n\n this.userCode = `\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${convInfo.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 ${compareOp} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${\n flattenPositions ? (includeBatchInIndex ? batchFlattenPositionStr :\n flattenPositionStr) :\n `wR * ${effectiveFilterWidth} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `;\n return;\n }\n\n const compareOp = 'max';\n\n let returnValue = `${poolType}(${poolType}(${poolType}(` +\n 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';\n if (poolType === 'avg') {\n returnValue = `avgValue / count`;\n }\n\n const filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;\n const filterWidthVec4Remainder = filterWidth % 4;\n\n const updateSnippet = `\n if (${isAvgPool}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = ${compareOp}(values, minMaxValue);\n }\n `;\n\n this.userCode = `\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n const float initializationValue = ${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 >= ${convInfo.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(${initializationValue});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidthNearestVec4}; wC += 4) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${dilationWidth}, d),\n getValue(batch, xR, xC + 2 * ${dilationWidth}, d),\n getValue(batch, xR, xC + 3 * ${dilationWidth}, d)\n );\n\n ${updateSnippet}\n }\n\n int xC = xCCorner + ${filterWidthNearestVec4};\n if (${filterWidthVec4Remainder === 1}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${filterWidthVec4Remainder === 2}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${dilationWidth}, d),\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${filterWidthVec4Remainder === 3}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${dilationWidth}, d),\n getValue(batch, xR, xC + 2 * ${dilationWidth}, d),\n initializationValue\n );\n\n ${updateSnippet}\n }\n }\n setOutput(${returnValue});\n }\n `;\n }\n}\n\nexport class Pool3DProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv3DInfo, poolType: 'max'|'avg',\n computePositions: boolean, flattenPositions = false,\n includeBatchInIndex = false) {\n if (poolType === 'avg' && computePositions) {\n throw new Error('Cannot compute positions for average pool.');\n }\n\n const filterWidth = convInfo.filterWidth;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n this.outputShape = convInfo.outShape;\n\n const isAvgPool = poolType === 'avg';\n\n let initializationValue = '0.0';\n if (!isAvgPool) {\n // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.\n initializationValue = '-1.0 / 1e-20';\n }\n\n if (computePositions) {\n const compareOp = '>=';\n\n this.userCode = `\n const ivec3 strides =\n ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\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 < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${convInfo.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 ${compareOp} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${\n flattenPositions ?\n (includeBatchInIndex ?\n `(((batch * ${convInfo.inDepth} + xD) * ${\n convInfo.inHeight} + xR) * ${convInfo.inWidth} + xC) * ${\n convInfo.inChannels} + ch` :\n `((xD * ${convInfo.inHeight} + xR) * ${\n convInfo.inWidth} + xC) * ${convInfo.inChannels} + ch`) :\n `wD * ${effectiveFilterHeight} * ${effectiveFilterWidth} +\n wR * ${effectiveFilterWidth} + wC`};\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `;\n return;\n }\n\n const compareOp = 'max';\n\n let returnValue = `${poolType}(${poolType}(${poolType}(` +\n 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';\n if (poolType === 'avg') {\n returnValue = `avgValue / count`;\n }\n\n const filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;\n const filterWidthVec4Remainder = filterWidth % 4;\n\n const updateSnippet = `\n if (${isAvgPool}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = ${compareOp}(values, minMaxValue);\n }\n `;\n\n this.userCode = `\n const ivec3 strides =\n ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n const float initializationValue = ${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 xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= ${convInfo.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(${initializationValue});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidthNearestVec4}; wC += 4) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${dilationWidth}, ch),\n getValue(batch, xD, xR, xC + 2 * ${dilationWidth}, ch),\n getValue(batch, xD, xR, xC + 3 * ${dilationWidth}, ch)\n );\n\n ${updateSnippet}\n }\n\n int xC = xCCorner + ${filterWidthNearestVec4};\n if (${filterWidthVec4Remainder === 1}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${filterWidthVec4Remainder === 2}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${dilationWidth}, ch),\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${filterWidthVec4Remainder === 3}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${dilationWidth}, ch),\n getValue(batch, xD, xR, xC + 2 * ${dilationWidth}, ch),\n initializationValue\n );\n\n ${updateSnippet}\n }\n }\n setOutput(${returnValue});\n }\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {AvgPool, AvgPoolAttrs, AvgPoolInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool2DProgram} from '../pool_gpu';\nimport {assertNotComplex} from '../webgl_util';\nimport {identity} from './Identity';\n\nexport function avgPool(args: {\n inputs: AvgPoolInputs,\n backend: MathBackendWebGL,\n attrs: AvgPoolAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n assertNotComplex(x, 'avgPool');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations = 1;\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in avgPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&\n util.arraysEqual(convInfo.inShape, convInfo.outShape)) {\n return identity({inputs: {x}, backend});\n }\n const avgPoolProgram = new Pool2DProgram(convInfo, 'avg', false);\n return backend.runWebGLProgram(avgPoolProgram, [x], 'float32');\n}\n\nexport const avgPoolConfig: KernelConfig = {\n kernelName: AvgPool,\n backendName: 'webgl',\n kernelFunc: avgPool as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {AvgPool3D, AvgPool3DAttrs, AvgPool3DInputs, backend_util, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool3DProgram} from '../pool_gpu';\n\nexport function avgPool3D(args: {\n inputs: AvgPool3DInputs,\n backend: MathBackendWebGL,\n attrs: AvgPool3DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {filterSize, strides, pad, dimRoundingMode, dataFormat} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode, dataFormat);\n const avgPoolProgram = new Pool3DProgram(convInfo, 'avg', false);\n return backend.runWebGLProgram(avgPoolProgram, [x], 'float32');\n}\n\nexport const avgPool3DConfig: KernelConfig = {\n kernelName: AvgPool3D,\n backendName: 'webgl',\n kernelFunc: avgPool3D as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class AvgPool2DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const avgMultiplier = 1 / (filterHeight * filterWidth);\n\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n const float avgMultiplier = float(${avgMultiplier});\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 < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC+= ${dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.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 `;\n }\n}\n\nexport class AvgPool3DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.inShape;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);\n\n this.userCode = `\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n const float avgMultiplier = float(${avgMultiplier});\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 < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n float dyD = float(dyDCorner + wD) / ${strideDepth}.0;\n\n if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {AvgPool3DGrad, AvgPool3DGradAttrs, AvgPool3DGradInputs, backend_util, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {AvgPool3DBackpropProgram} from '../avg_pool_backprop_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function avgPool3DGrad(args: {\n inputs: AvgPool3DGradInputs,\n backend: MathBackendWebGL,\n attrs: AvgPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n const avgPoolBackpropProgram = new AvgPool3DBackpropProgram(convInfo);\n return backend.runWebGLProgram(avgPoolBackpropProgram, [dy], x.dtype);\n}\n\nexport const avgPoolGrad3DConfig: KernelConfig = {\n kernelName: AvgPool3DGrad,\n backendName: 'webgl',\n kernelFunc: avgPool3DGrad as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {AvgPoolGrad, AvgPoolGradAttrs, AvgPoolGradInputs, backend_util, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {AvgPool2DBackpropProgram} from '../avg_pool_backprop_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {assertNotComplex} from '../webgl_util';\n\nexport function avgPoolGrad(args: {\n inputs: AvgPoolGradInputs,\n backend: MathBackendWebGL,\n attrs: AvgPoolGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n assertNotComplex([dy, input], 'avgPoolGrad');\n const {filterSize, strides, pad} = attrs;\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad);\n const avgPoolBackpropProgram = new AvgPool2DBackpropProgram(convInfo);\n return backend.runWebGLProgram(avgPoolBackpropProgram, [dy], x.dtype);\n}\n\nexport const avgPoolGradConfig: KernelConfig = {\n kernelName: AvgPoolGrad,\n backendName: 'webgl',\n kernelFunc: avgPoolGrad as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {batchMatMulImpl} from './BatchMatMul_impl';\n\nexport function batchMatMul(args: {\n inputs: BatchMatMulInputs,\n attrs: BatchMatMulAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b} = inputs;\n const {transposeA, transposeB} = attrs;\n\n return batchMatMulImpl({a, b, transposeA, transposeB, backend});\n}\n\nexport const batchMatMulConfig: KernelConfig = {\n kernelName: BatchMatMul,\n backendName: 'webgl',\n kernelFunc: batchMatMul as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class BatchNormProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n xShape: number[], meanShape: number[], varianceShape: number[],\n offsetShape: number[]|null, scaleShape: number[]|null,\n varianceEpsilon: number) {\n this.variableNames = ['x', 'mean', 'variance'];\n backend_util.assertAndGetBroadcastShape(xShape, meanShape);\n backend_util.assertAndGetBroadcastShape(xShape, varianceShape);\n\n let offsetSnippet = '0.0';\n if (offsetShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, offsetShape);\n this.variableNames.push('offset');\n offsetSnippet = 'getOffsetAtOutCoords()';\n }\n\n let scaleSnippet = '1.0';\n if (scaleShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, scaleShape);\n this.variableNames.push('scale');\n scaleSnippet = 'getScaleAtOutCoords()';\n }\n\n this.outputShape = xShape;\n this.userCode = `\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${offsetSnippet};\n float scale = ${scaleSnippet};\n float inv = scale * inversesqrt(variance + float(${varianceEpsilon}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class BatchNormPackedProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n xShape: number[], meanShape: number[], varianceShape: number[],\n offsetShape: number[]|null, scaleShape: number[]|null,\n varianceEpsilon: number) {\n this.variableNames = ['x', 'mean', 'variance'];\n backend_util.assertAndGetBroadcastShape(xShape, meanShape);\n backend_util.assertAndGetBroadcastShape(xShape, varianceShape);\n\n let offsetSnippet = 'vec4(0.0)';\n if (offsetShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, offsetShape);\n this.variableNames.push('offset');\n offsetSnippet = 'getOffsetAtOutCoords()';\n }\n\n let scaleSnippet = 'vec4(1.0)';\n if (scaleShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, scaleShape);\n this.variableNames.push('scale');\n scaleSnippet = 'getScaleAtOutCoords()';\n }\n\n this.outputShape = xShape;\n this.userCode = `\n void main() {\n vec4 offset = ${offsetSnippet};\n vec4 scale = ${scaleSnippet};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${varianceEpsilon}));\n\n setOutput((x - mean) * inv + offset);\n }\n `;\n }\n}\n","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BatchNormProgram} from '../batchnorm_gpu';\nimport {BatchNormPackedProgram} from '../batchnorm_packed_gpu';\n\nexport const batchNorm: (params: {\n inputs: FusedBatchNormInputs,\n backend: MathBackendWebGL,\n attrs: FusedBatchNormAttrs\n}) => TensorInfo = ({inputs, backend, attrs}) => {\n const {x, mean, variance, offset, scale} = inputs;\n\n util.assert(\n mean.shape.length === variance.shape.length,\n () => 'Batch normalization gradient requires mean and variance to have ' +\n 'equal ranks.');\n util.assert(\n offset == null || mean.shape.length === offset.shape.length,\n () => 'Batch normalization gradient requires mean and offset to have ' +\n 'equal ranks.');\n util.assert(\n scale == null || mean.shape.length === scale.shape.length,\n () => 'Batch normalization gradient requires mean and scale to have ' +\n 'equal ranks.');\n\n let {varianceEpsilon} = attrs;\n if (varianceEpsilon == null) {\n varianceEpsilon = 0.001;\n }\n\n const finalInputs = [x, mean, variance];\n\n let offsetShape = null;\n if (offset != null) {\n offsetShape = offset.shape;\n finalInputs.push(offset);\n }\n\n let scaleShape = null;\n if (scale != null) {\n scaleShape = scale.shape;\n finalInputs.push(scale);\n }\n\n const program = env().getBool('WEBGL_PACK_NORMALIZATION') ?\n new BatchNormPackedProgram(\n x.shape, mean.shape, variance.shape, offsetShape, scaleShape,\n varianceEpsilon) :\n new BatchNormProgram(\n x.shape, mean.shape, variance.shape, offsetShape, scaleShape,\n varianceEpsilon);\n const output =\n backend.runWebGLProgram(program, finalInputs, finalInputs[0].dtype);\n\n return output;\n};\n\nexport const batchNormConfig: KernelConfig = {\n kernelName: FusedBatchNorm,\n backendName: 'webgl',\n kernelFunc: batchNorm as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class SliceProgram implements GPGPUProgram {\n variableNames = ['source'];\n outputShape: number[];\n userCode: string;\n rank: number;\n\n // Caching uniform location for speed.\n startLoc: WebGLUniformLocation;\n\n constructor(destSize: number[]) {\n this.outputShape = destSize;\n this.rank = destSize.length;\n\n const dtype = getCoordsDataType(this.rank);\n const uniformPart = `uniform int start[${this.rank}];`;\n const sourceCoords = getCoords(this.rank);\n\n let body: string;\n const coordSum = destSize.map((_, i) => {\n return `sourceLoc.${coords[i]} = start[${i}] + coords.${coords[i]};`;\n });\n body = `\n ${dtype} sourceLoc;\n ${dtype} coords = getOutputCoords();\n ${coordSum.join('\\n')}\n `;\n this.userCode = `\n ${uniformPart}\n void main() {\n ${body}\n setOutput(getSource(${sourceCoords}));\n }\n `;\n }\n\n getCustomSetupFunc(start: number[]) {\n if (start.length !== this.rank) {\n throw Error(\n `The rank (${this.rank}) of the program must match the ` +\n `length of start (${start.length})`);\n }\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.startLoc == null) {\n this.startLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'start');\n if (this.startLoc == null) {\n // This means the compiler has optimized and realized it doesn't need\n // the uniform.\n return;\n }\n }\n gpgpu.gl.uniform1iv(this.startLoc, start);\n };\n }\n}\n\nconst coords = ['x', 'y', 'z', 'w', 'u', 'v'];\n\nfunction getCoords(rank: number): string {\n if (rank === 1) {\n return 'sourceLoc';\n } else if (rank <= 6) {\n return coords.slice(0, rank).map(x => 'sourceLoc.' + x).join(',');\n } else {\n throw Error(`Slicing for rank ${rank} is not yet supported`);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class SlicePackedProgram implements GPGPUProgram {\n variableNames = ['source'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n rank: number;\n\n // Caching uniform location for speed.\n startLoc: WebGLUniformLocation;\n\n constructor(destSize: number[]) {\n this.outputShape = destSize;\n this.rank = destSize.length;\n\n const dtype = getCoordsDataType(this.rank);\n const coords = getChannels('coords', this.rank);\n const sourceLoc = getChannels('sourceLoc', this.rank);\n\n const innerDims =\n this.rank === 1 ? 'sourceLoc' : `vec2(${sourceLoc.slice(-2).join()})`;\n const getChannel =\n `getChannel(getSource(${sourceLoc.join()}), ${innerDims})`;\n const upperRow = `\n result.x = ${getChannel};\n if (++${coords[this.rank - 1]} < ${destSize[this.rank - 1]}) {\n ++${sourceLoc[this.rank - 1]};\n result.y = ${getChannel};\n --${sourceLoc[this.rank - 1]};\n }\n `;\n const lowerRow = this.rank === 1 ? '' : `\n --${coords[this.rank - 1]};\n if (++${coords[this.rank - 2]} < ${destSize[this.rank - 2]}) {\n ++${sourceLoc[this.rank - 2]};\n result.z = ${getChannel};\n if (++${coords[this.rank - 1]} < ${destSize[this.rank - 1]}) {\n ++${sourceLoc[this.rank - 1]};\n result.w = ${getChannel};\n }\n }\n `;\n\n const sourceLocSetup = this.rank <= 4 ?\n `sourceLoc = coords +\n ${dtype}(${destSize.map((_, i) => `start[${i}]`).join()});` :\n destSize.map((_, i) => `${sourceLoc[i]} = ${coords[i]} + start[${i}];`)\n .join('\\n');\n this.userCode = `\n uniform int start[${this.rank}];\n void main() {\n ${dtype} coords = getOutputCoords();\n ${dtype} sourceLoc;\n ${sourceLocSetup}\n vec4 result = vec4(0.);\n ${upperRow}\n ${lowerRow}\n setOutput(result);\n }\n `;\n }\n\n getCustomSetupFunc(start: number[]) {\n if (start.length !== this.rank) {\n throw Error(\n `The rank (${this.rank}) of the program must match the ` +\n `length of start (${start.length})`);\n }\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.startLoc == null) {\n this.startLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'start');\n if (this.startLoc == null) {\n // This means the compiler has optimized and realized it doesn't need\n // the uniform.\n return;\n }\n }\n gpgpu.gl.uniform1iv(this.startLoc, start);\n };\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, Slice, slice_util, SliceAttrs, SliceInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sliceImplCPU} from '../kernel_utils/shared';\nimport {SliceProgram} from '../slice_gpu';\nimport {SlicePackedProgram} from '../slice_packed_gpu';\n\nfunction shallowSlice(\n x: TensorInfo, begin: number[], size: number[], backend: MathBackendWebGL) {\n const xTexData = backend.texData.get(x.dataId);\n const t = backend.makeTensorInfo(size, x.dtype);\n const newTexData = backend.texData.get(t.dataId);\n // Copy texture data from the original tensor.\n Object.assign(newTexData, xTexData);\n newTexData.refCount = 1;\n newTexData.shape = size;\n newTexData.dtype = x.dtype;\n let flatOffset =\n slice_util.computeFlatOffset(begin, util.computeStrides(x.shape));\n if (xTexData.slice) {\n // We are slicing an already sliced tensor, so we have to accumulate\n // the offset.\n flatOffset += xTexData.slice.flatOffset;\n }\n newTexData.slice = {\n flatOffset,\n // Point to the original dataId, which is used to do ref counting.\n origDataId: xTexData.slice && xTexData.slice.origDataId || x.dataId\n };\n\n // Increase the ref count for that data bucket.\n const refCount = backend.dataRefCount.get(newTexData.slice.origDataId) || 1;\n backend.dataRefCount.set(newTexData.slice.origDataId, refCount + 1);\n return t;\n}\n\nexport function slice(\n args: {inputs: SliceInputs, backend: MathBackendWebGL, attrs: SliceAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {begin, size} = attrs;\n\n const [$begin, $size] = slice_util.parseSliceParams(x, begin, size);\n slice_util.assertParamsValid(x, $begin, $size);\n\n if (util.sizeFromShape($size) === 0) {\n return backend.makeTensorInfo($size, x.dtype, []);\n }\n\n // Run on cpu if dtype is string. For string, the backend represents it\n // as Uint8Array[], where each Uint8Array is a character. Given that the\n // computation is only on the outer array, uploading the whole data onto\n // gpu is wasteful. Also, currently webgl doesn't have a design to\n // upload and retrieve Uint8Array[] between cpu and gpu. Therefore, we\n // just run the kernel on cpu if dtype is string.\n if (backend.shouldExecuteOnCPU([x]) || x.dtype === 'string') {\n const xTexData = backend.texData.get(x.dataId);\n const outValues = sliceImplCPU(\n xTexData.values as TypedArray, $begin, $size, x.shape, x.dtype);\n return backend.makeTensorInfo($size, x.dtype, outValues);\n }\n\n const {isPacked} = backend.texData.get(x.dataId);\n const isContinous = slice_util.isSliceContinous(x.shape, $begin, $size);\n if (isPacked || !isContinous) {\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new SlicePackedProgram($size) :\n new SliceProgram($size);\n const customSetup = program.getCustomSetupFunc($begin);\n return backend.runWebGLProgram(program, [x], x.dtype, customSetup);\n }\n backend.uploadToGPU(x.dataId);\n return shallowSlice(x, $begin, $size, backend);\n}\n\nexport const sliceConfig: KernelConfig = {\n kernelName: Slice,\n backendName: 'webgl',\n kernelFunc: slice as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BatchToSpaceND, BatchToSpaceNDAttrs, BatchToSpaceNDInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\nimport {transpose} from './Transpose';\n\nexport const batchToSpaceND = (args: {\n inputs: BatchToSpaceNDInputs,\n backend: MathBackendWebGL,\n attrs: BatchToSpaceNDAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, crops} = attrs;\n\n util.assert(\n x.shape.length <= 4,\n () => 'batchToSpaceND for rank > 4 with a WebGL backend not ' +\n 'implemented yet');\n const prod = blockShape.reduce((a, b) => a * b);\n\n const reshaped = backend_util.getReshaped(x.shape, blockShape, prod);\n const permuted = backend_util.getPermuted(reshaped.length, blockShape.length);\n const reshapedPermuted =\n backend_util.getReshapedPermuted(x.shape, blockShape, prod);\n const sliceBeginCoords =\n backend_util.getSliceBeginCoords(crops, blockShape.length);\n const sliceSize =\n backend_util.getSliceSize(reshapedPermuted, crops, blockShape.length);\n\n const toDispose = [];\n\n const reshapedIntermediate =\n reshape({inputs: {x}, backend, attrs: {shape: reshaped}});\n const transposedIntermediate = transpose(\n {inputs: {x: reshapedIntermediate}, backend, attrs: {perm: permuted}});\n const reshapedIntermediate2 = reshape({\n inputs: {x: transposedIntermediate},\n backend,\n attrs: {shape: reshapedPermuted}\n });\n const sliced = slice({\n inputs: {x: reshapedIntermediate2},\n backend,\n attrs: {begin: sliceBeginCoords, size: sliceSize}\n });\n\n toDispose.push(reshapedIntermediate);\n toDispose.push(transposedIntermediate);\n toDispose.push(reshapedIntermediate2);\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return sliced;\n};\n\nexport const batchToSpaceNDConfig: KernelConfig = {\n kernelName: BatchToSpaceND,\n backendName: 'webgl',\n kernelFunc: batchToSpaceND as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Bincount, BincountAttrs, BincountInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {bincountImplCPU} from '../kernel_utils/shared';\n\nexport function bincount(args: {\n inputs: BincountInputs,\n backend: MathBackendWebGL,\n attrs: BincountAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, weights} = inputs;\n const {size} = attrs;\n\n const xVals = backend.readSync(x.dataId) as TypedArray;\n const weightsVals = backend.readSync(weights.dataId) as TypedArray;\n\n const outVals =\n bincountImplCPU(xVals, weightsVals, weights.dtype, weights.shape, size);\n\n return backend.makeTensorInfo([size], weights.dtype, outVals);\n}\n\nexport const bincountConfig: KernelConfig = {\n kernelName: Bincount,\n backendName: 'webgl',\n kernelFunc: bincount as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {NotEqual} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {notEqualImplCPU} from '../kernel_utils/shared';\n\nconst NOT_EQUAL = `return float(a != b);`;\n\nexport const notEqual = binaryKernelFunc(\n {opSnippet: NOT_EQUAL, cpuKernelImpl: notEqualImplCPU, dtype: 'bool'});\n\nexport const notEqualConfig: KernelConfig = {\n kernelName: NotEqual,\n backendName: 'webgl',\n kernelFunc: notEqual,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Real, RealInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\nexport function real(args: {inputs: RealInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n const inputData = backend.texData.get(input.dataId);\n\n return identity({inputs: {x: inputData.complexTensorInfos.real}, backend});\n}\n\nexport const realConfig: KernelConfig = {\n kernelName: Real,\n backendName: 'webgl',\n kernelFunc: real as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {UnaryOpProgram} from '../unaryop_gpu';\n\nconst TO_INT = `return float(int(x));`;\n\nexport function int(input: TensorInfo, backend: MathBackendWebGL): TensorInfo {\n const program = new UnaryOpProgram(input.shape, TO_INT);\n const output = backend.runWebGLProgram(program, [input], 'int32');\n return {dataId: output.dataId, shape: output.shape, dtype: output.dtype};\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport * as tf from '@tensorflow/tfjs-core';\nimport {BinaryInputs, Cast, CastAttrs, CastInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {complex} from './Complex';\nimport {identity} from './Identity';\nimport {notEqual} from './NotEqual';\nimport {real} from './Real';\n\nimport {int} from '../kernel_utils/int';\n\nexport function cast(\n args: {inputs: CastInputs, backend: MathBackendWebGL, attrs: CastAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {dtype} = attrs;\n\n // Casting to complex64.\n if (dtype === 'complex64') {\n if (x.dtype === 'complex64') {\n return identity({inputs: {x}, backend});\n }\n\n // TODO(annxingyuan): Import kernel function once zeros is modularized.\n const zerosTensor = tf.zeros(x.shape);\n const floatX = cast({inputs: {x}, backend, attrs: {dtype: 'float32'}});\n\n const result =\n complex({inputs: {real: floatX, imag: zerosTensor}, backend});\n\n zerosTensor.dispose();\n backend.disposeIntermediateTensorInfo(floatX);\n\n return result;\n }\n\n // Casting from complex64\n if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const result = cast({inputs: {x: realPart}, backend, attrs: {dtype}});\n backend.disposeIntermediateTensorInfo(realPart);\n return result;\n }\n\n if (!util.hasEncodingLoss(x.dtype, dtype)) {\n // We don't change the underlying data, since we cast to higher\n // precision.\n const result = identity({inputs: {x}, backend});\n return {dataId: result.dataId, shape: result.shape, dtype};\n }\n\n if (dtype === 'int32') {\n return int(x, backend);\n }\n\n if (dtype === 'bool') {\n const zerosTensorInfo = backend.makeTensorInfo(\n [], 'bool', util.getTypedArrayFromDType('bool', 1));\n\n const binaryInputs: BinaryInputs = {a: x, b: zerosTensorInfo};\n\n const result = notEqual({inputs: binaryInputs, backend}) as TensorInfo;\n backend.disposeIntermediateTensorInfo(zerosTensorInfo);\n return result;\n }\n\n throw new Error(`Error in Cast: failed to cast ${x.dtype} to ${dtype}`);\n}\n\nexport const castConfig: KernelConfig = {\n kernelName: Cast,\n backendName: 'webgl',\n kernelFunc: cast as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Ceil, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {ceilImplCPU} from '../kernel_utils/shared';\n\nconst CEIL = `return ceil(x);`;\n\nexport const ceil = unaryKernelFunc(\n {opSnippet: CEIL, packedOpSnippet: CEIL, cpuKernelImpl: ceilImplCPU});\n\nexport const ceilConfig: KernelConfig = {\n kernelName: Ceil,\n backendName: 'webgl',\n kernelFunc: ceil as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ClipProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n\n // Caching uniform locations for speed.\n minLoc: WebGLUniformLocation;\n maxLoc: WebGLUniformLocation;\n\n constructor(aShape: number[]) {\n this.outputShape = aShape;\n 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 `;\n }\n\n getCustomSetupFunc(min: number, max: number) {\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.minLoc == null) {\n this.minLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'minVal');\n this.maxLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'maxVal');\n }\n gpgpu.gl.uniform1f(this.minLoc, min);\n gpgpu.gl.uniform1f(this.maxLoc, max);\n };\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ClipPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n userCode: string;\n outputShape: number[];\n\n // Caching uniform locations for speed.\n minLoc: WebGLUniformLocation;\n maxLoc: WebGLUniformLocation;\n\n constructor(aShape: number[]) {\n this.outputShape = aShape;\n 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 `;\n }\n\n getCustomSetupFunc(min: number, max: number) {\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.minLoc == null) {\n this.minLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'minVal');\n this.maxLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'maxVal');\n }\n gpgpu.gl.uniform1f(this.minLoc, min);\n gpgpu.gl.uniform1f(this.maxLoc, max);\n };\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ClipByValue, ClipByValueAttrs, ClipByValueInputs, env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ClipProgram} from '../clip_gpu';\nimport {ClipPackedProgram} from '../clip_packed_gpu';\n\nexport function clipByValue(args: {\n inputs: ClipByValueInputs,\n backend: MathBackendWebGL,\n attrs: ClipByValueAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {clipValueMin, clipValueMax} = attrs;\n\n let program;\n if (env().getBool('WEBGL_PACK_CLIP')) {\n program = new ClipPackedProgram(x.shape);\n } else {\n program = new ClipProgram(x.shape);\n }\n const customSetup = program.getCustomSetupFunc(clipValueMin, clipValueMax);\n return backend.runWebGLProgram(program, [x], x.dtype, customSetup);\n}\n\nexport const clipByValueConfig: KernelConfig = {\n kernelName: ClipByValue,\n backendName: 'webgl',\n kernelFunc: clipByValue as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ComplexAbsProgram implements GPGPUProgram {\n variableNames = ['real', 'imag'];\n userCode: string;\n outputShape: number[];\n\n constructor(shape: number[]) {\n this.outputShape = shape;\n 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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ComplexAbs, ComplexAbsInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ComplexAbsProgram} from '../complex_abs_gpu';\n\n// Returns a TensorInfo with the complex shape and the dataId of the\n// underlying part. We need to do this because a reshaped complex tensor is\n// not reflected in its parts.\nfunction makeComplexComponentTensorInfo(\n complexTensor: TensorInfo, complexPart: TensorInfo): TensorInfo {\n return {\n dataId: complexPart.dataId,\n dtype: complexPart.dtype,\n shape: complexTensor.shape\n };\n}\n\nexport function complexAbs(\n args: {inputs: ComplexAbsInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n const xData = backend.texData.get(x.dataId);\n\n const program = new ComplexAbsProgram(x.shape);\n const programInputs = [\n makeComplexComponentTensorInfo(x, xData.complexTensorInfos.real),\n makeComplexComponentTensorInfo(x, xData.complexTensorInfos.imag),\n ];\n\n return backend.runWebGLProgram(\n program, programInputs, programInputs[0].dtype);\n}\n\nexport const complexAbsConfig: KernelConfig = {\n kernelName: ComplexAbs,\n backendName: 'webgl',\n kernelFunc: complexAbs as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ConcatProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n // Concats 2d tensors along axis=1. See comments in MathBackendWebGL.concat().\n constructor(shapes: Array<[number, number]>) {\n this.outputShape = backend_util.computeOutShape(shapes, 1 /* axis */);\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const offsets: number[] = new Array(shapes.length - 1);\n offsets[0] = shapes[0][1];\n for (let i = 1; i < offsets.length; i++) {\n offsets[i] = offsets[i - 1] + shapes[i][1];\n }\n\n const snippets = [`if (yC < ${offsets[0]}) setOutput(getT0(yR, yC));`];\n for (let i = 1; i < offsets.length; i++) {\n const shift = offsets[i - 1];\n snippets.push(\n `else if (yC < ${offsets[i]}) ` +\n `setOutput(getT${i}(yR, yC-${shift}));`);\n }\n const lastIndex = offsets.length;\n const lastShift = offsets[offsets.length - 1];\n snippets.push(`else setOutput(getT${lastIndex}(yR, yC-${lastShift}));`);\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n ${snippets.join('\\n ')}\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ConcatPackedProgram implements GPGPUProgram {\n variableNames: string[];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[] = [];\n userCode: string;\n\n constructor(shapes: number[][], axis: number) {\n this.outputShape = backend_util.computeOutShape(shapes, axis);\n const shape = this.outputShape;\n const rank = shape.length;\n const dtype = getCoordsDataType(rank);\n const coords = getChannels('coords', rank);\n const channels = ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, rank);\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const offsets: number[] = new Array(shapes.length - 1);\n offsets[0] = shapes[0][axis];\n for (let i = 1; i < offsets.length; i++) {\n offsets[i] = offsets[i - 1] + shapes[i][axis];\n }\n\n const channel = channels[axis];\n const lastChannels = channels.slice(-2);\n const allChannels = channels.join();\n\n let getValueSnippet = `if (${channel} < ${offsets[0]}) {\n return getChannel(\n getT0(${allChannels}), vec2(${lastChannels.join()}));\n }`;\n for (let i = 1; i < offsets.length; i++) {\n const shift = offsets[i - 1];\n // Note: the >= comparison below may seem unnecessary given the check\n // above but is needed to workaround branch execution issues on some\n // devices. It makes all the conditions exclusive without relying on\n // execution order.\n getValueSnippet += `\n if (${channel} < ${offsets[i]} && ${channel} >= ${offsets[i - 1]}) {\n return getChannel(\n getT${i}(${shiftedChannels(channels, channel, shift)}),\n vec2(${shiftedChannels(lastChannels, channel, shift)}));\n }`;\n }\n const lastIndex = offsets.length;\n const shift = offsets[offsets.length - 1];\n getValueSnippet += `\n return getChannel(\n getT${lastIndex}(${shiftedChannels(channels, channel, shift)}),\n vec2(${shiftedChannels(lastChannels, channel, shift)}));`;\n\n this.userCode = `\n float getValue(${channels.map(x => 'int ' + x)}) {\n ${getValueSnippet}\n }\n\n void main() {\n ${dtype} coords = getOutputCoords();\n vec4 result = vec4(getValue(${coords}), 0., 0., 0.);\n\n ${coords[rank - 1]} = ${coords[rank - 1]} + 1;\n if (${coords[rank - 1]} < ${shape[rank - 1]}) {\n result.g = getValue(${coords});\n }\n\n ${coords[rank - 2]} = ${coords[rank - 2]} + 1;\n if (${coords[rank - 2]} < ${shape[rank - 2]}) {\n result.a = getValue(${coords});\n }\n\n ${coords[rank - 1]} = ${coords[rank - 1]} - 1;\n if (${coords[rank - 2]} < ${shape[rank - 2]} &&\n ${coords[rank - 1]} < ${shape[rank - 1]}) {\n result.b = getValue(${coords});\n }\n setOutput(result);\n }\n `;\n }\n}\n\n/**\n * Return an expression for coordinates into a vector where a given channel\n * will be offset by [shift].\n *\n * @param channels the channels to consider\n * @param channel the channel we want shifted\n * @param shift the amount to subtract from the channel.\n *\n * @returns a string of the form 'x, y-[shift], z' where any one channel can\n * have the shift applied.\n */\nfunction shiftedChannels(channels: string[], channel: string, shift: number) {\n const channelIdx = channels.indexOf(channel);\n const res = channels.map((c, idx) => {\n if (idx === channelIdx) {\n return `${c} - ${shift}`;\n } else {\n return c;\n }\n });\n return res.join();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Imag, ImagInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\nexport function imag(args: {inputs: ImagInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n const inputData = backend.texData.get(input.dataId);\n\n return identity({inputs: {x: inputData.complexTensorInfos.imag}, backend});\n}\n\nexport const imagConfig: KernelConfig = {\n kernelName: Imag,\n backendName: 'webgl',\n kernelFunc: imag as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, ConcatInputs, env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ConcatProgram} from '../concat_gpu';\nimport {ConcatPackedProgram} from '../concat_packed_gpu';\nimport {concatImplCPU} from '../kernel_utils/shared';\n\nimport {complex} from './Complex';\nimport {imag} from './Imag';\nimport {real} from './Real';\nimport {reshape} from './Reshape';\n\nexport function concatImpl(\n inputs: ConcatInputs, axis: number, backend: MathBackendWebGL): TensorInfo {\n const dtype = inputs[0].dtype;\n if (dtype === 'complex64') {\n const reals = inputs.map((t) => real({inputs: {input: t}, backend}));\n const imags = inputs.map((t) => imag({inputs: {input: t}, backend}));\n\n const realConcated = concatImpl(reals, axis, backend);\n const imagConcated = concatImpl(imags, axis, backend);\n\n const result =\n complex({inputs: {real: realConcated, imag: imagConcated}, backend});\n\n reals.forEach(r => backend.disposeIntermediateTensorInfo(r));\n imags.forEach(i => backend.disposeIntermediateTensorInfo(i));\n backend.disposeIntermediateTensorInfo(realConcated);\n backend.disposeIntermediateTensorInfo(imagConcated);\n\n return result;\n }\n\n let runOnCpu = backend.shouldExecuteOnCPU(inputs);\n\n // Run on cpu if dtype is string. For string, the backend represents it\n // as Uint8Array[], where each Uint8Array is a character. Given that the\n // computation is only on the outer array, uploading the whole data onto\n // gpu is wasteful. Also, currently webgl doesn't have a design to\n // upload and retrieve Uint8Array[] between cpu and gpu. Therefore, we\n // just run the kernel on cpu if dtype is string.\n if (dtype === 'string') {\n runOnCpu = true;\n }\n\n if (runOnCpu) {\n // Any concat of n-dimensional tensors across any axis can be reduced to\n // a concatenation of two-dimensional tensors across the axis 1 by first\n // partitioning the axes of the original tensors into those less than the\n // axis to be concatenated and the rest. Then reshape the tensors\n // into a two-dimensional tensor by collapsing these two sets of axes and\n // concatenate the resulting matrices across the axis 1, finally reshaping\n // the result to have the proper shape.\n const tensors2D = inputs.map(t => {\n const innerSize = util.sizeFromShape(t.shape.slice(axis));\n const shape = [-1, innerSize];\n return reshape({inputs: {x: t}, backend, attrs: {shape}});\n });\n\n const inputsValShapes = tensors2D.map(t => {\n return {vals: backend.readSync(t.dataId), shape: t.shape};\n });\n\n // Concats 2d tensors along axis=1.\n const outShape =\n backend_util.computeOutShape(tensors2D.map(t => t.shape), 1 /* axis */);\n const simplyConcat = tensors2D[0].shape[0] === 1;\n const outVals =\n concatImplCPU(inputsValShapes, outShape, dtype, simplyConcat);\n\n const finalOutShape =\n backend_util.computeOutShape(inputs.map(t => t.shape), axis);\n\n const outInfo = backend.makeTensorInfo(finalOutShape, dtype, outVals);\n\n tensors2D.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return outInfo;\n }\n\n if (inputs.length > env().getNumber('WEBGL_MAX_TEXTURES_IN_SHADER')) {\n const midIndex = Math.floor(inputs.length / 2);\n const leftSide = concatImpl(inputs.slice(0, midIndex), axis, backend);\n const rightSide = concatImpl(inputs.slice(midIndex), axis, backend);\n\n const result = concatImpl([leftSide, rightSide], axis, backend);\n\n backend.disposeIntermediateTensorInfo(leftSide);\n backend.disposeIntermediateTensorInfo(rightSide);\n\n return result;\n }\n\n if (env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') &&\n inputs[0].shape.length > 1) {\n const program = new ConcatPackedProgram(inputs.map(t => t.shape), axis);\n return backend.runWebGLProgram(program, inputs, dtype);\n }\n\n const {tensors2D, outShape} = computeTensors2D(inputs, axis, backend);\n const program =\n new ConcatProgram(tensors2D.map(t => t.shape as [number, number]));\n const result = backend.runWebGLProgram(program, tensors2D, dtype);\n\n tensors2D.forEach(r => backend.disposeIntermediateTensorInfo(r));\n const reshapedResult =\n reshape({inputs: {x: result}, attrs: {shape: outShape}, backend});\n backend.disposeIntermediateTensorInfo(result);\n\n return reshapedResult;\n}\n\nfunction computeTensors2D(\n inputs: ConcatInputs, axis: number, backend: MathBackendWebGL) {\n // Any concat of n-dimensional tensors across any axis can be reduced to\n // a concatenation of two-dimensional tensors across the axis 1 by first\n // partitioning the axes of the original tensors into those less than the\n // axis to be concatenated and the rest. Then reshape the tensors\n // into a two-dimensional tensor by collapsing these two sets of axes and\n // concatenate the resulting matrices across the axis 1, finally reshaping\n // the result to have the proper shape.\n const outShape = backend_util.computeOutShape(inputs.map(t => t.shape), axis);\n const tensors2D = inputs.map(\n x => reshape({\n inputs: {x},\n attrs: {shape: [-1, util.sizeFromShape(x.shape.slice(axis))]},\n backend\n }));\n\n return {tensors2D, outShape};\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Concat, ConcatAttrs, ConcatInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {concatImpl} from './Concat_impl';\nimport {identity} from './Identity';\n\nexport function concat(\n args:\n {inputs: ConcatInputs, attrs: ConcatAttrs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {axis} = attrs;\n\n const $axis = util.parseAxisParam(axis, inputs[0].shape)[0];\n const outShape =\n backend_util.computeOutShape(inputs.map(t => t.shape), $axis);\n\n if (util.sizeFromShape(outShape) === 0) {\n return backend.makeTensorInfo(outShape, inputs[0].dtype, []);\n }\n\n // Keep only non-empty tensors (ignore tensors with 0 in their shape).\n const $inputs = inputs.filter(t => util.sizeFromShape(t.shape) > 0);\n if ($inputs.length === 1) {\n return identity({inputs: {x: $inputs[0]}, backend});\n }\n\n const shapes = $inputs.map(t => t.shape);\n backend_util.assertParamsConsistent(shapes, $axis);\n\n return concatImpl($inputs, $axis, backend);\n}\n\nexport const concatConfig: KernelConfig = {\n kernelName: Concat,\n backendName: 'webgl',\n kernelFunc: concat as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Conv2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, addBias = false,\n activation: string = null, hasPreluActivationWeights = false,\n hasLeakyreluAlpha = false) {\n this.outputShape = convInfo.outShape;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n\n const inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;\n const inputDepthVec4Remainder = convInfo.inChannels % 4;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n const rowDim = isChannelsLast ? 1 : 2;\n const colDim = isChannelsLast ? 2 : 3;\n const channelDim = isChannelsLast ? 3 : 1;\n\n let activationSnippet = '', applyActivationSnippet = '';\n if (activation) {\n if (hasPreluActivationWeights) {\n activationSnippet = `float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${activation}\n }`;\n } else if (hasLeakyreluAlpha) {\n activationSnippet = `float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${activation}\n }`;\n } else {\n activationSnippet = `\n float activation(float x) {\n ${activation}\n }\n `;\n }\n\n applyActivationSnippet = `result = activation(result);`;\n }\n\n const addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';\n if (addBias) {\n this.variableNames.push('bias');\n }\n\n if (hasPreluActivationWeights) {\n this.variableNames.push('preluActivationWeights');\n }\n\n if (hasLeakyreluAlpha) {\n this.variableNames.push('leakyreluAlpha');\n }\n\n this.userCode = `\n ${activationSnippet}\n\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${channelDim}];\n\n ivec2 xRCCorner =\n ivec2(coords[${rowDim}], coords[${colDim}]) * 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 < ${filterHeight}; wR++) {\n int xR = xRCorner + wR * ${dilationHeight};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${inputDepthNearestVec4}; 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 (${isChannelsLast}) {\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 (${inputDepthVec4Remainder === 1}) {\n\n if (${isChannelsLast}) {\n dotProd +=\n getX(batch, xR, xC, ${inputDepthNearestVec4}) *\n getW(wR, wC, ${inputDepthNearestVec4}, d2);\n } else {\n dotProd +=\n getX(batch, ${inputDepthNearestVec4}, xR, xC) *\n getW(wR, wC, ${inputDepthNearestVec4}, d2);\n }\n\n } else if (${inputDepthVec4Remainder === 2}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wR, wC, ${inputDepthNearestVec4} + 1, d2)\n );\n\n if (${isChannelsLast}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xR, xC, ${inputDepthNearestVec4} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${inputDepthNearestVec4}, xR, xC),\n getX(batch, ${inputDepthNearestVec4} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${inputDepthVec4Remainder === 3}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wR, wC, ${inputDepthNearestVec4} + 1, d2),\n getW(wR, wC, ${inputDepthNearestVec4} + 2, d2)\n );\n\n if (${isChannelsLast}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xR, xC, ${inputDepthNearestVec4} + 1),\n getX(batch, xR, xC, ${inputDepthNearestVec4} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${inputDepthNearestVec4}, xR, xC),\n getX(batch, ${inputDepthNearestVec4} + 1, xR, xC),\n getX(batch, ${inputDepthNearestVec4} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${addBiasSnippet}\n ${applyActivationSnippet}\n setOutput(result);\n }\n `;\n }\n}\n\nexport class Conv3DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.outShape;\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n\n const inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;\n const inputDepthVec4Remainder = convInfo.inChannels % 4;\n\n this.userCode = `\n const ivec3 strides = ivec3(${strideDepth}, ${strideHeight}, ${\n strideWidth});\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\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 < ${filterDepth}; wF++) {\n int xF = xFCorner + wF * ${dilationDepth};\n\n if (xF < 0 || xF >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n int xR = xRCorner + wR * ${dilationHeight};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${inputDepthNearestVec4}; 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 (${inputDepthVec4Remainder === 1}) {\n dotProd +=\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4}) *\n getW(wF, wR, wC, ${inputDepthNearestVec4}, d2);\n } else if (${inputDepthVec4Remainder === 2}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${inputDepthVec4Remainder === 3}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1),\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2),\n getW(wF, wR, wC, ${inputDepthNearestVec4} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Im2ColPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(\n outputShape: number[], inputShape: number[],\n convInfo: backend_util.Conv2DInfo) {\n this.outputShape = outputShape;\n\n const {\n filterWidth,\n inChannels,\n strideWidth,\n strideHeight,\n padInfo,\n outWidth,\n dilationWidth,\n dilationHeight,\n dataFormat\n } = convInfo;\n const {left, top} = padInfo;\n const itemsPerBlockRow = inChannels * filterWidth;\n const glsl = getGlslDifferences();\n const isChannelsLast = dataFormat === 'channelsLast';\n const rowDim = isChannelsLast ? 0 : 1;\n const colDim = isChannelsLast ? 1 : 2;\n\n let unrolled = ``;\n\n for (let row = 0; row <= 1; row++) {\n for (let col = 0; col <= 1; col++) {\n unrolled += `\n blockIndex = rc.y + ${col};\n pos = rc.x + ${row};\n\n if(blockIndex < ${outputShape[1]} && pos < ${outputShape[0]}) {\n offsetY = int(blockIndex / (${outWidth})) * ${strideHeight} - ${\n top};\n d0 = offsetY + ${dilationHeight} * (pos / ${itemsPerBlockRow});\n\n if(d0 < ${inputShape[rowDim]} && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), ${outWidth}.) * ${\n strideWidth}. - ${left}.);\n d1 = offsetX + ${dilationWidth} * (int(mod(float(pos), ${\n itemsPerBlockRow}.) / ${inChannels}.));\n\n if(d1 < ${inputShape[colDim]} && d1 >= 0) {\n\n ch = int(mod(float(pos), ${inChannels}.));\n\n if (${isChannelsLast}) {\n innerDims = vec2(d1, ch);\n result[${row * 2 + col}] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${row * 2 + col}] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\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 ${unrolled}\n\n ${glsl.output} = result;\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Im2ColPackedProgram} from '../im2col_packed_gpu';\nimport {mapActivationToShaderProgram} from '../kernel_utils/kernel_funcs_utils';\nimport {MatMulPackedProgram} from '../mulmat_packed_gpu';\nimport * as webgl_util from '../webgl_util';\n\nimport {batchMatMulImpl, MATMUL_SHARED_DIM_THRESHOLD} from './BatchMatMul_impl';\nimport {identity} from './Identity';\nimport {reshape} from './Reshape';\n\ntype Conv2DConfig = {\n x: TensorInfo,\n filter: TensorInfo,\n convInfo: backend_util.Conv2DInfo,\n backend: MathBackendWebGL,\n bias?: TensorInfo,\n preluActivationWeights?: TensorInfo,\n leakyreluAlpha?: number,\n activation?: backend_util.Activation\n};\n\n// For 1x1 kernels that iterate through every point in the input, convolution\n// can be expressed as matrix multiplication (without need for memory\n// remapping).\nexport function conv2dByMatMul({\n x,\n filter,\n convInfo,\n backend,\n bias = null,\n preluActivationWeights = null,\n leakyreluAlpha = 0,\n activation = null\n}: Conv2DConfig) {\n // Reshapes conv2D input to 2D tensors, uses matMul and then reshape the\n // result from 2D to 4D.\n const xShape = x.shape;\n const xTexData = backend.texData.get(x.dataId);\n const sharedMatMulDim = convInfo.inChannels;\n const outerShapeX = xShape[0] * xShape[1] * xShape[2];\n const outerShapeFilter = convInfo.outChannels;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n const transposeA = false;\n const transposeB = false;\n\n let out: TensorInfo;\n const intermediates: TensorInfo[] = [];\n\n // TODO: Once reduction ops are packed, batchMatMul will always be packed\n // and we can remove this condition.\n const batchMatMulWillBeUnpacked =\n (outerShapeX === 1 || outerShapeFilter === 1) &&\n sharedMatMulDim > MATMUL_SHARED_DIM_THRESHOLD;\n const reshapeWillBeExpensive = xShape[2] % 2 !== 0 && !!xTexData.isPacked;\n\n if (batchMatMulWillBeUnpacked || !env().getBool('WEBGL_LAZILY_UNPACK') ||\n !env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ||\n !reshapeWillBeExpensive) {\n const targetShape = isChannelsLast ? xShape[0] * xShape[1] * xShape[2] :\n xShape[0] * xShape[2] * xShape[3];\n const xReshaped = reshape({\n inputs: {x},\n backend,\n attrs: {shape: [1, targetShape, convInfo.inChannels]}\n });\n const filterReshaped = reshape({\n inputs: {x: filter},\n backend,\n attrs: {shape: [1, convInfo.inChannels, convInfo.outChannels]}\n });\n const result = batchMatMulImpl({\n a: xReshaped,\n b: filterReshaped,\n transposeA,\n transposeB,\n backend,\n bias,\n activation,\n preluActivationWeights,\n leakyreluAlpha\n });\n\n out = reshape(\n {inputs: {x: result}, backend, attrs: {shape: convInfo.outShape}});\n\n intermediates.push(xReshaped);\n intermediates.push(filterReshaped);\n intermediates.push(result);\n } else {\n // Following optimization is specific to packed |x| with odd row count\n // (For example, in channelLast mode, 'row count' refers to x.shape[2]):\n // we avoid expensive packed 2x2 reshape by padding row count to next,\n // even number. When x.shape[2] is odd, the result of packed batchMatMul is\n // the same (has the same texture layout and and values in the texture) as\n // it is for even x.shape[2] + 1. We make the odd-rows tensor to look like\n // even-rows tensor before the operation and, after the batchMatMul,\n // fix the even-rows result to have odd number of rows.\n const targetShape = isChannelsLast ?\n xShape[0] * xShape[1] * (xShape[2] + 1) :\n xShape[0] * xShape[2] * (xShape[3] + 1);\n const xReshaped: TensorInfo = {\n dataId: x.dataId,\n shape: [1, targetShape, convInfo.inChannels],\n dtype: x.dtype\n };\n // xTexData.shape gets referenced from GPGPUBinary.inShapeInfos.\n // Decrementing row count, after batchMatMul->...->compileProgram leads to\n // invalid row count within the reference in GPGPUBinary.inShapeInfos.\n // Alternative fix would be to provide a copy to GPGPUBinary.inShapeInfos\n // in compileProgram method, but that would affect compilation of all\n // programs - instead, provide a copy here, with even row count, before\n // calling batchMatMul->...->compileProgram and after that, the original\n // xTexData.shape is restored.\n const originalXTexDataShape = xTexData.shape;\n xTexData.shape = xTexData.shape.slice();\n xTexData.shape[xTexData.shape.length - 2]++;\n util.assert(\n webgl_util.isReshapeFree(xTexData.shape, xReshaped.shape),\n () => `packed reshape ${xTexData.shape} to ${\n xReshaped.shape} isn't free`);\n const filterReshaped = reshape({\n inputs: {x: filter},\n backend,\n attrs: {shape: [1, convInfo.inChannels, convInfo.outChannels]}\n });\n intermediates.push(filterReshaped);\n const pointwiseConv = batchMatMulImpl({\n a: xReshaped,\n b: filterReshaped,\n backend,\n transposeA,\n transposeB,\n bias,\n activation,\n preluActivationWeights,\n leakyreluAlpha\n });\n\n const pointwiseConvTexData = backend.texData.get(pointwiseConv.dataId);\n util.assert(\n pointwiseConvTexData.isPacked,\n () => 'batchMatMul result is expected to be packed');\n // Restore the input shape to original.\n xTexData.shape = originalXTexDataShape;\n // Set the output shape - there is no need for expensive reshape as data\n // layout is already correct.\n pointwiseConvTexData.shape = convInfo.outShape;\n\n out = identity({inputs: {x: pointwiseConv}, backend});\n out.shape = convInfo.outShape;\n\n intermediates.push(pointwiseConv);\n }\n\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n\n return out;\n}\n\n// Implements the im2row algorithm as outlined in \"High Performance\n// Convolutional Neural Networks for Document Processing\" (Suvisoft, 2006)\nexport function conv2dWithIm2Row({\n x,\n filter,\n convInfo,\n backend,\n bias = null,\n preluActivationWeights = null,\n leakyreluAlpha = 0,\n activation = null\n}: Conv2DConfig) {\n // Rearranges conv2d input so each block to be convolved over forms the\n // column of a new matrix with shape [filterWidth * filterHeight *\n // inChannels, outHeight * outWidth]. The filter is also rearranged so each\n // output channel forms a row of a new matrix with shape [outChannels,\n // filterWidth * filterHeight * inChannels]. The convolution is then\n // computed by multiplying these matrices and reshaping the result.\n const {\n filterWidth,\n filterHeight,\n inChannels,\n outWidth,\n outHeight,\n dataFormat\n } = convInfo;\n\n const isChannelsLast = dataFormat === 'channelsLast';\n\n const sharedDim = filterWidth * filterHeight * inChannels;\n const numCols = outHeight * outWidth;\n const x2ColShape = [sharedDim, numCols];\n const transposeA = true;\n const transposeB = false;\n\n const intermediates: TensorInfo[] = [];\n\n const xSqueezed =\n reshape({inputs: {x}, backend, attrs: {shape: x.shape.slice(1)}});\n const w2Row = reshape({\n inputs: {x: filter},\n backend,\n attrs: {shape: [1, sharedDim, util.sizeFromShape(filter.shape) / sharedDim]}\n });\n\n intermediates.push(xSqueezed);\n intermediates.push(w2Row);\n\n const im2ColProgram =\n new Im2ColPackedProgram(x2ColShape, xSqueezed.shape, convInfo);\n const im2Col = backend.runWebGLProgram(im2ColProgram, [xSqueezed], 'float32');\n const im2ColReshaped = reshape({\n inputs: {x: im2Col},\n backend,\n attrs: {shape: [1, x2ColShape[0], x2ColShape[1]]}\n });\n\n intermediates.push(im2Col);\n intermediates.push(im2ColReshaped);\n\n const hasBias = bias != null;\n const hasPreluActivationWeights = preluActivationWeights != null;\n const hasLeakyreluAlpha = activation === 'leakyrelu';\n const fusedActivation =\n activation ? mapActivationToShaderProgram(activation, true) : null;\n const matmulProgram = new MatMulPackedProgram(\n im2ColReshaped.shape as [number, number, number],\n w2Row.shape as [number, number, number],\n [1, numCols, convInfo.outChannels], transposeA, transposeB, hasBias,\n fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);\n const inputs: TensorInfo[] = [im2ColReshaped, w2Row];\n if (bias) {\n inputs.push(bias);\n }\n if (hasPreluActivationWeights) {\n inputs.push(preluActivationWeights);\n }\n if (hasLeakyreluAlpha) {\n const $leakyreluAlpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(leakyreluAlpha as {} as 'float32', 'float32'));\n inputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n const product = backend.runWebGLProgram(matmulProgram, inputs, 'float32');\n\n const outShape = isChannelsLast ?\n [1, outHeight, outWidth, convInfo.outChannels] :\n [1, convInfo.outChannels, outHeight, outWidth];\n const out =\n reshape({inputs: {x: product}, backend, attrs: {shape: outShape}});\n\n intermediates.push(product);\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n\n return out;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv2D, Conv2DAttrs, Conv2DInputs, env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DProgram} from '../conv_gpu';\nimport {conv2dByMatMul, conv2dWithIm2Row} from './Conv2D_impl';\nimport {reshape} from './Reshape';\n\nexport function conv2d(\n args:\n {inputs: Conv2DInputs, attrs: Conv2DAttrs, backend: MathBackendWebGL}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dataFormat, dilations, dimRoundingMode} = attrs;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, dilations, pad,\n dimRoundingMode, false /* depthwise */, $dataFormat);\n let out: TensorInfo;\n\n if (convInfo.filterHeight === 1 && convInfo.filterWidth === 1 &&\n convInfo.dilationHeight === 1 && convInfo.dilationWidth === 1 &&\n convInfo.strideHeight === 1 && convInfo.strideWidth === 1 &&\n (convInfo.padInfo.type === 'SAME' || convInfo.padInfo.type === 'VALID')) {\n out = conv2dByMatMul({x, filter, convInfo, backend});\n } else if (env().getBool('WEBGL_CONV_IM2COL') && x.shape[0] === 1) {\n out = conv2dWithIm2Row({x, filter, convInfo, backend});\n } else {\n const program = new Conv2DProgram(convInfo);\n out = backend.runWebGLProgram(program, [x, filter], 'float32');\n }\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: convInfo.outShape}});\n backend.disposeIntermediateTensorInfo(out);\n\n return outReshaped;\n}\n\nexport const conv2DConfig: KernelConfig = {\n kernelName: Conv2D,\n backendName: 'webgl',\n kernelFunc: conv2d as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Conv2DDerFilterProgram implements GPGPUProgram {\n variableNames = ['x', 'dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.filterShape;\n\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n 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 < ${convInfo.batchSize}; b++) {\n for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {\n int xR = wR + yR * ${strideHeight} - ${padTop};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {\n int xC = wC + yC * ${strideWidth} - ${padLeft};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n if (${isChannelsLast}) {\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 `;\n }\n}\n\nexport class Conv2DDerInputProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\n\n const rowDim = isChannelsLast ? 1 : 2;\n const colDim = isChannelsLast ? 2 : 3;\n const channelDim = isChannelsLast ? 3 : 1;\n\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${channelDim}];\n\n ivec2 dyCorner = ivec2(coords[${rowDim}], coords[${colDim}]) - 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 < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${filterWidth} - 1 - wC;\n\n for (int d2 = 0; d2 < ${convInfo.outChannels}; d2++) {\n\n if (${isChannelsLast}) {\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 `;\n }\n}\n\nexport class Conv3DDerFilterProgram implements GPGPUProgram {\n variableNames = ['x', 'dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.filterShape;\n\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n\n 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 < ${convInfo.batchSize}; b++) {\n for (int yF = 0; yF < ${convInfo.outDepth}; yF++) {\n int xF = wF + yF * ${strideDepth} - ${padFront};\n\n if (xF < 0 || xF >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {\n int xR = wR + yR * ${strideHeight} - ${padTop};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {\n int xC = wC + yC * ${strideWidth} - ${padLeft};\n\n if (xC < 0 || xC >= ${convInfo.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 `;\n }\n}\n\nexport class Conv3DDerInputProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.inShape;\n\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n\n const padFront = filterDepth - 1 - convInfo.padInfo.front;\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\n\n this.userCode = `\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\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 < ${filterDepth}; wF++) {\n float dyF = float(dyFCorner + wF) / ${strideDepth}.0;\n\n if (dyF < 0.0 || dyF >= ${convInfo.outDepth}.0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = ${filterDepth} - 1 - wF;\n\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${filterWidth} - 1 - wC;\n\n for (int d2 = 0; d2 < ${convInfo.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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv2DBackpropFilter, Conv2DBackpropFilterAttrs, Conv2DBackpropFilterInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DDerFilterProgram} from '../conv_backprop_gpu';\n\nexport function conv2DBackpropFilter(args: {\n inputs: Conv2DBackpropFilterInputs,\n attrs: Conv2DBackpropFilterAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, pad, dataFormat, dimRoundingMode, filterShape} = attrs;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n 1 /* dilations */, pad, dimRoundingMode, false /* depthwise */,\n $dataFormat);\n\n const program = new Conv2DDerFilterProgram(convInfo);\n return backend.runWebGLProgram(program, [x, dy], 'float32');\n}\n\nexport const conv2DBackpropFilterConfig: KernelConfig = {\n kernelName: Conv2DBackpropFilter,\n backendName: 'webgl',\n kernelFunc: conv2DBackpropFilter as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DDerInputProgram} from '../conv_backprop_gpu';\n\nexport function conv2DBackpropInput(args: {\n inputs: Conv2DBackpropInputInputs,\n attrs: Conv2DBackpropInputAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {inputShape, strides, pad, dataFormat, dimRoundingMode} = attrs;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n inputShape, filter.shape as [number, number, number, number], strides,\n 1 /* dilations */, pad, dimRoundingMode, false, $dataFormat);\n\n const program = new Conv2DDerInputProgram(convInfo);\n return backend.runWebGLProgram(program, [dy, filter], 'float32');\n}\n\nexport const conv2DBackpropInputConfig: KernelConfig = {\n kernelName: Conv2DBackpropInput,\n backendName: 'webgl',\n kernelFunc: conv2DBackpropInput as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv3D, Conv3DAttrs, Conv3DInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv3DProgram} from '../conv_gpu';\n\nexport function conv3D(\n args:\n {inputs: Conv3DInputs, attrs: Conv3DAttrs, backend: MathBackendWebGL}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations} = attrs;\n\n const convInfo = backend_util.computeConv3DInfo(\n x.shape as [number, number, number, number, number],\n filter.shape as [number, number, number, number, number], strides,\n dilations, pad);\n\n const program = new Conv3DProgram(convInfo);\n return backend.runWebGLProgram(program, [x, filter], 'float32');\n}\n\nexport const conv3DConfig: KernelConfig = {\n kernelName: Conv3D,\n backendName: 'webgl',\n kernelFunc: conv3D as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv3DBackpropFilterV2, Conv3DBackpropFilterV2Attrs, Conv3DBackpropFilterV2Inputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv3DDerFilterProgram} from '../conv_backprop_gpu';\n\nexport function conv3DBackpropFilterV2(args: {\n inputs: Conv3DBackpropFilterV2Inputs,\n attrs: Conv3DBackpropFilterV2Attrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, pad, filterShape} = attrs;\n\n const convInfo = backend_util.computeConv3DInfo(\n x.shape as [number, number, number, number, number], filterShape, strides,\n 1 /* dilations */, pad);\n\n const program = new Conv3DDerFilterProgram(convInfo);\n return backend.runWebGLProgram(program, [x, dy], 'float32');\n}\n\nexport const conv3DBackpropFilterV2Config: KernelConfig = {\n kernelName: Conv3DBackpropFilterV2,\n backendName: 'webgl',\n kernelFunc: conv3DBackpropFilterV2 as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Conv3DBackpropInputV2, Conv3DBackpropInputV2Attrs, Conv3DBackpropInputV2Inputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv3DDerInputProgram} from '../conv_backprop_gpu';\n\nexport function conv3DBackpropInput(args: {\n inputs: Conv3DBackpropInputV2Inputs,\n attrs: Conv3DBackpropInputV2Attrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {pad, strides, inputShape} = attrs;\n\n const convInfo = backend_util.computeConv3DInfo(\n inputShape, filter.shape as [number, number, number, number, number],\n strides, 1 /* dilations */, pad);\n\n const program = new Conv3DDerInputProgram(convInfo);\n return backend.runWebGLProgram(program, [dy, filter], 'float32');\n}\n\nexport const conv3DBackpropInputConfig: KernelConfig = {\n kernelName: Conv3DBackpropInputV2,\n backendName: 'webgl',\n kernelFunc: conv3DBackpropInput as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Cos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_UNARY, unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst COS = CHECK_NAN_SNIPPET_UNARY + `\n return cos(x);\n`;\n\nexport const cos = unaryKernelFunc({opSnippet: COS});\n\nexport const cosConfig: KernelConfig = {\n kernelName: Cos,\n backendName: 'webgl',\n kernelFunc: cos,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Cosh, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst COSH = `\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n`;\n\nexport const cosh = unaryKernelFunc({opSnippet: COSH});\n\nexport const coshConfig: KernelConfig = {\n kernelName: Cosh,\n backendName: 'webgl',\n kernelFunc: cosh,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class CropAndResizeProgram implements GPGPUProgram {\n variableNames = ['Image', 'Boxes', 'BoxInd'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n imageShape: [number, number, number, number], boxShape: [number, number],\n cropSize: [number, number], method: 'bilinear'|'nearest',\n extrapolationValue: number) {\n const [batch, imageHeight, imageWidth, depth] = imageShape;\n const [numBoxes, ] = boxShape;\n const [cropHeight, cropWidth] = cropSize;\n this.outputShape = [numBoxes, cropHeight, cropWidth, depth];\n const methodId = method === 'bilinear' ? 1 : 0;\n\n const [inputHeightFloat, inputWidthFloat] =\n [`${imageHeight - 1}.0`, `${imageWidth - 1}.0`];\n\n const [heightRatio, heightScale, inY] = cropHeight > 1 ?\n [\n `${(imageHeight - 1) / (cropHeight - 1)}`,\n '(y2-y1) * height_ratio',\n `y1*${inputHeightFloat} + float(y)*(height_scale)`,\n ] :\n [\n '0.0',\n '0.0',\n `0.5 * (y1+y2) * ${inputHeightFloat}`,\n ];\n const [widthRatio, widthScale, inX] = cropWidth > 1 ?\n [\n `${(imageWidth - 1) / (cropWidth - 1)}`,\n '(x2-x1) * width_ratio',\n `x1*${inputWidthFloat} + float(x)*(width_scale)`,\n ] :\n [\n '0.0',\n '0.0',\n `0.5 * (x1+x2) * ${inputWidthFloat}`,\n ];\n\n // Reference implementation\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/crop_and_resize_op_gpu.cu.cc\n this.userCode = `\n const float height_ratio = float(${heightRatio});\n const float width_ratio = float(${widthRatio});\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 >= ${batch}) {\n return;\n }\n\n float height_scale = ${heightScale};\n float width_scale = ${widthScale};\n\n float in_y = ${inY};\n if( in_y < 0.0 || in_y > ${inputHeightFloat} ) {\n setOutput(float(${extrapolationValue}));\n return;\n }\n float in_x = ${inX};\n if( in_x < 0.0 || in_x > ${inputWidthFloat} ) {\n setOutput(float(${extrapolationValue}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${methodId} == 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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {CropAndResize, CropAndResizeAttrs, CropAndResizeInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CropAndResizeProgram} from '../crop_and_resize_gpu';\n\nexport const cropAndResize = (args: {\n inputs: CropAndResizeInputs,\n backend: MathBackendWebGL,\n attrs: CropAndResizeAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {image, boxes, boxInd} = inputs;\n const {cropSize, method, extrapolationValue} = attrs;\n\n const program = new CropAndResizeProgram(\n image.shape as [number, number, number, number],\n boxes.shape as [number, number], cropSize, method, extrapolationValue);\n return backend.runWebGLProgram(program, [image, boxes, boxInd], 'float32');\n};\n\nexport const cropAndResizeConfig: KernelConfig = {\n kernelName: CropAndResize,\n backendName: 'webgl',\n kernelFunc: cropAndResize as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class CumSumProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n // Caching uniform location for speed.\n index: WebGLUniformLocation;\n\n constructor(shape: number[], exclusive: boolean, reverse: boolean) {\n this.outputShape = shape;\n const rank = shape.length;\n const val = exclusive ? '0.0' : `getX(${getCoords(rank, 'coords')})`;\n const length = shape[shape.length - 1];\n let condition = '';\n let idxString = '';\n // When exclusive is set, the cumsum op becomes roll op that copies the\n // value from the previous index based on the direction specified by the\n // reverse flag.\n if (exclusive) {\n condition = reverse ? `end != ${length - 1}` : 'end != 0';\n idxString = reverse ? 'end + 1' : 'end - 1';\n } else {\n condition = reverse ? `end + pow2 < ${length}` : 'end >= pow2';\n idxString = (reverse ? 'end + pow2' : 'end - pow2');\n }\n\n this.userCode = `\n uniform float index;\n void main() {\n ${getCoordsDataType(rank)} coords = getOutputCoords();\n int end = ${getFinalCoord(rank, 'coords')};\n float val = ${val};\n int pow2 = int(pow(2.0, index));\n if (${condition}) {\n int idx = ${idxString};\n ${getFinalCoord(rank, 'coords')} = idx;\n val += getX(${getCoords(rank, 'coords')});\n }\n setOutput(val);\n }\n `;\n }\n\n getCustomSetupFunc(index: number) {\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.index == null) {\n this.index = gpgpu.getUniformLocation(webGLProgram, 'index');\n }\n gpgpu.gl.uniform1f(this.index, index);\n };\n }\n}\n\nfunction getCoords(rank: number, name: string): string {\n if (rank === 1) {\n return `${name}`;\n } else if (rank === 2) {\n return `${name}.x, ${name}.y`;\n } else if (rank === 3) {\n return `${name}.x, ${name}.y, ${name}.z`;\n } else if (rank === 4) {\n return `${name}.x, ${name}.y, ${name}.z, ${name}.w`;\n } else {\n throw Error(`Cumulative sum for rank ${rank} is not yet supported`);\n }\n}\n\nfunction getFinalCoord(rank: number, name: string): string {\n if (rank === 1) {\n return `${name}`;\n } else if (rank === 2) {\n return `${name}.y`;\n } else if (rank === 3) {\n return `${name}.z`;\n } else if (rank === 4) {\n return `${name}.w`;\n } else {\n throw Error(`Cumulative sum for rank ${rank} is not yet supported`);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Cumsum, CumsumAttrs, CumsumInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CumSumProgram} from '../cumsum_gpu';\n\nimport {identity} from './Identity';\nimport {transpose} from './Transpose';\n\nexport function cumsum(\n args:\n {inputs: CumsumInputs, backend: MathBackendWebGL, attrs: CumsumAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, exclusive, reverse} = attrs;\n\n const xRank = x.shape.length;\n const permutation = backend_util.getAxesPermutation([axis], xRank);\n let permutedX = x;\n if (permutation != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n }\n const permutedAxis = backend_util.getInnerMostAxes(1, xRank)[0];\n\n if (permutedAxis !== xRank - 1) {\n throw new Error(\n `WebGL cumsum shader expects an inner-most axis=${\n x.shape.length - 1} ` +\n `but got axis=${axis}`);\n }\n const size = permutedX.shape[permutedAxis];\n let result = identity({inputs: {x: permutedX}, backend});\n // Use cumsum parallel algorithm, ref:\n // https://developer.nvidia.com/gpugems/gpugems3/part-vi-gpu-computing/chapter-39-parallel-prefix-sum-scan-cuda\n\n for (let i = 0; i <= Math.ceil(Math.log2(size)) - 1; i++) {\n const program = new CumSumProgram(permutedX.shape, false, reverse);\n const customSetup = program.getCustomSetupFunc(i);\n const prevResult = result;\n result =\n backend.runWebGLProgram(program, [result], result.dtype, customSetup);\n backend.disposeIntermediateTensorInfo(prevResult);\n }\n // For exclusive cumsum, shift the end result in the direction of sum\n // and add 0 to the front index.\n if (exclusive) {\n const program = new CumSumProgram(permutedX.shape, exclusive, reverse);\n const prevResult = result;\n result = backend.runWebGLProgram(program, [result], result.dtype);\n backend.disposeIntermediateTensorInfo(prevResult);\n }\n\n if (permutation != null) {\n const reversePermutation = backend_util.getUndoAxesPermutation(permutation);\n const reverseTransposedResult = transpose(\n {inputs: {x: result}, backend, attrs: {perm: reversePermutation}});\n\n backend.disposeIntermediateTensorInfo(result);\n backend.disposeIntermediateTensorInfo(permutedX);\n\n return reverseTransposedResult;\n }\n\n return result;\n}\n\nexport const cumsumConfig: KernelConfig = {\n kernelName: Cumsum,\n backendName: 'webgl',\n kernelFunc: cumsum as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DenseBincount, DenseBincountAttrs, DenseBincountInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {bincountImplCPU, bincountReduceImplCPU} from '../kernel_utils/shared';\n\nexport function denseBincount(args: {\n inputs: DenseBincountInputs,\n backend: MathBackendWebGL,\n attrs: DenseBincountAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, weights} = inputs;\n const {size, binaryOutput} = attrs;\n\n if (x.shape.length === 1) {\n const xVals = backend.readSync(x.dataId) as TypedArray;\n const weightsVals = backend.readSync(weights.dataId) as TypedArray;\n\n const outVals =\n bincountImplCPU(xVals, weightsVals, weights.dtype, weights.shape, size);\n\n return backend.makeTensorInfo([size], weights.dtype, outVals);\n } else if (x.shape.length === 2) {\n const xBuf = backend.bufferSync(x);\n const weightsBuf = backend.bufferSync(weights);\n\n const outBuf = bincountReduceImplCPU(xBuf, weightsBuf, size, binaryOutput);\n\n return backend.makeTensorInfo(outBuf.shape, weights.dtype, outBuf.values);\n }\n\n throw new Error(\n `Error in denseBincount: input must be at most rank 2, but got rank` +\n `${x.shape.length}.`);\n}\n\nexport const denseBincountConfig: KernelConfig = {\n kernelName: DenseBincount,\n backendName: 'webgl',\n kernelFunc: denseBincount as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthToSpaceProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[] = [];\n userCode: string;\n blockSize: number;\n dataFormat: string;\n\n constructor(\n outputShape: number[], blockSize: number, dataFormat: 'NHWC'|'NCHW') {\n this.outputShape = outputShape;\n this.blockSize = blockSize;\n this.dataFormat = dataFormat;\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = ${this.getHeightCoordString()};\n int w = ${this.getWidthCoordString()};\n int d = ${this.getDepthCoordString()};\n\n int in_h = h / ${blockSize};\n int offset_h = imod(h, ${blockSize});\n int in_w = w / ${blockSize};\n int offset_w = imod(w, ${blockSize});\n int offset_d = (offset_h * ${blockSize} + offset_w) *\n ${this.getOutputDepthSize()};\n int in_d = d + offset_d;\n\n float result = ${this.getInputSamplingString()};\n setOutput(result);\n }\n `;\n }\n\n private getHeightCoordString(): string {\n if (this.dataFormat === 'NHWC') {\n return `coords[1]`;\n } else {\n return `coords[2]`;\n }\n }\n\n private getWidthCoordString(): string {\n if (this.dataFormat === 'NHWC') {\n return `coords[2]`;\n } else {\n return `coords[3]`;\n }\n }\n\n private getDepthCoordString(): string {\n if (this.dataFormat === 'NHWC') {\n return `coords[3]`;\n } else {\n return `coords[1]`;\n }\n }\n\n private getOutputDepthSize(): number {\n if (this.dataFormat === 'NHWC') {\n return this.outputShape[3];\n } else {\n return this.outputShape[1];\n }\n }\n\n private getInputSamplingString(): string {\n if (this.dataFormat === 'NHWC') {\n return `getX(b, in_h, in_w, in_d)`;\n } else {\n return `getX(b, in_d, in_h, in_w)`;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthToSpaceProgram} from '../depth_to_space_gpu';\n\nexport function depthToSpace(args: {\n inputs: DepthToSpaceInputs,\n backend: MathBackendWebGL,\n attrs: DepthToSpaceAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockSize, dataFormat} = attrs;\n\n util.assert(\n blockSize > 1,\n () => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);\n\n const batchSize = x.shape[0];\n const inputHeight = (dataFormat === 'NHWC') ? x.shape[1] : x.shape[2];\n const inputWidth = (dataFormat === 'NHWC') ? x.shape[2] : x.shape[3];\n const inputDepth = (dataFormat === 'NHWC') ? x.shape[3] : x.shape[1];\n\n const outputHeight = inputHeight * blockSize;\n const outputWidth = inputWidth * blockSize;\n const outputDepth = inputDepth / (blockSize * blockSize);\n\n const outputShape = (dataFormat === 'NHWC') ?\n [batchSize, outputHeight, outputWidth, outputDepth] :\n [batchSize, outputDepth, outputHeight, outputWidth];\n\n const program = new DepthToSpaceProgram(outputShape, blockSize, dataFormat);\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const depthToSpaceConfig: KernelConfig = {\n kernelName: DepthToSpace,\n backendName: 'webgl',\n kernelFunc: depthToSpace as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthwiseConv2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, addBias = false,\n activation: string = null, hasPreluActivation = false,\n hasLeakyReluAlpha = false) {\n this.outputShape = convInfo.outShape;\n\n const xNumRows = convInfo.inHeight;\n const xNumCols = convInfo.inWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n\n let activationSnippet = '', applyActivationSnippet = '';\n if (activation) {\n if (hasPreluActivation) {\n activationSnippet = `float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${activation}\n }`;\n } else if (hasLeakyReluAlpha) {\n activationSnippet = `float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${activation}\n }`;\n } else {\n activationSnippet = `\n float activation(float x) {\n ${activation}\n }\n `;\n }\n\n applyActivationSnippet = `result = activation(result);`;\n }\n\n const addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';\n if (addBias) {\n this.variableNames.push('bias');\n }\n\n if (hasPreluActivation) {\n this.variableNames.push('preluActivationWeights');\n }\n if (hasLeakyReluAlpha) {\n this.variableNames.push('leakyreluAlpha');\n }\n\n this.userCode = `\n ${activationSnippet}\n\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\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 / ${channelMul};\n int q = d2 - d1 * ${channelMul};\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 < ${filterHeight}; wR++) {\n int xR = xRCorner + wR * ${dilationHeight};\n\n if (xR < 0 || xR >= ${xNumRows}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n if (xC < 0 || xC >= ${xNumCols}) {\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 ${addBiasSnippet}\n ${applyActivationSnippet}\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthwiseConvPacked2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, addBias = false,\n activation: string = null, hasPreluActivation = false,\n hasLeakyReluAlpha = false) {\n this.outputShape = convInfo.outShape;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n const xNumRows = convInfo.inHeight;\n const xNumCols = convInfo.inWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const texelsAcross = filterWidth;\n\n let mainLoop = `\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;`;\n\n for (let c = 0; c < filterWidth; c++) {\n mainLoop += `\n vec4 xTexelC${c * 2};\n int xTexelC${c * 2}Ready;\n vec4 xC${c};`;\n }\n\n /**\n * This vectorized implementation works by gathering the values needed for\n * each output channel's dot product into vec4's and then multiplying them\n * all together (this happens in the final double for-loop below). Most of\n * the main loop consists of constructing these vec4's with the minimum\n * number of texture2D calls, which means making use of all four returned\n * values from a texture2D call at once.\n */\n for (let r = 0; r < filterHeight; r++) {\n for (let c = 0; c < filterWidth; c++) {\n mainLoop += `\n xTexelC${c * 2} = vec4(0.0);\n xTexelC${c * 2}Ready = 0;\n xC${c} = vec4(0.0);`;\n }\n mainLoop += `\n xR = xRCorner + ${r * dilationHeight};\n if (xR >=0 && xR < ${xNumRows}) {\n `;\n\n for (let texelC = 0; texelC < (texelsAcross + 1) / 2; texelC++) {\n const colIndex = texelC * 2;\n const c = colIndex * dilationWidth;\n\n mainLoop += `\n xC = xCCorner + ${c};\n `;\n\n if (strideWidth === 1) {\n if (colIndex < filterWidth) {\n // If padding is odd, the outer texels have to be composed.\n if (padLeft % 2 === 1) {\n // TODO: Ensure vec4 previous does not result in redundant sample,\n // and avoid setting xTexelRC's that exceed the boundary in the\n // first place rather than resetting them to vec4(0)).\n\n // To compute xCOffset:\n // - If padding is odd, we must add 1 to ensure we ask for an\n // even-numbered row.\n // - We subtract 2 to access the previous texel.\n\n mainLoop += `\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n c}Ready == 0) {\n xTexelC${c} = 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 >= ${xNumCols}) {\n xTexelC${c}.zw = vec2(0.0);\n }\n xTexelC${c}Ready = 1;\n }\n `;\n // This texel has been read in previous iteration if the dilation\n // is 1.\n if (dilationWidth === 1 && c > 0) {\n mainLoop += `\n xC${colIndex} = vec4(xTexelC${c - 2}.zw, xTexelC${c}.xy);\n `;\n } else {\n mainLoop += `\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < ${xNumCols}) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= ${xNumCols}) {\n previous.zw = vec2(0.0);\n }\n\n xC${colIndex} = vec4(previous.zw, xTexelC${c}.xy);\n } else {\n xC${colIndex} = vec4(0.0, 0.0, xTexelC${c}.xy);\n }\n `;\n }\n } else {\n // Padding is even, so xRC corresponds to a single texel.\n mainLoop += `\n if (xC >= 0 && xC < ${xNumCols} && xTexelC${c}Ready == 0) {\n xTexelC${c} = getX(batch, xR, xC, d1);\n if (xC + 1 >= ${xNumCols}) {\n xTexelC${c}.zw = vec2(0.0);\n }\n xTexelC${c}Ready = 1;\n }\n\n xC${colIndex} = xTexelC${c};\n `;\n }\n\n if (c + 1 < filterWidth) {\n // If dilation is even, the second entry should match the first\n // (either both are composed or both are single samples). But if\n // dilation is odd, then the second entry should be the opposite\n // of the first (if the first is composed, the second is a single\n // sample, and vice versa.)\n\n const nextTexelOffset = padLeft % 2 === 0 ?\n util.nearestLargerEven(dilationWidth) :\n dilationWidth;\n\n if ((dilationWidth % 2 === 0 && padLeft % 2 === 1) ||\n (dilationWidth % 2 !== 0 && padLeft % 2 !== 1)) {\n mainLoop += `\n xCOffset = xC + ${padLeft % 2} + ${nextTexelOffset};\n\n if (xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n c + 2}Ready == 0) {\n xTexelC${c + 2} = 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 >= ${xNumCols}) {\n xTexelC${c + 2}.zw = vec2(0.0);\n }\n xTexelC${c + 2}Ready = 1;\n }\n `;\n\n // If dilation > 1 then the xRC's will not be able to share any\n // values, so each xRC will require two unique calls to getX.\n if (dilationWidth > 1) {\n mainLoop += `\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n c}Ready == 0) {\n xTexelC${c} = getX(batch, xR, xCOffset, d1);\n xTexelC${c}Ready = 1;\n }\n `;\n }\n\n mainLoop += `\n xC${colIndex + 1} = vec4(xTexelC${c}.zw, xTexelC${c + 2}.xy);\n `;\n } else {\n // If dilation is 1 and padding is odd, we have already read the\n // texel when constructing the previous x value. Here we can\n // simply skip the texture read.\n if (nextTexelOffset === 1) {\n mainLoop += `\n xC${colIndex + 1} = xTexelC${c};\n `;\n } else {\n mainLoop += `\n xCOffset = xC + ${nextTexelOffset};\n\n if (xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n c + 2}Ready == 0) {\n xTexelC${c + 2} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= ${xNumCols}) {\n xTexelC${c + 2}.zw = vec2(0.0);\n }\n xTexelC${c + 2}Ready = 1;\n }\n\n xC${colIndex + 1} = xTexelC${c + 2};\n `;\n }\n }\n }\n }\n } else { // stride === 2\n if (c < filterWidth) {\n // Depending on whether padLeft is even or odd, we want either the\n // xy or zw channels from X texels for xC${colIndex}. If padLeft is\n // even, xC${colIndex +1} is simply the zw channels of texels we've\n // already sampled. But if padLeft is odd, xC{$c + 1}.zw will\n // need to come from the xy channels of a new texel, hence the `\n // vec4\n // final` initialized below.\n if (padLeft % 2 === 1) {\n mainLoop += `\n xCOffset = xC + 1 - ${strideWidth};\n if(xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n c}Ready == 0) {\n xTexelC${c} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= ${xNumCols}) {\n xTexelC${c}.zw = vec2(0.0);\n }\n xTexelC${c}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < ${xNumCols} && xTexelC${\n c + 2}Ready == 0) {\n xTexelC${c + 2} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= ${xNumCols}) {\n xTexelC${c + 2}.zw = vec2(0.0);\n }\n xTexelC${c + 2}Ready = 1;\n }\n\n xC${colIndex} = vec4(xTexelC${c}.zw, xTexelC${c + 2}.zw);\n `;\n\n if (c + 1 < filterWidth) {\n mainLoop += `\n final = vec4(0.0);\n xCOffset = xC + 1 + ${strideWidth};\n if(xCOffset >= 0 && xCOffset < ${xNumCols}) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${colIndex + 1} = vec4(xTexelC${c + 2}.xy, final.xy);\n `;\n }\n } else {\n mainLoop += `\n if(xC >= 0 && xC < ${xNumCols} && xTexelC${c}Ready == 0) {\n xTexelC${c} = getX(batch, xR, xC, d1);\n if (xC + 1 >= ${xNumCols}) {\n xTexelC${c}.zw = vec2(0.0);\n }\n xTexelC${c}Ready = 1;\n }\n\n xCOffset = xC + ${strideWidth};\n if(xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n c + 2}Ready == 0) {\n xTexelC${c + 2} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= ${xNumCols}) {\n xTexelC${c + 2}.zw = vec2(0.);\n }\n xTexelC${c + 2}Ready = 1;\n }\n\n xC${colIndex} = vec4(\n xTexelC${c}.xy, xTexelC${c + 2}.xy);\n `;\n\n if (c + 1 < filterWidth) {\n mainLoop += `\n xC${colIndex + 1} = vec4(xTexelC${c}.zw, xTexelC${c + 2}.zw);\n `;\n }\n }\n }\n }\n\n // localize the dotProd accumulation within the loop, the theory is for\n // GPU with limited cache, accumulate sum across large amount of\n // veriables will cause lots of cache misses. (i.e. 5x5 filter will have\n // 50 variables)\n if (colIndex < filterWidth) {\n mainLoop += `\n wTexel = getW(${r}, ${c}, d1, q);\n dotProd += xC${colIndex} * vec4(wTexel.xz, wTexel.xz);\n `;\n\n if (c + 1 < filterWidth) {\n mainLoop += `\n wTexel = getW(${r}, ${c + 1}, d1, q);\n dotProd += xC${colIndex + 1} * vec4(wTexel.xz, wTexel.xz);\n `;\n }\n }\n }\n mainLoop += `\n }\n `;\n }\n\n let activationSnippet = '', applyActivationSnippet = '';\n if (activation) {\n if (hasPreluActivation) {\n activationSnippet = `vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${activation}\n }`;\n } else if (hasLeakyReluAlpha) {\n activationSnippet = `vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${activation}\n }`;\n } else {\n activationSnippet = `vec4 activation(vec4 x) {\n ${activation}\n }`;\n }\n\n applyActivationSnippet = `result = activation(result);`;\n }\n\n const addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';\n if (addBias) {\n this.variableNames.push('bias');\n }\n\n if (hasPreluActivation) {\n this.variableNames.push('preluActivationWeights');\n }\n if (hasLeakyReluAlpha) {\n this.variableNames.push('leakyreluAlpha');\n }\n\n this.userCode = `\n ${activationSnippet}\n\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n\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 / ${channelMul};\n int q = d2 - d1 * ${channelMul};\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${mainLoop}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${addBiasSnippet}\n ${applyActivationSnippet}\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs, env, KernelConfig, KernelFunc, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DProgram} from '../conv_gpu_depthwise';\nimport {DepthwiseConvPacked2DProgram} from '../conv_packed_gpu_depthwise';\n\nexport function depthwiseConv2dNative(args: {\n inputs: DepthwiseConv2dNativeInputs,\n attrs: DepthwiseConv2dNativeAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations, dimRoundingMode} = attrs;\n\n let $dilations = dilations;\n if ($dilations == null) {\n $dilations = [1, 1];\n }\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, $dilations),\n () => 'Error in depthwiseConv2d: Either strides or dilations must be ' +\n `1. Got strides ${strides} and dilations '${$dilations}'`);\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, $dilations,\n pad, dimRoundingMode, true /* depthwise */);\n\n let program: DepthwiseConv2DProgram|DepthwiseConvPacked2DProgram;\n if (env().getBool('WEBGL_PACK_DEPTHWISECONV') && convInfo.strideWidth <= 2 &&\n convInfo.outChannels / convInfo.inChannels === 1) {\n program = new DepthwiseConvPacked2DProgram(convInfo);\n } else {\n program = new DepthwiseConv2DProgram(convInfo);\n }\n\n return backend.runWebGLProgram(program, [x, filter], 'float32');\n}\n\nexport const depthwiseConv2dNativeConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNative,\n backendName: 'webgl',\n kernelFunc: depthwiseConv2dNative as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthwiseConv2DDerFilterProgram implements GPGPUProgram {\n variableNames = ['x', 'dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.filterShape;\n\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n\n 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 * ${channelMul} + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < ${convInfo.batchSize}; b++) {\n for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {\n int xR = wR + yR * ${strideHeight} - ${padTop};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {\n int xC = wC + yC * ${strideWidth} - ${padLeft};\n\n if (xC < 0 || xC >= ${convInfo.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 `;\n }\n}\n\nexport class DepthwiseConv2DDerInputProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\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 < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${filterWidth} - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < ${channelMul}; dm++) {\n int d2 = d1 * ${channelMul} + 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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DepthwiseConv2dNativeBackpropFilter, DepthwiseConv2dNativeBackpropFilterAttrs, DepthwiseConv2dNativeBackpropFilterInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DDerFilterProgram} from '../conv_backprop_gpu_depthwise';\n\nexport function depthwiseConv2dNativeBackpropFilter(args: {\n inputs: DepthwiseConv2dNativeBackpropFilterInputs,\n attrs: DepthwiseConv2dNativeBackpropFilterAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, dilations, pad, dimRoundingMode, filterShape} = attrs;\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n dilations, pad, dimRoundingMode, true /* depthwise */);\n\n const program = new DepthwiseConv2DDerFilterProgram(convInfo);\n return backend.runWebGLProgram(program, [x, dy], 'float32');\n}\n\nexport const depthwiseConv2dNativeBackpropFilterConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNativeBackpropFilter,\n backendName: 'webgl',\n kernelFunc: depthwiseConv2dNativeBackpropFilter as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DepthwiseConv2dNativeBackpropInput, DepthwiseConv2dNativeBackpropInputAttrs, DepthwiseConv2dNativeBackpropInputInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DDerInputProgram} from '../conv_backprop_gpu_depthwise';\n\nexport function depthwiseConv2dNativeBackpropInput(args: {\n inputs: DepthwiseConv2dNativeBackpropInputInputs,\n attrs: DepthwiseConv2dNativeBackpropInputAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {strides, dilations, pad, dimRoundingMode, inputShape} = attrs;\n\n const convInfo = backend_util.computeConv2DInfo(\n inputShape, filter.shape as [number, number, number, number], strides,\n dilations, pad, dimRoundingMode, true /* depthwise */);\n\n const program = new DepthwiseConv2DDerInputProgram(convInfo);\n return backend.runWebGLProgram(program, [dy, filter], 'float32');\n}\n\nexport const depthwiseConv2dNativeBackpropInputConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNativeBackpropInput,\n backendName: 'webgl',\n kernelFunc: depthwiseConv2dNativeBackpropInput as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DiagProgram implements GPGPUProgram {\n variableNames = ['X'];\n outputShape: number[];\n userCode: string;\n\n constructor(size: number) {\n this.outputShape = [size, size];\n 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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Diag, DiagInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DiagProgram} from '../diag_gpu';\nimport {reshape} from './Reshape';\n\nexport function diag(args: {inputs: DiagInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n const outShape = [...x.shape, ...x.shape];\n const xSize = util.sizeFromShape(x.shape);\n\n const flat = reshape({inputs: {x}, backend, attrs: {shape: [xSize]}});\n\n const program = new DiagProgram(xSize);\n const res = backend.runWebGLProgram(program, [flat], flat.dtype);\n\n const out = reshape({inputs: {x: res}, backend, attrs: {shape: outShape}});\n\n backend.disposeIntermediateTensorInfo(flat);\n backend.disposeIntermediateTensorInfo(res);\n\n return out;\n}\n\nexport const diagConfig: KernelConfig = {\n kernelName: Diag,\n backendName: 'webgl',\n kernelFunc: diag as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Dilation2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.outShape;\n\n const {\n inHeight,\n inWidth,\n padInfo,\n strideHeight,\n strideWidth,\n filterHeight,\n filterWidth,\n dilationHeight,\n dilationWidth\n } = convInfo;\n\n const {top: padTop, left: padLeft} = padInfo;\n\n this.userCode = `\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < ${filterHeight}; h++) {\n int hIn = hBeg + h * ${dilationHeight};\n\n if (hIn >= 0 && hIn < ${inHeight}) {\n for (int w = 0; w < ${filterWidth}; w++) {\n int wIn = wBeg + w * ${dilationWidth};\n\n if (wIn >= 0 && wIn < ${inWidth}) {\n float xVal = getX(batch, hIn, wIn, d1);\n float wVal = getW(h, w, d1);\n\n float val = xVal + wVal;\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n\n float result = curVal;\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Dilation2D, Dilation2DAttrs, Dilation2DInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Dilation2DProgram} from '../dilation_gpu';\nimport {reshape} from './Reshape';\n\nexport function dilation2D(args: {\n inputs: Dilation2DInputs,\n attrs: Dilation2DAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations} = attrs;\n\n const convInfo = backend_util.computeDilation2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number], strides, pad,\n 'NHWC' /* dataFormat */, dilations);\n let out: TensorInfo;\n\n const program = new Dilation2DProgram(convInfo);\n out = backend.runWebGLProgram(program, [x, filter], 'float32');\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: convInfo.outShape}});\n backend.disposeIntermediateTensorInfo(out);\n\n return outReshaped;\n}\n\nexport const dilation2DConfig: KernelConfig = {\n kernelName: Dilation2D,\n backendName: 'webgl',\n kernelFunc: dilation2D as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Einsum, EinsumAttrs, EinsumInputs, KernelConfig, KernelFunc, Tensor, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {multiply} from './Multiply';\nimport {reshape} from './Reshape';\nimport {sum} from './Sum';\nimport {transpose} from './Transpose';\n\nexport function einsum(\n args:\n {inputs: EinsumInputs, backend: MathBackendWebGL, attrs: EinsumAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {equation} = attrs;\n const tensors = inputs as Tensor[];\n\n const {allDims, summedDims, idDims} =\n backend_util.decodeEinsumEquation(equation, tensors.length);\n backend_util.checkEinsumDimSizes(allDims.length, idDims, tensors);\n const {path, steps} = backend_util.getEinsumComputePath(summedDims, idDims);\n\n const nSteps = steps.length;\n let out: TensorInfo|null = null;\n let numDimsRemaining = allDims.length;\n const tensorsToDispose: TensorInfo[] = [];\n for (let i = 0; i < nSteps; ++i) {\n for (const idTerm of steps[i]) {\n const {permutationIndices: perm, expandDims: dimsToExpand} =\n backend_util.getEinsumPermutation(numDimsRemaining, idDims[idTerm]);\n let x: TensorInfo;\n if (backend_util.isIdentityPermutation(perm)) {\n x = tensors[idTerm];\n } else {\n x = transpose({inputs: {x: tensors[idTerm]}, backend, attrs: {perm}});\n tensorsToDispose.push(x);\n }\n const targetShape: number[] = x.shape.slice();\n for (let k = 0; k < dimsToExpand.length; ++k) {\n targetShape.splice(dimsToExpand[k], 0, 1);\n }\n\n if (!util.arraysEqual(x.shape, targetShape)) {\n x = reshape({inputs: {x}, backend, attrs: {shape: targetShape}});\n tensorsToDispose.push(x);\n }\n if (out === null) {\n out = x;\n } else {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n out = multiply({inputs: {a: x, b: out}, backend}) as TensorInfo;\n tensorsToDispose.push(out);\n }\n }\n if (i < nSteps - 1) {\n if (path[i] >= 0) {\n out = sum({\n inputs: {x: out},\n backend,\n attrs: {\n axis: path[i] - (allDims.length - numDimsRemaining),\n keepDims: false\n }\n });\n tensorsToDispose.push(out);\n }\n numDimsRemaining--;\n }\n }\n\n // Clean up intermediate tensors.\n for (const tensorInfo of tensorsToDispose) {\n if (tensorInfo === out) {\n continue;\n }\n backend.disposeIntermediateTensorInfo(tensorInfo);\n }\n\n return out;\n}\n\nexport const einsumConfig: KernelConfig = {\n kernelName: Einsum,\n backendName: 'webgl',\n kernelFunc: einsum as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Elu, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst ELU = `return (x >= 0.0) ? x : (exp(x) - 1.0);`;\n\nconst ELU_PACKED = `\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n`;\n\nconst elu = unaryKernelFunc({opSnippet: ELU, packedOpSnippet: ELU_PACKED});\n\nexport const eluConfig: KernelConfig = {\n kernelName: Elu,\n backendName: 'webgl',\n kernelFunc: elu as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {EluGrad, EluGradInputs, env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\n\nconst ELU_DER = `return (b >= 1.0) ? a : a * (b + 1.0);`;\nconst ELU_DER_PACKED = `\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n`;\n\nexport const eluGrad =\n (args: {inputs: EluGradInputs, backend: MathBackendWebGL}): TensorInfo => {\n const {inputs, backend} = args;\n const {dy, y} = inputs;\n\n const program = env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ?\n new BinaryOpPackedProgram(ELU_DER_PACKED, dy.shape, y.shape) :\n new BinaryOpProgram(ELU_DER, dy.shape, y.shape);\n return backend.runWebGLProgram(program, [dy, y], dy.dtype);\n };\n\nexport const eluGradConfig: KernelConfig = {\n kernelName: EluGrad,\n backendName: 'webgl',\n kernelFunc: eluGrad as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Equal, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {equalImplCPU} from '../kernel_utils/shared';\nconst PACKED_EQUAL = `\n return vec4(equal(a, b));\n`;\n\nconst EQUAL = `return float(a == b);`;\n\nexport const equal = binaryKernelFunc({\n opSnippet: EQUAL,\n packedOpSnippet: PACKED_EQUAL,\n dtype: 'bool',\n cpuKernelImpl: equalImplCPU,\n});\n\nexport const equalConfig: KernelConfig = {\n kernelName: Equal,\n backendName: 'webgl',\n kernelFunc: equal as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Erf, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst ERF = `\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 = ${backend_util.ERF_P};\n float a1 = ${backend_util.ERF_A1};\n float a2 = ${backend_util.ERF_A2};\n float a3 = ${backend_util.ERF_A3};\n float a4 = ${backend_util.ERF_A4};\n float a5 = ${backend_util.ERF_A5};\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`;\n\nexport const erf = unaryKernelFunc({opSnippet: ERF});\n\nexport const erfConfig: KernelConfig = {\n kernelName: Erf,\n backendName: 'webgl',\n kernelFunc: erf,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Exp, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {expImplCPU} from '../kernel_utils/shared';\n\nexport const EXP = `return exp(x);`;\nexport const exp = unaryKernelFunc(\n {opSnippet: EXP, packedOpSnippet: EXP, cpuKernelImpl: expImplCPU});\n\nexport const expConfig: KernelConfig = {\n kernelName: Exp,\n backendName: 'webgl',\n kernelFunc: exp as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ExpandDims, ExpandDimsAttrs, ExpandDimsInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reshape} from './Reshape';\n\nexport function expandDims(args: {\n inputs: ExpandDimsInputs,\n attrs: ExpandDimsAttrs,\n backend: MathBackendWebGL\n}): TensorInfo {\n const {inputs, attrs, backend} = args;\n const {dim} = attrs;\n const {input} = inputs;\n\n const inputRank = input.shape.length;\n const newShape = input.shape.slice();\n let $dim = dim;\n if (dim < 0) {\n // Negative value is counted from the tail of rank.\n util.assert(\n -(inputRank + 1) <= dim,\n () => `Axis must be in the interval [${- (inputRank + 1)}, ${\n inputRank}]`);\n $dim = inputRank + dim + 1;\n }\n newShape.splice($dim, 0, 1);\n\n return reshape({inputs: {x: input}, backend, attrs: {shape: newShape}});\n}\n\nexport const expandDimsConfig: KernelConfig = {\n kernelName: ExpandDims,\n backendName: 'webgl',\n kernelFunc: expandDims as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Expm1, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {expm1ImplCPU} from '../kernel_utils/shared';\n\nconst EXPM1 = `return exp(x) - 1.0;`;\n\nexport const expm1 = unaryKernelFunc(\n {opSnippet: EXPM1, packedOpSnippet: EXPM1, cpuKernelImpl: expm1ImplCPU});\n\nexport const expm1Config: KernelConfig = {\n kernelName: Expm1,\n backendName: 'webgl',\n kernelFunc: expm1 as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class FFTProgram implements GPGPUProgram {\n variableNames = ['real', 'imag'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n component: 'real'|'imag', inputShape: [number, number],\n inverse: boolean) {\n const innerDim = inputShape[1];\n this.outputShape = inputShape;\n\n const exponentMultiplierSnippet =\n inverse ? `2.0 * ${Math.PI}` : `-2.0 * ${Math.PI}`;\n const resultDenominator = inverse ? `${innerDim}.0` : '1.0';\n\n let opString: string;\n if (component === 'real') {\n opString = 'return real * expR - imag * expI;';\n } else if (component === 'imag') {\n opString = 'return real * expI + imag * expR;';\n } else {\n throw new Error(\n `FFT component must be either \"real\" or \"imag\", got ${component}.`);\n }\n\n this.userCode = `\n const float exponentMultiplier = ${exponentMultiplierSnippet};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${opString}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${innerDim});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${innerDim}; 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) / ${resultDenominator};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {FFTProgram} from '../fft_gpu';\n\nimport {complex} from './Complex';\nimport {reshape} from './Reshape';\n\nexport function fftImpl(\n x: TensorInfo, inverse: boolean, backend: MathBackendWebGL): TensorInfo {\n const xData = backend.texData.get(x.dataId);\n\n const inputSize = util.sizeFromShape(x.shape);\n // Collapse all outer dimensions to a single batch dimension.\n const innerDimensionSize = x.shape[x.shape.length - 1];\n const batch = inputSize / innerDimensionSize;\n\n const input2D = reshape(\n {inputs: {x}, backend, attrs: {shape: [batch, innerDimensionSize]}});\n\n const xShape = input2D.shape as [number, number];\n const realProgram = new FFTProgram('real', xShape, inverse);\n const imagProgram = new FFTProgram('imag', xShape, inverse);\n\n const inputs = [\n {\n dataId: xData.complexTensorInfos.real.dataId,\n dtype: xData.complexTensorInfos.real.dtype,\n shape: xShape\n },\n {\n dataId: xData.complexTensorInfos.imag.dataId,\n dtype: xData.complexTensorInfos.imag.dtype,\n shape: xShape\n }\n ];\n\n const realPart = backend.runWebGLProgram(realProgram, inputs, 'float32');\n const imagPart = backend.runWebGLProgram(imagProgram, inputs, 'float32');\n\n const complexOutput =\n complex({inputs: {real: realPart, imag: imagPart}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(imagPart);\n\n const complexOutputReshaped =\n reshape({inputs: {x: complexOutput}, backend, attrs: {shape: x.shape}});\n\n backend.disposeIntermediateTensorInfo(input2D);\n backend.disposeIntermediateTensorInfo(complexOutput);\n return complexOutputReshaped;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {FFT, FFTInputs, KernelConfig, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {fftImpl} from './FFT_impl';\n\nexport function fft(args: {inputs: FFTInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n return fftImpl(input, false /* inverse */, backend);\n}\n\nexport const fftConfig: KernelConfig = {\n kernelName: FFT,\n backendName: 'webgl',\n kernelFunc: fft\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class FillProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n valueLoc: WebGLUniformLocation;\n\n constructor(shape: number[], value: number) {\n this.variableNames = ['x'];\n this.outputShape = shape;\n\n this.userCode = `\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n `;\n }\n\n getCustomSetupFunc(value: number) {\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.valueLoc == null) {\n this.valueLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'value');\n }\n gpgpu.gl.uniform1f(this.valueLoc, value);\n };\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Fill, FillAttrs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {FillProgram} from '../fill_gpu';\n\nexport function fill(args: {backend: MathBackendWebGL, attrs: FillAttrs}):\n TensorInfo {\n const {backend, attrs} = args;\n const {shape, value} = attrs;\n let {dtype} = attrs;\n\n dtype = dtype || util.inferDtype(value);\n\n if (dtype === 'string') {\n // String type should be handled in CPU memory.\n const values = util.getArrayFromDType(dtype, util.sizeFromShape(shape));\n values.fill(value as string);\n return backend.makeTensorInfo(shape, dtype, values);\n } else {\n const program = new FillProgram(shape, value as number);\n const customSetup = program.getCustomSetupFunc(value as number);\n return backend.runWebGLProgram(program, [], dtype, customSetup);\n }\n}\n\nexport const fillConfig: KernelConfig = {\n kernelName: Fill,\n backendName: 'webgl',\n kernelFunc: fill as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class FlipLeftRightProgram implements GPGPUProgram {\n variableNames = ['Image'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(imageShape: [number, number, number, number]) {\n const imageWidth = imageShape[2];\n this.outputShape = imageShape;\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = ${imageWidth} - x;\n float outputValue;\n if(coordX >= 0 && coordX < ${imageWidth}) {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Tensor4D} from '@tensorflow/tfjs-core';\nimport {FlipLeftRight, FlipLeftRightInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {FlipLeftRightProgram} from '../flip_left_right_gpu';\n\nexport const flipLeftRightConfig: KernelConfig = {\n kernelName: FlipLeftRight,\n backendName: 'webgl',\n kernelFunc: ({inputs, backend}) => {\n const {image} = inputs as FlipLeftRightInputs;\n const webglBackend = backend as MathBackendWebGL;\n\n const program = new FlipLeftRightProgram((image as Tensor4D).shape);\n const output = webglBackend.runWebGLProgram(program, [image], image.dtype);\n return output;\n }\n};\n","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Floor, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {floorImplCPU} from '../kernel_utils/shared';\n\nconst FLOOR = `return floor(x);`;\n\nexport const floor = unaryKernelFunc(\n {opSnippet: FLOOR, packedOpSnippet: FLOOR, cpuKernelImpl: floorImplCPU});\n\nexport const floorConfig: KernelConfig = {\n kernelName: Floor,\n backendName: 'webgl',\n kernelFunc: floor,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {FloorDiv, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\n// We use native integer division to deal with floating point imprecision. Since\n// we implement floor division and glsl implements truncated division, we\n// correct for this by subtracting 1 from result when the result is negative and\n// there is a remainder.\nconst INT_DIV = `\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`;\n\nconst INT_DIV_PACKED = `\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`;\n\nexport const floorDiv = binaryKernelFunc(\n {opSnippet: INT_DIV, packedOpSnippet: INT_DIV_PACKED, dtype: 'int32'});\n\nexport const floorDivConfig: KernelConfig = {\n kernelName: FloorDiv,\n backendName: 'webgl',\n kernelFunc: floorDiv as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from '../../glsl_version';\nimport {GPGPUProgram} from '../../gpgpu_math';\n\nexport class FromPixelsProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n\n constructor(outputShape: number[]) {\n const glsl = getGlslDifferences();\n const [height, width, ] = outputShape;\n this.outputShape = outputShape;\n this.userCode = `\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${width}.0, ${height}.0);\n\n vec4 values = ${glsl.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {getGlslDifferences} from '../../glsl_version';\nimport {GPGPUProgram} from '../../gpgpu_math';\n\nexport class FromPixelsPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n packedInputs = false;\n packedOutput = true;\n\n constructor(outputShape: number[]) {\n const glsl = getGlslDifferences();\n const [height, width, ] = outputShape;\n this.outputShape = outputShape;\n this.userCode = `\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${width}.0, ${height}.0);\n vec4 values = ${glsl.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${glsl.output} = result;\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\nimport {FromPixels, FromPixelsAttrs, FromPixelsInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {TextureUsage} from '../tex_util';\n\nimport {FromPixelsProgram} from './FromPixels_utils/from_pixels_gpu';\nimport {FromPixelsPackedProgram} from './FromPixels_utils/from_pixels_packed_gpu';\n\nexport const fromPixelsConfig: KernelConfig = {\n kernelName: FromPixels,\n backendName: 'webgl',\n kernelFunc: fromPixels as {} as KernelFunc,\n};\n\nlet fromPixels2DContext: CanvasRenderingContext2D;\n\nfunction fromPixels(args: {\n inputs: FromPixelsInputs,\n backend: MathBackendWebGL,\n attrs: FromPixelsAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n let {pixels} = inputs;\n const {numChannels} = attrs;\n\n const isVideo = typeof (HTMLVideoElement) !== 'undefined' &&\n pixels instanceof HTMLVideoElement;\n const isImage = typeof (HTMLImageElement) !== 'undefined' &&\n pixels instanceof HTMLImageElement;\n const [width, height] = isVideo ?\n [\n (pixels as HTMLVideoElement).videoWidth,\n (pixels as HTMLVideoElement).videoHeight\n ] :\n [pixels.width, pixels.height];\n\n const texShape: [number, number] = [height, width];\n const outShape = [height, width, numChannels];\n\n if (isImage || isVideo) {\n if (fromPixels2DContext == null) {\n fromPixels2DContext = document.createElement('canvas').getContext('2d');\n }\n\n fromPixels2DContext.canvas.width = width;\n fromPixels2DContext.canvas.height = height;\n fromPixels2DContext.drawImage(\n pixels as HTMLVideoElement | HTMLImageElement | ImageBitmap,\n 0, 0, width, height);\n pixels = fromPixels2DContext.canvas;\n }\n\n const tempPixelHandle = backend.makeTensorInfo(texShape, 'int32');\n // This is a byte texture with pixels.\n backend.texData.get(tempPixelHandle.dataId).usage = TextureUsage.PIXELS;\n backend.gpgpu.uploadPixelDataToTexture(\n backend.getTexture(tempPixelHandle.dataId), pixels as ImageData);\n const program = env().getBool('WEBGL_PACK') ?\n new FromPixelsPackedProgram(outShape) :\n new FromPixelsProgram(outShape);\n const res = backend.runWebGLProgram(program, [tempPixelHandle], 'int32');\n backend.disposeData(tempPixelHandle.dataId);\n return res;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, env, FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DProgram} from '../conv_gpu';\nimport {mapActivationToShaderProgram} from '../kernel_utils/kernel_funcs_utils';\n\nimport {conv2dByMatMul, conv2dWithIm2Row} from './Conv2D_impl';\nimport {reshape} from './Reshape';\n\nexport function fusedConv2d(args: {\n inputs: FusedConv2DInputs,\n attrs: FusedConv2DAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n } = attrs;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, dilations, pad,\n dimRoundingMode, false /* depthwise */, $dataFormat);\n let out: TensorInfo;\n const intermediates: TensorInfo[] = [];\n\n if (convInfo.filterHeight === 1 && convInfo.filterWidth === 1 &&\n convInfo.dilationHeight === 1 && convInfo.dilationWidth === 1 &&\n convInfo.strideHeight === 1 && convInfo.strideWidth === 1 &&\n (convInfo.padInfo.type === 'SAME' || convInfo.padInfo.type === 'VALID')) {\n out = conv2dByMatMul({\n x,\n filter,\n convInfo,\n backend,\n bias,\n activation,\n preluActivationWeights,\n leakyreluAlpha\n });\n } else if (env().getBool('WEBGL_CONV_IM2COL') && x.shape[0] === 1) {\n out = conv2dWithIm2Row({\n x,\n filter,\n convInfo,\n backend,\n bias,\n activation,\n preluActivationWeights,\n leakyreluAlpha\n });\n } else {\n const hasBias = bias != null;\n const hasPreluActivationWeights = preluActivationWeights != null;\n const hasLeakyreluAlpha = activation === 'leakyrelu';\n const fusedActivation =\n activation ? mapActivationToShaderProgram(activation, false) : null;\n const program = new Conv2DProgram(\n convInfo, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n const inputs: TensorInfo[] = [x, filter];\n if (bias) {\n inputs.push(bias);\n }\n if (preluActivationWeights) {\n inputs.push(preluActivationWeights);\n }\n if (hasLeakyreluAlpha) {\n const $leakyreluAlpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(leakyreluAlpha as {} as 'float32', 'float32'));\n inputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n out = backend.runWebGLProgram(program, inputs, 'float32');\n }\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: convInfo.outShape}});\n\n intermediates.push(out);\n intermediates.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return outReshaped;\n}\n\nexport const fusedConv2DConfig: KernelConfig = {\n kernelName: FusedConv2D,\n backendName: 'webgl',\n kernelFunc: fusedConv2d as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, env, FusedDepthwiseConv2D, FusedDepthwiseConv2DAttrs, FusedDepthwiseConv2DInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DProgram} from '../conv_gpu_depthwise';\nimport {DepthwiseConvPacked2DProgram} from '../conv_packed_gpu_depthwise';\nimport {mapActivationToShaderProgram} from '../kernel_utils/kernel_funcs_utils';\n\nexport function fusedDepthwiseConv2D(args: {\n inputs: FusedDepthwiseConv2DInputs,\n attrs: FusedDepthwiseConv2DAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {strides, pad, dilations, dimRoundingMode, activation, leakyreluAlpha} =\n attrs;\n\n const intermediates: TensorInfo[] = [];\n\n let $dilations = dilations;\n if ($dilations == null) {\n $dilations = [1, 1];\n }\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, $dilations),\n () => 'Error in depthwiseConv2d: Either strides or dilations must be ' +\n `1. Got strides ${strides} and dilations '${$dilations}'`);\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, $dilations,\n pad, dimRoundingMode, true /* depthwise */);\n\n const shouldPackDepthwiseConv = env().getBool('WEBGL_PACK_DEPTHWISECONV') &&\n convInfo.strideWidth <= 2 &&\n convInfo.outChannels / convInfo.inChannels === 1;\n const fusedActivation = activation ?\n mapActivationToShaderProgram(activation, shouldPackDepthwiseConv) :\n null;\n const programInputs: TensorInfo[] = [x, filter];\n\n const hasBias = bias != null;\n const hasPreluActivationWeights = preluActivationWeights != null;\n const hasLeakyreluAlpha = activation === 'leakyrelu';\n\n if (hasBias) {\n programInputs.push(bias);\n }\n if (hasPreluActivationWeights) {\n programInputs.push(preluActivationWeights);\n }\n if (hasLeakyreluAlpha) {\n const $leakyreluAlpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(leakyreluAlpha as {} as 'float32', 'float32'));\n programInputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n\n let program: DepthwiseConv2DProgram|DepthwiseConvPacked2DProgram;\n if (shouldPackDepthwiseConv) {\n program = new DepthwiseConvPacked2DProgram(\n convInfo, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n } else {\n program = new DepthwiseConv2DProgram(\n convInfo, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n }\n\n const result = backend.runWebGLProgram(program, programInputs, 'float32');\n\n intermediates.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return result;\n}\n\nexport const fusedDepthwiseConv2DConfig: KernelConfig = {\n kernelName: FusedDepthwiseConv2D,\n backendName: 'webgl',\n kernelFunc: fusedDepthwiseConv2D as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class GatherNDProgram implements GPGPUProgram {\n variableNames = ['x', 'indices'];\n outputShape: number[];\n userCode: string;\n constructor(\n private sliceDim: number, private strides: number[], shape: number[]) {\n this.outputShape = shape;\n const stridesType = getCoordsDataType(strides.length);\n const dtype = getCoordsDataType(shape.length);\n const strideString = this.sliceDim > 1 ? 'strides[j]' : 'strides';\n this.userCode = `\n ${stridesType} strides = ${stridesType}(${this.strides});\n void main() {\n ${dtype} 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 * ${strideString};\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, GatherNd, GatherNdInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {GatherNDProgram} from '../gather_nd_gpu';\nimport {gatherNdImplCPU} from '../kernel_utils/shared';\n\nimport {reshape} from './Reshape';\n\nexport function gatherNd(\n args: {inputs: GatherNdInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {params, indices} = inputs;\n\n const indicesShape = indices.shape;\n const sliceRank = indicesShape[indicesShape.length - 1];\n const paramsSize = util.sizeFromShape(params.shape);\n\n const [resultShape, numSlices, sliceSize, strides] =\n backend_util.prepareAndValidate(params, indices);\n\n const flattenIndices = reshape(\n {inputs: {x: indices}, backend, attrs: {shape: [numSlices, sliceRank]}});\n const flattenX = reshape({\n inputs: {x: params},\n backend,\n attrs: {shape: [(util.sizeFromShape(params.shape) / sliceSize), sliceSize]}\n });\n\n if (backend.shouldExecuteOnCPU([params, indices]) ||\n params.dtype === 'string') {\n const indicesData = backend.readSync(indices.dataId) as TypedArray;\n const paramsBuf = backend.bufferSync(params);\n const outValue = gatherNdImplCPU(\n indicesData, paramsBuf, params.dtype, numSlices, sliceRank, sliceSize,\n strides, params.shape, paramsSize);\n\n return backend.makeTensorInfo(resultShape, params.dtype, outValue.values);\n }\n const program =\n new GatherNDProgram(sliceRank, strides, [numSlices, sliceSize]);\n const res = backend.runWebGLProgram(\n program, [flattenX, flattenIndices], flattenX.dtype);\n\n const reshaped =\n reshape({inputs: {x: res}, backend, attrs: {shape: resultShape}});\n\n backend.disposeIntermediateTensorInfo(flattenIndices);\n backend.disposeIntermediateTensorInfo(flattenX);\n backend.disposeIntermediateTensorInfo(res);\n\n return reshaped;\n}\n\nexport const gatherNdConfig: KernelConfig = {\n kernelName: GatherNd,\n backendName: 'webgl',\n kernelFunc: gatherNd as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class GatherProgram implements GPGPUProgram {\n variableNames = ['A', 'indices'];\n outputShape: number[];\n userCode: string;\n rank: number;\n\n constructor(aShape: number[], outputShape: number[]) {\n this.outputShape = outputShape;\n this.rank = outputShape.length;\n const dtype = getCoordsDataType(this.rank);\n const sourceCoords = getSourceCoords(aShape, 2);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n setOutput(getA(${sourceCoords}));\n }\n `;\n }\n}\n\n// The input and output are always flattened into rank 4 tensors.\nfunction getSourceCoords(aShape: number[], axis: number): string {\n const currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w'];\n\n const sourceCoords = [];\n for (let i = 0; i < aShape.length; i++) {\n if (i === 2) {\n sourceCoords.push('int(getIndices(resRC.x, resRC.z))');\n } else {\n sourceCoords.push(`${currentCoords[i]}`);\n }\n }\n return sourceCoords.join();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, GatherV2, GatherV2Attrs, GatherV2Inputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {GatherProgram} from '../gather_gpu';\nimport {gatherV2ImplCPU} from '../kernel_utils/shared';\n\nimport {reshape} from './Reshape';\n\nexport function gatherV2(args: {\n inputs: GatherV2Inputs,\n backend: MathBackendWebGL,\n attrs: GatherV2Attrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, indices} = inputs;\n const {axis, batchDims} = attrs;\n\n const parsedAxis = util.parseAxisParam(axis, x.shape)[0];\n const shapeInfo = backend_util.segment_util.collectGatherOpShapeInfo(\n x, indices, parsedAxis, batchDims);\n\n const indicesSize = util.sizeFromShape(indices.shape);\n\n const toDispose = [];\n\n const flattenX = reshape({\n inputs: {x},\n backend,\n attrs: {\n shape: [\n shapeInfo.batchSize, shapeInfo.outerSize, shapeInfo.dimSize,\n shapeInfo.sliceSize\n ]\n }\n });\n\n const flattenIndex = reshape({\n inputs: {x: indices},\n backend,\n attrs: {shape: [shapeInfo.batchSize, indicesSize / shapeInfo.batchSize]}\n });\n\n toDispose.push(flattenX);\n toDispose.push(flattenIndex);\n\n const flattenOutputShape = [\n shapeInfo.batchSize, shapeInfo.outerSize, indicesSize / shapeInfo.batchSize,\n shapeInfo.sliceSize\n ];\n\n if (backend.shouldExecuteOnCPU([x, indices]) || x.dtype === 'string') {\n const indicesBuf = backend.bufferSync(flattenIndex);\n const xBuf = backend.bufferSync(flattenX);\n const outBuf = gatherV2ImplCPU(xBuf, indicesBuf, flattenOutputShape);\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return backend.makeTensorInfo(\n shapeInfo.outputShape, outBuf.dtype, outBuf.values as TypedArray);\n }\n\n const program = new GatherProgram(flattenX.shape, flattenOutputShape);\n const res = backend.runWebGLProgram(\n program, [flattenX, flattenIndex], flattenX.dtype);\n toDispose.push(res);\n\n const reshaped = reshape(\n {inputs: {x: res}, backend, attrs: {shape: shapeInfo.outputShape}});\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n return reshaped;\n}\n\nexport const gatherV2Config: KernelConfig = {\n kernelName: GatherV2,\n backendName: 'webgl',\n kernelFunc: gatherV2 as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Greater, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {greaterImplCPU} from '../kernel_utils/shared';\n\nconst GREATER = `return float(a > b);`;\nconst GREATER_PACKED = `\n return vec4(greaterThan(a, b));\n`;\n\nexport const greater = binaryKernelFunc({\n opSnippet: GREATER,\n packedOpSnippet: GREATER_PACKED,\n cpuKernelImpl: greaterImplCPU,\n dtype: 'bool'\n});\n\nexport const greaterConfig: KernelConfig = {\n kernelName: Greater,\n backendName: 'webgl',\n kernelFunc: greater as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GreaterEqual, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {greaterEqualImplCPU} from '../kernel_utils/shared';\n\nconst GREATER_EQUAL = `return float(a >= b);`;\nconst GREATER_EQUAL_PACKED = `\n return vec4(greaterThanEqual(a, b));\n`;\n\nexport const greaterEqual = binaryKernelFunc({\n opSnippet: GREATER_EQUAL,\n packedOpSnippet: GREATER_EQUAL_PACKED,\n dtype: 'bool',\n cpuKernelImpl: greaterEqualImplCPU\n});\n\nexport const greaterEqualConfig: KernelConfig = {\n kernelName: GreaterEqual,\n backendName: 'webgl',\n kernelFunc: greaterEqual as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IFFT, IFFTInputs, KernelConfig, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {fftImpl} from './FFT_impl';\n\nexport function ifft(args: {inputs: IFFTInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n return fftImpl(input, true /* inverse */, backend);\n}\n\nexport const ifftConfig: KernelConfig = {\n kernelName: IFFT,\n backendName: 'webgl',\n kernelFunc: ifft\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IsFinite, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst IS_FINITE = `return float(!isnan(x) && !isinf(x));`;\n\nexport const isFinite = unaryKernelFunc({opSnippet: IS_FINITE, dtype: 'bool'});\n\nexport const isFiniteConfig: KernelConfig = {\n kernelName: IsFinite,\n backendName: 'webgl',\n kernelFunc: isFinite,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IsInf, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst IS_INF = `return float(isinf(x));`;\n\nexport const isInf = unaryKernelFunc({opSnippet: IS_INF, dtype: 'bool'});\n\nexport const isInfConfig: KernelConfig = {\n kernelName: IsInf,\n backendName: 'webgl',\n kernelFunc: isInf,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IsNan, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst IS_NAN = `return float(isnan(x));`;\n\nexport const isNaN = unaryKernelFunc({opSnippet: IS_NAN, dtype: 'bool'});\n\nexport const isNaNConfig: KernelConfig = {\n kernelName: IsNan,\n backendName: 'webgl',\n kernelFunc: isNaN,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Less} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {lessImplCPU} from '../kernel_utils/shared';\n\nconst LESS = `return float(a < b);`;\nconst LESS_PACKED = `\n return vec4(lessThan(a, b));\n`;\n\nexport const less = binaryKernelFunc({\n opSnippet: LESS,\n packedOpSnippet: LESS_PACKED,\n cpuKernelImpl: lessImplCPU,\n dtype: 'bool'\n});\n\nexport const lessConfig: KernelConfig = {\n kernelName: Less,\n backendName: 'webgl',\n kernelFunc: less as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LessEqual} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {lessEqualImplCPU} from '../kernel_utils/shared';\n\nexport const LESS_EQUAL = `return float(a <= b);`;\nexport const LESS_EQUAL_PACKED = `\n return vec4(lessThanEqual(a, b));\n`;\n\nexport const lessEqual = binaryKernelFunc({\n opSnippet: LESS_EQUAL,\n packedOpSnippet: LESS_EQUAL_PACKED,\n cpuKernelImpl: lessEqualImplCPU,\n dtype: 'bool'\n});\n\nexport const lessEqualConfig: KernelConfig = {\n kernelName: LessEqual,\n backendName: 'webgl',\n kernelFunc: lessEqual as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LinSpace, LinSpaceAttrs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {linSpaceImplCPU} from '../kernel_utils/shared';\n\nexport function linSpace(\n args: {backend: MathBackendWebGL, attrs: LinSpaceAttrs}): TensorInfo {\n const {backend, attrs} = args;\n const {start, stop, num} = attrs;\n\n // TODO: Use CPU implementation due to the precision problem in Safari.\n const outVals = linSpaceImplCPU(start, stop, num);\n return backend.makeTensorInfo([outVals.length], 'float32', outVals);\n}\n\nexport const linSpaceConfig: KernelConfig = {\n kernelName: LinSpace,\n backendName: 'webgl',\n kernelFunc: linSpace as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Log} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {logImplCPU} from '../kernel_utils/shared';\n\nconst LOG = `if (x < 0.0) return NAN;\n return log(x);`;\n\nconst LOG_PACKED = `\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`;\n\nexport const log = unaryKernelFunc(\n {opSnippet: LOG, packedOpSnippet: LOG_PACKED, cpuKernelImpl: logImplCPU});\n\nexport const logConfig: KernelConfig = {\n kernelName: Log,\n backendName: 'webgl',\n kernelFunc: log as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Log1p} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst LOG1P = `return log(1.0 + x);`;\n\nexport const log1p = unaryKernelFunc({opSnippet: LOG1P});\n\nexport const log1pConfig: KernelConfig = {\n kernelName: Log1p,\n backendName: 'webgl',\n kernelFunc: log1p,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LogicalAnd} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst LOGICAL_AND = `return float(a >= 1.0 && b >= 1.0);`;\nconst LOGICAL_AND_PACKED = `\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n`;\n\nexport const logicalAnd = binaryKernelFunc({\n opSnippet: LOGICAL_AND,\n packedOpSnippet: LOGICAL_AND_PACKED,\n dtype: 'bool'\n});\n\nexport const logicalAndConfig: KernelConfig = {\n kernelName: LogicalAnd,\n backendName: 'webgl',\n kernelFunc: logicalAnd as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, LogicalNot} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst LOGICAL_NOT = `return float(!(x >= 1.0));`;\n\nexport const logicalNot = unaryKernelFunc({opSnippet: LOGICAL_NOT});\n\nexport const logicalNotConfig: KernelConfig = {\n kernelName: LogicalNot,\n backendName: 'webgl',\n kernelFunc: logicalNot,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LogicalOr} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst LOGICAL_OR = `return float(a >= 1.0 || b >= 1.0);`;\nconst LOGICAL_OR_PACKED = `\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n`;\n\nexport const logicalOr = binaryKernelFunc(\n {opSnippet: LOGICAL_OR, packedOpSnippet: LOGICAL_OR_PACKED, dtype: 'bool'});\n\nexport const logicalOrConfig: KernelConfig = {\n kernelName: LogicalOr,\n backendName: 'webgl',\n kernelFunc: logicalOr as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class LRNProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n xShape: number[], radius: number, bias: number, alpha: number,\n beta: number) {\n const rad = radius;\n const maxD = xShape[3] - 1;\n this.outputShape = xShape;\n\n // optimize pow(bias + alpha * sum, -beta)\n // src: https://github.com/tensorflow/tensorflow/..\n // blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..\n // tensorflow/core/kernels/mkl_lrn_op.cc#L320\n let powOperator;\n const basis = `float(${bias}) + float(${alpha}) * sum`;\n if (beta === 0.5) {\n powOperator = `inversesqrt(${basis})`;\n } else if (beta === 1.0) {\n powOperator = `1.0/(${basis})`;\n } else {\n powOperator = `exp(log(${basis}) * float(-${beta}));`;\n }\n\n 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 = -${rad}; j <= ${rad}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${maxD}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${powOperator};\n setOutput(val);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class LRNPackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[] = [];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n xShape: number[], radius: number, bias: number, alpha: number,\n beta: number) {\n const rad = radius;\n const maxD = xShape[3] - 1;\n this.outputShape = xShape;\n\n // optimize pow(bias + alpha * sum, -beta)\n // src: https://github.com/tensorflow/tensorflow/..\n // blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..\n // tensorflow/core/kernels/mkl_lrn_op.cc#L320\n let powOperator;\n const basis = `float(${bias}) + float(${alpha}) * sum`;\n if (beta === 0.5) {\n powOperator = `inversesqrt(${basis})`;\n } else if (beta === 1.0) {\n powOperator = `1.0/(${basis})`;\n } else {\n powOperator = `exp(log(${basis}) * float(-${beta}));`;\n }\n\n 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 - ${rad};\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 = - ${rad}; j <= ${rad}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${maxD}));\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 * ${powOperator};\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, LRN, LRNAttrs, LRNInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {LRNProgram} from '../lrn_gpu';\nimport {LRNPackedProgram} from '../lrn_packed_gpu';\n\nexport const lrn =\n (args: {inputs: LRNInputs, backend: MathBackendWebGL, attrs: LRNAttrs}):\n TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n const program = env().getBool('WEBGL_PACK_NORMALIZATION') ?\n new LRNPackedProgram(x.shape, depthRadius, bias, alpha, beta) :\n new LRNProgram(x.shape, depthRadius, bias, alpha, beta);\n return backend.runWebGLProgram(program, [x], x.dtype);\n };\n\n// tslint:disable-next-line: variable-name\nexport const LRNConfig: KernelConfig = {\n kernelName: LRN,\n backendName: 'webgl',\n kernelFunc: lrn as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class LRNGradProgram implements GPGPUProgram {\n variableNames = ['inputImage', 'outputImage', 'dy'];\n outputShape: number[] = [];\n userCode: string;\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n depth: number;\n\n constructor(\n inputShape: number[], depthRadius: number, bias: number, alpha: number,\n beta: number) {\n this.outputShape = inputShape;\n this.depth = inputShape[3];\n this.depthRadius = depthRadius;\n this.bias = bias;\n this.alpha = alpha;\n this.beta = beta;\n 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 - ${depthRadius})));\n int depthEnd = int(min(float(${this.depth}),\n float(d + ${depthRadius} + 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(${alpha}) * norm + float(${bias});\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(${alpha})\n * float(${beta})\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${beta});\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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, LRNGrad, LRNGradAttrs, LRNGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {LRNGradProgram} from '../lrn_grad_gpu';\n\nexport const lrnGrad = (args: {\n inputs: LRNGradInputs,\n backend: MathBackendWebGL,\n attrs: LRNGradAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x, y, dy} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n const program = new LRNGradProgram(x.shape, depthRadius, bias, alpha, beta);\n return backend.runWebGLProgram(program, [x, y, dy], x.dtype);\n};\n\n// tslint:disable-next-line: variable-name\nexport const LRNGradConfig: KernelConfig = {\n kernelName: LRNGrad,\n backendName: 'webgl',\n kernelFunc: lrnGrad as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from '../kernels/Reshape';\n\nexport function maxImpl(\n x: TensorInfo, reduceShape: number[], outShape: number[],\n backend: MathBackendWebGL): TensorInfo {\n const inSize = util.sizeFromShape(reduceShape);\n const xSize = util.sizeFromShape(x.shape);\n const batchSize = xSize / inSize;\n const reshapedInput =\n reshape({inputs: {x}, attrs: {shape: [batchSize, inSize]}, backend});\n\n const reduced = reduce(reshapedInput, x.dtype, 'max', backend);\n const reshapedOutput =\n reshape({inputs: {x: reduced}, attrs: {shape: outShape}, backend});\n\n backend.disposeIntermediateTensorInfo(reshapedInput);\n backend.disposeIntermediateTensorInfo(reduced);\n\n return reshapedOutput;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelFunc, Max, MaxAttrs, MaxInputs, TensorInfo} from '@tensorflow/tfjs-core';\nimport {backend_util, KernelConfig, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {maxImplCPU} from '../kernel_utils/shared';\n\nimport {maxImpl} from './Max_impl';\nimport {transposeImpl, transposeImplCPU} from './Transpose_impl';\n\nexport function max(\n args: {inputs: MaxInputs, backend: MathBackendWebGL, attrs: MaxAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {reductionIndices, keepDims} = attrs;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(reductionIndices, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n const maxInputIsTransposed = permutedAxes != null;\n const shouldExecuteOnCPU = backend.shouldExecuteOnCPU([x]);\n\n let maxInput = x;\n if (maxInputIsTransposed) {\n if (shouldExecuteOnCPU) {\n const xTexData = backend.texData.get(maxInput.dataId);\n const values = xTexData.values as TypedArray;\n\n const newShape: number[] = new Array(xRank);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = x.shape[permutedAxes[i]];\n }\n const maxInputValues =\n transposeImplCPU(values, x.shape, x.dtype, permutedAxes, newShape);\n\n maxInput = backend.makeTensorInfo(newShape, x.dtype);\n const maxInputData = backend.texData.get(maxInput.dataId);\n maxInputData.values = maxInputValues;\n } else {\n maxInput = transposeImpl(x, permutedAxes, backend);\n }\n\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('max', axes, xRank);\n const [maxOutShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(maxInput.shape, axes);\n\n let outShape = maxOutShape;\n if (keepDims) {\n // rather than reshape at the end, set the target shape here.\n outShape = backend_util.expandShapeToKeepDim(maxOutShape, origAxes);\n }\n\n let out;\n if (shouldExecuteOnCPU) {\n const xTexData = backend.texData.get(maxInput.dataId);\n const values = xTexData.values as TypedArray;\n\n const outValues =\n maxImplCPU(values, util.sizeFromShape(reduceShape), outShape, x.dtype);\n\n out = backend.makeTensorInfo(outShape, x.dtype);\n const outData = backend.texData.get(out.dataId);\n outData.values = outValues;\n } else {\n out = maxImpl(maxInput, reduceShape, outShape, backend);\n }\n\n if (maxInputIsTransposed) {\n backend.disposeIntermediateTensorInfo(maxInput);\n }\n\n return out;\n}\n\nexport const maxConfig: KernelConfig = {\n kernelName: Max,\n backendName: 'webgl',\n kernelFunc: max as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Maximum} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_gpu';\nimport {CHECK_NAN_SNIPPET as CHECK_NAN_SNIPPET_PACKED} from '../binaryop_packed_gpu';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {maximumImplCPU} from '../kernel_utils/shared';\n\nconst MAXIMUM = CHECK_NAN_SNIPPET + `\n return max(a, b);\n`;\n\nconst MAXIMUM_PACKED = `\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n ` +\n CHECK_NAN_SNIPPET_PACKED + `\n return result;\n`;\n\nexport const maximum = binaryKernelFunc({\n opSnippet: MAXIMUM,\n packedOpSnippet: MAXIMUM_PACKED,\n cpuKernelImpl: maximumImplCPU\n});\n\nexport const maximumConfig: KernelConfig = {\n kernelName: Maximum,\n backendName: 'webgl',\n kernelFunc: maximum as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {backend_util, KernelConfig, KernelFunc, MaxPool, MaxPoolAttrs, MaxPoolInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool2DProgram} from '../pool_gpu';\nimport {assertNotComplex} from '../webgl_util';\nimport {identity} from './Identity';\n\nexport function maxPool(args: {\n inputs: MaxPoolInputs,\n backend: MathBackendWebGL,\n attrs: MaxPoolAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n assertNotComplex(x, 'maxPool');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations = 1;\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&\n util.arraysEqual(convInfo.inShape, convInfo.outShape)) {\n return identity({inputs: {x}, backend});\n }\n const maxPoolProgram = new Pool2DProgram(convInfo, 'max', false);\n return backend.runWebGLProgram(maxPoolProgram, [x], x.dtype);\n}\n\nexport const maxPoolConfig: KernelConfig = {\n kernelName: MaxPool,\n backendName: 'webgl',\n kernelFunc: maxPool as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {backend_util, KernelConfig, KernelFunc, MaxPool3D, MaxPool3DAttrs, MaxPool3DInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool3DProgram} from '../pool_gpu';\n\nexport function maxPool3d(args: {\n inputs: MaxPool3DInputs,\n backend: MathBackendWebGL,\n attrs: MaxPool3DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {filterSize, strides, pad, dataFormat, dimRoundingMode} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode, dataFormat);\n const maxPoolProgram = new Pool3DProgram(convInfo, 'max', false);\n return backend.runWebGLProgram(maxPoolProgram, [x], x.dtype);\n}\n\nexport const maxPool3DConfig: KernelConfig = {\n kernelName: MaxPool3D,\n backendName: 'webgl',\n kernelFunc: maxPool3d as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class MaxPool2DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy', 'maxPos'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const lastIndex = effectiveFilterHeight * effectiveFilterWidth - 1;\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\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 < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.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 = ${lastIndex} - 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 * ${effectiveFilterWidth} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class MaxPool3DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy', 'maxPos'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.inShape;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const lastIndex =\n effectiveFilterDepth * effectiveFilterHeight * effectiveFilterWidth - 1;\n this.userCode = `\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\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 < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n float dyD = float(dyDCorner + wD) / ${strideDepth}.0;\n\n if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.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 = ${lastIndex} -\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 * ${effectiveFilterHeight} * ${effectiveFilterWidth} +\n wR * ${effectiveFilterWidth} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {backend_util, KernelConfig, KernelFunc, MaxPool3DGrad, MaxPool3DGradAttrs, MaxPool3DGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MaxPool3DBackpropProgram} from '../max_pool_backprop_gpu';\nimport {Pool3DProgram} from '../pool_gpu';\n\nexport function maxPool3DGrad(args: {\n inputs: MaxPool3DGradInputs,\n backend: MathBackendWebGL,\n attrs: MaxPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n\n const maxPool3dPositionsProgram =\n new Pool3DProgram(convInfo, 'max', true /* get positions */);\n const maxPool3dPositions =\n backend.runWebGLProgram(maxPool3dPositionsProgram, [x], x.dtype);\n const maxPoolBackpropProgram = new MaxPool3DBackpropProgram(convInfo);\n const result = backend.runWebGLProgram(\n maxPoolBackpropProgram, [dy, maxPool3dPositions], x.dtype);\n backend.disposeIntermediateTensorInfo(maxPool3dPositions);\n return result;\n}\n\nexport const maxPoolGrad3DConfig: KernelConfig = {\n kernelName: MaxPool3DGrad,\n backendName: 'webgl',\n kernelFunc: maxPool3DGrad as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {backend_util, KernelConfig, KernelFunc, MaxPoolGrad, MaxPoolGradAttrs, MaxPoolGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MaxPool2DBackpropProgram} from '../max_pool_backprop_gpu';\nimport {Pool2DProgram} from '../pool_gpu';\nimport {assertNotComplex} from '../webgl_util';\n\nexport function maxPoolGrad(args: {\n inputs: MaxPoolGradInputs,\n backend: MathBackendWebGL,\n attrs: MaxPoolGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input, output} = inputs;\n const x = input;\n assertNotComplex([input, output], 'maxPoolGrad');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad, dimRoundingMode);\n const getPositions = true;\n const maxPoolPositionsProgram =\n new Pool2DProgram(convInfo, 'max', getPositions);\n const maxPoolPositions: TensorInfo =\n backend.runWebGLProgram(maxPoolPositionsProgram, [x], x.dtype);\n\n const maxPoolBackPropProgram = new MaxPool2DBackpropProgram(convInfo);\n const result = backend.runWebGLProgram(\n maxPoolBackPropProgram, [dy, maxPoolPositions], x.dtype);\n backend.disposeIntermediateTensorInfo(maxPoolPositions);\n return result;\n}\n\nexport const maxPoolGradConfig: KernelConfig = {\n kernelName: MaxPoolGrad,\n backendName: 'webgl',\n kernelFunc: maxPoolGrad as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool2DProgram} from '../pool_gpu';\n\nexport function maxPoolWithArgmaxImpl(\n x: TensorInfo, includeBatchInIndex: boolean,\n convInfo: backend_util.Conv2DInfo,\n backend: MathBackendWebGL): TensorInfo[] {\n let program = new Pool2DProgram(convInfo, 'max', false);\n const poolOutput = backend.runWebGLProgram(program, [x], 'float32');\n\n program = new Pool2DProgram(convInfo, 'max', true, true, includeBatchInIndex);\n const indexOutput = backend.runWebGLProgram(program, [x], 'float32');\n return [poolOutput, indexOutput];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {MaxPoolWithArgmax, MaxPoolWithArgmaxAttrs, MaxPoolWithArgmaxInputs} from '@tensorflow/tfjs-core';\nimport {backend_util, KernelConfig, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {maxPoolWithArgmaxImpl} from './MaxPoolWithArgmax_impl';\n\nexport const maxPoolWithArgmaxConfig: KernelConfig = {\n kernelName: MaxPoolWithArgmax,\n backendName: 'webgl',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {x} = inputs as MaxPoolWithArgmaxInputs;\n const {filterSize, strides, pad, includeBatchInIndex} =\n attrs as {} as MaxPoolWithArgmaxAttrs;\n const webglBackend = backend as MathBackendWebGL;\n\n util.assert(\n x.shape.length === 4,\n () => `Error in maxPool: input must be rank 4 but got rank ${\n x.shape.length}.`);\n const dilations: [number, number] = [1, 1];\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad);\n\n const [result, indexes] =\n maxPoolWithArgmaxImpl(x, includeBatchInIndex, convInfo, webglBackend);\n return [result, indexes];\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from '../kernels/Reshape';\n\nexport function meanImpl(\n x: TensorInfo, reduceShape: number[], outShape: number[],\n backend: MathBackendWebGL): TensorInfo {\n const inSize = util.sizeFromShape(reduceShape);\n const xSize = util.sizeFromShape(x.shape);\n const batchSize = xSize / inSize;\n const reshapedInput =\n reshape({inputs: {x}, attrs: {shape: [batchSize, inSize]}, backend});\n\n const reduced = reduce(reshapedInput, 'float32', 'mean', backend);\n const reshapedOutput =\n reshape({inputs: {x: reduced}, attrs: {shape: outShape}, backend});\n\n backend.disposeIntermediateTensorInfo(reshapedInput);\n backend.disposeIntermediateTensorInfo(reduced);\n\n return reshapedOutput;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, Mean, MeanAttrs, MeanInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {meanImpl} from './Mean_impl';\nimport {transposeImpl, transposeImplCPU} from './Transpose_impl';\n\nexport const meanConfig: KernelConfig = {\n kernelName: Mean,\n backendName: 'webgl',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {x} = inputs as MeanInputs;\n const {keepDims, axis} = attrs as {} as MeanAttrs;\n const webglBackend = backend as MathBackendWebGL;\n\n const xRank = x.shape.length;\n const origAxes = util.parseAxisParam(axis, x.shape);\n\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n const meanInputIsTransposed = permutedAxes != null;\n const shouldExecuteOnCPU = webglBackend.shouldExecuteOnCPU([x]);\n\n const intermediates: TensorInfo[] = [];\n\n let meanInput = x;\n if (meanInputIsTransposed) {\n if (shouldExecuteOnCPU) {\n const xTexData = webglBackend.texData.get(meanInput.dataId);\n const values = xTexData.values as TypedArray;\n\n const newShape: number[] = new Array(xRank);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = x.shape[permutedAxes[i]];\n }\n const meanInputValues =\n transposeImplCPU(values, x.shape, x.dtype, permutedAxes, newShape);\n\n meanInput = webglBackend.makeTensorInfo(newShape, x.dtype);\n const meanInputData = webglBackend.texData.get(meanInput.dataId);\n meanInputData.values = meanInputValues;\n } else {\n meanInput = transposeImpl(x, permutedAxes, webglBackend);\n }\n\n intermediates.push(meanInput);\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('sum', axes, xRank);\n const [meanOutShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(meanInput.shape, axes);\n\n let outShape = meanOutShape;\n if (keepDims) {\n // rather than reshape at the end, set the target shape here.\n outShape = backend_util.expandShapeToKeepDim(meanOutShape, origAxes);\n }\n\n const out = meanImpl(meanInput, reduceShape, outShape, webglBackend);\n for (const i of intermediates) {\n webglBackend.disposeIntermediateTensorInfo(i);\n }\n\n return out;\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Min, MinAttrs, MinInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\n\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function min(\n args: {inputs: MinInputs, backend: MathBackendWebGL, attrs: MinAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let permutedX = x;\n if (permutedAxes != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('min', axes, xRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(permutedX.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n const a2D =\n reshape({inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n const reduced = reduce(a2D, a2D.dtype, 'min', backend);\n\n let res;\n if (keepDims) {\n const newShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: newShape}});\n } else {\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n }\n\n backend.disposeIntermediateTensorInfo(a2D);\n backend.disposeIntermediateTensorInfo(reduced);\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo(permutedX);\n }\n\n return res;\n}\n\nexport const minConfig: KernelConfig = {\n kernelName: Min,\n backendName: 'webgl',\n kernelFunc: min as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Minimum} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_gpu';\nimport {CHECK_NAN_SNIPPET as CHECK_NAN_SNIPPET_PACKED} from '../binaryop_packed_gpu';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {minimumImplCPU} from '../kernel_utils/shared';\n\nconst MINIMUM = CHECK_NAN_SNIPPET + `\n return min(a, b);\n`;\n\nconst MINIMUM_PACKED = `\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n ` +\n CHECK_NAN_SNIPPET_PACKED + `\n return result;\n`;\n\nexport const minimum = binaryKernelFunc({\n opSnippet: MINIMUM,\n packedOpSnippet: MINIMUM_PACKED,\n cpuKernelImpl: minimumImplCPU\n});\n\nexport const minimumConfig: KernelConfig = {\n kernelName: Minimum,\n backendName: 'webgl',\n kernelFunc: minimum as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class MirrorPadProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n mode: 'reflect'|'symmetric') {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const dtype = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const unpackedCoords =\n ['coords[0]', 'coords[1]', 'coords[2]', 'coords[3]'].slice(0, rank);\n const offset = mode === 'reflect' ? 0 : 1;\n\n if (rank === 1) {\n this.userCode = `\n int start = ${start};\n int end = ${end};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${offset};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${offset};\n }\n setOutput(getX(outC - start));\n }\n `;\n return;\n }\n this.userCode = `\n ${dtype} start = ${dtype}(${start});\n ${dtype} end = ${dtype}(${end});\n\n void main() {\n ${dtype} outC = getOutputCoords();\n for (int i = 0; i < ${rank}; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - ${offset};\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + ${offset};\n }\n }\n ${dtype} coords = outC - start;\n setOutput(getX(${unpackedCoords}));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\n/**\n * Example shader code for\n * `mirrorPad(tf.tensor1d([1, 2, 3], 'int32'), [[2, 2]], 'reflect')`\n * ```\n * const int start = int(2);\n * const int end = int(5);\n *\n * void main() {\n * int outputLoc = getOutputCoords();\n * vec4 result = vec4(0.);\n *\n * int rc = outputLoc;\n *\n * int source = rc;\n * if (source < start) {\n * source = start * 2 - source - 0;\n * } else if (source >= end) {\n * source = (end - 1) * 2 - source + 0;\n * }\n * source -= start;\n *\n * result[0] = getChannel(getX(source), source);\n * rc += 1;\n * if(rc < 6) {\n * int source = rc;\n * if (source < start) {\n * source = start * 2 - source - 0;\n * } else if (source >= end) {\n * source = (end - 1) * 2 - source + 0;\n * }\n * source -= start;\n *\n * result[1] = getChannel(getX(source), source);\n * }\n *\n * setOutput(result);\n * }\n * ```\n */\nexport class MirrorPadPackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n mode: 'reflect'|'symmetric') {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const dtype = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const coords = getChannels('rc', rank);\n const source = getChannels('source', rank);\n const cLimit = `${coords[rank - 1]} < ${this.outputShape[rank - 1]}`;\n const innerDims =\n rank === 1 ? 'source' : `vec2(${source.slice(-2).join()})`;\n const offset = mode === 'reflect' ? 0 : 1;\n\n let mainLoop = '';\n if (rank === 1) {\n const padSetup = `\n ${dtype} source = rc;\n if (source < start) {\n source = start * 2 - source - ${offset};\n } else if (source >= end) {\n source = (end - 1) * 2 - source + ${offset};\n }\n source -= start;\n `;\n mainLoop = `\n ${dtype} rc = outputLoc;\n ${padSetup}\n result[0] = getChannel(getX(${source.join()}), ${innerDims});\n ${coords[rank - 1]} += 1;\n if(${cLimit}) {\n ${padSetup}\n result[1] = getChannel(getX(${source.join()}), ${innerDims});\n }\n `;\n } else {\n const padSetup = `\n ${dtype} source = rc;\n ${dtype} lt = ${dtype}(lessThan(source, start));\n ${dtype} gte = ${dtype}(greaterThanEqual(source, end));\n ${dtype} orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - ${offset}) +\n gte * ((end - 1) * 2 - source + ${offset});\n source -= start;\n `;\n\n mainLoop = `\n ${dtype} rc = outputLoc;\n ${padSetup}\n result[0] = getChannel(getX(${source.join()}), ${innerDims});\n ${coords[rank - 1]} += 1;\n if(${cLimit}) {\n ${padSetup}\n result[1] = getChannel(getX(${source.join()}), ${innerDims});\n }\n rc = outputLoc;\n ${coords[rank - 2]} += 1;\n if(${coords[rank - 2]} < ${this.outputShape[rank - 2]}) {\n ${padSetup}\n result[2] = getChannel(getX(${source.join()}), ${innerDims});\n ${coords[rank - 1]} += 1;\n if(${cLimit}) {\n ${padSetup}\n result[3] = getChannel(getX(${source.join()}), ${innerDims});\n }\n }\n `;\n }\n\n this.userCode = `\n const ${dtype} start = ${dtype}(${start});\n const ${dtype} end = ${dtype}(${end});\n\n void main() {\n ${dtype} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${mainLoop}\n setOutput(result);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, MirrorPad, MirrorPadAttrs, MirrorPadInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MirrorPadProgram} from '../mirror_pad_gpu';\nimport {MirrorPadPackedProgram} from '../mirror_pad_packed_gpu';\n\nexport const mirrorPadKernelFunc: (params: {\n inputs: MirrorPadInputs,\n backend: MathBackendWebGL,\n attrs: MirrorPadAttrs\n}) => TensorInfo = ({inputs, backend, attrs}) => {\n const {x} = inputs;\n const {paddings, mode} = attrs;\n\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new MirrorPadPackedProgram(x.shape, paddings, mode) :\n new MirrorPadProgram(x.shape, paddings, mode);\n\n const output = backend.runWebGLProgram(program, [x], x.dtype);\n\n return output;\n};\n\nexport const mirrorPadConfig: KernelConfig = {\n kernelName: MirrorPad,\n backendName: 'webgl',\n kernelFunc: mirrorPadKernelFunc as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Mod} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_packed_gpu';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst MOD = `if (b == 0.0) return NAN;\n return mod(a, b);`;\n\nconst MOD_PACKED = `\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n ` +\n CHECK_NAN_SNIPPET + `\n return result;\n`;\n\nexport const mod = binaryKernelFunc({\n opSnippet: MOD,\n packedOpSnippet: MOD_PACKED,\n});\n\nexport const modConfig: KernelConfig = {\n kernelName: Mod,\n backendName: 'webgl',\n kernelFunc: mod as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class MultinomialProgram implements GPGPUProgram {\n variableNames = ['probs'];\n outputShape: number[];\n userCode: string;\n\n // Caching uniform location for speed.\n seedLoc: WebGLUniformLocation;\n\n constructor(batchSize: number, numOutcomes: number, numSamples: number) {\n this.outputShape = [batchSize, numSamples];\n\n 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 < ${numOutcomes - 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(${numOutcomes - 1}));\n }\n `;\n }\n\n getCustomSetupFunc(seed: number) {\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.seedLoc == null) {\n this.seedLoc = gpgpu.getUniformLocation(webGLProgram, 'seed');\n }\n gpgpu.gl.uniform1f(this.seedLoc, seed);\n };\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {RealDiv} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\n// Without the equality check div produces 0.9999 for a = b, which when\n// floored can cause errors.\nconst DIV = `\nif (a == b) {\n return 1.0;\n};\nreturn a / b;`;\n\n// We do the same as in ./binaryop_gpu, with vec4 and ivec4.\n// On Linux, the vectorized implementation produces NaNs when a and b are 0.\nconst DIV_PACKED = `\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`;\n\nexport const realDiv = binaryKernelFunc(\n {opSnippet: DIV, packedOpSnippet: DIV_PACKED, checkOutOfBounds: true});\n\nexport const realDivConfig: KernelConfig = {\n kernelName: RealDiv,\n backendName: 'webgl',\n kernelFunc: realDiv,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sub} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {subImplCPU as cpuSub} from '../kernel_utils/shared';\n\nconst SUB = 'return a - b;';\n\nexport const sub = binaryKernelFunc({\n opSnippet: SUB,\n packedOpSnippet: SUB,\n supportsComplex: true,\n cpuKernelImpl: cpuSub\n});\n\nexport const subConfig: KernelConfig = {\n kernelName: Sub,\n backendName: 'webgl',\n kernelFunc: sub\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Softmax, SoftmaxAttrs, SoftmaxInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {exp} from './Exp';\nimport {max} from './Max';\nimport {realDiv} from './RealDiv';\nimport {reshape} from './Reshape';\nimport {sub} from './Sub';\nimport {sum} from './Sum';\n\nexport function softmax(args: {\n inputs: SoftmaxInputs,\n backend: MathBackendWebGL,\n attrs: SoftmaxAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {logits} = inputs;\n const {dim} = attrs;\n\n const axes = util.parseAxisParam([dim], logits.shape);\n\n const maxLogit = max({\n inputs: {x: logits},\n backend,\n attrs: {reductionIndices: axes, keepDims: false}\n });\n\n const expandedShape = backend_util.expandShapeToKeepDim(maxLogit.shape, axes);\n\n const maxLogitsReshaped =\n reshape({inputs: {x: maxLogit}, backend, attrs: {shape: expandedShape}});\n const a =\n sub({inputs: {a: logits, b: maxLogitsReshaped}, backend}) as TensorInfo;\n const b = exp({inputs: {x: a}, backend}) as TensorInfo;\n const sumExp =\n sum({inputs: {x: b}, backend, attrs: {axis: axes, keepDims: false}});\n const sumExpReshaped =\n reshape({inputs: {x: sumExp}, backend, attrs: {shape: expandedShape}});\n\n const res =\n realDiv({inputs: {a: b, b: sumExpReshaped}, backend}) as TensorInfo;\n\n backend.disposeIntermediateTensorInfo(maxLogit);\n backend.disposeIntermediateTensorInfo(maxLogitsReshaped);\n backend.disposeIntermediateTensorInfo(a);\n backend.disposeIntermediateTensorInfo(b);\n backend.disposeIntermediateTensorInfo(sumExp);\n backend.disposeIntermediateTensorInfo(sumExpReshaped);\n\n return res;\n}\n\nexport const softmaxConfig: KernelConfig = {\n kernelName: Softmax,\n backendName: 'webgl',\n kernelFunc: softmax as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Multinomial, MultinomialAttrs, MultinomialInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MultinomialProgram} from '../multinomial_gpu';\n\nimport {softmax} from './Softmax';\n\nexport function multinomial(args: {\n inputs: MultinomialInputs,\n backend: MathBackendWebGL,\n attrs: MultinomialAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {logits} = inputs;\n const {numSamples, seed, normalized} = attrs;\n\n const probs = normalized ?\n logits :\n softmax(\n {inputs: {logits}, backend, attrs: {dim: logits.shape.length - 1}});\n const batchSize = probs.shape[0];\n const numOutcomes = probs.shape[1];\n const program = new MultinomialProgram(batchSize, numOutcomes, numSamples);\n const customSetup = program.getCustomSetupFunc(seed);\n\n const res = backend.runWebGLProgram(program, [probs], 'int32', customSetup);\n if (!normalized) {\n backend.disposeIntermediateTensorInfo(probs);\n }\n return res;\n}\n\nexport const multinomialConfig: KernelConfig = {\n kernelName: Multinomial,\n backendName: 'webgl',\n kernelFunc: multinomial as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, Neg, NegInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {negImplCPU} from '../kernel_utils/shared';\nimport {UnaryOpProgram} from '../unaryop_gpu';\nimport {UnaryOpPackedProgram} from '../unaryop_packed_gpu';\n\nconst NEG = `return -x;`;\n\n// This doesn't use unaryKernelFunc because negImplCPU is not of type\n// SimpleUnaryKernelImplCPU.\nexport function neg(args: {inputs: NegInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (backend.shouldExecuteOnCPU([x])) {\n const xData = backend.texData.get(x.dataId);\n const [outValues, newShape] =\n negImplCPU(xData.values as TypedArray, x.shape, x.dtype);\n return backend.makeTensorInfo(newShape, x.dtype, outValues);\n }\n\n let program: UnaryOpProgram|UnaryOpPackedProgram;\n if (env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {\n program = new UnaryOpPackedProgram(x.shape, NEG);\n } else {\n program = new UnaryOpProgram(x.shape, NEG);\n }\n\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const negConfig: KernelConfig = {\n kernelName: Neg,\n backendName: 'webgl',\n kernelFunc: neg as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV3, NonMaxSuppressionV3Attrs, NonMaxSuppressionV3Inputs, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV3Impl = kernel_impls.nonMaxSuppressionV3Impl;\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function nonMaxSuppressionV3(args: {\n inputs: NonMaxSuppressionV3Inputs,\n backend: MathBackendWebGL,\n attrs: NonMaxSuppressionV3Attrs\n}) {\n backend_util.warn(\n 'tf.nonMaxSuppression() in webgl locks the UI thread. ' +\n 'Call tf.nonMaxSuppressionAsync() instead');\n\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold} = attrs;\n\n const boxesVals = backend.readSync(boxes.dataId) as TypedArray;\n const scoresVals = backend.readSync(scores.dataId) as TypedArray;\n\n const {selectedIndices} = nonMaxSuppressionV3Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);\n\n return backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices));\n}\n\nexport const nonMaxSuppressionV3Config: KernelConfig = {\n kernelName: NonMaxSuppressionV3,\n backendName: 'webgl',\n kernelFunc: nonMaxSuppressionV3 as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV4, NonMaxSuppressionV4Attrs, NonMaxSuppressionV4Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\nconst nonMaxSuppressionV4Impl = kernel_impls.nonMaxSuppressionV4Impl;\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function nonMaxSuppressionV4(args: {\n inputs: NonMaxSuppressionV4Inputs,\n backend: MathBackendWebGL,\n attrs: NonMaxSuppressionV4Attrs\n}): [TensorInfo, TensorInfo] {\n backend_util.warn(\n 'tf.nonMaxSuppression() in webgl locks the UI thread. ' +\n 'Call tf.nonMaxSuppressionAsync() instead');\n\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize} =\n attrs;\n\n const boxesVals = backend.readSync(boxes.dataId) as TypedArray;\n const scoresVals = backend.readSync(scores.dataId) as TypedArray;\n\n const {selectedIndices, validOutputs} = nonMaxSuppressionV4Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold,\n padToMaxOutputSize);\n\n return [\n backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices)),\n backend.makeTensorInfo([], 'int32', new Int32Array([validOutputs]))\n ];\n}\n\nexport const nonMaxSuppressionV4Config: KernelConfig = {\n kernelName: NonMaxSuppressionV4,\n backendName: 'webgl',\n kernelFunc: nonMaxSuppressionV4 as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV5, NonMaxSuppressionV5Attrs, NonMaxSuppressionV5Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV5Impl = kernel_impls.nonMaxSuppressionV5Impl;\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function nonMaxSuppressionV5(args: {\n inputs: NonMaxSuppressionV5Inputs,\n backend: MathBackendWebGL,\n attrs: NonMaxSuppressionV5Attrs\n}): [TensorInfo, TensorInfo] {\n backend_util.warn(\n 'tf.nonMaxSuppression() in webgl locks the UI thread. ' +\n 'Call tf.nonMaxSuppressionAsync() instead');\n\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma} = attrs;\n\n const boxesVals = backend.readSync(boxes.dataId) as TypedArray;\n const scoresVals = backend.readSync(scores.dataId) as TypedArray;\n\n const maxOutputSizeVal = maxOutputSize;\n const iouThresholdVal = iouThreshold;\n const scoreThresholdVal = scoreThreshold;\n const softNmsSigmaVal = softNmsSigma;\n\n const {selectedIndices, selectedScores} = nonMaxSuppressionV5Impl(\n boxesVals, scoresVals, maxOutputSizeVal, iouThresholdVal,\n scoreThresholdVal, softNmsSigmaVal);\n\n return [\n backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices)),\n backend.makeTensorInfo(\n [selectedScores.length], 'float32', new Float32Array(selectedScores))\n ];\n}\n\nexport const nonMaxSuppressionV5Config: KernelConfig = {\n kernelName: NonMaxSuppressionV5,\n backendName: 'webgl',\n kernelFunc: nonMaxSuppressionV5 as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class OneHotProgram implements GPGPUProgram {\n variableNames = ['indices'];\n outputShape: number[];\n userCode: string;\n\n // Caching uniform location for speed.\n seedLoc: WebGLUniformLocation;\n\n constructor(\n numIndices: number, depth: number, onValue: number, offValue: number) {\n this.outputShape = [numIndices, depth];\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(${offValue}), float(${onValue}),\n float(index == coords.y)));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, OneHot, OneHotAttrs, OneHotInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {OneHotProgram} from '../onehot_gpu';\nimport {reshape} from './Reshape';\n\nexport const oneHot = (args: {\n inputs: OneHotInputs,\n backend: MathBackendWebGL,\n attrs: OneHotAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {indices} = inputs;\n const {depth, onValue, offValue} = attrs;\n\n const indicesSize = util.sizeFromShape(indices.shape);\n const program = new OneHotProgram(indicesSize, depth, onValue, offValue);\n const reshaped =\n reshape({inputs: {x: indices}, backend, attrs: {shape: [indicesSize]}});\n const result = backend.runWebGLProgram(program, [reshaped], indices.dtype);\n backend.disposeIntermediateTensorInfo(reshaped);\n\n const outShape = [...indices.shape, depth];\n const out = reshape({inputs: {x: result}, backend, attrs: {shape: outShape}});\n backend.disposeIntermediateTensorInfo(result);\n return out;\n};\n\nexport const oneHotConfig: KernelConfig = {\n kernelName: OneHot,\n backendName: 'webgl',\n kernelFunc: oneHot as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, ZerosLike, ZerosLikeInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {complex} from './Complex';\nimport {fill} from './Fill';\nimport {imag} from './Imag';\nimport {real} from './Real';\n\nexport function zerosLike(\n args: {inputs: ZerosLikeInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const r = zerosLike({inputs: {x: realPart}, backend});\n const imagPart = imag({inputs: {input: x}, backend});\n const i = zerosLike({inputs: {x: imagPart}, backend});\n\n const result = complex({inputs: {real: r, imag: i}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(r);\n backend.disposeIntermediateTensorInfo(imagPart);\n backend.disposeIntermediateTensorInfo(i);\n\n return result;\n } else {\n return fill({\n attrs: {\n shape: x.shape,\n dtype: x.dtype,\n value: x.dtype === 'string' ? '' : 0\n },\n backend\n });\n }\n}\n\nexport const zerosLikeConfig: KernelConfig = {\n kernelName: ZerosLike,\n backendName: 'webgl',\n kernelFunc: zerosLike as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, OnesLike, OnesLikeInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {complex} from './Complex';\nimport {fill} from './Fill';\nimport {imag} from './Imag';\nimport {real} from './Real';\nimport {zerosLike} from './ZerosLike';\n\nexport function onesLike(\n args: {inputs: OnesLikeInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (x.dtype === 'string') {\n throw new Error('onesLike is not supported under string dtype');\n } else if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const r = onesLike({inputs: {x: realPart}, backend});\n const imagPart = imag({inputs: {input: x}, backend});\n const i = zerosLike({inputs: {x: imagPart}, backend});\n\n const result = complex({inputs: {real: r, imag: i}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(r);\n backend.disposeIntermediateTensorInfo(imagPart);\n backend.disposeIntermediateTensorInfo(i);\n\n return result;\n } else {\n // TODO(cais, smilkov): Add WebGL shader for onesLike:\n // https://github.com/tensorflow/tfjs/issues/1293\n return fill({attrs: {shape: x.shape, dtype: x.dtype, value: 1}, backend});\n }\n}\n\nexport const onesLikeConfig: KernelConfig = {\n kernelName: OnesLike,\n backendName: 'webgl',\n kernelFunc: onesLike as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Pack, PackAttrs, PackInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {concat} from './Concat';\nimport {expandDims} from './ExpandDims';\n\nexport function pack(\n args: {inputs: PackInputs, backend: MathBackendWebGL, attrs: PackAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {axis} = attrs;\n\n if (inputs.length === 1) {\n return expandDims(\n {inputs: {input: inputs[0]}, backend, attrs: {dim: axis}});\n }\n\n const shape = inputs[0].shape;\n const dtype = inputs[0].dtype;\n\n inputs.forEach(t => {\n util.assertShapesMatch(\n shape, t.shape,\n 'All tensors passed to stack must have matching shapes');\n util.assert(\n dtype === t.dtype,\n () => 'All tensors passed to stack must have matching dtypes');\n });\n\n const intermediateTensorInfos: TensorInfo[] = [];\n const expandedTensors = inputs.map(t => {\n const expandedT =\n expandDims({inputs: {input: t}, backend, attrs: {dim: axis}});\n intermediateTensorInfos.push(expandedT);\n return expandedT;\n });\n\n const result = concat({inputs: expandedTensors, backend, attrs: {axis}});\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n\n return result;\n}\n\nexport const packConfig: KernelConfig = {\n kernelName: Pack,\n backendName: 'webgl',\n kernelFunc: pack as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class PadProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n valueLoc: WebGLUniformLocation;\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n constantValue: number) {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const type = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const unpackedCoords =\n ['coords[0]', 'coords[1]', 'coords[2]', 'coords[3]'].slice(0, rank);\n\n if (rank === 1) {\n this.userCode = `\n int start = ${start};\n int end = ${end};\n uniform float value;\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `;\n return;\n }\n this.userCode = `\n ${type} start = ${type}(${start});\n ${type} end = ${type}(${end});\n uniform float value;\n\n void main() {\n ${type} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${type} coords = outC - start;\n setOutput(getX(${unpackedCoords}));\n }\n }\n `;\n }\n\n getCustomSetupFunc(value: number) {\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.valueLoc == null) {\n this.valueLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'value');\n }\n gpgpu.gl.uniform1f(this.valueLoc, value);\n };\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class PadPackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n valueLoc: WebGLUniformLocation;\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n constantValue: number) {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const dtype = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const coords = getChannels('rc', rank);\n const source = getChannels('source', rank);\n const cLimit = `${coords[rank - 1]} < ${this.outputShape[rank - 1]}`;\n const innerDims =\n rank === 1 ? 'source' : `vec2(${source.slice(-2).join()})`;\n\n const componentSetup = [\n `${dtype} rc = outputLoc;`, `${coords[rank - 1]} += 1;\n if(${cLimit}) {\n `,\n rank === 1 ? '' : `}\n rc = outputLoc;\n ${coords[rank - 2]} += 1;\n if(${coords[rank - 2]} < ${this.outputShape[rank - 2]}) {`,\n rank === 1 ? '' : ` ${coords[rank - 1]} += 1;\n if(${cLimit}) {`\n ];\n\n const paddingArea = rank === 1 ?\n 'rc < start || rc >= end' :\n 'any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))';\n let mainLoop = '';\n for (let i = 0, j = rank === 1 ? 2 : 4; i < j; i++) {\n mainLoop += `\n ${componentSetup[i]}\n if (${paddingArea}) {\n result[${i}] = float(value);\n } else {\n ${dtype} source = rc - start;\n result[${i}] = getChannel(getX(${source.join()}), ${innerDims});\n }\n `;\n }\n mainLoop += (rank === 1 ? `} ` : `}}`);\n\n this.userCode = `\n const ${dtype} start = ${dtype}(${start});\n const ${dtype} end = ${dtype}(${end});\n uniform float value;\n\n void main() {\n ${dtype} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${mainLoop}\n setOutput(result);\n }\n `;\n }\n\n getCustomSetupFunc(value: number) {\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.valueLoc == null) {\n this.valueLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'value');\n }\n gpgpu.gl.uniform1f(this.valueLoc, value);\n };\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, PadV2, PadV2Attrs, PadV2Inputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {PadProgram} from '../pad_gpu';\nimport {PadPackedProgram} from '../pad_packed_gpu';\n\nexport const padV2 =\n (args: {inputs: PadV2Inputs, backend: MathBackendWebGL, attrs: PadV2Attrs}):\n TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {paddings, constantValue} = attrs;\n\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new PadPackedProgram(x.shape, paddings, constantValue) :\n new PadProgram(x.shape, paddings, constantValue);\n const customSetup = program.getCustomSetupFunc(constantValue);\n return backend.runWebGLProgram(program, [x], x.dtype, customSetup);\n };\n\nexport const padV2Config: KernelConfig = {\n kernelName: PadV2,\n backendName: 'webgl',\n kernelFunc: padV2 as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Pow} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_packed_gpu';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst POW = `\n if(a < 0.0 && floor(b) < b){\n return NAN;\n }\n if (b == 0.0) {\n return 1.0;\n }\n return (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n`;\n\nconst POW_PACKED = `\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 CHECK_NAN_SNIPPET + `\n return result;\n`;\n\nexport const pow =\n binaryKernelFunc({opSnippet: POW, packedOpSnippet: POW_PACKED});\n\nexport const powConfig: KernelConfig = {\n kernelName: Pow,\n backendName: 'webgl',\n kernelFunc: pow as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Prod, ProdAttrs, ProdInputs, sumOutType, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {prodImplCPU} from '../kernel_utils/shared';\n\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function prod(\n args: {inputs: ProdInputs, backend: MathBackendWebGL, attrs: ProdAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n const xRank = x.shape.length;\n const toDispose = [];\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let permutedX = x;\n if (permutedAxes != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n toDispose.push(permutedX);\n }\n\n backend_util.assertAxesAreInnerMostDims('prod', axes, xRank);\n\n let res;\n if (backend.shouldExecuteOnCPU([permutedX])) {\n const xVals = backend.texData.get(permutedX.dataId).values as TypedArray;\n const {outVals, outShape, outDtype} =\n prodImplCPU(permutedX.shape, permutedX.dtype, xVals, axes);\n res = backend.makeTensorInfo(outShape, outDtype, outVals);\n } else {\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(permutedX.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n const a2D = reshape(\n {inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n const outputDType = sumOutType(x.dtype);\n const reduced = reduce(a2D, outputDType, 'prod', backend);\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n\n toDispose.push(a2D);\n toDispose.push(reduced);\n }\n\n if (keepDims) {\n toDispose.push(res);\n const newShape = backend_util.expandShapeToKeepDim(res.shape, origAxes);\n res = reshape({inputs: {x: res}, backend, attrs: {shape: newShape}});\n }\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return res;\n}\n\nexport const prodConfig: KernelConfig = {\n kernelName: Prod,\n backendName: 'webgl',\n kernelFunc: prod as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Range, RangeAttrs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {rangeImplCPU} from '../kernel_utils/shared';\n\nexport const range =\n (args: {backend: MathBackendWebGL, attrs: RangeAttrs}): TensorInfo => {\n const {backend, attrs} = args;\n const {start, stop, step, dtype} = attrs;\n const values = rangeImplCPU(start, stop, step, dtype);\n return backend.makeTensorInfo([values.length], dtype, values);\n };\n\nexport const rangeConfig: KernelConfig = {\n kernelName: Range,\n backendName: 'webgl',\n kernelFunc: range as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Reciprocal} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst RECIPROCAL = `return 1.0 / x;`;\n\nexport const reciprocal = unaryKernelFunc({opSnippet: RECIPROCAL});\n\nexport const reciprocalConfig: KernelConfig = {\n kernelName: Reciprocal,\n backendName: 'webgl',\n kernelFunc: reciprocal,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Relu} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst RELU = CHECK_NAN_SNIPPET + `\n return (x < 0.0) ? 0.0 : x;\n`;\n\nconst RELU_PACKED = `\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n`;\n\nexport const relu =\n unaryKernelFunc({opSnippet: RELU, packedOpSnippet: RELU_PACKED});\n\nexport const reluConfig: KernelConfig = {\n kernelName: Relu,\n backendName: 'webgl',\n kernelFunc: relu as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Relu6} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst RELU6 = CHECK_NAN_SNIPPET + `\n return (x < 0.0) ? 0.0 : min(6.0, x);\n`;\n\nconst RELU6_PACKED = `\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n`;\n\nexport const relu6 =\n unaryKernelFunc({opSnippet: RELU6, packedOpSnippet: RELU6_PACKED});\n\nexport const relu6Config: KernelConfig = {\n kernelName: Relu6,\n backendName: 'webgl',\n kernelFunc: relu6 as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeBilinearProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC =\n `(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC` +\n ` - vec2(0.5)`;\n } else {\n sourceFracIndexRC = `vec2(yRC) * effectiveInputOverOutputRatioRC`;\n }\n\n this.userCode = `\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.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 = ${sourceFracIndexRC};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeBilinearPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC = `(vec3(yRC) + vec3(0.5)) * ` +\n `effectiveInputOverOutputRatioRC - vec3(0.5)`;\n } else {\n sourceFracIndexRC = `vec3(yRC) * effectiveInputOverOutputRatioRC`;\n }\n\n this.userCode = `\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec3 inputShapeRC = vec3(${oldHeight}.0, ${oldWidth}.0,\n ${oldWidth}.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 = ${sourceFracIndexRC};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${depth - 1};\n bool hasNextRow = coords.z < ${newWidth - 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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeBilinearProgram} from '../resize_bilinear_gpu';\nimport {ResizeBilinearPackedProgram} from '../resize_bilinear_packed_gpu';\n\nexport function resizeBilinear(args: {\n inputs: ResizeBilinearInputs,\n backend: MathBackendWebGL,\n attrs: ResizeBilinearAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n const [newHeight, newWidth] = size;\n\n const program = env().getBool('WEBGL_PACK_IMAGE_OPERATIONS') ?\n new ResizeBilinearPackedProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters) :\n new ResizeBilinearProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters);\n return backend.runWebGLProgram(program, [images], 'float32');\n}\n\nexport const resizeBilinearConfig: KernelConfig = {\n kernelName: ResizeBilinear,\n backendName: 'webgl',\n kernelFunc: resizeBilinear as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeBilinearBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n dyShape: [number, number, number, number],\n inputShape: [number, number, number, number], alignCorners: boolean) {\n this.outputShape = inputShape;\n const [, xHeight, xWidth, ] = inputShape;\n const [, yHeight, yWidth] = dyShape;\n\n // In the backwards pass, we want to find the pixels that were generated for\n // each pixel in the input image the forward pass and add the corresponding\n // coefficient from dy to the gradient (with some interpolation).\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n const invHeightScale = 1 / heightScale;\n const invWidthScale = 1 / widthScale;\n\n // This defines the size of the window of values around a particular\n // index in dy that we want to search for contributions to dx.\n const winHeight = (Math.ceil(invHeightScale) * 2) + 2;\n const winWidth = (Math.ceil(invWidthScale) * 2) + 2;\n\n 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(${heightScale});\n const float widthScale = float(${widthScale});\n\n const float invHeightScale = float(${invHeightScale});\n const float invWidthScale = float(${invWidthScale});\n\n const int winHeight = int(${winHeight});\n const int winWidth = int(${winWidth});\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 >= ${yHeight}) {\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 >= ${yWidth}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${xHeight - 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), ${xWidth - 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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, ResizeBilinearGrad, ResizeBilinearGradAttrs, ResizeBilinearGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeBilinearBackpropProgram} from '../resize_bilinear_backprop_gpu';\n\nexport function resizeBilinearGrad(args: {\n inputs: ResizeBilinearGradInputs,\n backend: MathBackendWebGL,\n attrs: ResizeBilinearGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n const program = new ResizeBilinearBackpropProgram(\n dy.shape as [number, number, number, number],\n images.shape as [number, number, number, number], alignCorners);\n\n return backend.runWebGLProgram(program, [dy], dy.dtype);\n}\n\nexport const resizeBilinearGradConfig: KernelConfig = {\n kernelName: ResizeBilinearGrad,\n backendName: 'webgl',\n kernelFunc: resizeBilinearGrad as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeNearestNeighborProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n // When align corners is false, we rounds the value with floor.\n const roundBase = alignCorners ? '0.5' : '0.0';\n\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC =\n `max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC` +\n `, vec2(0.0))`;\n } else {\n sourceFracIndexRC = `vec2(yRC) * effectiveInputOverOutputRatioRC`;\n }\n this.userCode = `\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.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 = ${sourceFracIndexRC};\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${roundBase})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeNearestNeighborPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n // When align corners is false, we rounds the value with floor.\n const roundBase = alignCorners ? '0.5' : '0.0';\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC = `max((vec3(yRC) + vec3(0.5)) * ` +\n `effectiveInputOverOutputRatioRC, vec3(0.0))`;\n } else {\n sourceFracIndexRC = `vec3(yRC) * effectiveInputOverOutputRatioRC`;\n }\n\n this.userCode = `\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec3 inputShapeRC = vec3(${oldHeight}.0, ${oldWidth}.0,\n ${oldWidth}.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 = ${sourceFracIndexRC};\n\n // Compute the coordinators of nearest neighbor point.\n ivec3 sourceNearestRC = ivec3(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${roundBase})));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${depth - 1};\n bool hasNextRow = coords.z < ${newWidth - 1};\n\n vec4 newValue = vec4(\n getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\n hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\n\n setOutput(newValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, ResizeNearestNeighbor, ResizeNearestNeighborAttrs, ResizeNearestNeighborInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeNearestNeighborProgram} from '../resize_nearest_neighbor_gpu';\nimport {ResizeNearestNeighborPackedProgram} from '../resize_nearest_neighbor_packed_gpu';\n\nexport function resizeNearestNeighbor(args: {\n inputs: ResizeNearestNeighborInputs,\n backend: MathBackendWebGL,\n attrs: ResizeNearestNeighborAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n const [newHeight, newWidth] = size;\n\n const program = env().getBool('WEBGL_PACK_IMAGE_OPERATIONS') ?\n new ResizeNearestNeighborPackedProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters) :\n new ResizeNearestNeighborProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters);\n return backend.runWebGLProgram(program, [images], images.dtype);\n}\n\nexport const resizeNearestNeighborConfig: KernelConfig = {\n kernelName: ResizeNearestNeighbor,\n backendName: 'webgl',\n kernelFunc: resizeNearestNeighbor as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeNearestNeigborBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n dyShape: [number, number, number, number],\n inputShape: [number, number, number, number], alignCorners: boolean) {\n this.outputShape = inputShape;\n const [, xHeight, xWidth, ] = inputShape;\n const [, yHeight, yWidth] = dyShape;\n\n // In the backwards pass, we want to find the pixels that were generated for\n // each pixel in the input image the forward pass and add the corresponding\n // coefficient from dy to the gradient (with some interpolation).\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n const invHeightScale = 1 / heightScale;\n const invWidthScale = 1 / widthScale;\n\n // This defines the size of the window of values around a particular\n // index in dy that we want to search for contributions to dx.\n const winHeight = (Math.ceil(invHeightScale) * 2) + 2;\n const winWidth = (Math.ceil(invWidthScale) * 2) + 2;\n\n 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(${heightScale});\n const float widthScale = float(${widthScale});\n\n const float invHeightScale = float(${invHeightScale});\n const float invWidthScale = float(${invWidthScale});\n\n const int winHeight = int(${winHeight});\n const int winWidth = int(${winWidth});\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 >= ${yHeight}) {\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 >= ${yWidth}) {\n continue;\n }\n\n float sourceFracRow =\n float(${effectiveXSize[0]}) *\n (float(dyR) / float(${effectiveYSize[0]}));\n\n float sourceFracCol =\n float(${effectiveXSize[1]}) *\n (float(dyC) / float(${effectiveYSize[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${xHeight}) - 1),\n ${alignCorners} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${xWidth}) - 1),\n ${alignCorners} ? 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 `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, ResizeNearestNeighborGrad, ResizeNearestNeighborGradAttrs, ResizeNearestNeighborGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeNearestNeigborBackpropProgram} from '../resize_nearest_neighbor_backprop_gpu';\n\nexport function resizeNearestNeighborGrad(args: {\n inputs: ResizeNearestNeighborGradInputs,\n backend: MathBackendWebGL,\n attrs: ResizeNearestNeighborGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n const program = new ResizeNearestNeigborBackpropProgram(\n dy.shape as [number, number, number, number],\n images.shape as [number, number, number, number], alignCorners);\n return backend.runWebGLProgram(program, [dy], dy.dtype);\n}\n\nexport const resizeNearestNeighborGradConfig: KernelConfig = {\n kernelName: ResizeNearestNeighborGrad,\n backendName: 'webgl',\n kernelFunc: resizeNearestNeighborGrad as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ReverseProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(xShape: number[], axis: number[]) {\n const rank = xShape.length;\n if (rank > 4) {\n throw new Error(\n `WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);\n }\n this.outputShape = xShape;\n\n if (rank === 1) {\n this.userCode = `\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${xShape[0]} - coord - 1));\n }\n `;\n return;\n }\n const getInCoord = (i: number) => {\n if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {\n return `${xShape[i]} - coords[${i}] - 1`;\n }\n return `coords[${i}]`;\n };\n const inCoords = xShape.map((_, i) => getInCoord(i)).join(',');\n const type = getCoordsDataType(rank);\n\n this.userCode = `\n void main() {\n ${type} coords = getOutputCoords();\n setOutput(getX(${inCoords}));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ReversePackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(xShape: number[], axis: number[]) {\n const rank = xShape.length;\n if (rank > 4) {\n throw new Error(\n `WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);\n }\n this.outputShape = xShape;\n const channels = getChannels('rc', rank);\n const nextColumn =\n `${channels[rank - 1]} + 1 < ${this.outputShape[rank - 1]}`;\n const nextRow = `${channels[rank - 2]} + 1 < ${this.outputShape[rank - 2]}`;\n const type = getCoordsDataType(rank);\n if (rank === 1) {\n this.userCode = `\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${xShape[0]} - rc - 1),\n ${xShape[0]} - rc - 1);\n if(${nextColumn}){\n result.g = getChannel(getX(${xShape[0]} - (rc + 1) - 1),\n ${xShape[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `;\n } else {\n this.userCode = `\n void main() {\n ${type} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${getR(channels.slice())};\n if(${nextColumn}){\n result.g = ${getG(channels.slice())};\n }\n if(${nextRow}) {\n result.b = ${getB(channels.slice())};\n if(${nextColumn}) {\n result.a = ${getA(channels.slice())};\n }\n }\n setOutput(result);\n }\n `;\n }\n\n function getR(channels: string[]): string {\n return getChannel(channels);\n }\n\n function getG(channels: string[]): string {\n channels[rank - 1] = '(' + channels[rank - 1] + ` + 1)`;\n return getChannel(channels);\n }\n\n function getB(channels: string[]): string {\n channels[rank - 2] = '(' + channels[rank - 2] + ` + 1)`;\n return getChannel(channels);\n }\n\n function getA(channels: string[]): string {\n channels[rank - 1] = '(' + channels[rank - 1] + ` + 1)`;\n channels[rank - 2] = '(' + channels[rank - 2] + ` + 1)`;\n return getChannel(channels);\n }\n\n function getChannel(channels: string[]): string {\n const inCoordsArray = xShape.map((_, i) => getInCoord(i, channels));\n const inCoords = inCoordsArray.join(',');\n const innerDims = inCoordsArray.slice(-2).join(',');\n return `getChannel(getX(${inCoords}), vec2(${innerDims}))`;\n }\n\n function getInCoord(i: number, channels1: string[]): string {\n if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {\n return `${xShape[i]} - ${channels1[i]} - 1`;\n } else {\n return `${channels1[i]}`;\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env, KernelConfig, KernelFunc, Reverse, ReverseAttrs, ReverseInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ReverseProgram} from '../reverse_gpu';\nimport {ReversePackedProgram} from '../reverse_packed_gpu';\n\nimport {identity} from './Identity';\n\nexport function reverse(args: {\n inputs: ReverseInputs,\n backend: MathBackendWebGL,\n attrs: ReverseAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {dims} = attrs;\n\n const xRank = x.shape.length;\n\n const $dims = util.parseAxisParam(dims, x.shape);\n if (xRank === 0) {\n return identity({inputs: {x}, backend});\n }\n\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new ReversePackedProgram(x.shape, $dims) :\n new ReverseProgram(x.shape, $dims);\n\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const reverseConfig: KernelConfig = {\n kernelName: Reverse,\n backendName: 'webgl',\n kernelFunc: reverse as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class RotateProgram implements GPGPUProgram {\n variableNames = ['Image'];\n outputShape: number[] = [];\n userCode: string;\n paramsLoc: WebGLUniformLocation;\n constructor(\n imageShape: [number, number, number, number],\n fillValue: number|[number, number, number]) {\n const imageHeight = imageShape[1];\n const imageWidth = imageShape[2];\n this.outputShape = imageShape;\n\n let fillSnippet = '';\n if (typeof fillValue === 'number') {\n fillSnippet = `float outputValue = ${fillValue.toFixed(2)};`;\n } else {\n fillSnippet = `\n vec3 fill = vec3(${fillValue.join(',')});\n float outputValue = fill[coords[3]];`;\n }\n\n this.userCode = `\n uniform vec4 params;\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - params[0]) * params[3] -\n (float(y) - params[1]) * params[2];\n float coordYFloat = (float(x) - params[0]) * params[2] +\n (float(y) - params[1]) * params[3];\n int coordX = int(round(coordXFloat + params[0]));\n int coordY = int(round(coordYFloat + params[1]));\n ${fillSnippet}\n if(coordX >= 0 && coordX < ${imageWidth} && coordY >= 0 && coordY < ${\n imageHeight}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\n }\n `;\n }\n\n getCustomSetupFunc(\n centerX: number, centerY: number, sinFactor: number, cosFactor: number) {\n return (gpgpu: GPGPUContext, webGLProgram: WebGLProgram) => {\n if (this.paramsLoc == null) {\n this.paramsLoc =\n gpgpu.getUniformLocationNoThrow(webGLProgram, 'params');\n }\n gpgpu.gl.uniform4f(\n this.paramsLoc, centerX, centerY, sinFactor, cosFactor);\n };\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, Tensor4D} from '@tensorflow/tfjs-core';\nimport {RotateWithOffset, RotateWithOffsetAttrs, RotateWithOffsetInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {RotateProgram} from '../rotate_gpu';\n\nexport const rotateWithOffsetConfig: KernelConfig = {\n kernelName: RotateWithOffset,\n backendName: 'webgl',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {image} = inputs as RotateWithOffsetInputs;\n const {radians, fillValue, center} = attrs as {} as RotateWithOffsetAttrs;\n const webglBackend = backend as MathBackendWebGL;\n\n const program = new RotateProgram((image as Tensor4D).shape, fillValue);\n const [centerX, centerY] =\n backend_util.getImageCenter(center, image.shape[1], image.shape[2]);\n const customSetup = program.getCustomSetupFunc(\n centerX, centerY, Math.sin(radians), Math.cos(radians));\n const output = webglBackend.runWebGLProgram(\n program, [image], image.dtype, customSetup);\n return output;\n }\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Round} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst ROUND = `\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`;\n\nexport const round = unaryKernelFunc({opSnippet: ROUND});\n\nexport const roundConfig: KernelConfig = {\n kernelName: Round,\n backendName: 'webgl',\n kernelFunc: round,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Rsqrt} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {rsqrtImplCPU} from '../kernel_utils/shared';\n\nconst RSQRT = `return inversesqrt(x);`;\n\nexport const rsqrt =\n unaryKernelFunc({opSnippet: RSQRT, cpuKernelImpl: rsqrtImplCPU});\n\nexport const rsqrtConfig: KernelConfig = {\n kernelName: Rsqrt,\n backendName: 'webgl',\n kernelFunc: rsqrt as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ScatterProgram implements GPGPUProgram {\n variableNames = ['updates', 'indices', 'defaultValue'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n updateSize: number, sliceDim: number, indicesRank: number,\n updatesRank: number, strides: number[], shape: number[],\n summingDupeIndex = true) {\n this.outputShape = shape;\n const stridesType = getCoordsDataType(strides.length);\n const dtype = getCoordsDataType(shape.length);\n let indicesString = '';\n if (indicesRank === 1) {\n indicesString = 'i';\n } else if (indicesRank === 2) {\n indicesString = 'i, j';\n }\n const indicesSnippet = `getIndices(${indicesString})`;\n\n let updatesString = '';\n if (updatesRank === 1) {\n updatesString = 'i';\n } else if (updatesRank === 2) {\n updatesString = 'i, coords[1]';\n }\n const updatesSnippet = `getUpdates(${updatesString})`;\n\n const strideString = sliceDim > 1 ? 'strides[j]' : 'strides';\n this.userCode = `\n ${stridesType} strides = ${stridesType}(${strides});\n\n void main() {\n ${dtype} coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < ${updateSize}; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < ${sliceDim}; j++) {\n int index = round(${indicesSnippet});\n flattenedIndex += index * ${strideString};\n }\n if (flattenedIndex == coords[0]) {\n sum += ${updatesSnippet};\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, ScatterNd, ScatterNdAttrs, ScatterNdInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ScatterProgram} from '../scatter_gpu';\nimport {reshape} from './Reshape';\n\nexport function scatterNd(args: {\n inputs: ScatterNdInputs,\n backend: MathBackendWebGL,\n attrs: ScatterNdAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {indices, updates} = inputs;\n const {shape} = attrs;\n\n const {sliceRank, numUpdates, sliceSize, strides, outputSize} =\n backend_util.calculateShapes(updates, indices, shape);\n\n const flattenShape = [outputSize / sliceSize, sliceSize];\n\n if (outputSize === 0) {\n return backend.makeTensorInfo(shape, indices.dtype);\n }\n\n const flattenIndices = reshape(\n {inputs: {x: indices}, backend, attrs: {shape: [numUpdates, sliceRank]}});\n const flattenX = reshape(\n {inputs: {x: updates}, backend, attrs: {shape: [numUpdates, sliceSize]}});\n\n const defaultValue = backend.makeTensorInfo(\n [], 'float32', new Float32Array([0])); // scalar(0)\n const program = new ScatterProgram(\n numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length,\n strides, flattenShape);\n const res = backend.runWebGLProgram(\n program, [flattenX, flattenIndices, defaultValue], flattenX.dtype);\n\n const reshaped = reshape({inputs: {x: res}, backend, attrs: {shape}});\n\n backend.disposeIntermediateTensorInfo(flattenIndices);\n backend.disposeIntermediateTensorInfo(flattenX);\n backend.disposeIntermediateTensorInfo(res);\n backend.disposeIntermediateTensorInfo(defaultValue);\n\n return reshaped;\n}\n\nexport const scatterNdConfig: KernelConfig = {\n kernelName: ScatterNd,\n backendName: 'webgl',\n kernelFunc: scatterNd as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class SelectProgram implements GPGPUProgram {\n variableNames = ['c', 'a', 'b'];\n outputShape: number[];\n userCode: string;\n\n constructor(cRank: number, shape: number[], rank: number) {\n this.outputShape = shape;\n\n let cCoords;\n let abCoords;\n if (rank > 4) {\n throw Error(`Where for rank ${rank} is not yet supported`);\n }\n\n if (rank === 1) {\n abCoords = `resRC`;\n cCoords = `resRC`;\n } else {\n const currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w'];\n const cCoordVars = [];\n const abCoordVars = [];\n for (let i = 0; i < shape.length; i++) {\n abCoordVars.push(`${currentCoords[i]}`);\n if (i < cRank) {\n cCoordVars.push(`${currentCoords[i]}`);\n }\n }\n cCoords = cCoordVars.join();\n abCoords = abCoordVars.join();\n }\n\n const dtype = getCoordsDataType(rank);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n float cVal = getC(${cCoords});\n if (cVal >= 1.0) {\n setOutput(getA(${abCoords}));\n } else {\n setOutput(getB(${abCoords}));\n }\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Select, SelectInputs, TensorInfo, upcastType} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {SelectProgram} from '../select_gpu';\n\nexport function select(args: {inputs: SelectInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {condition, t, e} = inputs;\n\n const program =\n new SelectProgram(condition.shape.length, t.shape, t.shape.length);\n return backend.runWebGLProgram(\n program, [condition, t, e], upcastType(t.dtype, e.dtype));\n}\n\nexport const selectConfig: KernelConfig = {\n kernelName: Select,\n backendName: 'webgl',\n kernelFunc: select as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, Selu} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SELU = `\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${backend_util.SELU_SCALEALPHA};\n float scale = ${backend_util.SELU_SCALE};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`;\n\nexport const selu = unaryKernelFunc({opSnippet: SELU});\n\nexport const seluConfig: KernelConfig = {\n kernelName: Selu,\n backendName: 'webgl',\n kernelFunc: selu,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sigmoid} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * x));`;\n\nexport const sigmoid = unaryKernelFunc({opSnippet: SIGMOID});\n\nexport const sigmoidConfig: KernelConfig = {\n kernelName: Sigmoid,\n backendName: 'webgl',\n kernelFunc: sigmoid,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sign} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\n// Sign does not propagate NANs.\nconst SIGN = `\n if (isnan(x)) { return 0.0; }\n return sign(x);\n`;\n\nexport const sign = unaryKernelFunc({opSnippet: SIGN});\n\nexport const signConfig: KernelConfig = {\n kernelName: Sign,\n backendName: 'webgl',\n kernelFunc: sign,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sin} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_UNARY, unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SIN = CHECK_NAN_SNIPPET_UNARY + `\n return sin(x);\n`;\n\nexport const sin = unaryKernelFunc({opSnippet: SIN});\n\nexport const sinConfig: KernelConfig = {\n kernelName: Sin,\n backendName: 'webgl',\n kernelFunc: sin,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sinh} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SINH = `\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n`;\n\nexport const sinh = unaryKernelFunc({opSnippet: SINH});\n\nexport const sinhConfig: KernelConfig = {\n kernelName: Sinh,\n backendName: 'webgl',\n kernelFunc: sinh,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Softplus} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SOFTPLUS = `\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`;\n\nexport const softplus = unaryKernelFunc({opSnippet: SOFTPLUS});\n\nexport const softplusConfig: KernelConfig = {\n kernelName: Softplus,\n backendName: 'webgl',\n kernelFunc: softplus,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, SpaceToBatchND, SpaceToBatchNDAttrs, SpaceToBatchNDInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {padV2} from './PadV2';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport const spaceToBatchND = (args: {\n inputs: SpaceToBatchNDInputs,\n backend: MathBackendWebGL,\n attrs: SpaceToBatchNDAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, paddings} = attrs;\n\n util.assert(\n x.shape.length <= 4,\n () => 'spaceToBatchND for rank > 4 with a WebGL backend not ' +\n 'implemented yet');\n\n const prod = blockShape.reduce((a, b) => a * b);\n\n const completePaddings: Array<[number, number]> = [[0, 0]];\n completePaddings.push(...paddings as Array<[number, number]>);\n for (let i = 1 + blockShape.length; i < x.shape.length; ++i) {\n completePaddings.push([0, 0]);\n }\n\n const toDispose = [];\n\n const paddedX = padV2({\n inputs: {x},\n backend,\n attrs: {paddings: completePaddings, constantValue: 0}\n });\n\n const reshapedPaddedShape =\n backend_util.getReshaped(paddedX.shape, blockShape, prod, false);\n\n const permutedReshapedPaddedPermutation = backend_util.getPermuted(\n reshapedPaddedShape.length, blockShape.length, false);\n\n const flattenShape =\n backend_util.getReshapedPermuted(paddedX.shape, blockShape, prod, false);\n\n const reshapedPaddedX = reshape(\n {inputs: {x: paddedX}, backend, attrs: {shape: reshapedPaddedShape}});\n\n const paddedXT = transpose({\n inputs: {x: reshapedPaddedX},\n backend,\n attrs: {perm: permutedReshapedPaddedPermutation}\n });\n\n const result =\n reshape({inputs: {x: paddedXT}, backend, attrs: {shape: flattenShape}});\n\n toDispose.push(paddedX);\n toDispose.push(reshapedPaddedX);\n toDispose.push(paddedXT);\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return result;\n};\n\nexport const spaceToBatchNDConfig: KernelConfig = {\n kernelName: SpaceToBatchND,\n backendName: 'webgl',\n kernelFunc: spaceToBatchND as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, SparseFillEmptyRows, SparseFillEmptyRowsInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseFillEmptyRowsImplCPU} from '../kernel_utils/shared';\n\nexport function sparseFillEmptyRows(args: {\n inputs: SparseFillEmptyRowsInputs,\n backend: MathBackendWebGL\n}): [TensorInfo, TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {indices, values, denseShape, defaultValue} = inputs;\n if (denseShape.shape.length !== 1) {\n throw new Error(`Dense shape must be a vector, saw:\n ${denseShape.shape}`);\n }\n if (indices.shape.length !== 2) {\n throw new Error(`Indices must be a matrix, saw:\n ${indices.shape}`);\n }\n if (values.shape.length !== 1) {\n throw new Error(`Values must be a vector, saw:\n ${values.shape}`);\n }\n if (defaultValue.shape.length !== 0) {\n throw new Error(`Default value must be a scalar, saw:\n ${defaultValue.shape}`);\n }\n\n const $indices = backend.readSync(indices.dataId) as TypedArray;\n const $values = backend.readSync(values.dataId) as TypedArray;\n const $denseShape = backend.readSync(denseShape.dataId) as TypedArray;\n const $defaultValue =\n backend.readSync(defaultValue.dataId)[0] as number;\n\n const [outputIndices, outputIndicesShape, outputValues,\n emptyRowIndicator, reverseIndexMap] =\n sparseFillEmptyRowsImplCPU(\n $indices, indices.shape, indices.dtype, $values, values.dtype,\n $denseShape, $defaultValue);\n return [\n backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),\n backend.makeTensorInfo(\n [outputIndicesShape[0]], values.dtype, outputValues),\n backend.makeTensorInfo(\n [emptyRowIndicator.length], 'bool',\n new Uint8Array(\n emptyRowIndicator.map((value: boolean) => Number(value)))),\n backend.makeTensorInfo(\n [reverseIndexMap.length], indices.dtype,\n new Int32Array(reverseIndexMap)),\n ];\n}\n\nexport const sparseFillEmptyRowsConfig: KernelConfig = {\n kernelName: SparseFillEmptyRows,\n backendName: 'webgl',\n kernelFunc: sparseFillEmptyRows as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, SparseReshape, SparseReshapeInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseReshapeImplCPU} from '../kernel_utils/shared';\n\nexport function sparseReshape(\n args: {inputs: SparseReshapeInputs, backend: MathBackendWebGL}):\n [TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {inputIndices, inputShape, newShape} = inputs;\n if (inputIndices.shape.length !== 2) {\n throw new Error(`Input indices should be a matrix but received shape ${\n inputIndices.shape}`);\n }\n if (inputShape.shape.length !== 1) {\n throw new Error(`Input shape should be a vector but received shape ${\n inputShape.shape}`);\n }\n\n if (newShape.shape.length !== 1) {\n throw new Error(\n `Target shape should be a vector but received shape ${newShape.shape}`);\n }\n\n const $inputShape =\n Array.from(backend.readSync(inputShape.dataId) as TypedArray);\n const $inputIndices = backend.readSync(inputIndices.dataId) as TypedArray;\n const targetShape =\n Array.from(backend.readSync(newShape.dataId) as TypedArray);\n\n const [newIndices, indicesShape, outputShape] = sparseReshapeImplCPU(\n $inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape,\n targetShape);\n return [\n backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),\n backend.makeTensorInfo(\n [outputShape.length], newShape.dtype, new Int32Array(outputShape)),\n ];\n}\n\nexport const sparseReshapeConfig: KernelConfig = {\n kernelName: SparseReshape,\n backendName: 'webgl',\n kernelFunc: sparseReshape,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, SparseSegmentMean, SparseSegmentMeanInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseSegmentReductionImplCPU} from '../kernel_utils/shared';\n\nexport function sparseSegmentMean(\n args: {inputs: SparseSegmentMeanInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {data, indices, segmentIds} = inputs;\n if (data.shape.length < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if (indices.shape.length !== 1) {\n throw new Error(`Indices should be a vector but received shape\n ${indices.shape}`);\n }\n if (segmentIds.shape.length !== 1) {\n throw new Error(`Segment ids should be a vector but received shape\n ${segmentIds.shape}`);\n }\n\n const $data = backend.readSync(data.dataId) as TypedArray;\n const $indices = backend.readSync(indices.dataId) as TypedArray;\n const $segmentIds = backend.readSync(segmentIds.dataId) as TypedArray;\n\n const [outputData, outputDataShape] = sparseSegmentReductionImplCPU(\n $data, data.shape, data.dtype, $indices, $segmentIds, true);\n return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);\n}\n\nexport const sparseSegmentMeanConfig: KernelConfig = {\n kernelName: SparseSegmentMean,\n backendName: 'webgl',\n kernelFunc: sparseSegmentMean as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, SparseSegmentSum, SparseSegmentSumInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseSegmentReductionImplCPU} from '../kernel_utils/shared';\n\nexport function sparseSegmentSum(\n args: {inputs: SparseSegmentSumInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {data, indices, segmentIds} = inputs;\n if (data.shape.length < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if (indices.shape.length !== 1) {\n throw new Error(`Indices should be a vector but received shape\n ${indices.shape}`);\n }\n if (segmentIds.shape.length !== 1) {\n throw new Error(`Segment ids should be a vector but received shape\n ${segmentIds.shape}`);\n }\n\n const $data = backend.readSync(data.dataId) as TypedArray;\n const $indices = backend.readSync(indices.dataId) as TypedArray;\n const $segmentIds = backend.readSync(segmentIds.dataId) as TypedArray;\n\n const [outputData, outputDataShape] = sparseSegmentReductionImplCPU(\n $data, data.shape, data.dtype, $indices, $segmentIds);\n return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);\n}\n\nexport const sparseSegmentSumConfig: KernelConfig = {\n kernelName: SparseSegmentSum,\n backendName: 'webgl',\n kernelFunc: sparseSegmentSum as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, SparseToDense, SparseToDenseAttrs, SparseToDenseInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ScatterProgram} from '../scatter_gpu';\nimport {reshape} from './Reshape';\n\nexport function sparseToDense(args: {\n inputs: SparseToDenseInputs,\n backend: MathBackendWebGL,\n attrs: SparseToDenseAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {sparseIndices, sparseValues, defaultValue} = inputs;\n const {outputShape} = attrs;\n\n const {sliceRank, numUpdates, strides, outputSize} =\n backend_util.calculateShapes(sparseValues, sparseIndices, outputShape);\n\n const sumDupeIndices = false;\n const program = new ScatterProgram(\n numUpdates, sliceRank, sparseIndices.shape.length,\n sparseValues.shape.length, strides, [outputSize, 1], sumDupeIndices);\n\n const res = backend.runWebGLProgram(\n program, [sparseValues, sparseIndices, defaultValue], sparseValues.dtype);\n\n const reshaped =\n reshape({inputs: {x: res}, backend, attrs: {shape: outputShape}});\n\n backend.disposeIntermediateTensorInfo(res);\n return reshaped;\n}\n\nexport const sparseToDenseConfig: KernelConfig = {\n kernelName: SparseToDense,\n backendName: 'webgl',\n kernelFunc: sparseToDense as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, SplitV, SplitVAttrs, SplitVInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {slice} from './Slice';\n\nexport function splitV(\n args:\n {inputs: SplitVInputs, backend: MathBackendWebGL, attrs: SplitVAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {numOrSizeSplits, axis} = attrs;\n\n const $axis = util.parseAxisParam(axis, x.shape)[0];\n const splitSizes = backend_util.prepareSplitSize(x, numOrSizeSplits, $axis);\n\n const xRank = x.shape.length;\n const begin = new Array(xRank).fill(0);\n const size = x.shape.slice();\n\n return splitSizes.map(s => {\n const sliceSize = [...size];\n sliceSize[$axis] = s;\n const sliceT =\n slice({inputs: {x}, backend, attrs: {begin, size: sliceSize}});\n begin[$axis] += s;\n return sliceT;\n });\n}\n\nexport const splitVConfig: KernelConfig = {\n kernelName: SplitV,\n backendName: 'webgl',\n kernelFunc: splitV as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Sqrt} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SQRT = `return sqrt(x);`;\n\nexport const sqrt = unaryKernelFunc({opSnippet: SQRT});\n\nexport const sqrtConfig: KernelConfig = {\n kernelName: Sqrt,\n backendName: 'webgl',\n kernelFunc: sqrt as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Square} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SQUARE = `return x * x;`;\n\nexport const square = unaryKernelFunc({opSnippet: SQUARE});\n\nexport const squareConfig: KernelConfig = {\n kernelName: Square,\n backendName: 'webgl',\n kernelFunc: square,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, SquaredDifference} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SQUARED_DIFFERENCE = 'return (a - b) * (a - b);';\n\nexport const squaredDifference = binaryKernelFunc(\n {opSnippet: SQUARED_DIFFERENCE, packedOpSnippet: SQUARED_DIFFERENCE});\n\nexport const squaredDifferenceConfig: KernelConfig = {\n kernelName: SquaredDifference,\n backendName: 'webgl',\n kernelFunc: squaredDifference,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Step, StepAttrs, TensorInfo, UnaryInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CHECK_NAN_SNIPPET, UnaryOpProgram} from '../unaryop_gpu';\n\nexport function step(\n {inputs, attrs, backend}:\n {inputs: UnaryInputs, attrs: StepAttrs, backend: MathBackendWebGL}):\n TensorInfo {\n const {x} = inputs;\n const opSnippet = CHECK_NAN_SNIPPET + `\n return x > 0.0 ? 1.0 : float(${attrs.alpha});\n `;\n\n const program = new UnaryOpProgram(x.shape, opSnippet);\n\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const stepConfig: KernelConfig = {\n kernelName: Step,\n backendName: 'webgl',\n kernelFunc: step as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class StridedSliceProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(begin: number[], strides: number[], size: number[]) {\n this.outputShape = size;\n const rank = size.length;\n const inputDtype = getCoordsDataType(size.length);\n const dtype = getCoordsDataType(size.length);\n\n let newCoords = '';\n if (rank === 1) {\n newCoords = 'coords * strides + begin';\n } else {\n let outputAxis = 0;\n newCoords =\n size.map((_, i) => {\n outputAxis++;\n return size.length === 1 ?\n `coords * strides[${i}] + begin[${i}]` :\n `coords[${outputAxis - 1}] * strides[${i}] + begin[${i}]`;\n })\n .join(',');\n }\n\n this.userCode = `\n ${inputDtype} begin = ${inputDtype}(${begin});\n ${inputDtype} strides = ${inputDtype}(${strides});\n\n void main() {\n ${dtype} coords = getOutputCoords();\n setOutput(getX(${newCoords}));\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, KernelConfig, KernelFunc, Rank, slice_util, StridedSlice, StridedSliceAttrs, StridedSliceInputs, TensorBuffer, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stridedSliceImplCPU} from '../kernel_utils/shared';\nimport {StridedSliceProgram} from '../strided_slice_gpu';\n\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\n\nexport function stridedSlice(args: {\n inputs: StridedSliceInputs,\n backend: MathBackendWebGL,\n attrs: StridedSliceAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {\n begin,\n end,\n strides,\n beginMask,\n endMask,\n ellipsisMask,\n newAxisMask,\n shrinkAxisMask\n } = attrs;\n\n const {nonStrided, $begin, $strides, size, newShape, outShape} =\n slice_util.sliceInfo(\n x.shape, begin, end, strides, beginMask, endMask, ellipsisMask,\n newAxisMask, shrinkAxisMask);\n\n const $x = reshape({inputs: {x}, backend, attrs: {shape: newShape}});\n\n let result;\n if (nonStrided) {\n const sliced =\n slice({inputs: {x: $x}, backend, attrs: {begin: $begin, size}});\n result = reshape({inputs: {x: sliced}, backend, attrs: {shape: outShape}});\n\n backend.disposeIntermediateTensorInfo(sliced);\n } else if (outShape.some(axis => axis === 0)) {\n result = backend.makeTensorInfo(outShape, x.dtype, []);\n } else {\n const shouldExecuteOnCPU = backend.shouldExecuteOnCPU([$x]);\n if (shouldExecuteOnCPU) {\n const xTexData = backend.texData.get($x.dataId);\n const values = xTexData.values as TypedArray;\n const xBuf = buffer($x.shape, $x.dtype, values) as TensorBuffer;\n const resultValues =\n stridedSliceImplCPU(outShape, xBuf, $strides, $begin);\n result = backend.makeTensorInfo(outShape, $x.dtype, resultValues.values);\n } else {\n const program = new StridedSliceProgram($begin, $strides, outShape);\n result = backend.runWebGLProgram(program, [$x], $x.dtype);\n }\n }\n\n const resultReshaped =\n reshape({inputs: {x: result}, backend, attrs: {shape: outShape}});\n\n backend.disposeIntermediateTensorInfo($x);\n backend.disposeIntermediateTensorInfo(result);\n\n return resultReshaped;\n}\n\nexport const stridedSliceConfig: KernelConfig = {\n kernelName: StridedSlice,\n backendName: 'webgl',\n kernelFunc: stridedSlice as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, StringNGrams, StringNGramsAttrs, StringNGramsInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stringNGramsImplCPU} from '../kernel_utils/shared';\n\nexport function stringNGrams(args: {\n inputs: StringNGramsInputs,\n backend: MathBackendWebGL,\n attrs: StringNGramsAttrs\n}): [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {\n separator,\n nGramWidths,\n leftPad,\n rightPad,\n padWidth,\n preserveShortSequences\n } = attrs;\n const {data, dataSplits} = inputs;\n const $data = backend.readSync(data.dataId) as Uint8Array[];\n const $dataSplits = backend.readSync(dataSplits.dataId) as Int32Array;\n\n const [nGrams, nGramsSplits] = stringNGramsImplCPU(\n $data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth,\n preserveShortSequences);\n return [\n backend.makeTensorInfo([nGrams.length], 'string', nGrams),\n backend.makeTensorInfo(dataSplits.shape, 'int32', nGramsSplits),\n ];\n}\n\nexport const stringNGramsConfig: KernelConfig = {\n kernelName: StringNGrams,\n backendName: 'webgl',\n kernelFunc: stringNGrams as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, StringSplit, StringSplitAttrs, StringSplitInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stringSplitImplCPU} from '../kernel_utils/shared';\n\nexport function stringSplit(args: {\n inputs: StringSplitInputs,\n backend: MathBackendWebGL,\n attrs: StringSplitAttrs\n}): [TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {skipEmpty} = attrs;\n const {input, delimiter} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (input.shape.length !== 1) {\n throw new Error(`Input must be a vector, got shape: ${input.shape}`);\n }\n if (delimiter.shape.length !== 0) {\n throw new Error(\n `Delimiter must be a scalar, got shape: ${delimiter.shape}`);\n }\n\n const $input = backend.readSync(input.dataId) as Uint8Array[];\n const $delimiter = backend.readSync(delimiter.dataId)[0] as Uint8Array;\n\n const [indices, values, shape] =\n stringSplitImplCPU($input, $delimiter, skipEmpty);\n const outputSize = values.length;\n return [\n backend.makeTensorInfo([outputSize, 2], 'int32', indices),\n backend.makeTensorInfo([outputSize], 'string', values),\n backend.makeTensorInfo([2], 'int32', new Int32Array(shape))\n ];\n}\n\nexport const stringSplitConfig: KernelConfig = {\n kernelName: StringSplit,\n backendName: 'webgl',\n kernelFunc: stringSplit as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, StringToHashBucketFast, StringToHashBucketFastAttrs, StringToHashBucketFastInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stringToHashBucketFastImplCPU} from '../kernel_utils/shared';\n\nexport function stringToHashBucketFast(args: {\n inputs: StringToHashBucketFastInputs,\n backend: MathBackendWebGL,\n attrs: StringToHashBucketFastAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {numBuckets} = attrs;\n const {input} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (numBuckets <= 0) {\n throw new Error(`Number of buckets must be at least 1`);\n }\n\n const $input = backend.readSync(input.dataId) as Uint8Array[];\n\n const output = stringToHashBucketFastImplCPU($input, numBuckets);\n return backend.makeTensorInfo(input.shape, 'int32', output);\n}\n\nexport const stringToHashBucketFastConfig: KernelConfig = {\n kernelName: StringToHashBucketFast,\n backendName: 'webgl',\n kernelFunc: stringToHashBucketFast as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Tan} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst TAN = `return tan(x);`;\n\nexport const tan = unaryKernelFunc({opSnippet: TAN});\n\nexport const tanConfig: KernelConfig = {\n kernelName: Tan,\n backendName: 'webgl',\n kernelFunc: tan,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Tanh} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst TANH = `\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n`;\n\nexport const tanh = unaryKernelFunc({opSnippet: TANH});\n\nexport const tanhConfig: KernelConfig = {\n kernelName: Tanh,\n backendName: 'webgl',\n kernelFunc: tanh,\n};\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class TileProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n rank: number;\n\n constructor(aShape: number[], reps: number[]) {\n const outputShape: number[] = new Array(aShape.length);\n for (let i = 0; i < outputShape.length; i++) {\n outputShape[i] = aShape[i] * reps[i];\n }\n this.outputShape = outputShape;\n this.rank = outputShape.length;\n const dtype = getCoordsDataType(this.rank);\n const sourceCoords = getSourceCoords(aShape);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n setOutput(getA(${sourceCoords}));\n }\n `;\n }\n}\n\nfunction getSourceCoords(aShape: number[]): string {\n const rank = aShape.length;\n if (rank > 5) {\n throw Error(`Tile for rank ${rank} is not yet supported`);\n }\n if (rank === 1) {\n return `imod(resRC, ${aShape[0]})`;\n }\n\n const currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u'];\n\n const sourceCoords = [];\n for (let i = 0; i < aShape.length; i++) {\n sourceCoords.push(`imod(${currentCoords[i]}, ${aShape[i]})`);\n }\n return sourceCoords.join();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, KernelConfig, KernelFunc, TensorInfo, Tile, TileAttrs, TileInputs, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {tileImplCPU} from '../kernel_utils/shared';\nimport {TileProgram} from '../tile_gpu';\n\nexport function tile(\n params: {inputs: TileInputs, backend: MathBackendWebGL, attrs: TileAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = params;\n const {x} = inputs;\n const {reps} = attrs;\n\n // tile gpu program cannot handle rank > 5 case.\n if (x.dtype === 'string' || x.shape.length > 5) {\n // Even thought string tensor is always on CPU, just to be consistent on how\n // to access tensor data.\n const data = backend.readSync(x.dataId);\n const value = x.dtype === 'string' ?\n (data as Uint8Array[]).map(d => util.decodeString(d)) :\n data as TypedArray;\n const buf = buffer(x.shape, x.dtype, value);\n const outBuf = tileImplCPU(buf, reps);\n return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n }\n\n const program = new TileProgram(x.shape, reps);\n const output = backend.runWebGLProgram(program, [x], x.dtype);\n\n return output;\n}\n\nexport const tileConfig: KernelConfig = {\n kernelName: Tile,\n backendName: 'webgl',\n kernelFunc: tile as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, NumericDataType, TensorInfo, TopK, TopKAttrs, TopKInputs, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {topKImplCPU} from '../kernel_utils/shared';\n\nexport function topK(\n args: {inputs: TopKInputs, backend: MathBackendWebGL, attrs: TopKAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {k, sorted} = attrs;\n\n const xVals = backend.readSync(x.dataId) as TypedArray;\n const [allTopKVals, allTopKIndices] =\n topKImplCPU(xVals, x.shape, x.dtype as NumericDataType, k, sorted);\n\n return [\n backend.makeTensorInfo(\n allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),\n backend.makeTensorInfo(\n allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)\n ];\n}\n\nexport const topKConfig: KernelConfig = {\n kernelName: TopK,\n backendName: 'webgl',\n kernelFunc: topK as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class TransformProgram implements GPGPUProgram {\n variableNames = ['Image', 'Transforms'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n imageHeight: number, imageWidth: number,\n interpolation: 'nearest'|'bilinear',\n fillMode: 'constant'|'reflect'|'wrap'|'nearest', fillValue: number,\n outShape: [number, number, number, number]) {\n this.outputShape = outShape;\n const interpolationModeId = interpolation === 'nearest' ? 1 : 2;\n let fillModeId;\n switch (fillMode) {\n case 'constant':\n fillModeId = 1;\n break;\n case 'reflect':\n fillModeId = 2;\n break;\n case 'wrap':\n fillModeId = 3;\n break;\n case 'nearest':\n fillModeId = 4;\n break;\n default:\n fillModeId = 1;\n break;\n }\n this.userCode = `\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(${fillModeId} == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n inCoord -= sz2 * float(int(float(inCoord / sz2)));\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1.0;\n }\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${fillModeId} == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord -= len * float(int(float(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${fillModeId} == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n } else {\n return outCoord;\n }\n }\n\n float readWithFillValue(int batch, int coordY, int coordX,\n int channel) {\n float outputValue;\n if (0 <= coordY && coordY < ${\n imageHeight} && 0 <= coordX && coordX < ${imageWidth}) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(${fillValue});\n }\n return outputValue;\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n float outputValue;\n int batch = coords[0];\n int x = coords[2];\n int y = coords[1];\n int channel = coords[3];\n float xf = float(x);\n float yf = float(y);\n float a1 = getTransforms(batch, 0);\n float a2 = getTransforms(batch, 1);\n float a3 = getTransforms(batch, 2);\n float b1 = getTransforms(batch, 3);\n float b2 = getTransforms(batch, 4);\n float b3 = getTransforms(batch, 5);\n float c1 = getTransforms(batch, 6);\n float c2 = getTransforms(batch, 7);\n float projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = float(${fillValue});\n } else {\n float inX = (a1 * xf + a2 * yf + a3) / projection;\n float inY = (b1 * xf + b2 * yf + b3) / projection;\n float mapX = mapCoord(inX, float(${imageWidth}));\n float mapY = mapCoord(inY, float(${imageHeight}));\n\n if (${interpolationModeId} == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Transform, TransformAttrs, TransformInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {TransformProgram} from '../transform_gpu';\n\nexport function transform(args: {\n inputs: TransformInputs,\n backend: MathBackendWebGL,\n attrs: TransformAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {image, transforms} = inputs;\n const {interpolation, fillMode, fillValue, outputShape} = attrs;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n const [outHeight, outWidth] =\n outputShape != null ? outputShape : [imageHeight, imageWidth];\n const outShape =\n [batch, outHeight, outWidth,\n numChannels] as [number, number, number, number];\n\n const program = new TransformProgram(\n imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape);\n return backend.runWebGLProgram(program, [image, transforms], 'float32');\n}\n\nexport const transformConfig: KernelConfig = {\n kernelName: Transform,\n backendName: 'webgl',\n kernelFunc: transform as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Unique, UniqueAttrs, UniqueInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {uniqueImplCPU} from '../kernel_utils/shared';\nimport {assertNotComplex} from '../webgl_util';\n\nexport function unique(\n args:\n {inputs: UniqueInputs, attrs: UniqueAttrs, backend: MathBackendWebGL}):\n TensorInfo[] {\n const {inputs, attrs, backend} = args;\n const {axis} = attrs;\n const {x} = inputs;\n assertNotComplex(x, 'unique');\n\n // For now, always forward calculation to the CPU backend.\n console.warn(\n 'WARNING: ',\n 'UI might be locked temporarily as data is being downloaded');\n const values = backend.readSync(x.dataId);\n const {outputValues, outputShape, indices} =\n uniqueImplCPU(values, axis, x.shape, x.dtype);\n return [\n backend.makeTensorInfo(outputShape, x.dtype, outputValues),\n backend.makeTensorInfo([indices.length], 'int32', indices),\n ];\n}\n\nexport const uniqueConfig: KernelConfig = {\n kernelName: Unique,\n backendName: 'webgl',\n kernelFunc: unique as {} as KernelFunc,\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Unpack, UnpackAttrs, UnpackInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\n\nexport function unpack(\n args:\n {inputs: UnpackInputs, backend: MathBackendWebGL, attrs: UnpackAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {value} = inputs;\n let {axis} = attrs;\n\n if (axis < 0) {\n axis += value.shape.length;\n }\n\n const x = value;\n const xRank = x.shape.length;\n\n const num = value.shape[axis];\n const outShape: number[] = new Array(xRank - 1);\n let outIndex = 0;\n for (let i = 0; i < xRank; i++) {\n if (i !== axis) {\n outShape[outIndex++] = x.shape[i];\n }\n }\n\n const toDispose = [];\n\n const begin = new Array(xRank).fill(0);\n const size = x.shape.slice();\n size[axis] = 1;\n const res: TensorInfo[] = new Array(num);\n for (let i = 0; i < res.length; i++) {\n begin[axis] = i;\n const sliced = slice({inputs: {x}, backend, attrs: {begin, size}});\n const reshaped =\n reshape({inputs: {x: sliced}, backend, attrs: {shape: outShape}});\n res[i] = reshaped;\n\n toDispose.push(sliced);\n }\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n return res;\n}\n\nexport const unpackConfig: KernelConfig = {\n kernelName: Unpack,\n backendName: 'webgl',\n kernelFunc: unpack as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class SegmentOpProgram implements GPGPUProgram {\n variableNames = ['x', 'segmentIds'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n segOpInfo: backend_util.segment_util.SegOpInfo,\n segOpType: 'unsortedSegmentSum') {\n const windowSize = segOpInfo.windowSize;\n const batchSize = segOpInfo.batchSize;\n const inSize = segOpInfo.inSize;\n const numSegments = segOpInfo.numSegments;\n const outSize = numSegments * Math.ceil(inSize / windowSize);\n this.outputShape = [batchSize, outSize];\n\n const initializationValue = '0.0';\n const returnValue = `sumValue`;\n\n const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;\n const windowSizeVec4Remainder = windowSize % 4;\n\n const updateSnippet = `\n sumValue += dot(values, segFilter);\n `;\n\n let checkValueOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkValueOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return initializationValue;\n }\n `;\n }\n\n let checkSegmentIdOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkSegmentIdOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return -1.0;\n }\n `;\n }\n\n this.userCode = `\n const float initializationValue = ${initializationValue};\n\n float getValue(int batch, int inIdx) {\n ${checkValueOutOfBounds}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${checkSegmentIdOutOfBounds}\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 ${numSegments})) * float(${windowSize}));\n int currentSeg = int(mod(float(outIdx), float(${numSegments})));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${windowSizeNearestVec4}; 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 ${updateSnippet}\n }\n\n int inIdx = inOffset + ${windowSizeNearestVec4};\n if (${windowSizeVec4Remainder === 1}) {\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 ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 2}) {\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 ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 3}) {\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 ${updateSnippet}\n }\n setOutput(${returnValue});\n }\n `;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataType, KernelConfig, KernelFunc, sumOutType, TensorInfo, UnsortedSegmentSum, UnsortedSegmentSumAttrs, UnsortedSegmentSumInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {SegmentOpProgram} from '../segment_gpu';\n\nimport {range} from './Range';\nimport {reshape} from './Reshape';\nimport {tile} from './Tile';\nimport {transpose} from './Transpose';\n\nexport function unsortedSegmentSum(args: {\n inputs: UnsortedSegmentSumInputs,\n backend: MathBackendWebGL,\n attrs: UnsortedSegmentSumAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, segmentIds} = inputs;\n const {numSegments} = attrs;\n\n const xRank = x.shape.length;\n\n const toDispose = [];\n\n let axis = 0;\n const permutation = backend_util.getAxesPermutation([axis], xRank);\n let permutedX = x;\n if (permutation != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n toDispose.push(permutedX);\n axis = backend_util.getInnerMostAxes(1, xRank)[0];\n }\n\n const outShape = backend_util.segment_util.computeOutShape(\n permutedX.shape, axis, numSegments);\n const inSize = util.sizeFromShape([permutedX.shape[axis]]);\n const a2D =\n reshape({inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n toDispose.push(a2D);\n\n const outputDType = sumOutType(x.dtype);\n\n const segOpCompute =\n (x: TensorInfo, segOpType: 'unsortedSegmentSum', segmentIds: TensorInfo,\n dtype: DataType, numSegments: number): TensorInfo => {\n const batchSize = x.shape[0];\n const inSize = x.shape[1];\n const windowSize =\n backend_util.segment_util.segOpComputeOptimalWindowSize(\n inSize, numSegments);\n const segOpInfo = {windowSize, inSize, batchSize, numSegments};\n const program = new SegmentOpProgram(segOpInfo, segOpType);\n const output = backend.compileAndRun(program, [x, segmentIds], dtype);\n toDispose.push(output);\n // No need to run another GPGPU program.\n if (output.shape[1] === numSegments) {\n return output;\n }\n const rangeInfo = range({\n backend,\n attrs: {start: 0, stop: numSegments, step: 1, dtype: 'float32'}\n });\n const tileInfo = tile({\n inputs: {x: rangeInfo},\n backend,\n attrs: {reps: [inSize / windowSize]}\n });\n\n toDispose.push(rangeInfo);\n toDispose.push(tileInfo);\n\n const result =\n segOpCompute(output, segOpType, tileInfo, dtype, numSegments);\n return result;\n };\n\n const segOpResult = segOpCompute(\n a2D, 'unsortedSegmentSum', segmentIds, outputDType, numSegments);\n\n const reshaped =\n reshape({inputs: {x: segOpResult}, backend, attrs: {shape: outShape}});\n\n let result = reshaped;\n if (permutation != null) {\n toDispose.push(reshaped);\n const perm = backend_util.getUndoAxesPermutation(permutation);\n result = transpose({inputs: {x: result}, backend, attrs: {perm}});\n }\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n return result;\n}\n\nexport const unsortedSegmentSumConfig: KernelConfig = {\n kernelName: UnsortedSegmentSum,\n backendName: 'webgl',\n kernelFunc: unsortedSegmentSum as {} as KernelFunc\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {KernelConfig, registerKernel} from '@tensorflow/tfjs-core';\n\nimport {_fusedMatMulConfig} from './kernels/_FusedMatMul';\nimport {absConfig} from './kernels/Abs';\nimport {acosConfig} from './kernels/Acos';\nimport {acoshConfig} from './kernels/Acosh';\nimport {addConfig} from './kernels/Add';\nimport {addNConfig} from './kernels/AddN';\nimport {allConfig} from './kernels/All';\nimport {anyConfig} from './kernels/Any';\nimport {argMaxConfig} from './kernels/ArgMax';\nimport {argMinConfig} from './kernels/ArgMin';\nimport {asinConfig} from './kernels/Asin';\nimport {asinhConfig} from './kernels/Asinh';\nimport {atanConfig} from './kernels/Atan';\nimport {atan2Config} from './kernels/Atan2';\nimport {atanhConfig} from './kernels/Atanh';\nimport {avgPoolConfig} from './kernels/AvgPool';\nimport {avgPool3DConfig} from './kernels/AvgPool3D';\nimport {avgPoolGrad3DConfig} from './kernels/AvgPool3DGrad';\nimport {avgPoolGradConfig} from './kernels/AvgPoolGrad';\nimport {batchMatMulConfig} from './kernels/BatchMatMul';\nimport {batchNormConfig} from './kernels/BatchNorm';\nimport {batchToSpaceNDConfig} from './kernels/BatchToSpaceND';\nimport {bincountConfig} from './kernels/Bincount';\nimport {castConfig} from './kernels/Cast';\nimport {ceilConfig} from './kernels/Ceil';\nimport {clipByValueConfig} from './kernels/ClipByValue';\nimport {complexConfig} from './kernels/Complex';\nimport {complexAbsConfig} from './kernels/ComplexAbs';\nimport {concatConfig} from './kernels/Concat';\nimport {conv2DConfig} from './kernels/Conv2D';\nimport {conv2DBackpropFilterConfig} from './kernels/Conv2DBackpropFilter';\nimport {conv2DBackpropInputConfig} from './kernels/Conv2DBackpropInput';\nimport {conv3DConfig} from './kernels/Conv3D';\nimport {conv3DBackpropFilterV2Config} from './kernels/Conv3DBackpropFilterV2';\nimport {conv3DBackpropInputConfig} from './kernels/Conv3DBackpropInputV2';\nimport {cosConfig} from './kernels/Cos';\nimport {coshConfig} from './kernels/Cosh';\nimport {cropAndResizeConfig} from './kernels/CropAndResize';\nimport {cumsumConfig} from './kernels/Cumsum';\nimport {denseBincountConfig} from './kernels/DenseBincount';\nimport {depthToSpaceConfig} from './kernels/DepthToSpace';\nimport {depthwiseConv2dNativeConfig} from './kernels/DepthwiseConv2dNative';\nimport {depthwiseConv2dNativeBackpropFilterConfig} from './kernels/DepthwiseConv2dNativeBackpropFilter';\nimport {depthwiseConv2dNativeBackpropInputConfig} from './kernels/DepthwiseConv2dNativeBackpropInput';\nimport {diagConfig} from './kernels/Diag';\nimport {dilation2DConfig} from './kernels/Dilation2D';\nimport {einsumConfig} from './kernels/Einsum';\nimport {eluConfig} from './kernels/Elu';\nimport {eluGradConfig} from './kernels/EluGrad';\nimport {equalConfig} from './kernels/Equal';\nimport {erfConfig} from './kernels/Erf';\nimport {expConfig} from './kernels/Exp';\nimport {expandDimsConfig} from './kernels/ExpandDims';\nimport {expm1Config} from './kernels/Expm1';\nimport {fftConfig} from './kernels/FFT';\nimport {fillConfig} from './kernels/Fill';\nimport {flipLeftRightConfig} from './kernels/FlipLeftRight';\nimport {floorConfig} from './kernels/Floor';\nimport {floorDivConfig} from './kernels/FloorDiv';\nimport {fromPixelsConfig} from './kernels/FromPixels';\nimport {fusedConv2DConfig} from './kernels/FusedConv2D';\nimport {fusedDepthwiseConv2DConfig} from './kernels/FusedDepthwiseConv2D';\nimport {gatherNdConfig} from './kernels/GatherNd';\nimport {gatherV2Config} from './kernels/GatherV2';\nimport {greaterConfig} from './kernels/Greater';\nimport {greaterEqualConfig} from './kernels/GreaterEqual';\nimport {identityConfig} from './kernels/Identity';\nimport {ifftConfig} from './kernels/IFFT';\nimport {imagConfig} from './kernels/Imag';\nimport {isFiniteConfig} from './kernels/IsFinite';\nimport {isInfConfig} from './kernels/IsInf';\nimport {isNaNConfig} from './kernels/IsNaN';\nimport {leakyReluConfig} from './kernels/LeakyRelu';\nimport {lessConfig} from './kernels/Less';\nimport {lessEqualConfig} from './kernels/LessEqual';\nimport {linSpaceConfig} from './kernels/LinSpace';\nimport {logConfig} from './kernels/Log';\nimport {log1pConfig} from './kernels/Log1p';\nimport {logicalAndConfig} from './kernels/LogicalAnd';\nimport {logicalNotConfig} from './kernels/LogicalNot';\nimport {logicalOrConfig} from './kernels/LogicalOr';\nimport {LRNConfig} from './kernels/LRN';\nimport {LRNGradConfig} from './kernels/LRNGrad';\nimport {maxConfig} from './kernels/Max';\nimport {maximumConfig} from './kernels/Maximum';\nimport {maxPoolConfig} from './kernels/MaxPool';\nimport {maxPool3DConfig} from './kernels/MaxPool3D';\nimport {maxPoolGrad3DConfig} from './kernels/MaxPool3DGrad';\nimport {maxPoolGradConfig} from './kernels/MaxPoolGrad';\nimport {maxPoolWithArgmaxConfig} from './kernels/MaxPoolWithArgmax';\nimport {meanConfig} from './kernels/Mean';\nimport {minConfig} from './kernels/Min';\nimport {minimumConfig} from './kernels/Minimum';\nimport {mirrorPadConfig} from './kernels/MirrorPad';\nimport {modConfig} from './kernels/Mod';\nimport {multinomialConfig} from './kernels/Multinomial';\nimport {multiplyConfig} from './kernels/Multiply';\nimport {negConfig} from './kernels/Neg';\nimport {nonMaxSuppressionV3Config} from './kernels/NonMaxSuppressionV3';\nimport {nonMaxSuppressionV4Config} from './kernels/NonMaxSuppressionV4';\nimport {nonMaxSuppressionV5Config} from './kernels/NonMaxSuppressionV5';\nimport {notEqualConfig} from './kernels/NotEqual';\nimport {oneHotConfig} from './kernels/OneHot';\nimport {onesLikeConfig} from './kernels/OnesLike';\nimport {packConfig} from './kernels/Pack';\nimport {padV2Config} from './kernels/PadV2';\nimport {powConfig} from './kernels/Pow';\nimport {preluConfig} from './kernels/Prelu';\nimport {prodConfig} from './kernels/Prod';\nimport {rangeConfig} from './kernels/Range';\nimport {realConfig} from './kernels/Real';\nimport {realDivConfig} from './kernels/RealDiv';\nimport {reciprocalConfig} from './kernels/Reciprocal';\nimport {reluConfig} from './kernels/Relu';\nimport {relu6Config} from './kernels/Relu6';\nimport {reshapeConfig} from './kernels/Reshape';\nimport {resizeBilinearConfig} from './kernels/ResizeBilinear';\nimport {resizeBilinearGradConfig} from './kernels/ResizeBilinearGrad';\nimport {resizeNearestNeighborConfig} from './kernels/ResizeNearestNeighbor';\nimport {resizeNearestNeighborGradConfig} from './kernels/ResizeNearestNeighborGrad';\nimport {reverseConfig} from './kernels/Reverse';\nimport {rotateWithOffsetConfig} from './kernels/RotateWithOffset';\nimport {roundConfig} from './kernels/Round';\nimport {rsqrtConfig} from './kernels/Rsqrt';\nimport {scatterNdConfig} from './kernels/ScatterNd';\nimport {selectConfig} from './kernels/Select';\nimport {seluConfig} from './kernels/Selu';\nimport {sigmoidConfig} from './kernels/Sigmoid';\nimport {signConfig} from './kernels/Sign';\nimport {sinConfig} from './kernels/Sin';\nimport {sinhConfig} from './kernels/Sinh';\nimport {sliceConfig} from './kernels/Slice';\nimport {softmaxConfig} from './kernels/Softmax';\nimport {softplusConfig} from './kernels/Softplus';\nimport {spaceToBatchNDConfig} from './kernels/SpaceToBatchND';\nimport {sparseFillEmptyRowsConfig} from './kernels/SparseFillEmptyRows';\nimport {sparseReshapeConfig} from './kernels/SparseReshape';\nimport {sparseSegmentMeanConfig} from './kernels/SparseSegmentMean';\nimport {sparseSegmentSumConfig} from './kernels/SparseSegmentSum';\nimport {sparseToDenseConfig} from './kernels/SparseToDense';\nimport {splitVConfig} from './kernels/SplitV';\nimport {sqrtConfig} from './kernels/Sqrt';\nimport {squareConfig} from './kernels/Square';\nimport {squaredDifferenceConfig} from './kernels/SquaredDifference';\nimport {stepConfig} from './kernels/Step';\nimport {stridedSliceConfig} from './kernels/StridedSlice';\nimport {stringNGramsConfig} from './kernels/StringNGrams';\nimport {stringSplitConfig} from './kernels/StringSplit';\nimport {stringToHashBucketFastConfig} from './kernels/StringToHashBucketFast';\nimport {subConfig} from './kernels/Sub';\nimport {sumConfig} from './kernels/Sum';\nimport {tanConfig} from './kernels/Tan';\nimport {tanhConfig} from './kernels/Tanh';\nimport {tileConfig} from './kernels/Tile';\nimport {topKConfig} from './kernels/TopK';\nimport {transformConfig} from './kernels/Transform';\nimport {transposeConfig} from './kernels/Transpose';\nimport {uniqueConfig} from './kernels/Unique';\nimport {unpackConfig} from './kernels/Unpack';\nimport {unsortedSegmentSumConfig} from './kernels/UnsortedSegmentSum';\nimport {zerosLikeConfig} from './kernels/ZerosLike';\n\n// List all kernel configs here\nconst kernelConfigs: KernelConfig[] = [\n LRNConfig,\n LRNGradConfig,\n _fusedMatMulConfig,\n absConfig,\n acosConfig,\n acoshConfig,\n addConfig,\n addNConfig,\n allConfig,\n anyConfig,\n argMaxConfig,\n argMinConfig,\n asinConfig,\n asinhConfig,\n atan2Config,\n atanConfig,\n atanhConfig,\n avgPool3DConfig,\n avgPoolConfig,\n avgPoolGrad3DConfig,\n avgPoolGradConfig,\n batchMatMulConfig,\n batchNormConfig,\n batchToSpaceNDConfig,\n bincountConfig,\n castConfig,\n ceilConfig,\n clipByValueConfig,\n complexAbsConfig,\n complexConfig,\n concatConfig,\n conv2DBackpropFilterConfig,\n conv2DBackpropInputConfig,\n conv2DConfig,\n conv3DBackpropFilterV2Config,\n conv3DBackpropInputConfig,\n conv3DConfig,\n cosConfig,\n coshConfig,\n cropAndResizeConfig,\n cumsumConfig,\n denseBincountConfig,\n depthToSpaceConfig,\n depthwiseConv2dNativeBackpropFilterConfig,\n depthwiseConv2dNativeBackpropInputConfig,\n depthwiseConv2dNativeConfig,\n diagConfig,\n dilation2DConfig,\n einsumConfig,\n eluConfig,\n eluGradConfig,\n equalConfig,\n erfConfig,\n expConfig,\n expandDimsConfig,\n expm1Config,\n fftConfig,\n fillConfig,\n flipLeftRightConfig,\n floorConfig,\n floorDivConfig,\n fromPixelsConfig,\n fusedConv2DConfig,\n fusedDepthwiseConv2DConfig,\n gatherNdConfig,\n gatherV2Config,\n greaterConfig,\n greaterEqualConfig,\n identityConfig,\n ifftConfig,\n imagConfig,\n isFiniteConfig,\n isInfConfig,\n isNaNConfig,\n leakyReluConfig,\n lessConfig,\n lessEqualConfig,\n linSpaceConfig,\n log1pConfig,\n logConfig,\n logicalAndConfig,\n logicalNotConfig,\n logicalOrConfig,\n maxConfig,\n maxPool3DConfig,\n maxPoolConfig,\n maxPoolGrad3DConfig,\n maxPoolGradConfig,\n maxPoolWithArgmaxConfig,\n maximumConfig,\n meanConfig,\n minConfig,\n minimumConfig,\n mirrorPadConfig,\n modConfig,\n multinomialConfig,\n multiplyConfig,\n negConfig,\n nonMaxSuppressionV3Config,\n nonMaxSuppressionV4Config,\n nonMaxSuppressionV5Config,\n notEqualConfig,\n oneHotConfig,\n onesLikeConfig,\n packConfig,\n padV2Config,\n powConfig,\n preluConfig,\n prodConfig,\n rangeConfig,\n realConfig,\n realDivConfig,\n reciprocalConfig,\n relu6Config,\n reluConfig,\n reshapeConfig,\n resizeBilinearConfig,\n resizeBilinearGradConfig,\n resizeNearestNeighborConfig,\n resizeNearestNeighborGradConfig,\n reverseConfig,\n rotateWithOffsetConfig,\n roundConfig,\n rsqrtConfig,\n scatterNdConfig,\n selectConfig,\n seluConfig,\n sigmoidConfig,\n signConfig,\n sinConfig,\n sinhConfig,\n sliceConfig,\n softmaxConfig,\n softplusConfig,\n spaceToBatchNDConfig,\n sparseFillEmptyRowsConfig,\n sparseReshapeConfig,\n sparseSegmentMeanConfig,\n sparseSegmentSumConfig,\n sparseToDenseConfig,\n splitVConfig,\n sqrtConfig,\n squareConfig,\n squaredDifferenceConfig,\n stepConfig,\n stridedSliceConfig,\n stringNGramsConfig,\n stringSplitConfig,\n stringToHashBucketFastConfig,\n subConfig,\n sumConfig,\n tanConfig,\n tanhConfig,\n tileConfig,\n topKConfig,\n transformConfig,\n transposeConfig,\n uniqueConfig,\n unpackConfig,\n unsortedSegmentSumConfig,\n zerosLikeConfig\n];\n\nfor (const kernelConfig of kernelConfigs) {\n registerKernel(kernelConfig);\n}\n"],"names":["util","env","device_util","shader_util.getLogicalCoordinatesFromFlatIndex","shader_util.getFlatIndexFrom3D","createVertexShader","webgl_util.createVertexShader","webgl_util.createStaticVertexBuffer","webgl_util.createStaticIndexBuffer","webgl_util.validateTextureSize","webgl_util.createTexture","webgl_util.callAndCheck","webgl_util.bindVertexBufferToProgramAttribute","tex_util.getUnpackedArraySizeFromMatrixSize","tex_util.getPackedRGBAArraySizeFromMatrixShape","webgl_util.getExtensionOrThrow","webgl_util.hasExtension","gpgpu_util.createVertexBuffer","gpgpu_util.createIndexBuffer","webgl_util.createFramebuffer","tex_util.getTextureConfig","gpgpu_util.createFloat32MatrixTexture","gpgpu_util.createFloat16MatrixTexture","gpgpu_util.createUnsignedBytesMatrixTexture","gpgpu_util.uploadPixelDataToTexture","gpgpu_util.uploadDenseMatrixToTexture","gpgpu_util.createFloat16PackedMatrixTexture","gpgpu_util.createPackedMatrixTexture","webgl_util.unbindColorTextureFromFramebuffer","gpgpu_util.downloadByteEncodedFloatMatrixFromOutputTexture","gpgpu_util.downloadPackedMatrixFromBuffer","gpgpu_util.downloadFloat32MatrixFromBuffer","gpgpu_util.createBufferFromOutputTexture","gpgpu_util.downloadMatrixFromPackedOutputTexture","webgl_util.createFragmentShader","gpgpu_util.createVertexShader","webgl_util.createProgram","webgl_util.linkProgram","webgl_util.validateProgram","gpgpu_util.bindVertexProgramAttributeStreams","webgl_util.getProgramUniformLocationOrThrow","webgl_util.getProgramUniformLocation","webgl_util.bindTextureToProgramUniformSampler","webgl_util.validateFramebuffer","webgl_util.bindColorTextureToFramebuffer","shader_compiler.makeShader","backend_util","buffer","upcastType","slice_util","TensorBuffer","LINEAR","ELU","RELU","RELU6","SIGMOID","kernel_impls","tslib_1.__extends","DataStorage","engine","unary_op.CLONE","tex_util.getDenseTexShape","webgl_util.canBeRepresented","webgl_util.getShapeAs3D","unary_op.ABS","webgl_util.getBatchDim","webgl_util.getRowsCols","tex_util.PackingScheme","webgl_util.isReshapeFree","gpgpu_math.makeShaderKey","gpgpu_math.compileProgram","gpgpu_math.runProgram","tidy","scalar","webgl_util.getTextureShapeFromLogicalShape","KernelBackend","registerBackend","CHECK_NAN_SNIPPET","Identity","Complex","LeakyRelu","Prelu","unary_packed_op.LINEAR","unary_op.LINEAR","unary_packed_op.RELU","unary_op.RELU","unary_packed_op.ELU","unary_op.ELU","unary_packed_op.RELU6","unary_op.RELU6","unary_packed_op.SIGMOID","unary_op.SIGMOID","binaryop_complex_gpu.COMPLEX_MULTIPLY","Multiply","Reshape","transposeImpl","sumOutType","Sum","cpuTranspose","Transpose","_FusedMatMul","ABS","Abs","Acos","Acosh","cpuAdd","Add","AddN","All","Any","ArgMax","ArgMin","Asin","Asinh","Atan","Atan2","Atanh","AvgPool","AvgPool3D","AvgPool3DGrad","AvgPoolGrad","BatchMatMul","FusedBatchNorm","Slice","BatchToSpaceND","Bincount","NotEqual","Real","tf.zeros","Cast","Ceil","ClipByValue","ComplexAbs","Imag","concatImpl","Concat","Conv2D","Conv2DBackpropFilter","Conv2DBackpropInput","Conv3D","Conv3DBackpropFilterV2","Conv3DBackpropInputV2","Cos","Cosh","CropAndResize","getCoords","Cumsum","DenseBincount","DepthToSpace","DepthwiseConv2dNative","DepthwiseConv2dNativeBackpropFilter","DepthwiseConv2dNativeBackpropInput","Diag","Dilation2D","Einsum","Elu","EluGrad","Equal","Erf","Exp","ExpandDims","Expm1","FFT","Fill","FlipLeftRight","Floor","FloorDiv","FromPixels","FusedConv2D","FusedDepthwiseConv2D","GatherNd","getSourceCoords","GatherV2","Greater","GreaterEqual","IFFT","IsFinite","IsInf","IsNan","Less","LessEqual","LinSpace","Log","Log1p","LogicalAnd","LogicalNot","LogicalOr","LRN","LRNGrad","maxImpl","Max","CHECK_NAN_SNIPPET_PACKED","Maximum","MaxPool","MaxPool3D","MaxPool3DGrad","MaxPoolGrad","MaxPoolWithArgmax","Mean","Min","Minimum","MirrorPad","Mod","RealDiv","cpuSub","Sub","Softmax","Multinomial","Neg","NonMaxSuppressionV3","NonMaxSuppressionV4","NonMaxSuppressionV5","OneHot","ZerosLike","OnesLike","Pack","PadV2","Pow","Prod","Range","Reciprocal","Relu","Relu6","ResizeBilinear","ResizeBilinearGrad","ResizeNearestNeighbor","ResizeNearestNeighborGrad","Reverse","RotateWithOffset","Round","Rsqrt","ScatterNd","Select","Selu","Sigmoid","Sign","Sin","Sinh","Softplus","SpaceToBatchND","SparseFillEmptyRows","SparseReshape","SparseSegmentMean","SparseSegmentSum","SparseToDense","SplitV","Sqrt","Square","SquaredDifference","Step","StridedSlice","StringNGrams","StringSplit","StringToHashBucketFast","Tan","Tanh","Tile","TopK","Transform","Unique","Unpack","UnsortedSegmentSum","registerKernel"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAA;;;;;;;;;;;;;;;;IAiBA,IAAM,QAAQ,GAA2C,EAAE,CAAC;IAE5D,IAAM,gBAAgB,GAA2B;QAC/C,KAAK,EAAE,KAAK;QACZ,SAAS,EAAE,KAAK;QAChB,kBAAkB,EAAE,KAAK;QACzB,qBAAqB,EAAE,KAAK;QAC5B,KAAK,EAAE,KAAK;QACZ,OAAO,EAAE,KAAK;QACd,4BAA4B,EAAE,IAAI;KACnC,CAAC;aAMc,eAAe,C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AAU;QACV,aAAa;QACb,UAAU;QACV,SAAS;QACT,UAAU;QACV,WAAW;QACX,aAAa;QACb,cAAc;QACd,oBAAoB;QACpB,yBAAyB;QACzB,mBAAmB;QACnB,uBAAuB;QACvB,sBAAsB;QACtB,mBAAmB;QACnB,YAAY;QACZ,UAAU;QACV,YAAY;QACZ,uBAAuB;QACvB,UAAU;QACV,kBAAkB;QAClB,kBAAkB;QAClB,iBAAiB;QACjB,4BAA4B;QAC5B,SAAS;QACT,SAAS;QACT,SAAS;QACT,UAAU;QACV,UAAU;QACV,UAAU;QACV,eAAe;QACf,eAAe;QACf,YAAY;QACZ,YAAY;QACZ,wBAAwB;QACxB,eAAe;KAChB,CAAC;IAEF,KAA2B,UAAa,EAAb,+BAAa,EAAb,2BAAa,EAAb,IAAa,EAAE;QAArC,IAAM,YAAY,sBAAA;QACrBC,iBAAc,CAAC,YAAY,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;"}
\ No newline at end of file
diff --git a/thirdparty/tfjs/tf-converter.js b/thirdparty/tfjs/tf-converter.js
new file mode 100644
index 0000000..795805a
--- /dev/null
+++ b/thirdparty/tfjs/tf-converter.js
@@ -0,0 +1,8058 @@
+/**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tensorflow/tfjs-core'), require('@tensorflow/tfjs-core/dist/ops/ops_for_converter')) :
+ typeof define === 'function' && define.amd ? define(['exports', '@tensorflow/tfjs-core', '@tensorflow/tfjs-core/dist/ops/ops_for_converter'], factory) :
+ (global = global || self, factory(global.tf = global.tf || {}, global.tf, global.tf));
+}(this, (function (exports, tfc, tfOps) { 'use strict';
+
+ /*! *****************************************************************************
+ Copyright (c) Microsoft Corporation.
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ PERFORMANCE OF THIS SOFTWARE.
+ ***************************************************************************** */
+
+ var __assign = function() {
+ __assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+ };
+
+ function __awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ }
+
+ function __generator(thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (_) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+ }
+
+ function __read(o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+ }
+
+ function __spread() {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(__read(arguments[i]));
+ return ar;
+ }
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * =============================================================================
+ */
+ /** DataType enum. */
+ var DataType;
+ (function (DataType) {
+ DataType[DataType["DT_INVALID"] = 0] = "DT_INVALID";
+ DataType[DataType["DT_FLOAT"] = 1] = "DT_FLOAT";
+ DataType[DataType["DT_DOUBLE"] = 2] = "DT_DOUBLE";
+ DataType[DataType["DT_INT32"] = 3] = "DT_INT32";
+ DataType[DataType["DT_UINT8"] = 4] = "DT_UINT8";
+ DataType[DataType["DT_INT16"] = 5] = "DT_INT16";
+ DataType[DataType["DT_INT8"] = 6] = "DT_INT8";
+ DataType[DataType["DT_STRING"] = 7] = "DT_STRING";
+ DataType[DataType["DT_COMPLEX64"] = 8] = "DT_COMPLEX64";
+ DataType[DataType["DT_INT64"] = 9] = "DT_INT64";
+ DataType[DataType["DT_BOOL"] = 10] = "DT_BOOL";
+ DataType[DataType["DT_QINT8"] = 11] = "DT_QINT8";
+ DataType[DataType["DT_QUINT8"] = 12] = "DT_QUINT8";
+ DataType[DataType["DT_QINT32"] = 13] = "DT_QINT32";
+ DataType[DataType["DT_BFLOAT16"] = 14] = "DT_BFLOAT16";
+ DataType[DataType["DT_FLOAT_REF"] = 101] = "DT_FLOAT_REF";
+ DataType[DataType["DT_DOUBLE_REF"] = 102] = "DT_DOUBLE_REF";
+ DataType[DataType["DT_INT32_REF"] = 103] = "DT_INT32_REF";
+ DataType[DataType["DT_UINT8_REF"] = 104] = "DT_UINT8_REF";
+ DataType[DataType["DT_INT16_REF"] = 105] = "DT_INT16_REF";
+ DataType[DataType["DT_INT8_REF"] = 106] = "DT_INT8_REF";
+ DataType[DataType["DT_STRING_REF"] = 107] = "DT_STRING_REF";
+ DataType[DataType["DT_COMPLEX64_REF"] = 108] = "DT_COMPLEX64_REF";
+ DataType[DataType["DT_INT64_REF"] = 109] = "DT_INT64_REF";
+ DataType[DataType["DT_BOOL_REF"] = 110] = "DT_BOOL_REF";
+ DataType[DataType["DT_QINT8_REF"] = 111] = "DT_QINT8_REF";
+ DataType[DataType["DT_QUINT8_REF"] = 112] = "DT_QUINT8_REF";
+ DataType[DataType["DT_QINT32_REF"] = 113] = "DT_QINT32_REF";
+ DataType[DataType["DT_BFLOAT16_REF"] = 114] = "DT_BFLOAT16_REF";
+ })(DataType || (DataType = {}));
+ var SaverDef;
+ (function (SaverDef) {
+ /** CheckpointFormatVersion enum. */
+ var CheckpointFormatVersion;
+ (function (CheckpointFormatVersion) {
+ CheckpointFormatVersion[CheckpointFormatVersion["LEGACY"] = 0] = "LEGACY";
+ CheckpointFormatVersion[CheckpointFormatVersion["V1"] = 1] = "V1";
+ CheckpointFormatVersion[CheckpointFormatVersion["V2"] = 2] = "V2";
+ })(CheckpointFormatVersion = SaverDef.CheckpointFormatVersion || (SaverDef.CheckpointFormatVersion = {}));
+ })(SaverDef || (SaverDef = {}));
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var CUSTOM_OPS = {};
+ /**
+ * Register an Op for graph model executor. This allow you to register
+ * TensorFlow custom op or override existing op.
+ *
+ * Here is an example of registering a new MatMul Op.
+ * ```js
+ * const customMatmul = (node) =>
+ * tf.matMul(
+ * node.inputs[0], node.inputs[1],
+ * node.attrs['transpose_a'], node.attrs['transpose_b']);
+ *
+ * tf.registerOp('MatMul', customMatmul);
+ * ```
+ * The inputs and attrs of the node object is based on the TensorFlow op
+ * registry.
+ *
+ * @param name The Tensorflow Op name.
+ * @param opFunc An op function which is called with the current graph node
+ * during execution and needs to return a tensor or a list of tensors. The node
+ * has the following attributes:
+ * - attr: A map from attribute name to its value
+ * - inputs: A list of input tensors
+ *
+ * @doc {heading: 'Models', subheading: 'Op Registry'}
+ */
+ function registerOp(name, opFunc) {
+ var opMapper = {
+ tfOpName: name,
+ category: 'custom',
+ inputs: [],
+ attrs: [],
+ customExecutor: opFunc
+ };
+ CUSTOM_OPS[name] = opMapper;
+ }
+ /**
+ * Retrieve the OpMapper object for the registered op.
+ *
+ * @param name The Tensorflow Op name.
+ *
+ * @doc {heading: 'Models', subheading: 'Op Registry'}
+ */
+ function getRegisteredOp(name) {
+ return CUSTOM_OPS[name];
+ }
+ /**
+ * Deregister the Op for graph model executor.
+ *
+ * @param name The Tensorflow Op name.
+ *
+ * @doc {heading: 'Models', subheading: 'Op Registry'}
+ */
+ function deregisterOp(name) {
+ delete CUSTOM_OPS[name];
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function getParamValue(paramName, node, tensorMap, context, resourceManager) {
+ var inputParam = node.inputParams[paramName];
+ if (inputParam && inputParam.inputIndexStart !== undefined) {
+ var start = inputParam.inputIndexStart;
+ var end = inputParam.inputIndexEnd === 0 ?
+ undefined :
+ (inputParam.inputIndexEnd === undefined ? start + 1 :
+ inputParam.inputIndexEnd);
+ if (inputParam.type === 'tensor') {
+ return getTensor(node.inputNames[inputParam.inputIndexStart], tensorMap, context, resourceManager);
+ }
+ if (inputParam.type === 'tensors') {
+ var inputs = node.inputNames.slice(start, end);
+ return inputs.map(function (name) { return getTensor(name, tensorMap, context, resourceManager); });
+ }
+ var tensor = getTensor(node.inputNames.slice(start)[0], tensorMap, context, resourceManager);
+ var data = tensor.dataSync();
+ return inputParam.type === 'number' ?
+ data[0] :
+ tfc.util.toNestedArray(tensor.shape, data);
+ }
+ var attrParam = node.attrParams[paramName];
+ return attrParam && attrParam.value;
+ }
+ /**
+ * Retrieve the tensor from tensorsMap based on input name.
+ * @param name Node input name
+ * @param tensorsMap Tensors map keyed by the node
+ * @param context contains tensors and information for running the current node.
+ * @param resourceManager Optional. Contains global resources of the model.
+ */
+ function getTensor(name, tensorsMap, context, resourceManager) {
+ var _a = __read(parseNodeName(name), 2), nodeName = _a[0], index = _a[1];
+ if (resourceManager != null) {
+ var tensor = resourceManager.getHashTableHandleByName(nodeName);
+ if (tensor != null) {
+ return tensor;
+ }
+ }
+ var contextId = context.currentContextIds.find(function (contextId) {
+ return !!tensorsMap[getNodeNameWithContextId(nodeName, contextId)];
+ });
+ return contextId !== undefined ?
+ tensorsMap[getNodeNameWithContextId(nodeName, contextId)][index] :
+ undefined;
+ }
+ /**
+ * Retrieve the tensors based on input name for current context.
+ * @param name Node input name
+ * @param tensorsMap Tensors map keyed by the node
+ */
+ function getTensorsForCurrentContenxt(name, tensorsMap, context) {
+ return tensorsMap[getNodeNameWithContextId(name, context.currentContextId)];
+ }
+ /**
+ * Returns the node name, outputName and index from the Node input name.
+ * @param inputName The input name of the node, in format of
+ * node_name:output_index, i.e. MatMul:0, if the output_index is not set, it is
+ * default to 0.
+ * If the input name contains output name i.e. StringSplit:indices:0, it will
+ * return ['StringSplit', 0, 'indices'].
+ */
+ function getNodeNameAndIndex(inputName, context) {
+ var _a = __read(parseNodeName(inputName), 3), nodeName = _a[0], index = _a[1], outputName = _a[2];
+ return [
+ getNodeNameWithContextId(nodeName, context && context.currentContextId),
+ index, outputName
+ ];
+ }
+ function getNodeNameWithContextId(name, contextId) {
+ return !!contextId ? name + "-" + contextId : name;
+ }
+ function parseNodeName(name) {
+ var parts = name.split(':');
+ if (parts.length === 1) {
+ return [name, 0, undefined];
+ }
+ var nodeName = parts[0];
+ var outputName = parts.length === 3 ? parts[1] : undefined;
+ var index = Number(parts[parts.length - 1]);
+ return [nodeName, index, outputName];
+ }
+ function getPadding(node, tensorMap, context) {
+ var pad = getParamValue('pad', node, tensorMap, context);
+ if (pad === 'explicit') {
+ // This is 1d array, we need to convert it to 2d array
+ pad = getParamValue('explicitPaddings', node, tensorMap, context);
+ var explicitPadding = [[0, 0], [0, 0], [0, 0], [0, 0]];
+ for (var i = 0; i < 4; i++) {
+ explicitPadding[i][0] = pad[i * 2];
+ explicitPadding[i][1] = pad[i * 2 + 1];
+ }
+ return explicitPadding;
+ }
+ return pad;
+ }
+ /**
+ * Reuse the tensor if it is marked as keep, otherwise clone the tensor to
+ * avoid disposal. This is important for TensorArray and TensorList ops, since
+ * internally they use a tensor as the id for TensorArray and TensorList, and
+ * to simplify lookup, they also use Tensor.id as the key to the internal map.
+ * These id tensors have been marked as kept in the backend, we need avoid clone
+ * them in order to create new Tensor.id.
+ * @param tensor
+ */
+ function cloneTensor(tensor) {
+ return tensor.kept ? tensor : tfc.clone(tensor);
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json = [
+ {
+ 'tfOpName': 'Add',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'AddV2',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'AddN',
+ 'category': 'arithmetic',
+ 'inputs': [{ 'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors' }]
+ },
+ {
+ 'tfOpName': 'BiasAdd',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Sub',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'RealDiv',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Div',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'DivNoNan',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'FloorDiv',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Mul',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Maximum',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' }
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Minimum',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' }
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Pow',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'SquaredDifference',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Mod',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'FloorMod',
+ 'category': 'arithmetic',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [{
+ 'tfName': 'T',
+ 'name': 'dtype',
+ 'type': 'dtype',
+ 'notSupported': true
+ }]
+ }
+ ];
+
+ var arithmetic = {
+ __proto__: null,
+ json: json
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$1 = [
+ {
+ 'tfOpName': 'Abs',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Acos',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Asin',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Atan',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Atan2',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'y', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Ceil',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'ClipByValue',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'clipValueMin', 'type': 'number' },
+ { 'start': 2, 'name': 'clipValueMax', 'type': 'number' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Complex',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'real', 'type': 'tensor' },
+ { 'start': 1, 'name': 'imag', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'ComplexAbs',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Cos',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Cosh',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Elu',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Exp',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Floor',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Log',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Imag',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
+ 'tfName': 'Tout',
+ 'name': 'outputType',
+ 'type': 'dtype',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Neg',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Real',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
+ 'tfName': 'Tout',
+ 'name': 'outputType',
+ 'type': 'dtype',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Prelu',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'alpha', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Relu',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Relu6',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Selu',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Sigmoid',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Sin',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Sinh',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Sqrt',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Rsqrt',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Square',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Tan',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Tanh',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Sign',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Round',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Expm1',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Log1p',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Reciprocal',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Softplus',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Asinh',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Acosh',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Atanh',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Erf',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Prod',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axes', 'type': 'number[]' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'keep_dims',
+ 'name': 'keepDims',
+ 'type': 'bool',
+ 'notSupported': true
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'LeakyRelu',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'alpha',
+ 'name': 'alpha',
+ 'type': 'number',
+ 'defaultValue': 0.2
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'IsNan',
+ 'category': 'basic_math',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [{
+ 'tfName': 'T',
+ 'name': 'dtype',
+ 'type': 'dtype',
+ 'notSupported': true
+ }]
+ }
+ ];
+
+ var basicMath = {
+ __proto__: null,
+ json: json$1
+ };
+
+ var json$2 = [
+ {
+ 'tfOpName': 'EmptyTensorList',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'elementShape', 'type': 'shape' },
+ { 'start': 1, 'name': 'maxNumElements', 'type': 'number' },
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'LoopCond',
+ 'category': 'control',
+ 'inputs': [{ 'start': 0, 'name': 'pred', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'Switch',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'data', 'type': 'tensor' },
+ { 'start': 1, 'name': 'pred', 'type': 'tensor' }
+ ]
+ },
+ {
+ 'tfOpName': 'Merge',
+ 'category': 'control',
+ 'inputs': [{ 'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors' }]
+ },
+ {
+ 'tfOpName': 'Enter',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensor', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true },
+ { 'tfName': 'frame_name', 'name': 'frameName', 'type': 'string' },
+ { 'tfName': 'is_constant', 'name': 'isConstant', 'type': 'bool' }
+ ]
+ },
+ {
+ 'tfOpName': 'Exit',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensor', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'NextIteration',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensor', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'TensorArrayV3',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'size', 'type': 'number' },
+ ],
+ 'attrs': [
+ { 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' },
+ { 'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape' },
+ { 'tfName': 'dynamic_size', 'name': 'dynamicSize', 'type': 'bool' },
+ { 'tfName': 'clear_after_read', 'name': 'clearAfterRead', 'type': 'bool' },
+ {
+ 'tfName': 'identical_element_shapes',
+ 'name': 'identicalElementShapes',
+ 'type': 'bool'
+ },
+ { 'tfName': 'tensor_array_name', 'name': 'name', 'type': 'string' }
+ ]
+ },
+ {
+ 'tfOpName': 'TensorArrayWriteV3',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'index', 'type': 'number' },
+ { 'start': 2, 'name': 'tensor', 'type': 'tensor' },
+ { 'start': 3, 'name': 'flowIn', 'type': 'number' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'TensorArrayReadV3',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'index', 'type': 'number' },
+ { 'start': 2, 'name': 'flowIn', 'type': 'number' },
+ ],
+ 'attrs': [{
+ 'tfName': 'dtype',
+ 'name': 'dtype',
+ 'type': 'dtype',
+ 'notSupported': true
+ }]
+ },
+ {
+ 'tfOpName': 'TensorArrayGatherV3',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'number[]' },
+ { 'start': 2, 'name': 'flowIn', 'type': 'number' },
+ ],
+ 'attrs': [
+ { 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' },
+ { 'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape' }
+ ]
+ },
+ {
+ 'tfOpName': 'TensorArrayScatterV3',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'number[]' },
+ { 'start': 2, 'name': 'tensor', 'type': 'tensor' },
+ { 'start': 3, 'name': 'flowIn', 'type': 'number' },
+ ],
+ 'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorArrayConcatV3',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'flowIn', 'type': 'number' },
+ ],
+ 'attrs': [
+ { 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' }, {
+ 'tfName': 'element_shape_except0',
+ 'name': 'elementShapeExcept0',
+ 'type': 'shape',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'TensorArraySplitV3',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'tensor', 'type': 'tensor' },
+ { 'start': 2, 'name': 'lengths', 'type': 'number[]' },
+ { 'start': 3, 'name': 'flowIn', 'type': 'number' },
+ ],
+ 'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorArraySizeV3',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'flowIn', 'type': 'number' }
+ ]
+ },
+ {
+ 'tfOpName': 'TensorArrayCloseV3',
+ 'category': 'control',
+ 'inputs': [{ 'start': 0, 'name': 'tensorArrayId', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'StatelessIf',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'cond', 'type': 'tensor' },
+ { 'start': 1, 'end': 0, 'name': 'args', 'type': 'tensors' }
+ ],
+ 'attrs': [
+ { 'tfName': 'then_branch', 'name': 'thenBranch', 'type': 'func' },
+ { 'tfName': 'else_branch', 'name': 'elseBranch', 'type': 'func' }
+ ]
+ },
+ {
+ 'tfOpName': 'If',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'cond', 'type': 'tensor' },
+ { 'start': 1, 'end': 0, 'name': 'args', 'type': 'tensors' }
+ ],
+ 'attrs': [
+ { 'tfName': 'then_branch', 'name': 'thenBranch', 'type': 'func' },
+ { 'tfName': 'else_branch', 'name': 'elseBranch', 'type': 'func' }
+ ]
+ },
+ {
+ 'tfOpName': 'StatelessWhile',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'end': 0, 'name': 'args', 'type': 'tensors' },
+ ],
+ 'attrs': [
+ { 'tfName': 'cond', 'name': 'cond', 'type': 'func' },
+ { 'tfName': 'body', 'name': 'body', 'type': 'func' }
+ ]
+ },
+ {
+ 'tfOpName': 'While',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'end': 0, 'name': 'args', 'type': 'tensors' },
+ ],
+ 'attrs': [
+ { 'tfName': 'cond', 'name': 'cond', 'type': 'func' },
+ { 'tfName': 'body', 'name': 'body', 'type': 'func' }
+ ]
+ },
+ {
+ 'tfOpName': 'TensorListScatter',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensor', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'number[]' },
+ { 'start': 2, 'name': 'elementShape', 'type': 'shape' }
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorListScatterV2',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensor', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'number[]' },
+ { 'start': 2, 'name': 'elementShape', 'type': 'shape' },
+ { 'start': 3, 'name': 'numElements', 'type': 'number' },
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorListGather',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'number[]' },
+ { 'start': 2, 'name': 'elementShape', 'type': 'shape' },
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorListGetItem',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'index', 'type': 'number' },
+ { 'start': 2, 'name': 'elementShape', 'type': 'shape' },
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorListSetItem',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'index', 'type': 'number' },
+ { 'start': 2, 'name': 'tensor', 'type': 'tensor' },
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorListReserve',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'elementShape', 'type': 'shape' },
+ { 'start': 1, 'name': 'numElements', 'type': 'number' },
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorListFromTensor',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensor', 'type': 'tensor' },
+ { 'start': 1, 'name': 'elementShape', 'type': 'shape' }
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorListStack',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'elementShape', 'type': 'shape' },
+ ],
+ 'attrs': [
+ { 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' },
+ { 'tfName': 'num_elements', 'name': 'numElements', 'type': 'dtype' }
+ ]
+ },
+ {
+ 'tfOpName': 'TensorListSplit',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensor', 'type': 'tensor' },
+ { 'start': 1, 'name': 'elementShape', 'type': 'shape' },
+ { 'start': 2, 'name': 'lengths', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorListConcat',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape' },
+ { 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }
+ ]
+ },
+ {
+ 'tfOpName': 'TensorListPopBack',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'elementShape', 'type': 'shape' },
+ ],
+ 'attrs': [{ 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TensorListPushBack',
+ 'category': 'control',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensorListId', 'type': 'tensor' },
+ { 'start': 1, 'name': 'tensor', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype' }
+ ]
+ }
+ ];
+
+ var control = {
+ __proto__: null,
+ json: json$2
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$3 = [
+ {
+ 'tfOpName': 'AvgPool',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'notSupported': true
+ },
+ { 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'MaxPool',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'notSupported': true
+ },
+ { 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' }, {
+ 'tfName': 'explicit_paddings',
+ 'name': 'explicitPaddings',
+ 'type': 'number[]',
+ 'defaultValue': [],
+ 'notSupported': true
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'MaxPoolWithArgmax',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' },
+ { 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' }, {
+ 'tfName': 'include_batch_in_index',
+ 'name': 'includeBatchInIndex',
+ 'type': 'bool'
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'AvgPool3D',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'notSupported': true
+ },
+ { 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'MaxPool3D',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'notSupported': true
+ },
+ { 'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]' },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Conv1D',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'filter', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'stride', 'name': 'stride', 'type': 'number' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'defaultValue': 'NWC'
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
+ 'tfName': 'dilation',
+ 'name': 'dilation',
+ 'type': 'number',
+ 'defaultValue': 1
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Conv2D',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'filter', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true },
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' },
+ { 'tfName': 'useCudnnOnGpu', 'name': 'useCudnnOnGpu', 'type': 'bool' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'defaultValue': 'NHWC'
+ },
+ {
+ 'tfName': 'explicit_paddings',
+ 'name': 'explicitPaddings',
+ 'type': 'number[]',
+ 'defaultValue': []
+ },
+ { 'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': '_FusedConv2D',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'filter', 'type': 'tensor' },
+ { 'start': 2, end: 0, 'name': 'args', 'type': 'tensors' },
+ ],
+ 'attrs': [
+ { 'tfName': 'num_args', 'name': 'numArgs', 'type': 'number' },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true },
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'explicit_paddings',
+ 'name': 'explicitPaddings',
+ 'type': 'number[]',
+ 'defaultValue': []
+ },
+ {
+ 'tfName': 'use_cudnn_on_gpu',
+ 'name': 'useCudnnOnGpu',
+ 'type': 'bool',
+ 'defaultValue': true
+ },
+ {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'defaultValue': 'NHWC'
+ },
+ {
+ 'tfName': 'dilations',
+ 'name': 'dilations',
+ 'type': 'number[]',
+ 'defaultValue': [1, 1, 1, 1]
+ },
+ {
+ 'tfName': 'fused_ops',
+ 'name': 'fusedOps',
+ 'type': 'string[]',
+ 'defaultValue': []
+ },
+ {
+ 'tfName': 'epsilon',
+ 'name': 'epsilon',
+ 'type': 'number',
+ 'defaultValue': 0.0001
+ },
+ {
+ 'tfName': 'leakyrelu_alpha',
+ 'name': 'leakyreluAlpha',
+ 'type': 'number'
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Conv2DBackpropInput',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 2, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'filter', 'type': 'tensor' },
+ { 'start': 0, 'name': 'outputShape', 'type': 'number[]' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'notSupported': true
+ },
+ {
+ 'tfName': 'explicit_paddings',
+ 'name': 'explicitPaddings',
+ 'type': 'number[]',
+ 'defaultValue': []
+ },
+ {
+ 'tfName': 'dilations',
+ 'name': 'dilations',
+ 'type': 'number[]',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'DepthwiseConv2d',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'input', 'type': 'tensor' },
+ { 'start': 1, 'name': 'filter', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'defaultValue': 'NHWC'
+ },
+ {
+ 'tfName': 'explicit_paddings',
+ 'name': 'explicitPaddings',
+ 'type': 'number[]',
+ 'defaultValue': []
+ },
+ { 'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'DepthwiseConv2dNative',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'input', 'type': 'tensor' },
+ { 'start': 1, 'name': 'filter', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'defaultValue': 'NHWC'
+ },
+ {
+ 'tfName': 'explicit_paddings',
+ 'name': 'explicitPaddings',
+ 'type': 'number[]',
+ 'defaultValue': []
+ },
+ { 'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'FusedDepthwiseConv2dNative',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'filter', 'type': 'tensor' },
+ { 'start': 2, end: 0, 'name': 'args', 'type': 'tensors' },
+ ],
+ 'attrs': [
+ { 'tfName': 'num_args', 'name': 'numArgs', 'type': 'number' },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true },
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'defaultValue': 'NHWC'
+ },
+ {
+ 'tfName': 'dilations',
+ 'name': 'dilations',
+ 'type': 'number[]',
+ 'defaultValue': [1, 1, 1, 1]
+ },
+ {
+ 'tfName': 'fused_ops',
+ 'name': 'fusedOps',
+ 'type': 'string[]',
+ 'defaultValue': []
+ },
+ {
+ 'tfName': 'explicit_paddings',
+ 'name': 'explicitPaddings',
+ 'type': 'number[]',
+ 'defaultValue': []
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Conv3D',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'filter', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }, {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'defaultValue': 'NHWC'
+ },
+ { 'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]' }
+ ],
+ },
+ {
+ 'tfOpName': 'Dilation2D',
+ 'category': 'convolution',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'filter', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'strides', 'name': 'strides', 'type': 'number[]' },
+ { 'tfName': 'rates', 'name': 'dilations', 'type': 'number[]' },
+ { 'tfName': 'padding', 'name': 'pad', 'type': 'string' }
+ ]
+ }
+ ];
+
+ var convolution = {
+ __proto__: null,
+ json: json$3
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$4 = [
+ {
+ 'tfOpName': 'Fill',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'shape', 'type': 'number[]' },
+ { 'start': 1, 'name': 'value', 'type': 'number' },
+ ],
+ 'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'LinSpace',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'start', 'type': 'number' },
+ { 'start': 1, 'name': 'stop', 'type': 'number' },
+ { 'start': 2, 'name': 'num', 'type': 'number' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'OneHot',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'indices', 'type': 'tensor' },
+ { 'start': 1, 'name': 'depth', 'type': 'number' },
+ { 'start': 2, 'name': 'onValue', 'type': 'number', 'defaultValue': 1 },
+ { 'start': 3, 'name': 'offValue', 'type': 'number', 'defaultValue': 0 },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'axis',
+ 'name': 'axis',
+ 'type': 'number',
+ 'notSupported': true
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Ones',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'shape', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'OnesLike',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [{ 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'RandomUniform',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'shape', 'type': 'number[]' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'minval',
+ 'name': 'minval',
+ 'type': 'number',
+ 'defaultValue': 0
+ },
+ {
+ 'tfName': 'maxval',
+ 'name': 'maxval',
+ 'type': 'number',
+ 'defaultValue': 1
+ },
+ { 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' },
+ { 'tfName': 'seed', 'name': 'seed', 'type': 'number', 'defaultValue': 0 }, {
+ 'tfName': 'seed2',
+ 'name': 'seed2',
+ 'type': 'number',
+ 'defaultValue': 0,
+ 'notSupported': true
+ },
+ { 'tfName': 'T', 'name': 'T', 'type': 'number', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Range',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'start', 'type': 'number' },
+ { 'start': 1, 'name': 'stop', 'type': 'number' },
+ { 'start': 2, 'name': 'step', 'type': 'number', 'defaultValue': 0 },
+ ],
+ 'attrs': [{ 'tfName': 'Tidx', 'name': 'dtype', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'TruncatedNormal',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'shape', 'type': 'number[]' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'means',
+ 'name': 'mean',
+ 'type': 'number',
+ 'defaultValue': 0.0
+ },
+ {
+ 'tfName': 'stddev',
+ 'name': 'stdDev',
+ 'type': 'number',
+ 'defaultValue': 1.0
+ },
+ { 'tfName': 'seed', 'name': 'seed', 'type': 'number' }, {
+ 'tfName': 'seed2',
+ 'name': 'seed2',
+ 'type': 'number',
+ 'defaultValue': 0,
+ 'notSupported': true
+ },
+ { 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' },
+ { 'tfName': 'T', 'name': 'T', 'type': 'number', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Zeros',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'shape', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'ZerosLike',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [{ 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }]
+ },
+ {
+ 'tfOpName': 'Multinomial',
+ 'category': 'creation',
+ 'inputs': [
+ { 'start': 0, 'name': 'logits', 'type': 'tensor' },
+ { 'start': 1, 'name': 'numSamples', 'type': 'number' },
+ ],
+ 'attrs': [
+ { 'tfName': 'seed', 'name': 'seed', 'type': 'number' },
+ { 'tfName': 'seed2', 'name': 'seed2', 'type': 'number' },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' },
+ { 'tfName': 'output_dtype', 'name': 'output_dtype', 'type': 'dtype' }
+ ]
+ }
+ ];
+
+ var creation = {
+ __proto__: null,
+ json: json$4
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$5 = [
+ {
+ 'tfOpName': 'NonMaxSuppressionV2',
+ 'category': 'dynamic',
+ 'inputs': [
+ { 'start': 0, 'name': 'boxes', 'type': 'tensor' },
+ { 'start': 1, 'name': 'scores', 'type': 'tensor' },
+ { 'start': 2, 'name': 'maxOutputSize', 'type': 'number' },
+ { 'start': 3, 'name': 'iouThreshold', 'type': 'number' }
+ ]
+ },
+ {
+ 'tfOpName': 'NonMaxSuppressionV3',
+ 'category': 'dynamic',
+ 'inputs': [
+ { 'start': 0, 'name': 'boxes', 'type': 'tensor' },
+ { 'start': 1, 'name': 'scores', 'type': 'tensor' },
+ { 'start': 2, 'name': 'maxOutputSize', 'type': 'number' },
+ { 'start': 3, 'name': 'iouThreshold', 'type': 'number' },
+ { 'start': 4, 'name': 'scoreThreshold', 'type': 'number' }
+ ]
+ },
+ {
+ 'tfOpName': 'NonMaxSuppressionV4',
+ 'category': 'dynamic',
+ 'inputs': [
+ { 'start': 0, 'name': 'boxes', 'type': 'tensor' },
+ { 'start': 1, 'name': 'scores', 'type': 'tensor' },
+ { 'start': 2, 'name': 'maxOutputSize', 'type': 'number' },
+ { 'start': 3, 'name': 'iouThreshold', 'type': 'number' },
+ { 'start': 4, 'name': 'scoreThreshold', 'type': 'number' }
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }, {
+ 'tfName': 'T_threshold',
+ 'name': 'threshold',
+ 'type': 'dtype',
+ 'notSupported': true
+ },
+ {
+ 'tfName': 'pad_to_max_output_size',
+ 'name': 'padToMaxOutputSize',
+ 'type': 'bool'
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'NonMaxSuppressionV5',
+ 'category': 'dynamic',
+ 'inputs': [
+ { 'start': 0, 'name': 'boxes', 'type': 'tensor' },
+ { 'start': 1, 'name': 'scores', 'type': 'tensor' },
+ { 'start': 2, 'name': 'maxOutputSize', 'type': 'number' },
+ { 'start': 3, 'name': 'iouThreshold', 'type': 'number' },
+ { 'start': 4, 'name': 'scoreThreshold', 'type': 'number' },
+ { 'start': 5, 'name': 'softNmsSigma', 'type': 'number' }
+ ]
+ },
+ {
+ 'tfOpName': 'Where',
+ 'category': 'dynamic',
+ 'inputs': [
+ { 'start': 0, 'name': 'condition', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'ListDiff',
+ 'category': 'dynamic',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'y', 'type': 'tensor' },
+ ],
+ 'attrs': [{
+ 'tfName': 'T',
+ 'name': 'dtype',
+ 'type': 'dtype',
+ 'notSupported': true
+ }]
+ }
+ ];
+
+ var dynamic = {
+ __proto__: null,
+ json: json$5
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$6 = [
+ {
+ 'tfOpName': 'TopKV2',
+ 'category': 'evaluation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'k', 'type': 'number' },
+ ],
+ 'attrs': [{ 'tfName': 'sorted', 'name': 'sorted', 'type': 'bool' }]
+ },
+ {
+ 'tfOpName': 'Unique',
+ 'category': 'evaluation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ },
+ {
+ 'tfOpName': 'UniqueV2',
+ 'category': 'evaluation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number' },
+ ],
+ },
+ ];
+
+ var evaluation = {
+ __proto__: null,
+ json: json$6
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$7 = [
+ {
+ 'tfOpName': 'PlaceholderWithDefault',
+ 'category': 'graph',
+ 'inputs': [
+ { 'start': 0, 'name': 'default', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'shape', 'name': 'shape', 'type': 'shape' },
+ { 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' }
+ ]
+ },
+ {
+ 'tfOpName': 'Placeholder',
+ 'category': 'graph',
+ 'attrs': [
+ { 'tfName': 'shape', 'name': 'shape', 'type': 'shape' },
+ { 'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype' }
+ ]
+ },
+ { 'tfOpName': 'Const', 'category': 'graph' }, {
+ 'tfOpName': 'Identity',
+ 'category': 'graph',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'IdentityN',
+ 'category': 'graph',
+ 'inputs': [{ 'start': 0, 'end': 0, 'name': 'x', 'type': 'tensors' }]
+ },
+ {
+ 'tfOpName': 'Snapshot',
+ 'category': 'graph',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'Rank',
+ 'category': 'graph',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'Size',
+ 'category': 'graph',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'Shape',
+ 'category': 'graph',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'ShapeN',
+ 'category': 'graph',
+ 'inputs': [{ 'start': 0, 'end': 0, 'name': 'x', 'type': 'tensors' }]
+ },
+ {
+ 'tfOpName': 'Print',
+ 'category': 'graph',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'data', 'type': 'tensors' },
+ ],
+ 'attrs': [
+ { 'tfName': 'message', 'name': 'message', 'type': 'string' }, {
+ 'tfName': 'first_n',
+ 'name': 'firstN',
+ 'type': 'number',
+ 'notSupported': true
+ },
+ {
+ 'tfName': 'summarize',
+ 'name': 'summarize',
+ 'type': 'number',
+ 'defaultValue': 3
+ }
+ ]
+ },
+ { 'tfOpName': 'NoOp', 'category': 'graph', 'inputs': [] }, {
+ 'tfOpName': 'StopGradient',
+ 'category': 'graph',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'FakeQuantWithMinMaxVars',
+ 'category': 'graph',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'min', 'name': 'min', 'type': 'number' },
+ { 'tfName': 'max', 'name': 'max', 'type': 'number' }
+ ]
+ }
+ ];
+
+ var graph = {
+ __proto__: null,
+ json: json$7
+ };
+
+ var json$8 = [
+ {
+ 'tfOpName': 'HashTable',
+ 'category': 'hash_table',
+ 'inputs': [],
+ 'attrs': [
+ { 'tfName': 'shared_name', 'name': 'sharedName', 'type': 'string' },
+ {
+ 'tfName': 'use_node_name_sharing',
+ 'name': 'useNodeNameSharing',
+ 'type': 'bool'
+ },
+ { 'tfName': 'key_dtype', 'name': 'keyDType', 'type': 'dtype' },
+ { 'tfName': 'value_dtype', 'name': 'valueDType', 'type': 'dtype' },
+ ]
+ },
+ {
+ 'tfOpName': 'HashTableV2',
+ 'category': 'hash_table',
+ 'inputs': [],
+ 'attrs': [
+ { 'tfName': 'shared_name', 'name': 'sharedName', 'type': 'string' },
+ {
+ 'tfName': 'use_node_name_sharing',
+ 'name': 'useNodeNameSharing',
+ 'type': 'bool'
+ },
+ { 'tfName': 'key_dtype', 'name': 'keyDType', 'type': 'dtype' },
+ { 'tfName': 'value_dtype', 'name': 'valueDType', 'type': 'dtype' },
+ ]
+ },
+ {
+ 'tfOpName': 'LookupTableImport',
+ 'category': 'hash_table',
+ 'inputs': [
+ { 'start': 0, 'name': 'tableHandle', 'type': 'tensor' },
+ { 'start': 1, 'name': 'keys', 'type': 'tensor' },
+ { 'start': 2, 'name': 'values', 'type': 'tensor' }
+ ],
+ 'attrs': [
+ { 'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true }, {
+ 'tfName': 'Tout',
+ 'name': 'tOut',
+ 'type': 'dtype',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'LookupTableImportV2',
+ 'category': 'hash_table',
+ 'inputs': [
+ { 'start': 0, 'name': 'tableHandle', 'type': 'tensor' },
+ { 'start': 1, 'name': 'keys', 'type': 'tensor' },
+ { 'start': 2, 'name': 'values', 'type': 'tensor' }
+ ],
+ 'attrs': [
+ { 'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true }, {
+ 'tfName': 'Tout',
+ 'name': 'tOut',
+ 'type': 'dtype',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'LookupTableFind',
+ 'category': 'hash_table',
+ 'inputs': [
+ { 'start': 0, 'name': 'tableHandle', 'type': 'tensor' },
+ { 'start': 1, 'name': 'keys', 'type': 'tensor' },
+ { 'start': 2, 'name': 'defaultValue', 'type': 'tensor' }
+ ],
+ 'attrs': [
+ { 'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true }, {
+ 'tfName': 'Tout',
+ 'name': 'tOut',
+ 'type': 'dtype',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'LookupTableFindV2',
+ 'category': 'hash_table',
+ 'inputs': [
+ { 'start': 0, 'name': 'tableHandle', 'type': 'tensor' },
+ { 'start': 1, 'name': 'keys', 'type': 'tensor' },
+ { 'start': 2, 'name': 'defaultValue', 'type': 'tensor' }
+ ],
+ 'attrs': [
+ { 'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true }, {
+ 'tfName': 'Tout',
+ 'name': 'tOut',
+ 'type': 'dtype',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'LookupTableSize',
+ 'category': 'hash_table',
+ 'inputs': [
+ { 'start': 0, 'name': 'tableHandle', 'type': 'tensor' }
+ ]
+ },
+ {
+ 'tfOpName': 'LookupTableSizeV2',
+ 'category': 'hash_table',
+ 'inputs': [
+ { 'start': 0, 'name': 'tableHandle', 'type': 'tensor' }
+ ]
+ }
+ ];
+
+ var hashTable = {
+ __proto__: null,
+ json: json$8
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$9 = [
+ {
+ 'tfOpName': 'ResizeBilinear',
+ 'category': 'image',
+ 'inputs': [
+ { 'start': 0, 'name': 'images', 'type': 'tensor' },
+ { 'start': 1, 'name': 'size', 'type': 'number[]' },
+ ],
+ 'attrs': [
+ { 'tfName': 'align_corners', 'name': 'alignCorners', 'type': 'bool' }, {
+ 'tfName': 'half_pixel_centers',
+ 'name': 'halfPixelCenters',
+ 'type': 'bool'
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'ResizeNearestNeighbor',
+ 'category': 'image',
+ 'inputs': [
+ { 'start': 0, 'name': 'images', 'type': 'tensor' },
+ { 'start': 1, 'name': 'size', 'type': 'number[]' },
+ ],
+ 'attrs': [
+ { 'tfName': 'align_corners', 'name': 'alignCorners', 'type': 'bool' }, {
+ 'tfName': 'half_pixel_centers',
+ 'name': 'halfPixelCenters',
+ 'type': 'bool'
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'CropAndResize',
+ 'category': 'image',
+ 'inputs': [
+ { 'start': 0, 'name': 'image', 'type': 'tensor' },
+ { 'start': 1, 'name': 'boxes', 'type': 'tensor' },
+ { 'start': 2, 'name': 'boxInd', 'type': 'tensor' },
+ { 'start': 3, 'name': 'cropSize', 'type': 'number[]' },
+ ],
+ 'attrs': [
+ { 'tfName': 'method', 'name': 'method', 'type': 'string' }, {
+ 'tfName': 'extrapolation_value',
+ 'name': 'extrapolationValue',
+ 'type': 'number'
+ }
+ ]
+ }
+ ];
+
+ var image = {
+ __proto__: null,
+ json: json$9
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$a = [
+ {
+ 'tfOpName': 'Equal',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'NotEqual',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Greater',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'GreaterEqual',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Less',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'LessEqual',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'LogicalAnd',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'LogicalNot',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'LogicalOr',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Select',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'condition', 'type': 'tensor' },
+ { 'start': 1, 'name': 'a', 'type': 'tensor' },
+ { 'start': 2, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'SelectV2',
+ 'category': 'logical',
+ 'inputs': [
+ { 'start': 0, 'name': 'condition', 'type': 'tensor' },
+ { 'start': 1, 'name': 'a', 'type': 'tensor' },
+ { 'start': 2, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [{
+ 'tfName': 'T',
+ 'name': 'dtype',
+ 'type': 'dtype',
+ 'notSupported': true
+ }]
+ }
+ ];
+
+ var logical = {
+ __proto__: null,
+ json: json$a
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$b = [
+ {
+ 'tfOpName': '_FusedMatMul',
+ 'category': 'matrices',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ { 'start': 2, end: 0, 'name': 'args', 'type': 'tensors' },
+ ],
+ 'attrs': [
+ { 'tfName': 'num_args', 'name': 'numArgs', 'type': 'number' }, {
+ 'tfName': 'fused_ops',
+ 'name': 'fusedOps',
+ 'type': 'string[]',
+ 'defaultValue': []
+ },
+ {
+ 'tfName': 'epsilon',
+ 'name': 'epsilon',
+ 'type': 'number',
+ 'defaultValue': 0.0001
+ },
+ {
+ 'tfName': 'transpose_a',
+ 'name': 'transposeA',
+ 'type': 'bool',
+ 'defaultValue': false
+ },
+ {
+ 'tfName': 'transpose_b',
+ 'name': 'transposeB',
+ 'type': 'bool',
+ 'defaultValue': false
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'MatMul',
+ 'category': 'matrices',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'transpose_a',
+ 'name': 'transposeA',
+ 'type': 'bool',
+ 'defaultValue': false
+ },
+ {
+ 'tfName': 'transpose_b',
+ 'name': 'transposeB',
+ 'type': 'bool',
+ 'defaultValue': false
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'BatchMatMul',
+ 'category': 'matrices',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'adj_x',
+ 'name': 'transposeA',
+ 'type': 'bool',
+ 'defaultValue': false
+ },
+ {
+ 'tfName': 'adj_y',
+ 'name': 'transposeB',
+ 'type': 'bool',
+ 'defaultValue': false
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'BatchMatMulV2',
+ 'category': 'matrices',
+ 'inputs': [
+ { 'start': 0, 'name': 'a', 'type': 'tensor' },
+ { 'start': 1, 'name': 'b', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'adj_x',
+ 'name': 'transposeA',
+ 'type': 'bool',
+ 'defaultValue': false
+ },
+ {
+ 'tfName': 'adj_y',
+ 'name': 'transposeB',
+ 'type': 'bool',
+ 'defaultValue': false
+ },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Transpose',
+ 'category': 'matrices',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'perm', 'type': 'number[]' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'Einsum',
+ 'category': 'matrices',
+ 'inputs': [{ 'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors' }],
+ 'attrs': [
+ { 'tfName': 'equation', 'name': 'equation', 'type': 'string' },
+ { 'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2 },
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype' }
+ ]
+ }
+ ];
+
+ var matrices = {
+ __proto__: null,
+ json: json$b
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$c = [
+ {
+ 'tfOpName': 'FusedBatchNorm',
+ 'category': 'normalization',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'scale', 'type': 'tensor' },
+ { 'start': 2, 'name': 'offset', 'type': 'tensor' },
+ { 'start': 3, 'name': 'mean', 'type': 'tensor' },
+ { 'start': 4, 'name': 'variance', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'epsilon',
+ 'name': 'epsilon',
+ 'type': 'number',
+ 'defaultValue': 0.001
+ },
+ {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'FusedBatchNormV2',
+ 'category': 'normalization',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'scale', 'type': 'tensor' },
+ { 'start': 2, 'name': 'offset', 'type': 'tensor' },
+ { 'start': 3, 'name': 'mean', 'type': 'tensor' },
+ { 'start': 4, 'name': 'variance', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'epsilon',
+ 'name': 'epsilon',
+ 'type': 'number',
+ 'defaultValue': 0.001
+ },
+ {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'FusedBatchNormV3',
+ 'category': 'normalization',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'scale', 'type': 'tensor' },
+ { 'start': 2, 'name': 'offset', 'type': 'tensor' },
+ { 'start': 3, 'name': 'mean', 'type': 'tensor' },
+ { 'start': 4, 'name': 'variance', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'epsilon',
+ 'name': 'epsilon',
+ 'type': 'number',
+ 'defaultValue': 0.001
+ },
+ {
+ 'tfName': 'data_format',
+ 'name': 'dataFormat',
+ 'type': 'string',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'LRN',
+ 'category': 'normalization',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'depth_radius',
+ 'name': 'radius',
+ 'type': 'number',
+ 'defaultValue': 5
+ },
+ { 'tfName': 'bias', 'name': 'bias', 'type': 'number', 'defaultValue': 1.0 },
+ {
+ 'tfName': 'alpha',
+ 'name': 'alpha',
+ 'type': 'number',
+ 'defaultValue': 1.0
+ },
+ {
+ 'tfName': 'beta',
+ 'name': 'beta',
+ 'type': 'number',
+ 'defaultValue': 0.5
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Softmax',
+ 'category': 'normalization',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'LogSoftmax',
+ 'category': 'normalization',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'SparseToDense',
+ 'category': 'normalization',
+ 'inputs': [
+ { 'start': 0, 'name': 'sparseIndices', 'type': 'tensor' },
+ { 'start': 1, 'name': 'outputShape', 'type': 'number[]' },
+ { 'start': 2, 'name': 'sparseValues', 'type': 'tensor' },
+ { 'start': 3, 'name': 'defaultValue', 'type': 'tensor' },
+ ],
+ 'attrs': [{
+ 'tfName': 'validate_indices',
+ 'name': 'validateIndices',
+ 'type': 'bool',
+ 'defaultValue': true,
+ 'notSupported': true
+ }]
+ }
+ ];
+
+ var normalization = {
+ __proto__: null,
+ json: json$c
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$d = [
+ {
+ 'tfOpName': 'Bincount',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'size', 'type': 'number' },
+ { 'start': 2, 'name': 'weights', 'type': 'tensor' }
+ ]
+ },
+ {
+ 'tfOpName': 'DenseBincount',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'size', 'type': 'number' },
+ { 'start': 2, 'name': 'weights', 'type': 'tensor' }
+ ],
+ 'attrs': [{ 'tfName': 'binary_output', 'name': 'binaryOutput', 'type': 'bool' }]
+ },
+ {
+ 'tfOpName': 'Max',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
+ },
+ {
+ 'tfOpName': 'Mean',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
+ },
+ {
+ 'tfOpName': 'Min',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
+ },
+ {
+ 'tfOpName': 'Sum',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
+ },
+ {
+ 'tfOpName': 'All',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
+ },
+ {
+ 'tfOpName': 'Any',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
+ },
+ {
+ 'tfOpName': 'ArgMax',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number' }
+ ]
+ },
+ {
+ 'tfOpName': 'ArgMin',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number' }
+ ]
+ },
+ {
+ 'tfOpName': 'Prod',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool' }]
+ },
+ {
+ 'tfOpName': 'Cumsum',
+ 'category': 'reduction',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number' },
+ ],
+ 'attrs': [
+ { 'tfName': 'exclusive', 'name': 'exclusive', 'type': 'bool' },
+ { 'tfName': 'reverse', 'name': 'reverse', 'type': 'bool' }
+ ]
+ }
+ ];
+
+ var reduction = {
+ __proto__: null,
+ json: json$d
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$e = [
+ {
+ 'tfOpName': 'ConcatV2',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'end': -1, 'name': 'tensors', 'type': 'tensors' },
+ { 'start': -1, 'name': 'axis', 'type': 'number' }
+ ],
+ 'attrs': [{ 'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2 }]
+ },
+ {
+ 'tfOpName': 'Concat',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 1, 'end': 0, 'name': 'tensors', 'type': 'tensors' },
+ { 'start': 0, 'name': 'axis', 'type': 'number' }
+ ],
+ 'attrs': [{ 'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2 }]
+ },
+ {
+ 'tfOpName': 'GatherV2',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'tensor' },
+ { 'start': 2, 'name': 'axis', 'type': 'number', 'defaultValue': 0 }
+ ],
+ 'attrs': [{
+ 'tfName': 'batch_dims',
+ 'name': 'batchDims',
+ 'type': 'number',
+ 'defaultValue': 0
+ }]
+ },
+ {
+ 'tfOpName': 'Gather',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'tensor' },
+ ],
+ 'attrs': [{
+ 'tfName': 'validate_indices',
+ 'name': 'validateIndices',
+ 'type': 'bool',
+ 'notSupported': true
+ }]
+ },
+ {
+ 'tfOpName': 'Reverse',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'dims', 'type': 'bool[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'ReverseV2',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'Slice',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'begin', 'type': 'number[]' },
+ { 'start': 2, 'name': 'size', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'StridedSlice',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'begin', 'type': 'number[]' },
+ { 'start': 2, 'name': 'end', 'type': 'number[]' },
+ { 'start': 3, 'name': 'strides', 'type': 'number[]' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'begin_mask',
+ 'name': 'beginMask',
+ 'type': 'number',
+ 'defaultValue': 0
+ },
+ {
+ 'tfName': 'end_mask',
+ 'name': 'endMask',
+ 'type': 'number',
+ 'defaultValue': 0
+ },
+ {
+ 'tfName': 'new_axis_mask',
+ 'name': 'newAxisMask',
+ 'type': 'number',
+ 'defaultValue': 0
+ },
+ {
+ 'tfName': 'ellipsis_mask',
+ 'name': 'ellipsisMask',
+ 'type': 'number',
+ 'defaultValue': 0
+ },
+ {
+ 'tfName': 'shrink_axis_mask',
+ 'name': 'shrinkAxisMask',
+ 'type': 'number',
+ 'defaultValue': 0
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Pack',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors' },
+ ],
+ 'attrs': [
+ { 'tfName': 'axis', 'name': 'axis', 'type': 'number', 'defaultValue': 0 }
+ ]
+ },
+ {
+ 'tfOpName': 'Unpack',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'tensor', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'axis', 'name': 'axis', 'type': 'number', 'defaultValue': 0 }, {
+ 'tfName': 'num',
+ 'name': 'num',
+ 'type': 'number',
+ 'defaultValue': 0,
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Tile',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'reps', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'Split',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'axis', 'type': 'number', 'defaultValue': 0 },
+ { 'start': 1, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [{
+ 'tfName': 'num_split',
+ 'name': 'numOrSizeSplits',
+ 'type': 'number',
+ 'defaultValue': 1
+ }]
+ },
+ {
+ 'tfOpName': 'SplitV',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'numOrSizeSplits', 'type': 'number[]' },
+ { 'start': 2, 'name': 'axis', 'type': 'number', 'defaultValue': 0 }
+ ]
+ },
+ {
+ 'tfOpName': 'ScatterNd',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'indices', 'type': 'tensor' },
+ { 'start': 1, 'name': 'values', 'type': 'tensor' },
+ { 'start': 2, 'name': 'shape', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'GatherNd',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'tensor' }
+ ]
+ },
+ {
+ 'tfOpName': 'SparseToDense',
+ 'category': 'slice_join',
+ 'inputs': [
+ { 'start': 0, 'name': 'sparseIndices', 'type': 'tensor' },
+ { 'start': 1, 'name': 'outputShape', 'type': 'number[]' },
+ { 'start': 2, 'name': 'sparseValues', 'type': 'tensor' },
+ { 'start': 3, 'name': 'defaultValue', 'type': 'tensor' },
+ ],
+ 'attrs': [{
+ 'tfName': 'validate_indices',
+ 'name': 'validateIndices',
+ 'type': 'bool',
+ 'defaultValue': false,
+ 'notSupported': true
+ }]
+ }
+ ];
+
+ var sliceJoin = {
+ __proto__: null,
+ json: json$e
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$f = [
+ {
+ 'tfOpName': 'SparseFillEmptyRows',
+ 'category': 'sparse',
+ 'inputs': [
+ { 'start': 0, 'name': 'indices', 'type': 'tensor' },
+ { 'start': 1, 'name': 'values', 'type': 'tensor' },
+ { 'start': 2, 'name': 'denseShape', 'type': 'tensor' },
+ { 'start': 3, 'name': 'defaultValue', 'type': 'tensor' },
+ ]
+ },
+ {
+ 'tfOpName': 'SparseReshape',
+ 'category': 'sparse',
+ 'inputs': [
+ { 'start': 0, 'name': 'inputIndices', 'type': 'tensor' },
+ { 'start': 1, 'name': 'inputShape', 'type': 'tensor' },
+ { 'start': 2, 'name': 'newShape', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true }
+ ]
+ },
+ {
+ 'tfOpName': 'SparseSegmentMean',
+ 'category': 'sparse',
+ 'inputs': [
+ { 'start': 0, 'name': 'data', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'tensor' },
+ { 'start': 2, 'name': 'segmentIds', 'type': 'tensor' },
+ ]
+ },
+ {
+ 'tfOpName': 'SparseSegmentSum',
+ 'category': 'sparse',
+ 'inputs': [
+ { 'start': 0, 'name': 'data', 'type': 'tensor' },
+ { 'start': 1, 'name': 'indices', 'type': 'tensor' },
+ { 'start': 2, 'name': 'segmentIds', 'type': 'tensor' },
+ ]
+ }
+ ];
+
+ var sparse = {
+ __proto__: null,
+ json: json$f
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$g = [
+ {
+ 'tfOpName': 'FFT',
+ 'category': 'spectral',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'IFFT',
+ 'category': 'spectral',
+ 'inputs': [{ 'start': 0, 'name': 'x', 'type': 'tensor' }]
+ },
+ {
+ 'tfOpName': 'RFFT',
+ 'category': 'spectral',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' }, {
+ 'start': 1,
+ 'name': 'fft_length',
+ 'type': 'number',
+ 'notSupported': true
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'IRFFT',
+ 'category': 'spectral',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' }, {
+ 'start': 1,
+ 'name': 'fft_length',
+ 'type': 'number',
+ 'notSupported': true
+ }
+ ]
+ }
+ ];
+
+ var spectral = {
+ __proto__: null,
+ json: json$g
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$h = [
+ {
+ 'tfOpName': 'StringNGrams',
+ 'category': 'string',
+ 'inputs': [
+ { 'start': 0, 'name': 'data', 'type': 'tensor' },
+ { 'start': 1, 'name': 'dataSplits', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'separator', 'name': 'separator', 'type': 'string' },
+ { 'tfName': 'ngram_widths', 'name': 'nGramWidths', 'type': 'number[]' },
+ { 'tfName': 'left_pad', 'name': 'leftPad', 'type': 'string' },
+ { 'tfName': 'right_pad', 'name': 'rightPad', 'type': 'string' },
+ { 'tfName': 'pad_width', 'name': 'padWidth', 'type': 'number' }, {
+ 'tfName': 'preserve_short_sequences',
+ 'name': 'preserveShortSequences',
+ 'type': 'bool'
+ }
+ ],
+ 'outputs': ['ngrams', 'ngrams_splits']
+ },
+ {
+ 'tfOpName': 'StringSplit',
+ 'category': 'string',
+ 'inputs': [
+ { 'start': 0, 'name': 'input', 'type': 'tensor' },
+ { 'start': 1, 'name': 'delimiter', 'type': 'tensor' },
+ ],
+ 'attrs': [{ 'tfName': 'skip_empty', 'name': 'skipEmpty', 'type': 'bool' }],
+ 'outputs': ['indices', 'values', 'shape']
+ },
+ {
+ 'tfOpName': 'StringToHashBucketFast',
+ 'category': 'string',
+ 'inputs': [
+ { 'start': 0, 'name': 'input', 'type': 'tensor' },
+ ],
+ 'attrs': [{ 'tfName': 'num_buckets', 'name': 'numBuckets', 'type': 'number' }]
+ }
+ ];
+
+ var string = {
+ __proto__: null,
+ json: json$h
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var json$i = [
+ {
+ 'tfOpName': 'Cast',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ {
+ 'tfName': 'SrcT',
+ 'name': 'sdtype',
+ 'type': 'dtype',
+ 'notSupported': true
+ },
+ { 'tfName': 'DstT', 'name': 'dtype', 'type': 'dtype' }
+ ]
+ },
+ {
+ 'tfOpName': 'ExpandDims',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'axis', 'type': 'number' }
+ ]
+ },
+ {
+ 'tfOpName': 'MirrorPad',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'padding', 'type': 'number[]' },
+ ],
+ 'attrs': [{ 'tfName': 'mode', 'name': 'mode', 'type': 'string' }]
+ },
+ {
+ 'tfOpName': 'Pad',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'padding', 'type': 'number[]' },
+ ],
+ 'attrs': [{
+ 'tfName': 'constant_value',
+ 'name': 'constantValue',
+ 'type': 'number',
+ 'defaultValue': 0
+ }]
+ },
+ {
+ 'tfOpName': 'PadV2',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'padding', 'type': 'number[]' }, {
+ 'start': 2,
+ 'name': 'constantValue',
+ 'type': 'number',
+ 'defaultValue': 0
+ }
+ ]
+ },
+ {
+ 'tfOpName': 'Reshape',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'shape', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'Squeeze',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [{
+ 'tfName': 'axis',
+ 'tfDeprecatedName': 'squeeze_dims',
+ 'name': 'axis',
+ 'type': 'number[]'
+ }]
+ },
+ {
+ 'tfOpName': 'SpaceToBatchND',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'blockShape', 'type': 'number[]' },
+ { 'start': 2, 'name': 'paddings', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'BatchToSpaceND',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'blockShape', 'type': 'number[]' },
+ { 'start': 2, 'name': 'crops', 'type': 'number[]' }
+ ]
+ },
+ {
+ 'tfOpName': 'DepthToSpace',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ ],
+ 'attrs': [
+ { 'tfName': 'block_size', 'name': 'blockSize', 'type': 'number' },
+ { 'tfName': 'data_format', 'name': 'dataFormat', 'type': 'string' }
+ ]
+ },
+ {
+ 'tfOpName': 'BroadcastTo',
+ 'category': 'transformation',
+ 'inputs': [
+ { 'start': 0, 'name': 'x', 'type': 'tensor' },
+ { 'start': 1, 'name': 'shape', 'type': 'number[]' },
+ ],
+ 'attrs': []
+ }
+ ];
+
+ var transformation = {
+ __proto__: null,
+ json: json$i
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var OperationMapper = /** @class */ (function () {
+ // Loads the op mapping from the JSON file.
+ function OperationMapper() {
+ var ops = [
+ arithmetic, basicMath, control, convolution, creation, dynamic,
+ evaluation, graph, hashTable, image, logical, matrices, normalization,
+ reduction, sliceJoin, sparse, spectral, string, transformation
+ ];
+ var mappersJson = [].concat.apply([], __spread(ops.map(function (op) { return op.json; })));
+ this.opMappers = mappersJson.reduce(function (map, mapper) {
+ map[mapper.tfOpName] = mapper;
+ return map;
+ }, {});
+ }
+ Object.defineProperty(OperationMapper, "Instance", {
+ // Singleton instance for the mapper
+ get: function () {
+ return this._instance || (this._instance = new this());
+ },
+ enumerable: true,
+ configurable: true
+ });
+ // Converts the model inference graph from Tensorflow GraphDef to local
+ // representation for TensorFlow.js API
+ OperationMapper.prototype.transformGraph = function (graph, signature) {
+ var _this = this;
+ if (signature === void 0) { signature = {}; }
+ var tfNodes = graph.node;
+ var placeholders = [];
+ var weights = [];
+ var initNodes = [];
+ var nodes = tfNodes.reduce(function (map, node) {
+ map[node.name] = _this.mapNode(node);
+ if (node.op.startsWith('Placeholder')) {
+ placeholders.push(map[node.name]);
+ }
+ else if (node.op === 'Const') {
+ weights.push(map[node.name]);
+ }
+ else if (node.input == null || node.input.length === 0) {
+ initNodes.push(map[node.name]);
+ }
+ return map;
+ }, {});
+ var inputs = [];
+ var outputs = [];
+ var inputNodeNameToKey = {};
+ var outputNodeNameToKey = {};
+ if (signature != null) {
+ inputNodeNameToKey = this.mapSignatureEntries(signature.inputs);
+ outputNodeNameToKey = this.mapSignatureEntries(signature.outputs);
+ }
+ var allNodes = Object.keys(nodes);
+ allNodes.forEach(function (key) {
+ var node = nodes[key];
+ node.inputNames.forEach(function (name, index) {
+ var _a = __read(getNodeNameAndIndex(name), 3), nodeName = _a[0], outputName = _a[2];
+ var inputNode = nodes[nodeName];
+ if (inputNode.outputs != null) {
+ var outputIndex = inputNode.outputs.indexOf(outputName);
+ if (outputIndex !== -1) {
+ var inputName = nodeName + ":" + outputIndex;
+ // update the input name to use the mapped output index directly.
+ node.inputNames[index] = inputName;
+ }
+ }
+ node.inputs.push(inputNode);
+ inputNode.children.push(node);
+ });
+ });
+ // if signature has not outputs set, add any node that does not have
+ // outputs.
+ if (Object.keys(outputNodeNameToKey).length === 0) {
+ allNodes.forEach(function (key) {
+ var node = nodes[key];
+ if (node.children.length === 0) {
+ outputs.push(node);
+ }
+ });
+ }
+ else {
+ Object.keys(outputNodeNameToKey).forEach(function (name) {
+ var _a = __read(getNodeNameAndIndex(name), 1), nodeName = _a[0];
+ var node = nodes[nodeName];
+ if (node != null) {
+ node.signatureKey = outputNodeNameToKey[name];
+ outputs.push(node);
+ }
+ });
+ }
+ if (Object.keys(inputNodeNameToKey).length > 0) {
+ Object.keys(inputNodeNameToKey).forEach(function (name) {
+ var _a = __read(getNodeNameAndIndex(name), 1), nodeName = _a[0];
+ var node = nodes[nodeName];
+ if (node) {
+ node.signatureKey = inputNodeNameToKey[name];
+ inputs.push(node);
+ }
+ });
+ }
+ else {
+ inputs = placeholders;
+ }
+ var functions = {};
+ if (graph.library != null && graph.library.function != null) {
+ functions = graph.library.function.reduce(function (functions, func) {
+ functions[func.signature.name] = _this.mapFunction(func);
+ return functions;
+ }, {});
+ }
+ var result = { nodes: nodes, inputs: inputs, outputs: outputs, weights: weights, placeholders: placeholders, signature: signature, functions: functions };
+ if (initNodes.length > 0) {
+ result.initNodes = initNodes;
+ }
+ return result;
+ };
+ OperationMapper.prototype.mapSignatureEntries = function (entries) {
+ return Object.keys(entries || {})
+ .reduce(function (prev, curr) {
+ prev[entries[curr].name] = curr;
+ return prev;
+ }, {});
+ };
+ OperationMapper.prototype.mapNode = function (node) {
+ // Unsupported ops will cause an error at run-time (not parse time), since
+ // they may not be used by the actual execution subgraph.
+ var mapper = getRegisteredOp(node.op) || this.opMappers[node.op] || {};
+ if (node.attr == null) {
+ node.attr = {};
+ }
+ var newNode = {
+ name: node.name,
+ op: node.op,
+ category: mapper.category,
+ inputNames: (node.input ||
+ []).map(function (input) { return input.startsWith('^') ? input.substr(1) : input; }),
+ inputs: [],
+ children: [],
+ inputParams: {},
+ attrParams: {},
+ rawAttrs: node.attr,
+ outputs: mapper.outputs
+ };
+ if (mapper.inputs != null) {
+ newNode.inputParams =
+ mapper.inputs.reduce(function (map, param) {
+ map[param.name] = {
+ type: param.type,
+ inputIndexStart: param.start,
+ inputIndexEnd: param.end
+ };
+ return map;
+ }, {});
+ }
+ if (mapper.attrs != null) {
+ newNode.attrParams =
+ mapper.attrs.reduce(function (map, param) {
+ var type = param.type;
+ var value = undefined;
+ switch (param.type) {
+ case 'string':
+ value = getStringParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getStringParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'string[]':
+ value = getStringArrayParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getStringArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'number':
+ value = getNumberParam(node.attr, param.tfName, (param.defaultValue || 0));
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getNumberParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'number[]':
+ value = getNumericArrayParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getNumericArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'bool':
+ value = getBoolParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getBoolParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'bool[]':
+ value = getBoolArrayParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getBoolArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'shape':
+ value = getTensorShapeParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getTensorShapeParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'shape[]':
+ value = getTensorShapeArrayParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getTensorShapeArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'dtype':
+ value = getDtypeParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getDtypeParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'dtype[]':
+ value = getDtypeArrayParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getDtypeArrayParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'func':
+ value = getFuncParam(node.attr, param.tfName, param.defaultValue);
+ if (value === undefined && !!param.tfDeprecatedName) {
+ value = getFuncParam(node.attr, param.tfDeprecatedName, param.defaultValue);
+ }
+ break;
+ case 'tensor':
+ case 'tensors':
+ break;
+ default:
+ throw new Error("Unsupported param type: " + param.type + " for op: " + node.op);
+ }
+ map[param.name] = { value: value, type: type };
+ return map;
+ }, {});
+ }
+ return newNode;
+ };
+ // map the TFunctionDef to TFJS graph object
+ OperationMapper.prototype.mapFunction = function (functionDef) {
+ var _this = this;
+ var tfNodes = functionDef.nodeDef;
+ var placeholders = [];
+ var weights = [];
+ var nodes = {};
+ if (tfNodes != null) {
+ nodes = tfNodes.reduce(function (map, node) {
+ map[node.name] = _this.mapNode(node);
+ if (node.op === 'Const') {
+ weights.push(map[node.name]);
+ }
+ return map;
+ }, {});
+ }
+ var inputs = [];
+ var outputs = [];
+ functionDef.signature.inputArg.forEach(function (arg) {
+ var _a = __read(getNodeNameAndIndex(arg.name), 1), nodeName = _a[0];
+ var node = {
+ name: nodeName,
+ op: 'Placeholder',
+ inputs: [],
+ inputNames: [],
+ category: 'graph',
+ inputParams: {},
+ attrParams: { dtype: { value: parseDtypeParam(arg.type), type: 'dtype' } },
+ children: []
+ };
+ node.signatureKey = arg.name;
+ inputs.push(node);
+ nodes[nodeName] = node;
+ });
+ var allNodes = Object.keys(nodes);
+ allNodes.forEach(function (key) {
+ var node = nodes[key];
+ node.inputNames.forEach(function (name, index) {
+ var _a = __read(getNodeNameAndIndex(name), 3), nodeName = _a[0], outputName = _a[2];
+ var inputNode = nodes[nodeName];
+ if (inputNode.outputs != null) {
+ var outputIndex = inputNode.outputs.indexOf(outputName);
+ if (outputIndex !== -1) {
+ var inputName = nodeName + ":" + outputIndex;
+ // update the input name to use the mapped output index directly.
+ node.inputNames[index] = inputName;
+ }
+ }
+ node.inputs.push(inputNode);
+ inputNode.children.push(node);
+ });
+ });
+ var returnNodeMap = functionDef.ret;
+ functionDef.signature.outputArg.forEach(function (output) {
+ var _a = __read(getNodeNameAndIndex(returnNodeMap[output.name]), 2), nodeName = _a[0], index = _a[1];
+ var node = nodes[nodeName];
+ if (node != null) {
+ node.defaultOutput = index;
+ outputs.push(node);
+ }
+ });
+ var signature = this.mapArgsToSignature(functionDef);
+ return { nodes: nodes, inputs: inputs, outputs: outputs, weights: weights, placeholders: placeholders, signature: signature };
+ };
+ OperationMapper.prototype.mapArgsToSignature = function (functionDef) {
+ var _this = this;
+ return {
+ methodName: functionDef.signature.name,
+ inputs: functionDef.signature.inputArg.reduce(function (map, arg) {
+ map[arg.name] = _this.mapArgToTensorInfo(arg);
+ return map;
+ }, {}),
+ outputs: functionDef.signature.outputArg.reduce(function (map, arg) {
+ map[arg.name] = _this.mapArgToTensorInfo(arg, functionDef.ret);
+ return map;
+ }, {}),
+ };
+ };
+ OperationMapper.prototype.mapArgToTensorInfo = function (arg, nameMap) {
+ var name = arg.name;
+ if (nameMap != null) {
+ name = nameMap[name];
+ }
+ return { name: name, dtype: arg.type };
+ };
+ return OperationMapper;
+ }());
+ function decodeBase64(text) {
+ var global = tfc.env().global;
+ if (typeof global.atob !== 'undefined') {
+ return global.atob(text);
+ }
+ else if (typeof Buffer !== 'undefined') {
+ return new Buffer(text, 'base64').toString();
+ }
+ else {
+ throw new Error('Unable to decode base64 in this environment. ' +
+ 'Missing built-in atob() or Buffer()');
+ }
+ }
+ function parseStringParam(s, keepCase) {
+ var value = Array.isArray(s) ? String.fromCharCode.apply(null, s) : decodeBase64(s);
+ return keepCase ? value : value.toLowerCase();
+ }
+ function getStringParam(attrs, name, def, keepCase) {
+ if (keepCase === void 0) { keepCase = false; }
+ var param = attrs[name];
+ if (param != null) {
+ return parseStringParam(param.s, keepCase);
+ }
+ return def;
+ }
+ function getBoolParam(attrs, name, def) {
+ var param = attrs[name];
+ return param ? param.b : def;
+ }
+ function getNumberParam(attrs, name, def) {
+ var param = attrs[name] || {};
+ var value = param['i'] != null ? param['i'] : (param['f'] != null ? param['f'] : def);
+ return (typeof value === 'number') ? value : parseInt(value, 10);
+ }
+ function parseDtypeParam(value) {
+ if (typeof (value) === 'string') {
+ // tslint:disable-next-line:no-any
+ value = DataType[value];
+ }
+ switch (value) {
+ case DataType.DT_FLOAT:
+ return 'float32';
+ case DataType.DT_INT32:
+ case DataType.DT_INT64:
+ case DataType.DT_INT8:
+ case DataType.DT_UINT8:
+ return 'int32';
+ case DataType.DT_BOOL:
+ return 'bool';
+ case DataType.DT_DOUBLE:
+ return 'float32';
+ case DataType.DT_STRING:
+ return 'string';
+ default:
+ // Unknown dtype error will happen at runtime (instead of parse time),
+ // since these nodes might not be used by the actual subgraph execution.
+ return null;
+ }
+ }
+ function getFuncParam(attrs, name, def) {
+ var param = attrs[name];
+ if (param && param.func) {
+ return param.func.name;
+ }
+ return def;
+ }
+ function getDtypeParam(attrs, name, def) {
+ var param = attrs[name];
+ if (param && param.type) {
+ return parseDtypeParam(param.type);
+ }
+ return def;
+ }
+ function getDtypeArrayParam(attrs, name, def) {
+ var param = attrs[name];
+ if (param && param.list && param.list.type) {
+ return param.list.type.map(function (v) { return parseDtypeParam(v); });
+ }
+ return def;
+ }
+ function parseTensorShapeParam(shape) {
+ if (shape.unknownRank) {
+ return undefined;
+ }
+ if (shape.dim != null) {
+ return shape.dim.map(function (dim) {
+ return (typeof dim.size === 'number') ? dim.size : parseInt(dim.size, 10);
+ });
+ }
+ return [];
+ }
+ function getTensorShapeParam(attrs, name, def) {
+ var param = attrs[name];
+ if (param && param.shape) {
+ return parseTensorShapeParam(param.shape);
+ }
+ return def;
+ }
+ function getNumericArrayParam(attrs, name, def) {
+ var param = attrs[name];
+ if (param) {
+ return ((param.list.f && param.list.f.length ? param.list.f :
+ param.list.i) ||
+ [])
+ .map(function (v) { return (typeof v === 'number') ? v : parseInt(v, 10); });
+ }
+ return def;
+ }
+ function getStringArrayParam(attrs, name, def, keepCase) {
+ if (keepCase === void 0) { keepCase = false; }
+ var param = attrs[name];
+ if (param && param.list && param.list.s) {
+ return param.list.s.map(function (v) {
+ return parseStringParam(v, keepCase);
+ });
+ }
+ return def;
+ }
+ function getTensorShapeArrayParam(attrs, name, def) {
+ var param = attrs[name];
+ if (param && param.list && param.list.shape) {
+ return param.list.shape.map(function (v) {
+ return parseTensorShapeParam(v);
+ });
+ }
+ return def;
+ }
+ function getBoolArrayParam(attrs, name, def) {
+ var param = attrs[name];
+ if (param && param.list && param.list.b) {
+ return param.list.b;
+ }
+ return def;
+ }
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Helper class for lookup inputs and params for nodes in the model graph.
+ */
+ var NodeValueImpl = /** @class */ (function () {
+ function NodeValueImpl(node, tensorMap, context) {
+ var _this = this;
+ this.node = node;
+ this.tensorMap = tensorMap;
+ this.context = context;
+ this.inputs = [];
+ this.attrs = {};
+ this.inputs = node.inputNames.map(function (name) { return _this.getInput(name); });
+ if (node.rawAttrs != null) {
+ this.attrs = Object.keys(node.rawAttrs)
+ .reduce(function (attrs, key) {
+ attrs[key] = _this.getAttr(key);
+ return attrs;
+ }, {});
+ }
+ }
+ /**
+ * Return the value of the attribute or input param.
+ * @param name String: name of attribute or input param.
+ */
+ NodeValueImpl.prototype.getInput = function (name) {
+ return getTensor(name, this.tensorMap, this.context);
+ };
+ /**
+ * Return the value of the attribute or input param.
+ * @param name String: name of attribute or input param.
+ */
+ NodeValueImpl.prototype.getAttr = function (name, defaultValue) {
+ var value = this.node.rawAttrs[name];
+ if (value.tensor != null) {
+ return getTensor(name, this.tensorMap, this.context);
+ }
+ if (value.i != null || value.f != null) {
+ return getNumberParam(this.node.rawAttrs, name, defaultValue);
+ }
+ if (value.s != null) {
+ return getStringParam(this.node.rawAttrs, name, defaultValue);
+ }
+ if (value.b != null) {
+ return getBoolParam(this.node.rawAttrs, name, defaultValue);
+ }
+ if (value.shape != null) {
+ return getTensorShapeParam(this.node.rawAttrs, name, defaultValue);
+ }
+ if (value.type != null) {
+ return getDtypeParam(this.node.rawAttrs, name, defaultValue);
+ }
+ if (value.list != null) {
+ if (value.list.i != null || value.list.f != null) {
+ return getNumericArrayParam(this.node.rawAttrs, name, defaultValue);
+ }
+ if (value.list.s != null) {
+ return getStringArrayParam(this.node.rawAttrs, name, defaultValue);
+ }
+ if (value.list.shape != null) {
+ return getTensorShapeArrayParam(this.node.rawAttrs, name, defaultValue);
+ }
+ if (value.list.b != null) {
+ return getBoolArrayParam(this.node.rawAttrs, name, defaultValue);
+ }
+ if (value.list.type != null) {
+ return getDtypeArrayParam(this.node.rawAttrs, name, defaultValue);
+ }
+ }
+ return defaultValue;
+ };
+ return NodeValueImpl;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'BiasAdd':
+ case 'AddV2':
+ case 'Add': {
+ return [tfOps.add(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'AddN': {
+ return [tfOps.addN(getParamValue('tensors', node, tensorMap, context))];
+ }
+ case 'FloorMod':
+ case 'Mod':
+ return [tfOps.mod(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ case 'Mul':
+ return [tfOps.mul(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ case 'RealDiv':
+ case 'Div': {
+ return [tfOps.div(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'DivNoNan': {
+ return [tfOps.divNoNan(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'FloorDiv': {
+ return [tfOps.floorDiv(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'Sub': {
+ return [tfOps.sub(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'Minimum': {
+ return [tfOps.minimum(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'Maximum': {
+ return [tfOps.maximum(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'Pow': {
+ return [tfOps.pow(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'SquaredDifference': {
+ return [tfOps.squaredDifference(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$1 = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'Abs':
+ case 'ComplexAbs':
+ return [tfOps.abs(getParamValue('x', node, tensorMap, context))];
+ case 'Acos':
+ return [tfOps.acos(getParamValue('x', node, tensorMap, context))];
+ case 'Acosh':
+ return [tfOps.acosh(getParamValue('x', node, tensorMap, context))];
+ case 'Asin':
+ return [tfOps.asin(getParamValue('x', node, tensorMap, context))];
+ case 'Asinh':
+ return [tfOps.asinh(getParamValue('x', node, tensorMap, context))];
+ case 'Atan':
+ return [tfOps.atan(getParamValue('x', node, tensorMap, context))];
+ case 'Atan2':
+ return [tfOps.atan2(getParamValue('x', node, tensorMap, context), getParamValue('y', node, tensorMap, context))];
+ case 'Atanh':
+ return [tfOps.atanh(getParamValue('x', node, tensorMap, context))];
+ case 'Ceil':
+ return [tfOps.ceil(getParamValue('x', node, tensorMap, context))];
+ case 'Complex':
+ return [tfOps.complex(getParamValue('real', node, tensorMap, context), getParamValue('imag', node, tensorMap, context))];
+ case 'Cos':
+ return [tfOps.cos(getParamValue('x', node, tensorMap, context))];
+ case 'Cosh':
+ return [tfOps.cosh(getParamValue('x', node, tensorMap, context))];
+ case 'Elu':
+ return [tfOps.elu(getParamValue('x', node, tensorMap, context))];
+ case 'Erf':
+ return [tfOps.erf(getParamValue('x', node, tensorMap, context))];
+ case 'Exp':
+ return [tfOps.exp(getParamValue('x', node, tensorMap, context))];
+ case 'Expm1': {
+ return [tfOps.expm1(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Floor':
+ return [tfOps.floor(getParamValue('x', node, tensorMap, context))];
+ case 'Log':
+ return [tfOps.log(getParamValue('x', node, tensorMap, context))];
+ case 'Log1p': {
+ return [tfOps.log1p(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Imag':
+ return [tfOps.imag(getParamValue('x', node, tensorMap, context))];
+ case 'Neg':
+ return [tfOps.neg(getParamValue('x', node, tensorMap, context))];
+ case 'Reciprocal': {
+ return [tfOps.reciprocal(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Real':
+ return [tfOps.real(getParamValue('x', node, tensorMap, context))];
+ case 'Relu':
+ return [tfOps.relu(getParamValue('x', node, tensorMap, context))];
+ case 'Round': {
+ return [tfOps.round(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Selu':
+ return [tfOps.selu(getParamValue('x', node, tensorMap, context))];
+ case 'Sigmoid':
+ return [tfOps.sigmoid(getParamValue('x', node, tensorMap, context))];
+ case 'Sin':
+ return [tfOps.sin(getParamValue('x', node, tensorMap, context))];
+ case 'Sign': {
+ return [tfOps.sign(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Sinh': {
+ return [tfOps.sinh(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Softplus': {
+ return [tfOps.softplus(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Sqrt': {
+ return [tfOps.sqrt(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Square': {
+ return [tfOps.square(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Tanh': {
+ return [tfOps.tanh(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'Tan':
+ return [tfOps.tan(getParamValue('x', node, tensorMap, context))];
+ case 'ClipByValue':
+ return [tfOps.clipByValue(getParamValue('x', node, tensorMap, context), getParamValue('clipValueMin', node, tensorMap, context), getParamValue('clipValueMax', node, tensorMap, context))];
+ case 'Relu6':
+ return [tfOps.relu6(getParamValue('x', node, tensorMap, context))];
+ case 'Rsqrt':
+ return [tfOps.rsqrt(getTensor(node.inputNames[0], tensorMap, context))];
+ case 'Prod':
+ return [tfOps.prod(getParamValue('x', node, tensorMap, context), getParamValue('axes', node, tensorMap, context))];
+ case 'LeakyRelu':
+ return [tfOps.leakyRelu(getParamValue('x', node, tensorMap, context), getParamValue('alpha', node, tensorMap, context))];
+ case 'Prelu':
+ return [tfOps.prelu(getParamValue('x', node, tensorMap, context), getParamValue('alpha', node, tensorMap, context))];
+ case 'IsNan':
+ return [tfOps.isNaN(getTensor(node.inputNames[0], tensorMap, context))];
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Used by TensorList and TensorArray to verify if elementShape matches, support
+ * negative value as the dim shape.
+ * @param shapeA
+ * @param shapeB
+ * @param errorMessagePrefix
+ */
+ function assertShapesMatchAllowUndefinedSize(shapeA, shapeB, errorMessagePrefix) {
+ if (errorMessagePrefix === void 0) { errorMessagePrefix = ''; }
+ // constant shape means unknown rank
+ if (typeof shapeA === 'number' || typeof shapeB === 'number') {
+ return;
+ }
+ tfc.util.assert(shapeA.length === shapeB.length, function () { return errorMessagePrefix + (" Shapes " + shapeA + " and " + shapeB + " must match"); });
+ for (var i = 0; i < shapeA.length; i++) {
+ var dim0 = shapeA[i];
+ var dim1 = shapeB[i];
+ tfc.util.assert(dim0 < 0 || dim1 < 0 || dim0 === dim1, function () {
+ return errorMessagePrefix + (" Shapes " + shapeA + " and " + shapeB + " must match");
+ });
+ }
+ }
+ function fullDefinedShape(elementShape) {
+ if (typeof elementShape === 'number' || elementShape.some(function (dim) { return dim < 0; })) {
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Generate the output element shape from the list elementShape, list tensors
+ * and input param.
+ * @param listElementShape
+ * @param tensors
+ * @param elementShape
+ */
+ function inferElementShape(listElementShape, tensors, elementShape) {
+ var partialShape = mergeElementShape(listElementShape, elementShape);
+ var notfullDefinedShape = !fullDefinedShape(partialShape);
+ if (notfullDefinedShape && tensors.length === 0) {
+ throw new Error("Tried to calculate elements of an empty list" +
+ (" with non-fully-defined elementShape: " + partialShape));
+ }
+ if (notfullDefinedShape) {
+ tensors.forEach(function (tensor) {
+ partialShape = mergeElementShape(tensor.shape, partialShape);
+ });
+ }
+ if (!fullDefinedShape(partialShape)) {
+ throw new Error("Non-fully-defined elementShape: " + partialShape);
+ }
+ return partialShape;
+ }
+ function mergeElementShape(elementShapeA, elementShapeB) {
+ if (typeof elementShapeA === 'number') {
+ return elementShapeB;
+ }
+ if (typeof elementShapeB === 'number') {
+ return elementShapeA;
+ }
+ if (elementShapeA.length !== elementShapeB.length) {
+ throw new Error("Incompatible ranks during merge: " + elementShapeA + " vs. " + elementShapeB);
+ }
+ var result = [];
+ for (var i = 0; i < elementShapeA.length; ++i) {
+ var dim0 = elementShapeA[i];
+ var dim1 = elementShapeB[i];
+ if (dim0 >= 0 && dim1 >= 0 && dim0 !== dim1) {
+ throw new Error("Incompatible shape during merge: " + elementShapeA + " vs. " + elementShapeB);
+ }
+ result[i] = dim0 >= 0 ? dim0 : dim1;
+ }
+ return result;
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * The TensorArray object keeps an array of Tensors. It
+ * allows reading from the array and writing to the array.
+ */
+ var TensorArray = /** @class */ (function () {
+ function TensorArray(name, dtype, maxSize, elementShape, identicalElementShapes, dynamicSize, clearAfterRead) {
+ this.name = name;
+ this.dtype = dtype;
+ this.maxSize = maxSize;
+ this.elementShape = elementShape;
+ this.identicalElementShapes = identicalElementShapes;
+ this.dynamicSize = dynamicSize;
+ this.clearAfterRead = clearAfterRead;
+ this.tensors = [];
+ this.closed_ = false;
+ this.idTensor = tfc.scalar(0);
+ tfc.keep(this.idTensor);
+ }
+ Object.defineProperty(TensorArray.prototype, "id", {
+ get: function () {
+ return this.idTensor.id;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(TensorArray.prototype, "closed", {
+ get: function () {
+ return this.closed_;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ /**
+ * Dispose the tensors and idTensor and mark the TensoryArray as closed.
+ */
+ TensorArray.prototype.clearAndClose = function (keepIds) {
+ this.tensors.forEach(function (tensor) {
+ if (keepIds == null || !keepIds.has(tensor.tensor.id)) {
+ tensor.tensor.dispose();
+ }
+ });
+ this.tensors = [];
+ this.closed_ = true;
+ this.idTensor.dispose();
+ };
+ TensorArray.prototype.size = function () {
+ return this.tensors.length;
+ };
+ /**
+ * Read the value at location index in the TensorArray.
+ * @param index Number the index to read from.
+ */
+ TensorArray.prototype.read = function (index) {
+ if (this.closed_) {
+ throw new Error("TensorArray " + this.name + " has already been closed.");
+ }
+ if (index < 0 || index >= this.size()) {
+ throw new Error("Tried to read from index " + index + ", but array size is: " + this.size());
+ }
+ var tensorWithState = this.tensors[index];
+ if (tensorWithState.cleared) {
+ throw new Error("TensorArray " + this.name + ": Could not read index " + index + " twice because it was cleared after a previous read " +
+ "(perhaps try setting clear_after_read = false?).");
+ }
+ if (this.clearAfterRead) {
+ tensorWithState.cleared = true;
+ }
+ tensorWithState.read = true;
+ return tensorWithState.tensor;
+ };
+ /**
+ * Helper method to read multiple tensors from the specified indices.
+ */
+ TensorArray.prototype.readMany = function (indices) {
+ var _this = this;
+ return indices.map(function (index) { return _this.read(index); });
+ };
+ /**
+ * Write value into the index of the TensorArray.
+ * @param index number the index to write to.
+ * @param tensor
+ */
+ TensorArray.prototype.write = function (index, tensor) {
+ if (this.closed_) {
+ throw new Error("TensorArray " + this.name + " has already been closed.");
+ }
+ if (index < 0 || !this.dynamicSize && index >= this.maxSize) {
+ throw new Error("Tried to write to index " + index + ", but array is not resizeable and size is: " + this.maxSize);
+ }
+ var t = this.tensors[index] || {};
+ if (tensor.dtype !== this.dtype) {
+ throw new Error("TensorArray " + this.name + ": Could not write to TensorArray index " + index + ",\n because the value dtype is " + tensor.dtype + ", but TensorArray dtype is " + this.dtype + ".");
+ }
+ // Set the shape for the first time write to unknow shape tensor array
+ if (this.size() === 0 &&
+ (this.elementShape == null || this.elementShape.length === 0)) {
+ this.elementShape = tensor.shape;
+ }
+ assertShapesMatchAllowUndefinedSize(this.elementShape, tensor.shape, "TensorArray " + this.name + ": Could not write to TensorArray index " + index + ".");
+ if (t.read) {
+ throw new Error("TensorArray " + this.name + ": Could not write to TensorArray index " + index + ", because it has already been read.");
+ }
+ if (t.written) {
+ throw new Error("TensorArray " + this.name + ": Could not write to TensorArray index " + index + ", because it has already been written.");
+ }
+ t.tensor = tensor;
+ tfc.keep(tensor);
+ t.written = true;
+ this.tensors[index] = t;
+ };
+ /**
+ * Helper method to write multiple tensors to the specified indices.
+ */
+ TensorArray.prototype.writeMany = function (indices, tensors) {
+ var _this = this;
+ if (indices.length !== tensors.length) {
+ throw new Error("TensorArray " + this.name + ": could not write multiple tensors," +
+ ("because the index size: " + indices.length + " is not the same as tensors size: " + tensors.length + "."));
+ }
+ indices.forEach(function (i, index) { return _this.write(i, tensors[index]); });
+ };
+ /**
+ * Return selected values in the TensorArray as a packed Tensor. All of
+ * selected values must have been written and their shapes must all match.
+ * @param [indices] number[] Optional. Taking values in [0, max_value). If the
+ * TensorArray is not dynamic, max_value=size(). If not specified returns
+ * all tensors in the original order.
+ * @param [dtype]
+ */
+ TensorArray.prototype.gather = function (indices, dtype) {
+ if (!!dtype && dtype !== this.dtype) {
+ throw new Error("TensorArray dtype is " + this.dtype + " but gather requested dtype " + dtype);
+ }
+ if (!indices) {
+ indices = [];
+ for (var i = 0; i < this.size(); i++) {
+ indices.push(i);
+ }
+ }
+ else {
+ indices = indices.slice(0, this.size());
+ }
+ if (indices.length === 0) {
+ return tfc.tensor([], [0].concat(this.elementShape));
+ }
+ // Read all the PersistentTensors into a vector to keep track of
+ // their memory.
+ var tensors = this.readMany(indices);
+ assertShapesMatchAllowUndefinedSize(this.elementShape, tensors[0].shape, 'TensorArray shape mismatch: ');
+ return tfc.stack(tensors, 0);
+ };
+ /**
+ * Return the values in the TensorArray as a concatenated Tensor.
+ */
+ TensorArray.prototype.concat = function (dtype) {
+ if (!!dtype && dtype !== this.dtype) {
+ throw new Error("TensorArray dtype is " + this.dtype + " but concat requested dtype " + dtype);
+ }
+ if (this.size() === 0) {
+ return tfc.tensor([], [0].concat(this.elementShape));
+ }
+ var indices = [];
+ for (var i = 0; i < this.size(); i++) {
+ indices.push(i);
+ }
+ // Collect all the tensors from the tensors array.
+ var tensors = this.readMany(indices);
+ assertShapesMatchAllowUndefinedSize(this.elementShape, tensors[0].shape, "TensorArray shape mismatch: tensor array shape (" + this.elementShape + ") vs first tensor shape (" + tensors[0].shape + ")");
+ return tfc.concat(tensors, 0);
+ };
+ /**
+ * Scatter the values of a Tensor in specific indices of a TensorArray.
+ * @param indices nummber[] values in [0, max_value). If the
+ * TensorArray is not dynamic, max_value=size().
+ * @param tensor Tensor input tensor.
+ */
+ TensorArray.prototype.scatter = function (indices, tensor) {
+ if (tensor.dtype !== this.dtype) {
+ throw new Error("TensorArray dtype is " + this.dtype + " but tensor has dtype " + tensor.dtype);
+ }
+ if (indices.length !== tensor.shape[0]) {
+ throw new Error("Expected len(indices) == tensor.shape[0], but saw: " + indices.length + " vs. " + tensor.shape[0]);
+ }
+ var maxIndex = Math.max.apply(Math, __spread(indices));
+ if (!this.dynamicSize && maxIndex >= this.maxSize) {
+ throw new Error("Max index must be < array size (" + maxIndex + " vs. " + this.maxSize + ")");
+ }
+ this.writeMany(indices, tfc.unstack(tensor, 0));
+ };
+ /**
+ * Split the values of a Tensor into the TensorArray.
+ * @param length number[] with the lengths to use when splitting value along
+ * its first dimension.
+ * @param tensor Tensor, the tensor to split.
+ */
+ TensorArray.prototype.split = function (length, tensor) {
+ var _this = this;
+ if (tensor.dtype !== this.dtype) {
+ throw new Error("TensorArray dtype is " + this.dtype + " but tensor has dtype " + tensor.dtype);
+ }
+ var totalLength = 0;
+ var cumulativeLengths = length.map(function (len) {
+ totalLength += len;
+ return totalLength;
+ });
+ if (totalLength !== tensor.shape[0]) {
+ throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n " + totalLength + ", and tensor's shape is: " + tensor.shape);
+ }
+ if (!this.dynamicSize && length.length !== this.maxSize) {
+ throw new Error("TensorArray's size is not equal to the size of lengths (" + this.maxSize + " vs. " + length.length + "), " +
+ 'and the TensorArray is not marked as dynamically resizeable');
+ }
+ var elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;
+ var tensors = [];
+ tfc.tidy(function () {
+ tensor = tfc.reshape(tensor, [1, totalLength, elementPerRow]);
+ for (var i = 0; i < length.length; ++i) {
+ var previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];
+ var indices_1 = [0, previousLength, 0];
+ var sizes = [1, length[i], elementPerRow];
+ tensors[i] = tfc.reshape(tfc.slice(tensor, indices_1, sizes), _this.elementShape);
+ }
+ return tensors;
+ });
+ var indices = [];
+ for (var i = 0; i < length.length; i++) {
+ indices[i] = i;
+ }
+ this.writeMany(indices, tensors);
+ };
+ return TensorArray;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * TensorList stores a container of `tf.Tensor` objects, which are accessible
+ * via tensors field.
+ *
+ * In order to get a copy of the underlying list, use the copy method:
+ * ```
+ * TensorList b = a.copy();
+ * b.tensors().pushBack(t); // This does not modify a.tensors().
+ * ```
+ *
+ * Note that this is not a deep copy: the memory locations of the underlying
+ * tensors will still point to the same locations of the corresponding tensors
+ * in the original.
+ */
+ var TensorList = /** @class */ (function () {
+ /**
+ *
+ * @param tensors list of tensors
+ * @param elementShape shape of each tensor, this can be a single number (any
+ * shape is allowed) or partial shape (dim = -1).
+ * @param elementDtype data type of each tensor
+ * @param maxNumElements The maximum allowed size of `tensors`. Defaults to -1
+ * meaning that the size of `tensors` is unbounded.
+ */
+ function TensorList(tensors, elementShape, elementDtype, maxNumElements) {
+ if (maxNumElements === void 0) { maxNumElements = -1; }
+ this.tensors = tensors;
+ this.elementShape = elementShape;
+ this.elementDtype = elementDtype;
+ if (tensors != null) {
+ tensors.forEach(function (tensor) {
+ if (elementDtype !== tensor.dtype) {
+ throw new Error("Invalid data types; op elements " + elementDtype + ", but list elements " + tensor.dtype);
+ }
+ assertShapesMatchAllowUndefinedSize(elementShape, tensor.shape, 'TensorList shape mismatch: ');
+ tfc.keep(tensor);
+ });
+ }
+ this.idTensor = tfc.scalar(0);
+ this.maxNumElements = maxNumElements;
+ tfc.keep(this.idTensor);
+ }
+ Object.defineProperty(TensorList.prototype, "id", {
+ get: function () {
+ return this.idTensor.id;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ /**
+ * Get a new TensorList containing a copy of the underlying tensor container.
+ */
+ TensorList.prototype.copy = function () {
+ return new TensorList(__spread(this.tensors), this.elementShape, this.elementDtype);
+ };
+ /**
+ * Dispose the tensors and idTensor and clear the tensor list.
+ */
+ TensorList.prototype.clearAndClose = function (keepIds) {
+ this.tensors.forEach(function (tensor) {
+ if (keepIds == null || !keepIds.has(tensor.id)) {
+ tensor.dispose();
+ }
+ });
+ this.tensors.length = 0;
+ this.idTensor.dispose();
+ };
+ /**
+ * The size of the tensors in the tensor list.
+ */
+ TensorList.prototype.size = function () {
+ return this.tensors.length;
+ };
+ /**
+ * Return a tensor that stacks a list of rank-R tf.Tensors into one rank-(R+1)
+ * tf.Tensor.
+ * @param elementShape shape of each tensor
+ * @param elementDtype data type of each tensor
+ * @param numElements the number of elements to stack
+ */
+ TensorList.prototype.stack = function (elementShape, elementDtype, numElements) {
+ var _this = this;
+ if (numElements === void 0) { numElements = -1; }
+ if (elementDtype !== this.elementDtype) {
+ throw new Error("Invalid data types; op elements " + elementDtype + ", but list elements " + this.elementDtype);
+ }
+ if (numElements !== -1 && this.tensors.length !== numElements) {
+ throw new Error("Operation expected a list with " + numElements + " elements but got a list with " + this.tensors.length + " elements.");
+ }
+ assertShapesMatchAllowUndefinedSize(elementShape, this.elementShape, 'TensorList shape mismatch: ');
+ var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
+ return tfc.tidy(function () {
+ var reshapedTensors = _this.tensors.map(function (tensor) { return tfc.reshape(tensor, outputElementShape); });
+ return tfc.stack(reshapedTensors, 0);
+ });
+ };
+ /**
+ * Pop a tensor from the end of the list.
+ * @param elementShape shape of the tensor
+ * @param elementDtype data type of the tensor
+ */
+ TensorList.prototype.popBack = function (elementShape, elementDtype) {
+ if (elementDtype !== this.elementDtype) {
+ throw new Error("Invalid data types; op elements " + elementDtype + ", but list elements " + this.elementDtype);
+ }
+ if (this.size() === 0) {
+ throw new Error('Trying to pop from an empty list.');
+ }
+ var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
+ var tensor = this.tensors.pop();
+ assertShapesMatchAllowUndefinedSize(tensor.shape, elementShape, 'TensorList shape mismatch: ');
+ return tfc.reshape(tensor, outputElementShape);
+ };
+ /**
+ * Push a tensor to the end of the list.
+ * @param tensor Tensor to be pushed.
+ */
+ TensorList.prototype.pushBack = function (tensor) {
+ if (tensor.dtype !== this.elementDtype) {
+ throw new Error("Invalid data types; op elements " + tensor.dtype + ", but list elements " + this.elementDtype);
+ }
+ assertShapesMatchAllowUndefinedSize(tensor.shape, this.elementShape, 'TensorList shape mismatch: ');
+ if (this.maxNumElements === this.size()) {
+ throw new Error("Trying to push element into a full list.");
+ }
+ tfc.keep(tensor);
+ this.tensors.push(tensor);
+ };
+ /**
+ * Update the size of the list.
+ * @param size the new size of the list.
+ */
+ TensorList.prototype.resize = function (size) {
+ if (size < 0) {
+ throw new Error("TensorListResize expects size to be non-negative. Got: " + size);
+ }
+ if (this.maxNumElements !== -1 && size > this.maxNumElements) {
+ throw new Error("TensorListResize input size " + size + " is greater maxNumElement " + this.maxNumElements + ".");
+ }
+ this.tensors.length = size;
+ };
+ /**
+ * Retrieve the element at the provided index
+ * @param elementShape shape of the tensor
+ * @param elementDtype dtype of the tensor
+ * @param elementIndex index of the tensor
+ */
+ TensorList.prototype.getItem = function (elementIndex, elementShape, elementDtype) {
+ if (elementDtype !== this.elementDtype) {
+ throw new Error("Invalid data types; op elements " + elementDtype + ", but list elements " + this.elementDtype);
+ }
+ if (elementIndex < 0 || elementIndex > this.tensors.length) {
+ throw new Error("Trying to access element " + elementIndex + " in a list with " + this.tensors.length + " elements.");
+ }
+ if (this.tensors[elementIndex] == null) {
+ throw new Error("element at index " + elementIndex + " is null.");
+ }
+ assertShapesMatchAllowUndefinedSize(this.tensors[elementIndex].shape, elementShape, 'TensorList shape mismatch: ');
+ var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
+ return tfc.reshape(this.tensors[elementIndex], outputElementShape);
+ };
+ /**
+ * Set the tensor at the index
+ * @param elementIndex index of the tensor
+ * @param tensor the tensor to be inserted into the list
+ */
+ TensorList.prototype.setItem = function (elementIndex, tensor) {
+ if (tensor.dtype !== this.elementDtype) {
+ throw new Error("Invalid data types; op elements " + tensor.dtype + ", but list elements " + this.elementDtype);
+ }
+ if (elementIndex < 0 ||
+ this.maxNumElements !== -1 && elementIndex >= this.maxNumElements) {
+ throw new Error("Trying to set element " + elementIndex + " in a list with max " + this.maxNumElements + " elements.");
+ }
+ assertShapesMatchAllowUndefinedSize(this.elementShape, tensor.shape, 'TensorList shape mismatch: ');
+ tfc.keep(tensor);
+ this.tensors[elementIndex] = tensor;
+ };
+ /**
+ * Return selected values in the TensorList as a stacked Tensor. All of
+ * selected values must have been written and their shapes must all match.
+ * @param indices indices of tensors to gather
+ * @param elementDtype output tensor dtype
+ * @param elementShape output tensor element shape
+ */
+ TensorList.prototype.gather = function (indices, elementDtype, elementShape) {
+ var _this = this;
+ if (elementDtype !== this.elementDtype) {
+ throw new Error("Invalid data types; op elements " + elementDtype + ", but list elements " + this.elementDtype);
+ }
+ assertShapesMatchAllowUndefinedSize(this.elementShape, elementShape, 'TensorList shape mismatch: ');
+ // When indices is greater than the size of the list, indices beyond the
+ // size of the list are ignored.
+ indices = indices.slice(0, this.size());
+ var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
+ if (indices.length === 0) {
+ return tfc.tensor([], [0].concat(outputElementShape));
+ }
+ return tfc.tidy(function () {
+ var tensors = indices.map(function (i) { return tfc.reshape(_this.tensors[i], outputElementShape); });
+ return tfc.stack(tensors, 0);
+ });
+ };
+ /**
+ * Return the values in the TensorList as a concatenated Tensor.
+ * @param elementDtype output tensor dtype
+ * @param elementShape output tensor element shape
+ */
+ TensorList.prototype.concat = function (elementDtype, elementShape) {
+ var _this = this;
+ if (!!elementDtype && elementDtype !== this.elementDtype) {
+ throw new Error("TensorList dtype is " + this.elementDtype + " but concat requested dtype " + elementDtype);
+ }
+ assertShapesMatchAllowUndefinedSize(this.elementShape, elementShape, 'TensorList shape mismatch: ');
+ var outputElementShape = inferElementShape(this.elementShape, this.tensors, elementShape);
+ if (this.size() === 0) {
+ return tfc.tensor([], [0].concat(outputElementShape));
+ }
+ return tfc.tidy(function () {
+ var tensors = _this.tensors.map(function (t) { return tfc.reshape(t, outputElementShape); });
+ return tfc.concat(tensors, 0);
+ });
+ };
+ return TensorList;
+ }());
+ /**
+ * Creates a TensorList which, when stacked, has the value of tensor.
+ * @param tensor from tensor
+ * @param elementShape output tensor element shape
+ */
+ function fromTensor(tensor, elementShape, elementDtype) {
+ var dtype = tensor.dtype;
+ if (tensor.shape.length < 1) {
+ throw new Error("Tensor must be at least a vector, but saw shape: " + tensor.shape);
+ }
+ if (tensor.dtype !== elementDtype) {
+ throw new Error("Invalid data types; op elements " + tensor.dtype + ", but list elements " + elementDtype);
+ }
+ var tensorElementShape = tensor.shape.slice(1);
+ assertShapesMatchAllowUndefinedSize(tensorElementShape, elementShape, 'TensorList shape mismatch: ');
+ var tensorList = tfc.unstack(tensor);
+ return new TensorList(tensorList, elementShape, dtype);
+ }
+ /**
+ * Return a TensorList of the given size with empty elements.
+ * @param elementShape the shape of the future elements of the list
+ * @param elementDtype the desired type of elements in the list
+ * @param numElements the number of elements to reserve
+ */
+ function reserve(elementShape, elementDtype, numElements) {
+ return new TensorList([], elementShape, elementDtype, numElements);
+ }
+ /**
+ * Put tensors at specific indices of a stacked tensor into a TensorList.
+ * @param indices list of indices on how to scatter the tensor.
+ * @param tensor input tensor.
+ * @param elementShape the shape of the future elements of the list
+ * @param numElements the number of elements to scatter
+ */
+ function scatter(tensor, indices, elementShape, numElements) {
+ if (indices.length !== tensor.shape[0]) {
+ throw new Error("Expected len(indices) == tensor.shape[0], but saw: " + indices.length + " vs. " + tensor.shape[0]);
+ }
+ var maxIndex = Math.max.apply(Math, __spread(indices));
+ if (numElements != null && numElements !== -1 && maxIndex >= numElements) {
+ throw new Error("Max index must be < array size (" + maxIndex + " vs. " + numElements + ")");
+ }
+ var list = new TensorList([], elementShape, tensor.dtype, numElements);
+ var tensors = tfc.unstack(tensor, 0);
+ indices.forEach(function (value, index) {
+ list.setItem(value, tensors[index]);
+ });
+ return list;
+ }
+ /**
+ * Split the values of a Tensor into a TensorList.
+ * @param length the lengths to use when splitting value along
+ * its first dimension.
+ * @param tensor the tensor to split.
+ * @param elementShape the shape of the future elements of the list
+ */
+ function split(tensor, length, elementShape) {
+ var totalLength = 0;
+ var cumulativeLengths = length.map(function (len) {
+ totalLength += len;
+ return totalLength;
+ });
+ if (totalLength !== tensor.shape[0]) {
+ throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n " + totalLength + ", and tensor's shape is: " + tensor.shape);
+ }
+ var shapeWithoutFirstDim = tensor.shape.slice(1);
+ var outputElementShape = mergeElementShape(shapeWithoutFirstDim, elementShape);
+ var elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;
+ var tensors = tfc.tidy(function () {
+ var tensors = [];
+ tensor = tfc.reshape(tensor, [1, totalLength, elementPerRow]);
+ for (var i = 0; i < length.length; ++i) {
+ var previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];
+ var indices = [0, previousLength, 0];
+ var sizes = [1, length[i], elementPerRow];
+ tensors[i] = tfc.reshape(tfc.slice(tensor, indices, sizes), outputElementShape);
+ }
+ tensor.dispose();
+ return tensors;
+ });
+ var list = new TensorList([], elementShape, tensor.dtype, length.length);
+ for (var i = 0; i < tensors.length; i++) {
+ list.setItem(i, tensors[i]);
+ }
+ return list;
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var _this = undefined;
+ var executeOp$2 = function (node, tensorMap, context) { return __awaiter(_this, void 0, void 0, function () {
+ var _a, thenFunc, elseFunc, cond, args, condValue, bodyFunc, condFunc, args, condResult, argIds_1, condValue, result, _loop_1, pred, pred, data, inputName, data, frameId, data, data, data, size, dtype, elementShape, dynamicSize, clearAfterRead, identicalElementShapes, name_1, tensorArray, id, index, writeTensor, writeTensorArray, readId, readIndex, readTensorArray, gatherId, gatherIndices, gatherDtype, gatherTensorArray, scatterId, scatterIndices, scatterTensor, scatterTensorArray, concatId, concatTensorArray, concatDtype, splitId, splitTensor, lengths, splitTensorArray, sizeId, sizeTensorArray, closeId, closeTensorArray, idTensor, index, writeTensor, tensorList, idTensor, readIndex, elementShape, elementDType, tensorList, scatterIndices, scatterTensor, elementShape, numElements, tensorList, elementShape, elementDtype, numElementsParam, numElements, tensorList, gatherId, gatherIndices, elementShape, elementDtype, tensorList, idTensor, elementShape, elementDtype, numElements, tensorList, tensor, elementShape, elementDtype, tensorList, concatId, tensorList, concatDtype, elementShape, idTensor, writeTensor, tensorList, idTensor, elementShape, elementDType, tensorList, splitTensor, elementShape, lengths, tensorList;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ _a = node.op;
+ switch (_a) {
+ case 'If': return [3 /*break*/, 1];
+ case 'StatelessIf': return [3 /*break*/, 1];
+ case 'While': return [3 /*break*/, 3];
+ case 'StatelessWhile': return [3 /*break*/, 3];
+ case 'LoopCond': return [3 /*break*/, 9];
+ case 'Switch': return [3 /*break*/, 10];
+ case 'Merge': return [3 /*break*/, 12];
+ case 'Enter': return [3 /*break*/, 13];
+ case 'Exit': return [3 /*break*/, 14];
+ case 'NextIteration': return [3 /*break*/, 15];
+ case 'TensorArrayV3': return [3 /*break*/, 16];
+ case 'TensorArrayWriteV3': return [3 /*break*/, 17];
+ case 'TensorArrayReadV3': return [3 /*break*/, 18];
+ case 'TensorArrayGatherV3': return [3 /*break*/, 19];
+ case 'TensorArrayScatterV3': return [3 /*break*/, 20];
+ case 'TensorArrayConcatV3': return [3 /*break*/, 21];
+ case 'TensorArraySplitV3': return [3 /*break*/, 22];
+ case 'TensorArraySizeV3': return [3 /*break*/, 23];
+ case 'TensorArrayCloseV3': return [3 /*break*/, 24];
+ case 'TensorListSetItem': return [3 /*break*/, 25];
+ case 'TensorListGetItem': return [3 /*break*/, 26];
+ case 'TensorListScatterV2': return [3 /*break*/, 27];
+ case 'TensorListScatter': return [3 /*break*/, 27];
+ case 'TensorListReserve': return [3 /*break*/, 28];
+ case 'EmptyTensorList': return [3 /*break*/, 28];
+ case 'TensorListGather': return [3 /*break*/, 29];
+ case 'TensorListStack': return [3 /*break*/, 30];
+ case 'TensorListFromTensor': return [3 /*break*/, 31];
+ case 'TensorListConcat': return [3 /*break*/, 32];
+ case 'TensorListPushBack': return [3 /*break*/, 33];
+ case 'TensorListPopBack': return [3 /*break*/, 34];
+ case 'TensorListSplit': return [3 /*break*/, 35];
+ }
+ return [3 /*break*/, 36];
+ case 1:
+ thenFunc = getParamValue('thenBranch', node, tensorMap, context);
+ elseFunc = getParamValue('elseBranch', node, tensorMap, context);
+ cond = getParamValue('cond', node, tensorMap, context);
+ args = getParamValue('args', node, tensorMap, context);
+ return [4 /*yield*/, cond.data()];
+ case 2:
+ condValue = _b.sent();
+ if (condValue[0]) {
+ return [2 /*return*/, context.functionMap[thenFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap)];
+ }
+ else {
+ return [2 /*return*/, context.functionMap[elseFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap)];
+ }
+ case 3:
+ bodyFunc = getParamValue('body', node, tensorMap, context);
+ condFunc = getParamValue('cond', node, tensorMap, context);
+ args = getParamValue('args', node, tensorMap, context);
+ return [4 /*yield*/, context.functionMap[condFunc].executeFunctionAsync(args, context.tensorArrayMap, context.tensorListMap)];
+ case 4:
+ condResult = (_b.sent());
+ argIds_1 = args.map(function (tensor) { return tensor.id; });
+ return [4 /*yield*/, condResult[0].data()];
+ case 5:
+ condValue = _b.sent();
+ // Dispose the intermediate tensors for condition function
+ condResult.forEach(function (tensor) {
+ if (!tensor.kept && argIds_1.indexOf(tensor.id) === -1) {
+ tensor.dispose();
+ }
+ });
+ result = args;
+ _loop_1 = function () {
+ var origResult, resultIds, condResult_1;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ origResult = result;
+ return [4 /*yield*/, context.functionMap[bodyFunc].executeFunctionAsync(result, context.tensorArrayMap, context.tensorListMap)];
+ case 1:
+ // Execution the body of the loop
+ result = _a.sent();
+ resultIds = result.map(function (tensor) { return tensor.id; });
+ // Dispose the intermediate tensor for body function that is not global
+ // kept, not input/output of the body function
+ origResult.forEach(function (tensor) {
+ if (!tensor.kept && argIds_1.indexOf(tensor.id) === -1 &&
+ resultIds.indexOf(tensor.id) === -1) {
+ tensor.dispose();
+ }
+ });
+ return [4 /*yield*/, context.functionMap[condFunc].executeFunctionAsync(result, context.tensorArrayMap, context.tensorListMap)];
+ case 2:
+ condResult_1 = (_a.sent());
+ return [4 /*yield*/, condResult_1[0].data()];
+ case 3:
+ condValue = _a.sent();
+ // Dispose the intermediate tensors for condition function
+ condResult_1.forEach(function (tensor) {
+ if (!tensor.kept && argIds_1.indexOf(tensor.id) === -1 &&
+ resultIds.indexOf(tensor.id) === -1) {
+ tensor.dispose();
+ }
+ });
+ return [2 /*return*/];
+ }
+ });
+ };
+ _b.label = 6;
+ case 6:
+ if (!condValue[0]) return [3 /*break*/, 8];
+ return [5 /*yield**/, _loop_1()];
+ case 7:
+ _b.sent();
+ return [3 /*break*/, 6];
+ case 8: return [2 /*return*/, result];
+ case 9:
+ {
+ pred = getParamValue('pred', node, tensorMap, context);
+ return [2 /*return*/, [cloneTensor(pred)]];
+ }
+ case 10:
+ pred = getParamValue('pred', node, tensorMap, context);
+ data = getParamValue('data', node, tensorMap, context);
+ if (!data.kept) {
+ data = cloneTensor(data);
+ }
+ return [4 /*yield*/, pred.data()];
+ case 11:
+ // Outputs nodes :0 => false, :1 => true
+ return [2 /*return*/, (_b.sent())[0] ? [undefined, data] : [data, undefined]];
+ case 12:
+ {
+ inputName = node.inputNames.find(function (name) { return getTensor(name, tensorMap, context) !== undefined; });
+ if (inputName) {
+ data = getTensor(inputName, tensorMap, context);
+ return [2 /*return*/, [cloneTensor(data)]];
+ }
+ return [2 /*return*/, undefined];
+ }
+ case 13:
+ {
+ frameId = getParamValue('frameName', node, tensorMap, context);
+ data = getParamValue('tensor', node, tensorMap, context);
+ context.enterFrame(frameId);
+ return [2 /*return*/, [cloneTensor(data)]];
+ }
+ case 14:
+ {
+ data = getParamValue('tensor', node, tensorMap, context);
+ context.exitFrame();
+ return [2 /*return*/, [cloneTensor(data)]];
+ }
+ case 15:
+ {
+ data = getParamValue('tensor', node, tensorMap, context);
+ context.nextIteration();
+ return [2 /*return*/, [cloneTensor(data)]];
+ }
+ case 16:
+ {
+ size = getParamValue('size', node, tensorMap, context);
+ dtype = getParamValue('dtype', node, tensorMap, context);
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ dynamicSize = getParamValue('dynamicSize', node, tensorMap, context);
+ clearAfterRead = getParamValue('clearAfterRead', node, tensorMap, context);
+ identicalElementShapes = getParamValue('identicalElementShapes', node, tensorMap, context);
+ name_1 = getParamValue('name', node, tensorMap, context);
+ tensorArray = new TensorArray(name_1, dtype, size, elementShape, identicalElementShapes, dynamicSize, clearAfterRead);
+ context.addTensorArray(tensorArray);
+ return [2 /*return*/, [tensorArray.idTensor, tfc.scalar(1.0)]];
+ }
+ case 17:
+ {
+ id = getParamValue('tensorArrayId', node, tensorMap, context);
+ index = getParamValue('index', node, tensorMap, context);
+ writeTensor = getParamValue('tensor', node, tensorMap, context);
+ writeTensorArray = context.getTensorArray(id.id);
+ writeTensorArray.write(index, writeTensor);
+ return [2 /*return*/, [writeTensorArray.idTensor]];
+ }
+ case 18:
+ {
+ readId = getParamValue('tensorArrayId', node, tensorMap, context);
+ readIndex = getParamValue('index', node, tensorMap, context);
+ readTensorArray = context.getTensorArray(readId.id);
+ return [2 /*return*/, [readTensorArray.read(readIndex)]];
+ }
+ case 19:
+ {
+ gatherId = getParamValue('tensorArrayId', node, tensorMap, context);
+ gatherIndices = getParamValue('indices', node, tensorMap, context);
+ gatherDtype = getParamValue('dtype', node, tensorMap, context);
+ gatherTensorArray = context.getTensorArray(gatherId.id);
+ return [2 /*return*/, [gatherTensorArray.gather(gatherIndices, gatherDtype)]];
+ }
+ case 20:
+ {
+ scatterId = getParamValue('tensorArrayId', node, tensorMap, context);
+ scatterIndices = getParamValue('indices', node, tensorMap, context);
+ scatterTensor = getParamValue('tensor', node, tensorMap, context);
+ scatterTensorArray = context.getTensorArray(scatterId.id);
+ scatterTensorArray.scatter(scatterIndices, scatterTensor);
+ return [2 /*return*/, [scatterTensorArray.idTensor]];
+ }
+ case 21:
+ {
+ concatId = getParamValue('tensorArrayId', node, tensorMap, context);
+ concatTensorArray = context.getTensorArray(concatId.id);
+ concatDtype = getParamValue('dtype', node, tensorMap, context);
+ return [2 /*return*/, [concatTensorArray.concat(concatDtype)]];
+ }
+ case 22:
+ {
+ splitId = getParamValue('tensorArrayId', node, tensorMap, context);
+ splitTensor = getParamValue('tensor', node, tensorMap, context);
+ lengths = getParamValue('lengths', node, tensorMap, context);
+ splitTensorArray = context.getTensorArray(splitId.id);
+ splitTensorArray.split(lengths, splitTensor);
+ return [2 /*return*/, [splitTensorArray.idTensor]];
+ }
+ case 23:
+ {
+ sizeId = getParamValue('tensorArrayId', node, tensorMap, context);
+ sizeTensorArray = context.getTensorArray(sizeId.id);
+ return [2 /*return*/, [tfc.scalar(sizeTensorArray.size(), 'int32')]];
+ }
+ case 24:
+ {
+ closeId = getParamValue('tensorArrayId', node, tensorMap, context);
+ closeTensorArray = context.getTensorArray(closeId.id);
+ closeTensorArray.clearAndClose();
+ return [2 /*return*/, [closeTensorArray.idTensor]];
+ }
+ case 25:
+ {
+ idTensor = getParamValue('tensorListId', node, tensorMap, context);
+ index = getParamValue('index', node, tensorMap, context);
+ writeTensor = getParamValue('tensor', node, tensorMap, context);
+ tensorList = context.getTensorList(idTensor.id);
+ tensorList.setItem(index, writeTensor);
+ return [2 /*return*/, [tensorList.idTensor]];
+ }
+ case 26:
+ {
+ idTensor = getParamValue('tensorListId', node, tensorMap, context);
+ readIndex = getParamValue('index', node, tensorMap, context);
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ elementDType = getParamValue('elementDType', node, tensorMap, context);
+ tensorList = context.getTensorList(idTensor.id);
+ return [2 /*return*/, [tensorList.getItem(readIndex, elementShape, elementDType)]];
+ }
+ case 27:
+ {
+ scatterIndices = getParamValue('indices', node, tensorMap, context);
+ scatterTensor = getParamValue('tensor', node, tensorMap, context);
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ numElements = getParamValue('numElements', node, tensorMap, context);
+ tensorList = scatter(scatterTensor, scatterIndices, elementShape, numElements);
+ context.addTensorList(tensorList);
+ return [2 /*return*/, [tensorList.idTensor]];
+ }
+ case 28:
+ {
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ elementDtype = getParamValue('elementDType', node, tensorMap, context);
+ numElementsParam = void 0;
+ if (node.op === 'TensorListReserve') {
+ numElementsParam = 'numElements';
+ }
+ else {
+ numElementsParam = 'maxNumElements';
+ }
+ numElements = getParamValue(numElementsParam, node, tensorMap, context);
+ tensorList = reserve(elementShape, elementDtype, numElements);
+ context.addTensorList(tensorList);
+ return [2 /*return*/, [tensorList.idTensor]];
+ }
+ case 29:
+ {
+ gatherId = getParamValue('tensorListId', node, tensorMap, context);
+ gatherIndices = getParamValue('indices', node, tensorMap, context);
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ elementDtype = getParamValue('elementDType', node, tensorMap, context);
+ tensorList = context.getTensorList(gatherId.id);
+ return [2 /*return*/, [tensorList.gather(gatherIndices, elementDtype, elementShape)]];
+ }
+ case 30:
+ {
+ idTensor = getParamValue('tensorListId', node, tensorMap, context);
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ elementDtype = getParamValue('elementDType', node, tensorMap, context);
+ numElements = getParamValue('numElements', node, tensorMap, context);
+ tensorList = context.getTensorList(idTensor.id);
+ return [2 /*return*/, [tensorList.stack(elementShape, elementDtype, numElements)]];
+ }
+ case 31:
+ {
+ tensor = getParamValue('tensor', node, tensorMap, context);
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ elementDtype = getParamValue('elementDType', node, tensorMap, context);
+ tensorList = fromTensor(tensor, elementShape, elementDtype);
+ context.addTensorList(tensorList);
+ return [2 /*return*/, [tensorList.idTensor]];
+ }
+ case 32:
+ {
+ concatId = getParamValue('tensorListId', node, tensorMap, context);
+ tensorList = context.getTensorList(concatId.id);
+ concatDtype = getParamValue('dtype', node, tensorMap, context);
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ return [2 /*return*/, [tensorList.concat(concatDtype, elementShape)]];
+ }
+ case 33:
+ {
+ idTensor = getParamValue('tensorListId', node, tensorMap, context);
+ writeTensor = getParamValue('tensor', node, tensorMap, context);
+ tensorList = context.getTensorList(idTensor.id);
+ tensorList.pushBack(writeTensor);
+ return [2 /*return*/, [tensorList.idTensor]];
+ }
+ case 34:
+ {
+ idTensor = getParamValue('tensorListId', node, tensorMap, context);
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ elementDType = getParamValue('elementDType', node, tensorMap, context);
+ tensorList = context.getTensorList(idTensor.id);
+ return [2 /*return*/, [tensorList.popBack(elementShape, elementDType)]];
+ }
+ case 35:
+ {
+ splitTensor = getParamValue('tensor', node, tensorMap, context);
+ elementShape = getParamValue('elementShape', node, tensorMap, context);
+ lengths = getParamValue('lengths', node, tensorMap, context);
+ tensorList = split(splitTensor, lengths, elementShape);
+ context.addTensorList(tensorList);
+ return [2 /*return*/, [tensorList.idTensor]];
+ }
+ case 36: throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ });
+ }); };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function fusedConvAndDepthWiseParams(node, tensorMap, context) {
+ var _a = __read(getParamValue('fusedOps', node, tensorMap, context), 2), extraOp = _a[0], activationFunc = _a[1];
+ var isBiasAdd = extraOp === 'biasadd';
+ var noBiasAdd = !isBiasAdd;
+ var isPrelu = activationFunc === 'prelu';
+ var isBatchNorm = extraOp === 'fusedbatchnorm';
+ var numArgs = getParamValue('numArgs', node, tensorMap, context);
+ if (isBiasAdd) {
+ if (isPrelu && numArgs !== 2) {
+ throw new Error('FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu ' +
+ 'must have two extra arguments: bias and alpha.');
+ }
+ if (!isPrelu && isBiasAdd && numArgs !== 1) {
+ throw new Error('FusedConv2d and DepthwiseConv2d with BiasAdd must have ' +
+ 'one extra argument: bias.');
+ }
+ }
+ if (isBatchNorm) {
+ throw new Error('FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported');
+ }
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getPadding(node, tensorMap, context);
+ var dataFormat = getParamValue('dataFormat', node, tensorMap, context)
+ .toUpperCase();
+ var dilations = getParamValue('dilations', node, tensorMap, context);
+ var _b = __read(getParamValue('args', node, tensorMap, context), 2), biasArg = _b[0], preluArg = _b[1];
+ if (noBiasAdd) {
+ preluArg = biasArg;
+ biasArg = undefined;
+ }
+ var leakyreluAlpha = getParamValue('leakyreluAlpha', node, tensorMap, context);
+ return {
+ stride: stride,
+ pad: pad,
+ dataFormat: dataFormat,
+ dilations: dilations,
+ biasArg: biasArg,
+ preluArg: preluArg,
+ activationFunc: activationFunc,
+ leakyreluAlpha: leakyreluAlpha
+ };
+ }
+ var executeOp$3 = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'Conv1D': {
+ var stride = getParamValue('stride', node, tensorMap, context);
+ var pad = getParamValue('pad', node, tensorMap, context);
+ var dataFormat = getParamValue('dataFormat', node, tensorMap, context)
+ .toUpperCase();
+ var dilation = getParamValue('dilation', node, tensorMap, context);
+ return [tfOps.conv1d(getParamValue('x', node, tensorMap, context), getParamValue('filter', node, tensorMap, context), stride, pad, dataFormat, dilation)];
+ }
+ case 'Conv2D': {
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getPadding(node, tensorMap, context);
+ var dataFormat = getParamValue('dataFormat', node, tensorMap, context)
+ .toUpperCase();
+ var dilations = getParamValue('dilations', node, tensorMap, context);
+ return [tfOps.conv2d(getParamValue('x', node, tensorMap, context), getParamValue('filter', node, tensorMap, context), [stride[1], stride[2]], pad, dataFormat, [dilations[1], dilations[2]])];
+ }
+ case '_FusedConv2D': {
+ var _a = fusedConvAndDepthWiseParams(node, tensorMap, context), stride = _a.stride, pad = _a.pad, dataFormat = _a.dataFormat, dilations = _a.dilations, biasArg = _a.biasArg, preluArg = _a.preluArg, activationFunc = _a.activationFunc, leakyreluAlpha = _a.leakyreluAlpha;
+ return [tfOps.fused.conv2d({
+ x: getParamValue('x', node, tensorMap, context),
+ filter: getParamValue('filter', node, tensorMap, context),
+ strides: [stride[1], stride[2]],
+ pad: pad,
+ dataFormat: dataFormat,
+ dilations: [dilations[1], dilations[2]],
+ bias: biasArg,
+ activation: activationFunc,
+ preluActivationWeights: preluArg,
+ leakyreluAlpha: leakyreluAlpha
+ })];
+ }
+ case 'FusedDepthwiseConv2dNative': {
+ var _b = fusedConvAndDepthWiseParams(node, tensorMap, context), stride = _b.stride, pad = _b.pad, dataFormat = _b.dataFormat, dilations = _b.dilations, biasArg = _b.biasArg, preluArg = _b.preluArg, activationFunc = _b.activationFunc, leakyreluAlpha = _b.leakyreluAlpha;
+ return [tfOps.fused.depthwiseConv2d({
+ x: getParamValue('x', node, tensorMap, context),
+ filter: getParamValue('filter', node, tensorMap, context),
+ strides: [stride[1], stride[2]],
+ pad: pad,
+ dataFormat: dataFormat,
+ dilations: [dilations[1], dilations[2]],
+ bias: biasArg,
+ activation: activationFunc,
+ preluActivationWeights: preluArg,
+ leakyreluAlpha: leakyreluAlpha
+ })];
+ }
+ case 'Conv2DBackpropInput':
+ case 'Conv2dTranspose': {
+ var shape = getParamValue('outputShape', node, tensorMap, context);
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getPadding(node, tensorMap, context);
+ return [tfOps.conv2dTranspose(getParamValue('x', node, tensorMap, context), getParamValue('filter', node, tensorMap, context), shape, [stride[1], stride[2]], pad)];
+ }
+ case 'DepthwiseConv2dNative':
+ case 'DepthwiseConv2d': {
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getPadding(node, tensorMap, context);
+ var dilations = getParamValue('dilations', node, tensorMap, context);
+ var dataFormat = getParamValue('dataFormat', node, tensorMap, context)
+ .toUpperCase();
+ return [tfOps.depthwiseConv2d(getParamValue('input', node, tensorMap, context), getParamValue('filter', node, tensorMap, context), [stride[1], stride[2]], pad, dataFormat, [dilations[1], dilations[2]])];
+ }
+ case 'Conv3D': {
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getParamValue('pad', node, tensorMap, context);
+ var dataFormat = getParamValue('dataFormat', node, tensorMap, context)
+ .toUpperCase();
+ var dilations = getParamValue('dilations', node, tensorMap, context);
+ return [tfOps.conv3d(getParamValue('x', node, tensorMap, context), getParamValue('filter', node, tensorMap, context), [stride[1], stride[2], stride[3]], pad, dataFormat, [dilations[1], dilations[2], dilations[3]])];
+ }
+ case 'AvgPool': {
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getParamValue('pad', node, tensorMap, context);
+ var kernelSize = getParamValue('kernelSize', node, tensorMap, context);
+ return [tfOps.avgPool(getParamValue('x', node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad)];
+ }
+ case 'MaxPool': {
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getParamValue('pad', node, tensorMap, context);
+ var kernelSize = getParamValue('kernelSize', node, tensorMap, context);
+ return [tfOps.maxPool(getParamValue('x', node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad)];
+ }
+ case 'MaxPoolWithArgmax': {
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getParamValue('pad', node, tensorMap, context);
+ var kernelSize = getParamValue('kernelSize', node, tensorMap, context);
+ var includeBatchInIndex = getParamValue('includeBatchInIndex', node, tensorMap, context);
+ var _c = tfOps.maxPoolWithArgmax(getParamValue('x', node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad, includeBatchInIndex), result = _c.result, indexes = _c.indexes;
+ return [result, indexes];
+ }
+ case 'AvgPool3D': {
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getParamValue('pad', node, tensorMap, context);
+ var kernelSize = getParamValue('kernelSize', node, tensorMap, context);
+ return [tfOps.avgPool3d(getParamValue('x', node, tensorMap, context), [kernelSize[1], kernelSize[2], kernelSize[3]], [stride[1], stride[2], stride[3]], pad)];
+ }
+ case 'MaxPool3D': {
+ var stride = getParamValue('strides', node, tensorMap, context);
+ var pad = getParamValue('pad', node, tensorMap, context);
+ var kernelSize = getParamValue('kernelSize', node, tensorMap, context);
+ return [tfOps.maxPool3d(getParamValue('x', node, tensorMap, context), [kernelSize[1], kernelSize[2], kernelSize[3]], [stride[1], stride[2], stride[3]], pad)];
+ }
+ case 'Dilation2D': {
+ var strides = getParamValue('strides', node, tensorMap, context);
+ var pad = getParamValue('pad', node, tensorMap, context);
+ var dilations = getParamValue('dilations', node, tensorMap, context);
+ // strides: [1, stride_height, stride_width, 1].
+ var strideHeight = strides[1];
+ var strideWidth = strides[2];
+ // dilations: [1, dilation_height, dilation_width, 1].
+ var dilationHeight = dilations[1];
+ var dilationWidth = dilations[2];
+ return [tfOps.dilation2d(getParamValue('x', node, tensorMap, context), getParamValue('filter', node, tensorMap, context), [strideHeight, strideWidth], pad, [dilationHeight, dilationWidth], 'NHWC' /* dataFormat */)];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$4 = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'Fill': {
+ var shape = getParamValue('shape', node, tensorMap, context);
+ var dtype = getParamValue('dtype', node, tensorMap, context);
+ var value = getParamValue('value', node, tensorMap, context);
+ return [tfOps.fill(shape, value, dtype)];
+ }
+ case 'LinSpace': {
+ var start = getParamValue('start', node, tensorMap, context);
+ var stop_1 = getParamValue('stop', node, tensorMap, context);
+ var num = getParamValue('num', node, tensorMap, context);
+ return [tfOps.linspace(start, stop_1, num)];
+ }
+ case 'Multinomial': {
+ var logits = getParamValue('logits', node, tensorMap, context);
+ var numSamples = getParamValue('numSamples', node, tensorMap, context);
+ var seed = getParamValue('seed', node, tensorMap, context);
+ return [tfOps.multinomial(logits, numSamples, seed)];
+ }
+ case 'OneHot': {
+ var indices = getParamValue('indices', node, tensorMap, context);
+ var depth = getParamValue('depth', node, tensorMap, context);
+ var onValue = getParamValue('onValue', node, tensorMap, context);
+ var offValue = getParamValue('offValue', node, tensorMap, context);
+ return [tfOps.oneHot(indices, depth, onValue, offValue)];
+ }
+ case 'Ones': {
+ return [tfOps.ones(getParamValue('shape', node, tensorMap, context), getParamValue('dtype', node, tensorMap, context))];
+ }
+ case 'OnesLike': {
+ return [tfOps.onesLike(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'RandomUniform': {
+ return [tfOps.randomUniform(
+ // tslint:disable-next-line:no-any
+ getParamValue('shape', node, tensorMap, context), getParamValue('minval', node, tensorMap, context), getParamValue('maxval', node, tensorMap, context), getParamValue('dtype', node, tensorMap, context))];
+ }
+ case 'Range': {
+ var start = getParamValue('start', node, tensorMap, context);
+ var stop_2 = getParamValue('stop', node, tensorMap, context);
+ var step = getParamValue('step', node, tensorMap, context);
+ return [tfOps.range(start, stop_2, step, getParamValue('dtype', node, tensorMap, context))];
+ }
+ case 'TruncatedNormal': {
+ var shape = getParamValue('shape', node, tensorMap, context);
+ var mean = getParamValue('mean', node, tensorMap, context);
+ var stdDev = getParamValue('stdDev', node, tensorMap, context);
+ var seed = getParamValue('seed', node, tensorMap, context);
+ return [tfOps.truncatedNormal(shape, mean, stdDev, getParamValue('dtype', node, tensorMap, context), seed)];
+ }
+ case 'Zeros': {
+ return [tfOps.zeros(getParamValue('shape', node, tensorMap, context), getParamValue('dtype', node, tensorMap, context))];
+ }
+ case 'ZerosLike': {
+ return [tfOps.zerosLike(getParamValue('x', node, tensorMap, context))];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var _this$1 = undefined;
+ function nmsParams(node, tensorMap, context) {
+ var boxes = getParamValue('boxes', node, tensorMap, context);
+ var scores = getParamValue('scores', node, tensorMap, context);
+ var maxOutputSize = getParamValue('maxOutputSize', node, tensorMap, context);
+ var iouThreshold = getParamValue('iouThreshold', node, tensorMap, context);
+ var scoreThreshold = getParamValue('scoreThreshold', node, tensorMap, context);
+ var softNmsSigma = getParamValue('softNmsSigma', node, tensorMap, context);
+ return {
+ boxes: boxes,
+ scores: scores,
+ maxOutputSize: maxOutputSize,
+ iouThreshold: iouThreshold,
+ scoreThreshold: scoreThreshold,
+ softNmsSigma: softNmsSigma
+ };
+ }
+ var executeOp$5 = function (node, tensorMap, context) { return __awaiter(_this$1, void 0, void 0, function () {
+ var _a, _b, boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, result, _c, boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize, result, _d, boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, condition, result;
+ return __generator(this, function (_e) {
+ switch (_e.label) {
+ case 0:
+ _a = node.op;
+ switch (_a) {
+ case 'NonMaxSuppressionV5': return [3 /*break*/, 1];
+ case 'NonMaxSuppressionV4': return [3 /*break*/, 3];
+ case 'NonMaxSuppressionV3': return [3 /*break*/, 5];
+ case 'NonMaxSuppressionV2': return [3 /*break*/, 5];
+ case 'Where': return [3 /*break*/, 7];
+ case 'ListDiff': return [3 /*break*/, 9];
+ }
+ return [3 /*break*/, 10];
+ case 1:
+ _b = nmsParams(node, tensorMap, context), boxes = _b.boxes, scores = _b.scores, maxOutputSize = _b.maxOutputSize, iouThreshold = _b.iouThreshold, scoreThreshold = _b.scoreThreshold, softNmsSigma = _b.softNmsSigma;
+ return [4 /*yield*/, tfOps.image.nonMaxSuppressionWithScoreAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma)];
+ case 2:
+ result = _e.sent();
+ return [2 /*return*/, [result.selectedIndices, result.selectedScores]];
+ case 3:
+ _c = nmsParams(node, tensorMap, context), boxes = _c.boxes, scores = _c.scores, maxOutputSize = _c.maxOutputSize, iouThreshold = _c.iouThreshold, scoreThreshold = _c.scoreThreshold;
+ padToMaxOutputSize = getParamValue('padToMaxOutputSize', node, tensorMap, context);
+ return [4 /*yield*/, tfOps.image.nonMaxSuppressionPaddedAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize)];
+ case 4:
+ result = _e.sent();
+ return [2 /*return*/, [result.selectedIndices, result.validOutputs]];
+ case 5:
+ _d = nmsParams(node, tensorMap, context), boxes = _d.boxes, scores = _d.scores, maxOutputSize = _d.maxOutputSize, iouThreshold = _d.iouThreshold, scoreThreshold = _d.scoreThreshold;
+ return [4 /*yield*/, tfOps.image.nonMaxSuppressionAsync(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold)];
+ case 6: return [2 /*return*/, [_e.sent()]];
+ case 7:
+ condition = tfOps.cast(getParamValue('condition', node, tensorMap, context), 'bool');
+ return [4 /*yield*/, tfOps.whereAsync(condition)];
+ case 8:
+ result = [_e.sent()];
+ condition.dispose();
+ return [2 /*return*/, result];
+ case 9:
+ {
+ return [2 /*return*/, tfOps.setdiff1dAsync(getParamValue('x', node, tensorMap, context), getParamValue('y', node, tensorMap, context))];
+ }
+ case 10: throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ });
+ }); };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$6 = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'TopKV2': {
+ var x = getParamValue('x', node, tensorMap, context);
+ var k = getParamValue('k', node, tensorMap, context);
+ var sorted = getParamValue('sorted', node, tensorMap, context);
+ var result = tfOps.topk(x, k, sorted);
+ return [result.values, result.indices];
+ }
+ case 'Unique': {
+ var x = getParamValue('x', node, tensorMap, context);
+ var result = tfOps.unique(x);
+ return [result.values, result.indices];
+ }
+ case 'UniqueV2': {
+ var x = getParamValue('x', node, tensorMap, context);
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var result = tfOps.unique(x, axis);
+ return [result.values, result.indices];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$7 = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'Const': {
+ return tensorMap[node.name];
+ }
+ case 'PlaceholderWithDefault':
+ var def = getParamValue('default', node, tensorMap, context);
+ return [getTensor(node.name, tensorMap, context) || def];
+ case 'Placeholder':
+ return [getTensor(node.name, tensorMap, context)];
+ case 'Identity':
+ case 'StopGradient':
+ case 'FakeQuantWithMinMaxVars': { // This op is currently ignored.
+ var data_1 = getParamValue('x', node, tensorMap, context);
+ return [cloneTensor(data_1)];
+ }
+ case 'IdentityN':
+ return getParamValue('x', node, tensorMap, context)
+ .map(function (t) { return cloneTensor(t); });
+ case 'Snapshot':
+ var snapshot = getParamValue('x', node, tensorMap, context);
+ return [cloneTensor(snapshot)];
+ case 'Shape':
+ return [tfOps.tensor1d(getParamValue('x', node, tensorMap, context).shape, 'int32')];
+ case 'ShapeN':
+ return getParamValue('x', node, tensorMap, context)
+ .map(function (t) { return tfOps.tensor1d(t.shape); });
+ case 'Size':
+ return [tfOps.scalar(getParamValue('x', node, tensorMap, context).size, 'int32')];
+ case 'Rank':
+ return [tfOps.scalar(getParamValue('x', node, tensorMap, context).rank, 'int32')];
+ case 'NoOp':
+ return [tfOps.scalar(1)];
+ case 'Print':
+ var input = getParamValue('x', node, tensorMap, context);
+ var data = getParamValue('data', node, tensorMap, context);
+ var message = getParamValue('message', node, tensorMap, context);
+ var summarize = getParamValue('summarize', node, tensorMap, context);
+ console.warn('The graph has a tf.print() operation,' +
+ 'usually used for debugging, which slows down performance.');
+ console.log(message);
+ for (var i = 0; i < data.length; i++) {
+ console.log(Array.prototype.slice.call(data[i].dataSync())
+ .slice(0, summarize));
+ }
+ return [input];
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * Hashtable contains a set of tensors, which can be accessed by key.
+ */
+ var HashTable = /** @class */ (function () {
+ /**
+ * Constructor of HashTable. Creates a hash table.
+ *
+ * @param keyDType `dtype` of the table keys.
+ * @param valueDType `dtype` of the table values.
+ */
+ function HashTable(keyDType, valueDType) {
+ this.keyDType = keyDType;
+ this.valueDType = valueDType;
+ this.handle = tfc.scalar(0);
+ // tslint:disable-next-line: no-any
+ this.tensorMap = new Map();
+ tfc.keep(this.handle);
+ }
+ Object.defineProperty(HashTable.prototype, "id", {
+ get: function () {
+ return this.handle.id;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ /**
+ * Dispose the tensors and handle and clear the hashtable.
+ */
+ HashTable.prototype.clearAndClose = function () {
+ this.tensorMap.forEach(function (value) { return value.dispose(); });
+ this.tensorMap.clear();
+ this.handle.dispose();
+ };
+ /**
+ * The number of items in the hash table.
+ */
+ HashTable.prototype.size = function () {
+ return this.tensorMap.size;
+ };
+ /**
+ * The number of items in the hash table as a rank-0 tensor.
+ */
+ HashTable.prototype.tensorSize = function () {
+ return tfOps.scalar(this.size(), 'int32');
+ };
+ /**
+ * Replaces the contents of the table with the specified keys and values.
+ * @param keys Keys to store in the hashtable.
+ * @param values Values to store in the hashtable.
+ */
+ HashTable.prototype.import = function (keys, values) {
+ return __awaiter(this, void 0, void 0, function () {
+ var $keys;
+ var _this = this;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ this.checkKeyAndValueTensor(keys, values);
+ return [4 /*yield*/, keys.data()];
+ case 1:
+ $keys = _a.sent();
+ // Clear the hashTable before inserting new values.
+ this.tensorMap.forEach(function (value) { return value.dispose(); });
+ this.tensorMap.clear();
+ return [2 /*return*/, tfc.tidy(function () {
+ var $values = tfc.unstack(values);
+ var keysLength = $keys.length;
+ var valuesLength = $values.length;
+ tfc.util.assert(keysLength === valuesLength, function () { return "The number of elements doesn't match, keys has " +
+ (keysLength + " elements, the values has " + valuesLength + " ") +
+ "elements."; });
+ for (var i = 0; i < keysLength; i++) {
+ var key = $keys[i];
+ var value = $values[i];
+ tfc.keep(value);
+ _this.tensorMap.set(key, value);
+ }
+ return _this.handle;
+ })];
+ }
+ });
+ });
+ };
+ /**
+ * Looks up keys in a hash table, outputs the corresponding values.
+ *
+ * Performs batch lookups, for every element in the key tensor, `find`
+ * stacks the corresponding value into the return tensor.
+ *
+ * If an element is not present in the table, the given `defaultValue` is
+ * used.
+ *
+ * @param keys Keys to look up. Must have the same type as the keys of the
+ * table.
+ * @param defaultValue The scalar `defaultValue` is the value output for keys
+ * not present in the table. It must also be of the same type as the
+ * table values.
+ */
+ HashTable.prototype.find = function (keys, defaultValue) {
+ return __awaiter(this, void 0, void 0, function () {
+ var $keys;
+ var _this = this;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ this.checkKeyAndValueTensor(keys, defaultValue);
+ return [4 /*yield*/, keys.data()];
+ case 1:
+ $keys = _a.sent();
+ return [2 /*return*/, tfc.tidy(function () {
+ var result = [];
+ for (var i = 0; i < $keys.length; i++) {
+ var key = $keys[i];
+ var value = _this.findWithDefault(key, defaultValue);
+ result.push(value);
+ }
+ return tfc.stack(result);
+ })];
+ }
+ });
+ });
+ };
+ // tslint:disable-next-line: no-any
+ HashTable.prototype.findWithDefault = function (key, defaultValue) {
+ var result = this.tensorMap.get(key);
+ return result != null ? result : defaultValue;
+ };
+ HashTable.prototype.checkKeyAndValueTensor = function (key, value) {
+ if (key.dtype !== this.keyDType) {
+ throw new Error("Expect key dtype " + this.keyDType + ", but got " +
+ ("" + key.dtype));
+ }
+ if (value.dtype !== this.valueDType) {
+ throw new Error("Expect value dtype " + this.valueDType + ", but got " +
+ ("" + value.dtype));
+ }
+ };
+ return HashTable;
+ }());
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var _this$2 = undefined;
+ var executeOp$8 = function (node, tensorMap, context, resourceManager) { return __awaiter(_this$2, void 0, void 0, function () {
+ var _a, keyDType, valueDType, hashTable, handle, keys, values, hashTable, handle, keys, defaultValue, hashTable, handle, hashTable;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ _a = node.op;
+ switch (_a) {
+ case 'HashTable': return [3 /*break*/, 1];
+ case 'HashTableV2': return [3 /*break*/, 1];
+ case 'LookupTableImport': return [3 /*break*/, 2];
+ case 'LookupTableImportV2': return [3 /*break*/, 2];
+ case 'LookupTableFind': return [3 /*break*/, 4];
+ case 'LookupTableFindV2': return [3 /*break*/, 4];
+ case 'LookupTableSize': return [3 /*break*/, 6];
+ case 'LookupTableSizeV2': return [3 /*break*/, 6];
+ }
+ return [3 /*break*/, 7];
+ case 1:
+ {
+ keyDType = getParamValue('keyDType', node, tensorMap, context);
+ valueDType = getParamValue('valueDType', node, tensorMap, context);
+ hashTable = new HashTable(keyDType, valueDType);
+ resourceManager.addHashTable(node.name, hashTable);
+ return [2 /*return*/, [hashTable.handle]];
+ }
+ case 2:
+ handle = getParamValue('tableHandle', node, tensorMap, context, resourceManager);
+ keys = getParamValue('keys', node, tensorMap, context);
+ values = getParamValue('values', node, tensorMap, context);
+ hashTable = resourceManager.getHashTableById(handle.id);
+ return [4 /*yield*/, hashTable.import(keys, values)];
+ case 3: return [2 /*return*/, [_b.sent()]];
+ case 4:
+ handle = getParamValue('tableHandle', node, tensorMap, context, resourceManager);
+ keys = getParamValue('keys', node, tensorMap, context);
+ defaultValue = getParamValue('defaultValue', node, tensorMap, context);
+ hashTable = resourceManager.getHashTableById(handle.id);
+ return [4 /*yield*/, hashTable.find(keys, defaultValue)];
+ case 5: return [2 /*return*/, [_b.sent()]];
+ case 6:
+ {
+ handle = getParamValue('tableHandle', node, tensorMap, context, resourceManager);
+ hashTable = resourceManager.getHashTableById(handle.id);
+ return [2 /*return*/, [hashTable.tensorSize()]];
+ }
+ case 7: throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ });
+ }); };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$9 = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'ResizeBilinear': {
+ var images = getParamValue('images', node, tensorMap, context);
+ var size = getParamValue('size', node, tensorMap, context);
+ var alignCorners = getParamValue('alignCorners', node, tensorMap, context);
+ var halfPixelCenters = getParamValue('halfPixelCenters', node, tensorMap, context);
+ return [tfOps.image.resizeBilinear(images, [size[0], size[1]], alignCorners, halfPixelCenters)];
+ }
+ case 'ResizeNearestNeighbor': {
+ var images = getParamValue('images', node, tensorMap, context);
+ var size = getParamValue('size', node, tensorMap, context);
+ var alignCorners = getParamValue('alignCorners', node, tensorMap, context);
+ var halfPixelCenters = getParamValue('halfPixelCenters', node, tensorMap, context);
+ return [tfOps.image.resizeNearestNeighbor(images, [size[0], size[1]], alignCorners, halfPixelCenters)];
+ }
+ case 'CropAndResize': {
+ var image = getParamValue('image', node, tensorMap, context);
+ var boxes = getParamValue('boxes', node, tensorMap, context);
+ var boxInd = getParamValue('boxInd', node, tensorMap, context);
+ var cropSize = getParamValue('cropSize', node, tensorMap, context);
+ var method = getParamValue('method', node, tensorMap, context);
+ var extrapolationValue = getParamValue('extrapolationValue', node, tensorMap, context);
+ return [tfOps.image.cropAndResize(image, boxes, boxInd, cropSize, method, extrapolationValue)];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$a = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'Equal': {
+ return [tfOps.equal(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'NotEqual': {
+ return [tfOps.notEqual(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'Greater': {
+ return [tfOps.greater(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'GreaterEqual': {
+ return [tfOps.greaterEqual(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'Less': {
+ return [tfOps.less(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'LessEqual': {
+ return [tfOps.lessEqual(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'LogicalAnd': {
+ return [tfOps.logicalAnd(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'LogicalNot': {
+ return [tfOps.logicalNot(getParamValue('a', node, tensorMap, context))];
+ }
+ case 'LogicalOr': {
+ return [tfOps.logicalOr(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ case 'Select':
+ case 'SelectV2': {
+ return [tfOps.where(getParamValue('condition', node, tensorMap, context), getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context))];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$b = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'BatchMatMul':
+ case 'BatchMatMulV2':
+ case 'MatMul':
+ return [tfOps.matMul(getParamValue('a', node, tensorMap, context), getParamValue('b', node, tensorMap, context), getParamValue('transposeA', node, tensorMap, context), getParamValue('transposeB', node, tensorMap, context))];
+ case 'Einsum':
+ return [tfOps.einsum.apply(tfOps, __spread([getParamValue('equation', node, tensorMap, context)], getParamValue('tensors', node, tensorMap, context)))];
+ case 'Transpose':
+ return [tfOps.transpose(getParamValue('x', node, tensorMap, context), getParamValue('perm', node, tensorMap, context))];
+ case '_FusedMatMul':
+ var _a = __read(getParamValue('fusedOps', node, tensorMap, context), 2), extraOp = _a[0], activationFunc = _a[1];
+ var isBiasAdd = extraOp === 'biasadd';
+ var isPrelu = activationFunc === 'prelu';
+ var numArgs = getParamValue('numArgs', node, tensorMap, context);
+ var leakyreluAlpha = getParamValue('leakyreluAlpha', node, tensorMap, context);
+ if (isBiasAdd) {
+ if (isPrelu && numArgs !== 2) {
+ throw new Error('Fused MatMul with BiasAdd and Prelu must have two ' +
+ 'extra arguments: bias and alpha.');
+ }
+ if (!isPrelu && numArgs !== 1) {
+ throw new Error('Fused MatMul with BiasAdd must have one extra argument: bias.');
+ }
+ }
+ var _b = __read(getParamValue('args', node, tensorMap, context), 2), biasArg = _b[0], preluArg = _b[1];
+ return [tfOps.fused.matMul({
+ a: getParamValue('a', node, tensorMap, context),
+ b: getParamValue('b', node, tensorMap, context),
+ transposeA: getParamValue('transposeA', node, tensorMap, context),
+ transposeB: getParamValue('transposeB', node, tensorMap, context),
+ bias: biasArg,
+ activation: activationFunc,
+ preluActivationWeights: preluArg,
+ leakyreluAlpha: leakyreluAlpha
+ })];
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$c = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'FusedBatchNorm':
+ case 'FusedBatchNormV2': {
+ return [tfOps.batchNorm(getParamValue('x', node, tensorMap, context), getParamValue('mean', node, tensorMap, context), getParamValue('variance', node, tensorMap, context), getParamValue('offset', node, tensorMap, context), getParamValue('scale', node, tensorMap, context), getParamValue('epsilon', node, tensorMap, context))];
+ }
+ case 'FusedBatchNormV3': {
+ return [tfOps.batchNorm(getParamValue('x', node, tensorMap, context), getParamValue('mean', node, tensorMap, context), getParamValue('variance', node, tensorMap, context), getParamValue('offset', node, tensorMap, context), getParamValue('scale', node, tensorMap, context), getParamValue('epsilon', node, tensorMap, context))];
+ }
+ case 'LRN': {
+ return [tfOps.localResponseNormalization(getParamValue('x', node, tensorMap, context), getParamValue('radius', node, tensorMap, context), getParamValue('bias', node, tensorMap, context), getParamValue('alpha', node, tensorMap, context), getParamValue('beta', node, tensorMap, context))];
+ }
+ case 'Softmax': {
+ return [tfOps.softmax(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'LogSoftmax': {
+ return [tfOps.logSoftmax(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'SparseToDense': {
+ return [tfOps.sparseToDense(getParamValue('sparseIndices', node, tensorMap, context), getParamValue('outputShape', node, tensorMap, context), getParamValue('sparseValues', node, tensorMap, context), getParamValue('defaultValue', node, tensorMap, context))];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$d = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'Max': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var keepDims = getParamValue('keepDims', node, tensorMap, context);
+ return [tfOps.max(getParamValue('x', node, tensorMap, context), axis, keepDims)];
+ }
+ case 'Mean': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var keepDims = getParamValue('keepDims', node, tensorMap, context);
+ return [tfOps.mean(getParamValue('x', node, tensorMap, context), axis, keepDims)];
+ }
+ case 'Min': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var keepDims = getParamValue('keepDims', node, tensorMap, context);
+ return [tfOps.min(getParamValue('x', node, tensorMap, context), axis, keepDims)];
+ }
+ case 'Sum': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var keepDims = getParamValue('keepDims', node, tensorMap, context);
+ return [tfOps.sum(getParamValue('x', node, tensorMap, context), axis, keepDims)];
+ }
+ case 'All': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var keepDims = getParamValue('keepDims', node, tensorMap, context);
+ return [tfOps.all(getParamValue('x', node, tensorMap, context), axis, keepDims)];
+ }
+ case 'Any': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var keepDims = getParamValue('keepDims', node, tensorMap, context);
+ return [tfOps.any(getParamValue('x', node, tensorMap, context), axis, keepDims)];
+ }
+ case 'ArgMax': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ return [tfOps.argMax(getParamValue('x', node, tensorMap, context), axis)];
+ }
+ case 'ArgMin': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ return [tfOps.argMin(getParamValue('x', node, tensorMap, context), axis)];
+ }
+ case 'Prod': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var keepDims = getParamValue('keepDims', node, tensorMap, context);
+ return [tfOps.prod(getParamValue('x', node, tensorMap, context), axis, keepDims)];
+ }
+ case 'Cumsum': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var exclusive = getParamValue('exclusive', node, tensorMap, context);
+ var reverse = getParamValue('reverse', node, tensorMap, context);
+ return [tfOps.cumsum(getParamValue('x', node, tensorMap, context), axis, exclusive, reverse)];
+ }
+ case 'Bincount':
+ var x = getParamValue('x', node, tensorMap, context);
+ var weights = getParamValue('weights', node, tensorMap, context);
+ var size = getParamValue('size', node, tensorMap, context);
+ return [tfOps.bincount(x, weights, size)];
+ case 'DenseBincount': {
+ var x_1 = getParamValue('x', node, tensorMap, context);
+ var weights_1 = getParamValue('weights', node, tensorMap, context);
+ var size_1 = getParamValue('size', node, tensorMap, context);
+ var binaryOutput = getParamValue('binaryOutput', node, tensorMap, context);
+ return [tfOps.denseBincount(x_1, weights_1, size_1, binaryOutput)];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$e = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'ConcatV2':
+ case 'Concat': {
+ var n = getParamValue('n', node, tensorMap, context);
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var inputs = getParamValue('tensors', node, tensorMap, context);
+ inputs = inputs.slice(0, n);
+ return [tfOps.concat(inputs, axis)];
+ }
+ case 'Gather': {
+ var input = getParamValue('x', node, tensorMap, context);
+ var indices = getParamValue('indices', node, tensorMap, context);
+ return [tfOps.gather(input, tfOps.cast(indices, 'int32'), 0)];
+ }
+ case 'GatherV2': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var batchDims = getParamValue('batchDims', node, tensorMap, context);
+ var input = getParamValue('x', node, tensorMap, context);
+ var indices = getParamValue('indices', node, tensorMap, context);
+ return [tfOps.gather(input, tfOps.cast(indices, 'int32'), axis, batchDims)];
+ }
+ case 'Reverse': {
+ var dims = getParamValue('dims', node, tensorMap, context);
+ var axis = [];
+ for (var i = 0; i < dims.length; i++) {
+ if (dims[i]) {
+ axis.push(i);
+ }
+ }
+ var input = getParamValue('x', node, tensorMap, context);
+ return [tfOps.reverse(input, axis)];
+ }
+ case 'ReverseV2': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var input = getParamValue('x', node, tensorMap, context);
+ return [tfOps.reverse(input, axis)];
+ }
+ case 'Slice': {
+ // tslint:disable-next-line:no-any
+ var begin = getParamValue('begin', node, tensorMap, context);
+ // tslint:disable-next-line:no-any
+ var size = getParamValue('size', node, tensorMap, context);
+ return [tfOps.slice(getParamValue('x', node, tensorMap, context), begin, size)];
+ }
+ case 'StridedSlice': {
+ var begin = getParamValue('begin', node, tensorMap, context);
+ var end = getParamValue('end', node, tensorMap, context);
+ var strides = getParamValue('strides', node, tensorMap, context);
+ var beginMask = getParamValue('beginMask', node, tensorMap, context);
+ var endMask = getParamValue('endMask', node, tensorMap, context);
+ var ellipsisMask = getParamValue('ellipsisMask', node, tensorMap, context);
+ var newAxisMask = getParamValue('newAxisMask', node, tensorMap, context);
+ var shrinkAxisMask = getParamValue('shrinkAxisMask', node, tensorMap, context);
+ var tensor = getParamValue('x', node, tensorMap, context);
+ return [tfOps.stridedSlice(tensor, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask)];
+ }
+ case 'Pack': {
+ return tfc.tidy(function () {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var tensors = getParamValue('tensors', node, tensorMap, context);
+ // Reshape the tensors to the first tensor's shape if they don't
+ // match.
+ var shape = tensors[0].shape;
+ var squeezedShape = tfOps.squeeze(tensors[0]).shape;
+ var mapped = tensors.map(function (tensor) {
+ var sameShape = tfc.util.arraysEqual(tensor.shape, shape);
+ if (!sameShape &&
+ !tfc.util.arraysEqual(tfOps.squeeze(tensor).shape, squeezedShape)) {
+ throw new Error('the input tensors shape does not match');
+ }
+ return sameShape ? tensor : tfOps.reshape(tensor, shape);
+ });
+ return [tfOps.stack(mapped, axis)];
+ });
+ }
+ case 'Unpack': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var tensor = getParamValue('tensor', node, tensorMap, context);
+ return tfOps.unstack(tensor, axis);
+ }
+ case 'Tile': {
+ var reps = getParamValue('reps', node, tensorMap, context);
+ return [tfOps.tile(getParamValue('x', node, tensorMap, context), reps)];
+ }
+ case 'Split':
+ case 'SplitV': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ var numOrSizeSplits = getParamValue('numOrSizeSplits', node, tensorMap, context);
+ var tensor = getParamValue('x', node, tensorMap, context);
+ return tfOps.split(tensor, numOrSizeSplits, axis);
+ }
+ case 'ScatterNd': {
+ var indices = getParamValue('indices', node, tensorMap, context);
+ var values = getParamValue('values', node, tensorMap, context);
+ var shape = getParamValue('shape', node, tensorMap, context);
+ return [tfOps.scatterND(indices, values, shape)];
+ }
+ case 'GatherNd': {
+ var x = getParamValue('x', node, tensorMap, context);
+ var indices = getParamValue('indices', node, tensorMap, context);
+ return [tfOps.gatherND(x, indices)];
+ }
+ case 'SparseToDense': {
+ var indices = getParamValue('sparseIndices', node, tensorMap, context);
+ var shape = getParamValue('outputShape', node, tensorMap, context);
+ var sparseValues = getParamValue('sparseValues', node, tensorMap, context);
+ var defaultValue = getParamValue('defaultValue', node, tensorMap, context);
+ return [tfOps.sparseToDense(indices, sparseValues, shape, sparseValues.dtype === defaultValue.dtype ?
+ defaultValue :
+ tfOps.cast(defaultValue, sparseValues.dtype))];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$f = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'SparseFillEmptyRows': {
+ var _a = tfOps.sparse.sparseFillEmptyRows(getParamValue('indices', node, tensorMap, context), getParamValue('values', node, tensorMap, context), getParamValue('denseShape', node, tensorMap, context), getParamValue('defaultValue', node, tensorMap, context)), outputIndices = _a.outputIndices, outputValues = _a.outputValues, emptyRowIndicator = _a.emptyRowIndicator, reverseIndexMap = _a.reverseIndexMap;
+ return [
+ outputIndices, outputValues, emptyRowIndicator, reverseIndexMap
+ ];
+ }
+ case 'SparseReshape': {
+ var _b = tfOps.sparse.sparseReshape(getParamValue('inputIndices', node, tensorMap, context), getParamValue('inputShape', node, tensorMap, context), getParamValue('newShape', node, tensorMap, context)), outputIndices = _b.outputIndices, outputShape = _b.outputShape;
+ return [outputIndices, outputShape];
+ }
+ case 'SparseSegmentMean': {
+ var outputData = tfOps.sparse.sparseSegmentMean(getParamValue('data', node, tensorMap, context), getParamValue('indices', node, tensorMap, context), getParamValue('segmentIds', node, tensorMap, context));
+ return [outputData];
+ }
+ case 'SparseSegmentSum': {
+ var outputData = tfOps.sparse.sparseSegmentSum(getParamValue('data', node, tensorMap, context), getParamValue('indices', node, tensorMap, context), getParamValue('segmentIds', node, tensorMap, context));
+ return [outputData];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$g = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'FFT': {
+ return [tfOps.fft(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'IFFT': {
+ return [tfOps.ifft(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'RFFT': {
+ return [tfOps.rfft(getParamValue('x', node, tensorMap, context))];
+ }
+ case 'IRFFT': {
+ return [tfOps.irfft(getParamValue('x', node, tensorMap, context))];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$h = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'StringNGrams': {
+ var _a = tfOps.string.stringNGrams(getParamValue('data', node, tensorMap, context), getParamValue('dataSplits', node, tensorMap, context), getParamValue('separator', node, tensorMap, context), getParamValue('nGramWidths', node, tensorMap, context), getParamValue('leftPad', node, tensorMap, context), getParamValue('rightPad', node, tensorMap, context), getParamValue('padWidth', node, tensorMap, context), getParamValue('preserveShortSequences', node, tensorMap, context)), nGrams = _a.nGrams, nGramsSplits = _a.nGramsSplits;
+ return [nGrams, nGramsSplits];
+ }
+ case 'StringSplit': {
+ var _b = tfOps.string.stringSplit(getParamValue('input', node, tensorMap, context), getParamValue('delimiter', node, tensorMap, context), getParamValue('skipEmpty', node, tensorMap, context)), indices = _b.indices, values = _b.values, shape = _b.shape;
+ return [indices, values, shape];
+ }
+ case 'StringToHashBucketFast': {
+ var output = tfOps.string.stringToHashBucketFast(getParamValue('input', node, tensorMap, context), getParamValue('numBuckets', node, tensorMap, context));
+ return [output];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var executeOp$i = function (node, tensorMap, context) {
+ switch (node.op) {
+ case 'Cast': {
+ return [tfOps.cast(getParamValue('x', node, tensorMap, context), getParamValue('dtype', node, tensorMap, context))];
+ }
+ case 'ExpandDims': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ return [tfOps.expandDims(getParamValue('x', node, tensorMap, context), axis)];
+ }
+ case 'Squeeze': {
+ var axis = getParamValue('axis', node, tensorMap, context);
+ return [tfOps.squeeze(getParamValue('x', node, tensorMap, context), axis)];
+ }
+ case 'Reshape': {
+ return [tfOps.reshape(getParamValue('x', node, tensorMap, context), getParamValue('shape', node, tensorMap, context))];
+ }
+ case 'MirrorPad': {
+ return [tfOps.mirrorPad(getParamValue('x', node, tensorMap, context), getParamValue('padding', node, tensorMap, context), getParamValue('mode', node, tensorMap, context))];
+ }
+ case 'PadV2':
+ case 'Pad': {
+ return [tfOps.pad(getParamValue('x', node, tensorMap, context), getParamValue('padding', node, tensorMap, context), getParamValue('constantValue', node, tensorMap, context))];
+ }
+ case 'SpaceToBatchND': {
+ var blockShape = getParamValue('blockShape', node, tensorMap, context);
+ var paddings = getParamValue('paddings', node, tensorMap, context);
+ return [tfOps.spaceToBatchND(getParamValue('x', node, tensorMap, context), blockShape, paddings)];
+ }
+ case 'BatchToSpaceND': {
+ var blockShape = getParamValue('blockShape', node, tensorMap, context);
+ var crops = getParamValue('crops', node, tensorMap, context);
+ return [tfOps.batchToSpaceND(getParamValue('x', node, tensorMap, context), blockShape, crops)];
+ }
+ case 'DepthToSpace': {
+ var blockSize = getParamValue('blockSize', node, tensorMap, context);
+ var dataFormat = getParamValue('dataFormat', node, tensorMap, context).toUpperCase();
+ return [tfOps.depthToSpace(getParamValue('x', node, tensorMap, context), blockSize, dataFormat)];
+ }
+ case 'BroadcastTo': {
+ return [tfOps.broadcastTo(getParamValue('x', node, tensorMap, context), getParamValue('shape', node, tensorMap, context))];
+ }
+ default:
+ throw TypeError("Node type " + node.op + " is not implemented");
+ }
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Executes the op defined by the node object.
+ * @param node
+ * @param tensorMap contains tensors for executed nodes and weights
+ * @param context contains tensors and information for running the current node.
+ * @param resourceManager Optional. Contains global resources of the model.
+ */
+ function executeOp$j(node, tensorMap, context, resourceManager) {
+ var value = (function (node, tensorMap, context) {
+ switch (node.category) {
+ case 'arithmetic':
+ return tfc.tidy(function () { return executeOp(node, tensorMap, context); });
+ case 'basic_math':
+ return tfc.tidy(function () { return executeOp$1(node, tensorMap, context); });
+ case 'control':
+ return executeOp$2(node, tensorMap, context);
+ case 'convolution':
+ return tfc.tidy(function () { return executeOp$3(node, tensorMap, context); });
+ case 'creation':
+ return tfc.tidy(function () { return executeOp$4(node, tensorMap, context); });
+ case 'dynamic':
+ return executeOp$5(node, tensorMap, context);
+ case 'evaluation':
+ return tfc.tidy(function () { return executeOp$6(node, tensorMap, context); });
+ case 'image':
+ return tfc.tidy(function () { return executeOp$9(node, tensorMap, context); });
+ case 'graph':
+ return tfc.tidy(function () { return executeOp$7(node, tensorMap, context); });
+ case 'logical':
+ return tfc.tidy(function () { return executeOp$a(node, tensorMap, context); });
+ case 'matrices':
+ return tfc.tidy(function () { return executeOp$b(node, tensorMap, context); });
+ case 'normalization':
+ return tfc.tidy(function () { return executeOp$c(node, tensorMap, context); });
+ case 'reduction':
+ return tfc.tidy(function () { return executeOp$d(node, tensorMap, context); });
+ case 'slice_join':
+ return tfc.tidy(function () { return executeOp$e(node, tensorMap, context); });
+ case 'sparse':
+ return tfc.tidy(function () { return executeOp$f(node, tensorMap, context); });
+ case 'spectral':
+ return tfc.tidy(function () { return executeOp$g(node, tensorMap, context); });
+ case 'string':
+ return tfc.tidy(function () { return executeOp$h(node, tensorMap, context); });
+ case 'transformation':
+ return tfc.tidy(function () { return executeOp$i(node, tensorMap, context); });
+ case 'hash_table':
+ return executeOp$8(node, tensorMap, context, resourceManager);
+ case 'custom':
+ var opMapper = getRegisteredOp(node.op);
+ if (opMapper && opMapper.customExecutor) {
+ return opMapper.customExecutor(new NodeValueImpl(node, tensorMap, context));
+ }
+ else {
+ throw TypeError("Custom op " + node.op + " is not registered.");
+ }
+ default:
+ throw TypeError("Unknown op '" + node.op + "'. File an issue at " +
+ "https://github.com/tensorflow/tfjs/issues so we can add it" +
+ ", or register a custom execution with tf.registerOp()");
+ }
+ })(node, tensorMap, context);
+ if (tfc.util.isPromise(value)) {
+ return value.then(function (data) { return [].concat(data); });
+ }
+ return [].concat(value);
+ }
+
+ /**
+ * ExecutionContext captures the runtime environment of the node. It keeps
+ * track of the current frame and iteration for the control flow ops.
+ *
+ * For example, typical Dynamic RNN model may contain loops, for which
+ * TensorFlow will generate graphs with Enter/Exit nodes to control the
+ * current execution frame, and NextIteration Nodes for iteration id increment.
+ * For model with branch logic, TensorFLow will generate Switch/Merge ops.
+ */
+ var ExecutionContext = /** @class */ (function () {
+ function ExecutionContext(weightMap, tensorArrayMap, tensorListMap, functionMap) {
+ if (weightMap === void 0) { weightMap = {}; }
+ if (tensorArrayMap === void 0) { tensorArrayMap = {}; }
+ if (tensorListMap === void 0) { tensorListMap = {}; }
+ if (functionMap === void 0) { functionMap = {}; }
+ this.weightMap = weightMap;
+ this.tensorArrayMap = tensorArrayMap;
+ this.tensorListMap = tensorListMap;
+ this.functionMap = functionMap;
+ this.rootContext = { id: 0, frameName: '', iterationId: 0 };
+ this.contexts = [this.rootContext];
+ this.lastId = 0;
+ this.generateCurrentContextIds();
+ }
+ ExecutionContext.prototype.newFrame = function (id, frameName) {
+ return { id: id, frameName: frameName, iterationId: 0 };
+ };
+ Object.defineProperty(ExecutionContext.prototype, "currentContext", {
+ get: function () {
+ return this.contexts;
+ },
+ /**
+ * Set the current context
+ * @param contexts: ExecutionContextInfo[] the current path of execution
+ * frames
+ */
+ set: function (contexts) {
+ if (this.contexts !== contexts) {
+ this.contexts = contexts;
+ this.generateCurrentContextIds();
+ }
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(ExecutionContext.prototype, "currentContextId", {
+ /**
+ * Returns the current context in string format.
+ */
+ get: function () {
+ return this._currentContextIds[0];
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(ExecutionContext.prototype, "currentContextIds", {
+ /**
+ * Returns the current context and all parent contexts in string format.
+ * This allow access to the nodes in the current and parent frames.
+ */
+ get: function () {
+ return this._currentContextIds;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ ExecutionContext.prototype.generateCurrentContextIds = function () {
+ var names = [];
+ for (var i = 0; i < this.contexts.length - 1; i++) {
+ var contexts = this.contexts.slice(0, this.contexts.length - i);
+ names.push(this.contextIdforContexts(contexts));
+ }
+ names.push('');
+ this._currentContextIds = names;
+ };
+ ExecutionContext.prototype.contextIdforContexts = function (contexts) {
+ return contexts ?
+ contexts
+ .map(function (context) { return (context.id === 0 && context.iterationId === 0) ?
+ '' :
+ context.frameName + "-" + context.iterationId; })
+ .join('/') :
+ '';
+ };
+ /**
+ * Enter a new frame, a new context is pushed on the current context list.
+ * @param frameId new frame id
+ */
+ ExecutionContext.prototype.enterFrame = function (frameId) {
+ if (this.contexts) {
+ this.lastId++;
+ this.contexts = this.contexts.slice();
+ this.contexts.push(this.newFrame(this.lastId, frameId));
+ this._currentContextIds.unshift(this.contextIdforContexts(this.contexts));
+ }
+ };
+ /**
+ * Exit the current frame, the last context is removed from the current
+ * context list.
+ */
+ ExecutionContext.prototype.exitFrame = function () {
+ if (this.contexts && this.contexts.length > 1) {
+ this.contexts = this.contexts.slice();
+ this.contexts.splice(-1);
+ this.currentContextIds.shift();
+ }
+ else {
+ throw new Error('Cannot exit frame, the context is empty');
+ }
+ };
+ /**
+ * Enter the next iteration of a loop, the iteration id of last context is
+ * increased.
+ */
+ ExecutionContext.prototype.nextIteration = function () {
+ if (this.contexts && this.contexts.length > 0) {
+ this.contexts = this.contexts.slice();
+ this.lastId++;
+ var context = Object.assign({}, this.contexts[this.contexts.length - 1]);
+ context.iterationId += 1;
+ context.id = this.lastId;
+ this.contexts.splice(-1, 1, context);
+ this._currentContextIds.splice(0, 1, this.contextIdforContexts(this.contexts));
+ }
+ else {
+ throw new Error('Cannot increase frame iteration, the context is empty');
+ }
+ };
+ ExecutionContext.prototype.getWeight = function (name) {
+ return this.weightMap[name];
+ };
+ ExecutionContext.prototype.addTensorArray = function (tensorArray) {
+ this.tensorArrayMap[tensorArray.id] = tensorArray;
+ };
+ ExecutionContext.prototype.getTensorArray = function (id) {
+ return this.tensorArrayMap[id];
+ };
+ ExecutionContext.prototype.addTensorList = function (tensorList) {
+ this.tensorListMap[tensorList.id] = tensorList;
+ };
+ ExecutionContext.prototype.getTensorList = function (id) {
+ return this.tensorListMap[id];
+ };
+ ExecutionContext.prototype.dispose = function (keepIds) {
+ for (var key in this.tensorArrayMap) {
+ this.tensorArrayMap[key].clearAndClose(keepIds);
+ }
+ for (var key in this.tensorListMap) {
+ this.tensorListMap[key].clearAndClose(keepIds);
+ }
+ };
+ return ExecutionContext;
+ }());
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Given graph inputs and desired outputs, find the minimal set of nodes
+ * to execute in order to compute the outputs. In addition return other useful
+ * info such:
+ * - Missing inputs needed to compute the output.
+ * - Whether the subgraph contains dynamic ops (control flow, dynamic shape).
+ * - Alternative inputs in order to avoid async (dynamic op) execution.
+ */
+ function getExecutionSubgraph(inputs, outputs, weightMap, initNodes) {
+ var usedNodes = new Set();
+ var missingInputs = [];
+ var dynamicNode = null;
+ var syncInputs = null;
+ // Start with the outputs, going backwards and find all the nodes that are
+ // needed to compute those outputs.
+ var seen = new Set();
+ var inputNodeNames = Object.keys(inputs).map(function (name) { return parseNodeName(name)[0]; });
+ var initNodeNames = [];
+ if (initNodes != null) {
+ initNodeNames = initNodes.map(function (node) { return parseNodeName(node.name)[0]; });
+ }
+ var frontier = __spread(outputs);
+ while (frontier.length > 0) {
+ var node = frontier.pop();
+ if (isControlFlow(node) || isDynamicShape(node) || isHashTable(node)) {
+ if (dynamicNode == null) {
+ dynamicNode = node;
+ syncInputs = dynamicNode.children.map(function (child) { return child.name; })
+ .filter(function (name) { return usedNodes.has(name); });
+ }
+ }
+ usedNodes.add(node.name);
+ // Weights are dead end since we already have their values.
+ if (weightMap[node.name] != null) {
+ continue;
+ }
+ // This node is a dead end since it's one of the user-provided inputs.
+ if (inputNodeNames.indexOf(node.name) !== -1) {
+ continue;
+ }
+ // This node is a dead end since it doesn't have any inputs.
+ if (initNodeNames.indexOf(node.name) !== -1) {
+ continue;
+ }
+ if (node.inputs.length === 0) {
+ missingInputs.push(node.name);
+ continue;
+ }
+ node.inputs.forEach(function (input) {
+ // Don't add to the frontier if it is already there.
+ if (seen.has(input.name)) {
+ return;
+ }
+ seen.add(input.name);
+ frontier.push(input);
+ });
+ }
+ return { inputs: inputs, outputs: outputs, usedNodes: usedNodes, missingInputs: missingInputs, dynamicNode: dynamicNode, syncInputs: syncInputs };
+ }
+ /**
+ * Given the execution info, return a list of nodes in topological order that
+ * need to be executed to compute the output.
+ */
+ function getNodesInTopologicalOrder(graph, weightMap, executionInfo) {
+ var usedNodes = executionInfo.usedNodes, inputs = executionInfo.inputs;
+ var frontier = [];
+ var inputNodes = Object.keys(inputs)
+ .map(function (name) { return parseNodeName(name)[0]; })
+ .map(function (name) { return graph.nodes[name]; });
+ var initNodes = graph.initNodes;
+ inputNodes.forEach(function (input) {
+ if (usedNodes.has(input.name)) {
+ frontier.push(input);
+ }
+ });
+ graph.weights.forEach(function (weight) {
+ if (usedNodes.has(weight.name)) {
+ frontier.push(weight);
+ }
+ });
+ if (initNodes != null) {
+ initNodes.forEach(function (node) {
+ if (usedNodes.has(node.name)) {
+ frontier.push(node);
+ }
+ });
+ }
+ var seen = new Set();
+ var orderedNodes = [];
+ while (frontier.length > 0) {
+ var node = frontier.pop();
+ seen.add(node.name);
+ if (!weightMap[node.name]) {
+ orderedNodes.push(node);
+ }
+ node.children.forEach(function (child) {
+ if (!seen.has(child.name) && usedNodes.has(child.name) &&
+ child.inputs.every(function (input) { return seen.has(input.name); })) {
+ frontier.push(child);
+ }
+ });
+ }
+ return orderedNodes;
+ }
+ var CONTROL_FLOW_OPS = [
+ 'Switch', 'Merge', 'Enter', 'Exit', 'NextIteration', 'StatelessIf',
+ 'StatelessWhile', 'if', 'While'
+ ];
+ var DYNAMIC_SHAPE_OPS = [
+ 'NonMaxSuppressionV2', 'NonMaxSuppressionV3', 'NonMaxSuppressionV5', 'Where'
+ ];
+ var HASH_TABLE_OPS = [
+ 'HashTable', 'HashTableV2', 'LookupTableImport', 'LookupTableImportV2',
+ 'LookupTableFind', 'LookupTableFindV2', 'LookupTableSize', 'LookupTableSizeV2'
+ ];
+ function isControlFlow(node) {
+ return CONTROL_FLOW_OPS.indexOf(node.op) >= 0;
+ }
+ function isDynamicShape(node) {
+ return DYNAMIC_SHAPE_OPS.indexOf(node.op) >= 0;
+ }
+ function isHashTable(node) {
+ return HASH_TABLE_OPS.indexOf(node.op) >= 0;
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var GraphExecutor = /** @class */ (function () {
+ /**
+ *
+ * @param graph Graph the model or function graph to be executed.
+ * @param parent When building function exector you need to set the parent
+ * executor. Since the weights and function executor maps are set at parant
+ * level, that function executor can access the function maps and weight maps
+ * through the parent.
+ */
+ function GraphExecutor(graph, parent) {
+ var _this = this;
+ this.graph = graph;
+ this.parent = parent;
+ this.compiledMap = new Map();
+ this._weightMap = {};
+ this.SEPERATOR = ',';
+ this._functions = {};
+ this._functionExecutorMap = {};
+ this._outputs = graph.outputs;
+ this._inputs = graph.inputs;
+ this._initNodes = graph.initNodes;
+ this._signature = graph.signature;
+ this._functions = graph.functions;
+ // create sub-graph executors
+ if (graph.functions != null) {
+ Object.keys(graph.functions).forEach(function (name) {
+ _this._functionExecutorMap[name] =
+ new GraphExecutor(graph.functions[name], _this);
+ });
+ }
+ }
+ Object.defineProperty(GraphExecutor.prototype, "weightIds", {
+ get: function () {
+ return this.parent ? this.parent.weightIds : this._weightIds;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphExecutor.prototype, "functionExecutorMap", {
+ get: function () {
+ return this.parent ? this.parent.functionExecutorMap :
+ this._functionExecutorMap;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphExecutor.prototype, "weightMap", {
+ get: function () {
+ return this.parent ? this.parent.weightMap : this._weightMap;
+ },
+ set: function (weightMap) {
+ var weightIds = Object.keys(weightMap).map(function (key) { return weightMap[key].map(function (tensor) { return tensor.id; }); });
+ this._weightIds = [].concat.apply([], __spread(weightIds));
+ this._weightMap = weightMap;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphExecutor.prototype, "resourceManager", {
+ /**
+ * Set `ResourceManager` shared by executors of a model.
+ * @param resourceManager: `ResourceManager` of the `GraphModel`.
+ */
+ set: function (resourceManager) {
+ this._resourceManager = resourceManager;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphExecutor.prototype, "inputs", {
+ get: function () {
+ return this._inputs.map(function (node) {
+ return {
+ name: node.name,
+ shape: node.attrParams['shape'] ?
+ node.attrParams['shape'].value :
+ undefined,
+ dtype: node.attrParams['dtype'] ?
+ node.attrParams['dtype'].value :
+ undefined
+ };
+ });
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphExecutor.prototype, "outputs", {
+ get: function () {
+ return this._outputs.map(function (node) {
+ return {
+ name: node.name,
+ shape: node.attrParams['shape'] ?
+ node.attrParams['shape'].value :
+ undefined,
+ dtype: node.attrParams['dtype'] ?
+ node.attrParams['dtype'].value :
+ undefined
+ };
+ });
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphExecutor.prototype, "inputNodes", {
+ get: function () {
+ return this._inputs.map(function (node) { return node.signatureKey || node.name; });
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphExecutor.prototype, "outputNodes", {
+ get: function () {
+ return this._outputs.map(function (node) {
+ var name = node.signatureKey || node.name;
+ return node.defaultOutput ? (name + ":" + node.defaultOutput) : name;
+ });
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphExecutor.prototype, "functions", {
+ get: function () {
+ var _this = this;
+ return Object.keys(this._functions).reduce(function (map, key) {
+ map[key] = _this._functions[key].signature;
+ return map;
+ }, {});
+ },
+ enumerable: true,
+ configurable: true
+ });
+ GraphExecutor.prototype.getCompilationKey = function (inputs, outputs) {
+ var sortedInputs = inputs.map(function (node) { return node.name; }).sort();
+ var sortedOutputs = outputs.map(function (node) { return node.name; }).sort();
+ return sortedInputs.join(this.SEPERATOR) + '--' +
+ sortedOutputs.join(this.SEPERATOR);
+ };
+ /**
+ * Compiles the inference graph and returns the minimal set of nodes that are
+ * required for execution, in the correct execution order.
+ */
+ GraphExecutor.prototype.compile = function (inputs, outputs) {
+ var executionInfo = getExecutionSubgraph(inputs, outputs, this.weightMap, this._initNodes);
+ var missingInputs = executionInfo.missingInputs, dynamicNode = executionInfo.dynamicNode, syncInputs = executionInfo.syncInputs;
+ if (dynamicNode != null) {
+ throw new Error("This execution contains the node '" + dynamicNode.name + "', which has " +
+ ("the dynamic op '" + dynamicNode.op + "'. Please use ") +
+ "model.executeAsync() instead. Alternatively, to avoid the " +
+ ("dynamic ops, specify the inputs [" + syncInputs + "]"));
+ }
+ if (missingInputs.length > 0) {
+ var outNames = outputs.map(function (n) { return n.name; });
+ var inNames = Object.keys(inputs);
+ throw new Error("Cannot compute the outputs [" + outNames + "] from the provided inputs " +
+ ("[" + inNames + "]. Missing the following inputs: [" + missingInputs + "]"));
+ }
+ return getNodesInTopologicalOrder(this.graph, this.weightMap, executionInfo);
+ };
+ /**
+ * Executes the inference for given input tensors.
+ * @param inputs Tensor map for the model inputs, keyed by the input node
+ * names.
+ * @param outputs Optional. output node name from the Tensorflow model, if
+ * no outputs are specified, the default outputs of the model would be used.
+ * You can inspect intermediate nodes of the model by adding them to the
+ * outputs array.
+ */
+ GraphExecutor.prototype.execute = function (inputs, outputs) {
+ var _this = this;
+ inputs = this.mapInputs(inputs);
+ var names = Object.keys(inputs).sort();
+ this.checkInputs(inputs);
+ this.checkInputShapeAndType(inputs);
+ outputs = this.mapOutputs(outputs);
+ this.checkOutputs(outputs);
+ var inputNodes = names.map(function (name) { return _this.graph.nodes[parseNodeName(name)[0]]; });
+ var outputNodeNames = outputs.map(function (name) { return parseNodeName(name)[0]; });
+ var outputNodes = outputNodeNames.map(function (name) { return _this.graph.nodes[name]; });
+ // If no outputs are specified, then use the default outputs of the model.
+ if (outputNodes.length === 0) {
+ outputNodes = this._outputs;
+ }
+ var compilationKey = this.getCompilationKey(inputNodes, outputNodes);
+ // Do nothing if the compiled graph cache contains the input.
+ var orderedNodes = this.compiledMap.get(compilationKey);
+ if (orderedNodes == null) {
+ orderedNodes = this.compile(inputs, outputNodes);
+ this.compiledMap.set(compilationKey, orderedNodes);
+ }
+ var tensorArrayMap = {};
+ var tensorListMap = {};
+ return tfc.tidy(function () {
+ var context = new ExecutionContext(_this.weightMap, tensorArrayMap, tensorListMap, _this.functionExecutorMap);
+ var tensorsMap = __assign({}, _this.weightMap);
+ Object.keys(inputs).forEach(function (name) {
+ var _a = __read(parseNodeName(name), 2), nodeName = _a[0], index = _a[1];
+ var tensors = [];
+ tensors[index] = inputs[name];
+ tensorsMap[nodeName] = tensors;
+ });
+ var tensorsToKeep = _this.getFrozenTensorIds(tensorsMap);
+ var intermediateTensorConsumerCount = {};
+ for (var i = 0; i < orderedNodes.length; i++) {
+ var node = orderedNodes[i];
+ if (!tensorsMap[node.name]) {
+ var tensors = executeOp$j(node, tensorsMap, context, _this._resourceManager);
+ if (tfc.util.isPromise(tensors)) {
+ throw new Error("The execution of the op '" + node.op + "' returned a promise. " +
+ "Please use model.executeAsync() instead.");
+ }
+ tensorsMap[node.name] = tensors;
+ _this.checkTensorForDisposal(node.name, node, tensorsMap, context, tensorsToKeep, outputNodeNames, intermediateTensorConsumerCount);
+ }
+ }
+ // dispose the context for the root executor
+ if (_this.parent == null) {
+ context.dispose(tensorsToKeep);
+ }
+ return outputs.map(function (name) { return getTensor(name, tensorsMap, context); });
+ });
+ };
+ GraphExecutor.prototype.getFrozenTensorIds = function (tensorMap) {
+ var ids = [].concat.apply([], Object.keys(tensorMap)
+ .map(function (key) { return tensorMap[key]; })
+ .map(function (tensors) { return tensors.map(function (tensor) { return tensor.id; }); }));
+ return new Set(ids);
+ };
+ GraphExecutor.prototype.checkTensorForDisposal = function (nodeName, node, tensorMap, context, tensorsToKeep, outputNames, intermediateTensorConsumerCount) {
+ // Skip output nodes and any control flow nodes, since its dependency is
+ // tricky to track correctly.
+ if (node.category === 'control' || outputNames.indexOf(nodeName) !== -1) {
+ return;
+ }
+ tensorMap[nodeName].forEach(function (tensor) {
+ if (tensor != null) {
+ intermediateTensorConsumerCount[tensor.id] =
+ (intermediateTensorConsumerCount[tensor.id] || 0) +
+ node.children.length;
+ }
+ });
+ node.inputs.forEach(function (input) {
+ // Skip any control flow nodes, since its dependency is tricky to track
+ // correctly.
+ if (input.category !== 'control') {
+ var tensors = getTensorsForCurrentContenxt(input.name, tensorMap, context);
+ if (tensors != null) {
+ tensors.forEach(function (tensor) {
+ if (tensor && !tensor.kept && !tensorsToKeep.has(tensor.id)) {
+ var count = intermediateTensorConsumerCount[tensor.id];
+ if (count === 1) {
+ tensor.dispose();
+ delete intermediateTensorConsumerCount[tensor.id];
+ }
+ else if (count != null) {
+ // only intermediate nodes has count set, inputs and weights are
+ // not.
+ intermediateTensorConsumerCount[tensor.id]--;
+ }
+ }
+ });
+ }
+ }
+ });
+ };
+ /**
+ * Executes the inference for given input tensors in Async fashion.
+ * @param inputs Tensor map for the model inputs, keyed by the input node
+ * names.
+ * @param outputs output node name from the Tensorflow model, if no outputs
+ * are specified, the default outputs of the model would be used. You can
+ * inspect intermediate nodes of the model by adding them to the outputs
+ * array.
+ */
+ GraphExecutor.prototype.executeAsync = function (inputs, outputs) {
+ return __awaiter(this, void 0, void 0, function () {
+ return __generator(this, function (_a) {
+ return [2 /*return*/, this._executeAsync(inputs, outputs)];
+ });
+ });
+ };
+ /**
+ * Executes the inference for given input tensors in Async fashion.
+ * @param inputs Tensor map for the model inputs, keyed by the input node
+ * names.
+ * @param outputs Optional. output node name from the Tensorflow model,
+ * if no outputs are specified, the default outputs of the model would be
+ * used. You can inspect intermediate nodes of the model by adding them to the
+ * outputs array.
+ * @param isFunctionExecution Optional. Flag for executing a function.
+ * @param tensorArrayMap Optional, global TensorArray map by id. Used for
+ * function execution.
+ * @param tensorArrayMap Optinal global TensorList map by id. Used for
+ * function execution.
+ */
+ GraphExecutor.prototype._executeAsync = function (inputs, outputs, isFunctionExecution, tensorArrayMap, tensorListMap) {
+ if (isFunctionExecution === void 0) { isFunctionExecution = false; }
+ if (tensorArrayMap === void 0) { tensorArrayMap = {}; }
+ if (tensorListMap === void 0) { tensorListMap = {}; }
+ return __awaiter(this, void 0, void 0, function () {
+ var context, tensorMap, results, outputIds, inputIds, keepIds;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ if (!isFunctionExecution) {
+ inputs = this.mapInputs(inputs);
+ this.checkInputs(inputs);
+ this.checkInputShapeAndType(inputs);
+ outputs = this.mapOutputs(outputs);
+ this.checkOutputs(outputs);
+ }
+ context = new ExecutionContext(this.weightMap, tensorArrayMap, tensorListMap, this.functionExecutorMap);
+ return [4 /*yield*/, this.executeWithControlFlow(inputs, context, outputs, isFunctionExecution)];
+ case 1:
+ tensorMap = _a.sent();
+ results = outputs.map(function (name) { return getTensor(name, tensorMap, context); });
+ outputIds = results.map(function (t) { return t.id; });
+ inputIds = Object.keys(inputs).map(function (name) { return inputs[name].id; });
+ keepIds = new Set(__spread(outputIds, inputIds, this.weightIds));
+ Object.keys(tensorMap).forEach(function (key) {
+ var tensorArray = tensorMap[key];
+ tensorArray.forEach(function (tensor) {
+ if (tensor && !tensor.kept && !tensor.isDisposed &&
+ !keepIds.has(tensor.id)) {
+ tensor.dispose();
+ }
+ });
+ });
+ // dispose the context for the root executor
+ if (this.parent == null) {
+ context.dispose(keepIds);
+ }
+ return [2 /*return*/, results];
+ }
+ });
+ });
+ };
+ GraphExecutor.prototype.executeFunctionAsync = function (inputs, tensorArrayMap, tensorListMap) {
+ return __awaiter(this, void 0, void 0, function () {
+ var mappedInputs;
+ var _this = this;
+ return __generator(this, function (_a) {
+ mappedInputs = inputs.reduce(function (map, tensor, index) {
+ map[_this.inputs[index].name] = tensor;
+ return map;
+ }, {});
+ return [2 /*return*/, this._executeAsync(mappedInputs, this.outputNodes, true, tensorArrayMap, tensorListMap)];
+ });
+ });
+ };
+ /**
+ * When there are control flow nodes in the graph, the graph execution use
+ * ExecutionContext to keep track of the frames and loop iterators.
+ * @param inputs placeholder tensors for the graph.
+ * @param context the execution context object for current execution.
+ * @param outputNames Optional. output node name from the Tensorflow model,
+ * if no outputs are specified, the default outputs of the model would be
+ * used. You can inspect intermediate nodes of the model by adding them to the
+ * outputs array.
+ * @param isFunctionExecution Flag for executing a function.
+ */
+ GraphExecutor.prototype.executeWithControlFlow = function (inputs, context, outputNames, isFunctionExecution) {
+ return __awaiter(this, void 0, void 0, function () {
+ var names, inputNodes, outputNodeNames, outputNodes, _a, usedNodes, missingInputs, dynamicNode, syncInputs, stack, tensorsMap, intermediateTensorConsumerCount, tensorsToKeep, added, promises, missingOutputs, alternativeMsg;
+ var _this = this;
+ return __generator(this, function (_b) {
+ switch (_b.label) {
+ case 0:
+ names = Object.keys(inputs);
+ inputNodes = names.map(function (name) { return _this.graph.nodes[parseNodeName(name)[0]]; });
+ outputNodeNames = outputNames.map(function (name) { return parseNodeName(name)[0]; });
+ outputNodes = outputNodeNames.map(function (name) { return _this.graph.nodes[name]; });
+ // If no outputs are specified, then use the default outputs of the model.
+ if (outputNodes.length === 0) {
+ outputNodes = this._outputs;
+ }
+ _a = getExecutionSubgraph(inputs, outputNodes, this.weightMap, this._initNodes), usedNodes = _a.usedNodes, missingInputs = _a.missingInputs, dynamicNode = _a.dynamicNode, syncInputs = _a.syncInputs;
+ stack = __spread(inputNodes, this.graph.weights, (this._initNodes || [])).map(function (node) {
+ return { node: node, contexts: context.currentContext };
+ });
+ tensorsMap = __assign({}, this.weightMap);
+ Object.keys(inputs).forEach(function (name) {
+ var _a = __read(parseNodeName(name), 2), nodeName = _a[0], index = _a[1];
+ var tensors = [];
+ tensors[index] = inputs[name];
+ tensorsMap[nodeName] = tensors;
+ });
+ intermediateTensorConsumerCount = {};
+ tensorsToKeep = this.getFrozenTensorIds(tensorsMap);
+ added = {};
+ _b.label = 1;
+ case 1:
+ if (!(stack.length > 0)) return [3 /*break*/, 3];
+ promises = this.processStack(inputNodes, stack, context, tensorsMap, added, tensorsToKeep, outputNodeNames, intermediateTensorConsumerCount, usedNodes);
+ return [4 /*yield*/, Promise.all(promises)];
+ case 2:
+ _b.sent();
+ return [3 /*break*/, 1];
+ case 3:
+ if (dynamicNode == null && !isFunctionExecution) {
+ console.warn("This model execution did not contain any nodes with control flow " +
+ "or dynamic output shapes. You can use model.execute() instead.");
+ }
+ missingOutputs = outputNodes
+ .filter(function (node) { return !isControlFlow(node) &&
+ !getTensor(node.name, tensorsMap, context); })
+ .map(function (node) { return node.name; });
+ if (missingOutputs.length > 0) {
+ alternativeMsg = '';
+ if (dynamicNode != null) {
+ alternativeMsg =
+ "Alternatively, to avoid the dynamic ops, use model.execute() " +
+ ("and specify the inputs [" + syncInputs + "]");
+ }
+ throw new Error("Cannot compute the outputs [" + missingOutputs + "] from the provided " +
+ ("inputs [" + names + "]. Consider providing the following inputs: ") +
+ ("[" + missingInputs + "]. " + alternativeMsg));
+ }
+ return [2 /*return*/, tensorsMap];
+ }
+ });
+ });
+ };
+ GraphExecutor.prototype.processStack = function (inputNodes, stack, context, tensorMap, added, tensorsToKeep, outputNames, intermediateTensorConsumerCount, usedNodes) {
+ var _this = this;
+ var promises = [];
+ var _loop_1 = function () {
+ var _a, _b;
+ var item = stack.pop();
+ context.currentContext = item.contexts;
+ var nodeName = '';
+ // The tensor of the Enter op with isConstant set should be set
+ // in the parent scope, so it will be available as constant for the
+ // whole loop.
+ if (item.node.op === 'Enter' &&
+ getParamValue('isConstant', item.node, tensorMap, context)) {
+ _a = __read(getNodeNameAndIndex(item.node.name, context), 1), nodeName = _a[0];
+ }
+ // only process nodes that are not in the tensorMap yet, this include
+ // inputNodes and internal initNodes.
+ if (tensorMap[item.node.name] == null) {
+ var tensors = executeOp$j(item.node, tensorMap, context, this_1._resourceManager);
+ if (!nodeName) {
+ _b = __read(getNodeNameAndIndex(item.node.name, context), 1), nodeName = _b[0];
+ }
+ var currentContext_1 = context.currentContext;
+ if (tfc.util.isPromise(tensors)) {
+ promises.push(tensors.then(function (t) {
+ tensorMap[nodeName] = t;
+ context.currentContext = currentContext_1;
+ _this.checkTensorForDisposal(nodeName, item.node, tensorMap, context, tensorsToKeep, outputNames, intermediateTensorConsumerCount);
+ _this.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
+ return t;
+ }));
+ }
+ else {
+ tensorMap[nodeName] = tensors;
+ this_1.checkTensorForDisposal(nodeName, item.node, tensorMap, context, tensorsToKeep, outputNames, intermediateTensorConsumerCount);
+ this_1.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
+ }
+ }
+ else {
+ this_1.processChildNodes(item.node, stack, context, tensorMap, added, usedNodes);
+ }
+ };
+ var this_1 = this;
+ while (stack.length > 0) {
+ _loop_1();
+ }
+ return promises;
+ };
+ GraphExecutor.prototype.processChildNodes = function (node, stack, context, tensorMap, added, usedNodes) {
+ node.children.forEach(function (childNode) {
+ var _a = __read(getNodeNameAndIndex(childNode.name, context), 1), nodeName = _a[0];
+ if (added[nodeName] || !usedNodes.has(childNode.name)) {
+ return;
+ }
+ // Merge op can be pushed if any of its inputs has value.
+ if (childNode.op === 'Merge') {
+ if (childNode.inputNames.some(function (name) {
+ return !!getTensor(name, tensorMap, context);
+ })) {
+ added[nodeName] = true;
+ stack.push({ contexts: context.currentContext, node: childNode });
+ }
+ }
+ else // Otherwise all inputs must to have value.
+ if (childNode.inputNames.every(function (name) {
+ return !!getTensor(name, tensorMap, context);
+ })) {
+ added[nodeName] = true;
+ stack.push({ contexts: context.currentContext, node: childNode });
+ }
+ });
+ };
+ /**
+ * Releases the memory used by the weight tensors.
+ */
+ GraphExecutor.prototype.dispose = function () {
+ var _this = this;
+ Object.keys(this.weightMap)
+ .forEach(function (key) { return _this.weightMap[key].forEach(function (tensor) { return tensor.dispose(); }); });
+ };
+ GraphExecutor.prototype.checkInputShapeAndType = function (inputs) {
+ var _this = this;
+ Object.keys(inputs).forEach(function (name) {
+ var input = inputs[name];
+ var _a = __read(parseNodeName(name), 1), nodeName = _a[0];
+ var node = _this.graph.nodes[nodeName];
+ if (node.attrParams['shape'] && node.attrParams['shape'].value) {
+ var shape_1 = node.attrParams['shape'].value;
+ var match = shape_1.length === input.shape.length &&
+ input.shape.every(function (dim, index) { return shape_1[index] === -1 || shape_1[index] === dim; });
+ tfc.util.assert(match, function () { return "The shape of dict['" + node.name + "'] provided in " +
+ ("model.execute(dict) must be [" + shape_1 + "], but was ") +
+ ("[" + input.shape + "]"); });
+ }
+ if (node.attrParams['dtype'] && node.attrParams['dtype'].value) {
+ tfc.util.assert(input.dtype === node.attrParams['dtype'].value, function () { return "The dtype of dict['" + node.name + "'] provided in " +
+ "model.execute(dict) must be " +
+ (node.attrParams['dtype'].value + ", but was " + input.dtype); });
+ }
+ });
+ };
+ GraphExecutor.prototype.mapInputs = function (inputs) {
+ var result = {};
+ for (var inputName in inputs) {
+ if (this._signature != null && this._signature.inputs != null &&
+ this._signature.inputs[inputName] != null) {
+ var tensor = this._signature.inputs[inputName];
+ result[tensor.name] = inputs[inputName];
+ }
+ else {
+ result[inputName] = inputs[inputName];
+ }
+ }
+ return result;
+ };
+ GraphExecutor.prototype.checkInputs = function (inputs) {
+ var _this = this;
+ var notInGraph = Object.keys(inputs).filter(function (name) {
+ var _a = __read(parseNodeName(name), 1), nodeName = _a[0];
+ return _this.graph.nodes[nodeName] == null;
+ });
+ if (notInGraph.length > 0) {
+ throw new Error("The dict provided in model.execute(dict) has " +
+ ("keys: [" + notInGraph + "] that are not part of graph"));
+ }
+ };
+ GraphExecutor.prototype.mapOutputs = function (outputs) {
+ var _this = this;
+ return outputs.map(function (name) {
+ if (_this._signature != null && _this._signature.outputs != null &&
+ _this._signature.outputs[name] != null) {
+ var tensor = _this._signature.outputs[name];
+ return tensor.name;
+ }
+ return name;
+ }, {});
+ };
+ GraphExecutor.prototype.checkOutputs = function (outputs) {
+ var _this = this;
+ outputs.forEach(function (name) {
+ var _a = __read(parseNodeName(name), 1), normalizedName = _a[0];
+ if (!_this.graph.nodes[normalizedName]) {
+ throw new Error("The output '" + name + "' is not found in the graph");
+ }
+ });
+ };
+ return GraphExecutor;
+ }());
+
+ /**
+ * Contains global resources of a model.
+ */
+ var ResourceManager = /** @class */ (function () {
+ function ResourceManager(hashTableNameToHandle, hashTableMap) {
+ if (hashTableNameToHandle === void 0) { hashTableNameToHandle = {}; }
+ if (hashTableMap === void 0) { hashTableMap = {}; }
+ this.hashTableNameToHandle = hashTableNameToHandle;
+ this.hashTableMap = hashTableMap;
+ }
+ /**
+ * Register a `HashTable` in the resource manager.
+ *
+ * The `HashTable` can be retrieved by `resourceManager.getHashTableById`,
+ * where id is the table handle tensor's id.
+ *
+ * @param name Op node name that creates the `HashTable`.
+ * @param hashTable The `HashTable` to be added to resource manager.
+ */
+ ResourceManager.prototype.addHashTable = function (name, hashTable) {
+ this.hashTableNameToHandle[name] = hashTable.handle;
+ this.hashTableMap[hashTable.id] = hashTable;
+ };
+ /**
+ * Get the table handle by node name.
+ * @param name Op node name that creates the `HashTable`. This name is also
+ * used in the inputs list of lookup and import `HashTable` ops.
+ */
+ ResourceManager.prototype.getHashTableHandleByName = function (name) {
+ return this.hashTableNameToHandle[name];
+ };
+ /**
+ * Get the actual `HashTable` by its handle tensor's id.
+ * @param id The id of the handle tensor.
+ */
+ ResourceManager.prototype.getHashTableById = function (id) {
+ return this.hashTableMap[id];
+ };
+ /**
+ * Dispose `ResourceManager`, including its hashTables and tensors in them.
+ */
+ ResourceManager.prototype.dispose = function () {
+ for (var key in this.hashTableMap) {
+ this.hashTableMap[key].clearAndClose();
+ delete this.hashTableMap[key];
+ }
+ for (var name_1 in this.hashTableNameToHandle) {
+ this.hashTableNameToHandle[name_1].dispose();
+ delete this.hashTableNameToHandle[name_1];
+ }
+ };
+ return ResourceManager;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var TFHUB_SEARCH_PARAM = '?tfjs-format=file';
+ var DEFAULT_MODEL_NAME = 'model.json';
+ /**
+ * A `tf.GraphModel` is a directed, acyclic graph built from a
+ * SavedModel GraphDef and allows inference execution.
+ *
+ * A `tf.GraphModel` can only be created by loading from a model converted from
+ * a [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) using
+ * the command line converter tool and loaded via `tf.loadGraphModel`.
+ *
+ * @doc {heading: 'Models', subheading: 'Classes'}
+ */
+ var GraphModel = /** @class */ (function () {
+ /**
+ * @param modelUrl url for the model, or an `io.IOHandler`.
+ * @param weightManifestUrl url for the weight file generated by
+ * scripts/convert.py script.
+ * @param requestOption options for Request, which allows to send credentials
+ * and custom headers.
+ * @param onProgress Optional, progress callback function, fired periodically
+ * before the load is completed.
+ */
+ function GraphModel(modelUrl, loadOptions) {
+ if (loadOptions === void 0) { loadOptions = {}; }
+ this.modelUrl = modelUrl;
+ this.loadOptions = loadOptions;
+ this.version = 'n/a';
+ if (loadOptions == null) {
+ this.loadOptions = {};
+ }
+ this.resourceManager = new ResourceManager();
+ }
+ Object.defineProperty(GraphModel.prototype, "modelVersion", {
+ // Returns the version information for the tensorflow model GraphDef.
+ get: function () {
+ return this.version;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphModel.prototype, "inputNodes", {
+ get: function () {
+ return this.executor.inputNodes;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphModel.prototype, "outputNodes", {
+ get: function () {
+ return this.executor.outputNodes;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphModel.prototype, "inputs", {
+ get: function () {
+ return this.executor.inputs;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphModel.prototype, "outputs", {
+ get: function () {
+ return this.executor.outputs;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphModel.prototype, "weights", {
+ get: function () {
+ return this.executor.weightMap;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphModel.prototype, "metadata", {
+ get: function () {
+ return this.artifacts.userDefinedMetadata;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Object.defineProperty(GraphModel.prototype, "modelSignature", {
+ get: function () {
+ return this.signature;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ GraphModel.prototype.findIOHandler = function () {
+ var path = this.modelUrl;
+ if (path.load != null) {
+ // Path is an IO Handler.
+ this.handler = path;
+ }
+ else if (this.loadOptions.requestInit != null) {
+ this.handler = tfc.io.browserHTTPRequest(path, this.loadOptions);
+ }
+ else {
+ var handlers = tfc.io.getLoadHandlers(path, this.loadOptions);
+ if (handlers.length === 0) {
+ // For backward compatibility: if no load handler can be found,
+ // assume it is a relative http path.
+ handlers.push(tfc.io.browserHTTPRequest(path, this.loadOptions));
+ }
+ else if (handlers.length > 1) {
+ throw new Error("Found more than one (" + handlers.length + ") load handlers for " +
+ ("URL '" + [path] + "'"));
+ }
+ this.handler = handlers[0];
+ }
+ };
+ /**
+ * Loads the model and weight files, construct the in memory weight map and
+ * compile the inference graph.
+ */
+ GraphModel.prototype.load = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var artifacts;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ this.findIOHandler();
+ if (this.handler.load == null) {
+ throw new Error('Cannot proceed with model loading because the IOHandler provided ' +
+ 'does not have the `load` method implemented.');
+ }
+ return [4 /*yield*/, this.handler.load()];
+ case 1:
+ artifacts = _a.sent();
+ return [2 /*return*/, this.loadSync(artifacts)];
+ }
+ });
+ });
+ };
+ /**
+ * Synchronously construct the in memory weight map and
+ * compile the inference graph. Also initialize hashtable if any.
+ *
+ * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
+ */
+ GraphModel.prototype.loadSync = function (artifacts) {
+ this.artifacts = artifacts;
+ var graph = this.artifacts.modelTopology;
+ var signature;
+ if (this.artifacts.userDefinedMetadata != null &&
+ this.artifacts.userDefinedMetadata.signature != null) {
+ signature = // tslint:disable-next-line:no-any
+ this.artifacts.userDefinedMetadata.signature;
+ }
+ else {
+ signature = this.artifacts.signature;
+ }
+ this.signature = signature;
+ this.version = graph.versions.producer + "." + graph.versions.minConsumer;
+ var weightMap = tfc.io.decodeWeights(this.artifacts.weightData, this.artifacts.weightSpecs);
+ this.executor = new GraphExecutor(OperationMapper.Instance.transformGraph(graph, this.signature));
+ this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap);
+ // Attach a model-level resourceManager to each executor to share resources,
+ // such as `HashTable`.
+ this.executor.resourceManager = this.resourceManager;
+ if (artifacts.modelInitializer != null &&
+ artifacts.modelInitializer.node != null) {
+ var initializer = OperationMapper.Instance.transformGraph(artifacts.modelInitializer);
+ this.initializer = new GraphExecutor(initializer);
+ this.initializer.weightMap = this.executor.weightMap;
+ // Attach a model-level resourceManager to the initializer, the
+ // hashTables created from when executing the initializer will be stored
+ // in the resourceManager.
+ this.initializer.resourceManager = this.resourceManager;
+ this.initializer.executeAsync({}, []);
+ }
+ return true;
+ };
+ /**
+ * Save the configuration and/or weights of the GraphModel.
+ *
+ * An `IOHandler` is an object that has a `save` method of the proper
+ * signature defined. The `save` method manages the storing or
+ * transmission of serialized data ("artifacts") that represent the
+ * model's topology and weights onto or via a specific medium, such as
+ * file downloads, local storage, IndexedDB in the web browser and HTTP
+ * requests to a server. TensorFlow.js provides `IOHandler`
+ * implementations for a number of frequently used saving mediums, such as
+ * `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`
+ * for more details.
+ *
+ * This method also allows you to refer to certain types of `IOHandler`s
+ * as URL-like string shortcuts, such as 'localstorage://' and
+ * 'indexeddb://'.
+ *
+ * Example 1: Save `model`'s topology and weights to browser [local
+ * storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);
+ * then load it back.
+ *
+ * ```js
+ * const modelUrl =
+ * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
+ * const model = await tf.loadGraphModel(modelUrl);
+ * const zeros = tf.zeros([1, 224, 224, 3]);
+ * model.predict(zeros).print();
+ *
+ * const saveResults = await model.save('localstorage://my-model-1');
+ *
+ * const loadedModel = await tf.loadGraphModel('localstorage://my-model-1');
+ * console.log('Prediction from loaded model:');
+ * model.predict(zeros).print();
+ * ```
+ *
+ * @param handlerOrURL An instance of `IOHandler` or a URL-like,
+ * scheme-based string shortcut for `IOHandler`.
+ * @param config Options for saving the model.
+ * @returns A `Promise` of `SaveResult`, which summarizes the result of
+ * the saving, such as byte sizes of the saved artifacts for the model's
+ * topology and weight values.
+ *
+ * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
+ */
+ GraphModel.prototype.save = function (handlerOrURL, config) {
+ return __awaiter(this, void 0, void 0, function () {
+ var handlers;
+ return __generator(this, function (_a) {
+ if (typeof handlerOrURL === 'string') {
+ handlers = tfc.io.getSaveHandlers(handlerOrURL);
+ if (handlers.length === 0) {
+ throw new Error("Cannot find any save handlers for URL '" + handlerOrURL + "'");
+ }
+ else if (handlers.length > 1) {
+ throw new Error("Found more than one (" + handlers.length + ") save handlers for " +
+ ("URL '" + handlerOrURL + "'"));
+ }
+ handlerOrURL = handlers[0];
+ }
+ if (handlerOrURL.save == null) {
+ throw new Error('GraphModel.save() cannot proceed because the IOHandler ' +
+ 'provided does not have the `save` attribute defined.');
+ }
+ return [2 /*return*/, handlerOrURL.save(this.artifacts)];
+ });
+ });
+ };
+ /**
+ * Execute the inference for the input tensors.
+ *
+ * @param input The input tensors, when there is single input for the model,
+ * inputs param should be a `tf.Tensor`. For models with mutliple inputs,
+ * inputs params should be in either `tf.Tensor`[] if the input order is
+ * fixed, or otherwise NamedTensorMap format.
+ *
+ * For model with multiple inputs, we recommend you use NamedTensorMap as the
+ * input type, if you use `tf.Tensor`[], the order of the array needs to
+ * follow the
+ * order of inputNodes array. @see {@link GraphModel.inputNodes}
+ *
+ * You can also feed any intermediate nodes using the NamedTensorMap as the
+ * input type. For example, given the graph
+ * InputNode => Intermediate => OutputNode,
+ * you can execute the subgraph Intermediate => OutputNode by calling
+ * model.execute('IntermediateNode' : tf.tensor(...));
+ *
+ * This is useful for models that uses tf.dynamic_rnn, where the intermediate
+ * state needs to be fed manually.
+ *
+ * For batch inference execution, the tensors for each input need to be
+ * concatenated together. For example with mobilenet, the required input shape
+ * is [1, 244, 244, 3], which represents the [batch, height, width, channel].
+ * If we are provide a batched data of 100 images, the input tensor should be
+ * in the shape of [100, 244, 244, 3].
+ *
+ * @param config Prediction configuration for specifying the batch size and
+ * output node names. Currently the batch size option is ignored for graph
+ * model.
+ *
+ * @returns Inference result tensors. The output would be single `tf.Tensor`
+ * if model has single output node, otherwise Tensor[] or NamedTensorMap[]
+ * will be returned for model with multiple outputs.
+ *
+ * @doc {heading: 'Models', subheading: 'Classes'}
+ */
+ GraphModel.prototype.predict = function (inputs, config) {
+ return this.execute(inputs, this.outputNodes);
+ };
+ GraphModel.prototype.normalizeInputs = function (inputs) {
+ if (!(inputs instanceof tfc.Tensor) && !Array.isArray(inputs)) {
+ // The input is already a NamedTensorMap.
+ return inputs;
+ }
+ inputs = Array.isArray(inputs) ? inputs : [inputs];
+ if (inputs.length !== this.inputNodes.length) {
+ throw new Error('Input tensor count mismatch,' +
+ ("the graph model has " + this.inputNodes.length + " placeholders, ") +
+ ("while there are " + inputs.length + " input tensors."));
+ }
+ return this.inputNodes.reduce(function (map, inputName, i) {
+ map[inputName] = inputs[i];
+ return map;
+ }, {});
+ };
+ GraphModel.prototype.normalizeOutputs = function (outputs) {
+ outputs = outputs || this.outputNodes;
+ return !Array.isArray(outputs) ? [outputs] : outputs;
+ };
+ /**
+ * Executes inference for the model for given input tensors.
+ * @param inputs tensor, tensor array or tensor map of the inputs for the
+ * model, keyed by the input node names.
+ * @param outputs output node name from the Tensorflow model, if no
+ * outputs are specified, the default outputs of the model would be used.
+ * You can inspect intermediate nodes of the model by adding them to the
+ * outputs array.
+ *
+ * @returns A single tensor if provided with a single output or no outputs
+ * are provided and there is only one default output, otherwise return a
+ * tensor array. The order of the tensor array is the same as the outputs
+ * if provided, otherwise the order of outputNodes attribute of the model.
+ *
+ * @doc {heading: 'Models', subheading: 'Classes'}
+ */
+ GraphModel.prototype.execute = function (inputs, outputs) {
+ inputs = this.normalizeInputs(inputs);
+ outputs = this.normalizeOutputs(outputs);
+ var result = this.executor.execute(inputs, outputs);
+ return result.length > 1 ? result : result[0];
+ };
+ /**
+ * Executes inference for the model for given input tensors in async
+ * fashion, use this method when your model contains control flow ops.
+ * @param inputs tensor, tensor array or tensor map of the inputs for the
+ * model, keyed by the input node names.
+ * @param outputs output node name from the Tensorflow model, if no outputs
+ * are specified, the default outputs of the model would be used. You can
+ * inspect intermediate nodes of the model by adding them to the outputs
+ * array.
+ *
+ * @returns A Promise of single tensor if provided with a single output or
+ * no outputs are provided and there is only one default output, otherwise
+ * return a tensor map.
+ *
+ * @doc {heading: 'Models', subheading: 'Classes'}
+ */
+ GraphModel.prototype.executeAsync = function (inputs, outputs) {
+ return __awaiter(this, void 0, void 0, function () {
+ var result;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ inputs = this.normalizeInputs(inputs);
+ outputs = this.normalizeOutputs(outputs);
+ return [4 /*yield*/, this.executor.executeAsync(inputs, outputs)];
+ case 1:
+ result = _a.sent();
+ return [2 /*return*/, result.length > 1 ? result : result[0]];
+ }
+ });
+ });
+ };
+ GraphModel.prototype.convertTensorMapToTensorsMap = function (map) {
+ return Object.keys(map).reduce(function (newMap, key) {
+ newMap[key] = [map[key]];
+ return newMap;
+ }, {});
+ };
+ /**
+ * Releases the memory used by the weight tensors and resourceManager.
+ *
+ * @doc {heading: 'Models', subheading: 'Classes'}
+ */
+ GraphModel.prototype.dispose = function () {
+ this.executor.dispose();
+ if (this.initializer) {
+ this.initializer.dispose();
+ }
+ this.resourceManager.dispose();
+ };
+ return GraphModel;
+ }());
+ /**
+ * Load a graph model given a URL to the model definition.
+ *
+ * Example of loading MobileNetV2 from a URL and making a prediction with a
+ * zeros input:
+ *
+ * ```js
+ * const modelUrl =
+ * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
+ * const model = await tf.loadGraphModel(modelUrl);
+ * const zeros = tf.zeros([1, 224, 224, 3]);
+ * model.predict(zeros).print();
+ * ```
+ *
+ * Example of loading MobileNetV2 from a TF Hub URL and making a prediction with
+ * a zeros input:
+ *
+ * ```js
+ * const modelUrl =
+ * 'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';
+ * const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true});
+ * const zeros = tf.zeros([1, 224, 224, 3]);
+ * model.predict(zeros).print();
+ * ```
+ * @param modelUrl The url or an `io.IOHandler` that loads the model.
+ * @param options Options for the HTTP request, which allows to send credentials
+ * and custom headers.
+ *
+ * @doc {heading: 'Models', subheading: 'Loading'}
+ */
+ function loadGraphModel(modelUrl, options) {
+ if (options === void 0) { options = {}; }
+ return __awaiter(this, void 0, void 0, function () {
+ var model;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ if (modelUrl == null) {
+ throw new Error('modelUrl in loadGraphModel() cannot be null. Please provide a url ' +
+ 'or an IOHandler that loads the model');
+ }
+ if (options == null) {
+ options = {};
+ }
+ if (options.fromTFHub) {
+ if (modelUrl.load == null) {
+ if (!modelUrl.endsWith('/')) {
+ modelUrl = modelUrl + '/';
+ }
+ modelUrl = "" + modelUrl + DEFAULT_MODEL_NAME + TFHUB_SEARCH_PARAM;
+ }
+ }
+ model = new GraphModel(modelUrl, options);
+ return [4 /*yield*/, model.load()];
+ case 1:
+ _a.sent();
+ return [2 /*return*/, model];
+ }
+ });
+ });
+ }
+
+ /** @license See the LICENSE file. */
+ // This code is auto-generated, do not modify this file!
+ var version = '3.7.0';
+
+ exports.GraphModel = GraphModel;
+ exports.deregisterOp = deregisterOp;
+ exports.loadGraphModel = loadGraphModel;
+ exports.registerOp = registerOp;
+ exports.version_converter = version;
+
+ Object.defineProperty(exports, '__esModule', { value: true });
+
+})));
+//# sourceMappingURL=tf-converter.js.map
diff --git a/thirdparty/tfjs/tf-converter.js.map b/thirdparty/tfjs/tf-converter.js.map
new file mode 100644
index 0000000..54dbe33
--- /dev/null
+++ b/thirdparty/tfjs/tf-converter.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"tf-converter.js","sources":["../src/data/compiled_api.ts","../src/operations/custom_op/register.ts","../src/operations/executors/utils.ts","../src/operations/op_list/arithmetic.ts","../src/operations/op_list/basic_math.ts","../src/operations/op_list/control.ts","../src/operations/op_list/convolution.ts","../src/operations/op_list/creation.ts","../src/operations/op_list/dynamic.ts","../src/operations/op_list/evaluation.ts","../src/operations/op_list/graph.ts","../src/operations/op_list/hash_table.ts","../src/operations/op_list/image.ts","../src/operations/op_list/logical.ts","../src/operations/op_list/matrices.ts","../src/operations/op_list/normalization.ts","../src/operations/op_list/reduction.ts","../src/operations/op_list/slice_join.ts","../src/operations/op_list/sparse.ts","../src/operations/op_list/spectral.ts","../src/operations/op_list/string.ts","../src/operations/op_list/transformation.ts","../src/operations/operation_mapper.ts","../src/operations/custom_op/node_value_impl.ts","../src/operations/executors/arithmetic_executor.ts","../src/operations/executors/basic_math_executor.ts","../src/executor/tensor_utils.ts","../src/executor/tensor_array.ts","../src/executor/tensor_list.ts","../src/operations/executors/control_executor.ts","../src/operations/executors/convolution_executor.ts","../src/operations/executors/creation_executor.ts","../src/operations/executors/dynamic_executor.ts","../src/operations/executors/evaluation_executor.ts","../src/operations/executors/graph_executor.ts","../src/executor/hash_table.ts","../src/operations/executors/hash_table_executor.ts","../src/operations/executors/image_executor.ts","../src/operations/executors/logical_executor.ts","../src/operations/executors/matrices_executor.ts","../src/operations/executors/normalization_executor.ts","../src/operations/executors/reduction_executor.ts","../src/operations/executors/slice_join_executor.ts","../src/operations/executors/sparse_executor.ts","../src/operations/executors/spectral_executor.ts","../src/operations/executors/string_executor.ts","../src/operations/executors/transformation_executor.ts","../src/operations/operation_executor.ts","../src/executor/execution_context.ts","../src/executor/model_analysis.ts","../src/executor/graph_executor.ts","../src/executor/resource_manager.ts","../src/executor/graph_model.ts","../src/version.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * =============================================================================\n */\n\n/* tslint:disable */\n\n/** Properties of an Any. */\nexport declare interface IAny {\n /** Any typeUrl */\n typeUrl?: (string|null);\n\n /** Any value */\n value?: (Uint8Array|null);\n}\n\n/** DataType enum. */\nexport enum DataType {\n 'DT_INVALID' = 0,\n 'DT_FLOAT' = 1,\n 'DT_DOUBLE' = 2,\n 'DT_INT32' = 3,\n 'DT_UINT8' = 4,\n 'DT_INT16' = 5,\n 'DT_INT8' = 6,\n 'DT_STRING' = 7,\n 'DT_COMPLEX64' = 8,\n 'DT_INT64' = 9,\n 'DT_BOOL' = 10,\n 'DT_QINT8' = 11,\n 'DT_QUINT8' = 12,\n 'DT_QINT32' = 13,\n 'DT_BFLOAT16' = 14,\n 'DT_FLOAT_REF' = 101,\n 'DT_DOUBLE_REF' = 102,\n 'DT_INT32_REF' = 103,\n 'DT_UINT8_REF' = 104,\n 'DT_INT16_REF' = 105,\n 'DT_INT8_REF' = 106,\n 'DT_STRING_REF' = 107,\n 'DT_COMPLEX64_REF' = 108,\n 'DT_INT64_REF' = 109,\n 'DT_BOOL_REF' = 110,\n 'DT_QINT8_REF' = 111,\n 'DT_QUINT8_REF' = 112,\n 'DT_QINT32_REF' = 113,\n 'DT_BFLOAT16_REF' = 114\n}\n\n/** Properties of a TensorShape. */\nexport declare interface ITensorShape {\n /** TensorShape dim */\n dim?: (TensorShape.IDim[]|null);\n\n /** TensorShape unknownRank */\n unknownRank?: (boolean|null);\n}\n\nexport namespace TensorShape {\n /** Properties of a Dim. */\n export declare interface IDim {\n /** Dim size */\n size?: (number|string|null);\n\n /** Dim name */\n name?: (string|null);\n }\n}\n\n/** Properties of a Tensor. */\nexport declare interface ITensor {\n /** Tensor dtype */\n dtype?: (DataType|null);\n\n /** Tensor tensorShape */\n tensorShape?: (ITensorShape|null);\n\n /** Tensor versionNumber */\n versionNumber?: (number|null);\n\n /** Tensor tensorContent */\n tensorContent?: (Uint8Array|null);\n\n /** Tensor floatVal */\n floatVal?: (number[]|null);\n\n /** Tensor doubleVal */\n doubleVal?: (number[]|null);\n\n /** Tensor intVal */\n intVal?: (number[]|null);\n\n /** Tensor stringVal */\n stringVal?: (Uint8Array[]|null);\n\n /** Tensor scomplexVal */\n scomplexVal?: (number[]|null);\n\n /** Tensor int64Val */\n int64Val?: ((number | string)[]|null);\n\n /** Tensor boolVal */\n boolVal?: (boolean[]|null);\n\n /** Tensor uint32Val */\n uint32Val?: (number[]|null);\n\n /** Tensor uint64Val */\n uint64Val?: ((number | string)[]|null);\n}\n\n/** Properties of an AttrValue. */\nexport declare interface IAttrValue {\n /** AttrValue list */\n list?: (AttrValue.IListValue|null);\n\n /** AttrValue s */\n s?: (string|null);\n\n /** AttrValue i */\n i?: (number|string|null);\n\n /** AttrValue f */\n f?: (number|null);\n\n /** AttrValue b */\n b?: (boolean|null);\n\n /** AttrValue type */\n type?: (DataType|null);\n\n /** AttrValue shape */\n shape?: (ITensorShape|null);\n\n /** AttrValue tensor */\n tensor?: (ITensor|null);\n\n /** AttrValue placeholder */\n placeholder?: (string|null);\n\n /** AttrValue func */\n func?: (INameAttrList|null);\n}\n\nexport namespace AttrValue {\n /** Properties of a ListValue. */\n export declare interface IListValue {\n /** ListValue s */\n s?: (string[]|null);\n\n /** ListValue i */\n i?: ((number | string)[]|null);\n\n /** ListValue f */\n f?: (number[]|null);\n\n /** ListValue b */\n b?: (boolean[]|null);\n\n /** ListValue type */\n type?: (DataType[]|null);\n\n /** ListValue shape */\n shape?: (ITensorShape[]|null);\n\n /** ListValue tensor */\n tensor?: (ITensor[]|null);\n\n /** ListValue func */\n func?: (INameAttrList[]|null);\n }\n}\n\n/** Properties of a NameAttrList. */\nexport declare interface INameAttrList {\n /** NameAttrList name */\n name?: (string|null);\n\n /** NameAttrList attr */\n attr?: ({[k: string]: IAttrValue}|null);\n}\n\n/** Properties of a NodeDef. */\nexport declare interface INodeDef {\n /** NodeDef name */\n name?: (string|null);\n\n /** NodeDef op */\n op?: (string|null);\n\n /** NodeDef input */\n input?: (string[]|null);\n\n /** NodeDef device */\n device?: (string|null);\n\n /** NodeDef attr */\n attr?: ({[k: string]: IAttrValue}|null);\n}\n\n/** Properties of a VersionDef. */\nexport declare interface IVersionDef {\n /** VersionDef producer */\n producer?: (number|null);\n\n /** VersionDef minConsumer */\n minConsumer?: (number|null);\n\n /** VersionDef badConsumers */\n badConsumers?: (number[]|null);\n}\n\n/** Properties of a GraphDef. */\nexport declare interface IGraphDef {\n /** GraphDef node */\n node?: (INodeDef[]|null);\n\n /** GraphDef versions */\n versions?: (IVersionDef|null);\n\n /** GraphDef library */\n library?: (IFunctionDefLibrary|null);\n}\n\n/** Properties of a CollectionDef. */\nexport declare interface ICollectionDef {\n /** CollectionDef nodeList */\n nodeList?: (CollectionDef.INodeList|null);\n\n /** CollectionDef bytesList */\n bytesList?: (CollectionDef.IBytesList|null);\n\n /** CollectionDef int64List */\n int64List?: (CollectionDef.IInt64List|null);\n\n /** CollectionDef floatList */\n floatList?: (CollectionDef.IFloatList|null);\n\n /** CollectionDef anyList */\n anyList?: (CollectionDef.IAnyList|null);\n}\n\nexport namespace CollectionDef {\n /** Properties of a NodeList. */\n export declare interface INodeList {\n /** NodeList value */\n value?: (string[]|null);\n }\n\n /** Properties of a BytesList. */\n export declare interface IBytesList {\n /** BytesList value */\n value?: (Uint8Array[]|null);\n }\n\n /** Properties of an Int64List. */\n export declare interface IInt64List {\n /** Int64List value */\n value?: ((number | string)[]|null);\n }\n\n /** Properties of a FloatList. */\n export declare interface IFloatList {\n /** FloatList value */\n value?: (number[]|null);\n }\n\n /** Properties of an AnyList. */\n export declare interface IAnyList {\n /** AnyList value */\n value?: (IAny[]|null);\n }\n}\n\n/** Properties of a SaverDef. */\nexport declare interface ISaverDef {\n /** SaverDef filenameTensorName */\n filenameTensorName?: (string|null);\n\n /** SaverDef saveTensorName */\n saveTensorName?: (string|null);\n\n /** SaverDef restoreOpName */\n restoreOpName?: (string|null);\n\n /** SaverDef maxToKeep */\n maxToKeep?: (number|null);\n\n /** SaverDef sharded */\n sharded?: (boolean|null);\n\n /** SaverDef keepCheckpointEveryNHours */\n keepCheckpointEveryNHours?: (number|null);\n\n /** SaverDef version */\n version?: (SaverDef.CheckpointFormatVersion|null);\n}\n\nexport namespace SaverDef {\n /** CheckpointFormatVersion enum. */\n export enum CheckpointFormatVersion {'LEGACY' = 0, 'V1' = 1, 'V2' = 2}\n}\n\n/** Properties of a TensorInfo. */\nexport declare interface ITensorInfo {\n /** TensorInfo name */\n name?: (string|null);\n\n /** TensorInfo cooSparse */\n cooSparse?: (TensorInfo.ICooSparse|null);\n\n /** TensorInfo dtype */\n dtype?: (DataType|null);\n\n /** TensorInfo tensorShape */\n tensorShape?: (ITensorShape|null);\n}\n\nexport namespace TensorInfo {\n /** Properties of a CooSparse. */\n export declare interface ICooSparse {\n /** CooSparse valuesTensorName */\n valuesTensorName?: (string|null);\n\n /** CooSparse indicesTensorName */\n indicesTensorName?: (string|null);\n\n /** CooSparse denseShapeTensorName */\n denseShapeTensorName?: (string|null);\n }\n}\n\n/** Properties of a SignatureDef. */\nexport declare interface ISignatureDef {\n /** SignatureDef inputs */\n inputs?: ({[k: string]: ITensorInfo}|null);\n\n /** SignatureDef outputs */\n outputs?: ({[k: string]: ITensorInfo}|null);\n\n /** SignatureDef methodName */\n methodName?: (string|null);\n}\n\n/** Properties of an AssetFileDef. */\nexport declare interface IAssetFileDef {\n /** AssetFileDef tensorInfo */\n tensorInfo?: (ITensorInfo|null);\n\n /** AssetFileDef filename */\n filename?: (string|null);\n}\n\n/** Properties of an OpDef. */\nexport declare interface IOpDef {\n /** OpDef name */\n name?: (string|null);\n\n /** OpDef inputArg */\n inputArg?: (OpDef.IArgDef[]|null);\n\n /** OpDef outputArg */\n outputArg?: (OpDef.IArgDef[]|null);\n\n /** OpDef attr */\n attr?: (OpDef.IAttrDef[]|null);\n\n /** OpDef deprecation */\n deprecation?: (OpDef.IOpDeprecation|null);\n\n /** OpDef summary */\n summary?: (string|null);\n\n /** OpDef description */\n description?: (string|null);\n\n /** OpDef isCommutative */\n isCommutative?: (boolean|null);\n\n /** OpDef isAggregate */\n isAggregate?: (boolean|null);\n\n /** OpDef isStateful */\n isStateful?: (boolean|null);\n\n /** OpDef allowsUninitializedInput */\n allowsUninitializedInput?: (boolean|null);\n}\n\nexport namespace OpDef {\n /** Properties of an ArgDef. */\n export declare interface IArgDef {\n /** ArgDef name */\n name?: (string|null);\n\n /** ArgDef description */\n description?: (string|null);\n\n /** ArgDef type */\n type?: (DataType|null);\n\n /** ArgDef typeAttr */\n typeAttr?: (string|null);\n\n /** ArgDef numberAttr */\n numberAttr?: (string|null);\n\n /** ArgDef typeListAttr */\n typeListAttr?: (string|null);\n\n /** ArgDef isRef */\n isRef?: (boolean|null);\n }\n\n /** Properties of an AttrDef. */\n export declare interface IAttrDef {\n /** AttrDef name */\n name?: (string|null);\n\n /** AttrDef type */\n type?: (string|null);\n\n /** AttrDef defaultValue */\n defaultValue?: (IAttrValue|null);\n\n /** AttrDef description */\n description?: (string|null);\n\n /** AttrDef hasMinimum */\n hasMinimum?: (boolean|null);\n\n /** AttrDef minimum */\n minimum?: (number|string|null);\n\n /** AttrDef allowedValues */\n allowedValues?: (IAttrValue|null);\n }\n\n /** Properties of an OpDeprecation. */\n export declare interface IOpDeprecation {\n /** OpDeprecation version */\n version?: (number|null);\n\n /** OpDeprecation explanation */\n explanation?: (string|null);\n }\n}\n\n/** Properties of an OpList. */\nexport declare interface IOpList {\n /** OpList op */\n op?: (IOpDef[]|null);\n}\n\n/** Properties of a MetaGraphDef. */\nexport declare interface IMetaGraphDef {\n /** MetaGraphDef metaInfoDef */\n metaInfoDef?: (MetaGraphDef.IMetaInfoDef|null);\n\n /** MetaGraphDef graphDef */\n graphDef?: (IGraphDef|null);\n\n /** MetaGraphDef saverDef */\n saverDef?: (ISaverDef|null);\n\n /** MetaGraphDef collectionDef */\n collectionDef?: ({[k: string]: ICollectionDef}|null);\n\n /** MetaGraphDef signatureDef */\n signatureDef?: ({[k: string]: ISignatureDef}|null);\n\n /** MetaGraphDef assetFileDef */\n assetFileDef?: (IAssetFileDef[]|null);\n}\n\nexport namespace MetaGraphDef {\n /** Properties of a MetaInfoDef. */\n export declare interface IMetaInfoDef {\n /** MetaInfoDef metaGraphVersion */\n metaGraphVersion?: (string|null);\n\n /** MetaInfoDef strippedOpList */\n strippedOpList?: (IOpList|null);\n\n /** MetaInfoDef anyInfo */\n anyInfo?: (IAny|null);\n\n /** MetaInfoDef tags */\n tags?: (string[]|null);\n\n /** MetaInfoDef tensorflowVersion */\n tensorflowVersion?: (string|null);\n\n /** MetaInfoDef tensorflowGitVersion */\n tensorflowGitVersion?: (string|null);\n }\n}\n\n/** Properties of a SavedModel. */\nexport declare interface ISavedModel {\n /** SavedModel savedModelSchemaVersion */\n savedModelSchemaVersion?: (number|string|null);\n\n /** SavedModel metaGraphs */\n metaGraphs?: (IMetaGraphDef[]|null);\n}\n\n/** Properties of a FunctionDefLibrary. */\nexport declare interface IFunctionDefLibrary {\n /** FunctionDefLibrary function */\n 'function'?: (IFunctionDef[]|null);\n\n /** FunctionDefLibrary gradient */\n gradient?: (IGradientDef[]|null);\n}\n\n/** Properties of a FunctionDef. */\nexport declare interface IFunctionDef {\n /** FunctionDef signature */\n signature?: (IOpDef|null);\n\n /** FunctionDef attr */\n attr?: ({[k: string]: IAttrValue}|null);\n\n /** FunctionDef nodeDef */\n nodeDef?: (INodeDef[]|null);\n\n /** FunctionDef ret */\n ret?: ({[k: string]: string}|null);\n}\n\n/** Properties of a GradientDef. */\nexport declare interface IGradientDef {\n /** GradientDef functionName */\n functionName?: (string|null);\n\n /** GradientDef gradientFunc */\n gradientFunc?: (string|null);\n}\n","\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpExecutor, OpMapper} from '../types';\n\nconst CUSTOM_OPS: {[key: string]: OpMapper} = {};\n\n/**\n * Register an Op for graph model executor. This allow you to register\n * TensorFlow custom op or override existing op.\n *\n * Here is an example of registering a new MatMul Op.\n * ```js\n * const customMatmul = (node) =>\n * tf.matMul(\n * node.inputs[0], node.inputs[1],\n * node.attrs['transpose_a'], node.attrs['transpose_b']);\n *\n * tf.registerOp('MatMul', customMatmul);\n * ```\n * The inputs and attrs of the node object is based on the TensorFlow op\n * registry.\n *\n * @param name The Tensorflow Op name.\n * @param opFunc An op function which is called with the current graph node\n * during execution and needs to return a tensor or a list of tensors. The node\n * has the following attributes:\n * - attr: A map from attribute name to its value\n * - inputs: A list of input tensors\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function registerOp(name: string, opFunc: OpExecutor) {\n const opMapper: OpMapper = {\n tfOpName: name,\n category: 'custom',\n inputs: [],\n attrs: [],\n customExecutor: opFunc\n };\n\n CUSTOM_OPS[name] = opMapper;\n}\n\n/**\n * Retrieve the OpMapper object for the registered op.\n *\n * @param name The Tensorflow Op name.\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function getRegisteredOp(name: string): OpMapper {\n return CUSTOM_OPS[name];\n}\n\n/**\n * Deregister the Op for graph model executor.\n *\n * @param name The Tensorflow Op name.\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function deregisterOp(name: string) {\n delete CUSTOM_OPS[name];\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {clone, Tensor, util} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {ResourceManager} from '../../executor/resource_manager';\nimport {Node, ValueType} from '../types';\n\nexport function getParamValue(\n paramName: string, node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, resourceManager?: ResourceManager): ValueType {\n const inputParam = node.inputParams[paramName];\n if (inputParam && inputParam.inputIndexStart !== undefined) {\n const start = inputParam.inputIndexStart;\n const end = inputParam.inputIndexEnd === 0 ?\n undefined :\n (inputParam.inputIndexEnd === undefined ? start + 1 :\n inputParam.inputIndexEnd);\n if (inputParam.type === 'tensor') {\n return getTensor(\n node.inputNames[inputParam.inputIndexStart], tensorMap, context,\n resourceManager);\n }\n if (inputParam.type === 'tensors') {\n const inputs = node.inputNames.slice(start, end);\n\n return inputs.map(\n name => getTensor(name, tensorMap, context, resourceManager));\n }\n const tensor = getTensor(\n node.inputNames.slice(start)[0], tensorMap, context, resourceManager);\n const data = tensor.dataSync();\n return inputParam.type === 'number' ?\n data[0] :\n util.toNestedArray(tensor.shape, data);\n }\n const attrParam = node.attrParams[paramName];\n return attrParam && attrParam.value;\n}\n\n/**\n * Retrieve the tensor from tensorsMap based on input name.\n * @param name Node input name\n * @param tensorsMap Tensors map keyed by the node\n * @param context contains tensors and information for running the current node.\n * @param resourceManager Optional. Contains global resources of the model.\n */\nexport function getTensor(\n name: string, tensorsMap: NamedTensorsMap, context: ExecutionContext,\n resourceManager?: ResourceManager): Tensor {\n const [nodeName, index] = parseNodeName(name);\n\n if (resourceManager != null) {\n const tensor = resourceManager.getHashTableHandleByName(nodeName);\n if (tensor != null) {\n return tensor;\n }\n }\n\n const contextId = context.currentContextIds.find(contextId => {\n return !!tensorsMap[getNodeNameWithContextId(nodeName, contextId)];\n });\n\n return contextId !== undefined ?\n tensorsMap[getNodeNameWithContextId(nodeName, contextId)][index] :\n undefined;\n}\n\n/**\n * Retrieve the tensors based on input name for current context.\n * @param name Node input name\n * @param tensorsMap Tensors map keyed by the node\n */\nexport function getTensorsForCurrentContenxt(\n name: string, tensorsMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] {\n return tensorsMap[getNodeNameWithContextId(name, context.currentContextId)];\n}\n\n/**\n * Returns the node name, outputName and index from the Node input name.\n * @param inputName The input name of the node, in format of\n * node_name:output_index, i.e. MatMul:0, if the output_index is not set, it is\n * default to 0.\n * If the input name contains output name i.e. StringSplit:indices:0, it will\n * return ['StringSplit', 0, 'indices'].\n */\nexport function getNodeNameAndIndex(\n inputName: string, context?: ExecutionContext): [string, number, string] {\n const [nodeName, index, outputName] = parseNodeName(inputName);\n\n return [\n getNodeNameWithContextId(nodeName, context && context.currentContextId),\n index, outputName\n ];\n}\n\nfunction getNodeNameWithContextId(name: string, contextId?: string): string {\n return !!contextId ? `${name}-${contextId}` : name;\n}\n\nexport function parseNodeName(name: string): [string, number, string] {\n const parts = name.split(':');\n if (parts.length === 1) {\n return [name, 0, undefined];\n }\n\n const nodeName = parts[0];\n const outputName = parts.length === 3 ? parts[1] : undefined;\n const index = Number(parts[parts.length - 1]);\n return [nodeName, index, outputName];\n}\n\nexport function split(arr: number[], size: number) {\n const res = [];\n for (let i = 0; i < arr.length; i += size) {\n res.push(arr.slice(i, i + size));\n }\n return res;\n}\nexport function getPadding(\n node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): ValueType {\n let pad = getParamValue('pad', node, tensorMap, context);\n if (pad === 'explicit') {\n // This is 1d array, we need to convert it to 2d array\n pad = getParamValue('explicitPaddings', node, tensorMap, context);\n const explicitPadding: [\n [number, number], [number, number], [number, number], [number, number]\n ] = [[0, 0], [0, 0], [0, 0], [0, 0]];\n for (let i = 0; i < 4; i++) {\n explicitPadding[i][0] = (pad as number[])[i * 2];\n explicitPadding[i][1] = (pad as number[])[i * 2 + 1];\n }\n return explicitPadding;\n }\n return pad;\n}\n\n/**\n * Reuse the tensor if it is marked as keep, otherwise clone the tensor to\n * avoid disposal. This is important for TensorArray and TensorList ops, since\n * internally they use a tensor as the id for TensorArray and TensorList, and\n * to simplify lookup, they also use Tensor.id as the key to the internal map.\n * These id tensors have been marked as kept in the backend, we need avoid clone\n * them in order to create new Tensor.id.\n * @param tensor\n */\nexport function cloneTensor(tensor: Tensor): Tensor {\n return tensor.kept ? tensor : clone(tensor);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Add',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'AddV2',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'AddN',\n 'category': 'arithmetic',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors'}]\n },\n {\n 'tfOpName': 'BiasAdd',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Sub',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'RealDiv',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Div',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'DivNoNan',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'FloorDiv',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Mul',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Maximum',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Minimum',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Pow',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'SquaredDifference',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Mod',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'FloorMod',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Abs',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Acos',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Asin',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Atan',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Atan2',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'y', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Ceil',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'ClipByValue',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'clipValueMin', 'type': 'number'},\n {'start': 2, 'name': 'clipValueMax', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Complex',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'real', 'type': 'tensor'},\n {'start': 1, 'name': 'imag', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'ComplexAbs',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Cos',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Cosh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Elu',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Exp',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Floor',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Log',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Imag',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\n 'tfName': 'Tout',\n 'name': 'outputType',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Neg',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Real',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\n 'tfName': 'Tout',\n 'name': 'outputType',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Prelu',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'alpha', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Relu',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Relu6',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Selu',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sigmoid',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sin',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sinh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sqrt',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Rsqrt',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Square',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Tan',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Tanh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sign',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Round',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Expm1',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Log1p',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Reciprocal',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Softplus',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Asinh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Acosh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Atanh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Erf',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Prod',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axes', 'type': 'number[]'},\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool',\n 'notSupported': true\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LeakyRelu',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'alpha',\n 'name': 'alpha',\n 'type': 'number',\n 'defaultValue': 0.2\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'IsNan',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }]\n }\n];\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'EmptyTensorList',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'elementShape', 'type': 'shape'},\n {'start': 1, 'name': 'maxNumElements', 'type': 'number'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'LoopCond',\n 'category': 'control',\n 'inputs': [{'start': 0, 'name': 'pred', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'Switch',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'data', 'type': 'tensor'},\n {'start': 1, 'name': 'pred', 'type': 'tensor'}\n ]\n },\n {\n 'tfOpName': 'Merge',\n 'category': 'control',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors'}]\n },\n {\n 'tfOpName': 'Enter',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true},\n {'tfName': 'frame_name', 'name': 'frameName', 'type': 'string'},\n {'tfName': 'is_constant', 'name': 'isConstant', 'type': 'bool'}\n ]\n },\n {\n 'tfOpName': 'Exit',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'NextIteration',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'TensorArrayV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'size', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape'},\n {'tfName': 'dynamic_size', 'name': 'dynamicSize', 'type': 'bool'},\n {'tfName': 'clear_after_read', 'name': 'clearAfterRead', 'type': 'bool'},\n {\n 'tfName': 'identical_element_shapes',\n 'name': 'identicalElementShapes',\n 'type': 'bool'\n },\n {'tfName': 'tensor_array_name', 'name': 'name', 'type': 'string'}\n ]\n },\n {\n 'tfOpName': 'TensorArrayWriteV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'index', 'type': 'number'},\n {'start': 2, 'name': 'tensor', 'type': 'tensor'},\n {'start': 3, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'TensorArrayReadV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'index', 'type': 'number'},\n {'start': 2, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [{\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }]\n },\n {\n 'tfOpName': 'TensorArrayGatherV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape'}\n ]\n },\n {\n 'tfOpName': 'TensorArrayScatterV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'tensor', 'type': 'tensor'},\n {'start': 3, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorArrayConcatV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'}, {\n 'tfName': 'element_shape_except0',\n 'name': 'elementShapeExcept0',\n 'type': 'shape',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'TensorArraySplitV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'tensor', 'type': 'tensor'},\n {'start': 2, 'name': 'lengths', 'type': 'number[]'},\n {'start': 3, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorArraySizeV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'flowIn', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'TensorArrayCloseV3',\n 'category': 'control',\n 'inputs': [{'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'StatelessIf',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'cond', 'type': 'tensor'},\n {'start': 1, 'end': 0, 'name': 'args', 'type': 'tensors'}\n ],\n 'attrs': [\n {'tfName': 'then_branch', 'name': 'thenBranch', 'type': 'func'},\n {'tfName': 'else_branch', 'name': 'elseBranch', 'type': 'func'}\n ]\n },\n {\n 'tfOpName': 'If',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'cond', 'type': 'tensor'},\n {'start': 1, 'end': 0, 'name': 'args', 'type': 'tensors'}\n ],\n 'attrs': [\n {'tfName': 'then_branch', 'name': 'thenBranch', 'type': 'func'},\n {'tfName': 'else_branch', 'name': 'elseBranch', 'type': 'func'}\n ]\n },\n {\n 'tfOpName': 'StatelessWhile',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'end': 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'cond', 'name': 'cond', 'type': 'func'},\n {'tfName': 'body', 'name': 'body', 'type': 'func'}\n ]\n },\n {\n 'tfOpName': 'While',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'end': 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'cond', 'name': 'cond', 'type': 'func'},\n {'tfName': 'body', 'name': 'body', 'type': 'func'}\n ]\n },\n {\n 'tfOpName': 'TensorListScatter',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'elementShape', 'type': 'shape'}\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListScatterV2',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'elementShape', 'type': 'shape'},\n {'start': 3, 'name': 'numElements', 'type': 'number'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListGather',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'elementShape', 'type': 'shape'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListGetItem',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'index', 'type': 'number'},\n {'start': 2, 'name': 'elementShape', 'type': 'shape'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListSetItem',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'index', 'type': 'number'},\n {'start': 2, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListReserve',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'elementShape', 'type': 'shape'},\n {'start': 1, 'name': 'numElements', 'type': 'number'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListFromTensor',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n {'start': 1, 'name': 'elementShape', 'type': 'shape'}\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListStack',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'elementShape', 'type': 'shape'},\n ],\n 'attrs': [\n {'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'},\n {'tfName': 'num_elements', 'name': 'numElements', 'type': 'dtype'}\n ]\n },\n {\n 'tfOpName': 'TensorListSplit',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n {'start': 1, 'name': 'elementShape', 'type': 'shape'},\n {'start': 2, 'name': 'lengths', 'type': 'number[]'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListConcat',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape'},\n {'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}\n ]\n },\n {\n 'tfOpName': 'TensorListPopBack',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'elementShape', 'type': 'shape'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListPushBack',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}\n ]\n }\n];\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'AvgPool',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'MaxPool',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'}, {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': [],\n 'notSupported': true\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'MaxPoolWithArgmax',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'},\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'}, {\n 'tfName': 'include_batch_in_index',\n 'name': 'includeBatchInIndex',\n 'type': 'bool'\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'AvgPool3D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'MaxPool3D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Conv1D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'stride', 'name': 'stride', 'type': 'number'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NWC'\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\n 'tfName': 'dilation',\n 'name': 'dilation',\n 'type': 'number',\n 'defaultValue': 1\n }\n ]\n },\n {\n 'tfOpName': 'Conv2D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true},\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'},\n {'tfName': 'useCudnnOnGpu', 'name': 'useCudnnOnGpu', 'type': 'bool'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': '_FusedConv2D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n {'start': 2, end: 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'num_args', 'name': 'numArgs', 'type': 'number'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true},\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'use_cudnn_on_gpu',\n 'name': 'useCudnnOnGpu',\n 'type': 'bool',\n 'defaultValue': true\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]',\n 'defaultValue': [1, 1, 1, 1]\n },\n {\n 'tfName': 'fused_ops',\n 'name': 'fusedOps',\n 'type': 'string[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.0001\n },\n {\n 'tfName': 'leakyrelu_alpha',\n 'name': 'leakyreluAlpha',\n 'type': 'number'\n }\n ]\n },\n {\n 'tfOpName': 'Conv2DBackpropInput',\n 'category': 'convolution',\n 'inputs': [\n {'start': 2, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n {'start': 0, 'name': 'outputShape', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'DepthwiseConv2d',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'input', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'DepthwiseConv2dNative',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'input', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n },\n {'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'FusedDepthwiseConv2dNative',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n {'start': 2, end: 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'num_args', 'name': 'numArgs', 'type': 'number'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true},\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {\n 'tfName': 'dilations',\n 'name': 'dilations',\n 'type': 'number[]',\n 'defaultValue': [1, 1, 1, 1]\n },\n {\n 'tfName': 'fused_ops',\n 'name': 'fusedOps',\n 'type': 'string[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': []\n }\n ]\n },\n {\n 'tfOpName': 'Conv3D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]'}\n ],\n },\n {\n 'tfOpName': 'Dilation2D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'rates', 'name': 'dilations', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}\n ]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Fill',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\n {'start': 1, 'name': 'value', 'type': 'number'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'LinSpace',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'start', 'type': 'number'},\n {'start': 1, 'name': 'stop', 'type': 'number'},\n {'start': 2, 'name': 'num', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'OneHot',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'indices', 'type': 'tensor'},\n {'start': 1, 'name': 'depth', 'type': 'number'},\n {'start': 2, 'name': 'onValue', 'type': 'number', 'defaultValue': 1},\n {'start': 3, 'name': 'offValue', 'type': 'number', 'defaultValue': 0},\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'name': 'axis',\n 'type': 'number',\n 'notSupported': true\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Ones',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'OnesLike',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'RandomUniform',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\n ],\n 'attrs': [\n {\n 'tfName': 'minval',\n 'name': 'minval',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'maxval',\n 'name': 'maxval',\n 'type': 'number',\n 'defaultValue': 1\n },\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'seed', 'name': 'seed', 'type': 'number', 'defaultValue': 0}, {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {'tfName': 'T', 'name': 'T', 'type': 'number', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Range',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'start', 'type': 'number'},\n {'start': 1, 'name': 'stop', 'type': 'number'},\n {'start': 2, 'name': 'step', 'type': 'number', 'defaultValue': 0},\n ],\n 'attrs': [{'tfName': 'Tidx', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TruncatedNormal',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\n ],\n 'attrs': [\n {\n 'tfName': 'means',\n 'name': 'mean',\n 'type': 'number',\n 'defaultValue': 0.0\n },\n {\n 'tfName': 'stddev',\n 'name': 'stdDev',\n 'type': 'number',\n 'defaultValue': 1.0\n },\n {'tfName': 'seed', 'name': 'seed', 'type': 'number'}, {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'T', 'name': 'T', 'type': 'number', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Zeros',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'ZerosLike',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'Multinomial',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'logits', 'type': 'tensor'},\n {'start': 1, 'name': 'numSamples', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'seed', 'name': 'seed', 'type': 'number'},\n {'tfName': 'seed2', 'name': 'seed2', 'type': 'number'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'output_dtype', 'name': 'output_dtype', 'type': 'dtype'}\n ]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'NonMaxSuppressionV2',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'boxes', 'type': 'tensor'},\n {'start': 1, 'name': 'scores', 'type': 'tensor'},\n {'start': 2, 'name': 'maxOutputSize', 'type': 'number'},\n {'start': 3, 'name': 'iouThreshold', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV3',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'boxes', 'type': 'tensor'},\n {'start': 1, 'name': 'scores', 'type': 'tensor'},\n {'start': 2, 'name': 'maxOutputSize', 'type': 'number'},\n {'start': 3, 'name': 'iouThreshold', 'type': 'number'},\n {'start': 4, 'name': 'scoreThreshold', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV4',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'boxes', 'type': 'tensor'},\n {'start': 1, 'name': 'scores', 'type': 'tensor'},\n {'start': 2, 'name': 'maxOutputSize', 'type': 'number'},\n {'start': 3, 'name': 'iouThreshold', 'type': 'number'},\n {'start': 4, 'name': 'scoreThreshold', 'type': 'number'}\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\n 'tfName': 'T_threshold',\n 'name': 'threshold',\n 'type': 'dtype',\n 'notSupported': true\n },\n {\n 'tfName': 'pad_to_max_output_size',\n 'name': 'padToMaxOutputSize',\n 'type': 'bool'\n }\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV5',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'boxes', 'type': 'tensor'},\n {'start': 1, 'name': 'scores', 'type': 'tensor'},\n {'start': 2, 'name': 'maxOutputSize', 'type': 'number'},\n {'start': 3, 'name': 'iouThreshold', 'type': 'number'},\n {'start': 4, 'name': 'scoreThreshold', 'type': 'number'},\n {'start': 5, 'name': 'softNmsSigma', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'Where',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'condition', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'ListDiff',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'y', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'TopKV2',\n 'category': 'evaluation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'k', 'type': 'number'},\n ],\n 'attrs': [{'tfName': 'sorted', 'name': 'sorted', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Unique',\n 'category': 'evaluation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n },\n {\n 'tfOpName': 'UniqueV2',\n 'category': 'evaluation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'},\n ],\n },\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'PlaceholderWithDefault',\n 'category': 'graph',\n 'inputs': [\n {'start': 0, 'name': 'default', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'shape', 'name': 'shape', 'type': 'shape'},\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'}\n ]\n },\n {\n 'tfOpName': 'Placeholder',\n 'category': 'graph',\n 'attrs': [\n {'tfName': 'shape', 'name': 'shape', 'type': 'shape'},\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'}\n ]\n },\n {'tfOpName': 'Const', 'category': 'graph'}, {\n 'tfOpName': 'Identity',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'IdentityN',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'x', 'type': 'tensors'}]\n },\n {\n 'tfOpName': 'Snapshot',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'Rank',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'Size',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'Shape',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'ShapeN',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'x', 'type': 'tensors'}]\n },\n {\n 'tfOpName': 'Print',\n 'category': 'graph',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'data', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'message', 'name': 'message', 'type': 'string'}, {\n 'tfName': 'first_n',\n 'name': 'firstN',\n 'type': 'number',\n 'notSupported': true\n },\n {\n 'tfName': 'summarize',\n 'name': 'summarize',\n 'type': 'number',\n 'defaultValue': 3\n }\n ]\n },\n {'tfOpName': 'NoOp', 'category': 'graph', 'inputs': []}, {\n 'tfOpName': 'StopGradient',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'FakeQuantWithMinMaxVars',\n 'category': 'graph',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'min', 'name': 'min', 'type': 'number'},\n {'tfName': 'max', 'name': 'max', 'type': 'number'}\n ]\n }\n];\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'HashTable',\n 'category': 'hash_table',\n 'inputs': [],\n 'attrs': [\n {'tfName': 'shared_name', 'name': 'sharedName', 'type': 'string'},\n {\n 'tfName': 'use_node_name_sharing',\n 'name': 'useNodeNameSharing',\n 'type': 'bool'\n },\n {'tfName': 'key_dtype', 'name': 'keyDType', 'type': 'dtype'},\n {'tfName': 'value_dtype', 'name': 'valueDType', 'type': 'dtype'},\n ]\n },\n {\n 'tfOpName': 'HashTableV2',\n 'category': 'hash_table',\n 'inputs': [],\n 'attrs': [\n {'tfName': 'shared_name', 'name': 'sharedName', 'type': 'string'},\n {\n 'tfName': 'use_node_name_sharing',\n 'name': 'useNodeNameSharing',\n 'type': 'bool'\n },\n {'tfName': 'key_dtype', 'name': 'keyDType', 'type': 'dtype'},\n {'tfName': 'value_dtype', 'name': 'valueDType', 'type': 'dtype'},\n ]\n },\n {\n 'tfOpName': 'LookupTableImport',\n 'category': 'hash_table',\n 'inputs': [\n {'start': 0, 'name': 'tableHandle', 'type': 'tensor'},\n {'start': 1, 'name': 'keys', 'type': 'tensor'},\n {'start': 2, 'name': 'values', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true}, {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableImportV2',\n 'category': 'hash_table',\n 'inputs': [\n {'start': 0, 'name': 'tableHandle', 'type': 'tensor'},\n {'start': 1, 'name': 'keys', 'type': 'tensor'},\n {'start': 2, 'name': 'values', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true}, {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableFind',\n 'category': 'hash_table',\n 'inputs': [\n {'start': 0, 'name': 'tableHandle', 'type': 'tensor'},\n {'start': 1, 'name': 'keys', 'type': 'tensor'},\n {'start': 2, 'name': 'defaultValue', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true}, {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableFindV2',\n 'category': 'hash_table',\n 'inputs': [\n {'start': 0, 'name': 'tableHandle', 'type': 'tensor'},\n {'start': 1, 'name': 'keys', 'type': 'tensor'},\n {'start': 2, 'name': 'defaultValue', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true}, {\n 'tfName': 'Tout',\n 'name': 'tOut',\n 'type': 'dtype',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LookupTableSize',\n 'category': 'hash_table',\n 'inputs': [\n {'start': 0, 'name': 'tableHandle', 'type': 'tensor'}\n ]\n },\n {\n 'tfOpName': 'LookupTableSizeV2',\n 'category': 'hash_table',\n 'inputs': [\n {'start': 0, 'name': 'tableHandle', 'type': 'tensor'}\n ]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'ResizeBilinear',\n 'category': 'image',\n 'inputs': [\n {'start': 0, 'name': 'images', 'type': 'tensor'},\n {'start': 1, 'name': 'size', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'align_corners', 'name': 'alignCorners', 'type': 'bool'}, {\n 'tfName': 'half_pixel_centers',\n 'name': 'halfPixelCenters',\n 'type': 'bool'\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'ResizeNearestNeighbor',\n 'category': 'image',\n 'inputs': [\n {'start': 0, 'name': 'images', 'type': 'tensor'},\n {'start': 1, 'name': 'size', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'align_corners', 'name': 'alignCorners', 'type': 'bool'}, {\n 'tfName': 'half_pixel_centers',\n 'name': 'halfPixelCenters',\n 'type': 'bool'\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'CropAndResize',\n 'category': 'image',\n 'inputs': [\n {'start': 0, 'name': 'image', 'type': 'tensor'},\n {'start': 1, 'name': 'boxes', 'type': 'tensor'},\n {'start': 2, 'name': 'boxInd', 'type': 'tensor'},\n {'start': 3, 'name': 'cropSize', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'method', 'name': 'method', 'type': 'string'}, {\n 'tfName': 'extrapolation_value',\n 'name': 'extrapolationValue',\n 'type': 'number'\n }\n ]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Equal',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'NotEqual',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Greater',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'GreaterEqual',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Less',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LessEqual',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LogicalAnd',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LogicalNot',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LogicalOr',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Select',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'condition', 'type': 'tensor'},\n {'start': 1, 'name': 'a', 'type': 'tensor'},\n {'start': 2, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'SelectV2',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'condition', 'type': 'tensor'},\n {'start': 1, 'name': 'a', 'type': 'tensor'},\n {'start': 2, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }]\n }\n];\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': '_FusedMatMul',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n {'start': 2, end: 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'num_args', 'name': 'numArgs', 'type': 'number'}, {\n 'tfName': 'fused_ops',\n 'name': 'fusedOps',\n 'type': 'string[]',\n 'defaultValue': []\n },\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.0001\n },\n {\n 'tfName': 'transpose_a',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'transpose_b',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'MatMul',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'transpose_a',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'transpose_b',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'BatchMatMul',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'adj_x',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'adj_y',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'BatchMatMulV2',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'adj_x',\n 'name': 'transposeA',\n 'type': 'bool',\n 'defaultValue': false\n },\n {\n 'tfName': 'adj_y',\n 'name': 'transposeB',\n 'type': 'bool',\n 'defaultValue': false\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Transpose',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'perm', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Einsum',\n 'category': 'matrices',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors'}],\n 'attrs': [\n {'tfName': 'equation', 'name': 'equation', 'type': 'string'},\n {'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}\n ]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'FusedBatchNorm',\n 'category': 'normalization',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'scale', 'type': 'tensor'},\n {'start': 2, 'name': 'offset', 'type': 'tensor'},\n {'start': 3, 'name': 'mean', 'type': 'tensor'},\n {'start': 4, 'name': 'variance', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.001\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FusedBatchNormV2',\n 'category': 'normalization',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'scale', 'type': 'tensor'},\n {'start': 2, 'name': 'offset', 'type': 'tensor'},\n {'start': 3, 'name': 'mean', 'type': 'tensor'},\n {'start': 4, 'name': 'variance', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.001\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'FusedBatchNormV3',\n 'category': 'normalization',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'scale', 'type': 'tensor'},\n {'start': 2, 'name': 'offset', 'type': 'tensor'},\n {'start': 3, 'name': 'mean', 'type': 'tensor'},\n {'start': 4, 'name': 'variance', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'epsilon',\n 'name': 'epsilon',\n 'type': 'number',\n 'defaultValue': 0.001\n },\n {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'LRN',\n 'category': 'normalization',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'depth_radius',\n 'name': 'radius',\n 'type': 'number',\n 'defaultValue': 5\n },\n {'tfName': 'bias', 'name': 'bias', 'type': 'number', 'defaultValue': 1.0},\n {\n 'tfName': 'alpha',\n 'name': 'alpha',\n 'type': 'number',\n 'defaultValue': 1.0\n },\n {\n 'tfName': 'beta',\n 'name': 'beta',\n 'type': 'number',\n 'defaultValue': 0.5\n }\n ]\n },\n {\n 'tfOpName': 'Softmax',\n 'category': 'normalization',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'LogSoftmax',\n 'category': 'normalization',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'SparseToDense',\n 'category': 'normalization',\n 'inputs': [\n {'start': 0, 'name': 'sparseIndices', 'type': 'tensor'},\n {'start': 1, 'name': 'outputShape', 'type': 'number[]'},\n {'start': 2, 'name': 'sparseValues', 'type': 'tensor'},\n {'start': 3, 'name': 'defaultValue', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'defaultValue': true,\n 'notSupported': true\n }]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Bincount',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'size', 'type': 'number'},\n {'start': 2, 'name': 'weights', 'type': 'tensor'}\n ]\n },\n {\n 'tfOpName': 'DenseBincount',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'size', 'type': 'number'},\n {'start': 2, 'name': 'weights', 'type': 'tensor'}\n ],\n 'attrs':\n [{'tfName': 'binary_output', 'name': 'binaryOutput', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Max',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Mean',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Min',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Sum',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'All',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Any',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'ArgMax',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'ArgMin',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'Prod',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Cumsum',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'exclusive', 'name': 'exclusive', 'type': 'bool'},\n {'tfName': 'reverse', 'name': 'reverse', 'type': 'bool'}\n ]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'ConcatV2',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'end': -1, 'name': 'tensors', 'type': 'tensors'},\n {'start': -1, 'name': 'axis', 'type': 'number'}\n ],\n 'attrs':\n [{'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2}]\n },\n {\n 'tfOpName': 'Concat',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 1, 'end': 0, 'name': 'tensors', 'type': 'tensors'},\n {'start': 0, 'name': 'axis', 'type': 'number'}\n ],\n 'attrs': [{'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2}]\n\n },\n {\n 'tfOpName': 'GatherV2',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'},\n {'start': 2, 'name': 'axis', 'type': 'number', 'defaultValue': 0}\n ],\n 'attrs': [{\n 'tfName': 'batch_dims',\n 'name': 'batchDims',\n 'type': 'number',\n 'defaultValue': 0\n }]\n },\n {\n 'tfOpName': 'Gather',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'notSupported': true\n }]\n },\n {\n 'tfOpName': 'Reverse',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'dims', 'type': 'bool[]'}\n ]\n },\n {\n 'tfOpName': 'ReverseV2',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'Slice',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'begin', 'type': 'number[]'},\n {'start': 2, 'name': 'size', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'StridedSlice',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'begin', 'type': 'number[]'},\n {'start': 2, 'name': 'end', 'type': 'number[]'},\n {'start': 3, 'name': 'strides', 'type': 'number[]'},\n ],\n 'attrs': [\n {\n 'tfName': 'begin_mask',\n 'name': 'beginMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'end_mask',\n 'name': 'endMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'new_axis_mask',\n 'name': 'newAxisMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'ellipsis_mask',\n 'name': 'ellipsisMask',\n 'type': 'number',\n 'defaultValue': 0\n },\n {\n 'tfName': 'shrink_axis_mask',\n 'name': 'shrinkAxisMask',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Pack',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'axis', 'name': 'axis', 'type': 'number', 'defaultValue': 0}\n ]\n },\n {\n 'tfOpName': 'Unpack',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'axis', 'name': 'axis', 'type': 'number', 'defaultValue': 0}, {\n 'tfName': 'num',\n 'name': 'num',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'Tile',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'reps', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'Split',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'axis', 'type': 'number', 'defaultValue': 0},\n {'start': 1, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'num_split',\n 'name': 'numOrSizeSplits',\n 'type': 'number',\n 'defaultValue': 1\n }]\n },\n {\n 'tfOpName': 'SplitV',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'numOrSizeSplits', 'type': 'number[]'},\n {'start': 2, 'name': 'axis', 'type': 'number', 'defaultValue': 0}\n ]\n },\n {\n 'tfOpName': 'ScatterNd',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'indices', 'type': 'tensor'},\n {'start': 1, 'name': 'values', 'type': 'tensor'},\n {'start': 2, 'name': 'shape', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'GatherNd',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'}\n ]\n },\n {\n 'tfOpName': 'SparseToDense',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'sparseIndices', 'type': 'tensor'},\n {'start': 1, 'name': 'outputShape', 'type': 'number[]'},\n {'start': 2, 'name': 'sparseValues', 'type': 'tensor'},\n {'start': 3, 'name': 'defaultValue', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'defaultValue': false,\n 'notSupported': true\n }]\n }\n];\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'SparseFillEmptyRows',\n 'category': 'sparse',\n 'inputs': [\n {'start': 0, 'name': 'indices', 'type': 'tensor'},\n {'start': 1, 'name': 'values', 'type': 'tensor'},\n {'start': 2, 'name': 'denseShape', 'type': 'tensor'},\n {'start': 3, 'name': 'defaultValue', 'type': 'tensor'},\n ]\n },\n {\n 'tfOpName': 'SparseReshape',\n 'category': 'sparse',\n 'inputs': [\n {'start': 0, 'name': 'inputIndices', 'type': 'tensor'},\n {'start': 1, 'name': 'inputShape', 'type': 'tensor'},\n {'start': 2, 'name': 'newShape', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'SparseSegmentMean',\n 'category': 'sparse',\n 'inputs': [\n {'start': 0, 'name': 'data', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'},\n {'start': 2, 'name': 'segmentIds', 'type': 'tensor'},\n ]\n },\n {\n 'tfOpName': 'SparseSegmentSum',\n 'category': 'sparse',\n 'inputs': [\n {'start': 0, 'name': 'data', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'},\n {'start': 2, 'name': 'segmentIds', 'type': 'tensor'},\n ]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'FFT',\n 'category': 'spectral',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'IFFT',\n 'category': 'spectral',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'RFFT',\n 'category': 'spectral',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'}, {\n 'start': 1,\n 'name': 'fft_length',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n },\n {\n 'tfOpName': 'IRFFT',\n 'category': 'spectral',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'}, {\n 'start': 1,\n 'name': 'fft_length',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n }\n];\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'StringNGrams',\n 'category': 'string',\n 'inputs': [\n {'start': 0, 'name': 'data', 'type': 'tensor'},\n {'start': 1, 'name': 'dataSplits', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'separator', 'name': 'separator', 'type': 'string'},\n {'tfName': 'ngram_widths', 'name': 'nGramWidths', 'type': 'number[]'},\n {'tfName': 'left_pad', 'name': 'leftPad', 'type': 'string'},\n {'tfName': 'right_pad', 'name': 'rightPad', 'type': 'string'},\n {'tfName': 'pad_width', 'name': 'padWidth', 'type': 'number'}, {\n 'tfName': 'preserve_short_sequences',\n 'name': 'preserveShortSequences',\n 'type': 'bool'\n }\n ],\n 'outputs': ['ngrams', 'ngrams_splits']\n },\n {\n 'tfOpName': 'StringSplit',\n 'category': 'string',\n 'inputs': [\n {'start': 0, 'name': 'input', 'type': 'tensor'},\n {'start': 1, 'name': 'delimiter', 'type': 'tensor'},\n ],\n 'attrs': [{'tfName': 'skip_empty', 'name': 'skipEmpty', 'type': 'bool'}],\n 'outputs': ['indices', 'values', 'shape']\n },\n {\n 'tfOpName': 'StringToHashBucketFast',\n 'category': 'string',\n 'inputs': [\n {'start': 0, 'name': 'input', 'type': 'tensor'},\n ],\n 'attrs': [{'tfName': 'num_buckets', 'name': 'numBuckets', 'type': 'number'}]\n }\n];\n","import {OpMapper} from '../types';\n\n/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Cast',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'SrcT',\n 'name': 'sdtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {'tfName': 'DstT', 'name': 'dtype', 'type': 'dtype'}\n ]\n },\n {\n 'tfOpName': 'ExpandDims',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'MirrorPad',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'padding', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'mode', 'name': 'mode', 'type': 'string'}]\n },\n {\n 'tfOpName': 'Pad',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'padding', 'type': 'number[]'},\n ],\n 'attrs': [{\n 'tfName': 'constant_value',\n 'name': 'constantValue',\n 'type': 'number',\n 'defaultValue': 0\n }]\n },\n {\n 'tfOpName': 'PadV2',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'padding', 'type': 'number[]'}, {\n 'start': 2,\n 'name': 'constantValue',\n 'type': 'number',\n 'defaultValue': 0\n }\n ]\n },\n {\n 'tfOpName': 'Reshape',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'shape', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'Squeeze',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'axis',\n 'tfDeprecatedName': 'squeeze_dims',\n 'name': 'axis',\n 'type': 'number[]'\n }]\n },\n {\n 'tfOpName': 'SpaceToBatchND',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'blockShape', 'type': 'number[]'},\n {'start': 2, 'name': 'paddings', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'BatchToSpaceND',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'blockShape', 'type': 'number[]'},\n {'start': 2, 'name': 'crops', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'DepthToSpace',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'block_size', 'name': 'blockSize', 'type': 'number'},\n {'tfName': 'data_format', 'name': 'dataFormat', 'type': 'string'}\n ]\n },\n {\n 'tfOpName': 'BroadcastTo',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'shape', 'type': 'number[]'},\n ],\n 'attrs': []\n }\n];\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, env} from '@tensorflow/tfjs-core';\n\nimport * as tensorflow from '../data/compiled_api';\n\nimport {getRegisteredOp} from './custom_op/register';\nimport {getNodeNameAndIndex} from './executors/utils';\nimport * as arithmetic from './op_list/arithmetic';\nimport * as basicMath from './op_list/basic_math';\nimport * as control from './op_list/control';\nimport * as convolution from './op_list/convolution';\nimport * as creation from './op_list/creation';\nimport * as dynamic from './op_list/dynamic';\nimport * as evaluation from './op_list/evaluation';\nimport * as graph from './op_list/graph';\nimport * as hashTable from './op_list/hash_table';\nimport * as image from './op_list/image';\nimport * as logical from './op_list/logical';\nimport * as matrices from './op_list/matrices';\nimport * as normalization from './op_list/normalization';\nimport * as reduction from './op_list/reduction';\nimport * as sliceJoin from './op_list/slice_join';\nimport * as sparse from './op_list/sparse';\nimport * as spectral from './op_list/spectral';\nimport * as string from './op_list/string';\nimport * as transformation from './op_list/transformation';\nimport {Graph, InputParamValue, Node, OpMapper, ParamValue} from './types';\n\nexport class OperationMapper {\n private static _instance: OperationMapper;\n\n private opMappers: {[key: string]: OpMapper};\n\n // Singleton instance for the mapper\n public static get Instance() {\n return this._instance || (this._instance = new this());\n }\n\n // Loads the op mapping from the JSON file.\n private constructor() {\n const ops = [\n arithmetic, basicMath, control, convolution, creation, dynamic,\n evaluation, graph, hashTable, image, logical, matrices, normalization,\n reduction, sliceJoin, sparse, spectral, string, transformation\n ];\n const mappersJson: OpMapper[] = [].concat(...ops.map(op => op.json));\n\n this.opMappers = mappersJson.reduce<{[key: string]: OpMapper}>(\n (map, mapper: OpMapper) => {\n map[mapper.tfOpName] = mapper;\n return map;\n },\n {});\n }\n\n // Converts the model inference graph from Tensorflow GraphDef to local\n // representation for TensorFlow.js API\n transformGraph(\n graph: tensorflow.IGraphDef,\n signature: tensorflow.ISignatureDef = {}): Graph {\n const tfNodes = graph.node;\n const placeholders: Node[] = [];\n const weights: Node[] = [];\n const initNodes: Node[] = [];\n const nodes = tfNodes.reduce<{[key: string]: Node}>((map, node) => {\n map[node.name] = this.mapNode(node);\n if (node.op.startsWith('Placeholder')) {\n placeholders.push(map[node.name]);\n } else if (node.op === 'Const') {\n weights.push(map[node.name]);\n } else if (node.input == null || node.input.length === 0) {\n initNodes.push(map[node.name]);\n }\n return map;\n }, {});\n\n let inputs: Node[] = [];\n const outputs: Node[] = [];\n let inputNodeNameToKey: {[key: string]: string} = {};\n let outputNodeNameToKey: {[key: string]: string} = {};\n if (signature != null) {\n inputNodeNameToKey = this.mapSignatureEntries(signature.inputs);\n outputNodeNameToKey = this.mapSignatureEntries(signature.outputs);\n }\n const allNodes = Object.keys(nodes);\n allNodes.forEach(key => {\n const node = nodes[key];\n node.inputNames.forEach((name, index) => {\n const [nodeName, , outputName] = getNodeNameAndIndex(name);\n const inputNode = nodes[nodeName];\n if (inputNode.outputs != null) {\n const outputIndex = inputNode.outputs.indexOf(outputName);\n if (outputIndex !== -1) {\n const inputName = `${nodeName}:${outputIndex}`;\n // update the input name to use the mapped output index directly.\n node.inputNames[index] = inputName;\n }\n }\n node.inputs.push(inputNode);\n inputNode.children.push(node);\n });\n });\n\n // if signature has not outputs set, add any node that does not have\n // outputs.\n if (Object.keys(outputNodeNameToKey).length === 0) {\n allNodes.forEach(key => {\n const node = nodes[key];\n if (node.children.length === 0) {\n outputs.push(node);\n }\n });\n } else {\n Object.keys(outputNodeNameToKey).forEach(name => {\n const [nodeName, ] = getNodeNameAndIndex(name);\n const node = nodes[nodeName];\n if (node != null) {\n node.signatureKey = outputNodeNameToKey[name];\n outputs.push(node);\n }\n });\n }\n\n if (Object.keys(inputNodeNameToKey).length > 0) {\n Object.keys(inputNodeNameToKey).forEach(name => {\n const [nodeName, ] = getNodeNameAndIndex(name);\n const node = nodes[nodeName];\n if (node) {\n node.signatureKey = inputNodeNameToKey[name];\n inputs.push(node);\n }\n });\n } else {\n inputs = placeholders;\n }\n\n let functions = {};\n if (graph.library != null && graph.library.function != null) {\n functions = graph.library.function.reduce((functions, func) => {\n functions[func.signature.name] = this.mapFunction(func);\n return functions;\n }, {} as {[key: string]: Graph});\n }\n\n const result: Graph =\n {nodes, inputs, outputs, weights, placeholders, signature, functions};\n\n if (initNodes.length > 0) {\n result.initNodes = initNodes;\n }\n\n return result;\n }\n\n private mapSignatureEntries(entries: {[k: string]: tensorflow.ITensorInfo}) {\n return Object.keys(entries || {})\n .reduce<{[key: string]: string}>((prev, curr) => {\n prev[entries[curr].name] = curr;\n return prev;\n }, {});\n }\n\n private mapNode(node: tensorflow.INodeDef): Node {\n // Unsupported ops will cause an error at run-time (not parse time), since\n // they may not be used by the actual execution subgraph.\n const mapper =\n getRegisteredOp(node.op) || this.opMappers[node.op] || {} as OpMapper;\n if (node.attr == null) {\n node.attr = {};\n }\n\n const newNode: Node = {\n name: node.name,\n op: node.op,\n category: mapper.category,\n inputNames:\n (node.input ||\n []).map(input => input.startsWith('^') ? input.substr(1) : input),\n inputs: [],\n children: [],\n inputParams: {},\n attrParams: {},\n rawAttrs: node.attr,\n outputs: mapper.outputs\n };\n\n if (mapper.inputs != null) {\n newNode.inputParams =\n mapper.inputs.reduce<{[key: string]: InputParamValue}>(\n (map, param) => {\n map[param.name] = {\n type: param.type,\n inputIndexStart: param.start,\n inputIndexEnd: param.end\n };\n return map;\n },\n {});\n }\n if (mapper.attrs != null) {\n newNode.attrParams =\n mapper.attrs.reduce<{[key: string]: ParamValue}>((map, param) => {\n const type = param.type;\n let value = undefined;\n switch (param.type) {\n case 'string':\n value = getStringParam(\n node.attr, param.tfName, param.defaultValue as string);\n\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getStringParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as string);\n }\n break;\n case 'string[]':\n value = getStringArrayParam(\n node.attr, param.tfName, param.defaultValue as string[]);\n\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getStringArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as string[]);\n }\n break;\n case 'number':\n value = getNumberParam(\n node.attr, param.tfName,\n (param.defaultValue || 0) as number);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getNumberParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number);\n }\n break;\n case 'number[]':\n value = getNumericArrayParam(\n node.attr, param.tfName, param.defaultValue as number[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getNumericArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number[]);\n }\n break;\n case 'bool':\n value = getBoolParam(\n node.attr, param.tfName, param.defaultValue as boolean);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getBoolParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as boolean);\n }\n break;\n case 'bool[]':\n value = getBoolArrayParam(\n node.attr, param.tfName, param.defaultValue as boolean[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getBoolArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as boolean[]);\n }\n break;\n case 'shape':\n value = getTensorShapeParam(\n node.attr, param.tfName, param.defaultValue as number[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getTensorShapeParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number[]);\n }\n break;\n case 'shape[]':\n value = getTensorShapeArrayParam(\n node.attr, param.tfName, param.defaultValue as number[][]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getTensorShapeArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as number[][]);\n }\n break;\n case 'dtype':\n value = getDtypeParam(\n node.attr, param.tfName, param.defaultValue as DataType);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getDtypeParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as DataType);\n }\n break;\n case 'dtype[]':\n value = getDtypeArrayParam(\n node.attr, param.tfName, param.defaultValue as DataType[]);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getDtypeArrayParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as DataType[]);\n }\n break;\n case 'func':\n value = getFuncParam(\n node.attr, param.tfName, param.defaultValue as string);\n if (value === undefined && !!param.tfDeprecatedName) {\n value = getFuncParam(\n node.attr, param.tfDeprecatedName,\n param.defaultValue as string);\n }\n break;\n case 'tensor':\n case 'tensors':\n break;\n default:\n throw new Error(\n `Unsupported param type: ${param.type} for op: ${node.op}`);\n }\n map[param.name] = {value, type};\n return map;\n }, {});\n }\n return newNode;\n }\n\n // map the TFunctionDef to TFJS graph object\n private mapFunction(functionDef: tensorflow.IFunctionDef): Graph {\n const tfNodes = functionDef.nodeDef;\n const placeholders: Node[] = [];\n const weights: Node[] = [];\n let nodes: {[key: string]: Node} = {};\n if (tfNodes != null) {\n nodes = tfNodes.reduce<{[key: string]: Node}>((map, node) => {\n map[node.name] = this.mapNode(node);\n if (node.op === 'Const') {\n weights.push(map[node.name]);\n }\n return map;\n }, {});\n }\n const inputs: Node[] = [];\n const outputs: Node[] = [];\n\n functionDef.signature.inputArg.forEach(arg => {\n const [nodeName, ] = getNodeNameAndIndex(arg.name);\n const node: Node = {\n name: nodeName,\n op: 'Placeholder',\n inputs: [],\n inputNames: [],\n category: 'graph',\n inputParams: {},\n attrParams: {dtype: {value: parseDtypeParam(arg.type), type: 'dtype'}},\n children: []\n };\n node.signatureKey = arg.name;\n inputs.push(node);\n nodes[nodeName] = node;\n });\n\n const allNodes = Object.keys(nodes);\n allNodes.forEach(key => {\n const node = nodes[key];\n node.inputNames.forEach((name, index) => {\n const [nodeName, , outputName] = getNodeNameAndIndex(name);\n const inputNode = nodes[nodeName];\n if (inputNode.outputs != null) {\n const outputIndex = inputNode.outputs.indexOf(outputName);\n if (outputIndex !== -1) {\n const inputName = `${nodeName}:${outputIndex}`;\n // update the input name to use the mapped output index directly.\n node.inputNames[index] = inputName;\n }\n }\n node.inputs.push(inputNode);\n inputNode.children.push(node);\n });\n });\n\n const returnNodeMap = functionDef.ret;\n\n functionDef.signature.outputArg.forEach(output => {\n const [nodeName, index] = getNodeNameAndIndex(returnNodeMap[output.name]);\n const node = nodes[nodeName];\n if (node != null) {\n node.defaultOutput = index;\n outputs.push(node);\n }\n });\n\n const signature = this.mapArgsToSignature(functionDef);\n return {nodes, inputs, outputs, weights, placeholders, signature};\n }\n\n private mapArgsToSignature(functionDef: tensorflow.IFunctionDef):\n tensorflow.ISignatureDef {\n return {\n methodName: functionDef.signature.name,\n inputs: functionDef.signature.inputArg.reduce(\n (map, arg) => {\n map[arg.name] = this.mapArgToTensorInfo(arg);\n return map;\n },\n {} as {[key: string]: tensorflow.ITensorInfo}),\n outputs: functionDef.signature.outputArg.reduce(\n (map, arg) => {\n map[arg.name] = this.mapArgToTensorInfo(arg, functionDef.ret);\n return map;\n },\n {} as {[key: string]: tensorflow.ITensorInfo}),\n };\n }\n\n private mapArgToTensorInfo(\n arg: tensorflow.OpDef.IArgDef,\n nameMap?: {[key: string]: string}): tensorflow.ITensorInfo {\n let name = arg.name;\n if (nameMap != null) {\n name = nameMap[name];\n }\n return {name, dtype: arg.type};\n }\n}\n\nexport function decodeBase64(text: string): string {\n const global = env().global;\n if (typeof global.atob !== 'undefined') {\n return global.atob(text);\n } else if (typeof Buffer !== 'undefined') {\n return new Buffer(text, 'base64').toString();\n } else {\n throw new Error(\n 'Unable to decode base64 in this environment. ' +\n 'Missing built-in atob() or Buffer()');\n }\n}\n\nexport function parseStringParam(s: []|string, keepCase: boolean): string {\n const value =\n Array.isArray(s) ? String.fromCharCode.apply(null, s) : decodeBase64(s);\n return keepCase ? value : value.toLowerCase();\n}\n\nexport function getStringParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string, def: string,\n keepCase = false): string {\n const param = attrs[name];\n if (param != null) {\n return parseStringParam(param.s, keepCase);\n }\n return def;\n}\n\nexport function getBoolParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: boolean): boolean {\n const param = attrs[name];\n return param ? param.b : def;\n}\n\nexport function getNumberParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: number): number {\n const param = attrs[name] || {};\n const value =\n param['i'] != null ? param['i'] : (param['f'] != null ? param['f'] : def);\n return (typeof value === 'number') ? value : parseInt(value, 10);\n}\n\nexport function parseDtypeParam(value: string|tensorflow.DataType): DataType {\n if (typeof (value) === 'string') {\n // tslint:disable-next-line:no-any\n value = tensorflow.DataType[value as any];\n }\n switch (value) {\n case tensorflow.DataType.DT_FLOAT:\n return 'float32';\n case tensorflow.DataType.DT_INT32:\n case tensorflow.DataType.DT_INT64:\n case tensorflow.DataType.DT_INT8:\n case tensorflow.DataType.DT_UINT8:\n return 'int32';\n case tensorflow.DataType.DT_BOOL:\n return 'bool';\n case tensorflow.DataType.DT_DOUBLE:\n return 'float32';\n case tensorflow.DataType.DT_STRING:\n return 'string';\n default:\n // Unknown dtype error will happen at runtime (instead of parse time),\n // since these nodes might not be used by the actual subgraph execution.\n return null;\n }\n}\n\nexport function getFuncParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: string): string {\n const param = attrs[name];\n if (param && param.func) {\n return param.func.name;\n }\n return def;\n}\n\nexport function getDtypeParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: DataType): DataType {\n const param = attrs[name];\n if (param && param.type) {\n return parseDtypeParam(param.type);\n }\n return def;\n}\n\nexport function getDtypeArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: DataType[]): DataType[] {\n const param = attrs[name];\n if (param && param.list && param.list.type) {\n return param.list.type.map(v => parseDtypeParam(v));\n }\n return def;\n}\n\nexport function parseTensorShapeParam(shape: tensorflow.ITensorShape): number[]|\n undefined {\n if (shape.unknownRank) {\n return undefined;\n }\n if (shape.dim != null) {\n return shape.dim.map(\n dim =>\n (typeof dim.size === 'number') ? dim.size : parseInt(dim.size, 10));\n }\n return [];\n}\n\nexport function getTensorShapeParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def?: number[]): number[]|undefined {\n const param = attrs[name];\n if (param && param.shape) {\n return parseTensorShapeParam(param.shape);\n }\n return def;\n}\n\nexport function getNumericArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: number[]): number[] {\n const param = attrs[name];\n if (param) {\n return ((param.list.f && param.list.f.length ? param.list.f :\n param.list.i) ||\n [])\n .map(v => (typeof v === 'number') ? v : parseInt(v, 10));\n }\n return def;\n}\n\nexport function getStringArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string, def: string[],\n keepCase = false): string[] {\n const param = attrs[name];\n if (param && param.list && param.list.s) {\n return param.list.s.map((v) => {\n return parseStringParam(v, keepCase);\n });\n }\n return def;\n}\n\nexport function getTensorShapeArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: number[][]): number[][] {\n const param = attrs[name];\n if (param && param.list && param.list.shape) {\n return param.list.shape.map((v) => {\n return parseTensorShapeParam(v);\n });\n }\n return def;\n}\n\nexport function getBoolArrayParam(\n attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n def: boolean[]): boolean[] {\n const param = attrs[name];\n if (param && param.list && param.list.b) {\n return param.list.b;\n }\n return def;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {getTensor} from '../executors/utils';\nimport {getBoolArrayParam, getBoolParam, getDtypeArrayParam, getDtypeParam, getNumberParam, getNumericArrayParam, getStringArrayParam, getStringParam, getTensorShapeArrayParam, getTensorShapeParam} from '../operation_mapper';\nimport {GraphNode, Node, ValueType} from '../types';\n\n/**\n * Helper class for lookup inputs and params for nodes in the model graph.\n */\nexport class NodeValueImpl implements GraphNode {\n public readonly inputs: Tensor[] = [];\n public readonly attrs: {[key: string]: ValueType} = {};\n constructor(\n private node: Node, private tensorMap: NamedTensorsMap,\n private context: ExecutionContext) {\n this.inputs = node.inputNames.map(name => this.getInput(name));\n if (node.rawAttrs != null) {\n this.attrs = Object.keys(node.rawAttrs)\n .reduce((attrs: {[key: string]: ValueType}, key) => {\n attrs[key] = this.getAttr(key);\n return attrs;\n }, {});\n }\n }\n\n /**\n * Return the value of the attribute or input param.\n * @param name String: name of attribute or input param.\n */\n private getInput(name: string): Tensor {\n return getTensor(name, this.tensorMap, this.context);\n }\n\n /**\n * Return the value of the attribute or input param.\n * @param name String: name of attribute or input param.\n */\n private getAttr(name: string, defaultValue?: ValueType): ValueType {\n const value = this.node.rawAttrs[name];\n if (value.tensor != null) {\n return getTensor(name, this.tensorMap, this.context);\n }\n if (value.i != null || value.f != null) {\n return getNumberParam(this.node.rawAttrs, name, defaultValue as number);\n }\n if (value.s != null) {\n return getStringParam(this.node.rawAttrs, name, defaultValue as string);\n }\n if (value.b != null) {\n return getBoolParam(this.node.rawAttrs, name, defaultValue as boolean);\n }\n if (value.shape != null) {\n return getTensorShapeParam(\n this.node.rawAttrs, name, defaultValue as number[]);\n }\n if (value.type != null) {\n return getDtypeParam(this.node.rawAttrs, name, defaultValue as DataType);\n }\n if (value.list != null) {\n if (value.list.i != null || value.list.f != null) {\n return getNumericArrayParam(\n this.node.rawAttrs, name, defaultValue as number[]);\n }\n if (value.list.s != null) {\n return getStringArrayParam(\n this.node.rawAttrs, name, defaultValue as string[]);\n }\n if (value.list.shape != null) {\n return getTensorShapeArrayParam(\n this.node.rawAttrs, name, defaultValue as number[][]);\n }\n if (value.list.b != null) {\n return getBoolArrayParam(\n this.node.rawAttrs, name, defaultValue as boolean[]);\n }\n if (value.list.type != null) {\n return getDtypeArrayParam(\n this.node.rawAttrs, name, defaultValue as DataType[]);\n }\n }\n\n return defaultValue;\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'BiasAdd':\n case 'AddV2':\n case 'Add': {\n return [tfOps.add(\n (getParamValue('a', node, tensorMap, context) as Tensor),\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'AddN': {\n return [tfOps.addN((\n getParamValue('tensors', node, tensorMap, context) as Tensor[]))];\n }\n case 'FloorMod':\n case 'Mod':\n return [tfOps.mod(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n case 'Mul':\n return [tfOps.mul(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n case 'RealDiv':\n case 'Div': {\n return [tfOps.div(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'DivNoNan': {\n return [tfOps.divNoNan(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'FloorDiv': {\n return [tfOps.floorDiv(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Sub': {\n return [tfOps.sub(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Minimum': {\n return [tfOps.minimum(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Maximum': {\n return [tfOps.maximum(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Pow': {\n return [tfOps.pow(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'SquaredDifference': {\n return [tfOps.squaredDifference(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'arithmetic';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Abs':\n case 'ComplexAbs':\n return [tfOps.abs(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Acos':\n return [tfOps.acos(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Acosh':\n return [tfOps.acosh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Asin':\n return [tfOps.asin(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Asinh':\n return [tfOps.asinh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Atan':\n return [tfOps.atan(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Atan2':\n return [tfOps.atan2(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('y', node, tensorMap, context) as Tensor)];\n case 'Atanh':\n return [tfOps.atanh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Ceil':\n return [tfOps.ceil(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Complex':\n return [tfOps.complex(\n getParamValue('real', node, tensorMap, context) as Tensor,\n getParamValue('imag', node, tensorMap, context) as Tensor)];\n case 'Cos':\n return [tfOps.cos(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Cosh':\n return [tfOps.cosh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Elu':\n return [tfOps.elu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Erf':\n return [tfOps.erf(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Exp':\n return [tfOps.exp(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Expm1': {\n return [tfOps.expm1(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Floor':\n return [tfOps.floor(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Log':\n return [tfOps.log(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Log1p': {\n return [tfOps.log1p(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Imag':\n return [tfOps.imag(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n\n case 'Neg':\n return [tfOps.neg(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Reciprocal': {\n return [tfOps.reciprocal(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Real':\n return [tfOps.real(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Relu':\n return [tfOps.relu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Round': {\n return [tfOps.round(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Selu':\n return [tfOps.selu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sigmoid':\n return [tfOps.sigmoid(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sin':\n return [tfOps.sin(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sign': {\n return [tfOps.sign(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Sinh': {\n return [tfOps.sinh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Softplus': {\n return [tfOps.softplus(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Sqrt': {\n return [tfOps.sqrt(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Square': {\n return [tfOps.square(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Tanh': {\n return [tfOps.tanh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Tan':\n return [tfOps.tan(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'ClipByValue':\n return [tfOps.clipByValue(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('clipValueMin', node, tensorMap, context) as number,\n getParamValue('clipValueMax', node, tensorMap, context) as\n number)];\n case 'Relu6':\n return [tfOps.relu6(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Rsqrt':\n return [tfOps.rsqrt(\n getTensor(node.inputNames[0], tensorMap, context))];\n case 'Prod':\n return [tfOps.prod(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('axes', node, tensorMap, context) as number[])];\n case 'LeakyRelu':\n return [tfOps.leakyRelu(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('alpha', node, tensorMap, context) as number)];\n case 'Prelu':\n return [tfOps.prelu(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('alpha', node, tensorMap, context) as Tensor)];\n case 'IsNan':\n return [tfOps.isNaN(\n getTensor(node.inputNames[0], tensorMap, context))];\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'basic_math';\n","\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * This differs from util.assertShapesMatch in that it allows values of\n * negative one, an undefined size of a dimensinon, in a shape to match\n * anything.\n */\n\nimport {Tensor, util} from '@tensorflow/tfjs-core';\n\n/**\n * Used by TensorList and TensorArray to verify if elementShape matches, support\n * negative value as the dim shape.\n * @param shapeA\n * @param shapeB\n * @param errorMessagePrefix\n */\nexport function assertShapesMatchAllowUndefinedSize(\n shapeA: number|number[], shapeB: number|number[],\n errorMessagePrefix = ''): void {\n // constant shape means unknown rank\n if (typeof shapeA === 'number' || typeof shapeB === 'number') {\n return;\n }\n util.assert(\n shapeA.length === shapeB.length,\n () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n for (let i = 0; i < shapeA.length; i++) {\n const dim0 = shapeA[i];\n const dim1 = shapeB[i];\n util.assert(\n dim0 < 0 || dim1 < 0 || dim0 === dim1,\n () =>\n errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n }\n}\n\nexport function fullDefinedShape(elementShape: number|number[]): boolean {\n if (typeof elementShape === 'number' || elementShape.some(dim => dim < 0)) {\n return false;\n }\n return true;\n}\n/**\n * Generate the output element shape from the list elementShape, list tensors\n * and input param.\n * @param listElementShape\n * @param tensors\n * @param elementShape\n */\nexport function inferElementShape(\n listElementShape: number|number[], tensors: Tensor[],\n elementShape: number|number[]): number[] {\n let partialShape = mergeElementShape(listElementShape, elementShape);\n const notfullDefinedShape = !fullDefinedShape(partialShape);\n if (notfullDefinedShape && tensors.length === 0) {\n throw new Error(\n `Tried to calculate elements of an empty list` +\n ` with non-fully-defined elementShape: ${partialShape}`);\n }\n if (notfullDefinedShape) {\n tensors.forEach(tensor => {\n partialShape = mergeElementShape(tensor.shape, partialShape);\n });\n }\n if (!fullDefinedShape(partialShape)) {\n throw new Error(`Non-fully-defined elementShape: ${partialShape}`);\n }\n return partialShape as number[];\n}\n\nexport function mergeElementShape(\n elementShapeA: number|number[], elementShapeB: number|number[]): number|\n number[] {\n if (typeof elementShapeA === 'number') {\n return elementShapeB;\n }\n if (typeof elementShapeB === 'number') {\n return elementShapeA;\n }\n\n if (elementShapeA.length !== elementShapeB.length) {\n throw new Error(`Incompatible ranks during merge: ${elementShapeA} vs. ${\n elementShapeB}`);\n }\n\n const result: number[] = [];\n for (let i = 0; i < elementShapeA.length; ++i) {\n const dim0 = elementShapeA[i];\n const dim1 = elementShapeB[i];\n if (dim0 >= 0 && dim1 >= 0 && dim0 !== dim1) {\n throw new Error(`Incompatible shape during merge: ${elementShapeA} vs. ${\n elementShapeB}`);\n }\n result[i] = dim0 >= 0 ? dim0 : dim1;\n }\n return result;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {concat, DataType, keep, reshape, scalar, slice, stack, Tensor, tensor, tidy, unstack} from '@tensorflow/tfjs-core';\n\nimport {assertShapesMatchAllowUndefinedSize} from './tensor_utils';\n\nexport interface TensorWithState {\n tensor?: Tensor;\n written?: boolean;\n read?: boolean;\n cleared?: boolean;\n}\n/**\n * The TensorArray object keeps an array of Tensors. It\n * allows reading from the array and writing to the array.\n */\nexport class TensorArray {\n private tensors: TensorWithState[] = [];\n private closed_ = false;\n readonly idTensor: Tensor;\n constructor(\n readonly name: string, readonly dtype: DataType, private maxSize: number,\n private elementShape: number[], readonly identicalElementShapes: boolean,\n readonly dynamicSize: boolean, readonly clearAfterRead: boolean) {\n this.idTensor = scalar(0);\n keep(this.idTensor);\n }\n\n get id() {\n return this.idTensor.id;\n }\n\n get closed() {\n return this.closed_;\n }\n\n /**\n * Dispose the tensors and idTensor and mark the TensoryArray as closed.\n */\n clearAndClose(keepIds?: Set) {\n this.tensors.forEach(tensor => {\n if (keepIds == null || !keepIds.has(tensor.tensor.id)) {\n tensor.tensor.dispose();\n }\n });\n this.tensors = [];\n this.closed_ = true;\n this.idTensor.dispose();\n }\n\n size(): number {\n return this.tensors.length;\n }\n\n /**\n * Read the value at location index in the TensorArray.\n * @param index Number the index to read from.\n */\n read(index: number): Tensor {\n if (this.closed_) {\n throw new Error(`TensorArray ${this.name} has already been closed.`);\n }\n\n if (index < 0 || index >= this.size()) {\n throw new Error(`Tried to read from index ${index}, but array size is: ${\n this.size()}`);\n }\n\n const tensorWithState = this.tensors[index];\n if (tensorWithState.cleared) {\n throw new Error(\n `TensorArray ${this.name}: Could not read index ${\n index} twice because it was cleared after a previous read ` +\n `(perhaps try setting clear_after_read = false?).`);\n }\n\n if (this.clearAfterRead) {\n tensorWithState.cleared = true;\n }\n\n tensorWithState.read = true;\n return tensorWithState.tensor;\n }\n\n /**\n * Helper method to read multiple tensors from the specified indices.\n */\n readMany(indices: number[]): Tensor[] {\n return indices.map(index => this.read(index));\n }\n\n /**\n * Write value into the index of the TensorArray.\n * @param index number the index to write to.\n * @param tensor\n */\n write(index: number, tensor: Tensor) {\n if (this.closed_) {\n throw new Error(`TensorArray ${this.name} has already been closed.`);\n }\n\n if (index < 0 || !this.dynamicSize && index >= this.maxSize) {\n throw new Error(`Tried to write to index ${\n index}, but array is not resizeable and size is: ${this.maxSize}`);\n }\n\n const t = this.tensors[index] || {};\n\n if (tensor.dtype !== this.dtype) {\n throw new Error(`TensorArray ${\n this.name}: Could not write to TensorArray index ${index},\n because the value dtype is ${\n tensor.dtype}, but TensorArray dtype is ${this.dtype}.`);\n }\n\n // Set the shape for the first time write to unknow shape tensor array\n if (this.size() === 0 &&\n (this.elementShape == null || this.elementShape.length === 0)) {\n this.elementShape = tensor.shape;\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, tensor.shape,\n `TensorArray ${this.name}: Could not write to TensorArray index ${\n index}.`);\n\n if (t.read) {\n throw new Error(\n `TensorArray ${this.name}: Could not write to TensorArray index ${\n index}, because it has already been read.`);\n }\n\n if (t.written) {\n throw new Error(\n `TensorArray ${this.name}: Could not write to TensorArray index ${\n index}, because it has already been written.`);\n }\n\n t.tensor = tensor;\n keep(tensor);\n t.written = true;\n\n this.tensors[index] = t;\n }\n\n /**\n * Helper method to write multiple tensors to the specified indices.\n */\n writeMany(indices: number[], tensors: Tensor[]) {\n if (indices.length !== tensors.length) {\n throw new Error(\n `TensorArray ${this.name}: could not write multiple tensors,` +\n `because the index size: ${\n indices.length} is not the same as tensors size: ${\n tensors.length}.`);\n }\n\n indices.forEach((i, index) => this.write(i, tensors[index]));\n }\n\n /**\n * Return selected values in the TensorArray as a packed Tensor. All of\n * selected values must have been written and their shapes must all match.\n * @param [indices] number[] Optional. Taking values in [0, max_value). If the\n * TensorArray is not dynamic, max_value=size(). If not specified returns\n * all tensors in the original order.\n * @param [dtype]\n */\n gather(indices?: number[], dtype?: DataType): Tensor {\n if (!!dtype && dtype !== this.dtype) {\n throw new Error(`TensorArray dtype is ${\n this.dtype} but gather requested dtype ${dtype}`);\n }\n\n if (!indices) {\n indices = [];\n for (let i = 0; i < this.size(); i++) {\n indices.push(i);\n }\n } else {\n indices = indices.slice(0, this.size());\n }\n\n if (indices.length === 0) {\n return tensor([], [0].concat(this.elementShape));\n }\n\n // Read all the PersistentTensors into a vector to keep track of\n // their memory.\n const tensors = this.readMany(indices);\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, tensors[0].shape, 'TensorArray shape mismatch: ');\n\n return stack(tensors, 0);\n }\n\n /**\n * Return the values in the TensorArray as a concatenated Tensor.\n */\n concat(dtype?: DataType): Tensor {\n if (!!dtype && dtype !== this.dtype) {\n throw new Error(`TensorArray dtype is ${\n this.dtype} but concat requested dtype ${dtype}`);\n }\n\n if (this.size() === 0) {\n return tensor([], [0].concat(this.elementShape));\n }\n\n const indices = [];\n for (let i = 0; i < this.size(); i++) {\n indices.push(i);\n }\n // Collect all the tensors from the tensors array.\n const tensors = this.readMany(indices);\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, tensors[0].shape,\n `TensorArray shape mismatch: tensor array shape (${\n this.elementShape}) vs first tensor shape (${tensors[0].shape})`);\n\n return concat(tensors, 0);\n }\n\n /**\n * Scatter the values of a Tensor in specific indices of a TensorArray.\n * @param indices nummber[] values in [0, max_value). If the\n * TensorArray is not dynamic, max_value=size().\n * @param tensor Tensor input tensor.\n */\n scatter(indices: number[], tensor: Tensor) {\n if (tensor.dtype !== this.dtype) {\n throw new Error(`TensorArray dtype is ${\n this.dtype} but tensor has dtype ${tensor.dtype}`);\n }\n\n if (indices.length !== tensor.shape[0]) {\n throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${\n indices.length} vs. ${tensor.shape[0]}`);\n }\n\n const maxIndex = Math.max(...indices);\n\n if (!this.dynamicSize && maxIndex >= this.maxSize) {\n throw new Error(\n `Max index must be < array size (${maxIndex} vs. ${this.maxSize})`);\n }\n\n this.writeMany(indices, unstack(tensor, 0));\n }\n\n /**\n * Split the values of a Tensor into the TensorArray.\n * @param length number[] with the lengths to use when splitting value along\n * its first dimension.\n * @param tensor Tensor, the tensor to split.\n */\n split(length: number[], tensor: Tensor) {\n if (tensor.dtype !== this.dtype) {\n throw new Error(`TensorArray dtype is ${\n this.dtype} but tensor has dtype ${tensor.dtype}`);\n }\n let totalLength = 0;\n const cumulativeLengths = length.map(len => {\n totalLength += len;\n return totalLength;\n });\n\n if (totalLength !== tensor.shape[0]) {\n throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${totalLength}, and tensor's shape is: ${tensor.shape}`);\n }\n\n if (!this.dynamicSize && length.length !== this.maxSize) {\n throw new Error(\n `TensorArray's size is not equal to the size of lengths (${\n this.maxSize} vs. ${length.length}), ` +\n 'and the TensorArray is not marked as dynamically resizeable');\n }\n\n const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;\n const tensors: Tensor[] = [];\n tidy(() => {\n tensor = reshape(tensor, [1, totalLength, elementPerRow]);\n for (let i = 0; i < length.length; ++i) {\n const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];\n const indices = [0, previousLength, 0];\n const sizes = [1, length[i], elementPerRow];\n tensors[i] = reshape(slice(tensor, indices, sizes), this.elementShape);\n }\n return tensors;\n });\n const indices = [];\n for (let i = 0; i < length.length; i++) {\n indices[i] = i;\n }\n this.writeMany(indices, tensors);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {concat, DataType, keep, reshape, scalar, slice, stack, Tensor, tensor, tidy, unstack} from '@tensorflow/tfjs-core';\n\nimport {assertShapesMatchAllowUndefinedSize, inferElementShape, mergeElementShape} from './tensor_utils';\n\n/**\n * TensorList stores a container of `tf.Tensor` objects, which are accessible\n * via tensors field.\n *\n * In order to get a copy of the underlying list, use the copy method:\n * ```\n * TensorList b = a.copy();\n * b.tensors().pushBack(t); // This does not modify a.tensors().\n * ```\n *\n * Note that this is not a deep copy: the memory locations of the underlying\n * tensors will still point to the same locations of the corresponding tensors\n * in the original.\n */\n\nexport class TensorList {\n readonly idTensor: Tensor;\n maxNumElements: number;\n\n get id() {\n return this.idTensor.id;\n }\n /**\n *\n * @param tensors list of tensors\n * @param elementShape shape of each tensor, this can be a single number (any\n * shape is allowed) or partial shape (dim = -1).\n * @param elementDtype data type of each tensor\n * @param maxNumElements The maximum allowed size of `tensors`. Defaults to -1\n * meaning that the size of `tensors` is unbounded.\n */\n constructor(\n readonly tensors: Tensor[], readonly elementShape: number|number[],\n readonly elementDtype: DataType, maxNumElements = -1) {\n if (tensors != null) {\n tensors.forEach(tensor => {\n if (elementDtype !== tensor.dtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${tensor.dtype}`);\n }\n assertShapesMatchAllowUndefinedSize(\n elementShape, tensor.shape, 'TensorList shape mismatch: ');\n\n keep(tensor);\n });\n }\n this.idTensor = scalar(0);\n this.maxNumElements = maxNumElements;\n keep(this.idTensor);\n }\n\n /**\n * Get a new TensorList containing a copy of the underlying tensor container.\n */\n copy(): TensorList {\n return new TensorList(\n [...this.tensors], this.elementShape, this.elementDtype);\n }\n\n /**\n * Dispose the tensors and idTensor and clear the tensor list.\n */\n clearAndClose(keepIds?: Set) {\n this.tensors.forEach(tensor => {\n if (keepIds == null || !keepIds.has(tensor.id)) {\n tensor.dispose();\n }\n });\n this.tensors.length = 0;\n this.idTensor.dispose();\n }\n /**\n * The size of the tensors in the tensor list.\n */\n size() {\n return this.tensors.length;\n }\n\n /**\n * Return a tensor that stacks a list of rank-R tf.Tensors into one rank-(R+1)\n * tf.Tensor.\n * @param elementShape shape of each tensor\n * @param elementDtype data type of each tensor\n * @param numElements the number of elements to stack\n */\n stack(elementShape: number[], elementDtype: DataType, numElements = -1):\n Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n if (numElements !== -1 && this.tensors.length !== numElements) {\n throw new Error(`Operation expected a list with ${\n numElements} elements but got a list with ${\n this.tensors.length} elements.`);\n }\n assertShapesMatchAllowUndefinedSize(\n elementShape, this.elementShape, 'TensorList shape mismatch: ');\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n return tidy(() => {\n const reshapedTensors =\n this.tensors.map(tensor => reshape(tensor, outputElementShape));\n return stack(reshapedTensors, 0);\n });\n }\n\n /**\n * Pop a tensor from the end of the list.\n * @param elementShape shape of the tensor\n * @param elementDtype data type of the tensor\n */\n popBack(elementShape: number[], elementDtype: DataType): Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n\n if (this.size() === 0) {\n throw new Error('Trying to pop from an empty list.');\n }\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n const tensor = this.tensors.pop();\n\n assertShapesMatchAllowUndefinedSize(\n tensor.shape, elementShape, 'TensorList shape mismatch: ');\n\n return reshape(tensor, outputElementShape);\n }\n\n /**\n * Push a tensor to the end of the list.\n * @param tensor Tensor to be pushed.\n */\n pushBack(tensor: Tensor) {\n if (tensor.dtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n tensor.dtype}, but list elements ${this.elementDtype}`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n tensor.shape, this.elementShape, 'TensorList shape mismatch: ');\n\n if (this.maxNumElements === this.size()) {\n throw new Error(`Trying to push element into a full list.`);\n }\n keep(tensor);\n this.tensors.push(tensor);\n }\n\n /**\n * Update the size of the list.\n * @param size the new size of the list.\n */\n resize(size: number) {\n if (size < 0) {\n throw new Error(\n `TensorListResize expects size to be non-negative. Got: ${size}`);\n }\n\n if (this.maxNumElements !== -1 && size > this.maxNumElements) {\n throw new Error(`TensorListResize input size ${\n size} is greater maxNumElement ${this.maxNumElements}.`);\n }\n this.tensors.length = size;\n }\n\n /**\n * Retrieve the element at the provided index\n * @param elementShape shape of the tensor\n * @param elementDtype dtype of the tensor\n * @param elementIndex index of the tensor\n */\n getItem(elementIndex: number, elementShape: number[], elementDtype: DataType):\n Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n if (elementIndex < 0 || elementIndex > this.tensors.length) {\n throw new Error(`Trying to access element ${\n elementIndex} in a list with ${this.tensors.length} elements.`);\n }\n\n if (this.tensors[elementIndex] == null) {\n throw new Error(`element at index ${elementIndex} is null.`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.tensors[elementIndex].shape, elementShape,\n 'TensorList shape mismatch: ');\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n return reshape(this.tensors[elementIndex], outputElementShape);\n }\n\n /**\n * Set the tensor at the index\n * @param elementIndex index of the tensor\n * @param tensor the tensor to be inserted into the list\n */\n setItem(elementIndex: number, tensor: Tensor) {\n if (tensor.dtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n tensor.dtype}, but list elements ${this.elementDtype}`);\n }\n\n if (elementIndex < 0 ||\n this.maxNumElements !== -1 && elementIndex >= this.maxNumElements) {\n throw new Error(`Trying to set element ${\n elementIndex} in a list with max ${this.maxNumElements} elements.`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, tensor.shape, 'TensorList shape mismatch: ');\n keep(tensor);\n this.tensors[elementIndex] = tensor;\n }\n\n /**\n * Return selected values in the TensorList as a stacked Tensor. All of\n * selected values must have been written and their shapes must all match.\n * @param indices indices of tensors to gather\n * @param elementDtype output tensor dtype\n * @param elementShape output tensor element shape\n */\n gather(indices: number[], elementDtype: DataType, elementShape: number[]):\n Tensor {\n if (elementDtype !== this.elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n elementDtype}, but list elements ${this.elementDtype}`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, elementShape, 'TensorList shape mismatch: ');\n\n // When indices is greater than the size of the list, indices beyond the\n // size of the list are ignored.\n indices = indices.slice(0, this.size());\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n if (indices.length === 0) {\n return tensor([], [0].concat(outputElementShape));\n }\n\n return tidy(() => {\n const tensors =\n indices.map(i => reshape(this.tensors[i], outputElementShape));\n return stack(tensors, 0);\n });\n }\n\n /**\n * Return the values in the TensorList as a concatenated Tensor.\n * @param elementDtype output tensor dtype\n * @param elementShape output tensor element shape\n */\n concat(elementDtype: DataType, elementShape: number[]): Tensor {\n if (!!elementDtype && elementDtype !== this.elementDtype) {\n throw new Error(`TensorList dtype is ${\n this.elementDtype} but concat requested dtype ${elementDtype}`);\n }\n\n assertShapesMatchAllowUndefinedSize(\n this.elementShape, elementShape, 'TensorList shape mismatch: ');\n const outputElementShape =\n inferElementShape(this.elementShape, this.tensors, elementShape);\n\n if (this.size() === 0) {\n return tensor([], [0].concat(outputElementShape));\n }\n return tidy(() => {\n const tensors = this.tensors.map(t => reshape(t, outputElementShape));\n return concat(tensors, 0);\n });\n }\n}\n\n/**\n * Creates a TensorList which, when stacked, has the value of tensor.\n * @param tensor from tensor\n * @param elementShape output tensor element shape\n */\nexport function fromTensor(\n tensor: Tensor, elementShape: number[], elementDtype: DataType) {\n const dtype = tensor.dtype;\n if (tensor.shape.length < 1) {\n throw new Error(\n `Tensor must be at least a vector, but saw shape: ${tensor.shape}`);\n }\n if (tensor.dtype !== elementDtype) {\n throw new Error(`Invalid data types; op elements ${\n tensor.dtype}, but list elements ${elementDtype}`);\n }\n const tensorElementShape = tensor.shape.slice(1);\n assertShapesMatchAllowUndefinedSize(\n tensorElementShape, elementShape, 'TensorList shape mismatch: ');\n const tensorList: Tensor[] = unstack(tensor);\n return new TensorList(tensorList, elementShape, dtype);\n}\n\n/**\n * Return a TensorList of the given size with empty elements.\n * @param elementShape the shape of the future elements of the list\n * @param elementDtype the desired type of elements in the list\n * @param numElements the number of elements to reserve\n */\nexport function reserve(\n elementShape: number[], elementDtype: DataType, numElements: number) {\n return new TensorList([], elementShape, elementDtype, numElements);\n}\n\n/**\n * Put tensors at specific indices of a stacked tensor into a TensorList.\n * @param indices list of indices on how to scatter the tensor.\n * @param tensor input tensor.\n * @param elementShape the shape of the future elements of the list\n * @param numElements the number of elements to scatter\n */\nexport function scatter(\n tensor: Tensor, indices: number[], elementShape: number[],\n numElements?: number): TensorList {\n if (indices.length !== tensor.shape[0]) {\n throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${\n indices.length} vs. ${tensor.shape[0]}`);\n }\n\n const maxIndex = Math.max(...indices);\n\n if (numElements != null && numElements !== -1 && maxIndex >= numElements) {\n throw new Error(\n `Max index must be < array size (${maxIndex} vs. ${numElements})`);\n }\n\n const list = new TensorList([], elementShape, tensor.dtype, numElements);\n const tensors = unstack(tensor, 0);\n indices.forEach((value, index) => {\n list.setItem(value, tensors[index]);\n });\n return list;\n}\n\n/**\n * Split the values of a Tensor into a TensorList.\n * @param length the lengths to use when splitting value along\n * its first dimension.\n * @param tensor the tensor to split.\n * @param elementShape the shape of the future elements of the list\n */\nexport function split(\n tensor: Tensor, length: number[], elementShape: number[]) {\n let totalLength = 0;\n const cumulativeLengths = length.map(len => {\n totalLength += len;\n return totalLength;\n });\n\n if (totalLength !== tensor.shape[0]) {\n throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${totalLength}, and tensor's shape is: ${tensor.shape}`);\n }\n\n const shapeWithoutFirstDim = tensor.shape.slice(1);\n const outputElementShape =\n mergeElementShape(shapeWithoutFirstDim, elementShape);\n const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;\n const tensors: Tensor[] = tidy(() => {\n const tensors = [];\n tensor = reshape(tensor, [1, totalLength, elementPerRow]);\n for (let i = 0; i < length.length; ++i) {\n const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];\n const indices = [0, previousLength, 0];\n const sizes = [1, length[i], elementPerRow];\n tensors[i] = reshape(\n slice(tensor, indices, sizes), outputElementShape as number[]);\n }\n tensor.dispose();\n return tensors;\n });\n\n const list = new TensorList([], elementShape, tensor.dtype, length.length);\n\n for (let i = 0; i < tensors.length; i++) {\n list.setItem(i, tensors[i]);\n }\n return list;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, scalar, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {TensorArray} from '../../executor/tensor_array';\nimport {fromTensor, reserve, scatter, split} from '../../executor/tensor_list';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {cloneTensor, getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Promise => {\n switch (node.op) {\n case 'If':\n case 'StatelessIf': {\n const thenFunc =\n getParamValue('thenBranch', node, tensorMap, context) as string;\n const elseFunc =\n getParamValue('elseBranch', node, tensorMap, context) as string;\n const cond = getParamValue('cond', node, tensorMap, context) as Tensor;\n const args = getParamValue('args', node, tensorMap, context) as Tensor[];\n const condValue = await cond.data();\n if (condValue[0]) {\n return context.functionMap[thenFunc].executeFunctionAsync(\n args, context.tensorArrayMap, context.tensorListMap);\n } else {\n return context.functionMap[elseFunc].executeFunctionAsync(\n args, context.tensorArrayMap, context.tensorListMap);\n }\n }\n case 'While':\n case 'StatelessWhile': {\n const bodyFunc =\n getParamValue('body', node, tensorMap, context) as string;\n const condFunc =\n getParamValue('cond', node, tensorMap, context) as string;\n const args = getParamValue('args', node, tensorMap, context) as Tensor[];\n\n // Calculate the condition of the loop\n const condResult =\n (await context.functionMap[condFunc].executeFunctionAsync(\n args, context.tensorArrayMap, context.tensorListMap));\n const argIds = args.map(tensor => tensor.id);\n let condValue = await condResult[0].data();\n // Dispose the intermediate tensors for condition function\n condResult.forEach(tensor => {\n if (!tensor.kept && argIds.indexOf(tensor.id) === -1) {\n tensor.dispose();\n }\n });\n\n let result: Tensor[] = args;\n\n while (condValue[0]) {\n // Record the previous result for intermediate tensor tracking\n const origResult = result;\n // Execution the body of the loop\n result = await context.functionMap[bodyFunc].executeFunctionAsync(\n result, context.tensorArrayMap, context.tensorListMap);\n const resultIds = result.map(tensor => tensor.id);\n\n // Dispose the intermediate tensor for body function that is not global\n // kept, not input/output of the body function\n origResult.forEach(tensor => {\n if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&\n resultIds.indexOf(tensor.id) === -1) {\n tensor.dispose();\n }\n });\n\n // Recalcuate the condition of the loop using the latest results.\n const condResult =\n (await context.functionMap[condFunc].executeFunctionAsync(\n result, context.tensorArrayMap, context.tensorListMap));\n condValue = await condResult[0].data();\n // Dispose the intermediate tensors for condition function\n condResult.forEach(tensor => {\n if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&\n resultIds.indexOf(tensor.id) === -1) {\n tensor.dispose();\n }\n });\n }\n return result;\n }\n case 'LoopCond': {\n const pred = getParamValue('pred', node, tensorMap, context) as Tensor;\n return [cloneTensor(pred)];\n }\n case 'Switch': {\n const pred = getParamValue('pred', node, tensorMap, context) as Tensor;\n let data = getParamValue('data', node, tensorMap, context) as Tensor;\n if (!data.kept) {\n data = cloneTensor(data);\n }\n // Outputs nodes :0 => false, :1 => true\n return (await pred.data())[0] ? [undefined, data] : [data, undefined];\n }\n case 'Merge': {\n const inputName = node.inputNames.find(\n name => getTensor(name, tensorMap, context) !== undefined);\n if (inputName) {\n const data = getTensor(inputName, tensorMap, context);\n return [cloneTensor(data)];\n }\n return undefined;\n }\n case 'Enter': {\n const frameId =\n getParamValue('frameName', node, tensorMap, context) as string;\n const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n context.enterFrame(frameId);\n return [cloneTensor(data)];\n }\n case 'Exit': {\n const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n context.exitFrame();\n return [cloneTensor(data)];\n }\n case 'NextIteration': {\n const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n context.nextIteration();\n return [cloneTensor(data)];\n }\n case 'TensorArrayV3': {\n const size = getParamValue('size', node, tensorMap, context) as number;\n const dtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const dynamicSize =\n getParamValue('dynamicSize', node, tensorMap, context) as boolean;\n const clearAfterRead =\n getParamValue('clearAfterRead', node, tensorMap, context) as boolean;\n const identicalElementShapes =\n getParamValue('identicalElementShapes', node, tensorMap, context) as\n boolean;\n const name = getParamValue('name', node, tensorMap, context) as string;\n const tensorArray = new TensorArray(\n name, dtype, size, elementShape, identicalElementShapes, dynamicSize,\n clearAfterRead);\n context.addTensorArray(tensorArray);\n return [tensorArray.idTensor, scalar(1.0)];\n }\n case 'TensorArrayWriteV3': {\n const id =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const index = getParamValue('index', node, tensorMap, context) as number;\n const writeTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const writeTensorArray = context.getTensorArray(id.id);\n writeTensorArray.write(index, writeTensor);\n return [writeTensorArray.idTensor];\n }\n case 'TensorArrayReadV3': {\n const readId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const readIndex =\n getParamValue('index', node, tensorMap, context) as number;\n const readTensorArray = context.getTensorArray(readId.id);\n return [readTensorArray.read(readIndex)];\n }\n case 'TensorArrayGatherV3': {\n const gatherId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const gatherIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const gatherDtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const gatherTensorArray = context.getTensorArray(gatherId.id);\n return [gatherTensorArray.gather(gatherIndices, gatherDtype)];\n }\n case 'TensorArrayScatterV3': {\n const scatterId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const scatterIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const scatterTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const scatterTensorArray = context.getTensorArray(scatterId.id);\n scatterTensorArray.scatter(scatterIndices, scatterTensor);\n return [scatterTensorArray.idTensor];\n }\n case 'TensorArrayConcatV3': {\n const concatId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const concatTensorArray = context.getTensorArray(concatId.id);\n const concatDtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n return [concatTensorArray.concat(concatDtype)];\n }\n case 'TensorArraySplitV3': {\n const splitId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const splitTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const lengths =\n getParamValue('lengths', node, tensorMap, context) as number[];\n const splitTensorArray = context.getTensorArray(splitId.id);\n splitTensorArray.split(lengths, splitTensor);\n return [splitTensorArray.idTensor];\n }\n case 'TensorArraySizeV3': {\n const sizeId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const sizeTensorArray = context.getTensorArray(sizeId.id);\n return [scalar(sizeTensorArray.size(), 'int32')];\n }\n case 'TensorArrayCloseV3': {\n const closeId =\n getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n const closeTensorArray = context.getTensorArray(closeId.id);\n closeTensorArray.clearAndClose();\n return [closeTensorArray.idTensor];\n }\n case 'TensorListSetItem': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const index = getParamValue('index', node, tensorMap, context) as number;\n const writeTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(idTensor.id);\n tensorList.setItem(index, writeTensor);\n return [tensorList.idTensor];\n }\n case 'TensorListGetItem': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const readIndex =\n getParamValue('index', node, tensorMap, context) as number;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n\n const elementDType =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = context.getTensorList(idTensor.id);\n return [tensorList.getItem(readIndex, elementShape, elementDType)];\n }\n case 'TensorListScatterV2':\n case 'TensorListScatter': {\n const scatterIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const scatterTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const numElements =\n getParamValue('numElements', node, tensorMap, context) as number;\n const tensorList =\n scatter(scatterTensor, scatterIndices, elementShape, numElements);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListReserve':\n case 'EmptyTensorList': {\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n let numElementsParam;\n\n if (node.op === 'TensorListReserve') {\n numElementsParam = 'numElements';\n } else {\n numElementsParam = 'maxNumElements';\n }\n\n const numElements =\n getParamValue(numElementsParam, node, tensorMap, context) as number;\n\n const tensorList = reserve(elementShape, elementDtype, numElements);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListGather': {\n const gatherId =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const gatherIndices =\n getParamValue('indices', node, tensorMap, context) as number[];\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = context.getTensorList(gatherId.id);\n return [tensorList.gather(gatherIndices, elementDtype, elementShape)];\n }\n case 'TensorListStack': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const numElements =\n getParamValue('numElements', node, tensorMap, context) as number;\n const tensorList = context.getTensorList(idTensor.id);\n return [tensorList.stack(elementShape, elementDtype, numElements)];\n }\n case 'TensorListFromTensor': {\n const tensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDtype =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = fromTensor(tensor, elementShape, elementDtype);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n case 'TensorListConcat': {\n const concatId =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(concatId.id);\n const concatDtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n return [tensorList.concat(concatDtype, elementShape)];\n }\n case 'TensorListPushBack': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const writeTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const tensorList = context.getTensorList(idTensor.id);\n tensorList.pushBack(writeTensor);\n return [tensorList.idTensor];\n }\n case 'TensorListPopBack': {\n const idTensor =\n getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const elementDType =\n getParamValue('elementDType', node, tensorMap, context) as DataType;\n const tensorList = context.getTensorList(idTensor.id);\n return [tensorList.popBack(elementShape, elementDType)];\n }\n case 'TensorListSplit': {\n const splitTensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n const elementShape =\n getParamValue('elementShape', node, tensorMap, context) as number[];\n const lengths =\n getParamValue('lengths', node, tensorMap, context) as number[];\n\n const tensorList = split(splitTensor, lengths, elementShape);\n context.addTensorList(tensorList);\n return [tensorList.idTensor];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n};\n\nexport const CATEGORY = 'control';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Rank, Tensor, Tensor3D, Tensor4D, Tensor5D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getPadding, getParamValue} from './utils';\n\nfunction fusedConvAndDepthWiseParams(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) {\n const [extraOp, activationFunc] =\n (getParamValue('fusedOps', node, tensorMap, context) as string[]);\n\n const isBiasAdd = extraOp === 'biasadd';\n const noBiasAdd = !isBiasAdd;\n const isPrelu = activationFunc === 'prelu';\n const isBatchNorm = extraOp === 'fusedbatchnorm';\n\n const numArgs =\n (getParamValue('numArgs', node, tensorMap, context) as number);\n if (isBiasAdd) {\n if (isPrelu && numArgs !== 2) {\n throw new Error(\n 'FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu ' +\n 'must have two extra arguments: bias and alpha.');\n }\n if (!isPrelu && isBiasAdd && numArgs !== 1) {\n throw new Error(\n 'FusedConv2d and DepthwiseConv2d with BiasAdd must have ' +\n 'one extra argument: bias.');\n }\n }\n if (isBatchNorm) {\n throw new Error(\n 'FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported');\n }\n const stride = getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n let [biasArg, preluArg] =\n getParamValue('args', node, tensorMap, context) as Tensor[];\n if (noBiasAdd) {\n preluArg = biasArg;\n biasArg = undefined;\n }\n const leakyreluAlpha =\n getParamValue('leakyreluAlpha', node, tensorMap, context) as number;\n\n return {\n stride,\n pad,\n dataFormat,\n dilations,\n biasArg,\n preluArg,\n activationFunc,\n leakyreluAlpha\n };\n}\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Conv1D': {\n const stride =\n getParamValue('stride', node, tensorMap, context) as number;\n const pad = getParamValue('pad', node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilation =\n getParamValue('dilation', node, tensorMap, context) as number;\n return [tfOps.conv1d(\n getParamValue('x', node, tensorMap, context) as Tensor3D,\n getParamValue('filter', node, tensorMap, context) as Tensor3D,\n stride, pad as 'valid' | 'same', dataFormat as 'NWC' | 'NCW',\n dilation)];\n }\n case 'Conv2D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n return [tfOps.conv2d(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor4D,\n [stride[1], stride[2]], pad as 'valid' | 'same',\n dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])];\n }\n case '_FusedConv2D': {\n const {\n stride,\n pad,\n dataFormat,\n dilations,\n biasArg,\n preluArg,\n activationFunc,\n leakyreluAlpha\n } = fusedConvAndDepthWiseParams(node, tensorMap, context);\n\n return [tfOps.fused.conv2d({\n x: getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n filter: getParamValue('filter', node, tensorMap, context) as\n Tensor4D,\n strides: [stride[1], stride[2]],\n pad: pad as 'valid' | 'same',\n dataFormat: dataFormat as 'NHWC' | 'NCHW',\n dilations: [dilations[1], dilations[2]],\n bias: biasArg,\n activation: activationFunc as tfOps.fused.Activation,\n preluActivationWeights: preluArg,\n leakyreluAlpha\n })];\n }\n\n case 'FusedDepthwiseConv2dNative': {\n const {\n stride,\n pad,\n dataFormat,\n dilations,\n biasArg,\n preluArg,\n activationFunc,\n leakyreluAlpha,\n } = fusedConvAndDepthWiseParams(node, tensorMap, context);\n\n return [tfOps.fused.depthwiseConv2d({\n x: getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n filter: getParamValue('filter', node, tensorMap, context) as\n Tensor4D,\n strides: [stride[1], stride[2]],\n pad: pad as 'valid' | 'same',\n dataFormat: dataFormat as 'NHWC' | 'NCHW',\n dilations: [dilations[1], dilations[2]],\n bias: biasArg,\n activation: activationFunc as tfOps.fused.Activation,\n preluActivationWeights: preluArg,\n leakyreluAlpha\n })];\n }\n case 'Conv2DBackpropInput':\n case 'Conv2dTranspose': {\n const shape = getParamValue(\n 'outputShape', node, tensorMap,\n context) as [number, number, number] |\n [number, number, number, number];\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n return [tfOps.conv2dTranspose(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor4D,\n shape, [stride[1], stride[2]], pad as 'valid' | 'same')];\n }\n case 'DepthwiseConv2dNative':\n case 'DepthwiseConv2d': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getPadding(node, tensorMap, context);\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n\n return [tfOps.depthwiseConv2d(\n getParamValue('input', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor4D,\n [stride[1], stride[2]], pad as 'valid' | 'same',\n dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])];\n }\n case 'Conv3D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as string)\n .toUpperCase();\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n return [tfOps.conv3d(\n getParamValue('x', node, tensorMap, context) as Tensor4D |\n Tensor,\n getParamValue('filter', node, tensorMap, context) as\n Tensor,\n [stride[1], stride[2], stride[3]], pad as 'valid' | 'same',\n dataFormat as 'NDHWC' | 'NCDHW',\n [dilations[1], dilations[2], dilations[3]])];\n }\n case 'AvgPool': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [tfOps.avgPool(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n pad as 'valid' | 'same')];\n }\n case 'MaxPool': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [tfOps.maxPool(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n pad as 'valid' | 'same')];\n }\n case 'MaxPoolWithArgmax': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n const includeBatchInIndex =\n getParamValue('includeBatchInIndex', node, tensorMap, context) as\n boolean;\n const {result, indexes} = tfOps.maxPoolWithArgmax(\n getParamValue('x', node, tensorMap, context) as Tensor4D,\n [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n pad as 'valid' | 'same', includeBatchInIndex);\n return [result, indexes];\n }\n case 'AvgPool3D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [tfOps.avgPool3d(\n getParamValue('x', node, tensorMap, context) as Tensor5D,\n [kernelSize[1], kernelSize[2], kernelSize[3]],\n [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')];\n }\n\n case 'MaxPool3D': {\n const stride =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const kernelSize =\n getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n return [tfOps.maxPool3d(\n getParamValue('x', node, tensorMap, context) as Tensor5D,\n [kernelSize[1], kernelSize[2], kernelSize[3]],\n [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')];\n }\n\n case 'Dilation2D': {\n const strides =\n getParamValue('strides', node, tensorMap, context) as number[];\n const pad = getParamValue('pad', node, tensorMap, context);\n const dilations =\n getParamValue('dilations', node, tensorMap, context) as number[];\n\n // strides: [1, stride_height, stride_width, 1].\n const strideHeight = strides[1];\n const strideWidth = strides[2];\n\n // dilations: [1, dilation_height, dilation_width, 1].\n const dilationHeight = dilations[1];\n const dilationWidth = dilations[2];\n\n return [tfOps.dilation2d(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('filter', node, tensorMap, context) as Tensor3D,\n [strideHeight, strideWidth], pad as 'valid' | 'same',\n [dilationHeight, dilationWidth], 'NHWC' /* dataFormat */)];\n }\n\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'convolution';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, Tensor, Tensor1D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Fill': {\n const shape =\n getParamValue('shape', node, tensorMap, context) as number[];\n const dtype =\n getParamValue('dtype', node, tensorMap, context) as DataType;\n const value =\n getParamValue('value', node, tensorMap, context) as number;\n return [tfOps.fill(shape, value, dtype)];\n }\n case 'LinSpace': {\n const start =\n getParamValue('start', node, tensorMap, context) as number;\n const stop =\n getParamValue('stop', node, tensorMap, context) as number;\n const num = getParamValue('num', node, tensorMap, context) as number;\n return [tfOps.linspace(start, stop, num)];\n }\n case 'Multinomial': {\n const logits =\n getParamValue('logits', node, tensorMap, context) as Tensor1D;\n const numSamples =\n getParamValue('numSamples', node, tensorMap, context) as number;\n const seed =\n getParamValue('seed', node, tensorMap, context) as number;\n return [tfOps.multinomial(logits, numSamples, seed)];\n }\n case 'OneHot': {\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor1D;\n const depth =\n getParamValue('depth', node, tensorMap, context) as number;\n const onValue =\n getParamValue('onValue', node, tensorMap, context) as number;\n const offValue =\n getParamValue('offValue', node, tensorMap, context) as number;\n return [tfOps.oneHot(indices, depth, onValue, offValue)];\n }\n case 'Ones': {\n return [tfOps.ones(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'OnesLike': {\n return [tfOps.onesLike(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'RandomUniform': {\n return [tfOps.randomUniform(\n // tslint:disable-next-line:no-any\n getParamValue('shape', node, tensorMap, context) as any,\n getParamValue('minval', node, tensorMap, context) as number,\n getParamValue('maxval', node, tensorMap, context) as number,\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'Range': {\n const start =\n getParamValue('start', node, tensorMap, context) as number;\n const stop =\n getParamValue('stop', node, tensorMap, context) as number;\n const step =\n getParamValue('step', node, tensorMap, context) as number;\n return [tfOps.range(\n start, stop, step,\n getParamValue('dtype', node, tensorMap, context) as 'float32' |\n 'int32')];\n }\n case 'TruncatedNormal': {\n const shape =\n getParamValue('shape', node, tensorMap, context) as number[];\n const mean =\n getParamValue('mean', node, tensorMap, context) as number;\n const stdDev =\n getParamValue('stdDev', node, tensorMap, context) as number;\n const seed =\n getParamValue('seed', node, tensorMap, context) as number;\n return [tfOps.truncatedNormal(\n shape, mean, stdDev,\n getParamValue('dtype', node, tensorMap, context) as 'float32' |\n 'int32',\n seed)];\n }\n case 'Zeros': {\n return [tfOps.zeros(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'ZerosLike': {\n return [tfOps.zerosLike(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'creation';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nfunction nmsParams(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) {\n const boxes = getParamValue('boxes', node, tensorMap, context) as Tensor;\n const scores = getParamValue('scores', node, tensorMap, context) as Tensor;\n const maxOutputSize =\n getParamValue('maxOutputSize', node, tensorMap, context) as number;\n const iouThreshold =\n getParamValue('iouThreshold', node, tensorMap, context) as number;\n const scoreThreshold =\n getParamValue('scoreThreshold', node, tensorMap, context) as number;\n const softNmsSigma =\n getParamValue('softNmsSigma', node, tensorMap, context) as number;\n\n return {\n boxes,\n scores,\n maxOutputSize,\n iouThreshold,\n scoreThreshold,\n softNmsSigma\n };\n}\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Promise => {\n switch (node.op) {\n case 'NonMaxSuppressionV5': {\n const {\n boxes,\n scores,\n maxOutputSize,\n iouThreshold,\n scoreThreshold,\n softNmsSigma\n } = nmsParams(node, tensorMap, context);\n\n const result = await tfOps.image.nonMaxSuppressionWithScoreAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold, softNmsSigma);\n\n return [result.selectedIndices, result.selectedScores];\n }\n case 'NonMaxSuppressionV4': {\n const {boxes, scores, maxOutputSize, iouThreshold, scoreThreshold} =\n nmsParams(node, tensorMap, context);\n\n const padToMaxOutputSize =\n getParamValue('padToMaxOutputSize', node, tensorMap, context) as\n boolean;\n\n const result = await tfOps.image.nonMaxSuppressionPaddedAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold, padToMaxOutputSize);\n\n return [result.selectedIndices, result.validOutputs];\n }\n case 'NonMaxSuppressionV3':\n case 'NonMaxSuppressionV2': {\n const {boxes, scores, maxOutputSize, iouThreshold, scoreThreshold} =\n nmsParams(node, tensorMap, context);\n\n return [await tfOps.image.nonMaxSuppressionAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold)];\n }\n case 'Where': {\n const condition = tfOps.cast(\n (getParamValue('condition', node, tensorMap, context) as Tensor),\n 'bool');\n const result = [await tfOps.whereAsync(condition)];\n condition.dispose();\n return result;\n }\n case 'ListDiff': {\n return tfOps.setdiff1dAsync(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('y', node, tensorMap, context) as Tensor);\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n};\n\nexport const CATEGORY = 'dynamic';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext):\n Tensor[] => {\n switch (node.op) {\n case 'TopKV2': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const k = getParamValue('k', node, tensorMap, context) as number;\n const sorted =\n getParamValue('sorted', node, tensorMap, context) as boolean;\n const result = tfOps.topk(x, k, sorted);\n return [result.values, result.indices];\n }\n case 'Unique': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const result = tfOps.unique(x);\n return [result.values, result.indices];\n }\n case 'UniqueV2': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const result = tfOps.unique(x, axis);\n return [result.values, result.indices];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'evaluation';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {cloneTensor, getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Const': {\n return tensorMap[node.name];\n }\n case 'PlaceholderWithDefault':\n const def =\n getParamValue('default', node, tensorMap, context) as Tensor;\n return [getTensor(node.name, tensorMap, context) || def];\n case 'Placeholder':\n return [getTensor(node.name, tensorMap, context)];\n case 'Identity':\n case 'StopGradient':\n case 'FakeQuantWithMinMaxVars': { // This op is currently ignored.\n const data = getParamValue('x', node, tensorMap, context) as Tensor;\n return [cloneTensor(data)];\n }\n case 'IdentityN':\n return (getParamValue('x', node, tensorMap, context) as Tensor[])\n .map((t: Tensor) => cloneTensor(t));\n case 'Snapshot':\n const snapshot =\n (getParamValue('x', node, tensorMap, context) as Tensor);\n return [cloneTensor(snapshot)];\n case 'Shape':\n return [tfOps.tensor1d(\n (getParamValue('x', node, tensorMap, context) as Tensor).shape,\n 'int32')];\n case 'ShapeN':\n return (getParamValue('x', node, tensorMap, context) as Tensor[])\n .map((t: Tensor) => tfOps.tensor1d(t.shape));\n case 'Size':\n return [tfOps.scalar(\n (getParamValue('x', node, tensorMap, context) as Tensor).size,\n 'int32')];\n case 'Rank':\n return [tfOps.scalar(\n (getParamValue('x', node, tensorMap, context) as Tensor).rank,\n 'int32')];\n case 'NoOp':\n return [tfOps.scalar(1)];\n case 'Print':\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n const data =\n getParamValue('data', node, tensorMap, context) as Tensor[];\n const message =\n getParamValue('message', node, tensorMap, context) as string;\n const summarize =\n getParamValue('summarize', node, tensorMap, context) as number;\n console.warn(\n 'The graph has a tf.print() operation,' +\n 'usually used for debugging, which slows down performance.');\n console.log(message);\n for (let i = 0; i < data.length; i++) {\n console.log(Array.prototype.slice.call(data[i].dataSync())\n .slice(0, summarize));\n }\n return [input];\n\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'graph';\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {DataType, keep, scalar, stack, Tensor, tidy, unstack, util} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\n/**\n * Hashtable contains a set of tensors, which can be accessed by key.\n */\nexport class HashTable {\n readonly handle: Tensor;\n\n // tslint:disable-next-line: no-any\n private tensorMap: Map;\n\n get id() {\n return this.handle.id;\n }\n\n /**\n * Constructor of HashTable. Creates a hash table.\n *\n * @param keyDType `dtype` of the table keys.\n * @param valueDType `dtype` of the table values.\n */\n constructor(readonly keyDType: DataType, readonly valueDType: DataType) {\n this.handle = scalar(0);\n // tslint:disable-next-line: no-any\n this.tensorMap = new Map();\n\n keep(this.handle);\n }\n\n /**\n * Dispose the tensors and handle and clear the hashtable.\n */\n clearAndClose() {\n this.tensorMap.forEach(value => value.dispose());\n this.tensorMap.clear();\n this.handle.dispose();\n }\n\n /**\n * The number of items in the hash table.\n */\n size(): number {\n return this.tensorMap.size;\n }\n\n /**\n * The number of items in the hash table as a rank-0 tensor.\n */\n tensorSize(): Tensor {\n return tfOps.scalar(this.size(), 'int32');\n }\n\n /**\n * Replaces the contents of the table with the specified keys and values.\n * @param keys Keys to store in the hashtable.\n * @param values Values to store in the hashtable.\n */\n async import(keys: Tensor, values: Tensor): Promise {\n this.checkKeyAndValueTensor(keys, values);\n\n // We only store the primitive values of the keys, this allows lookup\n // to be O(1).\n const $keys = await keys.data();\n\n // Clear the hashTable before inserting new values.\n this.tensorMap.forEach(value => value.dispose());\n this.tensorMap.clear();\n\n return tidy(() => {\n const $values = unstack(values);\n\n const keysLength = $keys.length;\n const valuesLength = $values.length;\n\n util.assert(\n keysLength === valuesLength,\n () => `The number of elements doesn't match, keys has ` +\n `${keysLength} elements, the values has ${valuesLength} ` +\n `elements.`);\n\n for (let i = 0; i < keysLength; i++) {\n const key = $keys[i];\n const value = $values[i];\n\n keep(value);\n this.tensorMap.set(key, value);\n }\n\n return this.handle;\n });\n }\n\n /**\n * Looks up keys in a hash table, outputs the corresponding values.\n *\n * Performs batch lookups, for every element in the key tensor, `find`\n * stacks the corresponding value into the return tensor.\n *\n * If an element is not present in the table, the given `defaultValue` is\n * used.\n *\n * @param keys Keys to look up. Must have the same type as the keys of the\n * table.\n * @param defaultValue The scalar `defaultValue` is the value output for keys\n * not present in the table. It must also be of the same type as the\n * table values.\n */\n async find(keys: Tensor, defaultValue: Tensor): Promise {\n this.checkKeyAndValueTensor(keys, defaultValue);\n\n const $keys = await keys.data();\n\n return tidy(() => {\n const result: Tensor[] = [];\n\n for (let i = 0; i < $keys.length; i++) {\n const key = $keys[i];\n\n const value = this.findWithDefault(key, defaultValue);\n result.push(value);\n }\n\n return stack(result);\n });\n }\n\n // tslint:disable-next-line: no-any\n private findWithDefault(key: any, defaultValue: Tensor): Tensor {\n const result = this.tensorMap.get(key);\n\n return result != null ? result : defaultValue;\n }\n\n private checkKeyAndValueTensor(key: Tensor, value: Tensor) {\n if (key.dtype !== this.keyDType) {\n throw new Error(\n `Expect key dtype ${this.keyDType}, but got ` +\n `${key.dtype}`);\n }\n\n if (value.dtype !== this.valueDType) {\n throw new Error(\n `Expect value dtype ${this.valueDType}, but got ` +\n `${value.dtype}`);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {HashTable} from '../../executor/hash_table';\nimport {ResourceManager} from '../../executor/resource_manager';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n resourceManager: ResourceManager): Promise => {\n switch (node.op) {\n case 'HashTable':\n case 'HashTableV2': {\n const keyDType =\n getParamValue('keyDType', node, tensorMap, context) as DataType;\n const valueDType =\n getParamValue('valueDType', node, tensorMap, context) as DataType;\n\n const hashTable = new HashTable(keyDType, valueDType);\n resourceManager.addHashTable(node.name, hashTable);\n return [hashTable.handle];\n }\n case 'LookupTableImport':\n case 'LookupTableImportV2': {\n const handle = getParamValue(\n 'tableHandle', node, tensorMap, context,\n resourceManager) as Tensor;\n const keys = getParamValue('keys', node, tensorMap, context) as Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n\n const hashTable = resourceManager.getHashTableById(handle.id);\n\n return [await hashTable.import(keys, values)];\n }\n case 'LookupTableFind':\n case 'LookupTableFindV2': {\n const handle = getParamValue(\n 'tableHandle', node, tensorMap, context,\n resourceManager) as Tensor;\n const keys = getParamValue('keys', node, tensorMap, context) as Tensor;\n const defaultValue =\n getParamValue('defaultValue', node, tensorMap, context) as Tensor;\n\n const hashTable = resourceManager.getHashTableById(handle.id);\n return [await hashTable.find(keys, defaultValue)];\n }\n case 'LookupTableSize':\n case 'LookupTableSizeV2': {\n const handle = getParamValue(\n 'tableHandle', node, tensorMap, context,\n resourceManager) as Tensor;\n\n const hashTable = resourceManager.getHashTableById(handle.id);\n return [hashTable.tensorSize()];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n};\n\nexport const CATEGORY = 'hash_table';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D, Tensor3D, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'ResizeBilinear': {\n const images =\n getParamValue('images', node, tensorMap, context) as Tensor;\n const size =\n getParamValue('size', node, tensorMap, context) as number[];\n const alignCorners =\n getParamValue('alignCorners', node, tensorMap, context) as\n boolean;\n const halfPixelCenters =\n getParamValue('halfPixelCenters', node, tensorMap, context) as\n boolean;\n return [tfOps.image.resizeBilinear(\n images as Tensor3D | Tensor4D, [size[0], size[1]], alignCorners,\n halfPixelCenters)];\n }\n case 'ResizeNearestNeighbor': {\n const images =\n getParamValue('images', node, tensorMap, context) as Tensor;\n const size =\n getParamValue('size', node, tensorMap, context) as number[];\n const alignCorners =\n getParamValue('alignCorners', node, tensorMap, context) as\n boolean;\n const halfPixelCenters =\n getParamValue('halfPixelCenters', node, tensorMap, context) as\n boolean;\n return [tfOps.image.resizeNearestNeighbor(\n images as Tensor3D | Tensor4D, [size[0], size[1]], alignCorners,\n halfPixelCenters)];\n }\n case 'CropAndResize': {\n const image =\n getParamValue('image', node, tensorMap, context) as Tensor;\n const boxes =\n getParamValue('boxes', node, tensorMap, context) as Tensor;\n const boxInd =\n getParamValue('boxInd', node, tensorMap, context) as Tensor;\n const cropSize =\n getParamValue('cropSize', node, tensorMap, context) as number[];\n const method =\n getParamValue('method', node, tensorMap, context) as string;\n const extrapolationValue =\n getParamValue('extrapolationValue', node, tensorMap, context) as\n number;\n return [tfOps.image.cropAndResize(\n image as Tensor4D, boxes as Tensor2D, boxInd as Tensor1D,\n cropSize as [number, number], method as 'bilinear' | 'nearest',\n extrapolationValue)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'image';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Equal': {\n return [tfOps.equal(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'NotEqual': {\n return [tfOps.notEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Greater': {\n return [tfOps.greater(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'GreaterEqual': {\n return [tfOps.greaterEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Less': {\n return [tfOps.less(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LessEqual': {\n return [tfOps.lessEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalAnd': {\n return [tfOps.logicalAnd(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalNot': {\n return [tfOps.logicalNot(\n getParamValue('a', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalOr': {\n return [tfOps.logicalOr(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Select':\n case 'SelectV2': {\n return [tfOps.where(\n getParamValue('condition', node, tensorMap, context) as Tensor,\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'logical';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'BatchMatMul':\n case 'BatchMatMulV2':\n case 'MatMul':\n return [tfOps.matMul(\n getParamValue('a', node, tensorMap, context) as Tensor2D,\n getParamValue('b', node, tensorMap, context) as Tensor2D,\n getParamValue('transposeA', node, tensorMap, context) as boolean,\n getParamValue('transposeB', node, tensorMap, context) as\n boolean)];\n\n case 'Einsum':\n return [tfOps.einsum(\n getParamValue('equation', node, tensorMap, context) as string,\n ...getParamValue('tensors', node, tensorMap, context) as\n Tensor[])];\n\n case 'Transpose':\n return [tfOps.transpose(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('perm', node, tensorMap, context) as number[])];\n\n case '_FusedMatMul':\n const [extraOp, activationFunc] =\n (getParamValue('fusedOps', node, tensorMap, context) as string[]);\n\n const isBiasAdd = extraOp === 'biasadd';\n const isPrelu = activationFunc === 'prelu';\n\n const numArgs =\n (getParamValue('numArgs', node, tensorMap, context) as number);\n const leakyreluAlpha =\n getParamValue('leakyreluAlpha', node, tensorMap, context) as\n number;\n\n if (isBiasAdd) {\n if (isPrelu && numArgs !== 2) {\n throw new Error(\n 'Fused MatMul with BiasAdd and Prelu must have two ' +\n 'extra arguments: bias and alpha.');\n }\n if (!isPrelu && numArgs !== 1) {\n throw new Error(\n 'Fused MatMul with BiasAdd must have one extra argument: bias.');\n }\n }\n const [biasArg, preluArg] =\n getParamValue('args', node, tensorMap, context) as Tensor[];\n return [tfOps.fused.matMul({\n a: getParamValue('a', node, tensorMap, context) as Tensor2D,\n b: getParamValue('b', node, tensorMap, context) as Tensor2D,\n transposeA: getParamValue('transposeA', node, tensorMap, context) as\n boolean,\n transposeB: getParamValue('transposeB', node, tensorMap, context) as\n boolean,\n bias: biasArg,\n activation: activationFunc as tfOps.fused.Activation,\n preluActivationWeights: preluArg,\n leakyreluAlpha\n })];\n\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'matrices';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor3D, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'FusedBatchNorm':\n case 'FusedBatchNormV2': {\n return [tfOps.batchNorm(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('mean', node, tensorMap, context) as Tensor,\n getParamValue('variance', node, tensorMap, context) as Tensor,\n getParamValue('offset', node, tensorMap, context) as Tensor,\n getParamValue('scale', node, tensorMap, context) as Tensor,\n getParamValue('epsilon', node, tensorMap, context) as number)];\n }\n case 'FusedBatchNormV3': {\n return [tfOps.batchNorm(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('mean', node, tensorMap, context) as Tensor,\n getParamValue('variance', node, tensorMap, context) as Tensor,\n getParamValue('offset', node, tensorMap, context) as Tensor,\n getParamValue('scale', node, tensorMap, context) as Tensor,\n getParamValue('epsilon', node, tensorMap, context) as number)];\n }\n case 'LRN': {\n return [tfOps.localResponseNormalization(\n getParamValue('x', node, tensorMap, context) as Tensor3D |\n Tensor4D,\n getParamValue('radius', node, tensorMap, context) as number,\n getParamValue('bias', node, tensorMap, context) as number,\n getParamValue('alpha', node, tensorMap, context) as number,\n getParamValue('beta', node, tensorMap, context) as number)];\n }\n case 'Softmax': {\n return [tfOps.softmax(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'LogSoftmax': {\n return [tfOps.logSoftmax(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'SparseToDense': {\n return [tfOps.sparseToDense(\n getParamValue('sparseIndices', node, tensorMap, context) as\n Tensor,\n getParamValue('outputShape', node, tensorMap, context) as Tensor,\n getParamValue('sparseValues', node, tensorMap, context) as\n number[],\n getParamValue('defaultValue', node, tensorMap, context) as\n Scalar)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'normalization';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Max': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [tfOps.max(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Mean': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [tfOps.mean(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Min': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [tfOps.min(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Sum': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [tfOps.sum(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'All': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [tfOps.all(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Any': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [tfOps.any(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'ArgMax': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n return [tfOps.argMax(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n case 'ArgMin': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n return [tfOps.argMin(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n case 'Prod': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const keepDims =\n getParamValue('keepDims', node, tensorMap, context) as boolean;\n return [tfOps.prod(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\n }\n case 'Cumsum': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const exclusive =\n getParamValue('exclusive', node, tensorMap, context) as boolean;\n const reverse =\n getParamValue('reverse', node, tensorMap, context) as boolean;\n return [tfOps.cumsum(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n exclusive, reverse)];\n }\n case 'Bincount':\n const x = getParamValue('x', node, tensorMap, context) as Tensor1D;\n const weights =\n getParamValue('weights', node, tensorMap, context) as Tensor1D;\n const size =\n getParamValue('size', node, tensorMap, context) as number;\n\n return [tfOps.bincount(x, weights, size)];\n case 'DenseBincount': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor1D |\n Tensor2D;\n const weights =\n getParamValue('weights', node, tensorMap, context) as Tensor1D |\n Tensor2D;\n const size =\n getParamValue('size', node, tensorMap, context) as number;\n\n const binaryOutput =\n getParamValue('binaryOutput', node, tensorMap, context) as\n boolean;\n\n return [tfOps.denseBincount(x, weights, size, binaryOutput)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'reduction';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D, tidy, util} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'ConcatV2':\n case 'Concat': {\n const n = getParamValue('n', node, tensorMap, context) as number;\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n let inputs =\n getParamValue('tensors', node, tensorMap, context) as Tensor[];\n inputs = inputs.slice(0, n);\n return [tfOps.concat(inputs, axis)];\n }\n case 'Gather': {\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor1D;\n return [tfOps.gather(input, tfOps.cast(indices, 'int32'), 0)];\n }\n case 'GatherV2': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const batchDims =\n getParamValue('batchDims', node, tensorMap, context) as number;\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor1D;\n return [tfOps.gather(\n input, tfOps.cast(indices, 'int32'), axis, batchDims)];\n }\n case 'Reverse': {\n const dims =\n getParamValue('dims', node, tensorMap, context) as boolean[];\n const axis = [];\n for (let i = 0; i < dims.length; i++) {\n if (dims[i]) {\n axis.push(i);\n }\n }\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n return [tfOps.reverse(input, axis)];\n }\n case 'ReverseV2': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n const input = getParamValue('x', node, tensorMap, context) as Tensor;\n return [tfOps.reverse(input, axis)];\n }\n case 'Slice': {\n // tslint:disable-next-line:no-any\n const begin = getParamValue('begin', node, tensorMap, context) as any;\n // tslint:disable-next-line:no-any\n const size = getParamValue('size', node, tensorMap, context) as any;\n return [tfOps.slice(\n getParamValue('x', node, tensorMap, context) as Tensor, begin,\n size)];\n }\n case 'StridedSlice': {\n const begin =\n getParamValue('begin', node, tensorMap, context) as number[];\n const end =\n getParamValue('end', node, tensorMap, context) as number[];\n const strides =\n getParamValue('strides', node, tensorMap, context) as number[];\n const beginMask =\n getParamValue('beginMask', node, tensorMap, context) as number;\n const endMask =\n getParamValue('endMask', node, tensorMap, context) as number;\n const ellipsisMask =\n getParamValue('ellipsisMask', node, tensorMap, context) as number;\n const newAxisMask =\n getParamValue('newAxisMask', node, tensorMap, context) as number;\n const shrinkAxisMask =\n getParamValue('shrinkAxisMask', node, tensorMap, context) as\n number;\n const tensor = getParamValue('x', node, tensorMap, context) as Tensor;\n\n return [tfOps.stridedSlice(\n tensor, begin, end, strides, beginMask, endMask, ellipsisMask,\n newAxisMask, shrinkAxisMask)];\n }\n case 'Pack': {\n return tidy(() => {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const tensors =\n getParamValue('tensors', node, tensorMap, context) as Tensor[];\n // Reshape the tensors to the first tensor's shape if they don't\n // match.\n const shape = tensors[0].shape;\n const squeezedShape = tfOps.squeeze(tensors[0]).shape;\n const mapped = tensors.map(tensor => {\n const sameShape = util.arraysEqual(tensor.shape, shape);\n if (!sameShape &&\n !util.arraysEqual(\n tfOps.squeeze(tensor).shape, squeezedShape)) {\n throw new Error('the input tensors shape does not match');\n }\n return sameShape ? tensor : tfOps.reshape(tensor, shape);\n });\n return [tfOps.stack(mapped, axis)];\n });\n }\n case 'Unpack': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const tensor =\n getParamValue('tensor', node, tensorMap, context) as Tensor;\n return tfOps.unstack(tensor, axis);\n }\n case 'Tile': {\n const reps =\n getParamValue('reps', node, tensorMap, context) as number[];\n return [tfOps.tile(\n getParamValue('x', node, tensorMap, context) as Tensor, reps)];\n }\n case 'Split':\n case 'SplitV': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n const numOrSizeSplits =\n getParamValue('numOrSizeSplits', node, tensorMap, context) as\n number |\n number[];\n const tensor = getParamValue('x', node, tensorMap, context) as Tensor;\n\n return tfOps.split(tensor, numOrSizeSplits, axis);\n }\n case 'ScatterNd': {\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor;\n const values =\n getParamValue('values', node, tensorMap, context) as Tensor;\n const shape =\n getParamValue('shape', node, tensorMap, context) as number[];\n return [tfOps.scatterND(indices, values, shape)];\n }\n case 'GatherNd': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const indices =\n getParamValue('indices', node, tensorMap, context) as Tensor;\n return [tfOps.gatherND(x, indices)];\n }\n case 'SparseToDense': {\n const indices =\n getParamValue('sparseIndices', node, tensorMap, context) as\n Tensor;\n const shape =\n getParamValue('outputShape', node, tensorMap, context) as\n number[];\n const sparseValues =\n getParamValue('sparseValues', node, tensorMap, context) as Tensor;\n const defaultValue =\n getParamValue('defaultValue', node, tensorMap, context) as Scalar;\n return [tfOps.sparseToDense(\n indices, sparseValues, shape,\n sparseValues.dtype === defaultValue.dtype ?\n defaultValue :\n tfOps.cast(defaultValue, sparseValues.dtype))];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'slice_join';\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'SparseFillEmptyRows': {\n const {\n outputIndices,\n outputValues,\n emptyRowIndicator,\n reverseIndexMap\n } =\n tfOps.sparse.sparseFillEmptyRows(\n getParamValue('indices', node, tensorMap, context) as\n Tensor2D,\n getParamValue('values', node, tensorMap, context) as Tensor1D,\n getParamValue('denseShape', node, tensorMap, context) as\n Tensor1D,\n getParamValue('defaultValue', node, tensorMap, context) as\n Scalar);\n return [\n outputIndices, outputValues, emptyRowIndicator, reverseIndexMap\n ];\n }\n case 'SparseReshape': {\n const {outputIndices, outputShape} = tfOps.sparse.sparseReshape(\n getParamValue('inputIndices', node, tensorMap, context) as\n Tensor2D,\n getParamValue('inputShape', node, tensorMap, context) as Tensor1D,\n getParamValue('newShape', node, tensorMap, context) as Tensor1D);\n return [outputIndices, outputShape];\n }\n case 'SparseSegmentMean': {\n const outputData = tfOps.sparse.sparseSegmentMean(\n getParamValue('data', node, tensorMap, context) as Tensor,\n getParamValue('indices', node, tensorMap, context) as Tensor1D,\n getParamValue('segmentIds', node, tensorMap, context) as\n Tensor1D);\n return [outputData];\n }\n case 'SparseSegmentSum': {\n const outputData = tfOps.sparse.sparseSegmentSum(\n getParamValue('data', node, tensorMap, context) as Tensor,\n getParamValue('indices', node, tensorMap, context) as Tensor1D,\n getParamValue('segmentIds', node, tensorMap, context) as\n Tensor1D);\n return [outputData];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'sparse';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext):\n Tensor[] => {\n switch (node.op) {\n case 'FFT': {\n return [tfOps.fft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'IFFT': {\n return [tfOps.ifft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'RFFT': {\n return [tfOps.rfft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'IRFFT': {\n return [tfOps.irfft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'spectral';\n","/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'StringNGrams': {\n const {nGrams, nGramsSplits} = tfOps.string.stringNGrams(\n getParamValue('data', node, tensorMap, context) as Tensor1D,\n getParamValue('dataSplits', node, tensorMap, context) as Tensor,\n getParamValue('separator', node, tensorMap, context) as string,\n getParamValue('nGramWidths', node, tensorMap, context) as\n number[],\n getParamValue('leftPad', node, tensorMap, context) as string,\n getParamValue('rightPad', node, tensorMap, context) as string,\n getParamValue('padWidth', node, tensorMap, context) as number,\n getParamValue(\n 'preserveShortSequences', node, tensorMap, context) as\n boolean);\n return [nGrams, nGramsSplits];\n }\n case 'StringSplit': {\n const {indices, values, shape} = tfOps.string.stringSplit(\n getParamValue('input', node, tensorMap, context) as Tensor1D,\n getParamValue('delimiter', node, tensorMap, context) as Scalar,\n getParamValue('skipEmpty', node, tensorMap, context) as boolean);\n return [indices, values, shape];\n }\n case 'StringToHashBucketFast': {\n const output = tfOps.string.stringToHashBucketFast(\n getParamValue('input', node, tensorMap, context) as Tensor,\n getParamValue('numBuckets', node, tensorMap, context) as number);\n return [output];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'string';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n (node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Cast': {\n return [tfOps.cast(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('dtype', node, tensorMap, context) as 'int32' |\n 'float32' | 'bool')];\n }\n case 'ExpandDims': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number;\n return [tfOps.expandDims(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n case 'Squeeze': {\n const axis =\n getParamValue('axis', node, tensorMap, context) as number[];\n return [tfOps.squeeze(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n\n case 'Reshape': {\n return [tfOps.reshape(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('shape', node, tensorMap, context) as number[])];\n }\n case 'MirrorPad': {\n return [tfOps.mirrorPad(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('padding', node, tensorMap, context) as\n Array<[number, number]>,\n getParamValue('mode', node, tensorMap, context) as 'reflect' |\n 'symmetric')];\n }\n case 'PadV2':\n case 'Pad': {\n return [tfOps.pad(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('padding', node, tensorMap, context) as\n Array<[number, number]>,\n getParamValue('constantValue', node, tensorMap, context) as\n number)];\n }\n case 'SpaceToBatchND': {\n const blockShape =\n getParamValue('blockShape', node, tensorMap, context) as number[];\n const paddings =\n getParamValue('paddings', node, tensorMap, context) as number[][];\n return [tfOps.spaceToBatchND(\n getParamValue('x', node, tensorMap, context) as Tensor,\n blockShape, paddings)];\n }\n case 'BatchToSpaceND': {\n const blockShape =\n getParamValue('blockShape', node, tensorMap, context) as number[];\n const crops =\n getParamValue('crops', node, tensorMap, context) as number[][];\n return [tfOps.batchToSpaceND(\n getParamValue('x', node, tensorMap, context) as Tensor,\n blockShape, crops)];\n }\n case 'DepthToSpace': {\n const blockSize =\n getParamValue('blockSize', node, tensorMap, context) as number;\n const dataFormat =\n (getParamValue('dataFormat', node, tensorMap, context) as\n string).toUpperCase() as 'NHWC' |\n 'NCHW';\n return [tfOps.depthToSpace(\n getParamValue('x', node, tensorMap, context) as Tensor4D,\n blockSize, dataFormat)];\n }\n case 'BroadcastTo': {\n return [tfOps.broadcastTo(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('shape', node, tensorMap, context) as number[])];\n }\n default:\n throw TypeError(`Node type ${node.op} is not implemented`);\n }\n };\n\nexport const CATEGORY = 'transformation';\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../data/types';\nimport {ExecutionContext} from '../executor/execution_context';\nimport {ResourceManager} from '../executor/resource_manager';\n\nimport {NodeValueImpl} from './custom_op/node_value_impl';\nimport {getRegisteredOp} from './custom_op/register';\nimport * as arithmetic from './executors/arithmetic_executor';\nimport * as basicMath from './executors/basic_math_executor';\nimport * as control from './executors/control_executor';\nimport * as convolution from './executors/convolution_executor';\nimport * as creation from './executors/creation_executor';\nimport * as dynamic from './executors/dynamic_executor';\nimport * as evaluation from './executors/evaluation_executor';\nimport * as graph from './executors/graph_executor';\nimport * as hashTable from './executors/hash_table_executor';\nimport * as image from './executors/image_executor';\nimport * as logical from './executors/logical_executor';\nimport * as matrices from './executors/matrices_executor';\nimport * as normalization from './executors/normalization_executor';\nimport * as reduction from './executors/reduction_executor';\nimport * as sliceJoin from './executors/slice_join_executor';\nimport * as sparse from './executors/sparse_executor';\nimport * as spectral from './executors/spectral_executor';\nimport * as string from './executors/string_executor';\nimport * as transformation from './executors/transformation_executor';\nimport {Node} from './types';\n\n/**\n * Executes the op defined by the node object.\n * @param node\n * @param tensorMap contains tensors for executed nodes and weights\n * @param context contains tensors and information for running the current node.\n * @param resourceManager Optional. Contains global resources of the model.\n */\nexport function executeOp(\n node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n resourceManager?: ResourceManager): tfc.Tensor[]|Promise {\n const value =\n ((node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) => {\n switch (node.category) {\n case 'arithmetic':\n return tfc.tidy(\n () => arithmetic.executeOp(node, tensorMap, context));\n case 'basic_math':\n return tfc.tidy(\n () => basicMath.executeOp(node, tensorMap, context));\n case 'control':\n return control.executeOp(node, tensorMap, context);\n case 'convolution':\n return tfc.tidy(\n () => convolution.executeOp(node, tensorMap, context));\n case 'creation':\n return tfc.tidy(() => creation.executeOp(node, tensorMap, context));\n case 'dynamic':\n return dynamic.executeOp(node, tensorMap, context);\n case 'evaluation':\n return tfc.tidy(\n () => evaluation.executeOp(node, tensorMap, context));\n case 'image':\n return tfc.tidy(() => image.executeOp(node, tensorMap, context));\n case 'graph':\n return tfc.tidy(() => graph.executeOp(node, tensorMap, context));\n case 'logical':\n return tfc.tidy(() => logical.executeOp(node, tensorMap, context));\n case 'matrices':\n return tfc.tidy(() => matrices.executeOp(node, tensorMap, context));\n case 'normalization':\n return tfc.tidy(\n () => normalization.executeOp(node, tensorMap, context));\n case 'reduction':\n return tfc.tidy(\n () => reduction.executeOp(node, tensorMap, context));\n case 'slice_join':\n return tfc.tidy(\n () => sliceJoin.executeOp(node, tensorMap, context));\n case 'sparse':\n return tfc.tidy(() => sparse.executeOp(node, tensorMap, context));\n case 'spectral':\n return tfc.tidy(() => spectral.executeOp(node, tensorMap, context));\n case 'string':\n return tfc.tidy(() => string.executeOp(node, tensorMap, context));\n case 'transformation':\n return tfc.tidy(\n () => transformation.executeOp(node, tensorMap, context));\n case 'hash_table':\n return hashTable.executeOp(\n node, tensorMap, context, resourceManager);\n case 'custom':\n const opMapper = getRegisteredOp(node.op);\n if (opMapper && opMapper.customExecutor) {\n return opMapper.customExecutor(\n new NodeValueImpl(node, tensorMap, context));\n } else {\n throw TypeError(`Custom op ${node.op} is not registered.`);\n }\n default:\n throw TypeError(\n `Unknown op '${node.op}'. File an issue at ` +\n `https://github.com/tensorflow/tfjs/issues so we can add it` +\n `, or register a custom execution with tf.registerOp()`);\n }\n })(node, tensorMap, context);\n if (tfc.util.isPromise(value)) {\n return (value as Promise).then((data) => [].concat(data));\n }\n return [].concat(value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap, TensorArrayMap, TensorListMap} from '../data/types';\n\nimport {TensorArray} from './tensor_array';\nimport {TensorList} from './tensor_list';\nimport {FunctionExecutor} from './types';\n\nexport interface ExecutionContextInfo {\n id: number; // the unique id of the context info\n frameName: string; // The frame name of the loop, this comes from\n // the TensorFlow NodeDef.\n iterationId: number; // The iteration id of the loop\n}\n\n/**\n * ExecutionContext captures the runtime environment of the node. It keeps\n * track of the current frame and iteration for the control flow ops.\n *\n * For example, typical Dynamic RNN model may contain loops, for which\n * TensorFlow will generate graphs with Enter/Exit nodes to control the\n * current execution frame, and NextIteration Nodes for iteration id increment.\n * For model with branch logic, TensorFLow will generate Switch/Merge ops.\n */\nexport class ExecutionContext {\n private rootContext = {id: 0, frameName: '', iterationId: 0};\n private contexts: ExecutionContextInfo[] = [this.rootContext];\n private lastId = 0;\n private _currentContextIds: string[];\n\n constructor(\n readonly weightMap: NamedTensorsMap = {},\n readonly tensorArrayMap: TensorArrayMap = {},\n readonly tensorListMap: TensorListMap = {},\n readonly functionMap: {[key: string]: FunctionExecutor} = {}) {\n this.generateCurrentContextIds();\n }\n\n private newFrame(id: number, frameName: string) {\n return {id, frameName, iterationId: 0};\n }\n\n /**\n * Set the current context\n * @param contexts: ExecutionContextInfo[] the current path of execution\n * frames\n */\n set currentContext(contexts: ExecutionContextInfo[]) {\n if (this.contexts !== contexts) {\n this.contexts = contexts;\n this.generateCurrentContextIds();\n }\n }\n\n get currentContext(): ExecutionContextInfo[] {\n return this.contexts;\n }\n\n /**\n * Returns the current context in string format.\n */\n get currentContextId(): string {\n return this._currentContextIds[0];\n }\n\n /**\n * Returns the current context and all parent contexts in string format.\n * This allow access to the nodes in the current and parent frames.\n */\n get currentContextIds(): string[] {\n return this._currentContextIds;\n }\n\n private generateCurrentContextIds() {\n const names = [];\n for (let i = 0; i < this.contexts.length - 1; i++) {\n const contexts = this.contexts.slice(0, this.contexts.length - i);\n names.push(this.contextIdforContexts(contexts));\n }\n names.push('');\n this._currentContextIds = names;\n }\n\n private contextIdforContexts(contexts: ExecutionContextInfo[]) {\n return contexts ?\n contexts\n .map(\n context => (context.id === 0 && context.iterationId === 0) ?\n '' :\n `${context.frameName}-${context.iterationId}`)\n .join('/') :\n '';\n }\n\n /**\n * Enter a new frame, a new context is pushed on the current context list.\n * @param frameId new frame id\n */\n enterFrame(frameId: string) {\n if (this.contexts) {\n this.lastId++;\n this.contexts = this.contexts.slice();\n this.contexts.push(this.newFrame(this.lastId, frameId));\n this._currentContextIds.unshift(this.contextIdforContexts(this.contexts));\n }\n }\n\n /**\n * Exit the current frame, the last context is removed from the current\n * context list.\n */\n exitFrame() {\n if (this.contexts && this.contexts.length > 1) {\n this.contexts = this.contexts.slice();\n this.contexts.splice(-1);\n this.currentContextIds.shift();\n } else {\n throw new Error('Cannot exit frame, the context is empty');\n }\n }\n\n /**\n * Enter the next iteration of a loop, the iteration id of last context is\n * increased.\n */\n nextIteration() {\n if (this.contexts && this.contexts.length > 0) {\n this.contexts = this.contexts.slice();\n this.lastId++;\n const context =\n Object.assign({}, this.contexts[this.contexts.length - 1]);\n context.iterationId += 1;\n context.id = this.lastId;\n this.contexts.splice(-1, 1, context);\n this._currentContextIds.splice(\n 0, 1, this.contextIdforContexts(this.contexts));\n } else {\n throw new Error('Cannot increase frame iteration, the context is empty');\n }\n }\n\n getWeight(name: string): Tensor[] {\n return this.weightMap[name];\n }\n\n addTensorArray(tensorArray: TensorArray) {\n this.tensorArrayMap[tensorArray.id] = tensorArray;\n }\n\n getTensorArray(id: number): TensorArray {\n return this.tensorArrayMap[id];\n }\n\n addTensorList(tensorList: TensorList) {\n this.tensorListMap[tensorList.id] = tensorList;\n }\n\n getTensorList(id: number): TensorList {\n return this.tensorListMap[id];\n }\n\n dispose(keepIds: Set) {\n for (const key in this.tensorArrayMap) {\n this.tensorArrayMap[key].clearAndClose(keepIds);\n }\n\n for (const key in this.tensorListMap) {\n this.tensorListMap[key].clearAndClose(keepIds);\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {NamedTensorMap} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../data/types';\nimport {parseNodeName} from '../operations/executors/utils';\nimport {Graph, Node} from '../operations/types';\n\nexport interface ExecutionInfo {\n inputs: NamedTensorMap;\n outputs: Node[];\n usedNodes: Set;\n missingInputs: string[];\n dynamicNode: Node;\n syncInputs: string[];\n}\n\n/**\n * Given graph inputs and desired outputs, find the minimal set of nodes\n * to execute in order to compute the outputs. In addition return other useful\n * info such:\n * - Missing inputs needed to compute the output.\n * - Whether the subgraph contains dynamic ops (control flow, dynamic shape).\n * - Alternative inputs in order to avoid async (dynamic op) execution.\n */\nexport function getExecutionSubgraph(\n inputs: NamedTensorMap, outputs: Node[], weightMap: NamedTensorsMap,\n initNodes?: Node[]): ExecutionInfo {\n const usedNodes = new Set();\n const missingInputs: string[] = [];\n let dynamicNode: Node = null;\n let syncInputs: string[] = null;\n\n // Start with the outputs, going backwards and find all the nodes that are\n // needed to compute those outputs.\n const seen = new Set();\n const inputNodeNames =\n Object.keys(inputs).map(name => parseNodeName(name)[0]);\n\n let initNodeNames: string[] = [];\n if (initNodes != null) {\n initNodeNames = initNodes.map(node => parseNodeName(node.name)[0]);\n }\n\n const frontier = [...outputs];\n while (frontier.length > 0) {\n const node = frontier.pop();\n if (isControlFlow(node) || isDynamicShape(node) || isHashTable(node)) {\n if (dynamicNode == null) {\n dynamicNode = node;\n syncInputs = dynamicNode.children.map(child => child.name)\n .filter(name => usedNodes.has(name));\n }\n }\n usedNodes.add(node.name);\n\n // Weights are dead end since we already have their values.\n if (weightMap[node.name] != null) {\n continue;\n }\n // This node is a dead end since it's one of the user-provided inputs.\n if (inputNodeNames.indexOf(node.name) !== -1) {\n continue;\n }\n // This node is a dead end since it doesn't have any inputs.\n if (initNodeNames.indexOf(node.name) !== -1) {\n continue;\n }\n if (node.inputs.length === 0) {\n missingInputs.push(node.name);\n continue;\n }\n node.inputs.forEach(input => {\n // Don't add to the frontier if it is already there.\n if (seen.has(input.name)) {\n return;\n }\n seen.add(input.name);\n frontier.push(input);\n });\n }\n return {inputs, outputs, usedNodes, missingInputs, dynamicNode, syncInputs};\n}\n\n/**\n * Given the execution info, return a list of nodes in topological order that\n * need to be executed to compute the output.\n */\nexport function getNodesInTopologicalOrder(\n graph: Graph, weightMap: NamedTensorsMap,\n executionInfo: ExecutionInfo): Node[] {\n const {usedNodes, inputs} = executionInfo;\n const frontier: Node[] = [];\n const inputNodes = Object.keys(inputs)\n .map(name => parseNodeName(name)[0])\n .map(name => graph.nodes[name]);\n const initNodes = graph.initNodes;\n\n inputNodes.forEach(input => {\n if (usedNodes.has(input.name)) {\n frontier.push(input);\n }\n });\n graph.weights.forEach(weight => {\n if (usedNodes.has(weight.name)) {\n frontier.push(weight);\n }\n });\n if (initNodes != null) {\n initNodes.forEach(node => {\n if (usedNodes.has(node.name)) {\n frontier.push(node);\n }\n });\n }\n const seen = new Set();\n const orderedNodes: Node[] = [];\n while (frontier.length > 0) {\n const node = frontier.pop();\n seen.add(node.name);\n if (!weightMap[node.name]) {\n orderedNodes.push(node);\n }\n node.children.forEach(child => {\n if (!seen.has(child.name) && usedNodes.has(child.name) &&\n child.inputs.every(input => seen.has(input.name))) {\n frontier.push(child);\n }\n });\n }\n return orderedNodes;\n}\n\nconst CONTROL_FLOW_OPS = [\n 'Switch', 'Merge', 'Enter', 'Exit', 'NextIteration', 'StatelessIf',\n 'StatelessWhile', 'if', 'While'\n];\nconst DYNAMIC_SHAPE_OPS = [\n 'NonMaxSuppressionV2', 'NonMaxSuppressionV3', 'NonMaxSuppressionV5', 'Where'\n];\nconst HASH_TABLE_OPS = [\n 'HashTable', 'HashTableV2', 'LookupTableImport', 'LookupTableImportV2',\n 'LookupTableFind', 'LookupTableFindV2', 'LookupTableSize', 'LookupTableSizeV2'\n];\n\nexport function isControlFlow(node: Node) {\n return CONTROL_FLOW_OPS.indexOf(node.op) >= 0;\n}\n\nexport function isDynamicShape(node: Node) {\n return DYNAMIC_SHAPE_OPS.indexOf(node.op) >= 0;\n}\n\nexport function isHashTable(node: Node) {\n return HASH_TABLE_OPS.indexOf(node.op) >= 0;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, NamedTensorMap, Tensor, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {ISignatureDef} from '../data/compiled_api';\nimport {NamedTensorsMap, TensorArrayMap, TensorInfo, TensorListMap} from '../data/types';\nimport {getNodeNameAndIndex, getParamValue, getTensor, getTensorsForCurrentContenxt, parseNodeName} from '../operations/executors/utils';\nimport {executeOp} from '../operations/operation_executor';\nimport {Graph, Node} from '../operations/types';\n\nimport {ExecutionContext, ExecutionContextInfo} from './execution_context';\nimport {getExecutionSubgraph, getNodesInTopologicalOrder, isControlFlow} from './model_analysis';\nimport {ResourceManager} from './resource_manager';\nimport {FunctionExecutor} from './types';\n\ninterface NodeWithContexts {\n contexts: ExecutionContextInfo[];\n node: Node;\n}\n\nexport class GraphExecutor implements FunctionExecutor {\n private compiledMap: Map = new Map();\n private _weightMap: NamedTensorsMap = {};\n private _weightIds: number[];\n private _signature: ISignatureDef;\n private _inputs: Node[];\n private _outputs: Node[];\n private _initNodes: Node[]; // Internal init nodes to start initialization.\n private SEPERATOR = ',';\n private _functions: {[key: string]: Graph} = {};\n private _functionExecutorMap: {[key: string]: FunctionExecutor} = {};\n private _resourceManager: ResourceManager;\n\n get weightIds(): number[] {\n return this.parent ? this.parent.weightIds : this._weightIds;\n }\n\n get functionExecutorMap(): {[key: string]: FunctionExecutor} {\n return this.parent ? this.parent.functionExecutorMap :\n this._functionExecutorMap;\n }\n\n get weightMap(): NamedTensorsMap {\n return this.parent ? this.parent.weightMap : this._weightMap;\n }\n\n set weightMap(weightMap: NamedTensorsMap) {\n const weightIds = Object.keys(weightMap).map(\n key => weightMap[key].map(tensor => tensor.id));\n this._weightIds = [].concat(...weightIds);\n this._weightMap = weightMap;\n }\n\n /**\n * Set `ResourceManager` shared by executors of a model.\n * @param resourceManager: `ResourceManager` of the `GraphModel`.\n */\n set resourceManager(resourceManager: ResourceManager) {\n this._resourceManager = resourceManager;\n }\n\n get inputs(): TensorInfo[] {\n return this._inputs.map(node => {\n return {\n name: node.name,\n shape: node.attrParams['shape'] ?\n node.attrParams['shape'].value as number[] :\n undefined,\n dtype: node.attrParams['dtype'] ?\n node.attrParams['dtype'].value as DataType :\n undefined\n };\n });\n }\n\n get outputs(): TensorInfo[] {\n return this._outputs.map(node => {\n return {\n name: node.name,\n shape: node.attrParams['shape'] ?\n node.attrParams['shape'].value as number[] :\n undefined,\n dtype: node.attrParams['dtype'] ?\n node.attrParams['dtype'].value as DataType :\n undefined\n };\n });\n }\n\n get inputNodes(): string[] {\n return this._inputs.map(node => node.signatureKey || node.name);\n }\n\n get outputNodes(): string[] {\n return this._outputs.map((node) => {\n const name = node.signatureKey || node.name;\n return node.defaultOutput ? (`${name}:${node.defaultOutput}`) : name;\n });\n }\n\n get functions(): {[key: string]: ISignatureDef} {\n return Object.keys(this._functions).reduce((map, key) => {\n map[key] = this._functions[key].signature;\n return map;\n }, {} as {[key: string]: ISignatureDef});\n }\n\n /**\n *\n * @param graph Graph the model or function graph to be executed.\n * @param parent When building function exector you need to set the parent\n * executor. Since the weights and function executor maps are set at parant\n * level, that function executor can access the function maps and weight maps\n * through the parent.\n */\n constructor(private graph: Graph, private parent?: GraphExecutor) {\n this._outputs = graph.outputs;\n this._inputs = graph.inputs;\n this._initNodes = graph.initNodes;\n this._signature = graph.signature;\n this._functions = graph.functions;\n // create sub-graph executors\n if (graph.functions != null) {\n Object.keys(graph.functions).forEach(name => {\n this._functionExecutorMap[name] =\n new GraphExecutor(graph.functions[name], this);\n });\n }\n }\n\n private getCompilationKey(inputs: Node[], outputs: Node[]): string {\n const sortedInputs = inputs.map(node => node.name).sort();\n const sortedOutputs = outputs.map(node => node.name).sort();\n return sortedInputs.join(this.SEPERATOR) + '--' +\n sortedOutputs.join(this.SEPERATOR);\n }\n\n /**\n * Compiles the inference graph and returns the minimal set of nodes that are\n * required for execution, in the correct execution order.\n */\n private compile(inputs: NamedTensorMap, outputs: Node[]): Node[] {\n const executionInfo =\n getExecutionSubgraph(inputs, outputs, this.weightMap, this._initNodes);\n const {missingInputs, dynamicNode, syncInputs} = executionInfo;\n if (dynamicNode != null) {\n throw new Error(\n `This execution contains the node '${dynamicNode.name}', which has ` +\n `the dynamic op '${dynamicNode.op}'. Please use ` +\n `model.executeAsync() instead. Alternatively, to avoid the ` +\n `dynamic ops, specify the inputs [${syncInputs}]`);\n }\n\n if (missingInputs.length > 0) {\n const outNames = outputs.map(n => n.name);\n const inNames = Object.keys(inputs);\n throw new Error(\n `Cannot compute the outputs [${outNames}] from the provided inputs ` +\n `[${inNames}]. Missing the following inputs: [${missingInputs}]`);\n }\n\n return getNodesInTopologicalOrder(\n this.graph, this.weightMap, executionInfo);\n }\n\n /**\n * Executes the inference for given input tensors.\n * @param inputs Tensor map for the model inputs, keyed by the input node\n * names.\n * @param outputs Optional. output node name from the Tensorflow model, if\n * no outputs are specified, the default outputs of the model would be used.\n * You can inspect intermediate nodes of the model by adding them to the\n * outputs array.\n */\n execute(inputs: NamedTensorMap, outputs?: string[]): Tensor[] {\n inputs = this.mapInputs(inputs);\n const names = Object.keys(inputs).sort();\n this.checkInputs(inputs);\n this.checkInputShapeAndType(inputs);\n outputs = this.mapOutputs(outputs);\n this.checkOutputs(outputs);\n const inputNodes =\n names.map(name => this.graph.nodes[parseNodeName(name)[0]]);\n const outputNodeNames = outputs.map(name => parseNodeName(name)[0]);\n let outputNodes = outputNodeNames.map(name => this.graph.nodes[name]);\n\n // If no outputs are specified, then use the default outputs of the model.\n if (outputNodes.length === 0) {\n outputNodes = this._outputs;\n }\n\n const compilationKey = this.getCompilationKey(inputNodes, outputNodes);\n\n // Do nothing if the compiled graph cache contains the input.\n let orderedNodes = this.compiledMap.get(compilationKey);\n if (orderedNodes == null) {\n orderedNodes = this.compile(inputs, outputNodes);\n this.compiledMap.set(compilationKey, orderedNodes);\n }\n\n const tensorArrayMap: TensorArrayMap = {};\n const tensorListMap: TensorListMap = {};\n\n return tidy(() => {\n const context = new ExecutionContext(\n this.weightMap, tensorArrayMap, tensorListMap,\n this.functionExecutorMap);\n const tensorsMap: NamedTensorsMap = {...this.weightMap};\n\n Object.keys(inputs).forEach(name => {\n const [nodeName, index] = parseNodeName(name);\n const tensors: Tensor[] = [];\n tensors[index] = inputs[name];\n tensorsMap[nodeName] = tensors;\n });\n\n const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);\n const intermediateTensorConsumerCount: {[key: number]: number} = {};\n for (let i = 0; i < orderedNodes.length; i++) {\n const node = orderedNodes[i];\n if (!tensorsMap[node.name]) {\n const tensors =\n executeOp(node, tensorsMap, context, this._resourceManager) as\n Tensor[];\n if (util.isPromise(tensors)) {\n throw new Error(\n `The execution of the op '${node.op}' returned a promise. ` +\n `Please use model.executeAsync() instead.`);\n }\n tensorsMap[node.name] = tensors;\n this.checkTensorForDisposal(\n node.name, node, tensorsMap, context, tensorsToKeep,\n outputNodeNames, intermediateTensorConsumerCount);\n }\n }\n // dispose the context for the root executor\n if (this.parent == null) {\n context.dispose(tensorsToKeep);\n }\n return outputs.map(name => getTensor(name, tensorsMap, context));\n });\n }\n\n private getFrozenTensorIds(tensorMap: NamedTensorsMap): Set {\n const ids = [].concat.apply(\n [],\n Object.keys(tensorMap)\n .map(key => tensorMap[key])\n .map(tensors => tensors.map(tensor => tensor.id)));\n return new Set(ids);\n }\n private checkTensorForDisposal(\n nodeName: string, node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, tensorsToKeep: Set,\n outputNames: string[],\n intermediateTensorConsumerCount: {[key: string]: number}) {\n // Skip output nodes and any control flow nodes, since its dependency is\n // tricky to track correctly.\n if (node.category === 'control' || outputNames.indexOf(nodeName) !== -1) {\n return;\n }\n\n tensorMap[nodeName].forEach(tensor => {\n if (tensor != null) {\n intermediateTensorConsumerCount[tensor.id] =\n (intermediateTensorConsumerCount[tensor.id] || 0) +\n node.children.length;\n }\n });\n node.inputs.forEach(input => {\n // Skip any control flow nodes, since its dependency is tricky to track\n // correctly.\n if (input.category !== 'control') {\n const tensors =\n getTensorsForCurrentContenxt(input.name, tensorMap, context);\n if (tensors != null) {\n tensors.forEach(tensor => {\n if (tensor && !tensor.kept && !tensorsToKeep.has(tensor.id)) {\n const count = intermediateTensorConsumerCount[tensor.id];\n if (count === 1) {\n tensor.dispose();\n delete intermediateTensorConsumerCount[tensor.id];\n } else if (count != null) {\n // only intermediate nodes has count set, inputs and weights are\n // not.\n intermediateTensorConsumerCount[tensor.id]--;\n }\n }\n });\n }\n }\n });\n }\n\n /**\n * Executes the inference for given input tensors in Async fashion.\n * @param inputs Tensor map for the model inputs, keyed by the input node\n * names.\n * @param outputs output node name from the Tensorflow model, if no outputs\n * are specified, the default outputs of the model would be used. You can\n * inspect intermediate nodes of the model by adding them to the outputs\n * array.\n */\n async executeAsync(inputs: NamedTensorMap, outputs?: string[]):\n Promise {\n return this._executeAsync(inputs, outputs);\n }\n\n /**\n * Executes the inference for given input tensors in Async fashion.\n * @param inputs Tensor map for the model inputs, keyed by the input node\n * names.\n * @param outputs Optional. output node name from the Tensorflow model,\n * if no outputs are specified, the default outputs of the model would be\n * used. You can inspect intermediate nodes of the model by adding them to the\n * outputs array.\n * @param isFunctionExecution Optional. Flag for executing a function.\n * @param tensorArrayMap Optional, global TensorArray map by id. Used for\n * function execution.\n * @param tensorArrayMap Optinal global TensorList map by id. Used for\n * function execution.\n */\n private async _executeAsync(\n inputs: NamedTensorMap, outputs?: string[], isFunctionExecution = false,\n tensorArrayMap: TensorArrayMap = {},\n tensorListMap: TensorListMap = {}): Promise {\n if (!isFunctionExecution) {\n inputs = this.mapInputs(inputs);\n this.checkInputs(inputs);\n this.checkInputShapeAndType(inputs);\n outputs = this.mapOutputs(outputs);\n this.checkOutputs(outputs);\n }\n\n const context = new ExecutionContext(\n this.weightMap, tensorArrayMap, tensorListMap,\n this.functionExecutorMap);\n\n // Graph with control flow op requires runtime evaluation of the execution\n // order, while without control flow the execution order is pre-determined\n // in the compile method.\n const tensorMap = await this.executeWithControlFlow(\n inputs, context, outputs, isFunctionExecution);\n const results = outputs.map(name => getTensor(name, tensorMap, context));\n\n // dispose all the intermediate tensors\n const outputIds = results.map(t => t.id);\n const inputIds = Object.keys(inputs).map(name => inputs[name].id);\n const keepIds =\n new Set([...outputIds, ...inputIds, ...this.weightIds]);\n Object.keys(tensorMap).forEach(key => {\n const tensorArray = tensorMap[key];\n tensorArray.forEach(tensor => {\n if (tensor && !tensor.kept && !tensor.isDisposed &&\n !keepIds.has(tensor.id)) {\n tensor.dispose();\n }\n });\n });\n // dispose the context for the root executor\n if (this.parent == null) {\n context.dispose(keepIds);\n }\n\n return results;\n }\n\n async executeFunctionAsync(\n inputs: Tensor[], tensorArrayMap: TensorArrayMap,\n tensorListMap: TensorListMap): Promise {\n const mappedInputs = inputs.reduce((map, tensor, index) => {\n map[this.inputs[index].name] = tensor;\n return map;\n }, {} as NamedTensorMap);\n\n return this._executeAsync(\n mappedInputs, this.outputNodes, true, tensorArrayMap, tensorListMap);\n }\n /**\n * When there are control flow nodes in the graph, the graph execution use\n * ExecutionContext to keep track of the frames and loop iterators.\n * @param inputs placeholder tensors for the graph.\n * @param context the execution context object for current execution.\n * @param outputNames Optional. output node name from the Tensorflow model,\n * if no outputs are specified, the default outputs of the model would be\n * used. You can inspect intermediate nodes of the model by adding them to the\n * outputs array.\n * @param isFunctionExecution Flag for executing a function.\n */\n private async executeWithControlFlow(\n inputs: NamedTensorMap, context: ExecutionContext, outputNames?: string[],\n isFunctionExecution?: boolean): Promise {\n const names = Object.keys(inputs);\n const inputNodes =\n names.map(name => this.graph.nodes[parseNodeName(name)[0]]);\n const outputNodeNames = outputNames.map(name => parseNodeName(name)[0]);\n let outputNodes = outputNodeNames.map(name => this.graph.nodes[name]);\n\n // If no outputs are specified, then use the default outputs of the model.\n if (outputNodes.length === 0) {\n outputNodes = this._outputs;\n }\n\n const {usedNodes, missingInputs, dynamicNode, syncInputs} =\n getExecutionSubgraph(\n inputs, outputNodes, this.weightMap, this._initNodes);\n\n // First nodes to execute include inputNodes, weights, and initNodes.\n const stack: NodeWithContexts[] = [\n ...inputNodes, ...this.graph.weights, ...(this._initNodes || [])\n ].map(node => {\n return {node, contexts: context.currentContext};\n });\n const tensorsMap: NamedTensorsMap = {...this.weightMap};\n Object.keys(inputs).forEach(name => {\n const [nodeName, index] = parseNodeName(name);\n const tensors: Tensor[] = [];\n tensors[index] = inputs[name];\n tensorsMap[nodeName] = tensors;\n });\n const intermediateTensorConsumerCount: {[key: number]: number} = {};\n const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);\n const added: {[key: string]: boolean} = {};\n while (stack.length > 0) {\n const promises = this.processStack(\n inputNodes, stack, context, tensorsMap, added, tensorsToKeep,\n outputNodeNames, intermediateTensorConsumerCount, usedNodes);\n await Promise.all(promises);\n }\n if (dynamicNode == null && !isFunctionExecution) {\n console.warn(\n `This model execution did not contain any nodes with control flow ` +\n `or dynamic output shapes. You can use model.execute() instead.`);\n }\n const missingOutputs =\n outputNodes\n .filter(\n node => !isControlFlow(node) &&\n !getTensor(node.name, tensorsMap, context))\n .map(node => node.name);\n if (missingOutputs.length > 0) {\n let alternativeMsg = '';\n if (dynamicNode != null) {\n alternativeMsg =\n `Alternatively, to avoid the dynamic ops, use model.execute() ` +\n `and specify the inputs [${syncInputs}]`;\n }\n throw new Error(\n `Cannot compute the outputs [${missingOutputs}] from the provided ` +\n `inputs [${names}]. Consider providing the following inputs: ` +\n `[${missingInputs}]. ${alternativeMsg}`);\n }\n return tensorsMap;\n }\n\n private processStack(\n inputNodes: Node[], stack: NodeWithContexts[], context: ExecutionContext,\n tensorMap: NamedTensorsMap, added: {[key: string]: boolean},\n tensorsToKeep: Set, outputNames: string[],\n intermediateTensorConsumerCount: {[key: number]: number},\n usedNodes: Set) {\n const promises: Array> = [];\n while (stack.length > 0) {\n const item = stack.pop();\n context.currentContext = item.contexts;\n let nodeName = '';\n // The tensor of the Enter op with isConstant set should be set\n // in the parent scope, so it will be available as constant for the\n // whole loop.\n if (item.node.op === 'Enter' &&\n getParamValue('isConstant', item.node, tensorMap, context)) {\n [nodeName] = getNodeNameAndIndex(item.node.name, context);\n }\n\n // only process nodes that are not in the tensorMap yet, this include\n // inputNodes and internal initNodes.\n if (tensorMap[item.node.name] == null) {\n const tensors =\n executeOp(item.node, tensorMap, context, this._resourceManager);\n if (!nodeName) {\n [nodeName] = getNodeNameAndIndex(item.node.name, context);\n }\n const currentContext = context.currentContext;\n if (util.isPromise(tensors)) {\n promises.push((tensors as Promise).then(t => {\n tensorMap[nodeName] = t;\n context.currentContext = currentContext;\n this.checkTensorForDisposal(\n nodeName, item.node, tensorMap, context, tensorsToKeep,\n outputNames, intermediateTensorConsumerCount);\n this.processChildNodes(\n item.node, stack, context, tensorMap, added, usedNodes);\n return t;\n }));\n } else {\n tensorMap[nodeName] = tensors as Tensor[];\n this.checkTensorForDisposal(\n nodeName, item.node, tensorMap, context, tensorsToKeep,\n outputNames, intermediateTensorConsumerCount);\n this.processChildNodes(\n item.node, stack, context, tensorMap, added, usedNodes);\n }\n } else {\n this.processChildNodes(\n item.node, stack, context, tensorMap, added, usedNodes);\n }\n }\n return promises;\n }\n\n private processChildNodes(\n node: Node, stack: NodeWithContexts[], context: ExecutionContext,\n tensorMap: NamedTensorsMap, added: {[key: string]: boolean},\n usedNodes: Set) {\n node.children.forEach((childNode) => {\n const [nodeName, ] = getNodeNameAndIndex(childNode.name, context);\n if (added[nodeName] || !usedNodes.has(childNode.name)) {\n return;\n }\n // Merge op can be pushed if any of its inputs has value.\n if (childNode.op === 'Merge') {\n if (childNode.inputNames.some(name => {\n return !!getTensor(name, tensorMap, context);\n })) {\n added[nodeName] = true;\n stack.push({contexts: context.currentContext, node: childNode});\n }\n } else // Otherwise all inputs must to have value.\n if (childNode.inputNames.every(name => {\n return !!getTensor(name, tensorMap, context);\n })) {\n added[nodeName] = true;\n stack.push({contexts: context.currentContext, node: childNode});\n }\n });\n }\n\n /**\n * Releases the memory used by the weight tensors.\n */\n dispose() {\n Object.keys(this.weightMap)\n .forEach(\n key => this.weightMap[key].forEach(tensor => tensor.dispose()));\n }\n\n private checkInputShapeAndType(inputs: NamedTensorMap) {\n Object.keys(inputs).forEach(name => {\n const input = inputs[name];\n const [nodeName, ] = parseNodeName(name);\n const node = this.graph.nodes[nodeName];\n if (node.attrParams['shape'] && node.attrParams['shape'].value) {\n const shape = node.attrParams['shape'].value as number[];\n const match = shape.length === input.shape.length &&\n input.shape.every(\n (dim, index) => shape[index] === -1 || shape[index] === dim);\n util.assert(\n match,\n () => `The shape of dict['${node.name}'] provided in ` +\n `model.execute(dict) must be [${shape}], but was ` +\n `[${input.shape}]`);\n }\n if (node.attrParams['dtype'] && node.attrParams['dtype'].value) {\n util.assert(\n input.dtype === node.attrParams['dtype'].value as string,\n () => `The dtype of dict['${node.name}'] provided in ` +\n `model.execute(dict) must be ` +\n `${node.attrParams['dtype'].value}, but was ${input.dtype}`);\n }\n });\n }\n\n private mapInputs(inputs: NamedTensorMap) {\n const result: NamedTensorMap = {};\n for (const inputName in inputs) {\n if (this._signature != null && this._signature.inputs != null &&\n this._signature.inputs[inputName] != null) {\n const tensor = this._signature.inputs[inputName];\n result[tensor.name] = inputs[inputName];\n } else {\n result[inputName] = inputs[inputName];\n }\n }\n return result;\n }\n\n private checkInputs(inputs: NamedTensorMap) {\n const notInGraph = Object.keys(inputs).filter(name => {\n const [nodeName] = parseNodeName(name);\n return this.graph.nodes[nodeName] == null;\n });\n if (notInGraph.length > 0) {\n throw new Error(\n `The dict provided in model.execute(dict) has ` +\n `keys: [${notInGraph}] that are not part of graph`);\n }\n }\n\n private mapOutputs(outputs: string[]) {\n return outputs.map(name => {\n if (this._signature != null && this._signature.outputs != null &&\n this._signature.outputs[name] != null) {\n const tensor = this._signature.outputs[name];\n return tensor.name;\n }\n return name;\n }, {});\n }\n\n private checkOutputs(outputs: string[]): void {\n outputs.forEach(name => {\n const [normalizedName] = parseNodeName(name);\n if (!this.graph.nodes[normalizedName]) {\n throw new Error(`The output '${name}' is not found in the graph`);\n }\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {HashTableMap, NamedTensorMap} from '../data/types';\nimport {HashTable} from './hash_table';\n\n/**\n * Contains global resources of a model.\n */\nexport class ResourceManager {\n constructor(\n readonly hashTableNameToHandle: NamedTensorMap = {},\n readonly hashTableMap: HashTableMap = {}) {}\n\n /**\n * Register a `HashTable` in the resource manager.\n *\n * The `HashTable` can be retrieved by `resourceManager.getHashTableById`,\n * where id is the table handle tensor's id.\n *\n * @param name Op node name that creates the `HashTable`.\n * @param hashTable The `HashTable` to be added to resource manager.\n */\n addHashTable(name: string, hashTable: HashTable) {\n this.hashTableNameToHandle[name] = hashTable.handle;\n this.hashTableMap[hashTable.id] = hashTable;\n }\n\n /**\n * Get the table handle by node name.\n * @param name Op node name that creates the `HashTable`. This name is also\n * used in the inputs list of lookup and import `HashTable` ops.\n */\n getHashTableHandleByName(name: string) {\n return this.hashTableNameToHandle[name];\n }\n\n /**\n * Get the actual `HashTable` by its handle tensor's id.\n * @param id The id of the handle tensor.\n */\n getHashTableById(id: number): HashTable {\n return this.hashTableMap[id];\n }\n\n /**\n * Dispose `ResourceManager`, including its hashTables and tensors in them.\n */\n dispose() {\n for (const key in this.hashTableMap) {\n this.hashTableMap[key].clearAndClose();\n delete this.hashTableMap[key];\n }\n\n for (const name in this.hashTableNameToHandle) {\n this.hashTableNameToHandle[name].dispose();\n delete this.hashTableNameToHandle[name];\n }\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {InferenceModel, io, ModelPredictConfig, NamedTensorMap, Tensor} from '@tensorflow/tfjs-core';\n\nimport * as tensorflow from '../data/compiled_api';\nimport {NamedTensorsMap, TensorInfo} from '../data/types';\nimport {OperationMapper} from '../operations/operation_mapper';\n\nimport {GraphExecutor} from './graph_executor';\nimport {ResourceManager} from './resource_manager';\n\nexport const TFHUB_SEARCH_PARAM = '?tfjs-format=file';\nexport const DEFAULT_MODEL_NAME = 'model.json';\n/**\n * A `tf.GraphModel` is a directed, acyclic graph built from a\n * SavedModel GraphDef and allows inference execution.\n *\n * A `tf.GraphModel` can only be created by loading from a model converted from\n * a [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) using\n * the command line converter tool and loaded via `tf.loadGraphModel`.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\nexport class GraphModel implements InferenceModel {\n private executor: GraphExecutor;\n private version = 'n/a';\n private handler: io.IOHandler;\n private artifacts: io.ModelArtifacts;\n private initializer: GraphExecutor;\n private resourceManager: ResourceManager;\n private signature: tensorflow.ISignatureDef;\n\n // Returns the version information for the tensorflow model GraphDef.\n get modelVersion(): string {\n return this.version;\n }\n\n get inputNodes(): string[] {\n return this.executor.inputNodes;\n }\n\n get outputNodes(): string[] {\n return this.executor.outputNodes;\n }\n\n get inputs(): TensorInfo[] {\n return this.executor.inputs;\n }\n\n get outputs(): TensorInfo[] {\n return this.executor.outputs;\n }\n\n get weights(): NamedTensorsMap {\n return this.executor.weightMap;\n }\n\n get metadata(): {} {\n return this.artifacts.userDefinedMetadata;\n }\n\n get modelSignature(): {} {\n return this.signature;\n }\n\n /**\n * @param modelUrl url for the model, or an `io.IOHandler`.\n * @param weightManifestUrl url for the weight file generated by\n * scripts/convert.py script.\n * @param requestOption options for Request, which allows to send credentials\n * and custom headers.\n * @param onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n */\n constructor(\n private modelUrl: string|io.IOHandler,\n private loadOptions: io.LoadOptions = {}) {\n if (loadOptions == null) {\n this.loadOptions = {};\n }\n this.resourceManager = new ResourceManager();\n }\n\n private findIOHandler() {\n const path = this.modelUrl;\n if ((path as io.IOHandler).load != null) {\n // Path is an IO Handler.\n this.handler = path as io.IOHandler;\n } else if (this.loadOptions.requestInit != null) {\n this.handler = io.browserHTTPRequest(path as string, this.loadOptions);\n } else {\n const handlers = io.getLoadHandlers(path as string, this.loadOptions);\n if (handlers.length === 0) {\n // For backward compatibility: if no load handler can be found,\n // assume it is a relative http path.\n handlers.push(io.browserHTTPRequest(path as string, this.loadOptions));\n } else if (handlers.length > 1) {\n throw new Error(\n `Found more than one (${handlers.length}) load handlers for ` +\n `URL '${[path]}'`);\n }\n this.handler = handlers[0];\n }\n }\n\n /**\n * Loads the model and weight files, construct the in memory weight map and\n * compile the inference graph.\n */\n async load(): Promise {\n this.findIOHandler();\n if (this.handler.load == null) {\n throw new Error(\n 'Cannot proceed with model loading because the IOHandler provided ' +\n 'does not have the `load` method implemented.');\n }\n const artifacts = await this.handler.load();\n\n return this.loadSync(artifacts);\n }\n\n /**\n * Synchronously construct the in memory weight map and\n * compile the inference graph. Also initialize hashtable if any.\n *\n * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}\n */\n loadSync(artifacts: io.ModelArtifacts) {\n this.artifacts = artifacts;\n const graph = this.artifacts.modelTopology as tensorflow.IGraphDef;\n\n let signature;\n if (this.artifacts.userDefinedMetadata != null &&\n this.artifacts.userDefinedMetadata.signature != null) {\n signature = // tslint:disable-next-line:no-any\n (this.artifacts.userDefinedMetadata as any).signature as\n tensorflow.ISignatureDef;\n } else {\n signature = this.artifacts.signature;\n }\n this.signature = signature;\n\n this.version = `${graph.versions.producer}.${graph.versions.minConsumer}`;\n const weightMap =\n io.decodeWeights(this.artifacts.weightData, this.artifacts.weightSpecs);\n this.executor = new GraphExecutor(\n OperationMapper.Instance.transformGraph(graph, this.signature));\n this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap);\n // Attach a model-level resourceManager to each executor to share resources,\n // such as `HashTable`.\n this.executor.resourceManager = this.resourceManager;\n\n if (artifacts.modelInitializer != null &&\n (artifacts.modelInitializer as tensorflow.IGraphDef).node != null) {\n const initializer =\n OperationMapper.Instance.transformGraph(artifacts.modelInitializer);\n this.initializer = new GraphExecutor(initializer);\n this.initializer.weightMap = this.executor.weightMap;\n // Attach a model-level resourceManager to the initializer, the\n // hashTables created from when executing the initializer will be stored\n // in the resourceManager.\n this.initializer.resourceManager = this.resourceManager;\n this.initializer.executeAsync({}, []);\n }\n\n return true;\n }\n\n /**\n * Save the configuration and/or weights of the GraphModel.\n *\n * An `IOHandler` is an object that has a `save` method of the proper\n * signature defined. The `save` method manages the storing or\n * transmission of serialized data (\"artifacts\") that represent the\n * model's topology and weights onto or via a specific medium, such as\n * file downloads, local storage, IndexedDB in the web browser and HTTP\n * requests to a server. TensorFlow.js provides `IOHandler`\n * implementations for a number of frequently used saving mediums, such as\n * `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`\n * for more details.\n *\n * This method also allows you to refer to certain types of `IOHandler`s\n * as URL-like string shortcuts, such as 'localstorage://' and\n * 'indexeddb://'.\n *\n * Example 1: Save `model`'s topology and weights to browser [local\n * storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);\n * then load it back.\n *\n * ```js\n * const modelUrl =\n * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';\n * const model = await tf.loadGraphModel(modelUrl);\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n *\n * const saveResults = await model.save('localstorage://my-model-1');\n *\n * const loadedModel = await tf.loadGraphModel('localstorage://my-model-1');\n * console.log('Prediction from loaded model:');\n * model.predict(zeros).print();\n * ```\n *\n * @param handlerOrURL An instance of `IOHandler` or a URL-like,\n * scheme-based string shortcut for `IOHandler`.\n * @param config Options for saving the model.\n * @returns A `Promise` of `SaveResult`, which summarizes the result of\n * the saving, such as byte sizes of the saved artifacts for the model's\n * topology and weight values.\n *\n * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}\n */\n async save(handlerOrURL: io.IOHandler|string, config?: io.SaveConfig):\n Promise {\n if (typeof handlerOrURL === 'string') {\n const handlers = io.getSaveHandlers(handlerOrURL);\n if (handlers.length === 0) {\n throw new Error(\n `Cannot find any save handlers for URL '${handlerOrURL}'`);\n } else if (handlers.length > 1) {\n throw new Error(\n `Found more than one (${handlers.length}) save handlers for ` +\n `URL '${handlerOrURL}'`);\n }\n handlerOrURL = handlers[0];\n }\n if (handlerOrURL.save == null) {\n throw new Error(\n 'GraphModel.save() cannot proceed because the IOHandler ' +\n 'provided does not have the `save` attribute defined.');\n }\n\n return handlerOrURL.save(this.artifacts);\n }\n\n /**\n * Execute the inference for the input tensors.\n *\n * @param input The input tensors, when there is single input for the model,\n * inputs param should be a `tf.Tensor`. For models with mutliple inputs,\n * inputs params should be in either `tf.Tensor`[] if the input order is\n * fixed, or otherwise NamedTensorMap format.\n *\n * For model with multiple inputs, we recommend you use NamedTensorMap as the\n * input type, if you use `tf.Tensor`[], the order of the array needs to\n * follow the\n * order of inputNodes array. @see {@link GraphModel.inputNodes}\n *\n * You can also feed any intermediate nodes using the NamedTensorMap as the\n * input type. For example, given the graph\n * InputNode => Intermediate => OutputNode,\n * you can execute the subgraph Intermediate => OutputNode by calling\n * model.execute('IntermediateNode' : tf.tensor(...));\n *\n * This is useful for models that uses tf.dynamic_rnn, where the intermediate\n * state needs to be fed manually.\n *\n * For batch inference execution, the tensors for each input need to be\n * concatenated together. For example with mobilenet, the required input shape\n * is [1, 244, 244, 3], which represents the [batch, height, width, channel].\n * If we are provide a batched data of 100 images, the input tensor should be\n * in the shape of [100, 244, 244, 3].\n *\n * @param config Prediction configuration for specifying the batch size and\n * output node names. Currently the batch size option is ignored for graph\n * model.\n *\n * @returns Inference result tensors. The output would be single `tf.Tensor`\n * if model has single output node, otherwise Tensor[] or NamedTensorMap[]\n * will be returned for model with multiple outputs.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n predict(inputs: Tensor|Tensor[]|NamedTensorMap, config?: ModelPredictConfig):\n Tensor|Tensor[]|NamedTensorMap {\n return this.execute(inputs, this.outputNodes);\n }\n\n private normalizeInputs(inputs: Tensor|Tensor[]|\n NamedTensorMap): NamedTensorMap {\n if (!(inputs instanceof Tensor) && !Array.isArray(inputs)) {\n // The input is already a NamedTensorMap.\n return inputs;\n }\n inputs = Array.isArray(inputs) ? inputs : [inputs];\n if (inputs.length !== this.inputNodes.length) {\n throw new Error(\n 'Input tensor count mismatch,' +\n `the graph model has ${this.inputNodes.length} placeholders, ` +\n `while there are ${inputs.length} input tensors.`);\n }\n return this.inputNodes.reduce((map, inputName, i) => {\n map[inputName] = (inputs as Tensor[])[i];\n return map;\n }, {} as NamedTensorMap);\n }\n\n private normalizeOutputs(outputs: string|string[]): string[] {\n outputs = outputs || this.outputNodes;\n return !Array.isArray(outputs) ? [outputs] : outputs;\n }\n\n /**\n * Executes inference for the model for given input tensors.\n * @param inputs tensor, tensor array or tensor map of the inputs for the\n * model, keyed by the input node names.\n * @param outputs output node name from the Tensorflow model, if no\n * outputs are specified, the default outputs of the model would be used.\n * You can inspect intermediate nodes of the model by adding them to the\n * outputs array.\n *\n * @returns A single tensor if provided with a single output or no outputs\n * are provided and there is only one default output, otherwise return a\n * tensor array. The order of the tensor array is the same as the outputs\n * if provided, otherwise the order of outputNodes attribute of the model.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n execute(inputs: Tensor|Tensor[]|NamedTensorMap, outputs?: string|string[]):\n Tensor|Tensor[] {\n inputs = this.normalizeInputs(inputs);\n outputs = this.normalizeOutputs(outputs);\n const result = this.executor.execute(inputs, outputs);\n return result.length > 1 ? result : result[0];\n }\n /**\n * Executes inference for the model for given input tensors in async\n * fashion, use this method when your model contains control flow ops.\n * @param inputs tensor, tensor array or tensor map of the inputs for the\n * model, keyed by the input node names.\n * @param outputs output node name from the Tensorflow model, if no outputs\n * are specified, the default outputs of the model would be used. You can\n * inspect intermediate nodes of the model by adding them to the outputs\n * array.\n *\n * @returns A Promise of single tensor if provided with a single output or\n * no outputs are provided and there is only one default output, otherwise\n * return a tensor map.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async executeAsync(\n inputs: Tensor|Tensor[]|NamedTensorMap,\n outputs?: string|string[]): Promise {\n inputs = this.normalizeInputs(inputs);\n outputs = this.normalizeOutputs(outputs);\n const result = await this.executor.executeAsync(inputs, outputs);\n return result.length > 1 ? result : result[0];\n }\n\n private convertTensorMapToTensorsMap(map: NamedTensorMap): NamedTensorsMap {\n return Object.keys(map).reduce((newMap: NamedTensorsMap, key) => {\n newMap[key] = [map[key]];\n return newMap;\n }, {});\n }\n\n /**\n * Releases the memory used by the weight tensors and resourceManager.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n dispose() {\n this.executor.dispose();\n\n if (this.initializer) {\n this.initializer.dispose();\n }\n\n this.resourceManager.dispose();\n }\n}\n\n/**\n * Load a graph model given a URL to the model definition.\n *\n * Example of loading MobileNetV2 from a URL and making a prediction with a\n * zeros input:\n *\n * ```js\n * const modelUrl =\n * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';\n * const model = await tf.loadGraphModel(modelUrl);\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n * ```\n *\n * Example of loading MobileNetV2 from a TF Hub URL and making a prediction with\n * a zeros input:\n *\n * ```js\n * const modelUrl =\n * 'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';\n * const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true});\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n * ```\n * @param modelUrl The url or an `io.IOHandler` that loads the model.\n * @param options Options for the HTTP request, which allows to send credentials\n * and custom headers.\n *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport async function loadGraphModel(\n modelUrl: string|io.IOHandler,\n options: io.LoadOptions = {}): Promise {\n if (modelUrl == null) {\n throw new Error(\n 'modelUrl in loadGraphModel() cannot be null. Please provide a url ' +\n 'or an IOHandler that loads the model');\n }\n if (options == null) {\n options = {};\n }\n\n if (options.fromTFHub) {\n if ((modelUrl as io.IOHandler).load == null) {\n if (!(modelUrl as string).endsWith('/')) {\n modelUrl = (modelUrl as string) + '/';\n }\n modelUrl = `${modelUrl}${DEFAULT_MODEL_NAME}${TFHUB_SEARCH_PARAM}`;\n }\n }\n const model = new GraphModel(modelUrl, options);\n await model.load();\n return model;\n}\n","/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '3.7.0';\nexport {version};\n"],"names":["util","clone","json","env","tensorflow.DataType","tfOps.add","tfOps.addN","tfOps.mod","tfOps.mul","tfOps.div","tfOps.divNoNan","tfOps.floorDiv","tfOps.sub","tfOps.minimum","tfOps.maximum","tfOps.pow","tfOps.squaredDifference","executeOp","tfOps.abs","tfOps.acos","tfOps.acosh","tfOps.asin","tfOps.asinh","tfOps.atan","tfOps.atan2","tfOps.atanh","tfOps.ceil","tfOps.complex","tfOps.cos","tfOps.cosh","tfOps.elu","tfOps.erf","tfOps.exp","tfOps.expm1","tfOps.floor","tfOps.log","tfOps.log1p","tfOps.imag","tfOps.neg","tfOps.reciprocal","tfOps.real","tfOps.relu","tfOps.round","tfOps.selu","tfOps.sigmoid","tfOps.sin","tfOps.sign","tfOps.sinh","tfOps.softplus","tfOps.sqrt","tfOps.square","tfOps.tanh","tfOps.tan","tfOps.clipByValue","tfOps.relu6","tfOps.rsqrt","tfOps.prod","tfOps.leakyRelu","tfOps.prelu","tfOps.isNaN","scalar","keep","tensor","stack","concat","unstack","tidy","reshape","slice","tfOps.conv1d","tfOps.conv2d","tfOps.fused","tfOps.conv2dTranspose","tfOps.depthwiseConv2d","tfOps.conv3d","tfOps.avgPool","tfOps.maxPool","tfOps.avgPool3d","tfOps.maxPool3d","tfOps.dilation2d","tfOps.fill","tfOps.linspace","tfOps.multinomial","tfOps.oneHot","tfOps.ones","tfOps.onesLike","tfOps.randomUniform","tfOps.range","tfOps.truncatedNormal","tfOps.zeros","tfOps.zerosLike","tfOps.image","tfOps.cast","tfOps.whereAsync","tfOps.setdiff1dAsync","tfOps.topk","tfOps.unique","tfOps.tensor1d","tfOps.scalar","tfOps.equal","tfOps.notEqual","tfOps.greater","tfOps.greaterEqual","tfOps.less","tfOps.lessEqual","tfOps.logicalAnd","tfOps.logicalNot","tfOps.logicalOr","tfOps.where","tfOps.matMul","tfOps.einsum","tfOps.transpose","tfOps.batchNorm","tfOps.localResponseNormalization","tfOps.softmax","tfOps.logSoftmax","tfOps.sparseToDense","tfOps.max","tfOps.mean","tfOps.min","tfOps.sum","tfOps.all","tfOps.any","tfOps.argMax","tfOps.argMin","tfOps.cumsum","tfOps.bincount","tfOps.denseBincount","tfOps.concat","tfOps.gather","tfOps.reverse","tfOps.slice","tfOps.stridedSlice","tfOps.squeeze","tfOps.reshape","tfOps.stack","tfOps.unstack","tfOps.tile","tfOps.split","tfOps.scatterND","tfOps.gatherND","tfOps.sparse","tfOps.fft","tfOps.ifft","tfOps.rfft","tfOps.irfft","tfOps.string","tfOps.expandDims","tfOps.mirrorPad","tfOps.pad","tfOps.spaceToBatchND","tfOps.batchToSpaceND","tfOps.depthToSpace","tfOps.broadcastTo","tfc.tidy","arithmetic.executeOp","basicMath.executeOp","control.executeOp","convolution.executeOp","creation.executeOp","dynamic.executeOp","evaluation.executeOp","image.executeOp","graph.executeOp","logical.executeOp","matrices.executeOp","normalization.executeOp","reduction.executeOp","sliceJoin.executeOp","sparse.executeOp","spectral.executeOp","string.executeOp","transformation.executeOp","hashTable.executeOp","tfc.util","tslib_1.__spread","io","Tensor"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAA;;;;;;;;;;;;;;;;;IA6BA;IACA,IAAY,QA8BX;IA9BD,WAAY,QAAQ;QAClB,mDAAgB,CAAA;QAChB,+CAAc,CAAA;QACd,iDAAe,CAAA;QACf,+CAAc,CAAA;QACd,+CAAc,CAAA;QACd,+CAAc,CAAA;QACd,6CAAa,CAAA;QACb,iDAAe,CAAA;QACf,uDAAkB,CAAA;QAClB,+CAAc,CAAA;QACd,8CAAc,CAAA;QACd,gDAAe,CAAA;QACf,kDAAgB,CAAA;QAChB,kDAAgB,CAAA;QAChB,sDAAkB,CAAA;QAClB,yDAAoB,CAAA;QACpB,2DAAqB,CAAA;QACrB,yDAAoB,CAAA;QACpB,yDAAoB,CAAA;QACpB,yDAAoB,CAAA;QACpB,uDAAmB,CAAA;QACnB,2DAAqB,CAAA;QACrB,iEAAwB,CAAA;QACxB,yDAAoB,CAAA;QACpB,uDAAmB,CAAA;QACnB,yDAAoB,CAAA;QACpB,2DAAqB,CAAA;QACrB,2DAAqB,CAAA;QACrB,+DAAuB,CAAA;IACzB,CAAC,EA9BW,QAAQ,KAAR,QAAQ,QA8BnB;QA2PgB,QAAQ,CAGxB;IAHD,WAAiB,QAAQ;;QAEvB,IAAY,uBAA0D;QAAtE,WAAY,uBAAuB;YAAE,yEAAY,CAAA;YAAE,iEAAQ,CAAA;YAAE,iEAAQ,CAAA;SAAC,EAA1D,uBAAuB,GAAvB,gCAAuB,KAAvB,gCAAuB,QAAmC;I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G,IAAI,UAAU,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;wBAChD,qBAAM,KAAK,CAAC,IAAI,EAAE,EAAA;;wBAAlB,SAAkB,CAAC;wBACnB,sBAAO,KAAK,EAAC;;;;;;ICxbf;IAEA;QACM,OAAO,GAAG;;;;;;;;;;;;;;;;"}
\ No newline at end of file
diff --git a/thirdparty/tfjs/tf-core.js b/thirdparty/tfjs/tf-core.js
new file mode 100644
index 0000000..5898f7b
--- /dev/null
+++ b/thirdparty/tfjs/tf-core.js
@@ -0,0 +1,27681 @@
+/**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
+ (global = global || self, factory(global.tf = global.tf || {}));
+}(this, (function (exports) { 'use strict';
+
+ /*! *****************************************************************************
+ Copyright (c) Microsoft Corporation.
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ PERFORMANCE OF THIS SOFTWARE.
+ ***************************************************************************** */
+ /* global Reflect, Promise */
+
+ var extendStatics = function(d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ };
+
+ function __extends(d, b) {
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ }
+
+ function __awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ }
+
+ function __generator(thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (_) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var EPSILON_FLOAT32 = 1e-7;
+ var EPSILON_FLOAT16 = 1e-4;
+ /** Convenient class for storing tensor-related data. */
+ var DataStorage = /** @class */ (function () {
+ function DataStorage(backend, dataMover) {
+ this.backend = backend;
+ this.dataMover = dataMover;
+ this.data = new WeakMap();
+ this.dataIdsCount = 0;
+ }
+ DataStorage.prototype.get = function (dataId) {
+ if (!this.data.has(dataId)) {
+ this.dataMover.moveData(this.backend, dataId);
+ }
+ return this.data.get(dataId);
+ };
+ DataStorage.prototype.set = function (dataId, value) {
+ this.dataIdsCount++;
+ this.data.set(dataId, value);
+ };
+ DataStorage.prototype.has = function (dataId) {
+ return this.data.has(dataId);
+ };
+ DataStorage.prototype.delete = function (dataId) {
+ this.dataIdsCount--;
+ return this.data.delete(dataId);
+ };
+ DataStorage.prototype.numDataIds = function () {
+ return this.dataIdsCount;
+ };
+ return DataStorage;
+ }());
+ /**
+ * The interface that defines the kernels that should be implemented when
+ * adding a new backend. New backends don't need to implement every one of the
+ * methods, this can be done gradually (throw an error for unimplemented
+ * methods).
+ */
+ var KernelBackend = /** @class */ (function () {
+ function KernelBackend() {
+ }
+ KernelBackend.prototype.refCount = function (dataId) {
+ return notYetImplemented('refCount');
+ };
+ KernelBackend.prototype.incRef = function (dataId) {
+ return notYetImplemented('incRef');
+ };
+ KernelBackend.prototype.timerAvailable = function () {
+ return true;
+ };
+ KernelBackend.prototype.time = function (f) {
+ return notYetImplemented('time');
+ };
+ KernelBackend.prototype.read = function (dataId) {
+ return notYetImplemented('read');
+ };
+ KernelBackend.prototype.readSync = function (dataId) {
+ return notYetImplemented('readSync');
+ };
+ KernelBackend.prototype.numDataIds = function () {
+ return notYetImplemented('numDataIds');
+ };
+ KernelBackend.prototype.disposeData = function (dataId, force) {
+ return notYetImplemented('disposeData');
+ };
+ KernelBackend.prototype.write = function (values, shape, dtype) {
+ return notYetImplemented('write');
+ };
+ KernelBackend.prototype.move = function (dataId, values, shape, dtype, refCount) {
+ return notYetImplemented('move');
+ };
+ KernelBackend.prototype.memory = function () {
+ return notYetImplemented('memory');
+ };
+ /** Returns the highest precision for floats in bits (e.g. 16 or 32) */
+ KernelBackend.prototype.floatPrecision = function () {
+ return notYetImplemented('floatPrecision');
+ };
+ /** Returns the smallest representable number. */
+ KernelBackend.prototype.epsilon = function () {
+ return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
+ };
+ KernelBackend.prototype.dispose = function () {
+ return notYetImplemented('dispose');
+ };
+ return KernelBackend;
+ }());
+ function notYetImplemented(kernelName) {
+ throw new Error("'" + kernelName + "' not yet implemented or not found in the registry. " +
+ "This kernel may not be supported by the tfjs backend you have chosen");
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Shuffles the array in-place using Fisher-Yates algorithm.
+ *
+ * ```js
+ * const a = [1, 2, 3, 4, 5];
+ * tf.util.shuffle(a);
+ * console.log(a);
+ * ```
+ *
+ * @param array The array to shuffle in-place.
+ *
+ * @doc {heading: 'Util', namespace: 'util'}
+ */
+ // tslint:disable-next-line:no-any
+ function shuffle(array) {
+ var counter = array.length;
+ var temp = 0;
+ var index = 0;
+ // While there are elements in the array
+ while (counter > 0) {
+ // Pick a random index
+ index = (Math.random() * counter) | 0;
+ // Decrease counter by 1
+ counter--;
+ // And swap the last element with it
+ temp = array[counter];
+ array[counter] = array[index];
+ array[index] = temp;
+ }
+ }
+ /**
+ * Shuffles two arrays in-place the same way using Fisher-Yates algorithm.
+ *
+ * ```js
+ * const a = [1,2,3,4,5];
+ * const b = [11,22,33,44,55];
+ * tf.util.shuffleCombo(a, b);
+ * console.log(a, b);
+ * ```
+ *
+ * @param array The first array to shuffle in-place.
+ * @param array2 The second array to shuffle in-place with the same permutation
+ * as the first array.
+ *
+ * @doc {heading: 'Util', namespace: 'util'}
+ */
+ function shuffleCombo(
+ // tslint:disable-next-line:no-any
+ array,
+ // tslint:disable-next-line:no-any
+ array2) {
+ if (array.length !== array2.length) {
+ throw new Error("Array sizes must match to be shuffled together " +
+ ("First array length was " + array.length) +
+ ("Second array length was " + array2.length));
+ }
+ var counter = array.length;
+ var temp, temp2;
+ var index = 0;
+ // While there are elements in the array
+ while (counter > 0) {
+ // Pick a random index
+ index = (Math.random() * counter) | 0;
+ // Decrease counter by 1
+ counter--;
+ // And swap the last element of each array with it
+ temp = array[counter];
+ temp2 = array2[counter];
+ array[counter] = array[index];
+ array2[counter] = array2[index];
+ array[index] = temp;
+ array2[index] = temp2;
+ }
+ }
+ /** Clamps a value to a specified range. */
+ function clamp(min, x, max) {
+ return Math.max(min, Math.min(x, max));
+ }
+ function nearestLargerEven(val) {
+ return val % 2 === 0 ? val : val + 1;
+ }
+ function sum(arr) {
+ var sum = 0;
+ for (var i = 0; i < arr.length; i++) {
+ sum += arr[i];
+ }
+ return sum;
+ }
+ /**
+ * Returns a sample from a uniform [a, b) distribution.
+ *
+ * @param a The minimum support (inclusive).
+ * @param b The maximum support (exclusive).
+ * @return A pseudorandom number on the half-open interval [a,b).
+ */
+ function randUniform(a, b) {
+ var r = Math.random();
+ return (b * r) + (1 - r) * a;
+ }
+ /** Returns the squared Euclidean distance between two vectors. */
+ function distSquared(a, b) {
+ var result = 0;
+ for (var i = 0; i < a.length; i++) {
+ var diff = Number(a[i]) - Number(b[i]);
+ result += diff * diff;
+ }
+ return result;
+ }
+ /**
+ * Asserts that the expression is true. Otherwise throws an error with the
+ * provided message.
+ *
+ * ```js
+ * const x = 2;
+ * tf.util.assert(x === 2, 'x is not 2');
+ * ```
+ *
+ * @param expr The expression to assert (as a boolean).
+ * @param msg A function that returns the message to report when throwing an
+ * error. We use a function for performance reasons.
+ *
+ * @doc {heading: 'Util', namespace: 'util'}
+ */
+ function assert(expr, msg) {
+ if (!expr) {
+ throw new Error(typeof msg === 'string' ? msg : msg());
+ }
+ }
+ function assertShapesMatch(shapeA, shapeB, errorMessagePrefix) {
+ if (errorMessagePrefix === void 0) { errorMessagePrefix = ''; }
+ assert(arraysEqual(shapeA, shapeB), function () { return errorMessagePrefix + (" Shapes " + shapeA + " and " + shapeB + " must match"); });
+ }
+ function assertNonNull(a) {
+ assert(a != null, function () { return "The input to the tensor constructor must be a non-null value."; });
+ }
+ // NOTE: We explicitly type out what T extends instead of any so that
+ // util.flatten on a nested array of number doesn't try to infer T as a
+ // number[][], causing us to explicitly type util.flatten().
+ /**
+ * Flattens an arbitrarily nested array.
+ *
+ * ```js
+ * const a = [[1, 2], [3, 4], [5, [6, [7]]]];
+ * const flat = tf.util.flatten(a);
+ * console.log(flat);
+ * ```
+ *
+ * @param arr The nested array to flatten.
+ * @param result The destination array which holds the elements.
+ * @param skipTypedArray If true, avoids flattening the typed arrays. Defaults
+ * to false.
+ *
+ * @doc {heading: 'Util', namespace: 'util'}
+ */
+ function flatten(arr, result, skipTypedArray) {
+ if (result === void 0) { result = []; }
+ if (skipTypedArray === void 0) { skipTypedArray = false; }
+ if (result == null) {
+ result = [];
+ }
+ if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) {
+ for (var i = 0; i < arr.length; ++i) {
+ flatten(arr[i], result, skipTypedArray);
+ }
+ }
+ else {
+ result.push(arr);
+ }
+ return result;
+ }
+ /**
+ * Returns the size (number of elements) of the tensor given its shape.
+ *
+ * ```js
+ * const shape = [3, 4, 2];
+ * const size = tf.util.sizeFromShape(shape);
+ * console.log(size);
+ * ```
+ *
+ * @doc {heading: 'Util', namespace: 'util'}
+ */
+ function sizeFromShape(shape) {
+ if (shape.length === 0) {
+ // Scalar.
+ return 1;
+ }
+ var size = shape[0];
+ for (var i = 1; i < shape.length; i++) {
+ size *= shape[i];
+ }
+ return size;
+ }
+ function isScalarShape(shape) {
+ return shape.length === 0;
+ }
+ function arraysEqual(n1, n2) {
+ if (n1 === n2) {
+ return true;
+ }
+ if (n1 == null || n2 == null) {
+ return false;
+ }
+ if (n1.length !== n2.length) {
+ return false;
+ }
+ for (var i = 0; i < n1.length; i++) {
+ if (n1[i] !== n2[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+ function isInt(a) {
+ return a % 1 === 0;
+ }
+ function tanh(x) {
+ // tslint:disable-next-line:no-any
+ if (Math.tanh != null) {
+ // tslint:disable-next-line:no-any
+ return Math.tanh(x);
+ }
+ if (x === Infinity) {
+ return 1;
+ }
+ else if (x === -Infinity) {
+ return -1;
+ }
+ else {
+ var e2x = Math.exp(2 * x);
+ return (e2x - 1) / (e2x + 1);
+ }
+ }
+ function sizeToSquarishShape(size) {
+ var width = Math.ceil(Math.sqrt(size));
+ return [width, Math.ceil(size / width)];
+ }
+ /**
+ * Creates a new array with randomized indicies to a given quantity.
+ *
+ * ```js
+ * const randomTen = tf.util.createShuffledIndices(10);
+ * console.log(randomTen);
+ * ```
+ *
+ * @param number Quantity of how many shuffled indicies to create.
+ *
+ * @doc {heading: 'Util', namespace: 'util'}
+ */
+ function createShuffledIndices(n) {
+ var shuffledIndices = new Uint32Array(n);
+ for (var i = 0; i < n; ++i) {
+ shuffledIndices[i] = i;
+ }
+ shuffle(shuffledIndices);
+ return shuffledIndices;
+ }
+ function rightPad(a, size) {
+ if (size <= a.length) {
+ return a;
+ }
+ return a + ' '.repeat(size - a.length);
+ }
+ function repeatedTry(checkFn, delayFn, maxCounter) {
+ if (delayFn === void 0) { delayFn = function (counter) { return 0; }; }
+ return new Promise(function (resolve, reject) {
+ var tryCount = 0;
+ var tryFn = function () {
+ if (checkFn()) {
+ resolve();
+ return;
+ }
+ tryCount++;
+ var nextBackoff = delayFn(tryCount);
+ if (maxCounter != null && tryCount >= maxCounter) {
+ reject();
+ return;
+ }
+ setTimeout(tryFn, nextBackoff);
+ };
+ tryFn();
+ });
+ }
+ /**
+ * Given the full size of the array and a shape that may contain -1 as the
+ * implicit dimension, returns the inferred shape where -1 is replaced.
+ * E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].
+ *
+ * @param shape The shape, which may contain -1 in some dimension.
+ * @param size The full size (number of elements) of the array.
+ * @return The inferred shape where -1 is replaced with the inferred size.
+ */
+ function inferFromImplicitShape(shape, size) {
+ var shapeProd = 1;
+ var implicitIdx = -1;
+ for (var i = 0; i < shape.length; ++i) {
+ if (shape[i] >= 0) {
+ shapeProd *= shape[i];
+ }
+ else if (shape[i] === -1) {
+ if (implicitIdx !== -1) {
+ throw Error("Shapes can only have 1 implicit size. " +
+ ("Found -1 at dim " + implicitIdx + " and dim " + i));
+ }
+ implicitIdx = i;
+ }
+ else if (shape[i] < 0) {
+ throw Error("Shapes can not be < 0. Found " + shape[i] + " at dim " + i);
+ }
+ }
+ if (implicitIdx === -1) {
+ if (size > 0 && size !== shapeProd) {
+ throw Error("Size(" + size + ") must match the product of shape " + shape);
+ }
+ return shape;
+ }
+ if (shapeProd === 0) {
+ throw Error("Cannot infer the missing size in [" + shape + "] when " +
+ "there are 0 elements");
+ }
+ if (size % shapeProd !== 0) {
+ throw Error("The implicit shape can't be a fractional number. " +
+ ("Got " + size + " / " + shapeProd));
+ }
+ var newShape = shape.slice();
+ newShape[implicitIdx] = size / shapeProd;
+ return newShape;
+ }
+ function parseAxisParam(axis, shape) {
+ var rank = shape.length;
+ // Normalize input
+ axis = axis == null ? shape.map(function (s, i) { return i; }) : [].concat(axis);
+ // Check for valid range
+ assert(axis.every(function (ax) { return ax >= -rank && ax < rank; }), function () {
+ return "All values in axis param must be in range [-" + rank + ", " + rank + ") but " +
+ ("got axis " + axis);
+ });
+ // Check for only integers
+ assert(axis.every(function (ax) { return isInt(ax); }), function () { return "All values in axis param must be integers but " +
+ ("got axis " + axis); });
+ // Handle negative axis.
+ return axis.map(function (a) { return a < 0 ? rank + a : a; });
+ }
+ /** Reduces the shape by removing all dimensions of shape 1. */
+ function squeezeShape(shape, axis) {
+ var newShape = [];
+ var keptDims = [];
+ var isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
+ var axes = (axis == null || isEmptyArray) ?
+ null :
+ parseAxisParam(axis, shape).sort();
+ var j = 0;
+ for (var i = 0; i < shape.length; ++i) {
+ if (axes != null) {
+ if (axes[j] === i && shape[i] !== 1) {
+ throw new Error("Can't squeeze axis " + i + " since its dim '" + shape[i] + "' is not 1");
+ }
+ if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {
+ newShape.push(shape[i]);
+ keptDims.push(i);
+ }
+ if (axes[j] <= i) {
+ j++;
+ }
+ }
+ if (shape[i] !== 1) {
+ newShape.push(shape[i]);
+ keptDims.push(i);
+ }
+ }
+ return { newShape: newShape, keptDims: keptDims };
+ }
+ function getTypedArrayFromDType(dtype, size) {
+ var values = null;
+ if (dtype == null || dtype === 'float32') {
+ values = new Float32Array(size);
+ }
+ else if (dtype === 'int32') {
+ values = new Int32Array(size);
+ }
+ else if (dtype === 'bool') {
+ values = new Uint8Array(size);
+ }
+ else {
+ throw new Error("Unknown data type " + dtype);
+ }
+ return values;
+ }
+ function getArrayFromDType(dtype, size) {
+ var values = null;
+ if (dtype == null || dtype === 'float32') {
+ values = new Float32Array(size);
+ }
+ else if (dtype === 'int32') {
+ values = new Int32Array(size);
+ }
+ else if (dtype === 'bool') {
+ values = new Uint8Array(size);
+ }
+ else if (dtype === 'string') {
+ values = new Array(size);
+ }
+ else {
+ throw new Error("Unknown data type " + dtype);
+ }
+ return values;
+ }
+ function checkConversionForErrors(vals, dtype) {
+ for (var i = 0; i < vals.length; i++) {
+ var num = vals[i];
+ if (isNaN(num) || !isFinite(num)) {
+ throw Error("A tensor of type " + dtype + " being uploaded contains " + num + ".");
+ }
+ }
+ }
+ /** Returns true if the dtype is valid. */
+ function isValidDtype(dtype) {
+ return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||
+ dtype === 'int32' || dtype === 'string';
+ }
+ /**
+ * Returns true if the new type can't encode the old type without loss of
+ * precision.
+ */
+ function hasEncodingLoss(oldType, newType) {
+ if (newType === 'complex64') {
+ return false;
+ }
+ if (newType === 'float32' && oldType !== 'complex64') {
+ return false;
+ }
+ if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {
+ return false;
+ }
+ if (newType === 'bool' && oldType === 'bool') {
+ return false;
+ }
+ return true;
+ }
+ function isTypedArray(a) {
+ return a instanceof Float32Array || a instanceof Int32Array ||
+ a instanceof Uint8Array;
+ }
+ function bytesPerElement(dtype) {
+ if (dtype === 'float32' || dtype === 'int32') {
+ return 4;
+ }
+ else if (dtype === 'complex64') {
+ return 8;
+ }
+ else if (dtype === 'bool') {
+ return 1;
+ }
+ else {
+ throw new Error("Unknown dtype " + dtype);
+ }
+ }
+ /**
+ * Returns the approximate number of bytes allocated in the string array - 2
+ * bytes per character. Computing the exact bytes for a native string in JS is
+ * not possible since it depends on the encoding of the html page that serves
+ * the website.
+ */
+ function bytesFromStringArray(arr) {
+ if (arr == null) {
+ return 0;
+ }
+ var bytes = 0;
+ arr.forEach(function (x) { return bytes += x.length; });
+ return bytes;
+ }
+ /** Returns true if the value is a string. */
+ function isString(value) {
+ return typeof value === 'string' || value instanceof String;
+ }
+ function isBoolean(value) {
+ return typeof value === 'boolean';
+ }
+ function isNumber(value) {
+ return typeof value === 'number';
+ }
+ function inferDtype(values) {
+ if (Array.isArray(values)) {
+ return inferDtype(values[0]);
+ }
+ if (values instanceof Float32Array) {
+ return 'float32';
+ }
+ else if (values instanceof Int32Array || values instanceof Uint8Array) {
+ return 'int32';
+ }
+ else if (isNumber(values)) {
+ return 'float32';
+ }
+ else if (isString(values)) {
+ return 'string';
+ }
+ else if (isBoolean(values)) {
+ return 'bool';
+ }
+ return 'float32';
+ }
+ function isFunction(f) {
+ return !!(f && f.constructor && f.call && f.apply);
+ }
+ function nearestDivisor(size, start) {
+ for (var i = start; i < size; ++i) {
+ if (size % i === 0) {
+ return i;
+ }
+ }
+ return size;
+ }
+ function computeStrides(shape) {
+ var rank = shape.length;
+ if (rank < 2) {
+ return [];
+ }
+ // Last dimension has implicit stride of 1, thus having D-1 (instead of D)
+ // strides.
+ var strides = new Array(rank - 1);
+ strides[rank - 2] = shape[rank - 1];
+ for (var i = rank - 3; i >= 0; --i) {
+ strides[i] = strides[i + 1] * shape[i + 1];
+ }
+ return strides;
+ }
+ function createNestedArray(offset, shape, a, isComplex) {
+ if (isComplex === void 0) { isComplex = false; }
+ var ret = new Array();
+ if (shape.length === 1) {
+ var d = shape[0] * (isComplex ? 2 : 1);
+ for (var i = 0; i < d; i++) {
+ ret[i] = a[offset + i];
+ }
+ }
+ else {
+ var d = shape[0];
+ var rest = shape.slice(1);
+ var len = rest.reduce(function (acc, c) { return acc * c; }) * (isComplex ? 2 : 1);
+ for (var i = 0; i < d; i++) {
+ ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);
+ }
+ }
+ return ret;
+ }
+ // Provide a nested array of TypedArray in given shape.
+ function toNestedArray(shape, a, isComplex) {
+ if (isComplex === void 0) { isComplex = false; }
+ if (shape.length === 0) {
+ // Scalar type should return a single number.
+ return a[0];
+ }
+ var size = shape.reduce(function (acc, c) { return acc * c; }) * (isComplex ? 2 : 1);
+ if (size === 0) {
+ // A tensor with shape zero should be turned into empty list.
+ return [];
+ }
+ if (size !== a.length) {
+ throw new Error("[" + shape + "] does not match the input size " + a.length + (isComplex ? ' for a complex tensor' : '') + ".");
+ }
+ return createNestedArray(0, shape, a, isComplex);
+ }
+ function makeOnesTypedArray(size, dtype) {
+ var array = makeZerosTypedArray(size, dtype);
+ for (var i = 0; i < array.length; i++) {
+ array[i] = 1;
+ }
+ return array;
+ }
+ function makeZerosTypedArray(size, dtype) {
+ if (dtype == null || dtype === 'float32' || dtype === 'complex64') {
+ return new Float32Array(size);
+ }
+ else if (dtype === 'int32') {
+ return new Int32Array(size);
+ }
+ else if (dtype === 'bool') {
+ return new Uint8Array(size);
+ }
+ else {
+ throw new Error("Unknown data type " + dtype);
+ }
+ }
+ /**
+ * Make nested `TypedArray` filled with zeros.
+ * @param shape The shape information for the nested array.
+ * @param dtype dtype of the array element.
+ */
+ function makeZerosNestedTypedArray(shape, dtype) {
+ var size = shape.reduce(function (prev, curr) { return prev * curr; }, 1);
+ if (dtype == null || dtype === 'float32') {
+ return toNestedArray(shape, new Float32Array(size));
+ }
+ else if (dtype === 'int32') {
+ return toNestedArray(shape, new Int32Array(size));
+ }
+ else if (dtype === 'bool') {
+ return toNestedArray(shape, new Uint8Array(size));
+ }
+ else {
+ throw new Error("Unknown data type " + dtype);
+ }
+ }
+ function assertNonNegativeIntegerDimensions(shape) {
+ shape.forEach(function (dimSize) {
+ assert(Number.isInteger(dimSize) && dimSize >= 0, function () {
+ return "Tensor must have a shape comprised of positive integers but got " +
+ ("shape [" + shape + "].");
+ });
+ });
+ }
+ /**
+ * Computes flat index for a given location (multidimentionsal index) in a
+ * Tensor/multidimensional array.
+ *
+ * @param locs Location in the tensor.
+ * @param rank Rank of the tensor.
+ * @param strides Tensor strides.
+ */
+ function locToIndex(locs, rank, strides) {
+ if (rank === 0) {
+ return 0;
+ }
+ else if (rank === 1) {
+ return locs[0];
+ }
+ var index = locs[locs.length - 1];
+ for (var i = 0; i < locs.length - 1; ++i) {
+ index += strides[i] * locs[i];
+ }
+ return index;
+ }
+ /**
+ * Computes the location (multidimensional index) in a tensor/multidimentional
+ * array for a given flat index.
+ *
+ * @param index Index in flat array.
+ * @param rank Rank of tensor.
+ * @param strides Strides of tensor.
+ */
+ function indexToLoc(index, rank, strides) {
+ if (rank === 0) {
+ return [];
+ }
+ else if (rank === 1) {
+ return [index];
+ }
+ var locs = new Array(rank);
+ for (var i = 0; i < locs.length - 1; ++i) {
+ locs[i] = Math.floor(index / strides[i]);
+ index -= locs[i] * strides[i];
+ }
+ locs[locs.length - 1] = index;
+ return locs;
+ }
+ /**
+ * This method asserts whether an object is a Promise instance.
+ * @param object
+ */
+ // tslint:disable-next-line: no-any
+ function isPromise(object) {
+ // We chose to not use 'obj instanceOf Promise' for two reasons:
+ // 1. It only reliably works for es6 Promise, not other Promise
+ // implementations.
+ // 2. It doesn't work with framework that uses zone.js. zone.js monkey patch
+ // the async calls, so it is possible the obj (patched) is comparing to a
+ // pre-patched Promise.
+ return object && object.then && typeof object.then === 'function';
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.
+ var TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';
+ /**
+ * The environment contains evaluated flags as well as the registered platform.
+ * This is always used as a global singleton and can be retrieved with
+ * `tf.env()`.
+ *
+ * @doc {heading: 'Environment'}
+ */
+ var Environment = /** @class */ (function () {
+ // tslint:disable-next-line: no-any
+ function Environment(global) {
+ this.global = global;
+ this.flags = {};
+ this.flagRegistry = {};
+ this.urlFlags = {};
+ // Jasmine spies on this in 'environment_test.ts'
+ this.getQueryParams = getQueryParams;
+ this.populateURLFlags();
+ }
+ Environment.prototype.setPlatform = function (platformName, platform) {
+ if (this.platform != null) {
+ console.warn("Platform " + this.platformName + " has already been set. " +
+ ("Overwriting the platform with " + platform + "."));
+ }
+ this.platformName = platformName;
+ this.platform = platform;
+ };
+ Environment.prototype.registerFlag = function (flagName, evaluationFn, setHook) {
+ this.flagRegistry[flagName] = { evaluationFn: evaluationFn, setHook: setHook };
+ // Override the flag value from the URL. This has to happen here because the
+ // environment is initialized before flags get registered.
+ if (this.urlFlags[flagName] != null) {
+ var flagValue = this.urlFlags[flagName];
+ console.warn("Setting feature override from URL " + flagName + ": " + flagValue + ".");
+ this.set(flagName, flagValue);
+ }
+ };
+ Environment.prototype.getAsync = function (flagName) {
+ return __awaiter(this, void 0, void 0, function () {
+ var _a, _b;
+ return __generator(this, function (_c) {
+ switch (_c.label) {
+ case 0:
+ if (flagName in this.flags) {
+ return [2 /*return*/, this.flags[flagName]];
+ }
+ _a = this.flags;
+ _b = flagName;
+ return [4 /*yield*/, this.evaluateFlag(flagName)];
+ case 1:
+ _a[_b] = _c.sent();
+ return [2 /*return*/, this.flags[flagName]];
+ }
+ });
+ });
+ };
+ Environment.prototype.get = function (flagName) {
+ if (flagName in this.flags) {
+ return this.flags[flagName];
+ }
+ var flagValue = this.evaluateFlag(flagName);
+ if (isPromise(flagValue)) {
+ throw new Error("Flag " + flagName + " cannot be synchronously evaluated. " +
+ "Please use getAsync() instead.");
+ }
+ this.flags[flagName] = flagValue;
+ return this.flags[flagName];
+ };
+ Environment.prototype.getNumber = function (flagName) {
+ return this.get(flagName);
+ };
+ Environment.prototype.getBool = function (flagName) {
+ return this.get(flagName);
+ };
+ Environment.prototype.getFlags = function () {
+ return this.flags;
+ };
+ Object.defineProperty(Environment.prototype, "features", {
+ // For backwards compatibility.
+ get: function () {
+ return this.flags;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Environment.prototype.set = function (flagName, value) {
+ if (this.flagRegistry[flagName] == null) {
+ throw new Error("Cannot set flag " + flagName + " as it has not been registered.");
+ }
+ this.flags[flagName] = value;
+ if (this.flagRegistry[flagName].setHook != null) {
+ this.flagRegistry[flagName].setHook(value);
+ }
+ };
+ Environment.prototype.evaluateFlag = function (flagName) {
+ if (this.flagRegistry[flagName] == null) {
+ throw new Error("Cannot evaluate flag '" + flagName + "': no evaluation function found.");
+ }
+ return this.flagRegistry[flagName].evaluationFn();
+ };
+ Environment.prototype.setFlags = function (flags) {
+ this.flags = Object.assign({}, flags);
+ };
+ Environment.prototype.reset = function () {
+ this.flags = {};
+ this.urlFlags = {};
+ this.populateURLFlags();
+ };
+ Environment.prototype.populateURLFlags = function () {
+ var _this = this;
+ if (typeof this.global === 'undefined' ||
+ typeof this.global.location === 'undefined' ||
+ typeof this.global.location.search === 'undefined') {
+ return;
+ }
+ var urlParams = this.getQueryParams(this.global.location.search);
+ if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {
+ var keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');
+ keyValues.forEach(function (keyValue) {
+ var _a = keyValue.split(':'), key = _a[0], value = _a[1];
+ _this.urlFlags[key] = parseValue(key, value);
+ });
+ }
+ };
+ return Environment;
+ }());
+ function getQueryParams(queryString) {
+ var params = {};
+ queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, function (s) {
+ var t = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ t[_i - 1] = arguments[_i];
+ }
+ decodeParam(params, t[0], t[1]);
+ return t.join('=');
+ });
+ return params;
+ }
+ function decodeParam(params, name, value) {
+ params[decodeURIComponent(name)] = decodeURIComponent(value || '');
+ }
+ function parseValue(flagName, value) {
+ value = value.toLowerCase();
+ if (value === 'true' || value === 'false') {
+ return value === 'true';
+ }
+ else if ("" + +value === value) {
+ return +value;
+ }
+ throw new Error("Could not parse value flag value " + value + " for flag " + flagName + ".");
+ }
+ /**
+ * Returns the current environment (a global singleton).
+ *
+ * The environment object contains the evaluated feature values as well as the
+ * active platform.
+ *
+ * @doc {heading: 'Environment'}
+ */
+ function env() {
+ return exports.ENV;
+ }
+ exports.ENV = null;
+ function setEnvironmentGlobal(environment) {
+ exports.ENV = environment;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // Note that the identifier globalNameSpace is scoped to this module, but will
+ // always resolve to the same global object regardless of how the module is
+ // resolved.
+ // tslint:disable-next-line:no-any
+ var globalNameSpace;
+ // tslint:disable-next-line:no-any
+ function getGlobalNamespace() {
+ if (globalNameSpace == null) {
+ // tslint:disable-next-line:no-any
+ var ns = void 0;
+ if (typeof (window) !== 'undefined') {
+ ns = window;
+ }
+ else if (typeof (global) !== 'undefined') {
+ ns = global;
+ }
+ else if (typeof (process) !== 'undefined') {
+ ns = process;
+ }
+ else if (typeof (self) !== 'undefined') {
+ ns = self;
+ }
+ else {
+ throw new Error('Could not find a global object');
+ }
+ globalNameSpace = ns;
+ }
+ return globalNameSpace;
+ }
+ // tslint:disable-next-line:no-any
+ function getGlobalMap() {
+ var ns = getGlobalNamespace();
+ if (ns._tfGlobals == null) {
+ ns._tfGlobals = new Map();
+ }
+ return ns._tfGlobals;
+ }
+ /**
+ * Returns a globally accessible 'singleton' object.
+ *
+ * @param key the name of the object
+ * @param init a function to initialize to initialize this object
+ * the first time it is fetched.
+ */
+ function getGlobal(key, init) {
+ var globalMap = getGlobalMap();
+ if (globalMap.has(key)) {
+ return globalMap.get(key);
+ }
+ else {
+ var singleton = init();
+ globalMap.set(key, singleton);
+ return globalMap.get(key);
+ }
+ }
+
+ var Abs = 'Abs';
+ var Acos = 'Acos';
+ var Acosh = 'Acosh';
+ var Add = 'Add';
+ var AddN = 'AddN';
+ var All = 'All';
+ var Any = 'Any';
+ var ArgMax = 'ArgMax';
+ var ArgMin = 'ArgMin';
+ var Asin = 'Asin';
+ var Asinh = 'Asinh';
+ var Atan = 'Atan';
+ var Atanh = 'Atanh';
+ var Atan2 = 'Atan2';
+ var AvgPool = 'AvgPool';
+ var AvgPoolGrad = 'AvgPoolGrad';
+ var AvgPool3D = 'AvgPool3D';
+ var AvgPool3DGrad = 'AvgPool3DGrad';
+ var BatchMatMul = 'BatchMatMul';
+ var BatchToSpaceND = 'BatchToSpaceND';
+ var Bincount = 'Bincount';
+ var BroadcastTo = 'BroadcastTo';
+ var Cast = 'Cast';
+ var Ceil = 'Ceil';
+ var ClipByValue = 'ClipByValue';
+ var Complex = 'Complex';
+ var ComplexAbs = 'ComplexAbs';
+ var Concat = 'Concat';
+ var Conv2D = 'Conv2D';
+ var Conv2DBackpropFilter = 'Conv2DBackpropFilter';
+ var Conv2DBackpropInput = 'Conv2DBackpropInput';
+ var Conv3D = 'Conv3D';
+ var Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';
+ var Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';
+ var Cos = 'Cos';
+ var Cosh = 'Cosh';
+ var Cumsum = 'Cumsum';
+ var CropAndResize = 'CropAndResize';
+ var DenseBincount = 'DenseBincount';
+ var DepthToSpace = 'DepthToSpace';
+ var DepthwiseConv2dNative = 'DepthwiseConv2dNative';
+ var DepthwiseConv2dNativeBackpropFilter = 'DepthwiseConv2dNativeBackpropFilter';
+ var DepthwiseConv2dNativeBackpropInput = 'DepthwiseConv2dNativeBackpropInput';
+ var Diag = 'Diag';
+ var Dilation2D = 'Dilation2D';
+ var Dilation2DBackpropInput = 'Dilation2DBackpropInput';
+ var Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';
+ var RealDiv = 'RealDiv';
+ var Einsum = 'Einsum';
+ var Elu = 'Elu';
+ var EluGrad = 'EluGrad';
+ var Erf = 'Erf';
+ var Equal = 'Equal';
+ var Exp = 'Exp';
+ var ExpandDims = 'ExpandDims';
+ var Expm1 = 'Expm1';
+ var FFT = 'FFT';
+ var Fill = 'Fill';
+ var FlipLeftRight = 'FlipLeftRight';
+ var Floor = 'Floor';
+ var FloorDiv = 'FloorDiv';
+ var FusedBatchNorm = 'FusedBatchNorm';
+ var GatherV2 = 'GatherV2';
+ var GatherNd = 'GatherNd';
+ var Greater = 'Greater';
+ var GreaterEqual = 'GreaterEqual';
+ var Identity = 'Identity';
+ var IFFT = 'IFFT';
+ var Imag = 'Imag';
+ var IsFinite = 'IsFinite';
+ var IsInf = 'IsInf';
+ var IsNan = 'IsNan';
+ var LeakyRelu = 'LeakyRelu';
+ var Less = 'Less';
+ var LessEqual = 'LessEqual';
+ var LinSpace = 'LinSpace';
+ var Log = 'Log';
+ var Log1p = 'Log1p';
+ var LogicalAnd = 'LogicalAnd';
+ var LogicalNot = 'LogicalNot';
+ var LogicalOr = 'LogicalOr';
+ var LogSoftmax = 'LogSoftmax';
+ var LRN = 'LRN';
+ var LRNGrad = 'LRNGrad';
+ var Max = 'Max';
+ var Maximum = 'Maximum';
+ var MaxPool = 'MaxPool';
+ var MaxPoolGrad = 'MaxPoolGrad';
+ var MaxPool3D = 'MaxPool3D';
+ var MaxPool3DGrad = 'MaxPool3DGrad';
+ var MaxPoolWithArgmax = 'MaxPoolWithArgmax';
+ var Mean = 'Mean';
+ var Min = 'Min';
+ var Minimum = 'Minimum';
+ var MirrorPad = 'MirrorPad';
+ var Mod = 'Mod';
+ var Multinomial = 'Multinomial';
+ var Multiply = 'Multiply';
+ var Neg = 'Neg';
+ var NotEqual = 'NotEqual';
+ var NonMaxSuppressionV3 = 'NonMaxSuppressionV3';
+ var NonMaxSuppressionV4 = 'NonMaxSuppressionV4';
+ var NonMaxSuppressionV5 = 'NonMaxSuppressionV5';
+ var OnesLike = 'OnesLike';
+ var OneHot = 'OneHot';
+ var Pack = 'Pack';
+ var PadV2 = 'PadV2';
+ var Pool = 'Pool';
+ var Pow = 'Pow';
+ var Prelu = 'Prelu';
+ var Prod = 'Prod';
+ var Range = 'Range';
+ var Real = 'Real';
+ var Reciprocal = 'Reciprocal';
+ var Relu = 'Relu';
+ var Reshape = 'Reshape';
+ var ResizeNearestNeighbor = 'ResizeNearestNeighbor';
+ var ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';
+ var ResizeBilinear = 'ResizeBilinear';
+ var ResizeBilinearGrad = 'ResizeBilinearGrad';
+ var Relu6 = 'Relu6';
+ var Reverse = 'Reverse';
+ var Round = 'Round';
+ var Rsqrt = 'Rsqrt';
+ var ScatterNd = 'ScatterNd';
+ var Select = 'Select';
+ var Selu = 'Selu';
+ var Slice = 'Slice';
+ var Sin = 'Sin';
+ var Sinh = 'Sinh';
+ var Sign = 'Sign';
+ var Sigmoid = 'Sigmoid';
+ var Softplus = 'Softplus';
+ var Sqrt = 'Sqrt';
+ var Sum = 'Sum';
+ var SpaceToBatchND = 'SpaceToBatchND';
+ var SplitV = 'SplitV';
+ var Softmax = 'Softmax';
+ var SparseFillEmptyRows = 'SparseFillEmptyRows';
+ var SparseReshape = 'SparseReshape';
+ var SparseSegmentMean = 'SparseSegmentMean';
+ var SparseSegmentSum = 'SparseSegmentSum';
+ var SparseToDense = 'SparseToDense';
+ var SquaredDifference = 'SquaredDifference';
+ var Square = 'Square';
+ var StridedSlice = 'StridedSlice';
+ var StringNGrams = 'StringNGrams';
+ var StringSplit = 'StringSplit';
+ var StringToHashBucketFast = 'StringToHashBucketFast';
+ var Sub = 'Sub';
+ var Tan = 'Tan';
+ var Tanh = 'Tanh';
+ var Tile = 'Tile';
+ var TopK = 'TopK';
+ var Transform = 'Transform';
+ var Transpose = 'Transpose';
+ var Unique = 'Unique';
+ var Unpack = 'Unpack';
+ var UnsortedSegmentSum = 'UnsortedSegmentSum';
+ var ZerosLike = 'ZerosLike';
+ /**
+ * TensorFlow.js-only kernels
+ */
+ var Step = 'Step';
+ var FromPixels = 'FromPixels';
+ var RotateWithOffset = 'RotateWithOffset';
+ var _FusedMatMul = '_FusedMatMul';
+ var FusedConv2D = 'FusedConv2D';
+ var FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var kernelRegistry = getGlobal('kernelRegistry', function () { return new Map(); });
+ var gradRegistry = getGlobal('gradRegistry', function () { return new Map(); });
+ /**
+ * Returns the kernel function (code) associated with the provided names.
+ *
+ * @param kernelName The official name of the kernel.
+ * @param backendName The official name of the backend.
+ */
+ function getKernel(kernelName, backendName) {
+ var key = makeKey(kernelName, backendName);
+ return kernelRegistry.get(key);
+ }
+ /**
+ * Returns the registered gradient info associated with the provided kernel.
+ * @param kernelName The official TF kernel name.
+ */
+ function getGradient(kernelName) {
+ return gradRegistry.get(kernelName);
+ }
+ function getKernelsForBackend(backendName) {
+ var it = kernelRegistry.entries();
+ var result = [];
+ while (true) {
+ var _a = it.next(), done = _a.done, value = _a.value;
+ if (done) {
+ break;
+ }
+ var key = value[0], config = value[1];
+ var backend = key.split('_')[0];
+ if (backend === backendName) {
+ result.push(config);
+ }
+ }
+ return result;
+ }
+ /**
+ * Registers the function (forward pass) for the kernel in a global registry.
+ *
+ * @param config A config object with the following properties:
+ * - `kernelName` The official name of the kernel.
+ * - `backendName` The official name of the backend.
+ * - `kernelFunc` The function to run during the forward pass of the kernel.
+ * - `setupFunc` Optional. Gets called once, after the backend initializes.
+ * - `disposeFunc` Optional. Gets called once, right before the backend is
+ * disposed.
+ */
+ function registerKernel(config) {
+ var kernelName = config.kernelName, backendName = config.backendName;
+ var key = makeKey(kernelName, backendName);
+ if (kernelRegistry.has(key)) {
+ console.warn("The kernel '" + kernelName + "' for backend " +
+ ("'" + backendName + "' is already registered"));
+ }
+ kernelRegistry.set(key, config);
+ }
+ /**
+ * Registers a gradient function for a given kernel in the global registry,
+ * to be used during the back-propagation of that kernel.
+ *
+ * @param config An object with the following properties:
+ * - `kernelName` The name of the kernel that the gradient function is for.
+ * - `gradFunc` The function to run during back-propagation.
+ */
+ function registerGradient(config) {
+ var kernelName = config.kernelName;
+ if (gradRegistry.has(kernelName)) {
+ // TODO (yassogba) after 3.0 assess whether we need to keep this gated
+ // to debug mode.
+ if (env().getBool('DEBUG')) {
+ console.warn("Overriding the gradient for '" + kernelName + "'");
+ }
+ }
+ gradRegistry.set(kernelName, config);
+ }
+ /**
+ * Removes the kernel function from the registry.
+ *
+ * @param kernelName The official name of the kernel.
+ * @param backendName The official name of the backend.
+ *
+ */
+ function unregisterKernel(kernelName, backendName) {
+ var key = makeKey(kernelName, backendName);
+ if (!kernelRegistry.has(key)) {
+ throw new Error("The kernel '" + kernelName + "' for backend " +
+ ("'" + backendName + "' is not registered"));
+ }
+ kernelRegistry.delete(key);
+ }
+ /** Removes the registered gradient from the global registry. */
+ function unregisterGradient(kernelName) {
+ if (!gradRegistry.has(kernelName)) {
+ throw new Error("The gradient '" + kernelName + "' for backend is not registered");
+ }
+ gradRegistry.delete(kernelName);
+ }
+ /**
+ * Finds kernels that have already been registered to a backend and re-registers
+ * them for a new backend. Useful for registering custom backends.
+ * @param registeredBackendName Already registered backend.
+ * @param newBackendName New backend.
+ */
+ function copyRegisteredKernels(registeredBackendName, newBackendName) {
+ var kernels = getKernelsForBackend(registeredBackendName);
+ kernels.forEach(function (kernelConfig) {
+ var newKernelConfig = Object.assign({}, kernelConfig, { backendName: newBackendName });
+ registerKernel(newKernelConfig);
+ });
+ }
+ function makeKey(kernelName, backendName) {
+ return backendName + "_" + kernelName;
+ }
+
+ var long_1 = Long;
+
+ /**
+ * wasm optimizations, to do native i64 multiplication and divide
+ */
+ var wasm = null;
+
+ try {
+ wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
+ 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11
+ ])), {}).exports;
+ } catch (e) {
+ // no wasm support :(
+ }
+
+ /**
+ * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
+ * See the from* functions below for more convenient ways of constructing Longs.
+ * @exports Long
+ * @class A Long class for representing a 64 bit two's-complement integer value.
+ * @param {number} low The low (signed) 32 bits of the long
+ * @param {number} high The high (signed) 32 bits of the long
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @constructor
+ */
+ function Long(low, high, unsigned) {
+
+ /**
+ * The low 32 bits as a signed value.
+ * @type {number}
+ */
+ this.low = low | 0;
+
+ /**
+ * The high 32 bits as a signed value.
+ * @type {number}
+ */
+ this.high = high | 0;
+
+ /**
+ * Whether unsigned or not.
+ * @type {boolean}
+ */
+ this.unsigned = !!unsigned;
+ }
+
+ // The internal representation of a long is the two given signed, 32-bit values.
+ // We use 32-bit pieces because these are the size of integers on which
+ // Javascript performs bit-operations. For operations like addition and
+ // multiplication, we split each number into 16 bit pieces, which can easily be
+ // multiplied within Javascript's floating-point representation without overflow
+ // or change in sign.
+ //
+ // In the algorithms below, we frequently reduce the negative case to the
+ // positive case by negating the input(s) and then post-processing the result.
+ // Note that we must ALWAYS check specially whether those values are MIN_VALUE
+ // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
+ // a positive number, it overflows back into a negative). Not handling this
+ // case would often result in infinite recursion.
+ //
+ // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
+ // methods on which they depend.
+
+ /**
+ * An indicator used to reliably determine if an object is a Long or not.
+ * @type {boolean}
+ * @const
+ * @private
+ */
+ Long.prototype.__isLong__;
+
+ Object.defineProperty(Long.prototype, "__isLong__", { value: true });
+
+ /**
+ * @function
+ * @param {*} obj Object
+ * @returns {boolean}
+ * @inner
+ */
+ function isLong(obj) {
+ return (obj && obj["__isLong__"]) === true;
+ }
+
+ /**
+ * Tests if the specified object is a Long.
+ * @function
+ * @param {*} obj Object
+ * @returns {boolean}
+ */
+ Long.isLong = isLong;
+
+ /**
+ * A cache of the Long representations of small integer values.
+ * @type {!Object}
+ * @inner
+ */
+ var INT_CACHE = {};
+
+ /**
+ * A cache of the Long representations of small unsigned integer values.
+ * @type {!Object}
+ * @inner
+ */
+ var UINT_CACHE = {};
+
+ /**
+ * @param {number} value
+ * @param {boolean=} unsigned
+ * @returns {!Long}
+ * @inner
+ */
+ function fromInt(value, unsigned) {
+ var obj, cachedObj, cache;
+ if (unsigned) {
+ value >>>= 0;
+ if (cache = (0 <= value && value < 256)) {
+ cachedObj = UINT_CACHE[value];
+ if (cachedObj)
+ return cachedObj;
+ }
+ obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
+ if (cache)
+ UINT_CACHE[value] = obj;
+ return obj;
+ } else {
+ value |= 0;
+ if (cache = (-128 <= value && value < 128)) {
+ cachedObj = INT_CACHE[value];
+ if (cachedObj)
+ return cachedObj;
+ }
+ obj = fromBits(value, value < 0 ? -1 : 0, false);
+ if (cache)
+ INT_CACHE[value] = obj;
+ return obj;
+ }
+ }
+
+ /**
+ * Returns a Long representing the given 32 bit integer value.
+ * @function
+ * @param {number} value The 32 bit integer in question
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {!Long} The corresponding Long value
+ */
+ Long.fromInt = fromInt;
+
+ /**
+ * @param {number} value
+ * @param {boolean=} unsigned
+ * @returns {!Long}
+ * @inner
+ */
+ function fromNumber(value, unsigned) {
+ if (isNaN(value))
+ return unsigned ? UZERO : ZERO;
+ if (unsigned) {
+ if (value < 0)
+ return UZERO;
+ if (value >= TWO_PWR_64_DBL)
+ return MAX_UNSIGNED_VALUE;
+ } else {
+ if (value <= -TWO_PWR_63_DBL)
+ return MIN_VALUE;
+ if (value + 1 >= TWO_PWR_63_DBL)
+ return MAX_VALUE;
+ }
+ if (value < 0)
+ return fromNumber(-value, unsigned).neg();
+ return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
+ }
+
+ /**
+ * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
+ * @function
+ * @param {number} value The number in question
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {!Long} The corresponding Long value
+ */
+ Long.fromNumber = fromNumber;
+
+ /**
+ * @param {number} lowBits
+ * @param {number} highBits
+ * @param {boolean=} unsigned
+ * @returns {!Long}
+ * @inner
+ */
+ function fromBits(lowBits, highBits, unsigned) {
+ return new Long(lowBits, highBits, unsigned);
+ }
+
+ /**
+ * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
+ * assumed to use 32 bits.
+ * @function
+ * @param {number} lowBits The low 32 bits
+ * @param {number} highBits The high 32 bits
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {!Long} The corresponding Long value
+ */
+ Long.fromBits = fromBits;
+
+ /**
+ * @function
+ * @param {number} base
+ * @param {number} exponent
+ * @returns {number}
+ * @inner
+ */
+ var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
+
+ /**
+ * @param {string} str
+ * @param {(boolean|number)=} unsigned
+ * @param {number=} radix
+ * @returns {!Long}
+ * @inner
+ */
+ function fromString(str, unsigned, radix) {
+ if (str.length === 0)
+ throw Error('empty string');
+ if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
+ return ZERO;
+ if (typeof unsigned === 'number') {
+ // For goog.math.long compatibility
+ radix = unsigned,
+ unsigned = false;
+ } else {
+ unsigned = !! unsigned;
+ }
+ radix = radix || 10;
+ if (radix < 2 || 36 < radix)
+ throw RangeError('radix');
+
+ var p;
+ if ((p = str.indexOf('-')) > 0)
+ throw Error('interior hyphen');
+ else if (p === 0) {
+ return fromString(str.substring(1), unsigned, radix).neg();
+ }
+
+ // Do several (8) digits each time through the loop, so as to
+ // minimize the calls to the very expensive emulated div.
+ var radixToPower = fromNumber(pow_dbl(radix, 8));
+
+ var result = ZERO;
+ for (var i = 0; i < str.length; i += 8) {
+ var size = Math.min(8, str.length - i),
+ value = parseInt(str.substring(i, i + size), radix);
+ if (size < 8) {
+ var power = fromNumber(pow_dbl(radix, size));
+ result = result.mul(power).add(fromNumber(value));
+ } else {
+ result = result.mul(radixToPower);
+ result = result.add(fromNumber(value));
+ }
+ }
+ result.unsigned = unsigned;
+ return result;
+ }
+
+ /**
+ * Returns a Long representation of the given string, written using the specified radix.
+ * @function
+ * @param {string} str The textual representation of the Long
+ * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed
+ * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
+ * @returns {!Long} The corresponding Long value
+ */
+ Long.fromString = fromString;
+
+ /**
+ * @function
+ * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
+ * @param {boolean=} unsigned
+ * @returns {!Long}
+ * @inner
+ */
+ function fromValue(val, unsigned) {
+ if (typeof val === 'number')
+ return fromNumber(val, unsigned);
+ if (typeof val === 'string')
+ return fromString(val, unsigned);
+ // Throws for non-objects, converts non-instanceof Long:
+ return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
+ }
+
+ /**
+ * Converts the specified value to a Long using the appropriate from* function for its type.
+ * @function
+ * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {!Long}
+ */
+ Long.fromValue = fromValue;
+
+ // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
+ // no runtime penalty for these.
+
+ /**
+ * @type {number}
+ * @const
+ * @inner
+ */
+ var TWO_PWR_16_DBL = 1 << 16;
+
+ /**
+ * @type {number}
+ * @const
+ * @inner
+ */
+ var TWO_PWR_24_DBL = 1 << 24;
+
+ /**
+ * @type {number}
+ * @const
+ * @inner
+ */
+ var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
+
+ /**
+ * @type {number}
+ * @const
+ * @inner
+ */
+ var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
+
+ /**
+ * @type {number}
+ * @const
+ * @inner
+ */
+ var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
+
+ /**
+ * @type {!Long}
+ * @const
+ * @inner
+ */
+ var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
+
+ /**
+ * @type {!Long}
+ * @inner
+ */
+ var ZERO = fromInt(0);
+
+ /**
+ * Signed zero.
+ * @type {!Long}
+ */
+ Long.ZERO = ZERO;
+
+ /**
+ * @type {!Long}
+ * @inner
+ */
+ var UZERO = fromInt(0, true);
+
+ /**
+ * Unsigned zero.
+ * @type {!Long}
+ */
+ Long.UZERO = UZERO;
+
+ /**
+ * @type {!Long}
+ * @inner
+ */
+ var ONE = fromInt(1);
+
+ /**
+ * Signed one.
+ * @type {!Long}
+ */
+ Long.ONE = ONE;
+
+ /**
+ * @type {!Long}
+ * @inner
+ */
+ var UONE = fromInt(1, true);
+
+ /**
+ * Unsigned one.
+ * @type {!Long}
+ */
+ Long.UONE = UONE;
+
+ /**
+ * @type {!Long}
+ * @inner
+ */
+ var NEG_ONE = fromInt(-1);
+
+ /**
+ * Signed negative one.
+ * @type {!Long}
+ */
+ Long.NEG_ONE = NEG_ONE;
+
+ /**
+ * @type {!Long}
+ * @inner
+ */
+ var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
+
+ /**
+ * Maximum signed value.
+ * @type {!Long}
+ */
+ Long.MAX_VALUE = MAX_VALUE;
+
+ /**
+ * @type {!Long}
+ * @inner
+ */
+ var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
+
+ /**
+ * Maximum unsigned value.
+ * @type {!Long}
+ */
+ Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
+
+ /**
+ * @type {!Long}
+ * @inner
+ */
+ var MIN_VALUE = fromBits(0, 0x80000000|0, false);
+
+ /**
+ * Minimum signed value.
+ * @type {!Long}
+ */
+ Long.MIN_VALUE = MIN_VALUE;
+
+ /**
+ * @alias Long.prototype
+ * @inner
+ */
+ var LongPrototype = Long.prototype;
+
+ /**
+ * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
+ * @returns {number}
+ */
+ LongPrototype.toInt = function toInt() {
+ return this.unsigned ? this.low >>> 0 : this.low;
+ };
+
+ /**
+ * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
+ * @returns {number}
+ */
+ LongPrototype.toNumber = function toNumber() {
+ if (this.unsigned)
+ return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
+ return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
+ };
+
+ /**
+ * Converts the Long to a string written in the specified radix.
+ * @param {number=} radix Radix (2-36), defaults to 10
+ * @returns {string}
+ * @override
+ * @throws {RangeError} If `radix` is out of range
+ */
+ LongPrototype.toString = function toString(radix) {
+ radix = radix || 10;
+ if (radix < 2 || 36 < radix)
+ throw RangeError('radix');
+ if (this.isZero())
+ return '0';
+ if (this.isNegative()) { // Unsigned Longs are never negative
+ if (this.eq(MIN_VALUE)) {
+ // We need to change the Long value before it can be negated, so we remove
+ // the bottom-most digit in this base and then recurse to do the rest.
+ var radixLong = fromNumber(radix),
+ div = this.div(radixLong),
+ rem1 = div.mul(radixLong).sub(this);
+ return div.toString(radix) + rem1.toInt().toString(radix);
+ } else
+ return '-' + this.neg().toString(radix);
+ }
+
+ // Do several (6) digits each time through the loop, so as to
+ // minimize the calls to the very expensive emulated div.
+ var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
+ rem = this;
+ var result = '';
+ while (true) {
+ var remDiv = rem.div(radixToPower),
+ intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
+ digits = intval.toString(radix);
+ rem = remDiv;
+ if (rem.isZero())
+ return digits + result;
+ else {
+ while (digits.length < 6)
+ digits = '0' + digits;
+ result = '' + digits + result;
+ }
+ }
+ };
+
+ /**
+ * Gets the high 32 bits as a signed integer.
+ * @returns {number} Signed high bits
+ */
+ LongPrototype.getHighBits = function getHighBits() {
+ return this.high;
+ };
+
+ /**
+ * Gets the high 32 bits as an unsigned integer.
+ * @returns {number} Unsigned high bits
+ */
+ LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
+ return this.high >>> 0;
+ };
+
+ /**
+ * Gets the low 32 bits as a signed integer.
+ * @returns {number} Signed low bits
+ */
+ LongPrototype.getLowBits = function getLowBits() {
+ return this.low;
+ };
+
+ /**
+ * Gets the low 32 bits as an unsigned integer.
+ * @returns {number} Unsigned low bits
+ */
+ LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
+ return this.low >>> 0;
+ };
+
+ /**
+ * Gets the number of bits needed to represent the absolute value of this Long.
+ * @returns {number}
+ */
+ LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
+ if (this.isNegative()) // Unsigned Longs are never negative
+ return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
+ var val = this.high != 0 ? this.high : this.low;
+ for (var bit = 31; bit > 0; bit--)
+ if ((val & (1 << bit)) != 0)
+ break;
+ return this.high != 0 ? bit + 33 : bit + 1;
+ };
+
+ /**
+ * Tests if this Long's value equals zero.
+ * @returns {boolean}
+ */
+ LongPrototype.isZero = function isZero() {
+ return this.high === 0 && this.low === 0;
+ };
+
+ /**
+ * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.
+ * @returns {boolean}
+ */
+ LongPrototype.eqz = LongPrototype.isZero;
+
+ /**
+ * Tests if this Long's value is negative.
+ * @returns {boolean}
+ */
+ LongPrototype.isNegative = function isNegative() {
+ return !this.unsigned && this.high < 0;
+ };
+
+ /**
+ * Tests if this Long's value is positive.
+ * @returns {boolean}
+ */
+ LongPrototype.isPositive = function isPositive() {
+ return this.unsigned || this.high >= 0;
+ };
+
+ /**
+ * Tests if this Long's value is odd.
+ * @returns {boolean}
+ */
+ LongPrototype.isOdd = function isOdd() {
+ return (this.low & 1) === 1;
+ };
+
+ /**
+ * Tests if this Long's value is even.
+ * @returns {boolean}
+ */
+ LongPrototype.isEven = function isEven() {
+ return (this.low & 1) === 0;
+ };
+
+ /**
+ * Tests if this Long's value equals the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.equals = function equals(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
+ return false;
+ return this.high === other.high && this.low === other.low;
+ };
+
+ /**
+ * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.eq = LongPrototype.equals;
+
+ /**
+ * Tests if this Long's value differs from the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.notEquals = function notEquals(other) {
+ return !this.eq(/* validates */ other);
+ };
+
+ /**
+ * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.neq = LongPrototype.notEquals;
+
+ /**
+ * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.ne = LongPrototype.notEquals;
+
+ /**
+ * Tests if this Long's value is less than the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.lessThan = function lessThan(other) {
+ return this.comp(/* validates */ other) < 0;
+ };
+
+ /**
+ * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.lt = LongPrototype.lessThan;
+
+ /**
+ * Tests if this Long's value is less than or equal the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
+ return this.comp(/* validates */ other) <= 0;
+ };
+
+ /**
+ * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.lte = LongPrototype.lessThanOrEqual;
+
+ /**
+ * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.le = LongPrototype.lessThanOrEqual;
+
+ /**
+ * Tests if this Long's value is greater than the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.greaterThan = function greaterThan(other) {
+ return this.comp(/* validates */ other) > 0;
+ };
+
+ /**
+ * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.gt = LongPrototype.greaterThan;
+
+ /**
+ * Tests if this Long's value is greater than or equal the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
+ return this.comp(/* validates */ other) >= 0;
+ };
+
+ /**
+ * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.gte = LongPrototype.greaterThanOrEqual;
+
+ /**
+ * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {boolean}
+ */
+ LongPrototype.ge = LongPrototype.greaterThanOrEqual;
+
+ /**
+ * Compares this Long's value with the specified's.
+ * @param {!Long|number|string} other Other value
+ * @returns {number} 0 if they are the same, 1 if the this is greater and -1
+ * if the given one is greater
+ */
+ LongPrototype.compare = function compare(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ if (this.eq(other))
+ return 0;
+ var thisNeg = this.isNegative(),
+ otherNeg = other.isNegative();
+ if (thisNeg && !otherNeg)
+ return -1;
+ if (!thisNeg && otherNeg)
+ return 1;
+ // At this point the sign bits are the same
+ if (!this.unsigned)
+ return this.sub(other).isNegative() ? -1 : 1;
+ // Both are positive if at least one is unsigned
+ return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
+ };
+
+ /**
+ * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
+ * @function
+ * @param {!Long|number|string} other Other value
+ * @returns {number} 0 if they are the same, 1 if the this is greater and -1
+ * if the given one is greater
+ */
+ LongPrototype.comp = LongPrototype.compare;
+
+ /**
+ * Negates this Long's value.
+ * @returns {!Long} Negated Long
+ */
+ LongPrototype.negate = function negate() {
+ if (!this.unsigned && this.eq(MIN_VALUE))
+ return MIN_VALUE;
+ return this.not().add(ONE);
+ };
+
+ /**
+ * Negates this Long's value. This is an alias of {@link Long#negate}.
+ * @function
+ * @returns {!Long} Negated Long
+ */
+ LongPrototype.neg = LongPrototype.negate;
+
+ /**
+ * Returns the sum of this and the specified Long.
+ * @param {!Long|number|string} addend Addend
+ * @returns {!Long} Sum
+ */
+ LongPrototype.add = function add(addend) {
+ if (!isLong(addend))
+ addend = fromValue(addend);
+
+ // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
+
+ var a48 = this.high >>> 16;
+ var a32 = this.high & 0xFFFF;
+ var a16 = this.low >>> 16;
+ var a00 = this.low & 0xFFFF;
+
+ var b48 = addend.high >>> 16;
+ var b32 = addend.high & 0xFFFF;
+ var b16 = addend.low >>> 16;
+ var b00 = addend.low & 0xFFFF;
+
+ var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+ c00 += a00 + b00;
+ c16 += c00 >>> 16;
+ c00 &= 0xFFFF;
+ c16 += a16 + b16;
+ c32 += c16 >>> 16;
+ c16 &= 0xFFFF;
+ c32 += a32 + b32;
+ c48 += c32 >>> 16;
+ c32 &= 0xFFFF;
+ c48 += a48 + b48;
+ c48 &= 0xFFFF;
+ return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+ };
+
+ /**
+ * Returns the difference of this and the specified Long.
+ * @param {!Long|number|string} subtrahend Subtrahend
+ * @returns {!Long} Difference
+ */
+ LongPrototype.subtract = function subtract(subtrahend) {
+ if (!isLong(subtrahend))
+ subtrahend = fromValue(subtrahend);
+ return this.add(subtrahend.neg());
+ };
+
+ /**
+ * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
+ * @function
+ * @param {!Long|number|string} subtrahend Subtrahend
+ * @returns {!Long} Difference
+ */
+ LongPrototype.sub = LongPrototype.subtract;
+
+ /**
+ * Returns the product of this and the specified Long.
+ * @param {!Long|number|string} multiplier Multiplier
+ * @returns {!Long} Product
+ */
+ LongPrototype.multiply = function multiply(multiplier) {
+ if (this.isZero())
+ return ZERO;
+ if (!isLong(multiplier))
+ multiplier = fromValue(multiplier);
+
+ // use wasm support if present
+ if (wasm) {
+ var low = wasm.mul(this.low,
+ this.high,
+ multiplier.low,
+ multiplier.high);
+ return fromBits(low, wasm.get_high(), this.unsigned);
+ }
+
+ if (multiplier.isZero())
+ return ZERO;
+ if (this.eq(MIN_VALUE))
+ return multiplier.isOdd() ? MIN_VALUE : ZERO;
+ if (multiplier.eq(MIN_VALUE))
+ return this.isOdd() ? MIN_VALUE : ZERO;
+
+ if (this.isNegative()) {
+ if (multiplier.isNegative())
+ return this.neg().mul(multiplier.neg());
+ else
+ return this.neg().mul(multiplier).neg();
+ } else if (multiplier.isNegative())
+ return this.mul(multiplier.neg()).neg();
+
+ // If both longs are small, use float multiplication
+ if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
+ return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
+
+ // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
+ // We can skip products that would overflow.
+
+ var a48 = this.high >>> 16;
+ var a32 = this.high & 0xFFFF;
+ var a16 = this.low >>> 16;
+ var a00 = this.low & 0xFFFF;
+
+ var b48 = multiplier.high >>> 16;
+ var b32 = multiplier.high & 0xFFFF;
+ var b16 = multiplier.low >>> 16;
+ var b00 = multiplier.low & 0xFFFF;
+
+ var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+ c00 += a00 * b00;
+ c16 += c00 >>> 16;
+ c00 &= 0xFFFF;
+ c16 += a16 * b00;
+ c32 += c16 >>> 16;
+ c16 &= 0xFFFF;
+ c16 += a00 * b16;
+ c32 += c16 >>> 16;
+ c16 &= 0xFFFF;
+ c32 += a32 * b00;
+ c48 += c32 >>> 16;
+ c32 &= 0xFFFF;
+ c32 += a16 * b16;
+ c48 += c32 >>> 16;
+ c32 &= 0xFFFF;
+ c32 += a00 * b32;
+ c48 += c32 >>> 16;
+ c32 &= 0xFFFF;
+ c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
+ c48 &= 0xFFFF;
+ return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+ };
+
+ /**
+ * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
+ * @function
+ * @param {!Long|number|string} multiplier Multiplier
+ * @returns {!Long} Product
+ */
+ LongPrototype.mul = LongPrototype.multiply;
+
+ /**
+ * Returns this Long divided by the specified. The result is signed if this Long is signed or
+ * unsigned if this Long is unsigned.
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Quotient
+ */
+ LongPrototype.divide = function divide(divisor) {
+ if (!isLong(divisor))
+ divisor = fromValue(divisor);
+ if (divisor.isZero())
+ throw Error('division by zero');
+
+ // use wasm support if present
+ if (wasm) {
+ // guard against signed division overflow: the largest
+ // negative number / -1 would be 1 larger than the largest
+ // positive number, due to two's complement.
+ if (!this.unsigned &&
+ this.high === -0x80000000 &&
+ divisor.low === -1 && divisor.high === -1) {
+ // be consistent with non-wasm code path
+ return this;
+ }
+ var low = (this.unsigned ? wasm.div_u : wasm.div_s)(
+ this.low,
+ this.high,
+ divisor.low,
+ divisor.high
+ );
+ return fromBits(low, wasm.get_high(), this.unsigned);
+ }
+
+ if (this.isZero())
+ return this.unsigned ? UZERO : ZERO;
+ var approx, rem, res;
+ if (!this.unsigned) {
+ // This section is only relevant for signed longs and is derived from the
+ // closure library as a whole.
+ if (this.eq(MIN_VALUE)) {
+ if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
+ return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
+ else if (divisor.eq(MIN_VALUE))
+ return ONE;
+ else {
+ // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
+ var halfThis = this.shr(1);
+ approx = halfThis.div(divisor).shl(1);
+ if (approx.eq(ZERO)) {
+ return divisor.isNegative() ? ONE : NEG_ONE;
+ } else {
+ rem = this.sub(divisor.mul(approx));
+ res = approx.add(rem.div(divisor));
+ return res;
+ }
+ }
+ } else if (divisor.eq(MIN_VALUE))
+ return this.unsigned ? UZERO : ZERO;
+ if (this.isNegative()) {
+ if (divisor.isNegative())
+ return this.neg().div(divisor.neg());
+ return this.neg().div(divisor).neg();
+ } else if (divisor.isNegative())
+ return this.div(divisor.neg()).neg();
+ res = ZERO;
+ } else {
+ // The algorithm below has not been made for unsigned longs. It's therefore
+ // required to take special care of the MSB prior to running it.
+ if (!divisor.unsigned)
+ divisor = divisor.toUnsigned();
+ if (divisor.gt(this))
+ return UZERO;
+ if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
+ return UONE;
+ res = UZERO;
+ }
+
+ // Repeat the following until the remainder is less than other: find a
+ // floating-point that approximates remainder / other *from below*, add this
+ // into the result, and subtract it from the remainder. It is critical that
+ // the approximate value is less than or equal to the real value so that the
+ // remainder never becomes negative.
+ rem = this;
+ while (rem.gte(divisor)) {
+ // Approximate the result of division. This may be a little greater or
+ // smaller than the actual value.
+ approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
+
+ // We will tweak the approximate result by changing it in the 48-th digit or
+ // the smallest non-fractional digit, whichever is larger.
+ var log2 = Math.ceil(Math.log(approx) / Math.LN2),
+ delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
+
+ // Decrease the approximation until it is smaller than the remainder. Note
+ // that if it is too large, the product overflows and is negative.
+ approxRes = fromNumber(approx),
+ approxRem = approxRes.mul(divisor);
+ while (approxRem.isNegative() || approxRem.gt(rem)) {
+ approx -= delta;
+ approxRes = fromNumber(approx, this.unsigned);
+ approxRem = approxRes.mul(divisor);
+ }
+
+ // We know the answer can't be zero... and actually, zero would cause
+ // infinite recursion since we would make no progress.
+ if (approxRes.isZero())
+ approxRes = ONE;
+
+ res = res.add(approxRes);
+ rem = rem.sub(approxRem);
+ }
+ return res;
+ };
+
+ /**
+ * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
+ * @function
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Quotient
+ */
+ LongPrototype.div = LongPrototype.divide;
+
+ /**
+ * Returns this Long modulo the specified.
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Remainder
+ */
+ LongPrototype.modulo = function modulo(divisor) {
+ if (!isLong(divisor))
+ divisor = fromValue(divisor);
+
+ // use wasm support if present
+ if (wasm) {
+ var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(
+ this.low,
+ this.high,
+ divisor.low,
+ divisor.high
+ );
+ return fromBits(low, wasm.get_high(), this.unsigned);
+ }
+
+ return this.sub(this.div(divisor).mul(divisor));
+ };
+
+ /**
+ * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
+ * @function
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Remainder
+ */
+ LongPrototype.mod = LongPrototype.modulo;
+
+ /**
+ * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
+ * @function
+ * @param {!Long|number|string} divisor Divisor
+ * @returns {!Long} Remainder
+ */
+ LongPrototype.rem = LongPrototype.modulo;
+
+ /**
+ * Returns the bitwise NOT of this Long.
+ * @returns {!Long}
+ */
+ LongPrototype.not = function not() {
+ return fromBits(~this.low, ~this.high, this.unsigned);
+ };
+
+ /**
+ * Returns the bitwise AND of this Long and the specified.
+ * @param {!Long|number|string} other Other Long
+ * @returns {!Long}
+ */
+ LongPrototype.and = function and(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
+ };
+
+ /**
+ * Returns the bitwise OR of this Long and the specified.
+ * @param {!Long|number|string} other Other Long
+ * @returns {!Long}
+ */
+ LongPrototype.or = function or(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
+ };
+
+ /**
+ * Returns the bitwise XOR of this Long and the given one.
+ * @param {!Long|number|string} other Other Long
+ * @returns {!Long}
+ */
+ LongPrototype.xor = function xor(other) {
+ if (!isLong(other))
+ other = fromValue(other);
+ return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
+ };
+
+ /**
+ * Returns this Long with bits shifted to the left by the given amount.
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+ LongPrototype.shiftLeft = function shiftLeft(numBits) {
+ if (isLong(numBits))
+ numBits = numBits.toInt();
+ if ((numBits &= 63) === 0)
+ return this;
+ else if (numBits < 32)
+ return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
+ else
+ return fromBits(0, this.low << (numBits - 32), this.unsigned);
+ };
+
+ /**
+ * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
+ * @function
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+ LongPrototype.shl = LongPrototype.shiftLeft;
+
+ /**
+ * Returns this Long with bits arithmetically shifted to the right by the given amount.
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+ LongPrototype.shiftRight = function shiftRight(numBits) {
+ if (isLong(numBits))
+ numBits = numBits.toInt();
+ if ((numBits &= 63) === 0)
+ return this;
+ else if (numBits < 32)
+ return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
+ else
+ return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
+ };
+
+ /**
+ * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
+ * @function
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+ LongPrototype.shr = LongPrototype.shiftRight;
+
+ /**
+ * Returns this Long with bits logically shifted to the right by the given amount.
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+ LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
+ if (isLong(numBits))
+ numBits = numBits.toInt();
+ numBits &= 63;
+ if (numBits === 0)
+ return this;
+ else {
+ var high = this.high;
+ if (numBits < 32) {
+ var low = this.low;
+ return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
+ } else if (numBits === 32)
+ return fromBits(high, 0, this.unsigned);
+ else
+ return fromBits(high >>> (numBits - 32), 0, this.unsigned);
+ }
+ };
+
+ /**
+ * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
+ * @function
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+ LongPrototype.shru = LongPrototype.shiftRightUnsigned;
+
+ /**
+ * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
+ * @function
+ * @param {number|!Long} numBits Number of bits
+ * @returns {!Long} Shifted Long
+ */
+ LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
+
+ /**
+ * Converts this Long to signed.
+ * @returns {!Long} Signed long
+ */
+ LongPrototype.toSigned = function toSigned() {
+ if (!this.unsigned)
+ return this;
+ return fromBits(this.low, this.high, false);
+ };
+
+ /**
+ * Converts this Long to unsigned.
+ * @returns {!Long} Unsigned long
+ */
+ LongPrototype.toUnsigned = function toUnsigned() {
+ if (this.unsigned)
+ return this;
+ return fromBits(this.low, this.high, true);
+ };
+
+ /**
+ * Converts this Long to its byte representation.
+ * @param {boolean=} le Whether little or big endian, defaults to big endian
+ * @returns {!Array.} Byte representation
+ */
+ LongPrototype.toBytes = function toBytes(le) {
+ return le ? this.toBytesLE() : this.toBytesBE();
+ };
+
+ /**
+ * Converts this Long to its little endian byte representation.
+ * @returns {!Array.} Little endian byte representation
+ */
+ LongPrototype.toBytesLE = function toBytesLE() {
+ var hi = this.high,
+ lo = this.low;
+ return [
+ lo & 0xff,
+ lo >>> 8 & 0xff,
+ lo >>> 16 & 0xff,
+ lo >>> 24 ,
+ hi & 0xff,
+ hi >>> 8 & 0xff,
+ hi >>> 16 & 0xff,
+ hi >>> 24
+ ];
+ };
+
+ /**
+ * Converts this Long to its big endian byte representation.
+ * @returns {!Array.} Big endian byte representation
+ */
+ LongPrototype.toBytesBE = function toBytesBE() {
+ var hi = this.high,
+ lo = this.low;
+ return [
+ hi >>> 24 ,
+ hi >>> 16 & 0xff,
+ hi >>> 8 & 0xff,
+ hi & 0xff,
+ lo >>> 24 ,
+ lo >>> 16 & 0xff,
+ lo >>> 8 & 0xff,
+ lo & 0xff
+ ];
+ };
+
+ /**
+ * Creates a Long from its byte representation.
+ * @param {!Array.} bytes Byte representation
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @param {boolean=} le Whether little or big endian, defaults to big endian
+ * @returns {Long} The corresponding Long value
+ */
+ Long.fromBytes = function fromBytes(bytes, unsigned, le) {
+ return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
+ };
+
+ /**
+ * Creates a Long from its little endian byte representation.
+ * @param {!Array.} bytes Little endian byte representation
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {Long} The corresponding Long value
+ */
+ Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
+ return new Long(
+ bytes[0] |
+ bytes[1] << 8 |
+ bytes[2] << 16 |
+ bytes[3] << 24,
+ bytes[4] |
+ bytes[5] << 8 |
+ bytes[6] << 16 |
+ bytes[7] << 24,
+ unsigned
+ );
+ };
+
+ /**
+ * Creates a Long from its big endian byte representation.
+ * @param {!Array.} bytes Big endian byte representation
+ * @param {boolean=} unsigned Whether unsigned or not, defaults to signed
+ * @returns {Long} The corresponding Long value
+ */
+ Long.fromBytesBE = function fromBytesBE(bytes, unsigned) {
+ return new Long(
+ bytes[4] << 24 |
+ bytes[5] << 16 |
+ bytes[6] << 8 |
+ bytes[7],
+ bytes[0] << 24 |
+ bytes[1] << 16 |
+ bytes[2] << 8 |
+ bytes[3],
+ unsigned
+ );
+ };
+
+ var LongExports = {
+ __proto__: null,
+ 'default': long_1,
+ __moduleExports: long_1
+ };
+
+ /**
+ * @license
+ * Copyright 2021 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // tslint:disable-next-line
+ var Long$1 =
+ // tslint:disable-next-line
+ long_1 || LongExports;
+ function hexToLong(hex) {
+ return Long$1.fromString(hex, true, 16);
+ }
+ // Some primes between 2^63 and 2^64 for various uses.
+ // Hex 0xc3a5c85c97cb3127
+ var k0 = hexToLong('c3a5c85c97cb3127');
+ // Hex 0xb492b66fbe98f273
+ var k1 = hexToLong('b492b66fbe98f273');
+ // Hex 0x9ae16a3b2f90404f
+ var k2 = hexToLong('9ae16a3b2f90404f');
+ function shiftMix(val) {
+ return val.xor(val.shru(47));
+ }
+ function fetch$1(s, offset, numBytes) {
+ var bytes = s.slice(offset, offset + numBytes);
+ return Long$1.fromBytes(Array.from(bytes), true, true);
+ }
+ function fetch64(s, offset) {
+ return fetch$1(s, offset, 8);
+ }
+ function fetch32(s, offset) {
+ return fetch$1(s, offset, 4);
+ }
+ function rotate64(val, shift) {
+ // Avoid shifting by 64: doing so yields an undefined result.
+ return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift));
+ }
+ function hashLen16(u, v, mul) {
+ if (mul === void 0) { mul = hexToLong('9ddfea08eb382d69'); }
+ // Murmur-inspired hashing.
+ var a = u.xor(v).mul(mul);
+ a = a.xor(a.shru(47));
+ var b = v.xor(a).mul(mul);
+ b = b.xor(b.shru(47));
+ b = b.mul(mul);
+ return b;
+ }
+ // Return a 16-byte hash for 48 bytes. Quick and dirty.
+ // Callers do best to use "random-looking" values for a and b.
+ function weakHashLen32WithSeeds(w, x, y, z, a, b) {
+ a = a.add(w);
+ b = rotate64(b.add(a).add(z), 21);
+ var c = a;
+ a = a.add(x);
+ a = a.add(y);
+ b = b.add(rotate64(a, 44));
+ return [a.add(z), b.add(c)];
+ }
+ function weakHashLen32WithSeedsStr(s, offset, a, b) {
+ return weakHashLen32WithSeeds(fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16), fetch64(s, offset + 24), a, b);
+ }
+ function hashLen0to16(s, len) {
+ if (len === void 0) { len = s.length; }
+ if (len >= 8) {
+ var mul = k2.add(len * 2);
+ var a = fetch64(s, 0).add(k2);
+ var b = fetch64(s, len - 8);
+ var c = rotate64(b, 37).mul(mul).add(a);
+ var d = rotate64(a, 25).add(b).mul(mul);
+ return hashLen16(c, d, mul);
+ }
+ if (len >= 4) {
+ var mul = k2.add(len * 2);
+ var a = fetch32(s, 0);
+ return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul);
+ }
+ if (len > 0) {
+ var a = s[0];
+ var b = s[len >> 1];
+ var c = s[len - 1];
+ var y = a + (b << 8);
+ var z = len + (c << 2);
+ return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2);
+ }
+ return k2;
+ }
+ function hashLen17to32(s, len) {
+ if (len === void 0) { len = s.length; }
+ var mul = k2.add(len * 2);
+ var a = fetch64(s, 0).mul(k1);
+ var b = fetch64(s, 8);
+ var c = fetch64(s, len - 8).mul(mul);
+ var d = fetch64(s, len - 16).mul(k2);
+ return hashLen16(rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d), a.add(rotate64(b.add(k2), 18)).add(c), mul);
+ }
+ function hashLen33to64(s, len) {
+ if (len === void 0) { len = s.length; }
+ var mul = k2.add(len * 2);
+ var a = fetch64(s, 0).mul(k2);
+ var b = fetch64(s, 8);
+ var c = fetch64(s, len - 8).mul(mul);
+ var d = fetch64(s, len - 16).mul(k2);
+ var y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d);
+ var z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul);
+ var e = fetch64(s, 16).mul(mul);
+ var f = fetch64(s, 24);
+ var g = y.add(fetch64(s, len - 32)).mul(mul);
+ var h = z.add(fetch64(s, len - 24)).mul(mul);
+ return hashLen16(rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h), e.add(rotate64(f.add(a), 18)).add(g), mul);
+ }
+ function fingerPrint64(s, len) {
+ var _a, _b;
+ if (len === void 0) { len = s.length; }
+ var seed = Long$1.fromNumber(81, true);
+ if (len <= 32) {
+ if (len <= 16) {
+ return hashLen0to16(s, len);
+ }
+ else {
+ return hashLen17to32(s, len);
+ }
+ }
+ else if (len <= 64) {
+ return hashLen33to64(s, len);
+ }
+ // For strings over 64 bytes we loop. Internal state consists of
+ // 56 bytes: v, w, x, y, and z.
+ var x = seed;
+ var y = seed.mul(k1).add(113);
+ var z = shiftMix(y.mul(k2).add(113)).mul(k2);
+ var v = [Long$1.UZERO, Long$1.UZERO];
+ var w = [Long$1.UZERO, Long$1.UZERO];
+ x = x.mul(k2).add(fetch64(s, 0));
+ var offset = 0;
+ // Set end so that after the loop we have 1 to 64 bytes left to process.
+ var end = ((len - 1) >> 6) * 64;
+ var last64 = end + ((len - 1) & 63) - 63;
+ do {
+ x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1);
+ y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1);
+ x = x.xor(w[1]);
+ y = y.add(v[0]).add(fetch64(s, offset + 40));
+ z = rotate64(z.add(w[0]), 33).mul(k1);
+ v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0]));
+ w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));
+ _a = [x, z], z = _a[0], x = _a[1];
+ offset += 64;
+ } while (offset !== end);
+ var mul = k1.add(z.and(0xff).shl(1));
+ // Point to the last 64 bytes of input.
+ offset = last64;
+ w[0] = w[0].add((len - 1) & 63);
+ v[0] = v[0].add(w[0]);
+ w[0] = w[0].add(v[0]);
+ x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul);
+ y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul);
+ x = x.xor(w[1].mul(9));
+ y = y.add(v[0].mul(9).add(fetch64(s, offset + 40)));
+ z = rotate64(z.add(w[0]), 33).mul(mul);
+ v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul), x.add(w[0]));
+ w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));
+ _b = [x, z], z = _b[0], x = _b[1];
+ return hashLen16(hashLen16(v[0], w[0], mul).add(shiftMix(y).mul(k0)).add(z), hashLen16(v[1], w[1], mul).add(x), mul);
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Create typed array for scalar value. Used for storing in `DataStorage`.
+ */
+ function createScalarValue(value, dtype) {
+ if (dtype === 'string') {
+ return encodeString(value);
+ }
+ return toTypedArray([value], dtype);
+ }
+ function noConversionNeeded(a, dtype) {
+ return (a instanceof Float32Array && dtype === 'float32') ||
+ (a instanceof Int32Array && dtype === 'int32') ||
+ (a instanceof Uint8Array && dtype === 'bool');
+ }
+ function toTypedArray(a, dtype) {
+ if (dtype === 'string') {
+ throw new Error('Cannot convert a string[] to a TypedArray');
+ }
+ if (Array.isArray(a)) {
+ a = flatten(a);
+ }
+ if (env().getBool('DEBUG')) {
+ checkConversionForErrors(a, dtype);
+ }
+ if (noConversionNeeded(a, dtype)) {
+ return a;
+ }
+ if (dtype == null || dtype === 'float32' || dtype === 'complex64') {
+ return new Float32Array(a);
+ }
+ else if (dtype === 'int32') {
+ return new Int32Array(a);
+ }
+ else if (dtype === 'bool') {
+ var bool = new Uint8Array(a.length);
+ for (var i = 0; i < bool.length; ++i) {
+ if (Math.round(a[i]) !== 0) {
+ bool[i] = 1;
+ }
+ }
+ return bool;
+ }
+ else {
+ throw new Error("Unknown data type " + dtype);
+ }
+ }
+ /**
+ * Returns the current high-resolution time in milliseconds relative to an
+ * arbitrary time in the past. It works across different platforms (node.js,
+ * browsers).
+ *
+ * ```js
+ * console.log(tf.util.now());
+ * ```
+ *
+ * @doc {heading: 'Util', namespace: 'util'}
+ */
+ function now() {
+ return env().platform.now();
+ }
+ /**
+ * Returns a platform-specific implementation of
+ * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
+ *
+ * If `fetch` is defined on the global object (`window`, `process`, etc.),
+ * `tf.util.fetch` returns that function.
+ *
+ * If not, `tf.util.fetch` returns a platform-specific solution.
+ *
+ * ```js
+ * const resource = await tf.util.fetch('https://unpkg.com/@tensorflow/tfjs');
+ * // handle response
+ * ```
+ *
+ * @doc {heading: 'Util'}
+ */
+ function fetch$2(path, requestInits) {
+ return env().platform.fetch(path, requestInits);
+ }
+ /**
+ * Encodes the provided string into bytes using the provided encoding scheme.
+ *
+ * @param s The string to encode.
+ * @param encoding The encoding scheme. Defaults to utf-8.
+ *
+ * @doc {heading: 'Util'}
+ */
+ function encodeString(s, encoding) {
+ if (encoding === void 0) { encoding = 'utf-8'; }
+ encoding = encoding || 'utf-8';
+ return env().platform.encode(s, encoding);
+ }
+ /**
+ * Decodes the provided bytes into a string using the provided encoding scheme.
+ * @param bytes The bytes to decode.
+ *
+ * @param encoding The encoding scheme. Defaults to utf-8.
+ *
+ * @doc {heading: 'Util'}
+ */
+ function decodeString(bytes, encoding) {
+ if (encoding === void 0) { encoding = 'utf-8'; }
+ encoding = encoding || 'utf-8';
+ return env().platform.decode(bytes, encoding);
+ }
+
+ var util = {
+ __proto__: null,
+ createScalarValue: createScalarValue,
+ toTypedArray: toTypedArray,
+ now: now,
+ fetch: fetch$2,
+ encodeString: encodeString,
+ decodeString: decodeString,
+ shuffle: shuffle,
+ shuffleCombo: shuffleCombo,
+ clamp: clamp,
+ nearestLargerEven: nearestLargerEven,
+ sum: sum,
+ randUniform: randUniform,
+ distSquared: distSquared,
+ assert: assert,
+ assertShapesMatch: assertShapesMatch,
+ assertNonNull: assertNonNull,
+ flatten: flatten,
+ sizeFromShape: sizeFromShape,
+ isScalarShape: isScalarShape,
+ arraysEqual: arraysEqual,
+ isInt: isInt,
+ tanh: tanh,
+ sizeToSquarishShape: sizeToSquarishShape,
+ createShuffledIndices: createShuffledIndices,
+ rightPad: rightPad,
+ repeatedTry: repeatedTry,
+ inferFromImplicitShape: inferFromImplicitShape,
+ parseAxisParam: parseAxisParam,
+ squeezeShape: squeezeShape,
+ getTypedArrayFromDType: getTypedArrayFromDType,
+ getArrayFromDType: getArrayFromDType,
+ checkConversionForErrors: checkConversionForErrors,
+ isValidDtype: isValidDtype,
+ hasEncodingLoss: hasEncodingLoss,
+ isTypedArray: isTypedArray,
+ bytesPerElement: bytesPerElement,
+ bytesFromStringArray: bytesFromStringArray,
+ isString: isString,
+ isBoolean: isBoolean,
+ isNumber: isNumber,
+ inferDtype: inferDtype,
+ isFunction: isFunction,
+ nearestDivisor: nearestDivisor,
+ computeStrides: computeStrides,
+ toNestedArray: toNestedArray,
+ makeOnesTypedArray: makeOnesTypedArray,
+ makeZerosTypedArray: makeZerosTypedArray,
+ makeZerosNestedTypedArray: makeZerosNestedTypedArray,
+ assertNonNegativeIntegerDimensions: assertNonNegativeIntegerDimensions,
+ locToIndex: locToIndex,
+ indexToLoc: indexToLoc,
+ isPromise: isPromise,
+ hexToLong: hexToLong,
+ fingerPrint64: fingerPrint64
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var Profiler = /** @class */ (function () {
+ function Profiler(backendTimer, logger) {
+ this.backendTimer = backendTimer;
+ this.logger = logger;
+ if (logger == null) {
+ this.logger = new Logger();
+ }
+ }
+ Profiler.prototype.profileKernel = function (kernelName, inputs, f) {
+ var outputs;
+ var holdResultWrapperFn = function () {
+ outputs = f();
+ };
+ var timer;
+ var start = now();
+ if (this.backendTimer.timerAvailable()) {
+ timer = this.backendTimer.time(holdResultWrapperFn);
+ }
+ else {
+ holdResultWrapperFn();
+ for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) {
+ var output = outputs_1[_i];
+ output.dataSync();
+ }
+ timer = Promise.resolve({ kernelMs: now() - start });
+ }
+ if (env().getBool('CHECK_COMPUTATION_FOR_ERRORS')) {
+ var _loop_1 = function (i) {
+ var output = outputs[i];
+ // Dangling promise here because we don't want to propagate up
+ // asynchronicity.
+ output.data().then(function (tensorVals) {
+ checkComputationForErrors(tensorVals, output.dtype, kernelName);
+ });
+ };
+ for (var i = 0; i < outputs.length; i++) {
+ _loop_1(i);
+ }
+ }
+ var kernelProfile = {
+ kernelName: kernelName,
+ outputs: outputs,
+ inputs: inputs,
+ timeMs: timer.then(function (timing) { return timing.kernelMs; }),
+ extraInfo: timer.then(function (timing) { return timing.getExtraProfileInfo != null ?
+ timing.getExtraProfileInfo() :
+ ''; })
+ };
+ return kernelProfile;
+ };
+ Profiler.prototype.logKernelProfile = function (kernelProfile) {
+ var _this = this;
+ var kernelName = kernelProfile.kernelName, outputs = kernelProfile.outputs, timeMs = kernelProfile.timeMs, inputs = kernelProfile.inputs, extraInfo = kernelProfile.extraInfo;
+ outputs.forEach(function (result) {
+ Promise.all([result.data(), timeMs, extraInfo]).then(function (valueContainer) {
+ _this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]);
+ });
+ });
+ };
+ return Profiler;
+ }());
+ function checkComputationForErrors(vals, dtype, kernelName) {
+ if (dtype !== 'float32') {
+ // Only floating point computations will generate NaN values
+ return false;
+ }
+ for (var i = 0; i < vals.length; i++) {
+ var num = vals[i];
+ if (isNaN(num) || !isFinite(num)) {
+ // Throwing custom exception so behavior is testable.
+ console.warn("Found " + num + " in the result of '" + kernelName + "'");
+ return true;
+ }
+ }
+ return false;
+ }
+ var Logger = /** @class */ (function () {
+ function Logger() {
+ }
+ Logger.prototype.logKernelProfile = function (name, result, vals, timeMs, inputs, extraInfo) {
+ var time = typeof timeMs === 'number' ? rightPad(timeMs + "ms", 9) :
+ timeMs['error'];
+ var paddedName = rightPad(name, 25);
+ var rank = result.rank;
+ var size = result.size;
+ var shape = rightPad(result.shape.toString(), 14);
+ var inputShapesDescription = '';
+ for (var name_1 in inputs) {
+ var input = inputs[name_1];
+ if (input != null) {
+ // The input might be a non-tensor (e.g HTMLImageElement), in which case
+ // we claim the output shape as input shape.
+ var inputShape = input.shape || result.shape;
+ var inputRank = inputShape.length;
+ inputShapesDescription +=
+ name_1 + ": " + inputRank + "D " + (inputRank > 0 ? inputShape : '') + " ";
+ }
+ }
+ console.log("%c" + paddedName + "\t%c" + time + "\t%c" + rank + "D " + shape + "\t%c" + size + "\t%c" + inputShapesDescription + "\t%c" + extraInfo, 'font-weight:bold', 'color:red', 'color:blue', 'color: orange', 'color: green', 'color: steelblue');
+ };
+ return Logger;
+ }());
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Computes a list of TapeNodes that connect x to y, filtering everything else
+ * out and preserving the order of the original tape elements.
+ *
+ * @param tape The tape elements to filter.
+ * @param xs The input Tensors.
+ * @param y The output Tensor.
+ */
+ function getFilteredNodesXToY(tape, xs, y) {
+ // Forward pass to compute all the nodes and Tensors that are transitively a
+ // function of x.
+ var tensorsFromX = {};
+ var nodesFromX = {};
+ for (var i = 0; i < xs.length; i++) {
+ tensorsFromX[xs[i].id] = true;
+ }
+ for (var i = 0; i < tape.length; i++) {
+ var node = tape[i];
+ var nodeInputs = node.inputs;
+ for (var inputName in nodeInputs) {
+ var input = nodeInputs[inputName];
+ var anyInputFromX = false;
+ for (var j = 0; j < xs.length; j++) {
+ if (tensorsFromX[input.id]) {
+ node.outputs.forEach(function (output) { return tensorsFromX[output.id] = true; });
+ anyInputFromX = true;
+ nodesFromX[node.id] = true;
+ break;
+ }
+ }
+ if (anyInputFromX) {
+ break;
+ }
+ }
+ }
+ // Backward pass to find all of the nodes and Tensors that lead to y.
+ var tensorsLeadToY = {};
+ tensorsLeadToY[y.id] = true;
+ var nodesToY = {};
+ for (var i = tape.length - 1; i >= 0; i--) {
+ var node = tape[i];
+ var nodeInputs = node.inputs;
+ // If any of the outputs lead to y, mark all of the inputs as leading to y.
+ for (var j = 0; j < node.outputs.length; j++) {
+ if (tensorsLeadToY[node.outputs[j].id]) {
+ for (var inputName in nodeInputs) {
+ tensorsLeadToY[nodeInputs[inputName].id] = true;
+ nodesToY[node.id] = true;
+ }
+ break;
+ }
+ }
+ }
+ // Return the paths that come from x and lead to y.
+ var filteredTape = [];
+ for (var i = 0; i < tape.length; i++) {
+ var node = tape[i];
+ if (nodesFromX[node.id] && nodesToY[node.id]) {
+ // Prune the inputs from the node that aren't a function of x.
+ var prunedInputs = {};
+ for (var inputName in node.inputs) {
+ var nodeInput = node.inputs[inputName];
+ if (tensorsFromX[nodeInput.id]) {
+ prunedInputs[inputName] = nodeInput;
+ }
+ }
+ // Copy the node and overwrite inputsAndArgs to the pruned version.
+ var prunedNode = Object.assign({}, node);
+ prunedNode.inputs = prunedInputs;
+ prunedNode.outputs = node.outputs;
+ filteredTape.push(prunedNode);
+ }
+ }
+ return filteredTape;
+ }
+ /**
+ * Backpropagate gradients through the filtered TapeNodes.
+ *
+ * @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map
+ * is mutated by this method.
+ * @param filteredTape The filtered TapeNodes to backprop through.
+ */
+ function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy, add) {
+ var _loop_1 = function (i) {
+ var node = filteredTape[i];
+ var dys = [];
+ node.outputs.forEach(function (o) {
+ var gradTensor = tensorAccumulatedGradientMap[o.id];
+ if (gradTensor != null) {
+ dys.push(gradTensor);
+ }
+ else {
+ // This particular output is not in the back-propagation subgraph, so it
+ // does not affect the final output, thus we put null for its dy.
+ dys.push(null);
+ }
+ });
+ if (node.gradient == null) {
+ throw new Error("Cannot compute gradient: gradient function not found " +
+ ("for " + node.kernelName + "."));
+ }
+ // Backprop dy through this node and accumulate gradients over the inputs.
+ var inputGradients = node.gradient(dys);
+ var _loop_2 = function (inputName) {
+ if (!(inputName in inputGradients)) {
+ throw new Error("Cannot backprop through input " + inputName + ". " +
+ ("Available gradients found: " + Object.keys(inputGradients) + "."));
+ }
+ // Call the gradient function.
+ var dx = tidy(function () { return inputGradients[inputName](); });
+ if (dx.dtype !== 'float32') {
+ throw new Error("Error in gradient for op " + node.kernelName + ". The gradient of input " +
+ (inputName + " must have 'float32' dtype, but has '" + dx.dtype + "'"));
+ }
+ var x = node.inputs[inputName];
+ if (!arraysEqual(dx.shape, x.shape)) {
+ throw new Error("Error in gradient for op " + node.kernelName + ". The gradient of input " +
+ ("'" + inputName + "' has shape '" + dx.shape + "', which does not match ") +
+ ("the shape of the input '" + x.shape + "'"));
+ }
+ if (tensorAccumulatedGradientMap[x.id] == null) {
+ tensorAccumulatedGradientMap[x.id] = dx;
+ }
+ else {
+ var curGradient = tensorAccumulatedGradientMap[x.id];
+ tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);
+ curGradient.dispose();
+ }
+ };
+ for (var inputName in node.inputs) {
+ _loop_2(inputName);
+ }
+ };
+ // Walk the tape backward and keep a map of Tensor to its gradient.
+ for (var i = filteredTape.length - 1; i >= 0; i--) {
+ _loop_1(i);
+ }
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // Maximum number of values before we decide to show ellipsis.
+ var FORMAT_LIMIT_NUM_VALS = 20;
+ // Number of first and last values to show when displaying a, b,...,y, z.
+ var FORMAT_NUM_FIRST_LAST_VALS = 3;
+ // Number of significant digits to show.
+ var FORMAT_NUM_SIG_DIGITS = 7;
+ function tensorToString(vals, shape, dtype, verbose) {
+ var strides = computeStrides(shape);
+ var padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);
+ var rank = shape.length;
+ var valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);
+ var lines = ['Tensor'];
+ if (verbose) {
+ lines.push(" dtype: " + dtype);
+ lines.push(" rank: " + rank);
+ lines.push(" shape: [" + shape + "]");
+ lines.push(" values:");
+ }
+ lines.push(valsLines.map(function (l) { return ' ' + l; }).join('\n'));
+ return lines.join('\n');
+ }
+ function computeMaxSizePerColumn(vals, shape, dtype, strides) {
+ var n = sizeFromShape(shape);
+ var numCols = strides[strides.length - 1];
+ var padPerCol = new Array(numCols).fill(0);
+ var rank = shape.length;
+ var valuesOrTuples = dtype === 'complex64' ? createComplexTuples(vals) : vals;
+ if (rank > 1) {
+ for (var row = 0; row < n / numCols; row++) {
+ var offset = row * numCols;
+ for (var j = 0; j < numCols; j++) {
+ padPerCol[j] = Math.max(padPerCol[j], valToString(valuesOrTuples[offset + j], 0, dtype).length);
+ }
+ }
+ }
+ return padPerCol;
+ }
+ function valToString(val, pad, dtype) {
+ var valStr;
+ if (Array.isArray(val)) {
+ valStr = parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS)) + " + " +
+ (parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS)) + "j");
+ }
+ else if (isString(val)) {
+ valStr = "'" + val + "'";
+ }
+ else if (dtype === 'bool') {
+ valStr = boolNumToString(val);
+ }
+ else {
+ valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();
+ }
+ return rightPad(valStr, pad);
+ }
+ function boolNumToString(v) {
+ return v === 0 ? 'false' : 'true';
+ }
+ function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast) {
+ if (isLast === void 0) { isLast = true; }
+ var storagePerElement = dtype === 'complex64' ? 2 : 1;
+ var size = shape[0];
+ var rank = shape.length;
+ if (rank === 0) {
+ if (dtype === 'complex64') {
+ var complexTuple = createComplexTuples(vals);
+ return [valToString(complexTuple[0], 0, dtype)];
+ }
+ if (dtype === 'bool') {
+ return [boolNumToString(vals[0])];
+ }
+ return [vals[0].toString()];
+ }
+ if (rank === 1) {
+ if (size > FORMAT_LIMIT_NUM_VALS) {
+ var firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;
+ var firstVals = Array.from(vals.slice(0, firstValsSize));
+ var lastVals = Array.from(vals.slice((size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size * storagePerElement));
+ if (dtype === 'complex64') {
+ firstVals = createComplexTuples(firstVals);
+ lastVals = createComplexTuples(lastVals);
+ }
+ return [
+ '[' +
+ firstVals.map(function (x, i) { return valToString(x, padPerCol[i], dtype); })
+ .join(', ') +
+ ', ..., ' +
+ lastVals
+ .map(function (x, i) { return valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype); })
+ .join(', ') +
+ ']'
+ ];
+ }
+ var displayVals = dtype === 'complex64' ? createComplexTuples(vals) :
+ Array.from(vals);
+ return [
+ '[' +
+ displayVals.map(function (x, i) { return valToString(x, padPerCol[i], dtype); })
+ .join(', ') +
+ ']'
+ ];
+ }
+ // The array is rank 2 or more.
+ var subshape = shape.slice(1);
+ var substrides = strides.slice(1);
+ var stride = strides[0] * storagePerElement;
+ var lines = [];
+ if (size > FORMAT_LIMIT_NUM_VALS) {
+ for (var i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {
+ var start = i * stride;
+ var end = start + stride;
+ lines.push.apply(lines, subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, false /* isLast */));
+ }
+ lines.push('...');
+ for (var i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {
+ var start = i * stride;
+ var end = start + stride;
+ lines.push.apply(lines, subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1 /* isLast */));
+ }
+ }
+ else {
+ for (var i = 0; i < size; i++) {
+ var start = i * stride;
+ var end = start + stride;
+ lines.push.apply(lines, subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1 /* isLast */));
+ }
+ }
+ var sep = rank === 2 ? ',' : '';
+ lines[0] = '[' + lines[0] + sep;
+ for (var i = 1; i < lines.length - 1; i++) {
+ lines[i] = ' ' + lines[i] + sep;
+ }
+ var newLineSep = ',\n';
+ for (var i = 2; i < rank; i++) {
+ newLineSep += '\n';
+ }
+ lines[lines.length - 1] =
+ ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);
+ return lines;
+ }
+ function createComplexTuples(vals) {
+ var complexTuples = [];
+ for (var i = 0; i < vals.length; i += 2) {
+ complexTuples.push([vals[i], vals[i + 1]]);
+ }
+ return complexTuples;
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * A mutable object, similar to `tf.Tensor`, that allows users to set values
+ * at locations before converting to an immutable `tf.Tensor`.
+ *
+ * See `tf.buffer` for creating a tensor buffer.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ var TensorBuffer = /** @class */ (function () {
+ function TensorBuffer(shape, dtype, values) {
+ var _this = this;
+ this.dtype = dtype;
+ this.shape = shape.slice();
+ this.size = sizeFromShape(shape);
+ if (values != null) {
+ var n_1 = values.length;
+ assert(n_1 === this.size, function () { return "Length of values '" + n_1 + "' does not match the size " +
+ ("inferred by the shape '" + _this.size + "'."); });
+ }
+ if (dtype === 'complex64') {
+ throw new Error("complex64 dtype TensorBuffers are not supported. Please create " +
+ "a TensorBuffer for the real and imaginary parts separately and " +
+ "call tf.complex(real, imag).");
+ }
+ this.values = values || getArrayFromDType(dtype, this.size);
+ this.strides = computeStrides(shape);
+ }
+ /**
+ * Sets a value in the buffer at a given location.
+ *
+ * @param value The value to set.
+ * @param locs The location indices.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ TensorBuffer.prototype.set = function (value) {
+ var _this = this;
+ var locs = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ locs[_i - 1] = arguments[_i];
+ }
+ if (locs.length === 0) {
+ locs = [0];
+ }
+ assert(locs.length === this.rank, function () { return "The number of provided coordinates (" + locs.length + ") must " +
+ ("match the rank (" + _this.rank + ")"); });
+ var index = this.locToIndex(locs);
+ this.values[index] = value;
+ };
+ /**
+ * Returns the value in the buffer at the provided location.
+ *
+ * @param locs The location indices.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ TensorBuffer.prototype.get = function () {
+ var locs = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ locs[_i] = arguments[_i];
+ }
+ if (locs.length === 0) {
+ locs = [0];
+ }
+ var i = 0;
+ for (var _a = 0, locs_1 = locs; _a < locs_1.length; _a++) {
+ var loc = locs_1[_a];
+ if (loc < 0 || loc >= this.shape[i]) {
+ var msg = "Requested out of range element at " + locs + ". " +
+ (" Buffer shape=" + this.shape);
+ throw new Error(msg);
+ }
+ i++;
+ }
+ var index = locs[locs.length - 1];
+ for (var i_1 = 0; i_1 < locs.length - 1; ++i_1) {
+ index += this.strides[i_1] * locs[i_1];
+ }
+ return this.values[index];
+ };
+ TensorBuffer.prototype.locToIndex = function (locs) {
+ if (this.rank === 0) {
+ return 0;
+ }
+ else if (this.rank === 1) {
+ return locs[0];
+ }
+ var index = locs[locs.length - 1];
+ for (var i = 0; i < locs.length - 1; ++i) {
+ index += this.strides[i] * locs[i];
+ }
+ return index;
+ };
+ TensorBuffer.prototype.indexToLoc = function (index) {
+ if (this.rank === 0) {
+ return [];
+ }
+ else if (this.rank === 1) {
+ return [index];
+ }
+ var locs = new Array(this.shape.length);
+ for (var i = 0; i < locs.length - 1; ++i) {
+ locs[i] = Math.floor(index / this.strides[i]);
+ index -= locs[i] * this.strides[i];
+ }
+ locs[locs.length - 1] = index;
+ return locs;
+ };
+ Object.defineProperty(TensorBuffer.prototype, "rank", {
+ get: function () {
+ return this.shape.length;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ /**
+ * Creates an immutable `tf.Tensor` object from the buffer.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ TensorBuffer.prototype.toTensor = function () {
+ return trackerFn().makeTensor(this.values, this.shape, this.dtype);
+ };
+ return TensorBuffer;
+ }());
+ // For tracking tensor creation and disposal.
+ var trackerFn = null;
+ // Used by chaining methods to call into ops.
+ var opHandler = null;
+ /**
+ * An external consumer can register itself as the tensor tracker. This way
+ * the Tensor class can notify the tracker for every tensor created and
+ * disposed.
+ */
+ function setTensorTracker(fn) {
+ trackerFn = fn;
+ }
+ /**
+ * An external consumer can register itself as the op handler. This way the
+ * Tensor class can have chaining methods that call into ops via the op
+ * handler.
+ */
+ function setOpHandler(handler) {
+ opHandler = handler;
+ }
+ /**
+ * A `tf.Tensor` object represents an immutable, multidimensional array of
+ * numbers that has a shape and a data type.
+ *
+ * For performance reasons, functions that create tensors do not necessarily
+ * perform a copy of the data passed to them (e.g. if the data is passed as a
+ * `Float32Array`), and changes to the data will change the tensor. This is not
+ * a feature and is not supported. To avoid this behavior, use the tensor before
+ * changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.
+ *
+ * See `tf.tensor` for details on how to create a `tf.Tensor`.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ var Tensor = /** @class */ (function () {
+ function Tensor(shape, dtype, dataId, id) {
+ /** Whether this tensor has been globally kept. */
+ this.kept = false;
+ this.isDisposedInternal = false;
+ this.shape = shape.slice();
+ this.dtype = dtype || 'float32';
+ this.size = sizeFromShape(shape);
+ this.strides = computeStrides(shape);
+ this.dataId = dataId;
+ this.id = id;
+ this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher');
+ }
+ Object.defineProperty(Tensor.prototype, "rank", {
+ get: function () {
+ return this.shape.length;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ /**
+ * Returns a promise of `tf.TensorBuffer` that holds the underlying data.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.buffer = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var vals;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0: return [4 /*yield*/, this.data()];
+ case 1:
+ vals = _a.sent();
+ return [2 /*return*/, opHandler.buffer(this.shape, this.dtype, vals)];
+ }
+ });
+ });
+ };
+ /**
+ * Returns a `tf.TensorBuffer` that holds the underlying data.
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.bufferSync = function () {
+ return opHandler.buffer(this.shape, this.dtype, this.dataSync());
+ };
+ /**
+ * Returns the tensor data as a nested array. The transfer of data is done
+ * asynchronously.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.array = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var vals;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0: return [4 /*yield*/, this.data()];
+ case 1:
+ vals = _a.sent();
+ return [2 /*return*/, toNestedArray(this.shape, vals, this.dtype === 'complex64')];
+ }
+ });
+ });
+ };
+ /**
+ * Returns the tensor data as a nested array. The transfer of data is done
+ * synchronously.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.arraySync = function () {
+ return toNestedArray(this.shape, this.dataSync(), this.dtype === 'complex64');
+ };
+ /**
+ * Asynchronously downloads the values from the `tf.Tensor`. Returns a
+ * promise of `TypedArray` that resolves when the computation has finished.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.data = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var data, bytes;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ this.throwIfDisposed();
+ data = trackerFn().read(this.dataId);
+ if (!(this.dtype === 'string')) return [3 /*break*/, 2];
+ return [4 /*yield*/, data];
+ case 1:
+ bytes = _a.sent();
+ try {
+ return [2 /*return*/, bytes.map(function (b) { return decodeString(b); })];
+ }
+ catch (_b) {
+ throw new Error('Failed to decode the string bytes into utf-8. ' +
+ 'To get the original bytes, call tensor.bytes().');
+ }
+ _a.label = 2;
+ case 2: return [2 /*return*/, data];
+ }
+ });
+ });
+ };
+ /**
+ * Synchronously downloads the values from the `tf.Tensor`. This blocks the
+ * UI thread until the values are ready, which can cause performance issues.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.dataSync = function () {
+ this.throwIfDisposed();
+ var data = trackerFn().readSync(this.dataId);
+ if (this.dtype === 'string') {
+ try {
+ return data.map(function (b) { return decodeString(b); });
+ }
+ catch (_a) {
+ throw new Error('Failed to decode the string bytes into utf-8. ' +
+ 'To get the original bytes, call tensor.bytes().');
+ }
+ }
+ return data;
+ };
+ /** Returns the underlying bytes of the tensor's data. */
+ Tensor.prototype.bytes = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var data;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ this.throwIfDisposed();
+ return [4 /*yield*/, trackerFn().read(this.dataId)];
+ case 1:
+ data = _a.sent();
+ if (this.dtype === 'string') {
+ return [2 /*return*/, data];
+ }
+ else {
+ return [2 /*return*/, new Uint8Array(data.buffer)];
+ }
+ }
+ });
+ });
+ };
+ /**
+ * Disposes `tf.Tensor` from memory.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.dispose = function () {
+ if (this.isDisposed) {
+ return;
+ }
+ trackerFn().disposeTensor(this);
+ this.isDisposedInternal = true;
+ };
+ Object.defineProperty(Tensor.prototype, "isDisposed", {
+ get: function () {
+ return this.isDisposedInternal;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Tensor.prototype.throwIfDisposed = function () {
+ if (this.isDisposed) {
+ throw new Error("Tensor is disposed.");
+ }
+ };
+ /**
+ * Prints the `tf.Tensor`. See `tf.print` for details.
+ *
+ * @param verbose Whether to print verbose information about the tensor,
+ * including dtype and size.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.print = function (verbose) {
+ if (verbose === void 0) { verbose = false; }
+ return opHandler.print(this, verbose);
+ };
+ /**
+ * Returns a copy of the tensor. See `tf.clone` for details.
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.clone = function () {
+ this.throwIfDisposed();
+ return opHandler.clone(this);
+ };
+ /**
+ * Returns a human-readable description of the tensor. Useful for logging.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Tensor.prototype.toString = function (verbose) {
+ if (verbose === void 0) { verbose = false; }
+ var vals = this.dataSync();
+ return tensorToString(vals, this.shape, this.dtype, verbose);
+ };
+ Tensor.prototype.cast = function (dtype) {
+ this.throwIfDisposed();
+ return opHandler.cast(this, dtype);
+ };
+ Tensor.prototype.variable = function (trainable, name, dtype) {
+ if (trainable === void 0) { trainable = true; }
+ this.throwIfDisposed();
+ return trackerFn().makeVariable(this, trainable, name, dtype);
+ };
+ return Tensor;
+ }());
+ Object.defineProperty(Tensor, Symbol.hasInstance, {
+ value: function (instance) {
+ // Implementation note: we should use properties of the object that will be
+ // defined before the constructor body has finished executing (methods).
+ // This is because when this code is transpiled by babel, babel will call
+ // classCallCheck before the constructor body is run.
+ // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.
+ return !!instance && instance.data != null && instance.dataSync != null &&
+ instance.throwIfDisposed != null;
+ }
+ });
+ function getGlobalTensorClass() {
+ // Use getGlobal so that we can augment the Tensor class across package
+ // boundaries becase the node resolution alg may result in different modules
+ // being returned for this file depending on the path they are loaded from.
+ return getGlobal('Tensor', function () {
+ return Tensor;
+ });
+ }
+ // Global side effect. Cache global reference to Tensor class
+ getGlobalTensorClass();
+ /**
+ * A mutable `tf.Tensor`, useful for persisting state, e.g. for training.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ var Variable = /** @class */ (function (_super) {
+ __extends(Variable, _super);
+ function Variable(initialValue, trainable, name, tensorId) {
+ var _this = _super.call(this, initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId) || this;
+ _this.trainable = trainable;
+ _this.name = name;
+ return _this;
+ }
+ /**
+ * Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have
+ * the same shape and dtype as the old `tf.Tensor`.
+ *
+ * @param newValue New tensor to be assigned to this variable.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Classes'}
+ */
+ Variable.prototype.assign = function (newValue) {
+ if (newValue.dtype !== this.dtype) {
+ throw new Error("dtype of the new value (" + newValue.dtype + ") and " +
+ ("previous value (" + this.dtype + ") must match"));
+ }
+ if (!arraysEqual(newValue.shape, this.shape)) {
+ throw new Error("shape of the new value (" + newValue.shape + ") and " +
+ ("previous value (" + this.shape + ") must match"));
+ }
+ trackerFn().disposeTensor(this);
+ this.dataId = newValue.dataId;
+ trackerFn().incRef(this, null /* backend */);
+ };
+ Variable.prototype.dispose = function () {
+ trackerFn().disposeVariable(this);
+ this.isDisposedInternal = true;
+ };
+ return Variable;
+ }(Tensor));
+ Object.defineProperty(Variable, Symbol.hasInstance, {
+ value: function (instance) {
+ return instance instanceof Tensor && instance.assign != null &&
+ instance.assign instanceof Function;
+ }
+ });
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ (function (Rank) {
+ Rank["R0"] = "R0";
+ Rank["R1"] = "R1";
+ Rank["R2"] = "R2";
+ Rank["R3"] = "R3";
+ Rank["R4"] = "R4";
+ Rank["R5"] = "R5";
+ Rank["R6"] = "R6";
+ })(exports.Rank || (exports.Rank = {}));
+ // Looks for upcasting types. Used, for example, in operations with mixed dtype
+ // inputs.
+ var UpcastInt32AndMap;
+ (function (UpcastInt32AndMap) {
+ UpcastInt32AndMap["float32"] = "float32";
+ UpcastInt32AndMap["int32"] = "int32";
+ UpcastInt32AndMap["bool"] = "int32";
+ UpcastInt32AndMap["complex64"] = "complex64";
+ })(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
+ var UpcastBoolAndMap;
+ (function (UpcastBoolAndMap) {
+ UpcastBoolAndMap["float32"] = "float32";
+ UpcastBoolAndMap["int32"] = "int32";
+ UpcastBoolAndMap["bool"] = "bool";
+ UpcastBoolAndMap["complex64"] = "complex64";
+ })(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
+ var UpcastFloat32AndMap;
+ (function (UpcastFloat32AndMap) {
+ UpcastFloat32AndMap["float32"] = "float32";
+ UpcastFloat32AndMap["int32"] = "float32";
+ UpcastFloat32AndMap["bool"] = "float32";
+ UpcastFloat32AndMap["complex64"] = "complex64";
+ })(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
+ var UpcastComplex64AndMap;
+ (function (UpcastComplex64AndMap) {
+ UpcastComplex64AndMap["float32"] = "complex64";
+ UpcastComplex64AndMap["int32"] = "complex64";
+ UpcastComplex64AndMap["bool"] = "complex64";
+ UpcastComplex64AndMap["complex64"] = "complex64";
+ })(UpcastComplex64AndMap || (UpcastComplex64AndMap = {}));
+ var upcastTypeMap = {
+ 'float32': UpcastFloat32AndMap,
+ 'int32': UpcastInt32AndMap,
+ 'bool': UpcastBoolAndMap,
+ 'complex64': UpcastComplex64AndMap
+ };
+ function upcastType(typeA, typeB) {
+ if (typeA === 'string' || typeB === 'string') {
+ if (typeA === 'string' && typeB === 'string') {
+ return 'string';
+ }
+ throw new Error("Can not upcast " + typeA + " with " + typeB);
+ }
+ return upcastTypeMap[typeA][typeB];
+ }
+ /** Returns the output type after summation. */
+ function sumOutType(type) {
+ return upcastType(type, 'int32');
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function makeTypesMatch(a, b) {
+ if (a.dtype === b.dtype) {
+ return [a, b];
+ }
+ var dtype = upcastType(a.dtype, b.dtype);
+ return [a.cast(dtype), b.cast(dtype)];
+ }
+ function assertTypesMatch(a, b) {
+ assert(a.dtype === b.dtype, function () { return "The dtypes of the first(" + a.dtype + ") and" +
+ (" second(" + b.dtype + ") input must match"); });
+ }
+ function isTensorInList(tensor, tensorList) {
+ return tensorList.some(function (x) { return x.id === tensor.id; });
+ }
+ /**
+ * Extracts any `Tensor`s found within the provided object.
+ *
+ * @param container an object that may be a `Tensor` or may directly contain
+ * `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it
+ * is safe to pass any object here, except that `Promise`s are not
+ * supported.
+ * @returns An array of `Tensors` found within the passed object. If the
+ * argument is simply a `Tensor', a list containing that `Tensor` is
+ * returned. If the object is not a `Tensor` or does not
+ * contain `Tensors`, an empty list is returned.
+ */
+ function getTensorsInContainer(result) {
+ var list = [];
+ var seen = new Set();
+ walkTensorContainer(result, list, seen);
+ return list;
+ }
+ function walkTensorContainer(container, list, seen) {
+ if (container == null) {
+ return;
+ }
+ if (container instanceof Tensor) {
+ list.push(container);
+ return;
+ }
+ if (!isIterable(container)) {
+ return;
+ }
+ // Iteration over keys works also for arrays.
+ var iterable = container;
+ for (var k in iterable) {
+ var val = iterable[k];
+ if (!seen.has(val)) {
+ seen.add(val);
+ walkTensorContainer(val, list, seen);
+ }
+ }
+ }
+ // tslint:disable-next-line:no-any
+ function isIterable(obj) {
+ return Array.isArray(obj) || typeof obj === 'object';
+ }
+
+ var tensor_util = {
+ __proto__: null,
+ makeTypesMatch: makeTypesMatch,
+ assertTypesMatch: assertTypesMatch,
+ isTensorInList: isTensorInList,
+ getTensorsInContainer: getTensorsInContainer
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function isRegisteredKernelInvocation(kernelInvocation) {
+ return kernelInvocation.kernelName != null;
+ }
+ var EngineState = /** @class */ (function () {
+ function EngineState() {
+ // Public since optimizers will use it.
+ this.registeredVariables = {};
+ this.nextTapeNodeId = 0;
+ this.numBytes = 0;
+ this.numTensors = 0;
+ this.numStringTensors = 0;
+ this.numDataBuffers = 0;
+ // Number of nested tf.grad() statements when computing higher-order
+ // gradients. E.g. `1` for first-order gradients and `2` for second-order
+ // gradients. Used to track if the tape should be removed after a backprop.
+ this.gradientDepth = 0;
+ // Number of nested kernel calls. When kernel depth is greater than 1, we turn
+ // off the tape.
+ this.kernelDepth = 0;
+ this.scopeStack = [];
+ /**
+ * Keeps track of the number of data moves during a kernel execution. We
+ * maintain a stack since kernels can call other kernels, recursively.
+ */
+ this.numDataMovesStack = [];
+ this.nextScopeId = 0;
+ this.tensorInfo = new WeakMap();
+ this.profiling = false;
+ this.activeProfile = {
+ newBytes: 0,
+ newTensors: 0,
+ peakBytes: 0,
+ kernels: [],
+ result: null,
+ get kernelNames() {
+ return Array.from(new Set(this.kernels.map(function (k) { return k.name; })));
+ }
+ };
+ }
+ EngineState.prototype.dispose = function () {
+ for (var variableName in this.registeredVariables) {
+ this.registeredVariables[variableName].dispose();
+ }
+ };
+ return EngineState;
+ }());
+ var Engine = /** @class */ (function () {
+ function Engine(ENV) {
+ this.ENV = ENV;
+ this.registry = {};
+ this.registryFactory = {};
+ this.pendingBackendInitId = 0;
+ this.state = new EngineState();
+ }
+ Engine.prototype.ready = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var sortedBackends, i, backendName, success;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ if (this.pendingBackendInit != null) {
+ return [2 /*return*/, this.pendingBackendInit.then(function () { })];
+ }
+ if (this.backendInstance != null) {
+ return [2 /*return*/];
+ }
+ sortedBackends = this.getSortedBackends();
+ i = 0;
+ _a.label = 1;
+ case 1:
+ if (!(i < sortedBackends.length)) return [3 /*break*/, 5];
+ backendName = sortedBackends[i];
+ return [4 /*yield*/, this.initializeBackend(backendName).success];
+ case 2:
+ success = _a.sent();
+ if (!success) return [3 /*break*/, 4];
+ return [4 /*yield*/, this.setBackend(backendName)];
+ case 3:
+ _a.sent();
+ return [2 /*return*/];
+ case 4:
+ i++;
+ return [3 /*break*/, 1];
+ case 5: throw new Error("Could not initialize any backends, all backend initializations " +
+ "failed.");
+ }
+ });
+ });
+ };
+ Object.defineProperty(Engine.prototype, "backend", {
+ get: function () {
+ if (this.pendingBackendInit != null) {
+ throw new Error("Backend '" + this.backendName + "' has not yet been initialized. Make " +
+ "sure to await tf.ready() or await tf.setBackend() before calling " +
+ "other methods");
+ }
+ if (this.backendInstance == null) {
+ var _a = this.initializeBackendsAndReturnBest(), name_1 = _a.name, asyncInit = _a.asyncInit;
+ if (asyncInit) {
+ throw new Error("The highest priority backend '" + name_1 + "' has not yet been " +
+ "initialized. Make sure to await tf.ready() or " +
+ "await tf.setBackend() before calling other methods");
+ }
+ this.setBackend(name_1);
+ }
+ return this.backendInstance;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ Engine.prototype.backendNames = function () {
+ return Object.keys(this.registryFactory);
+ };
+ Engine.prototype.findBackend = function (backendName) {
+ if (!(backendName in this.registry)) {
+ // If the backend hasn't been initialized but we have a registry entry for
+ // it, initialize it and return it.
+ if (backendName in this.registryFactory) {
+ var asyncInit = this.initializeBackend(backendName).asyncInit;
+ if (asyncInit) {
+ // Backend is not ready yet.
+ return null;
+ }
+ }
+ else {
+ return null;
+ }
+ }
+ return this.registry[backendName];
+ };
+ Engine.prototype.findBackendFactory = function (backendName) {
+ if (!(backendName in this.registryFactory)) {
+ return null;
+ }
+ return this.registryFactory[backendName].factory;
+ };
+ Engine.prototype.registerBackend = function (backendName, factory, priority) {
+ if (priority === void 0) { priority = 1; }
+ if (backendName in this.registryFactory) {
+ console.warn(backendName + " backend was already registered. " +
+ "Reusing existing backend factory.");
+ return false;
+ }
+ this.registryFactory[backendName] = { factory: factory, priority: priority };
+ return true;
+ };
+ Engine.prototype.setBackend = function (backendName) {
+ return __awaiter(this, void 0, void 0, function () {
+ var _a, success, asyncInit, result, _b;
+ return __generator(this, function (_c) {
+ switch (_c.label) {
+ case 0:
+ if (this.registryFactory[backendName] == null) {
+ throw new Error("Backend name '" + backendName + "' not found in registry");
+ }
+ this.backendName = backendName;
+ if (!(this.registry[backendName] == null)) return [3 /*break*/, 4];
+ this.backendInstance = null;
+ _a = this.initializeBackend(backendName), success = _a.success, asyncInit = _a.asyncInit;
+ if (!asyncInit) return [3 /*break*/, 2];
+ return [4 /*yield*/, success];
+ case 1:
+ _b = _c.sent();
+ return [3 /*break*/, 3];
+ case 2:
+ _b = success;
+ _c.label = 3;
+ case 3:
+ result = _b;
+ if (!result) {
+ return [2 /*return*/, false];
+ }
+ _c.label = 4;
+ case 4:
+ this.backendInstance = this.registry[backendName];
+ this.setupRegisteredKernels();
+ // Reset the profiler.
+ this.profiler = new Profiler(this.backendInstance);
+ return [2 /*return*/, true];
+ }
+ });
+ });
+ };
+ Engine.prototype.setupRegisteredKernels = function () {
+ var _this = this;
+ var kernels = getKernelsForBackend(this.backendName);
+ kernels.forEach(function (kernel) {
+ if (kernel.setupFunc != null) {
+ kernel.setupFunc(_this.backendInstance);
+ }
+ });
+ };
+ Engine.prototype.disposeRegisteredKernels = function (backendName) {
+ var _this = this;
+ var kernels = getKernelsForBackend(backendName);
+ kernels.forEach(function (kernel) {
+ if (kernel.disposeFunc != null) {
+ kernel.disposeFunc(_this.registry[backendName]);
+ }
+ });
+ };
+ /**
+ * Initializes a backend by looking up the backend name in the factory
+ * registry and calling the factory method. Returns a boolean representing
+ * whether the initialization of the backend suceeded. Throws an error if
+ * there is no backend in the factory registry.
+ */
+ Engine.prototype.initializeBackend = function (backendName) {
+ var _this = this;
+ var registryFactoryEntry = this.registryFactory[backendName];
+ if (registryFactoryEntry == null) {
+ throw new Error("Cannot initialize backend " + backendName + ", no registration found.");
+ }
+ try {
+ var backend = registryFactoryEntry.factory();
+ /* Test if the factory returns a promise.
+ Done in a more liberal way than
+ previous 'Promise.resolve(backend)===backend'
+ as we needed to account for custom Promise
+ implementations (e.g. Angular) */
+ if (backend && !(backend instanceof KernelBackend) &&
+ typeof backend.then === 'function') {
+ var promiseId_1 = ++this.pendingBackendInitId;
+ var success = backend
+ .then(function (backendInstance) {
+ // Outdated promise. Another backend was set in the meantime.
+ if (promiseId_1 < _this.pendingBackendInitId) {
+ return false;
+ }
+ _this.registry[backendName] = backendInstance;
+ _this.pendingBackendInit = null;
+ return true;
+ })
+ .catch(function (err) {
+ // Outdated promise. Another backend was set in the meantime.
+ if (promiseId_1 < _this.pendingBackendInitId) {
+ return false;
+ }
+ _this.pendingBackendInit = null;
+ console.warn("Initialization of backend " + backendName + " failed");
+ console.warn(err.stack || err.message);
+ return false;
+ });
+ this.pendingBackendInit = success;
+ return { success: success, asyncInit: true };
+ }
+ else {
+ this.registry[backendName] = backend;
+ return { success: true, asyncInit: false };
+ }
+ }
+ catch (err) {
+ console.warn("Initialization of backend " + backendName + " failed");
+ console.warn(err.stack || err.message);
+ return { success: false, asyncInit: false };
+ }
+ };
+ Engine.prototype.removeBackend = function (backendName) {
+ if (!(backendName in this.registryFactory)) {
+ throw new Error(backendName + " backend not found in registry");
+ }
+ if (this.backendName === backendName && this.pendingBackendInit != null) {
+ // There is a pending promise of the backend we want to remove. Make it
+ // obsolete.
+ this.pendingBackendInitId++;
+ }
+ if (backendName in this.registry) {
+ this.disposeRegisteredKernels(backendName);
+ this.registry[backendName].dispose();
+ delete this.registry[backendName];
+ }
+ delete this.registryFactory[backendName];
+ // Unset the backend if it is active.
+ if (this.backendName === backendName) {
+ this.pendingBackendInit = null;
+ this.backendName = null;
+ this.backendInstance = null;
+ }
+ };
+ Engine.prototype.getSortedBackends = function () {
+ var _this = this;
+ if (Object.keys(this.registryFactory).length === 0) {
+ throw new Error('No backend found in registry.');
+ }
+ return Object.keys(this.registryFactory).sort(function (a, b) {
+ // Highest priority comes first.
+ return _this.registryFactory[b].priority -
+ _this.registryFactory[a].priority;
+ });
+ };
+ Engine.prototype.initializeBackendsAndReturnBest = function () {
+ var sortedBackends = this.getSortedBackends();
+ for (var i = 0; i < sortedBackends.length; i++) {
+ var backendName = sortedBackends[i];
+ var _a = this.initializeBackend(backendName), success = _a.success, asyncInit = _a.asyncInit;
+ if (asyncInit || success) {
+ return { name: backendName, asyncInit: asyncInit };
+ }
+ }
+ throw new Error("Could not initialize any backends, all backend initializations " +
+ "failed.");
+ };
+ Engine.prototype.moveData = function (backend, dataId) {
+ var info = this.state.tensorInfo.get(dataId);
+ var srcBackend = info.backend;
+ var values = this.readSync(dataId);
+ var refCount = srcBackend.refCount(dataId);
+ // Delete the tensor from the old backend and move it to the new
+ // backend.
+ srcBackend.disposeData(dataId, true);
+ info.backend = backend;
+ backend.move(dataId, values, info.shape, info.dtype, refCount);
+ if (this.shouldCheckForMemLeaks()) {
+ // Track the number of moves during a kernel execution to correctly
+ // detect memory leaks.
+ this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
+ }
+ };
+ Engine.prototype.tidy = function (nameOrFn, fn) {
+ var _this = this;
+ var name = null;
+ if (fn == null) {
+ // Called with only 1 argument.
+ if (typeof nameOrFn !== 'function') {
+ throw new Error('Please provide a function to tidy()');
+ }
+ fn = nameOrFn;
+ }
+ else {
+ // Called with 2 arguments.
+ if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {
+ throw new Error('When calling with two arguments, the first argument ' +
+ 'to tidy() must be a string');
+ }
+ if (typeof fn !== 'function') {
+ throw new Error('When calling with two arguments, the 2nd argument ' +
+ 'to tidy() must be a function');
+ }
+ name = nameOrFn;
+ // TODO(nsthorat,smilkov): Do operation logging and performance
+ // profiling.
+ }
+ var result;
+ return this.scopedRun(function () { return _this.startScope(name); }, function () { return _this.endScope(result); }, function () {
+ result = fn();
+ if (result instanceof Promise) {
+ console.error('Cannot return a Promise inside of tidy.');
+ }
+ return result;
+ });
+ };
+ Engine.prototype.scopedRun = function (start, end, f) {
+ start();
+ try {
+ var res = f();
+ end();
+ return res;
+ }
+ catch (ex) {
+ end();
+ throw ex;
+ }
+ };
+ Engine.prototype.nextTensorId = function () {
+ return Engine.nextTensorId++;
+ };
+ Engine.prototype.nextVariableId = function () {
+ return Engine.nextVariableId++;
+ };
+ /**
+ * This method is called instead of the public-facing tensor.clone() when
+ * saving a tensor for backwards pass. It makes sure to add the clone
+ * operation to the tape regardless of being called inside a kernel
+ * execution.
+ */
+ Engine.prototype.clone = function (x) {
+ var y = ENGINE.runKernel(Identity, { x: x });
+ var inputs = { x: x };
+ var grad = function (dy) { return ({
+ x: function () {
+ var dtype = 'float32';
+ var gradInputs = { x: dy };
+ var attrs = { dtype: dtype };
+ return ENGINE.runKernel(Cast, gradInputs,
+ // tslint:disable-next-line: no-unnecessary-type-assertion
+ attrs);
+ }
+ }); };
+ var saved = [];
+ this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});
+ return y;
+ };
+ /**
+ * Execute a kernel with the given name and return the output tensor.
+ *
+ * @param kernelName The name of the kernel to execute.
+ * @param inputs A map of input names to tensors.
+ * @param attrs A map of attribute names to their values. An attribute is a
+ * primitive (non-tensor) input to the kernel.
+ * @param inputsToSave A list of tensors, inputs to save for the backprop
+ * computation.
+ * @param outputsToSave A list of booleans, specifying which output to save
+ * for the backprop computation. These are booleans since the output
+ * tensors are not visible to the user.
+ */
+ Engine.prototype.runKernel = function (kernelName, inputs, attrs) {
+ var hasKernel = getKernel(kernelName, this.backendName) != null;
+ if (!hasKernel) {
+ throw new Error("Kernel '" + kernelName + "' not registered for backend '" + this.backendName + "'");
+ }
+ return this.runKernelFunc({ kernelName: kernelName, inputs: inputs, attrs: attrs });
+ };
+ Engine.prototype.shouldCheckForMemLeaks = function () {
+ return this.ENV.getBool('IS_TEST');
+ };
+ Engine.prototype.checkKernelForMemLeak = function (kernelName, numDataIdsBefore, outInfos) {
+ var numDataIdsAfter = this.backend.numDataIds();
+ // Count the number of data ids associated with the result of the kernel.
+ var numOutputDataIds = 0;
+ outInfos.forEach(function (info) {
+ // Complex numbers allocate 3 data ids, one for 'real', one for
+ // 'imaginary', and one for the container that holds the former two.
+ numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);
+ });
+ // Account for the number of moves during kernel execution. A "data move"
+ // can happen in the middle of a kernel execution, placing a new (key,value)
+ // pair in the data storage. Since data moves have net zero effect (we
+ // always remove the data from the old backend), we have to cancel them out
+ // when detecting memory leaks.
+ var numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];
+ var dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;
+ if (dataIdsLeaked > 0) {
+ throw new Error("Backend '" + this.backendName + "' has an internal memory leak " +
+ ("(" + dataIdsLeaked + " data ids) after running '" + kernelName + "'"));
+ }
+ };
+ /**
+ * Internal helper method to execute a kernel Func
+ *
+ * Use `runKernel` to execute kernels from outside of engine.
+ */
+ Engine.prototype.runKernelFunc = function (kernelParams) {
+ var _this = this;
+ var outputs;
+ var saved = [];
+ var isTapeOn = this.isTapeOn();
+ var startingBytecount = this.state.numBytes;
+ var startingNumTensors = this.state.numTensors;
+ if (this.shouldCheckForMemLeaks()) {
+ this.state.numDataMovesStack.push(0);
+ }
+ var kernelFunc;
+ if (this.backendName == null) {
+ // backend has not been initialized yet (backend initialization is lazy
+ // can be deferred until an op/ kernel is run).
+ // The below getter has side effects that will try to initialize the
+ // backend and set properties like this.backendName
+ // tslint:disable-next-line: no-unused-expression
+ this.backend;
+ }
+ var out;
+ var kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?
+ kernelParams.kernelName :
+ this.state.activeScope != null ? this.state.activeScope.name : '';
+ // Create the kernelFunc from either a registered kernel OR passed in
+ // forward/backward functions (used by custom grad). In this context a
+ // kernelFunc wraps a kernel implementation with some bookkeeping.
+ if (isRegisteredKernelInvocation(kernelParams)) {
+ var kernelName_1 = kernelParams.kernelName, inputs_1 = kernelParams.inputs, attrs_1 = kernelParams.attrs;
+ if (this.backendName == null) {
+ // backend has not been initialized yet (backend initialization is lazy
+ // can be deferred until an op/ kernel is run).
+ // The below getter has side effects that will try to initialize the
+ // backend and set properties like this.backendName
+ // tslint:disable-next-line: no-unused-expression
+ this.backend;
+ }
+ var kernel_1 = getKernel(kernelName_1, this.backendName);
+ assert(kernel_1 != null, function () { return "Cannot find registered kernel '" + kernelName_1 + "' for backend '" + _this.backendName + "'"; });
+ kernelFunc = function () {
+ var numDataIdsBefore = _this.backend.numDataIds();
+ out = kernel_1.kernelFunc({ inputs: inputs_1, attrs: attrs_1, backend: _this.backend });
+ var outInfos = Array.isArray(out) ? out : [out];
+ if (_this.shouldCheckForMemLeaks()) {
+ _this.checkKernelForMemLeak(kernelName_1, numDataIdsBefore, outInfos);
+ }
+ var outTensors = outInfos.map(function (outInfo) {
+ // todo (yassogba) remove this option (Tensor) when node backend
+ // methods have been modularized and they all return tensorInfo.
+ // TensorInfos do not have a rank attribute.
+ if (outInfo.rank != null) {
+ return outInfo;
+ }
+ var _a = outInfo, dataId = _a.dataId, shape = _a.shape, dtype = _a.dtype;
+ return _this.makeTensorFromDataId(dataId, shape, dtype);
+ });
+ // Save any required inputs and outputs.
+ // Do not save unless we are recording to the tape. Otherwise it would
+ // cause a mem leak since there would be no backprop for these tensors
+ // (which would otherwise dispose them).
+ if (isTapeOn) {
+ var tensorsToSave = _this.getTensorsForGradient(kernelName_1, inputs_1, outTensors);
+ saved = _this.saveTensorsForBackwardMode(tensorsToSave);
+ }
+ return outTensors;
+ };
+ }
+ else {
+ var forwardFunc_1 = kernelParams.forwardFunc;
+ // Running a customGrad op.
+ var saveFunc_1 = function (tensors) {
+ // Do not save unless we are recording to the tape. Otherwise it would
+ // cause a mem leak since we would never run backprop, which disposes
+ // the kept tensors.
+ if (!isTapeOn) {
+ return;
+ }
+ saved = tensors.map(function (tensor) { return _this.keep(_this.clone(tensor)); });
+ };
+ kernelFunc = function () {
+ var numDataIdsBefore = _this.backend.numDataIds();
+ out = _this.tidy(function () { return forwardFunc_1(_this.backend, saveFunc_1); });
+ var outs = (Array.isArray(out) ? out : [out]);
+ if (_this.shouldCheckForMemLeaks()) {
+ // Scope name is used to print a more helpful error message if needed.
+ _this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);
+ }
+ return outs;
+ };
+ }
+ //
+ // Run the kernelFunc. Optionally profiling it.
+ //
+ var inputs = kernelParams.inputs, attrs = kernelParams.attrs;
+ var backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?
+ null :
+ kernelParams.backwardsFunc;
+ var kernelProfile;
+ this.scopedRun(
+ // Stop recording to a tape when running a kernel.
+ function () { return _this.state.kernelDepth++; }, function () { return _this.state.kernelDepth--; }, function () {
+ if (!_this.ENV.getBool('DEBUG') && !_this.state.profiling) {
+ outputs = kernelFunc();
+ }
+ else {
+ kernelProfile = _this.profiler.profileKernel(kernelOrScopeName, inputs, function () { return kernelFunc(); });
+ if (_this.ENV.getBool('DEBUG')) {
+ _this.profiler.logKernelProfile(kernelProfile);
+ }
+ outputs = kernelProfile.outputs;
+ }
+ });
+ if (isTapeOn) {
+ this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);
+ }
+ if (this.state.profiling) {
+ this.state.activeProfile.kernels.push({
+ name: kernelOrScopeName,
+ bytesAdded: this.state.numBytes - startingBytecount,
+ totalBytesSnapshot: this.state.numBytes,
+ tensorsAdded: this.state.numTensors - startingNumTensors,
+ totalTensorsSnapshot: this.state.numTensors,
+ inputShapes: Object.keys(inputs).map(function (key) { return inputs[key] != null ? inputs[key].shape : null; }),
+ outputShapes: outputs.map(function (item) { return item.shape; }),
+ kernelTimeMs: kernelProfile.timeMs,
+ extraInfo: kernelProfile.extraInfo
+ });
+ }
+ return (Array.isArray(out) ? outputs : outputs[0]);
+ };
+ /**
+ * Saves tensors used in forward mode for use in backward mode.
+ *
+ * @param tensors the list of tensors to save.
+ */
+ Engine.prototype.saveTensorsForBackwardMode = function (tensors) {
+ var _this = this;
+ var saved = tensors.map(function (tensor) { return _this.keep(_this.clone(tensor)); });
+ return saved;
+ };
+ /**
+ * Returns a list of tensors to save for a given gradient calculation.
+ *
+ * @param kernelName name of kernel to look up gradient for.
+ * @param inputs a map of input tensors.
+ * @param outputs an array of output tensors from forward mode of kernel.
+ */
+ Engine.prototype.getTensorsForGradient = function (kernelName, inputs, outputs) {
+ var gradConfig = getGradient(kernelName);
+ if (gradConfig != null) {
+ var inputsToSave = gradConfig.inputsToSave || [];
+ var outputsToSave_1 = gradConfig.outputsToSave || [];
+ // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs
+ // specified in inputsToSave will be saved.
+ var inputTensorsToSave = void 0;
+ if (gradConfig.saveAllInputs) {
+ assert(Array.isArray(inputs), function () { return 'saveAllInputs is true, expected inputs to be an array.'; });
+ inputTensorsToSave = Object.keys(inputs).map(function (key) { return inputs[key]; });
+ }
+ else {
+ inputTensorsToSave = inputsToSave.map(function (inputName) { return inputs[inputName]; });
+ }
+ var outputTensorsToSave = outputs.filter(function (_, i) { return outputsToSave_1[i]; });
+ return inputTensorsToSave.concat(outputTensorsToSave);
+ }
+ // We return an empty list rather than throw an error because the kernel we
+ // are looking up may not actually be relevant to backproping through the
+ // overall function
+ //
+ // See 'does not error if irrelevant (pruned) ops are missing grads' test
+ // in gradients_test.ts for an example.
+ return [];
+ };
+ /**
+ * Internal method used by public APIs for tensor creation. Makes a new
+ * tensor with the provided shape, dtype and values. It always
+ * creates a new data id and writes the values to the underlying backend.
+ */
+ Engine.prototype.makeTensor = function (values, shape, dtype, backend) {
+ if (values == null) {
+ throw new Error('Values passed to engine.makeTensor() are null');
+ }
+ dtype = dtype || 'float32';
+ backend = backend || this.backend;
+ var backendVals = values;
+ if (dtype === 'string' && isString(values[0])) {
+ backendVals = values.map(function (d) { return encodeString(d); });
+ }
+ var dataId = backend.write(backendVals, shape, dtype);
+ var t = new Tensor(shape, dtype, dataId, this.nextTensorId());
+ this.trackTensor(t, backend);
+ // Count bytes for string tensors.
+ if (dtype === 'string') {
+ var info = this.state.tensorInfo.get(dataId);
+ var newBytes = bytesFromStringArray(backendVals);
+ this.state.numBytes += newBytes - info.bytes;
+ info.bytes = newBytes;
+ }
+ return t;
+ };
+ /**
+ * Internal method used by backends. Makes a new tensor
+ * that is a wrapper around an existing data id. It doesn't create
+ * a new data id, only increments the ref count used in memory tracking.
+ */
+ Engine.prototype.makeTensorFromDataId = function (dataId, shape, dtype, backend) {
+ dtype = dtype || 'float32';
+ var t = new Tensor(shape, dtype, dataId, this.nextTensorId());
+ this.trackTensor(t, backend);
+ return t;
+ };
+ Engine.prototype.makeVariable = function (initialValue, trainable, name, dtype) {
+ if (trainable === void 0) { trainable = true; }
+ name = name || this.nextVariableId().toString();
+ if (dtype != null && dtype !== initialValue.dtype) {
+ initialValue = initialValue.cast(dtype);
+ }
+ var v = new Variable(initialValue, trainable, name, this.nextTensorId());
+ if (this.state.registeredVariables[v.name] != null) {
+ throw new Error("Variable with name " + v.name + " was already registered");
+ }
+ this.state.registeredVariables[v.name] = v;
+ this.incRef(v, this.backend);
+ return v;
+ };
+ Engine.prototype.trackTensor = function (a, backend) {
+ this.state.numTensors++;
+ if (a.dtype === 'string') {
+ this.state.numStringTensors++;
+ }
+ // Bytes for complex numbers are counted by their components. Bytes for
+ // string tensors are counted when writing values.
+ var bytes = 0;
+ if (a.dtype !== 'complex64' && a.dtype !== 'string') {
+ bytes = a.size * bytesPerElement(a.dtype);
+ }
+ this.state.numBytes += bytes;
+ if (!this.state.tensorInfo.has(a.dataId)) {
+ this.state.numDataBuffers++;
+ this.state.tensorInfo.set(a.dataId, {
+ backend: backend || this.backend,
+ dtype: a.dtype,
+ shape: a.shape,
+ bytes: bytes
+ });
+ }
+ if (!(a instanceof Variable)) {
+ this.track(a);
+ }
+ };
+ // Track the tensor by dataId and increase the refCount for the dataId in the
+ // backend.
+ // TODO(pyu10055): This is currently used by makeVariable method, to increase
+ // refCount on the backend for the dataId. It can potentially be replaced with
+ // Identity op indead of calling backend directly.
+ Engine.prototype.incRef = function (a, backend) {
+ this.trackTensor(a, backend);
+ this.backend.incRef(a.dataId);
+ };
+ Engine.prototype.removeDataId = function (dataId, backend) {
+ if (this.state.tensorInfo.has(dataId) &&
+ this.state.tensorInfo.get(dataId).backend === backend) {
+ this.state.tensorInfo.delete(dataId);
+ this.state.numDataBuffers--;
+ }
+ };
+ Engine.prototype.disposeTensor = function (a) {
+ if (!this.state.tensorInfo.has(a.dataId)) {
+ return;
+ }
+ var info = this.state.tensorInfo.get(a.dataId);
+ this.state.numTensors--;
+ if (a.dtype === 'string') {
+ this.state.numStringTensors--;
+ this.state.numBytes -= info.bytes;
+ }
+ // Don't count bytes for complex numbers as they are counted by their
+ // components.
+ if (a.dtype !== 'complex64' && a.dtype !== 'string') {
+ var bytes = a.size * bytesPerElement(a.dtype);
+ this.state.numBytes -= bytes;
+ }
+ // Remove the reference to dataId if backend dispose the data successfully
+ if (info.backend.disposeData(a.dataId)) {
+ this.removeDataId(a.dataId, info.backend);
+ }
+ // TODO(nsthorat): Construct an error and save the stack trace for
+ // debugging when in debug mode. Creating a stack trace is too expensive
+ // to do unconditionally.
+ };
+ Engine.prototype.disposeVariables = function () {
+ for (var varName in this.state.registeredVariables) {
+ var v = this.state.registeredVariables[varName];
+ this.disposeVariable(v);
+ }
+ };
+ Engine.prototype.disposeVariable = function (v) {
+ this.disposeTensor(v);
+ if (this.state.registeredVariables[v.name] != null) {
+ delete this.state.registeredVariables[v.name];
+ }
+ };
+ Engine.prototype.memory = function () {
+ var info = this.backend.memory();
+ info.numTensors = this.state.numTensors;
+ info.numDataBuffers = this.state.numDataBuffers;
+ info.numBytes = this.state.numBytes;
+ if (this.state.numStringTensors > 0) {
+ info.unreliable = true;
+ if (info.reasons == null) {
+ info.reasons = [];
+ }
+ info.reasons.push('Memory usage by string tensors is approximate ' +
+ '(2 bytes per character)');
+ }
+ return info;
+ };
+ Engine.prototype.profile = function (query) {
+ return __awaiter(this, void 0, void 0, function () {
+ var startBytes, startNumTensors, _a, _i, _b, kernel, _c, _d;
+ return __generator(this, function (_e) {
+ switch (_e.label) {
+ case 0:
+ this.state.profiling = true;
+ startBytes = this.state.numBytes;
+ startNumTensors = this.state.numTensors;
+ this.state.activeProfile.kernels = [];
+ _a = this.state.activeProfile;
+ return [4 /*yield*/, query()];
+ case 1:
+ _a.result = _e.sent();
+ this.state.profiling = false;
+ this.state.activeProfile.peakBytes = Math.max.apply(Math, this.state.activeProfile.kernels.map(function (d) { return d.totalBytesSnapshot; }));
+ this.state.activeProfile.newBytes = this.state.numBytes - startBytes;
+ this.state.activeProfile.newTensors =
+ this.state.numTensors - startNumTensors;
+ _i = 0, _b = this.state.activeProfile.kernels;
+ _e.label = 2;
+ case 2:
+ if (!(_i < _b.length)) return [3 /*break*/, 6];
+ kernel = _b[_i];
+ _c = kernel;
+ return [4 /*yield*/, kernel.kernelTimeMs];
+ case 3:
+ _c.kernelTimeMs = _e.sent();
+ _d = kernel;
+ return [4 /*yield*/, kernel.extraInfo];
+ case 4:
+ _d.extraInfo = _e.sent();
+ _e.label = 5;
+ case 5:
+ _i++;
+ return [3 /*break*/, 2];
+ case 6: return [2 /*return*/, this.state.activeProfile];
+ }
+ });
+ });
+ };
+ Engine.prototype.isTapeOn = function () {
+ return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
+ };
+ Engine.prototype.addTapeNode = function (kernelName, inputs, outputs, gradientsFunc, saved, attrs) {
+ var _this = this;
+ var tapeNode = { id: this.state.nextTapeNodeId++, kernelName: kernelName, inputs: inputs, outputs: outputs, saved: saved };
+ var gradConfig = getGradient(kernelName);
+ if (gradConfig != null) {
+ gradientsFunc = gradConfig.gradFunc;
+ }
+ if (gradientsFunc != null) {
+ tapeNode.gradient = function (dys) {
+ // TODO(smilkov): To optimize back-prop, pass dys that are not used in
+ // the backprop graph to the user as null instead of zeros
+ dys = dys.map(function (dy, i) {
+ if (dy == null) {
+ var output = outputs[i];
+ var vals = makeZerosTypedArray(output.size, output.dtype);
+ return _this.makeTensor(vals, output.shape, output.dtype);
+ }
+ return dy;
+ });
+ // Grad functions of ops with single outputs expect a dy, while ops
+ // with multiple outputs expect dys (array of dy).
+ return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);
+ };
+ }
+ this.state.activeTape.push(tapeNode);
+ };
+ Engine.prototype.keep = function (result) {
+ result.kept = true;
+ return result;
+ };
+ Engine.prototype.startTape = function () {
+ if (this.state.gradientDepth === 0) {
+ this.state.activeTape = [];
+ }
+ this.state.gradientDepth++;
+ };
+ Engine.prototype.endTape = function () {
+ this.state.gradientDepth--;
+ };
+ /**
+ * Start a scope. Use this with endScope() to achieve the same functionality
+ * as scope() without the need for a function closure.
+ */
+ Engine.prototype.startScope = function (name) {
+ var scopeInfo = {
+ track: [],
+ name: 'unnamed scope',
+ id: this.state.nextScopeId++
+ };
+ if (name) {
+ scopeInfo.name = name;
+ }
+ this.state.scopeStack.push(scopeInfo);
+ this.state.activeScope = scopeInfo;
+ };
+ /**
+ * End a scope. Use this with startScope() to achieve the same functionality
+ * as scope() without the need for a function closure.
+ */
+ Engine.prototype.endScope = function (result) {
+ var _this = this;
+ var tensorsToTrackInParent = getTensorsInContainer(result);
+ var tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map(function (t) { return t.id; }));
+ // Dispose the arrays tracked in this scope.
+ for (var i = 0; i < this.state.activeScope.track.length; i++) {
+ var tensor = this.state.activeScope.track[i];
+ if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {
+ tensor.dispose();
+ }
+ }
+ var oldScope = this.state.scopeStack.pop();
+ this.state.activeScope = this.state.scopeStack.length === 0 ?
+ null :
+ this.state.scopeStack[this.state.scopeStack.length - 1];
+ // Track the current result in the parent scope.
+ tensorsToTrackInParent.forEach(function (tensor) {
+ // Only track the tensor if was allocated in the inner scope and is not
+ // globally kept.
+ if (!tensor.kept && tensor.scopeId === oldScope.id) {
+ _this.track(tensor);
+ }
+ });
+ };
+ /**
+ * Returns gradients of `f` with respect to each of the `xs`. The gradients
+ * returned are of the same length as `xs`, but some might be null if `f`
+ * was not a function of that `x`. It also takes optional dy to multiply the
+ * gradient, which defaults to `1`.
+ */
+ Engine.prototype.gradients = function (f, xs, dy, allowNoGradients) {
+ var _this = this;
+ if (allowNoGradients === void 0) { allowNoGradients = false; }
+ assert(xs.length > 0, function () { return 'gradients() received an empty list of xs.'; });
+ if (dy != null && dy.dtype !== 'float32') {
+ throw new Error("dy must have 'float32' dtype, but has '" + dy.dtype + "'");
+ }
+ var y = this.scopedRun(function () { return _this.startTape(); }, function () { return _this.endTape(); }, function () { return _this.tidy('forward', f); });
+ assert(y instanceof Tensor, function () { return 'The result y returned by f() must be a tensor.'; });
+ // Filter out the nodes that don't connect x => y.
+ var filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);
+ if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {
+ throw new Error('Cannot compute gradient of y=f(x) with respect to x. Make sure ' +
+ 'that the f you passed encloses all operations that lead from x ' +
+ 'to y.');
+ }
+ return this.tidy('backward', function () {
+ var accumulatedGradientMap = {};
+ accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;
+ // Backprop gradients through the filtered nodes.
+ backpropagateGradients(accumulatedGradientMap, filteredTape,
+ // Pass the tidy function to avoid circular dep with `tape.ts`.
+ function (f) { return _this.tidy(f); },
+ // Pass an add function to avoide a circular dep with `tape.ts`.
+ add);
+ var grads = xs.map(function (x) { return accumulatedGradientMap[x.id]; });
+ if (_this.state.gradientDepth === 0) {
+ // This means that we are not computing higher-order gradients
+ // and can clean up the tape.
+ _this.state.activeTape.forEach(function (node) {
+ for (var _i = 0, _a = node.saved; _i < _a.length; _i++) {
+ var tensor = _a[_i];
+ tensor.dispose();
+ }
+ });
+ _this.state.activeTape = null;
+ }
+ return { value: y, grads: grads };
+ });
+ };
+ Engine.prototype.customGrad = function (f) {
+ var _this = this;
+ assert(isFunction(f), function () { return 'The f passed in customGrad(f) must be a function.'; });
+ return function () {
+ var inputs = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ inputs[_i] = arguments[_i];
+ }
+ assert(inputs.every(function (t) { return t instanceof Tensor; }), function () { return 'The args passed in customGrad(f)(x1, x2,...) must all be ' +
+ 'tensors'; });
+ var res;
+ var inputMap = {};
+ inputs.forEach(function (input, i) {
+ inputMap[i] = input;
+ });
+ var forwardFunc = function (_, save) {
+ res = f.apply(void 0, inputs.concat([save]));
+ assert(res.value instanceof Tensor, function () { return 'The function f passed in customGrad(f) must return an ' +
+ 'object where `obj.value` is a tensor'; });
+ assert(isFunction(res.gradFunc), function () { return 'The function f passed in customGrad(f) must return an ' +
+ 'object where `obj.gradFunc` is a function.'; });
+ return res.value;
+ };
+ var backwardsFunc = function (dy, saved) {
+ var gradRes = res.gradFunc(dy, saved);
+ var grads = Array.isArray(gradRes) ? gradRes : [gradRes];
+ assert(grads.length === inputs.length, function () { return 'The function f passed in customGrad(f) must return an ' +
+ 'object where `obj.gradFunc` is a function that returns ' +
+ 'the same number of tensors as inputs passed to f(...).'; });
+ assert(grads.every(function (t) { return t instanceof Tensor; }), function () { return 'The function f passed in customGrad(f) must return an ' +
+ 'object where `obj.gradFunc` is a function that returns ' +
+ 'a list of only tensors.'; });
+ var gradMap = {};
+ grads.forEach(function (grad, i) {
+ gradMap[i] = function () { return grad; };
+ });
+ return gradMap;
+ };
+ return _this.runKernelFunc({
+ forwardFunc: forwardFunc,
+ backwardsFunc: backwardsFunc,
+ inputs: inputMap,
+ });
+ };
+ };
+ Engine.prototype.readSync = function (dataId) {
+ // Route the read to the correct backend.
+ var info = this.state.tensorInfo.get(dataId);
+ return info.backend.readSync(dataId);
+ };
+ Engine.prototype.read = function (dataId) {
+ // Route the read to the correct backend.
+ var info = this.state.tensorInfo.get(dataId);
+ return info.backend.read(dataId);
+ };
+ Engine.prototype.time = function (query) {
+ return __awaiter(this, void 0, void 0, function () {
+ var start, timingInfo;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ start = now();
+ return [4 /*yield*/, this.backend.time(query)];
+ case 1:
+ timingInfo = _a.sent();
+ timingInfo.wallMs = now() - start;
+ return [2 /*return*/, timingInfo];
+ }
+ });
+ });
+ };
+ /**
+ * Tracks a Tensor in the current scope to be automatically cleaned up
+ * when the current scope ends, and returns the value.
+ *
+ * @param result The Tensor to track in the current scope.
+ */
+ Engine.prototype.track = function (result) {
+ if (this.state.activeScope != null) {
+ result.scopeId = this.state.activeScope.id;
+ this.state.activeScope.track.push(result);
+ }
+ return result;
+ };
+ Object.defineProperty(Engine.prototype, "registeredVariables", {
+ get: function () {
+ return this.state.registeredVariables;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ /**
+ * Resets the engine state. Removes all backends but does not remove
+ * registered backend factories.
+ */
+ Engine.prototype.reset = function () {
+ // Make any pending promise obsolete.
+ this.pendingBackendInitId++;
+ this.state.dispose();
+ this.ENV.reset();
+ this.state = new EngineState();
+ for (var backendName in this.registry) {
+ this.disposeRegisteredKernels(backendName);
+ this.registry[backendName].dispose();
+ delete this.registry[backendName];
+ }
+ this.backendName = null;
+ this.backendInstance = null;
+ this.pendingBackendInit = null;
+ };
+ Engine.nextTensorId = 0;
+ Engine.nextVariableId = 0;
+ return Engine;
+ }());
+ function ones(shape) {
+ var values = makeOnesTypedArray(sizeFromShape(shape), 'float32');
+ return ENGINE.makeTensor(values, shape, 'float32');
+ }
+ function getOrMakeEngine() {
+ var ns = getGlobalNamespace();
+ if (ns._tfengine == null) {
+ var environment = new Environment(ns);
+ ns._tfengine = new Engine(environment);
+ }
+ setEnvironmentGlobal(ns._tfengine.ENV);
+ // Tell the current tensor interface that the global engine is responsible
+ // for tracking.
+ setTensorTracker(function () { return ns._tfengine; });
+ return ns._tfengine;
+ }
+ var ENGINE = getOrMakeEngine();
+ /**
+ * A implementation of the add op for use within engine and tape.
+ *
+ * This allows us to avoid a circular dependency between add.ts and engine.
+ * It is exported to be available in tape tests.
+ */
+ function add(a, b) {
+ // We duplicate Add here to avoid a circular dependency with add.ts.
+ var inputs = { a: a, b: b };
+ return ENGINE.runKernel(Add, inputs);
+ }
+
+ /**
+ * @license
+ * Copyright 2017 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // tslint:disable-next-line:no-any
+ function _isNavigatorDefined() {
+ return typeof navigator !== 'undefined' && navigator != null;
+ }
+ function isMobile(nav) {
+ if (nav || _isNavigatorDefined()) {
+ if (!nav) {
+ nav = navigator;
+ }
+ if (nav.product === 'ReactNative') {
+ return true;
+ }
+ // tslint:disable-next-line:no-any
+ var a = nav.userAgent || nav.vendor || window.opera;
+ // tslint:disable-next-line:max-line-length
+ return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i
+ .test(a) ||
+ // tslint:disable-next-line:max-line-length
+ /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(a.substr(0, 4));
+ }
+ return false;
+ }
+ function isBrowser() {
+ return (typeof window !== 'undefined' && window.document != null) ||
+ //@ts-ignore
+ (typeof WorkerGlobalScope !== 'undefined');
+ }
+
+ var device_util = {
+ __proto__: null,
+ isMobile: isMobile,
+ isBrowser: isBrowser
+ };
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var ENV = env();
+ /**
+ * This file contains environment-related flag registrations.
+ */
+ /** Whether to enable debug mode. */
+ ENV.registerFlag('DEBUG', function () { return false; }, function (debugValue) {
+ if (debugValue) {
+ console.warn('Debugging mode is ON. The output of every math call will ' +
+ 'be downloaded to CPU and checked for NaNs. ' +
+ 'This significantly impacts performance.');
+ }
+ });
+ /** Whether we are in a browser (as versus, say, node.js) environment. */
+ ENV.registerFlag('IS_BROWSER', function () { return isBrowser(); });
+ /** Whether we are in a browser (as versus, say, node.js) environment. */
+ ENV.registerFlag('IS_NODE', function () { return (typeof process !== 'undefined') &&
+ (typeof process.versions !== 'undefined') &&
+ (typeof process.versions.node !== 'undefined'); });
+ /** Whether this browser is Chrome. */
+ ENV.registerFlag('IS_CHROME', function () { return typeof navigator !== 'undefined' && navigator != null &&
+ navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&
+ /Google Inc/.test(navigator.vendor); });
+ /**
+ * True when the environment is "production" where we disable safety checks
+ * to gain performance.
+ */
+ ENV.registerFlag('PROD', function () { return false; });
+ /**
+ * Whether to do sanity checks when inferring a shape from user-provided
+ * values, used when creating a new tensor.
+ */
+ ENV.registerFlag('TENSORLIKE_CHECK_SHAPE_CONSISTENCY', function () { return ENV.getBool('DEBUG'); });
+ /** Whether deprecation warnings are enabled. */
+ ENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', function () { return true; });
+ /** True if running unit tests. */
+ ENV.registerFlag('IS_TEST', function () { return false; });
+ /** Whether to check computation result for errors. */
+ ENV.registerFlag('CHECK_COMPUTATION_FOR_ERRORS', function () { return true; });
+ /** Whether the backend needs to wrap input to imageBitmap. */
+ ENV.registerFlag('WRAP_TO_IMAGEBITMAP', function () { return false; });
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ function inferShape(val, dtype) {
+ var firstElem = val;
+ if (isTypedArray(val)) {
+ return dtype === 'string' ? [] : [val.length];
+ }
+ if (!Array.isArray(val)) {
+ return []; // Scalar.
+ }
+ var shape = [];
+ while (Array.isArray(firstElem) ||
+ isTypedArray(firstElem) && dtype !== 'string') {
+ shape.push(firstElem.length);
+ firstElem = firstElem[0];
+ }
+ if (Array.isArray(val) &&
+ env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {
+ deepAssertShapeConsistency(val, shape, []);
+ }
+ return shape;
+ }
+ function deepAssertShapeConsistency(val, shape, indices) {
+ indices = indices || [];
+ if (!(Array.isArray(val)) && !isTypedArray(val)) {
+ assert(shape.length === 0, function () { return "Element arr[" + indices.join('][') + "] is a primitive, " +
+ ("but should be an array/TypedArray of " + shape[0] + " elements"); });
+ return;
+ }
+ assert(shape.length > 0, function () { return "Element arr[" + indices.join('][') + "] should be a primitive, " +
+ ("but is an array of " + val.length + " elements"); });
+ assert(val.length === shape[0], function () { return "Element arr[" + indices.join('][') + "] should have " + shape[0] + " " +
+ ("elements, but has " + val.length + " elements"); });
+ var subShape = shape.slice(1);
+ for (var i = 0; i < val.length; ++i) {
+ deepAssertShapeConsistency(val[i], subShape, indices.concat(i));
+ }
+ }
+ function assertDtype(expectedDtype, actualDType, argName, functionName) {
+ if (expectedDtype === 'string_or_numeric') {
+ return;
+ }
+ if (expectedDtype == null) {
+ throw new Error("Expected dtype cannot be null.");
+ }
+ if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||
+ expectedDtype === 'numeric' && actualDType === 'string') {
+ throw new Error("Argument '" + argName + "' passed to '" + functionName + "' must " +
+ ("be " + expectedDtype + " tensor, but got " + actualDType + " tensor"));
+ }
+ }
+ function convertToTensor(x, argName, functionName, parseAsDtype) {
+ if (parseAsDtype === void 0) { parseAsDtype = 'numeric'; }
+ if (x instanceof Tensor) {
+ assertDtype(parseAsDtype, x.dtype, argName, functionName);
+ return x;
+ }
+ var inferredDtype = inferDtype(x);
+ // If the user expects a bool/int/float, use that info to update the
+ // inferredDtype when it is not a string.
+ if (inferredDtype !== 'string' &&
+ ['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {
+ inferredDtype = parseAsDtype;
+ }
+ assertDtype(parseAsDtype, inferredDtype, argName, functionName);
+ if ((x == null) ||
+ (!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&
+ typeof x !== 'boolean' && typeof x !== 'string')) {
+ var type = x == null ? 'null' : x.constructor.name;
+ throw new Error("Argument '" + argName + "' passed to '" + functionName + "' must be a " +
+ ("Tensor or TensorLike, but got '" + type + "'"));
+ }
+ var inferredShape = inferShape(x, inferredDtype);
+ if (!isTypedArray(x) && !Array.isArray(x)) {
+ x = [x];
+ }
+ var skipTypedArray = true;
+ var values = inferredDtype !== 'string' ?
+ toTypedArray(x, inferredDtype) :
+ flatten(x, [], skipTypedArray);
+ return ENGINE.makeTensor(values, inferredShape, inferredDtype);
+ }
+ function convertToTensorArray(arg, argName, functionName, parseAsDtype) {
+ if (parseAsDtype === void 0) { parseAsDtype = 'numeric'; }
+ if (!Array.isArray(arg)) {
+ throw new Error("Argument " + argName + " passed to " + functionName + " must be a " +
+ '`Tensor[]` or `TensorLike[]`');
+ }
+ var tensors = arg;
+ return tensors.map(function (t, i) {
+ return convertToTensor(t, argName + "[" + i + "]", functionName, parseAsDtype);
+ });
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var OP_SCOPE_SUFFIX = '__op';
+ /**
+ * Used for wrapping functions that perform math operations on
+ * Tensors. The function will be wrapped in a named scope that cleans all
+ * memory usage after the function is done.
+ */
+ function op(f) {
+ var keys = Object.keys(f);
+ if (keys.length !== 1) {
+ throw new Error("Please provide an object with a single key " +
+ "(operation name) mapping to a function. Got an object with " +
+ (keys.length + " keys."));
+ }
+ var opName = keys[0];
+ var fn = f[opName];
+ // Strip the underscore from the end of the function name.
+ if (opName.endsWith('_')) {
+ opName = opName.substring(0, opName.length - 1);
+ }
+ // add an __op suffix to distinguish ops from kernels in tf.profile
+ opName = opName + OP_SCOPE_SUFFIX;
+ // tslint:disable-next-line:no-any
+ var f2 = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ ENGINE.startScope(opName);
+ try {
+ var result = fn.apply(void 0, args);
+ if (isPromise(result)) {
+ console.error('Cannot return a Promise inside of tidy.');
+ }
+ ENGINE.endScope(result);
+ return result;
+ }
+ catch (ex) {
+ ENGINE.endScope(null);
+ throw ex;
+ }
+ };
+ Object.defineProperty(f2, 'name', { value: opName, configurable: true });
+ // tslint:disable-next-line:no-any
+ return f2;
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Converts two real numbers to a complex number.
+ *
+ * Given a tensor `real` representing the real part of a complex number, and a
+ * tensor `imag` representing the imaginary part of a complex number, this
+ * operation returns complex numbers elementwise of the form [r0, i0, r1, i1],
+ * where r represents the real part and i represents the imag part.
+ *
+ * The input tensors real and imag must have the same shape.
+ *
+ * ```js
+ * const real = tf.tensor1d([2.25, 3.25]);
+ * const imag = tf.tensor1d([4.75, 5.75]);
+ * const complex = tf.complex(real, imag);
+ *
+ * complex.print();
+ * ```
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ function complex_(real, imag) {
+ var $real = convertToTensor(real, 'real', 'complex');
+ var $imag = convertToTensor(imag, 'imag', 'complex');
+ assertShapesMatch($real.shape, $imag.shape, "real and imag shapes, " + $real.shape + " and " + $imag.shape + ", " +
+ "must match in call to tf.complex().");
+ var inputs = { real: $real, imag: $imag };
+ return ENGINE.runKernel(Complex, inputs);
+ }
+ var complex = op({ complex_: complex_ });
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /** This is shared code across all tensor creation methods. */
+ function makeTensor(values, shape, inferredShape, dtype) {
+ if (dtype == null) {
+ dtype = inferDtype(values);
+ }
+ if (dtype === 'complex64') {
+ throw new Error("Cannot construct a complex64 tensor directly. " +
+ "Please use tf.complex(real, imag).");
+ }
+ if (!isTypedArray(values) && !Array.isArray(values) &&
+ typeof values !== 'number' && typeof values !== 'boolean' &&
+ typeof values !== 'string') {
+ throw new Error('values passed to tensor(values) must be a number/boolean/string or ' +
+ 'an array of numbers/booleans/strings, or a TypedArray');
+ }
+ if (shape != null) {
+ assertNonNegativeIntegerDimensions(shape);
+ var providedSize_1 = sizeFromShape(shape);
+ var inferredSize_1 = sizeFromShape(inferredShape);
+ assert(providedSize_1 === inferredSize_1, function () {
+ return "Based on the provided shape, [" + shape + "], the tensor should have " +
+ (providedSize_1 + " values but has " + inferredSize_1);
+ });
+ for (var i = 0; i < inferredShape.length; ++i) {
+ var inferred = inferredShape[i];
+ var flatDimsDontMatch = i === inferredShape.length - 1 ?
+ inferred !== sizeFromShape(shape.slice(i)) :
+ true;
+ assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, function () { return "Error creating a new Tensor. Inferred shape " +
+ ("(" + inferredShape + ") does not match the provided ") +
+ ("shape (" + shape + "). "); });
+ }
+ }
+ if (!isTypedArray(values) && !Array.isArray(values)) {
+ values = [values];
+ }
+ shape = shape || inferredShape;
+ values = dtype !== 'string' ?
+ toTypedArray(values, dtype) :
+ flatten(values, [], true);
+ return ENGINE.makeTensor(values, shape, dtype);
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Creates a `tf.Tensor` with the provided values, shape and dtype.
+ *
+ * ```js
+ * // Pass an array of values to create a vector.
+ * tf.tensor([1, 2, 3, 4]).print();
+ * ```
+ *
+ * ```js
+ * // Pass a nested array of values to make a matrix or a higher
+ * // dimensional tensor.
+ * tf.tensor([[1, 2], [3, 4]]).print();
+ * ```
+ *
+ * ```js
+ * // Pass a flat array and specify a shape yourself.
+ * tf.tensor([1, 2, 3, 4], [2, 2]).print();
+ * ```
+ *
+ * @param values The values of the tensor. Can be nested array of numbers,
+ * or a flat array, or a `TypedArray`. If the values are strings,
+ * they will be encoded as utf-8 and kept as `Uint8Array[]`.
+ * @param shape The shape of the tensor. Optional. If not provided,
+ * it is inferred from `values`.
+ * @param dtype The data type.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ function tensor(values, shape, dtype) {
+ var inferredShape = inferShape(values, dtype);
+ return makeTensor(values, shape, inferredShape, dtype);
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /* Type definitions for exporting and importing of models. */
+ /**
+ * A map from Tensor dtype to number of bytes per element of the Tensor.
+ */
+ var DTYPE_VALUE_SIZE_MAP = {
+ 'float32': 4,
+ 'float16': 2,
+ 'int32': 4,
+ 'uint16': 2,
+ 'uint8': 1,
+ 'bool': 1,
+ 'complex64': 8
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /** Number of bytes reserved for the length of the string. (32bit integer). */
+ var NUM_BYTES_STRING_LENGTH = 4;
+ /**
+ * Encode a map from names to weight values as an ArrayBuffer, along with an
+ * `Array` of `WeightsManifestEntry` as specification of the encoded weights.
+ *
+ * This function does not perform sharding.
+ *
+ * This function is the reverse of `decodeWeights`.
+ *
+ * @param tensors A map ("dict") from names to tensors.
+ * @param group Group to which the weights belong (optional).
+ * @returns A `Promise` of
+ * - A flat `ArrayBuffer` with all the binary values of the `Tensor`s
+ * concatenated.
+ * - An `Array` of `WeightManifestEntry`s, carrying information including
+ * tensor names, `dtype`s and shapes.
+ * @throws Error: on unsupported tensor `dtype`.
+ */
+ function encodeWeights(tensors, group) {
+ return __awaiter(this, void 0, void 0, function () {
+ var specs, dataPromises, names, _loop_1, i, tensorValues;
+ var _this = this;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ specs = [];
+ dataPromises = [];
+ names = Array.isArray(tensors) ?
+ tensors.map(function (tensor) { return tensor.name; }) :
+ Object.keys(tensors);
+ _loop_1 = function (i) {
+ var name_1 = names[i];
+ var t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name_1];
+ if (t.dtype !== 'float32' && t.dtype !== 'int32' && t.dtype !== 'bool' &&
+ t.dtype !== 'string' && t.dtype !== 'complex64') {
+ throw new Error("Unsupported dtype in weight '" + name_1 + "': " + t.dtype);
+ }
+ var spec = { name: name_1, shape: t.shape, dtype: t.dtype };
+ if (t.dtype === 'string') {
+ var utf8bytes = new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () {
+ var vals, totalNumBytes, bytes, offset, i_1, val, bytesOfLength;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0: return [4 /*yield*/, t.bytes()];
+ case 1:
+ vals = _a.sent();
+ totalNumBytes = vals.reduce(function (p, c) { return p + c.length; }, 0) +
+ NUM_BYTES_STRING_LENGTH * vals.length;
+ bytes = new Uint8Array(totalNumBytes);
+ offset = 0;
+ for (i_1 = 0; i_1 < vals.length; i_1++) {
+ val = vals[i_1];
+ bytesOfLength = new Uint8Array(new Uint32Array([val.length]).buffer);
+ bytes.set(bytesOfLength, offset);
+ offset += NUM_BYTES_STRING_LENGTH;
+ bytes.set(val, offset);
+ offset += val.length;
+ }
+ resolve(bytes);
+ return [2 /*return*/];
+ }
+ });
+ }); });
+ dataPromises.push(utf8bytes);
+ }
+ else {
+ dataPromises.push(t.data());
+ }
+ if (group != null) {
+ spec.group = group;
+ }
+ specs.push(spec);
+ };
+ for (i = 0; i < names.length; ++i) {
+ _loop_1(i);
+ }
+ return [4 /*yield*/, Promise.all(dataPromises)];
+ case 1:
+ tensorValues = _a.sent();
+ return [2 /*return*/, { data: concatenateTypedArrays(tensorValues), specs: specs }];
+ }
+ });
+ });
+ }
+ /**
+ * Decode flat ArrayBuffer as weights.
+ *
+ * This function does not handle sharding.
+ *
+ * This function is the reverse of `encodeWeights`.
+ *
+ * @param buffer A flat ArrayBuffer carrying the binary values of the tensors
+ * concatenated in the order specified in `specs`.
+ * @param specs Specifications of the names, dtypes and shapes of the tensors
+ * whose value are encoded by `buffer`.
+ * @return A map from tensor name to tensor value, with the names corresponding
+ * to names in `specs`.
+ * @throws Error, if any of the tensors has unsupported dtype.
+ */
+ function decodeWeights(buffer, specs) {
+ // TODO(adarob, cais): Support quantization.
+ var out = {};
+ var float16Decode;
+ var offset = 0;
+ for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) {
+ var spec = specs_1[_i];
+ var name_2 = spec.name;
+ var dtype = spec.dtype;
+ var shape = spec.shape;
+ var size = sizeFromShape(shape);
+ var values = void 0;
+ if ('quantization' in spec) {
+ var quantization = spec.quantization;
+ if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {
+ if (!('min' in quantization && 'scale' in quantization)) {
+ throw new Error("Weight " + spec.name + " with quantization " + quantization.dtype + " " +
+ "doesn't have corresponding metadata min and scale.");
+ }
+ }
+ else if (quantization.dtype === 'float16') {
+ if (dtype !== 'float32') {
+ throw new Error("Weight " + spec.name + " is quantized with " + quantization.dtype + " " +
+ ("which only supports weights of type float32 not " + dtype + "."));
+ }
+ }
+ else {
+ throw new Error("Weight " + spec.name + " has unknown " +
+ ("quantization dtype " + quantization.dtype + ". ") +
+ "Supported quantization dtypes are: " +
+ "'uint8', 'uint16', and 'float16'.");
+ }
+ var quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];
+ var byteBuffer = buffer.slice(offset, offset + size * quantizationSizeFactor);
+ var quantizedArray = (quantization.dtype === 'uint8') ?
+ new Uint8Array(byteBuffer) :
+ new Uint16Array(byteBuffer);
+ if (dtype === 'float32') {
+ if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {
+ values = new Float32Array(quantizedArray.length);
+ for (var i = 0; i < quantizedArray.length; i++) {
+ var v = quantizedArray[i];
+ values[i] = v * quantization.scale + quantization.min;
+ }
+ }
+ else if (quantization.dtype === 'float16') {
+ if (float16Decode === undefined) {
+ float16Decode = getFloat16Decoder();
+ }
+ values = float16Decode(quantizedArray);
+ }
+ else {
+ throw new Error("Unsupported quantization type " + quantization.dtype + " " +
+ "for weight type float32.");
+ }
+ }
+ else if (dtype === 'int32') {
+ if (quantization.dtype !== 'uint8' && quantization.dtype !== 'uint16') {
+ throw new Error("Unsupported quantization type " + quantization.dtype + " " +
+ "for weight type int32.");
+ }
+ values = new Int32Array(quantizedArray.length);
+ for (var i = 0; i < quantizedArray.length; i++) {
+ var v = quantizedArray[i];
+ values[i] = Math.round(v * quantization.scale + quantization.min);
+ }
+ }
+ else {
+ throw new Error("Unsupported dtype in weight '" + name_2 + "': " + dtype);
+ }
+ offset += size * quantizationSizeFactor;
+ }
+ else if (dtype === 'string') {
+ var size_1 = sizeFromShape(spec.shape);
+ values = [];
+ for (var i = 0; i < size_1; i++) {
+ var byteLength = new Uint32Array(buffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];
+ offset += NUM_BYTES_STRING_LENGTH;
+ var bytes = new Uint8Array(buffer.slice(offset, offset + byteLength));
+ values.push(bytes);
+ offset += byteLength;
+ }
+ }
+ else {
+ var dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];
+ var byteBuffer = buffer.slice(offset, offset + size * dtypeFactor);
+ if (dtype === 'float32') {
+ values = new Float32Array(byteBuffer);
+ }
+ else if (dtype === 'int32') {
+ values = new Int32Array(byteBuffer);
+ }
+ else if (dtype === 'bool') {
+ values = new Uint8Array(byteBuffer);
+ }
+ else if (dtype === 'complex64') {
+ values = new Float32Array(byteBuffer);
+ var real = new Float32Array(values.length / 2);
+ var image = new Float32Array(values.length / 2);
+ for (var i = 0; i < real.length; i++) {
+ real[i] = values[i * 2];
+ image[i] = values[i * 2 + 1];
+ }
+ var realTensor = tensor(real, shape, 'float32');
+ var imageTensor = tensor(image, shape, 'float32');
+ out[name_2] = complex(realTensor, imageTensor);
+ realTensor.dispose();
+ imageTensor.dispose();
+ }
+ else {
+ throw new Error("Unsupported dtype in weight '" + name_2 + "': " + dtype);
+ }
+ offset += size * dtypeFactor;
+ }
+ if (dtype !== 'complex64') {
+ out[name_2] = tensor(values, shape, dtype);
+ }
+ }
+ return out;
+ }
+ /**
+ * Concatenate TypedArrays into an ArrayBuffer.
+ */
+ function concatenateTypedArrays(xs) {
+ // TODO(adarob, cais): Support quantization.
+ if (xs === null) {
+ throw new Error("Invalid input value: " + JSON.stringify(xs));
+ }
+ var totalByteLength = 0;
+ // `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'
+ // can have a different byte length from that of the `TypedArray` itself,
+ // for example, when the `TypedArray` is created from an offset in an
+ // `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match
+ // the `TypedArray` in byte length. If an element of `xs` does not show
+ // this property, a new `TypedArray` that satisfy this property will be
+ // constructed and pushed into `normalizedXs`.
+ var normalizedXs = [];
+ xs.forEach(function (x) {
+ totalByteLength += x.byteLength;
+ // tslint:disable:no-any
+ normalizedXs.push(x.byteLength === x.buffer.byteLength ? x :
+ new x.constructor(x));
+ if (!(x instanceof Float32Array || x instanceof Int32Array ||
+ x instanceof Uint8Array)) {
+ throw new Error("Unsupported TypedArray subtype: " + x.constructor.name);
+ }
+ // tslint:enable:no-any
+ });
+ var y = new Uint8Array(totalByteLength);
+ var offset = 0;
+ normalizedXs.forEach(function (x) {
+ y.set(new Uint8Array(x.buffer), offset);
+ offset += x.byteLength;
+ });
+ return y.buffer;
+ }
+ // Use Buffer on Node.js instead of Blob/atob/btoa
+ var useNodeBuffer = typeof Buffer !== 'undefined' &&
+ (typeof Blob === 'undefined' || typeof atob === 'undefined' ||
+ typeof btoa === 'undefined');
+ /**
+ * Calculate the byte length of a JavaScript string.
+ *
+ * Note that a JavaScript string can contain wide characters, therefore the
+ * length of the string is not necessarily equal to the byte length.
+ *
+ * @param str Input string.
+ * @returns Byte length.
+ */
+ function stringByteLength(str) {
+ if (useNodeBuffer) {
+ return Buffer.byteLength(str);
+ }
+ return new Blob([str]).size;
+ }
+ /**
+ * Encode an ArrayBuffer as a base64 encoded string.
+ *
+ * @param buffer `ArrayBuffer` to be converted.
+ * @returns A string that base64-encodes `buffer`.
+ */
+ function arrayBufferToBase64String(buffer) {
+ if (useNodeBuffer) {
+ return Buffer.from(buffer).toString('base64');
+ }
+ var buf = new Uint8Array(buffer);
+ var s = '';
+ for (var i = 0, l = buf.length; i < l; i++) {
+ s += String.fromCharCode(buf[i]);
+ }
+ return btoa(s);
+ }
+ /**
+ * Decode a base64 string as an ArrayBuffer.
+ *
+ * @param str Base64 string.
+ * @returns Decoded `ArrayBuffer`.
+ */
+ function base64StringToArrayBuffer(str) {
+ if (useNodeBuffer) {
+ var buf = Buffer.from(str, 'base64');
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ }
+ var s = atob(str);
+ var buffer = new Uint8Array(s.length);
+ for (var i = 0; i < s.length; ++i) {
+ buffer.set([s.charCodeAt(i)], i);
+ }
+ return buffer.buffer;
+ }
+ /**
+ * Concatenate a number of ArrayBuffers into one.
+ *
+ * @param buffers A number of array buffers to concatenate.
+ * @returns Result of concatenating `buffers` in order.
+ */
+ function concatenateArrayBuffers(buffers) {
+ if (buffers.length === 1) {
+ return buffers[0];
+ }
+ var totalByteLength = 0;
+ buffers.forEach(function (buffer) {
+ totalByteLength += buffer.byteLength;
+ });
+ var temp = new Uint8Array(totalByteLength);
+ var offset = 0;
+ buffers.forEach(function (buffer) {
+ temp.set(new Uint8Array(buffer), offset);
+ offset += buffer.byteLength;
+ });
+ return temp.buffer;
+ }
+ /**
+ * Get the basename of a path.
+ *
+ * Behaves in a way analogous to Linux's basename command.
+ *
+ * @param path
+ */
+ function basename(path) {
+ var SEPARATOR = '/';
+ path = path.trim();
+ while (path.endsWith(SEPARATOR)) {
+ path = path.slice(0, path.length - 1);
+ }
+ var items = path.split(SEPARATOR);
+ return items[items.length - 1];
+ }
+ /**
+ * Populate ModelArtifactsInfo fields for a model with JSON topology.
+ * @param modelArtifacts
+ * @returns A ModelArtifactsInfo object.
+ */
+ function getModelArtifactsInfoForJSON(modelArtifacts) {
+ if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
+ throw new Error('Expected JSON model topology, received ArrayBuffer.');
+ }
+ return {
+ dateSaved: new Date(),
+ modelTopologyType: 'JSON',
+ modelTopologyBytes: modelArtifacts.modelTopology == null ?
+ 0 :
+ stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),
+ weightSpecsBytes: modelArtifacts.weightSpecs == null ?
+ 0 :
+ stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),
+ weightDataBytes: modelArtifacts.weightData == null ?
+ 0 :
+ modelArtifacts.weightData.byteLength,
+ };
+ }
+ /**
+ * Computes mantisa table for casting Float16 to Float32
+ * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
+ *
+ * @returns Uint32Array, 2048 mantissa lookup values.
+ */
+ function computeFloat16MantisaTable() {
+ var convertMantissa = function (i) {
+ var m = i << 13;
+ var e = 0;
+ while ((m & 0x00800000) === 0) {
+ e -= 0x00800000;
+ m <<= 1;
+ }
+ m &= ~0x00800000;
+ e += 0x38800000;
+ return m | e;
+ };
+ var mantisaTable = new Uint32Array(2048);
+ mantisaTable[0] = 0;
+ for (var i = 1; i < 1024; i++) {
+ mantisaTable[i] = convertMantissa(i);
+ }
+ for (var i = 1024; i < 2048; i++) {
+ mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);
+ }
+ return mantisaTable;
+ }
+ /**
+ * Computes exponent table for casting Float16 to Float32
+ * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
+ *
+ * @returns Uint32Array, 64 exponent lookup values.
+ */
+ function computeFloat16ExponentTable() {
+ var exponentTable = new Uint32Array(64);
+ exponentTable[0] = 0;
+ exponentTable[31] = 0x47800000;
+ exponentTable[32] = 0x80000000;
+ exponentTable[63] = 0xc7800000;
+ for (var i = 1; i < 31; i++) {
+ exponentTable[i] = i << 23;
+ }
+ for (var i = 33; i < 63; i++) {
+ exponentTable[i] = 0x80000000 + ((i - 32) << 23);
+ }
+ return exponentTable;
+ }
+ /**
+ * Computes offset table for casting Float16 to Float32
+ * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
+ *
+ * @returns Uint32Array, 6d offset values.
+ */
+ function computeFloat16OffsetTable() {
+ var offsetTable = new Uint32Array(64);
+ for (var i = 0; i < 64; i++) {
+ offsetTable[i] = 1024;
+ }
+ offsetTable[0] = offsetTable[32] = 0;
+ return offsetTable;
+ }
+ /**
+ * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values
+ * to a Float32Array.
+ *
+ * @returns Function (buffer: Uint16Array) => Float32Array which decodes
+ * the Uint16Array of Float16 bytes to a Float32Array.
+ */
+ function getFloat16Decoder() {
+ // Algorithm is based off of
+ // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
+ // Cache lookup tables
+ var mantisaTable = computeFloat16MantisaTable();
+ var exponentTable = computeFloat16ExponentTable();
+ var offsetTable = computeFloat16OffsetTable();
+ return function (quantizedArray) {
+ var buffer = new ArrayBuffer(4 * quantizedArray.length);
+ var bufferUint32View = new Uint32Array(buffer);
+ for (var index = 0; index < quantizedArray.length; index++) {
+ var float16Bits = quantizedArray[index];
+ var float32Bits = mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +
+ exponentTable[float16Bits >> 10];
+ bufferUint32View[index] = float32Bits;
+ }
+ return new Float32Array(buffer);
+ };
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var IORouterRegistry = /** @class */ (function () {
+ function IORouterRegistry() {
+ this.saveRouters = [];
+ this.loadRouters = [];
+ }
+ IORouterRegistry.getInstance = function () {
+ if (IORouterRegistry.instance == null) {
+ IORouterRegistry.instance = new IORouterRegistry();
+ }
+ return IORouterRegistry.instance;
+ };
+ /**
+ * Register a save-handler router.
+ *
+ * @param saveRouter A function that maps a URL-like string onto an instance
+ * of `IOHandler` with the `save` method defined or `null`.
+ */
+ IORouterRegistry.registerSaveRouter = function (saveRouter) {
+ IORouterRegistry.getInstance().saveRouters.push(saveRouter);
+ };
+ /**
+ * Register a load-handler router.
+ *
+ * @param loadRouter A function that maps a URL-like string onto an instance
+ * of `IOHandler` with the `load` method defined or `null`.
+ */
+ IORouterRegistry.registerLoadRouter = function (loadRouter) {
+ IORouterRegistry.getInstance().loadRouters.push(loadRouter);
+ };
+ /**
+ * Look up IOHandler for saving, given a URL-like string.
+ *
+ * @param url
+ * @returns If only one match is found, an instance of IOHandler with the
+ * `save` method defined. If no match is found, `null`.
+ * @throws Error, if more than one match is found.
+ */
+ IORouterRegistry.getSaveHandlers = function (url) {
+ return IORouterRegistry.getHandlers(url, 'save');
+ };
+ /**
+ * Look up IOHandler for loading, given a URL-like string.
+ *
+ * @param url
+ * @param loadOptions Optional, custom load options.
+ * @returns All valid handlers for `url`, given the currently registered
+ * handler routers.
+ */
+ IORouterRegistry.getLoadHandlers = function (url, loadOptions) {
+ return IORouterRegistry.getHandlers(url, 'load', loadOptions);
+ };
+ IORouterRegistry.getHandlers = function (url, handlerType, loadOptions) {
+ var validHandlers = [];
+ var routers = handlerType === 'load' ?
+ IORouterRegistry.getInstance().loadRouters :
+ IORouterRegistry.getInstance().saveRouters;
+ routers.forEach(function (router) {
+ var handler = router(url, loadOptions);
+ if (handler !== null) {
+ validHandlers.push(handler);
+ }
+ });
+ return validHandlers;
+ };
+ return IORouterRegistry;
+ }());
+ var registerSaveRouter = function (loudRouter) {
+ return IORouterRegistry.registerSaveRouter(loudRouter);
+ };
+ var registerLoadRouter = function (loudRouter) {
+ return IORouterRegistry.registerLoadRouter(loudRouter);
+ };
+ var getSaveHandlers = function (url) {
+ return IORouterRegistry.getSaveHandlers(url);
+ };
+ var getLoadHandlers = function (url, loadOptions) {
+ return IORouterRegistry.getLoadHandlers(url, loadOptions);
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var DATABASE_NAME = 'tensorflowjs';
+ var DATABASE_VERSION = 1;
+ // Model data and ModelArtifactsInfo (metadata) are stored in two separate
+ // stores for efficient access of the list of stored models and their metadata.
+ // 1. The object store for model data: topology, weights and weight manifests.
+ var MODEL_STORE_NAME = 'models_store';
+ // 2. The object store for ModelArtifactsInfo, including meta-information such
+ // as the type of topology (JSON vs binary), byte size of the topology, byte
+ // size of the weights, etc.
+ var INFO_STORE_NAME = 'model_info_store';
+ function getIndexedDBFactory() {
+ if (!env().getBool('IS_BROWSER')) {
+ // TODO(cais): Add more info about what IOHandler subtypes are available.
+ // Maybe point to a doc page on the web and/or automatically determine
+ // the available IOHandlers and print them in the error message.
+ throw new Error('Failed to obtain IndexedDB factory because the current environment' +
+ 'is not a web browser.');
+ }
+ // tslint:disable-next-line:no-any
+ var theWindow = typeof window === 'undefined' ? self : window;
+ var factory = theWindow.indexedDB || theWindow.mozIndexedDB ||
+ theWindow.webkitIndexedDB || theWindow.msIndexedDB ||
+ theWindow.shimIndexedDB;
+ if (factory == null) {
+ throw new Error('The current browser does not appear to support IndexedDB.');
+ }
+ return factory;
+ }
+ function setUpDatabase(openRequest) {
+ var db = openRequest.result;
+ db.createObjectStore(MODEL_STORE_NAME, { keyPath: 'modelPath' });
+ db.createObjectStore(INFO_STORE_NAME, { keyPath: 'modelPath' });
+ }
+ /**
+ * IOHandler subclass: Browser IndexedDB.
+ *
+ * See the doc string of `browserIndexedDB` for more details.
+ */
+ var BrowserIndexedDB = /** @class */ (function () {
+ function BrowserIndexedDB(modelPath) {
+ this.indexedDB = getIndexedDBFactory();
+ if (modelPath == null || !modelPath) {
+ throw new Error('For IndexedDB, modelPath must not be null, undefined or empty.');
+ }
+ this.modelPath = modelPath;
+ }
+ BrowserIndexedDB.prototype.save = function (modelArtifacts) {
+ return __awaiter(this, void 0, void 0, function () {
+ return __generator(this, function (_a) {
+ // TODO(cais): Support saving GraphDef models.
+ if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
+ throw new Error('BrowserLocalStorage.save() does not support saving model topology ' +
+ 'in binary formats yet.');
+ }
+ return [2 /*return*/, this.databaseAction(this.modelPath, modelArtifacts)];
+ });
+ });
+ };
+ BrowserIndexedDB.prototype.load = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ return __generator(this, function (_a) {
+ return [2 /*return*/, this.databaseAction(this.modelPath)];
+ });
+ });
+ };
+ /**
+ * Perform database action to put model artifacts into or read model artifacts
+ * from IndexedDB object store.
+ *
+ * Whether the action is put or get depends on whether `modelArtifacts` is
+ * specified. If it is specified, the action will be put; otherwise the action
+ * will be get.
+ *
+ * @param modelPath A unique string path for the model.
+ * @param modelArtifacts If specified, it will be the model artifacts to be
+ * stored in IndexedDB.
+ * @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`
+ * of `ModelArtifacts`, if the action is get.
+ */
+ BrowserIndexedDB.prototype.databaseAction = function (modelPath, modelArtifacts) {
+ var _this = this;
+ return new Promise(function (resolve, reject) {
+ var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
+ openRequest.onupgradeneeded = function () { return setUpDatabase(openRequest); };
+ openRequest.onsuccess = function () {
+ var db = openRequest.result;
+ if (modelArtifacts == null) {
+ // Read model out from object store.
+ var modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');
+ var modelStore = modelTx.objectStore(MODEL_STORE_NAME);
+ var getRequest_1 = modelStore.get(_this.modelPath);
+ getRequest_1.onsuccess = function () {
+ if (getRequest_1.result == null) {
+ db.close();
+ return reject(new Error("Cannot find model with path '" + _this.modelPath + "' " +
+ "in IndexedDB."));
+ }
+ else {
+ resolve(getRequest_1.result.modelArtifacts);
+ }
+ };
+ getRequest_1.onerror = function (error) {
+ db.close();
+ return reject(getRequest_1.error);
+ };
+ modelTx.oncomplete = function () { return db.close(); };
+ }
+ else {
+ // Put model into object store.
+ var modelArtifactsInfo_1 = getModelArtifactsInfoForJSON(modelArtifacts);
+ // First, put ModelArtifactsInfo into info store.
+ var infoTx_1 = db.transaction(INFO_STORE_NAME, 'readwrite');
+ var infoStore_1 = infoTx_1.objectStore(INFO_STORE_NAME);
+ var putInfoRequest_1 = infoStore_1.put({ modelPath: _this.modelPath, modelArtifactsInfo: modelArtifactsInfo_1 });
+ var modelTx_1;
+ putInfoRequest_1.onsuccess = function () {
+ // Second, put model data into model store.
+ modelTx_1 = db.transaction(MODEL_STORE_NAME, 'readwrite');
+ var modelStore = modelTx_1.objectStore(MODEL_STORE_NAME);
+ var putModelRequest = modelStore.put({
+ modelPath: _this.modelPath,
+ modelArtifacts: modelArtifacts,
+ modelArtifactsInfo: modelArtifactsInfo_1
+ });
+ putModelRequest.onsuccess = function () { return resolve({ modelArtifactsInfo: modelArtifactsInfo_1 }); };
+ putModelRequest.onerror = function (error) {
+ // If the put-model request fails, roll back the info entry as
+ // well.
+ infoStore_1 = infoTx_1.objectStore(INFO_STORE_NAME);
+ var deleteInfoRequest = infoStore_1.delete(_this.modelPath);
+ deleteInfoRequest.onsuccess = function () {
+ db.close();
+ return reject(putModelRequest.error);
+ };
+ deleteInfoRequest.onerror = function (error) {
+ db.close();
+ return reject(putModelRequest.error);
+ };
+ };
+ };
+ putInfoRequest_1.onerror = function (error) {
+ db.close();
+ return reject(putInfoRequest_1.error);
+ };
+ infoTx_1.oncomplete = function () {
+ if (modelTx_1 == null) {
+ db.close();
+ }
+ else {
+ modelTx_1.oncomplete = function () { return db.close(); };
+ }
+ };
+ }
+ };
+ openRequest.onerror = function (error) { return reject(openRequest.error); };
+ });
+ };
+ BrowserIndexedDB.URL_SCHEME = 'indexeddb://';
+ return BrowserIndexedDB;
+ }());
+ var indexedDBRouter = function (url) {
+ if (!env().getBool('IS_BROWSER')) {
+ return null;
+ }
+ else {
+ if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {
+ return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));
+ }
+ else {
+ return null;
+ }
+ }
+ };
+ IORouterRegistry.registerSaveRouter(indexedDBRouter);
+ IORouterRegistry.registerLoadRouter(indexedDBRouter);
+ /**
+ * Creates a browser IndexedDB IOHandler for saving and loading models.
+ *
+ * ```js
+ * const model = tf.sequential();
+ * model.add(
+ * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));
+ *
+ * const saveResult = await model.save('indexeddb://MyModel'));
+ * console.log(saveResult);
+ * ```
+ *
+ * @param modelPath A unique identifier for the model to be saved. Must be a
+ * non-empty string.
+ * @returns An instance of `BrowserIndexedDB` (sublcass of `IOHandler`),
+ * which can be used with, e.g., `tf.Model.save`.
+ */
+ function browserIndexedDB(modelPath) {
+ return new BrowserIndexedDB(modelPath);
+ }
+ function maybeStripScheme(key) {
+ return key.startsWith(BrowserIndexedDB.URL_SCHEME) ?
+ key.slice(BrowserIndexedDB.URL_SCHEME.length) :
+ key;
+ }
+ var BrowserIndexedDBManager = /** @class */ (function () {
+ function BrowserIndexedDBManager() {
+ this.indexedDB = getIndexedDBFactory();
+ }
+ BrowserIndexedDBManager.prototype.listModels = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var _this = this;
+ return __generator(this, function (_a) {
+ return [2 /*return*/, new Promise(function (resolve, reject) {
+ var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
+ openRequest.onupgradeneeded = function () { return setUpDatabase(openRequest); };
+ openRequest.onsuccess = function () {
+ var db = openRequest.result;
+ var tx = db.transaction(INFO_STORE_NAME, 'readonly');
+ var store = tx.objectStore(INFO_STORE_NAME);
+ // tslint:disable:max-line-length
+ // Need to cast `store` as `any` here because TypeScript's DOM
+ // library does not have the `getAll()` method even though the
+ // method is supported in the latest version of most mainstream
+ // browsers:
+ // https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll
+ // tslint:enable:max-line-length
+ // tslint:disable-next-line:no-any
+ var getAllInfoRequest = store.getAll();
+ getAllInfoRequest.onsuccess = function () {
+ var out = {};
+ for (var _i = 0, _a = getAllInfoRequest.result; _i < _a.length; _i++) {
+ var item = _a[_i];
+ out[item.modelPath] = item.modelArtifactsInfo;
+ }
+ resolve(out);
+ };
+ getAllInfoRequest.onerror = function (error) {
+ db.close();
+ return reject(getAllInfoRequest.error);
+ };
+ tx.oncomplete = function () { return db.close(); };
+ };
+ openRequest.onerror = function (error) { return reject(openRequest.error); };
+ })];
+ });
+ });
+ };
+ BrowserIndexedDBManager.prototype.removeModel = function (path) {
+ return __awaiter(this, void 0, void 0, function () {
+ var _this = this;
+ return __generator(this, function (_a) {
+ path = maybeStripScheme(path);
+ return [2 /*return*/, new Promise(function (resolve, reject) {
+ var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
+ openRequest.onupgradeneeded = function () { return setUpDatabase(openRequest); };
+ openRequest.onsuccess = function () {
+ var db = openRequest.result;
+ var infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');
+ var infoStore = infoTx.objectStore(INFO_STORE_NAME);
+ var getInfoRequest = infoStore.get(path);
+ var modelTx;
+ getInfoRequest.onsuccess = function () {
+ if (getInfoRequest.result == null) {
+ db.close();
+ return reject(new Error("Cannot find model with path '" + path + "' " +
+ "in IndexedDB."));
+ }
+ else {
+ // First, delete the entry in the info store.
+ var deleteInfoRequest = infoStore.delete(path);
+ var deleteModelData_1 = function () {
+ // Second, delete the entry in the model store.
+ modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');
+ var modelStore = modelTx.objectStore(MODEL_STORE_NAME);
+ var deleteModelRequest = modelStore.delete(path);
+ deleteModelRequest.onsuccess = function () {
+ return resolve(getInfoRequest.result.modelArtifactsInfo);
+ };
+ deleteModelRequest.onerror = function (error) {
+ return reject(getInfoRequest.error);
+ };
+ };
+ // Proceed with deleting model data regardless of whether deletion
+ // of info data succeeds or not.
+ deleteInfoRequest.onsuccess = deleteModelData_1;
+ deleteInfoRequest.onerror = function (error) {
+ deleteModelData_1();
+ db.close();
+ return reject(getInfoRequest.error);
+ };
+ }
+ };
+ getInfoRequest.onerror = function (error) {
+ db.close();
+ return reject(getInfoRequest.error);
+ };
+ infoTx.oncomplete = function () {
+ if (modelTx == null) {
+ db.close();
+ }
+ else {
+ modelTx.oncomplete = function () { return db.close(); };
+ }
+ };
+ };
+ openRequest.onerror = function (error) { return reject(openRequest.error); };
+ })];
+ });
+ });
+ };
+ return BrowserIndexedDBManager;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var PATH_SEPARATOR = '/';
+ var PATH_PREFIX = 'tensorflowjs_models';
+ var INFO_SUFFIX = 'info';
+ var MODEL_TOPOLOGY_SUFFIX = 'model_topology';
+ var WEIGHT_SPECS_SUFFIX = 'weight_specs';
+ var WEIGHT_DATA_SUFFIX = 'weight_data';
+ var MODEL_METADATA_SUFFIX = 'model_metadata';
+ function getModelKeys(path) {
+ return {
+ info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),
+ topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),
+ weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),
+ weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),
+ modelMetadata: [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)
+ };
+ }
+ /**
+ * Get model path from a local-storage key.
+ *
+ * E.g., 'tensorflowjs_models/my/model/1/info' --> 'my/model/1'
+ *
+ * @param key
+ */
+ function getModelPathFromKey(key) {
+ var items = key.split(PATH_SEPARATOR);
+ if (items.length < 3) {
+ throw new Error("Invalid key format: " + key);
+ }
+ return items.slice(1, items.length - 1).join(PATH_SEPARATOR);
+ }
+ function maybeStripScheme$1(key) {
+ return key.startsWith(BrowserLocalStorage.URL_SCHEME) ?
+ key.slice(BrowserLocalStorage.URL_SCHEME.length) :
+ key;
+ }
+ /**
+ * IOHandler subclass: Browser Local Storage.
+ *
+ * See the doc string to `browserLocalStorage` for more details.
+ */
+ var BrowserLocalStorage = /** @class */ (function () {
+ function BrowserLocalStorage(modelPath) {
+ if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||
+ typeof window.localStorage === 'undefined') {
+ // TODO(cais): Add more info about what IOHandler subtypes are
+ // available.
+ // Maybe point to a doc page on the web and/or automatically determine
+ // the available IOHandlers and print them in the error message.
+ throw new Error('The current environment does not support local storage.');
+ }
+ this.LS = window.localStorage;
+ if (modelPath == null || !modelPath) {
+ throw new Error('For local storage, modelPath must not be null, undefined or empty.');
+ }
+ this.modelPath = modelPath;
+ this.keys = getModelKeys(this.modelPath);
+ }
+ /**
+ * Save model artifacts to browser local storage.
+ *
+ * See the documentation to `browserLocalStorage` for details on the saved
+ * artifacts.
+ *
+ * @param modelArtifacts The model artifacts to be stored.
+ * @returns An instance of SaveResult.
+ */
+ BrowserLocalStorage.prototype.save = function (modelArtifacts) {
+ return __awaiter(this, void 0, void 0, function () {
+ var topology, weightSpecs, modelArtifactsInfo, result;
+ return __generator(this, function (_a) {
+ if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
+ throw new Error('BrowserLocalStorage.save() does not support saving model topology ' +
+ 'in binary formats yet.');
+ }
+ else {
+ topology = JSON.stringify(modelArtifacts.modelTopology);
+ weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);
+ modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts);
+ try {
+ this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));
+ this.LS.setItem(this.keys.topology, topology);
+ this.LS.setItem(this.keys.weightSpecs, weightSpecs);
+ this.LS.setItem(this.keys.weightData, arrayBufferToBase64String(modelArtifacts.weightData));
+ result = {
+ format: modelArtifacts.format,
+ generatedBy: modelArtifacts.generatedBy,
+ convertedBy: modelArtifacts.convertedBy
+ };
+ if (modelArtifacts.signature != null) {
+ result.signature = modelArtifacts.signature;
+ }
+ if (modelArtifacts.userDefinedMetadata != null) {
+ result.userDefinedMetadata = modelArtifacts.userDefinedMetadata;
+ }
+ if (modelArtifacts.modelInitializer != null) {
+ result.modelInitializer = modelArtifacts.modelInitializer;
+ }
+ this.LS.setItem(this.keys.modelMetadata, JSON.stringify(result));
+ return [2 /*return*/, { modelArtifactsInfo: modelArtifactsInfo }];
+ }
+ catch (err) {
+ // If saving failed, clean up all items saved so far.
+ this.LS.removeItem(this.keys.info);
+ this.LS.removeItem(this.keys.topology);
+ this.LS.removeItem(this.keys.weightSpecs);
+ this.LS.removeItem(this.keys.weightData);
+ this.LS.removeItem(this.keys.modelMetadata);
+ throw new Error("Failed to save model '" + this.modelPath + "' to local storage: " +
+ "size quota being exceeded is a possible cause of this failure: " +
+ ("modelTopologyBytes=" + modelArtifactsInfo.modelTopologyBytes + ", ") +
+ ("weightSpecsBytes=" + modelArtifactsInfo.weightSpecsBytes + ", ") +
+ ("weightDataBytes=" + modelArtifactsInfo.weightDataBytes + "."));
+ }
+ }
+ return [2 /*return*/];
+ });
+ });
+ };
+ /**
+ * Load a model from local storage.
+ *
+ * See the documentation to `browserLocalStorage` for details on the saved
+ * artifacts.
+ *
+ * @returns The loaded model (if loading succeeds).
+ */
+ BrowserLocalStorage.prototype.load = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var info, out, topology, weightSpecs, metadataString, metadata, weightDataBase64;
+ return __generator(this, function (_a) {
+ info = JSON.parse(this.LS.getItem(this.keys.info));
+ if (info == null) {
+ throw new Error("In local storage, there is no model with name '" + this.modelPath + "'");
+ }
+ if (info.modelTopologyType !== 'JSON') {
+ throw new Error('BrowserLocalStorage does not support loading non-JSON model ' +
+ 'topology yet.');
+ }
+ out = {};
+ topology = JSON.parse(this.LS.getItem(this.keys.topology));
+ if (topology == null) {
+ throw new Error("In local storage, the topology of model '" + this.modelPath + "' " +
+ "is missing.");
+ }
+ out.modelTopology = topology;
+ weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
+ if (weightSpecs == null) {
+ throw new Error("In local storage, the weight specs of model '" + this.modelPath + "' " +
+ "are missing.");
+ }
+ out.weightSpecs = weightSpecs;
+ metadataString = this.LS.getItem(this.keys.modelMetadata);
+ if (metadataString != null) {
+ metadata = JSON.parse(metadataString);
+ out.format = metadata['format'];
+ out.generatedBy = metadata['generatedBy'];
+ out.convertedBy = metadata['convertedBy'];
+ if (metadata['signature'] != null) {
+ out.signature = metadata['signature'];
+ }
+ if (metadata['userDefinedMetadata'] != null) {
+ out.userDefinedMetadata = metadata['userDefinedMetadata'];
+ }
+ if (metadata['modelInitializer'] != null) {
+ out.modelInitializer = metadata['modelInitializer'];
+ }
+ }
+ weightDataBase64 = this.LS.getItem(this.keys.weightData);
+ if (weightDataBase64 == null) {
+ throw new Error("In local storage, the binary weight values of model " +
+ ("'" + this.modelPath + "' are missing."));
+ }
+ out.weightData = base64StringToArrayBuffer(weightDataBase64);
+ return [2 /*return*/, out];
+ });
+ });
+ };
+ BrowserLocalStorage.URL_SCHEME = 'localstorage://';
+ return BrowserLocalStorage;
+ }());
+ var localStorageRouter = function (url) {
+ if (!env().getBool('IS_BROWSER')) {
+ return null;
+ }
+ else {
+ if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {
+ return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length));
+ }
+ else {
+ return null;
+ }
+ }
+ };
+ IORouterRegistry.registerSaveRouter(localStorageRouter);
+ IORouterRegistry.registerLoadRouter(localStorageRouter);
+ /**
+ * Factory function for local storage IOHandler.
+ *
+ * This `IOHandler` supports both `save` and `load`.
+ *
+ * For each model's saved artifacts, four items are saved to local storage.
+ * - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the
+ * model, such as date saved, type of the topology, size in bytes, etc.
+ * - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-
+ * style models, this is a stringized JSON.
+ * - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the
+ * model, can be used to decode the saved binary weight values (see
+ * item below).
+ * - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary
+ * weight values, stored as a base64-encoded string.
+ *
+ * Saving may throw an `Error` if the total size of the artifacts exceed the
+ * browser-specific quota.
+ *
+ * @param modelPath A unique identifier for the model to be saved. Must be a
+ * non-empty string.
+ * @returns An instance of `IOHandler`, which can be used with, e.g.,
+ * `tf.Model.save`.
+ */
+ function browserLocalStorage(modelPath) {
+ return new BrowserLocalStorage(modelPath);
+ }
+ var BrowserLocalStorageManager = /** @class */ (function () {
+ function BrowserLocalStorageManager() {
+ assert(env().getBool('IS_BROWSER'), function () { return 'Current environment is not a web browser'; });
+ assert(typeof window === 'undefined' ||
+ typeof window.localStorage !== 'undefined', function () { return 'Current browser does not appear to support localStorage'; });
+ this.LS = window.localStorage;
+ }
+ BrowserLocalStorageManager.prototype.listModels = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var out, prefix, suffix, i, key, modelPath;
+ return __generator(this, function (_a) {
+ out = {};
+ prefix = PATH_PREFIX + PATH_SEPARATOR;
+ suffix = PATH_SEPARATOR + INFO_SUFFIX;
+ for (i = 0; i < this.LS.length; ++i) {
+ key = this.LS.key(i);
+ if (key.startsWith(prefix) && key.endsWith(suffix)) {
+ modelPath = getModelPathFromKey(key);
+ out[modelPath] = JSON.parse(this.LS.getItem(key));
+ }
+ }
+ return [2 /*return*/, out];
+ });
+ });
+ };
+ BrowserLocalStorageManager.prototype.removeModel = function (path) {
+ return __awaiter(this, void 0, void 0, function () {
+ var keys, info;
+ return __generator(this, function (_a) {
+ path = maybeStripScheme$1(path);
+ keys = getModelKeys(path);
+ if (this.LS.getItem(keys.info) == null) {
+ throw new Error("Cannot find model at path '" + path + "'");
+ }
+ info = JSON.parse(this.LS.getItem(keys.info));
+ this.LS.removeItem(keys.info);
+ this.LS.removeItem(keys.topology);
+ this.LS.removeItem(keys.weightSpecs);
+ this.LS.removeItem(keys.weightData);
+ return [2 /*return*/, info];
+ });
+ });
+ };
+ return BrowserLocalStorageManager;
+ }());
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var URL_SCHEME_SUFFIX = '://';
+ var ModelStoreManagerRegistry = /** @class */ (function () {
+ function ModelStoreManagerRegistry() {
+ this.managers = {};
+ }
+ ModelStoreManagerRegistry.getInstance = function () {
+ if (ModelStoreManagerRegistry.instance == null) {
+ ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();
+ }
+ return ModelStoreManagerRegistry.instance;
+ };
+ /**
+ * Register a save-handler router.
+ *
+ * @param saveRouter A function that maps a URL-like string onto an instance
+ * of `IOHandler` with the `save` method defined or `null`.
+ */
+ ModelStoreManagerRegistry.registerManager = function (scheme, manager) {
+ assert(scheme != null, function () { return 'scheme must not be undefined or null.'; });
+ if (scheme.endsWith(URL_SCHEME_SUFFIX)) {
+ scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));
+ }
+ assert(scheme.length > 0, function () { return 'scheme must not be an empty string.'; });
+ var registry = ModelStoreManagerRegistry.getInstance();
+ assert(registry.managers[scheme] == null, function () { return "A model store manager is already registered for scheme '" + scheme + "'."; });
+ registry.managers[scheme] = manager;
+ };
+ ModelStoreManagerRegistry.getManager = function (scheme) {
+ var manager = this.getInstance().managers[scheme];
+ if (manager == null) {
+ throw new Error("Cannot find model manager for scheme '" + scheme + "'");
+ }
+ return manager;
+ };
+ ModelStoreManagerRegistry.getSchemes = function () {
+ return Object.keys(this.getInstance().managers);
+ };
+ return ModelStoreManagerRegistry;
+ }());
+ /**
+ * Helper method for parsing a URL string into a scheme and a path.
+ *
+ * @param url E.g., 'localstorage://my-model'
+ * @returns A dictionary with two fields: scheme and path.
+ * Scheme: e.g., 'localstorage' in the example above.
+ * Path: e.g., 'my-model' in the example above.
+ */
+ function parseURL(url) {
+ if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {
+ throw new Error("The url string provided does not contain a scheme. " +
+ "Supported schemes are: " +
+ ("" + ModelStoreManagerRegistry.getSchemes().join(',')));
+ }
+ return {
+ scheme: url.split(URL_SCHEME_SUFFIX)[0],
+ path: url.split(URL_SCHEME_SUFFIX)[1],
+ };
+ }
+ function cloneModelInternal(sourceURL, destURL, deleteSource) {
+ if (deleteSource === void 0) { deleteSource = false; }
+ return __awaiter(this, void 0, void 0, function () {
+ var loadHandlers, loadHandler, saveHandlers, saveHandler, sourceScheme, sourcePath, sameMedium, modelArtifacts, saveResult;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ assert(sourceURL !== destURL, function () { return "Old path and new path are the same: '" + sourceURL + "'"; });
+ loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);
+ assert(loadHandlers.length > 0, function () { return "Copying failed because no load handler is found for source URL " + sourceURL + "."; });
+ assert(loadHandlers.length < 2, function () { return "Copying failed because more than one (" + loadHandlers.length + ") " +
+ ("load handlers for source URL " + sourceURL + "."); });
+ loadHandler = loadHandlers[0];
+ saveHandlers = IORouterRegistry.getSaveHandlers(destURL);
+ assert(saveHandlers.length > 0, function () { return "Copying failed because no save handler is found for destination " +
+ ("URL " + destURL + "."); });
+ assert(saveHandlers.length < 2, function () { return "Copying failed because more than one (" + loadHandlers.length + ") " +
+ ("save handlers for destination URL " + destURL + "."); });
+ saveHandler = saveHandlers[0];
+ sourceScheme = parseURL(sourceURL).scheme;
+ sourcePath = parseURL(sourceURL).path;
+ sameMedium = sourceScheme === parseURL(sourceURL).scheme;
+ return [4 /*yield*/, loadHandler.load()];
+ case 1:
+ modelArtifacts = _a.sent();
+ if (!(deleteSource && sameMedium)) return [3 /*break*/, 3];
+ return [4 /*yield*/, ModelStoreManagerRegistry.getManager(sourceScheme)
+ .removeModel(sourcePath)];
+ case 2:
+ _a.sent();
+ _a.label = 3;
+ case 3: return [4 /*yield*/, saveHandler.save(modelArtifacts)];
+ case 4:
+ saveResult = _a.sent();
+ if (!(deleteSource && !sameMedium)) return [3 /*break*/, 6];
+ return [4 /*yield*/, ModelStoreManagerRegistry.getManager(sourceScheme)
+ .removeModel(sourcePath)];
+ case 5:
+ _a.sent();
+ _a.label = 6;
+ case 6: return [2 /*return*/, saveResult.modelArtifactsInfo];
+ }
+ });
+ });
+ }
+ /**
+ * List all models stored in registered storage mediums.
+ *
+ * For a web browser environment, the registered mediums are Local Storage and
+ * IndexedDB.
+ *
+ * ```js
+ * // First create and save a model.
+ * const model = tf.sequential();
+ * model.add(tf.layers.dense(
+ * {units: 1, inputShape: [10], activation: 'sigmoid'}));
+ * await model.save('localstorage://demo/management/model1');
+ *
+ * // Then list existing models.
+ * console.log(JSON.stringify(await tf.io.listModels()));
+ *
+ * // Delete the model.
+ * await tf.io.removeModel('localstorage://demo/management/model1');
+ *
+ * // List models again.
+ * console.log(JSON.stringify(await tf.io.listModels()));
+ * ```
+ *
+ * @returns A `Promise` of a dictionary mapping URLs of existing models to
+ * their model artifacts info. URLs include medium-specific schemes, e.g.,
+ * 'indexeddb://my/model/1'. Model artifacts info include type of the
+ * model's topology, byte sizes of the topology, weights, etc.
+ *
+ * @doc {
+ * heading: 'Models',
+ * subheading: 'Management',
+ * namespace: 'io',
+ * ignoreCI: true
+ * }
+ */
+ function listModels() {
+ return __awaiter(this, void 0, void 0, function () {
+ var schemes, out, _i, schemes_1, scheme, schemeOut, path, url;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ schemes = ModelStoreManagerRegistry.getSchemes();
+ out = {};
+ _i = 0, schemes_1 = schemes;
+ _a.label = 1;
+ case 1:
+ if (!(_i < schemes_1.length)) return [3 /*break*/, 4];
+ scheme = schemes_1[_i];
+ return [4 /*yield*/, ModelStoreManagerRegistry.getManager(scheme).listModels()];
+ case 2:
+ schemeOut = _a.sent();
+ for (path in schemeOut) {
+ url = scheme + URL_SCHEME_SUFFIX + path;
+ out[url] = schemeOut[path];
+ }
+ _a.label = 3;
+ case 3:
+ _i++;
+ return [3 /*break*/, 1];
+ case 4: return [2 /*return*/, out];
+ }
+ });
+ });
+ }
+ /**
+ * Remove a model specified by URL from a reigstered storage medium.
+ *
+ * ```js
+ * // First create and save a model.
+ * const model = tf.sequential();
+ * model.add(tf.layers.dense(
+ * {units: 1, inputShape: [10], activation: 'sigmoid'}));
+ * await model.save('localstorage://demo/management/model1');
+ *
+ * // Then list existing models.
+ * console.log(JSON.stringify(await tf.io.listModels()));
+ *
+ * // Delete the model.
+ * await tf.io.removeModel('localstorage://demo/management/model1');
+ *
+ * // List models again.
+ * console.log(JSON.stringify(await tf.io.listModels()));
+ * ```
+ *
+ * @param url A URL to a stored model, with a scheme prefix, e.g.,
+ * 'localstorage://my-model-1', 'indexeddb://my/model/2'.
+ * @returns ModelArtifactsInfo of the deleted model (if and only if deletion
+ * is successful).
+ * @throws Error if deletion fails, e.g., if no model exists at `path`.
+ *
+ * @doc {
+ * heading: 'Models',
+ * subheading: 'Management',
+ * namespace: 'io',
+ * ignoreCI: true
+ * }
+ */
+ function removeModel(url) {
+ return __awaiter(this, void 0, void 0, function () {
+ var schemeAndPath, manager;
+ return __generator(this, function (_a) {
+ schemeAndPath = parseURL(url);
+ manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);
+ return [2 /*return*/, manager.removeModel(schemeAndPath.path)];
+ });
+ });
+ }
+ /**
+ * Copy a model from one URL to another.
+ *
+ * This function supports:
+ *
+ * 1. Copying within a storage medium, e.g.,
+ * `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`
+ * 2. Copying between two storage mediums, e.g.,
+ * `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`
+ *
+ * ```js
+ * // First create and save a model.
+ * const model = tf.sequential();
+ * model.add(tf.layers.dense(
+ * {units: 1, inputShape: [10], activation: 'sigmoid'}));
+ * await model.save('localstorage://demo/management/model1');
+ *
+ * // Then list existing models.
+ * console.log(JSON.stringify(await tf.io.listModels()));
+ *
+ * // Copy the model, from Local Storage to IndexedDB.
+ * await tf.io.copyModel(
+ * 'localstorage://demo/management/model1',
+ * 'indexeddb://demo/management/model1');
+ *
+ * // List models again.
+ * console.log(JSON.stringify(await tf.io.listModels()));
+ *
+ * // Remove both models.
+ * await tf.io.removeModel('localstorage://demo/management/model1');
+ * await tf.io.removeModel('indexeddb://demo/management/model1');
+ * ```
+ *
+ * @param sourceURL Source URL of copying.
+ * @param destURL Destination URL of copying.
+ * @returns ModelArtifactsInfo of the copied model (if and only if copying
+ * is successful).
+ * @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or
+ * if `oldPath` and `newPath` are identical.
+ *
+ * @doc {
+ * heading: 'Models',
+ * subheading: 'Management',
+ * namespace: 'io',
+ * ignoreCI: true
+ * }
+ */
+ function copyModel(sourceURL, destURL) {
+ return __awaiter(this, void 0, void 0, function () {
+ var deleteSource;
+ return __generator(this, function (_a) {
+ deleteSource = false;
+ return [2 /*return*/, cloneModelInternal(sourceURL, destURL, deleteSource)];
+ });
+ });
+ }
+ /**
+ * Move a model from one URL to another.
+ *
+ * This function supports:
+ *
+ * 1. Moving within a storage medium, e.g.,
+ * `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`
+ * 2. Moving between two storage mediums, e.g.,
+ * `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`
+ *
+ * ```js
+ * // First create and save a model.
+ * const model = tf.sequential();
+ * model.add(tf.layers.dense(
+ * {units: 1, inputShape: [10], activation: 'sigmoid'}));
+ * await model.save('localstorage://demo/management/model1');
+ *
+ * // Then list existing models.
+ * console.log(JSON.stringify(await tf.io.listModels()));
+ *
+ * // Move the model, from Local Storage to IndexedDB.
+ * await tf.io.moveModel(
+ * 'localstorage://demo/management/model1',
+ * 'indexeddb://demo/management/model1');
+ *
+ * // List models again.
+ * console.log(JSON.stringify(await tf.io.listModels()));
+ *
+ * // Remove the moved model.
+ * await tf.io.removeModel('indexeddb://demo/management/model1');
+ * ```
+ *
+ * @param sourceURL Source URL of moving.
+ * @param destURL Destination URL of moving.
+ * @returns ModelArtifactsInfo of the copied model (if and only if copying
+ * is successful).
+ * @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or
+ * if `oldPath` and `newPath` are identical.
+ *
+ * @doc {
+ * heading: 'Models',
+ * subheading: 'Management',
+ * namespace: 'io',
+ * ignoreCI: true
+ * }
+ */
+ function moveModel(sourceURL, destURL) {
+ return __awaiter(this, void 0, void 0, function () {
+ var deleteSource;
+ return __generator(this, function (_a) {
+ deleteSource = true;
+ return [2 /*return*/, cloneModelInternal(sourceURL, destURL, deleteSource)];
+ });
+ });
+ }
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var PlatformBrowser = /** @class */ (function () {
+ function PlatformBrowser() {
+ }
+ PlatformBrowser.prototype.fetch = function (path, init) {
+ return fetch(path, init);
+ };
+ PlatformBrowser.prototype.now = function () {
+ return performance.now();
+ };
+ PlatformBrowser.prototype.encode = function (text, encoding) {
+ if (encoding !== 'utf-8' && encoding !== 'utf8') {
+ throw new Error("Browser's encoder only supports utf-8, but got " + encoding);
+ }
+ if (this.textEncoder == null) {
+ this.textEncoder = new TextEncoder();
+ }
+ return this.textEncoder.encode(text);
+ };
+ PlatformBrowser.prototype.decode = function (bytes, encoding) {
+ return new TextDecoder(encoding).decode(bytes);
+ };
+ return PlatformBrowser;
+ }());
+ if (env().get('IS_BROWSER')) {
+ env().setPlatform('browser', new PlatformBrowser());
+ // Register LocalStorage IOHandler
+ try {
+ ModelStoreManagerRegistry.registerManager(BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());
+ }
+ catch (err) {
+ }
+ // Register IndexedDB IOHandler
+ try {
+ ModelStoreManagerRegistry.registerManager(BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());
+ }
+ catch (err) {
+ }
+ }
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ // We are wrapping this within an object so it can be stubbed by Jasmine.
+ var getNodeFetch = {
+ // tslint:disable-next-line:no-require-imports
+ importFetch: function () { return require('node-fetch'); }
+ };
+ var systemFetch;
+ var PlatformNode = /** @class */ (function () {
+ function PlatformNode() {
+ // tslint:disable-next-line:no-require-imports
+ this.util = require('util');
+ // According to the spec, the built-in encoder can do only UTF-8 encoding.
+ // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder
+ this.textEncoder = new this.util.TextEncoder();
+ }
+ PlatformNode.prototype.fetch = function (path, requestInits) {
+ if (env().global.fetch != null) {
+ return env().global.fetch(path, requestInits);
+ }
+ if (systemFetch == null) {
+ systemFetch = getNodeFetch.importFetch();
+ }
+ return systemFetch(path, requestInits);
+ };
+ PlatformNode.prototype.now = function () {
+ var time = process.hrtime();
+ return time[0] * 1000 + time[1] / 1000000;
+ };
+ PlatformNode.prototype.encode = function (text, encoding) {
+ if (encoding !== 'utf-8' && encoding !== 'utf8') {
+ throw new Error("Node built-in encoder only supports utf-8, but got " + encoding);
+ }
+ return this.textEncoder.encode(text);
+ };
+ PlatformNode.prototype.decode = function (bytes, encoding) {
+ if (bytes.length === 0) {
+ return '';
+ }
+ return new this.util.TextDecoder(encoding).decode(bytes);
+ };
+ return PlatformNode;
+ }());
+ if (env().get('IS_NODE')) {
+ env().setPlatform('node', new PlatformNode());
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google Inc. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.
+ *
+ * The values are stored in CPU as `TypedArray`. Fill the buffer using
+ * `buffer.set()`, or by modifying directly `buffer.values`.
+ *
+ * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with
+ * those values.
+ *
+ * ```js
+ * // Create a buffer and set values at particular indices.
+ * const buffer = tf.buffer([2, 2]);
+ * buffer.set(3, 0, 0);
+ * buffer.set(5, 1, 0);
+ *
+ * // Convert the buffer back to a tensor.
+ * buffer.toTensor().print();
+ * ```
+ *
+ * @param shape An array of integers defining the output tensor shape.
+ * @param dtype The dtype of the buffer. Defaults to 'float32'.
+ * @param values The values of the buffer as `TypedArray`. Defaults to
+ * zeros.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ function buffer(shape, dtype, values) {
+ if (dtype === void 0) { dtype = 'float32'; }
+ dtype = dtype || 'float32';
+ assertNonNegativeIntegerDimensions(shape);
+ return new TensorBuffer(shape, dtype, values);
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google Inc. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Casts a `tf.Tensor` to a new dtype.
+ *
+ * ```js
+ * const x = tf.tensor1d([1.5, 2.5, 3]);
+ * tf.cast(x, 'int32').print();
+ * ```
+ * @param x The input tensor to be casted.
+ * @param dtype The dtype to cast the input tensor to.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Transformations'}
+ */
+ function cast_(x, dtype) {
+ var $x = convertToTensor(x, 'x', 'cast');
+ // Sanity checks.
+ if (!isValidDtype(dtype)) {
+ throw new Error("Failed to cast to unknown dtype " + dtype);
+ }
+ if (dtype === 'string' && $x.dtype !== 'string' ||
+ dtype !== 'string' && $x.dtype === 'string') {
+ throw new Error('Only strings can be casted to strings');
+ }
+ var inputs = { x: $x };
+ var attrs = { dtype: dtype };
+ return ENGINE.runKernel(Cast, inputs, attrs);
+ }
+ var cast = op({ cast_: cast_ });
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Creates a new tensor with the same values and shape as the specified
+ * tensor.
+ *
+ * ```js
+ * const x = tf.tensor([1, 2]);
+ *
+ * x.clone().print();
+ * ```
+ *
+ * @param x The tensor to clone.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ function clone_(x) {
+ var $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');
+ var inputs = { x: $x };
+ // Note this op is called tf.identity in python. Hence the kernel name used
+ // here.
+ return ENGINE.runKernel(Identity, inputs);
+ }
+ var clone = op({ clone_: clone_ });
+
+ /**
+ * @license
+ * Copyright 2020 Google Inc. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Prints information about the `tf.Tensor` including its data.
+ *
+ * ```js
+ * const verbose = true;
+ * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);
+ * ```
+ * @param x The tensor to be printed.
+ * @param verbose Whether to print verbose information about the ` Tensor`,
+ * including dtype and size.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ function print(x, verbose) {
+ if (verbose === void 0) { verbose = false; }
+ console.log(x.toString(verbose));
+ }
+
+ /**
+ * @license
+ * Copyright 2020 Google Inc. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ getOrMakeEngine();
+ var opHandler$1 = {
+ buffer: buffer,
+ cast: cast,
+ clone: clone,
+ print: print
+ };
+ setOpHandler(opHandler$1);
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var DEFAULT_FILE_NAME_PREFIX = 'model';
+ var DEFAULT_JSON_EXTENSION_NAME = '.json';
+ var DEFAULT_WEIGHT_DATA_EXTENSION_NAME = '.weights.bin';
+ function defer(f) {
+ return new Promise(function (resolve) { return setTimeout(resolve); }).then(f);
+ }
+ var BrowserDownloads = /** @class */ (function () {
+ function BrowserDownloads(fileNamePrefix) {
+ if (!env().getBool('IS_BROWSER')) {
+ // TODO(cais): Provide info on what IOHandlers are available under the
+ // current environment.
+ throw new Error('browserDownloads() cannot proceed because the current environment ' +
+ 'is not a browser.');
+ }
+ if (fileNamePrefix.startsWith(BrowserDownloads.URL_SCHEME)) {
+ fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length);
+ }
+ if (fileNamePrefix == null || fileNamePrefix.length === 0) {
+ fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;
+ }
+ this.modelTopologyFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;
+ this.weightDataFileName =
+ fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;
+ }
+ BrowserDownloads.prototype.save = function (modelArtifacts) {
+ return __awaiter(this, void 0, void 0, function () {
+ var weightsURL, weightsManifest, modelTopologyAndWeightManifest, modelTopologyAndWeightManifestURL, jsonAnchor_1, weightDataAnchor_1;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ if (typeof (document) === 'undefined') {
+ throw new Error('Browser downloads are not supported in ' +
+ 'this environment since `document` is not present');
+ }
+ weightsURL = window.URL.createObjectURL(new Blob([modelArtifacts.weightData], { type: 'application/octet-stream' }));
+ if (!(modelArtifacts.modelTopology instanceof ArrayBuffer)) return [3 /*break*/, 1];
+ throw new Error('BrowserDownloads.save() does not support saving model topology ' +
+ 'in binary formats yet.');
+ case 1:
+ weightsManifest = [{
+ paths: ['./' + this.weightDataFileName],
+ weights: modelArtifacts.weightSpecs
+ }];
+ modelTopologyAndWeightManifest = {
+ modelTopology: modelArtifacts.modelTopology,
+ format: modelArtifacts.format,
+ generatedBy: modelArtifacts.generatedBy,
+ convertedBy: modelArtifacts.convertedBy,
+ weightsManifest: weightsManifest
+ };
+ if (modelArtifacts.signature != null) {
+ modelTopologyAndWeightManifest.signature = modelArtifacts.signature;
+ }
+ if (modelArtifacts.userDefinedMetadata != null) {
+ modelTopologyAndWeightManifest.userDefinedMetadata =
+ modelArtifacts.userDefinedMetadata;
+ }
+ if (modelArtifacts.modelInitializer != null) {
+ modelTopologyAndWeightManifest.modelInitializer =
+ modelArtifacts.modelInitializer;
+ }
+ modelTopologyAndWeightManifestURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: 'application/json' }));
+ jsonAnchor_1 = this.jsonAnchor == null ? document.createElement('a') :
+ this.jsonAnchor;
+ jsonAnchor_1.download = this.modelTopologyFileName;
+ jsonAnchor_1.href = modelTopologyAndWeightManifestURL;
+ // Trigger downloads by evoking a click event on the download anchors.
+ // When multiple downloads are started synchronously, Firefox will only
+ // save the last one.
+ return [4 /*yield*/, defer(function () { return jsonAnchor_1.dispatchEvent(new MouseEvent('click')); })];
+ case 2:
+ // Trigger downloads by evoking a click event on the download anchors.
+ // When multiple downloads are started synchronously, Firefox will only
+ // save the last one.
+ _a.sent();
+ if (!(modelArtifacts.weightData != null)) return [3 /*break*/, 4];
+ weightDataAnchor_1 = this.weightDataAnchor == null ?
+ document.createElement('a') :
+ this.weightDataAnchor;
+ weightDataAnchor_1.download = this.weightDataFileName;
+ weightDataAnchor_1.href = weightsURL;
+ return [4 /*yield*/, defer(function () { return weightDataAnchor_1.dispatchEvent(new MouseEvent('click')); })];
+ case 3:
+ _a.sent();
+ _a.label = 4;
+ case 4: return [2 /*return*/, { modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts) }];
+ }
+ });
+ });
+ };
+ BrowserDownloads.URL_SCHEME = 'downloads://';
+ return BrowserDownloads;
+ }());
+ var BrowserFiles = /** @class */ (function () {
+ function BrowserFiles(files) {
+ if (files == null || files.length < 1) {
+ throw new Error("When calling browserFiles, at least 1 file is required, " +
+ ("but received " + files));
+ }
+ this.files = files;
+ }
+ BrowserFiles.prototype.load = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var jsonFile, weightFiles;
+ var _this = this;
+ return __generator(this, function (_a) {
+ jsonFile = this.files[0];
+ weightFiles = this.files.slice(1);
+ return [2 /*return*/, new Promise(function (resolve, reject) {
+ var jsonReader = new FileReader();
+ jsonReader.onload = function (event) {
+ // tslint:disable-next-line:no-any
+ var modelJSON = JSON.parse(event.target.result);
+ var modelTopology = modelJSON.modelTopology;
+ if (modelTopology == null) {
+ reject(new Error("modelTopology field is missing from file " + jsonFile.name));
+ return;
+ }
+ if (weightFiles.length === 0) {
+ resolve({ modelTopology: modelTopology });
+ }
+ var weightsManifest = modelJSON.weightsManifest;
+ if (weightsManifest == null) {
+ reject(new Error("weightManifest field is missing from file " + jsonFile.name));
+ return;
+ }
+ var pathToFile;
+ try {
+ pathToFile =
+ _this.checkManifestAndWeightFiles(weightsManifest, weightFiles);
+ }
+ catch (err) {
+ reject(err);
+ return;
+ }
+ var weightSpecs = [];
+ var paths = [];
+ var perFileBuffers = [];
+ weightsManifest.forEach(function (weightsGroup) {
+ weightsGroup.paths.forEach(function (path) {
+ paths.push(path);
+ perFileBuffers.push(null);
+ });
+ weightSpecs.push.apply(weightSpecs, weightsGroup.weights);
+ });
+ weightsManifest.forEach(function (weightsGroup) {
+ weightsGroup.paths.forEach(function (path) {
+ var weightFileReader = new FileReader();
+ weightFileReader.onload = function (event) {
+ // tslint:disable-next-line:no-any
+ var weightData = event.target.result;
+ var index = paths.indexOf(path);
+ perFileBuffers[index] = weightData;
+ if (perFileBuffers.indexOf(null) === -1) {
+ var result = {
+ modelTopology: modelTopology,
+ weightSpecs: weightSpecs,
+ weightData: concatenateArrayBuffers(perFileBuffers),
+ format: modelJSON.format,
+ generatedBy: modelJSON.generatedBy,
+ convertedBy: modelJSON.convertedBy
+ };
+ if (modelJSON.signature != null) {
+ result.signature = modelJSON.signature;
+ }
+ if (modelJSON.userDefinedMetadata != null) {
+ result.userDefinedMetadata = modelJSON.userDefinedMetadata;
+ }
+ if (modelJSON.modelInitializer != null) {
+ result.modelInitializer = modelJSON.modelInitializer;
+ }
+ resolve(result);
+ }
+ };
+ weightFileReader.onerror = function (error) {
+ return reject("Failed to weights data from file of path '" + path + "'.");
+ };
+ weightFileReader.readAsArrayBuffer(pathToFile[path]);
+ });
+ });
+ };
+ jsonReader.onerror = function (error) { return reject("Failed to read model topology and weights manifest JSON " +
+ ("from file '" + jsonFile.name + "'. BrowserFiles supports loading ") +
+ "Keras-style tf.Model artifacts only."); };
+ jsonReader.readAsText(jsonFile);
+ })];
+ });
+ });
+ };
+ /**
+ * Check the compatibility between weights manifest and weight files.
+ */
+ BrowserFiles.prototype.checkManifestAndWeightFiles = function (manifest, files) {
+ var basenames = [];
+ var fileNames = files.map(function (file) { return basename(file.name); });
+ var pathToFile = {};
+ for (var _i = 0, manifest_1 = manifest; _i < manifest_1.length; _i++) {
+ var group = manifest_1[_i];
+ group.paths.forEach(function (path) {
+ var pathBasename = basename(path);
+ if (basenames.indexOf(pathBasename) !== -1) {
+ throw new Error("Duplicate file basename found in weights manifest: " +
+ ("'" + pathBasename + "'"));
+ }
+ basenames.push(pathBasename);
+ if (fileNames.indexOf(pathBasename) === -1) {
+ throw new Error("Weight file with basename '" + pathBasename + "' is not provided.");
+ }
+ else {
+ pathToFile[path] = files[fileNames.indexOf(pathBasename)];
+ }
+ });
+ }
+ if (basenames.length !== files.length) {
+ throw new Error("Mismatch in the number of files in weights manifest " +
+ ("(" + basenames.length + ") and the number of weight files provided ") +
+ ("(" + files.length + ")."));
+ }
+ return pathToFile;
+ };
+ return BrowserFiles;
+ }());
+ var browserDownloadsRouter = function (url) {
+ if (!env().getBool('IS_BROWSER')) {
+ return null;
+ }
+ else {
+ if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) {
+ return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));
+ }
+ else {
+ return null;
+ }
+ }
+ };
+ IORouterRegistry.registerSaveRouter(browserDownloadsRouter);
+ /**
+ * Creates an IOHandler that triggers file downloads from the browser.
+ *
+ * The returned `IOHandler` instance can be used as model exporting methods such
+ * as `tf.Model.save` and supports only saving.
+ *
+ * ```js
+ * const model = tf.sequential();
+ * model.add(tf.layers.dense(
+ * {units: 1, inputShape: [10], activation: 'sigmoid'}));
+ * const saveResult = await model.save('downloads://mymodel');
+ * // This will trigger downloading of two files:
+ * // 'mymodel.json' and 'mymodel.weights.bin'.
+ * console.log(saveResult);
+ * ```
+ *
+ * @param fileNamePrefix Prefix name of the files to be downloaded. For use with
+ * `tf.Model`, `fileNamePrefix` should follow either of the following two
+ * formats:
+ * 1. `null` or `undefined`, in which case the default file
+ * names will be used:
+ * - 'model.json' for the JSON file containing the model topology and
+ * weights manifest.
+ * - 'model.weights.bin' for the binary file containing the binary weight
+ * values.
+ * 2. A single string or an Array of a single string, as the file name prefix.
+ * For example, if `'foo'` is provided, the downloaded JSON
+ * file and binary weights file will be named 'foo.json' and
+ * 'foo.weights.bin', respectively.
+ * @param config Additional configuration for triggering downloads.
+ * @returns An instance of `BrowserDownloads` `IOHandler`.
+ *
+ * @doc {
+ * heading: 'Models',
+ * subheading: 'Loading',
+ * namespace: 'io',
+ * ignoreCI: true
+ * }
+ */
+ function browserDownloads(fileNamePrefix) {
+ if (fileNamePrefix === void 0) { fileNamePrefix = 'model'; }
+ return new BrowserDownloads(fileNamePrefix);
+ }
+ /**
+ * Creates an IOHandler that loads model artifacts from user-selected files.
+ *
+ * This method can be used for loading from files such as user-selected files
+ * in the browser.
+ * When used in conjunction with `tf.loadLayersModel`, an instance of
+ * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.
+ *
+ * ```js
+ * // Note: This code snippet won't run properly without the actual file input
+ * // elements in the HTML DOM.
+ *
+ * // Suppose there are two HTML file input (``)
+ * // elements.
+ * const uploadJSONInput = document.getElementById('upload-json');
+ * const uploadWeightsInput = document.getElementById('upload-weights');
+ * const model = await tf.loadLayersModel(tf.io.browserFiles(
+ * [uploadJSONInput.files[0], uploadWeightsInput.files[0]]));
+ * ```
+ *
+ * @param files `File`s to load from. Currently, this function supports only
+ * loading from files that contain Keras-style models (i.e., `tf.Model`s), for
+ * which an `Array` of `File`s is expected (in that order):
+ * - A JSON file containing the model topology and weight manifest.
+ * - Optionally, One or more binary files containing the binary weights.
+ * These files must have names that match the paths in the `weightsManifest`
+ * contained by the aforementioned JSON file, or errors will be thrown
+ * during loading. These weights files have the same format as the ones
+ * generated by `tensorflowjs_converter` that comes with the `tensorflowjs`
+ * Python PIP package. If no weights files are provided, only the model
+ * topology will be loaded from the JSON file above.
+ * @returns An instance of `Files` `IOHandler`.
+ *
+ * @doc {
+ * heading: 'Models',
+ * subheading: 'Loading',
+ * namespace: 'io',
+ * ignoreCI: true
+ * }
+ */
+ function browserFiles(files) {
+ return new BrowserFiles(files);
+ }
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Monitor Promise.all progress, fire onProgress callback function.
+ *
+ * @param promises Promise list going to be monitored
+ * @param onProgress Callback function. Fired when a promise resolved.
+ * @param startFraction Optional fraction start. Default to 0.
+ * @param endFraction Optional fraction end. Default to 1.
+ */
+ function monitorPromisesProgress(promises, onProgress, startFraction, endFraction) {
+ checkPromises(promises);
+ startFraction = startFraction == null ? 0 : startFraction;
+ endFraction = endFraction == null ? 1 : endFraction;
+ checkFraction(startFraction, endFraction);
+ var resolvedPromise = 0;
+ var registerMonitor = function (promise) {
+ promise.then(function (value) {
+ var fraction = startFraction +
+ ++resolvedPromise / promises.length * (endFraction - startFraction);
+ // pass fraction as parameter to callback function.
+ onProgress(fraction);
+ return value;
+ });
+ return promise;
+ };
+ function checkPromises(promises) {
+ assert(promises != null && Array.isArray(promises) && promises.length > 0, function () { return 'promises must be a none empty array'; });
+ }
+ function checkFraction(startFraction, endFraction) {
+ assert(startFraction >= 0 && startFraction <= 1, function () { return "Progress fraction must be in range [0, 1], but " +
+ ("got startFraction " + startFraction); });
+ assert(endFraction >= 0 && endFraction <= 1, function () { return "Progress fraction must be in range [0, 1], but " +
+ ("got endFraction " + endFraction); });
+ assert(endFraction >= startFraction, function () { return "startFraction must be no more than endFraction, but " +
+ ("got startFraction " + startFraction + " and endFraction ") +
+ ("" + endFraction); });
+ }
+ return Promise.all(promises.map(registerMonitor));
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Reads binary weights data from a number of URLs.
+ *
+ * @param fetchURLs URLs to send the HTTP requests at, using `fetch` calls.
+ * @param requestOptions RequestInit (options) for the HTTP requests.
+ * @param fetchFunc Optional overriding value for the `window.fetch` function.
+ * @param onProgress Optional, progress callback function, fired periodically
+ * before the load is completed.
+ * @returns A `Promise` of an Array of `ArrayBuffer`. The Array has the same
+ * length as `fetchURLs`.
+ */
+ function loadWeightsAsArrayBuffer(fetchURLs, loadOptions) {
+ return __awaiter(this, void 0, void 0, function () {
+ var fetchFunc, requests, fetchStartFraction, fetchEndFraction, responses, _a, bufferPromises, bufferStartFraction, bufferEndFraction, buffers, _b;
+ return __generator(this, function (_c) {
+ switch (_c.label) {
+ case 0:
+ if (loadOptions == null) {
+ loadOptions = {};
+ }
+ fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch :
+ loadOptions.fetchFunc;
+ requests = fetchURLs.map(function (fetchURL) {
+ return fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true });
+ });
+ fetchStartFraction = 0;
+ fetchEndFraction = 0.5;
+ if (!(loadOptions.onProgress == null)) return [3 /*break*/, 2];
+ return [4 /*yield*/, Promise.all(requests)];
+ case 1:
+ _a = _c.sent();
+ return [3 /*break*/, 4];
+ case 2: return [4 /*yield*/, monitorPromisesProgress(requests, loadOptions.onProgress, fetchStartFraction, fetchEndFraction)];
+ case 3:
+ _a = _c.sent();
+ _c.label = 4;
+ case 4:
+ responses = _a;
+ bufferPromises = responses.map(function (response) { return response.arrayBuffer(); });
+ bufferStartFraction = 0.5;
+ bufferEndFraction = 1;
+ if (!(loadOptions.onProgress == null)) return [3 /*break*/, 6];
+ return [4 /*yield*/, Promise.all(bufferPromises)];
+ case 5:
+ _b = _c.sent();
+ return [3 /*break*/, 8];
+ case 6: return [4 /*yield*/, monitorPromisesProgress(bufferPromises, loadOptions.onProgress, bufferStartFraction, bufferEndFraction)];
+ case 7:
+ _b = _c.sent();
+ _c.label = 8;
+ case 8:
+ buffers = _b;
+ return [2 /*return*/, buffers];
+ }
+ });
+ });
+ }
+ /**
+ * Reads a weights manifest JSON configuration, fetches the weights and
+ * returns them as `Tensor`s.
+ *
+ * @param manifest The weights manifest JSON.
+ * @param filePathPrefix The path prefix for filenames given in the manifest.
+ * Defaults to the empty string.
+ * @param weightNames The names of the weights to be fetched.
+ */
+ function loadWeights(manifest, filePathPrefix, weightNames, requestInit) {
+ if (filePathPrefix === void 0) { filePathPrefix = ''; }
+ return __awaiter(this, void 0, void 0, function () {
+ var fetchWeights, loadWeights;
+ return __generator(this, function (_a) {
+ fetchWeights = function (fetchUrls) {
+ return loadWeightsAsArrayBuffer(fetchUrls, { requestInit: requestInit });
+ };
+ loadWeights = weightsLoaderFactory(fetchWeights);
+ return [2 /*return*/, loadWeights(manifest, filePathPrefix, weightNames)];
+ });
+ });
+ }
+ /**
+ * Creates a function, which reads a weights manifest JSON configuration,
+ * fetches the weight files using the specified function and returns them as
+ * `Tensor`s.
+ *
+ * ```js
+ * // example for creating a nodejs weight loader, which reads the weight files
+ * // from disk using fs.readFileSync
+ *
+ * import * as fs from 'fs'
+ *
+ * const fetchWeightsFromDisk = (filePaths: string[]) =>
+ * filePaths.map(filePath => fs.readFileSync(filePath).buffer)
+ *
+ * const loadWeights = tf.io.weightsLoaderFactory(fetchWeightsFromDisk)
+ *
+ * const manifest = JSON.parse(
+ * fs.readFileSync('./my_model-weights_manifest').toString()
+ * )
+ * const weightMap = await loadWeights(manifest, './')
+ * ```
+ * @param fetchWeightsFunction The function used for fetching the weight files.
+ * @returns Weight loading function.
+ */
+ function weightsLoaderFactory(fetchWeightsFunction) {
+ var _this = this;
+ return function (manifest, filePathPrefix, weightNames) {
+ if (filePathPrefix === void 0) { filePathPrefix = ''; }
+ return __awaiter(_this, void 0, void 0, function () {
+ var groupIndicesToFetchMap, groupWeightsToFetch, weightsFound, allManifestWeightNames, weightsNotFound, groupIndicesToFetch, fetchUrls, buffers, weightsTensorMap, bufferIndexOffset;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ groupIndicesToFetchMap = manifest.map(function () { return false; });
+ groupWeightsToFetch = {};
+ weightsFound = weightNames != null ? weightNames.map(function () { return false; }) : [];
+ allManifestWeightNames = [];
+ manifest.forEach(function (manifestGroupConfig, groupIndex) {
+ var groupOffset = 0;
+ manifestGroupConfig.weights.forEach(function (weightsEntry) {
+ var rawDtype = ('quantization' in weightsEntry) ?
+ weightsEntry.quantization.dtype :
+ weightsEntry.dtype;
+ var weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] *
+ sizeFromShape(weightsEntry.shape);
+ var enqueueWeightsForFetchingFn = function () {
+ groupIndicesToFetchMap[groupIndex] = true;
+ if (groupWeightsToFetch[groupIndex] == null) {
+ groupWeightsToFetch[groupIndex] = [];
+ }
+ groupWeightsToFetch[groupIndex].push({
+ manifestEntry: weightsEntry,
+ groupOffset: groupOffset,
+ sizeBytes: weightsBytes
+ });
+ };
+ if (weightNames != null) {
+ weightNames.forEach(function (weightName, weightIndex) {
+ if (weightName === weightsEntry.name) {
+ enqueueWeightsForFetchingFn();
+ weightsFound[weightIndex] = true;
+ }
+ });
+ }
+ else {
+ enqueueWeightsForFetchingFn();
+ }
+ allManifestWeightNames.push(weightsEntry.name);
+ groupOffset += weightsBytes;
+ });
+ });
+ if (!weightsFound.every(function (found) { return found; })) {
+ weightsNotFound = weightNames.filter(function (_, i) { return !weightsFound[i]; });
+ throw new Error("Could not find weights in manifest with names: " +
+ (weightsNotFound.join(', ') + ". \n") +
+ "Manifest JSON has weights with names: " +
+ (allManifestWeightNames.join(', ') + "."));
+ }
+ groupIndicesToFetch = groupIndicesToFetchMap.reduce(function (accumulator, shouldFetch, i) {
+ if (shouldFetch) {
+ accumulator.push(i);
+ }
+ return accumulator;
+ }, []);
+ fetchUrls = [];
+ groupIndicesToFetch.forEach(function (i) {
+ manifest[i].paths.forEach(function (filepath) {
+ var fetchUrl = filePathPrefix +
+ (!filePathPrefix.endsWith('/') ? '/' : '') + filepath;
+ fetchUrls.push(fetchUrl);
+ });
+ });
+ return [4 /*yield*/, fetchWeightsFunction(fetchUrls)];
+ case 1:
+ buffers = _a.sent();
+ weightsTensorMap = {};
+ bufferIndexOffset = 0;
+ groupIndicesToFetch.forEach(function (i) {
+ var numBuffers = manifest[i].paths.length;
+ var groupBytes = 0;
+ for (var i_1 = 0; i_1 < numBuffers; i_1++) {
+ groupBytes += buffers[bufferIndexOffset + i_1].byteLength;
+ }
+ // Create a buffer for the whole group.
+ var groupBuffer = new ArrayBuffer(groupBytes);
+ var groupByteBuffer = new Uint8Array(groupBuffer);
+ var groupBufferOffset = 0;
+ for (var i_2 = 0; i_2 < numBuffers; i_2++) {
+ var buffer = new Uint8Array(buffers[bufferIndexOffset + i_2]);
+ groupByteBuffer.set(buffer, groupBufferOffset);
+ groupBufferOffset += buffer.byteLength;
+ }
+ var weightsEntries = groupWeightsToFetch[i];
+ weightsEntries.forEach(function (weightsEntry) {
+ var byteBuffer = groupBuffer.slice(weightsEntry.groupOffset, weightsEntry.groupOffset + weightsEntry.sizeBytes);
+ var nameToTensorMap = decodeWeights(byteBuffer, [weightsEntry.manifestEntry]);
+ for (var name_1 in nameToTensorMap) {
+ weightsTensorMap[name_1] = nameToTensorMap[name_1];
+ }
+ });
+ bufferIndexOffset += numBuffers;
+ });
+ return [2 /*return*/, weightsTensorMap];
+ }
+ });
+ });
+ };
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var OCTET_STREAM_MIME_TYPE = 'application/octet-stream';
+ var JSON_TYPE = 'application/json';
+ var HTTPRequest = /** @class */ (function () {
+ function HTTPRequest(path, loadOptions) {
+ this.DEFAULT_METHOD = 'POST';
+ if (loadOptions == null) {
+ loadOptions = {};
+ }
+ this.weightPathPrefix = loadOptions.weightPathPrefix;
+ this.onProgress = loadOptions.onProgress;
+ this.weightUrlConverter = loadOptions.weightUrlConverter;
+ if (loadOptions.fetchFunc != null) {
+ assert(typeof loadOptions.fetchFunc === 'function', function () { return 'Must pass a function that matches the signature of ' +
+ '`fetch` (see ' +
+ 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)'; });
+ this.fetch = loadOptions.fetchFunc;
+ }
+ else {
+ this.fetch = env().platform.fetch;
+ }
+ assert(path != null && path.length > 0, function () { return 'URL path for http must not be null, undefined or ' +
+ 'empty.'; });
+ if (Array.isArray(path)) {
+ assert(path.length === 2, function () { return 'URL paths for http must have a length of 2, ' +
+ ("(actual length is " + path.length + ")."); });
+ }
+ this.path = path;
+ if (loadOptions.requestInit != null &&
+ loadOptions.requestInit.body != null) {
+ throw new Error('requestInit is expected to have no pre-existing body, but has one.');
+ }
+ this.requestInit = loadOptions.requestInit || {};
+ }
+ HTTPRequest.prototype.save = function (modelArtifacts) {
+ return __awaiter(this, void 0, void 0, function () {
+ var init, weightsManifest, modelTopologyAndWeightManifest, response;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0:
+ if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
+ throw new Error('BrowserHTTPRequest.save() does not support saving model topology ' +
+ 'in binary formats yet.');
+ }
+ init = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);
+ init.body = new FormData();
+ weightsManifest = [{
+ paths: ['./model.weights.bin'],
+ weights: modelArtifacts.weightSpecs,
+ }];
+ modelTopologyAndWeightManifest = {
+ modelTopology: modelArtifacts.modelTopology,
+ format: modelArtifacts.format,
+ generatedBy: modelArtifacts.generatedBy,
+ convertedBy: modelArtifacts.convertedBy,
+ weightsManifest: weightsManifest
+ };
+ if (modelArtifacts.signature != null) {
+ modelTopologyAndWeightManifest.signature = modelArtifacts.signature;
+ }
+ if (modelArtifacts.userDefinedMetadata != null) {
+ modelTopologyAndWeightManifest.userDefinedMetadata =
+ modelArtifacts.userDefinedMetadata;
+ }
+ if (modelArtifacts.modelInitializer != null) {
+ modelTopologyAndWeightManifest.modelInitializer =
+ modelArtifacts.modelInitializer;
+ }
+ init.body.append('model.json', new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: JSON_TYPE }), 'model.json');
+ if (modelArtifacts.weightData != null) {
+ init.body.append('model.weights.bin', new Blob([modelArtifacts.weightData], { type: OCTET_STREAM_MIME_TYPE }), 'model.weights.bin');
+ }
+ return [4 /*yield*/, this.fetch(this.path, init)];
+ case 1:
+ response = _a.sent();
+ if (response.ok) {
+ return [2 /*return*/, {
+ modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),
+ responses: [response],
+ }];
+ }
+ else {
+ throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status " +
+ (response.status + "."));
+ }
+ }
+ });
+ });
+ };
+ /**
+ * Load model artifacts via HTTP request(s).
+ *
+ * See the documentation to `tf.io.http` for details on the saved
+ * artifacts.
+ *
+ * @returns The loaded model artifacts (if loading succeeds).
+ */
+ HTTPRequest.prototype.load = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ var modelConfigRequest, modelConfig, e_1, message, modelTopology, weightsManifest, generatedBy, convertedBy, format, signature, userDefinedMetadata, weightSpecs, weightData, results, artifacts, initializer;
+ return __generator(this, function (_a) {
+ switch (_a.label) {
+ case 0: return [4 /*yield*/, this.fetch(this.path, this.requestInit)];
+ case 1:
+ modelConfigRequest = _a.sent();
+ if (!modelConfigRequest.ok) {
+ throw new Error("Request to " + this.path + " failed with status code " +
+ (modelConfigRequest.status + ". Please verify this URL points to ") +
+ "the model JSON of the model to load.");
+ }
+ _a.label = 2;
+ case 2:
+ _a.trys.push([2, 4, , 5]);
+ return [4 /*yield*/, modelConfigRequest.json()];
+ case 3:
+ modelConfig = _a.sent();
+ return [3 /*break*/, 5];
+ case 4:
+ e_1 = _a.sent();
+ message = "Failed to parse model JSON of response from " + this.path + ".";
+ // TODO(nsthorat): Remove this after some time when we're comfortable that
+ // .pb files are mostly gone.
+ if (this.path.endsWith('.pb')) {
+ message += ' 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.';
+ }
+ else {
+ message += ' Please make sure the server is serving valid ' +
+ 'JSON for this request.';
+ }
+ throw new Error(message);
+ case 5:
+ modelTopology = modelConfig.modelTopology;
+ weightsManifest = modelConfig.weightsManifest;
+ generatedBy = modelConfig.generatedBy;
+ convertedBy = modelConfig.convertedBy;
+ format = modelConfig.format;
+ signature = modelConfig.signature;
+ userDefinedMetadata = modelConfig.userDefinedMetadata;
+ // We do not allow both modelTopology and weightsManifest to be missing.
+ if (modelTopology == null && weightsManifest == null) {
+ throw new Error("The JSON from HTTP path " + this.path + " contains neither model " +
+ "topology or manifest for weights.");
+ }
+ if (!(weightsManifest != null)) return [3 /*break*/, 7];
+ return [4 /*yield*/, this.loadWeights(weightsManifest)];
+ case 6:
+ results = _a.sent();
+ weightSpecs = results[0], weightData = results[1];
+ _a.label = 7;
+ case 7:
+ artifacts = {
+ modelTopology: modelTopology,
+ weightSpecs: weightSpecs,
+ weightData: weightData,
+ generatedBy: generatedBy,
+ convertedBy: convertedBy,
+ format: format
+ };
+ if (signature != null) {
+ artifacts.signature = signature;
+ }
+ if (userDefinedMetadata != null) {
+ artifacts.userDefinedMetadata = userDefinedMetadata;
+ }
+ initializer = modelConfig.modelInitializer;
+ if (initializer) {
+ artifacts.modelInitializer = initializer;
+ }
+ return [2 /*return*/, artifacts];
+ }
+ });
+ });
+ };
+ HTTPRequest.prototype.loadWeights = function (weightsManifest) {
+ return __awaiter(this, void 0, void 0, function () {
+ var weightPath, _a, prefix, suffix, pathPrefix, weightSpecs, _i, weightsManifest_1, entry, fetchURLs, urlPromises, _b, weightsManifest_2, weightsGroup, _c, _d, path, _e, _f, _g, buffers;
+ return __generator(this, function (_h) {
+ switch (_h.label) {
+ case 0:
+ weightPath = Array.isArray(this.path) ? this.path[1] : this.path;
+ _a = parseUrl(weightPath), prefix = _a[0], suffix = _a[1];
+ pathPrefix = this.weightPathPrefix || prefix;
+ weightSpecs = [];
+ for (_i = 0, weightsManifest_1 = weightsManifest; _i < weightsManifest_1.length; _i++) {
+ entry = weightsManifest_1[_i];
+ weightSpecs.push.apply(weightSpecs, entry.weights);
+ }
+ fetchURLs = [];
+ urlPromises = [];
+ for (_b = 0, weightsManifest_2 = weightsManifest; _b < weightsManifest_2.length; _b++) {
+ weightsGroup = weightsManifest_2[_b];
+ for (_c = 0, _d = weightsGroup.paths; _c < _d.length; _c++) {
+ path = _d[_c];
+ if (this.weightUrlConverter != null) {
+ urlPromises.push(this.weightUrlConverter(path));
+ }
+ else {
+ fetchURLs.push(pathPrefix + path + suffix);
+ }
+ }
+ }
+ if (!this.weightUrlConverter) return [3 /*break*/, 2];
+ _f = (_e = fetchURLs.push).apply;
+ _g = [fetchURLs];
+ return [4 /*yield*/, Promise.all(urlPromises)];
+ case 1:
+ _f.apply(_e, _g.concat([_h.sent()]));
+ _h.label = 2;
+ case 2: return [4 /*yield*/, loadWeightsAsArrayBuffer(fetchURLs, {
+ requestInit: this.requestInit,
+ fetchFunc: this.fetch,
+ onProgress: this.onProgress
+ })];
+ case 3:
+ buffers = _h.sent();
+ return [2 /*return*/, [weightSpecs, concatenateArrayBuffers(buffers)]];
+ }
+ });
+ });
+ };
+ HTTPRequest.URL_SCHEME_REGEX = /^https?:\/\//;
+ return HTTPRequest;
+ }());
+ /**
+ * Extract the prefix and suffix of the url, where the prefix is the path before
+ * the last file, and suffix is the search params after the last file.
+ * ```
+ * const url = 'http://tfhub.dev/model/1/tensorflowjs_model.pb?tfjs-format=file'
+ * [prefix, suffix] = parseUrl(url)
+ * // prefix = 'http://tfhub.dev/model/1/'
+ * // suffix = '?tfjs-format=file'
+ * ```
+ * @param url the model url to be parsed.
+ */
+ function parseUrl(url) {
+ var lastSlash = url.lastIndexOf('/');
+ var lastSearchParam = url.lastIndexOf('?');
+ var prefix = url.substring(0, lastSlash);
+ var suffix = lastSearchParam > lastSlash ? url.substring(lastSearchParam) : '';
+ return [prefix + '/', suffix];
+ }
+ function isHTTPScheme(url) {
+ return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;
+ }
+ var httpRouter = function (url, loadOptions) {
+ if (typeof fetch === 'undefined' &&
+ (loadOptions == null || loadOptions.fetchFunc == null)) {
+ // `http` uses `fetch` or `node-fetch`, if one wants to use it in
+ // an environment that is not the browser or node they have to setup a
+ // global fetch polyfill.
+ return null;
+ }
+ else {
+ var isHTTP = true;
+ if (Array.isArray(url)) {
+ isHTTP = url.every(function (urlItem) { return isHTTPScheme(urlItem); });
+ }
+ else {
+ isHTTP = isHTTPScheme(url);
+ }
+ if (isHTTP) {
+ return http(url, loadOptions);
+ }
+ }
+ return null;
+ };
+ IORouterRegistry.registerSaveRouter(httpRouter);
+ IORouterRegistry.registerLoadRouter(httpRouter);
+ /**
+ * Creates an IOHandler subtype that sends model artifacts to HTTP server.
+ *
+ * An HTTP request of the `multipart/form-data` mime type will be sent to the
+ * `path` URL. The form data includes artifacts that represent the topology
+ * and/or weights of the model. In the case of Keras-style `tf.Model`, two
+ * blobs (files) exist in form-data:
+ * - A JSON file consisting of `modelTopology` and `weightsManifest`.
+ * - A binary weights file consisting of the concatenated weight values.
+ * These files are in the same format as the one generated by
+ * [tfjs_converter](https://js.tensorflow.org/tutorials/import-keras.html).
+ *
+ * The following code snippet exemplifies the client-side code that uses this
+ * function:
+ *
+ * ```js
+ * const model = tf.sequential();
+ * model.add(
+ * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));
+ *
+ * const saveResult = await model.save(tf.io.http(
+ * 'http://model-server:5000/upload', {requestInit: {method: 'PUT'}}));
+ * console.log(saveResult);
+ * ```
+ *
+ * If the default `POST` method is to be used, without any custom parameters
+ * such as headers, you can simply pass an HTTP or HTTPS URL to `model.save`:
+ *
+ * ```js
+ * const saveResult = await model.save('http://model-server:5000/upload');
+ * ```
+ *
+ * The following GitHub Gist
+ * https://gist.github.com/dsmilkov/1b6046fd6132d7408d5257b0976f7864
+ * implements a server based on [flask](https://github.com/pallets/flask) that
+ * can receive the request. Upon receiving the model artifacts via the requst,
+ * this particular server reconsistutes instances of [Keras
+ * Models](https://keras.io/models/model/) in memory.
+ *
+ *
+ * @param path A URL path to the model.
+ * Can be an absolute HTTP path (e.g.,
+ * 'http://localhost:8000/model-upload)') or a relative path (e.g.,
+ * './model-upload').
+ * @param requestInit Request configurations to be used when sending
+ * HTTP request to server using `fetch`. It can contain fields such as
+ * `method`, `credentials`, `headers`, `mode`, etc. See
+ * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request
+ * for more information. `requestInit` must not have a body, because the
+ * body will be set by TensorFlow.js. File blobs representing the model
+ * topology (filename: 'model.json') and the weights of the model (filename:
+ * 'model.weights.bin') will be appended to the body. If `requestInit` has a
+ * `body`, an Error will be thrown.
+ * @param loadOptions Optional configuration for the loading. It includes the
+ * following fields:
+ * - weightPathPrefix Optional, this specifies the path prefix for weight
+ * files, by default this is calculated from the path param.
+ * - fetchFunc Optional, custom `fetch` function. E.g., in Node.js,
+ * the `fetch` from node-fetch can be used here.
+ * - onProgress Optional, progress callback function, fired periodically
+ * before the load is completed.
+ * @returns An instance of `IOHandler`.
+ *
+ * @doc {
+ * heading: 'Models',
+ * subheading: 'Loading',
+ * namespace: 'io',
+ * ignoreCI: true
+ * }
+ */
+ function http(path, loadOptions) {
+ return new HTTPRequest(path, loadOptions);
+ }
+ /**
+ * Deprecated. Use `tf.io.http`.
+ * @param path
+ * @param loadOptions
+ */
+ function browserHTTPRequest(path, loadOptions) {
+ return http(path, loadOptions);
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var PassthroughLoader = /** @class */ (function () {
+ function PassthroughLoader(modelArtifacts) {
+ this.modelArtifacts = modelArtifacts;
+ }
+ PassthroughLoader.prototype.load = function () {
+ return __awaiter(this, void 0, void 0, function () {
+ return __generator(this, function (_a) {
+ return [2 /*return*/, this.modelArtifacts];
+ });
+ });
+ };
+ return PassthroughLoader;
+ }());
+ var PassthroughSaver = /** @class */ (function () {
+ function PassthroughSaver(saveHandler) {
+ this.saveHandler = saveHandler;
+ }
+ PassthroughSaver.prototype.save = function (modelArtifacts) {
+ return __awaiter(this, void 0, void 0, function () {
+ return __generator(this, function (_a) {
+ return [2 /*return*/, this.saveHandler(modelArtifacts)];
+ });
+ });
+ };
+ return PassthroughSaver;
+ }());
+ /**
+ * Creates an IOHandler that loads model artifacts from memory.
+ *
+ * When used in conjunction with `tf.loadLayersModel`, an instance of
+ * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.
+ *
+ * ```js
+ * const model = await tf.loadLayersModel(tf.io.fromMemory(
+ * modelTopology, weightSpecs, weightData));
+ * ```
+ *
+ * @param modelArtifacts a object containing model topology (i.e., parsed from
+ * the JSON format).
+ * @param weightSpecs An array of `WeightsManifestEntry` objects describing the
+ * names, shapes, types, and quantization of the weight data.
+ * @param weightData A single `ArrayBuffer` containing the weight data,
+ * concatenated in the order described by the weightSpecs.
+ * @param trainingConfig Model training configuration. Optional.
+ *
+ * @returns A passthrough `IOHandler` that simply loads the provided data.
+ */
+ function fromMemory(modelArtifacts, weightSpecs, weightData, trainingConfig) {
+ if (arguments.length === 1) {
+ var isModelArtifacts = modelArtifacts.modelTopology != null ||
+ modelArtifacts.weightSpecs != null;
+ if (isModelArtifacts) {
+ return new PassthroughLoader(modelArtifacts);
+ }
+ else {
+ // Legacy support: with only modelTopology.
+ // TODO(cais): Remove this deprecated API.
+ console.warn('Please call tf.io.fromMemory() with only one argument. ' +
+ 'The argument should be of type ModelArtifacts. ' +
+ 'The multi-argument signature of tf.io.fromMemory() has been ' +
+ 'deprecated and will be removed in a future release.');
+ return new PassthroughLoader({ modelTopology: modelArtifacts });
+ }
+ }
+ else {
+ // Legacy support.
+ // TODO(cais): Remove this deprecated API.
+ console.warn('Please call tf.io.fromMemory() with only one argument. ' +
+ 'The argument should be of type ModelArtifacts. ' +
+ 'The multi-argument signature of tf.io.fromMemory() has been ' +
+ 'deprecated and will be removed in a future release.');
+ return new PassthroughLoader({
+ modelTopology: modelArtifacts,
+ weightSpecs: weightSpecs,
+ weightData: weightData,
+ trainingConfig: trainingConfig
+ });
+ }
+ }
+ /**
+ * Creates an IOHandler that passes saved model artifacts to a callback.
+ *
+ * ```js
+ * function handleSave(artifacts) {
+ * // ... do something with the artifacts ...
+ * return {modelArtifactsInfo: {...}, ...};
+ * }
+ *
+ * const saveResult = model.save(tf.io.withSaveHandler(handleSave));
+ * ```
+ *
+ * @param saveHandler A function that accepts a `ModelArtifacts` and returns a
+ * `SaveResult`.
+ */
+ function withSaveHandler(saveHandler) {
+ return new PassthroughSaver(saveHandler);
+ }
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+
+ var io = {
+ __proto__: null,
+ browserFiles: browserFiles,
+ browserHTTPRequest: browserHTTPRequest,
+ concatenateArrayBuffers: concatenateArrayBuffers,
+ decodeWeights: decodeWeights,
+ encodeWeights: encodeWeights,
+ fromMemory: fromMemory,
+ getLoadHandlers: getLoadHandlers,
+ getModelArtifactsInfoForJSON: getModelArtifactsInfoForJSON,
+ getSaveHandlers: getSaveHandlers,
+ http: http,
+ isHTTPScheme: isHTTPScheme,
+ loadWeights: loadWeights,
+ registerLoadRouter: registerLoadRouter,
+ registerSaveRouter: registerSaveRouter,
+ weightsLoaderFactory: weightsLoaderFactory,
+ withSaveHandler: withSaveHandler,
+ copyModel: copyModel,
+ listModels: listModels,
+ moveModel: moveModel,
+ removeModel: removeModel
+ };
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Computes the dot product of two matrices, A * B. These must be matrices.
+ *
+ * ```js
+ * const a = tf.tensor2d([1, 2], [1, 2]);
+ * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
+ *
+ * a.matMul(b).print(); // or tf.matMul(a, b)
+ * ```
+ * @param a First matrix in dot product operation.
+ * @param b Second matrix in dot product operation.
+ * @param transposeA If true, `a` is transposed before multiplication.
+ * @param transposeB If true, `b` is transposed before multiplication.
+ *
+ * @doc {heading: 'Operations', subheading: 'Matrices'}
+ */
+ function matMul_(a, b, transposeA, transposeB) {
+ var _a;
+ if (transposeA === void 0) { transposeA = false; }
+ if (transposeB === void 0) { transposeB = false; }
+ var $a = convertToTensor(a, 'a', 'matMul');
+ var $b = convertToTensor(b, 'b', 'matMul');
+ _a = makeTypesMatch($a, $b), $a = _a[0], $b = _a[1];
+ var inputs = { a: $a, b: $b };
+ var attrs = { transposeA: transposeA, transposeB: transposeB };
+ return ENGINE.runKernel(BatchMatMul, inputs, attrs);
+ }
+ var matMul = op({ matMul_: matMul_ });
+
+ /**
+ * @license
+ * Copyright 2020 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Creates a one-hot `tf.Tensor`. The locations represented by `indices` take
+ * value `onValue` (defaults to 1), while all other locations take value
+ * `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank
+ * `R+1` with the last axis of size `depth`.
+ *
+ * ```js
+ * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();
+ * ```
+ *
+ * @param indices `tf.Tensor` of indices with dtype `int32`.
+ * @param depth The depth of the one hot dimension.
+ * @param onValue A number used to fill in the output when the index matches
+ * the location.
+ * @param offValue A number used to fill in the output when the index does
+ * not match the location.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ function oneHot_(indices, depth, onValue, offValue) {
+ if (onValue === void 0) { onValue = 1; }
+ if (offValue === void 0) { offValue = 0; }
+ if (depth < 2) {
+ throw new Error("Error in oneHot: depth must be >=2, but it is " + depth);
+ }
+ var $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');
+ var inputs = { indices: $indices };
+ var attrs = { depth: depth, onValue: onValue, offValue: offValue };
+ return ENGINE.runKernel(OneHot, inputs, attrs);
+ }
+ var oneHot = op({ oneHot_: oneHot_ });
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.
+ *
+ * The returned `tf.Tensor`'s dimension `i` will correspond to the input
+ * dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,
+ * where `n` is the rank of the input `tf.Tensor`. Hence by default, this
+ * operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.
+ *
+ * ```js
+ * const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);
+ *
+ * a.transpose().print(); // or tf.transpose(a)
+ * ```
+ *
+ * @param x The tensor to transpose.
+ * @param perm The permutation of the dimensions of a.
+ *
+ * @doc {heading: 'Operations', subheading: 'Matrices'}
+ */
+ function transpose_(x, perm) {
+ var $x = convertToTensor(x, 'x', 'transpose');
+ if (perm == null) {
+ perm = $x.shape.map(function (s, i) { return i; }).reverse();
+ }
+ assert($x.rank === perm.length, function () { return "Error in transpose: rank of input " + $x.rank + " " +
+ ("must match length of perm " + perm + "."); });
+ perm.forEach(function (axis) {
+ assert(axis >= 0 && axis < $x.rank, function () { return "All entries in 'perm' must be between 0 and " + ($x.rank - 1) +
+ (" but got " + perm); });
+ });
+ if ($x.rank <= 1) {
+ return $x.clone();
+ }
+ var inputs = { x: $x };
+ var attrs = { perm: perm };
+ return ENGINE.runKernel(Transpose, inputs, attrs);
+ }
+ var transpose = op({ transpose_: transpose_ });
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Computes the confusion matrix from true labels and predicted labels.
+ *
+ * ```js
+ * const labels = tf.tensor1d([0, 1, 2, 1, 0], 'int32');
+ * const predictions = tf.tensor1d([0, 2, 2, 1, 0], 'int32');
+ * const numClasses = 3;
+ * const out = tf.math.confusionMatrix(labels, predictions, numClasses);
+ * out.print();
+ * // Expected output matrix:
+ * // [[2, 0, 0],
+ * // [0, 1, 1],
+ * // [0, 0, 1]]
+ * ```
+ *
+ * @param labels The target labels, assumed to be 0-based integers
+ * for the classes. The shape is `[numExamples]`, where
+ * `numExamples` is the number of examples included.
+ * @param predictions The predicted classes, assumed to be
+ * 0-based integers for the classes. Must have the same shape as `labels`.
+ * @param numClasses Number of all classes, as an integer.
+ * Its value must be larger than the largest element in `labels` and
+ * `predictions`.
+ * @returns The confusion matrix as a int32-type 2D tensor. The value at
+ * row `r` and column `c` is the number of times examples of actual class
+ * `r` were predicted as class `c`.
+ *
+ * @doc {heading: 'Operations', subheading: 'Evaluation'}
+ */
+ function confusionMatrix_(labels, predictions, numClasses) {
+ var $labels = convertToTensor(labels, 'labels', 'confusionMatrix');
+ var $predictions = convertToTensor(predictions, 'predictions', 'confusionMatrix');
+ assert(numClasses == null || numClasses > 0 && Number.isInteger(numClasses), function () { return "If provided, numClasses must be a positive integer, " +
+ ("but got " + numClasses); });
+ assert($labels.rank === 1, function () { return "Expected the rank of labels to be 1, but got " + $labels.rank; });
+ assert($predictions.rank === 1, function () { return "Expected the rank of predictions to be 1, " +
+ ("but got " + $predictions.rank); });
+ assert($labels.shape[0] === $predictions.shape[0], function () { return "Mismatch in the number of examples: " +
+ ($labels.shape[0] + " vs. " + $predictions.shape[0] + ". ") +
+ "Labels and predictions should have the same number of elements."; });
+ assert(numClasses > 0 && Number.isInteger(numClasses), function () { return "numClasses is required to be a positive integer, but got " +
+ ("" + numClasses); });
+ // TODO(cais): In the future, if oneHot supports tensors inputs for
+ // `numClasses`, `confusionMatrix` can make `numClasses` optional.
+ var oneHotLabels = oneHot(cast($labels, 'int32'), numClasses);
+ var oneHotPredictions = oneHot(cast($predictions, 'int32'), numClasses);
+ var oneHotLabelsT = transpose(oneHotLabels);
+ var product = matMul(oneHotLabelsT, oneHotPredictions);
+ return cast(product, 'int32');
+ }
+ var confusionMatrix = op({ confusionMatrix_: confusionMatrix_ });
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+
+ var math = {
+ __proto__: null,
+ confusionMatrix: confusionMatrix
+ };
+
+ /**
+ * @license
+ * Copyright 2018 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ /**
+ * Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.
+ *
+ * The same functionality can be achieved with `tf.tensor`, but in general
+ * we recommend using `tf.tensor3d` as it makes the code more readable.
+ *
+ * ```js
+ * // Pass a nested array.
+ * tf.tensor3d([[[1], [2]], [[3], [4]]]).print();
+ * ```
+ * ```js
+ * // Pass a flat array and specify a shape.
+ * tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();
+ * ```
+ *
+ * @param values The values of the tensor. Can be nested array of numbers,
+ * or a flat array, or a `TypedArray`.
+ * @param shape The shape of the tensor. If not provided, it is inferred from
+ * `values`.
+ * @param dtype The data type.
+ *
+ * @doc {heading: 'Tensors', subheading: 'Creation'}
+ */
+ function tensor3d(values, shape, dtype) {
+ assertNonNull(values);
+ if (shape != null && shape.length !== 3) {
+ throw new Error('tensor3d() requires shape to have three numbers');
+ }
+ var inferredShape = inferShape(values, dtype);
+ if (inferredShape.length !== 3 && inferredShape.length !== 1) {
+ throw new Error('tensor3d() requires values to be number[][][] or flat/TypedArray');
+ }
+ if (inferredShape.length === 1 && shape == null) {
+ throw new Error('tensor3d() requires shape to be provided when `values` ' +
+ 'are a flat array');
+ }
+ return makeTensor(values, shape, inferredShape, dtype);
+ }
+
+ /**
+ * @license
+ * Copyright 2019 Google LLC. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * =============================================================================
+ */
+ var fromPixels2DContext;
+ /**
+ * Creates a `tf.Tensor` from an image.
+ *
+ * ```js
+ * const image = new ImageData(1, 1);
+ * image.data[0] = 100;
+ * image.data[1] = 150;
+ * image.data[2] = 200;
+ * image.data[3] = 255;
+ *
+ * tf.browser.fromPixels(image).print();
+ * ```
+ *
+ * @param pixels The input image to construct the tensor from. The
+ * supported image types are all 4-channel. You can also pass in an image
+ * object with following attributes:
+ * `{data: Uint8Array; width: number; height: number}`
+ * @param numChannels The number of channels of the output tensor. A
+ * numChannels value less than 4 allows you to ignore channels. Defaults to
+ * 3 (ignores alpha channel of input image).
+ *
+ * @returns A Tensor3D with the shape `[height, width, numChannels]`.
+ *
+ * @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}
+ */
+ function fromPixels_(pixels, numChannels) {
+ if (numChannels === void 0) { numChannels = 3; }
+ // Sanity checks.
+ if (numChannels > 4) {
+ throw new Error('Cannot construct Tensor with more than 4 channels from pixels.');
+ }
+ if (pixels == null) {
+ throw new Error('pixels passed to tf.browser.fromPixels() can not be null');
+ }
+ var isPixelData = false;
+ var isImageData = false;
+ var isVideo = false;
+ var isImage = false;
+ var isCanvasLike = false;
+ var isImageBitmap = false;
+ if (pixels.data instanceof Uint8Array) {
+ isPixelData = true;
+ }
+ else if (typeof (ImageData) !== 'undefined' && pixels instanceof ImageData) {
+ isImageData = true;
+ }
+ else if (typeof (HTMLVideoElement) !== 'undefined' &&
+ pixels instanceof HTMLVideoElement) {
+ isVideo = true;
+ }
+ else if (typeof (HTMLImageElement) !== 'undefined' &&
+ pixels instanceof HTMLImageElement) {
+ isImage = true;
+ // tslint:disable-next-line: no-any
+ }
+ else if (pixels.getContext != null) {
+ isCanvasLike = true;
+ }
+ else if (typeof (ImageBitmap) !== 'undefined' && pixels instanceof ImageBitmap) {
+ isImageBitmap = true;
+ }
+ else {
+ throw new Error('pixels passed to tf.browser.fromPixels() must be either an ' +
+ "HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData " +
+ "in browser, or OffscreenCanvas, ImageData in webworker" +
+ " or {data: Uint32Array, width: number, height: number}, " +
+ ("but was " + pixels.constructor.name));
+ }
+ if (isVideo) {
+ var HAVE_CURRENT_DATA_READY_STATE = 2;
+ if (isVideo &&
+ pixels.readyState <
+ HAVE_CURRENT_DATA_READY_STATE) {
+ throw new Error('The video element has not loaded data yet. Please wait for ' +
+ '`loadeddata` event on the