How to convert pixel formats in a Vulkan compute shader — bit-exact vs Pillow

Every GPU image pipeline starts and ends with format conversion: RGB↔RGBA for the API that insists on 4 channels, RGB→gray for thumbnails, RGB↔YCbCr around JPEG, HSV for color-based filtering. Doing those conversions on the CPU is often the largest remaining cost once decode and resize are on the GPU — expanding a 24 MP image to RGBA alone is ~124 ms on a desktop CPU.

This post is a Vulkan compute shader that does 14 conversions in one dispatch, bit-exact against Pillow’s Image.convert() — and the three non-obvious traps that made “bit-exact” hard.

Full example: p82_pixfmt in VulkanExamples.

Supported conversions

conversionreference
rgb2rgba, rgba2rgbconvert("RGBA"/"RGB")
rgb2bgr, bgr2rgbnumpy [..., ::-1] (PIL has no BGR mode)
rgb2gray, rgba2grayconvert("L")
gray2rgb, gray2rgbaconvert("RGB"/"RGBA")
rgb2ycbcr, ycbcr2rgbconvert("YCbCr"/"RGB")
rgb2hsv, hsv2rgbconvert("HSV"/"RGB")
gray2ycbcr, ycbcr2grayconvert("YCbCr"/"L")

Design: one invocation per output word

Packed layouts (1, 3 or 4 bytes per pixel) don’t align to 32-bit words, so byte-granular writes would need atomics or read-modify-write. Instead each invocation produces one full 4-byte output word, computing the 1-2 pixels whose bytes it covers and extracting just the bytes it needs:

conv.comp
layout(set = 0, binding = 0) readonly buffer In  { uint inBuf[]; };
layout(set = 0, binding = 1) readonly buffer Lut { int  lut[]; };
layout(set = 0, binding = 3) writeonly buffer Out{ uint outBuf[]; };
layout(push_constant) uniform P { uint npx, inComp, outComp, conv; };

void main() {
    uint w = gl_GlobalInvocationID.x;
    if (w * 4u >= npx * outComp) return;
    uint word = 0u;
    for (uint k = 0u; k < 4u; ++k) {
        uint bpos = w * 4u + k;
        if (bpos >= npx * outComp) break;
        uint px = bpos / outComp, ch = bpos - px * outComp;
        uvec3 c = convPx(px);          // full conversion of one pixel
        uint v = (ch == 3u) ? 255u
               : (ch == 0u ? c.x : (ch == 1u ? c.y : c.z));
        word |= v << (k * 8u);
    }
    outBuf[w] = word;
}

A boundary pixel gets computed twice (~25% redundant work on 3-byte outputs) — far cheaper than atomics, and it keeps both sides packed: the input goes up as raw bytes and the output is written directly as the final byte stream, no CPU repack anywhere.

The three traps

1. Vulkan fp32 division is 2.5 ULP — and RADV uses reciprocal-multiply

PIL computes HSV saturation as a plain C division, which is correctly rounded. In a shader, 246.0 / 246.0 returned 0.99999994 on RADV: the driver lowers OpFDiv to reciprocal + multiply, which the Vulkan spec permits (division must only be within 2.5 ULP). That single ULP made int(s * 255.0) return 254 instead of 255.

The fix is 64-bit integer long division — exact by construction:

conv.comp
float idivRN(uint a, uint b) {          // correctly-rounded fp32 of a/b
    uint64_t num = uint64_t(a) << 48u;
    uint64_t q = num / uint64_t(b);
    uint64_t rem = num - q * uint64_t(b);
    int sh = int(findMSB(q)) - 23;
    uint m;
    if (sh <= 0) {
        m = uint(q);
        uint64_t twice = rem * 2u;
        if (twice > uint64_t(b) ||
            (twice == uint64_t(b) && (m & 1u) != 0u)) m += 1u;
        return float(m) * exp2(-48.0);
    }
    m = uint(q >> uint(sh));
    uint64_t lost = q & ((uint64_t(1) << uint(sh)) - 1u);
    uint64_t halfway = uint64_t(1) << uint(sh - 1);
    if (lost > halfway ||
        (lost == halfway && (rem > 0u || (m & 1u) != 0u)))
        m += 1u;
    return float(m) * exp2(float(sh - 48));
}

(48 fractional bits guarantee ≥25 significant bits for any ratio of 16-bit inputs; rem carries the sticky bit for round-to-even.)

2. The optimizer deletes intermediate float roundings

PIL’s HSV code stores intermediates in float but does the final scaling in double:

libImaging/Convert.c
float h = fmod((h / 6.0 + 1.0), 1.0);   // stored to float — rounded
uh = (UINT8)CLIP8((int)(h * 255.0));    // promoted back to double

The shader compiler sees float(...) followed by double(...) and folds the pair away — the value is never actually rounded to 24 bits, so h * 255.0 came out 169.9999… → 169 instead of 170. A bit-cast round-trip is opaque to that optimization and forces the rounding:

conv.comp
float fr(float x) { return uintBitsToFloat(floatBitsToUint(x)); }

3. Fast-math folds fma residuals to zero

Computing the exact guard bits of trunc(x*255) is textbook:

conv.comp
float hi = x * 255.0;
float err = fma(x, 255.0, -hi);   // exact residual...

…except that fma(x, c, -x*c) is algebraically zero, and with fast-math flags the compiler may assume exactly that — err becomes 0 and the last bit is lost. Anything expressed in FP is fair game; integer mantissa arithmetic is not:

conv.comp
int mul255trunc(float x) {          // exact trunc(x*255), x in [0,1]
    if (!(x > 0.0)) return 0;
    uint bits = floatBitsToUint(x);
    int e = int((bits >> 23) & 0xFFu) - 150;   // exponent of mantissa lsb
    uint64_t M = uint64_t((bits & 0x7FFFFFu) | 0x800000u);
    uint64_t prod = M * 255u;                  // exact, M <= 2^24
    if (e >= 0) return int(prod << uint(e));
    return int(prod >> uint(-e));
}

The same trick computes x/6 (divide the 24-bit mantissa by 3, rem == 2 rounds the last bit up).

YCbCr: Pillow’s exact tables

PIL’s YCbCr conversion is JFIF with INT16 lookup tables at SCALE = 6:

libImaging/ConvertYCbCr.c
y  = (Y_R[r]  + Y_G[g]  + Y_B[b])  >> SCALE;
cb = ((Cb_R[r] + Cb_G[g] + Cb_B[b]) >> SCALE) + 128;

The tables are (int)(coef * 64 * i + 0.5) — note the +0.5 before a truncating cast, which is round-half-up for positives but asymmetric for negatives. Regenerating them on the host with that exact expression reproduces Pillow’s embedded tables bit-for-bit (verified over all 256 entries), and the shader then needs just three loads and two adds per pixel.

Verification

check.py runs all 14 conversions on noise + gradient images at five sizes (including 1×1 and a 2049×3 strip). Noise matters: it exercises every one of the 256 LUT entries and every HSV sector.

check.py output
70 pass, 0 fail (ALL BIT-EXACT)

Performance

RADV/Renoir iGPU, 6000×4000 RGB (24 MP), end-to-end including the 72 MB upload and readback:

conversionGPUPIL
rgb2rgba104 ms135 ms1.3x
rgb2gray51 ms38 msPIL wins — its L convert is hand-SIMD
rgb2ycbcr99 ms225 ms2.3x
rgb2hsv424 ms701 ms1.7x

The honest reading: for trivial per-pixel work the transfer dominates and PIL’s hand-vectorized C is competitive. The GPU wins where the conversion is expensive (YCbCr, HSV) — and, more importantly, where the data is already on the GPU. Chained after a GPU JPEG decoder or before a GPU resizer, the transfer disappears and only the dispatch remains.

Takeaways

  • If you need bit-exactness with CPU reference code on a GPU: audit division (2.5 ULP!), double-rounding (compilers remove intermediate float stores), and fast-math (algebraic identities silently break error-compensation tricks).
  • Integer mantissa arithmetic is the reliable substrate: shifts and multiplies can’t be “optimized” into different rounding.
  • When the reference library uses lookup tables, embed or regenerate the tables — don’t recompute the math in floating point.

Check out similar posts by category: C++ Vulkan Image Processing