iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎨

Introduction to WebGPU

に公開

Overview

This is a memo of my personal catch-up on WebGPU, following the documentation at the link below.

https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API

Operating Environment

  • MBA M3 Sequoia 15.6.1
  • Chrome Version 141.0.7390.123 (Official Build) (arm64)

What is WebGPU…?

The successor to WebGL, compatible with modern GPU APIs, supporting general-purpose GPU compute, faster operations, and providing access to more advanced GPU features.

You can actually try out various WebGPU samples published at the link below to see what it can do! (Thank you for the helpful site ✨)

https://compute.toys/

What is WebGL…?

A port of the OpenGL ES 2.0 graphics library to JavaScript. It allows rendering GPU computation results inside a <canvas> element. Shader code must be written in GLSL.

Problems with WebGL

  • Emergence of next-generation native GPU APIs
    • Direct3D 12, Metal, Vulkan
    • OpenGL updates are no longer planned, and the same applies to WebGL, making the new GPU APIs above unusable
  • Cannot handle general-purpose GPU (GPGPU) computations very well
  • The workload of 3D graphics applications will continue to increase

WebGPU addresses these issues.

General Model (1 Device 1 GPU) Diagram

image1.png

※ From MDN documentation

The "Native GPU API / Driver" part in the diagram above corresponds to, for example, Metal on macOS. The WebGPU Adapter handles communication with the Native GPU API.

Accessing the Device

In WebGPU, a logical device is represented by an instance of the GPUDevice object. To access a logical device, you write as follows:

async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU is not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Failed to request WebGPU adapter.");
  }

  const device = await adapter.requestDevice();
  console.log(device);
}

I created the following index.html to actually test this.

Running this on my local machine produced the following results:

--- WebGPU initialization start ---
navigator.gpu found.
GPUAdapter acquired. Number of available features: 18
GPUDevice acquired.
Summary: {
  "limits": {
    "maxTextureDimension2D": 8192,
    "maxBindGroups": 4,
    "maxComputeWorkgroupSizeX": 256,
    "maxComputeWorkgroupSizeY": 256,
    "maxComputeWorkgroupSizeZ": 64
  },
  "supportedFeaturesCount": 1
}
--- Initialization complete ---

Pipelines and Shaders: Structure of WebGPU Applications

Pipeline: A logical structure that contains programmable stages. WebGPU supports two types of pipelines:

  1. Render Pipeline
    • Renders graphics onto a canvas element or offscreen (first draws to a texture for later use)
    • Has two programmable stages:
      1. Vertex Stage: Determines the shape
      2. Fragment Stage: Determines the color
  2. Compute Pipeline
    • Used for general computation; receives data, performs parallel calculations across a specified number of workgroups, and returns results in one or more buffers

Programmable stages are implemented in a Rust-like low-level language called WebGPU Shader Language (WGSL).

Basics of Render Pipeline

Let's try a simple render pipeline example that displays a single triangle on a blue background.

image2.png

https://mdn.github.io/dom-examples/webgpu-render-demo/

The shader code used here is as follows:

const shaders = `
struct VertexOut {
  @builtin(position) position : vec4f,
  @location(0) color : vec4f
}

@vertex
fn vertex_main(@location(0) position: vec4f,
               @location(1) color: vec4f) -> VertexOut
{
  var output : VertexOut;
  output.position = position;
  output.color = color;
  return output;
}

@fragment
fn fragment_main(fragData: VertexOut) -> @location(0) vec4f
{
  return fragData.color;
}
`;

In the shader above, the programmable stages are:

  • Vertex Stage: The part with @vertex
  • Fragment Stage: The part with @fragment

Let's run this.

If there are no errors, the triangle should be displayed.

Using Shader Modules

To use shader code in WebGPU, you need to obtain a GPUShaderModule using GPUDevice.createShaderModule() as follows:

const shaderModule = device.createShaderModule({
  code: shaders,
});

Getting and Configuring the Canvas Context

To set the rendering target to a <canvas> element, we get the <canvas> element and call canvas.getContext("webgpu") to obtain a GPU context (an instance of GPUCanvasContext), then configure it.

      const canvas = document.querySelector('#gpuCanvas');
      const context = canvas.getContext('webgpu');

      context.configure({
        device: device,
        format: navigator.gpu.getPreferredCanvasFormat(),
        alphaMode: 'premultiplied',
      });

Let's look at the parameters of context.configure:

  • device

  • format

    • The format of the texture returned by getCurrentTexture().

    • One of bgra8unorm, rgba8unorm, or rgba16float.

      Format Order Bits per channel Total/px Value type Typical use case
      bgra8unorm B G R A 8-bit 32-bit UNORM (normalizes 0–255 to 0.0–1.0) For screen display. High platform compatibility, often chosen as the default for canvas
      rgba8unorm R G B A 8-bit 32-bit UNORM (same as above) General textures/render targets. UI and standard rendering
      rgba16float R G B A 16-bit 64-bit Half-precision floating point (FP16) HDR, post-processing, accumulation/compute buffers where high dynamic range or precision is needed
  • alphaMode

    • Specifies the effect of the alpha value.
    • opaque: The alpha value is ignored.
    • premultiplied: Color values are already multiplied by the alpha value.

Triangle Data

The triangle stores 8 data items per vertex (position X, Y, Z, W and color R, G, B, A).

      const vertices = new Float32Array([
        0.0, 0.6, 0, 1, 1, 0, 0, 1, -0.5, -0.6, 0, 1, 0, 1, 0, 1, 0.5, -0.6, 0,
        1, 0, 0, 1, 1,
      ]);

This data must be stored in a GPUBuffer. A GPUBuffer can be created with GPUDevice.createBuffer().

        const vertexBuffer = device.createBuffer({
          size: vertices.byteLength,
          usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
        });

        device.queue.writeBuffer(vertexBuffer, 0, vertices, 0, vertices.length);

You can check the possible values for usage here. In this case, it seems to be set to vertex data and buffer can be used as a destination for copy/write operations.

Next, we write the data to the GPUBuffer using writeBuffer.

Defining and Creating the Render Pipeline

Now we actually create the pipeline to be used for rendering.

        const vertexBuffers = [
          {
            attributes: [
              {
                shaderLocation: 0, // Position X, Y, Z, W
                offset: 0,
                format: 'float32x4', // Corresponds to WGSL vec4<f32> type
              },
              {
                shaderLocation: 1, // Color R, G, B, A
                offset: 16,
                format: 'float32x4',
              },
            ],
            arrayStride: 32, // Total bytes per vertex
            stepMode: 'vertex',
          },
        ];

        const pipelineDescriptor = {
          vertex: {
            module: shaderModule,
            entryPoint: 'vertex_main',
            buffers: vertexBuffers,
          },
          fragment: {
            module: shaderModule,
            entryPoint: 'fragment_main',
            targets: [
              {
                format: navigator.gpu.getPreferredCanvasFormat(),
              },
            ],
          },
          primitive: {
            topology: 'triangle-list',
          },
          layout: 'auto',
        };

        const renderPipeline = device.createRenderPipeline(pipelineDescriptor);

In vertexBuffers, we define the attributes of the triangle vertex data. In pipelineDescriptor, we specify the module for the vertex stage, the entry point in the shader, and the previously created vertexBuffers. Similarly, for the fragment stage, we specify the module, entry point, and format.

  • Parameters of pipelineDescriptor
    • primitive
      • An object describing how the pipeline constructs primitives from its vertex inputs and rasterizes them.
        • topology
          • An enumerated value that determines how to construct primitives from the provided vertices.
            • line-list: Each consecutive pair of two vertices defines a line primitive.
            • line-strip: Each vertex after the first defines a line primitive between it and the previous vertex.
            • point-list: Each vertex defines a point primitive.
            • triangle-list: Each consecutive group of three vertices defines a triangle primitive.
            • triangle-strip: Each vertex after the first two defines a triangle primitive between it and the two previous vertices.
          • If omitted, the default topology is triangle-list.
        • layout
          • Defines the layout (structure, purpose, type) of all GPU resources (buffers, textures, etc.) used during pipeline execution.
            • GPUPipelineLayout: Allows the GPU to figure out how to run the pipeline most efficiently ahead of time.
            • "auto": Makes the pipeline generate an implicit bind group layout based on the bindings defined in the shader code.
        • vertex
          • An object describing the pipeline's vertex shader entry point and its input buffer layout.
        • fragment
          • An object describing the pipeline's fragment shader entry point and its output colors.

Finally, we create the render pipeline with createRenderPipeline.

Executing a Render Pass

Now that everything is ready, we will draw to the <canvas>. To encode commands to be sent to the GPU, we need to create a GPUCommandEncoder.

const commandEncoder = device.createCommandEncoder();

Next, call GPUCommandEncoder.beginRenderPass() to start a render pass. We need to define the required property renderPassDescriptor.

const clearColor = { r: 0.0, g: 0.5, b: 1.0, a: 1.0 };

const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear", // After loading, "clear" to the specified color before any drawing
      storeOp: "store",
      view: context.getCurrentTexture().createView(), // Create a new view from the canvas
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

The structure of colorAttachments is defined here.

  • clearValue
    • The color value to clear the view texture to before the render pass executes.
    • This value is ignored if loadOp is not set to "clear".
    • Accepts an array or object representing the four color components (r, g, b, a) in decimal form.
  • loadOp
    • Sets the load behavior. Choose one of the following:
      1. clear
        1. Clears with the clearValue.
      2. load
        1. Loads the existing values into the render pass.
  • storeOp
    • The store operation to perform on the view after the render pass execution.
      1. discard
        1. Discards the result values of the render pass.
      2. store
        1. Stores the result values of the render pass.
  • view
    • The output destination.

Finally, execute the drawing.

passEncoder.setPipeline(renderPipeline); // Set the pipeline to be used for this render pass
passEncoder.setVertexBuffer(0, vertexBuffer); // Set the data source to be passed to the pipeline for rendering
passEncoder.draw(3); // Execute drawing. Pass the number of vertices: 3
passEncoder.end(); // Mark the end of the render pass command list

device.queue.submit([commandEncoder.finish()]); // Add commands to the queue to be sent to the GPU

We have now gone through a complete basic render pipeline process. A rough diagram would look like this 👇 (Please correct me if I'm wrong).

image3.png

Compute Pipeline Basics

The following demo calculates a value on the GPU and outputs the result to the console log.

https://mdn.github.io/dom-examples/webgpu-compute-demo/

image4.png

The shader code used here is as follows:

const BUFFER_SIZE = 1000;

const shader = `
@group(0) @binding(0)
var<storage, read_write> output: array<f32>;

@compute @workgroup_size(64)
fn main(
  @builtin(global_invocation_id)
  global_id : vec3u,

  @builtin(local_invocation_id)
  local_id : vec3u,
) {
  // Protect against accessing outside the buffer bounds
  if (global_id.x >= ${BUFFER_SIZE}) {
    return;
  }

  output[global_id.x] =
    f32(global_id.x) * 1000. + f32(local_id.x);
}
`;

Unlike the render pipeline, this one has only a single @compute stage. Let's run it.

The computation results should be output.

Creating Buffers for Data

To handle data, we create two types of GPUBuffer:

  1. output buffer for fast GPU write of computation results.
  2. stagingBuffer to copy the output contents and map them for JavaScript access.
const output = device.createBuffer({
  size: BUFFER_SIZE,
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
});

const stagingBuffer = device.createBuffer({
  size: BUFFER_SIZE,
  usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
  • GPUBufferUsage.STORAGE
    • Allows the buffer to be used as a storage area on the GPU.
  • GPUBufferUsage.COPY_SRC
    • The buffer can be used as the source of a copy operation.
  • GPUBufferUsage.MAP_READ
    • Makes the GPU memory area mappable for CPU access.
  • GPUBufferUsage.COPY_DST
    • The buffer can be used as a destination for copy/write operations.

Creating a Bind Group Layout

When creating a pipeline, you need to specify the bind groups it will use. To do this, first create a GPUBindGroupLayout as a template that the bind group will follow.

const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.COMPUTE,
      buffer: {
        type: "storage",
      },
    },
  ],
});

The binding: 0 above links to the corresponding binding number @binding(0) in the shader code. It allows access to a single memory buffer defined with a purpose of storage, usable in the computer stage of the pipeline.

Next, create a GPUBindGroup as follows:

const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    {
      binding: 0,
      resource: {
        buffer: output,
      },
    },
  ],
});

Creating a Compute Pipeline

Create a compute pipeline using GPUDevice.createComputePipeline(). This is done in a similar way to creating a render pipeline.

const computePipeline = device.createComputePipeline({
  layout: device.createPipelineLayout({
    bindGroupLayouts: [bindGroupLayout],
  }),
  compute: {
    module: shaderModule,
    entryPoint: "main",
  },
});

Executing a Compute Pass

Executing a compute pass looks like this:

const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginComputePass();

passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(Math.ceil(BUFFER_SIZE / 64)); // Specify the number of GPU workgroups to use for the computation

passEncoder.end();

GPUDevice.createCommandEncoder() creates a GPUCommandEncoder (an encoder that collects a sequence of GPU commands to be issued to the GPU). Then GPUCommandEncoder.beginComputePass() creates a pass encoder. The pass encoder forms part of the overall encoding process of the GPUCommandEncoder.

GPUComputePassEncoder.dispatchWorkgroups() specifies the number of GPU workgroups to use for the computation.

Reading Results in JavaScript

Finally, we make the computation results written to the stagingBuffer readable and output them.

// Copy the output buffer to the staging buffer
commandEncoder.copyBufferToBuffer(
  output,
  0, // Source offset
  stagingBuffer,
  0, // Destination offset
  BUFFER_SIZE,
);

// Submit the command buffer array to the command queue for execution, ending the frame
device.queue.submit([commandEncoder.finish()]);

// Map the staging buffer to read the results back in JS
await stagingBuffer.mapAsync(
  GPUMapMode.READ,
  0, // Offset
  BUFFER_SIZE, // Size
);

const copyArrayBuffer = stagingBuffer.getMappedRange(0, BUFFER_SIZE);
const data = copyArrayBuffer.slice();
stagingBuffer.unmap();
console.log(new Float32Array(data));

Now that we've seen the compute pipeline process, here is a rough diagram (please correct me if I'm wrong).

image5.png

Summary

This time, I followed the documentation to get a feel for WebGPU. There are many actors (GPUDevice, GPUXXXX…), so it can be easy to get lost, but once you grasp the flow, it doesn't seem too confusing. There's still plenty to explore, so I'll keep trying various things.

Discussion