From bcedb0697cc122e84b2589bbf18b9910cca6b6ff Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:03:45 -0500 Subject: [PATCH 01/15] Frame generation (D3D12): tiled/fused pre-net2, batched FP16 conversion, and tap-pipelined net1/net2 WMMAs (-53.1% Preset C 2x, -49.5% Preset A 2x, 116/116 exact) --- clean/dx12/hlsl/fg_fp16.hlsli | 14 + clean/dx12/hlsl/fg_full.hlsli | 55 +- clean/dx12/hlsl/fg_lite_common.hlsli | 27 +- clean/dx12/hlsl/fg_net2_fast.hlsli | 88 ++ clean/dx12/kernels/fg_exec_io.hlsl | 79 +- clean/dx12/kernels/fg_full_blend.hlsl | 109 ++- clean/dx12/kernels/fg_lite_blend.hlsl | 6 +- clean/dx12/kernels/fg_lite_g.hlsl | 59 +- clean/dx12/kernels/fg_lite_menu.hlsl | 2 +- clean/dx12/kernels/fg_lite_net1io.hlsl | 72 +- clean/dx12/kernels/fg_lite_p2c.hlsl | 185 +++- clean/dx12/kernels/fg_lite_r3.hlsl | 465 ++++++++-- clean/dx12/kernels/fg_lite_r4.hlsl | 27 +- clean/dx12/kernels/fg_mconv.hlsl | 256 ++++-- clean/dx12/kernels/fg_mpair.hlsl | 215 +++-- clean/dx12/kernels/fg_net2_mconv.hlsl | 438 ++++++++-- clean/dx12/kernels/fg_net2_merge_pixels.hlsl | 27 + clean/dx12/kernels/fg_net2_upwarp.hlsl | 21 +- clean/dx12/kernels/fg_out_pull.hlsl | 224 +++-- clean/dx12/kernels/fg_out_push.hlsl | 16 +- clean/fg/proxy/win32/fg_asi_session.cpp | 3 +- clean/fg/runner/fg_net2_mma.py | 363 ++++++-- clean/fg/runtime/fg_d3d12_executor.cpp | 855 +++++++++++++++---- clean/fg/runtime/fg_d3d12_executor.h | 47 +- clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 646 +++++++++++++- 25 files changed, 3536 insertions(+), 763 deletions(-) create mode 100644 clean/dx12/hlsl/fg_fp16.hlsli create mode 100644 clean/dx12/kernels/fg_net2_merge_pixels.hlsl diff --git a/clean/dx12/hlsl/fg_fp16.hlsli b/clean/dx12/hlsl/fg_fp16.hlsli new file mode 100644 index 00000000..c1399133 --- /dev/null +++ b/clean/dx12/hlsl/fg_fp16.hlsli @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT +#pragma once + +static uint fg_fp16_zero; +#define FG_FP16_SETUP() (WG_SETUP(), fg_fp16_zero = wg_grid_ >> 31) + +// Driver-channel FP32 to FP16 RNE. The opaque zero keeps the driver from folding the producing +// FP32 operation into a mixed-precision instruction and losing its separate FP32 rounding. +uint fg_f2h(float value) +{ + return wg_ags_call(0x1cu, 0u, 1u, asuint(value) ^ fg_fp16_zero, 0u) & 0xffffu; +} + +uint fg_pack_h2(float x, float y) { return fg_f2h(x) | (fg_f2h(y) << 16); } diff --git a/clean/dx12/hlsl/fg_full.hlsli b/clean/dx12/hlsl/fg_full.hlsli index b01d7604..fab816a9 100644 --- a/clean/dx12/hlsl/fg_full.hlsli +++ b/clean/dx12/hlsl/fg_full.hlsli @@ -3,7 +3,7 @@ // fg_out_pull.hlsl, fg_out_push.hlsl, fg_distortion.hlsl), with the bits of clean/fg/reference/stages_full.py. // // - Images live in the arena, row-major: 4 x float16 = 8 bytes per texel (r | g << 16, b | a << 16), 2 x float16 = 4 -// bytes, 1 x float16 = 2 bytes, 2 x float32 = 8 bytes; float16 is written with wg_f2h (nearest even). +// bytes, 1 x float16 = 2 bytes, 2 x float32 = 8 bytes; float16 is written with fg_f2h (nearest even). // - The reference's approximate division is wg_div (IEEE); float -> int is (int) (truncate, saturate, NaN -> 0). // - Bilinear reads by hand (fgf_tap / fgf_mix): i = floor(t), f = t - i, taps i and i + 1 clamped to the image, weights // (1 - fx)(1 - fy), fx (1 - fy), fy (1 - fx), fx fy, value fma(w11, c11, fma(w01, c01, fma(w00, c00, w10 c10))). @@ -13,9 +13,10 @@ // 1, 2, 4, ... sums pairs in x, then y, at every scale (the reference's block_sums order). // The including file includes wg_platform.hlsli first and starts its kernel with FGF_SETUP(). #pragma once +#include "fg_fp16.hlsli" static uint fgf_z_; // an opaque zero: wg_grid_ >> 31 (a grid never has 2^31 workgroups) -#define FGF_SETUP() (WG_SETUP(), fgf_z_ = wg_grid_ >> 31) +#define FGF_SETUP() (FG_FP16_SETUP(), fgf_z_ = wg_grid_ >> 31) float fgf_opq(float x) { return asfloat(asuint(x) ^ fgf_z_); } float3 fgf_opq3(float3 x) { return asfloat(asuint(x) ^ fgf_z_); } @@ -23,6 +24,30 @@ float fgf_zero() { return asfloat(fgf_z_); } float fgf_sat(float x) { return min(max(x, 0.0f), 1.0f); } float3 fgf_sat3(float3 x) { return min(max(x, 0.0f), 1.0f); } +// The refinement in wg_div without exponent normalization. Use it for a positive +// normal divisor and finite operands in the range needed by the Full path. +float fgf_div_reciprocal(float b) +{ + const float y = rcp(b); + return mad(mad(-b, y, 1.0f), y, y); +} + +float3 fgf_div_normal3(float3 a, float b, float y) +{ + float3 q = a * y; + q = mad(mad(-b, q, a), y, q); + return mad(mad(-b, q, a), y, q); +} + +float fgf_pixel_centre(int i, int n) +{ + const float a = (float)i + 0.5f, b = (float)n; + const float y = fgf_div_reciprocal(b); + float q = a * y; + q = mad(mad(-b, q, a), y, q); + return fgf_sat(mad(mad(-b, q, a), y, q)); +} + // sat((i + 0.5) / n): the normalized centre of pixel i of an n-pixel axis float fgf_centre(int i, int n) { return fgf_sat(wg_div((float)i + 0.5f, (float)n)); } @@ -40,9 +65,23 @@ float4 fgf_ld4h(uint p, int i) } float2 fgf_ld2h(uint p, int i) { const uint d = wg_ld32(p, (uint)i * 4u); return float2(wg_h2f_lo(d), wg_h2f_hi(d)); } float fgf_ld1h(uint p, int i) { return wg_h2f(wg_ld16(p, (uint)i * 2u)); } -void fgf_st4h(uint p, int i, float4 v) { wg_st64(p, (uint)i * 8u, uint2(wg_pack_h2(v.x, v.y), wg_pack_h2(v.z, v.w))); } -void fgf_st2h(uint p, int i, float2 v) { wg_st32(p, (uint)i * 4u, wg_pack_h2(v.x, v.y)); } -void fgf_st1h(uint p, int i, float v) { wg_st16(p, (uint)i * 2u, wg_f2h(v)); } +void fgf_st4h(uint p, int i, float4 v) { wg_st64(p, (uint)i * 8u, uint2(fg_pack_h2(v.x, v.y), fg_pack_h2(v.z, v.w))); } +void fgf_st2h(uint p, int i, float2 v) { wg_st32(p, (uint)i * 4u, fg_pack_h2(v.x, v.y)); } +void fgf_st1h(uint p, int i, float v) { wg_st16(p, (uint)i * 2u, fg_f2h(v)); } + +// Adjacent Morton lanes cover an aligned horizontal pair when the row pitch is even. +// Call with the full wave active, including lanes outside the frame. +void fgf_store_morton_flag(uint p, int x, int y, int w, int h, bool flag) +{ + const uint bits = flag ? 0x3c00u : 0u; + if ((w & 1) == 0 && (p & 3u) == 0u) { + const uint other = QuadReadAcrossX(bits); + if ((x & 1) == 0 && x < w && y < h) + wg_st32(p, (uint)(y * w + x) * 2u, bits | (other << 16)); + } else if (x < w && y < h) { + wg_st16(p, (uint)(y * w + x) * 2u, bits); + } +} // ---- bilinear reads --------------------------------------------------------------------------------------------------- struct FgfTap { int i00, i10, i01, i11; float w00, w10, w01, w11; }; @@ -53,9 +92,9 @@ FgfTap fgf_tap(float tx, float ty, int W, int H) FgfTap t; const float x0f = floor(tx), y0f = floor(ty); const float fx = tx - x0f, fy = ty - y0f; - const int xi = (int)x0f, yi = (int)y0f; - const int x0 = clamp(xi, 0, W - 1), x1 = clamp(xi, -1, W - 2) + 1; - const int y0 = clamp(yi, 0, H - 1), y1 = clamp(yi, -1, H - 2) + 1; + const int xi = clamp((int)x0f, -1, W - 1), yi = clamp((int)y0f, -1, H - 1); + const int x0 = max(xi, 0), x1 = min(xi + 1, W - 1); + const int y0 = max(yi, 0), y1 = min(yi + 1, H - 1); t.i00 = y0 * W + x0; t.i10 = y0 * W + x1; t.i01 = y1 * W + x0; t.i11 = y1 * W + x1; const float gx = 1.0f - fx, gy = 1.0f - fy; t.w00 = fgf_opq(gx * gy); diff --git a/clean/dx12/hlsl/fg_lite_common.hlsli b/clean/dx12/hlsl/fg_lite_common.hlsli index f1d3eb59..1d118635 100644 --- a/clean/dx12/hlsl/fg_lite_common.hlsli +++ b/clean/dx12/hlsl/fg_lite_common.hlsli @@ -12,9 +12,10 @@ // The driver's compiler regroups chains of operations with constant or uniform terms (clean/dx12/README.md "Driver // exceptions"); fg_opq() passes a value through an integer xor with a zero it cannot see, which cuts such a chain. #pragma once +#include "fg_fp16.hlsli" static uint fg_z_; // 0 at run time (the grid size is below 2^31), unknown to the compiler -#define FG_SETUP() (WG_SETUP(), fg_z_ = wg_grid_ >> 31) +#define FG_SETUP() (FG_FP16_SETUP(), fg_z_ = wg_grid_ >> 31) float fg_opq(float x) { return asfloat(asuint(x) ^ fg_z_); } // a * b exactly as one rounded product, as an fma with an opaque -0: neither regrouped nor fused @@ -39,6 +40,18 @@ float fg_sq(float x, float y) { return mad(x, x, fg_mul(y, y)); } // u = sat((i + 0.5) / n), approximate division float fg_centre(uint i, uint n) { return fg_sat(fg_mul((float)i + 0.5f, fg_rcp((float)n))); } +// Remap the existing 256-thread linear dispatch when the frame fits 32 x 8 tiles. +uint2 fg_lite_tile_pixel(uint idx, uint w, uint h) +{ + if ((w & 31u) == 0u && (h & 7u) == 0u) { + const uint tile = wg_block_id(), tiles_x = w >> 5u, lane = wg_lane_id(); + const uint ty = tile / tiles_x; + return uint2(((tile - ty * tiles_x) << 5u) + (lane & 31u), (ty << 3u) + (lane >> 5u)); + } + const uint y = idx / w; + return uint2(idx - y * w, y); +} + // 2^y: the coefficients are stages_common.EX2_COEFFS (this project's least-squares fit of 2^f on [0, 1]) float fg_ex2(float y) { @@ -90,17 +103,17 @@ float4 fg_texel(uint base, uint kind, uint idx) return float4(asfloat(wg_ld32(base, idx * 4u)), 0.0f, 0.0f, 0.0f); } -void fg_st_h1(uint base, uint idx, float a) { wg_st16(base, idx * 2u, wg_f2h(a)); } -void fg_st_h2(uint base, uint idx, float a, float b) { wg_st32(base, idx * 4u, wg_f2h(a) | (wg_f2h(b) << 16)); } +void fg_st_h1(uint base, uint idx, float a) { wg_st16(base, idx * 2u, fg_f2h(a)); } +void fg_st_h2(uint base, uint idx, float a, float b) { wg_st32(base, idx * 4u, fg_pack_h2(a, b)); } void fg_st_h3(uint base, uint idx, float3 a) { - wg_st16(base, idx * 6u, wg_f2h(a.x)); - wg_st16(base, idx * 6u + 2u, wg_f2h(a.y)); - wg_st16(base, idx * 6u + 4u, wg_f2h(a.z)); + wg_st16(base, idx * 6u, fg_f2h(a.x)); + wg_st16(base, idx * 6u + 2u, fg_f2h(a.y)); + wg_st16(base, idx * 6u + 4u, fg_f2h(a.z)); } void fg_st_h4(uint base, uint idx, float4 a) { - wg_st64(base, idx * 8u, uint2(wg_f2h(a.x) | (wg_f2h(a.y) << 16), wg_f2h(a.z) | (wg_f2h(a.w) << 16))); + wg_st64(base, idx * 8u, uint2(fg_pack_h2(a.x, a.y), fg_pack_h2(a.z, a.w))); } // integer read at (x, y), clamped diff --git a/clean/dx12/hlsl/fg_net2_fast.hlsli b/clean/dx12/hlsl/fg_net2_fast.hlsli index 7ae055cd..46139362 100644 --- a/clean/dx12/hlsl/fg_net2_fast.hlsli +++ b/clean/dx12/hlsl/fg_net2_fast.hlsli @@ -69,9 +69,26 @@ uint4 fg_fma8v(float w[8], uint4 p, uint4 t) [unroll] for (uint i = 0; i < 8; ++i) m[i] = fg_sum_odd(w[i] * wg_h2f(fg_half(p, i)), wg_h2f(fg_half(t, i))); return fg_cvt8(m); } +#if FG_NATIVE_LEAKY +uint fg_leaky2(uint packed) +{ + const half2 slope = asfloat16((uint16_t)FG2_SLOPE16); + const half2 negzero = asfloat16((uint16_t)(0x8000u | fg_opq0())); + const uint scaled = wg_h2_bits(mad(slope, wg_as_h2(packed), negzero)); + const uint lo = packed & 0xffffu, hi = packed >> 16; + const uint mask = select(lo > 0x8000u && lo <= 0xfc00u, 0xffffu, 0u) | + select(hi > 0x8000u && hi <= 0xfc00u, 0xffff0000u, 0u); + return (packed & ~mask) | (scaled & mask); +} +#endif + // fg2_leaky on 8 values: max(h(s v), v) by the keys (NaN unchanged) uint4 fg_leaky8(uint4 v) { +#if FG_NATIVE_LEAKY + // For a negative number the slope product wins. Zeros, positives and NaNs keep their bits. + return uint4(fg_leaky2(v.x), fg_leaky2(v.y), fg_leaky2(v.z), fg_leaky2(v.w)); +#else const uint4 t = fg_mul8(wg_h2f(FG2_SLOPE16), v); uint r[8]; [unroll] for (uint i = 0; i < 8; ++i) { @@ -79,6 +96,77 @@ uint4 fg_leaky8(uint4 v) r[i] = select(fg_is_nan16(hv) != 0u, hv, select(fg_key16(ht) > fg_key16(hv), ht, hv)); } return fg_pack8(r); +#endif +} + +#if FG_NATIVE_UP || FG_NATIVE_POST +bool fg_nonfinite2(uint p) +{ + return or((p & 0x7c00u) == 0x7c00u, (p & 0x7c000000u) == 0x7c000000u); +} + +bool fg_nonfinite8(uint4 p) +{ + return or(or(fg_nonfinite2(p.x), fg_nonfinite2(p.y)), or(fg_nonfinite2(p.z), fg_nonfinite2(p.w))); +} + +#endif + +#if FG_NATIVE_POST +uint4 fg_fma8_post(uint wbits, uint4 p, uint4 t) +{ + if (!WaveActiveAnyTrue(fg_nonfinite8(p) || fg_nonfinite8(t) || fg_nonfinite2(wbits))) { + const half2 w = asfloat16((uint16_t)wbits); + return uint4(wg_h2_bits(mad(w, wg_as_h2(p.x), wg_as_h2(t.x))), + wg_h2_bits(mad(w, wg_as_h2(p.y), wg_as_h2(t.y))), + wg_h2_bits(mad(w, wg_as_h2(p.z), wg_as_h2(t.z))), + wg_h2_bits(mad(w, wg_as_h2(p.w), wg_as_h2(t.w)))); + } + return fg_fma8(wg_h2f(wbits), p, t); +} +#endif + +#if FG_JOINED_POST +uint4 fg_fma8_heads(uint wbits, uint4 p, uint4 t) +{ +#if FG_NATIVE_POST + if (!WaveActiveAnyTrue(fg_nonfinite8(p) || fg_nonfinite8(t) || fg_nonfinite2(wbits))) { + const half2 w = asfloat16((uint16_t)wbits); + const half2 one = asfloat16((uint16_t)FG2_ONE16); + return uint4(wg_h2_bits(mad(w, wg_as_h2(p.x), wg_as_h2(t.x))), + wg_h2_bits(mad(w, wg_as_h2(p.y), wg_as_h2(t.y))), + wg_h2_bits(mad(one, wg_as_h2(p.z), wg_as_h2(t.z))), + wg_h2_bits(mad(one, wg_as_h2(p.w), wg_as_h2(t.w)))); + } +#endif + float weights[8]; + [unroll] for (int i = 0; i < 8; ++i) weights[i] = i < 4 ? wg_h2f(wbits) : 1.0f; + return fg_fma8v(weights, p, t); +} +#endif + +#if FG_NATIVE_UP +uint fg_up_axis2(half2 w0, half2 w1, half2 nz, uint p0, uint p1) +{ + const half2 t = mad(w0, wg_as_h2(p0), nz); + return wg_h2_bits(mad(w1, wg_as_h2(p1), t)); +} +#endif + +// One axis of net2's 2x half-pixel upsample, with the same two float16 roundings as fg_net2_up2. +uint4 fg_up_axis8(Fg2Tap tap, uint4 p0, uint4 p1) +{ +#if FG_NATIVE_UP + // Preserve FP32 NaN propagation in the exceptional case. Otherwise the two FP16 fused instructions + // reproduce the same roundings. Using -0 in the first FMA preserves the sign of a zero product. + if (!WaveActiveAnyTrue(fg_nonfinite8(p0) || fg_nonfinite8(p1))) { + const half2 w0 = asfloat16((uint16_t)tap.w0), w1 = asfloat16((uint16_t)tap.w1); + const half2 nz = asfloat16((uint16_t)(0x8000u | fg_opq0())); + return uint4(fg_up_axis2(w0, w1, nz, p0.x, p1.x), fg_up_axis2(w0, w1, nz, p0.y, p1.y), + fg_up_axis2(w0, w1, nz, p0.z, p1.z), fg_up_axis2(w0, w1, nz, p0.w, p1.w)); + } +#endif + return fg_fma8(wg_h2f(tap.w1), p1, fg_mul8(wg_h2f(tap.w0), p0)); } // net2's 2x half-pixel upsample (fg_net2_up2's bits) of 8 values at output (ox, oy) from q00 = (y0, x0), q01 = diff --git a/clean/dx12/kernels/fg_exec_io.hlsl b/clean/dx12/kernels/fg_exec_io.hlsl index 09782c1b..0f65786e 100644 --- a/clean/dx12/kernels/fg_exec_io.hlsl +++ b/clean/dx12/kernels/fg_exec_io.hlsl @@ -5,7 +5,7 @@ // fg_exec_capture: one lane per texel of a game texture (mip 0, read through the shader resource view at t0 in the // executor's descriptor table): dst[y * tw + x] := the texel as the arena image kind the stage kernels read // (clean/dx12/hlsl/fg_lite_common.hlsli): kind 4 = float16 x 4, kind 1 = float16 (channel 0), kind 5 = float32 x 2, -// kind 6 = float32 (channel 0). Float16 values are rounded to nearest even (wg_f2h), so a float16 texture is copied +// kind 6 = float32 (channel 0). Float16 values are rounded to nearest even (fg_f2h), so a float16 texture is copied // bit for bit and an 8 / 10-bit UNORM texture keeps every code (its float16 value converts back exactly). // fg_exec_pack: one lane per pixel of a w x h float16 x 4 image (row stride sstride texels) into rows of dpitch bytes in // a presenter slot's format: fmt 0 = R16G16B16A16_FLOAT (the bits), 1 = R8G8B8A8_UNORM, 2 = B8G8R8A8_UNORM, @@ -13,7 +13,9 @@ // // @wg-kernel fg_exec_capture co=- block=256 wave=32 args=p,u,u,u defines=FGX_K=1 // @wg-kernel fg_exec_pack co=- block=256 wave=32 args=p,u,p,u,u,u,u defines=FGX_K=2 +// @wg-kernel fg_exec_pack_pairs co=- entry=fg_exec_pack block=256 wave=32 args=p,u,p,u,u,u,u defines=FGX_K=2,FGX_PAIRS=1 #include "wg_platform.hlsli" +#include "fg_fp16.hlsli" uint fgx_unorm(float v, float mx) { @@ -28,19 +30,37 @@ WG_ARGS_END Texture2D fgx_src : register(t0); +uint2 fgx_capture_tile(uint w, uint log_width) +{ + const uint tile = wg_block_id(), tiles_x = w >> log_width, lane = wg_lane_id(); + const uint ty = tile / tiles_x; + const uint tile_w = 1u << log_width, tile_h = 256u >> log_width; + return uint2((tile - ty * tiles_x) * tile_w + (lane & (tile_w - 1u)), ty * tile_h + (lane >> log_width)); +} + +uint2 fgx_capture_pixel(uint w, uint h, uint idx) +{ + // Both tile shapes cover exactly 256 texels. Partially tiled dimensions use the linear dispatch. + if (((w | h) & 15u) == 0u) return fgx_capture_tile(w, 4u); + if ((w & 31u) == 0u && (h & 7u) == 0u) return fgx_capture_tile(w, 5u); + const uint y = idx / w; + return uint2(idx - y * w, y); +} + // fg_exec_capture: a0 = dst, a1 = tw, a2 = th, a3 = kind WG_KERNEL(fg_exec_capture) { - WG_SETUP(); - const uint idx = wg_block_id() * 256u + wg_lane_id(); - const uint tw = a1, th = a2, kind = a3; - if (idx >= tw * th) return; - const uint x = idx % tw, y = idx / tw; - const float4 c = fgx_src.Load(int3((int)x, (int)y, 0)); + FG_FP16_SETUP(); + const uint linear_idx = wg_block_id() * 256u + wg_lane_id(); + const uint tw = a1, th = a2, kind = (uint)wg_uniform((int)a3); + if (linear_idx >= tw * th) return; + const uint2 xy = fgx_capture_pixel(tw, th, linear_idx); + const uint idx = xy.y * tw + xy.x; + const float4 c = fgx_src.Load(int3(xy, 0)); if (kind == 4u) - wg_st64(a0, idx * 8u, uint2(wg_f2h(c.x) | (wg_f2h(c.y) << 16), wg_f2h(c.z) | (wg_f2h(c.w) << 16))); + wg_st64(a0, idx * 8u, uint2(fg_pack_h2(c.x, c.y), fg_pack_h2(c.z, c.w))); else if (kind == 1u) - wg_st16(a0, idx * 2u, wg_f2h(c.x)); + wg_st16(a0, idx * 2u, fg_f2h(c.x)); else if (kind == 5u) wg_st64(a0, idx * 8u, uint2(asuint(c.x), asuint(c.y))); else @@ -53,19 +73,8 @@ WG_ARGS_BEGIN uint a0, a1, a2, a3, a4, a5, a6; WG_ARGS_END -// fg_exec_pack: a0 = src, a1 = sstride, a2 = dst, a3 = dpitch, a4 = w, a5 = h, a6 = fmt -WG_KERNEL(fg_exec_pack) +uint fgx_pack_pixel(uint2 v, uint fmt) { - WG_SETUP(); - const uint idx = wg_block_id() * 256u + wg_lane_id(); - const uint w = a4, h = a5, fmt = a6; - if (idx >= w * h) return; - const uint x = idx % w, y = idx / w; - const uint2 v = wg_ld64(a0, (y * a1 + x) * 8u); - if (fmt == 0u) { - wg_st64(a2, y * a3 + x * 8u, v); - return; - } const float r = f16tof32(v.x), g = f16tof32(v.x >> 16), b = f16tof32(v.y), a = f16tof32(v.y >> 16); uint word; if (fmt == 1u) @@ -77,6 +86,32 @@ WG_KERNEL(fg_exec_pack) else word = fgx_unorm(r, 1023.0f) | (fgx_unorm(g, 1023.0f) << 10) | (fgx_unorm(b, 1023.0f) << 20) | (fgx_unorm(a, 3.0f) << 30); - wg_st32(a2, y * a3 + x * 4u, word); + return word; +} + +// fg_exec_pack: a0 = src, a1 = sstride, a2 = dst, a3 = dpitch, a4 = w, a5 = h, a6 = fmt +WG_KERNEL(fg_exec_pack) +{ + WG_SETUP(); + const uint idx = wg_block_id() * 256u + wg_lane_id(); +#if FGX_PAIRS + const uint pairs = (a4 + 1u) >> 1u; + if (idx >= pairs * a5) return; + const uint x = (idx % pairs) * 2u, y = idx / pairs; + const uint src = (y * a1 + x) * 8u, dst = y * a3 + x * 4u; + if (x + 1u < a4) { + const uint4 v = wg_ld128(a0, src); + wg_st64(a2, dst, uint2(fgx_pack_pixel(v.xy, a6), fgx_pack_pixel(v.zw, a6))); + } else { + wg_st32(a2, dst, fgx_pack_pixel(wg_ld64(a0, src), a6)); + } +#else + const uint w = a4, h = a5, fmt = a6; + if (idx >= w * h) return; + const uint x = idx % w, y = idx / w; + const uint2 v = wg_ld64(a0, (y * a1 + x) * 8u); + if (fmt == 0u) wg_st64(a2, y * a3 + x * 8u, v); + else wg_st32(a2, y * a3 + x * 4u, fgx_pack_pixel(v, fmt)); +#endif } #endif diff --git a/clean/dx12/kernels/fg_full_blend.hlsl b/clean/dx12/kernels/fg_full_blend.hlsl index ffdc6d50..dc415a5c 100644 --- a/clean/dx12/kernels/fg_full_blend.hlsl +++ b/clean/dx12/kernels/fg_full_blend.hlsl @@ -4,8 +4,8 @@ // // One workgroup per 16 x 16 tile of the padded frame Wp x Hp (tiles_x = Wp / 16), one lane per pixel in Morton order. // Frame pixels write X0, X1 (4 x float16) and Xw (float16 0 / 1); every lane's single-precision values (zero outside -// the frame) then go through a lane tree in shared memory, and the first lane of each k x k block writes its net2 -// element: Ib, Ic (4 x float16, the means), Ia (float16, 1 if any hole). +// the frame) then go through a lane tree, and the first lane of each k x k block writes its net2 element: +// Ib, Ic (4 x float16, the means), Ia (float16, 1 if any hole). Only cross-wave sums use shared memory. // Inputs: Cp, Cc, Up, Uc (frame, 4 x float16), W (scatter grid W1 x H1, 2 x float16), Qc (Wd x Hd, 2 x float16), MA, MB // (scatter grid, 64-bit words). ui != 0: preset B (UI recomposition with Up / Uc), else preset A (Up / Uc not read). // @@ -19,24 +19,42 @@ WG_ARGS_BEGIN int Wo, Ho, W1, H1, Wd, Hd, k, tiles_x, ui; WG_ARGS_END -groupshared float fgb_s[9 * 256]; +groupshared float fgb_s[9 * 8]; + +float4 fgb_mean(float4 a, uint shift) +{ + // k is a power of two in [1, 16]. + const float scale = asfloat((127u - 2u * shift) << 23u); + // The general division quiets NaNs without changing the sign or payload. + return select((asuint(a) & 0x7fffffffu) > 0x7f800000u, asfloat(asuint(a) | 0x00400000u), a * scale); +} + +float fgb_add(float a, float b) +{ + // Preserve the lower Morton lane's payload when both operands are NaNs. + return isnan(a) ? a : a + b; +} WG_KERNEL(fg_full_blend) { FGF_SETUP(); const uint l = wg_lane_id(); const uint t = wg_block_id(); - const int px = (int)((t % (uint)tiles_x) * 16u + fgf_mx(l)); - const int py = (int)((t / (uint)tiles_x) * 16u + fgf_my(l)); + const uint ty = t / (uint)tiles_x; + const int2 origin = int2(t - ty * (uint)tiles_x, ty) * 16; + const int px = origin.x + (int)fgf_mx(l); + const int py = origin.y + (int)fgf_my(l); float v[9]; [unroll] for (uint c = 0; c < 9u; ++c) v[c] = 0.0f; - if (px < Wo && py < Ho) { - const float u = fgf_centre(px, Wo), vv = fgf_centre(py, Ho); + const bool in_bounds = px < Wo && py < Ho; + if (in_bounds) { + const float u = fgf_pixel_centre(px, Wo), vv = fgf_pixel_centre(py, Ho); const float tie = asfloat(0xB4000000u); // -2^-23 const int ix = clamp((int)round(mad(u, (float)W1, -0.5f) + tie), 0, W1 - 1); const int iy = clamp((int)round(mad(vv, (float)H1, -0.5f) + tie), 0, H1 - 1); - const uint2 wa = wg_ld64(ma, (uint)(iy * W1 + ix) * 8u); - const uint2 wb = wg_ld64(mb, (uint)(iy * W1 + ix) * 8u); + const uint offset = (uint)(iy * W1 + ix) * 8u; + const uint2 wa = wg_ld64(ma, offset); + const uint2 wb = wg_ld64(mb, offset); const bool emA = wa.x == 0x7FFFFFFFu && wa.y == 0x7FFFFFFFu; const bool emB = wb.x == 0x7FFFFFFFu && wb.y == 0x7FFFFFFFu; const float ax = emA ? 0.0f : wg_h2f_hi(wa.x), ay = emA ? 0.0f : wg_h2f_lo(wa.x); @@ -49,12 +67,14 @@ WG_KERNEL(fg_full_blend) const float3 cQ = fgf_bil4h(cc, fgf_tap_uv(ua, va, Wo, Ho)).xyz; const float2 w = fgf_bil2h(wimg, fgf_tap_uv(u, vv, W1, H1)); const float2 qu = fgf_bil2h(qc, fgf_tap_uv(u, vv, Wd, Hd)); - const float2 qb = fgf_bil2h(qc, fgf_tap_uv(ub, vb, Wd, Hd)); - const float2 qa = fgf_bil2h(qc, fgf_tap_uv(ua, va, Wd, Hd)); + // Reuse the co-located quality when the warped coordinates are identical. + float qbx = qu.x, qay = qu.y; + [branch] if (ub != u || vb != vv) qbx = fgf_bil2h(qc, fgf_tap_uv(ub, vb, Wd, Hd)).x; + [branch] if (ua != u || va != vv) qay = fgf_bil2h(qc, fgf_tap_uv(ua, va, Wd, Hd)).y; float3 x0rgb = mad(w.x, mad(eB, cQ - cP, cP) - P0, P0); - float x0a = mad(w.x, qb.x - qu.x, qu.x); + float x0a = mad(w.x, qbx - qu.x, qu.x); float3 x1rgb = mad(w.y, mad(eA, cP - cQ, cQ) - Q0, Q0); - float x1a = mad(w.y, qa.y - qu.y, qu.y); + float x1a = mad(w.y, qay - qu.y, qu.y); bool hole = emA && emB && (!(w.x < 0.5f) || !(w.y < 0.5f)); // unordered: NaN counts as >= 0.5 if (ui != 0) { const float4 Up = fgf_ld4h(up, pi), Uc = fgf_ld4h(uc, pi); @@ -66,29 +86,60 @@ WG_KERNEL(fg_full_blend) if (Uc.w > eps) x1a = e; hole = hole && Up.w < eps && Uc.w < eps; } - fgf_st4h(x0, pi, float4(x0rgb, x0a)); - fgf_st4h(x1, pi, float4(x1rgb, x1a)); - fgf_st1h(xw, pi, hole ? 1.0f : 0.0f); v[0] = x0rgb.x; v[1] = x0rgb.y; v[2] = x0rgb.z; v[3] = x0a; v[4] = x1rgb.x; v[5] = x1rgb.y; v[6] = x1rgb.z; v[7] = x1a; v[8] = hole ? 1.0f : 0.0f; } - [unroll] for (uint c2 = 0; c2 < 9u; ++c2) fgb_s[c2 * 256u + l] = v[c2]; + { + v8f pv; + [unroll] for (uint c = 0; c < 8u; ++c) pv.v[c] = fgf_opq(v[c]); + const uint4 h = wg_to_f16_ags(pv); + if (in_bounds) { + const uint pi8 = (uint)(py * Wo + px) * 8u; + wg_st64(x0, pi8, h.xy); + wg_st64(x1, pi8, h.zw); + } + } + fgf_store_morton_flag(xw, px, py, Wo, Ho, v[8] > 0.0f); + const uint shift = (uint)firstbithigh((uint)k); const uint kk = (uint)(k * k); - [loop] for (uint s = 1u; s < kk; s <<= 1u) { + const uint lane = wg_wave_lane(); + // Each surviving lane adds the higher half in Morton order at every stride. + if (kk >= 4u) { + [unroll] for (uint c = 0; c < 9u; ++c) { + v[c] = fgb_add(v[c], QuadReadAcrossX(v[c])); + v[c] = fgb_add(v[c], QuadReadAcrossY(v[c])); + } + } + if (kk > 4u) { + [unroll] for (uint c = 0; c < 9u; ++c) { + v[c] = fgb_add(v[c], WaveReadLaneAt(v[c], lane ^ 4u)); + v[c] = fgb_add(v[c], WaveReadLaneAt(v[c], lane ^ 8u)); + } + } + [branch] if (kk > 32u) { + [unroll] for (uint c = 0; c < 9u; ++c) + v[c] = fgb_add(v[c], WaveReadLaneAt(v[c], lane ^ 16u)); + if (lane == 0u) { + [unroll] for (uint c = 0; c < 9u; ++c) fgb_s[c * 8u + (l >> 5)] = v[c]; + } wg_barrier_lds(); - if ((l & (2u * s - 1u)) == 0u) { - [unroll] for (uint c3 = 0; c3 < 9u; ++c3) fgb_s[c3 * 256u + l] = fgb_s[c3 * 256u + l] + fgb_s[c3 * 256u + l + s]; + if (l < 32u) { + // The first wave continues the same tree over the eight partial sums. + const uint part = lane & 7u; + [unroll] for (uint c = 0; c < 9u; ++c) v[c] = fgb_s[c * 8u + part]; + [loop] for (uint s = 1u; s < (kk >> 5); s <<= 1u) { + [unroll] for (uint c = 0; c < 9u; ++c) v[c] = fgb_add(v[c], WaveReadLaneAt(v[c], lane ^ s)); + } } } - wg_barrier_lds(); - if ((l & (kk - 1u)) == 0u) { - const int e = (py / k) * (tiles_x * 16 / k) + px / k; - const float n = (float)kk; - fgf_st4h(ib, e, float4(wg_div(fgb_s[l], n), wg_div(fgb_s[256u + l], n), wg_div(fgb_s[512u + l], n), - wg_div(fgb_s[768u + l], n))); - fgf_st4h(ic, e, float4(wg_div(fgb_s[1024u + l], n), wg_div(fgb_s[1280u + l], n), wg_div(fgb_s[1536u + l], n), - wg_div(fgb_s[1792u + l], n))); - fgf_st1h(ia, e, fgb_s[2048u + l] > 0.0f ? 1.0f : 0.0f); + const uint leader_lane = kk > 32u ? l * 32u : l; + if ((kk <= 32u || l < 8u) && (leader_lane & (kk - 1u)) == 0u) { + const int bx = origin.x + (int)fgf_mx(leader_lane); + const int by = origin.y + (int)fgf_my(leader_lane); + const int e = (by >> shift) * ((tiles_x * 16) >> shift) + (bx >> shift); + fgf_st4h(ib, e, fgb_mean(float4(v[0], v[1], v[2], v[3]), shift)); + fgf_st4h(ic, e, fgb_mean(float4(v[4], v[5], v[6], v[7]), shift)); + wg_st16(ia, (uint)e * 2u, v[8] > 0.0f ? 0x3c00u : 0u); } } diff --git a/clean/dx12/kernels/fg_lite_blend.hlsl b/clean/dx12/kernels/fg_lite_blend.hlsl index 9a4fa7ec..dd72cd7d 100644 --- a/clean/dx12/kernels/fg_lite_blend.hlsl +++ b/clean/dx12/kernels/fg_lite_blend.hlsl @@ -28,7 +28,6 @@ bool fg_in_box(float px, float py) float3 fg_correct(float3 c, float alpha, float2 uv, float u, float v, bool empty, float4 P0, float4 Q0, uint L, float3 own) { - const FgRegion lr = FG_REGION(l); bool ok = fg_finite3(c) && !empty && fg_finite(uv.x) && fg_finite(uv.y) && wo >= 2u && ho >= 2u; ok = ok && fg_in_box(mad(uv.x, (float)wo, -0.5f), mad(uv.y, (float)ho, -0.5f)); ok = ok && fg_finite(u) && fg_finite(v) && fg_in_box(mad(u, (float)wo, -0.5f), mad(v, (float)ho, -0.5f)); @@ -39,12 +38,15 @@ float3 fg_correct(float3 c, float alpha, float2 uv, float u, float v, bool empty const float dx = fg_mul(uv.x - u, (float)wo), dy = fg_mul(uv.y - v, (float)ho); ok = ok && fg_sq(dx, dy) >= 4.0f; ok = ok && fg_finite3(P0.xyz) && fg_finite3(Q0.xyz) && P0.w == 0.0f && Q0.w == 0.0f; + [branch] if (!ok) return c; + + const FgRegion lr = FG_REGION(l); const float2 X1 = fg_region_xy(lr, uv.x, uv.y, false); const float3 d1 = fg_read_linear(L, 4u, (int)wo, (int)ho, X1.x, X1.y).xyz; const float2 X0 = fg_region_xy(lr, u, v, false); const float3 d0 = fg_read_linear(L, 4u, (int)wo, (int)ho, X0.x, X0.y).xyz; const float3 dl = own - d0; - ok = ok && fg_finite3(d1) && fg_finite3(d0) && fg_finite3(dl); + ok = fg_finite3(d1) && fg_finite3(d0) && fg_finite3(dl); const float3 ad = abs(dl); ok = ok && max(max(ad.x, ad.y), ad.z) <= asfloat(0x3E19999Au); const float3 tgt = d1 + dl; diff --git a/clean/dx12/kernels/fg_lite_g.hlsl b/clean/dx12/kernels/fg_lite_g.hlsl index 965928e4..1cd0af13 100644 --- a/clean/dx12/kernels/fg_lite_g.hlsl +++ b/clean/dx12/kernels/fg_lite_g.hlsl @@ -10,6 +10,7 @@ // fg_lite_weights: W = (sigma(NA at the MB vector - NA co-located), sigma(NB at the MA vector - NB co-located)). // // @wg-kernel fg_lite_interm co=- block=256 wave=32 args=u,p,p,p,u,u,u,u,u,u,u defines=FG_K=1 +// @wg-kernel fg_lite_interm_tiled co=- entry=fg_lite_interm block=256 wave=32 args=u,p,p,p,u,u,u,u,u,u,u defines=FG_K=1,FG_TILE=1 // @wg-kernel fg_lite_weights co=- block=256 wave=32 args=p,p,p,p,p,u,u,u,u defines=FG_K=2 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" @@ -44,21 +45,62 @@ int fg_radius(float qmax, float qmin, float qp) return clamp((int)fg_med3(ceil(a + 0.5f), 2.0f, 5.0f), 2, 5); } +#if FG_TILE +// A four-pixel halo covers both the 3x3 depth test and the largest 5x5 scatter. +static const int fg_tile_width = 24; +static const int fg_halo = 4; +groupshared float fg_tile_key[fg_tile_width * fg_tile_width]; +groupshared float fg_tile_dx[fg_tile_width * fg_tile_width]; +groupshared float fg_tile_dy[fg_tile_width * fg_tile_width]; + +float2 fg_tile_disp(int i) { return float2(fg_tile_dx[i], fg_tile_dy[i]); } +#endif + WG_KERNEL(fg_lite_interm) { FG_SETUP(); +#if FG_TILE + const uint tiles_x = (w1 + 15u) >> 4u, block = wg_block_id(), lane = wg_lane_id(); + const int2 origin = int2(block % tiles_x, block / tiles_x) * 16; + for (uint i = lane; i < fg_tile_width * fg_tile_width; i += 256u) { + const int2 p = origin + int2(i % fg_tile_width, i / fg_tile_width) - fg_halo; + const float2 d = fg_disp(p.x, p.y); + fg_tile_key[i] = fg_key_at(p.x, p.y); + fg_tile_dx[i] = d.x; + fg_tile_dy[i] = d.y; + } + wg_barrier_lds(); + const int2 local = int2(lane & 15u, lane >> 4u) + fg_halo; + const int2 xy = origin + local - fg_halo; + if (xy.x >= (int)w1 || xy.y >= (int)h1) return; + const int center = local.y * fg_tile_width + local.x; +#else const uint idx = wg_block_id() * 256u + wg_lane_id(); if (idx >= w1 * h1) return; - const int x = (int)(idx % w1), y = (int)(idx / w1); + const int2 xy = int2(fg_lite_tile_pixel(idx, w1, h1)); +#endif + const int x = xy.x, y = xy.y; const float tauf = asfloat(tau); +#if FG_TILE + const float kp = fg_tile_key[center]; + const float2 dp = fg_tile_disp(center); +#else const float kp = fg_key_at(x, y); const float2 dp = fg_disp(x, y); +#endif float kmax = -FG_INF, kmin = FG_INF, qxmax = -10000.0f, qymax = -10000.0f, qxmin = 10000.0f, qymin = 10000.0f; [unroll] for (int j = -1; j <= 1; ++j) [unroll] for (int i = -1; i <= 1; ++i) { - const float kn = fg_key_at(x + i, y + j); - const float2 dn = fg_disp(x + i, y + j); +#if FG_TILE + const int neighbor = center + j * fg_tile_width + i; + const float kn = fg_tile_key[neighbor]; + const float2 dn = fg_tile_disp(neighbor); +#else + const bool centre = i == 0 && j == 0; + const float kn = centre ? kp : fg_key_at(x + i, y + j); + const float2 dn = centre ? dp : fg_disp(x + i, y + j); +#endif kmax = max(kmax, kn); kmin = min(kmin, kn); const float qx = fg_opq((float)(x + i) + 0.5f) + dn.x, qy = fg_opq((float)(y + j) + 0.5f) + dn.y; @@ -70,7 +112,7 @@ WG_KERNEL(fg_lite_interm) const int rx = edge ? 2 : fg_radius(qxmax, qxmin, qpx); const int ry = edge ? 2 : fg_radius(qymax, qymin, qpy); const uint hi = asuint(kp); - const uint lo = (wg_f2h(fg_adiv(-dp.x, (float)w1)) << 16) | wg_f2h(fg_adiv(-dp.y, (float)h1)); + const uint lo = (fg_f2h(fg_adiv(-dp.x, (float)w1)) << 16) | fg_f2h(fg_adiv(-dp.y, (float)h1)); const float thr = max(fg_adiv(fg_sq(dp.x, dp.y), asfloat(t2)), 1.0f); const int sx = fg_sgn(dp.x), sy = fg_sgn(dp.y); const int bx = x + (int)dp.x, by = y + (int)dp.y; @@ -79,13 +121,22 @@ WG_KERNEL(fg_lite_interm) { const int tx = bx + ii * sx, ty = by + jj * sy; if (tx < 0 || tx >= (int)w1 || ty < 0 || ty >= (int)h1) continue; +#if FG_TILE + const int neighbor = center + jj * sy * fg_tile_width + ii * sx; + const float2 nd = fg_tile_disp(neighbor); +#else const int nx = x + ii * sx, ny = y + jj * sy; const float2 nd = fg_disp(nx, ny); +#endif const float dd = fg_sq(nd.x - dp.x, nd.y - dp.y); bool ok; if (pass_ == 0u) { +#if FG_TILE + const float kt = (float)(uint)fg_tile_key[neighbor]; +#else const float kt = (float)(uint)fg_key_at(nx, ny); +#endif ok = !(!(abs(kt - kp) < 3.0f) && !(dd < thr)); } else diff --git a/clean/dx12/kernels/fg_lite_menu.hlsl b/clean/dx12/kernels/fg_lite_menu.hlsl index 0245871c..eac0cb74 100644 --- a/clean/dx12/kernels/fg_lite_menu.hlsl +++ b/clean/dx12/kernels/fg_lite_menu.hlsl @@ -112,6 +112,6 @@ WG_KERNEL(fg_lite_menu_output) const float a = fg_read_nearest(alpha, a_kind, (int)a_w, (int)a_h, AX.x, AX.y)[a_ch]; const float oma = 1.0f - a; const float3 rgb = float3(c.x + fg_mul(g.x - hc.x, oma), c.y + fg_mul(g.y - hc.y, oma), c.z + fg_mul(g.z - hc.z, oma)); - fg_st_h4(outp, oi, float4(rgb, g.w)); + wg_st64(outp, oi * 8u, uint2(wg_pack_h2(rgb.x, rgb.y), wg_pack_h2(rgb.z, g.w))); } #endif diff --git a/clean/dx12/kernels/fg_lite_net1io.hlsl b/clean/dx12/kernels/fg_lite_net1io.hlsl index e7512ee6..676af76a 100644 --- a/clean/dx12/kernels/fg_lite_net1io.hlsl +++ b/clean/dx12/kernels/fg_lite_net1io.hlsl @@ -7,8 +7,8 @@ // fg_lite_quality_init: Qc := (sat(((r + g) + b) / 3), 0) of Dc. // fg_lite_net1_input: one lane per pixel of the 2 x 2-fold grid (2 W0 x 2 H0): the ten values of its image pixel (zero // outside the image) at cell channels 4 v + 2 dy + dx (channels 40..47 zero, written by the dx = dy = 0 lane); the -// cell layout is element (channel * cs + (Y * W0 + X) * ps) of float16 (HWC: cs 1, ps 48; CHW: cs H0 W0, ps 1); -// image pixels also write Qc = (v6, v2) and Om = sat((E Hp) Hc). +// cell layout is element (channel * cs + (Y * W0 + X) * ps) of float16 (HWC: cs 1, ps 48; CHW: cs H0 W0, ps 1). +// Aligned HWC cells use six vector stores. Image pixels also write Qc = (v6, v2) and Om = sat((E Hp) Hc). // fg_lite_net1_output: one lane per net1 image pixel: the four values of its (clamped) cell, the occlusion push-down, the // sigmoid map m, the UI forcing (ui_forcing != 0) and the logit pairs NA, NB. // @@ -71,20 +71,51 @@ float fg_warp(float3 a, float3 b) void fg_cell_store(uint X, uint Y, uint ch, float val) { - wg_st16(cells, (ch * cs + (Y * W0 + X) * ps) * 2u, wg_f2h(val)); + wg_st16(cells, (ch * cs + (Y * W0 + X) * ps) * 2u, fg_f2h(val)); +} + +// Each quad generates the four pixels of one HWC cell. The tile stores two channels per +// word from each pixel, then transposes those words into vectors in channel order. +groupshared uint fg_cell_pairs[5][256]; + +uint4 fg_cell_vector(uint pair, uint lane) +{ + const uint a = fg_cell_pairs[pair][lane], b = fg_cell_pairs[pair][lane + 1u]; + const uint c = fg_cell_pairs[pair][lane + 2u], d = fg_cell_pairs[pair][lane + 3u]; + return uint4((a & 0xffffu) | (b << 16), (c & 0xffffu) | (d << 16), + (a >> 16) | (b & 0xffff0000u), (c >> 16) | (d & 0xffff0000u)); } WG_KERNEL(fg_lite_net1_input) { FG_SETUP(); - const uint idx = wg_block_id() * 256u + wg_lane_id(); + const uint lane = wg_lane_id(), block = wg_block_id(); + const uint idx = block * 256u + lane; const uint gw = 2u * W0, gh = 2u * H0; - if (idx >= gw * gh) return; - const uint gx = idx % gw, gy = idx / gw; - const int x = (int)gx - 2 * (int)pad_l, y = (int)gy - 2 * (int)pad_t; - const uint X = gx >> 1, Y = gy >> 1, q = 2u * (gy & 1u) + (gx & 1u); + const bool hwc = cs == 1u && ps == 48u && (cells & 15u) == 0u; + const bool tiled = hwc && ((W0 | H0) & 7u) == 0u; + uint X, Y, q; + if (hwc) { + const uint cell = idx >> 2u; + q = lane & 3u; + if (tiled) { + X = (block % (W0 >> 3u)) * 8u + ((lane >> 2u) & 7u); + Y = (block / (W0 >> 3u)) * 8u + (lane >> 5u); + } else { + X = cell % W0; + Y = cell / W0; + } + } else { + if (idx >= gw * gh) return; + const uint gx = idx % gw, gy = idx / gw; + X = gx >> 1u; + Y = gy >> 1u; + q = 2u * (gy & 1u) + (gx & 1u); + } + const int x = (int)(2u * X + (q & 1u)) - 2 * (int)pad_l; + const int y = (int)(2u * Y + (q >> 1u)) - 2 * (int)pad_t; float vals[10] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; - if (x >= 0 && x < (int)wd && y >= 0 && y < (int)hd) + if (Y < H0 && x >= 0 && x < (int)wd && y >= 0 && y < (int)hd) { const uint pi = (uint)y * wd + (uint)x; const float u = fg_centre((uint)x, wd), v = fg_centre((uint)y, hd); @@ -111,6 +142,18 @@ WG_KERNEL(fg_lite_net1_input) fg_st_h2(qc, pi, v6, v2); fg_st_h1(om, pi, fg_sat(fg_mul(fg_mul(e, hpv), hcv))); } + if (hwc) { + [unroll] for (uint pair = 0u; pair < 5u; ++pair) + fg_cell_pairs[pair][lane] = fg_pack_h2(vals[2u * pair], vals[2u * pair + 1u]); + wg_barrier_lds(); + if (Y >= H0) return; + const uint off = (Y * W0 + X) * 96u; + const uint quad = lane & ~3u; + wg_st128(cells, off + 16u * q, fg_cell_vector(q, quad)); + if (q == 0u) wg_st128(cells, off + 64u, fg_cell_vector(4u, quad)); + if (q == 1u) wg_st128(cells, off + 80u, uint4(0u, 0u, 0u, 0u)); + return; + } [unroll] for (uint k = 0u; k < 10u; ++k) fg_cell_store(X, Y, 4u * k + q, vals[k]); if (q == 0u) [unroll] for (uint c = 40u; c < 48u; ++c) fg_cell_store(X, Y, c, 0.0f); @@ -123,6 +166,9 @@ WG_ARGS_BEGIN uint wd, hd, pad_l, pad_t, W0, H0, cs, ps, ui_forcing; WG_ARGS_END +void fg_output_h1(uint base, uint idx, float a) { wg_st16(base, idx * 2u, wg_f2h(a)); } +void fg_output_h2(uint base, uint idx, float a, float b) { wg_st32(base, idx * 4u, wg_f2h(a) | (wg_f2h(b) << 16)); } + WG_KERNEL(fg_lite_net1_output) { FG_SETUP(); @@ -143,8 +189,10 @@ WG_KERNEL(fg_lite_net1_output) if (fg_texel(ump, 1u, idx).x > 0.99f) { o[0] = o[0] - 1000.0f; o[1] = o[1] + 1000.0f; } if (fg_texel(um, 1u, idx).x > 0.99f) { o[2] = o[2] - 1000.0f; o[3] = o[3] + 1000.0f; } } - fg_st_h2(na, idx, o[0], o[1]); - fg_st_h2(nb, idx, o[2], o[3]); - fg_st_h1(mimg, idx, mm); + // Preserve the original conversion sequence for the two logit pairs and + // sigmoid output. Its code generation also applies to partial edge grids. + fg_output_h2(na, idx, o[0], o[1]); + fg_output_h2(nb, idx, o[2], o[3]); + fg_output_h1(mimg, idx, mm); } #endif diff --git a/clean/dx12/kernels/fg_lite_p2c.hlsl b/clean/dx12/kernels/fg_lite_p2c.hlsl index 9abb3e23..0d709e99 100644 --- a/clean/dx12/kernels/fg_lite_p2c.hlsl +++ b/clean/dx12/kernels/fg_lite_p2c.hlsl @@ -19,6 +19,8 @@ // @wg-kernel fg_lite_p2c_inpaint_mut co=- entry=fg_lite_p2c_inpaint block=256 wave=32 args=p,p,u,u defines=FG_K=3,FG_MUT=1 // @wg-kernel fg_lite_p2c_pull co=- block=256 wave=32 args=u,p,p,p,p,u,u,u,u,u defines=FG_K=4 // @wg-kernel fg_lite_p2c_push co=- block=256 wave=32 args=p,u,u,p,u,u defines=FG_K=5 +// @wg-kernel fg_lite_p2c_pull_tiled co=- entry=fg_lite_p2c_pull block=256 wave=32 args=u,p,p,p,p,u,u,u,u,u,p,p,p,u defines=FG_K=4,FG_PULL_TILE=1 +// @wg-kernel fg_lite_p2c_push_tail co=- block=256 wave=32 args=u,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_K=7 // @wg-kernel fg_lite_p2c_fine co=- block=256 wave=32 args=p,u,u,p,p,u,u defines=FG_K=6 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" @@ -49,7 +51,7 @@ WG_KERNEL(fg_lite_p2c_scatter) fg_st_h1(kc, idx, cons ? 0.0f : 1.0f); const float key = cons ? kap + fg_opq(fg_mul(kap, cam.z) - kap) : kap; const uint hi = (asuint(key) & 0xFFFFFFFEu) | (cons ? 1u : 0u); - const uint lo = (wg_f2h(mx) << 16) | wg_f2h(my); + const uint lo = (fg_f2h(mx) << 16) | fg_f2h(my); const float thr2 = max(fg_adiv(msq, asfloat(t2)), 1.0f); const int sx = fg_sgn(mx), sy = fg_sgn(my); const int bx = x + (int)mx, by = y + (int)my; @@ -116,31 +118,52 @@ WG_ARGS_BEGIN uint fl, gout, w1, h1; WG_ARGS_END +// Each row holds the 256 centers and the two horizontal halo pixels on either side. +// A row is addressed in the flat grid, then trimmed at the center pixel's image edges. +groupshared uint fg_inpaint_flags[5][9]; + WG_KERNEL(fg_lite_p2c_inpaint) { FG_SETUP(); - const uint idx = wg_block_id() * 256u + wg_lane_id(); - if (idx >= w1 * h1) return; - const int x = (int)(idx % w1), y = (int)(idx / w1); - uint bits = 0u; // bit (j + 2) * 5 + (i + 2): flag bit 1 of pixel (x + i, y + j), 0 outside the grid - [unroll] for (int j = -2; j <= 2; ++j) - [unroll] for (int i = -2; i <= 2; ++i) + const uint l = wg_lane_id(); + const uint idx = wg_block_id() * 256u + l; + const uint size = w1 * h1; + const uint lane = wg_wave_lane(); + [unroll] for (int j = 0; j < 5; ++j) + { + const int p = (int)idx + (j - 2) * (int)w1 - 2; + const bool flag = (uint)p < size && (wg_ld32(fl, (uint)p * 4u) & 2u) != 0u; + const uint row = WaveActiveBallot(flag).x; + if (lane == 0u) fg_inpaint_flags[j][l >> 5] = row; + if (l < 32u) { - const int px = x + i, py = y + j; - const bool in_ = px >= 0 && px < (int)w1 && py >= 0 && py < (int)h1; - const uint b = in_ ? (wg_ld32(fl, (uint)(py * (int)w1 + px) * 4u) >> 1) & 1u : 0u; - bits |= b << (uint)((j + 2) * 5 + (i + 2)); + const int q = p + 256; + const bool halo = l < 4u && (uint)q < size && (wg_ld32(fl, (uint)q * 4u) & 2u) != 0u; + const uint tail = WaveActiveBallot(halo).x; + if (lane == 0u) fg_inpaint_flags[j][8] = tail; } + } + wg_barrier_lds(); + if (idx >= size) return; + + const int x = (int)(idx % w1); + const uint xmask = ((1u << (uint)min((int)w1 - x + 2, 5)) - 1u) & (31u << (uint)max(2 - x, 0)); + uint bits = 0u; + [unroll] for (int j = 0; j < 5; ++j) + { + const uint a = fg_inpaint_flags[j][l >> 5]; + const uint b = fg_inpaint_flags[j][(l >> 5) + 1u]; + const uint row = (a >> lane) | (lane > 27u ? (b << (32u - lane)) : 0u); + bits |= (row & xmask) << (uint)(j * 5); + } bool inp = true; - [unroll] for (int cj = -1; cj <= 1; ++cj) - [unroll] for (int ci = -1; ci <= 1; ++ci) + [unroll] for (int j = 0; j < 3; ++j) + [unroll] for (int i = 0; i < 3; ++i) { - bool w = false; - [unroll] for (int j2 = -1; j2 <= 1; ++j2) - [unroll] for (int i2 = -1; i2 <= 1; ++i2) - w = w || ((bits >> (uint)((cj + j2 + 2) * 5 + (ci + i2 + 2))) & 1u) != 0u; + const uint mask = 0x1ce7u << (uint)(j * 5 + i); // three 3-bit rows on a 5-bit stride + const bool w = (bits & mask) != 0u; #if FG_MUT - inp = inp && (w || (cj == 1 && ci == 1)); // mutant: the last window is not required + inp = inp && (w || (j == 2 && i == 2)); // mutant: the last window is not required #else inp = inp && w; #endif @@ -153,6 +176,9 @@ WG_KERNEL(fg_lite_p2c_inpaint) #if FG_K == 4 WG_ARGS_BEGIN uint mode, srca, srcb, sums_out, elem_out, ws, hs, wl, hl, nbits; +#if FG_PULL_TILE + uint elem2, elem3, elem4, levels; +#endif WG_ARGS_END float3 fg_child(int cx, int cy) @@ -170,30 +196,99 @@ float3 fg_child(int cx, int cy) return float3(fg_mul(e.x, e.z), fg_mul(e.y, e.z), e.z); } -WG_KERNEL(fg_lite_p2c_pull) +float3 fg_pull_sum(int X, int Y) { - FG_SETUP(); - const uint idx = wg_block_id() * 256u + wg_lane_id(); - if (idx >= wl * hl) return; - const int X = (int)(idx % wl), Y = (int)(idx / wl); const float3 c00 = fg_child(2 * X, 2 * Y), c10 = fg_child(2 * X + 1, 2 * Y); const float3 c01 = fg_child(2 * X, 2 * Y + 1), c11 = fg_child(2 * X + 1, 2 * Y + 1); float3 s; s.x = fg_opq(fg_opq(c00.x + c10.x) + fg_opq(c01.x + c11.x)); s.y = fg_opq(fg_opq(c00.y + c10.y) + fg_opq(c01.y + c11.y)); s.z = fg_opq(fg_opq(c00.z + c10.z) + fg_opq(c01.z + c11.z)); + return s; +} + +void fg_pull_element(uint dst, uint idx, float3 s, float area) +{ + const float den = max(s.z, FG_WEIGHT_FLOOR); + fg_st_h3(dst, idx, float3(fg_adiv(s.x, den), fg_adiv(s.y, den), fg_adiv(s.z, area))); +} + +#if FG_PULL_TILE +groupshared float3 fg_pull_waves[8]; + +uint fg_pull_morton_x(uint l) +{ + return (l & 1u) | ((l >> 1u) & 2u) | ((l >> 2u) & 4u) | ((l >> 3u) & 8u); +} + +float3 fg_pull_ordered(float3 left, float3 right) +{ + const float3 s = left + right; + // A WaveReadLaneAt operand may be commuted by the compiler. When both + // operands are NaNs, retain the left operand as the standalone pull does. + return select(isnan(left), left, float3(fg_opq(s.x), fg_opq(s.y), fg_opq(s.z))); +} + +float3 fg_pull_quad(float3 s, uint lane, uint stride) +{ + s = fg_pull_ordered(s, WaveReadLaneAt(s, lane ^ stride)); + return fg_pull_ordered(s, WaveReadLaneAt(s, lane ^ (2u * stride))); +} + +void fg_pull_level(uint dst, uint x, uint y, uint shift, float3 s) +{ + const uint mask = (1u << shift) - 1u; + const uint w = (wl + mask) >> shift, h = (hl + mask) >> shift; + x >>= shift; + y >>= shift; + if (x < w && y < h) fg_pull_element(dst, y * w + x, s, (float)(4u << (2u * shift))); +} +#endif + +WG_KERNEL(fg_lite_p2c_pull) +{ + FG_SETUP(); +#if FG_PULL_TILE + const uint l = wg_lane_id(), lane = wg_wave_lane(); + const uint tiles_x = (wl + 15u) >> 4u, tile = wg_block_id(); + const uint base_x = (tile % tiles_x) * 16u, base_y = (tile / tiles_x) * 16u; + const uint x = base_x + fg_pull_morton_x(l), y = base_y + fg_pull_morton_x(l >> 1u); + float3 s = 0.0f; + if (x < wl && y < hl) { + s = fg_pull_sum((int)x, (int)y); + fg_pull_element(elem_out, y * wl + x, s, asfloat(nbits)); + } + if (levels == 1u) return; + s = fg_pull_quad(s, lane, 1u); + if ((l & 3u) == 0u) fg_pull_level(elem2, x, y, 1u, s); + if (levels == 2u) return; + s = fg_pull_quad(s, lane, 4u); + if ((l & 15u) == 0u) fg_pull_level(elem3, x, y, 2u, s); + if (levels == 3u) return; + s = fg_pull_ordered(s, WaveReadLaneAt(s, lane ^ 16u)); + if (lane == 0u) fg_pull_waves[l >> 5u] = s; + wg_barrier_lds(); + if (l < 4u) { + const uint wave = 2u * l; + s = fg_pull_ordered(fg_pull_waves[wave], fg_pull_waves[wave + 1u]); + fg_pull_level(elem4, base_x + (l & 1u) * 8u, base_y + (l >> 1u) * 8u, 3u, s); + } +#else + const uint idx = wg_block_id() * 256u + wg_lane_id(); + if (idx >= wl * hl) return; + const float3 s = fg_pull_sum((int)(idx % wl), (int)(idx / wl)); if (sums_out != 0u) { wg_st32(sums_out, idx * 12u, asuint(s.x)); wg_st32(sums_out, idx * 12u + 4u, asuint(s.y)); wg_st32(sums_out, idx * 12u + 8u, asuint(s.z)); } - const float den = max(s.z, FG_WEIGHT_FLOOR); - fg_st_h3(elem_out, idx, float3(fg_adiv(s.x, den), fg_adiv(s.y, den), fg_adiv(s.z, asfloat(nbits)))); + fg_pull_element(elem_out, idx, s, asfloat(nbits)); +#endif } #endif -#if FG_K == 5 || FG_K == 6 +#if FG_K == 5 || FG_K == 6 || FG_K == 7 // (v_up, w_up) of fine element (qx, qy) from the filled parent level [ph][pw] (float16 x 3) float3 fg_upsample(uint parent, int pw, int ph, int qx, int qy) { @@ -216,6 +311,16 @@ float3 fg_upsample(uint parent, int pw, int ph, int qx, int qy) } #endif +#if FG_K == 5 || FG_K == 7 +void fg_push_pixel(uint parent, int pw, int ph, uint level, uint lw, uint lh, uint idx) +{ + if (idx >= lw * lh) return; + const float4 own = fg_texel(level, 3u, idx); + if (!(own.z <= 0.0f)) return; + fg_st_h3(level, idx, fg_upsample(parent, pw, ph, (int)(idx % lw), (int)(idx / lw))); +} +#endif + #if FG_K == 5 WG_ARGS_BEGIN uint parent, pw, ph, level, lw, lh; @@ -225,11 +330,29 @@ WG_KERNEL(fg_lite_p2c_push) { FG_SETUP(); const uint idx = wg_block_id() * 256u + wg_lane_id(); - if (idx >= lw * lh) return; - const int qx = (int)(idx % lw), qy = (int)(idx / lw); - const float4 own = fg_texel(level, 3u, idx); - if (!(own.z <= 0.0f)) return; // the level's own value stays - fg_st_h3(level, idx, fg_upsample(parent, (int)pw, (int)ph, qx, qy)); + fg_push_pixel(parent, (int)pw, (int)ph, level, lw, lh, idx); +} +#endif + +#if FG_K == 7 +WG_ARGS_BEGIN + uint count, p0, p1, p2, p3, p4, p5, p6, p7; + uint w0, w1, w2, w3, w4, w5, w6, w7; + uint h0, h1, h2, h3, h4, h5, h6, h7; +WG_ARGS_END + +// Every level fits in this one workgroup. The device barrier makes the stored FP16 +// parent visible to the next level, with the same rounding as separate dispatches. +WG_KERNEL(fg_lite_p2c_push_tail) +{ + FG_SETUP(); + const uint p[8] = {p0, p1, p2, p3, p4, p5, p6, p7}; + const uint w[8] = {w0, w1, w2, w3, w4, w5, w6, w7}; + const uint h[8] = {h0, h1, h2, h3, h4, h5, h6, h7}; + [loop] for (uint i = 1u; i <= count; ++i) { + fg_push_pixel(p[i - 1u], (int)w[i - 1u], (int)h[i - 1u], p[i], w[i], h[i], wg_lane_id()); + if (i < count) wg_barrier(); + } } #endif diff --git a/clean/dx12/kernels/fg_lite_r3.hlsl b/clean/dx12/kernels/fg_lite_r3.hlsl index 9fd2db31..de62a5ee 100644 --- a/clean/dx12/kernels/fg_lite_r3.hlsl +++ b/clean/dx12/kernels/fg_lite_r3.hlsl @@ -9,6 +9,9 @@ // // @wg-kernel fg_lite_downsample2 co=- entry=fg_lite_downsample block=256 wave=32 args=p,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,p,p,p,p,p,u,u,u,u,u defines=FG_D=2 // @wg-kernel fg_lite_downsample4 co=- entry=fg_lite_downsample block=256 wave=32 args=p,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,p,p,p,p,p,u,u,u,u,u defines=FG_D=4 +// @wg-kernel fg_lite_downsample2_srv co=- entry=fg_lite_downsample block=256 wave=32 args=p,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,p,p,p,p,p,u,u,u,u,u rs=direct defines=FG_D=2,FG_SRV=1 +// @wg-kernel fg_lite_downsample2_srv_hud_tile co=- entry=fg_lite_downsample block=256 wave=32 args=p,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,p,p,p,p,p,u,u,u,u,u rs=direct defines=FG_D=2,FG_SRV=1,FG_HUD_TILE=1 +// @wg-kernel fg_lite_downsample4_srv co=- entry=fg_lite_downsample block=256 wave=32 args=p,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,p,p,p,p,p,u,u,u,u,u rs=direct defines=FG_D=4,FG_SRV=1 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" @@ -22,29 +25,119 @@ WG_ARGS_BEGIN uint wo, ho, wd, hd, flags; WG_ARGS_END +#if FG_SRV +Texture2D fg_colour_srv : register(t0); +Texture2D fg_hud_srv : register(t1); +Texture2D fg_alpha_srv : register(t2); + +float3 fg_r3_hud_texel(int x, int y) +{ + const float3 c = fg_hud_srv.Load(int3(x, y, 0)).xyz; + return float3(wg_h2f(fg_f2h(c.x)), wg_h2f(fg_f2h(c.y)), wg_h2f(fg_f2h(c.z))); +} +#endif + +uint2 fg_r3_colour_bits(uint x, uint y) +{ +#if FG_SRV + const float3 c = fg_colour_srv.Load(int3(cbx + x, cby + y, 0)).xyz; + return uint2(fg_pack_h2(c.x, c.y), fg_f2h(c.z)); +#else + return wg_ld64(colour, ((cby + y) * cw + cbx + x) * 8u); +#endif +} + +float3 fg_r3_unpack_colour(uint2 c) +{ + return float3(wg_h2f_lo(c.x), wg_h2f_hi(c.x), wg_h2f_lo(c.y)); +} + +bool fg_r3_special_colour(uint2 c) +{ + const uint3 mag = uint3(c.x, c.x >> 16, c.y) & 0x7fffu; + // Zero round-trips unchanged. Retain explicit conversion for NaNs and subnormals. + return any(mag > 0x7c00u) || any((mag - 1u) < 0x03ffu); +} + float3 fg_opq3(float3 v) { return float3(fg_opq(v.x), fg_opq(v.y), fg_opq(v.z)); } -float fg_r16(float x) { return wg_h2f(wg_f2h(x)); } + +#if FG_HUD_TILE +static const int fg_hud_tile_w = 34, fg_hud_tile_h = 10; +groupshared float fg_hud_r[fg_hud_tile_w * fg_hud_tile_h]; +groupshared float fg_hud_g[fg_hud_tile_w * fg_hud_tile_h]; +groupshared float fg_hud_b[fg_hud_tile_w * fg_hud_tile_h]; +static int2 fg_hud_origin; + +float3 fg_r3_hud_tap(int x, int y) +{ + const int2 p = int2(x, y) - fg_hud_origin; + const int i = p.y * fg_hud_tile_w + p.x; + return float3(fg_hud_r[i], fg_hud_g[i], fg_hud_b[i]); +} +#elif FG_SRV +#define fg_r3_hud_tap fg_r3_hud_texel +#endif + +float3 fg_r3_hud(uint x, uint y, bool linear_filter) +{ + const float2 xy = fg_region_xy(FG_REGION(h), fg_centre(x, wo), fg_centre(y, ho), false); +#if FG_SRV + if (!linear_filter) + return fg_r3_hud_texel(fg_nearest_index(xy.x, (int)hw), fg_nearest_index(xy.y, (int)hh)); + const float2 p = mad(xy, float2(hw, hh), -0.5f); + const float2 f = floor(p), a = p - f; + const int2 hi = int2(hw, hh) - 1; + const int2 r = clamp(int2(f), -1, hi); + const int2 lo = max(r, 0), up = min(r + 1, hi); + const float3 t00 = fg_r3_hud_tap(lo.x, lo.y), t10 = fg_r3_hud_tap(up.x, lo.y); + const float3 t01 = fg_r3_hud_tap(lo.x, up.y), t11 = fg_r3_hud_tap(up.x, up.y); + const float3 r0 = mad(a.xxx, t10 - t00, t00); + const float3 r1 = mad(a.xxx, t11 - t01, t01); + return mad(a.yyy, r1 - r0, r0); +#else + return linear_filter ? fg_read_linear(hud, 4u, (int)hw, (int)hh, xy.x, xy.y).xyz + : fg_read_nearest(hud, 4u, (int)hw, (int)hh, xy.x, xy.y).xyz; +#endif +} // one frame pixel: writes Cc / Uc / Lc, returns the block source colour, the luma change and the UI flag -void fg_r3_pixel(uint x, uint y, out float3 s, out float diff, out bool flag) +void fg_r3_pixel(uint x, uint y, uint mode, out float3 s, out float diff, out bool flag) { - const bool F1 = (flags & 1u) != 0u, A = (flags & 2u) != 0u, Hd = (flags & 4u) != 0u; - const bool L1 = (flags & 8u) != 0u, L2 = (flags & 16u) != 0u; - const uint caseU = F1 ? 1u : 0u, caseA = (!F1 && A) ? 1u : 0u, caseH = (!F1 && !A && Hd) ? 1u : 0u; - const float u = fg_centre(x, wo), v = fg_centre(y, ho); const uint pi = y * wo + x; - const float4 c = fg_texel(colour, 4u, (cby + y) * cw + cbx + x); - float4 hc = float4(0.0f, 0.0f, 0.0f, 0.0f); - if (caseU != 0u || caseH != 0u || (caseA != 0u && L2)) - { - const float2 XY = fg_region_xy(FG_REGION(h), u, v, false); - hc = L2 ? fg_read_linear(hud, 4u, (int)hw, (int)hh, XY.x, XY.y) : fg_read_nearest(hud, 4u, (int)hw, (int)hh, XY.x, XY.y); + if (mode == 0u) { + const uint2 raw = fg_r3_colour_bits(x, y); + s = fg_r3_unpack_colour(raw); + uint2 packed = uint2(raw.x, raw.y & 0xffffu); + float3 c16 = s; + [branch] if (fg_r3_special_colour(raw)) { + packed = uint2(fg_pack_h2(s.x, s.y), fg_f2h(s.z)); + c16 = float3(wg_h2f_lo(packed.x), wg_h2f_hi(packed.x), wg_h2f_lo(packed.y)); + } + wg_st64(cc, pi * 8u, packed); + diff = abs(fg_luma(c16) - fg_luma(fg_texel(cp, 4u, pi).xyz)); + flag = false; + return; } + + const bool F1 = (mode & 1u) != 0u, A = (mode & 2u) != 0u, Hd = (mode & 4u) != 0u; + const bool L1 = (mode & 8u) != 0u, L2 = (mode & 16u) != 0u; + const uint caseU = F1 ? 1u : 0u, caseA = (!F1 && A) ? 1u : 0u, caseH = (!F1 && !A && Hd) ? 1u : 0u; + const uint2 raw = fg_r3_colour_bits(x, y); + const float3 c = fg_r3_unpack_colour(raw); + float3 hc = 0.0f; + if (caseU != 0u || caseH != 0u || (caseA != 0u && L2)) + hc = fg_r3_hud(x, y, L2); float al = 0.0f; if (caseU != 0u || caseA != 0u) { - const float2 XY = fg_region_xy(FG_REGION(a), u, v, false); + const float2 XY = fg_region_xy(FG_REGION(a), fg_centre(x, wo), fg_centre(y, ho), false); +#if FG_SRV + const float4 texel = fg_alpha_srv.Load(int3(fg_nearest_index(XY.x, (int)aw), + fg_nearest_index(XY.y, (int)ah), 0)); + al = wg_h2f(fg_f2h(texel[ach])); +#else al = fg_read_nearest(alpha, akind, (int)aw, (int)ah, XY.x, XY.y)[ach]; +#endif } float4 ccv; flag = false; @@ -84,69 +177,309 @@ void fg_r3_pixel(uint x, uint y, out float3 s, out float diff, out bool flag) ccv = float4(c.xyz, 0.0f); s = c.xyz; } - fg_st_h4(cc, pi, ccv); - const float3 c16 = float3(fg_r16(ccv.x), fg_r16(ccv.y), fg_r16(ccv.z)); + uint2 packed; + float3 c16; +#if FG_SRV + [branch] if (caseU == 0u && !fg_r3_special_colour(raw)) { + packed = uint2(raw.x, (raw.y & 0xffffu) | (fg_f2h(ccv.w) << 16)); + c16 = c; + } else +#endif + { + packed = uint2(fg_pack_h2(ccv.x, ccv.y), fg_pack_h2(ccv.z, ccv.w)); + c16 = fg_r3_unpack_colour(packed); + } + wg_st64(cc, pi * 8u, packed); const float3 p = fg_texel(cp, 4u, pi).xyz; diff = abs(fg_luma(c16) - fg_luma(p)); } +float3 fg_r3_source(uint x, uint y, uint mode) +{ + if (x >= wo || y >= ho) return 0.0f; + if ((mode & 1u) != 0u) return fg_r3_hud(x, y, (mode & 16u) != 0u); + return fg_r3_unpack_colour(fg_r3_colour_bits(x, y)); +} + +float3 fg_r3_ordered_sum(float3 a, float3 b) +{ + return select(isnan(a), a, fg_opq3(a + b)); +} + +float3 fg_r3_nan_sum(uint X, uint Y, uint mode) +{ + float3 sum = 0.0f; + [loop] for (uint j = 0u; j < FG_D; j += 2u) { + float3 strip = 0.0f; + [loop] for (uint i = 0u; i < FG_D; i += 2u) { + const uint x = FG_D * X + i, y = FG_D * Y + j; + const float3 top = fg_r3_ordered_sum(fg_r3_source(x, y, mode), fg_r3_source(x + 1u, y, mode)); + const float3 bottom = fg_r3_ordered_sum(fg_r3_source(x, y + 1u, mode), fg_r3_source(x + 1u, y + 1u, mode)); + const float3 square = fg_r3_ordered_sum(top, bottom); + strip = i == 0u ? square : fg_r3_ordered_sum(strip, square); + } + sum = j == 0u ? strip : fg_r3_ordered_sum(sum, strip); + } + return sum; +} + +void fg_r3_write(uint x, uint y, float3 c, float diff, bool any_flag, uint mode) +{ + if (x >= wd || y >= hd) return; + const uint ni = y * wd + x; + // A commuted instruction can choose either NaN when both operands are NaNs. + // Reevaluate affected blocks in the baseline's left-first order. + [branch] if (any(isnan(c))) c = fg_r3_nan_sum(x, y, mode); + const float scale = 1.0f / (FG_D * FG_D); + fg_st_h4(dc, ni, float4(fg_mul(c.x, scale), fg_mul(c.y, scale), fg_mul(c.z, scale), 0.0f)); + fg_st_h1(ld, ni, diff); + if ((mode & 1u) == 0u && (mode & 6u) != 0u) fg_st_h1(um, ni, any_flag ? 1.0f : 0.0f); +} + +void fg_r3_wave_m0(uint X, uint Y, uint lane, out float3 result, out float diff) +{ + const uint blocks = 32u / FG_D; + const uint source = (lane & (blocks - 1u)) * FG_D; + result = 0.0f; + diff = 0.0f; + [loop] for (uint p = 0u; p < FG_D; ++p) + { + const uint x = FG_D * X + p * 32u + lane; + float3 c = 0.0f; + float d = 0.0f; + [unroll] for (uint j2 = 0u; j2 < FG_D; j2 += 2u) + { + const uint y0 = FG_D * Y + j2, y1 = y0 + 1u; + const uint pi0 = y0 * wo + x, pi1 = y1 * wo + x; +#if FG_SRV + const float3 r0 = fg_colour_srv.Load(int3(cbx + x, cby + y0, 0)).xyz; + const float3 r1 = fg_colour_srv.Load(int3(cbx + x, cby + y1, 0)).xyz; + const float3 p0 = fg_texel(cp, 4u, pi0).xyz; + const float3 p1 = fg_texel(cp, 4u, pi1).xyz; + v8f pv; + pv.v[0] = fg_opq(r0.x); pv.v[1] = fg_opq(r0.y); pv.v[2] = fg_opq(r0.z); + pv.v[3] = fg_opq(r1.x); pv.v[4] = fg_opq(r1.y); pv.v[5] = fg_opq(r1.z); + pv.v[6] = 0.0f; pv.v[7] = 0.0f; + const uint4 h = wg_to_f16_ags(pv); + const uint2 pk0 = uint2(h.x, h.y & 0xffffu); + const uint2 pk1 = uint2((h.y >> 16) | (h.z << 16), h.z >> 16); + wg_st64(cc, pi0 * 8u, pk0); + wg_st64(cc, pi1 * 8u, pk1); + const float3 s0 = fg_r3_unpack_colour(pk0); + const float3 s1 = fg_r3_unpack_colour(pk1); + const float dv0 = abs(fg_luma(s0) - fg_luma(p0)); + const float dv1 = abs(fg_luma(s1) - fg_luma(p1)); +#else + const uint2 raw0 = wg_ld64(colour, ((cby + y0) * cw + cbx + x) * 8u); + const uint2 raw1 = wg_ld64(colour, ((cby + y1) * cw + cbx + x) * 8u); + const float3 p0 = fg_texel(cp, 4u, pi0).xyz; + const float3 p1 = fg_texel(cp, 4u, pi1).xyz; + const float3 s0 = fg_r3_unpack_colour(raw0), s1 = fg_r3_unpack_colour(raw1); + uint2 pk0 = uint2(raw0.x, raw0.y & 0xffffu), pk1 = uint2(raw1.x, raw1.y & 0xffffu); + float3 c16_0 = s0, c16_1 = s1; + [branch] if (fg_r3_special_colour(raw0)) { + pk0 = uint2(fg_pack_h2(s0.x, s0.y), fg_f2h(s0.z)); + c16_0 = fg_r3_unpack_colour(pk0); + } + [branch] if (fg_r3_special_colour(raw1)) { + pk1 = uint2(fg_pack_h2(s1.x, s1.y), fg_f2h(s1.z)); + c16_1 = fg_r3_unpack_colour(pk1); + } + wg_st64(cc, pi0 * 8u, pk0); + wg_st64(cc, pi1 * 8u, pk1); + const float dv0 = abs(fg_luma(c16_0) - fg_luma(p0)); + const float dv1 = abs(fg_luma(c16_1) - fg_luma(p1)); +#endif + const float3 row0 = fg_opq3(s0 + QuadReadAcrossX(s0)); + const float pd0 = min(dv0, QuadReadAcrossX(dv0)); + const float3 row1 = fg_opq3(s1 + QuadReadAcrossX(s1)); + const float pd1 = min(dv1, QuadReadAcrossX(dv1)); + const float3 square = fg_opq3(row0 + row1); + const float m = min(pd0, pd1); +#if FG_D == 4 + const float3 strip = fg_opq3(square + QuadReadAcrossY(square)); + const float md = fg_opq(m + QuadReadAcrossY(m)); + c = j2 == 0u ? strip : fg_opq3(c + strip); + d = j2 == 0u ? md : fg_opq(d + md); +#else + c = square; + d = m; +#endif + } + const float3 gathered = WaveReadLaneAt(c, source); + const float gathered_diff = WaveReadLaneAt(d, source); + if (lane / blocks == p) { + result = gathered; + diff = gathered_diff; + } + } +} + +void fg_r3_wave(uint X, uint Y, uint lane, uint mode, out float3 result, out float diff, out bool any_flag) +{ + // Each p visits a contiguous 32-pixel strip. Only the first lane of each + // block supplies the reduction, preserving the left-to-right operand order. + const uint blocks = 32u / FG_D; + const uint source = (lane & (blocks - 1u)) * FG_D; + result = 0.0f; + diff = 0.0f; + uint any = 0u; + [loop] for (uint p = 0u; p < FG_D; ++p) + { + const uint x = FG_D * X + p * 32u + lane; + float3 c = 0.0f, row = 0.0f; + float d = 0.0f, row_diff = 0.0f; + uint mask = 0u; + [loop] for (uint j = 0u; j < FG_D; ++j) + { + float3 s; + float dv; + bool flag; + fg_r3_pixel(x, FG_D * Y + j, mode, s, dv, flag); + const float3 pair = fg_opq3(s + QuadReadAcrossX(s)); + const float pd = min(dv, QuadReadAcrossX(dv)); + mask |= flag ? 1u : 0u; + if ((j & 1u) == 0u) { + row = pair; + row_diff = pd; + } else { + const float3 square = fg_opq3(row + pair); + const float m = min(row_diff, pd); +#if FG_D == 4 + const float3 strip = fg_opq3(square + QuadReadAcrossY(square)); + const float md = fg_opq(m + QuadReadAcrossY(m)); + c = j == 1u ? strip : fg_opq3(c + strip); + d = j == 1u ? md : fg_opq(d + md); +#else + c = square; + d = m; +#endif + } + } + if ((mode & 1u) == 0u && (mode & 6u) != 0u) { + mask |= QuadReadAcrossX(mask); +#if FG_D == 4 + mask |= QuadReadAcrossY(mask); +#endif + } + // Compact the blocks from all strips into one consecutive run of net1 elements. + const float3 gathered = WaveReadLaneAt(c, source); + const float gathered_diff = WaveReadLaneAt(d, source); + const uint gathered_mask = WaveReadLaneAt(mask, source); + if (lane / blocks == p) { + result = gathered; + diff = gathered_diff; + any = gathered_mask; + } + } + any_flag = any != 0u; +} + +void fg_r3_block(uint X, uint Y, uint mode, out float3 sum, out float diff, out bool any_flag) +{ + // A wrapped wave or partial block keeps each lane on its own pixels. + sum = 0.0f; + diff = 0.0f; + any_flag = false; + [loop] for (uint j = 0u; j < FG_D; j += 2u) { + float3 strip = 0.0f; + float strip_diff = 0.0f; + [loop] for (uint i = 0u; i < FG_D; i += 2u) + { + float3 left = 0.0f, top = 0.0f, square = 0.0f; + float left_diff = 0.0f, top_diff = 0.0f, square_diff = 0.0f; + [loop] for (uint q = 0u; q < 4u; ++q) { + const uint x = FG_D * X + i + (q & 1u), y = FG_D * Y + j + (q >> 1u); + float3 s = 0.0f; + float d = 0.0f; + bool flag = false; + if (x < wo && y < ho) fg_r3_pixel(x, y, mode, s, d, flag); + any_flag = any_flag || flag; + if ((q & 1u) == 0u) { + left = s; + left_diff = d; + } else { + const float3 row = fg_opq3(left + s); + const float row_diff = min(left_diff, d); + if (q == 1u) { + top = row; + top_diff = row_diff; + } else { + square = fg_opq3(top + row); + square_diff = min(top_diff, row_diff); + } + } + } + strip = i == 0u ? square : fg_opq3(strip + square); + strip_diff = i == 0u ? square_diff : fg_opq(strip_diff + square_diff); + } + sum = j == 0u ? strip : fg_opq3(sum + strip); + diff = j == 0u ? strip_diff : fg_opq(diff + strip_diff); + } +} + +#if FG_HUD_TILE +WG_KERNEL(fg_lite_downsample) +{ + FG_SETUP(); + const uint tile = wg_block_id(), lane = wg_lane_id(), tiles_x = (wo + 31u) / 32u; + const uint2 base = uint2((tile % tiles_x) * 32u, (tile / tiles_x) * 8u); + fg_hud_origin = int2(base) - 1; + for (uint i = lane; i < fg_hud_tile_w * fg_hud_tile_h; i += 256u) { + const int2 p = clamp(fg_hud_origin + int2(i % fg_hud_tile_w, i / fg_hud_tile_w), 0, int2(hw, hh) - 1); + const float3 c = fg_r3_hud_texel(p.x, p.y); + fg_hud_r[i] = c.x; + fg_hud_g[i] = c.y; + fg_hud_b[i] = c.z; + } + wg_barrier_lds(); + const uint q = lane & 3u; + const uint2 p = base + uint2(((lane >> 2u) & 15u) * 2u + (q & 1u), (lane >> 6u) * 2u + (q >> 1u)); + float3 s = 0.0f; + float dv = 0.0f; + bool flag = false; + // The executor selects this entry only for the Lite flag 2 paths. + const uint mode = (flags & 6u) | 16u; + if (p.x < wo && p.y < ho) fg_r3_pixel(p.x, p.y, mode, s, dv, flag); + float3 pair = fg_opq3(s + QuadReadAcrossX(s)); + float d = min(dv, QuadReadAcrossX(dv)); + uint f = flag ? 1u : 0u; + f |= QuadReadAcrossX(f); + pair = fg_opq3(pair + QuadReadAcrossY(pair)); + d = min(d, QuadReadAcrossY(d)); + f |= QuadReadAcrossY(f); + if (q == 0u) fg_r3_write(p.x >> 1u, p.y >> 1u, pair, d, f != 0u, mode); +} +#else WG_KERNEL(fg_lite_downsample) { FG_SETUP(); const uint nbx = (wo + FG_D - 1u) / FG_D, nby = (ho + FG_D - 1u) / FG_D; const uint idx = wg_block_id() * 256u + wg_lane_id(); if (idx >= nbx * nby) return; - const uint X = idx % nbx, Y = idx / nbx; - float3 s[FG_D * FG_D]; - float df[FG_D * FG_D]; - bool any = false; - [unroll] for (uint j = 0u; j < FG_D; ++j) - [unroll] for (uint i = 0u; i < FG_D; ++i) - { - const uint x = FG_D * X + i, y = FG_D * Y + j; - float3 sv = float3(0.0f, 0.0f, 0.0f); - float dv = 0.0f; - bool fv = false; - if (x < wo && y < ho) fg_r3_pixel(x, y, sv, dv, fv); - s[j * FG_D + i] = sv; - df[j * FG_D + i] = dv; - any = any || fv; + const uint2 xy = fg_lite_tile_pixel(idx, nbx, nby); + const uint X = xy.x, Y = xy.y; + const uint lane = wg_wave_lane(), Xbase = WaveReadLaneFirst(X); + const uint mode = (uint)wg_uniform((int)flags); + float3 sum; + float diff; + bool any_flag; + if (WaveActiveAllEqual(Y) && FG_D * (Xbase + 32u) <= wo && FG_D * (Y + 1u) <= ho) + { + [branch] if ((mode & 7u) == 0u) { + fg_r3_wave_m0(Xbase, Y, lane, sum, diff); + any_flag = false; + } else { + fg_r3_wave(Xbase, Y, lane, mode, sum, diff, any_flag); } - if (X >= wd || Y >= hd) return; - float3 dcv; - float ldv; -#if FG_D == 2 - dcv = float3(fg_mul(fg_opq(fg_opq(s[0].x + s[1].x) + fg_opq(s[2].x + s[3].x)), 0.25f), - fg_mul(fg_opq(fg_opq(s[0].y + s[1].y) + fg_opq(s[2].y + s[3].y)), 0.25f), - fg_mul(fg_opq(fg_opq(s[0].z + s[1].z) + fg_opq(s[2].z + s[3].z)), 0.25f)); - ldv = min(min(df[0], df[1]), min(df[2], df[3])); -#else - // colour: pairs over x + 1, then y + 1, then x + 2, then y + 2 - float3 a[8]; // a(i, j), i in {0, 2} -> 0 / 1, j = 0..3: a[j * 2 + i / 2] - [unroll] for (uint jj = 0u; jj < 4u; ++jj) - [unroll] for (uint ii = 0u; ii < 2u; ++ii) - a[jj * 2u + ii] = fg_opq3(s[jj * 4u + 2u * ii] + s[jj * 4u + 2u * ii + 1u]); - float3 b[4]; // b(i, j), j in {0, 2} - [unroll] for (uint jb = 0u; jb < 2u; ++jb) - [unroll] for (uint ib = 0u; ib < 2u; ++ib) - b[jb * 2u + ib] = fg_opq3(a[(2u * jb) * 2u + ib] + a[(2u * jb + 1u) * 2u + ib]); - const float3 c0 = fg_opq3(b[0] + b[1]), c2 = fg_opq3(b[2] + b[3]); - const float3 e = fg_opq3(c0 + c2); - dcv = float3(fg_mul(e.x, 0.0625f), fg_mul(e.y, 0.0625f), fg_mul(e.z, 0.0625f)); - float m1[8]; - [unroll] for (uint jm = 0u; jm < 4u; ++jm) - [unroll] for (uint im = 0u; im < 2u; ++im) - m1[jm * 2u + im] = min(df[jm * 4u + 2u * im], df[jm * 4u + 2u * im + 1u]); - float m2[4]; - [unroll] for (uint jn = 0u; jn < 2u; ++jn) - [unroll] for (uint in_ = 0u; in_ < 2u; ++in_) - m2[jn * 2u + in_] = min(m1[(2u * jn) * 2u + in_], m1[(2u * jn + 1u) * 2u + in_]); - const float s0 = fg_opq(m2[0] + m2[1]), s2 = fg_opq(m2[2] + m2[3]); - ldv = fg_mul(fg_opq(s0 + s2), 0.25f); + } + else + { + fg_r3_block(X, Y, mode, sum, diff, any_flag); + } +#if FG_D == 4 + diff = fg_mul(diff, 0.25f); #endif - const uint ni = Y * wd + X; - fg_st_h4(dc, ni, float4(dcv, 0.0f)); - fg_st_h1(ld, ni, ldv); - const bool F1 = (flags & 1u) != 0u, A = (flags & 2u) != 0u, Hd = (flags & 4u) != 0u; - if (!F1 && (A || Hd)) fg_st_h1(um, ni, any ? 1.0f : 0.0f); + fg_r3_write(X, Y, sum, diff, any_flag, mode); } +#endif diff --git a/clean/dx12/kernels/fg_lite_r4.hlsl b/clean/dx12/kernels/fg_lite_r4.hlsl index 80c9adf2..ff6dffc7 100644 --- a/clean/dx12/kernels/fg_lite_r4.hlsl +++ b/clean/dx12/kernels/fg_lite_r4.hlsl @@ -5,9 +5,15 @@ // motion scales (float32 x 2). D3D12 only. // // @wg-kernel fg_lite_mvec co=- block=256 wave=32 args=p,u,u,u,u,u,u,u,u,u,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,p,p,u,u,u,u,u,u +// @wg-kernel fg_lite_mvec_srv co=- entry=fg_lite_mvec block=256 wave=32 args=p,u,u,u,u,u,u,u,u,u,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,p,p,u,u,u,u,u,u rs=direct defines=FG_SRV=1 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" +#if FG_SRV +Texture2D fg_depth_srv : register(t0); +Texture2D fg_motion_srv : register(t1); +#endif + WG_ARGS_BEGIN uint depth, dw, dh; FG_REGION_ARGS(d) @@ -21,7 +27,14 @@ WG_KERNEL(fg_lite_mvec) FG_SETUP(); const uint idx = wg_block_id() * 256u + wg_lane_id(); if (idx >= w1 * h1) return; +#if FG_SRV + const uint2 xy = fg_lite_tile_pixel(idx, w1, h1); + const uint x = xy.x, y = xy.y; + const uint dst = y * w1 + x; +#else const uint x = idx % w1, y = idx / w1; + const uint dst = idx; +#endif const float u = fg_centre(x, w1), v = fg_centre(y, h1); const FgRegion dr = FG_REGION(d); const float dx = fg_rcp(dr.ew), dy = fg_rcp(dr.eh); @@ -33,15 +46,23 @@ WG_KERNEL(fg_lite_mvec) [unroll] for (uint i = 0u; i < 5u; ++i) { const float2 XY = fg_region_xy(dr, u + ox[i], v + oy[i], true); +#if FG_SRV + const float di = fg_depth_srv.Load(int3(fg_nearest_index(XY.x, (int)dw), fg_nearest_index(XY.y, (int)dh), 0)).x; +#else const float di = fg_read_nearest(depth, 6u, (int)dw, (int)dh, XY.x, XY.y).x; +#endif const float ki = fg_depth_key(di, sk, inverted); if (i == 0u) { b = di; kb = ki; } else if (ki < kb) { b = di; kb = ki; sel = i; } } const float z = fg_sat(b); const float sx = ox[sel], sy = oy[sel]; - wg_st32(zc, idx * 4u, fg_pack_depth(z, sx > 0.0f, sy > 0.0f, sel == 0u)); + wg_st32(zc, dst * 4u, fg_pack_depth(z, sx > 0.0f, sy > 0.0f, sel == 0u)); const float2 MXY = fg_region_xy(FG_REGION(m), u + sx, v + sy, true); - const float4 m = fg_read_nearest(motion, 5u, (int)mw, (int)mh, MXY.x, MXY.y); - wg_st64(mv, idx * 8u, uint2(asuint(fg_mul(m.x, asfloat(scx))), asuint(fg_mul(m.y, asfloat(scy))))); +#if FG_SRV + const float2 m = fg_motion_srv.Load(int3(fg_nearest_index(MXY.x, (int)mw), fg_nearest_index(MXY.y, (int)mh), 0)).xy; +#else + const float2 m = fg_read_nearest(motion, 5u, (int)mw, (int)mh, MXY.x, MXY.y).xy; +#endif + wg_st64(mv, dst * 8u, uint2(asuint(fg_mul(m.x, asfloat(scx))), asuint(fg_mul(m.y, asfloat(scy))))); } diff --git a/clean/dx12/kernels/fg_mconv.hlsl b/clean/dx12/kernels/fg_mconv.hlsl index 9f337998..7e78afa8 100644 --- a/clean/dx12/kernels/fg_mconv.hlsl +++ b/clean/dx12/kernels/fg_mconv.hlsl @@ -2,28 +2,36 @@ // D3D12 port of frame generation's matrix convolution (issue #96; tier B of the net1 fast path): fg_mconv of // fg_net1_mma.co (clean/fg/kernels/fg_net1_mma.hip), byte-identical to HIP: the same fragments and chunk order, // v_wmma_f32_16x16x16_f16 through the driver channel (wg_wmma_f16) with the float16 accumulator as C, its result rounded -// to float16 after every chunk (wg_f2h = v_cvt_f16_f32, nearest even), the leaky ReLU of fg_fast16.h (fg_leaky16's -// bits) and the exact pool (fg_exact16.h). Driver rules (clean/dx12/README.md): every load of a chunk before its first matrix call; branchless -// selects; the chunk loop bound through an opaque zero (no forced unrolling); store pointers through wg_uniform(). +// to float16 after every chunk (wg_to_f16_ags, nearest even), followed by the exact leaky ReLU and pool. The +// BlockKxKy variants stage one channel block's 3 x 3 halo in LDS. Workgroups of up to 128 lanes unroll the nine +// taps within each staged channel block. Other paths keep the chunk loop bound opaque. Issue all loads for a +// chunk before its first matrix call and keep store pointers uniform (clean/dx12/README.md). // Built only when --only names the kernels (fg_ kernels are in no model's set). // -// @wg-kernel fg_mconv1 co=fg_net1_mma.co entry=fg_mconv block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1 -// @wg-kernel fg_mconv2 co=fg_net1_mma.co entry=fg_mconv block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2 -// @wg-kernel fg_mconv4 co=fg_net1_mma.co entry=fg_mconv block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=4 +// @wg-kernel fg_mconv1 co=fg_net1_mma.co entry=fg_mconv block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,WG_LD_A16=1 +// @wg-kernel fg_mconv2 co=fg_net1_mma.co entry=fg_mconv block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,WG_LD_A16=1,FG_HALO=1 +// @wg-kernel fg_mconv4 co=fg_net1_mma.co entry=fg_mconv block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=4,WG_LD_A16=1 +// @wg-kernel fg_mconv2_narrow co=fg_net1_mma.co entry=fg_mconv block=64 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,WG_LD_A16=1,FG_HALO=1 +// @wg-kernel fg_mconv1_late co=fg_net1_mma.co entry=fg_mconv block=64 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,WG_LD_A16=1,FG_HALO=1 +// @wg-kernel fg_mconv2_mid co=fg_net1_mma.co entry=fg_mconv block=128 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,WG_LD_A16=1,FG_HALO=1 #include "wg_platform.hlsli" #define FG_FN #define FG_I64 int64_t #define FG_FBH32(v) firstbithigh((uint)(v)) #include "../../fg/kernels/fg_exact16.h" -#define FG_F2H(f) wg_f2h(f) -#define FG_H2F(h) wg_h2f(h) -#define FG_SEL(c, a, b) select(c, a, b) -#include "../../fg/kernels/fg_fast16.h" #ifndef FG_MT #define FG_MT 4 #endif +#define FG_TH (2 * (WG_BLOCK / 32)) +#ifndef FG_HALO +#define FG_HALO 0 +#endif +#if FG_HALO +#define FG_HALO_PX (18 * (FG_TH + 2)) +groupshared uint4 fg_halo[2 * FG_HALO_PX]; +#endif WG_ARGS_BEGIN uint x, wf, b, y, p; // pointers (arena byte offsets) @@ -38,21 +46,167 @@ uint fg_half(uint4 u, uint j) const uint d = select(j < 2u, u.x, select(j < 4u, u.y, select(j < 6u, u.z, u.w))); return (d >> ((j & 1u) * 16u)) & 0xffffu; } -// 8 packed float16 values -> the float32 accumulator fragment (exact) +// 8 packed float16 values -> the float32 accumulator fragment (exact; mask-free low halves via f16tof32) v8f fg_widen(uint4 hp) { v8f r; - [unroll] for (uint v = 0; v < 8; ++v) r.v[v] = wg_h2f(fg_half(hp, v)); + r.v[0] = f16tof32(hp.x); r.v[1] = wg_h2f_hi(hp.x); + r.v[2] = f16tof32(hp.y); r.v[3] = wg_h2f_hi(hp.y); + r.v[4] = f16tof32(hp.z); r.v[5] = wg_h2f_hi(hp.z); + r.v[6] = f16tof32(hp.w); r.v[7] = wg_h2f_hi(hp.w); return r; } -// One chunk (tier B): the matrix instruction, then the whole fragment rounded to float16 by the driver channel's -// conversion (v_cvt_f16_f32, nearest even: HIP's (_Float16) of each element; the software wg_f2h costs ~20 instructions -// per element on this driver, where a (half) cast rounds toward zero). hp keeps the packed float16 accumulator. -void fg_chunk_b(uint4 av, uint4 bv, inout v8f c, inout uint4 hp) +// Software-pipelined Tier B chunks across (mt = 0..FG_MT-1, nt = 0..1): overlaps fg_widen (8x v_cvt_f32_f16) +// and wg_to_f16_ags (8x v_cvt_f16_f32) directly with independent wg_wmma_f16 ops (only 2 v8f live; bit-identical). +void fg_chunk_b_pipe(uint4 fa[FG_MT], uint4 fb[2], inout uint4 h16[FG_MT][2]) +{ + const int N = FG_MT * 2; + v8f w_next = fg_widen(h16[0][0]); + v8f d_prev = w_next; + [unroll] for (int s = 0; s < N; ++s) { + const v8f d_cur = wg_wmma_f16(fa[s >> 1], fb[s & 1], w_next); + if (s > 0) h16[(s - 1) >> 1][(s - 1) & 1] = wg_to_f16_ags(d_prev); + if (s + 1 < N) w_next = fg_widen(h16[(s + 1) >> 1][(s + 1) & 1]); + d_prev = d_cur; + } + h16[(N - 1) >> 1][(N - 1) & 1] = wg_to_f16_ags(d_prev); +} + +#if FG_HALO +void fg_stage_halo(int tx, int ty, int cb) +{ + for (int i = (int)wg_lane_id(); i < 2 * FG_HALO_PX; i += WG_BLOCK) { + const int p = i / 2, frag = i % 2; + const int sx = tx * 16 + p % 18 - 1, sy = ty * FG_TH + p / 18 - 1; + const bool inside = sx >= 0 && sx < W && sy >= 0 && sy < H; + const uint e = inside ? (uint)((sy * W + sx) * cin + cb * 16 + frag * 8) : 0u; + fg_halo[frag * FG_HALO_PX + p] = wg_ld128(x, e * 2u) & select(inside, ~0u, 0u); + } + wg_barrier_lds(); +} +#endif + +#if FG_HALO && WG_BLOCK <= 128 +void fg_accumulate_halo(int tx, int ty, int mg, int n, int hh, int wy, uint lane, inout uint4 h16[FG_MT][2]) +{ + const int nb = cin / 16; + const int nq = nb * 9; + const int pixel = hh * FG_HALO_PX + wy * 18 + n; + for (int cb = 0; cb < nb; ++cb) { + // Finish reading this block's final tap before overwriting the halo. + if (cb != 0) wg_barrier_lds(); + fg_stage_halo(tx, ty, cb); + // Software-pipeline tap loads with WMMAs: prefetch tap+1's weight/halo fragments before tap's WMMAs. + uint4 fb[2], fa[FG_MT]; + { + fb[0] = fg_halo[pixel]; + fb[1] = fg_halo[pixel + 18]; + [unroll] for (int mt = 0; mt < FG_MT; ++mt) + fa[mt] = wg_ld128(wf, (uint)((((mg * FG_MT + mt) * nq + cb * 9) * 32 + (int)lane) * 16)); + } + [unroll] for (int tap = 0; tap < 9; ++tap) { + uint4 fb_n[2], fa_n[FG_MT]; + if (tap + 1 < 9) { + const int nt = tap + 1; + const int qn = cb * 9 + nt; + const int ppn = pixel + 18 * (nt % 3) + nt / 3; + fb_n[0] = fg_halo[ppn]; + fb_n[1] = fg_halo[ppn + 18]; + [unroll] for (int mt = 0; mt < FG_MT; ++mt) + fa_n[mt] = wg_ld128(wf, (uint)((((mg * FG_MT + mt) * nq + qn) * 32 + (int)lane) * 16)); + } + fg_chunk_b_pipe(fa, fb, h16); + if (tap + 1 < 9) { + fb[0] = fb_n[0]; fb[1] = fb_n[1]; + [unroll] for (int mt2 = 0; mt2 < FG_MT; ++mt2) fa[mt2] = fa_n[mt2]; + } + } + } +} +#endif + +void fg_accumulate(int tx, int ty, int mg, int n, int hh, int wy, uint lane, + bool staged, inout uint4 h16[FG_MT][2]) +{ + const int px = tx * 16 + n, py0 = ty * FG_TH + wy; + const int pad = k / 2, nb = cin / 16, nq = nb * k * k; + const int nq_loop = nq + (int)fg_opq0(); + const bool one_tap = order == 0, block_first = order == 1; + int cb = 0, ky = 0, kx = 0; + for (int q = 0; q < nq_loop; ++q) { +#if FG_HALO + if (staged && kx == 0 && ky == 0) { + // The old block's final tap must finish reading before the next block overwrites it. + if (cb != 0) wg_barrier_lds(); + fg_stage_halo(tx, ty, cb); + } +#endif + uint4 fb[2], fa[FG_MT]; + const int sx = px + kx - pad; + [unroll] for (int nt = 0; nt < 2; ++nt) { +#if FG_HALO + if (staged) { + fb[nt] = fg_halo[hh * FG_HALO_PX + (wy + nt + ky) * 18 + n + kx]; + } else +#endif + { + const int sy = py0 + nt + ky - pad; + const bool inb = and(and(sx >= 0, sx < W), and(sy >= 0, sy < H)); + const uint e = select(inb, (uint)((sy * W + sx) * cin + cb * 16 + 8 * hh), 0u); + const uint4 u = wg_ld128(x, e * 2u); + fb[nt] = u & select(inb, ~0u, 0u); + } + } + [unroll] for (int mt2 = 0; mt2 < FG_MT; ++mt2) + fa[mt2] = wg_ld128(wf, (uint)((((mg * FG_MT + mt2) * nq + q) * 32 + (int)lane) * 16)); + fg_chunk_b_pipe(fa, fb, h16); + + // ky varies fastest in both spatial orders. The middle digit is kx for + // block_kx_ky and cb for kx_block_ky. The 1 x 1 path just advances cb. + const bool next_ky = ky + 1 == k; + const bool next_kx = kx + 1 == k; + const bool next_cb = cb + 1 == nb; + const bool step_x = !one_tap && next_ky && (block_first || next_cb); + const bool step_c = one_tap || (next_ky && (!block_first || next_kx)); + ky = select(one_tap || next_ky, 0, ky + 1); + kx = select(step_x, select(next_kx, 0, kx + 1), kx); + cb = select(step_c, select(!one_tap && !block_first && next_cb, 0, cb + 1), cb); + } +} + +uint fg_leaky2(uint packed) +{ + const half2 slope = asfloat16((uint16_t)FG_LEAKY_SLOPE16); + const half2 negzero = asfloat16((uint16_t)(0x8000u | fg_opq0())); + const uint scaled = wg_h2_bits(mad(slope, wg_as_h2(packed), negzero)); + const uint lo = packed & 0xffffu, hi = packed >> 16; + // Positive values, zeros and NaNs keep their incoming bits. For negative numbers the scaled value wins. + const uint mask = select(lo > 0x8000u && lo <= 0xfc00u, 0xffffu, 0u) | + select(hi > 0x8000u && hi <= 0xfc00u, 0xffff0000u, 0u); + return (packed & ~mask) | (scaled & mask); +} + +uint4 fg_leaky8(uint4 bits) +{ + return uint4(fg_leaky2(bits.x), fg_leaky2(bits.y), fg_leaky2(bits.z), fg_leaky2(bits.w)); +} + +// A finite maximum with +0 ranked above -0 gives the same zero sign as the spec's two products and sum. +// A NaN or any negative infinity is invalid, as is a second positive infinity (0 * infinity). +uint fg_ordered_half(uint bits) { - const v8f d = wg_wmma_f16(av, bv, c); - hp = wg_to_f16_ags(d); - c = fg_widen(hp); + return bits ^ select(bits < 0x8000u, 0x8000u, 0xffffu); +} + +uint fg_pool4(uint a, uint b, uint c, uint d) +{ + const uint ka = fg_ordered_half(a), kb = fg_ordered_half(b); + const uint kc = fg_ordered_half(c), kd = fg_ordered_half(d); + const uint top = max(max(ka, kb), max(kc, kd)); + const bool invalid = min(min(ka, kb), min(kc, kd)) <= 0x03ffu || + top > 0xfc00u || + ((uint)(a == 0x7c00u) + (uint)(b == 0x7c00u) + (uint)(c == 0x7c00u) + (uint)(d == 0x7c00u) > 1u); + return select(invalid, FG_NAN16, top ^ select(top >= 0x8000u, 0x8000u, 0xffffu)); } WG_KERNEL(fg_mconv) @@ -64,62 +218,38 @@ WG_KERNEL(fg_mconv) const int ty = rest % tiles_y, mg = rest / tiles_y; const int n = (int)(lane & 15u), hh = (int)(lane >> 4); const int px = tx * 16 + n; - const int py0 = ty * 16 + 2 * (int)wave; - const int pad = k / 2, nb = cin / 16, taps = k * k, nq = nb * taps; + const int wy = 2 * (int)wave, py0 = ty * FG_TH + wy; const uint py = (uint)wg_uniform((int)y), pp = (uint)wg_uniform((int)p); - v8f a32[FG_MT][2]; - uint4 h16[FG_MT][2]; // the same accumulator as packed float16 + uint4 h16[FG_MT][2]; // one packed float16 accumulator per output fragment [unroll] for (int mt = 0; mt < FG_MT; ++mt) { const int o0 = (mg * FG_MT + mt) * 16 + 8 * hh; - uint bb[8]; - [unroll] for (uint v = 0; v < 8; ++v) bb[v] = wg_ld16(b, (uint)(o0 + (int)v) * 2u); - h16[mt][0] = fg_pack8(bb); + h16[mt][0] = wg_ld128(b, (uint)o0 * 2u); h16[mt][1] = h16[mt][0]; - a32[mt][0] = fg_widen(h16[mt][0]); - a32[mt][1] = a32[mt][0]; } - const int nq_loop = nq + (int)fg_opq0(); - for (int q = 0; q < nq_loop; ++q) { - // the chunk's (channel block, ky, kx) in the layer's order, branchless - const int t1 = q % taps, cb1 = q / taps; - const int kx2 = q / (nb * k), r2 = q % (nb * k); - const int cb = select(order == 0, q, select(order == 1, cb1, r2 / k)); - const int kx = select(order == 0, 0, select(order == 1, t1 / k, kx2)); - const int ky = select(order == 0, 0, select(order == 1, t1 % k, r2 % k)); - uint4 fb[2], fa[FG_MT]; - const int sx = px + kx - pad; - [unroll] for (int nt = 0; nt < 2; ++nt) { - const int sy = py0 + nt + ky - pad; - const bool inb = and(and(sx >= 0, sx < W), and(sy >= 0, sy < H)); - const uint e = select(inb, (uint)((sy * W + sx) * cin + cb * 16 + 8 * hh), 0u); - const uint4 u = wg_ld128(x, e * 2u); - fb[nt] = uint4(select(inb, u.x, 0u), select(inb, u.y, 0u), select(inb, u.z, 0u), select(inb, u.w, 0u)); - } - [unroll] for (int mt2 = 0; mt2 < FG_MT; ++mt2) - fa[mt2] = wg_ld128(wf, (uint)((((mg * FG_MT + mt2) * nq + q) * 32 + (int)lane) * 16)); - [unroll] for (int mt3 = 0; mt3 < FG_MT; ++mt3) - [unroll] for (int nt2 = 0; nt2 < 2; ++nt2) fg_chunk_b(fa[mt3], fb[nt2], a32[mt3][nt2], h16[mt3][nt2]); +#if FG_HALO + if (k == 3 && order == 1) { +#if WG_BLOCK <= 128 + fg_accumulate_halo(tx, ty, mg, n, hh, wy, lane, h16); +#else + fg_accumulate(tx, ty, mg, n, hh, wy, lane, true, h16); +#endif + } else +#endif + { + fg_accumulate(tx, ty, mg, n, hh, wy, lane, false, h16); } [unroll] for (int mt4 = 0; mt4 < FG_MT; ++mt4) { const int o0 = (mg * FG_MT + mt4) * 16 + 8 * hh; - uint r0[8], r1[8]; - [unroll] for (uint v4 = 0; v4 < 8; ++v4) { - const uint h0 = fg_half(h16[mt4][0], v4), h1 = fg_half(h16[mt4][1], v4); - r0[v4] = select(act == 1, fg_leaky_fast16(h0), h0); - r1[v4] = select(act == 1, fg_leaky_fast16(h1), h1); - } - if (px < W && py0 < H) wg_st128(py, (uint)((py0 * W + px) * cout + o0) * 2u, fg_pack8(r0)); - if (px < W && py0 + 1 < H) wg_st128(py, (uint)(((py0 + 1) * W + px) * cout + o0) * 2u, fg_pack8(r1)); + const uint4 r0 = act == 1 ? fg_leaky8(h16[mt4][0]) : h16[mt4][0]; + const uint4 r1 = act == 1 ? fg_leaky8(h16[mt4][1]) : h16[mt4][1]; + if (px < W && py0 < H) wg_st128(py, (uint)((py0 * W + px) * cout + o0) * 2u, r0); + if (px < W && py0 + 1 < H) wg_st128(py, (uint)(((py0 + 1) * W + px) * cout + o0) * 2u, r1); if (pool == 1) { uint m[8]; [unroll] for (uint v5 = 0; v5 < 8; ++v5) { - const uint x01 = wg_xor_u(r0[v5], 1u), x11 = wg_xor_u(r1[v5], 1u); - uint t = r0[v5]; - t = fg_pool_step16(t, x01); - t = fg_pool_step16(t, r1[v5]); - t = fg_pool_step16(t, x11); - m[v5] = t; + const uint h0 = fg_half(r0, v5), h1 = fg_half(r1, v5); + m[v5] = fg_pool4(h0, wg_xor_u(h0, 1u), h1, wg_xor_u(h1, 1u)); } const int Ho = H / 2, Wo = W / 2, ox = px / 2, oy = py0 / 2; if ((n & 1) == 0 && ox < Wo && oy < Ho) wg_st128(pp, (uint)((oy * Wo + ox) * cout + o0) * 2u, fg_pack8(m)); diff --git a/clean/dx12/kernels/fg_mpair.hlsl b/clean/dx12/kernels/fg_mpair.hlsl index 46c56eb3..8a04f8f0 100644 --- a/clean/dx12/kernels/fg_mpair.hlsl +++ b/clean/dx12/kernels/fg_mpair.hlsl @@ -7,22 +7,25 @@ // loads before the matrix calls of a group, branchless selects, runtime loop bounds through an opaque zero, the store // pointer through wg_uniform(). Built only when --only names the kernels. // -// @wg-kernel fg_mpair_b co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=0,FG_C1T=32,FG_C2T=16,FG_NT=1,FG_LAZY=1 -// @wg-kernel fg_mpair_d4 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=16,FG_C2T=8,FG_NT=1,FG_LAZY=1,FG_CINT=16 -// @wg-kernel fg_mpair_d3 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=8,FG_C2T=8,FG_NT=1,FG_LAZY=0 -// @wg-kernel fg_mpair_d2 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=8,FG_C2T=4,FG_NT=1,FG_LAZY=0 -// @wg-kernel fg_mpair_d1 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=4,FG_C2T=2,FG_NT=2,FG_LAZY=0 -// @wg-kernel fg_mpair_d0 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=2,FG_C2T=1,FG_NT=2,FG_LAZY=0 +// @wg-kernel fg_mpair_b co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=0,FG_C1T=32,FG_C2T=16,FG_NT=1,FG_LAZY=1,WG_LD_A16=1 +// @wg-kernel fg_mpair_d4 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=16,FG_C2T=8,FG_NT=1,FG_LAZY=1,FG_CINT=16,WG_LD_A16=1 +// @wg-kernel fg_mpair_d3 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=8,FG_C2T=8,FG_NT=1,FG_LAZY=0,WG_LD_A16=1 +// @wg-kernel fg_mpair_d2 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=8,FG_C2T=4,FG_NT=1,FG_LAZY=0,WG_LD_A16=1 +// @wg-kernel fg_mpair_d1 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=4,FG_C2T=2,FG_NT=2,FG_LAZY=0,FG_NATIVE_PAIR=1,WG_LD_A16=1 +// @wg-kernel fg_mpair_d0 co=fg_net1_mma.co entry=fg_mpair block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=2,FG_C2T=1,FG_NT=2,FG_LAZY=0,FG_NATIVE_PAIR=1,WG_LD_A16=1 +// @wg-kernel fg_mpair_d3_narrow co=fg_net1_mma.co entry=fg_mpair block=64 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=8,FG_C2T=8,FG_NT=1,FG_LAZY=0,FG_NATIVE_PAIR=1,WG_LD_A16=1 +// @wg-kernel fg_mpair_d2_narrow co=fg_net1_mma.co entry=fg_mpair block=64 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=8,FG_C2T=4,FG_NT=1,FG_LAZY=0,FG_NATIVE_PAIR=1,WG_LD_A16=1 +// @wg-kernel fg_mpair_b_first co=fg_net1_mma.co entry=fg_mpair block=64 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=0,FG_C1T=32,FG_C2T=16,FG_NT=1,FG_LAZY=1,FG_PAIR_PASS=1,FG_PASS_MT=2,FG_NATIVE_PAIR=1,WG_LD_A16=1 +// @wg-kernel fg_mpair_b_second co=fg_net1_mma.co entry=fg_mpair block=64 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=0,FG_C1T=32,FG_C2T=16,FG_NT=1,FG_LAZY=1,FG_PAIR_PASS=2,FG_PASS_MT=2,FG_NATIVE_PAIR=1,WG_LD_A16=1 +// @wg-kernel fg_mpair_d4_first co=fg_net1_mma.co entry=fg_mpair block=64 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=16,FG_C2T=8,FG_NT=1,FG_LAZY=1,FG_PAIR_PASS=1,FG_PASS_MT=2,FG_NATIVE_PAIR=1,WG_LD_A16=1 +// @wg-kernel fg_mpair_d4_second co=fg_net1_mma.co entry=fg_mpair block=64 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u defines=FG_MODE=1,FG_C1T=16,FG_C2T=8,FG_NT=1,FG_LAZY=1,FG_PAIR_PASS=2,FG_PASS_MT=2,FG_NATIVE_PAIR=1,WG_LD_A16=1 #include "wg_platform.hlsli" +#include "fg_fp16.hlsli" #define FG_FN #define FG_I64 int64_t #define FG_FBH32(v) firstbithigh((uint)(v)) #include "../../fg/kernels/fg_exact16.h" -#define FG_F2H(f) wg_f2h(f) -#define FG_H2F(h) wg_h2f(h) -#define FG_SEL(c, a, b) select(c, a, b) -#include "../../fg/kernels/fg_fast16.h" #ifndef FG_MODE #define FG_MODE 1 @@ -31,6 +34,7 @@ #define FG_NT 2 #define FG_LAZY 0 #endif +#define FG_C2_BATCH 4 WG_ARGS_BEGIN uint x, a, wf1, b1, wf2, b2, y; // pointers (arena byte offsets) @@ -50,16 +54,11 @@ FgTap fg_axis(float r, int o, int n_in) t.i0 = (int)s; t.i1 = (int)(s + 1.0f); if (t.i1 >= n_in) { t.i0 = n_in - 1; t.i1 = n_in - 1; } - t.w1 = wg_h2f(wg_f2h(s - (float)t.i0)); - t.w0 = wg_h2f(wg_f2h(((float)t.i0 - s) + 1.0f)); + t.w1 = wg_h2f(fg_f2h(s - (float)t.i0)); + t.w0 = wg_h2f(fg_f2h(((float)t.i0 - s) + 1.0f)); return t; } -float fg_lerp16(float wa, float av, float wb, float bv) -{ - return wg_h2f(wg_f2h(wg_h2f(wg_f2h(wa * av)) + wg_h2f(wg_f2h(wb * bv)))); -} - uint fg_half(uint4 u, uint j) { const uint d = select(j < 2u, u.x, select(j < 4u, u.y, select(j < 6u, u.z, u.w))); @@ -78,9 +77,24 @@ uint4 fg_f2h8(float m[8]) return wg_to_f16_ags(t); } +#if FG_NATIVE_PAIR +uint fg_lerp2(half2 wa, uint a, half2 wb, uint b) +{ + const half nz = asfloat16((uint16_t)(0x8000u | fg_opq0())); + const half2 first = mad(wa, wg_as_h2(a), nz.xx); + const half2 second = mad(wb, wg_as_h2(b), nz.xx); + return wg_h2_bits(first + second); +} +#endif + // h(h(wa * a_j) + h(wb * b_j)) for the 8 channels of two packed fragments (fg_lerp16 per channel) uint4 fg_lerp16x8(float wa, uint4 av, float wb, uint4 bv) { +#if FG_NATIVE_PAIR + const half2 a = (half)wa, b = (half)wb; + return uint4(fg_lerp2(a, av.x, b, bv.x), fg_lerp2(a, av.y, b, bv.y), + fg_lerp2(a, av.z, b, bv.z), fg_lerp2(a, av.w, b, bv.w)); +#else float m[8]; [unroll] for (uint i = 0; i < 8; ++i) m[i] = wa * wg_h2f(fg_half(av, i)); const uint4 pa = fg_f2h8(m); @@ -88,6 +102,7 @@ uint4 fg_lerp16x8(float wa, uint4 av, float wb, uint4 bv) const uint4 pb = fg_f2h8(m); [unroll] for (uint i3 = 0; i3 < 8; ++i3) m[i3] = wg_h2f(fg_half(pa, i3)) + wg_h2f(fg_half(pb, i3)); return fg_f2h8(m); +#endif } // the 8 channels with every NaN as 0x7E00 @@ -113,54 +128,124 @@ uint4 fg_pair_in(int pc, int c0, FgTap tx, FgTap ty) const uint4 top = fg_lerp16x8(tx.w0, q00, tx.w1, q01); const uint4 bot = fg_lerp16x8(tx.w0, q10, tx.w1, q11); const uint4 u = fg_canon8(fg_lerp16x8(ty.w0, top, ty.w1, bot)); +#if FG_NATIVE_PAIR + return fg_canon8(uint4(wg_h2_bits(wg_as_h2(u.x) + wg_as_h2(sk.x)), wg_h2_bits(wg_as_h2(u.y) + wg_as_h2(sk.y)), + wg_h2_bits(wg_as_h2(u.z) + wg_as_h2(sk.z)), wg_h2_bits(wg_as_h2(u.w) + wg_as_h2(sk.w)))); +#else float m[8]; [unroll] for (uint i = 0; i < 8; ++i) m[i] = wg_h2f(fg_half(u, i)) + wg_h2f(fg_half(sk, i)); return fg_canon8(fg_f2h8(m)); #endif +#endif } -// 8 packed float16 values -> the float32 accumulator fragment (exact) +// 8 packed float16 values -> the float32 accumulator fragment (exact; mask-free low halves via f16tof32) v8f fg_widen(uint4 hp) { v8f r; - [unroll] for (uint v = 0; v < 8; ++v) r.v[v] = wg_h2f(fg_half(hp, v)); + r.v[0] = f16tof32(hp.x); r.v[1] = wg_h2f_hi(hp.x); + r.v[2] = f16tof32(hp.y); r.v[3] = wg_h2f_hi(hp.y); + r.v[4] = f16tof32(hp.z); r.v[5] = wg_h2f_hi(hp.z); + r.v[6] = f16tof32(hp.w); r.v[7] = wg_h2f_hi(hp.w); return r; } // One chunk (tier B): the matrix instruction, then the whole fragment rounded to float16 by the driver channel's // conversion (v_cvt_f16_f32, nearest even; see fg_mconv.hlsl). hp keeps the packed float16 accumulator. -void fg_chunk_b(uint4 av, uint4 bv, inout v8f c, inout uint4 hp) +void fg_chunk_b(uint4 av, uint4 bv, inout uint4 hp) { - const v8f d = wg_wmma_f16(av, bv, c); + const v8f d = wg_wmma_f16(av, bv, fg_widen(hp)); hp = wg_to_f16_ags(d); - c = fg_widen(hp); +} + +uint fg_leaky2(uint packed) +{ + const half2 slope = asfloat16((uint16_t)FG_LEAKY_SLOPE16); + const half2 negzero = asfloat16((uint16_t)(0x8000u | fg_opq0())); + const uint scaled = wg_h2_bits(mad(slope, wg_as_h2(packed), negzero)); + const uint lo = packed & 0xffffu, hi = packed >> 16; + const uint mask = select(lo > 0x8000u && lo <= 0xfc00u, 0xffffu, 0u) | + select(hi > 0x8000u && hi <= 0xfc00u, 0xffff0000u, 0u); + return (packed & ~mask) | (scaled & mask); } // the packed float16 accumulator, leaky ReLU if act uint4 fg_acc_out(uint4 hp, int act) { - uint r[8]; - [unroll] for (uint v = 0; v < 8; ++v) { - const uint hb = fg_half(hp, v); - r[v] = select(act == 1, fg_leaky_fast16(hb), hb); - } - return fg_pack8(r); + if (act != 1) return hp; + return uint4(fg_leaky2(hp.x), fg_leaky2(hp.y), fg_leaky2(hp.z), fg_leaky2(hp.w)); } // the bias of output tile mt as packed float16 uint4 fg_bias8(uint bp, int mt, int hh) { - uint bb[8]; - [unroll] for (uint v = 0; v < 8; ++v) bb[v] = wg_ld16(bp, (uint)(16 * mt + 8 * hh + (int)v) * 2u); - return fg_pack8(bb); + return wg_ld128(bp, (uint)(16 * mt + 8 * hh) * 2u); } +#if FG_PAIR_PASS +// The coarse grids can distribute each conv independently across both pixels and output channels. WG_KERNEL(fg_mpair) { - WG_SETUP(); + FG_FP16_SETUP(); + const int lane = (int)wg_lane_id() & 31, wave = (int)wg_lane_id() / 32; + const int n = lane & 15, hh = lane / 16; +#if FG_PAIR_PASS == 1 + const int input_ch = C, output_tiles = FG_C1T; + const uint weights = wf1, bias = b1; +#else + const int input_ch = FG_C1T * 16, output_tiles = FG_C2T; + const uint weights = wf2, bias = b2; +#endif + const int groups = output_tiles / FG_PASS_MT; + const int group = (int)wg_block_id(); + const int tile = (group % groups) * FG_PASS_MT; + const int pixel = ((group / groups) * (WG_BLOCK / 32) + wave) * 16 + n; + const int pc = min(pixel, H * W - 1); +#if FG_PAIR_PASS == 1 && FG_MODE == 1 + const FgTap tx = fg_axis(asfloat(rx), pc % W, wi); + const FgTap ty = fg_axis(asfloat(ry), pc / W, hi); +#endif + const int nq = input_ch / 16; + uint4 acc[FG_PASS_MT]; + [unroll] for (int mt = 0; mt < FG_PASS_MT; ++mt) acc[mt] = fg_bias8(bias, tile + mt, hh); + const int rounds = nq + (int)fg_opq0(); + for (int cb = 0; cb < rounds; ++cb) { + const int c0 = cb * 16 + 8 * hh; +#if FG_PAIR_PASS == 1 && FG_MODE == 1 + const uint4 fb = fg_pair_in(pc, c0, tx, ty); +#else + const uint4 fb = wg_ld128(x, (uint)(pc * input_ch + c0) * 2u); +#endif + uint4 fa[FG_PASS_MT]; + [unroll] for (int mt = 0; mt < FG_PASS_MT; ++mt) + fa[mt] = wg_ld128(weights, (uint)((((tile + mt) * nq + cb) * 32 + lane) * 16)); + // Software-pipelined Tier B chunks across FG_PASS_MT: overlaps fg_widen & wg_to_f16_ags with wg_wmma_f16 + { + v8f w_next = fg_widen(acc[0]); + v8f d_prev = w_next; + [unroll] for (int mt = 0; mt < FG_PASS_MT; ++mt) { + const v8f d_cur = wg_wmma_f16(fa[mt], fb, w_next); + if (mt > 0) acc[mt - 1] = wg_to_f16_ags(d_prev); + if (mt + 1 < FG_PASS_MT) w_next = fg_widen(acc[mt + 1]); + d_prev = d_cur; + } + acc[FG_PASS_MT - 1] = wg_to_f16_ags(d_prev); + } + } + const uint dst = (uint)wg_uniform((int)y); + [unroll] for (int mt = 0; mt < FG_PASS_MT; ++mt) { + const uint4 r = fg_acc_out(acc[mt], FG_PAIR_PASS == 1 ? 1 : act2); + const int elem = pc * output_tiles * 16 + (tile + mt) * 16 + 8 * hh; + if (pixel < H * W) wg_st128(dst, (uint)elem * 2u, r); + } +} +#else +WG_KERNEL(fg_mpair) +{ + FG_FP16_SETUP(); const uint lane = wg_lane_id() & 31u, wave = wg_lane_id() >> 5; const int n = (int)(lane & 15u), hh = (int)(lane >> 4); - const int p0 = ((int)wg_block_id() * 8 + (int)wave) * 16 * FG_NT; + const int p0 = ((int)wg_block_id() * (WG_BLOCK / 32) + (int)wave) * 16 * FG_NT; const int nq = C / 16; const uint py = (uint)wg_uniform((int)y); // every lane computes a pixel inside the grid (the last one for lanes past the end); only the store tests the range @@ -172,18 +257,16 @@ WG_KERNEL(fg_mpair) tx[nt] = fg_axis(asfloat(rx), xx, wi); ty[nt] = fg_axis(asfloat(ry), yy, hi); } - v8f acc2[FG_C2T][FG_NT]; uint4 h2[FG_C2T][FG_NT]; [unroll] for (int mt = 0; mt < FG_C2T; ++mt) { const uint4 bh = fg_bias8(b2, mt, hh); - [unroll] for (int nt = 0; nt < FG_NT; ++nt) { h2[mt][nt] = bh; acc2[mt][nt] = fg_widen(bh); } + [unroll] for (int nt = 0; nt < FG_NT; ++nt) { h2[mt][nt] = bh; } } #if FG_LAZY == 0 - v8f acc1[FG_C1T][FG_NT]; uint4 h1[FG_C1T][FG_NT]; [unroll] for (int mt1 = 0; mt1 < FG_C1T; ++mt1) { const uint4 bh = fg_bias8(b1, mt1, hh); - [unroll] for (int nt1 = 0; nt1 < FG_NT; ++nt1) { h1[mt1][nt1] = bh; acc1[mt1][nt1] = fg_widen(bh); } + [unroll] for (int nt1 = 0; nt1 < FG_NT; ++nt1) { h1[mt1][nt1] = bh; } } const int nq_loop = nq + (int)fg_opq0(); for (int cb = 0; cb < nq_loop; ++cb) { @@ -191,8 +274,18 @@ WG_KERNEL(fg_mpair) [unroll] for (int nt2 = 0; nt2 < FG_NT; ++nt2) fb[nt2] = fg_pair_in(pc[nt2], cb * 16 + 8 * hh, tx[nt2], ty[nt2]); [unroll] for (int mt2 = 0; mt2 < FG_C1T; ++mt2) fa[mt2] = wg_ld128(wf1, (uint)(((mt2 * nq + cb) * 32 + (int)lane) * 16)); - [unroll] for (int mt3 = 0; mt3 < FG_C1T; ++mt3) - [unroll] for (int nt3 = 0; nt3 < FG_NT; ++nt3) fg_chunk_b(fa[mt3], fb[nt3], acc1[mt3][nt3], h1[mt3][nt3]); + { + const int N1 = FG_C1T * FG_NT; + v8f w_next = fg_widen(h1[0][0]); + v8f d_prev = w_next; + [unroll] for (int s = 0; s < N1; ++s) { + const v8f d_cur = wg_wmma_f16(fa[s / FG_NT], fb[s % FG_NT], w_next); + if (s > 0) h1[(s - 1) / FG_NT][(s - 1) % FG_NT] = wg_to_f16_ags(d_prev); + if (s + 1 < N1) w_next = fg_widen(h1[(s + 1) / FG_NT][(s + 1) % FG_NT]); + d_prev = d_cur; + } + h1[(N1 - 1) / FG_NT][(N1 - 1) % FG_NT] = wg_to_f16_ags(d_prev); + } } uint4 e[FG_C1T][FG_NT]; [unroll] for (int mt4 = 0; mt4 < FG_C1T; ++mt4) @@ -201,8 +294,18 @@ WG_KERNEL(fg_mpair) uint4 fa2[FG_C2T]; [unroll] for (int mt5 = 0; mt5 < FG_C2T; ++mt5) fa2[mt5] = wg_ld128(wf2, (uint)(((mt5 * FG_C1T + cb2) * 32 + (int)lane) * 16)); - [unroll] for (int mt6 = 0; mt6 < FG_C2T; ++mt6) - [unroll] for (int nt6 = 0; nt6 < FG_NT; ++nt6) fg_chunk_b(fa2[mt6], e[cb2][nt6], acc2[mt6][nt6], h2[mt6][nt6]); + { + const int N2 = FG_C2T * FG_NT; + v8f w_next = fg_widen(h2[0][0]); + v8f d_prev = w_next; + [unroll] for (int s = 0; s < N2; ++s) { + const v8f d_cur = wg_wmma_f16(fa2[s / FG_NT], e[cb2][s % FG_NT], w_next); + if (s > 0) h2[(s - 1) / FG_NT][(s - 1) % FG_NT] = wg_to_f16_ags(d_prev); + if (s + 1 < N2) w_next = fg_widen(h2[(s + 1) / FG_NT][(s + 1) % FG_NT]); + d_prev = d_cur; + } + h2[(N2 - 1) / FG_NT][(N2 - 1) % FG_NT] = wg_to_f16_ags(d_prev); + } } #else #ifdef FG_CINT @@ -213,14 +316,13 @@ WG_KERNEL(fg_mpair) #endif const int c1t_loop = FG_C1T + (int)fg_opq0(); for (int cb2 = 0; cb2 < c1t_loop; ++cb2) { - v8f a1[FG_NT]; uint4 hl[FG_NT]; const uint4 bh1 = fg_bias8(b1, cb2, hh); - [unroll] for (int nt7 = 0; nt7 < FG_NT; ++nt7) { hl[nt7] = bh1; a1[nt7] = fg_widen(bh1); } + [unroll] for (int nt7 = 0; nt7 < FG_NT; ++nt7) { hl[nt7] = bh1; } #ifdef FG_CINT [unroll] for (int cb = 0; cb < FG_CINT; ++cb) { const uint4 fa = wg_ld128(wf1, (uint)(((cb2 * FG_CINT + cb) * 32 + (int)lane) * 16)); - [unroll] for (int nt9 = 0; nt9 < FG_NT; ++nt9) fg_chunk_b(fa, sc[cb][nt9], a1[nt9], hl[nt9]); + [unroll] for (int nt9 = 0; nt9 < FG_NT; ++nt9) fg_chunk_b(fa, sc[cb][nt9], hl[nt9]); } #else const int nq_loop = nq + (int)fg_opq0(); @@ -228,16 +330,28 @@ WG_KERNEL(fg_mpair) uint4 fb[FG_NT]; [unroll] for (int nt8 = 0; nt8 < FG_NT; ++nt8) fb[nt8] = fg_pair_in(pc[nt8], cb * 16 + 8 * hh, tx[nt8], ty[nt8]); const uint4 fa = wg_ld128(wf1, (uint)(((cb2 * nq + cb) * 32 + (int)lane) * 16)); - [unroll] for (int nt9 = 0; nt9 < FG_NT; ++nt9) fg_chunk_b(fa, fb[nt9], a1[nt9], hl[nt9]); + [unroll] for (int nt9 = 0; nt9 < FG_NT; ++nt9) fg_chunk_b(fa, fb[nt9], hl[nt9]); } #endif uint4 eb[FG_NT]; [unroll] for (int nt10 = 0; nt10 < FG_NT; ++nt10) eb[nt10] = fg_acc_out(hl[nt10], 1); - uint4 fa2[FG_C2T]; - [unroll] for (int mt11 = 0; mt11 < FG_C2T; ++mt11) - fa2[mt11] = wg_ld128(wf2, (uint)(((mt11 * FG_C1T + cb2) * 32 + (int)lane) * 16)); - [unroll] for (int mt12 = 0; mt12 < FG_C2T; ++mt12) - [unroll] for (int nt12 = 0; nt12 < FG_NT; ++nt12) fg_chunk_b(fa2[mt12], eb[nt12], acc2[mt12][nt12], h2[mt12][nt12]); + [unroll] for (int tile = 0; tile < FG_C2T; tile += FG_C2_BATCH) { + uint4 fa2[FG_C2_BATCH]; + [unroll] for (int mt = 0; mt < FG_C2_BATCH; ++mt) + fa2[mt] = wg_ld128(wf2, (uint)((((tile + mt) * FG_C1T + cb2) * 32 + (int)lane) * 16)); + { + const int Nb = FG_C2_BATCH * FG_NT; + v8f w_next = fg_widen(h2[tile][0]); + v8f d_prev = w_next; + [unroll] for (int s = 0; s < Nb; ++s) { + const v8f d_cur = wg_wmma_f16(fa2[s / FG_NT], eb[s % FG_NT], w_next); + if (s > 0) h2[tile + (s - 1) / FG_NT][(s - 1) % FG_NT] = wg_to_f16_ags(d_prev); + if (s + 1 < Nb) w_next = fg_widen(h2[tile + (s + 1) / FG_NT][(s + 1) % FG_NT]); + d_prev = d_cur; + } + h2[tile + (Nb - 1) / FG_NT][(Nb - 1) % FG_NT] = wg_to_f16_ags(d_prev); + } + } } #endif const int C2 = 16 * FG_C2T; @@ -247,3 +361,4 @@ WG_KERNEL(fg_mpair) if (p0 + 16 * nt13 + n < H * W) wg_st128(py, (uint)(pc[nt13] * C2 + 16 * mt13 + 8 * hh) * 2u, r); } } +#endif diff --git a/clean/dx12/kernels/fg_net2_mconv.hlsl b/clean/dx12/kernels/fg_net2_mconv.hlsl index e7c53402..f5b628a5 100644 --- a/clean/dx12/kernels/fg_net2_mconv.hlsl +++ b/clean/dx12/kernels/fg_net2_mconv.hlsl @@ -12,13 +12,16 @@ // skip, v), pool = 1: the 2 x 2 average h(h(h(h(a00 + a01) + a10) + a11) * 0.25). // // FG_UP = 1 (L12, L13, L24, L25): the conv grid H x W is the 2x upsample of the stored input (H / 2 x W / 2): the -// workgroup stages its conv-grid tile plus a one-pixel border in LDS, each value the exact half-pixel bilinear sample -// of fg_net2_up2 (top = fma(wx1, P01, h(wx0 P00)), bottom likewise, out = fma(wy1, bottom, h(wy0 top))), 0 outside -// the grid; the taps read the tile. heads = 1 (L13, L25): the three heads in one launch, head j = workgroup group mg +// workgroup builds its conv-grid tile and one-pixel border directly from the half-resolution input, in one LDS +// buffer. Adjacent rows share the exact horizontal samples of fg_net2_up2. Values outside the grid are zero. +// Selected plain variants stage the same halo directly from the input. +// heads = 1 (L13, L25): the three heads in one launch, head j = workgroup group mg // (the weight tensor's one tile of 8 outputs for every head): input channels in_co + j cin, kept outputs 0-3 / 4 / 5-7 // (so clamp_from = 4 gives "none / clamp / clamp"), output y / y1 / y2 with out_cs = the kept count when out_cs = 0, // else one shared output (out_cs, out_co + first kept output); residual skip / skip1 / skip2 (channel stride = kept -// count, multiplier res_mul for head 0 and 1 for heads 1 and 2). +// count, multiplier res_mul for head 0 and 1 for heads 1 and 2). The h3 variants take the same arguments and use +// one workgroup per spatial tile. They reuse the LDS tile across heads and join a shared eight-channel output +// before the residual and store. // // Work split: workgroup = 16 x FG_TH conv pixels (tile tx, ty; FG_TH = 2 rows per wave) and FG_MT output tiles of 16 // weight outputs (group mg); a wave owns two rows of 16 pixels (two B fragments per chunk), so a pooled 2 x 2 cell sits @@ -41,6 +44,8 @@ // @wg-kernel fg_net2_mconv_m2b4u co=fg_net2_mma.co entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,FG_NB=4,FG_UP=1 // @wg-kernel fg_net2_mconv_m3b2u co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=3,FG_NB=2,FG_UP=1 // @wg-kernel fg_net2_mconv_m3b4u co=fg_net2_mma.co entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=3,FG_NB=4,FG_UP=1 +// @wg-kernel fg_net2_mconv_h3b1u co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1,FG_UP=1,FG_FUSED_HEADS=1 +// @wg-kernel fg_net2_mconv_h3b2u co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=2,FG_UP=1,FG_FUSED_HEADS=1 #include "wg_platform.hlsli" #include "fg_net2.hlsli" @@ -61,27 +66,52 @@ WG_ARGS_BEGIN uint res_mul; int skip_cs, skip_co, tiles_x, tiles_y, heads; WG_ARGS_END +#ifndef FG_FUSED_HEADS +#define FG_FUSED_HEADS 0 +#endif +#define FG_NATIVE_UP FG_UP +#define FG_NATIVE_POST ((!FG_UP && (FG_NB == 2 || FG_MT == 2 || FG_NB == 4)) || (FG_UP && FG_NB == 1)) +#define FG_NATIVE_LEAKY 1 +#define FG_JOINED_POST FG_FUSED_HEADS #include "fg_net2_fast.hlsli" -#if FG_UP -#define FG_TG (FG_NB * 2) // 8-channel groups per staged pixel -groupshared uint4 fg_tile[(FG_TH + 2) * 18 * FG_TG]; +// Preserve the unaligned path for packed 10- and 18-channel input and for channel slices. +uint4 fg_load_aligned8(uint base, uint off) +{ + return wg_mem.Load4((base + off) & ~15u); +} + +uint4 fg_load_input8(uint off, int ico) +{ + if (((in_cs | ico) & 7) == 0) return fg_load_aligned8(x, off); + return wg_ld128(x, off); +} + +#define FG_STAGE (FG_UP || FG_NB == 2 || (FG_MT == 2 && FG_NB == 1) || (FG_MT == 1 && FG_NB == 4)) +#if FG_STAGE +#define FG_TG (FG_NB * 2) +#define FG_TILE_PIXELS ((FG_TH + 2) * 18) +groupshared uint4 fg_tile[FG_TILE_PIXELS * FG_TG]; + +uint fg_tile_index(uint p, uint g) { return g * FG_TILE_PIXELS + p; } #endif -// 8 packed float16 values -> the float32 accumulator fragment (exact) +// 8 packed float16 values -> the float32 accumulator fragment (exact; mask-free low halves via f16tof32) v8f fg_widen(uint4 hp) { v8f r; - [unroll] for (uint v = 0; v < 8; ++v) r.v[v] = wg_h2f(fg_half(hp, v)); + r.v[0] = f16tof32(hp.x); r.v[1] = wg_h2f_hi(hp.x); + r.v[2] = f16tof32(hp.y); r.v[3] = wg_h2f_hi(hp.y); + r.v[4] = f16tof32(hp.z); r.v[5] = wg_h2f_hi(hp.z); + r.v[6] = f16tof32(hp.w); r.v[7] = wg_h2f_hi(hp.w); return r; } // One chunk (tier B, as fg_mconv.hlsl): the matrix instruction, then the fragment rounded to float16 by the driver // channel's conversion; hp keeps the packed float16 accumulator. -void fg_chunk_b(uint4 av, uint4 bv, inout v8f c, inout uint4 hp) +void fg_chunk_b(uint4 av, uint4 bv, inout uint4 hp) { - const v8f d = wg_wmma_f16(av, bv, c); + const v8f d = wg_wmma_f16(av, bv, fg_widen(hp)); hp = wg_to_f16_ags(d); - c = fg_widen(hp); } // the mask of 8 input channels c0 .. c0 + 7 (dword d: channels c0 + 2d, c0 + 2d + 1): channels >= cin read 0 uint4 fg_cmask(int c0) @@ -97,23 +127,58 @@ uint4 fg_cmask(int c0) // the launch's output parameters for this workgroup (heads: per head) struct FgOut { int lo; int n; int cs; int co; uint yp; uint sp; int scs; uint rmul; }; +// Load the packed 4-, 1-, or 3-channel residual for a head. The 3-channel stride alternates alignment. +uint4 fg_head_skip(FgOut q, int e, bool live) +{ + const uint at = live ? (uint)e * 2u : 0u; + if (q.n == 4 && (e & 1) == 0) { + const uint2 v = wg_ld64(q.sp, at); + return uint4(v, 0u, 0u); + } + if (q.n == 1) return uint4(0u, 0u, wg_ld16(q.sp, at), 0u); + if (q.n == 3) { + uint a, bc; + if ((e & 1) != 0) { + a = wg_ld16(q.sp, at); + bc = wg_ld32(q.sp, at + 2u * (uint)live); + } else { + const uint ab = wg_ld32(q.sp, at); + a = ab & 0xffffu; + bc = (ab >> 16) | (wg_ld16(q.sp, at + 4u * (uint)live) << 16); + } + return uint4(0u, 0u, a << 16, bc); + } + return uint4(wg_ld16(q.sp, at) | (wg_ld16(q.sp, at + 2u * (uint)live) << 16), + wg_ld16(q.sp, at + 4u * (uint)live) | (wg_ld16(q.sp, at + 6u * (uint)live) << 16), 0u, 0u); +} + // the exact post-ops of fg_net2_conv on the lane's 8 weight outputs o0 .. o0 + 7 at conv pixel (cy, cx): leaky, // clamp from clamp_from, residual (res 1: h(v + 0); res 2: fma(rmul, skip, v), the skip channels of the kept outputs) -uint4 fg_post8(FgOut q, uint4 v, int o0, int cy, int cx, bool live) +uint4 fg_adjust8(uint4 v, int o0) { if (leaky != 0) v = fg_leaky8(v); uint r[8]; [unroll] for (int i = 0; i < 8; ++i) { const uint hv = fg_half(v, (uint)i); - r[i] = select(o0 + i >= clamp_from, fg2_clamp6(hv), hv); + const uint mag = hv & 0x7fffu; + const bool clamp_value = o0 + i >= clamp_from && mag > FG2_SIX16 && mag <= 0x7c00u; + r[i] = select(clamp_value, (hv & 0x8000u) | FG2_SIX16, hv); r[i] = select(res == 1, fg2_plus0(r[i]), r[i]); } - v = fg_pack8(r); + return fg_pack8(r); +} + +uint4 fg_post8(FgOut q, uint4 v, int o0, int cy, int cx, bool live) +{ + v = fg_adjust8(v, o0); if (res == 2) { const int e0 = (cy * W + cx) * q.scs + skip_co - q.lo; uint4 sk; - if (live && o0 >= q.lo && o0 + 8 <= q.lo + q.n && ((e0 + o0) & 1) == 0) { - sk = wg_ld128(q.sp, (uint)(e0 + o0) * 2u); // 8 contiguous skip channels + if (heads != 0) { + sk = fg_head_skip(q, (cy * W + cx) * q.scs + skip_co, live && o0 == 0); + } else if (live && o0 >= q.lo && o0 + 8 <= q.lo + q.n && ((e0 + o0) & 1) == 0) { + const uint off = (uint)(e0 + o0) * 2u; + sk = ((q.scs | (skip_co - q.lo)) & 7) == 0 ? fg_load_aligned8(q.sp, off) : wg_ld128(q.sp, off); } else { uint s8[8]; [unroll] for (int j = 0; j < 8; ++j) { @@ -122,7 +187,11 @@ uint4 fg_post8(FgOut q, uint4 v, int o0, int cy, int cx, bool live) } sk = fg_pack8(s8); } +#if FG_NATIVE_POST + v = fg_fma8_post(q.rmul, sk, v); +#else v = fg_fma8(wg_h2f(q.rmul), sk, v); +#endif } return v; } @@ -132,7 +201,26 @@ void fg_store8(FgOut q, int pix, int o0, uint4 p) { const bool wide = (q.lo & 7) == 0 && (q.n & 7) == 0 && (q.cs & 7) == 0 && (q.co & 7) == 0; const int e0 = pix * q.cs + q.co - q.lo; - if (wide) { + if (heads != 0) { + if (o0 != 0) return; + const int e = e0 + q.lo; + const uint at = (uint)e * 2u; + if (q.n == 4 && (e & 1) == 0) { + wg_st64(q.yp, at, p.xy); + } else if (q.n == 1) { + wg_st16(q.yp, at, p.z); + } else if (q.n == 3) { + if ((e & 1) == 0) { + wg_st32(q.yp, at, (p.z >> 16) | (p.w << 16)); + wg_st16(q.yp, at + 4u, p.w >> 16); + } else { + wg_st16(q.yp, at, p.z >> 16); + wg_st32(q.yp, at + 2u, p.w); + } + } else { + [unroll] for (int i = 0; i < 4; ++i) wg_st16(q.yp, at + 2u * (uint)i, fg_half(p, (uint)i)); + } + } else if (wide) { if (o0 >= q.lo && o0 + 8 <= q.lo + q.n) wg_st128(q.yp, (uint)(e0 + o0) * 2u, p); } else { [unroll] for (int v = 0; v < 8; ++v) @@ -141,50 +229,69 @@ void fg_store8(FgOut q, int pix, int o0, uint4 p) } #if FG_UP -// stages the 2x upsample (fg_up8) of conv-grid rows y0 - 1 .. y0 + FG_TH and columns x0 - 1 .. x0 + 16 (zero outside the grid) +// Specialization of fg2_up_tap for integer output positions on a 2x grid. +Fg2Tap fg_stage_tap(int o, int n) +{ + const int i = (o - 1) >> 1; + Fg2Tap t; + t.i0 = max(i, 0); + t.i1 = clamp(i + 1, 0, n - 1); + t.w0 = o == 0 ? 0x3d00u : ((o & 1) ? 0x3a00u : 0x3400u); + t.w1 = o == 0 ? 0xb400u : ((o & 1) ? 0x3400u : 0x3a00u); + return t; +} + +// Rows 2j-1 and 2j use the same source row pair. Reuse their rounded horizontal samples. void fg_stage(int x0, int y0, int ico) { const int hi = H / 2, wi = W / 2; - const int items = (FG_TH + 2) * 18 * FG_TG; + const int items = (FG_TH / 2 + 1) * 18 * FG_TG; const int rounds = (items + WG_BLOCK - 1) / WG_BLOCK + (int)fg_opq0(); - // uniform control flow around the driver-channel conversions: every lane computes a clamped position, the select - // zeroes positions outside the grid and the store skips items past the tile - for (int k = 0; k < rounds; ++k) { - const int it = k * WG_BLOCK + (int)wg_lane_id(); - const int ic = min(it, items - 1); - const int g = ic % FG_TG, pp = ic / FG_TG; - const int cy = y0 - 1 + pp / 18, cx = x0 - 1 + pp % 18; - const bool inside = cy >= 0 && cy < H && cx >= 0 && cx < W; - const Fg2Tap tX = fg2_up_tap(clamp(cx, 0, W - 1), wi), tY = fg2_up_tap(clamp(cy, 0, H - 1), hi); - const uint c0 = (uint)(ico + 8 * g); - const uint4 q00 = wg_ld128(x, ((uint)((tY.i0 * wi + tX.i0) * in_cs) + c0) * 2u); - const uint4 q01 = wg_ld128(x, ((uint)((tY.i0 * wi + tX.i1) * in_cs) + c0) * 2u); - const uint4 q10 = wg_ld128(x, ((uint)((tY.i1 * wi + tX.i0) * in_cs) + c0) * 2u); - const uint4 q11 = wg_ld128(x, ((uint)((tY.i1 * wi + tX.i1) * in_cs) + c0) * 2u); - const uint4 v = fg_up8(tX, tY, q00, q01, q10, q11) & fg_cmask(8 * g); - const uint z = select(inside, 0xffffffffu, 0u); - if (it < items) fg_tile[it] = uint4(v.x & z, v.y & z, v.z & z, v.w & z); + for (int round = 0; round < rounds; ++round) { + // Lanes past the end still participate in the wave's conversion. + const int it = round * WG_BLOCK + (int)wg_lane_id(), elem = min(it, items - 1); + const int g = elem % FG_TG, p = elem / FG_TG; + const int cy = y0 - 1 + 2 * (p / 18), cx = x0 - 1 + p % 18; + const Fg2Tap tx = fg_stage_tap(clamp(cx, 0, W - 1), wi); + const Fg2Tap ty0 = fg_stage_tap(clamp(cy, 0, H - 1), hi); + const Fg2Tap ty1 = fg_stage_tap(clamp(cy + 1, 0, H - 1), hi); + const int row0 = ty0.i0 * wi, row1 = ty0.i1 * wi, c0 = ico + 8 * g; + const uint4 q00 = fg_load_input8((uint)(((row0 + tx.i0) * in_cs + c0) * 2), ico); + const uint4 q01 = fg_load_input8((uint)(((row0 + tx.i1) * in_cs + c0) * 2), ico); + const uint4 q10 = fg_load_input8((uint)(((row1 + tx.i0) * in_cs + c0) * 2), ico); + const uint4 q11 = fg_load_input8((uint)(((row1 + tx.i1) * in_cs + c0) * 2), ico); + const uint4 top = fg_up_axis8(tx, q00, q01), bot = fg_up_axis8(tx, q10, q11); + const uint4 mask = fg_cmask(8 * g); + const bool inside_x = cx >= 0 && cx < W; + const uint4 v0 = fg_up_axis8(ty0, top, bot) & mask & select(inside_x && cy >= 0 && cy < H, ~0u, 0u); + const uint4 v1 = fg_up_axis8(ty1, top, bot) & mask & select(inside_x && cy + 1 >= 0 && cy + 1 < H, ~0u, 0u); + if (it < items) { + const int dst = p + p / 18 * 18; + fg_tile[fg_tile_index(dst, g)] = v0; + fg_tile[fg_tile_index(dst + 18, g)] = v1; + } } - GroupMemoryBarrierWithGroupSync(); + wg_barrier_lds(); +} +#elif FG_STAGE +void fg_stage(int x0, int y0, int ico) +{ + const uint items = FG_TILE_PIXELS * FG_TG; + for (uint i = wg_lane_id(); i < items; i += WG_BLOCK) { + const int g = (int)(i % FG_TG), p = (int)(i / FG_TG); + const int sx = x0 + p % 18 - 1, sy = y0 + p / 18 - 1; + const bool inside = and(and(sx >= 0, sx < W), and(sy >= 0, sy < H)); + const uint e = select(inside, (uint)((sy * W + sx) * in_cs + ico), 0u); + const uint mask = select(inside, 0xffffffffu, 0u); + fg_tile[fg_tile_index(p, g)] = fg_load_input8((e + (uint)(8 * g)) * 2u, ico) & fg_cmask(8 * g) & mask; + } + wg_barrier_lds(); } #endif -WG_KERNEL(fg_net2_mconv) +FgOut fg_output(int hj) { - WG_SETUP(); - const uint lane = wg_lane_id() & 31u; - const int blk = (int)wg_block_id(); - const int tx = blk % tiles_x, rest = blk / tiles_x; - const int ty = rest % tiles_y, mg = rest / tiles_y; - const int n = (int)(lane & 15u), hh = (int)(lane >> 4); - const int px = tx * 16 + n; - const int wrow = 2 * (int)(wg_lane_id() >> 5); // the wave's first row in the tile - const int py0 = wg_uniform(ty * FG_TH + wrow); - - // per-head launch parameters (uniform) FgOut q; - const int wt = heads != 0 ? 0 : mg; // weight tile group - const int hj = heads != 0 ? mg : 0; q.lo = heads != 0 ? (hj == 0 ? 0 : (hj == 1 ? 4 : 5)) : co_lo; q.n = heads != 0 ? (hj == 0 ? 4 : (hj == 1 ? 1 : 3)) : co_n; q.cs = heads != 0 && out_cs == 0 ? q.n : out_cs; @@ -193,55 +300,217 @@ WG_KERNEL(fg_net2_mconv) q.sp = (uint)wg_uniform((int)(hj == 0 ? skip : (hj == 1 ? skip1 : skip2))); q.scs = heads != 0 ? q.n : skip_cs; q.rmul = hj == 0 ? res_mul : FG2_ONE16; - const int ico = in_co + hj * cin; - -#if FG_UP - fg_stage(tx * 16, ty * FG_TH, ico); -#endif - if (py0 >= H) return; // wave-uniform: both rows of this wave are past the grid + return q; +} - v8f a32[FG_MT][2]; - uint4 h16[FG_MT][2]; // the same accumulator as packed float16 +void fg_conv_tile(int px, int py0, int wrow, int n, int hh, uint lane, int wt, int ico, out uint4 h16[FG_MT][2]) +{ [unroll] for (int mt = 0; mt < FG_MT; ++mt) { const int o0 = (wt * FG_MT + mt) * 16 + 8 * hh; - uint bb[8]; - [unroll] for (uint v = 0; v < 8; ++v) bb[v] = wg_ld16(b, (uint)(o0 + (int)v) * 2u); - h16[mt][0] = fg_pack8(bb); + h16[mt][0] = fg_load_aligned8(b, (uint)o0 * 2u); h16[mt][1] = h16[mt][0]; - a32[mt][0] = fg_widen(h16[mt][0]); - a32[mt][1] = a32[mt][0]; } -#if !FG_UP +#if !FG_STAGE uint4 cm[FG_NB]; - [unroll] for (int cb0 = 0; cb0 < FG_NB; ++cb0) cm[cb0] = fg_cmask(cb0 * 16 + 8 * hh); + [unroll] for (int cb = 0; cb < FG_NB; ++cb) cm[cb] = fg_cmask(cb * 16 + 8 * hh); #endif - +#if FG_STAGE && (FG_MT * FG_NB <= 2) + // Software-pipeline tap loads with WMMAs (same win as fg_mconv.hlsl): prefetch tap t+1's weights and LDS tile + // before tap t's WMMAs. Unrolled 9 taps eliminates dynamic tap-index bit math while keeping VGPRs low. + uint4 fb[2][FG_NB], fa[FG_MT][FG_NB]; + { + [unroll] for (int nt = 0; nt < 2; ++nt) { + const int pp = (wrow + nt) * 18 + n; + [unroll] for (int cb = 0; cb < FG_NB; ++cb) fb[nt][cb] = fg_tile[fg_tile_index(pp, 2 * cb + hh)]; + } + [unroll] for (int mt = 0; mt < FG_MT; ++mt) + [unroll] for (int cb = 0; cb < FG_NB; ++cb) + fa[mt][cb] = fg_load_aligned8(wf, (uint)(((((wt * FG_MT + mt) * 9) * FG_NB + cb) * 32 + (int)lane) * 16)); + } + [unroll] for (int t = 0; t < 9; ++t) { + uint4 fb_n[2][FG_NB], fa_n[FG_MT][FG_NB]; + if (t + 1 < 9) { + const int tn = t + 1; + const int kxn = tn % 3, kyn = tn / 3; + [unroll] for (int nt = 0; nt < 2; ++nt) { + const int ppn = (wrow + nt + kyn) * 18 + n + kxn; + [unroll] for (int cb = 0; cb < FG_NB; ++cb) fb_n[nt][cb] = fg_tile[fg_tile_index(ppn, 2 * cb + hh)]; + } + [unroll] for (int mt = 0; mt < FG_MT; ++mt) + [unroll] for (int cb = 0; cb < FG_NB; ++cb) + fa_n[mt][cb] = fg_load_aligned8(wf, (uint)(((((wt * FG_MT + mt) * 9 + tn) * FG_NB + cb) * 32 + (int)lane) * 16)); + } + { + const int N = FG_NB * FG_MT * 2; + v8f w_next = fg_widen(h16[0][0]); + v8f d_prev = w_next; + [unroll] for (int s = 0; s < N; ++s) { + const int cb = s / (FG_MT * 2); + const int r = s - cb * (FG_MT * 2); + const int mt = r >> 1; + const int nt = r & 1; + const v8f d_cur = wg_wmma_f16(fa[mt][cb], fb[nt][cb], w_next); + if (s > 0) { + const int ps = s - 1; + const int pr = ps % (FG_MT * 2); + h16[pr >> 1][pr & 1] = wg_to_f16_ags(d_prev); + } + if (s + 1 < N) { + const int ns = s + 1; + const int nr = ns % (FG_MT * 2); + w_next = fg_widen(h16[nr >> 1][nr & 1]); + } + d_prev = d_cur; + } + const int lr = (N - 1) % (FG_MT * 2); + h16[lr >> 1][lr & 1] = wg_to_f16_ags(d_prev); + } + if (t + 1 < 9) { + [unroll] for (int nt2 = 0; nt2 < 2; ++nt2) + [unroll] for (int cb2 = 0; cb2 < FG_NB; ++cb2) fb[nt2][cb2] = fb_n[nt2][cb2]; + [unroll] for (int mt2 = 0; mt2 < FG_MT; ++mt2) + [unroll] for (int cb3 = 0; cb3 < FG_NB; ++cb3) fa[mt2][cb3] = fa_n[mt2][cb3]; + } + } +#else const int taps = 9 + (int)fg_opq0(); for (int t = 0; t < taps; ++t) { - const int ky = t / 3, kx = t - 3 * (t / 3); + // Two-bit tap coordinates, low to high: x = 0,1,2,0,1,2,0,1,2 and y = 0,0,0,1,1,1,2,2,2. + const uint shift = (uint)t * 2u; + const int kx = (int)((0x24924u >> shift) & 3u), ky = (int)((0x2a540u >> shift) & 3u); uint4 fb[2][FG_NB], fa[FG_MT][FG_NB]; [unroll] for (int nt = 0; nt < 2; ++nt) { -#if FG_UP +#if FG_STAGE const int pp = (wrow + nt + ky) * 18 + n + kx; - [unroll] for (int cb = 0; cb < FG_NB; ++cb) fb[nt][cb] = fg_tile[pp * FG_TG + 2 * cb + hh]; + [unroll] for (int cb = 0; cb < FG_NB; ++cb) fb[nt][cb] = fg_tile[fg_tile_index(pp, 2 * cb + hh)]; #else const int sx = px + kx - 1, sy = py0 + nt + ky - 1; const bool inb = and(and(sx >= 0, sx < W), and(sy >= 0, sy < H)); const uint e = select(inb, (uint)((sy * W + sx) * in_cs + ico + 8 * hh), 0u); - const uint z = select(inb, 0xffffffffu, 0u); - [unroll] for (int cb = 0; cb < FG_NB; ++cb) { - const uint4 u = wg_ld128(x, (e + (uint)(cb * 16)) * 2u); - fb[nt][cb] = uint4(u.x & cm[cb].x & z, u.y & cm[cb].y & z, u.z & cm[cb].z & z, u.w & cm[cb].w & z); + const uint z = select(inb, ~0u, 0u); + [unroll] for (int cb = 0; cb < FG_NB; ++cb) + fb[nt][cb] = fg_load_input8((e + (uint)(cb * 16)) * 2u, ico) & cm[cb] & z; +#endif + } + [unroll] for (int mt = 0; mt < FG_MT; ++mt) + [unroll] for (int cb = 0; cb < FG_NB; ++cb) + fa[mt][cb] = fg_load_aligned8(wf, (uint)(((((wt * FG_MT + mt) * 9 + t) * FG_NB + cb) * 32 + (int)lane) * 16)); + // Software-pipelined Tier B chunks across (cb, mt, nt): overlaps both fg_widen (8x v_cvt_f32_f16) + // and wg_to_f16_ags (8x v_cvt_f16_f32) directly with independent wg_wmma_f16 ops (only 2 v8f live; bit-identical). + { + const int N = FG_NB * FG_MT * 2; + v8f w_next = fg_widen(h16[0][0]); + v8f d_prev = w_next; + [unroll] for (int s = 0; s < N; ++s) { + const int cb = s / (FG_MT * 2); + const int r = s - cb * (FG_MT * 2); + const int mt = r >> 1; + const int nt = r & 1; + const v8f d_cur = wg_wmma_f16(fa[mt][cb], fb[nt][cb], w_next); + if (s > 0) { + const int ps = s - 1; + const int pr = ps % (FG_MT * 2); + h16[pr >> 1][pr & 1] = wg_to_f16_ags(d_prev); + } + if (s + 1 < N) { + const int ns = s + 1; + const int nr = ns % (FG_MT * 2); + w_next = fg_widen(h16[nr >> 1][nr & 1]); + } + d_prev = d_cur; + } + const int lr = (N - 1) % (FG_MT * 2); + h16[lr >> 1][lr & 1] = wg_to_f16_ags(d_prev); + } + } +#endif +} + +#if FG_FUSED_HEADS +void fg_fused_output(int hj, uint4 accum[2], int px, int py0, int hh, inout uint4 packed[2]) +{ + const bool joined = out_cs == 8 && (out_co & 7) == 0; + [unroll] for (int nt = 0; nt < 2; ++nt) { + const int cy = py0 + nt, pix = cy * W + px; + const bool live = px < W && cy < H; + if (joined) { + const uint4 r = accum[nt]; + if (hj == 0) packed[nt].xy = r.xy; + if (hj == 1) packed[nt].z = r.z & 0xffffu; + if (hj == 2) { + packed[nt].z |= r.z & 0xffff0000u; + packed[nt].w = r.w; } + } else { + const FgOut q = fg_output(hj); + const uint4 r = fg_post8(q, accum[nt], 8 * hh, cy, px, live); + if (live) fg_store8(q, pix, 8 * hh, r); + } + } +} + +uint4 fg_joined_post(uint4 v, int px, int cy, int hh, bool live) +{ + v = fg_adjust8(v, 8 * hh); + if (res == 2) { + const int pix = cy * W + px; + const bool kept = live && hh == 0; + const uint4 sk0 = fg_head_skip(fg_output(0), pix * 4 + skip_co, kept); + const uint4 sk1 = fg_head_skip(fg_output(1), pix + skip_co, kept); + const uint4 sk2 = fg_head_skip(fg_output(2), pix * 3 + skip_co, kept); + v = fg_fma8_heads(res_mul, uint4(sk0.xy, sk1.z | sk2.z, sk2.w), v); + } + return v; +} #endif + +WG_KERNEL(fg_net2_mconv) +{ + WG_SETUP(); + const uint lane = wg_lane_id() & 31u; + const int blk = (int)wg_block_id(); + const int tx = blk % tiles_x, rest = blk / tiles_x; + const int ty = rest % tiles_y, mg = rest / tiles_y; + const int n = (int)(lane & 15u), hh = (int)(lane >> 4); + const int px = tx * 16 + n; + const int wrow = 2 * (int)(wg_lane_id() >> 5); // the wave's first row in the tile + const int py0 = wg_uniform(ty * FG_TH + wrow); + +#if FG_FUSED_HEADS + uint4 packed[2] = {uint4(0u, 0u, 0u, 0u), uint4(0u, 0u, 0u, 0u)}; + // Each head consumes the same weights and bias on its own input channel slice. + for (int hj = 0; hj < 3 + (int)fg_opq0(); ++hj) { + if (hj > 0) wg_barrier_lds(); + const int ico = in_co + hj * cin; + fg_stage(tx * 16, ty * FG_TH, ico); + if (py0 < H) { + uint4 h16[1][2]; + fg_conv_tile(px, py0, wrow, n, hh, lane, 0, ico, h16); + fg_fused_output(hj, h16[0], px, py0, hh, packed); } - [unroll] for (int mt2 = 0; mt2 < FG_MT; ++mt2) - [unroll] for (int cb2 = 0; cb2 < FG_NB; ++cb2) - fa[mt2][cb2] = wg_ld128(wf, (uint)(((((wt * FG_MT + mt2) * 9 + t) * FG_NB + cb2) * 32 + (int)lane) * 16)); - [unroll] for (int cb3 = 0; cb3 < FG_NB; ++cb3) - [unroll] for (int mt3 = 0; mt3 < FG_MT; ++mt3) - [unroll] for (int nt3 = 0; nt3 < 2; ++nt3) fg_chunk_b(fa[mt3][cb3], fb[nt3][cb3], a32[mt3][nt3], h16[mt3][nt3]); } + if (out_cs == 8 && (out_co & 7) == 0) { + const uint dst = (uint)wg_uniform((int)y); + [unroll] for (int nt = 0; nt < 2; ++nt) { + const int cy = py0 + nt; + const bool live = px < W && cy < H; + const uint4 v = fg_joined_post(packed[nt], px, cy, hh, live); + if (hh == 0 && live) wg_st128(dst, (uint)(((cy * W + px) * 8 + out_co) * 2), v); + } + } +#else + const int wt = heads != 0 ? 0 : mg; + const int hj = heads != 0 ? mg : 0; + const FgOut q = fg_output(hj); + const int ico = in_co + hj * cin; + +#if FG_STAGE + fg_stage(tx * 16, ty * FG_TH, ico); +#endif + if (py0 >= H) return; // wave-uniform: both rows of this wave are past the grid + + uint4 h16[FG_MT][2]; + fg_conv_tile(px, py0, wrow, n, hh, lane, wt, ico, h16); const bool live0 = px < W && py0 < H, live1 = px < W && py0 + 1 < H; [unroll] for (int mt4 = 0; mt4 < FG_MT; ++mt4) { @@ -255,9 +524,16 @@ WG_KERNEL(fg_net2_mconv) // h(h(h(h(a00 + a01) + a10) + a11) * 0.25), a01 / a11 from the neighbouring lane const uint4 x01 = uint4(wg_xor_u(r0.x, 1u), wg_xor_u(r0.y, 1u), wg_xor_u(r0.z, 1u), wg_xor_u(r0.w, 1u)); const uint4 x11 = uint4(wg_xor_u(r1.x, 1u), wg_xor_u(r1.y, 1u), wg_xor_u(r1.z, 1u), wg_xor_u(r1.w, 1u)); +#if FG_NATIVE_POST + const uint4 s0 = fg_fma8_post(FG2_ONE16, x01, r0); + const uint4 s1 = fg_fma8_post(FG2_ONE16, r1, s0); + const uint4 m = fg_mul8(0.25f, fg_fma8_post(FG2_ONE16, x11, s1)); +#else const uint4 m = fg_mul8(0.25f, fg_fma8(1.0f, x11, fg_fma8(1.0f, r1, fg_fma8(1.0f, x01, r0)))); +#endif const int Ho = H / 2, Wo = W / 2, ox = px / 2, oy = py0 / 2; if ((n & 1) == 0 && ox < Wo && oy < Ho) fg_store8(q, oy * Wo + ox, o0, m); } } +#endif } diff --git a/clean/dx12/kernels/fg_net2_merge_pixels.hlsl b/clean/dx12/kernels/fg_net2_merge_pixels.hlsl new file mode 100644 index 00000000..82b56c8e --- /dev/null +++ b/clean/dx12/kernels/fg_net2_merge_pixels.hlsl @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): net2's input merge (clean/fg/reference/net2.py merge_in), one pixel per lane: +// x [npx][10] float16 = Ib [npx][4], Ic [npx][4], Ia [npx][1], then the single-precision scalar f (bits fbits) rounded to +// float16 (nearest even, wg_f2h). Built only when --only names it. +// +// @wg-kernel fg_net2_merge_pixels co=fg_net2.co block=256 wave=32 args=p,p,p,p,u,u +#include "wg_platform.hlsli" + +WG_ARGS_BEGIN + uint ib, ic, ia, x; // pointers (arena byte offsets) + int npx; + uint fbits; +WG_ARGS_END + +WG_KERNEL(fg_net2_merge_pixels) +{ + WG_SETUP(); + const int p = (int)(wg_block_id() * WG_BLOCK + wg_lane_id()); + if (p >= npx) return; + const uint rgba = (uint)p * 8u; + const uint2 b = wg_ld64(ib, rgba), c = wg_ld64(ic, rgba); + const uint a = wg_ld16(ia, (uint)p * 2u); + const uint f = wg_f2h(asfloat(fbits)); + const uint o = (uint)p * 20u; + wg_st128(x, o, uint4(b.x, b.y, c.x, c.y)); + wg_st32(x, o + 16u, a | (f << 16)); +} diff --git a/clean/dx12/kernels/fg_net2_upwarp.hlsl b/clean/dx12/kernels/fg_net2_upwarp.hlsl index 44ef580f..89047777 100644 --- a/clean/dx12/kernels/fg_net2_upwarp.hlsl +++ b/clean/dx12/kernels/fg_net2_upwarp.hlsl @@ -19,6 +19,7 @@ WG_ARGS_BEGIN int W, H; uint fbits; WG_ARGS_END +#define FG_NATIVE_UP 1 #include "fg_net2_fast.hlsli" // the 8 head channels of half-resolution pixel q @@ -61,6 +62,19 @@ uint4 fg_pair8(int yy, int xx, int zy, int zx) return uint4(b.x, b.y, c.x, c.y); } +// The taps have fixed FP16 weights on the 2x grid; preserve the extrapolation at pixel zero. +Fg2Tap fg_upwarp_tap(int o, int n) +{ + const bool odd = (o & 1) != 0; + const int i = (o >> 1) - (int)!odd; + Fg2Tap t; + t.i0 = clamp(i, 0, n - 1); + t.i1 = min(i + 1, n - 1); + t.w0 = select(o == 0, 0x3d00u, select(odd, 0x3a00u, FG2_QUARTER16)); + t.w1 = select(o == 0, 0xb400u, select(odd, FG2_QUARTER16, 0x3a00u)); + return t; +} + WG_KERNEL(fg_net2_upwarp) { WG_SETUP(); @@ -69,9 +83,10 @@ WG_KERNEL(fg_net2_upwarp) const int p = min(idx, W * H - 1); const int py_ = p / W, px_ = p - (p / W) * W; const int wi = W / 2, hi = H / 2; - const Fg2Tap tX = fg2_up_tap(px_, wi), tY = fg2_up_tap(py_, hi); - const uint4 U = fg_up8(tX, tY, fg_heads8(tY.i0 * wi + tX.i0), fg_heads8(tY.i0 * wi + tX.i1), - fg_heads8(tY.i1 * wi + tX.i0), fg_heads8(tY.i1 * wi + tX.i1)); + const Fg2Tap tX = fg_upwarp_tap(px_, wi), tY = fg_upwarp_tap(py_, hi); + const uint4 top = fg_up_axis8(tX, fg_heads8(tY.i0 * wi + tX.i0), fg_heads8(tY.i0 * wi + tX.i1)); + const uint4 bottom = fg_up_axis8(tX, fg_heads8(tY.i1 * wi + tX.i0), fg_heads8(tY.i1 * wi + tX.i1)); + const uint4 U = fg_up_axis8(tY, top, bottom); const FgSample sb = fg_sample(fg_half(U, 0u), fg_half(U, 1u), px_, py_); const FgSample sc = fg_sample(fg_half(U, 2u), fg_half(U, 3u), px_, py_); diff --git a/clean/dx12/kernels/fg_out_pull.hlsl b/clean/dx12/kernels/fg_out_pull.hlsl index f80aa25f..edeb081d 100644 --- a/clean/dx12/kernels/fg_out_pull.hlsl +++ b/clean/dx12/kernels/fg_out_pull.hlsl @@ -20,19 +20,66 @@ #define FGP_MID 0 #endif -groupshared float4 fgp_s[256]; +groupshared float4 fgp_wave_sums[8]; -// two lane-tree steps (x then y) at strides s and 2 s -void fgp_steps(uint l, uint s) +int fgp_size(int n, uint lvl) { return (n + (1 << lvl) - 1) >> lvl; } + +float4 fgp_level(float4 acc, uint m) { - wg_barrier_lds(); - if ((l & (2u * s - 1u)) == 0u) fgp_s[l] = fgp_s[l] + fgp_s[l + s]; - wg_barrier_lds(); - if ((l & (4u * s - 1u)) == 0u) fgp_s[l] = fgp_s[l] + fgp_s[l + 2u * s]; - wg_barrier_lds(); +#if FGP_MID + return fgf_level(acc, (float)(1u << (2u * m))); +#else + // The first tile receives saturated finite RGB and weights of zero or one. + // With no contributing pixels RGB is zero, so its denominator can be one. + const float den = max(acc.w, 1.0f); + const float3 rgb = fgf_div_normal3(acc.xyz, den, fgf_div_reciprocal(den)); + const float scale = asfloat((127u - 2u * m) << 23u); + return float4(select(acc.xyz == 0.0f, acc.xyz, rgb), acc.w * scale); +#endif } -int fgp_size(int n, uint lvl) { return (n + (1 << lvl) - 1) >> lvl; } +void fgp_write(uint dst, int px, int py, int w, int h, uint lvl, uint m, float4 acc) +{ + const int X = px >> m, Y = py >> m; + if (X < fgp_size(w, lvl) && Y < fgp_size(h, lvl)) + fgf_st4h(dst, Y * fgp_size(w, lvl) + X, fgp_level(acc, m)); +} + +float4 fgp_pair(float4 acc, uint lane, uint stride) +{ + return acc + WaveReadLaneAt(acc, lane ^ stride); +} + +void fgp_reduce(float4 acc, int2 origin, int w, int h, uint lvl0, uint4 dst) +{ + const uint l = wg_lane_id(), lane = wg_wave_lane(); + const int px = origin.x + (int)fgf_mx(l), py = origin.y + (int)fgf_my(l); +#if FGP_MID + acc = fgp_pair(fgp_pair(acc, lane, 1u), lane, 2u); +#else + acc += QuadReadAcrossX(acc); + acc += QuadReadAcrossY(acc); +#endif + if ((l & 3u) == 0u) fgp_write(dst.x, px, py, w, h, lvl0 + 1u, 1u, acc); + acc = fgp_pair(fgp_pair(acc, lane, 4u), lane, 8u); + if ((l & 15u) == 0u) fgp_write(dst.y, px, py, w, h, lvl0 + 2u, 2u, acc); + acc = fgp_pair(acc, lane, 16u); + if (lane == 0u) fgp_wave_sums[l >> 5] = acc; + wg_barrier_lds(); + + // The first wave gathers the eight partial sums and continues the same tree. + if (l < 32u) { + const uint part = lane & 7u; + acc = fgp_pair(fgp_wave_sums[part], lane, 1u); + if (l < 8u && (part & 1u) == 0u) { + const uint tile_lane = part * 32u; + fgp_write(dst.z, origin.x + (int)fgf_mx(tile_lane), origin.y + (int)fgf_my(tile_lane), + w, h, lvl0 + 3u, 3u, acc); + } + acc = fgp_pair(fgp_pair(acc, lane, 2u), lane, 4u); + if (l == 0u) fgp_write(dst.w, origin.x, origin.y, w, h, lvl0 + 4u, 4u, acc); + } +} WG_ARGS_BEGIN #if FGP_MID @@ -51,25 +98,14 @@ WG_KERNEL(fg_out_pull_mid) FGF_SETUP(); const uint l = wg_lane_id(); const uint t = wg_block_id(); - const int ex = (int)((t % (uint)tiles_x) * 16u + fgf_mx(l)); - const int ey = (int)((t / (uint)tiles_x) * 16u + fgf_my(l)); + const int2 origin = int2(t % (uint)tiles_x, t / (uint)tiles_x) * 16; + const int ex = origin.x + (int)fgf_mx(l), ey = origin.y + (int)fgf_my(l); float4 acc = 0.0f; if (ex < w4 && ey < h4) { const float4 e = fgf_ld4h(lv4, ey * w4 + ex); acc = float4(e.xyz * e.w, e.w); } - fgp_s[l] = acc; - [unroll] for (uint m = 1u; m <= 4u; ++m) { - fgp_steps(l, 1u << (2u * m - 2u)); - const uint lvl = m + 4u; - if ((l & ((1u << (2u * m)) - 1u)) == 0u) { - const int X = ex >> m, Y = ey >> m; - if (X < fgp_size(Wo, lvl) && Y < fgp_size(Ho, lvl)) { - const uint dst = m == 1u ? lv5 : (m == 2u ? lv6 : (m == 3u ? lv7 : lv8)); - fgf_st4h(dst, Y * fgp_size(Wo, lvl) + X, fgf_level(fgp_s[l], (float)(1u << (2u * m)))); - } - } - } + fgp_reduce(acc, origin, Wo, Ho, 4u, uint4(lv5, lv6, lv7, lv8)); } #else // net2's bilinear rule: fma(1 - fy, fma(1 - fx, q00, fx q10), fy fma(1 - fx, q01, fx q11)) @@ -78,67 +114,109 @@ float fgp_bil(float fx, float fy, float gx, float gy, float q00, float q10, floa return mad(gy, mad(gx, q00, fx * q10), fy * mad(gx, q01, fx * q11)); } +// One 20-bit mask per row of the 16 x 16 tile with its two-pixel halo. +groupshared uint fgp_need_rows[20]; +groupshared uint3 fgp_n2_tile[25]; + +uint3 fgp_n2_at(int x, int y) +{ + const uint4 d = wg_ld128(n2, (uint)(y * W2 + x) * 16u); + return uint3(d.x, d.y, wg_ld32(sigtab, (d.z & 0xffffu) * 4u)); +} + +void fgp_stage(int2 origin, bool cache_n2) +{ + const uint l = wg_lane_id(), lane = wg_wave_lane(); + const int x = origin.x + (int)lane - 2; + for (uint row = l >> 5; row < 20u; row += 8u) { + const int y = origin.y + (int)row - 2; + const bool inside = x >= 0 && x < Wo && y >= 0 && y < Ho; + const bool need = lane < 20u && (!inside || fgf_ld1h(xw, y * Wo + x) > 0.0f); + const uint mask = WaveActiveBallot(need).x; + if (lane == 0u) fgp_need_rows[row] = mask; + } + + // With k = 4, sixteen adjacent pixels sample the same four taps. The tile spans + // four coarse cells in each dimension and needs one extra tap on the right and bottom. + if (cache_n2 && l < 25u) { + const int x0 = min((origin.x >> 2) + (int)(l % 5u), W2 - 1); + const int y0 = min((origin.y >> 2) + (int)(l / 5u), H2 - 1); + fgp_n2_tile[l] = fgp_n2_at(x0, y0); + } + wg_barrier_lds(); +} + WG_KERNEL(fg_out_pull) { FGF_SETUP(); const uint l = wg_lane_id(); const uint t = wg_block_id(); - const int px = (int)((t % (uint)tiles_x) * 16u + fgf_mx(l)); - const int py = (int)((t / (uint)tiles_x) * 16u + fgf_my(l)); + const int2 origin = int2(t % (uint)tiles_x, t / (uint)tiles_x) * 16; + const uint lx = fgf_mx(l), ly = fgf_my(l); + const int px = origin.x + (int)lx, py = origin.y + (int)ly; + const bool cache_n2 = k == 4 && rk_bits == 0x3e800000u; + fgp_stage(origin, cache_n2); + float4 acc = 0.0f; - if (px < Wo && py < Ho) { - // hole: every 3 x 3 window containing the pixel holds a pixel with Xw > 0 (outside the frame: need) + float3 out_c = 0.0f; + bool hole = false; + const bool in_bounds = px < Wo && py < Ho; + if (in_bounds) { + // Every 3 x 3 window containing this pixel must have at least one need bit. uint m = 0u; - [unroll] for (int dy = 0; dy < 5; ++dy) { - [unroll] for (int dx = 0; dx < 5; ++dx) { - const int qx = px + dx - 2, qy = py + dy - 2; - const bool inside = qx >= 0 && qy >= 0 && qx < Wo && qy < Ho; - const float need = fgf_ld1h(xw, clamp(qy, 0, Ho - 1) * Wo + clamp(qx, 0, Wo - 1)); - m |= ((!inside || need > 0.0f) ? 1u : 0u) << (uint)(dy * 5 + dx); - } - } - bool hole = true; - [unroll] for (int cy = 0; cy < 3; ++cy) { - [unroll] for (int cx = 0; cx < 3; ++cx) { - const uint wmask = (7u << (uint)(cy * 5 + cx)) | (7u << (uint)(cy * 5 + 5 + cx)) | (7u << (uint)(cy * 5 + 10 + cx)); - hole = hole && (m & wmask) != 0u; + [unroll] for (uint dy = 0u; dy < 5u; ++dy) + m |= ((fgp_need_rows[ly + dy] >> lx) & 31u) << (dy * 5u); + // OR down three rows, then across three columns. Only the nine valid + // window origins are tested, so shifts across packed row boundaries are harmless. + const uint rows = m | (m >> 5u) | (m >> 10u); + const uint windows = rows | (rows >> 1u) | (rows >> 2u); + const uint origins = 7u | (7u << 5u) | (7u << 10u); + hole = (windows & origins) == origins; + float3 c = 0.0f; + [branch] if (!hole) { + // net2's output at (x / k, y / k) + const float rk = asfloat(rk_bits); + const float s = min((float)px * rk, (float)(W2 - 1)), tt = min((float)py * rk, (float)(H2 - 1)); + const float sf = floor(s), tf = floor(tt); + const int i0 = (int)sf, j0 = (int)tf, i1 = min(i0 + 1, W2 - 1), j1 = min(j0 + 1, H2 - 1); + const float fx = s - sf, fy = tt - tf, gx = 1.0f - fx, gy = 1.0f - fy; + uint3 d00, d10, d01, d11; + [branch] if (cache_n2) { + const uint i = (ly >> 2) * 5u + (lx >> 2); + d00 = fgp_n2_tile[i]; + d10 = fgp_n2_tile[i + 1u]; + d01 = fgp_n2_tile[i + 5u]; + d11 = fgp_n2_tile[i + 6u]; + } else { + d00 = fgp_n2_at(i0, j0); + d10 = fgp_n2_at(i1, j0); + d01 = fgp_n2_at(i0, j1); + d11 = fgp_n2_at(i1, j1); } + const float sigma = fgp_bil(fx, fy, gx, gy, asfloat(d00.z), asfloat(d10.z), asfloat(d01.z), asfloat(d11.z)); + const float vax = fgp_bil(fx, fy, gx, gy, wg_h2f_lo(d00.x), wg_h2f_lo(d10.x), wg_h2f_lo(d01.x), wg_h2f_lo(d11.x)); + const float vay = fgp_bil(fx, fy, gx, gy, wg_h2f_hi(d00.x), wg_h2f_hi(d10.x), wg_h2f_hi(d01.x), wg_h2f_hi(d11.x)); + const float vbx = fgp_bil(fx, fy, gx, gy, wg_h2f_lo(d00.y), wg_h2f_lo(d10.y), wg_h2f_lo(d01.y), wg_h2f_lo(d11.y)); + const float vby = fgp_bil(fx, fy, gx, gy, wg_h2f_hi(d00.y), wg_h2f_hi(d10.y), wg_h2f_hi(d01.y), wg_h2f_hi(d11.y)); + // the two candidates re-sampled at the pixel plus k times the vectors (pixel units) + const float kf = (float)k; + const float3 A = fgf_bil4h(x0, fgf_tap(vax * kf + (float)px, vay * kf + (float)py, Wo, Ho)).xyz; + const float3 B = fgf_bil4h(x1, fgf_tap(vbx * kf + (float)px, vby * kf + (float)py, Wo, Ho)).xyz; + c = fgf_sat3(mad(sigma, A, (1.0f - sigma) * B)); + if (isnan(abs(c.z * (c.x * c.y)))) c = float3(0.0f, 1.0f, 1.0f); } - // net2's output at (x / k, y / k) - const float rk = asfloat(rk_bits); - const float s = min((float)px * rk, (float)(W2 - 1)), tt = min((float)py * rk, (float)(H2 - 1)); - const float sf = floor(s), tf = floor(tt); - const int i0 = (int)sf, j0 = (int)tf, i1 = min(i0 + 1, W2 - 1), j1 = min(j0 + 1, H2 - 1); - const float fx = s - sf, fy = tt - tf, gx = 1.0f - fx, gy = 1.0f - fy; - const uint4 d00 = wg_ld128(n2, (uint)(j0 * W2 + i0) * 16u), d10 = wg_ld128(n2, (uint)(j0 * W2 + i1) * 16u); - const uint4 d01 = wg_ld128(n2, (uint)(j1 * W2 + i0) * 16u), d11 = wg_ld128(n2, (uint)(j1 * W2 + i1) * 16u); - const float sigma = fgp_bil(fx, fy, gx, gy, wg_ldf(sigtab, (d00.z & 0xFFFFu) * 4u), wg_ldf(sigtab, (d10.z & 0xFFFFu) * 4u), - wg_ldf(sigtab, (d01.z & 0xFFFFu) * 4u), wg_ldf(sigtab, (d11.z & 0xFFFFu) * 4u)); - const float vax = fgp_bil(fx, fy, gx, gy, wg_h2f_lo(d00.x), wg_h2f_lo(d10.x), wg_h2f_lo(d01.x), wg_h2f_lo(d11.x)); - const float vay = fgp_bil(fx, fy, gx, gy, wg_h2f_hi(d00.x), wg_h2f_hi(d10.x), wg_h2f_hi(d01.x), wg_h2f_hi(d11.x)); - const float vbx = fgp_bil(fx, fy, gx, gy, wg_h2f_lo(d00.y), wg_h2f_lo(d10.y), wg_h2f_lo(d01.y), wg_h2f_lo(d11.y)); - const float vby = fgp_bil(fx, fy, gx, gy, wg_h2f_hi(d00.y), wg_h2f_hi(d10.y), wg_h2f_hi(d01.y), wg_h2f_hi(d11.y)); - // the two candidates re-sampled at the pixel plus k times the vectors (pixel units) - const float kf = (float)k; - const float3 A = fgf_bil4h(x0, fgf_tap(vax * kf + (float)px, vay * kf + (float)py, Wo, Ho)).xyz; - const float3 B = fgf_bil4h(x1, fgf_tap(vbx * kf + (float)px, vby * kf + (float)py, Wo, Ho)).xyz; - float3 c = fgf_sat3(mad(sigma, A, (1.0f - sigma) * B)); - if (isnan(abs(c.z * (c.x * c.y)))) c = float3(0.0f, 1.0f, 1.0f); - if (hole) c = 0.0f; - fgf_st4h(outp, (py + out_y) * out_pitch + px + out_x, float4(c, 1.0f)); - fgf_st1h(fine, py * Wo + px, hole ? 1.0f : 0.0f); + out_c = c; acc = float4(c, hole ? 0.0f : 1.0f); } - fgp_s[l] = acc; - [unroll] for (uint lvl = 1u; lvl <= 4u; ++lvl) { - fgp_steps(l, 1u << (2u * lvl - 2u)); - if ((l & ((1u << (2u * lvl)) - 1u)) == 0u) { - const int X = px >> lvl, Y = py >> lvl; - if (X < fgp_size(Wo, lvl) && Y < fgp_size(Ho, lvl)) { - const uint dst = lvl == 1u ? lv1 : (lvl == 2u ? lv2 : (lvl == 3u ? lv3 : lv4)); - fgf_st4h(dst, Y * fgp_size(Wo, lvl) + X, fgf_level(fgp_s[l], (float)(1u << (2u * lvl)))); - } - } + { + v8f pv; + pv.v[0] = fgf_opq(out_c.x); pv.v[1] = fgf_opq(out_c.y); pv.v[2] = fgf_opq(out_c.z); + [unroll] for (uint ci = 3u; ci < 8u; ++ci) pv.v[ci] = 0.0f; + const uint4 h = wg_to_f16_ags(pv); + if (in_bounds) + wg_st64(outp, (uint)((py + out_y) * out_pitch + px + out_x) * 8u, uint2(h.x, (h.y & 0xffffu) | 0x3c000000u)); } + fgf_store_morton_flag(fine, px, py, Wo, Ho, hole); + fgp_reduce(acc, origin, Wo, Ho, 0u, uint4(lv1, lv2, lv3, lv4)); } #endif diff --git a/clean/dx12/kernels/fg_out_push.hlsl b/clean/dx12/kernels/fg_out_push.hlsl index 67fe9327..3094f3b7 100644 --- a/clean/dx12/kernels/fg_out_push.hlsl +++ b/clean/dx12/kernels/fg_out_push.hlsl @@ -4,7 +4,8 @@ // // fg_out_push: one lane per element of one level (wf x hf), launched once per level from the coarsest written level // minus one down to level 1. filled := own (pull's level, bits copied) where own weight > 0 (unordered: a NaN weight -// keeps own), else the 9/3/3/1 upsample of the filled coarser level (wc x hc), 4 x float16. +// keeps own), else the 9/3/3/1 upsample of the filled coarser level (wc x hc), 4 x float16. In-place +// pushes only read the old weight, then write the filled pixel where it was missing. // fg_out_push_fine: one lane per frame pixel; where the fine flag is > 0 (a hole), out := (upsample of filled level 1, // 1.0) (row pitch out_pitch, offset (out_x, out_y)); other pixels are not written. // @@ -44,10 +45,15 @@ WG_KERNEL(fg_out_push) FGF_SETUP(); const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); if (idx >= wf * hf) return; - const uint2 o = wg_ld64(own, (uint)idx * 8u); - if (!(wg_h2f_hi(o.y) <= 0.0f)) { - wg_st64(filled, (uint)idx * 8u, o); - return; + const uint offset = (uint)idx * 8u; + if (own == filled) { + if (!(wg_h2f(wg_ld16(own, offset + 6u)) <= 0.0f)) return; + } else { + const uint2 o = wg_ld64(own, offset); + if (!(wg_h2f_hi(o.y) <= 0.0f)) { + wg_st64(filled, offset, o); + return; + } } const int qy = idx / wf, qx = idx - qy * wf; fgf_st4h(filled, idx, fgf_up(coarse, wc, hc, qx, qy)); diff --git a/clean/fg/proxy/win32/fg_asi_session.cpp b/clean/fg/proxy/win32/fg_asi_session.cpp index a457ddbb..ac508c48 100644 --- a/clean/fg/proxy/win32/fg_asi_session.cpp +++ b/clean/fg/proxy/win32/fg_asi_session.cpp @@ -318,8 +318,7 @@ struct FgAsiSessionHost::Impl { last_values[1] = last_values[2]; last_values[2] = exec->LastComputeValue(); if (want == 0) return; - const ULONGLONG until = GetTickCount64() + 50; - while (exec->CompletedComputeValue() < want && GetTickCount64() < until) Sleep(0); + exec->WaitForComputeValue(want, 50); } void DestroySession(const char* why) { diff --git a/clean/fg/runner/fg_net2_mma.py b/clean/fg/runner/fg_net2_mma.py index 399c096d..22aeb5d1 100644 --- a/clean/fg/runner/fg_net2_mma.py +++ b/clean/fg/runner/fg_net2_mma.py @@ -4,7 +4,7 @@ python clean/fg/runner/fg_net2_mma.py --build --rocm "C:\\Program Files\\AMD\\ROCm\\7.2" --prepare python clean/fg/runner/fg_net2_mma.py --build --make - python clean/fg/runner/fg_net2_mma.py --build --run [--json out.json] + python clean/fg/runner/fg_net2_mma.py --build --run [--model ] [--json out.json] python clean/fg/runner/fg_net2_mma.py --build --timing --record out.json [--json timing.json] python clean/fg/runner/fg_net2_mma.py --build --profile "," [--json profile.json] @@ -633,93 +633,287 @@ def chain_lines(m, fill, tag, **kw): return out -def run(build, groups=("exactval", "probe", "kernel", "chain", "mutant", "exact", "full")): - cdir = os.path.join(build, "replay-net2-mma") - man = json.load(open(os.path.join(cdir, "manifest.json"), encoding="utf-8")) +def _model_chain_no_ref(name, W2, H2, params, ib, ic, ia, f, fast): + """net2 fast or exact chain without running the slow CPU reference (for large --model grids compared GPU-vs-GPU).""" + ext = N.extents(W2, H2) + c = FastCase(name, "chain") if fast else K.Case(name, "chain") + A = {"Ib": c.buf("Ib", ib), "Ic": c.buf("Ic", ic), "Ia": c.buf("Ia", ia)} + for l in L.NET2: + w, b = params[l.name] + A["w" + l.name[-2:]], A["b" + l.name[-2:]] = c.buf("w" + l.name[-2:], w), c.buf("b" + l.name[-2:], b) + shapes = { + "x": (H2, W2, 10), "a1": (H2 // 2, W2 // 2, 32), "a2": (H2 // 4, W2 // 4, 32), + "r0": (H2 // 8, W2 // 8, 64), "g": (H2 // 4, W2 // 4, 96), + "hA4": (*ext["A4"], 4), "hA1": (*ext["A1"], 1), "hA3": (*ext["A3"], 3), + "U4": (H2, W2, 4), "U1": (H2, W2, 1), "U3": (H2, W2, 3), + "y": (H2, W2, 18), "b1": (H2 // 2, W2 // 2, 16), "s0": (H2 // 4, W2 // 4, 32), + "e": (H2 // 2, W2 // 2, 48), "out": (H2, W2, 8), + } + for u in range(1, 5): + shapes["t%d" % u] = (H2 // 8, W2 // 8, 64) + shapes["r%d" % u] = (H2 // 8, W2 // 8, 64) + shapes["tb%d" % u] = (H2 // 4, W2 // 4, 32) + shapes["s%d" % u] = (H2 // 4, W2 // 4, 32) + if not fast: + shapes["r4u"] = (H2 // 4, W2 // 4, 64) + shapes["gu"] = (*ext["A4"], 96) + shapes["s4u"] = (H2 // 2, W2 // 2, 32) + shapes["eu"] = (H2, W2, 48) + for i, sh in shapes.items(): + A[i] = c.out(i, sh) + + def wb(n): + return A["w%02d" % n], A["b%02d" % n] + + def conv(n, src, dst, cin, H, W, **kw): + l = L.NET2[n - 1] + c.conv(A[src], *wb(n), A[dst], in_cs=shapes[src][2], cin=cin, cw=l.cin, + co_n=kw.pop("co_n", l.out), H=H, W=W, **kw) + + def block(first, src, temps, outs, cin): + H, W = shapes[src][:2] + for u in range(4): + t, r = "%s%d" % (temps, u + 1), "%s%d" % (outs, u + 1) + conv(first + 2 * u, src, t, cin, H, W, res=1) + conv(first + 2 * u + 1, t, r, cin, H, W, res=2, skip=A[src], skip_cs=cin) + src = r + + c.merge(A["Ib"], A["Ic"], A["Ia"], A["x"], W2 * H2, f) + conv(1, "x", "a1", 10, H2, W2, pool=1) + conv(2, "a1", "a2", 32, *shapes["a1"][:2], pool=1) + conv(3, "a2", "r0", 32, *shapes["a2"][:2], pool=1) + block(4, "r0", "t", "r", 64) + h4, w4 = shapes["g"][:2] + h2, w2 = ext["A4"] + if fast: + conv(12, "r4", "g", 64, h4, w4, up=1, clamp_from=32) + conv(13, "g", "hA4", 32, h2, w2, up=1, heads=1, co_n=8, out_cs=0, leaky=0, clamp_from=4, y1=A["hA1"], y2=A["hA3"]) + c.upwarp(A["Ib"], A["Ic"], A["Ia"], A["hA4"], A["hA1"], A["hA3"], A["U4"], A["U1"], A["U3"], A["y"], W2, H2, f) + else: + c.up2(A["r4"], A["r4u"], 64, *shapes["r4"][:2]) + conv(12, "r4u", "g", 64, h4, w4, clamp_from=32) + c.up2(A["g"], A["gu"], 96, h4, w4) + for j, ((lo, n), cf, nm) in enumerate(zip(HEAD_KEEP, (K.NO_CLAMP, 0, 0), ("hA4", "hA1", "hA3"))): + conv(13, "gu", nm, 32, h2, w2, in_co=32 * j, co_lo=lo, co_n=n, leaky=0, clamp_from=cf) + for nm, ch in (("A4", 4), ("A1", 1), ("A3", 3)): + c.up2(A["h" + nm], A["U" + nm[1]], ch, h2, w2) + c.warp(A["Ib"], A["Ic"], A["Ia"], A["U4"], A["U1"], A["U3"], A["y"], W2, H2, f) + conv(14, "y", "b1", 18, H2, W2, pool=1) + conv(15, "b1", "s0", 16, *shapes["b1"][:2], pool=1) + block(16, "s0", "tb", "s", 32) + eh, ew = shapes["e"][:2] + if fast: + conv(24, "s4", "e", 32, eh, ew, up=1, clamp_from=K.NO_CLAMP) + conv(25, "e", "out", 16, H2, W2, up=1, heads=1, co_n=8, out_cs=8, leaky=0, clamp_from=4, res=2, + res_mul=K.F16_TWO, skip=A["U4"], skip1=A["U1"], skip2=A["U3"]) + else: + c.up2(A["s4"], A["s4u"], 32, *shapes["s4"][:2]) + conv(24, "s4u", "e", 32, eh, ew, clamp_from=K.NO_CLAMP) + c.up2(A["e"], A["eu"], 48, eh, ew) + for j, ((lo, n), cf, unm) in enumerate(zip(HEAD_KEEP, (K.NO_CLAMP, 0, 0), ("U4", "U1", "U3"))): + conv(25, "eu", "out", 16, H2, W2, in_co=16 * j, co_lo=lo, co_n=n, out_cs=8, out_co=lo, leaky=0, + clamp_from=cf, res=2, res_mul=K.F16_TWO if j == 0 else K.F16_ONE, skip=A[unm], skip_cs=n) + return c + + +def run_model(build, model_path): + """Execute-only check of a converted preset-FG model.wgcm on net2 (fast Tier B vs exact oracle): + - 48x32 smooth input with CPU reference (exact must match CPU bit-for-bit; fast reported vs CPU/exact); + - 480x272 (1080p/4K net2 grid) smooth input GPU-vs-GPU (fast vs exact on D3D12, both fills, slack checked). + Every temporary file written for the replay (weights, inputs, expectations, outputs) is deleted in finally.""" + from clean.fg.reference import forward as F + with open(model_path, "rb") as fh: + model_sha = hashlib.sha256(fh.read()).hexdigest() + raw_params = F.params_from_model_file(model_path) + params = {} + for l in L.NET2: + w, b = raw_params[l.name] + w = np.asarray(w, np.float64) + if w.shape[3] < l.cin: + p = np.zeros((l.out, 3, 3, l.cin), np.float64) + p[:, :, :, :w.shape[3]] = w + w = p + params[l.name] = (w, np.asarray(b, np.float64)) rid = time.strftime("%H%M%S") - tags = [("f%02x_%s" % (f, rid), f) for f in FILLS] - neg_tag = "neg_" + rid - lines, negs = [], {} - for g in groups: - for m in man.get(g, []): - if g == "mutant": - lines += chain_lines(m, FILLS[0], tags[0][0]) - continue - for tag, fill in tags: - lines += chain_lines(m, fill, tag) - k0 = m["steps"][0][0] - if g == "exactval" and k0 not in negs and m["steps"][0][1] >= 2: - negs[k0] = m - lines += chain_lines(m, FILLS[0], neg_tag, half=0) - used = [m for g in groups for m in man.get(g, [])] - rep, out = K.replay(build, cdir, lines, K.arena_for(used)) - names = [ln.split()[1] for ln in lines if ln.startswith("chain ")] - not_ok = [n for n in names if "%s: ok" % n not in out] - rep["chains"], rep["chains_not_ok"] = len(names), not_ok - res = {"replay": rep, "cases": [], "negative_controls": {}, "mutants": {}} - ok = rep["exit"] == 0 and rep["killed"] is None and not not_ok - base = None - for g in groups: - for m in man.get(g, []): - if g == "mutant": - if m["name"] == "fast mutant base": - base = m - good, bufs = fills_agree(cdir, m, [tags[0], tags[0]]) - res["mutants"]["base"] = {"present": good, "report": total_report(report_entry(cdir, m, - tags[0][0]).values())} - ok = ok and good + mdir = os.path.join(build, "replay-net2-model-" + rid) + os.makedirs(mdir, exist_ok=True) + tags = [("f%02x_%s" % (fl, rid), fl) for fl in FILLS] + try: + rng = np.random.default_rng(20261123) + ib_s, ic_s, ia_s = (smooth(rng, 32, 48, ch, 1.0) for ch in (4, 4, 1)) + ib_l, ic_l, ia_l = (smooth(rng, 272, 480, ch, 1.0) for ch in (4, 4, 1)) + fval = np.float32(0.4375) + with reference_memo(): + c_small_fast = fast_chain_case("model fast 48x32", 48, 32, params, ib_s, ic_s, ia_s, fval) + c_small_exact = K.chain_case("model exact 48x32", 48, 32, params, ib_s, ic_s, ia_s, fval) + c_big_fast = _model_chain_no_ref("model fast 480x272", 480, 272, params, ib_l, ic_l, ia_l, fval, True) + c_big_exact = _model_chain_no_ref("model exact 480x272", 480, 272, params, ib_l, ic_l, ia_l, fval, False) + cases_list = [c_small_fast, c_small_exact, c_big_fast, c_big_exact] + metas = [] + for c in cases_list: + m = K.write_case(mdir, c) + m["sizes"] = {i: len(b) for i, b in c.data.items()} + metas.append(m) + lines = [] + for m in metas: + for tag, fl in tags: + lines += chain_lines(m, fl, tag) + rep, out = K.replay(build, mdir, lines, K.arena_for(metas)) + names = [ln.split()[1] for ln in lines if ln.startswith("chain ")] + not_ok = [n for n in names if "%s: ok" % n not in out] + rep["chains"], rep["chains_not_ok"] = len(names), not_ok + ok = rep["exit"] == 0 and rep["killed"] is None and not not_ok + entries = [] + # small exact vs CPU reference + msf, mse, mbf, mbe = metas + good_se, bufs_se = K.check_entry(mdir, mse, tags) + ok = ok and good_se + entries.append({"group": "model", "case": mse["name"], "launches": len(mse["steps"]), + "gate": "byte-identical to the CPU reference", "ok": good_se, + "out_sha256": hashlib.sha256(_saved(mdir, mse, tags[0][0], "out")[:mse["outs"]["out"]]).hexdigest()}) + # small fast vs CPU reference + fills + good_sf, _ = fills_agree(mdir, msf, tags) + reps_sf = report_entry(mdir, msf, tags[0][0]) + ok = ok and good_sf + entries.append({"group": "model", "case": msf["name"], "launches": len(msf["steps"]), + "gate": "both fills identical, slack kept", "ok": good_sf, + "vs_cpu_out": reps_sf.get("out"), "vs_cpu_total": total_report(reps_sf.values()), + "out_sha256": hashlib.sha256(_saved(mdir, msf, tags[0][0], "out")[:msf["outs"]["out"]]).hexdigest()}) + # large exact (both fills deterministic + slack) + good_be, _ = fills_agree(mdir, mbe, tags) + ok = ok and good_be + be_out = _saved(mdir, mbe, tags[0][0], "out")[:mbe["outs"]["out"]] + entries.append({"group": "model", "case": mbe["name"], "launches": len(mbe["steps"]), + "gate": "both fills identical, slack kept", "ok": good_be, + "out_sha256": hashlib.sha256(be_out).hexdigest()}) + # large fast vs large exact (GPU-vs-GPU across all common buffers) + good_bf, _ = fills_agree(mdir, mbf, tags) + ok = ok and good_bf + bf_out = _saved(mdir, mbf, tags[0][0], "out")[:mbf["outs"]["out"]] + common = [i for i in mbf["outs"] if i in mbe["outs"]] + vs_ex = {} + for i in common: + n = mbf["outs"][i] + rf = _saved(mdir, mbf, tags[0][0], i)[:n] + re = _saved(mdir, mbe, tags[0][0], i)[:n] + vs_ex[i] = step_report(np.frombuffer(rf, np.uint16), np.frombuffer(re, np.float16).astype(np.float64)) + entries.append({"group": "model", "case": mbf["name"], "launches": len(mbf["steps"]), + "gate": "both fills identical, slack kept", "ok": good_bf, + "vs_exact_out": vs_ex.get("out"), "vs_exact_total": total_report(vs_ex.values()), + "out_sha256": hashlib.sha256(bf_out).hexdigest()}) + return {"model_sha256": model_sha, "replay": rep, "cases": entries, "ok": bool(ok)} + finally: + for fn in os.listdir(mdir): + p = os.path.join(mdir, fn) + if os.path.isfile(p): + os.remove(p) + if os.path.isdir(mdir) and not os.listdir(mdir): + os.rmdir(mdir) + + +def run(build, groups=("exactval", "probe", "kernel", "chain", "mutant", "exact", "full"), model=None): + cdir = os.path.join(build, "replay-net2-mma") + std_groups = [g for g in groups if g != "model"] + run_mod = bool(model) or ("model" in groups) + if run_mod and not model: + raise SystemExit("--groups model requires --model ") + res = {"replay": None, "cases": [], "negative_controls": {}, "mutants": {}} + ok = True + if std_groups: + man = json.load(open(os.path.join(cdir, "manifest.json"), encoding="utf-8")) + rid = time.strftime("%H%M%S") + tags = [("f%02x_%s" % (f, rid), f) for f in FILLS] + neg_tag = "neg_" + rid + lines, negs = [], {} + for g in std_groups: + for m in man.get(g, []): + if g == "mutant": + lines += chain_lines(m, FILLS[0], tags[0][0]) continue - kind = m["name"].split()[-1] - target, before = K.MUTANT_TARGETS[kind] - diff = {} - for i, n in m["outs"].items(): - a, b = _saved(cdir, m, tags[0][0], i), _saved(cdir, base, tags[0][0], i) - diff[i] = (-1 if len(a) != n + SLACK or len(b) != n + SLACK else - int(np.sum(np.frombuffer(a[:n], np.uint16) != np.frombuffer(b[:n], np.uint16)))) - before = [i for i in before if i in diff] if before is not None else [i for i in diff if i != target] - caught = diff[target] > 0 - clean = all(diff[i] == 0 for i in before) - res["mutants"][m["name"]] = {"caught": caught and clean, "target": target, "target_differ": diff[target], - "before_match_plain_run": clean} - ok = ok and caught and clean - continue - entry = {"group": g, "case": m["name"], "kernels": m["launch_kernels"], "launches": len(m["steps"])} - if g in ("exactval", "probe", "exact"): - good, bufs = K.check_entry(cdir, m, tags) - entry.update({"gate": "byte-identical to the CPU reference", "ok": good, "buffers": bufs}) - if m.get("alts"): - n = 0 - for i in m["alts"]: - alt = np.load(os.path.join(cdir, "%s.alt.%s.npy" % (m["id"], i))) - r = K.compare(_saved(cdir, m, tags[0][0], i), alt, m["outs"][i], tags[0][1]) - n += max(0, r["differ"]) - res["mutants"]["two roundings: " + m["name"]] = {"caught": n > 0, "differ": n} - good = good and n > 0 - else: - good, bufs = fills_agree(cdir, m, tags) - reps = report_entry(cdir, m, tags[0][0]) - entry.update({"gate": "both fills identical, slack kept", "ok": good, "buffers": bufs, - "vs_cpu": reps, "vs_cpu_total": total_report(reps.values())}) - if "out" in m["outs"]: - entry["out_sha256"] = hashlib.sha256(_saved(cdir, m, tags[0][0], "out")[:m["outs"]["out"]]).hexdigest() - ok = ok and good - res["cases"].append(entry) - for k in FAST_KERNELS: - m = negs.get(k) - if m is None: - res["negative_controls"][k] = None - ok = False - continue - _, bufs = K.check_entry(cdir, m, [(neg_tag, FILLS[0])]) - caught = any(b["differ"][0] > 0 for b in bufs.values()) and all(b["differ"][0] >= 0 for b in bufs.values()) - res["negative_controls"][k] = {"case": m["name"], "half_grid": True, "caught": caught, - "differ": sum(b["differ"][0] for b in bufs.values())} - ok = ok and caught + for tag, fill in tags: + lines += chain_lines(m, fill, tag) + k0 = m["steps"][0][0] + if g == "exactval" and k0 not in negs and m["steps"][0][1] >= 2: + negs[k0] = m + lines += chain_lines(m, FILLS[0], neg_tag, half=0) + used = [m for g in std_groups for m in man.get(g, [])] + rep, out = K.replay(build, cdir, lines, K.arena_for(used)) + names = [ln.split()[1] for ln in lines if ln.startswith("chain ")] + not_ok = [n for n in names if "%s: ok" % n not in out] + rep["chains"], rep["chains_not_ok"] = len(names), not_ok + res["replay"] = rep + ok = rep["exit"] == 0 and rep["killed"] is None and not not_ok + base = None + for g in std_groups: + for m in man.get(g, []): + if g == "mutant": + if m["name"] == "fast mutant base": + base = m + good, bufs = fills_agree(cdir, m, [tags[0], tags[0]]) + res["mutants"]["base"] = {"present": good, "report": total_report(report_entry(cdir, m, + tags[0][0]).values())} + ok = ok and good + continue + kind = m["name"].split()[-1] + target, before = K.MUTANT_TARGETS[kind] + diff = {} + for i, n in m["outs"].items(): + a, b = _saved(cdir, m, tags[0][0], i), _saved(cdir, base, tags[0][0], i) + diff[i] = (-1 if len(a) != n + SLACK or len(b) != n + SLACK else + int(np.sum(np.frombuffer(a[:n], np.uint16) != np.frombuffer(b[:n], np.uint16)))) + before = [i for i in before if i in diff] if before is not None else [i for i in diff if i != target] + caught = diff[target] > 0 + clean = all(diff[i] == 0 for i in before) + res["mutants"][m["name"]] = {"caught": caught and clean, "target": target, "target_differ": diff[target], + "before_match_plain_run": clean} + ok = ok and caught and clean + continue + entry = {"group": g, "case": m["name"], "kernels": m["launch_kernels"], "launches": len(m["steps"])} + if g in ("exactval", "probe", "exact"): + good, bufs = K.check_entry(cdir, m, tags) + entry.update({"gate": "byte-identical to the CPU reference", "ok": good, "buffers": bufs}) + if m.get("alts"): + n = 0 + for i in m["alts"]: + alt = np.load(os.path.join(cdir, "%s.alt.%s.npy" % (m["id"], i))) + r = K.compare(_saved(cdir, m, tags[0][0], i), alt, m["outs"][i], tags[0][1]) + n += max(0, r["differ"]) + res["mutants"]["two roundings: " + m["name"]] = {"caught": n > 0, "differ": n} + good = good and n > 0 + else: + good, bufs = fills_agree(cdir, m, tags) + reps = report_entry(cdir, m, tags[0][0]) + entry.update({"gate": "both fills identical, slack kept", "ok": good, "buffers": bufs, + "vs_cpu": reps, "vs_cpu_total": total_report(reps.values())}) + if "out" in m["outs"]: + entry["out_sha256"] = hashlib.sha256(_saved(cdir, m, tags[0][0], "out")[:m["outs"]["out"]]).hexdigest() + ok = ok and good + res["cases"].append(entry) + if "exactval" in std_groups: + for k in FAST_KERNELS: + m = negs.get(k) + if m is None: + res["negative_controls"][k] = None + ok = False + continue + _, bufs = K.check_entry(cdir, m, [(neg_tag, FILLS[0])]) + caught = any(b["differ"][0] > 0 for b in bufs.values()) and all(b["differ"][0] >= 0 for b in bufs.values()) + res["negative_controls"][k] = {"case": m["name"], "half_grid": True, "caught": caught, + "differ": sum(b["differ"][0] for b in bufs.values())} + ok = ok and caught + if run_mod: + mres = run_model(build, model) + res["model"] = {"model_sha256": mres["model_sha256"], "replay": mres["replay"], "ok": mres["ok"]} + if res["replay"] is None: + res["replay"] = mres["replay"] + res["cases"].extend(mres["cases"]) + ok = ok and mres["ok"] cs = res["cases"] res["summary"] = {"cases": len(cs), "cases_ok": sum(c["ok"] for c in cs), - "byte_exact_cases": sum(1 for c in cs if c["group"] in ("exactval", "probe", "exact")), + "byte_exact_cases": sum(1 for c in cs if c["group"] in ("exactval", "probe", "exact") or c["case"] == "model exact 48x32"), "fills": [hex(f) for f in FILLS], "pass": bool(ok)} - res["accuracy"] = {c["case"]: c["vs_cpu_total"] for c in cs if c.get("vs_cpu_total")} + res["accuracy"] = {c["case"]: (c.get("vs_cpu_total") or c.get("vs_exact_total")) + for c in cs if (c.get("vs_cpu_total") or c.get("vs_exact_total"))} return res @@ -840,6 +1034,7 @@ def main(argv=None): ap.add_argument("--make", action="store_true") ap.add_argument("--no-full", action="store_true", help="--make / --run without the 480 x 272 and 640 x 368 chains") ap.add_argument("--run", action="store_true") + ap.add_argument("--model", help="converted preset-FG model.wgcm (execute-only: per-run files deleted after run)") ap.add_argument("--groups", default="exactval,probe,kernel,chain,mutant,exact,full") ap.add_argument("--timing", action="store_true") ap.add_argument("--record", help="--timing: the passing --run record") @@ -856,7 +1051,7 @@ def main(argv=None): res = None if a.run: groups = [g for g in a.groups.split(",") if not (a.no_full and g == "full")] - res = run(a.build, groups) + res = run(a.build, groups, model=a.model) print(json.dumps(res["summary"])) print("negative controls:", json.dumps({k: v and v["caught"] for k, v in res["negative_controls"].items()}), "mutants:", json.dumps({k: v.get("caught", v.get("present")) for k, v in res["mutants"].items()})) diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index 0aa26175..49d6b00c 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include "fg_frame_dump.h" @@ -36,9 +37,14 @@ enum Kernel : uint32_t { kNet2Conv, kNet2Up2, kNet2Merge, kNet2Warp, kN2m1b1, kN2m1b2, kN2m2b1, kN2m2b2, kN2m2b4, kN2m1b4s, kN2m1b2s, kN2m1b1u, kN2m1b2u, kN2m2b4u, kN2m3b2u, kN2m3b4u, kNet2Upwarp, + kMConv2Narrow, kMConv1Late, kMPairBFirst, kMPairBSecond, kMPairD4First, kMPairD4Second, + kMPairD3Narrow, kMPairD2Narrow, + kDown2Srv, kDown4Srv, kMvecSrv, kIntermTiled, kPackPairs, kPullTiled, kPushTail, kDown2HudTile, + kMConv2Mid, kN2h3b1u, kNet2MergePixels, kKernelCount, }; constexpr uint32_t kFirstFull = kFullBlend; +constexpr uint32_t kFirstOptional = kMConv2Narrow; // The fast net2 convolution variants (clean/dx12/kernels/fg_net2_mconv.hlsl declarations, in the order // clean/fg/runner/fg_net2_mma.py VARIANTS lists them): output tiles per wave, 16-channel blocks per tap, upsample @@ -55,7 +61,7 @@ constexpr uint32_t kSmallGrid = 16384; // conv grids of at most this many pixel constexpr uint32_t kMTile = 16; bool KernelNeeded(uint32_t k, bool full, FgNet2Path path) { - if (k < kFirstFull) return true; + if (k < kFirstFull || k >= kFirstOptional) return true; if (!full) return false; if (k == kNet2Conv || k == kNet2Up2 || k == kNet2Warp) return path == FgNet2Path::Exact; if (k >= kN2m1b1 && k <= kNet2Upwarp) return path == FgNet2Path::Fast; @@ -95,12 +101,19 @@ const char* const kKernelNames[kKernelCount] = { "fg_net2_mconv_m1b1", "fg_net2_mconv_m1b2", "fg_net2_mconv_m2b1", "fg_net2_mconv_m2b2", "fg_net2_mconv_m2b4", "fg_net2_mconv_m1b4s", "fg_net2_mconv_m1b2s", "fg_net2_mconv_m1b1u", "fg_net2_mconv_m1b2u", "fg_net2_mconv_m2b4u", "fg_net2_mconv_m3b2u", "fg_net2_mconv_m3b4u", "fg_net2_upwarp", + "fg_mconv2_narrow", "fg_mconv1_late", "fg_mpair_b_first", "fg_mpair_b_second", + "fg_mpair_d4_first", "fg_mpair_d4_second", "fg_mpair_d3_narrow", "fg_mpair_d2_narrow", + "fg_lite_downsample2_srv", "fg_lite_downsample4_srv", "fg_lite_mvec_srv", "fg_lite_interm_tiled", "fg_exec_pack_pairs", + "fg_lite_p2c_pull_tiled", "fg_lite_p2c_push_tail", "fg_lite_downsample2_srv_hud_tile", + "fg_mconv2_mid", "fg_net2_mconv_h3b1u", "fg_net2_merge_pixels", }; constexpr uint32_t kRootConstants = 59; // 2 runtime constants + up to 57 argument DWORDs constexpr uint32_t kMaxArgs = kRootConstants - 2; constexpr uint32_t kChannelSpace = 0x7FFF0ADE; -constexpr uint32_t kPairs = 8; // descriptor pairs (channel UAV, texture view) per allocator +constexpr uint32_t kTables = 8; // immutable descriptor tables per command recording +constexpr uint32_t kInputSrvs = 4; +constexpr uint32_t kTableSize = 1 + kInputSrvs; // channel UAV followed by t0..t3 constexpr uint32_t kNoClamp = 1u << 20; constexpr uint32_t kHalfOne = 0x3C00, kHalfTwo = 0x4000; @@ -175,6 +188,18 @@ int pack_code(DXGI_FORMAT f, uint32_t* bpp) { return -1; } +DXGI_FORMAT linear_copy_format(DXGI_FORMAT f) { + switch (f) { + case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + return DXGI_FORMAT_R8G8B8A8_UNORM; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + return DXGI_FORMAT_B8G8R8A8_UNORM; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: + return DXGI_FORMAT_R10G10B10A2_UNORM; + default: return f; + } +} + // ---- weights ----------------------------------------------------------------------------------------------------- struct Rng { @@ -349,7 +374,7 @@ bool FgD3d12MotionFormatAccepted(uint32_t dxgi_format) { std::vector FgD3d12ExecutorKernelNames(bool enable_full, FgNet2Path net2) { std::vector names; - for (uint32_t k = 0; k < kKernelCount; ++k) + for (uint32_t k = 0; k < kFirstOptional; ++k) if (KernelNeeded(k, enable_full, net2)) names.emplace_back(kKernelNames[k]); return names; } @@ -438,6 +463,16 @@ struct Entry { ComPtr list; uint64_t fence = 0; uint32_t desc_base = 0; + uint32_t query_base = 0, stage_count = 0; + FgExecStage stages[static_cast(FgExecStage::Count)] = {}; +}; + +constexpr uint32_t kTimingQueries = static_cast(FgExecStage::Count) + 1; + +struct TimingQueries { + ComPtr heap; + ComPtr readback; + uint64_t hz = 0; }; struct InputTex { @@ -453,6 +488,7 @@ struct InputTex { // The per-game-frame values the per-index stages read. struct FrameCtx { bool valid = false; + bool colour_captured = false; uint64_t token = 0; FgPreset preset = FgPreset::C; bool lite = true; @@ -468,9 +504,15 @@ struct FrameCtx { struct Rec { Entry* e = nullptr; ID3D12GraphicsCommandList* cl = nullptr; - uint32_t pair = 0; + uint32_t table = 0; D3D12_RESOURCE_STATES arena = D3D12_RESOURCE_STATE_COMMON; bool dirty = false; // a dispatch or copy wrote since the last UAV barrier + bool open = false, direct = false, uses_arena = true; + ID3D12Resource* written_slot = nullptr; + + ~Rec() { + if (open) cl->Close(); + } }; struct Net2Buf { @@ -489,6 +531,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { ComPtr device; ComPtr queue; + ComPtr compute_queue; D3D12_COMMAND_LIST_TYPE list_type = D3D12_COMMAND_LIST_TYPE_DIRECT; ComPtr root; ComPtr pso[kKernelCount]; @@ -497,13 +540,20 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { ComPtr fence; HANDLE event = nullptr; uint64_t next_value = 0; + ComPtr handoff_fence; + uint64_t handoff_value = 0, joined_handoff = 0, arena_value = 0; + std::unordered_map compute_slot_values; std::vector entries; + std::vector direct_entries; ComPtr heap; uint32_t desc_inc = 0; ComPtr channel; ComPtr arena; uint64_t arena_bytes = 0; ComPtr menu_rb; + TimingQueries producer_queries, direct_queries; + FgExecTimings timings; + bool timing_failed = false; IFgSlotTarget* target = nullptr; uint32_t fence_id = 0; @@ -525,9 +575,9 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { uint32_t pack_off = 0, pack_pitch = 0; // packed slot rows FgNet1Plan n1plan; FgArenaBinding n1arena; - uint32_t n1_cells = 0, n1_out = 0; + uint32_t n1_cells = 0, n1_out = 0, n1_pair_scratch = 0; // Full path - uint32_t x0 = 0, x1 = 0, xw = 0, ib = 0, ic = 0, ia = 0, fine = 0, sig = 0, lv[9] = {}, fd[8] = {}; + uint32_t x0 = 0, x1 = 0, xw = 0, ib = 0, ic = 0, ia = 0, fine = 0, sig = 0, lv[9] = {}; uint32_t n2w[kFgNet2Layers] = {}, n2b[kFgNet2Layers] = {}; uint32_t n2fw[kFgNet2Layers] = {}, n2fb[kFgNet2Layers] = {}; // fast path: A fragments, padded biases std::vector n2frag[kFgNet2Layers], n2fbias[kFgNet2Layers]; @@ -548,6 +598,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { struct DumpRb { ComPtr buf; uint64_t fence_value = 0; // 0 until the recording that copies it is submitted + bool direct = false; uint32_t w = 0, h = 0, pitch = 0, format = 0; std::string name; }; @@ -584,6 +635,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { char kind, uint64_t token, uint32_t index) { if (!dump_armed || token != dump_token || (kind != 'g' && kind != 'r' && kind != 'm')) return; DumpRb d; + d.direct = r.direct; d.w = fp.Footprint.Width; d.h = fp.Footprint.Height; d.format = static_cast(fp.Footprint.Format); @@ -617,8 +669,9 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { try { for (size_t i = 0; i < dumps.size();) { DumpRb& d = dumps[i]; - if (d.fence_value == 0 || (fence->GetCompletedValue() < d.fence_value && - !(wait && WaitValue(d.fence_value, desc.wait_ms)))) { + ID3D12Fence* completion = d.direct ? handoff_fence.Get() : fence.Get(); + if (d.fence_value == 0 || (completion->GetCompletedValue() < d.fence_value && + !(wait && WaitFence(completion, d.fence_value, desc.wait_ms)))) { ++i; continue; } @@ -668,7 +721,10 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { if (!KernelNeeded(k, desc.enable_full, desc.net2)) continue; const std::string path = desc.dxil_dir + "\\" + kKernelNames[k] + ".dxil"; std::vector c; - if (!read_file(path, &c)) return Fail(FgExecRefusal::DxilMissing, std::string(kKernelNames[k]) + ".dxil"); + if (!read_file(path, &c)) { + if (k >= kFirstOptional) continue; + return Fail(FgExecRefusal::DxilMissing, std::string(kKernelNames[k]) + ".dxil"); + } if (c.size() < 32 || c.size() > 64u * 1024u * 1024u || std::memcmp(c.data(), "DXBC", 4) != 0) return Fail(FgExecRefusal::DxilInvalid, std::string(kKernelNames[k]) + ".dxil is not a DXIL container"); code[k] = std::move(c); @@ -683,7 +739,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { ranges[0].RegisterSpace = kChannelSpace; ranges[0].OffsetInDescriptorsFromTableStart = 0; ranges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; - ranges[1].NumDescriptors = 1; + ranges[1].NumDescriptors = kInputSrvs; ranges[1].OffsetInDescriptorsFromTableStart = 1; D3D12_ROOT_PARAMETER p[4] = {}; p[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; @@ -703,7 +759,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { IID_PPV_ARGS(&root)))) return Fail(FgExecRefusal::RootSignature, "root signature creation failed"); for (uint32_t k = 0; k < kKernelCount; ++k) { - if (!KernelNeeded(k, desc.enable_full, desc.net2)) continue; + if (code[k].empty()) continue; D3D12_COMPUTE_PIPELINE_STATE_DESC pd = {}; pd.pRootSignature = root.Get(); pd.CS.pShaderBytecode = code[k].data(); @@ -758,6 +814,15 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { n1arena.region_base[2] = Alloc(n1plan.region_bytes[2]); n1_cells = static_cast(n1arena.region_base[0] + n1plan.buffers[n1plan.Find("cells")].offset); n1_out = static_cast(n1arena.region_base[2] + n1plan.buffers[n1plan.Find("out")].offset); + // The two coarse pairs run in sequence and can share the first convolution's output buffer. + const bool split_b = pso[kMPairBFirst] && pso[kMPairBSecond]; + const bool split_d4 = pso[kMPairD4First] && pso[kMPairD4Second]; + n1_pair_scratch = 0; + if (split_b || split_d4) { + const uint64_t b_bytes = split_b ? 2 * n1plan.buffers[n1plan.Find("p5")].bytes : 0; + const uint64_t d4_bytes = split_d4 ? n1plan.buffers[n1plan.Find("a4")].bytes : 0; + n1_pair_scratch = Alloc(std::max(b_bytes, d4_bytes)); + } if (desc.enable_full) { const uint64_t fr = static_cast(g.wo) * g.ho, n2 = static_cast(g.W2) * g.H2; x0 = Alloc(fr * 8); @@ -771,7 +836,6 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { uint32_t w, h; FgExecOutLevelSize(g, l, &w, &h); lv[l] = Alloc(8ull * w * h); - if (l < 8) fd[l] = Alloc(8ull * w * h); } nb_x = N2(1, 10); nb_a1 = N2(2, 32); @@ -883,14 +947,17 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { if (!fence) { if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_SHARED, IID_PPV_ARGS(&fence)))) return Fail(FgExecRefusal::FenceFailed, "shared fence creation failed"); + } + if (!event) { event = CreateEventW(nullptr, FALSE, FALSE, nullptr); if (!event) return Fail(FgExecRefusal::FenceFailed, "event creation failed"); } - if (entries.empty()) { + if (!heap) { const uint32_t n = std::max(4, desc.allocators); + const uint32_t count = compute_queue ? 2 * n : n; D3D12_DESCRIPTOR_HEAP_DESC hd = {}; hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - hd.NumDescriptors = n * kPairs * 2; + hd.NumDescriptors = count * kTables * kTableSize; hd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; if (FAILED(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap)))) return Fail(FgExecRefusal::AllocationFailed, "descriptor heap"); @@ -902,7 +969,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { for (uint32_t d = 0; d < hd.NumDescriptors; ++d) { D3D12_CPU_DESCRIPTOR_HANDLE h = heap->GetCPUDescriptorHandleForHeapStart(); h.ptr += static_cast(d) * desc_inc; - if (d % 2 == 0) { + if (d % kTableSize == 0) { D3D12_UNORDERED_ACCESS_VIEW_DESC uav = {}; uav.Format = DXGI_FORMAT_R32_TYPELESS; uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; @@ -918,23 +985,99 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { device->CreateShaderResourceView(nullptr, &sv, h); } } - entries.resize(n); - for (uint32_t i = 0; i < n; ++i) { - if (FAILED(device->CreateCommandAllocator(list_type, IID_PPV_ARGS(&entries[i].alloc))) || - FAILED(device->CreateCommandList(0, list_type, entries[i].alloc.Get(), nullptr, - IID_PPV_ARGS(&entries[i].list))) || - FAILED(entries[i].list->Close())) - return Fail(FgExecRefusal::AllocationFailed, "command allocator / list"); - entries[i].desc_base = i * kPairs * 2; + if (!CreateEntries(entries, n, 0, ProducerQueue()) || + (compute_queue && !CreateEntries(direct_entries, n, n, queue.Get()))) + return Fail(FgExecRefusal::AllocationFailed, "command allocator / list"); + if (desc.timing) { + CreateTimingQueries(producer_queries, n, ProducerQueue()); + if (compute_queue) CreateTimingQueries(direct_queries, n, queue.Get()); } } return FgExecResult::Ok; } - bool WaitValue(uint64_t v, uint32_t ms) { - if (fence->GetCompletedValue() >= v) return true; - if (FAILED(fence->SetEventOnCompletion(v, event))) return false; - return WaitForSingleObject(event, ms) == WAIT_OBJECT_0 || fence->GetCompletedValue() >= v; + ID3D12CommandQueue* ProducerQueue() const { return compute_queue ? compute_queue.Get() : queue.Get(); } + + bool CreateEntries(std::vector& ring, uint32_t count, uint32_t first, ID3D12CommandQueue* q) { + const auto type = q->GetDesc().Type; + ring.resize(count); + for (uint32_t i = 0; i < count; ++i) { + Entry& e = ring[i]; + if (FAILED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&e.alloc))) || + FAILED(device->CreateCommandList(0, type, e.alloc.Get(), nullptr, IID_PPV_ARGS(&e.list))) || + FAILED(e.list->Close())) + return false; + e.desc_base = (first + i) * kTables * kTableSize; + e.query_base = i * kTimingQueries; + } + return true; + } + + void CreateTimingQueries(TimingQueries& q, uint32_t count, ID3D12CommandQueue* source) { + if (FAILED(source->GetTimestampFrequency(&q.hz)) || !q.hz) return; + D3D12_QUERY_HEAP_DESC qd = {}; + qd.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP; + qd.Count = count * kTimingQueries; + if (SUCCEEDED(device->CreateQueryHeap(&qd, IID_PPV_ARGS(&q.heap)))) + q.readback = Buffer(qd.Count * sizeof(uint64_t), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST); + } + + void TimeStage(Rec& r, FgExecStage stage) { + const auto& q = r.direct ? direct_queries : producer_queries; + if (!q.readback) return; + Entry& e = *r.e; + if (e.stage_count && e.stages[e.stage_count - 1] == stage) return; + r.cl->EndQuery(q.heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.query_base + e.stage_count); + e.stages[e.stage_count++] = stage; + } + + void ResolveTimings(Rec& r) { + const Entry& e = *r.e; + if (!e.stage_count) return; + const auto& q = r.direct ? direct_queries : producer_queries; + r.cl->EndQuery(q.heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.query_base + e.stage_count); + r.cl->ResolveQueryData(q.heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.query_base, e.stage_count + 1, + q.readback.Get(), e.query_base * sizeof(uint64_t)); + } + + void CollectTimings(Entry& e, const TimingQueries& q) { + if (!e.stage_count || !e.fence) return; + const D3D12_RANGE range = {e.query_base * sizeof(uint64_t), + (e.query_base + e.stage_count + 1) * sizeof(uint64_t)}; + void* p = nullptr; + if (SUCCEEDED(q.readback->Map(0, &range, &p))) { + const auto* ts = static_cast(p) + e.query_base; + for (uint32_t i = 0; i < e.stage_count; ++i) + timings.ms[static_cast(e.stages[i])] += (ts[i + 1] - ts[i]) * 1000.0 / q.hz; + const D3D12_RANGE none = {0, 0}; + q.readback->Unmap(0, &none); + } else { + timing_failed = true; + } + e.stage_count = 0; + } + + bool WaitFence(ID3D12Fence* f, uint64_t v, uint32_t ms) { + const ULONGLONG until = GetTickCount64() + ms; + if (!v || f->GetCompletedValue() >= v) return true; + if (!ms || !event || FAILED(f->SetEventOnCompletion(v, event))) return false; + // An earlier timed-out registration can still signal this event. + while (f->GetCompletedValue() < v) { + const ULONGLONG now = GetTickCount64(); + if (now >= until || WaitForSingleObject(event, static_cast(until - now)) != WAIT_OBJECT_0) + return f->GetCompletedValue() >= v; + } + return true; + } + + bool WaitValue(uint64_t v, uint32_t ms) { return WaitFence(fence.Get(), v, ms); } + + bool WaitIdle(uint32_t ms) { + const ULONGLONG until = GetTickCount64() + ms; + if (!WaitValue(next_value, ms)) return false; + const ULONGLONG now = GetTickCount64(); + return WaitFence(handoff_fence.Get(), handoff_value, now < until ? static_cast(until - now) : 0); } FgExecResult Upload() { @@ -959,30 +1102,39 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } // ---- recording ------------------------------------------------------------------------------------------- - FgExecResult Begin(Rec* r) { + FgExecResult Begin(Rec* r, bool on_game_queue = false, bool uses_arena = true) { + r->direct = compute_queue && on_game_queue; + r->uses_arena = uses_arena; + auto& ring = r->direct ? direct_entries : entries; + ID3D12Fence* reuse_fence = r->direct ? handoff_fence.Get() : fence.Get(); Entry* e = nullptr; - const uint64_t done = fence->GetCompletedValue(); - for (Entry& x : entries) + const uint64_t done = reuse_fence->GetCompletedValue(); + for (Entry& x : ring) if (x.fence <= done) { e = &x; break; } if (!e) { - Entry* oldest = &entries[0]; - for (Entry& x : entries) + Entry* oldest = &ring[0]; + for (Entry& x : ring) if (x.fence < oldest->fence) oldest = &x; - if (!WaitValue(oldest->fence, desc.wait_ms)) { + if (!WaitFence(reuse_fence, oldest->fence, desc.wait_ms)) { if (DeviceRemoved()) return Fail(FgExecRefusal::DeviceLost, "device removed"); return Fail(FgExecRefusal::WaitTimeout, "no free command allocator"); } e = oldest; } + CollectTimings(*e, r->direct ? direct_queries : producer_queries); + e->fence = 0; + e->stage_count = 0; if (FAILED(e->alloc->Reset()) || FAILED(e->list->Reset(e->alloc.Get(), nullptr))) return Fail(FgExecRefusal::CommandFailed, "command list reset"); r->e = e; r->cl = e->list.Get(); - r->pair = 0; + r->open = true; + r->table = 0; r->dirty = false; + if (!uses_arena) return FgExecResult::Ok; ID3D12DescriptorHeap* heaps[] = {heap.Get()}; r->cl->SetDescriptorHeaps(1, heaps); r->cl->SetComputeRootSignature(root.Get()); @@ -995,9 +1147,9 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return FgExecResult::Ok; } - void SetTable(Rec& r, uint32_t pair) { + void SetTable(Rec& r, uint32_t table) { D3D12_GPU_DESCRIPTOR_HANDLE h = heap->GetGPUDescriptorHandleForHeapStart(); - h.ptr += static_cast(r.e->desc_base + 2 * pair) * desc_inc; + h.ptr += static_cast(r.e->desc_base + kTableSize * table) * desc_inc; r.cl->SetComputeRootDescriptorTable(3, h); } @@ -1034,9 +1186,9 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { r.dirty = false; } - void Dispatch(Rec& r, uint32_t k, uint32_t groups, const uint32_t* args, uint32_t n) { + void Dispatch(Rec& r, uint32_t k, uint32_t groups, const uint32_t* args, uint32_t n, bool barrier = true) { ArenaTo(r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - Barrier(r); + if (barrier) Barrier(r); r.cl->SetPipelineState(pso[k].Get()); uint32_t c[kRootConstants] = {}; c[1] = groups; @@ -1049,23 +1201,37 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { r.dirty = true; ++counters.dispatches; } - void D(Rec& r, uint32_t k, uint32_t groups, std::initializer_list a) { + void D(Rec& r, uint32_t k, uint32_t groups, std::initializer_list a, bool barrier = true) { uint32_t v[kMaxArgs] = {}; uint32_t n = 0; for (uint32_t x : a) if (n < kMaxArgs) v[n++] = x; - Dispatch(r, k, groups, v, n); + Dispatch(r, k, groups, v, n, barrier); } FgExecResult Submit(Rec* r, uint64_t* value) { cur = nullptr; + // Buffers decay at submission boundaries. Make the Direct-to-Compute release explicit. + if (r->direct && r->uses_arena) ArenaTo(*r, D3D12_RESOURCE_STATE_COMMON); + ResolveTimings(*r); + r->open = false; if (FAILED(r->cl->Close())) return Fail(FgExecRefusal::CommandFailed, "command list close"); + ID3D12CommandQueue* q = r->direct ? queue.Get() : ProducerQueue(); + if (r->direct) { + uint64_t dependency = r->uses_arena ? arena_value : 0; + const auto slot = compute_slot_values.find(r->written_slot); + if (slot != compute_slot_values.end()) dependency = std::max(dependency, slot->second); + if (dependency > fence->GetCompletedValue() && FAILED(q->Wait(fence.Get(), dependency))) + return QueueFailure("wait for compute writes"); + } + if (!r->direct && !JoinGameQueue()) return QueueFailure("wait for game queue handoff"); ID3D12CommandList* l[] = {r->cl}; - queue->ExecuteCommandLists(1, l); - const uint64_t v = ++next_value; - if (FAILED(queue->Signal(fence.Get(), v))) { - if (DeviceRemoved()) return Fail(FgExecRefusal::DeviceLost, "device removed"); - return Fail(FgExecRefusal::CommandFailed, "queue signal"); + q->ExecuteCommandLists(1, l); + uint64_t v = 0; + if (!(r->direct ? SignalHandoff(&v) : SignalProducer(&v))) return QueueFailure("queue signal"); + if (compute_queue && !r->direct) { + if (r->uses_arena) arena_value = v; + if (r->written_slot) compute_slot_values[r->written_slot] = v; } r->e->fence = v; ++counters.submissions; @@ -1074,6 +1240,31 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return FgExecResult::Ok; } + FgExecResult QueueFailure(const char* operation) { + if (DeviceRemoved()) return Fail(FgExecRefusal::DeviceLost, "device removed"); + return Fail(FgExecRefusal::CommandFailed, operation); + } + + bool SignalHandoff(uint64_t* value) { + if (FAILED(queue->Signal(handoff_fence.Get(), handoff_value + 1))) return false; + *value = ++handoff_value; + return true; + } + + bool JoinGameQueue() { + if (!compute_queue || joined_handoff == handoff_value) return true; + if (FAILED(compute_queue->Wait(handoff_fence.Get(), handoff_value))) return false; + joined_handoff = handoff_value; + return true; + } + + bool SignalProducer(uint64_t* value) { + // Only the producer queue publishes values, so a direct copy cannot overtake earlier compute work. + if (FAILED(ProducerQueue()->Signal(fence.Get(), next_value + 1))) return false; + *value = ++next_value; + return true; + } + // IFgComputeRecorder (net1) void BindArena() override {} void UavBarrier() override { @@ -1082,26 +1273,86 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { Barrier(*cur); } } - void SetPipeline(FgNet1Kernel k) override { - if (cur) cur->cl->SetPipelineState(pso[kMConv1 + static_cast(k)].Get()); - } + FgNet1Kernel n1_record_kernel{}; + std::array n1_record_constants{}; + + void SetPipeline(FgNet1Kernel k) override { n1_record_kernel = k; } void SetConstants(const uint32_t* dwords, uint32_t count) override { - if (cur) cur->cl->SetComputeRoot32BitConstants(2, count, dwords, 0); + std::copy_n(dwords, count, n1_record_constants.begin()); } + + void Net1PairSplit(Rec& r, Kernel first, Kernel second, uint32_t first_tiles, uint32_t second_tiles, + const uint32_t* args) { + const uint32_t pixel_groups = cdiv(static_cast(args[8]) * args[9], 32); + const uint32_t dst = args[6]; + uint32_t a[kFgNet1Args]; + std::copy_n(args, kFgNet1Args, a); + a[6] = n1_pair_scratch; + Dispatch(r, first, pixel_groups * (first_tiles / 2), a, kFgNet1Args, false); + a[0] = n1_pair_scratch; + a[6] = dst; + Dispatch(r, second, pixel_groups * (second_tiles / 2), a, kFgNet1Args); + } + void Dispatch(uint32_t groups_x) override { - if (cur) { - cur->cl->Dispatch(groups_x, 1, 1); - cur->dirty = true; - ++counters.dispatches; + if (!cur) return; + const auto& c = n1_record_constants; + const uint32_t* args = c.data() + 2; + const FgNet1Kernel kernel = n1_record_kernel; + // The validator records the original launch. Retile complete launches when a tuned PSO is available. + if (c[0] == 0 && c[1] == groups_x) { + if (kernel == FgNet1Kernel::MPairB && pso[kMPairBFirst] && pso[kMPairBSecond] && n1_pair_scratch) { + Net1PairSplit(*cur, kMPairBFirst, kMPairBSecond, 32, 16, args); + return; + } + if (kernel == FgNet1Kernel::MPairD4 && pso[kMPairD4First] && pso[kMPairD4Second] && n1_pair_scratch) { + Net1PairSplit(*cur, kMPairD4First, kMPairD4Second, 16, 8, args); + return; + } + if ((kernel == FgNet1Kernel::MPairD3 && pso[kMPairD3Narrow]) || + (kernel == FgNet1Kernel::MPairD2 && pso[kMPairD2Narrow])) { + const Kernel tuned = kernel == FgNet1Kernel::MPairD3 ? kMPairD3Narrow : kMPairD2Narrow; + Dispatch(*cur, tuned, cdiv(static_cast(args[8]) * args[9], 32), args, kFgNet1Args, false); + return; + } + + Kernel tuned = kKernelCount; + uint32_t tiles_per_wave = 0; + uint32_t tile_h = 4; + const bool small_conv = kernel == FgNet1Kernel::MConv4 && args[9] == 3 && groups_x <= 128; + if (small_conv && groups_x <= 48 && pso[kMConv1Late]) { + tuned = kMConv1Late; + tiles_per_wave = 1; + } else if (kernel == FgNet1Kernel::MConv2 && args[9] == 3 && args[10] == 1 && pso[kMConv2Mid]) { + tuned = kMConv2Mid; + tiles_per_wave = 2; + tile_h = 8; + } else if ((kernel == FgNet1Kernel::MConv2 || small_conv) && pso[kMConv2Narrow]) { + tuned = kMConv2Narrow; + tiles_per_wave = 2; + } + if (tuned != kKernelCount) { + uint32_t a[kFgNet1Args]; + std::copy_n(args, kFgNet1Args, a); + a[14] = cdiv(a[7], tile_h); + const uint32_t groups = a[13] * a[14] * (a[6] / (16 * tiles_per_wave)); + Dispatch(*cur, tuned, groups, a, kFgNet1Args, false); + return; + } } + cur->cl->SetPipelineState(pso[kMConv1 + static_cast(kernel)].Get()); + cur->cl->SetComputeRoot32BitConstants(2, static_cast(c.size()), c.data(), 0); + cur->cl->Dispatch(groups_x, 1, 1); + cur->dirty = true; + ++counters.dispatches; } // ---- stages ---------------------------------------------------------------------------------------------- uint32_t R(uint32_t role) const { return role_off[role]; } - void Fill16(Rec& r, uint32_t off, uint64_t bytes, const uint32_t* p, uint32_t period) { + void Fill16(Rec& r, uint32_t off, uint64_t bytes, const uint32_t* p, uint32_t period, bool barrier = true) { const uint32_t n16 = static_cast(bytes / 2); - D(r, kFill16, groups_for(n16, 8), {off, n16, p[0], p[1], p[2], p[3], period}); + D(r, kFill16, groups_for(n16, 8), {off, n16, p[0], p[1], p[2], p[3], period}, barrier); } void RegArgs(const InputTex& t, bool present, uint32_t* out10) const { @@ -1113,7 +1364,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } // One schedule operation. Returns false when a step cannot be recorded (net1 refusal). - bool RecordOp(Rec& r, const FgExecOp& op) { + bool RecordOp(Rec& r, const FgExecOp& op, bool input_srvs = false) { const FrameCtx& f = frame; const uint32_t col = cap_colour, ctw = f.colour.w; const InputTex& cr = f.colour; @@ -1133,14 +1384,14 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { const uint32_t inv = f.inverted ? 1u : 0u; switch (op.op) { case FgOp::Clear: - Fill16(r, R(op.role), FgRoleBytes(g, op.role), op.value, op.period); - return true; case FgOp::Fill64: - Fill16(r, R(op.role), FgRoleBytes(g, op.role), op.value, op.period); + // History clears have distinct destinations, S is independent of downsample and motion prep, + // and the per-index MA and MB clears are independent of each other. + Fill16(r, R(op.role), FgRoleBytes(g, op.role), op.value, op.period, false); return true; case FgOp::SetDisable: { const uint32_t p[4] = {op.base & 0xFFFFu, op.base >> 16, 0, 0}; - Fill16(r, dis_off, 4, p, 2); + Fill16(r, dis_off, 4, p, 2, false); frame.disable = op.base; return true; } @@ -1178,7 +1429,19 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { R(kRoleUm), g.wo, g.ho, g.wd, g.hd, host.Frame().r3_bits}; for (uint32_t x : h3) a[n++] = x; const uint64_t nb = static_cast(cdiv(g.wo, g.d)) * cdiv(g.ho, g.d); - Dispatch(r, g.d == 4 ? kDown4 : kDown2, groups_for(nb), a, n); + // A reset cleared the history/UI roles this dispatch accesses. With history, the preceding + // SetDisable writes a separate word, or the detector already ended its own submission. + if (input_srvs) + BindInputs(r, {&cr, f.hud ? &f.hudless : nullptr, alpha ? &f.alpha : nullptr}); + uint32_t kernel = input_srvs ? (g.d == 4 ? kDown4Srv : kDown2Srv) : (g.d == 4 ? kDown4 : kDown2); + uint32_t groups = groups_for(nb); + const auto& hr = f.hudless.region; + if (kernel == kDown2Srv && pso[kDown2HudTile] && (host.Frame().r3_bits & 16u) && + hw == g.wo && hh == g.ho && !hr.bx && !hr.by && hr.ew == hw && hr.eh == hh) { + kernel = kDown2HudTile; + groups = cdiv(g.wo, 32) * cdiv(g.ho, 8); + } + Dispatch(r, kernel, groups, a, n, !host.Frame().history); return true; } case FgOp::Mvec: { @@ -1197,7 +1460,10 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { for (uint32_t x : mreg) a[n++] = x; const uint32_t t[8] = {R(kRoleZc), R(kRoleMv), g.w1, g.h1, inv, fb(st.s_k), fb(f.scx), fb(f.scy)}; for (uint32_t x : t) a[n++] = x; - Dispatch(r, kMvec, groups_for(nsc), a, n); + // Downsample writes colour/UI roles. Motion prep writes depth and motion roles. + if (input_srvs) BindInputs(r, {&f.depth, &f.motion}); + Dispatch(r, input_srvs ? kMvecSrv : kMvec, groups_for(nsc), a, n, false); + if (input_srvs) SetTable(r, 0); return true; } case FgOp::P2cScatter: { @@ -1227,6 +1493,17 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { D(r, kInpaint, groups_for(nsc), {R(kRoleFl), R(kRoleG), g.w1, g.h1}); return true; case FgOp::P2cPull: + if (pso[kPullTiled]) { + for (uint32_t l : {1u, 5u}) { + if (l > g.top) break; + const uint32_t w = g.lw[l], h = g.lh[l]; + D(r, kPullTiled, cdiv(w, 16) * cdiv(h, 16), + {l == 1 ? 0u : 2u, l == 1 ? R(kRoleG) : R(kRoleP1 + 3), R(kRoleVf), 0u, + R(kRoleP1 + l - 1), g.lw[l - 1], g.lh[l - 1], w, h, fb(4.0f), + R(kRoleP1 + l), R(kRoleP1 + l + 1), R(kRoleP1 + l + 2), std::min(4u, g.top - l + 1)}); + } + return true; + } for (uint32_t l = 1; l <= g.top; ++l) { const uint32_t wl = g.lw[l], hl = g.lh[l], ws = g.lw[l - 1], hs = g.lh[l - 1]; uint32_t mode, sa, sb = 0; @@ -1248,23 +1525,40 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { {mode, sa, sb, ps_off[l], R(kRoleP1 + l - 1), ws, hs, wl, hl, fb(n)}); } return true; - case FgOp::P2cPush: - for (uint32_t l = g.top - 1; l >= 1; --l) { + case FgOp::P2cPush: { + uint32_t l = g.top - 1; + if (pso[kPushTail]) { + uint32_t args[25] = {}; + for (uint32_t j = 0; j <= l && g.lw[g.top - j] * g.lh[g.top - j] <= 256; ++j) { + const uint32_t level = g.top - j; + args[0] = j; + args[1 + j] = R(kRoleP1 + level - 1); + args[9 + j] = g.lw[level]; + args[17 + j] = g.lh[level]; + } + if (args[0] > 1) { + Dispatch(r, kPushTail, 1, args, 25); + l -= args[0]; + } + } + for (; l >= 1; --l) { D(r, kPush, groups_for(static_cast(g.lw[l]) * g.lh[l]), {R(kRoleP1 + l), g.lw[l + 1], g.lh[l + 1], R(kRoleP1 + l - 1), g.lw[l], g.lh[l]}); if (l == 1) break; } D(r, kFine, groups_for(nsc), {R(kRoleP1), g.lw[1], g.lh[1], R(kRoleG), R(kRoleF), g.w1, g.h1}); return true; + } case FgOp::HoleMask: { const uint32_t p[4] = {0x3C00u, 0, 0, 0}; - Fill16(r, R(kRoleHc), FgRoleBytes(g, kRoleHc), p, 1); + Fill16(r, R(kRoleHc), FgRoleBytes(g, kRoleHc), p, 1, false); D(r, kHoleMask, groups_for(static_cast(g.wd) * g.hd), {R(kRoleF), g.w1, g.h1, R(kRoleHc), g.wd, g.hd}); return true; } case FgOp::QualityInit: - D(r, kQualityInit, groups_for(static_cast(g.wd) * g.hd), {R(kRoleDc), R(kRoleQc), g.wd * g.hd}); + D(r, kQualityInit, groups_for(static_cast(g.wd) * g.hd), + {R(kRoleDc), R(kRoleQc), g.wd * g.hd}, false); return true; case FgOp::Net1Input: D(r, kNet1Input, groups_for(4ull * g.W0 * g.H0), @@ -1292,12 +1586,16 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { {n1_out, R(kRoleOm), R(kRoleUm), R(kRoleUmp), R(kRoleNA), R(kRoleNB), R(kRoleM), g.wd, g.hd, g.pad_l, g.pad_t, g.W0, g.H0, 1u, 16u, op.ui_forcing ? 1u : 0u}); return true; - case FgOp::Interm: - D(r, kInterm, groups_for(nsc), + case FgOp::Interm: { + const uint32_t kernel = pso[kIntermTiled] ? kIntermTiled : kInterm; + const uint32_t groups = kernel == kIntermTiled ? cdiv(g.w1, 16) * cdiv(g.h1, 16) : groups_for(nsc); + D(r, kernel, groups, {0u, R(kRoleMv), R(kRoleZc), R(kRoleMA), g.w1, g.h1, fb(op.t), fb(st.s_k), inv, fb(t2), fb(st.tau)}); - D(r, kInterm, groups_for(nsc), - {1u, R(kRoleF), R(kRoleZp), R(kRoleMB), g.w1, g.h1, fb(op.t), fb(st.s_k), inv, fb(t2), fb(st.tau)}); + D(r, kernel, groups, + {1u, R(kRoleF), R(kRoleZp), R(kRoleMB), g.w1, g.h1, fb(op.t), fb(st.s_k), inv, fb(t2), fb(st.tau)}, + false); return true; + } case FgOp::Weights: D(r, kWeights, groups_for(nsc), {R(kRoleMA), R(kRoleMB), R(kRoleNA), R(kRoleNB), R(kRoleW), g.w1, g.h1, g.wd, g.hd}); @@ -1360,12 +1658,12 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { void Conv(Rec& r, uint32_t layer, const Net2Buf& x, const Net2Buf& y, uint32_t in_cs, uint32_t in_co, uint32_t cin, uint32_t co_lo, uint32_t co_n, uint32_t out_cs, uint32_t out_co, uint32_t H, uint32_t W, uint32_t pool, uint32_t leaky, uint32_t clamp_from, uint32_t res, uint32_t res_mul, uint32_t skip, - uint32_t skip_cs) { + uint32_t skip_cs, bool barrier = true) { const FgNet2Layer& l = FgNet2Layers()[layer - 1]; const uint64_t threads = static_cast(pool ? H / 2 : H) * (pool ? W / 2 : W) * co_n; D(r, kNet2Conv, groups_for(threads), {x.off, n2w[layer - 1], n2b[layer - 1], y.off, skip, in_cs, in_co, cin, l.cin, co_lo, co_n, out_cs, out_co, - H, W, pool, leaky, clamp_from, res, res_mul, skip_cs, 0u}); + H, W, pool, leaky, clamp_from, res, res_mul, skip_cs, 0u}, barrier); } // conv(n, src, dst, cin, ...) of the reference chain: the layer's full output, input channels from 0 void ConvL(Rec& r, uint32_t layer, const Net2Buf& src, const Net2Buf& dst, uint32_t cin, uint32_t pool, @@ -1374,13 +1672,21 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { Conv(r, layer, src, dst, src.c, 0, cin, 0, l.cout, l.cout, 0, src.h, src.w, pool, 1, clamp_from, res, kHalfOne, skip ? skip->off : 0u, skip ? cin : 0u); } - void Up2(Rec& r, const Net2Buf& x, const Net2Buf& y) { - D(r, kNet2Up2, groups_for(4ull * x.h * x.w * x.c), {x.off, y.off, x.c, x.h, x.w}); + void Up2(Rec& r, const Net2Buf& x, const Net2Buf& y, bool barrier = true) { + D(r, kNet2Up2, groups_for(4ull * x.h * x.w * x.c), {x.off, y.off, x.c, x.h, x.w}, barrier); + } + + void MergeNet2Inputs(Rec& r, uint32_t npx, float f) { + if (pso[kNet2MergePixels]) { + D(r, kNet2MergePixels, groups_for(npx), {ib, ic, ia, nb_x.off, npx, fb(f)}); + } else { + D(r, kNet2Merge, groups_for(10ull * npx), {ib, ic, ia, nb_x.off, npx, fb(f)}); + } } void RecordNet2(Rec& r, float f) { const uint32_t npx = g.W2 * g.H2; - D(r, kNet2Merge, groups_for(10ull * npx), {ib, ic, ia, nb_x.off, npx, fb(f)}); + MergeNet2Inputs(r, npx, f); ConvL(r, 1, nb_x, nb_a1, 10, 1, 0, 0, nullptr); ConvL(r, 2, nb_a1, nb_a2, 32, 1, 0, 0, nullptr); ConvL(r, 3, nb_a2, nb_r0, 32, 1, 0, 0, nullptr); @@ -1397,10 +1703,10 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { const uint32_t lo[3] = {0, 4, 5}, cnt[3] = {4, 1, 3}, cf[3] = {kNoClamp, 0, 0}; for (uint32_t j = 0; j < 3; ++j) Conv(r, 13, nb_gu, *heads[j], 96, 32 * j, 32, lo[j], cnt[j], cnt[j], 0, nb_gu.h, nb_gu.w, 0, 0, cf[j], 0, - kHalfOne, 0, 0); + kHalfOne, 0, 0, j == 0); Up2(r, nb_hA4, nb_U4); - Up2(r, nb_hA1, nb_U1); - Up2(r, nb_hA3, nb_U3); + Up2(r, nb_hA1, nb_U1, false); + Up2(r, nb_hA3, nb_U3, false); D(r, kNet2Warp, groups_for(18ull * npx), {ib, ic, ia, nb_U4.off, nb_U1.off, nb_U3.off, nb_y.off, g.W2, g.H2, fb(f)}); ConvL(r, 14, nb_y, nb_b1, 18, 1, 0, 0, nullptr); ConvL(r, 15, nb_b1, nb_s0, 16, 1, 0, 0, nullptr); @@ -1417,7 +1723,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { const uint32_t rm[3] = {kHalfTwo, kHalfOne, kHalfOne}; for (uint32_t j = 0; j < 3; ++j) Conv(r, 25, nb_eu, nb_out, 48, 16 * j, 16, lo[j], cnt[j], 8, lo[j], g.H2, g.W2, 0, 0, cf[j], 2, rm[j], - us[j]->off, cnt[j]); + us[j]->off, cnt[j], j == 0); ++counters.net2_exact; } @@ -1442,7 +1748,19 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { uint32_t groups = 0, rows = 0; // Configure checked every layer's variant (FgNet2FastPlan) if (!ChooseMconv(l.cout, l.cin, o.up, static_cast(H) * W, &v, &groups, &rows)) return; - if (o.heads) groups = 3; + if (n == 12 && static_cast(H) * W <= 8192) { + // Two output tiles per wave give the smaller L12 grids more workgroups. + v.kernel = kN2m2b4u; + groups = l.cout / (2 * kMTile); + } + if (o.heads) { + if (n == 25 && pso[kN2h3b1u]) { + v.kernel = kN2h3b1u; + groups = 1; + } else { + groups = 3; + } + } const uint32_t co_n = o.co_n ? o.co_n : l.cout; const uint32_t out_cs = o.out_cs < 0 ? co_n : static_cast(o.out_cs); const uint32_t tx = cdiv(W, kMTile), ty = cdiv(H, rows); @@ -1460,7 +1778,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { void RecordNet2Fast(Rec& r, float f, bool half_last) { const uint32_t npx = g.W2 * g.H2; - D(r, kNet2Merge, groups_for(10ull * npx), {ib, ic, ia, nb_x.off, npx, fb(f)}); + MergeNet2Inputs(r, npx, f); MOpt pool; pool.pool = 1; MConv(r, 1, nb_x, nb_a1, 10, g.H2, g.W2, pool); @@ -1548,16 +1866,24 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { FgExecOutLevelSize(g, l, &wf, &hf); FgExecOutLevelSize(g, l + 1, &wc, &hc); D(r, kOutPush, groups_for(static_cast(wf) * hf), - {lv[l], l == lc - 1 ? lv[lc] : fd[l + 1], fd[l], wf, hf, wc, hc}); + {lv[l], lv[l + 1], lv[l], wf, hf, wc, hc}); if (l == 1) break; } uint32_t w1o, h1o; FgExecOutLevelSize(g, 1, &w1o, &h1o); D(r, kOutPushFine, groups_for(static_cast(g.wo) * g.ho), - {fine, fd[1], out_off, g.wo, g.ho, w1o, h1o, out_stride, 0u, 0u}); + {fine, lv[1], out_off, g.wo, g.ho, w1o, h1o, out_stride, 0u, 0u}); } // ---- inputs ---------------------------------------------------------------------------------------------- + bool CanTransitionInput(D3D12_RESOURCE_STATES state) const { + constexpr uint32_t compute_states = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_COPY_SOURCE | D3D12_RESOURCE_STATE_COPY_DEST | + D3D12_RESOURCE_STATE_UNORDERED_ACCESS | D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | + D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; + return list_type == D3D12_COMMAND_LIST_TYPE_DIRECT || !(state & ~compute_states); + } + FgExecRefusal TakeInput(const FgTextureRef& t, InputTex* out, std::string* w, const char* name) { if (!t.resource) { *w = std::string(name) + " missing"; @@ -1581,6 +1907,10 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { x.w = static_cast(d.Width); x.h = d.Height; x.state = static_cast(t.state); + if (NeedsTransition(x.state) && !CanTransitionInput(x.state)) { + *w = std::string(name) + ": state transition requires a direct queue"; + return FgExecRefusal::InputFormat; + } if (x.w > cap_w || x.h > cap_h) { *w = std::string(name) + ": texture larger than the capture area"; return FgExecRefusal::InputExtent; @@ -1595,18 +1925,25 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return FgExecRefusal::None; } - void Capture(Rec& r, const InputTex& t, uint32_t dst, uint32_t kind) { - const uint32_t pair = r.pair + 1 < kPairs ? ++r.pair : r.pair; + void BindInputs(Rec& r, std::initializer_list inputs) { + const uint32_t table = ++r.table; D3D12_CPU_DESCRIPTOR_HANDLE h = heap->GetCPUDescriptorHandleForHeapStart(); - h.ptr += static_cast(r.e->desc_base + 2 * pair + 1) * desc_inc; + h.ptr += static_cast(r.e->desc_base + kTableSize * table + 1) * desc_inc; D3D12_SHADER_RESOURCE_VIEW_DESC sv = {}; - sv.Format = t.view; sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; sv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; sv.Texture2D.MipLevels = 1; - device->CreateShaderResourceView(t.res, &sv, h); - SetTable(r, pair); - D(r, kCapture, groups_for(static_cast(t.w) * t.h), {dst, t.w, t.h, kind}); + for (const InputTex* t : inputs) { + sv.Format = t ? t->view : DXGI_FORMAT_R16G16B16A16_FLOAT; + device->CreateShaderResourceView(t ? t->res : nullptr, &sv, h); + h.ptr += desc_inc; + } + SetTable(r, table); + } + + void Capture(Rec& r, const InputTex& t, uint32_t dst, uint32_t kind) { + BindInputs(r, {&t}); + D(r, kCapture, groups_for(static_cast(t.w) * t.h), {dst, t.w, t.h, kind}, false); ++counters.captures; } @@ -1614,7 +1951,54 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return s != D3D12_RESOURCE_STATE_COMMON && !(s & D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); } + void CaptureColour(Rec& r) { + const InputTex& src = frame.colour; + const bool transition = NeedsTransition(src.state); + if (transition) Transition(r, src.res, src.state, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + Capture(r, src, cap_colour, 4); + if (transition) Transition(r, src.res, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, src.state); + SetTable(r, 0); + } + // ---- slot output ----------------------------------------------------------------------------------------- + ID3D12Resource* DirectCopySlot(uint32_t slot) const { + const InputTex& src = frame.colour; + if (desc.keep_outputs || !target || !src.res || !CanTransitionInput(src.state) || + src.w != g.wo || src.h != g.ho || src.region.bx || src.region.by || + src.region.ew != g.wo || src.region.eh != g.ho) + return nullptr; + ID3D12Resource* dst = target->SlotResource(slot); + if (!dst || dst == src.res) return nullptr; + const auto in = src.res->GetDesc(); + const auto out = dst->GetDesc(); + if (out.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || out.Width != in.Width || out.Height != in.Height || + out.DepthOrArraySize != 1 || out.MipLevels != 1 || in.MipLevels != 1 || + out.SampleDesc.Count != 1 || out.SampleDesc.Quality != in.SampleDesc.Quality) + return nullptr; + // Capture linearizes an sRGB SRV, and its float16 conversion quiets signaling NaNs. Only the linear + // UNORM formats round-trip every input code through capture and pack. + const DXGI_FORMAT format = linear_copy_format(out.Format); + if (src.view != format || + (format != DXGI_FORMAT_R8G8B8A8_UNORM && format != DXGI_FORMAT_B8G8R8A8_UNORM && + format != DXGI_FORMAT_R10G10B10A2_UNORM)) + return nullptr; + return dst; + } + + void CopySlot(Rec& r, ID3D12Resource* dst, char kind, uint64_t token, uint32_t index) { + const InputTex& src = frame.colour; + const auto out = dst->GetDesc(); + Transition(r, src.res, src.state, D3D12_RESOURCE_STATE_COPY_SOURCE); + Transition(r, dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + r.cl->CopyResource(dst, src.res); + r.written_slot = dst; + Transition(r, src.res, D3D12_RESOURCE_STATE_COPY_SOURCE, src.state); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp = {}; + fp.Footprint = {linear_copy_format(out.Format), g.wo, g.ho, 1, 0}; + RecordDump(r, dst, fp, 4, kind, token, index); + Transition(r, dst, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + } + FgExecResult WriteSlot(Rec& r, uint32_t slot, char kind, uint64_t token, uint32_t index) { if (!target) return Fail(FgExecRefusal::SlotTargetMissing, "no presenter bound to the executor"); ID3D12Resource* res = target->SlotResource(slot); @@ -1629,7 +2013,9 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { uint64_t src_off = out_off; uint32_t pitch = out_stride * 8; if (code_ != 0) { - D(r, kPack, groups_for(static_cast(g.wo) * g.ho), + const bool pairs = pso[kPackPairs] != nullptr; + const uint32_t columns = pairs ? cdiv(g.wo, 2) : g.wo; + D(r, pairs ? kPackPairs : kPack, groups_for(static_cast(columns) * g.ho), {out_off, out_stride, pack_off, pack_pitch, g.wo, g.ho, static_cast(code_)}); src_off = pack_off; pitch = pack_pitch; @@ -1650,6 +2036,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { src.PlacedFootprint.Footprint.Depth = 1; src.PlacedFootprint.Footprint.RowPitch = pitch; r.cl->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + r.written_slot = res; if (desc.keep_outputs) { PendingRb p; p.rec.kind = kind; @@ -1692,14 +2079,15 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { FgExecResult Finish(Rec& r, FgReadyFence* ready) { uint64_t v = 0; const FgExecResult s = Submit(&r, &v); - if (s != FgExecResult::Ok) { - // the recording was not submitted: its dump copies never run + if (!v) { dumps.erase(std::remove_if(dumps.begin(), dumps.end(), [](const DumpRb& d) { return d.fence_value == 0; }), dumps.end()); - return s; } for (DumpRb& d : dumps) if (d.fence_value == 0) d.fence_value = v; + if (s != FgExecResult::Ok) return s; + if (r.direct && (!JoinGameQueue() || !SignalProducer(&v))) + return QueueFailure("publish the game queue handoff"); if (desc.keep_outputs) for (PendingRb& p : pending) if (p.rec.fence_value == 0) p.rec.fence_value = v; @@ -1709,12 +2097,49 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } return FgExecResult::Ok; } + + FgExecResult CopyFrameToSlot(uint32_t slot, char kind, uint64_t token, uint32_t index, FgReadyFence* ready) { + ID3D12Resource* dst = DirectCopySlot(slot); + const bool capture = !dst && !frame.colour_captured; + Rec first; + Rec after_capture; + Rec* r = &first; + FgExecResult s = Begin(r, dst || capture, !dst); + if (s != FgExecResult::Ok) return s; + if (kind == 'r') TimeStage(*r, FgExecStage::RealEndpoint); + if (dst) { + CopySlot(*r, dst, kind, token, index); + } else { + if (capture) { + CaptureColour(*r); + if (compute_queue) { + uint64_t v = 0; + s = Submit(r, &v); + if (s != FgExecResult::Ok) return s; + r = &after_capture; + s = Begin(r); + if (s != FgExecResult::Ok) return s; + if (kind == 'r') TimeStage(*r, FgExecStage::RealEndpoint); + } + } + FgExecOp op; + op.op = FgOp::FinalCopy; + RecordOp(*r, op); + s = WriteSlot(*r, slot, kind, token, index); + if (s != FgExecResult::Ok) return s; + } + s = Finish(*r, ready); + if (s == FgExecResult::Ok && capture) frame.colour_captured = true; + return s; + } }; // ---- public ------------------------------------------------------------------------------------------------------ FgD3d12Executor::FgD3d12Executor(const FgD3d12ExecutorDesc& desc) : impl_(new Impl()) { impl_->desc = desc; + char timing[2] = {}; + impl_->desc.timing |= GetEnvironmentVariableA("WRONGGPU_FG_TIMING", timing, sizeof(timing)) == 1 && timing[0] == '1'; if (desc.weights) { impl_->weights = *desc.weights; impl_->have_weights = true; @@ -1724,7 +2149,7 @@ FgD3d12Executor::FgD3d12Executor(const FgD3d12ExecutorDesc& desc) : impl_(new Im FgD3d12Executor::~FgD3d12Executor() { if (impl_ && impl_->fence) { - impl_->WaitValue(impl_->next_value, impl_->desc.wait_ms); + impl_->WaitIdle(impl_->desc.wait_ms); impl_->FlushDumps(true); } } @@ -1772,12 +2197,37 @@ FgExecResult FgD3d12Executor::Configure(const FgCreateDesc& cd, uint32_t /*histo ID3D12Device* dev = static_cast(cd.device); ID3D12CommandQueue* q = static_cast(cd.queue); if (m.device && m.device.Get() != dev) return m.Fail(FgExecRefusal::BadArgument, "another device than before"); + const D3D12_COMMAND_QUEUE_DESC queue_desc = q->GetDesc(); + if (queue_desc.Type != D3D12_COMMAND_LIST_TYPE_DIRECT && queue_desc.Type != D3D12_COMMAND_LIST_TYPE_COMPUTE) + return m.Fail(FgExecRefusal::NullQueue, "the queue is neither a direct nor a compute queue"); + if (!m.WaitIdle(m.desc.wait_ms)) return m.Fail(FgExecRefusal::WaitTimeout, "reconfigure while work is in flight"); + m.FlushDumps(false); m.device = dev; m.queue = q; - m.list_type = q->GetDesc().Type; - if (m.list_type != D3D12_COMMAND_LIST_TYPE_DIRECT && m.list_type != D3D12_COMMAND_LIST_TYPE_COMPUTE) - return m.Fail(FgExecRefusal::NullQueue, "the queue is neither a direct nor a compute queue"); - if (m.fence) m.WaitValue(m.next_value, m.desc.wait_ms); + m.list_type = queue_desc.Type; + m.entries.clear(); + m.direct_entries.clear(); + m.heap.Reset(); + m.producer_queries = {}; + m.direct_queries = {}; + m.timings = {}; + m.timing_failed = false; + m.compute_queue.Reset(); + m.handoff_fence.Reset(); + m.handoff_value = m.joined_handoff = m.arena_value = 0; + m.compute_slot_values.clear(); + char async_compute[2] = {}; + const bool async_off = GetEnvironmentVariableA("WRONGGPU_FG_ASYNC_COMPUTE", async_compute, sizeof(async_compute)) == + 1 && async_compute[0] == '0'; + if (m.list_type == D3D12_COMMAND_LIST_TYPE_DIRECT && !async_off) { + D3D12_COMMAND_QUEUE_DESC compute_desc = {}; + compute_desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + compute_desc.NodeMask = queue_desc.NodeMask; + if (FAILED(dev->CreateCommandQueue(&compute_desc, IID_PPV_ARGS(&m.compute_queue)))) + return m.Fail(FgExecRefusal::AllocationFailed, "compute queue"); + if (FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m.handoff_fence)))) + return m.Fail(FgExecRefusal::FenceFailed, "game queue handoff fence"); + } if (!m.pipelines_built) { const FgExecResult p = m.BuildPipelines(); if (p != FgExecResult::Ok) return p; @@ -1888,7 +2338,21 @@ FgExecResult FgD3d12Executor::RecordSharedGameFrame(const FgSharedDispatchDesc& } std::memcpy(f.clip_to_prev, p.camera_current, sizeof(f.clip_to_prev)); std::memcpy(f.prev_to_clip, p.camera_previous, sizeof(f.prev_to_clip)); - f.valid = true; + + const InputTex* ins[5] = {&f.colour, &f.depth, &f.motion, f.hud ? &f.hudless : nullptr, + (f.ui1 || f.ui4) ? &f.alpha : nullptr}; + bool transition[5] = {}; + for (int i = 0; i < 5; ++i) { + if (!ins[i]) continue; + transition[i] = Impl::NeedsTransition(ins[i]->state); + for (int j = 0; j < i; ++j) { + if (!ins[j] || ins[i]->res != ins[j]->res) continue; + if (ins[i]->state != ins[j]->state) + return m.Fail(FgExecRefusal::BadArgument, "aliased inputs report different resource states"); + transition[i] = false; + break; + } + } // the previous game frame's last-index part, then this frame's schedule std::vector pairs; @@ -1903,53 +2367,71 @@ FgExecResult FgD3d12Executor::RecordSharedGameFrame(const FgSharedDispatchDesc& else ++m.counters.full_frames; - // submission 1: capture, clears and the menu decision - Rec r; - FgExecResult s = m.Begin(&r); + // Menu detection and the corresponding generated MenuOutput both consume the captured inputs. + const bool input_srvs = !m.host.Frame().detect_ran && !m.desc.keep_outputs && + m.pso[m.g.d == 4 ? kDown4Srv : kDown2Srv] && m.pso[kMvecSrv]; + Rec inputs; + FgExecResult s = m.Begin(&inputs, true); if (s != FgExecResult::Ok) return s; - InputTex* ins[5] = {&m.frame.colour, &m.frame.depth, &m.frame.motion, f.hud ? &m.frame.hudless : nullptr, - (f.ui1 || f.ui4) ? &m.frame.alpha : nullptr}; - const uint32_t dst[5] = {m.cap_colour, m.cap_depth, m.cap_motion, m.cap_hud, f.ui1 ? m.cap_ui1 : m.cap_ui4}; - const uint32_t kind[5] = {4, 6, 5, 4, f.ui1 ? 1u : 4u}; - for (InputTex* t : ins) - if (t && Impl::NeedsTransition(t->state)) - m.Transition(r, t->res, t->state, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - for (int i = 0; i < 5; ++i) - if (ins[i]) m.Capture(r, *ins[i], dst[i], kind[i]); - for (InputTex* t : ins) - if (t && Impl::NeedsTransition(t->state)) - m.Transition(r, t->res, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, t->state); - size_t i = 0; - bool detected = false; - for (; i < ops.size(); ++i) { - if (!m.RecordOp(r, ops[i])) return FgExecResult::Refused; - if (ops[i].op == FgOp::Detect || ops[i].op == FgOp::SetDisable) { - detected = ops[i].op == FgOp::Detect; - ++i; - break; + m.TimeStage(inputs, input_srvs ? FgExecStage::SharedPreNet1 : FgExecStage::Capture); + size_t next_op = 0; + if (input_srvs) { + // History clears must precede downsample. Keep the input transitions around the two SRV users. + while (ops[next_op].op != FgOp::Downsample) { + if (!m.RecordOp(inputs, ops[next_op++])) return FgExecResult::Refused; } } - if (detected) { - m.ArenaTo(r, D3D12_RESOURCE_STATE_COPY_SOURCE); - r.cl->CopyBufferRegion(m.menu_rb.Get(), 0, m.arena.Get(), m.detres_off, 32); + for (int i = 0; i < 5; ++i) + if (transition[i]) + m.Transition(inputs, ins[i]->res, ins[i]->state, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + if (input_srvs) { + if (!m.RecordOp(inputs, ops[next_op++], true) || !m.RecordOp(inputs, ops[next_op++], true)) + return FgExecResult::Refused; + } else { + const uint32_t dst[5] = {m.cap_colour, m.cap_depth, m.cap_motion, m.cap_hud, f.ui1 ? m.cap_ui1 : m.cap_ui4}; + const uint32_t kind[5] = {4, 6, 5, 4, f.ui1 ? 1u : 4u}; + for (int i = 0; i < 5; ++i) + if (ins[i]) m.Capture(inputs, *ins[i], dst[i], kind[i]); + m.SetTable(inputs, 0); } - uint64_t v1 = 0; - s = m.Submit(&r, &v1); - if (s != FgExecResult::Ok) return s; - // submission 2: the rest of the once-per-game-frame stages - Rec r2; - s = m.Begin(&r2); - if (s != FgExecResult::Ok) return s; - for (; i < ops.size(); ++i) - if (!m.RecordOp(r2, ops[i])) return FgExecResult::Refused; - uint64_t v2 = 0; - s = m.Submit(&r2, &v2); + for (int i = 0; i < 5; ++i) + if (transition[i]) + m.Transition(inputs, ins[i]->res, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, ins[i]->state); + Rec compute; + Rec post_detect; + Rec* r = &inputs; + uint64_t v = 0, menu_value = 0; + if (m.compute_queue) { + s = m.Submit(&inputs, &v); + if (s != FgExecResult::Ok) return s; + r = &compute; + s = m.Begin(r); + if (s != FgExecResult::Ok) return s; + } else if (!input_srvs) { + m.Barrier(inputs); + } + for (; next_op < ops.size(); ++next_op) { + const FgExecOp& op = ops[next_op]; + m.TimeStage(*r, op.op == FgOp::Net1 ? FgExecStage::Net1 : + op.op == FgOp::Net1Output ? FgExecStage::SharedPostNet1 : FgExecStage::SharedPreNet1); + if (!m.RecordOp(*r, op)) return FgExecResult::Refused; + if (op.op == FgOp::Detect) { + m.ArenaTo(*r, D3D12_RESOURCE_STATE_COPY_SOURCE); + r->cl->CopyBufferRegion(m.menu_rb.Get(), 0, m.arena.Get(), m.detres_off, 32); + s = m.Submit(r, &menu_value); + if (s != FgExecResult::Ok) return s; + r = &post_detect; + s = m.Begin(r); + if (s != FgExecResult::Ok) return s; + } + } + s = m.Submit(r, &v); if (s != FgExecResult::Ok) return s; out->menu.frame_token = d.frame_token; out->menu.detected = false; - if (detected) { + if (menu_value) { ++m.counters.menu_waits; - if (!m.WaitValue(v1, m.desc.wait_ms)) { + if (!m.WaitValue(menu_value, m.desc.wait_ms)) { if (m.DeviceRemoved()) return m.Fail(FgExecRefusal::DeviceLost, "device removed"); return m.Fail(FgExecRefusal::WaitTimeout, "menu decision"); } @@ -1964,6 +2446,8 @@ FgExecResult FgD3d12Executor::RecordSharedGameFrame(const FgSharedDispatchDesc& m.frame.disable = words[4]; } ++m.counters.shared; + m.frame.valid = true; + m.frame.colour_captured = !input_srvs; return FgExecResult::Ok; } @@ -1979,15 +2463,42 @@ FgExecResult FgD3d12Executor::RecordGeneratedIndex(const FgIndexDispatchDesc& d, m.ArmDumpOnGenerated(d.frame_token); std::vector ops; m.host.IndexOps(d.t, m.frame.hud, m.frame.ui4, false, &ops); + const bool capture = !m.frame.colour_captured && std::any_of(ops.begin(), ops.end(), [](const FgExecOp& op) { + return op.op == FgOp::FinalCopy || op.op == FgOp::Prefill; + }); + if (capture && m.compute_queue) { + Rec inputs; + FgExecResult s = m.Begin(&inputs, true); + if (s != FgExecResult::Ok) return s; + m.TimeStage(inputs, FgExecStage::GenPreNet2); + m.CaptureColour(inputs); + uint64_t value = 0; + s = m.Submit(&inputs, &value); + if (s != FgExecResult::Ok) return s; + m.frame.colour_captured = true; + } Rec r; FgExecResult s = m.Begin(&r); if (s != FgExecResult::Ok) return s; - for (const FgExecOp& op : ops) + FgExecStage stage = FgExecStage::GenPreNet2; + if (capture && !m.frame.colour_captured) { + m.TimeStage(r, stage); + m.CaptureColour(r); + } + for (const FgExecOp& op : ops) { + if (op.op == FgOp::Net2) stage = FgExecStage::Net2; + if (op.op == FgOp::OutPyramid) stage = FgExecStage::OutPyramid; + m.TimeStage(r, stage); if (!m.RecordOp(r, op)) return FgExecResult::Refused; + } + m.TimeStage(r, FgExecStage::PackCopy); s = m.WriteSlot(r, d.slot.slot, 'g', d.frame_token, d.index); if (s != FgExecResult::Ok) return s; s = m.Finish(r, ready); - if (s == FgExecResult::Ok) ++m.counters.indices; + if (s == FgExecResult::Ok) { + if (capture) m.frame.colour_captured = true; + ++m.counters.indices; + } return s; } @@ -1997,15 +2508,7 @@ FgExecResult FgD3d12Executor::RecordMenuCopy(const FgCopyDispatchDesc& d, FgRead if (!ready) return m.Fail(FgExecRefusal::BadArgument, "null ready fence"); if (!m.frame.valid || m.frame.token != d.frame_token) return m.Fail(FgExecRefusal::BadArgument, "no captured game frame for this token"); - Rec r; - FgExecResult s = m.Begin(&r); - if (s != FgExecResult::Ok) return s; - FgExecOp op; - op.op = FgOp::FinalCopy; - m.RecordOp(r, op); - s = m.WriteSlot(r, d.slot.slot, 'm', d.frame_token, d.index); - if (s != FgExecResult::Ok) return s; - s = m.Finish(r, ready); + const FgExecResult s = m.CopyFrameToSlot(d.slot.slot, 'm', d.frame_token, d.index, ready); if (s == FgExecResult::Ok) ++m.counters.copies; return s; } @@ -2048,35 +2551,25 @@ FgExecResult FgD3d12Executor::RecordRealEndpoint(const FgRealDispatchDesc& d, Fg if (write) { if (!have_frame && !from_bb) return m.Fail(FgExecRefusal::BadArgument, "no captured game frame for this token"); - Rec r; - FgExecResult s = m.Begin(&r); - if (s != FgExecResult::Ok) return s; if (from_bb) { - // capture the back buffer as this token's colour; the previous game frame's indices are all recorded - // before this (single caller, queue order), and the next game frame captures its own inputs FrameCtx f; f.token = d.frame_token; f.colour = bb; f.valid = true; m.frame = f; - if (Impl::NeedsTransition(bb.state)) - m.Transition(r, bb.res, bb.state, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - m.Capture(r, m.frame.colour, m.cap_colour, 4); - if (Impl::NeedsTransition(bb.state)) - m.Transition(r, bb.res, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, bb.state); - ++m.counters.game_colour_copies; } - FgExecOp op; - op.op = FgOp::FinalCopy; - m.RecordOp(r, op); - s = m.WriteSlot(r, slot, 'r', d.frame_token, 0); - if (s != FgExecResult::Ok) return s; - s = m.Finish(r, ready); - if (s == FgExecResult::Ok) ++m.counters.real_endpoints; + const FgExecResult s = m.CopyFrameToSlot(slot, 'r', d.frame_token, 0, ready); + if (s == FgExecResult::Ok) { + ++m.counters.real_endpoints; + if (from_bb) ++m.counters.game_colour_copies; + } + if (s != FgExecResult::Ok && from_bb) m.frame.valid = false; return s; } - const uint64_t v = ++m.next_value; - if (FAILED(m.queue->Signal(m.fence.Get(), v))) return m.Fail(FgExecRefusal::CommandFailed, "queue signal"); + uint64_t v = 0; + if (m.compute_queue && (!m.SignalHandoff(&v) || !m.JoinGameQueue())) + return m.QueueFailure("publish the game queue handoff"); + if (!m.SignalProducer(&v)) return m.QueueFailure("queue signal"); ready->fence = m.fence_id; ready->value = v; ++m.counters.real_endpoints; @@ -2151,7 +2644,7 @@ FgExecResult FgD3d12Executor::Net2SelfTest(uint32_t seed, float t, uint32_t runs if (runs == 0 || !gpu_ms) return FgExecResult::Ok; UINT64 freq = 0; - if (FAILED(m.queue->GetTimestampFrequency(&freq)) || freq == 0) return FgExecResult::Ok; + if (FAILED(m.ProducerQueue()->GetTimestampFrequency(&freq)) || freq == 0) return FgExecResult::Ok; D3D12_QUERY_HEAP_DESC qd = {}; qd.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP; qd.Count = 2; @@ -2198,13 +2691,29 @@ uint64_t FgD3d12Executor::CompletedComputeValue() const { return impl_->fence ? impl_->fence->GetCompletedValue() : 0; } +bool FgD3d12Executor::WaitForComputeValue(uint64_t value, uint32_t timeout_ms) { + return impl_->fence && impl_->WaitValue(value, timeout_ms); +} + bool FgD3d12Executor::WaitIdle(uint32_t timeout_ms) { - if (!impl_->fence) return true; - const bool idle = impl_->WaitValue(impl_->next_value, timeout_ms); + const bool idle = impl_->WaitIdle(timeout_ms); if (idle) impl_->FlushDumps(false); return idle; } +bool FgD3d12Executor::TakeTimings(FgExecTimings* out, uint32_t timeout_ms) { + Impl& m = *impl_; + if (!out || !m.producer_queries.readback || (m.compute_queue && !m.direct_queries.readback) || + !WaitIdle(timeout_ms)) + return false; + for (Entry& e : m.entries) m.CollectTimings(e, m.producer_queries); + for (Entry& e : m.direct_entries) m.CollectTimings(e, m.direct_queries); + if (m.timing_failed) return false; + *out = m.timings; + m.timings = {}; + return true; +} + bool FgD3d12Executor::TakeOutputs(std::vector* out) { Impl& m = *impl_; if (!out || !WaitIdle(m.desc.wait_ms * 4)) return false; diff --git a/clean/fg/runtime/fg_d3d12_executor.h b/clean/fg/runtime/fg_d3d12_executor.h index e9307f8e..632bf7ab 100644 --- a/clean/fg/runtime/fg_d3d12_executor.h +++ b/clean/fg/runtime/fg_d3d12_executor.h @@ -6,30 +6,28 @@ // Device side: // - One root signature for every FG kernel (clean/dx12/hlsl/wg_platform.hlsli): the arena as root UAV u0 and its // coherent alias u1, 59 root constants at b0 ([group base, workgroups, arguments...]) and a descriptor table with -// the driver channel's raw UAV (u0, space 0x7FFF0ADE, clean/dx12/hlsl/wg_ags.hlsli) and one texture view (t0) for -// the input capture. Kernels address the arena by 32-bit byte offsets; offset 0 is never a buffer (null). +// the driver channel's raw UAV (u0, space 0x7FFF0ADE, clean/dx12/hlsl/wg_ags.hlsli) and four input texture +// views (t0..t3). Kernels address the arena by 32-bit byte offsets; offset 0 is never a buffer (null). // - Configure (off the present path): loads the DXIL of every kernel it needs from FgD3d12ExecutorDesc::dxil_dir // (/.dxil, built by clean/dx12/build_dx12.py --only), builds every pipeline once, sizes the arena for // the frame size (every light-path image, the pyramid, net1's three regions, the input capture areas, the generated // image, and with the Full path its images, net2's tensors, the output pyramid and the logistic table), uploads the // weights (net1's fragments, net2's canonical weights) and creates the shared producer fence, the command // allocators, the descriptor heap and the readback buffer for the menu decision. -// - RecordSharedGameFrame: captures the game frame's colour, motion, depth and optional hudless colour / UI alpha -// into the arena (fg_exec_io.hlsl fg_exec_capture), then runs the once-per-game-frame stages of fg_exec_plan.h's -// schedule: history clears, menu detection, R3 downsample / UI, R4 motion and depth, the previous-to-current scatter -// (signed 64-bit atomic minimum), unpack, hole rule, pull / push, the hole mask, and net1's input pack, the fused -// 11-launch net1 (fg_net1_plan.h FgRecordNet1) and its output, or the quality image without history. The capture -// and the detection are submitted first; when a detector ran, the executor waits (bounded) for that submission -// only and reads the detection back, so the session gets this frame's decision. +// - RecordSharedGameFrame: runs the history clears, R3 downsample / UI and R4 motion and depth. The SRV kernels read +// the game textures on the game queue. Menu detection and output readbacks use arena captures. The remaining +// work uses the arena: previous-to-current scatter, unpack, hole rule, pull / push, hole mask, and net1's input, +// network and output (or the quality image without history). Menu detection waits for its decision readback. // - RecordGeneratedIndex: the per-index stages (intermediate-time scatters MA / MB, blend weights, then the light // blend (preset C) or the Full blend, net2 and the output pyramid (presets A / B), the menu output) into the // generated image, which is written into the presenter slot's texture (fg_exec_pack when the slot is not float16, // then a copy; the slot goes COMMON -> COPY_DEST -> COMMON), followed by a signal of the shared producer fence. -// - RecordMenuCopy / RecordRealEndpoint: the game frame's colour, exactly, into the slot; a real-only endpoint only -// signals the fence after the game frame's work on the queue. +// - RecordMenuCopy / RecordRealEndpoint: copy matching linear UNORM textures on the game queue, or capture colour +// on demand and convert it to the slot format. An endpoint without a slot signals the game frame's queue work. // - Every refusal names its reason (LastRefusal / LastWhy); nothing falls back to another path. -// The executor records on the session's queue (FgCreateDesc::queue), so the game's work that produced the inputs is -// ordered before it. Single caller (the session's present owner). No lambda captures a copy that can throw. +// The executor reads game textures on the session's queue (FgCreateDesc::queue), ordered after the game's producers. +// A direct game queue hands arena work to a dedicated compute queue by default +// (WRONGGPU_FG_ASYNC_COMPUTE=0 selects the game queue for all work). Single caller (the session's present owner). // // Conventions the frame contract leaves to the executor (until the adapter contract names them): // - FgFramePacket::camera_current is the clip-to-previous-clip matrix and camera_previous the previous-clip-to-clip @@ -39,9 +37,10 @@ // - net2's scalar input f is the index's intermediate time t. // - A real-only interval shows the game frame from a slot the executor reserves (ReserveRealSlot) and fills with an // exact copy, when the session recorded that frame's shared work, or, for an adapter-side real-only frame (FG off, -// menu flag, missing inputs), from the game's back buffer (FgRealDispatchDesc::game_colour: captured, then copied -// exactly) when it is a four-channel image of the output size; otherwise only the fence is signalled. +// menu flag, missing inputs), from the game's back buffer (FgRealDispatchDesc::game_colour) when it is a +// four-channel image of the output size; otherwise only the fence is signalled. // - A frame that carries the distortion field is refused (not modelled) unless the setting ignores it. +#include #include #include #include @@ -132,7 +131,7 @@ void FgExecSigTable(std::vector* out); enum class FgNet2Path : uint32_t { Fast = 0, Exact = 1 }; const char* FgNet2PathName(FgNet2Path p); -// One launch of the fast net2 plan for a net2 grid (CPU side, tested on its own): the kernel variant chosen for the +// One launch of the fast net2 plan for a net2 grid (CPU side, tested on its own): the baseline kernel variant for the // layer (clean/fg/runner/fg_net2_mma.py variant()), its workgroup count and the conv grid. struct FgNet2FastLaunch { uint32_t layer = 0; // 1..25, 0: the input merge, 26: the upwarp @@ -147,7 +146,7 @@ bool FgNet2FastPlan(uint32_t W2, uint32_t H2, std::vector* out bool FgNet2SwizzleFast(const std::vector& canonical, const std::vector& bias, uint32_t cout, uint32_t cw, std::vector* fragments, std::vector* bias_padded); -// The DXIL files (without ".dxil") an executor with these choices loads from FgD3d12ExecutorDesc::dxil_dir. +// The required DXIL files (without ".dxil") for these choices. The executor also loads available net1 tuning variants. std::vector FgD3d12ExecutorKernelNames(bool enable_full, FgNet2Path net2); // Whether a game texture of this DXGI format is accepted as the motion-vector input: it must be readable as a colour @@ -164,6 +163,7 @@ struct FgD3d12ExecutorDesc { uint32_t wait_ms = 2000; // bounded waits (menu decision, allocator reuse, idle) uint32_t allocators = 24; // command allocators in the ring bool keep_outputs = false; // tests: keep a host copy of every image written into a slot + bool timing = false; // also enabled by WRONGGPU_FG_TIMING=1 // Developer frame dumps (off while dump_dir is empty; the ASI sets it only in a developer build): of the game // frames that generate, every dump_every-th one (at most dump_max), the game frame's slot image (game_.ppm) and // each generated slot image (gen__.ppm) are copied to a readback buffer after the slot write, and written as @@ -199,6 +199,15 @@ struct FgExecCounters { uint64_t net2_fast = 0, net2_exact = 0; // net2 recordings per path }; +enum class FgExecStage : uint32_t { + Capture, SharedPreNet1, Net1, SharedPostNet1, GenPreNet2, Net2, OutPyramid, PackCopy, RealEndpoint, Count +}; + +struct FgExecTimings { + // Sum of GPU timestamp intervals for each stage since the previous collection, in milliseconds. + std::array(FgExecStage::Count)> ms = {}; +}; + class FgD3d12Executor final : public IFgKernelExecutor { public: explicit FgD3d12Executor(const FgD3d12ExecutorDesc& desc); @@ -221,8 +230,12 @@ class FgD3d12Executor final : public IFgKernelExecutor { const FgExecCounters& Counters() const; const FgExecGeometry& Geometry() const; uint64_t ArenaBytes() const; + // Bounded wait for a value on the producer fence. + bool WaitForComputeValue(uint64_t value, uint32_t timeout_ms); // Bounded wait until every submission completed. bool WaitIdle(uint32_t timeout_ms); + // Collect and clear the timings through the latest submission. Returns false when profiling is unavailable. + bool TakeTimings(FgExecTimings* out, uint32_t timeout_ms); // keep_outputs: waits idle and moves the host copies out (oldest first). bool TakeOutputs(std::vector* out); diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index 3c15b4ec..6681066f 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -8,6 +8,8 @@ // resets), every executor refusal that needs no GPU, and a session whose // executor refuses (no presenter is created, nothing falls back) // test_fg_d3d12_e2e --gpu --dxil adds the headless GPU leg (no window): a synthetic game drives the game +// test_fg_d3d12_e2e --bench --dxil reports steady-state 1440p GPU stage timings for presets A and C +// --reference-dxil compare direct-SRV output bytes against the captured path built with these kernels // adapter core, the FG session and this executor on the D3D12 device with // the composition back end (unbound surface) and the DXGI back end // (composition swap chain): preset C 2x and 6x, presets A / B 2x, a menu @@ -465,6 +467,17 @@ struct FakeChain { int g_fn_a = 0, g_fn_b = 0; FgTicks RealClock(void*) { return FgInterruptNow(); } + +struct PipelineClock { + FgTicks arrival = 0; + static FgTicks Read(void* ctx) { + auto& clock = *static_cast(ctx); + if (clock.arrival == 0) return FgInterruptNow(); + const FgTicks arrival = clock.arrival; + clock.arrival = 0; + return arrival; + } +}; bool g_debug_layer = false; int g_log_lines = 0; void PrintLog(void*, const char* line) { @@ -563,6 +576,7 @@ float Noise(uint32_t frame, uint32_t i, uint32_t c) { // optional full-screen menu overlay, a depth plane, motion in pixels, the translation matrices). struct Game { Gpu* gpu = nullptr; + uint32_t width = kW, height = kH; ComPtr colour, hudless, ui, depth, motion; DXGI_FORMAT colour_format = DXGI_FORMAT_R16G16B16A16_FLOAT; // the chain's format (B8G8R8A8 or RGBA16F) ComPtr upload; @@ -570,26 +584,31 @@ struct Game { D3D12_RESOURCE_STATES other_state = D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE; float clip_to_prev[16] = {}, prev_to_clip[16] = {}; - ComPtr Tex(DXGI_FORMAT f) { + ComPtr Tex(DXGI_FORMAT f, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { D3D12_HEAP_PROPERTIES hp = {}; hp.Type = D3D12_HEAP_TYPE_DEFAULT; D3D12_RESOURCE_DESC rd = {}; rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - rd.Width = kW; - rd.Height = kH; + rd.Width = width; + rd.Height = height; rd.DepthOrArraySize = 1; rd.MipLevels = 1; rd.Format = f; rd.SampleDesc.Count = 1; + rd.Flags = flags; ComPtr r; gpu->device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&r)); return r; } - bool Init(Gpu* g, DXGI_FORMAT cf) { + bool Init(Gpu* g, DXGI_FORMAT cf, uint32_t w = kW, uint32_t h = kH) { colour_format = cf; gpu = g; - colour = Tex(cf); + width = w; + height = h; + const uint32_t pitch8 = (width * 8 + 255) & ~255u; + colour = Tex(cf, colour_state == D3D12_RESOURCE_STATE_RENDER_TARGET + ? D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET : D3D12_RESOURCE_FLAG_NONE); hudless = Tex(DXGI_FORMAT_R16G16B16A16_FLOAT); ui = Tex(DXGI_FORMAT_R16G16B16A16_FLOAT); depth = Tex(DXGI_FORMAT_R32_FLOAT); @@ -598,7 +617,7 @@ struct Game { hp.Type = D3D12_HEAP_TYPE_UPLOAD; D3D12_RESOURCE_DESC rd = {}; rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - rd.Width = 5ull * 3072 * kH; // five textures, rows of 3072 bytes (320 x 8 rounded up to 256) + rd.Width = 5ull * pitch8 * height; rd.Height = 1; rd.DepthOrArraySize = 1; rd.MipLevels = 1; @@ -610,27 +629,50 @@ struct Game { clip_to_prev[0] = clip_to_prev[5] = clip_to_prev[15] = 1.0f; clip_to_prev[11] = 0.0625f; std::memcpy(prev_to_clip, clip_to_prev, sizeof(prev_to_clip)); - const float tx = 12.0f / static_cast(kW); + const float tx = 12.0f / static_cast(width); clip_to_prev[12] = tx; prev_to_clip[12] = -tx; return colour && hudless && ui && depth && motion && upload; } + FgFramePacket Packet() const { + const auto input = [&](ID3D12Resource* tex, D3D12_RESOURCE_STATES state) { + FgTextureRef ref; + ref.resource = tex; + ref.format = tex->GetDesc().Format; + ref.state = state; + ref.width = width; + ref.height = height; + ref.rect = {0, 0, width, height}; + return ref; + }; + FgFramePacket packet; + packet.color = input(colour.Get(), colour_state); + packet.depth = input(depth.Get(), other_state); + packet.motion = input(motion.Get(), other_state); + packet.optional[kFgOptHudless] = input(hudless.Get(), other_state); + packet.optional[kFgOptUiAlpha] = input(ui.Get(), other_state); + packet.optional_present = FgOptBit(kFgOptHudless) | FgOptBit(kFgOptUiAlpha); + packet.flags = kFgFlagDepthReversed; + std::memcpy(packet.camera_current, clip_to_prev, sizeof(clip_to_prev)); + std::memcpy(packet.camera_previous, prev_to_clip, sizeof(prev_to_clip)); + return packet; + } // Writes frame `f` (menu: the overlay) into the textures and waits for the copies. bool Upload(uint32_t f, bool menu, bool first) { uint8_t* base = nullptr; if (FAILED(upload->Map(0, nullptr, reinterpret_cast(&base)))) return false; - const uint32_t p8 = 3072, p4 = 1280, region = p8 * kH; // row pitches: 8-byte and 4-byte texels + const uint32_t p8 = (width * 8 + 255) & ~255u, p4 = (width * 4 + 255) & ~255u, region = p8 * height; uint16_t* col = reinterpret_cast(base); uint16_t* hud = reinterpret_cast(base + region); uint16_t* uim = reinterpret_cast(base + 2 * region); float* dep = reinterpret_cast(base + 3 * region); uint16_t* mot = reinterpret_cast(base + 4 * region); const float pan = 6.0f * static_cast(f); - const uint32_t bx0 = static_cast(kW * 0.3f) + 2 * f, by0 = static_cast(kH * 0.35f) + f; - const uint32_t bw = kW / 5, bh = kH / 4; - for (uint32_t y = 0; y < kH; ++y) - for (uint32_t x = 0; x < kW; ++x) { - const uint32_t i = y * kW + x; + const uint32_t bx0 = static_cast(width * 0.3f) + 2 * f, by0 = static_cast(height * 0.35f) + f; + const uint32_t bw = width / 5, bh = height / 4; + for (uint32_t y = 0; y < height; ++y) + for (uint32_t x = 0; x < width; ++x) { + const uint32_t i = y * width + x; const float fx = static_cast(x), fy = static_cast(y); float rgb[3] = {0.5f + 0.4f * std::sin((fx + pan) * 0.11f) * std::cos(fy * 0.07f), 0.5f + 0.3f * std::cos((fx + pan) * 0.05f + fy * 0.09f), @@ -643,14 +685,14 @@ struct Game { rgb[2] = 0.15f; } float alpha = 0.0f, uc[3] = {0, 0, 0}; - const bool panel = x >= kW * 0.62f && x < kW * 0.62f + kW / 4 && y >= kH * 0.08f && y < kH * 0.08f + kH / 5; + const bool panel = x >= width * 0.62f && x < width * 0.62f + width / 4 && y >= height * 0.08f && y < height * 0.08f + height / 5; if (panel) { alpha = ((x / 3 + y / 2) % 3 == 0) ? 1.0f : 0.75f; uc[0] = alpha == 1.0f ? 1.0f : 0.1f; uc[1] = alpha == 1.0f ? 1.0f : 0.8f; uc[2] = alpha == 1.0f ? 1.0f : 0.9f; } - if (menu && x >= kW * 0.05f && x < kW * 0.95f && y >= kH * 0.03f && y < kH * 0.97f) { + if (menu && x >= width * 0.05f && x < width * 0.95f && y >= height * 0.03f && y < height * 0.97f) { alpha = 0.9f; uc[0] = 0.05f; uc[1] = 0.05f; @@ -676,8 +718,8 @@ struct Game { else cp[3] = 0x3C00; up[3] = FgExecHalfBits(alpha); - const float dplane = 0.3f + 0.3f * fy / kH; - dep[y * p4 / 4 + x] = 1.0f - (block ? 0.012f + 0.008f * fx / kW : dplane); + const float dplane = 0.3f + 0.3f * fy / height; + dep[y * p4 / 4 + x] = 1.0f - (block ? 0.012f + 0.008f * fx / width : dplane); const float mx = block ? -4.0f : 6.0f, my = block ? -2.0f : 0.0f; mot[y * p4 / 2 + 2 * x] = FgExecHalfBits(mx + 0.4f * Noise(f, i, 3)); mot[y * p4 / 2 + 2 * x + 1] = FgExecHalfBits(my + 0.4f * Noise(f, i, 4)); @@ -705,7 +747,7 @@ struct Game { src.pResource = upload.Get(); src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; src.PlacedFootprint.Offset = static_cast(t) * region; - src.PlacedFootprint.Footprint = {fmts[t], kW, kH, 1, pitches[t]}; + src.PlacedFootprint.Footprint = {fmts[t], width, height, 1, pitches[t]}; gpu->list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; b.Transition.StateAfter = st; @@ -771,7 +813,8 @@ struct HeadlessSource final : public IFgPresenterSource { dd.swap_chain = chain.Get(); dd.pacing = FgDxgiPacing::Tearing; dd.max_generated = desc.max_generated; - dd.slot_count = desc.max_generated + 5; + // Fit two complete intervals and the real reserve while the headless display thread drains. + dd.slot_count = 2 * (desc.max_generated + 1) + 1; std::unique_ptr p; const FgWinResult r = FgDxgiPresenter::Create(dd, &p); last = std::string("dxgi tearing: ") + FgWinRefusalName(r.refusal); @@ -868,6 +911,7 @@ RunResult RunPipeline(Gpu& gpu, const std::string& dxil, const FgExecWeights& we proxy->set_options(WG_FEAT_FRAME_GENERATION, 1, &o, &o); proxy->claim_present(kChain, WG_FG_OWNER_NATIVE_ADAPTER); + PipelineClock clock; FgSession session; FgSessionDesc sd; FgCreateDesc& c = sd.create; @@ -891,13 +935,14 @@ RunResult RunPipeline(Gpu& gpu, const std::string& dxil, const FgExecWeights& we sd.executor = &exec; sd.presenter_source = &source; sd.history_banks = 3; - sd.clock = &RealClock; + sd.clock = &PipelineClock::Read; + sd.clock_ctx = &clock; sd.log = &PrintLog; g_log_lines = 0; sd.scheduler.display.min_interval = 1; sd.scheduler.display.max_interval = 10000000; sd.scheduler.max_lead = 2000000; - sd.scheduler.first_image_budget = 600000; + sd.scheduler.first_image_budget = dxgi ? 300000 : 600000; const FgSessionResult cr = session.Create(sd); std::printf(" create: %s (executor %s: %s; presenter %s)\n", FgSessionErrorName(cr.error), FgExecRefusalName(exec.LastRefusal()), exec.LastWhy().c_str(), headless.last.c_str()); @@ -910,9 +955,11 @@ RunResult RunPipeline(Gpu& gpu, const std::string& dxil, const FgExecWeights& we WgFgExecutorV1 h = session.ExecutorHandOff(); proxy->set_executor(&h); - const FgTicks period = 333333; // 30 game frames per second + const FgTicks period = dxgi ? 500000 : 333333; + const FgTicks first_arrival = FgInterruptNow() + period; int errors = 0; bool menu_seen = false; + uint32_t menu_recorded = 0; int off_frames = 0; for (int f = 0; f < frames; ++f) { const uint64_t tok = static_cast(f) + 1; @@ -976,7 +1023,11 @@ RunResult RunPipeline(Gpu& gpu, const std::string& dxil, const FgExecWeights& we pd.backbuffer.rect = {0, 0, kW, kH}; WgFgPresentResult pr = {}; FgSessionResult r; + // Fix the synthetic arrival cadence. The presenter and deadline checks still use wall time. + clock.arrival = first_arrival + f * period; + while (FgInterruptNow() < clock.arrival) Sleep(1); FgSessionPresent(proxy.get(), &session, &pd, &pr, &r); + clock.arrival = 0; if (r.error != FgSessionError::None) { ++errors; std::printf(" frame %llu: session %s, executor %s (%s), presenter %s; core status %u reason %u " @@ -985,9 +1036,14 @@ RunResult RunPipeline(Gpu& gpu, const std::string& dxil, const FgExecWeights& we FgExecRefusalName(exec.LastRefusal()), exec.LastWhy().c_str(), FgStatusName(r.presenter), pr.status, pr.reason, pr.real_only); } - if (menu) menu_seen = r.menu_detected; + if (menu) { + menu_seen = r.menu_detected; + menu_recorded = r.copies_recorded; + if (menu_recorded != n) + std::printf(" menu frame: scheduled %u, copied %u, unreserved %u, stale %u\n", + r.scheduled, menu_recorded, r.not_reserved, r.stale_cancelled); + } ++rr.frames; - Sleep(static_cast(period / 10000)); } CHECK(errors == 0); CHECK(exec.WaitIdle(5000)); @@ -1083,7 +1139,7 @@ RunResult RunPipeline(Gpu& gpu, const std::string& dxil, const FgExecWeights& we CHECK(rr.generated > 0 && gen_ok == rr.generated && finite); CHECK(copy_ok == rr.copies + rr.real); CHECK(slot_ok == outs.size()); - if (menu_frame >= 0) CHECK(menu_tok_copies == n); + if (menu_frame >= 0) CHECK(menu_recorded == n && menu_tok_copies == menu_recorded); // every slot comes back to the DXGI back end once the display path is done (the unbound composition surface // never composes, so its slots stay with the display: see HeadlessSource) if (FgDxgiPresenter* dp = dynamic_cast(pres)) { @@ -1301,18 +1357,548 @@ void TestMotionFormats() { CHECK(!FgD3d12MotionFormatAccepted(DXGI_FORMAT_BC1_UNORM)); } +struct ExecutorSlots final : IFgSlotTarget { + ComPtr textures[2]; + ID3D12Resource* SlotResource(uint32_t slot) const override { + return slot < 2 ? textures[slot].Get() : nullptr; + } + uint32_t RegisterFence(ID3D12Fence*, std::string*) override { return 1; } + bool ReserveRealSlot(uint32_t* slot) override { + *slot = 1; + return true; + } +}; + +bool CopiesMatchUpload(Gpu& gpu, const Game& game, const ExecutorSlots& slots) { + const UINT pitch = (game.width * 4 + 255) & ~255u; + const UINT64 bytes = static_cast(pitch) * game.height; + const UINT64 stride = (bytes + 511) & ~511ull; + D3D12_HEAP_PROPERTIES hp = {}; + hp.Type = D3D12_HEAP_TYPE_READBACK; + D3D12_RESOURCE_DESC rd = {}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = stride + bytes; + rd.Height = 1; + rd.DepthOrArraySize = 1; + rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ComPtr readback; + if (FAILED(gpu.device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback))) || + FAILED(gpu.alloc->Reset()) || FAILED(gpu.list->Reset(gpu.alloc.Get(), nullptr))) + return false; + for (uint32_t i = 0; i < 2; ++i) { + D3D12_TEXTURE_COPY_LOCATION src = {}; + src.pResource = slots.textures[i].Get(); + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + D3D12_TEXTURE_COPY_LOCATION dst = {}; + dst.pResource = readback.Get(); + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint.Offset = i * stride; + dst.PlacedFootprint.Footprint = {game.colour_format, game.width, game.height, 1, pitch}; + // A COMMON texture is implicitly promoted for this read-only copy and decays at the list boundary. + gpu.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + if (FAILED(gpu.list->Close())) return false; + ID3D12CommandList* lists[] = {gpu.list.Get()}; + gpu.queue->ExecuteCommandLists(1, lists); + if (!gpu.Wait()) return false; + void* expected = nullptr; + void* actual = nullptr; + if (FAILED(game.upload->Map(0, nullptr, &expected))) return false; + const bool mapped = SUCCEEDED(readback->Map(0, nullptr, &actual)); + bool exact = mapped; + if (mapped) { + const auto* images = static_cast(actual); + const auto* upload = static_cast(expected); + for (UINT y = 0; exact && y < game.height; ++y) { + const UINT64 row = static_cast(pitch) * y; + exact = std::memcmp(images + row, upload + row, game.width * 4) == 0 && + std::memcmp(images + stride + row, upload + row, game.width * 4) == 0; + } + } + const D3D12_RANGE none = {0, 0}; + if (mapped) readback->Unmap(0, &none); + game.upload->Unmap(0, &none); + return exact; +} + +void TestCopyPaths(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, bool supplied_compute) { + g_case = supplied_compute ? "gpu-copy-paths-supplied-compute" : "gpu-copy-paths-direct"; + constexpr DXGI_FORMAT format = DXGI_FORMAT_B8G8R8A8_UNORM; + Game game; + game.colour_state = supplied_compute ? D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE : D3D12_RESOURCE_STATE_RENDER_TARGET; + game.other_state = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + const bool game_ready = game.Init(&gpu, format) && game.Upload(0, false, true); + CHECK(game_ready); + if (!game_ready) return; + ExecutorSlots slots; + slots.textures[0] = game.Tex(format); + slots.textures[1] = game.Tex(supplied_compute ? format : DXGI_FORMAT_B8G8R8A8_TYPELESS); + CHECK(slots.textures[0] && slots.textures[1]); + if (!slots.textures[0] || !slots.textures[1]) return; + + ComPtr queue = gpu.queue; + if (supplied_compute) { + D3D12_COMMAND_QUEUE_DESC desc = {}; + desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + queue.Reset(); + const HRESULT hr = gpu.device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)); + CHECK(SUCCEEDED(hr)); + if (FAILED(hr)) return; + } + FgD3d12ExecutorDesc ed; + ed.dxil_dir = dxil; + ed.weights = &weights; + ed.enable_full = false; + FgD3d12Executor exec(ed); + FgCreateDesc create = CpuCreate(kW, kH); + create.device = gpu.device.Get(); + create.queue = queue.Get(); + const auto ok = [&](FgExecResult s) { + if (s != FgExecResult::Ok) std::printf(" executor: %s\n", exec.LastWhy().c_str()); + CHECK(s == FgExecResult::Ok); + return s == FgExecResult::Ok; + }; + if (!ok(exec.Configure(create, 3))) return; + const bool bound = exec.BindSlotTarget(&slots); + CHECK(bound); + if (!bound) return; + + const FgFramePacket packet = game.Packet(); + for (uint64_t token = 1; token <= 2; ++token) { + FgSharedDispatchDesc shared; + shared.frame_token = token; + shared.preset = FgPreset::C; + shared.has_previous = token > 1; + shared.generates = true; + shared.packet = &packet; + FgSharedResult result; + const uint64_t before = exec.LastComputeValue(); + if (!ok(exec.RecordSharedGameFrame(shared, &result))) return; + CHECK(exec.LastComputeValue() == before + 1 && !result.menu.detected); + } + FgReadyFence ready; + FgIndexDispatchDesc gen; + gen.frame_token = 2; + gen.index = gen.generated_count = 1; + gen.is_last_index = true; + gen.preset = FgPreset::C; + gen.t = 0.5f; + gen.slot.reserved = true; + if (!ok(exec.RecordGeneratedIndex(gen, &ready))) return; + const uint64_t dispatches = exec.Counters().dispatches; + const bool uncaptured = exec.Counters().captures == 0; + const uint64_t menu_cost = supplied_compute ? 2 + static_cast(uncaptured) : 0; + // Reuse the generated slot for the menu copy while compute may still be writing it. + FgCopyDispatchDesc menu; + menu.frame_token = 2; + menu.slot.reserved = true; + if (!ok(exec.RecordMenuCopy(menu, &ready))) return; + CHECK(exec.Counters().dispatches == dispatches + menu_cost); + + FgRealDispatchDesc real; + real.frame_token = 2; + real.slot.slot = 1; + real.slot.reserved = true; + if (!ok(exec.RecordRealEndpoint(real, &ready))) return; + CHECK(exec.Counters().dispatches == dispatches + menu_cost + (supplied_compute ? 2 : 0)); + real.frame_token = 3; + real.real_only = true; + real.game_colour = packet.color; + if (!ok(exec.RecordRealEndpoint(real, &ready))) return; + CHECK(exec.Counters().dispatches == dispatches + menu_cost + (supplied_compute ? 5 : 0)); + CHECK(exec.Counters().game_colour_copies == 1); + const bool idle = exec.WaitIdle(5000); + CHECK(idle && exec.CompletedComputeValue() >= ready.value); + if (idle) CHECK(CopiesMatchUpload(gpu, game, slots)); + const int64_t debug_errors = gpu.DebugErrors(); + if (debug_errors >= 0) CHECK(debug_errors == 0); +} + +// Upload shader-readable images directly in their declared format. The depth +// fixture uses an R32 typeless resource with the D32_FLOAT depth-stencil cast. +enum class FixtureRole { Colour, Depth, Motion, Alpha }; + +bool UploadFixture(Gpu& gpu, ID3D12Resource* tex, FixtureRole role, uint32_t frame) { + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp = {}; + const auto d = tex->GetDesc(); + UINT64 size = 0; + gpu.device->GetCopyableFootprints(&d, 0, 1, 0, &fp, nullptr, nullptr, &size); + D3D12_HEAP_PROPERTIES hp = {}; + hp.Type = D3D12_HEAP_TYPE_UPLOAD; + D3D12_RESOURCE_DESC bd = {}; + bd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + bd.Width = size; + bd.Height = 1; + bd.DepthOrArraySize = 1; + bd.MipLevels = 1; + bd.SampleDesc.Count = 1; + bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ComPtr upload; + uint8_t* bytes = nullptr; + if (FAILED(gpu.device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &bd, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&upload))) || + FAILED(upload->Map(0, nullptr, reinterpret_cast(&bytes)))) + return false; + for (uint32_t y = 0; y < d.Height; ++y) { + uint8_t* row = bytes + fp.Footprint.RowPitch * y; + for (uint32_t x = 0; x < d.Width; ++x) { + const uint32_t code = Hash(x + 419u * y + 611953u * frame); + const uint16_t half[4] = {static_cast(0x3000u + (code & 0xbffu)), + static_cast(0x3000u + ((code >> 7) & 0xbffu)), + static_cast(0x3000u + ((code >> 13) & 0xbffu)), + static_cast(0x3400u + ((code >> 21) & 0x7ffu))}; + if (role == FixtureRole::Depth) { + const float z = 0.1f + 0.8f * static_cast(code & 0xffffu) / 65535.0f; + std::memcpy(row + 4u * x, &z, 4); + } else if (role == FixtureRole::Motion) { + const float m[2] = {3.0f + 8.0f * Noise(frame, x + y * 419u, 0), + 2.0f + 6.0f * Noise(frame, x + y * 419u, 1)}; + const uint16_t h[2] = {FgExecHalfBits(m[0]), FgExecHalfBits(m[1])}; + if (d.Format == DXGI_FORMAT_R32G32_FLOAT) std::memcpy(row + 8u * x, m, 8); + else std::memcpy(row + 4u * x, h, 4); + } else if (d.Format == DXGI_FORMAT_R16G16B16A16_FLOAT) { + std::memcpy(row + 8u * x, half, 8); + } else if (d.Format == DXGI_FORMAT_R8_UNORM) { + row[x] = static_cast(code >> 24u); + } else { + const uint32_t packed = d.Format == DXGI_FORMAT_R11G11B10_FLOAT + ? ((half[0] >> 4u) | ((half[1] >> 4u) << 11u) | ((half[2] >> 5u) << 22u)) : code; + std::memcpy(row + 4u * x, &packed, 4); + } + } + } + upload->Unmap(0, nullptr); + if (FAILED(gpu.alloc->Reset()) || FAILED(gpu.list->Reset(gpu.alloc.Get(), nullptr))) return false; + D3D12_RESOURCE_BARRIER b = {}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {tex, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST}; + gpu.list->ResourceBarrier(1, &b); + D3D12_TEXTURE_COPY_LOCATION dst = {}, src = {}; + dst.pResource = tex; + dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src.pResource = upload.Get(); + src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src.PlacedFootprint = fp; + gpu.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + gpu.list->ResourceBarrier(1, &b); + if (FAILED(gpu.list->Close())) return false; + ID3D12CommandList* lists[] = {gpu.list.Get()}; + gpu.queue->ExecuteCommandLists(1, lists); + return gpu.Wait(); +} + +bool SlotsMatch(Gpu& gpu, const ExecutorSlots& actual, const ExecutorSlots& expected) { + // Read both sets of textures through identical footprints and compare only the texel bytes. + D3D12_RESOURCE_DESC bd = {}; + bd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + bd.Height = 1; + bd.DepthOrArraySize = 1; + bd.MipLevels = 1; + bd.SampleDesc.Count = 1; + bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp[2][2] = {}; + UINT64 row_bytes[2] = {}; + UINT rows[2] = {}; + for (uint32_t i = 0; i < 2; ++i) { + const auto d = actual.textures[i]->GetDesc(); + for (auto& dest : fp[i]) { + UINT64 size = 0; + gpu.device->GetCopyableFootprints(&d, 0, 1, (bd.Width + 511u) & ~511ull, &dest, + &rows[i], &row_bytes[i], &size); + bd.Width = dest.Offset + size; + } + } + D3D12_HEAP_PROPERTIES hp = {}; + hp.Type = D3D12_HEAP_TYPE_READBACK; + ComPtr readback; + if (FAILED(gpu.device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &bd, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback))) || + FAILED(gpu.alloc->Reset()) || FAILED(gpu.list->Reset(gpu.alloc.Get(), nullptr))) + return false; + for (uint32_t i = 0; i < 2; ++i) { + ID3D12Resource* srcs[] = {actual.textures[i].Get(), expected.textures[i].Get()}; + for (uint32_t j = 0; j < 2; ++j) { + D3D12_TEXTURE_COPY_LOCATION src = {}, dst = {}; + src.pResource = srcs[j]; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dst.pResource = readback.Get(); + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = fp[i][j]; + gpu.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + } + if (FAILED(gpu.list->Close())) return false; + ID3D12CommandList* lists[] = {gpu.list.Get()}; + gpu.queue->ExecuteCommandLists(1, lists); + if (!gpu.Wait()) return false; + void* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, &mapped))) return false; + const auto* bytes = static_cast(mapped); + bool exact = true; + for (uint32_t i = 0; i < 2; ++i) + for (uint32_t y = 0; y < rows[i] && exact; ++y) + exact = std::memcmp(bytes + fp[i][0].Offset + y * fp[i][0].Footprint.RowPitch, + bytes + fp[i][1].Offset + y * fp[i][1].Footprint.RowPitch, + static_cast(row_bytes[i])) == 0; + const D3D12_RANGE none = {0, 0}; + readback->Unmap(0, &none); + return exact; +} + +void TestInputSrvPaths(Gpu& gpu, const std::string& dxil, const std::string& reference, const FgExecWeights& weights) { + g_case = "gpu-input-srv-formats"; + std::ifstream shader(dxil + "/fg_lite_mvec_srv.dxil", std::ios::binary); + if (!shader) { + CHECK(reference.empty()); + return; + } + struct FormatCase { + DXGI_FORMAT colour, alpha, motion, slot; + FgPreset preset; + uint32_t height; + }; + const FormatCase cases[] = { + {DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16_FLOAT, + DXGI_FORMAT_R16G16B16A16_FLOAT, FgPreset::B, 89}, + {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R8G8B8A8_UNORM, FgPreset::C, 91}, + {DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R16G16_FLOAT, + DXGI_FORMAT_R8G8B8A8_UNORM, FgPreset::C, 93}, + {DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_B8G8R8A8_UNORM, FgPreset::A, 95}, + {DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R16G16_FLOAT, + DXGI_FORMAT_R10G10B10A2_UNORM, FgPreset::C, 97}, + {DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R16G16B16A16_FLOAT, FgPreset::C, 1441}, + {DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R16G16_FLOAT, + DXGI_FORMAT_R16G16B16A16_FLOAT, FgPreset::C, 1443}, + }; + for (const auto& c : cases) { + Game game; + game.gpu = &gpu; + game.width = 131; + game.height = c.height; + game.colour_state = game.other_state = D3D12_RESOURCE_STATE_COMMON; + game.colour = game.Tex(c.colour); + game.hudless = game.Tex(c.colour); + game.ui = game.Tex(c.alpha); + game.depth = game.Tex(DXGI_FORMAT_R32_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + game.motion = game.Tex(c.motion); + const bool ready = game.colour && game.hudless && game.ui && game.depth && game.motion; + CHECK(ready); + if (!ready) continue; + D3D12_DEPTH_STENCIL_VIEW_DESC dsv = {}; + dsv.Format = DXGI_FORMAT_D32_FLOAT; + dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + D3D12_DESCRIPTOR_HEAP_DESC dh = {}; + dh.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; + dh.NumDescriptors = 1; + ComPtr heap; + if (FAILED(gpu.device->CreateDescriptorHeap(&dh, IID_PPV_ARGS(&heap)))) { + CHECK(false); + return; + } + gpu.device->CreateDepthStencilView(game.depth.Get(), &dsv, heap->GetCPUDescriptorHandleForHeapStart()); + for (int i = 0; i < 16; i += 5) game.clip_to_prev[i] = game.prev_to_clip[i] = 1.0f; + + ExecutorSlots test_slots, ref_slots; + FgD3d12ExecutorDesc ed; + ed.dxil_dir = dxil; + ed.weights = &weights; + ed.enable_full = c.preset != FgPreset::C; + FgD3d12Executor test(ed); + ed.dxil_dir = reference.empty() ? dxil : reference; + ed.keep_outputs = true; + FgD3d12Executor ref(ed); + FgCreateDesc create = CpuCreate(game.width, game.height); + create.device = gpu.device.Get(); + create.queue = gpu.queue.Get(); + create.preset = c.preset; + auto ok = [&](FgD3d12Executor& exec, FgExecResult status) { + if (status != FgExecResult::Ok) + std::printf(" input SRV test: %s\n", exec.LastWhy().c_str()); + CHECK(status == FgExecResult::Ok); + return status == FgExecResult::Ok; + }; + for (auto* slots : {&test_slots, &ref_slots}) + for (auto& tex : slots->textures) tex = game.Tex(c.slot); + if (!ok(test, test.Configure(create, 3)) || !ok(ref, ref.Configure(create, 3))) return; + if (!test.BindSlotTarget(&test_slots) || !ref.BindSlotTarget(&ref_slots)) { + CHECK(false); + return; + } + for (uint64_t token = 1; token <= 2; ++token) { + const auto f = static_cast(token); + const bool uploaded = UploadFixture(gpu, game.colour.Get(), FixtureRole::Colour, f) && + UploadFixture(gpu, game.hudless.Get(), FixtureRole::Colour, f + 2) && + UploadFixture(gpu, game.ui.Get(), FixtureRole::Alpha, f + 4) && + UploadFixture(gpu, game.depth.Get(), FixtureRole::Depth, f) && + UploadFixture(gpu, game.motion.Get(), FixtureRole::Motion, f); + CHECK(uploaded); + if (!uploaded) return; + auto packet = game.Packet(); + packet.frame_token = token; + packet.motion_scale_x = 8.0f; + packet.motion_scale_y = 8.0f; + if (c.colour != DXGI_FORMAT_R8G8B8A8_UNORM_SRGB && c.colour != DXGI_FORMAT_R10G10B10A2_UNORM) + packet.optional[kFgOptHudless].rect = {1, 3, game.width - 2, game.height - 5}; + packet.optional[kFgOptUiAlpha].rect = {2, 1, game.width - 4, game.height - 2}; + FgSharedDispatchDesc shared; + shared.frame_token = token; + shared.preset = c.preset; + shared.has_previous = token == 2; + shared.generates = true; + shared.packet = &packet; + FgSharedResult result; + const uint64_t captures = test.Counters().captures; + if (!ok(test, test.RecordSharedGameFrame(shared, &result)) || + !ok(ref, ref.RecordSharedGameFrame(shared, &result))) return; + CHECK(test.Counters().captures == captures); + FgIndexDispatchDesc gen; + gen.frame_token = token; + gen.index = gen.generated_count = 1; + gen.is_last_index = true; + gen.preset = c.preset; + gen.t = 0.5f; + gen.slot.reserved = true; + FgRealDispatchDesc real; + real.frame_token = token; + real.slot.slot = 1; + real.slot.reserved = true; + FgReadyFence fence; + for (auto* exec : {&test, &ref}) { + if (!ok(*exec, exec->RecordGeneratedIndex(gen, &fence)) || + !ok(*exec, exec->RecordRealEndpoint(real, &fence))) return; + } + const bool idle = test.WaitIdle(5000) && ref.WaitIdle(5000); + CHECK(idle); + if (!idle) return; + const bool exact = SlotsMatch(gpu, test_slots, ref_slots); + if (!exact) + std::printf(" input SRV mismatch: colour %u, alpha %u, motion %u, slot %u, frame %llu\n", + c.colour, c.alpha, c.motion, c.slot, static_cast(token)); + CHECK(exact); + } + } + const int64_t errors = gpu.DebugErrors(); + if (errors >= 0) CHECK(errors == 0); +} + +bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, FgPreset preset) { + constexpr uint32_t width = 2560, height = 1440, warmup = 8, timed = 30; + constexpr uint32_t timeout = 30000; + const char label = preset == FgPreset::A ? 'A' : 'C'; + Game game; + const DXGI_FORMAT format = DXGI_FORMAT_B8G8R8A8_UNORM; + if (!game.Init(&gpu, format, width, height) || !game.Upload(0, false, true)) return false; + ExecutorSlots slots; + for (auto& tex : slots.textures) { + tex = game.Tex(format); + if (!tex) return false; + } + + FgD3d12ExecutorDesc ed; + ed.dxil_dir = dxil; + ed.weights = &weights; + ed.enable_full = preset == FgPreset::A; + ed.timing = true; + FgD3d12Executor exec(ed); + const auto ok = [&](FgExecResult s) { + if (s == FgExecResult::Ok) return true; + std::printf("bench %c: %s (%s)\n", label, FgExecRefusalName(exec.LastRefusal()), exec.LastWhy().c_str()); + return false; + }; + FgCreateDesc create = CpuCreate(width, height); + create.device = gpu.device.Get(); + create.queue = gpu.queue.Get(); + create.preset = preset; + if (!ok(exec.Configure(create, 3)) || !exec.BindSlotTarget(&slots)) return false; + + FgFramePacket packet = game.Packet(); + + FgExecTimings timing; + for (uint32_t i = 0; i < warmup + timed; ++i) { + packet.frame_token = i + 1; + FgSharedDispatchDesc shared; + shared.frame_token = packet.frame_token; + shared.preset = preset; + shared.has_previous = i != 0; + shared.generated_count = 1; + shared.generates = true; + shared.packet = &packet; + FgSharedResult result; + if (!ok(exec.RecordSharedGameFrame(shared, &result))) return false; + FgIndexDispatchDesc gen; + gen.frame_token = packet.frame_token; + gen.index = gen.generated_count = 1; + gen.is_last_index = true; + gen.preset = preset; + gen.t = 0.5f; + gen.slot.slot = 0; + gen.slot.reserved = true; + FgReadyFence ready; + if (!ok(exec.RecordGeneratedIndex(gen, &ready))) return false; + FgRealDispatchDesc real; + real.frame_token = packet.frame_token; + real.slot.slot = 1; + real.slot.reserved = true; + if (!ok(exec.RecordRealEndpoint(real, &ready))) return false; + if (i + 1 == warmup && !exec.TakeTimings(&timing, timeout)) { + std::printf("bench %c: warmup timestamps unavailable\n", label); + return false; + } + } + if (!exec.TakeTimings(&timing, timeout)) { + std::printf("bench %c: timed timestamps unavailable\n", label); + return false; + } + const char* stages[] = {"capture", "shared_pre_net1", "net1", "shared_post_net1", "gen_pre_net2", + "net2", "out_pyramid", "pack_copy", "real_endpoint"}; + static_assert(sizeof(stages) / sizeof(*stages) == static_cast(FgExecStage::Count)); + std::printf("bench preset %c 2x %ux%u (%u warmup, %u timed, mean GPU ms)\n", label, width, height, warmup, timed); + double shared = 0.0, gen = 0.0; + for (size_t i = 0; i < timing.ms.size(); ++i) { + const double mean = timing.ms[i] / timed; + std::printf(" %-18s %.6f\n", stages[i], mean); + if (i <= static_cast(FgExecStage::SharedPostNet1)) shared += mean; + else if (i <= static_cast(FgExecStage::PackCopy)) gen += mean; + } + // Totals sum GPU execution intervals. Queue waits and overlap are not wall-clock frame time. + std::printf(" %-18s %.6f\n %-18s %.6f\n %-18s %.6f\n", "total_shared", shared, "total_gen", gen, + "total_2x_frame", shared + gen + timing.ms[static_cast(FgExecStage::RealEndpoint)] / timed); + return gpu.DebugErrors() <= 0; +} + int main(int argc, char** argv) { - bool gpu = false; - std::string dxil, scratch = ".", only; + bool gpu = false, bench = false; + std::string dxil, reference_dxil, scratch = ".", only; for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--gpu") == 0) gpu = true; + if (std::strcmp(argv[i], "--bench") == 0) bench = true; if (std::strcmp(argv[i], "--dxil") == 0 && i + 1 < argc) dxil = argv[++i]; + if (std::strcmp(argv[i], "--reference-dxil") == 0 && i + 1 < argc) reference_dxil = argv[++i]; if (std::strcmp(argv[i], "--scratch") == 0 && i + 1 < argc) scratch = argv[++i]; if (std::strcmp(argv[i], "--debug-layer") == 0) g_debug_layer = true; if (std::strcmp(argv[i], "--only") == 0 && i + 1 < argc) only = argv[++i]; } FgExecWeights weights; FgExecSyntheticWeights(11, &weights); + if (bench) { + Gpu g; + if (dxil.empty() || !g.Init()) { + std::printf("bench requires --dxil and a D3D12 device\n"); + return 1; + } + std::printf("gpu: %s\n", g.name.c_str()); + if (!RunBench(g, dxil, weights, FgPreset::A) || !RunBench(g, dxil, weights, FgPreset::C)) return 1; + if (!gpu) return 0; + } TestGeometry(); TestRegionsAndThresholds(); TestHalf(); @@ -1373,6 +1959,12 @@ int main(int argc, char** argv) { want_dxgi); if (only.empty()) CHECK(ran_comp == want_comp && ran_dxgi == want_dxgi); // every configuration ran if (only.empty() || only.find("net2") != std::string::npos) TestNet2Paths(g, dxil, weights); + if (only.empty() || only.find("copy-paths") != std::string::npos) { + TestCopyPaths(g, dxil, weights, false); + TestCopyPaths(g, dxil, weights, true); + } + if (only.empty() || only.find("input-srv") != std::string::npos) + TestInputSrvPaths(g, dxil, reference_dxil, weights); if (only.empty()) TestBrokenKernels(g, dxil, weights, scratch); } } From a8150dbac2906e3075bf4268dc36f2d0536af30f Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:13:50 -0500 Subject: [PATCH 02/15] FG proxy tests: use static_assert for constant gate checks (fixes MSVC /W4 /WX C4127) --- clean/fg/proxy/tests/test_fg_proxy.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/clean/fg/proxy/tests/test_fg_proxy.cpp b/clean/fg/proxy/tests/test_fg_proxy.cpp index f69229fa..f483bfa5 100644 --- a/clean/fg/proxy/tests/test_fg_proxy.cpp +++ b/clean/fg/proxy/tests/test_fg_proxy.cpp @@ -529,9 +529,9 @@ void TestReleaseGateForwardsEverything() { FgProxyConfig cfg = QualifiedConfig(); // the shipped gate is closed (a developer build with WRONGGPU_FG_DEV_QUALIFIED opens it; the closed gate's // behaviour is still checked there) - CHECK(kFgModesQualified == (WG_FG_MODES_QUALIFIED != 0)); + static_assert(kFgModesQualified == (WG_FG_MODES_QUALIFIED != 0), "kFgModesQualified must match macro"); #if !WG_FG_MODES_QUALIFIED - CHECK(!kFgModesQualified); + static_assert(!kFgModesQualified, "shipped gate must be closed"); #endif cfg.modes_qualified = false; Rig rig(cfg); @@ -1245,9 +1245,9 @@ void TestRuntimeContractBridge() { CHECK(packet.generated_count == 5 && packet.preset == wgfg::FgPreset::C && packet.optional_present == 0x5); CHECK(packet.motion.resource == Res(1) && packet.optional[2].resource == Res(5)); CHECK(create.max_generated == 5 && create.presenter_mode == 0); - CHECK(kFgModesQualified == wgfg::kFgModesQualified); + static_assert(kFgModesQualified == wgfg::kFgModesQualified, "proxy and runtime gate must agree"); #if !WG_FG_MODES_QUALIFIED - CHECK(!wgfg::kFgModesQualified); + static_assert(!wgfg::kFgModesQualified, "shipped runtime gate must be closed"); #endif } #endif From 4cf408627f4f98cfce4fd5e0730886332237890c Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:50:18 -0500 Subject: [PATCH 03/15] FG swapchain hook: silence MSVC /W4 /WX C4127 on mutant 6 --- clean/fg/proxy/win32/fg_swapchain_hook.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/clean/fg/proxy/win32/fg_swapchain_hook.cpp b/clean/fg/proxy/win32/fg_swapchain_hook.cpp index ee122b59..efb09b9b 100644 --- a/clean/fg/proxy/win32/fg_swapchain_hook.cpp +++ b/clean/fg/proxy/win32/fg_swapchain_hook.cpp @@ -174,15 +174,14 @@ uint32_t FgSwapChain::Attach(IFgPresentCallback* callback, FgProxy* core, FgPres if (callback_) return WG_FG_REASON_DOUBLE_ATTACH; FgPresentOwners* reg = owners ? owners : &FgProcessPresentOwners(); #if WG_FG_WIN32_MUTANT == 6 - const uint32_t r = WG_FG_REASON_NONE; (void)core; #else const uint32_t r = core ? core->claim_present(id_, owner) : reg->claim(id_, owner); -#endif if (r != WG_FG_REASON_NONE) { Log("fg swap chain: present owner not claimed (reason " + std::to_string(r) + "); the chain presents as before"); return r; } +#endif callback_ = callback; core_ = core; owners_ = reg; From bcf27ef57e9ce704be43fd1967d96d5ba9a516c5 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:57:56 -0500 Subject: [PATCH 04/15] Frame generation (D3D12): the output kernels write the presenter slot's packed rows directly, dropping the fg_exec_pack pass (Preset A 2x -45 us, 6x -219 us; Preset C 2x -45 us, 6x -223 us; exact) The Full path's fg_out_pull / fg_out_push_fine and the light path's fg_lite_blend each get a _pack variant that stores the 8 / 10-bit UNORM slot code (clean/dx12/hlsl/fg_pack.hlsli, the same code fg_exec_pack computes) instead of the float16 image, so the generated frame is neither written at 8 B per pixel, read back, nor given its own dispatch and barrier. The executor picks them when nothing writes the output image after them (no menu output, prefill or copy), outputs are not kept for readback and the slot is an RGBA8 / BGRA8 / RGB10A2 image of the output size; every other case keeps the old kernels. Two Full-path slot-format cases join the input-SRV test (RGBA8 preset A, RGB10A2 preset B, odd widths). --- clean/dx12/hlsl/fg_pack.hlsli | 27 +++++++++ clean/dx12/kernels/fg_exec_io.hlsl | 23 +------- clean/dx12/kernels/fg_lite_blend.hlsl | 13 +++++ clean/dx12/kernels/fg_out_pull.hlsl | 20 +++++++ clean/dx12/kernels/fg_out_push.hlsl | 14 +++++ clean/fg/runtime/fg_d3d12_executor.cpp | 58 +++++++++++++++---- clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 5 ++ .../fg/tests/test_fg_full_stages_gpu_plan.py | 4 +- 8 files changed, 131 insertions(+), 33 deletions(-) create mode 100644 clean/dx12/hlsl/fg_pack.hlsli diff --git a/clean/dx12/hlsl/fg_pack.hlsli b/clean/dx12/hlsl/fg_pack.hlsli new file mode 100644 index 00000000..2fa45ed6 --- /dev/null +++ b/clean/dx12/hlsl/fg_pack.hlsli @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): the presenter-slot packing shared by fg_exec_pack and the output kernels that write the +// packed slot rows directly (fg_out_pull_pack, fg_out_push_fine_pack). fmt: 1 = R8G8B8A8_UNORM, 2 = B8G8R8A8_UNORM, +// 3 = R10G10B10A2_UNORM; UNORM codes are floor(sat(v) * max + 0.5) with sat(NaN) = 0. v = the pixel as 4 x float16. +#pragma once + +uint fgx_unorm(float v, float mx) +{ + const float s = min(max(v, 0.0f), 1.0f); + return (uint)floor(mad(s, mx, 0.5f)); +} + +uint fgx_pack_pixel(uint2 v, uint fmt) +{ + const float r = f16tof32(v.x), g = f16tof32(v.x >> 16), b = f16tof32(v.y), a = f16tof32(v.y >> 16); + uint word; + if (fmt == 1u) + word = fgx_unorm(r, 255.0f) | (fgx_unorm(g, 255.0f) << 8) | (fgx_unorm(b, 255.0f) << 16) | + (fgx_unorm(a, 255.0f) << 24); + else if (fmt == 2u) + word = fgx_unorm(b, 255.0f) | (fgx_unorm(g, 255.0f) << 8) | (fgx_unorm(r, 255.0f) << 16) | + (fgx_unorm(a, 255.0f) << 24); + else + word = fgx_unorm(r, 1023.0f) | (fgx_unorm(g, 1023.0f) << 10) | (fgx_unorm(b, 1023.0f) << 20) | + (fgx_unorm(a, 3.0f) << 30); + return word; +} diff --git a/clean/dx12/kernels/fg_exec_io.hlsl b/clean/dx12/kernels/fg_exec_io.hlsl index 0f65786e..35396269 100644 --- a/clean/dx12/kernels/fg_exec_io.hlsl +++ b/clean/dx12/kernels/fg_exec_io.hlsl @@ -16,12 +16,7 @@ // @wg-kernel fg_exec_pack_pairs co=- entry=fg_exec_pack block=256 wave=32 args=p,u,p,u,u,u,u defines=FGX_K=2,FGX_PAIRS=1 #include "wg_platform.hlsli" #include "fg_fp16.hlsli" - -uint fgx_unorm(float v, float mx) -{ - const float s = min(max(v, 0.0f), 1.0f); - return (uint)floor(mad(s, mx, 0.5f)); -} +#include "fg_pack.hlsli" #if FGX_K == 1 WG_ARGS_BEGIN @@ -73,22 +68,6 @@ WG_ARGS_BEGIN uint a0, a1, a2, a3, a4, a5, a6; WG_ARGS_END -uint fgx_pack_pixel(uint2 v, uint fmt) -{ - const float r = f16tof32(v.x), g = f16tof32(v.x >> 16), b = f16tof32(v.y), a = f16tof32(v.y >> 16); - uint word; - if (fmt == 1u) - word = fgx_unorm(r, 255.0f) | (fgx_unorm(g, 255.0f) << 8) | (fgx_unorm(b, 255.0f) << 16) | - (fgx_unorm(a, 255.0f) << 24); - else if (fmt == 2u) - word = fgx_unorm(b, 255.0f) | (fgx_unorm(g, 255.0f) << 8) | (fgx_unorm(r, 255.0f) << 16) | - (fgx_unorm(a, 255.0f) << 24); - else - word = fgx_unorm(r, 1023.0f) | (fgx_unorm(g, 1023.0f) << 10) | (fgx_unorm(b, 1023.0f) << 20) | - (fgx_unorm(a, 3.0f) << 30); - return word; -} - // fg_exec_pack: a0 = src, a1 = sstride, a2 = dst, a3 = dpitch, a4 = w, a5 = h, a6 = fmt WG_KERNEL(fg_exec_pack) { diff --git a/clean/dx12/kernels/fg_lite_blend.hlsl b/clean/dx12/kernels/fg_lite_blend.hlsl index dd72cd7d..27729392 100644 --- a/clean/dx12/kernels/fg_lite_blend.hlsl +++ b/clean/dx12/kernels/fg_lite_blend.hlsl @@ -4,11 +4,16 @@ // refined candidates (detail transfer from the reference images Lp / Lc where a candidate's source sits on UI and both // co-located pixels are UI-free); flag1: the time-interpolated UI estimate laid over the result. D3D12 only. // fg_lite_blend_mut is a negative control for the GPU check (the empty-MB fallback dropped), never used otherwise. +// fg_lite_blend_pack (FG_PACK) writes the presenter slot's packed row instead (fg_pack.hlsli): outp = the packed rows' +// offset, ostride = their pitch in bytes, ox = the format code (1 R8G8B8A8, 2 B8G8R8A8, 3 R10G10B10A2), oy = 0; each +// pixel is stored as the code fg_exec_pack makes of the float16 pixel fg_lite_blend writes. // // @wg-kernel fg_lite_blend co=- block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u +// @wg-kernel fg_lite_blend_pack co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_PACK=1 // @wg-kernel fg_lite_blend_mut co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MUT=1 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" +#include "fg_pack.hlsli" WG_ARGS_BEGIN uint cp, cc, ma, mb, wimg, up, uc, lp, lc, outp; @@ -19,6 +24,9 @@ WG_ARGS_END #ifndef FG_MUT #define FG_MUT 0 #endif +#ifndef FG_PACK +#define FG_PACK 0 +#endif bool fg_in_box(float px, float py) { @@ -94,5 +102,10 @@ WG_KERNEL(fg_lite_blend) const float4 U = mad(ucv - upv, t.xxxx, upv); o = mad(o, (1.0f - U.w).xxx, U.xyz); } +#if FG_PACK + const uint2 h = uint2(fg_pack_h2(o.x, o.y), fg_pack_h2(o.z, 1.0f)); + wg_st32(outp, (oy + y) * ostride + x * 4u, fgx_pack_pixel(h, ox)); +#else fg_st_h4(outp, (oy + y) * ostride + ox + x, float4(o, 1.0f)); +#endif } diff --git a/clean/dx12/kernels/fg_out_pull.hlsl b/clean/dx12/kernels/fg_out_pull.hlsl index edeb081d..16e26f63 100644 --- a/clean/dx12/kernels/fg_out_pull.hlsl +++ b/clean/dx12/kernels/fg_out_pull.hlsl @@ -11,14 +11,23 @@ // fg_out_pull_mid: one workgroup per 16 x 16 tile of level 4 (tiles_x = ceil(w4 / 16)): levels 5..8 from level 4's // stored values (partials (r w, g w, b w, w)). // +// fg_out_pull_pack (FGP_PACK): the same, but out is the presenter slot's packed row (fg_pack.hlsli): outp = the packed +// rows' offset, out_pitch = their pitch in bytes, out_x = the format code (1 R8G8B8A8, 2 B8G8R8A8, 3 R10G10B10A2), +// out_y = 0; each pixel is stored as the code fg_exec_pack makes of the float16 pixel fg_out_pull writes. +// // @wg-kernel fg_out_pull co=fg_full.co block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u +// @wg-kernel fg_out_pull_pack co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_PACK=1 // @wg-kernel fg_out_pull_mid co=fg_full.co block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u defines=FGP_MID=1 #include "wg_platform.hlsli" #include "fg_full.hlsli" +#include "fg_pack.hlsli" #ifndef FGP_MID #define FGP_MID 0 #endif +#ifndef FGP_PACK +#define FGP_PACK 0 +#endif groupshared float4 fgp_wave_sums[8]; @@ -213,8 +222,19 @@ WG_KERNEL(fg_out_pull) pv.v[0] = fgf_opq(out_c.x); pv.v[1] = fgf_opq(out_c.y); pv.v[2] = fgf_opq(out_c.z); [unroll] for (uint ci = 3u; ci < 8u; ++ci) pv.v[ci] = 0.0f; const uint4 h = wg_to_f16_ags(pv); +#if FGP_PACK + const uint word = fgx_pack_pixel(uint2(h.x, (h.y & 0xffffu) | 0x3c000000u), (uint)out_x); + const uint pair = QuadReadAcrossX(word); + // Adjacent Morton lanes are a horizontal pair (the origin is a multiple of 16); the rows are 8-byte aligned. + if (in_bounds && (px & 1) == 0) { + const uint at = (uint)(py + out_y) * (uint)out_pitch + (uint)px * 4u; + if (px + 1 < Wo) wg_st64(outp, at, uint2(word, pair)); + else wg_st32(outp, at, word); + } +#else if (in_bounds) wg_st64(outp, (uint)((py + out_y) * out_pitch + px + out_x) * 8u, uint2(h.x, (h.y & 0xffffu) | 0x3c000000u)); +#endif } fgf_store_morton_flag(fine, px, py, Wo, Ho, hole); fgp_reduce(acc, origin, Wo, Ho, 0u, uint4(lv1, lv2, lv3, lv4)); diff --git a/clean/dx12/kernels/fg_out_push.hlsl b/clean/dx12/kernels/fg_out_push.hlsl index 3094f3b7..c44d360e 100644 --- a/clean/dx12/kernels/fg_out_push.hlsl +++ b/clean/dx12/kernels/fg_out_push.hlsl @@ -9,14 +9,23 @@ // fg_out_push_fine: one lane per frame pixel; where the fine flag is > 0 (a hole), out := (upsample of filled level 1, // 1.0) (row pitch out_pitch, offset (out_x, out_y)); other pixels are not written. // +// fg_out_push_fine_pack (FGU_PACK): writes the presenter slot's packed row instead (fg_pack.hlsli): outp = the packed +// rows' offset, out_pitch = their pitch in bytes, out_x = the format code (1 R8G8B8A8, 2 B8G8R8A8, 3 R10G10B10A2), +// out_y = 0; the pixel is stored as the code fg_exec_pack makes of the float16 pixel fg_out_push_fine writes. +// // @wg-kernel fg_out_push co=fg_full.co block=256 wave=32 args=p,p,p,u,u,u,u // @wg-kernel fg_out_push_fine co=fg_full.co block=256 wave=32 args=p,p,p,u,u,u,u,u,u,u defines=FGU_FINE=1 +// @wg-kernel fg_out_push_fine_pack co=- entry=fg_out_push_fine block=256 wave=32 args=p,p,p,u,u,u,u,u,u,u defines=FGU_FINE=1,FGU_PACK=1 #include "wg_platform.hlsli" #include "fg_full.hlsli" +#include "fg_pack.hlsli" #ifndef FGU_FINE #define FGU_FINE 0 #endif +#ifndef FGU_PACK +#define FGU_PACK 0 +#endif WG_ARGS_BEGIN #if FGU_FINE @@ -37,7 +46,12 @@ WG_KERNEL(fg_out_push_fine) if (!(fgf_ld1h(fine, idx) > 0.0f)) return; const int qy = idx / Wo, qx = idx - qy * Wo; const float4 up = fgf_up(filled1, w1, h1, qx, qy); +#if FGU_PACK + const uint2 h = uint2(fg_pack_h2(up.x, up.y), fg_pack_h2(up.z, 1.0f)); + wg_st32(outp, (uint)(qy + out_y) * (uint)out_pitch + (uint)qx * 4u, fgx_pack_pixel(h, (uint)out_x)); +#else fgf_st4h(outp, (qy + out_y) * out_pitch + qx + out_x, float4(up.xyz, 1.0f)); +#endif } #else WG_KERNEL(fg_out_push) diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index 49d6b00c..2a5fc875 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -40,7 +40,8 @@ enum Kernel : uint32_t { kMConv2Narrow, kMConv1Late, kMPairBFirst, kMPairBSecond, kMPairD4First, kMPairD4Second, kMPairD3Narrow, kMPairD2Narrow, kDown2Srv, kDown4Srv, kMvecSrv, kIntermTiled, kPackPairs, kPullTiled, kPushTail, kDown2HudTile, - kMConv2Mid, kN2h3b1u, kNet2MergePixels, + kMConv2Mid, kN2h3b1u, kNet2MergePixels, kOutPullPack, kOutPushFinePack, + kLiteBlendPack, kKernelCount, }; constexpr uint32_t kFirstFull = kFullBlend; @@ -106,6 +107,7 @@ const char* const kKernelNames[kKernelCount] = { "fg_lite_downsample2_srv", "fg_lite_downsample4_srv", "fg_lite_mvec_srv", "fg_lite_interm_tiled", "fg_exec_pack_pairs", "fg_lite_p2c_pull_tiled", "fg_lite_p2c_push_tail", "fg_lite_downsample2_srv_hud_tile", "fg_mconv2_mid", "fg_net2_mconv_h3b1u", "fg_net2_merge_pixels", + "fg_out_pull_pack", "fg_out_push_fine_pack", "fg_lite_blend_pack", }; constexpr uint32_t kRootConstants = 59; // 2 runtime constants + up to 57 argument DWORDs @@ -573,6 +575,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { uint32_t cap_colour = 0, cap_hud = 0, cap_ui4 = 0, cap_ui1 = 0, cap_depth = 0, cap_motion = 0; uint32_t out_off = 0, out_stride = 0; // generated image (float16 x 4), stride in texels uint32_t pack_off = 0, pack_pitch = 0; // packed slot rows + uint32_t fuse_pack = 0; // slot format code (1..3) the output pyramid packs directly; 0: fg_exec_pack runs FgNet1Plan n1plan; FgArenaBinding n1arena; uint32_t n1_cells = 0, n1_out = 0, n1_pair_scratch = 0; @@ -1611,12 +1614,15 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { fr.Args(rg); uint32_t a[30]; uint32_t n = 0; + // fuse_pack: the slot's packed rows (pack_pitch bytes, format code in the ox argument) + const bool packed = fuse_pack != 0; const uint32_t h[20] = {R(kRoleCp), R(kRoleCc), R(kRoleMA), R(kRoleMB), R(kRoleW), R(kRoleUp), - R(kRoleUc), R(kRoleLp), R(kRoleLc), out_off, out_stride, 0, 0, g.wo, g.ho, + R(kRoleUc), R(kRoleLp), R(kRoleLc), packed ? pack_off : out_off, + packed ? pack_pitch : out_stride, packed ? fuse_pack : 0u, 0, g.wo, g.ho, g.w1, g.h1, fb(op.t), op.flag1 ? 1u : 0u, op.flag2 ? 1u : 0u}; for (uint32_t x : h) a[n++] = x; for (uint32_t x : rg) a[n++] = x; - Dispatch(r, kLiteBlend, groups_for(static_cast(g.wo) * g.ho), a, n); + Dispatch(r, packed ? kLiteBlendPack : kLiteBlend, groups_for(static_cast(g.wo) * g.ho), a, n); return true; } case FgOp::FullBlend: @@ -1852,9 +1858,12 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { const uint32_t tx = cdiv(g.wo, 16), ty = cdiv(g.ho, 16); const volatile float kf = static_cast(g.k); const float rk = 1.0f / kf; - D(r, kOutPull, tx * ty, - {x0, x1, xw, nb_out.off, sig, out_off, fine, lv[1], lv[2], lv[3], lv[4], g.wo, g.ho, g.W2, g.H2, g.k, tx, - out_stride, 0u, 0u, fb(rk)}); + // fuse_pack: the pull and push-fine kernels write the slot's packed rows (pack_off, pack_pitch bytes, format + // code in the out_x argument) instead of the float16 image + const bool packed = fuse_pack != 0; + D(r, packed ? kOutPullPack : kOutPull, tx * ty, + {x0, x1, xw, nb_out.off, sig, packed ? pack_off : out_off, fine, lv[1], lv[2], lv[3], lv[4], g.wo, g.ho, + g.W2, g.H2, g.k, tx, packed ? pack_pitch : out_stride, packed ? fuse_pack : 0u, 0u, fb(rk)}); const uint32_t lc = g.out_coarsest; if (lc == 8) { uint32_t w4, h4; @@ -1871,8 +1880,9 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } uint32_t w1o, h1o; FgExecOutLevelSize(g, 1, &w1o, &h1o); - D(r, kOutPushFine, groups_for(static_cast(g.wo) * g.ho), - {fine, lv[1], out_off, g.wo, g.ho, w1o, h1o, out_stride, 0u, 0u}); + D(r, packed ? kOutPushFinePack : kOutPushFine, groups_for(static_cast(g.wo) * g.ho), + {fine, lv[1], packed ? pack_off : out_off, g.wo, g.ho, w1o, h1o, packed ? pack_pitch : out_stride, + packed ? fuse_pack : 0u, 0u}); } // ---- inputs ---------------------------------------------------------------------------------------------- @@ -1999,7 +2009,32 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { Transition(r, dst, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); } + // The slot format code the last output kernel of this generated index (the Full path's output pyramid or the light + // path's blend) can pack directly, else 0: that kernel is the last writer of the output image (no menu output, + // prefill or copy after it), outputs are not kept for readback, the slot is an 8 / 10-bit UNORM image of the output + // size and the packing kernels are present. + uint32_t PackFusion(const std::vector& ops, uint32_t slot) const { + if (desc.keep_outputs || !target) return 0; + bool pyramid = false, blend = false; + for (const FgExecOp& op : ops) { + if (op.op == FgOp::OutPyramid) pyramid = true; + else if (op.op == FgOp::LiteBlend) blend = true; + else if (op.op == FgOp::MenuOutput || op.op == FgOp::Prefill || op.op == FgOp::FinalCopy) return 0; + } + if (pyramid ? !(pso[kOutPullPack] && pso[kOutPushFinePack]) : !(blend && pso[kLiteBlendPack])) return 0; + ID3D12Resource* res = target->SlotResource(slot); + if (!res) return 0; + const D3D12_RESOURCE_DESC d = res->GetDesc(); + uint32_t bpp = 0; + const int code_ = pack_code(d.Format, &bpp); + if (d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || d.Width != g.wo || d.Height != g.ho || code_ <= 0) + return 0; + return static_cast(code_); + } + FgExecResult WriteSlot(Rec& r, uint32_t slot, char kind, uint64_t token, uint32_t index) { + const uint32_t fused = fuse_pack; // consumed here, so a refused recording cannot leak it into the next slot + fuse_pack = 0; if (!target) return Fail(FgExecRefusal::SlotTargetMissing, "no presenter bound to the executor"); ID3D12Resource* res = target->SlotResource(slot); if (!res) return Fail(FgExecRefusal::SlotMissing, "slot " + std::to_string(slot) + " has no texture"); @@ -2015,8 +2050,10 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { if (code_ != 0) { const bool pairs = pso[kPackPairs] != nullptr; const uint32_t columns = pairs ? cdiv(g.wo, 2) : g.wo; - D(r, pairs ? kPackPairs : kPack, groups_for(static_cast(columns) * g.ho), - {out_off, out_stride, pack_off, pack_pitch, g.wo, g.ho, static_cast(code_)}); + // the output pyramid already wrote the packed rows + if (fused != static_cast(code_)) + D(r, pairs ? kPackPairs : kPack, groups_for(static_cast(columns) * g.ho), + {out_off, out_stride, pack_off, pack_pitch, g.wo, g.ho, static_cast(code_)}); src_off = pack_off; pitch = pack_pitch; } @@ -2463,6 +2500,7 @@ FgExecResult FgD3d12Executor::RecordGeneratedIndex(const FgIndexDispatchDesc& d, m.ArmDumpOnGenerated(d.frame_token); std::vector ops; m.host.IndexOps(d.t, m.frame.hud, m.frame.ui4, false, &ops); + m.fuse_pack = m.PackFusion(ops, d.slot.slot); const bool capture = !m.frame.colour_captured && std::any_of(ops.begin(), ops.end(), [](const FgExecOp& op) { return op.op == FgOp::FinalCopy || op.op == FgOp::Prefill; }); diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index 6681066f..43cef85d 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -1674,6 +1674,11 @@ void TestInputSrvPaths(Gpu& gpu, const std::string& dxil, const std::string& ref DXGI_FORMAT_B8G8R8A8_UNORM, FgPreset::A, 95}, {DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R10G10B10A2_UNORM, FgPreset::C, 97}, + // the Full path packs the slot rows in the output pyramid (RGBA8 and RGB10A2 slots, odd widths) + {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R16G16_FLOAT, + DXGI_FORMAT_R8G8B8A8_UNORM, FgPreset::A, 99}, + {DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R10G10B10A2_UNORM, FgPreset::B, 101}, {DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, FgPreset::C, 1441}, {DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R16G16_FLOAT, diff --git a/clean/fg/tests/test_fg_full_stages_gpu_plan.py b/clean/fg/tests/test_fg_full_stages_gpu_plan.py index c368b8df..13c9d50c 100644 --- a/clean/fg/tests/test_fg_full_stages_gpu_plan.py +++ b/clean/fg/tests/test_fg_full_stages_gpu_plan.py @@ -23,7 +23,9 @@ def declarations(): m = re.match(r"^//\s*@wg-kernel\s+(\S+)(.*)$", line) if m: kv = dict(t.split("=", 1) for t in m.group(2).split()) - out[m.group(1)] = kv + # co=- : D3D12-only variants (the executor's packed-slot output kernels), not stage-check kernels + if kv.get("co") != "-": + out[m.group(1)] = kv return out From 426a43499765267a5c71f9c4f08cac462b920815 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:16:49 -0500 Subject: [PATCH 05/15] Frame generation (D3D12): the Full blend writes net2's merged input itself, dropping the merge dispatch (Preset A 2x -10 us; exact) fg_full_blend_merge stores the ten-channel net2 input element (the two block means, the hole flag and the float16 of t) next to the three mean images it already writes, with the bits fg_net2_merge_pixels builds from them, so the executor skips that dispatch and its barrier in both net2 paths. The Full blend op now carries t. Used only when the kernel is present and outputs are not kept for readback. --- clean/dx12/kernels/fg_full_blend.hlsl | 24 ++++++++++++++++++++++++ clean/fg/runtime/fg_d3d12_executor.cpp | 24 ++++++++++++++++++------ clean/fg/runtime/fg_exec_plan.cpp | 1 + 3 files changed, 43 insertions(+), 6 deletions(-) diff --git a/clean/dx12/kernels/fg_full_blend.hlsl b/clean/dx12/kernels/fg_full_blend.hlsl index dc415a5c..88ab13c9 100644 --- a/clean/dx12/kernels/fg_full_blend.hlsl +++ b/clean/dx12/kernels/fg_full_blend.hlsl @@ -8,15 +8,26 @@ // Ib, Ic (4 x float16, the means), Ia (float16, 1 if any hole). Only cross-wave sums use shared memory. // Inputs: Cp, Cc, Up, Uc (frame, 4 x float16), W (scatter grid W1 x H1, 2 x float16), Qc (Wd x Hd, 2 x float16), MA, MB // (scatter grid, 64-bit words). ui != 0: preset B (UI recomposition with Up / Uc), else preset A (Up / Uc not read). +// fg_full_blend_merge (FGB_MERGE) also writes net2's merged input x [W2 x H2][10] float16 = Ib [4], Ic [4], Ia, then the +// scalar f (bits fbits) rounded to float16, as fg_net2_merge_pixels builds it from the three means (the same bits), +// so that dispatch is not needed (extra arguments nx = x's offset, fbits). // // @wg-kernel fg_full_blend co=fg_full.co block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u +// @wg-kernel fg_full_blend_merge co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,u defines=FGB_MERGE=1 #include "wg_platform.hlsli" #include "fg_full.hlsli" +#ifndef FGB_MERGE +#define FGB_MERGE 0 +#endif + WG_ARGS_BEGIN uint cp, cc, wimg, qc, ma, mb, up, uc; // inputs (arena byte offsets) uint x0, x1, xw, ib, ic, ia; // outputs int Wo, Ho, W1, H1, Wd, Hd, k, tiles_x, ui; +#if FGB_MERGE + uint nx, fbits; +#endif WG_ARGS_END groupshared float fgb_s[9 * 8]; @@ -138,8 +149,21 @@ WG_KERNEL(fg_full_blend) const int bx = origin.x + (int)fgf_mx(leader_lane); const int by = origin.y + (int)fgf_my(leader_lane); const int e = (by >> shift) * ((tiles_x * 16) >> shift) + (bx >> shift); +#if FGB_MERGE + const float4 mb4 = fgb_mean(float4(v[0], v[1], v[2], v[3]), shift); + const float4 mc4 = fgb_mean(float4(v[4], v[5], v[6], v[7]), shift); + const uint flag = v[8] > 0.0f ? 0x3c00u : 0u; + const uint2 pb = uint2(fg_pack_h2(mb4.x, mb4.y), fg_pack_h2(mb4.z, mb4.w)); + const uint2 pc = uint2(fg_pack_h2(mc4.x, mc4.y), fg_pack_h2(mc4.z, mc4.w)); + wg_st64(ib, (uint)e * 8u, pb); + wg_st64(ic, (uint)e * 8u, pc); + wg_st16(ia, (uint)e * 2u, flag); + wg_st128(nx, (uint)e * 20u, uint4(pb.x, pb.y, pc.x, pc.y)); + wg_st32(nx, (uint)e * 20u + 16u, flag | (wg_f2h(asfloat(fbits)) << 16)); +#else fgf_st4h(ib, e, fgb_mean(float4(v[0], v[1], v[2], v[3]), shift)); fgf_st4h(ic, e, fgb_mean(float4(v[4], v[5], v[6], v[7]), shift)); wg_st16(ia, (uint)e * 2u, v[8] > 0.0f ? 0x3c00u : 0u); +#endif } } diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index 2a5fc875..1f4205d3 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -41,7 +41,7 @@ enum Kernel : uint32_t { kMPairD3Narrow, kMPairD2Narrow, kDown2Srv, kDown4Srv, kMvecSrv, kIntermTiled, kPackPairs, kPullTiled, kPushTail, kDown2HudTile, kMConv2Mid, kN2h3b1u, kNet2MergePixels, kOutPullPack, kOutPushFinePack, - kLiteBlendPack, + kLiteBlendPack, kFullBlendMerge, kKernelCount, }; constexpr uint32_t kFirstFull = kFullBlend; @@ -62,6 +62,7 @@ constexpr uint32_t kSmallGrid = 16384; // conv grids of at most this many pixel constexpr uint32_t kMTile = 16; bool KernelNeeded(uint32_t k, bool full, FgNet2Path path) { + if (k == kOutPullPack || k == kOutPushFinePack || k == kFullBlendMerge) return full; // Full path only if (k < kFirstFull || k >= kFirstOptional) return true; if (!full) return false; if (k == kNet2Conv || k == kNet2Up2 || k == kNet2Warp) return path == FgNet2Path::Exact; @@ -108,6 +109,7 @@ const char* const kKernelNames[kKernelCount] = { "fg_lite_p2c_pull_tiled", "fg_lite_p2c_push_tail", "fg_lite_downsample2_srv_hud_tile", "fg_mconv2_mid", "fg_net2_mconv_h3b1u", "fg_net2_merge_pixels", "fg_out_pull_pack", "fg_out_push_fine_pack", "fg_lite_blend_pack", + "fg_full_blend_merge", }; constexpr uint32_t kRootConstants = 59; // 2 runtime constants + up to 57 argument DWORDs @@ -575,6 +577,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { uint32_t cap_colour = 0, cap_hud = 0, cap_ui4 = 0, cap_ui1 = 0, cap_depth = 0, cap_motion = 0; uint32_t out_off = 0, out_stride = 0; // generated image (float16 x 4), stride in texels uint32_t pack_off = 0, pack_pitch = 0; // packed slot rows + bool net2_input_merged = false; // the Full blend wrote net2's merged input: the next merge is skipped uint32_t fuse_pack = 0; // slot format code (1..3) the output pyramid packs directly; 0: fg_exec_pack runs FgNet1Plan n1plan; FgArenaBinding n1arena; @@ -1625,12 +1628,17 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { Dispatch(r, packed ? kLiteBlendPack : kLiteBlend, groups_for(static_cast(g.wo) * g.ho), a, n); return true; } - case FgOp::FullBlend: - D(r, kFullBlend, (g.Wp / 16) * (g.Hp / 16), - {R(kRoleCp), R(kRoleCc), R(kRoleW), R(kRoleQc), R(kRoleMA), R(kRoleMB), op.ui ? R(kRoleUp) : 0u, - op.ui ? R(kRoleUc) : 0u, x0, x1, xw, ib, ic, ia, g.wo, g.ho, g.w1, g.h1, g.wd, g.hd, g.k, - g.Wp / 16, op.ui ? 1u : 0u}); + case FgOp::FullBlend: { + // the merged variant also builds net2's input (the next op), so the merge dispatch is dropped + const bool merged = pso[kFullBlendMerge] != nullptr && !desc.keep_outputs; + const uint32_t a[25] = {R(kRoleCp), R(kRoleCc), R(kRoleW), R(kRoleQc), R(kRoleMA), R(kRoleMB), + op.ui ? R(kRoleUp) : 0u, op.ui ? R(kRoleUc) : 0u, x0, x1, xw, ib, ic, ia, + g.wo, g.ho, g.w1, g.h1, g.wd, g.hd, g.k, g.Wp / 16, op.ui ? 1u : 0u, + nb_x.off, fb(op.t)}; + Dispatch(r, merged ? kFullBlendMerge : kFullBlend, (g.Wp / 16) * (g.Hp / 16), a, merged ? 25u : 23u); + net2_input_merged = merged; return true; + } case FgOp::Net2: if (fast()) RecordNet2Fast(r, op.t, false); @@ -1683,6 +1691,10 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } void MergeNet2Inputs(Rec& r, uint32_t npx, float f) { + if (net2_input_merged) { + net2_input_merged = false; + return; + } if (pso[kNet2MergePixels]) { D(r, kNet2MergePixels, groups_for(npx), {ib, ic, ia, nb_x.off, npx, fb(f)}); } else { diff --git a/clean/fg/runtime/fg_exec_plan.cpp b/clean/fg/runtime/fg_exec_plan.cpp index 310943d8..f2f34eb3 100644 --- a/clean/fg/runtime/fg_exec_plan.cpp +++ b/clean/fg/runtime/fg_exec_plan.cpp @@ -383,6 +383,7 @@ void FgExecHost::IndexOps(float t, bool hudless_now, bool ui4_now, bool out_subr FgExecOp b; b.op = FgOp::FullBlend; b.ui = f.ui_recomp; + b.t = t; ops->push_back(b); FgExecOp n; n.op = FgOp::Net2; From ff06d00e4ebbcc2d4de6d3c6ff67d34633df3b40 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:48:51 -0500 Subject: [PATCH 06/15] Frame generation (D3D12): Full blend converts NaN lanes as before; DirectComposition entry points load at run time fg_full_blend / fg_full_blend_merge: the driver's packed float16 conversion does not quiet a NaN the way fg_f2h does, so a lane holding a NaN now converts through fg_pack_h2 (a rare, branch-guarded path); the Full-path input-SRV cases (131-wide frames) match the 86105a8 kernels bit for bit again. Preset A 2x costs about +20 us against the unfixed kernel. Presenter: DCompositionGetFrameId / GetStatistics / GetTargetStatistics / CreateSurfaceHandle (bound by ordinal through dcomp.lib, which fails to load the module on Windows Server 2022), CreateDevice3 and CreatePresentationFactory are resolved with GetProcAddress on first use; a missing export is an ordinary failure. dcomp.lib is no longer linked. --- clean/dx12/kernels/fg_full_blend.hlsl | 7 +- clean/fg/presenter/CMakeLists.txt | 2 +- clean/fg/presenter/fg_presenter_factory.cpp | 2 +- clean/fg/presenter/fg_win_common.cpp | 72 +++++++++++++++++++- clean/fg/presenter/fg_win_common.h | 17 +++++ clean/fg/presenter/fg_win_comp_presenter.cpp | 10 +-- clean/fg/proxy/CMakeLists.txt | 2 +- clean/fg/runtime/CMakeLists.txt | 2 +- 8 files changed, 102 insertions(+), 12 deletions(-) diff --git a/clean/dx12/kernels/fg_full_blend.hlsl b/clean/dx12/kernels/fg_full_blend.hlsl index 88ab13c9..e88f6bbb 100644 --- a/clean/dx12/kernels/fg_full_blend.hlsl +++ b/clean/dx12/kernels/fg_full_blend.hlsl @@ -104,7 +104,12 @@ WG_KERNEL(fg_full_blend) { v8f pv; [unroll] for (uint c = 0; c < 8u; ++c) pv.v[c] = fgf_opq(v[c]); - const uint4 h = wg_to_f16_ags(pv); + uint4 h = wg_to_f16_ags(pv); + // The driver's packed conversion does not quiet a NaN as fg_f2h does: a lane holding one converts the old way. + uint mag = 0u; + [unroll] for (uint c = 0; c < 8u; ++c) mag = max(mag, asuint(v[c]) & 0x7fffffffu); + [branch] if (mag > 0x7f800000u) + h = uint4(fg_pack_h2(v[0], v[1]), fg_pack_h2(v[2], v[3]), fg_pack_h2(v[4], v[5]), fg_pack_h2(v[6], v[7])); if (in_bounds) { const uint pi8 = (uint)(py * Wo + px) * 8u; wg_st64(x0, pi8, h.xy); diff --git a/clean/fg/presenter/CMakeLists.txt b/clean/fg/presenter/CMakeLists.txt index 1bf4a4be..18b9a215 100644 --- a/clean/fg/presenter/CMakeLists.txt +++ b/clean/fg/presenter/CMakeLists.txt @@ -34,7 +34,7 @@ if(WIN32) ${CMAKE_CURRENT_LIST_DIR}/fg_dxgi_presenter.cpp ${CMAKE_CURRENT_LIST_DIR}/fg_presenter_factory.cpp) target_link_libraries(wg_fg_win_presenter PUBLIC wg_fg_presenter - d3d11.lib d3d12.lib dxgi.lib dcomp.lib gdi32.lib user32.lib mincore.lib) + d3d11.lib d3d12.lib dxgi.lib gdi32.lib user32.lib mincore.lib) target_compile_definitions(wg_fg_win_presenter PUBLIC NOMINMAX WIN32_LEAN_AND_MEAN) add_executable(test_fg_win_presenters ${CMAKE_CURRENT_LIST_DIR}/tests/test_fg_win_presenters.cpp) diff --git a/clean/fg/presenter/fg_presenter_factory.cpp b/clean/fg/presenter/fg_presenter_factory.cpp index 97cd13f8..2757374a 100644 --- a/clean/fg/presenter/fg_presenter_factory.cpp +++ b/clean/fg/presenter/fg_presenter_factory.cpp @@ -94,7 +94,7 @@ FgWinResult FgProbePresenterCapabilities(ID3D12Device* device, FgPresenterCapabi if (FAILED(hr)) return FgWinFail(FgStatus::Unsupported, FgWinRefusal::D3D11DeviceFailed, hr); caps->presentation_probed = true; ComPtr pf; - hr = CreatePresentationFactory(dev.Get(), IID_PPV_ARGS(&pf)); + hr = FgDCompCreatePresentationFactory(dev.Get(), IID_PPV_ARGS(&pf)); if (SUCCEEDED(hr)) { caps->presentation_supported = pf->IsPresentationSupported() != 0; caps->independent_flip_supported = pf->IsPresentationSupportedWithIndependentFlip() != 0; diff --git a/clean/fg/presenter/fg_win_common.cpp b/clean/fg/presenter/fg_win_common.cpp index 57d29dea..5f8afb30 100644 --- a/clean/fg/presenter/fg_win_common.cpp +++ b/clean/fg/presenter/fg_win_common.cpp @@ -77,14 +77,82 @@ FgTicks FgClockMap::FromQpc(std::int64_t qpc) const { return it0_ + secs * 10000000 + (rem * 10000000) / freq_; } +namespace { + +struct FgDCompApi { + decltype(&::DCompositionGetFrameId) get_frame_id = nullptr; + decltype(&::DCompositionGetStatistics) get_statistics = nullptr; + decltype(&::DCompositionGetTargetStatistics) get_target_statistics = nullptr; + decltype(&::DCompositionCreateSurfaceHandle) create_surface_handle = nullptr; + decltype(&::DCompositionCreateDevice3) create_device3 = nullptr; + decltype(&::CreatePresentationFactory) create_presentation_factory = nullptr; + + FgDCompApi() { + const HMODULE m = LoadLibraryExW(L"dcomp.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!m) return; + Resolve(m, "DCompositionGetFrameId", &get_frame_id); + Resolve(m, "DCompositionGetStatistics", &get_statistics); + Resolve(m, "DCompositionGetTargetStatistics", &get_target_statistics); + Resolve(m, "DCompositionCreateSurfaceHandle", &create_surface_handle); + Resolve(m, "DCompositionCreateDevice3", &create_device3); + Resolve(m, "CreatePresentationFactory", &create_presentation_factory); + } + + template + static void Resolve(HMODULE m, const char* name, F* out) { + *out = reinterpret_cast(reinterpret_cast(GetProcAddress(m, name))); + } +}; + +const FgDCompApi& DCompApi() { + static const FgDCompApi api; // thread-safe first use; dcomp.dll stays loaded for the process + return api; +} + +constexpr HRESULT kDCompAbsent = HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND); + +} // namespace + +HRESULT FgDCompGetFrameId(COMPOSITION_FRAME_ID_TYPE type, COMPOSITION_FRAME_ID* id) { + const auto f = DCompApi().get_frame_id; + return f ? f(type, id) : kDCompAbsent; +} + +HRESULT FgDCompGetStatistics(COMPOSITION_FRAME_ID id, COMPOSITION_FRAME_STATS* stats, UINT target_count, + COMPOSITION_TARGET_ID* targets, UINT* actual_count) { + const auto f = DCompApi().get_statistics; + return f ? f(id, stats, target_count, targets, actual_count) : kDCompAbsent; +} + +HRESULT FgDCompGetTargetStatistics(COMPOSITION_FRAME_ID id, const COMPOSITION_TARGET_ID* target, + COMPOSITION_TARGET_STATS* stats) { + const auto f = DCompApi().get_target_statistics; + return f ? f(id, target, stats) : kDCompAbsent; +} + +HRESULT FgDCompCreateSurfaceHandle(DWORD access, SECURITY_ATTRIBUTES* attributes, HANDLE* handle) { + const auto f = DCompApi().create_surface_handle; + return f ? f(access, attributes, handle) : kDCompAbsent; +} + +HRESULT FgDCompCreatePresentationFactory(IUnknown* d3d_device, REFIID iid, void** factory) { + const auto f = DCompApi().create_presentation_factory; + return f ? f(d3d_device, iid, factory) : kDCompAbsent; +} + +HRESULT FgDCompCreateDevice3(IUnknown* rendering_device, REFIID iid, void** device) { + const auto f = DCompApi().create_device3; + return f ? f(rendering_device, iid, device) : kDCompAbsent; +} + bool FgReadCompositorGrid(const FgClockMap& map, FgTicks period_override, FgRefreshGrid* out) { if (!out) return false; COMPOSITION_FRAME_ID id = 0; - if (FAILED(DCompositionGetFrameId(COMPOSITION_FRAME_ID_COMPLETED, &id))) return false; + if (FAILED(FgDCompGetFrameId(COMPOSITION_FRAME_ID_COMPLETED, &id))) return false; COMPOSITION_FRAME_STATS st = {}; COMPOSITION_TARGET_ID targets[4] = {}; UINT count = 0; - if (FAILED(DCompositionGetStatistics(id, &st, 4, targets, &count)) || st.targetTime == 0) return false; + if (FAILED(FgDCompGetStatistics(id, &st, 4, targets, &count)) || st.targetTime == 0) return false; LARGE_INTEGER f = {}; QueryPerformanceFrequency(&f); if (f.QuadPart <= 0) return false; diff --git a/clean/fg/presenter/fg_win_common.h b/clean/fg/presenter/fg_win_common.h index ade7b50b..d7dbaf04 100644 --- a/clean/fg/presenter/fg_win_common.h +++ b/clean/fg/presenter/fg_win_common.h @@ -14,6 +14,10 @@ #endif #include #include +#include +#include +#include +#include #include #include @@ -99,6 +103,19 @@ class FgClockMap { // reports no frame. bool FgReadCompositorGrid(const FgClockMap& map, FgTicks period_override, FgRefreshGrid* out); +// DirectComposition and presentation entry points, resolved from dcomp.dll when first used (GetProcAddress by name, never a static +// import: dcomp.lib binds the undocumented statistics exports by ordinal, which a Windows without them (Server 2022) +// refuses to load the module for). Each returns HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND) when dcomp.dll or the export +// is absent, so a caller treats it like any other failure. +HRESULT FgDCompGetFrameId(COMPOSITION_FRAME_ID_TYPE type, COMPOSITION_FRAME_ID* id); +HRESULT FgDCompGetStatistics(COMPOSITION_FRAME_ID id, COMPOSITION_FRAME_STATS* stats, UINT target_count, + COMPOSITION_TARGET_ID* targets, UINT* actual_count); +HRESULT FgDCompGetTargetStatistics(COMPOSITION_FRAME_ID id, const COMPOSITION_TARGET_ID* target, + COMPOSITION_TARGET_STATS* stats); +HRESULT FgDCompCreateSurfaceHandle(DWORD access, SECURITY_ATTRIBUTES* attributes, HANDLE* handle); +HRESULT FgDCompCreatePresentationFactory(IUnknown* d3d_device, REFIID iid, void** factory); +HRESULT FgDCompCreateDevice3(IUnknown* rendering_device, REFIID iid, void** device); + // --- High-resolution waitable timer ------------------------------------------------------------------------------ class FgHighResTimer { diff --git a/clean/fg/presenter/fg_win_comp_presenter.cpp b/clean/fg/presenter/fg_win_comp_presenter.cpp index d920f65d..ec9df50b 100644 --- a/clean/fg/presenter/fg_win_comp_presenter.cpp +++ b/clean/fg/presenter/fg_win_comp_presenter.cpp @@ -95,7 +95,7 @@ FgWinResult FgWinCompPresenter::Initialize() { if (FAILED(hr = dev.As(&device11_)) || FAILED(hr = ctx.As(&context11_))) return FgWinFail(FgStatus::Unsupported, FgWinRefusal::D3D11DeviceFailed, hr); - hr = CreatePresentationFactory(device11_.Get(), IID_PPV_ARGS(&factory_)); + hr = FgDCompCreatePresentationFactory(device11_.Get(), IID_PPV_ARGS(&factory_)); if (FAILED(hr)) return FgWinFail(FgStatus::Unsupported, FgWinRefusal::NoPresentationManager, hr); info_.presentation_supported = factory_->IsPresentationSupported() != 0; info_.independent_flip_supported = factory_->IsPresentationSupportedWithIndependentFlip() != 0; @@ -113,7 +113,7 @@ FgWinResult FgWinCompPresenter::Initialize() { FgWinResult r = CreateBuffers(desc_.width, desc_.height); if (!r.Ok()) return r; - hr = DCompositionCreateSurfaceHandle(COMPOSITIONOBJECT_ALL_ACCESS, nullptr, &surface_handle_); + hr = FgDCompCreateSurfaceHandle(COMPOSITIONOBJECT_ALL_ACCESS, nullptr, &surface_handle_); if (FAILED(hr)) return FgWinFail(FgStatus::Refused, FgWinRefusal::CompositionTarget, hr); hr = manager_->CreatePresentationSurface(surface_handle_, &surface_); if (FAILED(hr)) return FgWinFail(FgStatus::Refused, FgWinRefusal::CompositionTarget, hr); @@ -124,7 +124,7 @@ FgWinResult FgWinCompPresenter::Initialize() { return FgWinFail(FgStatus::Refused, FgWinRefusal::CompositionTarget, hr); if (desc_.bind_window) { - if (FAILED(hr = DCompositionCreateDevice3(nullptr, IID_PPV_ARGS(&dcomp_))) || + if (FAILED(hr = FgDCompCreateDevice3(nullptr, IID_PPV_ARGS(&dcomp_))) || FAILED(hr = dcomp_->CreateTargetForHwnd(desc_.hwnd, TRUE, &target_)) || FAILED(hr = dcomp_->CreateVisual(&visual_)) || FAILED(hr = dcomp_->CreateSurfaceFromHandle(surface_handle_, &dcomp_surface_)) || @@ -554,9 +554,9 @@ void FgWinCompPresenter::DrainStatisticsLocked() { COMPOSITION_FRAME_STATS fst = {}; COMPOSITION_TARGET_ID targets[4] = {}; UINT count = 0; - if (FAILED(DCompositionGetStatistics(fid, &fst, 4, targets, &count)) || count == 0) break; + if (FAILED(FgDCompGetStatistics(fid, &fst, 4, targets, &count)) || count == 0) break; COMPOSITION_TARGET_STATS ts = {}; - if (FAILED(DCompositionGetTargetStatistics(fid, &targets[0], &ts)) || ts.presentTime == 0) break; + if (FAILED(FgDCompGetTargetStatistics(fid, &targets[0], &ts)) || ts.presentTime == 0) break; if (pid > last_displayed_platform_) last_displayed_platform_ = pid; if (EngineIdForPlatform(pid, &eid, true)) engine_.OnPresentDisplayed(eid, clock_map_.FromQpc(static_cast(ts.presentTime))); diff --git a/clean/fg/proxy/CMakeLists.txt b/clean/fg/proxy/CMakeLists.txt index 751c3aec..e268a257 100644 --- a/clean/fg/proxy/CMakeLists.txt +++ b/clean/fg/proxy/CMakeLists.txt @@ -123,7 +123,7 @@ if(WIN32) target_include_directories(wg_fg_asi_runtime PUBLIC ${WG_FG_RT_DIR} ${WG_FG_PR_DIR}) # (the win32 headers define WIN32_LEAN_AND_MEAN themselves) target_compile_definitions(wg_fg_asi_runtime PUBLIC NOMINMAX WG_FG_SESSION_WIN=1) - target_link_libraries(wg_fg_asi_runtime PUBLIC wg_fg_win32 d3d11.lib d3d12.lib dxgi.lib dcomp.lib gdi32.lib + target_link_libraries(wg_fg_asi_runtime PUBLIC wg_fg_win32 d3d11.lib d3d12.lib dxgi.lib gdi32.lib user32.lib mincore.lib) wg_fg_flags(wg_fg_asi_runtime) diff --git a/clean/fg/runtime/CMakeLists.txt b/clean/fg/runtime/CMakeLists.txt index f53251d0..ace712cc 100644 --- a/clean/fg/runtime/CMakeLists.txt +++ b/clean/fg/runtime/CMakeLists.txt @@ -57,7 +57,7 @@ if(WIN32) ${WG_FG_PRESENTER_DIR}/fg_dxgi_presenter.cpp ${WG_FG_PRESENTER_DIR}/fg_presenter_factory.cpp) target_link_libraries(wg_fg_session_deps PUBLIC - d3d11.lib d3d12.lib dxgi.lib dcomp.lib gdi32.lib user32.lib mincore.lib) + d3d11.lib d3d12.lib dxgi.lib gdi32.lib user32.lib mincore.lib) target_compile_definitions(wg_fg_session_deps PUBLIC NOMINMAX WIN32_LEAN_AND_MEAN WG_FG_SESSION_WIN=1) list(APPEND WG_FG_SESSION_SOURCES ${WG_FG_RUNTIME_DIR}/fg_session_win.cpp) endif() From d894510358247c32bac2fbe1f6d61af5cae00b03 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:50:46 -0500 Subject: [PATCH 07/15] Frame generation (D3D12): per-launch profile and multi-queue timing, multi-frame batching, hoisted per-index work, split shared queue work (all exact, each with an off switch) Phase 0: WRONGGPU_FG_KPROF=1 / FgD3d12ExecutorDesc::kernel_profile times every launch (kernel, workgroups, ordinal), including net1's raw dispatches; TakeTimings also reports the wall-clock span and the busy time of every queue on one clock. test_fg_d3d12_e2e --bench takes --gen 1..5 (2x..6x, really recorded), --kprof and --batch / --hoist / --dualq 0|1 for paired runs. Phase 1: the per-index images live in scratch banks (one per generated index). RecordGeneratedBatch records layer k of every index back to back, so the barriers sit only between dependent layers (WG_FG_BATCH=0 off; the session batches consecutive generated indices when the executor asks for it). The per-index MA / MB fills and intermediate-time scatters of every index run on a second compute queue beside net1 (WG_FG_HOIST=0 off). The downsample runs beside the motion / p2c chain on the game queue (WG_FG_DUALQ=0 off). The kernels and their arguments are unchanged; only where and when independent work is recorded differs. --- clean/fg/runtime/fg_d3d12_executor.cpp | 734 +++++++++++++++++-- clean/fg/runtime/fg_d3d12_executor.h | 38 + clean/fg/runtime/fg_session.cpp | 67 +- clean/fg/runtime/fg_session.h | 14 + clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 134 +++- clean/fg/runtime/tests/test_fg_session.cpp | 84 +++ 6 files changed, 953 insertions(+), 118 deletions(-) diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index 1f4205d3..b003663d 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include "fg_frame_dump.h" @@ -462,6 +463,12 @@ bool FgNet2SwizzleFast(const std::vector& canonical, const std::vector< namespace { +// One launch of the per-launch profile: the kernel, its workgroups and its ordinal among that kernel's launches of the +// recording. +struct ProfTag { + uint32_t kernel = 0, groups = 0, ordinal = 0; +}; + struct Entry { ComPtr alloc; ComPtr list; @@ -469,13 +476,19 @@ struct Entry { uint32_t desc_base = 0; uint32_t query_base = 0, stage_count = 0; FgExecStage stages[static_cast(FgExecStage::Count)] = {}; + uint32_t prof_base = 0; // first per-launch timestamp of this entry (kernel_profile) + std::vector prof; // one tag per timestamp written }; constexpr uint32_t kTimingQueries = static_cast(FgExecStage::Count) + 1; +constexpr uint32_t kProfQueries = 1024; // per-launch timestamps per recording (one closing timestamp included) struct TimingQueries { ComPtr heap; ComPtr readback; + ComPtr prof_heap; + ComPtr prof_readback; + ID3D12CommandQueue* source = nullptr; // for the clock calibration (owned by the executor) uint64_t hz = 0; }; @@ -505,6 +518,17 @@ struct FrameCtx { uint32_t disable = 0; }; +// A recorded launch kept back so that the layers of several generated indices can be emitted interleaved +// (RecordGeneratedBatch). The arguments are the ones the launch would have been recorded with. +struct Deferred { + uint32_t kernel = 0, groups = 0, n = 0; + bool barrier = true; + FgExecStage stage = FgExecStage::GenPreNet2; + uint32_t args[57] = {}; +}; + +constexpr uint32_t kMaxWrittenSlots = 8; + struct Rec { Entry* e = nullptr; ID3D12GraphicsCommandList* cl = nullptr; @@ -512,8 +536,20 @@ struct Rec { D3D12_RESOURCE_STATES arena = D3D12_RESOURCE_STATE_COMMON; bool dirty = false; // a dispatch or copy wrote since the last UAV barrier bool open = false, direct = false, uses_arena = true; - ID3D12Resource* written_slot = nullptr; - + bool aux = false; // recorded for the second compute queue + ID3D12Resource* written_slots[kMaxWrittenSlots] = {}; + uint32_t written_count = 0; + // Submit: the game queue handoff value this recording waits for (0: the latest), the producer fence value an + // auxiliary recording waits for + uint64_t wait_handoff = 0, wait_producer = 0; + std::vector* defer = nullptr; // set: Dispatch keeps the launch here instead of recording it + FgExecStage defer_stage = FgExecStage::GenPreNet2; + + void NoteSlot(ID3D12Resource* res) { + for (uint32_t i = 0; i < written_count; ++i) + if (written_slots[i] == res) return; + if (written_count < kMaxWrittenSlots) written_slots[written_count++] = res; + } ~Rec() { if (open) cl->Close(); } @@ -555,9 +591,36 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { ComPtr arena; uint64_t arena_bytes = 0; ComPtr menu_rb; - TimingQueries producer_queries, direct_queries; + TimingQueries producer_queries, direct_queries, aux_queries; FgExecTimings timings; bool timing_failed = false; + std::vector> intervals; // every collected recording [start, end] in ms of one clock + struct ProfRow { + uint32_t kernel = 0, ordinal = 0; + uint64_t calls = 0, groups = 0; + double ms = 0.0; + }; + std::vector prof_rows; + std::map, size_t> prof_index; + + // Turbo v2 levers (fg_d3d12_executor.h FgD3d12ExecutorDesc): wanted at construction, active after Configure. + bool want_batch = true, want_hoist = true, want_dualq = true; + bool batch_on = false, hoist_on = false, dualq_on = false; + ComPtr aux_queue; // the second compute queue (hoisted MA / MB work) + ComPtr aux_fence; + uint64_t aux_value = 0, aux_joined = 0; + std::vector aux_entries; + // Scratch banks: the per-index images (MA, MB, W, the generated image and its packed rows, the Full path's + // blend images, net2's tensors and the output pyramid) live in one block that is repeated sc_banks times at + // sc_stride bytes; SelectBank(b) moves every per-index offset to bank b. + uint32_t sc_banks = 1, sc_bank = 0; + uint64_t sc_base = 0, sc_stride = 0; + // The game frame's hoisted per-index work (fills and intermediate-time scatters of every index, recorded on the + // second queue beside net1): valid for this frame token, indices 1..hoist_n and these intermediate times. + bool hoist_valid = false; + uint64_t hoist_token = 0; + uint32_t hoist_n = 0; + float hoist_t[kFgMaxGenerated] = {}; IFgSlotTarget* target = nullptr; uint32_t fence_id = 0; @@ -792,12 +855,47 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return b; } - FgExecResult Layout() { + // Every per-index offset, for SelectBank (zero: not allocated on this path). + template + void ForEachScratchOffset(F&& f) { + uint32_t* single[] = {&role_off[kRoleMA], &role_off[kRoleMB], &role_off[kRoleW], &out_off, &pack_off, &x0, &x1, + &xw, &ib, &ic, &ia, &fine}; + for (uint32_t* p : single) f(*p); + for (uint32_t l = 1; l <= 8; ++l) f(lv[l]); + Net2Buf* bufs[] = {&nb_x, &nb_a1, &nb_a2, &nb_r0, &nb_r4u, &nb_g, &nb_gu, &nb_hA4, &nb_hA1, &nb_hA3, &nb_U4, + &nb_U1, &nb_U3, &nb_y, &nb_b1, &nb_s0, &nb_s4u, &nb_e, &nb_eu, &nb_out}; + for (Net2Buf* b : bufs) f(b->off); + for (int u = 0; u < 4; ++u) { + f(nb_t[u].off); + f(nb_r[u].off); + f(nb_tb[u].off); + f(nb_s[u].off); + } + } + // Moves every per-index offset to scratch bank b (a bank beyond the allocated ones is bank 0). + void SelectBank(uint32_t b) { + if (b >= sc_banks) b = 0; + if (b == sc_bank) return; + const int64_t delta = (static_cast(b) - static_cast(sc_bank)) * static_cast(sc_stride); + ForEachScratchOffset([delta](uint32_t& off) { + if (off) off = static_cast(static_cast(off) + delta); + }); + sc_bank = b; + } + // The bank an index records into: its own when the levers need one per index, else the shared bank 0. + uint32_t BankFor(uint32_t index) const { + return (batch_on || hoist_on) && index >= 1 && index <= sc_banks ? index - 1 : 0; + } + + FgExecResult Layout(uint32_t banks) { bump = 256; // offset 0 is the null pointer + sc_bank = 0; for (uint32_t r = 0; r < kRoleCount; ++r) { + if (r == kRoleMA || r == kRoleMB || r == kRoleW) continue; // per-index: the scratch block below const uint64_t n = FgRoleBytes(g, r); role_off[r] = n ? Alloc(n) : 0; } + role_off[kRoleMA] = role_off[kRoleMB] = role_off[kRoleW] = 0; for (uint32_t l = 1; l <= g.top; ++l) ps_off[l] = Alloc(12ull * g.lw[l] * g.lh[l]); detres_off = Alloc(32); dis_off = detres_off + 16; @@ -809,9 +907,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { cap_depth = Alloc(cap * 4); cap_motion = Alloc(cap * 8); out_stride = static_cast(align(g.wo, 32)); - out_off = Alloc(8ull * out_stride * g.ho, 512); pack_pitch = static_cast(align(4ull * g.wo, 256)); - pack_off = Alloc(static_cast(pack_pitch) * g.ho, 512); // net1: input, weights and scratch regions const FgRefusal pr = FgBuildNet1Plan(g.H0, g.W0, &n1plan); if (pr != FgRefusal::None) return Fail(FgExecRefusal::SizeUnsupported, std::string("net1 plan: ") + FgRefusalName(pr)); @@ -829,6 +925,14 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { const uint64_t d4_bytes = split_d4 ? n1plan.buffers[n1plan.Find("a4")].bytes : 0; n1_pair_scratch = Alloc(std::max(b_bytes, d4_bytes)); } + // The scratch block: everything one generated index writes (and nothing else), repeated once per bank. + bump = align(bump, 4096); + sc_base = bump; + role_off[kRoleMA] = Alloc(FgRoleBytes(g, kRoleMA)); + role_off[kRoleMB] = Alloc(FgRoleBytes(g, kRoleMB)); + role_off[kRoleW] = Alloc(FgRoleBytes(g, kRoleW)); + out_off = Alloc(8ull * out_stride * g.ho, 512); + pack_off = Alloc(static_cast(pack_pitch) * g.ho, 512); if (desc.enable_full) { const uint64_t fr = static_cast(g.wo) * g.ho, n2 = static_cast(g.W2) * g.H2; x0 = Alloc(fr * 8); @@ -872,6 +976,9 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { if (!fast()) nb_eu = N2(1, 48); nb_out = N2(1, 8); } + sc_stride = align(bump - sc_base, 4096); + sc_banks = banks; + bump = sc_base + sc_stride * banks; // the weights region last: net1's weights region, net2's weights, the logistic table weight_base = Alloc(0, 256); bump = weight_base; @@ -960,7 +1067,8 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } if (!heap) { const uint32_t n = std::max(4, desc.allocators); - const uint32_t count = compute_queue ? 2 * n : n; + const uint32_t first_aux = compute_queue ? 2 * n : n; + const uint32_t count = aux_queue ? first_aux + n : first_aux; D3D12_DESCRIPTOR_HEAP_DESC hd = {}; hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; hd.NumDescriptors = count * kTables * kTableSize; @@ -992,11 +1100,13 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } } if (!CreateEntries(entries, n, 0, ProducerQueue()) || - (compute_queue && !CreateEntries(direct_entries, n, n, queue.Get()))) + (compute_queue && !CreateEntries(direct_entries, n, n, queue.Get())) || + (aux_queue && !CreateEntries(aux_entries, n, first_aux, aux_queue.Get()))) return Fail(FgExecRefusal::AllocationFailed, "command allocator / list"); if (desc.timing) { CreateTimingQueries(producer_queries, n, ProducerQueue()); if (compute_queue) CreateTimingQueries(direct_queries, n, queue.Get()); + if (aux_queue) CreateTimingQueries(aux_queries, n, aux_queue.Get()); } } return FgExecResult::Ok; @@ -1015,11 +1125,13 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return false; e.desc_base = (first + i) * kTables * kTableSize; e.query_base = i * kTimingQueries; + e.prof_base = i * kProfQueries; } return true; } void CreateTimingQueries(TimingQueries& q, uint32_t count, ID3D12CommandQueue* source) { + q.source = source; if (FAILED(source->GetTimestampFrequency(&q.hz)) || !q.hz) return; D3D12_QUERY_HEAP_DESC qd = {}; qd.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP; @@ -1027,41 +1139,119 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { if (SUCCEEDED(device->CreateQueryHeap(&qd, IID_PPV_ARGS(&q.heap)))) q.readback = Buffer(qd.Count * sizeof(uint64_t), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + if (desc.kernel_profile) { + qd.Count = count * kProfQueries; + if (SUCCEEDED(device->CreateQueryHeap(&qd, IID_PPV_ARGS(&q.prof_heap)))) + q.prof_readback = Buffer(qd.Count * sizeof(uint64_t), D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + } + } + + TimingQueries& QueriesOf(const Rec& r) { + return r.aux ? aux_queries : r.direct ? direct_queries : producer_queries; } void TimeStage(Rec& r, FgExecStage stage) { - const auto& q = r.direct ? direct_queries : producer_queries; + if (r.defer) return; // the launches are only being kept: EmitDeferred marks the stages + const auto& q = QueriesOf(r); if (!q.readback) return; Entry& e = *r.e; if (e.stage_count && e.stages[e.stage_count - 1] == stage) return; + if (e.stage_count >= static_cast(FgExecStage::Count)) return; r.cl->EndQuery(q.heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.query_base + e.stage_count); e.stages[e.stage_count++] = stage; } + // The per-launch profile: one timestamp before the launch (after its barrier), tagged with the kernel and its + // workgroup count. Launch i takes the time to the next timestamp (the next launch's, or the recording's end). + void ProfMark(Rec& r, uint32_t kernel, uint32_t groups) { + const auto& q = QueriesOf(r); + if (!q.prof_readback) return; + Entry& e = *r.e; + if (e.prof.size() + 1 >= kProfQueries) return; + ProfTag t; + t.kernel = kernel; + t.groups = groups; + for (const ProfTag& x : e.prof) t.ordinal += x.kernel == kernel; + r.cl->EndQuery(q.prof_heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, + e.prof_base + static_cast(e.prof.size())); + e.prof.push_back(t); + } + void ResolveTimings(Rec& r) { const Entry& e = *r.e; - if (!e.stage_count) return; - const auto& q = r.direct ? direct_queries : producer_queries; - r.cl->EndQuery(q.heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.query_base + e.stage_count); - r.cl->ResolveQueryData(q.heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.query_base, e.stage_count + 1, - q.readback.Get(), e.query_base * sizeof(uint64_t)); + const auto& q = QueriesOf(r); + if (e.stage_count && q.readback) { + r.cl->EndQuery(q.heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.query_base + e.stage_count); + r.cl->ResolveQueryData(q.heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.query_base, e.stage_count + 1, + q.readback.Get(), e.query_base * sizeof(uint64_t)); + } + if (!e.prof.empty() && q.prof_readback) { + const uint32_t n = static_cast(e.prof.size()); + r.cl->EndQuery(q.prof_heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.prof_base + n); + r.cl->ResolveQueryData(q.prof_heap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, e.prof_base, n + 1, + q.prof_readback.Get(), e.prof_base * sizeof(uint64_t)); + } + } + + // A GPU timestamp of a queue on the CPU clock, in milliseconds (calibrated at the call). + static double ClockMs(const TimingQueries& q, uint64_t ts, uint64_t cal_gpu, uint64_t cal_cpu, uint64_t qpc_hz) { + const double cpu_s = static_cast(cal_cpu) / static_cast(qpc_hz) + + static_cast(static_cast(ts - cal_gpu)) / static_cast(q.hz); + return cpu_s * 1000.0; } void CollectTimings(Entry& e, const TimingQueries& q) { - if (!e.stage_count || !e.fence) return; - const D3D12_RANGE range = {e.query_base * sizeof(uint64_t), - (e.query_base + e.stage_count + 1) * sizeof(uint64_t)}; - void* p = nullptr; - if (SUCCEEDED(q.readback->Map(0, &range, &p))) { - const auto* ts = static_cast(p) + e.query_base; - for (uint32_t i = 0; i < e.stage_count; ++i) - timings.ms[static_cast(e.stages[i])] += (ts[i + 1] - ts[i]) * 1000.0 / q.hz; - const D3D12_RANGE none = {0, 0}; - q.readback->Unmap(0, &none); - } else { - timing_failed = true; + if (!e.fence) return; + if (e.stage_count && q.readback) { + const D3D12_RANGE range = {e.query_base * sizeof(uint64_t), + (e.query_base + e.stage_count + 1) * sizeof(uint64_t)}; + void* p = nullptr; + if (SUCCEEDED(q.readback->Map(0, &range, &p))) { + const auto* ts = static_cast(p) + e.query_base; + for (uint32_t i = 0; i < e.stage_count; ++i) + timings.ms[static_cast(e.stages[i])] += (ts[i + 1] - ts[i]) * 1000.0 / q.hz; + UINT64 cal_gpu = 0, cal_cpu = 0; + LARGE_INTEGER qpc; + if (q.source && QueryPerformanceFrequency(&qpc) && qpc.QuadPart > 0 && + SUCCEEDED(q.source->GetClockCalibration(&cal_gpu, &cal_cpu))) { + const uint64_t hz = static_cast(qpc.QuadPart); + intervals.emplace_back(ClockMs(q, ts[0], cal_gpu, cal_cpu, hz), + ClockMs(q, ts[e.stage_count], cal_gpu, cal_cpu, hz)); + } + const D3D12_RANGE none = {0, 0}; + q.readback->Unmap(0, &none); + } else { + timing_failed = true; + } } e.stage_count = 0; + if (!e.prof.empty() && q.prof_readback) { + const uint32_t n = static_cast(e.prof.size()); + const D3D12_RANGE range = {e.prof_base * sizeof(uint64_t), (e.prof_base + n + 1) * sizeof(uint64_t)}; + void* p = nullptr; + if (SUCCEEDED(q.prof_readback->Map(0, &range, &p))) { + const auto* ts = static_cast(p) + e.prof_base; + for (uint32_t i = 0; i < n; ++i) { + const auto key = std::make_pair(e.prof[i].kernel, e.prof[i].ordinal); + auto it = prof_index.find(key); + if (it == prof_index.end()) { + it = prof_index.emplace(key, prof_rows.size()).first; + ProfRow row; + row.kernel = key.first; + row.ordinal = key.second; + prof_rows.push_back(row); + } + ProfRow& row = prof_rows[it->second]; + ++row.calls; + row.groups += e.prof[i].groups; + row.ms += (ts[i + 1] - ts[i]) * 1000.0 / q.hz; + } + const D3D12_RANGE none = {0, 0}; + q.prof_readback->Unmap(0, &none); + } + } + e.prof.clear(); } bool WaitFence(ID3D12Fence* f, uint64_t v, uint32_t ms) { @@ -1081,9 +1271,13 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { bool WaitIdle(uint32_t ms) { const ULONGLONG until = GetTickCount64() + ms; + const auto left = [until]() { + const ULONGLONG now = GetTickCount64(); + return now < until ? static_cast(until - now) : 0u; + }; if (!WaitValue(next_value, ms)) return false; - const ULONGLONG now = GetTickCount64(); - return WaitFence(handoff_fence.Get(), handoff_value, now < until ? static_cast(until - now) : 0); + if (!WaitFence(handoff_fence.Get(), handoff_value, left())) return false; + return !aux_fence || WaitFence(aux_fence.Get(), aux_value, left()); } FgExecResult Upload() { @@ -1108,11 +1302,12 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } // ---- recording ------------------------------------------------------------------------------------------- - FgExecResult Begin(Rec* r, bool on_game_queue = false, bool uses_arena = true) { - r->direct = compute_queue && on_game_queue; + FgExecResult Begin(Rec* r, bool on_game_queue = false, bool uses_arena = true, bool aux = false) { + r->aux = aux && aux_queue; + r->direct = !r->aux && compute_queue && on_game_queue; r->uses_arena = uses_arena; - auto& ring = r->direct ? direct_entries : entries; - ID3D12Fence* reuse_fence = r->direct ? handoff_fence.Get() : fence.Get(); + auto& ring = r->aux ? aux_entries : r->direct ? direct_entries : entries; + ID3D12Fence* reuse_fence = r->aux ? aux_fence.Get() : r->direct ? handoff_fence.Get() : fence.Get(); Entry* e = nullptr; const uint64_t done = reuse_fence->GetCompletedValue(); for (Entry& x : ring) @@ -1130,9 +1325,10 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } e = oldest; } - CollectTimings(*e, r->direct ? direct_queries : producer_queries); + CollectTimings(*e, QueriesOf(*r)); e->fence = 0; e->stage_count = 0; + e->prof.clear(); if (FAILED(e->alloc->Reset()) || FAILED(e->list->Reset(e->alloc.Get(), nullptr))) return Fail(FgExecRefusal::CommandFailed, "command list reset"); r->e = e; @@ -1140,6 +1336,9 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { r->open = true; r->table = 0; r->dirty = false; + r->written_count = 0; + r->wait_handoff = r->wait_producer = 0; + r->defer = nullptr; if (!uses_arena) return FgExecResult::Ok; ID3D12DescriptorHeap* heaps[] = {heap.Get()}; r->cl->SetDescriptorHeaps(1, heaps); @@ -1193,8 +1392,23 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } void Dispatch(Rec& r, uint32_t k, uint32_t groups, const uint32_t* args, uint32_t n, bool barrier = true) { + if (r.defer) { + Deferred d; + d.kernel = k; + d.groups = groups; + d.n = std::min(n, kMaxArgs); + d.barrier = barrier; + d.stage = r.defer_stage; + std::memcpy(d.args, args, 4ull * d.n); + r.defer->push_back(d); + return; + } + EmitDispatch(r, k, groups, args, n, barrier); + } + void EmitDispatch(Rec& r, uint32_t k, uint32_t groups, const uint32_t* args, uint32_t n, bool barrier) { ArenaTo(r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); if (barrier) Barrier(r); + if (desc.kernel_profile) ProfMark(r, k, groups); r.cl->SetPipelineState(pso[k].Get()); uint32_t c[kRootConstants] = {}; c[1] = groups; @@ -1222,22 +1436,30 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { ResolveTimings(*r); r->open = false; if (FAILED(r->cl->Close())) return Fail(FgExecRefusal::CommandFailed, "command list close"); - ID3D12CommandQueue* q = r->direct ? queue.Get() : ProducerQueue(); - if (r->direct) { + ID3D12CommandQueue* q = r->aux ? aux_queue.Get() : r->direct ? queue.Get() : ProducerQueue(); + if (r->aux) { + // the second queue starts when the producer queue reached the value it was forked at + if (r->wait_producer && FAILED(q->Wait(fence.Get(), r->wait_producer))) + return QueueFailure("wait for the producer fork"); + } else if (r->direct) { uint64_t dependency = r->uses_arena ? arena_value : 0; - const auto slot = compute_slot_values.find(r->written_slot); - if (slot != compute_slot_values.end()) dependency = std::max(dependency, slot->second); + for (uint32_t i = 0; i < r->written_count; ++i) { + const auto slot = compute_slot_values.find(r->written_slots[i]); + if (slot != compute_slot_values.end()) dependency = std::max(dependency, slot->second); + } if (dependency > fence->GetCompletedValue() && FAILED(q->Wait(fence.Get(), dependency))) return QueueFailure("wait for compute writes"); } - if (!r->direct && !JoinGameQueue()) return QueueFailure("wait for game queue handoff"); + if (!r->direct && !r->aux && !JoinGameQueue(r->wait_handoff)) + return QueueFailure("wait for game queue handoff"); ID3D12CommandList* l[] = {r->cl}; q->ExecuteCommandLists(1, l); uint64_t v = 0; - if (!(r->direct ? SignalHandoff(&v) : SignalProducer(&v))) return QueueFailure("queue signal"); - if (compute_queue && !r->direct) { + if (!(r->aux ? SignalAux(&v) : r->direct ? SignalHandoff(&v) : SignalProducer(&v))) + return QueueFailure("queue signal"); + if (compute_queue && !r->direct && !r->aux) { if (r->uses_arena) arena_value = v; - if (r->written_slot) compute_slot_values[r->written_slot] = v; + for (uint32_t i = 0; i < r->written_count; ++i) compute_slot_values[r->written_slots[i]] = v; } r->e->fence = v; ++counters.submissions; @@ -1257,10 +1479,30 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return true; } - bool JoinGameQueue() { - if (!compute_queue || joined_handoff == handoff_value) return true; - if (FAILED(compute_queue->Wait(handoff_fence.Get(), handoff_value))) return false; - joined_handoff = handoff_value; + // The producer queue waits for the game queue's handoff value (0: the latest signalled one). + bool JoinGameQueue(uint64_t value = 0) { + const uint64_t v = value ? value : handoff_value; + if (!compute_queue || joined_handoff >= v) return true; + if (FAILED(compute_queue->Wait(handoff_fence.Get(), v))) return false; + joined_handoff = v; + return true; + } + + bool SignalAux(uint64_t* value) { + if (FAILED(aux_queue->Signal(aux_fence.Get(), aux_value + 1))) return false; + *value = ++aux_value; + return true; + } + + // The producer timeline waits for everything the second queue was given and publishes a value after it: the + // game frame's last list runs after the hoisted work and the next frame's work sees both finished. + bool JoinAux() { + if (!aux_queue || aux_joined >= aux_value) return true; + if (FAILED(ProducerQueue()->Wait(aux_fence.Get(), aux_value))) return false; + aux_joined = aux_value; + uint64_t v = 0; + if (!SignalProducer(&v)) return false; + if (compute_queue) arena_value = v; return true; } @@ -1346,6 +1588,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return; } } + if (desc.kernel_profile) ProfMark(*cur, kMConv1 + static_cast(kernel), groups_x); cur->cl->SetPipelineState(pso[kMConv1 + static_cast(kernel)].Get()); cur->cl->SetComputeRoot32BitConstants(2, static_cast(c.size()), c.data(), 0); cur->cl->Dispatch(groups_x, 1, 1); @@ -2013,7 +2256,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { Transition(r, src.res, src.state, D3D12_RESOURCE_STATE_COPY_SOURCE); Transition(r, dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); r.cl->CopyResource(dst, src.res); - r.written_slot = dst; + r.NoteSlot(dst); Transition(r, src.res, D3D12_RESOURCE_STATE_COPY_SOURCE, src.state); D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp = {}; fp.Footprint = {linear_copy_format(out.Format), g.wo, g.ho, 1, 0}; @@ -2085,7 +2328,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { src.PlacedFootprint.Footprint.Depth = 1; src.PlacedFootprint.Footprint.RowPitch = pitch; r.cl->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - r.written_slot = res; + r.NoteSlot(res); if (desc.keep_outputs) { PendingRb p; p.rec.kind = kind; @@ -2181,6 +2424,97 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { if (s == FgExecResult::Ok && capture) frame.colour_captured = true; return s; } + + // ---- Turbo v2: scratch banks, interleaved recording, hoisted work ------------------------------------------ + // Moves the per-index offsets to a bank for the scope. + struct BankScope { + Impl& m; + uint32_t prev; + BankScope(Impl& impl, uint32_t b) : m(impl), prev(impl.sc_bank) { m.SelectBank(b); } + ~BankScope() { m.SelectBank(prev); } + }; + + // Records one deferred launch (Dispatch with r.defer set keeps them). + void EmitDeferred(Rec& r, const Deferred& d, bool barrier, bool mark_stage) { + if (mark_stage) TimeStage(r, d.stage); + EmitDispatch(r, d.kernel, d.groups, d.args, d.n, barrier); + } + + // Records the deferred launches of several frames (one list per frame). When every frame runs the same plan + // (same kernels and barrier needs at every position) the frames are interleaved: launch j of every frame back to + // back, the barrier only before the first of them. The frames write disjoint banks and read only the game + // frame's shared state, so the one barrier before launch j of frame 0 (which waits for every earlier launch of + // every frame) is all the dependencies of launch j need. Otherwise the frames are recorded one after the other + // with their own barriers. + void EmitFrames(Rec& r, const std::vector>& lists) { + if (lists.empty()) return; + bool same = true; + for (size_t f = 1; f < lists.size() && same; ++f) { + same = lists[f].size() == lists[0].size(); + for (size_t j = 0; same && j < lists[0].size(); ++j) + same = lists[f][j].kernel == lists[0][j].kernel && lists[f][j].barrier == lists[0][j].barrier; + } + if (!same) { + for (const auto& list : lists) + for (const Deferred& d : list) EmitDeferred(r, d, d.barrier, true); + return; + } + for (size_t j = 0; j < lists[0].size(); ++j) + for (size_t f = 0; f < lists.size(); ++f) EmitDeferred(r, lists[f][j], f == 0 && lists[0][j].barrier, f == 0); + } + + static bool SameBits(float a, float b) { return FgExecFloatBits(a) == FgExecFloatBits(b); } + + // The per-index ops that only need the game frame's p2c results: the MA / MB fills and the intermediate-time + // scatters (the first three ops of an index with history). + static bool IsHoistable(const std::vector& ops) { + return ops.size() >= 3 && ops[0].op == FgOp::Fill64 && ops[0].role == kRoleMA && ops[1].op == FgOp::Fill64 && + ops[1].role == kRoleMB && ops[2].op == FgOp::Interm; + } + + // Whether the shared recording already ran this index's fills and intermediate-time scatters. + bool HoistedFor(const FgIndexDispatchDesc& d, const std::vector& ops) const { + return hoist_valid && hoist_token == d.frame_token && d.index >= 1 && d.index <= hoist_n && + SameBits(d.t, hoist_t[d.index - 1]) && IsHoistable(ops) && BankFor(d.index) == d.index - 1; + } + + // Records the hoisted work of every index of this game frame (fills and intermediate-time scatters, each into its + // index's bank, launch by launch across the indices) into `aux` (not submitted). + bool RecordHoist(Rec& aux, const std::vector& ts) { + std::vector> lists(ts.size()); + for (size_t i = 0; i < ts.size(); ++i) { + std::vector ops; + host.IndexOps(ts[i], frame.hud, frame.ui4, false, &ops); + if (!IsHoistable(ops)) return false; + BankScope bank(*this, BankFor(static_cast(i) + 1)); + aux.defer = &lists[i]; + aux.defer_stage = FgExecStage::GenPreNet2; + for (size_t k = 0; k < 3; ++k) { + if (!RecordOp(aux, ops[k])) { + aux.defer = nullptr; + return false; + } + } + aux.defer = nullptr; + } + EmitFrames(aux, lists); + return true; + } + + // Launches recorded for one index, the shared part of RecordGeneratedIndex and RecordGeneratedBatch. + bool RecordIndexOps(Rec& r, const std::vector& ops, bool skip_hoisted) { + FgExecStage stage = FgExecStage::GenPreNet2; + size_t k = 0; + for (const FgExecOp& op : ops) { + if (skip_hoisted && k++ < 3) continue; + if (op.op == FgOp::Net2) stage = FgExecStage::Net2; + if (op.op == FgOp::OutPyramid) stage = FgExecStage::OutPyramid; + r.defer_stage = stage; + TimeStage(r, stage); // a no-op while the launches are only being kept + if (!RecordOp(r, op)) return false; + } + return true; + } }; // ---- public ------------------------------------------------------------------------------------------------------ @@ -2189,6 +2523,19 @@ FgD3d12Executor::FgD3d12Executor(const FgD3d12ExecutorDesc& desc) : impl_(new Im impl_->desc = desc; char timing[2] = {}; impl_->desc.timing |= GetEnvironmentVariableA("WRONGGPU_FG_TIMING", timing, sizeof(timing)) == 1 && timing[0] == '1'; + char kprof[2] = {}; + impl_->desc.kernel_profile |= + GetEnvironmentVariableA("WRONGGPU_FG_KPROF", kprof, sizeof(kprof)) == 1 && kprof[0] == '1'; + impl_->desc.timing |= impl_->desc.kernel_profile; + // a lever is on unless the description or WG_FG_=0 turns it off + const auto lever = [](int forced, const char* env) { + if (forced >= 0) return forced != 0; + char v[2] = {}; + return !(GetEnvironmentVariableA(env, v, sizeof(v)) == 1 && v[0] == '0'); + }; + impl_->want_batch = lever(desc.batch, "WG_FG_BATCH"); + impl_->want_hoist = lever(desc.hoist, "WG_FG_HOIST"); + impl_->want_dualq = lever(desc.dualq, "WG_FG_DUALQ"); if (desc.weights) { impl_->weights = *desc.weights; impl_->have_weights = true; @@ -2265,6 +2612,15 @@ FgExecResult FgD3d12Executor::Configure(const FgCreateDesc& cd, uint32_t /*histo m.handoff_fence.Reset(); m.handoff_value = m.joined_handoff = m.arena_value = 0; m.compute_slot_values.clear(); + m.aux_queue.Reset(); + m.aux_fence.Reset(); + m.aux_entries.clear(); + m.aux_queries = {}; + m.aux_value = m.aux_joined = 0; + m.hoist_valid = false; + m.intervals.clear(); + m.prof_rows.clear(); + m.prof_index.clear(); char async_compute[2] = {}; const bool async_off = GetEnvironmentVariableA("WRONGGPU_FG_ASYNC_COMPUTE", async_compute, sizeof(async_compute)) == 1 && async_compute[0] == '0'; @@ -2281,19 +2637,45 @@ FgExecResult FgD3d12Executor::Configure(const FgCreateDesc& cd, uint32_t /*histo const FgExecResult p = m.BuildPipelines(); if (p != FgExecResult::Ok) return p; } + // The second compute queue (the hoisted per-index work) is optional: without it the lever is simply off. + if (m.want_hoist) { + D3D12_COMMAND_QUEUE_DESC aux_desc = {}; + aux_desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + aux_desc.NodeMask = queue_desc.NodeMask; + if (FAILED(dev->CreateCommandQueue(&aux_desc, IID_PPV_ARGS(&m.aux_queue))) || + FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m.aux_fence)))) { + m.aux_queue.Reset(); + m.aux_fence.Reset(); + } + } + m.hoist_on = m.want_hoist && m.aux_queue; + m.dualq_on = m.want_dualq && m.compute_queue; // a direct game queue with the compute queue beside it FgExecResult s = m.CreateObjects(); if (s != FgExecResult::Ok) return s; m.create = cd; m.g = g; m.cap_w = std::max(cd.output_width, cd.render_max_width); m.cap_h = std::max(cd.output_height, cd.render_max_height); - s = m.Layout(); - if (s != FgExecResult::Ok) return s; - s = m.FillWeightImage(); + // One scratch bank per generated index when a lever needs them; fewer when the arena would not fit. + uint32_t banks = (m.want_batch || m.hoist_on) ? std::min(std::max(cd.max_generated, 1u), kFgMaxGenerated) : 1u; + for (;;) { + s = m.Layout(banks); + if (s == FgExecResult::Ok) s = m.FillWeightImage(); + if (s == FgExecResult::Ok) { + m.arena = m.Buffer(m.arena_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON); + if (!m.arena) + s = m.Fail(FgExecRefusal::AllocationFailed, + "arena of " + std::to_string(m.arena_bytes) + " bytes"); + } + if (s != FgExecResult::Ok && banks > 1) { + banks = 1; + continue; + } + break; + } if (s != FgExecResult::Ok) return s; - m.arena = m.Buffer(m.arena_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_COMMON); - if (!m.arena) return m.Fail(FgExecRefusal::AllocationFailed, "arena of " + std::to_string(m.arena_bytes) + " bytes"); + m.batch_on = m.want_batch && m.sc_banks >= 2; s = m.Upload(); if (s != FgExecResult::Ok) return s; m.host.Configure(m.desc.settings, g); @@ -2419,6 +2801,21 @@ FgExecResult FgD3d12Executor::RecordSharedGameFrame(const FgSharedDispatchDesc& // Menu detection and the corresponding generated MenuOutput both consume the captured inputs. const bool input_srvs = !m.host.Frame().detect_ran && !m.desc.keep_outputs && m.pso[m.g.d == 4 ? kDown4Srv : kDown2Srv] && m.pso[kMvecSrv]; + const bool fg_gen = d.generates && d.generated_count >= 1; + // Split the game queue's work in two recordings, the motion preparation then the downsample: the producer + // queue's p2c chain starts after the first and runs beside the downsample (it waits for the second before net1's + // input). The inputs the two recordings transition must be different resources. + bool alias = false; + for (int a : {1, 2}) + for (int b : {0, 3, 4}) + if (ins[a] && ins[b] && ins[a]->res == ins[b]->res) alias = true; + // The per-index fills and intermediate-time scatters of every index run on the second queue beside net1. + std::vector hoist_ts; + m.hoist_valid = false; + if (m.hoist_on && fg_gen && m.host.Frame().history && !m.host.Frame().detect_ran && + d.generated_count <= m.sc_banks) + for (uint32_t i = 1; i <= d.generated_count; ++i) hoist_ts.push_back(FgIndexTime(i, d.generated_count)); + Rec inputs; FgExecResult s = m.Begin(&inputs, true); if (s != FgExecResult::Ok) return s; @@ -2430,32 +2827,63 @@ FgExecResult FgD3d12Executor::RecordSharedGameFrame(const FgSharedDispatchDesc& if (!m.RecordOp(inputs, ops[next_op++])) return FgExecResult::Refused; } } - for (int i = 0; i < 5; ++i) - if (transition[i]) - m.Transition(inputs, ins[i]->res, ins[i]->state, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - if (input_srvs) { - if (!m.RecordOp(inputs, ops[next_op++], true) || !m.RecordOp(inputs, ops[next_op++], true)) - return FgExecResult::Refused; + const bool split = m.dualq_on && input_srvs && fg_gen && !alias && next_op + 1 < ops.size() && + ops[next_op + 1].op == FgOp::Mvec; + Rec downsample_list; + uint64_t v = 0, menu_value = 0, h_mvec = 0, h_down = 0; + const auto transitions = [&](Rec& rec, std::initializer_list which, bool to_srv) { + for (int i : which) { + if (!transition[i]) continue; + if (to_srv) + m.Transition(rec, ins[i]->res, ins[i]->state, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + else + m.Transition(rec, ins[i]->res, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, ins[i]->state); + } + }; + if (split) { + transitions(inputs, {1, 2}, true); + if (!m.RecordOp(inputs, ops[next_op + 1], true)) return FgExecResult::Refused; // Mvec + transitions(inputs, {1, 2}, false); + s = m.Submit(&inputs, &h_mvec); + if (s != FgExecResult::Ok) return s; + s = m.Begin(&downsample_list, true); + if (s != FgExecResult::Ok) return s; + m.TimeStage(downsample_list, FgExecStage::SharedPreNet1); + transitions(downsample_list, {0, 3, 4}, true); + if (!m.RecordOp(downsample_list, ops[next_op], true)) return FgExecResult::Refused; // Downsample + transitions(downsample_list, {0, 3, 4}, false); + s = m.Submit(&downsample_list, &h_down); + if (s != FgExecResult::Ok) return s; + next_op += 2; } else { - const uint32_t dst[5] = {m.cap_colour, m.cap_depth, m.cap_motion, m.cap_hud, f.ui1 ? m.cap_ui1 : m.cap_ui4}; - const uint32_t kind[5] = {4, 6, 5, 4, f.ui1 ? 1u : 4u}; - for (int i = 0; i < 5; ++i) - if (ins[i]) m.Capture(inputs, *ins[i], dst[i], kind[i]); - m.SetTable(inputs, 0); - } - for (int i = 0; i < 5; ++i) - if (transition[i]) - m.Transition(inputs, ins[i]->res, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, ins[i]->state); + transitions(inputs, {0, 1, 2, 3, 4}, true); + if (input_srvs) { + if (!m.RecordOp(inputs, ops[next_op++], true) || !m.RecordOp(inputs, ops[next_op++], true)) + return FgExecResult::Refused; + } else { + const uint32_t dst[5] = {m.cap_colour, m.cap_depth, m.cap_motion, m.cap_hud, + f.ui1 ? m.cap_ui1 : m.cap_ui4}; + const uint32_t kind[5] = {4, 6, 5, 4, f.ui1 ? 1u : 4u}; + for (int i = 0; i < 5; ++i) + if (ins[i]) m.Capture(inputs, *ins[i], dst[i], kind[i]); + m.SetTable(inputs, 0); + } + transitions(inputs, {0, 1, 2, 3, 4}, false); + } Rec compute; Rec post_detect; + Rec post_fork; Rec* r = &inputs; - uint64_t v = 0, menu_value = 0; + bool forked = false; if (m.compute_queue) { - s = m.Submit(&inputs, &v); - if (s != FgExecResult::Ok) return s; + if (!split) { + s = m.Submit(&inputs, &v); + if (s != FgExecResult::Ok) return s; + } r = &compute; s = m.Begin(r); if (s != FgExecResult::Ok) return s; + if (split) r->wait_handoff = h_mvec; } else if (!input_srvs) { m.Barrier(inputs); } @@ -2473,9 +2901,38 @@ FgExecResult FgD3d12Executor::RecordSharedGameFrame(const FgSharedDispatchDesc& s = m.Begin(r); if (s != FgExecResult::Ok) return s; } + if (op.op == FgOp::P2cPush && (split || !hoist_ts.empty())) { + // The fork: the producer list ends with the p2c chain (the intermediate-time scatters read its results), + // the second queue runs the per-index fills and scatters, the producer queue goes on with net1. + uint64_t fork = 0; + s = m.Submit(r, &fork); + if (s != FgExecResult::Ok) return s; + if (!hoist_ts.empty()) { + Rec aux; + s = m.Begin(&aux, false, true, true); + if (s != FgExecResult::Ok) return s; + aux.wait_producer = fork; + m.TimeStage(aux, FgExecStage::GenPreNet2); + if (!m.RecordHoist(aux, hoist_ts)) return FgExecResult::Refused; + uint64_t aux_done = 0; + s = m.Submit(&aux, &aux_done); + if (s != FgExecResult::Ok) return s; + m.hoist_valid = true; + m.hoist_token = d.frame_token; + m.hoist_n = d.generated_count; + for (size_t i = 0; i < hoist_ts.size(); ++i) m.hoist_t[i] = hoist_ts[i]; + } + r = &post_fork; + s = m.Begin(r); + if (s != FgExecResult::Ok) return s; + if (split) r->wait_handoff = h_down; + forked = true; + } } + if (split && !forked) r->wait_handoff = h_down; // every split frame has a P2cPush; kept for safety s = m.Submit(r, &v); if (s != FgExecResult::Ok) return s; + if (!m.JoinAux()) return m.QueueFailure("join the second queue"); out->menu.frame_token = d.frame_token; out->menu.detected = false; if (menu_value) { @@ -2527,20 +2984,18 @@ FgExecResult FgD3d12Executor::RecordGeneratedIndex(const FgIndexDispatchDesc& d, if (s != FgExecResult::Ok) return s; m.frame.colour_captured = true; } + // the index's scratch bank (its own when a lever needs one per index) and whether the shared recording already + // ran its fills and intermediate-time scatters + Impl::BankScope bank(m, m.BankFor(d.index)); + const bool hoisted = m.HoistedFor(d, ops); Rec r; FgExecResult s = m.Begin(&r); if (s != FgExecResult::Ok) return s; - FgExecStage stage = FgExecStage::GenPreNet2; if (capture && !m.frame.colour_captured) { - m.TimeStage(r, stage); + m.TimeStage(r, FgExecStage::GenPreNet2); m.CaptureColour(r); } - for (const FgExecOp& op : ops) { - if (op.op == FgOp::Net2) stage = FgExecStage::Net2; - if (op.op == FgOp::OutPyramid) stage = FgExecStage::OutPyramid; - m.TimeStage(r, stage); - if (!m.RecordOp(r, op)) return FgExecResult::Refused; - } + if (!m.RecordIndexOps(r, ops, hoisted)) return FgExecResult::Refused; m.TimeStage(r, FgExecStage::PackCopy); s = m.WriteSlot(r, d.slot.slot, 'g', d.frame_token, d.index); if (s != FgExecResult::Ok) return s; @@ -2552,6 +3007,80 @@ FgExecResult FgD3d12Executor::RecordGeneratedIndex(const FgIndexDispatchDesc& d, return s; } +bool FgD3d12Executor::BatchesGenerated() const { return impl_->batch_on; } +bool FgD3d12Executor::BatchActive() const { return impl_->batch_on; } +bool FgD3d12Executor::HoistActive() const { return impl_->hoist_on; } +bool FgD3d12Executor::DualQueueActive() const { return impl_->dualq_on; } +uint32_t FgD3d12Executor::ScratchBanks() const { return impl_->sc_banks; } + +FgExecResult FgD3d12Executor::RecordGeneratedBatch(const FgIndexDispatchDesc* descs, uint32_t n, FgReadyFence* ready, + uint32_t* done) { + Impl& m = *impl_; + if (done) *done = 0; + if (!descs || !ready || n == 0) return m.Fail(FgExecRefusal::BadArgument, "empty generated batch"); + const auto one_by_one = [&]() { + FgExecResult r = FgExecResult::Ok; + uint32_t i = 0; + for (; i < n && r == FgExecResult::Ok; ++i) r = RecordGeneratedIndex(descs[i], &ready[i]); + if (done) *done = r == FgExecResult::Ok ? i : i - 1; + return r; + }; + // Anything that is not the plain case goes one index at a time (which also reports every refusal). + bool plain = m.batch_on && m.configured && n >= 2 && n <= m.sc_banks && n <= kMaxWrittenSlots && m.target && + m.frame.valid && m.host.InFrame() && m.host.Frame().history; + for (uint32_t k = 0; plain && k < n; ++k) + plain = descs[k].frame_token == m.frame.token && descs[k].preset == m.frame.preset && + descs[k].index == descs[0].index + k && m.BankFor(descs[k].index) == descs[k].index - 1; + std::vector> ops(n); + for (uint32_t k = 0; plain && k < n; ++k) { + m.host.IndexOps(descs[k].t, m.frame.hud, m.frame.ui4, false, &ops[k]); + plain = ops[k].size() == ops[0].size(); + for (size_t j = 0; plain && j < ops[k].size(); ++j) { + plain = ops[k][j].op == ops[0][j].op; + if (ops[k][j].op == FgOp::FinalCopy || ops[k][j].op == FgOp::Prefill || ops[k][j].op == FgOp::MenuOutput) + plain = false; + } + } + if (!plain) return one_by_one(); + + m.FlushDumps(false); + for (uint32_t k = 0; k < n; ++k) m.ArmDumpOnGenerated(descs[k].frame_token); + std::vector fuse(n); + for (uint32_t k = 0; k < n; ++k) fuse[k] = m.PackFusion(ops[k], descs[k].slot.slot); + Rec r; + FgExecResult s = m.Begin(&r); + if (s != FgExecResult::Ok) return s; + // Keep every index's launches, then record them layer by layer across the indices. + std::vector> lists(n); + for (uint32_t k = 0; k < n; ++k) { + Impl::BankScope bank(m, m.BankFor(descs[k].index)); + m.fuse_pack = fuse[k]; + const bool hoisted = m.HoistedFor(descs[k], ops[k]); + r.defer = &lists[k]; + const bool recorded = m.RecordIndexOps(r, ops[k], hoisted); + r.defer = nullptr; + if (!recorded) { + m.fuse_pack = 0; + return FgExecResult::Refused; + } + } + m.fuse_pack = 0; + m.EmitFrames(r, lists); + for (uint32_t k = 0; k < n; ++k) { + Impl::BankScope bank(m, m.BankFor(descs[k].index)); + m.fuse_pack = fuse[k]; + m.TimeStage(r, FgExecStage::PackCopy); + s = m.WriteSlot(r, descs[k].slot.slot, 'g', descs[k].frame_token, descs[k].index); + if (s != FgExecResult::Ok) return s; + } + s = m.Finish(r, &ready[0]); + if (s != FgExecResult::Ok) return s; + for (uint32_t k = 1; k < n; ++k) ready[k] = ready[0]; // one submission: every image is complete at its value + m.counters.indices += n; + if (done) *done = n; + return FgExecResult::Ok; +} + FgExecResult FgD3d12Executor::RecordMenuCopy(const FgCopyDispatchDesc& d, FgReadyFence* ready) { Impl& m = *impl_; if (!m.configured) return m.Fail(FgExecRefusal::NotConfigured, "Configure has not succeeded"); @@ -2754,16 +3283,61 @@ bool FgD3d12Executor::WaitIdle(uint32_t timeout_ms) { bool FgD3d12Executor::TakeTimings(FgExecTimings* out, uint32_t timeout_ms) { Impl& m = *impl_; if (!out || !m.producer_queries.readback || (m.compute_queue && !m.direct_queries.readback) || - !WaitIdle(timeout_ms)) + (m.aux_queue && !m.aux_queries.readback) || !WaitIdle(timeout_ms)) return false; for (Entry& e : m.entries) m.CollectTimings(e, m.producer_queries); for (Entry& e : m.direct_entries) m.CollectTimings(e, m.direct_queries); + for (Entry& e : m.aux_entries) m.CollectTimings(e, m.aux_queries); if (m.timing_failed) return false; *out = m.timings; + // the recordings of every queue on one clock: wall-clock span and the time something ran (overlap counted once) + std::sort(m.intervals.begin(), m.intervals.end()); + out->recordings = static_cast(m.intervals.size()); + out->span_ms = out->busy_ms = 0.0; + if (!m.intervals.empty()) { + double end = m.intervals[0].second, run_start = m.intervals[0].first, last_end = end; + for (const auto& iv : m.intervals) { + if (iv.first > end) { // a gap: close the busy run + out->busy_ms += end - run_start; + run_start = iv.first; + end = iv.second; + } else { + end = std::max(end, iv.second); + } + last_end = std::max(last_end, iv.second); + } + out->busy_ms += end - run_start; + out->span_ms = last_end - m.intervals[0].first; + } + m.intervals.clear(); m.timings = {}; return true; } +bool FgD3d12Executor::TakeKernelProfile(std::vector* out, uint32_t timeout_ms) { + Impl& m = *impl_; + if (!out || !m.desc.kernel_profile || !m.producer_queries.prof_readback || + (m.compute_queue && !m.direct_queries.prof_readback) || (m.aux_queue && !m.aux_queries.prof_readback) || + !WaitIdle(timeout_ms)) + return false; + for (Entry& e : m.entries) m.CollectTimings(e, m.producer_queries); + for (Entry& e : m.direct_entries) m.CollectTimings(e, m.direct_queries); + for (Entry& e : m.aux_entries) m.CollectTimings(e, m.aux_queries); + out->clear(); + for (const Impl::ProfRow& row : m.prof_rows) { + FgExecKernelProfileRow x; + x.name = kKernelNames[row.kernel]; + x.ordinal = row.ordinal; + x.calls = row.calls; + x.groups = row.groups; + x.ms = row.ms; + out->push_back(std::move(x)); + } + m.prof_rows.clear(); + m.prof_index.clear(); + return true; +} + bool FgD3d12Executor::TakeOutputs(std::vector* out) { Impl& m = *impl_; if (!out || !WaitIdle(m.desc.wait_ms * 4)) return false; diff --git a/clean/fg/runtime/fg_d3d12_executor.h b/clean/fg/runtime/fg_d3d12_executor.h index 632bf7ab..8c2ec06f 100644 --- a/clean/fg/runtime/fg_d3d12_executor.h +++ b/clean/fg/runtime/fg_d3d12_executor.h @@ -164,6 +164,17 @@ struct FgD3d12ExecutorDesc { uint32_t allocators = 24; // command allocators in the ring bool keep_outputs = false; // tests: keep a host copy of every image written into a slot bool timing = false; // also enabled by WRONGGPU_FG_TIMING=1 + // Per-launch profile (TakeKernelProfile): one timestamp before every dispatch of every recording. It serialises + // the queue a little, so it is a profile, not a frame time; also enabled by WRONGGPU_FG_KPROF=1 (implies timing). + bool kernel_profile = false; + // Turbo v2 levers (all exact: every one only changes where and when independent work runs). -1 takes the + // environment (default on); 0 / 1 force it (tests, paired A / B runs). + // - batch (WG_FG_BATCH=0 off): RecordGeneratedBatch records layer k of every index back to back, so the barriers + // sit only between dependent layers (needs one scratch bank per index: max_generated banks). + // - hoist (WG_FG_HOIST=0 off): the per-index MA / MB fills and the intermediate-time scatters run on the second + // compute queue while the game frame's net1 runs (needs the second queue and banks). + // - dualq (WG_FG_DUALQ=0 off): the second compute queue; the downsample runs beside the motion / p2c chain. + int batch = -1, hoist = -1, dualq = -1; // Developer frame dumps (off while dump_dir is empty; the ASI sets it only in a developer build): of the game // frames that generate, every dump_every-th one (at most dump_max), the game frame's slot image (game_.ppm) and // each generated slot image (gen__.ppm) are copied to a readback buffer after the slot write, and written as @@ -206,6 +217,22 @@ enum class FgExecStage : uint32_t { struct FgExecTimings { // Sum of GPU timestamp intervals for each stage since the previous collection, in milliseconds. std::array(FgExecStage::Count)> ms = {}; + // The honest multi-queue numbers over the same window (every queue's recordings on one clock): the wall-clock + // span from the first recording's start to the last one's end (idle gaps included), the time at least one + // recording ran (the union of the recordings' intervals: overlap between queues counted once), and the number + // of recordings. The per-stage sums above double count work that two queues overlap. + double span_ms = 0.0, busy_ms = 0.0; + uint32_t recordings = 0; +}; + +// One row of the per-launch profile (kernel_profile), summed over the window since the previous collection. Rows of +// one kernel are told apart by the ordinal of the launch inside its recording. +struct FgExecKernelProfileRow { + std::string name; + uint32_t ordinal = 0; // n-th launch of this kernel in a recording (net1's repeated kernels: its layers in order) + uint64_t calls = 0; // launches summed + uint64_t groups = 0; // workgroups summed over the calls (groups / calls: the launch's workgroup count) + double ms = 0.0; // summed time from this launch's timestamp to the next one's }; class FgD3d12Executor final : public IFgKernelExecutor { @@ -218,6 +245,9 @@ class FgD3d12Executor final : public IFgKernelExecutor { FgExecResult Configure(const FgCreateDesc& desc, uint32_t history_banks) override; FgExecResult RecordSharedGameFrame(const FgSharedDispatchDesc& desc, FgSharedResult* out) override; FgExecResult RecordGeneratedIndex(const FgIndexDispatchDesc& desc, FgReadyFence* ready) override; + FgExecResult RecordGeneratedBatch(const FgIndexDispatchDesc* descs, uint32_t n, FgReadyFence* ready, + uint32_t* done) override; + bool BatchesGenerated() const override; FgExecResult RecordMenuCopy(const FgCopyDispatchDesc& desc, FgReadyFence* ready) override; FgExecResult RecordRealEndpoint(const FgRealDispatchDesc& desc, FgReadyFence* ready) override; uint64_t LastComputeValue() const override; @@ -236,6 +266,14 @@ class FgD3d12Executor final : public IFgKernelExecutor { bool WaitIdle(uint32_t timeout_ms); // Collect and clear the timings through the latest submission. Returns false when profiling is unavailable. bool TakeTimings(FgExecTimings* out, uint32_t timeout_ms); + // kernel_profile: waits idle, collects and clears the per-launch profile (rows in first-seen order). Returns + // false when it is off or unavailable. + bool TakeKernelProfile(std::vector* out, uint32_t timeout_ms); + // The levers that are active after Configure (a lever the device or the arena cannot take stays off). + bool BatchActive() const; + bool HoistActive() const; + bool DualQueueActive() const; + uint32_t ScratchBanks() const; // keep_outputs: waits idle and moves the host copies out (oldest first). bool TakeOutputs(std::vector* out); diff --git a/clean/fg/runtime/fg_session.cpp b/clean/fg/runtime/fg_session.cpp index fdfc095a..9bfdddd1 100644 --- a/clean/fg/runtime/fg_session.cpp +++ b/clean/fg/runtime/fg_session.cpp @@ -417,6 +417,30 @@ FgSessionResult FgSession::RunInterval(const FgFramePacket& packet, const FgInge sub.count = res.count; bool failed = pre_failed; // the shared work already failed: only the game frame is submitted bool stale = false; + // An executor that records several indices more cheaply together (BatchesGenerated) gets the consecutive + // generated indices of the interval in one call; every other path records them one by one as always. The + // checks of each index (plan, history, slot, deadline) still run in order before it is queued; the queue is + // recorded before anything that is not a generated index, before the history advance and at the end. +#if WG_FG_SESSION_MUTANT == 0 + const bool batching = !failed && desc_.executor->BatchesGenerated(); +#else + const bool batching = false; +#endif + FgIndexDispatchDesc pending[kFgMaxGenerated]; + uint32_t pending_n = 0; + const auto flush = [&]() { + if (pending_n == 0) return true; + uint32_t done = 0; + const uint32_t first = pending[0].index; + r.executor = desc_.executor->RecordGeneratedBatch(pending, pending_n, &sub.ready[first - 1], &done); + for (uint32_t k = 0; k < done; ++k) { + sub.produced[first - 1 + k] = true; + ++r.generated_recorded; + ++counters_.index_records; + } + pending_n = 0; + return r.executor == FgExecResult::Ok; + }; for (uint32_t i = 1; i <= n && !failed; ++i) { const FgFrameTarget& tg = plan.targets[i - 1]; const FgPresentSlot& slot = res.slots[i - 1]; @@ -440,12 +464,24 @@ FgSessionResult FgSession::RunInterval(const FgFramePacket& packet, const FgInge } } if (!slot.reserved) { + if (!flush()) { + failed = true; + break; + } ++r.not_reserved; } else if (stale || Now() > tg.deadline) { // too late to be shown: this index and every later one of the interval are cancelled + if (!flush()) { + failed = true; + break; + } stale = true; ++r.stale_cancelled; } else if (copy_output || !generated_history) { + if (!flush()) { + failed = true; + break; + } FgCopyDispatchDesc cd; cd.frame_token = packet.frame_token; cd.interval_id = plan.interval_id; @@ -491,20 +527,24 @@ FgSessionResult FgSession::RunInterval(const FgFramePacket& packet, const FgInge id.current_bank = ingest.current_bank; id.slot = slot; id.target = tg; - r.executor = desc_.executor->RecordGeneratedIndex(id, &sub.ready[i - 1]); + if (batching) { + pending[pending_n++] = id; + } else { + r.executor = desc_.executor->RecordGeneratedIndex(id, &sub.ready[i - 1]); #if WG_FG_SESSION_MUTANT == 4 - if (r.executor == FgExecResult::Refused) { - r.executor = FgExecResult::Ok; - continue; - } + if (r.executor == FgExecResult::Refused) { + r.executor = FgExecResult::Ok; + continue; + } #endif - if (r.executor != FgExecResult::Ok) { - failed = true; - break; + if (r.executor != FgExecResult::Ok) { + failed = true; + break; + } + sub.produced[i - 1] = true; + ++r.generated_recorded; + ++counters_.index_records; } - sub.produced[i - 1] = true; - ++r.generated_recorded; - ++counters_.index_records; } #if WG_FG_SESSION_MUTANT == 5 if (generated_history) { @@ -512,11 +552,16 @@ FgSessionResult FgSession::RunInterval(const FgFramePacket& packet, const FgInge if (last && generated_history) { #endif // the interval's last index is handled: history reads are fenced and the history advance is counted + if (!flush()) { + failed = true; + break; + } history_->MarkRead(desc_.executor->LastComputeValue()); r.history_advanced = true; ++counters_.history_advances; } } + if (pending_n != 0 && !flush()) failed = true; // a break above (plan mismatch) left indices queued if (failed && r.executor == FgExecResult::DeviceLost) { r.error = FgSessionError::ExecutorDeviceLost; return Lose(r); diff --git a/clean/fg/runtime/fg_session.h b/clean/fg/runtime/fg_session.h index a5520515..d1ebdb70 100644 --- a/clean/fg/runtime/fg_session.h +++ b/clean/fg/runtime/fg_session.h @@ -143,6 +143,20 @@ class IFgKernelExecutor { virtual FgExecResult RecordSharedGameFrame(const FgSharedDispatchDesc& desc, FgSharedResult* out) = 0; // Once per generated index i = 1..N (preset A / B full blend, C Lite blend), into desc.slot. virtual FgExecResult RecordGeneratedIndex(const FgIndexDispatchDesc& desc, FgReadyFence* ready) = 0; + // Several consecutive generated indices of one game frame (n >= 1, ascending index, the same frame, preset and + // count) recorded together: an executor may interleave their layers so that the barriers sit only between + // dependent layers. ready[k] is the fence of descs[k]. *done is the number of indices recorded when it returns + // (all of them on Ok); the default records them one by one. A session calls it only when BatchesGenerated(). + virtual FgExecResult RecordGeneratedBatch(const FgIndexDispatchDesc* descs, uint32_t n, FgReadyFence* ready, + uint32_t* done) { + uint32_t i = 0; + FgExecResult r = FgExecResult::Ok; + for (; i < n && r == FgExecResult::Ok; ++i) r = RecordGeneratedIndex(descs[i], &ready[i]); + if (done) *done = r == FgExecResult::Ok ? i : i - 1; + return r; + } + // True when RecordGeneratedBatch records several indices more cheaply than one by one. + virtual bool BatchesGenerated() const { return false; } // An exact copy of the game frame into a generated slot (menu latch, priming). virtual FgExecResult RecordMenuCopy(const FgCopyDispatchDesc& desc, FgReadyFence* ready) = 0; // The game frame of the interval: copied into its reserved slot, or (real-only) its readiness on the queue. diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index 43cef85d..05d6bd67 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -9,6 +9,13 @@ // executor refuses (no presenter is created, nothing falls back) // test_fg_d3d12_e2e --gpu --dxil adds the headless GPU leg (no window): a synthetic game drives the game // test_fg_d3d12_e2e --bench --dxil reports steady-state 1440p GPU stage timings for presets A and C +// [--gen N] N = 1..5 generated images per game frame (2x .. 6x), really recorded (default 1) +// [--preset AC] which presets (default AC) [--timed N] [--warmup N] +// [--kprof] per-launch profile: kernel, workgroups, time per call (serialises the queue a little) +// [--batch 0|1] [--hoist 0|1] [--dualq 0|1] Turbo v2 levers for paired A / B runs (default: on, or the +// environment WG_FG_BATCH / WG_FG_HOIST / WG_FG_DUALQ = 0) +// The report has the per-stage sums and the honest multi-queue numbers: the wall-clock GPU span and the busy +// time per game frame over the timed window (overlap between queues is counted once there, twice in the sums). // --reference-dxil compare direct-SRV output bytes against the captured path built with these kernels // adapter core, the FG session and this executor on the D3D12 device with // the composition back end (unbound surface) and the DXGI back end @@ -1358,9 +1365,9 @@ void TestMotionFormats() { } struct ExecutorSlots final : IFgSlotTarget { - ComPtr textures[2]; + ComPtr textures[8]; // the generated indices' slots and the real endpoint's (benchmarks use up to 6) ID3D12Resource* SlotResource(uint32_t slot) const override { - return slot < 2 ? textures[slot].Get() : nullptr; + return slot < 8 ? textures[slot].Get() : nullptr; } uint32_t RegisterFence(ID3D12Fence*, std::string*) override { return 1; } bool ReserveRealSlot(uint32_t* slot) override { @@ -1795,17 +1802,26 @@ void TestInputSrvPaths(Gpu& gpu, const std::string& dxil, const std::string& ref if (errors >= 0) CHECK(errors == 0); } -bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, FgPreset preset) { - constexpr uint32_t width = 2560, height = 1440, warmup = 8, timed = 30; +struct BenchOptions { + uint32_t gen = 1, warmup = 8, timed = 30; + std::string presets = "AC"; + bool kprof = false; + int batch = -1, hoist = -1, dualq = -1; // -1: the environment (default on) +}; + +bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, FgPreset preset, + const BenchOptions& bo) { + constexpr uint32_t width = 2560, height = 1440; constexpr uint32_t timeout = 30000; + const uint32_t gen_count = bo.gen, warmup = bo.warmup, timed = bo.timed; const char label = preset == FgPreset::A ? 'A' : 'C'; Game game; const DXGI_FORMAT format = DXGI_FORMAT_B8G8R8A8_UNORM; if (!game.Init(&gpu, format, width, height) || !game.Upload(0, false, true)) return false; ExecutorSlots slots; - for (auto& tex : slots.textures) { - tex = game.Tex(format); - if (!tex) return false; + for (uint32_t i = 0; i <= gen_count; ++i) { // slot i - 1 holds index i, slot gen_count the real endpoint + slots.textures[i] = game.Tex(format); + if (!slots.textures[i]) return false; } FgD3d12ExecutorDesc ed; @@ -1813,6 +1829,10 @@ bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, F ed.weights = &weights; ed.enable_full = preset == FgPreset::A; ed.timing = true; + ed.kernel_profile = bo.kprof; + ed.batch = bo.batch; + ed.hoist = bo.hoist; + ed.dualq = bo.dualq; FgD3d12Executor exec(ed); const auto ok = [&](FgExecResult s) { if (s == FgExecResult::Ok) return true; @@ -1823,40 +1843,57 @@ bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, F create.device = gpu.device.Get(); create.queue = gpu.queue.Get(); create.preset = preset; + create.max_generated = gen_count; if (!ok(exec.Configure(create, 3)) || !exec.BindSlotTarget(&slots)) return false; FgFramePacket packet = game.Packet(); FgExecTimings timing; + std::vector profile; for (uint32_t i = 0; i < warmup + timed; ++i) { packet.frame_token = i + 1; FgSharedDispatchDesc shared; shared.frame_token = packet.frame_token; shared.preset = preset; shared.has_previous = i != 0; - shared.generated_count = 1; + shared.generated_count = gen_count; shared.generates = true; shared.packet = &packet; FgSharedResult result; if (!ok(exec.RecordSharedGameFrame(shared, &result))) return false; - FgIndexDispatchDesc gen; - gen.frame_token = packet.frame_token; - gen.index = gen.generated_count = 1; - gen.is_last_index = true; - gen.preset = preset; - gen.t = 0.5f; - gen.slot.slot = 0; - gen.slot.reserved = true; - FgReadyFence ready; - if (!ok(exec.RecordGeneratedIndex(gen, &ready))) return false; + FgIndexDispatchDesc gens[kFgMaxGenerated]; + FgReadyFence ready[kFgMaxGenerated + 1]; + for (uint32_t k = 0; k < gen_count; ++k) { + FgIndexDispatchDesc& gen = gens[k]; + gen.frame_token = packet.frame_token; + gen.index = k + 1; + gen.generated_count = gen_count; + gen.is_last_index = k + 1 == gen_count; + gen.preset = preset; + gen.t = FgIndexTime(k + 1, gen_count); + gen.slot.slot = k; + gen.slot.reserved = true; + } + if (gen_count > 1) { // the executor falls back to one index at a time when batching is off + uint32_t done = 0; + if (!ok(exec.RecordGeneratedBatch(gens, gen_count, ready, &done)) || done != gen_count) return false; + } else if (!ok(exec.RecordGeneratedIndex(gens[0], &ready[0]))) { + return false; + } FgRealDispatchDesc real; real.frame_token = packet.frame_token; - real.slot.slot = 1; + real.slot.slot = gen_count; real.slot.reserved = true; - if (!ok(exec.RecordRealEndpoint(real, &ready))) return false; - if (i + 1 == warmup && !exec.TakeTimings(&timing, timeout)) { - std::printf("bench %c: warmup timestamps unavailable\n", label); - return false; + if (!ok(exec.RecordRealEndpoint(real, &ready[gen_count]))) return false; + if (i + 1 == warmup) { + if (!exec.TakeTimings(&timing, timeout)) { + std::printf("bench %c: warmup timestamps unavailable\n", label); + return false; + } + if (bo.kprof && !exec.TakeKernelProfile(&profile, timeout)) { + std::printf("bench %c: warmup kernel profile unavailable\n", label); + return false; + } } } if (!exec.TakeTimings(&timing, timeout)) { @@ -1866,7 +1903,10 @@ bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, F const char* stages[] = {"capture", "shared_pre_net1", "net1", "shared_post_net1", "gen_pre_net2", "net2", "out_pyramid", "pack_copy", "real_endpoint"}; static_assert(sizeof(stages) / sizeof(*stages) == static_cast(FgExecStage::Count)); - std::printf("bench preset %c 2x %ux%u (%u warmup, %u timed, mean GPU ms)\n", label, width, height, warmup, timed); + std::printf("bench preset %c %ux (gen %u) %ux%u (%u warmup, %u timed, mean GPU ms per game frame)\n", label, + gen_count + 1, gen_count, width, height, warmup, timed); + std::printf(" levers: batch %s, hoist %s, dualq %s, scratch banks %u\n", exec.BatchActive() ? "on" : "off", + exec.HoistActive() ? "on" : "off", exec.DualQueueActive() ? "on" : "off", exec.ScratchBanks()); double shared = 0.0, gen = 0.0; for (size_t i = 0; i < timing.ms.size(); ++i) { const double mean = timing.ms[i] / timed; @@ -1874,18 +1914,51 @@ bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, F if (i <= static_cast(FgExecStage::SharedPostNet1)) shared += mean; else if (i <= static_cast(FgExecStage::PackCopy)) gen += mean; } - // Totals sum GPU execution intervals. Queue waits and overlap are not wall-clock frame time. + // The stage totals sum GPU execution intervals: work that two queues overlap is counted twice and queue waits + // are not counted. The span and busy lines are measured on one clock over the whole timed window. std::printf(" %-18s %.6f\n %-18s %.6f\n %-18s %.6f\n", "total_shared", shared, "total_gen", gen, - "total_2x_frame", shared + gen + timing.ms[static_cast(FgExecStage::RealEndpoint)] / timed); + "sum_of_stages", shared + gen + timing.ms[static_cast(FgExecStage::RealEndpoint)] / timed); + std::printf(" %-18s %.6f (first start to last end of the window / frames, idle gaps included)\n", + "gpu_span_per_frame", timing.span_ms / timed); + std::printf(" %-18s %.6f (time at least one queue ran / frames; %u recordings)\n", "gpu_busy_per_frame", + timing.busy_ms / timed, timing.recordings); + if (bo.kprof) { + if (!exec.TakeKernelProfile(&profile, timeout)) { + std::printf("bench %c: kernel profile unavailable\n", label); + return false; + } + std::printf(" per-launch profile (kernel#ordinal, workgroups per call, calls and mean us per game frame):\n"); + double total = 0.0; + for (const FgExecKernelProfileRow& row : profile) { + const double calls = static_cast(row.calls) / timed; + const double wg = row.calls ? static_cast(row.groups) / static_cast(row.calls) : 0.0; + const double per_call = row.calls ? row.ms * 1000.0 / static_cast(row.calls) : 0.0; + std::printf(" %-34s #%-2u wg %8.0f x%-5.2f %9.2f us/call %9.2f us/frame\n", row.name.c_str(), + row.ordinal, wg, calls, per_call, row.ms * 1000.0 / timed); + total += row.ms * 1000.0 / timed; + } + std::printf(" %-34s %55.2f us/frame\n", "(sum of launches)", total); + } return gpu.DebugErrors() <= 0; } int main(int argc, char** argv) { bool gpu = false, bench = false; std::string dxil, reference_dxil, scratch = ".", only; + BenchOptions bo; for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--gpu") == 0) gpu = true; if (std::strcmp(argv[i], "--bench") == 0) bench = true; + // --gen N: N generated images per game frame (1..5: 2x .. 6x), really recorded and timed + if (std::strcmp(argv[i], "--gen") == 0 && i + 1 < argc) bo.gen = static_cast(std::atoi(argv[++i])); + if (std::strcmp(argv[i], "--timed") == 0 && i + 1 < argc) bo.timed = static_cast(std::atoi(argv[++i])); + if (std::strcmp(argv[i], "--warmup") == 0 && i + 1 < argc) bo.warmup = static_cast(std::atoi(argv[++i])); + if (std::strcmp(argv[i], "--preset") == 0 && i + 1 < argc) bo.presets = argv[++i]; + if (std::strcmp(argv[i], "--kprof") == 0) bo.kprof = true; + // paired A / B levers inside one process (default: the environment, WG_FG_BATCH / _HOIST / _DUALQ = 0 off) + if (std::strcmp(argv[i], "--batch") == 0 && i + 1 < argc) bo.batch = std::atoi(argv[++i]); + if (std::strcmp(argv[i], "--hoist") == 0 && i + 1 < argc) bo.hoist = std::atoi(argv[++i]); + if (std::strcmp(argv[i], "--dualq") == 0 && i + 1 < argc) bo.dualq = std::atoi(argv[++i]); if (std::strcmp(argv[i], "--dxil") == 0 && i + 1 < argc) dxil = argv[++i]; if (std::strcmp(argv[i], "--reference-dxil") == 0 && i + 1 < argc) reference_dxil = argv[++i]; if (std::strcmp(argv[i], "--scratch") == 0 && i + 1 < argc) scratch = argv[++i]; @@ -1901,7 +1974,14 @@ int main(int argc, char** argv) { return 1; } std::printf("gpu: %s\n", g.name.c_str()); - if (!RunBench(g, dxil, weights, FgPreset::A) || !RunBench(g, dxil, weights, FgPreset::C)) return 1; + if (bo.gen < 1 || bo.gen > 5) { + std::printf("--gen takes 1..5\n"); + return 1; + } + for (char c : bo.presets) { + if ((c == 'A' || c == 'a') && !RunBench(g, dxil, weights, FgPreset::A, bo)) return 1; + if ((c == 'C' || c == 'c') && !RunBench(g, dxil, weights, FgPreset::C, bo)) return 1; + } if (!gpu) return 0; } TestGeometry(); diff --git a/clean/fg/runtime/tests/test_fg_session.cpp b/clean/fg/runtime/tests/test_fg_session.cpp index 39f340cf..fc976953 100644 --- a/clean/fg/runtime/tests/test_fg_session.cpp +++ b/clean/fg/runtime/tests/test_fg_session.cpp @@ -205,6 +205,15 @@ class FakeKernelExecutor final : public IFgKernelExecutor { } return FgExecResult::Ok; } + // A batching executor (the D3D12 one with several scratch banks): the session hands it the consecutive generated + // indices of an interval in one call; the records inside are the same as one by one. + bool BatchesGenerated() const override { return batch_generated; } + FgExecResult RecordGeneratedBatch(const FgIndexDispatchDesc* d, uint32_t n, FgReadyFence* ready, + uint32_t* done) override { + batch_sizes.push_back(n); + batch_first.push_back(n ? d[0].index : 0); + return IFgKernelExecutor::RecordGeneratedBatch(d, n, ready, done); + } FgExecResult RecordMenuCopy(const FgCopyDispatchDesc& d, FgReadyFence* ready) override { if (Fail('C')) return fail_result; ExecEvent e; @@ -259,6 +268,7 @@ class FakeKernelExecutor final : public IFgKernelExecutor { uint64_t stall_token = 0; FgTicks stall_slot = 0; bool refuse_configure = false; + bool batch_generated = false; // BatchesGenerated(): the session calls RecordGeneratedBatch bool compute_stalled = false; // the compute timeline reports nothing completed (history banks stay read) char fail_kind = 0; // 'S', 'G', 'C', 'R' or '*' (every record) int fail_after = 0; // calls of that kind that still succeed first @@ -266,6 +276,7 @@ class FakeKernelExecutor final : public IFgKernelExecutor { // observations std::vector events; + std::vector batch_sizes, batch_first; // every RecordGeneratedBatch call: its size, its first index int configures = 0; uint32_t configured_w = 0, configured_h = 0, configured_banks = 0; int bad_packets = 0; @@ -1064,6 +1075,78 @@ void TestLateDrops() { CHECK(rig.Shutdown()); } +// An executor that batches (BatchesGenerated) gets the consecutive generated indices of an interval in one call, in +// order; copies (menu latch), late cancellation and a refusal inside a batch behave as they do one index at a time, and +// the history advances once per interval after the batch was recorded. +void TestBatchedIndices() { + { // every generating interval is one batch of N consecutive indices + Rig rig(5, WG_FG_PRESET_A); + rig.exec.batch_generated = true; + CHECK(rig.Create().error == FgSessionError::None); + rig.Frames(10); + CHECK(!rig.exec.batch_sizes.empty()); + bool five = true; + for (size_t i = 0; i < rig.exec.batch_sizes.size(); ++i) + five = five && rig.exec.batch_sizes[i] == 5 && rig.exec.batch_first[i] == 1; + CHECK(five); + CHECK(rig.exec.batch_sizes.size() * 5 == static_cast(rig.exec.count('G'))); + const std::vector g = IndexEvents(rig.exec, rig.token, 'G'); + bool order = g.size() == 5; + for (uint32_t i = 0; i < g.size(); ++i) + order = order && g[i].index == i + 1 && g[i].last == (i + 1 == 5) && g[i].slot_reserved; + CHECK(order); + CHECK(FrameOrderOk(rig.exec, rig.token, 5, 'G')); + const FrameRecord& f = rig.frames.back(); + CHECK(f.session.error == FgSessionError::None && f.session.generated_recorded == 5 && f.session.history_advanced); + CHECK(rig.GeneratedShown(rig.token) == 5 && rig.RealShown(rig.token) == 1); + CHECK(rig.session.History()->primes() == 1); + CHECK(rig.HistoryOk()); + CHECK(rig.Shutdown()); + } + { // a refusal inside a batch: the indices recorded before it count, the session refuses, nothing falls back + Rig rig(5, WG_FG_PRESET_A); + rig.exec.batch_generated = true; + CHECK(rig.Create().error == FgSessionError::None); + rig.Frames(10); + rig.exec.fail_kind = 'G'; + rig.exec.fail_after = 2; + rig.Frames(1); + const FrameRecord& f = rig.frames.back(); + CHECK(f.session.error == FgSessionError::ExecutorRefused); + CHECK(f.session.generated_recorded == 2); + CHECK(rig.session.State() == FgSessionState::Refused); + } + { // a menu frame records copies, never a batch + Rig rig(4, WG_FG_PRESET_A); + rig.exec.batch_generated = true; + rig.exec.menu_tokens = {12}; + CHECK(rig.Create().error == FgSessionError::None); + rig.Frames(16); + CHECK(rig.exec.count('G', 12) == 0 && rig.exec.count('C', 12) == 4 && rig.exec.count('C', 13) == 4); + CHECK(rig.exec.count('G', 11) == 4 && rig.exec.count('G', 14) == 4); + CHECK(rig.exec.batch_sizes.size() * 4 == static_cast(rig.exec.count('G'))); + CHECK(rig.session.History()->primes() == 1 && rig.HistoryOk()); + CHECK(rig.Shutdown()); + } + { // a batching executor and a per-index one record the same indices with the same times + Rig batched(3, WG_FG_PRESET_B), single(3, WG_FG_PRESET_B); + batched.exec.batch_generated = true; + CHECK(batched.Create().error == FgSessionError::None && single.Create().error == FgSessionError::None); + batched.Frames(12); + single.Frames(12); + CHECK(batched.exec.events.size() == single.exec.events.size()); + bool same = batched.exec.events.size() == single.exec.events.size(); + for (size_t i = 0; same && i < batched.exec.events.size(); ++i) { + const ExecEvent& a = batched.exec.events[i]; + const ExecEvent& b = single.exec.events[i]; + same = a.kind == b.kind && a.token == b.token && a.index == b.index && a.slot == b.slot && + std::memcmp(&a.t, &b.t, sizeof(float)) == 0; + } + CHECK(same); + CHECK(batched.Shutdown() && single.Shutdown()); + } +} + // A broken executor: the session refuses explicitly and never falls back; the game frame of the failing interval is // still shown when it can be recorded. void TestExecutorRefusalNoFallback() { @@ -1377,6 +1460,7 @@ int main() { Run("TestDeviceLost", &TestDeviceLost); Run("TestVrrExitAndReentry", &TestVrrExitAndReentry); Run("TestLateDrops", &TestLateDrops); + Run("TestBatchedIndices", &TestBatchedIndices); Run("TestExecutorRefusalNoFallback", &TestExecutorRefusalNoFallback); Run("TestCreateRefusals", &TestCreateRefusals); Run("TestHandOffArguments", &TestHandOffArguments); From 153d351c9f4b060c696815aa8c69713812e8a9e8 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:13:57 -0500 Subject: [PATCH 08/15] Frame generation (D3D12): fused and retiled kernels (fine pass + hole mask, tiled hole rule, both intermediate-time passes with LDS-binned minima, net2 L25 heads staged in one pass), all exact and switchable (WG_FG_FUSE=0) fg_lite_p2c_fine_mask runs the hole mask on the value the fine pass finishes (net1 grid = scatter grid), dropping one launch and one read of F. fg_lite_p2c_inpaint_tiled computes the 5 x 5 hole rule on 32 x 8 tiles from ballot row masks (1.7 loads per pixel instead of 5). fg_lite_interm_both runs both passes in one launch and bins each tile's scatters in a 32 x 32 window of signed 64-bit LDS cells before one global minimum per cell (min is associative and commutative, the result is the same bits). fg_net2_mconv_h3b1u_s3 stages L25's three heads in one pass. The kernels they replace are unchanged (their DXIL is byte-identical to the previous build). CPU proofs of the exactness arguments in clean/fg/tests/test_fg_turbo_v2.py; test_fg_d3d12_e2e --gpu --only turbo compares every lever on against every lever off byte for byte; fg_lite_d3d12_check.py --turbo checks the new kernels against the CPU reference. --- clean/dx12/kernels/fg_lite_g.hlsl | 148 +++++++++++++ clean/dx12/kernels/fg_lite_p2c.hlsl | 92 ++++++++ clean/dx12/kernels/fg_net2_mconv.hlsl | 61 ++++++ clean/fg/README.md | 1 + clean/fg/runner/fg_lite_d3d12_check.py | 47 +++- clean/fg/runtime/fg_d3d12_executor.cpp | 75 +++++-- clean/fg/runtime/fg_d3d12_executor.h | 8 +- clean/fg/runtime/fg_exec_plan.cpp | 18 ++ clean/fg/runtime/fg_exec_plan.h | 19 ++ clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 218 ++++++++++++++++++- clean/fg/tests/test_fg_turbo_v2.py | 167 ++++++++++++++ 11 files changed, 813 insertions(+), 41 deletions(-) create mode 100644 clean/fg/tests/test_fg_turbo_v2.py diff --git a/clean/dx12/kernels/fg_lite_g.hlsl b/clean/dx12/kernels/fg_lite_g.hlsl index 1cd0af13..49ac4694 100644 --- a/clean/dx12/kernels/fg_lite_g.hlsl +++ b/clean/dx12/kernels/fg_lite_g.hlsl @@ -7,10 +7,18 @@ // Zp, written when the displacement test passes. Footprint 2 at a depth edge (key range over 3 x 3 > tau), else from // the spread of the warped 3 x 3 positions (2..5 per axis). Signed 64-bit atomic minimum (SM 6.6) of (key bits << 32 // | float16 of the vector back to the source frame, normalised). +// fg_lite_interm_both: both passes in one launch (pass A into MA, then pass B into MB, the same tile geometry and the same +// arithmetic per lane as fg_lite_interm_tiled), with the scatters of a tile binned in LDS first: a 32 x 32 window of +// signed 64-bit cells (initialised to the empty element 0x7FFFFFFF7FFFFFFF) placed around the tile's centre +// displacement takes the atomic minima of every target inside it, and each cell below the empty value is then +// minimised into the global element once. A target outside the window goes to the global element directly. The minimum +// of signed 64-bit values is associative and commutative: every global element ends as the minimum of its initial value and +// all the values aimed at it, the same bits as one global atomic minimum per scatter, in any order. // fg_lite_weights: W = (sigma(NA at the MB vector - NA co-located), sigma(NB at the MA vector - NB co-located)). // // @wg-kernel fg_lite_interm co=- block=256 wave=32 args=u,p,p,p,u,u,u,u,u,u,u defines=FG_K=1 // @wg-kernel fg_lite_interm_tiled co=- entry=fg_lite_interm block=256 wave=32 args=u,p,p,p,u,u,u,u,u,u,u defines=FG_K=1,FG_TILE=1 +// @wg-kernel fg_lite_interm_both co=- block=256 wave=32 args=p,p,p,p,p,p,u,u,u,u,u,u,u defines=FG_K=3 // @wg-kernel fg_lite_weights co=- block=256 wave=32 args=p,p,p,p,p,u,u,u,u defines=FG_K=2 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" @@ -146,6 +154,146 @@ WG_KERNEL(fg_lite_interm) } #endif + +#if FG_K == 3 +WG_ARGS_BEGIN + uint src_a, z_a, tgt_a, src_b, z_b, tgt_b, w1, h1, tbits, s_k, inverted, t2, tau; +WG_ARGS_END + +static const int fg_tile_width = 24; +static const int fg_halo = 4; +static const int64_t fg_empty64 = 0x7FFFFFFF7FFFFFFFll; +groupshared float fg_tile_key[fg_tile_width * fg_tile_width]; +groupshared float fg_tile_dx[fg_tile_width * fg_tile_width]; +groupshared float fg_tile_dy[fg_tile_width * fg_tile_width]; +groupshared int64_t fg_bin[1024]; + +float2 fg_disp(uint pass_, uint src, int x, int y) +{ + const float t = asfloat(tbits); + if (pass_ == 0u) + { + const float omt = 1.0f - t; + const float4 m = fg_read_int(src, 5u, (int)w1, (int)h1, x, y); + return float2(fg_mul(omt, fg_mul(m.x, (float)w1)), fg_mul(omt, fg_mul(m.y, (float)h1))); + } + const float4 f = fg_read_int(src, 2u, (int)w1, (int)h1, x, y); + return float2(fg_mul(t, f.x), fg_mul(t, f.y)); +} + +float fg_key_at(uint zimg, int x, int y) +{ + const uint Z = wg_ld32(zimg, (uint)(clamp(y, 0, (int)h1 - 1) * (int)w1 + clamp(x, 0, (int)w1 - 1)) * 4u); + return fg_depth_key(fg_unpack_depth(Z, 0.0f, 0.0f).x, asfloat(s_k), inverted); +} + +int fg_radius(float qmax, float qmin, float qp) +{ + const float a = max(abs(qmax - qp), abs(qmin - qp)); + return clamp((int)fg_med3(ceil(a + 0.5f), 2.0f, 5.0f), 2, 5); +} + +float2 fg_tile_disp(int i) { return float2(fg_tile_dx[i], fg_tile_dy[i]); } + +void fg_min64_global(uint base, uint idx, int64_t v) +{ + wg_mem_gc.InterlockedMin64(base + idx * 8u, v); +} + +void fg_interm_pass(uint pass_, uint src, uint zimg, uint target) +{ + const uint tiles_x = (w1 + 15u) >> 4u, block = wg_block_id(), lane = wg_lane_id(); + const int2 origin = int2(block % tiles_x, block / tiles_x) * 16; + for (uint i = lane; i < fg_tile_width * fg_tile_width; i += 256u) { + const int2 p = origin + int2(i % fg_tile_width, i / fg_tile_width) - fg_halo; + const float2 d = fg_disp(pass_, src, p.x, p.y); + fg_tile_key[i] = fg_key_at(zimg, p.x, p.y); + fg_tile_dx[i] = d.x; + fg_tile_dy[i] = d.y; + } + for (uint c = lane; c < 1024u; c += 256u) fg_bin[c] = fg_empty64; + wg_barrier_lds(); + // the window follows the displacement of the tile's centre pixel (any window gives the same result) + const int centre_tile = (fg_halo + 8) * fg_tile_width + fg_halo + 8; + const int wx0 = origin.x + (int)clamp(fg_tile_dx[centre_tile], -16384.0f, 16384.0f) - 8; + const int wy0 = origin.y + (int)clamp(fg_tile_dy[centre_tile], -16384.0f, 16384.0f) - 8; + const int2 local = int2(lane & 15u, lane >> 4u) + fg_halo; + const int2 xy = origin + local - fg_halo; + if (xy.x < (int)w1 && xy.y < (int)h1) + { + const int center = local.y * fg_tile_width + local.x; + const int x = xy.x, y = xy.y; + const float tauf = asfloat(tau); + const float kp = fg_tile_key[center]; + const float2 dp = fg_tile_disp(center); + float kmax = -FG_INF, kmin = FG_INF, qxmax = -10000.0f, qymax = -10000.0f, qxmin = 10000.0f, qymin = 10000.0f; + [unroll] for (int j = -1; j <= 1; ++j) + [unroll] for (int i = -1; i <= 1; ++i) + { + const int neighbor = center + j * fg_tile_width + i; + const float kn = fg_tile_key[neighbor]; + const float2 dn = fg_tile_disp(neighbor); + kmax = max(kmax, kn); + kmin = min(kmin, kn); + const float qx = fg_opq((float)(x + i) + 0.5f) + dn.x, qy = fg_opq((float)(y + j) + 0.5f) + dn.y; + qxmax = max(qxmax, qx); qxmin = min(qxmin, qx); + qymax = max(qymax, qy); qymin = min(qymin, qy); + } + const float qpx = fg_opq((float)x + 0.5f) + dp.x, qpy = fg_opq((float)y + 0.5f) + dp.y; + const bool edge = (kmax - kp) > tauf || (kp - kmin) > tauf; + const int rx = edge ? 2 : fg_radius(qxmax, qxmin, qpx); + const int ry = edge ? 2 : fg_radius(qymax, qymin, qpy); + const uint hi = asuint(kp); + const uint lo = (fg_f2h(fg_adiv(-dp.x, (float)w1)) << 16) | fg_f2h(fg_adiv(-dp.y, (float)h1)); + const int64_t value = (int64_t)(((uint64_t)hi << 32) | (uint64_t)lo); + const float thr = max(fg_adiv(fg_sq(dp.x, dp.y), asfloat(t2)), 1.0f); + const int sx = fg_sgn(dp.x), sy = fg_sgn(dp.y); + const int bx = x + (int)dp.x, by = y + (int)dp.y; + [loop] for (int jj = 0; jj < ry; ++jj) + [loop] for (int ii = 0; ii < rx; ++ii) + { + const int tx = bx + ii * sx, ty = by + jj * sy; + if (tx < 0 || tx >= (int)w1 || ty < 0 || ty >= (int)h1) continue; + const int neighbor = center + jj * sy * fg_tile_width + ii * sx; + const float2 nd = fg_tile_disp(neighbor); + const float dd = fg_sq(nd.x - dp.x, nd.y - dp.y); + bool ok; + if (pass_ == 0u) + { + const float kt = (float)(uint)fg_tile_key[neighbor]; + ok = !(!(abs(kt - kp) < 3.0f) && !(dd < thr)); + } + else + ok = dd < thr; + if (ok) + { + const int cx = tx - wx0, cy = ty - wy0; + if ((uint)cx < 32u && (uint)cy < 32u) + { + int64_t before; + InterlockedMin(fg_bin[cy * 32 + cx], value, before); + } + else + fg_min64_global(target, (uint)(ty * (int)w1 + tx), value); + } + } + } + wg_barrier_lds(); + for (uint c = lane; c < 1024u; c += 256u) { + const int64_t v = fg_bin[c]; + if (v < fg_empty64) fg_min64_global(target, (uint)((wy0 + (int)(c >> 5u)) * (int)w1 + wx0 + (int)(c & 31u)), v); + } + wg_barrier_lds(); +} + +WG_KERNEL(fg_lite_interm_both) +{ + FG_SETUP(); + fg_interm_pass(0u, src_a, z_a, tgt_a); + fg_interm_pass(1u, src_b, z_b, tgt_b); +} +#endif + #if FG_K == 2 WG_ARGS_BEGIN uint ma, mb, na, nb, wout, w1, h1, wd, hd; diff --git a/clean/dx12/kernels/fg_lite_p2c.hlsl b/clean/dx12/kernels/fg_lite_p2c.hlsl index 0d709e99..8a5b78d2 100644 --- a/clean/dx12/kernels/fg_lite_p2c.hlsl +++ b/clean/dx12/kernels/fg_lite_p2c.hlsl @@ -12,6 +12,15 @@ // from a level's float16 elements; writes the level's sums (when sums_out != 0) and its float16 x 3 elements. // fg_lite_p2c_push: fills one level in place from its filled parent (9/16, 3/16, 3/16, 1/16 taps). // fg_lite_p2c_fine: F := v_up from level 1 at every pixel with G bit 0. +// fg_lite_p2c_fine_mask (the net1 grid is the scatter grid: d = dp): the fine pass and the hole mask in one launch. The lane +// that finishes F at its pixel (v_up, or the unpack pass's value where G bit 0 is clear) continues with +// fg_lite_hole_mask's work on that value: the mask reads F at the pixel centre of the same grid, which is its own pixel +// (the nearest-index product of a centre and the grid size is within 1e-3 of x + 0.5), and writes zeros only. Hc := 1 +// must be filled before the launch (the hole mask's zeros land in it). +// fg_lite_p2c_inpaint_tiled: the same hole rule on 32 x 8 pixel tiles. Each wave gathers one row of the tile (and the two rows +// above and below with the first four waves) as bit masks with ballots, so a pixel's 5 x 5 neighbourhood costs 1.7 loads +// instead of 5; the rule (every 3 x 3 window of the neighbourhood holds a flagged pixel = erosion of the 3 x 3 dilation of +// the flag-bit-1 image, zero outside the image) runs on the masks. // // @wg-kernel fg_lite_p2c_scatter co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_K=1 // @wg-kernel fg_lite_p2c_unpack co=- block=256 wave=32 args=p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_K=2 @@ -22,6 +31,8 @@ // @wg-kernel fg_lite_p2c_pull_tiled co=- entry=fg_lite_p2c_pull block=256 wave=32 args=u,p,p,p,p,u,u,u,u,u,p,p,p,u defines=FG_K=4,FG_PULL_TILE=1 // @wg-kernel fg_lite_p2c_push_tail co=- block=256 wave=32 args=u,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_K=7 // @wg-kernel fg_lite_p2c_fine co=- block=256 wave=32 args=p,u,u,p,p,u,u defines=FG_K=6 +// @wg-kernel fg_lite_p2c_fine_mask co=- entry=fg_lite_p2c_fine block=256 wave=32 args=p,u,u,p,p,u,u,p defines=FG_K=6,FG_MASK=1 +// @wg-kernel fg_lite_p2c_inpaint_tiled co=- entry=fg_lite_p2c_inpaint block=256 wave=32 args=p,p,u,u defines=FG_K=3,FG_IP_TILE=1 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" @@ -118,6 +129,61 @@ WG_ARGS_BEGIN uint fl, gout, w1, h1; WG_ARGS_END +#if FG_IP_TILE +// Tile row r (0 .. 11) is pixel row y0 - 2 + r, bit c (0 .. 35) is pixel column x0 - 2 + c: the flag-bit-1 image, 0 outside. +groupshared uint64_t fg_ip_row[12]; +groupshared uint64_t fg_ip_dil[12]; // bit c (0 .. 33): OR of the 3 x 3 flags around centre (x0 - 1 + c, y0 - 1 + r) +groupshared uint64_t fg_ip_dv[10]; // the same ORed over three rows + +bool fg_ip_flag(int x, int y) +{ + return x >= 0 && x < (int)w1 && y >= 0 && y < (int)h1 && + (wg_ld32(fl, ((uint)y * w1 + (uint)x) * 4u) & 2u) != 0u; +} + +// the 36-bit mask of pixel row y of the tile (columns x0 - 2 .. x0 + 33); the wave's lanes are the 32 tile columns, lanes 0 .. 3 +// also the four halo columns +uint64_t fg_ip_row_mask(int x0, int y, uint lane) +{ + const int x = x0 + (int)lane; + const bool own = fg_ip_flag(x, y); + const int xh = lane < 2u ? x0 - 2 + (int)lane : x0 + 32 + (int)lane - 2; + const bool halo = lane < 4u && fg_ip_flag(xh, y); + const uint m = WaveActiveBallot(own).x, hb = WaveActiveBallot(halo).x; + return (uint64_t)(hb & 3u) | ((uint64_t)m << 2) | ((uint64_t)((hb >> 2) & 3u) << 34); +} + +WG_KERNEL(fg_lite_p2c_inpaint) +{ + FG_SETUP(); + const uint l = wg_lane_id(), lane = l & 31u, wave = l >> 5u; + const uint tiles_x = (w1 + 31u) >> 5u, tile = wg_block_id(); + const int x0 = (int)((tile % tiles_x) * 32u), y0 = (int)((tile / tiles_x) * 8u); + const int x = x0 + (int)lane, y = y0 + (int)wave; + const bool live = x < (int)w1 && y < (int)h1; + const uint fw = wg_ld32(fl, select(live, ((uint)y * w1 + (uint)x) * 4u, 0u)); + const uint64_t main_row = fg_ip_row_mask(x0, y, lane); + if (lane == 0u) fg_ip_row[2u + wave] = main_row; + if (wave < 4u) { // wave-uniform: the rows y0 - 2, y0 - 1, y0 + 8, y0 + 9 + const int ey = wave < 2u ? y0 - 2 + (int)wave : y0 + 8 + (int)wave - 2; + const uint64_t extra = fg_ip_row_mask(x0, ey, lane); + if (lane == 0u) fg_ip_row[wave < 2u ? wave : wave + 8u] = extra; + } + wg_barrier_lds(); + if (l < 12u) { + const uint64_t b = fg_ip_row[l]; + fg_ip_dil[l] = b | (b >> 1) | (b >> 2); + } + wg_barrier_lds(); + if (l < 10u) fg_ip_dv[l] = fg_ip_dil[l] | fg_ip_dil[l + 1u] | fg_ip_dil[l + 2u]; + wg_barrier_lds(); + if (!live) return; + const uint64_t e = fg_ip_dv[wave] & fg_ip_dv[wave + 1u] & fg_ip_dv[wave + 2u]; + const bool inp = ((e >> lane) & 7ull) == 7ull; + const bool dyn = (fw & 1u) != 0u; + wg_st32(gout, ((uint)y * w1 + (uint)x) * 4u, ((dyn && !inp) ? 2u : 0u) | (inp ? 1u : 0u)); +} +#else // Each row holds the 256 centers and the two horizontal halo pixels on either side. // A row is addressed in the flat grid, then trimmed at the center pixel's image edges. groupshared uint fg_inpaint_flags[5][9]; @@ -172,6 +238,7 @@ WG_KERNEL(fg_lite_p2c_inpaint) wg_st32(gout, idx * 4u, ((dyn && !inp) ? 2u : 0u) | (inp ? 1u : 0u)); } #endif +#endif #if FG_K == 4 WG_ARGS_BEGIN @@ -359,6 +426,9 @@ WG_KERNEL(fg_lite_p2c_push_tail) #if FG_K == 6 WG_ARGS_BEGIN uint parent, pw, ph, gin, fio, w1, h1; +#if FG_MASK + uint hc; +#endif WG_ARGS_END WG_KERNEL(fg_lite_p2c_fine) @@ -366,8 +436,30 @@ WG_KERNEL(fg_lite_p2c_fine) FG_SETUP(); const uint idx = wg_block_id() * 256u + wg_lane_id(); if (idx >= w1 * h1) return; +#if FG_MASK + // F at this pixel as the next pass reads it (float16 x 2): v_up where G bit 0 is set, else the unpack pass's value + uint fw; + if ((wg_ld32(gin, idx * 4u) & 1u) != 0u) { + const float3 up = fg_upsample(parent, (int)pw, (int)ph, (int)(idx % w1), (int)(idx / w1)); + fw = fg_pack_h2(up.x, up.y); + wg_st32(fio, idx * 4u, fw); + } else { + fw = wg_ld32(fio, idx * 4u); + } + // fg_lite_hole_mask on the same grid (wd = w1, hd = h1): Hc := 0 at the four targets of this pixel's vector + const int x = (int)(idx % w1), y = (int)(idx / w1); + const float mx = fg_mul(fg_adiv(f16tof32(fw), (float)w1), (float)w1); + const float my = fg_mul(fg_adiv(f16tof32(fw >> 16), (float)h1), (float)h1); + const int bx = x + (int)mx, by = y + (int)my, sx = fg_sgn(mx), sy = fg_sgn(my); + [unroll] for (uint e = 0u; e < 4u; ++e) + { + const int tx = bx + (int)(e >> 1) * sx, ty = by + (int)(e & 1u) * sy; + if (tx >= 0 && tx < (int)w1 && ty >= 0 && ty < (int)h1) wg_st16(hc, (uint)(ty * (int)w1 + tx) * 2u, 0u); + } +#else if ((wg_ld32(gin, idx * 4u) & 1u) == 0u) return; const float3 up = fg_upsample(parent, (int)pw, (int)ph, (int)(idx % w1), (int)(idx / w1)); fg_st_h2(fio, idx, up.x, up.y); +#endif } #endif diff --git a/clean/dx12/kernels/fg_net2_mconv.hlsl b/clean/dx12/kernels/fg_net2_mconv.hlsl index f5b628a5..aafb7f7e 100644 --- a/clean/dx12/kernels/fg_net2_mconv.hlsl +++ b/clean/dx12/kernels/fg_net2_mconv.hlsl @@ -23,6 +23,11 @@ // one workgroup per spatial tile. They reuse the LDS tile across heads and join a shared eight-channel output // before the residual and store. // +// FG_STAGE_ALL = 1 (fused heads only, fg_net2_mconv_h3b1u_s3): the three heads' tiles are staged in one pass (one loop over +// the three heads' items, one LDS barrier, a tile of three head blocks) instead of three passes with a barrier each, so +// the staging rounds are full (972 items over 256 lanes: 3.8 rounds instead of 3 x 1.27) and no barrier separates the heads. +// Every staged value and every convolution is the same computation on the same data as the three-pass kernel. +// // Work split: workgroup = 16 x FG_TH conv pixels (tile tx, ty; FG_TH = 2 rows per wave) and FG_MT output tiles of 16 // weight outputs (group mg); a wave owns two rows of 16 pixels (two B fragments per chunk), so a pooled 2 x 2 cell sits // in one wave (lanes n, n ^ 1). A fragments: wf [cout / 16][9 taps][FG_NB blocks][32 lanes][8] float16 @@ -45,6 +50,7 @@ // @wg-kernel fg_net2_mconv_m3b2u co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=3,FG_NB=2,FG_UP=1 // @wg-kernel fg_net2_mconv_m3b4u co=fg_net2_mma.co entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=3,FG_NB=4,FG_UP=1 // @wg-kernel fg_net2_mconv_h3b1u co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1,FG_UP=1,FG_FUSED_HEADS=1 +// @wg-kernel fg_net2_mconv_h3b1u_s3 co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1,FG_UP=1,FG_FUSED_HEADS=1,FG_STAGE_ALL=1 // @wg-kernel fg_net2_mconv_h3b2u co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=2,FG_UP=1,FG_FUSED_HEADS=1 #include "wg_platform.hlsli" #include "fg_net2.hlsli" @@ -69,6 +75,9 @@ WG_ARGS_END #ifndef FG_FUSED_HEADS #define FG_FUSED_HEADS 0 #endif +#ifndef FG_STAGE_ALL +#define FG_STAGE_ALL 0 +#endif #define FG_NATIVE_UP FG_UP #define FG_NATIVE_POST ((!FG_UP && (FG_NB == 2 || FG_MT == 2 || FG_NB == 4)) || (FG_UP && FG_NB == 1)) #define FG_NATIVE_LEAKY 1 @@ -91,10 +100,17 @@ uint4 fg_load_input8(uint off, int ico) #if FG_STAGE #define FG_TG (FG_NB * 2) #define FG_TILE_PIXELS ((FG_TH + 2) * 18) +#if FG_STAGE_ALL +groupshared uint4 fg_tile[FG_TILE_PIXELS * FG_TG * 3]; +static uint fg_tile_head; // the head whose block of the tile the convolution reads (wave-uniform) + +uint fg_tile_index(uint p, uint g) { return (fg_tile_head * FG_TG + g) * FG_TILE_PIXELS + p; } +#else groupshared uint4 fg_tile[FG_TILE_PIXELS * FG_TG]; uint fg_tile_index(uint p, uint g) { return g * FG_TILE_PIXELS + p; } #endif +#endif // 8 packed float16 values -> the float32 accumulator fragment (exact; mask-free low halves via f16tof32) v8f fg_widen(uint4 hp) @@ -273,6 +289,43 @@ void fg_stage(int x0, int y0, int ico) } wg_barrier_lds(); } +#if FG_STAGE_ALL +// fg_stage for the three heads (head hj reads the channels in_co + hj cin ..), one pass and one barrier +void fg_stage_heads(int x0, int y0) +{ + const int hi = H / 2, wi = W / 2; + const int items1 = (FG_TH / 2 + 1) * 18 * FG_TG; + const int items = 3 * items1; + const int rounds = (items + WG_BLOCK - 1) / WG_BLOCK + (int)fg_opq0(); + for (int round = 0; round < rounds; ++round) { + // Lanes past the end still participate in the wave's conversion. + const int it = round * WG_BLOCK + (int)wg_lane_id(), elem = min(it, items - 1); + const int hj = elem / items1, e1 = elem - hj * items1; + const int ico = in_co + hj * cin; + const int g = e1 % FG_TG, p = e1 / FG_TG; + const int cy = y0 - 1 + 2 * (p / 18), cx = x0 - 1 + p % 18; + const Fg2Tap tx = fg_stage_tap(clamp(cx, 0, W - 1), wi); + const Fg2Tap ty0 = fg_stage_tap(clamp(cy, 0, H - 1), hi); + const Fg2Tap ty1 = fg_stage_tap(clamp(cy + 1, 0, H - 1), hi); + const int row0 = ty0.i0 * wi, row1 = ty0.i1 * wi, c0 = ico + 8 * g; + const uint4 q00 = fg_load_input8((uint)(((row0 + tx.i0) * in_cs + c0) * 2), ico); + const uint4 q01 = fg_load_input8((uint)(((row0 + tx.i1) * in_cs + c0) * 2), ico); + const uint4 q10 = fg_load_input8((uint)(((row1 + tx.i0) * in_cs + c0) * 2), ico); + const uint4 q11 = fg_load_input8((uint)(((row1 + tx.i1) * in_cs + c0) * 2), ico); + const uint4 top = fg_up_axis8(tx, q00, q01), bot = fg_up_axis8(tx, q10, q11); + const uint4 mask = fg_cmask(8 * g); + const bool inside_x = cx >= 0 && cx < W; + const uint4 v0 = fg_up_axis8(ty0, top, bot) & mask & select(inside_x && cy >= 0 && cy < H, ~0u, 0u); + const uint4 v1 = fg_up_axis8(ty1, top, bot) & mask & select(inside_x && cy + 1 >= 0 && cy + 1 < H, ~0u, 0u); + if (it < items) { + const int dst = p + p / 18 * 18; + fg_tile[(hj * FG_TG + g) * FG_TILE_PIXELS + dst] = v0; + fg_tile[(hj * FG_TG + g) * FG_TILE_PIXELS + dst + 18] = v1; + } + } + wg_barrier_lds(); +} +#endif #elif FG_STAGE void fg_stage(int x0, int y0, int ico) { @@ -479,10 +532,18 @@ WG_KERNEL(fg_net2_mconv) #if FG_FUSED_HEADS uint4 packed[2] = {uint4(0u, 0u, 0u, 0u), uint4(0u, 0u, 0u, 0u)}; // Each head consumes the same weights and bias on its own input channel slice. +#if FG_STAGE_ALL + fg_stage_heads(tx * 16, ty * FG_TH); +#endif for (int hj = 0; hj < 3 + (int)fg_opq0(); ++hj) { +#if FG_STAGE_ALL + const int ico = in_co + hj * cin; + fg_tile_head = (uint)hj; +#else if (hj > 0) wg_barrier_lds(); const int ico = in_co + hj * cin; fg_stage(tx * 16, ty * FG_TH, ico); +#endif if (py0 < H) { uint4 h16[1][2]; fg_conv_tile(px, py0, wrow, n, hh, lane, 0, ico, h16); diff --git a/clean/fg/README.md b/clean/fg/README.md index 74b35af9..15c36f6e 100644 --- a/clean/fg/README.md +++ b/clean/fg/README.md @@ -66,6 +66,7 @@ front end or the launcher yet. Status, open items and formats: [FORMATS.md](FORM | `runtime/fg_exec_plan.h`, `.cpp` | the D3D12 executor's CPU side (F7b, plain C++17): the light path's settings, the grid sizes of a frame size (net1 image and cell grids, scatter grid and pyramid, net2's factor and grid, the output pyramid), application regions and their ten kernel values, the float16 rounding, and the schedule of `reference/pipeline.py` `Host` split at the session's seam: once per game frame (history clears, menu detection or the disable word, R3 .. R8, net1's input / net1 / output or the quality image), per index (the intermediate-time scatters, the blend weights, the light blend for preset C or the Full blend, net2 and the output pyramid for presets A / B, the menu output; the game frame's copy without history) and the last-index part (history advances, the image pairs swap) | | `runtime/fg_d3d12_executor.h`, `.cpp` | `FgD3d12Executor`, the production `IFgKernelExecutor` on the game's D3D12 device and queue (F7b): one root signature for every FG kernel (arena root UAVs, 59 root constants, the driver channel and one texture view), the kernels' DXIL loaded from a folder built by `clean/dx12/build_dx12.py --only` and their pipelines built once, the arena sized for the frame (every image, net1's three regions, the input capture areas, the Full path and net2) with the weights uploaded at configuration; per game frame the inputs are captured from the game's textures (`fg_exec_io.hlsl`) and the shared stages recorded, the menu detection read back (a bounded wait on that submission only); per index the generated image is written into the presenter slot's texture (packed to the slot's format, COMMON -> COPY_DEST -> COMMON) and the shared producer fence signalled; menu / priming copies and the game frame's endpoint copy the colour exactly; an adapter-side real-only frame (no shared work) is captured from the game's back buffer and copied into a reserved slot (F9); net2 runs on the fast path by default (27 launches on the matrix unit, tier B: `fg_net2_mconv.hlsl`, `fg_net2_upwarp.hlsl`, the plan of `runner/fg_net2_mma.py`) with the exact 38-launch chain selectable (`FgD3d12ExecutorDesc::net2`), and `Net2SelfTest` runs net2 alone on synthetic inputs for the comparison and timing legs; every refusal names its reason and nothing falls back. `FgExecutorPresenterSource` binds the executor to the composition or DXGI back end the session creates; `FgExecWeightsFromModel` takes the weights from a checked model file | | `runtime/tests/test_fg_d3d12_e2e.cpp` | ctest `fg_d3d12_e2e` (CPU): geometry, regions, thresholds and the logistic table against the CPU reference, the float16 rounding, the schedule, every executor refusal that needs no GPU and a session whose executor refuses (no presenter, no fallback). `--gpu --dxil /dx12` adds the headless GPU leg (no window): a synthetic game through the adapter core, the session and the executor with the composition back end (unbound surface) and the DXGI back end (composition swap chain) for preset C 2x / 6x and presets A / B 2x with a menu frame, net2's exact path, and frames with generation switched off in the game's options (real-only from the back buffer) (generated images finite, menu and endpoint copies exact, slot bytes equal to the image in the slot's format, fences complete, DXGI slots all returned, the swap chain released right after teardown; `--debug-layer` adds the D3D12 debug layer), net2's fast path against the exact one on synthetic inputs (within tolerance, deterministic, every value written, a half-covered last launch caught; GPU time at the 1080p and 1440p grids, information only), and kernel folders with a broken kernel that must be refused | +| Turbo v2 (executor levers, all exact: the kernels' arithmetic is untouched, only where and when independent work runs and four fused / retiled kernels) | `WG_FG_BATCH=0` / `WG_FG_HOIST=0` / `WG_FG_DUALQ=0` / `WG_FG_FUSE=0` (or `FgD3d12ExecutorDesc::batch / hoist / dualq / fuse`) turn a lever off for paired A / B runs; all four give the same bytes as all four off (`test_fg_d3d12_e2e --gpu --dxil --only turbo`: every slot over four game frames, presets A / B / C, N = 1..5, byte for byte). Scratch banks: the per-index images (MA, MB, W, the generated image and its packed rows, the Full blend's images, net2's tensors, the output pyramid) are one block repeated once per generated index (`max_generated` banks while the arena fits). `RecordGeneratedBatch` (the session calls it when `BatchesGenerated()`) records layer k of every index back to back, so barriers sit only between dependent layers and the small net2 / pyramid layers of several indices fill the GPU together. Hoist: the per-index MA / MB fills and intermediate-time scatters of every index of the game frame run on a second compute queue beside net1 (they read only the p2c results) and the producer queue waits for them before the first index. Dual queue: the game queue's work is two recordings (motion preparation, then the downsample) so the p2c chain starts after the first and the net1 input waits for the second. Fuse: `fg_lite_p2c_fine_mask` (fine pass + hole mask when the net1 grid is the scatter grid), `fg_lite_p2c_inpaint_tiled` (32 x 8 tiles, ballot row masks), `fg_lite_interm_both` (both passes, 32 x 32 LDS-binned signed 64-bit minima) and `fg_net2_mconv_h3b1u_s3` (L25's three heads staged in one pass). Profiling: `WRONGGPU_FG_KPROF=1` or `test_fg_d3d12_e2e --bench --kprof` lists every launch (kernel, workgroups, us); `--gen N` benchmarks 2x..6x for real and reports the wall-clock span and busy time of all queues next to the per-stage sums; the CPU proofs of the exactness arguments are `tests/test_fg_turbo_v2.py`, and `runner/fg_lite_d3d12_check.py --turbo` checks the Turbo kernels against the CPU reference | | `clean/dx12/kernels/fg_exec_io.hlsl` | the executor's input capture (a game texture of any readable format into the arena's float16 / float32 image kinds) and output pack (the float16 image into a slot format: RGBA16F, RGBA8 / BGRA8, RGB10A2) | | `fg_limits.h` | `kFgMaxGenerated`, shared by the presenter and the runtime so one file can include both (the runtime contract's own status and real-only enums are `FgFrameStatus` / `FgFrameRealOnly`, distinct from the presenter's `FgStatus` / `FgRealOnlyReason`) | | `tools/gen_fg_runtime_tables.py`, `tests/test_fg_runtime_tables.py` | writes / checks the two generated headers (the map table; the fused plan and the weight fragments of constructed float16 patterns from `runner/fg_net1_mma.py`) | diff --git a/clean/fg/runner/fg_lite_d3d12_check.py b/clean/fg/runner/fg_lite_d3d12_check.py index 00049a14..bf6cc5e6 100644 --- a/clean/fg/runner/fg_lite_d3d12_check.py +++ b/clean/fg/runner/fg_lite_d3d12_check.py @@ -62,8 +62,12 @@ "fg_lite_p2c_inpaint", "fg_lite_p2c_inpaint_mut", "fg_lite_p2c_pull", "fg_lite_p2c_push", "fg_lite_p2c_fine", "fg_lite_hole_mask", "fg_lite_quality_init", "fg_lite_net1_input", "fg_lite_net1_output", "fg_lite_interm", "fg_lite_weights", "fg_lite_blend", "fg_lite_blend_mut"] +# Turbo v2 (--turbo): the fused / retiled kernels take the place of the ones they replace in the plan (and are built with +# them: clean/dx12/build_dx12.py --only includes them); every output is still compared with the CPU reference +TURBO_KERNELS = ["fg_lite_p2c_fine_mask", "fg_lite_p2c_inpaint_tiled", "fg_lite_interm_both"] +TURBO = False NET1_KERNELS = MMA.MCONV + list(MMA.MPAIR) + MMA.EXACT + ["fg_add_f16"] -KERNELS = LITE_KERNELS + NET1_KERNELS + ["native_fill"] +KERNELS = LITE_KERNELS + TURBO_KERNELS + NET1_KERNELS + ["native_fill"] MUTANTS = {"fg_lite_p2c_inpaint": "fg_lite_p2c_inpaint_mut", "fg_lite_blend": "fg_lite_blend_mut"} # negative controls taken at a given case and call (a launch that writes: the menu output on a latched game frame) NEG_AT = {"fg_lite_menu_output": ("menu_latch_3x", "f2_c")} @@ -158,6 +162,7 @@ def __init__(self, name, geom, settings, net1_path, params): if i != "out": self.bufs["n1a_" + i] = [n, None, SENT] self.frame, self.callno = -1, 0 + self.turbo, self.hole_fused = TURBO, False self.n1_frames, self.out_ids, self.dis_ids = [], [], [] self.tags = [] # per call: (frame, i) @@ -266,8 +271,12 @@ def call(self, c): fb(st.kmax), fb(st.tau)] self.step("fg_lite_p2c_unpack", nsc, a, [self.roles[x] for x in ("F", "E", "Fl", "Vf")], st_tag) elif name == "p2c_inpaint": - self.step("fg_lite_p2c_inpaint", nsc, [self.r("Fl"), self.r("G"), g.w1, g.h1], [self.roles["G"]], - st_tag) + if self.turbo: # 32 x 8 pixel tiles + self.steps.append(("fg_lite_p2c_inpaint_tiled", (-(-g.w1 // 32)) * (-(-g.h1 // 8)), + [self.r("Fl"), self.r("G"), g.w1, g.h1], [self.roles["G"]], st_tag)) + else: + self.step("fg_lite_p2c_inpaint", nsc, [self.r("Fl"), self.r("G"), g.w1, g.h1], [self.roles["G"]], + st_tag) elif name == "p2c_pull": for l in range(1, p["top"] + 1): wl, hl = g.levels[l] @@ -288,12 +297,23 @@ def call(self, c): self.step("fg_lite_p2c_push", lw * lh, [self.r("P%d" % (l + 1)), pw, ph, self.r("P%d" % l), lw, lh], [self.roles["P%d" % l]], st_tag) pw, ph = g.levels[1] - self.step("fg_lite_p2c_fine", nsc, [self.r("P1"), pw, ph, self.r("G"), self.r("F"), g.w1, g.h1], - [self.roles["F"]], st_tag) + if self.turbo and g.wd == g.w1 and g.hd == g.h1: + # the net1 grid is the scatter grid: the fine pass runs the hole mask (Hc := 1 first) + self.fill16(self.roles["Hc"], [0x3C00], st_tag) + self.step("fg_lite_p2c_fine_mask", nsc, + [self.r("P1"), pw, ph, self.r("G"), self.r("F"), g.w1, g.h1, self.r("Hc")], + [self.roles["F"], self.roles["Hc"]], st_tag) + self.hole_fused = True + else: + self.step("fg_lite_p2c_fine", nsc, [self.r("P1"), pw, ph, self.r("G"), self.r("F"), g.w1, g.h1], + [self.roles["F"]], st_tag) elif name == "hole_mask": - self.fill16(self.roles["Hc"], [0x3C00], st_tag) - self.step("fg_lite_hole_mask", g.wd * g.hd, [self.r("F"), g.w1, g.h1, self.r("Hc"), g.wd, g.hd], - [self.roles["Hc"]], st_tag) + if self.hole_fused: + self.hole_fused = False + else: + self.fill16(self.roles["Hc"], [0x3C00], st_tag) + self.step("fg_lite_hole_mask", g.wd * g.hd, [self.r("F"), g.w1, g.h1, self.r("Hc"), g.wd, g.hd], + [self.roles["Hc"]], st_tag) elif name == "quality_init": self.step("fg_lite_quality_init", g.wd * g.hd, [self.r("Dc"), self.r("Qc"), g.wd * g.hd], [self.roles["Qc"]], st_tag) @@ -326,6 +346,11 @@ def ref(a): [g.wd, g.hd, g.pad_l, g.pad_t, g.W0, g.H0, self.cs, 1 if self.ps == 1 else 16, 1 if p["ui_forcing"] else 0] self.step("fg_lite_net1_output", g.wd * g.hd, a, [self.roles[x] for x in ("NA", "NB", "m")], st_tag) + elif name == "interm" and self.turbo: # both passes in one launch, LDS-binned scatters + self.steps.append(("fg_lite_interm_both", (-(-g.w1 // 16)) * (-(-g.h1 // 16)), + [self.r("Mv"), self.r("Zc"), self.r("MA"), self.r("F"), self.r("Zp"), self.r("MB"), + g.w1, g.h1, fb(p["t"]), fb(st.s_k), int(c.depth_inverted), fb(T2), fb(st.tau)], + [self.roles["MA"], self.roles["MB"]], st_tag)) elif name == "interm": for ps_, src, z, tgt in ((0, "Mv", "Zc", "MA"), (1, "F", "Zp", "MB")): self.step("fg_lite_interm", nsc, [ps_, self.r(src), self.r(z), self.r(tgt), g.w1, g.h1, @@ -746,9 +771,15 @@ def main(argv=None): ap.add_argument("--verify", action="store_true") ap.add_argument("--report-timing", action="store_true") ap.add_argument("--only", default=None, help="comma-separated case names (--plan)") + ap.add_argument("--turbo", action="store_true", + help="plan the Turbo v2 kernels (fg_lite_p2c_fine_mask, fg_lite_p2c_inpaint_tiled, " + "fg_lite_interm_both) instead of the kernels they replace; use the same flag for --plan and " + "--verify") ap.add_argument("--timeout", type=int, default=85) ap.add_argument("--json", default=None) a = ap.parse_args(argv) + global TURBO + TURBO = a.turbo res = None if a.plan: m = plan(a.build, a.work, a.only.split(",") if a.only else None) diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index b003663d..2d0b0a98 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -43,8 +43,11 @@ enum Kernel : uint32_t { kDown2Srv, kDown4Srv, kMvecSrv, kIntermTiled, kPackPairs, kPullTiled, kPushTail, kDown2HudTile, kMConv2Mid, kN2h3b1u, kNet2MergePixels, kOutPullPack, kOutPushFinePack, kLiteBlendPack, kFullBlendMerge, + // Turbo v2: exact fused / retiled kernels, used only when their DXIL is present and the fuse lever is on + kFineMask, kInpaintTiled, kInterm2, kN2h3b1uS3, kKernelCount, }; +constexpr uint32_t kFirstTurbo = kFineMask; // a pipeline of these that the device refuses is dropped, not fatal constexpr uint32_t kFirstFull = kFullBlend; constexpr uint32_t kFirstOptional = kMConv2Narrow; @@ -111,7 +114,9 @@ const char* const kKernelNames[kKernelCount] = { "fg_mconv2_mid", "fg_net2_mconv_h3b1u", "fg_net2_merge_pixels", "fg_out_pull_pack", "fg_out_push_fine_pack", "fg_lite_blend_pack", "fg_full_blend_merge", + "fg_lite_p2c_fine_mask", "fg_lite_p2c_inpaint_tiled", "fg_lite_interm_both", "fg_net2_mconv_h3b1u_s3", }; +static_assert(sizeof(kKernelNames) / sizeof(*kKernelNames) == kKernelCount, "one name per kernel"); constexpr uint32_t kRootConstants = 59; // 2 runtime constants + up to 57 argument DWORDs constexpr uint32_t kMaxArgs = kRootConstants - 2; @@ -604,8 +609,11 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { std::map, size_t> prof_index; // Turbo v2 levers (fg_d3d12_executor.h FgD3d12ExecutorDesc): wanted at construction, active after Configure. - bool want_batch = true, want_hoist = true, want_dualq = true; + bool want_batch = true, want_hoist = true, want_dualq = true, want_fuse = true; bool batch_on = false, hoist_on = false, dualq_on = false; + bool hole_fused = false; // the fine pass already ran the hole mask of this frame (the HoleMask op is then empty) + // the fused / retiled kernels (kFineMask, kInpaintTiled, kInterm2) are used when present + bool Fused(uint32_t k) const { return want_fuse && pso[k] != nullptr; } ComPtr aux_queue; // the second compute queue (hoisted MA / MB work) ComPtr aux_fence; uint64_t aux_value = 0, aux_joined = 0; @@ -833,8 +841,14 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { pd.pRootSignature = root.Get(); pd.CS.pShaderBytecode = code[k].data(); pd.CS.BytecodeLength = code[k].size(); - if (FAILED(device->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso[k])))) + if (FAILED(device->CreateComputePipelineState(&pd, IID_PPV_ARGS(&pso[k])))) { + if (k >= kFirstTurbo) { // e.g. a device without 64-bit atomics on shared memory: the lever stays off + code[k].clear(); + pso[k].Reset(); + continue; + } return Fail(FgExecRefusal::PipelineFailed, std::string("pipeline ") + kKernelNames[k]); + } } pipelines_built = true; return FgExecResult::Ok; @@ -1739,7 +1753,10 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return true; } case FgOp::P2cInpaint: - D(r, kInpaint, groups_for(nsc), {R(kRoleFl), R(kRoleG), g.w1, g.h1}); + if (Fused(kInpaintTiled)) + D(r, kInpaintTiled, cdiv(g.w1, 32) * cdiv(g.h1, 8), {R(kRoleFl), R(kRoleG), g.w1, g.h1}); + else + D(r, kInpaint, groups_for(nsc), {R(kRoleFl), R(kRoleG), g.w1, g.h1}); return true; case FgOp::P2cPull: if (pso[kPullTiled]) { @@ -1795,10 +1812,23 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { {R(kRoleP1 + l), g.lw[l + 1], g.lh[l + 1], R(kRoleP1 + l - 1), g.lw[l], g.lh[l]}); if (l == 1) break; } + if (Fused(kFineMask) && g.wd == g.w1 && g.hd == g.h1) { + // the net1 grid is the scatter grid: the fine pass also runs the hole mask (Hc := 1 first) + const uint32_t p[4] = {0x3C00u, 0, 0, 0}; + Fill16(r, R(kRoleHc), FgRoleBytes(g, kRoleHc), p, 1, false); + D(r, kFineMask, groups_for(nsc), + {R(kRoleP1), g.lw[1], g.lh[1], R(kRoleG), R(kRoleF), g.w1, g.h1, R(kRoleHc)}); + hole_fused = true; + return true; + } D(r, kFine, groups_for(nsc), {R(kRoleP1), g.lw[1], g.lh[1], R(kRoleG), R(kRoleF), g.w1, g.h1}); return true; } case FgOp::HoleMask: { + if (hole_fused) { + hole_fused = false; + return true; + } const uint32_t p[4] = {0x3C00u, 0, 0, 0}; Fill16(r, R(kRoleHc), FgRoleBytes(g, kRoleHc), p, 1, false); D(r, kHoleMask, groups_for(static_cast(g.wd) * g.hd), @@ -1836,6 +1866,13 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { g.pad_l, g.pad_t, g.W0, g.H0, 1u, 16u, op.ui_forcing ? 1u : 0u}); return true; case FgOp::Interm: { + if (Fused(kInterm2)) { + // both passes in one launch: A (Mv, Zc -> MA) and B (F, Zp -> MB) + D(r, kInterm2, cdiv(g.w1, 16) * cdiv(g.h1, 16), + {R(kRoleMv), R(kRoleZc), R(kRoleMA), R(kRoleF), R(kRoleZp), R(kRoleMB), g.w1, g.h1, fb(op.t), + fb(st.s_k), inv, fb(t2), fb(st.tau)}); + return true; + } const uint32_t kernel = pso[kIntermTiled] ? kIntermTiled : kInterm; const uint32_t groups = kernel == kIntermTiled ? cdiv(g.w1, 16) * cdiv(g.h1, 16) : groups_for(nsc); D(r, kernel, groups, @@ -2016,7 +2053,8 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } if (o.heads) { if (n == 25 && pso[kN2h3b1u]) { - v.kernel = kN2h3b1u; + // the three heads staged in one pass (same arithmetic) when that kernel is there + v.kernel = Fused(kN2h3b1uS3) ? kN2h3b1uS3 : kN2h3b1u; groups = 1; } else { groups = 3; @@ -2440,27 +2478,14 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { EmitDispatch(r, d.kernel, d.groups, d.args, d.n, barrier); } - // Records the deferred launches of several frames (one list per frame). When every frame runs the same plan - // (same kernels and barrier needs at every position) the frames are interleaved: launch j of every frame back to - // back, the barrier only before the first of them. The frames write disjoint banks and read only the game - // frame's shared state, so the one barrier before launch j of frame 0 (which waits for every earlier launch of - // every frame) is all the dependencies of launch j need. Otherwise the frames are recorded one after the other - // with their own barriers. + // Records the deferred launches of several frames (one list per frame) in the order of FgInterleaveLaunches. void EmitFrames(Rec& r, const std::vector>& lists) { - if (lists.empty()) return; - bool same = true; - for (size_t f = 1; f < lists.size() && same; ++f) { - same = lists[f].size() == lists[0].size(); - for (size_t j = 0; same && j < lists[0].size(); ++j) - same = lists[f][j].kernel == lists[0][j].kernel && lists[f][j].barrier == lists[0][j].barrier; - } - if (!same) { - for (const auto& list : lists) - for (const Deferred& d : list) EmitDeferred(r, d, d.barrier, true); - return; - } - for (size_t j = 0; j < lists[0].size(); ++j) - for (size_t f = 0; f < lists.size(); ++f) EmitDeferred(r, lists[f][j], f == 0 && lists[0][j].barrier, f == 0); + std::vector> keys(lists.size()); + for (size_t f = 0; f < lists.size(); ++f) + for (const Deferred& d : lists[f]) keys[f].push_back({d.kernel, d.barrier}); + std::vector order; + FgInterleaveLaunches(keys, &order); // the rule (fg_exec_plan.h) is tested on its own + for (const FgLaunchSlot& s : order) EmitDeferred(r, lists[s.frame][s.index], s.barrier, s.mark_stage); } static bool SameBits(float a, float b) { return FgExecFloatBits(a) == FgExecFloatBits(b); } @@ -2536,6 +2561,7 @@ FgD3d12Executor::FgD3d12Executor(const FgD3d12ExecutorDesc& desc) : impl_(new Im impl_->want_batch = lever(desc.batch, "WG_FG_BATCH"); impl_->want_hoist = lever(desc.hoist, "WG_FG_HOIST"); impl_->want_dualq = lever(desc.dualq, "WG_FG_DUALQ"); + impl_->want_fuse = lever(desc.fuse, "WG_FG_FUSE"); if (desc.weights) { impl_->weights = *desc.weights; impl_->have_weights = true; @@ -2793,6 +2819,7 @@ FgExecResult FgD3d12Executor::RecordSharedGameFrame(const FgSharedDispatchDesc& const bool reset = !d.has_previous || (p.flags & kFgFlagReset) != 0; m.host.BeginFrame(f.lite, d.preset == FgPreset::B, f.hud, f.ui4, f.ui1, reset, &ops); m.frame = f; + m.hole_fused = false; if (f.lite) ++m.counters.lite_frames; else diff --git a/clean/fg/runtime/fg_d3d12_executor.h b/clean/fg/runtime/fg_d3d12_executor.h index 8c2ec06f..156f82fb 100644 --- a/clean/fg/runtime/fg_d3d12_executor.h +++ b/clean/fg/runtime/fg_d3d12_executor.h @@ -173,8 +173,12 @@ struct FgD3d12ExecutorDesc { // sit only between dependent layers (needs one scratch bank per index: max_generated banks). // - hoist (WG_FG_HOIST=0 off): the per-index MA / MB fills and the intermediate-time scatters run on the second // compute queue while the game frame's net1 runs (needs the second queue and banks). - // - dualq (WG_FG_DUALQ=0 off): the second compute queue; the downsample runs beside the motion / p2c chain. - int batch = -1, hoist = -1, dualq = -1; + // - dualq (WG_FG_DUALQ=0 off): the downsample runs on the game queue beside the motion / p2c chain on the + // producer queue (two recordings and a handoff each). + // - fuse (WG_FG_FUSE=0 off): the fused / retiled kernels fg_lite_p2c_fine_mask (fine pass + hole mask), + // fg_lite_p2c_inpaint_tiled and fg_lite_interm_both (both intermediate-time passes, LDS-binned scatters) replace + // their separate kernels when their DXIL is in the kernel folder. + int batch = -1, hoist = -1, dualq = -1, fuse = -1; // Developer frame dumps (off while dump_dir is empty; the ASI sets it only in a developer build): of the game // frames that generate, every dump_every-th one (at most dump_max), the game frame's slot image (game_.ppm) and // each generated slot image (gen__.ppm) are copied to a readback buffer after the slot write, and written as diff --git a/clean/fg/runtime/fg_exec_plan.cpp b/clean/fg/runtime/fg_exec_plan.cpp index f2f34eb3..4c674628 100644 --- a/clean/fg/runtime/fg_exec_plan.cpp +++ b/clean/fg/runtime/fg_exec_plan.cpp @@ -267,6 +267,24 @@ char FgExecR3Case(const FgExecFlags& f) { return f.hudless ? 'H' : '0'; } +void FgInterleaveLaunches(const std::vector>& frames, std::vector* out) { + out->clear(); + if (frames.empty()) return; + bool same = true; + for (size_t f = 1; f < frames.size() && same; ++f) { + same = frames[f].size() == frames[0].size(); + for (size_t j = 0; same && j < frames[0].size(); ++j) + same = frames[f][j].kernel == frames[0][j].kernel && frames[f][j].barrier == frames[0][j].barrier; + } + if (!same) { + for (uint32_t f = 0; f < frames.size(); ++f) + for (uint32_t j = 0; j < frames[f].size(); ++j) out->push_back({f, j, frames[f][j].barrier, true}); + return; + } + for (uint32_t j = 0; j < frames[0].size(); ++j) + for (uint32_t f = 0; f < frames.size(); ++f) out->push_back({f, j, f == 0 && frames[0][j].barrier, f == 0}); +} + const char* FgOpName(FgOp op) { switch (op) { case FgOp::Clear: return "clear"; diff --git a/clean/fg/runtime/fg_exec_plan.h b/clean/fg/runtime/fg_exec_plan.h index 9d76c740..4b32fab5 100644 --- a/clean/fg/runtime/fg_exec_plan.h +++ b/clean/fg/runtime/fg_exec_plan.h @@ -179,6 +179,25 @@ class FgExecHost { FgExecFrameInfo frame_; }; +// The order in which the launches of several generated indices that share one command list are recorded (the executor's +// RecordGeneratedBatch; plain C++ so that the rule is tested on its own). Every frame is the launch list of one index: +// its kernels and whether each launch needs a barrier before it (it reads what an earlier launch of the same index wrote). +struct FgLaunchKey { + uint32_t kernel = 0; + bool barrier = true; +}; +struct FgLaunchSlot { + uint32_t frame = 0, index = 0; // frame f's launch `index` + bool barrier = true; // a barrier is recorded before this launch + bool mark_stage = true; // the stage timestamp is written before this launch +}; +// Frames that run the same plan (equal launch counts, kernels and barrier needs at every position) are interleaved: +// launch j of every frame back to back, a barrier only before frame 0's launch j and only when it needs one (the frames +// write disjoint images and read only state that is final before the batch, so the barrier before frame 0's launch j, +// which waits for every launch recorded before it, also covers the other frames' launch j - 1). Any other set of frames +// is recorded frame after frame with each launch's own barrier flag. +void FgInterleaveLaunches(const std::vector>& frames, std::vector* out); + // net2's 25 convolutions (clean/fg/layout.py NET2): stored input channels, used input channels, outputs. struct FgNet2Layer { uint32_t cin, cin_used, cout; diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index 05d6bd67..660b0a52 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -164,6 +164,85 @@ void TestSigTable() { CHECK(std::memcmp(d.data(), want, 32) == 0); } +// Turbo v2: the order in which the launches of several indices sharing one command list are recorded, and the shape of an +// index's ops that the hoisted work (the first three) and the batch rely on. +void TestInterleave() { + g_case = "interleave"; + using Key = FgLaunchKey; + std::vector out; + FgInterleaveLaunches({}, &out); + CHECK(out.empty()); + // one frame: its own order and barrier flags + const std::vector plan = {{1, true}, {2, false}, {3, true}, {4, true}}; + FgInterleaveLaunches({plan}, &out); + CHECK(out.size() == 4); + for (uint32_t j = 0; j < out.size(); ++j) + CHECK(out[j].frame == 0 && out[j].index == j && out[j].barrier == plan[j].barrier && out[j].mark_stage); + // three frames of the same plan: launch j of every frame in turn, one barrier only before frame 0's launch j and + // only where the plan needs one; the stage mark only on frame 0 + FgInterleaveLaunches({plan, plan, plan}, &out); + CHECK(out.size() == 12); + bool order = true; + for (uint32_t j = 0; j < 4; ++j) + for (uint32_t f = 0; f < 3; ++f) { + const FgLaunchSlot& x = out[j * 3 + f]; + order = order && x.frame == f && x.index == j && x.mark_stage == (f == 0) && + x.barrier == (f == 0 && plan[j].barrier); + } + CHECK(order); + // every launch of every frame appears exactly once + int seen[3][4] = {}; + for (const FgLaunchSlot& x : out) ++seen[x.frame][x.index]; + bool once = true; + for (auto& row : seen) + for (int n : row) once = once && n == 1; + CHECK(once); + // frames of different plans (a different kernel, a different barrier need, a different length) are not interleaved: + // frame after frame with the frame's own barrier flags + const std::vector other_kernel = {{1, true}, {2, false}, {9, true}, {4, true}}; + const std::vector other_barrier = {{1, true}, {2, true}, {3, true}, {4, true}}; + const std::vector shorter = {{1, true}, {2, false}}; + for (const auto& frames : {std::vector>{plan, other_kernel}, + std::vector>{plan, other_barrier}, + std::vector>{plan, shorter}}) { + FgInterleaveLaunches(frames, &out); + size_t total = 0, at = 0; + for (const auto& f : frames) total += f.size(); + CHECK(out.size() == total); + bool sequential = out.size() == total; + for (uint32_t f = 0; f < frames.size(); ++f) + for (uint32_t j = 0; sequential && j < frames[f].size(); ++j, ++at) + sequential = out[at].frame == f && out[at].index == j && out[at].barrier == frames[f][j].barrier && + out[at].mark_stage; + CHECK(sequential); + } + // the hoisted work is the first three ops of an index with history (fills of MA / MB, then the intermediate-time + // scatters), for every index and preset; a game frame without history has none + for (const bool lite : {true, false}) { + FgExecSettings st; + FgExecGeometry g; + std::string why; + FgExecMakeGeometry(160, 90, &g, &why); + FgExecHost h; + h.Configure(st, g); + std::vector ops; + h.BeginFrame(lite, false, true, false, false, true, &ops); + std::vector pairs; + h.EndFrame(&pairs); + ops.clear(); + h.BeginFrame(lite, false, true, false, false, false, &ops); + CHECK(h.Frame().history); + for (uint32_t i = 1; i <= 5; ++i) { + std::vector idx; + h.IndexOps(FgIndexTime(i, 5), true, false, false, &idx); + CHECK(idx.size() >= 5 && idx[0].op == FgOp::Fill64 && idx[0].role == kRoleMA && idx[1].op == FgOp::Fill64 && + idx[1].role == kRoleMB && idx[2].op == FgOp::Interm && idx[3].op == FgOp::Weights); + const float t = FgIndexTime(i, 5); + CHECK(std::memcmp(&idx[2].t, &t, sizeof(float)) == 0); + } + } +} + void TestSchedule() { g_case = "schedule"; FgExecSettings st; @@ -1600,7 +1679,7 @@ bool UploadFixture(Gpu& gpu, ID3D12Resource* tex, FixtureRole role, uint32_t fra return gpu.Wait(); } -bool SlotsMatch(Gpu& gpu, const ExecutorSlots& actual, const ExecutorSlots& expected) { +bool SlotsMatch(Gpu& gpu, const ExecutorSlots& actual, const ExecutorSlots& expected, uint32_t count = 2) { // Read both sets of textures through identical footprints and compare only the texel bytes. D3D12_RESOURCE_DESC bd = {}; bd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -1609,10 +1688,10 @@ bool SlotsMatch(Gpu& gpu, const ExecutorSlots& actual, const ExecutorSlots& expe bd.MipLevels = 1; bd.SampleDesc.Count = 1; bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp[2][2] = {}; - UINT64 row_bytes[2] = {}; - UINT rows[2] = {}; - for (uint32_t i = 0; i < 2; ++i) { + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp[8][2] = {}; + UINT64 row_bytes[8] = {}; + UINT rows[8] = {}; + for (uint32_t i = 0; i < count; ++i) { const auto d = actual.textures[i]->GetDesc(); for (auto& dest : fp[i]) { UINT64 size = 0; @@ -1628,7 +1707,7 @@ bool SlotsMatch(Gpu& gpu, const ExecutorSlots& actual, const ExecutorSlots& expe nullptr, IID_PPV_ARGS(&readback))) || FAILED(gpu.alloc->Reset()) || FAILED(gpu.list->Reset(gpu.alloc.Get(), nullptr))) return false; - for (uint32_t i = 0; i < 2; ++i) { + for (uint32_t i = 0; i < count; ++i) { ID3D12Resource* srcs[] = {actual.textures[i].Get(), expected.textures[i].Get()}; for (uint32_t j = 0; j < 2; ++j) { D3D12_TEXTURE_COPY_LOCATION src = {}, dst = {}; @@ -1648,7 +1727,7 @@ bool SlotsMatch(Gpu& gpu, const ExecutorSlots& actual, const ExecutorSlots& expe if (FAILED(readback->Map(0, nullptr, &mapped))) return false; const auto* bytes = static_cast(mapped); bool exact = true; - for (uint32_t i = 0; i < 2; ++i) + for (uint32_t i = 0; i < count; ++i) for (uint32_t y = 0; y < rows[i] && exact; ++y) exact = std::memcmp(bytes + fp[i][0].Offset + y * fp[i][0].Footprint.RowPitch, bytes + fp[i][1].Offset + y * fp[i][1].Footprint.RowPitch, @@ -1802,6 +1881,129 @@ void TestInputSrvPaths(Gpu& gpu, const std::string& dxil, const std::string& ref if (errors >= 0) CHECK(errors == 0); } +// Turbo v2: every lever on (batched indices, hoisted per-index work on the second queue, the split shared work, the fused +// and retiled kernels) must give the same bytes as every lever off, in every generated slot and the real one, over several +// game frames (history, swaps), the presets A / B / C and N = 1 .. 5. Both executors read the same game textures and run +// the same kernel folder (`dxil`: the Turbo kernels sit beside the ones they replace). +void TestTurboExact(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights) { + g_case = "gpu-turbo-exact"; + { + std::ifstream probe(dxil + "/fg_lite_interm_both.dxil", std::ios::binary); + if (!probe) std::printf(" turbo: the Turbo v2 kernels are not in %s (batching, hoisting and the split only)\n", dxil.c_str()); + } + struct Case { + FgPreset preset; + uint32_t n, width, height; + DXGI_FORMAT colour; + }; + const Case cases[] = { + {FgPreset::C, 1, kW, kH, DXGI_FORMAT_B8G8R8A8_UNORM}, {FgPreset::C, 2, 131, 89, DXGI_FORMAT_B8G8R8A8_UNORM}, + {FgPreset::C, 5, kW, kH, DXGI_FORMAT_R16G16B16A16_FLOAT}, {FgPreset::A, 1, kW, kH, DXGI_FORMAT_B8G8R8A8_UNORM}, + {FgPreset::A, 3, 131, 89, DXGI_FORMAT_B8G8R8A8_UNORM}, {FgPreset::A, 5, kW, kH, DXGI_FORMAT_B8G8R8A8_UNORM}, + {FgPreset::B, 2, kW, kH, DXGI_FORMAT_R16G16B16A16_FLOAT}, + }; + for (const Case& c : cases) { + char name[96]; + std::snprintf(name, sizeof(name), "preset %c N=%u %ux%u", c.preset == FgPreset::A ? 'A' : c.preset == FgPreset::B ? 'B' : 'C', + c.n, c.width, c.height); + Game game; + const bool ready = game.Init(&gpu, c.colour, c.width, c.height) && game.Upload(1, false, true); + CHECK(ready); + if (!ready) return; + FgD3d12ExecutorDesc ed; + ed.dxil_dir = dxil; + ed.weights = &weights; + ed.enable_full = c.preset != FgPreset::C; + ed.batch = ed.hoist = ed.dualq = ed.fuse = 1; + FgD3d12Executor test(ed); + ed.batch = ed.hoist = ed.dualq = ed.fuse = 0; + FgD3d12Executor ref(ed); + FgCreateDesc create = CpuCreate(c.width, c.height); + create.device = gpu.device.Get(); + create.queue = gpu.queue.Get(); + create.preset = c.preset; + create.max_generated = c.n; + const auto ok = [&](FgD3d12Executor& exec, FgExecResult status) { + if (status != FgExecResult::Ok) std::printf(" turbo %s: %s (%s)\n", name, FgExecRefusalName(exec.LastRefusal()), exec.LastWhy().c_str()); + CHECK(status == FgExecResult::Ok); + return status == FgExecResult::Ok; + }; + ExecutorSlots test_slots, ref_slots; + for (uint32_t i = 0; i <= c.n; ++i) { + test_slots.textures[i] = game.Tex(c.colour); + ref_slots.textures[i] = game.Tex(c.colour); + } + if (!ok(test, test.Configure(create, 3)) || !ok(ref, ref.Configure(create, 3))) return; + if (!test.BindSlotTarget(&test_slots) || !ref.BindSlotTarget(&ref_slots)) { + CHECK(false); + return; + } + std::printf(" turbo %s: batch %d hoist %d dualq %d banks %u (reference: batch %d hoist %d dualq %d)\n", name, + test.BatchActive(), test.HoistActive(), test.DualQueueActive(), test.ScratchBanks(), + ref.BatchActive(), ref.HoistActive(), ref.DualQueueActive()); + CHECK(!ref.BatchActive() && !ref.HoistActive() && !ref.DualQueueActive()); + bool exact_all = true; + for (uint64_t token = 1; token <= 4; ++token) { + if (!game.Upload(static_cast(token), false, token == 1)) { + CHECK(false); + return; + } + FgFramePacket packet = game.Packet(); + packet.frame_token = token; + packet.motion_scale_x = 8.0f; + packet.motion_scale_y = 8.0f; + FgSharedDispatchDesc shared; + shared.frame_token = token; + shared.preset = c.preset; + shared.has_previous = token > 1; + shared.generated_count = c.n; + shared.generates = token > 1; + shared.packet = &packet; + FgSharedResult result; + if (!ok(test, test.RecordSharedGameFrame(shared, &result)) || + !ok(ref, ref.RecordSharedGameFrame(shared, &result))) + return; + FgReadyFence fences[kFgMaxGenerated + 1]; + if (token > 1) { + FgIndexDispatchDesc gens[kFgMaxGenerated]; + for (uint32_t k = 0; k < c.n; ++k) { + gens[k].frame_token = token; + gens[k].index = k + 1; + gens[k].generated_count = c.n; + gens[k].is_last_index = k + 1 == c.n; + gens[k].preset = c.preset; + gens[k].t = FgIndexTime(k + 1, c.n); + gens[k].slot.slot = k; + gens[k].slot.reserved = true; + } + uint32_t done = 0; + const FgExecResult batched = c.n > 1 ? test.RecordGeneratedBatch(gens, c.n, fences, &done) + : test.RecordGeneratedIndex(gens[0], &fences[0]); + if (!ok(test, batched)) return; + for (uint32_t k = 0; k < c.n; ++k) + if (!ok(ref, ref.RecordGeneratedIndex(gens[k], &fences[k]))) return; + } + FgRealDispatchDesc real; + real.frame_token = token; + real.slot.slot = c.n; + real.slot.reserved = true; + if (!ok(test, test.RecordRealEndpoint(real, &fences[c.n])) || + !ok(ref, ref.RecordRealEndpoint(real, &fences[c.n]))) + return; + const bool idle = test.WaitIdle(30000) && ref.WaitIdle(30000); + CHECK(idle); + if (!idle) return; + const bool exact = SlotsMatch(gpu, test_slots, ref_slots, c.n + 1); + if (!exact) std::printf(" turbo %s: slots differ at game frame %llu\n", name, static_cast(token)); + exact_all = exact_all && exact; + CHECK(exact); + } + if (exact_all) std::printf(" turbo %s: 4 game frames, 0 byte differences\n", name); + } + const int64_t errors = gpu.DebugErrors(); + if (errors >= 0) CHECK(errors == 0); +} + struct BenchOptions { uint32_t gen = 1, warmup = 8, timed = 30; std::string presets = "AC"; @@ -1989,6 +2191,7 @@ int main(int argc, char** argv) { TestHalf(); TestSigTable(); TestSchedule(); + TestInterleave(); TestNet2FastPlan(); TestRefusals(weights); TestMotionFormats(); @@ -2050,6 +2253,7 @@ int main(int argc, char** argv) { } if (only.empty() || only.find("input-srv") != std::string::npos) TestInputSrvPaths(g, dxil, reference_dxil, weights); + if (only.empty() || only.find("turbo") != std::string::npos) TestTurboExact(g, dxil, weights); if (only.empty()) TestBrokenKernels(g, dxil, weights, scratch); } } diff --git a/clean/fg/tests/test_fg_turbo_v2.py b/clean/fg/tests/test_fg_turbo_v2.py new file mode 100644 index 00000000..806bc090 --- /dev/null +++ b/clean/fg/tests/test_fg_turbo_v2.py @@ -0,0 +1,167 @@ +# SPDX-License-Identifier: MIT +"""CPU proofs of the exactness arguments behind frame generation's Turbo v2 kernels (clean/dx12/kernels/fg_lite_p2c.hlsl, +fg_lite_g.hlsl). Each class re-states what the old kernel computes and what the new kernel computes, step by step as the +HLSL does, and compares them on random and edge inputs. The kernels themselves are checked on a GPU +(clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp --gpu, paired runs against the kernels they replace).""" +import unittest + +import numpy as np + +F32 = np.float32 + + +# ---- fg_lite_p2c_inpaint_tiled == fg_lite_p2c_inpaint ------------------------------------------------------------------- +def inpaint_old(fl, w1, h1): + """fg_lite_p2c_inpaint: bits of the 5 x 5 neighbourhood by flat index and column mask, nine 3 x 3 windows.""" + size = w1 * h1 + out = np.zeros(size, dtype=np.uint32) + for idx in range(size): + x = idx % w1 + xmask = ((1 << min(w1 - x + 2, 5)) - 1) & (31 << max(2 - x, 0)) + bits = 0 + for j in range(5): + p = idx + (j - 2) * w1 - 2 + row = 0 + for i in range(5): + q = p + i + if 0 <= q < size and (int(fl[q]) & 2): + row |= 1 << i + bits |= (row & xmask) << (j * 5) + inp = True + for j in range(3): + for i in range(3): + mask = 0x1ce7 << (j * 5 + i) + inp = inp and (bits & mask) != 0 + dyn = (int(fl[idx]) & 1) != 0 + out[idx] = (2 if (dyn and not inp) else 0) | (1 if inp else 0) + return out + + +def inpaint_tiled(fl, w1, h1): + """fg_lite_p2c_inpaint_tiled: 32 x 8 tiles, 36-bit row masks (columns x0 - 2 .. x0 + 33), dilate then erode.""" + out = np.zeros(w1 * h1, dtype=np.uint32) + + def flag(x, y): + return 0 <= x < w1 and 0 <= y < h1 and (int(fl[y * w1 + x]) & 2) != 0 + + for ty in range((h1 + 7) // 8): + for tx in range((w1 + 31) // 32): + x0, y0 = tx * 32, ty * 8 + row = [0] * 12 + for r in range(12): + m = 0 + for c in range(36): + if flag(x0 - 2 + c, y0 - 2 + r): + m |= 1 << c + row[r] = m + dil = [b | (b >> 1) | (b >> 2) for b in row] + dv = [dil[r] | dil[r + 1] | dil[r + 2] for r in range(10)] + for wave in range(8): + for lane in range(32): + x, y = x0 + lane, y0 + wave + if x >= w1 or y >= h1: + continue + e = dv[wave] & dv[wave + 1] & dv[wave + 2] + inp = ((e >> lane) & 7) == 7 + dyn = (int(fl[y * w1 + x]) & 1) != 0 + out[y * w1 + x] = (2 if (dyn and not inp) else 0) | (1 if inp else 0) + return out + + +class InpaintTiledTest(unittest.TestCase): + def test_equal_on_random_and_edge_grids(self): + rng = np.random.default_rng(7) + sizes = [(1, 1), (2, 3), (3, 2), (5, 9), (31, 8), (32, 8), (33, 9), (40, 17), (65, 7), (64, 16), (1, 20), (20, 1)] + for w1, h1 in sizes: + for density in (0.0, 0.05, 0.3, 0.7, 0.97, 1.0): + fl = np.zeros(w1 * h1, dtype=np.uint32) + fl |= (rng.random(w1 * h1) < density).astype(np.uint32) * 2 + fl |= (rng.random(w1 * h1) < 0.5).astype(np.uint32) + np.testing.assert_array_equal(inpaint_old(fl, w1, h1), inpaint_tiled(fl, w1, h1), + err_msg="%dx%d density %.2f" % (w1, h1, density)) + + +# ---- fg_lite_p2c_fine_mask: the hole mask reads F at the pixel's own index when the grids are equal --------------------- +class HoleMaskGridTest(unittest.TestCase): + def test_nearest_index_of_a_centre_is_the_pixel(self): + """fg_centre(i, n) = sat(fl((i + 0.5) * (1 / n))); fg_nearest_index(X, n) = floor(X * n): i for every i, n.""" + for n in list(range(1, 300)) + [511, 512, 513, 640, 720, 1023, 1024, 1279, 1280, 1281, 1920, 2048, 2880, 3840, + 4095, 4096, 8191, 8192]: + i = np.arange(n, dtype=F32) + rcp = F32(1.0) / F32(n) + u = np.clip((i + F32(0.5)) * rcp, F32(0.0), F32(1.0)).astype(F32) + idx = np.clip(np.floor(u * F32(n)).astype(np.int64), 0, n - 1) + np.testing.assert_array_equal(idx, np.arange(n), err_msg="n = %d" % n) + + +# ---- fg_lite_interm_both: LDS-binned minima == one global atomic minimum per scatter ---------------------------------- +EMPTY = 0x7FFFFFFF7FFFFFFF + + +def to_i64(hi, lo): + v = (hi << 32) | lo + return v - (1 << 64) if v >= (1 << 63) else v + + +class BinnedMinimumTest(unittest.TestCase): + def run_case(self, rng, w1, h1, tile_ox, tile_oy, disp, footprint, hi_range): + # sources of one 16 x 16 tile aimed at targets around origin + displacement (+ per-pixel noise) + scatters = [] + for sy in range(16): + for sx in range(16): + x, y = tile_ox + sx, tile_oy + sy + if x >= w1 or y >= h1: + continue + dx = disp[0] + int(rng.integers(-3, 4)) + dy = disp[1] + int(rng.integers(-3, 4)) + hi = int(rng.integers(*hi_range)) + lo = int(rng.integers(0, 1 << 32)) + v = to_i64(hi, lo) + for jj in range(footprint): + for ii in range(footprint): + tx, ty = x + dx + ii, y + dy + jj + if 0 <= tx < w1 and 0 <= ty < h1: + scatters.append((tx, ty, v)) + init = np.full(w1 * h1, EMPTY, dtype=np.int64) + direct = init.copy() + for tx, ty, v in scatters: + direct[ty * w1 + tx] = min(int(direct[ty * w1 + tx]), v) + # the kernel: window around the centre displacement, cells start empty, outside targets go straight to global + wx0, wy0 = tile_ox + disp[0] - 8, tile_oy + disp[1] - 8 + cell = np.full(32 * 32, EMPTY, dtype=np.int64) + binned = init.copy() + for tx, ty, v in scatters: + cx, cy = tx - wx0, ty - wy0 + if 0 <= cx < 32 and 0 <= cy < 32: + cell[cy * 32 + cx] = min(int(cell[cy * 32 + cx]), v) + else: + binned[ty * w1 + tx] = min(int(binned[ty * w1 + tx]), v) + for c in range(1024): + if int(cell[c]) < EMPTY: + gx, gy = wx0 + (c & 31), wy0 + (c >> 5) + binned[gy * w1 + gx] = min(int(binned[gy * w1 + gx]), int(cell[c])) + np.testing.assert_array_equal(direct, binned) + return len(scatters) + + def test_random_tiles(self): + rng = np.random.default_rng(11) + n = 0 + for _ in range(40): + w1, h1 = int(rng.integers(20, 90)), int(rng.integers(20, 90)) + ox, oy = int(rng.integers(0, w1)) // 16 * 16, int(rng.integers(0, h1)) // 16 * 16 + disp = (int(rng.integers(-30, 30)), int(rng.integers(-30, 30))) + footprint = int(rng.integers(2, 6)) + # keys: ordinary positive float bit patterns, and values above / at the empty element + hi_range = [(0x3F000000, 0x40000000), (0x7FFFFFF0, 0x7FFFFFFF), (0, 0x7FFFFFFF)][int(rng.integers(0, 3))] + n += self.run_case(rng, w1, h1, ox, oy, disp, footprint, hi_range) + self.assertGreater(n, 1000) + + def test_a_value_above_the_empty_element_never_wins(self): + # hi == 0x7FFFFFFF and a low word above 0x7FFFFFFF is larger than the empty element as a signed 64-bit value + v = to_i64(0x7FFFFFFF, 0xFFFFFFFF) + self.assertGreater(v, EMPTY) + self.assertEqual(min(EMPTY, v), EMPTY) + + +if __name__ == "__main__": + unittest.main() From 92c5c2f63f9eca713224ef2485e8606dedc14c77 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:16:13 -0500 Subject: [PATCH 09/15] Frame generation (D3D12): the benchmark takes --fuse 0|1 beside the other lever switches --- clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index 660b0a52..52988ad1 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -12,8 +12,8 @@ // [--gen N] N = 1..5 generated images per game frame (2x .. 6x), really recorded (default 1) // [--preset AC] which presets (default AC) [--timed N] [--warmup N] // [--kprof] per-launch profile: kernel, workgroups, time per call (serialises the queue a little) -// [--batch 0|1] [--hoist 0|1] [--dualq 0|1] Turbo v2 levers for paired A / B runs (default: on, or the -// environment WG_FG_BATCH / WG_FG_HOIST / WG_FG_DUALQ = 0) +// [--batch 0|1] [--hoist 0|1] [--dualq 0|1] [--fuse 0|1] Turbo v2 levers for paired A / B runs (default: on, +// or the environment WG_FG_BATCH / _HOIST / _DUALQ / _FUSE = 0) // The report has the per-stage sums and the honest multi-queue numbers: the wall-clock GPU span and the busy // time per game frame over the timed window (overlap between queues is counted once there, twice in the sums). // --reference-dxil compare direct-SRV output bytes against the captured path built with these kernels @@ -2008,7 +2008,7 @@ struct BenchOptions { uint32_t gen = 1, warmup = 8, timed = 30; std::string presets = "AC"; bool kprof = false; - int batch = -1, hoist = -1, dualq = -1; // -1: the environment (default on) + int batch = -1, hoist = -1, dualq = -1, fuse = -1; // -1: the environment (default on) }; bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, FgPreset preset, @@ -2035,6 +2035,7 @@ bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, F ed.batch = bo.batch; ed.hoist = bo.hoist; ed.dualq = bo.dualq; + ed.fuse = bo.fuse; FgD3d12Executor exec(ed); const auto ok = [&](FgExecResult s) { if (s == FgExecResult::Ok) return true; @@ -2161,6 +2162,7 @@ int main(int argc, char** argv) { if (std::strcmp(argv[i], "--batch") == 0 && i + 1 < argc) bo.batch = std::atoi(argv[++i]); if (std::strcmp(argv[i], "--hoist") == 0 && i + 1 < argc) bo.hoist = std::atoi(argv[++i]); if (std::strcmp(argv[i], "--dualq") == 0 && i + 1 < argc) bo.dualq = std::atoi(argv[++i]); + if (std::strcmp(argv[i], "--fuse") == 0 && i + 1 < argc) bo.fuse = std::atoi(argv[++i]); if (std::strcmp(argv[i], "--dxil") == 0 && i + 1 < argc) dxil = argv[++i]; if (std::strcmp(argv[i], "--reference-dxil") == 0 && i + 1 < argc) reference_dxil = argv[++i]; if (std::strcmp(argv[i], "--scratch") == 0 && i + 1 < argc) scratch = argv[++i]; From 55923d5ad7498279bfe2c8658a1854a7ac7ac308 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:55:34 -0500 Subject: [PATCH 10/15] Frame generation (D3D12): Wave 1B fusions (net1 cells in LDS, net2 residual pairs, upwarp in L14's staging, blend weights in the blends, pyramid tail, RGB X0 / X1), all exact and switchable (WG_FG_FUSE2=0) Eighteen kernels beside the ones they replace (whose DXIL is byte-identical to the previous build); each lever is used only when its kernels are in the kernel folder and its bit is wanted (FgD3d12ExecutorDesc::fuse2: 0 off, 1 all, or a mask). - fg_mconv2_mid_cells: net1_01 builds its cells in LDS from the images fg_lite_net1_input packs (and writes Qc / Om itself): no input launch, no cell tensor round trip. - fg_net2_mpair_res_c64 / _c32: net2's residual pairs (L4+L5 .. L10+L11, L16+L17 .. L22+L23) in one launch on 14 x 6 interiors; the first layer runs on the region with its border and stays in LDS; both layers are the single-layer kernels' code. - fg_net2_mconv_m1b2_uw / _m1b2s_uw: L14 evaluates the upwarp for its staged tile (shared with fg_net2_upwarp through fg_net2_upwarp.hlsli) and writes U4 / U1 / U3 itself: no y tensor, no upwarp launch. - fg_lite_blend_w / _pack_w, fg_full_blend_w / _merge_w: the blend builds the W texels its tile's taps touch in LDS (fg_weight_texel, a copy of fg_lite_weights' body): no weights launch. - fg_out_tail (the coarsest pushes in one workgroup, as many levels as fit 28 KB) and fg_out_push_fine_l1 / _pack_l1 (level 1 pushed on the spot at the holes' taps). - fg_full_blend_*_x3 / fg_out_pull_x3: X0 / X1 stored as 3 x float16 (nothing reads their alpha). RGA (gfx1201): 0 spills, 0 scratch, at most 152 VGPRs. CPU proofs of the exactness arguments in clean/fg/tests/test_fg_turbo_v2.py; test_fg_d3d12_e2e --gpu --only turbo compares every lever on against every lever off and Wave 1B alone against Wave 1, byte for byte; --bench takes --fuse2 0|1|MASK. --- clean/dx12/hlsl/fg_full_up.hlsli | 30 ++ clean/dx12/hlsl/fg_net1_pixel.hlsli | 51 +++ clean/dx12/hlsl/fg_net2_upwarp.hlsli | 85 +++++ clean/dx12/hlsl/fg_weights.hlsli | 23 ++ clean/dx12/kernels/fg_full_blend.hlsl | 139 +++++++ clean/dx12/kernels/fg_lite_blend.hlsl | 111 +++++- clean/dx12/kernels/fg_mconv.hlsl | 108 ++++++ clean/dx12/kernels/fg_net2_mconv.hlsl | 168 ++++++++- clean/dx12/kernels/fg_net2_upwarp.hlsl | 74 +--- clean/dx12/kernels/fg_out_pull.hlsl | 28 +- clean/dx12/kernels/fg_out_push.hlsl | 113 +++++- clean/fg/README.md | 2 +- clean/fg/runtime/fg_d3d12_executor.cpp | 216 ++++++++++- clean/fg/runtime/fg_d3d12_executor.h | 12 +- clean/fg/runtime/fg_exec_plan.cpp | 5 +- clean/fg/runtime/fg_exec_plan.h | 1 + clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 43 ++- clean/fg/tests/test_fg_turbo_v2.py | 377 +++++++++++++++++++ 18 files changed, 1466 insertions(+), 120 deletions(-) create mode 100644 clean/dx12/hlsl/fg_full_up.hlsli create mode 100644 clean/dx12/hlsl/fg_net1_pixel.hlsli create mode 100644 clean/dx12/hlsl/fg_net2_upwarp.hlsli create mode 100644 clean/dx12/hlsl/fg_weights.hlsli diff --git a/clean/dx12/hlsl/fg_full_up.hlsli b/clean/dx12/hlsl/fg_full_up.hlsli new file mode 100644 index 00000000..c740b854 --- /dev/null +++ b/clean/dx12/hlsl/fg_full_up.hlsli @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): the output pyramid's 9/3/3/1 upsample on four already-loaded taps, for the kernels whose taps +// do not come from the arena (fg_out_push.hlsl FGU_TAIL: LDS; FGU_L1: texels pushed on the fly). It is the second half of +// fgf_up (fg_full.hlsli), line for line: clean/fg/tests/test_fg_turbo_v2.py compares the two texts. Include after +// fg_full.hlsli. +#pragma once + +// fgf_up's taps: the element indices (iP, iX, iY, iD) of the coarse level (wc x hc) around fine element (qx, qy) +void fgf_up_idx(int wc, int hc, int qx, int qy, out int iP, out int iX, out int iY, out int iD) +{ + const int px = qx >> 1, py = qy >> 1; + const int nx = clamp(px + ((qx & 1) != 0 ? 1 : -1), 0, wc - 1); + const int ny = clamp(py + ((qy & 1) != 0 ? 1 : -1), 0, hc - 1); + iP = py * wc + px; + iX = py * wc + nx; + iY = ny * wc + px; + iD = ny * wc + nx; +} + +// fgf_up's arithmetic from the four taps' float values (eP: own column and row, eX: neighbour column, eY: neighbour row, +// eD: both) +float4 fgf_up_taps(float4 eP, float4 eX, float4 eY, float4 eD) +{ + const float z = fgf_zero(); + const float ws = mad(eD.w, 0.0625f, mad(eY.w, 0.1875f, mad(eX.w, 0.1875f, mad(eP.w, 0.5625f, z)))); + const float3 vs = mad(fgf_opq3(eD.xyz * eD.w), 0.0625f, mad(fgf_opq3(eY.xyz * eY.w), 0.1875f, + mad(fgf_opq3(eX.xyz * eX.w), 0.1875f, mad(fgf_opq3(eP.xyz * eP.w), 0.5625f, z)))); + const float den = min(max(ws, 1e-12f), 1.0f); + return float4(wg_div(vs.x, den), wg_div(vs.y, den), wg_div(vs.z, den), ws); +} diff --git a/clean/dx12/hlsl/fg_net1_pixel.hlsli b/clean/dx12/hlsl/fg_net1_pixel.hlsli new file mode 100644 index 00000000..376992aa --- /dev/null +++ b/clean/dx12/hlsl/fg_net1_pixel.hlsli @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): the ten cell values of one net1 image pixel, for fg_mconv2_mid_cells (which builds net1_01's +// staged cells in LDS, fg_mconv.hlsl FG_CELLS). It is fg_lite_net1_input's lane work (fg_lite_net1io.hlsl FG_K == 3, left as +// it was so that its DXIL stays byte-identical), line for line: clean/fg/tests/test_fg_turbo_v2.py compares the two +// texts. The including file defines the argument block +// (ld, dc, dp, fin, mv, eimg, hc, hp, qp, mimg, qc, om: arena offsets; wd, hd, w1, h1: the net1 grid and the scatter grid) +// and includes wg_platform.hlsli and fg_lite_common.hlsli first. +#pragma once + +float fg_warp(float3 a, float3 b) +{ + const float3 d = abs(a - b); + return fg_sat(fg_adiv(d.z + fg_opq(d.x + d.y), 3.0f)); +} + +// The values of image pixel (x, y), all zero when not active or outside the image (x in [0, wd), y in [0, hd)). With store_side the pixel +// also writes its Qc = (v6, v2) and Om = sat((E Hp) Hc) texels. +void fg_net1_pixel(int x, int y, bool active, bool store_side, out float vals[10]) +{ + [unroll] for (int i = 0; i < 10; ++i) vals[i] = 0.0f; + if (active && x >= 0 && x < (int)wd && y >= 0 && y < (int)hd) + { + const uint pi = (uint)y * wd + (uint)x; + const float u = fg_centre((uint)x, wd), v = fg_centre((uint)y, hd); + const float4 dcv = fg_texel(dc, 4u, pi), dpv = fg_texel(dp, 4u, pi); + const float4 f = fg_read_nearest(fin, 2u, (int)w1, (int)h1, u, v); + const float su = u + fg_adiv(f.x, (float)w1), sv = v + fg_adiv(f.y, (float)h1); + const float v2 = fg_warp(fg_read_linear(dc, 4u, (int)wd, (int)hd, su, sv).xyz, dpv.xyz); + const float4 m = fg_read_nearest(mv, 5u, (int)w1, (int)h1, u, v); + const float v6 = fg_warp(fg_read_linear(dp, 4u, (int)wd, (int)hd, u + m.x, v + m.y).xyz, dcv.xyz); + const float e = fg_read_nearest(eimg, 1u, (int)w1, (int)h1, u, v).x; + const float hcv = fg_read_nearest(hc, 1u, (int)wd, (int)hd, u, v).x; + const float hpv = fg_read_nearest(hp, 1u, (int)wd, (int)hd, u, v).x; + const float mm = fg_texel(mimg, 1u, pi).x; + vals[0] = fg_texel(ld, 1u, pi).x; + vals[1] = fg_luma(dpv.xyz); + vals[2] = v2; + vals[3] = fg_texel(qp, 2u, pi).x; + vals[4] = e; + vals[5] = fg_luma(dcv.xyz); + vals[6] = v6; + vals[7] = hcv; + vals[8] = mm; + vals[9] = 1.0f - mm; + if (store_side) + { + fg_st_h2(qc, pi, v6, v2); + fg_st_h1(om, pi, fg_sat(fg_mul(fg_mul(e, hpv), hcv))); + } + } +} diff --git a/clean/dx12/hlsl/fg_net2_upwarp.hlsli b/clean/dx12/hlsl/fg_net2_upwarp.hlsli new file mode 100644 index 00000000..b037283b --- /dev/null +++ b/clean/dx12/hlsl/fg_net2_upwarp.hlsli @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): net2's head upsample + warp-merge of ONE pixel of the W x H grid (fg_net2_upwarp's lane work), +// shared by fg_net2_upwarp (which stores y, U4, U1, U3) and fg_net2_mconv_m1b2_uw (which builds L14's input tile from it in +// LDS, fg_net2_mconv.hlsl FG_UPWARP_STAGE): one definition, the same bits. The including file defines the argument block +// (ib, ic, ia, a4, a1, a3, W, H: arena offsets and the grid size), FG_NATIVE_UP = 1, and includes wg_platform.hlsli, +// fg_net2.hlsli and fg_net2_fast.hlsli first. +#pragma once + +// the 8 head channels of half-resolution pixel q +uint4 fg_heads8(int q) +{ + const uint2 h4 = wg_ld64(a4, (uint)q * 8u); + const uint h1 = wg_ld16(a1, (uint)q * 2u); + const uint c0 = wg_ld16(a3, (uint)(q * 3) * 2u), c1 = wg_ld16(a3, (uint)(q * 3 + 1) * 2u); + const uint c2 = wg_ld16(a3, (uint)(q * 3 + 2) * 2u); + return uint4(h4.x, h4.y, h1 | (c0 << 16), c1 | (c2 << 16)); +} + +// fg_net2_warp's sample point and weights for the displacement (ux, uy) at pixel (px_, py_) +struct FgSample { int x0; int x1; int y0; int y1; float w00; float w10; float w01; float w11; }; +FgSample fg_sample(uint ux, uint uy, int px_, int py_) +{ + FgSample s; + const uint sx = fg2_fma(FG2_TWO16, ux, wg_f2h((float)px_)); + const uint sy = fg2_fma(FG2_TWO16, uy, wg_f2h((float)py_)); + const float fX0 = floor(wg_h2f(sx)); + const float fY0 = floor(wg_h2f(sy)); + const uint fx = wg_f2h(wg_h2f(sx) - fX0); + const uint fy = wg_f2h(wg_h2f(sy) - fY0); + const int X0 = (int)fX0; + const int Y0 = (int)fY0; + s.x0 = clamp(X0, 0, W - 1); s.x1 = clamp(X0 + 1, 0, W - 1); + s.y0 = clamp(Y0, 0, H - 1); s.y1 = clamp(Y0 + 1, 0, H - 1); + const uint gx = wg_f2h(1.0f - wg_h2f(fx)); + const uint gy = wg_f2h(1.0f - wg_h2f(fy)); + s.w00 = wg_h2f(fg2_mul(gx, gy)); s.w10 = wg_h2f(fg2_mul(fx, gy)); + s.w01 = wg_h2f(fg2_mul(gx, fy)); s.w11 = wg_h2f(fg2_mul(fx, fy)); + return s; +} + +// 4 channels of Ib at (yy, xx) and 4 of Ic at (zy, zx) as 8 values +uint4 fg_pair8(int yy, int xx, int zy, int zx) +{ + const uint2 b = wg_ld64(ib, (uint)((yy * W + xx) * 4) * 2u); + const uint2 c = wg_ld64(ic, (uint)((zy * W + zx) * 4) * 2u); + return uint4(b.x, b.y, c.x, c.y); +} + +// The taps have fixed FP16 weights on the 2x grid; preserve the extrapolation at pixel zero. +Fg2Tap fg_upwarp_tap(int o, int n) +{ + const bool odd = (o & 1) != 0; + const int i = (o >> 1) - (int)!odd; + Fg2Tap t; + t.i0 = clamp(i, 0, n - 1); + t.i1 = min(i + 1, n - 1); + t.w0 = select(o == 0, 0x3d00u, select(odd, 0x3a00u, FG2_QUARTER16)); + t.w1 = select(o == 0, 0xb400u, select(odd, FG2_QUARTER16, 0x3a00u)); + return t; +} + +// The upsampled heads U (8 values: A4 0..3, A1, A3 0..2) and the warped 8 values val of pixel p (0 <= p < W x H), as +// fg_net2_upwarp computes them; every lane of the wave takes part (the upsample and the conversions are wave operations). +void fg_upwarp_eval(int p, out uint4 U, out uint4 val) +{ + const int py_ = p / W, px_ = p - (p / W) * W; + const int wi = W / 2, hi = H / 2; + const Fg2Tap tX = fg_upwarp_tap(px_, wi), tY = fg_upwarp_tap(py_, hi); + const uint4 top = fg_up_axis8(tX, fg_heads8(tY.i0 * wi + tX.i0), fg_heads8(tY.i0 * wi + tX.i1)); + const uint4 bottom = fg_up_axis8(tX, fg_heads8(tY.i1 * wi + tX.i0), fg_heads8(tY.i1 * wi + tX.i1)); + U = fg_up_axis8(tY, top, bottom); + + const FgSample sb = fg_sample(fg_half(U, 0u), fg_half(U, 1u), px_, py_); + const FgSample sc = fg_sample(fg_half(U, 2u), fg_half(U, 3u), px_, py_); + float w00[8], w10[8], w01[8], w11[8]; + [unroll] for (int i = 0; i < 4; ++i) { + w00[i] = sb.w00; w10[i] = sb.w10; w01[i] = sb.w01; w11[i] = sb.w11; + w00[i + 4] = sc.w00; w10[i + 4] = sc.w10; w01[i + 4] = sc.w01; w11[i + 4] = sc.w11; + } + const uint4 p00 = fg_pair8(sb.y0, sb.x0, sc.y0, sc.x0), p01 = fg_pair8(sb.y0, sb.x1, sc.y0, sc.x1); + const uint4 p10 = fg_pair8(sb.y1, sb.x0, sc.y1, sc.x0), p11 = fg_pair8(sb.y1, sb.x1, sc.y1, sc.x1); + uint4 acc = fg_fma8v(w10, p01, fg_mul8v(w00, p00)); + acc = fg_fma8v(w01, p10, acc); + val = fg_fma8v(w11, p11, acc); +} diff --git a/clean/dx12/hlsl/fg_weights.hlsli b/clean/dx12/hlsl/fg_weights.hlsli new file mode 100644 index 00000000..0cc9c6ce --- /dev/null +++ b/clean/dx12/hlsl/fg_weights.hlsli @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): the blend weight of one scatter-grid texel, shared by fg_lite_weights (which stores it) and +// the blends that build their W tile in LDS (fg_lite_blend FG_WEIGHTS, fg_full_blend FGB_WEIGHTS): one definition, so +// both produce the same packed float16 x 2 word (clean/fg/reference/stages_common.py blend_weights). +// The body is a copy of fg_lite_weights' (fg_lite_g.hlsl FG_K == 2), which is left as it was so that its DXIL stays +// byte-identical; clean/fg/tests/test_fg_turbo_v2.py compares the two texts line by line. +// W(x, y) = (sigma(NA at the MB vector - NA co-located), sigma(NB at the MA vector - NB co-located)), each rounded to +// float16 (the driver conversion, fg_pack_h2). Include after fg_lite_common.hlsli. +#pragma once + +// ma / mb: scatter-grid 64-bit words (w1 x h1); na / nb: net1 logit pairs (wd x hd, float16 x 2); (x, y): the texel. +uint fg_weight_texel(uint ma, uint mb, uint na, uint nb, uint x, uint y, uint w1, uint h1, uint wd, uint hd) +{ + const float u = fg_centre(x, w1), v = fg_centre(y, h1); + const uint mi = fg_index_rint(v, h1) * w1 + fg_index_rint(u, w1); + const float3 a = fg_vec64(ma, mi), b = fg_vec64(mb, mi); + const uint ji = fg_index_rint(v, hd) * wd + fg_index_rint(u, wd); + const float A1 = fg_read_linear(na, 2u, (int)wd, (int)hd, u + b.x, v + b.y).x; + const float A0 = fg_texel(na, 2u, ji).y; + const float B1 = fg_read_linear(nb, 2u, (int)wd, (int)hd, u + a.x, v + a.y).x; + const float B0 = fg_texel(nb, 2u, ji).y; + return fg_pack_h2(fg_sigmoid(A1, A0), fg_sigmoid(B1, B0)); +} diff --git a/clean/dx12/kernels/fg_full_blend.hlsl b/clean/dx12/kernels/fg_full_blend.hlsl index e88f6bbb..26e76834 100644 --- a/clean/dx12/kernels/fg_full_blend.hlsl +++ b/clean/dx12/kernels/fg_full_blend.hlsl @@ -11,15 +11,41 @@ // fg_full_blend_merge (FGB_MERGE) also writes net2's merged input x [W2 x H2][10] float16 = Ib [4], Ic [4], Ia, then the // scalar f (bits fbits) rounded to float16, as fg_net2_merge_pixels builds it from the three means (the same bits), // so that dispatch is not needed (extra arguments nx = x's offset, fbits). +// FGB_WEIGHTS (fg_full_blend_w, fg_full_blend_merge_w): the blend weights W are not read from an image: the workgroup +// computes the W texels its 16 x 16 pixels' bilinear taps touch (at most 12 x 12 of them: the scatter grid is at most half +// the frame's size) into LDS, each by fg_weight_texel (fg_weights.hlsli: the body of fg_lite_weights, the packed float16 x 2 +// word it stores), and the pixels read them from there with the same bilinear arithmetic. The tile's bounds come from +// the taps themselves (wave minima / maxima of every in-frame pixel's four texels). Extra arguments at the end: na, nb +// (net1's logit pairs, Wd x Hd); wimg is not read. Same bits as fg_lite_weights followed by fg_full_blend. +// FGB_X3 (the _x3 variants): X0 and X1 are stored as 3 x float16 (r, g, b: 6 bytes per pixel) instead of 4: nothing but +// fg_out_pull (FGP_X3) reads them and it never reads their alpha (the alpha means reach net2 through the lane tree, in +// registers). The same float16 words as the 4-channel store, without the alpha word. With an even frame width the lanes +// (x even, x + 1) of a Morton pair store their 12 bytes as three dwords; otherwise each pixel stores three 16-bit words. // // @wg-kernel fg_full_blend co=fg_full.co block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u // @wg-kernel fg_full_blend_merge co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,u defines=FGB_MERGE=1 +// @wg-kernel fg_full_blend_w co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,p defines=FGB_WEIGHTS=1 +// @wg-kernel fg_full_blend_merge_w co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,u,p,p defines=FGB_MERGE=1,FGB_WEIGHTS=1 +// @wg-kernel fg_full_blend_x3 co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u defines=FGB_X3=1 +// @wg-kernel fg_full_blend_merge_x3 co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,u defines=FGB_MERGE=1,FGB_X3=1 +// @wg-kernel fg_full_blend_w_x3 co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,p defines=FGB_WEIGHTS=1,FGB_X3=1 +// @wg-kernel fg_full_blend_merge_w_x3 co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,u,p,p defines=FGB_MERGE=1,FGB_WEIGHTS=1,FGB_X3=1 #include "wg_platform.hlsli" #include "fg_full.hlsli" #ifndef FGB_MERGE #define FGB_MERGE 0 #endif +#ifndef FGB_WEIGHTS +#define FGB_WEIGHTS 0 +#endif +#ifndef FGB_X3 +#define FGB_X3 0 +#endif +#if FGB_WEIGHTS +#include "fg_lite_common.hlsli" +#include "fg_weights.hlsli" +#endif WG_ARGS_BEGIN uint cp, cc, wimg, qc, ma, mb, up, uc; // inputs (arena byte offsets) @@ -28,10 +54,51 @@ WG_ARGS_BEGIN #if FGB_MERGE uint nx, fbits; #endif +#if FGB_WEIGHTS + uint na, nb; +#endif WG_ARGS_END groupshared float fgb_s[9 * 8]; +#if FGB_WEIGHTS +static const int FGB_WT = 12; // the W tile: FGB_WT x FGB_WT texels (the taps of 16 x 16 pixels span at most 10 x 10) +groupshared uint fgb_wtile[FGB_WT * FGB_WT]; +groupshared int4 fgb_wbox[8]; +static int fgb_wx0, fgb_wy0; // the tile's first texel + +// fgf_tap's texel coordinates and weights, bit for bit +struct FgbWTap { int x0, x1, y0, y1; float w00, w10, w01, w11; }; +FgbWTap fgb_wtap(float tx, float ty, int W, int H) +{ + FgbWTap t; + const float x0f = floor(tx), y0f = floor(ty); + const float fx = tx - x0f, fy = ty - y0f; + const int xi = clamp((int)x0f, -1, W - 1), yi = clamp((int)y0f, -1, H - 1); + t.x0 = max(xi, 0); t.x1 = min(xi + 1, W - 1); + t.y0 = max(yi, 0); t.y1 = min(yi + 1, H - 1); + const float gx = 1.0f - fx, gy = 1.0f - fy; + t.w00 = fgf_opq(gx * gy); + t.w10 = fgf_opq(fx * gy); + t.w01 = fgf_opq(fy * gx); + t.w11 = fgf_opq(fx * fy); + return t; +} + +float2 fgb_wld(int x, int y) +{ + const uint d = fgb_wtile[min((uint)((y - fgb_wy0) * FGB_WT + (x - fgb_wx0)), (uint)(FGB_WT * FGB_WT - 1))]; + return float2(wg_h2f_lo(d), wg_h2f_hi(d)); +} + +// fgf_bil2h on the LDS tile (fgf_mix2's expression) +float2 fgb_bil2(FgbWTap t) +{ + const float2 c00 = fgb_wld(t.x0, t.y0), c10 = fgb_wld(t.x1, t.y0), c01 = fgb_wld(t.x0, t.y1), c11 = fgb_wld(t.x1, t.y1); + return mad(t.w11, c11, mad(t.w01, c01, mad(t.w00, c00, t.w10 * c10))); +} +#endif + float4 fgb_mean(float4 a, uint shift) { // k is a power of two in [1, 16]. @@ -49,6 +116,9 @@ float fgb_add(float a, float b) WG_KERNEL(fg_full_blend) { FGF_SETUP(); +#if FGB_WEIGHTS + fg_z_ = wg_grid_ >> 31; +#endif const uint l = wg_lane_id(); const uint t = wg_block_id(); const uint ty = t / (uint)tiles_x; @@ -58,6 +128,43 @@ WG_KERNEL(fg_full_blend) float v[9]; [unroll] for (uint c = 0; c < 9u; ++c) v[c] = 0.0f; const bool in_bounds = px < Wo && py < Ho; +#if FGB_WEIGHTS + // the W tile: bounds of the taps of every pixel inside the frame, then its texels (every lane reaches the barriers) + FgbWTap wtap; + wtap.x0 = wtap.x1 = wtap.y0 = wtap.y1 = 0; + wtap.w00 = wtap.w10 = wtap.w01 = wtap.w11 = 0.0f; + if (in_bounds) { + const float wu = fgf_pixel_centre(px, Wo), wv = fgf_pixel_centre(py, Ho); + wtap = fgb_wtap(mad(wu, (float)W1, -0.5f), mad(wv, (float)H1, -0.5f), W1, H1); + } + { + const int bx0 = WaveActiveMin(in_bounds ? wtap.x0 : 0x7fffffff), bx1 = WaveActiveMax(in_bounds ? wtap.x1 : -1); + const int by0 = WaveActiveMin(in_bounds ? wtap.y0 : 0x7fffffff), by1 = WaveActiveMax(in_bounds ? wtap.y1 : -1); + if (wg_wave_lane() == 0u) fgb_wbox[l >> 5] = int4(bx0, bx1, by0, by1); + } + wg_barrier_lds(); + int wx1, wy1; + { + int4 box = fgb_wbox[0]; + [unroll] for (uint wi = 1u; wi < 8u; ++wi) { + const int4 o = fgb_wbox[wi]; + box = int4(min(box.x, o.x), max(box.y, o.y), min(box.z, o.z), max(box.w, o.w)); + } + fgb_wx0 = box.x; + wx1 = box.y; + fgb_wy0 = box.z; + wy1 = box.w; + } + if (l < (uint)(FGB_WT * FGB_WT)) { + const int gx = fgb_wx0 + (int)(l % (uint)FGB_WT), gy = fgb_wy0 + (int)(l / (uint)FGB_WT); + uint wword = 0u; + // (a tile entirely outside the frame has an empty box: nothing to compute) + if (fgb_wx0 <= wx1 && fgb_wy0 <= wy1 && gx <= wx1 && gy <= wy1) + wword = fg_weight_texel(ma, mb, na, nb, (uint)gx, (uint)gy, (uint)W1, (uint)H1, (uint)Wd, (uint)Hd); + fgb_wtile[l] = wword; + } + wg_barrier_lds(); +#endif if (in_bounds) { const float u = fgf_pixel_centre(px, Wo), vv = fgf_pixel_centre(py, Ho); const float tie = asfloat(0xB4000000u); // -2^-23 @@ -76,7 +183,11 @@ WG_KERNEL(fg_full_blend) const float3 P0 = fgf_ld4h(cp, pi).xyz, Q0 = fgf_ld4h(cc, pi).xyz; const float3 cP = fgf_bil4h(cp, fgf_tap_uv(ub, vb, Wo, Ho)).xyz; const float3 cQ = fgf_bil4h(cc, fgf_tap_uv(ua, va, Wo, Ho)).xyz; +#if FGB_WEIGHTS + const float2 w = fgb_bil2(wtap); +#else const float2 w = fgf_bil2h(wimg, fgf_tap_uv(u, vv, W1, H1)); +#endif const float2 qu = fgf_bil2h(qc, fgf_tap_uv(u, vv, Wd, Hd)); // Reuse the co-located quality when the warped coordinates are identical. float qbx = qu.x, qay = qu.y; @@ -110,11 +221,39 @@ WG_KERNEL(fg_full_blend) [unroll] for (uint c = 0; c < 8u; ++c) mag = max(mag, asuint(v[c]) & 0x7fffffffu); [branch] if (mag > 0x7f800000u) h = uint4(fg_pack_h2(v[0], v[1]), fg_pack_h2(v[2], v[3]), fg_pack_h2(v[4], v[5]), fg_pack_h2(v[6], v[7])); +#if FGB_X3 + // r, g | b (x0) and r, g | b (x1): the words h.x, h.y (X0) and h.z, h.w (X1) without their alpha halves + const uint4 partner = QuadReadAcrossX(h); + // stores through two pointer arguments at the same per-lane offset: the driver kept only one of a merged pair + // (README "Driver exceptions"); the pointers through readfirstlane keep both + const uint x0u = (uint)wg_uniform((int)x0), x1u = (uint)wg_uniform((int)x1); + if ((Wo & 1) == 0) { + // Morton pair (x, x + 1) in one row: pixel i at byte 6 i is dword-aligned for even i (an even width keeps i even) + if (in_bounds && (px & 1) == 0) { + const uint at = (uint)(py * Wo + px) * 6u; + wg_st32(x0u, at, h.x); + wg_st32(x0u, at + 4u, (h.y & 0xffffu) | (partner.x << 16)); + wg_st32(x0u, at + 8u, (partner.x >> 16) | (partner.y << 16)); + wg_st32(x1u, at, h.z); + wg_st32(x1u, at + 4u, (h.w & 0xffffu) | (partner.z << 16)); + wg_st32(x1u, at + 8u, (partner.z >> 16) | (partner.w << 16)); + } + } else if (in_bounds) { + const uint at = (uint)(py * Wo + px) * 6u; + wg_st16(x0u, at, h.x & 0xffffu); + wg_st16(x0u, at + 2u, h.x >> 16); + wg_st16(x0u, at + 4u, h.y & 0xffffu); + wg_st16(x1u, at, h.z & 0xffffu); + wg_st16(x1u, at + 2u, h.z >> 16); + wg_st16(x1u, at + 4u, h.w & 0xffffu); + } +#else if (in_bounds) { const uint pi8 = (uint)(py * Wo + px) * 8u; wg_st64(x0, pi8, h.xy); wg_st64(x1, pi8, h.zw); } +#endif } fgf_store_morton_flag(xw, px, py, Wo, Ho, v[8] > 0.0f); const uint shift = (uint)firstbithigh((uint)k); diff --git a/clean/dx12/kernels/fg_lite_blend.hlsl b/clean/dx12/kernels/fg_lite_blend.hlsl index 27729392..e70606ba 100644 --- a/clean/dx12/kernels/fg_lite_blend.hlsl +++ b/clean/dx12/kernels/fg_lite_blend.hlsl @@ -7,25 +7,82 @@ // fg_lite_blend_pack (FG_PACK) writes the presenter slot's packed row instead (fg_pack.hlsli): outp = the packed rows' // offset, ostride = their pitch in bytes, ox = the format code (1 R8G8B8A8, 2 B8G8R8A8, 3 R10G10B10A2), oy = 0; each // pixel is stored as the code fg_exec_pack makes of the float16 pixel fg_lite_blend writes. +// FG_WEIGHTS (fg_lite_blend_w, fg_lite_blend_pack_w): the blend weights W are not read from an image (the fg_lite_weights +// launch is dropped): the workgroup, one 32 x 8 tile of frame pixels (tiles_x = ceil(wo / 32), one wave per tile row; +// the launch is tiles_x * ceil(ho / 8) workgroups), computes the W texels its pixels' bilinear taps touch (at most 20 x 8 +// of them: the scatter grid is at most half the frame's size) into LDS, each by fg_weight_texel (fg_weights.hlsli: the +// body of fg_lite_weights, the packed float16 x 2 word it stores), and the pixels read them from there with +// fg_read_linear's arithmetic. The tile's bounds come from the taps themselves (the wave minima / maxima of every +// in-frame pixel's four texels). Extra arguments at the end: na, nb (net1's logit pairs, wd x hd), wd, hd; wimg is not +// read. Same bits as fg_lite_weights followed by fg_lite_blend (any pixel order gives the same bits: every pixel is +// independent). // // @wg-kernel fg_lite_blend co=- block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u // @wg-kernel fg_lite_blend_pack co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_PACK=1 // @wg-kernel fg_lite_blend_mut co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MUT=1 +// @wg-kernel fg_lite_blend_w co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,u,u defines=FG_WEIGHTS=1 +// @wg-kernel fg_lite_blend_pack_w co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,u,u defines=FG_PACK=1,FG_WEIGHTS=1 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" #include "fg_pack.hlsli" +#ifndef FG_MUT +#define FG_MUT 0 +#endif +#ifndef FG_PACK +#define FG_PACK 0 +#endif +#ifndef FG_WEIGHTS +#define FG_WEIGHTS 0 +#endif +#if FG_WEIGHTS +#include "fg_weights.hlsli" +#endif + WG_ARGS_BEGIN uint cp, cc, ma, mb, wimg, up, uc, lp, lc, outp; uint ostride, ox, oy, wo, ho, wm, hm, tbits, flag1, flag2; FG_REGION_ARGS(l) +#if FG_WEIGHTS + uint na, nb, wd, hd; +#endif WG_ARGS_END -#ifndef FG_MUT -#define FG_MUT 0 -#endif -#ifndef FG_PACK -#define FG_PACK 0 +#if FG_WEIGHTS +static const int FG_WTX = 20, FG_WTY = 8; // the W tile (the taps of 32 x 8 pixels span at most 18 x 5 texels) +groupshared uint fg_wtile[FG_WTX * FG_WTY]; +groupshared int4 fg_wbox[8]; +static int fg_wx0, fg_wy0; // the tile's first texel + +// fg_read_linear's texel coordinates and fractions, bit for bit +struct FgTapL { int x0, x1, y0, y1; float ax, ay; }; +FgTapL fg_tap_l(float X, float Y, int w, int h) +{ + FgTapL t; + const float px = mad(X, (float)w, -0.5f), py = mad(Y, (float)h, -0.5f); + const float fx = floor(px), fy = floor(py); + t.ax = px - fx; + t.ay = py - fy; + const int rx = clamp((int)fx, -1, w - 1), ry = clamp((int)fy, -1, h - 1); + t.x0 = max(rx, 0); t.x1 = min(rx + 1, w - 1); + t.y0 = max(ry, 0); t.y1 = min(ry + 1, h - 1); + return t; +} + +float2 fg_wld(int x, int y) +{ + const uint d = fg_wtile[min((uint)((y - fg_wy0) * FG_WTX + (x - fg_wx0)), (uint)(FG_WTX * FG_WTY - 1))]; + return float2(f16tof32(d), f16tof32(d >> 16)); +} + +// fg_read_linear(wimg, 2u, wm, hm, u, v).xy on the LDS tile +float2 fg_read_linear_w(FgTapL t) +{ + const float2 t00 = fg_wld(t.x0, t.y0), t10 = fg_wld(t.x1, t.y0), t01 = fg_wld(t.x0, t.y1), t11 = fg_wld(t.x1, t.y1); + const float2 r0 = mad(t.ax.xx, t10 - t00, t00); + const float2 r1 = mad(t.ax.xx, t11 - t01, t01); + return mad(t.ay.xx, r1 - r0, r0); +} #endif bool fg_in_box(float px, float py) @@ -65,10 +122,50 @@ float3 fg_correct(float3 c, float alpha, float2 uv, float u, float v, bool empty WG_KERNEL(fg_lite_blend) { FG_SETUP(); +#if FG_WEIGHTS + const uint lane = wg_lane_id(), tile = wg_block_id(), tiles_x = (wo + 31u) >> 5u; + const uint tile_y = tile / tiles_x; + const uint x = ((tile - tile_y * tiles_x) << 5u) + (lane & 31u), y = (tile_y << 3u) + (lane >> 5u); + const bool live = x < wo && y < ho; + const uint idx = y * wo + x; + const float u = fg_centre(x, wo), v = fg_centre(y, ho); + FgTapL wtap; + wtap.x0 = wtap.x1 = wtap.y0 = wtap.y1 = 0; + wtap.ax = wtap.ay = 0.0f; + if (live) wtap = fg_tap_l(u, v, (int)wm, (int)hm); + { + const int bx0 = WaveActiveMin(live ? wtap.x0 : 0x7fffffff), bx1 = WaveActiveMax(live ? wtap.x1 : -1); + const int by0 = WaveActiveMin(live ? wtap.y0 : 0x7fffffff), by1 = WaveActiveMax(live ? wtap.y1 : -1); + if (wg_wave_lane() == 0u) fg_wbox[lane >> 5] = int4(bx0, bx1, by0, by1); + } + wg_barrier_lds(); + int wx1, wy1; + { + int4 box = fg_wbox[0]; + [unroll] for (uint wi = 1u; wi < 8u; ++wi) { + const int4 o = fg_wbox[wi]; + box = int4(min(box.x, o.x), max(box.y, o.y), min(box.z, o.z), max(box.w, o.w)); + } + fg_wx0 = box.x; + wx1 = box.y; + fg_wy0 = box.z; + wy1 = box.w; + } + if (lane < (uint)(FG_WTX * FG_WTY)) { + const int gx = fg_wx0 + (int)(lane % (uint)FG_WTX), gy = fg_wy0 + (int)(lane / (uint)FG_WTX); + uint wword = 0u; + if (fg_wx0 <= wx1 && fg_wy0 <= wy1 && gx <= wx1 && gy <= wy1) + wword = fg_weight_texel(ma, mb, na, nb, (uint)gx, (uint)gy, wm, hm, wd, hd); + fg_wtile[lane] = wword; + } + wg_barrier_lds(); + if (!live) return; +#else const uint idx = wg_block_id() * 256u + wg_lane_id(); if (idx >= wo * ho) return; const uint x = idx % wo, y = idx / wo; const float u = fg_centre(x, wo), v = fg_centre(y, ho); +#endif const uint mi = fg_index_rint(v, hm) * wm + fg_index_rint(u, wm); const float3 A = fg_vec64(ma, mi), B = fg_vec64(mb, mi); const bool eA = A.z != 0.0f, eB = B.z != 0.0f; @@ -78,7 +175,11 @@ WG_KERNEL(fg_lite_blend) const float4 sP = fg_read_linear(cp, 4u, (int)wo, (int)ho, uvP.x, uvP.y); const float4 sQ = fg_read_linear(cc, 4u, (int)wo, (int)ho, uvQ.x, uvQ.y); float3 cP = sP.xyz, cQ = sQ.xyz; +#if FG_WEIGHTS + const float4 w = float4(fg_read_linear_w(wtap), 0.0f, 0.0f); +#else const float4 w = fg_read_linear(wimg, 2u, (int)wm, (int)hm, u, v); +#endif if (flag2 != 0u) { const float3 ncP = fg_correct(cP, sP.w, uvP, u, v, eB, P0, Q0, lp, P0.xyz); diff --git a/clean/dx12/kernels/fg_mconv.hlsl b/clean/dx12/kernels/fg_mconv.hlsl index 7e78afa8..473c173c 100644 --- a/clean/dx12/kernels/fg_mconv.hlsl +++ b/clean/dx12/kernels/fg_mconv.hlsl @@ -8,12 +8,22 @@ // chunk before its first matrix call and keep store pointers uniform (clean/dx12/README.md). // Built only when --only names the kernels (fg_ kernels are in no model's set). // +// FG_CELLS (fg_mconv2_mid_cells, net1_01 only: k = 3, order 1): the input is not the cell tensor read from memory but the +// cells built in LDS by this workgroup: every cell of its 18 x (FG_TH + 2) halo (zero outside the W x H cell grid) is made +// as fg_lite_net1_input makes it (fg_net1_pixel.hlsli: the ten values of each of the cell's four image pixels, packed to +// float16, transposed over the quad of lanes into the six 8-channel vectors of the HWC cell: channels 4 v + 2 dy + dx, +// 40..47 zero), in the six uint4 planes the channel blocks read; the convolution is fg_accumulate_halo's with the three +// blocks staged at once. The pixels of the workgroup's own 16 x FG_TH cells also write Qc and Om (what fg_lite_net1_input +// writes besides the cells), once each. The cell tensor is never written. Extra arguments after the 15 of the plain +// kernel: ld, dc, dp, fin, mv, eimg, hc, hp, qp, mimg, qc, om (arena offsets), wd, hd, w1, h1, pad_l, pad_t. +// // @wg-kernel fg_mconv1 co=fg_net1_mma.co entry=fg_mconv block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,WG_LD_A16=1 // @wg-kernel fg_mconv2 co=fg_net1_mma.co entry=fg_mconv block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,WG_LD_A16=1,FG_HALO=1 // @wg-kernel fg_mconv4 co=fg_net1_mma.co entry=fg_mconv block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=4,WG_LD_A16=1 // @wg-kernel fg_mconv2_narrow co=fg_net1_mma.co entry=fg_mconv block=64 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,WG_LD_A16=1,FG_HALO=1 // @wg-kernel fg_mconv1_late co=fg_net1_mma.co entry=fg_mconv block=64 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,WG_LD_A16=1,FG_HALO=1 // @wg-kernel fg_mconv2_mid co=fg_net1_mma.co entry=fg_mconv block=128 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,WG_LD_A16=1,FG_HALO=1 +// @wg-kernel fg_mconv2_mid_cells co=- entry=fg_mconv block=128 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u defines=FG_MT=2,WG_LD_A16=1,FG_HALO=1,FG_CELLS=1 #include "wg_platform.hlsli" #define FG_FN @@ -28,6 +38,9 @@ #ifndef FG_HALO #define FG_HALO 0 #endif +#ifndef FG_CELLS +#define FG_CELLS 0 +#endif #if FG_HALO #define FG_HALO_PX (18 * (FG_TH + 2)) groupshared uint4 fg_halo[2 * FG_HALO_PX]; @@ -36,7 +49,15 @@ groupshared uint4 fg_halo[2 * FG_HALO_PX]; WG_ARGS_BEGIN uint x, wf, b, y, p; // pointers (arena byte offsets) int cin, cout, H, W, k, order, act, pool, tiles_x, tiles_y; +#if FG_CELLS + uint ld, dc, dp, fin, mv, eimg, hc, hp, qp, mimg, qc, om; + uint wd, hd, w1, h1, pad_l, pad_t; +#endif WG_ARGS_END +#if FG_CELLS +#include "fg_lite_common.hlsli" +#include "fg_net1_pixel.hlsli" +#endif uint fg_opq0() { return wg_grid_ >> 31; } // an opaque zero (the grid size is below 2^31) @@ -125,6 +146,84 @@ void fg_accumulate_halo(int tx, int ty, int mg, int n, int hh, int wy, uint lane } #endif +#if FG_CELLS +// Six planes (the 8-channel vectors of the 48-channel cell: plane j = channels 8 j .. 8 j + 7) of the halo cells. +groupshared uint4 fg_cells[6 * FG_HALO_PX]; + +// The workgroup's halo cells (halo cell p = cell (tx * 16 + p % 18 - 1, ty * FG_TH + p / 18 - 1)), one lane per (cell, +// pixel q of the cell) -- the lanes of a quad are the four pixels of one cell, q = lane & 3: the pixel is +// (2 X + (q & 1) - 2 pad_l, 2 Y + (q >> 1) - 2 pad_t). +void fg_stage_cells(int tx, int ty) +{ + const int items = FG_HALO_PX * 4; + const int rounds = (items + WG_BLOCK - 1) / WG_BLOCK + (int)fg_opq0(); + for (int round = 0; round < rounds; ++round) { + // Lanes past the end still take part in the wave's conversions and quad reads (they redo the last cell). + const int it = round * WG_BLOCK + (int)wg_lane_id(), e = min(it, items - 1); + const int pc = e >> 2, q = e & 3; + const int cx = pc % 18, cy = pc / 18; + const int X = tx * 16 + cx - 1, Y = ty * FG_TH + cy - 1; + const bool inside = X >= 0 && X < W && Y >= 0 && Y < H; + const bool own = inside && cx >= 1 && cx <= 16 && cy >= 1 && cy <= FG_TH && it < items; + const int px = 2 * X + (q & 1) - 2 * (int)pad_l, py = 2 * Y + (q >> 1) - 2 * (int)pad_t; + float vals[10]; + fg_net1_pixel(px, py, inside, own, vals); + uint pr[5]; + [unroll] for (int j = 0; j < 5; ++j) pr[j] = fg_pack_h2(vals[2 * j], vals[2 * j + 1]); + // the vector j of the cell: halves (k = 2 j, 2 j + 1) of the four pixels, in channel order + uint4 vec[5]; + [unroll] for (int j2 = 0; j2 < 5; ++j2) { + const uint a = QuadReadLaneAt(pr[j2], 0), bq = QuadReadLaneAt(pr[j2], 1); + const uint c = QuadReadLaneAt(pr[j2], 2), d = QuadReadLaneAt(pr[j2], 3); + vec[j2] = uint4((a & 0xffffu) | (bq << 16), (c & 0xffffu) | (d << 16), + (a >> 16) | (bq & 0xffff0000u), (c >> 16) | (d & 0xffff0000u)); + } + if (it < items) { + const uint4 mine = q == 0 ? vec[0] : (q == 1 ? vec[1] : (q == 2 ? vec[2] : vec[3])); + fg_cells[q * FG_HALO_PX + pc] = mine; + if (q == 0) fg_cells[4 * FG_HALO_PX + pc] = vec[4]; + if (q == 1) fg_cells[5 * FG_HALO_PX + pc] = uint4(0u, 0u, 0u, 0u); + } + } + wg_barrier_lds(); +} + +// fg_accumulate_halo (k = 3, order 1) on the staged cells: block cb reads planes 2 cb and 2 cb + 1 +void fg_accumulate_cells(int mg, int n, int hh, int wy, uint lane, inout uint4 h16[FG_MT][2]) +{ + const int nb = cin / 16; + const int nq = nb * 9; + const int pixel = hh * FG_HALO_PX + wy * 18 + n; + for (int cb = 0; cb < nb; ++cb) { + const int at = cb * 2 * FG_HALO_PX + pixel; + uint4 fb[2], fa[FG_MT]; + { + fb[0] = fg_cells[at]; + fb[1] = fg_cells[at + 18]; + [unroll] for (int mt = 0; mt < FG_MT; ++mt) + fa[mt] = wg_ld128(wf, (uint)((((mg * FG_MT + mt) * nq + cb * 9) * 32 + (int)lane) * 16)); + } + [unroll] for (int tap = 0; tap < 9; ++tap) { + uint4 fb_n[2], fa_n[FG_MT]; + if (tap + 1 < 9) { + const int nt = tap + 1; + const int qn = cb * 9 + nt; + const int ppn = at + 18 * (nt % 3) + nt / 3; + fb_n[0] = fg_cells[ppn]; + fb_n[1] = fg_cells[ppn + 18]; + [unroll] for (int mt = 0; mt < FG_MT; ++mt) + fa_n[mt] = wg_ld128(wf, (uint)((((mg * FG_MT + mt) * nq + qn) * 32 + (int)lane) * 16)); + } + fg_chunk_b_pipe(fa, fb, h16); + if (tap + 1 < 9) { + fb[0] = fb_n[0]; fb[1] = fb_n[1]; + [unroll] for (int mt2 = 0; mt2 < FG_MT; ++mt2) fa[mt2] = fa_n[mt2]; + } + } + } +} +#endif + void fg_accumulate(int tx, int ty, int mg, int n, int hh, int wy, uint lane, bool staged, inout uint4 h16[FG_MT][2]) { @@ -211,7 +310,11 @@ uint fg_pool4(uint a, uint b, uint c, uint d) WG_KERNEL(fg_mconv) { +#if FG_CELLS + FG_SETUP(); +#else WG_SETUP(); +#endif const uint lane = wg_lane_id() & 31u, wave = wg_lane_id() >> 5; const int blk = (int)wg_block_id(); const int tx = blk % tiles_x, rest = blk / tiles_x; @@ -227,6 +330,10 @@ WG_KERNEL(fg_mconv) h16[mt][0] = wg_ld128(b, (uint)o0 * 2u); h16[mt][1] = h16[mt][0]; } +#if FG_CELLS + fg_stage_cells(tx, ty); + fg_accumulate_cells(mg, n, hh, wy, lane, h16); +#else #if FG_HALO if (k == 3 && order == 1) { #if WG_BLOCK <= 128 @@ -239,6 +346,7 @@ WG_KERNEL(fg_mconv) { fg_accumulate(tx, ty, mg, n, hh, wy, lane, false, h16); } +#endif [unroll] for (int mt4 = 0; mt4 < FG_MT; ++mt4) { const int o0 = (mg * FG_MT + mt4) * 16 + 8 * hh; const uint4 r0 = act == 1 ? fg_leaky8(h16[mt4][0]) : h16[mt4][0]; diff --git a/clean/dx12/kernels/fg_net2_mconv.hlsl b/clean/dx12/kernels/fg_net2_mconv.hlsl index aafb7f7e..34565d9f 100644 --- a/clean/dx12/kernels/fg_net2_mconv.hlsl +++ b/clean/dx12/kernels/fg_net2_mconv.hlsl @@ -28,6 +28,27 @@ // the staging rounds are full (972 items over 256 lanes: 3.8 rounds instead of 3 x 1.27) and no barrier separates the heads. // Every staged value and every convolution is the same computation on the same data as the three-pass kernel. // +// FG_UPWARP_STAGE = 1 (L14 only, fg_net2_mconv_m1b2_uw / _m1b2s_uw): the input y [H][W][18] is not read from memory: the +// workgroup evaluates fg_net2_upwarp's lane work (fg_net2_upwarp.hlsli: the 2x head upsample and the warp-merge) for every pixel of its +// staged tile (one lane per tile pixel, the pixels of the tile's one-pixel border included, zero outside the grid) and +// puts the four 8-channel groups of y (the 8 warped values; U4, U1, Ia, U3[0..1]; U3[2], h(f); zeros) into the LDS tile +// as the loads and the channel mask would have, so the convolution is the same computation on the same bits. The +// pixels of the workgroup's own 16 x FG_TH area also write U4, U1, U3 (net2's L25 residuals), as fg_net2_upwarp does. +// Extra arguments at the end: ib, ic, ia, a4, a1, a3, u4, u1, u3 (arena offsets), fbits (f's single-precision bits). +// +// FG_PAIR = 1 (fg_net2_mpair_res_c64 / _c32, net2's residual pairs L4+L5, L6+L7, L8+L9, L10+L11 and L16+L17, L18+L19, +// L20+L21, L22+L23; FG_C channels in and out of both, FG_MT = FG_NB = FG_C / 16, 128 lanes): one launch computes both +// convolutions of a pair. A workgroup owns an interior of 14 x 6 conv pixels (tile tx, ty over the grid); the first +// convolution (leaky, clamp to [-6, 6], h(v + 0): res 1) runs on the 16 x 8 region = the interior and its one-pixel +// border, from an input tile of 18 x 10 pixels staged as fg_stage does (the same LDS buffer, one-pixel border = the +// region's); its float16 results go to LDS in place of the input tile (zero outside the grid: the second convolution's +// zero padding) and the second convolution (leaky, clamp, residual fma(1, input, v): res 2, the input read from memory +// as for any residual) runs on the interior from there and stores. Both convolutions are fg_conv_tile and fg_post8 as in +// the single-layer launches: every chunk, every rounding and every post-op is the same computation on the same data, +// the intermediate tensor just never goes to memory. The other launch parameters of the pair (cin = cout = FG_C, no pool, +// leaky 1, clamp from 0, residual multiplier 1, channel strides FG_C) are constants of the kernel. +// Arguments: x (input, also the residual), wf, b (first layer), wf2, b2 (second), y, H, W, tiles_x, tiles_y. +// // Work split: workgroup = 16 x FG_TH conv pixels (tile tx, ty; FG_TH = 2 rows per wave) and FG_MT output tiles of 16 // weight outputs (group mg); a wave owns two rows of 16 pixels (two B fragments per chunk), so a pooled 2 x 2 cell sits // in one wave (lanes n, n ^ 1). A fragments: wf [cout / 16][9 taps][FG_NB blocks][32 lanes][8] float16 @@ -37,6 +58,10 @@ // wave whose rows are all past the grid) is on a wave-uniform value, after the LDS barrier. Built only when --only // names the kernels. // +// @wg-kernel fg_net2_mpair_res_c64 co=- entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,u,u,u,u defines=FG_MT=4,FG_NB=4,FG_PAIR=1,FG_C=64 +// @wg-kernel fg_net2_mpair_res_c32 co=- entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,u,u,u,u defines=FG_MT=2,FG_NB=2,FG_PAIR=1,FG_C=32 +// @wg-kernel fg_net2_mconv_m1b2_uw co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,p,p,p,p,p,p,p,u defines=FG_MT=1,FG_NB=2,FG_UPWARP_STAGE=1 +// @wg-kernel fg_net2_mconv_m1b2s_uw co=fg_net2_mma.co entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,p,p,p,p,p,p,p,u defines=FG_MT=1,FG_NB=2,FG_UPWARP_STAGE=1 // @wg-kernel fg_net2_mconv_m1b1 co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1 // @wg-kernel fg_net2_mconv_m1b2 co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=2 // @wg-kernel fg_net2_mconv_m2b1 co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,FG_NB=1 @@ -64,21 +89,54 @@ #ifndef FG_UP #define FG_UP 0 #endif +#ifndef FG_UPWARP_STAGE +#define FG_UPWARP_STAGE 0 +#endif +#ifndef FG_PAIR +#define FG_PAIR 0 +#endif #define FG_TH (2 * (WG_BLOCK / 32)) // conv rows per workgroup +#if FG_PAIR +WG_ARGS_BEGIN + uint x, wf, b, wf2, b2, y; // pointers (arena byte offsets) + int H, W, tiles_x, tiles_y; +WG_ARGS_END +// the single-layer launch parameters of the pair (see the header), as constants, so that fg_stage, fg_conv_tile, fg_post8 +// and fg_store8 below are the single-layer kernels' code +static const int in_cs = FG_C, cin = FG_C, co_lo = 0, co_n = FG_C, out_cs = FG_C, out_co = 0, pool = 0, leaky = 1; +static const int clamp_from = 0, skip_cs = FG_C, skip_co = 0, heads = 0; +static const uint res_mul = 0x3C00u; +static int res; // 1 in the first layer, 2 in the second (wave-uniform) +static uint skip, y1, y2, skip1, skip2; // set at the start: the residual is the input, one output +static uint fg_wf_cur, fg_b_cur; // the layer's weights and bias +#define FG_WF fg_wf_cur +#define FG_B fg_b_cur +#define FG_WF_SET(w, bias) fg_wf_cur = (w); fg_b_cur = (bias); +#else WG_ARGS_BEGIN uint x, wf, b, y, skip, y1, y2, skip1, skip2; // pointers (arena byte offsets) int in_cs, in_co, cin, H, W, co_lo, co_n, out_cs, out_co, pool, leaky, clamp_from, res; uint res_mul; int skip_cs, skip_co, tiles_x, tiles_y, heads; +#if FG_UPWARP_STAGE + uint ib, ic, ia, a4, a1, a3, u4, u1, u3, fbits; +#endif WG_ARGS_END +#define FG_WF wf +#define FG_B b +#endif #ifndef FG_FUSED_HEADS #define FG_FUSED_HEADS 0 #endif #ifndef FG_STAGE_ALL #define FG_STAGE_ALL 0 #endif +#if FG_UPWARP_STAGE +#define FG_NATIVE_UP 1 // the upwarp's wave operations (fg_net2_upwarp.hlsl declares it so too) +#else #define FG_NATIVE_UP FG_UP +#endif #define FG_NATIVE_POST ((!FG_UP && (FG_NB == 2 || FG_MT == 2 || FG_NB == 4)) || (FG_UP && FG_NB == 1)) #define FG_NATIVE_LEAKY 1 #define FG_JOINED_POST FG_FUSED_HEADS @@ -96,7 +154,7 @@ uint4 fg_load_input8(uint off, int ico) return wg_ld128(x, off); } -#define FG_STAGE (FG_UP || FG_NB == 2 || (FG_MT == 2 && FG_NB == 1) || (FG_MT == 1 && FG_NB == 4)) +#define FG_STAGE (FG_UP || FG_NB == 2 || (FG_MT == 2 && FG_NB == 1) || (FG_MT == 1 && FG_NB == 4) || FG_PAIR) #if FG_STAGE #define FG_TG (FG_NB * 2) #define FG_TILE_PIXELS ((FG_TH + 2) * 18) @@ -327,6 +385,46 @@ void fg_stage_heads(int x0, int y0) } #endif #elif FG_STAGE +#if FG_UPWARP_STAGE +#include "fg_net2_upwarp.hlsli" + +// The staged tile of L14's input built from fg_upwarp_eval (see the header): tile pixel pp is (x0 + pp % 18 - 1, +// y0 + pp / 18 - 1); its four groups are the channels 0..7, 8..15, 16..23 (16 and 17 only) and 24..31 (none) of y. +void fg_stage_upwarp(int x0, int y0) +{ + const int items = FG_TILE_PIXELS; + const int rounds = (items + WG_BLOCK - 1) / WG_BLOCK + (int)fg_opq0(); + const uint hf = wg_f2h(asfloat(fbits)); + for (int round = 0; round < rounds; ++round) { + // Lanes past the end still take part in the wave's conversions (they evaluate the last tile pixel). + const int it = round * WG_BLOCK + (int)wg_lane_id(), pp = min(it, items - 1); + const int sx = x0 + pp % 18 - 1, sy = y0 + pp / 18 - 1; + const bool inside = and(and(sx >= 0, sx < W), and(sy >= 0, sy < H)); + const int p = select(inside, sy * W + sx, 0); + uint4 U, val; + fg_upwarp_eval(p, U, val); + const uint iav = wg_ld16(ia, (uint)p * 2u); + const uint4 m = select(inside, ~0u, 0u).xxxx; + if (it < items) { + fg_tile[fg_tile_index(pp, 0)] = val & m; + fg_tile[fg_tile_index(pp, 1)] = uint4(U.x, U.y, fg_half(U, 4u) | (iav << 16), + fg_half(U, 5u) | (fg_half(U, 6u) << 16)) & m; + fg_tile[fg_tile_index(pp, 2)] = uint4(fg_half(U, 7u) | (hf << 16), 0u, 0u, 0u) & m; + fg_tile[fg_tile_index(pp, 3)] = uint4(0u, 0u, 0u, 0u); + // the pixels of this workgroup's own area keep U4 / U1 / U3 for L25's residuals + const int cx = pp % 18, cy = pp / 18; + if (inside && cx >= 1 && cx <= 16 && cy >= 1 && cy <= FG_TH) { + wg_st64(u4, (uint)p * 8u, U.xy); + wg_st16(u1, (uint)p * 2u, fg_half(U, 4u)); + wg_st16(u3, (uint)(p * 3) * 2u, fg_half(U, 5u)); + wg_st16(u3, (uint)(p * 3 + 1) * 2u, fg_half(U, 6u)); + wg_st16(u3, (uint)(p * 3 + 2) * 2u, fg_half(U, 7u)); + } + } + } + wg_barrier_lds(); +} +#else void fg_stage(int x0, int y0, int ico) { const uint items = FG_TILE_PIXELS * FG_TG; @@ -341,6 +439,7 @@ void fg_stage(int x0, int y0, int ico) wg_barrier_lds(); } #endif +#endif FgOut fg_output(int hj) { @@ -360,7 +459,7 @@ void fg_conv_tile(int px, int py0, int wrow, int n, int hh, uint lane, int wt, i { [unroll] for (int mt = 0; mt < FG_MT; ++mt) { const int o0 = (wt * FG_MT + mt) * 16 + 8 * hh; - h16[mt][0] = fg_load_aligned8(b, (uint)o0 * 2u); + h16[mt][0] = fg_load_aligned8(FG_B, (uint)o0 * 2u); h16[mt][1] = h16[mt][0]; } #if !FG_STAGE @@ -378,7 +477,7 @@ void fg_conv_tile(int px, int py0, int wrow, int n, int hh, uint lane, int wt, i } [unroll] for (int mt = 0; mt < FG_MT; ++mt) [unroll] for (int cb = 0; cb < FG_NB; ++cb) - fa[mt][cb] = fg_load_aligned8(wf, (uint)(((((wt * FG_MT + mt) * 9) * FG_NB + cb) * 32 + (int)lane) * 16)); + fa[mt][cb] = fg_load_aligned8(FG_WF, (uint)(((((wt * FG_MT + mt) * 9) * FG_NB + cb) * 32 + (int)lane) * 16)); } [unroll] for (int t = 0; t < 9; ++t) { uint4 fb_n[2][FG_NB], fa_n[FG_MT][FG_NB]; @@ -391,7 +490,7 @@ void fg_conv_tile(int px, int py0, int wrow, int n, int hh, uint lane, int wt, i } [unroll] for (int mt = 0; mt < FG_MT; ++mt) [unroll] for (int cb = 0; cb < FG_NB; ++cb) - fa_n[mt][cb] = fg_load_aligned8(wf, (uint)(((((wt * FG_MT + mt) * 9 + tn) * FG_NB + cb) * 32 + (int)lane) * 16)); + fa_n[mt][cb] = fg_load_aligned8(FG_WF, (uint)(((((wt * FG_MT + mt) * 9 + tn) * FG_NB + cb) * 32 + (int)lane) * 16)); } { const int N = FG_NB * FG_MT * 2; @@ -447,7 +546,7 @@ void fg_conv_tile(int px, int py0, int wrow, int n, int hh, uint lane, int wt, i } [unroll] for (int mt = 0; mt < FG_MT; ++mt) [unroll] for (int cb = 0; cb < FG_NB; ++cb) - fa[mt][cb] = fg_load_aligned8(wf, (uint)(((((wt * FG_MT + mt) * 9 + t) * FG_NB + cb) * 32 + (int)lane) * 16)); + fa[mt][cb] = fg_load_aligned8(FG_WF, (uint)(((((wt * FG_MT + mt) * 9 + t) * FG_NB + cb) * 32 + (int)lane) * 16)); // Software-pipelined Tier B chunks across (cb, mt, nt): overlaps both fg_widen (8x v_cvt_f32_f16) // and wg_to_f16_ags (8x v_cvt_f16_f32) directly with independent wg_wmma_f16 ops (only 2 v8f live; bit-identical). { @@ -517,6 +616,60 @@ uint4 fg_joined_post(uint4 v, int px, int cy, int hh, bool live) } #endif +#if FG_PAIR +WG_KERNEL(fg_net2_mconv) +{ + WG_SETUP(); + skip = x; + y1 = y; + y2 = y; + skip1 = 0u; + skip2 = 0u; + const uint lane = wg_lane_id() & 31u; + const int blk = (int)wg_block_id(); + const int tx = blk % tiles_x, ty = blk / tiles_x; + const int n = (int)(lane & 15u), hh = (int)(lane >> 4); + const int wave = wg_uniform((int)(wg_lane_id() >> 5)); + const int wrow = 2 * wave; // the wave's first row of the 16 x 8 region + const int ix = tx * 14, iy = ty * 6; // the interior's first pixel + + // first layer on the region (pixel (n, wrow + nt) of the region is conv pixel (ix - 1 + n, iy - 1 + wrow + nt)) + res = 1; + fg_stage(ix - 1, iy - 1, 0); // the tile starts at (ix - 2, iy - 2) + uint4 h1[FG_MT][2]; + FG_WF_SET(wf, b) + fg_conv_tile(ix - 1 + n, iy - 1 + wrow, wrow, n, hh, lane, 0, 0, h1); + wg_barrier_lds(); // every wave has read the input tile + [unroll] for (int mt = 0; mt < FG_MT; ++mt) { + const int o0 = mt * 16 + 8 * hh; + [unroll] for (int nt = 0; nt < 2; ++nt) { + const int gx = ix - 1 + n, gy = iy - 1 + wrow + nt; + const bool inside = and(and(gx >= 0, gx < W), and(gy >= 0, gy < H)); + const uint4 r = fg_adjust8(h1[mt][nt], o0); + fg_tile[fg_tile_index((wrow + nt) * 18 + n, 2 * mt + hh)] = r & select(inside, ~0u, 0u).xxxx; + } + } + wg_barrier_lds(); + + // second layer on the interior (waves 0 .. 2 hold its six rows) + res = 2; + if (wave < 3) { + uint4 h2[FG_MT][2]; + FG_WF_SET(wf2, b2) + fg_conv_tile(ix + n, iy + wrow, wrow, n, hh, lane, 0, 0, h2); + const FgOut q = fg_output(0); + [unroll] for (int mt2 = 0; mt2 < FG_MT; ++mt2) { + const int o0 = mt2 * 16 + 8 * hh; + [unroll] for (int nt2 = 0; nt2 < 2; ++nt2) { + const int cx = ix + n, cy = iy + wrow + nt2; + const bool live = and(and(n < 14, cx < W), cy < H); + const uint4 r = fg_post8(q, h2[mt2][nt2], o0, cy, cx, live); + if (live) fg_store8(q, cy * W + cx, o0, r); + } + } + } +} +#else WG_KERNEL(fg_net2_mconv) { WG_SETUP(); @@ -565,7 +718,9 @@ WG_KERNEL(fg_net2_mconv) const FgOut q = fg_output(hj); const int ico = in_co + hj * cin; -#if FG_STAGE +#if FG_UPWARP_STAGE + fg_stage_upwarp(tx * 16, ty * FG_TH); +#elif FG_STAGE fg_stage(tx * 16, ty * FG_TH, ico); #endif if (py0 >= H) return; // wave-uniform: both rows of this wave are past the grid @@ -598,3 +753,4 @@ WG_KERNEL(fg_net2_mconv) } #endif } +#endif diff --git a/clean/dx12/kernels/fg_net2_upwarp.hlsl b/clean/dx12/kernels/fg_net2_upwarp.hlsl index 89047777..17fe5f5d 100644 --- a/clean/dx12/kernels/fg_net2_upwarp.hlsl +++ b/clean/dx12/kernels/fg_net2_upwarp.hlsl @@ -22,58 +22,7 @@ WG_ARGS_END #define FG_NATIVE_UP 1 #include "fg_net2_fast.hlsli" -// the 8 head channels of half-resolution pixel q -uint4 fg_heads8(int q) -{ - const uint2 h4 = wg_ld64(a4, (uint)q * 8u); - const uint h1 = wg_ld16(a1, (uint)q * 2u); - const uint c0 = wg_ld16(a3, (uint)(q * 3) * 2u), c1 = wg_ld16(a3, (uint)(q * 3 + 1) * 2u); - const uint c2 = wg_ld16(a3, (uint)(q * 3 + 2) * 2u); - return uint4(h4.x, h4.y, h1 | (c0 << 16), c1 | (c2 << 16)); -} - -// fg_net2_warp's sample point and weights for the displacement (ux, uy) at pixel (px_, py_) -struct FgSample { int x0; int x1; int y0; int y1; float w00; float w10; float w01; float w11; }; -FgSample fg_sample(uint ux, uint uy, int px_, int py_) -{ - FgSample s; - const uint sx = fg2_fma(FG2_TWO16, ux, wg_f2h((float)px_)); - const uint sy = fg2_fma(FG2_TWO16, uy, wg_f2h((float)py_)); - const float fX0 = floor(wg_h2f(sx)); - const float fY0 = floor(wg_h2f(sy)); - const uint fx = wg_f2h(wg_h2f(sx) - fX0); - const uint fy = wg_f2h(wg_h2f(sy) - fY0); - const int X0 = (int)fX0; - const int Y0 = (int)fY0; - s.x0 = clamp(X0, 0, W - 1); s.x1 = clamp(X0 + 1, 0, W - 1); - s.y0 = clamp(Y0, 0, H - 1); s.y1 = clamp(Y0 + 1, 0, H - 1); - const uint gx = wg_f2h(1.0f - wg_h2f(fx)); - const uint gy = wg_f2h(1.0f - wg_h2f(fy)); - s.w00 = wg_h2f(fg2_mul(gx, gy)); s.w10 = wg_h2f(fg2_mul(fx, gy)); - s.w01 = wg_h2f(fg2_mul(gx, fy)); s.w11 = wg_h2f(fg2_mul(fx, fy)); - return s; -} - -// 4 channels of Ib at (yy, xx) and 4 of Ic at (zy, zx) as 8 values -uint4 fg_pair8(int yy, int xx, int zy, int zx) -{ - const uint2 b = wg_ld64(ib, (uint)((yy * W + xx) * 4) * 2u); - const uint2 c = wg_ld64(ic, (uint)((zy * W + zx) * 4) * 2u); - return uint4(b.x, b.y, c.x, c.y); -} - -// The taps have fixed FP16 weights on the 2x grid; preserve the extrapolation at pixel zero. -Fg2Tap fg_upwarp_tap(int o, int n) -{ - const bool odd = (o & 1) != 0; - const int i = (o >> 1) - (int)!odd; - Fg2Tap t; - t.i0 = clamp(i, 0, n - 1); - t.i1 = min(i + 1, n - 1); - t.w0 = select(o == 0, 0x3d00u, select(odd, 0x3a00u, FG2_QUARTER16)); - t.w1 = select(o == 0, 0xb400u, select(odd, FG2_QUARTER16, 0x3a00u)); - return t; -} +#include "fg_net2_upwarp.hlsli" WG_KERNEL(fg_net2_upwarp) { @@ -81,25 +30,8 @@ WG_KERNEL(fg_net2_upwarp) const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); const bool live = idx < W * H; const int p = min(idx, W * H - 1); - const int py_ = p / W, px_ = p - (p / W) * W; - const int wi = W / 2, hi = H / 2; - const Fg2Tap tX = fg_upwarp_tap(px_, wi), tY = fg_upwarp_tap(py_, hi); - const uint4 top = fg_up_axis8(tX, fg_heads8(tY.i0 * wi + tX.i0), fg_heads8(tY.i0 * wi + tX.i1)); - const uint4 bottom = fg_up_axis8(tX, fg_heads8(tY.i1 * wi + tX.i0), fg_heads8(tY.i1 * wi + tX.i1)); - const uint4 U = fg_up_axis8(tY, top, bottom); - - const FgSample sb = fg_sample(fg_half(U, 0u), fg_half(U, 1u), px_, py_); - const FgSample sc = fg_sample(fg_half(U, 2u), fg_half(U, 3u), px_, py_); - float w00[8], w10[8], w01[8], w11[8]; - [unroll] for (int i = 0; i < 4; ++i) { - w00[i] = sb.w00; w10[i] = sb.w10; w01[i] = sb.w01; w11[i] = sb.w11; - w00[i + 4] = sc.w00; w10[i + 4] = sc.w10; w01[i + 4] = sc.w01; w11[i + 4] = sc.w11; - } - const uint4 p00 = fg_pair8(sb.y0, sb.x0, sc.y0, sc.x0), p01 = fg_pair8(sb.y0, sb.x1, sc.y0, sc.x1); - const uint4 p10 = fg_pair8(sb.y1, sb.x0, sc.y1, sc.x0), p11 = fg_pair8(sb.y1, sb.x1, sc.y1, sc.x1); - uint4 acc = fg_fma8v(w10, p01, fg_mul8v(w00, p00)); - acc = fg_fma8v(w01, p10, acc); - const uint4 val = fg_fma8v(w11, p11, acc); + uint4 U, val; + fg_upwarp_eval(p, U, val); const uint iav = wg_ld16(ia, (uint)p * 2u); const uint hf = wg_f2h(asfloat(fbits)); diff --git a/clean/dx12/kernels/fg_out_pull.hlsl b/clean/dx12/kernels/fg_out_pull.hlsl index 16e26f63..14c2b60a 100644 --- a/clean/dx12/kernels/fg_out_pull.hlsl +++ b/clean/dx12/kernels/fg_out_pull.hlsl @@ -14,10 +14,14 @@ // fg_out_pull_pack (FGP_PACK): the same, but out is the presenter slot's packed row (fg_pack.hlsli): outp = the packed // rows' offset, out_pitch = their pitch in bytes, out_x = the format code (1 R8G8B8A8, 2 B8G8R8A8, 3 R10G10B10A2), // out_y = 0; each pixel is stored as the code fg_exec_pack makes of the float16 pixel fg_out_pull writes. +// FGP_X3 (fg_out_pull_x3, fg_out_pull_pack_x3): X0 / X1 are stored as 3 x float16 (6 bytes per pixel, fg_full_blend FGB_X3); +// a texel is read as the 8 bytes from its dword (the 6 bytes sit in them), the same float16 values as the 4-channel read. // // @wg-kernel fg_out_pull co=fg_full.co block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u // @wg-kernel fg_out_pull_pack co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_PACK=1 // @wg-kernel fg_out_pull_mid co=fg_full.co block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u defines=FGP_MID=1 +// @wg-kernel fg_out_pull_x3 co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_X3=1 +// @wg-kernel fg_out_pull_pack_x3 co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_PACK=1,FGP_X3=1 #include "wg_platform.hlsli" #include "fg_full.hlsli" #include "fg_pack.hlsli" @@ -28,6 +32,9 @@ #ifndef FGP_PACK #define FGP_PACK 0 #endif +#ifndef FGP_X3 +#define FGP_X3 0 +#endif groupshared float4 fgp_wave_sums[8]; @@ -123,6 +130,23 @@ float fgp_bil(float fx, float fy, float gx, float gy, float q00, float q10, floa return mad(gy, mad(gx, q00, fx * q10), fy * mad(gx, q01, fx * q11)); } +#if FGP_X3 +// texel i of a 3 x float16 image: its 6 bytes are inside the 8 bytes from the dword at or below byte 6 i +float4 fgp_ld3h(uint p, int i) +{ + const uint a = (uint)i * 6u; + const uint2 d = wg_ld64(p, a & ~3u); + const bool hi = (a & 2u) != 0u; + const uint rg = hi ? ((d.x >> 16) | (d.y << 16)) : d.x; + const uint b = hi ? (d.y >> 16) : (d.y & 0xffffu); + return float4(wg_h2f_lo(rg), wg_h2f_hi(rg), wg_h2f(b), 0.0f); +} +float4 fgp_bil3h(uint p, FgfTap t) { return fgf_mix4(t, fgp_ld3h(p, t.i00), fgp_ld3h(p, t.i10), fgp_ld3h(p, t.i01), fgp_ld3h(p, t.i11)); } +#define FGP_BIL_X(p, t) fgp_bil3h(p, t) +#else +#define FGP_BIL_X(p, t) fgf_bil4h(p, t) +#endif + // One 20-bit mask per row of the 16 x 16 tile with its two-pixel halo. groupshared uint fgp_need_rows[20]; groupshared uint3 fgp_n2_tile[25]; @@ -209,8 +233,8 @@ WG_KERNEL(fg_out_pull) const float vby = fgp_bil(fx, fy, gx, gy, wg_h2f_hi(d00.y), wg_h2f_hi(d10.y), wg_h2f_hi(d01.y), wg_h2f_hi(d11.y)); // the two candidates re-sampled at the pixel plus k times the vectors (pixel units) const float kf = (float)k; - const float3 A = fgf_bil4h(x0, fgf_tap(vax * kf + (float)px, vay * kf + (float)py, Wo, Ho)).xyz; - const float3 B = fgf_bil4h(x1, fgf_tap(vbx * kf + (float)px, vby * kf + (float)py, Wo, Ho)).xyz; + const float3 A = FGP_BIL_X(x0, fgf_tap(vax * kf + (float)px, vay * kf + (float)py, Wo, Ho)).xyz; + const float3 B = FGP_BIL_X(x1, fgf_tap(vbx * kf + (float)px, vby * kf + (float)py, Wo, Ho)).xyz; c = fgf_sat3(mad(sigma, A, (1.0f - sigma) * B)); if (isnan(abs(c.z * (c.x * c.y)))) c = float3(0.0f, 1.0f, 1.0f); } diff --git a/clean/dx12/kernels/fg_out_push.hlsl b/clean/dx12/kernels/fg_out_push.hlsl index c44d360e..fdc2f4aa 100644 --- a/clean/dx12/kernels/fg_out_push.hlsl +++ b/clean/dx12/kernels/fg_out_push.hlsl @@ -13,9 +13,22 @@ // rows' offset, out_pitch = their pitch in bytes, out_x = the format code (1 R8G8B8A8, 2 B8G8R8A8, 3 R10G10B10A2), // out_y = 0; the pixel is stored as the code fg_exec_pack makes of the float16 pixel fg_out_push_fine writes. // +// fg_out_push_fine_l1 / fg_out_push_fine_pack_l1 (FGU_L1): level 1 is not pushed beforehand: a pixel of a hole takes the four +// level-1 taps of its upsample as push would have left them, computed on the spot: the own texel (bits as they are) where +// its weight is not <= 0 (a NaN weight keeps it), else the upsample of the filled level 2 (arguments filled2, w2, h2 at the +// end) at that texel, rounded to float16 as the push stores it. Only the taps of hole pixels are ever computed (the launch +// of the level-1 push, a read and a write of the whole level, is dropped). +// fg_out_tail (FGU_TAIL): the pushes of the coarsest levels in one workgroup: the levels (nlev of them, coarsest first: +// arena offset o, size w x h) are loaded into LDS (at most 3584 texels in all), each level below the first is pushed +// in turn (in place, as fg_out_push does, one barrier between levels), and the last (finest) level goes back to memory: +// the same texels as nlev - 1 launches of fg_out_push, the coarser levels not being read again. +// // @wg-kernel fg_out_push co=fg_full.co block=256 wave=32 args=p,p,p,u,u,u,u // @wg-kernel fg_out_push_fine co=fg_full.co block=256 wave=32 args=p,p,p,u,u,u,u,u,u,u defines=FGU_FINE=1 // @wg-kernel fg_out_push_fine_pack co=- entry=fg_out_push_fine block=256 wave=32 args=p,p,p,u,u,u,u,u,u,u defines=FGU_FINE=1,FGU_PACK=1 +// @wg-kernel fg_out_push_fine_l1 co=- entry=fg_out_push_fine block=256 wave=32 args=p,p,p,u,u,u,u,u,u,u,p,u,u defines=FGU_FINE=1,FGU_L1=1 +// @wg-kernel fg_out_push_fine_pack_l1 co=- entry=fg_out_push_fine block=256 wave=32 args=p,p,p,u,u,u,u,u,u,u,p,u,u defines=FGU_FINE=1,FGU_PACK=1,FGU_L1=1 +// @wg-kernel fg_out_tail co=- block=256 wave=32 args=u,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FGU_TAIL=1 #include "wg_platform.hlsli" #include "fg_full.hlsli" #include "fg_pack.hlsli" @@ -26,18 +39,108 @@ #ifndef FGU_PACK #define FGU_PACK 0 #endif +#ifndef FGU_L1 +#define FGU_L1 0 +#endif +#ifndef FGU_TAIL +#define FGU_TAIL 0 +#endif +#if FGU_L1 || FGU_TAIL +#include "fg_full_up.hlsli" +#endif WG_ARGS_BEGIN -#if FGU_FINE +#if FGU_TAIL + uint nlev, o0, o1, o2, o3, o4, o5, o6, o7; + int lw0, lw1, lw2, lw3, lw4, lw5, lw6, lw7, lh0, lh1, lh2, lh3, lh4, lh5, lh6, lh7; +#elif FGU_FINE uint fine, filled1, outp; int Wo, Ho, w1, h1, out_pitch, out_x, out_y; +#if FGU_L1 + uint filled2; + int w2, h2; +#endif #else uint own, coarse, filled; int wf, hf, wc, hc; #endif WG_ARGS_END -#if FGU_FINE +#if FGU_TAIL +static const int FGU_TAIL_CELLS = 3584; // 28 KB of 8-byte texels +groupshared uint2 fgu_lds[FGU_TAIL_CELLS]; + +float4 fgu_ld(int base, int i) +{ + const uint2 d = fgu_lds[base + i]; + return float4(wg_h2f_lo(d.x), wg_h2f_hi(d.x), wg_h2f_lo(d.y), wg_h2f_hi(d.y)); +} + +// fgf_up on a level held in LDS +float4 fgu_up(int base, int wc, int hc, int qx, int qy) +{ + int iP, iX, iY, iD; + fgf_up_idx(wc, hc, qx, qy, iP, iX, iY, iD); + return fgf_up_taps(fgu_ld(base, iP), fgu_ld(base, iX), fgu_ld(base, iY), fgu_ld(base, iD)); +} + +WG_KERNEL(fg_out_tail) +{ + FGF_SETUP(); + const uint lane = wg_lane_id(); + const uint offs[8] = {o0, o1, o2, o3, o4, o5, o6, o7}; + const int ws[8] = {lw0, lw1, lw2, lw3, lw4, lw5, lw6, lw7}; + const int hs[8] = {lh0, lh1, lh2, lh3, lh4, lh5, lh6, lh7}; + int eoff[9]; + eoff[0] = 0; + [unroll] for (int j = 0; j < 8; ++j) eoff[j + 1] = eoff[j] + (j < (int)nlev ? ws[j] * hs[j] : 0); + // load every level + [unroll] for (int j = 0; j < 8; ++j) { + if (j < (int)nlev) { + const int n = ws[j] * hs[j]; + for (int i = (int)lane; i < n; i += 256) fgu_lds[eoff[j] + i] = wg_ld64(offs[j], (uint)i * 8u); + } + } + wg_barrier_lds(); + // push each level below the coarsest from the one above it (in place: own texel kept where its weight is not <= 0) + [unroll] for (int j = 1; j < 8; ++j) { + if (j < (int)nlev) { + const int n = ws[j] * hs[j], wf = ws[j]; + for (int i = (int)lane; i < n; i += 256) { + const uint2 o = fgu_lds[eoff[j] + i]; + if (!(wg_h2f_hi(o.y) <= 0.0f)) continue; + const int qy = i / wf, qx = i - qy * wf; + const float4 v = fgu_up(eoff[j - 1], ws[j - 1], hs[j - 1], qx, qy); + fgu_lds[eoff[j] + i] = uint2(fg_pack_h2(v.x, v.y), fg_pack_h2(v.z, v.w)); + } + wg_barrier_lds(); + } + } + // the finest level back to memory + [unroll] for (int j = 1; j < 8; ++j) { + if (j == (int)nlev - 1) { + const int n = ws[j] * hs[j]; + for (int i = (int)lane; i < n; i += 256) wg_st64(offs[j], (uint)i * 8u, fgu_lds[eoff[j] + i]); + } + } +} +#elif FGU_FINE +#if FGU_L1 +// level-1 texel idx as the in-place push leaves it: the own bits where the weight is not <= 0, else fgf_up of the filled +// level 2, rounded to float16 (fgf_st4h) and read back +float4 fgu_l1_texel(int idx) +{ + const uint2 o = wg_ld64(filled1, (uint)idx * 8u); + uint2 b = o; + if (wg_h2f_hi(o.y) <= 0.0f) { + const int qy = idx / w1, qx = idx - qy * w1; + const float4 v = fgf_up(filled2, w2, h2, qx, qy); + b = uint2(fg_pack_h2(v.x, v.y), fg_pack_h2(v.z, v.w)); + } + return float4(wg_h2f_lo(b.x), wg_h2f_hi(b.x), wg_h2f_lo(b.y), wg_h2f_hi(b.y)); +} +#endif + WG_KERNEL(fg_out_push_fine) { FGF_SETUP(); @@ -45,7 +148,13 @@ WG_KERNEL(fg_out_push_fine) if (idx >= Wo * Ho) return; if (!(fgf_ld1h(fine, idx) > 0.0f)) return; const int qy = idx / Wo, qx = idx - qy * Wo; +#if FGU_L1 + int iP, iX, iY, iD; + fgf_up_idx(w1, h1, qx, qy, iP, iX, iY, iD); + const float4 up = fgf_up_taps(fgu_l1_texel(iP), fgu_l1_texel(iX), fgu_l1_texel(iY), fgu_l1_texel(iD)); +#else const float4 up = fgf_up(filled1, w1, h1, qx, qy); +#endif #if FGU_PACK const uint2 h = uint2(fg_pack_h2(up.x, up.y), fg_pack_h2(up.z, 1.0f)); wg_st32(outp, (uint)(qy + out_y) * (uint)out_pitch + (uint)qx * 4u, fgx_pack_pixel(h, (uint)out_x)); diff --git a/clean/fg/README.md b/clean/fg/README.md index 15c36f6e..eb62cdd2 100644 --- a/clean/fg/README.md +++ b/clean/fg/README.md @@ -66,7 +66,7 @@ front end or the launcher yet. Status, open items and formats: [FORMATS.md](FORM | `runtime/fg_exec_plan.h`, `.cpp` | the D3D12 executor's CPU side (F7b, plain C++17): the light path's settings, the grid sizes of a frame size (net1 image and cell grids, scatter grid and pyramid, net2's factor and grid, the output pyramid), application regions and their ten kernel values, the float16 rounding, and the schedule of `reference/pipeline.py` `Host` split at the session's seam: once per game frame (history clears, menu detection or the disable word, R3 .. R8, net1's input / net1 / output or the quality image), per index (the intermediate-time scatters, the blend weights, the light blend for preset C or the Full blend, net2 and the output pyramid for presets A / B, the menu output; the game frame's copy without history) and the last-index part (history advances, the image pairs swap) | | `runtime/fg_d3d12_executor.h`, `.cpp` | `FgD3d12Executor`, the production `IFgKernelExecutor` on the game's D3D12 device and queue (F7b): one root signature for every FG kernel (arena root UAVs, 59 root constants, the driver channel and one texture view), the kernels' DXIL loaded from a folder built by `clean/dx12/build_dx12.py --only` and their pipelines built once, the arena sized for the frame (every image, net1's three regions, the input capture areas, the Full path and net2) with the weights uploaded at configuration; per game frame the inputs are captured from the game's textures (`fg_exec_io.hlsl`) and the shared stages recorded, the menu detection read back (a bounded wait on that submission only); per index the generated image is written into the presenter slot's texture (packed to the slot's format, COMMON -> COPY_DEST -> COMMON) and the shared producer fence signalled; menu / priming copies and the game frame's endpoint copy the colour exactly; an adapter-side real-only frame (no shared work) is captured from the game's back buffer and copied into a reserved slot (F9); net2 runs on the fast path by default (27 launches on the matrix unit, tier B: `fg_net2_mconv.hlsl`, `fg_net2_upwarp.hlsl`, the plan of `runner/fg_net2_mma.py`) with the exact 38-launch chain selectable (`FgD3d12ExecutorDesc::net2`), and `Net2SelfTest` runs net2 alone on synthetic inputs for the comparison and timing legs; every refusal names its reason and nothing falls back. `FgExecutorPresenterSource` binds the executor to the composition or DXGI back end the session creates; `FgExecWeightsFromModel` takes the weights from a checked model file | | `runtime/tests/test_fg_d3d12_e2e.cpp` | ctest `fg_d3d12_e2e` (CPU): geometry, regions, thresholds and the logistic table against the CPU reference, the float16 rounding, the schedule, every executor refusal that needs no GPU and a session whose executor refuses (no presenter, no fallback). `--gpu --dxil /dx12` adds the headless GPU leg (no window): a synthetic game through the adapter core, the session and the executor with the composition back end (unbound surface) and the DXGI back end (composition swap chain) for preset C 2x / 6x and presets A / B 2x with a menu frame, net2's exact path, and frames with generation switched off in the game's options (real-only from the back buffer) (generated images finite, menu and endpoint copies exact, slot bytes equal to the image in the slot's format, fences complete, DXGI slots all returned, the swap chain released right after teardown; `--debug-layer` adds the D3D12 debug layer), net2's fast path against the exact one on synthetic inputs (within tolerance, deterministic, every value written, a half-covered last launch caught; GPU time at the 1080p and 1440p grids, information only), and kernel folders with a broken kernel that must be refused | -| Turbo v2 (executor levers, all exact: the kernels' arithmetic is untouched, only where and when independent work runs and four fused / retiled kernels) | `WG_FG_BATCH=0` / `WG_FG_HOIST=0` / `WG_FG_DUALQ=0` / `WG_FG_FUSE=0` (or `FgD3d12ExecutorDesc::batch / hoist / dualq / fuse`) turn a lever off for paired A / B runs; all four give the same bytes as all four off (`test_fg_d3d12_e2e --gpu --dxil --only turbo`: every slot over four game frames, presets A / B / C, N = 1..5, byte for byte). Scratch banks: the per-index images (MA, MB, W, the generated image and its packed rows, the Full blend's images, net2's tensors, the output pyramid) are one block repeated once per generated index (`max_generated` banks while the arena fits). `RecordGeneratedBatch` (the session calls it when `BatchesGenerated()`) records layer k of every index back to back, so barriers sit only between dependent layers and the small net2 / pyramid layers of several indices fill the GPU together. Hoist: the per-index MA / MB fills and intermediate-time scatters of every index of the game frame run on a second compute queue beside net1 (they read only the p2c results) and the producer queue waits for them before the first index. Dual queue: the game queue's work is two recordings (motion preparation, then the downsample) so the p2c chain starts after the first and the net1 input waits for the second. Fuse: `fg_lite_p2c_fine_mask` (fine pass + hole mask when the net1 grid is the scatter grid), `fg_lite_p2c_inpaint_tiled` (32 x 8 tiles, ballot row masks), `fg_lite_interm_both` (both passes, 32 x 32 LDS-binned signed 64-bit minima) and `fg_net2_mconv_h3b1u_s3` (L25's three heads staged in one pass). Profiling: `WRONGGPU_FG_KPROF=1` or `test_fg_d3d12_e2e --bench --kprof` lists every launch (kernel, workgroups, us); `--gen N` benchmarks 2x..6x for real and reports the wall-clock span and busy time of all queues next to the per-stage sums; the CPU proofs of the exactness arguments are `tests/test_fg_turbo_v2.py`, and `runner/fg_lite_d3d12_check.py --turbo` checks the Turbo kernels against the CPU reference | +| Turbo v2 (executor levers, all exact: the kernels' arithmetic is untouched, only where and when independent work runs and four fused / retiled kernels) | `WG_FG_BATCH=0` / `WG_FG_HOIST=0` / `WG_FG_DUALQ=0` / `WG_FG_FUSE=0` (or `FgD3d12ExecutorDesc::batch / hoist / dualq / fuse`) turn a lever off for paired A / B runs; all four give the same bytes as all four off (`test_fg_d3d12_e2e --gpu --dxil --only turbo`: every slot over four game frames, presets A / B / C, N = 1..5, byte for byte). Scratch banks: the per-index images (MA, MB, W, the generated image and its packed rows, the Full blend's images, net2's tensors, the output pyramid) are one block repeated once per generated index (`max_generated` banks while the arena fits). `RecordGeneratedBatch` (the session calls it when `BatchesGenerated()`) records layer k of every index back to back, so barriers sit only between dependent layers and the small net2 / pyramid layers of several indices fill the GPU together. Hoist: the per-index MA / MB fills and intermediate-time scatters of every index of the game frame run on a second compute queue beside net1 (they read only the p2c results) and the producer queue waits for them before the first index. Dual queue: the game queue's work is two recordings (motion preparation, then the downsample) so the p2c chain starts after the first and the net1 input waits for the second. Fuse: `fg_lite_p2c_fine_mask` (fine pass + hole mask when the net1 grid is the scatter grid), `fg_lite_p2c_inpaint_tiled` (32 x 8 tiles, ballot row masks), `fg_lite_interm_both` (both passes, 32 x 32 LDS-binned signed 64-bit minima) and `fg_net2_mconv_h3b1u_s3` (L25's three heads staged in one pass). Wave 1B (`WG_FG_FUSE2=0` or `FgD3d12ExecutorDesc::fuse2 = 0` keeps the Wave 1 kernels; a mask picks levers: 1 net1 cells, 2 net2 pairs, 4 upwarp in L14, 8 blend weights, 16 pyramid tail, 32 X0 / X1 as RGB; `test_fg_d3d12_e2e --bench --fuse2 0|1|MASK`; each exact against the kernels it replaces, checked by `--gpu --only turbo` in two legs: every lever on against every lever off, and Wave 1B alone against Wave 1): `fg_mconv2_mid_cells` (net1_01 builds its cells in LDS from the same images `fg_lite_net1_input` packs and writes Qc / Om itself: no input launch, no cell round trip), `fg_net2_mpair_res_c64` / `_c32` (net2's residual pairs L4+L5 .. L10+L11 and L16+L17 .. L22+L23 in one launch: 14 x 6 interiors, the first layer on the 16 x 8 region with its border and its output kept in LDS), `fg_net2_mconv_m1b2_uw` / `_m1b2s_uw` (L14 computes the upwarp for its staged tile and writes U4 / U1 / U3 itself: no y tensor, no upwarp launch), `fg_lite_blend_w` / `_pack_w` and `fg_full_blend_w` / `_merge_w` (the blend builds the W texels its tile's taps touch in LDS: no weights launch or W image read), `fg_out_tail` (the coarsest pushes in one workgroup, as many levels as fit 28 KB of LDS) with `fg_out_push_fine_l1` / `_pack_l1` (level 1 pushed on the spot at the holes' taps: no level-1 launch), and `fg_full_blend_*_x3` / `fg_out_pull_x3` (X0 / X1 stored as 6-byte RGB: only the output pull reads them and never their alpha). The CPU proofs of their exactness arguments are in `tests/test_fg_turbo_v2.py` (copied bodies compared line by line, tile bounds, the pyramid push chain, the residual pair fusion). Profiling: `WRONGGPU_FG_KPROF=1` or `test_fg_d3d12_e2e --bench --kprof` lists every launch (kernel, workgroups, us); `--gen N` benchmarks 2x..6x for real and reports the wall-clock span and busy time of all queues next to the per-stage sums; the CPU proofs of the exactness arguments are `tests/test_fg_turbo_v2.py`, and `runner/fg_lite_d3d12_check.py --turbo` checks the Turbo kernels against the CPU reference | | `clean/dx12/kernels/fg_exec_io.hlsl` | the executor's input capture (a game texture of any readable format into the arena's float16 / float32 image kinds) and output pack (the float16 image into a slot format: RGBA16F, RGBA8 / BGRA8, RGB10A2) | | `fg_limits.h` | `kFgMaxGenerated`, shared by the presenter and the runtime so one file can include both (the runtime contract's own status and real-only enums are `FgFrameStatus` / `FgFrameRealOnly`, distinct from the presenter's `FgStatus` / `FgRealOnlyReason`) | | `tools/gen_fg_runtime_tables.py`, `tests/test_fg_runtime_tables.py` | writes / checks the two generated headers (the map table; the fused plan and the weight fragments of constructed float16 patterns from `runner/fg_net1_mma.py`) | diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index 2d0b0a98..1cb2ad0d 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -45,8 +46,20 @@ enum Kernel : uint32_t { kLiteBlendPack, kFullBlendMerge, // Turbo v2: exact fused / retiled kernels, used only when their DXIL is present and the fuse lever is on kFineMask, kInpaintTiled, kInterm2, kN2h3b1uS3, + // Turbo v2 Wave 1B (the fuse2 levers, FgD3d12ExecutorDesc::fuse2): each is used only when its DXIL is present + kLiteBlendW, kLiteBlendPackW, // A13: W built in the blend + kFullBlendW, kFullBlendMergeW, kFullBlendX3, kFullBlendMergeX3, kFullBlendWX3, kFullBlendMergeWX3, + kOutPullX3, kOutPullPackX3, // A12: X0 / X1 as RGB + kN2m1b2Uw, kN2m1b2sUw, // A9: upwarp in L14's staging + kPairC64, kPairC32, // A7: net2 residual pairs + kOutTail, kFineL1, kFinePackL1, // A14: output pyramid tail + kMConv2MidCells, // A6: net1_01 builds its cells kKernelCount, }; +// the Wave 1B levers (bits of FgD3d12ExecutorDesc::fuse2 when it is a mask) +enum Fuse2Bit : uint32_t { + kF2Cells = 1, kF2Pair = 2, kF2Upwarp = 4, kF2Weights = 8, kF2Tail = 16, kF2X3 = 32, kF2All = 63, +}; constexpr uint32_t kFirstTurbo = kFineMask; // a pipeline of these that the device refuses is dropped, not fatal constexpr uint32_t kFirstFull = kFullBlend; constexpr uint32_t kFirstOptional = kMConv2Narrow; @@ -67,6 +80,8 @@ constexpr uint32_t kMTile = 16; bool KernelNeeded(uint32_t k, bool full, FgNet2Path path) { if (k == kOutPullPack || k == kOutPushFinePack || k == kFullBlendMerge) return full; // Full path only + if ((k >= kFullBlendW && k <= kOutPullPackX3) || k == kOutTail || k == kFineL1 || k == kFinePackL1) return full; + if (k == kN2m1b2Uw || k == kN2m1b2sUw || k == kPairC64 || k == kPairC32) return full && path == FgNet2Path::Fast; if (k < kFirstFull || k >= kFirstOptional) return true; if (!full) return false; if (k == kNet2Conv || k == kNet2Up2 || k == kNet2Warp) return path == FgNet2Path::Exact; @@ -115,6 +130,14 @@ const char* const kKernelNames[kKernelCount] = { "fg_out_pull_pack", "fg_out_push_fine_pack", "fg_lite_blend_pack", "fg_full_blend_merge", "fg_lite_p2c_fine_mask", "fg_lite_p2c_inpaint_tiled", "fg_lite_interm_both", "fg_net2_mconv_h3b1u_s3", + "fg_lite_blend_w", "fg_lite_blend_pack_w", + "fg_full_blend_w", "fg_full_blend_merge_w", "fg_full_blend_x3", "fg_full_blend_merge_x3", "fg_full_blend_w_x3", + "fg_full_blend_merge_w_x3", + "fg_out_pull_x3", "fg_out_pull_pack_x3", + "fg_net2_mconv_m1b2_uw", "fg_net2_mconv_m1b2s_uw", + "fg_net2_mpair_res_c64", "fg_net2_mpair_res_c32", + "fg_out_tail", "fg_out_push_fine_l1", "fg_out_push_fine_pack_l1", + "fg_mconv2_mid_cells", }; static_assert(sizeof(kKernelNames) / sizeof(*kKernelNames) == kKernelCount, "one name per kernel"); @@ -611,6 +634,17 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { // Turbo v2 levers (fg_d3d12_executor.h FgD3d12ExecutorDesc): wanted at construction, active after Configure. bool want_batch = true, want_hoist = true, want_dualq = true, want_fuse = true; bool batch_on = false, hoist_on = false, dualq_on = false; + // Wave 1B (fuse2 bits wanted; the *_on flags are decided in Layout from the kernels that are present) + uint32_t want_fuse2 = kF2All; + bool Fused2(uint32_t bit, uint32_t k) const { return (want_fuse2 & bit) != 0 && pso[k] != nullptr; } + bool cells_on = false; // A6: net1_01 builds its cells in LDS (the net1 input launch is dropped) + bool pair64_on = false, pair32_on = false; // A7: net2's residual pairs (64- / 32-channel) in one launch + bool uw_on = false; // A9: the upwarp is computed in L14's staging (y is never written) + bool lite_weights_on = false; // A13: the light blend builds W + bool full_weights_on = false; // A13: the Full blend builds W + bool x3_on = false; // A12: X0 / X1 hold r, g, b only + bool tail_on = false; // A14: the pyramid's coarse pushes in one workgroup + bool l1_on = false; // A14: level 1 is pushed inside the fine pass bool hole_fused = false; // the fine pass already ran the hole mask of this frame (the HoleMask op is then empty) // the fused / retiled kernels (kFineMask, kInpaintTiled, kInterm2) are used when present bool Fused(uint32_t k) const { return want_fuse && pso[k] != nullptr; } @@ -860,12 +894,12 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { bump += align(bytes ? bytes : 4, 4); return static_cast(at); } - Net2Buf N2(uint32_t div, uint32_t c) { + Net2Buf N2(uint32_t div, uint32_t c, bool alloc = true) { Net2Buf b; b.h = g.H2 / div; b.w = g.W2 / div; b.c = c; - b.off = Alloc(2ull * b.h * b.w * c); + b.off = alloc ? Alloc(2ull * b.h * b.w * c) : 0u; return b; } @@ -901,9 +935,30 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return (batch_on || hoist_on) && index >= 1 && index <= sc_banks ? index - 1 : 0; } + // Wave 1B: a lever runs when its bit is wanted and every kernel it needs is present (else the Wave 1 kernels run) + void DecideFuse2() { + const bool full = desc.enable_full; + pair64_on = full && fast() && Fused2(kF2Pair, kPairC64); + pair32_on = full && fast() && Fused2(kF2Pair, kPairC32); + uw_on = full && fast() && Fused2(kF2Upwarp, kN2m1b2Uw) && pso[kN2m1b2sUw]; + lite_weights_on = Fused2(kF2Weights, kLiteBlendW) && pso[kLiteBlendPackW]; + full_weights_on = full && Fused2(kF2Weights, kFullBlendW) && pso[kFullBlendMergeW]; + x3_on = full && (want_fuse2 & kF2X3) && pso[kOutPullX3] && pso[kOutPullPackX3] && pso[kFullBlendX3] && + pso[kFullBlendMergeX3] && (!full_weights_on || (pso[kFullBlendWX3] && pso[kFullBlendMergeWX3])); + tail_on = full && Fused2(kF2Tail, kOutTail); + l1_on = full && Fused2(kF2Tail, kFineL1) && pso[kFinePackL1]; + } + // The Full blend kernel for (merged input, W built in, X0 / X1 as RGB) + uint32_t FullBlendKernel(bool merged) const { + const bool w = full_weights_on, x = x3_on; + if (merged) return w ? (x ? kFullBlendMergeWX3 : kFullBlendMergeW) : (x ? kFullBlendMergeX3 : kFullBlendMerge); + return w ? (x ? kFullBlendWX3 : kFullBlendW) : (x ? kFullBlendX3 : kFullBlend); + } + FgExecResult Layout(uint32_t banks) { bump = 256; // offset 0 is the null pointer sc_bank = 0; + DecideFuse2(); for (uint32_t r = 0; r < kRoleCount; ++r) { if (r == kRoleMA || r == kRoleMB || r == kRoleW) continue; // per-index: the scratch block below const uint64_t n = FgRoleBytes(g, r); @@ -929,6 +984,13 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { n1arena.region_base[0] = Alloc(n1plan.region_bytes[0]); n1arena.region_base[2] = Alloc(n1plan.region_bytes[2]); n1_cells = static_cast(n1arena.region_base[0] + n1plan.buffers[n1plan.Find("cells")].offset); + { + // A6: net1_01 (the one step that reads the cells) is the 3 x 3 block-first convolution of 48 channels + const FgNet1Step* s0 = n1plan.steps.empty() ? nullptr : &n1plan.steps[0]; + cells_on = s0 && Fused2(kF2Cells, kMConv2MidCells) && s0->kernel == FgNet1Kernel::MConv2 && + s0->args[0].buffer && s0->args[5].value == kFgCellChannels && s0->args[9].value == 3 && + s0->args[10].value == 1 && s0->args[6].value % 32 == 0 && s0->grid <= kFgMaxGroupsPerDispatch; + } n1_out = static_cast(n1arena.region_base[2] + n1plan.buffers[n1plan.Find("out")].offset); // The two coarse pairs run in sequence and can share the first convolution's output buffer. const bool split_b = pso[kMPairBFirst] && pso[kMPairBSecond]; @@ -949,8 +1011,8 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { pack_off = Alloc(static_cast(pack_pitch) * g.ho, 512); if (desc.enable_full) { const uint64_t fr = static_cast(g.wo) * g.ho, n2 = static_cast(g.W2) * g.H2; - x0 = Alloc(fr * 8); - x1 = Alloc(fr * 8); + x0 = Alloc(fr * (x3_on ? 6 : 8)); + x1 = Alloc(fr * (x3_on ? 6 : 8)); xw = Alloc(fr * 2); ib = Alloc(n2 * 8); ic = Alloc(n2 * 8); @@ -966,7 +1028,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { nb_a2 = N2(4, 32); nb_r0 = N2(8, 64); for (int u = 0; u < 4; ++u) { - nb_t[u] = N2(8, 64); + nb_t[u] = N2(8, 64, !pair64_on); // the pair kernels keep the first layer's output in LDS nb_r[u] = N2(8, 64); } if (!fast()) nb_r4u = N2(4, 64); // the fast path stages the upsamples inside the convolutions @@ -978,11 +1040,11 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { nb_U4 = N2(1, 4); nb_U1 = N2(1, 1); nb_U3 = N2(1, 3); - nb_y = N2(1, 18); + nb_y = N2(1, 18, !uw_on); // with the upwarp in L14's staging y is never written nb_b1 = N2(2, 16); nb_s0 = N2(4, 32); for (int u = 0; u < 4; ++u) { - nb_tb[u] = N2(4, 32); + nb_tb[u] = N2(4, 32, !pair32_on); nb_s[u] = N2(4, 32); } if (!fast()) nb_s4u = N2(2, 32); @@ -1578,6 +1640,20 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return; } + if (cells_on && kernel == FgNet1Kernel::MConv2 && args[0] == n1_cells) { + // net1_01 with its cells built in LDS from the images net1's input launch would have packed + uint32_t a[kFgNet1Args + 18]; + std::copy_n(args, kFgNet1Args, a); + a[14] = cdiv(a[7], 8); + const uint32_t groups = a[13] * a[14] * (a[6] / 32); + uint32_t n = kFgNet1Args; + for (uint32_t x : {R(kRoleLd), R(kRoleDc), R(kRoleDp), R(kRoleF), R(kRoleMv), R(kRoleE), R(kRoleHc), + R(kRoleHp), R(kRoleQp), R(kRoleM), R(kRoleQc), R(kRoleOm), g.wd, g.hd, g.w1, g.h1, + g.pad_l, g.pad_t}) + a[n++] = x; + Dispatch(*cur, kMConv2MidCells, groups, a, n, false); + return; + } Kernel tuned = kKernelCount; uint32_t tiles_per_wave = 0; uint32_t tile_h = 4; @@ -1840,6 +1916,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { {R(kRoleDc), R(kRoleQc), g.wd * g.hd}, false); return true; case FgOp::Net1Input: + if (cells_on) return true; // net1_01 builds its cells in LDS from the same images D(r, kNet1Input, groups_for(4ull * g.W0 * g.H0), {R(kRoleLd), R(kRoleDc), R(kRoleDp), R(kRoleF), R(kRoleMv), R(kRoleE), R(kRoleHc), R(kRoleHp), R(kRoleQp), R(kRoleM), n1_cells, R(kRoleQc), R(kRoleOm), g.wd, g.hd, g.w1, g.h1, g.W0, g.H0, @@ -1883,6 +1960,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { return true; } case FgOp::Weights: + if (op.lite_blend ? lite_weights_on : full_weights_on) return true; // the blend computes W in LDS D(r, kWeights, groups_for(nsc), {R(kRoleMA), R(kRoleMB), R(kRoleNA), R(kRoleNB), R(kRoleW), g.w1, g.h1, g.wd, g.hd}); return true; @@ -1905,6 +1983,17 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { g.w1, g.h1, fb(op.t), op.flag1 ? 1u : 0u, op.flag2 ? 1u : 0u}; for (uint32_t x : h) a[n++] = x; for (uint32_t x : rg) a[n++] = x; + if (lite_weights_on) { + // W is built in the blend: 32 x 8 pixel tiles; net1's logit pairs and grid at the end + uint32_t w[34]; + std::copy_n(a, n, w); + w[n++] = R(kRoleNA); + w[n++] = R(kRoleNB); + w[n++] = g.wd; + w[n++] = g.hd; + Dispatch(r, packed ? kLiteBlendPackW : kLiteBlendW, cdiv(g.wo, 32) * cdiv(g.ho, 8), w, n); + return true; + } Dispatch(r, packed ? kLiteBlendPack : kLiteBlend, groups_for(static_cast(g.wo) * g.ho), a, n); return true; } @@ -1915,7 +2004,14 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { op.ui ? R(kRoleUp) : 0u, op.ui ? R(kRoleUc) : 0u, x0, x1, xw, ib, ic, ia, g.wo, g.ho, g.w1, g.h1, g.wd, g.hd, g.k, g.Wp / 16, op.ui ? 1u : 0u, nb_x.off, fb(op.t)}; - Dispatch(r, merged ? kFullBlendMerge : kFullBlend, (g.Wp / 16) * (g.Hp / 16), a, merged ? 25u : 23u); + uint32_t n = merged ? 25u : 23u; + uint32_t av[27]; + std::copy_n(a, n, av); + if (full_weights_on) { + av[n++] = R(kRoleNA); + av[n++] = R(kRoleNB); + } + Dispatch(r, FullBlendKernel(merged), (g.Wp / 16) * (g.Hp / 16), av, n); net2_input_merged = merged; return true; } @@ -2036,6 +2132,8 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { const Net2Buf* y2 = nullptr; const Net2Buf* skip1 = nullptr; const Net2Buf* skip2 = nullptr; + bool upwarp = false; // L14 with the upwarp in its staging (uw_on): fbits = f's bits + uint32_t fbits = 0; }; uint32_t mconv_half_last = 0; // Net2SelfTest negative control: the next MConv on half its workgroups // One fg_net2_mconv launch: layer n from x into y, cin input channels, conv grid H x W. @@ -2069,12 +2167,29 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { mconv_half_last = 0; } auto off = [](const Net2Buf* b) { return b ? b->off : 0u; }; + if (o.upwarp) { + // L14: the same launch as m1b2 / m1b2s, input y built from the heads and the means in the staging + const uint32_t uw = v.kernel == kN2m1b2 ? kN2m1b2Uw : kN2m1b2sUw; + uint32_t a[38] = {x.off, n2fw[n - 1], n2fb[n - 1], y.off, off(o.skip), off(o.y1), off(o.y2), off(o.skip1), + off(o.skip2), x.c, 0u, cin, H, W, 0u, co_n, out_cs, 0u, o.pool, o.leaky, o.clamp_from, + o.res, o.res_mul, o.skip_cs, 0u, tx, ty, o.heads, + ib, ic, ia, nb_hA4.off, nb_hA1.off, nb_hA3.off, nb_U4.off, nb_U1.off, nb_U3.off, + o.fbits}; + Dispatch(r, uw, wg, a, 38); + return; + } D(r, v.kernel, wg, {x.off, n2fw[n - 1], n2fb[n - 1], y.off, off(o.skip), off(o.y1), off(o.y2), off(o.skip1), off(o.skip2), x.c, 0u, cin, H, W, 0u, co_n, out_cs, 0u, o.pool, o.leaky, o.clamp_from, o.res, o.res_mul, o.skip_cs, 0u, tx, ty, o.heads}); } + // net2's residual pair (layers n, n + 1: both 3 x 3, C channels, the second adds its input) in one launch + void MPair(Rec& r, uint32_t kernel, uint32_t n, const Net2Buf& x, const Net2Buf& y) { + const uint32_t tx = cdiv(x.w, 14), ty = cdiv(x.h, 6); + D(r, kernel, tx * ty, {x.off, n2fw[n - 1], n2fb[n - 1], n2fw[n], n2fb[n], y.off, x.h, x.w, tx, ty}); + } + void RecordNet2Fast(Rec& r, float f, bool half_last) { const uint32_t npx = g.W2 * g.H2; MergeNet2Inputs(r, npx, f); @@ -2085,6 +2200,11 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { MConv(r, 3, nb_a2, nb_r0, 32, nb_a2.h, nb_a2.w, pool); const Net2Buf* src = &nb_r0; for (uint32_t u = 0; u < 4; ++u) { + if (pair64_on) { + MPair(r, kPairC64, 4 + 2 * u, *src, nb_r[u]); + src = &nb_r[u]; + continue; + } MOpt a; a.res = 1; MConv(r, 4 + 2 * u, *src, nb_t[u], 64, src->h, src->w, a); @@ -2109,13 +2229,25 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { l13.y1 = &nb_hA1; l13.y2 = &nb_hA3; MConv(r, 13, nb_g, nb_hA4, 32, nb_hA4.h, nb_hA4.w, l13); - D(r, kNet2Upwarp, std::max(1, cdiv(npx, 256)), - {ib, ic, ia, nb_hA4.off, nb_hA1.off, nb_hA3.off, nb_U4.off, nb_U1.off, nb_U3.off, nb_y.off, g.W2, g.H2, - fb(f)}); - MConv(r, 14, nb_y, nb_b1, 18, g.H2, g.W2, pool); + if (uw_on) { + MOpt l14 = pool; + l14.upwarp = true; + l14.fbits = fb(f); + MConv(r, 14, nb_y, nb_b1, 18, g.H2, g.W2, l14); // y is built in the staging (U4, U1, U3 written there) + } else { + D(r, kNet2Upwarp, std::max(1, cdiv(npx, 256)), + {ib, ic, ia, nb_hA4.off, nb_hA1.off, nb_hA3.off, nb_U4.off, nb_U1.off, nb_U3.off, nb_y.off, g.W2, g.H2, + fb(f)}); + MConv(r, 14, nb_y, nb_b1, 18, g.H2, g.W2, pool); + } MConv(r, 15, nb_b1, nb_s0, 16, nb_b1.h, nb_b1.w, pool); src = &nb_s0; for (uint32_t u = 0; u < 4; ++u) { + if (pair32_on) { + MPair(r, kPairC32, 16 + 2 * u, *src, nb_s[u]); + src = &nb_s[u]; + continue; + } MOpt a; a.res = 1; MConv(r, 16 + 2 * u, *src, nb_tb[u], 32, src->h, src->w, a); @@ -2154,7 +2286,8 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { // fuse_pack: the pull and push-fine kernels write the slot's packed rows (pack_off, pack_pitch bytes, format // code in the out_x argument) instead of the float16 image const bool packed = fuse_pack != 0; - D(r, packed ? kOutPullPack : kOutPull, tx * ty, + const uint32_t pull = packed ? (x3_on ? kOutPullPackX3 : kOutPullPack) : (x3_on ? kOutPullX3 : kOutPull); + D(r, pull, tx * ty, {x0, x1, xw, nb_out.off, sig, packed ? pack_off : out_off, fine, lv[1], lv[2], lv[3], lv[4], g.wo, g.ho, g.W2, g.H2, g.k, tx, packed ? pack_pitch : out_stride, packed ? fuse_pack : 0u, 0u, fb(rk)}); const uint32_t lc = g.out_coarsest; @@ -2163,16 +2296,48 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { FgExecOutLevelSize(g, 4, &w4, &h4); D(r, kOutPullMid, cdiv(w4, 16) * cdiv(h4, 16), {lv[4], lv[5], lv[6], lv[7], lv[8], w4, h4, cdiv(w4, 16), g.wo, g.ho}); } - for (uint32_t l = lc - 1; l >= 1; --l) { + int first = static_cast(lc) - 1; // the first level a separate launch pushes + if (tail_on) { + // the coarsest levels (as many as fit in the tail kernel's LDS, none below level 2) pushed by one workgroup + uint32_t cells = 0, nlev = 0; + for (uint32_t l = lc; l >= 2 && nlev < 8; --l) { + uint32_t w, h; + FgExecOutLevelSize(g, l, &w, &h); + cells += w * h; + if (cells > 3584) break; + nlev = lc - l + 1; + } + if (nlev >= 2) { + uint32_t a[25] = {nlev}; + for (uint32_t j = 0; j < 8; ++j) { + uint32_t w = 0, h = 0; + if (j < nlev) FgExecOutLevelSize(g, lc - j, &w, &h); + a[1 + j] = j < nlev ? lv[lc - j] : 0u; + a[9 + j] = w; + a[17 + j] = h; + } + Dispatch(r, kOutTail, 1, a, 25); + first = static_cast(lc - nlev); + } + } + for (int l = first; l >= (l1_on ? 2 : 1); --l) { uint32_t wf, hf, wc, hc; - FgExecOutLevelSize(g, l, &wf, &hf); - FgExecOutLevelSize(g, l + 1, &wc, &hc); + FgExecOutLevelSize(g, static_cast(l), &wf, &hf); + FgExecOutLevelSize(g, static_cast(l) + 1, &wc, &hc); D(r, kOutPush, groups_for(static_cast(wf) * hf), {lv[l], lv[l + 1], lv[l], wf, hf, wc, hc}); - if (l == 1) break; } uint32_t w1o, h1o; FgExecOutLevelSize(g, 1, &w1o, &h1o); + if (l1_on) { + // level 1 is pushed on the fly for the holes: the fine pass takes the filled level 2 as well + uint32_t w2o, h2o; + FgExecOutLevelSize(g, 2, &w2o, &h2o); + D(r, packed ? kFinePackL1 : kFineL1, groups_for(static_cast(g.wo) * g.ho), + {fine, lv[1], packed ? pack_off : out_off, g.wo, g.ho, w1o, h1o, packed ? pack_pitch : out_stride, + packed ? fuse_pack : 0u, 0u, lv[2], w2o, h2o}); + return; + } D(r, packed ? kOutPushFinePack : kOutPushFine, groups_for(static_cast(g.wo) * g.ho), {fine, lv[1], packed ? pack_off : out_off, g.wo, g.ho, w1o, h1o, packed ? pack_pitch : out_stride, packed ? fuse_pack : 0u, 0u}); @@ -2562,6 +2727,17 @@ FgD3d12Executor::FgD3d12Executor(const FgD3d12ExecutorDesc& desc) : impl_(new Im impl_->want_hoist = lever(desc.hoist, "WG_FG_HOIST"); impl_->want_dualq = lever(desc.dualq, "WG_FG_DUALQ"); impl_->want_fuse = lever(desc.fuse, "WG_FG_FUSE"); + // Wave 1B: 0 off, 1 (or unset) every lever, any other value a mask of the levers (1 net1 cells, 2 net2 pairs, 4 upwarp + // in L14, 8 W in the blends, 16 pyramid tail, 32 X0 / X1 as RGB) + { + int v = desc.fuse2; + if (v < 0) { + char e[16] = {}; + v = GetEnvironmentVariableA("WG_FG_FUSE2", e, sizeof(e)) > 0 ? static_cast(std::strtol(e, nullptr, 0)) : 1; + if (v < 0) v = 1; + } + impl_->want_fuse2 = v == 0 ? 0u : (v == 1 ? static_cast(kF2All) : static_cast(v) & kF2All); + } if (desc.weights) { impl_->weights = *desc.weights; impl_->have_weights = true; @@ -3035,6 +3211,12 @@ FgExecResult FgD3d12Executor::RecordGeneratedIndex(const FgIndexDispatchDesc& d, } bool FgD3d12Executor::BatchesGenerated() const { return impl_->batch_on; } +uint32_t FgD3d12Executor::Fuse2Active() const { + const Impl& m = *impl_; + return (m.cells_on ? kF2Cells : 0u) | (m.pair64_on || m.pair32_on ? kF2Pair : 0u) | (m.uw_on ? kF2Upwarp : 0u) | + (m.lite_weights_on || m.full_weights_on ? kF2Weights : 0u) | (m.tail_on || m.l1_on ? kF2Tail : 0u) | + (m.x3_on ? kF2X3 : 0u); +} bool FgD3d12Executor::BatchActive() const { return impl_->batch_on; } bool FgD3d12Executor::HoistActive() const { return impl_->hoist_on; } bool FgD3d12Executor::DualQueueActive() const { return impl_->dualq_on; } diff --git a/clean/fg/runtime/fg_d3d12_executor.h b/clean/fg/runtime/fg_d3d12_executor.h index 156f82fb..8b895ab3 100644 --- a/clean/fg/runtime/fg_d3d12_executor.h +++ b/clean/fg/runtime/fg_d3d12_executor.h @@ -178,7 +178,14 @@ struct FgD3d12ExecutorDesc { // - fuse (WG_FG_FUSE=0 off): the fused / retiled kernels fg_lite_p2c_fine_mask (fine pass + hole mask), // fg_lite_p2c_inpaint_tiled and fg_lite_interm_both (both intermediate-time passes, LDS-binned scatters) replace // their separate kernels when their DXIL is in the kernel folder. - int batch = -1, hoist = -1, dualq = -1, fuse = -1; + // - fuse2 (WG_FG_FUSE2=0 off; Wave 1B, each exact against the Wave 1 kernels it replaces): 0 off, 1 (the default) every + // lever whose kernels are in the folder, any other value a mask of levers: 1 net1_01 builds its cells in LDS + // (fg_mconv2_mid_cells, no net1 input launch), 2 net2's residual pairs in one launch (fg_net2_mpair_res_c64 / _c32), + // 4 the upwarp computed in L14's staging (fg_net2_mconv_m1b2_uw), 8 the blend weights built in the blends + // (fg_lite_blend_w / _pack_w, fg_full_blend_*_w), 16 the output pyramid's coarse pushes in one workgroup + // (fg_out_tail) and level 1 pushed in the fine pass (fg_out_push_fine_l1), 32 X0 / X1 stored as RGB + // (fg_full_blend_*_x3, fg_out_pull_x3). Independent of fuse. + int batch = -1, hoist = -1, dualq = -1, fuse = -1, fuse2 = -1; // Developer frame dumps (off while dump_dir is empty; the ASI sets it only in a developer build): of the game // frames that generate, every dump_every-th one (at most dump_max), the game frame's slot image (game_.ppm) and // each generated slot image (gen__.ppm) are copied to a readback buffer after the slot write, and written as @@ -276,6 +283,9 @@ class FgD3d12Executor final : public IFgKernelExecutor { // The levers that are active after Configure (a lever the device or the arena cannot take stays off). bool BatchActive() const; bool HoistActive() const; + // The Wave 1B levers that run after Configure (bits as FgD3d12ExecutorDesc::fuse2 lists them: 1 net1 cells, 2 net2 + // pairs, 4 upwarp in L14, 8 blend weights, 16 pyramid tail, 32 X0 / X1 as RGB); 0 when off or their kernels are missing. + uint32_t Fuse2Active() const; bool DualQueueActive() const; uint32_t ScratchBanks() const; // keep_outputs: waits idle and moves the host copies out (oldest first). diff --git a/clean/fg/runtime/fg_exec_plan.cpp b/clean/fg/runtime/fg_exec_plan.cpp index 4c674628..64ed234c 100644 --- a/clean/fg/runtime/fg_exec_plan.cpp +++ b/clean/fg/runtime/fg_exec_plan.cpp @@ -388,7 +388,10 @@ void FgExecHost::IndexOps(float t, bool hudless_now, bool ui4_now, bool out_subr o.op = FgOp::Interm; o.t = t; ops->push_back(o); - simple(FgOp::Weights, ops); + FgExecOp w; + w.op = FgOp::Weights; + w.lite_blend = lite_; + ops->push_back(w); if (out_subrect) simple(FgOp::Prefill, ops); if (lite_) { FgExecOp b; diff --git a/clean/fg/runtime/fg_exec_plan.h b/clean/fg/runtime/fg_exec_plan.h index 4b32fab5..d9fffc07 100644 --- a/clean/fg/runtime/fg_exec_plan.h +++ b/clean/fg/runtime/fg_exec_plan.h @@ -130,6 +130,7 @@ struct FgExecOp { float t = 0.0f; bool flag1 = false, flag2 = false; bool ui = false; + bool lite_blend = false; // Weights: the blend that follows is the light blend (else the Full blend) }; struct FgExecFrameInfo { diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index 52988ad1..4de8f1b0 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -12,8 +12,10 @@ // [--gen N] N = 1..5 generated images per game frame (2x .. 6x), really recorded (default 1) // [--preset AC] which presets (default AC) [--timed N] [--warmup N] // [--kprof] per-launch profile: kernel, workgroups, time per call (serialises the queue a little) -// [--batch 0|1] [--hoist 0|1] [--dualq 0|1] [--fuse 0|1] Turbo v2 levers for paired A / B runs (default: on, -// or the environment WG_FG_BATCH / _HOIST / _DUALQ / _FUSE = 0) +// [--batch 0|1] [--hoist 0|1] [--dualq 0|1] [--fuse 0|1] [--fuse2 0|1|MASK] Turbo v2 levers for paired A / B runs +// (default: on, or the environment WG_FG_BATCH / _HOIST / _DUALQ / _FUSE / _FUSE2 = 0; --fuse2 takes +// a mask of the Wave 1B levers: 1 net1 cells, 2 net2 pairs, 4 upwarp in L14, 8 blend weights, +// 16 pyramid tail, 32 X0 / X1 as RGB) // The report has the per-stage sums and the honest multi-queue numbers: the wall-clock GPU span and the busy // time per game frame over the timed window (overlap between queues is counted once there, twice in the sums). // --reference-dxil compare direct-SRV output bytes against the captured path built with these kernels @@ -1885,11 +1887,15 @@ void TestInputSrvPaths(Gpu& gpu, const std::string& dxil, const std::string& ref // and retiled kernels) must give the same bytes as every lever off, in every generated slot and the real one, over several // game frames (history, swaps), the presets A / B / C and N = 1 .. 5. Both executors read the same game textures and run // the same kernel folder (`dxil`: the Turbo kernels sit beside the ones they replace). -void TestTurboExact(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights) { - g_case = "gpu-turbo-exact"; +// wave1b_only: both executors run the Wave 1 levers (batch, hoist, dualq, fuse), only the Wave 1B levers (fuse2) differ: +// the fused kernels against exactly the kernels they replace. +void TestTurboExact(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, bool wave1b_only = false) { + g_case = wave1b_only ? "gpu-turbo-exact-wave1b" : "gpu-turbo-exact"; { std::ifstream probe(dxil + "/fg_lite_interm_both.dxil", std::ios::binary); if (!probe) std::printf(" turbo: the Turbo v2 kernels are not in %s (batching, hoisting and the split only)\n", dxil.c_str()); + std::ifstream probe2(dxil + "/fg_net2_mpair_res_c64.dxil", std::ios::binary); + if (!probe2) std::printf(" turbo: the Wave 1B kernels are not in %s (fuse2 has nothing to run)\n", dxil.c_str()); } struct Case { FgPreset preset; @@ -1914,9 +1920,10 @@ void TestTurboExact(Gpu& gpu, const std::string& dxil, const FgExecWeights& weig ed.dxil_dir = dxil; ed.weights = &weights; ed.enable_full = c.preset != FgPreset::C; - ed.batch = ed.hoist = ed.dualq = ed.fuse = 1; + ed.batch = ed.hoist = ed.dualq = ed.fuse = ed.fuse2 = 1; FgD3d12Executor test(ed); - ed.batch = ed.hoist = ed.dualq = ed.fuse = 0; + ed.batch = ed.hoist = ed.dualq = ed.fuse = wave1b_only ? 1 : 0; + ed.fuse2 = 0; FgD3d12Executor ref(ed); FgCreateDesc create = CpuCreate(c.width, c.height); create.device = gpu.device.Get(); @@ -1938,10 +1945,12 @@ void TestTurboExact(Gpu& gpu, const std::string& dxil, const FgExecWeights& weig CHECK(false); return; } - std::printf(" turbo %s: batch %d hoist %d dualq %d banks %u (reference: batch %d hoist %d dualq %d)\n", name, - test.BatchActive(), test.HoistActive(), test.DualQueueActive(), test.ScratchBanks(), - ref.BatchActive(), ref.HoistActive(), ref.DualQueueActive()); - CHECK(!ref.BatchActive() && !ref.HoistActive() && !ref.DualQueueActive()); + std::printf(" turbo%s %s: batch %d hoist %d dualq %d banks %u fuse2 0x%x (reference: batch %d hoist %d dualq %d fuse2 0x%x)\n", + wave1b_only ? " (wave 1B)" : "", name, test.BatchActive(), test.HoistActive(), test.DualQueueActive(), + test.ScratchBanks(), test.Fuse2Active(), ref.BatchActive(), ref.HoistActive(), ref.DualQueueActive(), + ref.Fuse2Active()); + CHECK(ref.Fuse2Active() == 0); + if (!wave1b_only) CHECK(!ref.BatchActive() && !ref.HoistActive() && !ref.DualQueueActive()); bool exact_all = true; for (uint64_t token = 1; token <= 4; ++token) { if (!game.Upload(static_cast(token), false, token == 1)) { @@ -2008,7 +2017,7 @@ struct BenchOptions { uint32_t gen = 1, warmup = 8, timed = 30; std::string presets = "AC"; bool kprof = false; - int batch = -1, hoist = -1, dualq = -1, fuse = -1; // -1: the environment (default on) + int batch = -1, hoist = -1, dualq = -1, fuse = -1, fuse2 = -1; // -1: the environment (default on) }; bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, FgPreset preset, @@ -2036,6 +2045,7 @@ bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, F ed.hoist = bo.hoist; ed.dualq = bo.dualq; ed.fuse = bo.fuse; + ed.fuse2 = bo.fuse2; FgD3d12Executor exec(ed); const auto ok = [&](FgExecResult s) { if (s == FgExecResult::Ok) return true; @@ -2108,8 +2118,9 @@ bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, F static_assert(sizeof(stages) / sizeof(*stages) == static_cast(FgExecStage::Count)); std::printf("bench preset %c %ux (gen %u) %ux%u (%u warmup, %u timed, mean GPU ms per game frame)\n", label, gen_count + 1, gen_count, width, height, warmup, timed); - std::printf(" levers: batch %s, hoist %s, dualq %s, scratch banks %u\n", exec.BatchActive() ? "on" : "off", - exec.HoistActive() ? "on" : "off", exec.DualQueueActive() ? "on" : "off", exec.ScratchBanks()); + std::printf(" levers: batch %s, hoist %s, dualq %s, scratch banks %u, fuse2 mask 0x%x\n", exec.BatchActive() ? "on" : "off", + exec.HoistActive() ? "on" : "off", exec.DualQueueActive() ? "on" : "off", exec.ScratchBanks(), + exec.Fuse2Active()); double shared = 0.0, gen = 0.0; for (size_t i = 0; i < timing.ms.size(); ++i) { const double mean = timing.ms[i] / timed; @@ -2163,6 +2174,7 @@ int main(int argc, char** argv) { if (std::strcmp(argv[i], "--hoist") == 0 && i + 1 < argc) bo.hoist = std::atoi(argv[++i]); if (std::strcmp(argv[i], "--dualq") == 0 && i + 1 < argc) bo.dualq = std::atoi(argv[++i]); if (std::strcmp(argv[i], "--fuse") == 0 && i + 1 < argc) bo.fuse = std::atoi(argv[++i]); + if (std::strcmp(argv[i], "--fuse2") == 0 && i + 1 < argc) bo.fuse2 = static_cast(std::strtol(argv[++i], nullptr, 0)); if (std::strcmp(argv[i], "--dxil") == 0 && i + 1 < argc) dxil = argv[++i]; if (std::strcmp(argv[i], "--reference-dxil") == 0 && i + 1 < argc) reference_dxil = argv[++i]; if (std::strcmp(argv[i], "--scratch") == 0 && i + 1 < argc) scratch = argv[++i]; @@ -2255,7 +2267,10 @@ int main(int argc, char** argv) { } if (only.empty() || only.find("input-srv") != std::string::npos) TestInputSrvPaths(g, dxil, reference_dxil, weights); - if (only.empty() || only.find("turbo") != std::string::npos) TestTurboExact(g, dxil, weights); + if (only.empty() || only.find("turbo") != std::string::npos) { + TestTurboExact(g, dxil, weights); + TestTurboExact(g, dxil, weights, true); + } if (only.empty()) TestBrokenKernels(g, dxil, weights, scratch); } } diff --git a/clean/fg/tests/test_fg_turbo_v2.py b/clean/fg/tests/test_fg_turbo_v2.py index 806bc090..62cfab43 100644 --- a/clean/fg/tests/test_fg_turbo_v2.py +++ b/clean/fg/tests/test_fg_turbo_v2.py @@ -163,5 +163,382 @@ def test_a_value_above_the_empty_element_never_wins(self): self.assertEqual(min(EMPTY, v), EMPTY) +# ===================================================================================================================== +# Wave 1B (the fuse2 levers). Each class below states what the Wave 1 kernels compute and what the fused kernel computes, +# on the same inputs, and compares them; the HLSL itself is compared against the GPU by test_fg_d3d12_e2e --gpu +# (--only turbo: every lever on against every lever off, and Wave 1B alone against Wave 1). +# ===================================================================================================================== +import re +from pathlib import Path + +DX12 = Path(__file__).resolve().parents[2] / "dx12" + + +def _hlsl(rel): + return (DX12 / rel).read_text() + + +def _stripped(lines): + return [l.strip() for l in lines if l.strip()] + + +def _function_body(text, signature): + """The lines between the braces of the function that starts with `signature`.""" + start = text.index(signature) + open_ = text.index("{", start) + depth, i = 0, open_ + while True: + if text[i] == "{": + depth += 1 + elif text[i] == "}": + depth -= 1 + if depth == 0: + break + i += 1 + return text[open_ + 1:i].splitlines() + + +# ---- A13 / A6 / A14: the copied bodies stay copies ------------------------------------------------------------------------ +class CopiedBodiesTest(unittest.TestCase): + """The new kernels share a few lines of arithmetic with kernels whose DXIL had to stay byte-identical (so those + kernels were not rewritten to call a shared function): the copies are compared line by line.""" + + def test_weight_texel_is_fg_lite_weights(self): + kernel = _stripped(_function_body(_hlsl("kernels/fg_lite_g.hlsl"), "WG_KERNEL(fg_lite_weights)")) + helper = _stripped(_function_body(_hlsl("hlsl/fg_weights.hlsli"), "uint fg_weight_texel(")) + math_k = [l for l in kernel if l.startswith("const float") or l.startswith("const uint mi") or l.startswith("const uint ji")] + math_h = [l for l in helper if l.startswith("const float") or l.startswith("const uint mi") or l.startswith("const uint ji")] + self.assertEqual(len(math_k), 8) + self.assertEqual(math_k, math_h) + # the store: fg_st_h2(wout, idx, sigma(A1, A0), sigma(B1, B0)) is the packed pair the helper returns + self.assertIn("fg_st_h2(wout, idx, fg_sigmoid(A1, A0), fg_sigmoid(B1, B0));", kernel) + self.assertIn("return fg_pack_h2(fg_sigmoid(A1, A0), fg_sigmoid(B1, B0));", helper) + + def test_net1_pixel_is_fg_lite_net1_input(self): + kernel = _function_body(_hlsl("kernels/fg_lite_net1io.hlsl"), "WG_KERNEL(fg_lite_net1_input)") + k = _stripped(kernel) + a = next(i for i, l in enumerate(k) if l.startswith("if (Y < H0 && x >= 0")) + b = next(i for i, l in enumerate(k) if l.startswith("if (hwc) {") and i > a) + inner_k = [l for l in k[a + 2:b - 1]] # without the `{` and the closing `}` of the pixel block + helper = _stripped(_function_body(_hlsl("hlsl/fg_net1_pixel.hlsli"), "void fg_net1_pixel(")) + c = next(i for i, l in enumerate(helper) if l.startswith("if (active && x >= 0")) + inner_h = [l for l in helper[c + 2:-1] if l not in ("if (store_side)", "{", "}")] + inner_k = [l for l in inner_k if l not in ("{", "}")] + self.assertGreater(len(inner_k), 20) + self.assertEqual(inner_k, inner_h) + # fg_warp is the same function + wk = _stripped(_function_body(_hlsl("kernels/fg_lite_net1io.hlsl"), "float fg_warp(")) + wh = _stripped(_function_body(_hlsl("hlsl/fg_net1_pixel.hlsli"), "float fg_warp(")) + self.assertEqual(wk, wh) + + def test_up_taps_is_the_second_half_of_fgf_up(self): + full = _stripped(_function_body(_hlsl("hlsl/fg_full.hlsli"), "float4 fgf_up(")) + taps = _stripped(_function_body(_hlsl("hlsl/fg_full_up.hlsli"), "float4 fgf_up_taps(")) + z = next(i for i, l in enumerate(full) if l.startswith("const float z = fgf_zero()")) + self.assertEqual(full[z:], taps) + # the tap indices + idx = _stripped(_function_body(_hlsl("hlsl/fg_full_up.hlsli"), "void fgf_up_idx(")) + self.assertEqual([l for l in full if l.startswith("const int px") or l.startswith("const int nx") or l.startswith("const int ny")], + [l for l in idx if l.startswith("const int px") or l.startswith("const int nx") or l.startswith("const int ny")]) + loads = " ".join(full) + for expr in ("fgf_ld4h(lv, py * wc + px)", "fgf_ld4h(lv, py * wc + nx)", "fgf_ld4h(lv, ny * wc + px)", "fgf_ld4h(lv, ny * wc + nx)"): + self.assertIn(expr, loads) + self.assertEqual([l for l in idx if l.startswith("iP") or l.startswith("iX") or l.startswith("iY") or l.startswith("iD")], + ["iP = py * wc + px;", "iX = py * wc + nx;", "iY = ny * wc + px;", "iD = ny * wc + nx;"]) + + +# ---- A13: the W tile ------------------------------------------------------------------------------------------------------ +def _geometry(wo, ho): + dp = 4 if ho > 2880 else 2 + return wo // dp, ho // dp + + +def _taps(n_out, n_grid): + """x0 / x1 of the bilinear taps (fgf_tap / fg_read_linear) of every pixel of an axis of n_out pixels onto n_grid texels.""" + i = np.arange(n_out, dtype=np.float64) + u = np.clip(((i + 0.5).astype(F32) / F32(n_out)).astype(F32), 0, 1).astype(F32) # fgf_pixel_centre + t = (u.astype(np.float64) * n_grid - 0.5).astype(F32) # mad(u, n, -0.5) + f = np.floor(t) + r = np.clip(f.astype(np.int64), -1, n_grid - 1) + return np.maximum(r, 0), np.minimum(r + 1, n_grid - 1) + + +class WTileBoundTest(unittest.TestCase): + """The blends' LDS tile holds 12 x 12 (Full, 16 x 16 pixels) or 20 x 8 (light, 32 x 8 pixels) W texels: the taps of the + pixels of one tile span no more, for the frame sizes the executor takes (the scatter grid is a half or a quarter).""" + + SIZES = [(1920, 1080), (2560, 1440), (3840, 2160), (1280, 720), (640, 360), (3440, 1440), (2560, 1080), (5120, 2880), + (7680, 4320), (8192, 7680), (131, 89), (4, 4), (17, 33), (1001, 777), (4096, 2304)] + + def span(self, n_out, n_grid, tile): + x0, x1 = _taps(n_out, n_grid) + worst = 0 + for s in range(0, n_out, tile): + e = min(s + tile, n_out) + worst = max(worst, int(x1[s:e].max() - x0[s:e].min() + 1)) + return worst + + def test_full_blend_tile_is_12_by_12(self): + for wo, ho in self.SIZES: + w1, h1 = _geometry(wo, ho) + if w1 < 1 or h1 < 1: + continue + self.assertLessEqual(self.span(wo, w1, 16), 12, "%dx%d columns" % (wo, ho)) + self.assertLessEqual(self.span(ho, h1, 16), 12, "%dx%d rows" % (wo, ho)) + + def test_light_blend_tile_is_20_by_8(self): + for wo, ho in self.SIZES: + w1, h1 = _geometry(wo, ho) + if w1 < 1 or h1 < 1: + continue + self.assertLessEqual(self.span(wo, w1, 32), 20, "%dx%d columns" % (wo, ho)) + self.assertLessEqual(self.span(ho, h1, 8), 8, "%dx%d rows" % (wo, ho)) + + +# ---- A12: X0 / X1 as RGB ------------------------------------------------------------------------------------------------ +class X3LayoutTest(unittest.TestCase): + def test_pair_store_and_window_read(self): + rng = np.random.default_rng(5) + n = 64 + rgb = rng.integers(0, 65536, size=(n, 3), dtype=np.uint16) + a = rng.integers(0, 65536, size=n, dtype=np.uint16) + h_x = rgb[:, 0].astype(np.uint32) | (rgb[:, 1].astype(np.uint32) << 16) # r | g << 16 + h_y = rgb[:, 2].astype(np.uint32) | (a.astype(np.uint32) << 16) # b | a << 16 + out = np.zeros(n * 3, dtype=np.uint16) + words = np.zeros(n * 3 // 2, dtype=np.uint32) + for e in range(0, n, 2): # the even lane of a Morton pair + px, pa = (h_x[e], h_y[e]), (h_x[e + 1], h_y[e + 1]) # own and partner + at = e * 6 // 4 + words[at] = px[0] + words[at + 1] = (px[1] & 0xFFFF) | ((pa[0] << 16) & 0xFFFFFFFF) + words[at + 2] = (pa[0] >> 16) | ((pa[1] << 16) & 0xFFFFFFFF) + raw = words.tobytes() + np.testing.assert_array_equal(np.frombuffer(raw, dtype=np.uint16), rgb.reshape(-1)) + # fgp_ld3h: the 8 bytes from the dword at or below the texel's first byte hold its 6 bytes + buf = np.frombuffer(raw + bytes(8), dtype=np.uint32) + for i in range(n): + at = i * 6 + d = buf[(at & ~3) // 4], buf[(at & ~3) // 4 + 1] + hi = (at & 2) != 0 + rg = ((int(d[0]) >> 16) | (int(d[1]) << 16)) & 0xFFFFFFFF if hi else int(d[0]) + b = (int(d[1]) >> 16) if hi else (int(d[1]) & 0xFFFF) + self.assertEqual((rg & 0xFFFF, rg >> 16, b), tuple(int(v) for v in rgb[i])) + + +# ---- A9: L14's input tile from the upwarp --------------------------------------------------------------------------------- +class UpwarpStageLayoutTest(unittest.TestCase): + def test_four_groups_are_y_padded_to_32_channels(self): + rng = np.random.default_rng(9) + val = rng.integers(0, 65536, size=8, dtype=np.uint16) # the 8 warped values + U = rng.integers(0, 65536, size=8, dtype=np.uint16) # A4 (4), A1, A3 (3) + iav = int(rng.integers(0, 65536)) + hf = int(rng.integers(0, 65536)) + # fg_net2_upwarp's y: val, U.x U.y (A4), A1 | Ia << 16, A3[0] | A3[1] << 16, A3[2] | h(f) << 16 + y = list(val) + [U[0], U[1], U[2], U[3], U[4], iav, U[5], U[6], U[7], hf] + self.assertEqual(len(y), 18) + # the staged groups, as fg_stage_upwarp writes them (halves, low first) + g0 = list(val) + g1 = [U[0], U[1], U[2], U[3], U[4], iav, U[5], U[6]] + g2 = [U[7], hf, 0, 0, 0, 0, 0, 0] + g3 = [0] * 8 + self.assertEqual(g0 + g1 + g2 + g3, y + [0] * 14) + + +# ---- A14: the pyramid's tail and level 1 on the fly --------------------------------------------------------------------- +def _levels(wo, ho): + w, h, levels = wo, ho, 1 + while levels < 12 and (levels < 9 or w > 1 or h > 1): + w, h = (w + 1) // 2, (h + 1) // 2 + levels += 1 + sizes = [((wo + (1 << l) - 1) >> l, (ho + (1 << l) - 1) >> l) for l in range(levels)] + return sizes, (8 if levels > 9 else 4) + + +def _tail_levels(sizes, lc, cap=3584): + cells = nlev = 0 + for l in range(lc, 1, -1): + if nlev >= 8: + break + cells += sizes[l][0] * sizes[l][1] + if cells > cap: + break + nlev = lc - l + 1 + return nlev + + +F = np.float32 + + +def _h(x): + with np.errstate(all="ignore"): + return np.asarray(x, dtype=np.float32).astype(np.float16).astype(np.float32) + + +def _up_taps(eP, eX, eY, eD): + """fgf_up_taps on float32 4-vectors (the same function for both pipelines: this test is about which texel feeds which).""" + with np.errstate(all="ignore"): + ws = F(0.0625) * eD[3] + (F(0.1875) * eY[3] + (F(0.1875) * eX[3] + F(0.5625) * eP[3])) + vs = [F(0.0625) * (eD[c] * eD[3]) + (F(0.1875) * (eY[c] * eY[3]) + (F(0.1875) * (eX[c] * eX[3]) + F(0.5625) * (eP[c] * eP[3]))) + for c in range(3)] + den = min(max(ws, F(1e-12)), F(1.0)) + return np.array([vs[0] / den, vs[1] / den, vs[2] / den, ws], dtype=np.float32) + + +def _up(lv, wc, hc, qx, qy): + px, py = qx >> 1, qy >> 1 + nx = min(max(px + (1 if qx & 1 else -1), 0), wc - 1) + ny = min(max(py + (1 if qy & 1 else -1), 0), hc - 1) + return _up_taps(lv[py * wc + px], lv[py * wc + nx], lv[ny * wc + px], lv[ny * wc + nx]) + + +def _push(own, coarse, wf, wc, hc): + """fg_out_push in place: own where its weight is not <= 0 (NaN keeps it), else the upsample of the filled coarse level.""" + out = own.copy() + for i in range(len(own)): + if not (own[i][3] <= 0.0): + continue + out[i] = _h(_up(coarse, wc, hc, i % wf, i // wf)) + return out + + +class OutputTailTest(unittest.TestCase): + SIZES = [(1920, 1080), (2560, 1440), (3840, 2160), (131, 89), (200, 150), (64, 48), (7680, 4320), (4, 4), (255, 255), (256, 256)] + + def test_tail_levels_fit_and_stop_above_level_1(self): + for wo, ho in self.SIZES: + sizes, lc = _levels(wo, ho) + nlev = _tail_levels(sizes, lc) + if nlev >= 2: + lt = lc - nlev + 1 + self.assertGreaterEqual(lt, 2) + self.assertLessEqual(sum(sizes[l][0] * sizes[l][1] for l in range(lt, lc + 1)), 3584) + self.assertLessEqual(nlev, 8) + + def test_tail_and_level1_on_the_fly_equal_the_push_chain(self): + rng = np.random.default_rng(3) + for wo, ho in [(131, 89), (200, 150), (64, 48), (17, 33)]: + sizes, lc = _levels(wo, ho) + lv = [] + for (w, h) in sizes[:lc + 1]: + a = np.zeros((w * h, 4), dtype=np.float32) + a[:, :3] = _h(rng.random((w * h, 3))) + wgt = rng.choice([0.0, 0.0, 0.25, 1.0, -0.5, np.nan], size=w * h) + a[:, 3] = _h(wgt.astype(np.float32)) + lv.append(a) + # Wave 1: push levels lc - 1 .. 1 in place, then the fine pass reads filled level 1 + old = [a.copy() for a in lv] + for l in range(lc - 1, 0, -1): + old[l] = _push(old[l], old[l + 1], sizes[l][0], sizes[l + 1][0], sizes[l + 1][1]) + # Wave 1B: tail over the coarse levels, pushes down to level 2, level 1 pushed on the fly at the taps + new = [a.copy() for a in lv] + nlev = _tail_levels(sizes, lc) + first = lc - 1 + if nlev >= 2: + for l in range(lc - 1, lc - nlev, -1): + new[l] = _push(new[l], new[l + 1], sizes[l][0], sizes[l + 1][0], sizes[l + 1][1]) + first = lc - nlev + for l in range(first, 1, -1): + new[l] = _push(new[l], new[l + 1], sizes[l][0], sizes[l + 1][0], sizes[l + 1][1]) + w1, h1 = sizes[1] + w2, h2 = sizes[2] + + def texel1(i): + if not (new[1][i][3] <= 0.0): + return new[1][i] + return _h(_up(new[2], w2, h2, i % w1, i // w1)) + + for qy in range(ho): + for qx in range(wo): + px, py = qx >> 1, qy >> 1 + nx = min(max(px + (1 if qx & 1 else -1), 0), w1 - 1) + ny = min(max(py + (1 if qy & 1 else -1), 0), h1 - 1) + got = _up_taps(texel1(py * w1 + px), texel1(py * w1 + nx), texel1(ny * w1 + px), texel1(ny * w1 + nx)) + want = _up(old[1], w1, h1, qx, qy) + np.testing.assert_array_equal(got.view(np.uint32), want.view(np.uint32), err_msg="%dx%d (%d, %d)" % (wo, ho, qx, qy)) + + +# ---- A7: a residual pair in one launch ---------------------------------------------------------------------------------- +def _conv3(x, w, b): + """3 x 3 convolution, zero padding, float32 accumulation, float16 result (the same function for both pipelines).""" + H, W, _ = x.shape + out = np.zeros((H, W, w.shape[0]), dtype=np.float32) + xp = np.pad(x, ((1, 1), (1, 1), (0, 0))) + for ky in range(3): + for kx in range(3): + out += xp[ky:ky + H, kx:kx + W, :] @ w[:, :, ky, kx].T + return _h(out + b) + + +def _post(v, skip=None): + v = np.where(v < 0, _h(F(0.01) * v), v).astype(np.float32) # leaky ReLU + v = np.clip(v, -6, 6) + return _h(v + F(0.0)) if skip is None else _h(skip + v) # h(v + 0) / the residual add + + +def _fused_pair(x, wa, ba, wb, bb, tile_w=14, tile_h=6): + H, W, C = x.shape + out = np.zeros_like(x) + covered = np.zeros((H, W), dtype=np.int32) + for ty in range((H + tile_h - 1) // tile_h): + for tx in range((W + tile_w - 1) // tile_w): + ix, iy = tx * tile_w, ty * tile_h + # the input tile of 18 x 10 pixels from (ix - 2, iy - 2), zero outside the grid + tile = np.zeros((tile_h + 4, tile_w + 4, C), dtype=np.float32) + for r in range(tile_h + 4): + for c in range(tile_w + 4): + gx, gy = ix - 2 + c, iy - 2 + r + if 0 <= gx < W and 0 <= gy < H: + tile[r, c] = x[gy, gx] + # first layer on the 16 x 8 region (pixel (c, r) = conv pixel (ix - 1 + c, iy - 1 + r)), zero outside the grid + region = np.zeros((tile_h + 2, tile_w + 2, C), dtype=np.float32) + a = _post(_conv3(np.pad(tile, ((0, 0), (0, 0), (0, 0))), wa, ba)) + for r in range(tile_h + 2): + for c in range(tile_w + 2): + gx, gy = ix - 1 + c, iy - 1 + r + if 0 <= gx < W and 0 <= gy < H: + region[r, c] = a[1 + r, 1 + c] # the tile conv output at tile pixel (c + 1, r + 1) + # second layer on the interior from the region + b = _conv3(region, wb, bb) + for r in range(tile_h): + for c in range(tile_w): + gx, gy = ix + c, iy + r + if gx < W and gy < H: + out[gy, gx] = _post(b[1 + r, 1 + c], x[gy, gx]) + covered[gy, gx] += 1 + return out, covered + + +class PairFusionTest(unittest.TestCase): + def test_fused_pair_equals_two_launches(self): + rng = np.random.default_rng(21) + C = 4 + for H, W in [(12, 18), (17, 30), (3, 5), (6, 14), (7, 15), (34, 60), (1, 1), (9, 2)]: + x = _h(rng.normal(0, 1.5, size=(H, W, C))) + wa = (rng.normal(0, 0.3, size=(C, C, 3, 3))).astype(np.float32) + wb = (rng.normal(0, 0.3, size=(C, C, 3, 3))).astype(np.float32) + ba, bb = _h(rng.normal(0, 0.5, size=C)), _h(rng.normal(0, 0.5, size=C)) + a = _post(_conv3(x, wa, ba)) + want = _post(_conv3(a, wb, bb), x) + got, covered = _fused_pair(x, wa, ba, wb, bb) + np.testing.assert_array_equal(got, want, err_msg="%dx%d" % (H, W)) + self.assertTrue((covered == 1).all(), "every pixel is an interior pixel of exactly one workgroup") + + def test_region_and_tile_indexing_of_the_kernel(self): + # lane (n, row) of the region reads the input tile at (n + kx, row + ky) (18 columns, 10 rows); the second layer's + # interior lane (n < 14, row < 6) reads the region at (n + kx, row + ky): both inside what is staged + for n in range(16): + for row in range(8): + for ky in range(3): + for kx in range(3): + self.assertLess(n + kx, 18) + self.assertLess(row + ky, 10) + for n in range(14): + for row in range(6): + for ky in range(3): + for kx in range(3): + self.assertLess(n + kx, 16) + self.assertLess(row + ky, 8) + + if __name__ == "__main__": unittest.main() From 1b7deb76168a1dae315769a3f8f8d8d37ae440e6 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:28:58 -0500 Subject: [PATCH 11/15] Frame generation (D3D12): one arena alias and one driver-channel buffer per queue, so no buffer has writes from two queues in flight; the turbo test no longer re-claims COMMON for textures it already moved The debug layer's "Simultaneous-access or Buffer Resource is still referenced by write | transition_barrier GPU operations in-flight on another Command Queue" is raised for any two queues that use one buffer at the same time, UAV dispatches included (a two-queue program with the same shape raises it with and without transition barriers; one buffer resource per queue over the same heap memory raises nothing). The dual-queue and hoist levers do run the game queue's downsample and the second compute queue's fills / scatters beside the producer queue's work on disjoint ranges of the arena, so: - the arena is one heap with a placed buffer per queue that works in it at once (producer: arena, game queue: arena_game, second compute queue: arena_aux); the kernels see the same offsets through each, every recording uses its queue's alias (Rec::ares, Impl::ArenaFor) and starts with an aliasing barrier; fences still order every hand-over; - the driver-channel UAV of the descriptor tables is one buffer per queue's recordings as well. Test: TestTurboExact uploaded game frame 1 twice, the second time claiming the textures were in COMMON (state before = COMMON) when the first upload had left them in their input states: that was the "Before state ... does not match" error, not the executor. --- clean/fg/runtime/fg_d3d12_executor.cpp | 107 +++++++++++++++---- clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 3 +- 2 files changed, 88 insertions(+), 22 deletions(-) diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index 1cb2ad0d..143e6fe2 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -565,6 +565,7 @@ struct Rec { bool dirty = false; // a dispatch or copy wrote since the last UAV barrier bool open = false, direct = false, uses_arena = true; bool aux = false; // recorded for the second compute queue + ID3D12Resource* ares = nullptr; // the arena alias of the recording's queue (Impl::ArenaFor) ID3D12Resource* written_slots[kMaxWrittenSlots] = {}; uint32_t written_count = 0; // Submit: the game queue handoff value this recording waits for (0: the latest), the producer fence value an @@ -615,8 +616,54 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { std::vector direct_entries; ComPtr heap; uint32_t desc_inc = 0; - ComPtr channel; - ComPtr arena; + // the driver-channel UAV of the descriptor tables: one buffer per queue's recordings (like the arena aliases, so that + // no buffer is referenced by two queues at once) + ComPtr channel, channel_game, channel_aux; + // The arena is one block of memory in a heap, seen through one buffer resource per queue that works in it at the same + // time (the producer queue's `arena`, the game queue's `arena_game`, the second compute queue's `arena_aux`): all + // alias the same bytes and the kernels use the same offsets through each, but no resource ever has writes from two + // queues in flight (the debug layer, correctly, refuses that on one resource; the queues write disjoint ranges and + // meet only through fences). Every recording uses the alias of its queue (ArenaFor) and starts with an aliasing barrier. + ComPtr arena_heap; + ComPtr arena, arena_game, arena_aux; + ID3D12Resource* ArenaFor(const Rec& r) const { + if (r.aux && arena_aux) return arena_aux.Get(); + if (r.direct && arena_game) return arena_game.Get(); + return arena.Get(); + } + FgExecResult CreateArena() { + arena.Reset(); + arena_game.Reset(); + arena_aux.Reset(); + arena_heap.Reset(); + D3D12_HEAP_DESC hd = {}; + hd.SizeInBytes = arena_bytes; + hd.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; + hd.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + hd.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS; + if (FAILED(device->CreateHeap(&hd, IID_PPV_ARGS(&arena_heap)))) + return Fail(FgExecRefusal::AllocationFailed, "arena heap of " + std::to_string(arena_bytes) + " bytes"); + D3D12_RESOURCE_DESC rd = {}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = arena_bytes; + rd.Height = 1; + rd.DepthOrArraySize = 1; + rd.MipLevels = 1; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const auto place = [&](ComPtr* out) { + return SUCCEEDED(device->CreatePlacedResource(arena_heap.Get(), 0, &rd, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(out->GetAddressOf()))); + }; + if (!place(&arena) || (compute_queue && !place(&arena_game)) || (aux_queue && !place(&arena_aux))) { + arena.Reset(); + arena_game.Reset(); + arena_aux.Reset(); + return Fail(FgExecRefusal::AllocationFailed, "arena of " + std::to_string(arena_bytes) + " bytes"); + } + return FgExecResult::Ok; + } uint64_t arena_bytes = 0; ComPtr menu_rb; TimingQueries producer_queries, direct_queries, aux_queries; @@ -1154,8 +1201,17 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { desc_inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); channel = Buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + channel_game.Reset(); + channel_aux.Reset(); + if (compute_queue) + channel_game = Buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON); + if (aux_queue) + channel_aux = Buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON); menu_rb = Buffer(256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); - if (!channel || !menu_rb) return Fail(FgExecRefusal::AllocationFailed, "channel / readback buffer"); + if (!channel || !menu_rb || (compute_queue && !channel_game) || (aux_queue && !channel_aux)) + return Fail(FgExecRefusal::AllocationFailed, "channel / readback buffer"); for (uint32_t d = 0; d < hd.NumDescriptors; ++d) { D3D12_CPU_DESCRIPTOR_HANDLE h = heap->GetCPUDescriptorHandleForHeapStart(); h.ptr += static_cast(d) * desc_inc; @@ -1165,7 +1221,11 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uav.Buffer.NumElements = 64; uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; - device->CreateUnorderedAccessView(channel.Get(), nullptr, &uav, h); + const uint32_t entry = d / (kTables * kTableSize); // rings: producer, game queue, second queue + ID3D12Resource* ch = aux_queue && entry >= first_aux ? channel_aux.Get() + : compute_queue && entry >= n ? channel_game.Get() + : channel.Get(); + device->CreateUnorderedAccessView(ch, nullptr, &uav, h); } else { D3D12_SHADER_RESOURCE_VIEW_DESC sv = {}; sv.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; @@ -1369,7 +1429,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { FgExecResult b = Begin(&r); if (b != FgExecResult::Ok) return b; ArenaTo(r, D3D12_RESOURCE_STATE_COPY_DEST); - r.cl->CopyBufferRegion(arena.Get(), weight_base, up.Get(), 0, weight_image.size()); + r.cl->CopyBufferRegion(r.ares, weight_base, up.Get(), 0, weight_image.size()); uint64_t v = 0; b = Submit(&r, &v); if (b != FgExecResult::Ok) return b; @@ -1382,6 +1442,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { r->aux = aux && aux_queue; r->direct = !r->aux && compute_queue && on_game_queue; r->uses_arena = uses_arena; + r->ares = ArenaFor(*r); auto& ring = r->aux ? aux_entries : r->direct ? direct_entries : entries; ID3D12Fence* reuse_fence = r->aux ? aux_fence.Get() : r->direct ? handoff_fence.Get() : fence.Get(); Entry* e = nullptr; @@ -1419,9 +1480,17 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { ID3D12DescriptorHeap* heaps[] = {heap.Get()}; r->cl->SetDescriptorHeaps(1, heaps); r->cl->SetComputeRootSignature(root.Get()); - r->cl->SetComputeRootUnorderedAccessView(0, arena->GetGPUVirtualAddress()); - r->cl->SetComputeRootUnorderedAccessView(1, arena->GetGPUVirtualAddress()); + r->cl->SetComputeRootUnorderedAccessView(0, r->ares->GetGPUVirtualAddress()); + r->cl->SetComputeRootUnorderedAccessView(1, r->ares->GetGPUVirtualAddress()); SetTable(*r, 0); + if (arena_game || arena_aux) { + // the memory was last used through another alias (another queue's, or this queue's own earlier recording) + D3D12_RESOURCE_BARRIER ab = {}; + ab.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + ab.Aliasing.pResourceBefore = nullptr; + ab.Aliasing.pResourceAfter = r->ares; + r->cl->ResourceBarrier(1, &ab); + } r->arena = D3D12_RESOURCE_STATE_COMMON; ArenaTo(*r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); cur = r; @@ -1438,7 +1507,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { if (r.arena == s) return; D3D12_RESOURCE_BARRIER b = {}; b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - b.Transition.pResource = arena.Get(); + b.Transition.pResource = r.ares; b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; b.Transition.StateBefore = r.arena; b.Transition.StateAfter = s; @@ -2522,7 +2591,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dst.SubresourceIndex = 0; D3D12_TEXTURE_COPY_LOCATION src = {}; - src.pResource = arena.Get(); + src.pResource = r.ares; src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; src.PlacedFootprint.Offset = src_off; src.PlacedFootprint.Footprint.Format = d.Format; @@ -2550,8 +2619,8 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { p.colour = Buffer(colb, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); p.slot = Buffer(slotb, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); if (p.image && p.colour && p.slot) { - r.cl->CopyBufferRegion(p.image.Get(), 0, arena.Get(), out_off, img); - r.cl->CopyBufferRegion(p.colour.Get(), 0, arena.Get(), cap_colour, colb); + r.cl->CopyBufferRegion(p.image.Get(), 0, r.ares, out_off, img); + r.cl->CopyBufferRegion(p.colour.Get(), 0, r.ares, cap_colour, colb); Transition(r, res, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); D3D12_TEXTURE_COPY_LOCATION s2 = {}; s2.pResource = res; @@ -2864,11 +2933,7 @@ FgExecResult FgD3d12Executor::Configure(const FgCreateDesc& cd, uint32_t /*histo s = m.Layout(banks); if (s == FgExecResult::Ok) s = m.FillWeightImage(); if (s == FgExecResult::Ok) { - m.arena = m.Buffer(m.arena_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_COMMON); - if (!m.arena) - s = m.Fail(FgExecRefusal::AllocationFailed, - "arena of " + std::to_string(m.arena_bytes) + " bytes"); + s = m.CreateArena(); } if (s != FgExecResult::Ok && banks > 1) { banks = 1; @@ -3097,7 +3162,7 @@ FgExecResult FgD3d12Executor::RecordSharedGameFrame(const FgSharedDispatchDesc& if (!m.RecordOp(*r, op)) return FgExecResult::Refused; if (op.op == FgOp::Detect) { m.ArenaTo(*r, D3D12_RESOURCE_STATE_COPY_SOURCE); - r->cl->CopyBufferRegion(m.menu_rb.Get(), 0, m.arena.Get(), m.detres_off, 32); + r->cl->CopyBufferRegion(m.menu_rb.Get(), 0, r->ares, m.detres_off, 32); s = m.Submit(r, &menu_value); if (s != FgExecResult::Ok) return s; r = &post_detect; @@ -3410,9 +3475,9 @@ FgExecResult FgD3d12Executor::Net2SelfTest(uint32_t seed, float t, uint32_t runs FgExecResult st = m.Begin(&r); if (st != FgExecResult::Ok) return st; m.ArenaTo(r, D3D12_RESOURCE_STATE_COPY_DEST); - r.cl->CopyBufferRegion(m.arena.Get(), m.ib, up.Get(), 0, n2 * 8); - r.cl->CopyBufferRegion(m.arena.Get(), m.ic, up.Get(), n2 * 8, n2 * 8); - r.cl->CopyBufferRegion(m.arena.Get(), m.ia, up.Get(), n2 * 16, n2 * 2); + r.cl->CopyBufferRegion(r.ares, m.ib, up.Get(), 0, n2 * 8); + r.cl->CopyBufferRegion(r.ares, m.ic, up.Get(), n2 * 8, n2 * 8); + r.cl->CopyBufferRegion(r.ares, m.ia, up.Get(), n2 * 16, n2 * 2); const uint32_t sentinel[4] = {0x5A5A, 0x5A5A, 0x5A5A, 0x5A5A}; m.Fill16(r, m.nb_out.off, out_bytes, sentinel, 1); if (m.fast()) @@ -3420,7 +3485,7 @@ FgExecResult FgD3d12Executor::Net2SelfTest(uint32_t seed, float t, uint32_t runs else m.RecordNet2(r, t); m.ArenaTo(r, D3D12_RESOURCE_STATE_COPY_SOURCE); - r.cl->CopyBufferRegion(rb.Get(), 0, m.arena.Get(), m.nb_out.off, out_bytes); + r.cl->CopyBufferRegion(rb.Get(), 0, r.ares, m.nb_out.off, out_bytes); uint64_t v = 0; st = m.Submit(&r, &v); if (st != FgExecResult::Ok) return st; diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index 4de8f1b0..a6e375a8 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -1953,7 +1953,8 @@ void TestTurboExact(Gpu& gpu, const std::string& dxil, const FgExecWeights& weig if (!wave1b_only) CHECK(!ref.BatchActive() && !ref.HoistActive() && !ref.DualQueueActive()); bool exact_all = true; for (uint64_t token = 1; token <= 4; ++token) { - if (!game.Upload(static_cast(token), false, token == 1)) { + // (the textures already hold frame 1's state from the upload above: `first` would claim COMMON again) + if (!game.Upload(static_cast(token), false, false)) { CHECK(false); return; } From 9188c8870e9efbb9fb0ed9873cb573a237d9c98e Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:45:40 -0500 Subject: [PATCH 12/15] Frame generation (D3D12): Wave 1B defaults to the two levers that win in paired timing (net1 cells + pyramid tail); the others stay opt-in Paired ABBA at 2560x1440 on an RX 9070 XT (6 rounds, 200 frames): all six Wave 1B levers together cost +13 .. +306 us per game frame over Wave 1 (preset A 2x..6x, preset C 2x..6x); the weights-in-the-blend lever (A13) is the worst (+60 .. +245 us), then net2 pairs (A7) and the upwarp in L14 (A9) on preset A, and RGB X0 / X1 (A12) is neutral. Net1 cells (A6) and the pyramid tail (A14) win alone and together. - fuse2 = 1 (the default, WG_FG_FUSE2 unset) now means mask 17 (A6 + A14); 63 runs every lever; any other value is still a mask; 0 is off. - test_fg_d3d12_e2e: --only turbo runs the Wave 1B legs against every lever on (63) by default; --turbo-fuse2 MASK picks another mask (--turbo-fuse2 1 runs the executor's default levers). Both are byte-exact with the D3D12 debug layer at 0 errors. --- clean/fg/README.md | 2 +- clean/fg/runtime/fg_d3d12_executor.cpp | 11 +++++++---- clean/fg/runtime/fg_d3d12_executor.h | 5 +++-- clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 6 +++++- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/clean/fg/README.md b/clean/fg/README.md index eb62cdd2..5e3fc573 100644 --- a/clean/fg/README.md +++ b/clean/fg/README.md @@ -66,7 +66,7 @@ front end or the launcher yet. Status, open items and formats: [FORMATS.md](FORM | `runtime/fg_exec_plan.h`, `.cpp` | the D3D12 executor's CPU side (F7b, plain C++17): the light path's settings, the grid sizes of a frame size (net1 image and cell grids, scatter grid and pyramid, net2's factor and grid, the output pyramid), application regions and their ten kernel values, the float16 rounding, and the schedule of `reference/pipeline.py` `Host` split at the session's seam: once per game frame (history clears, menu detection or the disable word, R3 .. R8, net1's input / net1 / output or the quality image), per index (the intermediate-time scatters, the blend weights, the light blend for preset C or the Full blend, net2 and the output pyramid for presets A / B, the menu output; the game frame's copy without history) and the last-index part (history advances, the image pairs swap) | | `runtime/fg_d3d12_executor.h`, `.cpp` | `FgD3d12Executor`, the production `IFgKernelExecutor` on the game's D3D12 device and queue (F7b): one root signature for every FG kernel (arena root UAVs, 59 root constants, the driver channel and one texture view), the kernels' DXIL loaded from a folder built by `clean/dx12/build_dx12.py --only` and their pipelines built once, the arena sized for the frame (every image, net1's three regions, the input capture areas, the Full path and net2) with the weights uploaded at configuration; per game frame the inputs are captured from the game's textures (`fg_exec_io.hlsl`) and the shared stages recorded, the menu detection read back (a bounded wait on that submission only); per index the generated image is written into the presenter slot's texture (packed to the slot's format, COMMON -> COPY_DEST -> COMMON) and the shared producer fence signalled; menu / priming copies and the game frame's endpoint copy the colour exactly; an adapter-side real-only frame (no shared work) is captured from the game's back buffer and copied into a reserved slot (F9); net2 runs on the fast path by default (27 launches on the matrix unit, tier B: `fg_net2_mconv.hlsl`, `fg_net2_upwarp.hlsl`, the plan of `runner/fg_net2_mma.py`) with the exact 38-launch chain selectable (`FgD3d12ExecutorDesc::net2`), and `Net2SelfTest` runs net2 alone on synthetic inputs for the comparison and timing legs; every refusal names its reason and nothing falls back. `FgExecutorPresenterSource` binds the executor to the composition or DXGI back end the session creates; `FgExecWeightsFromModel` takes the weights from a checked model file | | `runtime/tests/test_fg_d3d12_e2e.cpp` | ctest `fg_d3d12_e2e` (CPU): geometry, regions, thresholds and the logistic table against the CPU reference, the float16 rounding, the schedule, every executor refusal that needs no GPU and a session whose executor refuses (no presenter, no fallback). `--gpu --dxil /dx12` adds the headless GPU leg (no window): a synthetic game through the adapter core, the session and the executor with the composition back end (unbound surface) and the DXGI back end (composition swap chain) for preset C 2x / 6x and presets A / B 2x with a menu frame, net2's exact path, and frames with generation switched off in the game's options (real-only from the back buffer) (generated images finite, menu and endpoint copies exact, slot bytes equal to the image in the slot's format, fences complete, DXGI slots all returned, the swap chain released right after teardown; `--debug-layer` adds the D3D12 debug layer), net2's fast path against the exact one on synthetic inputs (within tolerance, deterministic, every value written, a half-covered last launch caught; GPU time at the 1080p and 1440p grids, information only), and kernel folders with a broken kernel that must be refused | -| Turbo v2 (executor levers, all exact: the kernels' arithmetic is untouched, only where and when independent work runs and four fused / retiled kernels) | `WG_FG_BATCH=0` / `WG_FG_HOIST=0` / `WG_FG_DUALQ=0` / `WG_FG_FUSE=0` (or `FgD3d12ExecutorDesc::batch / hoist / dualq / fuse`) turn a lever off for paired A / B runs; all four give the same bytes as all four off (`test_fg_d3d12_e2e --gpu --dxil --only turbo`: every slot over four game frames, presets A / B / C, N = 1..5, byte for byte). Scratch banks: the per-index images (MA, MB, W, the generated image and its packed rows, the Full blend's images, net2's tensors, the output pyramid) are one block repeated once per generated index (`max_generated` banks while the arena fits). `RecordGeneratedBatch` (the session calls it when `BatchesGenerated()`) records layer k of every index back to back, so barriers sit only between dependent layers and the small net2 / pyramid layers of several indices fill the GPU together. Hoist: the per-index MA / MB fills and intermediate-time scatters of every index of the game frame run on a second compute queue beside net1 (they read only the p2c results) and the producer queue waits for them before the first index. Dual queue: the game queue's work is two recordings (motion preparation, then the downsample) so the p2c chain starts after the first and the net1 input waits for the second. Fuse: `fg_lite_p2c_fine_mask` (fine pass + hole mask when the net1 grid is the scatter grid), `fg_lite_p2c_inpaint_tiled` (32 x 8 tiles, ballot row masks), `fg_lite_interm_both` (both passes, 32 x 32 LDS-binned signed 64-bit minima) and `fg_net2_mconv_h3b1u_s3` (L25's three heads staged in one pass). Wave 1B (`WG_FG_FUSE2=0` or `FgD3d12ExecutorDesc::fuse2 = 0` keeps the Wave 1 kernels; a mask picks levers: 1 net1 cells, 2 net2 pairs, 4 upwarp in L14, 8 blend weights, 16 pyramid tail, 32 X0 / X1 as RGB; `test_fg_d3d12_e2e --bench --fuse2 0|1|MASK`; each exact against the kernels it replaces, checked by `--gpu --only turbo` in two legs: every lever on against every lever off, and Wave 1B alone against Wave 1): `fg_mconv2_mid_cells` (net1_01 builds its cells in LDS from the same images `fg_lite_net1_input` packs and writes Qc / Om itself: no input launch, no cell round trip), `fg_net2_mpair_res_c64` / `_c32` (net2's residual pairs L4+L5 .. L10+L11 and L16+L17 .. L22+L23 in one launch: 14 x 6 interiors, the first layer on the 16 x 8 region with its border and its output kept in LDS), `fg_net2_mconv_m1b2_uw` / `_m1b2s_uw` (L14 computes the upwarp for its staged tile and writes U4 / U1 / U3 itself: no y tensor, no upwarp launch), `fg_lite_blend_w` / `_pack_w` and `fg_full_blend_w` / `_merge_w` (the blend builds the W texels its tile's taps touch in LDS: no weights launch or W image read), `fg_out_tail` (the coarsest pushes in one workgroup, as many levels as fit 28 KB of LDS) with `fg_out_push_fine_l1` / `_pack_l1` (level 1 pushed on the spot at the holes' taps: no level-1 launch), and `fg_full_blend_*_x3` / `fg_out_pull_x3` (X0 / X1 stored as 6-byte RGB: only the output pull reads them and never their alpha). The CPU proofs of their exactness arguments are in `tests/test_fg_turbo_v2.py` (copied bodies compared line by line, tile bounds, the pyramid push chain, the residual pair fusion). Profiling: `WRONGGPU_FG_KPROF=1` or `test_fg_d3d12_e2e --bench --kprof` lists every launch (kernel, workgroups, us); `--gen N` benchmarks 2x..6x for real and reports the wall-clock span and busy time of all queues next to the per-stage sums; the CPU proofs of the exactness arguments are `tests/test_fg_turbo_v2.py`, and `runner/fg_lite_d3d12_check.py --turbo` checks the Turbo kernels against the CPU reference | +| Turbo v2 (executor levers, all exact: the kernels' arithmetic is untouched, only where and when independent work runs and four fused / retiled kernels) | `WG_FG_BATCH=0` / `WG_FG_HOIST=0` / `WG_FG_DUALQ=0` / `WG_FG_FUSE=0` (or `FgD3d12ExecutorDesc::batch / hoist / dualq / fuse`) turn a lever off for paired A / B runs; all four give the same bytes as all four off (`test_fg_d3d12_e2e --gpu --dxil --only turbo`: every slot over four game frames, presets A / B / C, N = 1..5, byte for byte). Scratch banks: the per-index images (MA, MB, W, the generated image and its packed rows, the Full blend's images, net2's tensors, the output pyramid) are one block repeated once per generated index (`max_generated` banks while the arena fits). `RecordGeneratedBatch` (the session calls it when `BatchesGenerated()`) records layer k of every index back to back, so barriers sit only between dependent layers and the small net2 / pyramid layers of several indices fill the GPU together. Hoist: the per-index MA / MB fills and intermediate-time scatters of every index of the game frame run on a second compute queue beside net1 (they read only the p2c results) and the producer queue waits for them before the first index. Dual queue: the game queue's work is two recordings (motion preparation, then the downsample) so the p2c chain starts after the first and the net1 input waits for the second. Fuse: `fg_lite_p2c_fine_mask` (fine pass + hole mask when the net1 grid is the scatter grid), `fg_lite_p2c_inpaint_tiled` (32 x 8 tiles, ballot row masks), `fg_lite_interm_both` (both passes, 32 x 32 LDS-binned signed 64-bit minima) and `fg_net2_mconv_h3b1u_s3` (L25's three heads staged in one pass). Wave 1B (`WG_FG_FUSE2=0` or `FgD3d12ExecutorDesc::fuse2 = 0` keeps the Wave 1 kernels; the default (1) runs the two levers that won in paired timing at 1440p on an RX 9070 XT, net1 cells + pyramid tail (mask 17), and 63 runs every lever (net2 pairs, upwarp in L14, blend weights and RGB X0 / X1 are exact but cost GPU time, so they stay opt-in); a mask picks levers: 1 net1 cells, 2 net2 pairs, 4 upwarp in L14, 8 blend weights, 16 pyramid tail, 32 X0 / X1 as RGB; `test_fg_d3d12_e2e --bench --fuse2 0|1|MASK`; each exact against the kernels it replaces, checked by `--gpu --only turbo` in two legs: every lever on against every lever off, and Wave 1B alone against Wave 1): `fg_mconv2_mid_cells` (net1_01 builds its cells in LDS from the same images `fg_lite_net1_input` packs and writes Qc / Om itself: no input launch, no cell round trip), `fg_net2_mpair_res_c64` / `_c32` (net2's residual pairs L4+L5 .. L10+L11 and L16+L17 .. L22+L23 in one launch: 14 x 6 interiors, the first layer on the 16 x 8 region with its border and its output kept in LDS), `fg_net2_mconv_m1b2_uw` / `_m1b2s_uw` (L14 computes the upwarp for its staged tile and writes U4 / U1 / U3 itself: no y tensor, no upwarp launch), `fg_lite_blend_w` / `_pack_w` and `fg_full_blend_w` / `_merge_w` (the blend builds the W texels its tile's taps touch in LDS: no weights launch or W image read), `fg_out_tail` (the coarsest pushes in one workgroup, as many levels as fit 28 KB of LDS) with `fg_out_push_fine_l1` / `_pack_l1` (level 1 pushed on the spot at the holes' taps: no level-1 launch), and `fg_full_blend_*_x3` / `fg_out_pull_x3` (X0 / X1 stored as 6-byte RGB: only the output pull reads them and never their alpha). The CPU proofs of their exactness arguments are in `tests/test_fg_turbo_v2.py` (copied bodies compared line by line, tile bounds, the pyramid push chain, the residual pair fusion). Profiling: `WRONGGPU_FG_KPROF=1` or `test_fg_d3d12_e2e --bench --kprof` lists every launch (kernel, workgroups, us); `--gen N` benchmarks 2x..6x for real and reports the wall-clock span and busy time of all queues next to the per-stage sums; the CPU proofs of the exactness arguments are `tests/test_fg_turbo_v2.py`, and `runner/fg_lite_d3d12_check.py --turbo` checks the Turbo kernels against the CPU reference | | `clean/dx12/kernels/fg_exec_io.hlsl` | the executor's input capture (a game texture of any readable format into the arena's float16 / float32 image kinds) and output pack (the float16 image into a slot format: RGBA16F, RGBA8 / BGRA8, RGB10A2) | | `fg_limits.h` | `kFgMaxGenerated`, shared by the presenter and the runtime so one file can include both (the runtime contract's own status and real-only enums are `FgFrameStatus` / `FgFrameRealOnly`, distinct from the presenter's `FgStatus` / `FgRealOnlyReason`) | | `tools/gen_fg_runtime_tables.py`, `tests/test_fg_runtime_tables.py` | writes / checks the two generated headers (the map table; the fused plan and the weight fragments of constructed float16 patterns from `runner/fg_net1_mma.py`) | diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index 143e6fe2..b070cc36 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -59,6 +59,9 @@ enum Kernel : uint32_t { // the Wave 1B levers (bits of FgD3d12ExecutorDesc::fuse2 when it is a mask) enum Fuse2Bit : uint32_t { kF2Cells = 1, kF2Pair = 2, kF2Upwarp = 4, kF2Weights = 8, kF2Tail = 16, kF2X3 = 32, kF2All = 63, + // the levers that won in paired ABBA runs at 1440p (A6 net1 cells, A14 pyramid tail); the others are exact but cost GPU time + // (A13 weights in the blends, A7 net2 pairs, A9 upwarp in L14, A12 RGB X0 / X1) and stay opt-in (a mask, e.g. 63) + kF2Default = kF2Cells | kF2Tail, }; constexpr uint32_t kFirstTurbo = kFineMask; // a pipeline of these that the device refuses is dropped, not fatal constexpr uint32_t kFirstFull = kFullBlend; @@ -682,7 +685,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { bool want_batch = true, want_hoist = true, want_dualq = true, want_fuse = true; bool batch_on = false, hoist_on = false, dualq_on = false; // Wave 1B (fuse2 bits wanted; the *_on flags are decided in Layout from the kernels that are present) - uint32_t want_fuse2 = kF2All; + uint32_t want_fuse2 = kF2Default; bool Fused2(uint32_t bit, uint32_t k) const { return (want_fuse2 & bit) != 0 && pso[k] != nullptr; } bool cells_on = false; // A6: net1_01 builds its cells in LDS (the net1 input launch is dropped) bool pair64_on = false, pair32_on = false; // A7: net2's residual pairs (64- / 32-channel) in one launch @@ -2796,8 +2799,8 @@ FgD3d12Executor::FgD3d12Executor(const FgD3d12ExecutorDesc& desc) : impl_(new Im impl_->want_hoist = lever(desc.hoist, "WG_FG_HOIST"); impl_->want_dualq = lever(desc.dualq, "WG_FG_DUALQ"); impl_->want_fuse = lever(desc.fuse, "WG_FG_FUSE"); - // Wave 1B: 0 off, 1 (or unset) every lever, any other value a mask of the levers (1 net1 cells, 2 net2 pairs, 4 upwarp - // in L14, 8 W in the blends, 16 pyramid tail, 32 X0 / X1 as RGB) + // Wave 1B: 0 off, 1 (or unset) the default levers (net1 cells + pyramid tail), any other value a mask of the levers (1 net1 + // cells, 2 net2 pairs, 4 upwarp in L14, 8 W in the blends, 16 pyramid tail, 32 X0 / X1 as RGB; 63 = every lever) { int v = desc.fuse2; if (v < 0) { @@ -2805,7 +2808,7 @@ FgD3d12Executor::FgD3d12Executor(const FgD3d12ExecutorDesc& desc) : impl_(new Im v = GetEnvironmentVariableA("WG_FG_FUSE2", e, sizeof(e)) > 0 ? static_cast(std::strtol(e, nullptr, 0)) : 1; if (v < 0) v = 1; } - impl_->want_fuse2 = v == 0 ? 0u : (v == 1 ? static_cast(kF2All) : static_cast(v) & kF2All); + impl_->want_fuse2 = v == 0 ? 0u : (v == 1 ? static_cast(kF2Default) : static_cast(v) & kF2All); } if (desc.weights) { impl_->weights = *desc.weights; diff --git a/clean/fg/runtime/fg_d3d12_executor.h b/clean/fg/runtime/fg_d3d12_executor.h index 8b895ab3..5b44ffa5 100644 --- a/clean/fg/runtime/fg_d3d12_executor.h +++ b/clean/fg/runtime/fg_d3d12_executor.h @@ -178,8 +178,9 @@ struct FgD3d12ExecutorDesc { // - fuse (WG_FG_FUSE=0 off): the fused / retiled kernels fg_lite_p2c_fine_mask (fine pass + hole mask), // fg_lite_p2c_inpaint_tiled and fg_lite_interm_both (both intermediate-time passes, LDS-binned scatters) replace // their separate kernels when their DXIL is in the kernel folder. - // - fuse2 (WG_FG_FUSE2=0 off; Wave 1B, each exact against the Wave 1 kernels it replaces): 0 off, 1 (the default) every - // lever whose kernels are in the folder, any other value a mask of levers: 1 net1_01 builds its cells in LDS + // - fuse2 (WG_FG_FUSE2=0 off; Wave 1B, each exact against the Wave 1 kernels it replaces): 0 off, 1 (the default) the levers + // that won in paired timing (1 + 16: net1 cells and the pyramid tail), any other value a mask of levers (63 = every lever + // whose kernels are in the folder; 2, 4, 8, 32 are exact but cost GPU time): 1 net1_01 builds its cells in LDS // (fg_mconv2_mid_cells, no net1 input launch), 2 net2's residual pairs in one launch (fg_net2_mpair_res_c64 / _c32), // 4 the upwarp computed in L14's staging (fg_net2_mconv_m1b2_uw), 8 the blend weights built in the blends // (fg_lite_blend_w / _pack_w, fg_full_blend_*_w), 16 the output pyramid's coarse pushes in one workgroup diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index a6e375a8..c583b4eb 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -16,6 +16,7 @@ // (default: on, or the environment WG_FG_BATCH / _HOIST / _DUALQ / _FUSE / _FUSE2 = 0; --fuse2 takes // a mask of the Wave 1B levers: 1 net1 cells, 2 net2 pairs, 4 upwarp in L14, 8 blend weights, // 16 pyramid tail, 32 X0 / X1 as RGB) +// [--turbo-fuse2 MASK] the Wave 1B mask the --only turbo legs run against all levers off (default 63: every lever) // The report has the per-stage sums and the honest multi-queue numbers: the wall-clock GPU span and the busy // time per game frame over the timed window (overlap between queues is counted once there, twice in the sums). // --reference-dxil compare direct-SRV output bytes against the captured path built with these kernels @@ -567,6 +568,7 @@ struct PipelineClock { } }; bool g_debug_layer = false; +int g_turbo_fuse2 = 63; // the Wave 1B mask TestTurboExact runs against all levers off (--turbo-fuse2 MASK) int g_log_lines = 0; void PrintLog(void*, const char* line) { if (g_log_lines++ < 40) std::printf(" log: %s\n", line); @@ -1920,7 +1922,8 @@ void TestTurboExact(Gpu& gpu, const std::string& dxil, const FgExecWeights& weig ed.dxil_dir = dxil; ed.weights = &weights; ed.enable_full = c.preset != FgPreset::C; - ed.batch = ed.hoist = ed.dualq = ed.fuse = ed.fuse2 = 1; + ed.batch = ed.hoist = ed.dualq = ed.fuse = 1; + ed.fuse2 = g_turbo_fuse2; // 63: every Wave 1B lever (default of the test), --turbo-fuse2 1: the executor's default levers FgD3d12Executor test(ed); ed.batch = ed.hoist = ed.dualq = ed.fuse = wave1b_only ? 1 : 0; ed.fuse2 = 0; @@ -2180,6 +2183,7 @@ int main(int argc, char** argv) { if (std::strcmp(argv[i], "--reference-dxil") == 0 && i + 1 < argc) reference_dxil = argv[++i]; if (std::strcmp(argv[i], "--scratch") == 0 && i + 1 < argc) scratch = argv[++i]; if (std::strcmp(argv[i], "--debug-layer") == 0) g_debug_layer = true; + if (std::strcmp(argv[i], "--turbo-fuse2") == 0 && i + 1 < argc) g_turbo_fuse2 = static_cast(std::strtol(argv[++i], nullptr, 0)); if (std::strcmp(argv[i], "--only") == 0 && i + 1 < argc) only = argv[++i]; } FgExecWeights weights; From 133e87efa9e5695b372afa3e980a2db72c0cd72b Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:42:32 -0500 Subject: [PATCH 13/15] Frame generation (D3D12): Wave 2 levers A15-A18, all bit-exact and switchable (fuse2 bits 64-1024, WG_FG_NET2_BATCH) A15 (64): fg_lite_fill16_p2, the fill without integer divisions. A lane's eight units are the same four words for every lane (first is a multiple of 8, the period 1, 2 or 4 divides 8), so the 16-byte word is built once and the tail unit is i & (period - 1). RGA: 9 v_mul_hi_u32 -> 0, 329 -> 82 instructions, 22 -> 5 VGPRs. Same grid and arguments. A16 (128): the _b kernels (fg_lite_blend / _pack, fg_lite_weights, fg_full_blend / _merge, fg_out_pull / _pack) read a bilinear tap row with one 16-byte (float16 x 4) or 8-byte (float16 x 2) load, since x1 is x0 + 1 or x0 itself at the frame border. The same four texel values reach the same fma chain. RGA: loads 34 -> 20 (light blend), 30 -> 18 (full blend), 12 -> 8 (weights), 19 -> 15 (pull); VGPRs up by 0 to 10 (at most 64, the 16-wave cap is unchanged); no scratch. A17 (256, 512): fg_lite_blend_t / _pack_t run 32 x 8 pixel tiles (tiles_x * ceil(ho / 8) workgroups) with an 8-byte pair store in the packed output and no per-pixel division; fg_out_pull_q skips the four divisions of a pyramid level on tiles without a hole, where the weight is 4^m and the division is the exact power-of-two scale. RGA: per-pixel division 1 -> 0. A18 (1024, WG_FG_NET2_BATCH=0 off): the _z twins of net2's fg_net2_mconv kernels (WG_Z_GRID, FG_ZB) take the launch of every index of a batch as one (groups, 1, N) dispatch; slice z adds z * bank stride to the pointers that differ between the frames. FgPlanZBatch decides it from the recorded arguments (CPU-tested); any other launch stays separate. The originals and their checkers are unchanged. WG_FG_FUSE2=17 is the Wave 1B default; the new default is 2001 (17 + 64 + 128 + 256 + 512 + 1024) and 2047 is every lever. The e2e turbo test now runs every lever against every lever off. Every unmodified DXIL is byte-identical to the previous set. CPU proofs: clean/fg/tests/test_fg_turbo_v2_wave2.py. --- clean/dx12/hlsl/fg_full.hlsli | 24 ++ clean/dx12/hlsl/fg_lite_common.hlsli | 32 ++ clean/dx12/hlsl/wg_platform.hlsli | 10 + clean/dx12/kernels/fg_full_blend.hlsl | 2 + clean/dx12/kernels/fg_lite_blend.hlsl | 36 ++ clean/dx12/kernels/fg_lite_g.hlsl | 1 + clean/dx12/kernels/fg_lite_util.hlsl | 29 ++ clean/dx12/kernels/fg_net2_mconv.hlsl | 45 ++ clean/dx12/kernels/fg_out_pull.hlsl | 20 +- clean/fg/runtime/fg_d3d12_executor.cpp | 148 ++++++- clean/fg/runtime/fg_d3d12_executor.h | 7 + clean/fg/runtime/fg_exec_plan.cpp | 19 + clean/fg/runtime/fg_exec_plan.h | 8 + clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 73 +++- clean/fg/tests/test_fg_turbo_v2_wave2.py | 410 +++++++++++++++++++ 15 files changed, 847 insertions(+), 17 deletions(-) create mode 100644 clean/fg/tests/test_fg_turbo_v2_wave2.py diff --git a/clean/dx12/hlsl/fg_full.hlsli b/clean/dx12/hlsl/fg_full.hlsli index fab816a9..0a708448 100644 --- a/clean/dx12/hlsl/fg_full.hlsli +++ b/clean/dx12/hlsl/fg_full.hlsli @@ -116,8 +116,32 @@ float2 fgf_mix2(FgfTap t, float2 c00, float2 c10, float2 c01, float2 c11) return mad(t.w11, c11, mad(t.w01, c01, mad(t.w00, c00, t.w10 * c10))); } +#ifndef FG_BIL128 +#define FG_BIL128 0 +#endif +#if FG_BIL128 +// A16: the two texels of a tap row are adjacent (i10 == i00 + 1) or the same texel (i10 == i00: the frame's left / right +// border clamps x1 to x0), so one load at i00 covers both: 16 bytes for 4 x float16 texels (8 for 2 x float16), the second +// texel taken from it unless the border made it the first. The same four texel values reach fgf_mix4 / fgf_mix2, so the +// result is bit for bit the 4-load version's. (Reads one texel past i00 at the frame's last texel: robust buffer access.) +float4 fgf_unpack4h(uint2 d) { return float4(wg_h2f_lo(d.x), wg_h2f_hi(d.x), wg_h2f_lo(d.y), wg_h2f_hi(d.y)); } +float4 fgf_bil4h(uint p, FgfTap t) +{ + const uint4 a = wg_ld128(p, (uint)t.i00 * 8u), b = wg_ld128(p, (uint)t.i01 * 8u); + const uint2 c10 = select(t.i10 == t.i00, a.xy, a.zw), c11 = select(t.i11 == t.i01, b.xy, b.zw); + return fgf_mix4(t, fgf_unpack4h(a.xy), fgf_unpack4h(c10), fgf_unpack4h(b.xy), fgf_unpack4h(c11)); +} +float2 fgf_unpack2h(uint d) { return float2(wg_h2f_lo(d), wg_h2f_hi(d)); } +float2 fgf_bil2h(uint p, FgfTap t) +{ + const uint2 a = wg_ld64(p, (uint)t.i00 * 4u), b = wg_ld64(p, (uint)t.i01 * 4u); + const uint c10 = select(t.i10 == t.i00, a.x, a.y), c11 = select(t.i11 == t.i01, b.x, b.y); + return fgf_mix2(t, fgf_unpack2h(a.x), fgf_unpack2h(c10), fgf_unpack2h(b.x), fgf_unpack2h(c11)); +} +#else float4 fgf_bil4h(uint p, FgfTap t) { return fgf_mix4(t, fgf_ld4h(p, t.i00), fgf_ld4h(p, t.i10), fgf_ld4h(p, t.i01), fgf_ld4h(p, t.i11)); } float2 fgf_bil2h(uint p, FgfTap t) { return fgf_mix2(t, fgf_ld2h(p, t.i00), fgf_ld2h(p, t.i10), fgf_ld2h(p, t.i01), fgf_ld2h(p, t.i11)); } +#endif // ---- output pyramid ----------------------------------------------------------------------------------------------------- // (sum r, sum g, sum b, sum w) -> (r / max(sum w, 1e-12), ..., sum w / n) diff --git a/clean/dx12/hlsl/fg_lite_common.hlsli b/clean/dx12/hlsl/fg_lite_common.hlsli index 1d118635..93568138 100644 --- a/clean/dx12/hlsl/fg_lite_common.hlsli +++ b/clean/dx12/hlsl/fg_lite_common.hlsli @@ -14,6 +14,9 @@ #pragma once #include "fg_fp16.hlsli" +#ifndef FG_BIL128 +#define FG_BIL128 0 +#endif static uint fg_z_; // 0 at run time (the grid size is below 2^31), unknown to the compiler #define FG_SETUP() (FG_FP16_SETUP(), fg_z_ = wg_grid_ >> 31) @@ -136,8 +139,37 @@ float4 fg_read_linear(uint base, uint kind, int w, int h, float X, float Y) float ax = px - fx, ay = py - fy; int rx = clamp((int)fx, -1, w - 1), ry = clamp((int)fy, -1, h - 1); int x0 = max(rx, 0), x1 = min(rx + 1, w - 1), y0 = max(ry, 0), y1 = min(ry + 1, h - 1); +#if FG_BIL128 + // A16 (kinds 4 and 2): x1 is x0 + 1 or x0 itself (the border clamp), so one load per row covers both texels + // (16 bytes for float16 x 4, 8 for float16 x 2) and the same four texel values reach the blend below. + float4 t00, t10, t01, t11; + if (kind == 4u) + { + const uint4 a = wg_ld128(base, (uint)(y0 * w + x0) * 8u), b = wg_ld128(base, (uint)(y1 * w + x0) * 8u); + const uint2 a1 = select(x1 == x0, a.xy, a.zw), b1 = select(x1 == x0, b.xy, b.zw); + t00 = float4(f16tof32(a.x), f16tof32(a.x >> 16), f16tof32(a.y), f16tof32(a.y >> 16)); + t10 = float4(f16tof32(a1.x), f16tof32(a1.x >> 16), f16tof32(a1.y), f16tof32(a1.y >> 16)); + t01 = float4(f16tof32(b.x), f16tof32(b.x >> 16), f16tof32(b.y), f16tof32(b.y >> 16)); + t11 = float4(f16tof32(b1.x), f16tof32(b1.x >> 16), f16tof32(b1.y), f16tof32(b1.y >> 16)); + } + else if (kind == 2u) + { + const uint2 a = wg_ld64(base, (uint)(y0 * w + x0) * 4u), b = wg_ld64(base, (uint)(y1 * w + x0) * 4u); + const uint a1 = select(x1 == x0, a.x, a.y), b1 = select(x1 == x0, b.x, b.y); + t00 = float4(f16tof32(a.x), f16tof32(a.x >> 16), 0.0f, 0.0f); + t10 = float4(f16tof32(a1), f16tof32(a1 >> 16), 0.0f, 0.0f); + t01 = float4(f16tof32(b.x), f16tof32(b.x >> 16), 0.0f, 0.0f); + t11 = float4(f16tof32(b1), f16tof32(b1 >> 16), 0.0f, 0.0f); + } + else + { + t00 = fg_texel(base, kind, (uint)(y0 * w + x0)); t10 = fg_texel(base, kind, (uint)(y0 * w + x1)); + t01 = fg_texel(base, kind, (uint)(y1 * w + x0)); t11 = fg_texel(base, kind, (uint)(y1 * w + x1)); + } +#else float4 t00 = fg_texel(base, kind, (uint)(y0 * w + x0)), t10 = fg_texel(base, kind, (uint)(y0 * w + x1)); float4 t01 = fg_texel(base, kind, (uint)(y1 * w + x0)), t11 = fg_texel(base, kind, (uint)(y1 * w + x1)); +#endif float4 r0 = mad(ax.xxxx, t10 - t00, t00); float4 r1 = mad(ax.xxxx, t11 - t01, t01); return mad(ay.xxxx, r1 - r0, r0); diff --git a/clean/dx12/hlsl/wg_platform.hlsli b/clean/dx12/hlsl/wg_platform.hlsli index 4a6b1f36..7d6e8ad9 100644 --- a/clean/dx12/hlsl/wg_platform.hlsli +++ b/clean/dx12/hlsl/wg_platform.hlsli @@ -37,8 +37,18 @@ globallycoherent RWByteAddressBuffer wg_mem_gc : register(u1); // the same memo static uint wg_tid_; // lane index in the workgroup (HIP threadIdx.x) static uint wg_bid_; // workgroup index in the grid (HIP blockIdx.x) +#ifndef WG_Z_GRID +#define WG_Z_GRID 0 +#endif +#if WG_Z_GRID // a kernel declared with WG_Z_GRID=1 is launched as (groups, 1, N): wg_gid_z() is the z slice (0 .. N - 1) +#define WG_KERNEL(name) [numthreads(WG_BLOCK, 1, 1)] [WaveSize(WG_WAVE)] \ + void name(uint wg_sv_tid_ : SV_GroupThreadID, uint3 wg_sv_gid3_ : SV_GroupID) +#define wg_sv_gid_ (wg_sv_gid3_.x) +#define wg_gid_z() (wg_sv_gid3_.z) +#else #define WG_KERNEL(name) [numthreads(WG_BLOCK, 1, 1)] [WaveSize(WG_WAVE)] \ void name(uint wg_sv_tid_ : SV_GroupThreadID, uint wg_sv_gid_ : SV_GroupID) +#endif #if WG_REV_ORDER // a kernel declared with WG_REV_ORDER=1: workgroup g does the work of workgroup G - 1 - g (the same // bytes; the last-written part of its input, likelier still in the caches, first) #define WG_SETUP() (wg_tid_ = wg_sv_tid_, wg_bid_ = wg_grid_ - 1u - (wg_sv_gid_ + wg_group_base_)) diff --git a/clean/dx12/kernels/fg_full_blend.hlsl b/clean/dx12/kernels/fg_full_blend.hlsl index 26e76834..3b1082c8 100644 --- a/clean/dx12/kernels/fg_full_blend.hlsl +++ b/clean/dx12/kernels/fg_full_blend.hlsl @@ -24,6 +24,8 @@ // // @wg-kernel fg_full_blend co=fg_full.co block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u // @wg-kernel fg_full_blend_merge co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,u defines=FGB_MERGE=1 +// @wg-kernel fg_full_blend_b co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u defines=FG_BIL128=1 +// @wg-kernel fg_full_blend_merge_b co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,u defines=FGB_MERGE=1,FG_BIL128=1 // @wg-kernel fg_full_blend_w co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,p defines=FGB_WEIGHTS=1 // @wg-kernel fg_full_blend_merge_w co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,p,u,p,p defines=FGB_MERGE=1,FGB_WEIGHTS=1 // @wg-kernel fg_full_blend_x3 co=- entry=fg_full_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u defines=FGB_X3=1 diff --git a/clean/dx12/kernels/fg_lite_blend.hlsl b/clean/dx12/kernels/fg_lite_blend.hlsl index e70606ba..cdec0246 100644 --- a/clean/dx12/kernels/fg_lite_blend.hlsl +++ b/clean/dx12/kernels/fg_lite_blend.hlsl @@ -19,6 +19,12 @@ // // @wg-kernel fg_lite_blend co=- block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u // @wg-kernel fg_lite_blend_pack co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_PACK=1 +// @wg-kernel fg_lite_blend_b co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_BIL128=1 +// @wg-kernel fg_lite_blend_pack_b co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_PACK=1,FG_BIL128=1 +// @wg-kernel fg_lite_blend_t co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_TILE=1 +// @wg-kernel fg_lite_blend_pack_t co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_PACK=1,FG_TILE=1 +// @wg-kernel fg_lite_blend_bt co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_TILE=1,FG_BIL128=1 +// @wg-kernel fg_lite_blend_pack_bt co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_PACK=1,FG_TILE=1,FG_BIL128=1 // @wg-kernel fg_lite_blend_mut co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MUT=1 // @wg-kernel fg_lite_blend_w co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,u,u defines=FG_WEIGHTS=1 // @wg-kernel fg_lite_blend_pack_w co=- entry=fg_lite_blend block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,u,u defines=FG_PACK=1,FG_WEIGHTS=1 @@ -35,6 +41,9 @@ #ifndef FG_WEIGHTS #define FG_WEIGHTS 0 #endif +#ifndef FG_TILE +#define FG_TILE 0 +#endif #if FG_WEIGHTS #include "fg_weights.hlsli" #endif @@ -160,6 +169,18 @@ WG_KERNEL(fg_lite_blend) } wg_barrier_lds(); if (!live) return; +#elif FG_TILE + // A17: 32 x 8 pixel tiles (tiles_x = ceil(wo / 32), the launch is tiles_x * ceil(ho / 8) workgroups, one wave per tile + // row) instead of 256-pixel scanlines: no per-pixel division, and the vertical bilinear taps of a tile share cache + // lines. A lane past the frame computes the nearest valid pixel (the wave's quad exchange needs every lane) and does + // not store. Every pixel is independent, so the bits are the scanline kernel's. + const uint lane = wg_lane_id(), tile = wg_block_id(), tiles_x = (wo + 31u) >> 5u; + const uint tile_y = tile / tiles_x; + const uint xr = ((tile - tile_y * tiles_x) << 5u) + (lane & 31u), yr = (tile_y << 3u) + (lane >> 5u); + const bool live = xr < wo && yr < ho; + const uint x = min(xr, wo - 1u), y = min(yr, ho - 1u); + const uint idx = y * wo + x; + const float u = fg_centre(x, wo), v = fg_centre(y, ho); #else const uint idx = wg_block_id() * 256u + wg_lane_id(); if (idx >= wo * ho) return; @@ -205,8 +226,23 @@ WG_KERNEL(fg_lite_blend) } #if FG_PACK const uint2 h = uint2(fg_pack_h2(o.x, o.y), fg_pack_h2(o.z, 1.0f)); +#if FG_TILE + // adjacent lanes are a horizontal pair (the tile origin is a multiple of 32): one 8-byte store per pair + const uint word = fgx_pack_pixel(h, ox); + const uint pair = QuadReadAcrossX(word); + if (live && (xr & 1u) == 0u) + { + const uint at = (oy + y) * ostride + x * 4u; + if (x + 1u < wo) wg_st64(outp, at, uint2(word, pair)); + else wg_st32(outp, at, word); + } +#else wg_st32(outp, (oy + y) * ostride + x * 4u, fgx_pack_pixel(h, ox)); +#endif #else +#if FG_TILE + if (live) +#endif fg_st_h4(outp, (oy + y) * ostride + ox + x, float4(o, 1.0f)); #endif } diff --git a/clean/dx12/kernels/fg_lite_g.hlsl b/clean/dx12/kernels/fg_lite_g.hlsl index 49ac4694..49b9c48e 100644 --- a/clean/dx12/kernels/fg_lite_g.hlsl +++ b/clean/dx12/kernels/fg_lite_g.hlsl @@ -20,6 +20,7 @@ // @wg-kernel fg_lite_interm_tiled co=- entry=fg_lite_interm block=256 wave=32 args=u,p,p,p,u,u,u,u,u,u,u defines=FG_K=1,FG_TILE=1 // @wg-kernel fg_lite_interm_both co=- block=256 wave=32 args=p,p,p,p,p,p,u,u,u,u,u,u,u defines=FG_K=3 // @wg-kernel fg_lite_weights co=- block=256 wave=32 args=p,p,p,p,p,u,u,u,u defines=FG_K=2 +// @wg-kernel fg_lite_weights_b co=- entry=fg_lite_weights block=256 wave=32 args=p,p,p,p,p,u,u,u,u defines=FG_K=2,FG_BIL128=1 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" diff --git a/clean/dx12/kernels/fg_lite_util.hlsl b/clean/dx12/kernels/fg_lite_util.hlsl index 89fe93dd..b5ee9bb2 100644 --- a/clean/dx12/kernels/fg_lite_util.hlsl +++ b/clean/dx12/kernels/fg_lite_util.hlsl @@ -7,15 +7,43 @@ // fg_lite_copy4: dst[(dy0 + y) * dstride + dx0 + x] := src[(sy0 + y) * sstride + sx0 + x], 8-byte texels, x < w, y < h. // // @wg-kernel fg_lite_fill16 co=- block=256 wave=32 args=p,u,u,u,u,u,u defines=FG_K=1 +// @wg-kernel fg_lite_fill16_p2 co=- entry=fg_lite_fill16 block=256 wave=32 args=p,u,u,u,u,u,u defines=FG_K=1,FG_FILL_P2=1 // @wg-kernel fg_lite_copy4 co=- block=256 wave=32 args=p,u,u,u,p,u,u,u,u,u defines=FG_K=2 #include "wg_platform.hlsli" #include "fg_lite_common.hlsli" +#ifndef FG_FILL_P2 +#define FG_FILL_P2 0 +#endif #if FG_K == 1 WG_ARGS_BEGIN uint dst, n16, p0, p1, p2, p3, period; WG_ARGS_END +#if FG_FILL_P2 +// A15 (fg_lite_fill16_p2, the executor only launches it with period 1, 2 or 4): `first` is a multiple of 8 and the period +// divides 8, so unit j of every lane's eight is p[j & (period - 1)]: the 16-byte word is built once from the arguments and +// the tail unit k = i & (period - 1); no integer division anywhere. The same bytes as fg_lite_fill16. +uint fg_unit_p2(uint i) { uint k = i & (period - 1u); return k == 0u ? p0 : (k == 1u ? p1 : (k == 2u ? p2 : p3)); } + +WG_KERNEL(fg_lite_fill16) +{ + FG_SETUP(); + const uint first = (wg_block_id() * 256u + wg_lane_id()) * 8u; + if (first >= n16) return; + if (first + 8u <= n16) + { + const uint u0 = p0 & 0xffffu; + const uint u1 = (period == 1u ? p0 : p1) & 0xffffu; + const uint u2 = (period == 4u ? p2 : p0) & 0xffffu; + const uint u3 = (period == 1u ? p0 : (period == 4u ? p3 : p1)) & 0xffffu; + const uint lo = u0 | (u1 << 16), hi = u2 | (u3 << 16); + wg_st128(dst, first * 2u, uint4(lo, hi, lo, hi)); + return; + } + [loop] for (uint i = first; i < n16; ++i) wg_st16(dst, i * 2u, fg_unit_p2(i) & 0xffffu); +} +#else uint fg_unit(uint i) { uint k = i % period; return k == 0u ? p0 : (k == 1u ? p1 : (k == 2u ? p2 : p3)); } WG_KERNEL(fg_lite_fill16) @@ -36,6 +64,7 @@ WG_KERNEL(fg_lite_fill16) [loop] for (uint i = first; i < n16; ++i) wg_st16(dst, i * 2u, fg_unit(i) & 0xffffu); } #endif +#endif #if FG_K == 2 WG_ARGS_BEGIN diff --git a/clean/dx12/kernels/fg_net2_mconv.hlsl b/clean/dx12/kernels/fg_net2_mconv.hlsl index 34565d9f..f7ab0434 100644 --- a/clean/dx12/kernels/fg_net2_mconv.hlsl +++ b/clean/dx12/kernels/fg_net2_mconv.hlsl @@ -77,6 +77,20 @@ // @wg-kernel fg_net2_mconv_h3b1u co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1,FG_UP=1,FG_FUSED_HEADS=1 // @wg-kernel fg_net2_mconv_h3b1u_s3 co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1,FG_UP=1,FG_FUSED_HEADS=1,FG_STAGE_ALL=1 // @wg-kernel fg_net2_mconv_h3b2u co=fg_net2_mma.co entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=2,FG_UP=1,FG_FUSED_HEADS=1 +// @wg-kernel fg_net2_mconv_m1b1_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m1b2_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=2,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m2b1_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,FG_NB=1,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m2b2_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,FG_NB=2,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m2b4_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,FG_NB=4,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m1b4s_z co=- entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=4,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m1b2s_z co=- entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=2,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m1b1u_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1,FG_UP=1,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m1b2u_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=2,FG_UP=1,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m2b4u_z co=- entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=2,FG_NB=4,FG_UP=1,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m3b2u_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=3,FG_NB=2,FG_UP=1,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_m3b4u_z co=- entry=fg_net2_mconv block=128 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=3,FG_NB=4,FG_UP=1,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_h3b1u_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1,FG_UP=1,FG_FUSED_HEADS=1,FG_ZB=1,WG_Z_GRID=1 +// @wg-kernel fg_net2_mconv_h3b1u_s3_z co=- entry=fg_net2_mconv block=256 wave=32 args=p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u defines=FG_MT=1,FG_NB=1,FG_UP=1,FG_FUSED_HEADS=1,FG_STAGE_ALL=1,FG_ZB=1,WG_Z_GRID=1 #include "wg_platform.hlsli" #include "fg_net2.hlsli" @@ -114,6 +128,34 @@ static uint fg_wf_cur, fg_b_cur; // the layer's weights and bias #define FG_B fg_b_cur #define FG_WF_SET(w, bias) fg_wf_cur = (w); fg_b_cur = (bias); #else +#ifndef FG_ZB +#define FG_ZB 0 +#endif +#if FG_ZB +// A18 (the _z kernels, WG_Z_GRID = 1): N frames' launches of one layer in one (groups, 1, N) dispatch. The N frames' scratch +// banks are bank_stride bytes apart, so slice z addresses frame z's activations by adding z * zstride to each pointer whose +// bit is set in zmask (bit i = the i-th pointer: x, wf, b, y, skip, y1, y2, skip1, skip2); the weights wf, b are the same +// in every frame (bits clear). Everything after the pointers is the single-frame kernel, so each slice computes the same +// bits as its own launch. +#if FG_UPWARP_STAGE +#error "FG_ZB is for the launches without the upwarp staging" +#endif +WG_ARGS_BEGIN + uint a_x, a_wf, a_b, a_y, a_skip, a_y1, a_y2, a_skip1, a_skip2; // pointers (arena byte offsets), frame 0's + int in_cs, in_co, cin, H, W, co_lo, co_n, out_cs, out_co, pool, leaky, clamp_from, res; + uint res_mul; + int skip_cs, skip_co, tiles_x, tiles_y, heads; + uint zstride, zmask; +WG_ARGS_END +static uint x, wf, b, y, skip, y1, y2, skip1, skip2; // this slice's pointers +#define FG_ZB_SETUP() \ + { const uint zo_ = wg_gid_z() * zstride; \ + x = a_x + ((zmask & 1u) != 0u ? zo_ : 0u); wf = a_wf + ((zmask & 2u) != 0u ? zo_ : 0u); \ + b = a_b + ((zmask & 4u) != 0u ? zo_ : 0u); y = a_y + ((zmask & 8u) != 0u ? zo_ : 0u); \ + skip = a_skip + ((zmask & 16u) != 0u ? zo_ : 0u); y1 = a_y1 + ((zmask & 32u) != 0u ? zo_ : 0u); \ + y2 = a_y2 + ((zmask & 64u) != 0u ? zo_ : 0u); skip1 = a_skip1 + ((zmask & 128u) != 0u ? zo_ : 0u); \ + skip2 = a_skip2 + ((zmask & 256u) != 0u ? zo_ : 0u); } +#else WG_ARGS_BEGIN uint x, wf, b, y, skip, y1, y2, skip1, skip2; // pointers (arena byte offsets) int in_cs, in_co, cin, H, W, co_lo, co_n, out_cs, out_co, pool, leaky, clamp_from, res; @@ -123,6 +165,8 @@ WG_ARGS_BEGIN uint ib, ic, ia, a4, a1, a3, u4, u1, u3, fbits; #endif WG_ARGS_END +#define FG_ZB_SETUP() +#endif #define FG_WF wf #define FG_B b #endif @@ -673,6 +717,7 @@ WG_KERNEL(fg_net2_mconv) WG_KERNEL(fg_net2_mconv) { WG_SETUP(); + FG_ZB_SETUP(); const uint lane = wg_lane_id() & 31u; const int blk = (int)wg_block_id(); const int tx = blk % tiles_x, rest = blk / tiles_x; diff --git a/clean/dx12/kernels/fg_out_pull.hlsl b/clean/dx12/kernels/fg_out_pull.hlsl index 14c2b60a..ee3770b0 100644 --- a/clean/dx12/kernels/fg_out_pull.hlsl +++ b/clean/dx12/kernels/fg_out_pull.hlsl @@ -19,6 +19,12 @@ // // @wg-kernel fg_out_pull co=fg_full.co block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u // @wg-kernel fg_out_pull_pack co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_PACK=1 +// @wg-kernel fg_out_pull_b co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_BIL128=1 +// @wg-kernel fg_out_pull_pack_b co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_PACK=1,FG_BIL128=1 +// @wg-kernel fg_out_pull_q co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_POW2=1 +// @wg-kernel fg_out_pull_pack_q co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_PACK=1,FGP_POW2=1 +// @wg-kernel fg_out_pull_bq co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_POW2=1,FG_BIL128=1 +// @wg-kernel fg_out_pull_pack_bq co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_PACK=1,FGP_POW2=1,FG_BIL128=1 // @wg-kernel fg_out_pull_mid co=fg_full.co block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u defines=FGP_MID=1 // @wg-kernel fg_out_pull_x3 co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_X3=1 // @wg-kernel fg_out_pull_pack_x3 co=- entry=fg_out_pull block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FGP_PACK=1,FGP_X3=1 @@ -35,6 +41,9 @@ #ifndef FGP_X3 #define FGP_X3 0 #endif +#ifndef FGP_POW2 +#define FGP_POW2 0 +#endif groupshared float4 fgp_wave_sums[8]; @@ -48,8 +57,17 @@ float4 fgp_level(float4 acc, uint m) // The first tile receives saturated finite RGB and weights of zero or one. // With no contributing pixels RGB is zero, so its denominator can be one. const float den = max(acc.w, 1.0f); - const float3 rgb = fgf_div_normal3(acc.xyz, den, fgf_div_reciprocal(den)); const float scale = asfloat((127u - 2u * m) << 23u); +#if FGP_POW2 + // A17: a tile with no hole has acc.w = 4^m exactly, a power of two: den = acc.w, its reciprocal is exactly scale and + // every refinement step of the division is exact (the residual is 0), so acc.xyz / den = acc.xyz * scale bit for + // bit (zeros keep their sign through the select below, as before). Only tiles with a hole divide. + float3 rgb = acc.xyz * scale; + [branch] if (acc.w != (float)(1u << (2u * m))) + rgb = fgf_div_normal3(acc.xyz, den, fgf_div_reciprocal(den)); +#else + const float3 rgb = fgf_div_normal3(acc.xyz, den, fgf_div_reciprocal(den)); +#endif return float4(select(acc.xyz == 0.0f, acc.xyz, rgb), acc.w * scale); #endif } diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index b070cc36..c8c1fd3e 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -54,14 +54,25 @@ enum Kernel : uint32_t { kPairC64, kPairC32, // A7: net2 residual pairs kOutTail, kFineL1, kFinePackL1, // A14: output pyramid tail kMConv2MidCells, // A6: net1_01 builds its cells + // Wave 2 (the fuse2 bits 64 .. 1024): exact variants of kernels above, each used only when its DXIL is present + kFill16P2, // A15: fill without divisions + kLiteBlendB, kLiteBlendPackB, kLiteBlendT, kLiteBlendPackT, kLiteBlendBT, kLiteBlendPackBT, kWeightsB, // A16 (B) / A17 (T) + kFullBlendB, kFullBlendMergeB, // A16 + kOutPullB, kOutPullPackB, kOutPullQ, kOutPullPackQ, kOutPullBQ, kOutPullPackBQ, // A16 (B) / A17 (Q) + kN2zm1b1, kN2zm1b2, kN2zm2b1, kN2zm2b2, kN2zm2b4, kN2zm1b4s, kN2zm1b2s, kN2zm1b1u, kN2zm1b2u, kN2zm2b4u, + kN2zm3b2u, kN2zm3b4u, kN2zh3b1u, kN2zh3b1uS3, // A18: z-sliced net2 convolutions kKernelCount, }; // the Wave 1B levers (bits of FgD3d12ExecutorDesc::fuse2 when it is a mask) enum Fuse2Bit : uint32_t { - kF2Cells = 1, kF2Pair = 2, kF2Upwarp = 4, kF2Weights = 8, kF2Tail = 16, kF2X3 = 32, kF2All = 63, + kF2Cells = 1, kF2Pair = 2, kF2Upwarp = 4, kF2Weights = 8, kF2Tail = 16, kF2X3 = 32, + // Wave 2, all bit-exact: A15 fill16 without divisions, A16 bilinear taps as 16 / 8-byte row loads, A17 the light blend on + // 32 x 8 tiles with 8-byte pair stores and the output pull skipping its division on hole-free tiles, A18 net2's + // convolutions of every generated index of a batch in one (groups, 1, N) launch + kF2Fill = 64, kF2Bil = 128, kF2Tile = 256, kF2Pow2 = 512, kF2NetZ = 1024, kF2All = 2047, // the levers that won in paired ABBA runs at 1440p (A6 net1 cells, A14 pyramid tail); the others are exact but cost GPU time // (A13 weights in the blends, A7 net2 pairs, A9 upwarp in L14, A12 RGB X0 / X1) and stay opt-in (a mask, e.g. 63) - kF2Default = kF2Cells | kF2Tail, + kF2Default = kF2Cells | kF2Tail | kF2Fill | kF2Bil | kF2Tile | kF2Pow2 | kF2NetZ, // 17 is the Wave 1B default }; constexpr uint32_t kFirstTurbo = kFineMask; // a pipeline of these that the device refuses is dropped, not fatal constexpr uint32_t kFirstFull = kFullBlend; @@ -85,6 +96,8 @@ bool KernelNeeded(uint32_t k, bool full, FgNet2Path path) { if (k == kOutPullPack || k == kOutPushFinePack || k == kFullBlendMerge) return full; // Full path only if ((k >= kFullBlendW && k <= kOutPullPackX3) || k == kOutTail || k == kFineL1 || k == kFinePackL1) return full; if (k == kN2m1b2Uw || k == kN2m1b2sUw || k == kPairC64 || k == kPairC32) return full && path == FgNet2Path::Fast; + if (k >= kN2zm1b1 && k <= kN2zh3b1uS3) return full && path == FgNet2Path::Fast; + if (k >= kFullBlendB && k <= kOutPullPackBQ) return full; // the Full path's A16 / A17 variants if (k < kFirstFull || k >= kFirstOptional) return true; if (!full) return false; if (k == kNet2Conv || k == kNet2Up2 || k == kNet2Warp) return path == FgNet2Path::Exact; @@ -141,6 +154,15 @@ const char* const kKernelNames[kKernelCount] = { "fg_net2_mpair_res_c64", "fg_net2_mpair_res_c32", "fg_out_tail", "fg_out_push_fine_l1", "fg_out_push_fine_pack_l1", "fg_mconv2_mid_cells", + "fg_lite_fill16_p2", + "fg_lite_blend_b", "fg_lite_blend_pack_b", "fg_lite_blend_t", "fg_lite_blend_pack_t", "fg_lite_blend_bt", + "fg_lite_blend_pack_bt", "fg_lite_weights_b", + "fg_full_blend_b", "fg_full_blend_merge_b", + "fg_out_pull_b", "fg_out_pull_pack_b", "fg_out_pull_q", "fg_out_pull_pack_q", "fg_out_pull_bq", "fg_out_pull_pack_bq", + "fg_net2_mconv_m1b1_z", "fg_net2_mconv_m1b2_z", "fg_net2_mconv_m2b1_z", "fg_net2_mconv_m2b2_z", + "fg_net2_mconv_m2b4_z", "fg_net2_mconv_m1b4s_z", "fg_net2_mconv_m1b2s_z", "fg_net2_mconv_m1b1u_z", + "fg_net2_mconv_m1b2u_z", "fg_net2_mconv_m2b4u_z", "fg_net2_mconv_m3b2u_z", "fg_net2_mconv_m3b4u_z", + "fg_net2_mconv_h3b1u_z", "fg_net2_mconv_h3b1u_s3_z", }; static_assert(sizeof(kKernelNames) / sizeof(*kKernelNames) == kKernelCount, "one name per kernel"); @@ -695,6 +717,12 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { bool x3_on = false; // A12: X0 / X1 hold r, g, b only bool tail_on = false; // A14: the pyramid's coarse pushes in one workgroup bool l1_on = false; // A14: level 1 is pushed inside the fine pass + bool fill_p2_on = false; // A15: fg_lite_fill16_p2 for the periods 1, 2, 4 + bool bil_on = false; // A16: the bilinear taps as row loads (the _b kernels, where present) + bool tile_on = false; // A17: the light blend on 32 x 8 tiles (the _t kernels) + bool pow2_on = false; // A17: the output pull skips its division on hole-free tiles (the _q kernels) + bool netz_on = false; // A18: net2's per-index launches of a batch as one (groups, 1, N) launch + bool want_netz_env = true; // WG_FG_NET2_BATCH=0 turns A18 off whatever the mask says bool hole_fused = false; // the fine pass already ran the hole mask of this frame (the HoleMask op is then empty) // the fused / retiled kernels (kFineMask, kInpaintTiled, kInterm2) are used when present bool Fused(uint32_t k) const { return want_fuse && pso[k] != nullptr; } @@ -997,11 +1025,28 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { pso[kFullBlendMergeX3] && (!full_weights_on || (pso[kFullBlendWX3] && pso[kFullBlendMergeWX3])); tail_on = full && Fused2(kF2Tail, kOutTail); l1_on = full && Fused2(kF2Tail, kFineL1) && pso[kFinePackL1]; + fill_p2_on = Fused2(kF2Fill, kFill16P2); + bil_on = (want_fuse2 & kF2Bil) != 0; + tile_on = (want_fuse2 & kF2Tile) != 0; + pow2_on = full && (want_fuse2 & kF2Pow2) != 0; + netz_on = full && fast() && want_netz_env && (want_fuse2 & kF2NetZ) != 0; // needs batch_on too (checked at emit) + } + bool Has(uint32_t k) const { return k < kKernelCount && pso[k] != nullptr; } + // the variant of `base` for the A16 (b) / A17 (t) levers that are on and whose kernels exist + uint32_t PickBT(uint32_t base, uint32_t kb, uint32_t kt, uint32_t kbt, bool b, bool t) const { + if (b && t && Has(kbt)) return kbt; + if (t && Has(kt)) return kt; + if (b && Has(kb)) return kb; + return base; } // The Full blend kernel for (merged input, W built in, X0 / X1 as RGB) uint32_t FullBlendKernel(bool merged) const { const bool w = full_weights_on, x = x3_on; - if (merged) return w ? (x ? kFullBlendMergeWX3 : kFullBlendMergeW) : (x ? kFullBlendMergeX3 : kFullBlendMerge); + if (merged) { + if (!w && !x && bil_on && Has(kFullBlendMergeB)) return kFullBlendMergeB; // A16 + return w ? (x ? kFullBlendMergeWX3 : kFullBlendMergeW) : (x ? kFullBlendMergeX3 : kFullBlendMerge); + } + if (!w && !x && bil_on && Has(kFullBlendB)) return kFullBlendB; return w ? (x ? kFullBlendWX3 : kFullBlendW) : (x ? kFullBlendX3 : kFullBlend); } @@ -1553,10 +1598,12 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } EmitDispatch(r, k, groups, args, n, barrier); } - void EmitDispatch(Rec& r, uint32_t k, uint32_t groups, const uint32_t* args, uint32_t n, bool barrier) { + // depth > 1 (A18): a (groups, 1, depth) launch of a WG_Z_GRID kernel; groups then fits one dispatch + void EmitDispatch(Rec& r, uint32_t k, uint32_t groups, const uint32_t* args, uint32_t n, bool barrier, + uint32_t depth = 1) { ArenaTo(r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); if (barrier) Barrier(r); - if (desc.kernel_profile) ProfMark(r, k, groups); + if (desc.kernel_profile) ProfMark(r, k, groups * depth); r.cl->SetPipelineState(pso[k].Get()); uint32_t c[kRootConstants] = {}; c[1] = groups; @@ -1564,7 +1611,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { for (uint32_t base = 0; base < groups; base += 65535) { c[0] = base; r.cl->SetComputeRoot32BitConstants(2, 2 + n, c, 0); - r.cl->Dispatch(std::min(groups - base, 65535), 1, 1); + r.cl->Dispatch(std::min(groups - base, 65535), 1, depth); } r.dirty = true; ++counters.dispatches; @@ -1763,7 +1810,9 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { void Fill16(Rec& r, uint32_t off, uint64_t bytes, const uint32_t* p, uint32_t period, bool barrier = true) { const uint32_t n16 = static_cast(bytes / 2); - D(r, kFill16, groups_for(n16, 8), {off, n16, p[0], p[1], p[2], p[3], period}, barrier); + // A15: every fill the runtime records has period 1, 2 or 4, which the division-free kernel needs + const bool p2 = fill_p2_on && (period == 1 || period == 2 || period == 4); + D(r, p2 ? kFill16P2 : kFill16, groups_for(n16, 8), {off, n16, p[0], p[1], p[2], p[3], period}, barrier); } void RegArgs(const InputTex& t, bool present, uint32_t* out10) const { @@ -2033,7 +2082,7 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { } case FgOp::Weights: if (op.lite_blend ? lite_weights_on : full_weights_on) return true; // the blend computes W in LDS - D(r, kWeights, groups_for(nsc), + D(r, bil_on && Has(kWeightsB) ? kWeightsB : kWeights, groups_for(nsc), {R(kRoleMA), R(kRoleMB), R(kRoleNA), R(kRoleNB), R(kRoleW), g.w1, g.h1, g.wd, g.hd}); return true; case FgOp::Prefill: @@ -2066,7 +2115,11 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { Dispatch(r, packed ? kLiteBlendPackW : kLiteBlendW, cdiv(g.wo, 32) * cdiv(g.ho, 8), w, n); return true; } - Dispatch(r, packed ? kLiteBlendPack : kLiteBlend, groups_for(static_cast(g.wo) * g.ho), a, n); + const uint32_t lk = packed ? PickBT(kLiteBlendPack, kLiteBlendPackB, kLiteBlendPackT, kLiteBlendPackBT, bil_on, tile_on) + : PickBT(kLiteBlend, kLiteBlendB, kLiteBlendT, kLiteBlendBT, bil_on, tile_on); + const bool tiled = lk == kLiteBlendT || lk == kLiteBlendPackT || lk == kLiteBlendBT || lk == kLiteBlendPackBT; + // A17: the tiled kernels take 32 x 8 pixel tiles (tiles_x * ceil(ho / 8) workgroups) + Dispatch(r, lk, tiled ? cdiv(g.wo, 32) * cdiv(g.ho, 8) : groups_for(static_cast(g.wo) * g.ho), a, n); return true; } case FgOp::FullBlend: { @@ -2358,7 +2411,10 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { // fuse_pack: the pull and push-fine kernels write the slot's packed rows (pack_off, pack_pitch bytes, format // code in the out_x argument) instead of the float16 image const bool packed = fuse_pack != 0; - const uint32_t pull = packed ? (x3_on ? kOutPullPackX3 : kOutPullPack) : (x3_on ? kOutPullX3 : kOutPull); + uint32_t pull = packed ? (x3_on ? kOutPullPackX3 : kOutPullPack) : (x3_on ? kOutPullX3 : kOutPull); + if (!x3_on) // A16 (b) / A17 (q) + pull = packed ? PickBT(kOutPullPack, kOutPullPackB, kOutPullPackQ, kOutPullPackBQ, bil_on, pow2_on) + : PickBT(kOutPull, kOutPullB, kOutPullQ, kOutPullBQ, bil_on, pow2_on); D(r, pull, tx * ty, {x0, x1, xw, nb_out.off, sig, packed ? pack_off : out_off, fine, lv[1], lv[2], lv[3], lv[4], g.wo, g.ho, g.W2, g.H2, g.k, tx, packed ? pack_pitch : out_stride, packed ? fuse_pack : 0u, 0u, fb(rk)}); @@ -2722,7 +2778,73 @@ struct FgD3d12Executor::Impl final : public IFgComputeRecorder { for (const Deferred& d : lists[f]) keys[f].push_back({d.kernel, d.barrier}); std::vector order; FgInterleaveLaunches(keys, &order); // the rule (fg_exec_plan.h) is tested on its own - for (const FgLaunchSlot& s : order) EmitDeferred(r, lists[s.frame][s.index], s.barrier, s.mark_stage); + const size_t nf = lists.size(); + for (size_t i = 0; i < order.size();) { + if (netz_on && batch_on && nf >= 2 && EmitZRun(r, lists, order, i, nf)) { + i += nf; + continue; + } + const FgLaunchSlot& s = order[i++]; + EmitDeferred(r, lists[s.frame][s.index], s.barrier, s.mark_stage); + } + } + + // A18: the z-sliced twin of a net2 convolution kernel (kKernelCount: none) + static uint32_t ZKernelOf(uint32_t k) { + switch (k) { + case kN2m1b1: return kN2zm1b1; + case kN2m1b2: return kN2zm1b2; + case kN2m2b1: return kN2zm2b1; + case kN2m2b2: return kN2zm2b2; + case kN2m2b4: return kN2zm2b4; + case kN2m1b4s: return kN2zm1b4s; + case kN2m1b2s: return kN2zm1b2s; + case kN2m1b1u: return kN2zm1b1u; + case kN2m1b2u: return kN2zm1b2u; + case kN2m2b4u: return kN2zm2b4u; + case kN2m3b2u: return kN2zm3b2u; + case kN2m3b4u: return kN2zm3b4u; + case kN2h3b1u: return kN2zh3b1u; + case kN2h3b1uS3: return kN2zh3b1uS3; + default: return kKernelCount; + } + } + static constexpr uint32_t kMconvArgs = 28, kMconvPointers = 9; // fg_net2_mconv: 9 pointers, 19 scalars + + // The launches order[i .. i + nf) are launch `index` of every frame back to back (the interleaved plan). When they are + // one net2 convolution kernel with the same grid and scalars, and each pointer is either the same in every frame + // (weights, null) or frame f's bank = frame 0's + f * sc_stride (the scratch banks are sc_stride bytes apart), they are + // recorded as one (groups, 1, nf) launch of the z-sliced kernel: slice f adds f * sc_stride to the pointers in zmask. + // Same launches, same data, one dispatch (and one set of weight reads) instead of nf. False: nothing recorded. + bool EmitZRun(Rec& r, const std::vector>& lists, const std::vector& order, + size_t i, size_t nf) { + if (i + nf > order.size() || order[i].frame != 0 || nf > 65535) return false; + const uint32_t index = order[i].index; + const Deferred& d0 = lists[0][index]; + const uint32_t zk = ZKernelOf(d0.kernel); + if (!Has(zk) || d0.n != kMconvArgs || d0.groups == 0 || d0.groups > 65535) return false; + for (size_t t = 1; t < nf; ++t) { + const FgLaunchSlot& s = order[i + t]; + if (s.frame != t || s.index != index || s.barrier) return false; + } + std::vector args(nf); + for (size_t t = 0; t < nf; ++t) { + const Deferred& d = lists[t][index]; + if (d.kernel != d0.kernel || d.groups != d0.groups || d.n != d0.n) return false; + args[t] = d.args; + } + uint32_t mask = 0; + if (!FgPlanZBatch(args.data(), static_cast(nf), kMconvArgs, kMconvPointers, sc_stride, &mask)) + return false; + uint32_t a[kMaxArgs] = {}; + std::memcpy(a, d0.args, 4ull * d0.n); + a[d0.n] = static_cast(sc_stride); + a[d0.n + 1] = mask; + if (order[i].mark_stage) TimeStage(r, d0.stage); + EmitDispatch(r, zk, d0.groups, a, d0.n + 2, order[i].barrier, static_cast(nf)); + ++counters.net2_z_launches; + counters.net2_z_saved += nf - 1; + return true; } static bool SameBits(float a, float b) { return FgExecFloatBits(a) == FgExecFloatBits(b); } @@ -2799,6 +2921,7 @@ FgD3d12Executor::FgD3d12Executor(const FgD3d12ExecutorDesc& desc) : impl_(new Im impl_->want_hoist = lever(desc.hoist, "WG_FG_HOIST"); impl_->want_dualq = lever(desc.dualq, "WG_FG_DUALQ"); impl_->want_fuse = lever(desc.fuse, "WG_FG_FUSE"); + impl_->want_netz_env = lever(-1, "WG_FG_NET2_BATCH"); // A18 (also needs the fuse2 bit 1024 and the batch lever) // Wave 1B: 0 off, 1 (or unset) the default levers (net1 cells + pyramid tail), any other value a mask of the levers (1 net1 // cells, 2 net2 pairs, 4 upwarp in L14, 8 W in the blends, 16 pyramid tail, 32 X0 / X1 as RGB; 63 = every lever) { @@ -3283,7 +3406,8 @@ uint32_t FgD3d12Executor::Fuse2Active() const { const Impl& m = *impl_; return (m.cells_on ? kF2Cells : 0u) | (m.pair64_on || m.pair32_on ? kF2Pair : 0u) | (m.uw_on ? kF2Upwarp : 0u) | (m.lite_weights_on || m.full_weights_on ? kF2Weights : 0u) | (m.tail_on || m.l1_on ? kF2Tail : 0u) | - (m.x3_on ? kF2X3 : 0u); + (m.x3_on ? kF2X3 : 0u) | (m.fill_p2_on ? kF2Fill : 0u) | (m.bil_on ? kF2Bil : 0u) | (m.tile_on ? kF2Tile : 0u) | + (m.pow2_on ? kF2Pow2 : 0u) | (m.netz_on && m.batch_on ? kF2NetZ : 0u); } bool FgD3d12Executor::BatchActive() const { return impl_->batch_on; } bool FgD3d12Executor::HoistActive() const { return impl_->hoist_on; } diff --git a/clean/fg/runtime/fg_d3d12_executor.h b/clean/fg/runtime/fg_d3d12_executor.h index 5b44ffa5..99b8ce86 100644 --- a/clean/fg/runtime/fg_d3d12_executor.h +++ b/clean/fg/runtime/fg_d3d12_executor.h @@ -186,6 +186,12 @@ struct FgD3d12ExecutorDesc { // (fg_lite_blend_w / _pack_w, fg_full_blend_*_w), 16 the output pyramid's coarse pushes in one workgroup // (fg_out_tail) and level 1 pushed in the fine pass (fg_out_push_fine_l1), 32 X0 / X1 stored as RGB // (fg_full_blend_*_x3, fg_out_pull_x3). Independent of fuse. + // Wave 2 (all bit-exact, in the default; WG_FG_FUSE2=17 is the Wave 1B default without them): 64 fg_lite_fill16_p2 (A15: + // the fill without integer divisions), 128 the bilinear taps of the blends, the light weights and the output pull as + // 16 / 8-byte row loads (A16: the _b kernels), 256 the light blend on 32 x 8 tiles with 8-byte pair stores (A17: the _t + // kernels), 512 the output pull's division skipped on hole-free tiles (A17: the _q kernels), 1024 net2's convolutions of + // the indices of a batch as one (groups, 1, N) launch (A18: the _z kernels; needs batch; WG_FG_NET2_BATCH=0 turns it + // off whatever the mask says). The default mask is 2001 = 17 + 64 + 128 + 256 + 512 + 1024; 2047 is every lever. int batch = -1, hoist = -1, dualq = -1, fuse = -1, fuse2 = -1; // Developer frame dumps (off while dump_dir is empty; the ASI sets it only in a developer build): of the game // frames that generate, every dump_every-th one (at most dump_max), the game frame's slot image (game_.ppm) and @@ -220,6 +226,7 @@ struct FgExecCounters { uint64_t lite_frames = 0, full_frames = 0; uint64_t game_colour_copies = 0; // real-only frames copied from the game's back buffer (no shared work) uint64_t net2_fast = 0, net2_exact = 0; // net2 recordings per path + uint64_t net2_z_launches = 0, net2_z_saved = 0; // A18: z-sliced net2 launches recorded, and the launches they replaced (nf - 1 each) }; enum class FgExecStage : uint32_t { diff --git a/clean/fg/runtime/fg_exec_plan.cpp b/clean/fg/runtime/fg_exec_plan.cpp index 64ed234c..0fdbe197 100644 --- a/clean/fg/runtime/fg_exec_plan.cpp +++ b/clean/fg/runtime/fg_exec_plan.cpp @@ -285,6 +285,25 @@ void FgInterleaveLaunches(const std::vector>& frames, s for (uint32_t f = 0; f < frames.size(); ++f) out->push_back({f, j, f == 0 && frames[0][j].barrier, f == 0}); } +bool FgPlanZBatch(const uint32_t* const* args, uint32_t frames, uint32_t n, uint32_t pointers, uint64_t stride, + uint32_t* mask) { + if (!args || !mask || frames < 2 || n == 0 || pointers > n || pointers > 32) return false; + uint32_t m = 0; + for (uint32_t a = 0; a < n; ++a) { + const uint32_t d1 = args[1][a] - args[0][a]; + const bool banked = d1 != 0; + if (banked && (a >= pointers || d1 != static_cast(stride))) return false; + for (uint32_t f = 1; f < frames; ++f) { + const uint32_t d = args[f][a] - args[0][a]; + if (d != (banked ? static_cast(f * stride) : 0u)) return false; + } + if (banked) m |= 1u << a; + } + if (m == 0) return false; + *mask = m; + return true; +} + const char* FgOpName(FgOp op) { switch (op) { case FgOp::Clear: return "clear"; diff --git a/clean/fg/runtime/fg_exec_plan.h b/clean/fg/runtime/fg_exec_plan.h index d9fffc07..a09c586a 100644 --- a/clean/fg/runtime/fg_exec_plan.h +++ b/clean/fg/runtime/fg_exec_plan.h @@ -199,6 +199,14 @@ struct FgLaunchSlot { // is recorded frame after frame with each launch's own barrier flag. void FgInterleaveLaunches(const std::vector>& frames, std::vector* out); +// A18: whether the same launch of `frames` frames (args[f] = frame f's n argument DWORDs) can be one (groups, 1, frames) +// launch of a z-sliced kernel, and the mask of the pointer arguments the slices must offset. Every argument is either the +// same in every frame (weights, null pointers, all scalars), or one of the first `pointers` arguments that frame f has at +// frame 0's value + f * stride (the scratch banks are `stride` bytes apart). Any other difference refuses; so does a launch +// with no banked pointer. mask bit i = argument i is banked. +bool FgPlanZBatch(const uint32_t* const* args, uint32_t frames, uint32_t n, uint32_t pointers, uint64_t stride, + uint32_t* mask); + // net2's 25 convolutions (clean/fg/layout.py NET2): stored input channels, used input channels, outputs. struct FgNet2Layer { uint32_t cin, cin_used, cout; diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index c583b4eb..a246076f 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -15,8 +15,10 @@ // [--batch 0|1] [--hoist 0|1] [--dualq 0|1] [--fuse 0|1] [--fuse2 0|1|MASK] Turbo v2 levers for paired A / B runs // (default: on, or the environment WG_FG_BATCH / _HOIST / _DUALQ / _FUSE / _FUSE2 = 0; --fuse2 takes // a mask of the Wave 1B levers: 1 net1 cells, 2 net2 pairs, 4 upwarp in L14, 8 blend weights, -// 16 pyramid tail, 32 X0 / X1 as RGB) -// [--turbo-fuse2 MASK] the Wave 1B mask the --only turbo legs run against all levers off (default 63: every lever) +// 16 pyramid tail, 32 X0 / X1 as RGB, and the Wave 2 levers 64 fill16 without divisions, 128 bilinear row +// loads, 256 light blend tiles, 512 output pull power-of-two skip, 1024 net2 z-batching; the default is +// 2001 = 17 + all of Wave 2, 17 alone is the Wave 1B default; WG_FG_NET2_BATCH=0 also stops 1024) +// [--turbo-fuse2 MASK] the Wave 1B mask the --only turbo legs run against all levers off (default 2047: every lever) // The report has the per-stage sums and the honest multi-queue numbers: the wall-clock GPU span and the busy // time per game frame over the timed window (overlap between queues is counted once there, twice in the sums). // --reference-dxil compare direct-SRV output bytes against the captured path built with these kernels @@ -167,6 +169,65 @@ void TestSigTable() { CHECK(std::memcmp(d.data(), want, 32) == 0); } +// Wave 2 A18: when the same launch of several frames can be one z-sliced launch (FgPlanZBatch), and which pointers the +// slices offset: the scratch banks are `stride` bytes apart, so a pointer argument is banked when frame f holds frame 0's +// value + f * stride; weights, null pointers and every scalar must be equal; anything else keeps the separate launches. +void TestZBatchPlan() { + g_case = "z-batch-plan"; + const uint64_t stride = 0x300000; + const uint32_t kPtr = 9, kN = 28; + const auto frame = [&](uint32_t f) { + std::vector a(kN); + for (uint32_t i = 0; i < kN; ++i) a[i] = 100 + i; // scalars (and shared pointers) the same in every frame + a[0] = 0x1000 + f * static_cast(stride); // x: banked + a[1] = 0x500; // wf: the weights, shared + a[3] = 0x2000 + f * static_cast(stride); // y: banked + a[4] = 0; // skip: null + return a; + }; + const auto plan = [&](const std::vector>& fr, uint32_t* mask) { + std::vector p; + for (const auto& a : fr) p.push_back(a.data()); + return FgPlanZBatch(p.data(), static_cast(p.size()), kN, kPtr, stride, mask); + }; + uint32_t mask = 0; + for (uint32_t n = 2; n <= 5; ++n) { + std::vector> fr; + for (uint32_t f = 0; f < n; ++f) fr.push_back(frame(f)); + mask = 0; + CHECK(plan(fr, &mask)); + CHECK(mask == (1u | 8u)); // x and y + } + std::vector> fr = {frame(0), frame(1), frame(2)}; + // a scalar that differs (e.g. a different time bit, a different grid): separate launches + auto bad = fr; + bad[2][15] += 1; + CHECK(!plan(bad, &mask)); + // a pointer that is not exactly one stride per frame + bad = fr; + bad[2][3] += 256; + CHECK(!plan(bad, &mask)); + // a pointer banked in frame 1 but not in frame 2, or the other way round + bad = fr; + bad[2][0] = bad[0][0]; + CHECK(!plan(bad, &mask)); + bad = fr; + bad[1][3] = bad[0][3]; + CHECK(!plan(bad, &mask)); + // a scalar (index >= the pointer count) that moves by a stride is not a bank + bad = fr; + for (uint32_t f = 0; f < 3; ++f) bad[f][12] = 7 + f * static_cast(stride); + CHECK(!plan(bad, &mask)); + // nothing banked at all, a single frame, bad arguments + CHECK(!plan({frame(0), frame(0)}, &mask)); + CHECK(!plan({frame(0)}, &mask)); + CHECK(!FgPlanZBatch(nullptr, 2, kN, kPtr, stride, &mask)); + // 32-bit wrap of an offset is the same arithmetic as the shader's + auto w = fr; + for (uint32_t f = 0; f < 3; ++f) w[f][0] = 0xFFF00000u + f * static_cast(stride); + CHECK(plan(w, &mask) && (mask & 1u)); +} + // Turbo v2: the order in which the launches of several indices sharing one command list are recorded, and the shape of an // index's ops that the hoisted work (the first three) and the batch rely on. void TestInterleave() { @@ -568,7 +629,7 @@ struct PipelineClock { } }; bool g_debug_layer = false; -int g_turbo_fuse2 = 63; // the Wave 1B mask TestTurboExact runs against all levers off (--turbo-fuse2 MASK) +int g_turbo_fuse2 = 2047; // the Wave 1B mask TestTurboExact runs against all levers off (--turbo-fuse2 MASK) int g_log_lines = 0; void PrintLog(void*, const char* line) { if (g_log_lines++ < 40) std::printf(" log: %s\n", line); @@ -1923,7 +1984,7 @@ void TestTurboExact(Gpu& gpu, const std::string& dxil, const FgExecWeights& weig ed.weights = &weights; ed.enable_full = c.preset != FgPreset::C; ed.batch = ed.hoist = ed.dualq = ed.fuse = 1; - ed.fuse2 = g_turbo_fuse2; // 63: every Wave 1B lever (default of the test), --turbo-fuse2 1: the executor's default levers + ed.fuse2 = g_turbo_fuse2; // 2047: every Wave 1B / Wave 2 lever (default of the test), --turbo-fuse2 1: the executor's default levers FgD3d12Executor test(ed); ed.batch = ed.hoist = ed.dualq = ed.fuse = wave1b_only ? 1 : 0; ed.fuse2 = 0; @@ -2125,6 +2186,9 @@ bool RunBench(Gpu& gpu, const std::string& dxil, const FgExecWeights& weights, F std::printf(" levers: batch %s, hoist %s, dualq %s, scratch banks %u, fuse2 mask 0x%x\n", exec.BatchActive() ? "on" : "off", exec.HoistActive() ? "on" : "off", exec.DualQueueActive() ? "on" : "off", exec.ScratchBanks(), exec.Fuse2Active()); + std::printf(" net2 z-batching: %llu z launches recorded, %llu launches saved (A18, fuse2 bit 1024, WG_FG_NET2_BATCH)\n", + static_cast(exec.Counters().net2_z_launches), + static_cast(exec.Counters().net2_z_saved)); double shared = 0.0, gen = 0.0; for (size_t i = 0; i < timing.ms.size(); ++i) { const double mean = timing.ms[i] / timed; @@ -2211,6 +2275,7 @@ int main(int argc, char** argv) { TestSigTable(); TestSchedule(); TestInterleave(); + TestZBatchPlan(); TestNet2FastPlan(); TestRefusals(weights); TestMotionFormats(); diff --git a/clean/fg/tests/test_fg_turbo_v2_wave2.py b/clean/fg/tests/test_fg_turbo_v2_wave2.py new file mode 100644 index 00000000..43c802df --- /dev/null +++ b/clean/fg/tests/test_fg_turbo_v2_wave2.py @@ -0,0 +1,410 @@ +# SPDX-License-Identifier: MIT +"""CPU proofs of the exactness arguments behind frame generation's Wave 2 kernels (the fuse2 bits 64 .. 1024): +A15 fg_lite_fill16_p2, A16 the bilinear row loads (FG_BIL128), A17 the light blend's 32 x 8 tiles with pair stores +(FG_TILE) and the output pull's division skip (FGP_POW2), A18 the z-sliced net2 convolutions (FG_ZB). Each class restates +what the Wave 1B kernel computes and what the Wave 2 kernel computes, as the HLSL does, and compares them on random and +edge inputs; the kernels themselves are checked on a GPU by test_fg_d3d12_e2e --gpu --only turbo (every lever on against +every lever off, default mask 2047).""" +import re +import unittest +from fractions import Fraction +from pathlib import Path + +import numpy as np + +F32 = np.float32 +DX12 = Path(__file__).resolve().parents[2] / "dx12" +RUNTIME = Path(__file__).resolve().parents[1] / "runtime" + + +def _text(rel): + return (DX12 / rel).read_text() + + +def _kernel_lines(text): + return [l for l in text.splitlines() if l.startswith("// @wg-kernel ")] + + +def _decl(line): + m = re.match(r"// @wg-kernel (\S+) (.*)$", line) + d = {"name": m.group(1)} + for tok in m.group(2).split(): + k, v = tok.split("=", 1) + d[k] = v + return d + + +def _function_text(text, signature): + start = text.index(signature) + open_ = text.index("{", start) + depth, i = 0, open_ + while True: + if text[i] == "{": + depth += 1 + elif text[i] == "}": + depth -= 1 + if depth == 0: + return text[start:i + 1] + i += 1 + + +# ---- A15: fg_lite_fill16_p2 ----------------------------------------------------------------------------------------------- +def fill_old(n16, period, p): + """fg_lite_fill16: unit i = p[i % period]; each lane writes 8 units (one 16-byte store when all 8 are inside).""" + out = np.zeros(n16, dtype=np.uint16) + for lane in range((n16 + 7) // 8): + first = lane * 8 + if first + 8 <= n16: + for j in range(8): + out[first + j] = p[(first + j) % period] & 0xFFFF + else: + for i in range(first, n16): + out[i] = p[i % period] & 0xFFFF + return out + + +def fill_new(n16, period, p): + """fg_lite_fill16_p2: the same word for every full lane, the tail by i & (period - 1).""" + u0 = p[0] & 0xFFFF + u1 = (p[0] if period == 1 else p[1]) & 0xFFFF + u2 = (p[2] if period == 4 else p[0]) & 0xFFFF + u3 = (p[0] if period == 1 else (p[3] if period == 4 else p[1])) & 0xFFFF + lo, hi = u0 | (u1 << 16), u2 | (u3 << 16) + word = (lo, hi, lo, hi) + out = np.zeros(n16, dtype=np.uint16) + for lane in range((n16 + 7) // 8): + first = lane * 8 + assert first % 8 == 0 + if first + 8 <= n16: + for j in range(8): + out[first + j] = (word[j // 2] >> (16 * (j % 2))) & 0xFFFF + else: + for i in range(first, n16): + out[i] = p[i & (period - 1)] & 0xFFFF + return out + + +class FillP2Test(unittest.TestCase): + def test_same_units_for_every_period_and_size(self): + rng = np.random.default_rng(15) + for period in (1, 2, 4): + for n16 in list(range(1, 40)) + [255, 256, 2047, 2048, 2049, 4097]: + for _ in range(3): + p = [int(v) for v in rng.integers(0, 1 << 32, size=4, dtype=np.uint64)] # the high bits are masked + np.testing.assert_array_equal(fill_old(n16, period, p), fill_new(n16, period, p), + err_msg="period %d n16 %d" % (period, n16)) + + def test_the_runtime_patterns(self): + # every Fill16 the executor records: clear {1.0}, clear {0,0,0,1}, a word as two units, fill64 (0xFFFF, 0x7FFF) + for period, p in ((1, [0x3C00, 0, 0, 0]), (4, [0, 0, 0, 0x3C00]), (2, [0xFFFF, 0x7FFF, 0, 0]), (2, [0, 0, 0, 0]), + (1, [0x5A5A] * 4)): + for n16 in (1, 2, 3, 7, 8, 9, 2457600, 1 << 20): + if n16 > 5000: + n16 = n16 % 5000 + 3 + np.testing.assert_array_equal(fill_old(n16, period, p), fill_new(n16, period, p)) + + def test_the_new_kernel_has_no_division(self): + text = _text("kernels/fg_lite_util.hlsl") + body = _function_text(text, "WG_KERNEL(fg_lite_fill16)") # the first one is the FG_FILL_P2 branch + self.assertIn("#if FG_FILL_P2", text) + p2 = text[text.index("#if FG_FILL_P2"):text.index("#else", text.index("#if FG_FILL_P2"))] + self.assertNotIn("%", p2.replace("// ", "//"), "no modulo in the FG_FILL_P2 kernel") + self.assertNotIn(" / ", re.sub(r"//.*", "", p2)) + self.assertIn("fg_lite_fill16_p2", text) + self.assertTrue(body) + + def test_first_is_a_multiple_of_eight(self): + # first = (block * 256 + lane) * 8: the units of a lane start at a multiple of 8, so unit j of the lane has + # i & (period - 1) == j & (period - 1) for every period that divides 8 + for first in range(0, 8 * 600, 8): + for period in (1, 2, 4): + for j in range(8): + self.assertEqual((first + j) % period, j & (period - 1)) + + +# ---- A16: bilinear row loads ---------------------------------------------------------------------------------------------- +def _tap_axis(t, n): + """fgf_tap / fg_read_linear: x0, x1 for the texel position t on an axis of n texels.""" + x0f = np.floor(F32(t)) + xi = int(np.clip(int(x0f), -1, n - 1)) + return max(xi, 0), min(xi + 1, n - 1) + + +class BilinearRowLoadTest(unittest.TestCase): + def test_second_texel_is_the_next_one_or_the_same(self): + rng = np.random.default_rng(16) + for n in (1, 2, 3, 5, 16, 17, 1920, 2560): + ts = list(rng.uniform(-3.0, n + 3.0, size=400)) + [-0.5, 0.0, n - 1.0, n - 0.5, n - 1e-4, float(n), -1e-9] + for t in ts: + x0, x1 = _tap_axis(t, n) + self.assertIn(x1 - x0, (0, 1), "n=%d t=%r" % (n, t)) + self.assertGreaterEqual(x0, 0) + self.assertLessEqual(x1, n - 1) + + def test_row_load_gives_the_four_load_texels(self): + # a buffer of 8-byte texels (W x H) with distinct values; the row load reads the texel at i00 and the one after it + # (zero past the end of the buffer: robust buffer access), the second texel is the loaded one unless x1 == x0 + rng = np.random.default_rng(17) + for W, H in ((1, 1), (1, 5), (2, 2), (5, 3), (17, 9), (64, 4)): + tex = rng.integers(1, 1 << 63, size=W * H, dtype=np.uint64) + + def row_load(i): + return int(tex[i]), (int(tex[i + 1]) if i + 1 < W * H else 0) + + for _ in range(300): + tx, ty = rng.uniform(-2.5, W + 2.5), rng.uniform(-2.5, H + 2.5) + x0, x1 = _tap_axis(tx, W) + y0, y1 = _tap_axis(ty, H) + i00, i10, i01, i11 = y0 * W + x0, y0 * W + x1, y1 * W + x0, y1 * W + x1 + a0, a1 = row_load(i00) + b0, b1 = row_load(i01) + got = (a0, a1 if i10 != i00 else a0, b0, b1 if i11 != i01 else b0) + want = (int(tex[i00]), int(tex[i10]), int(tex[i01]), int(tex[i11])) + self.assertEqual(got, want, "W=%d H=%d tap (%r, %r)" % (W, H, tx, ty)) + + def test_two_half_texels_the_same_way(self): + rng = np.random.default_rng(18) + for W, H in ((1, 3), (2, 2), (9, 4), (33, 7)): + tex = rng.integers(1, 1 << 31, size=W * H, dtype=np.uint64) + for _ in range(300): + tx, ty = rng.uniform(-2.5, W + 2.5), rng.uniform(-2.5, H + 2.5) + x0, x1 = _tap_axis(tx, W) + y0, y1 = _tap_axis(ty, H) + i00, i10, i01, i11 = y0 * W + x0, y0 * W + x1, y1 * W + x0, y1 * W + x1 + a = (int(tex[i00]), int(tex[i00 + 1]) if i00 + 1 < W * H else 0) + b = (int(tex[i01]), int(tex[i01 + 1]) if i01 + 1 < W * H else 0) + got = (a[0], a[1] if i10 != i00 else a[0], b[0], b[1] if i11 != i01 else b[0]) + self.assertEqual(got, (int(tex[i00]), int(tex[i10]), int(tex[i01]), int(tex[i11]))) + + def test_blend_arithmetic_is_untouched(self): + # the mix is the same call on the same four values; the _b code only changes where the values come from + full = _text("hlsl/fg_full.hlsli") + self.assertEqual(full.count("return fgf_mix4(t, fgf_unpack4h(a.xy), fgf_unpack4h(c10), fgf_unpack4h(b.xy), fgf_unpack4h(c11));"), 1) + self.assertEqual(full.count("return fgf_mix2(t, fgf_unpack2h(a.x), fgf_unpack2h(c10), fgf_unpack2h(b.x), fgf_unpack2h(c11));"), 1) + lite = _text("hlsl/fg_lite_common.hlsli") + tail = lite[lite.index("float4 fg_read_linear("):] + self.assertIn("float4 r0 = mad(ax.xxxx, t10 - t00, t00);", tail) + self.assertIn("return mad(ay.xxxx, r1 - r0, r0);", tail) + + def test_every_variant_is_declared_and_defaults_to_off(self): + for rel, base, variants in ( + ("kernels/fg_lite_blend.hlsl", "fg_lite_blend", ("fg_lite_blend_b", "fg_lite_blend_pack_b", "fg_lite_blend_bt", "fg_lite_blend_pack_bt")), + ("kernels/fg_full_blend.hlsl", "fg_full_blend", ("fg_full_blend_b", "fg_full_blend_merge_b")), + ("kernels/fg_out_pull.hlsl", "fg_out_pull", ("fg_out_pull_b", "fg_out_pull_pack_b", "fg_out_pull_bq", "fg_out_pull_pack_bq")), + ("kernels/fg_lite_g.hlsl", "fg_lite_weights", ("fg_lite_weights_b",)), + ): + decls = {d["name"]: d for d in map(_decl, _kernel_lines(_text(rel)))} + for v in variants: + self.assertIn(v, decls) + self.assertIn("FG_BIL128=1", decls[v]["defines"]) + self.assertNotIn("FG_BIL128", decls[base].get("defines", "")) + self.assertIn("#define FG_BIL128 0", _text("hlsl/fg_full.hlsli")) + self.assertIn("#define FG_BIL128 0", _text("hlsl/fg_lite_common.hlsli")) + + +# ---- A17: 32 x 8 tiles with pair stores ----------------------------------------------------------------------------------- +def _tile_map(wo, ho): + tiles_x = (wo + 31) >> 5 + n_tiles = tiles_x * ((ho + 7) // 8) + seen = {} + stores = {} + for tile in range(n_tiles): + tile_y = tile // tiles_x + for lane in range(256): + xr = ((tile - tile_y * tiles_x) << 5) + (lane & 31) + yr = (tile_y << 3) + (lane >> 5) + live = xr < wo and yr < ho + x, y = min(xr, wo - 1), min(yr, ho - 1) + if live: + seen[(x, y)] = seen.get((x, y), 0) + 1 + # the pair store: the even lane of a quad pair stores both pixels (its partner is the next lane, x + 1) + if live and (xr & 1) == 0: + if x + 1 < wo: + stores[(x, y)] = stores.get((x, y), 0) + 1 + stores[(x + 1, y)] = stores.get((x + 1, y), 0) + 1 + else: + stores[(x, y)] = stores.get((x, y), 0) + 1 + return seen, stores + + +class LiteBlendTileTest(unittest.TestCase): + def test_every_pixel_once_and_stored_once(self): + for wo, ho in ((1, 1), (2, 3), (31, 9), (32, 8), (33, 17), (64, 8), (100, 37), (127, 5), (640, 360)): + seen, stores = _tile_map(wo, ho) + want = {(x, y) for x in range(wo) for y in range(ho)} + self.assertEqual(set(seen), want, "%dx%d covered" % (wo, ho)) + self.assertTrue(all(v == 1 for v in seen.values()), "%dx%d no pixel twice" % (wo, ho)) + self.assertEqual(set(stores), want, "%dx%d stored" % (wo, ho)) + self.assertTrue(all(v == 1 for v in stores.values()), "%dx%d no pixel stored twice" % (wo, ho)) + + def test_the_grid_is_not_smaller_than_the_scanline_grid(self): + for wo, ho in ((2560, 1440), (1920, 1080), (3840, 2160), (1366, 768), (7, 3)): + tiles = ((wo + 31) >> 5) * ((ho + 7) // 8) + self.assertGreaterEqual(tiles * 256, wo * ho) + self.assertEqual(((2560 + 31) >> 5) * ((1440 + 7) // 8), (2560 * 1440 + 255) // 256) # 14400 both ways at 1440p + + def test_a_quad_pair_is_a_horizontal_pair(self): + # a wave is one tile row (lane & 31 = x offset, lane >> 5 = row) and QuadReadAcrossX swaps lane with lane ^ 1 + for lane in range(256): + partner = lane ^ 1 + self.assertEqual(lane >> 5, partner >> 5) + self.assertEqual((lane & 31) ^ 1, partner & 31) + + def test_the_kernel_is_declared_and_division_free_per_pixel(self): + decls = {d["name"]: d for d in map(_decl, _kernel_lines(_text("kernels/fg_lite_blend.hlsl")))} + for v in ("fg_lite_blend_t", "fg_lite_blend_pack_t", "fg_lite_blend_bt", "fg_lite_blend_pack_bt"): + self.assertIn("FG_TILE=1", decls[v]["defines"]) + text = _text("kernels/fg_lite_blend.hlsl") + tile = text[text.index("#elif FG_TILE"):text.index("#else", text.index("#elif FG_TILE"))] + self.assertEqual(len(re.findall(r"(? a: + e -= 1 + elif Fraction(2) ** (e + 1) <= a: + e += 1 + e = max(e, -126) + q = Fraction(2) ** (e - 23) + n = a / q + k = n.numerator // n.denominator + rem = n - k + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and k % 2 == 1): + k += 1 + v = float(k * q) + return F32(-v if neg else v) + + +def _fma(a, b, c): + a, b, c = float(a), float(b), float(c) + exact = Fraction(a) * Fraction(b) + Fraction(c) + if exact == 0: + neg = (np.signbit(a) != np.signbit(b)) and np.signbit(c) and (a * b == 0) # -0 only for (-0) + (-0) + return F32(-0.0) if neg else F32(0.0) + return _round32(exact) + + +def _mul(a, b): + return _fma(a, b, -0.0) + + +def _rcp(b): + return _round32(Fraction(1) / Fraction(float(b))) # v_rcp_f32 is exact on powers of two + + +def div_reciprocal(b): + y = _rcp(b) + return _fma(_fma(-b, y, 1.0), y, y) + + +def div_normal(a, b, y): + q = _mul(a, y) + q = _fma(_fma(-b, q, a), y, q) + return _fma(_fma(-b, q, a), y, q) + + +def level_old(a, w, m): + den = max(F32(w), F32(1.0)) + rgb = div_normal(a, den, div_reciprocal(den)) + return a if a == 0 else rgb + + +def level_new(a, w, m): + scale = F32(np.uint32((127 - 2 * m) << 23).view(F32)) + rgb = _mul(a, scale) + if F32(w) != F32(1 << (2 * m)): + raise AssertionError("the division branch is the old code") + return a if a == 0 else rgb + + +class PullPow2Test(unittest.TestCase): + def test_division_by_a_power_of_two_is_the_scale(self): + rng = np.random.default_rng(19) + samples = [F32(0.0), F32(-0.0), F32(1.0), F32(0.5), F32(1e-30), F32(1e-38), F32(1.4e-45), F32(1.17549435e-38), + F32(0.9999999), F32(3.0e-39)] + samples += [F32(v) for v in rng.uniform(0.0, 1.0, size=200)] + samples += [F32(v) for v in 10.0 ** rng.uniform(-45, 0, size=200)] + samples += [F32(v) * F32(16) for v in rng.uniform(0.0, 1.0, size=50)] # sums of 16 saturated values + for m in range(0, 5): + w = 1 << (2 * m) + for a in samples: + old = level_old(a, w, m) + new = level_new(a, w, m) + self.assertEqual(np.asarray(old, dtype=F32).view(np.uint32), np.asarray(new, dtype=F32).view(np.uint32), + "m=%d a=%r" % (m, a)) + + def test_the_condition_is_exactly_the_power_of_two(self): + # den = max(w, 1) is w itself for w = 4^m, so the reciprocal is exact; any other weight takes the division + for m in range(0, 5): + self.assertEqual(max(F32(1 << (2 * m)), F32(1.0)), F32(1 << (2 * m))) + self.assertEqual(div_reciprocal(F32(1 << (2 * m))), F32(2.0 ** (-2 * m))) + + def test_declared_and_off_by_default(self): + decls = {d["name"]: d for d in map(_decl, _kernel_lines(_text("kernels/fg_out_pull.hlsl")))} + for v in ("fg_out_pull_q", "fg_out_pull_pack_q", "fg_out_pull_bq", "fg_out_pull_pack_bq"): + self.assertIn("FGP_POW2=1", decls[v]["defines"]) + self.assertNotIn("FGP_POW2", decls["fg_out_pull"].get("defines", "")) + self.assertNotIn("FGP_POW2", decls["fg_out_pull_pack"].get("defines", "")) + self.assertIn("#define FGP_POW2 0", _text("kernels/fg_out_pull.hlsl")) + + +# ---- A18: z-sliced net2 convolutions ---------------------------------------------------------------------------------------- +class ZSliceTest(unittest.TestCase): + def setUp(self): + self.decls = [_decl(l) for l in _kernel_lines(_text("kernels/fg_net2_mconv.hlsl"))] + + def test_every_plain_convolution_has_a_z_twin(self): + base = {d["name"]: d for d in self.decls if d.get("entry") == "fg_net2_mconv" and "FG_PAIR" not in d.get("defines", "") + and "FG_UPWARP_STAGE" not in d.get("defines", "") and not d["name"].endswith("_z")} + z = {d["name"]: d for d in self.decls if d["name"].endswith("_z")} + for name, d in base.items(): + if name == "fg_net2_mconv_h3b2u": # not launched by the executor + continue + self.assertIn(name + "_z", z, name) + t = z[name + "_z"] + self.assertEqual(t["args"], d["args"] + ",u,u") # zstride, zmask + self.assertEqual(t["block"], d["block"]) + self.assertEqual(t["defines"], d["defines"] + ",FG_ZB=1,WG_Z_GRID=1") + # the originals (and what their checkers launch) are unchanged + for name, d in base.items(): + self.assertNotIn("FG_ZB", d.get("defines", "")) + self.assertNotIn("WG_Z_GRID", d.get("defines", "")) + + def test_the_pointer_order_matches_the_mask_bits(self): + text = _text("kernels/fg_net2_mconv.hlsl") + decl = re.search(r"uint a_x, a_wf, a_b, a_y, a_skip, a_y1, a_y2, a_skip1, a_skip2;", text) + self.assertTrue(decl) + setup = text[text.index("#define FG_ZB_SETUP()"):text.index("#else", text.index("#define FG_ZB_SETUP()"))] + order = ["x", "wf", "b", "y", "skip", "y1", "y2", "skip1", "skip2"] + for bit, name in enumerate(order): + self.assertIn("%s = a_%s + ((zmask & %du) != 0u ? zo_ : 0u)" % (name, name, 1 << bit), setup) + + def test_the_executor_maps_every_executor_variant(self): + cpp = (RUNTIME / "fg_d3d12_executor.cpp").read_text() + for v in ("m1b1", "m1b2", "m2b1", "m2b2", "m2b4", "m1b4s", "m1b2s", "m1b1u", "m1b2u", "m2b4u", "m3b2u", "m3b4u"): + self.assertIn('"fg_net2_mconv_%s_z"' % v, cpp) + self.assertIn("case kN2%s: return kN2z%s;" % (v, v), cpp) + self.assertIn('"fg_net2_mconv_h3b1u_z"', cpp) + self.assertIn('"fg_net2_mconv_h3b1u_s3_z"', cpp) + + def test_slice_addressing_is_the_frames_own_bank(self): + # frame f of a batch records into bank f (stride bytes after bank f - 1), the slice adds z * stride to the banked + # pointers: the address is the frame's own, in 32-bit arithmetic like the shader's + stride = 0x1200000 + for f in range(5): + for ptr in (0x400, 0x7FFFF00, 0xEF000000): + own = (ptr + f * stride) & 0xFFFFFFFF + z = f + self.assertEqual(own, (ptr + z * stride) & 0xFFFFFFFF) + + +if __name__ == "__main__": + unittest.main() From 2be02a071a97ac550f92c6df2884ae63b7a2d18c Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:15:41 -0500 Subject: [PATCH 14/15] Frame generation (D3D12): the default fuse2 mask is 593 (17 + A15 fill16 without divisions + A17 output pull power-of-two skip) Paired ABBA at 2560x1440 on an RX 9070 XT (gpu_span_per_frame, 10 rounds, interleaved, median of per-round diffs vs mask 17): mask 593 is -13 us (Preset A 2x), -1 us (C 2x), -52 us (A 6x) and -52 us (C 6x). A16 bilinear row loads (128) cost +4 to +56 us and A17 light blend tiles (256) cost +14 to +28 us on Preset C, so they leave the default; A18 net2 z-batching (1024) is neutral to worse (mask 1617: A 6x -34 us, C 2x +24 us), so it stays opt-in too. Mask 2001 (the previous default) was +14 to +20 us against 17, mask 2047 +44 to +353 us. Every lever stays switchable (WG_FG_FUSE2=MASK, --fuse2 MASK). Exact: --gpu --only turbo --debug-layer with masks 2047, 2001, 17 and 1 (the new default, 593) over Presets A / B / C and N = 1 .. 5 (2x .. 6x): 0 byte differences against every lever off, 0 Debug Layer errors; the full --gpu --debug-layer suite passes (1368 checks, 0 failed). WrongGPU-FG.asi has no dcomp.dll import. --- clean/fg/README.md | 2 +- clean/fg/runtime/fg_d3d12_executor.cpp | 8 +++++--- clean/fg/runtime/fg_d3d12_executor.h | 6 ++++-- clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp | 3 ++- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/clean/fg/README.md b/clean/fg/README.md index 5e3fc573..89fc6116 100644 --- a/clean/fg/README.md +++ b/clean/fg/README.md @@ -66,7 +66,7 @@ front end or the launcher yet. Status, open items and formats: [FORMATS.md](FORM | `runtime/fg_exec_plan.h`, `.cpp` | the D3D12 executor's CPU side (F7b, plain C++17): the light path's settings, the grid sizes of a frame size (net1 image and cell grids, scatter grid and pyramid, net2's factor and grid, the output pyramid), application regions and their ten kernel values, the float16 rounding, and the schedule of `reference/pipeline.py` `Host` split at the session's seam: once per game frame (history clears, menu detection or the disable word, R3 .. R8, net1's input / net1 / output or the quality image), per index (the intermediate-time scatters, the blend weights, the light blend for preset C or the Full blend, net2 and the output pyramid for presets A / B, the menu output; the game frame's copy without history) and the last-index part (history advances, the image pairs swap) | | `runtime/fg_d3d12_executor.h`, `.cpp` | `FgD3d12Executor`, the production `IFgKernelExecutor` on the game's D3D12 device and queue (F7b): one root signature for every FG kernel (arena root UAVs, 59 root constants, the driver channel and one texture view), the kernels' DXIL loaded from a folder built by `clean/dx12/build_dx12.py --only` and their pipelines built once, the arena sized for the frame (every image, net1's three regions, the input capture areas, the Full path and net2) with the weights uploaded at configuration; per game frame the inputs are captured from the game's textures (`fg_exec_io.hlsl`) and the shared stages recorded, the menu detection read back (a bounded wait on that submission only); per index the generated image is written into the presenter slot's texture (packed to the slot's format, COMMON -> COPY_DEST -> COMMON) and the shared producer fence signalled; menu / priming copies and the game frame's endpoint copy the colour exactly; an adapter-side real-only frame (no shared work) is captured from the game's back buffer and copied into a reserved slot (F9); net2 runs on the fast path by default (27 launches on the matrix unit, tier B: `fg_net2_mconv.hlsl`, `fg_net2_upwarp.hlsl`, the plan of `runner/fg_net2_mma.py`) with the exact 38-launch chain selectable (`FgD3d12ExecutorDesc::net2`), and `Net2SelfTest` runs net2 alone on synthetic inputs for the comparison and timing legs; every refusal names its reason and nothing falls back. `FgExecutorPresenterSource` binds the executor to the composition or DXGI back end the session creates; `FgExecWeightsFromModel` takes the weights from a checked model file | | `runtime/tests/test_fg_d3d12_e2e.cpp` | ctest `fg_d3d12_e2e` (CPU): geometry, regions, thresholds and the logistic table against the CPU reference, the float16 rounding, the schedule, every executor refusal that needs no GPU and a session whose executor refuses (no presenter, no fallback). `--gpu --dxil /dx12` adds the headless GPU leg (no window): a synthetic game through the adapter core, the session and the executor with the composition back end (unbound surface) and the DXGI back end (composition swap chain) for preset C 2x / 6x and presets A / B 2x with a menu frame, net2's exact path, and frames with generation switched off in the game's options (real-only from the back buffer) (generated images finite, menu and endpoint copies exact, slot bytes equal to the image in the slot's format, fences complete, DXGI slots all returned, the swap chain released right after teardown; `--debug-layer` adds the D3D12 debug layer), net2's fast path against the exact one on synthetic inputs (within tolerance, deterministic, every value written, a half-covered last launch caught; GPU time at the 1080p and 1440p grids, information only), and kernel folders with a broken kernel that must be refused | -| Turbo v2 (executor levers, all exact: the kernels' arithmetic is untouched, only where and when independent work runs and four fused / retiled kernels) | `WG_FG_BATCH=0` / `WG_FG_HOIST=0` / `WG_FG_DUALQ=0` / `WG_FG_FUSE=0` (or `FgD3d12ExecutorDesc::batch / hoist / dualq / fuse`) turn a lever off for paired A / B runs; all four give the same bytes as all four off (`test_fg_d3d12_e2e --gpu --dxil --only turbo`: every slot over four game frames, presets A / B / C, N = 1..5, byte for byte). Scratch banks: the per-index images (MA, MB, W, the generated image and its packed rows, the Full blend's images, net2's tensors, the output pyramid) are one block repeated once per generated index (`max_generated` banks while the arena fits). `RecordGeneratedBatch` (the session calls it when `BatchesGenerated()`) records layer k of every index back to back, so barriers sit only between dependent layers and the small net2 / pyramid layers of several indices fill the GPU together. Hoist: the per-index MA / MB fills and intermediate-time scatters of every index of the game frame run on a second compute queue beside net1 (they read only the p2c results) and the producer queue waits for them before the first index. Dual queue: the game queue's work is two recordings (motion preparation, then the downsample) so the p2c chain starts after the first and the net1 input waits for the second. Fuse: `fg_lite_p2c_fine_mask` (fine pass + hole mask when the net1 grid is the scatter grid), `fg_lite_p2c_inpaint_tiled` (32 x 8 tiles, ballot row masks), `fg_lite_interm_both` (both passes, 32 x 32 LDS-binned signed 64-bit minima) and `fg_net2_mconv_h3b1u_s3` (L25's three heads staged in one pass). Wave 1B (`WG_FG_FUSE2=0` or `FgD3d12ExecutorDesc::fuse2 = 0` keeps the Wave 1 kernels; the default (1) runs the two levers that won in paired timing at 1440p on an RX 9070 XT, net1 cells + pyramid tail (mask 17), and 63 runs every lever (net2 pairs, upwarp in L14, blend weights and RGB X0 / X1 are exact but cost GPU time, so they stay opt-in); a mask picks levers: 1 net1 cells, 2 net2 pairs, 4 upwarp in L14, 8 blend weights, 16 pyramid tail, 32 X0 / X1 as RGB; `test_fg_d3d12_e2e --bench --fuse2 0|1|MASK`; each exact against the kernels it replaces, checked by `--gpu --only turbo` in two legs: every lever on against every lever off, and Wave 1B alone against Wave 1): `fg_mconv2_mid_cells` (net1_01 builds its cells in LDS from the same images `fg_lite_net1_input` packs and writes Qc / Om itself: no input launch, no cell round trip), `fg_net2_mpair_res_c64` / `_c32` (net2's residual pairs L4+L5 .. L10+L11 and L16+L17 .. L22+L23 in one launch: 14 x 6 interiors, the first layer on the 16 x 8 region with its border and its output kept in LDS), `fg_net2_mconv_m1b2_uw` / `_m1b2s_uw` (L14 computes the upwarp for its staged tile and writes U4 / U1 / U3 itself: no y tensor, no upwarp launch), `fg_lite_blend_w` / `_pack_w` and `fg_full_blend_w` / `_merge_w` (the blend builds the W texels its tile's taps touch in LDS: no weights launch or W image read), `fg_out_tail` (the coarsest pushes in one workgroup, as many levels as fit 28 KB of LDS) with `fg_out_push_fine_l1` / `_pack_l1` (level 1 pushed on the spot at the holes' taps: no level-1 launch), and `fg_full_blend_*_x3` / `fg_out_pull_x3` (X0 / X1 stored as 6-byte RGB: only the output pull reads them and never their alpha). The CPU proofs of their exactness arguments are in `tests/test_fg_turbo_v2.py` (copied bodies compared line by line, tile bounds, the pyramid push chain, the residual pair fusion). Profiling: `WRONGGPU_FG_KPROF=1` or `test_fg_d3d12_e2e --bench --kprof` lists every launch (kernel, workgroups, us); `--gen N` benchmarks 2x..6x for real and reports the wall-clock span and busy time of all queues next to the per-stage sums; the CPU proofs of the exactness arguments are `tests/test_fg_turbo_v2.py`, and `runner/fg_lite_d3d12_check.py --turbo` checks the Turbo kernels against the CPU reference | +| Turbo v2 (executor levers, all exact: the kernels' arithmetic is untouched, only where and when independent work runs and four fused / retiled kernels) | `WG_FG_BATCH=0` / `WG_FG_HOIST=0` / `WG_FG_DUALQ=0` / `WG_FG_FUSE=0` (or `FgD3d12ExecutorDesc::batch / hoist / dualq / fuse`) turn a lever off for paired A / B runs; all four give the same bytes as all four off (`test_fg_d3d12_e2e --gpu --dxil --only turbo`: every slot over four game frames, presets A / B / C, N = 1..5, byte for byte). Scratch banks: the per-index images (MA, MB, W, the generated image and its packed rows, the Full blend's images, net2's tensors, the output pyramid) are one block repeated once per generated index (`max_generated` banks while the arena fits). `RecordGeneratedBatch` (the session calls it when `BatchesGenerated()`) records layer k of every index back to back, so barriers sit only between dependent layers and the small net2 / pyramid layers of several indices fill the GPU together. Hoist: the per-index MA / MB fills and intermediate-time scatters of every index of the game frame run on a second compute queue beside net1 (they read only the p2c results) and the producer queue waits for them before the first index. Dual queue: the game queue's work is two recordings (motion preparation, then the downsample) so the p2c chain starts after the first and the net1 input waits for the second. Fuse: `fg_lite_p2c_fine_mask` (fine pass + hole mask when the net1 grid is the scatter grid), `fg_lite_p2c_inpaint_tiled` (32 x 8 tiles, ballot row masks), `fg_lite_interm_both` (both passes, 32 x 32 LDS-binned signed 64-bit minima) and `fg_net2_mconv_h3b1u_s3` (L25's three heads staged in one pass). Wave 1B (`WG_FG_FUSE2=0` or `FgD3d12ExecutorDesc::fuse2 = 0` keeps the Wave 1 kernels; the default (1) runs the levers that won in paired timing at 1440p on an RX 9070 XT, net1 cells + pyramid tail + the fill without divisions + the output pull's power-of-two skip (mask 593 = 17 + 64 + 512; the Wave 2 levers 128 bilinear row loads and 256 light blend tiles regress and 1024 net2 z-batching is neutral, so they stay opt-in), and 63 runs every Wave 1B lever (net2 pairs, upwarp in L14, blend weights and RGB X0 / X1 are exact but cost GPU time, so they stay opt-in); a mask picks levers: 1 net1 cells, 2 net2 pairs, 4 upwarp in L14, 8 blend weights, 16 pyramid tail, 32 X0 / X1 as RGB; `test_fg_d3d12_e2e --bench --fuse2 0|1|MASK`; each exact against the kernels it replaces, checked by `--gpu --only turbo` in two legs: every lever on against every lever off, and Wave 1B alone against Wave 1): `fg_mconv2_mid_cells` (net1_01 builds its cells in LDS from the same images `fg_lite_net1_input` packs and writes Qc / Om itself: no input launch, no cell round trip), `fg_net2_mpair_res_c64` / `_c32` (net2's residual pairs L4+L5 .. L10+L11 and L16+L17 .. L22+L23 in one launch: 14 x 6 interiors, the first layer on the 16 x 8 region with its border and its output kept in LDS), `fg_net2_mconv_m1b2_uw` / `_m1b2s_uw` (L14 computes the upwarp for its staged tile and writes U4 / U1 / U3 itself: no y tensor, no upwarp launch), `fg_lite_blend_w` / `_pack_w` and `fg_full_blend_w` / `_merge_w` (the blend builds the W texels its tile's taps touch in LDS: no weights launch or W image read), `fg_out_tail` (the coarsest pushes in one workgroup, as many levels as fit 28 KB of LDS) with `fg_out_push_fine_l1` / `_pack_l1` (level 1 pushed on the spot at the holes' taps: no level-1 launch), and `fg_full_blend_*_x3` / `fg_out_pull_x3` (X0 / X1 stored as 6-byte RGB: only the output pull reads them and never their alpha). The CPU proofs of their exactness arguments are in `tests/test_fg_turbo_v2.py` (copied bodies compared line by line, tile bounds, the pyramid push chain, the residual pair fusion). Profiling: `WRONGGPU_FG_KPROF=1` or `test_fg_d3d12_e2e --bench --kprof` lists every launch (kernel, workgroups, us); `--gen N` benchmarks 2x..6x for real and reports the wall-clock span and busy time of all queues next to the per-stage sums; the CPU proofs of the exactness arguments are `tests/test_fg_turbo_v2.py`, and `runner/fg_lite_d3d12_check.py --turbo` checks the Turbo kernels against the CPU reference | | `clean/dx12/kernels/fg_exec_io.hlsl` | the executor's input capture (a game texture of any readable format into the arena's float16 / float32 image kinds) and output pack (the float16 image into a slot format: RGBA16F, RGBA8 / BGRA8, RGB10A2) | | `fg_limits.h` | `kFgMaxGenerated`, shared by the presenter and the runtime so one file can include both (the runtime contract's own status and real-only enums are `FgFrameStatus` / `FgFrameRealOnly`, distinct from the presenter's `FgStatus` / `FgRealOnlyReason`) | | `tools/gen_fg_runtime_tables.py`, `tests/test_fg_runtime_tables.py` | writes / checks the two generated headers (the map table; the fused plan and the weight fragments of constructed float16 patterns from `runner/fg_net1_mma.py`) | diff --git a/clean/fg/runtime/fg_d3d12_executor.cpp b/clean/fg/runtime/fg_d3d12_executor.cpp index c8c1fd3e..07926255 100644 --- a/clean/fg/runtime/fg_d3d12_executor.cpp +++ b/clean/fg/runtime/fg_d3d12_executor.cpp @@ -70,9 +70,11 @@ enum Fuse2Bit : uint32_t { // 32 x 8 tiles with 8-byte pair stores and the output pull skipping its division on hole-free tiles, A18 net2's // convolutions of every generated index of a batch in one (groups, 1, N) launch kF2Fill = 64, kF2Bil = 128, kF2Tile = 256, kF2Pow2 = 512, kF2NetZ = 1024, kF2All = 2047, - // the levers that won in paired ABBA runs at 1440p (A6 net1 cells, A14 pyramid tail); the others are exact but cost GPU time - // (A13 weights in the blends, A7 net2 pairs, A9 upwarp in L14, A12 RGB X0 / X1) and stay opt-in (a mask, e.g. 63) - kF2Default = kF2Cells | kF2Tail | kF2Fill | kF2Bil | kF2Tile | kF2Pow2 | kF2NetZ, // 17 is the Wave 1B default + // the levers that won in paired ABBA runs at 1440p (A6 net1 cells, A14 pyramid tail, A15 fill16 without divisions, A17 + // output pull power-of-two skip); the others are exact but do not win (A13 weights in the blends, A7 net2 pairs, A9 upwarp + // in L14, A12 RGB X0 / X1 cost GPU time; A16 bilinear row loads and the A17 light blend tiles regress, A18 net2 z-batching + // is neutral) and stay opt-in (a mask, e.g. 63 or 2047) + kF2Default = kF2Cells | kF2Tail | kF2Fill | kF2Pow2, // 593; 17 is the Wave 1B default }; constexpr uint32_t kFirstTurbo = kFineMask; // a pipeline of these that the device refuses is dropped, not fatal constexpr uint32_t kFirstFull = kFullBlend; diff --git a/clean/fg/runtime/fg_d3d12_executor.h b/clean/fg/runtime/fg_d3d12_executor.h index 99b8ce86..c63bd470 100644 --- a/clean/fg/runtime/fg_d3d12_executor.h +++ b/clean/fg/runtime/fg_d3d12_executor.h @@ -186,12 +186,14 @@ struct FgD3d12ExecutorDesc { // (fg_lite_blend_w / _pack_w, fg_full_blend_*_w), 16 the output pyramid's coarse pushes in one workgroup // (fg_out_tail) and level 1 pushed in the fine pass (fg_out_push_fine_l1), 32 X0 / X1 stored as RGB // (fg_full_blend_*_x3, fg_out_pull_x3). Independent of fuse. - // Wave 2 (all bit-exact, in the default; WG_FG_FUSE2=17 is the Wave 1B default without them): 64 fg_lite_fill16_p2 (A15: + // Wave 2 (all bit-exact; 64 and 512 are in the default, the others are opt-in; WG_FG_FUSE2=17 is the Wave 1B default + // without them): 64 fg_lite_fill16_p2 (A15: // the fill without integer divisions), 128 the bilinear taps of the blends, the light weights and the output pull as // 16 / 8-byte row loads (A16: the _b kernels), 256 the light blend on 32 x 8 tiles with 8-byte pair stores (A17: the _t // kernels), 512 the output pull's division skipped on hole-free tiles (A17: the _q kernels), 1024 net2's convolutions of // the indices of a batch as one (groups, 1, N) launch (A18: the _z kernels; needs batch; WG_FG_NET2_BATCH=0 turns it - // off whatever the mask says). The default mask is 2001 = 17 + 64 + 128 + 256 + 512 + 1024; 2047 is every lever. + // off whatever the mask says). The default mask is 593 = 17 + 64 + 512 (paired ABBA at 1440p: 128 and 256 regress, 1024 + // is neutral); 2001 is 17 + all of Wave 2 and 2047 is every lever. int batch = -1, hoist = -1, dualq = -1, fuse = -1, fuse2 = -1; // Developer frame dumps (off while dump_dir is empty; the ASI sets it only in a developer build): of the game // frames that generate, every dump_every-th one (at most dump_max), the game frame's slot image (game_.ppm) and diff --git a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp index a246076f..c75bfad5 100644 --- a/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp +++ b/clean/fg/runtime/tests/test_fg_d3d12_e2e.cpp @@ -17,7 +17,8 @@ // a mask of the Wave 1B levers: 1 net1 cells, 2 net2 pairs, 4 upwarp in L14, 8 blend weights, // 16 pyramid tail, 32 X0 / X1 as RGB, and the Wave 2 levers 64 fill16 without divisions, 128 bilinear row // loads, 256 light blend tiles, 512 output pull power-of-two skip, 1024 net2 z-batching; the default is -// 2001 = 17 + all of Wave 2, 17 alone is the Wave 1B default; WG_FG_NET2_BATCH=0 also stops 1024) +// 593 = 17 + 64 + 512, 17 alone is the Wave 1B default, 2001 = 17 + all of Wave 2; +// WG_FG_NET2_BATCH=0 also stops 1024) // [--turbo-fuse2 MASK] the Wave 1B mask the --only turbo legs run against all levers off (default 2047: every lever) // The report has the per-stage sums and the honest multi-queue numbers: the wall-clock GPU span and the busy // time per game frame over the timed window (overlap between queues is counted once there, twice in the sums). From 4bef024f9893d461dd6991650171f9acfe0bd9f1 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:32 -0500 Subject: [PATCH 15/15] Frame generation (D3D12): CI follow-up - Wave 2 test file in LF, K softmax self-check digest for the WG_Z_GRID line in wg_platform.hlsli test_fg_turbo_v2_wave2.py was committed with CR LF (tools/ci/check_line_endings.py). Wave 2's WG_Z_GRID block in wg_platform.hlsli (the default 0 leaves WG_KERNEL as before) is in the include closure of Model K's softmax self-check kernels, so k_smx_selfcheck.h's kSourceDigest no longer matched (clean/k/dx12/smx_selfcheck_digest.py); only the digest line is updated (the reference hashes come from the HIP kernels, which this change does not touch). test_k_smx_selfcheck_digest, test_dev_diagnostics_off, test_build_models and the FG turbo v2 tests pass locally. --- clean/fg/tests/test_fg_turbo_v2_wave2.py | 820 +++++++++++------------ clean/k/runtime/k_smx_selfcheck.h | 2 +- 2 files changed, 411 insertions(+), 411 deletions(-) diff --git a/clean/fg/tests/test_fg_turbo_v2_wave2.py b/clean/fg/tests/test_fg_turbo_v2_wave2.py index 43c802df..f3e430f4 100644 --- a/clean/fg/tests/test_fg_turbo_v2_wave2.py +++ b/clean/fg/tests/test_fg_turbo_v2_wave2.py @@ -1,410 +1,410 @@ -# SPDX-License-Identifier: MIT -"""CPU proofs of the exactness arguments behind frame generation's Wave 2 kernels (the fuse2 bits 64 .. 1024): -A15 fg_lite_fill16_p2, A16 the bilinear row loads (FG_BIL128), A17 the light blend's 32 x 8 tiles with pair stores -(FG_TILE) and the output pull's division skip (FGP_POW2), A18 the z-sliced net2 convolutions (FG_ZB). Each class restates -what the Wave 1B kernel computes and what the Wave 2 kernel computes, as the HLSL does, and compares them on random and -edge inputs; the kernels themselves are checked on a GPU by test_fg_d3d12_e2e --gpu --only turbo (every lever on against -every lever off, default mask 2047).""" -import re -import unittest -from fractions import Fraction -from pathlib import Path - -import numpy as np - -F32 = np.float32 -DX12 = Path(__file__).resolve().parents[2] / "dx12" -RUNTIME = Path(__file__).resolve().parents[1] / "runtime" - - -def _text(rel): - return (DX12 / rel).read_text() - - -def _kernel_lines(text): - return [l for l in text.splitlines() if l.startswith("// @wg-kernel ")] - - -def _decl(line): - m = re.match(r"// @wg-kernel (\S+) (.*)$", line) - d = {"name": m.group(1)} - for tok in m.group(2).split(): - k, v = tok.split("=", 1) - d[k] = v - return d - - -def _function_text(text, signature): - start = text.index(signature) - open_ = text.index("{", start) - depth, i = 0, open_ - while True: - if text[i] == "{": - depth += 1 - elif text[i] == "}": - depth -= 1 - if depth == 0: - return text[start:i + 1] - i += 1 - - -# ---- A15: fg_lite_fill16_p2 ----------------------------------------------------------------------------------------------- -def fill_old(n16, period, p): - """fg_lite_fill16: unit i = p[i % period]; each lane writes 8 units (one 16-byte store when all 8 are inside).""" - out = np.zeros(n16, dtype=np.uint16) - for lane in range((n16 + 7) // 8): - first = lane * 8 - if first + 8 <= n16: - for j in range(8): - out[first + j] = p[(first + j) % period] & 0xFFFF - else: - for i in range(first, n16): - out[i] = p[i % period] & 0xFFFF - return out - - -def fill_new(n16, period, p): - """fg_lite_fill16_p2: the same word for every full lane, the tail by i & (period - 1).""" - u0 = p[0] & 0xFFFF - u1 = (p[0] if period == 1 else p[1]) & 0xFFFF - u2 = (p[2] if period == 4 else p[0]) & 0xFFFF - u3 = (p[0] if period == 1 else (p[3] if period == 4 else p[1])) & 0xFFFF - lo, hi = u0 | (u1 << 16), u2 | (u3 << 16) - word = (lo, hi, lo, hi) - out = np.zeros(n16, dtype=np.uint16) - for lane in range((n16 + 7) // 8): - first = lane * 8 - assert first % 8 == 0 - if first + 8 <= n16: - for j in range(8): - out[first + j] = (word[j // 2] >> (16 * (j % 2))) & 0xFFFF - else: - for i in range(first, n16): - out[i] = p[i & (period - 1)] & 0xFFFF - return out - - -class FillP2Test(unittest.TestCase): - def test_same_units_for_every_period_and_size(self): - rng = np.random.default_rng(15) - for period in (1, 2, 4): - for n16 in list(range(1, 40)) + [255, 256, 2047, 2048, 2049, 4097]: - for _ in range(3): - p = [int(v) for v in rng.integers(0, 1 << 32, size=4, dtype=np.uint64)] # the high bits are masked - np.testing.assert_array_equal(fill_old(n16, period, p), fill_new(n16, period, p), - err_msg="period %d n16 %d" % (period, n16)) - - def test_the_runtime_patterns(self): - # every Fill16 the executor records: clear {1.0}, clear {0,0,0,1}, a word as two units, fill64 (0xFFFF, 0x7FFF) - for period, p in ((1, [0x3C00, 0, 0, 0]), (4, [0, 0, 0, 0x3C00]), (2, [0xFFFF, 0x7FFF, 0, 0]), (2, [0, 0, 0, 0]), - (1, [0x5A5A] * 4)): - for n16 in (1, 2, 3, 7, 8, 9, 2457600, 1 << 20): - if n16 > 5000: - n16 = n16 % 5000 + 3 - np.testing.assert_array_equal(fill_old(n16, period, p), fill_new(n16, period, p)) - - def test_the_new_kernel_has_no_division(self): - text = _text("kernels/fg_lite_util.hlsl") - body = _function_text(text, "WG_KERNEL(fg_lite_fill16)") # the first one is the FG_FILL_P2 branch - self.assertIn("#if FG_FILL_P2", text) - p2 = text[text.index("#if FG_FILL_P2"):text.index("#else", text.index("#if FG_FILL_P2"))] - self.assertNotIn("%", p2.replace("// ", "//"), "no modulo in the FG_FILL_P2 kernel") - self.assertNotIn(" / ", re.sub(r"//.*", "", p2)) - self.assertIn("fg_lite_fill16_p2", text) - self.assertTrue(body) - - def test_first_is_a_multiple_of_eight(self): - # first = (block * 256 + lane) * 8: the units of a lane start at a multiple of 8, so unit j of the lane has - # i & (period - 1) == j & (period - 1) for every period that divides 8 - for first in range(0, 8 * 600, 8): - for period in (1, 2, 4): - for j in range(8): - self.assertEqual((first + j) % period, j & (period - 1)) - - -# ---- A16: bilinear row loads ---------------------------------------------------------------------------------------------- -def _tap_axis(t, n): - """fgf_tap / fg_read_linear: x0, x1 for the texel position t on an axis of n texels.""" - x0f = np.floor(F32(t)) - xi = int(np.clip(int(x0f), -1, n - 1)) - return max(xi, 0), min(xi + 1, n - 1) - - -class BilinearRowLoadTest(unittest.TestCase): - def test_second_texel_is_the_next_one_or_the_same(self): - rng = np.random.default_rng(16) - for n in (1, 2, 3, 5, 16, 17, 1920, 2560): - ts = list(rng.uniform(-3.0, n + 3.0, size=400)) + [-0.5, 0.0, n - 1.0, n - 0.5, n - 1e-4, float(n), -1e-9] - for t in ts: - x0, x1 = _tap_axis(t, n) - self.assertIn(x1 - x0, (0, 1), "n=%d t=%r" % (n, t)) - self.assertGreaterEqual(x0, 0) - self.assertLessEqual(x1, n - 1) - - def test_row_load_gives_the_four_load_texels(self): - # a buffer of 8-byte texels (W x H) with distinct values; the row load reads the texel at i00 and the one after it - # (zero past the end of the buffer: robust buffer access), the second texel is the loaded one unless x1 == x0 - rng = np.random.default_rng(17) - for W, H in ((1, 1), (1, 5), (2, 2), (5, 3), (17, 9), (64, 4)): - tex = rng.integers(1, 1 << 63, size=W * H, dtype=np.uint64) - - def row_load(i): - return int(tex[i]), (int(tex[i + 1]) if i + 1 < W * H else 0) - - for _ in range(300): - tx, ty = rng.uniform(-2.5, W + 2.5), rng.uniform(-2.5, H + 2.5) - x0, x1 = _tap_axis(tx, W) - y0, y1 = _tap_axis(ty, H) - i00, i10, i01, i11 = y0 * W + x0, y0 * W + x1, y1 * W + x0, y1 * W + x1 - a0, a1 = row_load(i00) - b0, b1 = row_load(i01) - got = (a0, a1 if i10 != i00 else a0, b0, b1 if i11 != i01 else b0) - want = (int(tex[i00]), int(tex[i10]), int(tex[i01]), int(tex[i11])) - self.assertEqual(got, want, "W=%d H=%d tap (%r, %r)" % (W, H, tx, ty)) - - def test_two_half_texels_the_same_way(self): - rng = np.random.default_rng(18) - for W, H in ((1, 3), (2, 2), (9, 4), (33, 7)): - tex = rng.integers(1, 1 << 31, size=W * H, dtype=np.uint64) - for _ in range(300): - tx, ty = rng.uniform(-2.5, W + 2.5), rng.uniform(-2.5, H + 2.5) - x0, x1 = _tap_axis(tx, W) - y0, y1 = _tap_axis(ty, H) - i00, i10, i01, i11 = y0 * W + x0, y0 * W + x1, y1 * W + x0, y1 * W + x1 - a = (int(tex[i00]), int(tex[i00 + 1]) if i00 + 1 < W * H else 0) - b = (int(tex[i01]), int(tex[i01 + 1]) if i01 + 1 < W * H else 0) - got = (a[0], a[1] if i10 != i00 else a[0], b[0], b[1] if i11 != i01 else b[0]) - self.assertEqual(got, (int(tex[i00]), int(tex[i10]), int(tex[i01]), int(tex[i11]))) - - def test_blend_arithmetic_is_untouched(self): - # the mix is the same call on the same four values; the _b code only changes where the values come from - full = _text("hlsl/fg_full.hlsli") - self.assertEqual(full.count("return fgf_mix4(t, fgf_unpack4h(a.xy), fgf_unpack4h(c10), fgf_unpack4h(b.xy), fgf_unpack4h(c11));"), 1) - self.assertEqual(full.count("return fgf_mix2(t, fgf_unpack2h(a.x), fgf_unpack2h(c10), fgf_unpack2h(b.x), fgf_unpack2h(c11));"), 1) - lite = _text("hlsl/fg_lite_common.hlsli") - tail = lite[lite.index("float4 fg_read_linear("):] - self.assertIn("float4 r0 = mad(ax.xxxx, t10 - t00, t00);", tail) - self.assertIn("return mad(ay.xxxx, r1 - r0, r0);", tail) - - def test_every_variant_is_declared_and_defaults_to_off(self): - for rel, base, variants in ( - ("kernels/fg_lite_blend.hlsl", "fg_lite_blend", ("fg_lite_blend_b", "fg_lite_blend_pack_b", "fg_lite_blend_bt", "fg_lite_blend_pack_bt")), - ("kernels/fg_full_blend.hlsl", "fg_full_blend", ("fg_full_blend_b", "fg_full_blend_merge_b")), - ("kernels/fg_out_pull.hlsl", "fg_out_pull", ("fg_out_pull_b", "fg_out_pull_pack_b", "fg_out_pull_bq", "fg_out_pull_pack_bq")), - ("kernels/fg_lite_g.hlsl", "fg_lite_weights", ("fg_lite_weights_b",)), - ): - decls = {d["name"]: d for d in map(_decl, _kernel_lines(_text(rel)))} - for v in variants: - self.assertIn(v, decls) - self.assertIn("FG_BIL128=1", decls[v]["defines"]) - self.assertNotIn("FG_BIL128", decls[base].get("defines", "")) - self.assertIn("#define FG_BIL128 0", _text("hlsl/fg_full.hlsli")) - self.assertIn("#define FG_BIL128 0", _text("hlsl/fg_lite_common.hlsli")) - - -# ---- A17: 32 x 8 tiles with pair stores ----------------------------------------------------------------------------------- -def _tile_map(wo, ho): - tiles_x = (wo + 31) >> 5 - n_tiles = tiles_x * ((ho + 7) // 8) - seen = {} - stores = {} - for tile in range(n_tiles): - tile_y = tile // tiles_x - for lane in range(256): - xr = ((tile - tile_y * tiles_x) << 5) + (lane & 31) - yr = (tile_y << 3) + (lane >> 5) - live = xr < wo and yr < ho - x, y = min(xr, wo - 1), min(yr, ho - 1) - if live: - seen[(x, y)] = seen.get((x, y), 0) + 1 - # the pair store: the even lane of a quad pair stores both pixels (its partner is the next lane, x + 1) - if live and (xr & 1) == 0: - if x + 1 < wo: - stores[(x, y)] = stores.get((x, y), 0) + 1 - stores[(x + 1, y)] = stores.get((x + 1, y), 0) + 1 - else: - stores[(x, y)] = stores.get((x, y), 0) + 1 - return seen, stores - - -class LiteBlendTileTest(unittest.TestCase): - def test_every_pixel_once_and_stored_once(self): - for wo, ho in ((1, 1), (2, 3), (31, 9), (32, 8), (33, 17), (64, 8), (100, 37), (127, 5), (640, 360)): - seen, stores = _tile_map(wo, ho) - want = {(x, y) for x in range(wo) for y in range(ho)} - self.assertEqual(set(seen), want, "%dx%d covered" % (wo, ho)) - self.assertTrue(all(v == 1 for v in seen.values()), "%dx%d no pixel twice" % (wo, ho)) - self.assertEqual(set(stores), want, "%dx%d stored" % (wo, ho)) - self.assertTrue(all(v == 1 for v in stores.values()), "%dx%d no pixel stored twice" % (wo, ho)) - - def test_the_grid_is_not_smaller_than_the_scanline_grid(self): - for wo, ho in ((2560, 1440), (1920, 1080), (3840, 2160), (1366, 768), (7, 3)): - tiles = ((wo + 31) >> 5) * ((ho + 7) // 8) - self.assertGreaterEqual(tiles * 256, wo * ho) - self.assertEqual(((2560 + 31) >> 5) * ((1440 + 7) // 8), (2560 * 1440 + 255) // 256) # 14400 both ways at 1440p - - def test_a_quad_pair_is_a_horizontal_pair(self): - # a wave is one tile row (lane & 31 = x offset, lane >> 5 = row) and QuadReadAcrossX swaps lane with lane ^ 1 - for lane in range(256): - partner = lane ^ 1 - self.assertEqual(lane >> 5, partner >> 5) - self.assertEqual((lane & 31) ^ 1, partner & 31) - - def test_the_kernel_is_declared_and_division_free_per_pixel(self): - decls = {d["name"]: d for d in map(_decl, _kernel_lines(_text("kernels/fg_lite_blend.hlsl")))} - for v in ("fg_lite_blend_t", "fg_lite_blend_pack_t", "fg_lite_blend_bt", "fg_lite_blend_pack_bt"): - self.assertIn("FG_TILE=1", decls[v]["defines"]) - text = _text("kernels/fg_lite_blend.hlsl") - tile = text[text.index("#elif FG_TILE"):text.index("#else", text.index("#elif FG_TILE"))] - self.assertEqual(len(re.findall(r"(? a: - e -= 1 - elif Fraction(2) ** (e + 1) <= a: - e += 1 - e = max(e, -126) - q = Fraction(2) ** (e - 23) - n = a / q - k = n.numerator // n.denominator - rem = n - k - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and k % 2 == 1): - k += 1 - v = float(k * q) - return F32(-v if neg else v) - - -def _fma(a, b, c): - a, b, c = float(a), float(b), float(c) - exact = Fraction(a) * Fraction(b) + Fraction(c) - if exact == 0: - neg = (np.signbit(a) != np.signbit(b)) and np.signbit(c) and (a * b == 0) # -0 only for (-0) + (-0) - return F32(-0.0) if neg else F32(0.0) - return _round32(exact) - - -def _mul(a, b): - return _fma(a, b, -0.0) - - -def _rcp(b): - return _round32(Fraction(1) / Fraction(float(b))) # v_rcp_f32 is exact on powers of two - - -def div_reciprocal(b): - y = _rcp(b) - return _fma(_fma(-b, y, 1.0), y, y) - - -def div_normal(a, b, y): - q = _mul(a, y) - q = _fma(_fma(-b, q, a), y, q) - return _fma(_fma(-b, q, a), y, q) - - -def level_old(a, w, m): - den = max(F32(w), F32(1.0)) - rgb = div_normal(a, den, div_reciprocal(den)) - return a if a == 0 else rgb - - -def level_new(a, w, m): - scale = F32(np.uint32((127 - 2 * m) << 23).view(F32)) - rgb = _mul(a, scale) - if F32(w) != F32(1 << (2 * m)): - raise AssertionError("the division branch is the old code") - return a if a == 0 else rgb - - -class PullPow2Test(unittest.TestCase): - def test_division_by_a_power_of_two_is_the_scale(self): - rng = np.random.default_rng(19) - samples = [F32(0.0), F32(-0.0), F32(1.0), F32(0.5), F32(1e-30), F32(1e-38), F32(1.4e-45), F32(1.17549435e-38), - F32(0.9999999), F32(3.0e-39)] - samples += [F32(v) for v in rng.uniform(0.0, 1.0, size=200)] - samples += [F32(v) for v in 10.0 ** rng.uniform(-45, 0, size=200)] - samples += [F32(v) * F32(16) for v in rng.uniform(0.0, 1.0, size=50)] # sums of 16 saturated values - for m in range(0, 5): - w = 1 << (2 * m) - for a in samples: - old = level_old(a, w, m) - new = level_new(a, w, m) - self.assertEqual(np.asarray(old, dtype=F32).view(np.uint32), np.asarray(new, dtype=F32).view(np.uint32), - "m=%d a=%r" % (m, a)) - - def test_the_condition_is_exactly_the_power_of_two(self): - # den = max(w, 1) is w itself for w = 4^m, so the reciprocal is exact; any other weight takes the division - for m in range(0, 5): - self.assertEqual(max(F32(1 << (2 * m)), F32(1.0)), F32(1 << (2 * m))) - self.assertEqual(div_reciprocal(F32(1 << (2 * m))), F32(2.0 ** (-2 * m))) - - def test_declared_and_off_by_default(self): - decls = {d["name"]: d for d in map(_decl, _kernel_lines(_text("kernels/fg_out_pull.hlsl")))} - for v in ("fg_out_pull_q", "fg_out_pull_pack_q", "fg_out_pull_bq", "fg_out_pull_pack_bq"): - self.assertIn("FGP_POW2=1", decls[v]["defines"]) - self.assertNotIn("FGP_POW2", decls["fg_out_pull"].get("defines", "")) - self.assertNotIn("FGP_POW2", decls["fg_out_pull_pack"].get("defines", "")) - self.assertIn("#define FGP_POW2 0", _text("kernels/fg_out_pull.hlsl")) - - -# ---- A18: z-sliced net2 convolutions ---------------------------------------------------------------------------------------- -class ZSliceTest(unittest.TestCase): - def setUp(self): - self.decls = [_decl(l) for l in _kernel_lines(_text("kernels/fg_net2_mconv.hlsl"))] - - def test_every_plain_convolution_has_a_z_twin(self): - base = {d["name"]: d for d in self.decls if d.get("entry") == "fg_net2_mconv" and "FG_PAIR" not in d.get("defines", "") - and "FG_UPWARP_STAGE" not in d.get("defines", "") and not d["name"].endswith("_z")} - z = {d["name"]: d for d in self.decls if d["name"].endswith("_z")} - for name, d in base.items(): - if name == "fg_net2_mconv_h3b2u": # not launched by the executor - continue - self.assertIn(name + "_z", z, name) - t = z[name + "_z"] - self.assertEqual(t["args"], d["args"] + ",u,u") # zstride, zmask - self.assertEqual(t["block"], d["block"]) - self.assertEqual(t["defines"], d["defines"] + ",FG_ZB=1,WG_Z_GRID=1") - # the originals (and what their checkers launch) are unchanged - for name, d in base.items(): - self.assertNotIn("FG_ZB", d.get("defines", "")) - self.assertNotIn("WG_Z_GRID", d.get("defines", "")) - - def test_the_pointer_order_matches_the_mask_bits(self): - text = _text("kernels/fg_net2_mconv.hlsl") - decl = re.search(r"uint a_x, a_wf, a_b, a_y, a_skip, a_y1, a_y2, a_skip1, a_skip2;", text) - self.assertTrue(decl) - setup = text[text.index("#define FG_ZB_SETUP()"):text.index("#else", text.index("#define FG_ZB_SETUP()"))] - order = ["x", "wf", "b", "y", "skip", "y1", "y2", "skip1", "skip2"] - for bit, name in enumerate(order): - self.assertIn("%s = a_%s + ((zmask & %du) != 0u ? zo_ : 0u)" % (name, name, 1 << bit), setup) - - def test_the_executor_maps_every_executor_variant(self): - cpp = (RUNTIME / "fg_d3d12_executor.cpp").read_text() - for v in ("m1b1", "m1b2", "m2b1", "m2b2", "m2b4", "m1b4s", "m1b2s", "m1b1u", "m1b2u", "m2b4u", "m3b2u", "m3b4u"): - self.assertIn('"fg_net2_mconv_%s_z"' % v, cpp) - self.assertIn("case kN2%s: return kN2z%s;" % (v, v), cpp) - self.assertIn('"fg_net2_mconv_h3b1u_z"', cpp) - self.assertIn('"fg_net2_mconv_h3b1u_s3_z"', cpp) - - def test_slice_addressing_is_the_frames_own_bank(self): - # frame f of a batch records into bank f (stride bytes after bank f - 1), the slice adds z * stride to the banked - # pointers: the address is the frame's own, in 32-bit arithmetic like the shader's - stride = 0x1200000 - for f in range(5): - for ptr in (0x400, 0x7FFFF00, 0xEF000000): - own = (ptr + f * stride) & 0xFFFFFFFF - z = f - self.assertEqual(own, (ptr + z * stride) & 0xFFFFFFFF) - - -if __name__ == "__main__": - unittest.main() +# SPDX-License-Identifier: MIT +"""CPU proofs of the exactness arguments behind frame generation's Wave 2 kernels (the fuse2 bits 64 .. 1024): +A15 fg_lite_fill16_p2, A16 the bilinear row loads (FG_BIL128), A17 the light blend's 32 x 8 tiles with pair stores +(FG_TILE) and the output pull's division skip (FGP_POW2), A18 the z-sliced net2 convolutions (FG_ZB). Each class restates +what the Wave 1B kernel computes and what the Wave 2 kernel computes, as the HLSL does, and compares them on random and +edge inputs; the kernels themselves are checked on a GPU by test_fg_d3d12_e2e --gpu --only turbo (every lever on against +every lever off, default mask 2047).""" +import re +import unittest +from fractions import Fraction +from pathlib import Path + +import numpy as np + +F32 = np.float32 +DX12 = Path(__file__).resolve().parents[2] / "dx12" +RUNTIME = Path(__file__).resolve().parents[1] / "runtime" + + +def _text(rel): + return (DX12 / rel).read_text() + + +def _kernel_lines(text): + return [l for l in text.splitlines() if l.startswith("// @wg-kernel ")] + + +def _decl(line): + m = re.match(r"// @wg-kernel (\S+) (.*)$", line) + d = {"name": m.group(1)} + for tok in m.group(2).split(): + k, v = tok.split("=", 1) + d[k] = v + return d + + +def _function_text(text, signature): + start = text.index(signature) + open_ = text.index("{", start) + depth, i = 0, open_ + while True: + if text[i] == "{": + depth += 1 + elif text[i] == "}": + depth -= 1 + if depth == 0: + return text[start:i + 1] + i += 1 + + +# ---- A15: fg_lite_fill16_p2 ----------------------------------------------------------------------------------------------- +def fill_old(n16, period, p): + """fg_lite_fill16: unit i = p[i % period]; each lane writes 8 units (one 16-byte store when all 8 are inside).""" + out = np.zeros(n16, dtype=np.uint16) + for lane in range((n16 + 7) // 8): + first = lane * 8 + if first + 8 <= n16: + for j in range(8): + out[first + j] = p[(first + j) % period] & 0xFFFF + else: + for i in range(first, n16): + out[i] = p[i % period] & 0xFFFF + return out + + +def fill_new(n16, period, p): + """fg_lite_fill16_p2: the same word for every full lane, the tail by i & (period - 1).""" + u0 = p[0] & 0xFFFF + u1 = (p[0] if period == 1 else p[1]) & 0xFFFF + u2 = (p[2] if period == 4 else p[0]) & 0xFFFF + u3 = (p[0] if period == 1 else (p[3] if period == 4 else p[1])) & 0xFFFF + lo, hi = u0 | (u1 << 16), u2 | (u3 << 16) + word = (lo, hi, lo, hi) + out = np.zeros(n16, dtype=np.uint16) + for lane in range((n16 + 7) // 8): + first = lane * 8 + assert first % 8 == 0 + if first + 8 <= n16: + for j in range(8): + out[first + j] = (word[j // 2] >> (16 * (j % 2))) & 0xFFFF + else: + for i in range(first, n16): + out[i] = p[i & (period - 1)] & 0xFFFF + return out + + +class FillP2Test(unittest.TestCase): + def test_same_units_for_every_period_and_size(self): + rng = np.random.default_rng(15) + for period in (1, 2, 4): + for n16 in list(range(1, 40)) + [255, 256, 2047, 2048, 2049, 4097]: + for _ in range(3): + p = [int(v) for v in rng.integers(0, 1 << 32, size=4, dtype=np.uint64)] # the high bits are masked + np.testing.assert_array_equal(fill_old(n16, period, p), fill_new(n16, period, p), + err_msg="period %d n16 %d" % (period, n16)) + + def test_the_runtime_patterns(self): + # every Fill16 the executor records: clear {1.0}, clear {0,0,0,1}, a word as two units, fill64 (0xFFFF, 0x7FFF) + for period, p in ((1, [0x3C00, 0, 0, 0]), (4, [0, 0, 0, 0x3C00]), (2, [0xFFFF, 0x7FFF, 0, 0]), (2, [0, 0, 0, 0]), + (1, [0x5A5A] * 4)): + for n16 in (1, 2, 3, 7, 8, 9, 2457600, 1 << 20): + if n16 > 5000: + n16 = n16 % 5000 + 3 + np.testing.assert_array_equal(fill_old(n16, period, p), fill_new(n16, period, p)) + + def test_the_new_kernel_has_no_division(self): + text = _text("kernels/fg_lite_util.hlsl") + body = _function_text(text, "WG_KERNEL(fg_lite_fill16)") # the first one is the FG_FILL_P2 branch + self.assertIn("#if FG_FILL_P2", text) + p2 = text[text.index("#if FG_FILL_P2"):text.index("#else", text.index("#if FG_FILL_P2"))] + self.assertNotIn("%", p2.replace("// ", "//"), "no modulo in the FG_FILL_P2 kernel") + self.assertNotIn(" / ", re.sub(r"//.*", "", p2)) + self.assertIn("fg_lite_fill16_p2", text) + self.assertTrue(body) + + def test_first_is_a_multiple_of_eight(self): + # first = (block * 256 + lane) * 8: the units of a lane start at a multiple of 8, so unit j of the lane has + # i & (period - 1) == j & (period - 1) for every period that divides 8 + for first in range(0, 8 * 600, 8): + for period in (1, 2, 4): + for j in range(8): + self.assertEqual((first + j) % period, j & (period - 1)) + + +# ---- A16: bilinear row loads ---------------------------------------------------------------------------------------------- +def _tap_axis(t, n): + """fgf_tap / fg_read_linear: x0, x1 for the texel position t on an axis of n texels.""" + x0f = np.floor(F32(t)) + xi = int(np.clip(int(x0f), -1, n - 1)) + return max(xi, 0), min(xi + 1, n - 1) + + +class BilinearRowLoadTest(unittest.TestCase): + def test_second_texel_is_the_next_one_or_the_same(self): + rng = np.random.default_rng(16) + for n in (1, 2, 3, 5, 16, 17, 1920, 2560): + ts = list(rng.uniform(-3.0, n + 3.0, size=400)) + [-0.5, 0.0, n - 1.0, n - 0.5, n - 1e-4, float(n), -1e-9] + for t in ts: + x0, x1 = _tap_axis(t, n) + self.assertIn(x1 - x0, (0, 1), "n=%d t=%r" % (n, t)) + self.assertGreaterEqual(x0, 0) + self.assertLessEqual(x1, n - 1) + + def test_row_load_gives_the_four_load_texels(self): + # a buffer of 8-byte texels (W x H) with distinct values; the row load reads the texel at i00 and the one after it + # (zero past the end of the buffer: robust buffer access), the second texel is the loaded one unless x1 == x0 + rng = np.random.default_rng(17) + for W, H in ((1, 1), (1, 5), (2, 2), (5, 3), (17, 9), (64, 4)): + tex = rng.integers(1, 1 << 63, size=W * H, dtype=np.uint64) + + def row_load(i): + return int(tex[i]), (int(tex[i + 1]) if i + 1 < W * H else 0) + + for _ in range(300): + tx, ty = rng.uniform(-2.5, W + 2.5), rng.uniform(-2.5, H + 2.5) + x0, x1 = _tap_axis(tx, W) + y0, y1 = _tap_axis(ty, H) + i00, i10, i01, i11 = y0 * W + x0, y0 * W + x1, y1 * W + x0, y1 * W + x1 + a0, a1 = row_load(i00) + b0, b1 = row_load(i01) + got = (a0, a1 if i10 != i00 else a0, b0, b1 if i11 != i01 else b0) + want = (int(tex[i00]), int(tex[i10]), int(tex[i01]), int(tex[i11])) + self.assertEqual(got, want, "W=%d H=%d tap (%r, %r)" % (W, H, tx, ty)) + + def test_two_half_texels_the_same_way(self): + rng = np.random.default_rng(18) + for W, H in ((1, 3), (2, 2), (9, 4), (33, 7)): + tex = rng.integers(1, 1 << 31, size=W * H, dtype=np.uint64) + for _ in range(300): + tx, ty = rng.uniform(-2.5, W + 2.5), rng.uniform(-2.5, H + 2.5) + x0, x1 = _tap_axis(tx, W) + y0, y1 = _tap_axis(ty, H) + i00, i10, i01, i11 = y0 * W + x0, y0 * W + x1, y1 * W + x0, y1 * W + x1 + a = (int(tex[i00]), int(tex[i00 + 1]) if i00 + 1 < W * H else 0) + b = (int(tex[i01]), int(tex[i01 + 1]) if i01 + 1 < W * H else 0) + got = (a[0], a[1] if i10 != i00 else a[0], b[0], b[1] if i11 != i01 else b[0]) + self.assertEqual(got, (int(tex[i00]), int(tex[i10]), int(tex[i01]), int(tex[i11]))) + + def test_blend_arithmetic_is_untouched(self): + # the mix is the same call on the same four values; the _b code only changes where the values come from + full = _text("hlsl/fg_full.hlsli") + self.assertEqual(full.count("return fgf_mix4(t, fgf_unpack4h(a.xy), fgf_unpack4h(c10), fgf_unpack4h(b.xy), fgf_unpack4h(c11));"), 1) + self.assertEqual(full.count("return fgf_mix2(t, fgf_unpack2h(a.x), fgf_unpack2h(c10), fgf_unpack2h(b.x), fgf_unpack2h(c11));"), 1) + lite = _text("hlsl/fg_lite_common.hlsli") + tail = lite[lite.index("float4 fg_read_linear("):] + self.assertIn("float4 r0 = mad(ax.xxxx, t10 - t00, t00);", tail) + self.assertIn("return mad(ay.xxxx, r1 - r0, r0);", tail) + + def test_every_variant_is_declared_and_defaults_to_off(self): + for rel, base, variants in ( + ("kernels/fg_lite_blend.hlsl", "fg_lite_blend", ("fg_lite_blend_b", "fg_lite_blend_pack_b", "fg_lite_blend_bt", "fg_lite_blend_pack_bt")), + ("kernels/fg_full_blend.hlsl", "fg_full_blend", ("fg_full_blend_b", "fg_full_blend_merge_b")), + ("kernels/fg_out_pull.hlsl", "fg_out_pull", ("fg_out_pull_b", "fg_out_pull_pack_b", "fg_out_pull_bq", "fg_out_pull_pack_bq")), + ("kernels/fg_lite_g.hlsl", "fg_lite_weights", ("fg_lite_weights_b",)), + ): + decls = {d["name"]: d for d in map(_decl, _kernel_lines(_text(rel)))} + for v in variants: + self.assertIn(v, decls) + self.assertIn("FG_BIL128=1", decls[v]["defines"]) + self.assertNotIn("FG_BIL128", decls[base].get("defines", "")) + self.assertIn("#define FG_BIL128 0", _text("hlsl/fg_full.hlsli")) + self.assertIn("#define FG_BIL128 0", _text("hlsl/fg_lite_common.hlsli")) + + +# ---- A17: 32 x 8 tiles with pair stores ----------------------------------------------------------------------------------- +def _tile_map(wo, ho): + tiles_x = (wo + 31) >> 5 + n_tiles = tiles_x * ((ho + 7) // 8) + seen = {} + stores = {} + for tile in range(n_tiles): + tile_y = tile // tiles_x + for lane in range(256): + xr = ((tile - tile_y * tiles_x) << 5) + (lane & 31) + yr = (tile_y << 3) + (lane >> 5) + live = xr < wo and yr < ho + x, y = min(xr, wo - 1), min(yr, ho - 1) + if live: + seen[(x, y)] = seen.get((x, y), 0) + 1 + # the pair store: the even lane of a quad pair stores both pixels (its partner is the next lane, x + 1) + if live and (xr & 1) == 0: + if x + 1 < wo: + stores[(x, y)] = stores.get((x, y), 0) + 1 + stores[(x + 1, y)] = stores.get((x + 1, y), 0) + 1 + else: + stores[(x, y)] = stores.get((x, y), 0) + 1 + return seen, stores + + +class LiteBlendTileTest(unittest.TestCase): + def test_every_pixel_once_and_stored_once(self): + for wo, ho in ((1, 1), (2, 3), (31, 9), (32, 8), (33, 17), (64, 8), (100, 37), (127, 5), (640, 360)): + seen, stores = _tile_map(wo, ho) + want = {(x, y) for x in range(wo) for y in range(ho)} + self.assertEqual(set(seen), want, "%dx%d covered" % (wo, ho)) + self.assertTrue(all(v == 1 for v in seen.values()), "%dx%d no pixel twice" % (wo, ho)) + self.assertEqual(set(stores), want, "%dx%d stored" % (wo, ho)) + self.assertTrue(all(v == 1 for v in stores.values()), "%dx%d no pixel stored twice" % (wo, ho)) + + def test_the_grid_is_not_smaller_than_the_scanline_grid(self): + for wo, ho in ((2560, 1440), (1920, 1080), (3840, 2160), (1366, 768), (7, 3)): + tiles = ((wo + 31) >> 5) * ((ho + 7) // 8) + self.assertGreaterEqual(tiles * 256, wo * ho) + self.assertEqual(((2560 + 31) >> 5) * ((1440 + 7) // 8), (2560 * 1440 + 255) // 256) # 14400 both ways at 1440p + + def test_a_quad_pair_is_a_horizontal_pair(self): + # a wave is one tile row (lane & 31 = x offset, lane >> 5 = row) and QuadReadAcrossX swaps lane with lane ^ 1 + for lane in range(256): + partner = lane ^ 1 + self.assertEqual(lane >> 5, partner >> 5) + self.assertEqual((lane & 31) ^ 1, partner & 31) + + def test_the_kernel_is_declared_and_division_free_per_pixel(self): + decls = {d["name"]: d for d in map(_decl, _kernel_lines(_text("kernels/fg_lite_blend.hlsl")))} + for v in ("fg_lite_blend_t", "fg_lite_blend_pack_t", "fg_lite_blend_bt", "fg_lite_blend_pack_bt"): + self.assertIn("FG_TILE=1", decls[v]["defines"]) + text = _text("kernels/fg_lite_blend.hlsl") + tile = text[text.index("#elif FG_TILE"):text.index("#else", text.index("#elif FG_TILE"))] + self.assertEqual(len(re.findall(r"(? a: + e -= 1 + elif Fraction(2) ** (e + 1) <= a: + e += 1 + e = max(e, -126) + q = Fraction(2) ** (e - 23) + n = a / q + k = n.numerator // n.denominator + rem = n - k + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and k % 2 == 1): + k += 1 + v = float(k * q) + return F32(-v if neg else v) + + +def _fma(a, b, c): + a, b, c = float(a), float(b), float(c) + exact = Fraction(a) * Fraction(b) + Fraction(c) + if exact == 0: + neg = (np.signbit(a) != np.signbit(b)) and np.signbit(c) and (a * b == 0) # -0 only for (-0) + (-0) + return F32(-0.0) if neg else F32(0.0) + return _round32(exact) + + +def _mul(a, b): + return _fma(a, b, -0.0) + + +def _rcp(b): + return _round32(Fraction(1) / Fraction(float(b))) # v_rcp_f32 is exact on powers of two + + +def div_reciprocal(b): + y = _rcp(b) + return _fma(_fma(-b, y, 1.0), y, y) + + +def div_normal(a, b, y): + q = _mul(a, y) + q = _fma(_fma(-b, q, a), y, q) + return _fma(_fma(-b, q, a), y, q) + + +def level_old(a, w, m): + den = max(F32(w), F32(1.0)) + rgb = div_normal(a, den, div_reciprocal(den)) + return a if a == 0 else rgb + + +def level_new(a, w, m): + scale = F32(np.uint32((127 - 2 * m) << 23).view(F32)) + rgb = _mul(a, scale) + if F32(w) != F32(1 << (2 * m)): + raise AssertionError("the division branch is the old code") + return a if a == 0 else rgb + + +class PullPow2Test(unittest.TestCase): + def test_division_by_a_power_of_two_is_the_scale(self): + rng = np.random.default_rng(19) + samples = [F32(0.0), F32(-0.0), F32(1.0), F32(0.5), F32(1e-30), F32(1e-38), F32(1.4e-45), F32(1.17549435e-38), + F32(0.9999999), F32(3.0e-39)] + samples += [F32(v) for v in rng.uniform(0.0, 1.0, size=200)] + samples += [F32(v) for v in 10.0 ** rng.uniform(-45, 0, size=200)] + samples += [F32(v) * F32(16) for v in rng.uniform(0.0, 1.0, size=50)] # sums of 16 saturated values + for m in range(0, 5): + w = 1 << (2 * m) + for a in samples: + old = level_old(a, w, m) + new = level_new(a, w, m) + self.assertEqual(np.asarray(old, dtype=F32).view(np.uint32), np.asarray(new, dtype=F32).view(np.uint32), + "m=%d a=%r" % (m, a)) + + def test_the_condition_is_exactly_the_power_of_two(self): + # den = max(w, 1) is w itself for w = 4^m, so the reciprocal is exact; any other weight takes the division + for m in range(0, 5): + self.assertEqual(max(F32(1 << (2 * m)), F32(1.0)), F32(1 << (2 * m))) + self.assertEqual(div_reciprocal(F32(1 << (2 * m))), F32(2.0 ** (-2 * m))) + + def test_declared_and_off_by_default(self): + decls = {d["name"]: d for d in map(_decl, _kernel_lines(_text("kernels/fg_out_pull.hlsl")))} + for v in ("fg_out_pull_q", "fg_out_pull_pack_q", "fg_out_pull_bq", "fg_out_pull_pack_bq"): + self.assertIn("FGP_POW2=1", decls[v]["defines"]) + self.assertNotIn("FGP_POW2", decls["fg_out_pull"].get("defines", "")) + self.assertNotIn("FGP_POW2", decls["fg_out_pull_pack"].get("defines", "")) + self.assertIn("#define FGP_POW2 0", _text("kernels/fg_out_pull.hlsl")) + + +# ---- A18: z-sliced net2 convolutions ---------------------------------------------------------------------------------------- +class ZSliceTest(unittest.TestCase): + def setUp(self): + self.decls = [_decl(l) for l in _kernel_lines(_text("kernels/fg_net2_mconv.hlsl"))] + + def test_every_plain_convolution_has_a_z_twin(self): + base = {d["name"]: d for d in self.decls if d.get("entry") == "fg_net2_mconv" and "FG_PAIR" not in d.get("defines", "") + and "FG_UPWARP_STAGE" not in d.get("defines", "") and not d["name"].endswith("_z")} + z = {d["name"]: d for d in self.decls if d["name"].endswith("_z")} + for name, d in base.items(): + if name == "fg_net2_mconv_h3b2u": # not launched by the executor + continue + self.assertIn(name + "_z", z, name) + t = z[name + "_z"] + self.assertEqual(t["args"], d["args"] + ",u,u") # zstride, zmask + self.assertEqual(t["block"], d["block"]) + self.assertEqual(t["defines"], d["defines"] + ",FG_ZB=1,WG_Z_GRID=1") + # the originals (and what their checkers launch) are unchanged + for name, d in base.items(): + self.assertNotIn("FG_ZB", d.get("defines", "")) + self.assertNotIn("WG_Z_GRID", d.get("defines", "")) + + def test_the_pointer_order_matches_the_mask_bits(self): + text = _text("kernels/fg_net2_mconv.hlsl") + decl = re.search(r"uint a_x, a_wf, a_b, a_y, a_skip, a_y1, a_y2, a_skip1, a_skip2;", text) + self.assertTrue(decl) + setup = text[text.index("#define FG_ZB_SETUP()"):text.index("#else", text.index("#define FG_ZB_SETUP()"))] + order = ["x", "wf", "b", "y", "skip", "y1", "y2", "skip1", "skip2"] + for bit, name in enumerate(order): + self.assertIn("%s = a_%s + ((zmask & %du) != 0u ? zo_ : 0u)" % (name, name, 1 << bit), setup) + + def test_the_executor_maps_every_executor_variant(self): + cpp = (RUNTIME / "fg_d3d12_executor.cpp").read_text() + for v in ("m1b1", "m1b2", "m2b1", "m2b2", "m2b4", "m1b4s", "m1b2s", "m1b1u", "m1b2u", "m2b4u", "m3b2u", "m3b4u"): + self.assertIn('"fg_net2_mconv_%s_z"' % v, cpp) + self.assertIn("case kN2%s: return kN2z%s;" % (v, v), cpp) + self.assertIn('"fg_net2_mconv_h3b1u_z"', cpp) + self.assertIn('"fg_net2_mconv_h3b1u_s3_z"', cpp) + + def test_slice_addressing_is_the_frames_own_bank(self): + # frame f of a batch records into bank f (stride bytes after bank f - 1), the slice adds z * stride to the banked + # pointers: the address is the frame's own, in 32-bit arithmetic like the shader's + stride = 0x1200000 + for f in range(5): + for ptr in (0x400, 0x7FFFF00, 0xEF000000): + own = (ptr + f * stride) & 0xFFFFFFFF + z = f + self.assertEqual(own, (ptr + z * stride) & 0xFFFFFFFF) + + +if __name__ == "__main__": + unittest.main() diff --git a/clean/k/runtime/k_smx_selfcheck.h b/clean/k/runtime/k_smx_selfcheck.h index c6085970..f16679aa 100644 --- a/clean/k/runtime/k_smx_selfcheck.h +++ b/clean/k/runtime/k_smx_selfcheck.h @@ -8,7 +8,7 @@ namespace k_smx_selfcheck { -constexpr char kSourceDigest[] = "c7a083f24edaa314370dd3d27ce234398ceae9148942e6ee9d3bb9506d72d474"; +constexpr char kSourceDigest[] = "bada004b44ecbb91d0cac9e2256b510da2602e03bfa72c3b6b0a89f63cad92e0"; constexpr int kCount = 133; constexpr const char* kNames[kCount] = { "k_stage_e2@512x384/o4,4",