"""Oklab round trip, head patch layout, uint8 rounding, and the turbo sampler constants.""" import json import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(HERE), "src")) import torch # noqa: E402 def test_oklab_round_trip(): from pq_image_dwd.color import oklab_norm_to_srgb, srgb_to_oklab_norm g = torch.Generator().manual_seed(0) x = torch.rand(2, 3, 8, 8, generator=g, dtype=torch.float64) * 2 - 1 assert torch.allclose(oklab_norm_to_srgb(srgb_to_oklab_norm(x)), x, atol=1e-6) # white and black land on the normalized Oklab constants white = srgb_to_oklab_norm(torch.ones(1, 3, 1, 1, dtype=torch.float64))[:, :, 0, 0] black = srgb_to_oklab_norm(-torch.ones(1, 3, 1, 1, dtype=torch.float64))[:, :, 0, 0] assert torch.allclose(white, torch.tensor([[(1 - 0.56) / 0.16, 0.0, -0.01 / 0.16]], dtype=torch.float64), atol=1e-6) assert torch.allclose(black, torch.tensor([[-0.56 / 0.16, 0.0, -0.01 / 0.16]], dtype=torch.float64), atol=1e-6) def test_patch_layout(): from pq_image_dwd.color import head_to_srgb, oklab_norm_to_srgb, patchify, unpatchify x = torch.arange(2 * 3 * 32 * 48, dtype=torch.float32).reshape(2, 3, 32, 48) y = patchify(x) assert y.shape == (2, 2 * 3, 768) assert torch.equal(unpatchify(y, 2, 3), x) # token 1 is the tile at row 0, column 1; its first 256 values are channel 0 of that tile, row-major assert torch.equal(y[0, 1, :256], x[0, 0, :16, 16:32].reshape(-1)) yb = torch.randn(1, 6, 768).to(torch.bfloat16) assert torch.equal(head_to_srgb(yb, 2, 3), oklab_norm_to_srgb(unpatchify(yb.float(), 2, 3)).clamp(-1, 1)) def test_to_uint8(): from pq_image_dwd.color import to_uint8 x = torch.tensor([-1.0, -0.5, 0.0, 1.0, 2.0]).view(1, 1, 1, 5).expand(1, 3, 1, 5) u = to_uint8(x) assert u.shape == (1, 1, 5, 3) and u.dtype == torch.uint8 assert u[0, 0, :, 0].tolist() == [0, 64, 128, 255, 255] def test_sigmas_and_timesteps(tmp_path): from pq_image_dwd import schedule as S assert S.STEPS == 8 and S.HEAD_SIGMA == 0.414568 (tmp_path / "model_index.json").write_text(json.dumps({"sample_sigmas": S.SIGMAS})) assert S.sample_sigmas(str(tmp_path)) == S.SIGMAS assert S.sample_sigmas(None) == S.SIGMAS # the head step's timestep after the stock bf16 rounding t = S.model_timestep(torch.tensor([S.HEAD_SIGMA])) assert t.dtype == torch.bfloat16 and float(t) == 0.4140625