-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuffer.ts
More file actions
408 lines (375 loc) · 12.6 KB
/
Copy pathbuffer.ts
File metadata and controls
408 lines (375 loc) · 12.6 KB
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// import {Glslang} from '@webgpu/glslang/dist/web-devel-onefile/glslang';
import {Glslang} from '@webgpu/glslang/dist/web-devel/glslang.onefile';
import * as utils from './fixture';
export class BufferOp {
device: GPUDevice;
queue: GPUQueue;
glslang: Glslang;
commandQueue: GPUCommandEncoder[];
times: [];
resultMatrixBuffer: GPUBuffer;
resultMatrixBufferSize: number;
// TODO; This workaround memory usage. But not work.
// gpuReadBuffer: GPUBuffer;
shape: Uint32Array;
computePipeline: any;
bindGroup: any;
bufferID: number;
freeBuffers: Map<number, GPUBuffer[]> = new Map();
// enableTimeStamp: boolean;
constructor(device: GPUDevice, glslang: Glslang) {
this.device = device;
this.queue = device.defaultQueue;
this.glslang = glslang;
this.commandQueue = [];
this.bufferID = 0;
// this.enableTimeStamp = false;
}
/*
var x = new Int32Array(1);
x[0] = 17;
console.log(x[0]);
console.log(x.length);
this.uploadToGPU(x, 4, GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST);
*/
/*
private uploadToGPU(values: ArrayBufferView, byteSize: number, usage: any) {
const buffer = this.device.createBuffer({size: byteSize, usage});
if (values) {
buffer.setSubData(0, values as ArrayBufferView);
values = null;
}
return buffer;
}
*/
// TIMESTAMP
/*
async getQueryTime(dstBuffer: GPUBuffer) {
const dstStagingBuffer = this.device.createBuffer({
size: 16,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
const commandEncoder = this.device.createCommandEncoder();
commandEncoder.copyBufferToBuffer(dstBuffer, 0, dstStagingBuffer, 0, 16);
this.device.defaultQueue.submit([commandEncoder.finish()]);
// @ts-ignore
const arrayBuf = new BigUint64Array(await dstStagingBuffer.mapReadAsync());
// Time delta is a gpu ticks, we need convert to time using gpu frequency
const timeDelta = arrayBuf[1] - arrayBuf[0];
// gpu frequency can be got from console in chromium. For Winodws on
// UHD630/RX560 = 25000000;
const frequency = 25000000;
// 1 ms = 1000 000 ns
const timeInMS = Number(timeDelta) * 1000 / frequency;
console.log('timestamp: ' + timeInMS + 'ms');
dstStagingBuffer.destroy();
dstBuffer.destroy();
return timeInMS;
}
*/
compile(
firstMatrix: Float32Array|Uint32Array,
secondMatrix: Float32Array|Uint32Array, shape: Uint32Array,
computeShaderCode: any) {
this.shape = shape;
/*
const [gpuBufferFirstMatrix, arrayBufferFirstMatrix] =
this.device.createBufferMapped({
size: (firstMatrix as Float32Array).byteLength,
usage: GPUBufferUsage.STORAGE
});
new Float32Array(arrayBufferFirstMatrix).set(firstMatrix);
gpuBufferFirstMatrix.unmap();
*/
const gpuBufferFirstMatrix = this.device.createBuffer({
mappedAtCreation: true,
size: (firstMatrix as Float32Array).byteLength,
usage: GPUBufferUsage.STORAGE
});
// TODO: turn this into type of firstMatrix.
new Float32Array(gpuBufferFirstMatrix.getMappedRange()).set(firstMatrix);
gpuBufferFirstMatrix.unmap();
/*
const [gpuBufferSecondMatrix, arrayBufferSecondMatrix] =
this.device.createBufferMapped({
size: (secondMatrix as Float32Array).byteLength,
usage: GPUBufferUsage.STORAGE
});
new Float32Array(arrayBufferSecondMatrix).set(secondMatrix);
gpuBufferSecondMatrix.unmap();
*/
const gpuBufferSecondMatrix = this.device.createBuffer({
mappedAtCreation: true,
size: (secondMatrix as Float32Array).byteLength,
usage: GPUBufferUsage.STORAGE
});
// TODO: turn this into type of secondMatrix.
new Float32Array(gpuBufferSecondMatrix.getMappedRange()).set(secondMatrix);
gpuBufferSecondMatrix.unmap();
// Result Matrix
this.resultMatrixBufferSize =
Float32Array.BYTES_PER_ELEMENT * (shape[4] * shape[5]);
this.resultMatrixBuffer = this.device.createBuffer({
size: this.resultMatrixBufferSize,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC
});
// console.log(this.resultMatrixBufferSize);
// This works.
/*
const [shapeBuffer, shapeMapping] = this.device.createBufferMapped({
size: shape.byteLength,
usage: GPUBufferUsage.UNIFORM,
});
new Uint32Array(shapeMapping).set(shape);
shapeBuffer.unmap();
*/
const shapeBuffer = this.device.createBuffer({
mappedAtCreation: true,
size: shape.byteLength,
usage: GPUBufferUsage.UNIFORM
});
// TODO: turn this into type of shape.
new Uint32Array(shapeBuffer.getMappedRange()).set(shape);
shapeBuffer.unmap();
// This works too.
/*
const shapeBuffer = this.uploadToGPU(
shape, shape.byteLength,
GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_SRC |
GPUBufferUsage.COPY_DST);
*/
this.createLayout(
gpuBufferFirstMatrix, gpuBufferSecondMatrix, shapeBuffer,
computeShaderCode);
this.releaseBuffer(gpuBufferFirstMatrix);
this.releaseBuffer(gpuBufferSecondMatrix);
this.releaseBuffer(this.resultMatrixBuffer);
this.releaseBuffer(shapeBuffer);
return;
}
private createLayout(
gpuBufferFirstMatrix: GPUBuffer, gpuBufferSecondMatrix: GPUBuffer,
shapeBuffer: GPUBuffer, computeShaderCode: any) {
// Use old layout:
// Bind group layout and bind group
const bindGroupLayout = this.device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
type: 'uniform-buffer'
},
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
type: 'readonly-storage-buffer'
},
{
binding: 2,
visibility: GPUShaderStage.COMPUTE,
type: 'readonly-storage-buffer'
},
{binding: 3, visibility: GPUShaderStage.COMPUTE, type: 'storage-buffer'}
]
});
this.bindGroup = this.device.createBindGroup({
layout: bindGroupLayout,
entries: [
{binding: 0, resource: {buffer: shapeBuffer}},
{binding: 1, resource: {buffer: gpuBufferFirstMatrix}},
{binding: 2, resource: {buffer: gpuBufferSecondMatrix}},
{binding: 3, resource: {buffer: this.resultMatrixBuffer}}
]
});
// Old layout end.
// Pipeline setup
const result =
this.glslang.compileGLSLZeroCopy(computeShaderCode, 'compute', false);
if (result.data.length === 0) {
throw new Error('Shader compilation failed');
}
this.computePipeline = this.device.createComputePipeline({
// For new layout, remove this line.
layout: this.device.createPipelineLayout(
{bindGroupLayouts: [bindGroupLayout]}),
computeStage: {
module: this.device.createShaderModule({code: result.data}),
entryPoint: 'main'
}
});
/* New layout
const bindGroup = this.device.createBindGroup({
layout: computePipeline.getBindGroupLayout(0),
entries: [
{binding: 0, resource: {buffer: shapeBuffer}},
{binding: 1, resource: {buffer: gpuBufferFirstMatrix}},
{binding: 2, resource: {buffer: gpuBufferSecondMatrix}},
{binding: 3, resource: {buffer: this.resultMatrixBuffer}}
]
});
*/
}
compileAndRunSync(workGroupSize: [number, number, number], workPerThread: [
number, number, number
] = [1, 1, 1]) {
// TODO: figure out how to return non const two values.
// if (mode == 0) {
return this.dispatchAndSubmit(
this.computePipeline, this.bindGroup, this.shape[0], this.shape[1],
workGroupSize, workPerThread);
}
private dispatchAndSubmit(
computePipeline: any, bindGroup: any, dispatchX: number,
dispatchY: number, workGroupSize: [number, number, number],
workPerThread: [number, number, number] = [1, 1, 1]) {
// TIMESTAMP
// TODO: necessary to destroy querySet?
/*
let querySet: any;
let dstBuffer: GPUBuffer;
if (this.enableTimeStamp) {
querySet = this.device.createQuerySet({
type: 'timestamp',
count: 2,
});
dstBuffer = this.device.createBuffer({
size: 16,
usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
});
}
*/
// Commands submission
const commandEncoder = this.device.createCommandEncoder();
const passEncoder = commandEncoder.beginComputePass();
/*
if (this.enableTimeStamp) {
passEncoder.writeTimestamp(querySet, 0);
}
*/
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
// passEncoder.dispatch(dispatchX, dispatchY);
if (workGroupSize[1] == 1 && workGroupSize[2] == 1) {
passEncoder.dispatch(
Math.ceil(
dispatchX * dispatchY / workGroupSize[0] / workPerThread[0] /
workPerThread[1]),
1);
} else {
passEncoder.dispatch(
Math.ceil(dispatchX / workGroupSize[0] / workPerThread[0]),
Math.ceil(dispatchY / workGroupSize[1] / workPerThread[1]));
/*
console.log(
'dispatchX / workGroupSize[0] / workPerThread[0] =' +
dispatchX / workGroupSize[0] / workPerThread[0]);
console.log(
'dispatchY / workGroupSize[1] / workPerThread[1] =' +
dispatchY / workGroupSize[1] / workPerThread[1]);
*/
}
/*
if (this.enableTimeStamp) {
passEncoder.writeTimestamp(querySet, 1);
}
*/
passEncoder.endPass();
/*
if (this.enableTimeStamp) {
commandEncoder.resolveQuerySet(querySet, 0, 2, dstBuffer, 0);
}
*/
// Submit GPU commands.
const gpuCommands = commandEncoder.finish();
this.device.defaultQueue.submit([gpuCommands]);
/*
if (this.enableTimeStamp) {
await this.getQueryTime(dstBuffer);
}
*/
// return (this.now() - start);
return true;
}
async data() {
const arrayBuffer = await this.getBufferData();
return new Float32Array(arrayBuffer);
}
async getBufferData() {
// TODO: this is only used in readback.
const gpuReadBuffer = this.device.createBuffer({
size: this.resultMatrixBufferSize,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
});
// Commands submission
const commandEncoder = this.device.createCommandEncoder();
// Encode commands for copying buffer to buffer.
commandEncoder.copyBufferToBuffer(
this.resultMatrixBuffer /* source buffer */, 0 /* source offset */,
gpuReadBuffer /* destination buffer */, 0 /* destination offset */,
this.resultMatrixBufferSize /* size */
);
// Submit GPU commands.
const gpuCommands = commandEncoder.finish();
this.device.defaultQueue.submit([gpuCommands]);
// Read buffer.
// const mapped = await gpuReadBuffer.mapReadAsync();
// const arrayBuffer = mapped.slice(0);
await gpuReadBuffer.mapAsync(GPUMapMode.READ);
const arrayBuffer = gpuReadBuffer.getMappedRange().slice(0);
gpuReadBuffer.unmap();
gpuReadBuffer.destroy();
return arrayBuffer;
}
// ---------Below code is not used!-------------------
// Do not USE!
private async dispatchAndSubmitWithFence(
computePipeline: any, bindGroup: any, dispatchX: number,
dispatchY: number, workGroupSize: [number, number, number]) {
const start = utils.now();
this.dispatchAndSubmit(
this.computePipeline, this.bindGroup, this.shape[0], this.shape[1],
workGroupSize);
const fence = this.queue.createFence();
this.queue.signal(fence, 1);
await fence.onCompletion(1);
console.log((utils.now() - start).toFixed(2));
}
// TODO: Float32Array is bad. And buffer is bad.
async compileAndRun(workGroupSize: [number, number, number]) {
// TODO: figure out how to return non const two values.
// if (mode == 0) {
return await this.dispatchAndSubmitWithFence(
this.computePipeline, this.bindGroup, this.shape[0], this.shape[1],
workGroupSize);
}
getBufferKey() {
return this.bufferID++;
}
// Below is not used currently.
releaseBuffer(buffer: GPUBuffer) {
if (this.freeBuffers == null) {
return;
}
const key = this.getBufferKey();
if (!this.freeBuffers.has(key)) {
this.freeBuffers.set(key, []);
}
this.freeBuffers.get(key).push(buffer);
}
// Call this after execute.
disposeReadBackBuffer() {
if (this.freeBuffers == null) {
return;
}
this.freeBuffers.forEach((buffers, key) => {
buffers.forEach(buff => {
// console.log(' freeBuffers destroy key = ' + key);
// buff.unmap();
buff.destroy();
});
});
}
dispose() {
this.disposeReadBackBuffer();
}
}