← Wed, Sep 30 digest

Testing WebGPU data layouts with Facet

read article ↗ hn thread ↗

Matt Keeter uses Rust's facet reflection library and naga to write unit tests that automatically verify data layout compatibility between Rust structs and WebGPU compute shaders.

read it The article provides a practical, code-backed solution for catching subtle struct alignment bugs between Rust and WebGPU.

summary

Sharing configuration data between host code and WebGPU compute shaders often introduces subtle layout and padding discrepancies that are painful to debug. To prevent this, the author implements a unit test helper that parses WGSL shaders using naga and cross-references them against Rust types using the facet runtime reflection library. This approach automatically checks field offsets, member sizes, and missing fields across platforms without adding build-script overhead. Commenters also discuss alternative approaches and upcoming WebGPU layout extensions.

key points

  1. Rust structs and WGSL shaders can have mismatched layouts for types like matrices due to padding rules, causing silent bugs or GPU lockups.
  2. By parsing WGSL with naga and inspecting Rust types via facet, unit tests can automatically validate field offsets and sizes at runtime.
  3. The validation approach handles edge cases like trailing runtime-sized arrays by checking boundary offsets against std::mem::size_of.

who should read it

Rust developers writing WebGPU compute shaders or graphics applications.

discussion warm

consensus

Commenters appreciate the practical utility of layout validation and discuss broader alignment headaches in graphics APIs like Vulkan and WebGPU.

pushback

A commenter points out an experimental WebGPU extension that may eventually eliminate these layout discrepancies in browsers.

best comment by flohofwoe ↗

FWIW, there's a WebGPU extension which 'harmonizes' uniform buffer struct layout with other address spaces, but currently it's only implemented in Chromium-based browsers:

Ticket: https://github.com/gpuweb/gpuweb/issues/4973

Caniuse: https://caniuse.com/?search=uniform_buffer_standard_layout

The std140-style layout restrictions are basically a leftover when GPUs used vec4 "register tables" for uniform data.

It introduces a Chromium-supported WebGPU extension designed to harmonize uniform buffer layouts and reduce these exact padding headaches.

Generated by an LLM from the article and thread. Check the sources before relying on it.