onnxruntime/js/web/lib/wasm/jsep/webgpu/ops/expand.ts
Yulong Wang 14a8315f10
[js/web] [webgpu] new incides helper (#16957)
### Description
This PR introduces the new incides helper.

IndicesHelper is a helper class for generating WGSL code for
manipulating indices and data for a shader's input or output.

This class is designed to offer a unified way to generate WGSL code for
manipulating indices and data for a shader's input or output. The
following is a list of terminologies used in this class:
- `offset`: a uint32 value representing the offset of an element in the
data buffer.
- `indices`: an abstraction of a multi-dimensional array's indices
representing the data's index on each dimension.
- `value`: a value of a data element.

Users are expected to create an instance of this class for each shader's
input or output, and use the instance to generate WGSL code for
manipulating indices and data. The following 2 exported functions are
for users to call to create an instance of an indices helper:
 - `inputVariable()`: create an indices helper instance for an input.
 - `outputVariable()`: create an indices helper instance for an output.


An indices helper instance contains helper functions for the following
operations:
- access readonly basic information, including: `name`(the name of the
input or output), `usage`(whether it's an input or an output) and
`shape`(the passed in shape).
- `type`: access readonly type information, including: `indices`(the
type of indices), `value`(the type of value at runtime), `storage`(the
type of value at storage) and `tensor`(the tensor type as represented in
TensorView).
- generate WGSL code for getting indices from offset. Use
`offsetToIndices()` for WGSL code snippet to calculate incides from
offset, and use `indicesToOffset()` for WGSL code snippet to calculate
offset from indices.
- to manipulate an instance of indices, use `setIndices()` and
`getIndices()` to set and get the indices on an indices variable.
- to manipulate data, use `set()`/`get()` to access data at the given
indices from parameter list, use `setByIndices()`/`getByIndices()` to
access data at the given indices from an indices variable, and use
`setByOffset()`/`getByOffset()` to access data at the given offset.
- `impl`: get WGSL code of function implementation for the util
functions mentioned above.

This change applies the usage of new IndicesHelper through the code, but
not necessary for all code.
2023-08-11 11:36:59 -07:00

93 lines
3.7 KiB
TypeScript

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import {TensorView} from '../../tensor';
import {ShapeUtil} from '../../util';
import {ComputeContext, GpuDataType, ProgramInfo, ProgramMetadata} from '../types';
import {inputVariable, outputVariable, ShaderHelper} from './common';
export const expandProgramMetadata = {
name: 'Expand',
inputTypes: [GpuDataType.default]
};
const validateInputs = (inputs: readonly TensorView[]): void => {
if (!inputs || inputs.length !== 2) {
throw new Error('Expand requires 2 input.');
}
const inputShape = inputs[0].dims;
const shape = Array.from(inputs[1].getBigInt64Array(), Number);
let shapeIndex = shape.length < inputShape.length ? 0 : shape.length - inputShape.length;
let inputShapeIndex = inputShape.length < shape.length ? 0 : inputShape.length - shape.length;
for (; shapeIndex < shape.length && inputShapeIndex < inputShape.length; ++shapeIndex, ++inputShapeIndex) {
if (shape[shapeIndex] !== inputShape[inputShapeIndex] && shape[shapeIndex] !== 1 &&
inputShape[inputShapeIndex] !== 1) {
throw new Error('Expand requires shape to be broadcastable to input');
}
}
};
const getAdjustedShape = (shape1: readonly number[], shape2: readonly number[]): number[] => {
const diff = shape1.length - shape2.length;
const shape: number[] = [];
for (let i = 0; i < diff; ++i) {
shape.push(shape1[i]);
}
for (let i = 0; i < shape2.length; ++i) {
shape.push(shape2[i] === 1 ? shape1[i + diff] : shape2[i]);
}
return shape;
};
const calculateOutputShape = (inputShape: readonly number[], shape: readonly number[]): number[] =>
(inputShape.length > shape.length) ? getAdjustedShape(inputShape, shape) : getAdjustedShape(shape, inputShape);
const createExpandProgramInfo = (metadata: ProgramMetadata, inputs: readonly TensorView[]): ProgramInfo => {
const inputShape = inputs[0].dims;
const shape = Array.from(inputs[1].getBigInt64Array(), Number);
const outputShape: number[] = calculateOutputShape(inputShape, shape);
const outputSize = ShapeUtil.size(outputShape);
const dataType = inputs[0].dataType;
const input = inputVariable('input', dataType, inputShape);
const output = outputVariable('output', dataType, outputShape);
const getShaderSource = (shaderHelper: ShaderHelper) => `
const inputShape = ${input.indices(...inputShape)};
${shaderHelper.declareVariables(input, output)}
${output.impl('offsetToIndices')}
${input.impl('indicesToOffset', 'get')}
${shaderHelper.mainStart()}
${shaderHelper.guardAgainstOutOfBoundsWorkgroupSizes(outputSize)}
let outputIndices = ${output.offsetToIndices('global_idx')};
var inputIndices: ${input.type.indices};
for (var i = 0; i < ${inputShape.length}; i++) {
if (inputShape[i] == 1) {
// TODO: IndicesHelper should offer uniform way to get/set indices for all ranks
${input.indicesSet('inputIndices', 'i', 0)}
} else {
${
input.indicesSet(
'inputIndices', 'i', output.indicesGet('outputIndices', `i + ${outputShape.length - inputShape.length}`))}
}
}
${output.setByOffset('global_idx', input.getByIndices('inputIndices'))}
}`;
return {
...metadata,
getShaderSource,
outputs: [{dims: outputShape, dataType: inputs[0].dataType, gpuDataType: GpuDataType.default}],
dispatchGroup: () => ({x: Math.ceil(outputSize / 64 /* workgroup size */)})
};
};
export const expand = (context: ComputeContext): void => {
validateInputs(context.inputs);
const cacheHint = context.inputs.map(x => x.dims.toString()).join('_');
context.compute(
{...expandProgramMetadata, cacheHint, get: () => createExpandProgramInfo(expandProgramMetadata, context.inputs)},
{inputs: [0]});
};