DEV Community

Cover image for Your first GPU kernel in C#, in the browser and on the desktop
Todd Tanner
Todd Tanner

Posted on Edited on Originally published at spawndev.com

Your first GPU kernel in C#, in the browser and on the desktop

Live demo | Full example on GitHub

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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.Blazor
Enter fullscreen mode Exit fullscreen mode

Save 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();
Enter fullscreen mode Exit fullscreen mode

Add these lines to _Imports.razor:

@using SpawnDev.SpawnJS
@using SpawnDev.SpawnJS.JSObjects
Enter fullscreen mode Exit fullscreen mode

Get 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();
}
Enter fullscreen mode Exit fullscreen mode
  • CreatePreferredAcceleratorAsync picks the best option the browser has: WebGPU, then WebGL, then WebAssembly.
  • Allocate2DDenseX reserves memory for the image on the GPU.
  • LoadAutoGroupedStreamKernel compiles 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");
}
Enter fullscreen mode Exit fullscreen mode

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

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.ILGPU
Enter fullscreen mode Exit fullscreen mode

Copy 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}%");
Enter fullscreen mode Exit fullscreen mode

On the same PC this printed:

Cuda (NVIDIA GeForce RTX 4070): 0.4 ms
One CPU thread: 218.5 ms
Matching pixels: 100.00%
Enter fullscreen mode Exit fullscreen mode

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

Get the finished projects

git clone https://github.com/LostBeard/SpawnDev.Examples
cd SpawnDev.Examples/GpuKernel
dotnet run
Enter fullscreen mode Exit fullscreen mode

For the desktop version, run dotnet run -c Release in GpuKernel.Desktop.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The measurement table is what makes this land — 800 ms on the page, 1 to 5 ms on WebGPU, and 0.4 ms on CUDA, all for the same Mandelbrot.cs, with 100.00% matching pixels between the desktop and browser runs. That last number is the real story for me: the portability, not just the speedup. The honest caveat about GPU times leaving out one-time setup and first-run kernel compile is the part most demos skip, and it is exactly what decides whether this wins in a real app. The WebGL fallback at about 65 ms versus 1 to 5 ms on WebGPU is the gap I would want to understand — is that mostly compile, data transfer, or headless Chromium? And with kernels limited to numbers and structs, no objects or strings, what is the first workload where you hit that wall and have to restructure the data to fit?