File size: 11,353 Bytes
6daffc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fe1cfd
6daffc2
 
 
 
 
 
263b26f
 
 
 
 
 
6daffc2
 
 
263b26f
6daffc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263b26f
6daffc2
 
 
 
263b26f
6daffc2
 
 
 
 
263b26f
6daffc2
 
263b26f
6daffc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263b26f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6daffc2
 
 
 
 
 
 
 
263b26f
6daffc2
 
 
 
 
263b26f
6daffc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fe1cfd
 
 
 
 
263b26f
9fe1cfd
6daffc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263b26f
 
 
 
6daffc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263b26f
 
 
 
 
6daffc2
263b26f
 
6daffc2
 
263b26f
6daffc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"""Prompt-to-image pipeline: loading, sampling, decoding and PNG metadata."""

from __future__ import annotations

import json
from collections.abc import Sequence
from dataclasses import asdict, dataclass, field
from enum import Enum
from pathlib import Path

import torch
from huggingface_hub import snapshot_download
from PIL import Image, PngImagePlugin
from torch import Tensor

from .configuration import read_inference_policy
from .inference import (
    DFlowEngine,
    GenerationSettings,
    ImageToImage,
    LatentCallback,
)
from .loading import (
    CONFIG_FILENAME,
    load_dflow_denoiser,
    load_text_adapter_tensors,
    read_release_version,
)
from .preview import preview_images
from .text_conditioning import DFlowTextEncoder, TextAdapter
from .vae import DFlowVae
from .version import __version__

REPOSITORY = "data-archetype/dflow_2b"
TEXT_ENCODER_DIRNAME = "text_encoder"
PNG_METADATA_KEY = "dflow"
_RELEASE_PATTERNS = (
    "model.safetensors",
    "config.json",
    "release.json",
    f"{TEXT_ENCODER_DIRNAME}/*",
)


def resolve_release_directory(
    path_or_repository: str | Path,
    *,
    revision: str | None,
    cache_dir: Path | None,
) -> Path:
    """Return a local release directory.

    A ``Path`` or an existing directory is used as it is; any other string
    with a ``/`` is a Hub repository id whose weights and text encoder are
    downloaded at ``revision``.

    Raises:
        FileNotFoundError: If a ``Path`` names no directory, or a string is
            neither a directory nor a Hub id.
        ValueError: If ``revision`` is given with a local directory.
    """

    if isinstance(path_or_repository, Path):
        if not path_or_repository.is_dir():
            raise FileNotFoundError(f"No release directory at {path_or_repository}.")
        return _local_release(path_or_repository, revision)
    local = Path(path_or_repository).expanduser()
    if local.is_dir():
        return _local_release(local, revision)
    if "/" not in path_or_repository:
        raise FileNotFoundError(
            f"No release folder {path_or_repository!r} here; pass its path or the "
            "Hub id data-archetype/dflow_2b."
        )
    return Path(
        snapshot_download(
            path_or_repository,
            revision=revision,
            allow_patterns=list(_RELEASE_PATTERNS),
            cache_dir=None if cache_dir is None else str(cache_dir),
        )
    )


def _local_release(directory: Path, revision: str | None) -> Path:
    """Return a local release directory, which has no Hub revision.

    Raises:
        ValueError: If ``revision`` is given.
    """

    if revision is not None:
        raise ValueError(
            f"Revision {revision!r} selects a Hub release, but {directory} is a "
            "local folder. Load the repository id data-archetype/dflow_2b (the "
            "DFlow Loader's hub source) to use a revision."
        )
    return directory


@dataclass(frozen=True)
class DFlowComponents:
    """The loaded parts of the model.

    Attributes:
        engine: Denoiser and text encoder.
        vae: The dinac3_96 autoencoder.
        compiled: Whether the blocks were compiled.
        weights_version: The release the weights come from (``release.json``).
    """

    engine: DFlowEngine
    vae: DFlowVae
    compiled: bool
    weights_version: str

    @classmethod
    def from_pretrained(
        cls,
        path_or_repository: str | Path = REPOSITORY,
        *,
        device: torch.device | str = "cuda",
        compile: bool = True,
        revision: str | None = None,
        cache_dir: Path | None = None,
        vae_dir: Path | None = None,
    ) -> DFlowComponents:
        """Load the denoiser, text encoder and autoencoder.

        Args:
            path_or_repository: A local release directory or Hub repository.
            device: CUDA device.
            compile: ``torch.compile`` the denoiser blocks, encoder layers and
                autoencoder. Graphs build on first use (30 to 45 seconds);
                False runs eagerly.
            revision: Hub revision of the release (a repository id only).
            cache_dir: Hugging Face cache directory, or None for the default.
            vae_dir: A local copy of ``data-archetype/dinac3_96``, or None to
                download its pinned commit.

        Raises:
            FileNotFoundError: If release files are missing.
            ValueError: On a non-CUDA device or a release that does not match
                this code.
        """

        target = torch.device(device)
        directory = resolve_release_directory(
            path_or_repository, revision=revision, cache_dir=cache_dir
        )
        model = load_dflow_denoiser(directory, device=target, compile_model=compile)
        adapter = TextAdapter()
        adapter.load_state_dict(load_text_adapter_tensors(directory), strict=True)
        text_encoder = DFlowTextEncoder.from_directory(
            directory / TEXT_ENCODER_DIRNAME, adapter=adapter, device=target
        )
        if compile:
            text_encoder.compile_layers()
        vae = DFlowVae.from_pretrained(
            device=target, compile=compile, local_dir=vae_dir, cache_dir=cache_dir
        )
        policy = read_inference_policy(directory / CONFIG_FILENAME)
        return cls(
            engine=DFlowEngine(model, text_encoder, policy=policy),
            vae=vae,
            compiled=compile,
            weights_version=read_release_version(directory),
        )


class OutputType(Enum):
    """What ``DFlowPipeline.__call__`` returns."""

    PIL = "pil"
    TENSOR = "tensor"
    LATENT = "latent"


@dataclass(frozen=True)
class DFlowOutput:
    """Images of one call.

    Attributes:
        images: PIL images with their settings in the PNG text chunk (PIL
            output), else empty.
        tensors: ``[B, 3, H, W]`` float32 RGB in ``[-1, 1]`` (TENSOR output),
            or ``[B, 96, h, w]`` latents (LATENT output), else None.
        settings: The settings of the call.
    """

    images: list[Image.Image]
    tensors: Tensor | None
    settings: GenerationSettings


@dataclass
class DFlowPipeline:
    """Text to image with dflow_2b.

    Example::

        pipe = DFlowPipeline.from_pretrained("data-archetype/dflow_2b")
        image = pipe("A lighthouse on a cliff at dusk.").images[0]
        image.save("lighthouse.png", pnginfo=pipe.png_info(image))
    """

    components: DFlowComponents
    default_settings: GenerationSettings = field(default_factory=GenerationSettings)

    @classmethod
    def from_pretrained(
        cls,
        path_or_repository: str | Path = REPOSITORY,
        *,
        device: torch.device | str = "cuda",
        compile: bool = True,
        revision: str | None = None,
        cache_dir: Path | None = None,
        vae_dir: Path | None = None,
    ) -> DFlowPipeline:
        """Load a pipeline (see ``DFlowComponents.from_pretrained``)."""

        return cls(
            DFlowComponents.from_pretrained(
                path_or_repository,
                device=device,
                compile=compile,
                revision=revision,
                cache_dir=cache_dir,
                vae_dir=vae_dir,
            )
        )

    def __call__(
        self,
        prompt: str | Sequence[str],
        settings: GenerationSettings | None = None,
        *,
        num_images: int = 1,
        output_type: OutputType = OutputType.PIL,
        image_to_image: ImageToImage | None = None,
        callback: LatentCallback | None = None,
    ) -> DFlowOutput:
        """Generate images.

        Args:
            prompt: One prompt (repeated ``num_images`` times) or a list of
                prompts with the same token count.
            settings: Size, seed, sampling and guidance; the pipeline's
                ``default_settings`` when None.
            num_images: Images per prompt string (a single prompt only).
            output_type: PIL images, RGB tensors or latents.
            image_to_image: Start latents and start step, or None.
            callback: Receives the predicted clean latents after each update
                (``dflow.preview.LatentRgbPreview`` turns them into previews).

        Raises:
            ValueError: For ``num_images`` < 1 or with a prompt list.
        """

        chosen = self.default_settings if settings is None else settings
        prompts = _prompt_list(prompt, num_images)
        latents = self.components.engine.sample(
            prompts, chosen, image_to_image=image_to_image, callback=callback
        )
        match output_type:
            case OutputType.LATENT:
                return DFlowOutput(images=[], tensors=latents, settings=chosen)
            case OutputType.TENSOR:
                rgb = self.components.vae.decode(latents).clamp(-1.0, 1.0)
                return DFlowOutput(images=[], tensors=rgb, settings=chosen)
            case OutputType.PIL:
                rgb = self.components.vae.decode(latents).clamp(-1.0, 1.0)
                images = preview_images(rgb)
                for index, image in enumerate(images):
                    image.info[PNG_METADATA_KEY] = generation_metadata(
                        prompts[index],
                        chosen,
                        batch_index=index,
                        weights_version=self.components.weights_version,
                    )
                return DFlowOutput(images=images, tensors=None, settings=chosen)
            case _ as unreachable:
                raise ValueError(f"Unsupported output type: {unreachable}")

    @staticmethod
    def png_info(image: Image.Image) -> PngImagePlugin.PngInfo:
        """A ``PngInfo`` carrying the image's generation metadata, for
        ``image.save(path, pnginfo=...)``.

        Raises:
            KeyError: If the image did not come from this pipeline.
        """

        info = PngImagePlugin.PngInfo()
        info.add_text(PNG_METADATA_KEY, str(image.info[PNG_METADATA_KEY]))
        return info


def generation_metadata(
    prompt: str,
    settings: GenerationSettings,
    *,
    batch_index: int,
    weights_version: str,
) -> str:
    """JSON text describing one generated image; ``model`` names the release
    of the weights, ``package`` the code's version."""

    payload = {
        "model": f"dflow_2b {weights_version}",
        "package": __version__,
        "prompt": prompt,
        "batch_index": batch_index,
        "settings": asdict(settings),
    }
    return json.dumps(payload, default=_json_value, sort_keys=True)


def _json_value(value: object) -> object:
    """JSON form of enums in the settings."""

    match value:
        case Enum():
            return value.value
        case _:
            raise TypeError(f"Cannot serialize {type(value).__name__} to JSON.")


def _prompt_list(prompt: str | Sequence[str], num_images: int) -> list[str]:
    """The batch's prompts.

    Raises:
        ValueError: For ``num_images`` < 1, or ``num_images`` > 1 with a list.
    """

    if num_images < 1:
        raise ValueError(f"num_images must be >= 1, got {num_images}.")
    if isinstance(prompt, str):
        return [prompt] * num_images
    if num_images != 1:
        raise ValueError("num_images applies to a single prompt string only.")
    return list(prompt)