From 3d83c132383040a0053dbb47ebe139ac640366e1 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:08:07 -0500 Subject: [PATCH 1/5] Model L (D3D12): opt-in l_mode=fast (M-form route on Model L's values, with the decoder skip); l_mode=hybrid stays the default l_mode=hybrid|fast (runtime option, or env WG_L_MODE; the option wins; unset = hybrid). Fast, native D3D12 only, runs Model L on Model M's WMMA / FP8 _nc kernels with Model M's fusions (pm, xe, mb, xo, rv) and Model L's (ll, le, lc), on Model L's own values (the packers without the hybrid values), the C1/C2 reconstruction and the fused l_post_tf_p12[_pf] as the hybrid route's. The decoder block takes Model L's skip S = the encoder block's map l_x3: l_swin_block_c32_dec_coef12_add_nc / l_swin_block_c32_dec_add_nc (clean/dx12/kernels/l_swin_fast.hlsl: SW_ADD 1, SW_SRC 2, WG_LD_A16 on, 96 / 95 VGPRs, no spills; swin_block.hlsl only relaxes its #error for this one combination, so every other kernel's preprocessed input is unchanged). Hybrid is untouched (same kernels, same launches); warm_up leaves each mode's other kernels out (Device::warm_up_skip). Refusals by name: wrong value, fast off D3D12, fast with WG_L_FORM, a missing kernel, weights that need the clamped block, no bmegahg bottleneck build. Tests: clean/l/runtime/tests/test_l_runtime_fast_mode.py. --- clean/dx12/kernel_sets.json | 8 + clean/dx12/kernels/fused_swin.hlsl | 6 +- clean/dx12/kernels/l_swin_fast.hlsl | 22 ++ clean/dx12/kernels/swin_block.hlsl | 6 +- clean/dx12/vgpr_limits.json | 2 + clean/l/SPEED.md | 16 + .../runtime/tests/test_l_runtime_fast_mode.py | 346 ++++++++++++++++++ clean/runtime/device.h | 4 + clean/runtime/device_d3d12.cpp | 4 +- clean/runtime/runtime.cpp | 99 ++++- clean/tests/runtime_frame_trace.cpp | 15 +- clean/tests/test_runtime_frame_trace.py | 3 + 12 files changed, 515 insertions(+), 16 deletions(-) create mode 100644 clean/dx12/kernels/l_swin_fast.hlsl create mode 100644 clean/l/runtime/tests/test_l_runtime_fast_mode.py diff --git a/clean/dx12/kernel_sets.json b/clean/dx12/kernel_sets.json index 26c0d04b..c6863009 100644 --- a/clean/dx12/kernel_sets.json +++ b/clean/dx12/kernel_sets.json @@ -330,6 +330,14 @@ "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_hyb", "-" diff --git a/clean/dx12/kernels/fused_swin.hlsl b/clean/dx12/kernels/fused_swin.hlsl index 02d6e383..77bc7e35 100644 --- a/clean/dx12/kernels/fused_swin.hlsl +++ b/clean/dx12/kernels/fused_swin.hlsl @@ -627,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 diff --git a/clean/dx12/kernels/l_swin_fast.hlsl b/clean/dx12/kernels/l_swin_fast.hlsl new file mode 100644 index 00000000..714d6cdb --- /dev/null +++ b/clean/dx12/kernels/l_swin_fast.hlsl @@ -0,0 +1,22 @@ +// 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 +#include "swin_block.hlsl" diff --git a/clean/dx12/kernels/swin_block.hlsl b/clean/dx12/kernels/swin_block.hlsl index 2e77c5be..1aabd52d 100644 --- a/clean/dx12/kernels/swin_block.hlsl +++ b/clean/dx12/kernels/swin_block.hlsl @@ -598,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 diff --git a/clean/dx12/vgpr_limits.json b/clean/dx12/vgpr_limits.json index 367bfa10..019b3696 100644 --- a/clean/dx12/vgpr_limits.json +++ b/clean/dx12/vgpr_limits.json @@ -34,6 +34,8 @@ "swin_bneck6_hyb_mut": 256, "swin_bneck6_hyb_tmo": 256, "l_swin_block_c32_dec_coef12_nc": 96, + "l_swin_block_c32_dec_add_nc": 96, + "l_swin_block_c32_dec_coef12_add_nc": 96, "swin_block_c64_nc": 192, "swin_block_c64_add_ex_nc": 192, "swin_block_c96_nc": 192, diff --git a/clean/l/SPEED.md b/clean/l/SPEED.md index 1b6c809e..b2532002 100644 --- a/clean/l/SPEED.md +++ b/clean/l/SPEED.md @@ -74,6 +74,22 @@ shape), so do not compare them with the Model L harness table above. Record: [`l-vs-m-shapes-main.json`](records/l-vs-m-shapes-main.json) (its Model L rows timed an earlier form of Model L and are not shown). +## Fast mode (opt-in, `l_mode=fast`) + +The release form of Model L on Direct3D 12 is the hybrid form (`l_mode=hybrid`, the default: float32 chains with FP16 +rounding at each step, the form that matches the reference bit for bit). `l_mode=fast` is an opt-in preset for players +who prefer speed: it runs Model L's network on Model M's Swin kernels (the WMMA / FP8 `_nc` forms, with Model M's +fusions) on Model L's own weights, so its output follows the model closely but is not bit-exact to the reference. The +structure is Model L's: the decoder block adds the encoder block's output as its skip, the reconstruction and the +temporal history are the hybrid route's own kernels (the C1/C2 reconstruction, the fused output stage). + +Select it with the runtime option `l_mode=fast` (in the game's `runtime_options` line) or the environment variable +`WG_L_MODE=fast`; the option wins over the variable, and nothing set (or `l_mode=hybrid`) is the hybrid default, whose +kernels and launches the preset does not touch. Fast mode runs on native Direct3D 12 only and is refused with its +reason where a kernel it needs is missing from the build (a build made with `--model-l`; the bottleneck needs the +build's `variants.json` and `swin__bmegahg.co`). No timing is published for it yet: a figure goes on this page only +with its measurement record. + ## Building Model L Model L is off in a default build. It is built with the `--model-l` option of the two build scripts: diff --git a/clean/l/runtime/tests/test_l_runtime_fast_mode.py b/clean/l/runtime/tests/test_l_runtime_fast_mode.py new file mode 100644 index 00000000..d17dc0c2 --- /dev/null +++ b/clean/l/runtime/tests/test_l_runtime_fast_mode.py @@ -0,0 +1,346 @@ +# SPDX-License-Identifier: MIT +"""Model L's quality preset l_mode (runtime option l_mode=hybrid|fast, env WG_L_MODE) on the CPU: the runtime built with +Model L on the recording device of clean/tests/runtime_frame_trace.cpp (launches recorded with their arguments, not +executed; no GPU). + +- hybrid is the default and is untouched: nothing set, l_mode=hybrid, WG_L_MODE=hybrid and WG_L_MODE= (empty) trace the same + frames as each other, and a manifest without the fast-only kernels changes nothing for them (the hybrid route never + names a fast-only kernel, so it loads nothing of them). +- the option and the environment: a wrong value is refused with its source named; the runtime option wins over WG_L_MODE + and WG_RUNTIME_OPTIONS over the configuration string; fast is native D3D12 only and has no WG_L_FORM next to it. +- fast on native D3D12: the M-form route on Model L's own values (Model M's packers without the hybrid values: + clean/runner/packing.py pack_stage / l_pack.pack_model_l), Model M's "_nc" Swin kernels with Model M's fusions, Model L's + encoder block with the linears (le), its decoder block with the skip S = the encoder block's map and the pack12 store + (lc, l_swin_block_c32_dec_coef12_add_nc; unfused: l_swin_block_c32_dec_add_nc + l_coef_pack12), the C1/C2 + reconstruction; no hybrid twin, no no-skip decoder block. Every kernel the route needs is refused by name when missing. + +Built with the host C++ compiler (clean/tests/host_cxx.py; skipped without one). + +Run (repository root): + python -m unittest discover -s clean/l/runtime/tests -t clean/l/runtime/tests -p test_l_runtime_fast_mode.py +""" +import json +import os +import re +import shutil +import subprocess +import tempfile +import unittest + +import numpy as np + +import test_l_runtime_frame as F +from clean.l.reference import oracle as L +from clean.l.runner import l_pack as LP +from clean.runner import packing as P +from clean.runner import variants as V +from clean.tests import test_runtime_frame_trace as FT + +FAST_ONLY = ("l_swin_block_c32_dec_add_nc", "l_swin_block_c32_dec_coef12_add_nc") +FOLD_ADD = "l_swin_block_c32_dec_coef12_add_nc" +DEC_ADD = "l_swin_block_c32_dec_add_nc" +ENC_LIN = "l_swin_block_c32_enc_lin_nc" +M_FORM_SHARED = ("swin_block_c64_nc", "swin_block_c96_nc", "swin_block_c96_pm_nc", "swin_block_c96_pm_rev_nc", + "swin_block_c96_add_ex_nc", "swin_block_c64_add_ex_nc", "swin_block_c96_add_xe_nc", + "swin_block_c96_add_xe_rev_nc", "swin_block_c96_add_xe_xo_nc", "patch_merge_c64", "patch_merge_c96", + "bneck/swin_bneck6_nc", "bneck/swin_bneck6_mb_nc", "bneck/swin_bneck6_mbo_nc") +# what runtime.cpp l_native_missing asks of the fast route (after the release route's own checks: lc12 reconstruction) +FAST_NEEDS = ("lev/input_encoder", "lev/input_encoder_q20", "l_linear_32_32_relu", "l_linear_32_32_f16", + "l_swin_block_c32_enc_nc", ENC_LIN, "l_project_gather", "l_dec_project", DEC_ADD, FOLD_ADD, "l_coef_pack12", + "swin_block_c64_nc", "patch_merge_c64", "swin_block_c96_nc", "patch_merge_c96", "bneck/swin_bneck6_nc", + "swin_block_c96_add_ex_nc", "swin_block_c64_add_ex_nc") +SIZES = "--sizes=96x64,96x64,80x48,80x48,80x48,77x45" + + +def l_run(options="model=L", ports=None, frames=3, flags=(), backend=3, rw=F.RW, rh=F.RH, hdr=1, env=None, + tf_default=False, variants=True): + """The trace program's lines (the arguments of test_l_runtime_frame.run). variants: the build folder holds the + variants.json and swin__bmegahg.co of a full build (the bottleneck in one launch by default, Model M's geometry + variants; without them the six block launches, which D3D12 has no port of).""" + ports = F.full_ports() if ports is None else ports + build = tempfile.mkdtemp(prefix="wg_lfb_") + for n in FT.SHIPPING + (("swin__bmegahg.co",) if variants else ()): + open(os.path.join(build, n), "wb").close() + if variants: + with open(os.path.join(build, V.MANIFEST), "w") as fh: + json.dump({n: {"file": V.code_object(n), "defines": V.all_builds().get(n, {}), + "geometry": V.variant_geometry(n), "ablation": False} for n in ("base", "bmegahg")}, fh) + os.makedirs(os.path.join(build, "dx12")) + with open(os.path.join(build, "dx12", "manifest.json"), "w") as fh: + json.dump({"format": 1, "kernels": [{"name": k, "co": co} for k, co in ports]}, fh) + e = {k: v for k, v in os.environ.items() if not k.upper().startswith("WG_")} + if not tf_default: # the separate launches (WG_L_POST_TF=0), unless the test is of the shipped defaults + e["WG_L_POST_TF"] = "0" + e.update(env or {}) + try: + r = subprocess.run([F.trace_exe(), build, F.model_dir(), str(rw), str(rh), "120", "72", str(frames), options, + "--format=0", "--map=" + F.map_path(), "--hdr=%d" % hdr, "--backend=%d" % backend, *flags], + capture_output=True, text=True, env=e, timeout=600) + finally: + shutil.rmtree(build, ignore_errors=True) + if r.returncode != 0: + raise AssertionError("runtime_frame_trace failed (exit %d)\n%s%s" % (r.returncode, r.stdout, r.stderr)) + return r.stdout.splitlines() + + +def without(*ks): + return [kc for kc in F.full_ports() if kc[0] not in ks] + + +def names(frame): + return [ln.kernel for ln in frame["launches"]] + + +def fast_digests(): + """{blob name: SHA-256 hex} of the blobs Model L's fast route reads: Model L's own launches (pack_model_l on the + parameters as they are) and the ten shared stages by Model M's packer, on the parameters as they are (no hybrid + values), the post blob as every route's.""" + params = L.random_params(np.random.default_rng(F.SEED)) + blobs = LP.pack_model_l(params) + blobs.update({s: P.pack_stage(s, params[s], "gfx12", model="M") for s in F.SHARED}) + import hashlib + import struct + blobs["post"] = struct.pack("& names) { (void)names; } virtual bool write_value32(DevPtr ptr, uint32_t value) { (void)ptr, (void)value; return false; } // Frame guard (native D3D12; the hybrid Model L bottleneck's bounded wait, hyb_bneck.hlsl). guard_begin(word): from // here on, every launch and copy of this recording is skipped on the GPU while the 8 bytes at `word` (8-aligned) are diff --git a/clean/runtime/device_d3d12.cpp b/clean/runtime/device_d3d12.cpp index 5da26095..ab9b8df8 100644 --- a/clean/runtime/device_d3d12.cpp +++ b/clean/runtime/device_d3d12.cpp @@ -492,6 +492,7 @@ class NativeD3D12Device final : public Device, public NativeD3D12Ext { } uint64_t arena_high_water() const override { return high_; } bool hyb_tables() const override { return hyb_; } + void warm_up_skip(const std::vector& names) override { warm_skip_.insert(names.begin(), names.end()); } uint64_t arena_capacity() const override { return arena_bytes_; } uint64_t external_recorded() const override { return ext_recorded_; } uint64_t external_done() const override { @@ -506,7 +507,7 @@ class NativeD3D12Device final : public Device, public NativeD3D12Ext { if (external_) return extension_result(fail("native D3D12 warm_up: recording into the caller's list"), error); for (auto& entry : kernels_) { NativeKernel& k = entry.second; - if (k.pso || !variant_matches(k) || (k.rs != "buffer" && k.rs != "direct")) continue; + if (k.pso || warm_skip_.count(entry.first) || !variant_matches(k) || (k.rs != "buffer" && k.rs != "direct")) continue; if (!create_pso(k)) return extension_result(false, error); } return extension_result(true, error); @@ -1902,6 +1903,7 @@ class NativeD3D12Device final : public Device, public NativeD3D12Ext { std::map used_; std::map hosts_; std::multimap kernels_; // by name; several ports of one name differ in "co" + std::set warm_skip_; // warm_up leaves these out (Device::warm_up_skip) std::set untagged_cos_; std::map tagged_cos_; std::vector events_; diff --git a/clean/runtime/runtime.cpp b/clean/runtime/runtime.cpp index 89f67aff..252c871b 100644 --- a/clean/runtime/runtime.cpp +++ b/clean/runtime/runtime.cpp @@ -313,6 +313,17 @@ struct Runtime { std::string l_form_name; std::string l_form_label = "Model L"; // the resolved form in refusals ("Model L hybrid (default)", "WG_L_FORM=hybrid") bool l_post_c12 = false; + // Model L quality preset (runtime option l_mode=hybrid|fast, or env WG_L_MODE; Model L only; the option wins over the + // environment, unset / empty = hybrid): + // hybrid (default): the release form above (the hybrid twins on native D3D12), untouched by the preset + // fast (opt-in; native D3D12 only): Model L's M-form route: its ten shared Swin stages and its two width-32 blocks + // as Model M's WMMA / FP8 "_nc" kernels on Model L's own values (the packers' q8 weights, gamma without the + // hybrid's sqrt(C) factor), Model M's fusions (pm, xe, mb, xo, rv) and Model L's (ll, le, lc); the decoder block + // with Model L's skip S = the encoder block's map l_x3 (l_swin_block_c32_dec_[coef12_]add_nc), the C1/C2 + // reconstruction as the hybrid route's (lc12, the fused l_post_tf_p12[_pf]). Not bit-exact to the oracle (the + // hybrid form is the bit-exact one); the history, the reset and the temporal logic are the same code. + std::string l_mode_opt; + bool l_fast_d3d12 = false; // WG_L_FORM=hybrid on native D3D12 (hyb-fast, 0.6.5 L release form): Model L's M-form route (l_q7 off) with every // block stage packed from the hybrid values (clean/l/runtime/l_hyb_pack.h, the same blob names and layout) and every // Swin kernel launched as its hybrid twin from the kernel manifest (hyb-fast's names: the M-form route's name with @@ -673,6 +684,32 @@ struct Runtime { // reference or HIP (and in the game, no move to the HIP executor: executor_select.h dx12_refusal_action). const char* lform = std::getenv("WG_L_FORM"); const std::string lf = lform ? lform : ""; + // l_mode=hybrid|fast: the runtime option (the configuration string, then WG_RUNTIME_OPTIONS, whose keys win), else + // WG_L_MODE, else hybrid (the release default, whose route nothing below changes) + { + std::string lm, from = "l_mode"; + const char* env_opt = std::getenv("WG_RUNTIME_OPTIONS"); + const std::string opts = std::string(c.runtime_options ? c.runtime_options : "") + ";" + (env_opt ? env_opt : ""); + for (size_t a = 0; a <= opts.size();) { + size_t b = opts.find_first_of(";,", a); + if (b == std::string::npos) b = opts.size(); + const std::string kv = opts.substr(a, b - a); + a = b + 1; + const size_t eq = kv.find('='); + if (eq != std::string::npos && kv.substr(0, eq) == "l_mode" && eq + 1 < kv.size()) lm = kv.substr(eq + 1); + } + if (lm.empty()) + if (const char* e = std::getenv("WG_L_MODE")) + if (*e) lm = e, from = "WG_L_MODE"; + if (!lm.empty() && lm != "hybrid" && lm != "fast") + return fail(from + " must be hybrid or fast (got \"" + lm + "\")"); + l_mode_opt = lm.empty() ? "hybrid" : lm; + } + const bool lfast = l_mode_opt == "fast"; + if (lfast && c.backend != 3) + return fail("l_mode=fast runs on native D3D12 (backend 3) only (l_mode=hybrid is the default on every backend)"); + if (lfast && !lf.empty()) + return fail("l_mode=fast cannot be combined with WG_L_FORM=" + lf + " (the fast route is its own form: unset WG_L_FORM)"); if (lf == "m") return fail("WG_L_FORM=m refused: the M-form is not offered for Model L (default hybrid_full; q7 = reference)"); #ifndef WG_DEV_DIAGNOSTICS @@ -690,17 +727,22 @@ struct Runtime { if (l_twin && c.backend != 0) return fail("WG_L_FORM=hybrid_twin runs on the HIP backend only"); if (l_mut && c.backend != 0) return fail("WG_L_FORM=hybrid_mutant: the HIP backend only"); #endif - const bool hyb = lf.empty() || lf == "hybrid" || l_twin; + const bool hyb = (lf.empty() || lf == "hybrid" || l_twin) && !lfast; l_q7 = true; l_form_name = hyb ? std::string("hybrid") : (l_mut ? lf : std::string()); // the hybrid refusals name the form as resolved: nothing set is the release default, not a WG_L_FORM value - l_form_label = lf.empty() ? std::string("Model L hybrid (default)") : "WG_L_FORM=" + lf; + l_form_label = lfast ? std::string("Model L fast (l_mode=fast)") + : lf.empty() ? std::string("Model L hybrid (default)") : "WG_L_FORM=" + lf; l_hyb_d3d12 = (hyb && c.backend == 3) || l_twin; // the fast hybrid route (twins: on HIP) if (l_hyb_d3d12) l_q7 = false; // the fast kernels' M-form layout (the HIP reference route keeps l_q7__hyb) + if (lfast) { // l_mode=fast: the M-form route (l_q7 off, no hybrid twins, no hybrid values), the C1/C2 reconstruction + l_q7 = false; + l_fast_d3d12 = true; + } const char* lpost = std::getenv("WG_L_POST"); const std::string lp = lpost ? lpost : ""; if (!lp.empty() && lp != "c12") return fail("WG_L_POST: unknown value \"" + lp + "\" (c12)"); - l_post_c12 = lp == "c12" || hyb; // hybrid_full: the hybrid network AND the C1/C2 reconstruction + l_post_c12 = lp == "c12" || hyb || lfast; // hybrid_full: the hybrid network AND the C1/C2 reconstruction (fast too) if (l_post_c12 && c.backend != 0 && c.backend != 3) return fail("WG_L_POST=c12: HIP (backend 0) and native D3D12 (backend 3) only"); } @@ -784,6 +826,9 @@ struct Runtime { l_le_built = std::find(have.begin(), have.end(), "l_swin_block_c32_enc_lin_nc") != have.end(); l_q20_built = std::find(have.begin(), have.end(), "lev/input_encoder_q20") != have.end(); l_q20d_built = std::find(have.begin(), have.end(), "lev/input_encoder_direct_q20") != have.end(); + // l_mode=fast: the decoder store's fold is the skip form (l_decoder); l_native_missing names what the route needs + if (l_fast_d3d12) + l_fold_built = std::find(have.begin(), have.end(), "l_swin_block_c32_dec_coef12_add_nc") != have.end(); if (l_post_c12) { const std::string miss = manifest_missing({"lc12/l_post_recon", "lc12/l_post_recon_p12", "lc12/l_post_recon_ldr", "lc12/l_post_recon_p12_ldr"}); @@ -1002,6 +1047,9 @@ struct Runtime { uint32_t flags = 0; std::memcpy(&flags, blobs[s].data(), 4); swin_nc[s] = (flags & 1u) != 0 || hyb_d3d12(); // hybrid: the "_nc" names, whose twins always saturate + if (l_fast_d3d12 && !swin_nc[s]) // (native D3D12 has the _nc ports only; never another form in their place) + return fail(std::string("Model L fast on native D3D12: stage ") + s + "'s weights need the clamped block, which is " + "not ported to D3D12 (only the _nc forms are); use l_mode=hybrid"); } post_s = model["post"]["s"].f[0]; blobs["post"].assign(16, 0); // runner/post.py pack: s as f32, zero padding to 16 bytes @@ -1032,6 +1080,22 @@ struct Runtime { dev = make_hip_device(c.rocm_dir ? c.rocm_dir : "", &e); } if (!dev) return fail(e); +#ifdef WG_MODEL_L + if (model_l && c.backend == 3) { + // The pipeline states the native D3D12 device's warm_up compiles (every kernel of the build, selected or not): the + // hybrid default leaves out the two fast-only decoder blocks (and is otherwise as it was); l_mode=fast leaves out + // what it never launches: the hybrid twins, the FP16-form q7 blocks and the no-skip decoder blocks + std::vector skip; + for (const std::string& h : manifest_kernels()) { + const bool twin = h.size() > 4 && h.compare(h.size() - 4, 4, "_hyb") == 0; + if (l_fast_d3d12 ? (twin || h.compare(0, 5, "l_q7_") == 0 || h == "l_swin_block_c32_dec_nc" || + h == "l_swin_block_c32_dec_coef12_nc") + : (h == "l_swin_block_c32_dec_add_nc" || h == "l_swin_block_c32_dec_coef12_add_nc")) + skip.push_back(h); + } + dev->warm_up_skip(skip); + } +#endif for (const std::string& co : {swin_co, enc0_co, dec0_co, exposure_co, std::string("post.co"), std::string("frame.co")}) { if (model_l && (co == enc0_co || co == dec0_co)) continue; // Model L's encoder and decoder: below @@ -1110,6 +1174,9 @@ struct Runtime { if (l_post_own_given && !model_l) return fail("l_post=own is a Model L option (its own reconstruction)"); if (!mid_setup(c)) return false; if (!bneck_setup(c)) return false; + if (l_fast_d3d12 && bneck_variant.empty() && mid_variant.empty() && !manifest_missing({"swin_block_c128_nc"}).empty()) + return fail("Model L fast on native D3D12: no standalone swin_block_c128_nc port, so the bottleneck needs the " + "bmegahg build (variants.json and swin__bmegahg.co next to the library); l_mode=hybrid has its own"); if (c.backend == 3 && !hyb_d3d12() && !m_q7 && !model_l && bneck_variant.empty() && mid_variant.empty() && choose(c.swin_bneck, "WG_SWIN_BNECK", "") == "none" && !manifest_missing({"swin_block_c128_nc"}).empty()) return fail("native D3D12 m_mode=fast has no standalone swin_block_c128_nc port " @@ -1917,7 +1984,7 @@ struct Runtime { kernels_text += " swin_fused=" + (fz.empty() ? std::string("none") : fz); if (l_hyb_d3d12) kernels_text += std::string(" l_exfuse=") + (l_exfuse ? "on" : "off"); if (l_hyb_d3d12) kernels_text += std::string(" l_post_w64=") + (l_post_w64 ? "on" : "off"); - if (l_hyb_d3d12) kernels_text += std::string(" l_post_tf=") + (l_post_tf ? "on" : "off"); + if (l_hyb_d3d12 || l_fast_d3d12) kernels_text += std::string(" l_post_tf=") + (l_post_tf ? "on" : "off"); kernels_text += " swin_bneck=" + (bneck_variant.empty() ? std::string(hyb_mega ? "hyb6" : "none") : bneck_variant); if (diag_hooks_ignored) kernels_text += " diag_hooks=ignored"; kernels_text += " swin_resident=" + std::to_string(swin_resident); @@ -1948,7 +2015,7 @@ struct Runtime { (l_q7 ? (l_form_name.empty() ? std::string(",l_q7.co,l_q7w.co l_form=q7") : ",l_q7" + std::string(l_q7_tag) + ".co,l_q7w__hyb.co l_form=" + l_form_name) - : std::string(l_hyb_d3d12 ? " l_form=hybrid" : " l_form=m")) + + : std::string(l_hyb_d3d12 ? " l_form=hybrid" : l_fast_d3d12 ? " l_form=fast l_mode=fast" : " l_form=m")) + (l_post_c12 ? " l_post_c12=on" : "") + " l_post=" + (l_ldr ? "l_post_recon_ldr" : "l_post_recon"); if (m_q7) // Model M's shared stages on the q7 kernels (hybrid: the float32-chain build) @@ -1965,6 +2032,8 @@ struct Runtime { kernels_text += " l_hyb_d3d12=on hyb_twins=" + std::to_string(hyb_map.size() / 2) + " l_dec_skip=l_x3" + // the arena tables (native D3D12; "off" on the HIP twins' route, whose device has none) std::string(" hyb_tables=") + (dev->hyb_tables() ? "on" : "off"); + if (l_fast_d3d12) // l_mode=fast: the decoder block's skip S = the encoder block's map l_x3, in the M-form arithmetic + kernels_text += " l_dec_skip=l_x3"; if (m_hyb_d3d12) // Model M on the hybrid twins: dec1's map stored, dec0 = d1p12/dec0_q7 kernels_text += " m_form=hybrid m_hyb_d3d12=on hyb_twins=" + std::to_string(hyb_map.size() / 2) + std::string(" hyb_tables=") + (dev->hyb_tables() ? "on" : "off"); @@ -2141,7 +2210,7 @@ struct Runtime { // reads FP8 and writes FP16. bool l_block(const char* kind, DevPtr x, DevPtr out, DevPtr w, bool nc, int H, int W, bool decoder, int f, DevPtr skip = 0) { - DevPtr none = skip; // the hybrid decoder's skip S (l_x3); the M-form blocks take none + DevPtr none = skip; // the hybrid and fast decoder's skip S (l_x3); the plain M-form blocks take none int ox = 0, oy = 0; l_offsets(decoder, f, &ox, &oy); const int nwin = ((W + ox + 3) / 4) * ((H + oy + 3) / 4); @@ -2249,18 +2318,18 @@ struct Runtime { int tw = fw / 2, th = fh / 2; if (!l_q7 && fz_lc && l_fold_built && p12_frame && l_nc[1]) { DevPtr none = 0, wb = wdev["dec0_block"]; - DevPtr skip = l_hyb_d3d12 ? l_x3 : 0; // hybrid: the skip S = the encoder block's map (as l_block's dec) + DevPtr skip = l_hyb_d3d12 || l_fast_d3d12 ? l_x3 : 0; // hybrid, fast: the skip S = the encoder block's map (as l_block's dec) int ox = 0, oy = 0, H = fh, W = fw, rw = p.rw, rh = p.rh; l_offsets(true, f, &ox, &oy); const int nwin = ((W + ox + 3) / 4) * ((H + oy + 3) / 4); return launch("l_dec_project", cdiv(tw * th, 128), 256, {&out1, &l_narrow, &wd, &tw, &th}) && - launch("l_swin_block_c32_dec_coef12_nc", cdiv(nwin, 8), 256, + launch(l_fast_d3d12 ? "l_swin_block_c32_dec_coef12_add_nc" : "l_swin_block_c32_dec_coef12_nc", cdiv(nwin, 8), 256, {&l_narrow, &skip, &none, &wb, &H, &W, &ox, &oy, &A, &C, &latent[nxt], &wc, &rw, &rh}); } return launch("l_dec_project", cdiv(tw * th, 128), 256, {&out1, &l_narrow, &wd, &tw, &th}) && (l_q7 ? l_q7_block(true, l_narrow, l_x3, l_wide, fh, fw, f) // skip S = the encoder block's map l_x3 - : l_block("dec", l_narrow, l_wide, wdev["dec0_block"], l_nc[1], fh, fw, true, f, - l_hyb_d3d12 ? l_x3 : 0)) && // hybrid: the skip S = the encoder block's map + : l_block(l_fast_d3d12 ? "dec_add" : "dec", l_narrow, l_wide, wdev["dec0_block"], l_nc[1], fh, fw, true, f, + l_hyb_d3d12 || l_fast_d3d12 ? l_x3 : 0)) && // hybrid, fast: the skip S = the encoder block's map launch(p12_frame ? "l_coef_pack12" : "l_coef", cdiv(tw * th, 128), 256, {&l_wide, &A, &B, &C, &latent[nxt], &wc, &p}); } @@ -2308,6 +2377,14 @@ struct Runtime { return manifest_missing({native_direct_io ? "lev/input_encoder_direct" : "lev/input_encoder", "l_linear_32_32_relu", "l_linear_32_32_f16", "l_project_gather", "l_dec_project", "l_coef_pack12"}); + if (l_fast_d3d12) // l_mode=fast: the M-form route with the skip form of the decoder block (l_swin_fast.hlsl), each port by name + return manifest_missing({native_direct_io ? "lev/input_encoder_direct" : "lev/input_encoder", + native_direct_io ? "lev/input_encoder_direct_q20" : "lev/input_encoder_q20", + "l_linear_32_32_relu", "l_linear_32_32_f16", "l_swin_block_c32_enc_nc", + "l_swin_block_c32_enc_lin_nc", "l_project_gather", "l_dec_project", + "l_swin_block_c32_dec_add_nc", "l_swin_block_c32_dec_coef12_add_nc", "l_coef_pack12", + "swin_block_c64_nc", "patch_merge_c64", "swin_block_c96_nc", "patch_merge_c96", + "bneck/swin_bneck6_nc", "swin_block_c96_add_ex_nc", "swin_block_c64_add_ex_nc"}); return manifest_missing({native_direct_io ? "lev/input_encoder_direct" : "lev/input_encoder", "l_linear_32_32_relu", "l_linear_32_32_f16", "l_swin_block_c32_enc_nc", "l_project_gather", @@ -2368,7 +2445,7 @@ struct Runtime { // no interop input / output copy, no motion at output resolution), HDR colour, the default pack12 route with the unbanded // post, post_diet (the exposure pair carries dec_scale), a footprint the kernel stages, WG_L_POST_TF not 0. bool l_tf_frame_ok(int rw, int rh, bool raw, bool mo, const FrameIo* io) const { - return model_l && l_post_tf && l_own_post && l_hyb_d3d12 && d3d12_native && !native_direct_io && !l_ldr && !raw && !mo && + return model_l && l_post_tf && l_own_post && (l_hyb_d3d12 || l_fast_d3d12) && d3d12_native && !native_direct_io && !l_ldr && !raw && !mo && p12 && post_diet && !out_f16 && !recon_output && !(io && io->out_half_pitch > 0) && l_in_block_route() && l_tf_supported(rw, rh, dw, dh); } diff --git a/clean/tests/runtime_frame_trace.cpp b/clean/tests/runtime_frame_trace.cpp index ecfed74a..63cb6a47 100644 --- a/clean/tests/runtime_frame_trace.cpp +++ b/clean/tests/runtime_frame_trace.cpp @@ -23,6 +23,8 @@ // launch, copy, upload and memset is printed as "skipped " and not done; guard_end copies the // 16 bytes at the word for guard_read; a memset / upload of the word prints "guard_clear" / // "guard_upload " +// --warm-skip print "warm_skip " for every kernel the route leaves out of the device's warm-up +// (Device::warm_up_skip; Model L's l_mode), before the first frame; without it nothing is printed // --fail-hyb-tables the device refuses the hybrid tables (Device::hyb_reserve returns false: create must refuse a // Model L hybrid context on the native-D3D12 stand-in, --backend=3); without it the reservation // succeeds (silently: the trace lines stay those of every other device) @@ -98,6 +100,7 @@ const Signature kSignatures[] = { // le): x = q, then enc0.Win1, enc0.Win2 {"l_swin_block_c32_enc_lin_hyb", "ppppiiiipp"}, // its hybrid twin (speed lever 3; the same arguments) {"l_swin_block_c32_dec_coef12_hyb", "ppppiiiippppii"}, // its hybrid twin (speed lever 3; the same arguments) + {"l_swin_block_c32_dec_coef12_add_nc", "ppppiiiippppii"}, // l_mode=fast: the same arguments, the skip S = xadd {"l_swin_block_c32*", "ppppiiii"}, // Model L's blocks (clean/l/FORMATS.md) {"l_q7_block_*", "pppppiiii"}, // the FP16-form blocks (l_q7.co / l_q7w.co, their hybrid builds): x, skip, out, // w, the tables, H, W, ox, oy @@ -141,7 +144,7 @@ class RecordingDevice : public Device { std::map index; // allocation number of each block int allocs = 0, frame = -1, fail_frame = -1; std::string fail_kernel; - bool fail_hyb = false, hyb = false; + bool fail_hyb = false, hyb = false, print_warm_skip = false; DevPtr next = 0x10000; // the frame guard (see --guard-timeout) int guard_timeout = -1, guard_reads = 0; @@ -195,6 +198,11 @@ class RecordingDevice : public Device { return true; } bool hyb_tables() const override { return hyb; } + // the kernels the route leaves out of the device's warm-up (--warm-skip prints them: "warm_skip ") + void warm_up_skip(const std::vector& names) override { + if (print_warm_skip) + for (const std::string& n : names) log->push_back("warm_skip " + n); + } bool alloc(DevPtr* p, size_t bytes) override { *p = next; mem[next].assign(bytes ? bytes : 1, 0); @@ -361,7 +369,7 @@ int main(int argc, char** argv) { cfg.auto_exposure = 0; const int frames = std::atoi(argv[7]); std::string options, map_path, fail; - bool fail_hyb = false; + bool fail_hyb = false, warm_skip = false; float pre_exposure = 1.0f; int guard_timeout = -1; std::vector> sizes; @@ -390,6 +398,8 @@ int main(int argc, char** argv) { fail = s.substr(7); } else if (s == "--fail-hyb-tables") { fail_hyb = true; + } else if (s == "--warm-skip") { + warm_skip = true; } else if (s.compare(0, 16, "--guard-timeout=") == 0) { guard_timeout = std::atoi(s.c_str() + 16); } else if (s.compare(0, 6, "--geo=") == 0) { @@ -416,6 +426,7 @@ int main(int argc, char** argv) { auto dev = std::make_unique(&log); RecordingDevice* rec = dev.get(); rec->fail_hyb = fail_hyb; + rec->print_warm_skip = warm_skip; rec->guard_timeout = guard_timeout; if (!fail.empty()) { const size_t at = fail.find('@'); diff --git a/clean/tests/test_runtime_frame_trace.py b/clean/tests/test_runtime_frame_trace.py index 34db0858..c6904cfa 100644 --- a/clean/tests/test_runtime_frame_trace.py +++ b/clean/tests/test_runtime_frame_trace.py @@ -81,6 +81,7 @@ class Trace: def __init__(self, lines): self.create, self.allocs, self.uploads, self.loads, self.frames, self.kernels = lines[0], {}, {}, [], [], {} + self.warm_skip = [] # --warm-skip: the kernels the route leaves out of the device's warm-up for ln in lines[1:]: if ln.startswith("alloc b"): k, n = ln[7:].split(" ") @@ -93,6 +94,8 @@ def __init__(self, lines): self.frames[-1]["names"][nm] = addr elif ln.startswith("load "): self.loads.append(ln[5:]) + elif ln.startswith("warm_skip "): + self.warm_skip.append(ln[10:]) elif ln.startswith("frame "): f = ln.split(" ") info = {f[i]: int(f[i + 1]) for i in range(2, len(f) - 1, 2)} From 565415bc4176ec03b1aced1844a26314fc34427b Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:16:55 -0500 Subject: [PATCH 2/5] Model L (D3D12): l_mode=fast levers: the fused post, the projections and the encoder block's linears without the hybrid's bit-exactness l_mode=fast launches a "_fast" twin in place of a base kernel when the build has one (same arguments; the base kernels, the hybrid twins and everything l_mode=hybrid runs are untouched, a build without a twin runs the base kernel): - w64_lc12/l_post_tf_p12[_pf]_fast (new l_post_tf_fast.hlsl): no driver intrinsic channel and no opaque-zero guards; native FP16 packs with the round-to-nearest bias folded into the multiplier; the gather weight is one v_exp_f16 and the total weight is summed in FP16 from the weights of the nine features; no FP16 code table (1 KB LDS, a barrier, six lookups per texel); Dec as exp2(q k) - 1 for every lane; the filter ring in FP16 pairs (LDS 26752 -> 23040 bytes). Options in pitch_bytes: the weaker history candidate as a bilinear (bit 0), and not read twice when its motion equals the first's (bit 1). - l_project_gather_fast / l_dec_project_fast: the K blocks accumulate in FP32 and round once, in the FP8 pack. - l_swin_block_c32_enc_lin_nc_fast: the linears' results stay FP32 (TT_LINF32). RGA (gfx1201), VALU instructions: post 2096 -> 1703 (pf 2356 -> 1705), project_gather 537 -> 281, dec_project 675 -> 419, enc_lin 997 -> 893; no spills, VGPRs within each kernel's bound. runtime: l_fast_alt maps each base kernel to its twin; warm-up leaves out the twins for l_mode=hybrid and, for l_mode=fast, the hybrid twins, the replaced base kernels and the twins of levers that are off; a developer build reads WG_L_FAST_MASK (an A/B of each lever; no such string in a release build, check_no_dev_diagnostics lists it). Tests: CPU accuracy bounds (clean/l/tests/test_l_fast_numerics.py), the twins' dispatch and the mask (test_l_runtime_fast_mode.py), kernel_sets.json. --- clean/dx12/README.md | 4 + clean/dx12/build_dx12.py | 13 +- clean/dx12/kernel_sets.json | 20 + clean/dx12/kernels/l_ops_project.hlsl | 15 + clean/dx12/kernels/l_post_tf_fast.hlsl | 632 ++++++++++++++++++ clean/dx12/kernels/l_swin_fast.hlsl | 10 + clean/dx12/tests/test_kernel_sets.py | 30 +- clean/dx12/vgpr_limits.json | 7 +- clean/l/SPEED.md | 18 + .../runtime/tests/test_l_runtime_fast_mode.py | 168 ++++- clean/l/tests/test_l_fast_numerics.py | 249 +++++++ clean/runtime/runtime.cpp | 66 +- clean/tests/check_no_dev_diagnostics.py | 2 + clean/tests/runtime_frame_trace.cpp | 4 +- clean/tests/test_dev_diagnostics_off.py | 2 +- 15 files changed, 1205 insertions(+), 35 deletions(-) create mode 100644 clean/dx12/kernels/l_post_tf_fast.hlsl create mode 100644 clean/l/tests/test_l_fast_numerics.py diff --git a/clean/dx12/README.md b/clean/dx12/README.md index 35330d61..c8edbbb9 100644 --- a/clean/dx12/README.md +++ b/clean/dx12/README.md @@ -128,6 +128,10 @@ 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). * 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 1c49e792..4fe81b64 100644 --- a/clean/dx12/build_dx12.py +++ b/clean/dx12/build_dx12.py @@ -33,7 +33,7 @@ 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, and Model L's fused post -w64_lc12/l_post_tf_p12[_pf]) is run through RGA (gfx1201) and its +w64_lc12/l_post_tf_p12[_pf][_fast]) 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 @@ -229,10 +229,11 @@ def kernel_decls(path): 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 twin (named *_fast: + Model L's l_mode=fast, launched in place of the kernel it is named after).""" 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 decl["name"].endswith("_fast")) def is_frame_gen(decl): @@ -331,8 +332,8 @@ def rga_isa(dxil, isa_dir, stem): def vgpr_checked(name): - # l_swin_*: Model L's blocks (#89); l_post_tf_p12[_pf]: Model L's fused post (bound = 96-register tier) - return re.search(r"(^|/|l_)swin_|/l_post_tf_p12(_pf)?$", name) is not None + # l_swin_*: Model L's blocks (#89); l_post_tf_p12[_pf][_fast]: Model L's fused post (bound = 96-register tier) + return re.search(r"(^|/|l_)swin_|/l_post_tf_p12(_pf)?(_fast)?$", name) is not None def rga_vgprs(dxil, isa=False): diff --git a/clean/dx12/kernel_sets.json b/clean/dx12/kernel_sets.json index c6863009..fc875235 100644 --- a/clean/dx12/kernel_sets.json +++ b/clean/dx12/kernel_sets.json @@ -234,6 +234,10 @@ "l_dec_project", "l_ops.co" ], + [ + "l_dec_project_fast", + "-" + ], [ "l_direct_color", "-" @@ -286,6 +290,10 @@ "l_project_gather", "l_ops.co" ], + [ + "l_project_gather_fast", + "-" + ], [ "l_q7_block_c128", "l_q7w.co" @@ -366,6 +374,10 @@ "l_swin_block_c32_enc_lin_nc", "-" ], + [ + "l_swin_block_c32_enc_lin_nc_fast", + "-" + ], [ "l_swin_block_c32_enc_nc", "l_swin.co" @@ -505,6 +517,14 @@ [ "w64_lc12/l_post_recon_p12_ldr", "l_post__lc12.co" + ], + [ + "w64_lc12/l_post_tf_p12_fast", + "-" + ], + [ + "w64_lc12/l_post_tf_p12_pf_fast", + "-" ] ], "model_k": [ diff --git a/clean/dx12/kernels/l_ops_project.hlsl b/clean/dx12/kernels/l_ops_project.hlsl index d3d070c9..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. // +// 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; @@ -83,8 +96,10 @@ WG_KERNEL(l_project_gather) 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); 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..24a5ae2a --- /dev/null +++ b/clean/dx12/kernels/l_post_tf_fast.hlsl @@ -0,0 +1,632 @@ +// 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 +#include "wg_platform.hlsli" +#ifndef LP_PIDIV +#define LP_PIDIV 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 + +#define kStageCap 512 // staged render texels per step (6 dwords each: 12288 bytes); one per lane +#define kTexDw 6 // staged texel: f0 f1 | f2 f3 | f4 f5 | f6 f7 | f8 kA | kB kC (FP16 bits) +#define kLWin 4 +#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 + +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)); } + +// ---- 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 = wg_ld4f(color, ui * 16u); + r.d = wg_ld64(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; + r0 = floor_i(lpy(ys) - 0.5f) - 1; + return floor_i(lpy(yl) - 0.5f) + 2 - r0 + 1; +} + +// ---- 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 +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) +{ + 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 < kLWin; ++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))); + const half w1 = exp2(mad(u * v1[jj], kC, mad(vv1[jj], kB, ta))); + tap_acc(g0, t, w0); + tap_acc(g1, t, w1); + } +} + +// ---- 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 = 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); + 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(wg_mem.Load2(ro[0] + co[2])), wx.y * h3(wg_mem.Load2(ro[0] + co[1]))); + 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])), wx.x * h3(wg_mem.Load2(ro[1] + co[0]))))); + 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])), wx.x * h3(wg_mem.Load2(ro[2] + co[0]))))); + const float3 r3 = mad(wx.z, h3(wg_mem.Load2(ro[3] + co[2])), wx.y * h3(wg_mem.Load2(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(wg_mem.Load2(ra + cb)) - h3(wg_mem.Load2(ra + ca)), h3(wg_mem.Load2(ra + ca))); + const float3 t1 = mad(fx, h3(wg_mem.Load2(rb + cb)) - h3(wg_mem.Load2(rb + ca)), h3(wg_mem.Load2(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]; + [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); + L[n][0] = dec_hist(h.x); + L[n][1] = dec_hist(h.y); + L[n][2] = 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]; + [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]; + 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; +#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) + 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(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); + 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 + 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; + [loop] for (int i = -1; i <= (kLWin - 2); ++i) + gather_col(i, dx, tb0, rstride, 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); + 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_fast.hlsl b/clean/dx12/kernels/l_swin_fast.hlsl index 714d6cdb..29aa8c4e 100644 --- a/clean/dx12/kernels/l_swin_fast.hlsl +++ b/clean/dx12/kernels/l_swin_fast.hlsl @@ -19,4 +19,14 @@ // // @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/tests/test_kernel_sets.py b/clean/dx12/tests/test_kernel_sets.py index 52617fde..d238bf9d 100644 --- a/clean/dx12/tests/test_kernel_sets.py +++ b/clean/dx12/tests/test_kernel_sets.py @@ -48,10 +48,10 @@ def test_model_l_adds_only_model_l_kernels(self): self.assertTrue(m <= full) extra = full - m self.assertTrue(extra) - # Model L's kernels: its code objects, the l_* direct-route kernels, MODEL_L_ONLY, and the hybrid twins (*_hyb: - # Model L's route only; build_dx12.py is_model_l) + # Model L's kernels: its code objects, the l_* direct-route kernels, MODEL_L_ONLY, the hybrid twins (*_hyb) and the + # fast-mode twins (*_fast): Model L's route only; build_dx12.py is_model_l) self.assertFalse([k for k in extra if not (k[1].startswith("l_") or k[0].startswith("l_") or k[0] in B.MODEL_L_ONLY - or k[0].endswith("_hyb"))]) + or k[0].endswith("_hyb") or k[0].endswith("_fast"))]) def test_model_k_adds_only_model_k_kernels(self): @@ -91,6 +91,30 @@ def test_frame_gen_kernels_are_in_no_set(self): self.assertFalse([k for k in fg if k in full]) + def test_fast_twins_take_their_base_kernels_arguments(self): + """A "_fast" twin (Model L's l_mode=fast) is launched by the runtime in place of its base kernel with the same + grid, block and arguments: the declarations agree in block, wave, args and (for a twin of a kernel with a launch + shape of its own) group; the twin has no HIP code object, and is in Model L's set only.""" + decls = {} + for fn in sorted(os.listdir(B.KERNEL_DIR)): + if fn.endswith(".hlsl"): + for d in B.kernel_decls(os.path.join(B.KERNEL_DIR, fn)): + decls.setdefault(d["name"], []).append(d) + twins = [n for n in decls if n.endswith("_fast")] + self.assertTrue(twins) + full, m = set(B.kernel_set(True)), set(B.kernel_set(False)) + for n in twins: + base = n[:-5] + self.assertIn(base, decls, n) + (t,) = decls[n] + self.assertEqual(t["co"], "-", n) + self.assertTrue(B.is_model_l(t), n) + self.assertIn((n, "-"), full - m, n) + for b in decls[base]: + for key in ("block", "wave", "args", "group", "gscale"): + self.assertEqual(t.get(key), b.get(key), (n, key)) + + if __name__ == "__main__": if "--write" in sys.argv: with open(SETS, "w", newline="\n") as f: diff --git a/clean/dx12/vgpr_limits.json b/clean/dx12/vgpr_limits.json index 019b3696..665115ec 100644 --- a/clean/dx12/vgpr_limits.json +++ b/clean/dx12/vgpr_limits.json @@ -1,5 +1,5 @@ { - "_doc": "build_dx12.py VGPR check: the RGA (gfx1201) USED_VGPRs bound of every Swin / bottleneck kernel (a name with a swin_ part) and Model L's fused post (w64_lc12/l_post_tf_p12[_pf]). Each bound is the largest count that keeps the kernel's present occupancy: VGPR file 1536 per SIMD lane, granule 8, a 256-lane wave32 workgroup = 4 waves on each of a CU's 2 SIMDs, so 2 workgroups per CU need <= 192, 3 need <= 128 (a 128-lane workgroup = 2 waves per SIMD: 4 per CU need <= 192). A kernel over its bound fails the build (a merge or an edit lost a workgroup per CU: swin_block_c96_add_xe_* at 215 VGPRs ran 1 per CU, +38 us per frame at 1440p Q). Model L's fused post (block = 512 lanes, wave64, 26,752 bytes of LDS: 2 workgroups per CU = 8 waves64 per SIMD) is bounded at 96. A new Swin / bottleneck kernel needs an entry. WG_DX12_VGPR_CHECK=0 skips the check.", + "_doc": "build_dx12.py VGPR check: the RGA (gfx1201) USED_VGPRs bound of every Swin / bottleneck kernel (a name with a swin_ part) and Model L's fused post (w64_lc12/l_post_tf_p12[_pf]). Each bound is the largest count that keeps the kernel's present occupancy: VGPR file 1536 per SIMD lane, granule 8, a 256-lane wave32 workgroup = 4 waves on each of a CU's 2 SIMDs, so 2 workgroups per CU need <= 192, 3 need <= 128 (a 128-lane workgroup = 2 waves per SIMD: 4 per CU need <= 192). A kernel over its bound fails the build (a merge or an edit lost a workgroup per CU: swin_block_c96_add_xe_* at 215 VGPRs ran 1 per CU, +38 us per frame at 1440p Q). Model L's fused post (block = 512 lanes, wave64, 26,752 bytes of LDS: 2 workgroups per CU = 8 waves64 per SIMD) is bounded at 96; its fast-mode twins (w64_lc12/l_post_tf_p12[_pf]_fast, 23,040 bytes) keep that tier, and the fast-mode Swin twin of the encoder block the bound of its base. A new Swin / bottleneck kernel needs an entry. WG_DX12_VGPR_CHECK=0 skips the check.", "l_swin_block_c32_nc": 96, "l_swin_block_c32_enc_nc": 96, "l_swin_block_c32_enc_lin_nc": 96, @@ -36,6 +36,7 @@ "l_swin_block_c32_dec_coef12_nc": 96, "l_swin_block_c32_dec_add_nc": 96, "l_swin_block_c32_dec_coef12_add_nc": 96, + "l_swin_block_c32_enc_lin_nc_fast": 96, "swin_block_c64_nc": 192, "swin_block_c64_add_ex_nc": 192, "swin_block_c96_nc": 192, @@ -52,5 +53,7 @@ "d1p12/swin_block_c64_add_dec0_nc": 192, "d1p12/swin_block_c64_add_dec0_xd_nc": 192, "w64_lc12/l_post_tf_p12": 96, - "w64_lc12/l_post_tf_p12_pf": 96 + "w64_lc12/l_post_tf_p12_pf": 96, + "w64_lc12/l_post_tf_p12_fast": 96, + "w64_lc12/l_post_tf_p12_pf_fast": 96 } diff --git a/clean/l/SPEED.md b/clean/l/SPEED.md index b2532002..c3adb077 100644 --- a/clean/l/SPEED.md +++ b/clean/l/SPEED.md @@ -90,6 +90,24 @@ reason where a kernel it needs is missing from the build (a build made with `--m build's `variants.json` and `swin__bmegahg.co`). No timing is published for it yet: a figure goes on this page only with its measurement record. +The levers of the preset (each a kernel of the build named `_fast`, launched in place of its base kernel with the +same arguments; the base kernels and everything `l_mode=hybrid` runs are untouched, and a build without a twin simply runs +the base kernel). They drop the bit-exactness of the hybrid route where it costs instructions and keeps the model's values: + +| lever | kernel | what it changes | +|---|---|---| +| 1 | `w64_lc12/l_post_tf_p12[_pf]_fast` | the fused reconstruction + output filter without the driver intrinsic channel and the opaque-zero guards; native FP16 packs with the round-to-nearest bias folded in; the gather's weight is one `v_exp_f16` of the FP16 exponent and the total weight is summed in FP16 from the same weights as the nine features; no 1 KB code table; `Dec` as `exp2(q k) - 1` for every lane; the horizontal filter ring in FP16 pairs (LDS 26 752 -> 23 040 bytes) | +| 2 | `l_project_gather_fast`, `l_dec_project_fast` | the K blocks accumulate in FP32 and round once, in the FP8 pack (no FP16 rounding after every 32 inputs) | +| 4 | `l_swin_block_c32_enc_lin_nc_fast` | the two input linears of the encoder block keep their results in FP32 (no FP16 rounding of x1, x2) | +| 16 | (option of lever 1) | the weaker history candidate (weight at most 1/2) is a 4-tap bilinear of the previous history instead of the 12-tap Catmull-Rom | +| 64 | (option of lever 1) | a weaker history candidate whose motion is within 0.01 render pixel of the first one's is the same sample and is not read twice | +| 128 | (option of lever 1, off by default) | a weaker history candidate of weight below 0.05 is dropped (the hybrid route drops it below 1 / 255) | + +A developer build (`dev_diagnostics`) reads the selection of levers from `WG_L_FAST_MASK` (the sum of the lever values +above; the default is 127: every lever and option but 128) for an A/B of each; a release build has no such variable. The arithmetic choices are bounded +on the CPU by `clean/l/tests/test_l_fast_numerics.py` (the quality gate itself is measured on the GPU against +`l_mode=hybrid`: tone-mapped PSNR / SSIM and temporal stability). + ## Building Model L Model L is off in a default build. It is built with the `--model-l` option of the two build scripts: diff --git a/clean/l/runtime/tests/test_l_runtime_fast_mode.py b/clean/l/runtime/tests/test_l_runtime_fast_mode.py index d17dc0c2..db9434e2 100644 --- a/clean/l/runtime/tests/test_l_runtime_fast_mode.py +++ b/clean/l/runtime/tests/test_l_runtime_fast_mode.py @@ -30,6 +30,7 @@ import numpy as np import test_l_runtime_frame as F +from clean.tests import host_cxx from clean.l.reference import oracle as L from clean.l.runner import l_pack as LP from clean.runner import packing as P @@ -52,8 +53,23 @@ SIZES = "--sizes=96x64,96x64,80x48,80x48,80x48,77x45" +class FastTrace(FT.Trace): + """FT.Trace with the "_fast" twins folded back onto their base names (the lever kernels the fast route launches in place + of a base kernel, same arguments): every launch reads as the base kernel; frame["fast"] lists the twins launched.""" + + def __init__(self, lines): + super().__init__(lines) + for f in self.frames: + f["fast"] = [ln.kernel for ln in f["launches"] if ln.kernel.endswith("_fast")] + for ln in f["launches"]: + if ln.kernel.endswith("_fast"): + ln.kernel = ln.kernel[:-5] + if f["failed"] and f["failed"].endswith("_fast"): + f["failed"] = f["failed"][:-5] + + def l_run(options="model=L", ports=None, frames=3, flags=(), backend=3, rw=F.RW, rh=F.RH, hdr=1, env=None, - tf_default=False, variants=True): + tf_default=False, variants=True, exe=None): """The trace program's lines (the arguments of test_l_runtime_frame.run). variants: the build folder holds the variants.json and swin__bmegahg.co of a full build (the bottleneck in one launch by default, Model M's geometry variants; without them the six block launches, which D3D12 has no port of).""" @@ -73,7 +89,7 @@ def l_run(options="model=L", ports=None, frames=3, flags=(), backend=3, rw=F.RW, e["WG_L_POST_TF"] = "0" e.update(env or {}) try: - r = subprocess.run([F.trace_exe(), build, F.model_dir(), str(rw), str(rh), "120", "72", str(frames), options, + r = subprocess.run([exe or F.trace_exe(), build, F.model_dir(), str(rw), str(rh), "120", "72", str(frames), options, "--format=0", "--map=" + F.map_path(), "--hdr=%d" % hdr, "--backend=%d" % backend, *flags], capture_output=True, text=True, env=e, timeout=600) finally: @@ -125,7 +141,7 @@ def test_hybrid_needs_no_fast_kernel(self): a = F.same_frames(l_run("model=L", frames=3, rw=96, rh=64, variants=False)) b = F.same_frames(l_run("model=L", ports=without(*FAST_ONLY), frames=3, rw=96, rh=64, variants=False)) self.assertEqual(a, b) - t = FT.Trace(l_run("model=L", frames=3, rw=96, rh=64, variants=False)) + t = FastTrace(l_run("model=L", frames=3, rw=96, rh=64, variants=False)) self.assertEqual([n for f in t.frames for n in names(f) if n in FAST_ONLY], []) def test_warm_up_scope(self): @@ -133,21 +149,28 @@ def test_warm_up_scope(self): hybrid (the default) the two fast-only decoder blocks and nothing else; fast the hybrid twins, the FP16-form q7 blocks and the no-skip decoder blocks, none of the kernels its own route launches. Model M: nothing.""" ports = [k for k, _ in F.full_ports()] - t = FT.Trace(l_run("model=L", frames=1, rw=96, rh=64, variants=False, flags=("--warm-skip",))) - self.assertEqual(sorted(t.warm_skip), sorted(FAST_ONLY)) - t = FT.Trace(l_run("model=L", ports=without(*FAST_ONLY), frames=1, rw=96, rh=64, variants=False, + fast_twins = [k for k in ports if k.endswith("_fast")] + self.assertTrue(fast_twins) + t = FastTrace(l_run("model=L", frames=1, rw=96, rh=64, variants=False, flags=("--warm-skip",))) + self.assertEqual(sorted(t.warm_skip), sorted(FAST_ONLY + tuple(fast_twins))) + t = FastTrace(l_run("model=L", ports=without(*FAST_ONLY, *fast_twins), frames=1, rw=96, rh=64, variants=False, flags=("--warm-skip",))) self.assertEqual(t.warm_skip, []) - t = FT.Trace(l_run("model=L,l_mode=fast", frames=1, rw=96, rh=64, flags=("--warm-skip",))) + t = FastTrace(l_run("model=L,l_mode=fast", frames=1, rw=96, rh=64, flags=("--warm-skip",))) twins = [k for k in ports if k.endswith("_hyb")] self.assertTrue(twins) + replaced = {k[:-5] for k in fast_twins if k[:-5] in ports} # the base kernels a fast twin replaces want = set(twins) | {k for k in ports if k.startswith("l_q7_")} | {"l_swin_block_c32_dec_nc", - "l_swin_block_c32_dec_coef12_nc"} + "l_swin_block_c32_dec_coef12_nc"} | replaced + self.assertTrue(replaced) self.assertEqual(sorted(t.warm_skip), sorted(want)) - launched = {n for f in t.frames for n in names(f)} + launched = {n for f in t.frames for n in names(f)} - replaced # (a twin is launched in place of its base kernel) self.assertEqual(launched & set(t.warm_skip), set()) - self.assertEqual(set(FAST_NEEDS) & set(t.warm_skip), set()) - t = FT.Trace(F.run("", frames=1, build_files=FT.SHIPPING, flags=("--backend=3", "--warm-skip"), + self.assertEqual({k for f in t.frames for k in f["fast"]} & set(t.warm_skip), set()) + # every kernel the route launches (a twin in place of its base) is warmed up: not a base that a twin replaces + self.assertEqual(set(FAST_NEEDS) - replaced & set(t.warm_skip), set()) + self.assertEqual({k for k in fast_twins} & set(t.warm_skip), set()) + t = FastTrace(F.run("", frames=1, build_files=FT.SHIPPING, flags=("--backend=3", "--warm-skip"), manifest=F.full_ports())) self.assertEqual(t.warm_skip, []) @@ -162,7 +185,7 @@ def test_values_are_checked(self): def test_precedence(self): """The option over WG_L_MODE; WG_RUNTIME_OPTIONS over the configuration string (as every runtime option).""" def mode(options, env=None): - t = FT.Trace(l_run(options, frames=1, rw=96, rh=64, env=env)) + t = FastTrace(l_run(options, frames=1, rw=96, rh=64, env=env)) self.assertEqual(t.create, "create ok model L") return t.kernels.get("l_mode", "hybrid") self.assertEqual(mode("model=L,l_mode=fast"), "fast") @@ -199,7 +222,7 @@ class Fast(unittest.TestCase): """The fast route's dispatch plan on native D3D12.""" def trace(self, ports=None, frames=3, env=None, tf=False, **kw): - t = FT.Trace(l_run("model=L,l_mode=fast", ports=ports, frames=frames, env=env, tf_default=tf, **kw)) + t = FastTrace(l_run("model=L,l_mode=fast", ports=ports, frames=frames, env=env, tf_default=tf, **kw)) self.assertEqual(t.create, "create ok model L", t.create) self.assertEqual(t.unknown(), []) return t @@ -324,7 +347,8 @@ def test_hybrid_twins_not_needed(self): def test_failed_launch_stops_the_frame(self): for kernel, before in ((FOLD_ADD, "l_dec_project"), ("lc12/l_post_recon_p12", FOLD_ADD)): with self.subTest(kernel=kernel): - t = FT.Trace(l_run("model=L,l_mode=fast", frames=3, flags=("--fail=%s@1" % kernel,), tf_default=False)) + fail = kernel + "_fast" if kernel + "_fast" in twins() else kernel # launched as its twin + t = FastTrace(l_run("model=L,l_mode=fast", frames=3, flags=("--fail=%s@1" % fail,), tf_default=False)) ok0, bad, ok2 = t.frames self.assertEqual(bad["failed"], kernel) self.assertEqual(names(bad)[-1], before) @@ -334,7 +358,7 @@ def test_failed_launch_stops_the_frame(self): def test_ldr_and_fallback_post(self): """LDR colour and a frame the pack12 kernels do not take run the same decoder block (skip) and the lc12 forms.""" ports = F.full_ports() + [kc for hdr in F.D3D12.OWN for kc in F.D3D12.OWN[hdr] if kc not in F.full_ports()] - t = FT.Trace(l_run("model=L,l_mode=fast", ports=ports, frames=2, rw=96, rh=64, hdr=0)) + t = FastTrace(l_run("model=L,l_mode=fast", ports=ports, frames=2, rw=96, rh=64, hdr=0)) self.assertEqual(t.create, "create ok model L") for f in t.frames: n = names(f) @@ -342,5 +366,119 @@ def test_ldr_and_fallback_post(self): self.assertIn("lc12/l_post_recon_p12_ldr", n) +def twins(): + return [k for k, _ in F.full_ports() if k.endswith("_fast")] + + +def shape(t): + """Per frame: the launches as (base kernel, grid, block, arguments). The fused post's pitch_bytes (argument 18) is the + option word of its twin (bit 0: the weaker history candidate as a bilinear), the row pitch of the base kernel.""" + out = [] + for f in t.frames: + fr = [] + for ln in f["launches"]: + a = list(ln.args) + if ln.kernel.startswith("w64_lc12/l_post_tf_p12") and len(a) > 18: + a[18] = "*" + fr.append((ln.kernel, ln.grid, ln.block, tuple(a))) + out.append(fr) + return out + + +class FastKernels(unittest.TestCase): + """The "_fast" twins of the fast route (kernels of the build named "_fast": the same launch, grid, block and + arguments in place of the base kernel), selected by lever bits (runtime.cpp l_fast_mask; WG_L_FAST_MASK in developer + builds, which the trace program is not).""" + + # the twins the route launches per frame at the fast route's default (fused post on, lc / le / ll fusions, mb bottleneck) + LEVERS = ("l_project_gather", "l_dec_project", ENC_LIN, "w64_lc12/l_post_tf_p12") + + def test_twins_declared(self): + t = set(twins()) + for k in self.LEVERS: + self.assertIn(k + "_fast", t) + for k in t: + self.assertIn(k[:-5], [x for x, _ in F.full_ports()], k) # every twin replaces a base kernel of the build + + def test_launched_in_place_of_the_base_kernel(self): + a = FastTrace(l_run("model=L,l_mode=fast", frames=3, tf_default=True)) + self.assertEqual(a.create, "create ok model L") + b = FastTrace(l_run("model=L,l_mode=fast", ports=without(*twins()), frames=3, tf_default=True)) + self.assertEqual(b.create, "create ok model L") + self.assertEqual(shape(a), shape(b)) # the same launches with the same arguments, twins or not + for f in a.frames: + for k in self.LEVERS: + self.assertIn(k + "_fast", f["fast"], f["fast"]) + for f in b.frames: + self.assertEqual(f["fast"], []) + self.assertEqual(a.kernels.get("l_fast_kernels"), str(len(twins()))) + self.assertEqual(b.kernels.get("l_fast_kernels"), "0") + + def test_pre_exposure_post_twin(self): + t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, flags=("--pre-exposure=2.0",))) + for f in t.frames: + self.assertIn("w64_lc12/l_post_tf_p12_pf_fast", f["fast"]) + self.assertNotIn("w64_lc12/l_post_tf_p12_fast", f["fast"]) + + def test_every_lever_on_by_default(self): + t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True)) + self.assertNotIn("l_fast_mask", t.kernels) # (only a developer build reports it) + + def test_hybrid_launches_no_twin(self): + t = FastTrace(l_run("model=L", frames=3, variants=False, tf_default=True)) + self.assertEqual([f["fast"] for f in t.frames], [[], [], []]) + self.assertNotIn("l_fast_kernels", t.kernels) + # a hybrid build with or without the twins in its manifest: the same frames + b = FastTrace(l_run("model=L", ports=without(*twins()), frames=3, variants=False, tf_default=True)) + self.assertEqual(shape(t), shape(b)) + + +_DEV_EXE = None + + +def dev_exe(): + """The trace program built as a developer build (WG_DEV_DIAGNOSTICS: WG_L_FAST_MASK is read).""" + global _DEV_EXE + if _DEV_EXE is None: + _DEV_EXE = host_cxx.build("runtime_frame_trace_ldev", FT.SOURCES + F.L_SOURCES, + ["WG_NO_MODEL_K", "WG_MODEL_L", "WG_DEV_DIAGNOSTICS"]) + return _DEV_EXE + + +class FastMask(unittest.TestCase): + """The A/B of the fast levers: WG_L_FAST_MASK in a developer build (bit values: runtime.cpp l_fast_mask); a release + build has no such variable (it runs every lever whatever the environment says).""" + POST = {"w64_lc12/l_post_tf_p12_fast"} + PROJECT = {"l_project_gather_fast", "l_dec_project_fast"} + ENC = {"l_swin_block_c32_enc_lin_nc_fast"} + + def launched(self, mask, exe, **kw): + t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, exe=exe, env={"WG_L_FAST_MASK": str(mask)}, + flags=("--warm-skip",), **kw)) + self.assertEqual(t.create, "create ok model L") + sets = [set(f["fast"]) for f in t.frames] + self.assertEqual(sets[0], sets[1]) + return sets[0], t + + def test_developer_mask(self): + exe = dev_exe() + for mask, want in ((127, self.POST | self.PROJECT | self.ENC), (255, self.POST | self.PROJECT | self.ENC), (0, set()), (1, self.POST), (2, self.PROJECT), + (4, self.ENC), (1 | 4, self.POST | self.ENC), (16 | 64 | 128, set())): + with self.subTest(mask=mask): + got, t = self.launched(mask, exe) + self.assertEqual(got, want) + self.assertEqual(t.kernels.get("l_fast_mask"), str(mask)) + # a twin of a lever that is off is left out of the warm-up (and not launched) + skip = set(t.warm_skip) + for twin in twins(): + bit = 1 if twin.startswith("w64_lc12/") else (2 if "project" in twin else 4) + self.assertEqual(twin in skip, not (mask & bit), twin) + + def test_release_build_has_no_mask(self): + got, t = self.launched(0, None) # the release trace program: the variable is not read + self.assertEqual(got, self.POST | self.PROJECT | self.ENC) + self.assertNotIn("l_fast_mask", t.kernels) + + if __name__ == "__main__": unittest.main() diff --git a/clean/l/tests/test_l_fast_numerics.py b/clean/l/tests/test_l_fast_numerics.py new file mode 100644 index 00000000..03f874c7 --- /dev/null +++ b/clean/l/tests/test_l_fast_numerics.py @@ -0,0 +1,249 @@ +# SPDX-License-Identifier: MIT +"""CPU accuracy checks of the arithmetic choices of Model L's l_mode=fast kernels (no GPU). + + python -m unittest clean.l.tests.test_l_fast_numerics + +Each test models one choice of clean/dx12/kernels/l_post_tf_fast.hlsl / l_ops_project.hlsl in NumPy (float32 / float16 +arithmetic as the instructions give it) and bounds its error against the exact form: + * Dec as exp2(q kDecK) - 1 for every lane against the 7-term polynomial the hybrid route uses below kDecPolyMax; + * the round-to-nearest bias folded into a multiplier (kRn) and the half-FP16-step integer add (rn16) in front of the + truncating pack v_cvt_pk_rtz_f16_f32; + * the 16-bit horizontal Lanczos ring (two FP16 per dword) against the FP32 ring; + * the FP16 tap weight (v_exp_f16) with the total weight summed in FP16 from the same weights, against the FP32 gather; + * the MLP GELU forms (the arithmetic chain of the M-form kernels and the plain tanh form) against the erf GELU; + * the FP32 accumulation of the projections' K blocks against the stepwise FP16-rounded sum. +Numbers are printed with -v; the bounds are the ones the fast route is gated on (tone-mapped PSNR >= 48 dB per choice). +""" +import math +import unittest + +import numpy as np + +f32 = np.float32 +f16 = np.float16 + + +def bits(x): + return np.asarray(x, dtype=f32).view(np.uint32) + + +def from_bits(u): + return np.asarray(u, dtype=np.uint32).view(f32) + + +def rtz16(x): + """v_cvt_pk_rtz_f16_f32: round toward zero (the plain f32tof16 / (half) cast on this driver).""" + x = np.asarray(x, dtype=f32) + h = x.astype(f16) # nearest even + back = h.astype(f32) + # where the nearest value is larger in magnitude than x, step one FP16 ulp toward zero + over = np.abs(back) > np.abs(x) + hb = h.view(np.uint16).astype(np.int32) + hb = np.where(over, hb - 1, hb) + return hb.astype(np.uint16).view(f16) + + +def rn16(x): + """l_post_tf_fast.hlsl rn16: + half an FP16 step (bit pattern + 0x1000), then the truncating pack.""" + return rtz16(from_bits(bits(x) + np.uint32(0x1000))) + + +class DecFast(unittest.TestCase): + kDecK = f32(3.32192809488736235) / f32(0.36) + kDecLn = f32(2.30258509299404568) / f32(0.36) + kDecPolyMax = f32(0.35) / kDecLn + + def poly(self, q): + y = q * self.kDecLn + t = y * f32(1 / 5040) + f32(1 / 720) + for c in (f32(1 / 120), f32(1 / 24), f32(1 / 6), f32(0.5), f32(1.0)): + t = t * y + c + return t * y + + def test_dec_plain_vs_poly(self): + q = np.linspace(1e-4, float(self.kDecPolyMax), 200001, dtype=f32) + plain = np.exp2(q * self.kDecK).astype(f32) - f32(1.0) + ref = np.expm1(q.astype(np.float64) * float(self.kDecLn)) + err_plain = np.abs(plain - ref).max() + err_poly = np.abs(self.poly(q) - ref).max() + # Dec's output is 0.01 times this value times dec_scale: the absolute error in units of the output + print("Dec plain max abs err %.3g (poly %.3g), x 0.01 = %.3g" % (err_plain, err_poly, err_plain * 0.01)) + self.assertLess(err_plain, 1.5e-6) # the polynomial form's own error is 1e-7 order; both are below 1e-5 + # relative at the darkest clamp (q = 1e-4): the plain form keeps 3 digits, below the display's FP16 resolution + self.assertLess(abs(plain[0] - ref[0]) / ref[0], 5e-4) + + def test_dec_fold_g_k_hist(self): + # (exp2(.) - 1) * (0.01 e / e_prev) against ((exp2(.) - 1) * 0.01) / e_prev * e (the hybrid order): <= 2 ulp + rng = np.random.default_rng(1) + q = rng.uniform(1e-4, 3.0, 100000).astype(f32) + e, ep = f32(0.37), f32(1.9) + v = np.exp2(q * self.kDecK).astype(f32) - f32(1.0) + a = v * f32(f32(0.01) * e / ep) + b = (v * f32(0.01)) * (f32(1.0) / ep) * e + self.assertLess(np.abs(a / b - 1).max(), 3e-7) + + +class RoundingFold(unittest.TestCase): + kRn = f32(1.00034) + + def test_rn16_matches_rne_except_ties(self): + rng = np.random.default_rng(2) + x = (rng.uniform(0.02, 3.0, 400000).astype(f32)) * rng.choice([-1, 1], 400000).astype(f32) + want = x.astype(f16) # nearest even + got = rn16(x) + diff = (got.view(np.uint16) != want.view(np.uint16)).mean() + print("rn16 differs from RNE in %.5f%% of random inputs (exact ties go away from zero)" % (100 * diff)) + self.assertLess(diff, 1e-4) + self.assertLessEqual(np.abs(got.astype(f32) - x).max(), np.abs(want.astype(f32) - x).max() + 1e-12) + + def test_kRn_fold_unbiased(self): + rng = np.random.default_rng(3) + x = np.exp(rng.uniform(math.log(0.01), math.log(3.0), 400000)).astype(f32) + bias_plain = float(np.mean((rtz16(x).astype(np.float64) - x) / x)) + got = rtz16(x * self.kRn).astype(np.float64) + bias_fold = float(np.mean((got - x) / x)) + worst = float(np.max(np.abs(got - x) / x)) + print("mean relative error of the truncating pack %.3g; with the kRn fold %.3g (worst %.3g; RNE worst 4.9e-4)" % + (bias_plain, bias_fold, worst)) + self.assertLess(abs(bias_fold), 0.15 * abs(bias_plain)) + self.assertLess(abs(bias_fold), 6e-5) + self.assertLess(worst, 1.1e-3) + + +# post_filter_c1_s4's analytic Lanczos taps (l_post_tf.hlsl kLz0 .. kLz4) +KLZ = from_bits([0xbdba3b4b, 0x3de71ca9, 0x3f23b70f, 0x3ed182b5, 0xbd90a4ac]) + + +def lz5a(t, w): + v = w[0] * t[0] + for k in range(1, 5): + v = np.float32(w[k]) * t[k] + v + lo = np.minimum.reduce(t) + hi = np.maximum.reduce(t) + return np.minimum(np.maximum(v, lo), hi) + + +class Ring16(unittest.TestCase): + def test_fp16_ring_psnr(self): + rng = np.random.default_rng(4) + H, W = 60, 192 + # display-domain values (E-encoded, [0, 2.45]): smooth gradients, texture and edges, already FP16 on entry + yy, xx = np.mgrid[0:H, 0:W].astype(f32) + img = 1.2 + 0.7 * np.sin(xx / 17.0) * np.cos(yy / 11.0) + 0.15 * rng.standard_normal((H, W)).astype(f32) + img[:, 70:76] = 0.1 + img[20:30, :] += 0.8 + img = np.clip(img, 0.0, 2.45).astype(f16) + wev = [KLZ[0], KLZ[1], KLZ[3], KLZ[4]] + w_even = [KLZ[0], KLZ[1], KLZ[2], KLZ[3], KLZ[4]] + w_odd = [KLZ[4], KLZ[3], KLZ[2], KLZ[1], KLZ[0]] + t0 = img.astype(f32) + # horizontal 3:2 decimation as the kernel: output columns 4g .. 4g + 3 from display columns 6g .. 6g + 9 + cols = [] + for g in range(W // 6 - 1): + tp = [t0[:, 6 * g + i] for i in range(10)] + cols += [lz5a(tp[0:5], w_even), lz5a(tp[2:7], w_odd), lz5a(tp[3:8], w_even), lz5a(tp[5:10], w_odd)] + hz = np.stack(cols, axis=1).astype(f32) + + def vertical(ring): + # 3:2 vertical: output row pairs from 5 ring rows (even phase / odd phase), as the vertical pass + outs = [] + for p in range(2, H // 3 - 2): + for dy in (0, 1): + r0 = 3 * p - 2 + 2 * dy + outs.append(lz5a([ring[r0 + k] for k in range(5)], w_even if dy == 0 else w_odd)) + return np.stack(outs) + + ref = vertical(hz) + alt = vertical(np.array([rn16(row).astype(f32) for row in hz])) + dec = lambda q: (np.exp2(np.clip(q, 1e-4, 3.0) * np.float32(9.2275)) - 1) * 0.01 + # tone-mapped (gamma 1/2.2 of the linear value, relative to a 10-unit white) PSNR of the linear output + a, b = dec(ref), dec(alt) + tm = lambda v: np.clip(v / 10.0, 0, 1) ** (1 / 2.2) + mse = np.mean((tm(a) - tm(b)) ** 2) + psnr = 10 * math.log10(1.0 / mse) + print("FP16 ring vs FP32 ring: tone-mapped PSNR %.1f dB, max |dq| %.3g" % (psnr, np.abs(ref - alt).max())) + self.assertGreater(psnr, 55.0) + + +class GatherHalf(unittest.TestCase): + def test_half_weights_fbar(self): + rng = np.random.default_rng(5) + n = 20000 + # eps = kA u^2 + kB v^2 + kC u v per tap (4 x 4 window), kernel shapes like the staged ones (negative definite) + u = (rng.uniform(-0.5, 0.5, (n, 1)) + np.arange(-1, 3)[None, :]).astype(f16) # columns + v = (rng.uniform(-0.5, 0.5, (n, 1)) + np.arange(-1, 3)[None, :]).astype(f16) # rows + kA = (-0.7213 * rng.uniform(0.3, 1.6, n)).astype(f16) + kB = (-0.7213 * rng.uniform(0.3, 1.6, n)).astype(f16) + kC = (-1.4427 * rng.uniform(-0.4, 0.4, n)).astype(f16) + feat = (rng.uniform(0, 1, (n, 4, 4, 9)) * 0.5 + 0.3 * np.sin(np.arange(16).reshape(4, 4)[None, :, :, None])).astype(f16) + # reference: FP32 weights, FP32 sums + U = u.astype(np.float64)[:, None, :] * np.ones((1, 4, 1)) + V = v.astype(np.float64)[:, :, None] * np.ones((1, 1, 4)) + eps32 = kA.astype(np.float64)[:, None, None] * U**2 + kB.astype(np.float64)[:, None, None] * V**2 + \ + kC.astype(np.float64)[:, None, None] * U * V + w32 = 2.0 ** eps32 + ref = (w32[..., None] * feat.astype(np.float64)).sum((1, 2)) / w32.sum((1, 2))[:, None] + # fast: FP16 eps (fma chain), v_exp_f16 (nearest, +- 1 ulp), FP16 sums of w f and w + Uh, Vh = U.astype(f16), V.astype(f16) + uu = (Uh * Uh) + eps16 = (Uh * Vh * kC[:, None, None]) + ((Vh * Vh) * kB[:, None, None] + uu * kA[:, None, None]) + w16 = np.exp2(eps16.astype(f32)).astype(f16) + ulp = rng.integers(-1, 2, w16.shape) # the hardware exponential is faithful, not always nearest + w16 = (w16.view(np.uint16).astype(np.int32) + ulp).clip(0, 0x7bff).astype(np.uint16).view(f16) + F = np.zeros((n, 9), dtype=f16) + W = np.zeros(n, dtype=f16) + for i in range(4): + for j in range(4): + w = w16[:, j, i] + W = W + w + for k in range(9): + F[:, k] = w * feat[:, j, i, k] + F[:, k] + got = F.astype(np.float64) / np.maximum(W.astype(np.float64), 2.0**-24)[:, None] + err = np.abs(got - ref) + print("half gather: fbar max abs err %.3g, 99.9%% %.3g, rms %.3g (features in [0, 1])" % + (err.max(), np.quantile(err, 0.999), np.sqrt((err**2).mean()))) + self.assertLess(np.quantile(err, 0.999), 3e-3) + self.assertLess(np.sqrt((err**2).mean()), 5e-4) + + +class GeluForms(unittest.TestCase): + def test_gelu_chain_and_tanh(self): + x = np.linspace(-10, 10, 400001, dtype=np.float64) + erf = np.vectorize(math.erf) + ref = 0.5 * x * (1 + erf(x / math.sqrt(2))) + # the M-form kernels' chain (gelu_group): x / (1 + 2^(x (b x^2 + a))) + a, b = f32(-2.30816186), f32(-0.10029031) + xf = x.astype(f32) + chain = xf / (f32(1.0) + np.exp2(xf * (xf * xf * b + a))) + # plain tanh GELU as x sigmoid(2 sqrt(2/pi) (x + 0.044715 x^3)) in exp2 form + t = xf * (f32(1.0) + f32(0.044715) * xf * xf) + tanh = xf / (f32(1.0) + np.exp2(f32(-2 * math.sqrt(2 / math.pi) / math.log(2)) * t)) + ec, et = np.abs(chain - ref).max(), np.abs(tanh - ref).max() + print("GELU max abs err over [-10, 10]: M-form chain %.3g, tanh form %.3g" % (ec, et)) + self.assertLess(ec, 1e-3) + self.assertLess(et, 1.1e-3) + # the constant of the exp2 form: 2 sqrt(2 / pi) / ln 2 = 2.3022082 (not 2.3022227) + self.assertAlmostEqual(2 * math.sqrt(2 / math.pi) / math.log(2), 2.3022082, places=6) + + +class ProjectAccumulation(unittest.TestCase): + def test_fp32_accumulation_vs_stepwise_fp16(self): + rng = np.random.default_rng(6) + n, k = 4000, 64 + x = rng.uniform(-3, 3, (n, k)).astype(f32) + w = rng.uniform(-0.3, 0.3, (n, k)).astype(f32) + bias = rng.uniform(-1, 1, n).astype(f32) + exact = bias.astype(np.float64) + (x.astype(np.float64) * w).sum(1) + acc32 = bias.copy() + acc16 = bias.copy() + for g in range(k // 32): + blk = (x[:, 32 * g:32 * g + 32] * w[:, 32 * g:32 * g + 32]).sum(1, dtype=f32) + acc32 = acc32 + blk + acc16 = (acc16 + blk).astype(f16).astype(f32) + e32, e16 = np.abs(acc32 - exact).max(), np.abs(acc16 - exact).max() + print("projection accumulation: FP32 max err %.3g, stepwise FP16 %.3g" % (e32, e16)) + self.assertLess(e32, e16) + + +if __name__ == "__main__": + unittest.main() diff --git a/clean/runtime/runtime.cpp b/clean/runtime/runtime.cpp index 252c871b..b8568e85 100644 --- a/clean/runtime/runtime.cpp +++ b/clean/runtime/runtime.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -324,6 +325,29 @@ struct Runtime { // hybrid form is the bit-exact one); the history, the reset and the temporal logic are the same code. std::string l_mode_opt; bool l_fast_d3d12 = false; + // The levers of l_mode=fast (the kernels of the build named "_fast", native D3D12; every one is launched in place of + // its base kernel with the same arguments, l_fast_alt: base name -> fast name). One bit per group of kernels, all on by + // default; a developer build reads the selection from WG_L_FAST_MASK (an A/B of each lever, below). + // 1 l_post_tf_p12[_pf] the true-fusion output kernel without the bit-exactness guards (l_post_tf_fast.hlsl) + // 2 l_project_gather, l_dec_project the K blocks accumulated in FP32 and rounded once, in the FP8 pack + // 4 the width-32 Swin blocks (so far: the encoder block with the linears, its prologue in FP32) + // 8 the middle Swin blocks (c64, c96, the bottleneck: no twin yet; the build's "_fast" names decide) + // 16 the weaker history candidate as a 4-tap bilinear (inside the kernel of lever 1: pitch_bytes bit 0) + // 32 the q20 input encoder (no twin yet) + // 64 a weaker history candidate with the first one's motion (within 0.01 render pixel) is not read twice (lever 1: bit 1) + // 128 a weaker history candidate of weight below 0.05 (the hybrid route: 1 / 255) is dropped (lever 1: bit 2; off by default: + // a quality / speed trade-off for the A/B) + static constexpr unsigned kLFastAll = 255u, kLFastDefault = 127u; + unsigned l_fast_mask = kLFastDefault; + std::map l_fast_alt; + static unsigned l_fast_bit(const std::string& n) { + if (n.compare(0, 22, "w64_lc12/l_post_tf_p12") == 0) return 1u; + if (n == "l_project_gather" || n == "l_dec_project") return 2u; + if (n.compare(0, 17, "l_swin_block_c32_") == 0) return 4u; + if (n.compare(0, 11, "swin_block_") == 0 || n.compare(0, 16, "bneck/swin_bneck") == 0) return 8u; + if (n.compare(0, 20, "lev/input_encoder_q2") == 0) return 32u; + return 0u; + } // WG_L_FORM=hybrid on native D3D12 (hyb-fast, 0.6.5 L release form): Model L's M-form route (l_q7 off) with every // block stage packed from the hybrid values (clean/l/runtime/l_hyb_pack.h, the same blob names and layout) and every // Swin kernel launched as its hybrid twin from the kernel manifest (hyb-fast's names: the M-form route's name with @@ -705,6 +729,10 @@ struct Runtime { return fail(from + " must be hybrid or fast (got \"" + lm + "\")"); l_mode_opt = lm.empty() ? "hybrid" : lm; } +#ifdef WG_DEV_DIAGNOSTICS + if (const char* fm = std::getenv("WG_L_FAST_MASK")) // the A/B of each fast lever (bits: see l_fast_mask) + if (*fm) l_fast_mask = (unsigned)std::strtoul(fm, nullptr, 0) & kLFastAll; +#endif const bool lfast = l_mode_opt == "fast"; if (lfast && c.backend != 3) return fail("l_mode=fast runs on native D3D12 (backend 3) only (l_mode=hybrid is the default on every backend)"); @@ -1083,14 +1111,25 @@ struct Runtime { #ifdef WG_MODEL_L if (model_l && c.backend == 3) { // The pipeline states the native D3D12 device's warm_up compiles (every kernel of the build, selected or not): the - // hybrid default leaves out the two fast-only decoder blocks (and is otherwise as it was); l_mode=fast leaves out - // what it never launches: the hybrid twins, the FP16-form q7 blocks and the no-skip decoder blocks + // hybrid default leaves out the fast-only kernels (the skip-form decoder blocks and every "_fast" one) and is otherwise as + // it was; l_mode=fast leaves out what it never launches: the hybrid twins, the FP16-form q7 blocks, the no-skip + // decoder blocks, the base kernels that a fast one replaces (l_fast_alt) and the fast ones whose lever is off std::vector skip; - for (const std::string& h : manifest_kernels()) { + const std::vector mk = manifest_kernels(); + const std::set in_build(mk.begin(), mk.end()); + if (l_fast_d3d12) + for (const std::string& h : mk) { + const bool fast = h.size() > 5 && h.compare(h.size() - 5, 5, "_fast") == 0; + const std::string base = fast ? h.substr(0, h.size() - 5) : h; + if (fast && in_build.count(base) && (l_fast_mask & l_fast_bit(base))) l_fast_alt[base] = h; + } + for (const std::string& h : mk) { const bool twin = h.size() > 4 && h.compare(h.size() - 4, 4, "_hyb") == 0; + const bool fast = h.size() > 5 && h.compare(h.size() - 5, 5, "_fast") == 0; if (l_fast_d3d12 ? (twin || h.compare(0, 5, "l_q7_") == 0 || h == "l_swin_block_c32_dec_nc" || - h == "l_swin_block_c32_dec_coef12_nc") - : (h == "l_swin_block_c32_dec_add_nc" || h == "l_swin_block_c32_dec_coef12_add_nc")) + h == "l_swin_block_c32_dec_coef12_nc" || l_fast_alt.count(h) != 0 || + (fast && !l_fast_alt.count(h.substr(0, h.size() - 5)) ) ) + : (fast || h == "l_swin_block_c32_dec_add_nc" || h == "l_swin_block_c32_dec_coef12_add_nc")) skip.push_back(h); } dev->warm_up_skip(skip); @@ -2032,8 +2071,12 @@ struct Runtime { kernels_text += " l_hyb_d3d12=on hyb_twins=" + std::to_string(hyb_map.size() / 2) + " l_dec_skip=l_x3" + // the arena tables (native D3D12; "off" on the HIP twins' route, whose device has none) std::string(" hyb_tables=") + (dev->hyb_tables() ? "on" : "off"); - if (l_fast_d3d12) // l_mode=fast: the decoder block's skip S = the encoder block's map l_x3, in the M-form arithmetic - kernels_text += " l_dec_skip=l_x3"; + if (l_fast_d3d12) { // l_mode=fast: the decoder block's skip S = the encoder block's map l_x3, in the M-form arithmetic + kernels_text += " l_dec_skip=l_x3 l_fast_kernels=" + std::to_string(l_fast_alt.size()); +#ifdef WG_DEV_DIAGNOSTICS + kernels_text += " l_fast_mask=" + std::to_string(l_fast_mask); +#endif + } if (m_hyb_d3d12) // Model M on the hybrid twins: dec1's map stored, dec0 = d1p12/dec0_q7 kernels_text += " m_form=hybrid m_hyb_d3d12=on hyb_twins=" + std::to_string(hyb_map.size() / 2) + std::string(" hyb_tables=") + (dev->hyb_tables() ? "on" : "off"); @@ -2168,6 +2211,14 @@ struct Runtime { if (n == k) dev->unordered_next(); for (const auto& m : ((ab_block && ksub_b) ? ksub_ab : ksub_list)) if (m.first == k) k = m.second.c_str(); + std::string fast_k; + if (!l_fast_alt.empty()) { // l_mode=fast: the lever's kernel in place of the base one + const auto it = l_fast_alt.find(k); + if (it != l_fast_alt.end()) { + fast_k = it->second; + k = fast_k.c_str(); + } + } std::string hyb_k; if (hyb_d3d12()) { const std::string kk = k; @@ -3306,6 +3357,7 @@ struct Runtime { float dec_scale = (float)(0.01 / (fr.exposure == 0.0f ? 1.0 : (double)fr.exposure)), p_h = pi; if (l_fold_pidiv) std::memcpy(&p.pad0, &pi, 4); // the pre-exposure's bits: the _pf kernel divides every colour read post_last = l_fold_pidiv ? "w64_lc12/l_post_tf_p12_pf" : "w64_lc12/l_post_tf_p12"; + if (l_fast_alt.count(post_last)) hpitch = ((l_fast_mask & 16u) ? 1 : 0) | ((l_fast_mask & 64u) ? 2 : 0) | ((l_fast_mask & 128u) ? 4 : 0); // the fast kernel's pitch_bytes is its option word filter_last = "fused"; if (!launch(post_last.c_str(), cdiv(ow, 40) * nch, 512, {&cnet, &A, &B, &C, &hist[cur], &mnear[nxt], &mcenter, &mfar, &w, &hist[nxt], &reduced, &outp, &p, &expo, diff --git a/clean/tests/check_no_dev_diagnostics.py b/clean/tests/check_no_dev_diagnostics.py index 30b01605..b66dea99 100644 --- a/clean/tests/check_no_dev_diagnostics.py +++ b/clean/tests/check_no_dev_diagnostics.py @@ -45,6 +45,8 @@ b"/l_q7__hybmut.co", b"/l_q7w__hybmut.co", b"(WG_L_FORM=hybrid_twin: l_swin_hyb.co, swin_hyb.co)", b"WG_DEV_BNECK_ABORT", + # the A/B mask of Model L's l_mode=fast levers (runtime.cpp l_fast_mask, behind WG_DEV_DIAGNOSTICS) + b"WG_L_FAST_MASK", # the check routes' selector values (WG_L_FORM / WG_M_FORM): a release build does not know their names b"hybrid_mutant", b"hybrid_twin", b"__hybmut", ) diff --git a/clean/tests/runtime_frame_trace.cpp b/clean/tests/runtime_frame_trace.cpp index 63cb6a47..0fccfcf0 100644 --- a/clean/tests/runtime_frame_trace.cpp +++ b/clean/tests/runtime_frame_trace.cpp @@ -126,7 +126,9 @@ const Signature kSignatures[] = { const char* kinds_of(const std::string& kernel) { const size_t slash = kernel.find('/'); - const std::string k = slash == std::string::npos ? kernel : kernel.substr(slash + 1); + std::string k = slash == std::string::npos ? kernel : kernel.substr(slash + 1); + // a fast twin (l_mode=fast: "_fast", launched in place of its base kernel) has the base kernel's arguments + if (k.size() > 5 && k.compare(k.size() - 5, 5, "_fast") == 0) k.resize(k.size() - 5); // dec1's block fused with the decoder (swin_block_c64_add_dec0*): x, skip, w, H, W, ox, oy, then the decoder's // arguments: not the blocks' common form if (k.find("_add_dec0") != std::string::npos) return "pppiiii"; diff --git a/clean/tests/test_dev_diagnostics_off.py b/clean/tests/test_dev_diagnostics_off.py index 2e34f07f..00cb74cd 100644 --- a/clean/tests/test_dev_diagnostics_off.py +++ b/clean/tests/test_dev_diagnostics_off.py @@ -334,7 +334,7 @@ def test_each_selector_text_is_refused_alone(self): """Every check route's selector value is refused on its own in a library that says dev-diagnostics=0 (review: one negative test per selector).""" for t in (b"hybrid_mutant", b"hybrid_twin", b"__hybmut", b"WG_DEV_BNECK_ABORT", b"/l_q7__hybmut.co", - b"/l_q7w__hybmut.co"): + b"/l_q7w__hybmut.co", b"WG_L_FAST_MASK"): with self.subTest(t=t): self.assertIn(t, chk.DEV_ONLY_STRINGS) ok, text = chk.check_bytes(b"MZ" + MARK0 + b" ... " + t + b" ...") From 8d0e32f501bff7932ef606d398276dcda64ec243 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:38:08 -0500 Subject: [PATCH 3/5] Model L (D3D12): l_mode=fast levers 256 / 512 / 1024 / 4096 / 8: the centred 3 x 3 post gather, two windows per wave in the width-32 blocks, quick GELU, c64 twins New fast-mode kernels, each launched in place of a base kernel with the same arguments (runtime kLFastAlts / the "_fast" twins; every existing DXIL is byte-identical, swin_block.hlsl is not touched, l_mode=hybrid launches none of them): - w64_lc12/l_post_tf_p12[_pf]_fast3 (l_post_tf_fast.hlsl LP_WIN3, lever 256 with lever 1): the gather over the 3 x 3 render texels centred on each D pixel (every tap within 1.5 render pixels; each row of a pair with its own centred rows, the row n0 + 2 read under a wave-uniform branch) instead of the 4 x 4 window: 18 taps per row pair instead of 32. Staging cap 448 texels (LDS 23040 -> 21504 bytes); a frame whose step footprint does not fit (l_tf3_supported) runs the 4 x 4 twin. - l_swin_block_c32_enc_lin_w2[t]_fast (lever 512) and l_swin_block_c32_dec_coef12_add_w2[t]_fast (lever 1024), new l_swin_c32_fast.hlsl: two windows per wave in 128-lane workgroups (swin_c64w2.hlsl's launch shape: weight fragments, biases, norm vectors and the linears' weights loaded once for both windows, a barrier waits for 4 waves); the softmax without the maximum (the soft cap bounds the exponents to +-11); the decoder's coefficient store one pixel per lane in FP32 (the hh = 1 lanes take the second window's channels by v_permlanex16; no FP16 rounding of y2, tanh as 1 - 2 / (2^(2 t log2 e) + 1)). GELU: quick GELU x / (1 + 2^(-2.53 x)) in "_w2_fast" (lever 4096; no table load; max error 0.016, RMS 0.009 against the model's GELU), the arena table (the model's GELU bytes) in "_w2t_fast". - swin_block_c64_nc_fast / swin_block_c64_add_ex_nc_fast (lever 8, new l_swin_c64_fast.hlsl): the same body at C = 64. RGA (gfx1201), issue slots per window (without s_delay_alu / s_code_end), VGPRs, no spills: decoder block 1568 -> 978 (w2t 1044), 149 / 172 VGPRs; encoder block 1368 (enc_lin_nc_fast) -> 1090 (w2t 1147), 139 / 164 VGPRs; c64 1780 -> 1644, c64_add_ex 2118 -> 1995 (192 VGPRs, the base kernels' tier); the post 2683 -> 2520 static (96 VGPRs, 2 workgroups per CU as before). Quick GELU trades table loads for the exponential unit: w2 320 trans / 49 buffer loads per wave, w2t 64 / 177. runtime: WG_L_FAST_MASK default 127 -> 6015 (every lever but 128 and 2048, the latter reserved for a bottleneck twin); warm-up leaves out the fast kernels the mask does not select (the 3 x 3 post's 4 x 4 twin stays warm); build_dx12.py fast_base names the kernel each fast-mode kernel replaces (is_model_l, the trace's argument kinds). Tests: quick GELU, the softmax without the maximum, the fast coefficient store and the 3 x 3 gather by kernel width (test_l_fast_numerics.py: 3 x 3 vs 4 x 4 52.9 dB on texel noise at sigma 0.5 render pixel, 30.6 dB at sigma 1: lever 256 is the first one to A/B on the GPU), the selection, the warm-up and the footprint fallback (test_l_runtime_fast_mode.py), kernel_sets.json. --- clean/dx12/README.md | 3 + clean/dx12/build_dx12.py | 23 +- clean/dx12/kernel_sets.json | 32 ++ clean/dx12/kernels/l_post_tf_fast.hlsl | 89 ++++ clean/dx12/kernels/l_swin_c32_fast.hlsl | 406 ++++++++++++++++++ clean/dx12/kernels/l_swin_c64_fast.hlsl | 11 + clean/dx12/tests/test_kernel_sets.py | 19 +- clean/dx12/vgpr_limits.json | 12 +- clean/l/SPEED.md | 21 +- .../runtime/tests/test_l_runtime_fast_mode.py | 137 ++++-- clean/l/tests/test_l_fast_numerics.py | 206 ++++++++- clean/runtime/runtime.cpp | 90 +++- clean/tests/runtime_frame_trace.cpp | 12 +- 13 files changed, 990 insertions(+), 71 deletions(-) create mode 100644 clean/dx12/kernels/l_swin_c32_fast.hlsl create mode 100644 clean/dx12/kernels/l_swin_c64_fast.hlsl diff --git a/clean/dx12/README.md b/clean/dx12/README.md index c8edbbb9..d367fc94 100644 --- a/clean/dx12/README.md +++ b/clean/dx12/README.md @@ -132,6 +132,9 @@ WG_KERNEL(exposure_auto_diet) { WG_SETUP(); ... } // entry name = HIP kernel n 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 `_w2_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 4fe81b64..4e873666 100644 --- a/clean/dx12/build_dx12.py +++ b/clean/dx12/build_dx12.py @@ -33,7 +33,7 @@ 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, and Model L's fused post -w64_lc12/l_post_tf_p12[_pf][_fast]) is run through RGA (gfx1201) and its +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 @@ -227,13 +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 ; "_w2_fast" / "_w2t_fast" (the + two-windows-per-wave Swin blocks, l_swin_c32_fast.hlsl) replace "_nc".""" + m = re.fullmatch(r"(.+)_w2t?_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), a kernel - of the hybrid form (named *_hyb: WG_L_FORM = hybrid, Model L's route only so far), or a fast-mode twin (named *_fast: - Model L's l_mode=fast, launched in place of the kernel it is named after).""" + 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("_fast")) + or decl["name"].endswith("_hyb") or fast_base(decl["name"]) is not None) def is_frame_gen(decl): @@ -332,8 +343,8 @@ def rga_isa(dxil, isa_dir, stem): def vgpr_checked(name): - # l_swin_*: Model L's blocks (#89); l_post_tf_p12[_pf][_fast]: Model L's fused post (bound = 96-register tier) - return re.search(r"(^|/|l_)swin_|/l_post_tf_p12(_pf)?(_fast)?$", name) is not None + # 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): diff --git a/clean/dx12/kernel_sets.json b/clean/dx12/kernel_sets.json index fc875235..c41ec31d 100644 --- a/clean/dx12/kernel_sets.json +++ b/clean/dx12/kernel_sets.json @@ -346,6 +346,14 @@ "l_swin_block_c32_dec_coef12_add_nc", "-" ], + [ + "l_swin_block_c32_dec_coef12_add_w2_fast", + "-" + ], + [ + "l_swin_block_c32_dec_coef12_add_w2t_fast", + "-" + ], [ "l_swin_block_c32_dec_coef12_hyb", "-" @@ -378,6 +386,14 @@ "l_swin_block_c32_enc_lin_nc_fast", "-" ], + [ + "l_swin_block_c32_enc_lin_w2_fast", + "-" + ], + [ + "l_swin_block_c32_enc_lin_w2t_fast", + "-" + ], [ "l_swin_block_c32_enc_nc", "l_swin.co" @@ -458,6 +474,10 @@ "swin_block_c64_add_ex_nc", "swin.co" ], + [ + "swin_block_c64_add_ex_nc_fast", + "-" + ], [ "swin_block_c64_add_hyb", "-" @@ -470,6 +490,10 @@ "swin_block_c64_hyb", "-" ], + [ + "swin_block_c64_nc_fast", + "-" + ], [ "swin_block_c64_q7c_hyb", "-" @@ -522,9 +546,17 @@ "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": [ diff --git a/clean/dx12/kernels/l_post_tf_fast.hlsl b/clean/dx12/kernels/l_post_tf_fast.hlsl index 24a5ae2a..953d3417 100644 --- a/clean/dx12/kernels/l_post_tf_fast.hlsl +++ b/clean/dx12/kernels/l_post_tf_fast.hlsl @@ -24,10 +24,24 @@ // 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 @@ -42,9 +56,17 @@ WG_ARGS_BEGIN 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 @@ -140,8 +162,14 @@ 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 ---------------------------------------------- @@ -182,6 +210,38 @@ void gather_col(int i, half dx, int tb0, int rstride, half v0[kLWin], half v1[kL } } +#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) { @@ -433,8 +493,13 @@ WG_KERNEL(l_post_tf_p12_fast) 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)); @@ -456,7 +521,11 @@ WG_KERNEL(l_post_tf_p12_fast) 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; @@ -479,6 +548,25 @@ WG_KERNEL(l_post_tf_p12_fast) 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 @@ -498,6 +586,7 @@ WG_KERNEL(l_post_tf_p12_fast) 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, v0, v1, vv0, vv1, g0, g1); +#endif float r[3] = {0.0f, 0.0f, 0.0f}; [loop] for (int row = 0; row < 2; ++row) { 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..6b272185 --- /dev/null +++ b/clean/dx12/kernels/l_swin_c32_fast.hlsl @@ -0,0 +1,406 @@ +// 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 = x sigma(k x) = x / (1 + 2^(-2.53 x)) ("quick GELU" with its constant fitted to the model's GELU, +// k = 1.7537: three VALU operations, an exponential and a reciprocal per value, no table load; |error| <= 0.016, +// RMS 0.009 for N(0, 1.5) inputs against the model's GELU, test_l_fast_numerics.py); +// 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 quick GELU). +// (the "_w2t_fast" kernels are the "_w2_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_w2_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=8,SW_SRC=3,WG_LD_A16=1,WG_REV_ORDER=1,LF_NAME=l_swin_block_c32_enc_lin_w2_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=8,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_w2_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=8,SW_SRC=2,SW_OUT_F16=1,SW_OUT_COEF12=1,WG_LD_A16=1,LF_NAME=l_swin_block_c32_dec_coef12_add_w2_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=8,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 || 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 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 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 +#define NWW 2 // windows per wave + +// ---- GELU: q8 of one 16-row tile (8 values per lane) ---------------------------------------------------------------- +static const float kLfQg = asfloat(0xc021eb85u); // -2.53 = -1.7537 log2(e): the fitted constant (test_l_fast_numerics.py) +#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 + float t[8]; + [unroll] for (uint i = 0; i < 8; ++i) t[i] = h.v[i] * kLfQg; + [unroll] for (uint i1 = 0; i1 < 8; ++i1) t[i1] = wg_exp2(t[i1]); + [unroll] for (uint i2 = 0; i2 < 8; ++i2) t[i2] = 1.0f + t[i2]; + [unroll] for (uint i3 = 0; i3 < 8; ++i3) t[i3] = wg_rcp(t[i3]); + [unroll] for (uint i4 = 0; i4 < 8; ++i4) y.v[i4] = h.v[i4] * t[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 SW_SRC == 3 +// 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 SW_SRC == 3 + 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 SW_SRC == 3 + lf_halo_lin(x, pr, pc, hh, lb1, lf1, lb2, lf2, acc[i]); +#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 SW_SRC != 3 + [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); + [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); + acc[i1][k] = sw_add8(acc[i1][k], b); + } + } + } + + // 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 + [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]); + 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) { + 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; + } + 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) { + 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..6f02edb6 --- /dev/null +++ b/clean/dx12/kernels/l_swin_c64_fast.hlsl @@ -0,0 +1,11 @@ +// 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: quick GELU (no table load) 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/tests/test_kernel_sets.py b/clean/dx12/tests/test_kernel_sets.py index d238bf9d..eb76a955 100644 --- a/clean/dx12/tests/test_kernel_sets.py +++ b/clean/dx12/tests/test_kernel_sets.py @@ -51,7 +51,7 @@ def test_model_l_adds_only_model_l_kernels(self): # Model L's kernels: its code objects, the l_* direct-route kernels, MODEL_L_ONLY, the hybrid twins (*_hyb) and the # fast-mode twins (*_fast): Model L's route only; build_dx12.py is_model_l) self.assertFalse([k for k in extra if not (k[1].startswith("l_") or k[0].startswith("l_") or k[0] in B.MODEL_L_ONLY - or k[0].endswith("_hyb") or k[0].endswith("_fast"))]) + or k[0].endswith("_hyb") or B.fast_base(k[0]) is not None)]) def test_model_k_adds_only_model_k_kernels(self): @@ -92,26 +92,31 @@ def test_frame_gen_kernels_are_in_no_set(self): def test_fast_twins_take_their_base_kernels_arguments(self): - """A "_fast" twin (Model L's l_mode=fast) is launched by the runtime in place of its base kernel with the same - grid, block and arguments: the declarations agree in block, wave, args and (for a twin of a kernel with a launch - shape of its own) group; the twin has no HIP code object, and is in Model L's set only.""" + """A fast-mode kernel (Model L's l_mode=fast: "_fast", "_fast3", "_w2[t]_fast" in place of + "_nc", build_dx12.py fast_base) is launched by the runtime in place of its base kernel with the same grid, block + and arguments: the declarations agree in block, wave and args, and in group unless the fast kernel is a + two-windows-per-wave one (its own 128-lane workgroup per launched workgroup, gscale 1: the device's launch of the + same grid); the fast kernel has no HIP code object, and is in Model L's set only.""" decls = {} for fn in sorted(os.listdir(B.KERNEL_DIR)): if fn.endswith(".hlsl"): for d in B.kernel_decls(os.path.join(B.KERNEL_DIR, fn)): decls.setdefault(d["name"], []).append(d) - twins = [n for n in decls if n.endswith("_fast")] + twins = [n for n in decls if B.fast_base(n) is not None] self.assertTrue(twins) + self.assertTrue([n for n in twins if n.endswith("_w2_fast")]) + self.assertTrue([n for n in twins if n.endswith("_fast3")]) full, m = set(B.kernel_set(True)), set(B.kernel_set(False)) for n in twins: - base = n[:-5] + base = B.fast_base(n) self.assertIn(base, decls, n) (t,) = decls[n] self.assertEqual(t["co"], "-", n) self.assertTrue(B.is_model_l(t), n) self.assertIn((n, "-"), full - m, n) + w2 = t.get("group") == 128 and t.get("gscale") == 1 and t["block"] == 256 for b in decls[base]: - for key in ("block", "wave", "args", "group", "gscale"): + for key in ("block", "wave", "args") + (() if w2 else ("group", "gscale")): self.assertEqual(t.get(key), b.get(key), (n, key)) diff --git a/clean/dx12/vgpr_limits.json b/clean/dx12/vgpr_limits.json index 665115ec..654e72d4 100644 --- a/clean/dx12/vgpr_limits.json +++ b/clean/dx12/vgpr_limits.json @@ -1,5 +1,5 @@ { - "_doc": "build_dx12.py VGPR check: the RGA (gfx1201) USED_VGPRs bound of every Swin / bottleneck kernel (a name with a swin_ part) and Model L's fused post (w64_lc12/l_post_tf_p12[_pf]). Each bound is the largest count that keeps the kernel's present occupancy: VGPR file 1536 per SIMD lane, granule 8, a 256-lane wave32 workgroup = 4 waves on each of a CU's 2 SIMDs, so 2 workgroups per CU need <= 192, 3 need <= 128 (a 128-lane workgroup = 2 waves per SIMD: 4 per CU need <= 192). A kernel over its bound fails the build (a merge or an edit lost a workgroup per CU: swin_block_c96_add_xe_* at 215 VGPRs ran 1 per CU, +38 us per frame at 1440p Q). Model L's fused post (block = 512 lanes, wave64, 26,752 bytes of LDS: 2 workgroups per CU = 8 waves64 per SIMD) is bounded at 96; its fast-mode twins (w64_lc12/l_post_tf_p12[_pf]_fast, 23,040 bytes) keep that tier, and the fast-mode Swin twin of the encoder block the bound of its base. A new Swin / bottleneck kernel needs an entry. WG_DX12_VGPR_CHECK=0 skips the check.", + "_doc": "build_dx12.py VGPR check: the RGA (gfx1201) USED_VGPRs bound of every Swin / bottleneck kernel (a name with a swin_ part) and Model L's fused post (w64_lc12/l_post_tf_p12[_pf]). Each bound is the largest count that keeps the kernel's present occupancy: VGPR file 1536 per SIMD lane, granule 8, a 256-lane wave32 workgroup = 4 waves on each of a CU's 2 SIMDs, so 2 workgroups per CU need <= 192, 3 need <= 128 (a 128-lane workgroup = 2 waves per SIMD: 4 per CU need <= 192). A kernel over its bound fails the build (a merge or an edit lost a workgroup per CU: swin_block_c96_add_xe_* at 215 VGPRs ran 1 per CU, +38 us per frame at 1440p Q). Model L's fused post (block = 512 lanes, wave64, 26,752 bytes of LDS: 2 workgroups per CU = 8 waves64 per SIMD) is bounded at 96; its fast-mode twins (w64_lc12/l_post_tf_p12[_pf]_fast, 23,040 bytes; _fast3, 21,504 bytes) keep that tier, and the fast-mode Swin twin of the encoder block the bound of its base; the two-windows-per-wave fast kernels (l_swin_c32_fast.hlsl, l_swin_c64_fast.hlsl: 128-lane workgroups with 16 KB of staging, 4 per CU) <= 192. A new Swin / bottleneck kernel needs an entry. WG_DX12_VGPR_CHECK=0 skips the check.", "l_swin_block_c32_nc": 96, "l_swin_block_c32_enc_nc": 96, "l_swin_block_c32_enc_lin_nc": 96, @@ -37,8 +37,14 @@ "l_swin_block_c32_dec_add_nc": 96, "l_swin_block_c32_dec_coef12_add_nc": 96, "l_swin_block_c32_enc_lin_nc_fast": 96, + "l_swin_block_c32_enc_lin_w2_fast": 192, + "l_swin_block_c32_enc_lin_w2t_fast": 192, + "l_swin_block_c32_dec_coef12_add_w2_fast": 192, + "l_swin_block_c32_dec_coef12_add_w2t_fast": 192, "swin_block_c64_nc": 192, "swin_block_c64_add_ex_nc": 192, + "swin_block_c64_nc_fast": 192, + "swin_block_c64_add_ex_nc_fast": 192, "swin_block_c96_nc": 192, "swin_block_c96_add_ex_nc": 192, "swin_block_c96_pm_nc": 192, @@ -55,5 +61,7 @@ "w64_lc12/l_post_tf_p12": 96, "w64_lc12/l_post_tf_p12_pf": 96, "w64_lc12/l_post_tf_p12_fast": 96, - "w64_lc12/l_post_tf_p12_pf_fast": 96 + "w64_lc12/l_post_tf_p12_pf_fast": 96, + "w64_lc12/l_post_tf_p12_fast3": 96, + "w64_lc12/l_post_tf_p12_pf_fast3": 96 } diff --git a/clean/l/SPEED.md b/clean/l/SPEED.md index c3adb077..7172f7cc 100644 --- a/clean/l/SPEED.md +++ b/clean/l/SPEED.md @@ -90,9 +90,10 @@ reason where a kernel it needs is missing from the build (a build made with `--m build's `variants.json` and `swin__bmegahg.co`). No timing is published for it yet: a figure goes on this page only with its measurement record. -The levers of the preset (each a kernel of the build named `_fast`, launched in place of its base kernel with the -same arguments; the base kernels and everything `l_mode=hybrid` runs are untouched, and a build without a twin simply runs -the base kernel). They drop the bit-exactness of the hybrid route where it costs instructions and keeps the model's values: +The levers of the preset (each a kernel of the build launched in place of its base kernel with the same arguments: a +`_fast` twin, or one of the alternatives of runtime.cpp `kLFastAlts`, the first one in the build whose bits are all +set; the base kernels and everything `l_mode=hybrid` runs are untouched, and a build without a twin simply runs the base +kernel). They drop the bit-exactness of the hybrid route where it costs instructions and keeps the model's values: | lever | kernel | what it changes | |---|---|---| @@ -102,11 +103,19 @@ the base kernel). They drop the bit-exactness of the hybrid route where it costs | 16 | (option of lever 1) | the weaker history candidate (weight at most 1/2) is a 4-tap bilinear of the previous history instead of the 12-tap Catmull-Rom | | 64 | (option of lever 1) | a weaker history candidate whose motion is within 0.01 render pixel of the first one's is the same sample and is not read twice | | 128 | (option of lever 1, off by default) | a weaker history candidate of weight below 0.05 is dropped (the hybrid route drops it below 1 / 255) | +| 8 | `swin_block_c64_nc_fast`, `swin_block_c64_add_ex_nc_fast` | enc1's and dec1's blocks (`l_swin_c64_fast.hlsl`): the two-windows-per-wave body below at C = 64 with quick GELU (no table load) and the softmax without the maximum | +| 256 | `w64_lc12/l_post_tf_p12[_pf]_fast3` (with lever 1) | the gather over the 3 x 3 render texels centred on each D pixel (`LP_WIN3`; every tap within 1.5 render pixels, each row of a pair with its own centred rows) instead of the 4 x 4 window: 18 taps per row pair instead of 32; staging cap 448 texels, a frame whose step footprint does not fit (`l_tf3_supported`) runs the 4 x 4 twin | +| 512 | `l_swin_block_c32_enc_lin_w2[t]_fast` | the encoder block with the linears, two windows per wave in 128-lane workgroups (`l_swin_c32_fast.hlsl`, the launch shape of `swin_c64w2.hlsl`): weight fragments, biases and the linears' weights loaded once for both windows, a barrier waits for 4 waves; the softmax without the maximum (the soft cap bounds the exponents to +-11) | +| 1024 | `l_swin_block_c32_dec_coef12_add_w2[t]_fast` | the decoder block with the coefficient store, the same two-windows-per-wave body; the coefficient epilogue one pixel per lane (the hh = 1 lanes take the second window's channels by `v_permlanex16`) in FP32 from the block's FP32 output (no FP16 rounding of y2, tanh as `1 - 2 / (2^(2 t log2 e) + 1)`) | +| 4096 | (option of 512 / 1024) | quick GELU `x / (1 + 2^(-2.53 x))` in the two-windows kernels (`_w2_fast`: no table load; max error 0.016, RMS 0.009 against the model's GELU); off: their table form `_w2t_fast` (the model's GELU bytes by the arena table) | A developer build (`dev_diagnostics`) reads the selection of levers from `WG_L_FAST_MASK` (the sum of the lever values -above; the default is 127: every lever and option but 128) for an A/B of each; a release build has no such variable. The arithmetic choices are bounded -on the CPU by `clean/l/tests/test_l_fast_numerics.py` (the quality gate itself is measured on the GPU against -`l_mode=hybrid`: tone-mapped PSNR / SSIM and temporal stability). +above; the default is 6015 = every lever and option but 128 and 2048, the latter reserved for a bottleneck twin that does +not exist yet; the earlier default 127 is the set without 256, 512, 1024 and 4096) for an A/B of each; a release build has +no such variable. The arithmetic choices are bounded on the CPU by `clean/l/tests/test_l_fast_numerics.py` (the quality +gate itself is measured on the GPU against `l_mode=hybrid`: tone-mapped PSNR / SSIM and temporal stability). Lever 256 is +the one whose difference depends on the model's kernel widths (CPU bound: 52.9 dB on texel noise at sigma 0.5 render +pixel, 30.6 dB at sigma 1): it is the first one to check in that A/B. ## Building Model L diff --git a/clean/l/runtime/tests/test_l_runtime_fast_mode.py b/clean/l/runtime/tests/test_l_runtime_fast_mode.py index db9434e2..6aeabb73 100644 --- a/clean/l/runtime/tests/test_l_runtime_fast_mode.py +++ b/clean/l/runtime/tests/test_l_runtime_fast_mode.py @@ -53,19 +53,68 @@ SIZES = "--sizes=96x64,96x64,80x48,80x48,80x48,77x45" +def fast_base(n): + """The base kernel a fast-mode kernel is launched in place of (clean/dx12/build_dx12.py fast_base): "_fast", + "_fast3" -> ; "_w2_fast", "_w2t_fast" -> "_nc"; None for any other kernel.""" + m = re.fullmatch(r"(.+)_w2t?_fast", n) + if m: + return m.group(1) + "_nc" + m = re.fullmatch(r"(.+)_fast3?", n) + return m.group(1) if m else None + + +# runtime.cpp kLFastAlts (in order: the first one in the build whose bits are all set), then the "_fast" twins of +# their lever bit (l_fast_bit); kLFastDefault +ALTS = (("w64_lc12/l_post_tf_p12", "w64_lc12/l_post_tf_p12_fast3", 1 | 256), + ("w64_lc12/l_post_tf_p12_pf", "w64_lc12/l_post_tf_p12_pf_fast3", 1 | 256), + ("l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2_fast", 512 | 4096), + ("l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2t_fast", 512), + ("l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2_fast", 1024 | 4096), + ("l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2t_fast", 1024)) +DEFAULT_MASK = 8191 & ~128 & ~2048 + + +def lever_bit(base): + if base.startswith("w64_lc12/l_post_tf_p12"): + return 1 + if base in ("l_project_gather", "l_dec_project"): + return 2 + if base.startswith("l_swin_block_c32_"): + return 4 + if base.startswith("swin_block_") or base.startswith("bneck/swin_bneck"): + return 8 + return 32 if base.startswith("lev/input_encoder_q2") else 0 + + +def selection(mask=DEFAULT_MASK, ports=None): + """(base -> the kernel launched in its place, the fast kernels warmed up) of runtime.cpp's l_fast_alt for this mask.""" + have = {k for k, _ in (F.full_ports() if ports is None else ports)} + alt = {} + for b, a, bits in ALTS: + if b not in alt and b in have and a in have and (mask & bits) == bits and \ + (not a.endswith("_fast3") or b + "_fast" in have): + alt[b] = a + for k in sorted(have): + if k.endswith("_fast") and k[:-5] in have and k[:-5] not in alt and mask & lever_bit(k[:-5]): + alt[k[:-5]] = k + warm = set(alt.values()) | {b + "_fast" for b, a in alt.items() if a.endswith("_fast3")} + return alt, warm + + class FastTrace(FT.Trace): - """FT.Trace with the "_fast" twins folded back onto their base names (the lever kernels the fast route launches in place - of a base kernel, same arguments): every launch reads as the base kernel; frame["fast"] lists the twins launched.""" + """FT.Trace with the fast-mode kernels folded back onto their base names (fast_base: the lever kernels the fast route + launches in place of a base kernel, same arguments): every launch reads as the base kernel; frame["fast"] lists the + fast kernels launched.""" def __init__(self, lines): super().__init__(lines) for f in self.frames: - f["fast"] = [ln.kernel for ln in f["launches"] if ln.kernel.endswith("_fast")] + f["fast"] = [ln.kernel for ln in f["launches"] if fast_base(ln.kernel)] for ln in f["launches"]: - if ln.kernel.endswith("_fast"): - ln.kernel = ln.kernel[:-5] - if f["failed"] and f["failed"].endswith("_fast"): - f["failed"] = f["failed"][:-5] + if fast_base(ln.kernel): + ln.kernel = fast_base(ln.kernel) + if f["failed"] and fast_base(f["failed"]): + f["failed"] = fast_base(f["failed"]) def l_run(options="model=L", ports=None, frames=3, flags=(), backend=3, rw=F.RW, rh=F.RH, hdr=1, env=None, @@ -149,7 +198,7 @@ def test_warm_up_scope(self): hybrid (the default) the two fast-only decoder blocks and nothing else; fast the hybrid twins, the FP16-form q7 blocks and the no-skip decoder blocks, none of the kernels its own route launches. Model M: nothing.""" ports = [k for k, _ in F.full_ports()] - fast_twins = [k for k in ports if k.endswith("_fast")] + fast_twins = [k for k in ports if fast_base(k)] self.assertTrue(fast_twins) t = FastTrace(l_run("model=L", frames=1, rw=96, rh=64, variants=False, flags=("--warm-skip",))) self.assertEqual(sorted(t.warm_skip), sorted(FAST_ONLY + tuple(fast_twins))) @@ -159,17 +208,21 @@ def test_warm_up_scope(self): t = FastTrace(l_run("model=L,l_mode=fast", frames=1, rw=96, rh=64, flags=("--warm-skip",))) twins = [k for k in ports if k.endswith("_hyb")] self.assertTrue(twins) - replaced = {k[:-5] for k in fast_twins if k[:-5] in ports} # the base kernels a fast twin replaces + alt, warm = selection() + replaced = set(alt) # the base kernels a fast kernel replaces want = set(twins) | {k for k in ports if k.startswith("l_q7_")} | {"l_swin_block_c32_dec_nc", "l_swin_block_c32_dec_coef12_nc"} | replaced + want |= set(fast_twins) - warm # the alternatives not selected (lever 4's encoder twin, the table GELU forms) self.assertTrue(replaced) + self.assertIn("l_swin_block_c32_enc_lin_nc_fast", want) + self.assertNotIn("w64_lc12/l_post_tf_p12_fast", want) # the 3 x 3 post's 4 x 4 fallback stays warm self.assertEqual(sorted(t.warm_skip), sorted(want)) launched = {n for f in t.frames for n in names(f)} - replaced # (a twin is launched in place of its base kernel) self.assertEqual(launched & set(t.warm_skip), set()) self.assertEqual({k for f in t.frames for k in f["fast"]} & set(t.warm_skip), set()) # every kernel the route launches (a twin in place of its base) is warmed up: not a base that a twin replaces self.assertEqual(set(FAST_NEEDS) - replaced & set(t.warm_skip), set()) - self.assertEqual({k for k in fast_twins} & set(t.warm_skip), set()) + self.assertEqual(warm & set(t.warm_skip), set()) t = FastTrace(F.run("", frames=1, build_files=FT.SHIPPING, flags=("--backend=3", "--warm-skip"), manifest=F.full_ports())) self.assertEqual(t.warm_skip, []) @@ -347,7 +400,7 @@ def test_hybrid_twins_not_needed(self): def test_failed_launch_stops_the_frame(self): for kernel, before in ((FOLD_ADD, "l_dec_project"), ("lc12/l_post_recon_p12", FOLD_ADD)): with self.subTest(kernel=kernel): - fail = kernel + "_fast" if kernel + "_fast" in twins() else kernel # launched as its twin + fail = selection()[0].get(kernel, kernel) # launched as its fast kernel t = FastTrace(l_run("model=L,l_mode=fast", frames=3, flags=("--fail=%s@1" % fail,), tf_default=False)) ok0, bad, ok2 = t.frames self.assertEqual(bad["failed"], kernel) @@ -367,7 +420,7 @@ def test_ldr_and_fallback_post(self): def twins(): - return [k for k, _ in F.full_ports() if k.endswith("_fast")] + return [k for k, _ in F.full_ports() if fast_base(k)] def shape(t): @@ -397,8 +450,15 @@ def test_twins_declared(self): t = set(twins()) for k in self.LEVERS: self.assertIn(k + "_fast", t) + self.assertIn(k, selection()[0]) for k in t: - self.assertIn(k[:-5], [x for x, _ in F.full_ports()], k) # every twin replaces a base kernel of the build + self.assertIn(fast_base(k), [x for x, _ in F.full_ports()], k) # every fast kernel replaces a base kernel + # the default selection: the 3 x 3 post, the two-windows-per-wave width-32 blocks with quick GELU, the c64 twins + alt = selection()[0] + self.assertEqual(alt["w64_lc12/l_post_tf_p12"], "w64_lc12/l_post_tf_p12_fast3") + self.assertEqual(alt[ENC_LIN], "l_swin_block_c32_enc_lin_w2_fast") + self.assertEqual(alt[FOLD_ADD], "l_swin_block_c32_dec_coef12_add_w2_fast") + self.assertEqual(alt["swin_block_c64_nc"], "swin_block_c64_nc_fast") def test_launched_in_place_of_the_base_kernel(self): a = FastTrace(l_run("model=L,l_mode=fast", frames=3, tf_default=True)) @@ -406,19 +466,33 @@ def test_launched_in_place_of_the_base_kernel(self): b = FastTrace(l_run("model=L,l_mode=fast", ports=without(*twins()), frames=3, tf_default=True)) self.assertEqual(b.create, "create ok model L") self.assertEqual(shape(a), shape(b)) # the same launches with the same arguments, twins or not + alt = selection()[0] for f in a.frames: - for k in self.LEVERS: - self.assertIn(k + "_fast", f["fast"], f["fast"]) + for k in self.LEVERS + (FOLD_ADD, "swin_block_c64_nc", "swin_block_c64_add_ex_nc"): + self.assertIn(alt[k], f["fast"], f["fast"]) for f in b.frames: self.assertEqual(f["fast"], []) - self.assertEqual(a.kernels.get("l_fast_kernels"), str(len(twins()))) + self.assertEqual(a.kernels.get("l_fast_kernels"), str(len(alt))) self.assertEqual(b.kernels.get("l_fast_kernels"), "0") def test_pre_exposure_post_twin(self): t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, flags=("--pre-exposure=2.0",))) for f in t.frames: - self.assertIn("w64_lc12/l_post_tf_p12_pf_fast", f["fast"]) - self.assertNotIn("w64_lc12/l_post_tf_p12_fast", f["fast"]) + self.assertIn("w64_lc12/l_post_tf_p12_pf_fast3", f["fast"]) + self.assertNotIn("w64_lc12/l_post_tf_p12_fast3", f["fast"]) + + def test_post3_footprint_fallback(self): + """A frame whose step footprint the 3 x 3 post's staging (448 texels) does not take, but the 4 x 4 one's (512) does, + runs the 4 x 4 twin (render 96 x 48 for D 180 x 108: (33 + 5) 12 = 456 > 448, (33 + 6) 12 = 468 <= 512); the + same frames at 80 x 48 run the 3 x 3 kernel.""" + t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, rw=96, rh=48)) + self.assertEqual(t.create, "create ok model L") + for f in t.frames: + self.assertIn("w64_lc12/l_post_tf_p12_fast", f["fast"]) + self.assertNotIn("w64_lc12/l_post_tf_p12_fast3", f["fast"]) + t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, rw=80, rh=48)) + for f in t.frames: + self.assertIn("w64_lc12/l_post_tf_p12_fast3", f["fast"]) def test_every_lever_on_by_default(self): t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True)) @@ -447,10 +521,17 @@ def dev_exe(): class FastMask(unittest.TestCase): """The A/B of the fast levers: WG_L_FAST_MASK in a developer build (bit values: runtime.cpp l_fast_mask); a release - build has no such variable (it runs every lever whatever the environment says).""" + build has no such variable (it runs the default levers whatever the environment says).""" POST = {"w64_lc12/l_post_tf_p12_fast"} + POST3 = {"w64_lc12/l_post_tf_p12_fast3"} PROJECT = {"l_project_gather_fast", "l_dec_project_fast"} ENC = {"l_swin_block_c32_enc_lin_nc_fast"} + ENC_W2 = {"l_swin_block_c32_enc_lin_w2_fast"} + ENC_W2T = {"l_swin_block_c32_enc_lin_w2t_fast"} + DEC_W2 = {"l_swin_block_c32_dec_coef12_add_w2_fast"} + DEC_W2T = {"l_swin_block_c32_dec_coef12_add_w2t_fast"} + MID = {"swin_block_c64_nc_fast", "swin_block_c64_add_ex_nc_fast"} + DEFAULT = POST3 | PROJECT | ENC_W2 | DEC_W2 | MID def launched(self, mask, exe, **kw): t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, exe=exe, env={"WG_L_FAST_MASK": str(mask)}, @@ -462,21 +543,25 @@ def launched(self, mask, exe, **kw): def test_developer_mask(self): exe = dev_exe() - for mask, want in ((127, self.POST | self.PROJECT | self.ENC), (255, self.POST | self.PROJECT | self.ENC), (0, set()), (1, self.POST), (2, self.PROJECT), - (4, self.ENC), (1 | 4, self.POST | self.ENC), (16 | 64 | 128, set())): + for mask, want in ((DEFAULT_MASK, self.DEFAULT), (8191, self.DEFAULT), (127, self.POST | self.PROJECT | self.ENC | self.MID), + (0, set()), (1, self.POST), (1 | 256, self.POST3), (256, set()), (2, self.PROJECT), (4, self.ENC), + (4 | 512, self.ENC_W2T), (512 | 4096, self.ENC_W2), (1024, self.DEC_W2T), (1024 | 4096, self.DEC_W2), + (4096, set()), (8, self.MID), (16 | 64 | 128, set())): with self.subTest(mask=mask): got, t = self.launched(mask, exe) self.assertEqual(got, want) + # (the frames run the post without the pre-exposure: its _pf kernel is selected but not launched) + self.assertEqual(got, {v for b, v in selection(mask)[0].items() if b != "w64_lc12/l_post_tf_p12_pf"}) self.assertEqual(t.kernels.get("l_fast_mask"), str(mask)) - # a twin of a lever that is off is left out of the warm-up (and not launched) - skip = set(t.warm_skip) + # a fast kernel the mask does not select is left out of the warm-up (and not launched); the 3 x 3 post's + # 4 x 4 twin stays warm (the frames whose footprint the 3 x 3 kernel does not take) + skip, warm = set(t.warm_skip), selection(mask)[1] for twin in twins(): - bit = 1 if twin.startswith("w64_lc12/") else (2 if "project" in twin else 4) - self.assertEqual(twin in skip, not (mask & bit), twin) + self.assertEqual(twin in skip, twin not in warm, twin) def test_release_build_has_no_mask(self): got, t = self.launched(0, None) # the release trace program: the variable is not read - self.assertEqual(got, self.POST | self.PROJECT | self.ENC) + self.assertEqual(got, self.DEFAULT) self.assertNotIn("l_fast_mask", t.kernels) diff --git a/clean/l/tests/test_l_fast_numerics.py b/clean/l/tests/test_l_fast_numerics.py index 03f874c7..74770ac0 100644 --- a/clean/l/tests/test_l_fast_numerics.py +++ b/clean/l/tests/test_l_fast_numerics.py @@ -11,7 +11,12 @@ * the 16-bit horizontal Lanczos ring (two FP16 per dword) against the FP32 ring; * the FP16 tap weight (v_exp_f16) with the total weight summed in FP16 from the same weights, against the FP32 gather; * the MLP GELU forms (the arithmetic chain of the M-form kernels and the plain tanh form) against the erf GELU; - * the FP32 accumulation of the projections' K blocks against the stepwise FP16-rounded sum. + * the FP32 accumulation of the projections' K blocks against the stepwise FP16-rounded sum; + * the centred 3 x 3 gather of l_post_tf_p12[_pf]_fast3 (LP_WIN3) against the 4 x 4 window, by kernel width; + * the two-windows-per-wave Swin blocks (l_swin_c32_fast.hlsl): quick GELU x / (1 + 2^(-2.53 x)) against the model's GELU + (and its FP8 codes), the softmax without the maximum against the max-subtracted one, and the coefficient store in FP32 + (tanh as 1 - 2 / (2^(2 t log2 e) + 1), no RN16 points, the truncating FP16 pack with the kRn fold) against + l_coef_px.hlsli's arithmetic. Numbers are printed with -v; the bounds are the ones the fast route is gated on (tone-mapped PSNR >= 48 dB per choice). """ import math @@ -245,5 +250,204 @@ def test_fp32_accumulation_vs_stepwise_fp16(self): self.assertLess(e32, e16) + +def gelu_chain(x): + """The model's GELU as the M-form kernels compute it (and the arena tables hold): x / (1 + 2^(x (b x^2 + a))).""" + a, b = from_bits(0xc013b8ed), from_bits(0xbdcd6502) + x = np.asarray(x, dtype=f32) + with np.errstate(over="ignore"): + return x / (f32(1.0) + np.exp2(x * (x * x * b + a))) + + +def fp8_e4m3(x): + """Round to the nearest FP8 E4M3 value (v_cvt_pk_fp8_f32: nearest even; |x| <= 448 here).""" + x = np.asarray(x, dtype=np.float64) + _, e = np.frexp(np.abs(x)) # |x| = m 2^e, m in [0.5, 1) + e = np.maximum(e, -5) # below 2^-6: the subnormal step 2^-9 + step = np.ldexp(1.0, e - 4) # 3 mantissa bits + return np.sign(x) * np.round(np.abs(x) / step) * step + + +class QuickGelu(unittest.TestCase): + K = from_bits(0xc021eb85) # -2.53 (l_swin_c32_fast.hlsl kLfQg) + + def quick(self, x): + x = np.asarray(x, dtype=f32) + return x * (f32(1.0) / (f32(1.0) + np.exp2(x * self.K))) + + def test_error_bounds(self): + x = np.linspace(-12, 12, 2400001, dtype=f32) + err = np.abs(self.quick(x).astype(np.float64) - gelu_chain(x)) + rng = np.random.default_rng(11) + xs = rng.normal(0, 1.5, 2000000).astype(f32) + rms = np.sqrt(np.mean((self.quick(xs).astype(np.float64) - gelu_chain(xs)) ** 2)) + # the plain 1.702 constant for comparison: the fitted one has the smaller maximum and RMS + k0 = f32(-1.702 * math.log2(math.e)) + q0 = xs * (f32(1.0) / (f32(1.0) + np.exp2(xs * k0))) + rms0 = np.sqrt(np.mean((q0.astype(np.float64) - gelu_chain(xs)) ** 2)) + print("quick GELU (k = 2.53): max abs err %.4f, RMS %.4f on N(0, 1.5) (k = 1.702 log2 e: RMS %.4f)" % + (err.max(), rms, rms0)) + self.assertLess(err.max(), 0.016) + self.assertLess(rms, 0.0095) + self.assertLess(rms, rms0) + with np.errstate(over="ignore"): + ends = self.quick(np.array([-1e30, 1e30], dtype=f32)) + self.assertEqual(float(abs(ends[0])), 0.0) + self.assertEqual(float(ends[1]), float(f32(1e30))) + + def test_fp8_codes(self): + # the W2 input is the FP8 code of GELU(h): the share of codes that change, and the mean signed error + rng = np.random.default_rng(12) + h = rng.normal(0, 1.5, 1000000).astype(f32) + a, b = fp8_e4m3(gelu_chain(h)), fp8_e4m3(self.quick(h)) + same = np.mean(a == b) + bias = np.mean(b - a) + print("quick GELU FP8 codes: %.1f%% unchanged, 99%% of the changes within %.4f absolute, mean signed error %.2e " + "(mean |GELU| %.3f)" % (100 * same, np.quantile(np.abs(a - b)[a != b], 0.99), bias, np.mean(np.abs(a)))) + self.assertGreater(same, 0.55) + self.assertLess(abs(bias), 0.004) + + +class SoftmaxNoMax(unittest.TestCase): + def test_no_max_needed(self): + rng = np.random.default_rng(13) + n = 200000 + cap, k3, kt = from_bits(0x420179db), from_bits(0xb9a6cc38), from_bits(0x3f028297) + s = np.concatenate([rng.normal(0, 4, (n, 16)), rng.uniform(-80, 80, (n // 10, 16))]).astype(f32) + c = np.clip(s, -cap, cap) + t = (c * c * c * k3 + c).astype(f32) + # the M-form: z = t k - max(t) k; the fast form: z = t k (|z| <= 11: no overflow, no denormal) + z = (t * kt).astype(f32) + self.assertLess(np.abs(z).max(), 11.1) + e_fast = np.exp2(z) + p_fast = (e_fast * (f32(1.0) / e_fast.sum(1, dtype=f32, keepdims=True))).astype(f16) + e_ref = np.exp2((t * kt - (t.max(1, keepdims=True) * kt)).astype(f32)) + p_ref = (e_ref * (f32(1.0) / e_ref.sum(1, dtype=f32, keepdims=True))).astype(f16) + d = np.abs(p_fast.view(np.uint16).astype(np.int32) - p_ref.view(np.uint16).astype(np.int32)) + print("softmax without the max: FP16 weights equal %.3f%%, at most %d ulp apart" % (100 * np.mean(d == 0), d.max())) + self.assertLessEqual(d.max(), 2) + self.assertGreater(np.mean(d == 0), 0.97) + + +def gather(feat, kA, kB, kC, px, py, win3): + """The normalized gather of the D pixels at (px, py) (render pixels, texel centres at i + 1/2) over the 4 x 4 window + floor(p - 1/2) - 1 ... + 2 or the centred 3 x 3 window floor(p) - 1 ... + 1, float64. feat[y, x, k], shapes per texel.""" + if win3: + cx, cy, taps = np.floor(px).astype(int), np.floor(py).astype(int), range(-1, 2) + else: + cx, cy, taps = np.floor(px - 0.5).astype(int), np.floor(py - 0.5).astype(int), range(-1, 3) + num = np.zeros(px.shape + (feat.shape[2],)) + den = np.zeros(px.shape) + for j in taps: + for i in taps: + X, Y = cx + i, cy + j + u, v = X + 0.5 - px, Y + 0.5 - py + Xc, Yc = np.clip(X, 0, feat.shape[1] - 1), np.clip(Y, 0, feat.shape[0] - 1) + w = 2.0 ** (kA[Yc, Xc] * u * u + kB[Yc, Xc] * v * v + kC[Yc, Xc] * u * v) + num += w[..., None] * feat[Yc, Xc] + den += w + return num / den[..., None] + + +class CentredGather(unittest.TestCase): + def test_3x3_vs_4x4_by_width(self): + rng = np.random.default_rng(14) + H, W = 96, 96 + yy, xx = np.mgrid[0:H, 0:W] + smooth = np.stack([0.5 + 0.4 * np.sin(xx * 0.21 + k) * np.cos(yy * 0.17 + 2 * k) for k in range(3)], -1) + noise = rng.uniform(0, 1, (H, W, 3)) + r = 1707.0 / 3840.0 # render pixels per D pixel at 1440p Quality + dy, dx = np.mgrid[0:int((H - 8) / r), 0:int((W - 8) / r)] + px, py = (dx + 0.5) * r + 4.0, (dy + 0.5) * r + 4.0 + res = [] + for k0 in (4.0, 2.0, 1.0, 0.5): # w = exp(-k0 u^2 / 2): sigma = 1 / sqrt(k0) render pixels + kA = np.full((H, W), -0.721325 * k0) + kB = kA * rng.uniform(0.7, 1.3, (H, W)) + kC = -1.44265 * k0 * rng.uniform(-0.2, 0.2, (H, W)) + out = [] + for feat in (smooth, noise): + a = gather(feat, kA, kB, kC, px, py, False) + b = gather(feat, kA, kB, kC, px, py, True) + out.append(10 * math.log10(1.0 / max(np.mean((a - b) ** 2), 1e-20))) + res.append((k0, out[0], out[1])) + print("centred 3 x 3 vs 4 x 4 gather, sigma %.2f render px: PSNR %.1f dB (smooth field), %.1f dB (texel noise)" % + (1 / math.sqrt(k0), out[0], out[1])) + # narrow kernels (sigma 0.5 render px): the dropped ring carries little weight + self.assertGreater(res[0][1], 45.0) + self.assertGreater(res[0][2], 35.0) + # the difference grows with the kernel width: the A/B on the GPU decides (lever 256) + self.assertGreater(res[0][2], res[-1][2]) + + +def lcoef_exact(a, S, T): + """l_coef_px.hlsli's values (FP32 arithmetic, the RN16 points) of one pixel's 13 channels a (FP16 inputs).""" + a = [np.asarray(v, dtype=f16).astype(f32) for v in a] + sig = lambda x: (f32(1.0) / (f32(1.0) + np.exp2(x * from_bits(0xBFB8AA3B)))).astype(f32) + rn = lambda x: np.asarray(x, dtype=f32).astype(f16).astype(f32) + unorm = lambda v: np.round(v * f32(255.0)).astype(np.int64) + snorm = lambda v: np.round(np.clip(v, -1, 1) * f32(127.0)).astype(np.int64) + tanh = lambda x: np.tanh(x.astype(np.float64)).astype(f32) + A = [unorm(rn(sig(a[i]))) for i in range(3)] + m = np.maximum(np.maximum(a[3], a[4]), a[5]) + e = [np.exp2((a[i] - m) * from_bits(0x3FB8AA3B)) for i in (3, 4, 5)] + rs = f32(1.0) / (e[2] + (e[0] + e[1])) + B = [unorm(x * rs) for x in e] + g0, g1 = rn(sig(np.clip(a[6], -20, 20))), rn(sig(np.clip(a[7], -20, 20))) + sx, sy = S * g0, S * g1 + C = [(sx * sx).astype(f16), (sy * sy).astype(f16), ((sx * sy) * tanh(a[8] * T)).astype(f16)] + L = [snorm(tanh(a[i])) for i in (9, 10, 11, 12)] + return A, B, C, L + + +def lcoef_fast(a, S, T): + """l_swin_c32_fast.hlsl lf_coef_px: FP32 throughout from the block's FP32 output, the fast tanh, the truncating pack.""" + a = [np.asarray(v, dtype=f32) for v in a] + sig = lambda x: (f32(1.0) / (f32(1.0) + np.exp2(x * from_bits(0xBFB8AA3B)))).astype(f32) + tanh = lambda x: (f32(1.0) - f32(2.0) / (np.exp2(x * from_bits(0x4038AA3B)) + f32(1.0))).astype(f32) + unorm = lambda v: np.floor(v * f32(255.0) + f32(0.5)).astype(np.int64) + snorm = lambda v: np.round(v * f32(127.0)).astype(np.int64) + A = [unorm(sig(a[i])) for i in range(3)] + m = np.maximum(np.maximum(a[3], a[4]), a[5]) + e = [np.exp2((a[i] - m) * from_bits(0x3FB8AA3B)) for i in (3, 4, 5)] + rs = f32(1.0) / (e[2] + (e[0] + e[1])) + B = [unorm(x * rs) for x in e] + g0, g1 = sig(np.clip(a[6], -20, 20)), sig(np.clip(a[7], -20, 20)) + S2 = f32(S) * f32(S) * f32(1.00034) + sg0 = S2 * g0 + C = [rtz16(sg0 * g0), rtz16((S2 * g1) * g1), rtz16((sg0 * g1) * tanh(a[8] * T))] + L = [snorm(tanh(a[i])) for i in (9, 10, 11, 12)] + return A, B, C, L + + +class CoefFast(unittest.TestCase): + def test_fast_tanh(self): + t = np.linspace(-20, 20, 400001, dtype=f32) + with np.errstate(over="ignore"): + fast = f32(1.0) - f32(2.0) / (np.exp2(t * from_bits(0x4038AA3B)) + f32(1.0)) + err = np.abs(fast.astype(np.float64) - np.tanh(t.astype(np.float64))) + print("fast tanh: max abs err %.3g" % err.max()) + self.assertLess(err.max(), 3e-7) + self.assertTrue(np.all(np.abs(fast) <= 1.0)) + + def test_codes_and_products(self): + rng = np.random.default_rng(15) + n = 300000 + a = [rng.normal(0, 2.5, n).astype(f32) for _ in range(13)] + S, T = f32(1.7), f32(0.8) + with np.errstate(over="ignore"): + ex, fa = lcoef_exact(a, S, T), lcoef_fast(a, S, T) + worst = 0 + for grp in (0, 1, 3): # A, B, L: 8-bit codes + for x, y in zip(ex[grp], fa[grp]): + worst = max(worst, int(np.abs(x - y).max())) + # the FP16 products in units of their scale S^2 (the exact form rounds its inputs to FP16 first: near rho = 0 the + # relative difference of two tiny values says nothing) + rel = max(float(np.quantile(np.abs(x.astype(np.float64) - y.astype(np.float64)), 0.999)) for x, y in zip(ex[2], fa[2])) + rel /= float(S) * float(S) + print("fast coefficient store: 8-bit codes within %d LSB, FP16 products 99.9%% within %.2e of S^2" % (worst, rel)) + self.assertLessEqual(worst, 1) + self.assertLess(rel, 2.0 ** -9) + + if __name__ == "__main__": unittest.main() diff --git a/clean/runtime/runtime.cpp b/clean/runtime/runtime.cpp index b8568e85..1da4fadc 100644 --- a/clean/runtime/runtime.cpp +++ b/clean/runtime/runtime.cpp @@ -176,6 +176,14 @@ bool l_tf_supported(int rw, int rh, int dw, int dh) { return recon2_supported(rw, rh, dw, dh) && ((long long)(63.0 * rw / dw) + 6) * ((long long)(14.0 * rh / dh) + 6) <= kLTfCap; } +// l_mode=fast's centred 3 x 3 gather (l_post_tf_p12[_pf]_fast3, LP_WIN3): one render column less per step (columns +// floor(px) - 1 ... + 1: 63 r + 4 at most), the same rows (the second row of the last pair reads floor(py0) + 2: 14 r + 5), +// a staging area of 448 texels, the same margin of one column and one row. l_tf_supported holds too (the frame's route). +constexpr int kLTf3Cap = 448; +bool l_tf3_supported(int rw, int rh, int dw, int dh) { + return l_tf_supported(rw, rh, dw, dh) && + ((long long)(63.0 * rw / dw) + 5) * ((long long)(14.0 * rh / dh) + 6) <= kLTf3Cap; +} // post_tf4_dl_* (D3D12 only, dx12/kernels/post.hlsl; Brief 15): the same kernel with NW = 4 row pairs per step (256 lanes) // and a staging cap of 448, for native AA and every ratio between 1.0 and 1.5 on the native D3D12 backend (HIP's // post_tf_dl_* needs 41472 bytes of LDS, more than D3D12's 32 KB). The step footprint of NW = 4 (64 D columns x 4 row @@ -325,19 +333,29 @@ struct Runtime { // hybrid form is the bit-exact one); the history, the reset and the temporal logic are the same code. std::string l_mode_opt; bool l_fast_d3d12 = false; - // The levers of l_mode=fast (the kernels of the build named "_fast", native D3D12; every one is launched in place of - // its base kernel with the same arguments, l_fast_alt: base name -> fast name). One bit per group of kernels, all on by - // default; a developer build reads the selection from WG_L_FAST_MASK (an A/B of each lever, below). - // 1 l_post_tf_p12[_pf] the true-fusion output kernel without the bit-exactness guards (l_post_tf_fast.hlsl) - // 2 l_project_gather, l_dec_project the K blocks accumulated in FP32 and rounded once, in the FP8 pack - // 4 the width-32 Swin blocks (so far: the encoder block with the linears, its prologue in FP32) - // 8 the middle Swin blocks (c64, c96, the bottleneck: no twin yet; the build's "_fast" names decide) - // 16 the weaker history candidate as a 4-tap bilinear (inside the kernel of lever 1: pitch_bytes bit 0) - // 32 the q20 input encoder (no twin yet) - // 64 a weaker history candidate with the first one's motion (within 0.01 render pixel) is not read twice (lever 1: bit 1) - // 128 a weaker history candidate of weight below 0.05 (the hybrid route: 1 / 255) is dropped (lever 1: bit 2; off by default: - // a quality / speed trade-off for the A/B) - static constexpr unsigned kLFastAll = 255u, kLFastDefault = 127u; + // The levers of l_mode=fast (native D3D12): kernels of the build launched in place of a base kernel with the same grid, + // block and arguments (l_fast_alt: base name -> the kernel launched). A "_fast" twin replaces when its + // group's bit is set (l_fast_bit); the alternatives of kLFastAlts (in their order, the first one in the build whose bits + // are all set) come before it. All on by default but bit 128; a developer build reads the selection from WG_L_FAST_MASK + // (an A/B of each lever, below). + // 1 l_post_tf_p12[_pf] the true-fusion output kernel without the bit-exactness guards (l_post_tf_fast.hlsl) + // 2 l_project_gather, l_dec_project the K blocks accumulated in FP32 and rounded once, in the FP8 pack + // 4 the width-32 Swin blocks' "_fast" twins (the encoder block with the linears, its prologue in FP32) + // 8 the middle Swin blocks' "_fast" twins (swin_block_c64_nc_fast, swin_block_c64_add_ex_nc_fast when the build has + // them: l_swin_c64_fast.hlsl; c96 and the bottleneck: no twin) + // 16 the weaker history candidate as a 4-tap bilinear (inside the kernel of lever 1: pitch_bytes bit 0) + // 32 the q20 input encoder (no twin yet) + // 64 a weaker history candidate with the first one's motion (within 0.01 render pixel) is not read twice (lever 1: bit 1) + // 128 a weaker history candidate of weight below 0.05 (the hybrid route: 1 / 255) is dropped (lever 1: bit 2; off by + // default: a quality / speed trade-off for the A/B) + // 256 with lever 1: the centred 3 x 3 gather (l_post_tf_p12[_pf]_fast3) for every frame whose step footprint fits its + // staging (l_tf3_supported; a frame that does not runs the 4 x 4 twin, which the build must then have) + // 512 the encoder block with the linears: two windows per wave (l_swin_block_c32_enc_lin_w2[t]_fast, l_swin_c32_fast.hlsl) + // in place of lever 4's twin + // 1024 the decoder block with the coefficient store: two windows per wave (l_swin_block_c32_dec_coef12_add_w2[t]_fast) + // 2048 (reserved: the bottleneck's fast twin; none built) + // 4096 the quick GELU in the kernels of 512 / 1024 ("_w2_fast"); off: their table form "_w2t_fast" (the model's GELU bytes) + static constexpr unsigned kLFastAll = 8191u, kLFastDefault = 8191u & ~128u & ~2048u; unsigned l_fast_mask = kLFastDefault; std::map l_fast_alt; static unsigned l_fast_bit(const std::string& n) { @@ -348,6 +366,18 @@ struct Runtime { if (n.compare(0, 20, "lev/input_encoder_q2") == 0) return 32u; return 0u; } + struct LFastAlt { const char* base; const char* alt; unsigned bits; }; + static constexpr LFastAlt kLFastAlts[] = { + {"w64_lc12/l_post_tf_p12", "w64_lc12/l_post_tf_p12_fast3", 1u | 256u}, + {"w64_lc12/l_post_tf_p12_pf", "w64_lc12/l_post_tf_p12_pf_fast3", 1u | 256u}, + {"l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2_fast", 512u | 4096u}, + {"l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2t_fast", 512u}, + {"l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2_fast", 1024u | 4096u}, + {"l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2t_fast", 1024u}, + }; + // the 4 x 4 twin of a selected 3 x 3 post (l_fast_alt's value "_fast3" -> "_fast"): the frames whose + // footprint the 3 x 3 kernel's staging does not take + static bool l_is_post3(const std::string& k) { return k.size() > 6 && k.compare(k.size() - 6, 6, "_fast3") == 0; } // WG_L_FORM=hybrid on native D3D12 (hyb-fast, 0.6.5 L release form): Model L's M-form route (l_q7 off) with every // block stage packed from the hybrid values (clean/l/runtime/l_hyb_pack.h, the same blob names and layout) and every // Swin kernel launched as its hybrid twin from the kernel manifest (hyb-fast's names: the M-form route's name with @@ -1117,18 +1147,32 @@ struct Runtime { std::vector skip; const std::vector mk = manifest_kernels(); const std::set in_build(mk.begin(), mk.end()); - if (l_fast_d3d12) - for (const std::string& h : mk) { + std::set fast_kernels, warm; // every fast-mode kernel of the build; those this mode may launch + for (const auto& a : kLFastAlts) + if (in_build.count(a.alt)) fast_kernels.insert(a.alt); + for (const std::string& h : mk) + if (h.size() > 5 && h.compare(h.size() - 5, 5, "_fast") == 0) fast_kernels.insert(h); + if (l_fast_d3d12) { + for (const auto& a : kLFastAlts) // the table's alternatives first (the 3 x 3 post only beside its 4 x 4 twin) + if (!l_fast_alt.count(a.base) && in_build.count(a.base) && in_build.count(a.alt) && + (l_fast_mask & a.bits) == a.bits && (!l_is_post3(a.alt) || in_build.count(std::string(a.base) + "_fast"))) + l_fast_alt[a.base] = a.alt; + for (const std::string& h : mk) { // then the "_fast" twins of their lever bit const bool fast = h.size() > 5 && h.compare(h.size() - 5, 5, "_fast") == 0; const std::string base = fast ? h.substr(0, h.size() - 5) : h; - if (fast && in_build.count(base) && (l_fast_mask & l_fast_bit(base))) l_fast_alt[base] = h; + if (fast && in_build.count(base) && !l_fast_alt.count(base) && (l_fast_mask & l_fast_bit(base))) + l_fast_alt[base] = h; } + for (const auto& m : l_fast_alt) { + warm.insert(m.second); + if (l_is_post3(m.second)) warm.insert(m.first + "_fast"); // its fallback for a footprint over the cap + } + } for (const std::string& h : mk) { const bool twin = h.size() > 4 && h.compare(h.size() - 4, 4, "_hyb") == 0; - const bool fast = h.size() > 5 && h.compare(h.size() - 5, 5, "_fast") == 0; + const bool fast = fast_kernels.count(h) != 0; if (l_fast_d3d12 ? (twin || h.compare(0, 5, "l_q7_") == 0 || h == "l_swin_block_c32_dec_nc" || - h == "l_swin_block_c32_dec_coef12_nc" || l_fast_alt.count(h) != 0 || - (fast && !l_fast_alt.count(h.substr(0, h.size() - 5)) ) ) + h == "l_swin_block_c32_dec_coef12_nc" || l_fast_alt.count(h) != 0 || (fast && !warm.count(h))) : (fast || h == "l_swin_block_c32_dec_add_nc" || h == "l_swin_block_c32_dec_coef12_add_nc")) skip.push_back(h); } @@ -3357,9 +3401,13 @@ struct Runtime { float dec_scale = (float)(0.01 / (fr.exposure == 0.0f ? 1.0 : (double)fr.exposure)), p_h = pi; if (l_fold_pidiv) std::memcpy(&p.pad0, &pi, 4); // the pre-exposure's bits: the _pf kernel divides every colour read post_last = l_fold_pidiv ? "w64_lc12/l_post_tf_p12_pf" : "w64_lc12/l_post_tf_p12"; - if (l_fast_alt.count(post_last)) hpitch = ((l_fast_mask & 16u) ? 1 : 0) | ((l_fast_mask & 64u) ? 2 : 0) | ((l_fast_mask & 128u) ? 4 : 0); // the fast kernel's pitch_bytes is its option word + std::string post_k = post_last; + if (l_fast_alt.count(post_last)) { + hpitch = ((l_fast_mask & 16u) ? 1 : 0) | ((l_fast_mask & 64u) ? 2 : 0) | ((l_fast_mask & 128u) ? 4 : 0); // the fast kernel's pitch_bytes is its option word + if (l_is_post3(l_fast_alt[post_last]) && !l_tf3_supported(rw, rh, dw, dh)) post_k = post_last + "_fast"; // the 4 x 4 twin + } filter_last = "fused"; - if (!launch(post_last.c_str(), cdiv(ow, 40) * nch, 512, + if (!launch(post_k.c_str(), cdiv(ow, 40) * nch, 512, {&cnet, &A, &B, &C, &hist[cur], &mnear[nxt], &mcenter, &mfar, &w, &hist[nxt], &reduced, &outp, &p, &expo, &ow_i, &oh_i, &dec_scale, &p_h, &hpitch, &cp, &k1, &c2})) return false; diff --git a/clean/tests/runtime_frame_trace.cpp b/clean/tests/runtime_frame_trace.cpp index 0fccfcf0..dbf04320 100644 --- a/clean/tests/runtime_frame_trace.cpp +++ b/clean/tests/runtime_frame_trace.cpp @@ -127,8 +127,16 @@ const Signature kSignatures[] = { const char* kinds_of(const std::string& kernel) { const size_t slash = kernel.find('/'); std::string k = slash == std::string::npos ? kernel : kernel.substr(slash + 1); - // a fast twin (l_mode=fast: "_fast", launched in place of its base kernel) has the base kernel's arguments - if (k.size() > 5 && k.compare(k.size() - 5, 5, "_fast") == 0) k.resize(k.size() - 5); + // a fast-mode kernel (l_mode=fast, launched in place of its base kernel) has the base kernel's arguments: + // "_fast", "_fast3" -> ; "_w2_fast", "_w2t_fast" -> "_nc" (build_dx12.py fast_base) + const auto ends = [&](const char* suf) { + const size_t n = std::strlen(suf); + return k.size() > n && k.compare(k.size() - n, n, suf) == 0; + }; + if (ends("_w2_fast")) k.replace(k.size() - 8, 8, "_nc"); + else if (ends("_w2t_fast")) k.replace(k.size() - 9, 9, "_nc"); + else if (ends("_fast3")) k.resize(k.size() - 6); + else if (ends("_fast")) k.resize(k.size() - 5); // dec1's block fused with the decoder (swin_block_c64_add_dec0*): x, skip, w, H, W, ox, oy, then the decoder's // arguments: not the blocks' common form if (k.find("_add_dec0") != std::string::npos) return "pppiiii"; From 23a8b595ec97ffae22bade018cd8bc5e41a9fcf5 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:50:43 -0500 Subject: [PATCH 4/5] Model L (D3D12): l_mode=fast levers 4096 / 8 / 8192: the clamped-cubic GELU in the width-32 and width-64 twins, width-96 twins; 3 x 3 post off by default RX 9070 XT (2B-3, 8d0e32f): the 3 x 3 post gather (lever 256) failed the HDR gate (38.7 dB / SSIM 0.955 against 53.2 dB / 0.998 with the 4 x 4 gather); quick GELU x / (1 + 2^(-2.53 x)) was 44 / 56 us slower than the table form in the width-32 blocks and 7 / 18 us slower in the c64 twins (its exponential and reciprocal run on the quarter-rate transcendental unit). Best clean mask there: 1655, 3.266 ms. - GELU (l_swin_c32_fast.hlsl LF_GELU 1): 2 GELU(x) = x + |x| min(P(|x|), 1), P a cubic fitted (weighted minimax) to the model's GELU: |x| by an AND with an opaque mask, three v_fmaak, a v_min, a v_fmac, all of them VOPD-pairable (RGA: the driver pairs most of them), no exponential, no table load. The W2 products accumulate onto twice the residual (the accumulator doubled with b2 after norm2, halved at the output / coefficient store: exact power-of-two scalings, FP8(2 g) = 2 FP8(g) for every normal code), so the halving is no operation per value. Max error 0.0020, RMS 0.0014 against the model's GELU (quick GELU: 0.016 / 0.009), 84.8 % of the FP8 codes unchanged. The hidden values' FP8 range without a clamp is |h| < 224 (the table form's: 448). Kernels: l_swin_block_c32_enc_lin_w2p_fast / l_swin_block_c32_dec_coef12_add_w2p_fast (lever 512 / 1024 with 4096, replacing the quick-GELU "_w2_fast" ones; without 4096 the table twins "_w2t_fast"), swin_block_c64_nc_fast / swin_block_c64_add_ex_nc_fast (lever 8). - Width-96 twins (lever 8192, new l_swin_c96_fast.hlsl): the same body in the base kernels' launch shape (256 lanes, one window per wave), the clamped-cubic GELU (no groupshared table: LDS 26 624 / 28 672 -> 24 576 bytes) and the softmax without the maximum: swin_block_c96_add_ex_nc_fast (dec2, the fused expand) and swin_block_c96_pm_rev_nc_fast (enc2 with enc1's patch merge as its prologue: fused_swin.hlsl's SW_PM code, FZ_PMT 1, its aux / aux2 arguments appended to swin_block.hlsl's argument block by WG_ARGS_END). - No bottleneck twin (lever 2048 stays reserved; the persistent bmegahg kernel is generated and measured sensitive to its compiled form), no post or encoder change (a packed FP16 feature sum in the post gather compiled to the same ISA: the driver scalarizes it). RGA (gfx1201), per wave, loops expanded (base c96: head loop x4 / x2, MLP loop x2), no spills (scratch 0, VGPR / SGPR spills 0); slots without s_delay_alu / s_wait / s_nop: enc0 c32 w2t 164 VGPRs, 2027 slots, 1514 VALU, 41 trans, 192 buffer loads -> w2p 139, 2080, 1696, 41, 64 dec0 c32 w2t 172, 1846, 1391, 65, 177 -> w2p 150, 1880, 1554, 65, 49 enc1 c64 base 191, 3236, 2326, 169, 286 -> fast 192, 3244, 2531, 41, 94 dec1 c64 base 192, 3858, 2774, 169, 324 -> fast 192, 3916, 3026, 41, 132 enc2 c96 base 173 / 26 624 B, 4480, 2865, 39, 216, 451 ds -> fast 186 / 24 576 B, 3264, 2126, 39, 160, 300 ds dec2 c96 base 192 / 28 672 B, 4524, 2973, 39, 231, 417 ds -> fast 181 / 24 576 B, 3404, 2294, 39, 175, 257 ds The width-32 / width-64 twins trade the table loads (and in c64 128 transcendentals) for 1 to 3 % more issue slots; which one is faster is the GPU A/B of lever 4096 (w2p against w2t) and lever 8. The width-96 twins have 25 to 27 % fewer slots. runtime: WG_L_FAST_MASK default 6015 -> 13951 (every lever but 128, 256 and 2048), kLFastAll 16383; l_fast_bit: c96 -> 8192, bneck -> 2048, the other swin_block_* -> 8. build_dx12.py fast_base / runtime_frame_trace: "_w2p_fast". Every other DXIL of the build is byte-identical (135 of 139 entries; changed: the two c64 twins; replaced: the two "_w2_fast"); hyb_isa_scan clean on the 26 hybrid kernels. Tests: PolyGelu (constants, error bounds, shape, the doubled accumulator, FP8 codes) in test_l_fast_numerics.py, the new default and lever 8192 in test_l_runtime_fast_mode.py, kernel_sets.json, vgpr_limits.json. --- clean/dx12/README.md | 2 +- clean/dx12/build_dx12.py | 4 +- clean/dx12/kernel_sets.json | 12 +- clean/dx12/kernels/l_swin_c32_fast.hlsl | 124 +++++++++++++++--- clean/dx12/kernels/l_swin_c64_fast.hlsl | 4 +- clean/dx12/kernels/l_swin_c96_fast.hlsl | 25 ++++ clean/dx12/tests/test_kernel_sets.py | 4 +- clean/dx12/vgpr_limits.json | 6 +- clean/l/SPEED.md | 22 ++-- .../runtime/tests/test_l_runtime_fast_mode.py | 48 ++++--- clean/l/tests/test_l_fast_numerics.py | 95 ++++++++++---- clean/runtime/runtime.cpp | 26 ++-- clean/tests/runtime_frame_trace.cpp | 4 +- 13 files changed, 279 insertions(+), 97 deletions(-) create mode 100644 clean/dx12/kernels/l_swin_c96_fast.hlsl diff --git a/clean/dx12/README.md b/clean/dx12/README.md index d367fc94..8619a4b5 100644 --- a/clean/dx12/README.md +++ b/clean/dx12/README.md @@ -132,7 +132,7 @@ WG_KERNEL(exposure_auto_diet) { WG_SETUP(); ... } // entry name = HIP kernel n 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 `_w2_fast` / `_w2t_fast` (two windows per wave, in place of + `_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 diff --git a/clean/dx12/build_dx12.py b/clean/dx12/build_dx12.py index 4e873666..7ed7ebe5 100644 --- a/clean/dx12/build_dx12.py +++ b/clean/dx12/build_dx12.py @@ -229,9 +229,9 @@ def kernel_decls(path): 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 ; "_w2_fast" / "_w2t_fast" (the + 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"(.+)_w2t?_fast", name) + m = re.fullmatch(r"(.+)_w2[pt]_fast", name) if m: return m.group(1) + "_nc" m = re.fullmatch(r"(.+)_fast3?", name) diff --git a/clean/dx12/kernel_sets.json b/clean/dx12/kernel_sets.json index c41ec31d..7fe6a959 100644 --- a/clean/dx12/kernel_sets.json +++ b/clean/dx12/kernel_sets.json @@ -347,7 +347,7 @@ "-" ], [ - "l_swin_block_c32_dec_coef12_add_w2_fast", + "l_swin_block_c32_dec_coef12_add_w2p_fast", "-" ], [ @@ -387,7 +387,7 @@ "-" ], [ - "l_swin_block_c32_enc_lin_w2_fast", + "l_swin_block_c32_enc_lin_w2p_fast", "-" ], [ @@ -502,6 +502,10 @@ "swin_block_c96_add_ex_hyb", "-" ], + [ + "swin_block_c96_add_ex_nc_fast", + "-" + ], [ "swin_block_c96_add_hyb", "-" @@ -514,6 +518,10 @@ "swin_block_c96_hyb", "-" ], + [ + "swin_block_c96_pm_rev_nc_fast", + "-" + ], [ "swin_block_c96_q7c_hyb", "-" diff --git a/clean/dx12/kernels/l_swin_c32_fast.hlsl b/clean/dx12/kernels/l_swin_c32_fast.hlsl index 6b272185..305537cd 100644 --- a/clean/dx12/kernels/l_swin_c32_fast.hlsl +++ b/clean/dx12/kernels/l_swin_c32_fast.hlsl @@ -11,14 +11,22 @@ // // 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 = x sigma(k x) = x / (1 + 2^(-2.53 x)) ("quick GELU" with its constant fitted to the model's GELU, -// k = 1.7537: three VALU operations, an exponential and a reciprocal per value, no table load; |error| <= 0.016, -// RMS 0.009 for N(0, 1.5) inputs against the model's GELU, test_l_fast_numerics.py); +// - 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 quick GELU). -// (the "_w2t_fast" kernels are the "_w2_fast" ones with LF_GELU 2: the A/B of the GELU approximation alone) +// 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 @@ -29,9 +37,9 @@ // 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_w2_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=8,SW_SRC=3,WG_LD_A16=1,WG_REV_ORDER=1,LF_NAME=l_swin_block_c32_enc_lin_w2_fast,LF_GELU=1 +// @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=8,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=8,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_w2_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=8,SW_SRC=2,SW_OUT_F16=1,SW_OUT_COEF12=1,WG_LD_A16=1,LF_NAME=l_swin_block_c32_dec_coef12_add_w2_fast,LF_GELU=1 +// @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=8,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=8,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 @@ -50,16 +58,51 @@ #endif #include "swin_block.hlsl" -#if THREADS != 128 || 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 lanes, the M-form inner packs; output q8 or the coefficient store; source 0 (with or without the fused expand), 2 or 3" +#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 -#define NWW 2 // windows per wave +#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) +#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) ---------------------------------------------------------------- -static const float kLfQg = asfloat(0xc021eb85u); // -2.53 = -1.7537 log2(e): the fitted constant (test_l_fast_numerics.py) +// 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 @@ -67,12 +110,17 @@ uint2 lf_gelu_q8(v8f h) { v8f y; #if LF_GELU == 1 - float t[8]; - [unroll] for (uint i = 0; i < 8; ++i) t[i] = h.v[i] * kLfQg; - [unroll] for (uint i1 = 0; i1 < 8; ++i1) t[i1] = wg_exp2(t[i1]); - [unroll] for (uint i2 = 0; i2 < 8; ++i2) t[i2] = 1.0f + t[i2]; - [unroll] for (uint i3 = 0; i3 < 8; ++i3) t[i3] = wg_rcp(t[i3]); - [unroll] for (uint i4 = 0; i4 < 8; ++i4) y.v[i4] = h.v[i4] * t[i4]; + // 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]; @@ -104,7 +152,7 @@ uint4 lf_softmax(v8f s, v8f bias) return wg_to_f16_ags(pm); } -#if SW_SRC == 3 +#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]) @@ -176,7 +224,7 @@ WG_KERNEL(LF_NAME) int prw[NWW], pcw[NWW]; #endif v8f acc[NWW][KC]; -#if SW_SRC == 3 +#if LF_LIN v8f lb1[2], lb2[2]; uint2 lf1[2][2], lf2[2][2]; lin_blob(linW1, lane, hh, lb1, lf1); @@ -208,8 +256,28 @@ WG_KERNEL(LF_NAME) 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 SW_SRC == 3 +#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 @@ -239,7 +307,7 @@ WG_KERNEL(LF_NAME) // 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 SW_SRC != 3 +#if !LF_LIN [unroll] for (uint k = 0; k < KC; ++k) { acc[i1][k] = sw_unpack_fp8(xa[i1][k]); #if SW_ADD @@ -315,11 +383,18 @@ WG_KERNEL(LF_NAME) [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 } } } @@ -377,6 +452,9 @@ WG_KERNEL(LF_NAME) 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; +#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 @@ -389,6 +467,10 @@ WG_KERNEL(LF_NAME) #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]); diff --git a/clean/dx12/kernels/l_swin_c64_fast.hlsl b/clean/dx12/kernels/l_swin_c64_fast.hlsl index 6f02edb6..cc16e768 100644 --- a/clean/dx12/kernels/l_swin_c64_fast.hlsl +++ b/clean/dx12/kernels/l_swin_c64_fast.hlsl @@ -3,7 +3,9 @@ // 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: quick GELU (no table load) and the softmax without the maximum; everything else is the base +// 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 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/tests/test_kernel_sets.py b/clean/dx12/tests/test_kernel_sets.py index eb76a955..fd5b5359 100644 --- a/clean/dx12/tests/test_kernel_sets.py +++ b/clean/dx12/tests/test_kernel_sets.py @@ -92,7 +92,7 @@ def test_frame_gen_kernels_are_in_no_set(self): def test_fast_twins_take_their_base_kernels_arguments(self): - """A fast-mode kernel (Model L's l_mode=fast: "_fast", "_fast3", "_w2[t]_fast" in place of + """A fast-mode kernel (Model L's l_mode=fast: "_fast", "_fast3", "_w2p_fast" / "_w2t_fast" in place of "_nc", build_dx12.py fast_base) is launched by the runtime in place of its base kernel with the same grid, block and arguments: the declarations agree in block, wave and args, and in group unless the fast kernel is a two-windows-per-wave one (its own 128-lane workgroup per launched workgroup, gscale 1: the device's launch of the @@ -104,7 +104,7 @@ def test_fast_twins_take_their_base_kernels_arguments(self): decls.setdefault(d["name"], []).append(d) twins = [n for n in decls if B.fast_base(n) is not None] self.assertTrue(twins) - self.assertTrue([n for n in twins if n.endswith("_w2_fast")]) + self.assertTrue([n for n in twins if n.endswith("_w2p_fast")]) self.assertTrue([n for n in twins if n.endswith("_fast3")]) full, m = set(B.kernel_set(True)), set(B.kernel_set(False)) for n in twins: diff --git a/clean/dx12/vgpr_limits.json b/clean/dx12/vgpr_limits.json index 654e72d4..329373ea 100644 --- a/clean/dx12/vgpr_limits.json +++ b/clean/dx12/vgpr_limits.json @@ -37,14 +37,16 @@ "l_swin_block_c32_dec_add_nc": 96, "l_swin_block_c32_dec_coef12_add_nc": 96, "l_swin_block_c32_enc_lin_nc_fast": 96, - "l_swin_block_c32_enc_lin_w2_fast": 192, + "l_swin_block_c32_enc_lin_w2p_fast": 192, "l_swin_block_c32_enc_lin_w2t_fast": 192, - "l_swin_block_c32_dec_coef12_add_w2_fast": 192, + "l_swin_block_c32_dec_coef12_add_w2p_fast": 192, "l_swin_block_c32_dec_coef12_add_w2t_fast": 192, "swin_block_c64_nc": 192, "swin_block_c64_add_ex_nc": 192, "swin_block_c64_nc_fast": 192, "swin_block_c64_add_ex_nc_fast": 192, + "swin_block_c96_pm_rev_nc_fast": 192, + "swin_block_c96_add_ex_nc_fast": 192, "swin_block_c96_nc": 192, "swin_block_c96_add_ex_nc": 192, "swin_block_c96_pm_nc": 192, diff --git a/clean/l/SPEED.md b/clean/l/SPEED.md index 7172f7cc..5e34b645 100644 --- a/clean/l/SPEED.md +++ b/clean/l/SPEED.md @@ -103,19 +103,21 @@ kernel). They drop the bit-exactness of the hybrid route where it costs instruct | 16 | (option of lever 1) | the weaker history candidate (weight at most 1/2) is a 4-tap bilinear of the previous history instead of the 12-tap Catmull-Rom | | 64 | (option of lever 1) | a weaker history candidate whose motion is within 0.01 render pixel of the first one's is the same sample and is not read twice | | 128 | (option of lever 1, off by default) | a weaker history candidate of weight below 0.05 is dropped (the hybrid route drops it below 1 / 255) | -| 8 | `swin_block_c64_nc_fast`, `swin_block_c64_add_ex_nc_fast` | enc1's and dec1's blocks (`l_swin_c64_fast.hlsl`): the two-windows-per-wave body below at C = 64 with quick GELU (no table load) and the softmax without the maximum | -| 256 | `w64_lc12/l_post_tf_p12[_pf]_fast3` (with lever 1) | the gather over the 3 x 3 render texels centred on each D pixel (`LP_WIN3`; every tap within 1.5 render pixels, each row of a pair with its own centred rows) instead of the 4 x 4 window: 18 taps per row pair instead of 32; staging cap 448 texels, a frame whose step footprint does not fit (`l_tf3_supported`) runs the 4 x 4 twin | -| 512 | `l_swin_block_c32_enc_lin_w2[t]_fast` | the encoder block with the linears, two windows per wave in 128-lane workgroups (`l_swin_c32_fast.hlsl`, the launch shape of `swin_c64w2.hlsl`): weight fragments, biases and the linears' weights loaded once for both windows, a barrier waits for 4 waves; the softmax without the maximum (the soft cap bounds the exponents to +-11) | -| 1024 | `l_swin_block_c32_dec_coef12_add_w2[t]_fast` | the decoder block with the coefficient store, the same two-windows-per-wave body; the coefficient epilogue one pixel per lane (the hh = 1 lanes take the second window's channels by `v_permlanex16`) in FP32 from the block's FP32 output (no FP16 rounding of y2, tanh as `1 - 2 / (2^(2 t log2 e) + 1)`) | -| 4096 | (option of 512 / 1024) | quick GELU `x / (1 + 2^(-2.53 x))` in the two-windows kernels (`_w2_fast`: no table load; max error 0.016, RMS 0.009 against the model's GELU); off: their table form `_w2t_fast` (the model's GELU bytes by the arena table) | +| 8 | `swin_block_c64_nc_fast`, `swin_block_c64_add_ex_nc_fast` | enc1's and dec1's blocks (`l_swin_c64_fast.hlsl`): the two-windows-per-wave body below at C = 64 with the clamped-cubic GELU (no table load, no exponential) and the softmax without the maximum | +| 256 | `w64_lc12/l_post_tf_p12[_pf]_fast3` (with lever 1; off by default: RX 9070 XT 38.7 dB / SSIM 0.955 HDR against the hybrid route, the 4 x 4 gather 53.2 dB / 0.998) | the gather over the 3 x 3 render texels centred on each D pixel (`LP_WIN3`; every tap within 1.5 render pixels, each row of a pair with its own centred rows) instead of the 4 x 4 window: 18 taps per row pair instead of 32; staging cap 448 texels, a frame whose step footprint does not fit (`l_tf3_supported`) runs the 4 x 4 twin | +| 512 | `l_swin_block_c32_enc_lin_w2p_fast` / `_w2t_fast` | the encoder block with the linears, two windows per wave in 128-lane workgroups (`l_swin_c32_fast.hlsl`, the launch shape of `swin_c64w2.hlsl`): weight fragments, biases and the linears' weights loaded once for both windows, a barrier waits for 4 waves; the softmax without the maximum (the soft cap bounds the exponents to +-11) | +| 1024 | `l_swin_block_c32_dec_coef12_add_w2p_fast` / `_w2t_fast` | the decoder block with the coefficient store, the same two-windows-per-wave body; the coefficient epilogue one pixel per lane (the hh = 1 lanes take the second window's channels by `v_permlanex16`) in FP32 from the block's FP32 output (no FP16 rounding of y2, tanh as `1 - 2 / (2^(2 t log2 e) + 1)`) | +| 4096 | (option of 512 / 1024) | the clamped-cubic GELU `(x + abs(x) min(P(abs(x)), 1)) / 2` in the two-windows kernels (`_w2p_fast`: six full-rate operations per value the driver pairs as VOPD, no table load, no exponential; the W2 products accumulate onto twice the residual, so the halving costs nothing per value; max error 0.002, RMS 0.0014 against the model's GELU, 85 % of the FP8 codes unchanged); off: their table form `_w2t_fast` (the model's GELU bytes by the arena table) | +| 8192 | `swin_block_c96_pm_rev_nc_fast`, `swin_block_c96_add_ex_nc_fast` | enc2's block with enc1's patch merge and dec2's block with the fused expand (`l_swin_c96_fast.hlsl`): the same body in the base kernels' launch shape (one window per wave), the clamped-cubic GELU (no groupshared table: LDS 26 624 / 28 672 -> 24 576 bytes) and the softmax without the maximum | +| 2048 | (reserved) | the bottleneck's fast twin: none built (the persistent bottleneck kernel keeps its base form) | A developer build (`dev_diagnostics`) reads the selection of levers from `WG_L_FAST_MASK` (the sum of the lever values -above; the default is 6015 = every lever and option but 128 and 2048, the latter reserved for a bottleneck twin that does -not exist yet; the earlier default 127 is the set without 256, 512, 1024 and 4096) for an A/B of each; a release build has -no such variable. The arithmetic choices are bounded on the CPU by `clean/l/tests/test_l_fast_numerics.py` (the quality -gate itself is measured on the GPU against `l_mode=hybrid`: tone-mapped PSNR / SSIM and temporal stability). Lever 256 is +above; the default is 13951 = every lever and option but 128, 256 and 2048: 256 failed the GPU quality gate, 2048 is +reserved for a bottleneck twin that does not exist yet; earlier defaults: 127, then 6015 with 256 and the quick GELU) +for an A/B of each; a release build has no such variable. The arithmetic choices are bounded on the CPU by +`clean/l/tests/test_l_fast_numerics.py` (the quality gate itself is measured on the GPU against `l_mode=hybrid`: tone-mapped PSNR / SSIM and temporal stability). Lever 256 is the one whose difference depends on the model's kernel widths (CPU bound: 52.9 dB on texel noise at sigma 0.5 render -pixel, 30.6 dB at sigma 1): it is the first one to check in that A/B. +pixel, 30.6 dB at sigma 1): on the RX 9070 XT it measured 38.7 dB / SSIM 0.955 HDR and is off by default. ## Building Model L diff --git a/clean/l/runtime/tests/test_l_runtime_fast_mode.py b/clean/l/runtime/tests/test_l_runtime_fast_mode.py index 6aeabb73..fa9fe757 100644 --- a/clean/l/runtime/tests/test_l_runtime_fast_mode.py +++ b/clean/l/runtime/tests/test_l_runtime_fast_mode.py @@ -55,8 +55,8 @@ def fast_base(n): """The base kernel a fast-mode kernel is launched in place of (clean/dx12/build_dx12.py fast_base): "_fast", - "_fast3" -> ; "_w2_fast", "_w2t_fast" -> "_nc"; None for any other kernel.""" - m = re.fullmatch(r"(.+)_w2t?_fast", n) + "_fast3" -> ; "_w2p_fast", "_w2t_fast" -> "_nc"; None for any other kernel.""" + m = re.fullmatch(r"(.+)_w2[pt]_fast", n) if m: return m.group(1) + "_nc" m = re.fullmatch(r"(.+)_fast3?", n) @@ -67,11 +67,12 @@ def fast_base(n): # their lever bit (l_fast_bit); kLFastDefault ALTS = (("w64_lc12/l_post_tf_p12", "w64_lc12/l_post_tf_p12_fast3", 1 | 256), ("w64_lc12/l_post_tf_p12_pf", "w64_lc12/l_post_tf_p12_pf_fast3", 1 | 256), - ("l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2_fast", 512 | 4096), + ("l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2p_fast", 512 | 4096), ("l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2t_fast", 512), - ("l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2_fast", 1024 | 4096), + ("l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2p_fast", 1024 | 4096), ("l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2t_fast", 1024)) -DEFAULT_MASK = 8191 & ~128 & ~2048 +ALL_MASK = 16383 +DEFAULT_MASK = ALL_MASK & ~128 & ~256 & ~2048 def lever_bit(base): @@ -81,7 +82,11 @@ def lever_bit(base): return 2 if base.startswith("l_swin_block_c32_"): return 4 - if base.startswith("swin_block_") or base.startswith("bneck/swin_bneck"): + if base.startswith("swin_block_c96"): + return 8192 + if base.startswith("bneck/swin_bneck"): + return 2048 + if base.startswith("swin_block_"): return 8 return 32 if base.startswith("lev/input_encoder_q2") else 0 @@ -453,12 +458,16 @@ def test_twins_declared(self): self.assertIn(k, selection()[0]) for k in t: self.assertIn(fast_base(k), [x for x, _ in F.full_ports()], k) # every fast kernel replaces a base kernel - # the default selection: the 3 x 3 post, the two-windows-per-wave width-32 blocks with quick GELU, the c64 twins + # the default selection: the 4 x 4 post (lever 256, the 3 x 3 gather, is off), the two-windows-per-wave width-32 + # blocks with the clamped-cubic GELU, the c64 twins, the c96 twins of the build alt = selection()[0] - self.assertEqual(alt["w64_lc12/l_post_tf_p12"], "w64_lc12/l_post_tf_p12_fast3") - self.assertEqual(alt[ENC_LIN], "l_swin_block_c32_enc_lin_w2_fast") - self.assertEqual(alt[FOLD_ADD], "l_swin_block_c32_dec_coef12_add_w2_fast") + self.assertEqual(alt["w64_lc12/l_post_tf_p12"], "w64_lc12/l_post_tf_p12_fast") + self.assertEqual(alt[ENC_LIN], "l_swin_block_c32_enc_lin_w2p_fast") + self.assertEqual(alt[FOLD_ADD], "l_swin_block_c32_dec_coef12_add_w2p_fast") self.assertEqual(alt["swin_block_c64_nc"], "swin_block_c64_nc_fast") + self.assertEqual(alt["swin_block_c96_add_ex_nc"], "swin_block_c96_add_ex_nc_fast") + self.assertEqual(alt["swin_block_c96_pm_rev_nc"], "swin_block_c96_pm_rev_nc_fast") + self.assertNotIn("bneck/swin_bneck6_mb_nc", alt) # (lever 2048: no bottleneck twin) def test_launched_in_place_of_the_base_kernel(self): a = FastTrace(l_run("model=L,l_mode=fast", frames=3, tf_default=True)) @@ -478,19 +487,20 @@ def test_launched_in_place_of_the_base_kernel(self): def test_pre_exposure_post_twin(self): t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, flags=("--pre-exposure=2.0",))) for f in t.frames: - self.assertIn("w64_lc12/l_post_tf_p12_pf_fast3", f["fast"]) - self.assertNotIn("w64_lc12/l_post_tf_p12_fast3", f["fast"]) + self.assertIn("w64_lc12/l_post_tf_p12_pf_fast", f["fast"]) + self.assertNotIn("w64_lc12/l_post_tf_p12_fast", f["fast"]) def test_post3_footprint_fallback(self): """A frame whose step footprint the 3 x 3 post's staging (448 texels) does not take, but the 4 x 4 one's (512) does, runs the 4 x 4 twin (render 96 x 48 for D 180 x 108: (33 + 5) 12 = 456 > 448, (33 + 6) 12 = 468 <= 512); the same frames at 80 x 48 run the 3 x 3 kernel.""" - t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, rw=96, rh=48)) + dev = {"exe": dev_exe(), "env": {"WG_L_FAST_MASK": str(DEFAULT_MASK | 256)}} # (256 is off by default) + t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, rw=96, rh=48, **dev)) self.assertEqual(t.create, "create ok model L") for f in t.frames: self.assertIn("w64_lc12/l_post_tf_p12_fast", f["fast"]) self.assertNotIn("w64_lc12/l_post_tf_p12_fast3", f["fast"]) - t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, rw=80, rh=48)) + t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, rw=80, rh=48, **dev)) for f in t.frames: self.assertIn("w64_lc12/l_post_tf_p12_fast3", f["fast"]) @@ -526,12 +536,13 @@ class FastMask(unittest.TestCase): POST3 = {"w64_lc12/l_post_tf_p12_fast3"} PROJECT = {"l_project_gather_fast", "l_dec_project_fast"} ENC = {"l_swin_block_c32_enc_lin_nc_fast"} - ENC_W2 = {"l_swin_block_c32_enc_lin_w2_fast"} + ENC_W2 = {"l_swin_block_c32_enc_lin_w2p_fast"} ENC_W2T = {"l_swin_block_c32_enc_lin_w2t_fast"} - DEC_W2 = {"l_swin_block_c32_dec_coef12_add_w2_fast"} + DEC_W2 = {"l_swin_block_c32_dec_coef12_add_w2p_fast"} DEC_W2T = {"l_swin_block_c32_dec_coef12_add_w2t_fast"} MID = {"swin_block_c64_nc_fast", "swin_block_c64_add_ex_nc_fast"} - DEFAULT = POST3 | PROJECT | ENC_W2 | DEC_W2 | MID + C96 = {"swin_block_c96_add_ex_nc_fast", "swin_block_c96_pm_rev_nc_fast"} + DEFAULT = POST | PROJECT | ENC_W2 | DEC_W2 | MID | C96 def launched(self, mask, exe, **kw): t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, exe=exe, env={"WG_L_FAST_MASK": str(mask)}, @@ -543,7 +554,8 @@ def launched(self, mask, exe, **kw): def test_developer_mask(self): exe = dev_exe() - for mask, want in ((DEFAULT_MASK, self.DEFAULT), (8191, self.DEFAULT), (127, self.POST | self.PROJECT | self.ENC | self.MID), + for mask, want in ((DEFAULT_MASK, self.DEFAULT), (ALL_MASK, (self.DEFAULT - self.POST) | self.POST3), + (127, self.POST | self.PROJECT | self.ENC | self.MID), (8192, self.C96), (2048, set()), (0, set()), (1, self.POST), (1 | 256, self.POST3), (256, set()), (2, self.PROJECT), (4, self.ENC), (4 | 512, self.ENC_W2T), (512 | 4096, self.ENC_W2), (1024, self.DEC_W2T), (1024 | 4096, self.DEC_W2), (4096, set()), (8, self.MID), (16 | 64 | 128, set())): diff --git a/clean/l/tests/test_l_fast_numerics.py b/clean/l/tests/test_l_fast_numerics.py index 74770ac0..4271fb45 100644 --- a/clean/l/tests/test_l_fast_numerics.py +++ b/clean/l/tests/test_l_fast_numerics.py @@ -13,17 +13,20 @@ * the MLP GELU forms (the arithmetic chain of the M-form kernels and the plain tanh form) against the erf GELU; * the FP32 accumulation of the projections' K blocks against the stepwise FP16-rounded sum; * the centred 3 x 3 gather of l_post_tf_p12[_pf]_fast3 (LP_WIN3) against the 4 x 4 window, by kernel width; - * the two-windows-per-wave Swin blocks (l_swin_c32_fast.hlsl): quick GELU x / (1 + 2^(-2.53 x)) against the model's GELU - (and its FP8 codes), the softmax without the maximum against the max-subtracted one, and the coefficient store in FP32 + * the two-windows-per-wave Swin blocks (l_swin_c32_fast.hlsl, also the c64 / c96 twins): the clamped-cubic GELU + (x + |x| min(P(|x|), 1)) / 2 against the model's GELU (and its FP8 codes, the doubled residual accumulator), the softmax + without the maximum against the max-subtracted one, and the coefficient store in FP32 (tanh as 1 - 2 / (2^(2 t log2 e) + 1), no RN16 points, the truncating FP16 pack with the kRn fold) against l_coef_px.hlsli's arithmetic. Numbers are printed with -v; the bounds are the ones the fast route is gated on (tone-mapped PSNR >= 48 dB per choice). """ import math +import os import unittest import numpy as np +KERNELS = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "dx12", "kernels") f32 = np.float32 f16 = np.float16 @@ -268,44 +271,84 @@ def fp8_e4m3(x): return np.sign(x) * np.round(np.abs(x) / step) * step -class QuickGelu(unittest.TestCase): - K = from_bits(0xc021eb85) # -2.53 (l_swin_c32_fast.hlsl kLfQg) +class PolyGelu(unittest.TestCase): + """The clamped-cubic GELU of l_swin_c32_fast.hlsl (LF_GELU 1: the "_w2p_fast" width-32 blocks, the c64 / c96 twins): + 2 GELU(x) = x + |x| min(P(|x|), 1), P(t) = c0 + c1 t + c2 t^2 + c3 t^3, in the kernel's float32 operations (|x| by an + AND, three fmas, the min, one fma; the halving is the doubled residual accumulator's, exact).""" + C = (0xbd6c7ea1, 0x3f878bed, 0xbeb6e5c7, 0x3d25ab15) # kLfP0 ... kLfP3 + K_QUICK = from_bits(0xc021eb85) # 2B-3's quick GELU constant, for comparison - def quick(self, x): + def setUp(self): + self.c = [from_bits(v) for v in self.C] + + def g2(self, x): + """2 GELU(x) as the kernel computes it (float32, fused multiply-adds).""" x = np.asarray(x, dtype=f32) - return x * (f32(1.0) / (f32(1.0) + np.exp2(x * self.K))) + t = np.abs(x) + c0, c1, c2, c3 = (np.float64(v) for v in self.c) + fma = lambda a, b, c: (np.asarray(a, np.float64) * np.asarray(b, np.float64) + c).astype(f32) + p = fma(c3, t, c2) + p = fma(p, t, c1) + p = np.minimum(fma(p, t, c0), f32(1.0)) + return fma(t, p, x) + + def poly(self, x): + return self.g2(x).astype(np.float64) * 0.5 + + def test_constants_are_the_kernels(self): + src = open(os.path.join(KERNELS, "l_swin_c32_fast.hlsl"), encoding="utf-8").read() + for i, v in enumerate(self.C): + self.assertIn("kLfP%d = asfloat(0x%08xu)" % (i, v), src) def test_error_bounds(self): x = np.linspace(-12, 12, 2400001, dtype=f32) - err = np.abs(self.quick(x).astype(np.float64) - gelu_chain(x)) + err = np.abs(self.poly(x) - gelu_chain(x)) rng = np.random.default_rng(11) xs = rng.normal(0, 1.5, 2000000).astype(f32) - rms = np.sqrt(np.mean((self.quick(xs).astype(np.float64) - gelu_chain(xs)) ** 2)) - # the plain 1.702 constant for comparison: the fitted one has the smaller maximum and RMS - k0 = f32(-1.702 * math.log2(math.e)) - q0 = xs * (f32(1.0) / (f32(1.0) + np.exp2(xs * k0))) - rms0 = np.sqrt(np.mean((q0.astype(np.float64) - gelu_chain(xs)) ** 2)) - print("quick GELU (k = 2.53): max abs err %.4f, RMS %.4f on N(0, 1.5) (k = 1.702 log2 e: RMS %.4f)" % - (err.max(), rms, rms0)) - self.assertLess(err.max(), 0.016) - self.assertLess(rms, 0.0095) - self.assertLess(rms, rms0) - with np.errstate(over="ignore"): - ends = self.quick(np.array([-1e30, 1e30], dtype=f32)) - self.assertEqual(float(abs(ends[0])), 0.0) - self.assertEqual(float(ends[1]), float(f32(1e30))) + rms = np.sqrt(np.mean((self.poly(xs) - gelu_chain(xs)) ** 2)) + quick = xs * (f32(1.0) / (f32(1.0) + np.exp2(xs * self.K_QUICK))) + rms_q = np.sqrt(np.mean((quick.astype(np.float64) - gelu_chain(xs)) ** 2)) + print("clamped-cubic GELU: max abs err %.5f, RMS %.5f on N(0, 1.5) (quick GELU RMS %.4f)" % (err.max(), rms, rms_q)) + self.assertLess(err.max(), 0.0021) + self.assertLess(rms, 0.0015) + self.assertLess(rms * 5, rms_q) + # far out: GELU(x) = x for large x, 0 for large negative x (P stays >= 1, the min keeps it at 1) + big = np.array([3.5, 10.0, 200.0, -3.5, -10.0, -200.0], dtype=f32) + np.testing.assert_array_equal(self.g2(big), np.array([7.0, 20.0, 400.0, 0.0, 0.0, 0.0], dtype=f32)) + + def test_polynomial_shape(self): + # P' > 0 everywhere (no real root of c1 + 2 c2 t + 3 c3 t^2): P crosses 1 once (the knee) and never comes back; + # P < 0 only below t = 0.06, where the missing lower clamp costs less than the bound above + c0, c1, c2, c3 = (float(v) for v in self.c) + self.assertLess(4 * c2 * c2 - 12 * c1 * c3, 0.0) + t = np.linspace(0, 1000, 2000001) + p = ((c3 * t + c2) * t + c1) * t + c0 + knee = t[np.argmax(p >= 1.0)] + print("knee t = %.3f, P(0) = %.4f" % (knee, c0)) + self.assertTrue(3.0 < knee < 3.6) + self.assertTrue(np.all(p[t >= knee] >= 1.0)) + self.assertLess(t[np.argmax(p >= 0.0)], 0.06) + + def test_doubled_accumulator_is_exact(self): + # q8(2 g) = 2 q8(g) for every g whose FP8 code is normal on both sides: the W2 products accumulate onto 2 x the + # residual and the output halves it, both exact power-of-two scalings + rng = np.random.default_rng(14) + g = rng.normal(0, 2.0, 200000) + g = g[(np.abs(g) >= 2.0 ** -6) & (np.abs(g) <= 200.0)] + np.testing.assert_array_equal(fp8_e4m3(2 * g), 2 * fp8_e4m3(g)) def test_fp8_codes(self): # the W2 input is the FP8 code of GELU(h): the share of codes that change, and the mean signed error rng = np.random.default_rng(12) h = rng.normal(0, 1.5, 1000000).astype(f32) - a, b = fp8_e4m3(gelu_chain(h)), fp8_e4m3(self.quick(h)) + a = fp8_e4m3(gelu_chain(h)) + b = fp8_e4m3(self.g2(h)) * 0.5 # the kernel packs 2 GELU same = np.mean(a == b) bias = np.mean(b - a) - print("quick GELU FP8 codes: %.1f%% unchanged, 99%% of the changes within %.4f absolute, mean signed error %.2e " - "(mean |GELU| %.3f)" % (100 * same, np.quantile(np.abs(a - b)[a != b], 0.99), bias, np.mean(np.abs(a)))) - self.assertGreater(same, 0.55) - self.assertLess(abs(bias), 0.004) + print("clamped-cubic GELU FP8 codes: %.1f%% unchanged, mean signed error %.2e (mean |GELU| %.3f)" % + (100 * same, bias, np.mean(np.abs(a)))) + self.assertGreater(same, 0.84) + self.assertLess(abs(bias), 0.0005) class SoftmaxNoMax(unittest.TestCase): diff --git a/clean/runtime/runtime.cpp b/clean/runtime/runtime.cpp index 1da4fadc..a4a0fd09 100644 --- a/clean/runtime/runtime.cpp +++ b/clean/runtime/runtime.cpp @@ -336,33 +336,39 @@ struct Runtime { // The levers of l_mode=fast (native D3D12): kernels of the build launched in place of a base kernel with the same grid, // block and arguments (l_fast_alt: base name -> the kernel launched). A "_fast" twin replaces when its // group's bit is set (l_fast_bit); the alternatives of kLFastAlts (in their order, the first one in the build whose bits - // are all set) come before it. All on by default but bit 128; a developer build reads the selection from WG_L_FAST_MASK - // (an A/B of each lever, below). + // are all set) come before it. All on by default but bits 128, 256 and 2048; a developer build reads the selection from + // WG_L_FAST_MASK (an A/B of each lever, below). // 1 l_post_tf_p12[_pf] the true-fusion output kernel without the bit-exactness guards (l_post_tf_fast.hlsl) // 2 l_project_gather, l_dec_project the K blocks accumulated in FP32 and rounded once, in the FP8 pack // 4 the width-32 Swin blocks' "_fast" twins (the encoder block with the linears, its prologue in FP32) - // 8 the middle Swin blocks' "_fast" twins (swin_block_c64_nc_fast, swin_block_c64_add_ex_nc_fast when the build has - // them: l_swin_c64_fast.hlsl; c96 and the bottleneck: no twin) + // 8 the width-64 Swin blocks' "_fast" twins (swin_block_c64_nc_fast, swin_block_c64_add_ex_nc_fast when the build has + // them: l_swin_c64_fast.hlsl, two windows per wave with the clamped-cubic GELU) // 16 the weaker history candidate as a 4-tap bilinear (inside the kernel of lever 1: pitch_bytes bit 0) // 32 the q20 input encoder (no twin yet) // 64 a weaker history candidate with the first one's motion (within 0.01 render pixel) is not read twice (lever 1: bit 1) // 128 a weaker history candidate of weight below 0.05 (the hybrid route: 1 / 255) is dropped (lever 1: bit 2; off by // default: a quality / speed trade-off for the A/B) // 256 with lever 1: the centred 3 x 3 gather (l_post_tf_p12[_pf]_fast3) for every frame whose step footprint fits its - // staging (l_tf3_supported; a frame that does not runs the 4 x 4 twin, which the build must then have) + // staging (l_tf3_supported; a frame that does not runs the 4 x 4 twin, which the build must then have); off by + // default: RX 9070 XT (2B-3) 38.7 dB / SSIM 0.955 HDR against the hybrid route (4 x 4: 53.2 dB / 0.998) // 512 the encoder block with the linears: two windows per wave (l_swin_block_c32_enc_lin_w2[t]_fast, l_swin_c32_fast.hlsl) // in place of lever 4's twin // 1024 the decoder block with the coefficient store: two windows per wave (l_swin_block_c32_dec_coef12_add_w2[t]_fast) // 2048 (reserved: the bottleneck's fast twin; none built) - // 4096 the quick GELU in the kernels of 512 / 1024 ("_w2_fast"); off: their table form "_w2t_fast" (the model's GELU bytes) - static constexpr unsigned kLFastAll = 8191u, kLFastDefault = 8191u & ~128u & ~2048u; + // 4096 the clamped-cubic GELU in the kernels of 512 / 1024 ("_w2p_fast": no table load, no exponential); off: their + // table form "_w2t_fast" (the model's GELU bytes) + // 8192 the width-96 Swin blocks' "_fast" twins (swin_block_c96_pm_rev_nc_fast, swin_block_c96_add_ex_nc_fast: + // l_swin_c96_fast.hlsl, the clamped-cubic GELU and the softmax without the maximum, no groupshared table) + static constexpr unsigned kLFastAll = 16383u, kLFastDefault = 16383u & ~128u & ~256u & ~2048u; unsigned l_fast_mask = kLFastDefault; std::map l_fast_alt; static unsigned l_fast_bit(const std::string& n) { if (n.compare(0, 22, "w64_lc12/l_post_tf_p12") == 0) return 1u; if (n == "l_project_gather" || n == "l_dec_project") return 2u; if (n.compare(0, 17, "l_swin_block_c32_") == 0) return 4u; - if (n.compare(0, 11, "swin_block_") == 0 || n.compare(0, 16, "bneck/swin_bneck") == 0) return 8u; + if (n.compare(0, 14, "swin_block_c96") == 0) return 8192u; + if (n.compare(0, 16, "bneck/swin_bneck") == 0) return 2048u; + if (n.compare(0, 11, "swin_block_") == 0) return 8u; if (n.compare(0, 20, "lev/input_encoder_q2") == 0) return 32u; return 0u; } @@ -370,9 +376,9 @@ struct Runtime { static constexpr LFastAlt kLFastAlts[] = { {"w64_lc12/l_post_tf_p12", "w64_lc12/l_post_tf_p12_fast3", 1u | 256u}, {"w64_lc12/l_post_tf_p12_pf", "w64_lc12/l_post_tf_p12_pf_fast3", 1u | 256u}, - {"l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2_fast", 512u | 4096u}, + {"l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2p_fast", 512u | 4096u}, {"l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2t_fast", 512u}, - {"l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2_fast", 1024u | 4096u}, + {"l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2p_fast", 1024u | 4096u}, {"l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2t_fast", 1024u}, }; // the 4 x 4 twin of a selected 3 x 3 post (l_fast_alt's value "_fast3" -> "_fast"): the frames whose diff --git a/clean/tests/runtime_frame_trace.cpp b/clean/tests/runtime_frame_trace.cpp index dbf04320..7f5e7e0e 100644 --- a/clean/tests/runtime_frame_trace.cpp +++ b/clean/tests/runtime_frame_trace.cpp @@ -128,12 +128,12 @@ const char* kinds_of(const std::string& kernel) { const size_t slash = kernel.find('/'); std::string k = slash == std::string::npos ? kernel : kernel.substr(slash + 1); // a fast-mode kernel (l_mode=fast, launched in place of its base kernel) has the base kernel's arguments: - // "_fast", "_fast3" -> ; "_w2_fast", "_w2t_fast" -> "_nc" (build_dx12.py fast_base) + // "_fast", "_fast3" -> ; "_w2p_fast", "_w2t_fast" -> "_nc" (build_dx12.py fast_base) const auto ends = [&](const char* suf) { const size_t n = std::strlen(suf); return k.size() > n && k.compare(k.size() - n, n, suf) == 0; }; - if (ends("_w2_fast")) k.replace(k.size() - 8, 8, "_nc"); + if (ends("_w2p_fast")) k.replace(k.size() - 9, 9, "_nc"); else if (ends("_w2t_fast")) k.replace(k.size() - 9, 9, "_nc"); else if (ends("_fast3")) k.resize(k.size() - 6); else if (ends("_fast")) k.resize(k.size() - 5); From 3fb797bc29981c4f4d456ba9d442cec9309239b7 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:31:26 -0500 Subject: [PATCH 5/5] Model L (D3D12): l_mode=fast default 9847, one W2 tile in the decoder block's coefficient store, 8 KB width-32 staging; post options 16384 / 32768 (off) - l_swin_c32_fast.hlsl: the coefficient store reads channels 0..12 only, so the decoder block's W2 runs one output tile (LF_W2_ONE: tile 0 remapped to channels 0..15 by a lane exchange of tile 1's rows; the same products and the same accumulation order per stored channel): 128 -> 112 WMMAs, _w2t_fast 188 -> 165 VGPRs. The width-32 twins stage 2 x 4 KB of MLP weights (SW_HPU=4: 8 KB of LDS instead of 16 KB). - l_post_tf_fast.hlsl: history / A8 loads with their 8-byte alignment stated; option bit 3 (lever 16384) gathers the 4 x 4 window without its four corner taps, option bit 4 (lever 32768) blends two history candidates in the encoded domain and decodes once. Both off by default: 16384 measured 43.2 dB / SSIM 0.982 HDR 1440p Q and 40.5 dB 640 x 360 HDR against the hybrid route (below the gate); 32768 showed no gain. - runtime.cpp: the default selection is 9847 (levers 8 and 4096 off: neutral and +20 us in the A/B); kLFastAll 65535. - Tests and SPEED.md follow the new default. RX 9070 XT, 1440p Q, 6-round ABBA (median of rounds): hybrid 4.3805 / 4.4146 / 4.4160 ms, l_mode=fast (release) 3.2456 / 3.2421 / 3.2419 ms at pi 1.0 / 1.25 / 2.0. l_mode unset and l_mode=hybrid: 0 of 232 buffers differ from 8c07199 (1440p Q HDR / LDR, 640 x 360 HDR), no NaN / Inf. l_mode=fast against hybrid: tone-mapped PSNR >= 49.9 dB steady, SSIM >= 0.9976, no NaN / Inf in the output or the history; the release DLL is bit-identical to the developer build at mask 9847. --- clean/dx12/kernels/l_post_tf_fast.hlsl | 72 +++++++++++++------ clean/dx12/kernels/l_swin_c32_fast.hlsl | 37 ++++++++-- clean/dx12/vgpr_limits.json | 2 +- clean/l/SPEED.md | 9 ++- .../runtime/tests/test_l_runtime_fast_mode.py | 21 +++--- clean/runtime/runtime.cpp | 11 ++- 6 files changed, 109 insertions(+), 43 deletions(-) diff --git a/clean/dx12/kernels/l_post_tf_fast.hlsl b/clean/dx12/kernels/l_post_tf_fast.hlsl index 953d3417..584f7b01 100644 --- a/clean/dx12/kernels/l_post_tf_fast.hlsl +++ b/clean/dx12/kernels/l_post_tf_fast.hlsl @@ -106,6 +106,8 @@ static bool g_secbl; // bit 0: the weaker history candidate (n = 1, weight < 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); } @@ -122,14 +124,19 @@ float rn16(float x) { return asfloat(asuint(x) + 0x1000u); } 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 = wg_ld4f(color, ui * 16u); - r.d = wg_ld64(A, ui * 8u); + 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; } @@ -191,13 +198,14 @@ void tap_acc(inout LGather g, uint t[kTexDw], half w) } } // 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) + 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 = 0; jj < kLWin; ++jj) { + [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]; @@ -269,8 +277,8 @@ float3 history_cr(float qx, float qy) [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 = 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); + 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)))); @@ -284,12 +292,12 @@ float3 history_cr(float qx, float qy) 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(wg_mem.Load2(ro[0] + co[2])), wx.y * h3(wg_mem.Load2(ro[0] + co[1]))); - 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])), wx.x * h3(wg_mem.Load2(ro[1] + co[0]))))); - 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])), wx.x * h3(wg_mem.Load2(ro[2] + co[0]))))); - const float3 r3 = mad(wx.z, h3(wg_mem.Load2(ro[3] + co[2])), wx.y * h3(wg_mem.Load2(ro[3] + co[1]))); + 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); @@ -305,8 +313,8 @@ float3 history_bilinear(float qx, float qy) 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(wg_mem.Load2(ra + cb)) - h3(wg_mem.Load2(ra + ca)), h3(wg_mem.Load2(ra + ca))); - const float3 t1 = mad(fx, h3(wg_mem.Load2(rb + cb)) - h3(wg_mem.Load2(rb + ca)), h3(wg_mem.Load2(rb + ca))); + 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); } @@ -349,6 +357,8 @@ void l_post_core(LGather g, int x, int y, int fx, int fy, float mx[3], float my[ 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) { @@ -357,9 +367,10 @@ void l_post_core(LGather g, int x, int y, int fx, int fy, float mx[3], float my[ 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); - L[n][0] = dec_hist(h.x); - L[n][1] = dec_hist(h.y); - L[n][2] = dec_hist(h.z); + 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 @@ -371,10 +382,18 @@ void l_post_core(LGather g, int x, int y, int fx, int fy, float mx[3], float my[ } } float Hl[3], Cl[3]; - [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]; - Cl[i] = dec_cur(inv * (float)g.F[i]); + 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); @@ -472,6 +491,8 @@ WG_KERNEL(l_post_tf_p12_fast) 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 @@ -584,8 +605,15 @@ WG_KERNEL(l_post_tf_p12_fast) // 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, v0, v1, vv0, vv1, g0, g1); + [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}; diff --git a/clean/dx12/kernels/l_swin_c32_fast.hlsl b/clean/dx12/kernels/l_swin_c32_fast.hlsl index 305537cd..9d825067 100644 --- a/clean/dx12/kernels/l_swin_c32_fast.hlsl +++ b/clean/dx12/kernels/l_swin_c32_fast.hlsl @@ -37,10 +37,10 @@ // 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=8,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=8,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=8,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=8,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 +// @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 @@ -74,6 +74,10 @@ #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 @@ -399,6 +403,14 @@ WG_KERNEL(LF_NAME) } } +#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; @@ -431,9 +443,18 @@ WG_KERNEL(LF_NAME) [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) { @@ -449,9 +470,17 @@ WG_KERNEL(LF_NAME) 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 diff --git a/clean/dx12/vgpr_limits.json b/clean/dx12/vgpr_limits.json index 329373ea..45b4be43 100644 --- a/clean/dx12/vgpr_limits.json +++ b/clean/dx12/vgpr_limits.json @@ -1,5 +1,5 @@ { - "_doc": "build_dx12.py VGPR check: the RGA (gfx1201) USED_VGPRs bound of every Swin / bottleneck kernel (a name with a swin_ part) and Model L's fused post (w64_lc12/l_post_tf_p12[_pf]). Each bound is the largest count that keeps the kernel's present occupancy: VGPR file 1536 per SIMD lane, granule 8, a 256-lane wave32 workgroup = 4 waves on each of a CU's 2 SIMDs, so 2 workgroups per CU need <= 192, 3 need <= 128 (a 128-lane workgroup = 2 waves per SIMD: 4 per CU need <= 192). A kernel over its bound fails the build (a merge or an edit lost a workgroup per CU: swin_block_c96_add_xe_* at 215 VGPRs ran 1 per CU, +38 us per frame at 1440p Q). Model L's fused post (block = 512 lanes, wave64, 26,752 bytes of LDS: 2 workgroups per CU = 8 waves64 per SIMD) is bounded at 96; its fast-mode twins (w64_lc12/l_post_tf_p12[_pf]_fast, 23,040 bytes; _fast3, 21,504 bytes) keep that tier, and the fast-mode Swin twin of the encoder block the bound of its base; the two-windows-per-wave fast kernels (l_swin_c32_fast.hlsl, l_swin_c64_fast.hlsl: 128-lane workgroups with 16 KB of staging, 4 per CU) <= 192. A new Swin / bottleneck kernel needs an entry. WG_DX12_VGPR_CHECK=0 skips the check.", + "_doc": "build_dx12.py VGPR check: the RGA (gfx1201) USED_VGPRs bound of every Swin / bottleneck kernel (a name with a swin_ part) and Model L's fused post (w64_lc12/l_post_tf_p12[_pf]). Each bound is the largest count that keeps the kernel's present occupancy: VGPR file 1536 per SIMD lane, granule 8, a 256-lane wave32 workgroup = 4 waves on each of a CU's 2 SIMDs, so 2 workgroups per CU need <= 192, 3 need <= 128 (a 128-lane workgroup = 2 waves per SIMD: 4 per CU need <= 192). A kernel over its bound fails the build (a merge or an edit lost a workgroup per CU: swin_block_c96_add_xe_* at 215 VGPRs ran 1 per CU, +38 us per frame at 1440p Q). Model L's fused post (block = 512 lanes, wave64, 26,752 bytes of LDS: 2 workgroups per CU = 8 waves64 per SIMD) is bounded at 96; its fast-mode twins (w64_lc12/l_post_tf_p12[_pf]_fast, 23,040 bytes; _fast3, 21,504 bytes) keep that tier, and the fast-mode Swin twin of the encoder block the bound of its base; the two-windows-per-wave fast kernels (l_swin_c32_fast.hlsl: 128-lane workgroups with 8 KB of staging, SW_HPU=4; l_swin_c64_fast.hlsl: 16 KB, 4 per CU) <= 192. A new Swin / bottleneck kernel needs an entry. WG_DX12_VGPR_CHECK=0 skips the check.", "l_swin_block_c32_nc": 96, "l_swin_block_c32_enc_nc": 96, "l_swin_block_c32_enc_lin_nc": 96, diff --git a/clean/l/SPEED.md b/clean/l/SPEED.md index 5e34b645..f7da4d2f 100644 --- a/clean/l/SPEED.md +++ b/clean/l/SPEED.md @@ -106,14 +106,17 @@ kernel). They drop the bit-exactness of the hybrid route where it costs instruct | 8 | `swin_block_c64_nc_fast`, `swin_block_c64_add_ex_nc_fast` | enc1's and dec1's blocks (`l_swin_c64_fast.hlsl`): the two-windows-per-wave body below at C = 64 with the clamped-cubic GELU (no table load, no exponential) and the softmax without the maximum | | 256 | `w64_lc12/l_post_tf_p12[_pf]_fast3` (with lever 1; off by default: RX 9070 XT 38.7 dB / SSIM 0.955 HDR against the hybrid route, the 4 x 4 gather 53.2 dB / 0.998) | the gather over the 3 x 3 render texels centred on each D pixel (`LP_WIN3`; every tap within 1.5 render pixels, each row of a pair with its own centred rows) instead of the 4 x 4 window: 18 taps per row pair instead of 32; staging cap 448 texels, a frame whose step footprint does not fit (`l_tf3_supported`) runs the 4 x 4 twin | | 512 | `l_swin_block_c32_enc_lin_w2p_fast` / `_w2t_fast` | the encoder block with the linears, two windows per wave in 128-lane workgroups (`l_swin_c32_fast.hlsl`, the launch shape of `swin_c64w2.hlsl`): weight fragments, biases and the linears' weights loaded once for both windows, a barrier waits for 4 waves; the softmax without the maximum (the soft cap bounds the exponents to +-11) | -| 1024 | `l_swin_block_c32_dec_coef12_add_w2p_fast` / `_w2t_fast` | the decoder block with the coefficient store, the same two-windows-per-wave body; the coefficient epilogue one pixel per lane (the hh = 1 lanes take the second window's channels by `v_permlanex16`) in FP32 from the block's FP32 output (no FP16 rounding of y2, tanh as `1 - 2 / (2^(2 t log2 e) + 1)`) | +| 1024 | `l_swin_block_c32_dec_coef12_add_w2p_fast` / `_w2t_fast` | the decoder block with the coefficient store, the same two-windows-per-wave body; the coefficient epilogue one pixel per lane (the hh = 1 lanes take the second window's channels by `v_permlanex16`) in FP32 from the block's FP32 output (no FP16 rounding of y2, tanh as `1 - 2 / (2^(2 t log2 e) + 1)`); the store reads channels 0..12 only, so W2 runs one output tile (`LF_W2_ONE`: tile 0 remapped to channels 0..15, its rows 8..15 from tile 1 by a lane exchange; the same products and accumulation order per stored channel; 128 -> 112 WMMAs, `_w2t_fast` 188 -> 165 VGPRs). The width-32 twins stage 2 x 4 KB of MLP weights (`SW_HPU=4`, 8 KB of LDS instead of 16 KB) | | 4096 | (option of 512 / 1024) | the clamped-cubic GELU `(x + abs(x) min(P(abs(x)), 1)) / 2` in the two-windows kernels (`_w2p_fast`: six full-rate operations per value the driver pairs as VOPD, no table load, no exponential; the W2 products accumulate onto twice the residual, so the halving costs nothing per value; max error 0.002, RMS 0.0014 against the model's GELU, 85 % of the FP8 codes unchanged); off: their table form `_w2t_fast` (the model's GELU bytes by the arena table) | | 8192 | `swin_block_c96_pm_rev_nc_fast`, `swin_block_c96_add_ex_nc_fast` | enc2's block with enc1's patch merge and dec2's block with the fused expand (`l_swin_c96_fast.hlsl`): the same body in the base kernels' launch shape (one window per wave), the clamped-cubic GELU (no groupshared table: LDS 26 624 / 28 672 -> 24 576 bytes) and the softmax without the maximum | | 2048 | (reserved) | the bottleneck's fast twin: none built (the persistent bottleneck kernel keeps its base form) | +| 16384 | (option of lever 1, off by default) | the 4 x 4 gather without its four corner taps (12 taps); RX 9070 XT: 43.2 dB / SSIM 0.982 HDR 1440p Q, 40.5 dB 640 x 360 HDR against the hybrid route (fails the gate) for about -20 us | +| 32768 | (option of lever 1, off by default) | two history candidates blended in the encoded domain and decoded once (3 exponentials instead of 6); no measured gain at 1440p Q | A developer build (`dev_diagnostics`) reads the selection of levers from `WG_L_FAST_MASK` (the sum of the lever values -above; the default is 13951 = every lever and option but 128, 256 and 2048: 256 failed the GPU quality gate, 2048 is -reserved for a bottleneck twin that does not exist yet; earlier defaults: 127, then 6015 with 256 and the quick GELU) +above; the default is 9847 = 1 + 2 + 4 + 16 + 32 + 64 + 512 + 1024 + 8192: 256 and 16384 failed the GPU quality gate, 4096 +regressed (+20 us), 8 was neutral, 2048 is reserved for a bottleneck twin that does not exist yet; earlier defaults: 127, +then 6015 with 256 and the quick GELU, then 13951) for an A/B of each; a release build has no such variable. The arithmetic choices are bounded on the CPU by `clean/l/tests/test_l_fast_numerics.py` (the quality gate itself is measured on the GPU against `l_mode=hybrid`: tone-mapped PSNR / SSIM and temporal stability). Lever 256 is the one whose difference depends on the model's kernel widths (CPU bound: 52.9 dB on texel noise at sigma 0.5 render diff --git a/clean/l/runtime/tests/test_l_runtime_fast_mode.py b/clean/l/runtime/tests/test_l_runtime_fast_mode.py index fa9fe757..2ef4b897 100644 --- a/clean/l/runtime/tests/test_l_runtime_fast_mode.py +++ b/clean/l/runtime/tests/test_l_runtime_fast_mode.py @@ -71,8 +71,8 @@ def fast_base(n): ("l_swin_block_c32_enc_lin_nc", "l_swin_block_c32_enc_lin_w2t_fast", 512), ("l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2p_fast", 1024 | 4096), ("l_swin_block_c32_dec_coef12_add_nc", "l_swin_block_c32_dec_coef12_add_w2t_fast", 1024)) -ALL_MASK = 16383 -DEFAULT_MASK = ALL_MASK & ~128 & ~256 & ~2048 +ALL_MASK = 65535 +DEFAULT_MASK = 16383 & ~8 & ~128 & ~256 & ~2048 & ~4096 # 9847 def lever_bit(base): @@ -459,12 +459,12 @@ def test_twins_declared(self): for k in t: self.assertIn(fast_base(k), [x for x, _ in F.full_ports()], k) # every fast kernel replaces a base kernel # the default selection: the 4 x 4 post (lever 256, the 3 x 3 gather, is off), the two-windows-per-wave width-32 - # blocks with the clamped-cubic GELU, the c64 twins, the c96 twins of the build + # blocks with the table GELU (lever 4096 is off), no c64 twins (lever 8 is off), the c96 twins of the build alt = selection()[0] self.assertEqual(alt["w64_lc12/l_post_tf_p12"], "w64_lc12/l_post_tf_p12_fast") - self.assertEqual(alt[ENC_LIN], "l_swin_block_c32_enc_lin_w2p_fast") - self.assertEqual(alt[FOLD_ADD], "l_swin_block_c32_dec_coef12_add_w2p_fast") - self.assertEqual(alt["swin_block_c64_nc"], "swin_block_c64_nc_fast") + self.assertEqual(alt[ENC_LIN], "l_swin_block_c32_enc_lin_w2t_fast") + self.assertEqual(alt[FOLD_ADD], "l_swin_block_c32_dec_coef12_add_w2t_fast") + self.assertNotIn("swin_block_c64_nc", alt) self.assertEqual(alt["swin_block_c96_add_ex_nc"], "swin_block_c96_add_ex_nc_fast") self.assertEqual(alt["swin_block_c96_pm_rev_nc"], "swin_block_c96_pm_rev_nc_fast") self.assertNotIn("bneck/swin_bneck6_mb_nc", alt) # (lever 2048: no bottleneck twin) @@ -477,7 +477,7 @@ def test_launched_in_place_of_the_base_kernel(self): self.assertEqual(shape(a), shape(b)) # the same launches with the same arguments, twins or not alt = selection()[0] for f in a.frames: - for k in self.LEVERS + (FOLD_ADD, "swin_block_c64_nc", "swin_block_c64_add_ex_nc"): + for k in self.LEVERS + (FOLD_ADD, "swin_block_c96_pm_rev_nc", "swin_block_c96_add_ex_nc"): self.assertIn(alt[k], f["fast"], f["fast"]) for f in b.frames: self.assertEqual(f["fast"], []) @@ -542,7 +542,8 @@ class FastMask(unittest.TestCase): DEC_W2T = {"l_swin_block_c32_dec_coef12_add_w2t_fast"} MID = {"swin_block_c64_nc_fast", "swin_block_c64_add_ex_nc_fast"} C96 = {"swin_block_c96_add_ex_nc_fast", "swin_block_c96_pm_rev_nc_fast"} - DEFAULT = POST | PROJECT | ENC_W2 | DEC_W2 | MID | C96 + DEFAULT = POST | PROJECT | ENC_W2T | DEC_W2T | C96 + ALL = POST3 | PROJECT | ENC_W2 | DEC_W2 | MID | C96 def launched(self, mask, exe, **kw): t = FastTrace(l_run("model=L,l_mode=fast", frames=2, tf_default=True, exe=exe, env={"WG_L_FAST_MASK": str(mask)}, @@ -554,11 +555,11 @@ def launched(self, mask, exe, **kw): def test_developer_mask(self): exe = dev_exe() - for mask, want in ((DEFAULT_MASK, self.DEFAULT), (ALL_MASK, (self.DEFAULT - self.POST) | self.POST3), + for mask, want in ((DEFAULT_MASK, self.DEFAULT), (ALL_MASK, self.ALL), (127, self.POST | self.PROJECT | self.ENC | self.MID), (8192, self.C96), (2048, set()), (0, set()), (1, self.POST), (1 | 256, self.POST3), (256, set()), (2, self.PROJECT), (4, self.ENC), (4 | 512, self.ENC_W2T), (512 | 4096, self.ENC_W2), (1024, self.DEC_W2T), (1024 | 4096, self.DEC_W2), - (4096, set()), (8, self.MID), (16 | 64 | 128, set())): + (4096, set()), (8, self.MID), (16 | 64 | 128, set()), (16384 | 32768, set())): with self.subTest(mask=mask): got, t = self.launched(mask, exe) self.assertEqual(got, want) diff --git a/clean/runtime/runtime.cpp b/clean/runtime/runtime.cpp index a4a0fd09..6632ceec 100644 --- a/clean/runtime/runtime.cpp +++ b/clean/runtime/runtime.cpp @@ -336,7 +336,7 @@ struct Runtime { // The levers of l_mode=fast (native D3D12): kernels of the build launched in place of a base kernel with the same grid, // block and arguments (l_fast_alt: base name -> the kernel launched). A "_fast" twin replaces when its // group's bit is set (l_fast_bit); the alternatives of kLFastAlts (in their order, the first one in the build whose bits - // are all set) come before it. All on by default but bits 128, 256 and 2048; a developer build reads the selection from + // are all set) come before it. All on by default but bits 8, 128, 256, 2048, 4096, 16384 and 32768; a developer build reads the selection from // WG_L_FAST_MASK (an A/B of each lever, below). // 1 l_post_tf_p12[_pf] the true-fusion output kernel without the bit-exactness guards (l_post_tf_fast.hlsl) // 2 l_project_gather, l_dec_project the K blocks accumulated in FP32 and rounded once, in the FP8 pack @@ -359,7 +359,11 @@ struct Runtime { // table form "_w2t_fast" (the model's GELU bytes) // 8192 the width-96 Swin blocks' "_fast" twins (swin_block_c96_pm_rev_nc_fast, swin_block_c96_add_ex_nc_fast: // l_swin_c96_fast.hlsl, the clamped-cubic GELU and the softmax without the maximum, no groupshared table) - static constexpr unsigned kLFastAll = 16383u, kLFastDefault = 16383u & ~128u & ~256u & ~2048u; + // 16384 with lever 1: the 4 x 4 gather without its four corner taps (12 taps; lever 1: bit 3); off by default: RX 9070 XT + // 43.2 dB / SSIM 0.982 HDR 1440p Q, 40.5 dB 640 x 360 HDR against the hybrid route + // 32768 with lever 1: two history candidates blended in the encoded domain and decoded once (lever 1: bit 4); off by + // default: no measured gain at 1440p Q + static constexpr unsigned kLFastAll = 65535u, kLFastDefault = 16383u & ~8u & ~128u & ~256u & ~2048u & ~4096u; // 9847 unsigned l_fast_mask = kLFastDefault; std::map l_fast_alt; static unsigned l_fast_bit(const std::string& n) { @@ -3409,7 +3413,8 @@ struct Runtime { post_last = l_fold_pidiv ? "w64_lc12/l_post_tf_p12_pf" : "w64_lc12/l_post_tf_p12"; std::string post_k = post_last; if (l_fast_alt.count(post_last)) { - hpitch = ((l_fast_mask & 16u) ? 1 : 0) | ((l_fast_mask & 64u) ? 2 : 0) | ((l_fast_mask & 128u) ? 4 : 0); // the fast kernel's pitch_bytes is its option word + hpitch = ((l_fast_mask & 16u) ? 1 : 0) | ((l_fast_mask & 64u) ? 2 : 0) | ((l_fast_mask & 128u) ? 4 : 0) | + ((l_fast_mask & 16384u) ? 8 : 0) | ((l_fast_mask & 32768u) ? 16 : 0); // the fast kernel's pitch_bytes is its option word if (l_is_post3(l_fast_alt[post_last]) && !l_tf3_supported(rw, rh, dw, dh)) post_k = post_last + "_fast"; // the 4 x 4 twin } filter_last = "fused";