Measured on the RTX 3090 (headless EGL, 1080p Voidrunner frame): GLSL FXAA 0.072 ms, CAS 0.022 ms against torch (compiled) 0.99 and 1.03 ms. The window runs the setting this way unless OpenGL is software and CUDA is there (SUMMIT_AA_GL=1/0 forces it); SMAA-style and the AA comparison stay torch.
166 lines
7.3 KiB
Python
166 lines
7.3 KiB
Python
"""Anti-aliasing cost, both ways: framegen/aa_gl.py's GLSL pass against framegen/aa.py's torch filters (compiled, on
|
|
CUDA), on the same frame and the same graphics card, and how far the GLSL output is from aa.py's numpy reference.
|
|
|
|
python devtools/aa_gl_bench.py [VIDEO] [--size 1920x1080] [--runs 300] [--egl]
|
|
|
|
--egl makes the OpenGL context on the NVIDIA card itself, headless (EGL's device platform), so the GLSL times are the
|
|
GPU's and not a software renderer's; without it a hidden GLFW window is used (whatever the display's OpenGL is,
|
|
llvmpipe on a VM: its times are the CPU's, and printed as such).
|
|
|
|
GLSL: GPU time per pass from GL timer queries. torch: GPU time per filter from CUDA events, and the wall time of a
|
|
call with its synchronisation (what the pipeline pays), both after warm-up and compile.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import os
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
|
|
|
|
def egl_context():
|
|
"""A headless OpenGL 3.3+ context on the first EGL device (NVIDIA's), current on this thread."""
|
|
os.environ["PYOPENGL_PLATFORM"] = "egl"
|
|
import ctypes
|
|
from OpenGL import EGL
|
|
from OpenGL.EGL.EXT.device_base import eglQueryDevicesEXT
|
|
from OpenGL.EGL.EXT.platform_base import eglGetPlatformDisplayEXT
|
|
from OpenGL.EGL.EXT.platform_device import EGL_PLATFORM_DEVICE_EXT
|
|
devices = (EGL.EGLDeviceEXT * 8)()
|
|
n = EGL.EGLint()
|
|
eglQueryDevicesEXT(8, devices, ctypes.byref(n))
|
|
if n.value < 1:
|
|
raise RuntimeError("no EGL device")
|
|
dpy = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, devices[0], None)
|
|
major, minor = EGL.EGLint(), EGL.EGLint()
|
|
if not EGL.eglInitialize(dpy, ctypes.byref(major), ctypes.byref(minor)):
|
|
raise RuntimeError("eglInitialize failed")
|
|
attrs = (EGL.EGLint * 9)(EGL.EGL_SURFACE_TYPE, EGL.EGL_PBUFFER_BIT, EGL.EGL_RENDERABLE_TYPE, EGL.EGL_OPENGL_BIT,
|
|
EGL.EGL_RED_SIZE, 8, EGL.EGL_NONE, 0, 0)
|
|
cfg = EGL.EGLConfig()
|
|
count = EGL.EGLint()
|
|
EGL.eglChooseConfig(dpy, attrs, ctypes.byref(cfg), 1, ctypes.byref(count))
|
|
if count.value < 1:
|
|
raise RuntimeError("no EGL config")
|
|
surf = EGL.eglCreatePbufferSurface(dpy, cfg, (EGL.EGLint * 5)(EGL.EGL_WIDTH, 16, EGL.EGL_HEIGHT, 16,
|
|
EGL.EGL_NONE))
|
|
EGL.eglBindAPI(EGL.EGL_OPENGL_API)
|
|
ctx = EGL.eglCreateContext(dpy, cfg, EGL.EGL_NO_CONTEXT, (EGL.EGLint * 7)(
|
|
EGL.EGL_CONTEXT_MAJOR_VERSION, 3, EGL.EGL_CONTEXT_MINOR_VERSION, 3,
|
|
EGL.EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL.EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL.EGL_NONE))
|
|
if not ctx or not EGL.eglMakeCurrent(dpy, surf, surf, ctx):
|
|
raise RuntimeError("no EGL OpenGL context")
|
|
|
|
|
|
def glfw_context():
|
|
import glfw
|
|
if not glfw.init():
|
|
raise RuntimeError("no display for OpenGL")
|
|
glfw.window_hint(glfw.VISIBLE, glfw.FALSE)
|
|
win = glfw.create_window(64, 64, "Summit aa bench", None, None)
|
|
if not win:
|
|
raise RuntimeError("no OpenGL context")
|
|
glfw.make_context_current(win)
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
ap.add_argument("video", nargs="?")
|
|
ap.add_argument("--frame", type=int, default=120)
|
|
ap.add_argument("--size", default="1920x1080")
|
|
ap.add_argument("--runs", type=int, default=300)
|
|
ap.add_argument("--egl", action="store_true")
|
|
ap.add_argument("--no-torch", action="store_true")
|
|
a = ap.parse_args()
|
|
w, h = (int(v) for v in a.size.lower().split("x"))
|
|
import cv2
|
|
if a.video:
|
|
cap = cv2.VideoCapture(a.video)
|
|
cap.set(cv2.CAP_PROP_POS_FRAMES, a.frame)
|
|
ok, frame = cap.read()
|
|
if not ok:
|
|
raise SystemExit(f"no frame {a.frame} in {a.video}")
|
|
else:
|
|
from compare_shot import pattern
|
|
frame = pattern(1280, 720)
|
|
frame = np.ascontiguousarray(cv2.resize(frame, (w, h), interpolation=cv2.INTER_LINEAR))
|
|
|
|
(egl_context if a.egl else glfw_context)()
|
|
from OpenGL import GL
|
|
from framegen import aa
|
|
from framegen.aa_gl import AaGl
|
|
renderer = GL.glGetString(GL.GL_RENDERER).decode(errors="replace")
|
|
print(f"[aa_gl_bench] {w}x{h}, OpenGL: {renderer}", flush=True)
|
|
|
|
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
|
|
GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1)
|
|
|
|
def tex(data=None):
|
|
t = GL.glGenTextures(1)
|
|
GL.glBindTexture(GL.GL_TEXTURE_2D, t)
|
|
for p in (GL.GL_TEXTURE_MIN_FILTER, GL.GL_TEXTURE_MAG_FILTER):
|
|
GL.glTexParameteri(GL.GL_TEXTURE_2D, p, GL.GL_NEAREST)
|
|
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, data)
|
|
return t
|
|
|
|
src = tex(frame) # row 0 of the image in texel row 0, as the window uploads it
|
|
dst = tex()
|
|
fbo = GL.glGenFramebuffers(1)
|
|
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbo)
|
|
GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, dst, 0)
|
|
f = AaGl(GL)
|
|
q = int(np.ravel(GL.glGenQueries(1))[0])
|
|
results = {}
|
|
for mode in ("fxaa", "cas"):
|
|
for _ in range(20):
|
|
f.draw(mode, src, fbo, w, h)
|
|
GL.glFinish()
|
|
ms = []
|
|
for _ in range(a.runs):
|
|
GL.glBeginQuery(GL.GL_TIME_ELAPSED, q)
|
|
f.draw(mode, src, fbo, w, h)
|
|
GL.glEndQuery(GL.GL_TIME_ELAPSED)
|
|
ms.append(int(GL.glGetQueryObjectuiv(q, GL.GL_QUERY_RESULT)) / 1e6) # (32-bit ns: PyOpenGL's ui64v fails)
|
|
GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, fbo)
|
|
out = np.frombuffer(GL.glReadPixels(0, 0, w, h, GL.GL_BGR, GL.GL_UNSIGNED_BYTE), np.uint8).reshape(h, w, 3)
|
|
ref = aa.apply(frame, mode, gpu=False)
|
|
diff = np.abs(out.astype(int) - ref)
|
|
results[mode] = {"glsl": (float(np.mean(ms)), float(np.percentile(ms, 99)), float(np.max(ms)))}
|
|
print(f" GLSL {mode}: {np.mean(ms):.3f} ms average, {np.percentile(ms, 99):.3f} p99, {np.max(ms):.3f} worst "
|
|
f"(GPU time, {a.runs} runs); against aa.py's numpy: max diff {diff.max()}, "
|
|
f"{(diff > 1).mean() * 100:.3f}% of values off by more than 1", flush=True)
|
|
if not a.no_torch:
|
|
import torch
|
|
if not torch.cuda.is_available():
|
|
print(" torch: no CUDA here, skipped")
|
|
return 0
|
|
t = torch.from_numpy(frame).cuda()
|
|
for mode in ("fxaa", "smaa", "cas"):
|
|
fused = aa.settle(mode, t)
|
|
for _ in range(20):
|
|
aa.apply(t, mode)
|
|
torch.cuda.synchronize()
|
|
gpu, wall = [], []
|
|
for _ in range(a.runs):
|
|
e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
|
t0 = time.perf_counter()
|
|
e0.record()
|
|
aa.apply(t, mode)
|
|
e1.record()
|
|
torch.cuda.synchronize()
|
|
wall.append((time.perf_counter() - t0) * 1000)
|
|
gpu.append(e0.elapsed_time(e1))
|
|
print(f" torch {mode} ({'compiled' if fused else 'op by op'}): {np.mean(gpu):.3f} ms GPU average, "
|
|
f"{np.percentile(gpu, 99):.3f} p99; {np.mean(wall):.3f} ms per call with its sync, "
|
|
f"{np.max(wall):.3f} worst", flush=True)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|