-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
354 lines (284 loc) · 8.53 KB
/
main.ts
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
import * as twgl from 'twgl.js'
import './style.css'
const canvas = new OffscreenCanvas(1, 1)
const gl = canvas.getContext('webgl2')
if (!gl) {
throw new Error('WebGL 2 is not available')
}
twgl.addExtensionsToContext(gl)
const bufferInfo = twgl.createBufferInfoFromArrays(gl, {
inPosition: [-1, -1, 0, 1, -1, 0, -1, 1, 0, -1, 1, 0, 1, -1, 0, 1, 1, 0],
})
const vertexShader = /* glsl */ `#version 300 es
in vec2 inPosition;
void main() {
gl_Position = vec4(inPosition, 0, 1);
}
`
type FramebufferInfo = Omit<twgl.FramebufferInfo, 'attachments'> & {
attachment: WebGLTexture
}
const createFramebufferInfo = (
attachment: twgl.AttachmentOptions,
width: number,
height: number,
): FramebufferInfo => {
const fbi = twgl.createFramebufferInfo(gl, [attachment], width, height)
return {
framebuffer: fbi.framebuffer,
attachment: fbi.attachments[0],
width: fbi.width,
height: fbi.height,
}
}
const process = (
programInfo: twgl.ProgramInfo,
fbi: FramebufferInfo,
uniforms: Record<string, unknown>,
viewportWidth: number,
viewportHeight: number,
) => {
gl.viewport(0, 0, viewportWidth, viewportHeight)
gl.bindFramebuffer(gl.FRAMEBUFFER, fbi.framebuffer)
gl.useProgram(programInfo.program)
twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo)
twgl.setUniforms(programInfo, uniforms)
twgl.drawBufferInfo(gl, bufferInfo)
}
const fetchParameter = async (name: string) => {
const response = await fetch(`fashion-mnist/models/${name}.gz`)
const buffer = await response.arrayBuffer()
return new Float32Array(buffer)
}
type Size = [number, number]
type WeightSize = {
source: Size
destination: Size
tile: Size
viewport?: Size
}
const loadWeight = async (parameterName: string, size: WeightSize) => {
const tex = twgl.createTexture(gl, {
src: await fetchParameter(parameterName),
internalFormat: gl.R32F,
width: size.source[0],
height: size.source[1],
})
const fbi = createFramebufferInfo(
{ internalFormat: gl.RGBA32F },
size.destination[0],
size.destination[1],
)
const fragmentShader = /* glsl */ `#version 300 es
precision highp float;
uniform sampler2D tex;
out vec4 result;
void main() {
ivec2 fragCoord = ivec2(gl_FragCoord);
int x = fragCoord.x + (fragCoord.y % ${size.tile[1]}) * ${size.tile[0]};
int y = 4 * (fragCoord.y / ${size.tile[1]});
result = vec4(
texelFetch(tex, ivec2(x, y), 0).r,
texelFetch(tex, ivec2(x, y + 1), 0).r,
texelFetch(tex, ivec2(x, y + 2), 0).r,
texelFetch(tex, ivec2(x, y + 3), 0).r
);
}
`
const programInfo = twgl.createProgramInfo(gl, [vertexShader, fragmentShader])
const viewport = size.viewport ?? size.destination
process(programInfo, fbi, { tex }, viewport[0], viewport[1])
gl.deleteTexture(tex)
gl.deleteFramebuffer(fbi.framebuffer)
gl.deleteProgram(programInfo.program)
return fbi.attachment
}
const loadBias = async (parameterName: string, size: number) => {
let data = await fetchParameter(parameterName)
if (size * 4 !== data.length) {
const newData = new Float32Array(size * 4)
newData.set(data)
data = newData
}
return twgl.createTexture(gl, {
src: data,
internalFormat: gl.RGBA32F,
width: 1,
height: size,
})
}
const loadInput = () => {
return new Promise<WebGLTexture>((resolve, reject) =>
twgl.createTexture(
gl,
{ src: 'fashion-mnist/data/0.png' },
(err, texture) => {
if (err) {
reject(err)
} else {
resolve(texture)
}
},
),
)
}
type Activation = (x: string) => string
const Identity: Activation = (x: string) => x
const ReLU: Activation = (x: string) => `max(vec4(0), ${x})`
type SetupMultiplySize = {
source: Size
tile: Size
}
const setupMultiply = (
size: SetupMultiplySize,
sourceComponent: 'R' | 'RGBA' = 'RGBA',
) => {
const xComponent = sourceComponent === 'R' ? '.r' : '[fragCoord.x % 4]'
const xCoord =
size.source[0] === 1
? [0, `fragCoord.x + (fragCoord.y % ${size.tile[1]}) * ${size.tile[0]}`]
: ['fragCoord.x', `fragCoord.y % ${size.tile[1]}`]
if (sourceComponent === 'RGBA') {
xCoord[1] = `(${xCoord[1]}) / 4`
}
const fragmentShader = /* glsl */ `#version 300 es
precision highp float;
uniform sampler2D xTex;
uniform sampler2D wTex;
out vec4 y;
void main() {
ivec2 fragCoord = ivec2(gl_FragCoord);
ivec2 xCoord = ivec2(${xCoord.join(', ')});
float x = texelFetch(xTex, xCoord, 0)${xComponent};
vec4 w = texelFetch(wTex, fragCoord, 0);
y = x * w;
}
`
const programInfo = twgl.createProgramInfo(gl, [vertexShader, fragmentShader])
const multiply = (
xTex: WebGLTexture,
wTex: WebGLTexture,
fbi: FramebufferInfo,
viewportWidth: number,
viewportHeight: number,
) => {
process(programInfo, fbi, { xTex, wTex }, viewportWidth, viewportHeight)
}
return multiply
}
type SetupSumSize = {
tile: Size
}
const setupSum = (size: SetupSumSize, activation: Activation = Identity) => {
const tileCount = size.tile[0] / size.tile[1]
const lod = Math.log2(size.tile[1])
const x = Array.from(
{ length: tileCount },
(_v, k) => `texelFetch(xTex, ivec2(${k}, fragCoord.y), ${lod})`,
).join(' + ')
const fragmentShader = /* glsl */ `#version 300 es
precision highp float;
uniform sampler2D xTex;
uniform sampler2D bTex;
out vec4 y;
void main() {
ivec2 fragCoord = ivec2(gl_FragCoord);
vec4 x = ${tileCount > 1 ? `(${x})` : x} * ${size.tile[1] ** 2}.0;
vec4 b = texelFetch(bTex, fragCoord, 0);
y = ${activation('x + b')};
}
`
const programInfo = twgl.createProgramInfo(gl, [vertexShader, fragmentShader])
const sum = (
xTex: WebGLTexture,
bTex: WebGLTexture,
fbi: FramebufferInfo,
viewportWidth: number,
viewportHeight: number,
) => {
gl.bindTexture(gl.TEXTURE_2D, xTex)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAX_LEVEL, lod)
gl.generateMipmap(gl.TEXTURE_2D)
process(programInfo, fbi, { xTex, bTex }, viewportWidth, viewportHeight)
}
return sum
}
const [weight0, bias0, weight2, bias2, weight4, bias4, input] =
await Promise.all([
loadWeight('0-weight', {
source: [784, 512],
destination: [32, 4096],
tile: [28, 32],
viewport: [28, 4092],
}),
loadBias('0-bias', 128),
loadWeight('2-weight', {
source: [512, 512],
destination: [32, 2048],
tile: [32, 16],
}),
loadBias('2-bias', 128),
loadWeight('4-weight', {
source: [512, 10],
destination: [32, 64],
tile: [32, 16],
viewport: [32, 48],
}),
loadBias('4-bias', 4),
loadInput(),
])
const multiply0 = setupMultiply({ source: [32, 32], tile: [32, 32] }, 'R')
const sum0_1 = setupSum({ tile: [32, 32] }, ReLU)
const multiply2_4 = setupMultiply({ source: [1, 128], tile: [32, 16] })
const sum2_3 = setupSum({ tile: [32, 16] }, ReLU)
const sum4 = setupSum({ tile: [32, 16] })
const fbi = {
'32x4096': createFramebufferInfo({ internalFormat: gl.RGBA32F }, 32, 4096),
'1x128': createFramebufferInfo({ internalFormat: gl.RGBA32F }, 1, 128),
}
const predict = () => {
multiply0(input, weight0, fbi['32x4096'], 32, 4096)
sum0_1(fbi['32x4096'].attachment, bias0, fbi['1x128'], 1, 128)
multiply2_4(fbi['1x128'].attachment, weight2, fbi['32x4096'], 32, 2048)
sum2_3(fbi['32x4096'].attachment, bias2, fbi['1x128'], 1, 128)
multiply2_4(fbi['1x128'].attachment, weight4, fbi['32x4096'], 32, 48)
sum4(fbi['32x4096'].attachment, bias4, fbi['1x128'], 1, 3)
}
const argmax = (x: Float32Array) => {
return [...x].reduce(
(acc, value, index) => (value > acc.max ? { max: value, index } : acc),
{ max: -Infinity, index: -1 },
).index
}
const format = (data: Float32Array, maximumFractionDigits: number) => {
return [...data]
.map((value) => value.toLocaleString('en-US', { maximumFractionDigits }))
.join(', ')
}
const outputData = new Float32Array(12)
const output = outputData.subarray(0, 10)
const classes = [
'T-shirt/top',
'Trouser',
'Pullover',
'Dress',
'Coat',
'Sandal',
'Shirt',
'Sneaker',
'Bag',
'Ankle boot',
]
const separator = '-'.repeat(100)
for (let i = 0; i < 5; i++) {
console.log(separator)
const start = performance.now()
predict()
gl.readPixels(0, 0, 1, 3, gl.RGBA, gl.FLOAT, outputData)
const predicted = classes[argmax(output)]
const time = performance.now() - start
console.log(`Output: ${format(output, 4)}`)
console.log(`Predicted: ${predicted}`)
console.log(`Time: ${time}ms`)
}
console.log(separator)