Skip to content

Commit

Permalink
[js/web] BiasSplitGelu and BiasAdd kernels (microsoft#17161)
Browse files Browse the repository at this point in the history
### Description
Two contrib kernels that supposed to speed-up StableDiffusion according
to this doc
https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/transformers/models/stable_diffusion/README.md

However, there is no noticable effect in speed or memory consumption. So
i guess the only way to make it faster is to implement
MultiHeadAttention but i'm not capable of doing that right now. So i'll
focus on existing PRs and finding the JSEP kernel that produces
incorrect results. It should be one of the old ones (i suspect Conv or
ConvTranspose), as SD was not generating images correctly on webgpu
since i started working on it. I hoped someone else would fix that by
the time i finish with kernels/optimizations 😅

---------

Co-authored-by: Guenther Schmuelling <[email protected]>
Co-authored-by: Yulong Wang <[email protected]>
  • Loading branch information
3 people authored Oct 3, 2023
1 parent d11e053 commit d0519a7
Show file tree
Hide file tree
Showing 12 changed files with 2,443 additions and 0 deletions.
2 changes: 2 additions & 0 deletions js/web/docs/webgpu-operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ Do not modify directly.*
| Atan | ai.onnx(7+) | |
| Atanh | ai.onnx(9+) | |
| AveragePool | ai.onnx(7-9,10,11+); com.ms.internal.nhwc(11+) | need perf optimization; need implementing activation |
| BiasAdd | com.microsoft(1+) | |
| BiasSplitGelu | com.microsoft(1+) | |
| Cast | ai.onnx(6-8,9-12,13-18,19+) | |
| Ceil | ai.onnx(6-12,13+) | |
| Clip | ai.onnx(6-10,11,12,13+) | |
Expand Down
4 changes: 4 additions & 0 deletions js/web/lib/wasm/jsep/webgpu/op-resolve-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Licensed under the MIT License.

import {argMax, argMin, parseArgMinMaxAttributes} from './ops/argminmax';
import {biasAdd} from './ops/bias-add';
import {biasSplitGelu} from './ops/bias-split-gelu';
import * as binaryOps from './ops/binary-op';
import {concat, parseConcatAttributes} from './ops/concat';
import {conv, parseConvAttributes} from './ops/conv';
Expand Down Expand Up @@ -45,6 +47,8 @@ export const WEBGPU_OP_RESOLVE_RULES: Map<string, OperatorImplementation> = new
['Atanh', [unaryOps.atanh]],
// TODO: support new attributes for AveragePool-10
['AveragePool', [pool.averagePool, pool.parseAveragePoolAttributes]],
['BiasAdd', [biasAdd]],
['BiasSplitGelu', [biasSplitGelu]],
['Cast', [unaryOps.cast, unaryOps.parseCastAttributes]],
['Ceil', [unaryOps.ceil]],
['ClipV10', [unaryOps.clipV10]],
Expand Down
69 changes: 69 additions & 0 deletions js/web/lib/wasm/jsep/webgpu/ops/bias-add.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {TensorView} from '../../tensor-view';
import {ShapeUtil} from '../../util';
import {ComputeContext, GpuDataType, ProgramInfo, ProgramMetadata} from '../types';

import {inputVariable, outputVariable, ShaderHelper} from './common';

const validateInputs = (inputs: readonly TensorView[]): void => {
if (inputs[0].dims.length !== 3) {
throw new Error('input should have 3 dimensions');
}

if (![320, 640, 1280].includes(inputs[0].dims[2])) {
throw new Error('number of channels should be 320, 640 or 1280');
}

if (inputs[1].dims.length !== 1) {
throw new Error('bias is expected to have 1 dimensions');
}

if (inputs[0].dims[2] !== inputs[1].dims[0]) {
throw new Error('last dimension of input and bias are not the same');
}
};

const createBiasAddProgramInfo = (metadata: ProgramMetadata, inputs: readonly TensorView[]): ProgramInfo => {
const outputShape = inputs[0].dims;

const channels = inputs[0].dims[2];
// since channel number can be only 320/640/1280, it's always divisable by 4
const outputSize = ShapeUtil.size(outputShape) / 4;

const dataType = inputs[0].dataType;
const input = inputVariable('input', dataType, outputShape, 4);
const bias = inputVariable('bias', dataType, [channels], 4);
const residual = inputVariable('residual', dataType, outputShape, 4);
const output = outputVariable('output', dataType, outputShape, 4);

const getShaderSource = (shaderHelper: ShaderHelper) => `
const channels = ${channels}u / 4;
${shaderHelper.declareVariables(input, bias, residual, output)}
${shaderHelper.mainStart()}
${shaderHelper.guardAgainstOutOfBoundsWorkgroupSizes(outputSize)}
let value = ${input.getByOffset('global_idx')}
+ ${bias.getByOffset('global_idx % channels')} + ${residual.getByOffset('global_idx')};
${output.setByOffset('global_idx', 'value')}
}`;

return {
...metadata,
outputs: [{dims: outputShape, dataType: inputs[0].dataType, gpuDataType: GpuDataType.default}],
getShaderSource,
dispatchGroup: () => ({x: Math.ceil(outputSize / 64 /* workgroup size */)})
};
};

export const biasAdd = (context: ComputeContext): void => {
validateInputs(context.inputs);
const inputTypes = Array(context.inputs.length).fill(GpuDataType.default);
const metadata = {
name: 'BiasAdd',
inputTypes,
};

context.compute(createBiasAddProgramInfo(metadata, context.inputs));
};
76 changes: 76 additions & 0 deletions js/web/lib/wasm/jsep/webgpu/ops/bias-split-gelu.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {TensorView} from '../../tensor-view';
import {ShapeUtil} from '../../util';
import {ComputeContext, GpuDataType, ProgramInfo, ProgramMetadata} from '../types';

import {inputVariable, outputVariable, ShaderHelper} from './common';
import {erfImpl} from './unary-op';

const validateInputs = (inputs: readonly TensorView[]): void => {
if (inputs[0].dims.length !== 3) {
throw new Error('input should have 3 dimensions');
}

if (![2560, 5120, 10240].includes(inputs[0].dims[2])) {
throw new Error('hidden state should be 2560, 5120 or 10240');
}

if (inputs[1].dims.length !== 1) {
throw new Error('bias is expected to have 1 dimensions');
}

if (inputs[0].dims[2] !== inputs[1].dims[0]) {
throw new Error('last dimension of input and bias are not the same');
}
};

const createBiasSplitGeluProgramInfo = (metadata: ProgramMetadata, inputs: readonly TensorView[]): ProgramInfo => {
const outputShape = inputs[0].dims.slice();
outputShape[2] = outputShape[2] / 2;

const input = inputVariable('input', inputs[0].dataType, inputs[0].dims, 4);
const bias = inputVariable('bias', inputs[0].dataType, [inputs[0].dims[2]], 4);
const output = outputVariable('output', inputs[0].dataType, outputShape, 4);

const outputSize = ShapeUtil.size(outputShape) / 4;

const getShaderSource = (shaderHelper: ShaderHelper) => `
const M_SQRT2 = sqrt(2.0);
const halfChannels = ${inputs[0].dims[2] / 4 / 2}u;
${shaderHelper.declareVariables(input, bias, output)}
${erfImpl('vec4f')}
${shaderHelper.mainStart()}
${shaderHelper.guardAgainstOutOfBoundsWorkgroupSizes(outputSize)}
let biasIdx = global_idx % halfChannels;
let batchIndex = global_idx / halfChannels;
let inputOffset = biasIdx + batchIndex * halfChannels * 2;
let valueLeft = input[inputOffset] + bias[biasIdx];
let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];
let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
${output.setByOffset('global_idx', 'valueLeft * geluRight')}
}`;

return {
...metadata,
outputs: [{dims: outputShape, dataType: inputs[0].dataType, gpuDataType: GpuDataType.default}],
getShaderSource,
dispatchGroup: () => ({x: Math.ceil(outputSize / 64 /* workgroup size */)})
};
};

export const biasSplitGelu = (context: ComputeContext): void => {
validateInputs(context.inputs);

const metadata = {
name: 'BiasSplitGelu',
inputTypes: [GpuDataType.default, GpuDataType.default],
};

context.compute(createBiasSplitGeluProgramInfo(metadata, context.inputs));
};
Loading

0 comments on commit d0519a7

Please sign in to comment.