返回资讯中心
外部精选
软件工程
#开发者实时流

Let's Build a Transformer in C#, One GPU Kernel at a Time

I learned top-down recursive-descent parsing from Jack Crenshaw’s Let’s Build a Compiler!. I’ve used it many times since, including for a custom color formatter I wrote for a C board that didn’t have one. His approach s…

Hacker News 最新andyphunter2026/10/15 · 2026/10/1530 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

I learned top-down recursive-descent parsing from Jack Crenshaw’s Let’s Build a Compiler!. I’ve used it many times since, including for a custom color formatter I wrote for a C board that didn’t have one. His approach stayed with me: write a small piece, run it, understand what happened, and extend the same program.

I want to do that here with transformer inference. We’ll build a program that takes a prompt, loads a model’s weights, and generates text. Along the way we’ll write the operations that turn those weights and our input into the next token. We’ll introduce the arithmetic needed to understand each piece as we write it. You don’t need a course in machine learning before starting.

We’ll use C#, and we’ll use the GPU from the beginning. The .NET community includes developers on Windows, Linux, and Mac, so reaching that community means accounting for all three. As we covered in the prologue, native Metal support on Mac is the reason we’re using a pinned development revision of ILGPU. Keep that revision for this lesson; the examples depend on its API.

Today we’ll add two arrays. That gives us a small enough calculation to check by eye while we establish the whole path: choose a GPU, put data in its buffers, run our code there, and bring the result back. Element-by-element addition will also have a job later, when we connect parts of the transformer through residual connections.

Start from lesson-00, the completed prologue. If you’re following with Git and have a clean working tree, create a local branch for your changes:

git switch -c work/lesson-01 lesson-00 dotnet run --project src/Cradle

You should see:

Cradle is ready.

If you haven’t prepared the dependencies yet, follow the prologue first. From here on, commands run from the repository root. All our application code stays in src/Cradle/Program.cs, inside the existing Program class. We’ll add a few static methods, but we don’t yet need another class to manage the GPU for us. I want us to see what it takes to do that job before we package it up.

There are two choices involved in running our kernel: the kind of GPU code we build, and the device we run it on. ILGPU calls the first choice a backend. The project already defaults to Metal on Mac and CUDA elsewhere. CUDA is the NVIDIA path; a Windows or Linux machine with another GPU will need a different choice.

This compiler revision builds our application’s kernels for one backend at a time. The device we select must support that backend. Finding a Metal device doesn’t help a program containing CUDA kernels, even though both devices are GPUs. A device exposed through OpenCL is also a different target from one exposed through CUDA, even when they refer to the same physical card.

You can override the project default when building or running. For example, with an appropriate OpenCL device and driver:

dotnet run --project src/Cradle -p:ILGPUBackend=OpenCL

The GPU backend choices in this revision are CUDA, ROCm, OpenCL, and Metal. Choose for your device and installed driver, then use that setting on subsequent commands that build, including dotnet test. The commands below use the project default to keep them readable. If you chose an override, keep adding it. Passing a different setting with --no-build cannot change the kernels in a binary we’ve already built.

We need our running program to know that build-time choice. Open src/Cradle/Cradle.csproj and add this line to the existing ItemGroup, alongside the ILGPU project reference:

<AssemblyMetadata Include="ILGPUBackend" Value="$(ILGPUBackend)" />

The build writes the value into our application assembly. That avoids maintaining a second, hard-coded backend choice in Program.cs.

Add these imports above namespace Cradle;:

using System; using System.Reflection; using ILGPU; using ILGPU.Runtime; using ILGPU.Runtime.OpenCL;

Then add this method inside Program, above Main:

private static AcceleratorType GetCompiledBackend() { // The project records the same setting used by the kernel compiler. var backendName = typeof(Program).Assembly .GetCustomAttributes<AssemblyMetadataAttribute>() .Single(attribute => attribute.Key == "ILGPUBackend").Value!;

return Enum.Parse<AcceleratorType>(backendName, ignoreCase: true); }

This reads the metadata we just added and converts its name into ILGPU’s AcceleratorType. Now the compiler and device-selection code have the same source for that choice.

var compiledBackend = GetCompiledBackend(); using var context = Context.CreateDefault();

Console.WriteLine("Available devices"); Console.WriteLine($"Compiled kernel backend: {compiledBackend}"); Console.WriteLine(); foreach (var device in context.Devices) { device.PrintInformation(Console.Out); Console.WriteLine(); }

The context is our entry point into ILGPU. It discovers available devices and owns runtime resources used to work with them. Creating it hasn’t selected a GPU or launched any work.

Run the program again. You should get device information in place of the greeting. Look at the reported backend as well as the device names. A CPU entry is normal: ILGPU can also execute kernels on the CPU. We’re going to select a GPU explicitly.

Add the following after the device loop, still inside Main:

var preferredDevice = context.Devices .Where(device => device.AcceleratorType == compiledBackend) .Where(device => device switch { CLDevice cl => (cl.DeviceType & CLDeviceType.CL_DEVICE_TYPE_GPU) != 0,

_ => device.AcceleratorType is AcceleratorType.Cuda or AcceleratorType.ROCm or AcceleratorType.Metal }) .OrderByDescending(device => device.MemorySize) .FirstOrDefault();

if (preferredDevice is null) { Console.Error.WriteLine( $"No GPU compatible with the compiled {compiledBackend} backend was found."); Console.Error.WriteLine( "Check your GPU driver, or rebuild for its backend with -p:ILGPUBackend=CUDA, ROCm, OpenCL, or Metal."); Environment.ExitCode = 1; return; }

using var accelerator = preferredDevice.CreateAccelerator(context);

Console.WriteLine("Selected accelerator"); accelerator.PrintInformation(Console.Out);

The first filter matches the backend. The second keeps GPU devices. OpenCL needs an extra check because an OpenCL device can be a CPU; its device-type flags tell us which it is. If several GPUs qualify, we pick the one reporting the most memory. That is a simple selection rule, not a claim that it will be the fastest.

The device describes hardware ILGPU found. The accelerator is our working connection to that device: through it we can obtain streams, allocate memory, and launch work. Thinking of it as a handle to the GPU is useful, provided we remember that it owns resources and must be disposed. The using declarations handle that, disposing the accelerator before the context when Main ends.

Run again and check the selected accelerator. On my Mac, this selects the Apple M3 Max through Metal. If your program reports that no compatible GPU was found, compare the compiled backend with the devices listed above it. Correct the backend or driver before going further. We don’t silently fall back to the CPU, because this exercise needs to establish that our kernel actually runs on the GPU.

After printing the selected accelerator, add two ordinary C# arrays and the answer we expect:

var array1 = new float[] { 1.5f, 2.0f, 3.2f }; var array2 = new float[] { 2.1f, 4.2f, 3.0f }; var expected = new float[] { 3.6f, 6.2f, 6.2f };

At index zero we want 1.5 + 2.1; at index one, 2.0 + 4.2; at index two, 3.2 + 3.0. Each answer is independent of the others. That makes this a useful first parallel operation: no invocation has to wait for another invocation’s answer.

These arrays live on the host, in memory managed by .NET. They are one-dimensional because our operation has one index. Later we’ll give flat buffers rows, columns, and other shapes. For now, adding a second dimension would give us another thing to explain without changing the calculation.

We use float, the 32-bit floating-point type. GPU kernel code has restrictions that ordinary C# code doesn’t: we can’t send an arbitrary object graph to the GPU and expect it to run there. ILGPU’s buffer allocations require unmanaged element types, and the backend must support the operations we perform on those types. The float addition we need here is supported across our CUDA, ROCm, OpenCL, and Metal backends.

var stream = accelerator.DefaultStream; using var buffer1 = stream.Allocate1D<float>(array1.Length); using var buffer2 = stream.Allocate1D<float>(array2.Length); using var outputBuffer = stream.Allocate1D<float>(array1.Length);

A stream orders work submitted to the accelerator. We’ll use its default stream throughout this lesson. The accelerator owns that stream; we’re borrowing it. The buffers have their own using declarations and will be disposed before the accelerator.

Notice that allocating the input buffers hasn’t copied the arrays. We have reserved space for three floats in each buffer. Put the upload immediately after the allocations:

buffer1.CopyFromCPU(array1); buffer2.CopyFromCPU(array2);

We don’t upload anything to outputBuffer. Our kernel will write every element before we read it. We also don’t need to allocate a host output array yet; the readback call will give us one.

If you’re consulting the online ILGPU tutorials, this is one place where their examples differ from our pinned revision. They show allocation through the accelerator. Here, Allocate1D belongs to the stream. The allocation methods in the pinned source are the reference for the API we’re using.

Add this method at the top of the Program class, before our other methods:

private static void Kernel( Index1D i, ArrayView<float> input1, ArrayView<float> input2, ArrayView<float> output) { output[i] = input1[i] + input2[i]; }

That assignment is the whole calculation. A kernel is the function we arrange to execute across many GPU invocations. Each invocation receives an index, and this one uses its index to read two values and write their sum.

ArrayView<float> lets the kernel access a buffer’s elements. The view describes existing storage; creating one doesn’t allocate or copy another array. The buffer owns the memory, which is why we keep it alive through execution and readback.

There’s no loop here. We’ll ask ILGPU to launch an invocation for each array element. For our three-element input, the useful indices are zero, one, and two. Those invocations can run independently because each writes a different output element. We make no assumption about their execution order.

Return to Main. Immediately after the two uploads, add:

stream.Launch( (Index1D)array1.Length, i => Kernel(i, buffer1.View, buffer2.View, outputBuffer.View) );

stream.Synchronize();

var result = outputBuffer.GetAsArray1D();

Console.WriteLine("Results"); Console.WriteLine($"Actual: {string.Join(", ", result)}"); Console.WriteLine($"Expected: {string.Join(", ", expected)}");

The first argument to Launch is the extent: how many elements we want to process. The lambda supplies the operation and the views it needs. Although this looks like an ordinary C# lambda call, our build integration gives it a different job.

During the build, ILGPU’s compiler finds the launch, translates the kernel, and generates the launch code. It writes generated files under obj; it doesn’t rewrite our source file. That is why there is no separate call here to compile a kernel through the accelerator, as older ILGPU examples show. On Metal, the build embeds shader source that Metal compiles for the GPU at runtime.

Launching work doesn’t mean the GPU has finished it by the time the next C# statement runs. Synchronize waits for the stream’s work to finish. Then GetAsArray1D reads the output into a managed array that we can inspect on the CPU. We now have an explicit path from our two host arrays, through GPU execution, back to ordinary C# values.

dotnet run --project src/Cradle

After the device information, the result s

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →