-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
382 lines (344 loc) · 13.8 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
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
<body>
<h1 align='center'>ONNX Runtime Toolkit</h1>
<h2 align='center' id='status'></h2>
<text>
<b>Usage</b>
<p>You need to start Chrome with "--enable-dawn-features=allow_unsafe_apis" to make webgpuProfiling work.</p>
<p>OPFS Explorer: https://chrome.google.com/webstore/detail/opfs-explorer/acndjpgkpaclldomagafnognkcgjignd</p>
<p>If you meet cross origin issue, you may install Chrome extension "CORS Unblock"
(https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino?hl=en) and enable it.</p>
<p>Some parameters are supported in url, and you may use them as 'index.html?key0=value0&key1=value1...'. Supported
parameters are:</p>
<li>ep: execution provider. E.g., webgpu, wasm</li>
<li>layout=[NCHW|NHWC]. NHWC is the default.</li>
<li>modelName: name of modelName. E.g., mobilenetv2-12</li>
<li>modelUrl=[github|server|[url]]. Note that if you provide the url, you may fail to execute the modelName as the
inputs are not defined well.</li>
<li>ortUrl: ort url. Example: ortUrl=https://wp-27.sh.intel.com/workspace/project/onnxruntime
<li>runTimes: Run times</li>
<li>warmupTimes: Warmup times</li>
<li>tasks=[task0,task1,task2]: tasks to run, split by ','. Candidates are 'conformance', 'performance',
'ortProfiling', 'webgpuProfiling'.</li>
<li>Example:
https://wp-27.sh.intel.com/workspace/project/webatintel/ort-toolkit/?tasks=conformance&modelName=mobilenetv2-12&ep=webgpu&ortUrl=https://wp-27.sh.intel.com/workspace/project/onnxruntime&warmupTimes=10&runTimes=10
</li>
<p></p>
<b>Test Results</b>
</text>
<link href="sortable.min.css" rel="stylesheet" />
<script src="sortable.min.js"></script>
<style>
.highlight {
background-color: yellow;
}
</style>
<script>
'use strict';
const ep = getParam('ep') || 'webgpu';
let device = getParam('device') || 'gpu';
const modelName = getParam('modelName') || 'mobilenetv2-12';
let modelUrl = getParam('modelUrl') || 'server';
if (modelUrl === 'github') {
modelUrl = `https://github.com/webatintel/ort-models/blob/main/${modelName}.onnx?raw=true`;
} else if (modelUrl === 'server') {
modelUrl = `${window.location.origin}/${window.location.pathname}ort-models/${modelName}.onnx`;
}
const power = getParam('power') || 'default';
let runTimes = getParam('runTimes') || 3;
runTimes = parseInt(runTimes);
let warmupTimes = getParam('warmupTimes') || 10;
warmupTimes = parseInt(warmupTimes);
const tasks = getParam('tasks') || 'webgpuProfiling';
const wasmThreads = parseInt(getParam('wasmThreads')) || 4;
const layout = getParam('layout') || 'NHWC';
// for developers
const keepConsole = getParam('keepConsole') === 'true' || false;
const ortUrl = getParam('ortUrl');
const verbose = getParam('verbose') === 'true' || false;
if (ep === 'webgpu') {
device = 'gpu';
}
let ortProfilingData = [];
let ortProfilingIndex = 0;
let webgpuProfilingData = [];
let webgpuProfilingIndex = 0;
let warmupTimesLeft = warmupTimes;
const displayPrecision = 2;
const unitConversionFactor = 1000000;
let feeds;
async function main() {
let urls;
if (ortUrl) {
urls = [`${ortUrl}/js/web/dist/ort.webgpu.min.js`];
} else {
urls = ['https://cdn.jsdelivr.net/npm/onnxruntime-web@latest/dist/ort.webgpu.min.js'];
}
urls = urls.concat(['models.js', 'util.js']);
for (let url of urls) {
await loadScript(url);
}
for (let task of tasks.split(',')) {
if (task === 'conformance') {
let epOutput = await runTask('conformance', ep);
let cpuOutput = await runTask('conformance', 'wasm');
renderTask(task, [epOutput, cpuOutput]);
} else {
let times = await runTask(task, ep);
renderTask(task, times);
}
reportStatus(`Finished task ${task}`);
}
}
// For ortProfiling, session.endProfiling will dump results of all runs, so we couldn't have a session run multiple times.
// For webgpuProfiling, layout conversion is done in first run, so we need to collect data of second run.
async function runTask(task, ep) {
let sessionStartTime = performance.now();
let totalTime = 0;
let times = [];
let oldConsoleLog;
let session;
const getModelStartTime = performance.now();
const modelBuffer = await getModelCache(modelName, modelUrl);
const elapsedTime = parseFloat((performance.now() - getModelStartTime).toFixed(2));
console.info(`${elapsedTime}ms was used to get model`);
const option = {
executionProviders: [
{
name: ep,
deviceType: device,
powerPreference: power,
preferredLayout: layout,
},
],
};
if (ep === 'wasm') {
ort.env.wasm.numThreads = wasmThreads;
ort.env.wasm.simd = true;
} else if (ep === 'webnn') {
ort.env.wasm.simd = true;
ort.env.wasm.proxy = true;
option.freeDimensionOverrides = true;
}
if (task != 'ortProfiling') {
const sessionCreateStartTime = performance.now();
session = await ort.InferenceSession.create(modelBuffer, option);
if (feeds === undefined) {
feeds = getFeeds(session, modelName);
}
const elapsedTime = parseFloat((performance.now() - sessionCreateStartTime).toFixed(2));
console.info(`${elapsedTime}ms was used to create session`);
}
// Not sure why this doesn't work for WebNN
if (!keepConsole && task.endsWith('Profiling')) {
oldConsoleLog = console.log;
console.log = processConsole;
}
for (let i = 0; i < warmupTimes + runTimes; i++) {
if (!sessionStartTime) {
sessionStartTime = performance.now();
}
reportStatus(`Running task ${task} ${i} ...`);
if (i === warmupTimes && task === 'ortProfiling') {
option.enableProfiling = true;
}
if ((i === warmupTimes + 1 || runTimes == 1) && task === 'webgpuProfiling') {
ort.env.webgpu.profilingMode = 'default';
}
if (task === 'ortProfiling') {
const sessionCreateStartTime = performance.now();
session = await ort.InferenceSession.create(modelBuffer, option);
feeds = getFeeds(session, modelName);
const elapsedTime = parseFloat((performance.now() - sessionCreateStartTime).toFixed(2));
console.info(`${elapsedTime}ms was used to create session`);
}
let results;
if (ep === 'webnn') {
// Without clone(), you get DOMException: Failed to execute 'postMessage' on 'Worker': ArrayBuffer at index 0 is already detached.
results = await session.run(clone(feeds));
} else {
results = await session.run(feeds);
}
if (task === 'conformance') {
let result = results[session.outputNames[0]]['data'];
return result;
}
if (i === 0 || i >= warmupTimes) {
const elapsedTime = parseFloat((performance.now() - sessionStartTime).toFixed(2));
times.push(elapsedTime);
}
sessionStartTime = null;
if (i === warmupTimes && task === 'ortProfiling') {
session.endProfiling();
break;
}
if ((i === warmupTimes + 1 || runTimes == 1) && task === 'webgpuProfiling') {
ort.env.webgpu.profilingMode = '';
break;
}
}
if (!keepConsole && task.endsWith('Profiling')) {
console.log = oldConsoleLog;
}
return times;
}
function getParam(name) {
name = name.replace(/[\[\]]/g, '\\$&');
let regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)', 'i');
let results = regex.exec(window.location.href);
if (!results)
return null;
if (!results[2])
return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
async function loadScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.onload = resolve;
script.onerror = reject;
script.src = url;
if (url.startsWith('http')) {
script.crossOrigin = 'anonymous';
}
document.body.append(script);
})
}
function renderTask(task, data) {
let taskElement = document.createElement('p');
document.body.appendChild(taskElement);
taskElement.innerText = `[${task} results]`;
let resultElement = document.createElement('p');
document.body.appendChild(resultElement);
resultElement.id = 'result';
let result = {};
if (task === 'conformance') {
result['result'] = compare(data[0], data[1]);
for (let i = 0; i < data.length; i++) {
console.info(data[i]);
}
} else if (task === 'performance') {
let details = data.join(', ');
let detailsElement = document.createElement('p');
document.body.appendChild(detailsElement);
detailsElement.innerText = details;
result['first'] = data[0];
data.shift();
let totalTime = getSum(data);
let averageTime = parseFloat((totalTime / data.length).toFixed(2));
result['average'] = averageTime;
result['best'] = Math.min(...data);
}
if (task === 'conformance' || task === 'performance') {
resultElement.innerText = JSON.stringify(result);
return;
}
// profiling
resultElement.innerText = `${data[data.length - 1]}ms`;
if (task === 'ortProfiling') {
renderProfiling(['Index', 'Kernel', 'Time (ms)', 'Shape', 'Provider'], ortProfilingData);
}
if (task === 'webgpuProfiling') {
renderAggregatedProfiling(['Kernel', 'Time (ms)', 'Percentage (%)'], webgpuProfilingData);
renderProfiling(['Index', 'Kernel', 'Time (ms)', 'Shape'], webgpuProfilingData);
}
}
function renderAggregatedProfiling(heads, data) {
let kernelTime = {};
for (let d of data) {
let kernel = d[1];
if (!(kernel in kernelTime)) {
kernelTime[kernel] = d[2];
} else {
kernelTime[kernel] += d[2];
}
}
let totalTime = getSum(Object.values(kernelTime));
let keys = Object.keys(kernelTime);
let sortedKernelTime = keys.sort(function (a, b) {
return kernelTime[b] - kernelTime[a];
});
let sortedAggregatedData = [];
for (let kernel of sortedKernelTime) {
let time = kernelTime[kernel];
sortedAggregatedData.push([kernel, time, (time / totalTime * 100).toFixed(2)]);
}
renderProfiling(heads, sortedAggregatedData);
}
function renderProfiling(heads, data) {
let row, th, td;
// table
let table = document.createElement('table');
table.className = 'sortable';
table.align = 'center';
table.style.width = '80%';
table.setAttribute('border', '1');
document.body.appendChild(table);
// thead
let header = table.createTHead('thead');
row = header.insertRow(0);
row.style.fontWeight = 'bold';
for (let head of heads) {
let th = document.createElement('th');
th.innerHTML = head;
row.appendChild(th);
}
// tbody
let tbody = document.createElement('tbody');
table.appendChild(tbody);
// rest of line
for (let i = 0; i < data.length; ++i) {
let rowInfo = data[i];
row = tbody.insertRow(i);
row.onclick = function () { toggleClass(this, 'highlight'); };
for (let j = 0; j < heads.length; j++) {
td = row.insertCell(j);
let cellInfo = rowInfo[j];
if (heads[j].startsWith('Time')) {
cellInfo = cellInfo.toFixed(displayPrecision);
}
td.innerHTML = cellInfo;
}
}
// tfoot
let tfoot = document.createElement('tfoot');
table.appendChild(tfoot);
row = tfoot.insertRow(0);
row.style.fontWeight = 'bold';
let sums = new Array(heads.length).fill('');
sums[0] = 'Sum';
for (let i = 0; i < heads.length; ++i) {
if (!heads[i].startsWith('Time')) {
continue;
}
let sum = 0;
for (let j = 0; j < data.length; j++) {
sum += data[j][i];
}
sums[i] = sum.toFixed(displayPrecision);
}
for (let i = 0; i < heads.length; ++i) {
td = row.insertCell(i);
td.innerHTML = sums[i];
}
// blank line
document.body.appendChild(document.createElement('p'));
}
function processConsole(content) {
let results;
if (content.startsWith('{"cat"')) {
let results = JSON.parse(content.replace(/,$/, ''));
let args = results['args']
if ('provider' in args) {
let shape = /(\"input_type_shape.*),\"thread_scheduling_stats\"/.exec(content);
ortProfilingData.push([ortProfilingIndex++, args['op_name'], parseInt(results['dur']) / unitConversionFactor, shape[1], args['provider']]);
}
} else if (content.startsWith('[profiling]')) {
results = /\[profiling\] kernel \".*\[(.*)\].*\" (input.*), execution time\: (\d+) ns/.exec(content);
if (results) {
webgpuProfilingData.push([webgpuProfilingIndex++, results[1], parseInt(results[3]) / unitConversionFactor, results[2]]);
}
}
}
main();
</script>
</body>