Spaces:
Running on Zero
Running on Zero
Merge origin/develop, resolving upscale.py profiling conflict
Browse filesBoth branches touched upscale_frames(): develop added opt-in profiling
(UpscaleProfiler) for #48, this branch added the mypy --strict type
annotation on out_frames. Keep both.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
postprocess/upscale/profiling.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional profiling for `upscale_frames()`, gated by `UPSCALE_PROFILE=1` (see `upscale.PROFILE`).
|
| 2 |
+
|
| 3 |
+
Buckets each tiled `model()` call into "first call at this (tile-shape, batch-size)" vs. "steady
|
| 4 |
+
call" (a repeat of a shape/batch-size combo already seen this run): `torch.compile(dynamic=True)`
|
| 5 |
+
only marks a dim dynamic after seeing more than one value for it, so the very first call at a
|
| 6 |
+
given (shape, batch_size) pair is the one that risks eating a recompile, not just the first call
|
| 7 |
+
overall. Also tracks peak CUDA memory for the run. See issue #48.
|
| 8 |
+
|
| 9 |
+
Off by default — the `synchronize()` calls this needs for accurate per-call timing would
|
| 10 |
+
otherwise skew real request latency by killing async kernel overlap.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import time as _time
|
| 16 |
+
from contextlib import contextmanager
|
| 17 |
+
from typing import Iterator
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class UpscaleProfiler:
|
| 23 |
+
def __init__(self, enabled: bool, device: torch.device) -> None:
|
| 24 |
+
self.enabled = enabled
|
| 25 |
+
self._device = device
|
| 26 |
+
self._seen_keys: set[tuple[tuple[int, int], int]] = set()
|
| 27 |
+
self._first_call_count = 0
|
| 28 |
+
self._first_call_time = 0.0
|
| 29 |
+
self._steady_call_count = 0
|
| 30 |
+
self._steady_call_time = 0.0
|
| 31 |
+
self._wall_t0 = _time.perf_counter()
|
| 32 |
+
if self.enabled and device.type == "cuda":
|
| 33 |
+
torch.cuda.reset_peak_memory_stats(device)
|
| 34 |
+
|
| 35 |
+
@contextmanager
|
| 36 |
+
def timed(self, shape: tuple[int, int], batch_size: int) -> Iterator[None]:
|
| 37 |
+
"""Wrap a single tiled model() call, bucketing its elapsed time by (shape, batch_size)."""
|
| 38 |
+
if not self.enabled:
|
| 39 |
+
yield
|
| 40 |
+
return
|
| 41 |
+
if self._device.type == "cuda":
|
| 42 |
+
torch.cuda.synchronize()
|
| 43 |
+
t0 = _time.perf_counter()
|
| 44 |
+
yield
|
| 45 |
+
if self._device.type == "cuda":
|
| 46 |
+
torch.cuda.synchronize()
|
| 47 |
+
elapsed = _time.perf_counter() - t0
|
| 48 |
+
|
| 49 |
+
key = (shape, batch_size)
|
| 50 |
+
if key in self._seen_keys:
|
| 51 |
+
self._steady_call_count += 1
|
| 52 |
+
self._steady_call_time += elapsed
|
| 53 |
+
else:
|
| 54 |
+
self._seen_keys.add(key)
|
| 55 |
+
self._first_call_count += 1
|
| 56 |
+
self._first_call_time += elapsed
|
| 57 |
+
|
| 58 |
+
def report(self, frame_count: int, tile_size: int, frame_batch_size: int, max_tile_batch: int) -> None:
|
| 59 |
+
if not self.enabled:
|
| 60 |
+
return
|
| 61 |
+
wall_elapsed = _time.perf_counter() - self._wall_t0
|
| 62 |
+
model_time = self._first_call_time + self._steady_call_time
|
| 63 |
+
steady_avg = (
|
| 64 |
+
self._steady_call_time / self._steady_call_count if self._steady_call_count else float("nan")
|
| 65 |
+
)
|
| 66 |
+
print(
|
| 67 |
+
f"[upscale] profile: frames={frame_count} wall={wall_elapsed:.2f}s model_time={model_time:.2f}s "
|
| 68 |
+
f"(non_model={wall_elapsed - model_time:.2f}s) | first-at-shape calls={self._first_call_count} "
|
| 69 |
+
f"total={self._first_call_time:.2f}s avg={self._first_call_time / max(self._first_call_count, 1):.3f}s/call "
|
| 70 |
+
f"| steady calls={self._steady_call_count} total={self._steady_call_time:.2f}s avg={steady_avg:.3f}s/call",
|
| 71 |
+
flush=True,
|
| 72 |
+
)
|
| 73 |
+
if self._device.type == "cuda":
|
| 74 |
+
peak_allocated = torch.cuda.max_memory_allocated(self._device) / 1024**3
|
| 75 |
+
peak_reserved = torch.cuda.max_memory_reserved(self._device) / 1024**3
|
| 76 |
+
print(
|
| 77 |
+
f"[upscale] profile: peak CUDA memory allocated={peak_allocated:.2f} GiB "
|
| 78 |
+
f"reserved={peak_reserved:.2f} GiB (TILE_SIZE={tile_size}, "
|
| 79 |
+
f"FRAME_BATCH_SIZE={frame_batch_size}, MAX_TILE_BATCH={max_tile_batch})",
|
| 80 |
+
flush=True,
|
| 81 |
+
)
|
postprocess/upscale/upscale.py
CHANGED
|
@@ -26,6 +26,7 @@ fetch out of the metered GPU allocation on its first upscale request.
|
|
| 26 |
from __future__ import annotations
|
| 27 |
|
| 28 |
import math
|
|
|
|
| 29 |
from functools import lru_cache
|
| 30 |
from pathlib import Path
|
| 31 |
from typing import TYPE_CHECKING, Callable, cast
|
|
@@ -37,6 +38,7 @@ from PIL import Image
|
|
| 37 |
from safetensors.torch import load_file
|
| 38 |
from torch.hub import download_url_to_file, get_dir
|
| 39 |
|
|
|
|
| 40 |
from .srvgg_arch import SRVGGNetCompact
|
| 41 |
|
| 42 |
if TYPE_CHECKING:
|
|
@@ -67,6 +69,10 @@ MAX_TILE_BATCH = 16
|
|
| 67 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 68 |
dtype = torch.float16 if device.type == "cuda" else torch.float32
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
ProgressCallback = Callable[[int, int], None]
|
| 71 |
|
| 72 |
|
|
@@ -112,7 +118,7 @@ def _pre_pad(tensor: torch.Tensor, pad: int) -> torch.Tensor:
|
|
| 112 |
|
| 113 |
|
| 114 |
@torch.no_grad()
|
| 115 |
-
def _tile_process(model: torch.nn.Module, img: torch.Tensor) -> torch.Tensor:
|
| 116 |
batch, channel, height, width = img.shape
|
| 117 |
output = img.new_zeros((batch, channel, height * SCALE, width * SCALE))
|
| 118 |
tiles_x = math.ceil(width / TILE_SIZE)
|
|
@@ -136,14 +142,15 @@ def _tile_process(model: torch.nn.Module, img: torch.Tensor) -> torch.Tensor:
|
|
| 136 |
(b, in_x0, in_y0, in_x1, in_y1, pad_x0, pad_y0, pad_x1, pad_y1)
|
| 137 |
)
|
| 138 |
|
| 139 |
-
for jobs in jobs_by_shape.
|
| 140 |
for chunk_start in range(0, len(jobs), MAX_TILE_BATCH):
|
| 141 |
chunk = jobs[chunk_start:chunk_start + MAX_TILE_BATCH]
|
| 142 |
patch = torch.cat(
|
| 143 |
[img[b:b + 1, :, pad_y0:pad_y1, pad_x0:pad_x1] for b, _, _, _, _, pad_x0, pad_y0, pad_x1, pad_y1 in chunk],
|
| 144 |
dim=0,
|
| 145 |
)
|
| 146 |
-
|
|
|
|
| 147 |
|
| 148 |
for i, (b, in_x0, in_y0, in_x1, in_y1, pad_x0, pad_y0, pad_x1, pad_y1) in enumerate(chunk):
|
| 149 |
trim_x0, trim_y0 = (in_x0 - pad_x0) * SCALE, (in_y0 - pad_y0) * SCALE
|
|
@@ -189,6 +196,7 @@ def upscale_frames(
|
|
| 189 |
return []
|
| 190 |
model = _load_model()
|
| 191 |
out_frames: list[Image.Image] = []
|
|
|
|
| 192 |
|
| 193 |
i = 0
|
| 194 |
while i < len(frames):
|
|
@@ -201,7 +209,7 @@ def upscale_frames(
|
|
| 201 |
|
| 202 |
tensor = _frames_to_tensor(batch)
|
| 203 |
padded = _pre_pad(tensor, TILE_PAD)
|
| 204 |
-
upscaled = _tile_process(model, padded)
|
| 205 |
# crop the pre-pad border (scaled) back off
|
| 206 |
upscaled = upscaled[:, :, : h * SCALE, : w * SCALE]
|
| 207 |
results = upscaled.clamp(0, 1).permute(0, 2, 3, 1).float().cpu().numpy()
|
|
@@ -209,4 +217,6 @@ def upscale_frames(
|
|
| 209 |
out_frames.append(Image.fromarray((result * 255.0).round().astype(np.uint8)))
|
| 210 |
if progress_callback is not None:
|
| 211 |
progress_callback(len(out_frames), len(frames))
|
|
|
|
|
|
|
| 212 |
return out_frames
|
|
|
|
| 26 |
from __future__ import annotations
|
| 27 |
|
| 28 |
import math
|
| 29 |
+
import os
|
| 30 |
from functools import lru_cache
|
| 31 |
from pathlib import Path
|
| 32 |
from typing import TYPE_CHECKING, Callable, cast
|
|
|
|
| 38 |
from safetensors.torch import load_file
|
| 39 |
from torch.hub import download_url_to_file, get_dir
|
| 40 |
|
| 41 |
+
from .profiling import UpscaleProfiler
|
| 42 |
from .srvgg_arch import SRVGGNetCompact
|
| 43 |
|
| 44 |
if TYPE_CHECKING:
|
|
|
|
| 69 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 70 |
dtype = torch.float16 if device.type == "cuda" else torch.float32
|
| 71 |
|
| 72 |
+
# Set UPSCALE_PROFILE=1 on the dev Space to print per-model()-call timing and peak CUDA memory
|
| 73 |
+
# for each upscale_frames() invocation — see profiling.py. Off by default.
|
| 74 |
+
PROFILE = os.environ.get("UPSCALE_PROFILE", "") not in ("", "0")
|
| 75 |
+
|
| 76 |
ProgressCallback = Callable[[int, int], None]
|
| 77 |
|
| 78 |
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
@torch.no_grad()
|
| 121 |
+
def _tile_process(model: torch.nn.Module, img: torch.Tensor, profiler: UpscaleProfiler) -> torch.Tensor:
|
| 122 |
batch, channel, height, width = img.shape
|
| 123 |
output = img.new_zeros((batch, channel, height * SCALE, width * SCALE))
|
| 124 |
tiles_x = math.ceil(width / TILE_SIZE)
|
|
|
|
| 142 |
(b, in_x0, in_y0, in_x1, in_y1, pad_x0, pad_y0, pad_x1, pad_y1)
|
| 143 |
)
|
| 144 |
|
| 145 |
+
for shape, jobs in jobs_by_shape.items():
|
| 146 |
for chunk_start in range(0, len(jobs), MAX_TILE_BATCH):
|
| 147 |
chunk = jobs[chunk_start:chunk_start + MAX_TILE_BATCH]
|
| 148 |
patch = torch.cat(
|
| 149 |
[img[b:b + 1, :, pad_y0:pad_y1, pad_x0:pad_x1] for b, _, _, _, _, pad_x0, pad_y0, pad_x1, pad_y1 in chunk],
|
| 150 |
dim=0,
|
| 151 |
)
|
| 152 |
+
with profiler.timed(shape, patch.shape[0]):
|
| 153 |
+
tile_out = model(patch)
|
| 154 |
|
| 155 |
for i, (b, in_x0, in_y0, in_x1, in_y1, pad_x0, pad_y0, pad_x1, pad_y1) in enumerate(chunk):
|
| 156 |
trim_x0, trim_y0 = (in_x0 - pad_x0) * SCALE, (in_y0 - pad_y0) * SCALE
|
|
|
|
| 196 |
return []
|
| 197 |
model = _load_model()
|
| 198 |
out_frames: list[Image.Image] = []
|
| 199 |
+
profiler = UpscaleProfiler(PROFILE, device)
|
| 200 |
|
| 201 |
i = 0
|
| 202 |
while i < len(frames):
|
|
|
|
| 209 |
|
| 210 |
tensor = _frames_to_tensor(batch)
|
| 211 |
padded = _pre_pad(tensor, TILE_PAD)
|
| 212 |
+
upscaled = _tile_process(model, padded, profiler)
|
| 213 |
# crop the pre-pad border (scaled) back off
|
| 214 |
upscaled = upscaled[:, :, : h * SCALE, : w * SCALE]
|
| 215 |
results = upscaled.clamp(0, 1).permute(0, 2, 3, 1).float().cpu().numpy()
|
|
|
|
| 217 |
out_frames.append(Image.fromarray((result * 255.0).round().astype(np.uint8)))
|
| 218 |
if progress_callback is not None:
|
| 219 |
progress_callback(len(out_frames), len(frames))
|
| 220 |
+
|
| 221 |
+
profiler.report(len(frames), TILE_SIZE, FRAME_BATCH_SIZE, MAX_TILE_BATCH)
|
| 222 |
return out_frames
|