-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
425 lines (396 loc) · 13.9 KB
/
Copy pathindex.html
File metadata and controls
425 lines (396 loc) · 13.9 KB
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title id="title-tag">scratche-dit pt.2 HIPPO EDITION!</title>
<link id="favicon" rel="icon" type="image/png" href="" />
<style>
body {
font-family: sans-serif;
margin: 2rem;
background: #f8f8f8;
}
canvas {
border: 1px solid #ccc;
image-rendering: pixelated;
display: block;
width: 128px;
height: 128px;
margin: 0 auto;
}
#status {
text-align: center;
margin-top: 1rem;
font-family: monospace;
}
#controls {
text-align: center;
margin-top: 1rem;
}
button {
padding: 0.5rem 1rem;
font-size: 1rem;
cursor: pointer;
background: #4caf50;
color: white;
border: none;
border-radius: 4px;
}
button:hover {
background: #45a049;
}
button:disabled {
background: #cccccc;
cursor: not-allowed;
}
</style>
<!-- Load external scripts with defer so they're fetched asynchronously -->
<script src="shaders/shaders.js"></script>
<script src="dit.js"></script>
</head>
<body>
<h1 style="text-align: center">scratche-dit pt.2 HIPPO EDITION!</h1>
<canvas id="displayCanvas"></canvas>
<div id="status"></div>
<div id="controls">
<button id="retryButton" disabled>Generate New Image</button>
<button id="benchButton" style="margin-left: 10px" disabled>
Run Forward Pass Benchmark
</button>
</div>
<footer
style="
text-align: center;
margin-top: 2rem;
color: #666;
font-size: 0.9rem;
"
>
<p>
made with <3 by
<a
href="https://neelr.dev"
style="color: #4caf50; text-decoration: none"
>@neelr</a
>
|
<a
href="https://github.com/neelr/favicon-diffusion"
style="color: #4caf50; text-decoration: none"
>source code</a
>
|
<a
href="https://notebook.neelr.dev/stories/in-browser-favicon-diffusion-scratch-dit-pt-2"
style="color: #4caf50; text-decoration: none"
>check out the writeup =></a
>
</p>
</footer>
<script defer>
// ----- Utility Functions -----
function safeSqrt(x, eps = 1e-8) {
return Math.sqrt(Math.max(x, eps));
}
// Debug function to log GPU buffers
const DEBUG_LOG_BUFFERS = true;
async function logBuffer(device, buffer, numElements, label = "") {
const byteSize = numElements * 4;
const stagingBuffer = device.createBuffer({
size: byteSize,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
const commandEncoder = device.createCommandEncoder();
commandEncoder.copyBufferToBuffer(
buffer,
0,
stagingBuffer,
0,
byteSize
);
device.queue.submit([commandEncoder.finish()]);
await device.queue.onSubmittedWorkDone();
await stagingBuffer.mapAsync(GPUMapMode.READ);
const arrayBuffer = stagingBuffer.getMappedRange();
const data = new Float32Array(arrayBuffer.slice(0));
console.log(label, data);
stagingBuffer.unmap();
}
function gaussianRandom() {
let u = 0,
v = 0;
while (u === 0) u = Math.random();
while (v === 0) v = Math.random();
return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
}
function getCosineSchedule(T, s = 1e-4) {
const f = new Float32Array(T + 1);
for (let t = 0; t <= T; t++) {
const angle = ((t / T + s) / (1 + s)) * (Math.PI / 2);
f[t] = Math.cos(angle) ** 2;
}
const f0 = f[0];
for (let t = 0; t <= T; t++) {
f[t] /= f0;
}
const betas = new Float32Array(T);
for (let t = 0; t < T; t++) {
betas[t] = 1 - f[t + 1] / f[t];
if (betas[t] < 0) betas[t] = 0;
if (betas[t] > 0.999) betas[t] = 0.999;
}
const alphas = new Float32Array(T);
for (let t = 0; t < T; t++) {
alphas[t] = 1 - betas[t];
}
const alphaBars = new Float32Array(T);
alphaBars[0] = alphas[0];
for (let t = 1; t < T; t++) {
alphaBars[t] = alphaBars[t - 1] * alphas[t];
}
return { betas, alphas, alphaBars };
}
// Simple spinner for the title element:
function nextLoad() {
const title = document.getElementById("title-tag");
let x = title.innerHTML;
switch (x) {
case "-":
return "\\";
case "\\":
return "|";
case "|":
return "/";
case "/":
return "-";
default:
return "-";
}
}
// Draw an image from an array into the canvas context.
function drawImageFromArray(
data,
width,
height,
ctx,
normalized = false
) {
const imageData = ctx.createImageData(width, height);
const numPixels = width * height;
for (let i = 0; i < numPixels; i++) {
let r, g, b;
if (normalized) {
r = Math.floor(data[i * 3] * 255);
g = Math.floor(data[i * 3 + 1] * 255);
b = Math.floor(data[i * 3 + 2] * 255);
} else {
r = Math.floor(((data[i * 3] + 1) / 2) * 255);
g = Math.floor(((data[i * 3 + 1] + 1) / 2) * 255);
b = Math.floor(((data[i * 3 + 2] + 1) / 2) * 255);
}
imageData.data[i * 4] = Math.min(255, Math.max(0, r));
imageData.data[i * 4 + 1] = Math.min(255, Math.max(0, g));
imageData.data[i * 4 + 2] = Math.min(255, Math.max(0, b));
imageData.data[i * 4 + 3] = 255;
}
ctx.putImageData(imageData, 0, 0);
}
// ----- Main Diffusion Code -----
// The DiffusionGenerator class caches frequently used DOM elements and minimizes layout thrashing.
class DiffusionGenerator {
constructor() {
this.statusDiv = document.getElementById("status");
this.retryButton = document.getElementById("retryButton");
this.benchButton = document.getElementById("benchButton");
this.canvas = document.getElementById("displayCanvas");
this.ctx = this.canvas.getContext("2d");
this.titleTag = document.getElementById("title-tag");
this.favicon = document.getElementById("favicon");
this.isGenerating = false;
this.isBenchmarking = false;
// Model configuration.
this.config = {
inputSize: 64,
patchSize: 8,
inChannels: 3,
dim: 512,
depth: 4,
dimHead: 128,
mlpMult: 4,
timeEmbDim: 128,
};
this.T = 32; // Number of timesteps.
this.schedule = getCosineSchedule(this.T);
this.numElements =
this.config.inChannels *
this.config.inputSize *
this.config.inputSize;
// Set canvas dimensions.
this.canvas.width = this.config.inputSize;
this.canvas.height = this.config.inputSize;
// Set up the retry button.
this.retryButton.addEventListener("click", async () => {
if (!this.isGenerating && !this.isBenchmarking) {
this.retryButton.disabled = true;
await this.generateImage();
this.retryButton.disabled = false;
}
});
// Set up the benchmark button
this.benchButton.addEventListener("click", async () => {
if (!this.isGenerating && !this.isBenchmarking) {
this.benchButton.disabled = true;
await this.runBenchmark();
this.benchButton.disabled = false;
}
});
}
async initialize() {
if (!navigator.gpu) {
this.statusDiv.textContent =
"WebGPU is not supported in your browser.";
return false;
}
this.statusDiv.textContent = "Initializing WebGPU...";
const adapter = await navigator.gpu.requestAdapter();
this.device = await adapter.requestDevice();
this.statusDiv.textContent = "Loading DiT model weights...";
this.model = new GPUDiT(this.device, this.config);
await this.model.loadWeights("/matrices.bin");
await this.device.queue.onSubmittedWorkDone();
this.retryButton.disabled = false;
this.benchButton.disabled = false;
return true;
}
async predictNoise(inputArray, tVal) {
const outputBuffer = await this.model.forward(inputArray, tVal);
const byteSize = inputArray.length * 4;
const stagingBuffer = this.device.createBuffer({
size: byteSize,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
const commandEncoder = this.device.createCommandEncoder();
commandEncoder.copyBufferToBuffer(
outputBuffer,
0,
stagingBuffer,
0,
byteSize
);
this.device.queue.submit([commandEncoder.finish()]);
await this.device.queue.onSubmittedWorkDone();
await stagingBuffer.mapAsync(GPUMapMode.READ);
const arrayBuffer = stagingBuffer.getMappedRange();
const resultArray = new Float32Array(arrayBuffer.slice(0));
stagingBuffer.unmap();
return resultArray;
}
async updateAndDisplay(currentArray, currentT, startTime) {
const now = performance.now();
const elapsed = (now - startTime) / 1000;
const iterationsDone = this.T - currentT;
const iterPerSec = elapsed > 0 ? iterationsDone / elapsed : 0;
this.statusDiv.textContent = `Iteration: ${iterationsDone} | ${iterPerSec.toFixed(
2
)} iters/sec | Total Time: ${elapsed.toFixed(2)} s`;
// Update the title spinner.
this.titleTag.innerHTML = nextLoad();
// Use requestAnimationFrame to update both canvas and favicon in one frame.
requestAnimationFrame(() => {
drawImageFromArray(
currentArray,
this.config.inputSize,
this.config.inputSize,
this.ctx,
false
);
this.favicon.href = this.canvas.toDataURL("image/png");
});
}
async generateImage() {
if (this.isGenerating) return;
this.isGenerating = true;
const startTime = performance.now();
// Initialize with Gaussian noise.
let x = new Float32Array(this.numElements);
for (let i = 0; i < this.numElements; i++) {
x[i] = gaussianRandom();
}
// Reverse diffusion loop.
for (let t = this.T - 1; t >= 0; t--) {
const alpha_t = this.schedule.alphas[t];
const beta_t = this.schedule.betas[t];
const alpha_bar_t = this.schedule.alphaBars[t];
const sqrt_alpha_t = safeSqrt(alpha_t);
const sqrt_one_minus_alpha_bar = safeSqrt(1 - alpha_bar_t);
let eps_theta = await this.predictNoise(x, t);
for (let i = 0; i < eps_theta.length; i++) {
if (isNaN(eps_theta[i])) {
eps_theta[i] = 0;
console.warn(
"NaN detected in predicted noise; replacing with zero."
);
}
}
const new_x = new Float32Array(this.numElements);
for (let i = 0; i < this.numElements; i++) {
const mean =
(1 / sqrt_alpha_t) *
(x[i] - (beta_t / sqrt_one_minus_alpha_bar) * eps_theta[i]);
new_x[i] =
t > 0 ? mean + safeSqrt(beta_t) * gaussianRandom() : mean;
}
x = new_x;
this.updateAndDisplay(x, t, startTime);
}
this.titleTag.innerHTML = "scratche-dit pt.2 HIPPO EDITION!";
const totalElapsed = (performance.now() - startTime) / 1000;
this.statusDiv.textContent = `Sampling complete. Total Time: ${totalElapsed.toFixed(
2
)} s | Avg iters/sec: ${(this.T / totalElapsed).toFixed(2)}`;
this.isGenerating = false;
}
async runSingleBenchmark() {
// Create dummy input data
let x = new Float32Array(this.numElements);
for (let i = 0; i < this.numElements; i++) {
x[i] = gaussianRandom();
}
const t0 = performance.now();
// Just do forward passes without noise calculation
for (let t = 0; t < this.T; t++) {
await this.predictNoise(x, t);
await this.device.queue.onSubmittedWorkDone();
}
const t1 = performance.now();
return (t1 - t0) / 1000;
}
async runBenchmark() {
this.isBenchmarking = true;
this.statusDiv.textContent = "Running benchmark 100 times...";
let total = 0;
const runs = 100;
for (let i = 0; i < runs; i++) {
const elapsed = await this.runSingleBenchmark();
total += elapsed;
this.statusDiv.textContent = `Benchmark progress: ${
i + 1
}/${runs} runs | Avg time: ${(total / (i + 1)).toFixed(2)}s`;
}
const avg = total / runs;
this.statusDiv.textContent = `Benchmark complete. Average time over ${runs} runs: ${avg.toFixed(
2
)}s`;
this.isBenchmarking = false;
}
}
// Initialize and start
(async () => {
const generator = new DiffusionGenerator();
if (await generator.initialize()) {
await generator.generateImage();
}
})();
</script>
</body>
</html>