WebGPU - Futhark on your GPU in your browser
Part of the Futhark dream is the ability to run high-level array programs on any parallel machine. We are still pretty far from that dream entering the waking world, but after merging an experimental WebGPU backend, we can at least run Futhark code in browsers whilst taking advantage of the GPU, and since browsers seem reasonably popular these days, that seems worth noting. This post describes the development history behind this new WebGPU backend, goes into the reasons why WebGPU is a challenging target for Futhark, discusses which restrictions remain for Futhark programs that intend to run in a browser (they are pretty severe, and some are not clearly solvable), and argues for why I decided to merge a fragile and experimental backend.
Background
I am not an experienced web developer at all, nor do I particularly like the web
platform on its technical merits, but it is hard to dispute the fact that it is
prevalent. For this reason, we have long been interested in running Futhark in
the browser. This has actually been possible since a WebAssembly backend was
implemented by Philip Lassen, although
I don’t think many people actually used it. The backend worked (and still works)
by taking Futhark’s generated C code and compiling it to
WebAssembly through
Emscripten, along with a bit of glue JavaScript to
present a more friendly interface. Due to the efforts of the Emscripten
developers, and the fact that Futhark produces pretty straightforward and
portable C code, this backend actually supports the entire Futhark language.
Through Emscripten’s support for POSIX threads, even multithreaded execution is
possible through the wasm-multicore backend.
Yet while Futhark is intended to run everywhere, and a CPU is certainly part of
everywhere, it is pretty clear that our main focus has always been GPU
execution. Browsers have supported various GPU programming APIs over the years,
but WebGPU is the newest and by far the nicest. Although
mostly intended for graphics, it also has decent support for pure computation,
which is the niche that Futhark is interested in. Therefore, in 2024 Sebastian
Paarman implemented the beginnings of a WebGPU
backend for Futhark as part of his MSc
thesis.
Apart from laying the foundations of the backend, Sebastian also focused on how
to test it, in particular by creating a rather elaborate setup for how our
futhark test tool could talk to code running within a browser. At the
conclusion of Sebastian’s project, the bones were in place, but only a very
small part of Futhark could be handled, and it was not usable for most
interesting programs.
The following year, Caleb Andreasen continued the work in his BSc thesis, which mainly consisted of addressing a rather ad-hoc list of limitations. Among the more interesting things, Caleb worked on proper floating-point support (such as infinities and NaNs) and atomic updates.
This year, I then spent some time working on it myself, mostly by trying to systematically determine the limitations and setting up some reliable testing. In particular, I set up reliable non-browser testing using Node.js and CPU-based implementation of WebGPU. Despite many remaining limitations, discussed below, I think it is good enough for light use.
The basic idea of the WebGPU backend is similar to the WASM backends: generate some C code with calls to the WebGPU API, and compile it with Emscripten, which turns the CPU code into WebAssembly, but does not touch any embedded GPU code. Interacting with WebGPU from C is surprisingly well documented, and while there are some challenges related to mapping between C’s synchronous APIs and the asynchronous execution environment of the browser, all of this is papered over quite nicely by Emscripten through its Asyncify facility. The real challenge we encounter is actually expressing the GPU code itself (the “kernels”, which WebGPU calls “shaders”), which is done through the WebGPU Shading Language (WGSL), which is embedded as strings in the generated C code. That posed some difficulties, and required us to implement a completely new and custom code generator that uses a new Haskell library for representing WGSL programs.
Why WebGPU is such a difficult target for Futhark
Futhark does not make particularly harsh demands of the GPU, and we even put significant effort into doing clever things without requiring new GPU features. Yet even our modest requirements (or so I thought) exceed in some cases what WebGPU can provide, relative to what we are used to in OpenCL, CUDA, or HIP. I suspect the restrictions are rooted both in the incredibly hostile environment that browsers have to run in, as well as a desire for WebGPU to run even on terrible mobile GPUs.
Some of the limitations are fundamental to WebGPU or WGSL, some can be worked around by Futhark programmers, and some can be avoided by changing how the compiler optimises code to avoid unsupported constructs. Unfortunately, there are cases where a Futhark program will not work with WebGPU, and where it is very hard for a programmer to understand the reason. Let me go through some of the cases.
The simple issues
The simplest limitation is that double precision floating-point numbers are not
supported in WebGPU. This can be avoided by not using the f64 type in your
Futhark programs. When Futhark’s OpenCL backend was first developed, the GPU on
my laptop also had this restriction, so there was some vestigial code in our
code generators for conditionally including f64-specific code, which we used
to also handle this in WebGPU. I had actually planned to remove this facility,
but I suppose we’ll keep it around for a little while.
A sibling problem is that Futhark always requires the browser to support
half-precision floating point numbers (Futhark’s f16 type), whether they are
used by the program or not. As of this writing, Firefox’s WebGPU implementation
does not support this type, and so Futhark’s WGSL shaders do not work in
Firefox. There is no deep reason for this except we never had to include f16
runtime code conditionally before, and I
strongly suspect this can be solved using similar conditional compilation as we
do with f64 support, but I have not had time to try it out.
WGSL does not directly support 64-bit integers. For programs that use Futhark’s
i64 or u64 types, we emulate these using 32-bit arithmetic. This works (no
comment on performance…), but not when we want to perform 64-bit atomic
operations. As a result, programs that compute for example
histograms with 64-bit integers will fail to
compile with the WebGPU backend. These are easy enough to avoid on their own
(just don’t do them), but there are also some more exotic cases where the
Futhark compiler may produce 64-bit atomic operations for internal reasons, and
these will also fail to compile, for reasons that are somewhat opaque to the
user.
Futhark’s mechanism for bounds checking in GPU
code relies on goto (structured goto, but
still goto), which WGSL does not provide, and so any bounds checks (and other
dynamic safety checks) are silently
ignored. Safety checks outside of code that ends up in WGSL shaders are
maintained, which means most basic input validation code should remain
operational. The workaround is that programmers should just not make mistakes.
In principle, we could perhaps come up with another way of implementing bounds
checking that is not based on goto - one option would be to extract control
flow blocks into separate functions, as Futhark’s use of goto is equivalent to
returning from a function.
A nastier issue
The most thorny problem is that WGSL does not have first-class pointers. Futhark does not perform any pointer arithmetic, but it does need pointer values, or something equivalent. Consider an expression like the following:
let C = if cond then A
else BSuppose C is an array, and so are A and B. Taking a slightly naive view of
how Futhark associates arrays with memory (full story
here), we can imagine that A and B
are represented at run-time as the pointers A_mem and B_mem. The imperative
code for the conditional would then be something like this:
var C_mem : ptr
if cond:
C_mem <- A_mem
else:
C_mem <- B_mem
In Futhark’s imperative-level intermediate representation, this assignment of a
pointer value is a special SetMem construct. Unfortunately, this has no
counterpart in WGSL. Pointer assignment is, to my knowledge, not possible. This
is a major source of uncompilable Futhark programs, as not only is it perfectly
natural to write conditionals that produce arrays, but Futhark also has various
program transformations that have no particular compunctions about adding
conditionals that produce arrays as they are usually not a problem.
While very careful programming (basically, great paranoia about using arrays
inside map, which is the main source of shaders) can avoid running into this
issue, clearly we need to make improvements to the compiler. One possibility is
to aggressively transform cases such as the if above to pre-allocate a C_mem
of the right size (sometimes easier said than done), then copy the contents of
arrays instead of just doing pointer assignment. Since Futhark is
pure this can be done without
semantic harm, although there is of course an overhead involved.
Another option is a more invasive change to WGSL code generation where we use a form of static analysis to associate each pointer with a set of possible pointers at run-time, and turn every single index into a conditional. Following on from the example above, we could produce code such as:
var C_mem : int
if cond:
C_mem <- 0
else:
C_mem <- 1
And then an index operation such as C[i] would be translated to a conditional:
if C_mem == 0
then A_mem[i]
else B_mem[i]
Since the total number of pointers available in a WGSL shader is statically bounded (due to no pointer arithmetic), this is always possible, but can of course have an utterly ruinous impact on performance when there are many options.
I should note that not just conditionals are subject to this problem; any code
that involves flow-variant arrays induces pointer assignment. In particular,
loop will often do so.
As a related pointer issue, WGSL functions (not shaders) may only accept
pointer parameters when using the extension unrestricted_pointer_parameters.
Unfortunately, Firefox’s WebGPU implementation does not as of this writing
implement this extensino. While the Futhark compiler inlines very
aggressively, it will in some cases leave functions
in WGSL programs, and sometimes those functions end up with pointer parameters.
These will then not work in Firefox. Further, some of the runtime system code we
prepend generated WGSL also contains functions with pointer parameters, so
simply tweaking the inliner to be more aggressive is not going to cut it. I hope
Firefox will just get around to implementing this extension, but if not, we’ll
have to consider something invasive. I am very reluctant to contribute to the
current near-monoculture of browser implementations.
A dumber issue
Turning to a lighter problem, WGSL limits how many “storage buffers” (allocations) a WGSL shader may “bind” (access). The limit varies among implementations, but is usually not that many, but seems to typically be between 10 and 20. Programmers can generally rely on one array being one allocation (but beware the value representation), but with hoisting, fusion, flattening, and so on, it can be difficult to reason about how a program will ultimately be carved into shaders.
This is a silly problem. Browsers really ought to just bump that constant, or at least allow programs to request a higher limit. Yes, I am aware that this could be used for browser fingerprinting. The web is an awful, awful place…
An unknown issue that will certainly bite us in the future
WGSL only permits memory fences in uniform control flow, meaning that all
threads must reach the fence. This is essentially the same restriction as with
barriers. In most cases this is not a problem for Futhark, but in the specific
case where we implement very complicated histogram operators (tuple-typed) with
spinlocks, we actually depend on thread-level fences to implement the spinlock.
Our workaround solution is to just ignore fences when generating WGSL, but
this will certainly produce wrong results for such histograms. I can also say
with high confidence that there will be some other place where we insert a fence
for subtle reasons, since memory model properties are not simply things you can
ignore without future regret. But that is a discovery for the future.
Examples
Some of these restrictions sound pretty dire. Is the WebGPU backend useful at all? I think so! In fact, I have produced two new example programs that demonstrate execution of Futhark in your browser. Note that you must have enabled WebGPU in your browser for this to work, which is seemingly still not the default on all platforms. Further, due to the pointer parameter issue discussed above, Firefox rejects these programs, but they do work in Chromium.
The examples are as follows:
Mandelbrot is a simple visualiser of a Mandelbrot fractal, which also shows how you can use JavaScript events to interact with the Futhark program.
N-body shows how to do a timer-based animation.
Whilst these programs have been compiled with futhark webgpu, the exact same
JavaScript API is exposed by futhark wasm and futhark multicore, so they
could also be recompiled to run on the CPU instead. But where’s the fun in that?
There is also a repository of Futhark WebGPU examples, mostly developed by Tudor Pal during an employment as a research programmer funded by the STIBO Foundation. It contains more detailed examples on how to interact with Futhark code from JavaScript, and also some information on how to convince your browser to run WebGPU at all.
What next
The WebGPU backend has known limitations, and some of them seem like they have
reasonably achievable solutions. Yet I am not actively working on them, and
while they are documented in the futhark webgpu manpage, I have not even
bothered creating issues for them in our bug tracer. While I may fix some
restrictions as interest and time permits, my main hope is that people will find
something useful, fun, or interesting to do with Futhark’s WebGPU, and then I
will fix the limitations in the order they matter to people (or document more
precisely how to work around them).
Currently the WebGPU backend uses the exact same compiler pipeline as the other GPU backends. I expect that it would be profitable to make somewhat different optimisation choices, or at least disable those optimisations that run into WGSL limitations. We do not have good infrastructure for having much backend-specific logic in the compiler pipeline, mostly intentionally, but perhaps it is time to add it.
As a somewhat annoying wart, we do not currently test WebGPU on GPUs in our Continuous Integration suite. While our CI setup does have access to GPUs hosted at a compute cluster at the University of Copenhagen, which we use to test the other GPU backends, WebGPU implementations seemingly have to go through Vulkan, and that is missing from the cluster machines. I don’t think this is a big deal, as our Node.js/Lavapipe-based tests go through the same WebGPU frontend that (some) browsers use, but I am uncomfortable with the fact that we do not actually test the main intended execution environment.
I suppose we also need to actually benchmark the generated code at some point. Due to the challenges in getting this thing to work at all, I really have no idea how it performs. While I know some things (64-bit arithmetic…) are probably quite slow, most of the compiler is shared with the existing GPU backends, which we know are fast. Unfortunately, Futhark’s usual benchmarking tools don’t really work when you run the code in a browser.
Ultimately, I think the WebGPU backend serves no-one by staying unmerged for another year. It’s not invasive regarding the compiler as a whole, and its foundations are robust enough that I don’t mind pushing it out into the world. We’ll fix its problems as they crop up, and then we can see about actually building something nice on top of it.