torch.compile's tracing state is global: running the compiled CAS while FXAA was still being compiled on its thread ended the engine on the GPU VM. One lock now covers each compile, a compiled filter runs only when it can take it at once (else op by op for that frame), and a compiled filter that fails falls back to op by op for good.
411 lines
19 KiB
Python
411 lines
19 KiB
Python
"""Anti-aliasing and sharpening of the game's picture (settings "aa"), at the game's own size, before the upscaler.
|
|
|
|
Three clean-room filters, written for Summit from the published ideas (no code from the reference implementations):
|
|
|
|
- "fxaa": FXAA-style. Per pixel: the local luma contrast decides whether it is on an edge; the edge's direction
|
|
(horizontal or vertical) and its side come from luma differences; a short search along the edge finds how far its
|
|
ends are, and the pixel is blended towards its neighbour across the edge by how near it is to an end (plus a
|
|
sub-pixel term for single-pixel detail).
|
|
- "smaa": SMAA/MLAA-style morphological AA. Luma edges between pixels (with SMAA's local contrast adaptation), each
|
|
run of edge pixels measured to its ends, the ends' shapes read from the crossing edges (L, Z and U shapes), and each
|
|
pixel blended with its neighbour by the area under the line that joins the ends. Not Jimenez' SMAA: no lookup
|
|
textures, no diagonal or corner passes.
|
|
- "cas": contrast-adaptive sharpening (the idea of AMD's CAS): a sharpening kernel whose strength falls where the
|
|
neighbourhood is already near black or white, so edges don't ring. Not anti-aliasing, offered next to it because
|
|
it is the usual partner of a softening AA.
|
|
|
|
One implementation for both paths: frames on the GPU (torch tensors, what the live pipeline has) and numpy arrays
|
|
(the CPU fallback: tests, stills, devtools/compare_shot.py). The few array operations that differ are in _Ops.
|
|
Frames are HxWx3 uint8, BGR (as everywhere in the engine); the result has the same type, device and shape.
|
|
|
|
On an NVIDIA card each filter is also compiled (torch.compile, with Triton) into a few fused kernels, about 4 to 8
|
|
times faster than running it op by op. That takes 10 to 15 s the first time (Triton keeps the result on disk for
|
|
later sessions), so it happens on a thread of its own: the filter works at once, op by op, and moves to the compiled
|
|
version when that is ready (the log says so). SUMMIT_AA_COMPILE=0 turns this off.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import threading
|
|
|
|
import numpy as np
|
|
|
|
MODES = ("off", "fxaa", "smaa", "cas")
|
|
NAMES = {"off": "Off", "fxaa": "FXAA", "smaa": "SMAA-style", "cas": "CAS sharpen"}
|
|
|
|
# FXAA's thresholds (the "quality" preset's usual values)
|
|
FXAA_EDGE = 0.125 # local contrast needed, as a share of the brightest of the five pixels
|
|
FXAA_EDGE_MIN = 0.0312 # ... and at least this much (dark areas)
|
|
FXAA_SUBPIX = 0.75 # how much single-pixel detail is softened
|
|
FXAA_STEPS = (1, 2, 3, 4, 6, 8, 12) # how far the search along an edge looks, in pixels
|
|
FXAA_GUESS = 16.0 # an edge's end not found: taken to be this far
|
|
SMAA_THRESHOLD = 0.1 # luma step that counts as an edge
|
|
SMAA_ADAPT = 2.0 # an edge must be at least 1/this of its strongest neighbouring edge (local contrast adaptation)
|
|
CAS_SHARPNESS = 0.5 # 0..1
|
|
|
|
|
|
def is_tensor(x) -> bool:
|
|
return type(x).__module__.startswith("torch")
|
|
|
|
|
|
class _Ops:
|
|
"""numpy or torch, whichever the frame is: the handful of calls that are spelled differently."""
|
|
|
|
def __init__(self, like) -> None:
|
|
self.t = is_tensor(like)
|
|
if self.t:
|
|
import torch
|
|
self.torch, self.dev = torch, like.device
|
|
self._idx: dict = {}
|
|
|
|
def f32(self, a):
|
|
return a.float() / 255.0 if self.t else a.astype(np.float32) / 255.0
|
|
|
|
def u8(self, a, like):
|
|
if self.t:
|
|
return (a.clamp(0.0, 1.0) * 255.0 + 0.5).to(self.torch.uint8)
|
|
return (np.clip(a, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8)
|
|
|
|
def arange(self, n: int):
|
|
return self.torch.arange(n, device=self.dev) if self.t else np.arange(n)
|
|
|
|
def index(self, n: int, d: int):
|
|
"""Indices 0..n-1 moved by d, held at the ends (the edge pixel repeats)."""
|
|
k = (n, d)
|
|
if k not in self._idx:
|
|
i = np.clip(np.arange(n) + d, 0, n - 1)
|
|
self._idx[k] = self.torch.as_tensor(i, device=self.dev) if self.t else i
|
|
return self._idx[k]
|
|
|
|
def sh(self, a, dy: int, dx: int):
|
|
"""a sampled at (y + dy, x + dx), held at the borders."""
|
|
if dy:
|
|
a = a[self.index(a.shape[0], dy)]
|
|
if dx:
|
|
a = a[:, self.index(a.shape[1], dx)]
|
|
return a
|
|
|
|
def where(self, c, a, b):
|
|
return self.torch.where(c, a, b) if self.t else np.where(c, a, b)
|
|
|
|
def maximum(self, a, b):
|
|
if self.t:
|
|
return self.torch.maximum(a, b) if is_tensor(b) else a.clamp(min=b)
|
|
return np.maximum(a, b)
|
|
|
|
def minimum(self, a, b):
|
|
if self.t:
|
|
return self.torch.minimum(a, b) if is_tensor(b) else a.clamp(max=b)
|
|
return np.minimum(a, b)
|
|
|
|
def clip(self, a, lo: float, hi: float):
|
|
return a.clamp(lo, hi) if self.t else np.clip(a, lo, hi)
|
|
|
|
def sqrt(self, a):
|
|
return a.sqrt() if self.t else np.sqrt(a)
|
|
|
|
def cummax(self, a, axis: int):
|
|
return self.torch.cummax(a, dim=axis).values if self.t else np.maximum.accumulate(a, axis=axis)
|
|
|
|
def flip(self, a, axis: int):
|
|
return self.torch.flip(a, dims=(axis,)) if self.t else np.flip(a, axis=axis)
|
|
|
|
def take(self, a, idx, axis: int):
|
|
return self.torch.gather(a, axis, idx) if self.t else np.take_along_axis(a, idx, axis=axis)
|
|
|
|
def fl(self, a):
|
|
"""a as float32."""
|
|
return a.float() if self.t else a.astype(np.float32)
|
|
|
|
def zeros_like(self, a):
|
|
return self.torch.zeros_like(a) if self.t else np.zeros_like(a)
|
|
|
|
def full_like(self, a, v):
|
|
return self.torch.full_like(a, v) if self.t else np.full_like(a, v)
|
|
|
|
def T(self, a):
|
|
return a.transpose(0, 1) if self.t else a.T
|
|
|
|
def broadcast_x(self, a):
|
|
"""Column indices, the shape of the 2-D array a."""
|
|
x = self.arange(a.shape[1])
|
|
return x.expand(a.shape[0], -1) if self.t else np.broadcast_to(x, a.shape)
|
|
|
|
|
|
def _luma(c):
|
|
"""c: HxWx3 float BGR."""
|
|
return 0.114 * c[..., 0] + 0.587 * c[..., 1] + 0.299 * c[..., 2]
|
|
|
|
|
|
def _lerp(o: _Ops, a, b, t):
|
|
"""a + (b - a) * t, t per pixel."""
|
|
return a + (b - a) * t[..., None]
|
|
|
|
|
|
# ---- FXAA-style -------------------------------------------------------------------------------------------------
|
|
def _fxaa(o: _Ops, c):
|
|
L = _luma(c)
|
|
N, S, W, E = o.sh(L, -1, 0), o.sh(L, 1, 0), o.sh(L, 0, -1), o.sh(L, 0, 1)
|
|
NW, NE, SW, SE = o.sh(L, -1, -1), o.sh(L, -1, 1), o.sh(L, 1, -1), o.sh(L, 1, 1)
|
|
mx = o.maximum(o.maximum(o.maximum(N, S), o.maximum(W, E)), L)
|
|
mn = o.minimum(o.minimum(o.minimum(N, S), o.minimum(W, E)), L)
|
|
rng = mx - mn
|
|
active = rng >= o.maximum(mx * FXAA_EDGE, FXAA_EDGE_MIN)
|
|
# sub-pixel: how far the pixel stands out from its 3x3 neighbourhood
|
|
avg = (2.0 * (N + S + W + E) + NW + NE + SW + SE) / 12.0
|
|
sub = o.clip(abs(avg - L) / o.maximum(rng, 1e-6), 0.0, 1.0)
|
|
sub = (-2.0 * sub + 3.0) * sub * sub
|
|
sub = sub * sub * FXAA_SUBPIX
|
|
# direction: a horizontal edge has luma changing from row to row
|
|
horz = abs(N + S - 2.0 * L) * 2.0 + abs(NE + SE - 2.0 * E) + abs(NW + SW - 2.0 * W)
|
|
vert = abs(W + E - 2.0 * L) * 2.0 + abs(NW + NE - 2.0 * N) + abs(SW + SE - 2.0 * S)
|
|
is_h = horz >= vert
|
|
l1, l2 = o.where(is_h, N, W), o.where(is_h, S, E) # the two neighbours across the edge
|
|
g1, g2 = abs(l1 - L), abs(l2 - L)
|
|
first = g1 >= g2 # the edge is on the side of l1 (up, or left)
|
|
nb = o.where(first, l1, l2)
|
|
grad = o.maximum(g1, g2) * 0.25
|
|
local = 0.5 * (L + nb)
|
|
# luma halfway between the pixel's row (column) and its neighbour's, the line the search follows
|
|
half = (0.5 * (L + N), 0.5 * (L + S), 0.5 * (L + W), 0.5 * (L + E))
|
|
|
|
def along(k: int):
|
|
"""The half-way luma k pixels along the edge (for horizontal edges: x + k; vertical: y + k)."""
|
|
hu, hd = o.sh(half[0], 0, k), o.sh(half[1], 0, k)
|
|
vl, vr = o.sh(half[2], k, 0), o.sh(half[3], k, 0)
|
|
return o.where(is_h, o.where(first, hu, hd), o.where(first, vl, vr))
|
|
|
|
ends = []
|
|
for sign in (-1, 1):
|
|
dist = o.full_like(L, FXAA_GUESS)
|
|
delta = along(sign * FXAA_STEPS[-1]) - local
|
|
found = o.zeros_like(L) > 1.0 # all False
|
|
for k in FXAA_STEPS:
|
|
d = along(sign * k) - local
|
|
hit = (abs(d) >= grad) & ~found
|
|
dist = o.where(hit, o.full_like(L, float(k)), dist)
|
|
delta = o.where(hit, d, delta)
|
|
found = found | hit
|
|
ends.append((dist, delta))
|
|
(dn, en), (dp, ep) = ends
|
|
nearer_n = dn < dp
|
|
d_min = o.minimum(dn, dp)
|
|
end_delta = o.where(nearer_n, en, ep)
|
|
good = (end_delta < 0) != ((L - local) < 0)
|
|
off = o.where(good, 0.5 - d_min / (dn + dp), o.zeros_like(L))
|
|
t = o.where(active, o.maximum(off, sub), o.zeros_like(L))
|
|
cn = o.where(is_h[..., None], o.where(first[..., None], o.sh(c, -1, 0), o.sh(c, 1, 0)),
|
|
o.where(first[..., None], o.sh(c, 0, -1), o.sh(c, 0, 1)))
|
|
return _lerp(o, c, cn, t)
|
|
|
|
|
|
# ---- SMAA/MLAA-style --------------------------------------------------------------------------------------------
|
|
def _edges(o: _Ops, L):
|
|
"""(left, top): whether there is an edge on the left (top) side of each pixel, after local contrast adaptation."""
|
|
dl = abs(L - o.sh(L, 0, -1))
|
|
dt = abs(L - o.sh(L, -1, 0))
|
|
left = dl > SMAA_THRESHOLD
|
|
top = dt > SMAA_THRESHOLD
|
|
# an edge much weaker than one beside it is left alone (stops blurring next to strong edges)
|
|
near_l = o.maximum(o.maximum(o.sh(dl, 0, -1), o.sh(dl, 0, 1)),
|
|
o.maximum(o.maximum(dt, o.sh(dt, 1, 0)), o.maximum(o.sh(dt, 0, -1), o.sh(dt, 1, -1))))
|
|
near_t = o.maximum(o.maximum(o.sh(dt, -1, 0), o.sh(dt, 1, 0)),
|
|
o.maximum(o.maximum(dl, o.sh(dl, 0, 1)), o.maximum(o.sh(dl, -1, 0), o.sh(dl, -1, 1))))
|
|
left = left & (dl * SMAA_ADAPT >= near_l)
|
|
top = top & (dt * SMAA_ADAPT >= near_t)
|
|
left = left & (o.broadcast_x(L) > 0) # nothing left of the first column, above the first row
|
|
top = top & (o.T(o.broadcast_x(o.T(L))) > 0)
|
|
return left, top
|
|
|
|
|
|
def _line_weights(o: _Ops, line, cross):
|
|
"""Edges that run along x: line[y, x] = an edge between rows y-1 and y at column x; cross[y, x] = an edge between
|
|
columns x-1 and x in row y. Returns (up, down): how much pixel (y-1, x) takes of (y, x), and (y, x) of (y-1, x)."""
|
|
H, W = line.shape
|
|
x = o.broadcast_x(line)
|
|
# how many edge pixels run on to the left and to the right of each one
|
|
last_gap = o.cummax(o.where(line, o.full_like(x, -1), x), 1)
|
|
dl = x - last_gap - 1
|
|
xf = o.broadcast_x(line)
|
|
last_gap_r = o.cummax(o.where(o.flip(line, 1), o.full_like(xf, -1), xf), 1)
|
|
dr = o.flip(xf - last_gap_r - 1, 1)
|
|
xl = o.clip(x - dl, 0, W - 1) # first pixel of the run (non-edge pixels: anything; masked out below)
|
|
xr1 = o.clip(x + dr + 1, 0, W - 1) # just past the last one (held at the border)
|
|
past_end = (x + dr + 1) >= W
|
|
up_row, low_row = o.sh(cross, -1, 0), cross # the rows above and below the line
|
|
ul, dl_ = o.take(up_row, xl, 1), o.take(low_row, xl, 1)
|
|
ur, dr_ = o.take(up_row, xr1, 1) & ~past_end, o.take(low_row, xr1, 1) & ~past_end
|
|
zero = o.fl(o.zeros_like(x))
|
|
half = zero + 0.5
|
|
hl = o.where(ul & ~dl_, half, o.where(dl_ & ~ul, -half, zero))
|
|
hr = o.where(ur & ~dr_, half, o.where(dr_ & ~ur, -half, zero))
|
|
n, p = o.fl(dl + dr + 1), o.fl(dl)
|
|
mid = n * 0.5
|
|
# the line from height hl at the run's start to 0 at its middle, then to hr at its end: its area over [p, p+1]
|
|
a, b = p, o.minimum(p + 1.0, mid)
|
|
left = o.where(b > a, hl * ((b - a) - (b * b - a * a) / (2.0 * mid)), zero)
|
|
a, b = o.maximum(p, mid), p + 1.0
|
|
right = o.where(b > a, hr * (((b * b - a * a) * 0.5 - mid * (b - a)) / mid), zero)
|
|
up = o.where(line, o.maximum(left, 0.0) + o.maximum(right, 0.0), zero)
|
|
down = o.where(line, -(o.minimum(left, 0.0) + o.minimum(right, 0.0)), zero)
|
|
return up, down
|
|
|
|
|
|
def _smaa(o: _Ops, c):
|
|
L = _luma(c)
|
|
left, top = _edges(o, L)
|
|
up, down = _line_weights(o, top, left) # horizontal edges
|
|
lft, rgt = _line_weights(o, o.T(left), o.T(top)) # vertical edges, as rows of the transposed picture
|
|
lft, rgt = o.T(lft), o.T(rgt)
|
|
# what each pixel takes from each neighbour
|
|
w_t = down # its top edge: from the pixel above
|
|
w_b = o.sh(up, 1, 0) * o.fl(o.T(o.broadcast_x(o.T(L))) < L.shape[0] - 1) # its bottom edge (the top of the one below)
|
|
w_l = rgt # its left edge
|
|
w_r = o.sh(lft, 0, 1) * o.fl(o.broadcast_x(L) < L.shape[1] - 1)
|
|
# one direction per pixel, the stronger one (as SMAA's blending does): where edges cross, blending from all four
|
|
# sides at once would pull the pixel too far (dark blots where a fence's wires cross its posts)
|
|
horiz = (w_t + w_b) >= (w_l + w_r)
|
|
zero = w_t * 0.0
|
|
w_t, w_b = o.where(horiz, w_t, zero), o.where(horiz, w_b, zero)
|
|
w_l, w_r = o.where(horiz, zero, w_l), o.where(horiz, zero, w_r)
|
|
total = w_t + w_b + w_l + w_r # (at most 1: each side gives at most a half)
|
|
out = c * (1.0 - total)[..., None]
|
|
out = out + o.sh(c, -1, 0) * w_t[..., None] + o.sh(c, 1, 0) * w_b[..., None]
|
|
out = out + o.sh(c, 0, -1) * w_l[..., None] + o.sh(c, 0, 1) * w_r[..., None]
|
|
return out
|
|
|
|
|
|
# ---- CAS-style sharpening ---------------------------------------------------------------------------------------
|
|
def _cas(o: _Ops, c, sharpness: float = CAS_SHARPNESS):
|
|
N, S, W, E = o.sh(c, -1, 0), o.sh(c, 1, 0), o.sh(c, 0, -1), o.sh(c, 0, 1)
|
|
mn = o.minimum(o.minimum(o.minimum(N, S), o.minimum(W, E)), c)
|
|
mx = o.maximum(o.maximum(o.maximum(N, S), o.maximum(W, E)), c)
|
|
amp = o.sqrt(o.clip(o.minimum(mn, 1.0 - mx) / o.maximum(mx, 1e-6), 0.0, 1.0))
|
|
peak = -1.0 / (8.0 - 3.0 * float(sharpness)) # 1/8 (gentle) .. 1/5 (strong)
|
|
w = amp * peak
|
|
return o.clip((c + w * (N + S + W + E)) / (1.0 + 4.0 * w), 0.0, 1.0)
|
|
|
|
|
|
_FILTERS = {"fxaa": _fxaa, "smaa": _smaa, "cas": _cas}
|
|
|
|
|
|
def _whole(mode: str):
|
|
"""The filter from uint8 in to uint8 out, as one function (what torch.compile gets)."""
|
|
def run(frame):
|
|
o = _Ops(frame)
|
|
return o.u8(_FILTERS[mode](o, o.f32(frame)), frame)
|
|
return run
|
|
|
|
|
|
# ---- compiled on the GPU ----------------------------------------------------------------------------------------
|
|
COMPILE = os.environ.get("SUMMIT_AA_COMPILE", "1") != "0"
|
|
_compiled: dict = {} # (mode, shape, device) -> the compiled function, "pending" or "failed"
|
|
_lock = threading.Lock()
|
|
# held for the whole of each compile: torch.compile's tracing state is global, and a compiled filter run while
|
|
# another is being compiled fails ("FX to symbolically trace a dynamo-optimized function"). So one compile at a time,
|
|
# and a compiled filter runs only when no compile is going on (else it runs op by op for that frame).
|
|
_compiling = threading.Lock()
|
|
|
|
|
|
def _can_compile(frame) -> bool:
|
|
if not (COMPILE and getattr(frame, "is_cuda", False)):
|
|
return False
|
|
try:
|
|
import triton # noqa: F401 - torch.compile's GPU code generator
|
|
return True
|
|
except ImportError:
|
|
return False
|
|
|
|
|
|
def _compile(key: tuple, mode: str, sample) -> None:
|
|
import time
|
|
|
|
import torch
|
|
with _compiling:
|
|
t0 = time.perf_counter()
|
|
_compile_locked(key, mode, sample, t0, torch)
|
|
|
|
|
|
def _compile_locked(key: tuple, mode: str, sample, t0: float, torch) -> None:
|
|
import time
|
|
try:
|
|
fn = torch.compile(_whole(mode), dynamic=False)
|
|
with torch.no_grad(): # (grad mode is per thread)
|
|
fn(sample)
|
|
torch.cuda.current_stream(sample.device).synchronize()
|
|
_compiled[key] = fn
|
|
print(f"[aa] {NAMES[mode]} compiled for {sample.shape[1]}x{sample.shape[0]} in "
|
|
f"{time.perf_counter() - t0:.1f} s: it runs as fused kernels from now on", flush=True)
|
|
except Exception as e: # noqa: BLE001 - it keeps running op by op
|
|
_compiled[key] = "failed"
|
|
print(f"[aa] {NAMES[mode]} couldn't be compiled ({type(e).__name__}: {str(e)[:200]}): it keeps running op "
|
|
"by op", flush=True)
|
|
|
|
|
|
def compiled(mode: str, frame):
|
|
"""The compiled filter for frames like this one, or None while it is being made (or can't be): the first call
|
|
starts making it, on a thread of its own."""
|
|
if not _can_compile(frame):
|
|
return None
|
|
key = (mode, tuple(frame.shape), str(frame.device))
|
|
with _lock:
|
|
fn = _compiled.get(key)
|
|
if fn is None:
|
|
_compiled[key] = "pending"
|
|
threading.Thread(target=_compile, args=(key, mode, frame.clone()), name=f"aa-compile-{mode}",
|
|
daemon=True).start()
|
|
return fn if callable(fn) else None
|
|
|
|
|
|
def settle(mode: str, frame, timeout: float = 180.0) -> bool:
|
|
"""Waits until the compiled filter for frames like this one is made (or can't be): for tools that measure.
|
|
True if it is the compiled one that runs now."""
|
|
import time
|
|
if mode not in _FILTERS or compiled(mode, frame) is not None:
|
|
return mode in _FILTERS and _can_compile(frame)
|
|
key = (mode, tuple(frame.shape), str(frame.device))
|
|
end = time.monotonic() + timeout
|
|
while _compiled.get(key) == "pending" and time.monotonic() < end:
|
|
time.sleep(0.1)
|
|
return callable(_compiled.get(key))
|
|
|
|
|
|
_cuda: list = [] # [whether CUDA is there], asked once
|
|
|
|
|
|
def _has_cuda() -> bool:
|
|
if not _cuda:
|
|
try:
|
|
import torch
|
|
_cuda.append(bool(torch.cuda.is_available()))
|
|
except ImportError:
|
|
_cuda.append(False)
|
|
return _cuda[0]
|
|
|
|
|
|
def apply(frame, mode: str, gpu: bool = True):
|
|
"""The frame with the filter applied ("off": the frame itself, untouched). frame: HxWx3 uint8 BGR, numpy or a
|
|
torch tensor (any device); the result is the same kind. A numpy frame goes through the GPU when there is one
|
|
(gpu=False: never), there and back: about a millisecond at 1080p against a few hundred on the CPU (frames are on
|
|
the CPU when the window can't take them from the GPU, e.g. on software OpenGL)."""
|
|
if mode == "off" or mode not in _FILTERS:
|
|
return frame
|
|
if gpu and not is_tensor(frame) and _has_cuda():
|
|
import torch
|
|
return apply(torch.from_numpy(np.ascontiguousarray(frame)).cuda(), mode).cpu().numpy()
|
|
if is_tensor(frame):
|
|
import torch
|
|
fn = compiled(mode, frame)
|
|
with torch.no_grad():
|
|
if fn is not None and _compiling.acquire(blocking=False):
|
|
try:
|
|
return fn(frame)
|
|
except Exception as e: # noqa: BLE001 - never ends the session: op by op from now on
|
|
_compiled[(mode, tuple(frame.shape), str(frame.device))] = "failed"
|
|
print(f"[aa] the compiled {NAMES[mode]} failed ({type(e).__name__}: {str(e)[:160]}): it runs op "
|
|
"by op from now on", flush=True)
|
|
finally:
|
|
_compiling.release()
|
|
return _whole(mode)(frame)
|
|
return _whole(mode)(frame)
|