| 61 | } |
| 62 | |
| 63 | getUserCode(): string { |
| 64 | let reduceOp = ``; |
| 65 | let initValue = '0.0'; |
| 66 | const workgroupSizeX = this.workgroupSize[0]; |
| 67 | if (this.reduceType === 'min' || this.reduceType === 'max') { |
| 68 | reduceOp = ` |
| 69 | if (isnan(candidate)) { |
| 70 | bestValue = uniforms.NAN; |
| 71 | } else if (!isnan(bestValue) && candidate ${ |
| 72 | this.reduceType === 'min' ? '<' : '>'} bestValue) |
| 73 | { bestValue = candidate; }`; |
| 74 | initValue = 'f32(x[offset])'; |
| 75 | } else if (this.reduceType === 'sum' || this.reduceType === 'mean') { |
| 76 | reduceOp = ' bestValue = bestValue + candidate; '; |
| 77 | } else if (this.reduceType === 'prod') { |
| 78 | reduceOp = ' bestValue = bestValue * candidate; '; |
| 79 | initValue = '1.0'; |
| 80 | } else if (this.reduceType === 'all') { |
| 81 | reduceOp = ' bestValue = f32(bestValue >= 1.0 && candidate >= 1.0); '; |
| 82 | initValue = '1.0'; |
| 83 | } else if (this.reduceType === 'any') { |
| 84 | reduceOp = ' bestValue = f32(bestValue >= 1.0 || candidate >= 1.0); '; |
| 85 | initValue = '0.0'; |
| 86 | } |
| 87 | |
| 88 | const outputSnippet = this.reduceType === 'mean' ? |
| 89 | // tslint:disable-next-line:max-line-length |
| 90 | `setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));` : |
| 91 | `setOutputAtIndex(outputIndex, bestValue);`; |
| 92 | |
| 93 | const sharedMemorySnippet = ` |
| 94 | var<workgroup> xBestValues : array<f32, ${workgroupSizeX}>; |
| 95 | `; |
| 96 | |
| 97 | const userCode = ` |
| 98 | fn DIV_CEIL(a : u32, b : u32) -> u32 { |
| 99 | return ((a - 1u) / b + 1u); |
| 100 | } |
| 101 | |
| 102 | ${sharedMemorySnippet} |
| 103 | fn getOffset(outputIndex : i32) -> i32 { |
| 104 | let outputCoords = getCoordsFromIndex(outputIndex); |
| 105 | let offset = ${ |
| 106 | this.outputShape.length === 1 ? |
| 107 | 'outputCoords' : |
| 108 | 'outputCoords[0]'} * uniforms.reduceSize; |
| 109 | return offset; |
| 110 | } |
| 111 | ${main('index')} { |
| 112 | let outputIndex = index / ${workgroupSizeX}; |
| 113 | let offset = getOffset(outputIndex); |
| 114 | var bestValue = ${initValue}; |
| 115 | let Length = uniforms.reduceSize; |
| 116 | let WorkPerThread = DIV_CEIL(u32(Length), ${workgroupSizeX}u); |
| 117 | for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size; |
| 118 | k = k + ${workgroupSizeX}) { |
| 119 | let candidate = f32(x[offset + k]); |
| 120 | ${reduceOp} |