"""Fast latent-to-RGB previews for dinac3_96 latents. A fitted linear readout: a 3x3 convolution from the 96 whitened latent channels to a 2x2 cell of RGB values per latent token, pixel-shuffled to 1/8 of the image resolution. It is meant for live previews during sampling; the final image always comes from the VAE decoder. """ from __future__ import annotations import json from dataclasses import dataclass from pathlib import Path import torch import torch.nn.functional as F from PIL import Image from safetensors import safe_open from safetensors.torch import load_file from torch import Tensor LATENT_RGB_PREVIEW_FILENAME = "latent_rgb_preview.safetensors" _METADATA_KEY = "dflow" _FORMAT = "dflow.latent_rgb_preview.v1" _WEIGHT_KEY = "projection.weight" _BIAS_KEY = "projection.bias" _LATENT_CHANNELS = 96 _RGB_CHANNELS = 3 _EXPANSION = 2 @dataclass(frozen=True) class LatentRgbPreview: """The fitted projection, as float32 tensors on one device. Attributes: weight: ``[12, 96, k, k]`` convolution weight (k odd). bias: ``[12]`` bias. """ weight: Tensor bias: Tensor @classmethod def from_file(cls, path: Path) -> LatentRgbPreview: """Load a projection file and check its metadata and shapes. Raises: ValueError: If the metadata, tensor names, shapes or dtypes do not match the dinac3_96 preview format. """ _check_metadata(path) tensors = load_file(str(path), device="cpu") if set(tensors) != {_WEIGHT_KEY, _BIAS_KEY}: raise ValueError( f"{path} must hold exactly {_WEIGHT_KEY} and {_BIAS_KEY}, " f"got {sorted(tensors)}." ) weight = tensors[_WEIGHT_KEY] bias = tensors[_BIAS_KEY] cells = _RGB_CHANNELS * _EXPANSION**2 kernel = int(weight.shape[-1]) if ( weight.ndim != 4 or tuple(weight.shape[:2]) != (cells, _LATENT_CHANNELS) or int(weight.shape[2]) != kernel or kernel % 2 != 1 or tuple(bias.shape) != (cells,) ): raise ValueError( f"{path}: expected weight [{cells}, {_LATENT_CHANNELS}, k, k] with " f"odd k and bias [{cells}], got {tuple(weight.shape)} and " f"{tuple(bias.shape)}." ) if weight.dtype != torch.float32 or bias.dtype != torch.float32: raise ValueError(f"{path}: the projection must be stored in float32.") return cls(weight=weight.contiguous(), bias=bias.contiguous()) @classmethod def bundled(cls) -> LatentRgbPreview: """Load the projection shipped with the package.""" return cls.from_file(Path(__file__).with_name(LATENT_RGB_PREVIEW_FILENAME)) def to(self, device: torch.device) -> LatentRgbPreview: """Return a copy on ``device``.""" return LatentRgbPreview(self.weight.to(device), self.bias.to(device)) def project(self, latents: Tensor) -> Tensor: """Project whitened latents ``[B, 96, h, w]`` to RGB ``[B, 3, 2h, 2w]`` in ``[-1, 1]`` (float32, on the latents' device). The latents are padded by replication so the output keeps the latent grid's size. """ pad = int(self.weight.shape[-1]) // 2 with torch.autocast(device_type=latents.device.type, enabled=False): padded = F.pad(latents.float(), (pad, pad, pad, pad), mode="replicate") cells = F.conv2d(padded, self.weight, self.bias) return F.pixel_shuffle(cells, _EXPANSION).clamp(-1.0, 1.0) def preview_images(rgb: Tensor) -> list[Image.Image]: """Convert ``[B, 3, H, W]`` RGB in ``[-1, 1]`` to PIL images.""" pixels = ( rgb.detach() .float() .add(1.0) .mul(127.5) .round() .clamp(0.0, 255.0) .to(torch.uint8) .permute(0, 2, 3, 1) .cpu() .numpy() ) return [Image.fromarray(image, mode="RGB") for image in pixels] def _check_metadata(path: Path) -> None: """Require the dflow preview format in the file's metadata. Raises: ValueError: If the metadata is missing or describes another format. """ with safe_open(str(path), framework="pt", device="cpu") as handle: header = handle.metadata() if header is None or _METADATA_KEY not in header: raise ValueError(f"{path} has no '{_METADATA_KEY}' metadata.") metadata: dict[str, str] = json.loads(header[_METADATA_KEY]) expected = { "format": _FORMAT, "latent_channels": str(_LATENT_CHANNELS), "rgb_channels": str(_RGB_CHANNELS), "spatial_expansion_factor": str(_EXPANSION), } wrong = { key: (metadata.get(key), value) for key, value in expected.items() if metadata.get(key) != value } if wrong: raise ValueError(f"{path}: incompatible preview metadata {wrong}.")