Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(rife): the torch backend's device failing as the network is put on it is a RIFE that fails, in PyTorch's words, as a run's is
Soohong Kimfd604517036a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 760794d..e8cf841 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,9 +6,9 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the**Upgrading from 2.45.2: Defaults stay unchanged, cache keys update once, reports show the backend, install checks model hashes, and schemas are unchanged.** With `SPRITE_GEN_RIFE_BACKEND` unset (the default), RIFE is the `rife-ncnn-vulkan` binary as before. Its frames are the same bytes as 2.45.2. Measured: the binary's frames and sixteen-pass readings through the changed engine equal the old engine's, byte for byte. A `--between-cache` directory kept by 2.45.2 is made again once. The key now names the backend (`backend: "ncnn"`). The engine's `rife.py` changed, and its sha256 is part of the key anyway. Reports take `interpolator.kind` from what made the frames: `rife-ncnn-vulkan` as before for the binary, or `rife-torch` for the new backend. The overlapped wrap's record counts `binary_calls` for the binary as before, or `runs` for the torch backend. `sprite-gen rife install` now checks the model's two files (`rife-v4.6/flownet.param`, `flownet.bin`) against pinned SHA-256 after unpacking, for either backend. A model that differs installs nothing. The line a missing RIFE is reported with (`install` in records, warnings) is `sprite-gen rife install` for the binary. Where the torch backend is chosen, that line is: `pip install "sprite-gen[torch]" && sprite-gen rife install --backend torch`. No command-line flags of `video-loop` / `video-cycle-align` / `video-set` change. No restoration schemas change: `source-restoration-v5`, repair report `schema_version` 4, comparison `schema_version` 6.-- **New: RIFE's torch backend runs rife-v4.6 in PyTorch for compute GPUs without Vulkan.** `SPRITE_GEN_RIFE_BACKEND=torch` runs the same rife-v4.6 in PyTorch (`sprite_gen/video/rife_torch.py`). It serves a GPU the binary cannot run on: rife-ncnn-vulkan needs Vulkan, and a GPU offered for compute alone (CUDA with no Vulkan driver) has none. The network is rife-v4.6's IFNet written again from Practical-RIFE's `IFNet_HDv3` (MIT, notice in NOTICE). Its weights are read out of the binary's own model files (SHA-256 pinned, the binary's float16 weights), with no other download. One run does what one call of the binary does with `-x -z`. The pair is turned eight ways and run both ways in time, with flows averaged at each of four levels. The loop follows rife-ncnn-vulkan's `RIFE::process_v4` (MIT, notice in NOTICE). `SPRITE_GEN_RIFE_DEVICE` names `cuda` (default) or `cpu`. `SPRITE_GEN_RIFE_TTA` means the same for both backends. The default augmentation stays `-x -z`. To install: `pip install "sprite-gen[torch]"` (new extra: `torch>=2.13.0,<3`). Then run: `sprite-gen rife install --backend torch` (new flag; defaults to `SPRITE_GEN_RIFE_BACKEND`). This unpacks the model, and makes a check frame through PyTorch on `SPRITE_GEN_RIFE_DEVICE`. It reads the model only, so a Linux ARM machine the binary does not run on is not refused. A CPU-only host installs PyTorch's CPU build first: `pip install torch==2.13.0 --index-url https://download.pytorch.org/whl/cpu` (192 MB, against the CUDA build's 527 MB plus its CUDA libraries). Nothing falls back. With torch chosen the binary is never looked for or run. `cuda` where PyTorch finds no CUDA is refused naming why (a CPU-only PyTorch, or a CUDA that finds no GPU) and does not run on the CPU. `mps` (Apple's GPU) is refused (no lane measures it; on a Mac the binary runs on the GPU already). A backend or device named wrong is refused. PyTorch not installed, or no model where the backend looks (`SPRITE_GEN_RIFE_MODEL`, else the install root), is RIFE not installed, as the binary missing is. Under `--repair auto` the loop is cut as filmed with the warning, and its record names the torch install line. On CUDA each frame runs with cuDNN deterministic, its benchmark off and convolutions in IEEE float32 (no TF32). The same frame twice is the same bytes on one GPU, driver and PyTorch. What made a frame is the RIFE's identity: backend, model bytes loaded, network code, PyTorch, on CUDA the GPU, driver, CUDA, cuDNN and those settings; on the CPU its instruction set. Because of this identity, `--between-cache` never hands one backend's or GPU's frame to another. Measured on synthetic walkers: Seven walker pairs (clean, outline lost, ghost, torn, a cross-fade to look at) get the same verdicts from the binary on an Apple GPU, the binary on Mesa llvmpipe and the torch backend on a CPU. The torch frame lies 0.005 to 0.052 of 255 on average from the binary's Apple GPU frame. The binary's own llvmpipe frame lies 0.007 to 0.25. A 960 x 960 frame of a synthetic walker with `-x -z`: On an Apple M4 Max CPU (12 threads), 3.3 to 3.6 s; the binary on that Mac's GPU takes 1.27 to 1.37 s. In a Modal container of two CPUs (the app's job size), 22.6 to 28.5 s on two threads; the binary on Mesa llvmpipe in the same container takes 127.7 to 131.5 s. The torch backend's frames are not the binary's bytes, which is one reason the binary stays the default. [loop-repair](docs/loop-repair.md) section 1+- **New: RIFE's torch backend runs rife-v4.6 in PyTorch for compute GPUs without Vulkan.** `SPRITE_GEN_RIFE_BACKEND=torch` runs the same rife-v4.6 in PyTorch (`sprite_gen/video/rife_torch.py`). It serves a GPU the binary cannot run on: rife-ncnn-vulkan needs Vulkan, and a GPU offered for compute alone (CUDA with no Vulkan driver) has none. The network is rife-v4.6's IFNet written again from Practical-RIFE's `IFNet_HDv3` (MIT, notice in NOTICE). Its weights are read out of the binary's own model files (SHA-256 pinned, the binary's float16 weights), with no other download. One run does what one call of the binary does with `-x -z`. The pair is turned eight ways and run both ways in time, with flows averaged at each of four levels. The loop follows rife-ncnn-vulkan's `RIFE::process_v4` (MIT, notice in NOTICE). `SPRITE_GEN_RIFE_DEVICE` names `cuda` (default) or `cpu`. `SPRITE_GEN_RIFE_TTA` means the same for both backends. The default augmentation stays `-x -z`. To install: `pip install "sprite-gen[torch]"` (new extra: `torch>=2.13.0,<3`). Then run: `sprite-gen rife install --backend torch` (new flag; defaults to `SPRITE_GEN_RIFE_BACKEND`). This unpacks the model, and makes a check frame through PyTorch on `SPRITE_GEN_RIFE_DEVICE`. It reads the model only, so a Linux ARM machine the binary does not run on is not refused. A CPU-only host installs PyTorch's CPU build first: `pip install torch==2.13.0 --index-url https://download.pytorch.org/whl/cpu` (192 MB, against the CUDA build's 527 MB plus its CUDA libraries). Nothing falls back. With torch chosen the binary is never looked for or run. `cuda` where PyTorch finds no CUDA is refused naming why (a CPU-only PyTorch, or a CUDA that finds no GPU) and does not run on the CPU. `mps` (Apple's GPU) is refused (no lane measures it; on a Mac the binary runs on the GPU already). A backend or device named wrong is refused. A device that fails as the network is put on it or as a frame runs (out of its memory, its driver or CUDA failing) is a RIFE that fails, in PyTorch's own words: the loop fails with its record, and the install's check frame fails. PyTorch not installed, or no model where the backend looks (`SPRITE_GEN_RIFE_MODEL`, else the install root), is RIFE not installed, as the binary missing is. Under `--repair auto` the loop is cut as filmed with the warning, and its record names the torch install line. On CUDA each frame runs with cuDNN deterministic, its benchmark off and convolutions in IEEE float32 (no TF32). The same frame twice is the same bytes on one GPU, driver and PyTorch. What made a frame is the RIFE's identity: backend, model bytes loaded, network code, PyTorch, on CUDA the GPU, driver, CUDA, cuDNN and those settings; on the CPU its instruction set. Because of this identity, `--between-cache` never hands one backend's or GPU's frame to another. Measured on synthetic walkers: Seven walker pairs (clean, outline lost, ghost, torn, a cross-fade to look at) get the same verdicts from the binary on an Apple GPU, the binary on Mesa llvmpipe and the torch backend on a CPU. The torch frame lies 0.005 to 0.052 of 255 on average from the binary's Apple GPU frame. The binary's own llvmpipe frame lies 0.007 to 0.25. A 960 x 960 frame of a synthetic walker with `-x -z`: On an Apple M4 Max CPU (12 threads), 3.3 to 3.6 s; the binary on that Mac's GPU takes 1.27 to 1.37 s. In a Modal container of two CPUs (the app's job size), 22.6 to 28.5 s on two threads; the binary on Mesa llvmpipe in the same container takes 127.7 to 131.5 s. The torch backend's frames are not the binary's bytes, which is one reason the binary stays the default. [loop-repair](docs/loop-repair.md) section 1- **Lane: `scripts/linux_lane.sh` tests PyTorch 2.13.0 CPU after the suite.** After the suite, PyTorch 2.13.0 CPU is installed into the same environment. It runs `sprite-gen rife install --backend torch`'s check frame. It runs every test marked `torch_rife` with `SPRITE_GEN_RIFE_DEVICE=cpu`, with none skipped. `--rife-only` runs the same. `--rife-unmeasured` lets `torch_rife` tests skip as it lets `real_rife` ones. CUDA is not measured by this lane.-- **Tests**: `tests/video/test_rife_torch.py` (the eight ways undo themselves and are the single passes' eight turns; flows of a textured patch run alone each of the sixteen ways and turned back point alike, where a wrong sign, a transpose's x/y, or a backward swap puts one elsewhere; `-z` and `-x` give the same frame the other way in time and flipped; the install check frame's disc lands half way; the model loads strict and other bytes are refused by SHA-256; the same frame twice is the same bytes and the identity names what makes it; seven recorded synthetic walker pairs in `tests/fixtures/rife-walkers` are judged as the binary judged them with no binary, the frame within twice the binary's own GPU-to-GPU gap, and alike to this machine's binary where both run; without PyTorch: torch chosen and not installed is RIFE not installed and the binary is never run, a loop's record names it, a backend or device named wrong is refused before anything is looked for, cuda where there is none is refused, a model not the pinned one is refused; with a runner stood in: reports name rife-torch and count runs, the loop and the alignment name the torch backend, and a frame kept by one runner is not taken for another); `tests/video/test_rife_install.py` (a zip whose model is not the pinned one installs nothing for both backends; `--backend torch` installs on a machine the binary does not run on and checks its frame through torch); `tests/release/test_lane_rife_collection.py` (a test RIFE decides carries `real_rife` or `torch_rife`); new pytest mark `torch_rife` (skipped where PyTorch, the model or the named device is missing).+- **Tests**: `tests/video/test_rife_torch.py` (the eight ways undo themselves and are the single passes' eight turns; flows of a textured patch run alone each of the sixteen ways and turned back point alike, where a wrong sign, a transpose's x/y, or a backward swap puts one elsewhere; `-z` and `-x` give the same frame the other way in time and flipped; the install check frame's disc lands half way; the model loads strict and other bytes are refused by SHA-256; the same frame twice is the same bytes and the identity names what makes it; seven recorded synthetic walker pairs in `tests/fixtures/rife-walkers` are judged as the binary judged them with no binary, the frame within twice the binary's own GPU-to-GPU gap, and alike to this machine's binary where both run; a device that fails as the network is put on it or as a frame runs (out of its memory, its driver, CUDA not starting, a CUDA call deferred to its start) is a RIFE that fails in PyTorch's words, a TypeError there is raised as it is, a loop whose device fails as the network is put on it fails with its record, and the install's check frame fails; without PyTorch: torch chosen and not installed is RIFE not installed and the binary is never run, a loop's record names it, a backend or device named wrong is refused before anything is looked for, cuda where there is none is refused, a model not the pinned one is refused; with a runner stood in: reports name rife-torch and count runs, the loop and the alignment name the torch backend, and a frame kept by one runner is not taken for another); `tests/video/test_rife_install.py` (a zip whose model is not the pinned one installs nothing for both backends; `--backend torch` installs on a machine the binary does not run on and checks its frame through torch); `tests/release/test_lane_rife_collection.py` (a test RIFE decides carries `real_rife` or `torch_rife`); new pytest mark `torch_rife` (skipped where PyTorch, the model or the named device is missing).## v2.45.2 - The new `video-loop --overlap-wrap off` turns the overlapped wrap off on its own; the motion anchor's fine search is faster and gives the same valuesdiff --git a/docs/loop-repair.md b/docs/loop-repair.mdindex e67e0cb..14a2e72 100644--- a/docs/loop-repair.md+++ b/docs/loop-repair.md@@ -63,8 +63,9 @@ not chosen for you and not traded for another: `cuda` where PyTorch finds no CUDwhy (a PyTorch built for the CPU only, or a CUDA that finds no GPU), and does not run on the CPU.Apple's GPU (`mps`) is refused: no release lane measures it, and on a Mac the binary already runs onthe GPU. PyTorch not installed, or no model where it looks, is RIFE not installed ("Without RIFE"-below); a backend or device named wrong, a model whose files are not the pinned ones, or a run that-fails on the device, is a RIFE that fails.+below); a backend or device named wrong, a model whose files are not the pinned ones, or a device+that fails as the network is put on it or as a frame runs (out of its memory, its driver or CUDA+failing), is a RIFE that fails, in PyTorch's own words.On CUDA every frame runs with cuDNN deterministic, its benchmark off and its convolutions in IEEEfloat32 (`torch.backends.cudnn.conv.fp32_precision = "ieee"`: PyTorch turns TF32 on by default), so thediff --git a/sprite_gen/video/rife_torch.py b/sprite_gen/video/rife_torch.pyindex d67ed75..bb0e85c 100644--- a/sprite_gen/video/rife_torch.py+++ b/sprite_gen/video/rife_torch.py@@ -56,6 +56,12 @@ LAYERS = tuple(f"block{i}.{name}" for i in range(len(BLOCKS))for name in ("conv0.0.0", "conv0.1.0", *(f"convblock.{j}.conv" for j in range(8)), "lastconv.0"))NCNN_FLOAT16 = 0x01306B47 # ncnn's tag before a float16 weight blob; a float32 one is tagged 0NVIDIA_VERSION = Path("/proc/driver/nvidia/version")+# A device that fails, as the network is put on it or as a frame runs on it, is a RIFE that fails (`rife.RifeUnavailable`),+# PyTorch's words kept: out of its memory (`torch.OutOfMemoryError`), its driver failing on a call (`torch.AcceleratorError`)+# and CUDA that does not start are each a RuntimeError; a CUDA call queued before CUDA started that failed when it did is+# `torch.cuda.DeferredCudaCallError`, an Exception. Anything else (a TypeError, an AttributeError) is a fault of this code,+# raised as it is.+DEVICE_FAILURES = (RuntimeError, torch.cuda.DeferredCudaCallError)def _conv(cin: int, cout: int) -> nn.Sequential:@@ -225,7 +231,8 @@ class TorchRunner:`rife.pass_runs`). What its frames depend on is read once, as it loaded and set them, and stays for its life(`identity`): the weights' bytes, this network's code, PyTorch's version, and on CUDA its CUDA and cuDNN, the GPU,the driver and the settings that make a frame the same bytes; on the CPU the instructions PyTorch runs on.- `cuda` that is not there is refused, by why (`rife.RifeUnavailable`)."""+ `cuda` that is not there is refused, by why, and a device that fails as the network is put on it, or as a frame runs,+ is a RIFE that fails in PyTorch's words (`DEVICE_FAILURES`, `rife.RifeUnavailable`)."""def __init__(self, model: Path, device: str):if device not in rife.DEVICES:@@ -236,22 +243,27 @@ class TorchRunner:raise rife.RifeUnavailable(f"SPRITE_GEN_RIFE_DEVICE=cuda, and CUDA is not available here: {wheel}; nothing runs ""on another device in its place — name SPRITE_GEN_RIFE_DEVICE=cpu to run on the CPU")files = rife.model_bytes(model)- net = IFNet()try:+ net = IFNet()net.load_state_dict(state_from_ncnn(files), strict=True)except (ValueError, RuntimeError) as exc:raise rife.RifeUnavailable(f"rife-torch: the model {model} does not load: {exc}") from excself.model, self.device = model, device- self.net = net.to(device).eval()- self.blocks = tuple(getattr(self.net, f"block{i}") for i in range(len(BLOCKS)))- self._grids: dict[tuple, torch.Tensor] = {}ident: dict[str, object] = {"backend": "torch", "device": device, "net": CODE_SHA256, "torch": torch.__version__,"weights": {name: hashlib.sha256(data).hexdigest() for name, data in files.items()}}- if device == "cuda":- ident.update(cuda=torch.version.cuda, cudnn=torch.backends.cudnn.version(), gpu=torch.cuda.get_device_name(),- capability=list(torch.cuda.get_device_capability()), driver=_driver(), determinism=_deterministic())- else: # a frame made on the CPU is made by its instructions; one made on a GPU is not, and its host's CPU is no part of it- ident.update(cpu=torch.backends.cpu.get_cpu_capability(), arch=platform.machine())+ try:+ self.net = net.to(device).eval()+ if device == "cuda":+ ident.update(cuda=torch.version.cuda, cudnn=torch.backends.cudnn.version(), gpu=torch.cuda.get_device_name(),+ capability=list(torch.cuda.get_device_capability()), driver=_driver(), determinism=_deterministic())+ else:+ # a frame made on the CPU is made by its instructions; one made on a GPU is not, and its host's CPU is no+ # part of it+ ident.update(cpu=torch.backends.cpu.get_cpu_capability(), arch=platform.machine())+ except DEVICE_FAILURES as exc:+ raise rife.RifeUnavailable(f"rife-torch on {device} failed to set up: {exc}") from exc+ self.blocks = tuple(getattr(self.net, f"block{i}") for i in range(len(BLOCKS)))+ self._grids: dict[tuple, torch.Tensor] = {}self._identity = identdef identity(self) -> dict[str, object]:@@ -276,11 +288,11 @@ class TorchRunner:def run(self, x: np.ndarray, y: np.ndarray, t: float, modes: tuple[str, ...] | None) -> np.ndarray:"""One run, as one call of the binary makes it (`rife.Run`): `t` as the binary is handed it (`-s`, fourdecimals), the augmentation `modes` (None: `rife.tta()`). A run that fails on the device (out of its memory) is- a RIFE that fails (`rife.RifeUnavailable`)."""+ a RIFE that fails (`DEVICE_FAILURES`, `rife.RifeUnavailable`)."""modes = rife.tta() if modes is None else modestry:return self._run(x, y, float(f"{t:.4f}"), tuple(modes))- except RuntimeError as exc:+ except DEVICE_FAILURES as exc:raise rife.RifeUnavailable(f"rife-torch on {self.device} failed: {exc}") from exc@torch.inference_mode()