summaryrefslogtreecommitdiffstats
path: root/dom/webgpu/tests/cts/checkout/src/webgpu/shader/execution/shader_io/compute_builtins.spec.ts
blob: b2ce0f9c253a346f3a3f1827d338d7c7728380ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
export const description = `Test compute shader builtin variables`;

import { makeTestGroup } from '../../../../common/framework/test_group.js';
import { iterRange } from '../../../../common/util/util.js';
import { GPUTest } from '../../../gpu_test.js';

export const g = makeTestGroup(GPUTest);

// Test that the values for each input builtin are correct.
g.test('inputs')
  .desc(`Test compute shader builtin inputs values`)
  .params(u =>
    u
      .combine('method', ['param', 'struct', 'mixed'] as const)
      .combine('dispatch', ['direct', 'indirect'] as const)
      .combineWithParams([
        {
          groupSize: { x: 1, y: 1, z: 1 },
          numGroups: { x: 1, y: 1, z: 1 },
        },
        {
          groupSize: { x: 8, y: 4, z: 2 },
          numGroups: { x: 1, y: 1, z: 1 },
        },
        {
          groupSize: { x: 1, y: 1, z: 1 },
          numGroups: { x: 8, y: 4, z: 2 },
        },
        {
          groupSize: { x: 3, y: 7, z: 5 },
          numGroups: { x: 13, y: 9, z: 11 },
        },
      ] as const)
      .beginSubcases()
  )
  .fn(async t => {
    const invocationsPerGroup = t.params.groupSize.x * t.params.groupSize.y * t.params.groupSize.z;
    const totalInvocations =
      invocationsPerGroup * t.params.numGroups.x * t.params.numGroups.y * t.params.numGroups.z;

    // Generate the structures, parameters, and builtin expressions used in the shader.
    let params = '';
    let structures = '';
    let local_id = '';
    let local_index = '';
    let global_id = '';
    let group_id = '';
    let num_groups = '';
    switch (t.params.method) {
      case 'param':
        params = `
          @builtin(local_invocation_id) local_id : vec3<u32>,
          @builtin(local_invocation_index) local_index : u32,
          @builtin(global_invocation_id) global_id : vec3<u32>,
          @builtin(workgroup_id) group_id : vec3<u32>,
          @builtin(num_workgroups) num_groups : vec3<u32>,
        `;
        local_id = 'local_id';
        local_index = 'local_index';
        global_id = 'global_id';
        group_id = 'group_id';
        num_groups = 'num_groups';
        break;
      case 'struct':
        structures = `struct Inputs {
            @builtin(local_invocation_id) local_id : vec3<u32>,
            @builtin(local_invocation_index) local_index : u32,
            @builtin(global_invocation_id) global_id : vec3<u32>,
            @builtin(workgroup_id) group_id : vec3<u32>,
            @builtin(num_workgroups) num_groups : vec3<u32>,
          };`;
        params = `inputs : Inputs`;
        local_id = 'inputs.local_id';
        local_index = 'inputs.local_index';
        global_id = 'inputs.global_id';
        group_id = 'inputs.group_id';
        num_groups = 'inputs.num_groups';
        break;
      case 'mixed':
        structures = `struct InputsA {
          @builtin(local_invocation_index) local_index : u32,
          @builtin(global_invocation_id) global_id : vec3<u32>,
        };
        struct InputsB {
          @builtin(workgroup_id) group_id : vec3<u32>
        };`;
        params = `@builtin(local_invocation_id) local_id : vec3<u32>,
                  inputsA : InputsA,
                  inputsB : InputsB,
                  @builtin(num_workgroups) num_groups : vec3<u32>,`;
        local_id = 'local_id';
        local_index = 'inputsA.local_index';
        global_id = 'inputsA.global_id';
        group_id = 'inputsB.group_id';
        num_groups = 'num_groups';
        break;
    }

    // WGSL shader that stores every builtin value to a buffer, for every invocation in the grid.
    const wgsl = `
      struct S {
        data : array<u32>
      };
      struct V {
        data : array<vec3<u32>>
      };
      @group(0) @binding(0) var<storage, read_write> local_id_out : V;
      @group(0) @binding(1) var<storage, read_write> local_index_out : S;
      @group(0) @binding(2) var<storage, read_write> global_id_out : V;
      @group(0) @binding(3) var<storage, read_write> group_id_out : V;
      @group(0) @binding(4) var<storage, read_write> num_groups_out : V;

      ${structures}

      const group_width = ${t.params.groupSize.x}u;
      const group_height = ${t.params.groupSize.y}u;
      const group_depth = ${t.params.groupSize.z}u;

      @compute @workgroup_size(group_width, group_height, group_depth)
      fn main(
        ${params}
        ) {
        let group_index = ((${group_id}.z * ${num_groups}.y) + ${group_id}.y) * ${num_groups}.x + ${group_id}.x;
        let global_index = group_index * ${invocationsPerGroup}u + ${local_index};
        local_id_out.data[global_index] = ${local_id};
        local_index_out.data[global_index] = ${local_index};
        global_id_out.data[global_index] = ${global_id};
        group_id_out.data[global_index] = ${group_id};
        num_groups_out.data[global_index] = ${num_groups};
      }
    `;

    const pipeline = t.device.createComputePipeline({
      layout: 'auto',
      compute: {
        module: t.device.createShaderModule({
          code: wgsl,
        }),
        entryPoint: 'main',
      },
    });

    // Helper to create a `size`-byte buffer with binding number `binding`.
    function createBuffer(size: number, binding: number) {
      const buffer = t.device.createBuffer({
        size,
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
      });
      t.trackForCleanup(buffer);

      bindGroupEntries.push({
        binding,
        resource: {
          buffer,
        },
      });

      return buffer;
    }

    // Create the output buffers.
    const bindGroupEntries: GPUBindGroupEntry[] = [];
    const localIdBuffer = createBuffer(totalInvocations * 16, 0);
    const localIndexBuffer = createBuffer(totalInvocations * 4, 1);
    const globalIdBuffer = createBuffer(totalInvocations * 16, 2);
    const groupIdBuffer = createBuffer(totalInvocations * 16, 3);
    const numGroupsBuffer = createBuffer(totalInvocations * 16, 4);

    const bindGroup = t.device.createBindGroup({
      layout: pipeline.getBindGroupLayout(0),
      entries: bindGroupEntries,
    });

    // Run the shader.
    const encoder = t.device.createCommandEncoder();
    const pass = encoder.beginComputePass();
    pass.setPipeline(pipeline);
    pass.setBindGroup(0, bindGroup);
    switch (t.params.dispatch) {
      case 'direct':
        pass.dispatchWorkgroups(t.params.numGroups.x, t.params.numGroups.y, t.params.numGroups.z);
        break;
      case 'indirect': {
        const dispatchBuffer = t.device.createBuffer({
          size: 3 * Uint32Array.BYTES_PER_ELEMENT,
          usage: GPUBufferUsage.INDIRECT,
          mappedAtCreation: true,
        });
        t.trackForCleanup(dispatchBuffer);
        const dispatchData = new Uint32Array(dispatchBuffer.getMappedRange());
        dispatchData[0] = t.params.numGroups.x;
        dispatchData[1] = t.params.numGroups.y;
        dispatchData[2] = t.params.numGroups.z;
        dispatchBuffer.unmap();
        pass.dispatchWorkgroupsIndirect(dispatchBuffer, 0);
        break;
      }
    }
    pass.end();
    t.queue.submit([encoder.finish()]);

    type vec3 = { x: number; y: number; z: number };

    // Helper to check that the vec3<u32> value at each index of the provided `output` buffer
    // matches the expected value for that invocation, as generated by the `getBuiltinValue`
    // function. The `name` parameter is the builtin name, used for error messages.
    const checkEachIndex = (
      output: Uint32Array,
      name: string,
      getBuiltinValue: (groupId: vec3, localId: vec3) => vec3
    ) => {
      // Loop over workgroups.
      for (let gz = 0; gz < t.params.numGroups.z; gz++) {
        for (let gy = 0; gy < t.params.numGroups.y; gy++) {
          for (let gx = 0; gx < t.params.numGroups.x; gx++) {
            // Loop over invocations within a group.
            for (let lz = 0; lz < t.params.groupSize.z; lz++) {
              for (let ly = 0; ly < t.params.groupSize.y; ly++) {
                for (let lx = 0; lx < t.params.groupSize.x; lx++) {
                  const groupIndex = (gz * t.params.numGroups.y + gy) * t.params.numGroups.x + gx;
                  const localIndex = (lz * t.params.groupSize.y + ly) * t.params.groupSize.x + lx;
                  const globalIndex = groupIndex * invocationsPerGroup + localIndex;
                  const expected = getBuiltinValue(
                    { x: gx, y: gy, z: gz },
                    { x: lx, y: ly, z: lz }
                  );
                  if (output[globalIndex * 4 + 0] !== expected.x) {
                    return new Error(
                      `${name}.x failed at group(${gx},${gy},${gz}) local(${lx},${ly},${lz}))\n` +
                        `    expected: ${expected.x}\n` +
                        `    got:      ${output[globalIndex * 4 + 0]}`
                    );
                  }
                  if (output[globalIndex * 4 + 1] !== expected.y) {
                    return new Error(
                      `${name}.y failed at group(${gx},${gy},${gz}) local(${lx},${ly},${lz}))\n` +
                        `    expected: ${expected.y}\n` +
                        `    got:      ${output[globalIndex * 4 + 1]}`
                    );
                  }
                  if (output[globalIndex * 4 + 2] !== expected.z) {
                    return new Error(
                      `${name}.z failed at group(${gx},${gy},${gz}) local(${lx},${ly},${lz}))\n` +
                        `    expected: ${expected.z}\n` +
                        `    got:      ${output[globalIndex * 4 + 2]}`
                    );
                  }
                }
              }
            }
          }
        }
      }
      return undefined;
    };

    // Check @builtin(local_invocation_index) values.
    t.expectGPUBufferValuesEqual(
      localIndexBuffer,
      new Uint32Array([...iterRange(totalInvocations, x => x % invocationsPerGroup)])
    );

    // Check @builtin(local_invocation_id) values.
    t.expectGPUBufferValuesPassCheck(
      localIdBuffer,
      outputData => checkEachIndex(outputData, 'local_invocation_id', (_, localId) => localId),
      { type: Uint32Array, typedLength: totalInvocations * 4 }
    );

    // Check @builtin(global_invocation_id) values.
    const getGlobalId = (groupId: vec3, localId: vec3) => {
      return {
        x: groupId.x * t.params.groupSize.x + localId.x,
        y: groupId.y * t.params.groupSize.y + localId.y,
        z: groupId.z * t.params.groupSize.z + localId.z,
      };
    };
    t.expectGPUBufferValuesPassCheck(
      globalIdBuffer,
      outputData => checkEachIndex(outputData, 'global_invocation_id', getGlobalId),
      { type: Uint32Array, typedLength: totalInvocations * 4 }
    );

    // Check @builtin(workgroup_id) values.
    t.expectGPUBufferValuesPassCheck(
      groupIdBuffer,
      outputData => checkEachIndex(outputData, 'workgroup_id', (groupId, _) => groupId),
      { type: Uint32Array, typedLength: totalInvocations * 4 }
    );

    // Check @builtin(num_workgroups) values.
    t.expectGPUBufferValuesPassCheck(
      numGroupsBuffer,
      outputData => checkEachIndex(outputData, 'num_workgroups', () => t.params.numGroups),
      { type: Uint32Array, typedLength: totalInvocations * 4 }
    );
  });