GLSL subgroupQuadSwapVertical Explained

The subgroupQuadSwapVertical function in GLSL allows threads within a subgroup to exchange data directly across vertical neighbors within a 2x2 quad without using shared memory. By understanding the quad layout and invocation mapping, developers can use this built-in operation for efficient local spatial calculations, texture filtering, and image-processing kernels.

Quad Layout and Thread Organization

In GLSL subgroup quad operations (typically enabled via the GL_KHR_shader_subgroup_quad extension or Vulkan 1.1+ subgroup features), invocations within a subgroup are partitioned into localized 2x2 grids called quads. Each quad consists of four invocations indexed relative to the quad:

  • Lane 0: Top-left (x=0, y=0)
  • Lane 1: Top-right (x=1, y=0)
  • Lane 2: Bottom-left (x=0, y=1)
  • Lane 3: Bottom-right (x=1, y=1)

What subgroupQuadSwapVertical Does

The subgroupQuadSwapVertical intrinsic swaps data along the vertical axis of the quad. When called, each invocation reads the passed value from its vertical counterpart:

  • Invocation 0 swaps with Invocation 2
  • Invocation 1 swaps with Invocation 3
  • Invocation 2 swaps with Invocation 0
  • Invocation 3 swaps with Invocation 1

If invocation 0 passes value \(A\) and invocation 2 passes value \(C\), invocation 0 will receive \(C\) and invocation 2 will receive \(A\). Simultaneously, invocation 1 (passing \(B\)) and invocation 3 (passing \(D\)) exchange their values so that invocation 1 receives \(D\) and invocation 3 receives \(B\).

Use Cases and Significance

subgroupQuadSwapVertical operates at hardware register speed, bypassing memory writes and thread barriers. Typical use cases include:

  • Finite Difference and Derivatives: Calculating vertical derivatives (\(dF/dy\)) manually in compute shaders where standard texture gradient instructions like dFdy might not be available.
  • Image Filtering: Implementing small convolution kernels (such as Sobel or vertical blur filters) by sharing neighboring pixel values across rows.
  • Quad-Level Reductions: Pairing vertical swaps with horizontal swaps (subgroupQuadSwapHorizontal) to broadcast or reduce data across all four threads in the quad in two operations.

Execution Requirements

For subgroupQuadSwapVertical to return defined results, all invocations within the quad must be active and execute the instruction in uniform control flow. If a thread within the quad is inactive due to divergent branching or bounds checks, the value read from that lane is undefined.