Files
Spellcast3d/code/tests/test_detail_worker.py

266 lines
15 KiB
Python

"""The detail pass's own program (launchers/detail_worker.py): the upscaling network as its file names its layers,
a picture taken through it tile by tile, and the hold that keeps a larger picture to the one it was made from; and
what it puts into SeedVR2's runner for single pictures (launchers/detail_seedvr2.py). On the CPU, with networks of
a few layers: no weights are needed.
Runs in the pixal3d venv, with pytest from code/logs/profiling/pytools:
set PYTHONPATH=code\\logs\\profiling\\pytools
code\\venvs\\pixal3d\\Scripts\\python.exe -m pytest -p no:cacheprovider code\\tests\\test_detail_worker.py -q
Skipped in the hub venv (no torch).
"""
from __future__ import annotations
import io
import json
import sys
from pathlib import Path
import pytest
from spellcast import paths
from spellcast.adapters import omnitexture, omnitexture_detail
from spellcast.install import models
torch = pytest.importorskip("torch")
if str(paths.LAUNCHERS) not in sys.path: # the launchers are top-level modules of their folder
sys.path.insert(0, str(paths.LAUNCHERS))
import detail_seedvr2 as sv # noqa: E402
import detail_worker as dw # noqa: E402
def test_the_hub_and_the_program_agree_on_the_kinds_the_scale_and_the_file() -> None:
assert set(dw.KINDS) == set(omnitexture_detail.NETWORKS) and dw.SCALE == omnitexture.DETAIL_SCALE
assert (dw.UPSCALER,) == omnitexture_detail.NETWORKS[dw.UPSCALED].files == (models.DETAIL_UPSCALER,)
assert paths.MODELS_DETAIL / dw.UPSCALER == paths.MODELS_QWEN / next(iter(models.DETAIL_PINS))
# SeedVR2's files where the install puts them (install/models.py) and the hub looks for them
seedvr2 = f"{dw.SEEDVR2}/"
assert {f"{seedvr2}{dw.SEEDVR2_DIT}", f"{seedvr2}{dw.SEEDVR2_VAE}", *(seedvr2 + w for w in dw.SEEDVR2_WHEELS),
f"{seedvr2}{dw.SEEDVR2_RUNNER}/inference_cli.py"} == set(omnitexture_detail.NETWORKS[dw.DETAILED].files)
assert models.SEEDVR2_CODE == f"detail/{dw.SEEDVR2}/{dw.SEEDVR2_RUNNER}"
def test_a_sheets_figures_are_found_from_its_depth_picture_each_with_room_around_it() -> None:
"""The figures stand apart on the sheet: each one's crop holds its outline and FIGURE_AROUND beyond it (inside
the sheet), its sides whole multiples of FIGURE_STEP; a speck is none; the mask is the figure's alone."""
import numpy as np
outline = np.zeros((512, 640), bool)
outline[40:300, 30:200] = True # a figure
outline[100:460, 380:620] = True # another, reaching the right edge's room
outline[480:484, 10:14] = True # a speck
found = dw.figures(outline)
assert len(found) == 2
for (left, top, right, bottom, mask), (y0, y1, x0, x1) in zip(found, ((40, 300, 30, 200), (100, 460, 380, 620))):
assert (right - left) % dw.FIGURE_STEP == 0 and (bottom - top) % dw.FIGURE_STEP == 0
assert left <= max(0, x0 - dw.FIGURE_AROUND) and right >= min(640, x1 + dw.FIGURE_AROUND)
assert top <= max(0, y0 - dw.FIGURE_AROUND) and bottom >= min(512, y1 + dw.FIGURE_AROUND)
assert 0 <= left and right <= 640 and 0 <= top and bottom <= 512 and mask.shape == (bottom - top, right - left)
assert mask[(y0 + y1) // 2 - top, (x0 + x1) // 2 - left] and mask.sum() < mask.size
assert not found[0][4][:, -1].any(), "the other figure is not in this one's mask"
def test_the_detailed_kind_keeps_the_given_pictures_broad_tone() -> None:
"""toned(): a picture redrawn a little brighter and tinted comes back in the given one's tone, made small again,
while what it drew sharper stays."""
torch.manual_seed(4)
small = torch.nn.functional.interpolate(torch.rand(1, 3, 12, 12), size=(64, 64), mode="bicubic").clamp(0, 1)
edges = (torch.rand(1, 3, 128, 128) > 0.97).float() * 0.3
fine = torch.nn.functional.interpolate(small, scale_factor=2, mode="bicubic") * 1.1 + 0.05 + edges
toned = dw.toned(small, fine)
again = lambda picture: torch.nn.functional.interpolate(picture, scale_factor=0.5, mode="area") # noqa: E731
assert (again(fine) - small).mean().abs() > 0.05 and (again(toned) - small).mean().abs() < 0.01
assert (toned - fine).abs().max() < 0.2, "only the broad tone moves: the sharp marks stay"
def test_the_network_reads_its_file_as_the_file_names_its_layers(tmp_path: Path) -> None:
"""The file names its layers as MoSR does (gblocks.<n>.fc1, ..., shortcut.block.<n>, upsampler.0) - 208 tensors
for its 24 blocks - and keeps them in half precision: read into the network's own layers, as many blocks as
the file holds, it computes what the network it came from does, at four times the size."""
from safetensors.torch import save_file
torch.manual_seed(1)
assert len(dw.Upscaler().state_dict()) == 208
net = dw.Upscaler(blocks=3).eval()
assert {key.split(".")[0] for key in net.state_dict()} == {"gblocks", "shortcut", "upsampler"}
save_file({key: tensor.half() for key, tensor in net.state_dict().items()}, str(tmp_path / dw.UPSCALER))
read = dw.Upscaler.from_file(tmp_path / dw.UPSCALER)
picture = torch.rand(1, 3, 24, 16)
with torch.inference_mode():
net.load_state_dict({key: tensor.half().float() for key, tensor in net.state_dict().items()})
assert torch.equal(read(picture), net(picture)) and read(picture).shape == (1, 3, 96, 64)
def test_a_picture_goes_through_the_network_in_tiles_that_meet_without_a_seam(monkeypatch: pytest.MonkeyPatch) -> None:
"""With enough of its surroundings a tile computes what the whole picture does: no seam where two meet."""
torch.manual_seed(2)
network = dw.Upscaled.__new__(dw.Upscaled)
network.half, network.net = False, dw.Upscaler(blocks=1).eval()
monkeypatch.setattr(dw, "TILE", 32)
monkeypatch.setattr(dw, "AROUND", 40)
picture = torch.rand(1, 3, 96, 80)
with torch.inference_mode():
whole = torch.nn.functional.interpolate(network.net(picture), scale_factor=0.5, mode="area") # (4x -> 2x)
tiled = network.enlarge(picture)
assert tiled.shape == (1, 3, 192, 160) and torch.allclose(tiled, whole, atol=1e-5)
monkeypatch.setattr(dw, "AROUND", 2)
assert not torch.allclose(network.enlarge(picture), whole, atol=1e-3), "too little around a tile shows"
def test_a_larger_picture_held_to_its_own_keeps_only_what_is_finer_than_its_pixels() -> None:
"""A network that also brightens and tints: made small again, the picture held is the one given - and the
network's grain, which a picture of the smaller size cannot show, is still there."""
torch.manual_seed(3)
small = torch.nn.functional.interpolate(torch.rand(1, 3, 12, 12), size=(48, 48), mode="bicubic").clamp(0, 1)
grain = (torch.rand(1, 3, 96, 96) - 0.5) * 0.2
fine = torch.nn.functional.interpolate(small, scale_factor=2, mode="bicubic") * 1.15 + 0.04 + grain
held = dw.held(small, fine)
again = lambda picture: torch.nn.functional.interpolate(picture, scale_factor=0.5, mode="area") # noqa: E731
assert (again(fine) - small).abs().mean() > 0.05
assert (again(held) - small).abs().mean() < 0.004, "within a level of the picture given"
within = lambda picture: (picture - torch.nn.functional.interpolate(again(picture), scale_factor=2)).std() # noqa: E731
assert within(held) > 0.8 * within(fine), "the detail finer than the smaller picture's pixels stays"
def test_the_program_answers_one_line_a_request_and_says_what_it_cannot_do() -> None:
asked = io.StringIO("\n".join(json.dumps(request) for request in (
{"cmd": "enlarge", "picture": "a.png", "out": "b.png"}, {"cmd": "load", "kind": "8k", "models": "."},
{"cmd": "prepare", "kind": "upscaled", "models": "."}, {"cmd": "prepare", "kind": "8k", "models": "."},
{"cmd": "quit"}, {"cmd": "load", "kind": "upscaled", "models": "."})) + "\n")
answered = io.StringIO()
assert dw.main(asked, answered) == 0
first, second, ahead, unknown = (json.loads(line) for line in answered.getvalue().splitlines())
assert "'enlarge' before 'load'" in first["error"] and "unknown kind '8k'" in second["error"]
assert ahead["ok"] and ahead["kind"] == "upscaled" and "unknown kind '8k'" in unknown["error"]
assert not torch.cuda.is_initialized(), "nothing of it is on the card"
def test_the_bolder_the_smaller_the_picture_seedvr2_draws_a_figure_from() -> None:
"""At 0 the figure as it is; at 1 a quarter of its size (BOLDEST), each step shrinking it by the same factor -
what it draws from that is as large as ever."""
import numpy as np
crop = np.random.default_rng(6).integers(0, 255, (96, 160, 3), dtype=np.uint8)
assert dw.lessened(crop, 0.0) is crop and dw.lessened(crop, -1.0) is crop
assert dw.lessened(crop, 1.0).shape == (24, 40, 3) and dw.lessened(crop, 7.0).shape == (24, 40, 3)
assert dw.lessened(crop, 0.5).shape == (48, 80, 3) and dw.lessened(crop, 0.25).shape == (68, 113, 3)
assert abs(float(dw.lessened(crop, 1.0).mean()) - float(crop.mean())) < 1.0, "the same picture, smaller"
def test_as_many_of_the_dits_blocks_stay_on_the_card_as_it_has_room_for() -> None:
"""One at least is swapped (the runner then leaves the model where it is), a few stay whatever the card."""
assert dw.resident_blocks(11.0) == dw.BLOCKS - 1
assert dw.resident_blocks(7.0) == int((7.0 - dw.SEEDVR2_ROOM) / dw.BLOCK_GB) == 18
assert dw.resident_blocks(7.0) * dw.BLOCK_GB + dw.SEEDVR2_ROOM <= 7.0, "an 8 GB card's free memory holds it"
assert dw.resident_blocks(2.0) == dw.RESIDENT_LEAST
def test_seedvr2s_files_are_read_ahead_in_the_order_the_runner_reads_them(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
""""load" starts reading the VAE's file, then the DiT's, once and in large pieces (read_ahead), before the
runner maps them; a file that cannot be read stops it with a line, never the pass."""
for name, size in ((dw.SEEDVR2_VAE, 5), (dw.SEEDVR2_DIT, 11)):
(tmp_path / name).write_bytes(bytes(size))
started = []
class Thread:
def __init__(self, target, args, name, daemon) -> None: # noqa: ANN001
self.call = (target, *args)
def start(self) -> None:
started.append(self.call)
class Stop(Exception):
pass
def stop() -> None:
raise Stop
monkeypatch.setattr(dw.Detailed, "_runner", staticmethod(lambda models: tmp_path))
monkeypatch.setattr(dw.threading, "Thread", Thread)
monkeypatch.setattr(dw.torch.cuda, "mem_get_info", stop) # (no runner here: what follows is not wanted)
with pytest.raises(Stop):
dw.Detailed(tmp_path)
assert started == [(dw.read_ahead, [tmp_path / dw.SEEDVR2_VAE, tmp_path / dw.SEEDVR2_DIT])]
monkeypatch.setattr(dw, "READ_CHUNK", 4)
capsys.readouterr()
dw.read_ahead(started[0][1])
assert "files read ahead (0.0 GB in" in capsys.readouterr().err
dw.read_ahead([tmp_path / "gone.safetensors"])
assert "Reading SeedVR2's files ahead stopped" in capsys.readouterr().err
def test_a_causal_3d_convolution_of_one_frame_is_the_2d_one_with_its_steps_in_time_summed() -> None:
"""What the VAE's layers do to a single frame - the frame repeated before it for a causal convolution, the
first step in time kept of what an upsampling layer makes - against the 2D layers `folded` makes of them."""
F = torch.nn.functional
torch.manual_seed(5)
x = torch.randn(1, 6, 9, 8)
state = {"decoder.a.weight": torch.randn(4, 6, 3, 3, 3), "encoder.down.weight": torch.randn(4, 6, 3, 3, 3),
"encoder.flat.weight": torch.randn(4, 6, 1, 3, 3), "encoder.norm.weight": torch.randn(6),
"decoder.up.upscale_conv.weight": torch.randn(6 * 8, 6, 1, 1, 1),
"decoder.up.upscale_conv.bias": torch.randn(6 * 8),
"decoder.plain.upscale_conv.weight": torch.randn(6 * 4, 6, 1, 1, 1),
"decoder.plain.upscale_conv.bias": torch.randn(6 * 4), "quant_conv.weight": torch.randn(2, 2, 1, 1, 1)}
made = sv.folded(state)
assert "quant_conv.weight" not in made and torch.equal(made["encoder.norm.weight"], state["encoder.norm.weight"])
repeated = x[:, :, None].expand(-1, -1, 3, -1, -1) # (the frame, and itself twice before it)
for name, stride in (("decoder.a.weight", 1), ("encoder.down.weight", 2)):
in_3d = F.conv3d(F.pad(repeated, (1, 1, 1, 1)), state[name], stride=stride)[:, :, 0]
assert torch.allclose(F.conv2d(x, made[name], stride=stride, padding=1), in_3d, atol=1e-4)
assert torch.allclose(F.conv2d(x, made["encoder.flat.weight"]), F.conv3d(x[:, :, None], state["encoder.flat.weight"])[:, :, 0])
for name, steps in (("decoder.up.upscale_conv", 2), ("decoder.plain.upscale_conv", 1)):
every = F.conv3d(x[:, :, None], state[f"{name}.weight"], state[f"{name}.bias"]) # b (x y z c) 1 h w
b, _, _, h, w = every.shape
laid = every.reshape(b, 2, 2, steps, 6, 1, h, w).permute(0, 4, 5, 3, 6, 1, 7, 2) # b c f z h x w y
in_3d = laid.reshape(b, 6, steps, h * 2, w * 2)[:, :, 0] # (the first step in time)
in_2d = F.pixel_shuffle(F.conv2d(x, made[f"{name}.weight"], made[f"{name}.bias"]), 2)
assert torch.allclose(in_2d, in_3d, atol=1e-5), name
def test_the_2d_vae_takes_the_3d_ones_layers_and_makes_pictures_of_the_right_size() -> None:
net = sv.Vae2d()
state = {}
for name, tensor in net.state_dict().items(): # the 3D file's shapes for the 2D network's layers
if tensor.ndim == 4 and ".upscale_conv." in name:
steps = 2 if ".up_blocks.0." in name or ".up_blocks.1." in name else 1
tensor = torch.randn(tensor.shape[0] * steps, tensor.shape[1], 1, 1, 1) * 0.05
elif tensor.ndim == 4:
tensor = (torch.randn(*tensor.shape[:2], 3 if tensor.shape[-1] == 3 else 1, *tensor.shape[2:]) * 0.02)
elif ".upscale_conv." in name:
tensor = torch.zeros(tensor.shape[0] * (2 if ".up_blocks.0." in name or ".up_blocks.1." in name else 1))
state[name] = tensor
net = sv.Vae2d.of(state)
with torch.inference_mode():
assert net.encoder(torch.rand(1, 3, 32, 48)).shape == (1, 2 * sv.LATENT, 4, 6)
assert net.decoder(torch.rand(1, sv.LATENT, 4, 6)).shape == (1, 3, 32, 48)
def test_the_blocks_that_stay_on_the_card_are_cast_once_and_a_kept_dit_is_not_moved_away() -> None:
class Model(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.blocks = torch.nn.ModuleList(torch.nn.Linear(2, 2).half() for _ in range(4))
self.first = torch.nn.Linear(2, 2).half()
self.blocks_to_swap = 1 # (the runner's: the last swapped block's index)
model = Model()
sv.cast_resident(model, torch.float32)
assert [block.weight.dtype for block in model.blocks] == [torch.float16] * 2 + [torch.float32] * 2
assert model.first.weight.dtype == torch.float16, "what is not a block stays as the file has it"
model.blocks[3].half()
sv.cast_resident(model, torch.float32)
assert model.blocks[3].weight.dtype == torch.float16, "once: not looked at again"
moved = []
class Phases:
cleanup_dit = staticmethod(lambda runner, debug=None, cache_model=False: moved.append(cache_model))
sv._dit_stays_between_pictures(Phases)
Phases.cleanup_dit("runner", debug=None, cache_model=True)
assert moved == [], "kept for the next picture: left where it is"
Phases.cleanup_dit("runner", debug=None, cache_model=False)
assert moved == [False]