A SPIR-V backend for Intel GPUs

TL;DR — Vx now compiles GPU kernels for arch: spirv64 to SPIR-V and runs them on Intel Arc GPUs, through Level Zero and oneMKL. Violet White built almost all of this backend: the Arc A770 machine file, the binary payload, the SPIR-V argument flattener, the dispatch runtime, and the Arc conformance suite. Block, subgroup and lane loops, shared memory, atomics, helper calls, narrow floats, 4-bit integers, math functions and assert all work, and every SPIR-V test also runs on a plain CPU through PoCL. Along the way we hit five problems, such as atomic loads that LLVM 22 wrote as plain loads.

Three weeks ago, the table in The promise of Vx listed Linux with an Intel GPU as "Not yet". Today the same Vx kernel that becomes PTX on NVIDIA and Metal on Apple compiles to SPIR-V and runs on an Intel Arc. Violet White built almost the entire backend as Vx's first community target (#1137).

The same program, another machine file

In Vx, a GPU kernel is a spawn on region with plain for loops across blocks, subgroups and lanes. This program gives each row of 64 floats to a subgroup of 32 lanes. Lane l adds elements l and l + 32, and the subgroup then finds the sum and the largest of those 32 pair sums:

Memory CPU_DRAM {}
Memory HBM {
  within: Memory::CPU_DRAM, capacity: 16 GiB, bandwidth: 560 GB/s, managed: cached, scope: device
}
Memory SMEM {
  within: Memory::HBM, capacity: 64 KiB, managed: explicit, scope: sm
}
Topology Device {
  arch: spirv64,
  levels: [blocks(max_lanes: 1024, memory: cta), subgroups(lanes: 32), lanes(memory: thread)],
  memory: Memory::HBM,
  visible: [Memory::HBM, Memory::SMEM],
  transfer Memory::CPU_DRAM -> Memory::HBM : 31.5 GB/s,
  transfer Memory::HBM -> Memory::CPU_DRAM : 31.5 GB/s,
  transfer Memory::HBM -> Memory::SMEM
}

fn row_sums(
    sums : &mut Tensor<f32, [16], Memory::HBM>,
    peaks : &mut Tensor<f32, [16], Memory::HBM>,
    w : &Tensor<f32, [1024], Memory::HBM>) -> void {
  spawn on(Topology::Device) {
    for rb in 0..4 across blocks {
      let mut part = unsafe { Tensor<f32, [4, 32], Memory::SMEM>::uninit() };
      for s in 0..4 across subgroups {
        for l in 0..32 across lanes {
          let r = rb * 4 + s;
          part[s][l] = w[r * 64 + l] + w[r * 64 + l + 32];
        }
        let t = lanes::sum(&part[s], 32);
        let m = lanes::max(&part[s], 32);
        sums[rb * 4 + s] = t;
        peaks[rb * 4 + s] = m;
      }
    }
  }
  return;
}

fn main() -> i32 {
  let mut hw = Tensor<f32, [1024]>::fill(0.0);
  for i in 0..1024 {
    hw[i] = i as f32;
  }
  let w = transfer(hw, Memory::HBM);
  let mut sums = transfer(Tensor<f32, [16]>::fill(0.0), Memory::HBM);
  let mut peaks = transfer(Tensor<f32, [16]>::fill(0.0), Memory::HBM);
  row_sums(&mut sums, &mut peaks, &w);
  let out = transfer(sums, Memory::CPU_DRAM);
  let big = transfer(peaks, Memory::CPU_DRAM);
  println!("row 0: {}, row 13: {}, peak 13: {}", out[0], out[13], big[13]);
  return 0;
}

It prints row 0: 2016, row 13: 55264, peak 13: 1758.

In a normal program you do not write the Memory and Topology blocks by hand. You pass a machine file on the command line, such as fleet/arc-a770.vx (#1471):

vxc row_sums.vx --host default --machine fleet/arc-a770.vx

--host default says that the program runs on the machine that compiles it. The machine file describes the Intel Arc A770: 16 GiB of GDDR6, a 16 MiB L2 cache, 64 KiB of shared memory, and 32-lane subgroups. It also leaves out one element type:

dtypes: [f32, bf16, f16, i4, u4, i8, u8, i16, u16, i32, u32, i64, u64, bool]

f64 is not in the list, because the Arc A770 has no f64 hardware. In Vx, a missing hardware feature is a compile error, never a silent conversion to f32. Transferring an f64 tensor to the Arc, or building an f64 value inside a spawn on region (#1474), fails with error E6026 before the program runs.

Why kernel SPIR-V, and why two runtimes

SPIR-V is the binary intermediate format that OpenCL, Level Zero and Vulkan drivers read. Intel GPUs take SPIR-V and compile it to native Xe machine code inside the driver.

MLIR has three routes that target SPIR-V or Intel GPUs. Two of them could not compile an ordinary Vx kernel:

We took the third route. Because vxc already links against LLVM 22, it calls the spirv64 target in its own process and needs no external llc tool.

That choice forced one change to the dispatch payload, the record in the program that carries each kernel's metadata and code. PTX and Metal Shading Language are plain text, so vxc packed the payload as key=value strings ending in a zero byte. A binary SPIR-V module has zero bytes, starting in its header. Rather than encode binary as base64 text, #1918 gave the payload a version key (abi=1), a format tag (format=spirv), and a length-prefixed binary section.

On the runtime side, runtime/xpu_dispatch.cpp (#2763) uses both SYCL and Level Zero, for a single reason. Vx sends whole-tensor matrix products (a @ b) to the vendor's BLAS library: cuBLAS on NVIDIA, Metal Performance Shaders on Apple, and oneMKL on Intel. oneMKL takes a sycl::queue. Yet standard SYCL has no public call that loads raw SPIR-V bytes from memory. A SYCL kernel bundle holds only kernels that the SYCL compiler built from the program's own source.

Level Zero is the driver layer underneath SYCL, and it loads raw SPIR-V bytes with zeModuleCreate. So xpu_dispatch.cpp creates an in-order sycl::queue, reads out its native Level Zero context and device with sycl::get_native, and loads each SPIR-V image into that context. The kernels, the Unified Shared Memory allocations, and oneMKL then share one context and one device.

Typed pointers and flat tensor arguments

The first kernel compiled down that route still failed spirv-val, the Khronos validator for SPIR-V modules.

In MLIR, a tensor parameter arrives at a GPU kernel as a memref descriptor. That descriptor is a struct of five fields: an allocated pointer, an aligned pointer, an offset, an array of sizes, and an array of strides. On NVIDIA, PTX holds addresses in untyped 64-bit integer registers, so that struct passes straight through LLVM.

SPIR-V uses typed pointers. Every pointer type in a SPIR-V module names what it points to and its storage class. CrossWorkgroup is device memory, and Workgroup is shared memory. In LLVM 22, all pointers are an untyped ptr. When MLIR lowers a memref struct to LLVM IR, LLVM's SPIR-V backend has to pick a type for the struct's pointer fields and picks i8*. When the kernel puts a float* or i32* tensor pointer into that struct, spirv-val refuses the module:

The Object type (OpTypePointer) does not match the type that results from indexing into the Composite.

Every memref built inside a kernel hit the same wall. That includes loop counters in stack slots, memref.reinterpret_cast row views, and tiles in shared memory.

The fix in src/dialect/SpirvKernelArgs.cpp (#2446) uses a fact about Vx's launch ABI. On the host, runtime/vx_kernel_launch.h never passes a struct to a GPU kernel. It unpacks each tensor of rank r into 3 + 2 * r separate arguments: two pointers, an i64 offset, r sizes, and r strides. So the SPIR-V pipeline rewrites each kernel in five steps before LLVM sees it:

  1. Inline every helper function that the kernel calls (#3757), so tensor parameters of helpers become operations inside the kernel body.
  2. Run mem2reg so scalar stack slots, such as loop counters, become SSA values instead of one-element memrefs.
  3. Turn each Memory::SMEM tile into an LLVM global array in address space 3, which SPIR-V maps to Workgroup storage (#3756).
  4. Expand every tensor parameter of the kernel in place into the flat pointers, offset, sizes and strides of the launch ABI.
  5. Rewrite every load, store and view (memref.reinterpret_cast, extract_strided_metadata, memref.dim) into plain 64-bit integer arithmetic (offset + i * stride) and typed element pointers.

No memref descriptor reaches LLVM, and the host launch code did not change by a line.

Five problems along the way

Getting a small elementwise kernel through spirv-val and onto the Arc A770 was only step one. Compiling the rest of Vx's GPU language uncovered five problems: three bugs in LLVM 22's SPIR-V backend, a gap in standard SPIR-V, and a link problem in vxc.

1. Atomic loads and stores were neither atomic nor ordered. LLVM 22's SPIR-V backend writes an atomic load or store instruction as a plain OpLoad or OpStore. Both the atomicity and the memory order vanish. In one test, block 0 writes 42 and sets a flag with a release store, while block 1 spins on an acquire load of that flag. Because the load was plain, the flag stayed in a register, and on PoCL the loop never ended (#3763). Before serialization, vxc now rewrites each atomic load to an atomicrmw or with 0. It rewrites each atomic store to an atomicrmw xchg and drops the old value. Both become real SPIR-V atomic instructions with their scope and memory order.

2. Narrow integers kept dirty upper bits — even in f32 kernels. SPIR-V has no 4-bit integer type. LLVM 22's SPIR-V backend holds an i4 or u4 value in an 8-bit integer and never masks or sign-extends bit 3. So a sign extension of an i4 read bit 7 instead of bit 3, which turned -8 into 8, and 15u4 + 1u4 produced 16 instead of 0.

The same bug broke an f32 matrix product with no 4-bit types in the source at all. In a subgroup tile multiply with 8 columns, lane l reads column l % 8. LLVM's loop strength reduction rewrote l % 8 as a zero-extension of an i3, which the SPIR-V backend masked with 255 instead of 7. Lanes 8 through 31 read the wrong columns. vxc now runs the SPIR-V target machine with LLVM's codegen optimizations off, leaving optimization to the GPU driver. A pass before serialization widens every 2-to-7-bit integer operation to 8 bits with explicit masks and sign shifts (#3604). On PoCL, 24 of 39 i4 and u4 test programs gave wrong answers before this pass. All 39 match the CPU now.

3. A static map in LLVM 22 gave later kernels duplicate SPIR-V ids. vxc compiles each kernel in a SPIR-V module of its own. That keeps one kernel's shared tiles and printf format strings out of the next kernel's image. Yet on one test program with two kernels, spirv-val rejected about 7% of the compiles with a duplicate-id error.

LLVM 22's SPIR-V backend keeps basic-block ids in a static map keyed by the MachineFunction address. It forgets to clear that map after each module (llvm#160613, fixed in LLVM 23). When a new MachineFunction landed at the heap address of a freed one, its blocks took the old ids and defined them twice. Under LLVM 22, vxc drops the Free MachineFunction pass from the SPIR-V pass manager and never frees that manager (#4095). No two kernels ever get the same address.

4. Operations and types that SPIR-V lacks without extensions. Standard kernel SPIR-V has no bf16, fp8 or fp4 arithmetic, forbids integer multiply and shift on bool, and has no instruction that aborts a running kernel:

Vx featureWhat the SPIR-V pipeline writes
bf16, fp8, fp4 (#3582, #3603)Arithmetic runs in f32 and rounds back to the narrow type, as on the CPU. Memory, phi nodes and select instructions hold bf16 as i16, and 8-bit or 4-bit floats as integers of the same width.
1-bit math on bool (#3580)i1 multiply becomes and, defined shifts and divisions keep the left operand, and min and max become and and or.
f32::exp, tanh, sin and 23 other math methods (#3608)Mapped to OpenCL built-in calls in f32, because Vx's host libm computes in f64 and reads lookup tables.
assert in a kernel (#3610)Adds a hidden pointer to a 4-byte flag. A failed assert prints its message with OpenCL printf and sets the flag with an atomic or. The runtime checks the flag after the wait and stops the program.

5. Linking libsycl broke a Vx function named read. At first, vxc linked the active dispatch library into every compiled binary. When that library was XPU, it pulled in libsycl, whose static initializer runs before main. A CPU-only Vx test that defined its own fn read(...) exported a symbol named read, which replaced libc's read inside libsycl's startup code and crashed. vxc now links the dispatch library only when the program dispatches to a device. It also exports only the kernel entry points (_vx_ciface_*), so a GPU program can define its own read too (#2763).

Running SPIR-V images with and without an Intel GPU

FileCheck and spirv-val check that an image exists and obeys the SPIR-V specification. They cannot check whether the image computes the right numbers.

On the Arc A770, scripts/tools/vx_xpu_conformance.sh runs the same compiled Vx binaries against libvx_xpu_dispatch on the GPU and libvx_x86_dispatch on the CPU. It checks all 14 element types of fleet/arc-a770.vx, reductions, strided transposes, and passing and failing asserts. It also checks 1024×1024 and 8192×8192 matrix products through oneMKL, plus eight threads dispatching at once under ThreadSanitizer. More cases check the library's own decisions. For example, two libraries name their kernel vx_npu_kernel_0, and each call must reach its own kernel.

A second tool, scripts/tools/vx_spirv_run_image.cpp, breaks a launch on purpose. It flips a byte in a stride constant, moves a tensor's base pointer, and passes the wrong number of parameters, and each break must make the check fail. Level Zero does not check how many parameters a caller sets before a launch. So the runtime walks the SPIR-V words of each new image once and counts its OpFunctionParameter instructions.

Most machines do not have an Intel GPU, so we also run the SPIR-V images on the CPU with PoCL (#3731). PoCL is an open-source OpenCL driver that compiles and runs SPIR-V modules on host threads. The integration test tests/integration_test/spirv_images_on_pocl.rs builds a small OpenCL dispatch library. It runs every spirv64 test program twice: once on the host copy, and once on PoCL. Both runs must print the same output. A float from device math may differ from the host's by at most 1e-6 times the larger value. No kernel with a SPIR-V image may run its host copy.

Getting PoCL to run inside the test suite hit two snags of its own:

What works today, and what does not yet

A spawn on region may use something that a SPIR-V image cannot hold, such as a 128-bit integer (#3602). vxc then names the Vx function that holds the region, and gives the reason (#2742). If the region's tensors are in memory the host can read, this is a warning. That region runs on the CPU, and every other kernel in the program still gets its SPIR-V image (#3368, #3603). fleet/arc-a770.vx declares the Arc's memory managed: explicit, which the host cannot read, so there the message is an error and the compile stops. At run time, an error in a kernel names its Vx function and the line of its spawn on (#3806).

Here is where the Intel GPU backend stands today:

The images are standard kernel SPIR-V, so they are not tied to the Arc. PoCL already runs them on a CPU. The next backend on the roadmap is AMD. It will go through MLIR's ROCDL dialect, which sits close to the NVIDIA path.

Acknowledgments

Almost all of the Intel GPU backend is the work of Violet White (LinkedIn, Bluesky). She measured the Intel Arc A770 and wrote its machine file, generalized Vx's address spaces and element-type checks, and designed the binary dispatch payload. She then built the SPIR-V compiler pipeline and argument flattener, wrote the Level Zero and SYCL dispatch library, and checked every path on Arc hardware. Thank you, Violet, for taking Vx's first community backend from an open issue to working hardware.