human/dist/demo-browser-index.js

4936 lines
1.8 MiB
JavaScript
Raw Normal View History

2020-11-20 14:53:40 +01:00
/*
Human library
homepage: <https://github.com/vladmandic/human>
author: <https://github.com/vladmandic>'
*/
2020-12-27 14:12:22 +01:00
var __create=Object.create,__defProp=Object.defineProperty,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__markAsModule=target=>__defProp(target,"__esModule",{value:!0}),__commonJS=(callback,module)=>()=>(module||(module={exports:{}},callback(module.exports,module)),module.exports),__export=(target,all2)=>{__markAsModule(target);for(var name in all2)__defProp(target,name,{get:all2[name],enumerable:!0})},__exportStar=(target,module,desc)=>{if(__markAsModule(target),module&&typeof module=="object"||typeof module=="function")for(let key of __getOwnPropNames(module))!__hasOwnProp.call(target,key)&&key!=="default"&&__defProp(target,key,{get:()=>module[key],enumerable:!(desc=__getOwnPropDesc(module,key))||desc.enumerable});return target},__toModule=module=>module&&module.__esModule?module:__exportStar(__defProp(module!=null?__create(__getProtoOf(module)):{},"default",{value:module,enumerable:!0}),module),require_blazeface=__commonJS(exports=>{var NUM_LANDMARKS=6;function generateAnchors(inputSize){let spec={strides:[inputSize/16,inputSize/8],anchors:[2,6]},anchors=[];for(let i=0;i<spec.strides.length;i++){let stride=spec.strides[i],gridRows=Math.floor((inputSize+stride-1)/stride),gridCols=Math.floor((inputSize+stride-1)/stride),anchorsNum=spec.anchors[i];for(let gridY=0;gridY<gridRows;gridY++){let anchorY=stride*(gridY+.5);for(let gridX=0;gridX<gridCols;gridX++){let anchorX=stride*(gridX+.5);for(let n=0;n<anchorsNum;n++)anchors.push([anchorX,anchorY])}}}return anchors}var disposeBox=box=>{box.startEndTensor.dispose(),box.startPoint.dispose(),box.endPoint.dispose()},createBox=startEndTensor=>({startEndTensor,startPoint:slice(startEndTensor,[0,0],[-1,2]),endPoint:slice(startEndTensor,[0,2],[-1,2])}),scaleBox=(box,factors)=>{let starts=mul(box.startPoint,factors),ends=mul(box.endPoint,factors),newCoordinates=concat2d([starts,ends],1);return createBox(newCoordinates)};function decodeBounds(boxOutputs,anchors,inputSize){let boxStarts=slice(boxOutputs,[0,1],[-1,2]),centers=add2(boxStarts,anchors),boxSizes=slice(boxOutputs,[0,3],[-1,2]),boxSizesNormalized=div(boxSizes,inputSize),centersNormalized=div(centers,inputSize),halfBoxSize=div(boxSizesNormalized,2),starts=sub(centersNormalized,halfBoxSize),ends=add2(centersNormalized,halfBoxSize),startNormalized=mul(starts,inputSize),endNormalized=mul(ends,inputSize),concatAxis=1;return concat2d([startNormalized,endNormalized],concatAxis)}function scaleBoxFromPrediction(face3,scaleFactor){return tidy(()=>{let box=face3.box?face3.box:face3;return scaleBox(box,scaleFactor).startEndTensor.squeeze()})}var BlazeFaceModel=class{constructor(model2,config2){this.blazeFaceModel=model2,this.width=config2.face.detector.inputSize,this.height=config2.face.detector.inputSize,this.anchorsData=generateAnchors(config2.face.detector.inputSize),this.anchors=tensor2d(this.anchorsData),this.inputSize=tensor1d([this.width,this.height]),this.config=config2,this.scaleFaces=.8}async getBoundingBoxes(inputImage){if(!inputImage||inputImage.isDisposedInternal||inputImage.shape.length!==4||inputImage.shape[1]<1||inputImage.shape[2]<1)return null;let[detectedOutputs,boxes,scores]=tidy(()=>{let resizedImage=inputImage.resizeBilinear([this.width,this.height]),normalizedImage=sub(resizedImage.div(127.5),1),batchedPrediction=this.blazeFaceModel.predict(normalizedImage),prediction;if(Array.isArray(batchedPrediction)){let sorted=batchedPrediction.sort((a,b)=>a.size-b.size),concat384=concat([sorted[0],sorted[2]],2),concat512=concat([sorted[1],sorted[3]],2),concat2=concat([concat512,concat384],1);prediction=concat2.squeeze(0)}else prediction=batchedPrediction.squeeze();let decodedBounds=decodeBounds(prediction,this.anchors,this.inputSize),logits=slice(prediction,[0,0],[-1,1]),scoresOut=sigmoid(logits).squeeze();return[prediction,decodedBounds,scoresOut]}),boxIndicesTensor=await image.nonMaxSuppressionAsync(boxes,scores,this.config.face.detector.maxFaces,this.config.face.detector.iouThreshold,this.config
`),SHADER.FRAGMENT_IDENTITY=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","void main(void) {","gl_FragColor = texture2D(texture, vUv);","}"].join(`
2020-11-25 15:13:19 +01:00
`);let _filter={};_filter.colorMatrix=function(matrix){let m=new Float32Array(matrix);m[4]/=255,m[9]/=255,m[14]/=255,m[19]/=255;let shader=m[18]===1&&m[3]===0&&m[8]===0&&m[13]===0&&m[15]===0&&m[16]===0&&m[17]===0&&m[19]===0?_filter.colorMatrix.SHADER.WITHOUT_ALPHA:_filter.colorMatrix.SHADER.WITH_ALPHA,program=_compileShader(shader);gl.uniform1fv(program.uniform.m,m),_draw()},_filter.colorMatrix.SHADER={},_filter.colorMatrix.SHADER.WITH_ALPHA=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform float m[20];","void main(void) {","vec4 c = texture2D(texture, vUv);","gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];","gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];","gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];","gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];","}"].join(`
`),_filter.colorMatrix.SHADER.WITHOUT_ALPHA=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform float m[20];","void main(void) {","vec4 c = texture2D(texture, vUv);","gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];","gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];","gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];","gl_FragColor.a = c.a;","}"].join(`
2020-11-25 15:13:19 +01:00
`),_filter.brightness=function(brightness){let b=(brightness||0)+1;_filter.colorMatrix([b,0,0,0,0,0,b,0,0,0,0,0,b,0,0,0,0,0,1,0])},_filter.saturation=function(amount){let x=(amount||0)*2/3+1,y=(x-1)*-.5;_filter.colorMatrix([x,y,y,0,0,y,x,y,0,0,y,y,x,0,0,0,0,0,1,0])},_filter.desaturate=function(){_filter.saturation(-1)},_filter.contrast=function(amount){let v=(amount||0)+1,o=-128*(v-1);_filter.colorMatrix([v,0,0,0,o,0,v,0,0,o,0,0,v,0,o,0,0,0,1,0])},_filter.negative=function(){_filter.contrast(-2)},_filter.hue=function(rotation){rotation=(rotation||0)/180*Math.PI;let cos2=Math.cos(rotation),sin2=Math.sin(rotation),lumR=.213,lumG=.715,lumB=.072;_filter.colorMatrix([lumR+cos2*(1-lumR)+sin2*-lumR,lumG+cos2*-lumG+sin2*-lumG,lumB+cos2*-lumB+sin2*(1-lumB),0,0,lumR+cos2*-lumR+sin2*.143,lumG+cos2*(1-lumG)+sin2*.14,lumB+cos2*-lumB+sin2*-.283,0,0,lumR+cos2*-lumR+sin2*-(1-lumR),lumG+cos2*-lumG+sin2*lumG,lumB+cos2*(1-lumB)+sin2*lumB,0,0,0,0,0,1,0])},_filter.desaturateLuminance=function(){_filter.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},_filter.sepia=function(){_filter.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},_filter.brownie=function(){_filter.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},_filter.vintagePinhole=function(){_filter.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},_filter.kodachrome=function(){_filter.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},_filter.technicolor=function(){_filter.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},_filter.polaroid=function(){_filter.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},_filter.shiftToBGR=function(){_filter.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},_filter.convolution=function(matrix){let m=new Float32Array(matrix),pixelSizeX=1/_width,pixelSizeY=1/_height,program=_compileShader(_filter.convolution.SHADER);gl.uniform1fv(program.uniform.m,m),gl.uniform2f(program.uniform.px,pixelSizeX,pixelSizeY),_draw()},_filter.convolution.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","uniform float m[9];","void main(void) {","vec4 c11 = texture2D(texture, vUv - px);","vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));","vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));","vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );","vec4 c22 = texture2D(texture, vUv);","vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );","vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );","vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );","vec4 c33 = texture2D(texture, vUv + px );","gl_FragColor = ","c11 * m[0] + c12 * m[1] + c22 * m[2] +","c21 * m[3] + c22 * m[4] + c23 * m[5] +","c31 * m[6] + c32 * m[7] + c33 * m[8];","gl_FragColor.a = c22.a;","}"].join(`
`),_filter.detectEdges=function(){_filter.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},_filter.sobelX=function(){_filter.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},_filter.sobelY=function(){_filter.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},_filter.sharpen=function(amount){let a=amount||1;_filter.convolution.call(this,[0,-1*a,0,-1*a,1+4*a,-1*a,0,-1*a,0])},_filter.emboss=function(size){let s=size||1;_filter.convolution.call(this,[-2*s,-1*s,0,-1*s,1,1*s,0,1*s,2*s])},_filter.blur=function(size){let blurSizeX=size/7/_width,blurSizeY=size/7/_height,program=_compileShader(_filter.blur.SHADER);gl.uniform2f(program.uniform.px,0,blurSizeY),_draw(DRAW.INTERMEDIATE),gl.uniform2f(program.uniform.px,blurSizeX,0),_draw()},_filter.blur.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","void main(void) {","gl_FragColor = vec4(0.0);","gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;","gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv )*0.159576912161;","gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;","}"].join(`
`),_filter.pixelate=function(size){let blurSizeX=size/_width,blurSizeY=size/_height,program=_compileShader(_filter.pixelate.SHADER);gl.uniform2f(program.uniform.size,blurSizeX,blurSizeY),_draw()},_filter.pixelate.SHADER=["precision highp float;","varying vec2 vUv;","uniform vec2 size;","uniform sampler2D texture;","vec2 pixelate(vec2 coord, vec2 size) {","return floor( coord / size ) * size;","}","void main(void) {","gl_FragColor = vec4(0.0);","vec2 coord = pixelate(vUv, size);","gl_FragColor += texture2D(texture, coord);","}"].join(`
2020-12-27 14:12:22 +01:00
`)};exports.Canvas=WebGLImageFilter}),require_image=__commonJS(exports=>{var fxImage=__toModule(require_imagefx()),inCanvas=null,outCanvas=null;function process3(input2,config2){let tensor;if(input2 instanceof Tensor)tensor=clone(input2);else{let originalWidth=input2.naturalWidth||input2.videoWidth||input2.width||input2.shape&&input2.shape[1]>0,originalHeight=input2.naturalHeight||input2.videoHeight||input2.height||input2.shape&&input2.shape[2]>0,targetWidth=originalWidth,targetHeight=originalHeight;if(config2.filter.width>0?targetWidth=config2.filter.width:config2.filter.height>0&&(targetWidth=originalWidth*(config2.filter.height/originalHeight)),config2.filter.height>0?targetHeight=config2.filter.height:config2.filter.width>0&&(targetHeight=originalHeight*(config2.filter.width/originalWidth)),!targetWidth||!targetHeight)return log("Human: invalid input",input2),null;(!inCanvas||inCanvas.width!==targetWidth||inCanvas.height!==targetHeight)&&(inCanvas=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(targetWidth,targetHeight):document.createElement("canvas"),inCanvas.width!==targetWidth&&(inCanvas.width=targetWidth),inCanvas.height!==targetHeight&&(inCanvas.height=targetHeight));let ctx=inCanvas.getContext("2d");if(input2 instanceof ImageData?ctx.putImageData(input2,0,0):ctx.drawImage(input2,0,0,originalWidth,originalHeight,0,0,inCanvas.width,inCanvas.height),config2.filter.enabled){if((!this.fx||!outCanvas||inCanvas.width!==outCanvas.width||inCanvas.height!==outCanvas.height)&&(outCanvas=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(inCanvas.width,inCanvas.height):document.createElement("canvas"),outCanvas.width!==inCanvas.width&&(outCanvas.width=inCanvas.width),outCanvas.height!==inCanvas.height&&(outCanvas.height=inCanvas.height),this.fx=ENV.flags.IS_BROWSER?new fxImage.Canvas({canvas:outCanvas}):null),!this.fx)return inCanvas;this.fx.reset(),this.fx.addFilter("brightness",config2.filter.brightness),config2.filter.contrast!==0&&this.fx.addFilter("contrast",config2.filter.contrast),config2.filter.sharpness!==0&&this.fx.addFilter("sharpen",config2.filter.sharpness),config2.filter.blur!==0&&this.fx.addFilter("blur",config2.filter.blur),config2.filter.saturation!==0&&this.fx.addFilter("saturation",config2.filter.saturation),config2.filter.hue!==0&&this.fx.addFilter("hue",config2.filter.hue),config2.filter.negative&&this.fx.addFilter("negative"),config2.filter.sepia&&this.fx.addFilter("sepia"),config2.filter.vintage&&this.fx.addFilter("brownie"),config2.filter.sepia&&this.fx.addFilter("sepia"),config2.filter.kodachrome&&this.fx.addFilter("kodachrome"),config2.filter.technicolor&&this.fx.addFilter("technicolor"),config2.filter.polaroid&&this.fx.addFilter("polaroid"),config2.filter.pixelate!==0&&this.fx.addFilter("pixelate",config2.filter.pixelate),this.fx.apply(inCanvas)}else outCanvas=inCanvas;let pixels;if(outCanvas.data){let shape=[outCanvas.height,outCanvas.width,3];pixels=tensor3d(outCanvas.data,shape,"int32")}else if(config2.backend==="webgl"||outCanvas instanceof ImageData)pixels=browser_exports.fromPixels(outCanvas);else{let tempCanvas=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(targetWidth,targetHeight):document.createElement("canvas");tempCanvas.width=targetWidth,tempCanvas.height=targetHeight;let tempCtx=tempCanvas.getContext("2d");tempCtx==null||tempCtx.drawImage(outCanvas,0,0);let data2=tempCtx==null?void 0:tempCtx.getImageData(0,0,targetWidth,targetHeight);pixels=browser_exports.fromPixels(data2)}let casted=pixels.toFloat();tensor=casted.expandDims(0),pixels.dispose(),casted.dispose()}return{tensor,canvas:config2.filter.return?outCanvas:null}}exports.process=process3});function log(...msg){let dt=new Date,ts=`${dt.getHours().toString().padStart(2,"0")}:${dt.getMinutes().toString().padStart(2,"0")}:${dt.getSeconds().toString().padStart(2,"0")}.${dt.getMilliseconds().toString().padStart(3,"0")}`;msg&&console.log(ts,"Human:",...msg)}var tfjs_esm_exports={};__export(tfjs_esm_exports,{Abs:()=>Abs,Acos:()=>Acos,Acosh:()=>Acosh,AdadeltaOptimizer:()=>AdadeltaOptimizer,AdagradOptimizer:()=>
`)),lines.join(`
2020-12-22 18:34:47 +01:00
`)}function computeMaxSizePerColumn(vals,shape,dtype,strides){let n=sizeFromShape(shape),numCols=strides[strides.length-1],padPerCol=new Array(numCols).fill(0),rank=shape.length,valuesOrTuples=dtype==="complex64"?createComplexTuples(vals):vals;if(rank>1)for(let row=0;row<n/numCols;row++){let offset=row*numCols;for(let j=0;j<numCols;j++)padPerCol[j]=Math.max(padPerCol[j],valToString(valuesOrTuples[offset+j],0,dtype).length)}return padPerCol}function valToString(val,pad10,dtype){let valStr;return Array.isArray(val)?valStr=`${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`:isString(val)?valStr=`'${val}'`:dtype==="bool"?valStr=boolNumToString(val):valStr=parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString(),rightPad(valStr,pad10)}function boolNumToString(v){return v===0?"false":"true"}function subTensorToString(vals,shape,dtype,strides,padPerCol,isLast=!0){let storagePerElement=dtype==="complex64"?2:1,size=shape[0],rank=shape.length;if(rank===0){if(dtype==="complex64"){let complexTuple=createComplexTuples(vals);return[valToString(complexTuple[0],0,dtype)]}return dtype==="bool"?[boolNumToString(vals[0])]:[vals[0].toString()]}if(rank===1){if(size>FORMAT_LIMIT_NUM_VALS){let firstValsSize=FORMAT_NUM_FIRST_LAST_VALS*storagePerElement,firstVals=Array.from(vals.slice(0,firstValsSize)),lastVals=Array.from(vals.slice((size-FORMAT_NUM_FIRST_LAST_VALS)*storagePerElement,size*storagePerElement));return dtype==="complex64"&&(firstVals=createComplexTuples(firstVals),lastVals=createComplexTuples(lastVals)),["["+firstVals.map((x,i)=>valToString(x,padPerCol[i],dtype)).join(", ")+", ..., "+lastVals.map((x,i)=>valToString(x,padPerCol[size-FORMAT_NUM_FIRST_LAST_VALS+i],dtype)).join(", ")+"]"]}let displayVals=dtype==="complex64"?createComplexTuples(vals):Array.from(vals);return["["+displayVals.map((x,i)=>valToString(x,padPerCol[i],dtype)).join(", ")+"]"]}let subshape=shape.slice(1),substrides=strides.slice(1),stride=strides[0]*storagePerElement,lines=[];if(size>FORMAT_LIMIT_NUM_VALS){for(let i=0;i<FORMAT_NUM_FIRST_LAST_VALS;i++){let start=i*stride,end=start+stride;lines.push(...subTensorToString(vals.slice(start,end),subshape,dtype,substrides,padPerCol,!1))}lines.push("...");for(let i=size-FORMAT_NUM_FIRST_LAST_VALS;i<size;i++){let start=i*stride,end=start+stride;lines.push(...subTensorToString(vals.slice(start,end),subshape,dtype,substrides,padPerCol,i===size-1))}}else for(let i=0;i<size;i++){let start=i*stride,end=start+stride;lines.push(...subTensorToString(vals.slice(start,end),subshape,dtype,substrides,padPerCol,i===size-1))}let sep=rank===2?",":"";lines[0]="["+lines[0]+sep;for(let i=1;i<lines.length-1;i++)lines[i]=" "+lines[i]+sep;let newLineSep=`,
`;for(let i=2;i<rank;i++)newLineSep+=`
2020-12-22 18:34:47 +01:00
`;return lines[lines.length-1]=" "+lines[lines.length-1]+"]"+(isLast?"":newLineSep),lines}function createComplexTuples(vals){let complexTuples=[];for(let i=0;i<vals.length;i+=2)complexTuples.push([vals[i],vals[i+1]]);return complexTuples}var TensorBuffer=class{constructor(shape,dtype,values){if(this.dtype=dtype,this.shape=shape.slice(),this.size=sizeFromShape(shape),values!=null){let n=values.length;assert(n===this.size,()=>`Length of values '${n}' 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)}set(value,...locs){locs.length===0&&(locs=[0]),assert(locs.length===this.rank,()=>`The number of provided coordinates (${locs.length}) must match the rank (${this.rank})`);let index=this.locToIndex(locs);this.values[index]=value}get(...locs){locs.length===0&&(locs=[0]);let i=0;for(let loc of locs){if(loc<0||loc>=this.shape[i]){let msg=`Requested out of range element at ${locs}. Buffer shape=${this.shape}`;throw new Error(msg)}i++}let index=locs[locs.length-1];for(let i2=0;i2<locs.length-1;++i2)index+=this.strides[i2]*locs[i2];return this.values[index]}locToIndex(locs){if(this.rank===0)return 0;if(this.rank===1)return locs[0];let index=locs[locs.length-1];for(let i=0;i<locs.length-1;++i)index+=this.strides[i]*locs[i];return index}indexToLoc(index){if(this.rank===0)return[];if(this.rank===1)return[index];let locs=new Array(this.shape.length);for(let i=0;i<locs.length-1;++i)locs[i]=Math.floor(index/this.strides[i]),index-=locs[i]*this.strides[i];return locs[locs.length-1]=index,locs}get rank(){return this.shape.length}toTensor(){return trackerFn().makeTensor(this.values,this.shape,this.dtype)}},trackerFn=null,opHandler=null,deprecationWarningFn=null;function setTensorTracker(fn){trackerFn=fn}function setOpHandler(handler){opHandler=handler}function setDeprecationWarningFn(fn){deprecationWarningFn=fn}var Tensor=class{constructor(shape,dtype,dataId,id){this.kept=!1,this.isDisposedInternal=!1,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"}get rank(){return this.shape.length}async buffer(){let vals=await this.data();return opHandler.buffer(this.shape,this.dtype,vals)}bufferSync(){return opHandler.buffer(this.shape,this.dtype,this.dataSync())}async array(){let vals=await this.data();return toNestedArray(this.shape,vals)}arraySync(){return toNestedArray(this.shape,this.dataSync())}async data(){this.throwIfDisposed();let data2=trackerFn().read(this.dataId);if(this.dtype==="string"){let bytes=await data2;try{return bytes.map(b=>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 data2}dataSync(){this.throwIfDisposed();let data2=trackerFn().readSync(this.dataId);if(this.dtype==="string")try{return data2.map(b=>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 data2}async bytes(){this.throwIfDisposed();let data2=await trackerFn().read(this.dataId);return this.dtype==="string"?data2:new Uint8Array(data2.buffer)}dispose(){if(this.isDisposed)return;trackerFn().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(verbose=!1){return opHandler.print(this,verbose)}clone(){return this.throwIfDisposed(),opHandler.clone(this)}toString(verbose=!1){let vals=this.dataSync();return tensorToString(vals,this.shape,this.dtype,verbose)}cast(dtype){return this.throwIfDisposed(),opHandler.cast(this,dtype)}variable(trainable=!0,name,dtype){return this.throwIfDisposed(),trackerFn().makeVariable(thi
Manifest JSON has weights with names: ${allManifestWeightNames.join(", ")}.`)}let groupIndicesToFetch=groupIndicesToFetchMap.reduce((accumulator,shouldFetch,i)=>(shouldFetch&&accumulator.push(i),accumulator),[]),fetchUrls=[];groupIndicesToFetch.forEach(i=>{manifest[i].paths.forEach(filepath=>{let fetchUrl=filePathPrefix+(filePathPrefix.endsWith("/")?"":"/")+filepath;fetchUrls.push(fetchUrl)})});let buffers=await fetchWeightsFunction(fetchUrls),weightsTensorMap={},bufferIndexOffset=0;return groupIndicesToFetch.forEach(i=>{let numBuffers=manifest[i].paths.length,groupBytes=0;for(let i2=0;i2<numBuffers;i2++)groupBytes+=buffers[bufferIndexOffset+i2].byteLength;let groupBuffer=new ArrayBuffer(groupBytes),groupByteBuffer=new Uint8Array(groupBuffer),groupBufferOffset=0;for(let i2=0;i2<numBuffers;i2++){let buffer10=new Uint8Array(buffers[bufferIndexOffset+i2]);groupByteBuffer.set(buffer10,groupBufferOffset),groupBufferOffset+=buffer10.byteLength}let weightsEntries=groupWeightsToFetch[i];weightsEntries.forEach(weightsEntry=>{let byteBuffer=groupBuffer.slice(weightsEntry.groupOffset,weightsEntry.groupOffset+weightsEntry.sizeBytes),nameToTensorMap=decodeWeights(byteBuffer,[weightsEntry.manifestEntry]);for(let name in nameToTensorMap)weightsTensorMap[name]=nameToTensorMap[name]}),bufferIndexOffset+=numBuffers}),weightsTensorMap}}var OCTET_STREAM_MIME_TYPE="application/octet-stream",JSON_TYPE="application/json",HTTPRequest=class{constructor(path,loadOptions){if(this.DEFAULT_METHOD="POST",loadOptions==null&&(loadOptions={}),this.weightPathPrefix=loadOptions.weightPathPrefix,this.onProgress=loadOptions.onProgress,this.weightUrlConverter=loadOptions.weightUrlConverter,loadOptions.fetchFunc!=null?(assert(typeof loadOptions.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=loadOptions.fetchFunc):this.fetch=env().platform.fetch,assert(path!=null&&path.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(path)&&assert(path.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${path.length}).`),this.path=path,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||{}}async save(modelArtifacts){if(modelArtifacts.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let init2=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);init2.body=new FormData;let weightsManifest=[{paths:["./model.weights.bin"],weights:modelArtifacts.weightSpecs}],modelTopologyAndWeightManifest={modelTopology:modelArtifacts.modelTopology,format:modelArtifacts.format,generatedBy:modelArtifacts.generatedBy,convertedBy:modelArtifacts.convertedBy,userDefinedMetadata:modelArtifacts.userDefinedMetadata,weightsManifest};init2.body.append("model.json",new Blob([JSON.stringify(modelTopologyAndWeightManifest)],{type:JSON_TYPE}),"model.json"),modelArtifacts.weightData!=null&&init2.body.append("model.weights.bin",new Blob([modelArtifacts.weightData],{type:OCTET_STREAM_MIME_TYPE}),"model.weights.bin");let response=await this.fetch(this.path,init2);if(response.ok)return{modelArtifactsInfo:getModelArtifactsInfoForJSON(modelArtifacts),responses:[response]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${response.status}.`)}async load(){let modelConfigRequest=await this.fetch(this.path,this.requestInit);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.`);let modelConfig;try{modelConfig=await modelConfigRequest.json()}catch(e){let message=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?message+=" Your path contains a .pb file extension. Support for .pb models have been rem
2020-11-16 21:51:46 +01:00
Actual: ${actualFlat}.
2020-11-25 15:13:19 +01:00
Expected: ${expectedFlat}.`);for(let i=0;i<expectedFlat.length;++i){let a=actualFlat[i],e=expectedFlat[i];if(!predicate(a,e))throw new Error(`Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${e}.
2020-11-16 21:51:46 +01:00
Actual: ${actualFlat}.
2020-12-22 18:34:47 +01:00
Expected: ${expectedFlat}.`)}}function expectPromiseToFail(fn,done){fn().then(()=>done.fail(),()=>done())}function expectArraysEqual(actual,expected){let exp12=typeof expected=="string"||typeof expected=="number"||typeof expected=="boolean"?[expected]:expected;return isString(actual)||isString(actual[0])||isString(expected)||isString(expected[0])?expectArraysPredicate(actual,exp12,(a,b)=>a==b):expectArraysPredicate(actual,expected,(a,b)=>areClose(a,b,0))}function expectNumbersClose(a,e,epsilon3){if(epsilon3==null&&(epsilon3=testEpsilon()),!areClose(a,e,epsilon3))throw new Error(`Numbers differ: actual === ${a}, expected === ${e}`)}function areClose(a,e,epsilon3){return!isFinite(a)&&!isFinite(e)?!0:!(isNaN(a)||isNaN(e)||Math.abs(a-e)>epsilon3)}function expectValuesInRange(actual,low,high){for(let i=0;i<actual.length;i++)if(actual[i]<low||actual[i]>high)throw new Error(`Value out of range:${actual[i]} low: ${low}, high: ${high}`)}function expectArrayBuffersEqual(actual,expected){expect(new Float32Array(actual)).toEqual(new Float32Array(expected))}var version6="2.7.0";function enableProdMode(){env().set("PROD",!0)}function enableDebugMode(){env().set("DEBUG",!0)}function disableDeprecationWarnings(){env().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function deprecationWarn(msg){env().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(msg+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}setDeprecationWarningFn(deprecationWarn);function disposeVariables(){ENGINE.disposeVariables()}function engine15(){return ENGINE}function memory(){return ENGINE.memory()}function profile(f){return ENGINE.profile(f)}function tidy(nameOrFn,fn){return ENGINE.tidy(nameOrFn,fn)}function dispose(container2){let tensors=getTensorsInContainer(container2);tensors.forEach(tensor167=>tensor167.dispose())}function keep(result){return ENGINE.keep(result)}function time(f){return ENGINE.time(f)}function setBackend(backendName){return ENGINE.setBackend(backendName)}function ready(){return ENGINE.ready()}function getBackend(){return ENGINE.backendName}function removeBackend(name){ENGINE.removeBackend(name)}function findBackend(name){return ENGINE.findBackend(name)}function findBackendFactory(name){return ENGINE.findBackendFactory(name)}function registerBackend(name,factory,priority=1){return ENGINE.registerBackend(name,factory,priority)}function backend2(){return ENGINE.backend}function setPlatform(platformName,platform){env().setPlatform(platformName,platform)}function add_(a,b){let $a=convertToTensor(a,"a","add"),$b=convertToTensor(b,"b","add");[$a,$b]=makeTypesMatch($a,$b);let forward=(backend3,save)=>{let res=backend3.add($a,$b);return save([$a,$b]),res},inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,Add)}var add2=op({add_});function floorDiv_(a,b){let $a=convertToTensor(a,"a","floorDiv"),$b=convertToTensor(b,"b","floorDiv");[$a,$b]=makeTypesMatch($a,$b);let forward=(backend3,save)=>{let res=backend3.floorDiv($a,$b);return save([$a,$b]),res},inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,FloorDiv)}var floorDiv=op({floorDiv_});function div_(a,b){let $a=convertToTensor(a,"a","div"),$b=convertToTensor(b,"b","div");if([$a,$b]=makeTypesMatch($a,$b),$a.dtype==="int32"&&$b.dtype==="int32")return floorDiv($a,$b);let forward=(backend3,save)=>{let res=backend3.realDivide($a,$b);return save([$a,$b]),res},inputs={a:$a,b:$b},attrs={};return ENGINE.runKernelFunc(forward,inputs,null,Div,attrs)}var div=op({div_});function mul_(a,b){let $a=convertToTensor(a,"a","mul"),$b=convertToTensor(b,"b","mul");[$a,$b]=makeTypesMatch($a,$b);let forward=(backend3,save)=>{let res=backend3.multiply($a,$b);return save([$a,$b]),res},inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,Multiply)}var mul=op({mul_});function abs_(x){let $x=convertToTensor(x,"x","abs"),inputs={x:$x};return ENGINE.runKernelFunc((backend3,save)=>(save([$x]),$x.dtype==="complex64"?backend3.complexAbs($x):backend3.abs($x)),inputs,null,Abs)}var abs=op({abs_});fun
with dtype ${tensor167.dtype}. `)});let forward=(backend3,save)=>{let $axis=parseAxisParam(axis,$tensors[0].shape)[0],outShape=computeOutShape2($tensors.map(t=>t.shape),$axis);if(sizeFromShape(outShape)===0)return tensor4([],outShape);if($tensors=$tensors.filter(t=>t.size>0),$tensors.length===1)return $tensors[0];let shapes=$tensors.map(t=>t.shape);assertParamsConsistent(shapes,$axis);let res=backend3.concat($tensors,$axis);return save($tensors),res},inputs=$tensors,attr={axis};return ENGINE.runKernelFunc(forward,inputs,null,Concat,attr)}var concat=op({concat_});function sigmoid_(x){let $x=convertToTensor(x,"x","sigmoid"),inputs={x:$x};return ENGINE.runKernelFunc((backend3,save)=>{let res=backend3.sigmoid($x);return save([res]),res},inputs,null,Sigmoid)}var sigmoid=op({sigmoid_});function slice_(x,begin,size){let $x=convertToTensor(x,"x","slice");if($x.rank===0)throw new Error("Slicing scalar is not possible");let forward=(backend3,save)=>{let[begin_,size_]=parseSliceParams($x,begin,size);return assertParamsValid($x,begin_,size_),save([$x]),backend3.slice($x,begin_,size_)},inputs={x:$x},attrs={begin,size};return ENGINE.runKernelFunc(forward,inputs,null,Slice,attrs)}var slice=op({slice_});function tanh_(x){let $x=convertToTensor(x,"x","tanh"),inputs={x:$x};return ENGINE.runKernelFunc((backend3,save)=>{let y=backend3.tanh($x);return save([y]),y},inputs,null,Tanh)}var tanh2=op({tanh_});function basicLSTMCell_(forgetBias,lstmKernel,lstmBias,data2,c,h){let $forgetBias=convertToTensor(forgetBias,"forgetBias","basicLSTMCell"),$lstmKernel=convertToTensor(lstmKernel,"lstmKernel","basicLSTMCell"),$lstmBias=convertToTensor(lstmBias,"lstmBias","basicLSTMCell"),$data=convertToTensor(data2,"data","basicLSTMCell"),$c=convertToTensor(c,"c","basicLSTMCell"),$h=convertToTensor(h,"h","basicLSTMCell"),combined=concat([$data,$h],1),weighted=matMul(combined,$lstmKernel),res=add2(weighted,$lstmBias),batchSize=res.shape[0],sliceCols=res.shape[1]/4,sliceSize=[batchSize,sliceCols],i=slice(res,[0,0],sliceSize),j=slice(res,[0,sliceCols],sliceSize),f=slice(res,[0,sliceCols*2],sliceSize),o=slice(res,[0,sliceCols*3],sliceSize),newC=add2(mul(sigmoid(i),tanh2(j)),mul($c,sigmoid(add2($forgetBias,f)))),newH=mul(tanh2(newC),sigmoid(o));return[newC,newH]}var basicLSTMCell=op({basicLSTMCell_});function batchToSpaceND_(x,blockShape,crops){let $x=convertToTensor(x,"x","batchToSpaceND"),prod4=blockShape.reduce((a,b)=>a*b);assert($x.rank>=1+blockShape.length,()=>`input rank is ${$x.rank} but should be > than blockShape.length ${blockShape.length}`),assert(crops.length===blockShape.length,()=>`crops.length is ${crops.length} but should be equal to blockShape.length ${blockShape.length}`),assert($x.shape[0]%prod4===0,()=>`input tensor batch is ${$x.shape[0]} but is not divisible by the product of the elements of blockShape ${blockShape.join(" * ")} === ${prod4}`);let forward=backend3=>backend3.batchToSpaceND($x,blockShape,crops),inputs={x:$x},attrs={blockShape,crops};return ENGINE.runKernelFunc(forward,inputs,null,BatchToSpaceND,attrs)}var batchToSpaceND=op({batchToSpaceND_});function xAs4D(x){let x4D;return x.rank===0||x.rank===1?x4D=reshape(x,[1,1,1,x.size]):x.rank===2?x4D=reshape(x,[1,1,x.shape[0],x.shape[1]]):x.rank===3?x4D=reshape(x,[1,x.shape[0],x.shape[1],x.shape[2]]):x4D=x,x4D}function batchNorm_(x,mean6,variance,offset,scale2,varianceEpsilon){varianceEpsilon==null&&(varianceEpsilon=.001);let $x=convertToTensor(x,"x","batchNorm"),$mean=convertToTensor(mean6,"mean","batchNorm"),$variance=convertToTensor(variance,"variance","batchNorm"),$scale;scale2!=null&&($scale=convertToTensor(scale2,"scale","batchNorm"));let $offset;offset!=null&&($offset=convertToTensor(offset,"offset","batchNorm")),assert($mean.rank===$variance.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),assert($offset==null||$mean.rank===$offset.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),assert($scale==null||$mean.rank===$scale.rank,()=>"Batch normalization gradient requires mean and scale to have equ
2020-11-16 21:51:46 +01:00
${inputHeight} and ${blockSize} for depthToSpace with input shape
${$x.shape}`),assert(inputWidth*blockSize>=0,()=>`Negative dimension size caused by overflow when multiplying
2020-11-16 21:51:46 +01:00
${inputWidth} and ${blockSize} for depthToSpace with input shape
2020-12-22 18:34:47 +01:00
${$x.shape}`),assert(inputDepth%(blockSize*blockSize)===0,()=>`Dimension size must be evenly divisible by ${blockSize*blockSize} but is ${inputDepth} for depthToSpace with input shape ${$x.shape}`);let forward=backend3=>backend3.depthToSpace($x,blockSize,dataFormat),inputs={x:$x},attrs={blockSize,dataFormat};return ENGINE.runKernelFunc(forward,inputs,null,DepthToSpace,attrs)}var depthToSpace=op({depthToSpace_});function depthwiseConv2d_(x,filter,strides,pad10,dataFormat="NHWC",dilations=[1,1],dimRoundingMode){let $x=convertToTensor(x,"x","depthwiseConv2d"),$filter=convertToTensor(filter,"filter","depthwiseConv2d"),x4D=$x,reshapedTo4D=!1;$x.rank===3&&(reshapedTo4D=!0,x4D=reshape($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]])),assert(x4D.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${x4D.rank}.`),assert($filter.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${$filter.rank}.`),assert(x4D.shape[3]===$filter.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${x4D.shape[3]}) must match the inChannels dimension in filter ${$filter.shape[2]}.`),dimRoundingMode!=null&&assert(isInt(pad10),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${dimRoundingMode} but got pad ${pad10}.`);let forward=(backend3,save)=>{dilations==null&&(dilations=[1,1]),assert(eitherStridesOrDilationsAreOne(strides,dilations),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${strides} and dilations '${dilations}'`);let convInfo=computeConv2DInfo(x4D.shape,$filter.shape,strides,dilations,pad10,dimRoundingMode,!0),res2=backend3.depthwiseConv2D(x4D,$filter,convInfo);return save([x4D,$filter]),res2},inputs={x:x4D,filter:$filter},attrs={strides,pad:pad10,dataFormat,dilations,dimRoundingMode},res=ENGINE.runKernelFunc(forward,inputs,null,DepthwiseConv2dNative,attrs);return reshapedTo4D?reshape(res,[res.shape[1],res.shape[2],res.shape[3]]):res}var depthwiseConv2d=op({depthwiseConv2d_});function diag_(x){let $x=convertToTensor(x,"x","diag"),forward=backend3=>{let flat=reshape($x,[$x.size]),result=backend3.diag(flat),outShape=[...x.shape,...x.shape];return reshape(result,outShape)},inputs={x:$x};return ENGINE.runKernelFunc(forward,inputs,null,Diag)}var diag=op({diag_});function dilation2d_(x,filter,strides,pad10,dilations=[1,1],dataFormat="NHWC"){let $x=convertToTensor(x,"x","dilation2d"),$filter=convertToTensor(filter,"filter","dilation2d");assert($x.rank===3||$x.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${$x.rank}.`),assert($filter.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${$filter.rank}.`),assert(dataFormat==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${dataFormat}`);let x4D=$x,reshapedTo4D=!1;$x.rank===3&&(x4D=reshape($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]]),reshapedTo4D=!0);let inputs={x:x4D,filter:$filter},attrs={strides,pad:pad10,dilations},res=ENGINE.runKernel(Dilation2D,inputs,attrs);return reshapedTo4D?reshape(res,[res.shape[1],res.shape[2],res.shape[3]]):res}var dilation2d=op({dilation2d_});function getBroadcastDims(inShape,outShape){let inRank=inShape.length,dims=[];for(let i=0;i<inRank;i++){let dim=inRank-1-i,a=inShape[dim]||1,b=outShape[outShape.length-1-i]||1;b>1&&a===1&&dims.unshift(dim)}return dims}function getReductionAxes(inShape,outShape){let result=[];for(let i=0;i<outShape.length;i++){let inDim=inShape[inShape.length-i-1],outAxis=outShape.length-i-1,outDim=outShape[outAxis];(inDim==null||inDim===1&&outDim>1)&&result.unshift(outAxis)}return result}function assertAndGetBroadcastShape(shapeA,shapeB){let result=[],l=Math.max(shapeA.length,shapeB.length);for(let i=0;i<l;i++){let a=shapeA[shapeA.length-i-1];a==null&&(a=1);let b=shapeB[shapeB.length-i-1];if(b==null&&(b=1),a===1)result.unshift(b);else if(b===1)result.unshift(a);else if(a!==b){let errMsg=`Operands could not be broadcast together with shapes ${shapeA} and ${shapeB}.`;throw Error(errMsg)}else result.unshift(a)}return result}function equ
rank ${$x.rank}.`),assert(isInt(depthRadius),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${depthRadius}.`);let x4D=$x,reshapedTo4D=!1;$x.rank===3&&(reshapedTo4D=!0,x4D=reshape($x,[1,$x.shape[0],$x.shape[1],$x.shape[2]]));let forward=(backend3,save)=>{let y=backend3.localResponseNormalization4D(x4D,depthRadius,bias,alpha,beta);return save([x4D,y]),y},inputs={x:x4D},attrs={depthRadius,bias,alpha,beta},res=ENGINE.runKernelFunc(forward,inputs,null,LRN,attrs);return reshapedTo4D?reshape(res,[res.shape[1],res.shape[2],res.shape[3]]):res}var localResponseNormalization=op({localResponseNormalization_});function log_(x){let $x=convertToTensor(x,"x","log"),inputs={x:$x};return ENGINE.runKernelFunc((backend3,save)=>{let res=backend3.log($x);return save([$x]),res},inputs,null,Log)}var log2=op({log_});function log1p_(x){let $x=convertToTensor(x,"x","log1p"),inputs={x:$x};return ENGINE.runKernelFunc((backend3,save)=>{let res=backend3.log1p($x);return save([$x]),res},inputs,null,Log1p)}var log1p=op({log1p_});function grad(f){return assert(isFunction(f),()=>"The f passed in grad(f) must be a function"),(x,dy)=>{let $x=convertToTensor(x,"x","tf.grad",null),$dy=dy!=null?convertToTensor(dy,"dy","tf.grad"):null;return ENGINE.tidy(()=>{let{value,grads:grads2}=ENGINE.gradients(()=>f($x),[$x],$dy);return $dy!=null&&assertShapesMatch(value.shape,$dy.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),checkGrads(grads2),grads2[0]})}}function grads(f){return assert(isFunction(f),()=>"The f passed in grads(f) must be a function"),(args,dy)=>{assert(Array.isArray(args),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let $args=convertToTensorArray(args,"args","tf.grads",null),$dy=dy!=null?convertToTensor(dy,"dy","tf.grads"):null;return ENGINE.tidy(()=>{let{value,grads:grads2}=ENGINE.gradients(()=>f(...$args),$args,$dy);return $dy!=null&&assertShapesMatch(value.shape,$dy.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),checkGrads(grads2),grads2})}}function valueAndGrad(f){return assert(isFunction(f),()=>"The f passed in valueAndGrad(f) must be a function"),(x,dy)=>{assert(x instanceof Tensor,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),assert(dy==null||dy instanceof Tensor,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:grads2,value}=ENGINE.gradients(()=>f(x),[x],dy);return checkGrads(grads2),{grad:grads2[0],value}}}function valueAndGrads(f){return assert(isFunction(f),()=>"The f passed in valueAndGrads(f) must be a function"),(args,dy)=>{assert(Array.isArray(args)&&args.every(arg=>arg instanceof Tensor),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),assert(dy==null||dy instanceof Tensor,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let res=ENGINE.gradients(()=>f(...args),args,dy);return dy!=null&&assertShapesMatch(res.value.shape,dy.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),checkGrads(res.grads),res}}function variableGrads(f,varList){assert(isFunction(f),()=>"The f passed in variableGrads(f) must be a function"),assert(varList==null||Array.isArray(varList)&&varList.every(v=>v instanceof Variable),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let specifiedVarList=varList!=null;if(!specifiedVarList){varList=[];for(let varName in ENGINE.registeredVariables)varList.push(ENGINE.registeredVariables[varName])}let specifiedNonTrainable=specifiedVarList?varList.filter(variable2=>!variable2.trainable):null,originalVarCount=varList.length;varList=varList.filter(variable2=>variable2.trainable),assert(varList.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${originalVarCount} variables is trainable.`);let allowNoGradients=!0,{value,grads:grads2}=ENGINE.gradients(f,varList,null,allowNoGradients);assert(grads2.some(g=>g!=
the f you passed encloses all operations that lead from x to y.`)}function neg_(x){let $x=convertToTensor(x,"x","neg"),inputs={x:$x};return ENGINE.runKernelFunc(backend3=>backend3.neg($x),inputs,null,Negate)}var neg=op({neg_});function softplus_(x){let $x=convertToTensor(x,"x","softplus"),inputs={x:$x};return ENGINE.runKernelFunc((backend3,save)=>{let res=backend3.softplus($x);return save([$x]),res},inputs,null,Softplus)}var softplus=op({softplus_});function logSigmoid_(x){let $x=convertToTensor(x,"x","logSigmoid"),customOp=customGrad(x2=>{let value=neg(softplus(neg(x2))),gradFunc=dy=>{let derX=mul(dy,sigmoid(neg(x2)));return derX};return{value,gradFunc}});return customOp($x)}var logSigmoid=op({logSigmoid_});function max_(x,axis=null,keepDims=!1){let $x=convertToTensor(x,"x","max"),forward=(backend3,save)=>{let origAxes=parseAxisParam(axis,$x.shape),axes=origAxes,permutedAxes=getAxesPermutation(axes,$x.rank),maxInput=$x;permutedAxes!=null&&(maxInput=transpose($x,permutedAxes),axes=getInnerMostAxes(axes.length,maxInput.rank));let y=backend3.max(maxInput,axes);permutedAxes!=null&&maxInput.dispose();let res=y;if(keepDims){let expandedShape=expandShapeToKeepDim(res.shape,parseAxisParam(axis,$x.shape));res=reshape(res,expandedShape),y.dispose()}return save([$x,res]),res},inputs={x:$x},attrs={reductionIndices:axis,keepDims};return ENGINE.runKernelFunc(forward,inputs,null,Max,attrs)}var max=op({max_});function sub_(a,b){let $a=convertToTensor(a,"a","sub"),$b=convertToTensor(b,"b","sub");[$a,$b]=makeTypesMatch($a,$b);let forward=(backend3,save)=>{let res=backend3.subtract($a,$b);return save([$a,$b]),res},inputs={a:$a,b:$b};return ENGINE.runKernelFunc(forward,inputs,null,Sub)}var sub=op({sub_});function sum_(x,axis=null,keepDims=!1){let $x=convertToTensor(x,"x","sum");$x.dtype==="bool"&&($x=cast($x,"int32"));let forward=(backend3,save)=>{save([$x]);let axes=parseAxisParam(axis,$x.shape),permutation=getAxesPermutation(axes,$x.rank),reductionAxes=axes,permutedX=$x;permutation!=null&&(permutedX=transpose($x,permutation),reductionAxes=getInnerMostAxes(reductionAxes.length,$x.rank));let value=backend3.sum(permutedX,reductionAxes);if(keepDims){let newShape=expandShapeToKeepDim(value.shape,axes);value=reshape(value,newShape)}return value},inputs={x:$x},attrs={axis,keepDims};return ENGINE.runKernelFunc(forward,inputs,null,Sum,attrs)}var sum2=op({sum_});function logSoftmax_(logits,axis=-1){let $logits=convertToTensor(logits,"logits","logSoftmax");if(axis===-1&&(axis=$logits.rank-1),axis!==$logits.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${$logits.rank} and axis was ${axis}`);let forward=(backend3,save)=>{let keepDims=!0,xMax=max(logits,axis,!0),shifted=sub(logits,xMax),value=sub(cast(shifted,"float32"),log2(sum2(exp(shifted),axis,keepDims)));return save([value]),value},inputs={logits:$logits},attrs={axis};return ENGINE.runKernelFunc(forward,inputs,null,LogSoftmax,attrs)}var logSoftmax=op({logSoftmax_});function logSumExp_(x,axis=null,keepDims=!1){let $x=convertToTensor(x,"x","logSumExp"),axes=parseAxisParam(axis,$x.shape),xMax=max($x,axes,!0),a=sub($x,xMax),b=exp(a),c=sum2(b,axes),d=log2(c),res=add2(reshape(xMax,d.shape),d);if(keepDims){let newShape=expandShapeToKeepDim(res.shape,axes);return reshape(res,newShape)}return res}var logSumExp=op({logSumExp_});function logicalAnd_(a,b){let $a=convertToTensor(a,"a","logicalAnd","bool"),$b=convertToTensor(b,"b","logicalAnd","bool");assertAndGetBroadcastShape($a.shape,$b.shape);let inputs={a:$a,b:$b};return ENGINE.runKernelFunc(backend3=>backend3.logicalAnd($a,$b),inputs,null,LogicalAnd)}var logicalAnd=op({logicalAnd_});function logicalNot_(x){let $x=convertToTensor(x,"x","logicalNot","bool"),inputs={x:$x};return ENGINE.runKernelFunc(backend3=>backend3.logicalNot($x),inputs,null,LogicalNot)}var logicalNot=op({logicalNot_});function logicalOr_(a,b){let $a=convertToTensor(a,"a","logicalOr","bool"),$b=convertToTensor(b,"b","logicalOr","bool");assertAndGetBroadcastShape($a.shape,$b.shape);let inputs={a:$a,b:$b};return ENGINE.runKernelFunc(b
============================
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
2020-12-22 18:34:47 +01:00
============================`));let dataId={};return this.data.set(dataId,{values,dtype,refCount:1}),dataId}makeTensorInfo(shape,dtype,values){let outId;if(dtype==="string"&&values!=null&&values.length>0&&util_exports.isString(values[0])){let encodedValues=values.map(d=>util_exports.encodeString(d));outId=this.write(encodedValues,shape,dtype)}else outId=this.write(values,shape,dtype);return{dataId:outId,shape,dtype}}incRef(dataId){let tensorData=this.data.get(dataId);tensorData.refCount++}decRef(dataId){if(this.data.has(dataId)){let tensorData=this.data.get(dataId);tensorData.refCount--}}move(dataId,values,shape,dtype){this.data.set(dataId,{values,dtype,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(dataId){return this.readSync(dataId)}readSync(dataId){let{dtype,complexTensorInfos}=this.data.get(dataId);if(dtype==="complex64"){let realValues=this.readSync(complexTensorInfos.real.dataId),imagValues=this.readSync(complexTensorInfos.imag.dataId);return backend_util_exports.mergeRealAndImagArrays(realValues,imagValues)}return this.data.get(dataId).values}bufferSync(t){let data2=this.readSync(t.dataId),decodedData=data2;if(t.dtype==="string")try{decodedData=data2.map(d=>util_exports.decodeString(d))}catch(_a){throw new Error("Failed to decode encoded string bytes into utf-8")}return buffer(t.shape,t.dtype,decodedData)}makeOutput(values,shape,dtype){let dataId=this.write(values,shape,dtype);return engine15().makeTensorFromDataId(dataId,shape,dtype,this)}disposeData(dataId){if(this.data.has(dataId)){let{complexTensorInfos}=this.data.get(dataId);complexTensorInfos!=null&&(this.disposeData(complexTensorInfos.real.dataId),this.disposeData(complexTensorInfos.imag.dataId)),this.data.delete(dataId)}}disposeIntermediateTensorInfo(tensorInfo){let dataId=tensorInfo.dataId;if(this.data.has(dataId)){let tensorData=this.data.get(dataId);tensorData.refCount--,tensorData.refCount<1&&this.disposeData(dataId)}}async time(f){let start=util_exports.now();f();let kernelMs=util_exports.now()-start;return{kernelMs}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}stridedSlice(x,begin,end,strides){assertNotComplex(x,"stridedSlice");let outShape=slice_util_exports.computeOutShape(begin,end,strides);if(outShape.some(axis=>axis===0))return tensor4([],outShape);let buffer10=buffer(outShape,x.dtype),xBuf=this.bufferSync(x);for(let i=0;i<buffer10.size;i++){let loc=buffer10.indexToLoc(i),newLoc=new Array(loc.length);for(let j=0;j<newLoc.length;j++)newLoc[j]=loc[j]*strides[j]+begin[j];buffer10.set(xBuf.get(...newLoc),...loc)}return buffer10.toTensor()}diag(x){let xVals=this.readSync(x.dataId),buffer10=buffer([x.size,x.size],x.dtype),vals=buffer10.values;for(let i=0;i<xVals.length;i++)vals[i*x.size+i]=xVals[i];return buffer10.toTensor()}unstack(x,axis){let num=x.shape[axis],outShape=new Array(x.rank-1),outIndex=0;for(let i=0;i<x.rank;i++)i!==axis&&(outShape[outIndex++]=x.shape[i]);let begin=new Array(x.rank).fill(0),size=x.shape.slice();size[axis]=1;let res=new Array(num);for(let i=0;i<res.length;i++)begin[axis]=i,res[i]=slice(x,begin,size).reshape(outShape);return res}reverse(x,axis){assertNotComplex(x,"reverse");let buffer10=buffer(x.shape,x.dtype),xBuf=this.bufferSync(x);for(let i=0;i<buffer10.size;i++){let outLoc=buffer10.indexToLoc(i),inLoc=outLoc.slice();axis.forEach(ax=>inLoc[ax]=x.shape[ax]-1-inLoc[ax]),buffer10.set(xBuf.get(...inLoc),...outLoc)}return buffer10.toTensor()}neg(x){return assertNotComplex(x,"neg"),mul(scalar(-1),x)}addN(tensors){assertNotComplex(tensors,"addN");let vals=tensors.map(t=>this.readSync(t.dataId)),result=buffer(tensors[0].shape,tensors[0].dtype),resultVals=result.values;for(let i=0;i<tensors.length;i++){let currVals=vals[i];for(let j=0;j<resultVals.length;j++)resultVals[j]+=currVals[j]}return result.toTensor()}softmax(logits,dim){let axes=util_exports.parseAxisParam([dim],logits.shape),maxLogit=max(logits,axes),expandedShape=backend_util_exports.expandShapeToKeepDim(maxLogit.shape,axes),a=sub(logi
`),pad10=shaderLines.length.toString().length+2,linesWithLineNumbers=shaderLines.map((line,lineNumber2)=>util_exports.rightPad((lineNumber2+1).toString(),pad10)+line),maxLineLength=0;for(let i=0;i<linesWithLineNumbers.length;i++)maxLineLength=Math.max(linesWithLineNumbers[i].length,maxLineLength);let beforeErrorLines=linesWithLineNumbers.slice(0,lineNumber-1),errorLine=linesWithLineNumbers.slice(lineNumber-1,lineNumber),afterErrorLines=linesWithLineNumbers.slice(lineNumber);console.log(beforeErrorLines.join(`
`)),console.log(shaderInfoLog.split(`
`)[0]),console.log(`%c ${util_exports.rightPad(errorLine[0],maxLineLength)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(afterErrorLines.join(`
2020-12-22 18:34:47 +01:00
`))}function createProgram(gl){return throwIfNull(gl,()=>gl.createProgram(),"Unable to create WebGLProgram.")}function linkProgram(gl,program){if(callAndCheck(gl,()=>gl.linkProgram(program)),gl.getProgramParameter(program,gl.LINK_STATUS)===!1)throw console.log(gl.getProgramInfoLog(program)),new Error("Failed to link vertex and fragment shaders.")}function validateProgram(gl,program){if(callAndCheck(gl,()=>gl.validateProgram(program)),gl.getProgramParameter(program,gl.VALIDATE_STATUS)===!1)throw console.log(gl.getProgramInfoLog(program)),new Error("Shader program validation failed.")}function createStaticVertexBuffer(gl,data2){let buffer10=throwIfNull(gl,()=>gl.createBuffer(),"Unable to create WebGLBuffer");return callAndCheck(gl,()=>gl.bindBuffer(gl.ARRAY_BUFFER,buffer10)),callAndCheck(gl,()=>gl.bufferData(gl.ARRAY_BUFFER,data2,gl.STATIC_DRAW)),buffer10}function createStaticIndexBuffer(gl,data2){let buffer10=throwIfNull(gl,()=>gl.createBuffer(),"Unable to create WebGLBuffer");return callAndCheck(gl,()=>gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,buffer10)),callAndCheck(gl,()=>gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,data2,gl.STATIC_DRAW)),buffer10}function getNumChannels(){return env().getNumber("WEBGL_VERSION")===2?1:4}function createTexture(gl){return throwIfNull(gl,()=>gl.createTexture(),"Unable to create WebGLTexture.")}function validateTextureSize(width,height){let maxTextureSize=env().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(width<=0||height<=0){let requested=`[${width}x${height}]`;throw new Error("Requested texture size "+requested+" is invalid.")}if(width>maxTextureSize||height>maxTextureSize){let requested=`[${width}x${height}]`,max9=`[${maxTextureSize}x${maxTextureSize}]`;throw new Error("Requested texture size "+requested+" greater than WebGL maximum on this browser / GPU "+max9+".")}}function createFramebuffer(gl){return throwIfNull(gl,()=>gl.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function bindVertexBufferToProgramAttribute(gl,program,attribute,buffer10,arrayEntriesPerItem,itemStrideInBytes,itemOffsetInBytes){let loc=gl.getAttribLocation(program,attribute);return loc===-1?!1:(callAndCheck(gl,()=>gl.bindBuffer(gl.ARRAY_BUFFER,buffer10)),callAndCheck(gl,()=>gl.vertexAttribPointer(loc,arrayEntriesPerItem,gl.FLOAT,!1,itemStrideInBytes,itemOffsetInBytes)),callAndCheck(gl,()=>gl.enableVertexAttribArray(loc)),!0)}function bindTextureUnit(gl,texture,textureUnit){validateTextureUnit(gl,textureUnit),callAndCheck(gl,()=>gl.activeTexture(gl.TEXTURE0+textureUnit)),callAndCheck(gl,()=>gl.bindTexture(gl.TEXTURE_2D,texture))}function unbindTextureUnit(gl,textureUnit){validateTextureUnit(gl,textureUnit),callAndCheck(gl,()=>gl.activeTexture(gl.TEXTURE0+textureUnit)),callAndCheck(gl,()=>gl.bindTexture(gl.TEXTURE_2D,null))}function getProgramUniformLocationOrThrow(gl,program,uniformName){return throwIfNull(gl,()=>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,()=>bindTextureUnit(gl,texture,textureUnit)),callAndCheck(gl,()=>gl.uniform1i(uniformSamplerLocation,textureUnit))}function bindCanvasToFramebuffer(gl){callAndCheck(gl,()=>gl.bindFramebuffer(gl.FRAMEBUFFER,null)),callAndCheck(gl,()=>gl.viewport(0,0,gl.canvas.width,gl.canvas.height)),callAndCheck(gl,()=>gl.scissor(0,0,gl.canvas.width,gl.canvas.height))}function bindColorTextureToFramebuffer(gl,texture,framebuffer){callAndCheck(gl,()=>gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer)),callAndCheck(gl,()=>gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0))}function unbindColorTextureFromFramebuffer(gl,framebuffer){callAndCheck(gl,()=>gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer)),callAndCheck(gl,()=>gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,null,0))}function validateFramebuffer(gl){let status2=gl.checkFramebufferStatus(gl.FRAMEBUFFER);if(status2
2020-12-16 20:49:14 +01:00
void main() {
${snippets.join(`
`)}
2020-12-22 18:34:47 +01:00
float result = ${operation210};
2020-12-16 20:49:14 +01:00
setOutput(result);
}
2020-12-22 18:34:47 +01:00
`}},AddNPackedProgram=class{constructor(outputShape,shapes){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=outputShape,this.variableNames=shapes.map((_,i)=>`T${i}`);let snippets=[];this.variableNames.forEach(variable2=>{snippets.push(`vec4 v${variable2} = get${variable2}AtOutCoords();`)});let operation210=this.variableNames.map(variable2=>`v${variable2}`).join(" + ");this.userCode=`
2020-12-16 20:49:14 +01:00
void main() {
${snippets.join(`
`)}
2020-12-22 18:34:47 +01:00
vec4 result = ${operation210};
2020-12-16 20:49:14 +01:00
setOutput(result);
}
`}},ArgMinMaxProgram=class{constructor(reduceInfo,op2,firstPass){this.variableNames=["A"];let{windowSize,batchSize,outSize}=reduceInfo;firstPass||this.variableNames.push("bestIndicesA"),this.outputShape=[batchSize,outSize];let compOp=op2==="max"?">":"<",indexSnippet=firstPass?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${windowSize};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${windowSize}; i++) {
int inIdx = ${indexSnippet};
float candidate = getA(batch, inIdx);
if (candidate ${compOp} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
2020-12-22 18:34:47 +01:00
`}};function getVecChannels(name,rank){return["x","y","z","w","u","v"].slice(0,rank).map(d=>`${name}.${d}`)}function getChannels(name,rank){return rank===1?[name]:getVecChannels(name,rank)}function getSourceCoords(rank,dims){if(rank===1)return"rc";let coords2="";for(let i=0;i<rank;i++)coords2+=dims[i],i<rank-1&&(coords2+=",");return coords2}function getGlslDifferences(){let version19,attribute,varyingVs,varyingFs,texture2D,output,defineOutput,defineSpecialNaN,defineSpecialInf,defineRound;return env().getNumber("WEBGL_VERSION")===2?(version19="#version 300 es",attribute="in",varyingVs="out",varyingFs="in",texture2D="texture",output="outputColor",defineOutput="out vec4 outputColor;",defineSpecialNaN=`
2020-11-16 21:51:46 +01:00
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
`,defineSpecialInf="",defineRound=`
2020-11-16 21:51:46 +01:00
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-12-22 18:34:47 +01:00
`):(version19="",attribute="attribute",varyingVs="varying",varyingFs="varying",texture2D="texture2D",output="gl_FragColor",defineOutput="",defineSpecialNaN=`
2020-11-16 21:51:46 +01:00
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`,defineSpecialInf=`
2020-11-16 21:51:46 +01:00
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,defineRound=`
2020-11-16 21:51:46 +01:00
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
2020-12-22 18:34:47 +01:00
`),{version:version19,attribute,varyingVs,varyingFs,texture2D,output,defineOutput,defineSpecialNaN,defineSpecialInf,defineRound}}function getLogicalCoordinatesFromFlatIndex(coords2,shape,index="index"){let strides=util_exports.computeStrides(shape);return strides.map((stride,i)=>{let line1=`int ${coords2[i]} = ${index} / ${stride}`,line2=i===strides.length-1?`int ${coords2[i+1]} = ${index} - ${coords2[i]} * ${stride}`:`index -= ${coords2[i]} * ${stride}`;return`${line1}; ${line2};`}).join("")}function getFlatIndexFrom3D(shape){let strides=util_exports.computeStrides(shape).map(d=>d.toString());return`
2020-11-16 21:51:46 +01:00
int getFlatIndex(ivec3 coords) {
return coords.x * ${strides[0]} + coords.y * ${strides[1]} + coords.z;
2020-11-10 02:13:38 +01:00
}
2020-11-25 15:13:19 +01:00
`}var ENCODE_FLOAT_SNIPPET=`
2020-11-16 21:51:46 +01:00
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
2020-11-10 15:54:07 +01:00
}
2020-11-16 21:51:46 +01:00
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
2020-11-07 17:34:56 +01:00
}
2020-11-16 21:51:46 +01:00
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`,{getBroadcastDims:getBroadcastDims2}=backend_util_exports;function makeShader(inputsInfo,outputShape,userCode,usesPackedTextures){let prefixSnippets=[];inputsInfo.forEach(x=>{let size=util_exports.sizeFromShape(x.shapeInfo.logicalShape);x.shapeInfo.isUniform?prefixSnippets.push(`uniform float ${x.name}${size>1?`[${size}]`:""};`):(prefixSnippets.push(`uniform sampler2D ${x.name};`),prefixSnippets.push(`uniform int offset${x.name};`))});let inputPrefixSnippet=prefixSnippets.join(`
`),inputSamplingSnippet=inputsInfo.map(x=>getInputSamplingSnippet(x,outputShape,usesPackedTextures)).join(`
2020-11-25 15:13:19 +01:00
`),outTexShape=outputShape.texShape,glsl=getGlslDifferences(),floatTextureSampleSnippet=getFloatTextureSampleSnippet(glsl),outputSamplingSnippet,floatTextureSetOutputSnippet,shaderPrefix=getShaderPrefix(glsl);outputShape.isPacked?(outputSamplingSnippet=getPackedOutputSamplingSnippet(outputShape.logicalShape,outTexShape),floatTextureSetOutputSnippet=getFloatTextureSetRGBASnippet(glsl)):(outputSamplingSnippet=getOutputSamplingSnippet(outputShape.logicalShape,outTexShape),floatTextureSetOutputSnippet=getFloatTextureSetRSnippet(glsl)),usesPackedTextures&&(shaderPrefix+=SHADER_PACKED_PREFIX);let source=[shaderPrefix,floatTextureSampleSnippet,floatTextureSetOutputSnippet,inputPrefixSnippet,outputSamplingSnippet,inputSamplingSnippet,userCode].join(`
`);return source}function getSamplerFromInInfo(inInfo){let 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){let 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=!1){let res="";usesPackedTextures?res+=getPackedSamplerFromInInfo(inInfo):res+=getSamplerFromInInfo(inInfo);let inShape=inInfo.shapeInfo.logicalShape,outShape=outShapeInfo.logicalShape;return inShape.length<=outShape.length&&(usesPackedTextures?res+=getPackedSamplerAtOutputCoords(inInfo,outShapeInfo):res+=getSamplerAtOutputCoords(inInfo,outShapeInfo)),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`
2020-11-16 21:51:46 +01:00
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${glsl.texture2D}(textureSampler, uv).r;
2020-11-08 18:32:31 +01:00
}
2020-11-16 21:51:46 +01:00
`}function getFloatTextureSetRSnippet(glsl){return`
void setOutput(float val) {
${glsl.output} = vec4(val, 0, 0, 0);
2020-11-07 17:34:56 +01:00
}
2020-11-16 21:51:46 +01:00
`}function getFloatTextureSetRGBASnippet(glsl){return`
void setOutput(vec4 val) {
${glsl.output} = val;
2020-11-12 18:17:57 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getShaderPrefix(glsl){let SHADER_PREFIX=`${glsl.version}
2020-11-16 21:51:46 +01:00
precision highp float;
precision highp int;
precision highp sampler2D;
${glsl.varyingFs} vec2 resultUV;
${glsl.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${glsl.defineSpecialNaN}
${glsl.defineSpecialInf}
${glsl.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
2020-11-12 18:17:57 +01:00
}
2020-11-16 21:51:46 +01:00
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
return res;
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
${SAMPLE_1D_SNIPPET}
${SAMPLE_2D_SNIPPET}
${SAMPLE_3D_SNIPPET}
2020-11-25 15:13:19 +01:00
`;return SHADER_PREFIX}var SAMPLE_1D_SNIPPET=`
2020-11-16 21:51:46 +01:00
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,SAMPLE_2D_SNIPPET=`
2020-11-16 21:51:46 +01:00
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,SAMPLE_3D_SNIPPET=`
2020-11-16 21:51:46 +01:00
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,SHADER_PACKED_PREFIX=`
2020-11-16 21:51:46 +01:00
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
`;function getOutputScalarCoords(){return`
int getOutputCoords() {
2020-11-12 18:58:55 +01:00
return 0;
}
2020-11-25 15:13:19 +01:00
`}function getOutputPacked1DCoords(shape,texShape){let packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)];return packedTexShape[0]===1?`
2020-11-16 21:51:46 +01:00
int getOutputCoords() {
return 2 * int(resultUV.x * ${packedTexShape[1]}.0);
2020-11-07 17:34:56 +01:00
}
`:packedTexShape[1]===1?`
2020-11-16 21:51:46 +01:00
int getOutputCoords() {
return 2 * int(resultUV.y * ${packedTexShape[0]}.0);
}
`:`
2020-11-16 21:51:46 +01:00
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
return 2 * (resTexRC.x * ${packedTexShape[1]} + resTexRC.y);
2020-11-06 22:21:20 +01:00
}
`}function getOutput1DCoords(shape,texShape){return texShape[0]===1?`
2020-11-16 21:51:46 +01:00
int getOutputCoords() {
return int(resultUV.x * ${texShape[1]}.0);
2020-11-12 18:58:55 +01:00
}
`:texShape[1]===1?`
2020-11-16 21:51:46 +01:00
int getOutputCoords() {
return int(resultUV.y * ${texShape[0]}.0);
2020-11-04 17:57:44 +01:00
}
`:`
2020-11-16 21:51:46 +01:00
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
return resTexRC.x * ${texShape[1]} + resTexRC.y;
2020-11-04 17:57:44 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getOutputPacked3DCoords(shape,texShape){let packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)],texelsInLogicalRow=Math.ceil(shape[2]/2),texelsInBatch=texelsInLogicalRow*Math.ceil(shape[1]/2);return`
2020-11-16 21:51:46 +01:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;
int b = index / ${texelsInBatch};
index -= b * ${texelsInBatch};
int r = 2 * (index / ${texelsInLogicalRow});
int c = imod(index, ${texelsInLogicalRow}) * 2;
return ivec3(b, r, c);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getOutput3DCoords(shape,texShape){let coordsFromIndexSnippet=getLogicalCoordinatesFromFlatIndex(["r","c","d"],shape);return`
2020-11-16 21:51:46 +01:00
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
${coordsFromIndexSnippet}
return ivec3(r, c, d);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getOutputPackedNDCoords(shape,texShape){let packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)],texelsInLogicalRow=Math.ceil(shape[shape.length-1]/2),texelsInBatch=texelsInLogicalRow*Math.ceil(shape[shape.length-2]/2),texelsInBatchN=texelsInBatch,batches="",coords2="b, r, c";for(let b=2;b<shape.length-1;b++)texelsInBatchN*=shape[shape.length-b-1],batches=`
2020-11-16 21:51:46 +01:00
int b${b} = index / ${texelsInBatchN};
index -= b${b} * ${texelsInBatchN};
`+batches,coords2=`b${b}, `+coords2;return`
2020-11-16 21:51:46 +01:00
ivec${shape.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;
${batches}
int b = index / ${texelsInBatch};
index -= b * ${texelsInBatch};
int r = 2 * (index / ${texelsInLogicalRow});
int c = imod(index, ${texelsInLogicalRow}) * 2;
return ivec${shape.length}(${coords2});
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getOutput4DCoords(shape,texShape){let coordsFromIndexSnippet=getLogicalCoordinatesFromFlatIndex(["r","c","d","d2"],shape);return`
2020-11-16 21:51:46 +01:00
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
${coordsFromIndexSnippet}
return ivec4(r, c, d, d2);
2020-11-10 02:13:38 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getOutput5DCoords(shape,texShape){let coordsFromIndexSnippet=getLogicalCoordinatesFromFlatIndex(["r","c","d","d2","d3"],shape);return`
2020-11-16 21:51:46 +01:00
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${texShape[0]},
${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
${coordsFromIndexSnippet}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
2020-11-10 02:13:38 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getOutput6DCoords(shape,texShape){let coordsFromIndexSnippet=getLogicalCoordinatesFromFlatIndex(["r","c","d","d2","d3","d4"],shape);return`
2020-11-16 21:51:46 +01:00
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
${coordsFromIndexSnippet}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
2020-11-25 15:13:19 +01:00
`}function getOutputPacked2DCoords(shape,texShape){let packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)];if(util_exports.arraysEqual(shape,texShape))return`
2020-11-16 21:51:46 +01:00
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let texelsInLogicalRow=Math.ceil(shape[1]/2);return`
2020-11-16 21:51:46 +01:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${packedTexShape[0]}, ${packedTexShape[1]}));
int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;
int r = 2 * (index / ${texelsInLogicalRow});
int c = imod(index, ${texelsInLogicalRow}) * 2;
return ivec2(r, c);
}
`}function getOutput2DCoords(shape,texShape){return util_exports.arraysEqual(shape,texShape)?`
2020-11-16 21:51:46 +01:00
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${texShape[0]}, ${texShape[1]}));
2020-11-12 18:58:55 +01:00
}
`:shape[1]===1?`
2020-11-16 21:51:46 +01:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
return ivec2(index, 0);
2020-11-12 18:58:55 +01:00
}
`:shape[0]===1?`
2020-11-16 21:51:46 +01:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
return ivec2(0, index);
2020-11-12 18:58:55 +01:00
}
`:`
2020-11-16 21:51:46 +01:00
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = resTexRC.x * ${texShape[1]} + resTexRC.y;
int r = index / ${shape[1]};
int c = index - r * ${shape[1]};
return ivec2(r, c);
}
2020-11-25 15:13:19 +01:00
`}function getFlatOffsetUniformName(texName){return`offset${texName}`}function getPackedSamplerScalar(inputInfo){let texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),glsl=getGlslDifferences();return`
2020-11-16 21:51:46 +01:00
vec4 ${funcName}() {
return ${glsl.texture2D}(${texName}, halfCR);
}
2020-11-25 15:13:19 +01:00
`}function getSamplerScalar(inputInfo){let texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1);if(inputInfo.shapeInfo.isUniform)return`float ${funcName}() {return ${texName};}`;let[texNumR,texNumC]=inputInfo.shapeInfo.texShape;if(texNumR===1&&texNumC===1)return`
2020-11-16 21:51:46 +01:00
float ${funcName}() {
return sampleTexture(${texName}, halfCR);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let[tNumR,tNumC]=inputInfo.shapeInfo.texShape,offset=getFlatOffsetUniformName(texName);return`
2020-11-16 21:51:46 +01:00
float ${funcName}() {
vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, ${offset});
return sampleTexture(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`}function getPackedSampler1D(inputInfo){let texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),texShape=inputInfo.shapeInfo.texShape,packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)],glsl=getGlslDifferences();return`
2020-11-16 21:51:46 +01:00
vec4 ${funcName}(int index) {
vec2 uv = packedUVfrom1D(
${packedTexShape[0]}, ${packedTexShape[1]}, index);
return ${glsl.texture2D}(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`}function getSampler1D(inputInfo){let texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1);if(inputInfo.shapeInfo.isUniform)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int index) {
${getUniformSampler(inputInfo)}
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let texShape=inputInfo.shapeInfo.texShape,tNumR=texShape[0],tNumC=texShape[1];if(tNumC===1&&tNumR===1)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int index) {
return sampleTexture(${texName}, halfCR);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let offset=getFlatOffsetUniformName(texName);return tNumC===1?`
2020-11-16 21:51:46 +01:00
float ${funcName}(int index) {
vec2 uv = vec2(0.5, (float(index + ${offset}) + 0.5) / ${tNumR}.0);
return sampleTexture(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
`:tNumR===1?`
2020-11-16 21:51:46 +01:00
float ${funcName}(int index) {
vec2 uv = vec2((float(index + ${offset}) + 0.5) / ${tNumC}.0, 0.5);
return sampleTexture(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
`:`
2020-11-16 21:51:46 +01:00
float ${funcName}(int index) {
vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, index + ${offset});
return sampleTexture(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`}function getPackedSampler2D(inputInfo){let shape=inputInfo.shapeInfo.logicalShape,texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),texShape=inputInfo.shapeInfo.texShape,texNumR=texShape[0],texNumC=texShape[1],glsl=getGlslDifferences();if(texShape!=null&&util_exports.arraysEqual(shape,texShape))return`
2020-11-16 21:51:46 +01:00
vec4 ${funcName}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);
return ${glsl.texture2D}(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)],valuesPerRow=Math.ceil(shape[1]/2);return`
2020-11-16 21:51:46 +01:00
vec4 ${funcName}(int row, int col) {
vec2 uv = packedUVfrom2D(${valuesPerRow}, ${packedTexShape[0]}, ${packedTexShape[1]}, row, col);
return ${glsl.texture2D}(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`}function getSampler2D(inputInfo){let shape=inputInfo.shapeInfo.logicalShape,texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),texShape=inputInfo.shapeInfo.texShape;if(texShape!=null&&util_exports.arraysEqual(shape,texShape)){let texNumR2=texShape[0],texNumC2=texShape[1];return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC2}.0, ${texNumR2}.0);
return sampleTexture(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`}let{newShape,keptDims}=util_exports.squeezeShape(shape),squeezedShape=newShape;if(squeezedShape.length<shape.length){let newInputInfo=squeezeInputInfo(inputInfo,squeezedShape),params=["row","col"];return`
2020-11-16 21:51:46 +01:00
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col) {
return ${funcName}(${getSqueezedParams(params,keptDims)});
2020-11-12 18:58:55 +01:00
}
`}if(inputInfo.shapeInfo.isUniform)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${shape[1]}, 1)));
${getUniformSampler(inputInfo)}
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let texNumR=texShape[0],texNumC=texShape[1],offset=getFlatOffsetUniformName(texName);return texNumC===1?`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col) {
float index = dot(vec3(row, col, ${offset}), vec3(${shape[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`:texNumR===1?`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col) {
float index = dot(vec3(row, col, ${offset}), vec3(${shape[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${texNumC}.0, 0.5);
return sampleTexture(${texName}, uv);
}
`:`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${shape[1]} + col + ${offset};
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
return sampleTexture(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`}function getPackedSampler3D(inputInfo){let shape=inputInfo.shapeInfo.logicalShape,texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),texShape=inputInfo.shapeInfo.texShape,packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)];if(shape[0]===1){let squeezedShape=shape.slice(1),keptDims=[1,2],newInputInfo=squeezeInputInfo(inputInfo,squeezedShape),params=["b","row","col"];return`
2020-11-16 21:51:46 +01:00
${getPackedSamplerFromInInfo(newInputInfo)}
vec4 ${funcName}(int b, int row, int col) {
return ${funcName}(${getSqueezedParams(params,keptDims)});
}
2020-11-25 15:13:19 +01:00
`}let texNumR=packedTexShape[0],texNumC=packedTexShape[1],valuesPerRow=Math.ceil(shape[2]/2),texelsInBatch=valuesPerRow*Math.ceil(shape[1]/2),glsl=getGlslDifferences();return`
2020-11-16 21:51:46 +01:00
vec4 ${funcName}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${texNumR}, ${texNumC}, ${texelsInBatch}, ${valuesPerRow}, b, row, col);
return ${glsl.texture2D}(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`}function getSampler3D(inputInfo){let shape=inputInfo.shapeInfo.logicalShape,texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),stride0=shape[1]*shape[2],stride1=shape[2],{newShape,keptDims}=util_exports.squeezeShape(shape),squeezedShape=newShape;if(squeezedShape.length<shape.length){let newInputInfo=squeezeInputInfo(inputInfo,squeezedShape),params=["row","col","depth"];return`
2020-11-16 21:51:46 +01:00
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col, int depth) {
return ${funcName}(${getSqueezedParams(params,keptDims)});
}
`}if(inputInfo.shapeInfo.isUniform)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${stride0}, ${stride1}, 1)));
${getUniformSampler(inputInfo)}
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let texShape=inputInfo.shapeInfo.texShape,texNumR=texShape[0],texNumC=texShape[1],flatOffset=inputInfo.shapeInfo.flatOffset;if(texNumC===stride0&&flatOffset==null)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${stride1}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
`;if(texNumC===stride1&&flatOffset==null)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${shape[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`;let offset=getFlatOffsetUniformName(texName);return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${stride0} + col * ${stride1} + depth + ${offset};
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
return sampleTexture(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getPackedSamplerND(inputInfo){let shape=inputInfo.shapeInfo.logicalShape,rank=shape.length,texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),texShape=inputInfo.shapeInfo.texShape,packedTexShape=[Math.ceil(texShape[0]/2),Math.ceil(texShape[1]/2)],texNumR=packedTexShape[0],texNumC=packedTexShape[1],valuesPerRow=Math.ceil(shape[rank-1]/2),texelsInBatch=valuesPerRow*Math.ceil(shape[rank-2]/2),params="int b, int row, int col",index=`b * ${texelsInBatch} + (row / 2) * ${valuesPerRow} + (col / 2)`;for(let b=2;b<rank-1;b++)params=`int b${b}, `+params,texelsInBatch*=shape[rank-b-1],index=`b${b} * ${texelsInBatch} + `+index;let glsl=getGlslDifferences();return`
2020-11-16 21:51:46 +01:00
vec4 ${funcName}(${params}) {
2020-11-17 16:18:15 +01:00
int index = ${index};
2020-11-16 21:51:46 +01:00
int texR = index / ${texNumC};
int texC = index - texR * ${texNumC};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}, ${texNumR});
return ${glsl.texture2D}(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`}function getSampler4D(inputInfo){let shape=inputInfo.shapeInfo.logicalShape,texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),stride2=shape[3],stride1=shape[2]*stride2,stride0=shape[1]*stride1,{newShape,keptDims}=util_exports.squeezeShape(shape);if(newShape.length<shape.length){let newInputInfo=squeezeInputInfo(inputInfo,newShape),params=["row","col","depth","depth2"];return`
2020-11-16 21:51:46 +01:00
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col, int depth, int depth2) {
return ${funcName}(${getSqueezedParams(params,keptDims)});
2020-11-12 18:58:55 +01:00
}
`}if(inputInfo.shapeInfo.isUniform)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${stride0}, ${stride1}, ${stride2}, 1)));
${getUniformSampler(inputInfo)}
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let flatOffset=inputInfo.shapeInfo.flatOffset,texShape=inputInfo.shapeInfo.texShape,texNumR=texShape[0],texNumC=texShape[1];if(texNumC===stride0&&flatOffset==null)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${stride1}, ${stride2}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
`;if(texNumC===stride2&&flatOffset==null)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${shape[1]*shape[2]}, ${shape[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let offset=getFlatOffsetUniformName(texName);return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${stride0} + col * ${stride1} +
depth * ${stride2} + depth2;
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index + ${offset});
return sampleTexture(${texName}, uv);
}
2020-11-25 15:13:19 +01:00
`}function getSampler5D(inputInfo){let shape=inputInfo.shapeInfo.logicalShape,texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),stride3=shape[4],stride2=shape[3]*stride3,stride1=shape[2]*stride2,stride0=shape[1]*stride1,{newShape,keptDims}=util_exports.squeezeShape(shape);if(newShape.length<shape.length){let newInputInfo=squeezeInputInfo(inputInfo,newShape),params=["row","col","depth","depth2","depth3"];return`
2020-11-16 21:51:46 +01:00
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
return ${funcName}(${getSqueezedParams(params,keptDims)});
2020-11-12 18:58:55 +01:00
}
`}if(inputInfo.shapeInfo.isUniform)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${stride0}, ${stride1}, ${stride2}, ${stride3})) +
depth3;
${getUniformSampler(inputInfo)}
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let flatOffset=inputInfo.shapeInfo.flatOffset,texShape=inputInfo.shapeInfo.texShape,texNumR=texShape[0],texNumC=texShape[1];if(texNumC===stride0&&flatOffset==null)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${stride1}, ${stride2}, ${stride3}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
`;if(texNumC===stride3&&flatOffset==null)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${shape[1]*shape[2]*shape[3]},
${shape[2]*shape[3]}, ${shape[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
2020-11-10 02:13:38 +01:00
}
2020-11-25 15:13:19 +01:00
`;let offset=getFlatOffsetUniformName(texName);return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +
depth2 * ${stride3} + depth3 + ${offset};
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
return sampleTexture(${texName}, uv);
2020-11-10 02:13:38 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getSampler6D(inputInfo){let shape=inputInfo.shapeInfo.logicalShape,texName=inputInfo.name,funcName="get"+texName.charAt(0).toUpperCase()+texName.slice(1),{newShape,keptDims}=util_exports.squeezeShape(shape);if(newShape.length<shape.length){let newInputInfo=squeezeInputInfo(inputInfo,newShape),params=["row","col","depth","depth2","depth3","depth4"];return`
2020-11-16 21:51:46 +01:00
${getSamplerFromInInfo(newInputInfo)}
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${funcName}(${getSqueezedParams(params,keptDims)});
2020-11-10 02:13:38 +01:00
}
2020-11-25 15:13:19 +01:00
`}let stride4=shape[5],stride3=shape[4]*stride4,stride2=shape[3]*stride3,stride1=shape[2]*stride2,stride0=shape[1]*stride1;if(inputInfo.shapeInfo.isUniform)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${stride0}, ${stride1}, ${stride2}, ${stride3})) +
dot(
vec2(depth3, depth4),
vec2(${stride4}, 1)));
${getUniformSampler(inputInfo)}
2020-11-10 02:13:38 +01:00
}
2020-11-25 15:13:19 +01:00
`;let flatOffset=inputInfo.shapeInfo.flatOffset,texShape=inputInfo.shapeInfo.texShape,texNumR=texShape[0],texNumC=texShape[1];if(texNumC===stride0&&flatOffset==null)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${stride1}, ${stride2}, ${stride3}, ${stride4})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
`;if(texNumC===stride4&&flatOffset==null)return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${shape[1]*shape[2]*shape[3]*shape[4]},
${shape[2]*shape[3]*shape[4]},
${shape[3]*shape[4]},
${shape[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${texNumC}.0, ${texNumR}.0);
return sampleTexture(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let offset=getFlatOffsetUniformName(texName);return`
2020-11-16 21:51:46 +01:00
float ${funcName}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +
depth2 * ${stride3} + depth3 * ${stride4} + depth4 + ${offset};
vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);
return sampleTexture(${texName}, uv);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getUniformSampler(inputInfo){let texName=inputInfo.name,inSize=util_exports.sizeFromShape(inputInfo.shapeInfo.logicalShape);return inSize<2?`return ${texName};`:`
2020-11-16 21:51:46 +01:00
for (int i = 0; i < ${inSize}; i++) {
if (i == index) {
return ${texName}[i];
2020-11-07 17:34:56 +01:00
}
2020-11-10 02:13:38 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getPackedSamplerAtOutputCoords(inputInfo,outShapeInfo){let texName=inputInfo.name,texFuncSnippet=texName.charAt(0).toUpperCase()+texName.slice(1),funcName="get"+texFuncSnippet+"AtOutCoords",inRank=inputInfo.shapeInfo.logicalShape.length,outRank=outShapeInfo.logicalShape.length,broadcastDims=getBroadcastDims2(inputInfo.shapeInfo.logicalShape,outShapeInfo.logicalShape),type=getCoordsDataType(outRank),rankDiff=outRank-inRank,coordsSnippet,fields=["x","y","z","w","u","v"];inRank===0?coordsSnippet="":outRank<2&&broadcastDims.length>=1?coordsSnippet="coords = 0;":coordsSnippet=broadcastDims.map(d=>`coords.${fields[d+rankDiff]} = 0;`).join(`
`);let unpackedCoordsSnippet="";outRank<2&&inRank>0?unpackedCoordsSnippet="coords":unpackedCoordsSnippet=inputInfo.shapeInfo.logicalShape.map((s,i)=>`coords.${fields[i+rankDiff]}`).join(", ");let output="return outputValue;",inSize=util_exports.sizeFromShape(inputInfo.shapeInfo.logicalShape),isInputScalar=inSize===1,outSize=util_exports.sizeFromShape(outShapeInfo.logicalShape),isOutputScalar=outSize===1;if(inRank===1&&!isInputScalar&&!isOutputScalar)output=`
2020-11-16 21:51:46 +01:00
return vec4(outputValue.xy, outputValue.xy);
`;else if(isInputScalar&&!isOutputScalar)outRank===1?output=`
2020-11-16 21:51:46 +01:00
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:output=`
2020-11-16 21:51:46 +01:00
return vec4(outputValue.x);
2020-11-25 15:13:19 +01:00
`;else if(broadcastDims.length){let rows=inRank-2,cols=inRank-1;broadcastDims.indexOf(rows)>-1&&broadcastDims.indexOf(cols)>-1?output="return vec4(outputValue.x);":broadcastDims.indexOf(rows)>-1?output="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":broadcastDims.indexOf(cols)>-1&&(output="return vec4(outputValue.xx, outputValue.zz);")}return`
2020-11-16 21:51:46 +01:00
vec4 ${funcName}() {
${type} coords = getOutputCoords();
${coordsSnippet}
vec4 outputValue = get${texFuncSnippet}(${unpackedCoordsSnippet});
${output}
2020-11-12 18:17:57 +01:00
}
2020-11-25 15:13:19 +01:00
`}function getSamplerAtOutputCoords(inputInfo,outShapeInfo){let texName=inputInfo.name,texFuncSnippet=texName.charAt(0).toUpperCase()+texName.slice(1),funcName="get"+texFuncSnippet+"AtOutCoords",outTexShape=outShapeInfo.texShape,inTexShape=inputInfo.shapeInfo.texShape,inRank=inputInfo.shapeInfo.logicalShape.length,outRank=outShapeInfo.logicalShape.length;if(!inputInfo.shapeInfo.isUniform&&inRank===outRank&&inputInfo.shapeInfo.flatOffset==null&&util_exports.arraysEqual(inTexShape,outTexShape))return`
2020-11-16 21:51:46 +01:00
float ${funcName}() {
return sampleTexture(${texName}, resultUV);
2020-11-12 18:58:55 +01:00
}
2020-11-25 15:13:19 +01:00
`;let type=getCoordsDataType(outRank),broadcastDims=getBroadcastDims2(inputInfo.shapeInfo.logicalShape,outShapeInfo.logicalShape),rankDiff=outRank-inRank,coordsSnippet,fields=["x","y","z","w","u","v"];inRank===0?coordsSnippet="":outRank<2&&broadcastDims.length>=1?coordsSnippet="coords = 0;":coordsSnippet=broadcastDims.map(d=>`coords.${fields[d+rankDiff]} = 0;`).join(`
`);let unpackedCoordsSnippet="";return outRank<2&&inRank>0?unpackedCoordsSnippet="coords":unpackedCoordsSnippet=inputInfo.shapeInfo.logicalShape.map((s,i)=>`coords.${fields[i+rankDiff]}`).join(", "),`
2020-11-16 21:51:46 +01:00
float ${funcName}() {
${type} coords = getOutputCoords();
${coordsSnippet}
return get${texFuncSnippet}(${unpackedCoordsSnippet});
}
2020-12-16 20:49:14 +01:00
`}function getCoordsDataType(rank){if(rank<=1)return"int";if(rank===2)return"ivec2";if(rank===3)return"ivec3";if(rank===4)return"ivec4";if(rank===5)return"ivec5";if(rank===6)return"ivec6";throw Error(`GPU for rank ${rank} is not yet supported`)}function squeezeInputInfo(inInfo,squeezedShape){let newInputInfo=JSON.parse(JSON.stringify(inInfo));return newInputInfo.shapeInfo.logicalShape=squeezedShape,newInputInfo}function getSqueezedParams(params,keptDims){return keptDims.map(d=>params[d]).join(", ")}var ArgMinMaxPackedProgram=class{constructor(shape,windowSize,op2,firstPass){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,util_exports.assert(shape.length>2,()=>`Packed arg${op2.charAt(0).toUpperCase()+op2.slice(1)} supports only inputs with rank above 2.`);let inSize=shape[shape.length-1],outSize=Math.ceil(inSize/windowSize);this.outputShape=shape.slice(0,-1),outSize>1&&this.outputShape.push(outSize),firstPass||this.variableNames.push("bestIndicesA");let outShape=this.outputShape,rank=outShape.length,dtype=getCoordsDataType(rank),coords2=getChannels("coords",rank),sourceLocSetup,sourceRank;if(outSize===1){sourceRank=rank+1;let sourceLocDType=getCoordsDataType(sourceRank);sourceLocSetup=`
${sourceLocDType} sourceLocR = ${sourceLocDType}(${coords2.join()}, 0);
++${coords2[rank-1]};
${sourceLocDType} sourceLocG = ${sourceLocDType}(${coords2.join()}, 0);
++${coords2[rank-2]};
${sourceLocDType} sourceLocA = ${sourceLocDType}(${coords2.join()}, 0);
--${coords2[rank-1]};
${sourceLocDType} sourceLocB = ${sourceLocDType}(${coords2.join()}, 0);
--${coords2[rank-2]};`}else sourceRank=rank,sourceLocSetup=`
${dtype} sourceLocR = coords;
++${coords2[rank-1]};
${dtype} sourceLocG = coords;
++${coords2[rank-2]};
${dtype} sourceLocA = coords;
--${coords2[rank-1]};
${dtype} sourceLocB = coords;
--${coords2[rank-2]};`;let channels=["x","y","z","w","u","v"].slice(0,sourceRank),inChannel="."+channels[sourceRank-1],intChannels=channels.map(x=>"int "+x),srcRCoords=getChannels("sourceLocR",sourceRank-1).concat("inIdx.r"),srcGCoords=getChannels("sourceLocG",sourceRank-1).concat("inIdx.g"),srcBCoords=getChannels("sourceLocB",sourceRank-1).concat("inIdx.b"),srcACoords=getChannels("sourceLocA",sourceRank-1).concat("inIdx.a"),compOp=op2==="max"?"greaterThan":"lessThan",fetchCandidateIdx=firstPass?"":`
inIdx = round(vec4(getBestIndicesAChannel(${srcRCoords.join()}),
getBestIndicesAChannel(${srcGCoords.join()}),
getBestIndicesAChannel(${srcBCoords.join()}),
getBestIndicesAChannel(${srcACoords.join()})));`,fetchValue=`vec4(
getAChannel(${srcRCoords.join()}),
hasNextCol ? getAChannel(${srcGCoords.join()}) : 0.,
hasNextRow ? getAChannel(${srcBCoords.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${srcACoords.join()}) : 0.)`,getBestIndicesAChannelSnippet=firstPass?"":`
float getBestIndicesAChannel(${intChannels.join()}) {
return getChannel(getBestIndicesA(${channels.join()}),
vec2(${channels.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${intChannels.join()}) {
return getChannel(getA(${channels.join()}),
vec2(${channels.slice(-2).join()}));
}
${getBestIndicesAChannelSnippet}
void main() {
${dtype} coords = getOutputCoords();
bool hasNextCol = ${coords2[rank-1]} < ${outShape[rank-1]-1};
bool hasNextRow = ${coords2[rank-2]} < ${outShape[rank-2]-1};
${sourceLocSetup}
ivec4 srcIdx = ivec4(sourceLocR${inChannel}, sourceLocG${inChannel},
sourceLocB${inChannel}, sourceLocA${inChannel}) * ${windowSize};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${fetchValue};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int i = 0; i < ${windowSize}; i++) {
inIdx = srcIdx;
${fetchCandidateIdx}
vec4 candidate = ${fetchValue};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${compOp}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(bestIndex);
}
`}},AvgPool2DBackpropProgram=class{constructor(convInfo){this.variableNames=["dy"],this.outputShape=convInfo.inShape;let filterHeight=convInfo.filterHeight,filterWidth=convInfo.filterWidth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationHeight=convInfo.dilationHeight,dilationWidth=convInfo.dilationWidth,effectiveFilterHeight=convInfo.effectiveFilterHeight,effectiveFilterWidth=convInfo.effectiveFilterWidth,padTop=effectiveFilterHeight-1-convInfo.padInfo.top,padLeft=effectiveFilterWidth-1-convInfo.padInfo.left,avgMultiplier=1/(filterHeight*filterWidth);this.userCode=`
const ivec2 pads = ivec2(${padTop}, ${padLeft});
const float avgMultiplier = float(${avgMultiplier});
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${effectiveFilterWidth};
wC+= ${dilationWidth}) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},AvgPool3DBackpropProgram=class{constructor(convInfo){this.variableNames=["dy"],this.outputShape=convInfo.inShape;let filterDepth=convInfo.filterDepth,filterHeight=convInfo.filterHeight,filterWidth=convInfo.filterWidth,strideDepth=convInfo.strideDepth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationDepth=convInfo.dilationDepth,dilationHeight=convInfo.dilationHeight,dilationWidth=convInfo.dilationWidth,effectiveFilterDepth=convInfo.effectiveFilterDepth,effectiveFilterHeight=convInfo.effectiveFilterHeight,effectiveFilterWidth=convInfo.effectiveFilterWidth,padFront=effectiveFilterDepth-1-convInfo.padInfo.front,padTop=effectiveFilterHeight-1-convInfo.padInfo.top,padLeft=effectiveFilterWidth-1-convInfo.padInfo.left,avgMultiplier=1/(filterDepth*filterHeight*filterWidth);this.userCode=`
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
const float avgMultiplier = float(${avgMultiplier});
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wD = 0; wD < ${effectiveFilterDepth};
wD += ${dilationDepth}) {
float dyD = float(dyDCorner + wD) / ${strideDepth}.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${effectiveFilterWidth};
wC += ${dilationWidth}) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
2020-11-08 18:32:31 +01:00
}
2020-12-16 20:49:14 +01:00
`}},CHECK_NAN_SNIPPET=`
2020-11-16 21:51:46 +01:00
if (isnan(a)) return a;
if (isnan(b)) return b;
2020-12-16 20:49:14 +01:00
`,INT_DIV=`
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
`,POW=`
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
`,EQUAL="return float(a == b);",LESS="return float(a < b);",LESS_EQUAL="return float(a <= b);",GREATER="return float(a > b);",GREATER_EQUAL="return float(a >= b);",LOGICAL_AND="return float(a >= 1.0 && b >= 1.0);",LOGICAL_OR="return float(a >= 1.0 || b >= 1.0);",MAX=CHECK_NAN_SNIPPET+`
return max(a, b);
`,MIN=CHECK_NAN_SNIPPET+`
return min(a, b);
`,MOD=`if (b == 0.0) return NAN;
return mod(a, b);`,ELU_DER="return (b >= 1.0) ? a : a * (b + 1.0);",PRELU="return (a < 0.) ? b * a : a;",BinaryOpProgram=class{constructor(op2,aShape,bShape){this.variableNames=["A","B"],this.outputShape=backend_util_exports.assertAndGetBroadcastShape(aShape,bShape),this.userCode=`
2020-11-16 21:51:46 +01:00
float binaryOperation(float a, float b) {
2020-11-17 16:18:15 +01:00
${op2}
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
2020-11-08 18:32:31 +01:00
}
2020-12-16 20:49:14 +01:00
`}},CHECK_NAN_SNIPPET2=`
2020-11-16 21:51:46 +01:00
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2020-12-16 20:49:14 +01:00
`,INT_DIV2=`
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
`,POW2=`
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
`+CHECK_NAN_SNIPPET2+`
return result;
`,PRELU2=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`,ELU_DER2=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,EQUAL2=`
return vec4(equal(a, b));
`,LESS2=`
return vec4(lessThan(a, b));
`,LESS_EQUAL2=`
return vec4(lessThanEqual(a, b));
`,GREATER2=`
return vec4(greaterThan(a, b));
`,GREATER_EQUAL2=`
return vec4(greaterThanEqual(a, b));
`,LOGICAL_AND2=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,LOGICAL_OR2=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,MAX2=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+CHECK_NAN_SNIPPET2+`
return result;
`,MIN2=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+CHECK_NAN_SNIPPET2+`
return result;
`,MOD2=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+CHECK_NAN_SNIPPET2+`
return result;
2020-11-25 15:13:19 +01:00
`,BinaryOpPackedProgram=class{constructor(op2,aShape,bShape,checkOutOfBounds=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=backend_util_exports.assertAndGetBroadcastShape(aShape,bShape);let rank=this.outputShape.length,checkOutOfBoundsString="";if(checkOutOfBounds)if(rank===0||util_exports.sizeFromShape(this.outputShape)===1)checkOutOfBoundsString=`
2020-11-16 21:51:46 +01:00
result.y = 0.;
result.z = 0.;
result.w = 0.;
2020-11-25 15:13:19 +01:00
`;else{let dtype=getCoordsDataType(rank);if(checkOutOfBoundsString=`
2020-11-16 21:51:46 +01:00
${dtype} coords = getOutputCoords();
`,rank===1)checkOutOfBoundsString+=`
2020-11-16 21:51:46 +01:00
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
2020-11-25 15:13:19 +01:00
`;else{let channels=getChannels("coords",rank);checkOutOfBoundsString+=`
2020-11-16 21:51:46 +01:00
bool nextRowOutOfBounds =
(${channels[rank-2]} + 1) >= ${this.outputShape[rank-2]};
bool nextColOutOfBounds =
(${channels[rank-1]} + 1) >= ${this.outputShape[rank-1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}}this.userCode=`
2020-11-16 21:51:46 +01:00
vec4 binaryOperation(vec4 a, vec4 b) {
2020-11-17 16:18:15 +01:00
${op2}
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${checkOutOfBoundsString}
setOutput(result);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},ClipProgram=class{constructor(aShape){this.variableNames=["A"],this.outputShape=aShape,this.userCode=`
uniform float minVal;
uniform float maxVal;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
2020-11-16 21:51:46 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(clamp(value, minVal, maxVal));
2020-11-12 18:58:55 +01:00
}
2020-12-22 18:34:47 +01:00
`}getCustomSetupFunc(min7,max9){return(gpgpu,webGLProgram)=>{this.minLoc==null&&(this.minLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"minVal"),this.maxLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"maxVal")),gpgpu.gl.uniform1f(this.minLoc,min7),gpgpu.gl.uniform1f(this.maxLoc,max9)}}},ClipPackedProgram=class{constructor(aShape){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=aShape,this.userCode=`
2020-12-16 20:49:14 +01:00
uniform float minVal;
uniform float maxVal;
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
vec4 value = getAAtOutCoords();
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (any(isnan(value))) {
setOutput(value);
return;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
2020-12-15 14:44:42 +01:00
}
2020-12-22 18:34:47 +01:00
`}getCustomSetupFunc(min7,max9){return(gpgpu,webGLProgram)=>{this.minLoc==null&&(this.minLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"minVal"),this.maxLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"maxVal")),gpgpu.gl.uniform1f(this.minLoc,min7),gpgpu.gl.uniform1f(this.maxLoc,max9)}}},ComplexAbsProgram=class{constructor(shape){this.variableNames=["real","imag"],this.outputShape=shape,this.userCode=`
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},Conv2DDerFilterProgram=class{constructor(convInfo){this.variableNames=["x","dy"],this.outputShape=convInfo.filterShape;let strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,padTop=convInfo.padInfo.top,padLeft=convInfo.padInfo.left,isChannelsLast=convInfo.dataFormat==="channelsLast";this.userCode=`
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int b = 0; b < ${convInfo.batchSize}; b++) {
for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {
int xR = wR + yR * ${strideHeight} - ${padTop};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {
int xC = wC + yC * ${strideWidth} - ${padLeft};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (${isChannelsLast}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
}
}
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(dotProd);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},Conv2DDerInputProgram=class{constructor(convInfo){this.variableNames=["dy","W"],this.outputShape=convInfo.inShape;let filterHeight=convInfo.filterHeight,filterWidth=convInfo.filterWidth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,isChannelsLast=convInfo.dataFormat==="channelsLast",padTop=filterHeight-1-convInfo.padInfo.top,padLeft=filterWidth-1-convInfo.padInfo.left,rowDim=isChannelsLast?1:2,colDim=isChannelsLast?2:3,channelDim=isChannelsLast?3:1;this.userCode=`
const ivec2 pads = ivec2(${padTop}, ${padLeft});
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec4 coords = getOutputCoords();
2020-12-15 14:44:42 +01:00
int batch = coords[0];
2020-12-16 20:49:14 +01:00
int d1 = coords[${channelDim}];
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec2 dyCorner = ivec2(coords[${rowDim}], coords[${colDim}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${filterHeight}; wR++) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int wRPerm = ${filterHeight} - 1 - wR;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${filterWidth}; wC++) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int wCPerm = ${filterWidth} - 1 - wC;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int d2 = 0; d2 < ${convInfo.outChannels}; d2++) {
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (${isChannelsLast}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},Conv3DDerFilterProgram=class{constructor(convInfo){this.variableNames=["x","dy"],this.outputShape=convInfo.filterShape;let strideDepth=convInfo.strideDepth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,padFront=convInfo.padInfo.front,padTop=convInfo.padInfo.top,padLeft=convInfo.padInfo.left;this.userCode=`
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float dotProd = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int b = 0; b < ${convInfo.batchSize}; b++) {
for (int yF = 0; yF < ${convInfo.outDepth}; yF++) {
int xF = wF + yF * ${strideDepth} - ${padFront};
if (xF < 0 || xF >= ${convInfo.inDepth}) {
continue;
}
for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {
int xR = wR + yR * ${strideHeight} - ${padTop};
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {
int xC = wC + yC * ${strideWidth} - ${padLeft};
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
2020-11-12 18:17:57 +01:00
}
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(dotProd);
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
`}},Conv3DDerInputProgram=class{constructor(convInfo){this.variableNames=["dy","W"],this.outputShape=convInfo.inShape;let filterDepth=convInfo.filterDepth,filterHeight=convInfo.filterHeight,filterWidth=convInfo.filterWidth,strideDepth=convInfo.strideDepth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,padFront=filterDepth-1-convInfo.padInfo.front,padTop=filterHeight-1-convInfo.padInfo.top,padLeft=filterWidth-1-convInfo.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float dotProd = 0.0;
for (int wF = 0; wF < ${filterDepth}; wF++) {
float dyF = float(dyFCorner + wF) / ${strideDepth}.0;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (dyF < 0.0 || dyF >= ${convInfo.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
int wFPerm = ${filterDepth} - 1 - wF;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${filterHeight}; wR++) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||
fract(dyR) > 0.0) {
2020-11-16 21:51:46 +01:00
continue;
}
2020-12-16 20:49:14 +01:00
int idyR = int(dyR);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int wRPerm = ${filterHeight} - 1 - wR;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${filterWidth}; wC++) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
2020-11-16 21:51:46 +01:00
continue;
}
2020-12-16 20:49:14 +01:00
int idyC = int(dyC);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int wCPerm = ${filterWidth} - 1 - wC;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
for (int d2 = 0; d2 < ${convInfo.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
2020-12-15 14:44:42 +01:00
}
2020-11-16 21:51:46 +01:00
}
2020-11-12 18:58:55 +01:00
}
}
2020-12-16 20:49:14 +01:00
setOutput(dotProd);
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
`}},DepthwiseConv2DDerFilterProgram=class{constructor(convInfo){this.variableNames=["x","dy"],this.outputShape=convInfo.filterShape;let strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,padTop=convInfo.padInfo.top,padLeft=convInfo.padInfo.left,channelMul=convInfo.outChannels/convInfo.inChannels;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${channelMul} + dm;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float dotProd = 0.0;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${convInfo.batchSize}; b++) {
for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {
int xR = wR + yR * ${strideHeight} - ${padTop};
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {
int xC = wC + yC * ${strideWidth} - ${padLeft};
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(dotProd);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},DepthwiseConv2DDerInputProgram=class{constructor(convInfo){this.variableNames=["dy","W"],this.outputShape=convInfo.inShape;let filterHeight=convInfo.filterHeight,filterWidth=convInfo.filterWidth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,padTop=filterHeight-1-convInfo.padInfo.top,padLeft=filterWidth-1-convInfo.padInfo.left,channelMul=convInfo.outChannels/convInfo.inChannels;this.userCode=`
const ivec2 pads = ivec2(${padTop}, ${padLeft});
2020-11-16 21:51:46 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
2020-12-16 20:49:14 +01:00
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float dotProd = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${filterHeight}; wR++) {
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {
2020-11-16 21:51:46 +01:00
continue;
2020-11-08 18:32:31 +01:00
}
2020-12-16 20:49:14 +01:00
int idyR = int(dyR);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int wRPerm = ${filterHeight} - 1 - wR;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${filterWidth}; wC++) {
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
int wCPerm = ${filterWidth} - 1 - wC;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${channelMul}; dm++) {
int d2 = d1 * ${channelMul} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
2020-11-12 18:58:55 +01:00
}
}
2020-12-16 20:49:14 +01:00
setOutput(dotProd);
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
`}},Conv2DProgram=class{constructor(convInfo,addBias=!1,activation2=null,hasPreluActivationWeights=!1){this.variableNames=["x","W"],this.outputShape=convInfo.outShape;let padTop=convInfo.padInfo.top,padLeft=convInfo.padInfo.left,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationHeight=convInfo.dilationHeight,dilationWidth=convInfo.dilationWidth,filterHeight=convInfo.filterHeight,filterWidth=convInfo.filterWidth,inputDepthNearestVec4=Math.floor(convInfo.inChannels/4)*4,inputDepthVec4Remainder=convInfo.inChannels%4,isChannelsLast=convInfo.dataFormat==="channelsLast",rowDim=isChannelsLast?1:2,colDim=isChannelsLast?2:3,channelDim=isChannelsLast?3:1,activationSnippet="",applyActivationSnippet="";activation2&&(hasPreluActivationWeights?activationSnippet=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${activation2}
}`:activationSnippet=`
float activation(float x) {
${activation2}
}
`,applyActivationSnippet="result = activation(result);");let addBiasSnippet=addBias?"result += getBiasAtOutCoords();":"";addBias&&this.variableNames.push("bias"),hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${activationSnippet}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
const ivec2 pads = ivec2(${padTop}, ${padLeft});
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${channelDim}];
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec2 xRCCorner =
ivec2(coords[${rowDim}], coords[${colDim}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${filterHeight}; wR++) {
int xR = xRCorner + wR * ${dilationHeight};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
for (int wC = 0; wC < ${filterWidth}; wC++) {
int xC = xCCorner + wC * ${dilationWidth};
if (xC < 0 || xC >= ${convInfo.inWidth}) {
2020-11-16 21:51:46 +01:00
continue;
}
2020-12-16 20:49:14 +01:00
for (int d1 = 0; d1 < ${inputDepthNearestVec4}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (${isChannelsLast}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (${inputDepthVec4Remainder===1}) {
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (${isChannelsLast}) {
dotProd +=
getX(batch, xR, xC, ${inputDepthNearestVec4}) *
getW(wR, wC, ${inputDepthNearestVec4}, d2);
} else {
dotProd +=
getX(batch, ${inputDepthNearestVec4}, xR, xC) *
getW(wR, wC, ${inputDepthNearestVec4}, d2);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
} else if (${inputDepthVec4Remainder===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${inputDepthNearestVec4}, d2),
getW(wR, wC, ${inputDepthNearestVec4} + 1, d2)
);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (${isChannelsLast}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${inputDepthNearestVec4}),
getX(batch, xR, xC, ${inputDepthNearestVec4} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${inputDepthNearestVec4}, xR, xC),
getX(batch, ${inputDepthNearestVec4} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${inputDepthVec4Remainder===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${inputDepthNearestVec4}, d2),
getW(wR, wC, ${inputDepthNearestVec4} + 1, d2),
getW(wR, wC, ${inputDepthNearestVec4} + 2, d2)
);
if (${isChannelsLast}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${inputDepthNearestVec4}),
getX(batch, xR, xC, ${inputDepthNearestVec4} + 1),
getX(batch, xR, xC, ${inputDepthNearestVec4} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${inputDepthNearestVec4}, xR, xC),
getX(batch, ${inputDepthNearestVec4} + 1, xR, xC),
getX(batch, ${inputDepthNearestVec4} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
2020-11-16 21:51:46 +01:00
}
2020-12-16 20:49:14 +01:00
2020-11-16 21:51:46 +01:00
}
2020-11-12 18:58:55 +01:00
}
}
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float result = dotProd;
${addBiasSnippet}
${applyActivationSnippet}
setOutput(result);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},Conv3DProgram=class{constructor(convInfo){this.variableNames=["x","W"],this.outputShape=convInfo.outShape;let padFront=convInfo.padInfo.front,padTop=convInfo.padInfo.top,padLeft=convInfo.padInfo.left,strideDepth=convInfo.strideDepth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationDepth=convInfo.dilationDepth,dilationHeight=convInfo.dilationHeight,dilationWidth=convInfo.dilationWidth,filterDepth=convInfo.filterDepth,filterHeight=convInfo.filterHeight,filterWidth=convInfo.filterWidth,inputDepthNearestVec4=Math.floor(convInfo.inChannels/4)*4,inputDepthVec4Remainder=convInfo.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
2020-11-16 21:51:46 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
2020-12-16 20:49:14 +01:00
int d2 = coords.u;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${filterDepth}; wF++) {
int xF = xFCorner + wF * ${dilationDepth};
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (xF < 0 || xF >= ${convInfo.inDepth}) {
2020-11-16 21:51:46 +01:00
continue;
2020-11-08 18:32:31 +01:00
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${filterHeight}; wR++) {
int xR = xRCorner + wR * ${dilationHeight};
2020-11-16 21:51:46 +01:00
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${filterWidth}; wC++) {
2020-11-16 21:51:46 +01:00
int xC = xCCorner + wC * ${dilationWidth};
2020-12-16 20:49:14 +01:00
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int d1 = 0; d1 < ${inputDepthNearestVec4}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
dotProd += dot(xValues, wValues);
}
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (${inputDepthVec4Remainder===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${inputDepthNearestVec4}) *
getW(wF, wR, wC, ${inputDepthNearestVec4}, d2);
} else if (${inputDepthVec4Remainder===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),
getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),
getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${inputDepthVec4Remainder===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),
getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1),
getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),
getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2),
getW(wF, wR, wC, ${inputDepthNearestVec4} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
2020-11-12 18:58:55 +01:00
}
}
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(dotProd);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},DepthwiseConv2DProgram=class{constructor(convInfo,addBias=!1,activation2=null,hasPreluActivation=!1){this.variableNames=["x","W"],this.outputShape=convInfo.outShape;let xNumRows=convInfo.inHeight,xNumCols=convInfo.inWidth,padTop=convInfo.padInfo.top,padLeft=convInfo.padInfo.left,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationHeight=convInfo.dilationHeight,dilationWidth=convInfo.dilationWidth,filterHeight=convInfo.filterHeight,filterWidth=convInfo.filterWidth,channelMul=convInfo.outChannels/convInfo.inChannels,activationSnippet="",applyActivationSnippet="";activation2&&(hasPreluActivation?activationSnippet=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${activation2}
}`:activationSnippet=`
float activation(float x) {
${activation2}
}
`,applyActivationSnippet="result = activation(result);");let addBiasSnippet=addBias?"result += getBiasAtOutCoords();":"";addBias&&this.variableNames.push("bias"),hasPreluActivation&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${activationSnippet}
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
2020-11-16 21:51:46 +01:00
const ivec2 pads = ivec2(${padTop}, ${padLeft});
void main() {
ivec4 coords = getOutputCoords();
2020-12-16 20:49:14 +01:00
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${channelMul};
int q = d2 - d1 * ${channelMul};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
2020-11-16 21:51:46 +01:00
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-12-16 20:49:14 +01:00
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${filterHeight}; wR++) {
int xR = xRCorner + wR * ${dilationHeight};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xR < 0 || xR >= ${xNumRows}) {
2020-11-16 21:51:46 +01:00
continue;
2020-11-10 02:13:38 +01:00
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${filterWidth}; wC++) {
int xC = xCCorner + wC * ${dilationWidth};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xC < 0 || xC >= ${xNumCols}) {
2020-11-16 21:51:46 +01:00
continue;
}
2020-12-16 20:49:14 +01:00
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
2020-11-12 18:58:55 +01:00
}
}
2020-12-16 20:49:14 +01:00
float result = dotProd;
${addBiasSnippet}
${applyActivationSnippet}
setOutput(result);
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
`}},DepthwiseConvPacked2DProgram=class{constructor(convInfo,addBias=!1,activation2=null,hasPreluActivation=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=convInfo.outShape;let xNumRows=convInfo.inHeight,xNumCols=convInfo.inWidth,padTop=convInfo.padInfo.top,padLeft=convInfo.padInfo.left,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationHeight=convInfo.dilationHeight,dilationWidth=convInfo.dilationWidth,filterHeight=convInfo.filterHeight,filterWidth=convInfo.filterWidth,texelsAcross=filterWidth,mainLoop="int xR; int xC; int xCOffset;";for(let r=0;r<filterHeight;r++)for(let c=0;c<filterWidth;c++)mainLoop+=`
vec4 xTexelR${r}C${c*2} = vec4(0.);
vec4 wR${r}C${c} = vec4(0.);
vec4 xR${r}C${c} = vec4(0.);`;for(let r=0;r<filterHeight;r++)for(let texelC=0;texelC<texelsAcross;texelC++){let c=texelC*2;if(mainLoop+=`
xR = xRCorner + ${r*dilationHeight};
xC = xCCorner + ${c*dilationWidth};
`,strideWidth===1){if(c<filterWidth&&(padLeft%2===1?mainLoop+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < ${xNumRows} && xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xCOffset, d1);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${xNumCols}) {
xTexelR${r}C${c}.zw = vec2(0.);
}
} else {
xTexelR${r}C${c} = vec4(0.);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
xCOffset = xC + 1 - 2;
if(xR >= 0 && xR < ${xNumRows} && xCOffset >= 0 && xCOffset < ${xNumCols}) {
vec4 previous = getX(batch, xR, xCOffset, d1);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${xNumCols}) {
previous.zw = vec2(0.);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
xR${r}C${c} = vec4(previous.zw, xTexelR${r}C${c}.xy);
} else {
xR${r}C${c} = vec4(0, 0, xTexelR${r}C${c}.xy);
}
`:mainLoop+=`
if(xR >= 0 && xR < ${xNumRows} && xC >= 0 && xC < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xC, d1);
} else {
xTexelR${r}C${c} = vec4(0.);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
xR${r}C${c} = xTexelR${r}C${c};
`,c+1<filterWidth)){let nextTexelOffset=padLeft%2===0?util_exports.nearestLargerEven(dilationWidth):dilationWidth;dilationWidth%2===0&&padLeft%2===1||dilationWidth%2!==0&&padLeft%2!==1?(mainLoop+=`
xCOffset = xC + ${padLeft%2} + ${nextTexelOffset};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if(xR >= 0 && xR < ${xNumRows} &&
xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c+2} = getX(batch, xR, xCOffset, d1);
}
`,dilationWidth>1&&(mainLoop+=`
xCOffset -= 2;
if(xR >= 0 && xR < ${xNumRows} &&
xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${r}C${c} = vec4(0.);
}
`),mainLoop+=`
xR${r}C${c+1} = vec4(
xTexelR${r}C${c}.zw, xTexelR${r}C${c+2}.xy);
`):mainLoop+=`
xCOffset = xC + ${nextTexelOffset};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if(xR >= 0 && xR < ${xNumRows} &&
xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c+2} = getX(batch, xR, xCOffset, d1);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
xR${r}C${c+1} = xTexelR${r}C${c+2};
`}}else c<filterWidth&&(mainLoop+=`
if(xR >= 0 && xR < ${xNumRows}) {
`,padLeft%2===1?(mainLoop+=`
xCOffset = xC + 1 - ${strideWidth};
if(xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${r}C${c} = vec4(0.);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if(xC + 1 >= 0 && xC + 1 < ${xNumCols}) {
xTexelR${r}C${c+2} = getX(batch, xR, xC + 1, d1);
} else {
xTexelR${r}C${c+2} = vec4(0.);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
xR${r}C${c} = vec4(
xTexelR${r}C${c}.zw, xTexelR${r}C${c+2}.zw);
`,c+1<filterWidth&&(mainLoop+=`
vec4 final = vec4(0.);
xCOffset = xC + 1 + ${strideWidth};
if(xCOffset >= 0 && xCOffset < ${xNumCols}) {
final = getX(batch, xR, xCOffset, d1);
}
xR${r}C${c+1} = vec4(xTexelR${r}C${c+2}.xy, final.xy);
`)):(mainLoop+=`
if(xC >= 0 && xC < ${xNumCols}) {
xTexelR${r}C${c} = getX(batch, xR, xC, d1);
} else {
xTexelR${r}C${c} = vec4(0.);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
xCOffset = xC + ${strideWidth};
if(xCOffset >= 0 && xCOffset < ${xNumCols}) {
xTexelR${r}C${c+2} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${r}C${c+2} = vec4(0.);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
xR${r}C${c} = vec4(
xTexelR${r}C${c}.xy, xTexelR${r}C${c+2}.xy);
`,c+1<filterWidth&&(mainLoop+=`
xR${r}C${c+1} = vec4(
xTexelR${r}C${c}.zw, xTexelR${r}C${c+2}.zw);
`)),mainLoop+="}");c<filterWidth&&(mainLoop+=`
vec4 wTexelR${r}C${c} = getW(${r}, ${c}, d1, q);
wR${r}C${c} = vec4(wTexelR${r}C${c}.xz, wTexelR${r}C${c}.xz);
`,c+1<filterWidth&&(mainLoop+=`
vec4 wTexelR${r}C${c+1} = getW(${r}, ${c+1}, d1, q);
wR${r}C${c+1} =
vec4(wTexelR${r}C${c+1}.xz, wTexelR${r}C${c+1}.xz);`))}for(let r=0;r<filterHeight;r++)for(let c=0;c<filterWidth;c++)mainLoop+=`dotProd += xR${r}C${c} * wR${r}C${c};`;let activationSnippet="",applyActivationSnippet="";activation2&&(hasPreluActivation?activationSnippet=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${activation2}
}`:activationSnippet=`vec4 activation(vec4 x) {
${activation2}
}`,applyActivationSnippet="result = activation(result);");let addBiasSnippet=addBias?"result += getBiasAtOutCoords();":"";addBias&&this.variableNames.push("bias"),hasPreluActivation&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${activationSnippet}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
const ivec2 pads = ivec2(${padTop}, ${padLeft});
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2;
int q = 0;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
vec4 dotProd = vec4(0.);
${mainLoop}
vec4 result = dotProd;
${addBiasSnippet}
${applyActivationSnippet}
2020-12-15 14:44:42 +01:00
setOutput(result);
}
2020-12-16 20:49:14 +01:00
`}},CropAndResizeProgram=class{constructor(imageShape,boxShape,cropSize,method,extrapolationValue){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[batch,imageHeight,imageWidth,depth]=imageShape,[numBoxes]=boxShape,[cropHeight,cropWidth]=cropSize;this.outputShape=[numBoxes,cropHeight,cropWidth,depth];let methodId=method==="bilinear"?1:0,[inputHeightFloat,inputWidthFloat]=[`${imageHeight-1}.0`,`${imageWidth-1}.0`],[heightRatio,heightScale,inY]=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}`],[widthRatio,widthScale,inX]=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}`];this.userCode=`
const float height_ratio = float(${heightRatio});
const float width_ratio = float(${widthRatio});
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${batch}) {
2020-12-15 14:44:42 +01:00
return;
2020-11-10 02:13:38 +01:00
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float height_scale = ${heightScale};
float width_scale = ${widthScale};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float in_y = ${inY};
if( in_y < 0.0 || in_y > ${inputHeightFloat} ) {
setOutput(float(${extrapolationValue}));
return;
}
float in_x = ${inX};
if( in_x < 0.0 || in_x > ${inputWidthFloat} ) {
setOutput(float(${extrapolationValue}));
2020-12-15 14:44:42 +01:00
return;
2020-11-10 02:13:38 +01:00
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${methodId} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
2020-11-12 18:58:55 +01:00
}
2020-12-22 18:34:47 +01:00
`}},CumSumProgram=class{constructor(shape,exclusive,reverse11){this.variableNames=["x"],this.outputShape=shape;let rank=shape.length,val=exclusive?"0.0":`getX(${getCoords(rank,"coords")})`,length=shape[shape.length-1],condition="",idxString="";exclusive?(condition=reverse11?`end != ${length-1}`:"end != 0",idxString=reverse11?"end + 1":"end - 1"):(condition=reverse11?`end + pow2 < ${length}`:"end >= pow2",idxString=reverse11?"end + pow2":"end - pow2"),this.userCode=`
2020-12-16 20:49:14 +01:00
uniform float index;
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
${getCoordsDataType(rank)} coords = getOutputCoords();
int end = ${getFinalCoord(rank,"coords")};
float val = ${val};
int pow2 = int(pow(2.0, index));
if (${condition}) {
int idx = ${idxString};
${getFinalCoord(rank,"coords")} = idx;
val += getX(${getCoords(rank,"coords")});
}
setOutput(val);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}getCustomSetupFunc(index){return(gpgpu,webGLProgram)=>{this.index==null&&(this.index=gpgpu.getUniformLocation(webGLProgram,"index")),gpgpu.gl.uniform1f(this.index,index)}}};function getCoords(rank,name){if(rank===1)return`${name}`;if(rank===2)return`${name}.x, ${name}.y`;if(rank===3)return`${name}.x, ${name}.y, ${name}.z`;if(rank===4)return`${name}.x, ${name}.y, ${name}.z, ${name}.w`;throw Error(`Cumulative sum for rank ${rank} is not yet supported`)}function getFinalCoord(rank,name){if(rank===1)return`${name}`;if(rank===2)return`${name}.y`;if(rank===3)return`${name}.z`;if(rank===4)return`${name}.w`;throw Error(`Cumulative sum for rank ${rank} is not yet supported`)}var DecodeMatrixProgram=class{constructor(outputShape){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=PackingScheme.DENSE;let texShape=getDenseTexShape(outputShape),glsl=getGlslDifferences();this.outputShape=outputShape,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${getLogicalCoordinatesFromFlatIndex(["r","c","d"],outputShape)}
return ivec3(r, c, d);
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = 4 * (resTexRC.x * ${texShape[1]} + resTexRC.y);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 result = vec4(0.);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${glsl.output} = result;
}
`}},DecodeMatrixPackedProgram=class{constructor(outputShape){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=PackingScheme.DENSE;let texShape=getDenseTexShape(outputShape),glsl=getGlslDifferences();this.outputShape=outputShape,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${getLogicalCoordinatesFromFlatIndex(["r","c","d"],outputShape)}
return ivec3(r, c, d);
2020-11-12 18:58:55 +01:00
}
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${texShape[0]}, ${texShape[1]}));
int index = 4 * (resTexRC.x * ${texShape[1]} + resTexRC.y);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 result = vec4(0.);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${glsl.output} = result;
}
`}},DepthToSpaceProgram=class{constructor(outputShape,blockSize,dataFormat){this.variableNames=["x"],this.outputShape=[],this.outputShape=outputShape,this.blockSize=blockSize,this.dataFormat=dataFormat,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int in_h = h / ${blockSize};
int offset_h = imod(h, ${blockSize});
int in_w = w / ${blockSize};
int offset_w = imod(w, ${blockSize});
int offset_d = (offset_h * ${blockSize} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}},DiagProgram=class{constructor(size){this.variableNames=["X"],this.outputShape=[size,size],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`}},EncodeFloatProgram=class{constructor(outputShape){this.variableNames=["A"],this.outTexUsage=TextureUsage.DOWNLOAD;let glsl=getGlslDifferences();this.outputShape=outputShape,this.userCode=`
${ENCODE_FLOAT_SNIPPET}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
float x = getAAtOutCoords();
${glsl.output} = encode_float(x);
}
`}},EncodeFloatPackedProgram=class{constructor(outputShape){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=TextureUsage.DOWNLOAD;let glsl=getGlslDifferences();this.outputShape=outputShape,this.userCode=`
${ENCODE_FLOAT_SNIPPET}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${glsl.output} = encode_float(x);
}
`}},EncodeMatrixProgram=class{constructor(outputShape,texShape,inputIsUnsignedByte=!1){this.variableNames=["A"];let glsl=getGlslDifferences(),[height,width]=texShape;this.outputShape=outputShape;let output="result";inputIsUnsignedByte&&(output="floor(result * 255. + 0.5)"),this.userCode=`
${getFlatIndexFrom3D(outputShape)}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
ivec3 coords = getOutputCoords();
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
flatIndex = idiv(flatIndex, 4, 1.);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int r = flatIndex / ${width};
int c = imod(flatIndex, ${width});
vec2 uv = (vec2(c, r) + halfCR) / vec2(${width}.0, ${height}.0);
vec4 values = ${glsl.texture2D}(A, uv);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float result;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
2020-11-08 18:32:31 +01:00
}
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
${glsl.output} = vec4(${output}, 0., 0., 0.);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},EncodeMatrixPackedProgram=class{constructor(outputShape,texShape,inputIsUnsignedByte=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let glsl=getGlslDifferences(),[height,width]=texShape;this.outputShape=outputShape;let mainLoop="",output="result";inputIsUnsignedByte&&(output="floor(result * 255. + 0.5)");for(let row=0;row<=1;row++)for(let col=0;col<=1;col++){let channel=row*2+col;mainLoop+=`
localCoords = coords;
if(localCoords[2] + ${col} < ${outputShape[2]}) {
localCoords[2] += ${col};
if(localCoords[1] + ${row} < ${outputShape[1]}) {
localCoords[1] += ${row};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
flatIndex = idiv(flatIndex, 4, 1.);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
r = flatIndex / ${width};
c = imod(flatIndex, ${width});
uv = (vec2(c, r) + halfCR) / vec2(${width}.0, ${height}.0);
values = ${glsl.texture2D}(A, uv);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if(offset == 0) {
result[${channel}] = values[0];
} else if(offset == 1) {
result[${channel}] = values[1];
} else if(offset == 2) {
result[${channel}] = values[2];
} else {
result[${channel}] = values[3];
}
}
2020-11-16 21:51:46 +01:00
}
2020-12-16 20:49:14 +01:00
`}this.userCode=`
${getFlatIndexFrom3D(outputShape)}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
ivec3 coords = getOutputCoords();
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${mainLoop}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${glsl.output} = ${output};
}
`}},FillProgram=class{constructor(shape,value){this.outputShape=[],this.variableNames=["x"],this.outputShape=shape,this.userCode=`
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`}getCustomSetupFunc(value){return(gpgpu,webGLProgram)=>{this.valueLoc==null&&(this.valueLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"value")),gpgpu.gl.uniform1f(this.valueLoc,value)}}},GatherProgram=class{constructor(aShape,indicesLength,axis){this.variableNames=["A","indices"];let outputShape=aShape.slice();outputShape[axis]=indicesLength,this.outputShape=outputShape,this.rank=outputShape.length;let dtype=getCoordsDataType(this.rank),sourceCoords=getSourceCoords2(aShape,axis);this.userCode=`
void main() {
${dtype} resRC = getOutputCoords();
setOutput(getA(${sourceCoords}));
}
`}};function getSourceCoords2(aShape,axis){let rank=aShape.length;if(rank>4)throw Error(`Gather for rank ${rank} is not yet supported`);if(rank===1)return"int(getIndices(resRC))";let currentCoords=["resRC.x","resRC.y","resRC.z","resRC.w"],sourceCoords=[];for(let i=0;i<aShape.length;i++)i===axis?sourceCoords.push(`int(getIndices(${currentCoords[i]}))`):sourceCoords.push(`${currentCoords[i]}`);return sourceCoords.join()}var GatherNDProgram=class{constructor(sliceDim,strides,shape){this.sliceDim=sliceDim,this.strides=strides,this.variableNames=["x","indices"],this.outputShape=shape;let stridesType=getCoordsDataType(strides.length),dtype=getCoordsDataType(shape.length),strideString=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${stridesType} strides = ${stridesType}(${this.strides});
void main() {
${dtype} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${strideString};
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(getX(flattenIndex, coords[1]));
2020-11-08 18:32:31 +01:00
}
2020-12-16 20:49:14 +01:00
`}},gpgpu_util_exports={};__export2(gpgpu_util_exports,{bindVertexProgramAttributeStreams:()=>bindVertexProgramAttributeStreams,createBufferFromOutputTexture:()=>createBufferFromOutputTexture,createFloat16MatrixTexture:()=>createFloat16MatrixTexture,createFloat16PackedMatrixTexture:()=>createFloat16PackedMatrixTexture,createFloat32MatrixTexture:()=>createFloat32MatrixTexture,createIndexBuffer:()=>createIndexBuffer,createPackedMatrixTexture:()=>createPackedMatrixTexture,createUnsignedBytesMatrixTexture:()=>createUnsignedBytesMatrixTexture,createVertexBuffer:()=>createVertexBuffer,createVertexShader:()=>createVertexShader2,downloadByteEncodedFloatMatrixFromOutputTexture:()=>downloadByteEncodedFloatMatrixFromOutputTexture,downloadFloat32MatrixFromBuffer:()=>downloadFloat32MatrixFromBuffer,downloadMatrixFromPackedOutputTexture:()=>downloadMatrixFromPackedOutputTexture,downloadPackedMatrixFromBuffer:()=>downloadPackedMatrixFromBuffer,getInternalFormatForFloat16MatrixTexture:()=>getInternalFormatForFloat16MatrixTexture,getInternalFormatForFloat16PackedMatrixTexture:()=>getInternalFormatForFloat16PackedMatrixTexture,getInternalFormatForFloat32MatrixTexture:()=>getInternalFormatForFloat32MatrixTexture,getInternalFormatForPackedMatrixTexture:()=>getInternalFormatForPackedMatrixTexture,getInternalFormatForUnsignedBytesMatrixTexture:()=>getInternalFormatForUnsignedBytesMatrixTexture,uploadDenseMatrixToTexture:()=>uploadDenseMatrixToTexture,uploadPixelDataToTexture:()=>uploadPixelDataToTexture});function createVertexShader2(gl){let glsl=getGlslDifferences(),vertexShaderSource=`${glsl.version}
precision highp float;
${glsl.attribute} vec3 clipSpacePos;
${glsl.attribute} vec2 uv;
${glsl.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
2020-12-22 18:34:47 +01:00
}`;return createVertexShader(gl,vertexShaderSource)}function createVertexBuffer(gl){let 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){let triangleVertexIndices=new Uint16Array([0,1,2,2,1,3]);return createStaticIndexBuffer(gl,triangleVertexIndices)}function createAndConfigureTexture(gl,width,height,internalFormat,textureFormat,textureType){validateTextureSize(width,height);let texture=createTexture(gl),tex2d=gl.TEXTURE_2D;return callAndCheck(gl,()=>gl.bindTexture(tex2d,texture)),callAndCheck(gl,()=>gl.texParameteri(tex2d,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE)),callAndCheck(gl,()=>gl.texParameteri(tex2d,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE)),callAndCheck(gl,()=>gl.texParameteri(tex2d,gl.TEXTURE_MIN_FILTER,gl.NEAREST)),callAndCheck(gl,()=>gl.texParameteri(tex2d,gl.TEXTURE_MAG_FILTER,gl.NEAREST)),callAndCheck(gl,()=>gl.texImage2D(tex2d,0,internalFormat,width,height,0,textureFormat,textureType,null)),callAndCheck(gl,()=>gl.bindTexture(gl.TEXTURE_2D,null)),texture}function getInternalFormatForFloat32MatrixTexture(textureConfig){return textureConfig.internalFormatFloat}function createFloat32MatrixTexture(gl,rows,columns,textureConfig){let[width,height]=getUnpackedMatrixTextureShapeWidthHeight(rows,columns);return createAndConfigureTexture(gl,width,height,getInternalFormatForFloat32MatrixTexture(textureConfig),textureConfig.textureFormatFloat,gl.FLOAT)}function getInternalFormatForFloat16MatrixTexture(textureConfig){return textureConfig.internalFormatHalfFloat}function createFloat16MatrixTexture(gl,rows,columns,textureConfig){let[width,height]=getUnpackedMatrixTextureShapeWidthHeight(rows,columns);return createAndConfigureTexture(gl,width,height,getInternalFormatForFloat16MatrixTexture(textureConfig),textureConfig.textureFormatFloat,textureConfig.textureTypeHalfFloat)}function getInternalFormatForUnsignedBytesMatrixTexture(textureConfig){return textureConfig.downloadTextureFormat}function createUnsignedBytesMatrixTexture(gl,rows,columns,textureConfig){let[width,height]=getUnpackedMatrixTextureShapeWidthHeight(rows,columns);return createAndConfigureTexture(gl,width,height,getInternalFormatForUnsignedBytesMatrixTexture(textureConfig),gl.RGBA,gl.UNSIGNED_BYTE)}function getInternalFormatForPackedMatrixTexture(textureConfig){return textureConfig.internalFormatPackedFloat}function createPackedMatrixTexture(gl,rows,columns,textureConfig){let[width,height]=getPackedMatrixTextureShapeWidthHeight(rows,columns);return createAndConfigureTexture(gl,width,height,getInternalFormatForPackedMatrixTexture(textureConfig),gl.RGBA,gl.FLOAT)}function getInternalFormatForFloat16PackedMatrixTexture(textureConfig){return textureConfig.internalFormatPackedHalfFloat}function createFloat16PackedMatrixTexture(gl,rows,columns,textureConfig){let[width,height]=getPackedMatrixTextureShapeWidthHeight(rows,columns);return createAndConfigureTexture(gl,width,height,getInternalFormatForFloat16PackedMatrixTexture(textureConfig),gl.RGBA,textureConfig.textureTypeHalfFloat)}function bindVertexProgramAttributeStreams(gl,program,vertexBuffer){let posOffset=0,uvOffset=3*4,stride=3*4+2*4;callAndCheck(gl,()=>gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer));let 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,data2,textureConfig){callAndCheck(gl,()=>gl.bindTexture(gl.TEXTURE_2D,texture));let dataForUpload,texelDataType,internalFormat;data2 instanceof Uint8Array?(dataForUpload=new Uint8Array(width*height*4),texelDataType=gl.UNSIGNED_BYTE,internalFormat=gl.RGBA):(dataForUpload=new Float32Array(width*height*4),texelDataType=gl.FLOAT,internalFormat=textureConfig.internalFormatPackedFloat),dataForUpload.set(data2),callAndCheck(gl,()=>gl.texImage2D(gl.TEXTURE_2D,0,internalFormat,width,height,0,gl.RGBA,texelDataType,dataForUpload)),callAndCheck(gl,()=>gl.bindTexture(gl.TE
2020-12-15 14:44:42 +01:00
blockIndex = rc.y + ${col};
pos = rc.x + ${row};
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
if(blockIndex < ${outputShape[1]} && pos < ${outputShape[0]}) {
offsetY = int(blockIndex / (${outWidth})) * ${strideHeight} - ${top};
d0 = offsetY + ${dilationHeight} * (pos / ${itemsPerBlockRow});
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
if(d0 < ${inputShape[rowDim]} && d0 >= 0) {
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
offsetX = int(mod(float(blockIndex), ${outWidth}.) * ${strideWidth}. - ${left}.);
d1 = offsetX + ${dilationWidth} * (int(mod(float(pos), ${itemsPerBlockRow}.) / ${inChannels}.));
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
if(d1 < ${inputShape[colDim]} && d1 >= 0) {
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
ch = int(mod(float(pos), ${inChannels}.));
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
if (${isChannelsLast}) {
innerDims = vec2(d1, ch);
result[${row*2+col}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${row*2+col}] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
2020-11-16 21:51:46 +01:00
}
2020-12-15 14:44:42 +01:00
`;this.userCode=`
2020-11-16 21:51:46 +01:00
void main() {
2020-12-15 14:44:42 +01:00
ivec2 rc = getOutputCoords();
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
vec4 result = vec4(0);
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
${unrolled}
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
${glsl.output} = result;
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},LRNProgram=class{constructor(xShape,radius,bias,alpha,beta){this.variableNames=["x"],this.outputShape=[];let rad=radius,maxD=xShape[3]-1;this.outputShape=xShape;let powOperator,basis=`float(${bias}) + float(${alpha}) * sum`;beta===.5?powOperator=`inversesqrt(${basis})`:beta===1?powOperator=`1.0/(${basis})`:powOperator=`exp(log(${basis}) * float(-${beta}));`,this.userCode=`
2020-11-16 21:51:46 +01:00
void main() {
2020-12-15 14:44:42 +01:00
ivec4 coords = getOutputCoords();
2020-12-16 20:49:14 +01:00
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${rad}; j <= ${rad}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${maxD}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${powOperator};
setOutput(val);
}
`}},LRNGradProgram=class{constructor(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=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${depthRadius})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${depthRadius} + 1)));
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
2020-11-16 21:51:46 +01:00
continue;
}
2020-12-16 20:49:14 +01:00
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
norm = float(${alpha}) * norm + float(${bias});
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${alpha})
* float(${beta})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${beta});
2020-11-16 21:51:46 +01:00
}
2020-12-16 20:49:14 +01:00
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
2020-11-16 21:51:46 +01:00
}
2020-12-16 20:49:14 +01:00
}
else {
break;
}
}
}
setOutput(result);
}
`}},LRNPackedProgram=class{constructor(xShape,radius,bias,alpha,beta){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let rad=radius,maxD=xShape[3]-1;this.outputShape=xShape;let powOperator,basis=`float(${bias}) + float(${alpha}) * sum`;beta===.5?powOperator=`inversesqrt(${basis})`:beta===1?powOperator=`1.0/(${basis})`:powOperator=`exp(log(${basis}) * float(-${beta}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${rad};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${rad}; j <= ${rad}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${maxD}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
2020-11-16 21:51:46 +01:00
}
2020-12-16 20:49:14 +01:00
cache.xy = z.yw;
sum += z * z;
2020-11-16 21:51:46 +01:00
}
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
vec4 result = xAtOutputCoords * ${powOperator};
setOutput(result);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},MaxPool2DBackpropProgram=class{constructor(convInfo){this.variableNames=["dy","maxPos"],this.outputShape=convInfo.inShape;let strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationHeight=convInfo.dilationHeight,effectiveFilterHeight=convInfo.effectiveFilterHeight,effectiveFilterWidth=convInfo.effectiveFilterWidth,padTop=effectiveFilterHeight-1-convInfo.padInfo.top,padLeft=effectiveFilterWidth-1-convInfo.padInfo.left,lastIndex=effectiveFilterHeight*effectiveFilterWidth-1;this.userCode=`
2020-11-16 21:51:46 +01:00
const ivec2 pads = ivec2(${padTop}, ${padLeft});
void main() {
ivec4 coords = getOutputCoords();
2020-12-16 20:49:14 +01:00
int b = coords[0];
int d = coords[3];
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
2020-12-15 14:44:42 +01:00
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
2020-12-15 14:44:42 +01:00
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {
2020-11-16 21:51:46 +01:00
continue;
}
2020-12-15 14:44:42 +01:00
int idyR = int(dyR);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${effectiveFilterWidth}; wC++) {
2020-12-15 14:44:42 +01:00
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${lastIndex} - int(getMaxPos(b, idyR, idyC, d));
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${effectiveFilterWidth} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
dotProd += dyValue * mask;
2020-11-16 21:51:46 +01:00
}
2020-11-10 02:13:38 +01:00
}
2020-12-15 14:44:42 +01:00
setOutput(dotProd);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},MaxPool3DBackpropProgram=class{constructor(convInfo){this.variableNames=["dy","maxPos"],this.outputShape=convInfo.inShape;let strideDepth=convInfo.strideDepth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationDepth=convInfo.dilationDepth,dilationHeight=convInfo.dilationHeight,dilationWidth=convInfo.dilationWidth,effectiveFilterDepth=convInfo.effectiveFilterDepth,effectiveFilterHeight=convInfo.effectiveFilterHeight,effectiveFilterWidth=convInfo.effectiveFilterWidth,padFront=effectiveFilterDepth-1-convInfo.padInfo.front,padTop=effectiveFilterHeight-1-convInfo.padInfo.top,padLeft=effectiveFilterWidth-1-convInfo.padInfo.left,lastIndex=effectiveFilterDepth*effectiveFilterHeight*effectiveFilterWidth-1;this.userCode=`
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
2020-12-15 14:44:42 +01:00
void main() {
ivec5 coords = getOutputCoords();
2020-12-16 20:49:14 +01:00
int batch = coords.x;
int ch = coords.u;
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
2020-12-16 20:49:14 +01:00
int dyDCorner = dyCorner.x;
2020-12-15 14:44:42 +01:00
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
2020-12-15 14:44:42 +01:00
float dotProd = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wD = 0; wD < ${effectiveFilterDepth};
wD += ${dilationDepth}) {
float dyD = float(dyDCorner + wD) / ${strideDepth}.0;
if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {
2020-11-16 21:51:46 +01:00
continue;
}
2020-12-16 20:49:14 +01:00
int idyD = int(dyD);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
2020-12-15 14:44:42 +01:00
float dyR = float(dyRCorner + wR) / ${strideHeight}.0;
if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||
2020-12-16 20:49:14 +01:00
fract(dyR) > 0.0) {
2020-11-16 21:51:46 +01:00
continue;
}
2020-12-15 14:44:42 +01:00
int idyR = int(dyR);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${effectiveFilterWidth};
wC += ${dilationWidth}) {
2020-12-15 14:44:42 +01:00
float dyC = float(dyCCorner + wC) / ${strideWidth}.0;
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${lastIndex} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${effectiveFilterHeight} * ${effectiveFilterWidth} +
wR * ${effectiveFilterWidth} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
2020-11-16 21:51:46 +01:00
}
}
2020-11-10 02:13:38 +01:00
}
2020-12-15 14:44:42 +01:00
setOutput(dotProd);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},MatMulPackedProgram=class{constructor(aShape,bShape,outputShape,transposeA=!1,transposeB=!1,addBias=!1,activation2=null,hasPreluActivation=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=outputShape;let sharedDim=transposeA?aShape[1]:aShape[2],sharedDimensionPacked=Math.ceil(sharedDim/2),aSample=transposeA?"i * 2, rc.y":"rc.y, i * 2",bSample=transposeB?"rc.z, i * 2":"i * 2, rc.z",aSwizzle=transposeA?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],bSwizzle=transposeB?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],activationSnippet="",applyActivationSnippet="";activation2&&(hasPreluActivation?activationSnippet=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${activation2}
}`:activationSnippet=`vec4 activation(vec4 x) {
${activation2}
}`,applyActivationSnippet="result = activation(result);");let addBiasSnippet=addBias?"result += getBiasAtOutCoords();":"";addBias&&this.variableNames.push("bias"),hasPreluActivation&&this.variableNames.push("preluActivationWeights");let batchASnippet="rc.x",batchBSnippet="rc.x";aShape[0]<bShape[0]?batchASnippet=`int(min(float(rc.x), ${aShape[0]-1}.))`:bShape[0]<aShape[0]&&(batchBSnippet=`int(min(float(rc.x), ${bShape[0]-1}.))`),this.userCode=`
${activationSnippet}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
const float sharedDimension = ${sharedDimensionPacked}.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${sharedDimensionPacked}; i++) {
int batchA = ${batchASnippet};
int batchB = ${batchBSnippet};
vec4 a = getMatrixA(batchA, ${aSample});
vec4 b = getMatrixB(batchB, ${bSample});
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${aSwizzle[0]} * ${bSwizzle[0]});
result += (${aSwizzle[1]} * ${bSwizzle[1]});
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
return result;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${addBiasSnippet}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${applyActivationSnippet}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
setOutput(result);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},MultinomialProgram=class{constructor(batchSize,numOutcomes,numSamples){this.variableNames=["probs"],this.outputShape=[batchSize,numSamples],this.userCode=`
uniform float seed;
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec2 coords = getOutputCoords();
int batch = coords[0];
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float r = random(seed);
float cdf = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int i = 0; i < ${numOutcomes-1}; i++) {
cdf += getProbs(batch, i);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (r < cdf) {
setOutput(float(i));
return;
}
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// If no other event happened, last event happened.
setOutput(float(${numOutcomes-1}));
}
`}getCustomSetupFunc(seed){return(gpgpu,webGLProgram)=>{this.seedLoc==null&&(this.seedLoc=gpgpu.getUniformLocation(webGLProgram,"seed")),gpgpu.gl.uniform1f(this.seedLoc,seed)}}},OneHotProgram=class{constructor(numIndices,depth,onValue,offValue){this.variableNames=["indices"],this.outputShape=[numIndices,depth],this.userCode=`
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${offValue}), float(${onValue}),
float(index == coords.y)));
}
`}},PackProgram=class{constructor(outputShape){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=outputShape;let rank=outputShape.length;if(rank===0)this.userCode=`
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{let channels=getChannels("rc",rank),dtype=getCoordsDataType(rank),outOfBoundsCondition=getOutOfBoundsCondition(rank,outputShape,channels),setup38=getSetup(rank,outputShape[outputShape.length-1],outputShape[outputShape.length-2],channels),output=getOutput(outputShape,channels);this.userCode=`
void main() {
${dtype} rc = getOutputCoords();
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if(${outOfBoundsCondition}) {
setOutput(vec4(0));
} else {
${setup38}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
setOutput(vec4(${output}));
2020-11-16 21:51:46 +01:00
}
2020-12-16 20:49:14 +01:00
}
`}}};function getSourceCoordsArr(rank,dims){let coords2=[];for(let row=0;row<=1;row++)for(let col=0;col<=1;col++){let coord=`${row===0?"r":"rp1"}, ${col===0?"c":"cp1"}`;for(let d=2;d<rank;d++)coord=`${dims[dims.length-1-d]},`+coord;coords2.push(coord)}return coords2}function getOutOfBoundsCondition(rank,shape,dims){if(rank===1)return`rc > ${shape[0]}`;let cond="";for(let i=rank-2;i<rank;i++)cond+=`${dims[i]} >= ${shape[i]}`,i<rank-1&&(cond+="||");return cond}function getSetup(rank,cols,rows,dims){if(rank===1)return"";let innerDims=dims.slice(-2);return`
int r = ${innerDims[0]};
int c = ${innerDims[1]};
int rp1 = r + 1;
int cp1 = c + 1;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
bool cEdge = cp1 >= ${cols};
bool rEdge = rp1 >= ${rows};
`}function getOutput(shape,dims){let rank=shape.length,sourceCoords=getSourceCoordsArr(rank,dims);return rank===1?`getA(rc),
rc + 1 >= ${shape[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${sourceCoords[0]}),
cEdge ? 0. : getA(${sourceCoords[1]}),
rEdge ? 0. : getA(${sourceCoords[2]}),
rEdge || cEdge ? 0. : getA(${sourceCoords[3]})`}var PadProgram=class{constructor(xShape,paddings,constantValue){this.variableNames=["x"],this.outputShape=paddings.map((p2,i)=>p2[0]+xShape[i]+p2[1]);let rank=xShape.length,type=getCoordsDataType(rank),start=paddings.map(p2=>p2[0]).join(","),end=paddings.map((p2,i)=>p2[0]+xShape[i]).join(","),unpackedCoords=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,rank);if(rank===1){this.userCode=`
int start = ${start};
int end = ${end};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(${constantValue}));
} else {
setOutput(getX(outC - start));
2020-11-16 21:51:46 +01:00
}
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`;return}this.userCode=`
${type} start = ${type}(${start});
${type} end = ${type}(${end});
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
${type} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(float(${constantValue}));
} else {
${type} coords = outC - start;
setOutput(getX(${unpackedCoords}));
}
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
`}},PadPackedProgram=class{constructor(xShape,paddings,constantValue){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=paddings.map((p2,i)=>p2[0]+xShape[i]+p2[1]);let rank=xShape.length,dtype=getCoordsDataType(rank),start=paddings.map(p2=>p2[0]).join(","),end=paddings.map((p2,i)=>p2[0]+xShape[i]).join(","),coords2=getChannels("rc",rank),source=getChannels("source",rank),cLimit=`${coords2[rank-1]} < ${this.outputShape[rank-1]}`,innerDims=rank===1?"source":`vec2(${source.slice(-2).join()})`,componentSetup=[`${dtype} rc = outputLoc;`,`${coords2[rank-1]} += 1;
if(${cLimit}) {
`,rank===1?"":`}
rc = outputLoc;
${coords2[rank-2]} += 1;
if(${coords2[rank-2]} < ${this.outputShape[rank-2]}) {`,rank===1?"":` ${coords2[rank-1]} += 1;
if(${cLimit}) {`],paddingArea=rank===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",mainLoop="";for(let i=0,j=rank===1?2:4;i<j;i++)mainLoop+=`
${componentSetup[i]}
if (${paddingArea}) {
result[${i}] = float(${constantValue});
} else {
${dtype} source = rc - start;
result[${i}] = getChannel(getX(${source.join()}), ${innerDims});
}
`;mainLoop+=rank===1?"} ":"}}",this.userCode=`
const ${dtype} start = ${dtype}(${start});
const ${dtype} end = ${dtype}(${end});
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
${dtype} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${mainLoop}
setOutput(result);
}
`}},Pool2DProgram=class{constructor(convInfo,poolType,computePositions,flattenPositions=!1,includeBatchInIndex=!1){if(this.variableNames=["x"],poolType==="avg"&&computePositions)throw new Error("Cannot compute positions for average pool.");let filterWidth=convInfo.filterWidth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationHeight=convInfo.dilationHeight,dilationWidth=convInfo.dilationWidth,effectiveFilterHeight=convInfo.effectiveFilterHeight,effectiveFilterWidth=convInfo.effectiveFilterWidth,padTop=convInfo.padInfo.top,padLeft=convInfo.padInfo.left;this.outputShape=convInfo.outShape;let isAvgPool=poolType==="avg",batchFlattenPositionStr=`((batch * ${convInfo.inHeight} + xR) * ${convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`,flattenPositionStr=`(xR * ${convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`,initializationValue="0.0";if(isAvgPool||(initializationValue="-1.0 / 1e-20"),computePositions){let compareOp2=">=";this.userCode=`
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
const ivec2 pads = ivec2(${padTop}, ${padLeft});
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
int xR = xRCorner + wR;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${effectiveFilterWidth};
wC += ${dilationWidth}) {
int xC = xCCorner + wC;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float value = getX(batch, xR, xC, d);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${compareOp2} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${flattenPositions?includeBatchInIndex?batchFlattenPositionStr:flattenPositionStr:`wR * ${effectiveFilterWidth} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}let compareOp="max",returnValue=`${poolType}(${poolType}(${poolType}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;poolType==="avg"&&(returnValue="avgValue / count");let filterWidthNearestVec4=Math.floor(filterWidth/4)*4,filterWidthVec4Remainder=filterWidth%4,updateSnippet=`
if (${isAvgPool}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${compareOp}(values, minMaxValue);
}
`;this.userCode=`
2020-12-15 14:44:42 +01:00
const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});
const ivec2 pads = ivec2(${padTop}, ${padLeft});
2020-12-16 20:49:14 +01:00
const float initializationValue = ${initializationValue};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${convInfo.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
2020-12-15 14:44:42 +01:00
ivec4 coords = getOutputCoords();
2020-12-16 20:49:14 +01:00
int batch = coords[0];
int d = coords[3];
2020-12-15 14:44:42 +01:00
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${initializationValue});
float avgValue = 0.0;
count = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
int xR = xRCorner + wR;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${filterWidthNearestVec4}; wC += 4) {
int xC = xCCorner + wC * ${dilationWidth};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${dilationWidth}, d),
getValue(batch, xR, xC + 2 * ${dilationWidth}, d),
getValue(batch, xR, xC + 3 * ${dilationWidth}, d)
);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${updateSnippet}
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int xC = xCCorner + ${filterWidthNearestVec4};
if (${filterWidthVec4Remainder===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${updateSnippet}
} else if (${filterWidthVec4Remainder===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${dilationWidth}, d),
initializationValue,
initializationValue
);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${updateSnippet}
} else if (${filterWidthVec4Remainder===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${dilationWidth}, d),
getValue(batch, xR, xC + 2 * ${dilationWidth}, d),
initializationValue
);
${updateSnippet}
2020-11-16 21:51:46 +01:00
}
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(${returnValue});
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},Pool3DProgram=class{constructor(convInfo,poolType,computePositions,flattenPositions=!1,includeBatchInIndex=!1){if(this.variableNames=["x"],poolType==="avg"&&computePositions)throw new Error("Cannot compute positions for average pool.");let filterWidth=convInfo.filterWidth,strideDepth=convInfo.strideDepth,strideHeight=convInfo.strideHeight,strideWidth=convInfo.strideWidth,dilationDepth=convInfo.dilationDepth,dilationHeight=convInfo.dilationHeight,dilationWidth=convInfo.dilationWidth,effectiveFilterDepth=convInfo.effectiveFilterDepth,effectiveFilterHeight=convInfo.effectiveFilterHeight,effectiveFilterWidth=convInfo.effectiveFilterWidth,padFront=convInfo.padInfo.front,padTop=convInfo.padInfo.top,padLeft=convInfo.padInfo.left;this.outputShape=convInfo.outShape;let isAvgPool=poolType==="avg",initializationValue="0.0";if(isAvgPool||(initializationValue="-1.0 / 1e-20"),computePositions){let compareOp2=">=";this.userCode=`
const ivec3 strides =
ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
for (int wD = 0; wD < ${effectiveFilterDepth};
wD += ${dilationDepth}) {
int xD = xDCorner + wD;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (xD < 0 || xD >= ${convInfo.inDepth}) {
2020-12-15 14:44:42 +01:00
continue;
}
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
int xR = xRCorner + wR;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${effectiveFilterWidth};
wC += ${dilationWidth}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${convInfo.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${compareOp2} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
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} +
wR * ${effectiveFilterWidth} + wC`};
2020-12-15 14:44:42 +01:00
}
}
2020-11-16 21:51:46 +01:00
}
}
2020-12-16 20:49:14 +01:00
setOutput(float(minMaxPosition));
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`;return}let compareOp="max",returnValue=`${poolType}(${poolType}(${poolType}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;poolType==="avg"&&(returnValue="avgValue / count");let filterWidthNearestVec4=Math.floor(filterWidth/4)*4,filterWidthVec4Remainder=filterWidth%4,updateSnippet=`
if (${isAvgPool}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${compareOp}(values, minMaxValue);
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`;this.userCode=`
const ivec3 strides =
ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});
const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});
const float initializationValue = ${initializationValue};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float count = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${convInfo.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${initializationValue});
float avgValue = 0.0;
count = 0.0;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wD = 0; wD < ${effectiveFilterDepth};
wD += ${dilationDepth}) {
int xD = xDCorner + wD;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xD < 0 || xD >= ${convInfo.inDepth}) {
continue;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wR = 0; wR < ${effectiveFilterHeight};
wR += ${dilationHeight}) {
int xR = xRCorner + wR;
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
if (xR < 0 || xR >= ${convInfo.inHeight}) {
continue;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
for (int wC = 0; wC < ${filterWidthNearestVec4}; wC += 4) {
int xC = xCCorner + wC * ${dilationWidth};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${dilationWidth}, ch),
getValue(batch, xD, xR, xC + 2 * ${dilationWidth}, ch),
getValue(batch, xD, xR, xC + 3 * ${dilationWidth}, ch)
);
${updateSnippet}
}
int xC = xCCorner + ${filterWidthNearestVec4};
if (${filterWidthVec4Remainder===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${filterWidthVec4Remainder===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${dilationWidth}, ch),
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${filterWidthVec4Remainder===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${dilationWidth}, ch),
getValue(batch, xD, xR, xC + 2 * ${dilationWidth}, ch),
initializationValue
);
${updateSnippet}
}
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(${returnValue});
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
}
`}},ReduceProgram=class{constructor(reduceInfo,reduceType){this.variableNames=["x"];let{windowSize,batchSize,inSize,outSize}=reduceInfo;this.outputShape=[batchSize,outSize];let initializationValue="0.0",compareOp="";reduceType==="prod"?initializationValue="1.0":reduceType==="min"?(initializationValue="1.0 / 1e-20",compareOp="min"):reduceType==="max"&&(initializationValue="-1.0 / 1e-20",compareOp="max");let returnValue=`${reduceType}(${reduceType}(${reduceType}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;reduceType==="sum"?returnValue="sumValue":reduceType==="prod"?returnValue="prodValue":reduceType==="all"?returnValue="allValue":reduceType==="any"&&(returnValue="anyValue");let windowSizeNearestVec4=Math.floor(windowSize/4)*4,windowSizeVec4Remainder=windowSize%4,updateSnippet=`
if (${reduceType==="sum"}) {
sumValue += dot(values, ones);
} else if (${reduceType==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${compareOp}(values, minMaxValue);
}
`,vecType="vec4";reduceType==="all"?(initializationValue="1.0",updateSnippet=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,vecType="bvec4"):reduceType==="any"&&(initializationValue="0.0",updateSnippet=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,vecType="bvec4");let checkOutOfBounds="";inSize%windowSize>0&&(checkOutOfBounds=`
if (inIdx < 0 || inIdx >= ${inSize}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${initializationValue};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${checkOutOfBounds}
return getX(batch, inIdx);
}
2020-11-16 21:51:46 +01:00
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${windowSize};
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 minMaxValue = vec4(${initializationValue});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${windowSizeNearestVec4}; i += 4) {
int inIdx = inOffset + i;
${vecType} values = ${vecType}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${updateSnippet}
2020-12-15 14:44:42 +01:00
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
int inIdx = inOffset + ${windowSizeNearestVec4};
if (${windowSizeVec4Remainder===1}) {
${vecType} values = ${vecType}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${windowSizeVec4Remainder===2}) {
${vecType} values = ${vecType}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${updateSnippet}
} else if (${windowSizeVec4Remainder===3}) {
${vecType} values = ${vecType}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${updateSnippet}
}
setOutput(${returnValue});
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},ReshapePackedProgram=class{constructor(outputShape,inputShape){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=outputShape;let mainLoop="";for(let i=0;i<4;i++){let thisRC="thisRC = rc;";i%2===1&&(thisRC+="thisRC.z += 1;"),i>1&&(thisRC+="thisRC.y += 1;"),mainLoop+=`
${thisRC}
${i>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${i}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${i>0?"}":""}
`}this.userCode=`
${getReshapedInputCoords(inputShape)}
${getFlatIndexFrom3D(outputShape)}
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec3 rc = getOutputCoords();
2020-12-15 14:44:42 +01:00
vec4 result = vec4(0.);
2020-12-16 20:49:14 +01:00
ivec3 thisRC;
int rows = ${outputShape[1]};
int cols = ${outputShape[2]};
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
${mainLoop}
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
setOutput(result);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}};function getReshapedInputCoords(shape){let coordsFromIndexSnippet=getLogicalCoordinatesFromFlatIndex(["r","c","d"],shape);return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${coordsFromIndexSnippet}
return ivec3(r, c, d);
}
`}var ResizeBilinearBackpropProgram=class{constructor(dy,x,alignCorners){this.variableNames=["dy"],this.outputShape=[],this.outputShape=x.shape;let[,xHeight,xWidth]=x.shape,[,yHeight,yWidth]=dy.shape,effectiveXSize=[alignCorners&&yHeight>1?xHeight-1:xHeight,alignCorners&&yWidth>1?xWidth-1:xWidth],effectiveYSize=[alignCorners&&yHeight>1?yHeight-1:yHeight,alignCorners&&yWidth>1?yWidth-1:yWidth],heightScale=effectiveXSize[0]/effectiveYSize[0],widthScale=effectiveXSize[1]/effectiveYSize[1],invHeightScale=1/heightScale,invWidthScale=1/widthScale,winHeight=Math.ceil(invHeightScale)*2+2,winWidth=Math.ceil(invWidthScale)*2+2;this.userCode=`
2020-12-15 14:44:42 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
2020-12-16 20:49:14 +01:00
int d = coords[3];
2020-12-15 14:44:42 +01:00
int r = coords[1];
int c = coords[2];
2020-12-16 20:49:14 +01:00
float accumulator = 0.0;
const float heightScale = float(${heightScale});
const float widthScale = float(${widthScale});
const float invHeightScale = float(${invHeightScale});
const float invWidthScale = float(${invWidthScale});
const int winHeight = int(${winHeight});
const int winWidth = int(${winWidth});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${yHeight}) {
continue;
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${yWidth}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${xHeight-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${xWidth-1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
2020-12-15 14:44:42 +01:00
}
}
}
2020-12-16 20:49:14 +01:00
// End loop over dy
setOutput(accumulator);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},ResizeBilinearProgram=class{constructor(inputShape,newHeight,newWidth,alignCorners){this.variableNames=["A"],this.outputShape=[];let[batch,oldHeight,oldWidth,depth]=inputShape;this.outputShape=[batch,newHeight,newWidth,depth];let effectiveInSize=[alignCorners&&newHeight>1?oldHeight-1:oldHeight,alignCorners&&newWidth>1?oldWidth-1:oldWidth],effectiveOutSize=[alignCorners&&newHeight>1?newHeight-1:newHeight,alignCorners&&newWidth>1?newWidth-1:newWidth];this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${effectiveInSize[0]/effectiveOutSize[0]},
${effectiveInSize[1]/effectiveOutSize[1]});
const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.0);
2020-12-15 14:44:42 +01:00
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
2020-12-16 20:49:14 +01:00
int d = coords[3];
ivec2 yRC = coords.yz;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},ResizeBilinearPackedProgram=class{constructor(inputShape,newHeight,newWidth,alignCorners){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[batch,oldHeight,oldWidth,depth]=inputShape;this.outputShape=[batch,newHeight,newWidth,depth];let effectiveInSize=[alignCorners&&newHeight>1?oldHeight-1:oldHeight,alignCorners&&newWidth>1?oldWidth-1:oldWidth],effectiveOutSize=[alignCorners&&newHeight>1?newHeight-1:newHeight,alignCorners&&newWidth>1?newWidth-1:newWidth];this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${effectiveInSize[0]/effectiveOutSize[0]},
${effectiveInSize[1]/effectiveOutSize[1]},
${effectiveInSize[1]/effectiveOutSize[1]});
const vec3 inputShapeRC = vec3(${oldHeight}.0, ${oldWidth}.0,
${oldWidth}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
2020-12-15 14:44:42 +01:00
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
2020-12-16 20:49:14 +01:00
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// Fractional source index.
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${depth-1};
bool hasNextRow = coords.z < ${newWidth-1};
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
setOutput(newValue);
}
`}},ResizeNearestNeigborBackpropProgram=class{constructor(dy,x,alignCorners){this.variableNames=["dy"],this.outputShape=[],this.outputShape=x.shape;let[,xHeight,xWidth]=x.shape,[,yHeight,yWidth]=dy.shape,effectiveXSize=[alignCorners&&yHeight>1?xHeight-1:xHeight,alignCorners&&yWidth>1?xWidth-1:xWidth],effectiveYSize=[alignCorners&&yHeight>1?yHeight-1:yHeight,alignCorners&&yWidth>1?yWidth-1:yWidth],heightScale=effectiveXSize[0]/effectiveYSize[0],widthScale=effectiveXSize[1]/effectiveYSize[1],invHeightScale=1/heightScale,invWidthScale=1/widthScale,winHeight=Math.ceil(invHeightScale)*2+2,winWidth=Math.ceil(invWidthScale)*2+2;this.userCode=`
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float accumulator = 0.0;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
const float heightScale = float(${heightScale});
const float widthScale = float(${widthScale});
const float invHeightScale = float(${invHeightScale});
const float invWidthScale = float(${invWidthScale});
const int winHeight = int(${winHeight});
const int winWidth = int(${winWidth});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${yHeight}) {
2020-12-15 14:44:42 +01:00
continue;
}
2020-12-16 20:49:14 +01:00
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${yWidth}) {
2020-12-15 14:44:42 +01:00
continue;
}
2020-12-16 20:49:14 +01:00
float sourceFracRow =
float(${effectiveXSize[0]}) *
(float(dyR) / float(${effectiveYSize[0]}));
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float sourceFracCol =
float(${effectiveXSize[1]}) *
(float(dyC) / float(${effectiveYSize[1]}));
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
int sourceNearestRow = int(min(
float(int(${xHeight}) - 1),
${alignCorners} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
int sourceNearestCol = int(min(
float(int(${xWidth}) - 1),
${alignCorners} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
2020-12-15 14:44:42 +01:00
}
}
}
2020-12-16 20:49:14 +01:00
// End loop over dy
setOutput(accumulator);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},ResizeNearestNeighborProgram=class{constructor(inputShape,newHeight,newWidth,alignCorners){this.variableNames=["A"],this.outputShape=[];let[batch,oldHeight,oldWidth,depth]=inputShape;this.outputShape=[batch,newHeight,newWidth,depth];let effectiveInSize=[alignCorners&&newHeight>1?oldHeight-1:oldHeight,alignCorners&&newWidth>1?oldWidth-1:oldWidth],effectiveOutSize=[alignCorners&&newHeight>1?newHeight-1:newHeight,alignCorners&&newWidth>1?newWidth-1:newWidth],roundBase=alignCorners?"0.5":"0.0";this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${effectiveInSize[0]/effectiveOutSize[0]},
${effectiveInSize[1]/effectiveOutSize[1]});
const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${roundBase})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
setOutput(newValue);
}
`}},ReverseProgram=class{constructor(xShape,axis){this.variableNames=["x"];let rank=xShape.length;if(rank>4)throw new Error(`WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);if(this.outputShape=xShape,rank===1){this.userCode=`
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
int coord = getOutputCoords();
setOutput(getX(${xShape[0]} - coord - 1));
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`;return}let getInCoord=i=>axis.indexOf(i)!==-1&&xShape[i]!==1?`${xShape[i]} - coords[${i}] - 1`:`coords[${i}]`,inCoords=xShape.map((_,i)=>getInCoord(i)).join(","),type=getCoordsDataType(rank);this.userCode=`
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
${type} coords = getOutputCoords();
setOutput(getX(${inCoords}));
}
`}},ReversePackedProgram=class{constructor(xShape,axis){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let rank=xShape.length;if(rank>4)throw new Error(`WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);this.outputShape=xShape;let channels=getChannels("rc",rank),nextColumn=`${channels[rank-1]} + 1 < ${this.outputShape[rank-1]}`,nextRow=`${channels[rank-2]} + 1 < ${this.outputShape[rank-2]}`,type=getCoordsDataType(rank);rank===1?this.userCode=`
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${xShape[0]} - rc - 1),
${xShape[0]} - rc - 1);
if(${nextColumn}){
result.g = getChannel(getX(${xShape[0]} - (rc + 1) - 1),
${xShape[0]} - (rc + 1) - 1);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(result);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`:this.userCode=`
void main() {
${type} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${getR(channels.slice())};
if(${nextColumn}){
result.g = ${getG(channels.slice())};
}
if(${nextRow}) {
result.b = ${getB(channels.slice())};
if(${nextColumn}) {
result.a = ${getA(channels.slice())};
}
}
setOutput(result);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`;function getR(channels2){return getChannel(channels2)}function getG(channels2){return channels2[rank-1]="("+channels2[rank-1]+" + 1)",getChannel(channels2)}function getB(channels2){return channels2[rank-2]="("+channels2[rank-2]+" + 1)",getChannel(channels2)}function getA(channels2){return channels2[rank-1]="("+channels2[rank-1]+" + 1)",channels2[rank-2]="("+channels2[rank-2]+" + 1)",getChannel(channels2)}function getChannel(channels2){let inCoordsArray=xShape.map((_,i)=>getInCoord(i,channels2)),inCoords=inCoordsArray.join(","),innerDims=inCoordsArray.slice(-2).join(",");return`getChannel(getX(${inCoords}), vec2(${innerDims}))`}function getInCoord(i,channels1){return axis.indexOf(i)!==-1&&xShape[i]!==1?`${xShape[i]} - ${channels1[i]} - 1`:`${channels1[i]}`}}},ScatterProgram=class{constructor(updateSize,sliceDim,indicesRank,updatesRank,strides,shape,summingDupeIndex=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=shape;let stridesType=getCoordsDataType(strides.length),dtype=getCoordsDataType(shape.length),indicesString="";indicesRank===1?indicesString="i":indicesRank===2&&(indicesString="i, j");let indicesSnippet=`getIndices(${indicesString})`,updatesString="";updatesRank===1?updatesString="i":updatesRank===2&&(updatesString="i, coords[1]");let updatesSnippet=`getUpdates(${updatesString})`,strideString=sliceDim>1?"strides[j]":"strides";this.userCode=`
${stridesType} strides = ${stridesType}(${strides});
void main() {
${dtype} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${updateSize}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${sliceDim}; j++) {
int index = round(${indicesSnippet});
flattenedIndex += index * ${strideString};
}
if (flattenedIndex == coords[0]) {
sum += ${updatesSnippet};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`}},SegmentOpProgram=class{constructor(segOpInfo,segOpType){this.variableNames=["x","segmentIds"];let windowSize=segOpInfo.windowSize,batchSize=segOpInfo.batchSize,inSize=segOpInfo.inSize,numSegments=segOpInfo.numSegments,outSize=numSegments*Math.ceil(inSize/windowSize);this.outputShape=[batchSize,outSize];let initializationValue="0.0",returnValue="sumValue",windowSizeNearestVec4=Math.floor(windowSize/4)*4,windowSizeVec4Remainder=windowSize%4,updateSnippet=`
sumValue += dot(values, segFilter);
`,checkValueOutOfBounds="";inSize%windowSize>0&&(checkValueOutOfBounds=`
if (inIdx < 0 || inIdx >= ${inSize}) {
return initializationValue;
2020-11-12 18:58:55 +01:00
}
2020-12-16 20:49:14 +01:00
`);let checkSegmentIdOutOfBounds="";inSize%windowSize>0&&(checkSegmentIdOutOfBounds=`
if (inIdx < 0 || inIdx >= ${inSize}) {
return -1.0;
2020-11-16 21:51:46 +01:00
}
2020-12-16 20:49:14 +01:00
`),this.userCode=`
const float initializationValue = ${initializationValue};
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
float getValue(int batch, int inIdx) {
${checkValueOutOfBounds}
return getX(batch, inIdx);
2020-11-16 21:51:46 +01:00
}
2020-12-16 20:49:14 +01:00
float getSegmentIdAtIndex(int inIdx) {
${checkSegmentIdOutOfBounds}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${numSegments})) * float(${windowSize}));
int currentSeg = int(mod(float(outIdx), float(${numSegments})));
float sumValue = 0.0;
for (int i = 0; i < ${windowSizeNearestVec4}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${updateSnippet}
}
int inIdx = inOffset + ${windowSizeNearestVec4};
if (${windowSizeVec4Remainder===1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${updateSnippet}
} else if (${windowSizeVec4Remainder===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
${updateSnippet}
} else if (${windowSizeVec4Remainder===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
${updateSnippet}
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(${returnValue});
}
`}},SelectProgram=class{constructor(cRank,shape,rank){this.variableNames=["c","a","b"],this.outputShape=shape;let cCoords,abCoords;if(rank>4)throw Error(`Where for rank ${rank} is not yet supported`);if(rank===1)abCoords="resRC",cCoords="resRC";else{let currentCoords=["resRC.x","resRC.y","resRC.z","resRC.w"],cCoordVars=[],abCoordVars=[];for(let i=0;i<shape.length;i++)abCoordVars.push(`${currentCoords[i]}`),i<cRank&&cCoordVars.push(`${currentCoords[i]}`);cCoords=cCoordVars.join(),abCoords=abCoordVars.join()}let dtype=getCoordsDataType(rank);this.userCode=`
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
${dtype} resRC = getOutputCoords();
float cVal = getC(${cCoords});
if (cVal >= 1.0) {
setOutput(getA(${abCoords}));
2020-12-15 14:44:42 +01:00
} else {
2020-12-16 20:49:14 +01:00
setOutput(getB(${abCoords}));
2020-12-15 14:44:42 +01:00
}
}
2020-12-16 20:49:14 +01:00
`}},SliceProgram=class{constructor(destSize){this.variableNames=["source"],this.outputShape=destSize,this.rank=destSize.length;let dtype=getCoordsDataType(this.rank),uniformPart=`uniform int start[${this.rank}];`,sourceCoords=getCoords2(this.rank),body3,coordSum=destSize.map((_,i)=>`sourceLoc.${coords[i]} = start[${i}] + coords.${coords[i]};`);body3=`
${dtype} sourceLoc;
${dtype} coords = getOutputCoords();
${coordSum.join(`
`)}
`,this.userCode=`
${uniformPart}
void main() {
${body3}
setOutput(getSource(${sourceCoords}));
}
`}getCustomSetupFunc(start){if(start.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${start.length})`);return(gpgpu,webGLProgram)=>{if(this.startLoc==null&&(this.startLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"start"),this.startLoc==null))return;gpgpu.gl.uniform1iv(this.startLoc,start)}}},coords=["x","y","z","w","u","v"];function getCoords2(rank){if(rank===1)return"sourceLoc";if(rank<=6)return coords.slice(0,rank).map(x=>"sourceLoc."+x).join(",");throw Error(`Slicing for rank ${rank} is not yet supported`)}var SlicePackedProgram=class{constructor(destSize){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=destSize,this.rank=destSize.length;let dtype=getCoordsDataType(this.rank),coords2=getChannels("coords",this.rank),sourceLoc=getChannels("sourceLoc",this.rank),innerDims=this.rank===1?"sourceLoc":`vec2(${sourceLoc.slice(-2).join()})`,getChannel=`getChannel(getSource(${sourceLoc.join()}), ${innerDims})`,upperRow=`
result.x = ${getChannel};
if (++${coords2[this.rank-1]} < ${destSize[this.rank-1]}) {
++${sourceLoc[this.rank-1]};
result.y = ${getChannel};
--${sourceLoc[this.rank-1]};
}
`,lowerRow=this.rank===1?"":`
--${coords2[this.rank-1]};
if (++${coords2[this.rank-2]} < ${destSize[this.rank-2]}) {
++${sourceLoc[this.rank-2]};
result.z = ${getChannel};
if (++${coords2[this.rank-1]} < ${destSize[this.rank-1]}) {
++${sourceLoc[this.rank-1]};
result.w = ${getChannel};
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
}
`,sourceLocSetup=this.rank<=4?`sourceLoc = coords +
${dtype}(${destSize.map((_,i)=>`start[${i}]`).join()});`:destSize.map((_,i)=>`${sourceLoc[i]} = ${coords2[i]} + start[${i}];`).join(`
`);this.userCode=`
uniform int start[${this.rank}];
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
${dtype} coords = getOutputCoords();
${dtype} sourceLoc;
${sourceLocSetup}
2020-12-15 14:44:42 +01:00
vec4 result = vec4(0.);
2020-12-16 20:49:14 +01:00
${upperRow}
${lowerRow}
2020-12-15 14:44:42 +01:00
setOutput(result);
}
2020-12-16 20:49:14 +01:00
`}getCustomSetupFunc(start){if(start.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${start.length})`);return(gpgpu,webGLProgram)=>{if(this.startLoc==null&&(this.startLoc=gpgpu.getUniformLocationNoThrow(webGLProgram,"start"),this.startLoc==null))return;gpgpu.gl.uniform1iv(this.startLoc,start)}}},StridedSliceProgram=class{constructor(begin,strides,size){this.variableNames=["x"],this.outputShape=size;let rank=size.length,inputDtype=getCoordsDataType(size.length),dtype=getCoordsDataType(size.length),newCoords="";if(rank===1)newCoords="coords * strides + begin";else{let outputAxis=0;newCoords=size.map((_,i)=>(outputAxis++,size.length===1?`coords * strides[${i}] + begin[${i}]`:`coords[${outputAxis-1}] * strides[${i}] + begin[${i}]`)).join(",")}this.userCode=`
${inputDtype} begin = ${inputDtype}(${begin});
${inputDtype} strides = ${inputDtype}(${strides});
void main() {
${dtype} coords = getOutputCoords();
setOutput(getX(${newCoords}));
}
`}},TextureManager=class{constructor(gpgpu){this.gpgpu=gpgpu,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(shapeRC,usage,isPacked){let physicalTexType=getPhysicalFromLogicalTextureType(usage,isPacked),shapeKey=getKeyFromTextureShape(shapeRC,physicalTexType,isPacked);shapeKey in this.freeTextures||(this.freeTextures[shapeKey]=[]),shapeKey in this.usedTextures||(this.usedTextures[shapeKey]=[]);let 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();let newTexture2=this.freeTextures[shapeKey].shift();return this.usedTextures[shapeKey].push(newTexture2),newTexture2}let newTexture;return physicalTexType===PhysicalTextureType.PACKED_2X2_FLOAT32?newTexture=this.gpgpu.createPackedMatrixTexture(shapeRC[0],shapeRC[1]):physicalTexType===PhysicalTextureType.PACKED_2X2_FLOAT16?newTexture=this.gpgpu.createFloat16PackedMatrixTexture(shapeRC[0],shapeRC[1]):physicalTexType===PhysicalTextureType.UNPACKED_FLOAT32?newTexture=this.gpgpu.createFloat32MatrixTexture(shapeRC[0],shapeRC[1]):physicalTexType===PhysicalTextureType.UNPACKED_FLOAT16?newTexture=this.gpgpu.createFloat16MatrixTexture(shapeRC[0],shapeRC[1]):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(),newTexture}releaseTexture(texture,shape,logicalTexType,isPacked){if(this.freeTextures==null)return;let physicalTexType=getPhysicalFromLogicalTextureType(logicalTexType,isPacked),shapeKey=getKeyFromTextureShape(shape,physicalTexType,isPacked);shapeKey in this.freeTextures||(this.freeTextures[shapeKey]=[]);let texBytes=computeBytes(shape,physicalTexType,this.gpgpu.gl,this.gpgpu.textureConfig,isPacked),deleteTexThreshold=env().get("WEBGL_DELETE_TEXTURE_THRESHOLD");deleteTexThreshold!==-1&&this._numBytesAllocated>deleteTexThreshold?(this.gpgpu.deleteMatrixTexture(texture),this._numBytesAllocated-=texBytes):(this.freeTextures[shapeKey].push(texture),this.numFreeTextures++,this._numBytesFree+=texBytes),this.numUsedTextures--;let texList=this.usedTextures[shapeKey],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()}log(){if(!this.logEnabled)return;let total=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${total})`);let freeRatio=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*freeRatio)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures==null)return;for(let texShape in this.freeTextures)this.freeTextures[texShape].forEach(tex=>{this.gpgpu.deleteMatrixTexture(tex)});for(let texShape in this.usedTextures)this.usedTextures[texShape].forEach(tex=>{this.gpgpu.deleteMatrixTexture(tex)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}};function numBytesForInternalFormat(gl,internalFormat){let glany=gl;if(internalFormat===glany.R32F)return 4;if(internalFormat===glany.R16F)return 2;if(internalFormat===glany.RGBA32F)return 16;if(internalFormat===gl.RGBA)return 16;if(internalFormat===glany.RGBA16F)return 8;throw new Error(`Unknown internal format ${internalFormat}`)}function computeBytes(shape,physicalTexType,gl,textureConfig,isPacked){let internalFormat=internalFormatForPhysicalTexType(physicalTexType,textureConfig),numElem
void main() {
${dtype} resRC = getOutputCoords();
setOutput(getA(${sourceCoords}));
}
`}};function getSourceCoords3(aShape){let rank=aShape.length;if(rank>5)throw Error(`Tile for rank ${rank} is not yet supported`);if(rank===1)return`imod(resRC, ${aShape[0]})`;let currentCoords=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],sourceCoords=[];for(let i=0;i<aShape.length;i++)sourceCoords.push(`imod(${currentCoords[i]}, ${aShape[i]})`);return sourceCoords.join()}var UnaryOpProgram=class{constructor(aShape,opSnippet){this.variableNames=["A"],this.outputShape=aShape,this.userCode=`
float unaryOperation(float x) {
${opSnippet}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`}},CHECK_NAN_SNIPPET3="if (isnan(x)) return x;",LINEAR="return x;",ABS="return abs(x);",RELU=CHECK_NAN_SNIPPET3+`
return (x < 0.0) ? 0.0 : x;
`,RELU6=CHECK_NAN_SNIPPET3+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,ELU="return (x >= 0.0) ? x : (exp(x) - 1.0);",SELU=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${backend_util_exports.SELU_SCALEALPHA};
float scale = ${backend_util_exports.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;function STEP(alpha=0){return CHECK_NAN_SNIPPET3+`
return x > 0.0 ? 1.0 : float(${alpha});
`}var NEG="return -x;",CEIL="return ceil(x);",FLOOR="return floor(x);",SIGN=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,IS_NAN="return float(isnan(x));",IS_INF="return float(isinf(x));",IS_FINITE="return float(!isnan(x) && !isinf(x));",ROUND=`
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
`,EXP="return exp(x);",EXPM1="return exp(x) - 1.0;",LOG=`if (x < 0.0) return NAN;
return log(x);`,LOG1P="return log(1.0 + x);",SQRT="return sqrt(x);",RSQRT="return inversesqrt(x);",SIGMOID="return 1.0 / (1.0 + exp(-1.0 * x));",SOFTPLUS=`
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
`,ASIN=CHECK_NAN_SNIPPET3+`
if (abs(x) > 1.) {
2020-11-16 21:51:46 +01:00
return NAN;
2020-11-13 22:13:35 +01:00
}
2020-12-16 20:49:14 +01:00
return asin(x);
`,ACOS=CHECK_NAN_SNIPPET3+`
if (abs(x) > 1.) {
return NAN;
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
return acos(x);
`,ATAN=CHECK_NAN_SNIPPET3+`
return atan(x);
`,SINH=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,COSH=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,TANH=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,ASINH=CHECK_NAN_SNIPPET3+"return log(x + sqrt(x * x + 1.0));",ACOSH=CHECK_NAN_SNIPPET3+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,ATANH=CHECK_NAN_SNIPPET3+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,ERF=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${backend_util_exports.ERF_P};
float a1 = ${backend_util_exports.ERF_A1};
float a2 = ${backend_util_exports.ERF_A2};
float a3 = ${backend_util_exports.ERF_A3};
float a4 = ${backend_util_exports.ERF_A4};
float a5 = ${backend_util_exports.ERF_A5};
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
`,RECIPROCAL="return 1.0 / x;",LOGICAL_NOT="return float(!(x >= 1.0));",CLONE="return x;",LINEAR2="return x;",LOG2=`
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
2020-11-16 21:51:46 +01:00
return result;
2020-12-16 20:49:14 +01:00
`,RELU2=`
2020-11-16 21:51:46 +01:00
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2020-12-16 20:49:14 +01:00
`,RELU62=`
2020-11-16 21:51:46 +01:00
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
2020-12-16 20:49:14 +01:00
`,ELU2=`
vec4 result;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
return result;
`,UnaryOpPackedProgram=class{constructor(aShape,opSnippet){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=aShape,this.userCode=`
vec4 unaryOperation(vec4 x) {
${opSnippet}
2020-11-10 02:13:38 +01:00
}
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
setOutput(y);
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
`}},UnpackProgram=class{constructor(outputShape){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=outputShape;let rank=outputShape.length,channels=getChannels("rc",rank),dtype=getCoordsDataType(rank),sourceCoords=getSourceCoords(rank,channels),innerDims=channels.slice(-2),coords2=rank<=1?"rc":`vec2(${innerDims.join(",")})`;this.userCode=`
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
${dtype} rc = getOutputCoords();
vec4 packedInput = getA(${sourceCoords});
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
setOutput(getChannel(packedInput, ${coords2}));
2020-11-10 02:13:38 +01:00
}
2020-12-22 18:34:47 +01:00
`}},{segment_util:segment_util2}=backend_util_exports,split9=kernel_impls_exports.split,tile8=kernel_impls_exports.tile,topkImpl3=kernel_impls_exports.topkImpl,whereImpl3=kernel_impls_exports.whereImpl,EPSILON_FLOAT322=1e-7,EPSILON_FLOAT162=1e-4,binaryCaches={};function getBinaryCache(webGLVersion){return webGLVersion in binaryCaches||(binaryCaches[webGLVersion]={}),binaryCaches[webGLVersion]}function mapActivationToShaderProgram(activation2,packed=!1){if(activation2==="linear")return packed?LINEAR2:LINEAR;if(activation2==="relu")return packed?RELU2:RELU;if(activation2==="elu")return packed?ELU2:ELU;if(activation2==="relu6")return packed?RELU62:RELU6;if(activation2==="prelu")return packed?PRELU2:PRELU;throw new Error(`Activation ${activation2} has not been implemented for the WebGL backend.`)}var CPU_HANDOFF_SIZE_THRESHOLD=128,BEFORE_PAGING_CONSTANT=600;function numMBBeforeWarning(){return env().global.screen==null?1024:env().global.screen.height*env().global.screen.width*window.devicePixelRatio*BEFORE_PAGING_CONSTANT/1024/1024}var MATMUL_SHARED_DIM_THRESHOLD=1e3,MathBackendWebGL=class extends KernelBackend{constructor(gpgpu){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!env().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(gpgpu==null){let gl=getWebGLContext(env().getNumber("WEBGL_VERSION"));this.binaryCache=getBinaryCache(env().getNumber("WEBGL_VERSION")),this.gpgpu=new GPGPUContext(gl),this.canvas=gl.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=gpgpu,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=gpgpu.gl.canvas;this.textureManager=new TextureManager(this.gpgpu),this.numMBBeforeWarning=numMBBeforeWarning(),this.texData=new DataStorage(this,engine15())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(values,shape,dtype){if((env().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||env().getBool("DEBUG"))&&this.checkNumericalProblems(values),dtype==="complex64"&&values!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let dataId={};return this.texData.set(dataId,{shape,dtype,values,usage:TextureUsage.UPLOAD,refCount:1,complexParentRefCount:0}),dataId}incRef(dataId){let texData=this.texData.get(dataId);texData.refCount++}decRef(dataId){if(this.texData.has(dataId)){let texData=this.texData.get(dataId);texData.refCount--}}move(dataId,values,shape,dtype){if(env().getBool("DEBUG")&&this.checkNumericalProblems(values),dtype==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(dataId,{shape,dtype,values,usage:TextureUsage.UPLOAD,refCount:1,complexParentRefCount:0})}disposeIntermediateTensorInfo(tensorInfo){let dataId=tensorInfo.dataId;if(this.texData.has(dataId)){let textureData=this.texData.get(dataId);textureData.refCount--,textureData.refCount<1&&this.disposeData(dataId)}}readSync(dataId){let texData=this.texData.get(dataId),{values,dtype,complexTensorInfos,slice:slice20,shape,isPacked}=texData;if(slice20!=null){let program;isPacked?program=new UnaryOpPackedProgram(shape,CLONE):program=new UnaryOpProgram(shape,CLONE);let res=this.runWebGLProgram(program,[{dataId,shape,dtype}],dtype),data2=this.readSync(res.dataId);return this.disposeIntermediateTensorInfo(res),data2}if(values!=null)return this.convertAndCacheOnCPU(dataId);if(dtype==="string")return values;let shouldTimeProgram=this.activeTimers!=null,start;shouldTimeProgram&&(start=util_exports.now());let result;if(dtype==="complex64"){let realValues=this.readSync(complexTensorInfos.real.dataId),imagValues=this.readSync(complexTensorInfos.imag.dataId);result=backend_util_exports.mergeRealAndImagArrays(realValues,imagValues)}else result=this.getValuesFromTexture(dataId);return shouldTimeProgram&&(this.downloadWaitMs+=util_exports.now()
2020-12-16 20:49:14 +01:00
if (isnan(a)) return a;
if (isnan(b)) return b;
`,CHECK_NAN_SNIPPET_BINARY_PACKED=`
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
2020-12-22 18:34:47 +01:00
`;function unaryKernelFunc2(opSnippet){return({inputs,backend:backend3})=>{let{x}=inputs,webglBackend=backend3,program=new UnaryOpProgram(x.shape,opSnippet);return webglBackend.runWebGLProgram(program,[x],x.dtype)}}function binaryKernelFunc2({opSnippet,packedOpSnippet,checkOutOfBounds=!1,supportsComplex=!1,cpuKernelImpl,dtype}){return({inputs,backend:backend3})=>{let{a,b}=inputs,webglBackend=backend3;if(supportsComplex&&a.dtype==="complex64"){let aData=webglBackend.texData.get(a.dataId),bData=webglBackend.texData.get(b.dataId),[real7,imag7]=[[aData.complexTensorInfos.real,bData.complexTensorInfos.real],[aData.complexTensorInfos.imag,bData.complexTensorInfos.imag]].map(complexParts=>{let[aPart,bPart]=complexParts,aHandle={dataId:aPart.dataId,dtype:aPart.dtype,shape:a.shape},bHandle={dataId:bPart.dataId,dtype:bPart.dtype,shape:b.shape},program2=new BinaryOpProgram(opSnippet,a.shape,b.shape);return webglBackend.runWebGLProgram(program2,[aHandle,bHandle],upcastType(aPart.dtype,bPart.dtype))}),complexOutput=complex9({inputs:{real:real7,imag:imag7},backend:webglBackend});return webglBackend.disposeIntermediateTensorInfo(real7),webglBackend.disposeIntermediateTensorInfo(imag7),complexOutput}let $dtype=dtype||upcastType(a.dtype,b.dtype);if(webglBackend.shouldExecuteOnCPU([a,b])&&cpuKernelImpl!=null){let aData=webglBackend.texData.get(a.dataId),bData=webglBackend.texData.get(b.dataId),[outValues,outShape]=cpuKernelImpl(a.shape,b.shape,aData.values,bData.values,$dtype),out=webglBackend.makeTensorInfo(outShape,$dtype),outData=webglBackend.texData.get(out.dataId);return outData.values=outValues,out}let shouldUsePackedProgram=env().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&packedOpSnippet!=null,program;return shouldUsePackedProgram?program=new BinaryOpPackedProgram(packedOpSnippet,a.shape,b.shape,checkOutOfBounds):program=new BinaryOpProgram(opSnippet,a.shape,b.shape),webglBackend.runWebGLProgram(program,[a,b],$dtype)}}var ADD="return a + b;",addKernelFunc=binaryKernelFunc2({opSnippet:ADD,packedOpSnippet:ADD,supportsComplex:!0,cpuKernelImpl:addImplCPU}),addConfig2={kernelName:Add,backendName:"webgl",kernelFunc:addKernelFunc},ATAN2=CHECK_NAN_SNIPPET_BINARY+`
2020-12-16 20:49:14 +01:00
return atan(a, b);
`,ATAN2_PACKED=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+CHECK_NAN_SNIPPET_BINARY_PACKED+`
return result;
2020-12-22 18:34:47 +01:00
`,atan24=binaryKernelFunc2({opSnippet:ATAN2,packedOpSnippet:ATAN2_PACKED}),atan2Config={kernelName:Atan2,backendName:"webgl",kernelFunc:atan24};function avgPool3(args){let{inputs,backend:backend3,attrs}=args,{x}=inputs;assertNotComplex2(x,"avgPool");let{filterSize,strides,pad:pad10,dimRoundingMode}=attrs,dilations=1;util_exports.assert(backend_util_exports.eitherStridesOrDilationsAreOne(strides,dilations),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${strides} and dilations '${dilations}'`);let convInfo=backend_util_exports.computePool2DInfo(x.shape,filterSize,strides,dilations,pad10,dimRoundingMode);if(convInfo.filterWidth===1&&convInfo.filterHeight===1&&util_exports.arraysEqual(convInfo.inShape,convInfo.outShape))return identity2({inputs:{x},backend:backend3});let avgPoolProgram=new Pool2DProgram(convInfo,"avg",!1);return backend3.runWebGLProgram(avgPoolProgram,[x],"float32")}var avgPoolConfig2={kernelName:AvgPool,backendName:"webgl",kernelFunc:avgPool3};function avgPoolBackprop3(args){let{inputs,backend:backend3,attrs}=args,{dy,input:input2}=inputs,x=input2;assertNotComplex2([dy,input2],"avgPoolBackprop");let{filterSize,strides,pad:pad10}=attrs,convInfo=backend_util_exports.computePool2DInfo(x.shape,filterSize,strides,1,pad10),avgPoolBackpropProgram=new AvgPool2DBackpropProgram(convInfo);return backend3.runWebGLProgram(avgPoolBackpropProgram,[dy],x.dtype)}var avgPoolBackpropConfig2={kernelName:AvgPoolBackprop,backendName:"webgl",kernelFunc:avgPoolBackprop3},BatchNormProgram=class{constructor(xShape,meanShape,varianceShape,offsetShape,scaleShape,varianceEpsilon){this.outputShape=[],this.variableNames=["x","mean","variance"],backend_util_exports.assertAndGetBroadcastShape(xShape,meanShape),backend_util_exports.assertAndGetBroadcastShape(xShape,varianceShape);let offsetSnippet="0.0";offsetShape!=null&&(backend_util_exports.assertAndGetBroadcastShape(xShape,offsetShape),this.variableNames.push("offset"),offsetSnippet="getOffsetAtOutCoords()");let scaleSnippet="1.0";scaleShape!=null&&(backend_util_exports.assertAndGetBroadcastShape(xShape,scaleShape),this.variableNames.push("scale"),scaleSnippet="getScaleAtOutCoords()"),this.outputShape=xShape,this.userCode=`
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${offsetSnippet};
float scale = ${scaleSnippet};
float inv = scale * inversesqrt(variance + float(${varianceEpsilon}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
2020-11-10 02:13:38 +01:00
}
2020-12-16 20:49:14 +01:00
`}},BatchNormPackedProgram=class{constructor(xShape,meanShape,varianceShape,offsetShape,scaleShape,varianceEpsilon){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],backend_util_exports.assertAndGetBroadcastShape(xShape,meanShape),backend_util_exports.assertAndGetBroadcastShape(xShape,varianceShape);let offsetSnippet="vec4(0.0)";offsetShape!=null&&(backend_util_exports.assertAndGetBroadcastShape(xShape,offsetShape),this.variableNames.push("offset"),offsetSnippet="getOffsetAtOutCoords()");let scaleSnippet="vec4(1.0)";scaleShape!=null&&(backend_util_exports.assertAndGetBroadcastShape(xShape,scaleShape),this.variableNames.push("scale"),scaleSnippet="getScaleAtOutCoords()"),this.outputShape=xShape,this.userCode=`
2020-11-16 21:51:46 +01:00
void main() {
2020-12-16 20:49:14 +01:00
vec4 offset = ${offsetSnippet};
vec4 scale = ${scaleSnippet};
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 inv = scale * inversesqrt(variance + vec4(${varianceEpsilon}));
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
setOutput((x - mean) * inv + offset);
}
2020-12-22 18:34:47 +01:00
`}},batchNorm3=({inputs,backend:backend3,attrs})=>{let{x,mean:mean6,variance,offset,scale:scale2}=inputs;util_exports.assert(mean6.shape.length===variance.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),util_exports.assert(offset==null||mean6.shape.length===offset.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),util_exports.assert(scale2==null||mean6.shape.length===scale2.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon}=attrs;varianceEpsilon==null&&(varianceEpsilon=.001);let finalInputs=[x,mean6,variance],offsetShape=null;offset!=null&&(offsetShape=offset.shape,finalInputs.push(offset));let scaleShape=null;scale2!=null&&(scaleShape=scale2.shape,finalInputs.push(scale2));let program=env().getBool("WEBGL_PACK_NORMALIZATION")?new BatchNormPackedProgram(x.shape,mean6.shape,variance.shape,offsetShape,scaleShape,varianceEpsilon):new BatchNormProgram(x.shape,mean6.shape,variance.shape,offsetShape,scaleShape,varianceEpsilon),output=backend3.runWebGLProgram(program,finalInputs,finalInputs[0].dtype);return output},batchNormConfig2={kernelName:FusedBatchNorm,backendName:"webgl",kernelFunc:batchNorm3},NOT_EQUAL="return float(a != b);",notEqual3=binaryKernelFunc2({opSnippet:NOT_EQUAL,dtype:"bool"}),notEqualConfig2={kernelName:NotEqual,backendName:"webgl",kernelFunc:notEqual3};function real6(args){let{inputs,backend:backend3}=args,{input:input2}=inputs,inputData=backend3.texData.get(input2.dataId);return identity2({inputs:{x:inputData.complexTensorInfos.real},backend:backend3})}var realConfig2={kernelName:Real,backendName:"webgl",kernelFunc:real6},TO_INT="return float(int(x));";function int(input2,backend3){let program=new UnaryOpProgram(input2.shape,TO_INT),output=backend3.runWebGLProgram(program,[input2],"int32");return{dataId:output.dataId,shape:output.shape,dtype:output.dtype}}function cast48(args){let{inputs,backend:backend3,attrs}=args,{x}=inputs,{dtype}=attrs;if(dtype==="complex64"){if(x.dtype==="complex64")return identity2({inputs:{x},backend:backend3});let zerosTensor=zeros(x.shape),floatX=cast48({inputs:{x},backend:backend3,attrs:{dtype:"float32"}}),result=complex9({inputs:{real:floatX,imag:zerosTensor},backend:backend3});return zerosTensor.dispose(),backend3.disposeIntermediateTensorInfo(floatX),result}if(x.dtype==="complex64"){let realPart=real6({inputs:{input:x},backend:backend3}),result=cast48({inputs:{x:realPart},backend:backend3,attrs:{dtype}});return backend3.disposeIntermediateTensorInfo(realPart),result}if(!util_exports.hasEncodingLoss(x.dtype,dtype)){let result=identity2({inputs:{x},backend:backend3});return{dataId:result.dataId,shape:result.shape,dtype}}if(dtype==="int32")return int(x,backend3);if(dtype==="bool"){let zerosTensorInfo=backend3.makeTensorInfo([],"bool",util_exports.getTypedArrayFromDType("bool",1)),binaryInputs={a:x,b:zerosTensorInfo},result=notEqual3({inputs:binaryInputs,backend:backend3});return backend3.disposeIntermediateTensorInfo(zerosTensorInfo),result}throw new Error(`Error in Cast: failed to cast ${x.dtype} to ${dtype}`)}var castConfig2={kernelName:Cast,backendName:"webgl",kernelFunc:cast48},ConcatProgram=class{constructor(shapes){this.outputShape=[],this.outputShape=backend_util_exports.computeOutShape(shapes,1),this.variableNames=shapes.map((_,i)=>`T${i}`);let offsets=new Array(shapes.length-1);offsets[0]=shapes[0][1];for(let i=1;i<offsets.length;i++)offsets[i]=offsets[i-1]+shapes[i][1];let snippets=[`if (yC < ${offsets[0]}) setOutput(getT0(yR, yC));`];for(let i=1;i<offsets.length;i++){let shift=offsets[i-1];snippets.push(`else if (yC < ${offsets[i]}) setOutput(getT${i}(yR, yC-${shift}));`)}let lastIndex=offsets.length,lastShift=offsets[offsets.length-1];snippets.push(`else setOutput(getT${lastIndex}(yR, yC-${lastShift}));`),this.userCode=`
2020-12-16 20:49:14 +01:00
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
${snippets.join(`
`)}
}
`}},ConcatPackedProgram=class{constructor(shapes,axis){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=backend_util_exports.computeOutShape(shapes,axis);let shape=this.outputShape,rank=shape.length,dtype=getCoordsDataType(rank),coords2=getChannels("coords",rank),channels=["x","y","z","w","u","v"].slice(0,rank);this.variableNames=shapes.map((_,i)=>`T${i}`);let offsets=new Array(shapes.length-1);offsets[0]=shapes[0][axis];for(let i=1;i<offsets.length;i++)offsets[i]=offsets[i-1]+shapes[i][axis];let channel=channels[axis],lastChannels=channels.slice(-2),allChannels=channels.join(),getValueSnippet=`if (${channel} < ${offsets[0]}) {
return getChannel(
getT0(${allChannels}), vec2(${lastChannels.join()}));
}`;for(let i=1;i<offsets.length;i++){let shift2=offsets[i-1];getValueSnippet+=`
if (${channel} < ${offsets[i]} && ${channel} >= ${offsets[i-1]}) {
return getChannel(
getT${i}(${shiftedChannels(channels,channel,shift2)}),
vec2(${shiftedChannels(lastChannels,channel,shift2)}));
}`}let lastIndex=offsets.length,shift=offsets[offsets.length-1];getValueSnippet+=`
return getChannel(
getT${lastIndex}(${shiftedChannels(channels,channel,shift)}),
vec2(${shiftedChannels(lastChannels,channel,shift)}));`,this.userCode=`
float getValue(${channels.map(x=>"int "+x)}) {
${getValueSnippet}
}
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
void main() {
${dtype} coords = getOutputCoords();
vec4 result = vec4(getValue(${coords2}), 0., 0., 0.);
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
${coords2[rank-1]} = ${coords2[rank-1]} + 1;
if (${coords2[rank-1]} < ${shape[rank-1]}) {
result.g = getValue(${coords2});
}
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
${coords2[rank-2]} = ${coords2[rank-2]} + 1;
if (${coords2[rank-2]} < ${shape[rank-2]}) {
result.a = getValue(${coords2});
}
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
${coords2[rank-1]} = ${coords2[rank-1]} - 1;
if (${coords2[rank-2]} < ${shape[rank-2]} &&
${coords2[rank-1]} < ${shape[rank-1]}) {
result.b = getValue(${coords2});
}
setOutput(result);
}
2020-12-22 18:34:47 +01:00
`}};function shiftedChannels(channels,channel,shift){let channelIdx=channels.indexOf(channel),res=channels.map((c,idx)=>idx===channelIdx?`${c} - ${shift}`:c);return res.join()}function imag6(args){let{inputs,backend:backend3}=args,{input:input2}=inputs,inputData=backend3.texData.get(input2.dataId);return identity2({inputs:{x:inputData.complexTensorInfos.imag},backend:backend3})}var imagConfig2={kernelName:Imag,backendName:"webgl",kernelFunc:imag6};function packedReshape(input2,afterShape,backend3){let input3DShape=[getBatchDim(input2.shape),...getRowsCols(input2.shape)],input3D={dtype:input2.dtype,shape:input3DShape,dataId:input2.dataId},afterShapeAs3D=[getBatchDim(afterShape),...getRowsCols(afterShape)],program=new ReshapePackedProgram(afterShapeAs3D,input3DShape),preventEagerUnpackingOfOutput=!0,output=backend3.runWebGLProgram(program,[input3D],input2.dtype,null,preventEagerUnpackingOfOutput);return{dataId:output.dataId,shape:afterShape,dtype:output.dtype}}function reshape88(args){let{inputs,backend:backend3,attrs}=args,{x}=inputs,{shape}=attrs,webglBackend=backend3,xSize=util_exports.sizeFromShape(x.shape),$shape=util_exports.inferFromImplicitShape(shape,xSize),$xSize=util_exports.sizeFromShape($shape);util_exports.assert(xSize===$xSize,()=>`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.`);let xTexData=webglBackend.texData.get(x.dataId);return xTexData.isPacked&&!isReshapeFree(x.shape,$shape)&&!(xTexData.texture!==null&&isReshapeFree(xTexData.shape,$shape))?packedReshape(x,$shape,webglBackend):(webglBackend.incRef(x.dataId),{dataId:x.dataId,shape:$shape,dtype:x.dtype})}var reshapeConfig2={kernelName:Reshape,backendName:"webgl",kernelFunc:reshape88};function concatImpl(inputs,axis,backend3){let dtype=inputs[0].dtype;if(dtype==="complex64"){let reals=inputs.map(t=>real6({inputs:{input:t},backend:backend3})),imags=inputs.map(t=>imag6({inputs:{input:t},backend:backend3})),realConcated=concatImpl(reals,axis,backend3),imagConcated=concatImpl(imags,axis,backend3),result2=complex9({inputs:{real:realConcated,imag:imagConcated},backend:backend3});return reals.forEach(r=>backend3.disposeIntermediateTensorInfo(r)),imags.forEach(i=>backend3.disposeIntermediateTensorInfo(i)),backend3.disposeIntermediateTensorInfo(realConcated),backend3.disposeIntermediateTensorInfo(imagConcated),result2}if(inputs.length>env().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let midIndex=Math.floor(inputs.length/2),leftSide=concatImpl(inputs.slice(0,midIndex),axis,backend3),rightSide=concatImpl(inputs.slice(midIndex),axis,backend3),result2=concatImpl([leftSide,rightSide],axis,backend3);return backend3.disposeIntermediateTensorInfo(leftSide),backend3.disposeIntermediateTensorInfo(rightSide),result2}if(env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&inputs[0].shape.length>1){let program2=new ConcatPackedProgram(inputs.map(t=>t.shape),axis);return backend3.runWebGLProgram(program2,inputs,dtype)}let outShape=backend_util_exports.computeOutShape(inputs.map(t=>t.shape),axis),tensors2D=inputs.map(x=>reshape88({inputs:{x},attrs:{shape:[-1,util_exports.sizeFromShape(x.shape.slice(axis))]},backend:backend3})),program=new ConcatProgram(tensors2D.map(t=>t.shape)),result=backend3.runWebGLProgram(program,tensors2D,dtype);tensors2D.forEach(r=>backend3.disposeIntermediateTensorInfo(r));let reshapedResult=reshape88({inputs:{x:result},attrs:{shape:outShape},backend:backend3});return backend3.disposeIntermediateTensorInfo(result),reshapedResult}function concat17(args){let{inputs,backend:backend3,attrs}=args,{axis}=attrs,$axis=util_exports.parseAxisParam(axis,inputs[0].shape)[0],outShape=backend_util_exports.computeOutShape(inputs.map(t=>t.shape),$axis);if(util_exports.sizeFromShape(outShape)===0)return backend3.makeTensorInfo(outShape,inputs[0].dtype,[]);let $inputs=inputs.filter(t=>util_exports.sizeFromShape(t.shape)>0);if($inputs.length===1)return $inputs[0];let shapes=$inputs.map(t=>t.shape);return backend_util_exports.assertParamsConsistent(shape
2020-12-16 20:49:14 +01:00
return cos(x);
2020-12-22 18:34:47 +01:00
`,cos6=unaryKernelFunc2(COS),cosConfig2={kernelName:Cos,backendName:"webgl",kernelFunc:cos6},DIV=`
2020-12-16 20:49:14 +01:00
if (a == b) {
return 1.0;
};
return a / b;`,DIV_PACKED=`
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
return result;
2020-12-22 18:34:47 +01:00
`,div35=binaryKernelFunc2({opSnippet:DIV,packedOpSnippet:DIV_PACKED,checkOutOfBounds:!0}),divConfig2={kernelName:Div,backendName:"webgl",kernelFunc:div35},FFTProgram=class{constructor(component,inputShape,inverse){this.variableNames=["real","imag"];let innerDim=inputShape[1];this.outputShape=inputShape;let exponentMultiplierSnippet=inverse?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,resultDenominator=inverse?`${innerDim}.0`:"1.0",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=`
2020-12-16 20:49:14 +01:00
const float exponentMultiplier = ${exponentMultiplierSnippet};
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
float unaryOpComplex(float real, float expR, float imag, float expI) {
${opString}
}
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${innerDim});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
float result = 0.0;
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
for (int i = 0; i < ${innerDim}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
2020-12-13 00:34:30 +01:00
2020-12-16 20:49:14 +01:00
result +=
unaryOpComplex(real, expR, imag, expI) / ${resultDenominator};
2020-12-13 00:34:30 +01:00
}
2020-12-16 20:49:14 +01:00
return result;
2020-12-13 00:34:30 +01:00
}
2020-12-16 20:49:14 +01:00
2020-12-13 00:34:30 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
2020-12-13 00:34:30 +01:00
}
2020-12-22 18:34:47 +01:00
`}};function fftImpl2(x,inverse,backend3){let xData=backend3.texData.get(x.dataId),inputSize=util_exports.sizeFromShape(x.shape),innerDimensionSize=x.shape[x.shape.length-1],batch=inputSize/innerDimensionSize,input2D=reshape88({inputs:{x},backend:backend3,attrs:{shape:[batch,innerDimensionSize]}}),xShape=input2D.shape,realProgram=new FFTProgram("real",xShape,inverse),imagProgram=new FFTProgram("imag",xShape,inverse),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}],realPart=backend3.runWebGLProgram(realProgram,inputs,"float32"),imagPart=backend3.runWebGLProgram(imagProgram,inputs,"float32"),complexOutput=complex9({inputs:{real:realPart,imag:imagPart},backend:backend3});backend3.disposeIntermediateTensorInfo(realPart),backend3.disposeIntermediateTensorInfo(imagPart);let complexOutputReshaped=reshape88({inputs:{x:complexOutput},backend:backend3,attrs:{shape:x.shape}});return backend3.disposeIntermediateTensorInfo(complexOutputReshaped),complexOutputReshaped}function fft6(args){let{inputs,backend:backend3}=args,{input:input2}=inputs;return fftImpl2(input2,!1,backend3)}var fftConfig2={kernelName:FFT,backendName:"webgl",kernelFunc:fft6},FlipLeftRightProgram=class{constructor(imageShape){this.variableNames=["Image"],this.outputShape=[];let imageWidth=imageShape[2];this.outputShape=imageShape,this.userCode=`
2020-11-16 21:51:46 +01:00
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
2020-12-16 20:49:14 +01:00
int coordX = ${imageWidth} - x;
float outputValue;
if(coordX >= 0 && coordX < ${imageWidth}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
2020-11-07 17:34:56 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(outputValue);
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},flipLeftRightConfig2={kernelName:FlipLeftRight,backendName:"webgl",kernelFunc:({inputs,backend:backend3})=>{let{image:image3}=inputs,webglBackend=backend3,program=new FlipLeftRightProgram(image3.shape),output=webglBackend.runWebGLProgram(program,[image3],image3.dtype);return output}},FromPixelsProgram=class{constructor(outputShape){this.variableNames=["A"];let glsl=getGlslDifferences(),[height,width]=outputShape;this.outputShape=outputShape,this.userCode=`
2020-12-15 14:44:42 +01:00
void main() {
2020-12-16 20:49:14 +01:00
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${width}.0, ${height}.0);
vec4 values = ${glsl.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
2020-11-07 17:34:56 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(floor(value * 255.0 + 0.5));
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
`}},FromPixelsPackedProgram=class{constructor(outputShape){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let glsl=getGlslDifferences(),[height,width]=outputShape;this.outputShape=outputShape,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
2020-11-16 21:51:46 +01:00
2020-12-16 20:49:14 +01:00
vec4 result = vec4(0.);
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${width}.0, ${height}.0);
vec4 values = ${glsl.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
2020-12-15 14:44:42 +01:00
2020-12-16 20:49:14 +01:00
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
2020-12-15 14:44:42 +01:00
}
2020-12-16 20:49:14 +01:00
${glsl.output} = result;
}
2020-12-22 18:34:47 +01:00
`}},fromPixelsConfig={kernelName:FromPixels,backendName:"webgl",kernelFunc:fromPixels2},fromPixels2DContext2;function fromPixels2(args){let{inputs,backend:backend3,attrs}=args,{pixels}=inputs,{numChannels}=attrs,isVideo=typeof HTMLVideoElement!="undefined"&&pixels instanceof HTMLVideoElement,isImage=typeof HTMLImageElement!="undefined"&&pixels instanceof HTMLImageElement,[width,height]=isVideo?[pixels.videoWidth,pixels.videoHeight]:[pixels.width,pixels.height],texShape=[height,width],outShape=[height,width,numChannels];(isImage||isVideo)&&(fromPixels2DContext2==null&&(fromPixels2DContext2=document.createElement("canvas").getContext("2d")),fromPixels2DContext2.canvas.width=width,fromPixels2DContext2.canvas.height=height,fromPixels2DContext2.drawImage(pixels,0,0,width,height),pixels=fromPixels2DContext2.canvas);let tempPixelHandle=backend3.makeTensorInfo(texShape,"int32");backend3.texData.get(tempPixelHandle.dataId).usage=TextureUsage.PIXELS,backend3.gpgpu.uploadPixelDataToTexture(backend3.getTexture(tempPixelHandle.dataId),pixels);let program=env().getBool("WEBGL_PACK")?new FromPixelsPackedProgram(outShape):new FromPixelsProgram(outShape),res=backend3.runWebGLProgram(program,[tempPixelHandle],"int32");return backend3.disposeData(tempPixelHandle.dataId),res}function ifft6(args){let{inputs,backend:backend3}=args,{input:input2}=inputs;return fftImpl2(input2,!0,backend3)}var ifftConfig2={kernelName:IFFT,backendName:"webgl",kernelFunc:ifft6},MeanProgram=class{constructor(reduceInfo,divisor){this.variableNames=["x"];let{windowSize,batchSize,inSize,outSize}=reduceInfo;this.outputShape=[batchSize,outSize];let windowSizeNearestVec4=Math.floor(windowSize/4)*4,windowSizeVec4Remainder=windowSize%4,updateSnippet="sumValue += dot(values, ones);";if(divisor!=null){let denominator=1/divisor;updateSnippet=`sumValue += dot(values * ${util_exports.isInt(denominator)?denominator.toPrecision(2):denominator}, ones);`}let checkOutOfBounds="";inSize%windowSize>0&&(checkOutOfBounds=`
2020-12-15 14:44:42 +01:00
if (inIdx < 0 || inIdx >= ${inSize}) {
2020-12-16 20:49:14 +01:00
return 0.0;
2020-12-13 00:34:30 +01:00
}
`),this.userCode=`
2020-12-16 20:49:14 +01:00
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
2020-12-13 00:34:30 +01:00
float getValue(int batch, int inIdx) {
2020-12-16 20:49:14 +01:00
${checkOutOfBounds}
2020-12-13 00:34:30 +01:00
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
2020-12-16 20:49:14 +01:00
int inOffset = outIdx * ${windowSize};
2020-12-13 00:34:30 +01:00
float sumValue = 0.0;
for (int i = 0; i < ${windowSizeNearestVec4}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${updateSnippet}
}
int inIdx = inOffset + ${windowSizeNearestVec4};
if (${windowSizeVec4Remainder===1}) {
2020-12-16 20:49:14 +01:00
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
2020-12-13 00:34:30 +01:00
${updateSnippet}
} else if (${windowSizeVec4Remainder===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
2020-12-16 20:49:14 +01:00
getValue(batch, inIdx + 1), 0.0, 0.0);
2020-12-13 00:34:30 +01:00
${updateSnippet}
} else if (${windowSizeVec4Remainder===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
2020-12-16 20:49:14 +01:00
getValue(batch, inIdx + 2), 0.0);
2020-12-13 00:34:30 +01:00
2020-12-15 14:44:42 +01:00
${updateSnippet}
2020-12-13 00:34:30 +01:00
}
2020-12-16 20:49:14 +01:00
setOutput(sumValue);
}
2020-12-22 18:34:47 +01:00
`}};function getReductionStages(inShape){let stages=[];for(;stages.length===0||stages[stages.length-1].outSize!==1;){let outSize=stages.length?stages[stages.length-1].outSize:inShape[1],windowSize=backend_util_exports.computeOptimalWindowSize(outSize);stages.push({inSize:outSize,windowSize,outSize:Math.ceil(outSize/windowSize)})}return stages}function reduce(x,dtype,reductionType,backend3){let reductionStages=getReductionStages(x.shape),result=x;for(let i=0;i<reductionStages.length;i++){let{inSize,windowSize,outSize}=reductionStages[i],program,previousResult;reductionType==="mean"?program=i===0?new MeanProgram({windowSize,inSize,batchSize:x.shape[0],outSize},inSize):new MeanProgram({windowSize,inSize,batchSize:x.shape[0],outSize}):program=new ReduceProgram({windowSize,inSize,batchSize:x.shape[0],outSize},reductionType),previousResult=result,result=backend3.runWebGLProgram(program,[result],dtype),previousResult.dataId!==x.dataId&&backend3.disposeIntermediateTensorInfo(previousResult)}return result}function maxImpl2(x,reduceShape,outShape,backend3){let inSize=util_exports.sizeFromShape(reduceShape),xSize=util_exports.sizeFromShape(x.shape),batchSize=xSize/inSize,reshapedInput=reshape88({inputs:{x},attrs:{shape:[batchSize,inSize]},backend:backend3}),reduced=reduce(reshapedInput,x.dtype,"max",backend3),reshapedOutput=reshape88({inputs:{x:reduced},attrs:{shape:outShape},backend:backend3});return backend3.disposeIntermediateTensorInfo(reshapedInput),backend3.disposeIntermediateTensorInfo(reduced),reshapedOutput}var TransposeProgram=class{constructor(aShape,newDim){this.variableNames=["A"];let outputShape=new Array(aShape.length);for(let i=0;i<outputShape.length;i++)outputShape[i]=aShape[newDim[i]];this.outputShape=outputShape,this.rank=outputShape.length;let dtype=getCoordsDataType(this.rank),switched=getSwitchedCoords(newDim);this.userCode=`
2020-12-16 20:49:14 +01:00
void main() {
${dtype} resRC = getOutputCoords();
setOutput(getA(${switched}));
}
`}};function getSwitchedCoords(newDim){let rank=newDim.length;if(rank>6)throw Error(`Transpose for rank ${rank} is not yet supported`);let originalOrder=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],switchedCoords=new Array(rank);for(let i=0;i<newDim.length;i++)switchedCoords[newDim[i]]=originalOrder[i];return switchedCoords.join()}var TransposePackedProgram=class{constructor(aShape,newDim){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let outputShape=new Array(aShape.length);for(let i=0;i<outputShape.length;i++)outputShape[i]=aShape[newDim[i]];if(this.outputShape=outputShape,this.rank=outputShape.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let dtype=getCoordsDataType(this.rank),outputOrder=getVecChannels("rc",this.rank),switchedOrder=new Array(this.rank);for(let i=0;i<newDim.length;i++)switchedOrder[newDim[i]]=outputOrder[i];let innerDims=`vec2(${switchedOrder.slice(-2).join()})`,nextColumn=`++${outputOrder[this.rank-1]} < ${outputShape[this.rank-1]}`,getc=`getChannel(getA(${switchedOrder.join()}), ${innerDims})`;this.userCode=`
void main() {
${dtype} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${getc};
if(${nextColumn}) {
result[1] = ${getc};
}
--${outputOrder[this.rank-1]};
if(++${outputOrder[this.rank-2]} < ${outputShape[this.rank-2]}) {
result[2] = ${getc};
if(${nextColumn}) {
result[3] = ${getc};
}
}
setOutput(result);
}
2020-12-22 18:34:47 +01:00
`}};function transposeImpl2(x,perm,backend3){let program=env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new TransposePackedProgram(x.shape,perm):new TransposeProgram(x.shape,perm);return backend3.runWebGLProgram(program,[x],x.dtype)}var maxConfig2={kernelName:Max,backendName:"webgl",kernelFunc:({inputs,attrs,backend:backend3})=>{let{x}=inputs,{reductionIndices,keepDims}=attrs,webglBackend=backend3,xRank=x.shape.length,origAxes=util_exports.parseAxisParam(reductionIndices,x.shape),axes=origAxes,permutedAxes=backend_util_exports.getAxesPermutation(axes,xRank),maxInputIsTransposed=permutedAxes!=null,shouldExecuteOnCPU=webglBackend.shouldExecuteOnCPU([x]),maxInput=x;if(maxInputIsTransposed){if(shouldExecuteOnCPU){let xTexData=webglBackend.texData.get(maxInput.dataId),values=xTexData.values,newShape=new Array(xRank);for(let i=0;i<newShape.length;i++)newShape[i]=x.shape[permutedAxes[i]];let maxInputValues=transposeImplCPU(values,x.shape,x.dtype,permutedAxes,newShape);maxInput=webglBackend.makeTensorInfo(newShape,x.dtype);let maxInputData=webglBackend.texData.get(maxInput.dataId);maxInputData.values=maxInputValues}else maxInput=transposeImpl2(x,permutedAxes,webglBackend);axes=backend_util_exports.getInnerMostAxes(axes.length,xRank)}backend_util_exports.assertAxesAreInnerMostDims("max",axes,xRank);let[maxOutShape,reduceShape]=backend_util_exports.computeOutAndReduceShapes(maxInput.shape,axes),outShape=maxOutShape;keepDims&&(outShape=backend_util_exports.expandShapeToKeepDim(maxOutShape,origAxes));let out;if(shouldExecuteOnCPU){let xTexData=webglBackend.texData.get(maxInput.dataId),values=xTexData.values,outValues=maxImplCPU(values,util_exports.sizeFromShape(reduceShape),outShape,x.dtype);out=webglBackend.makeTensorInfo(outShape,x.dtype);let outData=webglBackend.texData.get(out.dataId);outData.values=outValues}else out=maxImpl2(maxInput,reduceShape,outShape,webglBackend);return maxInputIsTransposed&&webglBackend.disposeIntermediateTensorInfo(maxInput),out}};function maxPool3(args){let{inputs,backend:backend3,attrs}=args,{x}=inputs;assertNotComplex2(x,"maxPool");let{filterSize,strides,pad:pad10,dimRoundingMode}=attrs,dilations=1;util_exports.assert(backend_util_exports.eitherStridesOrDilationsAreOne(strides,dilations),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${strides} and dilations '${dilations}'`);let convInfo=backend_util_exports.computePool2DInfo(x.shape,filterSize,strides,dilations,pad10,dimRoundingMode);if(convInfo.filterWidth===1&&convInfo.filterHeight===1&&util_exports.arraysEqual(convInfo.inShape,convInfo.outShape))return identity2({inputs:{x},backend:backend3});let maxPoolProgram=new Pool2DProgram(convInfo,"max",!1);return backend3.runWebGLProgram(maxPoolProgram,[x],x.dtype)}var maxPoolConfig2={kernelName:MaxPool,backendName:"webgl",kernelFunc:maxPool3};function maxPoolBackprop3(args){let{inputs,backend:backend3,attrs}=args,{dy,input:input2,output}=inputs,x=input2;assertNotComplex2([input2,output],"maxPoolBackprop");let{filterSize,strides,pad:pad10,dimRoundingMode}=attrs,convInfo=backend_util_exports.computePool2DInfo(x.shape,filterSize,strides,1,pad10,dimRoundingMode),getPositions=!0,maxPoolPositionsProgram=new Pool2DProgram(convInfo,"max",getPositions),maxPoolPositions2=backend3.runWebGLProgram(maxPoolPositionsProgram,[x],x.dtype),maxPoolBackPropProgram=new MaxPool2DBackpropProgram(convInfo),result=backend3.runWebGLProgram(maxPoolBackPropProgram,[dy,maxPoolPositions2],x.dtype);return backend3.disposeIntermediateTensorInfo(maxPoolPositions2),result}var maxPoolBackpropConfig2={kernelName:MaxPoolBackprop,backendName:"webgl",kernelFunc:maxPoolBackprop3};function maxPoolWithArgmaxImpl2(x,includeBatchInIndex,convInfo,backend3){let program=new Pool2DProgram(convInfo,"max",!1),poolOutput=backend3.runWebGLProgram(program,[x],"float32");program=new Pool2DProgram(convInfo,"max",!0,!0,includeBatchInIndex);let indexOutput=backend3.runWebGLProgram(program,[x],"float32");return[poolOutput,indexOutput]}var maxPoolWithArgmaxConfig2={kernelName:MaxPoolWithArgmax,backendName:"webgl",kernelFunc:({inputs
2020-12-16 20:49:14 +01:00
int start = ${start};
int end = ${end};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${offset};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${offset};
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${dtype} start = ${dtype}(${start});
${dtype} end = ${dtype}(${end});
void main() {
${dtype} outC = getOutputCoords();
for (int i = 0; i < ${rank}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${offset};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${offset};
}
}
${dtype} coords = outC - start;
setOutput(getX(${unpackedCoords}));
}
`}},MirrorPadPackedProgram=class{constructor(xShape,paddings,mode){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=paddings.map((p2,i)=>p2[0]+xShape[i]+p2[1]);let rank=xShape.length,dtype=getCoordsDataType(rank),start=paddings.map(p2=>p2[0]).join(","),end=paddings.map((p2,i)=>p2[0]+xShape[i]).join(","),coords2=getChannels("rc",rank),source=getChannels("source",rank),cLimit=`${coords2[rank-1]} < ${this.outputShape[rank-1]}`,innerDims=rank===1?"source":`vec2(${source.slice(-2).join()})`,offset=mode==="reflect"?0:1,mainLoop="";if(rank===1){let padSetup=`
${dtype} source = rc;
if (source < start) {
source = start * 2 - source - ${offset};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${offset};
}
source -= start;
`;mainLoop=`
${dtype} rc = outputLoc;
${padSetup}
result[0] = getChannel(getX(${source.join()}), ${innerDims});
${coords2[rank-1]} += 1;
if(${cLimit}) {
${padSetup}
result[1] = getChannel(getX(${source.join()}), ${innerDims});
}
`}else{let padSetup=`
${dtype} source = rc;
${dtype} lt = ${dtype}(lessThan(source, start));
${dtype} gte = ${dtype}(greaterThanEqual(source, end));
${dtype} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${offset}) +
gte * ((end - 1) * 2 - source + ${offset});
source -= start;
`;mainLoop=`
${dtype} rc = outputLoc;
${padSetup}
result[0] = getChannel(getX(${source.join()}), ${innerDims});
${coords2[rank-1]} += 1;
if(${cLimit}) {
${padSetup}
result[1] = getChannel(getX(${source.join()}), ${innerDims});
}
rc = outputLoc;
${coords2[rank-2]} += 1;
if(${coords2[rank-2]} < ${this.outputShape[rank-2]}) {
${padSetup}
result[2] = getChannel(getX(${source.join()}), ${innerDims});
${coords2[rank-1]} += 1;
if(${cLimit}) {
${padSetup}
result[3] = getChannel(getX(${source.join()}), ${innerDims});
}
}
`}this.userCode=`
const ${dtype} start = ${dtype}(${start});
const ${dtype} end = ${dtype}(${end});
void main() {
${dtype} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${mainLoop}
setOutput(result);
}
`}},mirrorPadKernelFunc=({inputs,backend:backend3,attrs})=>{let{x}=inputs,{paddings,mode}=attrs,program=env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new MirrorPadPackedProgram(x.shape,paddings,mode):new MirrorPadProgram(x.shape,paddings,mode),output=backend3.runWebGLProgram(program,[x],x.dtype);return output},mirrorPadConfig2={kernelName:MirrorPad,backendName:"webgl",kernelFunc:mirrorPadKernelFunc},COMPLEX_MULTIPLY={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},BinaryOpComplexProgram=class{constructor(op2,aShape,bShape){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=backend_util_exports.assertAndGetBroadcastShape(aShape,bShape),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${op2}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
2020-12-13 00:34:30 +01:00
}
2020-12-22 18:34:47 +01:00
`}},MUL="return a * b;";function multiply2(args){let{inputs,backend:backend3}=args,{a,b}=inputs,dtype=backend_util_exports.upcastType(a.dtype,b.dtype);if(a.dtype==="complex64"){let aData=backend3.texData.get(a.dataId),bData=backend3.texData.get(b.dataId),realProgram=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.REAL,a.shape,b.shape),imagProgram=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.IMAG,a.shape,b.shape),inputs2=[{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}],realPart=backend3.runWebGLProgram(realProgram,inputs2,"float32"),imagPart=backend3.runWebGLProgram(imagProgram,inputs2,"float32"),complexOutput=complex9({inputs:{real:realPart,imag:imagPart},backend:backend3});return backend3.disposeIntermediateTensorInfo(realPart),backend3.disposeIntermediateTensorInfo(imagPart),complexOutput}if(backend3.shouldExecuteOnCPU([a,b])){let aData=backend3.texData.get(a.dataId),bData=backend3.texData.get(b.dataId),[outValues,outShape]=multiplyImplCPU(a.shape,b.shape,aData.values,bData.values,dtype),out=backend3.makeTensorInfo(outShape,dtype),outData=backend3.texData.get(out.dataId);return outData.values=outValues,out}let program;return env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?program=new BinaryOpPackedProgram(MUL,a.shape,b.shape):program=new BinaryOpProgram(MUL,a.shape,b.shape),backend3.runWebGLProgram(program,[a,b],dtype)}var multiplyConfig2={kernelName:Multiply,backendName:"webgl",kernelFunc:multiply2},nonMaxSuppressionV3Config={kernelName:NonMaxSuppressionV3,backendName:"webgl",kernelFunc:({inputs,backend:backend3,attrs})=>{backend_util_exports.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{boxes,scores}=inputs,{maxOutputSize,iouThreshold,scoreThreshold}=attrs,gpuBackend=backend3,boxesVals=gpuBackend.readSync(boxes.dataId),scoresVals=gpuBackend.readSync(scores.dataId),maxOutputSizeVal=maxOutputSize,iouThresholdVal=iouThreshold,scoreThresholdVal=scoreThreshold;return kernel_impls_exports.nonMaxSuppressionV3Impl(boxesVals,scoresVals,maxOutputSizeVal,iouThresholdVal,scoreThresholdVal)}},nonMaxSuppressionV4Impl3=kernel_impls_exports.nonMaxSuppressionV4Impl,nonMaxSuppressionV4Config2={kernelName:NonMaxSuppressionV4,backendName:"webgl",kernelFunc:({inputs,backend:backend3,attrs})=>{backend_util_exports.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{boxes,scores}=inputs,{maxOutputSize,iouThreshold,scoreThreshold,padToMaxOutputSize}=attrs,gpuBackend=backend3,boxesVals=gpuBackend.readSync(boxes.dataId),scoresVals=gpuBackend.readSync(scores.dataId),{selectedIndices,validOutputs}=nonMaxSuppressionV4Impl3(boxesVals,scoresVals,maxOutputSize,iouThreshold,scoreThreshold,padToMaxOutputSize);return[selectedIndices,validOutputs]}},nonMaxSuppressionV5Impl3=kernel_impls_exports.nonMaxSuppressionV5Impl,nonMaxSuppressionV5Config2={kernelName:NonMaxSuppressionV5,backendName:"webgl",kernelFunc:({inputs,backend:backend3,attrs})=>{backend_util_exports.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{boxes,scores}=inputs,{maxOutputSize,iouThreshold,scoreThreshold,softNmsSigma}=attrs,gpuBackend=backend3,boxesVals=gpuBackend.readSync(boxes.dataId),scoresVals=gpuBackend.readSync(scores.dataId),maxOutputSizeVal=maxOutputSize,iouThresholdVal=iouThreshold,scoreThresholdVal=scoreThreshold,softNmsSigmaVal=softNmsSigma,{selectedIndices,selectedScores}=nonMaxSuppressionV5Impl3(boxesVals,scoresVals,maxOutputSizeVal,iouThresholdVal,scoreThresholdVal,softNmsSigmaVal);return[selectedIndices,selectedScores]}},RotateProgram=class{constructor(imageShape,radians,fillValue,center){this.variableNames=["Image"],this.outputShape=[];let imageHei
2020-12-16 20:49:14 +01:00
vec3 fill = vec3(${fillValue.join(",")});
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - ${centerXString}) * ${cosFactor} - (float(y) - ${centerYString}) * ${sinFactor};
float coordYFloat = (float(x) - ${centerXString}) * ${sinFactor} + (float(y) - ${centerYString}) * ${cosFactor};
int coordX = int(round(coordXFloat + ${centerXString}));
int coordY = int(round(coordYFloat + ${centerYString}));
${fillSnippet}
if(coordX >= 0 && coordX < ${imageWidth} && coordY >= 0 && coordY < ${imageHeight}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}},rotateWithOffsetConfig2={kernelName:RotateWithOffset,backendName:"webgl",kernelFunc:({inputs,attrs,backend:backend3})=>{let{image:image3}=inputs,{radians,fillValue,center}=attrs,webglBackend=backend3,program=new RotateProgram(image3.shape,radians,fillValue,center),output=webglBackend.runWebGLProgram(program,[image3],image3.dtype);return output}},SIN=CHECK_NAN_SNIPPET_UNARY+`
return sin(x);
2020-12-22 18:34:47 +01:00
`,sin5=unaryKernelFunc2(SIN),sinConfig2={kernelName:Sin,backendName:"webgl",kernelFunc:sin5},SQUARE="return x * x;",square23=unaryKernelFunc2(SQUARE),squareConfig2={kernelName:Square,backendName:"webgl",kernelFunc:square23},SQUARED_DIFFERENCE="return (a - b) * (a - b);",squaredDifference3=binaryKernelFunc2({opSnippet:SQUARED_DIFFERENCE,packedOpSnippet:SQUARED_DIFFERENCE}),squaredDifferenceConfig2={kernelName:SquaredDifference,backendName:"webgl",kernelFunc:squaredDifference3},SUB="return a - b;",subKernelFunc=binaryKernelFunc2({opSnippet:SUB,packedOpSnippet:SUB,supportsComplex:!0,cpuKernelImpl:subImplCPU}),subConfig2={kernelName:Sub,backendName:"webgl",kernelFunc:subKernelFunc},TAN="return tan(x);",tan4=unaryKernelFunc2(TAN),tanConfig2={kernelName:Tan,backendName:"webgl",kernelFunc:tan4},transposeConfig2={kernelName:Transpose,backendName:"webgl",kernelFunc:({inputs,attrs,backend:backend3})=>{let{x}=inputs,{perm}=attrs,webglBackend=backend3,xRank=x.shape.length,newShape=new Array(xRank);for(let i=0;i<newShape.length;i++)newShape[i]=x.shape[perm[i]];let out;if(webglBackend.shouldExecuteOnCPU([x])){let xTexData=webglBackend.texData.get(x.dataId),values=xTexData.values,outValues=transposeImplCPU(values,x.shape,x.dtype,perm,newShape);out=webglBackend.makeTensorInfo(newShape,x.dtype);let outData=webglBackend.texData.get(out.dataId);outData.values=outValues}else out=transposeImpl2(x,perm,webglBackend);return out}};function unique5(args){let{inputs,attrs,backend:backend3}=args,{axis}=attrs,{x}=inputs;assertNotComplex2(x,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let values=backend3.readSync(x.dataId),{outputValues,outputShape,indices}=uniqueImplCPU(values,axis,x.shape,x.dtype);return[backend3.makeTensorInfo(outputShape,x.dtype,outputValues),backend3.makeTensorInfo([indices.length],"int32",indices)]}var uniqueConfig2={kernelName:Unique,backendName:"webgl",kernelFunc:unique5},kernelConfigs2=[addConfig2,atan2Config,avgPoolConfig2,avgPoolBackpropConfig2,batchNormConfig2,castConfig2,complexConfig2,concatConfig2,cosConfig2,divConfig2,fftConfig2,flipLeftRightConfig2,fromPixelsConfig,identityConfig2,ifftConfig2,imagConfig2,maxConfig2,maxPoolConfig2,maxPoolBackpropConfig2,maxPoolWithArgmaxConfig2,meanConfig,mirrorPadConfig2,multiplyConfig2,nonMaxSuppressionV3Config,nonMaxSuppressionV4Config2,nonMaxSuppressionV5Config2,notEqualConfig2,realConfig2,reshapeConfig2,rotateWithOffsetConfig2,sinConfig2,squareConfig2,subConfig2,squaredDifferenceConfig2,tanConfig2,transposeConfig2,uniqueConfig2];for(let kernelConfig of kernelConfigs2)registerKernel(kernelConfig);var CppDType;(function(CppDType2){CppDType2[CppDType2.float32=0]="float32",CppDType2[CppDType2.int32=1]="int32",CppDType2[CppDType2.bool=2]="bool",CppDType2[CppDType2.string=3]="string",CppDType2[CppDType2.complex64=4]="complex64"})(CppDType||(CppDType={}));var FusableActivation;(function(FusableActivation2){FusableActivation2[FusableActivation2.linear=0]="linear",FusableActivation2[FusableActivation2.relu=1]="relu",FusableActivation2[FusableActivation2.relu6=2]="relu6",FusableActivation2[FusableActivation2.prelu=3]="prelu"})(FusableActivation||(FusableActivation={}));var wasmFusedMatMul;function setup(backend3){wasmFusedMatMul=backend3.wasm.cwrap(_FusedMatMul,null,["number","array","number","number","array","number","number","number","number","number","number","number"])}function fusedBatchMatMul(args){let{inputs,backend:backend3,attrs}=args,{a,b,bias,preluActivationWeights}=inputs;if(a.dtype!=="float32"||b.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA,transposeB,activation:activation2}=attrs,aId=backend3.dataIdMap.get(a.dataId).id,bId=backend3.dataIdMap.get(b.dataId).id,biasId=0;if(bias!=null){let biasData=backend3.dataIdMap.get(bias.dataId);if(biasData.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${biasData.shape.length}.`);biasId=biasData.id}let preluActivationWeightsId=preluActivationWeights==null?0:backend3.dataIdMap.get(pre
2020-12-13 00:34:30 +01:00
1. The ${printableModuleName} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${printableModuleName} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return fn}else{let config2=identifier;if(config2.className==null||config2.config==null)throw new ValueError(`${printableModuleName}: Improper config format: ${JSON.stringify(config2)}.
'className' and 'config' must set.`);let className=config2.className,cls,fromConfig;if(className in customObjects?[cls,fromConfig]=customObjects[className]:className in _GLOBAL_CUSTOM_OBJECTS?[cls,fromConfig]=_GLOBAL_CUSTOM_OBJECTS.className:className in moduleObjects&&([cls,fromConfig]=moduleObjects[className]),cls==null)throw new ValueError(`Unknown ${printableModuleName}: ${className}. This may be due to one of the following reasons:
1. The ${printableModuleName} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2020-12-22 18:34:47 +01:00
2. The custom ${printableModuleName} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(fromConfig!=null){let customObjectsCombined={};for(let key of Object.keys(_GLOBAL_CUSTOM_OBJECTS))customObjectsCombined[key]=_GLOBAL_CUSTOM_OBJECTS[key];for(let key of Object.keys(customObjects))customObjectsCombined[key]=customObjects[key];let nestedConfig=config2.config;nestedConfig.customObjects=customObjectsCombined;let backupCustomObjects=Object.assign({},_GLOBAL_CUSTOM_OBJECTS);for(let key of Object.keys(customObjects))_GLOBAL_CUSTOM_OBJECTS[key]=customObjects[key];convertNDArrayScalarsInConfig(config2.config);let returnObj=fromConfig(cls,config2.config,customObjects,fastWeightInit);return _GLOBAL_CUSTOM_OBJECTS=Object.assign({},backupCustomObjects),returnObj}else{let backupCustomObjects=Object.assign({},_GLOBAL_CUSTOM_OBJECTS);for(let key of Object.keys(customObjects))_GLOBAL_CUSTOM_OBJECTS[key]=customObjects[key];let returnObj=new cls(config2.config);return _GLOBAL_CUSTOM_OBJECTS=Object.assign({},backupCustomObjects),returnObj}}}function numberCompare(a,b){return a<b?-1:a>b?1:0}function reverseNumberCompare(a,b){return-1*numberCompare(a,b)}function unique6(xs){if(xs==null)return xs;let out=[];for(let x of xs)out.indexOf(x)===-1&&out.push(x);return out}function isObjectEmpty(obj){if(obj==null)throw new ValueError(`Invalid value in obj: ${JSON.stringify(obj)}`);for(let key in obj)if(obj.hasOwnProperty(key))return!1;return!0}function checkStringTypeUnionValue(values,label,value){if(value==null)return;if(values.indexOf(value)<0)throw new ValueError(`${value} is not a valid ${label}. Valid values are ${values} or null/undefined.`)}function checkArrayTypeAndLength(x,expectedType,minLength=0,maxLength=Infinity){return assert2(minLength>=0),assert2(maxLength>=minLength),Array.isArray(x)&&x.length>=minLength&&x.length<=maxLength&&x.every(e=>typeof e===expectedType)}function assertPositiveInteger(value,name){Array.isArray(value)?(util_exports.assert(value.length>0,()=>`${name} is unexpectedly an empty array.`),value.forEach((v,i)=>assertPositiveInteger(v,`element ${i+1} of ${name}`))):util_exports.assert(Number.isInteger(value)&&value>0,()=>`Expected ${name} to be a positive integer, but got ${formatAsFriendlyString(value)}.`)}function formatAsFriendlyString(value){return value===null?"null":Array.isArray(value)?"["+value.map(v=>formatAsFriendlyString(v)).join(",")+"]":typeof value=="string"?`"${value}"`:`${value}`}function debounce(f,waitMs){let lastTime=util_exports.now(),lastResult,f2=(...args)=>{let now22=util_exports.now();return now22-lastTime<waitMs||(lastTime=now22,lastResult=f(...args)),lastResult};return f2}function mapActivationToFusedKernel(activationName){return activationName==="relu"?"relu":activationName==="linear"?"linear":activationName==="elu"?"elu":null}function calcL2Norms(w,axis){return tidy(()=>sqrt(sum2(mul(w,w),axis,!0)))}var Constraint=class extends serialization_exports.Serializable{getConfig(){return{}}},MaxNorm=class extends Constraint{constructor(args){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=args.maxValue!=null?args.maxValue:this.defaultMaxValue,this.axis=args.axis!=null?args.axis:this.defaultAxis}apply(w){return tidy(()=>{let norms=calcL2Norms(w,this.axis),desired=clipByValue(norms,0,this.maxValue);return mul(w,div(desired,add2(epsilon2(),norms)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};MaxNorm.className="MaxNorm";serialization_exports.registerClass(MaxNorm);var UnitNorm=class extends Constraint{constructor(args){super();this.defaultAxis=0,this.axis=args.axis!=null?args.axis:this.defaultAxis}apply(w){return tidy(()=>div(w,add2(epsilon2(),calcL2Norms(w,this.axis))))}getConfig(){return{axis:this.axis}}};UnitNorm.className="UnitNorm";serialization_exports.registerClass(UnitNorm);var NonNeg=class extends Constraint{apply(w){return relu(w)}};NonNeg.className="NonNeg";serialization_exports.registerClass(NonNeg);var MinMaxNorm=class extends Constraint{constructor(args){super();this.defaultMinValue=0,this.defaultMaxVa
because the value dtype is ${tensor167.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=tensor167.shape),assertShapesMatchAllowUndefinedSize(this.elementShape,tensor167.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${index}.`),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=tensor167,keep(tensor167),t.written=!0,this.tensors[index]=t}writeMany(indices,tensors){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((i,index)=>this.write(i,tensors[index]))}gather(indices,dtype){if(!!dtype&&dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${dtype}`);if(indices)indices=indices.slice(0,this.size());else{indices=[];for(let i=0;i<this.size();i++)indices.push(i)}if(indices.length===0)return tensor4([],[0].concat(this.elementShape));let tensors=this.readMany(indices);return assertShapesMatchAllowUndefinedSize(this.elementShape,tensors[0].shape,"TensorArray shape mismatch: "),stack(tensors,0)}concat(dtype){if(!!dtype&&dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${dtype}`);if(this.size()===0)return tensor4([],[0].concat(this.elementShape));let indices=[];for(let i=0;i<this.size();i++)indices.push(i);let tensors=this.readMany(indices);return assertShapesMatchAllowUndefinedSize(this.elementShape,tensors[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${tensors[0].shape})`),concat(tensors,0)}scatter(indices,tensor167){if(tensor167.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${tensor167.dtype}`);if(indices.length!==tensor167.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${indices.length} vs. ${tensor167.shape[0]}`);let maxIndex=Math.max(...indices);if(!this.dynamicSize&&maxIndex>=this.maxSize)throw new Error(`Max index must be < array size (${maxIndex} vs. ${this.maxSize})`);this.writeMany(indices,unstack(tensor167,0))}split(length,tensor167){if(tensor167.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${tensor167.dtype}`);let totalLength=0,cumulativeLengths=length.map(len=>(totalLength+=len,totalLength));if(totalLength!==tensor167.shape[0])throw new Error(`Expected sum of lengths to be equal to
2020-12-13 00:34:30 +01:00
tensor.shape[0], but sum of lengths is
2020-12-22 18:34:47 +01:00
${totalLength}, and tensor's shape is: ${tensor167.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`);let elementPerRow=totalLength===0?0:tensor167.size/totalLength,tensors=[];tidy(()=>{tensor167=reshape(tensor167,[1,totalLength,elementPerRow]);for(let i=0;i<length.length;++i){let previousLength=i===0?0:cumulativeLengths[i-1],indices2=[0,previousLength,0],sizes=[1,length[i],elementPerRow];tensors[i]=reshape(slice(tensor167,indices2,sizes),this.elementShape)}return tensors});let indices=[];for(let i=0;i<length.length;i++)indices[i]=i;this.writeMany(indices,tensors)}},TensorList=class{constructor(tensors,elementShape,elementDtype,maxNumElements=-1){this.tensors=tensors,this.elementShape=elementShape,this.elementDtype=elementDtype,tensors!=null&&tensors.forEach(tensor167=>{if(elementDtype!==tensor167.dtype)throw new Error(`Invalid data types; op elements ${elementDtype}, but list elements ${tensor167.dtype}`);assertShapesMatchAllowUndefinedSize(elementShape,tensor167.shape,"TensorList shape mismatch: "),keep(tensor167)}),this.idTensor=scalar(0),this.maxNumElements=maxNumElements,keep(this.idTensor)}get id(){return this.idTensor.id}copy(){return new TensorList([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(keepIds){this.tensors.forEach(tensor167=>{(keepIds==null||!keepIds.has(tensor167.id))&&tensor167.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(elementShape,elementDtype,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.`);return assertShapesMatchAllowUndefinedSize(elementShape,this.elementShape,"TensorList shape mismatch: "),tidy(()=>{let reshapedTensors=this.tensors.map(tensor167=>reshape(tensor167,elementShape));return stack(reshapedTensors,0)})}popBack(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.");let tensor167=this.tensors.pop();return assertShapesMatchAllowUndefinedSize(tensor167.shape,elementShape,"TensorList shape mismatch: "),reshape(tensor167,elementShape)}pushBack(tensor167){if(tensor167.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${tensor167.dtype}, but list elements ${this.elementDtype}`);if(assertShapesMatchAllowUndefinedSize(tensor167.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");keep(tensor167),this.tensors.push(tensor167)}resize(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}getItem(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.`);return assertShapesMatchAllowUndefinedSize(this.tensors[elementIndex].shape,elementShape,"TensorList shape mismatch: "),this.tensors[elementIndex]}setItem(elementIndex,tensor167){if(tensor167.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${tensor167.dtype}, but list elemen
2020-12-13 00:34:30 +01:00
tensor.shape[0], but sum of lengths is
2020-12-22 18:34:47 +01:00
${totalLength}, and tensor's shape is: ${tensor167.shape}`);let elementPerRow=totalLength===0?0:tensor167.size/totalLength,tensors=tidy(()=>{let tensors2=[];tensor167=reshape(tensor167,[1,totalLength,elementPerRow]);for(let i=0;i<length.length;++i){let previousLength=i===0?0:cumulativeLengths[i-1],indices=[0,previousLength,0],sizes=[1,length[i],elementPerRow];tensors2[i]=reshape(slice(tensor167,indices,sizes),elementShape)}return tensor167.dispose(),tensors2}),list=new TensorList([],elementShape,tensor167.dtype,length.length);for(let i=0;i<tensors.length;i++)list.setItem(i,tensors[i]);return list}var executeOp3=async(node,tensorMap,context)=>{switch(node.op){case"If":case"StatelessIf":{let thenFunc=getParamValue("thenBranch",node,tensorMap,context),elseFunc=getParamValue("elseBranch",node,tensorMap,context),cond=getParamValue("cond",node,tensorMap,context),args=getParamValue("args",node,tensorMap,context),condValue=await cond.data();return condValue[0]?context.functionMap[thenFunc].executeFunctionAsync(args,context.tensorArrayMap,context.tensorListMap):context.functionMap[elseFunc].executeFunctionAsync(args,context.tensorArrayMap,context.tensorListMap)}case"While":case"StatelessWhile":{let bodyFunc=getParamValue("body",node,tensorMap,context),condFunc=getParamValue("cond",node,tensorMap,context),args=getParamValue("args",node,tensorMap,context),condResult=await context.functionMap[condFunc].executeFunctionAsync(args,context.tensorArrayMap,context.tensorListMap),argIds=args.map(tensor167=>tensor167.id),condValue=await condResult[0].data();condResult.forEach(tensor167=>{!tensor167.kept&&argIds.indexOf(tensor167.id)===-1&&tensor167.dispose()});let result=args;for(;condValue[0];){let origResult=result;result=await context.functionMap[bodyFunc].executeFunctionAsync(result,context.tensorArrayMap,context.tensorListMap);let resultIds=result.map(tensor167=>tensor167.id);origResult.forEach(tensor167=>{!tensor167.kept&&argIds.indexOf(tensor167.id)===-1&&resultIds.indexOf(tensor167.id)===-1&&tensor167.dispose()});let condResult2=await context.functionMap[condFunc].executeFunctionAsync(result,context.tensorArrayMap,context.tensorListMap);condValue=await condResult2[0].data(),condResult2.forEach(tensor167=>{!tensor167.kept&&argIds.indexOf(tensor167.id)===-1&&resultIds.indexOf(tensor167.id)===-1&&tensor167.dispose()})}return result}case"LoopCond":{let pred=getParamValue("pred",node,tensorMap,context);return[cloneTensor(pred)]}case"Switch":{let pred=getParamValue("pred",node,tensorMap,context),data2=getParamValue("data",node,tensorMap,context);return data2.kept||(data2=cloneTensor(data2)),(await pred.data())[0]?[void 0,data2]:[data2,void 0]}case"Merge":{let inputName=node.inputNames.find(name=>getTensor(name,tensorMap,context)!==void 0);if(inputName){let data2=getTensor(inputName,tensorMap,context);return[cloneTensor(data2)]}return}case"Enter":{let frameId=getParamValue("frameName",node,tensorMap,context),data2=getParamValue("tensor",node,tensorMap,context);return context.enterFrame(frameId),[cloneTensor(data2)]}case"Exit":{let data2=getParamValue("tensor",node,tensorMap,context);return context.exitFrame(),[cloneTensor(data2)]}case"NextIteration":{let data2=getParamValue("tensor",node,tensorMap,context);return context.nextIteration(),[cloneTensor(data2)]}case"TensorArrayV3":{let 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=getParamValue("name",node,tensorMap,context),tensorArray=new TensorArray(name,dtype,size,elementShape,identicalElementShapes,dynamicSize,clearAfterRead);return context.addTensorArray(tensorArray),[tensorArray.idTensor,scalar(1)]}case"TensorArrayWriteV3":{let id=getParamValue("tensorArrayId",node,tensorMap,context),index=getParamValue("index",node,tensorMap,context),wr
2020-12-13 00:34:30 +01:00
${batchSize}`);let size;return this.size===Infinity||this.size==null?size=this.size:smallLastBatch?size=Math.ceil(this.size/batchSize):size=Math.floor(this.size/batchSize),datasetFromIteratorFn(async()=>(await base2.iterator()).columnMajorBatch(batchSize,smallLastBatch,deepBatchConcat),size)}concatenate(dataset5){let base2=this,size;return this.size===Infinity||dataset5.size===Infinity?size=Infinity:this.size!=null&&dataset5.size!=null?size=this.size+dataset5.size:size=null,datasetFromIteratorFn(async()=>(await base2.iterator()).concatenate(await dataset5.iterator()),size)}filter(predicate){let base2=this,size;return this.size===Infinity?size=Infinity:size=null,datasetFromIteratorFn(async()=>(await base2.iterator()).filter(x=>tidy(()=>predicate(x))),size)}async forEachAsync(f){return(await this.iterator()).forEachAsync(f)}map(transform){let base2=this;return datasetFromIteratorFn(async()=>(await base2.iterator()).map(x=>tidy(()=>transform(x))),this.size)}mapAsync(transform){let base2=this;return datasetFromIteratorFn(async()=>(await base2.iterator()).mapAsync(transform),this.size)}prefetch(bufferSize){if(bufferSize==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let base2=this;return datasetFromIteratorFn(async()=>(await base2.iterator()).prefetch(bufferSize),this.size)}repeat(count2){let base2=this,size;return this.size!=null&&count2>0?size=this.size*count2:count2===0?size=0:this.size!=null&&(count2===void 0||count2<0)?size=Infinity:size=null,datasetFromIteratorFn(async()=>{let iteratorIterator=iteratorFromFunction(async()=>({value:await base2.iterator(),done:!1}));return iteratorFromConcatenated(iteratorIterator.take(count2))},size)}skip(count2){let base2=this,size;return this.size!=null&&count2>=0&&this.size>=count2?size=this.size-count2:this.size!=null&&(this.size<count2||count2===void 0||count2<0)?size=0:size=null,datasetFromIteratorFn(async()=>(await base2.iterator()).skip(count2),size)}shuffle(bufferSize,seed,reshuffleEachIteration=!0){if(bufferSize==null||bufferSize<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let base2=this,random=seedrandom4.alea(seed||util_exports.now().toString());return datasetFromIteratorFn(async()=>{let seed2=random.int32();return reshuffleEachIteration&&(seed2+=random.int32()),(await base2.iterator()).shuffle(bufferSize,seed2.toString())},this.size)}take(count2){let base2=this,size;return this.size!=null&&this.size>count2?size=count2:this.size!=null&&this.size<=count2?size=this.size:size=null,datasetFromIteratorFn(async()=>(await base2.iterator()).take(count2),size)}async toArray(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};Dataset.MAX_BUFFER_SIZE=1e4;function datasetFromIteratorFn(iteratorFn,size=null){return new class extends Dataset{constructor(){super(...arguments);this.size=size}async iterator(){return iteratorFn()}}}function array(items){return datasetFromIteratorFn(async()=>iteratorFromItems(items),items.length)}function zip(datasets){if(!isIterable2(datasets))throw new Error("The argument to zip() must be an object or array.");let size;if(Array.isArray(datasets))for(let i=0;i<datasets.length;i++)size=size==null?datasets[i].size:Math.min(size,datasets[i].size);else if(datasets instanceof Object)for(let ds in datasets)size=size==null?datasets[ds].size:Math.min(size,datasets[ds].size);return datasetFromIteratorFn(async()=>{let streams=await deepMapAndAwaitAll(datasets,d=>{if(d instanceof Dataset)return{value:d.iterator(),recurse:!1};if(isIterable2(d))return{value:null,recurse:!0};throw new Error(
2020-12-22 18:34:47 +01:00
`).map(line=>(line.endsWith("\r")&&(line=line.slice(0,-1)),line));return lineIterator}},CODE_QUOTE='"',STATE_OUT=Symbol("out"),STATE_FIELD=Symbol("field"),STATE_QUOTE=Symbol("quote"),STATE_QUOTE_AFTER_QUOTE=Symbol("quoteafterquote"),STATE_WITHIN_QUOTE_IN_QUOTE=Symbol("quoteinquote"),CSVDataset=class extends Dataset{constructor(input2,csvConfig){super();this.input=input2,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new TextLineDataset(input2),csvConfig||(csvConfig={}),this.hasHeader=!(csvConfig.hasHeader===!1),this.fullColumnNames=csvConfig.columnNames,this.columnConfigs=csvConfig.columnConfigs,this.configuredColumnsOnly=csvConfig.configuredColumnsOnly,csvConfig.delimWhitespace?(util_exports.assert(csvConfig.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=csvConfig.delimiter?csvConfig.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let columnNamesFromFile=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!columnNamesFromFile)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&columnNamesFromFile&&util_exports.assert(columnNamesFromFile.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+columnNamesFromFile.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=columnNamesFromFile);let counts=this.fullColumnNames.reduce((countAcc,name)=>(countAcc[name]=countAcc[name]+1||1,countAcc),{}),duplicateNames=Object.keys(counts).filter(name=>counts[name]>1);if(util_exports.assert(duplicateNames.length===0,()=>"Duplicate column names found: "+duplicateNames.toString()),this.columnConfigs)for(let key of Object.keys(this.columnConfigs)){let index=this.fullColumnNames.indexOf(key);if(index===-1)throw new Error('The key "'+key+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let iter=await this.base.iterator(),firstElement=await iter.next();if(firstElement.done)throw new Error("No data was found for CSV parsing.");let firstLine=firstElement.value,headers=this.parseRow(firstLine,!1);return headers}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let lines=await this.base.iterator();return this.hasHeader&&(lines=lines.skip(1)),lines.map(x=>this.makeDataElement(x))}makeDataElement(line){let values=this.parseRow(line),features={},labels={};for(let i=0;i<this.fullColumnNames.length;i++){let key=this.fullColumnNames[i],config2=this.columnConfigs?this.columnConfigs[key]:null;if(this.configuredColumnsOnly&&!config2)continue;{let value=values[i],parsedValue=null;if(value==="")if(config2&&config2.default!==void 0)parsedValue=config2.default;else{if(config2&&(config2.required||config2.isLabel))throw new Error(`Required column ${key} is empty in this line: ${line}`);parsedValue=void 0}else{let valueAsNum=Number(value);if(isNaN(valueAsNum))config2&&config2.dtype==="bool"?parsedValue=this.getBoolean(value):parsedValue=value;else if(!config2||!config2.dtype)parsedValue=valueAsNum;else switch(config2.dtype){case"float32":parsedValue=valueAsNum;break;case"int32":parsedValue=Math.floor(valueAsNum);break;case"bool":parsedValue=this.getBoolean(value);break;default:parsedValue=valueAsNum}}config2&&config2.isLabel?labels[key]=parsedValue:features[key]=parsedValue}}return Object.keys(labels).length===0?features:{xs:features,ys:labels}}getBoolean(value){return value==="1"||value.toLowerCase()==="true"?1:0}parseRow(line,validateElementCount=!0){let result=[],readOffset=0,readLength=line.length,currentState=STATE_O
2020-12-08 15:58:30 +01:00
/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUA
AAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQu
bmV0IDQuMi4xMwAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxob
IxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgo
KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgBAAEAAwEhAAIRAQMRAf/E
AB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAE
EQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZH
SElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1
tre4ubrCw8TFxsfIyc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LW+i
UiZidukulmxxlx2paN4mNng+K4+I8Hy2yaTfl37TXetoCPfRxfp1qi3F48ofKMvtvxak8s6LDv61
rZji9rPaLUf5PC+bfttS0q8q3p9W/wBrRMdpUZuKdN99nzvFqPbTVz7nD8OKs+do2/mW3h4D7Xaq
ZnPrtNpqz35aRaYOHY9Zk4pNt9rR+rl6zi+OnS+WN57Rv1lXp/YrNaYtruL6zNPnGO3hxP6O5w/2
f0HDuun09Yv55Le9afznqcOvO4tBreMTHu30unnva0bWt8on+70nDuE4OHYYx4Kbesz3tPrMuhGO
IjpDOKrK9YVpsyiGUQnYGOyUgI2SlAIEmwMWMs9kTAMJYzDOYRMArmGErZhhMArlHmzmGMwDE3Ts
bAbs4swj5pgFkSziVcM4BZEsolXDKAZwyhjCYBkACQhIAAAAAAAJAAAAAAAAAAAAAAAAAAAShIAA
AAAAAAJAAAAAAAAAAAAAABAJEAAAAAAAAAAAAAAAIEoBKAAAAAAAAAAAAAAABAlAAAAAAAIAAAAA
BAkBAkBAkBAlACEgMZjdjbFW8bWrEx8YWANb6Fp+bfwab+vLDKMFK9qxH5L0bAr8OPRPKz2AY7J2
SbAjYZAI2E7AIEgIEgIEgMdkSy2NgY7MdlmyNoBXsxmFuyNgVTVjNV3KjlBRNTlXTVHKCrlIqt5T
lBhEMohlFerLlBjEMohMVTEARDKCITsAk2AEgAAAkAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAD/
2020-12-27 14:12:22 +01:00
2Q==`,version11="0.9.19",now2=()=>typeof performance!="undefined"?performance.now():parseInt(Number(process.hrtime.bigint())/1e3/1e3);function mergeDeep(...objects){let isObject=obj=>obj&&typeof obj=="object";return objects.reduce((prev,obj)=>(Object.keys(obj||{}).forEach(key=>{let pVal=prev[key],oVal=obj[key];Array.isArray(pVal)&&Array.isArray(oVal)?prev[key]=pVal.concat(...oVal):isObject(pVal)&&isObject(oVal)?prev[key]=mergeDeep(pVal,oVal):prev[key]=oVal}),prev),{})}var Human=class{constructor(userConfig2={}){this.tf=tfjs_esm_exports,this.version=version11,this.config=mergeDeep(config_default,userConfig2),this.fx=null,this.state="idle",this.numTensors=0,this.analyzeMemoryLeaks=!1,this.checkSanity=!1,this.firstRun=!0,this.perf={},this.models={facemesh:null,posenet:null,handpose:null,iris:null,age:null,gender:null,emotion:null},this.facemesh=facemesh,this.age=age,this.gender=gender,this.emotion=emotion,this.body=posenet,this.hand=handpose}profile(){return this.config.profile?profile2.data:{}}analyze(...msg){if(!this.analyzeMemoryLeaks)return;let current=engine15().state.numTensors,previous=this.numTensors;this.numTensors=current;let leaked=current-previous;leaked!==0&&log(...msg,leaked)}sanity(input2){if(!this.checkSanity)return null;if(!input2)return"input is not defined";if(ENV.flags.IS_NODE&&!(input2 instanceof Tensor))return"input must be a tensor";try{getBackend()}catch(e){return"backend not loaded"}return null}simmilarity(embedding1,embedding22){return this.config.face.embedding.enabled?embedding2.simmilarity(embedding1,embedding22):0}async load(userConfig2){this.state="load";let timeStamp=now2();userConfig2&&(this.config=mergeDeep(this.config,userConfig2)),this.firstRun&&(log(`version: ${this.version} TensorFlow/JS version: ${version6}`),await this.checkBackend(!0),ENV.flags.IS_BROWSER&&(log("configuration:",this.config),log("tf flags:",ENV.flags)),this.firstRun=!1),this.config.async?[this.models.facemesh,this.models.age,this.models.gender,this.models.emotion,this.models.embedding,this.models.posenet,this.models.handpose]=await Promise.all([this.models.facemesh||(this.config.face.enabled?facemesh.load(this.config):null),this.models.age||(this.config.face.enabled&&this.config.face.age.enabled?age.load(this.config):null),this.models.gender||(this.config.face.enabled&&this.config.face.gender.enabled?gender.load(this.config):null),this.models.emotion||(this.config.face.enabled&&this.config.face.emotion.enabled?emotion.load(this.config):null),this.models.embedding||(this.config.face.enabled&&this.config.face.embedding.enabled?embedding2.load(this.config):null),this.models.posenet||(this.config.body.enabled?posenet.load(this.config):null),this.models.handpose||(this.config.hand.enabled?handpose.load(this.config):null)]):(this.config.face.enabled&&!this.models.facemesh&&(this.models.facemesh=await facemesh.load(this.config)),this.config.face.enabled&&this.config.face.age.enabled&&!this.models.age&&(this.models.age=await age.load(this.config)),this.config.face.enabled&&this.config.face.gender.enabled&&!this.models.gender&&(this.models.gender=await gender.load(this.config)),this.config.face.enabled&&this.config.face.emotion.enabled&&!this.models.emotion&&(this.models.emotion=await emotion.load(this.config)),this.config.face.enabled&&this.config.face.embedding.enabled&&!this.models.embedding&&(this.models.embedding=await embedding2.load(this.config)),this.config.body.enabled&&!this.models.posenet&&(this.models.posenet=await posenet.load(this.config)),this.config.hand.enabled&&!this.models.handpose&&(this.models.handpose=await handpose.load(this.config)));let current=Math.trunc(now2()-timeStamp);current>(this.perf.load||0)&&(this.perf.load=current)}async checkBackend(force){if(this.config.backend&&this.config.backend!==""&&force||getBackend()!==this.config.backend){let timeStamp=now2();if(this.state="backend",log("setting backend:",this.config.backend),this.config.backend==="wasm"){log("settings wasm path:",this.config.wasmPath),setWasmPaths(this.config.wasmPath);let simd=await env().getAsync("WASM_HAS_SIMD_SUPPORT");simd||
2020-11-07 17:34:56 +01:00
:root { --rounded: 0.2rem; }
2020-11-23 13:44:10 +01:00
.menu { position: absolute; top: 0rem; right: 0; width: max-content; padding: 0 0.2rem 0 0.2rem; line-height: 1.8rem; z-index: 10;
2020-11-07 17:34:56 +01:00
box-shadow: 0 0 8px dimgrey; background: ${theme.background}; border-radius: var(--rounded); border-color: black; border-style: solid; border-width: thin; }
.menu:hover { box-shadow: 0 0 8px ${theme.hover}; }
.menu-container { display: block; max-height: 100vh; }
.menu-container-fadeout { max-height: 0; overflow: hidden; transition: max-height, 0.5s ease; }
.menu-container-fadein { max-height: 100vh; overflow: hidden; transition: max-height, 0.5s ease; }
2020-11-19 20:45:59 +01:00
.menu-item { display: flex; white-space: nowrap; padding: 0.2rem; cursor: default; width: 100%; }
.menu-title { cursor: pointer; }
2020-11-07 17:34:56 +01:00
.menu-hr { margin: 0.2rem; border: 1px solid rgba(0, 0, 0, 0.5) }
2020-11-08 18:26:45 +01:00
.menu-label { padding: 0; font-weight: 800; }
2020-11-07 17:34:56 +01:00
.menu-list { margin-right: 0.8rem; }
select:focus { outline: none; }
2020-11-10 02:13:38 +01:00
.menu-list-item { background: ${theme.itemBackground}; color: ${theme.itemColor}; border: none; padding: 0.2rem; font-family: inherit;
font-variant: inherit; border-radius: var(--rounded); font-weight: 800; }
2020-11-07 17:34:56 +01:00
.menu-chart-title { padding: 0; font-size: 0.8rem; font-weight: 800; align-items: center}
.menu-chart-canvas { background: transparent; margin: 0.2rem 0 0.2rem 0.6rem; }
2020-11-19 20:45:59 +01:00
.menu-button { border: 0; background: ${theme.buttonBackground}; width: -webkit-fill-available; padding: 8px; margin: 8px; cursor: pointer; box-shadow: 4px 4px 4px 0 dimgrey;
2020-11-10 02:13:38 +01:00
border-radius: var(--rounded); justify-content: center; font-family: inherit; font-variant: inherit; font-size: 1rem; font-weight: 800; }
2020-11-07 17:34:56 +01:00
.menu-button:hover { background: ${theme.buttonHover}; box-shadow: 4px 4px 4px 0 black; }
.menu-button:focus { outline: none; }
2020-11-19 20:45:59 +01:00
.menu-checkbox { width: 2.8rem; height: 1rem; background: ${theme.itemBackground}; margin: 0.5rem 0.5rem 0 0; position: relative; border-radius: var(--rounded); }
2020-11-07 17:34:56 +01:00
.menu-checkbox:after { content: 'OFF'; color: ${theme.checkboxOff}; position: absolute; right: 0.2rem; top: -0.4rem; font-weight: 800; font-size: 0.5rem; }
.menu-checkbox:before { content: 'ON'; color: ${theme.checkboxOn}; position: absolute; left: 0.3rem; top: -0.4rem; font-weight: 800; font-size: 0.5rem; }
2020-11-10 02:13:38 +01:00
.menu-checkbox-label { width: 1.3rem; height: 0.8rem; cursor: pointer; position: absolute; top: 0.1rem; left: 0.1rem; z-index: 1; background: ${theme.checkboxOff};
border-radius: var(--rounded); transition: left 0.6s ease; }
2020-11-07 17:34:56 +01:00
input[type=checkbox] { visibility: hidden; }
input[type=checkbox]:checked + label { left: 1.4rem; background: ${theme.checkboxOn}; }
2020-11-19 20:45:59 +01:00
.menu-range { margin: 0.2rem 0.5rem 0 0; width: 3.5rem; background: transparent; color: ${theme.rangeBackground}; }
2020-11-10 02:13:38 +01:00
.menu-range:before { color: ${theme.rangeLabel}; margin: 0 0.4rem 0 0; font-weight: 800; font-size: 0.6rem; position: relative; top: 0.3rem; content: attr(value); }
2020-11-07 17:34:56 +01:00
input[type=range] { -webkit-appearance: none; }
input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 1rem; cursor: pointer; background: ${theme.itemBackground}; border-radius: var(--rounded); border: 1px; }
2020-11-10 02:13:38 +01:00
input[type=range]::-moz-range-track { width: 100%; height: 1rem; cursor: pointer; background: ${theme.itemBackground}; border-radius: var(--rounded); border: 1px; }
2020-11-19 20:45:59 +01:00
input[type=range]::-webkit-slider-thumb { border: 1px solid #000000; margin-top: 0.05rem; height: 0.9rem; width: 1rem; border-radius: var(--rounded); background: ${theme.rangeBackground}; cursor: pointer; -webkit-appearance: none; }
input[type=range]::-moz-range-thumb { border: 1px solid #000000; margin-top: 0.05rem; height: 0.9rem; width: 1rem; border-radius: var(--rounded); background: ${theme.rangeBackground}; cursor: pointer; -webkit-appearance: none; }
2020-11-09 14:57:24 +01:00
.svg-background { fill:darkslategrey; cursor:pointer; opacity: 0.6; }
.svg-foreground { fill:white; cursor:pointer; opacity: 0.8; }
2020-11-25 15:13:19 +01:00
`,el=document.createElement("style");el.innerHTML=css,document.getElementsByTagName("head")[0].appendChild(el),CSScreated=!0}var Menu=class{constructor(parent,title,position,userTheme){userTheme&&(theme={...theme,...userTheme}),createCSS(),this.createMenu(parent,title,position),this.id=0,this.instance=instance,instance++,this._maxFPS=0,this.hidden=0}createMenu(parent,title="",position={top:null,left:null,bottom:null,right:null}){this.menu=document.createElement("div"),this.menu.id=`menu-${instance}`,this.menu.className="menu",position&&(position.top&&(this.menu.style.top=position.top),position.bottom&&(this.menu.style.bottom=position.bottom),position.left&&(this.menu.style.left=position.left),position.right&&(this.menu.style.right=position.right)),this.container=document.createElement("div"),this.container.id=`menu-container-${instance}`,this.container.className="menu-container menu-container-fadein";let elTitle=document.createElement("div");elTitle.className="menu-title",elTitle.id=`menu-title-${instance}`;let svg=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" style="width: 2rem; height: 2rem; vertical-align: top;">
2020-11-09 14:57:24 +01:00
<path d="M400 32H48A48 48 0 0 0 0 80v352a48 48 0 0 0 48 48h352a48 48 0 0 0 48-48V80a48 48 0 0 0-48-48zm-51.37 182.31L232.06 348.16a10.38 10.38 0 0 1-16.12 0L99.37 214.31C92.17 206 97.28 192 107.43 192h233.14c10.15 0 15.26 14 8.06 22.31z" class="svg-background"/>
<path d="M348.63 214.31L232.06 348.16a10.38 10.38 0 0 1-16.12 0L99.37 214.31C92.17 206 97.28 192 107.43 192h233.14c10.15 0 15.26 14 8.06 22.31z" class="svg-foreground"/>
2020-11-26 16:37:04 +01:00
</svg>`;title&&(elTitle.innerHTML=`${title}${svg}`),this.menu.appendChild(elTitle),elTitle.addEventListener("click",()=>{this.container.classList.toggle("menu-container-fadeout"),this.container.classList.toggle("menu-container-fadein"),this.menu.style.borderStyle=this.container.classList.contains("menu-container-fadeout")?"none":"solid"}),this.menu.appendChild(this.container),typeof parent=="object"?parent.appendChild(this.menu):document.getElementById(parent).appendChild(this.menu)}get newID(){return this.id++,`menu-${this.instance}-${this.id}`}get ID(){return`menu-${this.instance}-${this.id}`}get width(){return this.menu.offsetWidth}get height(){return this.menu.offsetHeight}hide(){this.container.classList.contains("menu-container-fadein")&&(this.container.classList.toggle("menu-container-fadeout"),this.container.classList.toggle("menu-container-fadein"))}visible(){return this.container.classList.contains("menu-container-fadein")}toggle(evt){if(this.container.classList.toggle("menu-container-fadeout"),this.container.classList.toggle("menu-container-fadein"),this.container.classList.contains("menu-container-fadein")&&evt){let x=evt.x||(evt.touches&&evt.touches[0]?evt.touches[0].pageX:null);x&&(this.menu.style.left=`${x-this.menu.offsetWidth/2}px`),this.menu.offsetLeft<0&&(this.menu.style.left=0),this.menu.offsetLeft+this.menu.offsetWidth>window.innerWidth&&(this.menu.style.left=null,this.menu.style.right=0),this.menu.style.borderStyle="solid"}else this.menu.style.borderStyle="none"}addTitle(title){let el=document.createElement("div");return el.className="menu-title",el.id=this.newID,el.innerHTML=title,this.menu.appendChild(el),el.addEventListener("click",()=>{this.hidden=!this.hidden;let all2=document.getElementsByClassName("menu");for(let item of all2)item.style.display=this.hidden?"none":"block"}),el}addLabel(title){let el=document.createElement("div");return el.className="menu-item menu-label",el.id=this.newID,el.innerHTML=title,this.container.appendChild(el),el}addBool(title,object,variable2,callback){let el=document.createElement("div");return el.className="menu-item",el.innerHTML=`<div class="menu-checkbox"><input class="menu-checkbox" type="checkbox" id="${this.newID}" ${object[variable2]?"checked":""}/><label class="menu-checkbox-label" for="${this.ID}"></label></div>${title}`,this.container.appendChild(el),el.addEventListener("change",evt=>{object[variable2]=evt.target.checked,callback&&callback(evt.target.checked)}),el}async addList(title,items,selected,callback){let el=document.createElement("div");el.className="menu-item";let options="";for(let item of items){let def=item===selected?"selected":"";options+=`<option value="${item}" ${def}>${item}</option>`}return el.innerHTML=`<div class="menu-list"><select name="${this.ID}" class="menu-list-item">${options}</select><label for="${this.ID}"></label></div>${title}`,el.style.fontFamily=document.body.style.fontFamily,el.style.fontSize=document.body.style.fontSize,el.style.fontVariant=document.body.style.fontVariant,this.container.appendChild(el),el.addEventListener("change",evt=>{callback&&callback(items[evt.target.selectedIndex])}),el}addRange(title,object,variable2,min2,max2,step2,callback){let el=document.createElement("div");return el.className="menu-item",el.innerHTML=`<input class="menu-range" type="range" id="${this.newID}" min="${min2}" max="${max2}" step="${step2}" value="${object[variable2]}">${title}`,this.container.appendChild(el),el.addEventListener("change",evt=>{object[variable2]=parseInt(evt.target.value)===parseFloat(evt.target.value)?parseInt(evt.target.value):parseFloat(evt.target.value),evt.target.setAttribute("value",evt.target.value),callback&&callback(evt.target.value)}),el.input=el.children[0],el}addHTML(html){let el=document.createElement("div");return el.className="menu-item",el.id=this.newID,html&&(el.innerHTML=html),this.container.appendChild(el),el}addButton(titleOn,titleOff,callback){let el=document.createElement("button");return el.className="menu-item menu-button",el.style.fontFamily=document.body.style.fontFamily,el.style.fo
2020-11-14 23:22:59 +01:00
#gl-bench { position: absolute; right: 1rem; bottom: 1rem; z-index:1000; -webkit-user-select: none; -moz-user-select: none; user-select: none; }
#gl-bench div { position: relative; display: block; margin: 4px; padding: 0 7px 0 10px; background: darkslategray; border-radius: 0.2rem; cursor: pointer; opacity: 0.9; }
2020-11-19 20:45:59 +01:00
#gl-bench svg { height: 60px; margin: 0 0px 0px 4px; }
2020-11-14 23:22:59 +01:00
#gl-bench text { font-size: 16px; font-family: 'Lato', 'Segoe UI'; dominant-baseline: middle; text-anchor: middle; }
#gl-bench .gl-mem { font-size: 12px; fill: white; }
#gl-bench .gl-fps { font-size: 13px; fill: white; }
#gl-bench line { stroke-width: 5; stroke: white; stroke-linecap: round; }
#gl-bench polyline { fill: none; stroke: white; stroke-linecap: round; stroke-linejoin: round; stroke-width: 3.5; }
#gl-bench rect { fill: black; }
#gl-bench .opacity { stroke: black; }
`,UISVG=`
2020-11-12 23:00:06 +01:00
<div class="gl-box">
<svg viewBox="0 0 55 60">
<text x="27" y="56" class="gl-fps">00 FPS</text>
2020-11-19 20:45:59 +01:00
<text x="30" y="8" class="gl-mem"></text>
2020-11-12 23:00:06 +01:00
<rect x="0" y="14" rx="4" ry="4" width="55" height="32"></rect>
<polyline class="gl-chart"></polyline>
</svg>
<svg viewBox="0 0 14 60" class="gl-cpu-svg">
<line x1="7" y1="38" x2="7" y2="11" class="opacity"/>
<line x1="7" y1="38" x2="7" y2="11" class="gl-cpu" stroke-dasharray="0 27"/>
2020-11-14 23:22:59 +01:00
<path d="M5.35 43c-.464 0-.812.377-.812.812v1.16c-.783.1972-1.421.812-1.595 1.624h-1.16c-.435 0-.812.348-.812.812s.348.812.812.812h1.102v1.653H1.812c-.464 0-.812.377-.812.812 0 .464.377.812.812.812h1.131c.1943.783.812 1.392 1.595 1.595v1.131c0 .464.377.812.812.812.464 0 .812-.377.812-.812V53.15h1.653v1.073c0 .464.377.812.812.812.464 0 .812-.377.812-.812v-1.131c.783-.1943 1.392-.812 1.595-1.595h1.131c.464 0 .812-.377.812-.812 0-.464-.377-.812-.812-.812h-1.073V48.22h1.102c.435 0 .812-.348.812-.812s-.348-.812-.812-.812h-1.16c-.1885-.783-.812-1.421-1.595-1.624v-1.131c0-.464-.377-.812-.812-.812-.464 0-.812.377-.812.812v1.073H6.162v-1.073c0-.464-.377-.812-.812-.812zm.58 3.48h2.088c.754 0 1.363.609 1.363 1.363v2.088c0 .754-.609 1.363-1.363 1.363H5.93c-.754 0-1.363-.609-1.363-1.363v-2.088c0-.754.609-1.363 1.363-1.363z" style="fill: grey"></path>
2020-11-12 23:00:06 +01:00
</svg>
<svg viewBox="0 0 14 60" class="gl-gpu-svg">
<line x1="7" y1="38" x2="7" y2="11" class="opacity"/>
<line x1="7" y1="38" x2="7" y2="11" class="gl-gpu" stroke-dasharray="0 27"/>
2020-11-14 23:22:59 +01:00
<path d="M1.94775 43.3772a.736.736 0 10-.00416 1.472c.58535.00231.56465.1288.6348.3197.07015.18975.04933.43585.04933.43585l-.00653.05405v8.671a.736.736 0 101.472 0v-1.4145c.253.09522.52785.1495.81765.1495h5.267c1.2535 0 2.254-.9752 2.254-2.185v-3.105c0-1.2075-1.00625-2.185-2.254-2.185h-5.267c-.28865 0-.5635.05405-.8165.1495.01806-.16445.04209-.598-.1357-1.0787-.22425-.6072-.9499-1.2765-2.0125-1.2765zm2.9095 3.6455c.42435 0 .7659.36225.7659.8119v2.9785c0 .44965-.34155.8119-.7659.8119s-.7659-.36225-.7659-.8119v-2.9785c0-.44965.34155-.8119.7659-.8119zm4.117 0a2.3 2.3 0 012.3 2.3 2.3 2.3 0 01-2.3 2.3 2.3 2.3 0 01-2.3-2.3 2.3 2.3 0 012.3-2.3z" style="fill: grey"></path>
2020-11-12 23:00:06 +01:00
</svg>
</div>
2020-12-18 03:09:25 +01:00
`,GLBench=class{constructor(gl,settings={}){this.css=UICSS,this.svg=UISVG,this.paramLogger=()=>{},this.chartLogger=()=>{},this.chartLen=20,this.chartHz=20,this.names=[],this.cpuAccums=[],this.gpuAccums=[],this.activeAccums=[],this.chart=new Array(this.chartLen),this.now=()=>performance&&performance.now?performance.now():Date.now(),this.updateUI=()=>{[].forEach.call(this.nodes["gl-gpu-svg"],node=>node.style.display=this.trackGPU?"inline":"none")},Object.assign(this,settings),this.detected=0,this.finished=[],this.isFramebuffer=0,this.frameId=0;let rafId,n=0,t0,loop=t=>{++n<20?rafId=requestAnimationFrame(loop):(this.detected=Math.ceil(1e3*n/(t-t0)/70),cancelAnimationFrame(rafId)),t0||(t0=t)};if(requestAnimationFrame(loop),gl){let glFinish=async(t,activeAccums)=>Promise.resolve(setTimeout(()=>{gl.getError();let dt=this.now()-t;activeAccums.forEach((active,i)=>{active&&(this.gpuAccums[i]+=dt)})},0)),addProfiler=(fn2,self2,target)=>{let t=self2.now();fn2.apply(target,arguments),self2.trackGPU&&self2.finished.push(glFinish(t,self2.activeAccums.slice(0)))},fn="drawElements";gl[fn]?gl[fn]=addProfiler(gl[fn],this,gl):console.log("bench: cannot attach to webgl function")}if(!this.withoutUI){this.dom||(this.dom=document.body);let elm=document.createElement("div");elm.id="gl-bench",this.dom.appendChild(elm),this.dom.insertAdjacentHTML("afterbegin",'<style id="gl-bench-style">'+this.css+"</style>"),this.dom=elm,this.dom.addEventListener("click",()=>{this.trackGPU=!this.trackGPU,this.updateUI()}),this.paramLogger=((logger,dom,names)=>{let classes=["gl-cpu","gl-gpu","gl-mem","gl-fps","gl-gpu-svg","gl-chart"],nodes={...classes};return classes.forEach(c=>nodes[c]=dom.getElementsByClassName(c)),this.nodes=nodes,(i,cpu,gpu,mem,fps,totalTime,frameId)=>{nodes["gl-cpu"][i].style.strokeDasharray=(cpu*.27).toFixed(0)+" 100",nodes["gl-gpu"][i].style.strokeDasharray=(gpu*.27).toFixed(0)+" 100",nodes["gl-mem"][i].innerHTML=names[i]?names[i]:mem?"mem: "+mem.toFixed(0)+"mb":"",nodes["gl-fps"][i].innerHTML="FPS: "+fps.toFixed(1),logger(names[i],cpu,gpu,mem,fps,totalTime,frameId)}})(this.paramLogger,this.dom,this.names),this.chartLogger=((logger,dom)=>{let nodes={"gl-chart":dom.getElementsByClassName("gl-chart")};return(i,chart,circularId)=>{let points="",len=chart.length;for(let j=0;j<len;j++){let id=(circularId+j+1)%len;chart[id]!==void 0&&(points=points+" "+(55*j/(len-1)).toFixed(1)+","+(45-chart[id]*22/60/this.detected).toFixed(1))}nodes["gl-chart"][i].setAttribute("points",points),logger(this.names[i],chart,circularId)}})(this.chartLogger,this.dom)}}addUI(name){this.names.indexOf(name)===-1&&(this.names.push(name),this.dom&&(this.dom.insertAdjacentHTML("beforeend",this.svg),this.updateUI()),this.cpuAccums.push(0),this.gpuAccums.push(0),this.activeAccums.push(!1))}nextFrame(now3){this.frameId++;let t=now3||this.now();if(this.frameId<=1)this.paramFrame=this.frameId,this.paramTime=t;else{let duration=t-this.paramTime;if(duration>=1e3){let frameCount=this.frameId-this.paramFrame,fps=frameCount/duration*1e3;for(let i=0;i<this.names.length;i++){let cpu=this.cpuAccums[i]/duration*100,gpu=this.gpuAccums[i]/duration*100,mem=performance&&performance.memory?performance.memory.usedJSHeapSize/(1<<20):0;this.paramLogger(i,cpu,gpu,mem,fps,duration,frameCount),this.cpuAccums[i]=0,Promise.all(this.finished).then(()=>{this.gpuAccums[i]=0,this.finished=[]})}this.paramFrame=this.frameId,this.paramTime=t}}if(!this.detected||!this.chartFrame)this.chartFrame=this.frameId,this.chartTime=t,this.circularId=0;else{let timespan=t-this.chartTime,hz=this.chartHz*timespan/1e3;for(;--hz>0&&this.detected;){let frameCount=this.frameId-this.chartFrame,fps=frameCount/timespan*1e3;this.chart[this.circularId%this.chartLen]=fps;for(let i=0;i<this.names.length;i++)this.chartLogger(i,this.chart,this.circularId);this.circularId++,this.chartFrame=this.frameId,this.chartTime=t}}}begin(name){this.updateAccums(name)}end(name){this.updateAccums(name)}updateAccums(name){let nameId=this.names.indexOf(name);nameId===-1&&(nameId=this.names.length,this.addUI(name));let t=this.now(),dt=t-this.t0;
2020-11-26 16:37:04 +01:00
video: ${ui.camera.name} | facing: ${ui.camera.facing} | screen: ${window.innerWidth} x ${window.innerHeight} camera: ${ui.camera.width} x ${ui.camera.height} ${processing}<br>
backend: ${human.tf.getBackend()} | ${memory2}<br>
performance: ${str(result.performance)}ms FPS process:${avgDetect} refresh:${avgDraw}<br>
${warning}<br>
2020-12-08 15:00:44 +01:00
`,ui.framesDraw++,ui.lastFrame=performance.now(),ui.buffered?ui.drawThread=requestAnimationFrame(()=>drawResults(input2,canvas)):!ui.buffered&&ui.drawThread&&(log3("stopping buffered refresh"),cancelAnimationFrame(ui.drawThread),ui.drawThread=null)}async function setupCamera(){var _a;if(ui.busy)return null;ui.busy=!0;let video=document.getElementById("video"),canvas=document.getElementById("canvas"),output=document.getElementById("log"),live=video.srcObject?video.srcObject.getVideoTracks()[0].readyState==="live"&&video.readyState>2&&!video.paused:!1,msg="";if(status("setting up camera"),!navigator.mediaDevices)return msg="camera access not supported",output.innerText+=`
${msg}`,log3(msg),status(msg),ui.busy=!1,msg;let stream,constraints={audio:!1,video:{facingMode:ui.facing?"user":"environment",resizeMode:ui.crop?"crop-and-scale":"none"}};window.innerWidth>window.innerHeight?constraints.video.width={ideal:window.innerWidth}:constraints.video.height={ideal:window.innerHeight-document.getElementById("menubar").offsetHeight};try{stream=await navigator.mediaDevices.getUserMedia(constraints)}catch(err){return err.name==="PermissionDeniedError"||err.name==="NotAllowedError"?msg="camera permission denied":err.name==="SourceUnavailableError"?msg="camera not available":msg=`camera error: ${err.message||err}`,output.innerText+=`
2020-12-27 14:12:22 +01:00
${msg}`,status(msg),log3("camera error:",err),ui.busy=!1,msg}if(stream)video.srcObject=stream;else return ui.busy=!1,"camera stream empty";let track=stream.getVideoTracks()[0],settings=track.getSettings();return ui.camera={name:(_a=track.label)==null?void 0:_a.toLowerCase(),width:settings.width,height:settings.height,facing:settings.facingMode==="user"?"front":"back"},new Promise(resolve=>{video.onloadeddata=async()=>{video.width=video.videoWidth,video.height=video.videoHeight,canvas.width=video.width,canvas.height=video.height,canvas.style.width=canvas.width>canvas.height?"100vw":"",canvas.style.height=canvas.width>canvas.height?"":"100vh",ui.menuWidth.input.setAttribute("value",video.width),ui.menuHeight.input.setAttribute("value",video.height);let size=Math.trunc(window.devicePixelRatio*(8+4*canvas.width/window.innerWidth));ui.baseFont=ui.baseFontProto.replace(/{size}/,`${size}px`),ui.baseLineHeight=size+4,live&&video.play(),live&&!ui.detectThread&&runHumanDetect(video,canvas),ui.busy=!1,status(""),resolve()}})}function initPerfMonitor(){if(!bench){let gl=null;bench=new gl_bench_default(gl,{trackGPU:!1,chartHz:20,chartLen:20}),bench.begin()}}function webWorker(input2,image3,canvas,timestamp){worker||(log3("creating worker thread"),worker=new Worker(ui.worker,{type:"module"}),worker.addEventListener("message",msg=>{msg.data.result.performance&&msg.data.result.performance.total&&ui.detectFPS.push(1e3/msg.data.result.performance.total),ui.detectFPS.length>ui.maxFPSframes&&ui.detectFPS.shift(),ui.bench&&(bench||initPerfMonitor(),bench.nextFrame(timestamp)),document.getElementById("gl-bench")&&(document.getElementById("gl-bench").style.display=ui.bench?"block":"none"),lastDetectedResult=msg.data.result,ui.framesDetect++,ui.drawThread||drawResults(input2),ui.detectThread=requestAnimationFrame(now3=>runHumanDetect(input2,canvas,now3))})),worker.postMessage({image:image3.data.buffer,width:canvas.width,height:canvas.height,userConfig},"Human",[image3.data.buffer])}function runHumanDetect(input2,canvas,timestamp){var _a;let live=input2.srcObject&&input2.srcObject.getVideoTracks()[0].readyState==="live"&&input2.readyState>2&&!input2.paused;if(!live&&input2.srcObject){ui.drawThread&&cancelAnimationFrame(ui.drawThread),ui.detectThread&&cancelAnimationFrame(ui.detectThread),ui.drawThread=null,ui.detectThread=null,input2.paused?log3("camera paused"):input2.srcObject.getVideoTracks()[0].readyState==="live"&&input2.readyState<=2?setTimeout(()=>runHumanDetect(input2,canvas),500):log3(`camera not ready: track state: ${(_a=input2.srcObject)==null?void 0:_a.getVideoTracks()[0].readyState} stream state: ${input2.readyState}`),clearTimeout(ui.drawThread),ui.drawThread=null,log3("frame statistics: process:",ui.framesDetect,"refresh:",ui.framesDraw),log3("memory",human.tf.engine().memory());return}if(status(""),ui.useWorker){let offscreen=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(canvas.width,canvas.height):document.createElement("canvas");offscreen.width=canvas.width,offscreen.height=canvas.height;let ctx=offscreen.getContext("2d");ctx.drawImage(input2,0,0,input2.width,input2.height,0,0,canvas.width,canvas.height);let data=ctx.getImageData(0,0,canvas.width,canvas.height);webWorker(input2,data,canvas,userConfig,timestamp)}else human.detect(input2,userConfig).then(result=>{result.performance&&result.performance.total&&ui.detectFPS.push(1e3/result.performance.total),ui.detectFPS.length>ui.maxFPSframes&&ui.detectFPS.shift(),ui.bench&&(bench||initPerfMonitor(),bench.nextFrame(timestamp)),document.getElementById("gl-bench")&&(document.getElementById("gl-bench").style.display=ui.bench?"block":"none"),result.error?(log3(result.error),document.getElementById("log").innerText+=`
2020-12-13 00:34:30 +01:00
Human error: ${result.error}`):(lastDetectedResult=result,ui.drawThread||drawResults(input2),ui.framesDetect++,ui.detectThread=requestAnimationFrame(now3=>runHumanDetect(input2,canvas,now3)))})}async function processImage(input2){return new Promise(resolve=>{let image3=new Image;image3.onload=async()=>{log3("Processing image:",image3.src);let canvas=document.getElementById("canvas");image3.width=image3.naturalWidth,image3.height=image3.naturalHeight,canvas.width=human.config.filter.width&&human.config.filter.width>0?human.config.filter.width:image3.naturalWidth,canvas.height=human.config.filter.height&&human.config.filter.height>0?human.config.filter.height:image3.naturalHeight;let result=await human.detect(image3,userConfig);lastDetectedResult=result,await drawResults(image3);let thumb=document.createElement("canvas");thumb.className="thumbnail",thumb.width=window.innerWidth/(ui.columns+.1),thumb.height=canvas.height/(window.innerWidth/thumb.width);let ctx=thumb.getContext("2d");ctx.drawImage(canvas,0,0,canvas.width,canvas.height,0,0,thumb.width,thumb.height),document.getElementById("samples-container").appendChild(thumb),image3.src="",resolve(!0)},image3.src=input2})}async function detectVideo(){userConfig.videoOptimized=!0,document.getElementById("samples-container").style.display="none",document.getElementById("canvas").style.display="block";let video=document.getElementById("video"),canvas=document.getElementById("canvas");if(video.srcObject!==null&&!video.paused)document.getElementById("play").style.display="block",document.getElementById("btnStart").className="button button-start",document.getElementById("btnStart").innerHTML="start<br>video",status("paused"),video.pause();else{let cameraError=await setupCamera();if(cameraError)status(cameraError);else{document.getElementById("play").style.display="none";for(let m of Object.values(menu2))m.hide();status(""),document.getElementById("btnStart").className="button button-stop",document.getElementById("btnStart").innerHTML="pause<br>video",await video.play(),ui.detectThread||runHumanDetect(video,canvas)}}}async function detectSampleImages(){document.getElementById("play").style.display="none",userConfig.videoOptimized=!1;let size=Math.trunc(window.devicePixelRatio*(8+4*ui.columns));ui.baseFont=ui.baseFontProto.replace(/{size}/,`${size}px`),ui.baseLineHeight=size+2,document.getElementById("canvas").style.display="none",document.getElementById("samples-container").style.display="block",log3("Running detection of sample images"),status("processing images"),document.getElementById("samples-container").innerHTML="";for(let image3 of ui.samples)await processImage(image3);status("")}function setupMenu(){let x=[];window.innerWidth>800?x=[`${document.getElementById("btnDisplay").offsetLeft-50}px`,`${document.getElementById("btnImage").offsetLeft-50}px`,`${document.getElementById("btnProcess").offsetLeft-50}px`,`${document.getElementById("btnModel").offsetLeft-50}px`]:x=["0rem","11rem","21.1rem","33rem"],menu2.display=new menu_default(document.body,"",{top:`${document.getElementById("menubar").offsetHeight}px`,left:x[0]}),menu2.display.addBool("perf monitor",ui,"bench",val=>ui.bench=val),menu2.display.addBool("buffered output",ui,"buffered",val=>ui.buffered=val),menu2.display.addBool("crop & scale",ui,"crop",()=>setupCamera()),menu2.display.addBool("camera facing",ui,"facing",()=>setupCamera()),menu2.display.addHTML('<hr style="border-style: inset; border-color: dimgray">'),menu2.display.addBool("use 3D depth",ui,"useDepth"),menu2.display.addBool("draw boxes",ui,"drawBoxes"),menu2.display.addBool("draw polygons",ui,"drawPolygons"),menu2.display.addBool("Fill Polygons",ui,"fillPolygons"),menu2.display.addBool("draw points",ui,"drawPoints"),menu2.image=new menu_default(document.body,"",{top:`${document.getElementById("menubar").offsetHeight}px`,left:x[1]}),menu2.image.addBool("enabled",human.config.filter,"enabled"),ui.menuWidth=menu2.image.addRange("image width",human.config.filter,"width",0,3840,10,val=>human.config.filter.width=parseInt(val)),ui.menuHeight=menu2.image.addRange
2020-11-16 21:51:46 +01:00
/**
* @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.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @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.
*
* =============================================================================
*/
/**
* @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.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @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.
*
* =============================================================================
*/
/**
* @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.
* =============================================================================
*/
/**
* @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.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @license See the LICENSE file. */
2020-11-04 17:43:51 +01:00
//# sourceMappingURL=demo-browser-index.js.map