diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f51c91cb..4728fb25 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,12 +59,30 @@ jobs: cmake -S clean/converter -B out/converter -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded cmake --build out/converter ctest --test-dir out/converter --output-on-failure + - name: Frame generation game adapter, Win32 transport and title bindings + run: | + $PSNativeCommandUseErrorActionPreference = $true + cmake -S clean/fg/proxy -B out/fg-proxy -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded + cmake --build out/fg-proxy + ctest --test-dir out/fg-proxy --output-on-failure - name: Shared settings run: | $PSNativeCommandUseErrorActionPreference = $true cmake -S clean/wgshared -B out/wgshared -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded cmake --build out/wgshared ctest --test-dir out/wgshared --output-on-failure + - name: Frame generation presenter, scheduler and Windows back ends (CPU tests) + run: | + $PSNativeCommandUseErrorActionPreference = $true + cmake -S clean/fg/presenter -B out/fg-presenter -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded + cmake --build out/fg-presenter + ctest --test-dir out/fg-presenter --output-on-failure + - name: Frame generation runtime and session + run: | + $PSNativeCommandUseErrorActionPreference = $true + cmake -S clean/fg/runtime -B out/fg-runtime -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded + cmake --build out/fg-runtime + ctest --test-dir out/fg-runtime --output-on-failure frontend: name: "CPU: FSR front end" @@ -117,8 +135,8 @@ jobs: run: | $PSNativeCommandUseErrorActionPreference = $true cmake -S clean/installer -B out/launcher-tests -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded -DWRONGGPU_PAYLOAD_DIR="$PWD/out/no-payload" -DWRONGGPU_TESTING=OFF -DWRONGGPU_PRESET_K=OFF -DWRONGGPU_DIRECT_ROUTE=OFF - cmake --build out/launcher-tests --target wg-core-tests launcher-core-tests coexist-core-tests convert-ignore-tests model-choice-tests model-choice-k-tests model-choice-k-only-tests - ctest --test-dir out/launcher-tests --output-on-failure -R "^(wg-core|launcher-core|coexist-core|convert-ignore|model-choice|model-choice-k|model-choice-k-only|source-size|wording)$" + cmake --build out/launcher-tests --target wg-core-tests launcher-core-tests coexist-core-tests convert-ignore-tests model-choice-tests model-choice-k-tests model-choice-k-only-tests fg-choice-tests + ctest --test-dir out/launcher-tests --output-on-failure -R "^(wg-core|launcher-core|coexist-core|convert-ignore|model-choice|model-choice-k|model-choice-k-only|fg-choice|source-size|wording)$" - name: Test launcher from the test suite's stand-in payload (and a release build refusing it) run: | $PSNativeCommandUseErrorActionPreference = $true @@ -177,8 +195,8 @@ jobs: run: | $PSNativeCommandUseErrorActionPreference = $true cmake -S clean/installer -B out/launcher-models -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_POLICY_DEFAULT_CMP0091=NEW -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded -DWRONGGPU_PAYLOAD_DIR="$PWD/out/no-payload" -DWRONGGPU_TESTING=OFF -DWRONGGPU_PRESET_K=ON -DWRONGGPU_MODEL_K=ON -DWRONGGPU_MODEL_L=ON -DWRONGGPU_DIRECT_ROUTE=OFF - cmake --build out/launcher-models --target wg-core-tests launcher-core-tests coexist-core-tests convert-ignore-tests model-choice-tests model-choice-k-tests model-choice-k-only-tests - ctest --test-dir out/launcher-models --output-on-failure -R "^(wg-core|launcher-core|coexist-core|convert-ignore|model-choice|model-choice-k|model-choice-k-only|source-size|wording)$" + cmake --build out/launcher-models --target wg-core-tests launcher-core-tests coexist-core-tests convert-ignore-tests model-choice-tests model-choice-k-tests model-choice-k-only-tests fg-choice-tests + ctest --test-dir out/launcher-models --output-on-failure -R "^(wg-core|launcher-core|coexist-core|convert-ignore|model-choice|model-choice-k|model-choice-k-only|fg-choice|source-size|wording)$" - name: Payload packager and package check refuse a developer runtime (R1) # The packager (clean/installer/tools/make_payload.py) runs clean/tests/check_no_dev_diagnostics.py on every runtime # library it embeds and refuses the payload for dev-diagnostics=1 or a missing marker; tools/release runs the same diff --git a/clean/FORMATS.md b/clean/FORMATS.md index 75d6af0d..9a6829f9 100644 --- a/clean/FORMATS.md +++ b/clean/FORMATS.md @@ -422,6 +422,7 @@ frame. | post (fused) | `post_kernel` | `WG_POST_KERNEL` | — | `post_fused*`, `post_fused3*`: reconstruction + filter in one launch (no display image; history 6 or 4 bytes, `_o16` RGBA16F output — refused for an external output unless `FrameIo.out_rgba16f`, and with pre-exposure ≠ 1) | | filter | `filter_kernel` | `WG_FILTER_KERNEL` | `post_filter_c1_s4_band` (with the banded default; else `post_filter_c1_s4`) | `post_filter[_c1][_s4\|_s16]` | | post (true fusion) | runtime options `post_tf`, `post_tf_cpairs` | `WG_POST_TF=0` (or `WG_RUNTIME_OPTIONS=post_tf=0`) | on: frames of the default banded pack12 path (post kernels in wave64, default filter) that `tf_supported` takes run one `post_tf_p12` / `post_tf_dl_p12` launch (interop output copy: RGBA16F rows, π folded in) or `post_tf_f32_p12` / `post_tf_dl_f32_p12` (3 × f32, then `scale_rgb` when π ≠ 1); C = 68 output row pairs per workgroup, 36 for the last dispatch round | `post_tf=0`: the banded sequence; `post_tf_cpairs=`; reported as `post_tf=` and `post_last` | +| scale_rgb fold (native D3D12) | runtime option `scale_fold` | `WG_SCALE_FOLD=0` (or `WG_RUNTIME_OPTIONS=scale_fold=0`) | on: staged buffers (not raw / direct / Model L / interop output copy) on the `post_tf_f32_p12_diet_vsit` / `post_tf4_dl_*` / `pmo/post_tf_*_mo` route with π ≠ 1: `scale_rgb` is done by the post kernel's store (its π argument; `native_scale`'s values), one launch fewer, the same bytes | `scale_fold=0`: `scale_rgb` after the post | Both spec 06 kernels take an extra last argument `expo`: a pointer to the exposure pair. When it is not null (the runtime), they derive e, e_prev, e/e_prev and 0.01/e from it on the GPU (0 → 1, the quotients via binary64 then diff --git a/clean/PERF.md b/clean/PERF.md index 83ca27b8..9a830156 100644 --- a/clean/PERF.md +++ b/clean/PERF.md @@ -65,11 +65,17 @@ written). The clean team has no GPU, but clang 18 here compiles the kernels for gfx1201, so the instruction mix of every build can be counted (static count per lane; the kernels are fully unrolled, so this is close to the dynamic count). -Cost model from the spec team's measurements (perf-targets, "Vector unit and overlap"): a stage takes its matrix time -plus its vector time; one vector instruction per wave per cycle, a transcendental (`v_exp_f32`, `v_log_f32`) about -4 times an FMA. Below, **cost = VALU instructions + 4 × transcendentals per lane** (a lane of enc0 or dec0 handles 2 -pixels). The same compile-time switches that remove one part of the work (ablations) are built for the GPU, so the -spec team can measure what each part really costs (`perf_variants.py`). +Cost model note (verified 2026-11-23 on RX 9070 XT `gfx1201`): pure WMMA and VALU (both FMA and TRANS `v_exp_f32`) +**serialize per SIMD** — both within a single wave (cycle counter: 8× FP8 WMMA = 64 cyc, 8×32 FMA = 286 cyc, +interleaved = 354 cyc; 8×8 `v_exp_f32` = 283 cyc, interleaved = 349 cyc) and across split waves on the same SIMD. +What **does** overlap with WMMA on `gfx1201` is **SALU** (`~0.9`), **VMEM** global loads / LUT gathers (`~0.37`), and +**LDS** latency (`~0.085`), plus higher wave occupancy (e.g. cutting LDS from 32 KiB → 16 KiB to go from 2 → 3 WGs/CU) +which hides VMEM/LDS/barrier stalls across resident waves. (Note: running `overlap_probe.py` in fixed un-interleaved +order without warmup allows GPU boost clocks to ramp ~40% mid-run and produces false positive overlap; interleaving +launch order shows `ov_mma + ov_valu32 ≈ ov_mix32` within every round.) For `enc0`/`dec0` estimation below, +**cost = VALU instructions + 4 × transcendentals per lane** (a lane of enc0 or dec0 handles 2 pixels). The same +compile-time switches that remove one part of the work (ablations) are built for the GPU, so the spec team can measure +what each part really costs (`perf_variants.py`). Version 1 (as measured: 0.331 ms) at that cost model: 3739 per lane, i.e. about 0.28 ms of vector issue at full occupancy plus about 0.02 ms of WMMA (6.8 GFLOP at 372 TFLOPS); the kernel was vector-bound. Where it went: diff --git a/clean/dx12/README.md b/clean/dx12/README.md index 35330d61..8c1ded32 100644 --- a/clean/dx12/README.md +++ b/clean/dx12/README.md @@ -20,7 +20,7 @@ as its HIP kernel (`clean/dx12/compare.py` proves it per kernel on synthetic fra | `dxil_asm.cpp` | tool used by the build (assembles the rewritten DXIL listing) | | `compare.py` | HIP vs hybrid D3D12, every stage output / state buffer byte for byte | | `kernels/exposure.hlsl` | the reference port (`exposure_auto_diet`): copy its structure | -| `kernels/fg_*.hlsl` | frame generation's ports (#96, `co=fg_*.co`): groundwork, built only when `--only` names them, never by a full build (`is_frame_gen`), so the Model M / Model L sets stay as they are; checks: `clean/fg/runner/fg_d3d12_check.py` (each kernel), `clean/fg/runner/fg_net1_gpu.py` (net1's 32 steps as a `kernel_replay` chain), `clean/fg/runner/fg_net1_mma.py` (net1's fast path on the matrix instructions, fused / unfused / exact) | +| `kernels/fg_*.hlsl` | frame generation's ports (#96, `co=fg_*.co`): groundwork, built only when `--only` names them, never by a full build (`is_frame_gen`), so the Model M / Model L sets stay as they are; checks: `clean/fg/runner/fg_d3d12_check.py` (each kernel), `clean/fg/runner/fg_net1_gpu.py` (net1's 32 steps as a `kernel_replay` chain), `clean/fg/runner/fg_net1_mma.py` (net1's fast path on the matrix instructions, fused / unfused / exact), `clean/fg/runner/fg_full_stages_d3d12_check.py` (the Full path's stage kernels `fg_full_blend`, `fg_out_*`, `fg_dist_*` against the CPU reference, each kernel, the chained stages and full-size frames), `clean/fg/runner/fg_net2_d3d12_check.py` (net2's exact kernels `fg_net2_*` against the CPU reference, each kernel and the whole network) | | `tests/kernel_replay.cpp` | replays launches from a case file on the native D3D12 device; `chain` blocks run several launches on buffers that persist between them (a whole network, optionally timed) | ## Arithmetic mode (why build_dx12.py and nothing else) @@ -128,6 +128,13 @@ WG_KERNEL(exposure_auto_diet) { WG_SETUP(); ... } // entry name = HIP kernel n * `args` = the HIP kernel's arguments in order: `p` pointer (DWORD: arena byte offset), `u` any 32-bit scalar, `b` struct by value (N bytes = N/4 DWORDs, copied verbatim). At most 57 DWORDs. The `WG_ARGS_BEGIN` block must declare exactly these DWORDs in order, **32-bit scalars only** (no vectors / arrays / structs: cbuffer packing). +* A kernel named `_fast` is Model L's `l_mode=fast` twin of `` (clean/l/SPEED.md "Fast mode"): the runtime + launches it in place of the base kernel with the same arguments when the build has it, so it declares the same `args`; it + is built with `--model-l` only (`is_model_l`), has no HIP twin (`co=-`), keeps the base kernel's DXIL untouched, and the + hybrid route never launches it. Its arithmetic is not bit-exact to the reference by design (the hybrid route is). + `_fast3` (the 3 x 3 post) and `_w2p_fast` / `_w2t_fast` (two windows per wave, in place of + `_nc`; `group=128 gscale=1`, the device's launch of the same grid) are fast-mode kernels too (`build_dx12.py + fast_base` names the kernel each one replaces). * Output: `/dx12/__.dxil` (`.dxil` without a tag) and a `manifest.json` line `{"name", "file", "co", "entry", "block", "wave", "args", "arg_dwords", "source", "sha256"}`. Build all kernels at once (no `--only`) for a release: `--only` rewrites the shared manifest read-modify-write. diff --git a/clean/dx12/build_dx12.py b/clean/dx12/build_dx12.py index 3781dcd4..7ed7ebe5 100644 --- a/clean/dx12/build_dx12.py +++ b/clean/dx12/build_dx12.py @@ -32,7 +32,8 @@ and rcp() (fdiv 1.0, x) is the hardware v_rcp_f32; it is reassembled (dxil_asm.cpp, DXC's IDxcAssembler) and signed by dxv. Any other float division ('/', which would be an IEEE division) or float remainder is refused: use wg_div. -VGPR check: every Swin / bottleneck kernel built (a name with a swin_ or l_swin_ part) is run through RGA (gfx1201) and its +VGPR check: every Swin / bottleneck kernel built (a name with a swin_ or l_swin_ part, and Model L's fused post +w64_lc12/l_post_tf_p12[_pf][_fast|_fast3]) is run through RGA (gfx1201) and its USED_VGPRs compared with its bound in clean/dx12/vgpr_limits.json (the count that keeps its present workgroups per CU); over the bound, or no bound listed, fails the build. WG_DX12_VGPR_CHECK=0 skips it. ISA rules of the hybrid kernels: every hybrid kernel built (a name with a _hyb part) is checked in the same RGA run by @@ -226,12 +227,24 @@ def kernel_decls(path): MODEL_L_ONLY = {"swin_block_c64_add_ex_nc", "lev/input_encoder_q20", "lev/input_encoder_direct_q20"} +def fast_base(name): + """The kernel a fast-mode kernel of Model L's l_mode=fast is launched in place of (same grid, block and arguments), or + None: "_fast" and "_fast3" (the 3 x 3 post) replace ; "_w2p_fast" / "_w2t_fast" (the + two-windows-per-wave Swin blocks, l_swin_c32_fast.hlsl) replace "_nc".""" + m = re.fullmatch(r"(.+)_w2[pt]_fast", name) + if m: + return m.group(1) + "_nc" + m = re.fullmatch(r"(.+)_fast3?", name) + return m.group(1) if m else None + + def is_model_l(decl): """A port of one of Model L's code objects (#89: l_swin.co, l_ops.co, l_post.co, l_enc_values.co), a Model L kernel - of the direct route with no code object (co "-", named l_*), a kernel only Model L launches (MODEL_L_ONLY), or a - kernel of the hybrid form (named *_hyb: WG_L_FORM = hybrid, Model L's route only so far).""" + of the direct route with no code object (co "-", named l_*), a kernel only Model L launches (MODEL_L_ONLY), a kernel + of the hybrid form (named *_hyb: WG_L_FORM = hybrid, Model L's route only so far), or a fast-mode kernel (fast_base: + Model L's l_mode=fast, launched in place of the kernel it names).""" return (decl["co"].startswith("l_") or decl["name"].startswith("l_") or decl["name"] in MODEL_L_ONLY - or decl["name"].endswith("_hyb")) + or decl["name"].endswith("_hyb") or fast_base(decl["name"]) is not None) def is_frame_gen(decl): @@ -330,7 +343,8 @@ def rga_isa(dxil, isa_dir, stem): def vgpr_checked(name): - return re.search(r"(^|/|l_)swin_", name) is not None # l_swin_*: Model L's blocks (#89) + # l_swin_*: Model L's blocks (#89); l_post_tf_p12[_pf][_fast|_fast3]: Model L's fused post (bound = 96-register tier) + return re.search(r"(^|/|l_)swin_|/l_post_tf_p12(_pf)?(_fast3?)?$", name) is not None def rga_vgprs(dxil, isa=False): @@ -358,7 +372,8 @@ def hyb_scanned(name): # Model hybrid kernels with no norm tree (no square to fuse): their mutants must fail rule 2 only. -HYB_NO_NORM = {"patch_merge_c64_hyb", "patch_merge_c96_hyb", "expand_c96_hyb", "expand_c128_hyb"} +HYB_NO_NORM = {"patch_merge_c64_hyb", "patch_merge_c96_hyb", "expand_c96_hyb", "expand_c128_hyb", + "patch_merge_c64_q7c_hyb", "patch_merge_c96_q7c_hyb", "expand_c96_q7c_hyb", "expand_c128_q7c_hyb"} def scan_mutant(name): 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 new file mode 100644 index 00000000..0a708448 --- /dev/null +++ b/clean/dx12/hlsl/fg_full.hlsli @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): shared helpers of the Full path's stage kernels (clean/dx12/kernels/fg_full_blend.hlsl, +// 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 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))). +// The four weights pass through fgf_opq (an xor with a zero the compiler cannot see) so that the driver cannot regroup +// the products that share a factor with the texel values. +// - Morton order inside a 16 x 16 tile: lane bits 0, 2, 4, 6 are x, bits 1, 3, 5, 7 are y, so a lane tree with strides +// 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() (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_); } +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)); } + +// nearest texel of normalized u on an n-texel axis +int fgf_nearest(float u, int n) { return clamp((int)floor(u * (float)n), 0, n - 1); } + +uint fgf_mx(uint l) { return (l & 1u) | ((l >> 1u) & 2u) | ((l >> 2u) & 4u) | ((l >> 3u) & 8u); } +uint fgf_my(uint l) { return fgf_mx(l >> 1u); } + +// ---- texels ----------------------------------------------------------------------------------------------------------- +float4 fgf_ld4h(uint p, int i) +{ + const uint2 d = wg_ld64(p, (uint)i * 8u); + return float4(wg_h2f_lo(d.x), wg_h2f_hi(d.x), wg_h2f_lo(d.y), wg_h2f_hi(d.y)); +} +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(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; }; + +// taps of texel position (tx, ty) in a W x H image (element indices y * W + x) +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 = 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); + t.w10 = fgf_opq(fx * gy); + t.w01 = fgf_opq(fy * gx); + t.w11 = fgf_opq(fx * fy); + return t; +} + +// the same at normalized (u, v): texel position (fma(u, W, -0.5), fma(v, H, -0.5)) +FgfTap fgf_tap_uv(float u, float v, int W, int H) { return fgf_tap(mad(u, (float)W, -0.5f), mad(v, (float)H, -0.5f), W, H); } + +float4 fgf_mix4(FgfTap t, float4 c00, float4 c10, float4 c01, float4 c11) +{ + return mad(t.w11, c11, mad(t.w01, c01, mad(t.w00, c00, t.w10 * c10))); +} +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) +float4 fgf_level(float4 s, float n) +{ + const float den = max(s.w, 1e-12f); + return float4(wg_div(s.x, den), wg_div(s.y, den), wg_div(s.z, den), wg_div(s.w, n)); +} + +// The 9/3/3/1 upsample of the filled coarse level lv (wc x hc, 4 x float16) at fine element (qx, qy): (v_up rgb, w_up), +// v_up normalized by clamp(Wsum, 1e-12, 1), w_up = Wsum unclamped. The chains start from fma(., 0.5625, +0) with an +// opaque +0 (the driver would otherwise turn fma(a, b, 0) into a b, which keeps -0). +float4 fgf_up(uint lv, int wc, int hc, int qx, int qy) +{ + 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); + const float4 eP = fgf_ld4h(lv, py * wc + px), eX = fgf_ld4h(lv, py * wc + nx); + const float4 eY = fgf_ld4h(lv, ny * wc + px), eD = fgf_ld4h(lv, ny * wc + nx); + 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_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_lite_common.hlsli b/clean/dx12/hlsl/fg_lite_common.hlsli new file mode 100644 index 00000000..93568138 --- /dev/null +++ b/clean/dx12/hlsl/fg_lite_common.hlsli @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): shared helpers of the light path's D3D12 kernels (clean/dx12/kernels/fg_lite_*.hlsl). +// They compute the bits of the CPU reference clean/fg/reference/stages_common.py (its module text lists the +// conventions): rcp = the correctly rounded 1 / x (wg_div), the approximate division a * rcp(b), the own deterministic +// 2^y (floor, a degree-6 polynomial in fma form, an exact power-of-two scale), minNum / maxNum clamps, textures emulated +// on arena buffers (nearest: clamp(floor(X * W)); bilinear: fma blends of the four clamped texels around X * W - 0.5), +// application inputs read through their region with the clamp to its texel centres. +// +// Image kinds (element layout in the arena): 1 = float16, 2 = float16 x 2, 3 = float16 x 3, 4 = float16 x 4, +// 5 = float32 x 2, 6 = float32. Row-major, texel (x, y) at element y * W + x. +// +// 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" + +#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) + +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 +float fg_mul(float a, float b) { return mad(a, b, asfloat(fg_z_ | 0x80000000u)); } + +#define FG_INF asfloat(0x7f800000u) +#define FG_BIAS asfloat(0x34000000u) // 2^-23 +#define FG_NEG_LOG2E asfloat(0xBFB8AA3Bu) +#define FG_PUSH asfloat(0xC47A0000u) // -1000 +#define FG_KEY_FLOOR 1e-7f +#define FG_WEIGHT_FLOOR 1e-12f + +float fg_rcp(float x) { return wg_div(1.0f, x); } +float fg_adiv(float a, float b) { return fg_mul(a, fg_rcp(b)); } +float fg_sat(float x) { return min(max(x, 0.0f), 1.0f); } +float fg_med3(float x, float lo, float hi) { return min(max(x, lo), hi); } +bool fg_finite(float x) { return abs(x) < FG_INF; } +bool fg_finite3(float3 c) { return fg_finite(c.x) && fg_finite(c.y) && fg_finite(c.z); } +float fg_f(uint bits) { return asfloat(bits); } +int fg_sgn(float x) { return x > 0.0f ? 1 : -1; } +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) +{ + float n = floor(y); + float f = y - n; + float p = asfloat(0x396566FBu); + p = mad(p, f, asfloat(0x3AA25EA2u)); + p = mad(p, f, asfloat(0x3C1EAC13u)); + p = mad(p, f, asfloat(0x3D633F72u)); + p = mad(p, f, asfloat(0x3E75FEFCu)); + p = mad(p, f, asfloat(0x3F317214u)); + p = mad(p, f, 1.0f); + int ni = (int)n; + float sc = asfloat((uint)(clamp(ni, -126, 127) + 127) << 23); + float r = fg_mul(p, sc); + r = ni < -126 ? 0.0f : r; + r = ni > 127 ? FG_INF : r; + return isnan(y) ? y : r; +} + +// sigma(a - b) as the reference computes it +float fg_sigmoid(float a, float b) +{ + float z = a - b; + float e = fg_ex2(fg_mul(abs(z), FG_NEG_LOG2E)); + float num = a > b ? 1.0f : e; + return fg_adiv(num, e + 1.0f); +} + +float fg_luma(float3 c) +{ + return fg_sat(mad(c.z, asfloat(0x3DE978D5u), mad(c.x, asfloat(0x3E991687u), fg_mul(c.y, asfloat(0x3F1645A2u))))); +} + +// ---- image elements -------------------------------------------------------------------------------------------------- +float4 fg_texel(uint base, uint kind, uint idx) +{ + if (kind == 1u) return float4(wg_h2f(wg_ld16(base, idx * 2u)), 0.0f, 0.0f, 0.0f); + if (kind == 2u) { uint w = wg_ld32(base, idx * 4u); return float4(f16tof32(w), f16tof32(w >> 16), 0.0f, 0.0f); } + if (kind == 3u) + return float4(wg_h2f(wg_ld16(base, idx * 6u)), wg_h2f(wg_ld16(base, idx * 6u + 2u)), + wg_h2f(wg_ld16(base, idx * 6u + 4u)), 0.0f); + if (kind == 4u) + { + uint2 w = wg_ld64(base, idx * 8u); + return float4(f16tof32(w.x), f16tof32(w.x >> 16), f16tof32(w.y), f16tof32(w.y >> 16)); + } + if (kind == 5u) { uint2 w = wg_ld64(base, idx * 8u); return float4(asfloat(w.x), asfloat(w.y), 0.0f, 0.0f); } + 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, 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, 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(fg_pack_h2(a.x, a.y), fg_pack_h2(a.z, a.w))); +} + +// integer read at (x, y), clamped +float4 fg_read_int(uint base, uint kind, int w, int h, int x, int y) +{ + return fg_texel(base, kind, (uint)(clamp(y, 0, h - 1) * w + clamp(x, 0, w - 1))); +} + +int fg_nearest_index(float X, int n) { return clamp((int)floor(X * (float)n), 0, n - 1); } + +float4 fg_read_nearest(uint base, uint kind, int w, int h, float X, float Y) +{ + return fg_texel(base, kind, (uint)(fg_nearest_index(Y, h) * w + fg_nearest_index(X, w))); +} + +float4 fg_read_linear(uint base, uint kind, int w, int h, float X, float Y) +{ + float px = mad(X, (float)w, -0.5f), py = mad(Y, (float)h, -0.5f); + float fx = floor(px), fy = floor(py); + 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); +} + +// ---- regions of application inputs ------------------------------------------------------------------------------- +struct FgRegion { float ew, eh, bx, by, rx, ry, lox, hix, loy, hiy; }; +#define FG_REGION_ARGS(p) uint p##_ew, p##_eh, p##_bx, p##_by, p##_rx, p##_ry, p##_lox, p##_hix, p##_loy, p##_hiy; +FgRegion fg_region_make(uint ew, uint eh, uint bx, uint by, uint rx, uint ry, uint lox, uint hix, uint loy, uint hiy) +{ + FgRegion r; + r.ew = asfloat(ew); r.eh = asfloat(eh); r.bx = asfloat(bx); r.by = asfloat(by); r.rx = asfloat(rx); + r.ry = asfloat(ry); r.lox = asfloat(lox); r.hix = asfloat(hix); r.loy = asfloat(loy); r.hiy = asfloat(hiy); + return r; +} +#define FG_REGION(p) fg_region_make(p##_ew, p##_eh, p##_bx, p##_by, p##_rx, p##_ry, p##_lox, p##_hix, p##_loy, p##_hiy) + +float2 fg_region_xy(FgRegion r, float u, float v, bool bias) +{ + float tx = mad(u, r.ew, r.bx), ty = mad(v, r.eh, r.by); + float X = bias ? mad(r.rx, tx, -FG_BIAS) : fg_mul(r.rx, tx); + float Y = bias ? mad(r.ry, ty, -FG_BIAS) : fg_mul(r.ry, ty); + return float2(fg_med3(X, r.lox, r.hix), fg_med3(Y, r.loy, r.hiy)); +} + +// ---- depth keys and the packed depth ----------------------------------------------------------------------------- +float fg_depth_key(float z, float s_k, uint inverted) +{ + float d = inverted != 0u ? z : 1.0f - z; + return fg_mul(s_k, fg_rcp(max(d, FG_KEY_FLOOR))); +} + +uint fg_pack_depth(float z, bool oxp, bool oyp, bool centre) +{ + uint B = asuint(z); + uint b29 = (B >> 29) & 1u; + uint oy = oyp ? 0x80000000u : 0u; + if (centre) return (b29 << 31) | (B & 0x1FFFFFFFu); + if (b29 != 0u) return oy | (oxp ? 0x40000000u : 0u) | (B & 0x3FFFFFFFu); + return oy | 0x40000000u | (B & 0x1FFFFFFEu) | (oxp ? 1u : 0u); +} + +// (z, offset x, offset y) +float3 fg_unpack_depth(uint Z, float sx, float sy) +{ + uint b31 = Z >> 31, b30 = (Z >> 30) & 1u, b29 = (Z >> 29) & 1u, b0 = Z & 1u; + bool centre = b30 == 0u && b29 == 0u; + uint low = Z & 0x1FFFFFFFu; + uint zb = centre ? (low | (b31 << 29)) : (low | (b29 << 29)); + bool xpos = (b29 != 0u ? b30 : b0) != 0u; + float ox = centre ? 0.0f : (xpos ? sx : -sx); + float oy = centre ? 0.0f : (b31 != 0u ? sy : -sy); + return float3(asfloat(zb), ox, oy); +} + +// camera motion (pixels) of normalised (u, v) at raw depth z with the 4 x 4 matrix m0..m15 (as supplied); (cx, cy, w) +float3 fg_camera(float u, float v, float z, float m0, float m1, float m3, float m4, float m5, float m7, float m8, + float m9, float m11, float m12, float m13, float m15, uint w1, uint h1) +{ + float nx = mad(u, 2.0f, -1.0f); + float ny = 1.0f - (v + v); + float xp = m12 + mad(m8, z, mad(ny, m4, fg_mul(m0, nx))); + float yp = m13 + mad(m9, z, mad(ny, m5, fg_mul(m1, nx))); + float w = m15 + mad(m11, z, mad(ny, m7, fg_mul(m3, nx))); + float aw = abs(w); + float cx = fg_mul(nx - fg_adiv(xp, aw), fg_mul((float)w1, -0.5f)); + float cy = fg_mul(ny - fg_adiv(yp, aw), fg_mul((float)h1, 0.5f)); + bool bad = !(w > 0.0f); + return float3(bad ? 10000.0f : cx, bad ? 10000.0f : cy, w); +} + +// a 64-bit scatter element: (vector in float, empty) +float3 fg_vec64(uint base, uint idx) +{ + uint2 e = wg_ld64(base, idx * 8u); + bool empty = e.x == 0x7FFFFFFFu && e.y == 0x7FFFFFFFu; + return float3(empty ? 0.0f : f16tof32(e.x >> 16), empty ? 0.0f : f16tof32(e.x & 0xffffu), empty ? 1.0f : 0.0f); +} + +uint fg_index_rint(float u, uint n) +{ + float p = fg_opq(mad(u, (float)n, -0.5f)); + return (uint)clamp((int)round(p + (-FG_BIAS)), 0, (int)n - 1); +} + +void fg_atomic_min64(uint base, uint idx, uint hi, uint lo) +{ + int64_t v = (int64_t)(((uint64_t)hi << 32) | (uint64_t)lo); + wg_mem_gc.InterlockedMin64(base + idx * 8u, v); +} 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.hlsli b/clean/dx12/hlsl/fg_net2.hlsli new file mode 100644 index 00000000..9abedfea --- /dev/null +++ b/clean/dx12/hlsl/fg_net2.hlsli @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): float16 operations of net2's D3D12 kernels (clean/dx12/kernels/fg_net2_*.hlsl), with the +// bits of the CPU reference clean/fg/reference/net2.py. Values are float16 bits in the low half of a uint. +// +// - Convolution chunks: the shared exact integer code clean/fg/kernels/fg_exact16.h (exact dot product, one nearest-even +// rounding per chunk; an exactly zero accumulator is +0), as the reference's fp16acc. +// - fg2_mul: the product of two float16 values is exact in single precision; wg_f2h rounds it once (IEEE signs). +// - fg2_fma: a b + c with one float16 rounding (wg_fma_f16: fused single-precision result made round-to-odd from its exact +// residual, then rounded once). The single-precision steps never meet a denormal here: every nonzero product or sum of +// float16 values is at least 2^-48. +// - fg2_leaky, fg2_clamp6, fg2_plus0: compares on the bits (NaN passes through unchanged). +// The including file includes wg_platform.hlsli first. +#pragma once + +#define FG_FN +#define FG_I64 int64_t +#define FG_FBH32(v) firstbithigh((uint)(v)) +#include "../../fg/kernels/fg_exact16.h" + +#define FG2_SLOPE16 0x211Fu // h(0.01) +#define FG2_ONE16 0x3C00u +#define FG2_TWO16 0x4000u +#define FG2_QUARTER16 0x3400u +#define FG2_SIX16 0x4600u +#define FG2_MSIX16 0xC600u + +uint fg2_mul(uint a, uint b) { return wg_f2h(wg_h2f(a) * wg_h2f(b)); } +uint fg2_fma(uint a, uint b, uint c) { return wg_fma_f16(wg_h2f(a), wg_h2f(b), wg_h2f(c)); } +uint fg2_add(uint a, uint b) { return wg_fma_f16(wg_h2f(a), 1.0f, wg_h2f(b)); } + +// max(h(s v), v): h(s v) has v's sign, so zeros of different signs never meet +uint fg2_leaky(uint v) +{ + if (fg_is_nan16(v) != 0u) return v; + const uint t = fg2_mul(FG2_SLOPE16, v); + return fg_key16(t) > fg_key16(v) ? t : v; +} + +uint fg2_clamp6(uint v) +{ + if (fg_is_nan16(v) != 0u) return v; + if (fg_key16(v) > fg_key16(FG2_SIX16)) return FG2_SIX16; + if (fg_key16(v) < fg_key16(FG2_MSIX16)) return FG2_MSIX16; + return v; +} + +// h(v + 0): -0 becomes +0 +uint fg2_plus0(uint v) { return (v & 0x7FFFu) == 0u ? 0u : v; } + +// the half-pixel 2x rule along one axis: output index o of an axis with n input samples +struct Fg2Tap { int i0; int i1; uint w0; uint w1; }; + +Fg2Tap fg2_up_tap(int o, int n) +{ + Fg2Tap t; + const float s = ((float)o - 0.5f) * 0.5f; + t.i0 = (int)s; + t.i1 = (int)(s + 1.0f); + if (t.i1 >= n) { t.i0 = n - 1; t.i1 = n - 1; } + if (s < 0.0f) { t.i0 = 0; t.i1 = 0; } + t.w1 = wg_f2h(s - (float)t.i0); + t.w0 = wg_f2h(((float)t.i0 - s) + 1.0f); + return t; +} diff --git a/clean/dx12/hlsl/fg_net2_fast.hlsli b/clean/dx12/hlsl/fg_net2_fast.hlsli new file mode 100644 index 00000000..46139362 --- /dev/null +++ b/clean/dx12/hlsl/fg_net2_fast.hlsli @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): exact float16 operations of net2's fast-path kernels (fg_net2_mconv.hlsl, +// fg_net2_upwarp.hlsl) on 8 values at once, with the bits of fg_net2.hlsli's one-value operations (fg2_mul, fg2_fma, +// fg2_add, fg2_leaky). Values are float16 bits, 8 packed in a uint4 (element i in dword i / 2, low half first). +// +// - The product of two float16 values is exact in single precision (at most 22 significant bits, never below 2^-48, +// never a single-precision subnormal), so h(w P) is one rounding of an exact value. +// - fma(w, P, t) = w P + t with one float16 rounding: s = a + t rounded to nearest in single precision with its exact +// residual (two-sum), made round-to-odd (wg_round_odd), then rounded once to float16 (13 spare bits: no double +// rounding). A non-finite s passes as it is, as in wg_fma_f16. +// - The float16 roundings of 8 values are one driver-channel conversion (wg_to_f16_ags: v_cvt_f16_f32 per element, +// nearest even); the opaque XOR keeps the driver from folding the producing operation into the conversion +// (fg_mpair.hlsl). The conversion is a driver-channel call: uniform control flow only. +// The including file includes wg_platform.hlsli and fg_net2.hlsli first and this header after its argument block +// (fg_opq0 reads the launch's grid size); wave32. +#pragma once + +uint fg_opq0() { return wg_grid_ >> 31; } // an opaque zero (the grid size is below 2^31) + +uint4 fg_pack8(uint r[8]) { return uint4(r[0] | (r[1] << 16), r[2] | (r[3] << 16), r[4] | (r[5] << 16), r[6] | (r[7] << 16)); } +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 single-precision values -> 8 packed float16, nearest even +uint4 fg_cvt8(float m[8]) +{ + v8f t; + const uint z = fg_opq0(); + [unroll] for (uint i = 0; i < 8; ++i) t.v[i] = asfloat(asuint(m[i]) ^ z); + return wg_to_f16_ags(t); +} + +// the single-precision rounding of a + c made round-to-odd (a, c exact single-precision values) +float fg_sum_odd(float a, float c) +{ + const float s = a + c, bv = s - a; + const float e = (a - (s - bv)) + (c - bv); + return (asuint(s) & 0x7fffffffu) >= 0x7f800000u ? s : asfloat(wg_round_odd(s, e)); +} + +// h(w P) for 8 values (fg2_mul) +uint4 fg_mul8(float w, uint4 p) +{ + float m[8]; + [unroll] for (uint i = 0; i < 8; ++i) m[i] = w * wg_h2f(fg_half(p, i)); + return fg_cvt8(m); +} +// h(w_i P_i): one float16 weight per value +uint4 fg_mul8v(float w[8], uint4 p) +{ + float m[8]; + [unroll] for (uint i = 0; i < 8; ++i) m[i] = w[i] * wg_h2f(fg_half(p, i)); + return fg_cvt8(m); +} +// fma(w, P, t) for 8 values (fg2_fma; w = 1 is fg2_add) +uint4 fg_fma8(float w, uint4 p, uint4 t) +{ + float m[8]; + [unroll] for (uint i = 0; i < 8; ++i) m[i] = fg_sum_odd(w * wg_h2f(fg_half(p, i)), wg_h2f(fg_half(t, i))); + return fg_cvt8(m); +} +// fma(w_i, P_i, t_i): one float16 weight per value +uint4 fg_fma8v(float w[8], uint4 p, uint4 t) +{ + float m[8]; + [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) { + const uint hv = fg_half(v, i), ht = fg_half(t, i); + 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 = +// (y0, x1), q10 = (y1, x0), q11 = (y1, x1) of the taps tX, tY (fg2_up_tap): top = fma(wx1, P01, h(wx0 P00)), bottom +// likewise, out = fma(wy1, bottom, h(wy0 top)); the weights (0.25, 0.75, 1.25, -0.25) are float16 values +uint4 fg_up8(Fg2Tap tX, Fg2Tap tY, uint4 q00, uint4 q01, uint4 q10, uint4 q11) +{ + const float wx0 = wg_h2f(tX.w0), wx1 = wg_h2f(tX.w1), wy0 = wg_h2f(tY.w0), wy1 = wg_h2f(tY.w1); + const uint4 top = fg_fma8(wx1, q01, fg_mul8(wx0, q00)); + const uint4 bot = fg_fma8(wx1, q11, fg_mul8(wx0, q10)); + return fg_fma8(wy1, bot, fg_mul8(wy0, top)); +} 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_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/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/hlsl/hyb_block.hlsli b/clean/dx12/hlsl/hyb_block.hlsli index 1d8c99e5..2c10ce5f 100644 --- a/clean/dx12/hlsl/hyb_block.hlsli +++ b/clean/dx12/hlsl/hyb_block.hlsli @@ -148,21 +148,106 @@ void hyb_norm(v8f x[KC], v8f gp[KC], uint hh, out v8f y[KC]) } } +hv8 hyb_u4_to_h(uint4 u) +{ + hv8 r; + r.p[0] = hyb_u2h(u.x); r.p[1] = hyb_u2h(u.y); r.p[2] = hyb_u2h(u.z); r.p[3] = hyb_u2h(u.w); + return r; +} + +// Fast norm from already-packed FP16 tiles xh_u (uint4[KC], e.g. SW_Q7_CHUNK norm2 acc_h): +// avoids 8*KC v_cvt_f32_f16 + 4*KC v_cvt_pk_rtz round-trip conversions; exact same FP16 ops in the exact same order. +void hyb_norm_h(uint4 xh_u[KC], v8f gp[KC], uint hh, out v8f y[KC]) +{ + hv8 xh[KC], q0h[KC], qph[KC]; +#if !(KC == 2 || KC == 4 || KC == 8) + hv8 T[2 * KC]; + const bool h0 = hh == 0u; +#endif + [unroll] for (uint k = 0; k < KC; ++k) { + xh[k] = hyb_u4_to_h(xh_u[k]); + [unroll] for (uint i = 0; i < 4; ++i) { + precise h2 sq = xh[k].p[i] * xh[k].p[i]; + q0h[k].p[i] = hyb_u2h(hyb_h2u(sq) | HYB_OPAQUE0); + } + qph[k] = hyb_hxor16(q0h[k]); +#if !(KC == 2 || KC == 4 || KC == 8) +#if defined(HYB_SCAN_MUTANT) && HYB_SCAN_MUTANT + T[k] = q0h[k]; + T[KC + k] = q0h[k]; +#else + T[k] = hyb_hsel(h0, q0h[k], qph[k]); + T[KC + k] = hyb_hsel(h0, qph[k], q0h[k]); +#endif +#endif + } +#if KC == 2 || KC == 4 || KC == 8 + hv8 L; +#if KC == 2 + L = hyb_hadd(hyb_hadd(q0h[0], qph[0]), hyb_hadd(q0h[1], qph[1])); +#else + { + hv8 ol[KC / 4], orr[KC / 4], pl2[KC / 4], pr2[KC / 4]; + [unroll] for (uint j2 = 0; j2 < KC; j2 += 4u) { + ol[j2 / 4u] = hyb_hadd(q0h[j2], q0h[j2 + 2u]); + orr[j2 / 4u] = hyb_hadd(q0h[j2 + 1u], q0h[j2 + 3u]); + pl2[j2 / 4u] = hyb_hadd(qph[j2], qph[j2 + 2u]); + pr2[j2 / 4u] = hyb_hadd(qph[j2 + 1u], qph[j2 + 3u]); + } +#if KC == 4 + L = hyb_hadd(hyb_hadd(ol[0], pl2[0]), hyb_hadd(orr[0], pr2[0])); +#else + L = hyb_hadd(hyb_hadd(hyb_hadd(ol[0], ol[1]), hyb_hadd(pl2[0], pl2[1])), + hyb_hadd(hyb_hadd(orr[0], orr[1]), hyb_hadd(pr2[0], pr2[1]))); +#endif + } +#endif +#else + const uint tiles = 2u * KC; + hv8 pl[4], pr[4]; + uint nl = 0u, nr = 0u; + [unroll] for (uint j = 0; j < tiles; j += 4u) { + pl[nl++] = hyb_hadd(T[j], T[j + 2u]); + pr[nr++] = hyb_hadd(T[j + 1u], T[j + 3u]); + } + const hv8 L = hyb_hadd(hyb_group(pl, nl), hyb_group(pr, nr)); +#endif + const h2 u01 = L.p[0] + L.p[1], u23 = L.p[2] + L.p[3]; + const h2 hv = u01 + u23; + const float16_t S = hv.x + hv.y; + const float16_t S2 = S + (float16_t)asfloat16((uint16_t)0x0800u); + const float16_t r = (float16_t)hyb_rsq16((uint)asuint16(S2)); + const h2 r2 = h2(r, r); + [unroll] for (uint k2 = 0; k2 < KC; ++k2) { + const hv8 g = hyb_to_h(gp[k2]); + hv8 yh; + [unroll] for (uint i2 = 0; i2 < 4; ++i2) yh.p[i2] = xh[k2].p[i2] * (r2 * g.p[i2]); + y[k2] = hyb_to_f(yh); + } +} + // The attention weights of the lane's 8 keys from its 8 scores s (float32 chain values started at B): -// RN16(s), e = hyb_softmax_e8, the row sum in the original's order (a_t = e_2t + e_8+2t, b_t = e_2t+1 + e_9+2t; -// a = (a0 + a1) + (a2 + a3), b likewise; sum = a + b), w = RN16(rcp32(sum)), P = RN16(e w) as packed FP16. -uint4 hyb_softmax_p(v8f s, uint hh) +// RN16(s), e = hyb_softmax_e8 (float32: exact products so fused == unfused under any FMad / NoContraction lowering), +// the row sum in the original's order (a_t = e_2t + e_8+2t, b_t = e_2t+1 + e_9+2t; a = (a0 + a1) + (a2 + a3), b +// likewise; sum = a + b), w = RN16(rcp32(sum)), P = RN16(e w) as packed FP16. Split into hyb_softmax_pre / +// hyb_softmax_fin so callers can hide hyb_rcp16's global LUT load latency behind independent Wv WMMAs. +struct HybSmaxPre { hv8 e; float16_t w; }; +HybSmaxPre hyb_softmax_pre(v8f s) { - const hv8 e = hyb_to_h(hyb_softmax_e8(hyb_round16(s))); // exact (e is FP16) - const hv8 ep = hyb_hxor16(e); - // p[t] = (a_t, b_t) = e (keys 2t, 2t+1 of this half) + the partner half's: FP16 addition is commutative, so - // e + ep on both lanes is the original's RN16(e_{2t} + e_{8+2t}) (no per-lane select) - const hv8 A = hyb_hadd(e, ep); + HybSmaxPre r; + r.e = hyb_to_h(hyb_softmax_e8(hyb_round16(s))); + const hv8 ep = hyb_hxor16(r.e); + const hv8 A = hyb_hadd(r.e, ep); const h2 ab = (A.p[0] + A.p[1]) + (A.p[2] + A.p[3]); // (a, b) const float16_t sum = ab.x + ab.y; - const float16_t w = (float16_t)hyb_rcp16((uint)asuint16(sum)); - const h2 w2 = h2(w, w); + r.w = (float16_t)hyb_rcp16((uint)asuint16(sum)); + return r; +} +uint4 hyb_softmax_fin(HybSmaxPre r) +{ + const h2 w2 = h2(r.w, r.w); hv8 P; - [unroll] for (uint i = 0; i < 4; ++i) P.p[i] = e.p[i] * w2; + [unroll] for (uint i = 0; i < 4; ++i) P.p[i] = r.e.p[i] * w2; return hyb_hpack(P); } +uint4 hyb_softmax_p(v8f s, uint hh) { return hyb_softmax_fin(hyb_softmax_pre(s)); } diff --git a/clean/dx12/hlsl/wg_hyb.hlsli b/clean/dx12/hlsl/wg_hyb.hlsli index 27de3e1e..2406192b 100644 --- a/clean/dx12/hlsl/wg_hyb.hlsli +++ b/clean/dx12/hlsl/wg_hyb.hlsli @@ -63,33 +63,54 @@ v8f hyb_round16(v8f d) { return hyb_h2f8(wg_to_f16_ags(d)); } // An FP8 point of FP16 values r (lever, exact): when no value of the wave exceeds 448 in magnitude, the saturating // pack's clamp and NaN keep change nothing, so the driver's plain conversion gives the same bytes (every NaN -> 0xff on // both paths; the driver's max drops NaN, a wave of NaNs only takes the clamped path). Wave-uniform branch. -bool hyb_wave_in448(v8f r) +float hyb_absmax8(float m, v8f r) { - float m = 0.0f; [unroll] for (uint i = 0; i < 8; ++i) m = max(m, abs(r.v[i])); - return WaveActiveAllTrue(m <= 448.0f); + return m; +} +bool hyb_wave_in448(v8f r) +{ + return WaveActiveAllTrue(hyb_absmax8(0.0f, r) <= 448.0f); } uint2 hyb_q8(v8f r) { if (hyb_wave_in448(r)) return wg_pack_q8_nc_ags(r); return wg_pack_q8_ags(r); } +void hyb_q8_pair(v8f r0, v8f r1, out uint2 q0, out uint2 q1) +{ + const float m = hyb_absmax8(hyb_absmax8(0.0f, r0), r1); + if (WaveActiveAllTrue(m <= 448.0f)) { + q0 = wg_pack_q8_nc_ags(r0); + q1 = wg_pack_q8_nc_ags(r1); + } else { + q0 = wg_pack_q8_ags(r0); + q1 = wg_pack_q8_ags(r1); + } +} // The chain end before an FP8 point: RN16, then the saturating FP8 pack of the FP16 value (two roundings, by design). uint2 hyb_q8_of_chain(v8f acc) { return hyb_q8(hyb_round16(acc)); } // GELU16 then the FP8 point, by table: h = the FP16 bits of 8 RN16'd W1 chain ends (hyb_rn16x8). Speed lever 2: the // 16-bit-entry copy of the table, one u16 load per value at h << 1 (the byte table needed a dword address, a shift // by the byte position and a mask per value); the same bytes (runtime/hyb_tables.h, checked by test_hyb_tables_cpp). -uint2 hyb_gelu_q8(uint4 h) +struct HybGeluPre { uint b[8]; }; +HybGeluPre hyb_gelu_pre(uint4 h) { const uint w[4] = { h.x, h.y, h.z, h.w }; - uint b[8]; + HybGeluPre r; [unroll] for (uint i = 0; i < 4; ++i) { - b[2 * i] = (uint)wg_mem.Load(WG_HYB_GELU16 + ((w[i] & 0xffffu) << 1)); - b[2 * i + 1] = (uint)wg_mem.Load(WG_HYB_GELU16 + ((w[i] >> 16) << 1)); + r.b[2 * i] = (uint)wg_mem.Load(WG_HYB_GELU16 + ((w[i] & 0xffffu) << 1)); + r.b[2 * i + 1] = (uint)wg_mem.Load(WG_HYB_GELU16 + ((w[i] >> 16) << 1)); } - return uint2(b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24), b[4] | (b[5] << 8) | (b[6] << 16) | (b[7] << 24)); + return r; +} +uint2 hyb_gelu_fin(HybGeluPre p) +{ + return uint2(p.b[0] | (p.b[1] << 8) | (p.b[2] << 16) | (p.b[3] << 24), + p.b[4] | (p.b[5] << 8) | (p.b[6] << 16) | (p.b[7] << 24)); } +uint2 hyb_gelu_q8(uint4 h) { return hyb_gelu_fin(hyb_gelu_pre(h)); } // The softmax weight e of 8 FP16 scores s (float32 values of FP16 numbers): u = RN16(s c), clamp to +-c' (a NaN takes // the lower clamp, as min / max return the number), t = RN16(fma(u, -u, t0)), p = RN16(fma(u, t, p0)), @@ -160,3 +181,99 @@ int hyb_mirror_coarse(int p, int n, int nc) const int c = p >> 1; // floor(p / 2) for negative p too (arithmetic shift) return min(nc - 1, min(abs(c), 2 * (n >> 1) - 2 - abs(c))); } + +// ---- SW_Q7_CHUNK helpers: fast per-32-channel FP16-rounded WMMA chunks (oracle mm8="exact") ------------------------ +// In-place 32-wide chunk accumulate into a packed FP16 tile (uint4): RN16(wmma(a1, b1, wmma(a0, b0, acc))). +// Only 12 VALUs + 2 WMMAs per 32-wide chunk (keeps acc packed in 4 VGPRs/tile for high occupancy). +uint4 hyb_q7c_step_h(uint2 a0, uint2 b0, uint2 a1, uint2 b1, uint4 acc_h) +{ + v8f t = wg_wmma_fp8(a0, b0, hyb_h2f8(acc_h)); + t = wg_wmma_fp8(a1, b1, t); + return hyb_rn16x8(t); +} + +// Guarded exact 16-term FP16xFP16 dot product for P V (matching l_q7w.hlsl two_sum + rn16_pair). +// Fast path: checks whether RN16(pv - err) == RN16(pv + err) for err = 2^-21 * max_finite|V| across the wave. +// Cold path: unpacked on the fly from packed uint4 p0/p1/v0/v1 (low VGPRs so c64 keeps 3 wg/CU) and only shuffles V +// for the specific v slot(s) where WaveActiveAnyTrue(need_v) holds. +void hyb_q7c_two_sum_pair(uint p_word, uint v_word, inout float s, inout float c) +{ + { + const float pr = f16tof32(p_word) * f16tof32(v_word); + const float u = s + pr; + const float bb = u - s; + c = c + ((s - (u - bb)) + (pr - bb)); + s = u; + } + { + const float pr = wg_h2f_hi(p_word) * wg_h2f_hi(v_word); + const float u = s + pr; + const float bb = u - s; + c = c + ((s - (u - bb)) + (pr - bb)); + s = u; + } +} + +// Guarded exact 16-term FP16xFP16 dot product for P V -> FP8 (matching l_q7w.hlsl two_sum + rn16_pair + q8). +// Because FP8(RN16(x)) is monotone, if qlo = FP8(RN16(pv - err)) == qhi = FP8(RN16(pv + err)) for err = 2^-20 * max|V|, +// then FP8(RN16(pv_exact)) == qlo is guaranteed! Since FP8 has 128x coarser spacing than FP16 (and never triggers +// near zero), the cold two_sum path executes on <0.3% of waves while guaranteeing 100% bit-exact FP8 output. +uint2 hyb_q7c_pv_q8(uint4 vt_dt, uint4 p, uint hh, uint z0, v8f pv) +{ + uint m16 = max(max(vt_dt.x & 0x7fffu, (vt_dt.x >> 16) & 0x7fffu), max(vt_dt.y & 0x7fffu, (vt_dt.y >> 16) & 0x7fffu)); + m16 = max(m16, max(max(vt_dt.z & 0x7fffu, (vt_dt.z >> 16) & 0x7fffu), max(vt_dt.w & 0x7fffu, (vt_dt.w >> 16) & 0x7fffu))); + if (m16 > 0x7bffu) m16 = 0x7bffu; + const float err = f16tof32(WaveActiveMax(m16)) * asfloat(0x35800000u); // 2^-20 * max|V| (16x safety margin) + v8f pv_lo, pv_hi; + [unroll] for (uint i = 0u; i < 8u; ++i) { pv_lo.v[i] = pv.v[i] - err; pv_hi.v[i] = pv.v[i] + err; } + uint2 qlo, qhi; + hyb_q8_pair(hyb_round16(pv_lo), hyb_round16(pv_hi), qlo, qhi); + const uint d0 = qlo.x ^ qhi.x, d1 = qlo.y ^ qhi.y; + if (!WaveActiveAnyTrue((d0 | d1) != 0u)) return qlo; + const uint4 po = uint4(wg_xor16_u(p.x), wg_xor16_u(p.y), wg_xor16_u(p.z), wg_xor16_u(p.w)); + const uint4 p0 = (hh == 0u) ? p : po; + const uint4 p1 = (hh == 0u) ? po : p; + [loop] for (uint v = 0u; v < 8u + z0; ++v) { + const uint dw = (v < 4u) ? d0 : d1; + const bool need_v = (((dw >> ((v & 3u) * 8u)) & 0xffu) != 0u); + if (WaveActiveAnyTrue(need_v)) { + const uint cl = hh * 8u + v; + const uint4 v0 = uint4(WaveReadLaneAt(vt_dt.x, cl), WaveReadLaneAt(vt_dt.y, cl), + WaveReadLaneAt(vt_dt.z, cl), WaveReadLaneAt(vt_dt.w, cl)); + const uint4 v1 = uint4(WaveReadLaneAt(vt_dt.x, cl + 16u), WaveReadLaneAt(vt_dt.y, cl + 16u), + WaveReadLaneAt(vt_dt.z, cl + 16u), WaveReadLaneAt(vt_dt.w, cl + 16u)); + if (need_v) { + float s = 0.0f, c = 0.0f; + hyb_q7c_two_sum_pair(p0.x, v0.x, s, c); + hyb_q7c_two_sum_pair(p0.y, v0.y, s, c); + hyb_q7c_two_sum_pair(p0.z, v0.z, s, c); + hyb_q7c_two_sum_pair(p0.w, v0.w, s, c); + hyb_q7c_two_sum_pair(p1.x, v1.x, s, c); + hyb_q7c_two_sum_pair(p1.y, v1.y, s, c); + hyb_q7c_two_sum_pair(p1.z, v1.z, s, c); + hyb_q7c_two_sum_pair(p1.w, v1.w, s, c); + const float z = s + c; + const float bb2 = z - s; + const float tl = (s - (z - bb2)) + (c - bb2); + const uint zb = asuint(z), tb = asuint(tl); + const bool ok = ((zb & 0x7f800000u) != 0x7f800000u) && ((tb & 0x7fffffffu) != 0u); + const uint opp = (zb ^ tb) >> 31; + pv.v[v] = asfloat(ok ? ((zb - opp) | 1u) : zb); + } + } + } + return hyb_q8_of_chain(pv); +} + +// Reorder N (even) FP8 fragments from Layout L (hh=0: 0..8N-1, hh=1: 8N..16N-1) to ascending kord_drow +// (dst[g]: hh=0 holds 16g..16g+7, hh=1 holds 16g+8..16g+15) using N/2 lane-xor16 exchanges. +#define HYB_Q7C_L2D(N, src, dst, hh) \ + do { \ + const bool _h0 = ((hh) == 0u); \ + [unroll] for (uint _p = 0u; _p < (N) / 2u; ++_p) { \ + const uint2 _s = _h0 ? (src)[2u * _p + 1u] : (src)[2u * _p]; \ + const uint2 _r = uint2(wg_xor16_u(_s.x), wg_xor16_u(_s.y)); \ + (dst)[_p] = _h0 ? (src)[2u * _p] : _r; \ + (dst)[(N) / 2u + _p] = _h0 ? _r : (src)[2u * _p + 1u]; \ + } \ + } while (0) diff --git a/clean/dx12/hlsl/wg_pidiv.hlsli b/clean/dx12/hlsl/wg_pidiv.hlsli new file mode 100644 index 00000000..458b8d77 --- /dev/null +++ b/clean/dx12/hlsl/wg_pidiv.hlsli @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: MIT +// The pre-exposure division of the staged native D3D12 route, done by the dedicated _pf kernels (input_encoder_pf, +// emo/input_encoder_mo_pf, and the post_tf _pf buffer forms) when pi != 1 instead of a separate color_divide launch. +// Include after wg_platform.hlsli. +// +// Per channel the value is native_color_div (native_helpers.hlsl: wg_div plus the exact repair of the one tiny quotient +// that rounds to the smallest normal): the staged route's color_divide bits. Like native_direct.hlsli's +// native_direct_color_div3 (the direct route's per-frame form, same proof: clean/runtime/native_direct_pi.h) three +// operations on the lanes whose |a| lies in the window [lo, hi) (or is zero / an FP32 denormal), the reference division on +// the others. The window is native_direct_pi_window(pi) of the host, computed here from the pre-exposure's bits (the host +// folds the division only for a pi whose window is valid: hi != 0): y = RN(1 / pi) is the kernel's own correctly rounded +// quotient, lo = 2^max(-79, B - 125), hi = 2^(B + 127) (+inf for B > 0), B the unbiased exponent of pi. Alpha is not touched +// by the caller (color_divide copies it as raw bits). +#pragma once + +// native_color_div (native_helpers.hlsl) +float pidiv_ref(float a, float b) +{ + const float r = wg_div(a, b); + const uint ua = asuint(a), ub = asuint(b); + const uint ea = (ua >> 23u) & 255u, eb = (ub >> 23u) & 255u; + if ((asuint(r) & 0x7fffffffu) == 0u && ea != 0u && eb != 255u && eb == ea + 127u && + (ua & 0x7fffffu) == 0x7fffffu && (ub & 0x7fffffu) == 0u) + return asfloat(((ua ^ ub) & 0x80000000u) | 0x00800000u); + return r; +} + +struct PiDiv { float b, y, lo, hi; }; // pi, RN(1 / pi), the window's bounds (|a| in [lo, hi) takes the fast form) + +PiDiv pidiv_make(uint bits) +{ + PiDiv d; + d.b = asfloat(bits); + d.y = wg_div(1.0f, d.b); + const uint eb = (bits >> 23u) & 255u; + const bool ok = and(bits < 0x80000000u, and(eb >= 1u, eb <= 252u)); + const int B = (int)eb - 127; + const int L = max(B - 125, -79); + d.lo = asfloat((uint)(L + 127) << 23u); + d.hi = ok ? (B > 0 ? asfloat(0x7f800000u) : asfloat((uint)(B + 254) << 23u)) : 0.0f; + return d; +} + +// c / pi per channel. z: a zero the compiler cannot see (the loop count, so that the three exact-fallback copies stay one +// rolled loop; the caller xors the result with it to keep the removed store's rounding boundary) +float3 pidiv3(float3 c, PiDiv d, uint z) +{ + const float3 q0 = c * d.y; + const float3 rn = mad(d.b, q0, -c); + float3 q = mad(-rn, d.y, q0); + const float3 m = abs(c); + const bool3 fast = and(m < d.hi, or(m >= d.lo, m < asfloat(0x00800000u))); + [branch] if (!all(fast)) { + float3 a = c; + uint3 f = uint3(fast); + [loop] for (uint i = 0u; i < 3u + z; ++i) { // channel i in .x; rotated after each + const float r = f.x != 0u ? q.x : pidiv_ref(a.x, d.b); + q = float3(q.y, q.z, r); + a = float3(a.y, a.z, a.x); + f = uint3(f.y, f.z, f.x); + } + } + return q; +} diff --git a/clean/dx12/hlsl/wg_w64.hlsli b/clean/dx12/hlsl/wg_w64.hlsli new file mode 100644 index 00000000..a6b323ce --- /dev/null +++ b/clean/dx12/hlsl/wg_w64.hlsli @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: MIT +// The matrix helpers of wave64 kernels (WG_WAVE 64; wg_platform.hlsli defines its own only for wave32): "design D" of the +// wave64 ports (clean/rr_f: rr_block_c32.hlsl, rr_block_c64_w64.hlsl), one wave64 = the work of two wave32 waves, tile t (0, 1) +// = one wave32 wave's 16 tokens. Wave64 lane L = l + 32 hh holds, for each tile, half hh of wave32 lane l's fragment: FP8 A / B +// bytes 4 hh .. 4 hh + 3, accumulator elements 4 hh .. 4 hh + 3 (the v_wmma wave64 layout; a wave64 v_wmma is the wave32 one bit +// for bit and the conversions are per value, so every output keeps its bits). A v8f holds elements 0-3 of tile 0 and 0-3 of +// tile 1; a uint2 FP8 fragment: x = tile 0, y = tile 1 (one dword each); a uint4 of packed FP16: x, y = tile 0, z, w = tile 1. +// A shared operand (the weights) passes the same dword in both: uint2(w, w). +#pragma once +#if WG_WAVE != 64 +#error "wg_w64.hlsli: wave64 kernels only" +#endif +#include "wg_ags.hlsli" +wg_frag wg_frag_v8f(v8f c) { wg_frag f; [unroll] for (uint i = 0; i < 8; ++i) f.v[i] = asuint(c.v[i]); return f; } +v8f wg_v8f_frag(wg_frag f) { v8f c; [unroll] for (uint i = 0; i < 8; ++i) c.v[i] = asfloat(f.v[i]); return c; } +wg_frag wg_w64f(uint a, uint b, uint c, uint d) // a wave64 fragment: the first 4 / 2 / 1 dwords are used +{ + wg_frag f; + f.v[0] = a; f.v[1] = b; f.v[2] = c; f.v[3] = d; + [unroll] for (uint i = 4; i < 8; ++i) f.v[i] = 0u; + return f; +} +v8f wg_wmma_fp8(uint2 a, uint2 b, v8f c) // tile 0: (a.x, b.x, c 0-3), tile 1: (a.y, b.y, c 4-7) +{ + const wg_frag r0 = wg_ags_mma(WG_AGS_FP8_F32, wg_w64f(a.x, 0u, 0u, 0u), wg_w64f(b.x, 0u, 0u, 0u), + wg_w64f(asuint(c.v[0]), asuint(c.v[1]), asuint(c.v[2]), asuint(c.v[3]))); + const wg_frag r1 = wg_ags_mma(WG_AGS_FP8_F32, wg_w64f(a.y, 0u, 0u, 0u), wg_w64f(b.y, 0u, 0u, 0u), + wg_w64f(asuint(c.v[4]), asuint(c.v[5]), asuint(c.v[6]), asuint(c.v[7]))); + v8f d; + [unroll] for (uint i = 0; i < 4; ++i) { d.v[i] = asfloat(r0.v[i]); d.v[4 + i] = asfloat(r1.v[i]); } + return d; +} +uint2 wg_pack_q8_nc_ags(v8f d) // v_cvt_pk_fp8_f32 per value pair, element i -> byte i of its tile's dword +{ + const wg_frag r0 = wg_ags_convert(wg_w64f(asuint(d.v[0]), asuint(d.v[1]), asuint(d.v[2]), asuint(d.v[3])), + WG_AGS_T_F32_ACC, WG_AGS_T_FP8_B); + const wg_frag r1 = wg_ags_convert(wg_w64f(asuint(d.v[4]), asuint(d.v[5]), asuint(d.v[6]), asuint(d.v[7])), + WG_AGS_T_F32_ACC, WG_AGS_T_FP8_B); + return uint2(r0.v[0], r1.v[0]); +} +uint2 wg_pack_q8_ags(v8f d) // the clamp of wg_pack_q8 (wg_sat448, per value), then the conversion +{ + [unroll] for (uint i = 0; i < 8; ++i) d.v[i] = wg_sat448(d.v[i]); + return wg_pack_q8_nc_ags(d); +} +uint4 wg_to_f16_ags(v8f d) // v_cvt_f16_f32 per value (round to nearest even) +{ + const wg_frag r0 = wg_ags_convert(wg_w64f(asuint(d.v[0]), asuint(d.v[1]), asuint(d.v[2]), asuint(d.v[3])), + WG_AGS_T_F32_ACC, WG_AGS_T_F16_ACC); + const wg_frag r1 = wg_ags_convert(wg_w64f(asuint(d.v[4]), asuint(d.v[5]), asuint(d.v[6]), asuint(d.v[7])), + WG_AGS_T_F32_ACC, WG_AGS_T_F16_ACC); + return uint4(r0.v[0], r0.v[1], r1.v[0], r1.v[1]); +} diff --git a/clean/dx12/isa_checks.json b/clean/dx12/isa_checks.json index 44840ee6..5491fbb0 100644 --- a/clean/dx12/isa_checks.json +++ b/clean/dx12/isa_checks.json @@ -1,8 +1,9 @@ { - "_doc": "build_dx12.py ISA check: for each kernel listed, the RGA (gfx1201) ISA must contain exactly the given number of instructions whose mnemonic matches each pattern (a regular expression, matched at the start of the mnemonic). Model K's softmax weights (clean/k/dx12/hlsl/k_smx.hlsli) are exact only when the driver folds the mix form p + e into one v_fma_mixlo/hi_f16 rounding per weight: 32 weights per lane per softmax round, i.e. 32 x heads x windows per workgroup for the narrow stages (e2 / d2: 2 heads, 1 window; d1: 2 heads, 2 windows) and 32 x heads / NG for the wide stages (e3 / d3 and the NG = 2 e4 / d4: 2 rounds; NG = 4 e4 / d4: 1; m: 8 heads / NG 4 = 2; the phase-split m attention k_split_m_attn: one head per workgroup = 1). A missing fold leaves v_cvt_f16_f32 after an FP32 add (a second rounding) and fails here. The __rodd ports (round to odd) must have none. The native D3D12 runtime checks the same fold on the player's driver at create (k_mix_probe). WG_DX12_ISA_CHECK=0 skips the check.", + "_doc": "build_dx12.py ISA check: for each kernel listed, the RGA (gfx1201) ISA must contain exactly the given number of instructions whose mnemonic matches each pattern (a regular expression, matched at the start of the mnemonic). Model K's softmax weights (clean/k/dx12/hlsl/k_smx.hlsli) are exact only when the driver folds the mix form p + e into one v_fma_mixlo/hi_f16 rounding per weight: 32 weights per lane per softmax round, i.e. 32 x heads x windows per workgroup for the narrow stages (e2 / d2 / d1: 2 heads, 1 window; the two-window d1: 2 heads, 2 windows) and 32 x heads / NG for the wide stages (e3 / d3 and the NG = 2 e4 / d4: 2 rounds; NG = 4 e4 / d4: 1; m: 8 heads / NG 4 = 2; the phase-split m attention k_split_m_attn: one head per workgroup = 1). A missing fold leaves v_cvt_f16_f32 after an FP32 add (a second rounding) and fails here. The __rodd ports (round to odd) must have none. The native D3D12 runtime checks the same fold on the player's driver at create (k_mix_probe). WG_DX12_ISA_CHECK=0 skips the check.", "k_stage_e2": {"v_fma_mix(lo|hi)_f16": 64}, "k_stage_d2": {"v_fma_mix(lo|hi)_f16": 64}, "k_stage2_d1": {"v_fma_mix(lo|hi)_f16": 128}, + "k_stage_d1": {"v_fma_mix(lo|hi)_f16": 64}, "k_stagew2_e3": {"v_fma_mix(lo|hi)_f16": 64}, "k_stagew4_e4": {"v_fma_mix(lo|hi)_f16": 32}, "k_stagew2_e4": {"v_fma_mix(lo|hi)_f16": 64}, @@ -18,6 +19,7 @@ "k_stage_e2__rodd": {"v_fma_mix(lo|hi)_f16": 0}, "k_stage_d2__rodd": {"v_fma_mix(lo|hi)_f16": 0}, "k_stage2_d1__rodd": {"v_fma_mix(lo|hi)_f16": 0}, + "k_stage_d1__rodd": {"v_fma_mix(lo|hi)_f16": 0}, "k_stagew2_e3__rodd": {"v_fma_mix(lo|hi)_f16": 0}, "k_stagew4_e4__rodd": {"v_fma_mix(lo|hi)_f16": 0}, "k_stagew2_e4__rodd": {"v_fma_mix(lo|hi)_f16": 0}, diff --git a/clean/dx12/kernel_sets.json b/clean/dx12/kernel_sets.json index b13ec118..f78596c6 100644 --- a/clean/dx12/kernel_sets.json +++ b/clean/dx12/kernel_sets.json @@ -36,6 +36,10 @@ "emo/input_encoder_mo_direct", "encoder_mo.co" ], + [ + "emo/input_encoder_mo_pf", + "encoder_mo.co" + ], [ "expand_c96", "swin.co" @@ -68,6 +72,14 @@ "input_encoder_direct", "encoder.co" ], + [ + "input_encoder_pf", + "encoder.co" + ], + [ + "lev/input_encoder_q20_pf", + "-" + ], [ "native_driver_probe", "-" @@ -92,6 +104,10 @@ "pmo/post_tf4_dl_f32_p12_mo_direct", "post_mo_w64__orig.co" ], + [ + "pmo/post_tf4_dl_f32_p12_mo_pf", + "post_mo_w64__orig.co" + ], [ "pmo/post_tf_f32_p12_mo", "post_mo_w64__orig.co" @@ -100,6 +116,10 @@ "pmo/post_tf_f32_p12_mo_direct", "post_mo_w64__orig.co" ], + [ + "pmo/post_tf_f32_p12_mo_pf", + "post_mo_w64__orig.co" + ], [ "scale_rgb", "frame.co" @@ -148,6 +168,10 @@ "w64/post_filter_c1_s4", "post_w64.co" ], + [ + "w64/post_filter_c1_s4", + "post_w64__orig.co" + ], [ "w64/post_tf4_dl_f32_p12_diet_vsit", "post_w64.co" @@ -164,6 +188,10 @@ "w64/post_tf4_dl_f32_p12_diet_vsit_direct", "post_w64__orig.co" ], + [ + "w64/post_tf4_dl_f32_p12_diet_vsit_pf", + "post_w64__orig.co" + ], [ "w64/post_tf_f32_p12_diet_vsit", "post_w64.co" @@ -180,6 +208,10 @@ "w64/post_tf_f32_p12_diet_vsit_direct", "post_w64__orig.co" ], + [ + "w64/post_tf_f32_p12_diet_vsit_pf", + "post_w64__orig.co" + ], [ "w64/post_tf_p12_diet_vsit", "post_w64__orig.co" @@ -187,6 +219,14 @@ [ "w64/post_tf_p12_diet_vsit_tex", "post_w64__orig.co" + ], + [ + "w64_lc12/l_post_tf_p12", + "-" + ], + [ + "w64_lc12/l_post_tf_p12_pf", + "-" ] ], "model_l": [ @@ -194,10 +234,18 @@ "expand_c128_hyb", "-" ], + [ + "expand_c128_q7c_hyb", + "-" + ], [ "expand_c96_hyb", "-" ], + [ + "expand_c96_q7c_hyb", + "-" + ], [ "l_coef", "l_ops.co" @@ -210,6 +258,10 @@ "l_dec_project", "l_ops.co" ], + [ + "l_dec_project_fast", + "-" + ], [ "l_direct_color", "-" @@ -234,6 +286,10 @@ "l_post_filter_direct_ldr", "-" ], + [ + "l_post_filter_direct_orig", + "-" + ], [ "l_post_filter_ldr", "l_post.co" @@ -258,6 +314,10 @@ "l_project_gather", "l_ops.co" ], + [ + "l_project_gather_fast", + "-" + ], [ "l_q7_block_c128", "l_q7w.co" @@ -302,6 +362,22 @@ "l_q7_merge_c96", "l_q7w.co" ], + [ + "l_swin_block_c32_dec_add_nc", + "-" + ], + [ + "l_swin_block_c32_dec_coef12_add_nc", + "-" + ], + [ + "l_swin_block_c32_dec_coef12_add_w2p_fast", + "-" + ], + [ + "l_swin_block_c32_dec_coef12_add_w2t_fast", + "-" + ], [ "l_swin_block_c32_dec_coef12_hyb", "-" @@ -330,6 +406,18 @@ "l_swin_block_c32_enc_lin_nc", "-" ], + [ + "l_swin_block_c32_enc_lin_nc_fast", + "-" + ], + [ + "l_swin_block_c32_enc_lin_w2p_fast", + "-" + ], + [ + "l_swin_block_c32_enc_lin_w2t_fast", + "-" + ], [ "l_swin_block_c32_enc_nc", "l_swin.co" @@ -370,41 +458,137 @@ "lev/input_encoder_q20", "-" ], + [ + "morig/l_post_recon", + "l_post__morig.co" + ], + [ + "morig/l_post_recon_p12", + "l_post__morig.co" + ], [ "patch_merge_c64_hyb", "-" ], + [ + "patch_merge_c64_q7c_hyb", + "-" + ], [ "patch_merge_c96_hyb", "-" ], + [ + "patch_merge_c96_q7c_hyb", + "-" + ], [ "swin_block_c128_hyb", "-" ], + [ + "swin_block_c128_q7c_hyb", + "-" + ], + [ + "swin_block_c64_add_ex_hyb", + "-" + ], [ "swin_block_c64_add_ex_nc", "swin.co" ], + [ + "swin_block_c64_add_ex_nc_fast", + "-" + ], [ "swin_block_c64_add_hyb", "-" ], + [ + "swin_block_c64_add_q7c_hyb", + "-" + ], [ "swin_block_c64_hyb", "-" ], + [ + "swin_block_c64_nc_fast", + "-" + ], + [ + "swin_block_c64_q7c_hyb", + "-" + ], + [ + "swin_block_c96_add_ex_hyb", + "-" + ], + [ + "swin_block_c96_add_ex_nc_fast", + "-" + ], [ "swin_block_c96_add_hyb", "-" ], + [ + "swin_block_c96_add_q7c_hyb", + "-" + ], [ "swin_block_c96_hyb", "-" ], + [ + "swin_block_c96_pm_rev_nc_fast", + "-" + ], + [ + "swin_block_c96_q7c_hyb", + "-" + ], [ "swin_bneck6_hyb", "-" + ], + [ + "swin_bneck6_q7c_hyb", + "-" + ], + [ + "w64_lc12/l_post_recon", + "l_post__lc12.co" + ], + [ + "w64_lc12/l_post_recon_ldr", + "l_post__lc12.co" + ], + [ + "w64_lc12/l_post_recon_p12", + "l_post__lc12.co" + ], + [ + "w64_lc12/l_post_recon_p12_ldr", + "l_post__lc12.co" + ], + [ + "w64_lc12/l_post_tf_p12_fast", + "-" + ], + [ + "w64_lc12/l_post_tf_p12_fast3", + "-" + ], + [ + "w64_lc12/l_post_tf_p12_pf_fast", + "-" + ], + [ + "w64_lc12/l_post_tf_p12_pf_fast3", + "-" ] ], "model_k": [ @@ -512,6 +696,10 @@ "k_stage_d1", "k_block.co" ], + [ + "k_stage_d1__rodd", + "k_block.co" + ], [ "k_stage_d2", "k_block.co" @@ -624,6 +812,30 @@ "kx/k_in_tiled__a1", "k_io_exact.co" ], + [ + "kx/k_in_tiled_color", + "k_io_exact.co" + ], + [ + "kx/k_in_tiled_color__a1", + "k_io_exact.co" + ], + [ + "kx/k_in_tiled_color_direct", + "k_io_exact.co" + ], + [ + "kx/k_in_tiled_color_direct__a1", + "k_io_exact.co" + ], + [ + "kx/k_in_tiled_color_uniform", + "k_io_exact.co" + ], + [ + "kx/k_in_tiled_color_uniform__a1", + "k_io_exact.co" + ], [ "kx/k_in_tiled_direct", "k_io_exact.co" diff --git a/clean/dx12/kernels/encoder.hlsl b/clean/dx12/kernels/encoder.hlsl index a5e0fd18..94164193 100644 --- a/clean/dx12/kernels/encoder.hlsl +++ b/clean/dx12/kernels/encoder.hlsl @@ -16,6 +16,7 @@ // projection into "tok < ntok" (its only effect is that store); here every lane runs it (the WMMA needs the whole wave) // and only the store is conditional: the same bytes. // @wg-kernel input_encoder co=encoder.co block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b116 +// @wg-kernel input_encoder_pf co=encoder.co entry=input_encoder block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b116 defines=WG_STAGED_PIDIV=1 // @wg-kernel input_encoder_direct co=encoder.co entry=input_encoder block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b116 rs=direct defines=WG_DIRECT_TEXTURES=1 // // Motion at output resolution (WG_ENC_MO; HIP: input_encoder_mo of kernels/encoder_mo.hip, code object encoder_mo.co @@ -25,6 +26,7 @@ // kernel without depth, then WgEncMoParams (mw, mh, pitch, wide, kmx, kmy) after WgEncParams. Buffer form: the raw // motion buffer (wg_motion_hi.hlsli); direct form: the game's motion texture (its `motion` pointer is not read). // @wg-kernel emo/input_encoder_mo co=encoder_mo.co entry=input_encoder block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,b116,b24 defines=WG_ENC_MO=1 +// @wg-kernel emo/input_encoder_mo_pf co=encoder_mo.co entry=input_encoder block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,b116,b24 defines=WG_ENC_MO=1,WG_STAGED_PIDIV=1 // @wg-kernel emo/input_encoder_mo_direct co=encoder_mo.co entry=input_encoder block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,b116,b24 rs=direct defines=WG_DIRECT_TEXTURES=1,WG_ENC_MO=1 // // Model L's value kernel (WG_ENC_VALUES_OUT; HIP: encoder.hip built with WG_ENC_VALUES_OUT=1 as l_enc_values.co, issue @@ -44,6 +46,10 @@ // runtime fusion le). // @wg-kernel lev/input_encoder_q20 co=- entry=input_encoder block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b116 defines=WG_ENC_VALUES_OUT=1,WG_ENC_Q20=1 // @wg-kernel lev/input_encoder_direct_q20 co=- entry=input_encoder block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b116 rs=direct defines=WG_DIRECT_TEXTURES=1,WG_ENC_VALUES_OUT=1,WG_ENC_Q20=1 +// The staged route's pre-exposure division folded in (WG_STAGED_PIDIV; wg_pidiv.hlsli; runtime WG_L_POST_TF with pi != 1): +// the colour is divided by pi (the bits of EncParams.pad0) as color_divide stores it, so no color_divide launch runs; the +// post's colour reads (l_post_tf_p12_pf) divide the same way. +// @wg-kernel lev/input_encoder_q20_pf co=- entry=input_encoder block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b116 defines=WG_ENC_VALUES_OUT=1,WG_ENC_Q20=1,WG_STAGED_PIDIV=1 #include "wg_platform.hlsli" #ifndef WG_ENC_VALUES_OUT #define WG_ENC_VALUES_OUT 0 @@ -65,6 +71,9 @@ #if defined(WG_ENC_MO) #include "wg_motion_hi.hlsli" #endif +#if defined(WG_STAGED_PIDIV) +#include "wg_pidiv.hlsli" +#endif WG_ARGS_BEGIN #if defined(WG_ENC_MO) @@ -182,7 +191,10 @@ void pixel_values(int mode, Uni U, int x, int y, float4 c, float2 mn, float2 mf, [unroll] for (uint ch = 0; ch < 3; ++ch) { float ec = U.e * c[ch]; float r = kG * wg_log2(wg_fmax(mad(100.0f, wg_fmin(ec, 32752.0f), 1.0f), k1em4)); - float g = ec > 32752.0f ? kG * wg_log2(mad(100.0f, ec, 1.0f)) : r; + float g = r; + [branch] if (WaveActiveAnyTrue(ec > 32752.0f)) { + g = ec > 32752.0f ? kG * wg_log2(mad(100.0f, ec, 1.0f)) : r; + } bool nan = ec != ec; v[ch] = nan ? 0.0f : r; gc[ch] = nan ? 0.0f : g; @@ -204,10 +216,35 @@ void pixel_values(int mode, Uni U, int x, int y, float4 c, float2 mn, float2 mf, [unroll] for (uint i2 = 15; i2 < 20; ++i2) v[i2] = 0.0f; return; } +#if WG_ENC_Q20 + // Model L's q20 encoders: near / far at the bit pattern of center (no motion change between the three vectors, the + // common case) read the same history texels with the same weights, so their values are center's, bit for bit; the + // history read and the transfer of that position run only when the whole wave needs them. + { + float3 h1 = hist_values(mode, U, qx[1], qy[1], valid[1], gc); + bool same0 = asuint(qx[0]) == asuint(qx[1]) && asuint(qy[0]) == asuint(qy[1]); + bool same2 = asuint(qx[2]) == asuint(qx[1]) && asuint(qy[2]) == asuint(qy[1]); + float3 h0 = h1, h2 = h1; + [branch] if (WaveActiveAnyTrue(!same0)) { + float3 t = hist_values(mode, U, qx[0], qy[0], valid[0], gc); + h0 = same0 ? h1 : t; + } + [branch] if (WaveActiveAnyTrue(!same2)) { + float3 t = hist_values(mode, U, qx[2], qy[2], valid[2], gc); + h2 = same2 ? h1 : t; + } + float3 h3 = hist_values(mode, U, qx[3], qy[3], valid[3], gc); + v[3] = h0.x; v[4] = h0.y; v[5] = h0.z; + v[6] = h1.x; v[7] = h1.y; v[8] = h1.z; + v[9] = h2.x; v[10] = h2.y; v[11] = h2.z; + v[12] = h3.x; v[13] = h3.y; v[14] = h3.z; + } +#else [unroll] for (uint k2 = 0; k2 < 4; ++k2) { float3 h = hist_values(mode, U, qx[k2], qy[k2], valid[k2], gc); v[3 + 3 * k2] = h.x; v[4 + 3 * k2] = h.y; v[5 + 3 * k2] = h.z; } +#endif // Motion disagreement (value 15) { @@ -516,9 +553,15 @@ void encoder_main() } // Slot 0, then slot 1: the 20 values -> 5 words of FP8, values 8..15 swapped with the partner lane (lane ^ 16) +#if defined(WG_STAGED_PIDIV) + const PiDiv pd = pidiv_make((uint)P_pad0); +#endif uint q[2][5], x8[2][2]; [unroll] for (uint dx2 = 0; dx2 < 2; ++dx2) { float4 c = cs[dx2]; +#if defined(WG_STAGED_PIDIV) + c = float4(asfloat(asuint(pidiv3(c.xyz, pd, (uint)P_rw >> 31u)) ^ ((uint)P_rw >> 31u)), c.w); +#endif float v[20]; if (U.mode == kHistGeneral) // uniform pixel_values(kHistGeneral, U, (int)xs[dx2], y, c, mn[dx2], mf[dx2], mc[dx2], v diff --git a/clean/dx12/kernels/fg_distortion.hlsl b/clean/dx12/kernels/fg_distortion.hlsl new file mode 100644 index 00000000..ad1edf48 --- /dev/null +++ b/clean/dx12/kernels/fg_distortion.hlsl @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): the optional distortion stages, as clean/fg/reference/stages_full.py r5_downsample and +// r5_fields, bit for bit. Built only when --only names them. +// +// fg_dist_down: one lane per scatter-grid pixel (W1 x H1): the application's distortion field (tw x th, 4 x float32) +// read nearest at the region-mapped position of the pixel centre (region (bx, by, ew, eh); rx, ry = 1 / tw, 1 / th and +// the clamp bounds lox, hix, loy, hiy come from the host as float bits), out = fma(scale, field, bias) as 4 x float16 +// ((bias, scale) = (0, 1) unless the low-precision setting gives them). +// fg_dist_fields: one lane per scatter-grid pixel: from the downsampled current / previous fields Dc, Dp (4 x float16), +// the packed depth Zc (32-bit words), the processed motion Mv (2 x float32, normalized) and the previous -> current +// field F (2 x float16, pixels): the distorted packed depth zd, the distorted current -> previous field mcp (normalized) +// and the distorted previous -> current field fout (pixels), both 2 x float16. +// +// @wg-kernel fg_dist_down co=fg_full.co block=256 wave=32 args=p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u +// @wg-kernel fg_dist_fields co=fg_full.co block=256 wave=32 args=p,p,p,p,p,p,p,p,u,u defines=FGD_FIELDS=1 +#include "wg_platform.hlsli" +#include "fg_full.hlsli" + +#ifndef FGD_FIELDS +#define FGD_FIELDS 0 +#endif + +WG_ARGS_BEGIN +#if FGD_FIELDS + uint dc, dp, zc, mv, fpc, zd, mcp, fout; + int W1, H1; +#else + uint field, outp; + int W1, H1, tw, th, bx, by, ew, eh; + uint rx, ry, lox, hix, loy, hiy, bias, scale; // float bits +#endif +WG_ARGS_END + +#if FGD_FIELDS +WG_KERNEL(fg_dist_fields) +{ + FGF_SETUP(); + const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); + if (idx >= W1 * H1) return; + const int y = idx / W1, x = idx - y * W1; + const float u = fgf_centre(x, W1), v = fgf_centre(y, H1); + const float W1f = (float)W1, H1f = (float)H1; + const float4 dcu = fgf_bil4h(dc, fgf_tap_uv(u, v, W1, H1)); + const float p1x = u + dcu.x, p1y = v + dcu.y; + const int i1 = fgf_nearest(p1y, H1) * W1 + fgf_nearest(p1x, W1); + wg_st32(zd, (uint)idx * 4u, wg_ld32(zc, (uint)i1 * 4u)); + const float2 m = asfloat(wg_ld64(mv, (uint)i1 * 8u)); + const float p2x = p1x + m.x, p2y = p1y + m.y; + const float4 q = fgf_bil4h(dp, fgf_tap_uv(p2x, p2y, W1, H1)); + fgf_st2h(mcp, idx, float2((p2x + q.z) - u, (p2y + q.w) - v)); + const float4 dpu = fgf_bil4h(dp, fgf_tap_uv(u, v, W1, H1)); + const float rx = u + dpu.x, ry = v + dpu.y; + const float2 f = fgf_ld2h(fpc, fgf_nearest(ry, H1) * W1 + fgf_nearest(rx, W1)); + const float sx = rx + wg_div(f.x, W1f), sy = ry + wg_div(f.y, H1f); + const float4 dcs = fgf_bil4h(dc, fgf_tap_uv(sx, sy, W1, H1)); + fgf_st2h(fout, idx, float2(((sx + dcs.z) - u) * W1f, ((sy + dcs.w) - v) * H1f)); +} +#else +WG_KERNEL(fg_dist_down) +{ + FGF_SETUP(); + const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); + if (idx >= W1 * H1) return; + const int y = idx / W1, x = idx - y * W1; + const float u = fgf_centre(x, W1), v = fgf_centre(y, H1); + const float X = min(max(asfloat(rx) * mad(u, (float)ew, (float)bx), asfloat(lox)), asfloat(hix)); + const float Y = min(max(asfloat(ry) * mad(v, (float)eh, (float)by), asfloat(loy)), asfloat(hiy)); + const float4 f = wg_ld4f(field, (uint)(fgf_nearest(Y, th) * tw + fgf_nearest(X, tw)) * 16u); + fgf_st4h(outp, idx, mad(asfloat(scale), f, asfloat(bias))); +} +#endif diff --git a/clean/dx12/kernels/fg_exec_io.hlsl b/clean/dx12/kernels/fg_exec_io.hlsl new file mode 100644 index 00000000..35396269 --- /dev/null +++ b/clean/dx12/kernels/fg_exec_io.hlsl @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96, F7b): the executor's two input / output kernels around the light and Full path kernels +// (clean/fg/runtime/fg_d3d12_executor.h). D3D12 only (no HIP counterpart). Built only when --only names them. +// +// 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 (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, +// 3 = R10G10B10A2_UNORM; UNORM codes are floor(sat(v) * max + 0.5) with sat(NaN) = 0. +// +// @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" +#include "fg_pack.hlsli" + +#if FGX_K == 1 +WG_ARGS_BEGIN + uint a0, a1, a2, a3; +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) +{ + 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(fg_pack_h2(c.x, c.y), fg_pack_h2(c.z, c.w))); + else if (kind == 1u) + 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 + wg_st32(a0, idx * 4u, asuint(c.x)); +} +#endif + +#if FGX_K == 2 +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) +{ + 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 new file mode 100644 index 00000000..3b1082c8 --- /dev/null +++ b/clean/dx12/kernels/fg_full_blend.hlsl @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): the Full blend (presets A and B) with net2's input tensors, as +// clean/fg/reference/stages_full.py g4_full_blend, bit for bit. Built only when --only names it. +// +// 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, 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). +// 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_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 +// @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) + 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 +#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]. + 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(); +#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; + 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; + 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 + 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 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); + const float bx = emB ? 0.0f : wg_h2f_hi(wb.x), by = emB ? 0.0f : wg_h2f_lo(wb.x); + const float eA = emA ? 1.0f : 0.0f, eB = emB ? 1.0f : 0.0f; + const float ub = u + bx, vb = vv + by, ua = u + ax, va = vv + ay; + const int pi = py * Wo + px; + 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; + [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, qbx - qu.x, qu.x); + float3 x1rgb = mad(w.y, mad(eA, cP - cQ, cQ) - Q0, Q0); + 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); + x0rgb = mad(x0rgb, 1.0f - Up.w, Up.xyz); + x1rgb = mad(x1rgb, 1.0f - Uc.w, Uc.xyz); + const float e = fgf_sat(wg_div(abs(Up.z - Uc.z) + (abs(Up.x - Uc.x) + abs(Up.y - Uc.y)), 3.0f)); + const float eps = asfloat(0x34000000u); // 2^-23 + if (Up.w > eps) x0a = e; + if (Uc.w > eps) x1a = e; + hole = hole && Up.w < eps && Uc.w < eps; + } + 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; + } + { + v8f pv; + [unroll] for (uint c = 0; c < 8u; ++c) pv.v[c] = fgf_opq(v[c]); + 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 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); + const uint kk = (uint)(k * k); + 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 < 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)); + } + } + } + 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); +#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/dx12/kernels/fg_lite_blend.hlsl b/clean/dx12/kernels/fg_lite_blend.hlsl new file mode 100644 index 00000000..cdec0246 --- /dev/null +++ b/clean/dx12/kernels/fg_lite_blend.hlsl @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96), light path: the light candidate blend of preset C (clean/fg/reference/lite.py +// lite_blend). One lane per frame pixel; writes (r, g, b, 1) as float16 x 4 at the output's base offset. flag2: the +// 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. +// 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_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 +#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 +#ifndef FG_TILE +#define FG_TILE 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 + +#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) +{ + return px >= 0.0f && px < (float)(wo - 1u) && py >= 0.0f && py < (float)(ho - 1u); +} + +float3 fg_correct(float3 c, float alpha, float2 uv, float u, float v, bool empty, float4 P0, float4 Q0, uint L, + float3 own) +{ + 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)); + float s = fg_adiv(alpha - 0.5f, asfloat(0x3EE66666u)); + s = s <= 0.0f ? 0.0f : (s >= 1.0f ? 1.0f : s); + const float g = fg_mul(fg_mul(s, s), 3.0f - (s + s)); + ok = ok && g > 0.0f; + 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 = 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; + const float3 corr = mad(g.xxx, float3(fg_sat(tgt.x), fg_sat(tgt.y), fg_sat(tgt.z)) - c, c); + return ok ? corr : c; +} + +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; +#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; + 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; + const float4 P0 = fg_texel(cp, 4u, idx), Q0 = fg_texel(cc, 4u, idx); + const float t = asfloat(tbits); + const float2 uvP = float2(u + B.x, v + B.y), uvQ = float2(u + A.x, v + A.y); + 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); + const float3 ncQ = fg_correct(cQ, sQ.w, uvQ, u, v, eA, P0, Q0, lc, Q0.xyz); + cP = ncP; + cQ = ncQ; + } + const float fB = eB ? 1.0f : 0.0f, fA = eA ? 1.0f : 0.0f; +#if FG_MUT + const float3 a = cP; +#else + const float3 a = mad(fB.xxx, cQ - cP, cP); +#endif + const float3 b = mad(fA.xxx, cP - cQ, cQ); + const float3 rP = mad(a - P0.xyz, w.xxx, P0.xyz); + const float3 rQ = mad(b - Q0.xyz, w.yyy, Q0.xyz); + float3 o = mad(rQ - rP, t.xxx, rP); + if (flag1 != 0u) + { + const float4 upv = fg_texel(up, 4u, idx), ucv = fg_texel(uc, 4u, idx); + 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)); +#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 new file mode 100644 index 00000000..49b9c48e --- /dev/null +++ b/clean/dx12/kernels/fg_lite_g.hlsl @@ -0,0 +1,319 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96), light path: G2 intermediate-time scatter and G3 blend weights (clean/fg/reference/ +// stages_common.py interm_scatter, interm_inputs, blend_weights). D3D12 only. +// +// fg_lite_interm: one lane per scatter-grid pixel; pass 0 (A): displacement (1 - t) (Mv W1, Mv H1) and keys from Zc, +// written unless both the truncated-key and the displacement test fail; pass 1 (B): displacement t F and keys from +// 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 +// @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" + +#if FG_K == 1 +WG_ARGS_BEGIN + uint pass_, src, zimg, target, w1, h1, tbits, s_k, inverted, t2, tau; +WG_ARGS_END + +float2 fg_disp(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(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); +} + +#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 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) + { +#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; + 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 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; +#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 + ok = dd < thr; + if (ok) fg_atomic_min64(target, (uint)(ty * (int)w1 + tx), hi, lo); + } +} +#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; +WG_ARGS_END + +WG_KERNEL(fg_lite_weights) +{ + FG_SETUP(); + const uint idx = wg_block_id() * 256u + wg_lane_id(); + if (idx >= w1 * h1) return; + const uint x = idx % w1, y = idx / w1; + 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; + fg_st_h2(wout, idx, fg_sigmoid(A1, A0), fg_sigmoid(B1, B0)); +} +#endif diff --git a/clean/dx12/kernels/fg_lite_menu.hlsl b/clean/dx12/kernels/fg_lite_menu.hlsl new file mode 100644 index 00000000..eac0cb74 --- /dev/null +++ b/clean/dx12/kernels/fg_lite_menu.hlsl @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96), light path: menu detection and the menu output stage (clean/fg/reference/ +// stages_common.py detect_* and menu_output). D3D12 only. Built only when --only names them. +// +// fg_lite_detect: one workgroup of 256 lanes, 8 points each = the 64 x 32 grid; kind 0 = UI alpha > threshold, kind 1 = +// hudless opacity > 0.7; lane 0 decides (count > fraction * 2048, or > 0.3 * 2048), writes DetRes (latch, detected, +// alpha detector's second value, 0) from the previous DetRes, and disable = base | (latch != 0). +// fg_lite_menu_output: one lane per pixel of the out extent: DetRes[0] != 0 -> the current colour texel; else +// DetRes[2] != 0 -> rgb = C + (G - H) (1 - a), alpha kept; else nothing. +// +// @wg-kernel fg_lite_detect co=- block=256 wave=32 args=u,p,u,u,u,u,u,u,u,u,u,p,u,u,u,u,u,u,u,u,u,u,u,u,u,p,p,u,u defines=FG_K=1 +// @wg-kernel fg_lite_menu_output co=- block=256 wave=32 args=p,p,u,u,u,p,u,u,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 defines=FG_K=2 +#include "wg_platform.hlsli" +#include "fg_lite_common.hlsli" + +#if FG_K == 1 +WG_ARGS_BEGIN + uint kind, img, img_w, img_kind, channel, x0, y0, wr, hr, thr, frac; + uint hud, hud_w, hud_h, hud_same; + FG_REGION_ARGS(h) + uint detres, disable, base, hyst_off; +WG_ARGS_END + +groupshared uint fg_count; + +WG_KERNEL(fg_lite_detect) +{ + FG_SETUP(); + const uint lane = wg_lane_id(); + if (lane == 0u) fg_count = 0u; + GroupMemoryBarrierWithGroupSync(); + uint n = 0u; + FgRegion hr_ = FG_REGION(h); + [loop] for (uint k = 0u; k < 8u; ++k) + { + const uint s = lane * 8u + k, j = s % 64u, kk = s / 64u; + const uint x = x0 + ((wr - 1u) * j) / 63u, y = y0 + ((hr - 1u) * kk) / 31u; + if (kind == 0u) + { + const float a = fg_texel(img, img_kind, y * img_w + x)[channel]; + n += a > asfloat(thr) ? 1u : 0u; + } + else + { + const float3 c = fg_texel(img, 4u, y * img_w + x).rgb; + float3 hc; + if (hud_same != 0u) + hc = fg_read_int(hud, 4u, (int)hud_w, (int)hud_h, (int)x, (int)y).rgb; + else + { + const float u = fg_sat(fg_adiv((float)(x - x0) + 0.5f, (float)wr)); + const float v = fg_sat(fg_adiv((float)(y - y0) + 0.5f, (float)hr)); + const float2 XY = fg_region_xy(hr_, u, v, false); + hc = fg_read_linear(hud, 4u, (int)hud_w, (int)hud_h, XY.x, XY.y).rgb; + } + float m[3]; + [unroll] for (uint q = 0u; q < 3u; ++q) + { + const float dl = hc[q] - c[q]; + const float a = fg_adiv(dl, hc[q] + 1e-10f); + const float b = fg_adiv(dl, fg_opq(hc[q] - 1.0f) - 1e-10f); + m[q] = max(a, b); + } + n += max(max(m[0], m[1]), m[2]) > 0.7f ? 1u : 0u; + } + } + InterlockedAdd(fg_count, n); + GroupMemoryBarrierWithGroupSync(); + if (lane != 0u) return; + const float f = kind == 0u ? asfloat(frac) : 0.3f; + const bool detected = (float)fg_count > fg_mul(f, 2048.0f); + const uint prev1 = wg_ld32(detres, 4u); + const uint latch = detected ? 0xFFFFFFFFu : (hyst_off != 0u ? 0u : (prev1 != 0u ? 0xFFFFFFFFu : 0u)); + const uint d1 = detected ? 1u : 0u; + const uint d2 = kind == 0u ? (hyst_off != 0u ? 0u : d1) : 0u; + wg_st32(detres, 0u, latch); + wg_st32(detres, 4u, d1); + wg_st32(detres, 8u, d2); + wg_st32(detres, 12u, 0u); + wg_st32(disable, 0u, base | (latch != 0u ? 1u : 0u)); +} +#endif + +#if FG_K == 2 +WG_ARGS_BEGIN + uint detres, colour, cstride, cbx, cby, outp, ostride, ox, oy, wo, ho; + uint hud, hud_w, hud_h; + FG_REGION_ARGS(h) + uint alpha, a_w, a_h, a_kind, a_ch; + FG_REGION_ARGS(a) +WG_ARGS_END + +WG_KERNEL(fg_lite_menu_output) +{ + FG_SETUP(); + const uint idx = wg_block_id() * 256u + wg_lane_id(); + if (idx >= wo * ho) return; + const uint x = idx % wo, y = idx / wo; + const uint oi = (oy + y) * ostride + ox + x; + if (wg_ld32(detres, 0u) != 0u) + { + wg_st64(outp, oi * 8u, wg_ld64(colour, ((cby + y) * cstride + cbx + x) * 8u)); + return; + } + if (wg_ld32(detres, 8u) == 0u) return; + const float u = fg_centre(x, wo), v = fg_centre(y, ho); + const float4 c = fg_texel(colour, 4u, (cby + y) * cstride + cbx + x); + const float4 g = fg_texel(outp, 4u, oi); + const float2 HX = fg_region_xy(FG_REGION(h), u, v, false); + const float4 hc = fg_read_linear(hud, 4u, (int)hud_w, (int)hud_h, HX.x, HX.y); + const float2 AX = fg_region_xy(FG_REGION(a), u, v, false); + 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)); + 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 new file mode 100644 index 00000000..676af76a --- /dev/null +++ b/clean/dx12/kernels/fg_lite_net1io.hlsl @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96), light path: R7 hole mask, R8 quality image and R9 net1 input packer / output unpacker +// (clean/fg/reference/stages_common.py hole_mask, quality_init, net1_input, net1_output). D3D12 only. +// +// fg_lite_hole_mask: (after Hc := 1) one lane per net1-grid pixel: F at the pixel centre (nearest, scatter grid), +// divided by the scatter grid size, times the net1 grid size; Hc := 0 at the four targets. +// 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). +// 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. +// +// @wg-kernel fg_lite_hole_mask co=- block=256 wave=32 args=p,u,u,p,u,u defines=FG_K=1 +// @wg-kernel fg_lite_quality_init co=- block=256 wave=32 args=p,p,u defines=FG_K=2 +// @wg-kernel fg_lite_net1_input co=- block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u,u defines=FG_K=3 +// @wg-kernel fg_lite_net1_output co=- block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u,u,u,u,u,u,u defines=FG_K=4 +#include "wg_platform.hlsli" +#include "fg_lite_common.hlsli" + +#if FG_K == 1 +WG_ARGS_BEGIN + uint fin, w1, h1, hc, wd, hd; +WG_ARGS_END + +WG_KERNEL(fg_lite_hole_mask) +{ + FG_SETUP(); + const uint idx = wg_block_id() * 256u + wg_lane_id(); + if (idx >= wd * hd) return; + const int x = (int)(idx % wd), y = (int)(idx / wd); + const float u = fg_centre((uint)x, wd), v = fg_centre((uint)y, hd); + const float4 m = fg_read_nearest(fin, 2u, (int)w1, (int)h1, u, v); + const float mx = fg_mul(fg_adiv(m.x, (float)w1), (float)wd), my = fg_mul(fg_adiv(m.y, (float)h1), (float)hd); + 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)wd && ty >= 0 && ty < (int)hd) wg_st16(hc, (uint)(ty * (int)wd + tx) * 2u, 0u); + } +} +#endif + +#if FG_K == 2 +WG_ARGS_BEGIN + uint dc, qc, n; +WG_ARGS_END + +WG_KERNEL(fg_lite_quality_init) +{ + FG_SETUP(); + const uint idx = wg_block_id() * 256u + wg_lane_id(); + if (idx >= n) return; + const float4 c = fg_texel(dc, 4u, idx); + fg_st_h2(qc, idx, fg_sat(fg_adiv(fg_opq(c.x + c.y) + c.z, 3.0f)), 0.0f); +} +#endif + +#if FG_K == 3 +WG_ARGS_BEGIN + uint ld, dc, dp, fin, mv, eimg, hc, hp, qp, mimg, cells, qc, om; + uint wd, hd, w1, h1, W0, H0, pad_l, pad_t, cs, ps; +WG_ARGS_END + +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)); +} + +void fg_cell_store(uint X, uint Y, uint ch, float 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 lane = wg_lane_id(), block = wg_block_id(); + const uint idx = block * 256u + lane; + const uint gw = 2u * W0, gh = 2u * H0; + 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 (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); + 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; + 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); +} +#endif + +#if FG_K == 4 +WG_ARGS_BEGIN + uint n1, om, um, ump, na, nb, mimg; + 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(); + const uint idx = wg_block_id() * 256u + wg_lane_id(); + if (idx >= wd * hd) return; + const uint x = idx % wd, y = idx / wd; + const uint ncx = max(wd / 2u, 1u), ncy = max(hd / 2u, 1u); + const uint cx = pad_l + min(x >> 1, ncx - 1u), cy = pad_t + min(y >> 1, ncy - 1u); + const uint q = 2u * (y & 1u) + (x & 1u), cell = cy * W0 + cx; + float o[4]; + [unroll] for (uint i = 0u; i < 4u; ++i) o[i] = wg_h2f(wg_ld16(n1, ((4u * i + q) * cs + cell * ps) * 2u)); + const float omv = fg_texel(om, 1u, idx).x; + o[0] = mad(FG_PUSH - o[0], omv, o[0]); + o[2] = mad(FG_PUSH - o[2], omv, o[2]); + const float mm = fg_sigmoid(o[2], o[3]); + if (ui_forcing != 0u) + { + 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; } + } + // 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 new file mode 100644 index 00000000..8a5b78d2 --- /dev/null +++ b/clean/dx12/kernels/fg_lite_p2c.hlsl @@ -0,0 +1,465 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96), light path: R6, the previous-to-current chain (clean/fg/reference/stages_common.py +// p2c_*). D3D12 only. +// +// fg_lite_p2c_scatter: one lane per current scatter-grid pixel: camera consistency (ClipToPrevClip), the camera mask +// Kc, and the payload (depth key bits 31..1, consistent bit, float16 motion in pixels) by signed 64-bit atomic +// minimum (SM 6.6) into S at up to four targets. +// fg_lite_p2c_unpack: one lane per previous scatter-grid pixel: F (float16 x 2), E, the flag word and the float32 +// vector Vf. +// fg_lite_p2c_inpaint: the hole rule over the 5 x 5 neighbourhood of bit 1 -> G = (w ? 2 : 0) | (inpaint ? 1 : 0). +// fg_lite_p2c_pull: one pull level: mode 0 from the base pixels (G, Vf), 1 from the previous level's float32 sums, 2 +// 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 +// @wg-kernel fg_lite_p2c_inpaint co=- block=256 wave=32 args=p,p,u,u defines=FG_K=3 +// @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 +// @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" + +#if FG_K == 1 +WG_ARGS_BEGIN + uint zc, mv, sbuf, kc, w1, h1; + uint m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15; + uint t1, t2, s_k, inverted, stepx, stepy; +WG_ARGS_END + +WG_KERNEL(fg_lite_p2c_scatter) +{ + 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); + const float u = fg_centre((uint)x, w1), v = fg_centre((uint)y, h1); + const float3 zo = fg_unpack_depth(wg_ld32(zc, idx * 4u), asfloat(stepx), asfloat(stepy)); + const float kap = fg_depth_key(zo.x, asfloat(s_k), inverted); + const float3 cam = fg_camera(u + zo.y, v + zo.z, zo.x, fg_f(m0), fg_f(m1), fg_f(m3), fg_f(m4), fg_f(m5), fg_f(m7), + fg_f(m8), fg_f(m9), fg_f(m11), fg_f(m12), fg_f(m13), fg_f(m15), w1, h1); + const float4 mvv = fg_texel(mv, 5u, idx); + const float mx = fg_mul(mvv.x, (float)w1), my = fg_mul(mvv.y, (float)h1); + const float msq = fg_sq(mx, my); + const float dd = fg_sq(mx - cam.x, my - cam.y); + const bool cons = !(cam.z <= 0.0f) && dd <= max(fg_adiv(msq, asfloat(t1)), 1.0f); + 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 = (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; + [unroll] for (uint e = 0u; e < 4u; ++e) + { + const int ex = (int)(e >> 1), ey = (int)(e & 1u); + const int tx = bx + ex * sx, ty = by + ey * sy; + bool ok = tx >= 0 && tx < (int)w1 && ty >= 0 && ty < (int)h1; + if (e != 0u) + { + const float4 nb = fg_read_int(mv, 5u, (int)w1, (int)h1, x + ex * sx, y + ey * sy); + ok = ok && fg_sq(fg_mul(nb.x, (float)w1) - mx, fg_mul(nb.y, (float)h1) - my) < thr2; + } + if (ok) fg_atomic_min64(sbuf, (uint)(ty * (int)w1 + tx), hi, lo); + } +} +#endif + +#if FG_K == 2 +WG_ARGS_BEGIN + uint sbuf, zp, kp, mv, fo, eo, flo, vfo, w1, h1; + uint m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15; + uint s_k, inverted, stepx, stepy, kmax, tau; +WG_ARGS_END + +WG_KERNEL(fg_lite_p2c_unpack) +{ + FG_SETUP(); + const uint idx = wg_block_id() * 256u + wg_lane_id(); + if (idx >= w1 * h1) return; + const uint x = idx % w1, y = idx / w1; + const float u = fg_centre(x, w1), v = fg_centre(y, h1); + const uint2 e64 = wg_ld64(sbuf, idx * 8u); + const bool empty = e64.x == 0x7FFFFFFFu && e64.y == 0x7FFFFFFFu; + const float sxv = empty ? 0.0f : f16tof32(e64.x >> 16), syv = empty ? 0.0f : f16tof32(e64.x & 0xffffu); + const float keyE = asfloat(e64.y & 0xFFFFFFFEu); + const bool cbit = (e64.y & 1u) != 0u; + const float3 zo = fg_unpack_depth(wg_ld32(zp, idx * 4u), asfloat(stepx), asfloat(stepy)); + const float kpv = fg_texel(kp, 1u, idx).x; + const float3 cam = fg_camera(u + zo.y, v + zo.z, zo.x, fg_f(m0), fg_f(m1), fg_f(m3), fg_f(m4), fg_f(m5), fg_f(m7), + fg_f(m8), fg_f(m9), fg_f(m11), fg_f(m12), fg_f(m13), fg_f(m15), w1, h1); + float kap = fg_depth_key(zo.x, asfloat(s_k), inverted); + kap = kpv == 0.0f ? fg_mul(kap, cam.z) : kap; + const float km = asfloat(kmax); + const float kE = keyE <= 0.0f ? 0.0f : (km <= keyE ? km : keyE); + const float kP = kap <= 0.0f ? 0.0f : (kap >= km ? km : kap); + const bool mismatch = empty || abs(kE - kP) > asfloat(tau); + const float gu = u + fg_adiv(cam.x, (float)w1), gv = v + fg_adiv(cam.y, (float)h1); + const float4 g = fg_read_nearest(mv, 5u, (int)w1, (int)h1, gu, gv); + const float rx = mad(g.x, (float)w1, cam.x), ry = mad(g.y, (float)h1, cam.y); + const bool dynamic = !(kpv == 0.0f); + const bool use_cam = cbit || mismatch || fg_sq(rx, ry) < 0.25f; + const float vx = dynamic ? -sxv : (use_cam ? cam.x : -sxv); + const float vy = dynamic ? -syv : (use_cam ? cam.y : -syv); + fg_st_h2(fo, idx, vx, vy); + fg_st_h1(eo, idx, empty ? 1.0f : 0.0f); + wg_st32(flo, idx * 4u, (dynamic ? 1u : 0u) | ((dynamic && mismatch) ? 2u : 0u) | (empty ? 4u : 0u)); + wg_st64(vfo, idx * 8u, uint2(asuint(vx), asuint(vy))); +} +#endif + +#if FG_K == 3 +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]; + +WG_KERNEL(fg_lite_p2c_inpaint) +{ + FG_SETUP(); + 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 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 j = 0; j < 3; ++j) + [unroll] for (int i = 0; i < 3; ++i) + { + 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 || (j == 2 && i == 2)); // mutant: the last window is not required +#else + inp = inp && w; +#endif + } + const bool dyn = (wg_ld32(fl, idx * 4u) & 1u) != 0u; + wg_st32(gout, idx * 4u, ((dyn && !inp) ? 2u : 0u) | (inp ? 1u : 0u)); +} +#endif +#endif + +#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) +{ + if (cx >= (int)ws || cy >= (int)hs) return float3(0.0f, 0.0f, 0.0f); + const uint i = (uint)cy * ws + (uint)cx; + if (mode == 0u) + { + const float w = (float)((wg_ld32(srca, i * 4u) >> 1) & 1u); + const float4 vf = fg_texel(srcb, 5u, i); + return float3(fg_mul(w, vf.x), fg_mul(w, vf.y), w); + } + if (mode == 1u) return asfloat(uint3(wg_ld32(srca, i * 12u), wg_ld32(srca, i * 12u + 4u), wg_ld32(srca, i * 12u + 8u))); + const float4 e = fg_texel(srca, 3u, i); + return float3(fg_mul(e.x, e.z), fg_mul(e.y, e.z), e.z); +} + +float3 fg_pull_sum(int X, int Y) +{ + 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)); + } + fg_pull_element(elem_out, idx, s, asfloat(nbits)); +#endif +} +#endif + +#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) +{ + const int px = qx >> 1, py = qy >> 1; + const int nx = clamp(px + ((qx & 1) != 0 ? 1 : -1), 0, pw - 1); + const int ny = clamp(py + ((qy & 1) != 0 ? 1 : -1), 0, ph - 1); + const float4 t[4] = { fg_texel(parent, 3u, (uint)(py * pw + px)), fg_texel(parent, 3u, (uint)(py * pw + nx)), + fg_texel(parent, 3u, (uint)(ny * pw + px)), fg_texel(parent, 3u, (uint)(ny * pw + nx)) }; + const float k[4] = { 0.5625f, 0.1875f, 0.1875f, 0.0625f }; + const float zero = asfloat(fg_z_); + float ws = zero, v0 = zero, v1 = zero; + [unroll] for (uint i = 0u; i < 4u; ++i) + { + ws = mad(t[i].z, k[i], ws); + v0 = mad(fg_mul(t[i].x, t[i].z), k[i], v0); + v1 = mad(fg_mul(t[i].y, t[i].z), k[i], v1); + } + const float den = fg_med3(ws, FG_WEIGHT_FLOOR, 1.0f); + return float3(fg_adiv(v0, den), fg_adiv(v1, den), ws); +} +#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; +WG_ARGS_END + +WG_KERNEL(fg_lite_p2c_push) +{ + FG_SETUP(); + const uint idx = wg_block_id() * 256u + wg_lane_id(); + 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 + +#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) +{ + 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_lite_r3.hlsl b/clean/dx12/kernels/fg_lite_r3.hlsl new file mode 100644 index 00000000..de62a5ee --- /dev/null +++ b/clean/dx12/kernels/fg_lite_r3.hlsl @@ -0,0 +1,485 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96), light path: R3, downsample to the net1 grid with the UI estimate and the colour alpha +// (clean/fg/reference/stages_common.py downsample_ui). One lane per d x d block (d = FG_D, 2 or 4) of the frame: +// every frame pixel of the block writes Cc (and Uc in case U, Lc with Lite flag 2 in cases A / H); blocks inside the +// net1 grid write Dc (block mean of the source colour), Ld (luma-change minima: min, or the mean of the four 2 x 2 +// minima for d = 4) and Um (any UI flag, cases A / H). Pixels outside the frame contribute zeros. D3D12 only. +// flags: bit 0 F1 (UI-recomposition path or Lite flag 1), 1 UI alpha active, 2 hudless active, 3 Lite flag 1, +// 4 Lite flag 2. +// +// @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" + +WG_ARGS_BEGIN + uint colour, cw, cbx, cby; + uint hud, hw, hh; + FG_REGION_ARGS(h) + uint alpha, aw, ah, akind, ach; + FG_REGION_ARGS(a) + uint cp, cc, uc, lc, dc, ld, um; + 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)); } + +#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, uint mode, out float3 s, out float diff, out bool flag) +{ + const uint pi = y * wo + x; + 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), 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; + if (caseU != 0u) + { + const float ap = L1 ? (fg_finite(al) ? fg_sat(al) : 1.0f) : al; + const float apm1 = ap - 1.0f; + const float3 U = float3(mad(hc.x, apm1, c.x), mad(hc.y, apm1, c.y), mad(hc.z, apm1, c.z)); + const bool nf = !fg_finite3(U); + const float mn = min(min(U.x, U.y), U.z); + const bool low = U.x < c.x - (hc.x + hc.x) || U.y < c.y - (hc.y + hc.y) || U.z < c.z - (hc.z + hc.z); + const bool bad = ap == 1.0f || nf || (!nf && mn <= -1.0f) || low; + const bool zero = L1 && ap == 0.0f; + float4 ucv = bad ? float4(c.xyz, 1.0f) : float4(U, ap); + ucv = zero ? float4(0.0f, 0.0f, 0.0f, 0.0f) : ucv; + fg_st_h4(uc, pi, ucv); + ccv = float4(hc.xyz, ap); + s = hc.xyz; + } + else if (caseA != 0u) + { + flag = al > asfloat(0x3ECCCCCDu); + ccv = float4(c.xyz, L2 ? (flag ? 1.0f : 0.0f) : al); + if (L2) fg_st_h4(lc, pi, float4(hc.xyz, 0.0f)); + s = c.xyz; + } + else if (caseH != 0u) + { + const float3 dd = abs(c.xyz - hc.xyz); + flag = max(max(dd.x, dd.y), dd.z) > asfloat(0x3D8F5C29u); + ccv = float4(c.xyz, L2 ? (flag ? 1.0f : 0.0f) : 0.0f); + if (L2) fg_st_h4(lc, pi, float4(hc.xyz, 0.0f)); + s = c.xyz; + } + else + { + ccv = float4(c.xyz, 0.0f); + s = c.xyz; + } + 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 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); + } + } + else + { + fg_r3_block(X, Y, mode, sum, diff, any_flag); + } +#if FG_D == 4 + diff = fg_mul(diff, 0.25f); +#endif + 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 new file mode 100644 index 00000000..ff6dffc7 --- /dev/null +++ b/clean/dx12/kernels/fg_lite_r4.hlsl @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96), light path: R4, motion and depth processing (clean/fg/reference/stages_common.py +// mvec_process). One lane per scatter-grid pixel: the nearest-depth sample of five (centre and the four diagonal depth +// texels, region reads with the -2^-23 bias), its 32-bit packed depth Zc, and the motion of that sample times the +// 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) + uint motion, mw, mh; + FG_REGION_ARGS(m) + uint zc, mv, w1, h1, inverted, s_k, scx, scy; +WG_ARGS_END + +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); + const float sk = asfloat(s_k); + float ox[5] = { 0.0f, -dx, dx, -dx, dx }; + float oy[5] = { 0.0f, -dy, -dy, dy, dy }; + float b = 0.0f, kb = 0.0f; + uint sel = 0u; + [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, 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); +#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_lite_util.hlsl b/clean/dx12/kernels/fg_lite_util.hlsl new file mode 100644 index 00000000..b5ee9bb2 --- /dev/null +++ b/clean/dx12/kernels/fg_lite_util.hlsl @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96), light path: buffer fills and 4-channel copies (clean/fg/reference/pipeline.py "clear", +// "fill64", "prefill", "final_copy"). D3D12 only (no HIP counterpart). Built only when --only names them. +// +// fg_lite_fill16: n16 float16-sized units of dst := a pattern of `period` (1, 2 or 4) units p0..p3, unit i taking +// p[i % period]; each lane writes 8 units (one 16-byte store when the 8 units are inside the buffer). +// 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) +{ + FG_SETUP(); + const uint first = (wg_block_id() * 256u + wg_lane_id()) * 8u; + if (first >= n16) return; + if (first + 8u <= n16) + { + uint4 w; + w.x = (fg_unit(first) & 0xffffu) | (fg_unit(first + 1u) << 16); + w.y = (fg_unit(first + 2u) & 0xffffu) | (fg_unit(first + 3u) << 16); + w.z = (fg_unit(first + 4u) & 0xffffu) | (fg_unit(first + 5u) << 16); + w.w = (fg_unit(first + 6u) & 0xffffu) | (fg_unit(first + 7u) << 16); + wg_st128(dst, first * 2u, w); + return; + } + [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 + uint dst, dstride, dx0, dy0, src, sstride, sx0, sy0, cw, ch; +WG_ARGS_END + +WG_KERNEL(fg_lite_copy4) +{ + FG_SETUP(); + const uint idx = wg_block_id() * 256u + wg_lane_id(); + if (idx >= cw * ch) return; + const uint x = idx % cw, y = idx / cw; + wg_st64(dst, ((dy0 + y) * dstride + dx0 + x) * 8u, wg_ld64(src, ((sy0 + y) * sstride + sx0 + x) * 8u)); +} +#endif diff --git a/clean/dx12/kernels/fg_mconv.hlsl b/clean/dx12/kernels/fg_mconv.hlsl index 9f337998..473c173c 100644 --- a/clean/dx12/kernels/fg_mconv.hlsl +++ b/clean/dx12/kernels/fg_mconv.hlsl @@ -2,33 +2,62 @@ // 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 +// 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 #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 +#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]; +#endif 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) @@ -38,88 +67,297 @@ 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 v8f d = wg_wmma_f16(av, bv, c); - hp = wg_to_f16_ags(d); - c = fg_widen(hp); + 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 + +#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]) +{ + 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) +{ + 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) { +#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; 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_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 + 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); } +#endif [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_conv.hlsl b/clean/dx12/kernels/fg_net2_conv.hlsl new file mode 100644 index 00000000..966f975a --- /dev/null +++ b/clean/dx12/kernels/fg_net2_conv.hlsl @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): net2's 3 x 3 convolution layer (clean/fg/reference/net2.py conv3 and its post-ops), exact, +// one output element per lane. Tensors are float16 [H][W][C] (channel innermost) with a channel stride and offset, so a +// launch can read one group of a wider tensor and write one channel range of a wider output. +// +// x: input at the conv grid H x W, channels x[(y W + x) in_cs + in_co + c] for c < cin (channels cin .. cw - 1 read 0); +// w: weights [cout][3][3][cw] (out, ky, kx, in); b: bias [cout]. The lane computes weight output o = co_lo + j +// (j < co_n): float16 accumulator from b[o]; chunks per tap (ky, kx) in row-major order, inside a tap ascending blocks +// of 16 weight channels (the last may be shorter); each chunk exact with one rounding (fg_exact16.h); zero border. +// Post-ops in order: leaky ReLU (leaky = 1), clamp to [-6, 6] when o >= clamp_from, then the residual: +// res 0 none, 1 h(v + 0), 2 fma(res_mul, skip[(y W + x) skip_cs + skip_co + j], v) (res_mul float16 bits). pool = 1: +// the conv runs at H x W and the output is the 2 x 2 average h(h(h(h(a00 + a01) + a10) + a11) * 0.25) at H/2 x W/2. +// The result goes to y[(oy Wo + ox) out_cs + out_co + j]. Built only when --only names it. +// +// @wg-kernel fg_net2_conv co=fg_net2.co block=256 wave=32 args=p,p,p,p,p,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u +#include "wg_platform.hlsli" +#include "fg_net2.hlsli" + +WG_ARGS_BEGIN + uint x, w, b, y, skip; // pointers (arena byte offsets) + int in_cs, in_co, cin, cw, co_lo, co_n, out_cs, out_co, H, W, pool, leaky, clamp_from, res; + uint res_mul; + int skip_cs, skip_co; +WG_ARGS_END + +uint fg2_conv_at(int o, int cy, int cx) +{ + uint acc = wg_ld16(b, (uint)o * 2u); + const int nb = (cw + 15) / 16; + [loop] for (int t = 0; t < 9; ++t) { + const int ky = t / 3; + const int kx = t - ky * 3; + const int sy = cy + ky - 1; + const int sx = cx + kx - 1; + const bool inside = sy >= 0 && sy < H && sx >= 0 && sx < W; + const uint wrow = (uint)(((o * 3 + ky) * 3 + kx) * cw); + const uint xrow = inside ? (uint)((sy * W + sx) * in_cs + in_co) : 0u; + [loop] for (int cb = 0; cb < nb; ++cb) { + FgAcc s = fg_acc_begin(acc); + const int c1 = min(cw, cb * 16 + 16); + [loop] for (int c = cb * 16; c < c1; ++c) { + const uint wv = wg_ld16(w, (wrow + (uint)c) * 2u); + uint xv = 0u; // outside the grid or past cin: 0 (0 * inf is NaN) + if (inside && c < cin) xv = wg_ld16(x, (xrow + (uint)c) * 2u); + s = fg_acc_add(s, wv, xv); + } + acc = fg_acc_end(s); + } + } + return acc; +} + +WG_KERNEL(fg_net2_conv) +{ + WG_SETUP(); + const int Ho = pool != 0 ? H / 2 : H; + const int Wo = pool != 0 ? W / 2 : W; + const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); + if (idx >= Ho * Wo * co_n) return; + const int pix = idx / co_n; + const int j = idx - pix * co_n; + const int oy = pix / Wo; + const int ox = pix - oy * Wo; + const int o = co_lo + j; + const int npos = pool != 0 ? 4 : 1; + uint sum = 0u; + [loop] for (int k = 0; k < npos; ++k) { + const int cy = pool != 0 ? 2 * oy + (k >> 1) : oy; + const int cx = pool != 0 ? 2 * ox + (k & 1) : ox; + uint v = fg2_conv_at(o, cy, cx); + if (leaky != 0) v = fg2_leaky(v); + if (o >= clamp_from) v = fg2_clamp6(v); + if (res == 1) v = fg2_plus0(v); + if (res == 2) v = fg2_fma(res_mul, wg_ld16(skip, (uint)((cy * W + cx) * skip_cs + skip_co + j) * 2u), v); + sum = k == 0 ? v : fg2_add(sum, v); + } + if (pool != 0) sum = fg2_mul(sum, FG2_QUARTER16); + wg_st16(y, (uint)((oy * Wo + ox) * out_cs + out_co + j) * 2u, sum); +} diff --git a/clean/dx12/kernels/fg_net2_mconv.hlsl b/clean/dx12/kernels/fg_net2_mconv.hlsl new file mode 100644 index 00000000..8a13f57e --- /dev/null +++ b/clean/dx12/kernels/fg_net2_mconv.hlsl @@ -0,0 +1,811 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): net2's 3 x 3 convolution on gfx12's matrix instructions (tier B of the fast path; the +// exact kernels fg_net2_conv.hlsl / fg_net2_up2.hlsl stay the validation path). Launch interface of fg_net2_conv (channel +// stride and offset of the input, channel range of the output, the post-ops) plus two fusions, with the arithmetic of +// net1's tier B (fg_mconv.hlsl): one v_wmma_f32_16x16x16_f16 per spec chunk through the driver channel (wg_wmma_f16), +// the float16 accumulator from the bias as C, the whole fragment rounded to float16 after every chunk (wg_to_f16_ags = +// v_cvt_f16_f32, nearest even). Chunk order of net2 (FG-PART3 3.1): taps (ky, kx) in row-major order, inside a tap +// ascending blocks of 16 input channels; channels at or past cin read 0 (L1's 10 channels as 16, L14's 18 as 16 + 16 +// with zero weights). Not bit-exact to the CPU reference: the matrix unit's chunk sum is not the exact sum. Everything +// else is exact, the bits of fg_net2_conv / fg_net2_up2 computed 8 values at a time (fg_net2_fast.hlsli): leaky ReLU +// (leaky = 1), clamp to [-6, 6] for weight outputs o >= clamp_from, residual res 0 none, 1 h(v + 0), 2 fma(res_mul, +// 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 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). 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. +// +// 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. +// +// 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 +// (clean/fg/runner/fg_net2_mma.py swizzle); b: the bias padded to whole tiles. Driver rules (clean/dx12/README.md): +// every load of a tap before its first matrix call, branchless selects in the loads, the tap loop bound through an +// opaque zero (no forced unrolling), store pointers through wg_uniform(); the only branch before the matrix calls (a +// 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 +// @wg-kernel fg_net2_mconv_m2b2 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=2 +// @wg-kernel fg_net2_mconv_m2b4 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=4 +// @wg-kernel fg_net2_mconv_m1b4s 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=1,FG_NB=4 +// @wg-kernel fg_net2_mconv_m1b2s 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=1,FG_NB=2 +// @wg-kernel fg_net2_mconv_m1b1u 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 +// @wg-kernel fg_net2_mconv_m1b2u 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 +// @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_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" +#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) +#undef WG_KERNEL +#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) +#endif +#include "fg_net2.hlsli" + +#ifndef FG_MT +#define FG_MT 1 +#endif +#ifndef FG_NB +#define FG_NB 1 +#endif +#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 +#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; + 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_ZB_SETUP() +#endif +#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 +#include "fg_net2_fast.hlsli" + +// 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) || FG_PAIR) +#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) +{ + v8f r; + 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 uint4 hp) +{ + const v8f d = wg_wmma_f16(av, bv, fg_widen(hp)); + hp = wg_to_f16_ags(d); +} +// 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) +{ + uint m[4]; + [unroll] for (int d = 0; d < 4; ++d) { + const int c = c0 + 2 * d; + m[d] = select(c + 1 < cin, 0xffffffffu, select(c < cin, 0x0000ffffu, 0u)); + } + return uint4(m[0], m[1], m[2], m[3]); +} + +// 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_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); + 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]); + } + 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 (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) { + const bool kept = live && o0 + j >= q.lo && o0 + j < q.lo + q.n; + s8[j] = wg_ld16(q.sp, kept ? (uint)(e0 + o0 + j) * 2u : 0u); + } + 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; +} + +// stores the lane's 8 weight outputs o0 .. o0 + 7 of output pixel pix (those inside [lo, lo + n)) +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 (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) + if (o0 + v >= q.lo && o0 + v < q.lo + q.n) wg_st16(q.yp, (uint)(e0 + o0 + v) * 2u, fg_half(p, (uint)v)); + } +} + +#if FG_UP +// 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 + 1) * 18 * FG_TG; + 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 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; + } + } + 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 +#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; + 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 +#endif + +FgOut fg_output(int hj) +{ + FgOut q; + 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; + q.co = heads != 0 ? (out_cs == 0 ? 0 : out_co + q.lo) : out_co; + q.yp = (uint)wg_uniform((int)(hj == 0 || out_cs != 0 ? y : (hj == 1 ? y1 : y2))); + 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; + return q; +} + +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; + h16[mt][0] = fg_load_aligned8(FG_B, (uint)o0 * 2u); + h16[mt][1] = h16[mt][0]; + } +#if !FG_STAGE + uint4 cm[FG_NB]; + [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(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]; + 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(FG_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) { + // 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_STAGE + const int pp = (wrow + nt + ky) * 18 + n + kx; + [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, ~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(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). + { + 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 + +#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(); + 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; + 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. +#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); + fg_fused_output(hj, h16[0], px, py0, hh, packed); + } + } + 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_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 + + 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) { + const int o0 = (wt * FG_MT + mt4) * 16 + 8 * hh; + const uint4 r0 = fg_post8(q, h16[mt4][0], o0, py0, px, live0); + const uint4 r1 = fg_post8(q, h16[mt4][1], o0, py0 + 1, px, live1); + if (pool == 0) { + if (live0) fg_store8(q, py0 * W + px, o0, r0); + if (live1) fg_store8(q, (py0 + 1) * W + px, o0, r1); + } else { + // 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 +} +#endif diff --git a/clean/dx12/kernels/fg_net2_merge.hlsl b/clean/dx12/kernels/fg_net2_merge.hlsl new file mode 100644 index 00000000..a511c78e --- /dev/null +++ b/clean/dx12/kernels/fg_net2_merge.hlsl @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): net2's input merge (clean/fg/reference/net2.py merge_in), one output element 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 co=fg_net2.co block=256 wave=32 args=p,p,p,p,u,u +#include "wg_platform.hlsli" +#include "fg_net2.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) +{ + WG_SETUP(); + const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); + if (idx >= npx * 10) return; + const int p = idx / 10; + const int c = idx - p * 10; + uint v; + if (c < 4) v = wg_ld16(ib, (uint)(p * 4 + c) * 2u); + else if (c < 8) v = wg_ld16(ic, (uint)(p * 4 + c - 4) * 2u); + else if (c == 8) v = wg_ld16(ia, (uint)p * 2u); + else v = wg_f2h(asfloat(fbits)); + wg_st16(x, (uint)idx * 2u, v); +} 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_up2.hlsl b/clean/dx12/kernels/fg_net2_up2.hlsl new file mode 100644 index 00000000..1e4d4d8f --- /dev/null +++ b/clean/dx12/kernels/fg_net2_up2.hlsl @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): net2's 2x bilinear upsample with half-pixel centres (clean/fg/reference/net2.py up2), +// exact, one output element per lane. x [hi][wi][C] float16 -> y [2 hi][2 wi][C]. Per axis (single precision, exact here): +// s = (o - 0.5) * 0.5, i0 = trunc(s), i1 = trunc(s + 1), both n - 1 when i1 >= n, both 0 when s < 0, w1 = h(s - i0), +// w0 = h((i0 - s) + 1). top = fma(wx1, P01, h(wx0 P00)), bottom likewise on row y1, out = fma(wy1, bottom, h(wy0 top)), +// each fma with one float16 rounding (fg_net2.hlsli). Built only when --only names it. +// +// @wg-kernel fg_net2_up2 co=fg_net2.co block=256 wave=32 args=p,p,u,u,u +#include "wg_platform.hlsli" +#include "fg_net2.hlsli" + +WG_ARGS_BEGIN + uint x, y; // pointers (arena byte offsets) + int C, hi, wi; +WG_ARGS_END + +WG_KERNEL(fg_net2_up2) +{ + WG_SETUP(); + const int ho = 2 * hi; + const int wo = 2 * wi; + const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); + if (idx >= ho * wo * C) return; + const int pix = idx / C; + const int c = idx - pix * C; + const int oy = pix / wo; + const int ox = pix - oy * wo; + const Fg2Tap tx = fg2_up_tap(ox, wi); + const Fg2Tap ty = fg2_up_tap(oy, hi); + const uint p00 = wg_ld16(x, (uint)((ty.i0 * wi + tx.i0) * C + c) * 2u); + const uint p01 = wg_ld16(x, (uint)((ty.i0 * wi + tx.i1) * C + c) * 2u); + const uint p10 = wg_ld16(x, (uint)((ty.i1 * wi + tx.i0) * C + c) * 2u); + const uint p11 = wg_ld16(x, (uint)((ty.i1 * wi + tx.i1) * C + c) * 2u); + const uint top = fg2_fma(tx.w1, p01, fg2_mul(tx.w0, p00)); + const uint bot = fg2_fma(tx.w1, p11, fg2_mul(tx.w0, p10)); + wg_st16(y, (uint)idx * 2u, fg2_fma(ty.w1, bot, fg2_mul(ty.w0, top))); +} diff --git a/clean/dx12/kernels/fg_net2_upwarp.hlsl b/clean/dx12/kernels/fg_net2_upwarp.hlsl new file mode 100644 index 00000000..17fe5f5d --- /dev/null +++ b/clean/dx12/kernels/fg_net2_upwarp.hlsl @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): net2's head upsample (launch 15) and warp-merge (launch 16) in one launch for the fast +// path, exact: the bits of fg_net2_up2 on A4 / A1 / A3 and of fg_net2_warp, one pixel of the W x H grid per lane. +// - The three heads are 8 channels per half-resolution pixel (A4 0..3, A1, A3 0..2), upsampled together (fg_up8 of +// fg_net2_fast.hlsli) and written to U4 [H][W][4], U1 [H][W][1], U3 [H][W][3]. +// - The warp sample of fg_net2_warp (the same single-value operations for the sample point and the four weights), +// then the bilinear of Ib (by U4 0, 1) and Ic (by U4 2, 3) as one 8-value chain with a weight per value: +// value = fma(w11, P11, fma(w01, P10, fma(w10, P01, h(w00 P00)))) (fg_mul8v / fg_fma8v). +// - y [H][W][18] = the 8 warped values, U4, U1, Ia, U3, h(f) (fbits: f's single-precision bits). +// Every lane runs the conversions (a lane past the grid computes the last pixel and stores nothing). Ib, Ic +// [H][W][4], Ia [H][W][1]; A4 / A1 / A3 at H / 2 x W / 2. Built only when --only names it. +// +// @wg-kernel fg_net2_upwarp co=fg_net2_mma.co block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u +#include "wg_platform.hlsli" +#include "fg_net2.hlsli" + +WG_ARGS_BEGIN + uint ib, ic, ia, a4, a1, a3, u4, u1, u3, y; // pointers (arena byte offsets) + int W, H; + uint fbits; +WG_ARGS_END +#define FG_NATIVE_UP 1 +#include "fg_net2_fast.hlsli" + +#include "fg_net2_upwarp.hlsli" + +WG_KERNEL(fg_net2_upwarp) +{ + WG_SETUP(); + 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); + 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)); + if (live) { + 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_st128(y, (uint)p * 36u, val); + wg_st128(y, (uint)p * 36u + 16u, uint4(U.x, U.y, fg_half(U, 4u) | (iav << 16), + fg_half(U, 5u) | (fg_half(U, 6u) << 16))); + wg_st32(y, (uint)p * 36u + 32u, fg_half(U, 7u) | (hf << 16)); + } +} diff --git a/clean/dx12/kernels/fg_net2_warp.hlsl b/clean/dx12/kernels/fg_net2_warp.hlsl new file mode 100644 index 00000000..6b6f087d --- /dev/null +++ b/clean/dx12/kernels/fg_net2_warp.hlsl @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): net2's warp-merge (clean/fg/reference/net2.py warp_merge / warp_sample), exact, one output +// element per lane: y [H][W][18] float16 = Ib warped by (U4 0, U4 1), Ic warped by (U4 2, U4 3), U4 0..3, U1, Ia, U3 0..2, +// h(f). The warp sample of pixel (x, y): px = fma(2, u, h(x)); X0 = floor(px), fx = h(px - X0); x0, x1 = X0, X0 + 1 +// clamped to [0, W - 1] (y likewise); gx = h(1 - fx); w00 = h(gx gy), w10 = h(fx gy), w01 = h(gx fy), w11 = h(fx fy); +// value = fma(w11, P11, fma(w01, P10, fma(w10, P01, h(w00 P00)))) with P01 = (y0, x1), P10 = (y1, x0). The single- +// precision steps (px - X0, 1 - fx, the weight products) are exact; each h is one wg_f2h. Ib, Ic [H][W][4], Ia, U1 +// [H][W][1], U4 [H][W][4], U3 [H][W][3]. Built only when --only names it. +// +// @wg-kernel fg_net2_warp co=fg_net2.co block=256 wave=32 args=p,p,p,p,p,p,p,u,u,u +#include "wg_platform.hlsli" +#include "fg_net2.hlsli" + +WG_ARGS_BEGIN + uint ib, ic, ia, u4, u1, u3, y; // pointers (arena byte offsets) + int W, H; + uint fbits; +WG_ARGS_END + +WG_KERNEL(fg_net2_warp) +{ + WG_SETUP(); + const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); + if (idx >= W * H * 18) return; + const int p = idx / 18; + const int c = idx - p * 18; + const int py_ = p / W; + const int px_ = p - py_ * W; + uint v; + if (c < 8) { + const uint img = c < 4 ? ib : ic; + const int ch = c & 3; + const uint ux = wg_ld16(u4, (uint)(p * 4 + (c < 4 ? 0 : 2)) * 2u); + const uint uy = wg_ld16(u4, (uint)(p * 4 + (c < 4 ? 1 : 3)) * 2u); + 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; + const int x0 = clamp(X0, 0, W - 1), x1 = clamp(X0 + 1, 0, W - 1); + const int y0 = clamp(Y0, 0, H - 1), 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)); + const uint w00 = fg2_mul(gx, gy), w10 = fg2_mul(fx, gy), w01 = fg2_mul(gx, fy), w11 = fg2_mul(fx, fy); + const uint q00 = wg_ld16(img, (uint)((y0 * W + x0) * 4 + ch) * 2u); + const uint q01 = wg_ld16(img, (uint)((y0 * W + x1) * 4 + ch) * 2u); + const uint q10 = wg_ld16(img, (uint)((y1 * W + x0) * 4 + ch) * 2u); + const uint q11 = wg_ld16(img, (uint)((y1 * W + x1) * 4 + ch) * 2u); + uint acc = fg2_fma(w10, q01, fg2_mul(w00, q00)); + acc = fg2_fma(w01, q10, acc); + v = fg2_fma(w11, q11, acc); + } else if (c < 12) { + v = wg_ld16(u4, (uint)(p * 4 + c - 8) * 2u); + } else if (c == 12) { + v = wg_ld16(u1, (uint)p * 2u); + } else if (c == 13) { + v = wg_ld16(ia, (uint)p * 2u); + } else if (c < 17) { + v = wg_ld16(u3, (uint)(p * 3 + c - 14) * 2u); + } else { + v = wg_f2h(asfloat(fbits)); + } + wg_st16(y, (uint)idx * 2u, v); +} diff --git a/clean/dx12/kernels/fg_out_pull.hlsl b/clean/dx12/kernels/fg_out_pull.hlsl new file mode 100644 index 00000000..ee3770b0 --- /dev/null +++ b/clean/dx12/kernels/fg_out_pull.hlsl @@ -0,0 +1,284 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): the Full path's output pull and middle pull, as clean/fg/reference/stages_full.py +// g6_output_pull and g6_output_pull_mid, bit for bit. Built only when --only names them. +// +// fg_out_pull: one workgroup per 16 x 16 frame tile (tiles_x = ceil(Wo / 16)), one lane per pixel in Morton order. +// Per frame pixel: the hole rule on Xw's 5 x 5 neighbourhood (outside the frame counts as need), net2's output N2 +// (W2 x H2, 8 x float16) sampled at (x / k, y / k) with the logistic of channel 4 per tap from the table sigtab +// (65,536 float32, indexed by the float16 bits), X0 / X1 read bilinearly at the pixel plus k times net2's two vectors, +// c = sat(fma(sigma, A, (1 - sigma) B)), holes black. Writes out (4 x float16, alpha 1, row pitch out_pitch, offset +// (out_x, out_y)), the fine flag image (float16 0 / 1) and output pyramid levels 1..4 (4 x float16) through a lane tree. +// 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. +// 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_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 +#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 +#ifndef FGP_X3 +#define FGP_X3 0 +#endif +#ifndef FGP_POW2 +#define FGP_POW2 0 +#endif + +groupshared float4 fgp_wave_sums[8]; + +int fgp_size(int n, uint lvl) { return (n + (1 << lvl) - 1) >> lvl; } + +float4 fgp_level(float4 acc, uint m) +{ +#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 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 +} + +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 + uint lv4, lv5, lv6, lv7, lv8; + int w4, h4, tiles_x, Wo, Ho; +#else + uint x0, x1, xw, n2, sigtab, outp, fine, lv1, lv2, lv3, lv4; + int Wo, Ho, W2, H2, k, tiles_x, out_pitch, out_x, out_y; + uint rk_bits; // 1 / k (float bits) +#endif +WG_ARGS_END + +#if FGP_MID +WG_KERNEL(fg_out_pull_mid) +{ + FGF_SETUP(); + const uint l = wg_lane_id(); + const uint t = wg_block_id(); + 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_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)) +float fgp_bil(float fx, float fy, float gx, float gy, float q00, float q10, float q01, float q11) +{ + 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]; + +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 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; + 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 (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 = 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); + } + out_c = c; + acc = float4(c, hole ? 0.0f : 1.0f); + } + { + 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 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)); +} +#endif diff --git a/clean/dx12/kernels/fg_out_push.hlsl b/clean/dx12/kernels/fg_out_push.hlsl new file mode 100644 index 00000000..fdc2f4aa --- /dev/null +++ b/clean/dx12/kernels/fg_out_push.hlsl @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MIT +// Frame generation (issue #96): the Full path's output push and push-fine, as clean/fg/reference/stages_full.py +// g6_output_push and g6_output_push_fine, bit for bit. Built only when --only names them. +// +// 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. 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. +// +// 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. +// +// 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" + +#ifndef FGU_FINE +#define FGU_FINE 0 +#endif +#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_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_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(); + const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); + 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)); +#else + fgf_st4h(outp, (qy + out_y) * out_pitch + qx + out_x, float4(up.xyz, 1.0f)); +#endif +} +#else +WG_KERNEL(fg_out_push) +{ + FGF_SETUP(); + const int idx = (int)(wg_block_id() * 256u + wg_lane_id()); + if (idx >= wf * hf) 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)); +} +#endif diff --git a/clean/dx12/kernels/fused_swin.hlsl b/clean/dx12/kernels/fused_swin.hlsl index 0a0a605b..77bc7e35 100644 --- a/clean/dx12/kernels/fused_swin.hlsl +++ b/clean/dx12/kernels/fused_swin.hlsl @@ -41,6 +41,12 @@ #ifndef SW_HYB #define SW_HYB 0 #endif +#ifndef SW_Q7_CHUNK +#define SW_Q7_CHUNK 0 // 1 (with SW_HYB): per-32-channel FP16-rounded WMMA chunks (oracle mm8="exact") +#endif +#if SW_Q7_CHUNK && !SW_HYB +#error "SW_Q7_CHUNK requires SW_HYB=1" +#endif #ifndef SW_HYB_MUT_ORDER #define SW_HYB_MUT_ORDER 0 // check mutants only: 1 one W2 chunk pair reversed, 2 the pair of every W2 group, // 3 the odd W2 groups in a second accumulator added at the end (one extra f32 rounding), @@ -103,15 +109,10 @@ #define SW_GELU_LATE0 0 #endif #endif -#if SW_HYB && (SW_GELU != 0 || SW_HEAD_UNROLL || SW_HEAD_PAIRS || SW_MLP_PAIRS || SW_MLP_STEP != 1 || SW_COMMIT_EARLY || \ - SW_N2_BATCH) -#error "SW_HYB: the hybrid kernels run the plain schedule (no M-form scheduling knobs)" -#endif -// (SW_SRC 3 and SW_OUT_COEF12 are allowed: the linears' prologue gives the block the same FP16 values as the x2 map, -// and the pack12 epilogue reads the same FP16 output, converted by the driver's RNE as the hybrid output point does) -#if SW_HYB &&(SW_ECL > 0 || SW_NORM1_EARLY || SW_NORM2_EARLY || SW_NORM_R2 || SW_SMAX_STAGED || SW_SMAX_ADDST || \ - SW_REV_PHI || SW_CLAMP_SKIP) -#error "SW_HYB: only the plain block path (no fused expand, no scheduling knobs) has the hybrid form so far" +// SW_ECL > 0 with SW_HYB (the hybrid decoder blocks with their expand fused in: swin_block_c96_add_ex_hyb, +// swin_block_c64_add_ex_hyb): SW_ADD only, plain FP8 (no q7c chunks), see hyb_fused_expand below +#if SW_HYB && (SW_GELU != 0 || (SW_ECL > 0 && (!SW_ADD || SW_Q7_CHUNK)) || SW_NORM_R2 || SW_SMAX_STAGED || SW_SMAX_ADDST || SW_REV_PHI || SW_CLAMP_SKIP || SW_N2_BATCH) +#error "SW_HYB: unsupported M-form knob enabled" #endif #if SW_HYB && SW_OUT_COEF12 && !COEF_CVT_HW #error "SW_HYB with SW_OUT_COEF12: COEF_CVT_HW 1 (the driver's RNE conversion of the hybrid output point)" @@ -215,8 +216,8 @@ WG_ARGS_END // order. #if defined(SW_HPU) #define HPU SW_HPU -#elif SW_C == 64 && SW_GELU != 0 -#define HPU 4 // MTH 16 +#elif SW_C == 64 && (SW_GELU != 0 || SW_HYB) +#define HPU 4 // MTH 16 (2 x 8 KB = 16 KB LDS -> 3-4 workgroups/CU instead of 2) #elif SW_C == 64 #define HPU 8 // MTH 16, limit 8 #elif SW_C == 96 @@ -626,7 +627,11 @@ void load_frags_g(uint base, uint off, out uint2 f[KC]) #ifndef SW_OUT_F16 #define SW_OUT_F16 0 #endif -#if (SW_SRC != 0 || (SW_OUT_F16 && !SW_HYB)) && (SW_ADD || SW_ECL > 0) +// The one exception outside the hybrid decoder: Model L's fast-mode decoder block (l_mode=fast, l_swin_fast.hlsl): the +// M-form chain (SW_HYB 0) with the skip, SW_SRC 2 (x by the token-grid mirror) + SW_ADD (xadd, the skip, by the fine one) +// + SW_OUT_F16, without a fused expand. +#define SW_L_FAST_DEC (SW_SRC == 2 && SW_ADD && SW_OUT_F16 && !SW_HYB && SW_ECL == 0) +#if (SW_SRC != 0 || (SW_OUT_F16 && !SW_HYB)) && (SW_ADD || SW_ECL > 0) && !SW_L_FAST_DEC #error "SW_SRC / SW_OUT_F16: plain blocks only (the hybrid C32 decoder: SW_OUT_F16 with SW_ADD, the skip)" #endif #ifndef SW_OUT_COEF12 @@ -666,9 +671,14 @@ void sw_load_halo_lin(uint base, int pr, int pc, int W, uint lane, uint hh, out const uint pix = (uint)((pr + 2) * (W + 4) + pc + 2); uint2 xq[2]; const uint plane1 = (uint)((H + 4) * (W + 4)) * 16u; - const uint4 v = wg_ld128(base, hh != 0u ? plane1 + pix * 4u : pix * 16u); // h = 1: .x = bytes 16..19 - xq[0] = uint2(v.x, hh != 0u ? 0u : v.y); - xq[1] = hh != 0u ? uint2(0u, 0u) : v.zw; + if (hh != 0u) { + xq[0] = uint2(wg_ld32(base, plane1 + pix * 4u), 0u); + xq[1] = uint2(0u, 0u); + } else { + const uint4 v = wg_ld128(base, pix * 16u); + xq[0] = v.xy; + xq[1] = v.zw; + } v8f b1[2], b2[2]; uint2 f1[2][2], f2[2][2]; lin_blob(linW1, lane, hh, b1, f1); @@ -791,6 +801,10 @@ void fused_expand(uint tail, uint e_lds, int nwx, int nwin, uint tid, int blk, u acc1 = wg_wmma_fp8(fa[it2][kc2], yf[1][kc2], acc1); } uint2 q0, q1; +#if SW_HYB + // the hybrid expand's FP8 point (expand_c96_hyb / expand_c128_hyb): E = FP8(RN16(be + We y)), hyb_q8_of_chain + q0 = hyb_q8_of_chain(acc0); q1 = hyb_q8_of_chain(acc1); +#else #if SW_CLAMP_SKIP if (sw_in448(sw_absmax8(sw_absmax8(0.0f, acc0), acc1))) { q0 = wg_pack_q8_nc_ags(acc0); q1 = wg_pack_q8_nc_ags(acc1); @@ -799,6 +813,7 @@ void fused_expand(uint tail, uint e_lds, int nwx, int nwin, uint tid, int blk, u { q0 = sw_pack_q8_v2(acc0); q1 = sw_pack_q8_v2(acc1); } +#endif uint slot0 = (0u + (t >> 2)) * 16u + (t & 3u) * 4u + k, slot1 = (4u + (t >> 2)) * 16u + (t & 3u) * 4u + k; sw_lds_st64(e_lds + slot0 * SW_C + hh * (SW_C / 2) + 8u * g, q0); sw_lds_st64(e_lds + slot1 * SW_C + hh * (SW_C / 2) + 8u * g, q1); @@ -806,6 +821,30 @@ void fused_expand(uint tail, uint e_lds, int nwx, int nwin, uint tid, int blk, u } #endif +#if SW_ECL > 0 && SW_HYB +// hyb_fused_expand (SW_HYB with SW_ECL): the hybrid decoder blocks read their expanded input E (the coarse mirror of the +// table's shared_dec_border, sw_coarse_src: the 2 x 2 group index mirrored, the sub-pixel kept) from the records the +// fused expand wrote, so a window's records cover the mirrored groups of its rows / columns (p0 even: the groups +// p0 / 2 and p0 / 2 + 1, whose mirrors are adjacent). sw_low0c(p0, n) = the smaller of the two mirrored groups of the +// window's first row / column p0 = 4 w - o of a map of n pixels (o even: the fused launches' offsets); sw_win_low0c = +// diet_c96.hlsli's sw_win_low0 with it (row base | column base << 16). +int sw_low0c(int p0, int n) +{ + const int g = p0 >> 1, nc = n >> 1; + return min(sw_mirror(g, nc), sw_mirror(g + 1, nc)); +} +uint sw_win_low0c(int nwx, int nwin, uint lane, int blk) +{ + int win = blk * 8 + (int)(lane & 7u); + win = win < nwin ? win : nwin - 1; + const int wy = win / nwx, wx = win - wy * nwx; + return (uint)sw_low0c(4 * wy - oy, H) | ((uint)sw_low0c(4 * wx - ox, W) << 16); +} +#define SW_WIN_LOW0 sw_win_low0c +#else +#define SW_WIN_LOW0 sw_win_low0 +#endif + #if SW_C != 96 || (SW_PM && (SW_ADD || SW_ECL > 0)) || (SW_XE && !(SW_ECL > 0)) || (SW_PM == SW_XE) #error "fused_swin.hlsl: swin_block_c96_pm_nc or swin_block_c96_add_xe_nc" #endif @@ -944,14 +983,20 @@ WG_KERNEL(SW_ENTRY) uint2 xb[KC]; #endif #if SW_ECL > 0 - const uint lowp = sw_win_low0(nwx, nwin, lane, (int)wg_block_id()); + const uint lowp = SW_WIN_LOW0(nwx, nwin, lane, (int)wg_block_id()); #if FZ_XO fz_wait_b5(nwx, nwin, tid); #endif fused_expand(w + L_TAIL, MAXU, nwx, nwin, tid, (int)wg_block_id(), lowp); const uint lpw = WaveReadLaneAt(lowp, wave_id); // this wave's window (win: the same clamp) - const int low = ((mr >> 1) - (int)(lpw & 0xffffu)) * 2 + ((mc >> 1) - (int)(lpw >> 16)); - const uint eslot = (tid >> 5) * 16u + (uint)low * 4u + (uint)(((mr & 1) << 1) | (mc & 1)); +#if SW_HYB + // the coarse source position of E (sw_coarse_src): the mirrored group, the member's own sub-pixel + const int mre = 2 * sw_mirror(pr >> 1, H >> 1) + (pr & 1), mce = 2 * sw_mirror(pc >> 1, W >> 1) + (pc & 1); +#else + const int mre = mr, mce = mc; +#endif + const int low = ((mre >> 1) - (int)(lpw & 0xffffu)) * 2 + ((mce >> 1) - (int)(lpw >> 16)); + const uint eslot = (tid >> 5) * 16u + (uint)low * 4u + (uint)(((mre & 1) << 1) | (mce & 1)); #elif SW_SRC == 1 v8f xf[KC]; sw_load_halo_f16(x, pr, pc, W, hh, xf); @@ -1020,6 +1065,9 @@ WG_KERNEL(SW_ENTRY) // Steps 1-2: a = q8(RMSNorm(x; gamma1)); the residual accumulator starts as x + bp. uint2 af[KC]; v8f acc[KC]; +#if SW_Q7_CHUNK + uint4 acc_h[KC]; +#endif { [unroll] for (uint k = 0; k < KC; ++k) { #if SW_SRC == 1 || SW_SRC == 3 @@ -1037,15 +1085,57 @@ WG_KERNEL(SW_ENTRY) #if SW_HYB // y = the original's norm (FP16 tree); a = FP8(y); the Wp chain starts at RN16(bp + x) { +#if SW_NORM1_EARLY + v8f y[KC]; + hyb_norm(acc, ng, hh, y); +#else const uint g1 = w + L_G1 + hh * (HALF * 4), bp = w + L_BP + hh * 32u; v8f gp[KC], y[KC]; [unroll] for (uint k1 = 0; k1 < KC; ++k1) gp[k1] = wg_load8f(g1, 32u * k1); hyb_norm(acc, gp, hh, y); +#endif [unroll] for (uint kd = 0; kd < KC; ++kd) { HD_ST8(8u * kd, acc[kd]); HD_ST8(8u * (KC + kd), y[kd]); } - [unroll] for (uint k3 = 0; k3 < KC; ++k3) { - af[k3] = hyb_q8(y[k3]); - acc[k3] = hyb_add16(acc[k3], wg_load8f(bp, 64u * k3)); +#if SW_Q7_CHUNK + uint2 af_l[KC]; +#if !SW_MEGA + float ym = 0.0f; + [unroll] for (uint km = 0; km < KC; ++km) ym = hyb_absmax8(ym, y[km]); + if (WaveActiveAllTrue(ym <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af_l[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af_l[k3] = wg_pack_q8_ags(y[k3]); } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af_l[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { +#if SW_NORM1_EARLY + acc_h[k3b] = hyb_rn16x8(sw_add8(acc[k3b], nb[k3b])); +#else + acc_h[k3b] = hyb_rn16x8(sw_add8(acc[k3b], wg_load8f(bp, 64u * k3b))); +#endif + } + HYB_Q7C_L2D(KC, af_l, af, hh); +#else +#if !SW_MEGA + float ym = 0.0f; + [unroll] for (uint km = 0; km < KC; ++km) ym = hyb_absmax8(ym, y[km]); + if (WaveActiveAllTrue(ym <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { +#if SW_NORM1_EARLY + acc[k3b] = hyb_add16(acc[k3b], nb[k3b]); +#else + acc[k3b] = hyb_add16(acc[k3b], wg_load8f(bp, 64u * k3b)); +#endif + } +#endif } #else const float r = norm_r(acc); @@ -1100,6 +1190,176 @@ WG_KERNEL(SW_ENTRY) #endif uint2 uf[2]; uint4 vt[2]; +#if SW_Q7_CHUNK + // VMEM/LUT latency hiding: compute Wqk -> S = U^T U + B first, then interleave Wv (2*KC FP8 WMMAs) + // across hyb_softmax_pre (hyb_rcp16 global LUT load) and hyb_softmax_fin so the LUT load latency is hidden. + { + v8f accq0 = sw_zero8(), accq1 = sw_zero8(); + [unroll] for (uint kc2 = 0; kc2 < KC; kc2 += 2u) { + const uint2 fq00 = sw_lfrag_b(fb, (0u * KC + kc2) * 2u); + const uint2 fq10 = sw_lfrag_b(fb, (1u * KC + kc2) * 2u); + const uint2 fq01 = sw_lfrag_b(fb, (0u * KC + kc2 + 1u) * 2u); + const uint2 fq11 = sw_lfrag_b(fb, (1u * KC + kc2 + 1u) * 2u); + accq0 = wg_wmma_fp8(fq00, af[kc2], accq0); + accq1 = wg_wmma_fp8(fq10, af[kc2], accq1); + accq0 = wg_wmma_fp8(fq01, af[kc2 + 1u], accq0); + accq1 = wg_wmma_fp8(fq11, af[kc2 + 1u], accq1); + if (kc2 + 2u < KC) { + accq0 = hyb_round16(accq0); + accq1 = hyb_round16(accq1); + } + } + hyb_q8_pair(hyb_round16(accq0), hyb_round16(accq1), uf[0], uf[1]); + } +#if SW_C != 64 + const v8f bias = wg_load8f(biasl, hd * 1024u); +#endif + v8f s = wg_wmma_fp8(uf[0], uf[0], bias); + s = wg_wmma_fp8(uf[1], uf[1], s); + uint4 p; + { + // Issue chunk 0 of Wv before hyb_softmax_pre, then hide hyb_rcp16 global LUT latency + // behind the remaining Wv chunks before hyb_softmax_fin. + v8f accv0 = sw_zero8(), accv1 = sw_zero8(); + { + const uint2 fv00 = sw_lfrag_b(fb, (0u * KC + 0u) * 2u + 1u); + const uint2 fv10 = sw_lfrag_b(fb, (1u * KC + 0u) * 2u + 1u); + const uint2 fv01 = sw_lfrag_b(fb, (0u * KC + 1u) * 2u + 1u); + const uint2 fv11 = sw_lfrag_b(fb, (1u * KC + 1u) * 2u + 1u); + accv0 = wg_wmma_fp8(af[0], fv00, accv0); + accv1 = wg_wmma_fp8(af[0], fv10, accv1); + accv0 = wg_wmma_fp8(af[1], fv01, accv0); + accv1 = wg_wmma_fp8(af[1], fv11, accv1); + } + const HybSmaxPre sp = hyb_softmax_pre(s); + [unroll] for (uint kc2 = 2; kc2 < KC; kc2 += 2u) { + accv0 = hyb_round16(accv0); + const uint2 fv00 = sw_lfrag_b(fb, (0u * KC + kc2) * 2u + 1u); + const uint2 fv10 = sw_lfrag_b(fb, (1u * KC + kc2) * 2u + 1u); + const uint2 fv01 = sw_lfrag_b(fb, (0u * KC + kc2 + 1u) * 2u + 1u); + const uint2 fv11 = sw_lfrag_b(fb, (1u * KC + kc2 + 1u) * 2u + 1u); + accv0 = wg_wmma_fp8(af[kc2], fv00, accv0); + accv1 = hyb_round16(accv1); + accv1 = wg_wmma_fp8(af[kc2], fv10, accv1); + accv0 = wg_wmma_fp8(af[kc2 + 1u], fv01, accv0); + accv1 = wg_wmma_fp8(af[kc2 + 1u], fv11, accv1); + } + p = hyb_softmax_fin(sp); + vt[0] = wg_to_f16_ags(accv0); + vt[1] = wg_to_f16_ags(accv1); + } + uint2 of[2]; + { + v8f pv0 = wg_wmma_f16(vt[0], p, sw_zero8()); + v8f pv1 = wg_wmma_f16(vt[1], p, sw_zero8()); + of[0] = hyb_q7c_pv_q8(vt[0], p, hh, sw_zero(), pv0); + of[1] = hyb_q7c_pv_q8(vt[1], p, hh, sw_zero(), pv1); + } + // x1 += Wp[:, head hd] q8(o_hd): 2-tile software-pipelined acc_h unpack/pack with FP8 WMMAs (reduces RAW stalls) + { + uint2 fp[KC][2]; + [unroll] for (uint m = 0; m < KC; ++m) { + fp[m][0] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u); + fp[m][1] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u + 1u); + } + v8f t0 = hyb_h2f8(acc_h[0]); + t0 = wg_wmma_fp8(fp[0][0], of[0], t0); + [unroll] for (uint m2 = 0; m2 + 1u < KC; ++m2) { + v8f t1 = hyb_h2f8(acc_h[m2 + 1u]); + t0 = wg_wmma_fp8(fp[m2][1], of[1], t0); + t1 = wg_wmma_fp8(fp[m2 + 1u][0], of[0], t1); + acc_h[m2] = hyb_rn16x8(t0); + t0 = t1; + } + t0 = wg_wmma_fp8(fp[KC - 1u][1], of[1], t0); + acc_h[KC - 1u] = hyb_rn16x8(t0); + } +#elif SW_HYB && (SW_C != 96) + // VMEM/LUT latency hiding (SW_HYB, C != 96): compute Wqk -> S = U^T U + B first, then interleave Wv + // (2*KC FP8 WMMAs) across hyb_softmax_pre (exact FP32 e8 + hyb_rcp16 global LUT load) and hyb_softmax_fin. + { + uint2 fq0[KC], fq1[KC]; + [unroll] for (uint kc = 0; kc < KC; ++kc) { + fq0[kc] = sw_lfrag_b(fb, (0u * KC + kc) * 2u); + fq1[kc] = sw_lfrag_b(fb, (1u * KC + kc) * 2u); + } + v8f accq0 = sw_zero8(), accq1 = sw_zero8(); + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) { + accq0 = wg_wmma_fp8(fq0[kc2], af[kc2], accq0); + accq1 = wg_wmma_fp8(fq1[kc2], af[kc2], accq1); + } + const v8f rq0 = hyb_round16(accq0), rq1 = hyb_round16(accq1); + HD_ST8(HD_HEAD + 60u * hd + 0u, rq0); + HD_ST8(HD_HEAD + 60u * hd + 8u, rq1); +#if !SW_MEGA + hyb_q8_pair(rq0, rq1, uf[0], uf[1]); +#else + uf[0] = hyb_q8(rq0); + uf[1] = hyb_q8(rq1); +#endif + } +#if SW_C != 64 +#if SW_HEAD_UNROLL + const v8f bias = wg_load8f(w + L_BIAS, ((hd * 16u + t) * 2u + hh) * 32u); +#else + const v8f bias = wg_load8f(biasl, hd * 1024u); +#endif +#endif + // s = one 32-term FP8 op started at B (the position bias, FP16 values); the original's weights P + v8f s = wg_wmma_fp8(uf[0], uf[0], bias); + s = wg_wmma_fp8(uf[1], uf[1], s); + uint4 p; + { + v8f accv0 = sw_zero8(), accv1 = sw_zero8(); + [unroll] for (uint kv0 = 0; kv0 < KC / 2; ++kv0) { + const uint2 fv0 = sw_lfrag_b(fb, (0u * KC + kv0) * 2u + 1u); + const uint2 fv1 = sw_lfrag_b(fb, (1u * KC + kv0) * 2u + 1u); + accv0 = wg_wmma_fp8(af[kv0], fv0, accv0); + accv1 = wg_wmma_fp8(af[kv0], fv1, accv1); + } + const HybSmaxPre sp = hyb_softmax_pre(s); + [unroll] for (uint kv1 = KC / 2; kv1 < KC; ++kv1) { + const uint2 fv0 = sw_lfrag_b(fb, (0u * KC + kv1) * 2u + 1u); + const uint2 fv1 = sw_lfrag_b(fb, (1u * KC + kv1) * 2u + 1u); + accv0 = wg_wmma_fp8(af[kv1], fv0, accv0); + accv1 = wg_wmma_fp8(af[kv1], fv1, accv1); + } + p = hyb_softmax_fin(sp); + vt[0] = wg_to_f16_ags(accv0); + vt[1] = wg_to_f16_ags(accv1); +#if SW_HYB_DUMP + HD_ST8(HD_HEAD + 60u * hd + 16u, hyb_h2f8(vt[0])); + HD_ST8(HD_HEAD + 60u * hd + 24u, hyb_h2f8(vt[1])); +#endif + } + HD_ST8(HD_HEAD + 60u * hd + 32u, hyb_round16(s)); + HD_ST4(HD_HEAD + 60u * hd + 40u, p); + // o = A V (rows value channels, columns tokens) + uint2 of[2]; + { + const v8f pv0 = wg_wmma_f16(vt[0], p, sw_zero8()); + const v8f pv1 = wg_wmma_f16(vt[1], p, sw_zero8()); + const v8f rp0 = hyb_round16(pv0), rp1 = hyb_round16(pv1); + HD_ST8(HD_HEAD + 60u * hd + 44u, rp0); + HD_ST8(HD_HEAD + 60u * hd + 52u, rp1); +#if !SW_MEGA + hyb_q8_pair(rp0, rp1, of[0], of[1]); +#else + of[0] = hyb_q8(rp0); + of[1] = hyb_q8(rp1); +#endif + } + // x1 += Wp[:, head hd] q8(o_hd) + uint2 fp[KC][2]; + [unroll] for (uint m = 0; m < KC; ++m) { + fp[m][0] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u); + fp[m][1] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u + 1u); + } + [unroll] for (uint m2 = 0; m2 < KC; ++m2) { + acc[m2] = wg_wmma_fp8(fp[m2][0], of[0], acc[m2]); + acc[m2] = wg_wmma_fp8(fp[m2][1], of[1], acc[m2]); + } +#else [unroll] for (uint mt = 0; mt < 2; ++mt) { uint2 fq[KC], fv[KC]; [unroll] for (uint kc = 0; kc < KC; ++kc) { @@ -1214,6 +1474,7 @@ WG_KERNEL(SW_ENTRY) acc[m2] = wg_wmma_fp8(fp[m2][0], of[0], acc[m2]); acc[m2] = wg_wmma_fp8(fp[m2][1], of[1], acc[m2]); } +#endif #if SW_NORM2_EARLY if (!last) { st_commit(stage, (buf ^ 1u) * MAXU, HEAD_BYTES / 16, tid); @@ -1241,18 +1502,75 @@ WG_KERNEL(SW_ENTRY) // Step 8: m = q8(RMSNorm(x1; gamma2)), then b2 into the residual accumulator. uint2 mf[KC]; -#if SW_HYB +#if SW_Q7_CHUNK + { +#if SW_NORM2_EARLY + v8f y[KC]; + hyb_norm_h(acc_h, ng2, hh, y); +#else + const uint g2 = w + L_G2 + hh * (HALF * 4), b2 = w + L_B2 + hh * 32u; + v8f gp[KC], y[KC]; + [unroll] for (uint k1 = 0; k1 < KC; ++k1) gp[k1] = wg_load8f(g2, 32u * k1); + hyb_norm_h(acc_h, gp, hh, y); +#endif + uint2 mf_l[KC]; +#if !SW_MEGA + float ym2 = 0.0f; + [unroll] for (uint km2 = 0; km2 < KC; ++km2) ym2 = hyb_absmax8(ym2, y[km2]); + if (WaveActiveAllTrue(ym2 <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf_l[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf_l[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf_l[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { + v8f s2 = hyb_h2f8(acc_h[k3b]); +#if SW_NORM2_EARLY + const v8f bv = nb2[k3b]; +#else + const v8f bv = wg_load8f(b2, 64u * k3b); +#endif + [unroll] for (uint i = 0; i < 8; ++i) s2.v[i] = s2.v[i] + bv.v[i]; + acc_h[k3b] = hyb_rn16x8(s2); + } + HYB_Q7C_L2D(KC, mf_l, mf, hh); + } +#elif SW_HYB { // z = RN16(the Wp chain); m = FP8(norm(z; g2')); the W2 chain starts at RN16(b2 + z) - [unroll] for (uint kz = 0; kz < KC; ++kz) acc[kz] = hyb_round16(acc[kz]); + uint4 acc_h2[KC]; + [unroll] for (uint kz = 0; kz < KC; ++kz) acc_h2[kz] = hyb_rn16x8(acc[kz]); +#if SW_NORM2_EARLY + v8f y[KC]; + hyb_norm_h(acc_h2, ng2, hh, y); +#else const uint g2 = w + L_G2 + hh * (HALF * 4), b2 = w + L_B2 + hh * 32u; v8f gp[KC], y[KC]; [unroll] for (uint k1 = 0; k1 < KC; ++k1) gp[k1] = wg_load8f(g2, 32u * k1); - hyb_norm(acc, gp, hh, y); - [unroll] for (uint kd = 0; kd < KC; ++kd) { HD_ST8(HD_Z + 8u * kd, acc[kd]); HD_ST8(HD_Y2 + 8u * kd, y[kd]); } - [unroll] for (uint k3 = 0; k3 < KC; ++k3) { - mf[k3] = hyb_q8(y[k3]); - acc[k3] = hyb_add16(acc[k3], wg_load8f(b2, 64u * k3)); + hyb_norm_h(acc_h2, gp, hh, y); +#endif +#if SW_HYB_DUMP + [unroll] for (uint kd = 0; kd < KC; ++kd) { HD_ST8(HD_Z + 8u * kd, hyb_h2f8(acc_h2[kd])); HD_ST8(HD_Y2 + 8u * kd, y[kd]); } +#endif +#if !SW_MEGA + float ym2 = 0.0f; + [unroll] for (uint km2 = 0; km2 < KC; ++km2) ym2 = hyb_absmax8(ym2, y[km2]); + if (WaveActiveAllTrue(ym2 <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { +#if SW_NORM2_EARLY + acc[k3b] = hyb_add16(hyb_h2f8(acc_h2[k3b]), nb2[k3b]); +#else + acc[k3b] = hyb_add16(hyb_h2f8(acc_h2[k3b]), wg_load8f(b2, 64u * k3b)); +#endif } } #else @@ -1339,6 +1657,166 @@ WG_KERNEL(SW_ENTRY) // around on every iteration, about 90 moves per group; C = 64: measured 3.6 % faster unrolled) and // software-pipelined by one group (c64 / c96 about 4 % faster): W1 of group j0 + GROUP is issued before the GELU // of group j0, so the GELU's exp / rcp can issue under independent matrix multiplies (same operations per value) +#if SW_Q7_CHUNK + uint4 hcur_h[GROUP]; + { + const uint fb0 = sw_lane_base(buf * MAXU, lane) + SW_MDZ; + v8f hc[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hc[g2] = wg_load8f(b1d, (u * HPU + g2) * 64u); + [unroll] for (uint kc2 = 0; kc2 < KC; kc2 += 2u) { + uint2 f0[GROUP], f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) { + f0[g] = sw_lfrag_b(fb0, g * 2u * KC + kc2); + f1[g] = sw_lfrag_b(fb0, g * 2u * KC + kc2 + 1u); + } + [unroll] for (uint g3a = 0; g3a < GROUP; ++g3a) + hc[g3a] = wg_wmma_fp8(f0[g3a], mf[kc2], hc[g3a]); + [unroll] for (uint g3b = 0; g3b < GROUP; ++g3b) + hc[g3b] = wg_wmma_fp8(f1[g3b], mf[kc2 + 1u], hc[g3b]); + if (kc2 + 2u < KC) + [unroll] for (uint g3c = 0; g3c < GROUP; ++g3c) hc[g3c] = hyb_round16(hc[g3c]); + } + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hcur_h[g3o] = hyb_rn16x8(hc[g3o]); + } + [unroll] for (uint j0 = 0; j0 < HPU; j0 += GROUP) { + const uint fb = sw_lane_base(buf * MAXU, lane) + SW_MDZ + j0 * (2u * KC * 32u); + uint4 hnext_h[GROUP]; + uint2 hf[GROUP]; + if (j0 + GROUP < HPU) { + // Split hyb_gelu_pre(hcur_h[0..1]) across W1(j0 + GROUP): 8x u16 LUT loads hide behind + // independent FP8 WMMAs with only 8 VGPRs live at a time. + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const uint fbn = fb + GROUP * (2u * KC * 32u); + v8f hn[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hn[g2] = wg_load8f(b1d, (u * HPU + j0 + GROUP + g2) * 64u); + { + uint2 f0[GROUP], f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) { + f0[g] = sw_lfrag_b(fbn, g * 2u * KC + 0u); + f1[g] = sw_lfrag_b(fbn, g * 2u * KC + 1u); + } + [unroll] for (uint g3a = 0; g3a < GROUP; ++g3a) hn[g3a] = wg_wmma_fp8(f0[g3a], mf[0], hn[g3a]); + [unroll] for (uint g3b = 0; g3b < GROUP; ++g3b) hn[g3b] = wg_wmma_fp8(f1[g3b], mf[1], hn[g3b]); + } + hf[0] = hyb_gelu_fin(gp0); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint kc2 = 2; kc2 < KC; kc2 += 2u) { + [unroll] for (uint g3c = 0; g3c < GROUP; ++g3c) hn[g3c] = hyb_round16(hn[g3c]); + uint2 f0[GROUP], f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) { + f0[g] = sw_lfrag_b(fbn, g * 2u * KC + kc2); + f1[g] = sw_lfrag_b(fbn, g * 2u * KC + kc2 + 1u); + } + [unroll] for (uint g3a = 0; g3a < GROUP; ++g3a) hn[g3a] = wg_wmma_fp8(f0[g3a], mf[kc2], hn[g3a]); + [unroll] for (uint g3b = 0; g3b < GROUP; ++g3b) hn[g3b] = wg_wmma_fp8(f1[g3b], mf[kc2 + 1u], hn[g3b]); + } + hf[1] = hyb_gelu_fin(gp1); + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hnext_h[g3o] = hyb_rn16x8(hn[g3o]); + } else { + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint g7 = 0; g7 < GROUP; ++g7) hnext_h[g7] = hcur_h[g7]; + hf[0] = hyb_gelu_fin(gp0); + hf[1] = hyb_gelu_fin(gp1); + } + // W2: 2-tile software-pipelined acc_h unpack/pack with FP8 WMMAs (reduces back-to-back RAW stalls + // between conversions and WMMAs). + uint2 f2[GROUP][KC]; + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) + [unroll] for (uint m = 0; m < KC; ++m) f2[g4][m] = sw_lfrag_b(fb, g4 * 2u * KC + KC + m); + v8f t0 = hyb_h2f8(acc_h[0]); + t0 = wg_wmma_fp8(f2[0][0], hf[0], t0); + [unroll] for (uint m2 = 0; m2 + 1u < KC; ++m2) { + v8f t1 = hyb_h2f8(acc_h[m2 + 1u]); + t0 = wg_wmma_fp8(f2[1][m2], hf[1], t0); + t1 = wg_wmma_fp8(f2[0][m2 + 1u], hf[0], t1); + acc_h[m2] = hyb_rn16x8(t0); + t0 = t1; + } + t0 = wg_wmma_fp8(f2[1][KC - 1u], hf[1], t0); + acc_h[KC - 1u] = hyb_rn16x8(t0); + [unroll] for (uint g8 = 0; g8 < GROUP; ++g8) hcur_h[g8] = hnext_h[g8]; +#if SW_COMMIT_EARLY + if (more && j0 == GROUP * (SW_COMMIT_EARLY - 1)) st_commit(stage, (buf ^ 1u) * MAXU + 8u * SW_MDZ, MLP_BYTES / 16, tid); +#endif + } +#elif SW_HYB && (SW_C != 96) + // VMEM/LUT latency hiding (SW_HYB MLP, C != 96): keep hcur packed as uint4[GROUP] (saves 8 VGPRs) and split + // hyb_gelu_pre(hcur_h[0..1]) (16x u16 global LUT loads) across W1(j0 + GROUP) FP8 WMMAs to hide LUT latency. + uint4 hcur_h[GROUP]; + { + const uint fb0 = sw_lane_base(buf * MAXU, lane) + SW_MDZ; + uint2 f1[GROUP][KC]; + [unroll] for (uint g = 0; g < GROUP; ++g) + [unroll] for (uint kc = 0; kc < KC; ++kc) f1[g][kc] = sw_lfrag_b(fb0, g * 2u * KC + kc); + v8f hc[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hc[g2] = wg_load8f(b1d, (u * HPU + g2) * 64u); + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hc[g3] = wg_wmma_fp8(f1[g3][kc2], mf[kc2], hc[g3]); + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hcur_h[g3o] = hyb_rn16x8(hc[g3o]); + } + [unroll] for (uint j0 = 0; j0 < HPU; j0 += GROUP) { + const uint fb = sw_lane_base(buf * MAXU, lane) + SW_MDZ + j0 * (2u * KC * 32u); +#if SW_HYB_DUMP + [unroll] for (uint ghd = 0; ghd < GROUP; ++ghd) + HD_ST8(HD_H + 8u * (u * HPU + j0 + ghd), hyb_h2f8(hcur_h[ghd])); +#endif + uint4 hnext_h[GROUP]; + uint2 hf[GROUP]; + if (j0 + GROUP < HPU) { + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const uint fbn = fb + GROUP * (2u * KC * 32u); + v8f hn[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hn[g2] = wg_load8f(b1d, (u * HPU + j0 + GROUP + g2) * 64u); + [unroll] for (uint kc0 = 0; kc0 < KC / 2; ++kc0) { + uint2 f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) f1[g] = sw_lfrag_b(fbn, g * 2u * KC + kc0); + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hn[g3] = wg_wmma_fp8(f1[g3], mf[kc0], hn[g3]); + } + hf[0] = hyb_gelu_fin(gp0); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint kc1 = KC / 2; kc1 < KC; ++kc1) { + uint2 f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) f1[g] = sw_lfrag_b(fbn, g * 2u * KC + kc1); + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hn[g3] = wg_wmma_fp8(f1[g3], mf[kc1], hn[g3]); + } + hf[1] = hyb_gelu_fin(gp1); + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hnext_h[g3o] = hyb_rn16x8(hn[g3o]); + } else { + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint g7 = 0; g7 < GROUP; ++g7) hnext_h[g7] = hcur_h[g7]; + hf[0] = hyb_gelu_fin(gp0); + hf[1] = hyb_gelu_fin(gp1); + } + uint2 f2[GROUP][KC]; + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) + [unroll] for (uint m = 0; m < KC; ++m) f2[g4][m] = sw_lfrag_b(fb, g4 * 2u * KC + KC + m); +#if SW_HYB_MUT_ORDER +#if SW_HYB_MUT_ORDER == 3 + if ((j0 / GROUP) & 1u) { + [unroll] for (uint m5 = 0; m5 < KC; ++m5) + [unroll] for (uint g11 = 0; g11 < GROUP; ++g11) acc2[m5] = wg_wmma_fp8(f2[g11][m5], hf[g11], acc2[m5]); + } else +#endif + if (SW_HYB_MUT_ORDER == 2 || (SW_HYB_MUT_ORDER == 1 && u == 0u && j0 == 0u)) { + [unroll] for (uint m3 = 0; m3 < KC; ++m3) + [unroll] for (uint g9 = 0; g9 < GROUP; ++g9) + acc[m3] = wg_wmma_fp8(f2[GROUP - 1u - g9][m3], hf[GROUP - 1u - g9], acc[m3]); + } else { + [unroll] for (uint m4 = 0; m4 < KC; ++m4) + [unroll] for (uint g10 = 0; g10 < GROUP; ++g10) acc[m4] = wg_wmma_fp8(f2[g10][m4], hf[g10], acc[m4]); + } +#else + [unroll] for (uint m2 = 0; m2 < KC; ++m2) + [unroll] for (uint g6 = 0; g6 < GROUP; ++g6) acc[m2] = wg_wmma_fp8(f2[g6][m2], hf[g6], acc[m2]); +#endif + [unroll] for (uint g8 = 0; g8 < GROUP; ++g8) hcur_h[g8] = hnext_h[g8]; +#if SW_COMMIT_EARLY + if (more && j0 == GROUP * (SW_COMMIT_EARLY - 1)) st_commit(stage, (buf ^ 1u) * MAXU + 8u * SW_MDZ, MLP_BYTES / 16, tid); +#endif + } +#else v8f hcur[GROUP]; { const uint fb0 = sw_lane_base(buf * MAXU, lane) + SW_MDZ; @@ -1444,6 +1922,7 @@ WG_KERNEL(SW_ENTRY) if (more && j0 == GROUP * (SW_COMMIT_EARLY - 1)) st_commit(stage, (buf ^ 1u) * MAXU + 8u * SW_MDZ, MLP_BYTES / 16, tid); #endif } +#endif if (more) { #if !SW_COMMIT_EARLY st_commit(stage, (buf ^ 1u) * MAXU, MLP_BYTES / 16, tid); @@ -1523,7 +2002,22 @@ WG_KERNEL(SW_ENTRY) } else #endif { -#if SW_HYB +#if SW_Q7_CHUNK + { + // Check |acc_h| <= 448.0 (FP16 0x5f00) directly on packed uint4 bits (1 VGPR vs 8*KC VGPRs!). + uint mx16 = 0u; + [unroll] for (uint km = 0; km < KC; ++km) { + const uint4 ah = acc_h[km]; + mx16 = max(mx16, max(max(ah.x & 0x7fffu, (ah.x >> 16) & 0x7fffu), max(ah.y & 0x7fffu, (ah.y >> 16) & 0x7fffu))); + mx16 = max(mx16, max(max(ah.z & 0x7fffu, (ah.z >> 16) & 0x7fffu), max(ah.w & 0x7fffu, (ah.w >> 16) & 0x7fffu))); + } + if (WaveActiveAllTrue(mx16 <= 0x5f00u)) { + [unroll] for (uint k2 = 0; k2 < KC; ++k2) o[k2] = wg_pack_q8_nc_ags(hyb_h2f8(acc_h[k2])); + } else { + [unroll] for (uint k2 = 0; k2 < KC; ++k2) o[k2] = wg_pack_q8_ags(hyb_h2f8(acc_h[k2])); + } + } +#elif SW_HYB [unroll] for (uint k = 0; k < KC; ++k) o[k] = hyb_q8_of_chain(acc[k]); #else [unroll] for (uint k = 0; k < KC; ++k) o[k] = sw_pack_q8_v2(acc[k]); diff --git a/clean/dx12/kernels/hyb_bneck.hlsl b/clean/dx12/kernels/hyb_bneck.hlsl index 08bf6675..2750bc3c 100644 --- a/clean/dx12/kernels/hyb_bneck.hlsl +++ b/clean/dx12/kernels/hyb_bneck.hlsl @@ -22,10 +22,12 @@ // swin_bneck6_hyb_tmo timeout control (probe=1): BNECK_SPIN_LIMIT 1 (a wait gives up at its first poll that // finds a producer not done): the check requires [12] and [15] nonzero after it (and zero // after the twin) -// @wg-kernel swin_bneck6_hyb co=- block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_MEGA=1,SW_ENTRY_OVERRIDE=swin_bneck6_hyb -// @wg-kernel swin_bneck6_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_MEGA=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_bneck6_hyb_scanmut +// @wg-kernel swin_bneck6_hyb co=- block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_MEGA=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_bneck6_hyb +// @wg-kernel swin_bneck6_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_MEGA=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_bneck6_hyb_scanmut // @wg-kernel swin_bneck6_hyb_mut co=- probe=1 block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_MEGA=1,SW_HYB_MUT_ORDER=4,SW_ENTRY_OVERRIDE=swin_bneck6_hyb_mut // @wg-kernel swin_bneck6_hyb_tmo co=- probe=1 block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_MEGA=1,BNECK_SPIN_LIMIT=1u,SW_ENTRY_OVERRIDE=swin_bneck6_hyb_tmo +// @wg-kernel swin_bneck6_q7c_hyb co=- block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_MEGA=1,SW_ENTRY_OVERRIDE=swin_bneck6_q7c_hyb +// @wg-kernel swin_bneck6_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,u,u,u,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_MEGA=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_bneck6_q7c_hyb_scanmut #include "swin_block.hlsl" #define BQ_SYNC_HEAD 16 diff --git a/clean/dx12/kernels/hyb_gemm.hlsl b/clean/dx12/kernels/hyb_gemm.hlsl index fb452e42..3c3f9605 100644 --- a/clean/dx12/kernels/hyb_gemm.hlsl +++ b/clean/dx12/kernels/hyb_gemm.hlsl @@ -26,6 +26,18 @@ // @wg-kernel patch_merge_c96_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,u,u defines=SW_PM_C=96,SW_PM_CO=128,SW_PM_SPLIT=4,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=patch_merge_c96_hyb_scanmut // @wg-kernel expand_c96_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,u,u defines=SW_EX_CL=96,SW_EX_C=64,SW_EX_SPLIT=0,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=expand_c96_hyb_scanmut // @wg-kernel expand_c128_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,u,u defines=SW_EX_CL=128,SW_EX_C=96,SW_EX_SPLIT=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=expand_c128_hyb_scanmut +// Per-32-chunk FP16-rounded exact q7 twins (SW_Q7_CHUNK=1): kord_drow weight packing. +// @wg-kernel patch_merge_c64_q7c_hyb co=- block=256 wave=32 args=p,p,p,u,u defines=SW_PM_C=64,SW_PM_CO=96,SW_PM_SPLIT=1,SW_Q7_CHUNK=1,SW_ENTRY_OVERRIDE=patch_merge_c64_q7c_hyb +// @wg-kernel patch_merge_c96_q7c_hyb co=- block=256 wave=32 args=p,p,p,u,u defines=SW_PM_C=96,SW_PM_CO=128,SW_PM_SPLIT=4,SW_Q7_CHUNK=1,SW_ENTRY_OVERRIDE=patch_merge_c96_q7c_hyb +// @wg-kernel expand_c96_q7c_hyb co=- block=256 wave=32 args=p,p,p,u,u defines=SW_EX_CL=96,SW_EX_C=64,SW_EX_SPLIT=0,SW_Q7_CHUNK=1,WG_REV_ORDER=1,SW_ENTRY_OVERRIDE=expand_c96_q7c_hyb +// @wg-kernel expand_c128_q7c_hyb co=- block=256 wave=32 args=p,p,p,u,u defines=SW_EX_CL=128,SW_EX_C=96,SW_EX_SPLIT=1,SW_Q7_CHUNK=1,WG_REV_ORDER=1,SW_ENTRY_OVERRIDE=expand_c128_q7c_hyb +// @wg-kernel patch_merge_c64_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,u,u defines=SW_PM_C=64,SW_PM_CO=96,SW_PM_SPLIT=1,SW_Q7_CHUNK=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=patch_merge_c64_q7c_hyb_scanmut +// @wg-kernel patch_merge_c96_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,u,u defines=SW_PM_C=96,SW_PM_CO=128,SW_PM_SPLIT=4,SW_Q7_CHUNK=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=patch_merge_c96_q7c_hyb_scanmut +// @wg-kernel expand_c96_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,u,u defines=SW_EX_CL=96,SW_EX_C=64,SW_EX_SPLIT=0,SW_Q7_CHUNK=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=expand_c96_q7c_hyb_scanmut +// @wg-kernel expand_c128_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,u,u defines=SW_EX_CL=128,SW_EX_C=96,SW_EX_SPLIT=1,SW_Q7_CHUNK=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=expand_c128_q7c_hyb_scanmut +#ifndef SW_Q7_CHUNK +#define SW_Q7_CHUNK 0 +#endif #include "wg_platform.hlsli" WG_ARGS_BEGIN @@ -90,10 +102,19 @@ WG_KERNEL(SW_ENTRY) const int tk = tok[i] < ntok ? tok[i] : ntok - 1; const int r = tk / Wm, c = tk - r * Wm; const uint off = (uint)((2 * r + (int)hh) * W + 2 * c) * SW_PM_C; +#if SW_Q7_CHUNK + uint2 zr[KZ]; + [unroll] for (uint q = 0; q < KZ / 2; ++q) { + uint4 v = wg_ld128(in_p, off + 16u * q); + zr[2 * q] = v.xy; zr[2 * q + 1] = v.zw; + } + HYB_Q7C_L2D(KZ, zr, zf[i], hh); +#else [unroll] for (uint q = 0; q < KZ / 2; ++q) { uint4 v = wg_ld128(in_p, off + 16u * q); zf[i][2 * q] = v.xy; zf[i][2 * q + 1] = v.zw; } +#endif } const uint bm = w + hh * 32u; [unroll] for (uint pass = 0; pass < SW_PM_SPLIT; ++pass) { @@ -105,12 +126,25 @@ WG_KERNEL(SW_ENTRY) uint2 f[KZ]; [unroll] for (uint g = 0; g < KZ; ++g) f[g] = sw_lfrag_b(sw_lane_base_m(0u, lane), mp * KZ + g); const v8f b = wg_load8f(bm, mt * 64u); + uint2 res[NT]; +#if SW_Q7_CHUNK + v8f acc[NT]; + [unroll] for (int i2 = 0; i2 < NT; ++i2) acc[i2] = b; + [unroll] for (uint g2 = 0; g2 < KZ; g2 += 2u) { + [unroll] for (int i3 = 0; i3 < NT; ++i3) { + acc[i3] = wg_wmma_fp8(f[g2], zf[i3][g2], acc[i3]); + acc[i3] = wg_wmma_fp8(f[g2 + 1u], zf[i3][g2 + 1u], acc[i3]); + if (g2 + 2u < KZ) acc[i3] = hyb_round16(acc[i3]); + } + } + [unroll] for (int i4 = 0; i4 < NT; ++i4) res[i4] = hyb_merge_q8(acc[i4]); +#else v8f acc[NT]; [unroll] for (int i2 = 0; i2 < NT; ++i2) acc[i2] = b; [unroll] for (uint g2 = 0; g2 < KZ; ++g2) [unroll] for (int i3 = 0; i3 < NT; ++i3) acc[i3] = wg_wmma_fp8(f[g2], zf[i3][g2], acc[i3]); - uint2 res[NT]; [unroll] for (int i4 = 0; i4 < NT; ++i4) res[i4] = hyb_merge_q8(acc[i4]); +#endif [unroll] for (int i5 = 0; i5 < NT; ++i5) if (tok[i5] < ntok) wg_st64(out_p, (uint)tok[i5] * SW_PM_CO + hh * (SW_PM_CO / 2) + 8u * mt, res[i5]); } @@ -141,10 +175,19 @@ WG_KERNEL(SW_ENTRY) tok[i] = tok0 + 16 * i; const int tk = tok[i] < ntok ? tok[i] : ntok - 1; const uint off = (uint)tk * SW_EX_CL + hh * (SW_EX_CL / 2); +#if SW_Q7_CHUNK + uint2 yr[KC]; + [unroll] for (uint q = 0; q < KC / 2; ++q) { + uint4 v = wg_ld128(in_p, off + 16u * q); + yr[2 * q] = v.xy; yr[2 * q + 1] = v.zw; + } + HYB_Q7C_L2D(KC, yr, yf[i], hh); +#else [unroll] for (uint q = 0; q < KC / 2; ++q) { uint4 v = wg_ld128(in_p, off + 16u * q); yf[i][2 * q] = v.xy; yf[i][2 * q + 1] = v.zw; } +#endif } #if !SW_EX_SPLIT copy_to_lds(w + WE, SW_LDS_BYTES, tid); @@ -170,11 +213,24 @@ WG_KERNEL(SW_ENTRY) uint2 f[KC]; [unroll] for (uint kc = 0; kc < KC; ++kc) f[kc] = sw_lfrag_b(sw_lane_base_m(0u, lane), fk + g * KC + kc); const v8f b = wg_load8f(be, mt * 64u); +#if SW_Q7_CHUNK + v8f acc[NT]; + [unroll] for (int i2 = 0; i2 < NT; ++i2) acc[i2] = b; + [unroll] for (uint kc2 = 0; kc2 < KC; kc2 += 2u) { + [unroll] for (int i3 = 0; i3 < NT; ++i3) { + acc[i3] = wg_wmma_fp8(f[kc2], yf[i3][kc2], acc[i3]); + acc[i3] = wg_wmma_fp8(f[kc2 + 1u], yf[i3][kc2 + 1u], acc[i3]); + if (kc2 + 2u < KC) acc[i3] = hyb_round16(acc[i3]); + } + } + [unroll] for (int i4 = 0; i4 < NT; ++i4) res[i4][g] = hyb_q8_of_chain(acc[i4]); +#else v8f acc[NT]; [unroll] for (int i2 = 0; i2 < NT; ++i2) acc[i2] = b; [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) [unroll] for (int i3 = 0; i3 < NT; ++i3) acc[i3] = wg_wmma_fp8(f[kc2], yf[i3][kc2], acc[i3]); [unroll] for (int i4 = 0; i4 < NT; ++i4) res[i4][g] = hyb_q8_of_chain(acc[i4]); +#endif } [unroll] for (int i5 = 0; i5 < NT; ++i5) { if (tok[i5] < ntok) { diff --git a/clean/dx12/kernels/hyb_swin.hlsl b/clean/dx12/kernels/hyb_swin.hlsl index ec622a6e..4aa8d7f3 100644 --- a/clean/dx12/kernels/hyb_swin.hlsl +++ b/clean/dx12/kernels/hyb_swin.hlsl @@ -11,21 +11,42 @@ // (the table's shared_dec_border) and the skip map with the fine mirror; the member input is RN16(E + S). // HIP twins: the same names in swin_hyb.co (clean/kernels/swin_hyb.hip). // -// @wg-kernel swin_block_c64_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_ENTRY_OVERRIDE=swin_block_c64_hyb,WG_REV_ORDER=1 -// @wg-kernel swin_block_c64_add_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_ENTRY_OVERRIDE=swin_block_c64_add_hyb -// @wg-kernel swin_block_c96_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_ENTRY_OVERRIDE=swin_block_c96_hyb,WG_REV_ORDER=1 -// @wg-kernel swin_block_c96_add_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_ENTRY_OVERRIDE=swin_block_c96_add_hyb -// @wg-kernel swin_block_c128_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_ENTRY_OVERRIDE=swin_block_c128_hyb +// @wg-kernel swin_block_c64_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c64_hyb,WG_REV_ORDER=1 +// @wg-kernel swin_block_c64_add_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c64_add_hyb +// @wg-kernel swin_block_c96_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c96_hyb,WG_REV_ORDER=1 +// @wg-kernel swin_block_c96_add_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c96_add_hyb +// @wg-kernel swin_block_c128_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c128_hyb // swin_block_c64_hyb_scanmut / _c128_hyb_scanmut the fused-square scan's mutants (probe=1, outside the manifest; see // l_swin.hlsl l_swin_block_c32_enc_hyb_scanmut): the select-free norm trees KC 4 and 8 -// @wg-kernel swin_block_c64_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c64_hyb_scanmut -// @wg-kernel swin_block_c64_add_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c64_add_hyb_scanmut +// @wg-kernel swin_block_c64_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c64_hyb_scanmut +// @wg-kernel swin_block_c64_add_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c64_add_hyb_scanmut // swin_block_c96_hyb_scanmut / _c96_add_hyb_scanmut the same for KC 6, as SUBSTITUTE mutants: the KC 6 tree keeps its // per-lane selects, so no square ever feeds an add (RGA: every square's first consumer is a // v_cndmask_b16 or v_permlanex16_b32) and the plain barrier-free build forms no multiply-add; // with HYB_SCAN_MUTANT, hyb_block.hlsli also bypasses the selects so that a square does feed // an add, and the scan must find it (wrong values by design; never in a model build) -// @wg-kernel swin_block_c96_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c96_hyb_scanmut -// @wg-kernel swin_block_c96_add_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c96_add_hyb_scanmut -// @wg-kernel swin_block_c128_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c128_hyb_scanmut +// @wg-kernel swin_block_c96_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_MLP_PAIRS=1,SW_COMMIT_EARLY=1,SW_NORM2_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c96_hyb_scanmut +// @wg-kernel swin_block_c96_add_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_MLP_PAIRS=1,SW_COMMIT_EARLY=1,SW_NORM2_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c96_add_hyb_scanmut +// @wg-kernel swin_block_c128_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c128_hyb_scanmut +// The decoder blocks with their expand fused in (SW_ECL: swin_block.hlsl's fused_expand with the hybrid FP8 point +// hyb_q8_of_chain, E read through the coarse mirror: hyb_fused_expand there): x = the low-resolution map (the previous +// decoder stage's output; 128 channels for dec2, 96 for dec1), xadd = the skip map, w = the block's section whose tail +// (L_TAIL) holds the expand weights (the section expand_c128_hyb / expand_c96_hyb read), aux unused (null). Byte for byte +// expand_c128_hyb + swin_block_c96_add_hyb / expand_c96_hyb + swin_block_c64_add_hyb (the expanded map is never stored). +// swin_block_c96_add_ex_hyb dec2 (SW_ECL 128) swin_block_c64_add_ex_hyb dec1 (SW_ECL 96) +// @wg-kernel swin_block_c96_add_ex_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=128,SW_HYB=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c96_add_ex_hyb +// @wg-kernel swin_block_c64_add_ex_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=1,SW_SAFE=1,SW_ECL=96,SW_HYB=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c64_add_ex_hyb +// @wg-kernel swin_block_c96_add_ex_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=128,SW_HYB=1,SW_MLP_PAIRS=1,SW_COMMIT_EARLY=1,SW_NORM2_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c96_add_ex_hyb_scanmut +// @wg-kernel swin_block_c64_add_ex_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=1,SW_SAFE=1,SW_ECL=96,SW_HYB=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c64_add_ex_hyb_scanmut +// Per-32-chunk FP16-rounded exact q7 twins (SW_Q7_CHUNK=1): same layout/shapes with kord_drow weight packing. +// @wg-kernel swin_block_c64_q7c_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c64_q7c_hyb,WG_REV_ORDER=1 +// @wg-kernel swin_block_c64_add_q7c_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c64_add_q7c_hyb +// @wg-kernel swin_block_c96_q7c_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_MLP_PAIRS=1,SW_COMMIT_EARLY=1,SW_NORM2_EARLY=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c96_q7c_hyb,WG_REV_ORDER=1 +// @wg-kernel swin_block_c96_add_q7c_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_MLP_PAIRS=1,SW_COMMIT_EARLY=1,SW_NORM2_EARLY=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c96_add_q7c_hyb +// @wg-kernel swin_block_c128_q7c_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=swin_block_c128_q7c_hyb +// @wg-kernel swin_block_c64_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c64_q7c_hyb_scanmut +// @wg-kernel swin_block_c64_add_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_HEAD_UNROLL=1,SW_MLP_STEP=2,SW_COMMIT_EARLY=1,SW_NORM1_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c64_add_q7c_hyb_scanmut +// @wg-kernel swin_block_c96_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_MLP_PAIRS=1,SW_COMMIT_EARLY=1,SW_NORM2_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c96_q7c_hyb_scanmut +// @wg-kernel swin_block_c96_add_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,SW_MLP_PAIRS=1,SW_COMMIT_EARLY=1,SW_NORM2_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c96_add_q7c_hyb_scanmut +// @wg-kernel swin_block_c128_q7c_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=128,SW_HEADS=4,SW_MLP=512,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HYB=1,SW_Q7_CHUNK=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=swin_block_c128_q7c_hyb_scanmut #include "swin_block.hlsl" diff --git a/clean/dx12/kernels/l_ops_project.hlsl b/clean/dx12/kernels/l_ops_project.hlsl index 723da953..105b79b1 100644 --- a/clean/dx12/kernels/l_ops_project.hlsl +++ b/clean/dx12/kernels/l_ops_project.hlsl @@ -13,10 +13,23 @@ // this kernel has no branch): RN16 = v_cvt_f16_f32 then the exact widening, the FP8 pack v_cvt_pk_fp8_f32 after the // clamp. The software forms were most of the kernels' instructions. // -// @wg-kernel l_project_gather co=l_ops.co block=256 wave=32 args=p,p,p,u,u defines=PJ_DEC=0 -// @wg-kernel l_dec_project co=l_ops.co block=256 wave=32 args=p,p,p,u,u defines=PJ_DEC=1 +// Fast mode (l_mode=fast, PJ_FAST 1: l_project_gather_fast, l_dec_project_fast; native D3D12 only, no HIP twin): the FP32 +// accumulation runs through all KB K blocks and rounds once, in the FP8 pack, instead of rounding to FP16 after every group of +// 32 inputs (the 128 conversions per lane of pj_rn16 were the kernel's longest chain). The result is the FP32 sum of the +// block's products: it differs from the reference's stepwise FP16 sum (which the hybrid route reproduces bit for bit, and +// l_ops.co's bytes follow) by the FP16 roundings of that sum, at most 3 ulp of FP16 at the largest value; the clamp and the +// pack are unchanged. +// +// @wg-kernel l_project_gather co=l_ops.co block=256 wave=32 args=p,p,p,u,u defines=PJ_DEC=0,WG_LD_A16=1 +// @wg-kernel l_dec_project co=l_ops.co block=256 wave=32 args=p,p,p,u,u defines=PJ_DEC=1,WG_LD_A16=1 +// @wg-kernel l_project_gather_fast co=- entry=l_project_gather block=256 wave=32 args=p,p,p,u,u defines=PJ_DEC=0,WG_LD_A16=1,PJ_FAST=1 +// @wg-kernel l_dec_project_fast co=- entry=l_dec_project block=256 wave=32 args=p,p,p,u,u defines=PJ_DEC=1,WG_LD_A16=1,PJ_FAST=1 #include "wg_platform.hlsli" +#ifndef PJ_FAST +#define PJ_FAST 0 +#endif + WG_ARGS_BEGIN uint src, dst, w; // gather: x (pixel map [2 th][2 tw][32] FP8), features [th][tw][64]; dec: z [th][tw][64], y pixel map int tw, th; @@ -56,32 +69,48 @@ WG_KERNEL(l_project_gather) const int r = tk / tw, c = tk - r * tw; uint2 zf[KB]; #if PJ_DEC - [unroll] for (uint kb = 0; kb < KB; ++kb) - zf[kb] = wg_ld64(src, (uint)tk * 64u + 32u * (kb >> 1) + 16u * hh + 8u * (kb & 1u)); + [unroll] for (uint g0 = 0; g0 < KB / 2; ++g0) { + const uint4 v = wg_ld128(src, (uint)tk * 64u + 32u * g0 + 16u * hh); + zf[2u * g0] = v.xy; + zf[2u * g0 + 1u] = v.zw; + } #else - [unroll] for (uint kb = 0; kb < KB; ++kb) { - const int p = (int)(kb >> 1); - const int pix = (2 * r + (p >> 1)) * (2 * tw) + 2 * c + (p & 1); - zf[kb] = wg_ld64(src, (uint)pix * 32u + 16u * hh + 8u * (kb & 1u)); + [unroll] for (uint p = 0; p < 4u; ++p) { + const int pix = (2 * r + (int)(p >> 1)) * (2 * tw) + 2 * c + (int)(p & 1u); + const uint4 v = wg_ld128(src, (uint)pix * 32u + 16u * hh); + zf[2u * p] = v.xy; + zf[2u * p + 1u] = v.zw; } #endif - [unroll] for (uint mt = 0; mt < MT; ++mt) { - // the loads of this tile's multiplies before its first matrix instruction - v8f acc = wg_load8f(w, (hh * 8u + mt * 16u) * 4u); - uint2 fr[KB]; - [unroll] for (uint k = 0; k < KB; ++k) fr[k] = wg_ld64(w, FRAG0 + (mt * KB + k) * 256u + lane * 8u); + [unroll] for (uint mt = 0; mt < MT; mt += 2u) { + // Pair two adjacent output tiles: interleaves weight loads with WMMAs and RN16 conversions to hide VMEM latency, and coalesces stores to 128-bit. + v8f acc0 = wg_load8f(w, (hh * 8u + mt * 16u) * 4u); + v8f acc1 = wg_load8f(w, (hh * 8u + (mt + 1u) * 16u) * 4u); + uint2 fr0[KB], fr1[KB]; + [unroll] for (uint k = 0; k < KB; ++k) { + fr0[k] = wg_ld64(w, FRAG0 + (mt * KB + k) * 256u + lane * 8u); + fr1[k] = wg_ld64(w, FRAG0 + ((mt + 1u) * KB + k) * 256u + lane * 8u); + } [unroll] for (uint g = 0; g < KB / 2; ++g) { - acc = wg_wmma_fp8(fr[2u * g], zf[2u * g], acc); - acc = wg_wmma_fp8(fr[2u * g + 1u], zf[2u * g + 1u], acc); - acc = pj_rn16(acc); + acc0 = wg_wmma_fp8(fr0[2u * g], zf[2u * g], acc0); + acc1 = wg_wmma_fp8(fr1[2u * g], zf[2u * g], acc1); + acc0 = wg_wmma_fp8(fr0[2u * g + 1u], zf[2u * g + 1u], acc0); + acc1 = wg_wmma_fp8(fr1[2u * g + 1u], zf[2u * g + 1u], acc1); +#if !PJ_FAST + acc0 = pj_rn16(acc0); + acc1 = pj_rn16(acc1); +#endif } #if PJ_DEC - const int s = (int)(mt >> 1), gg = (int)(mt & 1u); + const int s = (int)(mt >> 1); const int pix = (2 * r + (s >> 1)) * (2 * tw) + 2 * c + (s & 1); - wg_st64(dst, (uint)pix * 32u + 16u * hh + 8u * (uint)gg, wg_pack_q8_ags(acc)); + wg_st128(dst, (uint)pix * 32u + 16u * hh, uint4(wg_pack_q8_ags(acc0), wg_pack_q8_ags(acc1))); #else - [unroll] for (uint j = 0; j < 8u; ++j) acc.v[j] = wg_fmin(wg_fmax(acc.v[j], -6.28125f), 6.28125f); - wg_st64(dst, (uint)tk * 64u + hh * 32u + 8u * mt, wg_pack_q8_ags(acc)); + [unroll] for (uint j = 0; j < 8u; ++j) { + acc0.v[j] = wg_fmin(wg_fmax(acc0.v[j], -6.28125f), 6.28125f); + acc1.v[j] = wg_fmin(wg_fmax(acc1.v[j], -6.28125f), 6.28125f); + } + wg_st128(dst, (uint)tk * 64u + hh * 32u + 8u * mt, uint4(wg_pack_q8_ags(acc0), wg_pack_q8_ags(acc1))); #endif } } diff --git a/clean/dx12/kernels/l_post.hlsl b/clean/dx12/kernels/l_post.hlsl index 993e4da1..17351ee0 100644 --- a/clean/dx12/kernels/l_post.hlsl +++ b/clean/dx12/kernels/l_post.hlsl @@ -44,6 +44,26 @@ // @wg-kernel lc12/l_post_recon_p12 co=l_post__lc12.co entry=l_post_recon_p12 block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p defines=LP_P12=1,LP_C12=1 // @wg-kernel lc12/l_post_recon_ldr co=l_post__lc12.co entry=l_post_recon_ldr block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p defines=LP_LDR=1,LP_C12=1 // @wg-kernel lc12/l_post_recon_p12_ldr co=l_post__lc12.co entry=l_post_recon_p12_ldr block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p defines=LP_P12=1,LP_LDR=1,LP_C12=1 +// +// The wave64 form (LP_W64 = 1; runtime WG_L_POST_W64, default off, 1 = this port; 0 = the lc12 entries above): the same kernel (the same +// operations on the same values in the same order, every FP16 rounding kept) in 64-lane waves, tag w64_lc12 (the same +// code object l_post__lc12.co as lc12: the tag only selects the port). The 256-lane workgroup is unchanged (lane (l, k): +// column l & 31 of the row pair lane >> 5), so a wave holds two row pairs. Differences against the lc12 entries, each +// value-preserving: LP_CODE 1 (the FP16 code table is built from one multiplication by the FP32 1 / 255 and the driver's +// conversion instead of an IEEE division per lane: f16(f32(k) f32(1 / 255)) = f16(RN32(k / 255)) for k = 0 ... 255, +// checked for all 256 codes against the division), LP_RPUNI 1 (r_prev = 1 / e_prev is one IEEE division read from the first +// lane: the operand is wave-uniform, so every lane's quotient is the same value), LP_QX 1 (the lane x + 1 of the 2 x 2 block +// is the quad neighbour: QuadReadAcrossX is the lane ^ 1 exchange of wg_xor(v, 1), DPP instead of ds_bpermute), LP_WTEX +// (the wave's first lane of the staging rounds: the wave size in place of 32). +// @wg-kernel w64_lc12/l_post_recon co=l_post__lc12.co entry=l_post_recon block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p defines=LP_C12=1,LP_W64=1,LP_CODE=1,LP_RPUNI=1,LP_QX=1 +// @wg-kernel w64_lc12/l_post_recon_p12 co=l_post__lc12.co entry=l_post_recon_p12 block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p defines=LP_P12=1,LP_C12=1,LP_W64=1,LP_CODE=1,LP_RPUNI=1,LP_QX=1 +// @wg-kernel w64_lc12/l_post_recon_ldr co=l_post__lc12.co entry=l_post_recon_ldr block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p defines=LP_LDR=1,LP_C12=1,LP_W64=1,LP_CODE=1,LP_RPUNI=1,LP_QX=1 +// @wg-kernel w64_lc12/l_post_recon_p12_ldr co=l_post__lc12.co entry=l_post_recon_p12_ldr block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p defines=LP_P12=1,LP_LDR=1,LP_C12=1,LP_W64=1,LP_CODE=1,LP_RPUNI=1,LP_QX=1 +// +// LP_MORIG = 1 (WG_M_POST=orig on native D3D12: Model M's original reconstruction, 3 x 3 gather + encoded-domain +// history candidates, with C1/C2 machine-code forms; port of l_post__morig.co = l_post.hip with WG_LP_M, WG_LP_C1, WG_CR_C2). +// @wg-kernel morig/l_post_recon co=l_post__morig.co entry=l_post_recon block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p defines=LP_C12=1,LP_MORIG=1 +// @wg-kernel morig/l_post_recon_p12 co=l_post__morig.co entry=l_post_recon_p12 block=256 wave=32 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p defines=LP_P12=1,LP_C12=1,LP_MORIG=1 #include "wg_platform.hlsli" #ifndef LP_P12 #define LP_P12 0 @@ -54,6 +74,24 @@ #ifndef LP_LDR #define LP_LDR 0 #endif +#ifndef LP_MORIG +#define LP_MORIG 0 +#endif +#ifndef LP_W64 +#define LP_W64 0 // 1: the wave64 form (see the header) +#endif +#ifndef LP_CODE +#define LP_CODE 0 // 1: the FP16 code table from f32(k) f32(1 / 255) (exact for the 256 codes); 0: the IEEE division +#endif +#ifndef LP_RPUNI +#define LP_RPUNI 0 // 1: r_prev's division from the first lane's operand +#endif +#ifndef LP_QX +#define LP_QX 0 // 1: the 2 x 2 block's neighbour lane by QuadReadAcrossX +#endif +#if LP_W64 != (WG_WAVE == 64) +#error "l_post.hlsl: LP_W64 and the wave size (wave=) must agree" +#endif WG_ARGS_BEGIN uint color, A, B, C, hist_prev, m_near, m_center, m_far, w_p, hist_out, reduced, display; // pointers @@ -65,429 +103,7 @@ WG_ARGS_END #define kThreads 256 #define kTileX 32 #define kTilePairs 8 -#define kStageCap 512 -#define kLWin 4 -#define kTexDw 6 // staged texel: f0 f1 | f2 f3 | f4 f5 | f6 f7 | f8 kA | kB kC (FP16 bits) - -static const float kEncK = asfloat(0x3dddf184u); // 0.36f * 0.30102999566398120f -static const float kDecK = asfloat(0x4113a428u); // 3.32192809488736235f / 0.36f -static const float kDecLn = asfloat(0x40ccac9au); // 2.30258509299404568f / 0.36f -static const float kDecPolyMax = asfloat(0x3d60233du); // 0.35f / kDecLn -static const float kInv255 = asfloat(0x3b808081u); // 1.0f / 255.0f -static const float kInv245 = asfloat(0x3ed0fac6u); // 1.0f / 2.45f -static const float kP5040 = asfloat(0x39500d01u), kP720 = asfloat(0x3ab60b61u), kP120 = asfloat(0x3c088889u); -static const float kP24 = asfloat(0x3d2aaaabu), kP6 = asfloat(0x3e2aaaabu); -static const float k1em4 = asfloat(0x38d1b717u); // 1e-4f -static const float k1em10 = asfloat(0x2edbe6ffu); // 1e-10f -static const float k1p1 = asfloat(0x3f8ccccdu); // 1.1f -static const float k0p05 = asfloat(0x3d4ccccdu); // 0.05f -static const float kDisplayMax = asfloat(0x401ccccdu); // 2.45f -static const float k0p01 = asfloat(0x3c23d70au); // 0.01f -static const float kShapeAB = asfloat(0xbf38a8c1u); // -0.721325f -static const float kShapeC = asfloat(0xbfb8a8c1u); // -1.44265f -static const float kMinNormal = asfloat(0x00800000u); // 2^-126 - -groupshared uint sh_tex[kStageCap * kTexDw]; - -static uint g_z; // 0, opaque to the compiler (from the grid size) -static float g_e, g_ep; // exposures (0 replaced by 1) -static float g_rp; // 1 / e_prev (IEEE division, round to nearest even) -float opq(float x) { return asfloat(asuint(x) ^ g_z); } -half opqh(half x) { return asfloat16((uint16_t)(asuint16(x) ^ (uint16_t)g_z)); } -float mul_nz(float a, float b) { return mad(a, b, asfloat(g_z | 0x80000000u)); } -#ifndef LP_MUT -#define LP_MUT 0 // 1, 2, 4 ... 9: negative controls of the byte checks (never shipped) -#endif -#ifndef LP_DP -#define LP_DP 1 -#endif -#ifndef LP_FMANZ -#define LP_FMANZ 1 -#endif -#ifndef LP_HSCOUNT -#define LP_HSCOUNT 0 // 1: test builds only (clean/l/runner/l_post_edge_check.py): the history fast path's wave counter -#endif -// h(a b) as its own rounding that the driver cannot fuse into a following FP16 add: fma(a, b, -0) with an opaque -0 -// (RN16(a b + -0) = RN16(a b) for every non-NaN pair, zeros included); LP_FMANZ 0: the product through the xor guard -half mulh(half a, half b) -{ -#if LP_FMANZ - return mad(a, b, asfloat16((uint16_t)(0x8000u | g_z))); -#else - return opqh(a * b); -#endif -} -half h_bits(uint b) { return asfloat16((uint16_t)b); } -uint bits_h(half h) { return (uint)asuint16(h); } - -int clampi(int v, int lo, int hi) { int t = v > hi ? hi : v; return t < lo ? lo : t; } -int mini(int a, int b) { return a < b ? a : b; } -int floor_i(float v) { return (int)floor(v); } -float clampf(float v, float lo, float hi) { return min(max(v, lo), hi); } - -// E(v) = kEncK log2(max(fma(100, v, 1), 1e-4)); E_in(v) = E(min(v, 32752)), E_in(NaN) = 0 -float enc_log(float v) { return log2(max(mad(100.0f, v, 1.0f), k1em4)); } -float enc_e(float v) { return kEncK * enc_log(v); } -float enc_in(float v) { return isnan(v) ? 0.0f : enc_e(min(v, 32752.0f)); } - -float dec_m1_poly(float qc) -{ - float y = qc * kDecLn; - float t = mad(y, kP5040, kP720); - t = mad(t, y, kP120); - t = mad(t, y, kP24); - t = mad(t, y, kP6); - t = mad(t, y, 0.5f); - t = mad(t, y, 1.0f); - return t * y; -} -// D(q) = dec_m1(clamp(q, 1e-4, 3)) * 0.01, a NaN passed through (l_dec) -float l_dec(float q) -{ - const float qc = clampf(q, k1em4, 3.0f); -#if LP_DP - // Model M's wave-level skip (post.hlsl post_core_s): the exponential for every lane, the polynomial only when some - // active lane of the wave is below kDecPolyMax; per lane the same select as below, so the same value - float v = exp2(qc * kDecK) - 1.0f; - const bool sm = qc < kDecPolyMax; -#if LP_MUT == 6 - [branch] if (WaveActiveAllTrue(sm)) v = sm ? dec_m1_poly(qc) : v; // mutant 6: all lanes instead of any lane -#else - [branch] if (WaveActiveAnyTrue(sm)) v = sm ? dec_m1_poly(qc) : v; -#endif -#else - const float v = qc < kDecPolyMax ? dec_m1_poly(qc) : exp2(qc * kDecK) - 1.0f; -#endif - return isnan(q) ? q : mul_nz(v, k0p01); -} - -// (_Float16)((float)k / 255.0f) for the code k = 0 ... 255 (an IEEE FP32 division, then round to nearest even: HIP's -// v_div_* sequence and v_cvt_f16_f32): built per workgroup in LDS (code16_build), read by code16 -groupshared uint sh_code[256]; -uint code16(uint v, uint i) { return sh_code[(v >> (8u * i)) & 0xffu]; } - -// lane k of the workgroup (256 lanes) writes code k's FP16 bits: wg_div, then the driver's conversion (wave-uniform) -void code16_build(int lane) -{ - v8f cv; - cv.v[0] = opq(wg_div((float)lane, 255.0f)); - [unroll] for (int i = 1; i < 8; ++i) cv.v[i] = 0.0f; - sh_code[lane] = wg_to_f16_ags(cv).x & 0xffffu; -} - -// a * b as the round-to-odd FP32 value whose FP16 rounding is (f16)(a b) in one rounding (wg_mul_f16 before its -// conversion), and wg_mul_f16's +0 for an exact zero product (a NaN product keeps its conversion) -float mul_odd(float a, float b) -{ - const float p = a * b; - return asfloat(wg_round_odd(p, mad(a, b, -p))); -} -bool mul_zero(float a, float b) -{ - return ((asuint(a) & 0x7fffffffu) == 0u || (asuint(b) & 0x7fffffffu) == 0u) && !isnan(a * b); -} - -// render pixel idx's raw inputs: colour, codes a (A0 A1 A2), b (B0 B1 B2), kernel shape k (C0 | C1 << 16, C2) -void texel_inputs(int idx, out float4 c, out uint a, out uint b, out uint2 k) -{ - const uint ui = (uint)idx; - c = wg_ld4f(color, ui * 16u); -#if LP_P12 - const uint2 d = wg_ld64(A, ui * 8u); - const uint c01 = wg_ld32(C, ui * 4u); - a = d.x & 0xffffffu; - b = (d.x >> 24) | ((d.y & 0xffffu) << 8); - k = uint2(c01, d.y >> 16); // C0 | C1 << 16, C2 (l_coef's C dword 0 and the low half of dword 1) -#else - b = wg_ld32(B, ui * 4u); - a = wg_ld32(A, ui * 4u); - k = wg_ld64(C, ui * 8u); -#endif -} - -void pack_texel(uint f0, uint f1, uint f2, uint a, uint b, uint kA, uint kB, uint kC, out uint t[kTexDw]) -{ - t[0] = f0 | (f1 << 16); - t[1] = f2 | (code16(b, 0u) << 16); - t[2] = code16(b, 1u) | (code16(b, 2u) << 16); - t[3] = code16(a, 0u) | (code16(a, 1u) << 16); - t[4] = code16(a, 2u) | (kA << 16); - t[5] = kB | (kC << 16); -} - -// l_load_texel: the nine FP16 features and the FP16 kernel shape of render pixel idx, as six dwords of FP16 bits. The six -// roundings (E_in of the colour: wg_f2h; the kernel shape: wg_mul_f16) by the driver's conversion (v_cvt_f16_f32, the same -// bits): wave-uniform control flow only. The values going in pass opq or are round-to-odd values (the driver must not -// fold an FP32 operation into the conversion). -void load_texel_hw(int idx, out uint t[kTexDw]) -{ - float4 c; - uint a, b; - uint2 k; - texel_inputs(idx, c, a, b, k); - const float k0 = f16tof32(k.x), k1 = f16tof32(k.x >> 16), k2 = f16tof32(k.y); - v8f cv; -#if LP_LDR - cv.v[0] = opq(c.x); - cv.v[1] = opq(c.y); - cv.v[2] = opq(c.z); -#else - cv.v[0] = opq(enc_in(opq(g_e * c.x))); - cv.v[1] = opq(enc_in(opq(g_e * c.y))); - cv.v[2] = opq(enc_in(opq(g_e * c.z))); -#endif - cv.v[3] = mul_odd(k0, kShapeAB); - cv.v[4] = mul_odd(k1, kShapeAB); - cv.v[5] = mul_odd(k2, kShapeC); - cv.v[6] = 0.0f; - cv.v[7] = 0.0f; - const uint4 h = wg_to_f16_ags(cv); - const uint kA = mul_zero(k0, kShapeAB) ? 0u : (h.y >> 16), kB = mul_zero(k1, kShapeAB) ? 0u : (h.z & 0xffffu); - const uint kC = mul_zero(k2, kShapeC) ? 0u : (h.z >> 16); - pack_texel(h.x & 0xffffu, h.x >> 16, h.y & 0xffffu, a, b, kA, kB, kC, t); -} - -struct LGather { float W; half F[9]; }; - -LGather gather_zero() -{ - LGather g; - g.W = 0.0f; - const half z = h_bits(g_z); // +0, opaque: fma(w, f, +0) keeps its addend - [unroll] for (int k = 0; k < 9; ++k) g.F[k] = z; - return g; -} - -// One tap: eps = fma(h(u v), C, h(h(h(u u) A) + h(h(v v) B))), w = 2^eps (+0 below 2^-126), W += w, -// F_k = fma(h(w), f_k, F_k). uu, vv, uv come in already rounded (and opaque). tap_weight gives w; gather_acc adds the -// tap with h(w) = hw (the FP16 rounding of w: wg_f2h, or the driver's conversion of eight taps' w at once). -float tap_weight(uint t[kTexDw], half uu, half vv, half uv) -{ - const half kA = h_bits(t[4] >> 16), kB = h_bits(t[5]), kC = h_bits(t[5] >> 16); -#if LP_C12 - const half ta = mulh(uu, kA); // (#231's product: opqh(uu kA), or mad(uu, kA, -0) with LP_FMANZ) - const half s = mad(vv, kB, ta); // C1: the row term fused into the sum - const half eps = mad(uv, kC, s); -#else -#if LP_MUT == 1 - const half ta = mulh(uu, kB), tb = mulh(vv, kB); // mutant 1: wrong factor -#else - const half ta = mulh(uu, kA), tb = mulh(vv, kB); -#endif - const half s = tb + ta; - const half eps = mad(uv, kC, s); -#endif - const float w = exp2((float)opqh(eps)); - return w >= kMinNormal ? w : 0.0f; -} -void gather_acc(inout LGather g, uint t[kTexDw], float w, uint hwb) -{ - g.W = g.W + w; - const half hw = h_bits(hwb); - [unroll] for (int k = 0; k < 9; ++k) { - const uint d = t[k >> 1]; - g.F[k] = mad(hw, h_bits((k & 1) ? (d >> 16) : d), g.F[k]); - } -} - -// ---- history: 12-tap Catmull-Rom of the previous full history (history_cr, 8-byte RGBA16F texels) ------------ -float4 cr_weights(float f) -{ - float4 w; -#if LP_C12 - const float f2 = opq(f * f), f3 = opq(f * f2); - w.x = mad(-(f + f3), 0.5f, f2); - w.y = mad(f3, 1.5f, -opq(2.5f * f2)) + 1.0f; - w.w = opq(opq(f3 - f2) * 0.5f); - w.z = ((1.0f - w.x) - w.y) - w.w; - return w; -#endif - w.x = f * (-0.5f + f * (1.0f - 0.5f * f)); - w.y = 1.0f + f * f * (-2.5f + 1.5f * f); - w.z = f * (0.5f + f * (2.0f - 1.5f * f)); - w.w = f * f * (0.5f * f - 0.5f); - return w; -} -float3 h3(uint2 v) { return float3(f16tof32(v.x), f16tof32(v.x >> 16), f16tof32(v.y)); } - -float3 history_cr(float qx, float qy) -{ - const float tx = qx - 0.5f, ty = qy - 0.5f; - const float fx0 = floor(tx), fy0 = floor(ty); - const float4 wx = cr_weights(tx - fx0), wy = cr_weights(ty - fy0); - const int ix = (int)fx0, iy = (int)fy0; - const uint pitch = (uint)P_dw * 8u; - // interior fast path (Model M's history_cr_span): every lane's 4 x 4 footprint inside the image, so the clamps are - // the identity; six 16-byte span loads from one base instead of twelve 8-byte loads, the same texels in the same - // sums (same mad order). Footprint inside: 1 <= ix <= P_dw - 3 and 1 <= iy <= P_dh - 3, the unsigned tests valid only - // for an image of at least 4 x 4 (below, P_d* - 4 would wrap to a huge bound): smaller images take the clamped path. -#if LP_MUT == 8 // mutant 8: the predicate always false (the fast path never taken; same bytes, found by the counter) - const bool interior = false; -#elif LP_MUT == 9 // mutant 9: without the size guard (the span reads past a history narrower or shorter than 4) - const bool interior = and((uint)(ix - 1) <= (uint)(P_dw - 4), (uint)(iy - 1) <= (uint)(P_dh - 4)); -#else - const bool interior = and(and(P_dw >= 4, P_dh >= 4), - and((uint)(ix - 1) <= (uint)(P_dw - 4), (uint)(iy - 1) <= (uint)(P_dh - 4))); -#endif - [branch] if (WaveActiveAllTrue(interior)) { -#if LP_HSCOUNT // test builds only: count the waves taking the fast path, in the first dword after the full history - if (WaveIsFirstLane()) wg_atomic_add(hist_out, (uint)(P_dw * P_dh) * 8u, 1u); -#endif - const uint b0 = hist_prev + (uint)(ix - 1) * 8u + (uint)(iy - 1) * pitch; - const uint b1 = b0 + pitch, b2 = b0 + 2u * pitch, b3 = b0 + 3u * pitch; - const uint4 a0 = wg_mem.Load4(b0 + 8u), a10 = wg_mem.Load4(b1), a11 = wg_mem.Load4(b1 + 16u); - const uint4 a20 = wg_mem.Load4(b2), a21 = wg_mem.Load4(b2 + 16u), a3 = wg_mem.Load4(b3 + (LP_MUT == 4 ? 16u : 8u)); // mutant 4: wrong row span - const float3 zi = float3(0.0f, 0.0f, 0.0f); - const float3 q0 = mad(wx.z, h3(a0.zw), mad(wx.y, h3(a0.xy), zi)); - const float3 q1 = mad(wx.w, h3(a11.zw), mad(wx.z, h3(a11.xy), mad(wx.y, h3(a10.zw), mad(wx.x, h3(a10.xy), zi)))); - const float3 q2 = mad(wx.w, h3(a21.zw), mad(wx.z, h3(a21.xy), mad(wx.y, h3(a20.zw), mad(wx.x, h3(a20.xy), zi)))); - const float3 q3 = mad(wx.z, h3(a3.zw), mad(wx.y, h3(a3.xy), zi)); - const float3 acci = mad(wy.w, q3, mad(wy.z, q2, mad(wy.y, q1, mad(wy.x, q0, zi)))); - const float sxi = ((wx.x + wx.y) + wx.z) + wx.w; - const float normi = (wx.y + wx.z) * (wy.x + wy.w) + sxi * (wy.y + wy.z); - return acci * rcp(normi); - } - uint ro[4], co[4]; - [unroll] for (int k = 0; k < 4; ++k) { - co[k] = hist_prev + (uint)clampi(ix - 1 + k, 0, P_dw - 1) * 8u; - ro[k] = (uint)clampi(iy - 1 + k, 0, P_dh - 1) * pitch; - } - const float3 z = float3(0.0f, 0.0f, 0.0f); - const float3 r0 = mad(wx.z, h3(wg_mem.Load2(ro[0] + co[2])), mad(wx.y, h3(wg_mem.Load2(ro[0] + co[1])), z)); - const float3 r1 = mad(wx.w, h3(wg_mem.Load2(ro[1] + co[3])), mad(wx.z, h3(wg_mem.Load2(ro[1] + co[2])), - mad(wx.y, h3(wg_mem.Load2(ro[1] + co[1])), mad(wx.x, h3(wg_mem.Load2(ro[1] + co[0])), z)))); - const float3 r2 = mad(wx.w, h3(wg_mem.Load2(ro[2] + co[3])), mad(wx.z, h3(wg_mem.Load2(ro[2] + co[2])), - mad(wx.y, h3(wg_mem.Load2(ro[2] + co[1])), mad(wx.x, h3(wg_mem.Load2(ro[2] + co[0])), z)))); - const float3 r3 = mad(wx.z, h3(wg_mem.Load2(ro[3] + co[2])), mad(wx.y, h3(wg_mem.Load2(ro[3] + co[1])), z)); - const float3 acc = mad(wy.w, r3, mad(wy.z, r2, mad(wy.y, r1, mad(wy.x, r0, z)))); - const float sx = ((wx.x + wx.y) + wx.z) + wx.w; - const float norm = (wx.y + wx.z) * (wy.x + wy.w) + sx * (wy.y + wy.z); - return acc * rcp(norm); -} - -// ---- steps 3 to 5 of one D pixel (l_select + l_post_core) ----------------------------------------------------------- -void l_post_core(LGather g, int x, int y, int fx, int fy, float mx[3], float my[3], float s, out float hh[3], - out float oh[3]) -{ - const float inv = rcp(g.W); // rcp(0) = inf: 0 * inf = NaN features (zero total weight) - float fbar[9]; - [unroll] for (int k = 0; k < 9; ++k) fbar[k] = inv * (float)opqh(g.F[k]); - const float sig0 = fbar[3], sig1 = fbar[4], sig2 = fbar[5]; - const bool sb1 = sig1 > sig0; - const float best = sb1 ? sig1 : sig0; - const bool sb2 = sig2 > best; - const float s1 = sb2 ? sig2 : best; - const float m1x = sb2 ? mx[2] : (sb1 ? mx[1] : mx[0]), m1y = sb2 ? my[2] : (sb1 ? my[1] : my[0]); - const bool sf0 = !or(sb1, sb2); - const float so1 = sf0 ? sig1 : sig0, so2 = sb2 ? sig1 : sig2; - const float mo1x = sf0 ? mx[1] : mx[0], mo1y = sf0 ? my[1] : my[0]; -#if LP_MUT == 7 - const float mo2x = sb2 ? mx[2] : mx[1], mo2y = sb2 ? my[1] : my[2]; // mutant 7: wrong candidate motion -#else - const float mo2x = sb2 ? mx[1] : mx[2], mo2y = sb2 ? my[1] : my[2]; -#endif - const bool scc = so2 > so1; - const float s2 = scc ? so2 : so1; - const float m2x = scc ? mo2x : mo1x, m2y = scc ? mo2y : mo1y; - const float q1 = clampf(k1p1 * s1 - k0p05, 0.0f, 1.0f); - const float q2 = clampf(k1p1 * s2 - k0p05, 0.0f, 1.0f); - const float rden = rcp(max(q1 + q2, k1em10)); - float w2 = q2 * rden, w1; - if (w2 < kInv255) { - w2 = 0.0f; - w1 = 1.0f; - } else { - w1 = q1 * rden; - } - const float X = (float)x + 0.5f, Y = (float)y + 0.5f; - const int ncand = w2 != 0.0f ? 2 : 1; - float L[2][3]; - [unroll] for (int n = 0; n < 2; ++n) { - L[n][0] = 0.0f; L[n][1] = 0.0f; L[n][2] = 0.0f; - if (n < ncand) { - const float qx = X + (n == 0 ? m1x : m2x); - const float qy = Y + (n == 0 ? m1y : m2y); -#if LP_MUT == 5 - const bool valid = and(and(and(and(P_reset == 0, qx >= 0.0f), qx <= (float)P_dh), qy >= 0.0f), qy <= (float)P_dh); // mutant 5 -#else - const bool valid = and(and(and(and(P_reset == 0, qx >= 0.0f), qx <= (float)P_dw), qy >= 0.0f), qy <= (float)P_dh); -#endif - if (valid) { - const float3 h = history_cr(qx, qy); -#if LP_LDR - const float3 lq = h; -#else - const float3 lq = float3(l_dec(h.x), l_dec(h.y), l_dec(h.z)) * g_rp; -#endif - L[n][0] = lq.x; - L[n][1] = lq.y; - L[n][2] = lq.z; - } else { - const float4 c = wg_ld4f(color, (uint)(fy * P_rw + fx) * 16u); - L[n][0] = c.x; L[n][1] = c.y; L[n][2] = c.z; - } - } - } - float Hl[3], Cl[3]; - bool hl_inf = false; - [unroll] for (int i = 0; i < 3; ++i) { - const float comb = ncand == 2 ? mad(w1, L[0][i], w2 * L[1][i]) : w1 * L[0][i]; -#if LP_LDR - Hl[i] = opq(comb); -#else - Hl[i] = mul_nz(comb, g_e); -#endif - hl_inf = or(hl_inf, abs(Hl[i]) == asfloat(0x7f800000u)); -#if LP_LDR - Cl[i] = fbar[i]; -#else - Cl[i] = l_dec(fbar[i]); -#endif - } - const float alpha = clampf(opq(s * g.W) * fbar[6], 0.0f, 1.0f); - const float bh2 = mad(alpha, 1.0f - fbar[7], fbar[7]); - const float bo2 = mad(alpha, 1.0f - fbar[8], fbar[8]); - [unroll] for (int i = 0; i < 3; ++i) { - hh[i] = mad(Cl[i] - Hl[i], bh2, Hl[i]); - oh[i] = mad(Cl[i] - Hl[i], bo2, Hl[i]); - } - const float sh = hh[0] + hh[1] + hh[2], so = oh[0] + oh[1] + oh[2]; - if (or(isnan(sh), hl_inf)) { - [unroll] for (int i = 0; i < 3; ++i) hh[i] = Cl[i]; - } - if (or(isnan(so), hl_inf)) { - [unroll] for (int i = 0; i < 3; ++i) oh[i] = Cl[i]; - } -} - -// l_finish_pixel without its stores: motions, steps 3 to 5; H^ in hh, O^ in oh (the kernel converts and stores them) -void finish_pixel(LGather g, int x, int y, float px, float py, float s, out float hh[3], out float oh[3]) -{ - const int fx = clampi(floor_i(px), 0, P_rw - 1), fy = clampi(floor_i(py), 0, P_rh - 1); - float mx[3], my[3]; - const uint mn = wg_ld32(m_near, (uint)(fy * P_rw + fx) * 4u), mf = wg_ld32(m_far, (uint)(fy * P_rw + fx) * 4u); - mx[0] = f16tof32(mn); my[0] = f16tof32(mn >> 16); - mx[2] = f16tof32(mf); my[2] = f16tof32(mf >> 16); - { // motion_bilinear of m_center at (px, py), clamped texel coordinates - const float tx = px - 0.5f, ty = py - 0.5f; - const float x0f = floor(tx), y0f = floor(ty); - const float wx = tx - x0f, wy = ty - y0f; - const int c0 = (int)x0f, r0 = (int)y0f; - const int ca = clampi(c0, 0, P_rw - 1), cb = clampi(c0 + 1, 0, P_rw - 1); - const int ra = clampi(r0, 0, P_rh - 1), rb = clampi(r0 + 1, 0, P_rh - 1); - const uint ma = wg_ld32(m_center, (uint)(ra * P_rw + ca) * 4u), mb = wg_ld32(m_center, (uint)(ra * P_rw + cb) * 4u); - const uint mc = wg_ld32(m_center, (uint)(rb * P_rw + ca) * 4u), md = wg_ld32(m_center, (uint)(rb * P_rw + cb) * 4u); - const float owx = 1.0f - wx, owy = 1.0f - wy; - const float topx = f16tof32(ma) * owx + f16tof32(mb) * wx, topy = f16tof32(ma >> 16) * owx + f16tof32(mb >> 16) * wx; - const float botx = f16tof32(mc) * owx + f16tof32(md) * wx, boty = f16tof32(mc >> 16) * owx + f16tof32(md >> 16) * wx; - mx[1] = topx * owy + botx * wy; - my[1] = topy * owy + boty * wy; - } - l_post_core(g, x, y, fx, fy, mx, my, s, hh, oh); -} - -float lpx(int xx) { return mad(opq((float)xx + 0.5f), P_rx, P_jx); } // fused(x + 1/2, rx, jx) -float lpy(int yy) { return mad(P_ry, opq((float)yy + 0.5f), P_jy); } // fused(ry, y + 1/2, jy) +#include "l_post_core.hlsli" #if LP_P12 && LP_LDR WG_KERNEL(l_post_recon_p12_ldr) @@ -513,7 +129,12 @@ WG_KERNEL(l_post_recon) g_e = e0 == 0.0f ? 1.0f : e0; g_ep = e1 == 0.0f ? 1.0f : e1; } +#if LP_RPUNI + // g_ep is wave-uniform (a root constant or one loaded word): every lane's quotient is the first lane's + g_rp = asfloat(WaveReadLaneFirst(asuint(wg_div(1.0f, g_ep)))); +#else g_rp = wg_div(1.0f, g_ep); +#endif #endif const int lane = (int)wg_lane_id(); const int tiles_x = (P_dw + kTileX - 1) / kTileX; @@ -534,7 +155,9 @@ WG_KERNEL(l_post_recon) const bool staged = ncol > 0 && nrow > 0 && ncol <= kStageCap && nrow <= kStageCap && ncol * nrow <= kStageCap; if (staged) { // wave-uniform rounds (the driver's conversion in load_texel_hw); lanes past the end repeat the last const int ntex = ncol * nrow; + const int wl = wg_uniform(lane & ~(kTexWave - 1)); // this wave's first lane (uniform) [loop] for (int base = 0; base < ntex; base += kThreads) { + [branch] if (base + wl < ntex) { // a wave wholly past the end has nothing to store const int i = base + lane, ii = mini(i, ntex - 1); const int r = ii / ncol, c = ii - r * ncol; const int idx = clampi(r0 + r, 0, P_rh - 1) * P_rw + clampi(c0 + c, 0, P_rw - 1); @@ -543,6 +166,7 @@ WG_KERNEL(l_post_recon) if (i < ntex) { [unroll] for (int d = 0; d < kTexDw; ++d) sh_tex[i * kTexDw + d] = t[d]; } + } } } GroupMemoryBarrierWithGroupSync(); @@ -579,31 +203,13 @@ WG_KERNEL(l_post_recon) // the staged texel's LDS index without per-tap multiplies: one base per lane, the row stride and the column // step wave-uniform (integer identity: ((b + j - r0) ncol + (ax + i - c0)) kTexDw) const int tb0 = ((b - 1 - r0) * ncol + (ax - 1 - c0)) * kTexDw, rstride = ncol * kTexDw; - [loop] for (int i = -1; i <= kLWin - 2; ++i) { - const half u = dx + (half)(float)i; - const half uu = mulh(u, u); - uint t[kLWin][kTexDw]; - v8f wv; - [unroll] for (int j = -1; j <= kLWin - 2; ++j) { - if (staged) { - const int base = tb0 + (j + 1) * rstride + (i + 1) * kTexDw -#if LP_MUT == 2 - + (j == 2 && i == 2 ? kTexDw : 0) // mutant 2: one tap reads the wrong texel -#endif - ; - [unroll] for (int d = 0; d < kTexDw; ++d) t[j + 1][d] = sh_tex[base + d]; - } else { - load_texel_hw(clampi(b + j, 0, P_rh - 1) * P_rw + clampi(ax + i, 0, P_rw - 1), t[j + 1]); - } - wv.v[2 * (j + 1)] = tap_weight(t[j + 1], uu, vv0[j + 1], mulh(u, v0[j + 1])); - wv.v[2 * (j + 1) + 1] = tap_weight(t[j + 1], uu, vv1[j + 1], mulh(u, v1[j + 1])); - } - const uint4 hw = wg_to_f16_ags(wv); - [unroll] for (int jj = 0; jj < kLWin; ++jj) { - const uint hp = jj == 0 ? hw.x : (jj == 1 ? hw.y : (jj == 2 ? hw.z : hw.w)); - gather_acc(g0, t[jj], wv.v[2 * jj], hp & 0xffffu); - gather_acc(g1, t[jj], wv.v[2 * jj + 1], hp >> 16); - } + // the hot loop reads the staged texels; the unstaged fallback (a tile whose render footprint does not fit) is its own loop + [branch] if (staged) { + [loop] for (int i = -1; i <= (kLWin - 2); ++i) + gather_col(i, dx, tb0, rstride, b, ax, v0, v1, vv0, vv1, g0, g1); + } else { + [loop] for (int i = -1; i <= kLWin - 2; ++i) + gather_col(i, dx, tb0, rstride, b, ax, v0, v1, vv0, vv1, g0, g1); } // the two rows of the pair (wave-uniform: every lane runs both; a missing second row is not stored and adds +0 as @@ -615,8 +221,12 @@ WG_KERNEL(l_post_recon) LGather g = g0; if (second) g = g1; float hh[3], oo[3]; - finish_pixel(g, x, y0 + row, px, second ? py1 : py0, s, hh, oo); + const MotRaw mot = motion_load(px, second ? py1 : py0); + finish_pixel(g, x, y0 + row, mot, s, hh, oo); v8f cv; +#if !LP_LDR && !LP_MORIG + float el[3]; +#endif [unroll] for (int ci = 0; ci < 3; ++ci) { #if LP_LDR // h(H^); the display code floor(clamp(fused(O^ N + 1/2), 0, N)), then h(code RN32(1 / N)) (one rounding or @@ -625,8 +235,14 @@ WG_KERNEL(l_post_recon) const float k = asfloat(ci == 2 ? 0x3a802008u : 0x3a001002u); cv.v[ci] = opq(hh[ci]); cv.v[3 + ci] = opq(floor(clampf(mad(oo[ci], n, 0.5f), 0.0f, n)) * k); +#elif LP_MORIG + // Spec 06 draft 6: full-history store rounds FP32 -> FP16 toward zero (RTZ; f32tof16 -> v_cvt_pkrtz_f16_f32, + // matching HIP WG_LP_M wg_h2). Display channels stay RNE via wg_to_f16_ags. + cv.v[ci] = 0.0f; + cv.v[3 + ci] = opq(clampf(enc_e(oo[ci]), 0.0f, kDisplayMax)); #else - cv.v[ci] = mul_odd(kEncK, enc_log(hh[ci])); + el[ci] = enc_log(hh[ci]); + cv.v[ci] = mul_odd(kEncK, el[ci]); cv.v[3 + ci] = opq(clampf(enc_e(oo[ci]), 0.0f, kDisplayMax)); #endif } @@ -637,12 +253,17 @@ WG_KERNEL(l_post_recon) if (and(active, or(!second, has1))) { #if LP_LDR const uint q0 = hc.x & 0xffffu, q1 = hc.x >> 16, q2 = hc.y & 0xffffu; + wg_st64(hist_out, (uint)(y * P_dw + x) * 8u, uint2(q0 | (q1 << 16), q2)); +#elif LP_MORIG + const uint q01 = wg_h2(opq(enc_e(hh[0])), opq(enc_e(hh[1]))); + const uint q2 = f32tof16(opq(enc_e(hh[2]))); + wg_st64(hist_out, (uint)(y * P_dw + x) * 8u, uint2(q01, q2)); #else - const uint q0 = mul_zero(kEncK, enc_log(hh[0])) ? 0u : (hc.x & 0xffffu); - const uint q1 = mul_zero(kEncK, enc_log(hh[1])) ? 0u : (hc.x >> 16); - const uint q2 = mul_zero(kEncK, enc_log(hh[2])) ? 0u : (hc.y & 0xffffu); -#endif + const uint q0 = mul_zero_k(el[0]) ? 0u : (hc.x & 0xffffu); + const uint q1 = mul_zero_k(el[1]) ? 0u : (hc.x >> 16); + const uint q2 = mul_zero_k(el[2]) ? 0u : (hc.y & 0xffffu); wg_st64(hist_out, (uint)(y * P_dw + x) * 8u, uint2(q0 | (q1 << 16), q2)); +#endif const int di = y * pitch + x; wg_st16(display, (uint)di * 2u, hc.y >> 16); wg_st16(display, (uint)(plane + di) * 2u, hc.z & 0xffffu); @@ -654,7 +275,11 @@ WG_KERNEL(l_post_recon) } // lane x + 1 is lane ^ 1 (same wave) float o[3]; +#if LP_QX + [unroll] for (int i = 0; i < 3; ++i) o[i] = QuadReadAcrossX(r[i]); // lane ^ 1 +#else [unroll] for (int i = 0; i < 3; ++i) o[i] = wg_xor(r[i], 1u); +#endif if (active && has1 && (x & 1) == 0 && x + 1 < P_dw) { uint code = 0u; [unroll] for (int i = 0; i < 3; ++i) { diff --git a/clean/dx12/kernels/l_post_core.hlsli b/clean/dx12/kernels/l_post_core.hlsli new file mode 100644 index 00000000..618d75c9 --- /dev/null +++ b/clean/dx12/kernels/l_post_core.hlsli @@ -0,0 +1,646 @@ +// SPDX-License-Identifier: MIT +// The per-pixel reconstruction of Model L (l_post.hlsl: the staged-texel loads, the FP16 4 x 4 gather, the history candidates, +// steps 3 to 5 of one D pixel) shared by l_post.hlsl (the kernel that writes the display image) and l_post_tf.hlsl (the +// true-fusion kernel). The including kernel declares WG_ARGS (the names color, A, B, C, hist_prev, m_near, m_center, m_far, +// w_p, hist_out, reduced, P_*, expo are used here) and the LP_* switches first; every function below is moved from +// l_post.hlsl unchanged (the DXIL of its kernels is unchanged by the move). +#pragma once +#ifndef LP_HSEQ +#define LP_HSEQ 0 // 1: history_cr issues its loads in two dependent groups (fewer live registers) +#endif +#ifndef LP_FBLAZY +#define LP_FBLAZY 0 +#endif +#ifndef LP_PIDIV +#define LP_PIDIV 0 // 1: the staged route's pre-exposure division folded into every colour read (l_post_tf_p12_pf) +#endif +#if LP_PIDIV +#include "wg_pidiv.hlsli" +#endif +#if LP_W64 +// The driver's matrix conversion fragment (wg_ags.hlsli) is a wave32 form (RGA: the same intrinsic compiled in a wave64 +// kernel gives another conversion sequence: 112 instead of 182 v_cvt_f16_f32, no packs; not validated, not used), and the +// software RNE conversion (wg_to_f16: wg_f2h) is ~12 000 instructions per kernel in the 64-lane form. In 64-lane waves every +// "driver conversion" is the single-value conversion of the driver's intrinsic channel (op 0x1C, immediate 1: one hardware +// v_cvt_f16_f32, round to nearest even; the same call as rr_d0r.hlsl / rr_output_fast.hlsli), the same bits as wg_f2h (NaN +// payloads included). Wave-uniform control flow only, as every call of the channel. +#include "wg_ags.hlsli" +uint lp_f2h_hw(float x) { return wg_ags_call(0x1cu, 0u, 1u, asuint(x), 0u) & 0xffffu; } +uint4 wg_to_f16_ags(v8f d) +{ + return uint4(lp_f2h_hw(d.v[0]) | (lp_f2h_hw(d.v[1]) << 16), lp_f2h_hw(d.v[2]) | (lp_f2h_hw(d.v[3]) << 16), + lp_f2h_hw(d.v[4]) | (lp_f2h_hw(d.v[5]) << 16), lp_f2h_hw(d.v[6]) | (lp_f2h_hw(d.v[7]) << 16)); +} +#endif +#ifndef kStageCap +#define kStageCap 512 // staged render texels (l_post_tf.hlsl: its own cap) +#endif +#define kLWin (LP_MORIG ? 3 : 4) +#define kTexWave WG_WAVE // the wave's first lane of the staging rounds (LP_WTEX) +#define kTexDw 6 // staged texel: f0 f1 | f2 f3 | f4 f5 | f6 f7 | f8 kA | kB kC (FP16 bits) + +static const float kEncK = asfloat(0x3dddf184u); // 0.36f * 0.30102999566398120f +static const float kDecK = asfloat(0x4113a428u); // 3.32192809488736235f / 0.36f +static const float kDecLn = asfloat(0x40ccac9au); // 2.30258509299404568f / 0.36f +static const float kDecPolyMax = asfloat(0x3d60233du); // 0.35f / kDecLn +static const float kInv255 = asfloat(0x3b808081u); // 1.0f / 255.0f +static const float kInv245 = asfloat(0x3ed0fac6u); // 1.0f / 2.45f +static const float kP5040 = asfloat(0x39500d01u), kP720 = asfloat(0x3ab60b61u), kP120 = asfloat(0x3c088889u); +static const float kP24 = asfloat(0x3d2aaaabu), kP6 = asfloat(0x3e2aaaabu); +static const float k1em4 = asfloat(0x38d1b717u); // 1e-4f +static const float k1em10 = asfloat(0x2edbe6ffu); // 1e-10f +static const float k1p1 = asfloat(0x3f8ccccdu); // 1.1f +static const float k0p05 = asfloat(0x3d4ccccdu); // 0.05f +static const float kDisplayMax = asfloat(0x401ccccdu); // 2.45f +static const float k0p01 = asfloat(0x3c23d70au); // 0.01f +static const float kShapeAB = asfloat(0xbf38a8c1u); // -0.721325f +static const float kShapeC = asfloat(0xbfb8a8c1u); // -1.44265f +static const float kMinNormal = asfloat(0x00800000u); // 2^-126 + +groupshared uint sh_tex[kStageCap * kTexDw]; + +static uint g_z; // 0, opaque to the compiler (from the grid size) +static float g_e, g_ep; // exposures (0 replaced by 1) +static float g_rp; // 1 / e_prev (IEEE division, round to nearest even) +#if LP_PIDIV +static PiDiv g_pd; // the pre-exposure division (pidiv_make of the launch) +#endif +float opq(float x) { return asfloat(asuint(x) ^ g_z); } +half opqh(half x) { return asfloat16((uint16_t)(asuint16(x) ^ (uint16_t)g_z)); } +float mul_nz(float a, float b) { return mad(a, b, asfloat(g_z | 0x80000000u)); } +#ifndef LP_MUT +#define LP_MUT 0 // 1, 2, 4 ... 9: negative controls of the byte checks (never shipped) +#endif +#ifndef LP_DP +#define LP_DP 1 +#endif +#ifndef LP_FMANZ +#define LP_FMANZ 1 +#endif +#ifndef LP_HSCOUNT +#define LP_HSCOUNT 0 // 1: test builds only (clean/l/runner/l_post_edge_check.py): the history fast path's wave counter +#endif +// h(a b) as its own rounding that the driver cannot fuse into a following FP16 add: fma(a, b, -0) with an opaque -0 +// (RN16(a b + -0) = RN16(a b) for every non-NaN pair, zeros included); LP_FMANZ 0: the product through the xor guard +half mulh(half a, half b) +{ +#if LP_FMANZ + return mad(a, b, asfloat16((uint16_t)(0x8000u | g_z))); +#else + return opqh(a * b); +#endif +} +half h_bits(uint b) { return asfloat16((uint16_t)b); } +uint bits_h(half h) { return (uint)asuint16(h); } + +int clampi(int v, int lo, int hi) { int t = v > hi ? hi : v; return t < lo ? lo : t; } +int mini(int a, int b) { return a < b ? a : b; } +int floor_i(float v) { return (int)floor(v); } +float clampf(float v, float lo, float hi) { return min(max(v, lo), hi); } + +// E(v) = kEncK log2(max(fma(100, v, 1), 1e-4)); E_in(v) = E(min(v, 32752)), E_in(NaN) = 0 +float enc_log(float v) { return log2(max(mad(100.0f, v, 1.0f), k1em4)); } +float enc_e(float v) { return kEncK * enc_log(v); } +float enc_in(float v) { return isnan(v) ? 0.0f : enc_e(min(v, 32752.0f)); } + +float dec_m1_poly(float qc) +{ + float y = qc * kDecLn; + float t = mad(y, kP5040, kP720); + t = mad(t, y, kP120); + t = mad(t, y, kP24); + t = mad(t, y, kP6); + t = mad(t, y, 0.5f); + t = mad(t, y, 1.0f); + return t * y; +} +// D(q) = dec_m1(clamp(q, 1e-4, 3)) * 0.01, a NaN passed through (l_dec) +float l_dec(float q) +{ + const float qc = clampf(q, k1em4, 3.0f); +#if LP_DP + // Model M's wave-level skip (post.hlsl post_core_s): the exponential for every lane, the polynomial only when some + // active lane of the wave is below kDecPolyMax; per lane the same select as below, so the same value + float v = exp2(qc * kDecK) - 1.0f; + const bool sm = qc < kDecPolyMax; +#if LP_MUT == 6 + [branch] if (WaveActiveAllTrue(sm)) v = sm ? dec_m1_poly(qc) : v; // mutant 6: all lanes instead of any lane +#else + [branch] if (WaveActiveAnyTrue(sm)) v = sm ? dec_m1_poly(qc) : v; +#endif +#else + const float v = qc < kDecPolyMax ? dec_m1_poly(qc) : exp2(qc * kDecK) - 1.0f; +#endif + return isnan(q) ? q : mul_nz(v, k0p01); +} + +// (_Float16)((float)k / 255.0f) for the code k = 0 ... 255 (an IEEE FP32 division, then round to nearest even: HIP's +// v_div_* sequence and v_cvt_f16_f32): built per workgroup in LDS (code16_build), read by code16 +groupshared uint sh_code[256]; +uint code16(uint v, uint i) { return sh_code[(v >> (8u * i)) & 0xffu]; } + +// lane k of the workgroup (256 lanes) writes code k's FP16 bits: wg_div, then the driver's conversion (wave-uniform) +void code16_build(int lane) +{ +#if LP_W64 + // the 64-lane form: one hardware conversion (the other seven slots of wg_to_f16_ags(cv) are +0 and unused) +#if LP_CODE + sh_code[lane] = lp_f2h_hw(opq((float)lane * kInv255)); +#else + sh_code[lane] = lp_f2h_hw(opq(wg_div((float)lane, 255.0f))); +#endif +#else + v8f cv; +#if LP_CODE + cv.v[0] = opq((float)lane * kInv255); // f16(f32(k) f32(1 / 255)) = f16(RN32(k / 255)), all 256 codes (header) +#else + cv.v[0] = opq(wg_div((float)lane, 255.0f)); +#endif + [unroll] for (int i = 1; i < 8; ++i) cv.v[i] = 0.0f; + sh_code[lane] = wg_to_f16_ags(cv).x & 0xffffu; +#endif +} + +// a * b as the round-to-odd FP32 value whose FP16 rounding is (f16)(a b) in one rounding (wg_mul_f16 before its +// conversion), and wg_mul_f16's +0 for an exact zero product (a NaN product keeps its conversion) +float mul_odd(float a, float b) +{ + const float p = a * b; + return asfloat(wg_round_odd(p, mad(a, b, -p))); +} +bool mul_zero(float a, float b) +{ + return ((asuint(a) & 0x7fffffffu) == 0u || (asuint(b) & 0x7fffffffu) == 0u) && !isnan(a * b); +} +// mul_zero(a, c) for a nonzero finite constant c: a is +-0 (the product is then +-0, never NaN); a NaN or infinity a is not +bool mul_zero_k(float a) +{ + return (asuint(a) & 0x7fffffffu) == 0u; +} + +// render pixel idx's raw inputs: colour, codes a (A0 A1 A2), b (B0 B1 B2), kernel shape k (C0 | C1 << 16, C2) +void texel_inputs(int idx, out float4 c, out uint a, out uint b, out uint2 k) +{ + const uint ui = (uint)idx; + c = wg_ld4f(color, ui * 16u); +#if LP_P12 + const uint2 d = wg_ld64(A, ui * 8u); + const uint c01 = wg_ld32(C, ui * 4u); + a = d.x & 0xffffffu; + b = (d.x >> 24) | ((d.y & 0xffffu) << 8); + k = uint2(c01, d.y >> 16); // C0 | C1 << 16, C2 (l_coef's C dword 0 and the low half of dword 1) +#else + b = wg_ld32(B, ui * 4u); + a = wg_ld32(A, ui * 4u); + k = wg_ld64(C, ui * 8u); +#endif +} + +void pack_texel(uint f0, uint f1, uint f2, uint a, uint b, uint kA, uint kB, uint kC, out uint t[kTexDw]) +{ + t[0] = f0 | (f1 << 16); + t[1] = f2 | (code16(b, 0u) << 16); + t[2] = code16(b, 1u) | (code16(b, 2u) << 16); + t[3] = code16(a, 0u) | (code16(a, 1u) << 16); + t[4] = code16(a, 2u) | (kA << 16); + t[5] = kB | (kC << 16); +} + +// l_load_texel: the nine FP16 features and the FP16 kernel shape of render pixel idx, as six dwords of FP16 bits. The six +// roundings (E_in of the colour: wg_f2h; the kernel shape: wg_mul_f16) by the driver's conversion (v_cvt_f16_f32, the same +// bits): wave-uniform control flow only. The values going in pass opq or are round-to-odd values (the driver must not +// fold an FP32 operation into the conversion). +// the conversions of load_texel_hw on the raw inputs (colour c, codes a (A0 A1 A2), b (B0 B1 B2), kernel shape k); LP_PIDIV: the +// colour is divided by the pre-exposure first, as color_divide stored it +void texel_make(float4 c, uint a, uint b, uint2 k, out uint t[kTexDw]) +{ +#if LP_PIDIV + c.xyz = asfloat(asuint(pidiv3(c.xyz, g_pd, g_z)) ^ g_z); +#endif + const float k0 = f16tof32(k.x), k1 = f16tof32(k.x >> 16), k2 = f16tof32(k.y); + v8f cv; +#if LP_LDR + cv.v[0] = opq(c.x); + cv.v[1] = opq(c.y); + cv.v[2] = opq(c.z); +#else + cv.v[0] = opq(enc_in(opq(g_e * c.x))); + cv.v[1] = opq(enc_in(opq(g_e * c.y))); + cv.v[2] = opq(enc_in(opq(g_e * c.z))); +#endif + cv.v[3] = mul_odd(k0, kShapeAB); + cv.v[4] = mul_odd(k1, kShapeAB); + cv.v[5] = mul_odd(k2, kShapeC); + cv.v[6] = 0.0f; + cv.v[7] = 0.0f; + const uint4 h = wg_to_f16_ags(cv); + const uint kA = mul_zero_k(k0) ? 0u : (h.y >> 16), kB = mul_zero_k(k1) ? 0u : (h.z & 0xffffu); + const uint kC = mul_zero_k(k2) ? 0u : (h.z >> 16); + pack_texel(h.x & 0xffffu, h.x >> 16, h.y & 0xffffu, a, b, kA, kB, kC, t); +} + +// (the original body, kept inline: the DXIL of the kernels that stage per workgroup is unchanged) +void load_texel_hw(int idx, out uint t[kTexDw]) +{ + float4 c; + uint a, b; + uint2 k; + texel_inputs(idx, c, a, b, k); + const float k0 = f16tof32(k.x), k1 = f16tof32(k.x >> 16), k2 = f16tof32(k.y); + v8f cv; +#if LP_LDR + cv.v[0] = opq(c.x); + cv.v[1] = opq(c.y); + cv.v[2] = opq(c.z); +#else + cv.v[0] = opq(enc_in(opq(g_e * c.x))); + cv.v[1] = opq(enc_in(opq(g_e * c.y))); + cv.v[2] = opq(enc_in(opq(g_e * c.z))); +#endif + cv.v[3] = mul_odd(k0, kShapeAB); + cv.v[4] = mul_odd(k1, kShapeAB); + cv.v[5] = mul_odd(k2, kShapeC); + cv.v[6] = 0.0f; + cv.v[7] = 0.0f; + const uint4 h = wg_to_f16_ags(cv); + const uint kA = mul_zero_k(k0) ? 0u : (h.y >> 16), kB = mul_zero_k(k1) ? 0u : (h.z & 0xffffu); + const uint kC = mul_zero_k(k2) ? 0u : (h.z >> 16); + pack_texel(h.x & 0xffffu, h.x >> 16, h.y & 0xffffu, a, b, kA, kB, kC, t); +} + +struct LGather { float W; half F[9]; }; +#define LG_F(g, k) (g).F[k] + +LGather gather_zero() +{ + LGather g; + g.W = 0.0f; + const half z = h_bits(g_z); // +0, opaque: fma(w, f, +0) keeps its addend + [unroll] for (int k = 0; k < 9; ++k) g.F[k] = z; + return g; +} + +// One tap: eps = fma(h(u v), C, h(h(h(u u) A) + h(h(v v) B))), w = 2^eps (+0 below 2^-126), W += w, +// F_k = fma(h(w), f_k, F_k). uu, vv, uv come in already rounded (and opaque). tap_weight gives w; gather_acc adds the +// tap with h(w) = hw (the FP16 rounding of w: wg_f2h, or the driver's conversion of eight taps' w at once). +float tap_weight(uint t[kTexDw], half uu, half vv, half uv) +{ + const half kA = h_bits(t[4] >> 16), kB = h_bits(t[5]), kC = h_bits(t[5] >> 16); +#if LP_C12 + const half ta = mulh(uu, kA); // (#231's product: opqh(uu kA), or mad(uu, kA, -0) with LP_FMANZ) + const half s = mad(vv, kB, ta); // C1: the row term fused into the sum + const half eps = mad(uv, kC, s); +#else +#if LP_MUT == 1 + const half ta = mulh(uu, kB), tb = mulh(vv, kB); // mutant 1: wrong factor +#else + const half ta = mulh(uu, kA), tb = mulh(vv, kB); +#endif + const half s = tb + ta; + const half eps = mad(uv, kC, s); +#endif + const float w = exp2((float)opqh(eps)); + return w >= kMinNormal ? w : 0.0f; +} +void gather_acc(inout LGather g, uint t[kTexDw], float w, uint hwb) +{ + g.W = g.W + w; + const half hw = h_bits(hwb); + [unroll] for (int k = 0; k < 9; ++k) { + const uint d = t[k >> 1]; + g.F[k] = mad(hw, h_bits((k & 1) ? (d >> 16) : d), g.F[k]); + } +} + +// ---- history: 12-tap Catmull-Rom of the previous full history (history_cr, 8-byte RGBA16F texels) ------------ +float4 cr_weights(float f) +{ + float4 w; +#if LP_C12 + const float f2 = opq(f * f), f3 = opq(f * f2); + w.x = mad(-(f + f3), 0.5f, f2); + w.y = mad(f3, 1.5f, -opq(2.5f * f2)) + 1.0f; + w.w = opq(opq(f3 - f2) * 0.5f); + w.z = ((1.0f - w.x) - w.y) - w.w; + return w; +#endif + w.x = f * (-0.5f + f * (1.0f - 0.5f * f)); + w.y = 1.0f + f * f * (-2.5f + 1.5f * f); + w.z = f * (0.5f + f * (2.0f - 1.5f * f)); + w.w = f * f * (0.5f * f - 0.5f); + return w; +} +float3 h3(uint2 v) { return float3(f16tof32(v.x), f16tof32(v.x >> 16), f16tof32(v.y)); } + +float3 history_cr(float qx, float qy) +{ + const float tx = qx - 0.5f, ty = qy - 0.5f; + const float fx0 = floor(tx), fy0 = floor(ty); + const float4 wx = cr_weights(tx - fx0), wy = cr_weights(ty - fy0); + const int ix = (int)fx0, iy = (int)fy0; + const uint pitch = (uint)P_dw * 8u; + // interior fast path (Model M's history_cr_span): every lane's 4 x 4 footprint inside the image, so the clamps are + // the identity; six 16-byte span loads from one base instead of twelve 8-byte loads, the same texels in the same + // sums (same mad order). Footprint inside: 1 <= ix <= P_dw - 3 and 1 <= iy <= P_dh - 3, the unsigned tests valid only + // for an image of at least 4 x 4 (below, P_d* - 4 would wrap to a huge bound): smaller images take the clamped path. +#if LP_MUT == 8 // mutant 8: the predicate always false (the fast path never taken; same bytes, found by the counter) + const bool interior = false; +#elif LP_MUT == 9 // mutant 9: without the size guard (the span reads past a history narrower or shorter than 4) + const bool interior = and((uint)(ix - 1) <= (uint)(P_dw - 4), (uint)(iy - 1) <= (uint)(P_dh - 4)); +#else + const bool interior = and(and(P_dw >= 4, P_dh >= 4), + and((uint)(ix - 1) <= (uint)(P_dw - 4), (uint)(iy - 1) <= (uint)(P_dh - 4))); +#endif + [branch] if (WaveActiveAllTrue(interior)) { +#if LP_HSCOUNT // test builds only: count the waves taking the fast path, in the first dword after the full history + if (WaveIsFirstLane()) wg_atomic_add(hist_out, (uint)(P_dw * P_dh) * 8u, 1u); +#endif +#if LP_HSEQ + const uint b0 = hist_prev + (uint)(ix - 1) * 8u + (uint)(iy - 1) * pitch; + const uint b1 = b0 + pitch, b2 = b0 + 2u * pitch, b3 = b0 + 3u * pitch; + const uint4 a0 = wg_mem.Load4(b0 + 8u), a10 = wg_mem.Load4(b1), a11 = wg_mem.Load4(b1 + 16u); + const float3 zi = float3(0.0f, 0.0f, 0.0f); + const float3 q0 = mad(wx.z, h3(a0.zw), mad(wx.y, h3(a0.xy), zi)); + const float3 q1 = mad(wx.w, h3(a11.zw), mad(wx.z, h3(a11.xy), mad(wx.y, h3(a10.zw), mad(wx.x, h3(a10.xy), zi)))); + const uint dz = (asuint(q1.x) ^ asuint(q0.y)) & g_z; // the second group of loads after the first group's sums (an opaque +0 in their address): 12 live load registers, not 24 + const uint4 a20 = wg_mem.Load4(b2 + dz), a21 = wg_mem.Load4(b2 + 16u + dz), a3 = wg_mem.Load4(b3 + (LP_MUT == 4 ? 16u : 8u) + dz); // mutant 4: wrong row span + const float3 q2 = mad(wx.w, h3(a21.zw), mad(wx.z, h3(a21.xy), mad(wx.y, h3(a20.zw), mad(wx.x, h3(a20.xy), zi)))); + const float3 q3 = mad(wx.z, h3(a3.zw), mad(wx.y, h3(a3.xy), zi)); + const float3 acci = mad(wy.w, q3, mad(wy.z, q2, mad(wy.y, q1, mad(wy.x, q0, zi)))); + const float sxi = ((wx.x + wx.y) + wx.z) + wx.w; + const float normi = (wx.y + wx.z) * (wy.x + wy.w) + sxi * (wy.y + wy.z); +#else + const uint b0 = hist_prev + (uint)(ix - 1) * 8u + (uint)(iy - 1) * pitch; + const uint b1 = b0 + pitch, b2 = b0 + 2u * pitch, b3 = b0 + 3u * pitch; + const uint4 a0 = wg_mem.Load4(b0 + 8u), a10 = wg_mem.Load4(b1), a11 = wg_mem.Load4(b1 + 16u); + const uint4 a20 = wg_mem.Load4(b2), a21 = wg_mem.Load4(b2 + 16u), a3 = wg_mem.Load4(b3 + (LP_MUT == 4 ? 16u : 8u)); // mutant 4: wrong row span + const float3 zi = float3(0.0f, 0.0f, 0.0f); + const float3 q0 = mad(wx.z, h3(a0.zw), mad(wx.y, h3(a0.xy), zi)); + const float3 q1 = mad(wx.w, h3(a11.zw), mad(wx.z, h3(a11.xy), mad(wx.y, h3(a10.zw), mad(wx.x, h3(a10.xy), zi)))); + const float3 q2 = mad(wx.w, h3(a21.zw), mad(wx.z, h3(a21.xy), mad(wx.y, h3(a20.zw), mad(wx.x, h3(a20.xy), zi)))); + const float3 q3 = mad(wx.z, h3(a3.zw), mad(wx.y, h3(a3.xy), zi)); + const float3 acci = mad(wy.w, q3, mad(wy.z, q2, mad(wy.y, q1, mad(wy.x, q0, zi)))); + const float sxi = ((wx.x + wx.y) + wx.z) + wx.w; + const float normi = (wx.y + wx.z) * (wy.x + wy.w) + sxi * (wy.y + wy.z); +#endif + return acci * rcp(normi); + } + uint ro[4], co[4]; + [unroll] for (int k = 0; k < 4; ++k) { + co[k] = hist_prev + (uint)clampi(ix - 1 + k, 0, P_dw - 1) * 8u; + ro[k] = (uint)clampi(iy - 1 + k, 0, P_dh - 1) * pitch; + } +#if LP_HSEQ + const float3 z = float3(0.0f, 0.0f, 0.0f); + const float3 r0 = mad(wx.z, h3(wg_mem.Load2(ro[0] + co[2])), mad(wx.y, h3(wg_mem.Load2(ro[0] + co[1])), z)); + const float3 r1 = mad(wx.w, h3(wg_mem.Load2(ro[1] + co[3])), mad(wx.z, h3(wg_mem.Load2(ro[1] + co[2])), + mad(wx.y, h3(wg_mem.Load2(ro[1] + co[1])), mad(wx.x, h3(wg_mem.Load2(ro[1] + co[0])), z)))); + const uint dzs = (asuint(r1.x) ^ asuint(r0.y)) & g_z; // rows 2 and 3 after rows 0 and 1 (an opaque +0 in their address) + const float3 r2 = mad(wx.w, h3(wg_mem.Load2(ro[2] + dzs + co[3])), mad(wx.z, h3(wg_mem.Load2(ro[2] + dzs + co[2])), + mad(wx.y, h3(wg_mem.Load2(ro[2] + dzs + co[1])), mad(wx.x, h3(wg_mem.Load2(ro[2] + dzs + co[0])), z)))); + const float3 r3 = mad(wx.z, h3(wg_mem.Load2(ro[3] + dzs + co[2])), mad(wx.y, h3(wg_mem.Load2(ro[3] + dzs + co[1])), z)); +#else + const float3 z = float3(0.0f, 0.0f, 0.0f); + const float3 r0 = mad(wx.z, h3(wg_mem.Load2(ro[0] + co[2])), mad(wx.y, h3(wg_mem.Load2(ro[0] + co[1])), z)); + const float3 r1 = mad(wx.w, h3(wg_mem.Load2(ro[1] + co[3])), mad(wx.z, h3(wg_mem.Load2(ro[1] + co[2])), + mad(wx.y, h3(wg_mem.Load2(ro[1] + co[1])), mad(wx.x, h3(wg_mem.Load2(ro[1] + co[0])), z)))); + const float3 r2 = mad(wx.w, h3(wg_mem.Load2(ro[2] + co[3])), mad(wx.z, h3(wg_mem.Load2(ro[2] + co[2])), + mad(wx.y, h3(wg_mem.Load2(ro[2] + co[1])), mad(wx.x, h3(wg_mem.Load2(ro[2] + co[0])), z)))); + const float3 r3 = mad(wx.z, h3(wg_mem.Load2(ro[3] + co[2])), mad(wx.y, h3(wg_mem.Load2(ro[3] + co[1])), z)); +#endif + const float3 acc = mad(wy.w, r3, mad(wy.z, r2, mad(wy.y, r1, mad(wy.x, r0, z)))); + const float sx = ((wx.x + wx.y) + wx.z) + wx.w; + const float norm = (wx.y + wx.z) * (wy.x + wy.w) + sx * (wy.y + wy.z); + return acc * rcp(norm); +} + +// ---- steps 3 to 5 of one D pixel (l_select + l_post_core) ----------------------------------------------------------- +void l_post_core(LGather g, int x, int y, int fx, int fy, float mx[3], float my[3], float s, out float hh[3], + out float oh[3]) +{ + const float inv = rcp(g.W); // rcp(0) = inf: 0 * inf = NaN features (zero total weight) +#if LP_FBLAZY // l_post_tf: each normalized feature from its FP16 sum where it is used (the nine floats are not live together) +#define fbar_k(k) (inv * (float)opqh(LG_F(g, k))) + const float sig0 = fbar_k(3), sig1 = fbar_k(4), sig2 = fbar_k(5); +#else + float fbar[9]; + [unroll] for (int k = 0; k < 9; ++k) fbar[k] = inv * (float)opqh(LG_F(g, k)); +#define fbar_k(k) fbar[k] + const float sig0 = fbar[3], sig1 = fbar[4], sig2 = fbar[5]; +#endif + const bool sb1 = sig1 > sig0; + const float best = sb1 ? sig1 : sig0; + const bool sb2 = sig2 > best; + const float s1 = sb2 ? sig2 : best; + const float m1x = sb2 ? mx[2] : (sb1 ? mx[1] : mx[0]), m1y = sb2 ? my[2] : (sb1 ? my[1] : my[0]); + const bool sf0 = !or(sb1, sb2); + const float so1 = sf0 ? sig1 : sig0, so2 = sb2 ? sig1 : sig2; + const float mo1x = sf0 ? mx[1] : mx[0], mo1y = sf0 ? my[1] : my[0]; +#if LP_MUT == 7 + const float mo2x = sb2 ? mx[2] : mx[1], mo2y = sb2 ? my[1] : my[2]; // mutant 7: wrong candidate motion +#else + const float mo2x = sb2 ? mx[1] : mx[2], mo2y = sb2 ? my[1] : my[2]; +#endif + const bool scc = so2 > so1; + const float s2 = scc ? so2 : so1; + const float m2x = scc ? mo2x : mo1x, m2y = scc ? mo2y : mo1y; + const float q1 = clampf(k1p1 * s1 - k0p05, 0.0f, 1.0f); + const float q2 = clampf(k1p1 * s2 - k0p05, 0.0f, 1.0f); + const float rden = rcp(max(q1 + q2, k1em10)); + float w2 = q2 * rden, w1; + if (w2 < kInv255) { + w2 = 0.0f; + w1 = 1.0f; + } else { + w1 = q1 * rden; + } + const float X = (float)x + 0.5f, Y = (float)y + 0.5f; + const int ncand = w2 != 0.0f ? 2 : 1; + float L[2][3]; + // the second candidate at the first one's motion bits (the common case where the motion candidates agree): the same + // position, so the same history (or colour) values, bit for bit; copied instead of a second 12-tap read + const bool dup2 = asuint(m2x) == asuint(m1x) && asuint(m2y) == asuint(m1y); + [unroll] for (int n = 0; n < 2; ++n) { + L[n][0] = 0.0f; L[n][1] = 0.0f; L[n][2] = 0.0f; + if (n == 1 && n < ncand && dup2) { + L[1][0] = L[0][0]; L[1][1] = L[0][1]; L[1][2] = L[0][2]; + } else if (n < ncand) { + const float qx = X + (n == 0 ? m1x : m2x); + const float qy = Y + (n == 0 ? m1y : m2y); +#if LP_MUT == 5 + const bool valid = and(and(and(and(P_reset == 0, qx >= 0.0f), qx <= (float)P_dh), qy >= 0.0f), qy <= (float)P_dh); // mutant 5 +#else + const bool valid = and(and(and(and(P_reset == 0, qx >= 0.0f), qx <= (float)P_dw), qy >= 0.0f), qy <= (float)P_dh); +#endif + if (valid) { + const float3 h = history_cr(qx, qy); +#if LP_LDR || LP_MORIG + const float3 lq = h; +#else + const float3 lq = float3(l_dec(h.x), l_dec(h.y), l_dec(h.z)) * g_rp; +#endif + L[n][0] = lq.x; + L[n][1] = lq.y; + L[n][2] = lq.z; + } else { + float4 c = wg_ld4f(color, (uint)(fy * P_rw + fx) * 16u); +#if LP_PIDIV + c.xyz = asfloat(asuint(pidiv3(c.xyz, g_pd, g_z)) ^ g_z); +#endif +#if LP_MORIG && !LP_LDR + L[n][0] = enc_e(mul_nz(g_ep, c.x)); + L[n][1] = enc_e(mul_nz(g_ep, c.y)); + L[n][2] = enc_e(mul_nz(g_ep, c.z)); +#else + L[n][0] = c.x; L[n][1] = c.y; L[n][2] = c.z; +#endif + } + } + } + float Hl[3], Cl[3]; + bool hl_inf = false; + [unroll] for (int i = 0; i < 3; ++i) { + const float comb = ncand == 2 ? mad(w1, L[0][i], w2 * L[1][i]) : w1 * L[0][i]; +#if LP_LDR + Hl[i] = opq(comb); +#elif LP_MORIG + Hl[i] = mul_nz(mul_nz(l_dec(comb), g_rp), g_e); +#else + Hl[i] = mul_nz(comb, g_e); +#endif + hl_inf = or(hl_inf, abs(Hl[i]) == asfloat(0x7f800000u)); +#if LP_LDR + Cl[i] = fbar_k(i); +#else + Cl[i] = l_dec(fbar_k(i)); +#endif + } + const float alpha = clampf(opq(s * g.W) * fbar_k(6), 0.0f, 1.0f); + const float bh2 = mad(alpha, 1.0f - fbar_k(7), fbar_k(7)); + const float bo2 = mad(alpha, 1.0f - fbar_k(8), fbar_k(8)); + [unroll] for (int i = 0; i < 3; ++i) { + hh[i] = mad(Cl[i] - Hl[i], bh2, Hl[i]); + oh[i] = mad(Cl[i] - Hl[i], bo2, Hl[i]); + } + const float sh = hh[0] + hh[1] + hh[2], so = oh[0] + oh[1] + oh[2]; + if (or(isnan(sh), hl_inf)) { + [unroll] for (int i = 0; i < 3; ++i) hh[i] = Cl[i]; + } + if (or(isnan(so), hl_inf)) { + [unroll] for (int i = 0; i < 3; ++i) oh[i] = Cl[i]; + } +} + +// the render-resolution motion words of one pixel row: m_near / m_far at the nearest texel (fx, fy), m_center's four +// bilinear neighbours (clamped texel coordinates) of (px, py); loaded ahead of the gather (they do not depend on it) +struct MotRaw { uint mn, mf, ma, mb, mc, md; int fx, fy; float wx, wy; }; + +MotRaw motion_load(float px, float py) +{ + MotRaw m; + m.fx = clampi(floor_i(px), 0, P_rw - 1); + m.fy = clampi(floor_i(py), 0, P_rh - 1); + m.mn = wg_ld32(m_near, (uint)(m.fy * P_rw + m.fx) * 4u); + m.mf = wg_ld32(m_far, (uint)(m.fy * P_rw + m.fx) * 4u); + // motion_bilinear of m_center at (px, py) + const float tx = px - 0.5f, ty = py - 0.5f; + const float x0f = floor(tx), y0f = floor(ty); + m.wx = tx - x0f; + m.wy = ty - y0f; + const int c0 = (int)x0f, r0 = (int)y0f; + const int ca = clampi(c0, 0, P_rw - 1), cb = clampi(c0 + 1, 0, P_rw - 1); + const int ra = clampi(r0, 0, P_rh - 1), rb = clampi(r0 + 1, 0, P_rh - 1); + if (ca + 1 == cb) { + const uint2 top = wg_ld64(m_center, (uint)(ra * P_rw + ca) * 4u); + const uint2 bot = wg_ld64(m_center, (uint)(rb * P_rw + ca) * 4u); + m.ma = top.x; m.mb = top.y; + m.mc = bot.x; m.md = bot.y; + } else { + m.ma = wg_ld32(m_center, (uint)(ra * P_rw + ca) * 4u); + m.mb = wg_ld32(m_center, (uint)(ra * P_rw + cb) * 4u); + m.mc = wg_ld32(m_center, (uint)(rb * P_rw + ca) * 4u); + m.md = wg_ld32(m_center, (uint)(rb * P_rw + cb) * 4u); + } + return m; +} + +// l_finish_pixel without its stores: motions, steps 3 to 5; H^ in hh, O^ in oh (the kernel converts and stores them) +void finish_pixel(LGather g, int x, int y, MotRaw m, float s, out float hh[3], out float oh[3]) +{ + float mx[3], my[3]; + mx[0] = f16tof32(m.mn); my[0] = f16tof32(m.mn >> 16); + mx[2] = f16tof32(m.mf); my[2] = f16tof32(m.mf >> 16); + { // motion_bilinear of m_center, clamped texel coordinates + const float owx = 1.0f - m.wx, owy = 1.0f - m.wy; + const float topx = f16tof32(m.ma) * owx + f16tof32(m.mb) * m.wx, topy = f16tof32(m.ma >> 16) * owx + f16tof32(m.mb >> 16) * m.wx; + const float botx = f16tof32(m.mc) * owx + f16tof32(m.md) * m.wx, boty = f16tof32(m.mc >> 16) * owx + f16tof32(m.md >> 16) * m.wx; + mx[1] = topx * owy + botx * m.wy; + my[1] = topy * owy + boty * m.wy; + } + l_post_core(g, x, y, m.fx, m.fy, mx, my, s, hh, oh); +} + +float lpx(int xx) { return mad(opq((float)xx + 0.5f), P_rx, P_jx); } // fused(x + 1/2, rx, jx) +float lpy(int yy) { return mad(P_ry, opq((float)yy + 0.5f), P_jy); } // fused(ry, y + 1/2, jy) + +// one column i of the 4 x 4 gather (taps j = -1 ... 2 for both rows of the pair), from the staged texels (STAGED) or loaded +// per tap; the eight weights of the column are rounded to FP16 by one driver conversion +template +void gather_col(int i, half dx, int tb0, int rstride, int b, int ax, half v0[kLWin], half v1[kLWin], half vv0[kLWin], + half vv1[kLWin], inout LGather g0, inout LGather g1) +{ + const half u = dx + (half)(float)i; + const half uu = mulh(u, u); + v8f wv; +#if LP_MORIG + wv.v[6] = 0.0f; + wv.v[7] = 0.0f; +#endif + if (STAGED) { + // Read only kA/kB/kC (dwords 4..5) from LDS during weight evaluation so 24 texel VGPRs aren't live across exp2/cvt. + const int col_base = tb0 + (i + 1) * kTexDw; + [unroll] for (int j = -1; j <= kLWin - 2; ++j) { + const int base = col_base + (j + 1) * rstride +#if LP_MUT == 2 + + (j == 2 && i == 2 ? kTexDw : 0) // mutant 2: one tap reads the wrong texel +#endif + ; + uint tk[kTexDw]; + tk[0] = 0u; tk[1] = 0u; tk[2] = 0u; tk[3] = 0u; + tk[4] = sh_tex[base + 4]; + tk[5] = sh_tex[base + 5]; + wv.v[2 * (j + 1)] = tap_weight(tk, uu, vv0[j + 1], mulh(u, v0[j + 1])); + wv.v[2 * (j + 1) + 1] = tap_weight(tk, uu, vv1[j + 1], mulh(u, v1[j + 1])); + } + const uint4 hw = wg_to_f16_ags(wv); + [unroll] for (int jj = 0; jj < kLWin; ++jj) { + const int base = col_base + jj * rstride +#if LP_MUT == 2 + + (jj == 3 && i == 2 ? kTexDw : 0) +#endif + ; + uint tf[kTexDw]; + [unroll] for (int d = 0; d < 5; ++d) tf[d] = sh_tex[base + d]; + tf[5] = 0u; + const uint hp = jj == 0 ? hw.x : (jj == 1 ? hw.y : (jj == 2 ? hw.z : hw.w)); + gather_acc(g0, tf, wv.v[2 * jj], hp & 0xffffu); + gather_acc(g1, tf, wv.v[2 * jj + 1], hp >> 16); + } + } else { + // Rare unstaged fallback (footprint > kStageCap): avoid keeping uint t[4][6] (24 VGPRs) live across the kernel! + [unroll] for (int j = -1; j <= kLWin - 2; ++j) { + uint tk[kTexDw]; + load_texel_hw(clampi(b + j, 0, P_rh - 1) * P_rw + clampi(ax + i, 0, P_rw - 1), tk); + wv.v[2 * (j + 1)] = tap_weight(tk, uu, vv0[j + 1], mulh(u, v0[j + 1])); + wv.v[2 * (j + 1) + 1] = tap_weight(tk, uu, vv1[j + 1], mulh(u, v1[j + 1])); + } + const uint4 hw = wg_to_f16_ags(wv); + [unroll] for (int jj = 0; jj < kLWin; ++jj) { + uint tf[kTexDw]; + load_texel_hw(clampi(b + jj - 1, 0, P_rh - 1) * P_rw + clampi(ax + i, 0, P_rw - 1), tf); + const uint hp = jj == 0 ? hw.x : (jj == 1 ? hw.y : (jj == 2 ? hw.z : hw.w)); + gather_acc(g0, tf, wv.v[2 * jj], hp & 0xffffu); + gather_acc(g1, tf, wv.v[2 * jj + 1], hp >> 16); + } + } +} diff --git a/clean/dx12/kernels/l_post_tf.hlsl b/clean/dx12/kernels/l_post_tf.hlsl new file mode 100644 index 00000000..788fa61b --- /dev/null +++ b/clean/dx12/kernels/l_post_tf.hlsl @@ -0,0 +1,421 @@ +// SPDX-License-Identifier: MIT +// Model L's true-fusion output kernel (D3D12 only, no HIP kernel of its own; runtime WG_L_POST_TF, default on): the +// reconstruction (l_post_recon_p12, the lc12 form: l_post.hlsl) and the output filter (w64/post_filter_c1_s4: the analytic +// Lanczos, Dec, times dec_scale) and the staged route's scale_rgb in ONE wave64 kernel of 512 lanes, the display image never +// goes to memory. The structure is Model M's post_tf (post.hlsl w64/post_tf_f32_p12_diet_vsit, POST_OUT = 0, WG_LZ_ANALYTIC): +// workgroup = (strip of 40 output columns = 64 D columns incl. the filter's halo, chunk of output row pairs); per step +// of 16 D rows each of the 8 waves64 reconstructs one row pair of the strip's 64 columns, the display values (FP16) go to +// a ring in LDS, and the horizontal and vertical Lanczos passes run on the ring. What differs is the reconstruction of a +// D pixel: Model L's own (l_post_core.hlsli, the code of l_post_recon_p12: the staged FP16 features, the 4 x 4 gather, the +// linear-colour history candidates, steps 3 to 5), per lane the same operations on the same values as l_post_recon_p12 +// followed by post_filter_c1_s4 (a pixel is a function of its own inputs only; the staging only decides where a texel sits in +// LDS). The 8 FP16 roundings of a row use the driver's single-value conversion (op 0x1C: one hardware v_cvt_f16_f32, the +// bits of wg_f2h): wave64 has no matrix conversion (l_post_core.hlsli). +// The display value of D pixel (x, y) goes to the ring as the FP16 pair of lanes (x, x + 1) exactly as l_post_recon stores +// it to the display image (hc.y >> 16, hc.z), the filter's horizontal / vertical passes are post_filter_c1_s4's operations +// on those values (lz5a, clamp to [1e-4, 3], Dec) and the output is stored times dec_scale (the pre-exposure scale of the +// runtime's scale_rgb folded in, native_scale's bits: post.hlsl m1_scale; pi_arg == 1: the plain product). +// Arguments as w64/post_tf_f32_p12_diet_vsit (the analytic build): the post_recon arguments (A = image A8, B unused, C = image +// C4), the WgPostParams, expo, then ow, oh, dec_scale (read from the exposure pair at +16 when expo is not null: the diet pair), +// pi_arg (the pre-exposure; with _pf: the bits of P_pad0 divide every colour read, color_divide folded in), pitch_bytes (unused), +// cpairs, k1, c2 (post_tf's chunk plan). Staged render texels per step: at most kStageCap (host check l_tf_supported). +// @wg-kernel w64_lc12/l_post_tf_p12 co=- entry=l_post_tf_p12 block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u defines=LP_P12=1,LP_C12=1,LP_W64=1,LP_CODE=1,LP_RPUNI=1,LP_QX=1,LP_TF=1 +// @wg-kernel w64_lc12/l_post_tf_p12_pf co=- entry=l_post_tf_p12 block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u defines=LP_P12=1,LP_C12=1,LP_W64=1,LP_CODE=1,LP_RPUNI=1,LP_QX=1,LP_TF=1,LP_PIDIV=1 +#include "wg_platform.hlsli" +#ifndef LP_P12 +#define LP_P12 1 +#endif +#ifndef LP_C12 +#define LP_C12 1 +#endif +#define LP_LDR 0 +#define LP_MORIG 0 +#ifndef LP_W64 +#define LP_W64 1 +#endif +#ifndef LP_CODE +#define LP_CODE 1 +#endif +#ifndef LP_RPUNI +#define LP_RPUNI 1 +#endif +#ifndef LP_QX +#define LP_QX 1 +#endif +#if LP_W64 != (WG_WAVE == 64) || WG_BLOCK != 512 +#error "l_post_tf.hlsl: wave64, 512 lanes" +#endif +#if !LP_P12 +#error "l_post_tf.hlsl: the pack12 inputs only" +#endif + +WG_ARGS_BEGIN + uint color, A, B, C, hist_prev, m_near, m_center, m_far, w_p, hist_out, reduced, out_p; // pointers (A: A8, C: C4) + int P_rw, P_rh, P_dw, P_dh, P_reset, P_pad0, P_pad1, P_pad2; // WgPostParams + float P_rx, P_ry, P_jx, P_jy, P_e, P_e_prev, P_ratio, P_pad3; + uint expo; + int ow, oh; + float dec_scale_arg, pi_arg; + int pitch_bytes, cpairs, k1, c2; +WG_ARGS_END + +#define kStageCap 512 // staged render texels per step (6 dwords each: 12288 bytes); one per lane +#ifndef LP_HSEQ +#define LP_HSEQ 0 // all six history_cr span loads in one burst (RGA: 86 VGPRs, within the LDS-capped 96-VGPR tier) +#endif +#ifndef LP_FBLAZY +#define LP_FBLAZY 1 // the normalized features are not live together (RGA: -7 VGPRs) +#endif +#include "l_post_core.hlsli" + +#define kTfCols 64 +#define kTfOwn 60 +#define kTfOutX 40 +#define kNW 8 // row pairs per step (= waves64 of the workgroup) +#define kRing (2 * kNW + 6) // 22 +#define kThreads (64 * kNW) // 512 +#define kRowDw (3 * kTfOutX) // one ring row: 3 channels x 40 values = 120 dwords +#define kLdsDw ((kRing + 6) * kRowDw) // 3360 dwords = 13440 bytes (+ 12288 staged texels + 1024 code table = 26752) +#if kThreads != WG_BLOCK +#error "l_post_tf.hlsl: the workgroup is 64 kNW lanes" +#endif + +groupshared uint lds[kLdsDw]; + +static const float kLz0 = asfloat(0xbdba3b4bu), kLz1 = asfloat(0x3de71ca9u), kLz2 = asfloat(0x3f23b70fu); +static const float kLz3 = asfloat(0x3ed182b5u), kLz4 = asfloat(0xbd90a4acu); + +float unif(float x) { return asfloat(WaveReadLaneFirst(asuint(x))); } +uint mul24(uint a, uint b) { return (a & 0xffffffu) * (b & 0xffffffu); } +int mul_i24(int a, int b) { return ((int)((uint)a << 8) >> 8) * ((int)((uint)b << 8) >> 8); } + +// post_filter_c1_s4's lz5a: v = w0 t0, one fused multiply-add per further tap, clamp to the taps' range +float lz5a(float t0, float t1, float t2, float t3, float t4, float w0, float w1, float w3, float w4) +{ + float v = w0 * t0; + v = mad(w1, t1, v); + v = mad(kLz2, t2, v); + v = mad(w3, t3, v); + v = mad(w4, t4, v); + const float mid_lo = min(min(t1, t2), t3), mid_hi = max(max(t1, t2), t3); + const float lo = min(min(mid_lo, t0), t4), hi = max(max(mid_hi, t0), t4); + return min(max(v, lo), hi); // med3 (the taps are finite, lo <= hi) +} +uint lz5a_even(float t[10], int o) { return asuint(lz5a(t[o], t[o + 1], t[o + 2], t[o + 3], t[o + 4], kLz0, kLz1, kLz3, kLz4)); } +uint lz5a_odd(float t[10], int o) { return asuint(lz5a(t[o], t[o + 1], t[o + 2], t[o + 3], t[o + 4], kLz4, kLz3, kLz1, kLz0)); } + +// native_scale (native_helpers.hlsl: the staged route's scale_rgb) of one value, as post.hlsl m1_scale +float m1_scale_ref(float a, float b) +{ + const float r = a * b; + const uint ua = asuint(a), ub = asuint(b); + const uint ea = (ua >> 23u) & 255u, eb = (ub >> 23u) & 255u; + if ((asuint(r) & 0x7fffffffu) == 0u && ea != 0u && eb != 0u && ea + eb == 127u) { + const uint64_t product = (uint64_t)((ua & 0x7fffffu) | 0x800000u) * (uint64_t)((ub & 0x7fffffu) | 0x800000u); + const uint64_t normal = (uint64_t)1u << 47u; + if (product >= normal - ((uint64_t)1u << 23u) && product < normal) + return asfloat(((ua ^ ub) & 0x80000000u) | 0x00800000u); + } + return r; +} +float m1_scale(float a, float b) +{ + float r = a * b; + [branch] if (and(abs(r) == 0.0f, abs(a) >= asfloat(0x00800000u))) r = m1_scale_ref(a, b); + return r; +} + +// the raw inputs of render pixel idx (staged one step ahead; the conversions happen when the texel is put) +struct LRaw { float4 c; uint2 d; uint c01; }; +LRaw raw_fetch(int idx) +{ + LRaw r; + const uint ui = (uint)idx; + r.c = wg_ld4f(color, ui * 16u); + r.d = wg_ld64(A, ui * 8u); + r.c01 = wg_ld32(C, ui * 4u); + return r; +} +void raw_put(LRaw r, uint dst, bool store) +{ + const uint a = r.d.x & 0xffffffu; + const uint b = (r.d.x >> 24) | ((r.d.y & 0xffffu) << 8); + const uint2 k = uint2(r.c01, r.d.y >> 16); + uint t[kTexDw]; + texel_make(r.c, a, b, k, t); // wave-uniform control flow (the driver's conversion) + if (store) { + [unroll] for (int d = 0; d < kTexDw; ++d) sh_tex[dst + (uint)d] = t[d]; + } +} + +// The footprint of one step: rows r0 ..., ncol columns from c0; the render pixel of staged texel i (clamped) +int step_rows(int ys, int r_need, out int r0) +{ + const int yl = mini(ys + 2 * (kNW - 1), r_need) & ~1; + r0 = floor_i(lpy(ys) - 0.5f) - 1; + return floor_i(lpy(yl) - 0.5f) + 2 - r0 + 1; +} + +WG_KERNEL(l_post_tf_p12) +{ + WG_SETUP(); + if (P_dw < 4) return; + g_z = wg_grid_ >> 31; // 0, opaque to the compiler + g_e = P_e; + g_ep = P_e_prev; + float dec_scale = dec_scale_arg; + if (expo != 0u) { // the diet pair: [e, e_prev, last e, ratio, dec_scale] + const float e0 = unif(wg_ldf(expo, 0u)), e1 = unif(wg_ldf(expo, 4u)); + g_e = e0 == 0.0f ? 1.0f : e0; + g_ep = e1 == 0.0f ? 1.0f : e1; + dec_scale = unif(wg_ldf(expo, 16u)); + } + g_rp = asfloat(WaveReadLaneFirst(asuint(wg_div(1.0f, g_ep)))); // 1 / e_prev: wave-uniform operand +#if LP_PIDIV + g_pd = pidiv_make((uint)P_pad0); +#endif + const int lane = (int)wg_lane_id(); + const int wave = wg_uniform(lane >> 6), wl = lane & 63; // wave index: uniform (a scalar register) + const int strips = (ow + kTfOutX - 1) / kTfOutX; + const int bid = (int)wg_block_id(); + // workgroup bid -> (strip, chunk) as post_tf: the strips of chunk c rotated by c (the same set of workgroups) + const int chunk = wg_uniform(bid / strips); + const int strip = wg_uniform((bid - chunk * strips + chunk) % strips); + const int X0 = strip * kTfOwn; + const int csize = chunk < k1 ? cpairs : c2; + const int P0 = chunk < k1 ? chunk * cpairs : k1 * cpairs + (chunk - k1) * c2; + const int p_end = wg_uniform(mini(P0 + csize, (oh + 1) / 2)); + const int own_r0 = wg_uniform(3 * P0), own_r1 = wg_uniform(mini(3 * (P0 + csize), P_dh)); + const int r_first = wg_uniform(3 * P0 - 2 < 0 ? 0 : 3 * P0 - 2); + const int r_need = wg_uniform(mini(3 * (p_end - 1) + 4, P_dh - 1)); + const float s = wg_ldf(w_p, 0u); + + // the strip's render columns c0 ... c1 (taps ax - 1 ... ax + 2 of its first and last D column) + const int c0 = floor_i(lpx(clampi(X0 - 2, 0, P_dw - 1)) - 0.5f) - 1; + const int c1 = floor_i(lpx(clampi(X0 + kTfCols - 3, 0, P_dw - 1)) - 0.5f) + (kLWin - 2); + const int ncol = c1 - c0 + 1; + const float inv_ncol = unif(wg_div(1.0f, (float)ncol)); + + // the staging of step y_step: footprint rows r0 ..., texels loaded one step ahead + int r0, nstage; + { + const int nrow = step_rows(r_first, r_need, r0); + nstage = ncol * nrow < kStageCap ? ncol * nrow : kStageCap; + } + LRaw raw; + { + const int i = mini(lane, nstage - 1); + const int r = (int)(((float)i + 0.5f) * inv_ncol), c = i - mul_i24(r, ncol); + raw = raw_fetch(clampi(r0 + r, 0, P_rh - 1) * P_rw + clampi(c0 + c, 0, P_rw - 1)); + } + code16_build(lane & 255); // the FP16 code table: waves 4 ... 7 rewrite the entries of waves 0 ... 3 with the same values + wg_barrier_lds(); // (wave-uniform conversions: every wave runs the same instructions) + + // this lane's D column (fixed over the walk) + const int xv = X0 - 2 + wl; + const int x = clampi(xv, 0, P_dw - 1); + const bool own_x = and(and(xv >= X0, xv < X0 + kTfOwn), xv < P_dw); + const float px = lpx(x); + const int ax = floor_i(px - 0.5f); + const uint wlu = (uint)wl; + + int base_slot = 0; + int p_next = P0; + [loop] for (int y_step = r_first; y_step <= r_need; y_step += 2 * kNW) { + // 1. stage the footprint + [branch] if (wave * 64 < nstage) { // wave-uniform: a wave wholly past the staged range has nothing to store + raw_put(raw, (uint)lane * kTexDw, lane < nstage); + } + wg_barrier_lds(); + const int r0c = r0; + + // 2. reconstruction of the wave's row pair (yv, yv + 1) + const int yv = y_step + 2 * wave; + const bool wact = yv <= r_need; + int slot = base_slot + 2 * wave; + if (slot >= kRing) slot -= kRing; + const uint scr = (uint)slot * kRowDw; // dword of ring row slot (rows slot, slot + 1) + if (wact) { + const int y0 = yv; + const bool has1 = y0 + 1 < P_dh; + const float py0 = unif(lpy(y0)), py1 = unif(lpy(y0 + 1)); // wave-uniform (y0 is) + const int b = wg_uniform(floor_i(py0 - 0.5f)); + const int b1 = wg_uniform(floor_i(py1 - 0.5f)); + // gather offsets: dx = h((ax + 1/2) - px), d_y = h((b_y + 1/2) - py(y)) minus 1 (FP16) when the row's own b_y + // differs from the pair's b; the three offsets in one conversion (wave64: three hardware conversions) + v8f ov; + ov.v[0] = opq(((float)ax + 0.5f) - px); + ov.v[1] = opq(((float)b + 0.5f) - py0); + ov.v[2] = opq(((float)b1 + 0.5f) - py1); + [unroll] for (int oi = 3; oi < 8; ++oi) ov.v[oi] = 0.0f; + const uint4 oh16 = wg_to_f16_ags(ov); + const half dx = h_bits(oh16.x), dy0 = h_bits(oh16.x >> 16); + half dy1 = h_bits(oh16.y); + if (b1 != b) dy1 = dy1 - (half)1.0f; + half v0[kLWin], v1[kLWin], vv0[kLWin], vv1[kLWin]; + [unroll] for (int jj = 0; jj < kLWin; ++jj) { + v0[jj] = dy0 + (half)(float)(jj - 1); + v1[jj] = dy1 + (half)(float)(jj - 1); + vv0[jj] = mulh(v0[jj], v0[jj]); + vv1[jj] = mulh(v1[jj], v1[jj]); + } + // taps column by column (i outer, j inner), both rows' gathers in one pass over the staged texels + LGather g0 = gather_zero(), g1 = gather_zero(); + const int tb0 = ((b - 1 - r0c) * ncol + (ax - 1 - c0)) * kTexDw, rstride = ncol * kTexDw; + [loop] for (int i = -1; i <= (kLWin - 2); ++i) + gather_col(i, dx, tb0, rstride, b, ax, v0, v1, vv0, vv1, g0, g1); + + float r[3] = {0.0f, 0.0f, 0.0f}; + [loop] for (int row = 0; row < 2; ++row) { + const bool second = row == 1; + if (second && !has1) break; // wave-uniform: the missing second row is not stored and adds nothing + const int y = y0 + row; + LGather g = g0; + if (second) g = g1; + float hh[3], oo[3]; + const MotRaw mot = motion_load(px, second ? py1 : py0); + finish_pixel(g, x, y, mot, s, hh, oo); + v8f cv; + float el[3]; + [unroll] for (int ci = 0; ci < 3; ++ci) { + el[ci] = enc_log(hh[ci]); + cv.v[ci] = mul_odd(kEncK, el[ci]); + cv.v[3 + ci] = opq(clampf(enc_e(oo[ci]), 0.0f, kDisplayMax)); + } + cv.v[6] = 0.0f; + cv.v[7] = 0.0f; + const uint4 hc = wg_to_f16_ags(cv); + if (and(and(own_x, y >= own_r0), y < own_r1)) { + const uint q0 = mul_zero_k(el[0]) ? 0u : (hc.x & 0xffffu); + const uint q1 = mul_zero_k(el[1]) ? 0u : (hc.x >> 16); + const uint q2 = mul_zero_k(el[2]) ? 0u : (hc.y & 0xffffu); + wg_st64(hist_out, (uint)(y * P_dw + x) * 8u, uint2(q0 | (q1 << 16), q2)); + } + // display values (FP16) of the 64 columns -> scratch row slot + row: lanes 2m, 2m + 1 share a dword + const uint srow = scr + (uint)row * kRowDw; + [unroll] for (int c = 0; c < 3; ++c) { + const uint dv = c == 0 ? hc.y >> 16 : (c == 1 ? hc.z & 0xffffu : hc.z >> 16); + const uint nbv = QuadReadAcrossX(dv); + if ((wlu & 1u) == 0u) lds[srow + (uint)c * 32u + (wlu >> 1)] = dv | (nbv << 16); + } + // reduced history: mean of H^ over the 2 x 2 block, r = h0 + h1 + [unroll] for (int ri = 0; ri < 3; ++ri) r[ri] = second ? r[ri] + hh[ri] : hh[ri]; + } + float o[3]; + [unroll] for (int i = 0; i < 3; ++i) o[i] = QuadReadAcrossX(r[i]); // lane ^ 1 + if (and(and(and(and(and((wl & 1) == 0, own_x), x + 1 < P_dw), has1), y0 >= own_r0), y0 + 1 < own_r1)) { + uint code = 0u; + [unroll] for (int i = 0; i < 3; ++i) { + const float m = opq((r[i] + o[i]) * 0.25f); + const float v = clampf(opq(enc_e(m)) * kInv245, 0.0f, 1.0f); + code |= wg_f2u(round(v * 1023.0f)) << (10 * i); + } + wg_st32(reduced, (uint)((y0 / 2) * (P_dw / 2) + x / 2) * 4u, code); + } + } + // the next step's staging loads (every lane loads a valid clamped texel) + { + const int nrow = step_rows(y_step + 2 * kNW, r_need, r0); + nstage = ncol * nrow < kStageCap ? ncol * nrow : kStageCap; + const int i = mini(lane, nstage - 1 < 0 ? 0 : nstage - 1); + const int r = (int)(((float)i + 0.5f) * inv_ncol), c = i - mul_i24(r, ncol); + raw = raw_fetch(clampi(r0 + r, 0, P_rh - 1) * P_rw + clampi(c0 + c, 0, P_rw - 1)); + } + + // horizontal pass of the wave's two rows: lane (row hk, channel hc, cell hg), output columns 4 hg ... 4 hg + 3 + GroupMemoryBarrier(); // the 64 lanes are one wave: its LDS operations execute in order (the fence orders the compiler) + const int hl = wl; + const bool hact = and(wact, hl < 60); + const int hk = hl >= 30 ? 1 : 0, hrem = hl - 30 * hk, hc = hrem >= 20 ? 2 : (hrem >= 10 ? 1 : 0), + hg = hrem - 10 * hc; + uint hv[4] = { 0u, 0u, 0u, 0u }; + if (hact) { + const uint src = scr + (uint)hk * kRowDw + (uint)hc * 32u + (uint)hg * 3u; + float t[10]; // the FP16 display taps as FP32 values (exact); results FP32 bits + [unroll] for (int i = 0; i < 5; ++i) { + const uint q = lds[src + (uint)i]; + t[2 * i] = f16tof32(q); + t[2 * i + 1] = f16tof32(q >> 16); + } + hv[0] = lz5a_even(t, 0); + hv[1] = lz5a_odd(t, 2); + hv[2] = lz5a_even(t, 3); + hv[3] = lz5a_odd(t, 5); + } + GroupMemoryBarrier(); + if (hact) { + const uint dst = scr + (uint)hk * kRowDw + (uint)hc * (uint)kTfOutX + (uint)hg * 4u; + [unroll] for (int i = 0; i < 4; ++i) lds[dst + (uint)i] = hv[i]; + if (slot + hk < 6) { // the first six ring rows are mirrored after the ring (wrap-free vertical taps) + const uint dm = dst + (uint)kRing * kRowDw; + [unroll] for (int i2 = 0; i2 < 4; ++i2) lds[dm + (uint)i2] = hv[i2]; + } + } + wg_barrier_lds(); + + // 3. vertical pass, Dec and output of the row pairs whose input rows are complete + const int r_done = mini(y_step + 2 * kNW, r_need + 1); + const int p_rdy = r_done > r_need ? p_end : mini(p_end, (r_done - 5) / 3 + 1); + const int nitems = (p_rdy - p_next) * 2 * kTfOutX; + const bool interior = and(3 * p_next - 2 >= 0, 3 * p_rdy + 1 <= P_dh - 1); + const int s0 = interior ? (3 * p_next - 2 - r_first) % kRing : 0; + [loop] for (int it = lane; it < nitems; it += kThreads) { + const int pr = (int)(mul24((uint)it, 52429u) >> 22); + const int rem = it - (int)mul24((uint)pr, 2u * kTfOutX); + const int dy = rem >= kTfOutX ? 1 : 0, xo = rem - dy * kTfOutX; + const int pp = p_next + pr, y = 2 * pp + dy, xg = strip * kTfOutX + xo; + if (or(y >= oh, xg >= ow)) continue; + uint t[5][3]; + if (interior) { // one ring address, the 15 taps at constant offsets (mirrored rows: no wrap) + int u = s0 + 3 * pr + 2 * dy; + u = u >= kRing ? u - kRing : u; + u = u >= kRing ? u - kRing : u; + const uint rp = mul24((uint)u, (uint)kRowDw) + (uint)xo; + [unroll] for (int k = 0; k < 5; ++k) + [unroll] for (int c = 0; c < 3; ++c) t[k][c] = lds[rp + (uint)(k * kRowDw + c * kTfOutX)]; + } else { + const int xr = 3 * pp - 2 + 2 * dy; + const int row0 = clampi(xr, 0, P_dh - 1); + const int sl0 = (int)((uint)(row0 - r_first) % (uint)kRing); + [unroll] for (int k = 0; k < 5; ++k) { + const int st = clampi(xr + k, 0, P_dh - 1) - row0; + const int sl = sl0 + st >= kRing ? sl0 + st - kRing : sl0 + st; + [unroll] for (int c = 0; c < 3; ++c) t[k][c] = lds[(uint)sl * kRowDw + (uint)(c * kTfOutX + xo)]; + } + } + // emit: weights of the lane's phase by selects, lz5a, Dec, store 3 x f32 + const bool ev = dy == 0; + const float w0 = ev ? kLz0 : kLz4, w4 = ev ? kLz4 : kLz0, w1 = ev ? kLz1 : kLz3, w3 = ev ? kLz3 : kLz1; + float vo[3], qv[3]; + bool vsmall = false; + [unroll] for (int c = 0; c < 3; ++c) { + qv[c] = clampf(lz5a(asfloat(t[0][c]), asfloat(t[1][c]), asfloat(t[2][c]), asfloat(t[3][c]), asfloat(t[4][c]), + w0, w1, w3, w4), k1em4, 3.0f); + vo[c] = exp2(qv[c] * kDecK) - 1.0f; + vsmall = or(vsmall, qv[c] < kDecPolyMax); + } + if (WaveActiveAnyTrue(vsmall)) { // Dec's polynomial only when some lane needs it (post.hip's branches) + [unroll] for (int c = 0; c < 3; ++c) vo[c] = qv[c] < kDecPolyMax ? dec_m1_poly(qv[c]) : vo[c]; + } + const uint o = mul24((uint)y, (uint)ow * 12u) + mul24((uint)xg, 12u); +#if LP_PIDIV + { // _pf runs only when pi != 1: the scale_rgb fold is unconditional + const float3 res = float3(mul_nz(vo[0], dec_scale), mul_nz(vo[1], dec_scale), mul_nz(vo[2], dec_scale)); + const float3 so = float3(m1_scale(res.x, pi_arg), m1_scale(res.y, pi_arg), m1_scale(res.z, pi_arg)); + wg_mem.Store3(out_p + o, uint3(asuint(so.x), asuint(so.y), asuint(so.z))); + } +#else + [branch] if (pi_arg == 1.0f) { + wg_mem.Store3(out_p + o, uint3(asuint(vo[0] * dec_scale), asuint(vo[1] * dec_scale), asuint(vo[2] * dec_scale))); + } else { // the runtime's scale_rgb folded in (the division by pi done by a separate color_divide) + const float3 res = float3(mul_nz(vo[0], dec_scale), mul_nz(vo[1], dec_scale), mul_nz(vo[2], dec_scale)); + const float3 so = float3(m1_scale(res.x, pi_arg), m1_scale(res.y, pi_arg), m1_scale(res.z, pi_arg)); + wg_mem.Store3(out_p + o, uint3(asuint(so.x), asuint(so.y), asuint(so.z))); + } +#endif + } + p_next = p_rdy; + base_slot += 2 * kNW; + if (base_slot >= kRing) base_slot -= kRing; + } +} diff --git a/clean/dx12/kernels/l_post_tf_fast.hlsl b/clean/dx12/kernels/l_post_tf_fast.hlsl new file mode 100644 index 00000000..584f7b01 --- /dev/null +++ b/clean/dx12/kernels/l_post_tf_fast.hlsl @@ -0,0 +1,749 @@ +// SPDX-License-Identifier: MIT +// Model L's true-fusion output kernel in its fast-mode form (runtime l_mode=fast, native D3D12 only, no HIP kernel): +// w64_lc12/l_post_tf_p12_fast and _pf_fast. The same workgroup / chunk plan, staging, ring and filter as +// l_post_tf.hlsl (read its header: one wave64 kernel of 512 lanes, the reconstruction of a D pixel from the staged FP16 +// features, the history candidates, steps 3 to 5, the FP16 display values, then the analytic Lanczos passes on the ring in +// LDS, Dec, and the output times dec_scale), with the arithmetic of the hybrid route's bit-exactness removed: +// - no driver intrinsic channel (wg_ags_call, 0x1C): FP32 -> FP16 is the native pack (v_cvt_pk_rtz_f16_f32, round toward +// zero) with the round-to-nearest bias folded into the multiplier in front of it (kRn: x (1 + 2^-11.7) truncated has +// the mean error of the nearest rounding) or, where no multiplier precedes, an integer add of half an FP16 step +// (rn16); the opaque-zero guards (opq, opqh, mulh, mul_nz, mul_odd, mul_zero_k) are gone, the driver may fuse and +// regroup (the values are the model's, not the reference's bits); +// - the FP16 code table (sh_code, 1 KB of LDS, a barrier and six lookups per texel) is a multiply: (half)(byte / 255); +// - the gather's tap weight is one native FP16 exponential (v_exp_f16) of the FP16 exponent, and the total weight W is +// summed in FP16 from the same rounded weights as the nine features (the normalization is then self-consistent and the +// rounding of the weights adds no bias), instead of FP32 exp2 + a round to FP16 + an FP32 sum; +// - Dec is exp2(q kDecK) - 1 for every lane (no polynomial branch, no wave vote: the cancellation error of the plain form +// is 1.2e-7 of dec_scale at the darkest clamp, 1e-4, below the display's FP16 resolution); +// - the exposures, 0.01 and 1 / e_prev fold into two wave-uniform factors; the output scale is dec_scale * pi (one +// uniform product; with _pf the colours are multiplied by 1 / pi); +// - the horizontal Lanczos results sit in the ring as FP16 pairs (6.7 KB instead of 13.4 KB) and the vertical pass +// filters two adjacent output columns per lane from whole dwords. +// LDS: 12 288 B staged texels + 10 752 B ring = 23 040 B (l_post_tf_p12: 26 752 B). +// The quality gate is measured on the GPU (tone-mapped PSNR / SSIM against l_mode=hybrid, temporal stability): the hybrid +// route stays the bit-exact one; this kernel is selected only by l_mode=fast. +// @wg-kernel w64_lc12/l_post_tf_p12_fast co=- entry=l_post_tf_p12_fast block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u defines=LP_W64=1,LP_FAST=1 +// @wg-kernel w64_lc12/l_post_tf_p12_pf_fast co=- entry=l_post_tf_p12_fast block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u defines=LP_W64=1,LP_FAST=1,LP_PIDIV=1 +// +// LP_WIN3 (w64_lc12/l_post_tf_p12[_pf]_fast3; runtime lever bit 256 of WG_L_FAST_MASK, inside lever 1): the gather of every +// D pixel over the 3 x 3 render texels CENTRED on it (columns floor(px) - 1 ... + 1, rows floor(py) - 1 ... + 1: every tap +// within 1.5 render pixels on both axes; the outer ring of the 4 x 4 window floor(p - 1/2) - 1 ... + 2 that lies 1.5 to 2 +// pixels out on one side is dropped, where the anisotropic weight 2^(u^2 kA + v^2 kB + u v kC) is small). The two rows of +// a pair keep their own centred rows: the wave reads the pair's rows n0 - 1 ... n0 + 1 and, when the second row's nearest +// texel row is n0 + 1 (wave-uniform), the row n0 + 2 too: 18 taps per row pair instead of 32, 9 or 12 staged texels read +// instead of 16. One column less per step footprint: staging cap 448 texels (10 752 bytes; LDS 21 504 bytes, a third of +// the CU's 64 KB); host check l_tf3_supported (a footprint over the cap runs the 4 x 4 kernel). +// @wg-kernel w64_lc12/l_post_tf_p12_fast3 co=- entry=l_post_tf_p12_fast block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u defines=LP_W64=1,LP_FAST=1,LP_WIN3=1 +// @wg-kernel w64_lc12/l_post_tf_p12_pf_fast3 co=- entry=l_post_tf_p12_fast block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u defines=LP_W64=1,LP_FAST=1,LP_PIDIV=1,LP_WIN3=1 +#include "wg_platform.hlsli" +#ifndef LP_PIDIV +#define LP_PIDIV 0 +#endif +#ifndef LP_WIN3 +#define LP_WIN3 0 +#endif +#if WG_WAVE != 64 || WG_BLOCK != 512 +#error "l_post_tf_fast.hlsl: wave64, 512 lanes" +#endif + +WG_ARGS_BEGIN + uint color, A, B, C, hist_prev, m_near, m_center, m_far, w_p, hist_out, reduced, out_p; // pointers (A: A8, C: C4) + int P_rw, P_rh, P_dw, P_dh, P_reset, P_pad0, P_pad1, P_pad2; // WgPostParams + float P_rx, P_ry, P_jx, P_jy, P_e, P_e_prev, P_ratio, P_pad3; + uint expo; + int ow, oh; + float dec_scale_arg, pi_arg; + int pitch_bytes, cpairs, k1, c2; +WG_ARGS_END + +#if LP_WIN3 +#define kStageCap 448 // staged render texels per step (6 dwords each: 10752 bytes); lanes 448 ... 511 stage none +#else +#define kStageCap 512 // staged render texels per step (6 dwords each: 12288 bytes); one per lane +#endif +#define kTexDw 6 // staged texel: f0 f1 | f2 f3 | f4 f5 | f6 f7 | f8 kA | kB kC (FP16 bits) +#if LP_WIN3 +#define kLWin 3 // the centred window: taps -1, 0, +1 +#else +#define kLWin 4 +#endif +#define kTfCols 64 +#define kTfOwn 60 +#define kTfOutX 40 +#define kNW 8 // row pairs per step (= waves64 of the workgroup) +#define kRing (2 * kNW + 6) // 22 +#define kThreads (64 * kNW) // 512 +#define kRowDw 96 // one ring row: the display pass (3 channels x 32 dwords) / the filtered row (3 x 20 dwords of two FP16) +#define kLdsDw ((kRing + 6) * kRowDw) // 2688 dwords = 10752 bytes (+ 12288 staged texels = 23040) +#define kPairs (kTfOutX / 2) // 20 dwords of two adjacent output columns per channel + +groupshared uint sh_tex[kStageCap * kTexDw]; +groupshared uint lds[kLdsDw]; + +static const float kEncK = asfloat(0x3dddf184u); // 0.36f * 0.30102999566398120f +static const float kDecK = asfloat(0x4113a428u); // 3.32192809488736235f / 0.36f +static const float kInv255 = asfloat(0x3b808081u); // 1.0f / 255.0f +static const float kInv245 = asfloat(0x3ed0fac6u); // 1.0f / 2.45f +static const float k1em4 = asfloat(0x38d1b717u); // 1e-4f +static const float k1em10 = asfloat(0x2edbe6ffu); // 1e-10f +static const float k1p1 = asfloat(0x3f8ccccdu); // 1.1f +static const float k0p05 = asfloat(0x3d4ccccdu); // 0.05f +static const float kDisplayMax = asfloat(0x401ccccdu); // 2.45f +static const float k0p01 = asfloat(0x3c23d70au); // 0.01f +static const float kShapeAB = asfloat(0xbf38a8c1u); // -0.721325f +static const float kShapeC = asfloat(0xbfb8a8c1u); // -1.44265f +static const float kRn = 1.00034f; // 1 + 2^-11.7: the pack truncates, this makes its mean error ~0 +static const float kEncKr = kEncK * kRn, kInv255r = kInv255 * kRn, kShapeABr = kShapeAB * kRn, kShapeCr = kShapeC * kRn; +static const float kLz0 = asfloat(0xbdba3b4bu), kLz1 = asfloat(0x3de71ca9u), kLz2 = asfloat(0x3f23b70fu); +static const float kLz3 = asfloat(0x3ed182b5u), kLz4 = asfloat(0xbd90a4acu); + +static float g_e; // exposure (0 replaced by 1) +static float g_k_hist; // 0.01 / e_prev * e: the history candidates' scale into the current exposure's linear units +static float g_ipi; // 1 / pi (_pf) +// The option word is pitch_bytes (unused by the hybrid kernel; the runtime's l_mode=fast levers 16 and 64): +static bool g_secbl; // bit 0: the weaker history candidate (n = 1, weight <= 1/2) is a 4-tap bilinear of the previous history + // instead of the 12-tap Catmull-Rom +static bool g_w2hi; // bit 2 (off by default): a weaker candidate of weight below 0.05 is dropped (the hybrid route's threshold: 1 / 255) +static bool g_secsame; // bit 1: a weaker candidate whose motion is within 0.01 render pixel of the first one's is the same sample + // (the weights add to 1: the first candidate alone); static and smooth regions skip the second history read +static bool g_oct; // bit 3: the 4 x 4 gather without its four corner taps (12 taps: the inner 2 x 2 and the axial ones) +static bool g_encbl; // bit 4: two valid history candidates blended in the encoded domain, one decode (3 exponentials, not 6) + +float unif(float x) { return asfloat(WaveReadLaneFirst(asuint(x))); } +uint mul24(uint a, uint b) { return (a & 0xffffffu) * (b & 0xffffffu); } +int mul_i24(int a, int b) { return ((int)((uint)a << 8) >> 8) * ((int)((uint)b << 8) >> 8); } +int clampi(int v, int lo, int hi) { int t = v > hi ? hi : v; return t < lo ? lo : t; } +int mini(int a, int b) { return a < b ? a : b; } +int floor_i(float v) { return (int)floor(v); } +float clampf(float v, float lo, float hi) { return min(max(v, lo), hi); } +half h_bits(uint b) { return asfloat16((uint16_t)b); } +uint pk2(float a, float b) { return f32tof16(a) | (f32tof16(b) << 16); } // v_cvt_pk_rtz_f16_f32 +float rn16(float x) { return asfloat(asuint(x) + 0x1000u); } // + half an FP16 step, then the truncating pack + +// E(v) = kEncK log2(max(fma(100, v, 1), 1e-4)); the encoded colour of a staged texel: E_in(v) = E(min(v, 32752)), E_in(NaN) = 0 +float enc_log(float v) { return log2(max(mad(100.0f, v, 1.0f), k1em4)); } +float enc_in_r(float v) { return isnan(v) ? 0.0f : kEncKr * enc_log(min(v, 32752.0f)); } + +// 8-byte-aligned loads (every history texel and A8 texel is 8 bytes from a 256-byte-aligned arena base): the mask tells the +// compiler the alignment so each span is one 128-bit / 64-bit load instead of 32-bit pieces +uint2 ld64_a8(uint a) { return wg_mem.Load2(a & ~7u); } +uint4 ld128_a8(uint a) { return wg_mem.Load4(a & ~7u); } + +// ---- the staged texel ------------------------------------------------------------------------------------------------- +struct LRaw { float4 c; uint2 d; uint c01; }; +LRaw raw_fetch(int idx) +{ + LRaw r; + const uint ui = (uint)idx; + r.c = asfloat(wg_mem.Load4((color + ui * 16u) & ~15u)); // 16-byte texels of a 256-byte-aligned base + r.d = ld64_a8(A + ui * 8u); + r.c01 = wg_ld32(C, ui * 4u); + return r; +} +float code_f(uint v, uint i) { return (float)((v >> (8u * i)) & 0xffu) * kInv255r; } +// six dwords of FP16 bits, each one native pack of two values: (f0 f1) (f2 b0) (b1 b2) (a0 a1) (a2 kA) (kB kC) +void raw_put(LRaw r, uint dst, bool store) +{ + const uint a = r.d.x & 0xffffffu; + const uint b = (r.d.x >> 24) | ((r.d.y & 0xffffu) << 8); + const uint2 k = uint2(r.c01, r.d.y >> 16); + float3 c = r.c.xyz; +#if LP_PIDIV + c *= g_ipi; +#endif + const float k0 = f16tof32(k.x), k1 = f16tof32(k.x >> 16), k2 = f16tof32(k.y); + const float e0 = enc_in_r(g_e * c.x), e1 = enc_in_r(g_e * c.y), e2 = enc_in_r(g_e * c.z); + if (store) { + sh_tex[dst + 0u] = pk2(e0, e1); + sh_tex[dst + 1u] = pk2(e2, code_f(b, 0u)); + sh_tex[dst + 2u] = pk2(code_f(b, 1u), code_f(b, 2u)); + sh_tex[dst + 3u] = pk2(code_f(a, 0u), code_f(a, 1u)); + sh_tex[dst + 4u] = pk2(code_f(a, 2u), k0 * kShapeABr); + sh_tex[dst + 5u] = pk2(k1 * kShapeABr, k2 * kShapeCr); + } +} + +// The footprint of one step: rows r0 ..., ncol columns from c0 +float lpx(int xx) { return mad((float)xx + 0.5f, P_rx, P_jx); } +float lpy(int yy) { return mad(P_ry, (float)yy + 0.5f, P_jy); } +int step_rows(int ys, int r_need, out int r0) +{ + const int yl = mini(ys + 2 * (kNW - 1), r_need) & ~1; +#if LP_WIN3 + // rows floor(py0) - 1 of the first pair ... floor(py0) + 2 of the last (its second row's centred rows end there) + r0 = floor_i(lpy(ys)) - 1; + return floor_i(lpy(yl)) + 2 - r0 + 1; +#else + r0 = floor_i(lpy(ys) - 0.5f) - 1; + return floor_i(lpy(yl) - 0.5f) + 2 - r0 + 1; +#endif +} + +// ---- the gather: nine FP16 feature sums and the FP16 total weight, per pixel ---------------------------------------------- +struct LGather { half F[9]; half W; }; +LGather gather_zero() +{ + LGather g; + [unroll] for (int k = 0; k < 9; ++k) g.F[k] = (half)0.0f; + g.W = (half)0.0f; + return g; +} +// one tap: eps = fma(u v, kC, fma(v v, kB, u u kA)) in FP16, w = 2^eps (v_exp_f16); F_k += w f_k, W += w +void tap_acc(inout LGather g, uint t[kTexDw], half w) +{ + g.W += w; + [unroll] for (int k = 0; k < 9; ++k) { + const uint d = t[k >> 1]; + g.F[k] = mad(w, h_bits((k & 1) ? (d >> 16) : d), g.F[k]); + } +} +// one column i of the 4 x 4 gather (taps j = -1 ... 2 for both rows of the pair) from the staged texels +// (rows jj = j_lo ... j_hi: the full column, or with lever bit 3 the edge columns' middle rows / their corners alone) +void gather_col(int i, half dx, int tb0, int rstride, half v0[kLWin], half v1[kLWin], half vv0[kLWin], half vv1[kLWin], + inout LGather g0, inout LGather g1, int j_lo = 0, int j_hi = kLWin - 1, int j_step = 1) +{ + const half u = dx + (half)(float)i; + const half uu = u * u; + const int col_base = tb0 + (i + 1) * kTexDw; + [unroll] for (int jj = j_lo; jj <= j_hi; jj += j_step) { + const int base = col_base + jj * rstride; + uint t[kTexDw]; + [unroll] for (int d = 0; d < kTexDw; ++d) t[d] = sh_tex[base + d]; + const half kA = h_bits(t[4] >> 16), kB = h_bits(t[5]), kC = h_bits(t[5] >> 16); + const half ta = uu * kA; + const half w0 = exp2(mad(u * v0[jj], kC, mad(vv0[jj], kB, ta))); + const half w1 = exp2(mad(u * v1[jj], kC, mad(vv1[jj], kB, ta))); + tap_acc(g0, t, w0); + tap_acc(g1, t, w1); + } +} + +#if LP_WIN3 +// one column i of the centred 3 x 3 gathers of both rows: the staged rows n0 - 1 + jj; row 0 takes jj = 0, 1, 2, row 1 +// jj = d1, d1 + 1, d1 + 2 (d1 = n1 - n0, 0 or 1, wave-uniform): rows jj = 0 ... 2 for both (row 1's weight at jj = 0 is 0 +// when d1), then with d1 the row n0 + 2 for row 1 alone (a uniform branch: with d1 = 0 it is not read) +void gather_col3(int i, half dx, int tb0, int rstride, bool d1, half v0[4], half v1[4], half vv0[4], half vv1[4], + inout LGather g0, inout LGather g1) +{ + const half u = dx + (half)(float)i; + const half uu = u * u; + const int col_base = tb0 + (i + 1) * kTexDw; + [unroll] for (int jj = 0; jj < 3; ++jj) { + const int base = col_base + jj * rstride; + uint t[kTexDw]; + [unroll] for (int d = 0; d < kTexDw; ++d) t[d] = sh_tex[base + d]; + const half kA = h_bits(t[4] >> 16), kB = h_bits(t[5]), kC = h_bits(t[5] >> 16); + const half ta = uu * kA; + const half w0 = exp2(mad(u * v0[jj], kC, mad(vv0[jj], kB, ta))); + half w1 = exp2(mad(u * v1[jj], kC, mad(vv1[jj], kB, ta))); + if (jj == 0 && d1) w1 = (half)0.0f; + tap_acc(g0, t, w0); + tap_acc(g1, t, w1); + } + [branch] if (d1) { + const int base = col_base + 3 * rstride; + uint t[kTexDw]; + [unroll] for (int d = 0; d < kTexDw; ++d) t[d] = sh_tex[base + d]; + const half kA = h_bits(t[4] >> 16), kB = h_bits(t[5]), kC = h_bits(t[5] >> 16); + tap_acc(g1, t, exp2(mad(u * v1[3], kC, mad(vv1[3], kB, uu * kA)))); + } +} +#endif + +// ---- history: 12-tap Catmull-Rom of the previous full history (8-byte RGBA16F texels) -------------------------------- +float4 cr_weights(float f) // Catmull-Rom (a = -1/2) in Horner form: 12 operations (the weights sum to 1) +{ + const float f2 = f * f; + float4 w; + w.x = f * mad(f, mad(-0.5f, f, 1.0f), -0.5f); + w.y = mad(f2, mad(1.5f, f, -2.5f), 1.0f); + w.z = f * mad(f, mad(-1.5f, f, 2.0f), 0.5f); + w.w = f2 * mad(0.5f, f, -0.5f); + return w; +} +float3 h3(uint2 v) { return float3(f16tof32(v.x), f16tof32(v.x >> 16), f16tof32(v.y)); } + +float3 history_cr(float qx, float qy) +{ + const float tx = qx - 0.5f, ty = qy - 0.5f; + const float fx0 = floor(tx), fy0 = floor(ty); + const float4 wx = cr_weights(tx - fx0), wy = cr_weights(ty - fy0); + const int ix = (int)fx0, iy = (int)fy0; + const uint pitch = (uint)P_dw * 8u; + // interior fast path (every lane's 4 x 4 footprint inside the image): six 16-byte span loads from one base + const bool interior = and(and(P_dw >= 4, P_dh >= 4), + and((uint)(ix - 1) <= (uint)(P_dw - 4), (uint)(iy - 1) <= (uint)(P_dh - 4))); + const float3 zi = float3(0.0f, 0.0f, 0.0f); + [branch] if (WaveActiveAllTrue(interior)) { + const uint b0 = hist_prev + (uint)(ix - 1) * 8u + (uint)(iy - 1) * pitch; + const uint b1 = b0 + pitch, b2 = b0 + 2u * pitch, b3 = b0 + 3u * pitch; + const uint4 a0 = ld128_a8(b0 + 8u), a10 = ld128_a8(b1), a11 = ld128_a8(b1 + 16u); + const uint4 a20 = ld128_a8(b2), a21 = ld128_a8(b2 + 16u), a3 = ld128_a8(b3 + 8u); + const float3 q0 = mad(wx.z, h3(a0.zw), wx.y * h3(a0.xy)); + const float3 q1 = mad(wx.w, h3(a11.zw), mad(wx.z, h3(a11.xy), mad(wx.y, h3(a10.zw), wx.x * h3(a10.xy)))); + const float3 q2 = mad(wx.w, h3(a21.zw), mad(wx.z, h3(a21.xy), mad(wx.y, h3(a20.zw), wx.x * h3(a20.xy)))); + const float3 q3 = mad(wx.z, h3(a3.zw), wx.y * h3(a3.xy)); + const float3 acci = mad(wy.w, q3, mad(wy.z, q2, mad(wy.y, q1, wy.x * q0))); + const float normi = mad(wx.y + wx.z, wy.x + wy.w, wy.y + wy.z); // the weights of a row sum to 1 + return acci * rcp(normi); + } + uint ro[4], co[4]; + [unroll] for (int k = 0; k < 4; ++k) { + co[k] = hist_prev + (uint)clampi(ix - 1 + k, 0, P_dw - 1) * 8u; + ro[k] = (uint)clampi(iy - 1 + k, 0, P_dh - 1) * pitch; + } + const float3 r0 = mad(wx.z, h3(ld64_a8(ro[0] + co[2])), wx.y * h3(ld64_a8(ro[0] + co[1]))); + const float3 r1 = mad(wx.w, h3(ld64_a8(ro[1] + co[3])), mad(wx.z, h3(ld64_a8(ro[1] + co[2])), + mad(wx.y, h3(ld64_a8(ro[1] + co[1])), wx.x * h3(ld64_a8(ro[1] + co[0]))))); + const float3 r2 = mad(wx.w, h3(ld64_a8(ro[2] + co[3])), mad(wx.z, h3(ld64_a8(ro[2] + co[2])), + mad(wx.y, h3(ld64_a8(ro[2] + co[1])), wx.x * h3(ld64_a8(ro[2] + co[0]))))); + const float3 r3 = mad(wx.z, h3(ld64_a8(ro[3] + co[2])), wx.y * h3(ld64_a8(ro[3] + co[1]))); + const float3 acc = mad(wy.w, r3, mad(wy.z, r2, mad(wy.y, r1, wy.x * r0))); + const float norm = mad(wx.y + wx.z, wy.x + wy.w, wy.y + wy.z); + return acc * rcp(norm); +} + +// 4-tap bilinear of the previous history (the weaker candidate under LP_SEC_BILINEAR): clamped texel coordinates +float3 history_bilinear(float qx, float qy) +{ + const float tx = qx - 0.5f, ty = qy - 0.5f; + const float fx0 = floor(tx), fy0 = floor(ty); + const float fx = tx - fx0, fy = ty - fy0; + const int ix = (int)fx0, iy = (int)fy0; + const uint pitch = (uint)P_dw * 8u; + const uint ca = hist_prev + (uint)clampi(ix, 0, P_dw - 1) * 8u, cb = hist_prev + (uint)clampi(ix + 1, 0, P_dw - 1) * 8u; + const uint ra = (uint)clampi(iy, 0, P_dh - 1) * pitch, rb = (uint)clampi(iy + 1, 0, P_dh - 1) * pitch; + const float3 t0 = mad(fx, h3(ld64_a8(ra + cb)) - h3(ld64_a8(ra + ca)), h3(ld64_a8(ra + ca))); + const float3 t1 = mad(fx, h3(ld64_a8(rb + cb)) - h3(ld64_a8(rb + ca)), h3(ld64_a8(rb + ca))); + return mad(fy, t1 - t0, t0); +} + +// D(h) in the current exposure's linear units: (exp2(clamp(h, 1e-4, 3) kDecK) - 1) 0.01 e / e_prev (the 12-bit polynomial +// branch of the hybrid route is not needed: no wave vote, one exponential per value) +float dec_hist(float h) { return (exp2(clampf(h, k1em4, 3.0f) * kDecK) - 1.0f) * g_k_hist; } +float dec_cur(float h) { return (exp2(clampf(h, k1em4, 3.0f) * kDecK) - 1.0f) * k0p01; } + +// ---- steps 3 to 5 of one D pixel (l_select + l_post_core) ----------------------------------------------------------- +void l_post_core(LGather g, int x, int y, int fx, int fy, float mx[3], float my[3], float s, out float hh[3], out float oh[3]) +{ + const float inv = rcp(max((float)g.W, asfloat(0x33800000u))); // >= 2^-24: a pixel whose weights all flushed has zero features, not NaN + const float sig0 = inv * (float)g.F[3], sig1 = inv * (float)g.F[4], sig2 = inv * (float)g.F[5]; + const bool sb1 = sig1 > sig0; + const float best = sb1 ? sig1 : sig0; + const bool sb2 = sig2 > best; + const float s1 = sb2 ? sig2 : best; + const float m1x = sb2 ? mx[2] : (sb1 ? mx[1] : mx[0]), m1y = sb2 ? my[2] : (sb1 ? my[1] : my[0]); + const bool sf0 = !or(sb1, sb2); + const float so1 = sf0 ? sig1 : sig0, so2 = sb2 ? sig1 : sig2; + const float mo1x = sf0 ? mx[1] : mx[0], mo1y = sf0 ? my[1] : my[0]; + const float mo2x = sb2 ? mx[1] : mx[2], mo2y = sb2 ? my[1] : my[2]; + const bool scc = so2 > so1; + const float s2 = scc ? so2 : so1; + const float m2x = scc ? mo2x : mo1x, m2y = scc ? mo2y : mo1y; + const float q1 = clampf(mad(k1p1, s1, -k0p05), 0.0f, 1.0f); + const float q2 = clampf(mad(k1p1, s2, -k0p05), 0.0f, 1.0f); + const float rden = rcp(max(q1 + q2, k1em10)); + float w2 = q2 * rden, w1; + if (w2 < (g_w2hi ? k0p05 : kInv255)) { + w2 = 0.0f; + w1 = 1.0f; + } else { + w1 = q1 * rden; + } + if (g_secsame && abs(m2x - m1x) + abs(m2y - m1y) < 0.01f) { // the same sample twice: the first candidate alone + w2 = 0.0f; + w1 = 1.0f; + } + const float X = (float)x + 0.5f, Y = (float)y + 0.5f; + const int ncand = w2 != 0.0f ? 2 : 1; + float L[2][3]; + bool hvalid[2] = {false, false}; + const bool encm = and(g_encbl, ncand == 2); // L[n] of a valid history candidate holds its encoded value until the blend + [unroll] for (int n = 0; n < 2; ++n) { + L[n][0] = 0.0f; L[n][1] = 0.0f; L[n][2] = 0.0f; + if (n < ncand) { + const float qx = X + (n == 0 ? m1x : m2x); + const float qy = Y + (n == 0 ? m1y : m2y); + const bool valid = and(and(and(and(P_reset == 0, qx >= 0.0f), qx <= (float)P_dw), qy >= 0.0f), qy <= (float)P_dh); + if (valid) { + const float3 h = (n == 1 && g_secbl) ? history_bilinear(qx, qy) : history_cr(qx, qy); + hvalid[n] = true; + L[n][0] = encm ? h.x : dec_hist(h.x); + L[n][1] = encm ? h.y : dec_hist(h.y); + L[n][2] = encm ? h.z : dec_hist(h.z); + } else { + float4 c = wg_ld4f(color, (uint)(fy * P_rw + fx) * 16u); +#if LP_PIDIV + c.xyz *= g_ipi; +#endif + const float ge = g_e; // L is in the current exposure's units already: the raw colour times e + L[n][0] = c.x * ge; L[n][1] = c.y * ge; L[n][2] = c.z * ge; + } + } + } + float Hl[3], Cl[3]; + if (and(encm, and(hvalid[0], hvalid[1]))) { // two history candidates: one decode of the encoded blend + [unroll] for (int i = 0; i < 3; ++i) Hl[i] = dec_hist(mad(w1, L[0][i], w2 * L[1][i])); + } else { + if (encm) { // one of the two is the colour fallback: decode the history one, then the blend below + [unroll] for (int n = 0; n < 2; ++n) + if (hvalid[n]) { + [unroll] for (int i = 0; i < 3; ++i) L[n][i] = dec_hist(L[n][i]); + } + } + [unroll] for (int i = 0; i < 3; ++i) Hl[i] = ncand == 2 ? mad(w1, L[0][i], w2 * L[1][i]) : w1 * L[0][i]; + } + [unroll] for (int i = 0; i < 3; ++i) Cl[i] = dec_cur(inv * (float)g.F[i]); + const float f7 = inv * (float)g.F[7], f8 = inv * (float)g.F[8]; + const float alpha = clampf(s * (float)g.F[6], 0.0f, 1.0f); // s W (F6 / W) = s F6: the total weight cancels + const float bh2 = mad(alpha, 1.0f - f7, f7); + const float bo2 = mad(alpha, 1.0f - f8, f8); + [unroll] for (int i = 0; i < 3; ++i) { + hh[i] = mad(Cl[i] - Hl[i], bh2, Hl[i]); + oh[i] = mad(Cl[i] - Hl[i], bo2, Hl[i]); + } + const float sh = hh[0] + hh[1] + hh[2], so = oh[0] + oh[1] + oh[2]; + if (isnan(sh)) { + [unroll] for (int i = 0; i < 3; ++i) hh[i] = Cl[i]; + } + if (isnan(so)) { + [unroll] for (int i = 0; i < 3; ++i) oh[i] = Cl[i]; + } +} + +// the render-resolution motion words of one pixel row: m_near / m_far at the nearest texel (fx, fy), m_center's four +// bilinear neighbours (clamped texel coordinates) of (px, py); loaded ahead of the gather (they do not depend on it) +struct MotRaw { uint mn, mf, ma, mb, mc, md; int fx, fy; float wx, wy; }; + +MotRaw motion_load(float px, float py) +{ + MotRaw m; + m.fx = clampi(floor_i(px), 0, P_rw - 1); + m.fy = clampi(floor_i(py), 0, P_rh - 1); + m.mn = wg_ld32(m_near, (uint)(m.fy * P_rw + m.fx) * 4u); + m.mf = wg_ld32(m_far, (uint)(m.fy * P_rw + m.fx) * 4u); + // motion_bilinear of m_center at (px, py) + const float tx = px - 0.5f, ty = py - 0.5f; + const float x0f = floor(tx), y0f = floor(ty); + m.wx = tx - x0f; + m.wy = ty - y0f; + const int c0 = (int)x0f, r0 = (int)y0f; + const int ca = clampi(c0, 0, P_rw - 1), cb = clampi(c0 + 1, 0, P_rw - 1); + const int ra = clampi(r0, 0, P_rh - 1), rb = clampi(r0 + 1, 0, P_rh - 1); + if (ca + 1 == cb) { + const uint2 top = wg_ld64(m_center, (uint)(ra * P_rw + ca) * 4u); + const uint2 bot = wg_ld64(m_center, (uint)(rb * P_rw + ca) * 4u); + m.ma = top.x; m.mb = top.y; + m.mc = bot.x; m.md = bot.y; + } else { + m.ma = wg_ld32(m_center, (uint)(ra * P_rw + ca) * 4u); + m.mb = wg_ld32(m_center, (uint)(ra * P_rw + cb) * 4u); + m.mc = wg_ld32(m_center, (uint)(rb * P_rw + ca) * 4u); + m.md = wg_ld32(m_center, (uint)(rb * P_rw + cb) * 4u); + } + return m; +} + +void finish_pixel(LGather g, int x, int y, MotRaw m, float s, out float hh[3], out float oh[3]) +{ + float mx[3], my[3]; + mx[0] = f16tof32(m.mn); my[0] = f16tof32(m.mn >> 16); + mx[2] = f16tof32(m.mf); my[2] = f16tof32(m.mf >> 16); + { // motion_bilinear of m_center, clamped texel coordinates + const float owx = 1.0f - m.wx, owy = 1.0f - m.wy; + const float topx = f16tof32(m.ma) * owx + f16tof32(m.mb) * m.wx, topy = f16tof32(m.ma >> 16) * owx + f16tof32(m.mb >> 16) * m.wx; + const float botx = f16tof32(m.mc) * owx + f16tof32(m.md) * m.wx, boty = f16tof32(m.mc >> 16) * owx + f16tof32(m.md >> 16) * m.wx; + mx[1] = topx * owy + botx * m.wy; + my[1] = topy * owy + boty * m.wy; + } + l_post_core(g, x, y, m.fx, m.fy, mx, my, s, hh, oh); +} + +// ---- the output filter's FP32 tap sums (post_filter_c1_s4's lz5a: v = w0 t0, fused multiply-adds, clamp to the taps' range) +float lz5a(float t0, float t1, float t2, float t3, float t4, float w0, float w1, float w3, float w4) +{ + float v = w0 * t0; + v = mad(w1, t1, v); + v = mad(kLz2, t2, v); + v = mad(w3, t3, v); + v = mad(w4, t4, v); + const float mid_lo = min(min(t1, t2), t3), mid_hi = max(max(t1, t2), t3); + const float lo = min(min(mid_lo, t0), t4), hi = max(max(mid_hi, t0), t4); + return min(max(v, lo), hi); // med3 (the taps are finite, lo <= hi) +} +float lz5a_even(float t[10], int o) { return lz5a(t[o], t[o + 1], t[o + 2], t[o + 3], t[o + 4], kLz0, kLz1, kLz3, kLz4); } +float lz5a_odd(float t[10], int o) { return lz5a(t[o], t[o + 1], t[o + 2], t[o + 3], t[o + 4], kLz4, kLz3, kLz1, kLz0); } + +WG_KERNEL(l_post_tf_p12_fast) +{ + WG_SETUP(); + if (P_dw < 4) return; + g_e = P_e; + float g_ep = P_e_prev; + float dec_scale = dec_scale_arg; + if (expo != 0u) { // the diet pair: [e, e_prev, last e, ratio, dec_scale] + const float e0 = unif(wg_ldf(expo, 0u)), e1 = unif(wg_ldf(expo, 4u)); + g_e = e0 == 0.0f ? 1.0f : e0; + g_ep = e1 == 0.0f ? 1.0f : e1; + dec_scale = unif(wg_ldf(expo, 16u)); + } + g_k_hist = unif(k0p01 * g_e * rcp(g_ep)); + g_secbl = (pitch_bytes & 1) != 0; + g_secsame = (pitch_bytes & 2) != 0; + g_w2hi = (pitch_bytes & 4) != 0; + g_oct = (pitch_bytes & 8) != 0; + g_encbl = (pitch_bytes & 16) != 0; +#if LP_PIDIV + g_ipi = unif(rcp(asfloat((uint)P_pad0))); +#endif + const float out_scale = unif(dec_scale * pi_arg); // dec_scale; with pi != 1 the runtime's scale_rgb folded in + const int lane = (int)wg_lane_id(); + const int wave = wg_uniform(lane >> 6), wl = lane & 63; // wave index: uniform (a scalar register) + const int strips = (ow + kTfOutX - 1) / kTfOutX; + const int bid = (int)wg_block_id(); + // workgroup bid -> (strip, chunk) as post_tf: the strips of chunk c rotated by c (the same set of workgroups) + const int chunk = wg_uniform(bid / strips); + const int strip = wg_uniform((bid - chunk * strips + chunk) % strips); + const int X0 = strip * kTfOwn; + const int csize = chunk < k1 ? cpairs : c2; + const int P0 = chunk < k1 ? chunk * cpairs : k1 * cpairs + (chunk - k1) * c2; + const int p_end = wg_uniform(mini(P0 + csize, (oh + 1) / 2)); + const int own_r0 = wg_uniform(3 * P0), own_r1 = wg_uniform(mini(3 * (P0 + csize), P_dh)); + const int r_first = wg_uniform(3 * P0 - 2 < 0 ? 0 : 3 * P0 - 2); + const int r_need = wg_uniform(mini(3 * (p_end - 1) + 4, P_dh - 1)); + const float s = wg_ldf(w_p, 0u); + + // the strip's render columns c0 ... c1 (taps ax - 1 ... ax + 2 of its first and last D column) +#if LP_WIN3 + const int c0 = floor_i(lpx(clampi(X0 - 2, 0, P_dw - 1))) - 1; + const int c1 = floor_i(lpx(clampi(X0 + kTfCols - 3, 0, P_dw - 1))) + 1; +#else + const int c0 = floor_i(lpx(clampi(X0 - 2, 0, P_dw - 1)) - 0.5f) - 1; + const int c1 = floor_i(lpx(clampi(X0 + kTfCols - 3, 0, P_dw - 1)) - 0.5f) + (kLWin - 2); +#endif + const int ncol = c1 - c0 + 1; + const float inv_ncol = unif(rcp((float)ncol)); + + // the staging of step y_step: footprint rows r0 ..., texels loaded one step ahead + int r0, nstage; + { + const int nrow = step_rows(r_first, r_need, r0); + nstage = ncol * nrow < kStageCap ? ncol * nrow : kStageCap; + } + LRaw raw; + { + const int i = mini(lane, nstage - 1); + const int r = (int)(((float)i + 0.5f) * inv_ncol), c = i - mul_i24(r, ncol); + raw = raw_fetch(clampi(r0 + r, 0, P_rh - 1) * P_rw + clampi(c0 + c, 0, P_rw - 1)); + } + + // this lane's D column (fixed over the walk) + const int xv = X0 - 2 + wl; + const int x = clampi(xv, 0, P_dw - 1); + const bool own_x = and(and(xv >= X0, xv < X0 + kTfOwn), xv < P_dw); + const float px = lpx(x); +#if LP_WIN3 + const int ax = floor_i(px); // the nearest texel column (centre ax + 1/2 within 1/2 of px) +#else + const int ax = floor_i(px - 0.5f); +#endif + const uint wlu = (uint)wl; + + int base_slot = 0; + int p_next = P0; + [loop] for (int y_step = r_first; y_step <= r_need; y_step += 2 * kNW) { + // 1. stage the footprint + [branch] if (wave * 64 < nstage) { // wave-uniform: a wave wholly past the staged range has nothing to store + raw_put(raw, (uint)lane * kTexDw, lane < nstage); + } + wg_barrier_lds(); + const int r0c = r0; + + // 2. reconstruction of the wave's row pair (yv, yv + 1) + const int yv = y_step + 2 * wave; + const bool wact = yv <= r_need; + int slot = base_slot + 2 * wave; + if (slot >= kRing) slot -= kRing; + const uint scr = (uint)slot * kRowDw; // dword of ring row slot (rows slot, slot + 1) + if (wact) { + const int y0 = yv; + const bool has1 = y0 + 1 < P_dh; + const float py0 = unif(lpy(y0)), py1 = unif(lpy(y0 + 1)); // wave-uniform (y0 is) +#if LP_WIN3 + // centred windows: n0 = floor(py0), n1 = floor(py1) in {n0, n0 + 1}; v of the staged row n0 - 1 + jj for + // both rows: v0 = (n0 + 1/2 - py0) + jj - 1, v1 = (n0 + 1/2 - py1) + jj - 1 + const int n0 = wg_uniform(floor_i(py0)), n1 = wg_uniform(floor_i(py1)); + const bool d1 = n1 != n0; + const half dx = (half)rn16(((float)ax + 0.5f) - px), dy0 = (half)rn16(((float)n0 + 0.5f) - py0); + const half dy1 = (half)rn16(((float)n0 + 0.5f) - py1); + half v0[4], v1[4], vv0[4], vv1[4]; + [unroll] for (int jj = 0; jj < 4; ++jj) { + v0[jj] = dy0 + (half)(float)(jj - 1); + v1[jj] = dy1 + (half)(float)(jj - 1); + vv0[jj] = v0[jj] * v0[jj]; + vv1[jj] = v1[jj] * v1[jj]; + } + LGather g0 = gather_zero(), g1 = gather_zero(); + const int tb0 = ((n0 - 1 - r0c) * ncol + (ax - 1 - c0)) * kTexDw, rstride = ncol * kTexDw; + [loop] for (int i = -1; i <= 1; ++i) + gather_col3(i, dx, tb0, rstride, d1, v0, v1, vv0, vv1, g0, g1); +#else + const int b = wg_uniform(floor_i(py0 - 0.5f)); + const int b1 = wg_uniform(floor_i(py1 - 0.5f)); + // gather offsets: dx = h((ax + 1/2) - px), d_y = h((b_y + 1/2) - py(y)) minus 1 (FP16) when the row's own b_y + // differs from the pair's b + const half dx = (half)rn16(((float)ax + 0.5f) - px), dy0 = (half)rn16(((float)b + 0.5f) - py0); + half dy1 = (half)rn16(((float)b1 + 0.5f) - py1); + if (b1 != b) dy1 = dy1 - (half)1.0f; + half v0[kLWin], v1[kLWin], vv0[kLWin], vv1[kLWin]; + [unroll] for (int jj = 0; jj < kLWin; ++jj) { + v0[jj] = dy0 + (half)(float)(jj - 1); + v1[jj] = dy1 + (half)(float)(jj - 1); + vv0[jj] = v0[jj] * v0[jj]; + vv1[jj] = v1[jj] * v1[jj]; + } + // taps column by column (i outer, j inner), both rows' gathers in one pass over the staged texels + LGather g0 = gather_zero(), g1 = gather_zero(); + const int tb0 = ((b - 1 - r0c) * ncol + (ax - 1 - c0)) * kTexDw, rstride = ncol * kTexDw; + [branch] if (g_oct) { // lever bit 3: the inner columns whole, the edge columns' middle rows (12 taps) + [loop] for (int i = 0; i <= 1; ++i) + gather_col(i, dx, tb0, rstride, v0, v1, vv0, vv1, g0, g1); + [loop] for (int i = -1; i <= 2; i += 3) + gather_col(i, dx, tb0, rstride, v0, v1, vv0, vv1, g0, g1, 1, 2); + } else { + [loop] for (int i = -1; i <= (kLWin - 2); ++i) + gather_col(i, dx, tb0, rstride, v0, v1, vv0, vv1, g0, g1); + } +#endif + + float r[3] = {0.0f, 0.0f, 0.0f}; + [loop] for (int row = 0; row < 2; ++row) { + const bool second = row == 1; + if (second && !has1) break; // wave-uniform: the missing second row is not stored and adds nothing + const int y = y0 + row; + LGather g = g0; + if (second) g = g1; + float hh[3], oo[3]; + const MotRaw mot = motion_load(px, second ? py1 : py0); + finish_pixel(g, x, y, mot, s, hh, oo); + float el[3], dv[3]; + [unroll] for (int ci = 0; ci < 3; ++ci) { + el[ci] = kEncKr * enc_log(hh[ci]); + dv[ci] = clampf(kEncKr * enc_log(oo[ci]), 0.0f, kDisplayMax); + } + const uint hx = pk2(el[0], el[1]), hy = pk2(el[2], dv[0]), hz = pk2(dv[1], dv[2]); + if (and(and(own_x, y >= own_r0), y < own_r1)) + wg_st64(hist_out, (uint)(y * P_dw + x) * 8u, uint2(hx, hy & 0xffffu)); + // display values (FP16) of the 64 columns -> scratch row slot + row: lanes 2m, 2m + 1 share a dword + const uint srow = scr + (uint)row * kRowDw; + [unroll] for (int c = 0; c < 3; ++c) { + const uint dvb = c == 0 ? hy >> 16 : (c == 1 ? hz & 0xffffu : hz >> 16); + const uint nbv = QuadReadAcrossX(dvb); + if ((wlu & 1u) == 0u) lds[srow + (uint)c * 32u + (wlu >> 1)] = dvb | (nbv << 16); + } + // reduced history: mean of H^ over the 2 x 2 block, r = h0 + h1 + [unroll] for (int ri = 0; ri < 3; ++ri) r[ri] = second ? r[ri] + hh[ri] : hh[ri]; + } + float o[3]; + [unroll] for (int i = 0; i < 3; ++i) o[i] = QuadReadAcrossX(r[i]); // lane ^ 1 + if (and(and(and(and(and((wl & 1) == 0, own_x), x + 1 < P_dw), has1), y0 >= own_r0), y0 + 1 < own_r1)) { + uint code = 0u; + [unroll] for (int i = 0; i < 3; ++i) { + const float m = (r[i] + o[i]) * 0.25f; + const float v = clampf(kEncK * enc_log(m) * kInv245, 0.0f, 1.0f); + code |= (uint)mad(v, 1023.0f, 0.5f) << (10 * i); + } + wg_st32(reduced, (uint)((y0 / 2) * (P_dw / 2) + x / 2) * 4u, code); + } + } + // the next step's staging loads (every lane loads a valid clamped texel) + { + const int nrow = step_rows(y_step + 2 * kNW, r_need, r0); + nstage = ncol * nrow < kStageCap ? ncol * nrow : kStageCap; + const int i = mini(lane, nstage - 1 < 0 ? 0 : nstage - 1); + const int r = (int)(((float)i + 0.5f) * inv_ncol), c = i - mul_i24(r, ncol); + raw = raw_fetch(clampi(r0 + r, 0, P_rh - 1) * P_rw + clampi(c0 + c, 0, P_rw - 1)); + } + + // horizontal pass of the wave's two rows: lane (row hk, channel hc, cell hg), output columns 4 hg ... 4 hg + 3 + GroupMemoryBarrier(); // the 64 lanes are one wave: its LDS operations execute in order (the fence orders the compiler) + const int hl = wl; + const bool hact = and(wact, hl < 60); + const int hk = hl >= 30 ? 1 : 0, hrem = hl - 30 * hk, hc = hrem >= 20 ? 2 : (hrem >= 10 ? 1 : 0), + hg = hrem - 10 * hc; + uint hv0 = 0u, hv1 = 0u; // the four filtered columns as two FP16 pairs + if (hact) { + const uint src = scr + (uint)hk * kRowDw + (uint)hc * 32u + (uint)hg * 3u; + float t[10]; // the FP16 display taps as FP32 values (exact) + [unroll] for (int i = 0; i < 5; ++i) { + const uint q = lds[src + (uint)i]; + t[2 * i] = f16tof32(q); + t[2 * i + 1] = f16tof32(q >> 16); + } + hv0 = pk2(rn16(lz5a_even(t, 0)), rn16(lz5a_odd(t, 2))); + hv1 = pk2(rn16(lz5a_even(t, 3)), rn16(lz5a_odd(t, 5))); + } + GroupMemoryBarrier(); + if (hact) { + const uint dst = scr + (uint)hk * kRowDw + (uint)hc * (uint)kPairs + (uint)hg * 2u; + lds[dst] = hv0; + lds[dst + 1u] = hv1; + if (slot + hk < 6) { // the first six ring rows are mirrored after the ring (wrap-free vertical taps) + const uint dm = dst + (uint)kRing * kRowDw; + lds[dm] = hv0; + lds[dm + 1u] = hv1; + } + } + wg_barrier_lds(); + + // 3. vertical pass, Dec and output of the row pairs whose input rows are complete; one item = two adjacent columns + const int r_done = mini(y_step + 2 * kNW, r_need + 1); + const int p_rdy = r_done > r_need ? p_end : mini(p_end, (r_done - 5) / 3 + 1); + const int nitems = (p_rdy - p_next) * 2 * kPairs; + const bool interior = and(3 * p_next - 2 >= 0, 3 * p_rdy + 1 <= P_dh - 1); + const int s0 = interior ? (3 * p_next - 2 - r_first) % kRing : 0; + [loop] for (int it = lane; it < nitems; it += kThreads) { + const int pr = (int)(mul24((uint)it, 52429u) >> 21); // it / 40 + const int rem = it - (int)mul24((uint)pr, 2u * kPairs); + const int dy = rem >= kPairs ? 1 : 0, m = rem - dy * kPairs; + const int pp = p_next + pr, y = 2 * pp + dy, xg = strip * kTfOutX + 2 * m; + if (or(y >= oh, xg >= ow)) continue; + uint t[5][3]; + if (interior) { // one ring address, the 15 taps at constant offsets (mirrored rows: no wrap) + int u = s0 + 3 * pr + 2 * dy; + u = u >= kRing ? u - kRing : u; + u = u >= kRing ? u - kRing : u; + const uint rp = mul24((uint)u, (uint)kRowDw) + (uint)m; + [unroll] for (int k = 0; k < 5; ++k) + [unroll] for (int c = 0; c < 3; ++c) t[k][c] = lds[rp + (uint)(k * kRowDw + c * kPairs)]; + } else { + const int xr = 3 * pp - 2 + 2 * dy; + const int row0 = clampi(xr, 0, P_dh - 1); + const int sl0 = (int)((uint)(row0 - r_first) % (uint)kRing); + [unroll] for (int k = 0; k < 5; ++k) { + const int st = clampi(xr + k, 0, P_dh - 1) - row0; + const int sl = sl0 + st >= kRing ? sl0 + st - kRing : sl0 + st; + [unroll] for (int c = 0; c < 3; ++c) t[k][c] = lds[(uint)sl * kRowDw + (uint)(c * kPairs + m)]; + } + } + // emit: weights of the lane's phase by selects, lz5a, Dec, store 3 x f32 per column + const bool ev = dy == 0; + const float w0 = ev ? kLz0 : kLz4, w4 = ev ? kLz4 : kLz0, w1 = ev ? kLz1 : kLz3, w3 = ev ? kLz3 : kLz1; + const uint o = mul24((uint)y, (uint)ow * 12u) + mul24((uint)xg, 12u); + [unroll] for (int cs = 0; cs < 2; ++cs) { + if (cs == 1 && xg + 1 >= ow) break; + float vo[3]; + [unroll] for (int c = 0; c < 3; ++c) { + const float q = clampf(lz5a(f16tof32(t[0][c] >> (16 * cs)), f16tof32(t[1][c] >> (16 * cs)), + f16tof32(t[2][c] >> (16 * cs)), f16tof32(t[3][c] >> (16 * cs)), + f16tof32(t[4][c] >> (16 * cs)), w0, w1, w3, w4), k1em4, 3.0f); + vo[c] = mad(exp2(q * kDecK), out_scale, -out_scale); // (2^(q kDecK) - 1) out_scale + } + wg_mem.Store3(out_p + o + (uint)cs * 12u, uint3(asuint(vo[0]), asuint(vo[1]), asuint(vo[2]))); + } + } + p_next = p_rdy; + base_slot += 2 * kNW; + if (base_slot >= kRing) base_slot -= kRing; + } +} diff --git a/clean/dx12/kernels/l_swin.hlsl b/clean/dx12/kernels/l_swin.hlsl index b93d427c..594fca6f 100644 --- a/clean/dx12/kernels/l_swin.hlsl +++ b/clean/dx12/kernels/l_swin.hlsl @@ -38,23 +38,21 @@ // the coarse one, member input RN16(E + S), as l_q7_block_c32_dec and the oracle) // (the linears and l_coef_pack12 as their own launches) with the original's FP16 norm, softmax, // GELU and start values around float32 FP8 chains, one FP16 rounding at each chain's end -// @wg-kernel l_swin_block_c32_enc_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=1,SW_HYB=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_hyb,WG_REV_ORDER=1 -// @wg-kernel l_swin_block_c32_dec_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_HYB=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_hyb +// @wg-kernel l_swin_block_c32_enc_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=1,SW_HYB=1,SW_HEAD_UNROLL=1,SW_NORM1_EARLY=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_hyb,WG_REV_ORDER=1 +// @wg-kernel l_swin_block_c32_dec_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_HYB=1,SW_HEAD_UNROLL=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_hyb // l_swin_block_c32_enc_lin_hyb / _dec_coef12_hyb the hybrid twins of the fusions le / lc (D3D12 only, speed lever 3): // _enc_hyb with the two input linears as its prologue (SW_SRC 3: the q map in its 20-byte // form, enc0.Win1, enc0.Win2 as the last arguments) and _dec_hyb with l_coef_pack12 as its // epilogue (SW_OUT_COEF12, COEF_CVT_HW); the same bytes as the launches they replace -// @wg-kernel l_swin_block_c32_enc_lin_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=3,SW_HYB=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_lin_hyb,WG_REV_ORDER=1 -// @wg-kernel l_swin_block_c32_dec_coef12_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p,p,p,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_OUT_COEF12=1,COEF_CVT_HW=1,SW_HYB=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_coef12_hyb,WG_REV_ORDER=1 +// @wg-kernel l_swin_block_c32_enc_lin_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=3,SW_HYB=1,SW_HEAD_UNROLL=1,SW_NORM1_EARLY=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_lin_hyb,WG_REV_ORDER=1 // ..._enc_lin_hyb_dump / _dec_coef12_hyb_dump (+ _mutdump: SW_HYB_MUT_ORDER=4) their stage dumps (probe=1, check only: // l_hyb_stage_check.py --set fused, the oracle per stage); _scanmut: the fused-square scan's // mutants (no contraction barrier, built beside every hybrid build, outside the manifest) // @wg-kernel l_swin_block_c32_enc_lin_hyb_dump co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=3,SW_HYB=1,SW_HYB_DUMP=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_lin_hyb_dump,WG_REV_ORDER=1 // @wg-kernel l_swin_block_c32_enc_lin_hyb_mutdump co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=3,SW_HYB=1,SW_HYB_DUMP=1,SW_HYB_MUT_ORDER=4,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_lin_hyb_mutdump,WG_REV_ORDER=1 -// @wg-kernel l_swin_block_c32_enc_lin_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=3,SW_HYB=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_lin_hyb_scanmut,WG_REV_ORDER=1 +// @wg-kernel l_swin_block_c32_enc_lin_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=3,SW_HYB=1,SW_HEAD_UNROLL=1,SW_NORM1_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_lin_hyb_scanmut,WG_REV_ORDER=1 // @wg-kernel l_swin_block_c32_dec_coef12_hyb_dump co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p,p,p,u,u,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_OUT_COEF12=1,COEF_CVT_HW=1,SW_HYB=1,SW_HYB_DUMP=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_coef12_hyb_dump // @wg-kernel l_swin_block_c32_dec_coef12_hyb_mutdump co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p,p,p,u,u,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_OUT_COEF12=1,COEF_CVT_HW=1,SW_HYB=1,SW_HYB_DUMP=1,SW_HYB_MUT_ORDER=4,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_coef12_hyb_mutdump -// @wg-kernel l_swin_block_c32_dec_coef12_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p,p,p,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_OUT_COEF12=1,COEF_CVT_HW=1,SW_HYB=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_coef12_hyb_scanmut // l_swin_block_c32_enc_hyb_dump / _dec_hyb_dump check variants (probe=1, never in a model build): the same kernels plus // the stage dump (SW_HYB_DUMP, the extra pointer argument; l_hyb_stage_check.py) // @wg-kernel l_swin_block_c32_enc_hyb_dump co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=1,SW_HYB=1,SW_HYB_DUMP=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_hyb_dump,WG_REV_ORDER=1 @@ -67,6 +65,6 @@ // l_swin_block_c32_enc_hyb_scanmut the fused-square scan's mutant (probe=1; build_dx12.py builds it beside every build // of hybrid kernels, outside the manifest, and requires hyb_isa_scan.py to FAIL on it): // _enc_hyb without the contraction barrier (HYB_SCAN_MUTANT=1) -// @wg-kernel l_swin_block_c32_enc_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=1,SW_HYB=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_hyb_scanmut,WG_REV_ORDER=1 -// @wg-kernel l_swin_block_c32_dec_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_HYB=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_hyb_scanmut +// @wg-kernel l_swin_block_c32_enc_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_SRC=1,SW_HYB=1,SW_HEAD_UNROLL=1,SW_NORM1_EARLY=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_hyb_scanmut,WG_REV_ORDER=1 +// @wg-kernel l_swin_block_c32_dec_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_HYB=1,SW_HEAD_UNROLL=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_hyb_scanmut #include "swin_block.hlsl" diff --git a/clean/dx12/kernels/l_swin_c32_fast.hlsl b/clean/dx12/kernels/l_swin_c32_fast.hlsl new file mode 100644 index 00000000..9d825067 --- /dev/null +++ b/clean/dx12/kernels/l_swin_c32_fast.hlsl @@ -0,0 +1,517 @@ +// SPDX-License-Identifier: MIT +// Model L's fast-mode width-32 Swin blocks with TWO windows per wave (runtime l_mode=fast, native D3D12 only; launched in +// place of a base kernel with the same arguments, runtime l_fast_alt; the base kernels, their "_fast" twins and every +// kernel l_mode=hybrid runs are not touched). The launch shape of swin_c64w2.hlsl: the launch keeps HIP's geometry +// (8 windows per launched 256-lane workgroup, grid = ceil(windows / 8)), the D3D12 device runs each launched workgroup as +// one workgroup of 128 lanes (manifest "group" 128, "gscale" 1), and wave v does windows 8 g + 2 v and 8 g + 2 v + 1: +// every staged weight fragment is read from LDS once for both windows, every bias / norm / linear weight is loaded once +// for both, a unit barrier waits for 4 waves instead of 8, and the two windows are independent chains for the matrix +// unit and the VALU. LDS: the same 16 KB staging (2 x 8 KB units: 4 workgroups per CU = 32 windows per CU, as the +// one-window kernels at 96 VGPRs), which needs <= 192 VGPRs (wave32, 128 lanes = 2 waves per SIMD per workgroup). +// +// The arithmetic is swin_block.hlsl's M-form chain (WMMA FP8 / FP16, the same packs, norms, soft cap and order of the +// products) except where fast mode drops the reference's bit-exactness: +// - GELU (LF_GELU): 1 = the clamped cubic GELU(x) = (x + |x| sat(P(|x|))) / 2, P(t) = c0 + c1 t + c2 t^2 + c3 t^3 +// fitted (weighted minimax) to the model's GELU E(t) = 2 GELU(t) / t - 1, evaluated in packed FP16 (per pair of +// values: one v_cvt_pk_rtz_f16_f32 of |x|, three v_pk_fma_f16, the last one saturated; then per value one +// v_fma_mix_f32 2 GELU = |x| sat(P) + x in FP32): three full-rate VALU operations per value, no exponential, no +// reciprocal, no table load. The halving is not an operation: the W2 products accumulate onto 2 x the residual +// (the accumulator doubled with b2, halved at the output: exact power-of-two scalings; FP8(2 g) = 2 FP8(g) for +// every normal FP8 value). |error| <= 0.0031, RMS 0.0014 for N(0, 1.5) inputs against the model's GELU (FP32 +// evaluation of the same cubic: 0.0020), 85 % of the FP8 codes unchanged (test_l_fast_numerics.py PolyGelu). +// P >= 1 from t = 3.3 on and never falls back below 1, so GELU(x) = x for x >= 3.3 and 0 for x <= -3.3. +// RX 9070 XT (2B-3): the earlier quick GELU x / (1 + 2^(-2.53 x)) (an exponential and a reciprocal per value: the +// quarter-rate transcendental unit) was 44 / 56 us slower than the table form, hence the polynomial. +// 2 = the model's GELU bytes by the arena table (swin_block.hlsl's sw_gelu_pre / sw_gelu_fin with SW_GELU_PAT 13333, +// the base kernels' form: no exponential, one 8-byte table load per value; both windows' loads issued before either +// window's fmas); 0 = HIP's transcendental chain (the same bytes, two exponential-unit operations per value; not +// declared: the table form is the exact A/B of the polynomial). +// (the "_w2t_fast" kernels are the "_w2p_fast" ones with LF_GELU 2: the A/B of the GELU approximation alone) +// - softmax: the scores are clamped by the soft cap (|c| <= 32.37, t = c - c^3 / (3 cap^2) in [-21.6, 21.6], times +// tau log2(e) = 0.51: exponents in [-11, 11]), so 2^z needs no maximum subtracted (no overflow: the sum of 16 terms +// is below 2^15; no underflow): the max reduction, its swizzle and the negated product are gone. The weights are +// the same values up to the rounding of the exponentials. +// - the decoder block's coefficient epilogue (SW_OUT_COEF12): one pixel per LANE instead of per lane pair: the +// channels 0..12 of a token sit in its hh = 0 lane for both windows, so the hh = 1 lane takes the second window's +// (13 v_permlanex16 + 13 selects) and every lane evaluates Model L's coefficient functions once; in FP32 from the +// block's FP32 output (no FP16 rounding of y2, no RN16 of the sigmas, tanh as 1 - 2 / (2^(2 t log2 e) + 1) for +// every t: no polynomial branch), the FP16 products by the native conversion with the scale folded in. +// +// @wg-kernel l_swin_block_c32_enc_lin_w2p_fast co=- block=256 group=128 gscale=1 wave=32 args=p,p,p,p,u,u,u,u,p,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=4,SW_SRC=3,WG_LD_A16=1,WG_REV_ORDER=1,LF_NAME=l_swin_block_c32_enc_lin_w2p_fast,LF_GELU=1 +// @wg-kernel l_swin_block_c32_enc_lin_w2t_fast co=- block=256 group=128 gscale=1 wave=32 args=p,p,p,p,u,u,u,u,p,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=4,SW_SRC=3,WG_LD_A16=1,WG_REV_ORDER=1,LF_NAME=l_swin_block_c32_enc_lin_w2t_fast,LF_GELU=2,SW_GELU_PAT=13333 +// @wg-kernel l_swin_block_c32_dec_coef12_add_w2p_fast co=- block=256 group=128 gscale=1 wave=32 args=p,p,p,p,u,u,u,u,p,p,p,p,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=4,SW_SRC=2,SW_OUT_F16=1,SW_OUT_COEF12=1,WG_LD_A16=1,LF_NAME=l_swin_block_c32_dec_coef12_add_w2p_fast,LF_GELU=1 +// @wg-kernel l_swin_block_c32_dec_coef12_add_w2t_fast co=- block=256 group=128 gscale=1 wave=32 args=p,p,p,p,u,u,u,u,p,p,p,p,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=4,SW_SRC=2,SW_OUT_F16=1,SW_OUT_COEF12=1,WG_LD_A16=1,LF_NAME=l_swin_block_c32_dec_coef12_add_w2t_fast,LF_GELU=2,SW_GELU_PAT=13333 +// +// Arguments as the kernels they replace: l_swin_block_c32_enc_lin_nc (x = the FP8 q halo map in its 20-byte form, xadd and +// out_p unused / the output map, w, H, W, ox, oy, enc0.Win1, enc0.Win2) and l_swin_block_c32_dec_coef12_add_nc (y, S, out +// unused, w, H, W, ox, oy, then the store's A, C, latent, dec0.coef, rw, rh). l_swin_c64_fast.hlsl instantiates the same +// body at C = 64 (Model L's middle blocks). +#ifndef LF_GELU +#define LF_GELU 1 +#endif +#ifndef LF_NAME +#error "l_swin_c32_fast.hlsl: LF_NAME (the kernel's name)" +#endif +#define SW_ENTRY_OVERRIDE lf_sw_one_window_unused // swin_block.hlsl's entry under another name (not compiled: not the entry) +#ifndef SW_GELU_PAT +#define SW_GELU_PAT 10000 // swin_block.hlsl's GELU knobs: no table of its own in this kernel (no groupshared table) +#endif +#include "swin_block.hlsl" + +#if (THREADS != 128 && THREADS != 256) || SW_HYB || SW_MEGA || !SW_SAFE || (SW_OUT_F16 && !SW_OUT_COEF12) || (SW_SRC != 0 && SW_SRC != 2 && SW_SRC != 3) || (SW_ECL > 0 && SW_SRC != 0) +#error "l_swin_c32_fast.hlsl: 128 or 256 lanes, the M-form inner packs; output q8 or the coefficient store; source 0 (with or without the fused expand), 2 or 3" +#endif +#if THREADS == 256 && (SW_C != 96 || SW_OUT_COEF12) +#error "l_swin_c32_fast.hlsl: one window per wave (256 lanes) is the width-96 form (l_swin_c96_fast.hlsl)" +#endif +#if SW_OUT_COEF12 && (SW_C != 32 || !SW_ADD || SW_SRC != 2) +#error "l_swin_c32_fast.hlsl: the coefficient store is Model L's decoder block (C = 32, the skip, the coarse source)" +#endif +#ifndef LF_PM +#define LF_PM 0 +#endif +#if LF_PM && (SW_C != 96 || SW_SRC != 0 || SW_ADD || SW_ECL > 0 || !defined(LF_PM_ARGS)) +#error "LF_PM: enc2's block with enc1's patch merge (C = 96, source 0; aux and aux2 appended to the arguments: l_swin_c96_fast.hlsl)" +#endif +#define LF_LIN (SW_SRC == 3) // the encoder block's input linears (Model L's enc0) +// LF_W2_ONE (the coefficient store at C = 32): the store reads channels 0..12 only, so W2 runs one output tile, tile 0 +// remapped to channels 0..15 in order (rows 8..15: tile 1's rows 0..7, the residual from lane t, the weight fragment from +// lane l - 8): half the W2 WMMAs, the same products and the same accumulation order for every channel stored +#define LF_W2_ONE (SW_OUT_COEF12 && SW_C == 32 && KC == 2) +#if LF_PM +#define LF_PM_W (16 * 6 * 256) // the 24 KB of merge fragments: both staging buffers +#if LF_PM_W > 2 * MAXU +#error "LF_PM: the merge fragments must fit the staging buffers" +#endif +// fused_swin.hlsl fz_stage_w: the 24 KB of fragments at src into LDS byte 0 (6 16-byte chunks per lane), then a barrier +void lf_stage_w(uint src, uint tid) +{ + uint4 v[6]; + [unroll] for (uint i = 0; i < 6; ++i) v[i] = wg_ld128(src, (tid + i * 256u) * 16u); + [unroll] for (uint i2 = 0; i2 < 6; ++i2) sw_lds_st128((tid + i2 * 256u) * 16u, v[i2]); + wg_barrier_lds(); +} +#endif +#if THREADS == 128 +#define NWW 2 // windows per wave: 128-lane workgroups (the launch shape of swin_c64w2.hlsl) +#else +#define NWW 1 // 256-lane workgroups, one window per wave (the launch shape of the width-96 base kernels) +#endif + +// ---- GELU: q8 of one 16-row tile (8 values per lane) ---------------------------------------------------------------- +// P(t) of the clamped cubic (test_l_fast_numerics.py PolyGelu.C: the same float32 values) +#if LF_GELU == 1 +static const float kLfP0 = asfloat(0xbd6c7ea1u), kLfP1 = asfloat(0x3f878bedu), kLfP2 = asfloat(0xbeb6e5c7u), + kLfP3 = asfloat(0x3d25ab15u); // -0.05773795, 1.0589577, -0.35722181, 0.040446360 +#define LF_G2 1 // the MLP's W2 products accumulate onto 2 x the residual (q8 of 2 GELU) +#else +#define LF_G2 0 +#endif +#if LF_GELU == 2 && (SW_GELU != 3 || SW_GELU_PAT != 13333 || SW_GL_LDS) +#error "LF_GELU 2: swin_block.hlsl's arena table for every tile (SW_GELU 3, SW_GELU_PAT 13333)" +#endif +uint2 lf_gelu_q8(v8f h) +{ + v8f y; +#if LF_GELU == 1 + // q8(2 GELU(h)) (LF_G2) in operations the driver can pair (VOPD): |h| by an AND with an opaque mask (an abs source + // modifier would make every operation VOP3), the Horner steps as v_fmaak (one shared literal per step), the clamp as + // v_min (P < 0 only below t = 0.055, where GELU's error stays under 0.0013 without the lower clamp), 2 GELU by v_fmac. + // Written stage by stage: the 8 independent chains interleave. + const uint am = 0x7fffffffu ^ (wg_grid_ >> 31); + float t[8], p[8]; + [unroll] for (uint i = 0; i < 8; ++i) t[i] = asfloat(asuint(h.v[i]) & am); + [unroll] for (uint i1 = 0; i1 < 8; ++i1) p[i1] = mad(kLfP3, t[i1], kLfP2); + [unroll] for (uint i2 = 0; i2 < 8; ++i2) p[i2] = mad(p[i2], t[i2], kLfP1); + [unroll] for (uint i3 = 0; i3 < 8; ++i3) p[i3] = min(mad(p[i3], t[i3], kLfP0), 1.0f); + [unroll] for (uint i4 = 0; i4 < 8; ++i4) y.v[i4] = mad(t[i4], p[i4], h.v[i4]); +#else + float t[8]; // HIP's chain (swin_block.hlsl gelu_group / sw_gelu_fin digit 0) + [unroll] for (uint i = 0; i < 8; ++i) t[i] = h.v[i] * h.v[i]; + [unroll] for (uint i1 = 0; i1 < 8; ++i1) t[i1] = mad(t[i1], asfloat(0xbdcd6502u), asfloat(0xc013b8edu)); + [unroll] for (uint i2 = 0; i2 < 8; ++i2) t[i2] = h.v[i2] * t[i2]; + [unroll] for (uint i3 = 0; i3 < 8; ++i3) t[i3] = wg_exp2(t[i3]); + [unroll] for (uint i4 = 0; i4 < 8; ++i4) t[i4] = 1.0f + t[i4]; + [unroll] for (uint i5 = 0; i5 < 8; ++i5) t[i5] = wg_rcp(t[i5]); + [unroll] for (uint i6 = 0; i6 < 8; ++i6) y.v[i6] = h.v[i6] * t[i6]; +#endif + return wg_pack_q8_nc_ags(y); +} + +// ---- softmax of one head's scores (lane (t, h): S(t, s) of 8 keys; the other 8 in lane t ^ 16) ---------------------- +// c = clamp(S + B, -cap, cap); t = fma(c^3, -1 / (3 cap^2), c); p = FP16(2^(t tau log2 e) / sum) (no max: see the header) +uint4 lf_softmax(v8f s, v8f bias) +{ + v8f c, tc, e; + [unroll] for (uint va0 = 0; va0 < 8; ++va0) c.v[va0] = s.v[va0] + bias.v[va0]; + [unroll] for (uint v = 0; v < 8; ++v) c.v[v] = min(max(c.v[v], asfloat(0xc20179dbu)), asfloat(0x420179dbu)); + [unroll] for (uint v1 = 0; v1 < 8; ++v1) tc.v[v1] = c.v[v1] * c.v[v1]; + [unroll] for (uint v2 = 0; v2 < 8; ++v2) tc.v[v2] = mad(c.v[v2] * tc.v[v2], asfloat(0xb9a6cc38u), c.v[v2]); + [unroll] for (uint v4 = 0; v4 < 8; ++v4) e.v[v4] = wg_exp2(tc.v[v4] * asfloat(0x3f028297u)); + float sum = sw_hsum8(e); + sum = sum + wg_xor16(sum); + const float rs = wg_rcp(sum); + v8f pm; + [unroll] for (uint v6 = 0; v6 < 8; ++v6) pm.v[v6] = mad(e.v[v6], rs, 0.0f); // the driver's v_fma_mix (one rounding) + return wg_to_f16_ags(pm); +} + +#if LF_LIN +// sw_load_halo_lin's TT_LINF32 form (swin_block.hlsl: the two input linears in FP32, x1 = FP8(relu(b + W q)), +// x2 = b2 + W2 x1) with the linears' weights loaded once per wave for both windows (lin_blob outside) +void lf_halo_lin(uint base, int pr, int pc, uint hh, v8f b1[2], uint2 f1[2][2], v8f b2[2], uint2 f2[2][2], out v8f f[KC]) +{ + const uint pix = (uint)((pr + 2) * (W + 4) + pc + 2); + uint2 xq[2]; + const uint plane1 = (uint)((H + 4) * (W + 4)) * 16u; + if (hh != 0u) { + xq[0] = uint2(wg_ld32(base, plane1 + pix * 4u), 0u); + xq[1] = uint2(0u, 0u); + } else { + const uint4 v = wg_ld128(base, pix * 16u); + xq[0] = v.xy; + xq[1] = v.zw; + } + uint2 x1[2]; + [unroll] for (uint m1 = 0; m1 < 2u; ++m1) { + v8f r = lin_acc(b1[m1], f1[m1], xq); + [unroll] for (uint j = 0; j < 8u; ++j) r.v[j] = wg_fmax(r.v[j], 0.0f); + x1[m1] = wg_pack_q8_ags(r); + } + [unroll] for (uint k8 = 0; k8 < KC; ++k8) f[k8] = lin_acc(b2[k8], f2[k8], x1); +} +#endif + +#if SW_OUT_COEF12 +// Model L's coefficient functions of one pixel (l_coef_px.hlsli's values in FP32; see the header) +float lf_sigma(float x) { return wg_rcp(1.0f + wg_exp2(x * asfloat(0xBFB8AA3Bu))); } // 1 / (1 + 2^(-x log2 e)) +float lf_tanh(float x) { return mad(wg_rcp(wg_exp2(x * asfloat(0x4038AA3Bu)) + 1.0f), -2.0f, 1.0f); } // 1 - 2 / (e^2x + 1) +uint lf_unorm8(float v) { return wg_f2u(mad(v, 255.0f, 0.5f)); } // v in [0, 1] +uint lf_snorm8(float v) { return (uint)wg_f2i(wg_rint(v * 127.0f)) & 0xffu; } // v in [-1, 1] +void lf_coef_px(float a[13], float S2, float T, uint pA, uint pC, uint pL, uint i) +{ + const uint cA = lf_unorm8(lf_sigma(a[0])) | (lf_unorm8(lf_sigma(a[1])) << 8) | (lf_unorm8(lf_sigma(a[2])) << 16); + const float m = max(max(a[3], a[4]), a[5]); + const float e0 = wg_exp2((a[3] - m) * asfloat(0x3FB8AA3Bu)), e1 = wg_exp2((a[4] - m) * asfloat(0x3FB8AA3Bu)), + e2 = wg_exp2((a[5] - m) * asfloat(0x3FB8AA3Bu)); + const float rs = wg_rcp(e2 + (e0 + e1)); + const uint cB = lf_unorm8(e0 * rs) | (lf_unorm8(e1 * rs) << 8) | (lf_unorm8(e2 * rs) << 16); + // C: (S g0)^2, (S g1)^2, (S g0)(S g1) tanh(a8 T), the S^2 and the round-to-nearest bias of the truncating pack folded + // into S2 (= S^2 (1 + 2^-11.7)) + const float g0 = lf_sigma(clamp(a[6], -20.0f, 20.0f)), g1 = lf_sigma(clamp(a[7], -20.0f, 20.0f)); + const float rho = lf_tanh(a[8] * T); + const float sg0 = S2 * g0; + const uint c0 = f32tof16(sg0 * g0) | (f32tof16((S2 * g1) * g1) << 16); + const uint c1 = f32tof16((sg0 * g1) * rho); + const uint cL = lf_snorm8(lf_tanh(a[9])) | (lf_snorm8(lf_tanh(a[10])) << 8) | (lf_snorm8(lf_tanh(a[11])) << 16) | + (lf_snorm8(lf_tanh(a[12])) << 24); + wg_st64(pA, i * 8u, uint2(cA | (cB << 24), (cB >> 8) | (c1 << 16))); + wg_st32(pC, i * 4u, c0); + wg_st32(pL, i * 4u, cL); +} +#endif + +WG_KERNEL(LF_NAME) +{ + WG_SETUP(); + const uint tid = wg_lane_id(); + const uint lane = tid & 31u, t = lane & 15u, hh = lane >> 4; + const int nwx = (W + ox + 3) >> 2, nwy = (H + oy + 3) >> 2, nwin = nwx * nwy; + const uint wave_id = (uint)wg_uniform((int)(tid >> 5)); + + Stager stage; + st_fetch(stage, w + L_head(0), HEAD_BYTES / 16, tid); // unit 0 + + // Gather: token t of each window, mirrored at the borders. + int dst[NWW]; +#if SW_OUT_COEF12 + int prw[NWW], pcw[NWW]; +#endif + v8f acc[NWW][KC]; +#if LF_LIN + v8f lb1[2], lb2[2]; + uint2 lf1[2][2], lf2[2][2]; + lin_blob(linW1, lane, hh, lb1, lf1); + lin_blob(linW2, lane, hh, lb2, lf2); +#else + uint2 xa[NWW][KC]; +#endif +#if SW_ADD + uint2 xb[NWW][KC]; +#endif +#if SW_ECL > 0 + const uint lowp = sw_win_low0(nwx, nwin, lane, (int)wg_block_id()); + fused_expand(w + L_TAIL, MAXU, nwx, nwin, tid, (int)wg_block_id(), lowp); + uint eslot[NWW]; +#endif + [unroll] for (uint i = 0; i < NWW; ++i) { + const int win0 = (int)(wg_block_id() * (THREADS / 32 * NWW) + wave_id * NWW + i); + const int win = win0 < nwin ? win0 : nwin - 1; + const int wy = win / nwx, wx = win - wy * nwx; + const int pr = 4 * wy - oy + (int)(t >> 2), pc = 4 * wx - ox + (int)(t & 3u); + const bool real = win0 < nwin && pr >= 0 && pr < H && pc >= 0 && pc < W; + dst[i] = real ? pr * W + pc : -1; +#if SW_OUT_COEF12 + prw[i] = pr; pcw[i] = pc; +#endif + const int mr = sw_mirror(pr, H), mc = sw_mirror(pc, W); +#if SW_ECL > 0 + const uint wb = wave_id * NWW + i; + const uint lpw = WaveReadLaneAt(lowp, wb); + const int low = ((mr >> 1) - (int)(lpw & 0xffffu)) * 2 + ((mc >> 1) - (int)(lpw >> 16)); + eslot[i] = wb * 16u + (uint)low * 4u + (uint)(((mr & 1) << 1) | (mc & 1)); +#elif LF_LIN + lf_halo_lin(x, pr, pc, hh, lb1, lf1, lb2, lf2, acc[i]); +#elif LF_PM + { // fused_swin.hlsl SW_PM (FZ_PMT 1): enc1's patch merge of this lane's (mirrored) token, the bias as the first + // accumulator, the 16 K groups in order, the clamping FP8 pack (patch_merge_c64's bytes) + uint2 zf[16]; + const uint zo = (uint)((2 * mr + (int)hh) * (2 * W) + 2 * mc) * 64u; + [unroll] for (uint q = 0; q < 8; ++q) { + const uint4 v = wg_ld128(x, zo + 16u * q); + zf[2 * q] = v.xy; zf[2 * q + 1] = v.zw; + } + lf_stage_w(aux + 4u * 96u, tid); + const uint bm = aux + hh * 32u, fbm = sw_lane_base(0u, lane); + [unroll] for (uint mp = 0; mp < KC; ++mp) { + uint2 fa[16]; + [unroll] for (uint g = 0; g < 16; ++g) fa[g] = sw_lfrag_b(fbm, mp * 16u + g); + v8f m = wg_load8f(bm, mp * 64u); + [unroll] for (uint g2 = 0; g2 < 16; ++g2) m = wg_wmma_fp8(fa[g2], zf[g2], m); + xa[i][mp] = sw_pack_q8_v2(m); + } + wg_barrier_lds(); // every wave is done with the merge fragments before unit 0 overwrites them + } +#elif SW_SRC == 2 + load_frags_g(x, sw_coarse_src(pr, pc, H, W, hh), xa[i]); +#else + load_frags_g(x, (uint)(mr * W + mc) * SW_C + hh * HALF, xa[i]); +#endif +#if SW_ADD + load_frags_g(xadd, (uint)(mr * W + mc) * SW_C + hh * HALF, xb[i]); +#endif + } + v8f ng[KC], nb[KC]; + { + const uint g1 = w + L_G1 + hh * (HALF * 4), bp = w + L_BP + hh * 32u; + [unroll] for (uint k = 0; k < KC; ++k) { ng[k] = wg_load8f(g1, 32u * k); nb[k] = wg_load8f(bp, 64u * k); } + } + st_commit(stage, 0u, HEAD_BYTES / 16, tid); + wg_barrier_lds(); +#if SW_ECL > 0 + [unroll] for (uint ie = 0; ie < NWW; ++ie) + [unroll] for (uint je = 0; je < KC / 2; ++je) { + const uint4 v = sw_lds_ld128(MAXU + eslot[ie] * SW_C + hh * HALF + 16u * je); + xa[ie][2 * je] = v.xy; xa[ie][2 * je + 1] = v.zw; + } + wg_barrier_lds(); // read before the buffer they live in is refilled +#endif + uint buf = 0u; + + // Steps 1-2: a = q8(RMSNorm(x; gamma1)); the residual accumulator starts as x + bp. + uint2 af[NWW][KC]; + [unroll] for (uint i1 = 0; i1 < NWW; ++i1) { +#if !LF_LIN + [unroll] for (uint k = 0; k < KC; ++k) { + acc[i1][k] = sw_unpack_fp8(xa[i1][k]); +#if SW_ADD + acc[i1][k] = sw_add8(acc[i1][k], sw_unpack_fp8(xb[i1][k])); +#endif + } +#endif + const float r = norm_r(acc[i1]); + [unroll] for (uint k2 = 0; k2 < KC; ++k2) { + v8f d; + [unroll] for (uint v = 0; v < 8; ++v) d.v[v] = acc[i1][k2].v[v] * r * ng[k2].v[v]; + af[i1][k2] = pack_in(d); + acc[i1][k2] = sw_add8(acc[i1][k2], nb[k2]); + } + } + + // Steps 3-7, one head at a time (unrolled); one staged unit per head (QKV fragments, then the head's slice of Wp). + [unroll] for (uint hd = 0; hd < SW_HEADS; ++hd) { + const bool last = hd + 1u == SW_HEADS; + if (last) st_fetch(stage, w + L_mlp(0), MLP_BYTES / 16, tid); + else st_fetch(stage, w + L_head(hd + 1u), HEAD_BYTES / 16, tid); + const uint fb = sw_lane_base(buf * MAXU, lane); + const v8f bias = wg_load8f(w + L_BIAS, ((hd * 16u + t) * 2u + hh) * 32u); + uint2 uf[NWW][2]; + uint4 vt[NWW][2]; + [unroll] for (uint mt = 0; mt < 2; ++mt) { + uint2 fq[KC], fv[KC]; + [unroll] for (uint kc = 0; kc < KC; ++kc) { + fq[kc] = sw_lfrag_b(fb, (mt * KC + kc) * 2u); + fv[kc] = sw_lfrag_b(fb, (mt * KC + kc) * 2u + 1u); + } + v8f accq[NWW], accv[NWW]; + [unroll] for (uint i = 0; i < NWW; ++i) { accq[i] = sw_zero8(); accv[i] = sw_zero8(); } + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) + [unroll] for (uint i2 = 0; i2 < NWW; ++i2) { + accq[i2] = wg_wmma_fp8(fq[kc2], af[i2][kc2], accq[i2]); + accv[i2] = wg_wmma_fp8(af[i2][kc2], fv[kc2], accv[i2]); + } + [unroll] for (uint i3 = 0; i3 < NWW; ++i3) { + uf[i3][mt] = pack_in(accq[i3]); + vt[i3][mt] = wg_to_f16_ags(accv[i3]); + } + } + uint2 of[NWW][2]; + [unroll] for (uint i4 = 0; i4 < NWW; ++i4) { + v8f s = wg_wmma_fp8(uf[i4][0], uf[i4][0], sw_zero8()); // S = U^T U + s = wg_wmma_fp8(uf[i4][1], uf[i4][1], s); + const uint4 p = lf_softmax(s, bias); + [unroll] for (uint dt = 0; dt < 2; ++dt) of[i4][dt] = pack_in(wg_wmma_f16(vt[i4][dt], p, sw_zero8())); + } + // x1 += Wp[:, head hd] q8(o_hd) + uint2 fp[KC][2]; + [unroll] for (uint m = 0; m < KC; ++m) { + fp[m][0] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u); + fp[m][1] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u + 1u); + } + [unroll] for (uint m2 = 0; m2 < KC; ++m2) + [unroll] for (uint i5 = 0; i5 < NWW; ++i5) { + acc[i5][m2] = wg_wmma_fp8(fp[m2][0], of[i5][0], acc[i5][m2]); + acc[i5][m2] = wg_wmma_fp8(fp[m2][1], of[i5][1], acc[i5][m2]); + } + if (last) st_commit(stage, (buf ^ 1u) * MAXU, MLP_BYTES / 16, tid); + else st_commit(stage, (buf ^ 1u) * MAXU, HEAD_BYTES / 16, tid); + wg_barrier_lds(); + buf ^= 1u; + } + + // Step 8: m = q8(RMSNorm(x1; gamma2)), then b2 into the residual accumulator. + uint2 mf[NWW][KC]; + { + const uint g2 = w + L_G2 + hh * (HALF * 4), b2 = w + L_B2 + hh * 32u; + float r[NWW]; + [unroll] for (uint i = 0; i < NWW; ++i) r[i] = norm_r(acc[i]); + [unroll] for (uint k = 0; k < KC; ++k) { + const v8f g = wg_load8f(g2, 32u * k), b = wg_load8f(b2, 64u * k); +#if LF_G2 + const v8f b2x = sw_add8(b, b); // 2 (x1 + b2): once for both windows +#endif + [unroll] for (uint i1 = 0; i1 < NWW; ++i1) { + v8f d; + [unroll] for (uint v = 0; v < 8; ++v) d.v[v] = acc[i1][k].v[v] * r[i1] * g.v[v]; + mf[i1][k] = pack_in(d); +#if LF_G2 + [unroll] for (uint v2 = 0; v2 < 8; ++v2) acc[i1][k].v[v2] = mad(acc[i1][k].v[v2], 2.0f, b2x.v[v2]); +#else + acc[i1][k] = sw_add8(acc[i1][k], b); +#endif + } + } + } + +#if LF_W2_ONE + [unroll] for (uint iw = 0; iw < NWW; ++iw) + [unroll] for (uint v = 0; v < 8; ++v) { + const float x = wg_xor16(acc[iw][1].v[v]); // lane t's tile 1 row v: channel 8 + v + acc[iw][0].v[v] = hh != 0u ? x : acc[iw][0].v[v]; + } + const bool w2_hi = (lane & 8u) != 0u; // fragment rows 8..15 of the remapped tile +#endif + // Steps 9-10: x2 = x1 + W2 q8(GELU(W1 m + b1)) + b2, GROUP hidden tiles of 16 at a time (both windows per group: the + // other window's chain is the independent work under each GELU). + const uint b1 = w + L_B1 + hh * 32u; + [unroll] for (uint u = 0; u < NMLP; ++u) { + const bool more = u + 1u < NMLP; + if (more) st_fetch(stage, w + L_mlp(u + 1u), MLP_BYTES / 16, tid); + [unroll] for (uint j0 = 0; j0 < HPU; j0 += GROUP) { + const uint fb = sw_lane_base(buf * MAXU, lane) + j0 * (2u * KC * 32u); + v8f hcur[NWW][GROUP]; + { + uint2 f1[GROUP][KC]; + [unroll] for (uint g = 0; g < GROUP; ++g) + [unroll] for (uint kc = 0; kc < KC; ++kc) f1[g][kc] = sw_lfrag_b(fb, g * 2u * KC + kc); + v8f bh[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) bh[g2] = wg_load8f(b1, (u * HPU + j0 + g2) * 64u); + [unroll] for (uint i = 0; i < NWW; ++i) [unroll] for (uint g1 = 0; g1 < GROUP; ++g1) hcur[i][g1] = bh[g1]; + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) + [unroll] for (uint i2 = 0; i2 < NWW; ++i2) + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hcur[i2][g3] = wg_wmma_fp8(f1[g3][kc2], mf[i2][kc2], hcur[i2][g3]); + } + uint2 f2[GROUP][KC]; + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) + [unroll] for (uint m = 0; m < KC; ++m) f2[g4][m] = sw_lfrag_b(fb, g4 * 2u * KC + KC + m); + uint2 hf[NWW][GROUP]; +#if LF_GELU == 2 + SwGeluPre gp[NWW]; + [unroll] for (uint ia = 0; ia < NWW; ++ia) gp[ia] = sw_gelu_pre(hcur[ia]); + [unroll] for (uint ib = 0; ib < NWW; ++ib) sw_gelu_fin(hcur[ib], gp[ib], hf[ib]); +#else + [unroll] for (uint ib = 0; ib < NWW; ++ib) + [unroll] for (uint gb = 0; gb < GROUP; ++gb) hf[ib][gb] = lf_gelu_q8(hcur[ib][gb]); +#endif +#if LF_W2_ONE + [unroll] for (uint g5 = 0; g5 < GROUP; ++g5) { + const uint2 t1 = uint2(wg_xor_u(f2[g5][1].x, 8u), wg_xor_u(f2[g5][1].y, 8u)); + f2[g5][0] = w2_hi ? t1 : f2[g5][0]; + } + [unroll] for (uint i6 = 0; i6 < NWW; ++i6) + [unroll] for (uint g6 = 0; g6 < GROUP; ++g6) acc[i6][0] = wg_wmma_fp8(f2[g6][0], hf[i6][g6], acc[i6][0]); +#else + [unroll] for (uint m2 = 0; m2 < KC; ++m2) + [unroll] for (uint i6 = 0; i6 < NWW; ++i6) + [unroll] for (uint g6 = 0; g6 < GROUP; ++g6) acc[i6][m2] = wg_wmma_fp8(f2[g6][m2], hf[i6][g6], acc[i6][m2]); +#endif + if (more && j0 == 0u) st_commit(stage, (buf ^ 1u) * MAXU, MLP_BYTES / 16, tid); // the other buffer is free + } + if (more) { + wg_barrier_lds(); + buf ^= 1u; + } + } + +#if SW_OUT_COEF12 + // Model L's coefficient store, one pixel per lane: lane (t, 0) takes window 0's token t, lane (t, 1) window 1's (its + // channels 0..12 from lane (t, 0): acc[1][0] = channels 0..7, acc[1][1] = 8..15 of that lane) + { + float a[13]; + const uint ch[13] = {0u, 1u, 6u, 7u, 8u, 9u, 10u, 11u, 12u, 2u, 3u, 4u, 5u}; // L_DEC_VALUES + [unroll] for (uint q = 0; q < 13u; ++q) { +#if LF_W2_ONE + // tile 0 = channels 0..7 (lane t) and 8..15 (lane t + 16): the window's own half, the other from lane t ^ 16 + const uint vq = ch[q] & 7u; + const float own = hh != 0u ? acc[1][0].v[vq] : acc[0][0].v[vq]; + const float recv = wg_xor16(hh != 0u ? acc[0][0].v[vq] : acc[1][0].v[vq]); + a[q] = ((ch[q] < 8u) == (hh == 0u)) ? own : recv; +#else + const float own = acc[0][ch[q] >> 3].v[ch[q] & 7u]; + const float other = wg_xor16(acc[1][ch[q] >> 3].v[ch[q] & 7u]); + a[q] = hh != 0u ? other : own; +#endif +#if LF_G2 + a[q] = a[q] * 0.5f; // the doubled accumulator (exact) +#endif + } + const float S = wg_ldf(coefW, 320u), T = wg_ldf(coefW, 324u); + const float S2 = S * S * 1.00034f; // the truncating FP16 pack: x (1 + 2^-11.7) has the nearest rounding's mean error + const int pr = hh != 0u ? prw[1] : prw[0], pc = hh != 0u ? pcw[1] : pcw[0]; + const bool real = (hh != 0u ? dst[1] : dst[0]) >= 0; + if (real && pr < coefRh && pc < coefRw) + lf_coef_px(a, S2, T, (uint)wg_uniform((int)coefA), (uint)wg_uniform((int)coefC), (uint)wg_uniform((int)coefL), + (uint)(pr * coefRw + pc)); + } +#else + // Output q8(x2), real window members only. + [unroll] for (uint io = 0; io < NWW; ++io) { +#if LF_G2 + [unroll] for (uint kh = 0; kh < KC; ++kh) + [unroll] for (uint vh = 0; vh < 8; ++vh) acc[io][kh].v[vh] = acc[io][kh].v[vh] * 0.5f; // exact +#endif + uint2 o[KC]; + float am = 0.0f; + [unroll] for (uint k0 = 0; k0 < KC; ++k0) am = sw_absmax8(am, acc[io][k0]); + if (sw_in448(am)) { + [unroll] for (uint k = 0; k < KC; ++k) o[k] = wg_pack_q8_nc_ags(acc[io][k]); + } else { + [unroll] for (uint k = 0; k < KC; ++k) o[k] = sw_pack_q8_v2(acc[io][k]); + } + if (dst[io] >= 0) { + const uint ob = (uint)dst[io] * SW_C + hh * HALF; + [unroll] for (uint i = 0; i < KC / 2; ++i) wg_st128(out_p, ob + 16u * i, uint4(o[2 * i], o[2 * i + 1])); + } + } +#endif +} diff --git a/clean/dx12/kernels/l_swin_c64_fast.hlsl b/clean/dx12/kernels/l_swin_c64_fast.hlsl new file mode 100644 index 00000000..cc16e768 --- /dev/null +++ b/clean/dx12/kernels/l_swin_c64_fast.hlsl @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT +// Model L's fast-mode middle Swin blocks at width 64 (runtime l_mode=fast, lever bit 8; native D3D12 only): the "_fast" +// twins of swin_block_c64_nc (enc1) and swin_block_c64_add_ex_nc (dec1, the fused expand), launched in place of them with +// the same arguments (runtime l_fast_alt). l_swin_c32_fast.hlsl's two-windows-per-wave body at C = 64 (the launch shape +// of the base kernels, swin_c64w2.hlsl: 128-lane workgroups, 8 windows per launched workgroup, 16 KB of staging) with +// its fast arithmetic: the clamped-cubic GELU (no table load, no exponential: the quick GELU of 2B-3 had 512 more +// quarter-rate exponentials than the base kernels and measured 7 to 18 us slower) and the softmax without the maximum; +// everything else is the base +// kernels' M-form chain (the same packs, norms, soft cap, fused expand and output pack). +// +// @wg-kernel swin_block_c64_nc_fast co=- block=256 group=128 gscale=1 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=0,SW_SAFE=1,SW_ECL=0,WG_LD_A16=1,LF_NAME=swin_block_c64_nc_fast,LF_GELU=1 +// @wg-kernel swin_block_c64_add_ex_nc_fast co=- block=256 group=128 gscale=1 wave=32 args=p,p,p,p,u,u,u,u,p defines=SW_C=64,SW_HEADS=2,SW_MLP=256,SW_ADD=1,SW_SAFE=1,SW_ECL=96,LF_NAME=swin_block_c64_add_ex_nc_fast,LF_GELU=1 +#include "l_swin_c32_fast.hlsl" diff --git a/clean/dx12/kernels/l_swin_c96_fast.hlsl b/clean/dx12/kernels/l_swin_c96_fast.hlsl new file mode 100644 index 00000000..da3b49b5 --- /dev/null +++ b/clean/dx12/kernels/l_swin_c96_fast.hlsl @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +// Model L's fast-mode width-96 Swin blocks (runtime l_mode=fast, lever bit 8192; native D3D12 only): the "_fast" twins of +// swin_block_c96_pm_rev_nc (enc2 with enc1's patch merge as its prologue, fused_swin.hlsl SW_PM) and +// swin_block_c96_add_ex_nc (dec2 with the fused expand), launched in place of them with the same arguments (runtime +// l_fast_alt). l_swin_c32_fast.hlsl's body in the base kernel's launch shape (256-lane workgroups, one window per wave, +// 8 windows per workgroup) with its fast arithmetic: the clamped-cubic GELU (no table load, no groupshared table: LDS +// 28 672 -> 24 576 bytes; no exponential) and the softmax without the maximum; everything else is the base kernel's +// M-form chain (the same packs, norms, soft cap, fused expand / patch merge and output pack). The patch merge (LF_PM) is +// fused_swin.hlsl's prologue (FZ_PMT 1, the fragments staged in the idle staging buffers, bit-identical merged tokens); +// its two trailing pointers (aux = the merge weights, aux2 = the merged map, not written) are appended to swin_block.hlsl's +// argument block (WG_ARGS_END redefined before it is included: x, xadd, out_p, w, H, W, ox, oy, aux, aux2 as fused_swin.hlsl). +// +// @wg-kernel swin_block_c96_pm_rev_nc_fast co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=0,SW_SAFE=1,SW_ECL=0,LF_PM=1,LF_NAME=swin_block_c96_pm_rev_nc_fast,LF_GELU=1 +// @wg-kernel swin_block_c96_add_ex_nc_fast co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=128,LF_NAME=swin_block_c96_add_ex_nc_fast,LF_GELU=1 +// swin_block.hlsl's width-96 expand kernels declare their groupshared table's offset helper (sw_gl_offs8s) whatever the +// pattern; without the table (no digit 2 here) it is never called: its constants only have to exist. +#if defined(LF_PM) && LF_PM +#include "wg_platform.hlsli" +#undef WG_ARGS_END +#define WG_ARGS_END uint aux, aux2; }; // fused_swin.hlsl's two trailing pointers of the patch-merge kernels +#define LF_PM_ARGS 1 +#endif +#define WG_GL_A 0.0f +#define WG_GL_B 0.0f +#include "l_swin_c32_fast.hlsl" diff --git a/clean/dx12/kernels/l_swin_coef_rows.hlsli b/clean/dx12/kernels/l_swin_coef_rows.hlsli new file mode 100644 index 00000000..efc1cdfe --- /dev/null +++ b/clean/dx12/kernels/l_swin_coef_rows.hlsli @@ -0,0 +1,1913 @@ +// SPDX-License-Identifier: MIT +// D3D12 ports of the Swin block kernels of clean/kernels/swin.hip as built into swin.co (default knobs: 256 lanes, one +// window per wave, WG_MLP_GROUP 2, WG_UNIT_BYTES 16384, GELU mode 2, WG_AV8 0, WG_SMAX16 0, WG_NORM_DOT4 0) - the +// template swin_block once, instantiated per +// kernel by the defines of its @wg-kernel line: +// SW_C, SW_HEADS, SW_MLP block width, heads, MLP hidden width +// SW_ADD 1: the block input is x + xadd (decoder blocks) +// SW_SAFE 1: the "_nc" kernels (inner FP8 packs without the +-448 clamp; the output pack clamps) +// SW_ECL >0: fused expand (the "_ex" kernels): x is the low-resolution map with SW_ECL channels +// SW_SRC gather source (HIP's SRC hook; plain blocks only): 0 the FP8 map at the mirrored member +// (default); 1 Model L's encoder block, an FP16 halo map [H + 4][W + 4][C] read directly at +// (pr + 2, pc + 2) (LHaloF16Src); 2 Model L's decoder block, the FP8 map with the token-grid +// mirror, sub-pixel kept (LCoarseFp8Src); 3 (D3D12 only) Model L's encoder block with +// its two input linears as the prologue: the FP8 q halo map in its 20-byte form (two +// planes [H + 4][W + 4][16], [H + 4][W + 4][4]; lev/input_encoder_q20) at the same position +// through the linears +// (hlsl/l_lin_px.hlsli), the FP16 values mode 1 reads from x2, in registers (the x2 map is +// neither written nor read) +// SW_OUT_F16 1: the output is RN16(x2) as an FP16 map [H][W][C] (Model L's decoder block, LStoreF16Epi) +// SW_OUT_COEF12 1 (with SW_OUT_F16, C = 32): instead of the FP16 map, l_coef_pack12 of it as the epilogue: +// the lane that holds a pixel's channels 0..15 (hh = 0) runs hlsl/l_coef_px.hlsli on those +// FP16 values, the bytes the map would hold, for the pixels inside the render rectangle +// HIP ISA: \dx12-m\isa\swin_block_c64_nc.s, swin_block_c96_nc.s, swin_block_c96_add_ex_nc.s. +// Every FP32 operation follows that ISA: the RMSNorm sums of squares pair as fma(a_even, a_even, a_odd * a_odd); the +// soft cap is fma(c^3, -1 / (3 cap^2), c), the max is over t * (tau log2 e) but the exponent is fma(t, tau log2 e, -max); +// the probabilities are rounded once to FP16 (v_fma_mixlo_f16 e, 1 / sum, 0); GELU tt = fma(x^2, b, a). +// +// swin_block_c64_nc: declared in swin_c64w2.hlsl (launch-shape switch: two windows per wave in 128-lane workgroups, or +// with SW_W2=0 this file's kernel in HIP's 256-lane shape) +// @wg-kernel swin_block_c96_nc co=swin.co block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=0,SW_SAFE=1,SW_ECL=0 +// @wg-kernel swin_block_c96_add_ex_nc co=swin.co block=256 wave=32 args=p,p,p,p,u,u,u,u,p defines=SW_C=96,SW_HEADS=4,SW_MLP=384,SW_ADD=1,SW_SAFE=1,SW_ECL=128 +#include "wg_platform.hlsli" +#include "wg_gelu_lut.hlsli" +// SW_HYB 1: the HYBRID block form (WG_L_FORM / WG_M_FORM = hybrid; hlsl/wg_hyb.hlsli, hlsl/hyb_block.hlsli): float32 FP8 +// chains with one FP16 rounding at each chain's end, the original's FP16 norm / softmax / GELU and its start values; +// the weights in this file's layout with the original's values (FP16 biases, g', B; plain FP8 matrices). Default 0. +#ifndef SW_HYB +#define SW_HYB 0 +#endif +#ifndef SW_Q7_CHUNK +#define SW_Q7_CHUNK 0 // 1 (with SW_HYB): per-32-channel FP16-rounded WMMA chunks (oracle mm8="exact") +#endif +#if SW_Q7_CHUNK && !SW_HYB +#error "SW_Q7_CHUNK requires SW_HYB=1" +#endif +#ifndef SW_HYB_MUT_ORDER +#define SW_HYB_MUT_ORDER 0 // check mutants only: 1 one W2 chunk pair reversed, 2 the pair of every W2 group, + // 3 the odd W2 groups in a second accumulator added at the end (one extra f32 rounding), + // 4 the W2 chain end moved by one float32 ulp before its RN16 +#endif +#ifndef SW_HYB_DUMP +#define SW_HYB_DUMP 0 // check variant only (probe kernels, l_hyb_stage_check.py): every stage's values to `dumpp` +#endif +#if SW_HYB_DUMP && !SW_HYB +#error "SW_HYB_DUMP: hybrid kernels only" +#endif +#if SW_HYB +// The hybrid kernels at every width (C = 32, 64, 96, 128) run the plain schedule (the C = 32 knob set): no scheduling +// knob of the M-form kernels, no GELU table of theirs (hyb_gelu_q8 has its own), and every output pack through +// hyb_q8_of_chain (no clamp-skip shortcut: FP8(x2) without the RN16 is not the hybrid output). Set here, before the +// defaults below; setting one of them on a kernel line stops the build (the check after this block). +#ifndef SW_GELU +#define SW_GELU 0 +#endif +#ifndef SW_CLAMP_SKIP +#define SW_CLAMP_SKIP 0 +#endif +#ifndef SW_NORM1_EARLY +#define SW_NORM1_EARLY 0 +#endif +#ifndef SW_NORM2_EARLY +#define SW_NORM2_EARLY 0 +#endif +#ifndef SW_NORM_R2 +#define SW_NORM_R2 0 +#endif +#ifndef SW_SMAX_ADDST +#define SW_SMAX_ADDST 0 +#endif +#ifndef SW_SMAX_STAGED +#define SW_SMAX_STAGED 0 +#endif +#ifndef SW_HEAD_UNROLL +#define SW_HEAD_UNROLL 0 +#endif +#ifndef SW_HEAD_PAIRS +#define SW_HEAD_PAIRS 0 +#endif +#ifndef SW_MLP_PAIRS +#define SW_MLP_PAIRS 0 +#endif +#ifndef SW_MLP_STEP +#define SW_MLP_STEP 1 +#endif +#ifndef SW_REV_PHI +#define SW_REV_PHI 0 +#endif +#ifndef SW_COMMIT_EARLY +#define SW_COMMIT_EARLY 0 +#endif +#ifndef SW_N2_BATCH +#define SW_N2_BATCH 0 +#endif +#ifndef SW_GELU_LATE0 +#define SW_GELU_LATE0 0 +#endif +#endif +// SW_ECL > 0 with SW_HYB (the hybrid decoder blocks with their expand fused in: swin_block_c96_add_ex_hyb, +// swin_block_c64_add_ex_hyb): SW_ADD only, plain FP8 (no q7c chunks), see hyb_fused_expand below +#if SW_HYB && (SW_GELU != 0 || (SW_ECL > 0 && (!SW_ADD || SW_Q7_CHUNK)) || SW_NORM_R2 || SW_SMAX_STAGED || SW_SMAX_ADDST || SW_REV_PHI || SW_CLAMP_SKIP || SW_N2_BATCH) +#error "SW_HYB: unsupported M-form knob enabled" +#endif +#if SW_HYB && SW_OUT_COEF12 && !COEF_CVT_HW +#error "SW_HYB with SW_OUT_COEF12: COEF_CVT_HW 1 (the driver's RNE conversion of the hybrid output point)" +#endif +// SW_MEGA 1 (kernels/hyb_bneck.hlsl only): the body below becomes the function sw_item(), one item (8 windows) of the +// bottleneck's persistent queue; its arguments are the queue kernel's (bneck.hlsl's), and the block's x, out_p, w, ox, +// oy are statics the queue sets per item (wg_bid_ = the item's index in its block). The input gather and the output +// store use the coherent view (the maps are written by other workgroups of the same launch). The same instructions on +// the same values otherwise: b5's bytes equal six swin_block_c128_hyb launches. +#ifndef SW_MEGA +#define SW_MEGA 0 +#endif +#if SW_MEGA && (!SW_HYB || SW_C != 128 || SW_ADD || SW_ECL > 0 || SW_SRC || SW_OUT_F16 || SW_OUT_COEF12 || SW_HYB_DUMP) +#error "SW_MEGA: the hybrid C128 bottleneck block only (plain FP8 map in and out, no dump)" +#endif + +#if SW_MEGA +WG_ARGS_BEGIN + uint a_x, a_out, a_tmp, a_sync, a_w0, a_w1, a_w2, a_w3, a_w4, a_w5; // pointers (bneck.hlsl's arguments) + int H, W, a_oxe, a_oye, a_oxo, a_oyo, a_groups; +WG_ARGS_END +static uint x, out_p, w; // the current item's block: input map, output map, weight section +static int ox, oy; // its window offsets +#else +WG_ARGS_BEGIN + uint x, xadd, out_p, w; // pointers + int H, W, ox, oy; +#if SW_ECL > 0 + uint aux; // unused by the expand kernels (null) +#endif +#if SW_OUT_COEF12 + uint coefA, coefC, coefL, coefW; // pointers: l_coef_pack12's A, C, latent and coefficient blob (out_p unused) + int coefRw, coefRh; // the render rectangle +#endif +#if SW_SRC == 3 + uint linW1, linW2; // pointers: enc0.Win1, enc0.Win2 (x = the FP8 q halo map) +#endif +#if SW_HYB_DUMP + uint dumpp; // pointer: the stage dump (HD_WORDS words per lane of every real window) +#endif +WG_ARGS_END +#endif + +// ---- BlockLayout (FORMATS.md, "Swin block section") --------------------------------------------------- +#define KC (SW_C / 16) +#define HALF (SW_C / 2) +#define MTH (SW_MLP / 16) +#define L_G1 16 +#define L_G2 (L_G1 + 4 * SW_C) +#define L_BP (L_G2 + 4 * SW_C) +#define L_B2 (L_BP + 4 * SW_C) +#define L_B1 (L_B2 + 4 * SW_C) +#define L_BIAS (L_B1 + 4 * SW_MLP) +#define L_STREAM (L_BIAS + 4 * SW_HEADS * 256) +#define QKV_FRAGS (4 * KC) +#define HEAD_BYTES ((QKV_FRAGS + 2 * KC) * 256) +// q8(GELU) of the MLP (SW_GELU), all exact (bit-identical to HIP's wg_gelu + pack_in): +// 1 = the 16 KB arena table (wg_gelu_lut.hlsli; default for C = 64: one 8-byte load per value), +// 2 = the 2 KB table in groupshared memory (wg_gelu_lds.hlsli; default for C = 96, whose kernels are VALU-issue bound +// and measured slower with the arena table), 0 = HIP's transcendental chain (gelu_group). +// Measured against the transcendental chain (warm A/B): c64 arena + 8 KB units -41 us (groupshared -33, arena with +// 16 KB units -28); c96 groupshared -12 us, c96_add_ex groupshared -11 us. +// c96 (track diet-c96, round 2): mode 3 with pattern 12212 (the first tile of every odd group by the arena table, the +// rest by the groupshared table): vector-memory gathers take a quarter of the table reads off the LDS, whose random +// 8-byte gathers are bank-conflict bound (measured in the captured stages: -2.2 us c96, -1.3 us c96_add_ex; one arena +// tile in the even groups or two arena tiles were 2 to 45 us slower). +#ifndef SW_GELU +#define SW_GELU 3 +#if SW_C == 96 && !defined(SW_GELU_PAT) +#define SW_GELU_PAT 12212 +#endif +#endif +// HPU = largest divisor of MTH not above WG_UNIT_BYTES / (2 KC 256) = 16384 / (512 KC) (HIP), except C = 64 with a GELU +// table: 4 (8 KB MLP units; the staging buffers shrink from 2 x 16 KB to 2 x 8 KB, which leaves room for the groupshared +// table under the 32 KB limit and lets more workgroups share a CU; measured: alone -23 us). Same multiplies in the same +// order. +#if defined(SW_HPU) +#define HPU SW_HPU +#elif SW_C == 64 && (SW_GELU != 0 || SW_HYB) +#define HPU 4 // MTH 16 (2 x 8 KB = 16 KB LDS -> 3-4 workgroups/CU instead of 2) +#elif SW_C == 64 +#define HPU 8 // MTH 16, limit 8 +#elif SW_C == 96 +#define HPU 4 // MTH 24, limit 5 +#elif SW_C == 128 && SW_HYB +#define HPU 4 // MTH 32, limit 4 (the hybrid bottleneck block; the M-form C = 128 blocks are bneck.hlsl) +#else +#error "SW_C: 64 or 96" +#endif +#define MLP_BYTES (2 * KC * HPU * 256) +#define NMLP (MTH / HPU) +#define MAXU (HEAD_BYTES > MLP_BYTES ? HEAD_BYTES : MLP_BYTES) +#define L_SIZE (L_STREAM + SW_HEADS * HEAD_BYTES + NMLP * MLP_BYTES) +#define L_TAIL (((L_SIZE + 255) / 256) * 256) // merge / expand weights follow the block +#ifndef SW_GROUP +#define SW_GROUP 2 // hidden tiles per MLP group (HIP WG_MLP_GROUP 2; any divisor of HPU gives the same accumulation order) +#endif +#define GROUP SW_GROUP +#define THREADS WG_BLOCK +#define PFMAX ((MAXU / 16 + THREADS - 1) / THREADS) // staged 16-byte chunks per lane, largest unit + +#define SW_LDS_BYTES (2 * MAXU) +#include "swin_common.hlsli" +#include "speed_swin.hlsli" +#include "speed_c64.hlsli" +#if SW_GELU == 3 && !defined(SW_GELU_PAT) +#define SW_GELU_PAT 13033 +#endif +// SW_GL_LDS: the kernel uses the 2 KB groupshared GELU table (SW_GELU 2, or a digit 2 in SW_GELU_PAT); otherwise no +// table fill at kernel start and no 2 KB of groupshared memory. +#if SW_GELU == 2 +#define SW_GL_LDS 1 +#elif SW_GELU == 3 +#define SW_GL_LDS ((SW_GELU_PAT / 1000) % 10 == 2 || (SW_GELU_PAT / 100) % 10 == 2 || (SW_GELU_PAT / 10) % 10 == 2 || SW_GELU_PAT % 10 == 2) +#else +#define SW_GL_LDS 0 +#endif +#if SW_GL_LDS +#if SW_C == 96 && SW_ECL > 0 +groupshared uint64_t sw_gl_tab[512]; // the GELU table (wg_gelu_lds.hlsli) and its swapped copy (b, a), filled at start +#else +groupshared uint64_t sw_gl_tab[256]; // the 2 KB GELU table (wg_gelu_lds.hlsli), filled at kernel start +#endif +#define WG_GL_GET(off) sw_q2(sw_gl_tab[(off) >> (WG_GL_SCALE == 8u ? 3u : 0u)]) +#include "wg_gelu_lds.hlsli" +#endif + +// q8(GELU) of a group of 2 hidden tiles by a table, in two parts (same operations as wg_gelu_q8_lds2 / +// wg_gelu_q8_lut): sw_gelu_pre = the offsets and the table loads, sw_gelu_fin = the fmas and the FP8 conversions. +#if SW_GELU == 2 +struct SwGeluPre { uint2 e[16]; }; +SwGeluPre sw_gelu_pre(v8f h[2]) +{ + uint o0[8], o1[8]; + wg_gl_offs8(h[0], o0); + wg_gl_offs8(h[1], o1); + SwGeluPre r; + [unroll] for (uint i = 0; i < 8; ++i) { r.e[i] = WG_GL_GET(o0[i]); r.e[8 + i] = WG_GL_GET(o1[i]); } + return r; +} +void sw_gelu_fin(v8f h[2], SwGeluPre p, out uint2 q[2]) +{ + v8f y0, y1; + [unroll] for (uint i = 0; i < 8; ++i) { + y0.v[i] = mad(h[0].v[i], asfloat(p.e[i].x), asfloat(p.e[i].y)); + y1.v[i] = mad(h[1].v[i], asfloat(p.e[8 + i].x), asfloat(p.e[8 + i].y)); + } + q[0] = wg_pack_q8_nc_ags(y0); + q[1] = wg_pack_q8_nc_ags(y1); +} +#elif SW_GELU == 3 +// c96_add_ex: the groupshared-table tiles read a swapped copy (b, a) of the entries for their odd values, so that the +// final fmas accumulate alternately into the high and the low register of the loaded pairs and the driver dual-issues +// them (same entries, same fma; measured -1.5 us in c96_add_ex, +0.4 us in c96, which keeps the single table). +#if SW_C == 96 && SW_ECL > 0 +// wg_gl_offs8 with the odd values' offsets into the swapped copy (+ 2048 bytes, the v_dot4 accumulator) +void sw_gl_offs8s(v8f h, out uint o[8]) +{ + v8f w; + [unroll] for (uint i = 0; i < 8; ++i) w.v[i] = mad(h.v[i], h.v[i], WG_GL_A); + [unroll] for (uint i1 = 0; i1 < 8; ++i1) w.v[i1] = mad(w.v[i1], h.v[i1], WG_GL_B); + const uint2 c = wg_pack_q8_nc_ags(w); + [unroll] for (uint i2 = 0; i2 < 4; ++i2) { + o[i2] = dot4add_u8packed(c.x, 8u << (8u * i2), (i2 & 1u) * 2048u); + o[4 + i2] = dot4add_u8packed(c.y, 8u << (8u * i2), (i2 & 1u) * 2048u); + } +} +#define SW_GL_SWAP 1 +#else +#define sw_gl_offs8s wg_gl_offs8 +#define SW_GL_SWAP 0 +#endif +// Mixed: tile g of the group with parity j (j0 / GROUP of the unrolled unit) by method digit (2 j + g) of SW_GELU_PAT +// (written 1abcd: a, b = tiles 0, 1 of even groups, c, d = of odd groups; 1 = arena table: vector-memory loads, +// 2 = groupshared table: LDS loads, 0 = HIP's transcendental chain: VALU + TRANS, 3 = the arena table with the cheaper +// offsets of sw_gelu_fetch8_bn: about 32 issue slots per tile against 40 for the groupshared table, whose +// dot4 + mask offsets cost two operations per value). Every method gives HIP's bytes; +// mixing spreads the work over the units instead of queueing it all on one. c64: 10022 (the first group of every unit, +// whose W1 is not overlapped, by the transcendental chain, the second by the groupshared table) measured -12.6 us +// against the arena table alone (10012 -11.1, 10021 -9.8, 10011 -8.4; patterns that raised the VGPRs above 120 lost +// a workgroup per CU and were slower). With SW_GELU_LATE0 (below): 10222 (only tile 0 of the even groups by the chain) +// -4.4 us against 10022 (12022 -2.9, 10202 +1.1; all-table 12222 needs 140 VGPRs). Tile digits generalize to GROUP 1 +// (digit = the tile's index in its unit; measured slower: +8..+19 us). Round 2 (stage A/B on a capture whose arena +// holds the table): 10333 -5.0 us against 10222 (13333 / 10033 / 13033 need more than 120 VGPRs or were slower). +// Round 3 (without the unused groupshared table, see SW_GL_LDS): 13033 -1.3 us against 10333 (117 VGPRs; 10303 +4.4, +// 13333 / 13330 142 VGPRs, 12333 and the patterns with a groupshared tile 144 VGPRs or +1.4..+4.3 us). +static uint sw_gj = 0; // parity of the current group (set by the MLP loop; a compile-time constant after unrolling) +uint sw_gelu_m(uint g) +{ + const uint ix = (sw_gj * GROUP + g) & 3u; // the tile's index in its unit of 4 + return (SW_GELU_PAT / (ix == 0u ? 1000u : ix == 1u ? 100u : ix == 2u ? 10u : 1u)) % 10u; +} +struct SwGeluPre { uint2 e[GROUP][8]; }; +#ifndef TT_GELU +#define TT_GELU 0 +#endif +SwGeluPre sw_gelu_pre(v8f h[GROUP]) +{ + SwGeluPre r; +#if TT_GELU + [unroll] for (uint g0 = 0; g0 < GROUP; ++g0) [unroll] for (uint i0 = 0; i0 < 8; ++i0) r.e[g0][i0] = uint2(0, 0); + return r; +#endif + [unroll] for (uint g = 0; g < GROUP; ++g) { + if (sw_gelu_m(g) == 1u) { + const wg_gelu_lut_e a = wg_gelu_lut_fetch8(h[g]); + [unroll] for (uint i = 0; i < 8; ++i) r.e[g][i] = a.e[i]; + } else if (sw_gelu_m(g) == 3u) { + const wg_gelu_lut_e a = sw_gelu_fetch8_bn(h[g]); + [unroll] for (uint i = 0; i < 8; ++i) r.e[g][i] = a.e[i]; +#if SW_GL_LDS + } else if (sw_gelu_m(g) == 2u) { + uint o[8]; + sw_gl_offs8s(h[g], o); + [unroll] for (uint i = 0; i < 8; ++i) r.e[g][i] = WG_GL_GET(o[i]); +#endif + } else { + [unroll] for (uint i = 0; i < 8; ++i) r.e[g][i] = uint2(0, 0); + } + } + return r; +} +void sw_gelu_fin(v8f h[GROUP], SwGeluPre p, out uint2 q[GROUP]) +{ +#if TT_GELU == 3 + [unroll] for (uint g0 = 0; g0 < GROUP; ++g0) { + const uint2 c = wg_pack_q8_nc_ags(h[g0]); // the 8 codes + uint b[8]; + [unroll] for (uint i0 = 0; i0 < 4; ++i0) { + b[i0] = wg_mem.Load(x + ((c.x >> (8u * i0)) & 255u) * 4u); + b[4 + i0] = wg_mem.Load(x + ((c.y >> (8u * i0)) & 255u) * 4u); + } + q[g0] = uint2((b[0] & 255u) | ((b[1] & 255u) << 8) | ((b[2] & 255u) << 16) | (b[3] << 24), + (b[4] & 255u) | ((b[5] & 255u) << 8) | ((b[6] & 255u) << 16) | (b[7] << 24)); + } + return; +#elif TT_GELU == 4 + [unroll] for (uint g0 = 0; g0 < GROUP; ++g0) { + const uint2 c = wg_pack_q8_nc_ags(h[g0]); + const uint b0 = wg_mem.Load(x + (c.x & 65535u) * 4u), b1 = wg_mem.Load(x + (c.x >> 16) * 4u); + const uint b2 = wg_mem.Load(x + (c.y & 65535u) * 4u), b3 = wg_mem.Load(x + (c.y >> 16) * 4u); + q[g0] = uint2((b0 & 65535u) | (b1 << 16), (b2 & 65535u) | (b3 << 16)); + } + return; +#endif + [unroll] for (uint g = 0; g < GROUP; ++g) { + v8f y; + if (sw_gelu_m(g) != 0u) { + [unroll] for (uint i = 0; i < 8; ++i) { + const uint2 e = (SW_GL_SWAP && sw_gelu_m(g) == 2u && (i & 1u)) ? p.e[g][i].yx : p.e[g][i]; + y.v[i] = mad(h[g].v[i], asfloat(e.x), asfloat(e.y)); + } + } else { + float t[8]; + [unroll] for (uint i = 0; i < 8; ++i) t[i] = h[g].v[i] * h[g].v[i]; + [unroll] for (uint i1 = 0; i1 < 8; ++i1) t[i1] = mad(t[i1], asfloat(0xbdcd6502u), asfloat(0xc013b8edu)); + [unroll] for (uint i2 = 0; i2 < 8; ++i2) t[i2] = h[g].v[i2] * t[i2]; + [unroll] for (uint i3 = 0; i3 < 8; ++i3) t[i3] = wg_exp2(t[i3]); + [unroll] for (uint i4 = 0; i4 < 8; ++i4) t[i4] = 1.0f + t[i4]; + [unroll] for (uint i5 = 0; i5 < 8; ++i5) t[i5] = wg_rcp(t[i5]); + [unroll] for (uint i6 = 0; i6 < 8; ++i6) y.v[i6] = h[g].v[i6] * t[i6]; + } + q[g] = wg_pack_q8_nc_ags(y); + } +} +#elif SW_GELU == 1 +struct SwGeluPre { wg_gelu_lut_e e[GROUP]; }; +SwGeluPre sw_gelu_pre(v8f h[GROUP]) +{ + SwGeluPre r; + [unroll] for (uint g = 0; g < GROUP; ++g) r.e[g] = wg_gelu_lut_fetch8(h[g]); + return r; +} +void sw_gelu_fin(v8f h[GROUP], SwGeluPre p, out uint2 q[GROUP]) +{ + [unroll] for (uint g = 0; g < GROUP; ++g) q[g] = wg_gelu_lut_finish8(h[g], p.e[g]); +} +#endif +// SW_GELU_EARLY 1: with a table, the table loads of group j0 are issued before W1 of group j0 + GROUP (their latency +// under the multiplies), the fmas and conversions after; 0: the whole lookup after W1 of the next group (measured with +// all three kernels: 0 is about 20 us per frame slower). +// SW_SMAX_MIX 1: the softmax probabilities through the driver's folded v_fma_mixlo_f16 (HIP's instruction); 0: the FP32 +// round-to-odd emulation followed by the RNE conversion. +#ifndef SW_SMAX_MIX +#define SW_SMAX_MIX 1 +#endif +// SW_NORM1_EARLY / SW_NORM2_EARLY 1: the RMSNorm gamma / beta loads issued before the barrier ahead of the norm (the +// first barrier / the last head's) instead of in the norm; measured per kernel (c64 norm1 -1.4 us, norm2 +2.9; c96 +// norm2 -1.5, norm1 +2.1; c96_add_ex neither). +#ifndef SW_NORM1_EARLY +#define SW_NORM1_EARLY (SW_C == 64) +#endif +#ifndef SW_NORM2_EARLY +#define SW_NORM2_EARLY (SW_C == 96 && SW_ECL == 0) +#endif +// SW_CLAMP_SKIP 1: the output packs skip the +-448 clamp when the whole wave is inside it (sw_in448; exact either way). +#ifndef SW_CLAMP_SKIP +#define SW_CLAMP_SKIP 1 +#endif +#ifndef SW_GELU_EARLY +#define SW_GELU_EARLY 1 +#endif +// SW_GELU_LATE0 bit 0 / 1: the even / odd groups' table loads issued after W1 of the next group instead of before it +// (fewer registers in flight: c64 with SW_GELU_PAT 10222 stays at 120 VGPRs). +#ifndef SW_GELU_LATE0 +#define SW_GELU_LATE0 (SW_C == 64 ? 1 : 0) +#endif +// SW_MLP_STEP n: the MLP loop runs n units per pass (NMLP % n == 0); c64: 2 (2 passes of 2 units, -4.4 us). +// SW_REV_PHI 1: the MLP loop carries the residual accumulator with each fragment's 8 values in reverse order +// (sw_perm8: a renaming, the same values). The driver's register allocator gave the loop-carried values descending +// registers, so every W2 chain copied its accumulator into an ascending tuple and the back edge copied it back; +// reversed (with SW_MLP_STEP 2) -2.8 us more. Fully unrolled loops: no copies, but 140 VGPRs (one workgroup less per +// CU), slower. +// SW_COMMIT_EARLY g > 0: the next MLP unit's staging stores after group g - 1 of the unit instead of at its end (the +// other buffer is free for the whole unit: every wave passed the previous unit's barrier after its last read of it; +// the barrier stays at the end of the unit). c64: 1, -1.3 us. +#ifndef SW_MLP_STEP +#define SW_MLP_STEP (SW_C == 64 ? 2 : 1) +#endif +#ifndef SW_REV_PHI +#define SW_REV_PHI (SW_C == 64 ? 1 : 0) +#endif +#ifndef SW_COMMIT_EARLY +#define SW_COMMIT_EARLY (SW_C == 64 ? 1 : 0) +#endif +// SW_HEAD_UNROLL 1: the head loop unrolled (no loop-carried accumulator copies; each head's staging with constant +// sizes). c64 with SW_GELU_PAT 10333: -4.1 us (at 120 VGPRs). +// SW_N2_BATCH n > 0: norm2's gamma2 / beta2 loads n k at a time: the next batch's bases depend (by an opaque zero) on +// the previous batch's last FP8 pack, so the driver cannot hoist all of them at once (same values; fewer registers +// live at norm2, fewer moves into the MLP loop). c64 with the two above: 1, -2.4 us. +// Round 3 knobs (c64, stage A/B on the cap-a2 capture; the driver's register allocation decides most of them): +// SW_NORM_R2 bit 0 / 1 (norm1 / norm2): the odd values of every fragment multiplied by an opaque copy of r (same value): +// all 32 products by r read one VGPR, which a dual-issue pair cannot read twice; two copies let them pair. -50 issue +// slots, but outside the MLP loop a slot is worth about 0.03 us (inside about 0.09): 3 = -1.6 us on the old base; +// with SW_GL_LDS 0 it moved the loop's register allocation (+20 loop slots), not kept. +// SW_SMAX_ADDST 1: the soft cap's 8 bias additions as their own stage (they pair; same operations): c64 -0.9 us. +// SW_MLP_STEP NMLP: the MLP loop fully unrolled (no loop-carried copies: 1293 issue slots against 1439, but 140 VGPRs, +// +9.6 us). SW_MLP_DEP 1 / 2 / 3: the next units' loads (1), also the LDS fragment bases and staging commits per group +// (2) or per unit (3), through an opaque zero from the latest GELU pack (no hoisting across units): 131-144 VGPRs, +// +12..+19 us. SW_STAGE_LATE g > 0: the next MLP unit's staging loads after group g - 1's GELU (address through its +// pack; commit with SW_COMMIT_EARLY > g - 1): no VGPR gain. SW_F2_LATE bit 0 / 1: the even / odd groups' W2 fragments +// loaded after their GELU: 117-118 VGPRs but +0.2..+5.4 us (loop version), 137 VGPRs (unrolled). +#ifndef SW_F2_LATE +#define SW_F2_LATE 0 +#endif +#ifndef SW_STAGE_LATE +#define SW_STAGE_LATE 0 +#endif +#ifndef SW_MLP_DEP +#define SW_MLP_DEP 0 +#endif +#ifndef SW_NORM_R2 +#define SW_NORM_R2 0 +#endif +#ifndef SW_SMAX_ADDST +#define SW_SMAX_ADDST (SW_C == 64) +#endif +#ifndef SW_HEAD_UNROLL +#define SW_HEAD_UNROLL (SW_C == 64) +#endif +#ifndef SW_N2_BATCH +#define SW_N2_BATCH (SW_C == 64 ? 1 : 0) +#endif +// SW_HEAD_PAIRS / SW_MLP_PAIRS 1: the head / MLP loop runs pairs (MLP: triples, NMLP 6 = two iterations; round 2: +// -1.6 us c96_add_ex against pairs) of iterations (SW_HEADS even, NMLP a multiple of 3): fewer +// back-edges, at each of which the driver copies the residual accumulators it left outside their loop registers +// (same operations in the same order). Measured per kernel (c96: MLP pairs -1.4 us, both -0.9..-1.2; c96_add_ex: +// both -2.4 us, MLP only -1.0, heads only +0.8). +#ifndef SW_HEAD_PAIRS +#define SW_HEAD_PAIRS (SW_C == 96 && SW_ECL > 0) +#endif +#ifndef SW_MLP_PAIRS +#define SW_MLP_PAIRS (SW_C == 96) +#endif +// SW_SMAX_STAGED 1 (c96): the bias add as its own stage before the clamp (dual-issued adds), and the exponent argument +// fma(t, k, nmx) with nmx = RN(max * -k) = -RN(max * k) (round to nearest is symmetric; one multiply, no negation +// modifier on the eight fmas). Same values. +#ifndef SW_SMAX_STAGED +#define SW_SMAX_STAGED (SW_C == 96) +#endif +#if SW_HEAD_PAIRS && SW_HEADS % 2 != 0 +#error "SW_HEAD_PAIRS: SW_HEADS must be even" +#endif +#if SW_MLP_PAIRS && NMLP % 3 != 0 +#error "SW_MLP_PAIRS: NMLP must be a multiple of 3" +#endif + +uint L_head(uint hd) { return L_STREAM + hd * HEAD_BYTES; } +uint L_mlp(uint u) { return L_STREAM + SW_HEADS * HEAD_BYTES + u * MLP_BYTES; } + +// Inner FP8 pack (HIP pack_in) with the driver conversion (wave-uniform control flow); the output pack is sw_pack_q8. +uint2 pack_in(v8f d) +{ +#if SW_HYB + return wg_pack_q8_ags(d); +#elif SW_SAFE + return wg_pack_q8_nc_ags(d); +#else + return wg_pack_q8_inner_ags(d); +#endif +} + +#if SW_HYB +#include "wg_hyb.hlsli" +// a zero the compiler cannot prove (the grid height is never negative): hyb_block.hlsli's contraction barrier. +// HYB_SCAN_MUTANT=1 (the fused-square scan's mutant, *_scanmut, never in a model build): a literal zero, i.e. the +// barrier removed; build_dx12.py requires the scan to FAIL on it +#if HYB_SCAN_MUTANT +#define HYB_OPAQUE0 0u +#else +// the unknown bit in BOTH FP16 halves (bits 0 and 16): with bit 0 only, the compiler proved the high half untouched +// and fused it (v_and_or_b32 on the low half, v_fma_f16 on .h) +#define HYB_OPAQUE0 (((uint)H >> 31u) * 0x10001u) +#endif +#include "hyb_block.hlsli" +#endif +#if SW_HYB_DUMP +// Stage dump (l_hyb_stage_check.py): per real window and lane, HD_WORDS 32-bit words, every value in the lane's own +// register layout (float32 bits; P as its packed FP16 words). Fields: X the block input (after the skip add), Y1 norm1's +// output; per head (60 words): UQ RN16 of the q/k chain (2 tiles), V RN16 of the v chain (2 tiles), S RN16 of the score +// chain, P (4 words), O RN16 of the P V chain (2 tiles); Z RN16 of the Wp chain, Y2 norm2's output, H RN16 of the W1 +// chains (MTH tiles), OUT RN16 of the W2 chain (the block output before its FP8 / FP16 point). Only values the kernel +// computes anyway; the stores are its only addition. +#define HD_HEAD (16u * KC) +#define HD_Z (HD_HEAD + 60u * SW_HEADS) +#define HD_Y2 (HD_Z + 8u * KC) +#define HD_H (HD_Y2 + 8u * KC) +#define HD_OUT (HD_H + 8u * MTH) +#define HD_WORDS (HD_OUT + 8u * KC) +static uint hd_base; +static bool hd_on; +void hd_st4(uint word, uint4 a) { if (hd_on) wg_st128(dumpp, (hd_base + word) * 4u, a); } +void hd_st8(uint word, v8f a) +{ + hd_st4(word, uint4(asuint(a.v[0]), asuint(a.v[1]), asuint(a.v[2]), asuint(a.v[3]))); + hd_st4(word + 4u, uint4(asuint(a.v[4]), asuint(a.v[5]), asuint(a.v[6]), asuint(a.v[7]))); +} +#define HD_ST8(word, a) hd_st8(word, a) +#define HD_ST4(word, a) hd_st4(word, a) +#else +#define HD_ST8(word, a) +#define HD_ST4(word, a) +#endif + +// ---- Stager: global -> registers (fetch) -> LDS (commit), `chunks` 16-byte chunks (a compile-time +// constant at every call, so the row tests fold): lane tid moves chunks tid, tid + THREADS, ...; in a partial last row the +// lanes past the end re-load / re-store the unit's last chunk (same value: no per-lane branch). +struct Stager { uint4 pre[PFMAX]; }; +void st_fetch(inout Stager s, uint src, uint chunks, uint tid) +{ + [unroll] for (uint i = 0; i < PFMAX; ++i) { + if (i * THREADS >= chunks) break; + uint idx = tid + i * THREADS; + if ((i + 1u) * THREADS > chunks) idx = min(idx, chunks - 1u); + s.pre[i] = wg_ld128(src, idx * 16u); + } +} +void st_commit(Stager s, uint dst, uint chunks, uint tid) +{ + const uint base = (dst >> 3) + (tid + sw_zero_bits()) * 2u; // element of chunk tid (sw_zero_bits: see sw_lane_base) + [unroll] for (uint i = 0; i < PFMAX; ++i) { + if (i * THREADS >= chunks) break; + if ((i + 1u) * THREADS > chunks) { + sw_lds_st128(dst + min(tid + i * THREADS, chunks - 1u) * 16u, s.pre[i]); + } else { + SW_LDS_PUT(base + i * THREADS * 2u, s.pre[i].xy); + SW_LDS_PUT(base + i * THREADS * 2u + 1u, s.pre[i].zw); + } + } +} + +void load_frags_g(uint base, uint off, out uint2 f[KC]) +{ + [unroll] for (uint i = 0; i < KC / 2; ++i) { +#if SW_MEGA + uint4 v = wg_mem_gc.Load4(base + off + 16u * i); // written by other workgroups of this launch +#else + uint4 v = wg_ld128(base, off + 16u * i); +#endif + f[2 * i] = v.xy; f[2 * i + 1] = v.zw; + } +} + +#ifndef SW_SRC +#define SW_SRC 0 +#endif +#ifndef SW_OUT_F16 +#define SW_OUT_F16 0 +#endif +#if (SW_SRC != 0 || (SW_OUT_F16 && !SW_HYB)) && (SW_ADD || SW_ECL > 0) +#error "SW_SRC / SW_OUT_F16: plain blocks only (the hybrid C32 decoder: SW_OUT_F16 with SW_ADD, the skip)" +#endif +#ifndef SW_OUT_COEF12 +#define SW_OUT_COEF12 0 +#endif +#if SW_OUT_COEF12 +#if !SW_OUT_F16 || SW_C != 32 +#error "SW_OUT_COEF12: Model L's decoder block only (SW_OUT_F16, C = 32)" +#endif +#define COEF_PACK12 1 +#include "l_coef_px.hlsli" +#endif +// SW_COEF_ROWS 1 (the hybrid C32 decoder with the coefficient epilogue): the epilogue reads channels 0..15 only, so the +// W2 chain runs one 16-row tile instead of two: rows 0..7 = channels 0..7 (tile 0's rows 0..7, the hh = 0 lanes), rows +// 8..15 = channels 8..15 (tile 1's rows 0..7: the A fragment's lanes t >= 8 read 24 LDS slots further, no repack; the +// hh = 1 lanes), in place of channels 16..23 and with channels 24..31 dropped. Each output element is the same chain of +// the same products from the same start (RN16(b2 + z) moved to the hh = 1 lane), so the same bytes; the epilogue takes +// channels 8..15 back from lane ^ 16. +#ifndef SW_COEF_ROWS +#define SW_COEF_ROWS 0 +#endif +#if SW_COEF_ROWS && (!SW_OUT_COEF12 || !SW_HYB || SW_C != 32 || SW_Q7_CHUNK || SW_HYB_MUT_ORDER || SW_HYB_DUMP || SW_REV_PHI) +#error "SW_COEF_ROWS: the plain hybrid C32 decoder block with SW_OUT_COEF12 only" +#endif +#if SW_OUT_COEF12 +#endif +#if SW_SRC == 1 +// LHaloF16Src: the lane's channels hh * C/2 + 8 k + j of the member at grid position (pr, pc) (inside the 2-pixel halo), +// from the FP16 map [H + 4][W + 4][C] +void sw_load_halo_f16(uint base, int pr, int pc, int W, uint hh, out v8f f[KC]) +{ + const uint off = (uint)(((pr + 2) * (W + 4) + pc + 2) * SW_C) * 2u + hh * SW_C; + [unroll] for (uint k = 0; k < KC; ++k) { + const uint4 q = wg_ld128(base, off + 16u * k); + f[k].v[0] = wg_h2f_lo(q.x); f[k].v[1] = wg_h2f_hi(q.x); f[k].v[2] = wg_h2f_lo(q.y); f[k].v[3] = wg_h2f_hi(q.y); + f[k].v[4] = wg_h2f_lo(q.z); f[k].v[5] = wg_h2f_hi(q.z); f[k].v[6] = wg_h2f_lo(q.w); f[k].v[7] = wg_h2f_hi(q.w); + } +} +#elif SW_SRC == 3 +#if SW_C != 32 +#error "SW_SRC 3: Model L's encoder block (C = 32)" +#endif +#include "l_lin_px.hlsli" +// LHaloLinSrc: the values of LHaloF16Src without the x2 map: the member at grid position (pr, pc) is pixel +// (pr + 2) (W + 4) + pc + 2 of the FP8 q halo map, through l_linear_32_32_fused's arithmetic (lane (t, h) = that +// kernel's lane of the pixel; every lane runs it, also for outside members: wave-uniform control flow). The map's +// 20-byte form (two planes): lane half h = 0 loads bytes 0..15 from the first plane, h = 1 bytes 16..19 from the +// second and takes zeros for 20..31 (the 32-byte form's zero bytes): the same fragments as from the 32-byte map. +void sw_load_halo_lin(uint base, int pr, int pc, int W, uint lane, uint hh, out v8f f[KC]) +{ + const uint pix = (uint)((pr + 2) * (W + 4) + pc + 2); + uint2 xq[2]; + const uint plane1 = (uint)((H + 4) * (W + 4)) * 16u; + if (hh != 0u) { + xq[0] = uint2(wg_ld32(base, plane1 + pix * 4u), 0u); + xq[1] = uint2(0u, 0u); + } else { + const uint4 v = wg_ld128(base, pix * 16u); + xq[0] = v.xy; + xq[1] = v.zw; + } + v8f b1[2], b2[2]; + uint2 f1[2][2], f2[2][2]; + lin_blob(linW1, lane, hh, b1, f1); + lin_blob(linW2, lane, hh, b2, f2); +#if defined(TT_LINF32) && TT_LINF32 + { // no FP16 rounding points: x1 = q8(relu(acc)), x2 = acc (FP32) + uint2 x1[2]; + [unroll] for (uint m1 = 0; m1 < 2u; ++m1) { + v8f r = lin_acc(b1[m1], f1[m1], xq); + [unroll] for (uint j = 0; j < 8u; ++j) r.v[j] = wg_fmax(r.v[j], 0.0f); + x1[m1] = wg_pack_q8_ags(r); + } + [unroll] for (uint k8 = 0; k8 < KC; ++k8) f[k8] = lin_acc(b2[k8], f2[k8], x1); + return; + } +#endif + uint4 y[2]; + lin_pair(xq, b1, f1, b2, f2, y); + [unroll] for (uint k = 0; k < KC; ++k) { + f[k].v[0] = wg_h2f_lo(y[k].x); f[k].v[1] = wg_h2f_hi(y[k].x); f[k].v[2] = wg_h2f_lo(y[k].y); f[k].v[3] = wg_h2f_hi(y[k].y); + f[k].v[4] = wg_h2f_lo(y[k].z); f[k].v[5] = wg_h2f_hi(y[k].z); f[k].v[6] = wg_h2f_lo(y[k].w); f[k].v[7] = wg_h2f_hi(y[k].w); + } +} +#elif SW_SRC == 2 || (SW_HYB && SW_ADD) +// LCoarseFp8Src: a member outside the grid takes the mirrored 2 x 2 group (mirror of the group index) and keeps its +// sub-pixel; the byte offset of the lane's half of that pixel (also the hybrid decoder blocks' expanded map E: the +// table's shared_dec_border "coarse"; their skip map S keeps the fine mirror) +uint sw_coarse_src(int pr, int pc, int H, int W, uint hh) +{ + const int r = 2 * sw_mirror(pr >> 1, H >> 1) + (pr & 1), c = 2 * sw_mirror(pc >> 1, W >> 1) + (pc & 1); + return (uint)(r * W + c) * SW_C + hh * HALF; +} +#endif + +// sum of squares of a token's channels in this lane (k = 0 .. KC - 1, in order), the other half of the wave added +float norm_r(v8f a[KC]) +{ + float ss = sw_sumsq8(a[0]); + [unroll] for (uint k = 1; k < KC; ++k) ss = ss + sw_sumsq8(a[k]); + ss = ss + wg_xor16(ss); +#if SW_C == 64 + return wg_rsq((ss + asfloat(0x39000000u)) * asfloat(0x3c800000u)); // (ss + 2^-13) * (1 / 64) +#elif SW_C == 32 + return wg_rsq((ss + asfloat(0x39000000u)) * asfloat(0x3d000000u)); // (ss + 2^-13) * (1 / 32) (Model L, #89) +#else + return wg_rsq((ss + asfloat(0x39000000u)) * asfloat(0x3c2aaaabu)); // (ss + 2^-13) * (1 / 96) +#endif +} + +// GELU mode 2 of GROUP = 2 tiles: x / (1 + 2^(x (b x^2 + a))), with HIP's fma(x^2, b, a) +void gelu_group(v8f h[2], out v8f y[2]) +{ + float t[16]; + [unroll] for (uint i = 0; i < 16; ++i) t[i] = h[i >> 3].v[i & 7] * h[i >> 3].v[i & 7]; + [unroll] for (uint i1 = 0; i1 < 16; ++i1) t[i1] = mad(t[i1], asfloat(0xbdcd6502u), asfloat(0xc013b8edu)); // -0.10029031, -2.30816186 + [unroll] for (uint i2 = 0; i2 < 16; ++i2) t[i2] = h[i2 >> 3].v[i2 & 7] * t[i2]; + [unroll] for (uint i3 = 0; i3 < 16; ++i3) t[i3] = wg_exp2(t[i3]); + [unroll] for (uint i4 = 0; i4 < 16; ++i4) t[i4] = 1.0f + t[i4]; + [unroll] for (uint i5 = 0; i5 < 16; ++i5) t[i5] = wg_rcp(t[i5]); + [unroll] for (uint i6 = 0; i6 < 16; ++i6) y[i6 >> 3].v[i6 & 7] = h[i6 >> 3].v[i6 & 7] * t[i6]; +} + +#if SW_ECL > 0 +// HIP wg_low0: smallest low-resolution coordinate any of the 4 window rows / columns from p0 maps to. +int wg_low0(int p0, int n) +{ + int m = sw_mirror(p0, n); + int m1 = sw_mirror(p0 + 1, n), m2 = sw_mirror(p0 + 2, n), m3 = sw_mirror(p0 + 3, n); + m = m1 < m ? m1 : m; + m = m2 < m ? m2 : m; + m = m3 < m ? m3 : m; + return m >> 1; +} + +#define EKC (SW_ECL / 16) +#define FE_NW (THREADS / 32) // waves per workgroup (8; 4 in swin_c64w2.hlsl's 128-lane form) +#if (4 * SW_C / 16) % FE_NW != 0 +#error "fused_expand: MT = 4 C / 16 must be a multiple of the waves" +#endif +// HIP fused_expand: the 8 windows' expanded block input e = q8(We y + be) into LDS records +// [window][low token][sub-pixel][C] at e_lds. tail = expand weights (bias [4C] f32, then the fragments, in global memory). +#include "diet_c96.hlsli" +// lowp: sw_win_low0 of this lane (the 8 windows' low-resolution bases, computed once per lane instead of per lane and +// window pair; the same integers) +void fused_expand(uint tail, uint e_lds, int nwx, int nwin, uint tid, int blk, uint lowp) +{ + const uint G = SW_C / 16, MT = 4 * G, WE = 16 * SW_C; // MT % 8 == 0 (C = 96) + uint lane = tid & 31u, t = lane & 15u, hh = lane >> 4, wave = tid >> 5; + int Hl = H >> 1, Wl = W >> 1; + uint2 yf[2][EKC]; + [unroll] for (int n = 0; n < 2; ++n) { + const uint lp = WaveReadLaneAt(lowp, 4u * (uint)n + (t >> 2)); // window blk * 8 + 4 n + (t >> 2) + int lr = (int)(lp & 0xffffu) + (int)((t >> 1) & 1u), lc = (int)(lp >> 16) + (int)(t & 1u); + lr = lr < Hl ? lr : Hl - 1; + lc = lc < Wl ? lc : Wl - 1; + uint off = (uint)(lr * Wl + lc) * SW_ECL + hh * (SW_ECL / 2); + [unroll] for (uint i = 0; i < EKC / 2; ++i) { + uint4 v = wg_ld128(x, off + 16u * i); + yf[n][2 * i] = v.xy; yf[n][2 * i + 1] = v.zw; + } + } + uint be = tail + hh * 32u; + // MT = 24 = 3 x 8 waves: every wave runs exactly MT / FE_NW tiles, unrolled with all weight fragments and biases + // issued first (one exposed global latency instead of one per tile) + const uint wv = (uint)wg_uniform((int)wave); + uint2 fa[MT / FE_NW][EKC]; + v8f ba[MT / FE_NW]; + const uint fwb = tail + WE + wv * (EKC * 256u) + (lane * 8u + sw_zero_bits()); + [unroll] for (uint it = 0; it < MT / FE_NW; ++it) { + const uint mt = wv + FE_NW * it; + [unroll] for (uint kc = 0; kc < EKC; ++kc) fa[it][kc] = wg_ld64(fwb, (FE_NW * it * EKC + kc) * 256u); + ba[it] = wg_load8f(be, mt * 64u); + } + [unroll] for (uint it2 = 0; it2 < MT / FE_NW; ++it2) { + const uint mt = wv + FE_NW * it2; + uint k = mt / G, g = mt - k * G; + v8f acc0 = ba[it2], acc1 = ba[it2]; + [unroll] for (uint kc2 = 0; kc2 < EKC; ++kc2) { + acc0 = wg_wmma_fp8(fa[it2][kc2], yf[0][kc2], acc0); + acc1 = wg_wmma_fp8(fa[it2][kc2], yf[1][kc2], acc1); + } + uint2 q0, q1; +#if SW_HYB + // the hybrid expand's FP8 point (expand_c96_hyb / expand_c128_hyb): E = FP8(RN16(be + We y)), hyb_q8_of_chain + q0 = hyb_q8_of_chain(acc0); q1 = hyb_q8_of_chain(acc1); +#else +#if SW_CLAMP_SKIP + if (sw_in448(sw_absmax8(sw_absmax8(0.0f, acc0), acc1))) { + q0 = wg_pack_q8_nc_ags(acc0); q1 = wg_pack_q8_nc_ags(acc1); + } else +#endif + { + q0 = sw_pack_q8_v2(acc0); q1 = sw_pack_q8_v2(acc1); + } +#endif + uint slot0 = (0u + (t >> 2)) * 16u + (t & 3u) * 4u + k, slot1 = (4u + (t >> 2)) * 16u + (t & 3u) * 4u + k; + sw_lds_st64(e_lds + slot0 * SW_C + hh * (SW_C / 2) + 8u * g, q0); + sw_lds_st64(e_lds + slot1 * SW_C + hh * (SW_C / 2) + 8u * g, q1); + } +} +#endif + +#if SW_ECL > 0 && SW_HYB +// hyb_fused_expand (SW_HYB with SW_ECL): the hybrid decoder blocks read their expanded input E (the coarse mirror of the +// table's shared_dec_border, sw_coarse_src: the 2 x 2 group index mirrored, the sub-pixel kept) from the records the +// fused expand wrote, so a window's records cover the mirrored groups of its rows / columns (p0 even: the groups +// p0 / 2 and p0 / 2 + 1, whose mirrors are adjacent). sw_low0c(p0, n) = the smaller of the two mirrored groups of the +// window's first row / column p0 = 4 w - o of a map of n pixels (o even: the fused launches' offsets); sw_win_low0c = +// diet_c96.hlsli's sw_win_low0 with it (row base | column base << 16). +int sw_low0c(int p0, int n) +{ + const int g = p0 >> 1, nc = n >> 1; + return min(sw_mirror(g, nc), sw_mirror(g + 1, nc)); +} +uint sw_win_low0c(int nwx, int nwin, uint lane, int blk) +{ + int win = blk * 8 + (int)(lane & 7u); + win = win < nwin ? win : nwin - 1; + const int wy = win / nwx, wx = win - wy * nwx; + return (uint)sw_low0c(4 * wy - oy, H) | ((uint)sw_low0c(4 * wx - ox, W) << 16); +} +#define SW_WIN_LOW0 sw_win_low0c +#else +#define SW_WIN_LOW0 sw_win_low0 +#endif + +#if SW_ECL > 0 +#define SW_ENTRY swin_block_c96_add_ex_nc +#elif SW_C == 64 +#define SW_ENTRY swin_block_c64_nc +#else +#define SW_ENTRY swin_block_c96_nc +#endif +#ifdef SW_ENTRY_OVERRIDE // swin_c64w2.hlsl: its own kernel has the name; this one is renamed (and not compiled) +#undef SW_ENTRY +#define SW_ENTRY SW_ENTRY_OVERRIDE +#endif + +#if SW_MEGA +// the body's global stores (its output map, read by other workgroups of this launch) through the coherent view +#define wg_st128(b, o, v) wg_mem_gc.Store4((b) + (o), (v)) +void sw_item() // one queue item (hyb_bneck.hlsl): the block on windows 8 wg_bid_ .. + 7 of the current block +#else +WG_KERNEL(SW_ENTRY) +#endif +{ +#if !SW_MEGA + WG_SETUP(); +#endif + const uint tid = wg_lane_id(); + const uint lane = tid & 31u, t = lane & 15u, hh = lane >> 4; + const int nwx = (W + ox + 3) >> 2, nwy = (H + oy + 3) >> 2, nwin = nwx * nwy; + const uint wave_id = (uint)wg_uniform((int)(tid >> 5)); + const int win0 = (int)(wg_block_id() * (THREADS / 32) + wave_id); +#if SW_HYB_DUMP + hd_on = win0 < nwin; + hd_base = ((uint)win0 * 32u + lane) * HD_WORDS; +#endif + + Stager stage; + st_fetch(stage, w + L_head(0), HEAD_BYTES / 16, tid); // unit 0 +#if SW_GL_LDS + sw_gl_tab[tid] = sw_2q(wg_gl_entry(tid)); // THREADS = 256 entries; the first barrier orders it before the MLP +#if SW_C == 96 && SW_ECL > 0 + sw_gl_tab[tid + 256u] = sw_2q(wg_gl_entry(tid).yx); +#endif +#endif + + // Gather: token t of the window, mirrored at the borders. + const int win = win0 < nwin ? win0 : nwin - 1; + const int wy = win / nwx, wx = win - wy * nwx; + const int pr = 4 * wy - oy + (int)(t >> 2), pc = 4 * wx - ox + (int)(t & 3u); + const bool real = win0 < nwin && pr >= 0 && pr < H && pc >= 0 && pc < W; + const int dst = real ? pr * W + pc : -1; + const int mr = sw_mirror(pr, H), mc = sw_mirror(pc, W); + const uint src = (uint)(mr * W + mc) * SW_C + hh * HALF; + uint2 xa[KC]; +#if SW_ADD + uint2 xb[KC]; +#endif +#if SW_ECL > 0 + const uint lowp = SW_WIN_LOW0(nwx, nwin, lane, (int)wg_block_id()); + fused_expand(w + L_TAIL, MAXU, nwx, nwin, tid, (int)wg_block_id(), lowp); + const uint lpw = WaveReadLaneAt(lowp, wave_id); // this wave's window (win: the same clamp) +#if SW_HYB + // the coarse source position of E (sw_coarse_src): the mirrored group, the member's own sub-pixel + const int mre = 2 * sw_mirror(pr >> 1, H >> 1) + (pr & 1), mce = 2 * sw_mirror(pc >> 1, W >> 1) + (pc & 1); +#else + const int mre = mr, mce = mc; +#endif + const int low = ((mre >> 1) - (int)(lpw & 0xffffu)) * 2 + ((mce >> 1) - (int)(lpw >> 16)); + const uint eslot = (tid >> 5) * 16u + (uint)low * 4u + (uint)(((mre & 1) << 1) | (mce & 1)); +#elif SW_SRC == 1 + v8f xf[KC]; + sw_load_halo_f16(x, pr, pc, W, hh, xf); +#elif SW_SRC == 3 + v8f xf[KC]; + sw_load_halo_lin(x, pr, pc, W, lane, hh, xf); +#elif SW_SRC == 2 || (SW_HYB && SW_ADD) + load_frags_g(x, sw_coarse_src(pr, pc, H, W, hh), xa); +#else + load_frags_g(x, src, xa); +#endif +#if SW_ADD + load_frags_g(xadd, src, xb); +#endif +#if SW_NORM1_EARLY + v8f ng[KC], nb[KC]; + { + const uint g1 = w + L_G1 + hh * (HALF * 4), bp = w + L_BP + hh * 32u; + [unroll] for (uint k = 0; k < KC; ++k) { ng[k] = wg_load8f(g1, 32u * k); nb[k] = wg_load8f(bp, 64u * k); } + } +#endif + st_commit(stage, 0u, HEAD_BYTES / 16, tid); + wg_barrier_lds(); +#if SW_ECL > 0 + [unroll] for (uint i = 0; i < KC / 2; ++i) { + uint4 v = sw_lds_ld128(MAXU + eslot * SW_C + hh * HALF + 16u * i); + xa[2 * i] = v.xy; xa[2 * i + 1] = v.zw; + } + wg_barrier_lds(); // read before the buffer they live in is refilled +#endif + uint buf = 0u; + + // Steps 1-2: a = q8(RMSNorm(x; gamma1)); the residual accumulator starts as x + bp. + uint2 af[KC]; + v8f acc[KC]; +#if SW_Q7_CHUNK + uint4 acc_h[KC]; +#endif + { + [unroll] for (uint k = 0; k < KC; ++k) { +#if SW_SRC == 1 || SW_SRC == 3 + acc[k] = xf[k]; +#else + acc[k] = sw_unpack_fp8(xa[k]); +#endif +#if SW_ADD + acc[k] = sw_add8(acc[k], sw_unpack_fp8(xb[k])); +#if SW_HYB + acc[k] = hyb_round16(acc[k]); // x = RN16(dec(P) + dec(S)) +#endif +#endif + } +#if SW_HYB + // y = the original's norm (FP16 tree); a = FP8(y); the Wp chain starts at RN16(bp + x) + { +#if SW_NORM1_EARLY + v8f y[KC]; + hyb_norm(acc, ng, hh, y); +#else + const uint g1 = w + L_G1 + hh * (HALF * 4), bp = w + L_BP + hh * 32u; + v8f gp[KC], y[KC]; + [unroll] for (uint k1 = 0; k1 < KC; ++k1) gp[k1] = wg_load8f(g1, 32u * k1); + hyb_norm(acc, gp, hh, y); +#endif + [unroll] for (uint kd = 0; kd < KC; ++kd) { HD_ST8(8u * kd, acc[kd]); HD_ST8(8u * (KC + kd), y[kd]); } +#if SW_Q7_CHUNK + uint2 af_l[KC]; +#if !SW_MEGA + float ym = 0.0f; + [unroll] for (uint km = 0; km < KC; ++km) ym = hyb_absmax8(ym, y[km]); + if (WaveActiveAllTrue(ym <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af_l[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af_l[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af_l[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { +#if SW_NORM1_EARLY + acc_h[k3b] = hyb_rn16x8(sw_add8(acc[k3b], nb[k3b])); +#else + acc_h[k3b] = hyb_rn16x8(sw_add8(acc[k3b], wg_load8f(bp, 64u * k3b))); +#endif + } + HYB_Q7C_L2D(KC, af_l, af, hh); +#else +#if !SW_MEGA + float ym = 0.0f; + [unroll] for (uint km = 0; km < KC; ++km) ym = hyb_absmax8(ym, y[km]); + if (WaveActiveAllTrue(ym <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { +#if SW_NORM1_EARLY + acc[k3b] = hyb_add16(acc[k3b], nb[k3b]); +#else + acc[k3b] = hyb_add16(acc[k3b], wg_load8f(bp, 64u * k3b)); +#endif + } +#endif + } +#else + const float r = norm_r(acc); +#if SW_NORM_R2 & 1 + const float r2 = sw_opaque_copy(r); +#endif +#if !SW_NORM1_EARLY + const uint g1 = w + L_G1 + hh * (HALF * 4), bp = w + L_BP + hh * 32u; +#endif + [unroll] for (uint k2 = 0; k2 < KC; ++k2) { +#if SW_NORM1_EARLY + const v8f g = ng[k2], b = nb[k2]; +#else + const v8f g = wg_load8f(g1, 32u * k2), b = wg_load8f(bp, 64u * k2); +#endif + v8f d; +#if SW_NORM_R2 & 1 + d = sw_norm_mul8(acc[k2], r, r2, g); +#else + [unroll] for (uint v = 0; v < 8; ++v) d.v[v] = acc[k2].v[v] * r * g.v[v]; +#endif + af[k2] = pack_in(d); + acc[k2] = sw_add8(acc[k2], b); + } +#endif + } + + // Steps 3-7, one head at a time; one staged unit per head (QKV fragments, then the head's slice of Wp). +#if SW_HEAD_UNROLL + const uint nheads = SW_HEADS; + [unroll] for (uint hd = 0; hd < nheads; ++hd) { +#else + const uint nheads = SW_HEADS + sw_zero(); +#if SW_C != 64 + const uint biasl = w + L_BIAS + ((t * 2u + hh) * 32u + sw_zero_bits()); // lane part of the bias address +#endif +#if SW_HEAD_PAIRS + [loop] for (uint h2 = 0; h2 < nheads; h2 += 2u) [unroll] for (uint hq = 0; hq < 2u; ++hq) { + const uint hd = h2 + hq; +#else + [loop] for (uint hd = 0; hd < nheads; ++hd) { +#endif +#endif + const bool last = hd + 1u == nheads; + if (last) st_fetch(stage, w + L_mlp(0), MLP_BYTES / 16, tid); // uniform branches: unit sizes stay constants + else st_fetch(stage, w + L_head(hd + 1u), HEAD_BYTES / 16, tid); + const uint U = buf * MAXU, fb = sw_lane_base(U, lane); +#if SW_C == 64 + // c64: the head's position bias issued before the QKV products (load latency hidden; about 1 us faster). The + // c96 kernels keep it below: there the earlier load made the register allocator add about 60 moves (+23 us). + const v8f bias = wg_load8f(w + L_BIAS, ((hd * 16u + t) * 2u + hh) * 32u); +#endif + uint2 uf[2]; + uint4 vt[2]; +#if SW_Q7_CHUNK + // VMEM/LUT latency hiding: compute Wqk -> S = U^T U + B first, then interleave Wv (2*KC FP8 WMMAs) + // across hyb_softmax_pre (hyb_rcp16 global LUT load) and hyb_softmax_fin so the LUT load latency is hidden. + { + v8f accq0 = sw_zero8(), accq1 = sw_zero8(); + [unroll] for (uint kc2 = 0; kc2 < KC; kc2 += 2u) { + const uint2 fq00 = sw_lfrag_b(fb, (0u * KC + kc2) * 2u); + const uint2 fq10 = sw_lfrag_b(fb, (1u * KC + kc2) * 2u); + const uint2 fq01 = sw_lfrag_b(fb, (0u * KC + kc2 + 1u) * 2u); + const uint2 fq11 = sw_lfrag_b(fb, (1u * KC + kc2 + 1u) * 2u); + accq0 = wg_wmma_fp8(fq00, af[kc2], accq0); + accq1 = wg_wmma_fp8(fq10, af[kc2], accq1); + accq0 = wg_wmma_fp8(fq01, af[kc2 + 1u], accq0); + accq1 = wg_wmma_fp8(fq11, af[kc2 + 1u], accq1); + if (kc2 + 2u < KC) { + accq0 = hyb_round16(accq0); + accq1 = hyb_round16(accq1); + } + } + hyb_q8_pair(hyb_round16(accq0), hyb_round16(accq1), uf[0], uf[1]); + } +#if SW_C != 64 + const v8f bias = wg_load8f(biasl, hd * 1024u); +#endif + v8f s = wg_wmma_fp8(uf[0], uf[0], bias); + s = wg_wmma_fp8(uf[1], uf[1], s); + uint4 p; + { + // Issue chunk 0 of Wv before hyb_softmax_pre, then hide hyb_rcp16 global LUT latency + // behind the remaining Wv chunks before hyb_softmax_fin. + v8f accv0 = sw_zero8(), accv1 = sw_zero8(); + { + const uint2 fv00 = sw_lfrag_b(fb, (0u * KC + 0u) * 2u + 1u); + const uint2 fv10 = sw_lfrag_b(fb, (1u * KC + 0u) * 2u + 1u); + const uint2 fv01 = sw_lfrag_b(fb, (0u * KC + 1u) * 2u + 1u); + const uint2 fv11 = sw_lfrag_b(fb, (1u * KC + 1u) * 2u + 1u); + accv0 = wg_wmma_fp8(af[0], fv00, accv0); + accv1 = wg_wmma_fp8(af[0], fv10, accv1); + accv0 = wg_wmma_fp8(af[1], fv01, accv0); + accv1 = wg_wmma_fp8(af[1], fv11, accv1); + } + const HybSmaxPre sp = hyb_softmax_pre(s); + [unroll] for (uint kc2 = 2; kc2 < KC; kc2 += 2u) { + accv0 = hyb_round16(accv0); + const uint2 fv00 = sw_lfrag_b(fb, (0u * KC + kc2) * 2u + 1u); + const uint2 fv10 = sw_lfrag_b(fb, (1u * KC + kc2) * 2u + 1u); + const uint2 fv01 = sw_lfrag_b(fb, (0u * KC + kc2 + 1u) * 2u + 1u); + const uint2 fv11 = sw_lfrag_b(fb, (1u * KC + kc2 + 1u) * 2u + 1u); + accv0 = wg_wmma_fp8(af[kc2], fv00, accv0); + accv1 = hyb_round16(accv1); + accv1 = wg_wmma_fp8(af[kc2], fv10, accv1); + accv0 = wg_wmma_fp8(af[kc2 + 1u], fv01, accv0); + accv1 = wg_wmma_fp8(af[kc2 + 1u], fv11, accv1); + } + p = hyb_softmax_fin(sp); + vt[0] = wg_to_f16_ags(accv0); + vt[1] = wg_to_f16_ags(accv1); + } + uint2 of[2]; + { + v8f pv0 = wg_wmma_f16(vt[0], p, sw_zero8()); + v8f pv1 = wg_wmma_f16(vt[1], p, sw_zero8()); + of[0] = hyb_q7c_pv_q8(vt[0], p, hh, sw_zero(), pv0); + of[1] = hyb_q7c_pv_q8(vt[1], p, hh, sw_zero(), pv1); + } + // x1 += Wp[:, head hd] q8(o_hd): 2-tile software-pipelined acc_h unpack/pack with FP8 WMMAs (reduces RAW stalls) + { + uint2 fp[KC][2]; + [unroll] for (uint m = 0; m < KC; ++m) { + fp[m][0] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u); + fp[m][1] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u + 1u); + } + v8f t0 = hyb_h2f8(acc_h[0]); + t0 = wg_wmma_fp8(fp[0][0], of[0], t0); + [unroll] for (uint m2 = 0; m2 + 1u < KC; ++m2) { + v8f t1 = hyb_h2f8(acc_h[m2 + 1u]); + t0 = wg_wmma_fp8(fp[m2][1], of[1], t0); + t1 = wg_wmma_fp8(fp[m2 + 1u][0], of[0], t1); + acc_h[m2] = hyb_rn16x8(t0); + t0 = t1; + } + t0 = wg_wmma_fp8(fp[KC - 1u][1], of[1], t0); + acc_h[KC - 1u] = hyb_rn16x8(t0); + } +#elif SW_HYB && (SW_C != 96) + // VMEM/LUT latency hiding (SW_HYB, C != 96): compute Wqk -> S = U^T U + B first, then interleave Wv + // (2*KC FP8 WMMAs) across hyb_softmax_pre (exact FP32 e8 + hyb_rcp16 global LUT load) and hyb_softmax_fin. + { + uint2 fq0[KC], fq1[KC]; + [unroll] for (uint kc = 0; kc < KC; ++kc) { + fq0[kc] = sw_lfrag_b(fb, (0u * KC + kc) * 2u); + fq1[kc] = sw_lfrag_b(fb, (1u * KC + kc) * 2u); + } + v8f accq0 = sw_zero8(), accq1 = sw_zero8(); + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) { + accq0 = wg_wmma_fp8(fq0[kc2], af[kc2], accq0); + accq1 = wg_wmma_fp8(fq1[kc2], af[kc2], accq1); + } + const v8f rq0 = hyb_round16(accq0), rq1 = hyb_round16(accq1); + HD_ST8(HD_HEAD + 60u * hd + 0u, rq0); + HD_ST8(HD_HEAD + 60u * hd + 8u, rq1); +#if !SW_MEGA + hyb_q8_pair(rq0, rq1, uf[0], uf[1]); +#else + uf[0] = hyb_q8(rq0); + uf[1] = hyb_q8(rq1); +#endif + } +#if SW_C != 64 +#if SW_HEAD_UNROLL + const v8f bias = wg_load8f(w + L_BIAS, ((hd * 16u + t) * 2u + hh) * 32u); +#else + const v8f bias = wg_load8f(biasl, hd * 1024u); +#endif +#endif + // s = one 32-term FP8 op started at B (the position bias, FP16 values); the original's weights P + v8f s = wg_wmma_fp8(uf[0], uf[0], bias); + s = wg_wmma_fp8(uf[1], uf[1], s); + uint4 p; + { + v8f accv0 = sw_zero8(), accv1 = sw_zero8(); + [unroll] for (uint kv0 = 0; kv0 < KC / 2; ++kv0) { + const uint2 fv0 = sw_lfrag_b(fb, (0u * KC + kv0) * 2u + 1u); + const uint2 fv1 = sw_lfrag_b(fb, (1u * KC + kv0) * 2u + 1u); + accv0 = wg_wmma_fp8(af[kv0], fv0, accv0); + accv1 = wg_wmma_fp8(af[kv0], fv1, accv1); + } + const HybSmaxPre sp = hyb_softmax_pre(s); + [unroll] for (uint kv1 = KC / 2; kv1 < KC; ++kv1) { + const uint2 fv0 = sw_lfrag_b(fb, (0u * KC + kv1) * 2u + 1u); + const uint2 fv1 = sw_lfrag_b(fb, (1u * KC + kv1) * 2u + 1u); + accv0 = wg_wmma_fp8(af[kv1], fv0, accv0); + accv1 = wg_wmma_fp8(af[kv1], fv1, accv1); + } + p = hyb_softmax_fin(sp); + vt[0] = wg_to_f16_ags(accv0); + vt[1] = wg_to_f16_ags(accv1); +#if SW_HYB_DUMP + HD_ST8(HD_HEAD + 60u * hd + 16u, hyb_h2f8(vt[0])); + HD_ST8(HD_HEAD + 60u * hd + 24u, hyb_h2f8(vt[1])); +#endif + } + HD_ST8(HD_HEAD + 60u * hd + 32u, hyb_round16(s)); + HD_ST4(HD_HEAD + 60u * hd + 40u, p); + // o = A V (rows value channels, columns tokens) + uint2 of[2]; + { + const v8f pv0 = wg_wmma_f16(vt[0], p, sw_zero8()); + const v8f pv1 = wg_wmma_f16(vt[1], p, sw_zero8()); + const v8f rp0 = hyb_round16(pv0), rp1 = hyb_round16(pv1); + HD_ST8(HD_HEAD + 60u * hd + 44u, rp0); + HD_ST8(HD_HEAD + 60u * hd + 52u, rp1); +#if !SW_MEGA + hyb_q8_pair(rp0, rp1, of[0], of[1]); +#else + of[0] = hyb_q8(rp0); + of[1] = hyb_q8(rp1); +#endif + } + // x1 += Wp[:, head hd] q8(o_hd) + uint2 fp[KC][2]; + [unroll] for (uint m = 0; m < KC; ++m) { + fp[m][0] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u); + fp[m][1] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u + 1u); + } + [unroll] for (uint m2 = 0; m2 < KC; ++m2) { + acc[m2] = wg_wmma_fp8(fp[m2][0], of[0], acc[m2]); + acc[m2] = wg_wmma_fp8(fp[m2][1], of[1], acc[m2]); + } +#else + [unroll] for (uint mt = 0; mt < 2; ++mt) { + uint2 fq[KC], fv[KC]; + [unroll] for (uint kc = 0; kc < KC; ++kc) { + fq[kc] = sw_lfrag_b(fb, (mt * KC + kc) * 2u); + fv[kc] = sw_lfrag_b(fb, (mt * KC + kc) * 2u + 1u); + } + v8f accq = sw_zero8(), accv = sw_zero8(); + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) { + accq = wg_wmma_fp8(fq[kc2], af[kc2], accq); + accv = wg_wmma_fp8(af[kc2], fv[kc2], accv); + } +#if SW_HYB + uf[mt] = hyb_q8_of_chain(accq); + HD_ST8(HD_HEAD + 60u * hd + 8u * mt, hyb_round16(accq)); +#else + uf[mt] = pack_in(accq); +#endif + vt[mt] = wg_to_f16_ags(accv); +#if SW_HYB_DUMP + HD_ST8(HD_HEAD + 60u * hd + 16u + 8u * mt, hyb_h2f8(vt[mt])); +#endif + } + // Lane (t, h) holds the logits S(t, s) of 8 keys; the position bias is packed in the same order. +#if SW_C != 64 + const v8f bias = wg_load8f(biasl, hd * 1024u); +#endif +#if SW_HYB + // s = one 32-term FP8 op started at B (the position bias, FP16 values); the original's weights P + v8f s = wg_wmma_fp8(uf[0], uf[0], bias); + s = wg_wmma_fp8(uf[1], uf[1], s); + const uint4 p = hyb_softmax_p(s, hh); + HD_ST8(HD_HEAD + 60u * hd + 32u, hyb_round16(s)); + HD_ST4(HD_HEAD + 60u * hd + 40u, p); +#else + v8f s = wg_wmma_fp8(uf[0], uf[0], sw_zero8()); // S = U^T U + s = wg_wmma_fp8(uf[1], uf[1], s); + // soft cap: c = clamp(S + B, -cap, cap); t = c - c^3 / (3 cap^2) (fused); z = t tau log2(e). Written stage by stage + // (one loop per operation over the 8 values) so that the driver's compiler interleaves the 8 independent chains. + v8f c, tc; +#if SW_SMAX_ADDST || SW_SMAX_STAGED // c64 / c96: the same stage + [unroll] for (uint va0 = 0; va0 < 8; ++va0) c.v[va0] = s.v[va0] + bias.v[va0]; + [unroll] for (uint v = 0; v < 8; ++v) c.v[v] = min(max(c.v[v], asfloat(0xc20179dbu)), asfloat(0x420179dbu)); +#else + [unroll] for (uint v = 0; v < 8; ++v) c.v[v] = min(max(s.v[v] + bias.v[v], asfloat(0xc20179dbu)), asfloat(0x420179dbu)); +#endif + [unroll] for (uint v1 = 0; v1 < 8; ++v1) tc.v[v1] = c.v[v1] * c.v[v1]; + [unroll] for (uint v2 = 0; v2 < 8; ++v2) tc.v[v2] = mad(c.v[v2] * tc.v[v2], asfloat(0xb9a6cc38u), c.v[v2]); + // max over the rounded products RN(t tau log2e) = RN(tau log2e max t) (rounding is monotone, the factor > 0, t + // never NaN after the clamp): one multiply instead of eight + float mx = sw_hmax8(tc); + mx = max(mx, wg_xor16(mx)); +#if SW_SMAX_STAGED + const float nmx = mx * asfloat(0xbf028297u); // -RN(k max) + const float nmx1 = asfloat(asuint(nmx) | sw_zero()); // the same value in a second register (dual issue) + v8f e; + [unroll] for (uint v4 = 0; v4 < 8; ++v4) e.v[v4] = mad(tc.v[v4], asfloat(0x3f028297u), (v4 & 1u) ? nmx1 : nmx); +#else + mx = mx * asfloat(0x3f028297u); + v8f e; + [unroll] for (uint v4 = 0; v4 < 8; ++v4) e.v[v4] = mad(tc.v[v4], asfloat(0x3f028297u), -mx); +#endif + [unroll] for (uint v5 = 0; v5 < 8; ++v5) e.v[v5] = wg_exp2(e.v[v5]); + float sum = sw_hsum8(e); + sum = sum + wg_xor16(sum); + const float rs = wg_rcp(sum); +#if SW_SMAX_MIX + // p = (f16)(e / sum) with one rounding (HIP: v_fma_mixlo_f16 e, rcp, 0): the driver folds mad(e, rs, 0) into its + // F32 -> F16 matrix conversion as exactly that instruction (one rounding of the exact product; HIP's own operation). + v8f pm; + [unroll] for (uint v6 = 0; v6 < 8; ++v6) pm.v[v6] = mad(e.v[v6], rs, 0.0f); + const uint4 p = wg_to_f16_ags(pm); +#else + // p = (f16)(e / sum) with one rounding (HIP: v_fma_mixlo_f16 e, rcp, 0 = wg_mul_f16): the product q rounded to odd + // at FP32 precision (its exact residual by fma gives the direction), then the driver's round-to-nearest-even FP16 + // conversion. q >= 0 here (e = 2^x, rs > 0), so the round to odd needs no sign / infinity / zero cases: a nonzero + // residual with q even moves q one ulp toward the exact product (a zero q has a zero residual under FTZ). + // Same bits as wg_mul_f16 for these operands. + v8f q, r; + [unroll] for (uint v6 = 0; v6 < 8; ++v6) q.v[v6] = e.v[v6] * rs; + [unroll] for (uint v7 = 0; v7 < 8; ++v7) r.v[v7] = mad(e.v[v7], rs, -q.v[v7]); + // Select-free form (no compare / VCC chains): with nz = (r != 0) as 0 / 1 and s = 0 / -1 the residual sign, + // po = (q + s) | nz. nz = 0: q. r > 0: q | 1 (q even: q + 1; odd: q). r < 0: (q - 1) | 1 (q even: q - 1; + // odd: q). The bits of r: e > 0 and rs > 0 are finite (e = 2^x with x bounded by the soft cap, sum in [1, 16]), + // so r is finite and an exact-zero residual is +0 (x - x rounds to +0): r's sign bit is set only for r < 0. + v8f po; + uint nz[8], qs[8]; + [unroll] for (uint v8 = 0; v8 < 8; ++v8) nz[v8] = asuint(r.v[v8]) << 1; + [unroll] for (uint v9 = 0; v9 < 8; ++v9) qs[v9] = asuint(q.v[v9]) + (uint)(asint(r.v[v9]) >> 31); + [unroll] for (uint va = 0; va < 8; ++va) nz[va] = min(nz[va], 1u); + [unroll] for (uint vb = 0; vb < 8; ++vb) po.v[vb] = asfloat(qs[vb] | nz[vb]); + const uint4 p = wg_to_f16_ags(po); +#endif +#endif + // o = A V (rows value channels, columns tokens) + uint2 of[2]; +#if SW_HYB + [unroll] for (uint dt = 0; dt < 2; ++dt) { + const v8f pv = wg_wmma_f16(vt[dt], p, sw_zero8()); + of[dt] = hyb_q8_of_chain(pv); + HD_ST8(HD_HEAD + 60u * hd + 44u + 8u * dt, hyb_round16(pv)); + } +#else + [unroll] for (uint dt = 0; dt < 2; ++dt) of[dt] = pack_in(wg_wmma_f16(vt[dt], p, sw_zero8())); +#endif + // x1 += Wp[:, head hd] q8(o_hd) + uint2 fp[KC][2]; + [unroll] for (uint m = 0; m < KC; ++m) { + fp[m][0] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u); + fp[m][1] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u + 1u); + } + [unroll] for (uint m2 = 0; m2 < KC; ++m2) { + acc[m2] = wg_wmma_fp8(fp[m2][0], of[0], acc[m2]); + acc[m2] = wg_wmma_fp8(fp[m2][1], of[1], acc[m2]); + } +#endif +#if SW_NORM2_EARLY + if (!last) { + st_commit(stage, (buf ^ 1u) * MAXU, HEAD_BYTES / 16, tid); + wg_barrier_lds(); + buf ^= 1u; + } +#else + if (last) st_commit(stage, (buf ^ 1u) * MAXU, MLP_BYTES / 16, tid); + else st_commit(stage, (buf ^ 1u) * MAXU, HEAD_BYTES / 16, tid); + wg_barrier_lds(); + buf ^= 1u; +#endif + } +#if SW_NORM2_EARLY + // the last head's commit after the loop, with norm2's gamma / beta issued before its barrier + v8f ng2[KC], nb2[KC]; + { + const uint g2 = w + L_G2 + hh * (HALF * 4), b2 = w + L_B2 + hh * 32u; + [unroll] for (uint k = 0; k < KC; ++k) { ng2[k] = wg_load8f(g2, 32u * k); nb2[k] = wg_load8f(b2, 64u * k); } + } + st_commit(stage, (buf ^ 1u) * MAXU, MLP_BYTES / 16, tid); + wg_barrier_lds(); + buf ^= 1u; +#endif + + // Step 8: m = q8(RMSNorm(x1; gamma2)), then b2 into the residual accumulator. + uint2 mf[KC]; +#if SW_Q7_CHUNK + { +#if SW_NORM2_EARLY + v8f y[KC]; + hyb_norm_h(acc_h, ng2, hh, y); +#else + const uint g2 = w + L_G2 + hh * (HALF * 4), b2 = w + L_B2 + hh * 32u; + v8f gp[KC], y[KC]; + [unroll] for (uint k1 = 0; k1 < KC; ++k1) gp[k1] = wg_load8f(g2, 32u * k1); + hyb_norm_h(acc_h, gp, hh, y); +#endif + uint2 mf_l[KC]; +#if !SW_MEGA + float ym2 = 0.0f; + [unroll] for (uint km2 = 0; km2 < KC; ++km2) ym2 = hyb_absmax8(ym2, y[km2]); + if (WaveActiveAllTrue(ym2 <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf_l[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf_l[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf_l[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { + v8f s2 = hyb_h2f8(acc_h[k3b]); +#if SW_NORM2_EARLY + const v8f bv = nb2[k3b]; +#else + const v8f bv = wg_load8f(b2, 64u * k3b); +#endif + [unroll] for (uint i = 0; i < 8; ++i) s2.v[i] = s2.v[i] + bv.v[i]; + acc_h[k3b] = hyb_rn16x8(s2); + } + HYB_Q7C_L2D(KC, mf_l, mf, hh); + } +#elif SW_HYB + { + // z = RN16(the Wp chain); m = FP8(norm(z; g2')); the W2 chain starts at RN16(b2 + z) + uint4 acc_h2[KC]; + [unroll] for (uint kz = 0; kz < KC; ++kz) acc_h2[kz] = hyb_rn16x8(acc[kz]); +#if SW_NORM2_EARLY + v8f y[KC]; + hyb_norm_h(acc_h2, ng2, hh, y); +#else + const uint g2 = w + L_G2 + hh * (HALF * 4), b2 = w + L_B2 + hh * 32u; + v8f gp[KC], y[KC]; + [unroll] for (uint k1 = 0; k1 < KC; ++k1) gp[k1] = wg_load8f(g2, 32u * k1); + hyb_norm_h(acc_h2, gp, hh, y); +#endif +#if SW_HYB_DUMP + [unroll] for (uint kd = 0; kd < KC; ++kd) { HD_ST8(HD_Z + 8u * kd, hyb_h2f8(acc_h2[kd])); HD_ST8(HD_Y2 + 8u * kd, y[kd]); } +#endif +#if !SW_MEGA + float ym2 = 0.0f; + [unroll] for (uint km2 = 0; km2 < KC; ++km2) ym2 = hyb_absmax8(ym2, y[km2]); + if (WaveActiveAllTrue(ym2 <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { +#if SW_NORM2_EARLY + acc[k3b] = hyb_add16(hyb_h2f8(acc_h2[k3b]), nb2[k3b]); +#else + acc[k3b] = hyb_add16(hyb_h2f8(acc_h2[k3b]), wg_load8f(b2, 64u * k3b)); +#endif + } +#if SW_COEF_ROWS + [unroll] for (uint vr = 0; vr < 8; ++vr) { // channels 8..15 (acc[1] of the hh = 0 lane) to the hh = 1 lane + const float ar = asfloat(wg_xor16_u(asuint(acc[1].v[vr]))); + acc[0].v[vr] = hh != 0u ? ar : acc[0].v[vr]; + } +#endif + } +#else + { + const float r = norm_r(acc); +#if SW_NORM_R2 & 2 + const float r2 = sw_opaque_copy(r); +#endif +#if !SW_NORM2_EARLY + uint g2 = w + L_G2 + hh * (HALF * 4), b2 = w + L_B2 + hh * 32u; +#endif + [unroll] for (uint k = 0; k < KC; ++k) { +#if SW_N2_BATCH && !SW_NORM2_EARLY + if (k > 0u && k % SW_N2_BATCH == 0u) { + const uint dz = mf[k - 1u].x & sw_zero_bits(); // 0 at run time + g2 += dz; b2 += dz; + } +#endif +#if SW_NORM2_EARLY + const v8f g = ng2[k], b = nb2[k]; +#else + const v8f g = wg_load8f(g2, 32u * k), b = wg_load8f(b2, 64u * k); +#endif + v8f d; +#if SW_NORM_R2 & 2 + d = sw_norm_mul8(acc[k], r, r2, g); +#else + [unroll] for (uint v = 0; v < 8; ++v) d.v[v] = acc[k].v[v] * r * g.v[v]; +#endif + mf[k] = pack_in(d); + acc[k] = sw_add8(acc[k], b); + } + } +#endif + + // Steps 9-10: x2 = x1 + W2 q8(GELU(W1 m + b1)) + b2, GROUP hidden tiles of 16 at a time. + const uint b1 = w + L_B1 + hh * 32u; +#if SW_HYB && SW_HYB_MUT_ORDER == 3 + v8f acc2[KC]; // check mutant 3: the odd tile groups' W2 chunks accumulate here (from 0), added at the end + [unroll] for (uint ma = 0; ma < KC; ++ma) acc2[ma] = sw_zero8(); +#endif +#if SW_REV_PHI + v8f racc[KC]; + [unroll] for (uint rk = 0; rk < KC; ++rk) racc[rk] = sw_perm8(acc[rk], 7u, 7u); +#endif +#if SW_MLP_DEP + uint mdz = 0u; // opaque zero from the latest GELU pack: later loads' addresses depend on it (no early hoisting) +#endif +#if SW_MLP_DEP >= 2 +#define SW_MDZ mdz // 2: also the LDS fragment bases and the staging commit (every group) +#else +#define SW_MDZ 0u +#endif +#if SW_MLP_STEP == NMLP + const uint nmlp = NMLP; + [unroll] for (uint u = 0; u < NMLP; ++u) { +#elif SW_MLP_STEP > 1 + const uint nmlp = NMLP + sw_zero(); + [loop] for (uint us = 0; us < nmlp; us += SW_MLP_STEP) [unroll] for (uint ui = 0; ui < SW_MLP_STEP; ++ui) { + const uint u = us + ui; +#else + const uint nmlp = NMLP + sw_zero(); +#if SW_MLP_PAIRS + [loop] for (uint u2 = 0; u2 < nmlp; u2 += 3u) [unroll] for (uint uq = 0; uq < 3u; ++uq) { + const uint u = u2 + uq; +#else + [loop] for (uint u = 0; u < nmlp; ++u) { +#endif +#endif + const bool more = u + 1u < nmlp; +#if SW_MLP_DEP + const uint wd = w + mdz, b1d = b1 + mdz; +#else + const uint wd = w, b1d = b1; +#endif +#if SW_REV_PHI + [unroll] for (uint rk0 = 0; rk0 < KC; ++rk0) acc[rk0] = sw_unperm8(racc[rk0], 7u, 7u); +#endif +#if !SW_STAGE_LATE + st_fetch(stage, wd + L_mlp(more ? u + 1u : u), MLP_BYTES / 16, tid); +#endif + const uint U = buf * MAXU; + // the tile groups of a unit unrolled (C = 96: as a loop, the register allocator moved the 48 accumulator registers + // around on every iteration, about 90 moves per group; C = 64: measured 3.6 % faster unrolled) and + // software-pipelined by one group (c64 / c96 about 4 % faster): W1 of group j0 + GROUP is issued before the GELU + // of group j0, so the GELU's exp / rcp can issue under independent matrix multiplies (same operations per value) +#if SW_Q7_CHUNK + uint4 hcur_h[GROUP]; + { + const uint fb0 = sw_lane_base(buf * MAXU, lane) + SW_MDZ; + v8f hc[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hc[g2] = wg_load8f(b1d, (u * HPU + g2) * 64u); + [unroll] for (uint kc2 = 0; kc2 < KC; kc2 += 2u) { + uint2 f0[GROUP], f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) { + f0[g] = sw_lfrag_b(fb0, g * 2u * KC + kc2); + f1[g] = sw_lfrag_b(fb0, g * 2u * KC + kc2 + 1u); + } + [unroll] for (uint g3a = 0; g3a < GROUP; ++g3a) + hc[g3a] = wg_wmma_fp8(f0[g3a], mf[kc2], hc[g3a]); + [unroll] for (uint g3b = 0; g3b < GROUP; ++g3b) + hc[g3b] = wg_wmma_fp8(f1[g3b], mf[kc2 + 1u], hc[g3b]); + if (kc2 + 2u < KC) + [unroll] for (uint g3c = 0; g3c < GROUP; ++g3c) hc[g3c] = hyb_round16(hc[g3c]); + } + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hcur_h[g3o] = hyb_rn16x8(hc[g3o]); + } + [unroll] for (uint j0 = 0; j0 < HPU; j0 += GROUP) { + const uint fb = sw_lane_base(buf * MAXU, lane) + SW_MDZ + j0 * (2u * KC * 32u); + uint4 hnext_h[GROUP]; + uint2 hf[GROUP]; + if (j0 + GROUP < HPU) { + // Split hyb_gelu_pre(hcur_h[0..1]) across W1(j0 + GROUP): 8x u16 LUT loads hide behind + // independent FP8 WMMAs with only 8 VGPRs live at a time. + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const uint fbn = fb + GROUP * (2u * KC * 32u); + v8f hn[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hn[g2] = wg_load8f(b1d, (u * HPU + j0 + GROUP + g2) * 64u); + { + uint2 f0[GROUP], f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) { + f0[g] = sw_lfrag_b(fbn, g * 2u * KC + 0u); + f1[g] = sw_lfrag_b(fbn, g * 2u * KC + 1u); + } + [unroll] for (uint g3a = 0; g3a < GROUP; ++g3a) hn[g3a] = wg_wmma_fp8(f0[g3a], mf[0], hn[g3a]); + [unroll] for (uint g3b = 0; g3b < GROUP; ++g3b) hn[g3b] = wg_wmma_fp8(f1[g3b], mf[1], hn[g3b]); + } + hf[0] = hyb_gelu_fin(gp0); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint kc2 = 2; kc2 < KC; kc2 += 2u) { + [unroll] for (uint g3c = 0; g3c < GROUP; ++g3c) hn[g3c] = hyb_round16(hn[g3c]); + uint2 f0[GROUP], f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) { + f0[g] = sw_lfrag_b(fbn, g * 2u * KC + kc2); + f1[g] = sw_lfrag_b(fbn, g * 2u * KC + kc2 + 1u); + } + [unroll] for (uint g3a = 0; g3a < GROUP; ++g3a) hn[g3a] = wg_wmma_fp8(f0[g3a], mf[kc2], hn[g3a]); + [unroll] for (uint g3b = 0; g3b < GROUP; ++g3b) hn[g3b] = wg_wmma_fp8(f1[g3b], mf[kc2 + 1u], hn[g3b]); + } + hf[1] = hyb_gelu_fin(gp1); + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hnext_h[g3o] = hyb_rn16x8(hn[g3o]); + } else { + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint g7 = 0; g7 < GROUP; ++g7) hnext_h[g7] = hcur_h[g7]; + hf[0] = hyb_gelu_fin(gp0); + hf[1] = hyb_gelu_fin(gp1); + } + // W2: 2-tile software-pipelined acc_h unpack/pack with FP8 WMMAs (reduces back-to-back RAW stalls + // between conversions and WMMAs). + uint2 f2[GROUP][KC]; + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) + [unroll] for (uint m = 0; m < KC; ++m) f2[g4][m] = sw_lfrag_b(fb, g4 * 2u * KC + KC + m); + v8f t0 = hyb_h2f8(acc_h[0]); + t0 = wg_wmma_fp8(f2[0][0], hf[0], t0); + [unroll] for (uint m2 = 0; m2 + 1u < KC; ++m2) { + v8f t1 = hyb_h2f8(acc_h[m2 + 1u]); + t0 = wg_wmma_fp8(f2[1][m2], hf[1], t0); + t1 = wg_wmma_fp8(f2[0][m2 + 1u], hf[0], t1); + acc_h[m2] = hyb_rn16x8(t0); + t0 = t1; + } + t0 = wg_wmma_fp8(f2[1][KC - 1u], hf[1], t0); + acc_h[KC - 1u] = hyb_rn16x8(t0); + [unroll] for (uint g8 = 0; g8 < GROUP; ++g8) hcur_h[g8] = hnext_h[g8]; +#if SW_COMMIT_EARLY + if (more && j0 == GROUP * (SW_COMMIT_EARLY - 1)) st_commit(stage, (buf ^ 1u) * MAXU + 8u * SW_MDZ, MLP_BYTES / 16, tid); +#endif + } +#elif SW_HYB && (SW_C != 96) + // VMEM/LUT latency hiding (SW_HYB MLP, C != 96): keep hcur packed as uint4[GROUP] (saves 8 VGPRs) and split + // hyb_gelu_pre(hcur_h[0..1]) (16x u16 global LUT loads) across W1(j0 + GROUP) FP8 WMMAs to hide LUT latency. + uint4 hcur_h[GROUP]; + { + const uint fb0 = sw_lane_base(buf * MAXU, lane) + SW_MDZ; + uint2 f1[GROUP][KC]; + [unroll] for (uint g = 0; g < GROUP; ++g) + [unroll] for (uint kc = 0; kc < KC; ++kc) f1[g][kc] = sw_lfrag_b(fb0, g * 2u * KC + kc); + v8f hc[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hc[g2] = wg_load8f(b1d, (u * HPU + g2) * 64u); + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hc[g3] = wg_wmma_fp8(f1[g3][kc2], mf[kc2], hc[g3]); + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hcur_h[g3o] = hyb_rn16x8(hc[g3o]); + } + [unroll] for (uint j0 = 0; j0 < HPU; j0 += GROUP) { + const uint fb = sw_lane_base(buf * MAXU, lane) + SW_MDZ + j0 * (2u * KC * 32u); +#if SW_HYB_DUMP + [unroll] for (uint ghd = 0; ghd < GROUP; ++ghd) + HD_ST8(HD_H + 8u * (u * HPU + j0 + ghd), hyb_h2f8(hcur_h[ghd])); +#endif + uint4 hnext_h[GROUP]; + uint2 hf[GROUP]; + if (j0 + GROUP < HPU) { + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const uint fbn = fb + GROUP * (2u * KC * 32u); + v8f hn[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hn[g2] = wg_load8f(b1d, (u * HPU + j0 + GROUP + g2) * 64u); + [unroll] for (uint kc0 = 0; kc0 < KC / 2; ++kc0) { + uint2 f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) f1[g] = sw_lfrag_b(fbn, g * 2u * KC + kc0); + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hn[g3] = wg_wmma_fp8(f1[g3], mf[kc0], hn[g3]); + } + hf[0] = hyb_gelu_fin(gp0); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint kc1 = KC / 2; kc1 < KC; ++kc1) { + uint2 f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) f1[g] = sw_lfrag_b(fbn, g * 2u * KC + kc1); + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hn[g3] = wg_wmma_fp8(f1[g3], mf[kc1], hn[g3]); + } + hf[1] = hyb_gelu_fin(gp1); + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hnext_h[g3o] = hyb_rn16x8(hn[g3o]); + } else { + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint g7 = 0; g7 < GROUP; ++g7) hnext_h[g7] = hcur_h[g7]; + hf[0] = hyb_gelu_fin(gp0); + hf[1] = hyb_gelu_fin(gp1); + } +#if SW_COEF_ROWS + { + const uint fbr = fb + ((t & 8u) != 0u ? 24u : 0u); // rows 8..15: tile 1's rows 0..7 + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) { + const uint2 f2r = sw_lfrag_b(fbr, g4 * 2u * KC + KC); + acc[0] = wg_wmma_fp8(f2r, hf[g4], acc[0]); + } + } +#else + uint2 f2[GROUP][KC]; + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) + [unroll] for (uint m = 0; m < KC; ++m) f2[g4][m] = sw_lfrag_b(fb, g4 * 2u * KC + KC + m); +#if SW_HYB_MUT_ORDER +#if SW_HYB_MUT_ORDER == 3 + if ((j0 / GROUP) & 1u) { + [unroll] for (uint m5 = 0; m5 < KC; ++m5) + [unroll] for (uint g11 = 0; g11 < GROUP; ++g11) acc2[m5] = wg_wmma_fp8(f2[g11][m5], hf[g11], acc2[m5]); + } else +#endif + if (SW_HYB_MUT_ORDER == 2 || (SW_HYB_MUT_ORDER == 1 && u == 0u && j0 == 0u)) { + [unroll] for (uint m3 = 0; m3 < KC; ++m3) + [unroll] for (uint g9 = 0; g9 < GROUP; ++g9) + acc[m3] = wg_wmma_fp8(f2[GROUP - 1u - g9][m3], hf[GROUP - 1u - g9], acc[m3]); + } else { + [unroll] for (uint m4 = 0; m4 < KC; ++m4) + [unroll] for (uint g10 = 0; g10 < GROUP; ++g10) acc[m4] = wg_wmma_fp8(f2[g10][m4], hf[g10], acc[m4]); + } +#else + [unroll] for (uint m2 = 0; m2 < KC; ++m2) + [unroll] for (uint g6 = 0; g6 < GROUP; ++g6) acc[m2] = wg_wmma_fp8(f2[g6][m2], hf[g6], acc[m2]); +#endif +#endif // SW_COEF_ROWS + [unroll] for (uint g8 = 0; g8 < GROUP; ++g8) hcur_h[g8] = hnext_h[g8]; +#if SW_COMMIT_EARLY + if (more && j0 == GROUP * (SW_COMMIT_EARLY - 1)) st_commit(stage, (buf ^ 1u) * MAXU + 8u * SW_MDZ, MLP_BYTES / 16, tid); +#endif + } +#else + v8f hcur[GROUP]; + { + const uint fb0 = sw_lane_base(buf * MAXU, lane) + SW_MDZ; + uint2 f1[GROUP][KC]; + [unroll] for (uint g = 0; g < GROUP; ++g) + [unroll] for (uint kc = 0; kc < KC; ++kc) f1[g][kc] = sw_lfrag_b(fb0, g * 2u * KC + kc); + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hcur[g2] = wg_load8f(b1d, (u * HPU + g2) * 64u); + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hcur[g3] = wg_wmma_fp8(f1[g3][kc2], mf[kc2], hcur[g3]); + } + [unroll] for (uint j0 = 0; j0 < HPU; j0 += GROUP) { +#if SW_GELU == 3 + sw_gj = j0 / GROUP; +#endif + const uint fb = sw_lane_base(buf * MAXU, lane) + SW_MDZ + j0 * (2u * KC * 32u); + uint2 f2[GROUP][KC]; +#if SW_F2_LATE + if (!((SW_F2_LATE >> ((j0 / GROUP) % 2u)) & 1u)) +#endif + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) + [unroll] for (uint m = 0; m < KC; ++m) f2[g4][m] = sw_lfrag_b(fb, g4 * 2u * KC + KC + m); +#if SW_GELU != 0 && !SW_HYB +#if !SW_SAFE +#error "the GELU tables give HIP's pack_in bytes (no clamp)" +#endif +#if SW_GELU_EARLY + // q8(GELU) by the exact table (HIP: wg_gelu + pack_in): the loads now, the rest after W1(j0 + GROUP) + SwGeluPre gp; + if (!((SW_GELU_LATE0 >> ((j0 / GROUP) % 2u)) & 1u)) gp = sw_gelu_pre(hcur); +#endif +#endif + v8f hnext[GROUP]; + if (j0 + GROUP < HPU) { + const uint fbn = fb + GROUP * (2u * KC * 32u); + uint2 f1[GROUP][KC]; + [unroll] for (uint g = 0; g < GROUP; ++g) + [unroll] for (uint kc = 0; kc < KC; ++kc) f1[g][kc] = sw_lfrag_b(fbn, g * 2u * KC + kc); + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hnext[g2] = wg_load8f(b1d, (u * HPU + j0 + GROUP + g2) * 64u); + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hnext[g3] = wg_wmma_fp8(f1[g3][kc2], mf[kc2], hnext[g3]); + } else { + [unroll] for (uint g7 = 0; g7 < GROUP; ++g7) hnext[g7] = hcur[g7]; + } + uint2 hf[GROUP]; +#if SW_HYB + [unroll] for (uint gh = 0; gh < GROUP; ++gh) { + hf[gh] = hyb_gelu_q8(hyb_rn16x8(hcur[gh])); + HD_ST8(HD_H + 8u * (u * HPU + j0 + gh), hyb_round16(hcur[gh])); + } +#elif SW_GELU != 0 +#if SW_GELU_EARLY + if ((SW_GELU_LATE0 >> ((j0 / GROUP) % 2u)) & 1u) gp = sw_gelu_pre(hcur); + sw_gelu_fin(hcur, gp, hf); +#else + sw_gelu_fin(hcur, sw_gelu_pre(hcur), hf); +#endif +#else + // GELU of the GROUP x 8 values, written stage by stage so that the independent chains interleave (written + // value by value, the driver's compiler emitted each 7-operation chain on its own) + v8f ge[GROUP]; + gelu_group(hcur, ge); + [unroll] for (uint g5 = 0; g5 < GROUP; ++g5) hf[g5] = pack_in(ge[g5]); +#endif +#if SW_F2_LATE + // W2 fragments loaded after the GELU (their base through its first pack: the driver cannot hoist them) + if ((SW_F2_LATE >> ((j0 / GROUP) % 2u)) & 1u) { + const uint fbl = fb + (hf[0].x & sw_zero_bits()); + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) + [unroll] for (uint m = 0; m < KC; ++m) f2[g4][m] = sw_lfrag_b(fbl, g4 * 2u * KC + KC + m); + } +#endif +#if SW_MLP_DEP + if (SW_MLP_DEP == 2 || j0 + GROUP == HPU) mdz = hf[0].x & sw_zero_bits(); +#endif +#if SW_STAGE_LATE + // the next unit's staging loads after group SW_STAGE_LATE - 1's GELU (their address through its pack) + if (j0 == GROUP * (SW_STAGE_LATE - 1) && (SW_MLP_STEP != NMLP || more)) + st_fetch(stage, wd + (hf[0].x & sw_zero_bits()) + L_mlp(more ? u + 1u : u), MLP_BYTES / 16, tid); +#endif +#if SW_HYB && SW_HYB_MUT_ORDER + // check mutant (never shipped): the first unit's first tile group accumulates its W2 chunks in reverse order + // (same products, same start): inside the f32chain tolerance, but not HIP's bytes (l_hyb_stage_check.py) +#if SW_HYB_MUT_ORDER == 3 + if ((j0 / GROUP) & 1u) { // 3: odd groups into the second accumulator + [unroll] for (uint m5 = 0; m5 < KC; ++m5) + [unroll] for (uint g11 = 0; g11 < GROUP; ++g11) acc2[m5] = wg_wmma_fp8(f2[g11][m5], hf[g11], acc2[m5]); + } else +#endif + if (SW_HYB_MUT_ORDER == 2 || (SW_HYB_MUT_ORDER == 1 && u == 0u && j0 == 0u)) { // 1: first group; 2: every group + [unroll] for (uint m3 = 0; m3 < KC; ++m3) + [unroll] for (uint g9 = 0; g9 < GROUP; ++g9) + acc[m3] = wg_wmma_fp8(f2[GROUP - 1u - g9][m3], hf[GROUP - 1u - g9], acc[m3]); + } else { + [unroll] for (uint m4 = 0; m4 < KC; ++m4) + [unroll] for (uint g10 = 0; g10 < GROUP; ++g10) acc[m4] = wg_wmma_fp8(f2[g10][m4], hf[g10], acc[m4]); + } +#else + [unroll] for (uint m2 = 0; m2 < KC; ++m2) + [unroll] for (uint g6 = 0; g6 < GROUP; ++g6) acc[m2] = wg_wmma_fp8(f2[g6][m2], hf[g6], acc[m2]); +#endif + [unroll] for (uint g8 = 0; g8 < GROUP; ++g8) hcur[g8] = hnext[g8]; +#if SW_COMMIT_EARLY + if (more && j0 == GROUP * (SW_COMMIT_EARLY - 1)) st_commit(stage, (buf ^ 1u) * MAXU + 8u * SW_MDZ, MLP_BYTES / 16, tid); +#endif + } +#endif + if (more) { +#if !SW_COMMIT_EARLY + st_commit(stage, (buf ^ 1u) * MAXU, MLP_BYTES / 16, tid); +#endif + wg_barrier_lds(); + buf ^= 1u; + } +#if SW_REV_PHI + [unroll] for (uint rk1 = 0; rk1 < KC; ++rk1) racc[rk1] = sw_perm8(acc[rk1], 7u, 7u); +#endif + } +#if SW_REV_PHI + [unroll] for (uint rk2 = 0; rk2 < KC; ++rk2) acc[rk2] = sw_unperm8(racc[rk2], 7u, 7u); +#endif +#if SW_HYB && SW_HYB_MUT_ORDER == 3 + [unroll] for (uint mb = 0; mb < KC; ++mb) [unroll] for (uint vb = 0; vb < 8; ++vb) acc[mb].v[vb] = acc[mb].v[vb] + acc2[mb].v[vb]; +#endif +#if SW_HYB && SW_HYB_MUT_ORDER == 4 + // check mutant 4: the W2 chain end moved by one float32 ulp (last mantissa bit flipped) before its RN16: far inside + // the f32chain tolerance, visible in the bytes wherever the value sits on an FP16 rounding tie + [unroll] for (uint mc = 0; mc < KC; ++mc) + [unroll] for (uint vc = 0; vc < 8; ++vc) acc[mc].v[vc] = asfloat(asuint(acc[mc].v[vc]) ^ 1u); +#endif +#if SW_HYB_DUMP + [unroll] for (uint kdo = 0; kdo < KC; ++kdo) HD_ST8(HD_OUT + 8u * kdo, hyb_round16(acc[kdo])); +#endif + +#if SW_OUT_F16 + // Output RN16(x2) as FP16, real window members only (HIP LStoreF16Epi). + uint4 o16[KC]; +#if SW_OUT_COEF12 && COEF_CVT_HW + // the driver's conversions (the same bits as wg_to_f16 / the software forms): every lane computes, the hh = 0 lanes + // of real pixels inside the render rectangle store (the conversions need wave-uniform control flow) +#if SW_COEF_ROWS + o16[0] = wg_to_f16_ags(acc[0]); // hh = 0: channels 0..7; hh = 1: channels 8..15 of the same pixel + o16[1] = uint4(wg_xor16_u(o16[0].x), wg_xor16_u(o16[0].y), wg_xor16_u(o16[0].z), wg_xor16_u(o16[0].w)); +#else + [unroll] for (uint kh = 0; kh < KC; ++kh) o16[kh] = wg_to_f16_ags(acc[kh]); +#endif + { + g_z = wg_grid_ >> 31; + const float S = wg_ldf(coefW, 320u), T = wg_ldf(coefW, 324u); + const LCoefVals cv = l_coef_vals_hw(o16[0], o16[1], S, T); + if (dst >= 0 && hh == 0u && pr < coefRh && pc < coefRw) + l_coef_store12(cv, (uint)wg_uniform((int)coefA), (uint)wg_uniform((int)coefC), (uint)wg_uniform((int)coefL), + (uint)(pr * coefRw + pc)); + } + return; +#endif +#if SW_HYB + // the driver's RNE conversion (the chain-end RN16 of the hybrid helpers; HIP's LStoreF16Epi v_cvt_f16_f32) + [unroll] for (uint kf = 0; kf < KC; ++kf) o16[kf] = wg_to_f16_ags(acc[kf]); +#else + [unroll] for (uint kf = 0; kf < KC; ++kf) o16[kf] = wg_to_f16(acc[kf]); +#endif +#if SW_OUT_COEF12 + // l_coef_pack12 of the map: o16[0] / o16[1] of the hh = 0 lane are the pixel's channels 0..7 / 8..15 (the map's + // bytes dst * 64 + 0 .. 31, its lo / hi loads); Model L's 13 values are all among them + if (dst >= 0 && hh == 0u && pr < coefRh && pc < coefRw) { + g_z = wg_grid_ >> 31; + const float S = wg_ldf(coefW, 320u), T = wg_ldf(coefW, 324u); + const uint pA = (uint)wg_uniform((int)coefA), pC = (uint)wg_uniform((int)coefC), + pL = (uint)wg_uniform((int)coefL); + l_coef_px(o16[0], o16[1], S, T, pA, 0u, pC, pL, (uint)(pr * coefRw + pc)); + } + return; +#endif + if (dst >= 0) { + const uint ob16 = ((uint)dst * SW_C + hh * HALF) * 2u; + [unroll] for (uint kg = 0; kg < KC; ++kg) wg_st128(out_p, ob16 + 16u * kg, o16[kg]); + } + return; // the q8 output below stays the file's last block (fused_swin_gen.py's anchor); not compiled here +#endif + + // Output q8(x2), real window members only. + uint2 o[KC]; +#if SW_CLAMP_SKIP + float am = 0.0f; + [unroll] for (uint k0 = 0; k0 < KC; ++k0) am = sw_absmax8(am, acc[k0]); + if (sw_in448(am)) { + [unroll] for (uint k = 0; k < KC; ++k) o[k] = wg_pack_q8_nc_ags(acc[k]); + } else +#endif + { +#if SW_Q7_CHUNK + { + // Check |acc_h| <= 448.0 (FP16 0x5f00) directly on packed uint4 bits (1 VGPR vs 8*KC VGPRs!). + uint mx16 = 0u; + [unroll] for (uint km = 0; km < KC; ++km) { + const uint4 ah = acc_h[km]; + mx16 = max(mx16, max(max(ah.x & 0x7fffu, (ah.x >> 16) & 0x7fffu), max(ah.y & 0x7fffu, (ah.y >> 16) & 0x7fffu))); + mx16 = max(mx16, max(max(ah.z & 0x7fffu, (ah.z >> 16) & 0x7fffu), max(ah.w & 0x7fffu, (ah.w >> 16) & 0x7fffu))); + } + if (WaveActiveAllTrue(mx16 <= 0x5f00u)) { + [unroll] for (uint k2 = 0; k2 < KC; ++k2) o[k2] = wg_pack_q8_nc_ags(hyb_h2f8(acc_h[k2])); + } else { + [unroll] for (uint k2 = 0; k2 < KC; ++k2) o[k2] = wg_pack_q8_ags(hyb_h2f8(acc_h[k2])); + } + } +#elif SW_HYB + [unroll] for (uint k = 0; k < KC; ++k) o[k] = hyb_q8_of_chain(acc[k]); +#else + [unroll] for (uint k = 0; k < KC; ++k) o[k] = sw_pack_q8_v2(acc[k]); +#endif + } + if (dst >= 0) { + const uint ob = (uint)dst * SW_C + hh * HALF; + [unroll] for (uint i = 0; i < KC / 2; ++i) wg_st128(out_p, ob + 16u * i, uint4(o[2 * i], o[2 * i + 1])); + } +} diff --git a/clean/dx12/kernels/l_swin_dec_coef12_hyb.hlsl b/clean/dx12/kernels/l_swin_dec_coef12_hyb.hlsl new file mode 100644 index 00000000..48bf249f --- /dev/null +++ b/clean/dx12/kernels/l_swin_dec_coef12_hyb.hlsl @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: MIT +// Dedicated compilation unit for Model L's hybrid C=32 decoder block with one-tile W2 (SW_COEF_ROWS=1), +// isolated from swin_block.hlsl so unrelated Swin/hybrid kernels keep identical source digests. +// @wg-kernel l_swin_block_c32_dec_coef12_hyb co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p,p,p,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_OUT_COEF12=1,COEF_CVT_HW=1,SW_HYB=1,SW_HEAD_UNROLL=1,WG_LD_A16=1,SW_COEF_ROWS=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_coef12_hyb,WG_REV_ORDER=1 +// @wg-kernel l_swin_block_c32_dec_coef12_hyb_scanmut co=- probe=1 block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p,p,p,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=0,SW_OUT_F16=1,SW_OUT_COEF12=1,COEF_CVT_HW=1,SW_HYB=1,SW_HEAD_UNROLL=1,WG_LD_A16=1,HYB_SCAN_MUTANT=1,SW_COEF_ROWS=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_coef12_hyb_scanmut +#include "l_swin_coef_rows.hlsli" diff --git a/clean/dx12/kernels/l_swin_fast.hlsl b/clean/dx12/kernels/l_swin_fast.hlsl new file mode 100644 index 00000000..29aa8c4e --- /dev/null +++ b/clean/dx12/kernels/l_swin_fast.hlsl @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT +// Model L's fast-mode decoder blocks (runtime option l_mode=fast, env WG_L_MODE=fast; native D3D12 only): the M-form +// chain (SW_HYB 0, the WMMA / FP8 kernels of Model M's Swin stages) with Model L's decoder skip S. l_swin.hlsl's +// l_swin_block_c32_dec_nc / _dec_coef12_nc read the decoder's projection map y and nothing else (SW_ADD 0): the M-form +// route of the earlier Model L releases had no skip. Model L's decoder block adds the encoder block's map x3 (FP8) to +// the block input, as the hybrid twins do (SW_ADD 1, l_swin_block_c32_dec_hyb: x by the token-grid mirror, S by the +// fine mirror, the members' input x + S); here in the M-form arithmetic (swin_block.hlsl: the sum of the two decoded FP8 +// values in float32, no FP16 rounding step; the rest of the chain unchanged), so the fast route keeps the model's +// structure with Model M's cost per block. +// l_swin_block_c32_dec_add_nc _dec_nc with the skip (SW_ADD 1): FP16 map y2 out (the fallback route: l_coef / +// l_coef_pack12 as their own launches) +// l_swin_block_c32_dec_coef12_add_nc _dec_coef12_nc with the skip: the pack12 coefficient store as the epilogue +// Arguments as the hybrid twins' (and _dec_nc's): y, S (the encoder block's map l_x3), out (unused with the store), the +// block's blob (Model M's packer on Model L's values, not the hybrid values), H, W, ox, oy, then the store's A, C, +// latent, dec0.coef, rw, rh. The defines are the _nc kernels' with the cheaper GELU table offsets for every tile (SW_GELU 3, +// pattern 13333; the same bytes as SW_GELU 1), the staged softmax and, for the store variant, the head loop in pairs +// (SW_HEAD_PAIRS: 111 -> 96 VGPRs, the same operations in the same order: the skip's second map needs the registers). +// WG_LD_A16 (16-byte aligned loads, the hybrid twins' form: every wg_ld128 base + offset here is a multiple of 16) is on. +// +// @wg-kernel l_swin_block_c32_dec_add_nc co=- block=256 wave=32 args=p,p,p,p,u,u,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=3,SW_GELU_PAT=13333,SW_SRC=2,SW_OUT_F16=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_add_nc +// @wg-kernel l_swin_block_c32_dec_coef12_add_nc co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p,p,p,u,u defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=1,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=3,SW_GELU_PAT=13333,SW_SRC=2,SW_OUT_F16=1,SW_OUT_COEF12=1,COEF_CVT_HW=1,WG_LD_A16=1,SW_ENTRY_OVERRIDE=l_swin_block_c32_dec_coef12_add_nc,SW_SMAX_ADDST=1,SW_SMAX_STAGED=1,SW_HEAD_PAIRS=1 +// +// The "_fast" twin of the encoder block with the linears (l_swin_block_c32_enc_lin_nc_fast; launched in place of +// l_swin_block_c32_enc_lin_nc with the same arguments, runtime l_fast_alt / lever bit 4; the base kernel's DXIL is not touched): +// the two input linears of its prologue (swin_block.hlsl SW_SRC 3, TT_LINF32) keep their results in FP32: x1 = FP8(relu(b + W q)), +// x2 = b2 + W2 x1 as the block input, without the two FP16 roundings and the widening back (16 conversions and 16 unpacks per +// lane; RGA: 997 -> 893 VALU instructions, 1732 -> 1626 in all, 96 VGPRs, no spill). The FP32 value differs from the +// original's FP16 rounding (which the hybrid route keeps) by at most half an FP16 ulp; WG_LD_A16 is not set (RGA: the 16-byte loads of this +// kernel are already single instructions, the mask only adds operations). +// +// @wg-kernel l_swin_block_c32_enc_lin_nc_fast co=- block=256 wave=32 args=p,p,p,p,u,u,u,u,p,p defines=SW_C=32,SW_HEADS=2,SW_MLP=128,SW_ADD=0,SW_SAFE=1,SW_ECL=0,SW_HPU=8,SW_GELU=3,SW_GELU_PAT=13333,SW_SRC=3,SW_ENTRY_OVERRIDE=l_swin_block_c32_enc_lin_nc_fast,WG_REV_ORDER=1,SW_HEAD_PAIRS=1,SW_SMAX_STAGED=1,SW_NORM1_EARLY=1,TT_LINF32=1 +#include "swin_block.hlsl" diff --git a/clean/dx12/kernels/post.hlsl b/clean/dx12/kernels/post.hlsl index ef349ecd..79647f28 100644 --- a/clean/dx12/kernels/post.hlsl +++ b/clean/dx12/kernels/post.hlsl @@ -24,6 +24,7 @@ // forms 1/2 it does not clamp to FP16 or explicitly round to half. The UAV format supplies the final format conversion. // Form 3 uses native_direct.hlsli's immutable frame b1 and texture table (rs=direct). // @wg-kernel w64/post_tf_f32_p12_diet_vsit co=post_w64__orig.co entry=post_tf_f32_p12_diet_vsit block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,u,u,u,u,u +// @wg-kernel w64/post_tf_f32_p12_diet_vsit_pf co=post_w64__orig.co entry=post_tf_f32_p12_diet_vsit block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,u,u,u,u,u defines=WG_STAGED_PIDIV=1 // @wg-kernel w64/post_tf_p12_diet_vsit co=post_w64__orig.co entry=post_tf_p12_diet_vsit block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,u,u,u,u,u defines=POST_OUT=1 // @wg-kernel w64/post_tf_p12_diet_vsit_tex co=post_w64__orig.co rs=tex entry=post_tf_p12_diet_vsit block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,u,u,u,u,u defines=POST_OUT=2 // @wg-kernel w64/post_tf_f32_p12_diet_vsit_direct co=post_w64__orig.co rs=direct entry=post_tf_f32_p12_diet_vsit_direct block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,u,u,u,u,u defines=WG_DIRECT_TEXTURES=1,POST_OUT=3 @@ -38,6 +39,7 @@ // bx, by, idw, idh) after c2. Buffer form: the raw motion buffer (wg_motion_hi.hlsli); direct form: the game's motion // texture (its `motion` pointer is not read). // @wg-kernel pmo/post_tf_f32_p12_mo co=post_mo_w64__orig.co entry=post_tf_f32_p12_diet_vsit block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,b40,u,u,u,u,u defines=WG_POST_MO=1 +// @wg-kernel pmo/post_tf_f32_p12_mo_pf co=post_mo_w64__orig.co entry=post_tf_f32_p12_diet_vsit block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,b40,u,u,u,u,u defines=WG_POST_MO=1,WG_STAGED_PIDIV=1 // @wg-kernel pmo/post_tf_f32_p12_mo_direct co=post_mo_w64__orig.co rs=direct entry=post_tf_f32_p12_diet_vsit_direct block=512 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,b40,u,u,u,u,u defines=WG_DIRECT_TEXTURES=1,POST_OUT=3,WG_POST_MO=1 // // Native AA and ratios between 1.0 and 1.5 (Brief 15; D3D12 only, no HIP kernel of its own): the same body with NW = 4 @@ -47,8 +49,10 @@ // LDS); runtime.cpp tf4_supported is the host bound (the step footprint of NW = 4 fits 448). LDS: 448 x 48 + 20 x 480 = // 31104 bytes. The kernels above keep their DXIL (the defaults below). // @wg-kernel w64/post_tf4_dl_f32_p12_diet_vsit co=post_w64__orig.co entry=post_tf_f32_p12_diet_vsit block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,u,u,u,u,u defines=WG_TF_NW=4,WG_TF_CAP=448 +// @wg-kernel w64/post_tf4_dl_f32_p12_diet_vsit_pf co=post_w64__orig.co entry=post_tf_f32_p12_diet_vsit block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,u,u,u,u,u defines=WG_TF_NW=4,WG_TF_CAP=448,WG_STAGED_PIDIV=1 // @wg-kernel w64/post_tf4_dl_f32_p12_diet_vsit_direct co=post_w64__orig.co rs=direct entry=post_tf_f32_p12_diet_vsit_direct block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,u,u,u,u,u defines=WG_DIRECT_TEXTURES=1,POST_OUT=3,WG_TF_NW=4,WG_TF_CAP=448 // @wg-kernel pmo/post_tf4_dl_f32_p12_mo co=post_mo_w64__orig.co entry=post_tf_f32_p12_diet_vsit block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,b40,u,u,u,u,u defines=WG_POST_MO=1,WG_TF_NW=4,WG_TF_CAP=448 +// @wg-kernel pmo/post_tf4_dl_f32_p12_mo_pf co=post_mo_w64__orig.co entry=post_tf_f32_p12_diet_vsit block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,b40,u,u,u,u,u defines=WG_POST_MO=1,WG_TF_NW=4,WG_TF_CAP=448,WG_STAGED_PIDIV=1 // @wg-kernel pmo/post_tf4_dl_f32_p12_mo_direct co=post_mo_w64__orig.co rs=direct entry=post_tf_f32_p12_diet_vsit_direct block=256 wave=64 args=p,p,p,p,p,p,p,p,p,p,p,b64,p,u,u,u,u,u,u,u,u,b40,u,u,u,u,u defines=WG_DIRECT_TEXTURES=1,POST_OUT=3,WG_POST_MO=1,WG_TF_NW=4,WG_TF_CAP=448 // // Analytic output filter (WG_LZ_ANALYTIC = 1; HIP: post_w64.co, post.hip built with -mwavefrontsize64 and the default @@ -68,16 +72,66 @@ #if WG_LZ_ANALYTIC && ((POST_OUT != 0 && POST_OUT != 3) || defined(WG_POST_MO)) #error "analytic output filter: forms 0 and 3 (direct) only" #endif +#ifndef POST_OUT +#define POST_OUT 0 +#endif #if defined(WG_DIRECT_TEXTURES) #include "native_direct.hlsli" #include "wg_f16lut.hlsli" #endif -#ifndef POST_OUT -#define POST_OUT 0 +#if defined(WG_STAGED_PIDIV) +#include "wg_pidiv.hlsli" #endif // WG_POST_CUTS: the exact instruction cuts below (history base fold, shared horizontal min / max) in the forms whose // bytes the checks cover (0: 3 x f32 rows, 3: direct); the RGBA16F row forms 1 / 2 keep their previous code #define WG_POST_CUTS (POST_OUT == 0 || POST_OUT == 3) +#define WG_POST_OPT (POST_OUT == 0 || POST_OUT == 3) +// The WG_POST_OPT instruction cuts, one switch each (experiments: -DWG_PO_x=0). Form 3 (direct) always takes all of them. +#if POST_OUT == 3 +#define WG_PO_STAGE 1 // staging fetch with per-lane fixed texel row / column (pd_stage_fetch) +#define WG_PO_EXPO 1 // the exposure-pair loads after the first staging loads +#define WG_PO_HH 1 // the horizontal pass's lane roles and scratch offsets fixed per lane +#define WG_PO_VV 1 // the vertical pass's first item fixed per lane (pd_vsplit once) +#define WG_PO_GATH 1 // unrolled gather +#define WG_PO_QUAD 1 // display values: partner dwords by QuadReadAcrossX, three packed dwords +#define WG_PO_RH 1 // reduced history: two code chains +#else +// Staged form 0 (POST_OUT == 0; RGA, gfx1201): the three per-lane hoists (STAGE: staging row / column, HH: horizontal +// roles and offsets, VV: the vertical first item) each keep a few VGPRs live for the whole walk. With all of them +// post_tf is 96 VGPRs (1 workgroup per CU of 8 waves64; 85 keeps 2), so the 512-lane kernels (NW = 8) leave them out +// and keep the rest (76 VGPRs; _pf 77). The NW = 4 kernels (two staged texels per lane) keep STAGE and VV, leave out HH +// (83 VGPRs; _pf 85). +#if WG_TF_NW == 4 +#define WG_PO_STAGE_D 1 +#define WG_PO_HH_D 0 +#define WG_PO_VV_D 1 +#else +#define WG_PO_STAGE_D 0 +#define WG_PO_HH_D 0 +#define WG_PO_VV_D 0 +#endif +#ifndef WG_PO_STAGE +#define WG_PO_STAGE (WG_POST_OPT && WG_PO_STAGE_D) +#endif +#ifndef WG_PO_EXPO +#define WG_PO_EXPO WG_POST_OPT +#endif +#ifndef WG_PO_HH +#define WG_PO_HH (WG_POST_OPT && WG_PO_HH_D) +#endif +#ifndef WG_PO_VV +#define WG_PO_VV (WG_POST_OPT && WG_PO_VV_D) +#endif +#ifndef WG_PO_GATH +#define WG_PO_GATH WG_POST_OPT +#endif +#ifndef WG_PO_QUAD +#define WG_PO_QUAD WG_POST_OPT +#endif +#ifndef WG_PO_RH +#define WG_PO_RH WG_POST_OPT +#endif +#endif #if POST_OUT == 2 RWTexture2D wg_tex_out : register(u3); // the output texture (RGBA16F), written through a typed UAV #endif @@ -185,6 +239,9 @@ float unif(float x) { return asfloat(WaveReadLaneFirst(asuint(x))); } #if POST_OUT == 3 #define PD_P , const bool pd_rc, const bool pd_pi1 #define PD_A , pd_rc, pd_pi1 +#elif POST_OUT == 0 && defined(WG_STAGED_PIDIV) +#define PD_P , PiDiv pd_div +#define PD_A , pd_div #else #define PD_P #define PD_A @@ -193,10 +250,10 @@ float unif(float x) { return asfloat(WaveReadLaneFirst(asuint(x))); } #if WG_WAVE == 64 // wave32: wg_platform.hlsli includes it #include "wg_ags.hlsli" #endif -#if POST_OUT == 3 && !defined(WG_NO_PT_SMALL) +#if WG_POST_OPT && !defined(WG_NO_PT_SMALL) #define WG_PT_SMALL 1 // post_posttr.hlsli: Dec's polynomial flag by one minimum #endif -#if POST_OUT == 3 && !defined(WG_NO_PT_INF) +#if WG_POST_OPT && !defined(WG_NO_PT_INF) #define WG_PT_INF 1 // post_posttr.hlsli: blend's infinity flag by one maximum #endif @@ -257,6 +314,30 @@ float hw_hi(uint t, float w) { return mad(f16tof32(t >> 16), w, asfloat(g_z)); } // post.hip framebuffer_half: v clamped to +-65504 by compares (a NaN passes), then (_Float16) (v_cvt_f16_f32, RNE: the // driver's conversion, cvt3_f16). float fb_clamp(float v) { return select(v > 65504.0f, 65504.0f, select(v < -65504.0f, -65504.0f, v)); } +#if POST_OUT == 0 +// native_scale (native_helpers.hlsl: the staged route's scale_rgb) of one value: the product, plus the exact repair of a +// tiny product that the driver flushes to zero although its RNE result is the smallest normal (needs a zero product of a +// normal a, so only such lanes run it; every other lane's result is the product itself) +float m1_scale_ref(float a, float b) +{ + const float r = a * b; + const uint ua = asuint(a), ub = asuint(b); + const uint ea = (ua >> 23u) & 255u, eb = (ub >> 23u) & 255u; + if ((asuint(r) & 0x7fffffffu) == 0u && ea != 0u && eb != 0u && ea + eb == 127u) { + const uint64_t product = (uint64_t)((ua & 0x7fffffu) | 0x800000u) * (uint64_t)((ub & 0x7fffffu) | 0x800000u); + const uint64_t normal = (uint64_t)1u << 47u; + if (product >= normal - ((uint64_t)1u << 23u) && product < normal) + return asfloat(((ua ^ ub) & 0x80000000u) | 0x00800000u); + } + return r; +} +float m1_scale(float a, float b) +{ + float r = a * b; + [branch] if (and(abs(r) == 0.0f, abs(a) >= asfloat(0x00800000u))) r = m1_scale_ref(a, b); + return r; +} +#endif #if POST_OUT == 3 // The direct form's stored value. RGBA16F output with output_copy (nd_output_rne16): the HIP output-copy bytes, // framebuffer_half (clamp, RNE16; NaN passes), since typed RGBA16F stores round toward zero on this driver; the typed @@ -286,10 +367,8 @@ TexF tex_features(uint dw) // r2_features of the texel at dword dw return f; } -// 8-byte arena loads with their alignment made visible to the driver: RWByteAddressBuffer.Load2 / Load4 at a computed -// offset is known to be 4-byte aligned only, so each became two / four global_load_b32. The history (hist_prev) and the -// A8 features are the runtime's own allocations (256-byte aligned) and every offset formed on them here is a multiple of -// 8 bytes, so clearing the address's low 3 bits changes no address; the driver then issues global_load_b64. +// 8-byte arena loads: mask the 256-byte-aligned base pointers once at the scalar level (keeping 8-byte alignment +// provable for RADV/ACO without emitting per-load v_and_b32 or blocking immediate offset folding on AMD DX12). uint2 ld64_a8(uint a) { return wg_mem.Load2(a & ~7u); } uint4 ld128_a8(uint a) { return wg_mem.Load4(a & ~7u); } @@ -307,7 +386,7 @@ TfRaw tf_fetch(int idx, int col, int row PD_P) #else t.c = wg_ld4f(color, ui * 16u); #endif - uint2 d = ld64_a8(A8 + ui * 8u); + uint2 d = wg_mem.Load2((A8 & ~7u) + ui * 8u); t.d0 = d.x; t.d1 = d.y; t.c01 = wg_ld32(C4, ui * 4u); @@ -321,8 +400,8 @@ TfRaw tf_fetch(int idx, int col, int row PD_P) return t; } -#if POST_OUT == 3 -// The direct form's staging fetch of texel i = mini(lane, ilast) of footprint rows r0 ..., columns c0 ... (ncol per +#if WG_POST_OPT +// Staging fetch of texel i = mini(lane, ilast) of footprint rows r0 ..., columns c0 ... (ncol per // row): (row, column) = (st_r, st_col) on lane < ilast + 1 (the lane's own texel, fixed per lane), else those of texel // ilast (wave-uniform); the same texel and clamps as post_body's other forms TfRaw pd_stage_fetch(int lane, int ilast, int st_r, int st_col, float inv_ncol_u, int r0, int c0, int ncol PD_P) @@ -338,7 +417,7 @@ TfRaw pd_stage_fetch(int lane, int ilast, int st_r, int st_col, float inv_ncol_u } #endif -#if WG_TF_TWO && POST_OUT != 3 +#if WG_TF_TWO && !WG_PO_STAGE // The buffer forms' second staged texel of the lane: i = mini(lane + kThreads, nstage - 1), the first texel's formula TfRaw tf_stage2(int lane, int nstage, float inv_ncol, int r0, int c0, int ncol PD_P) { @@ -361,6 +440,9 @@ void tf_put(uint i, TfRaw r, float e PD_P) // reciprocal form (3 operations per channel, its own exact fallback lanes), as pd_normalize float4 c = r.c; if (pd_div_on(pd_rc, pd_pi1)) c.xyz = pd_xor(pd_div3(r.c.xyz)); +#elif POST_OUT == 0 && defined(WG_STAGED_PIDIV) + float4 c = r.c; + c.xyz = asfloat(asuint(pidiv3(r.c.xyz, pd_div, g_z)) ^ g_z); #else const float4 c = r.c; #endif @@ -462,31 +544,36 @@ float3 history_cr_span(float qx, float qy) const float fx0 = floor(tx), fy0 = floor(ty); const int ix = (int)fx0, iy = (int)fy0; const uint pitch = (uint)P_dw * 8u; + // pitch & 0xfffff8 == pitch & 0xffffff (pitch is a multiple of 8): the same 24-bit multiplicand, but a mask whose + // low three bits are clear, so that a product with it is visibly a multiple of 8 to the driver (the Linux compiler + // otherwise cannot prove 8-byte alignment of the history addresses and splits the 16-byte loads) + const uint pitch24 = pitch & 0xfffff8u; [branch] if (WaveActiveAllTrue(and((uint)(ix - 1) <= (uint)(P_dw - 4), (uint)(iy - 1) <= (uint)(P_dh - 4)))) { // O1: hist_prev + (ix - 1) 8 + (iy - 1) pitch == ix 8 + iy pitch + (hist_prev - 8 - pitch) mod 2^32, one // lshl_add + one mad_u24 (iy in [1, P_dh - 3] and pitch = 8 P_dw < 2^24, so the 24-bit product is the full one) // (the constant opaque, g_z: the driver would otherwise split it again into its parts, one add each) #if WG_POST_CUTS - uint b0 = mul24((uint)iy, pitch) + ((uint)ix * 8u + ((hist_prev - 8u - pitch) ^ g_z)); + uint b0 = mul24((uint)iy, pitch24) + (uint)ix * 8u + ((((hist_prev & ~7u) - 8u - pitch) ^ g_z) & ~7u); #else - uint b0 = hist_prev + (uint)(ix - 1) * 8u + mul24((uint)(iy - 1), pitch); + uint b0 = (hist_prev & ~7u) + (uint)(ix - 1) * 8u + mul24((uint)(iy - 1), pitch24); #endif #if defined(OP_POST_MUTANT) && OP_POST_MUTANT == 4 // test-only mutant (byte check must catch it): history base +8 b0 += 8u; #endif const uint b1 = b0 + pitch, b2 = b0 + 2u * pitch, b3 = b0 + 3u * pitch; - const uint4 a0 = ld128_a8(b0 + 8u), a10 = ld128_a8(b1), a11 = ld128_a8(b1 + 16u); - const uint4 a20 = ld128_a8(b2), a21 = ld128_a8(b2 + 16u), a3 = ld128_a8(b3 + 8u); + const uint4 a0 = wg_mem.Load4(b0 + 8u), a10 = wg_mem.Load4(b1), a11 = wg_mem.Load4(b1 + 16u); + const uint4 a20 = wg_mem.Load4(b2), a21 = wg_mem.Load4(b2 + 16u), a3 = wg_mem.Load4(b3 + 8u); return cr_sum(a0.xy, a0.zw, a10.xy, a10.zw, a11.xy, a11.zw, a20.xy, a20.zw, a21.xy, a21.zw, a3.xy, a3.zw, cr_weights(tx - fx0), cr_weights(ty - fy0)); } - const uint ro0 = mul24((uint)clampi(iy - 1, 0, P_dh - 1), pitch), ro1 = mul24((uint)clampi(iy, 0, P_dh - 1), pitch); - const uint ro2 = mul24((uint)clampi(iy + 1, 0, P_dh - 1), pitch), ro3 = mul24((uint)clampi(iy + 2, 0, P_dh - 1), pitch); - const uint c0 = hist_prev + (uint)clampi(ix - 1, 0, P_dw - 1) * 8u, c1 = hist_prev + (uint)clampi(ix, 0, P_dw - 1) * 8u; - const uint c2 = hist_prev + (uint)clampi(ix + 1, 0, P_dw - 1) * 8u, c3 = hist_prev + (uint)clampi(ix + 2, 0, P_dw - 1) * 8u; - return cr_sum(ld64_a8(ro0 + c1), ld64_a8(ro0 + c2), ld64_a8(ro1 + c0), ld64_a8(ro1 + c1), - ld64_a8(ro1 + c2), ld64_a8(ro1 + c3), ld64_a8(ro2 + c0), ld64_a8(ro2 + c1), - ld64_a8(ro2 + c2), ld64_a8(ro2 + c3), ld64_a8(ro3 + c1), ld64_a8(ro3 + c2), + const uint hp8 = hist_prev & ~7u; + const uint ro0 = mul24((uint)clampi(iy - 1, 0, P_dh - 1), pitch24), ro1 = mul24((uint)clampi(iy, 0, P_dh - 1), pitch24); + const uint ro2 = mul24((uint)clampi(iy + 1, 0, P_dh - 1), pitch24), ro3 = mul24((uint)clampi(iy + 2, 0, P_dh - 1), pitch24); + const uint c0 = hp8 + (uint)clampi(ix - 1, 0, P_dw - 1) * 8u, c1 = hp8 + (uint)clampi(ix, 0, P_dw - 1) * 8u; + const uint c2 = hp8 + (uint)clampi(ix + 1, 0, P_dw - 1) * 8u, c3 = hp8 + (uint)clampi(ix + 2, 0, P_dw - 1) * 8u; + return cr_sum(wg_mem.Load2(ro0 + c1), wg_mem.Load2(ro0 + c2), wg_mem.Load2(ro1 + c0), wg_mem.Load2(ro1 + c1), + wg_mem.Load2(ro1 + c2), wg_mem.Load2(ro1 + c3), wg_mem.Load2(ro2 + c0), wg_mem.Load2(ro2 + c1), + wg_mem.Load2(ro2 + c2), wg_mem.Load2(ro2 + c3), wg_mem.Load2(ro3 + c1), wg_mem.Load2(ro3 + c2), cr_weights(tx - fx0), cr_weights(ty - fy0)); } @@ -499,6 +586,9 @@ float3 fallback_rgb(int fx, int fy PD_P) const float4 c = pd_normalize(pd_raw_color(mul24((uint)fy, (uint)P_rw) + (uint)fx, fx, fy, pd_rc), pd_rc, pd_pi1); #else float4 c = wg_ld4f(color, mul24((uint)fy, (uint)P_rw * 16u) + (uint)fx * 16u); +#if POST_OUT == 0 && defined(WG_STAGED_PIDIV) + c.xyz = asfloat(asuint(pidiv3(c.xyz, pd_div, g_z)) ^ g_z); +#endif #endif return float3(enc_e(opq(g_e_prev * c.x)), enc_e(opq(g_e_prev * c.y)), enc_e(opq(g_e_prev * c.z))); } @@ -824,8 +914,8 @@ void tf_row_sync() #endif } -#if POST_OUT == 3 -// One vertical item of the direct form (post_body's step 3): output pixel (xg, y), ring column xo, its first ring row +#if WG_POST_OPT +// One vertical item (post_body's step 3): output pixel (xg, y), ring column xo, its first ring row // urel = 3 pr + 2 dy past the pass's first row pair, and the lane phase's filter weights wa = (w0, w4), wb = (w1, w3) as // FP16 bit pairs. post_body calls it with per-lane values fixed for the walk on the first pass (it = lane). void pd_vitem(int y, int xg, int xo, int urel, uint wa, uint wb, int p_next, bool interior, int s0, int r_first, bool lut, @@ -865,6 +955,7 @@ void pd_vitem(int y, int xg, int xo, int urel, uint wa, uint wb, int p_next, boo } #else const half w0 = hbox(wa), w4 = hbox(wa >> 16), w1 = hbox(wb), w3 = hbox(wb >> 16); +#if POST_OUT == 3 if (lut) { // the output values T[r] (wg_f16lut.hlsli, lev-f16lut d7149e2): the chain below, looked up float3 res; [unroll] for (int c = 0; c < 3; ++c) { @@ -874,6 +965,7 @@ void pd_vitem(int y, int xg, int xo, int urel, uint wa, uint wb, int p_next, boo native_direct_output[uint2((uint)xg, (uint)y)] = float4(res, 1.0f); return; } +#endif float vo[3], qv[3]; bool vsmall = false; [unroll] for (int c = 0; c < 3; ++c) { @@ -886,6 +978,7 @@ void pd_vitem(int y, int xg, int xo, int urel, uint wa, uint wb, int p_next, boo if (WaveActiveAnyTrue(vsmall)) { // Dec's polynomial only when some lane needs it (post.hip's branches) [unroll] for (int c = 0; c < 3; ++c) vo[c] = qv[c] < kDecPolyMax ? dec_m1_poly(qv[c]) : vo[c]; } +#if POST_OUT == 3 // Match the staged FP32 output, optional scale_rgb, then Converter's typed output. opq preserves the // first pass's rounding boundary: the driver must not regroup vo * (dec_scale * nd_color_pi). const float3 result = float3(mul_nz(vo[0], dec_scale), mul_nz(vo[1], dec_scale), mul_nz(vo[2], dec_scale)); @@ -902,6 +995,24 @@ void pd_vitem(int y, int xg, int xo, int urel, uint wa, uint wb, int p_next, boo if (zr) native_direct_output[uint2((uint)xg, (uint)y)] = float4(ex, 1.0f); } } +#else + const uint o = mul24((uint)y, (uint)ow * 12u) + mul24((uint)xg, 12u); +#if defined(WG_STAGED_PIDIV) + { // _pf kernels run only when pi != 1: the scale_rgb fold is unconditional (no pi == 1 copy of the store) + const float3 res = float3(mul_nz(vo[0], dec_scale), mul_nz(vo[1], dec_scale), mul_nz(vo[2], dec_scale)); + const float3 so = float3(m1_scale(res.x, pi_arg), m1_scale(res.y, pi_arg), m1_scale(res.z, pi_arg)); + wg_mem.Store3(out_p + o, uint3(asuint(so.x), asuint(so.y), asuint(so.z))); + } +#else + [branch] if (pi_arg == 1.0f) { + wg_mem.Store3(out_p + o, uint3(asuint(vo[0] * dec_scale), asuint(vo[1] * dec_scale), asuint(vo[2] * dec_scale))); + } else { // the runtime's scale_rgb folded in (m_pf_fold = 0, or a pi whose division window is invalid) + const float3 res = float3(mul_nz(vo[0], dec_scale), mul_nz(vo[1], dec_scale), mul_nz(vo[2], dec_scale)); + const float3 so = float3(m1_scale(res.x, pi_arg), m1_scale(res.y, pi_arg), m1_scale(res.z, pi_arg)); + wg_mem.Store3(out_p + o, uint3(asuint(so.x), asuint(so.y), asuint(so.z))); + } +#endif +#endif } // item it's (y - 2 p_next, xo, urel, wa, wb) (post_body's decomposition of an item index) @@ -939,10 +1050,13 @@ WG_KERNEL(post_tf_p12_diet_vsit) #endif if (P_dw < 4) return; g_z = (uint)ow >> 31; // 0 (ow > 0), unknown to the compiler +#if POST_OUT == 0 && defined(WG_STAGED_PIDIV) + const PiDiv pd_div = pidiv_make((uint)P_pad0); +#endif g_e = P_e; g_e_prev = P_e_prev; g_ratio = P_ratio; -#if POST_OUT != 3 +#if !WG_PO_EXPO float dec_scale = dec_scale_arg; if (expo != 0u) { // kDiet: ratio and dec_scale precomputed in the exposure pair float e0 = unif(wg_ldf(expo, 0u)), e1 = unif(wg_ldf(expo, 4u)); @@ -987,8 +1101,8 @@ WG_KERNEL(post_tf_p12_diet_vsit) nstage = ncol * nrow < kTfCap ? ncol * nrow : kTfCap; } TfRaw raw; -#if POST_OUT == 3 - // Direct form: texel i = mini(lane, nstage - 1) as below, but its footprint row and clamped column are fixed per lane +#if WG_PO_STAGE + // texel i = mini(lane, nstage - 1) as below, but its footprint row and clamped column are fixed per lane // for lane < nstage (opaque: computed once) and wave-uniform for the other lanes (texel nstage - 1: scalar ALU) const float inv_ncol_u = unif(inv_ncol); const int st_r = (int)(((float)lane + 0.5f) * inv_ncol); @@ -1012,8 +1126,8 @@ WG_KERNEL(post_tf_p12_diet_vsit) TfRaw raw2 = tf_stage2(lane, nstage, inv_ncol, r0, c0, ncol PD_A); #endif #endif -#if POST_OUT == 3 - // Direct form: the per-launch values after the first staging loads (lev-f16lut 1a9daed: with the exposure-pair loads +#if WG_PO_EXPO + // per-launch values after the first staging loads (lev-f16lut 1a9daed: with the exposure-pair loads // first, every wave waited for them before issuing any texel load) float dec_scale = dec_scale_arg; if (expo != 0u) { // kDiet: ratio and dec_scale precomputed in the exposure pair @@ -1023,12 +1137,17 @@ WG_KERNEL(post_tf_p12_diet_vsit) g_ratio = unif(wg_ldf(expo, 12u)); dec_scale = unif(wg_ldf(expo, 16u)); } +#if POST_OUT == 3 // the output table of this frame (wg_f16lut.hlsli; color: the table, 0 = none), wave-uniform #if WG_LZ_ANALYTIC const bool lut = false; // the table is indexed by an FP16 filter result (the original's); the analytic one is FP32 #else const bool lut = WaveReadLaneFirst(f16lut_valid(color, dec_scale, nd_color_pi, nd_output_rne16) ? 1u : 0u) != 0u; #endif +#endif +#endif +#if POST_OUT != 3 + const bool lut = false; #endif // this lane's D column (fixed over the walk) @@ -1046,7 +1165,7 @@ WG_KERNEL(post_tf_p12_diet_vsit) const uint2 mo_dims = uint2(0u, 0u); #endif -#if POST_OUT == 3 +#if WG_PO_HH // the horizontal pass's lane roles (row hk, channel hc, cell hg) and its scratch offsets: fixed per lane const int hk_l = wl >= 30 ? 1 : 0, hrem_l = wl - 30 * hk_l, hc_l = hrem_l >= 20 ? 2 : (hrem_l >= 10 ? 1 : 0), hg_l = hrem_l - 10 * hc_l; @@ -1054,6 +1173,8 @@ WG_KERNEL(post_tf_p12_diet_vsit) const uint h_src = ((uint)hk_l * kRowDw + (uint)hc_l * 32u + (uint)hg_l * 3u) ^ g_z; const uint h_dst = ((uint)hk_l * kRowDw + (uint)hc_l * (uint)kTfOutX + (uint)hg_l * 4u) ^ g_z; const bool h_lane = wl < 60; +#endif +#if WG_PO_VV // the vertical pass's first item of each step is it = lane: its values, fixed for the walk (opaque: computed once) int v_yrel, v_xo, v_urel; uint v_wa, v_wb; @@ -1128,7 +1249,7 @@ WG_KERNEL(post_tf_p12_diet_vsit) // order): each texel's features are read from LDS once for both rows. Row y0 + 1's sums wait in gnext. Gather gk; if (k == 0) { -#if POST_OUT == 3 +#if WG_PO_GATH // unrolled: the first texel starts the sums from zeros as operands (no zero moves) and the loop's // overhead goes (78 VGPRs). The colour sums start from an opaque +0 (gather_zero_opq): with a // literal 0 the driver turns fma(w, ec, +0) into w * ec (a -0 product would stay -0). @@ -1174,7 +1295,7 @@ WG_KERNEL(post_tf_p12_diet_vsit) wg_st64(hist_out, mul24((uint)y, (uint)P_dw * 8u) + (uint)x * 8u, he); // display values (FP16) of the 64 columns -> scratch row slot + k: lanes 2m, 2m + 1 share a dword const uint srow = scr + (uint)k * kRowDw; -#if POST_OUT == 3 +#if WG_PO_QUAD { // the partner's two dwords (c0 | c1 << 16, c2), then the even lane's three packed dwords (the same bits) const uint nx = QuadReadAcrossX(de.x), ny = QuadReadAcrossX(de.y); const uint d0 = (de.x & 0xffffu) | (nx << 16), d1 = (de.x >> 16) | (nx & 0xffff0000u); @@ -1199,7 +1320,7 @@ WG_KERNEL(post_tf_p12_diet_vsit) #endif } // reduced history: mean of H^ over the 2 x 2 block, the partner column in lane ^ 1 -#if POST_OUT == 3 +#if WG_PO_RH // two code chains for the three channels: chain a is channel 0 on the even lane and channel 1 on the odd lane // (its sum hsum_o[1] + hsum_e[1]: the even lane's hsum_e[1] + hsum_o[1] commuted, equal but for a NaN's // payload, and every NaN m gives the code of enc_arg = 1e-4), chain b channel 2; the odd lane's code a comes @@ -1235,7 +1356,7 @@ WG_KERNEL(post_tf_p12_diet_vsit) r0 = floor_i(pos_y(ys) - 0.5f) - 1; int nrow = floor_i(pos_y(yl) - 0.5f) + 2 - r0 + 1; nstage = ncol * nrow < kTfCap ? ncol * nrow : kTfCap; -#if POST_OUT == 3 +#if WG_PO_STAGE raw = pd_stage_fetch(lane, nstage - 1 < 0 ? 0 : nstage - 1, st_rx, st_col, inv_ncol_u, r0, c0, ncol PD_A); #if WG_TF_TWO raw2 = pd_stage_fetch(lane2, nstage - 1 < 0 ? 0 : nstage - 1, st_rx2, st_col2, inv_ncol_u, r0, c0, ncol PD_A); @@ -1253,7 +1374,7 @@ WG_KERNEL(post_tf_p12_diet_vsit) // horizontal pass of the wave's two rows: lane (row hk, channel hc, cell hg), output columns 4 hg ... 4 hg + 3 tf_row_sync(); -#if POST_OUT == 3 +#if WG_PO_HH const bool hact = and(wact, h_lane); const int hk = hk_l; #else @@ -1262,13 +1383,13 @@ WG_KERNEL(post_tf_p12_diet_vsit) const int hk = hl >= 30 ? 1 : 0, hrem = hl - 30 * hk, hc = hrem >= 20 ? 2 : (hrem >= 10 ? 1 : 0), hg = hrem - 10 * hc; #endif -#if POST_OUT == 3 +#if WG_PO_HH uint hv[4]; // set and used on the hact lanes only #else uint hv[4] = { 0u, 0u, 0u, 0u }; #endif if (hact) { -#if POST_OUT == 3 +#if WG_PO_HH const uint src = scr + h_src; #else const uint src = scr + (uint)hk * kRowDw + (uint)hc * 32u + (uint)hg * 3u; @@ -1331,7 +1452,7 @@ WG_KERNEL(post_tf_p12_diet_vsit) } tf_row_sync(); if (hact) { -#if POST_OUT == 3 +#if WG_PO_HH const uint dst = scr + h_dst; #else const uint dst = scr + (uint)hk * kRowDw + (uint)hc * (uint)kTfOutX + (uint)hg * 4u; @@ -1350,7 +1471,7 @@ WG_KERNEL(post_tf_p12_diet_vsit) const int nitems = (p_rdy - p_next) * 2 * kTfOutX; const bool interior = and(3 * p_next - 2 >= 0, 3 * p_rdy + 1 <= P_dh - 1); const int s0 = interior ? (3 * p_next - 2 - r_first) % kRing : 0; -#if POST_OUT == 3 +#if WG_PO_VV if (lane < nitems) pd_vitem(2 * p_next + v_yrel, v_xg, v_xo, v_urel, v_wa, v_wb, p_next, interior, s0, r_first, lut, dec_scale PD_A); [loop] for (int it = lane + kThreads; it < nitems; it += kThreads) { @@ -1424,7 +1545,17 @@ WG_KERNEL(post_tf_p12_diet_vsit) } #if POST_OUT == 0 const uint o = mul24((uint)y, (uint)ow * 12u) + mul24((uint)xg, 12u); - wg_mem.Store3(out_p + o, uint3(asuint(vo[0] * dec_scale), asuint(vo[1] * dec_scale), asuint(vo[2] * dec_scale))); + [branch] if (pi_arg == 1.0f) { + wg_mem.Store3(out_p + o, uint3(asuint(vo[0] * dec_scale), asuint(vo[1] * dec_scale), asuint(vo[2] * dec_scale))); + } else { + // The runtime's scale_rgb folded in (native D3D12 only; pi_arg = the frame's pre-exposure, 1 otherwise): + // native_scale(v dec_scale, pi) per channel, the stored FP32 value of the staged route. mul_nz keeps the + // first product's rounding (the driver would regroup v (dec_scale pi)); the repair of a flushed tiny + // product runs only on the lanes whose product is zero (as native_direct_scale). + const float3 res = float3(mul_nz(vo[0], dec_scale), mul_nz(vo[1], dec_scale), mul_nz(vo[2], dec_scale)); + const float3 so = float3(m1_scale(res.x, pi_arg), m1_scale(res.y, pi_arg), m1_scale(res.z, pi_arg)); + wg_mem.Store3(out_p + o, uint3(asuint(so.x), asuint(so.y), asuint(so.z))); + } #else // framebuffer_half((v dec_scale) pi): clamp to +-65504 (NaN passes), round to FP16 to nearest even; alpha 1. opq: // the driver would otherwise regroup the two uniform factors into v (dec_scale pi) diff --git a/clean/dx12/kernels/post_filter.hlsl b/clean/dx12/kernels/post_filter.hlsl index d007f41c..f7e0d666 100644 --- a/clean/dx12/kernels/post_filter.hlsl +++ b/clean/dx12/kernels/post_filter.hlsl @@ -25,7 +25,9 @@ // expo are not read); l_post_filter_direct_ldr: its direct form, stored as l_post_filter_direct stores. // // @wg-kernel w64/post_filter_c1_s4 co=post_w64.co entry=post_filter_c1_s4 block=64 wave=64 args=p,p,u,u,u,u,u,p +// @wg-kernel w64/post_filter_c1_s4 co=post_w64__orig.co file=w64__post_filter_c1_s4__orig entry=post_filter_c1_s4 block=64 wave=64 args=p,p,u,u,u,u,u,p,u,u,u,u,u defines=WG_LZ_ORIG=1 // @wg-kernel l_post_filter_direct co=- entry=post_filter_c1_s4 block=64 wave=64 args=p,p,u,u,u,u,u,p rs=direct defines=WG_DIRECT_TEXTURES=1 +// @wg-kernel l_post_filter_direct_orig co=- entry=post_filter_c1_s4 block=64 wave=64 args=p,p,u,u,u,u,u,p,u,u,u,u,u rs=direct defines=WG_DIRECT_TEXTURES=1,WG_LZ_ORIG=1 // @wg-kernel l_post_filter_ldr co=l_post.co entry=post_filter_c1_s4 block=64 wave=64 args=p,p,u,u,u,u,u,p defines=WG_FILTER_LDR=1 // @wg-kernel l_post_filter_direct_ldr co=- entry=post_filter_c1_s4 block=64 wave=64 args=p,p,u,u,u,u,u,p rs=direct defines=WG_DIRECT_TEXTURES=1,WG_FILTER_LDR=1 #include "wg_platform.hlsli" @@ -38,6 +40,9 @@ WG_ARGS_BEGIN int dw, dh, ow, oh; float dec_scale_arg; uint expo; // pointer (0 = null) +#if defined(WG_LZ_ORIG) + uint lz_w0, lz_w1, lz_w2, lz_w3, lz_w4; // FP16 bit patterns of the original 5-tap filter weights +#endif WG_ARGS_END static const float kLz0 = asfloat(0xbdba3b4bu), kLz1 = asfloat(0x3de71ca9u), kLz2 = asfloat(0x3f23b70fu); @@ -66,6 +71,52 @@ float dec_m1_poly(float qc) return t * y; } +#if defined(WG_LZ_ORIG) +// Original 5-tap FP16 Lanczos filter (post.hip WG_LZ_PROFILE=2, post.hlsl lz5_original): boxed FP16 bit patterns. +half hbox(uint v) { return asfloat16((uint16_t)(v & 0xffffu)); } +uint hunbox(half v) { return (uint)asuint16(v); } +uint lz5_original(uint t0b, uint t1b, uint t2b, uint t3b, uint t4b, half w0, half w1, half w2, half w3, half w4) +{ + half t0 = hbox(t0b), t1 = hbox(t1b), t2 = hbox(t2b), t3 = hbox(t3b), t4 = hbox(t4b); + half a = mad(w0, t0, (half)0.0); + a = mad(w1, t1, a); + a = mad(w2, t2, a); + a = mad(w3, t3, a); + a = mad(w4, t4, a); + half mid_lo = min(min(t1, t2), t3), mid_hi = max(max(t1, t2), t3); + half lo = min(min(mid_lo, t0), t4), hi = max(max(mid_hi, t0), t4); + return hunbox(min(max(a, lo), hi)); +} +uint lz5e_o(uint t0, uint t1, uint t2, uint t3, uint t4) +{ + return lz5_original(t0, t1, t2, t3, t4, hbox(lz_w0), hbox(lz_w1), hbox(lz_w2), hbox(lz_w3), hbox(lz_w4)); +} +uint lz5o_o(uint t0, uint t1, uint t2, uint t3, uint t4) +{ + return lz5_original(t0, t1, t2, t3, t4, hbox(lz_w4), hbox(lz_w3), hbox(lz_w2), hbox(lz_w1), hbox(lz_w0)); +} +uint4 row4_o(int pitch, int plane, int r, int m, bool fast, int c) +{ + const uint row = (uint)(r * pitch + c * plane) * 2u; + const int c0 = 6 * m - 2; + uint q[5]; + [unroll] for (int i = 0; i < 5; ++i) { + if (fast) { + q[i] = wg_ld32(display, row + (uint)(c0 + 2 * i) * 2u); + } else { + q[i] = wg_ld16(display, row + (uint)clampi(c0 + 2 * i, 0, dw - 1) * 2u) | + (wg_ld16(display, row + (uint)clampi(c0 + 2 * i + 1, 0, dw - 1) * 2u) << 16); + } + } + uint t[10]; + [unroll] for (int j = 0; j < 5; ++j) { + t[2 * j] = q[j] & 0xffffu; + t[2 * j + 1] = q[j] >> 16; + } + return uint4(lz5e_o(t[0], t[1], t[2], t[3], t[4]), lz5o_o(t[2], t[3], t[4], t[5], t[6]), + lz5e_o(t[3], t[4], t[5], t[6], t[7]), lz5o_o(t[5], t[6], t[7], t[8], t[9])); +} +#else // lz5 of post.hip, profile 0: v = w0 t0, then fma per tap; med3 with the taps' range (the taps are finite) float lz5a(float t0, float t1, float t2, float t3, float t4, float w0, float w1, float w3, float w4) { @@ -112,6 +163,7 @@ float4 row4(int pitch, int plane, int r, int m, bool fast, int c) row_c1(pitch, plane, r, m, fast, c, h); return float4(h[0], h[1], h[2], h[3]); } +#endif #if defined(WG_DIRECT_TEXTURES) // framebuffer_half's clamp (compares: a NaN passes), then wg_f2h (round to nearest even, NaN kept) @@ -154,9 +206,14 @@ WG_KERNEL(post_filter_c1_s4) // the sliding window: horizontal results of rows 3p - 2 + k in r0 ... r6 (named vectors, shifted one by one: a // shifted local array was compiled into a block copy that does not keep an overlapping shift's order) +#if defined(WG_LZ_ORIG) + uint4 r0 = 0u, r1 = 0u, r2 = 0u, r3 = 0u, r4 = 0u, r5 = 0u, r6 = row4_o(pitch, plane, + clampi(3 * p0 - 2, 0, dh - 1), m, fast, c); +#else float4 r0 = 0.0f, r1 = 0.0f, r2 = 0.0f, r3 = 0.0f, r4 = 0.0f, r5 = 0.0f, r6 = row4(pitch, plane, clampi(3 * p0 - 2, 0, dh - 1), m, fast, c); +#endif [loop] for (int st = -1; st < kS; ++st) { const int p = p0 + st; if (2 * p >= oh) break; @@ -164,16 +221,27 @@ WG_KERNEL(post_filter_c1_s4) r1 = r4; r2 = r5; r3 = r6; +#if defined(WG_LZ_ORIG) + r4 = row4_o(pitch, plane, clampi(3 * p + 2, 0, dh - 1), m, fast, c); + r5 = row4_o(pitch, plane, clampi(3 * p + 3, 0, dh - 1), m, fast, c); + r6 = row4_o(pitch, plane, clampi(3 * p + 4, 0, dh - 1), m, fast, c); +#else r4 = row4(pitch, plane, clampi(3 * p + 2, 0, dh - 1), m, fast, c); r5 = row4(pitch, plane, clampi(3 * p + 3, 0, dh - 1), m, fast, c); r6 = row4(pitch, plane, clampi(3 * p + 4, 0, dh - 1), m, fast, c); +#endif if (st < 0) continue; [unroll] for (int dy = 0; dy < 2; ++dy) { const int y = 2 * p + dy; if (y >= oh) break; const uint o0 = (uint)(y * ow + 4 * m); [unroll] for (int i = 0; i < 4; ++i) { +#if defined(WG_LZ_ORIG) + const float r = f16tof32(dy == 0 ? lz5e_o(r0[i], r1[i], r2[i], r3[i], r4[i]) + : lz5o_o(r2[i], r3[i], r4[i], r5[i], r6[i])); +#else const float r = dy == 0 ? lz5e(r0[i], r1[i], r2[i], r3[i], r4[i]) : lz5o(r2[i], r3[i], r4[i], r5[i], r6[i]); +#endif #if defined(WG_FILTER_LDR) const float v = r; #else diff --git a/clean/dx12/kernels/swin_block.hlsl b/clean/dx12/kernels/swin_block.hlsl index 755ae841..1aabd52d 100644 --- a/clean/dx12/kernels/swin_block.hlsl +++ b/clean/dx12/kernels/swin_block.hlsl @@ -37,6 +37,12 @@ #ifndef SW_HYB #define SW_HYB 0 #endif +#ifndef SW_Q7_CHUNK +#define SW_Q7_CHUNK 0 // 1 (with SW_HYB): per-32-channel FP16-rounded WMMA chunks (oracle mm8="exact") +#endif +#if SW_Q7_CHUNK && !SW_HYB +#error "SW_Q7_CHUNK requires SW_HYB=1" +#endif #ifndef SW_HYB_MUT_ORDER #define SW_HYB_MUT_ORDER 0 // check mutants only: 1 one W2 chunk pair reversed, 2 the pair of every W2 group, // 3 the odd W2 groups in a second accumulator added at the end (one extra f32 rounding), @@ -99,15 +105,10 @@ #define SW_GELU_LATE0 0 #endif #endif -#if SW_HYB && (SW_GELU != 0 || SW_HEAD_UNROLL || SW_HEAD_PAIRS || SW_MLP_PAIRS || SW_MLP_STEP != 1 || SW_COMMIT_EARLY || \ - SW_N2_BATCH) -#error "SW_HYB: the hybrid kernels run the plain schedule (no M-form scheduling knobs)" -#endif -// (SW_SRC 3 and SW_OUT_COEF12 are allowed: the linears' prologue gives the block the same FP16 values as the x2 map, -// and the pack12 epilogue reads the same FP16 output, converted by the driver's RNE as the hybrid output point does) -#if SW_HYB &&(SW_ECL > 0 || SW_NORM1_EARLY || SW_NORM2_EARLY || SW_NORM_R2 || SW_SMAX_STAGED || SW_SMAX_ADDST || \ - SW_REV_PHI || SW_CLAMP_SKIP) -#error "SW_HYB: only the plain block path (no fused expand, no scheduling knobs) has the hybrid form so far" +// SW_ECL > 0 with SW_HYB (the hybrid decoder blocks with their expand fused in: swin_block_c96_add_ex_hyb, +// swin_block_c64_add_ex_hyb): SW_ADD only, plain FP8 (no q7c chunks), see hyb_fused_expand below +#if SW_HYB && (SW_GELU != 0 || (SW_ECL > 0 && (!SW_ADD || SW_Q7_CHUNK)) || SW_NORM_R2 || SW_SMAX_STAGED || SW_SMAX_ADDST || SW_REV_PHI || SW_CLAMP_SKIP || SW_N2_BATCH) +#error "SW_HYB: unsupported M-form knob enabled" #endif #if SW_HYB && SW_OUT_COEF12 && !COEF_CVT_HW #error "SW_HYB with SW_OUT_COEF12: COEF_CVT_HW 1 (the driver's RNE conversion of the hybrid output point)" @@ -186,8 +187,8 @@ WG_ARGS_END // order. #if defined(SW_HPU) #define HPU SW_HPU -#elif SW_C == 64 && SW_GELU != 0 -#define HPU 4 // MTH 16 +#elif SW_C == 64 && (SW_GELU != 0 || SW_HYB) +#define HPU 4 // MTH 16 (2 x 8 KB = 16 KB LDS -> 3-4 workgroups/CU instead of 2) #elif SW_C == 64 #define HPU 8 // MTH 16, limit 8 #elif SW_C == 96 @@ -597,7 +598,11 @@ void load_frags_g(uint base, uint off, out uint2 f[KC]) #ifndef SW_OUT_F16 #define SW_OUT_F16 0 #endif -#if (SW_SRC != 0 || (SW_OUT_F16 && !SW_HYB)) && (SW_ADD || SW_ECL > 0) +// The one exception outside the hybrid decoder: Model L's fast-mode decoder block (l_mode=fast, l_swin_fast.hlsl): the +// M-form chain (SW_HYB 0) with the skip, SW_SRC 2 (x by the token-grid mirror) + SW_ADD (xadd, the skip, by the fine one) +// + SW_OUT_F16, without a fused expand. +#define SW_L_FAST_DEC (SW_SRC == 2 && SW_ADD && SW_OUT_F16 && !SW_HYB && SW_ECL == 0) +#if (SW_SRC != 0 || (SW_OUT_F16 && !SW_HYB)) && (SW_ADD || SW_ECL > 0) && !SW_L_FAST_DEC #error "SW_SRC / SW_OUT_F16: plain blocks only (the hybrid C32 decoder: SW_OUT_F16 with SW_ADD, the skip)" #endif #ifndef SW_OUT_COEF12 @@ -637,9 +642,14 @@ void sw_load_halo_lin(uint base, int pr, int pc, int W, uint lane, uint hh, out const uint pix = (uint)((pr + 2) * (W + 4) + pc + 2); uint2 xq[2]; const uint plane1 = (uint)((H + 4) * (W + 4)) * 16u; - const uint4 v = wg_ld128(base, hh != 0u ? plane1 + pix * 4u : pix * 16u); // h = 1: .x = bytes 16..19 - xq[0] = uint2(v.x, hh != 0u ? 0u : v.y); - xq[1] = hh != 0u ? uint2(0u, 0u) : v.zw; + if (hh != 0u) { + xq[0] = uint2(wg_ld32(base, plane1 + pix * 4u), 0u); + xq[1] = uint2(0u, 0u); + } else { + const uint4 v = wg_ld128(base, pix * 16u); + xq[0] = v.xy; + xq[1] = v.zw; + } v8f b1[2], b2[2]; uint2 f1[2][2], f2[2][2]; lin_blob(linW1, lane, hh, b1, f1); @@ -762,6 +772,10 @@ void fused_expand(uint tail, uint e_lds, int nwx, int nwin, uint tid, int blk, u acc1 = wg_wmma_fp8(fa[it2][kc2], yf[1][kc2], acc1); } uint2 q0, q1; +#if SW_HYB + // the hybrid expand's FP8 point (expand_c96_hyb / expand_c128_hyb): E = FP8(RN16(be + We y)), hyb_q8_of_chain + q0 = hyb_q8_of_chain(acc0); q1 = hyb_q8_of_chain(acc1); +#else #if SW_CLAMP_SKIP if (sw_in448(sw_absmax8(sw_absmax8(0.0f, acc0), acc1))) { q0 = wg_pack_q8_nc_ags(acc0); q1 = wg_pack_q8_nc_ags(acc1); @@ -770,6 +784,7 @@ void fused_expand(uint tail, uint e_lds, int nwx, int nwin, uint tid, int blk, u { q0 = sw_pack_q8_v2(acc0); q1 = sw_pack_q8_v2(acc1); } +#endif uint slot0 = (0u + (t >> 2)) * 16u + (t & 3u) * 4u + k, slot1 = (4u + (t >> 2)) * 16u + (t & 3u) * 4u + k; sw_lds_st64(e_lds + slot0 * SW_C + hh * (SW_C / 2) + 8u * g, q0); sw_lds_st64(e_lds + slot1 * SW_C + hh * (SW_C / 2) + 8u * g, q1); @@ -777,6 +792,30 @@ void fused_expand(uint tail, uint e_lds, int nwx, int nwin, uint tid, int blk, u } #endif +#if SW_ECL > 0 && SW_HYB +// hyb_fused_expand (SW_HYB with SW_ECL): the hybrid decoder blocks read their expanded input E (the coarse mirror of the +// table's shared_dec_border, sw_coarse_src: the 2 x 2 group index mirrored, the sub-pixel kept) from the records the +// fused expand wrote, so a window's records cover the mirrored groups of its rows / columns (p0 even: the groups +// p0 / 2 and p0 / 2 + 1, whose mirrors are adjacent). sw_low0c(p0, n) = the smaller of the two mirrored groups of the +// window's first row / column p0 = 4 w - o of a map of n pixels (o even: the fused launches' offsets); sw_win_low0c = +// diet_c96.hlsli's sw_win_low0 with it (row base | column base << 16). +int sw_low0c(int p0, int n) +{ + const int g = p0 >> 1, nc = n >> 1; + return min(sw_mirror(g, nc), sw_mirror(g + 1, nc)); +} +uint sw_win_low0c(int nwx, int nwin, uint lane, int blk) +{ + int win = blk * 8 + (int)(lane & 7u); + win = win < nwin ? win : nwin - 1; + const int wy = win / nwx, wx = win - wy * nwx; + return (uint)sw_low0c(4 * wy - oy, H) | ((uint)sw_low0c(4 * wx - ox, W) << 16); +} +#define SW_WIN_LOW0 sw_win_low0c +#else +#define SW_WIN_LOW0 sw_win_low0 +#endif + #if SW_ECL > 0 #define SW_ENTRY swin_block_c96_add_ex_nc #elif SW_C == 64 @@ -832,11 +871,17 @@ WG_KERNEL(SW_ENTRY) uint2 xb[KC]; #endif #if SW_ECL > 0 - const uint lowp = sw_win_low0(nwx, nwin, lane, (int)wg_block_id()); + const uint lowp = SW_WIN_LOW0(nwx, nwin, lane, (int)wg_block_id()); fused_expand(w + L_TAIL, MAXU, nwx, nwin, tid, (int)wg_block_id(), lowp); const uint lpw = WaveReadLaneAt(lowp, wave_id); // this wave's window (win: the same clamp) - const int low = ((mr >> 1) - (int)(lpw & 0xffffu)) * 2 + ((mc >> 1) - (int)(lpw >> 16)); - const uint eslot = (tid >> 5) * 16u + (uint)low * 4u + (uint)(((mr & 1) << 1) | (mc & 1)); +#if SW_HYB + // the coarse source position of E (sw_coarse_src): the mirrored group, the member's own sub-pixel + const int mre = 2 * sw_mirror(pr >> 1, H >> 1) + (pr & 1), mce = 2 * sw_mirror(pc >> 1, W >> 1) + (pc & 1); +#else + const int mre = mr, mce = mc; +#endif + const int low = ((mre >> 1) - (int)(lpw & 0xffffu)) * 2 + ((mce >> 1) - (int)(lpw >> 16)); + const uint eslot = (tid >> 5) * 16u + (uint)low * 4u + (uint)(((mre & 1) << 1) | (mce & 1)); #elif SW_SRC == 1 v8f xf[KC]; sw_load_halo_f16(x, pr, pc, W, hh, xf); @@ -872,6 +917,9 @@ WG_KERNEL(SW_ENTRY) // Steps 1-2: a = q8(RMSNorm(x; gamma1)); the residual accumulator starts as x + bp. uint2 af[KC]; v8f acc[KC]; +#if SW_Q7_CHUNK + uint4 acc_h[KC]; +#endif { [unroll] for (uint k = 0; k < KC; ++k) { #if SW_SRC == 1 || SW_SRC == 3 @@ -889,15 +937,57 @@ WG_KERNEL(SW_ENTRY) #if SW_HYB // y = the original's norm (FP16 tree); a = FP8(y); the Wp chain starts at RN16(bp + x) { +#if SW_NORM1_EARLY + v8f y[KC]; + hyb_norm(acc, ng, hh, y); +#else const uint g1 = w + L_G1 + hh * (HALF * 4), bp = w + L_BP + hh * 32u; v8f gp[KC], y[KC]; [unroll] for (uint k1 = 0; k1 < KC; ++k1) gp[k1] = wg_load8f(g1, 32u * k1); hyb_norm(acc, gp, hh, y); +#endif [unroll] for (uint kd = 0; kd < KC; ++kd) { HD_ST8(8u * kd, acc[kd]); HD_ST8(8u * (KC + kd), y[kd]); } - [unroll] for (uint k3 = 0; k3 < KC; ++k3) { - af[k3] = hyb_q8(y[k3]); - acc[k3] = hyb_add16(acc[k3], wg_load8f(bp, 64u * k3)); +#if SW_Q7_CHUNK + uint2 af_l[KC]; +#if !SW_MEGA + float ym = 0.0f; + [unroll] for (uint km = 0; km < KC; ++km) ym = hyb_absmax8(ym, y[km]); + if (WaveActiveAllTrue(ym <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af_l[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af_l[k3] = wg_pack_q8_ags(y[k3]); } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af_l[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { +#if SW_NORM1_EARLY + acc_h[k3b] = hyb_rn16x8(sw_add8(acc[k3b], nb[k3b])); +#else + acc_h[k3b] = hyb_rn16x8(sw_add8(acc[k3b], wg_load8f(bp, 64u * k3b))); +#endif + } + HYB_Q7C_L2D(KC, af_l, af, hh); +#else +#if !SW_MEGA + float ym = 0.0f; + [unroll] for (uint km = 0; km < KC; ++km) ym = hyb_absmax8(ym, y[km]); + if (WaveActiveAllTrue(ym <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) af[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { +#if SW_NORM1_EARLY + acc[k3b] = hyb_add16(acc[k3b], nb[k3b]); +#else + acc[k3b] = hyb_add16(acc[k3b], wg_load8f(bp, 64u * k3b)); +#endif + } +#endif } #else const float r = norm_r(acc); @@ -952,6 +1042,176 @@ WG_KERNEL(SW_ENTRY) #endif uint2 uf[2]; uint4 vt[2]; +#if SW_Q7_CHUNK + // VMEM/LUT latency hiding: compute Wqk -> S = U^T U + B first, then interleave Wv (2*KC FP8 WMMAs) + // across hyb_softmax_pre (hyb_rcp16 global LUT load) and hyb_softmax_fin so the LUT load latency is hidden. + { + v8f accq0 = sw_zero8(), accq1 = sw_zero8(); + [unroll] for (uint kc2 = 0; kc2 < KC; kc2 += 2u) { + const uint2 fq00 = sw_lfrag_b(fb, (0u * KC + kc2) * 2u); + const uint2 fq10 = sw_lfrag_b(fb, (1u * KC + kc2) * 2u); + const uint2 fq01 = sw_lfrag_b(fb, (0u * KC + kc2 + 1u) * 2u); + const uint2 fq11 = sw_lfrag_b(fb, (1u * KC + kc2 + 1u) * 2u); + accq0 = wg_wmma_fp8(fq00, af[kc2], accq0); + accq1 = wg_wmma_fp8(fq10, af[kc2], accq1); + accq0 = wg_wmma_fp8(fq01, af[kc2 + 1u], accq0); + accq1 = wg_wmma_fp8(fq11, af[kc2 + 1u], accq1); + if (kc2 + 2u < KC) { + accq0 = hyb_round16(accq0); + accq1 = hyb_round16(accq1); + } + } + hyb_q8_pair(hyb_round16(accq0), hyb_round16(accq1), uf[0], uf[1]); + } +#if SW_C != 64 + const v8f bias = wg_load8f(biasl, hd * 1024u); +#endif + v8f s = wg_wmma_fp8(uf[0], uf[0], bias); + s = wg_wmma_fp8(uf[1], uf[1], s); + uint4 p; + { + // Issue chunk 0 of Wv before hyb_softmax_pre, then hide hyb_rcp16 global LUT latency + // behind the remaining Wv chunks before hyb_softmax_fin. + v8f accv0 = sw_zero8(), accv1 = sw_zero8(); + { + const uint2 fv00 = sw_lfrag_b(fb, (0u * KC + 0u) * 2u + 1u); + const uint2 fv10 = sw_lfrag_b(fb, (1u * KC + 0u) * 2u + 1u); + const uint2 fv01 = sw_lfrag_b(fb, (0u * KC + 1u) * 2u + 1u); + const uint2 fv11 = sw_lfrag_b(fb, (1u * KC + 1u) * 2u + 1u); + accv0 = wg_wmma_fp8(af[0], fv00, accv0); + accv1 = wg_wmma_fp8(af[0], fv10, accv1); + accv0 = wg_wmma_fp8(af[1], fv01, accv0); + accv1 = wg_wmma_fp8(af[1], fv11, accv1); + } + const HybSmaxPre sp = hyb_softmax_pre(s); + [unroll] for (uint kc2 = 2; kc2 < KC; kc2 += 2u) { + accv0 = hyb_round16(accv0); + const uint2 fv00 = sw_lfrag_b(fb, (0u * KC + kc2) * 2u + 1u); + const uint2 fv10 = sw_lfrag_b(fb, (1u * KC + kc2) * 2u + 1u); + const uint2 fv01 = sw_lfrag_b(fb, (0u * KC + kc2 + 1u) * 2u + 1u); + const uint2 fv11 = sw_lfrag_b(fb, (1u * KC + kc2 + 1u) * 2u + 1u); + accv0 = wg_wmma_fp8(af[kc2], fv00, accv0); + accv1 = hyb_round16(accv1); + accv1 = wg_wmma_fp8(af[kc2], fv10, accv1); + accv0 = wg_wmma_fp8(af[kc2 + 1u], fv01, accv0); + accv1 = wg_wmma_fp8(af[kc2 + 1u], fv11, accv1); + } + p = hyb_softmax_fin(sp); + vt[0] = wg_to_f16_ags(accv0); + vt[1] = wg_to_f16_ags(accv1); + } + uint2 of[2]; + { + v8f pv0 = wg_wmma_f16(vt[0], p, sw_zero8()); + v8f pv1 = wg_wmma_f16(vt[1], p, sw_zero8()); + of[0] = hyb_q7c_pv_q8(vt[0], p, hh, sw_zero(), pv0); + of[1] = hyb_q7c_pv_q8(vt[1], p, hh, sw_zero(), pv1); + } + // x1 += Wp[:, head hd] q8(o_hd): 2-tile software-pipelined acc_h unpack/pack with FP8 WMMAs (reduces RAW stalls) + { + uint2 fp[KC][2]; + [unroll] for (uint m = 0; m < KC; ++m) { + fp[m][0] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u); + fp[m][1] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u + 1u); + } + v8f t0 = hyb_h2f8(acc_h[0]); + t0 = wg_wmma_fp8(fp[0][0], of[0], t0); + [unroll] for (uint m2 = 0; m2 + 1u < KC; ++m2) { + v8f t1 = hyb_h2f8(acc_h[m2 + 1u]); + t0 = wg_wmma_fp8(fp[m2][1], of[1], t0); + t1 = wg_wmma_fp8(fp[m2 + 1u][0], of[0], t1); + acc_h[m2] = hyb_rn16x8(t0); + t0 = t1; + } + t0 = wg_wmma_fp8(fp[KC - 1u][1], of[1], t0); + acc_h[KC - 1u] = hyb_rn16x8(t0); + } +#elif SW_HYB && (SW_C != 96) + // VMEM/LUT latency hiding (SW_HYB, C != 96): compute Wqk -> S = U^T U + B first, then interleave Wv + // (2*KC FP8 WMMAs) across hyb_softmax_pre (exact FP32 e8 + hyb_rcp16 global LUT load) and hyb_softmax_fin. + { + uint2 fq0[KC], fq1[KC]; + [unroll] for (uint kc = 0; kc < KC; ++kc) { + fq0[kc] = sw_lfrag_b(fb, (0u * KC + kc) * 2u); + fq1[kc] = sw_lfrag_b(fb, (1u * KC + kc) * 2u); + } + v8f accq0 = sw_zero8(), accq1 = sw_zero8(); + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) { + accq0 = wg_wmma_fp8(fq0[kc2], af[kc2], accq0); + accq1 = wg_wmma_fp8(fq1[kc2], af[kc2], accq1); + } + const v8f rq0 = hyb_round16(accq0), rq1 = hyb_round16(accq1); + HD_ST8(HD_HEAD + 60u * hd + 0u, rq0); + HD_ST8(HD_HEAD + 60u * hd + 8u, rq1); +#if !SW_MEGA + hyb_q8_pair(rq0, rq1, uf[0], uf[1]); +#else + uf[0] = hyb_q8(rq0); + uf[1] = hyb_q8(rq1); +#endif + } +#if SW_C != 64 +#if SW_HEAD_UNROLL + const v8f bias = wg_load8f(w + L_BIAS, ((hd * 16u + t) * 2u + hh) * 32u); +#else + const v8f bias = wg_load8f(biasl, hd * 1024u); +#endif +#endif + // s = one 32-term FP8 op started at B (the position bias, FP16 values); the original's weights P + v8f s = wg_wmma_fp8(uf[0], uf[0], bias); + s = wg_wmma_fp8(uf[1], uf[1], s); + uint4 p; + { + v8f accv0 = sw_zero8(), accv1 = sw_zero8(); + [unroll] for (uint kv0 = 0; kv0 < KC / 2; ++kv0) { + const uint2 fv0 = sw_lfrag_b(fb, (0u * KC + kv0) * 2u + 1u); + const uint2 fv1 = sw_lfrag_b(fb, (1u * KC + kv0) * 2u + 1u); + accv0 = wg_wmma_fp8(af[kv0], fv0, accv0); + accv1 = wg_wmma_fp8(af[kv0], fv1, accv1); + } + const HybSmaxPre sp = hyb_softmax_pre(s); + [unroll] for (uint kv1 = KC / 2; kv1 < KC; ++kv1) { + const uint2 fv0 = sw_lfrag_b(fb, (0u * KC + kv1) * 2u + 1u); + const uint2 fv1 = sw_lfrag_b(fb, (1u * KC + kv1) * 2u + 1u); + accv0 = wg_wmma_fp8(af[kv1], fv0, accv0); + accv1 = wg_wmma_fp8(af[kv1], fv1, accv1); + } + p = hyb_softmax_fin(sp); + vt[0] = wg_to_f16_ags(accv0); + vt[1] = wg_to_f16_ags(accv1); +#if SW_HYB_DUMP + HD_ST8(HD_HEAD + 60u * hd + 16u, hyb_h2f8(vt[0])); + HD_ST8(HD_HEAD + 60u * hd + 24u, hyb_h2f8(vt[1])); +#endif + } + HD_ST8(HD_HEAD + 60u * hd + 32u, hyb_round16(s)); + HD_ST4(HD_HEAD + 60u * hd + 40u, p); + // o = A V (rows value channels, columns tokens) + uint2 of[2]; + { + const v8f pv0 = wg_wmma_f16(vt[0], p, sw_zero8()); + const v8f pv1 = wg_wmma_f16(vt[1], p, sw_zero8()); + const v8f rp0 = hyb_round16(pv0), rp1 = hyb_round16(pv1); + HD_ST8(HD_HEAD + 60u * hd + 44u, rp0); + HD_ST8(HD_HEAD + 60u * hd + 52u, rp1); +#if !SW_MEGA + hyb_q8_pair(rp0, rp1, of[0], of[1]); +#else + of[0] = hyb_q8(rp0); + of[1] = hyb_q8(rp1); +#endif + } + // x1 += Wp[:, head hd] q8(o_hd) + uint2 fp[KC][2]; + [unroll] for (uint m = 0; m < KC; ++m) { + fp[m][0] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u); + fp[m][1] = sw_lfrag_b(fb, QKV_FRAGS + m * 2u + 1u); + } + [unroll] for (uint m2 = 0; m2 < KC; ++m2) { + acc[m2] = wg_wmma_fp8(fp[m2][0], of[0], acc[m2]); + acc[m2] = wg_wmma_fp8(fp[m2][1], of[1], acc[m2]); + } +#else [unroll] for (uint mt = 0; mt < 2; ++mt) { uint2 fq[KC], fv[KC]; [unroll] for (uint kc = 0; kc < KC; ++kc) { @@ -1066,6 +1326,7 @@ WG_KERNEL(SW_ENTRY) acc[m2] = wg_wmma_fp8(fp[m2][0], of[0], acc[m2]); acc[m2] = wg_wmma_fp8(fp[m2][1], of[1], acc[m2]); } +#endif #if SW_NORM2_EARLY if (!last) { st_commit(stage, (buf ^ 1u) * MAXU, HEAD_BYTES / 16, tid); @@ -1093,18 +1354,75 @@ WG_KERNEL(SW_ENTRY) // Step 8: m = q8(RMSNorm(x1; gamma2)), then b2 into the residual accumulator. uint2 mf[KC]; -#if SW_HYB +#if SW_Q7_CHUNK + { +#if SW_NORM2_EARLY + v8f y[KC]; + hyb_norm_h(acc_h, ng2, hh, y); +#else + const uint g2 = w + L_G2 + hh * (HALF * 4), b2 = w + L_B2 + hh * 32u; + v8f gp[KC], y[KC]; + [unroll] for (uint k1 = 0; k1 < KC; ++k1) gp[k1] = wg_load8f(g2, 32u * k1); + hyb_norm_h(acc_h, gp, hh, y); +#endif + uint2 mf_l[KC]; +#if !SW_MEGA + float ym2 = 0.0f; + [unroll] for (uint km2 = 0; km2 < KC; ++km2) ym2 = hyb_absmax8(ym2, y[km2]); + if (WaveActiveAllTrue(ym2 <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf_l[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf_l[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf_l[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { + v8f s2 = hyb_h2f8(acc_h[k3b]); +#if SW_NORM2_EARLY + const v8f bv = nb2[k3b]; +#else + const v8f bv = wg_load8f(b2, 64u * k3b); +#endif + [unroll] for (uint i = 0; i < 8; ++i) s2.v[i] = s2.v[i] + bv.v[i]; + acc_h[k3b] = hyb_rn16x8(s2); + } + HYB_Q7C_L2D(KC, mf_l, mf, hh); + } +#elif SW_HYB { // z = RN16(the Wp chain); m = FP8(norm(z; g2')); the W2 chain starts at RN16(b2 + z) - [unroll] for (uint kz = 0; kz < KC; ++kz) acc[kz] = hyb_round16(acc[kz]); + uint4 acc_h2[KC]; + [unroll] for (uint kz = 0; kz < KC; ++kz) acc_h2[kz] = hyb_rn16x8(acc[kz]); +#if SW_NORM2_EARLY + v8f y[KC]; + hyb_norm_h(acc_h2, ng2, hh, y); +#else const uint g2 = w + L_G2 + hh * (HALF * 4), b2 = w + L_B2 + hh * 32u; v8f gp[KC], y[KC]; [unroll] for (uint k1 = 0; k1 < KC; ++k1) gp[k1] = wg_load8f(g2, 32u * k1); - hyb_norm(acc, gp, hh, y); - [unroll] for (uint kd = 0; kd < KC; ++kd) { HD_ST8(HD_Z + 8u * kd, acc[kd]); HD_ST8(HD_Y2 + 8u * kd, y[kd]); } - [unroll] for (uint k3 = 0; k3 < KC; ++k3) { - mf[k3] = hyb_q8(y[k3]); - acc[k3] = hyb_add16(acc[k3], wg_load8f(b2, 64u * k3)); + hyb_norm_h(acc_h2, gp, hh, y); +#endif +#if SW_HYB_DUMP + [unroll] for (uint kd = 0; kd < KC; ++kd) { HD_ST8(HD_Z + 8u * kd, hyb_h2f8(acc_h2[kd])); HD_ST8(HD_Y2 + 8u * kd, y[kd]); } +#endif +#if !SW_MEGA + float ym2 = 0.0f; + [unroll] for (uint km2 = 0; km2 < KC; ++km2) ym2 = hyb_absmax8(ym2, y[km2]); + if (WaveActiveAllTrue(ym2 <= 448.0f)) { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf[k3] = wg_pack_q8_nc_ags(y[k3]); + } else { + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf[k3] = wg_pack_q8_ags(y[k3]); + } +#else + [unroll] for (uint k3 = 0; k3 < KC; ++k3) mf[k3] = hyb_q8(y[k3]); +#endif + [unroll] for (uint k3b = 0; k3b < KC; ++k3b) { +#if SW_NORM2_EARLY + acc[k3b] = hyb_add16(hyb_h2f8(acc_h2[k3b]), nb2[k3b]); +#else + acc[k3b] = hyb_add16(hyb_h2f8(acc_h2[k3b]), wg_load8f(b2, 64u * k3b)); +#endif } } #else @@ -1191,6 +1509,166 @@ WG_KERNEL(SW_ENTRY) // around on every iteration, about 90 moves per group; C = 64: measured 3.6 % faster unrolled) and // software-pipelined by one group (c64 / c96 about 4 % faster): W1 of group j0 + GROUP is issued before the GELU // of group j0, so the GELU's exp / rcp can issue under independent matrix multiplies (same operations per value) +#if SW_Q7_CHUNK + uint4 hcur_h[GROUP]; + { + const uint fb0 = sw_lane_base(buf * MAXU, lane) + SW_MDZ; + v8f hc[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hc[g2] = wg_load8f(b1d, (u * HPU + g2) * 64u); + [unroll] for (uint kc2 = 0; kc2 < KC; kc2 += 2u) { + uint2 f0[GROUP], f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) { + f0[g] = sw_lfrag_b(fb0, g * 2u * KC + kc2); + f1[g] = sw_lfrag_b(fb0, g * 2u * KC + kc2 + 1u); + } + [unroll] for (uint g3a = 0; g3a < GROUP; ++g3a) + hc[g3a] = wg_wmma_fp8(f0[g3a], mf[kc2], hc[g3a]); + [unroll] for (uint g3b = 0; g3b < GROUP; ++g3b) + hc[g3b] = wg_wmma_fp8(f1[g3b], mf[kc2 + 1u], hc[g3b]); + if (kc2 + 2u < KC) + [unroll] for (uint g3c = 0; g3c < GROUP; ++g3c) hc[g3c] = hyb_round16(hc[g3c]); + } + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hcur_h[g3o] = hyb_rn16x8(hc[g3o]); + } + [unroll] for (uint j0 = 0; j0 < HPU; j0 += GROUP) { + const uint fb = sw_lane_base(buf * MAXU, lane) + SW_MDZ + j0 * (2u * KC * 32u); + uint4 hnext_h[GROUP]; + uint2 hf[GROUP]; + if (j0 + GROUP < HPU) { + // Split hyb_gelu_pre(hcur_h[0..1]) across W1(j0 + GROUP): 8x u16 LUT loads hide behind + // independent FP8 WMMAs with only 8 VGPRs live at a time. + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const uint fbn = fb + GROUP * (2u * KC * 32u); + v8f hn[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hn[g2] = wg_load8f(b1d, (u * HPU + j0 + GROUP + g2) * 64u); + { + uint2 f0[GROUP], f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) { + f0[g] = sw_lfrag_b(fbn, g * 2u * KC + 0u); + f1[g] = sw_lfrag_b(fbn, g * 2u * KC + 1u); + } + [unroll] for (uint g3a = 0; g3a < GROUP; ++g3a) hn[g3a] = wg_wmma_fp8(f0[g3a], mf[0], hn[g3a]); + [unroll] for (uint g3b = 0; g3b < GROUP; ++g3b) hn[g3b] = wg_wmma_fp8(f1[g3b], mf[1], hn[g3b]); + } + hf[0] = hyb_gelu_fin(gp0); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint kc2 = 2; kc2 < KC; kc2 += 2u) { + [unroll] for (uint g3c = 0; g3c < GROUP; ++g3c) hn[g3c] = hyb_round16(hn[g3c]); + uint2 f0[GROUP], f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) { + f0[g] = sw_lfrag_b(fbn, g * 2u * KC + kc2); + f1[g] = sw_lfrag_b(fbn, g * 2u * KC + kc2 + 1u); + } + [unroll] for (uint g3a = 0; g3a < GROUP; ++g3a) hn[g3a] = wg_wmma_fp8(f0[g3a], mf[kc2], hn[g3a]); + [unroll] for (uint g3b = 0; g3b < GROUP; ++g3b) hn[g3b] = wg_wmma_fp8(f1[g3b], mf[kc2 + 1u], hn[g3b]); + } + hf[1] = hyb_gelu_fin(gp1); + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hnext_h[g3o] = hyb_rn16x8(hn[g3o]); + } else { + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint g7 = 0; g7 < GROUP; ++g7) hnext_h[g7] = hcur_h[g7]; + hf[0] = hyb_gelu_fin(gp0); + hf[1] = hyb_gelu_fin(gp1); + } + // W2: 2-tile software-pipelined acc_h unpack/pack with FP8 WMMAs (reduces back-to-back RAW stalls + // between conversions and WMMAs). + uint2 f2[GROUP][KC]; + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) + [unroll] for (uint m = 0; m < KC; ++m) f2[g4][m] = sw_lfrag_b(fb, g4 * 2u * KC + KC + m); + v8f t0 = hyb_h2f8(acc_h[0]); + t0 = wg_wmma_fp8(f2[0][0], hf[0], t0); + [unroll] for (uint m2 = 0; m2 + 1u < KC; ++m2) { + v8f t1 = hyb_h2f8(acc_h[m2 + 1u]); + t0 = wg_wmma_fp8(f2[1][m2], hf[1], t0); + t1 = wg_wmma_fp8(f2[0][m2 + 1u], hf[0], t1); + acc_h[m2] = hyb_rn16x8(t0); + t0 = t1; + } + t0 = wg_wmma_fp8(f2[1][KC - 1u], hf[1], t0); + acc_h[KC - 1u] = hyb_rn16x8(t0); + [unroll] for (uint g8 = 0; g8 < GROUP; ++g8) hcur_h[g8] = hnext_h[g8]; +#if SW_COMMIT_EARLY + if (more && j0 == GROUP * (SW_COMMIT_EARLY - 1)) st_commit(stage, (buf ^ 1u) * MAXU + 8u * SW_MDZ, MLP_BYTES / 16, tid); +#endif + } +#elif SW_HYB && (SW_C != 96) + // VMEM/LUT latency hiding (SW_HYB MLP, C != 96): keep hcur packed as uint4[GROUP] (saves 8 VGPRs) and split + // hyb_gelu_pre(hcur_h[0..1]) (16x u16 global LUT loads) across W1(j0 + GROUP) FP8 WMMAs to hide LUT latency. + uint4 hcur_h[GROUP]; + { + const uint fb0 = sw_lane_base(buf * MAXU, lane) + SW_MDZ; + uint2 f1[GROUP][KC]; + [unroll] for (uint g = 0; g < GROUP; ++g) + [unroll] for (uint kc = 0; kc < KC; ++kc) f1[g][kc] = sw_lfrag_b(fb0, g * 2u * KC + kc); + v8f hc[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hc[g2] = wg_load8f(b1d, (u * HPU + g2) * 64u); + [unroll] for (uint kc2 = 0; kc2 < KC; ++kc2) + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hc[g3] = wg_wmma_fp8(f1[g3][kc2], mf[kc2], hc[g3]); + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hcur_h[g3o] = hyb_rn16x8(hc[g3o]); + } + [unroll] for (uint j0 = 0; j0 < HPU; j0 += GROUP) { + const uint fb = sw_lane_base(buf * MAXU, lane) + SW_MDZ + j0 * (2u * KC * 32u); +#if SW_HYB_DUMP + [unroll] for (uint ghd = 0; ghd < GROUP; ++ghd) + HD_ST8(HD_H + 8u * (u * HPU + j0 + ghd), hyb_h2f8(hcur_h[ghd])); +#endif + uint4 hnext_h[GROUP]; + uint2 hf[GROUP]; + if (j0 + GROUP < HPU) { + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const uint fbn = fb + GROUP * (2u * KC * 32u); + v8f hn[GROUP]; + [unroll] for (uint g2 = 0; g2 < GROUP; ++g2) hn[g2] = wg_load8f(b1d, (u * HPU + j0 + GROUP + g2) * 64u); + [unroll] for (uint kc0 = 0; kc0 < KC / 2; ++kc0) { + uint2 f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) f1[g] = sw_lfrag_b(fbn, g * 2u * KC + kc0); + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hn[g3] = wg_wmma_fp8(f1[g3], mf[kc0], hn[g3]); + } + hf[0] = hyb_gelu_fin(gp0); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint kc1 = KC / 2; kc1 < KC; ++kc1) { + uint2 f1[GROUP]; + [unroll] for (uint g = 0; g < GROUP; ++g) f1[g] = sw_lfrag_b(fbn, g * 2u * KC + kc1); + [unroll] for (uint g3 = 0; g3 < GROUP; ++g3) hn[g3] = wg_wmma_fp8(f1[g3], mf[kc1], hn[g3]); + } + hf[1] = hyb_gelu_fin(gp1); + [unroll] for (uint g3o = 0; g3o < GROUP; ++g3o) hnext_h[g3o] = hyb_rn16x8(hn[g3o]); + } else { + const HybGeluPre gp0 = hyb_gelu_pre(hcur_h[0]); + const HybGeluPre gp1 = hyb_gelu_pre(hcur_h[1]); + [unroll] for (uint g7 = 0; g7 < GROUP; ++g7) hnext_h[g7] = hcur_h[g7]; + hf[0] = hyb_gelu_fin(gp0); + hf[1] = hyb_gelu_fin(gp1); + } + uint2 f2[GROUP][KC]; + [unroll] for (uint g4 = 0; g4 < GROUP; ++g4) + [unroll] for (uint m = 0; m < KC; ++m) f2[g4][m] = sw_lfrag_b(fb, g4 * 2u * KC + KC + m); +#if SW_HYB_MUT_ORDER +#if SW_HYB_MUT_ORDER == 3 + if ((j0 / GROUP) & 1u) { + [unroll] for (uint m5 = 0; m5 < KC; ++m5) + [unroll] for (uint g11 = 0; g11 < GROUP; ++g11) acc2[m5] = wg_wmma_fp8(f2[g11][m5], hf[g11], acc2[m5]); + } else +#endif + if (SW_HYB_MUT_ORDER == 2 || (SW_HYB_MUT_ORDER == 1 && u == 0u && j0 == 0u)) { + [unroll] for (uint m3 = 0; m3 < KC; ++m3) + [unroll] for (uint g9 = 0; g9 < GROUP; ++g9) + acc[m3] = wg_wmma_fp8(f2[GROUP - 1u - g9][m3], hf[GROUP - 1u - g9], acc[m3]); + } else { + [unroll] for (uint m4 = 0; m4 < KC; ++m4) + [unroll] for (uint g10 = 0; g10 < GROUP; ++g10) acc[m4] = wg_wmma_fp8(f2[g10][m4], hf[g10], acc[m4]); + } +#else + [unroll] for (uint m2 = 0; m2 < KC; ++m2) + [unroll] for (uint g6 = 0; g6 < GROUP; ++g6) acc[m2] = wg_wmma_fp8(f2[g6][m2], hf[g6], acc[m2]); +#endif + [unroll] for (uint g8 = 0; g8 < GROUP; ++g8) hcur_h[g8] = hnext_h[g8]; +#if SW_COMMIT_EARLY + if (more && j0 == GROUP * (SW_COMMIT_EARLY - 1)) st_commit(stage, (buf ^ 1u) * MAXU + 8u * SW_MDZ, MLP_BYTES / 16, tid); +#endif + } +#else v8f hcur[GROUP]; { const uint fb0 = sw_lane_base(buf * MAXU, lane) + SW_MDZ; @@ -1296,6 +1774,7 @@ WG_KERNEL(SW_ENTRY) if (more && j0 == GROUP * (SW_COMMIT_EARLY - 1)) st_commit(stage, (buf ^ 1u) * MAXU + 8u * SW_MDZ, MLP_BYTES / 16, tid); #endif } +#endif if (more) { #if !SW_COMMIT_EARLY st_commit(stage, (buf ^ 1u) * MAXU, MLP_BYTES / 16, tid); @@ -1375,7 +1854,22 @@ WG_KERNEL(SW_ENTRY) } else #endif { -#if SW_HYB +#if SW_Q7_CHUNK + { + // Check |acc_h| <= 448.0 (FP16 0x5f00) directly on packed uint4 bits (1 VGPR vs 8*KC VGPRs!). + uint mx16 = 0u; + [unroll] for (uint km = 0; km < KC; ++km) { + const uint4 ah = acc_h[km]; + mx16 = max(mx16, max(max(ah.x & 0x7fffu, (ah.x >> 16) & 0x7fffu), max(ah.y & 0x7fffu, (ah.y >> 16) & 0x7fffu))); + mx16 = max(mx16, max(max(ah.z & 0x7fffu, (ah.z >> 16) & 0x7fffu), max(ah.w & 0x7fffu, (ah.w >> 16) & 0x7fffu))); + } + if (WaveActiveAllTrue(mx16 <= 0x5f00u)) { + [unroll] for (uint k2 = 0; k2 < KC; ++k2) o[k2] = wg_pack_q8_nc_ags(hyb_h2f8(acc_h[k2])); + } else { + [unroll] for (uint k2 = 0; k2 < KC; ++k2) o[k2] = wg_pack_q8_ags(hyb_h2f8(acc_h[k2])); + } + } +#elif SW_HYB [unroll] for (uint k = 0; k < KC; ++k) o[k] = hyb_q8_of_chain(acc[k]); #else [unroll] for (uint k = 0; k < KC; ++k) o[k] = sw_pack_q8_v2(acc[k]); diff --git a/clean/dx12/tests/kernel_replay.cpp b/clean/dx12/tests/kernel_replay.cpp index 45869470..f03b5e47 100644 --- a/clean/dx12/tests/kernel_replay.cpp +++ b/clean/dx12/tests/kernel_replay.cpp @@ -39,9 +39,16 @@ // inside, manifest argument kind s:...: the file's bytes with the 8 // bytes at each byte offset replaced by that buffer's device pointer) // save after the run, the buffer's bytes are written to -// time after the run (and the saves), the steps run more times; the mean +// time [each] after the run (and the saves), the steps run more times; the mean // wall time per run (submission to completion, synchronised after each -// run) is printed as "chain : time ms per run ( runs)" +// run) is printed as "chain : time ms per run ( runs)"; +// with "each", every run's time first as "chain : run ms +// gpu ms" (gpu: device timestamps before the run's first launch and +// after its last one; -1 when the device has none) +// time