-
Notifications
You must be signed in to change notification settings - Fork 0
/
primitive.mjs
291 lines (274 loc) · 8.52 KB
/
primitive.mjs
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
import { TestInputBuffer, TestOutputBuffer } from "./testbuffer.mjs";
import { TimingHelper } from "./webgpufundamentals-timing.mjs";
export class BasePrimitive {
constructor(args) {
// expect that args are:
// { device: device,
// params: { param1: val1, param2: val2 },
// someConfigurationSetting: thatSetting,
// gputimestamps: true,
// uniforms: uniformbuffer0,
// inputs: [inputbuffer0, inputbuffer1],
// outputs: outputbuffer0,
// }
if (this.constructor === BasePrimitive) {
throw new Error(
"Cannot instantiate abstract class BasePrimitive directly."
);
}
/* required arguments, and handled first */
for (const field of ["device"]) {
if (!(field in args)) {
throw new Error(
`Primitive ${this.constructor.name} requires a "${field}" argument.`
);
}
/* set this first so that it can be used below */
this[field] = args[field];
}
/* arguments that could be objects or arrays */
for (const field of ["uniforms", "inputs", "outputs"]) {
this[`#${field}`] = undefined;
}
// now let's walk through all the fields
for (const [field, value] of Object.entries(args)) {
switch (field) {
case "params":
/* paste these directly into the primitive (flattened) */
Object.assign(this, args.params);
break;
case "gputimestamps":
/* only set this if BOTH it's requested AND it's enabled in the device */
this.gputimestamps =
this.device.features.has("timestamp-query") && value;
break;
case "device":
/* do nothing, handled above */
break;
case "uniforms":
case "inputs":
case "outputs": // fall-through deliberate
default:
this[field] = value;
break;
}
}
}
#uniforms;
#inputs;
#outputs;
set uniforms(val) {
const arr = Array.isArray(val) ? val : [val];
this.#uniforms = arr;
}
get uniforms() {
return this.#uniforms;
}
set inputs(val) {
const arr = Array.isArray(val) ? val : [val];
this.#inputs = arr;
}
get inputs() {
return this.#inputs;
}
set outputs(val) {
const arr = Array.isArray(val) ? val : [val];
this.#outputs = arr;
}
get outputs() {
return this.#outputs;
}
#timingHelper;
kernel() {
/* call this from a subclass instead */
throw new Error("Cannot call kernel() from abstract class BasePrimitive.");
}
getDispatchGeometry() {
/* call this from a subclass instead */
throw new Error(
"Cannot call getDispatchGeometry() from abstract class BasePrimitive."
);
}
getGPUBufferFromBinding(binding) {
/**
* Input is some sort of buffer object. Currently recognized:
* - GPUBuffer
* - *TestBuffer
* Returns a GPUBuffer
*/
let gpuBuffer;
switch (binding.constructor) {
case GPUBuffer:
gpuBuffer = binding;
break;
case TestInputBuffer: // fallthrough deliberate
case TestOutputBuffer:
gpuBuffer = binding.gpuBuffer;
break;
default:
console.error(
`Primitive:getGPUBufferFromBinding: Unknown datatype for buffer: ${typeof binding}`
);
break;
}
return gpuBuffer;
}
getCPUBufferFromBinding(binding) {
/**
* Input is some sort of buffer object. Currently recognized:
* - TypedArray
* - *TestBuffer
* Returns a TypedArray
*/
let cpuBuffer;
switch (binding.constructor) {
case TestInputBuffer: // fallthrough deliberate
case TestOutputBuffer:
cpuBuffer = binding.cpuBuffer;
break;
case Uint32Array:
case Int32Array:
case Float32Array:
cpuBuffer = binding;
default:
console.error(
`Primitive:getCPUBufferFromBinding: Unknown datatype for buffer: ${typeof binding}`
);
break;
}
return cpuBuffer;
}
/**
* Ensures output is an object with members "in", "out" where
* each member is an array of TypedArrays
* output: { "in": [TypedArray], "out": [TypedArray] }
* if input is not in that format, bindingsToTypedArrays converts it
* it should convert inputs of:
* { "in": [somethingBufferish], "out": [somethingBufferish] }
* or
* { "in": TypedArray, "out": TypedArray }
*/
bindingsToTypedArrays(bindings) {
// https://stackoverflow.com/questions/65824084/how-to-tell-if-an-object-is-a-typed-array
const TypedArray = Object.getPrototypeOf(Uint8Array);
const bindingsOut = {};
for (const type of ["in", "out"]) {
if (bindings[type] instanceof TypedArray) {
/* already a typed array! */
bindingsOut[type] = [bindings[type]];
} else {
/* array of something we need to convert */
bindingsOut[type] = bindings[type].map(this.getCPUBufferFromBinding);
}
}
return bindingsOut;
}
async execute() {
const encoder = this.device.createCommandEncoder({
label: `${this.constructor.name} primitive encoder`,
});
/** loop through each of the actions listed in this.compute(),
* instantiating whatever WebGPU constructs are necessary to run them
*
* TODO: memoize these constructs
*/
/* begin timestamp prep */
let kernelCount = 0; // how many kernels are there total?
if (this.gputimestamps) {
for (const action of this.compute()) {
if (action.constructor == Kernel) {
kernelCount++;
}
}
}
this.#timingHelper = new TimingHelper(this.device, kernelCount);
for (const action of this.compute()) {
switch (action.constructor) {
case Kernel:
const computeModule = this.device.createShaderModule({
label: `module: ${this.constructor.name}`,
code: action.kernel(),
});
const kernelPipeline = this.device.createComputePipeline({
label: `${this.constructor.name} compute pipeline`,
layout: "auto",
compute: {
module: computeModule,
},
});
const bindings = [];
let bindingIdx = 0;
for (const buffer of ["uniforms", "outputs", "inputs"]) {
if (this[buffer] !== undefined) {
for (const binding of this[buffer]) {
bindings.push({
binding: bindingIdx++,
resource: { buffer: this.getGPUBufferFromBinding(binding) },
});
}
}
}
const kernelBindGroup = this.device.createBindGroup({
label: `bindGroup for ${this.constructor.name} kernel`,
layout: kernelPipeline.getBindGroupLayout(0),
entries: bindings,
});
const kernelDescriptor = {
label: `${this.constructor.name} compute pass`,
};
const kernelPass = this.gputimestamps
? this.#timingHelper.beginComputePass(encoder, kernelDescriptor)
: encoder.beginComputePass(kernelDescriptor);
kernelPass.setPipeline(kernelPipeline);
kernelPass.setBindGroup(0, kernelBindGroup);
kernelPass.dispatchWorkgroups(...this.getDispatchGeometry());
kernelPass.end();
break;
case InitializeMemoryBlock:
let DatatypeArray;
switch (action.datatype) {
case "f32":
DatatypeArray = Float32Array;
break;
case "i32":
DatatypeArray = Int32Array;
break;
case "u32":
default:
DatatypeArray = Uint32Array;
break;
}
/* initialize entire array to action.value ... */
const initBlock = DatatypeArray.from(
{ length: action.buffer.size / DatatypeArray.BYTES_PER_ELEMENT },
() => action.value
);
/* ... then write it into the buffer */
this.device.queue.writeBuffer(
this.getGPUBufferFromBinding(action.buffer),
0 /* offset */,
initBlock
);
break;
}
}
const commandBuffer = encoder.finish();
this.device.queue.submit([commandBuffer]);
await this.device.queue.onSubmittedWorkDone();
}
async getResult() {
return this.#timingHelper.getResult();
}
}
export class Kernel {
constructor(k) {
this.kernel = k;
}
}
export class InitializeMemoryBlock {
constructor(buffer, value, datatype) {
this.buffer = buffer;
this.value = value;
this.datatype = datatype;
}
}