Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webgpu: Support depthwise conv2d with nchw format #6084

Merged
merged 16 commits into from
Jun 13, 2022
177 changes: 177 additions & 0 deletions tfjs-backend-webgpu/src/depthwise_conv2d_nchw_shared_webgpu.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/**
* @license
* Copyright 2022 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/

import {backend_util} from '@tensorflow/tfjs-core';

import {mapActivationToShaderProgram} from './activation_util';
import {getWorkGroupSizeString, WebGPUProgram} from './webgpu_program';
import {computeDispatch} from './webgpu_util';

export class DepthwiseConv2DNCHWSharedProgram implements WebGPUProgram {
outputShape: number[];
shaderKey: string;
dispatchLayout: {x: number[], y: number[], z: number[]};
dispatch: [number, number, number];
variableNames = ['x', 'W'];
uniforms = `pad : vec2<i32>, stride : vec2<i32>, dilation : vec2<i32>,
inDims : vec2<i32>, filterHeight : i32, filterWidth : i32,
channelMul : i32,`;
workGroupSize: [number, number, number] = [16, 16, 1];
addBias: boolean;
activation: backend_util.Activation;
hasPreluActivation: boolean;
filterHeight: number;
filterWidth: number;

constructor(
outputShape: number[], filterHeight: number, filterWidth: number,
addBias = false, activation: backend_util.Activation = null,
hasPreluActivation = false) {
this.outputShape = outputShape;
this.dispatchLayout = {x: [3], y: [2], z: [0, 1]};
this.dispatch = computeDispatch(
this.dispatchLayout, this.outputShape, this.workGroupSize);

if (addBias) {
this.variableNames.push('bias');
}
if (hasPreluActivation) {
this.variableNames.push('preluActivationWeights');
}

this.addBias = addBias;
this.activation = activation;
this.hasPreluActivation = hasPreluActivation;
this.filterHeight = filterHeight;
this.filterWidth = filterWidth;
this.shaderKey = `depthwiseNCHW_${this.activation}_${this.filterHeight}_${
this.filterWidth}`;
}

getUserCode(): string {
let activationSnippet = '', applyActivationSnippet = '';
if (this.activation) {
const activationOp = mapActivationToShaderProgram(this.activation, false);
if (this.hasPreluActivation) {
activationSnippet =
`fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
let b = getPreluActivationWeightsByOutputCoords(outCoord);
${activationOp}
}`;
} else {
activationSnippet = `
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
${activationOp}
}
`;
}

applyActivationSnippet = `dotProd = activation(dotProd, coords);`;
}

const addBiasSnippet = this.addBias ?
'dotProd = dotProd + getBiasByOutputCoords(coords);' :
'';

const filterSize = this.filterWidth * this.filterHeight;
const workGroupSize =
this.workGroupSize[0] * this.workGroupSize[1] * this.workGroupSize[2];
const tileAHeight = this.workGroupSize[1] + this.filterHeight - 1;
const tileAWidth = this.workGroupSize[0] + this.filterWidth - 1;

const userCode = `
${activationSnippet}

var<workgroup> mm_Asub : array<array<f32, ${tileAWidth}>, ${tileAHeight}>;
var<workgroup> mm_Bsub : array<array<f32, ${this.filterWidth}>, ${
this.filterHeight}>;
fn readX(batch : i32, channel : i32, row : i32, col : i32) -> f32 {
var value = 0.0;
if (row >=0 && row < uniforms.inDims[0] && col >=0 && col < uniforms.inDims[1])
{
value = getX(batch, channel, row, col);
}
return value;
}

${getWorkGroupSizeString()}
fn main(@builtin(local_invocation_id) LocalId : vec3<u32>,
@builtin(global_invocation_id) GlobalId : vec3<u32>,
@builtin(local_invocation_index) LocalIndex: u32,
@builtin(num_workgroups) NumWorkgroups: vec3<u32>) {
localId = LocalId;
globalId = GlobalId;
let localIndex = i32(LocalIndex);
numWorkgroups = NumWorkgroups;
let coords = getOutputCoords();
let batch = coords[0];
let xRCCorner = vec2<i32>(coords.zw) * uniforms.stride - uniforms.pad;
let d2 = coords[1];
let d1 = d2 / uniforms.channelMul;
let q = d2 - d1 * uniforms.channelMul;

let inputRowStart = xRCCorner.x;
let inputColStart = xRCCorner.y;

let localRow = i32(localId.y);
let localCol = i32(localId.x);

// Load one tile of X into local memory.
for (var inputRow = localRow; inputRow < ${
tileAHeight}; inputRow = inputRow + ${this.workGroupSize[1]}) {
for (var inputCol = localCol; inputCol < ${
tileAWidth}; inputCol = inputCol + ${this.workGroupSize[0]}) {
let rowOffset = inputRow - localRow;
let colOffset = inputCol - localCol;
mm_Asub[inputRow][inputCol] = readX(batch, d1, inputRowStart + rowOffset, inputColStart + colOffset);
}
}

// Load one tile of W into local memory.
var wIndex = localIndex;
${
filterSize < workGroupSize ?
`if (wIndex < ${filterSize})` :
`for(; wIndex < ${filterSize}; wIndex = wIndex + ${workGroupSize})`}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is if statement needed here? Is it already a subset of for?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I may be slightly good for perf to use if instead of for since it doesn't need to call wIndex = wIndex + ${workGroupSize}) and another wIndex < ${filterSize} checking if filterSize is smaller than workGroupSize.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it, thank you.


{
let wRow = wIndex / ${this.filterWidth};
let wCol = wIndex % ${this.filterWidth};
mm_Bsub[wRow][wCol] = getW(wRow, wCol, d1, q);
}

workgroupBarrier();

var dotProd = 0.0;
for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
let xVal = mm_Asub[localRow + wR][localCol + wC];
let wVal = mm_Bsub[wR][wC];
dotProd = fma(xVal, wVal, dotProd);
}
}

${addBiasSnippet}
${applyActivationSnippet}
if (coordsInBounds4D(coords, uniforms.outShape)) {
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd);
}
}
`;
return userCode;
}
}
42 changes: 19 additions & 23 deletions tfjs-backend-webgpu/src/depthwise_conv2d_webgpu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* =============================================================================
*/

import {backend_util, util} from '@tensorflow/tfjs-core';
import {backend_util} from '@tensorflow/tfjs-core';

import {mapActivationToShaderProgram} from './activation_util';
import {getMainHeaderString, WebGPUProgram} from './webgpu_program';
Expand All @@ -36,6 +36,7 @@ export class DepthwiseConv2DProgram implements WebGPUProgram {
addBias: boolean;
activation: backend_util.Activation;
hasPreluActivation: boolean;
isChannelsLast: boolean;

constructor(
convInfo: backend_util.Conv2DInfo, addBias = false,
Expand All @@ -44,10 +45,7 @@ export class DepthwiseConv2DProgram implements WebGPUProgram {
this.dispatchLayout = flatDispatchLayout(this.outputShape);
this.dispatch = computeDispatch(
this.dispatchLayout, this.outputShape, this.workGroupSize);

util.assert(
convInfo.dataFormat === 'channelsLast',
() => 'TODO: NCHW is unimplemented');
this.isChannelsLast = convInfo.dataFormat === 'channelsLast';

if (addBias) {
this.variableNames.push('bias');
Expand All @@ -60,7 +58,7 @@ export class DepthwiseConv2DProgram implements WebGPUProgram {
this.addBias = addBias;
this.activation = activation;
this.hasPreluActivation = hasPreluActivation;
this.shaderKey = `depthwise_${this.activation}`;
this.shaderKey = `depthwise_${this.activation}_${this.isChannelsLast}`;
}

getUserCode(): string {
Expand Down Expand Up @@ -88,22 +86,18 @@ export class DepthwiseConv2DProgram implements WebGPUProgram {
'dotProd = dotProd + getBiasByOutputCoords(coords);' :
'';

const getXSnippet = this.isChannelsLast ? 'getX(batch, xR, xC, d1);' :
'getX(batch, d1, xR, xC);';

const userCode = `
${activationSnippet}

fn writeResult(batch : i32, row : i32, col : i32, chan : i32,
value : f32) {
let coord = vec4<i32>(batch, row, col, chan);
if (coordsInBounds4D(coord, uniforms.outShape)) {
setOutputAtCoords(batch, row, col, chan, value);
}
}

${getMainHeaderString()}
let coords = getOutputCoords();
let batch = coords[0];
let xRCCorner = vec2<i32>(coords.yz) * uniforms.stride - uniforms.pad;
let d2 = coords[3];
let xRCCorner = vec2<i32>(coords.${
this.isChannelsLast ? 'yz' : 'zw'}) * uniforms.stride - uniforms.pad;
let d2 = coords[${this.isChannelsLast ? 3 : 1}];
let d1 = d2 / uniforms.channelMul;
let q = d2 - d1 * uniforms.channelMul;

Expand All @@ -114,23 +108,23 @@ export class DepthwiseConv2DProgram implements WebGPUProgram {
let inputColEnd = inputColStart + uniforms.filterWidth *
uniforms.dilation[1];

// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
// Convolve x(?, ?, d1)|x(d1, ?, ?) with w(:, :, d1, q) to get
// y(yR, yC, d2)|y(d2, yR, yC). ? = to be determined. : = across all
// values in that axis. x(?, ?, d1) and y(yR, yC, d2) is for NHWC.
// x(d1, ?, ?) and y(d2, yR, yC) is for NCHW.
var dotProd = 0.0;

// Extract if checking out of for loop for performance.
if (inputRowStart >= 0 && inputColStart >= 0 &&
inputRowEnd < uniforms.inDims[0] &&
inputColEnd < uniforms.inDims[1]) {
// Here using a constant value |this.convInfo.filterHeight| instead
// of uniform value is in order to loop unrolling.
for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
let xR = inputRowStart + wR * uniforms.dilation[0];

for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
let xC = inputColStart + wC * uniforms.dilation[1];

let xVal = getX(batch, xR, xC, d1);
let xVal = ${getXSnippet};
let wVal = getW(wR, wC, d1, q);
dotProd = dotProd + xVal * wVal;
}
Expand All @@ -150,7 +144,7 @@ export class DepthwiseConv2DProgram implements WebGPUProgram {
continue;
}

let xVal = getX(batch, xR, xC, d1);
let xVal = ${getXSnippet};
let wVal = getW(wR, wC, d1, q);
dotProd = dotProd + xVal * wVal;
}
Expand All @@ -159,7 +153,9 @@ export class DepthwiseConv2DProgram implements WebGPUProgram {

${addBiasSnippet}
${applyActivationSnippet}
writeResult(batch, coords[1], coords[2], d2, dotProd);
if (coordsInBounds4D(coords, uniforms.outShape)) {
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd);
}
}
`;
return userCode;
Expand Down
31 changes: 23 additions & 8 deletions tfjs-backend-webgpu/src/kernels/DepthwiseConv2dNative.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {backend_util, DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, Depthwi

import {WebGPUBackend} from '../backend_webgpu';
import {DepthwiseConv2D3x3Program} from '../depthwise_conv2d_3x3_webgpu';
import {DepthwiseConv2DNCHWSharedProgram} from '../depthwise_conv2d_nchw_shared_webgpu';
import {DepthwiseConv2DProgram} from '../depthwise_conv2d_webgpu';

export function depthwiseConv2dNative(args: {
Expand All @@ -28,8 +29,8 @@ export function depthwiseConv2dNative(args: {
}) {
const {inputs, backend, attrs} = args;
const {x, filter} = inputs;
const {strides, pad, dilations, dimRoundingMode} = attrs;

const {strides, pad, dataFormat, dilations, dimRoundingMode} = attrs;
const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);
let $dilations = dilations;
if ($dilations == null) {
$dilations = [1, 1];
Expand All @@ -38,19 +39,33 @@ export function depthwiseConv2dNative(args: {
const convInfo = backend_util.computeConv2DInfo(
x.shape as [number, number, number, number],
filter.shape as [number, number, number, number], strides, $dilations,
pad, dimRoundingMode, true /* depthwise */);

pad, dimRoundingMode, true /* depthwise */, $dataFormat);
const dimensions = [
{type: 'int32', data: [convInfo.padInfo.top, convInfo.padInfo.left]},
{type: 'int32', data: [convInfo.strideHeight, convInfo.strideWidth]},
{type: 'int32', data: [convInfo.dilationHeight, convInfo.dilationWidth]},
{type: 'int32', data: [convInfo.inHeight, convInfo.inWidth]}
];

let program: DepthwiseConv2DProgram|DepthwiseConv2D3x3Program;
// TODO: To see if we need to relax the limitation. Currently, it's only for
// filter size 3x3.
if (convInfo.batchSize === 1 && convInfo.inHeight === convInfo.outHeight &&
const isChannelsLast = convInfo.dataFormat === 'channelsLast';
let program: DepthwiseConv2DProgram|DepthwiseConv2D3x3Program|
DepthwiseConv2DNCHWSharedProgram;
if (!isChannelsLast && convInfo.inHeight > 16 && convInfo.inWidth > 16 &&
convInfo.strideHeight === 1 && convInfo.strideWidth === 1 &&
convInfo.dilationWidth === 1 && convInfo.dilationHeight === 1 &&
convInfo.inChannels === convInfo.outChannels) {
dimensions.push(
{type: 'int32', data: [convInfo.filterHeight]},
{type: 'int32', data: [convInfo.filterWidth]},
{type: 'int32', data: [convInfo.outChannels / convInfo.inChannels]});
program = new DepthwiseConv2DNCHWSharedProgram(
convInfo.outShape, convInfo.filterHeight, convInfo.filterWidth);
}
// TODO: To see if we need to relax the limitation. Currently, it's only
// for filter size 3x3.
else if (
isChannelsLast && convInfo.batchSize === 1 &&
convInfo.inHeight === convInfo.outHeight &&
convInfo.inWidth === convInfo.outWidth && convInfo.strideHeight === 1 &&
convInfo.strideWidth === 1 &&
convInfo.filterHeight === convInfo.filterWidth &&
Expand Down
Loading