File size: 4,972 Bytes
00ff9d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""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}.")