Some work is the same small calculation, repeated for every pixel or every item. A CPU does those a few at a time. A GPU does thousands at once.
Using the GPU usually means learning a second language for shaders, and a different one for the browser than for the desktop. With SpawnDev.ILGPU you write the calculation as a C# method. The same file runs in a Blazor app and in a desktop app.
We will draw a fractal, the Mandelbrot set, on the page and on the GPU, then run the same code in a console app. You need the .NET 10 SDK and a browser.
The kernel
A kernel is a method the GPU runs once for every item, in our case every pixel:
using ILGPU;
using ILGPU.Runtime;
namespace GpuKernel;
public static class Mandelbrot
{
/// <summary>The kernel: the GPU runs this once for every pixel.</summary>
public static void Kernel(Index2D pixel, ArrayView2D<uint, Stride2D.DenseX> image, int maxSteps) =>
image[pixel] = Color(pixel.X, pixel.Y, (int)image.Extent.X, (int)image.Extent.Y, maxSteps);
/// <summary>Plain C#: the color of one pixel.</summary>
public static uint Color(int x, int y, int width, int height, int maxSteps)
{
float cx = x * 3.0f / width - 2.2f;
float cy = y * 2.4f / height - 1.2f;
float zx = 0, zy = 0;
int step = 0;
while (step < maxSteps && zx * zx + zy * zy < 4)
{
float next = zx * zx - zy * zy + cx;
zy = 2 * zx * zy + cy;
zx = next;
step++;
}
if (step == maxSteps) return 0xFF000000; // inside the set: black
uint shade = (uint)(step * 8 & 255);
return 0xFF000000 | shade << 16 | (shade / 2) << 8 | 40;
}
}Kernel receives the pixel it should work on, the image to write to, and a setting. Color is ordinary C#, which is why we can also call it from the page and compare.
Kernels have some limits. They work with numbers and structs, and they cannot create objects, use strings or throw exceptions.
Set up
dotnet new blazorwasm -o GpuKernel --empty
cd GpuKernel
dotnet add package SpawnDev.ILGPU
dotnet add package SpawnDev.SpawnJS
dotnet add package SpawnDev.SpawnJS.BlazorSave the class above as Mandelbrot.cs, then replace Program.cs:
using GpuKernel;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using SpawnDev.SpawnJS;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddSpawnJSRuntime();
await builder.Build().SpawnJSRunAsync();Add these lines to _Imports.razor:
@using SpawnDev.SpawnJS
@using SpawnDev.SpawnJS.JSObjectsGet the GPU ready
async Task SetUpGpu()
{
if (kernel is not null) return;
context = await Context.CreateAsync(builder => builder.AllAcceleratorsAsync());
accelerator = await context.CreatePreferredAcceleratorAsync();
image = accelerator.Allocate2DDenseX<uint>(new Index2D(Width, Height));
kernel = accelerator.LoadAutoGroupedStreamKernel<Index2D, ArrayView2D<uint, Stride2D.DenseX>, int>(Mandelbrot.Kernel);
renderer = CanvasRendererFactory.Create(accelerator);
using var canvas = JS.Call<string, HTMLCanvasElement>("document.getElementById", "canvas");
renderer.AttachCanvas(canvas);
// The first run also compiles the kernel for this GPU, so do it once before timing.
kernel(image.IntExtent, image.View, MaxSteps);
await accelerator.SynchronizeAsync();
}CreatePreferredAcceleratorAsyncpicks the best option the browser has: WebGPU, then WebGL, then WebAssembly.Allocate2DDenseXreserves memory for the image on the GPU.LoadAutoGroupedStreamKernelcompiles the C# method for that GPU.
Run it
async Task DrawOnGpu()
{
await Start();
await SetUpGpu();
var timer = Stopwatch.StartNew();
kernel!(image!.IntExtent, image.View, MaxSteps);
await accelerator!.SynchronizeAsync();
timer.Stop();
await renderer!.PresentAsync(image);
Finish($"GPU ({accelerator.AcceleratorType}): {timer.Elapsed.TotalMilliseconds:F0} ms");
}Calling the kernel queues the work, and SynchronizeAsync waits for it to finish. In the browser, always wait this way. PresentAsync then shows the image on the canvas.
What we measured
800,000 pixels, on one PC with an RTX 4070:
| Where | Time |
|---|---|
| On the page (Chrome) | about 800 ms |
| GPU, WebGPU (Chrome) | 1 to 5 ms |
| GPU, WebGL (headless Chromium) | about 65 ms |
The GPU times leave out the one-time setup and the first run, which compiles the kernel. Your times will differ, and your browser may pick a different option.
The same kernel on the desktop
A console app can use the same Mandelbrot.cs:
dotnet new console -o GpuKernel.Desktop
cd GpuKernel.Desktop
dotnet add package SpawnDev.ILGPUCopy Mandelbrot.cs into it and replace Program.cs:
using System.Diagnostics;
using GpuKernel;
using ILGPU;
using ILGPU.Runtime;
using SpawnDev.ILGPU;
const int Width = 1000, Height = 800, MaxSteps = 500;
using var context = await Context.CreateAsync(builder => builder.AllAcceleratorsAsync());
using var accelerator = await context.CreatePreferredAcceleratorAsync();
using var image = accelerator.Allocate2DDenseX<uint>(new Index2D(Width, Height));
var kernel = accelerator.LoadAutoGroupedStreamKernel<Index2D, ArrayView2D<uint, Stride2D.DenseX>, int>(Mandelbrot.Kernel);
// The first run also compiles the kernel for this GPU, so do it once before timing.
kernel(image.IntExtent, image.View, MaxSteps);
await accelerator.SynchronizeAsync();
var timer = Stopwatch.StartNew();
kernel(image.IntExtent, image.View, MaxSteps);
await accelerator.SynchronizeAsync();
timer.Stop();
Console.WriteLine($"{accelerator.AcceleratorType} ({accelerator.Name}): {timer.Elapsed.TotalMilliseconds:F1} ms");
// Same method, plain C#, one thread.
timer.Restart();
var expected = new uint[Width * Height];
for (var y = 0; y < Height; y++)
for (var x = 0; x < Width; x++)
expected[y * Width + x] = Mandelbrot.Color(x, y, Width, Height, MaxSteps);
timer.Stop();
Console.WriteLine($"One CPU thread: {timer.Elapsed.TotalMilliseconds:F1} ms");
var pixels = image.GetAsArray2D();
var same = 0;
for (var y = 0; y < Height; y++)
for (var x = 0; x < Width; x++)
if (pixels[x, y] == expected[y * Width + x]) same++;
Console.WriteLine($"Matching pixels: {100.0 * same / expected.Length:F2}%");On the same PC this printed:
Cuda (NVIDIA GeForce RTX 4070): 0.4 ms
One CPU thread: 218.5 ms
Matching pixels: 100.00%Without an NVIDIA card it uses OpenCL, or a CPU backend when there is no GPU.
When a GPU helps
- Good fit: work that can be split into many small pieces that run at the same time. Images, physics, simulations, video codecs and neural networks.
- Poor fit: work that cannot be split up well, or too little work to make up for moving the data to the GPU and back.
Work with many steps is fine, as long as each step can be split up. Neural networks and video codecs run one kernel after another, and the data stays on the GPU between steps.
The whole page
Replace Pages/Home.razor with this:
@page "/"
@using System.Diagnostics
@using ILGPU
@using ILGPU.Runtime
@using SpawnDev.ILGPU
@using SpawnDev.ILGPU.Rendering
@inject SpawnJSRuntime JS
@implements IDisposable
<main>
<h1>Who draws it faster?</h1>
<p>Both buttons run the same C# method for every one of @((Width * Height).ToString("N0")) pixels. One runs it on the page, one on your GPU.</p>
<button id="cpu" disabled="@busy" @onclick="DrawOnPage">Draw on the page</button>
<button id="gpu" disabled="@busy" @onclick="DrawOnGpu">Draw on the GPU</button>
<p id="result" role="status">@result</p>
<canvas id="canvas" width="@Width" height="@Height"></canvas>
</main>
@code {
const int Width = 1000, Height = 800, MaxSteps = 500;
bool busy;
string result = "";
Context? context;
Accelerator? accelerator;
ICanvasRenderer? renderer;
MemoryBuffer2D<uint, Stride2D.DenseX>? image;
Action<Index2D, ArrayView2D<uint, Stride2D.DenseX>, int>? kernel;
async Task SetUpGpu()
{
if (kernel is not null) return;
context = await Context.CreateAsync(builder => builder.AllAcceleratorsAsync());
accelerator = await context.CreatePreferredAcceleratorAsync();
image = accelerator.Allocate2DDenseX<uint>(new Index2D(Width, Height));
kernel = accelerator.LoadAutoGroupedStreamKernel<Index2D, ArrayView2D<uint, Stride2D.DenseX>, int>(Mandelbrot.Kernel);
renderer = CanvasRendererFactory.Create(accelerator);
using var canvas = JS.Call<string, HTMLCanvasElement>("document.getElementById", "canvas");
renderer.AttachCanvas(canvas);
// The first run also compiles the kernel for this GPU, so do it once before timing.
kernel(image.IntExtent, image.View, MaxSteps);
await accelerator.SynchronizeAsync();
}
async Task DrawOnGpu()
{
await Start();
await SetUpGpu();
var timer = Stopwatch.StartNew();
kernel!(image!.IntExtent, image.View, MaxSteps);
await accelerator!.SynchronizeAsync();
timer.Stop();
await renderer!.PresentAsync(image);
Finish($"GPU ({accelerator.AcceleratorType}): {timer.Elapsed.TotalMilliseconds:F0} ms");
}
async Task DrawOnPage()
{
await Start();
await SetUpGpu(); // only to show the finished picture
var timer = Stopwatch.StartNew();
var pixels = new uint[Width * Height];
for (var y = 0; y < Height; y++)
for (var x = 0; x < Width; x++)
pixels[y * Width + x] = Mandelbrot.Color(x, y, Width, Height, MaxSteps);
timer.Stop();
image!.View.BaseView.CopyFromCPU(pixels);
await renderer!.PresentAsync(image);
Finish($"Page: {timer.Elapsed.TotalMilliseconds:F0} ms");
}
async Task Start()
{
busy = true;
result = "Drawing...";
await Task.Delay(50); // let the page draw
}
void Finish(string message)
{
result = message;
busy = false;
}
public void Dispose()
{
image?.Dispose();
renderer?.Dispose();
accelerator?.Dispose();
context?.Dispose();
}
}Get the finished projects
git clone https://github.com/LostBeard/SpawnDev.Examples
cd SpawnDev.Examples/GpuKernel
dotnet runFor the desktop version, run dotnet run -c Release in GpuKernel.Desktop.