Fast neural network in the browser
A previous post discusses training a simple GLU resnet MLP as the core component of a game-playing algorithm. This runs when you have suitable libraries, but it is slower in the browser. In this post we incrementally add improvements and compare performance of the different implementations.
You can play backgammon or azul against the fast implementation (two different games, the same underlying architecture and forward pass code). The C/JS/wasm code for forward pass is on github.
the model we are working with
The architecture is simple,
class GLUBlock:
# x => W_down @ (act(W_gate @ x) \odot (W_up @ x))
def forward(self, x):
norm_x = self.rms_norm(x) # (,128)
gate = self.gate(norm_x) # (,256)
up = self.up(norm_x) # (,256)
return x + self.down(F.silu(gate) * up) # (,128)
class Model:
# x => softmax . w_unemb . norm . glu2 . glu1 . emb $ x
def forward(self, x): # x: (,d_in)
x = self.emb(x) # (,128)
x = self.glu1(x) # (,128)
x = self.glu2(x) # (,128)
return self.unemb(self.rms_norm(x)).softmax(-1) # (,d_out)
helpful observations/statistics
For avoidance of doubt:
- FLOPs = 'floating point operations' is a count
- FLOPS = 'floating point operations per second' is a rate
To know very roughly if an implementation is fast or slow, it is useful to figure out how many FLOPs a forward pass takes. We can use this (along with the number of samples processes per second) to calculate the FLOPS of an implementation. By comparing with the FLOPS of the chip we are running on, we can see if we are in the right ballpark.
Some concrete statistics,
- we use
d_in = 226andd_out = 6. - total number parameters is roughly
d_in*128 + 2*3*(128*256) + d_out*128 ~= 200k(ignore vector parameters). - a matvec is roughly
2*d_out*d_inFLOPs. We care about this because it is the dominant operation in the forward pass. - the number of matvec FLOPs is roughly
2*[226*128 + 128*6]for the embedding/unembedding and then2*[2*3*(128*256)]for the GLU weights. This is around0.5 MFLOPsper forward pass. We can treat FLOPs from additions and norms etc. as negligible. - we can measure rough max fp32 FLOPS empirically. We get
~135GFLOPS (see [A1] for measurement script).
naive baseline
We first implement and benchmark the most obvious approach.
- we use standard JS (no numerical libraries) - so each weight matrix $W_{ij}$ is stored as a flat
Float32Array,W[i * d_in + j]. Matvecs are computed using nested for loops. - a non-obvious math detail: softmax is invariant to additive constants, i.e.
softmax(x+c) = softmax(x). One typically uses $c = -\operatorname{max}_i x_i$ for stability.
// y = W x + b, for W of shape (d_out, d_in). b may be null.
function linear(x, W, b) {
const dIn = x.length;
const dOut = W.length / dIn;
const y = new Float32Array(dOut);
for (let o = 0; o < dOut; o++) {
let sum = b ? b[o] : 0;
for (let i = 0; i < dIn; i++) {
sum += W[o * dIn + i] * x[i];
}
y[o] = sum;
}
return y;
}
// we inherit eps from pytorch rmsnorm implementation,
// https://docs.pytorch.org/docs/stable/generated/torch.nn.RMSNorm.html
const fp32MachineEps = 1.1920929e-7;
function rmsNorm(x, w, eps = fp32MachineEps) {
// x / rms(x) * w, where rms(x) = sqrt(mean(x^2) + eps).
const d = x.length;
let sumSq = 0;
for (let i = 0; i < d; i++) {
sumSq += x[i] * x[i];
}
const scale = 1 / Math.sqrt(sumSq / d + eps);
const y = new Float32Array(d);
for (let i = 0; i < d; i++) {
y[i] = x[i] * scale * w[i];
}
return y;
}
function silu(z) {
return z / (1 + Math.exp(-z));
}
function softmax(z) {
const max = Math.max(...z);
const y = new Float32Array(z.length);
let total = 0;
for (let k = 0; k < z.length; k++) {
y[k] = Math.exp(z[k] - max);
total += y[k];
}
for (let k = 0; k < z.length; k++) {
y[k] /= total;
}
return y;
}
// y = norm(x)
// x + W_down@(silu(W_gate@y) \odot (W_up@y))
function gluBlock(x, block) {
const n = rmsNorm(x, block.norm);
const gate = linear(n, block.gate, null);
const up = linear(n, block.up, null);
const h = new Float32Array(gate.length);
for (let j = 0; j < h.length; j++) {
h[j] = silu(gate[j]) * up[j];
}
const down = linear(h, block.down, null);
const y = new Float32Array(x.length);
for (let i = 0; i < x.length; i++) {
y[i] = x[i] + down[i];
}
return y;
}
// One input x of shape (d_in) to output probabilities of shape (d_out).
function forward(model, x) {
let h = linear(x, model.emb.W, model.emb.b);
for (const block of model.blocks) {
h = gluBlock(h, block);
}
const logits = linear(rmsNorm(h, model.norm), model.head.W, model.head.b);
return softmax(logits);
}
// A batch of inputs, one at a time.
function forwardBatch(model, xs) {
return xs.map(x => forward(model, x));
}
module.exports = { forward, forwardBatch };
benchmark
We benchmark memory and time of the naive method for different batch sizes, $B\in\{1,\,8,\,64,\,\ldots,\,4096,\,8192\}$:
Some observations:
- Time per sample is constant in $B$. There is no parallelization under the hood (e.g. no vectorization).
- Wall time equals CPU time. It all runs on one thread, and nothing waits. Ideally we'd use multiple threads!
- Way below theoretical max speed. Max possible speed was around 135 GFLOPS. The plot shows about
120 µs/sample, i.e. roughly8e3 samples/s. From earlier, we have roughly0.5 MFLOPs/sample = 5e5 FLOPs/sample. That's4 GFLOPS, so we are off by a factor of at least 20! - Memory usage is too high for large $B$. Take $B = 8192$. The data we actually need is small, around
8 MB(there are roughly200kfp32 parameters, which is2e5*4/1e6 ~= 1 MB, and there are8192*(226+6)inputs and outputs, which is~=8e3*2e2*4/1e6 ~= 7 MB). The jump from ~50 to ~200 is very big!
optimization ideas
The naive benchmark gives us some ideas of how to improve the code,
- memory gets very high, so arrays are being kept alive - presumably arrays containing intermediate activations. So it is likely a good idea to allocate these once and overwrite contents.
- batching the matvecs of each sample together, so that the matvecs become matmuls. This is a standard optimization used in tensor libraries.
- using WebAssembly - JS can't use vector instructions natively, so we have to go to wasm for this.
- using multiple cores for the computation. This one possibly only makes sense for large batch sizes.
optimization results
We show the results of the following optimizations,
- no allocation: allocate every intermediate array once -> expect this to fix high memory use.
- + batching: run each layer on many samples at once -> should improve speed when batch size > 1, possibly at the cost of more memory usage.
- + matmul in wasm: move the matmul to wasm, written in C and compiled with clang -> hopefully faster in general. We expect vectorized instructions to give a boost.
- + all in wasm: moving the whole model to wasm should improve performance a little more.
- + multiple threads: there is an obvious benefit here for large batch sizes (but probably not small ones).
We benchmark using node. Each method receives some data $X\in\mathbb{R}^{B\times d_\text{in}}$
and has to write out probabilities
$y\in\mathbb{R}^{B\times d_\text{out}}$ to an array allocated by the caller.
For each $B$ we run 20 batches of size $B$ to warm up, then we process $2^{14}=16,384$ samples and record peak memory and time.
| version | Wall time (µs) | GFLOPS | peak mem |
|---|---|---|---|
| naive | 123.4 | 3.7 | 182 MiB |
| 1. no allocation | 122.1 | 3.7 | 60 MiB |
| 2. + batching | 64.9 | 7.0 | 61 MiB |
| 3. + matmul in wasm | 7.4 | 62 | 62 MiB |
| 4. + all in wasm | 4.8 | 94 | 71 MiB |
| 5. + 6 threads | 0.95 | 475 | 147 MiB |
results
- 94 GFLOPS is about 70% of max GFLOPS
- overall we get a ~25x speed improvement for the large batch size on a single core
- this is only a CPU improvement. Larger improvements are possible if we use WebGPU, but potentially overhead could be relatively large due to the model itself being small.
We use '4. + all in wasm' on this site - it only uses ~10 MB more memory than the best alternative, but we get a massive speed benefit.
discussion of the different implementations
+ no allocation
For this, have each module of the forward pass take an 'out' parameter, and have an array for each intermediate activation. For example,
// y = W x + b, for W of shape (d_out, d_in). b may be null.
function linear(y, x, W, b) {
const dIn = x.length;
const dOut = y.length;
for (let o = 0; o < dOut; o++) {
let sum = b ? b[o] : 0;
for (let i = 0; i < dIn; i++) {
sum += W[o * dIn + i] * x[i];
}
y[o] = sum;
}
}
// h = h + W_down (silu(W_gate n) * (W_up n)), where n = rmsNorm(h).
function gluBlock(h, block, buf) {
rmsNorm(buf.n, h, block.norm);
linear(buf.gate, buf.n, block.gate, null);
linear(buf.up, buf.n, block.up, null);
for (let j = 0; j < buf.act.length; j++) {
buf.act[j] = silu(buf.gate[j]) * buf.up[j];
}
linear(buf.down, buf.act, block.down, null);
for (let i = 0; i < h.length; i++) {
h[i] += buf.down[i];
}
}
It's possible to be more aggressive, for example by sharing buf.act with buf.n, fusing the final linear with the residual add.
Overall, this simple change doesn't improve speed, but is 3x better for memory usage.
+ batching
We split the input data $X$ of shape $(B,\,d_\text{in})$ into tiles/batches/blocks of $n = 64$ and process them together. If $n$ is not a divisor of $B$, then pad with zeros. We store intermediate activations in a buffer of size $(n,\,d)$.
const TILE = 64;
// X : (B, d_in)
// output/y : (B, d_out)
// both have row-major layout
function forwardBatch(model, buf, X, out) {
const B = X.length / dIn;
for (let s = 0; s < B; s += TILE) {
// rows in this tile
const n = Math.min(TILE, B - s);
forwardTile(model, buf, X.subarray(s * dIn), n, out.subarray(s * dOut));
}
}
function forwardTile(model, buf, X, n, out) {
linear(buf.h, X, n, model.emb.W, model.emb.b, dIn, d); // H: (n, d)
for (const block of model.blocks) {
gluBlock(buf.h, n, block, buf);
}
rmsNorm(buf.n, buf.h, n, model.norm);
linear(out, buf.n, n, model.head.W, model.head.b, d, dOut);
softmax(out, n, dOut);
}
RMSNorm and softmax are the naive versions with a loop over the $n$ rows of the tile. For example,
function rmsNorm(Y, X, n, w, eps = fp32MachineEps) {
const d = w.length;
for (let s = 0; s < n; s++) {
let sumSq = 0;
for (let i = 0; i < d; i++) {
sumSq += X[s * d + i] * X[s * d + i];
}
const scale = 1 / Math.sqrt(sumSq / d + eps);
for (let i = 0; i < d; i++) {
Y[s * d + i] = X[s * d + i] * scale * w[i];
}
}
}
We end up doing even finer-grained tiling in
linear - we process 16 samples at once in the inner loop,
function linear(Y, X, n, W, b, dIn, dOut) {
let s = 0;
for (; s + 16 <= n; s += 16) {
// start of rows s, ..., s + 15 of X
const x0 = s * dIn, x1 = x0 + dIn, /* ... */ x15 = x14 + dIn;
for (let o = 0; o < dOut; o++) {
// one running sum per row, for output o
let a0 = b ? b[o] : 0, a1 = a0, /* ... */ a15 = a0;
for (let i = 0; i < dIn; i++) {
const w = W[o * dIn + i]; // loaded once, used by every row of the group
a0 += w * X[x0 + i];
a1 += w * X[x1 + i];
a2 += w * X[x2 + i];
// ... a3 to a15 are similar
}
Y[s * dOut + o] = a0;
// ... a1 to a15 are similar
}
}
}
The motivation for this is empirical. We tested various $r$ (how many samples to process in the inner loop), and find $16$ to be the best,
| rows per group $r$ | 1 | 2 | 4 | 8 | 16 | 32 | 64 |
|---|---|---|---|---|---|---|---|
mean µs per linear |
1245 | 925 | 674 | 565 | 558 | 848 | 1229 |
linear with $d_\text{in} = 128$ and $d_\text{out} = 256$, on a tile of 64 rows, for different group sizes $r$. Mean is taken over 500 calls.Overall, batching is faster than previous approaches, when $B>1$, but is slightly slower at $B=1$. The memory usage is very similar to the 'no batch' approach.
+ matmul in wasm
Since the majority of the FLOPs are in the matmuls, we move the matmul to WebAssembly. This allows the use of vector instructions! We can write the matmul in C, and compile to WebAssembly using LLVM. For now, we keep the other operations (norms, SiLU, softmax, etc.) in JS.
We compile the C code -nostdlib (no malloc, runtime, or standard library). We show the JS usage first. The compiled module exports,
- a function
linearthat we can call from JS, - a
memorybuffer (used to share data between JS and wasm), - pointer to the first byte we are allowed to use,
__heap_base.
We use these 3 exports in JS like so,
const fs = require("fs");
const kernel = fs.readFileSync("kernel.wasm")
const kernelMod = new WebAssembly.Module(kernel);
const { linear, memory, __heap_base } =
new WebAssembly.Instance(kernelMod).exports;
// `memory` is 64KiB for the stack, but may
// be more if statics are required
// the linker `wasm-ld` reserves this for us(?)
// `memory.grow(1);` increases it another 64KiB
// in practice we actually have to figure out how many bytes
// we need, and increase by that much:
memory.grow(Math.ceil(bytes / 65536));
// Copy an array into the wasm memory
// and return a pointer to it
let at = __heap_base.value;
function copyIn(a) {
new Float32Array(memory.buffer, at, a.length).set(a);
at += a.byteLength;
return at - a.byteLength;
}
const pX = copyIn(X), pWT = copyIn(WT);
const pB = copyIn(b), pY = copyIn(Y);
linear(pY, pX, n, pWT, pB, dIn, dOut);
// copy the result back out
Y.set(new Float32Array(memory.buffer, pY, Y.length));
The kernel is below, but here are some features:
- produces outputs in tiles/blocks of size 4 by 16. Yet again, more fine-grained tiling! As to why this particular arrangement - apparently ARM has 32 vector registers (our chip is ARM). With 4 by 16 blocks, we fill
4*16/4=16vector registers. See in the code that we also need 4 for the weights and 1 for the input, which makes 21. We did try some different tile sizes, which we discuss later. - uses
f32x4vectorized multiply-adds. Weights corresponding to 4 neighbouring outputs need to sit next to each other in memory. For this reason, the weight is stored transposed - remember $W^T$ has shape $(d_\text{in},\,d_\text{out})$, and we use row-major ordering! (this is possibly(?) why matmul libraries, e.g. torch.nn.Linear, use $x W^\top$ rather than $Wx$). - repeats the computation for each tile until complete
For simplicity we assume the tile size fits neatly, i.e. 'in-dim' should be a multiple of 4, and 'out-dim' should be a multiple of 16. If this is not the case, it can be fixed by padding.
#include <wasm_simd128.h>
#define INLINE static inline __attribute__((always_inline))
// the 4 x 16 block of Y at row 0, output 0 of the pointers given.
INLINE void block(float *Y, const float *X, const float *WT, const float *b,
int dIn, int dOut) {
v128_t sum[4][4]; // store intermediate result here
// this is an array of 4*4 fp32x4
// equivalently, 4*16 fp32
// r indexes samples in the batch
// v indexes a vector of 4 outputs
for (int r = 0; r < 4; r++)
for (int v = 0; v < 4; v++)
// load bias (independent of sample ==> indep of r)
sum[r][v] = wasm_v128_load(b + 4 * v);
for (int i = 0; i < dIn; i++) {
v128_t w[4];
for (int v = 0; v < 4; v++)
// w[v] = W^T_{i,4*v:4*v+4}
w[v] = wasm_v128_load(WT + i * dOut + 4 * v);
for (int r = 0; r < 4; r++) {
// x = [X_{r,i}, ..., X_{r,i}] copied 4 times
v128_t x = wasm_v128_load32_splat(X + r * dIn + i);
for (int v = 0; v < 4; v++)
// computes sum[r][v] += x_{r,i} @ W^T_{i,4*v:4*v+4}
sum[r][v] = wasm_f32x4_relaxed_madd(w[v], x, sum[r][v]);
// of course we really want to compute
// \sum_i x_{r,i} @ W^T_{i,4*v:4*v+4},
// but this is accumulated by the outer loop
}
}
// all that remains is to
// write result to Y
for (int r = 0; r < 4; r++)
for (int v = 0; v < 4; v++)
wasm_v128_store(Y + r * dOut + 4 * v, sum[r][v]);
}
// process all the tiles
INLINE void linear(float *Y, const float *X, int n, const float *WT, const float *b,
int dIn, int dOut) {
for (int s = 0; s < n; s += 4)
for (int o = 0; o < dOut; o += 16)
block(Y + s * dOut + o, X + s * dIn, WT + o, b + o, dIn, dOut);
}
This code is massively faster than the vanilla JS implementation! Around 10x faster (see Figure 2 or Table 1), and is by far the most effective single intervention. Memory is slightly higher, but not by much, probably due to interfacing with wasm.
how to pick tile size
We also investigated different tile sizes. Why have the linear code produce outputs specifically with size 4 by 16?
The only constraint is that the feature dimension needs to be a multiple of 4, since we are using vectorized multiply-adds. Given this, we tested output blocks of size $R\times 4V$, with $R \in \{1, 2, 3, 4, 6, 8\}$ and $4V \in \{4, 8, 16, 32\}$, using one linear layer with $d_\text{in} = 128$ and $d_\text{out} = 256$, and 64 samples (i.e. $X\in\mathbb{R}^{64\times 128}$).
Two promising contenders were $4\times 16$ and $2\times 32$.
However, we found an issue with $2 \times 32$ when investigating different weight sizes. See Figure 4, where there is a critical size for $W$, beyond which $2\times 32$ output blocks start to get slower.
It seems that the slowdown could be related to L1 cache. The L1 cache on this chip is 128 KiB, and seems to correspond to when speed declines. For small $V$ we are clearly compute bound, but eventually we become memory bound as we increase $V$ - for large $V$, we load more bytes from $W$ in the inner loop.
For simplicity we opted for $4\times 16$ blocks everywhere, but it would be faster to use different tile sizes for different combinations of weight dimension.
linear, computed using blocks of 4 rows × 16 outputs and 2 rows × 32 outputs, against the size of the whole of $W^T$, which is $d_\text{in} \times d_\text{out}$ floats of 4 bytes. Solid: $d_\text{in} = 128$ and $d_\text{out}$ from 32 to 1024. Dashed: $d_\text{out} = 128$ and $d_\text{in}$ from 32 to 1024.
Measurements taken using $n=64$ inputs.
Each point is the mean of 10 runs. The labels at the bottom mark sizes of the weights in our GLU resnet model.+ all in wasm
We convert the whole forward pass to WebAssembly. This is more involved than initially hoped...
The first issue is that we have to roll our own exp function! Of course, exp is necessary for SiLU and softmax.
exp and softmax
To compute exp(x) we can use a polynomial: write $x = k \ln 2 + r$, with $k$ an integer and $|r| \le \ln 2 / 2$. Then $\mathrm{e}^x = 2^k \mathrm{e}^r$, and $\mathrm{e}^r$ is calculated using Maclaurin series.
To make the $2^k$ computation more accurate, we write $k$ as $k = k_1 + k_2$. Basically if $k\geq128$, then $2^k$ is not representable in fp32 (fp32 has 8 exponent bits with a bias of 127, so the largest power of 2 it can hold is $2^{127}$). Writing as the sum of $k_i$ makes the representation possible. An example to illustrate the benefits of this in python,
f = np.float32
ln2 = f(np.log(2))
x = f(88.7)
k = 128 # x = k ln 2 + r
r = x - f(k * ln2) # e^r, about 0.98
print(np.exp(r) * f(2.0**128)) # inf: 2^128 isn't a float32
print(np.exp(r) * f(2.0**64) * f(2.0**64)) # 3.326e+38
print(np.exp(x)) # 3.326e+38
Output:
inf
3.325976e+38
3.3259769e+38
Clearly, splitting up $k$ allowed us to avoid overflow. However, there is still a small error compared to numpy. We can fix this by doing a similar trick but for $r$: write $r=r_\text{high} + r_\text{low}$.
f = np.float32
x = f(88.7)
k = f(128) # x = k ln 2 + r
# r in float32, with ln 2 as one float32, as before
r = x - k * f(np.log(2))
print(np.exp(r) * f(2.0**128)) # inf: 2^128 isn't a float32
print(np.exp(r) * f(2.0**64) * f(2.0**64)) # 3.325976e+38: close, but not np.exp
# r with Cody-Waite method: ln 2 = hi + lo
hi, lo = f(0.693145752), f(1.42860677e-6)
r = (x - k * hi) - k * lo
print(np.exp(r) * f(2.0**64) * f(2.0**64)) # 3.3259769e+38: matches
print(np.exp(x)) # 3.3259769e+38
Output:
inf
3.325976e+38
3.3259769e+38
3.3259769e+38
Now for the full implementation, with comments. We use the two methods just discussed.
INLINE v128_t exp4(v128_t x) {
// e^x is inf in fp32 above 88.72 and 0 below -103.97, so this clamp doesn't change it
x = wasm_f32x4_pmax(wasm_f32x4_pmin(x, splat(89.0f)), splat(-105.0f));
// 1/ln(2) ~= 1.44 , ln(2) ~= 0.69
v128_t k = wasm_f32x4_nearest(wasm_f32x4_mul(x, splat(1.44269504f)));
v128_t r = wasm_f32x4_sub(x, wasm_f32x4_mul(k, splat(0.693145752f)));
// Cody-Waite range reduction for r
r = wasm_f32x4_sub(r, wasm_f32x4_mul(k, splat(1.42860677e-6f)));
// taylor expansion with horner's method
// horner's method example for quadratic:
// p(x) = a_0 + (a_1 + a_2x)x
v128_t p = splat(1.0f / 720); // 1/6!
p = wasm_f32x4_relaxed_madd(p, r, splat(1.0f / 120));
p = wasm_f32x4_relaxed_madd(p, r, splat(1.0f / 24));
p = wasm_f32x4_relaxed_madd(p, r, splat(1.0f / 6));
p = wasm_f32x4_relaxed_madd(p, r, splat(0.5f));
p = wasm_f32x4_relaxed_madd(p, r, splat(1.0f));
p = wasm_f32x4_relaxed_madd(p, r, splat(1.0f));
// compute 2^k as 2^k1 * 2^k2
// k1 = floor(k / 2), so k is -151 to 128
v128_t k_int = wasm_i32x4_trunc_sat_f32x4(k);
v128_t k1 = wasm_i32x4_shr(k_int, 1), k2 = wasm_i32x4_sub(k_int, k1);
v128_t two_k1 = wasm_i32x4_shl(wasm_i32x4_add(k1, wasm_i32x4_splat(127)), 23);
v128_t two_k2 = wasm_i32x4_shl(wasm_i32x4_add(k2, wasm_i32x4_splat(127)), 23);
return wasm_f32x4_mul(wasm_f32x4_mul(p, two_k1), two_k2); // rounds to inf or a denormal
}
This makes SiLU easy to implement,
// silu(z) = z / (1 + e^-z), in each lane.
INLINE v128_t silu4(v128_t z) {
return wasm_f32x4_div(z, wasm_f32x4_add(splat(1.0f), exp4(wasm_f32x4_neg(z))));
}
softmax is still a bit of a pain... We have to make sure to pad outputs to a multiple of 4 since we are using vectorized f32. We trust that the caller allocated memory for us!
INLINE void softmax(float *Z, int n, int d, int stride) {
int d4 = (d + 3) / 4 * 4;
for (int s = 0; s < n; s++) {
float *z = Z + s * stride;
// first pad z to a multiple of 4
// need to use -\infty for softmax
for (int k = d; k < d4; k++)
z[k] = -__builtin_inff();
// compute max of the z array
v128_t max4 = wasm_v128_load(z);
for (int k = 4; k < d4; k += 4)
max4 = wasm_f32x4_pmax(max4, wasm_v128_load(z + k));
// at this point we know 1 of 4 is the max
// example: suppose 'a' is the largest
// first calculate max([ a, b, c, d], [c, d, a, b])
// = [a, b/d, a, b/d]
max4 = wasm_f32x4_pmax(max4, wasm_i32x4_shuffle(max4, max4, 2, 3, 0, 1));
// then max([a, b/d, a, b/d], [b/d, a, b/d, a]) = [a,a,a,a]
max4 = wasm_f32x4_pmax(max4, wasm_i32x4_shuffle(max4, max4, 1, 0, 3, 2));
// the same works for any order
// calculate totals and exp(z - max) as we
// iterate through the array
v128_t total4 = splat(0.0f);
for (int k = 0; k < d4; k += 4) {
v128_t e = exp4(wasm_f32x4_sub(wasm_v128_load(z + k), max4));
wasm_v128_store(z + k, e);
total4 = wasm_f32x4_add(total4, e);
}
// finally, divide everything by \sum exp(z - max)
float total = wasm_f32x4_extract_lane(total4, 0);
total += wasm_f32x4_extract_lane(total4, 1);
total += wasm_f32x4_extract_lane(total4, 2);
total += wasm_f32x4_extract_lane(total4, 3);
v128_t scale = splat(1.0f / total);
for (int k = 0; k < d4; k += 4)
wasm_v128_store(z + k, wasm_f32x4_mul(wasm_v128_load(z + k), scale));
}
}
putting the implementation together
The hard parts are done now.
There are some other very minor other changes, for example
storing the gate and up weights as a single weight, gate_up (arguably this should have been done earlier).
We check how many samples/rows we should process in a tile - see Figure 5 which tells us to use 4.
Accordingly, forward_batch splits inputs into groups/tiles of 4 rows:
// pointers for the different weight parameters
// in a GLU block
typedef struct {
float *norm;
float *gate_upT;
float *downT;
} Block;
// all data we need to compute forward pass
typedef struct {
int d_in, d, hidden, d_out, d_out_pad, n_blocks;
// parameters:
float *embT, *emb_b, *norm, *headT, *head_b, *zeros;
// activations, for one tile:
float *h, *n, *gate_up, *act, *down, *out;
Block blocks[MAX_BLOCKS];
} Model;
INLINE void rms_norm(float *Y, const float *X, int n, const float *w, int d) {
for (int s = 0; s < n; s++) {
const float *x = X + s * d;
float *y = Y + s * d;
v128_t sq = splat(0.0f);
for (int i = 0; i < d; i += 4) {
v128_t xi = wasm_v128_load(x + i);
sq = wasm_f32x4_relaxed_madd(xi, xi, sq);
}
float sum = wasm_f32x4_extract_lane(sq, 0);
sum += wasm_f32x4_extract_lane(sq, 1);
sum += wasm_f32x4_extract_lane(sq, 2);
sum += wasm_f32x4_extract_lane(sq, 3);
v128_t scale = splat(1.0f / __builtin_sqrtf(sum / d + 1.1920929e-7f));
for (int i = 0; i < d; i += 4) {
v128_t xi = wasm_v128_load(x + i);
wasm_v128_store(y + i,
wasm_f32x4_mul(wasm_f32x4_mul(xi, scale),
wasm_v128_load(w + i)));
}
}
}
// compute full forward pass
// computes n rows at once
static void forward_rows(const Model *m, const float *X, int n) {
int d = m->d, hidden = m->hidden;
linear(m->h, X, n, m->embT, m->emb_b, m->d_in, d);
for (int k = 0; k < m->n_blocks; k++) {
const Block *block = &m->blocks[k];
rms_norm(m->n, m->h, n, block->norm, d);
linear(m->gate_up, m->n, n, block->gate_upT, m->zeros, d, 2 * hidden);
for (int s = 0; s < n; s++) {
const float *gate = m->gate_up + s * 2 * hidden, *up = gate + hidden;
for (int j = 0; j < hidden; j += 4) {
v128_t act = wasm_f32x4_mul(silu4(wasm_v128_load(gate + j)), wasm_v128_load(up + j));
wasm_v128_store(m->act + s * hidden + j, act);
}
}
linear(m->down, m->act, n, block->downT, m->zeros, hidden, d);
for (int i = 0; i < n * d; i += 4) {
v128_t h = wasm_f32x4_add(wasm_v128_load(m->h + i), wasm_v128_load(m->down + i));
wasm_v128_store(m->h + i, h);
}
}
rms_norm(m->n, m->h, n, m->norm, d);
linear(m->out, m->n, n, m->headT, m->head_b, d, m->d_out_pad);
softmax(m->out, n, m->d_out, m->d_out_pad);
}
__attribute__((export_name("forward_batch")))
void forward_batch(const Model *m, const float *X, float *out, int B, int tile) {
// recommended tile = 4, based on Figure 5
for (int s = 0; s < B; s += tile) {
int n = B - s < tile ? B - s : tile;
forward_rows(m, X + s * m->d_in, n);
for (int r = 0; r < n; r++) // drop the head's padding
for (int k = 0; k < m->d_out; k++)
out[(s + r) * m->d_out + k] = m->out[r * m->d_out_pad + k];
}
}
We don't show the JS here for simplicity, but code is available on github
We begin to reach diminishing returns here. This implementation is a lot more effort, and only about 1.5x faster than just having the linear modules in wasm. Also, memory overhead is slightly worse.
+ multiple threads
Finally, we propose running the previous step in multiple threads. This should be an easy win! The idea is simple: split the batch into one chunk of rows per thread, and run step 4 on each chunk at the same time.
We tested this using node, but our implementation is not quite browser compatible. In principle at least, it should nonetheless be possible in the browser. It seems like using Web Workers is the correct approach.
We don't show an implementation here to avoid tedium. Of course multi-threading is faster, with 6 threads it's ~5x faster. On the downside, it does cost us memory - each thread holds its own copy of the weights. The overhead from duplicating weight should be small, so overhead is more likely from the runtime.
Appendix
A1, Max FLOPS estimate
Below is a script that estimates max fp32 GFLOPS of a single core. We get around 135 GFLOPS:
$ clang -O2 -std=c2x fp32_gflops.c -o gflops && ./gflops
134.2 GFLOPS (1.71799e+10)
The script performs multiply-adds to an array 1B times, using
the vectorized fp32 instructions. This (should) be faster than standard
multiply/adds. We clarify the float32x4_t functions/types,
#include <arm_neon.h>
// 128-bits, representing 4 fp32 numbers
type float32x4_t;
// computes a + b * c
float32x4_t vfmaq_f32(float32x4_t a, float32x4_t b, float32x4_t c);
// duplicates `x` into 4 'lanes', to give us 4 32bit floats
float32x4_t vdupq_n_f32(float x);
The script is,
// peak fp32 GFLOPS of one core
// $ clang -O2 -std=c2x fp32_gflops.c -o gflops && ./gflops
#include <arm_neon.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#define A_LEN 16
int main(void) {
float x = M_E, y = M_PI;
float32x4_t m = vdupq_n_f32(x), c = vdupq_n_f32(y), a[A_LEN] = {0};
//make sure we don't fold `m*c` into a const
__asm__ volatile("" : "+w"(m), "+w"(c));
long iters = 1'000'000'000; // 1B
clock_t t = clock();
for (long n = 0; n < iters; n++) {
for (int i = 0; i < A_LEN; i++) {
// calculates a + m * c
// 4 lanes, 2 FLOPs => 8 FLOPs per iter
a[i] = vfmaq_f32(a[i], m, c);
}
}
double s = (double)(clock() - t) / CLOCKS_PER_SEC;
// use a to avoid compiler skipping the computation
float sum = 0; // use the result, so the loop isn't removed
for (int i = 0; i < A_LEN; i++) { sum += vaddvq_f32(a[i]); }
printf("%.1f GFLOPS (%g)\n", iters * A_LEN * 8 / s / 1e9, sum);
}
The script is sensitive to A_LEN - 16 gave the highest FLOPS from 8, 16, 32, 64