Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(rife): rife-v4.25 is the default interpolator, through TNTwise's rife-ncnn-vulkan 20250112, each image padded to 128 with no augmentation; rife-v4.6 runs by name as 3.14.0 ran it, and the torch backend runs Practical-RIFE 4.25's IFNet
Soohong Kimb49324b0f900
diff --git a/pyproject.toml b/pyproject.tomlindex 5158cc9..8f99026 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -45,7 +45,7 @@ dev = [# subprocess.wait(), which is exactly the case that hangs here."pytest-timeout>=2.3",]-# RIFE's torch backend (SPRITE_GEN_RIFE_BACKEND=torch, docs/loop-repair.md section 1): rife-v4.6 in PyTorch, for a+# RIFE's torch backend (SPRITE_GEN_RIFE_BACKEND=torch, docs/loop-repair.md section 1): the binary's model in PyTorch (rife-v4.25 by default), for a# GPU host the binary cannot run on (Vulkan-less CUDA). 2.13.0 is the release it was measured on. PyPI's Linux x86-64# wheel is the CUDA 13 build; a host that runs it on the CPU only takes PyTorch's CPU index# (`pip install torch==2.13.0 --index-url https://download.pytorch.org/whl/cpu`) before the extra.@@ -78,7 +78,7 @@ 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+# Another names a test of the torch backend: skipped where PyTorch or the model is missing, run by# the lanes with none skipped (`-m torch_rife`, on SPRITE_GEN_RIFE_DEVICE; docs/release.md).# The last names a slow test: a plain `pytest` is the fast bundle, which tests/conftest.py makes by# deselecting the marked tests, and `pytest --full` runs every test, as the release lane does.diff --git a/scripts/t4_lane.py b/scripts/t4_lane.pyindex 9007a40..39cec74 100644--- a/scripts/t4_lane.py+++ b/scripts/t4_lane.py@@ -106,7 +106,8 @@ def gates(sha: str, whole_suite: bool) -> dict:if built != sha:rec["why"] = f"the image holds {built}, not {sha}"return rec- model = Path(json.loads(Path("/lane/rife-install.json").read_text())["dir"]) / "rife-v4.6"+ installed = json.loads(Path("/lane/rife-install.json").read_text())+ model = Path(installed["dir"]) / installed["model"] # the model the engine runs by default (rife-v4.25)# Nowhere the engine looks for the binary holds one: an empty data directory, nothing on PATH, no SPRITE_GEN_RIFE.env = {k: v for k, v in os.environ.items() if not k.startswith("SPRITE_GEN_")}env.update(PATH=f"{VENV}/bin:{env.get('PATH', '/usr/local/bin:/usr/bin:/bin')}", XDG_DATA_HOME=tempfile.mkdtemp(),diff --git a/sprite_gen/video/rife.py b/sprite_gen/video/rife.pyindex 9691c3f..639d952 100644--- a/sprite_gen/video/rife.py+++ b/sprite_gen/video/rife.py@@ -1,6 +1,7 @@# SPDX-License-Identifier: Apache-2.0"""RIFE in-betweens for RGBA sprite frames, through the external `rife-ncnn-vulkan` binary or, where SPRITE_GEN_RIFE_BACKEND-names it, the same rife-v4.6 in PyTorch (`rife_torch`).+names it, the same model in PyTorch (`rife_torch`). The model is rife-v4.25, or rife-v4.6 where it is named (`MODELS`,+`model_name()`).Where it runs, what it costs and why this build: docs/loop-repair.md section 1. RIFE readsthree colour channels and no alpha, so a frame is interpolated as two images — its colour and@@ -26,8 +27,10 @@ the sixteen single passes the binary's augmentation combines inside one call, onThe binary's own CPU path (`-g -1`) returns a wrong frame with rife-v4.6 on both macOS andLinux (measured 2026-10-03: mean error 39 against 3.3 through Vulkan), so it is never passed;a machine without a GPU runs the Vulkan path on Mesa's llvmpipe, which gives the GPU's frame.-Every call asks for the binary's test-time augmentation, spatial and temporal (`-x -z`, `TTA`;-docs/loop-repair.md section 1, "Which setting"); SPRITE_GEN_RIFE_TTA names another (`tta()`).+Each model's calls ask for its own augmentation (`MODELS`): rife-v4.25 none, each image padded with zeros to a multiple+of 128 first and the frame cut back after (`_binary_run`); rife-v4.6 the binary's test-time augmentation, spatial and+temporal (`-x -z`), each image handed as it is (docs/loop-repair.md section 1, "Which setting"). SPRITE_GEN_RIFE_TTA names+another for rife-v4.6 (`tta()`).The binary is found by SPRITE_GEN_RIFE, then on PATH, then where `sprite-gen rife install`puts it (`install_root()`, docs/loop-repair.md section 1). A RIFE that cannot be found is@@ -75,7 +78,7 @@ import sysimport tempfileimport zipfilefrom pathlib import Path-from typing import Callable+from typing import Callable, NamedTupleimport PILfrom PIL import Image, ImageFilter, PngImagePlugin@@ -84,28 +87,60 @@ from sprite_gen._deps import npfrom sprite_gen.video.frames import _components, _nearBINARY = "rife-ncnn-vulkan"-MODEL = "rife-v4.6"-RELEASE = "20221029"-# What runs RIFE (`backend()`): the binary, the default, or rife-v4.6 in PyTorch (`rife_torch`); and the torch devices-# it runs on (`device()`), the first the default.+# TNTwise's rife-ncnn-vulkan, the build `sprite-gen rife install` puts in place (docs/loop-repair.md section 1): nihui's+# 20221029 with the models since, rife-v4.25 among them, which the 20221029 binary does not run.+RELEASE = "20250112"+++class Model(NamedTuple):+ """A model the engine runs (`MODELS`): the augmentation every call asks for by default (`tta()`), and the multiple each+ image is padded to with zeros before RIFE is handed it, the frame cut back after (0: handed as it is)."""++ tta: tuple[str, ...]+ pad: int+++# The models the engine runs, each by the name of the directory its two files ship in (the binary reads the model's+# version from it). rife-v4.25, the default, runs with no augmentation (TNTwise's README marks -x and -z deprecated with+# it) and each image padded to 128, as Practical-RIFE pads it at scale 1: the binary pads it to 64 itself, and pip-jump,+# a public cut, takes 48 frames padded to 64 and 53 padded to 128, the 53 PyTorch takes from the published weights+# (docs/loop-repair.md section 1, "Which setting"). rife-v4.6, chosen by name (`model_name()`), runs as 3.14.0 ran it:+# -x -z, each image handed as it is, so its frames are the old ones.+MODELS = {+ "rife-v4.25": Model(tta=(), pad=128),+ "rife-v4.6": Model(tta=("-x", "-z"), pad=0),+}+MODEL = "rife-v4.25"+PLATFORMS = ("macos", "ubuntu", "windows")+# What runs RIFE (`backend()`): the binary, the default, or the same model in PyTorch (`rife_torch`); and the torch+# devices it runs on (`device()`), the first the default.BACKENDS = ("ncnn", "torch")DEVICES = ("cuda", "cpu")-# The model files of rife-v4.6 as the release zips ship them, the macOS and the Ubuntu zip alike: `sprite-gen rife install`-# checks them, and the torch backend reads its weights out of exactly these (`model_bytes`), as it reads them by their-# layout (docs/loop-repair.md section 1).+# Each model's two files as each release zip ships them: the Windows zip's flownet.param has CRLF line ends, the macOS and+# Ubuntu zips' LF, and flownet.bin is the same in all three. `sprite-gen rife install` checks them, and the torch backend+# reads its weights out of exactly these (`model_bytes`), as it reads them by their layout (docs/loop-repair.md section 1).MODEL_SHA256 = {- "flownet.param": "724569596bcd1e7b9fa50455c604777ebed99746d2ef40aa86e31b5725f1053c",- "flownet.bin": "f334ed2260149ce0188a6dcf049844e8b0cdd912e01cbcfb63553157d2508958",+ "rife-v4.25": {+ "flownet.param": {"macos": "6ba231fb00e4ae82b120f938d9b2df91db32fbf322bd110f29450efaf61848d6",+ "ubuntu": "6ba231fb00e4ae82b120f938d9b2df91db32fbf322bd110f29450efaf61848d6",+ "windows": "99d0f49866ff06f170c08e570e3e1b67b89019e3d11a87c8f0e7908fa50ab4c1"},+ "flownet.bin": {p: "10de487a095e61cb2971c39e3b5e17005a70fba6201c77fb96e063f4423b583f" for p in PLATFORMS},+ },+ "rife-v4.6": {+ "flownet.param": {"macos": "724569596bcd1e7b9fa50455c604777ebed99746d2ef40aa86e31b5725f1053c",+ "ubuntu": "724569596bcd1e7b9fa50455c604777ebed99746d2ef40aa86e31b5725f1053c",+ "windows": "28df14d57a225725ee5386f52eba422488450d37c9f40800ed4f62e8ba846692"},+ "flownet.bin": {p: "f334ed2260149ce0188a6dcf049844e8b0cdd912e01cbcfb63553157d2508958" for p in PLATFORMS},+ },}TORCH_EXTRA = 'pip install "sprite-gen[torch]"'# `RemoteRunner`: the version of the requests and answers a host and its executor exchange (`pack`); another is refused.PROTOCOL = 1-# The binary's test-time augmentation, passed on every call: `-x` runs the pair as its eight flips and-# transposes, `-z` runs it both ways in time as well, and what comes back is averaged — so a frame made-# from a to b is the one made from b to a (docs/loop-repair.md section 1, "Which setting"). On a machine-# without a GPU it costs 15 to 19 times the CPU of a plain call. SPRITE_GEN_RIFE_TTA names another-# (`tta()`): either mode, or none.-TTA = ("-x", "-z")+# The binary's test-time augmentation a call can ask for: `-x` runs the pair as its eight flips and transposes, `-z`+# runs it both ways in time as well, and what comes back is averaged — so a frame made from a to b is the one made from+# b to a. rife-v4.6 asks for both (`MODELS`), rife-v4.25 for neither (docs/loop-repair.md section 1, "Which setting").+# On a machine without a GPU both cost 15 to 19 times the CPU of a plain call. SPRITE_GEN_RIFE_TTA names another for+# rife-v4.6 (`tta()`): either mode, or none.TTA_MODES = ("-x", "-z")# Coverage RIFE leaves under this is its own blur, not body: dropped so no halo is invented.ALPHA_FLOOR = 2 / 255@@ -230,10 +265,10 @@ Read = Callable[[Image.Image, Image.Image, float], tuple[Image.Image, np.ndarray# The one line that installs it, quoted wherever a missing RIFE is reported.INSTALL_COMMAND = "sprite-gen rife install"INSTALL_HINT = (- f"run `{INSTALL_COMMAND}` (rife-ncnn-vulkan {RELEASE} with the model {MODEL}, sha256-checked, into the "- f"user data directory), or put {BINARY} on PATH or set SPRITE_GEN_RIFE to the binary — the model {MODEL}/ "- f"ships beside it (SPRITE_GEN_RIFE_MODEL overrides); on Linux without a GPU also `libvulkan1 mesa-vulkan-drivers`; "- f"see docs/loop-repair.md"+ f"run `{INSTALL_COMMAND}` (TNTwise's rife-ncnn-vulkan {RELEASE} with the models {' and '.join(MODELS)}, "+ f"sha256-checked, into the user data directory), or put {BINARY} {RELEASE} on PATH or set SPRITE_GEN_RIFE to the "+ f"binary — the model's directory ships beside it (SPRITE_GEN_RIFE_MODEL overrides); on Linux without a GPU also "+ f"`libvulkan1 mesa-vulkan-drivers`; see docs/loop-repair.md")@@ -278,9 +313,39 @@ def installed_binary(root: Path | None = None, platform: str | None = None) -> Preturn (root or install_root()) / f"{BINARY}-{RELEASE}-{platform}" / (BINARY + (".exe" if platform == "windows" else ""))+def model_name() -> str:+ """The model the engine runs (`MODELS`): SPRITE_GEN_RIFE_MODEL_NAME where it is set and not empty, else the name of the+ directory SPRITE_GEN_RIFE_MODEL names, else MODEL. A name the engine does not run, a directory not named as the model+ it holds (the binary reads the model's version from its name) and a directory and a name that disagree are each+ refused (`RifeUnavailable`, not RIFE not installed: a loop does not cut around it)."""+ named = os.environ.get("SPRITE_GEN_RIFE_MODEL_NAME") or None+ if named is not None and named not in MODELS:+ raise RifeUnavailable(f"SPRITE_GEN_RIFE_MODEL_NAME={named!r}: name {' or '.join(MODELS)} ({MODEL}, the default), "+ "or leave it unset")+ path = os.environ.get("SPRITE_GEN_RIFE_MODEL") or None+ held = Path(path).expanduser().name if path else None+ if held is not None:+ if held not in MODELS:+ raise RifeUnavailable(f"SPRITE_GEN_RIFE_MODEL={path!r}: its directory is named {held!r}, not as the model it "+ f"holds ({' or '.join(MODELS)}): the binary reads the model's version from that name")+ if named is not None and named != held:+ raise RifeUnavailable(f"SPRITE_GEN_RIFE_MODEL={path!r} holds {held}, and SPRITE_GEN_RIFE_MODEL_NAME={named!r}: "+ "name one model, or unset one of them")+ return named or held or MODEL+++def held_model(model: Path) -> str:+ """The model in the directory `model`, by its name (`MODELS`); a directory not named as one is refused."""+ if model.name not in MODELS:+ raise RifeUnavailable(f"RIFE model {model}: the directory is named {model.name!r}, not as the model it holds "+ f"({' or '.join(MODELS)}): the binary reads the model's version from that name")+ return model.name++def locate() -> tuple[Path, Path]:"""(binary, model directory): the binary from SPRITE_GEN_RIFE, else PATH, else `install_root()`;- the model from SPRITE_GEN_RIFE_MODEL, else beside the binary."""+ the model from SPRITE_GEN_RIFE_MODEL, else `model_name()`'s directory beside the binary."""+ name = model_name() # refused here, before anything is looked fornamed = os.environ.get("SPRITE_GEN_RIFE")installed = installed_binary() if platform_release() else Nonefound = named or shutil.which(BINARY) or (str(installed) if installed and installed.is_file() else None)@@ -291,32 +356,37 @@ def locate() -> tuple[Path, Path]:if not binary.is_file() or not os.access(binary, os.X_OK):raise RifeNotInstalled(f"{binary} is not an executable file; {INSTALL_HINT}")binary = binary.resolve()- model = Path(os.environ.get("SPRITE_GEN_RIFE_MODEL") or binary.parent / MODEL).expanduser()+ model = Path(os.environ.get("SPRITE_GEN_RIFE_MODEL") or binary.parent / name).expanduser()if not (model / "flownet.param").is_file() or not (model / "flownet.bin").is_file():raise RifeNotInstalled(f"RIFE model {model} has no flownet.param / flownet.bin; {INSTALL_HINT}")return binary, model-def tta() -> tuple[str, ...]:- """The test-time augmentation every call asks for: SPRITE_GEN_RIFE_TTA when it is set (`-x`, `-z`- or both, space-separated; empty for none), else TTA. Anything else is refused: a flag passed- through unread could be the binary's CPU path, which is wrong with this model."""+def tta(model: str | None = None) -> tuple[str, ...]:+ """The test-time augmentation every call of `model` (else `model_name()`'s) asks for: SPRITE_GEN_RIFE_TTA when it is set+ (`-x`, `-z` or both, space-separated; empty for none), else the model's own (`MODELS`). Anything else is refused: a+ flag passed through unread could be the binary's CPU path, which is wrong with rife-v4.6; and rife-v4.25 runs with+ none — TNTwise's README marks -x and -z deprecated with it, and none is what was measured."""+ model = model or model_name()named = os.environ.get("SPRITE_GEN_RIFE_TTA")if named is None:- return TTA+ return MODELS[model].ttamodes = tuple(named.split())if any(m not in TTA_MODES for m in modes) or len(set(modes)) < len(modes):raise RifeUnavailable(f"SPRITE_GEN_RIFE_TTA={named!r}: name -x, -z or both, space-separated, or leave it empty for none")+ if modes and not MODELS[model].tta:+ raise RifeUnavailable(f"SPRITE_GEN_RIFE_TTA={named!r}: {model} runs with no augmentation (TNTwise's README marks -x "+ "and -z deprecated with it); leave it empty or unset, or name SPRITE_GEN_RIFE_MODEL_NAME=rife-v4.6")return modesdef backend() -> str:- """What runs RIFE: SPRITE_GEN_RIFE_BACKEND, `ncnn` (the binary) where it is unset or empty, or `torch` (rife-v4.6 in- PyTorch, `rife_torch`). Anything else is refused, not read as the default."""+ """What runs RIFE: SPRITE_GEN_RIFE_BACKEND, `ncnn` (the binary) where it is unset or empty, or `torch` (the same model+ in PyTorch, `rife_torch`). Anything else is refused, not read as the default."""named = os.environ.get("SPRITE_GEN_RIFE_BACKEND") or "ncnn"if named not in BACKENDS:- raise RifeUnavailable(f"SPRITE_GEN_RIFE_BACKEND={named!r}: name ncnn ({BINARY}, the default) or torch (rife-v4.6 in "- f"PyTorch), or leave it unset")+ raise RifeUnavailable(f"SPRITE_GEN_RIFE_BACKEND={named!r}: name ncnn ({BINARY}, the default) or torch (the same "+ f"model in PyTorch), or leave it unset")return named@@ -381,40 +451,44 @@ def install_command() -> str:def locate_model() -> Path:"""The model directory the torch backend reads, with no binary looked for: SPRITE_GEN_RIFE_MODEL, else where- `sprite-gen rife install` puts the model (`<install_root()>/rife-ncnn-vulkan-<release>-<platform>/rife-v4.6`)."""+ `sprite-gen rife install` puts `model_name()`'s (`<install_root()>/rife-ncnn-vulkan-<release>-<platform>/<model>`)."""+ name = model_name()named = os.environ.get("SPRITE_GEN_RIFE_MODEL")- model = Path(named).expanduser() if named else installed_binary().parent / MODEL+ model = Path(named).expanduser() if named else installed_binary().parent / nameif not (model / "flownet.param").is_file() or not (model / "flownet.bin").is_file():where = "SPRITE_GEN_RIFE_MODEL" if named else "SPRITE_GEN_RIFE_MODEL is not set, and the install root"raise RifeNotInstalled(f"RIFE model {model} has no flownet.param / flownet.bin ({where}); run `{install_command()}` "- f"(the model {MODEL}, sha256-checked, into the user data directory), or set "- f"SPRITE_GEN_RIFE_MODEL to a {MODEL} directory; see docs/loop-repair.md")+ f"(the model {name}, sha256-checked, into the user data directory), or set "+ f"SPRITE_GEN_RIFE_MODEL to a {name} directory; see docs/loop-repair.md")return model.resolve()def model_bytes(model: Path) -> dict[str, bytes]:- """The two files of the model in `model`, each read once and checked against MODEL_SHA256, so the bytes handed on are- the bytes checked: another model, or one cut short or written over, is refused by name, never read- (`RifeUnavailable`)."""+ """The two files of the model in `model` (`held_model`), each read once and checked against its pins in MODEL_SHA256,+ any release zip's, so the bytes handed on are the bytes checked: another model, or one cut short or written over, is+ refused by name, never read (`RifeUnavailable`)."""+ held = held_model(model)files = {}- for name, pinned in MODEL_SHA256.items():+ for name, pins in MODEL_SHA256[held].items():try:data = (model / name).read_bytes()except OSError as exc:raise RifeUnavailable(f"RIFE model {model}: {name} could not be read: {exc}") from excgot = hashlib.sha256(data).hexdigest()- if got != pinned:- raise RifeUnavailable(f"RIFE model {model}: {name} has sha256 {got}, expected {pinned} ({MODEL} of "+ if got not in pins.values():+ expected = " or ".join(sorted(set(pins.values())))+ raise RifeUnavailable(f"RIFE model {model}: {name} has sha256 {got}, expected one of {expected} ({held} of "f"{BINARY} {RELEASE}); install it again (`{INSTALL_COMMAND} --force`), or point "- f"SPRITE_GEN_RIFE_MODEL at that {MODEL}")+ f"SPRITE_GEN_RIFE_MODEL at that {held}")files[name] = datareturn filesdef _call(binary: Path, model: Path, a: Image.Image, b: Image.Image, t: float, tmp: Path,modes: tuple[str, ...] | None = None) -> Image.Image:- """One run of the binary from `a` to `b` at `t`, with the augmentation `tta()` names, or `modes` (`passes`: none)."""- modes = tta() if modes is None else modes+ """One run of the binary from `a` to `b` at `t`, with the augmentation `tta()` names for the model, or `modes`+ (`passes`: none)."""+ modes = tta(held_model(model)) if modes is None else modesa.save(tmp / "a.png")b.save(tmp / "b.png")out = tmp / "o.png"@@ -473,7 +547,7 @@ def bleed(frame: np.ndarray) -> np.ndarray:# One run of RIFE, wherever it runs: from the first image to the second (H x W x 3, uint8) at a fraction, with the-# augmentation named (None: `tta()`'s, read for the run), to the image it makes (H x W x 3, uint8).+# augmentation named (None: `tta()`'s for the model, read for the run), to the image it makes (H x W x 3, uint8).Run = Callable[[np.ndarray, np.ndarray, float, tuple[str, ...] | None], np.ndarray]@@ -518,11 +592,27 @@ def pass_runs(run: Run, colour: list[np.ndarray], cover: list[np.ndarray], t: flreturn apart.astype(np.float32)+def padded(x: np.ndarray, multiple: int) -> np.ndarray:+ """An image (H x W x C) at the top left of a canvas a multiple of `multiple` each way, zeros round it."""+ h, w = x.shape[:2]+ out = np.zeros((-(-h // multiple) * multiple, -(-w // multiple) * multiple, *x.shape[2:]), dtype=x.dtype)+ out[:h, :w] = x+ return out++def _binary_run(binary: Path, model: Path, tmp: Path) -> Run:- """A run of the binary (`_call`, its images written in `tmp`)."""+ """A run of the binary (`_call`, its images written in `tmp`): each image handed to it as the model is handed one+ (`MODELS`) — rife-v4.25's padded with zeros to a multiple of 128 and the image it makes cut back to the pair's size,+ rife-v4.6's as it is."""+ pad = MODELS[held_model(model)].pad+def run(x: np.ndarray, y: np.ndarray, t: float, modes: tuple[str, ...] | None) -> np.ndarray:+ h, w = x.shape[:2]+ if pad:+ x, y = padded(x, pad), padded(y, pad)a, b = Image.fromarray(x, "RGB"), Image.fromarray(y, "RGB")- return np.asarray(_call(binary, model, a, b, t, tmp) if modes is None else _call(binary, model, a, b, t, tmp, modes))+ made = np.asarray(_call(binary, model, a, b, t, tmp) if modes is None else _call(binary, model, a, b, t, tmp, modes))+ return np.ascontiguousarray(made[:h, :w]) if pad else madereturn run@@ -1189,6 +1279,7 @@ class Binary:def __init__(self, binary: Path, model: Path):self.binary, self.model = binary, model+ self.model_name = held_model(model) # refused here, before a frame is asked fordef frame(self, colour: list[np.ndarray], cover: list[np.ndarray], t: float) -> tuple[np.ndarray, np.ndarray]:with tempfile.TemporaryDirectory(prefix="sprite-gen-rife-") as td:@@ -1367,6 +1458,11 @@ class RemoteRunner:self.calls = 0self.remote: dict = {}self.remote = self._sent({"probe": True}, {}, {})[0]+ held, wanted = self.remote.get("model"), model_name()+ if held != wanted:+ raise RifeUnavailable(f"{self.name}: the executor runs the model {held!r}, and this host runs {wanted} "+ "(SPRITE_GEN_RIFE_MODEL_NAME, else the default): run one model on both sides")+ self.model_name = wanteddef frame(self, colour: list[np.ndarray], cover: list[np.ndarray], t: float) -> tuple[np.ndarray, np.ndarray]:made = self._made(colour, cover, t, read=False)@@ -1385,11 +1481,11 @@ class RemoteRunner:def _made(self, colour: list[np.ndarray], cover: list[np.ndarray], t: float, *, read: bool) -> dict[str, np.ndarray]:"""A frame, or a read, made by the executor in one call: the request names the identity held, the fraction, the- augmentation this host asks for now (`tta()`) and whether the passes are read; the answer is that identity's, at+ augmentation this host asks for its model now (`tta()`) and whether the passes are read; the answer is that identity's, atthe frame's size, or it is not handed on."""h, w = cover[0].shapewant = {"rgb": ((h, w, 3), np.uint8), "alpha": ((h, w), np.uint8), **({"apart": ((h, w), np.float32)} if read else {})}- return self._sent({"expect": self.remote, "t": t, "modes": list(tta()), "read": read},+ return self._sent({"expect": self.remote, "t": t, "modes": list(tta(self.model_name)), "read": read},{"colour_a": colour[0], "colour_b": colour[1], "cover_a": cover[0], "cover_b": cover[1]}, want)[1]def _sent(self, header: dict, arrays: dict[str, np.ndarray],@@ -1451,7 +1547,7 @@ def torch_runner(model: Path | None = None) -> object:rife_torch = importlib.import_module("sprite_gen.video.rife_torch")except ImportError as exc:raise RifeNotInstalled(f"SPRITE_GEN_RIFE_BACKEND=torch, and PyTorch cannot be imported ({exc}); install it and the "- f"model {MODEL} with `{install_command()}`; see docs/loop-repair.md") from exc+ f"model {model_name()} with `{install_command()}`; see docs/loop-repair.md") from excexcept OSError as exc: # installed, and its libraries do not load: a RIFE found that failsraise RifeUnavailable(f"SPRITE_GEN_RIFE_BACKEND=torch, and PyTorch failed to load: {exc}") from excreturn rife_torch.TorchRunner(model or locate_model(), named)@@ -1478,7 +1574,10 @@ class Rife:runner = torch_runner()self.runner = runnerself.binary, self.model = getattr(runner, "binary", None), getattr(runner, "model", None)- self.tta = tta() # refused here, before a frame is asked for+ # the model its runner runs (a runner stood in names none: the one `model_name()` names), and its augmentation,+ # refused here, before a frame is asked for+ self.model_name = getattr(runner, "model_name", None) or model_name()+ self.tta = tta(self.model_name)self.made = 0self.calls = 0@@ -1497,9 +1596,9 @@ class Rife:return _joined(rgb, alpha), apartdef describe(self) -> dict[str, str]:- """What made the frames, for a report: its `kind` (`rife-ncnn-vulkan`, `rife-torch`), where it runs from, and the- augmentation."""- return {**self.runner.describe(), "tta": " ".join(self.tta)} # type: ignore[attr-defined]+ """What made the frames, for a report: its `kind` (`rife-ncnn-vulkan`, `rife-torch`), where it runs from, the model+ and the augmentation."""+ return {**self.runner.describe(), "model": self.model_name, "tta": " ".join(self.tta)} # type: ignore[attr-defined]def counts(self) -> dict[str, int]:"""The runs it made, as a report names them: the binary's calls (`binary_calls`), or the torch backend's runs@@ -1515,14 +1614,14 @@ class Rife:binary or model changed under this very RIFE is another identity; for the torch backend what it loaded and runson, the same for its life; on an executor what the executor answered as this RIFE was made, held for its life andenforced on every frame it makes, and the executor's name) and this host's, read as it is now on every call: the augmentation every call asks- for now (`tta()`: SPRITE_GEN_RIFE_TTA is read on every call, and another is another frame); the engine code this+ for now (`tta()` for its model: SPRITE_GEN_RIFE_TTA is read on every call, and another is another frame); the engine code thisprocess loaded (`CODE_SHA256`: it turns a frame into RIFE's two runs and back) and NumPy's andPillow's versions; and the machine — the OS, and `uname`'s host name, OS release and build andarchitecture (platform.uname() keeps its first answer) — as the Apple GPU and llvmpipe are only measuredto agree to the third decimal of an error (docs/loop-repair.md section 1), so a frame made on one is nottaken on another."""return json.dumps({- **self.runner.identity(), "tta": list(tta()), "code": CODE_SHA256, "numpy": np.__version__, # type: ignore[attr-defined]+ **self.runner.identity(), "tta": list(tta(self.model_name)), "code": CODE_SHA256, "numpy": np.__version__, # type: ignore[attr-defined]"pillow": PIL.__version__, "machine": [sys.platform, *(os.uname() if hasattr(os, "uname") else platform.uname()[:5])]},sort_keys=True)diff --git a/sprite_gen/video/rife_install.py b/sprite_gen/video/rife_install.pyindex bb7c0ba..ea2b30a 100644--- a/sprite_gen/video/rife_install.py+++ b/sprite_gen/video/rife_install.py@@ -1,18 +1,19 @@# SPDX-License-Identifier: Apache-2.0"""`sprite-gen rife install` — put the pinned RIFE where the engine finds it.-Downloads the rife-ncnn-vulkan release zip for this platform (pinned release and SHA-256,+Downloads TNTwise's rife-ncnn-vulkan release zip for this platform (pinned release and SHA-256,docs/loop-repair.md section 1), checks the hash before anything is unpacked, and keeps only what-the engine runs: the binary, the model `rife-v4.6/`, the licence and readme (and on Windows the-OpenMP runtime the binary loads). The install lands in `rife.install_root()` — the user data+the engine runs: the binary, the models `rife-v4.25/` (the default) and `rife-v4.6/`, the licence and+readme (and on Windows the OpenMP runtime the binary loads). The install lands in `rife.install_root()` — the user datadirectory — which `rife.locate()` searches after SPRITE_GEN_RIFE and PATH. `--dir` installssomewhere else and prints the SPRITE_GEN_RIFE line that points the engine at it.Unpacked into a staging directory and renamed into place, so an interrupted install never leaves-a half-written RIFE where the engine looks; the model's two files are checked against their pinned+a half-written RIFE where the engine looks; each model's two files are checked against their pinnedSHA-256 (`rife.MODEL_SHA256`) before it is. Running it again over a finished install of the samezip does nothing but the check. The check makes one frame between two discs through the-installed binary, so a machine that has the files but no working Vulkan finds out here.+installed binary and the model the engine runs (`rife.model_name()`), so a machine that has the files+but no working Vulkan finds out here.`--backend torch` (the default where SPRITE_GEN_RIFE_BACKEND names torch) installs the same zip for thetorch backend, which reads the model only (`rife.locate_model()`): a Linux machine the binary does not run@@ -43,33 +44,37 @@ from sprite_gen.util.console import utf8_streams# SHA-256 of each release zip, measured on the downloaded files (docs/loop-repair.md section 1).ZIP_SHA256 = {- "macos": "4a63a1f3c9c715773c57d2ee51df1b315ed20cd6c63103e45c483ecc4400b595",- "ubuntu": "1e2c7ee7fa7daa326542d50622f0afedc80cf6f1858bda411d16385ffa5cdf68",- "windows": "d8e4d772d26cd8006ef0ad0bc82eb191b53c68677d1ae2f42506d74cbbbea606",+ "macos": "543bf845a6160d8ad29a10c2b7a0713e78781dc2505c62185f7d14c3265bb4c0",+ "ubuntu": "a4166da15a9839350a3695c35d9e19288c5c48c0fc9afc5aacb766d3d7f8ab62",+ "windows": "42ed35e115b026f222386648920218cb8a9c7ae1e23698a7363bdd2e1455aba3",}+# The folder each zip holds the release in (the Windows zip's is named after the branch it was built from).+ZIP_TOP = {"macos": "macos", "ubuntu": "ubuntu", "windows": "rife-ncnn-vulkan-refs/heads/master-windows"}# The machines each zip's binary runs on (`platform.machine()`, lower case). The macOS binary is# universal; the Linux and Windows ones are x86-64 only.ZIP_MACHINES = {"macos": None, "ubuntu": {"x86_64", "amd64"}, "windows": {"amd64", "x86_64"}}-URL = "https://github.com/nihui/rife-ncnn-vulkan/releases/download/{release}/{name}"+SOURCE = "github.com/TNTwise/rife-ncnn-vulkan"+URL = "https://github.com/TNTwise/rife-ncnn-vulkan/releases/download/{release}/{name}"MARKER = ".sprite-gen-install.json"CHUNK = 1 << 20TIMEOUT_SECONDS = 60def zip_name(platform: str) -> str:- return f"{rife.BINARY}-{rife.RELEASE}-{platform}.zip"+ """The release zip's name for a platform, as the release names it."""+ return f"{platform}.zip"def _platform(platform: str | None, backend: str = "ncnn") -> str:name = platform or rife.platform_release()if name not in ZIP_SHA256:raise SystemExit(f"rife install: rife-ncnn-vulkan {rife.RELEASE} ships no build for {sys.platform}; build it from "- f"github.com/nihui/rife-ncnn-vulkan and set SPRITE_GEN_RIFE to the binary (docs/loop-repair.md)")+ f"{SOURCE} and set SPRITE_GEN_RIFE to the binary (docs/loop-repair.md)")machines = ZIP_MACHINES[name]machine = platform_mod.machine().lower()if backend == "ncnn" and platform is None and machines is not None and machine not in machines:raise SystemExit(f"rife install: the {name} build of rife-ncnn-vulkan {rife.RELEASE} is x86-64 only and this machine "- f"is {machine}; build it from github.com/nihui/rife-ncnn-vulkan and set SPRITE_GEN_RIFE to the binary")+ f"is {machine}; build it from {SOURCE} and set SPRITE_GEN_RIFE to the binary")return name@@ -102,15 +107,18 @@ def _kept(member: str, top: str, platform: str) -> bool:rel = member[len(top) + 1:]if any(part in ("", ".", "..") for part in rel.split("/")):return False- if rel.startswith(rife.MODEL + "/"):- return "/" not in rel[len(rife.MODEL) + 1:]- if "/" in rel:- return False+ folder, _, rest = rel.partition("/")+ if rest:+ return folder in rife.MODELS and "/" not in restreturn rel in (rife.BINARY, rife.BINARY + ".exe", "LICENSE", "README.md") or (platform == "windows" and rel.lower().endswith(".dll"))+def _models_whole(where: Path) -> bool:+ return all((where / m / f).is_file() for m in rife.MODELS for f in ("flownet.param", "flownet.bin"))++def _unpack(zip_path: Path, staging: Path, platform: str) -> list[str]:- top = f"{rife.BINARY}-{rife.RELEASE}-{platform}"+ top = ZIP_TOP[platform]kept: list[str] = []with zipfile.ZipFile(zip_path) as zf:for info in zf.infolist():@@ -123,9 +131,9 @@ def _unpack(zip_path: Path, staging: Path, platform: str) -> list[str]:shutil.copyfileobj(src, out, CHUNK)kept.append(rel)binary = staging / rife.installed_binary(Path("."), platform).name- model = staging / rife.MODEL- if not binary.is_file() or not (model / "flownet.param").is_file() or not (model / "flownet.bin").is_file():- raise SystemExit(f"rife install: {zip_path.name} has no {top}/{binary.name} with {rife.MODEL}/flownet.param and flownet.bin")+ if not binary.is_file() or not _models_whole(staging):+ models = " and ".join(f"{m}/flownet.param and flownet.bin" for m in rife.MODELS)+ raise SystemExit(f"rife install: {zip_path.name} has no {top}/{binary.name} with {models}")binary.chmod(binary.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)return sorted(kept)@@ -136,8 +144,7 @@ def _complete(target: Path, platform: str, sha: str) -> bool:except (OSError, ValueError):return Falsebinary = target / rife.installed_binary(Path("."), platform).name- return (marker.get("sha256") == sha and binary.is_file()- and all((target / rife.MODEL / f).is_file() for f in ("flownet.param", "flownet.bin")))+ return marker.get("sha256") == sha and binary.is_file() and _models_whole(target)def _disc(cx: int) -> Image.Image:@@ -148,8 +155,8 @@ def _disc(cx: int) -> Image.Image:def check(binary: Path, model: Path, *, backend: str = "ncnn") -> dict[str, Any]:- """One frame half way between two discs through `binary`, or through the torch backend from `model`: the disc must- land in the middle."""+ """One frame half way between two discs through `binary` running `model`, or through the torch backend from `model`:+ the disc must land in the middle."""try:made = rife.Rife(binary, model) if backend == "ncnn" else rife.Rife(runner=rife.torch_runner(model))mid = made(_disc(30), _disc(66), 0.5)@@ -172,12 +179,16 @@ def install(*, dest: Path | None = None, zip_path: Path | None = None, platform:raise SystemExit(f"rife install: {exc}") from excif backend not in rife.BACKENDS:raise SystemExit(f"rife install: backend {backend!r}: name ncnn or torch")+ try:+ model_name = rife.model_name()+ except rife.RifeUnavailable as exc:+ raise SystemExit(f"rife install: {exc}") from excname = _platform(platform, backend)sha = ZIP_SHA256[name]root = (dest or rife.install_root()).expanduser().resolve()binary = rife.installed_binary(root, name)target = binary.parent- report: dict[str, Any] = {"backend": backend, "release": rife.RELEASE, "model": rife.MODEL, "platform": name,+ report: dict[str, Any] = {"backend": backend, "release": rife.RELEASE, "model": model_name, "platform": name,"zip": zip_name(name), "sha256": sha, "dir": str(target), "binary": str(binary)}if not force and _complete(target, name, sha):report["installed"] = "already"@@ -199,7 +210,8 @@ def install(*, dest: Path | None = None, zip_path: Path | None = None, platform:staging = work / target.namereport["files"] = _unpack(zip_path, staging, name)try:- rife.model_bytes(staging / rife.MODEL)+ for model in rife.MODELS:+ rife.model_bytes(staging / model)except rife.RifeUnavailable as exc:raise SystemExit(f"rife install: {exc}; nothing was installed") from exc(staging / MARKER).write_text(json.dumps({"release": rife.RELEASE, "zip": zip_name(name), "sha256": sha}) + "\n",@@ -209,7 +221,7 @@ def install(*, dest: Path | None = None, zip_path: Path | None = None, platform:staging.rename(target)report["installed"] = "now"if run_check:- report["check"] = check(binary, target / rife.MODEL, backend=backend)+ report["check"] = check(binary, target / model_name, backend=backend)if backend == "torch":# What the torch backend will read: SPRITE_GEN_RIFE_MODEL before the install root.try:@@ -217,9 +229,9 @@ def install(*, dest: Path | None = None, zip_path: Path | None = None, platform:except rife.RifeUnavailable:found = Nonereport["engine_finds"] = found- if found != str((target / rife.MODEL).resolve()):+ if found != str((target / model_name).resolve()):report["note"] = (f"the torch backend reads SPRITE_GEN_RIFE_MODEL before {rife.install_root()}; to read this "- f"install set SPRITE_GEN_RIFE_MODEL={target / rife.MODEL}" + (f" (it now reads {found})" if found else ""))+ f"install set SPRITE_GEN_RIFE_MODEL={target / model_name}" + (f" (it now reads {found})" if found else ""))return report# What the engine will run: SPRITE_GEN_RIFE and PATH are searched before the install root.try:@@ -238,7 +250,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:p = sub.add_parser("install", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)p.add_argument("--dir", type=Path, help=f"install root (default: the user data directory, {rife.install_root()}; ""another directory needs SPRITE_GEN_RIFE, which the command prints)")- p.add_argument("--zip", type=Path, help=f"use this already-downloaded release zip ({zip_name('<platform>')}) instead of downloading it; "+ p.add_argument("--zip", type=Path, help=f"use this already-downloaded release zip ({SOURCE} {rife.RELEASE}, "+ f"{zip_name('<platform>')}) instead of downloading it; ""its SHA-256 is checked all the same")p.add_argument("--force", action="store_true", help="unpack again over a finished install")p.add_argument("--no-check", action="store_true", help="skip the check frame made through the installed binary")diff --git a/sprite_gen/video/rife_torch.py b/sprite_gen/video/rife_torch.pyindex 0c26a6f..9d6166b 100644--- a/sprite_gen/video/rife_torch.py+++ b/sprite_gen/video/rife_torch.py@@ -1,22 +1,33 @@# SPDX-License-Identifier: Apache-2.0-# The IFNet below follows Practical-RIFE's IFNet_HDv3 and warplayer (MIT, Copyright (c) 2021 hzwer; NOTICE).+# The IFNets below follow Practical-RIFE's IFNet_HDv3 and warplayer (MIT, Copyright (c) 2021 hzwer; NOTICE).# The augmentation loop follows rife-ncnn-vulkan 20221029's RIFE::process_v4 (MIT, Copyright (c) 2020 nihui; NOTICE).-"""rife-v4.6 in PyTorch: the torch backend of `rife.Rife` (SPRITE_GEN_RIFE_BACKEND=torch, docs/loop-repair.md section 1).+"""RIFE in PyTorch, rife-v4.25 or rife-v4.6: the torch backend of `rife.Rife` (SPRITE_GEN_RIFE_BACKEND=torch,+docs/loop-repair.md section 1).The one module of the engine that imports torch, and it is imported only where the torch backend is chosen(`rife.Rife()`), so the engine runs without PyTorch and is refused for it only there (`rife.RifeNotInstalled`).-The network is rife-v4.6's IFNet (Practical-RIFE f6b5132, `train_log/IFNet_HDv3.py`, `model/warplayer.py`) written-again here with the same parameter names — four IFBlocks of two strided 3x3 convolutions, eight residual convolutions and-a transposed convolution, the warp a bilinear `grid_sample` at the border — rather than imported: the official module-makes its warp grid on a device it picks itself at import.--Its weights are the binary's own model (`rife.MODEL_SHA256`), read without ncnn (`state_from_ncnn`): the 44-convolutions of `flownet.param` in file order, their float16 weights widened to float32 and their float32 biases; a-residual convolution's scale (`beta`) is folded into its convolution there, so it is 1 here; a transposed convolution's-weights are stored (out, in, ...) and read (in, out, ...). The same weights as the binary, as rounded for it.--What the binary's augmentation does inside one call is done here the same way (rife-ncnn-vulkan 20221029+Each network is the model's IFNet written again here with the same parameter names, rather than imported — the official+module makes its warp grid on a device it picks itself at import (`NETS`):++- rife-v4.25 (Practical-RIFE 4.25, `train_log/IFNet_HDv3.py`, `model/warplayer.py`): an encoder (`Head`: three 3x3+ convolutions, the first strided, and a transposed one, to four planes at the image's size) run on each image, and five+ IFBlocks at scales 16 to 1, each handed the two images warped, their encodings warped, t, the last block's mask and its+ eight planes of features, and returning a flow added to the last, a mask in its place and features; the frame is the+ two images warped by the last flow and blended by its mask. Each image is padded with zeros to a multiple of 128, as+ Practical-RIFE pads it at scale 1 and the engine hands the binary it (`rife.MODELS`). It runs with no augmentation.+- rife-v4.6 (Practical-RIFE f6b5132): four IFBlocks of two strided 3x3 convolutions, eight residual convolutions and a+ transposed convolution, the warp a bilinear `grid_sample` at the border, with the binary's augmentation below.++Its weights are the binary's own model (`rife.MODEL_SHA256`), read without ncnn (`state_from_ncnn`): the convolutions of+`flownet.param` in file order, their float16 weights widened to float32 and their float32 biases, and where the model+holds them apart, each residual convolution's scale (`beta`, float32) before it; a transposed convolution's weights are+stored (out, in, ...) and read (in, out, ...). rife-v4.6 folds each beta into its convolution, so it is 1 here; rife-v4.25+holds its encoder twice, once for each image, the two copies the same, which is checked. The same weights as the binary,+as rounded for it: rife-v4.25's are Practical-RIFE's published `flownet.pkl` (sha256+6615790efd627772917205db291f51cd392528a157ecbb2ecaeec3bff8eb6de2) cut to float16, its biases and betas the same.++What the binary's augmentation does inside one call is done here the same way for rife-v4.6 (rife-ncnn-vulkan 20221029`RIFE::process_v4`, `-x` and `-z`): the pair, padded with zeros to a multiple of 32, is turned its eight ways (`_geo`: 0as is, 1 left-right, 2 both, 3 up-down, 4 transposed, 5-7 transposed then 1-3) and run both ways in time (b to a at1 - t); at each of the four levels every way's flows and mask are turned back to the pair's own frame (`_to_canon`; the@@ -41,6 +52,7 @@ import reimport shutilimport subprocessfrom pathlib import Path+from typing import NamedTupleimport torchimport torch.nn as nn@@ -51,13 +63,56 @@ from sprite_gen.video import rife# The network code this process loaded (the runner's identity, `net`), read at import as rife.CODE_SHA256 is.CODE_SHA256 = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()-SCALES = (8, 4, 2, 1)-BLOCKS = ((7, 192), (12, 128), (12, 96), (12, 64)) # (input planes, width) of each IFBlock-# The official state dict's convolutions in the order the ncnn model holds them: each block's two strided ones, its-# eight residual ones and its transposed one.-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"))+++class Net(NamedTuple):+ """A model's IFNet: its blocks' (input planes, width), the scale each runs at, the planes its transposed convolution+ makes before the pixel shuffle (flow, mask and, for rife-v4.25, eight of features, times four), whether it encodes+ each image first (`Head`), and the multiple each image is padded to with zeros."""++ blocks: tuple[tuple[int, int], ...]+ scales: tuple[int, ...]+ out: int+ head: bool+ pad: int+++# rife-v4.6 is padded to 32 as the binary pads it, handed each image as it is; rife-v4.25 to 128 as the engine hands the+# binary each image padded (`rife.MODELS`).+NETS = {+ "rife-v4.25": Net(blocks=((7 + 8, 192), (8 + 4 + 8 + 8, 128), (28, 96), (28, 64), (28, 32)), scales=(16, 8, 4, 2, 1),+ out=4 * 13, head=True, pad=rife.MODELS["rife-v4.25"].pad),+ "rife-v4.6": Net(blocks=((7, 192), (12, 128), (12, 96), (12, 64)), scales=(8, 4, 2, 1), out=4 * 6, head=False, pad=32),+}+SCALES = NETS["rife-v4.6"].scales+BLOCKS = NETS["rife-v4.6"].blocks # (input planes, width) of each IFBlock+HEAD = ("encode.cnn0", "encode.cnn1", "encode.cnn2", "encode.cnn3")NCNN_FLOAT16 = 0x01306B47 # ncnn's tag before a float16 weight blob; a float32 one is tagged 0+++def layers(name: str) -> tuple[tuple[str, str], ...]:+ """The official state dict's parameters in the order the model's ncnn files hold them, each with its ncnn layer type:+ for rife-v4.6 each block's two strided convolutions, its eight residual ones and its transposed one; for rife-v4.25 the+ encoder twice (once for each image), then each block's first beta, its two strided convolutions, its residual+ convolutions each after its beta (the first's before the strided ones), and its transposed one."""+ net = NETS[name]+ found: list[tuple[str, str]] = []+ if net.head:+ found += [(h, "Deconvolution" if h.endswith("cnn3") else "Convolution") for h in HEAD] * 2+ for i in range(len(net.blocks)):+ b = f"block{i}"+ if net.head:+ found += [(f"{b}.convblock.0.beta", "MemoryData"), (f"{b}.conv0.0.0", "Convolution"), (f"{b}.conv0.1.0", "Convolution")]+ for j in range(8):+ found += ([(f"{b}.convblock.{j}.beta", "MemoryData")] if j else []) + [(f"{b}.convblock.{j}.conv", "Convolution")]+ else:+ found += [(f"{b}.conv0.0.0", "Convolution"), (f"{b}.conv0.1.0", "Convolution"),+ *((f"{b}.convblock.{j}.conv", "Convolution") for j in range(8))]+ found.append((f"{b}.lastconv.0", "Deconvolution"))+ return tuple(found)+++LAYERS = tuple(n for n, _ in layers("rife-v4.6"))NVIDIA_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`)@@ -83,11 +138,11 @@ class ResConv(nn.Module):class IFBlock(nn.Module):- def __init__(self, in_planes: int, c: int):+ def __init__(self, in_planes: int, c: int, out: int = 4 * 6):super().__init__()self.conv0 = nn.Sequential(_conv(in_planes, c // 2), _conv(c // 2, c))self.convblock = nn.Sequential(*(ResConv(c) for _ in range(8)))- self.lastconv = nn.Sequential(nn.ConvTranspose2d(c, 4 * 6, 4, 2, 1), nn.PixelShuffle(2))+ self.lastconv = nn.Sequential(nn.ConvTranspose2d(c, out, 4, 2, 1), nn.PixelShuffle(2))def raw(self, x: torch.Tensor, flow: torch.Tensor | None, scale: int) -> torch.Tensor:"""The official IFBlock.forward up to its output at the block's own scale, before it is scaled back up."""@@ -97,23 +152,52 @@ class IFBlock(nn.Module):x = torch.cat((x, flow), 1)return self.lastconv(self.convblock(self.conv0(x)))+ def forward(self, x: torch.Tensor, flow: torch.Tensor | None, scale: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """The official IFBlock.forward of rife-v4.25: the flow at the image's size, the mask and the features."""+ tmp = F.interpolate(self.raw(x, flow, scale), scale_factor=scale, mode="bilinear", align_corners=False)+ return tmp[:, :4] * scale, tmp[:, 4:5], tmp[:, 5:]+++class Head(nn.Module):+ """rife-v4.25's encoder: an image to four planes of features at its size."""-class IFNet(nn.Module):def __init__(self):super().__init__()- for i, (cin, c) in enumerate(BLOCKS):- setattr(self, f"block{i}", IFBlock(cin, c))+ self.cnn0 = nn.Conv2d(3, 16, 3, 2, 1)+ self.cnn1 = nn.Conv2d(16, 16, 3, 1, 1)+ self.cnn2 = nn.Conv2d(16, 16, 3, 1, 1)+ self.cnn3 = nn.ConvTranspose2d(16, 4, 4, 2, 1)+ self.relu = nn.LeakyReLU(0.2, True)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return self.cnn3(self.relu(self.cnn2(self.relu(self.cnn1(self.relu(self.cnn0(x)))))))+++class IFNet(nn.Module):+ def __init__(self, name: str = "rife-v4.6"):+ super().__init__()+ net = NETS[name]+ for i, (cin, c) in enumerate(net.blocks):+ setattr(self, f"block{i}", IFBlock(cin, c, net.out))+ if net.head:+ self.encode = Head()-def _ncnn_layers(param: bytes, weights: bytes) -> list[tuple[str, np.ndarray, np.ndarray]]:- """The convolutions of an ncnn model in file order: (layer type, weights, biases) as float32."""+def _ncnn_layers(param: bytes, weights: bytes) -> list[tuple[str, np.ndarray, np.ndarray | None]]:+ """The layers of an ncnn model that hold weights, in file order: (layer type, weights, biases) as float32 — a+ convolution's, and a MemoryData's values with no biases."""layers, pos = [], 0for line in param.decode("utf-8").split("\n")[2:]:parts = line.split()- if len(parts) < 4 or parts[0] not in ("Convolution", "Deconvolution"):+ if len(parts) < 4 or parts[0] not in ("Convolution", "Deconvolution", "MemoryData"):continuen_in, n_out = int(parts[2]), int(parts[3])kv = dict(p.split("=", 1) for p in parts[4 + n_in + n_out:])+ if parts[0] == "MemoryData": # its values float32 as they are, untagged (ncnn's MemoryData::load_model)+ size = math.prod(max(1, int(kv.get(k, 1))) for k in ("0", "1", "11", "2"))+ layers.append((parts[0], np.frombuffer(weights, np.float32, size, pos).copy(), None))+ pos += size * 4+ continuenum_output, size = int(kv["0"]), int(kv["6"])tag = int.from_bytes(weights[pos:pos + 4], "little")pos += 4@@ -135,22 +219,34 @@ def _ncnn_layers(param: bytes, weights: bytes) -> list[tuple[str, np.ndarray, npreturn layers-def state_from_ncnn(files: dict[str, bytes]) -> dict[str, torch.Tensor]:- """The official state dict of IFNet, every name and shape, filled from the ncnn model's files (`rife.model_bytes`)."""- shapes = {k: v.shape for k, v in IFNet().state_dict().items()}- layers = _ncnn_layers(files["flownet.param"], files["flownet.bin"])- if len(layers) != len(LAYERS):- raise ValueError(f"{len(layers)} convolutions in the model, {len(LAYERS)} in the network")- state = {}- for name, (kind, w, b) in zip(LAYERS, layers):- shape = shapes[name + ".weight"]+def state_from_ncnn(files: dict[str, bytes], name: str = "rife-v4.6") -> dict[str, torch.Tensor]:+ """The official state dict of model `name`'s IFNet, every name and shape, filled from the ncnn model's files+ (`rife.model_bytes`): its layers in the order `layers` names them, each of the type named there, and a part the+ model holds twice (rife-v4.25's encoder) the same both times."""+ shapes = {k: v.shape for k, v in IFNet(name).state_dict().items()}+ found = _ncnn_layers(files["flownet.param"], files["flownet.bin"])+ order = layers(name)+ if len(found) != len(order):+ raise ValueError(f"{len(found)} layers with weights in the model, {len(order)} in the network")+ state: dict[str, torch.Tensor] = {}+ for (param, wanted), (kind, w, b) in zip(order, found):+ if kind != wanted:+ raise ValueError(f"{param}: the model holds a {kind} where the network has a {wanted}")+ if kind == "MemoryData":+ state[param] = torch.from_numpy(w).reshape(shapes[param])+ continue+ shape = shapes[param + ".weight"]if kind == "Deconvolution":weight = torch.from_numpy(w).reshape(shape[1], shape[0], *shape[2:]).transpose(0, 1).contiguous()else:weight = torch.from_numpy(w).reshape(shape)- state[name + ".weight"], state[name + ".bias"] = weight, torch.from_numpy(b).reshape(shapes[name + ".bias"])- if ".convblock." in name:- beta = name.removesuffix(".conv") + ".beta"+ bias = torch.from_numpy(b).reshape(shapes[param + ".bias"])+ if param + ".weight" in state and not (torch.equal(state[param + ".weight"], weight)+ and torch.equal(state[param + ".bias"], bias)):+ raise ValueError(f"{param}: the model's two copies differ")+ state[param + ".weight"], state[param + ".bias"] = weight, bias+ if not NETS[name].head and ".convblock." in param: # rife-v4.6: the beta folded into the convolution+ beta = param.removesuffix(".conv") + ".beta"state[beta] = torch.ones(shapes[beta])return state@@ -229,8 +325,8 @@ def _deterministic() -> dict[str, object]:class TorchRunner:- """rife-v4.6 on a torch device, as the runner of a `rife.Rife`: the model in `model` (`rife.model_bytes`, checked- before it is read) loaded once, a frame its two runs and a read its sixteen passes as well (`rife.frame_runs`,+ """RIFE on a torch device, as the runner of a `rife.Rife`: the model in `model` (`rife.model_bytes`, checked+ before it is read; rife-v4.25 or rife-v4.6 by the directory's name, `rife.held_model`) loaded once, a frame its two runs and a read its sixteen passes as well (`rife.frame_runs`,`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.@@ -246,13 +342,15 @@ 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)+ self.model_name = rife.held_model(model)try:- net = IFNet()- net.load_state_dict(state_from_ncnn(files), strict=True)+ net = IFNet(self.model_name)+ net.load_state_dict(state_from_ncnn(files, self.model_name), strict=True)except (ValueError, RuntimeError) as exc:raise rife.RifeUnavailable(f"rife-torch: the model {model} does not load: {exc}") from exc- self.model, self.device = model, device+ self.model, self.device, self.net_of = model, device, NETS[self.model_name]ident: dict[str, object] = {"backend": "torch", "device": device, "net": CODE_SHA256, "torch": torch.__version__,+ "model": self.model_name,"weights": {name: hashlib.sha256(data).hexdigest() for name, data in files.items()}}try:self.net = net.to(device).eval()@@ -265,7 +363,7 @@ class TorchRunner: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.blocks = tuple(getattr(self.net, f"block{i}") for i in range(len(self.net_of.blocks)))self._grids: dict[tuple, torch.Tensor] = {}self._identity = ident@@ -283,11 +381,13 @@ 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`, four- decimals), the augmentation `modes` (None: `rife.tta()`); on CUDA under the settings that make it the same bytes,- set again for each run (other code in the process may set them), whoever asks for it — a frame, a read, or an- executor's request (`serve`). A run that fails on the device (out of its memory) is a RIFE that fails- (`DEVICE_FAILURES`, `rife.RifeUnavailable`)."""- modes = rife.tta() if modes is None else modes+ decimals), the augmentation `modes` (None: `rife.tta()` for the model; rife-v4.25 takes none); on CUDA under the+ settings that make it the same bytes, set again for each run (other code in the process may set them), whoever asks+ for it — a frame, a read, or an executor's request (`serve`). A run that fails on the device (out of its memory) is+ a RIFE that fails (`DEVICE_FAILURES`, `rife.RifeUnavailable`)."""+ modes = rife.tta(self.model_name) if modes is None else modes+ if modes and self.net_of.head:+ raise rife.RifeUnavailable(f"rife-torch: {self.model_name} runs with no augmentation, asked for {' '.join(modes)}")try:if self.device == "cuda":_deterministic()@@ -299,16 +399,21 @@ class TorchRunner:def _run(self, x: np.ndarray, y: np.ndarray, t: float, modes: tuple[str, ...]) -> np.ndarray:h, w = x.shape[:2]pads = [self._pad(im) for im in (x, y)]- ways = [(g, d) for g in (range(8) if "-x" in modes else (0,)) for d in ((0, 1) if "-z" in modes else (0,))]- frames, _ = self._infer(pads, t, ways)+ if self.net_of.head:+ frames = [self._encoded(pads, t)]+ else:+ ways = [(g, d) for g in (range(8) if "-x" in modes else (0,)) for d in ((0, 1) if "-z" in modes else (0,))]+ frames, _ = self._infer(pads, t, ways)v = torch.stack(frames).mean(0)[0, :, :h, :w]v = torch.clamp(torch.floor(v * 255.0 + 0.5), 0, 255).to(torch.uint8)return v.permute(1, 2, 0).contiguous().cpu().numpy()def _pad(self, im: np.ndarray) -> torch.Tensor:- """An H x W x 3 uint8 image on the device, 0..1, padded with zeros at the bottom and right to a multiple of 32."""+ """An H x W x 3 uint8 image on the device, 0..1, padded with zeros at the bottom and right to the model's multiple+ (`NETS`: 32 for rife-v4.6, 128 for rife-v4.25)."""h, w = im.shape[:2]- x = torch.zeros((1, 3, math.ceil(h / 32) * 32, math.ceil(w / 32) * 32), dtype=torch.float32, device=self.device)+ m = self.net_of.pad+ x = torch.zeros((1, 3, math.ceil(h / m) * m, math.ceil(w / m) * m), dtype=torch.float32, device=self.device)x[0, :, :h, :w] = torch.from_numpy(np.ascontiguousarray(im.transpose(2, 0, 1))).to(self.device).float() / 255.0return x@@ -324,6 +429,26 @@ class TorchRunner:return F.grid_sample(img, (self._grids[k] + flow).permute(0, 2, 3, 1), mode="bilinear", padding_mode="border",align_corners=True)+ def _encoded(self, pads: list[torch.Tensor], t: float) -> torch.Tensor:+ """rife-v4.25's IFNet.forward on a padded pair at `t` (Practical-RIFE 4.25, scale 1): each image encoded, five+ blocks, each after the first handed the images and their encodings warped by the flow so far, t, the last mask+ and features, its flow added and its mask taking the last one's place; the frame blended by the last mask+ (1 x 3 x H x W)."""+ img0, img1 = pads+ f0, f1 = self.net.encode(img0), self.net.encode(img1)+ ts = torch.full_like(img0[:, :1], t)+ flow = mask = feat = w0 = w1 = None+ for block, scale in zip(self.blocks, self.net_of.scales):+ if flow is None:+ flow, mask, feat = block(torch.cat((img0, img1, f0, f1, ts), 1), None, scale)+ else:+ wf0, wf1 = self._warp(f0, flow[:, :2]), self._warp(f1, flow[:, 2:4])+ fd, mask, feat = block(torch.cat((w0, w1, wf0, wf1, ts, mask, feat), 1), flow, scale)+ flow = flow + fd+ w0, w1 = self._warp(img0, flow[:, :2]), self._warp(img1, flow[:, 2:4])+ m = torch.sigmoid(mask)+ return (w0 * m + w1 * (1 - m)).float()+def _infer(self, pads: list[torch.Tensor], t: float, ways: list[tuple[int, int]], *,flows: bool = False) -> tuple[list[torch.Tensor], list[torch.Tensor] | None]:"""The four levels over `ways` — (g, d): turned way g, forward (d 0: the first to the second at t) or backwarddiff --git a/tests/conftest.py b/tests/conftest.pyindex a2885ca..171d25b 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -107,8 +107,8 @@ def pytest_addoption(parser: pytest.Parser) -> None:def _torch_rife_missing() -> str | None:- """Why the torch backend cannot run here, None where it can: PyTorch, the rife-v4.6 model it reads- (`rife.locate_model()`) and the device SPRITE_GEN_RIFE_DEVICE names."""+ """Why the torch backend cannot run here, None where it can: PyTorch, the model it reads (`rife.locate_model()`,+ rife-v4.25 unless another is named) and the device SPRITE_GEN_RIFE_DEVICE names."""from sprite_gen.video import rifetry:@@ -181,9 +181,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`) and its backend, the binary, in this process: a- SPRITE_GEN_RIFE_TTA, SPRITE_GEN_RIFE_BACKEND or SPRITE_GEN_RIFE_EXECUTOR 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."""+ """Every test runs the model and augmentation the engine ships (`rife.MODEL`, its `rife.MODELS` augmentation) and its+ backend, the binary, in this process: a SPRITE_GEN_RIFE_MODEL_NAME, SPRITE_GEN_RIFE_TTA, SPRITE_GEN_RIFE_BACKEND or+ SPRITE_GEN_RIFE_EXECUTOR 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, and SPRITE_GEN_RIFE_MODEL where the model+ is (a lane names the default model's directory)."""+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL_NAME", raising=False)monkeypatch.delenv("SPRITE_GEN_RIFE_TTA", raising=False)monkeypatch.delenv("SPRITE_GEN_RIFE_BACKEND", raising=False)monkeypatch.delenv("SPRITE_GEN_RIFE_EXECUTOR", raising=False)diff --git a/tests/video/test_between_cache.py b/tests/video/test_between_cache.pyindex b7cd6a0..73e0e46 100644--- a/tests/video/test_between_cache.py+++ b/tests/video/test_between_cache.py@@ -210,7 +210,7 @@ def test_the_same_rife_is_another_identity_once_its_machine_libraries_or_code_chassert (cache.hits, cache.misses) == (1, 6)-def _picking_rife(root: Path) -> tuple[Path, Path]:+def _picking_rife(root: Path, name: str = rife.MODEL) -> tuple[Path, Path]:"""(binary, its model's flownet.bin): a stand-in RIFE that runs. It hands back the first or the second of its twoimages (`-0`, `-1`) — the one its model's flownet.bin names, the other where its own FLIP is 1 — so a frame takenfor another model or binary shows in its pixels. Where a file `race` stands beside it, it first writes the other@@ -231,7 +231,7 @@ def _picking_rife(root: Path) -> tuple[Path, Path]:shutil.copyfile(args["-" + str(pick ^ FLIP)], args["-o"])"""))binary.chmod(0o700)- model = binary.parent / rife.MODEL+ model = binary.parent / namemodel.mkdir()(model / "flownet.param").write_text("synthetic")(model / "flownet.bin").write_text("0")@@ -250,7 +250,7 @@ def _dot(cx: int, colour: tuple[int, int, int]) -> Image.Image:def test_the_same_rife_makes_its_frame_again_once_a_file_it_runs_from_changed(tmp_path):"""One Rife makes and keeps a frame, then its model's bytes are written over: the next pass makes the frameagain, as this very RIFE now makes another. So for its binary written over, a file added to its model, and its- model's files under another name (the binary reads the model's version from the name). Every frame taken or made+ model's files under another path (the binary reads the model's version from its name). Every frame taken or madeis the frame the same RIFE makes with no directory, byte for byte. A RIFE whose model is gone fails as a RIFE thatfails."""binary, weights = _picking_rife(tmp_path)@@ -272,7 +272,7 @@ def test_the_same_rife_makes_its_frame_again_once_a_file_it_runs_from_changed(tmassert again(made) == (a.tobytes(), 0, 1)(weights.parent / "contextnet.bin").write_text("a file added")assert again(made) == (a.tobytes(), 0, 1)- assert again(rife.Rife(binary, shutil.copytree(weights.parent, tmp_path / "rife-v4"))) == (a.tobytes(), 0, 1)+ assert again(rife.Rife(binary, shutil.copytree(weights.parent, tmp_path / "elsewhere" / rife.MODEL))) == (a.tobytes(), 0, 1)shutil.rmtree(weights.parent)with pytest.raises(rife.RifeUnavailable, match="could not be read"):rife.Cache(tmp_path / "kept").frame(made, a, b, 0.5)@@ -302,11 +302,11 @@ def test_a_frame_made_while_its_rife_changed_is_handed_on_and_not_kept(tmp_path)@pytest.mark.skipif(sys.platform == "win32", reason="a shebang script cannot stand in for rife-ncnn-vulkan.exe")def test_a_frame_kept_under_one_augmentation_is_made_again_under_another(monkeypatch, tmp_path):- """SPRITE_GEN_RIFE_TTA is read on every call (`rife.tta()`), so one Rife makes another frame once it names another- augmentation: a frame kept by a pass without augmentation is made again by a pass with the default `-x -z`, and by- one with `-z` alone, and taken again by the next pass without. Every frame taken or made is the frame the same RIFE- makes with no directory, byte for byte."""- binary, weights = _picking_rife(tmp_path)+ """SPRITE_GEN_RIFE_TTA is read on every call (`rife.tta()`), so one Rife of rife-v4.6 makes another frame once it names+ another augmentation: a frame kept by a pass without augmentation is made again by a pass with rife-v4.6's `-x -z`,+ and by one with `-z` alone, and taken again by the next pass without. Every frame taken or made is the frame the same+ RIFE makes with no directory, byte for byte."""+ binary, weights = _picking_rife(tmp_path, "rife-v4.6")binary.write_text(binary.read_text().replace("FLIP = 0", 'FLIP = int("-x" in sys.argv)'))made = rife.Rife(binary, weights.parent)a, b = _dot(40, (255, 0, 0)), _dot(72, (0, 0, 255))@@ -321,7 +321,7 @@ def test_a_frame_kept_under_one_augmentation_is_made_again_under_another(monkeypassert again() == (a.tobytes(), 0, 1)assert again() == (a.tobytes(), 1, 0)monkeypatch.delenv("SPRITE_GEN_RIFE_TTA")- assert rife.tta() == rife.TTA == ("-x", "-z")+ assert rife.tta("rife-v4.6") == rife.MODELS["rife-v4.6"].tta == ("-x", "-z")assert again() == (b.tobytes(), 0, 1)monkeypatch.setenv("SPRITE_GEN_RIFE_TTA", "-z")assert again() == (a.tobytes(), 0, 1)diff --git a/tests/video/test_crossfade.py b/tests/video/test_crossfade.pyindex 4ada549..ce03e09 100644--- a/tests/video/test_crossfade.py+++ b/tests/video/test_crossfade.py@@ -80,7 +80,7 @@ def _made(a: Image.Image, b: Image.Image, t: float, coverage) -> Image.Image:rife._call = calltry:with tempfile.TemporaryDirectory() as td:- return rife.between(a, b, t, binary=Path("x"), model=Path("x"), tmp=Path(td))+ return rife.between(a, b, t, binary=Path("x"), model=Path("x") / "rife-v4.6", tmp=Path(td))finally:rife._call = realdiff --git a/tests/video/test_ghost_given_way.py b/tests/video/test_ghost_given_way.pyindex 50e4df6..3b380f4 100644--- a/tests/video/test_ghost_given_way.py+++ b/tests/video/test_ghost_given_way.py@@ -390,15 +390,20 @@ def test_the_applications_walk_gives_a_small_filmed_ghost_way(tmp_path):_app_ghost_given_way(report, tmp_path / "E")+# The binary's calls on the application's walk, by model (`rife.model_name()`): rife-v4.25's frame between held cells 32+# to 34 shows a neighbour's picture again, so it is refused (`held`), tried at another time and kept as filmed.+APP_RUNS = {"rife-v4.25": 10, "rife-v4.6": 8}++@pytest.mark.slow@pytest.mark.real_rife[email protected](900) # 8 calls of the binary at 280 x 221 (the held fill's frames between and the jump repair's): seconds on a GPU, minutes on a CPU's Vulkan driver[email protected](900) # 8 to 10 calls of the binary at 280 x 221 (the held fill's frames between and the jump repair's): seconds on a GPU, minutes on a CPU's Vulkan driverdef test_real_rife_the_applications_walk_gives_a_small_filmed_ghost_way(tmp_path, rife_runs):"""B1b through the real RIFE, located as `video-loop` locates it."""report = _app_cut(tmp_path, None)assert report["jump_repair"]["interpolator"]["kind"] == "rife-ncnn-vulkan"_app_ghost_given_way(report, tmp_path / "E")- assert rife_runs() == 8+ assert rife_runs() == APP_RUNS[rife.model_name()]# --- the source projection and the restoration ------------------------------------------------------diff --git a/tests/video/test_ghost_screen.py b/tests/video/test_ghost_screen.pyindex eefe728..c64a6ae 100644--- a/tests/video/test_ghost_screen.py+++ b/tests/video/test_ghost_screen.py@@ -183,9 +183,14 @@ def test_jump_repair_rejects_a_proposal_that_carries_a_ghost(monkeypatch):assert [f.tobytes() for f in out] == before+# The binary's calls of this resample, by model (`rife.model_name()`): rife-v4.25's frame made beside the filmed ghost+# carries a ghost of its own, so it is made again at other times and the nearer source frame taken.+SCREEN_CALLS = {"rife-v4.25": 28, "rife-v4.6": 20}++@pytest.mark.slow@pytest.mark.real_rife[email protected](900) # 20 calls of the binary at 128 x 192: seconds on a GPU, a minute or two on a CPU's Vulkan driver[email protected](900) # 20 to 28 calls of the binary at 128 x 192: seconds on a GPU, a minute or two on a CPU's Vulkan driverdef test_real_rife_delivers_no_cell_carrying_a_filmed_ghost():"""A filmed ghost resampled 4 to 8 through the real RIFE: before the screen the ghost itself wastaken at its own time, unmeasured, and the frames made beside it carried it, judged only beyond it."""@@ -195,4 +200,4 @@ def test_real_rife_delivers_no_cell_carrying_a_filmed_ghost():assert all(f is not frames[1] for f in out)assert max(rife.ghost(f) for f in out) <= GHOST_WARNassert [g["frame"] for g in facts["ghost_screen"]["ghosts"]] == [1]- assert interpolate.calls == 20+ assert interpolate.calls == SCREEN_CALLS[interpolate.model_name]diff --git a/tests/video/test_held_fill.py b/tests/video/test_held_fill.pyindex 4495dc1..5a31f9a 100644--- a/tests/video/test_held_fill.py+++ b/tests/video/test_held_fill.py@@ -127,6 +127,33 @@ def test_a_cut_with_no_held_cell_is_delivered_byte_for_byte_as_before(case, tmp_assert record["held_runs"] == [] and record["poses"] == cells+[email protected](os.name == "nt", reason="a shebang script cannot stand in for rife-ncnn-vulkan.exe")[email protected]("model", ["rife-v4.25", "rife-v4.6"])[email protected]("case", sorted(UNHELD))+def test_a_cut_with_no_held_cell_runs_no_rife_and_is_the_same_bytes_whichever_model(case, model, tmp_path, monkeypatch):+ """The six cuts with no held cell, with a RIFE there to be found — either model named (SPRITE_GEN_RIFE_MODEL_NAME) —+ are the bytes pinned before the fill: the binary is never run, so changing the default model changes none of+ them."""+ from sprite_gen.video import rife++ log = tmp_path / "rife" / "argv.txt"+ binary = tmp_path / "rife" / rife.BINARY+ binary.parent.mkdir()+ binary.write_text(f'#!/bin/sh\necho "$@" >> "{log}"\nexit 1\n')+ binary.chmod(0o700)+ for name in rife.MODELS:+ (binary.parent / name).mkdir()+ for f in ("flownet.param", "flownet.bin"):+ (binary.parent / name / f).write_bytes(b"x")+ monkeypatch.setenv("SPRITE_GEN_RIFE", str(binary))+ monkeypatch.setenv("SPRITE_GEN_RIFE_MODEL_NAME", model)+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL", raising=False)+ frames, kw, pinned = UNHELD[case]+ rep = _run(tmp_path, frames(), case, **kw)+ assert _pictures(Path(rep["out_dir"]), case) == pinned+ assert not log.exists()+STALLED = {5: 2, 13: 3} # the walk's frame 5 shown twice, frame 13 three timesSTALLED_OFF = { # the stalled walk cut on the engine before the fill (886936e)"strip": "32f2c1b7f4f3aedfa3eba4d49b849fd8efea9e011aaf2e035407a97ac6e9430d",diff --git a/tests/video/test_loop_overlap.py b/tests/video/test_loop_overlap.pyindex 0148d24..6799466 100644--- a/tests/video/test_loop_overlap.py+++ b/tests/video/test_loop_overlap.py@@ -466,19 +466,28 @@ def _painted(tail: float) -> Image.Image:return Image.fromarray(np.uint8(np.clip(f, 0, 1) * 255 + 0.5), "RGBA")+# The weights at which the real RIFE drags the third walker's hand apart, by model (`rife.model_name()`): rife-v4.6 at 0.5+# and 0.7; rife-v4.25 at 0.5, and at 0.7 it keeps the hand whole, its fingers their own colour.+TORN_AT = {"rife-v4.6": (0.5, 0.7), "rife-v4.25": (0.5,)}++@pytest.mark.slow@pytest.mark.real_rife@pytest.mark.timeout(900) # 102 calls of the binary at 480 x 640: over a minute on a GPU, minutes on a CPU's Vulkan driverdef test_real_rife_a_frame_made_across_a_hand_is_torn_and_refused_and_a_short_swing_is_kept():"""The third walker: between its frame with the tail swung over the hand (48 degrees) and its frame a cycle on with- the tail hanging (-8 degrees), the real RIFE drags the hand apart at weights 0.5 and 0.7, and only the passes say so —- the frame is refused as torn, and without that reading nothing refuses it (painted without a line, the outline readings- pass it, and its coverage keeps no ghost band). Swung 10 degrees, past no hand, its frame half way reads nothing."""+ the tail hanging (-8 degrees), the real RIFE drags the hand apart where the model does (TORN_AT), and only the passes+ say so — the frame is refused as torn, and without that reading nothing refuses it (painted without a line, the+ outline readings pass it, and its coverage keeps no ghost band); where it keeps the hand whole the passes read it+ under the bar. Swung 10 degrees, past no hand, its frame half way reads nothing."""interpolate = rife.Rife()early = _painted(-8)for u in (0.5, 0.7):_, said = repair.overlap_frame(interpolate.read, _painted(48), early, u, reads=True)- assert said["faults"] == ["torn"] and said["proposal"]["torn"] > TORN_WARN+ if u in TORN_AT[interpolate.model_name]:+ assert said["faults"] == ["torn"] and said["proposal"]["torn"] > TORN_WARN+ else:+ assert said["faults"] == [] and said["proposal"]["torn"] < TORN_WARNassert faults({**said["proposal"], "torn": None}) == []_, said = repair.overlap_frame(interpolate.read, _painted(2), early, 0.5, reads=True)assert said["faults"] == [] and said["proposal"]["torn"] < TORN_WARN / 2diff --git a/tests/video/test_play.py b/tests/video/test_play.pyindex bfba7bf..0c598d3 100644--- a/tests/video/test_play.py+++ b/tests/video/test_play.py@@ -15,7 +15,7 @@ import pytestfrom PIL import Image, ImageDrawfrom conftest import rife_located-from sprite_gen.video import batch, clip_prompt, effect, loop, nonloop, play+from sprite_gen.video import batch, clip_prompt, effect, loop, nonloop, play, rifefrom test_clip_prompt import PUNCH, punch_frames# state -> (preset, pinned seen from the side, cut): the engine as it was before play modes, by state name alone.@@ -258,10 +258,15 @@ def test_a_once_return_that_does_not_come_back_is_refused(tmp_path) -> None:assert json.loads((tmp_path / "out" / "punch.loop.report.json").read_text())["status"] == "failed"[email protected](900) # 36 calls of the binary at 96 x 96 (the held fill's frames between): seconds on a GPU, minutes on a CPU's Vulkan driver+# The binary's calls the held fill makes on this cut, by model (`rife.model_name()`): rife-v4.25's frame between held cells+# 31 to 33 shows a neighbour's picture again, so it is refused (`held`), tried at the group's other times and kept as filmed.+ONCE_RETURN_RUNS = {"rife-v4.25": 44, "rife-v4.6": 36}++[email protected](900) # 36 to 44 calls of the binary at 96 x 96 (the held fill's frames between): seconds on a GPU, minutes on a CPU's Vulkan driverdef test_a_once_return_cut_keeps_both_ends_and_plays_once(tmp_path, rife_runs) -> None:report = cut(tmp_path, punch_frames(tmp_path / "frames", (96, 96), count=90))- assert rife_runs() == (36 if rife_located() else 0)+ assert rife_runs() == (ONCE_RETURN_RUNS[rife.model_name()] if rife_located() else 0)meta = report["strip"]assert report["cycle"]["kind"] == "once-return" and report["cycle"]["length"] == 90assert meta["loop"] is False and meta["hold_last"] is False and meta["returns"] is Truediff --git a/tests/video/test_rife.py b/tests/video/test_rife.pyindex 8f41f22..2c90035 100644--- a/tests/video/test_rife.py+++ b/tests/video/test_rife.py@@ -36,7 +36,8 @@ def test_missing_binary_is_refused_with_the_install_line(monkeypatch, tmp_path):monkeypatch.delenv("SPRITE_GEN_RIFE", raising=False)monkeypatch.setenv("PATH", str(tmp_path))monkeypatch.setenv("SPRITE_GEN_DATA_DIR", str(tmp_path / "data"))- with pytest.raises(rife.RifeNotInstalled, match=r"run `sprite-gen rife install` \(rife-ncnn-vulkan 20221029"):+ with pytest.raises(rife.RifeNotInstalled, match=r"run `sprite-gen rife install` \(TNTwise's rife-ncnn-vulkan 20250112 with "+ r"the models rife-v4.25 and rife-v4.6"):rife.locate()@@ -65,7 +66,7 @@ def test_the_data_directory_follows_the_platform_rules(monkeypatch, tmp_path):monkeypatch.setattr(rife.sys, "platform", "linux")monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))assert rife.data_dir() == tmp_path / "xdg" / "sprite-gen"- assert rife.installed_binary().parent.name == "rife-ncnn-vulkan-20221029-ubuntu"+ assert rife.installed_binary().parent.name == "rife-ncnn-vulkan-20250112-ubuntu"monkeypatch.delenv("XDG_DATA_HOME")assert rife.data_dir() == Path.home() / ".local" / "share" / "sprite-gen"monkeypatch.setattr(rife.sys, "platform", "win32")@@ -104,21 +105,22 @@ def _recording_binary(tmp_path: Path) -> tuple[Path, Path]:def _modes_asked(monkeypatch, tmp_path: Path, named: str | None) -> tuple[list[list[str]], dict[str, str]]:- """The augmentation flags of each call one made frame sends, and the interpolator's record."""+ """The augmentation flags of each call one made frame of rife-v4.6 sends, and the interpolator's record."""if named is None:monkeypatch.delenv("SPRITE_GEN_RIFE_TTA", raising=False)else:monkeypatch.setenv("SPRITE_GEN_RIFE_TTA", named)binary, log = _recording_binary(tmp_path)- interpolate = rife.Rife(binary, tmp_path / rife.MODEL)+ interpolate = rife.Rife(binary, tmp_path / "rife-v4.6")interpolate(_disc(40), _disc(72), 0.5)calls = [line.split() for line in log.read_text().splitlines()]return [[a for a in argv if a in ("-x", "-z", "-u", "-g")] for argv in calls], interpolate.describe()-def test_every_call_asks_for_both_augmentations_and_never_the_cpu_path(monkeypatch, tmp_path):- """The colour run and the coverage run both go out with `-x -z` (docs/loop-repair.md section 1,- "Which setting"), and with no `-g`: the binary's own CPU path is wrong with this model."""+def test_every_call_of_rife_v4_6_asks_for_both_augmentations_and_never_the_cpu_path(monkeypatch, tmp_path):+ """rife-v4.6's colour run and coverage run both go out with `-x -z` (docs/loop-repair.md section 1,+ "Which setting"), and with no `-g`: the binary's own CPU path is wrong with this model. (rife-v4.25's go out with+ neither: tests/video/test_rife_models.py.)"""modes, record = _modes_asked(monkeypatch, tmp_path, None)assert modes == [["-x", "-z"], ["-x", "-z"]] and record["tta"] == "-x -z"@@ -134,7 +136,7 @@ def test_a_call_past_its_time_is_a_rife_that_failed(monkeypatch, tmp_path):binary.write_text("#!/bin/sh\nexec sleep 5\n") # exec: the stopped process is the one holding the pipesbinary.chmod(binary.stat().st_mode | stat.S_IXUSR)monkeypatch.setattr(rife, "CALL_TIMEOUT_SECONDS", 0.2)- with pytest.raises(rife.RifeUnavailable, match=r"made no frame in 0.2 s .*augmentation -x -z"):+ with pytest.raises(rife.RifeUnavailable, match=r"made no frame in 0.2 s .*augmentation none"):rife.Rife(binary, tmp_path / rife.MODEL)(_disc(40), _disc(72), 0.5)@@ -172,20 +174,22 @@ def _premultiplied(frame: Image.Image) -> np.ndarray:@pytest.mark.slow-def test_read_makes_the_frame_as_every_call_and_reads_sixteen_single_passes_turned_back(monkeypatch, tmp_path):- """`Rife.read`: the frame as `between` makes it, with the augmentation every call asks for, then the sixteen single- passes with none — the pair flipped and transposed eight ways, each from a to b at t and from b to a at 1 - t. A binary- that hands back its first frame makes every forward pass a and every backward pass b, once each pass is turned back:- the passes disagree by exactly how far a and b differ, and only where they differ."""[email protected]("model", list(rife.MODELS))+def test_read_makes_the_frame_as_every_call_and_reads_sixteen_single_passes_turned_back(monkeypatch, tmp_path, model):+ """`Rife.read`: the frame as `between` makes it, with the augmentation every call of the model asks for, then the+ sixteen single passes with none — the pair flipped and transposed eight ways, each from a to b at t and from b to a at+ 1 - t. A binary that hands back its first frame makes every forward pass a and every backward pass b, once each pass is+ turned back (and, for rife-v4.25, cut back from the padding): the passes disagree by exactly how far a and b differ,+ and only where they differ."""monkeypatch.delenv("SPRITE_GEN_RIFE_TTA", raising=False)binary, log = _recording_binary(tmp_path)- interpolate = rife.Rife(binary, tmp_path / rife.MODEL)+ interpolate = rife.Rife(binary, tmp_path / model)a, b = _marked(40), _marked(72)frame, apart = interpolate.read(a, b, 0.25)calls = [line.split() for line in log.read_text().splitlines()]assert len(calls) == 2 + rife.PASS_CALLS == interpolate.calls and interpolate.made == 1flags = [[x for x in argv if x in ("-x", "-z", "-u", "-g")] for argv in calls]- assert flags[:2] == [["-x", "-z"], ["-x", "-z"]] and all(f == [] for f in flags[2:])+ assert flags[:2] == [list(rife.MODELS[model].tta)] * 2 and all(f == [] for f in flags[2:])times = [argv[argv.index("-s") + 1] for argv in calls[2:]]assert times.count("0.2500") == times.count("0.7500") == rife.PASS_CALLS // 2assert np.array_equal(np.asarray(frame), np.asarray(a)) # the frame between, from the copying binary: a itself@@ -232,17 +236,21 @@ def test_real_rife_makes_the_frame_between_in_colour_and_alpha():@pytest.mark.slow@pytest.mark.real_rife-def test_real_rife_between_crossing_legs_adds_no_black():- """Two outlined legs walk through each other (the near one forward, the far one back): where they- cross (t=0.5) the frame between is no darker inside the body than either neighbour. 2.24- premultiplied the colour over black and left 6 % of the body dark there. Either side of the crossing- the flips of `-x` keep the near leg's outline whole over the far one, a line each neighbour draws in- another place: 1.3 % and 2.1 % of the body at t=0.25 and 0.75, the same on two GPUs — a line, not- the black fill."""- interpolate = rife.Rife()[email protected]("model", list(rife.MODELS))+def test_real_rife_between_crossing_legs_adds_no_black(model):+ """Two outlined legs walk through each other (the near one forward, the far one back): the frames between are not+ the black fill 2.24 left where they cross, premultiplying the colour over black — 6 % of the body dark at t=0.5 —+ only a line each neighbour draws in another place, under 3 % of the body at t=0.25, 0.5 and 0.75. rife-v4.6's flips+ of `-x` keep the near leg's outline whole over the far one: 1.3 % and 2.1 % either side of the crossing, the same on+ two GPUs, and at the crossing no darker inside the body than either neighbour. rife-v4.25, with no augmentation,+ leaves 0.4 %, 0.4 % and 1.8 % (an Apple GPU)."""+ root = rife.locate()[0].parent+ interpolate = rife.Rife(rife.locate()[0], root / model)a, b = _legs(36, 70), _legs(60, 46)dark = [rife.smear(interpolate(a, b, t), a, b)["dark_excess"] for t in (0.25, 0.5, 0.75)]- assert dark[1] <= 0 and max(dark) < 0.03+ assert max(dark) < 0.03, dark+ if model == "rife-v4.6":+ assert dark[1] <= 0, darkdef _legs(x_near: int, x_far: int) -> Image.Image:@@ -269,7 +277,7 @@ def test_where_the_colour_and_coverage_runs_disagree_the_body_shows_not_black(moreturn x if len(calls) % 2 else ymonkeypatch.setattr(rife, "_call", stand_in)- made = rife.between(a, b, 0.5, binary=tmp_path, model=tmp_path, tmp=tmp_path)+ made = rife.between(a, b, 0.5, binary=tmp_path, model=tmp_path / rife.MODEL, tmp=tmp_path)m = np.asarray(made).astype(int)bare_in_a = np.asarray(a)[..., 3] == 0covered = (m[..., 3] >= 128) & bare_in_adiff --git a/tests/video/test_rife_executor.py b/tests/video/test_rife_executor.pyindex 4eb1b34..0fb46cb 100644--- a/tests/video/test_rife_executor.py+++ b/tests/video/test_rife_executor.py@@ -11,8 +11,10 @@ answer from another is not handed on. So a frame kept is the RIFE's own, taken oexecutor changed keys its frames anew.The executor here is stood in: a pool of devices behind the send, each answering as the executor does (`rife.answer`)-from a device whose runs follow from the images and from what it is, so another device makes other bytes. One test,-marked `torch_rife`, serves the torch backend itself (`rife_torch.serve`) and finds the frames this process makes."""+from a device whose runs follow from the images and from what it is, so another device makes other bytes. It runs+rife-v4.6, named on this host too (SPRITE_GEN_RIFE_MODEL_NAME), so the augmentation each request names is the host's+`-x -z` or another; an executor of another model than the host's is refused as the RIFE is made. One test, marked+`torch_rife`, serves the torch backend itself (`rife_torch.serve`) and finds the frames this process makes."""from __future__ import annotations@@ -35,7 +37,8 @@ from tests.video.test_rife_torch import _binary_beside_a_model, _no_torchNAME = f"{__name__}:send"DETERMINISM = {"cudnn_deterministic": True, "cudnn_benchmark": False, "cudnn_conv_fp32_precision": "ieee"}# What a device of the executor is, as the torch backend names it on CUDA: no CPU, no host name.-T4 = {"backend": "torch", "device": "cuda", "weights": dict(rife.MODEL_SHA256), "net": "n" * 64, "torch": "2.13.0+cu130",+T4 = {"backend": "torch", "device": "cuda", "model": "rife-v4.6", "net": "n" * 64, "torch": "2.13.0+cu130",+ "weights": {name: pins["ubuntu"] for name, pins in rife.MODEL_SHA256["rife-v4.6"].items()},"cuda": "13.0", "cudnn": 92000, "gpu": "Tesla T4", "capability": [7, 5], "driver": "610.57.04","determinism": DETERMINISM}L4 = {**T4, "gpu": "NVIDIA L4", "capability": [8, 9]}@@ -58,7 +61,7 @@ class Device:if self.fails is not None:raise self.failsself.runs += 1- modes = rife.tta() if modes is None else modes+ modes = rife.tta(self.ident["model"]) if modes is None else modesout = np.rint(x.astype(np.float64) * (1 - t) + y.astype(np.float64) * t).astype(np.uint8)out[0, 0] = list(hashlib.sha256(json.dumps([self.ident, list(modes)], sort_keys=True).encode()).digest()[:3])return out@@ -71,7 +74,7 @@ class Device:return (*rife.frame_runs(self.run, colour, cover, t), rife.pass_runs(self.run, colour, cover, t))def describe(self) -> dict:- return {"kind": "rife-torch", "device": self.ident["device"], "model": rife.MODEL}+ return {"kind": "rife-torch", "device": self.ident["device"], "model": self.ident["model"]}class Executor:@@ -118,9 +121,16 @@ def send(request: bytes) -> bytes:return reached(request)[email protected](autouse=True)+def _host_model(monkeypatch) -> None:+ """This host runs rife-v4.6, the model of the devices stood in (T4)."""+ monkeypatch.setenv("SPRITE_GEN_RIFE_MODEL_NAME", "rife-v4.6")++@pytest.fixturedef executor(monkeypatch) -> Executor:- """The torch backend chosen and its frames sent (NAME) to an executor of one T4; no device named on this host."""+ """The torch backend chosen and its frames sent (NAME) to an executor of one T4 running rife-v4.6, the model this host+ names; no device named on this host."""stood = Executor(Device())monkeypatch.setattr(sys.modules[__name__], "reached", stood)monkeypatch.setenv("SPRITE_GEN_RIFE_BACKEND", "torch")@@ -153,7 +163,8 @@ def test_a_frame_is_one_call_a_read_one_call_and_the_rife_asks_the_executor_onceassert frame.tobytes() == there.tobytes() and apart.dtype == np.float32 and np.array_equal(apart, apart_here)assert executor.kinds() == ["probe", "frame", "read"] and device.runs == 2 + 2 + rife.PASS_CALLSassert made.counts() == {"runs": 2 + 2 + rife.PASS_CALLS, "executor_calls": 3}- assert made.describe() == {"kind": "rife-torch", "executor": NAME, "device": "cuda", "gpu": "Tesla T4", "tta": "-x -z"}+ assert made.describe() == {"kind": "rife-torch", "executor": NAME, "device": "cuda", "gpu": "Tesla T4",+ "model": "rife-v4.6", "tta": "-x -z"}monkeypatch.setenv("SPRITE_GEN_RIFE_TTA", "-z") # the host's augmentation, read as each frame is asked forother = made(a, b, 0.25)assert other.tobytes() == here(a, b, 0.25).tobytes() and executor.headers[-1]["modes"] == ["-z"]@@ -183,6 +194,28 @@ def test_each_request_carries_the_engine_code_and_the_identity_the_rife_holds(exassert captured[name].dtype == np.uint8 and np.array_equal(captured[name], want)[email protected]("host, held", [(None, "rife-v4.6"), ("rife-v4.6", "rife-v4.25"), ("rife-v4.6", None)])+def test_an_executor_of_another_model_than_this_host_runs_is_refused_as_the_rife_is_made(executor, monkeypatch, host, held):+ """The model is the executor's, named in its identity, and this host runs one (SPRITE_GEN_RIFE_MODEL_NAME, else+ rife-v4.25): an executor running another — or naming none, an older sprite-gen — is refused by the probe, both named,+ before a frame is asked for; one running the host's model makes its frames with the host's augmentation for it."""+ if host is None:+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL_NAME", raising=False)+ else:+ monkeypatch.setenv("SPRITE_GEN_RIFE_MODEL_NAME", host)+ executor.devices[0].ident = {k: v for k, v in {**T4, "model": held}.items() if v is not None}+ with pytest.raises(rife.RifeUnavailable, match=rf"the executor runs the model {held!r}, and this host runs "+ rf"{host or rife.MODEL} .*run one model on both sides") as refused:+ rife.Rife()+ assert not isinstance(refused.value, rife.RifeNotInstalled)+ assert executor.kinds() == ["probe"] and executor.devices[0].runs == 0+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL_NAME", raising=False)+ executor.devices[0].ident = {**T4, "model": rife.MODEL}+ made = rife.Rife()+ made(_disc(40), _disc(72), 0.5)+ assert made.describe()["model"] == rife.MODEL and executor.headers[-1]["modes"] == []++def test_the_host_runs_with_no_pytorch_installed(executor, monkeypatch):"""The host that sends its frames needs no PyTorch: with PyTorch not importable a RIFE is made, makes its frame throughthe executor, and the torch backend's module is never imported here."""@@ -639,7 +672,7 @@ def test_a_loop_names_the_executor_that_made_its_frames(executor, tmp_path):filmed, _ = _loop({10: 12})rep = _run(tmp_path, _keyed(tmp_path, filmed))assert rep["jump_repair"]["interpolator"] == {"kind": "rife-torch", "executor": NAME, "device": "cuda",- "gpu": "Tesla T4", "tta": "-x -z"}+ "gpu": "Tesla T4", "model": "rife-v4.6", "tta": "-x -z"}assert executor.kinds()[0] == "probe" and executor.kinds().count("probe") == 1diff --git a/tests/video/test_rife_install.py b/tests/video/test_rife_install.pyindex d269e9d..cebe3be 100644--- a/tests/video/test_rife_install.py+++ b/tests/video/test_rife_install.py@@ -1,7 +1,8 @@# SPDX-License-Identifier: Apache-2.0"""`sprite-gen rife install` without a network: a release-shaped zip built here, its SHA-256 putin place of the pinned one. The zip is checked before anything is unpacked, only what the engine-runs is kept, the install lands where `rife.locate()` looks last, and a second run does nothing."""+runs is kept — the binary and both models, rife-v4.25 and rife-v4.6 — the install lands where+`rife.locate()` looks last, and a second run does nothing."""from __future__ import annotations@@ -20,40 +21,53 @@ from sprite_gen import clifrom sprite_gen.video import rife, rife_installPLATFORM = rife.platform_release() or "ubuntu"-TOP = f"rife-ncnn-vulkan-{rife.RELEASE}-{PLATFORM}"+TOP = f"rife-ncnn-vulkan-{rife.RELEASE}-{PLATFORM}" # where the install puts it, whatever the zip's folder is namedBINARY = rife.installed_binary(Path("."), PLATFORM).name-# 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"}+# The fixture zip's model files, which its pins name in place of the models' (`rife.MODEL_SHA256`).+MODEL_FILES = {model: {"flownet.param": f"{model} param\n".encode(), "flownet.bin": f"{model} bin\n".encode()}+ for model in rife.MODELS}+MODEL_PINS = {model: {name: {p: hashlib.sha256(data).hexdigest() for p in rife.PLATFORMS} for name, data in files.items()}+ for model, files in MODEL_FILES.items()}-def _release_zip(tmp_path: Path, *, model: bool = True, platform: str = PLATFORM) -> Path:+def _release_zip(tmp_path: Path, *, models=tuple(rife.MODELS), platform: str = PLATFORM) -> Path:+ """A zip shaped as the release's for `platform`: its folder named as the release names it (`rife_install.ZIP_TOP`)."""path = tmp_path / rife_install.zip_name(platform)- top, binary = f"rife-ncnn-vulkan-{rife.RELEASE}-{platform}", rife.installed_binary(Path("."), platform).name+ top, binary = rife_install.ZIP_TOP[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")- if model:- for name, data in MODEL_FILES.items():- zf.writestr(f"{top}/{rife.MODEL}/{name}", data)+ for model in models:+ for name, data in MODEL_FILES[model].items():+ zf.writestr(f"{top}/{model}/{name}", data)zf.writestr(f"{top}/rife-v4/flownet.bin", "another model\n") # not what the engine runszf.writestr(f"{top}/{rife.MODEL}/../../escape.txt", "outside\n")zf.writestr("elsewhere/rife-ncnn-vulkan", "not in the release folder\n")return path+def test_each_platform_s_zip_is_named_and_unpacked_as_the_release_ships_it():+ """TNTwise's 20250112 release: `<platform>.zip` from its GitHub release, the Windows zip's folder named after the branch+ it was built from — pinned by sha256, each of the three."""+ assert rife.RELEASE == "20250112" and rife_install.URL.startswith("https://github.com/TNTwise/rife-ncnn-vulkan/")+ assert [rife_install.zip_name(p) for p in rife.PLATFORMS] == ["macos.zip", "ubuntu.zip", "windows.zip"]+ assert rife_install.ZIP_TOP == {"macos": "macos", "ubuntu": "ubuntu", "windows": "rife-ncnn-vulkan-refs/heads/master-windows"}+ assert set(rife_install.ZIP_SHA256) == set(rife.PLATFORMS) and all(len(v) == 64 for v in rife_install.ZIP_SHA256.values())++@pytest.fixturedef pinned(monkeypatch, 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."""+ """The fixture zip, with its SHA-256 and its models' 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.setattr(rife, "MODEL_SHA256", MODEL_PINS)monkeypatch.delenv("SPRITE_GEN_RIFE_BACKEND", raising=False)+ monkeypatch.delenv("SPRITE_GEN_RIFE_MODEL_NAME", 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)@@ -67,7 +81,8 @@ def test_install_keeps_what_the_engine_runs_where_locate_finds_it(pinned, tmp_pareport = rife_install.install(zip_path=pinned, platform=PLATFORM, run_check=False)target = tmp_path / "data" / "rife" / TOPassert report["installed"] == "now" and report["dir"] == str(target.resolve())- assert sorted(report["files"]) == sorted([BINARY, "LICENSE", "README.md", f"{rife.MODEL}/flownet.bin", f"{rife.MODEL}/flownet.param"])+ assert sorted(report["files"]) == sorted([BINARY, "LICENSE", "README.md",+ *(f"{m}/{f}" for m in rife.MODELS for f in ("flownet.bin", "flownet.param"))])assert not (target / "rife-v4").exists() and not (tmp_path / "data" / "escape.txt").exists()assert os.access(target / BINARY, os.X_OK) and (target / BINARY).stat().st_mode & stat.S_IXUSRassert json.loads((target / rife_install.MARKER).read_text())["sha256"] == rife_install.ZIP_SHA256[PLATFORM]@@ -83,9 +98,10 @@ def test_a_zip_whose_hash_differs_installs_nothing(pinned, tmp_path, monkeypatchassert not (tmp_path / "data" / "rife" / TOP).exists()-def test_a_zip_without_the_model_is_refused(pinned, tmp_path, monkeypatch):[email protected]("missing", list(rife.MODELS))+def test_a_zip_without_either_model_is_refused(pinned, tmp_path, monkeypatch, missing):(tmp_path / "bare").mkdir()- bare = _release_zip(tmp_path / "bare", model=False)+ bare = _release_zip(tmp_path / "bare", models=[m for m in rife.MODELS if m != missing])monkeypatch.setitem(rife_install.ZIP_SHA256, PLATFORM, hashlib.sha256(bare.read_bytes()).hexdigest())with pytest.raises(SystemExit, match="flownet.param"):rife_install.install(zip_path=bare, platform=PLATFORM, run_check=False)@@ -144,12 +160,14 @@ def test_a_platform_without_a_release_build_is_refused(monkeypatch):rife_install.install(run_check=False)[email protected]("model", list(rife.MODELS))@pytest.mark.parametrize("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:+def test_a_zip_whose_model_is_not_the_pinned_one_installs_nothing(pinned, tmp_path, monkeypatch, backend, model):+ """Its hash checked, the zip unpacked, each 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"):+ pins = {**MODEL_PINS, model: {**MODEL_PINS[model], "flownet.bin": {p: "0" * 64 for p in rife.PLATFORMS}}}+ monkeypatch.setattr(rife, "MODEL_SHA256", pins)+ with pytest.raises(SystemExit, match=rf"{model}: flownet.bin has sha256 [0-9a-f]{{64}}, expected one of 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()@@ -178,13 +196,12 @@ def test_the_torch_backend_installs_where_the_binary_does_not_run_and_checks_itsmonkeypatch.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"):+ for name in ("SPRITE_GEN_RIFE", "SPRITE_GEN_RIFE_MODEL", "SPRITE_GEN_RIFE_BACKEND", "SPRITE_GEN_RIFE_MODEL_NAME"):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)+ monkeypatch.setattr(rife, "MODEL_SHA256", MODEL_PINS)with pytest.raises(SystemExit, match="x86-64 only and this machine is aarch64"):rife_install.install(zip_path=zipped, run_check=False)asked = []diff --git a/tests/video/test_rife_models.py b/tests/video/test_rife_models.pynew file mode 100644index 0000000..038b0e3--- /dev/null+++ b/tests/video/test_rife_models.py@@ -0,0 +1,194 @@+# SPDX-License-Identifier: Apache-2.0+"""The two models RIFE runs (docs/loop-repair.md section 1): `rife-v4.25`, the default, with no augmentation, each image+handed to the binary padded with zeros to a multiple of 128 (`rife.Model.pad`); and `rife-v4.6`, chosen by name+(SPRITE_GEN_RIFE_MODEL_NAME), with `-x -z` and each image handed as it is — what 3.14.0 handed the binary, so its frames+are the old ones. A model named wrong, or a model directory named as another, is refused before anything runs.++A stand-in binary keeps each image it is handed and returns its first, so the tests need no RIFE and see what the binary+saw."""++from __future__ import annotations++import hashlib+import stat+from pathlib import Path++import numpy as np+import pytest+from PIL import Image++from sprite_gen.video import rife+from tests.video.test_rife import _disc, _marked+++def _keeping_binary(tmp_path: Path) -> tuple[Path, Path]:+ """A stand-in binary that keeps every pair it is handed (`in-<n>-0.png`, `in-<n>-1.png`, its arguments in `argv.txt`)+ and returns its first image: (binary, the directory it keeps them in)."""+ kept = tmp_path / "kept"+ kept.mkdir(parents=True)+ binary = tmp_path / rife.BINARY+ binary.write_text(f'#!/bin/sh\nk="{kept}"\necho "$@" >> "$k/argv.txt"\nn=$(wc -l < "$k/argv.txt" | tr -d " ")\n'+ 'while [ $# -gt 0 ]; do case "$1" in -0) a="$2"; shift;; -1) b="$2"; shift;; -o) o="$2"; shift;; esac; shift; done\n'+ 'cp "$a" "$k/in-$n-0.png"\ncp "$b" "$k/in-$n-1.png"\ncp "$a" "$o"\n')+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)+ return binary, kept+++def _handed(kept: Path) -> list[tuple[np.ndarray, np.ndarray, list[str]]]:+ """Each call's two images as the binary was handed them, and its arguments."""+ calls = [line.split() for line in (kept / "argv.txt").read_text().splitlines()]+ return [(np.asarray(Image.open(kept / f"in-{n}-0.png").convert("RGB")), np.asarray(Image.open(kept / f"in-{n}-1.png").convert("RGB")),+ argv) for n, argv in enumerate(calls, 1)]+++def _model_dir(tmp_path: Path, name: str) -> Path:+ model = tmp_path / name+ model.mkdir(parents=True)+ for f in ("flownet.param", "flownet.bin"):+ (model / f).write_bytes(b"x")+ return model+++def unnamed(monkeypatch):+ for name in ("SPRITE_GEN_RIFE_MODEL_NAME", "SPRITE_GEN_RIFE_MODEL", "SPRITE_GEN_RIFE_TTA"):+ monkeypatch.delenv(name, raising=False)+++def test_the_default_model_is_rife_v4_25_with_no_augmentation_and_rife_v4_6_keeps_both(unnamed, monkeypatch, tmp_path):+ """Nothing named, the model is rife-v4.25 and every call asks for no augmentation (TNTwise's README marks -x and -z+ deprecated with it); rife-v4.6 named, every call asks for -x -z as before. Each is found beside the binary."""+ assert rife.MODEL == rife.model_name() == "rife-v4.25" and set(rife.MODELS) == {"rife-v4.25", "rife-v4.6"}+ binary, kept = _keeping_binary(tmp_path)+ monkeypatch.setenv("SPRITE_GEN_RIFE", str(binary))+ for name in rife.MODELS:+ _model_dir(binary.parent, name)+ assert rife.locate() == (binary.resolve(), binary.resolve().parent / "rife-v4.25")+ made = rife.Rife()+ made(_disc(40), _disc(72), 0.5)+ assert [[a for a in argv if a in ("-x", "-z")] for _, _, argv in _handed(kept)] == [[], []]+ assert made.describe()["tta"] == "" and made.describe()["model"] == "rife-v4.25"+ monkeypatch.setenv("SPRITE_GEN_RIFE_MODEL_NAME", "rife-v4.6")+ assert rife.locate() == (binary.resolve(), binary.resolve().parent / "rife-v4.6")+ old = rife.Rife()+ old(_disc(40), _disc(72), 0.5)+ assert [[a for a in argv if a in ("-x", "-z")] for _, _, argv in _handed(kept)][2:] == [["-x", "-z"], ["-x", "-z"]]+ assert old.describe()["tta"] == "-x -z" and old.describe()["model"] == "rife-v4.6"+++def test_a_model_directory_names_the_model_it_holds(unnamed, monkeypatch, tmp_path):+ """SPRITE_GEN_RIFE_MODEL names a directory, and its name is the model run (the binary reads the model's version from+ it): a rife-v4.6 directory runs rife-v4.6 with -x -z, as it did before rife-v4.25 was the default."""+ binary, kept = _keeping_binary(tmp_path)+ monkeypatch.setenv("SPRITE_GEN_RIFE", str(binary))+ old = _model_dir(tmp_path / "models", "rife-v4.6")+ monkeypatch.setenv("SPRITE_GEN_RIFE_MODEL", str(old))+ assert rife.model_name() == "rife-v4.6" and rife.locate()[1] == old+ assert rife.Rife().describe()["tta"] == "-x -z"++[email protected]("names, refused", [+ ({"SPRITE_GEN_RIFE_MODEL_NAME": "rife-v4.26"}, r"SPRITE_GEN_RIFE_MODEL_NAME='rife-v4.26': name rife-v4.25 or rife-v4.6"),+ ({"SPRITE_GEN_RIFE_MODEL": "{tmp}/models/rife-v4.6-copy"}, r"its directory is named 'rife-v4.6-copy', not as the model it holds"),+ ({"SPRITE_GEN_RIFE_MODEL": "{tmp}/models/rife-v4.6", "SPRITE_GEN_RIFE_MODEL_NAME": "rife-v4.25"},+ r"SPRITE_GEN_RIFE_MODEL=.*rife-v4.6' holds rife-v4.6, and SPRITE_GEN_RIFE_MODEL_NAME='rife-v4.25'"),+ ({"SPRITE_GEN_RIFE_TTA": "-x"}, r"SPRITE_GEN_RIFE_TTA='-x': rife-v4.25 runs with no augmentation"),+ ({"SPRITE_GEN_RIFE_TTA": "-x -z"}, r"SPRITE_GEN_RIFE_TTA='-x -z': rife-v4.25 runs with no augmentation"),+])+def test_a_model_named_wrong_or_an_augmentation_it_has_not_is_refused_before_anything_runs(unnamed, monkeypatch, tmp_path,+ names, refused):+ """A model the engine does not run, a model directory not named as one, a directory and a name that disagree, and+ rife-v4.25 asked for an augmentation: refused by name (`RifeUnavailable`, not RIFE not installed, which a loop would+ cut around), and the binary never runs."""+ binary, kept = _keeping_binary(tmp_path)+ monkeypatch.setenv("SPRITE_GEN_RIFE", str(binary))+ for name in rife.MODELS:+ _model_dir(binary.parent, name)+ for name in ("rife-v4.6", "rife-v4.6-copy"):+ _model_dir(tmp_path / "models", name)+ for name, value in names.items():+ monkeypatch.setenv(name, value.format(tmp=tmp_path))+ with pytest.raises(rife.RifeUnavailable, match=refused) as refusal:+ rife.Rife()+ assert not isinstance(refusal.value, rife.RifeNotInstalled) and not (kept / "argv.txt").exists()+++def _padded(n: int, multiple: int) -> int:+ return -(-n // multiple) * multiple++[email protected]("size", [(128, 96), (130, 97), (400, 771)])+def test_rife_v4_25_is_handed_each_image_padded_with_zeros_to_128_and_the_frame_cut_back(tmp_path, size):+ """rife-v4.25: each image the binary is handed — the colour and the coverage of a frame, and each of a read's sixteen+ passes, turned or not — is the image RIFE is given (`rife.inputs`) at the top left of a canvas a multiple of 128 each+ way, zeros round it (`rife.Model.pad`: Practical-RIFE pads by 128 at scale 1, the binary by 64 for this model; the+ binary's own padding then adds nothing). The frame that comes back is cut back to the frame's size: from a binary that+ returns its first image, `a` itself."""+ w, h = size+ a, b = (_marked(40).resize(size, Image.NEAREST), _marked(72).resize(size, Image.NEAREST))+ binary, kept = _keeping_binary(tmp_path)+ made = rife.Rife(binary, _model_dir(tmp_path, "rife-v4.25"))+ frame, _ = made.read(a, b, 0.25)+ assert frame.size == size and np.array_equal(np.asarray(frame), np.asarray(a))+ colour, cover = rife.inputs(a, b)+ handed = _handed(kept)+ assert len(handed) == 2 + rife.PASS_CALLS+ for k, (x, y, argv) in enumerate(handed):+ for img in (x, y):+ ih, iw = img.shape[:2]+ assert ih % 128 == 0 and iw % 128 == 0, (k, img.shape)+ inner = (h, w) if k < 2 or not rife.PASS_GEOMETRIES[(k - 2) // 4][0] else (w, h) # a transposed pass is w x h+ assert (ih, iw) == (_padded(inner[0], 128), _padded(inner[1], 128))+ assert not img[inner[0]:].any() and not img[:, inner[1]:].any(), "outside the image is not zero"+ assert np.array_equal(handed[0][0][:h, :w], colour[0]) and np.array_equal(handed[0][1][:h, :w], colour[1])+ assert np.array_equal(handed[1][0][:h, :w], rife._grey(cover[0])) and np.array_equal(handed[1][1][:h, :w], rife._grey(cover[1]))+++def test_rife_v4_6_is_handed_each_image_as_it_is_as_before(tmp_path):+ """rife-v4.6: each image goes to the binary at the frame's own size, exactly what RIFE is given (`rife.inputs`), with+ -x -z — what 3.14.0 handed it, so the frames are the old ones (the binary pads by 32 itself)."""+ a, b = _marked(40).resize((130, 97), Image.NEAREST), _marked(72).resize((130, 97), Image.NEAREST)+ binary, kept = _keeping_binary(tmp_path)+ made = rife.Rife(binary, _model_dir(tmp_path, "rife-v4.6"))+ frame = made(a, b, 0.5)+ colour, cover = rife.inputs(a, b)+ (x0, y0, argv0), (x1, y1, argv1) = _handed(kept)+ assert np.array_equal(x0, colour[0]) and np.array_equal(y0, colour[1])+ assert np.array_equal(x1, rife._grey(cover[0])) and np.array_equal(y1, rife._grey(cover[1]))+ assert "-x" in argv0 and "-z" in argv0 and "-x" in argv1 and "-z" in argv1+ assert np.array_equal(np.asarray(frame), np.asarray(a))+++def test_each_model_is_pinned_on_every_platform_and_another_is_refused(tmp_path):+ """Each model's two files are pinned by sha256 as each release zip ships them (`rife.MODEL_SHA256`: the Windows zip's+ flownet.param has CRLF line ends, the others LF); the model read is checked against its own model's pins, any platform's,+ and another model's bytes are refused by name."""+ assert set(rife.MODEL_SHA256) == set(rife.MODELS)+ for name, files in rife.MODEL_SHA256.items():+ assert set(files) == {"flownet.param", "flownet.bin"}+ for pins in files.values():+ assert set(pins) == {"macos", "ubuntu", "windows"} and all(len(v) == 64 for v in pins.values())+ model = tmp_path / "rife-v4.25"+ model.mkdir()+ (model / "flownet.param").write_bytes(b"one")+ (model / "flownet.bin").write_bytes(b"two")+ with pytest.raises(rife.RifeUnavailable, match=r"flownet.param has sha256 [0-9a-f]{64}, expected one of"):+ rife.model_bytes(model)+++def test_a_frame_kept_for_one_model_is_not_taken_for_the_other(unnamed, tmp_path):+ """`Cache` keys a frame on its RIFE's identity, which names the model directory and each of its files by sha256: the+ same binary running rife-v4.6 and rife-v4.25 makes two keys, and a frame kept for one is made again for the other."""+ binary, _ = _keeping_binary(tmp_path)+ models = {}+ for name in rife.MODELS:+ models[name] = _model_dir(tmp_path / "beside", name)+ (models[name] / "flownet.bin").write_bytes(hashlib.sha256(name.encode()).digest())+ a, b = _disc(40), _disc(72)+ cache = rife.Cache(tmp_path / "kept")+ new, old = (rife.Rife(binary, models[n]) for n in ("rife-v4.25", "rife-v4.6"))+ assert cache.key(new, a, b, 0.5) != cache.key(old, a, b, 0.5)+ cache.frame(old, a, b, 0.5)+ cache.frame(new, a, b, 0.5)+ cache.frame(old, a, b, 0.5)+ assert (cache.hits, cache.misses) == (1, 2)diff --git a/tests/video/test_rife_torch.py b/tests/video/test_rife_torch.pyindex ab9c866..298ee3e 100644--- a/tests/video/test_rife_torch.py+++ b/tests/video/test_rife_torch.py@@ -1,12 +1,14 @@# 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.+"""RIFE's torch backend (docs/loop-repair.md section 1): the binary's model in PyTorch, from the binary's own files, run+as one call of the binary runs it — rife-v4.25, the default, padded to 128 with no augmentation+(tests/video/test_rife_torch_v425.py), and rife-v4.6, 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 chosenthe binary is never run, a device that cannot be had is not traded for another, and PyTorch missing is RIFE notinstalled, its reason named.-The tests marked `torch_rife` run the network: they need PyTorch and the rife-v4.6 model (`rife.locate_model()`), are+The tests marked `torch_rife` run the network: they need PyTorch and the models (`rife.locate_model()`, rife-v4.6 beside it), areskipped 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.@@ -34,12 +36,21 @@ WALKERS = Path(__file__).resolve().parents[1] / "fixtures" / "rife-walkers"@pytest.fixture(scope="module")def runner():- """The torch backend on SPRITE_GEN_RIFE_DEVICE, from the installed model."""+ """The torch backend on SPRITE_GEN_RIFE_DEVICE, from the installed model the engine runs (rife-v4.25 by default)."""from sprite_gen.video import rife_torchreturn rife_torch.TorchRunner(rife.locate_model(), rife.device())[email protected](scope="module")+def runner46():+ """The torch backend on SPRITE_GEN_RIFE_DEVICE, from the installed rife-v4.6, which `sprite-gen rife install` puts beside+ rife-v4.25: the model whose augmentation the binary runs inside one call, and the one the walker fixtures recorded."""+ from sprite_gen.video import rife_torch++ return rife_torch.TorchRunner(rife.locate_model().parent / "rife-v4.6", rife.device())++def _key(x: np.ndarray) -> tuple[tuple[int, ...], bytes]:return x.shape, np.ascontiguousarray(x).tobytes()@@ -72,7 +83,7 @@ def _patch(cx: int) -> Image.Image:@pytest.mark.torch_rife-def test_flows_turned_back_from_every_way_point_alike(runner):+def test_flows_turned_back_from_every_way_point_alike(runner46):"""Five fields of different values turned to each of the sixteen ways (eight turns, each both ways in time, the backwardswapped) and turned back are themselves. And a patch moving right, run alone each of the sixteen ways with its flowsturned 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@@ -89,9 +100,9 @@ def test_flows_turned_back_from_every_way_point_alike(runner):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]+ pads = [runner46._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)]+ flows = [runner46._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 tx0, y0, x1, y1, mask = np.array([[f[c][on].mean() for c in range(5)] for f in flows]).T@@ -101,23 +112,26 @@ def test_flows_turned_back_from_every_way_point_alike(runner):@pytest.mark.torch_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)."""+def test_a_frame_is_the_same_made_the_other_way_in_time_or_turned(runner46):+ """rife-v4.6's `-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",))+ there, back = runner46.run(colour[0], colour[1], 0.25, ("-z",)), runner46.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+ flipped = runner46.run(colour[0][:, ::-1].copy(), colour[1][:, ::-1].copy(), 0.25, ("-x",))+ assert np.abs(flipped[:, ::-1].astype(int) - runner46.run(colour[0], colour[1], 0.25, ("-x",)).astype(int)).max() <= 1@pytest.mark.torch_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."""[email protected]("model, named", [("rife-v4.25", None), ("rife-v4.6", None), ("rife-v4.6", "")])+def test_the_frame_between_two_discs_lands_half_way(request, monkeypatch, model, named):+ """`sprite-gen rife install`'s check frame through the torch backend, each model with the augmentation every call asks+ for (rife-v4.25 none, rife-v4.6 -x -z) and rife-v4.6 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)+ runner = request.getfixturevalue("runner46" if model == "rife-v4.6" else "runner")+ assert runner.model_name == modelmid = 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@@ -131,15 +145,18 @@ def test_the_model_loads_whole_and_any_other_bytes_are_refused_by_sha256(tmp_patfrom 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")+ for held in rife.MODELS:+ model = rife.locate_model().parent / held+ state = rife_torch.state_from_ncnn(rife.model_bytes(model), held)+ assert set(state) == set(rife_torch.IFNet(held).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 / held / str(k) / held)+ (copy / name).write_bytes(change((copy / name).read_bytes()))+ pins = " or ".join(sorted(set(rife.MODEL_SHA256[held][name].values())))+ with pytest.raises(rife.RifeUnavailable, match=rf"{name} has sha256 [0-9a-f]{{64}}, expected one of {pins}"):+ rife_torch.TorchRunner(copy, "cpu")@pytest.mark.torch_rife@@ -156,7 +173,8 @@ def test_the_same_frame_twice_is_the_same_bytes_and_the_identity_names_what_makea, 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["backend"], ident["device"], ident["model"]) == ("torch", rife.device(), rife.MODEL)+ assert all(ident["weights"][name] in pins.values() for name, pins in rife.MODEL_SHA256[rife.MODEL].items())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"}@@ -195,15 +213,16 @@ def _apart(m: Image.Image, n: Image.Image) -> tuple[float, float]:@pytest.mark.torch_rife@pytest.mark.timeout(900) # a frame and its sixteen passes, seven pairs: seconds on a GPU, a minute or two on two CPU cores@pytest.mark.parametrize("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,+def test_walkers_are_judged_as_the_binary_judged_them(runner46, key):+ """Each recorded walker pair, its rife-v4.6 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 werepicked where the binary on an Apple GPU, the binary on Mesa llvmpipe and the torch backend on a CPU all gave thatverdict, every reading at least a tenth of its bound away from it. The frame lies from the binary's no further thantwice 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"])+ made, apart = rife.Rife(runner=runner46).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"])@@ -214,8 +233,8 @@ def test_walkers_are_judged_as_the_binary_judged_them(runner, key):@pytest.mark.timeout(1800) # the binary on a CPU's Vulkan driver: a minute or more a pair@pytest.mark.parametrize("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."""+ """The recorded walker pairs through this machine's binary (llvmpipe on the Linux lane) and the torch backend, each+ running the model the engine runs: the same verdict for each."""t = _walkers()[key]["t"]a, b = _walker(key, "a"), _walker(key, "b")verdicts = []@@ -440,7 +459,8 @@ def test_a_model_other_than_the_pinned_one_is_refused_and_one_not_there_is_not_i(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']}"):+ pins = " or ".join(sorted(set(rife.MODEL_SHA256[rife.MODEL]["flownet.param"].values())))+ with pytest.raises(rife.RifeUnavailable, match=rf"flownet.param has sha256 [0-9a-f]{{64}}, expected one of {pins}"):rife.model_bytes(model)@@ -450,7 +470,8 @@ 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,+ self.ident = {"backend": "torch", "device": "cpu", "model": rife.MODEL, "net": "n" * 64,+ "weights": {name: pins["ubuntu"] for name, pins in rife.MODEL_SHA256[rife.MODEL].items()},"torch": "2.13.0", "cpu": "AVX2", "arch": "x86_64", **identity}self.model = Path("/models") / rife.MODELself.frames = self.reads = 0@@ -476,14 +497,14 @@ def test_a_report_names_the_torch_backend_and_counts_its_runs(monkeypatch, tmp_ptorch 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"}+ assert ncnn.describe() == {"kind": "rife-ncnn-vulkan", "binary": str(binary), "model": rife.MODEL, "tta": ""}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.describe() == {"kind": "rife-torch", "device": "cpu", "model": rife.MODEL, "tta": ""}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)@@ -502,11 +523,11 @@ def test_the_loop_and_the_alignment_name_the_torch_backend_that_made_their_framefilmed, _ = _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"}+ assert rep["jump_repair"]["interpolator"] == {"kind": "rife-torch", "device": "cpu", "model": rife.MODEL, "tta": ""}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"}+ assert report["interpolator"] == {"kind": "rife-torch", "device": "cpu", "model": rife.MODEL, "tta": ""}@pytest.mark.parametrize("field, value", [("backend", "ncnn"), ("weights", {"flownet.param": "0" * 64, "flownet.bin": "1" * 64}),diff --git a/tests/video/test_rife_torch_v425.py b/tests/video/test_rife_torch_v425.pynew file mode 100644index 0000000..9737e82--- /dev/null+++ b/tests/video/test_rife_torch_v425.py@@ -0,0 +1,105 @@+# SPDX-License-Identifier: Apache-2.0+"""rife-v4.25 in PyTorch, the torch backend of the default model (docs/loop-repair.md section 1): Practical-RIFE 4.25's+IFNet — an encoder run on each image and five blocks — read from the binary's own rife-v4.25 files, each image padded to+128 with zeros as the engine hands the binary it, with no augmentation.++Marked `torch_rife`: they need PyTorch and the installed model (`rife.locate_model()`); the lanes run them with none+skipped. That this network makes Practical-RIFE's own frame from the same weights — byte for byte on the CPU — was+measured against the official `train_log/IFNet_HDv3.py` outside this repository, which does not vendor it."""++from __future__ import annotations++import numpy as np+import pytest++from sprite_gen.video import rife, rife_install+from tests.video.test_rife import _marked++[email protected](scope="module")+def runner():+ from sprite_gen.video import rife_torch++ return rife_torch.TorchRunner(rife.locate_model().parent / "rife-v4.25", rife.device())++[email protected]_rife+def test_the_network_is_padded_as_the_engine_hands_the_binary_each_image():+ """rife-v4.25's IFNet pads to `rife.MODELS`' 128 and runs five blocks at scales 16 to 1, encoding each image;+ rife-v4.6's is unchanged (32, the binary's own padding, four blocks)."""+ from sprite_gen.video import rife_torch++ new, old = rife_torch.NETS["rife-v4.25"], rife_torch.NETS["rife-v4.6"]+ assert (new.pad, new.scales, len(new.blocks), new.head) == (rife.MODELS["rife-v4.25"].pad, (16, 8, 4, 2, 1), 5, True)+ assert (old.pad, old.scales, old.blocks, old.head) == (32, (8, 4, 2, 1), ((7, 192), (12, 128), (12, 96), (12, 64)), False)++[email protected]_rife+def test_the_model_is_read_layer_by_layer_in_its_own_order_and_loads_whole():+ """The installed rife-v4.25's layers with weights, read without ncnn, are the network's parameters in the order+ `rife_torch.layers` names them, each of the type named there: the encoder twice (once for each image), then each+ block's betas held apart before their convolutions (not folded in, as rife-v4.6's are), its strided convolutions and+ its transposed one. They fill every parameter of the network and no other; the betas are the model's, not ones."""+ import torch++ from sprite_gen.video import rife_torch++ files = rife.model_bytes(rife.locate_model().parent / "rife-v4.25")+ found = rife_torch._ncnn_layers(files["flownet.param"], files["flownet.bin"])+ assert [kind for kind, _, _ in found] == [kind for _, kind in rife_torch.layers("rife-v4.25")]+ state = rife_torch.state_from_ncnn(files, "rife-v4.25")+ assert set(state) == set(rife_torch.IFNet("rife-v4.25").state_dict())+ betas = [v for k, v in state.items() if k.endswith(".beta")]+ assert len(betas) == 5 * 8 and not all(torch.equal(b, torch.ones_like(b)) for b in betas)++[email protected]_rife+def test_a_model_whose_encoder_copies_differ_or_whose_layers_are_out_of_order_is_refused(monkeypatch):+ """The encoder the model holds twice must be the same both times, and each layer of the type the network has there:+ a second copy changed, or two layers swapped, is refused by name as the state is filled (`rife.RifeUnavailable` from+ the runner), not loaded."""+ from sprite_gen.video import rife_torch++ files = rife.model_bytes(rife.locate_model().parent / "rife-v4.25")+ real = rife_torch._ncnn_layers(files["flownet.param"], files["flownet.bin"])+ changed = list(real)+ kind, w, b = changed[4] # the second copy's first convolution+ changed[4] = (kind, w + 1e-3, b)+ monkeypatch.setattr(rife_torch, "_ncnn_layers", lambda *_: changed)+ with pytest.raises(ValueError, match=r"encode.cnn0: the model's two copies differ"):+ rife_torch.state_from_ncnn(files, "rife-v4.25")+ with pytest.raises(rife.RifeUnavailable, match=r"does not load: encode.cnn0: the model's two copies differ"):+ rife_torch.TorchRunner(rife.locate_model().parent / "rife-v4.25", "cpu")+ swapped = list(real)+ swapped[8], swapped[9] = swapped[9], swapped[8] # block0's first beta and its first convolution+ monkeypatch.setattr(rife_torch, "_ncnn_layers", lambda *_: swapped)+ with pytest.raises(ValueError, match=r"block0.convblock.0.beta: the model holds a Convolution where the network has a "+ r"MemoryData"):+ rife_torch.state_from_ncnn(files, "rife-v4.25")++[email protected]_rife+def test_rife_v4_25_pads_to_128_runs_with_no_augmentation_and_names_its_model(runner):+ """Each image goes in padded with zeros to a multiple of 128; an augmentation asked for is refused, not run; the runner+ names its model, in its identity (a `Cache` key, and what an executor answers as) and for a report."""+ import torch++ padded = runner._pad(np.full((97, 130, 3), 255, np.uint8))+ assert tuple(padded.shape) == (1, 3, 128, 256)+ assert torch.all(padded[..., :97, :130] == 1) and not padded[..., 97:, :].any() and not padded[..., 130:].any()+ colour = [np.asarray(_marked(x))[..., :3].copy() for x in (40, 72)]+ for modes in (("-x",), ("-z",), ("-x", "-z")):+ with pytest.raises(rife.RifeUnavailable, match=r"rife-v4.25 runs with no augmentation"):+ runner.run(colour[0], colour[1], 0.5, modes)+ made = runner.run(colour[0], colour[1], 0.5, None)+ assert made.shape == colour[0].shape and made.dtype == np.uint8+ assert np.array_equal(made, runner.run(colour[0], colour[1], 0.5, ()))+ assert runner.identity()["model"] == "rife-v4.25" and runner.describe()["model"] == "rife-v4.25"++[email protected]_rife+def test_the_check_frame_through_rife_v4_25_lands_half_way(runner):+ """`sprite-gen rife install --backend torch`'s check frame from rife-v4.25: the disc lands half way (x 48)."""+ 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