-
Notifications
You must be signed in to change notification settings - Fork 5
/
webnn-conv2d.html
349 lines (303 loc) · 12 KB
/
webnn-conv2d.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
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
<html>
<head>
<title>WebNN Conv2D</title>
<script src="half-floats.js"></script>
</head>
<body>
<p>
<label for="deviceType">Device preference:</label>
<select id="deviceType" disabled>
<option selected value="cpu">CPU</option>
<option value="gpu">GPU</option>
<option value="npu">NPU</option>
</select>
</p>
<p>
<label for="dataType">Data type:</label>
<select id="dataType" disabled>
<option value="float16">float16</option>
<option selected value="float32">float32</option>
</select>
</p>
<p>
<label for="filterType">Filter type:</label>
<select id="filterType" disabled>
<option selected value="blur">Blur</option>
<option value="grayscale">Grayscale</option>
</select>
</p>
<p>
<label for="blurRadius">Blur radius:</label>
<input id="blurRadius" type="number" min="1" max="50" value="2" disabled>
</p>
<p>
<label for="inputLayout">Input layout:</label>
<select id="inputLayout" disabled>
<option value="nchw">Channels first (NCHW)</option>
<option selected value="nhwc">Channels last (NHWC)</option>
</select>
</p>
<p>
<label for="dispatch">Use <code>MLBuffer</code>:</label>
<input id="dispatch" type="checkbox">
</p>
<table>
<tr><th>Input</th><th>Output</th></tr>
<tr>
<td><canvas id="input" width="500" height="500"></canvas></td>
<td><canvas id="output" width="500" height="500"></canvas></td>
</tr>
</table>
<p>
<button id="build" disabled>Build</button> <button disabled id="compute">Compute</button>
</p>
<pre id="status"></pre>
<script>
const channels = 4;
const inputShape = [1, 500, 500, channels];
let context;
let graph;
let inputData;
let inputs = {input: null};
let outputs = {output: null};
let inputBuffer;
let outputBuffer;
let outputDescriptor;
function getTypedArrayConstructor() {
switch (dataTypeOption.value) {
case 'float16':
return Uint16Array;
case 'float32':
return Float32Array;
}
}
function maybeConvertFilterData(float32Data) {
switch (dataTypeOption.value) {
case 'float16':
const float16Data = new Uint16Array(float32Data.length);
for (let i = 0; i < float32Data.length; ++i) {
float16Data[i] = toHalf(float32Data[i]);
}
return float16Data;
case 'float32':
return float32Data;
}
}
async function createBlurGraph(context) {
const inputLayout = inputLayoutElement.value;
const builder = new MLGraphBuilder(context);
let input = builder.input('input', {dataType: dataTypeOption.value, dimensions: inputShape});
if (inputLayout == 'nchw') {
input = builder.transpose(input, {permutation: [0, 3, 1, 2]})
}
// Right now Chromium only supports one filter layout for each input layout.
const filterHeight = Number(blurRadiusElement.value) * 2 + 1;
const filterWidth = Number(blurRadiusElement.value) * 2 + 1;
const filterLayout = inputLayout == 'nchw' ? 'oihw' : 'ihwo';
const filterShape =
filterLayout == 'oihw' ?
[channels, 1, filterHeight, filterWidth] :
[1, filterHeight, filterWidth, channels]
// A simple blur filter is easy because the layout doesn't matter, the
// elements simply have to sum to 1.
let filterData = new Float32Array(filterHeight * filterWidth * channels);
filterData.fill(1 / (filterHeight * filterWidth));
filterData = maybeConvertFilterData(filterData);
const filter = builder.constant(
{dataType: dataTypeOption.value, dimensions: filterShape}, filterData);
let output = builder.conv2d(input, filter, {
inputLayout, filterLayout,
groups: channels, // Convolve each input channel with its own filter.
});
if (inputLayout == 'nchw') {
output = builder.transpose(output, {permutation: [0, 2, 3, 1]})
}
graph = await builder.build({'output': output}),
outputDescriptor = {dataType: output.dataType(), dimensions: output.shape()};
}
async function createGrayscaleGraph(context) {
const inputLayout = inputLayoutElement.value;
const builder = new MLGraphBuilder(context);
let input = builder.input('input', {dataType: dataTypeOption.value, dimensions: inputShape});
if (inputLayout == 'nchw') {
input = builder.transpose(input, {permutation: [0, 3, 1, 2]})
}
// Right now Chromium only supports one filter layout for each input layout.
const filterLayout = inputLayout == 'nchw' ? 'oihw' : 'ohwi';
const filterShape =
filterLayout == 'oihw' ?
[channels, channels, 1, 1] : [channels, 1, 1, channels]
// Mix the RGB channels but not the alpha channel.
const filterData = maybeConvertFilterData(Float32Array.of(
1/3, 1/3, 1/3, 0,
1/3, 1/3, 1/3, 0,
1/3, 1/3, 1/3, 0,
0, 0, 0, 1));
const filter = builder.constant(
{dataType: dataTypeOption.value, dimensions: filterShape}, filterData);
let output = builder.conv2d(input, filter, {inputLayout, filterLayout});
if (inputLayout == 'nchw') {
output = builder.transpose(output, {permutation: [0, 2, 3, 1]})
}
graph = await builder.build({'output': output}),
outputDescriptor = {dataType: output.dataType(), dimensions: output.shape()};
}
function imageDataToTensor(imageData) {
const typedArray = getTypedArrayConstructor(dataTypeOption.value);
const tensor = new typedArray(imageData.data.length);
for (let i = 0; i < imageData.data.length; ++i) {
switch (dataTypeOption.value) {
case 'float16':
tensor[i] = toHalf(imageData.data[i] / 256);
break;
case 'float32':
tensor[i] = imageData.data[i] / 256;
break;
}
}
return tensor;
}
function tensorToImageData(tensor, width, height) {
const imageData = new ImageData(width, height);
for (let i = 0; i < tensor.length; ++i) {
switch (dataTypeOption.value) {
case 'float16':
imageData.data[i] = fromHalf(tensor[i]) * 256;
break;
case 'float32':
imageData.data[i] = tensor[i] * 256;
break;
}
}
return imageData;
}
const outputCanvas = document.getElementById('output');
const outputCtx = outputCanvas.getContext('2d');
const statusSpan = document.getElementById('status');
async function computeGraph() {
statusSpan.textContent = '';
try {
outputCtx.clearRect(0, 0, outputCanvas.width, outputCanvas.height);
const typedArray = getTypedArrayConstructor(dataTypeOption.value);
performance.mark('compute-start');
if (dispatchCheckbox.checked) {
context.dispatch(graph, {input: inputBuffer}, {output: outputBuffer});
const buffer = await context.readBuffer(outputBuffer);
outputs.output = new typedArray(buffer);
} else {
const outputLength = outputDescriptor.dimensions.reduce((acc, value) => acc * value, 1);
outputs.output = new typedArray(outputLength);
({inputs, outputs} = await context.compute(graph, inputs, outputs));
}
performance.mark('compute-end');
const outputData = tensorToImageData(outputs.output, outputDescriptor.dimensions[1], outputDescriptor.dimensions[2]);
outputCtx.putImageData(outputData, 0, 0);
const computeMeasure = performance.measure('compute-measure', 'compute-start', 'compute-end');
statusSpan.textContent = `Compute took ${(computeMeasure.duration).toFixed(1)}ms.`;
} catch (e) {
statusSpan.textContent = e.stack;
}
}
async function buildGraph() {
statusSpan.textContent = '';
try {
context = await navigator.ml.createContext({deviceType: deviceTypeElement.value});
performance.mark('build-start');
if (filterTypeElement.value == 'blur') {
await createBlurGraph(context);
} else {
await createGrayscaleGraph(context);
}
performance.mark('build-end');
if (dispatchCheckbox.checked) {
createMLBuffers();
}
buildButton.disabled = true;
computeButton.disabled = false;
const buildMeasure = performance.measure('build-duration', 'build-start', 'build-end');
statusSpan.textContent = `Build took ${(buildMeasure.duration).toFixed(1)}ms.`;
} catch (e) {
statusSpan.textContent = e.stack;
}
}
function createMLBuffers() {
inputBuffer = context.createBuffer({dataType: dataTypeOption.value, dimensions: inputShape});
context.writeBuffer(inputBuffer, inputs.input);
outputBuffer = context.createBuffer(outputDescriptor);
}
function destroyMLBuffers() {
if (inputBuffer) {
inputBuffer.destroy();
inputBuffer = null;
}
if (outputBuffer) {
outputBuffer.destroy();
outputBuffer = null;
}
}
function loadInput() {
const image = new Image();
image.onload = () => {
const inputCanvas = document.getElementById('input');
const inputCtx = inputCanvas.getContext('2d');
inputCtx.drawImage(image, 0, 0);
inputData = inputCtx.getImageData(0, 0, image.width, image.height);
inputs.input = imageDataToTensor(inputData);
if (!('ml' in navigator)) {
statusSpan.textContent = 'WebNN is not supported in your browser.';
return;
}
deviceTypeElement.disabled = false;
dataTypeOption.disabled = false;
filterTypeElement.disabled = false;
blurRadiusElement.disabled = false;
inputLayoutElement.disabled = false;
buildButton.disabled = false;
};
image.src = 'photo.jpg';
}
function contextOptionsChanged() {
destroyMLBuffers();
buildButton.disabled = false;
context = null;
graphOptionsChanged();
}
function graphOptionsChanged() {
buildButton.disabled = false;
computeButton.disabled = true;
graph = null;
}
const deviceTypeElement = document.getElementById('deviceType');
deviceTypeElement.onchange = contextOptionsChanged
const dataTypeOption = document.getElementById('dataType');
dataTypeOption.onchange = () => {
inputs.input = imageDataToTensor(inputData);
graphOptionsChanged();
};
const filterTypeElement = document.getElementById('filterType');
filterTypeElement.onchange = () => {
blurRadiusElement.disabled = filterTypeElement.value != 'blur';
graphOptionsChanged();
};
const blurRadiusElement = document.getElementById('blurRadius');
blurRadiusElement.onchange = graphOptionsChanged
const inputLayoutElement = document.getElementById('inputLayout');
inputLayoutElement.onchange = graphOptionsChanged
const dispatchCheckbox = document.getElementById('dispatch');
dispatchCheckbox.onchange = () => {
if (dispatchCheckbox.checked) {
if (context) {
createMLBuffers();
}
} else {
destroyMLBuffers();
}
};
const buildButton = document.getElementById('build');
buildButton.onclick = buildGraph;
const computeButton = document.getElementById('compute');
computeButton.onclick = computeGraph;
loadInput();
</script>
</body>
</html>