mirror of
https://github.com/saymrwulf/onnxruntime.git
synced 2026-07-27 20:02:15 +00:00
### Description
<!-- Describe your changes. -->
In previous implementation, there are two loops to iterate H * W
elements to calculate the `mean` and `squaredNorm` value in one thread,
meanwhile it outputs H * W elements in one thread. That results it's
very very slow when H * W is a large value. And usually, H * W does be a
large value in a model. For example, in the `candy-8` model, the shapes
of [H, W] are [224,224], [112,112], [56,56] for `InstanceNormalization`
op. And in my ADL, `[1,224,224,32]` consumes 17 ms. See below:
```
[profiling] kernel "23848328|[InstanceNormalization] 23848328" input[0]: [1,224,224,32] | float32, input[1]: [32] | float32, input[2]: [32] | float32, output[0]: [1,224,224,32] | float32, execution time: 17007914 ns
```
In this PR, it uses workgroup memory to optimize the original algorithm.
The advantage is that it can parallelly utilize the 64 (workgroupSize)
threads in one workgroup to calculate `mean` and `squaredNorm` value.
Meanwhile, it only outputs `H * W / workgroupSize` outputs for one
thread, which greatly reduces the overhead for one thread. With this
optimization, `[1,224,224,32]` becomes 3 ms and the main overhead is the
extra two `transpose`. The `createInstanceNormProgramInfo` only needs
`0.64` ms. See below:
```
[profiling] kernel "23003600|[InstanceNormalization] 23003600" input[0]: [1,224,224,32] | float32, output[0]: [1,32,224,224] | float32, execution time: 1543792 ns
program-manager.ts:115
[profiling] kernel "23003600|[InstanceNormalization] 23003600" input[0]: [1,32,224,224] | float32, input[1]: [32] | float32, input[2]: [32] | float32, output[0]: [1,32,224,224] | float32, execution time: 642652 ns
program-manager.ts:115
[profiling] kernel "23003600|[InstanceNormalization] 23003600" input[0]: [1,32,224,224] | float32, output[0]: [1,224,224,32] | float32, execution time: 991608 ns
```
This PR currently only applies the new algorithm to NCHW format. For
NHWC format, one way is to transpose the input so that it can use the
new algorithm. But the disadvantage is that 2 extra transpose are added.
@dakenf also gives another way to optimize NHWC. Details see
[here](d45a96616d/js/web/lib/wasm/jsep/webgpu/ops/instance-norm.ts).
I checked @dakenf's method. The perf is similar with transpose +
optimized NCHW. But on different GPUs, one is a little better than
another or vice versa. So I prefer this PR only does the NCHW part.
@dakenf can submit his optimization on NHWC.
184 lines
7.2 KiB
TypeScript
184 lines
7.2 KiB
TypeScript
// Copyright (c) Microsoft Corporation. All rights reserved.
|
|
// Licensed under the MIT License.
|
|
|
|
import {TensorView} from '../../tensor';
|
|
import {ShapeUtil} from '../../util';
|
|
import {AttributeWithCacheKey, createAttributeWithCacheKey} from '../attribute-with-cache-key';
|
|
import {ComputeContext, GpuDataType, ProgramInfo, ProgramMetadata} from '../types';
|
|
|
|
import {inputVariable, outputVariable, ShaderHelper, tensorTypeToWsglStorageType} from './common';
|
|
|
|
export interface InstanceNormAttributes extends AttributeWithCacheKey {
|
|
epsilon: number;
|
|
format: 'NHWC'|'NCHW';
|
|
}
|
|
|
|
const createInstanceNormProgramInfo =
|
|
(metadata: ProgramMetadata, inputs: readonly TensorView[], attributes: InstanceNormAttributes): ProgramInfo => {
|
|
const xShape = inputs[0].dims;
|
|
|
|
const outputShape = xShape;
|
|
const axis = 2;
|
|
const normCount = ShapeUtil.sizeToDimension(xShape, axis);
|
|
const normSize = ShapeUtil.sizeFromDimension(xShape, axis);
|
|
const C = xShape[1];
|
|
const x = inputVariable('x', inputs[0].dataType, [xShape[0], xShape[1], normSize]);
|
|
const scale = inputVariable('scale', inputs[1].dataType, inputs[1].dims);
|
|
const bias = inputVariable('bias', inputs[2].dataType, inputs[2].dims);
|
|
const output = outputVariable('output', inputs[0].dataType, [xShape[0], xShape[1], normSize]);
|
|
const variables = [x, scale, bias, output];
|
|
const dataType = x.type.value;
|
|
const workgroupSize = 64;
|
|
const getShaderSource = (shaderHelper: ShaderHelper) => `
|
|
|
|
const C: u32 = ${C};
|
|
const normSize: u32 = ${normSize};
|
|
const epsilon: f32 = ${attributes.epsilon};
|
|
var<workgroup> meanShared : ${dataType};
|
|
var<workgroup> squaredNormShared : ${dataType};
|
|
var<workgroup> workgroupShared : array<${dataType}, ${workgroupSize}>;
|
|
const workgroupSize = ${workgroupSize}u;
|
|
${shaderHelper.declareVariables(...variables)}
|
|
${shaderHelper.mainStart(workgroupSize)}
|
|
let norm = global_idx / workgroupSize;
|
|
let batch = norm / C;
|
|
let channel = norm % C;
|
|
let localIndex = local_id.x;
|
|
|
|
// initialize workgroup memory
|
|
var initial: ${dataType} = 0;
|
|
for (var h = localIndex; h < normSize; h += workgroupSize) {
|
|
initial = initial + ${x.get('batch', 'channel', 'h')};
|
|
}
|
|
workgroupShared[localIndex] = initial;
|
|
workgroupBarrier();
|
|
|
|
// Calculate the mean of current channel data.
|
|
for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
if (localIndex < currSize) {
|
|
workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];
|
|
}
|
|
workgroupBarrier();
|
|
}
|
|
if (localIndex == 0) {
|
|
meanShared = workgroupShared[0] / ${dataType}(normSize);
|
|
}
|
|
workgroupBarrier();
|
|
|
|
// reinitialize workgroup memory.
|
|
initial = 0;
|
|
for (var h = localIndex; h < normSize; h += workgroupSize) {
|
|
let deviation = ${x.get('batch', 'channel', 'h')} - meanShared;
|
|
initial = initial + deviation * deviation;
|
|
}
|
|
workgroupShared[localIndex] = initial;
|
|
workgroupBarrier();
|
|
|
|
// Calculate the sum of square of deviation of current channel data.
|
|
for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {
|
|
if (localIndex < currSize) {
|
|
workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];
|
|
}
|
|
workgroupBarrier();
|
|
}
|
|
if (localIndex == 0) {
|
|
squaredNormShared = workgroupShared[0];
|
|
}
|
|
workgroupBarrier();
|
|
|
|
let invStdDev = 1 / sqrt(squaredNormShared / ${dataType}(normSize) + epsilon);
|
|
let channelScale = invStdDev * ${scale.getByOffset('channel')};
|
|
let channelShift = ${bias.getByOffset('channel')} - meanShared * channelScale;
|
|
for (var h = localIndex; h < normSize; h += workgroupSize) {
|
|
let value = ${x.get('batch', 'channel', 'h')} * channelScale + channelShift;
|
|
${output.set('batch', 'channel', 'h', 'value')};
|
|
}
|
|
}`;
|
|
return {
|
|
...metadata,
|
|
outputs: [
|
|
{dims: outputShape, dataType: inputs[0].dataType, gpuDataType: GpuDataType.default},
|
|
],
|
|
getShaderSource,
|
|
dispatchGroup: () => ({x: normCount})
|
|
};
|
|
};
|
|
|
|
const createInstanceNormNHWCProgramInfo =
|
|
(metadata: ProgramMetadata, inputs: readonly TensorView[], attributes: InstanceNormAttributes): ProgramInfo => {
|
|
const xShape = inputs[0].dims;
|
|
const outputShape = xShape;
|
|
const outputSize = ShapeUtil.size(outputShape);
|
|
const N = xShape[0];
|
|
const C = xShape[xShape.length - 1];
|
|
const H = ShapeUtil.sizeFromDimension(xShape, 1) / C;
|
|
|
|
const dataType = tensorTypeToWsglStorageType(inputs[0].dataType);
|
|
|
|
const normCount = C * N;
|
|
const getShaderSource = (shaderHelper: ShaderHelper) => `
|
|
const N: u32 = ${N};
|
|
const H: u32 = ${H};
|
|
const C: u32 = ${C};
|
|
const normSizeTyped: ${dataType} = ${H};
|
|
const imageSize: u32 = ${H * C};
|
|
const epsilon: f32 = ${attributes.epsilon};
|
|
|
|
@group(0) @binding(0) var<storage, read> x : array<${dataType}>;
|
|
@group(0) @binding(1) var<storage, read> scale : array<${dataType}>;
|
|
@group(0) @binding(2) var<storage, read> bias : array<${dataType}>;
|
|
@group(0) @binding(3) var<storage, read_write> output : array<${dataType}>;
|
|
|
|
${shaderHelper.mainStart()}
|
|
let currentImageNumber = global_idx / C;
|
|
let currentChannelNumber = global_idx % C;
|
|
|
|
// offset is channel num * N
|
|
let offset = currentImageNumber * imageSize;
|
|
if (offset >= ${outputSize}) { return; }
|
|
var mean: ${dataType} = 0;
|
|
|
|
for (var i: u32 = 0u; i < H; i++) {
|
|
mean = mean + x[offset + i * C + currentChannelNumber];
|
|
}
|
|
mean = mean / normSizeTyped;
|
|
|
|
var squaredNorm: ${dataType} = 0;
|
|
for (var i: u32 = 0u; i < H; i++) {
|
|
let deviation: f32 = x[offset + i * C + currentChannelNumber] - mean;
|
|
squaredNorm = squaredNorm + deviation * deviation;
|
|
}
|
|
let invStdDev = 1 / sqrt(squaredNorm / normSizeTyped + epsilon);
|
|
let channelScale = invStdDev * scale[currentChannelNumber];
|
|
let channelShift = bias[currentChannelNumber] - mean * channelScale;
|
|
for (var i: u32 = 0u; i < H; i++) {
|
|
let currentOffset = offset + i * C + currentChannelNumber;
|
|
output[currentOffset] = x[currentOffset] * channelScale + channelShift;
|
|
}
|
|
}`;
|
|
return {
|
|
...metadata,
|
|
outputs: [
|
|
{dims: outputShape, dataType: inputs[0].dataType, gpuDataType: GpuDataType.default},
|
|
],
|
|
getShaderSource,
|
|
dispatchGroup: () => ({x: Math.ceil(normCount / 64 /* workgroup size */)})
|
|
};
|
|
};
|
|
|
|
export const parseInstanceNormAttributes = (attributes: InstanceNormAttributes): InstanceNormAttributes =>
|
|
createAttributeWithCacheKey({epsilon: attributes.epsilon, format: attributes.format});
|
|
|
|
export const instanceNorm = (context: ComputeContext, attributes: InstanceNormAttributes): void => {
|
|
const metadata = {
|
|
name: 'InstanceNormalization',
|
|
inputTypes: [GpuDataType.default, GpuDataType.default, GpuDataType.default],
|
|
cacheHint: attributes.cacheKey,
|
|
};
|
|
|
|
if (attributes.format === 'NHWC') {
|
|
context.compute(createInstanceNormNHWCProgramInfo(metadata, context.inputs, attributes));
|
|
} else {
|
|
context.compute(createInstanceNormProgramInfo(metadata, context.inputs, attributes));
|
|
}
|
|
};
|