Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
test(rife): RIFE's torch backend runs rife-v4.6 as one call of the binary does, from its own model, and nothing falls back (red)
Soohong Kimb8153998a9b4
diff --git a/pyproject.toml b/pyproject.tomlindex fdf59b8..3ef60a7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -73,8 +73,11 @@ pythonpath = ["tests"]timeout = 120# One mark names a test of the real rife-ncnn-vulkan: tests/conftest.py skips it where no RIFE is# reachable, and `scripts/linux_lane.sh --rife-only` runs exactly the marked tests (`-m real_rife`).+# Another names a test of the torch backend: skipped where PyTorch or the rife-v4.6 model is missing, run by+# the lanes with none skipped (`-m torch_rife`, on SPRITE_GEN_RIFE_DEVICE; docs/release.md).markers = ["real_rife: runs the real rife-ncnn-vulkan; skipped where none is reachable, run by `scripts/linux_lane.sh --rife-only`",+ "torch_rife: runs RIFE's torch backend; skipped where PyTorch or the model is missing, run by the lanes with `-m torch_rife`",]# The pipeline ships an importable sprite_gen package. The canonical invocation is thediff --git a/tests/conftest.py b/tests/conftest.pyindex d458133..ad35071 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -113,9 +113,12 @@ def _fail_unmeasured_skip(report: pytest.TestReport | pytest.CollectReport, node@pytest.fixture(autouse=True)def _engine_tta(monkeypatch: pytest.MonkeyPatch) -> None:- """Every test runs the augmentation the engine ships (`rife.TTA`): a SPRITE_GEN_RIFE_TTA left in the- calling shell would change what the real-RIFE tests measure."""+ """Every test runs the augmentation the engine ships (`rife.TTA`) and its backend, the binary: a+ SPRITE_GEN_RIFE_TTA or SPRITE_GEN_RIFE_BACKEND left in the calling shell would change what the real-RIFE+ tests measure. SPRITE_GEN_RIFE_DEVICE stays: it names where the torch backend's tests run."""monkeypatch.delenv("SPRITE_GEN_RIFE_TTA", raising=False)+ monkeypatch.delenv("SPRITE_GEN_RIFE_BACKEND", raising=False)+@pytest.hookimpl(wrapper=True)diff --git a/tests/fixtures/rife-walkers/bfar33.a.png b/tests/fixtures/rife-walkers/bfar33.a.pngnew file mode 100644index 0000000..3239182Binary files /dev/null and b/tests/fixtures/rife-walkers/bfar33.a.png differdiff --git a/tests/fixtures/rife-walkers/bfar33.b.png b/tests/fixtures/rife-walkers/bfar33.b.pngnew file mode 100644index 0000000..fa7ad8aBinary files /dev/null and b/tests/fixtures/rife-walkers/bfar33.b.png differdiff --git a/tests/fixtures/rife-walkers/bfar33.ncnn.png b/tests/fixtures/rife-walkers/bfar33.ncnn.pngnew file mode 100644index 0000000..4f3fd67Binary files /dev/null and b/tests/fixtures/rife-walkers/bfar33.ncnn.png differdiff --git a/tests/fixtures/rife-walkers/bfar50.a.png b/tests/fixtures/rife-walkers/bfar50.a.pngnew file mode 100644index 0000000..3239182Binary files /dev/null and b/tests/fixtures/rife-walkers/bfar50.a.png differdiff --git a/tests/fixtures/rife-walkers/bfar50.b.png b/tests/fixtures/rife-walkers/bfar50.b.pngnew file mode 100644index 0000000..fa7ad8aBinary files /dev/null and b/tests/fixtures/rife-walkers/bfar50.b.png differdiff --git a/tests/fixtures/rife-walkers/bfar50.ncnn.png b/tests/fixtures/rife-walkers/bfar50.ncnn.pngnew file mode 100644index 0000000..cd0f9f0Binary files /dev/null and b/tests/fixtures/rife-walkers/bfar50.ncnn.png differdiff --git a/tests/fixtures/rife-walkers/bnear50.a.png b/tests/fixtures/rife-walkers/bnear50.a.pngnew file mode 100644index 0000000..d137f21Binary files /dev/null and b/tests/fixtures/rife-walkers/bnear50.a.png differdiff --git a/tests/fixtures/rife-walkers/bnear50.b.png b/tests/fixtures/rife-walkers/bnear50.b.pngnew file mode 100644index 0000000..1437f31Binary files /dev/null and b/tests/fixtures/rife-walkers/bnear50.b.png differdiff --git a/tests/fixtures/rife-walkers/bnear50.ncnn.png b/tests/fixtures/rife-walkers/bnear50.ncnn.pngnew file mode 100644index 0000000..96bfacaBinary files /dev/null and b/tests/fixtures/rife-walkers/bnear50.ncnn.png differdiff --git a/tests/fixtures/rife-walkers/cross50.a.png b/tests/fixtures/rife-walkers/cross50.a.pngnew file mode 100644index 0000000..86d0bf5Binary files /dev/null and b/tests/fixtures/rife-walkers/cross50.a.png differdiff --git a/tests/fixtures/rife-walkers/cross50.b.png b/tests/fixtures/rife-walkers/cross50.b.pngnew file mode 100644index 0000000..bb5f031Binary files /dev/null and b/tests/fixtures/rife-walkers/cross50.b.png differdiff --git a/tests/fixtures/rife-walkers/cross50.ncnn.png b/tests/fixtures/rife-walkers/cross50.ncnn.pngnew file mode 100644index 0000000..bf91e01Binary files /dev/null and b/tests/fixtures/rife-walkers/cross50.ncnn.png differdiff --git a/tests/fixtures/rife-walkers/far50.a.png b/tests/fixtures/rife-walkers/far50.a.pngnew file mode 100644index 0000000..4c7a9ebBinary files /dev/null and b/tests/fixtures/rife-walkers/far50.a.png differdiff --git a/tests/fixtures/rife-walkers/far50.b.png b/tests/fixtures/rife-walkers/far50.b.pngnew file mode 100644index 0000000..bb5f031Binary files /dev/null and b/tests/fixtures/rife-walkers/far50.b.png differdiff --git a/tests/fixtures/rife-walkers/far50.ncnn.png b/tests/fixtures/rife-walkers/far50.ncnn.pngnew file mode 100644index 0000000..bb2b02cBinary files /dev/null and b/tests/fixtures/rife-walkers/far50.ncnn.png differdiff --git a/tests/fixtures/rife-walkers/mid50.a.png b/tests/fixtures/rife-walkers/mid50.a.pngnew file mode 100644index 0000000..4c7a9ebBinary files /dev/null and b/tests/fixtures/rife-walkers/mid50.a.png differdiff --git a/tests/fixtures/rife-walkers/mid50.b.png b/tests/fixtures/rife-walkers/mid50.b.pngnew file mode 100644index 0000000..86d0bf5Binary files /dev/null and b/tests/fixtures/rife-walkers/mid50.b.png differdiff --git a/tests/fixtures/rife-walkers/mid50.ncnn.png b/tests/fixtures/rife-walkers/mid50.ncnn.pngnew file mode 100644index 0000000..13fb465Binary files /dev/null and b/tests/fixtures/rife-walkers/mid50.ncnn.png differdiff --git a/tests/fixtures/rife-walkers/near25.a.png b/tests/fixtures/rife-walkers/near25.a.pngnew file mode 100644index 0000000..145cce1Binary files /dev/null and b/tests/fixtures/rife-walkers/near25.a.png differdiff --git a/tests/fixtures/rife-walkers/near25.b.png b/tests/fixtures/rife-walkers/near25.b.pngnew file mode 100644index 0000000..516e935Binary files /dev/null and b/tests/fixtures/rife-walkers/near25.b.png differdiff --git a/tests/fixtures/rife-walkers/near25.ncnn.png b/tests/fixtures/rife-walkers/near25.ncnn.pngnew file mode 100644index 0000000..91ce266Binary files /dev/null and b/tests/fixtures/rife-walkers/near25.ncnn.png differdiff --git a/tests/fixtures/rife-walkers/walkers.json b/tests/fixtures/rife-walkers/walkers.jsonnew file mode 100644index 0000000..4dbafe3--- /dev/null+++ b/tests/fixtures/rife-walkers/walkers.json@@ -0,0 +1,258 @@+{+ "frames": "rife-ncnn-vulkan 20221029, rife-v4.6, -x -z (the engine's rife.Rife), on an Apple M4 Max GPU (MoltenVK)",+ "gpu_gap": "the same binary's frame of the pair on Mesa llvmpipe against this one: premultiplied RGBA 0..255 inside the box either covers, mean and largest absolute difference",+ "pairs": {+ "near25": {+ "walker": "tests/video/test_rife.py _walker",+ "legs": [+ [+ 10,+ -10+ ],+ [+ 4,+ -4+ ]+ ],+ "t": 0.25,+ "sha256": {+ "a": "c07f8d42865a544f404ade340019101e79bf345043d2500b7957745988100d95",+ "b": "9ee8ef549f6c991a9cb8a3ef40fb04337e886eac0ec31b1505410c0a4e7e7384",+ "ncnn": "dc787aca55fa64456401d94486dfef38975987b651d5e339085a73cb622a604a"+ },+ "faults": [],+ "looks": [],+ "measure": {+ "dark_excess": -0.01238,+ "partial_excess": 0.01815,+ "outline_loss": 0.0,+ "outline_shift": 0.0,+ "ghost": 0.0,+ "crossfade": 0.0,+ "torn": 0.08203+ },+ "gpu_gap": {+ "mean_abs": 0.0131,+ "max_abs": 2.0+ }+ },+ "mid50": {+ "walker": "tests/video/test_rife.py _walker",+ "legs": [+ [+ 20,+ -20+ ],+ [+ 8,+ -8+ ]+ ],+ "t": 0.5,+ "sha256": {+ "a": "303140af493632e85c083cd471fd3d006a6f63113dc0bf354a16b1df2dceb2e4",+ "b": "de4aeab6f5cc2e527bec86fc1d4c6eceecd9863ebf5ba19d082e8fd6023bfa62",+ "ncnn": "0ed5d2dcc0006134defac6a5c954bf480750d004d856d9724330304d11681589"+ },+ "faults": [+ "torn"+ ],+ "looks": [],+ "measure": {+ "dark_excess": -0.01731,+ "partial_excess": 0.02714,+ "outline_loss": 0.00187,+ "outline_shift": 0.00187,+ "ghost": 0.0,+ "crossfade": 0.0,+ "torn": 0.39453+ },+ "gpu_gap": {+ "mean_abs": 0.0274,+ "max_abs": 4.0+ }+ },+ "far50": {+ "walker": "tests/video/test_rife.py _walker",+ "legs": [+ [+ 20,+ -20+ ],+ [+ -5,+ 5+ ]+ ],+ "t": 0.5,+ "sha256": {+ "a": "303140af493632e85c083cd471fd3d006a6f63113dc0bf354a16b1df2dceb2e4",+ "b": "d5bd7a3e9ed8fe69d81ea8c404a0d6dd0d0e41f835dfaeb3ff9e1d73192f043b",+ "ncnn": "5394303cbaf23ddff0e623e3efc548ca153ea21c1db8be851b573876a58f5c88"+ },+ "faults": [+ "outline",+ "torn"+ ],+ "looks": [],+ "measure": {+ "dark_excess": -0.00717,+ "partial_excess": 0.0346,+ "outline_loss": 0.25856,+ "outline_shift": 0.25856,+ "ghost": 0.00028,+ "crossfade": 0.0,+ "torn": 0.66797+ },+ "gpu_gap": {+ "mean_abs": 0.056,+ "max_abs": 6.0+ }+ },+ "cross50": {+ "walker": "tests/video/test_rife.py _walker",+ "legs": [+ [+ 8,+ -8+ ],+ [+ -5,+ 5+ ]+ ],+ "t": 0.5,+ "sha256": {+ "a": "de4aeab6f5cc2e527bec86fc1d4c6eceecd9863ebf5ba19d082e8fd6023bfa62",+ "b": "d5bd7a3e9ed8fe69d81ea8c404a0d6dd0d0e41f835dfaeb3ff9e1d73192f043b",+ "ncnn": "fff204462782c10947fe10c5077c7487d2bbde74eceb5685f13150edd1b98cfd"+ },+ "faults": [],+ "looks": [],+ "measure": {+ "dark_excess": -0.02292,+ "partial_excess": 0.01616,+ "outline_loss": 0.0,+ "outline_shift": 0.0,+ "ghost": 0.0,+ "crossfade": 0.0,+ "torn": 0.11719+ },+ "gpu_gap": {+ "mean_abs": 0.0188,+ "max_abs": 3.0+ }+ },+ "bnear50": {+ "walker": "tests/video/test_crossfade.py _walker, outline BLACK, boot LIGHT_BOOTS, s=2",+ "legs": [+ [+ 10,+ -10+ ],+ [+ 5,+ -5+ ]+ ],+ "t": 0.5,+ "sha256": {+ "a": "52f37a7859f61079d4a25f5f5bd57043e288313856e4e454c64622332bfe5d4d",+ "b": "55007d88aceeaa251ed58b5f9c6c1122121dc66185d0f3873ecd9b3eb3bff6b7",+ "ncnn": "9a9305ea78d41dd4a08a49515f8ada3dc17638622bcbe5bce1d4773b010de441"+ },+ "faults": [],+ "looks": [],+ "measure": {+ "dark_excess": -0.01153,+ "partial_excess": 0.0072,+ "outline_loss": 0.0,+ "outline_shift": 0.0,+ "ghost": 0.0,+ "crossfade": 0.0,+ "torn": 0.0+ },+ "gpu_gap": {+ "mean_abs": 0.0067,+ "max_abs": 2.0+ }+ },+ "bfar50": {+ "walker": "tests/video/test_crossfade.py _walker, outline BLACK, boot LIGHT_BOOTS, s=2",+ "legs": [+ [+ 20,+ -20+ ],+ [+ -5,+ 5+ ]+ ],+ "t": 0.5,+ "sha256": {+ "a": "2c245a60dd282fc824bb009a2e952271246c547ab49183474ef2e1fa0762c303",+ "b": "fa7a2677636c987b9f984752197b8aa82f39ebf958f4a9459699dfef4c70f8a7",+ "ncnn": "4dc2a1cde3c1265f81e332022c023b7fbef7c6c5374a738797a7a736e071537e"+ },+ "faults": [+ "outline",+ "ghost",+ "torn"+ ],+ "looks": [+ "crossfade"+ ],+ "measure": {+ "dark_excess": -0.02254,+ "partial_excess": 0.0237,+ "outline_loss": 0.12573,+ "outline_shift": 0.12573,+ "ghost": 0.00427,+ "crossfade": 0.05412,+ "torn": 0.89906+ },+ "gpu_gap": {+ "mean_abs": 0.2471,+ "max_abs": 71.0+ }+ },+ "bfar33": {+ "walker": "tests/video/test_crossfade.py _walker, outline BLACK, boot LIGHT_BOOTS, s=2",+ "legs": [+ [+ 20,+ -20+ ],+ [+ -5,+ 5+ ]+ ],+ "t": 0.3333,+ "sha256": {+ "a": "2c245a60dd282fc824bb009a2e952271246c547ab49183474ef2e1fa0762c303",+ "b": "fa7a2677636c987b9f984752197b8aa82f39ebf958f4a9459699dfef4c70f8a7",+ "ncnn": "38dacfe35e5719f806d18977d1a994496e06abe130613814c886a5846c79d807"+ },+ "faults": [+ "outline",+ "torn"+ ],+ "looks": [],+ "measure": {+ "dark_excess": -0.01883,+ "partial_excess": 0.0185,+ "outline_loss": 0.13247,+ "outline_shift": 0.13247,+ "ghost": 7e-05,+ "crossfade": 0.0,+ "torn": 0.75546+ },+ "gpu_gap": {+ "mean_abs": 0.2395,+ "max_abs": 76.0+ }+ }+ }+}diff --git a/tests/video/test_rife_install.py b/tests/video/test_rife_install.pyindex 54c0e41..d269e9d 100644--- a/tests/video/test_rife_install.py+++ b/tests/video/test_rife_install.py@@ -13,6 +13,7 @@ import sysimport zipfilefrom pathlib import Path+import numpy as npimport pytestfrom sprite_gen import cli@@ -23,28 +24,36 @@ TOP = f"rife-ncnn-vulkan-{rife.RELEASE}-{PLATFORM}"BINARY = rife.installed_binary(Path("."), PLATFORM).name-def _release_zip(tmp_path: Path, *, model: bool = True) -> Path:- path = tmp_path / rife_install.zip_name(PLATFORM)+# The fixture zip's model files, which its pin names in place of rife-v4.6's (`rife.MODEL_SHA256`).+MODEL_FILES = {"flownet.param": b"param\n", "flownet.bin": b"bin\n"}+++def _release_zip(tmp_path: Path, *, model: bool = True, platform: str = PLATFORM) -> Path:+ path = tmp_path / rife_install.zip_name(platform)+ top, binary = f"rife-ncnn-vulkan-{rife.RELEASE}-{platform}", rife.installed_binary(Path("."), platform).namewith zipfile.ZipFile(path, "w") as zf:- zf.writestr(f"{TOP}/", "")- zf.writestr(f"{TOP}/{BINARY}", "#!/bin/sh\nexit 0\n")- zf.writestr(f"{TOP}/LICENSE", "MIT\n")- zf.writestr(f"{TOP}/README.md", "readme\n")+ zf.writestr(f"{top}/", "")+ zf.writestr(f"{top}/{binary}", "#!/bin/sh\nexit 0\n")+ zf.writestr(f"{top}/LICENSE", "MIT\n")+ zf.writestr(f"{top}/README.md", "readme\n")if model:- zf.writestr(f"{TOP}/{rife.MODEL}/flownet.param", "param\n")- zf.writestr(f"{TOP}/{rife.MODEL}/flownet.bin", "bin\n")- zf.writestr(f"{TOP}/rife-v4/flownet.bin", "another model\n") # not what the engine runs- zf.writestr(f"{TOP}/{rife.MODEL}/../../escape.txt", "outside\n")+ for name, data in MODEL_FILES.items():+ zf.writestr(f"{top}/{rife.MODEL}/{name}", data)+ zf.writestr(f"{top}/rife-v4/flownet.bin", "another model\n") # not what the engine runs+ zf.writestr(f"{top}/{rife.MODEL}/../../escape.txt", "outside\n")zf.writestr("elsewhere/rife-ncnn-vulkan", "not in the release folder\n")return path@pytest.fixturedef pinned(monkeypatch, tmp_path):- """The fixture zip, with its SHA-256 as the pinned one, and the engine looking only at tmp_path."""+ """The fixture zip, with its SHA-256 and its model's as the pinned ones, and the engine looking only at tmp_path."""(tmp_path / "zips").mkdir()path = _release_zip(tmp_path / "zips")monkeypatch.setitem(rife_install.ZIP_SHA256, PLATFORM, hashlib.sha256(path.read_bytes()).hexdigest())+ monkeypatch.setattr(rife, "MODEL_SHA256", {name: hashlib.sha256(data).hexdigest() for name, data in MODEL_FILES.items()},+ raising=False)+ monkeypatch.delenv("SPRITE_GEN_RIFE_BACKEND", raising=False)monkeypatch.setenv("SPRITE_GEN_DATA_DIR", str(tmp_path / "data"))monkeypatch.delenv("SPRITE_GEN_RIFE", raising=False)monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL", raising=False)@@ -133,3 +142,58 @@ def test_a_platform_without_a_release_build_is_refused(monkeypatch):monkeypatch.setattr(rife, "platform_release", lambda: "")with pytest.raises(SystemExit, match="ships no build"):rife_install.install(run_check=False)++[email protected]("backend", ["ncnn", "torch"])+def test_a_zip_whose_model_is_not_the_pinned_one_installs_nothing(pinned, tmp_path, monkeypatch, backend):+ """Its hash checked, the zip unpacked, the model's two files are checked too (`rife.MODEL_SHA256`), for either backend:+ a model that is not the one pinned is named with what it is and what was expected, and nothing is installed."""+ monkeypatch.setattr(rife, "MODEL_SHA256", {**rife.MODEL_SHA256, "flownet.bin": "0" * 64}, raising=False)+ with pytest.raises(SystemExit, match=r"flownet.bin has sha256 [0-9a-f]{64}, expected 0{64}.*nothing was installed"):+ rife_install.install(zip_path=pinned, platform=PLATFORM, run_check=False, backend=backend)+ assert not (tmp_path / "data" / "rife" / TOP).exists()+++class _Halfway:+ """A torch runner stood in: the frame between is the first disc moved half the 36 px to the second (the check's discs)."""++ def __init__(self, model: Path):+ self.model = model++ def frame(self, colour, cover, t):+ return np.roll(colour[0], 18, axis=1), np.roll(cover[0], 18, axis=1)++ def identity(self):+ return {"backend": "torch"}++ def describe(self):+ return {"kind": "rife-torch", "device": "cpu", "model": self.model.name}+++def test_the_torch_backend_installs_where_the_binary_does_not_run_and_checks_its_frame_through_torch(monkeypatch, tmp_path, capsys):+ """`--backend torch` (or SPRITE_GEN_RIFE_BACKEND=torch, which it defaults to) reads the zip's model only: on a Linux+ machine its x86-64 binary does not run on, it is not refused as the binary's install is; the model's files are checked;+ the check frame is made through the torch backend from the model just installed — the binary in it never runs (it makes+ no frame) — and the report names the model the engine will read."""+ monkeypatch.setattr(rife, "platform_release", lambda: "ubuntu")+ monkeypatch.setattr(rife_install.platform_mod, "machine", lambda: "aarch64")+ monkeypatch.setenv("SPRITE_GEN_DATA_DIR", str(tmp_path / "data"))+ for name in ("SPRITE_GEN_RIFE", "SPRITE_GEN_RIFE_MODEL", "SPRITE_GEN_RIFE_BACKEND"):+ monkeypatch.delenv(name, raising=False)+ (tmp_path / "zips").mkdir()+ zipped = _release_zip(tmp_path / "zips", platform="ubuntu")+ monkeypatch.setitem(rife_install.ZIP_SHA256, "ubuntu", hashlib.sha256(zipped.read_bytes()).hexdigest())+ monkeypatch.setattr(rife, "MODEL_SHA256", {name: hashlib.sha256(data).hexdigest() for name, data in MODEL_FILES.items()},+ raising=False)+ with pytest.raises(SystemExit, match="x86-64 only and this machine is aarch64"):+ rife_install.install(zip_path=zipped, run_check=False)+ asked = []+ monkeypatch.setattr(rife, "torch_runner", lambda model=None: asked.append(model) or _Halfway(model), raising=False)+ report = rife_install.install(zip_path=zipped, backend="torch")+ model = (tmp_path / "data" / "rife" / f"rife-ncnn-vulkan-{rife.RELEASE}-ubuntu" / rife.MODEL).resolve()+ assert report["backend"] == "torch" and report["installed"] == "now" and asked == [model]+ assert report["check"] == {"passed": True, "disc_centre_x": 48.0}+ assert report["engine_finds"] == str(model) and "note" not in report+ monkeypatch.setenv("SPRITE_GEN_RIFE_BACKEND", "torch")+ assert cli.main(["rife", "install", "--zip", str(zipped)]) == 0+ assert json.loads(capsys.readouterr().out)["backend"] == "torch" and len(asked) == 2diff --git a/tests/video/test_rife_torch.py b/tests/video/test_rife_torch.pynew file mode 100644index 0000000..7eea060--- /dev/null+++ b/tests/video/test_rife_torch.py@@ -0,0 +1,422 @@+# SPDX-License-Identifier: Apache-2.0+"""RIFE's torch backend (docs/loop-repair.md section 1): rife-v4.6 in PyTorch, from the binary's own model, run as one+call of the binary runs it — the pair turned eight ways and run both ways in time, their flows averaged at every level.++Chosen by SPRITE_GEN_RIFE_BACKEND=torch, on the device SPRITE_GEN_RIFE_DEVICE names. Nothing falls back: with torch chosen+the binary is never run, a device that cannot be had is not traded for another, and PyTorch missing is RIFE not+installed, its reason named.++The tests marked `torch_rife` run the network: they need PyTorch and the rife-v4.6 model (`rife.locate_model()`), are+skipped where either is missing (tests/conftest.py) and run with none skipped by the lanes (`-m torch_rife`,+docs/release.md), on the device SPRITE_GEN_RIFE_DEVICE names. The rest need neither and stand a runner in where one runs.++The fixtures are synthetic: discs, legs and walkers drawn here or in tests/video/test_rife.py and test_crossfade.py,+and tests/fixtures/rife-walkers — walker pairs, clean and faulty, with the binary's own -x -z frame of each made on+an Apple GPU, the engine's verdict on it, and how far the same binary's frame on Mesa llvmpipe lay from it."""++from __future__ import annotations++import hashlib+import json+import sys+from pathlib import Path++import numpy as np+import pytest+from PIL import Image++from sprite_gen.video import align, rife, rife_install+from sprite_gen.video.interpolation_quality import faults, looks+from tests.video.test_rife import _disc, _legs, _marked, _recording_binary++WALKERS = Path(__file__).resolve().parents[1] / "fixtures" / "rife-walkers"++[email protected](scope="module")+def runner():+ """The torch backend on SPRITE_GEN_RIFE_DEVICE, from the installed model."""+ from sprite_gen.video import rife_torch++ return rife_torch.TorchRunner(rife.locate_model(), rife.device())+++def _key(x: np.ndarray) -> tuple[tuple[int, ...], bytes]:+ return x.shape, np.ascontiguousarray(x).tobytes()++[email protected]_rife+def test_the_eight_ways_turn_back_and_are_the_eight_turns_of_the_single_passes():+ """`-x`'s eight ways (`rife_torch._geo`) are each undone by `_geo_back`, and they are the eight flips and transposes the+ single passes turn the pair (`rife.PASS_GEOMETRIES`): none of them missing, none twice."""+ import torch++ from sprite_gen.video import rife_torch++ x = np.asarray(_marked(40))[..., :3].copy() # no flip or transpose of it is itself+ image = torch.from_numpy(x.transpose(2, 0, 1).copy())[None]+ ways = set()+ for g in range(8):+ turned = rife_torch._geo(image, g)+ assert torch.equal(rife_torch._geo_back(turned, g), image)+ ways.add(_key(turned[0].permute(1, 2, 0).numpy()))+ assert len(ways) == 8 and ways == {_key(rife._turned(x, geometry)) for geometry in rife.PASS_GEOMETRIES}+++def _patch(cx: int) -> Image.Image:+ """A square of noise 36 px wide (3 px cells, the same each time) centred at (cx, 48) on transparency: every pixel of it+ a feature a flow can follow, where the inside of a flat disc gives the flow nothing to hold."""+ cells = (np.random.default_rng(7).random((12, 12, 3)) * 255).astype(np.uint8)+ im = np.zeros((96, 128, 4), dtype=np.uint8)+ im[30:66, cx - 18:cx + 18] = np.dstack([np.kron(cells, np.ones((3, 3, 1), np.uint8)), np.full((36, 36), 255, np.uint8)])+ return Image.fromarray(im, "RGBA")++[email protected]_rife+def test_flows_turned_back_from_every_way_point_alike(runner):+ """Five fields of different values turned to each of the sixteen ways (eight turns, each both ways in time, the backward+ swapped) and turned back are themselves. And a patch moving right, run alone each of the sixteen ways with its flows+ turned back to the pair's own frame: at t = 0.25 it stands 8 px past where it was in a and 24 px short of where it is in+ b, and every way's flows say so — the flow to a pointing back left, the one to b on to the right, both level, the mask+ taking the nearer frame (a). A sign turned the wrong way for one turn, x and y not swapped for a transpose, or a backward+ run's flows or mask not swapped, puts that way's reading elsewhere."""+ import torch++ from sprite_gen.video import rife_torch as rt++ field = torch.arange(1.0, 6.0).view(1, 5, 1, 1).expand(1, 5, 6, 10).contiguous()+ for g in range(8):+ for d in (0, 1):+ turn = rt._swap if d else (lambda c: c)+ assert torch.equal(turn(rt._to_canon(rt._from_canon(turn(field), g), g)), field)+ colour, _ = rife.inputs(_patch(40), _patch(72)) # 96 x 128, a multiple of 32: no padding+ pads = [runner._pad(c) for c in colour]+ with torch.inference_mode():+ flows = [runner._infer(pads, 0.25, [(g, d)], flows=True)[1][0][0].cpu().numpy() for g in range(8) for d in (0, 1)]+ yy, xx = np.mgrid[:96, :128]+ on = (np.abs(yy - 48) <= 12) & (np.abs(xx - 48) <= 12) # inside the patch where it stands at t+ x0, y0, x1, y1, mask = np.array([[f[c][on].mean() for c in range(5)] for f in flows]).T+ assert np.all(np.abs(x0 + 8) < 2) and np.all(np.abs(x1 - 24) < 2), (x0, x1)+ assert np.all(np.abs(y0) < 1) and np.all(np.abs(y1) < 1), (y0, y1)+ assert np.all(mask > 0.5), mask++[email protected]_rife+def test_a_frame_is_the_same_made_the_other_way_in_time_or_turned(runner):+ """`-z`: the frame from a to b at t is the frame from b to a at 1 - t. `-x`: the frame of the pair flipped left-right+ is the frame flipped. Each to within a level of a channel (the order of a mean's terms)."""+ colour, _ = rife.inputs(_marked(40), _marked(72))+ there, back = runner.run(colour[0], colour[1], 0.25, ("-z",)), runner.run(colour[1], colour[0], 0.75, ("-z",))+ assert np.abs(there.astype(int) - back.astype(int)).max() <= 1+ flipped = runner.run(colour[0][:, ::-1].copy(), colour[1][:, ::-1].copy(), 0.25, ("-x",))+ assert np.abs(flipped[:, ::-1].astype(int) - runner.run(colour[0], colour[1], 0.25, ("-x",)).astype(int)).max() <= 1++[email protected]_rife[email protected]("named", [None, ""])+def test_the_frame_between_two_discs_lands_half_way(runner, monkeypatch, named):+ """`sprite-gen rife install`'s check frame through the torch backend, with the augmentation every call asks for and+ with none: the disc lands half way (x 48), not cross-faded at both ends."""+ if named is not None:+ monkeypatch.setenv("SPRITE_GEN_RIFE_TTA", named)+ mid = rife.Rife(runner=runner)(rife_install._disc(30), rife_install._disc(66), 0.5)+ xs = np.nonzero(np.asarray(mid)[..., 3] > 127)[1]+ assert abs(xs.mean() - 48) <= 4++[email protected]_rife+def test_the_model_loads_whole_and_any_other_bytes_are_refused_by_sha256(tmp_path):+ """The installed model fills every weight of the network and no other (loaded strict). A copy with one byte changed, a+ flownet.bin cut short or a flownet.param changed is refused by its sha256, the file named, before a weight is read."""+ import shutil++ from sprite_gen.video import rife_torch++ model = rife.locate_model()+ assert set(rife_torch.state_from_ncnn(rife.model_bytes(model))) == set(rife_torch.IFNet().state_dict())+ for k, (name, change) in enumerate((("flownet.bin", lambda b: b[:100] + bytes([b[100] ^ 1]) + b[101:]),+ ("flownet.bin", lambda b: b[: len(b) // 2]),+ ("flownet.param", lambda b: b.replace(b"Convolution", b"Convolutiom", 1)))):+ copy = shutil.copytree(model, tmp_path / str(k) / rife.MODEL)+ (copy / name).write_bytes(change((copy / name).read_bytes()))+ with pytest.raises(rife.RifeUnavailable, match=rf"{name} has sha256 [0-9a-f]{{64}}, expected {rife.MODEL_SHA256[name]}"):+ rife_torch.TorchRunner(copy, "cpu")++[email protected]_rife+def test_the_same_frame_twice_is_the_same_bytes_and_the_identity_names_what_makes_it(runner):+ """The same pair made twice is the same bytes on the device. Its runner's identity names the backend, the device, the+ weights it loaded by sha256, the network's code and PyTorch's version; on CUDA the GPU and the settings that make a+ frame the same bytes, as they read back (cuDNN deterministic, its benchmark off, its convolutions in IEEE float32), and+ no CPU; on the CPU the instructions it runs."""+ import torch++ from sprite_gen.video import rife_torch++ made = rife.Rife(runner=runner)+ a, b = _legs(40, 64), _legs(64, 52)+ assert made(a, b, 0.5).tobytes() == made(a, b, 0.5).tobytes()+ ident = runner.identity()+ assert (ident["backend"], ident["device"], ident["weights"]) == ("torch", rife.device(), rife.MODEL_SHA256)+ assert (ident["net"], ident["torch"]) == (rife_torch.CODE_SHA256, torch.__version__)+ if runner.device == "cuda":+ assert ident["determinism"] == {"cudnn_deterministic": True, "cudnn_benchmark": False, "cudnn_conv_fp32_precision": "ieee"}+ assert ident["gpu"] == torch.cuda.get_device_name() and "cpu" not in ident+ else:+ assert ident["cpu"] == torch.backends.cpu.get_cpu_capability() and "gpu" not in ident and "determinism" not in ident+++def _walkers() -> dict:+ return json.loads((WALKERS / "walkers.json").read_text())["pairs"]+++def _walker(key: str, name: str) -> Image.Image:+ """A frame of tests/fixtures/rife-walkers, its pixels the ones recorded."""+ im = Image.open(WALKERS / f"{key}.{name}.png").convert("RGBA")+ assert hashlib.sha256(im.tobytes()).hexdigest() == _walkers()[key]["sha256"][name]+ return im+++def _verdict(made: Image.Image, a: Image.Image, b: Image.Image, t: float, apart: np.ndarray) -> tuple[list[str], list[str]]:+ """The engine's faults and looks of a made frame and its passes, every reading the overlapped wrap takes."""+ m = {**rife.smear(made, a, b), "outline_shift": rife.outline_shift(made, a, b), "ghost": rife.ghost(made),+ "crossfade": rife.crossfade(made, a, b, t), "torn": rife.torn(apart, made)}+ return faults(m), looks(m)+++def _apart(m: Image.Image, n: Image.Image) -> tuple[float, float]:+ """Mean and largest absolute difference of two frames, premultiplied RGBA 0..255, inside the box either covers."""+ pm, pn = (np.dstack([x[..., :3] * x[..., 3:] / 255.0, x[..., 3:]]) for x in+ (np.asarray(f, dtype=np.float64) for f in (m, n)))+ ys, xs = np.nonzero((pm[..., 3] > 0) | (pn[..., 3] > 0))+ d = np.abs(pm - pn)[ys.min():ys.max() + 1, xs.min():xs.max() + 1]+ return float(d.mean()), float(d.max())++[email protected]_rife[email protected](900) # a frame and its sixteen passes, seven pairs: seconds on a GPU, a minute or two on two CPU cores[email protected]("key", sorted(_walkers()))+def test_walkers_are_judged_as_the_binary_judged_them(runner, key):+ """Each recorded walker pair, its frame and passes made by the torch backend, has the verdict the binary's frame had,+ on a machine with no binary: the same faults (smear, outline, ghost, torn) and looks (crossfade). The pairs were+ picked where the binary on an Apple GPU, the binary on Mesa llvmpipe and the torch backend on a CPU all gave that+ verdict, every reading at least a tenth of its bound away from it. The frame lies from the binary's no further than+ twice as far as the binary's own frames on those two GPUs lay apart."""+ rec = _walkers()[key]+ a, b, ncnn = (_walker(key, name) for name in ("a", "b", "ncnn"))+ made, apart = rife.Rife(runner=runner).read(a, b, rec["t"])+ assert _verdict(made, a, b, rec["t"], apart) == (rec["faults"], rec["looks"])+ mean, most = _apart(made, ncnn)+ assert mean <= 2 * rec["gpu_gap"]["mean_abs"] and most <= 2 * rec["gpu_gap"]["max_abs"], (mean, most, rec["gpu_gap"])++[email protected]_rife[email protected]_rife[email protected](1800) # the binary on a CPU's Vulkan driver: a minute or more a pair[email protected]("key", sorted(_walkers()))+def test_the_binary_and_the_torch_backend_judge_the_walkers_alike_on_one_machine(runner, key):+ """The recorded walker pairs through this machine's binary (llvmpipe on the Linux lane) and the torch backend: the same+ verdict for each."""+ t = _walkers()[key]["t"]+ a, b = _walker(key, "a"), _walker(key, "b")+ verdicts = []+ for made in (rife.Rife(*rife.locate()), rife.Rife(runner=runner)):+ frame, apart = made.read(a, b, t)+ verdicts.append(_verdict(frame, a, b, t, apart))+ assert verdicts[0] == verdicts[1]+++# --- choosing and refusing: no torch needed ---------------------------------------------------------------------------++def _no_torch(monkeypatch) -> None:+ """PyTorch not importable, as where it is not installed."""+ monkeypatch.setitem(sys.modules, "torch", None)+ monkeypatch.delitem(sys.modules, "sprite_gen.video.rife_torch", raising=False)+++def _binary_beside_a_model(monkeypatch, tmp_path: Path) -> Path:+ """A binary that would run and log its arguments, found by SPRITE_GEN_RIFE with a model beside it: its log."""+ tmp_path.mkdir(parents=True, exist_ok=True)+ binary, log = _recording_binary(tmp_path)+ (tmp_path / rife.MODEL).mkdir()+ for name in ("flownet.param", "flownet.bin"):+ (tmp_path / rife.MODEL / name).write_bytes(b"x")+ monkeypatch.setenv("SPRITE_GEN_RIFE", str(binary))+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL", raising=False)+ return log++[email protected](sys.platform == "win32", reason="a shebang script cannot stand in for rife-ncnn-vulkan.exe")+def test_torch_chosen_and_not_installed_is_rife_not_installed_and_the_binary_is_never_run(monkeypatch, tmp_path):+ """SPRITE_GEN_RIFE_BACKEND=torch where PyTorch is not installed: RIFE not installed, naming PyTorch and the line that+ installs it — and the binary, found and runnable, is not looked for, let alone run."""+ _no_torch(monkeypatch)+ log = _binary_beside_a_model(monkeypatch, tmp_path)+ rife.Rife(*rife.locate()) # the binary is there to be found+ for device in ("cuda", "cpu"):+ monkeypatch.setenv("SPRITE_GEN_RIFE_BACKEND", "torch")+ monkeypatch.setenv("SPRITE_GEN_RIFE_DEVICE", device)+ with pytest.raises(rife.RifeNotInstalled, match=r'PyTorch cannot be imported .*pip install "sprite-gen\[torch\]" && '+ r"sprite-gen rife install --backend torch"):+ rife.Rife()+ assert rife.install_command() == 'pip install "sprite-gen[torch]" && sprite-gen rife install --backend torch'+ assert not log.exists()++[email protected](sys.platform == "win32", reason="a shebang script cannot stand in for rife-ncnn-vulkan.exe")+def test_a_loop_cut_where_torch_is_chosen_and_not_installed_says_so_and_runs_no_binary(monkeypatch, tmp_path):+ """`video-loop --repair auto` with a jump to repair, torch chosen and PyTorch not installed: the jump is cut as filmed+ with the warning and the record a RIFE not installed leaves, and the record names PyTorch and its install line, not+ the binary's; the binary beside it never runs."""+ from tests.video.test_loop_repair import _keyed, _loop, _run++ _no_torch(monkeypatch)+ log = _binary_beside_a_model(monkeypatch, tmp_path / "rife")+ monkeypatch.setenv("SPRITE_GEN_RIFE_BACKEND", "torch")+ filmed, _ = _loop({10: 12})+ rep = _run(tmp_path, _keyed(tmp_path, filmed))+ jr = rep["jump_repair"]+ assert rep["status"] == "passed" and jr["applied"] is False and jr["why"] == "RIFE not installed — cut as filmed"+ assert jr["install"] == 'pip install "sprite-gen[torch]" && sprite-gen rife install --backend torch'+ assert "PyTorch cannot be imported" in jr["rife"] and jr["unmade"]["frames"] == [10]+ assert not log.exists()++[email protected]("names, refused", [+ ({"SPRITE_GEN_RIFE_BACKEND": "vulkan"}, r"SPRITE_GEN_RIFE_BACKEND='vulkan': name ncnn .* or torch"),+ ({"SPRITE_GEN_RIFE_BACKEND": "torch", "SPRITE_GEN_RIFE_DEVICE": "mps"}, r"mps: the torch backend does not run on Apple's GPU"),+ ({"SPRITE_GEN_RIFE_BACKEND": "torch", "SPRITE_GEN_RIFE_DEVICE": "gpu"}, r"SPRITE_GEN_RIFE_DEVICE='gpu': name cuda .* or cpu"),+])+def test_a_backend_or_device_named_wrong_is_refused_before_anything_is_looked_for(monkeypatch, tmp_path, names, refused):+ """A backend or a device the engine does not know, or Apple's GPU: refused by name (`RifeUnavailable`, never RIFE not+ installed, which a loop would cut around), before PyTorch is imported or a binary or model looked for — nothing is+ chosen in its place."""+ _no_torch(monkeypatch)+ log = _binary_beside_a_model(monkeypatch, tmp_path)+ for name, value in names.items():+ monkeypatch.setenv(name, value)+ with pytest.raises(rife.RifeUnavailable, match=refused) as refusal:+ rife.Rife()+ assert not isinstance(refusal.value, rife.RifeNotInstalled) and not log.exists()++[email protected]_rife+def test_cuda_named_where_there_is_none_is_refused_not_run_on_the_cpu(monkeypatch):+ """SPRITE_GEN_RIFE_DEVICE=cuda (the default) where PyTorch finds no CUDA: refused, naming why — PyTorch built for the CPU+ only, or built for a CUDA that finds no GPU — and that nothing runs elsewhere in its place."""+ import torch++ from sprite_gen.video import rife_torch++ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)+ monkeypatch.setenv("SPRITE_GEN_RIFE_BACKEND", "torch")+ monkeypatch.delenv("SPRITE_GEN_RIFE_DEVICE", raising=False)+ monkeypatch.setattr(torch.version, "cuda", None)+ with pytest.raises(rife.RifeUnavailable, match=r"CUDA is not available here: a PyTorch built for the CPU only .*nothing "+ r"runs on another device in its place"):+ rife.Rife()+ monkeypatch.setattr(torch.version, "cuda", "13.0")+ with pytest.raises(rife.RifeUnavailable, match=r"built for CUDA 13.0, which finds no GPU"):+ rife_torch.TorchRunner(rife.locate_model(), "cuda")+++def test_a_model_other_than_the_pinned_one_is_refused_and_one_not_there_is_not_installed(monkeypatch, tmp_path):+ """The model the torch backend reads (`rife.locate_model`: SPRITE_GEN_RIFE_MODEL, else the install root, never beside a+ binary): not there is RIFE not installed, naming the line that installs it and the variable; there with other bytes is+ refused by sha256 before it is read (`rife.model_bytes`)."""+ monkeypatch.setenv("SPRITE_GEN_DATA_DIR", str(tmp_path / "data"))+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL", raising=False)+ monkeypatch.setenv("SPRITE_GEN_RIFE_BACKEND", "torch")+ _binary_beside_a_model(monkeypatch, tmp_path / "beside")+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL", raising=False)+ with pytest.raises(rife.RifeNotInstalled, match=r"sprite-gen rife install --backend torch.*SPRITE_GEN_RIFE_MODEL"):+ rife.locate_model()+ model = tmp_path / "other" / rife.MODEL+ model.mkdir(parents=True)+ (model / "flownet.param").write_text("another model")+ (model / "flownet.bin").write_text("another model")+ monkeypatch.setenv("SPRITE_GEN_RIFE_MODEL", str(model))+ assert rife.locate_model() == model.resolve()+ with pytest.raises(rife.RifeUnavailable, match=rf"flownet.param has sha256 [0-9a-f]{{64}}, expected {rife.MODEL_SHA256['flownet.param']}"):+ rife.model_bytes(model)+++# --- reports and keys: a runner stood in ------------------------------------------------------------------------------++class FakeRunner:+ """A runner that makes each frame `a` itself (its colour as RIFE is given it, its coverage), and names itself."""++ def __init__(self, **identity):+ self.ident = {"backend": "torch", "device": "cpu", "weights": dict(rife.MODEL_SHA256), "net": "n" * 64,+ "torch": "2.13.0", "cpu": "AVX2", "arch": "x86_64", **identity}+ self.model = Path("/models") / rife.MODEL+ self.frames = self.reads = 0++ def frame(self, colour, cover, t):+ self.frames += 1+ return colour[0], cover[0]++ def read(self, colour, cover, t):+ self.reads += 1+ return colour[0], cover[0], np.zeros(cover[0].shape, np.float32)++ def identity(self):+ return dict(self.ident)++ def describe(self):+ return {"kind": "rife-torch", "device": self.ident["device"], "model": self.model.name}+++def test_a_report_names_the_torch_backend_and_counts_its_runs(monkeypatch, tmp_path):+ """`describe()` names what made the frames (`kind`): `rife-ncnn-vulkan` for the binary, as before, `rife-torch` for the+ torch backend; `counts()` names its runs as the overlapped wrap's record does — the binary's calls (`binary_calls`), the+ torch backend's runs (`runs`), 2 a frame and 2 + PASS_CALLS a read."""+ binary, _ = _recording_binary(tmp_path)+ ncnn = rife.Rife(binary, tmp_path / rife.MODEL)+ assert ncnn.describe() == {"kind": "rife-ncnn-vulkan", "binary": str(binary), "model": rife.MODEL, "tta": "-x -z"}+ a, b = _disc(40), _disc(72)+ ncnn(a, b, 0.5)+ ncnn.read(a, b, 0.5)+ assert ncnn.counts() == {"binary_calls": 2 + 2 + rife.PASS_CALLS}+ fake = FakeRunner()+ torch = rife.Rife(runner=fake)+ assert torch.describe() == {"kind": "rife-torch", "device": "cpu", "model": rife.MODEL, "tta": "-x -z"}+ assert torch(a, b, 0.5).tobytes() == a.tobytes()+ frame, apart = torch.read(a, b, 0.5)+ assert frame.tobytes() == a.tobytes() and apart.shape == (96, 128) and (fake.frames, fake.reads) == (1, 1)+ assert torch.counts() == {"runs": 2 + 2 + rife.PASS_CALLS} and torch.made == 2+++def test_the_loop_and_the_alignment_name_the_torch_backend_that_made_their_frames(monkeypatch, tmp_path):+ """Where `video-loop` and `video-cycle-align` find RIFE themselves and SPRITE_GEN_RIFE_BACKEND names torch, their reports+ name the torch backend as what made their frames — `kind` rife-torch, its device and model, the augmentation —+ not the binary."""+ from tests.video.test_cycle_align import _cut+ from tests.video.test_loop_repair import _keyed, _loop, _run++ monkeypatch.setenv("SPRITE_GEN_RIFE_BACKEND", "torch")+ monkeypatch.setattr(rife, "torch_runner", FakeRunner, raising=False)+ filmed, _ = _loop({10: 12})+ (tmp_path / "loop").mkdir()+ rep = _run(tmp_path / "loop", _keyed(tmp_path / "loop", filmed))+ assert rep["jump_repair"]["interpolator"] == {"kind": "rife-torch", "device": "cpu", "model": rife.MODEL, "tta": "-x -z"}+ dirs = [_cut(tmp_path, n, L) for n, L in (("S", 20), ("E", 24))]+ report = align.align_set(dirs, report_path=tmp_path / "align.json", between="rife")+ assert report["made_by_rife"] > 0+ assert report["interpolator"] == {"kind": "rife-torch", "device": "cpu", "model": rife.MODEL, "tta": "-x -z"}++[email protected]("field, value", [("backend", "ncnn"), ("weights", {"flownet.param": "0" * 64, "flownet.bin": "1" * 64}),+ ("torch", "2.14.0"), ("device", "cuda"), ("net", "m" * 64), ("cpu", "AVX512"),+ ("determinism", {"cudnn_deterministic": False})])+def test_a_frame_kept_by_one_runner_is_not_taken_for_another(tmp_path, field, value):+ """`Cache` keys a frame on its RIFE's identity, the runner's part of it whole: a runner whose backend, weights, PyTorch,+ device, network code, CPU or determinism differs in any one is another key, and its frame is made, not taken."""+ a, b = _disc(40), _disc(72)+ cache = rife.Cache(tmp_path / "kept")+ one = rife.Rife(runner=FakeRunner())+ assert cache.key(one, a, b, 0.5) == cache.key(rife.Rife(runner=FakeRunner()), a, b, 0.5)+ other = rife.Rife(runner=FakeRunner(**{field: value}))+ assert cache.key(one, a, b, 0.5) != cache.key(other, a, b, 0.5)+ cache.frame(one, a, b, 0.5)+ cache.frame(other, a, b, 0.5)+ assert (cache.hits, cache.misses) == (0, 2)