-
Notifications
You must be signed in to change notification settings - Fork 0
/
webgpu_single.html
261 lines (206 loc) · 9.75 KB
/
webgpu_single.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wasm Dot Product</title>
<script type="module">
import { perf } from 'https://cdn.jsdelivr.net/npm/@jsheaven/[email protected]/+esm'
import { generateSampleData } from "./lib/samples.mjs"
let gpuResources;
async function setupWebGpu(numVectors) {
if (!navigator.gpu) {
throw new Error('WebGPU is not supported in this browser.');
}
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
// Function to flatten and prepare data correctly
function prepareData(dataArrays) {
return new Float32Array(dataArrays.reduce((acc, val) => acc.concat(Array.from(val)), []));
}
// Function to pad data to ensure correct alignment and meet minimum buffer size
function padData(data, alignment) {
const byteCount = data.length * Float32Array.BYTES_PER_ELEMENT;
// Ensure at least 32 bytes to meet min size requirements
const paddedByteCount = Math.max(Math.ceil(byteCount / alignment) * alignment, 32);
const floatCount = paddedByteCount / Float32Array.BYTES_PER_ELEMENT;
const paddedData = new Float32Array(floatCount);
paddedData.set(data);
return paddedData;
}
// Helper function to create a buffer
function createBuffer(device, data, usage) {
const flatData = prepareData(data);
// Ensuring each segment starts on a 16-byte boundary
data = padData(flatData, 16);
const array = new Float32Array(data);
// Ensure the buffer size is a multiple of 16 bytes
const paddedSize = Math.ceil(array.byteLength / 16) * 16;
const buffer = device.createBuffer({
size: paddedSize,
usage: usage | GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
});
new Float32Array(buffer.getMappedRange()).set(array);
buffer.unmap();
return buffer;
}
const shaderCode = `
@group(0) @binding(0) var<storage, read> e1: array<vec4<f32>, ${2 * numVectors}>;
@group(0) @binding(1) var<storage, read> e2: array<vec4<f32>, ${2 * numVectors}>;
@group(0) @binding(2) var<storage, read_write> result: array<vec4<f32>, ${numVectors}>;
@compute @workgroup_size(1)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
let pairIndex = global_id.x;
var dot_product: f32 = 0.0;
for (var i: u32 = 0u; i < 2u; i = i + 1u) {
dot_product += dot(e1[pairIndex * 2u + i], e2[pairIndex * 2u + i]);
}
result[pairIndex] = vec4<f32>(dot_product, 0.0, 0.0, 0.0);
}
`;
const shaderModule = device.createShaderModule({ code: shaderCode });
// Compute pipeline
const computePipeline = device.createComputePipeline({
layout: "auto",
compute: {
module: shaderModule,
entryPoint: 'main'
}
});
return {
device, computePipeline, createBuffer
}
}
async function runBenchmark() {
document.getElementById('results').innerHTML = `<br /><b>Benchmarking... (might take a few secs.)</b>`
const dimensions = JSON.parse(document.querySelector('[name=dimensions]').value);
const iterations = JSON.parse(document.querySelector('[name=iterations]').value);
const times = {}
const results = []
const measurement = await perf([{
name: 'WebGPU',
fn: async (dims, i) => {
// 2 x 1024 float32 vectors with 1024 dimensions, seeded random
const sampleData = generateSampleData(31337 /* seed */, dims, 128)
// Number of vector pairs
const numVectors = sampleData.vectorsA.length;
console.log('sampleData.vectorsA', sampleData.vectorsA)
const { device, createBuffer, computePipeline } = await setupWebGpu(numVectors)
if (!times[dims]) {
times[dims] = performance.now()
}
const bufferA = createBuffer(device, sampleData.vectorsA, GPUBufferUsage.STORAGE)
const bufferB = createBuffer(device, sampleData.vectorsB, GPUBufferUsage.STORAGE)
console.log('WebGPU', bufferA, bufferB)
// Create buffer for result storage, padding to ensure alignment
const resultStorageBuffer = device.createBuffer({
size: Math.max(16 * numVectors, 32), // Each float result is padded to 16 bytes, ensuring minimum size
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});
// Create buffer for result copy, padding to ensure alignment
const resultCopyBuffer = device.createBuffer({
size: Math.max(16 * numVectors, 32), // Each float result is padded to 16 bytes, ensuring minimum size
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
// Bind group
const bindGroup = device.createBindGroup({
layout: computePipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: bufferA } },
{ binding: 1, resource: { buffer: bufferB } },
{ binding: 2, resource: { buffer: resultStorageBuffer } }
]
});
// Command encoding and dispatch
const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginComputePass();
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(numVectors);
passEncoder.end();
// Copy the result to the resultCopyBuffer
commandEncoder.copyBufferToBuffer(resultStorageBuffer, 0, resultCopyBuffer, 0, resultStorageBuffer.size);
// Submit commands
device.queue.submit([commandEncoder.finish()]);
// Read back the results
await resultCopyBuffer.mapAsync(GPUMapMode.READ);
const resultsArray = new Float32Array(resultCopyBuffer.getMappedRange());
const finalResults = new Float32Array(numVectors);
for (let i = 0; i < numVectors; i++) {
finalResults[i] = resultsArray[i * 4]; // Extract the x component
}
resultCopyBuffer.unmap();
results.push(...finalResults);
console.log('Final Results:', finalResults);
if (i === iterations - 1 && times[dims]) {
times[dims] = performance.now() - times[dims];
}
},
}],
dimensions /* sizes (dimensionality) */,
true /* warmup*/,
iterations /* iterations */,
30000 /* maxExecutionTime */,
1 /* chunk size, one call at a time */
)
let testFailed = true;
if (results[0] === -0.018422827124595642) {
testFailed = false;
}
console.log('testFailed', testFailed, 'result', results[0])
document.getElementById('results').innerHTML = `
<h2>Results:</h2>
<h3>WebAssembly, using SIMD vector instruction set:</h3>
<b>Runs:</b> <b>${iterations}</b> single dot product calculations / pairs of n-dimensional vectors<br />
<b>Took:</b> <br />${dimensions.map((d, i) => `<b>${times[d].toFixed()} ms</b> for <b>${d} dimensions</b>`).join(", <br />")}<br />`
}
window.runBenchmark = runBenchmark;
</script>
</head>
<body>
<h1>Fast Dot Product - WebAssembly using SIMD</h1>
Iterations: <input name="iterations" value="1" type="number" />
Dimensions (JSON): <input name="dimensions" value="[4, 384, 1024]" type="text" />
<button onclick="javascript:runBenchmark();">Run Benchmark</button>
<br />
<i>Notes: This implementation currently suffers from invokation/memory management overhead and limited parallelism. n ops should be processed at once in WASM instead of single ops.</i>
<div id="results"></div>
<h2>Implementation</h2>
<h3>C, using WASM v128 instruction set (emscripten):</h3>
<pre>
#include <stddef.h>
#include <stdint.h>
#include <wasm_simd128.h>
// limitation: aligns to min. 4 dimensions only
float dotProduct(const float *a, const float *b, size_t dims) {
v128_t sum = wasm_f32x4_splat(0.0f);
// Process in chunks of 4
for (size_t i = 0; i < dims; i += 4) {
v128_t vecA = wasm_v128_load(&a[i]);
v128_t vecB = wasm_v128_load(&b[i]);
v128_t product = wasm_f32x4_mul(vecA, vecB);
sum = wasm_f32x4_add(sum, product);
}
// Extract the results from the SIMD register and sum them
float result[4];
wasm_v128_store(result, sum);
return result[0] + result[1] + result[2] + result[3];
}
</pre>
<h3>JS:</h3>
<pre>
// Allocate memory in the WASM heap
const ptrA = Module._malloc(vectorA.length * vectorA.BYTES_PER_ELEMENT);
const ptrB = Module._malloc(vectorB.length * vectorB.BYTES_PER_ELEMENT);
// reference the vector Float32Array's
Module.HEAPF32.set(vectorA, ptrA / vectorA.BYTES_PER_ELEMENT);
Module.HEAPF32.set(vectorB, ptrB / vectorB.BYTES_PER_ELEMENT);
// Call the dotProduct function (WASM module export)
results.push(dotProduct(ptrA, ptrB, dims));
// Free the allocated memory
Module._free(ptrA);
Module._free(ptrB);
</pre>
</body>
</html>