File size: 9,646 Bytes
1ed770c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d69668
1ed770c
 
8d69668
1ed770c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""IRDiffAE: standalone HuggingFace-compatible iRDiffAE model."""

from __future__ import annotations

from pathlib import Path

import torch
from torch import Tensor, nn

from .config import IRDiffAEConfig, IRDiffAEInferenceConfig
from .decoder import Decoder
from .encoder import Encoder
from .samplers import run_ddim, run_dpmpp_2m
from .vp_diffusion import get_schedule, make_initial_state, sample_noise


def _resolve_model_dir(
    path_or_repo_id: str | Path,
    *,
    revision: str | None,
    cache_dir: str | Path | None,
) -> Path:
    """Resolve a local path or HuggingFace Hub repo ID to a local directory."""

    local = Path(path_or_repo_id)
    if local.is_dir():
        return local
    # Not a local directory — try HuggingFace Hub
    repo_id = str(path_or_repo_id)
    try:
        from huggingface_hub import snapshot_download
    except ImportError:
        raise ImportError(
            f"'{repo_id}' is not an existing local directory. "
            "To download from HuggingFace Hub, install huggingface_hub: "
            "pip install huggingface_hub"
        )
    cache_dir_str = str(cache_dir) if cache_dir is not None else None
    local_dir = snapshot_download(
        repo_id,
        revision=revision,
        cache_dir=cache_dir_str,
    )
    return Path(local_dir)


class IRDiffAE(nn.Module):
    """Standalone iRDiffAE model for HuggingFace distribution.

    A diffusion autoencoder that encodes images to compact latents and
    decodes them back via iterative VP diffusion.

    Usage::

        model = IRDiffAE.from_pretrained("path/to/weights")
        model = model.to("cuda", dtype=torch.bfloat16)

        # Encode
        latents = model.encode(images)  # images: [B,3,H,W] in [-1,1]

        # Decode (1 step by default — PSNR-optimal)
        recon = model.decode(latents, height=H, width=W)

        # Reconstruct (encode + 1-step decode)
        recon = model.reconstruct(images)
    """

    def __init__(self, config: IRDiffAEConfig) -> None:
        super().__init__()
        self.config = config

        self.encoder = Encoder(
            in_channels=config.in_channels,
            patch_size=config.patch_size,
            model_dim=config.model_dim,
            depth=config.encoder_depth,
            bottleneck_dim=config.bottleneck_dim,
            mlp_ratio=config.mlp_ratio,
            depthwise_kernel_size=config.depthwise_kernel_size,
        )

        self.decoder = Decoder(
            in_channels=config.in_channels,
            patch_size=config.patch_size,
            model_dim=config.model_dim,
            depth=config.decoder_depth,
            bottleneck_dim=config.bottleneck_dim,
            mlp_ratio=config.mlp_ratio,
            depthwise_kernel_size=config.depthwise_kernel_size,
            adaln_low_rank_rank=config.adaln_low_rank_rank,
        )

    @classmethod
    def from_pretrained(
        cls,
        path_or_repo_id: str | Path,
        *,
        dtype: torch.dtype = torch.bfloat16,
        device: str | torch.device = "cpu",
        revision: str | None = None,
        cache_dir: str | Path | None = None,
    ) -> IRDiffAE:
        """Load a pretrained model from a local directory or HuggingFace Hub.

        The directory (or repo) should contain:
        - config.json: Model architecture config.
        - model.safetensors (preferred) or model.pt: Model weights.

        Args:
            path_or_repo_id: Local directory path or HuggingFace Hub repo ID
                (e.g. ``"data-archetype/irdiffae-v1"``).
            dtype: Load weights in this dtype (float32 or bfloat16).
            device: Target device.
            revision: Git revision (branch, tag, or commit) for Hub downloads.
            cache_dir: Where to cache Hub downloads. Uses HF default if None.

        Returns:
            Loaded model in eval mode.
        """
        model_dir = _resolve_model_dir(
            path_or_repo_id, revision=revision, cache_dir=cache_dir
        )
        config = IRDiffAEConfig.load(model_dir / "config.json")
        model = cls(config)

        # Try safetensors first, fall back to .pt
        safetensors_path = model_dir / "model.safetensors"
        pt_path = model_dir / "model.pt"

        if safetensors_path.exists():
            try:
                from safetensors.torch import load_file

                state_dict = load_file(str(safetensors_path), device=str(device))
            except ImportError:
                raise ImportError(
                    "safetensors package required to load .safetensors files. "
                    "Install with: pip install safetensors"
                )
        elif pt_path.exists():
            state_dict = torch.load(
                str(pt_path), map_location=device, weights_only=True
            )
        else:
            raise FileNotFoundError(
                f"No model weights found in {model_dir}. "
                "Expected model.safetensors or model.pt."
            )

        model.load_state_dict(state_dict)
        model = model.to(dtype=dtype, device=torch.device(device))
        model.eval()
        return model

    def encode(self, images: Tensor) -> Tensor:
        """Encode images to latents.

        Args:
            images: [B, 3, H, W] in [-1, 1], H and W must be divisible by patch_size.

        Returns:
            Latents [B, bottleneck_dim, H/patch, W/patch].
        """
        try:
            model_dtype = next(self.parameters()).dtype
        except StopIteration:
            model_dtype = torch.float32
        return self.encoder(images.to(dtype=model_dtype))

    @torch.no_grad()
    def decode(
        self,
        latents: Tensor,
        height: int,
        width: int,
        *,
        inference_config: IRDiffAEInferenceConfig | None = None,
    ) -> Tensor:
        """Decode latents to images via VP diffusion.

        Args:
            latents: [B, bottleneck_dim, h, w] encoder latents.
            height: Output image height (must be divisible by patch_size).
            width: Output image width (must be divisible by patch_size).
            inference_config: Optional inference parameters. Uses defaults if None.

        Returns:
            Reconstructed images [B, 3, H, W] in float32.
        """
        cfg = inference_config or IRDiffAEInferenceConfig()
        config = self.config
        batch = int(latents.shape[0])
        device = latents.device

        # Determine model dtype from parameters
        try:
            model_dtype = next(self.parameters()).dtype
        except StopIteration:
            model_dtype = torch.float32

        # Validate dimensions
        if height % config.patch_size != 0 or width % config.patch_size != 0:
            raise ValueError(
                f"height={height} and width={width} must be divisible by patch_size={config.patch_size}"
            )

        # Generate initial noise
        shape = (batch, config.in_channels, height, width)
        noise = sample_noise(
            shape,
            noise_std=config.pixel_noise_std,
            seed=cfg.seed,
            device=torch.device("cpu"),
            dtype=torch.float32,
        )

        # Build schedule
        schedule = get_schedule(cfg.schedule, cfg.num_steps).to(device=device)

        # Construct initial state: sigma_start * noise
        initial_state = make_initial_state(
            noise=noise.to(device=device),
            t_start=schedule[0:1],
            logsnr_min=config.logsnr_min,
            logsnr_max=config.logsnr_max,
        )

        # Disable autocast for numerical precision
        device_type = "cuda" if device.type == "cuda" else "cpu"
        with torch.autocast(device_type=device_type, enabled=False):
            latents_in = latents.to(device=device)

            def _forward_fn(
                x_t: Tensor,
                t: Tensor,
                latents: Tensor,
                *,
                drop_middle_blocks: bool = False,
            ) -> Tensor:
                return self.decoder(
                    x_t.to(dtype=model_dtype),
                    t,
                    latents.to(dtype=model_dtype),
                    drop_middle_blocks=drop_middle_blocks,
                )

            # Select sampler
            if cfg.sampler == "ddim":
                sampler_fn = run_ddim
            elif cfg.sampler == "dpmpp_2m":
                sampler_fn = run_dpmpp_2m
            else:
                raise ValueError(
                    f"Unsupported sampler: {cfg.sampler!r}. Use 'ddim' or 'dpmpp_2m'."
                )

            result = sampler_fn(
                forward_fn=_forward_fn,
                initial_state=initial_state,
                schedule=schedule,
                latents=latents_in,
                logsnr_min=config.logsnr_min,
                logsnr_max=config.logsnr_max,
                pdg_enabled=cfg.pdg_enabled,
                pdg_strength=cfg.pdg_strength,
                device=device,
            )

        return result

    @torch.no_grad()
    def reconstruct(
        self,
        images: Tensor,
        *,
        inference_config: IRDiffAEInferenceConfig | None = None,
    ) -> Tensor:
        """Encode then decode. Convenience wrapper.

        Args:
            images: [B, 3, H, W] in [-1, 1].
            inference_config: Optional inference parameters.

        Returns:
            Reconstructed images [B, 3, H, W] in float32.
        """
        latents = self.encode(images)
        _, _, h, w = images.shape
        return self.decode(
            latents, height=h, width=w, inference_config=inference_config
        )