onnxruntime

Форк
0
133 строки · 5.3 Кб
1
// Copyright (c) Microsoft Corporation. All rights reserved.
2
// Licensed under the MIT License.
3

4
import { DataType } from '../../../wasm-common';
5
import { TensorView } from '../../tensor-view';
6
import { ShapeUtil } from '../../util';
7
import { AttributeWithCacheKey, createAttributeWithCacheKey } from '../attribute-with-cache-key';
8
import { ComputeContext, ProgramInfo, ProgramUniform } from '../types';
9

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

12
export interface GatherAttributes extends AttributeWithCacheKey {
13
  axis: number;
14
}
15

16
const validateInputs = (inputs: readonly TensorView[]): void => {
17
  if (!inputs || inputs.length !== 2) {
18
    throw new Error('Gather requires 2 inputs.');
19
  }
20
};
21

22
const createGatherProgramInfo = (inputs: readonly TensorView[], attributes: GatherAttributes): ProgramInfo => {
23
  const inputShape = inputs[0].dims;
24
  const indicesShape = inputs[1].dims;
25

26
  const inputRank = inputShape.length;
27
  const axis = ShapeUtil.normalizeAxis(attributes.axis, inputRank);
28

29
  const outputShape = inputShape.slice(0);
30
  outputShape.splice(axis, 1, ...indicesShape);
31

32
  const axisDimLimit = inputShape[axis];
33
  const components = inputs[0].dataType === DataType.bool ? 4 : 1;
34
  const outputSize = Math.ceil(ShapeUtil.size(outputShape) / components);
35

36
  const programUniforms: ProgramUniform[] = [
37
    { type: DataType.uint32, data: outputSize },
38
    { type: DataType.int32, data: axisDimLimit },
39
    { type: DataType.uint32, data: axis },
40
    ...createTensorShapeVariables(inputs[0].dims, inputs[1].dims, outputShape),
41
  ];
42

43
  const getShaderSource = (shaderHelper: ShaderHelper) => {
44
    const data = inputVariable('data', inputs[0].dataType, inputs[0].dims.length, components);
45
    const indices = inputVariable('inputIndices', inputs[1].dataType, inputs[1].dims.length);
46
    const output = outputVariable('output', inputs[0].dataType, outputShape.length, components);
47

48
    const calcDataIndices = (x: number | string): string => {
49
      const indicesRank = indicesShape.length;
50
      let calcStr = `var indicesIndices${x}  = ${indices.type.indices}(0);`;
51
      for (let i = 0; i < indicesRank; i++) {
52
        calcStr += `${indicesRank > 1 ? `indicesIndices${x}[${i}]` : `indicesIndices${x}`} = ${
53
          outputShape.length > 1 ? `outputIndices${x}[uniforms.axis + ${i}]` : `outputIndices${x}`
54
        };`;
55
      }
56
      calcStr += `
57
          var idx${x} = ${indices.getByIndices(`indicesIndices${x}`)};
58
          if (idx${x} < 0) {
59
            idx${x} = idx${x} + uniforms.axisDimLimit;
60
          }
61
          var dataIndices${x} : ${data.type.indices};
62
        `;
63
      for (let i = 0, j = 0; i < inputRank; i++) {
64
        if (i === axis) {
65
          calcStr += `${inputRank > 1 ? `dataIndices${x}[${i}]` : `dataIndices${x}`} = u32(idx${x});`;
66
          j += indicesRank;
67
        } else {
68
          calcStr += `${inputRank > 1 ? `dataIndices${x}[${i}]` : `dataIndices${x}`} = ${
69
            outputShape.length > 1 ? `outputIndices${x}[${j}]` : `outputIndices${x}`
70
          };`;
71
          j++;
72
        }
73
      }
74
      return calcStr;
75
    };
76
    let assignment: string;
77
    if (inputs[0].dataType === DataType.bool) {
78
      const singleAssignment = (resStr: string, x: number, typeCast = '') => `
79
          let outputIndices${x} = ${output.offsetToIndices(`outputOffset + ${x}u`)};
80
          ${calcDataIndices(x)};
81
          let offset${x} = ${data.indicesToOffset(`dataIndices${x}`)};
82
          let index${x} = offset${x} / 4u;
83
          let component${x} = offset${x} % 4u;
84
          ${resStr}[${x}] = ${typeCast}(${data.getByOffset(`index${x}`)}[component${x}]);
85
        `;
86
      assignment = `
87
        let outputOffset = global_idx * ${components};
88
        var value = vec4<u32>(0);
89
        ${singleAssignment('value', 0, 'u32')}
90
        ${singleAssignment('value', 1, 'u32')}
91
        ${singleAssignment('value', 2, 'u32')}
92
        ${singleAssignment('value', 3, 'u32')}
93
        ${output.setByOffset('global_idx', 'value')}
94
      `;
95
    } else {
96
      assignment = `
97
      let outputIndices = ${output.offsetToIndices('global_idx')};
98
      ${calcDataIndices('')};
99
      let value = ${data.getByIndices('dataIndices')};
100
      ${output.setByOffset('global_idx', 'value')};
101
      `;
102
    }
103
    return `
104
      ${shaderHelper
105
        .registerUniform('outputSize', 'u32')
106
        .registerUniform('axisDimLimit', 'i32')
107
        .registerUniform('axis', 'u32')
108
        .declareVariables(data, indices, output)}
109
      ${shaderHelper.mainStart()}
110
        ${shaderHelper.guardAgainstOutOfBoundsWorkgroupSizes('uniforms.outputSize')}
111
        ${assignment}
112
      }`;
113
  };
114
  return {
115
    name: 'Gather',
116
    shaderCache: { hint: attributes.cacheKey, inputDependencies: ['rank', 'rank'] },
117
    getRunData: () => ({
118
      outputs: [{ dims: outputShape, dataType: inputs[0].dataType }],
119
      dispatchGroup: { x: Math.ceil(outputSize / 64 /* workgroup size */) },
120
      programUniforms,
121
    }),
122
    getShaderSource,
123
  };
124
};
125

126
export const parseGatherAttributes = (attributes: Record<string, unknown>): GatherAttributes =>
127
  createAttributeWithCacheKey({ axis: attributes.axis as number });
128

129
export const gather = (context: ComputeContext, attributes: GatherAttributes): void => {
130
  const inputs = context.inputs;
131
  validateInputs(inputs);
132
  context.compute(createGatherProgramInfo(context.inputs, attributes));
133
};
134

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.