-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.html
207 lines (195 loc) · 7.35 KB
/
index.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
<html>
<head>
<title>TVM WebGPU MobileNet Demo</title>
</head>
<script src="tvmjs_runtime.wasi.js"></script>
<script src="tvmjs.bundle.js"></script>
<script>
function customLog(message) {
console.log(message);
const d = document.createElement("div");
d.innerHTML = message;
document.getElementById("log").appendChild(d);
}
function preprocImage(imageData) {
tvmjs.assert(imageData instanceof ImageData, "Input must be ImageData.");
tvmjs.assert(imageData.width == 224, "Width must be 224.");
tvmjs.assert(imageData.height == 224, "Height must be 224.");
const width = imageData.width;
const height = imageData.height;
const npixels = width * height;
const rgbaU8 = imageData.data;
tvmjs.assert(rgbaU8.length == npixels * 4, "Image should be RGBA.");
// Drop alpha channel. Resnet does not need it.
const rgbU8 = new Uint8Array(npixels * 3);
for (let i = 0; i < npixels; ++i) {
rgbU8[i * 3] = rgbaU8[i * 4];
rgbU8[i * 3 + 1] = rgbaU8[i * 4 + 1];
rgbU8[i * 3 + 2] = rgbaU8[i * 4 + 2];
}
// Cast to float and normalize.
const rgbF32 = new Float32Array(npixels * 3);
for (let i = 0; i < npixels; ++i) {
rgbF32[i * 3] = (rgbU8[i * 3] - 123.0) / 58.395;
rgbF32[i * 3 + 1] = (rgbU8[i * 3 + 1] - 117.0) / 57.12;
rgbF32[i * 3 + 2] = (rgbU8[i * 3 + 2] - 104.0) / 57.375;
}
// Transpose. Resnet expects 3 greyscale images.
const data = new Float32Array(npixels * 3);
for (let i = 0; i < npixels; ++i) {
data[i] = rgbF32[i * 3];
data[npixels + i] = rgbF32[i * 3 + 1];
data[npixels * 2 + i] = rgbF32[i * 3 + 2];
}
return data;
}
// Asynchrously load an image.
function loadImage(uri) {
return new Promise((resolve, reject) => {
const image = new Image();
image.src = uri;
image.setAttribute("crossOrigin", "anonymous");
image.onload = () => resolve(image);
image.onerror = reject;
});
}
// global classifier object
classifier = {};
// initialize the classifier.
async function initModel(network, logger) {
const wasmSource = await (
await fetch("./" + network + ".wasm")
).arrayBuffer();
const inst = await tvmjs.instantiate(
new Uint8Array(wasmSource),
new EmccWASI(),
logger
);
const gpuDevice = await tvmjs.detectGPUDevice();
if (gpuDevice === undefined) {
logger(
"Cannot find WebGPU device, make sure you use the browser that suports webGPU"
);
return;
}
inst.initWebGPU(gpuDevice);
const graphJson = await (await fetch("./" + network + ".json")).text();
const synset = await (await fetch("./imagenet1k_synset.json")).json();
const paramsBinary = new Uint8Array(
await (await fetch("./" + network + ".params")).arrayBuffer()
);
logger("Start to intialize the classifier with WebGPU...");
ctx = inst.webgpu(0);
const syslib = inst.systemLib();
const executor = inst.createGraphRuntime(graphJson, syslib, ctx);
executor.loadParams(paramsBinary);
const inputData = inst.empty([1, 3, 224, 224], "float32", inst.cpu());
const outputData = inst.empty([1, 1000], "float32", inst.cpu());
const outputGPU = executor.getOutput(0);
// run the first time to make sure all weights are populated.
executor.run();
await ctx.sync();
logger("Finish initializing the classifier with WebGPU support");
// the classify function
classifier.classify = async () => {
// preprocessing image
const imageURL = document.getElementById("imageURL").value;
const image = await loadImage(imageURL);
// resize the image to 224 224
const sourceWidth = image.width;
const sourceHeight = image.height;
const shortEdge = Math.min(image.width, image.height);
const yy = Math.floor((sourceHeight - shortEdge) / 2);
const xx = Math.floor((sourceWidth - shortEdge) / 2);
const imageCanvas = document.getElementById("canvas");
const imageCanvasContext = imageCanvas.getContext("2d");
imageCanvasContext.drawImage(
image,
xx,
yy,
shortEdge,
shortEdge,
0,
0,
224,
224
);
// preprocessing
const imageData = imageCanvasContext.getImageData(0, 0, 224, 224);
const processedImage = preprocImage(imageData);
// classify the image.
const tStart = performance.now();
inputData.copyFrom(processedImage);
executor.setInput("data", inputData);
executor.run();
outputData.copyFrom(outputGPU);
// need t sync before the data is avaialble.
await ctx.sync();
const tOnCopyCmplete = performance.now();
const standAloneRuns = await executor.benchmarkRuns(ctx, 1, 10);
const stats = Array.from(standAloneRuns).map(value => value.toFixed(2));
// report the result.
const sortedIndex = Array.from(outputData.toArray())
.map((value, index) => [value, index])
.sort(([a], [b]) => b - a)
.map(([, index]) => index);
clearLog();
if (typeof inst.lib.webGPUContext.device.defaultQueue.createFence == "undefined") {
logger("WARNING: createFence is not supported, timing will be inaccurate.");
}
logger(
"Time cost(ms): end to end=" +
(tOnCopyCmplete - tStart).toFixed(2) +
", GPU run benchmarks=" + stats.join(", ")
);
for (let i = 0; i < 5; ++i) {
logger("Top-" + (i + 1) + " " + synset[sortedIndex[i]]);
}
};
}
async function classify() {
while (classifier.classify === undefined) {
await new Promise((r) => setTimeout(r, 10));
}
classifier.classify();
}
function clearLog() {
const node = document.getElementById("log");
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
}
initModel("mobilenet1.0", customLog);
</script>
<body>
<h1>TVM WebGPU Demo</h1>
<ul>
<li>
You need a browser with web GPU capability.
Checkout instructions <a href="https://github.com/gpuweb/gpuweb/wiki/Implementation-Status">here</a> Tested on Chrome Canary
</li>
<li>End to end time cost includes data copy from/to the GPU.</li>
<li>GPU run benchmarks only invoke compute without data copy.
We can get a sense of copy overhead by comparing benchmark runs to the end to end timing.
</li>
<li>Try to click classify multiple times,
you will notice that the classifier becomes faster.
This could due to GPU driver execution stablizes.
The stablized GPU cost helps us to know what is the best performance
we can get if we run the model continuously(e.g. in an always on detetcor demo).
</li>
</ul>
<h2>Options</h2>
Image URL<input
name="imageURL"
id="imageURL"
type="text"
value="./cat.png"
/><br /><br />
<button onclick="classify()">Classify</button>
<button onclick="clearLog()">Clear Log</button><br />
<canvas id="canvas" width="224" height="224"></canvas>
<div id="result"></div>
<div id="log"></div>
</body>
</html>