File size: 15,879 Bytes
520f98d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8020c75
 
 
 
520f98d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8020c75
520f98d
8020c75
 
 
520f98d
 
8020c75
520f98d
8020c75
 
520f98d
 
 
 
 
 
8020c75
 
 
 
 
520f98d
 
8020c75
 
 
 
 
520f98d
 
 
 
 
 
 
 
8020c75
 
 
 
 
 
 
 
520f98d
8020c75
520f98d
8020c75
520f98d
 
8020c75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
520f98d
 
 
 
 
 
 
 
 
 
8020c75
520f98d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8020c75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
520f98d
8020c75
 
 
 
 
 
 
 
520f98d
8020c75
 
 
 
 
 
 
520f98d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8020c75
 
 
 
 
 
 
 
 
 
 
 
 
 
520f98d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8020c75
520f98d
 
8020c75
520f98d
 
 
 
 
 
8020c75
520f98d
8020c75
520f98d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8020c75
 
 
 
 
520f98d
 
 
8020c75
 
 
 
 
 
 
 
 
 
 
 
 
 
520f98d
 
 
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
<!doctype html>
<meta charset="utf-8" />
<title>Baberu end-to-end WebGPU OCR</title>
<style>
	body { background: #111; color: #eee; font: 14px/1.45 ui-monospace, monospace; margin: 24px; }
	.controls { display: flex; gap: 12px; align-items: center; margin-bottom: 16px; }
	button, input { font: inherit; }
	canvas { border: 1px solid #555; height: 224px; width: 224px; }
	pre { white-space: pre-wrap; }
</style>
<h1>Baberu end-to-end WebGPU OCR</h1>
<div class="controls">
	<input id="file" type="file" accept="image/*" />
	<button id="run" type="button">Run selected crop</button>
</div>
<canvas id="preview" width="224" height="224"></canvas>
<pre id="log">Starting…</pre>
<script type="module">
	import * as ort from "./.cache/ort/ort.webgpu.min.mjs";

	const VOCAB_SIZE = 14630;
	const BOS = 1;
	const EOS = 2;
	const MEAN = [0.485, 0.456, 0.406];
	const STD = [0.229, 0.224, 0.225];
	const cacheNames = [
		...Array.from({ length: 6 }, (_, index) => `present_k${index}`),
		...Array.from({ length: 6 }, (_, index) => `present_v${index}`),
	];
	const output = document.querySelector("#log");
	const preview = document.querySelector("#preview");
	const context = preview.getContext("2d", { willReadFrequently: true });
	const lines = [];
	const log = (message) => {
		lines.push(`${new Date().toISOString()} ${message}`);
		output.textContent = lines.join("\n");
		console.log(message);
	};
	const timed = async (label, operation) => {
		const started = performance.now();
		const result = await operation();
		log(`PASS ${label} (${(performance.now() - started).toFixed(1)} ms)`);
		return result;
	};
	window.addEventListener("error", (event) => log(`FAIL ${event.error?.stack ?? event.message}`));
	window.addEventListener("unhandledrejection", (event) => log(`FAIL ${event.reason?.stack ?? event.reason}`));

	ort.env.wasm.numThreads = 1;
	ort.env.wasm.wasmPaths = "/.cache/ort/";
	if (!navigator.gpu) throw new Error("WebGPU is unavailable");
	const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" });
	if (!adapter) throw new Error("No WebGPU adapter is available");
	const gpuDevice = await adapter.requestDevice();
	ort.env.webgpu.device = gpuDevice;
	log(`navigator.gpu=true secure=${window.isSecureContext}`);

	const createSession = async (path, preferredOutputLocation) => {
		const response = await fetch(path);
		if (!response.ok) throw new Error(`${path}: HTTP ${response.status}`);
		const bytes = new Uint8Array(await response.arrayBuffer());
		return ort.InferenceSession.create(bytes, {
			executionProviders: ["webgpu"],
			preferredOutputLocation,
			logSeverityLevel: 2,
		});
	};

	const parameters = new URLSearchParams(location.search);
	const bundle = parameters.get("bundle") ?? "lossless";
	const compactVision = bundle.startsWith("compact-");
	const compact = bundle === "compact-qdq";
	const compactFp16 = bundle === "compact-fp16";
	const gatherTokens = bundle === "compact-unified-gather" || bundle === "balanced-unified-gather";
	const unifiedQdq = bundle === "compact-unified-qdq" || bundle === "balanced-unified-qdq" || gatherTokens;
	const qdq = compact || bundle === "balanced-qdq";
	const publishedLayout = parameters.get("layout") === "hf";
	const publishedRoot = compactVision ? "./variants/webgpu-121" : "./variants/webgpu-242";
	const visionPath = publishedLayout
		? `${publishedRoot}/${compactVision ? "vision_int4.onnx" : "vision_fp16.onnx"}`
		: compactVision
			? "./model/onnx/vision_int4.onnx"
			: parameters.get("vision") === "fp32"
				? "./output/vision_fp32.onnx"
				: "./model/onnx/vision_fp16.onnx";
	const prefillPath = publishedLayout
		? `${publishedRoot}/decoder_prefill_qdq_int8.onnx`
		: compactFp16
			? "./output/decoder_prefill_fp16.onnx"
			: qdq
				? "./output/decoder_prefill_qdq_int8.onnx"
				: "./output/decoder_prefill_fp32.onnx";
	const stepPath = publishedLayout
		? `${publishedRoot}/decoder_step_qdq_int8.onnx`
		: compactFp16
			? "./output/decoder_step_fp16.onnx"
			: qdq
				? "./output/decoder_step_qdq_int8.onnx"
				: "./output/decoder_step_fp32.onnx";
	const maxTokens = Number(parameters.get("tokens") ?? 128);
	const vision = await timed("vision session creation", () =>
		createSession(visionPath, { vision_embeds: "gpu-buffer" })
	);
	const decoderOutputs = Object.fromEntries([
		["logits", "cpu"],
		...cacheNames.map((name) => [name, "gpu-buffer"]),
	]);
	const unifiedFile = gatherTokens
		? "decoder_unified_gather_qdq_int8.onnx"
		: "decoder_unified_qdq_int8.onnx";
	const unifiedPath = publishedLayout
		? `${publishedRoot}/${unifiedFile}`
		: `./output/${unifiedFile}`;
	const activePrefillPath = unifiedQdq ? unifiedPath : prefillPath;
	const activeStepPath = unifiedQdq ? unifiedPath : stepPath;
	const prefill = await timed("prefill session creation", () =>
		createSession(activePrefillPath, decoderOutputs)
	);
	const step = unifiedQdq ? prefill : await timed("step session creation", () =>
		createSession(stepPath, decoderOutputs)
	);
	let sessionsReleased = false;
	const releaseSessions = async () => {
		if (sessionsReleased) return;
		sessionsReleased = true;
		const sessions = step === prefill ? [vision, prefill] : [vision, prefill, step];
		const results = await Promise.allSettled(sessions.map((session) => session.release()));
		gpuDevice.destroy();
		const failed = results.filter((result) => result.status === "rejected");
		if (failed.length) {
			throw new Error(`Failed to release ${failed.length}/${sessions.length} model sessions`);
		}
		document.querySelector("#run").disabled = true;
		log(`PASS released ${sessions.length} model sessions`);
	};
	window.releaseSessions = releaseSessions;
	window.addEventListener("pagehide", () => void releaseSessions(), { once: true });
	const vocabPath = publishedLayout ? "./tokenizer/vocab.json" : "./model/tokenizer/vocab.json";
	const charset = await (await fetch(vocabPath)).json();
	const idToCharacter = ["", "", "", "", ...charset];
	const contentIds = new Set();
	for (let index = 0; index < charset.length; index += 1) {
		const character = charset[index];
		if (character.length === 1 && !"ーー〜~".includes(character) && /[\p{Letter}\p{Number}]/u.test(character)) {
			contentIds.add(index + 4);
		}
	}
	log(`models ready bundle=${bundle} vision=${visionPath} prefill=${activePrefillPath} step=${activeStepPath} sharedDecoder=${unifiedQdq} gatherTokens=${gatherTokens} vocab=${idToCharacter.length}`);

	const loadImage = (source) => new Promise((resolve, reject) => {
		const image = new Image();
		image.onload = () => resolve(image);
		image.onerror = reject;
		image.src = source;
	});
	const parseCrop = (image) => {
		const raw = parameters.get("crop");
		if (!raw) return [0, 0, image.naturalWidth, image.naturalHeight];
		const values = raw.split(",").map(Number);
		if (values.length !== 4 || values.some((value) => !Number.isFinite(value))) {
			throw new Error("crop must be x,y,width,height");
		}
		return values;
	};
	const preprocess = (image) => {
		const crop = parseCrop(image);
		context.imageSmoothingEnabled = true;
		context.imageSmoothingQuality = "high";
		context.clearRect(0, 0, 224, 224);
		context.drawImage(image, ...crop, 0, 0, 224, 224);
		const rgba = context.getImageData(0, 0, 224, 224).data;
		const values = new Float32Array(3 * 224 * 224);
		for (let pixel = 0; pixel < 224 * 224; pixel += 1) {
			for (let channel = 0; channel < 3; channel += 1) {
				values[channel * 224 * 224 + pixel] =
					(rgba[pixel * 4 + channel] / 255 - MEAN[channel]) / STD[channel];
			}
		}
		log(`crop=${crop.join(",")} source=${image.naturalWidth}x${image.naturalHeight}`);
		return new ort.Tensor("float32", values, [1, 3, 224, 224]);
	};
	const oneHot = (token) => {
		const values = new Float32Array(VOCAB_SIZE);
		values[token] = 1;
		return new ort.Tensor("float32", values, [1, 1, VOCAB_SIZE]);
	};
	const tokenId = (token) => new ort.Tensor("int32", Int32Array.of(token), [1, 1]);
	const emptyVision = () => new ort.Tensor("float32", new Float32Array(0), [1, 0, 512]);
	const emptyCache = () => new ort.Tensor("float32", new Float32Array(0), [1, 2, 0, 64]);
	const prefillPositions = () => new ort.Tensor(
		"int32",
		Int32Array.from({ length: 257 }, (_, index) => index),
		[1, 257],
	);
	const shouldBlockToken = (tokens) => {
		if (!tokens.length || !contentIds.has(tokens.at(-1))) return false;
		const last = tokens.at(-1);
		let run = 0;
		for (let index = tokens.length - 1; index >= 0 && tokens[index] === last; index -= 1) run += 1;
		return run >= 12;
	};
	const chooseToken = (source, sequence, tokens) => {
		const seen = new Set(sequence);
		const blocked = shouldBlockToken(tokens) ? tokens.at(-1) : -1;
		const adjusted = (index) => {
			if (index === blocked) return Number.NEGATIVE_INFINITY;
			const value = source[index];
			if (!seen.has(index)) return value;
			return value < 0 ? value * 1.2 : value / 1.2;
		};
		let result = 0;
		let best = adjusted(0);
		for (let index = 1; index < source.length; index += 1) {
			const value = adjusted(index);
			if (value > best) {
				best = value;
				result = index;
			}
		}
		return result;
	};
	const disposeResult = (result) => {
		for (const name of cacheNames) result[name].dispose();
		result.logits.dispose();
	};

	const recognize = async (image) => {
		const pixels = preprocess(image);
		const totalStarted = performance.now();
		const visionStarted = performance.now();
		const visionResult = await timed("vision execution", () => vision.run({ pixel_values: pixels }));
		const visionMs = performance.now() - visionStarted;
		log(`vision output=${visionResult.vision_embeds.location} ${JSON.stringify(visionResult.vision_embeds.dims)}`);
		const prefillStarted = performance.now();
		const prefillFeeds = unifiedQdq
			? {
				vision_embeds: visionResult.vision_embeds,
				[gatherTokens ? "token_ids" : "token_one_hot"]: gatherTokens ? tokenId(BOS) : oneHot(BOS),
				position_ids: prefillPositions(),
				...Object.fromEntries(cacheNames.map((name) => [name.replace("present_", "past_"), emptyCache()])),
			}
			: { vision_embeds: visionResult.vision_embeds };
		let cacheResult = await timed("decoder prefill", () => prefill.run(prefillFeeds));
		if (unifiedQdq) {
			prefillFeeds[gatherTokens ? "token_ids" : "token_one_hot"].dispose();
			prefillFeeds.position_ids.dispose();
			for (const name of cacheNames) prefillFeeds[name.replace("present_", "past_")].dispose();
		}
		const prefillMs = performance.now() - prefillStarted;
		log(`KV output=${cacheResult.present_k0.location} ${JSON.stringify(cacheResult.present_k0.dims)}`);
		visionResult.vision_embeds.dispose();
		pixels.dispose();

		const sequence = [BOS];
		const tokens = [];
		const decodeStarted = performance.now();
		for (let iteration = 0; iteration < maxTokens; iteration += 1) {
			const next = chooseToken(cacheResult.logits.data, sequence, tokens);
			if (next === EOS) break;
			tokens.push(next);
			sequence.push(next);
			if (tokens.length >= maxTokens) break;
			const feeds = {
				[gatherTokens ? "token_ids" : "token_one_hot"]: gatherTokens ? tokenId(next) : oneHot(next),
				position_ids: new ort.Tensor("int32", new Int32Array([257 + iteration]), [1, 1]),
			};
			if (unifiedQdq) feeds.vision_embeds = emptyVision();
			for (let layer = 0; layer < 6; layer += 1) {
				feeds[`past_k${layer}`] = cacheResult[`present_k${layer}`];
				feeds[`past_v${layer}`] = cacheResult[`present_v${layer}`];
			}
			const nextResult = await step.run(feeds);
			disposeResult(cacheResult);
			feeds[gatherTokens ? "token_ids" : "token_one_hot"].dispose();
			feeds.position_ids.dispose();
			if (unifiedQdq) feeds.vision_embeds.dispose();
			cacheResult = nextResult;
		}
		const decodeMs = performance.now() - decodeStarted;
		const text = tokens.map((token) => idToCharacter[token] ?? "").join("");
		log(`PASS decode ${tokens.length} tokens (${decodeMs.toFixed(1)} ms)`);
		log(`TEXT ${text}`);
		disposeResult(cacheResult);
		return {
			text,
			tokens: tokens.length,
			visionMs,
			prefillMs,
			decodeMs,
			totalMs: performance.now() - totalStarted,
		};
	};
	const normalizeText = (text) => text.normalize("NFKC").replace(/\s+/g, "");
	const editDistance = (left, right) => {
		let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
		for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
			const current = [leftIndex];
			for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
				current.push(Math.min(
					current[rightIndex - 1] + 1,
					previous[rightIndex] + 1,
					previous[rightIndex - 1] + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),
				));
			}
			previous = current;
		}
		return previous.at(-1);
	};
	const hayai13 = [
		["01", "知らない世界で見つけたイメージを"],
		["02", "カナデトモスソラ(Kanadetomosusora)"],
		["03", "建設会社社員行方"],
		["04", "だとしてもこのレベルがウロつくなんて...おそらく2級の呪い"],
		["05", "パチパチパチパチ"],
		["06", "バビュン"],
		["07", "僕の過去とか未来とか"],
		["08", "くらべられっ子"],
		["09", "そうだクラス分けがあるんだった!!"],
		["10", "脇役よ、主役を超えよ!"],
		["11", "Eh~Idon'treallywantto~"],
		["12", "「Sorryforthewait~!Didyouwaitlong?」"],
		["13", "YamateAreaNewresidentialdistrictforforeigners"],
	];
	const runHayai13 = async () => {
		const results = [];
		for (const [id, expected] of hayai13) {
			log(`CASE ${id}/13`);
			const result = await recognize(await loadImage(`./.cache/hayai13/${id}.png`));
			const normalizedExpected = normalizeText(expected);
			const normalizedActual = normalizeText(result.text);
			results.push({
				id,
				expected,
				actual: result.text,
				distance: editDistance(normalizedExpected, normalizedActual),
				characters: normalizedExpected.length,
				exact: normalizedExpected === normalizedActual,
				...result,
			});
		}
		const distance = results.reduce((sum, result) => sum + result.distance, 0);
		const characters = results.reduce((sum, result) => sum + result.characters, 0);
		const exact = results.filter((result) => result.exact).length;
		const sortedTimes = results.map((result) => result.totalMs).sort((a, b) => a - b);
		const summary = {
			bundle,
			cases: results.length,
			nCER: distance / characters,
			distance,
			characters,
			exact,
			medianMs: sortedTimes[Math.floor(sortedTimes.length / 2)],
			peakCaseMs: sortedTimes.at(-1),
			results,
		};
		log(`SUITE_RESULT ${JSON.stringify(summary)}`);
		window.__suiteResult = summary;
		await fetch("/benchmark-result", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify(summary),
		});
		log(`PASS persisted benchmark result for ${bundle}`);
	};
	window.runHayai13 = runHayai13;

	const fileInput = document.querySelector("#file");
	document.querySelector("#run").addEventListener("click", async () => {
		const [file] = fileInput.files;
		if (!file) throw new Error("Choose a speech-bubble crop first");
		try {
			await recognize(await loadImage(URL.createObjectURL(file)));
		} finally {
			await releaseSessions();
		}
	});
	const suite = parameters.get("suite");
	const imagePath = parameters.get("image");
	if (suite === "hayai13" || imagePath) {
		try {
			if (suite === "hayai13") {
				await runHayai13();
			} else {
				const image = await loadImage(imagePath);
				const runs = Number(parameters.get("runs") ?? 1);
				for (let run = 1; run <= runs; run += 1) {
					log(`RUN ${run}/${runs}`);
					await recognize(image);
				}
			}
		} finally {
			await releaseSessions();
		}
	}
</script>