File size: 14,721 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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""Prompts to ``TextConditioning``: tokenize, encode, standardize, project.

For a prompt the model receives ``L + 3`` tokens of width 2304:

1. the T5Gemma2 hidden states after layers 2, 6 and 12 (``text_encoder``),
   each standardized per channel with fixed statistics (FP32);
2. three linear maps 640 -> 2304, one per tap, summed in FP32;
3. three learned suffix tokens appended.

A blank prompt (empty or whitespace only) is the learned unconditional
sequence: the unconditional token followed by the same three suffix tokens.
This is the null text used for CFG and for an empty negative prompt.

Batching rule: the denoiser runs each batch as one dense attention forward
without padding, so every prompt of a batch must have the same token count.
``DFlowTextEncoder.encode`` raises on unequal counts;
``DFlowTextEncoder.encode_grouped`` splits a list into equal-length groups.
A prompt repeated over a batch always qualifies.
"""

from __future__ import annotations

from collections.abc import Callable, Sequence
from dataclasses import dataclass
from pathlib import Path

import torch
import torch.nn.functional as F
from torch import Tensor, nn

from .layout import is_compiled_layout, is_stored_layout
from .prompt_emphasis import (
    EmphasisSettings,
    TokenEmphasis,
    parse_prompt_weights,
    token_emphasis,
)
from .text_encoder import (
    COMPUTE_DTYPE,
    ENCODER_CONFIG,
    EncoderTaps,
    EncoderWeighting,
    T5Gemma2Encoder,
)
from .tokenization import PromptTokenizer
from .types import SUFFIX_TOKEN_COUNT, TextConditioning

__all__ = [
    "SUFFIX_TOKEN_COUNT",
    "TEXT_ADAPTER_KEY_MAP",
    "TEXT_ADAPTER_REQUIRED_FLAGS",
    "TEXT_WIDTH",
    "DFlowTextEncoder",
    "TextAdapter",
    "TextConditioningGroup",
]

TEXT_WIDTH = 2304
_TAP_COUNT = 3

# Training checkpoint key -> key relative to ``TextAdapter`` (the public file adds
# the prefix ``text_adapter.``).
TEXT_ADAPTER_KEY_MAP: dict[str, str] = {
    "conditioning._encoder._proj_lo.weight": "proj_lo.weight",
    "conditioning._encoder._proj_mid.weight": "proj_mid.weight",
    "conditioning._encoder._proj_hi.weight": "proj_hi.weight",
    "conditioning._encoder._tap_statistics.mean": "tap_mean",
    "conditioning._encoder._tap_statistics.std": "tap_std",
    "conditioning.uncond_token": "uncond_token",
    "conditioning.learned_padding_tokens": "suffix_tokens",
}
# Training checkpoint keys that are not published: each must hold this value.
TEXT_ADAPTER_REQUIRED_FLAGS: dict[str, bool] = {
    "conditioning._encoder._tap_statistics.calibrated": True,
}


class TextAdapter(nn.Module):
    """Tap standardization, the three projections and the learned tokens.

    Projection weights are bf16 (as published); statistics and learned tokens
    stay FP32 across ``.to(dtype)`` moves.
    """

    tap_mean: Tensor
    tap_std: Tensor
    uncond_token: Tensor
    suffix_tokens: Tensor

    def __init__(self) -> None:
        super().__init__()
        hidden = ENCODER_CONFIG.hidden_size
        self.proj_lo = nn.Linear(hidden, TEXT_WIDTH, bias=False, dtype=COMPUTE_DTYPE)
        self.proj_mid = nn.Linear(hidden, TEXT_WIDTH, bias=False, dtype=COMPUTE_DTYPE)
        self.proj_hi = nn.Linear(hidden, TEXT_WIDTH, bias=False, dtype=COMPUTE_DTYPE)
        self.register_buffer("tap_mean", torch.zeros(_TAP_COUNT, hidden))
        self.register_buffer("tap_std", torch.ones(_TAP_COUNT, hidden))
        self.register_buffer("uncond_token", torch.zeros(1, TEXT_WIDTH))
        self.register_buffer(
            "suffix_tokens", torch.zeros(SUFFIX_TOKEN_COUNT, TEXT_WIDTH)
        )

    def _apply(self, fn: Callable[[Tensor], Tensor], recurse: bool = True) -> nn.Module:
        """Apply device moves without rounding the FP32 tensors."""

        kept = {
            name: tensor.detach().float()
            for name, tensor in self.named_buffers(recurse=False)
        }
        super()._apply(fn, recurse=recurse)
        for name, tensor in self.named_buffers(recurse=False):
            tensor.data = kept[name].to(device=tensor.device)
        return self

    def project(self, taps: EncoderTaps) -> Tensor:
        """Return the summed projections ``[B, L, 2304]`` FP32 of three taps.

        Each tap is standardized per channel in FP32; each projection runs
        under bf16 autocast and is summed in FP32.
        """

        total: Tensor | None = None
        projections = (self.proj_lo, self.proj_mid, self.proj_hi)
        tap_values = (taps.low, taps.middle, taps.high)
        device = taps.low.device
        with torch.autocast(device_type=device.type, dtype=COMPUTE_DTYPE):
            for slot, (projection, tap) in enumerate(
                zip(projections, tap_values, strict=True)
            ):
                normalized = (tap.float() - self.tap_mean[slot]) / self.tap_std[slot]
                projected = F.linear(normalized, projection.weight).float()
                total = projected if total is None else total + projected
        if total is None:
            raise RuntimeError("TextAdapter has no projections.")
        return total

    def conditioning_tokens(self, taps: EncoderTaps) -> Tensor:
        """Return ``[B, L + 3, 2304]`` FP32: projected taps, then the suffix."""

        projected = self.project(taps)
        suffix = self.suffix_tokens.float().expand(projected.shape[0], -1, -1)
        return torch.cat((projected, suffix), dim=1)

    def unconditional_tokens(self, batch: int) -> Tensor:
        """Return the null text ``[batch, 4, 2304]`` FP32: unconditional token,
        then the suffix."""

        sequence = torch.cat((self.uncond_token, self.suffix_tokens), dim=0).float()
        return sequence.unsqueeze(0).expand(batch, -1, -1).contiguous()


@dataclass(frozen=True)
class _PreparedPrompt:
    """One prompt ready to encode.

    Attributes:
        ids: Token ids, or None for the null text.
        emphasis: Per-token emphasis over ``ids``, or None.
    """

    ids: tuple[int, ...] | None
    emphasis: TokenEmphasis | None

    @property
    def length(self) -> int:
        """Return the conditioning token count (suffix included)."""

        if self.ids is None:
            return 1 + SUFFIX_TOKEN_COUNT
        return len(self.ids) + SUFFIX_TOKEN_COUNT


@dataclass(frozen=True)
class TextConditioningGroup:
    """Prompts of equal token count and their conditioning.

    Attributes:
        indices: Positions of the group's prompts in the input list.
        conditioning: Their conditioning, rows in ``indices`` order.
    """

    indices: tuple[int, ...]
    conditioning: TextConditioning


class DFlowTextEncoder(nn.Module):
    """Prompts to ``TextConditioning`` with the bundled T5Gemma2 encoder.

    Args:
        tokenizer: The prompt tokenizer.
        encoder: The 12-layer T5Gemma2 encoder.
        adapter: The trained tap projections and learned tokens.
    """

    def __init__(
        self,
        *,
        tokenizer: PromptTokenizer,
        encoder: T5Gemma2Encoder,
        adapter: TextAdapter,
    ) -> None:
        super().__init__()
        self.tokenizer = tokenizer
        self.encoder = encoder
        self.adapter = adapter

    @classmethod
    def from_directory(
        cls, directory: str | Path, *, adapter: TextAdapter, device: torch.device
    ) -> DFlowTextEncoder:
        """Load the tokenizer and encoder of a ``text_encoder/`` folder.

        Args:
            directory: The bundled ``text_encoder/`` folder.
            adapter: The loaded ``text_adapter`` of the model weights.
            device: Execution device.
        """

        return cls(
            tokenizer=PromptTokenizer.from_directory(directory),
            encoder=T5Gemma2Encoder.from_directory(directory, device=device),
            adapter=adapter.to(device=device),
        )

    def compile_layers(self) -> None:
        """Compile the encoder layers (``T5Gemma2Encoder.compile_layers``)."""

        self.encoder.compile_layers()

    def _prepare(
        self, prompt: str, emphasis: EmphasisSettings | None
    ) -> _PreparedPrompt:
        """Tokenize one prompt and map its emphasis onto the tokens.

        Raises:
            ValueError: For a stored (uncompiled) layout.
            PromptTooLongError: If the prompt is too long.
        """

        if not prompt.strip():
            return _PreparedPrompt(ids=None, emphasis=None)
        if is_compiled_layout(prompt):
            if is_stored_layout(prompt):
                raise ValueError(
                    "This is a stored layout; compile it at the image size first "
                    "with dflow.layout.compile_layout(layout, width, height)."
                )
            return _PreparedPrompt(
                ids=self.tokenizer.tokenize(prompt).ids, emphasis=None
            )
        if emphasis is None:
            return _PreparedPrompt(
                ids=self.tokenizer.tokenize(prompt).ids, emphasis=None
            )
        parsed = parse_prompt_weights(prompt)
        tokenized = self.tokenizer.tokenize(parsed.clean_text)
        return _PreparedPrompt(
            ids=tokenized.ids,
            emphasis=token_emphasis(parsed, tokenized.offsets, emphasis),
        )

    def encode(
        self, prompts: Sequence[str], *, emphasis: EmphasisSettings | None
    ) -> TextConditioning:
        """Encode prompts of equal token count as one batch.

        Args:
            prompts: Prompts in batch order: plain text, compiled layout JSON,
                or blank for the null text.
            emphasis: Settings to parse and apply ``(phrase:weight)`` markup
                in plain prompts, or None to encode them verbatim.

        Raises:
            ValueError: If the prompts have different token counts (use
                ``encode_grouped``), the list is empty or a prompt is invalid.
            PromptTooLongError: If a prompt is too long.
        """

        if not prompts:
            raise ValueError("At least one prompt is required.")
        prepared = [self._prepare(prompt, emphasis) for prompt in prompts]
        lengths = sorted({row.length for row in prepared})
        if len(lengths) != 1:
            raise ValueError(
                "Prompts of one batch must have the same token count; got "
                f"{[row.length for row in prepared]}. Use encode_grouped."
            )
        return self._encode_prepared(prepared, emphasis=emphasis)

    def encode_grouped(
        self, prompts: Sequence[str], *, emphasis: EmphasisSettings | None
    ) -> list[TextConditioningGroup]:
        """Encode prompts in groups of equal token count (first-seen order).

        Raises:
            ValueError: If the list is empty or a prompt is invalid.
            PromptTooLongError: If a prompt is too long.
        """

        if not prompts:
            raise ValueError("At least one prompt is required.")
        prepared = [self._prepare(prompt, emphasis) for prompt in prompts]
        groups: dict[int, list[int]] = {}
        for index, row in enumerate(prepared):
            groups.setdefault(row.length, []).append(index)
        return [
            TextConditioningGroup(
                indices=tuple(indices),
                conditioning=self._encode_prepared(
                    [prepared[index] for index in indices], emphasis=emphasis
                ),
            )
            for indices in groups.values()
        ]

    def _device(self) -> torch.device:
        """Return the adapter's device."""

        return self.adapter.uncond_token.device

    @torch.no_grad()
    def _encode_prepared(
        self, prepared: Sequence[_PreparedPrompt], *, emphasis: EmphasisSettings | None
    ) -> TextConditioning:
        """Encode equal-length prepared prompts."""

        device = self._device()
        length = prepared[0].length
        tokens = torch.empty(
            (len(prepared), length, TEXT_WIDTH), device=device, dtype=torch.float32
        )
        null_rows = [pos for pos, row in enumerate(prepared) if row.ids is None]
        text_rows = [pos for pos, row in enumerate(prepared) if row.ids is not None]
        if null_rows:
            tokens[null_rows] = self.adapter.unconditional_tokens(len(null_rows))
        if text_rows:
            rows = [prepared[pos] for pos in text_rows]
            tokens[text_rows] = self._encode_text(rows, emphasis=emphasis)
        key_bias, value_scale = _emphasis_tensors(prepared, device=device)
        return TextConditioning(
            tokens=tokens, key_bias=key_bias, value_scale=value_scale
        )

    def _encode_text(
        self, rows: Sequence[_PreparedPrompt], *, emphasis: EmphasisSettings | None
    ) -> Tensor:
        """Run the encoder and adapter on text rows of equal length."""

        device = self._device()
        ids = torch.tensor(
            [row.ids for row in rows if row.ids is not None],
            dtype=torch.int64,
            device=device,
        )
        weighting = None
        if emphasis is not None and emphasis.encoder:
            key_bias, value_scale = _emphasis_tensors(rows, device=device, suffix=False)
            if key_bias is not None or value_scale is not None:
                weighting = EncoderWeighting(key_bias=key_bias, value_scale=value_scale)
        return self.adapter.conditioning_tokens(self.encoder(ids, weighting=weighting))


def _emphasis_tensors(
    rows: Sequence[_PreparedPrompt], *, device: torch.device, suffix: bool = True
) -> tuple[Tensor | None, Tensor | None]:
    """Return FP32 ``[B, L]`` key bias and value scale, each None if neutral.

    ``suffix`` appends the neutral suffix positions (conditioning tokens);
    without it the rows cover the encoder tokens only.
    """

    if all(row.emphasis is None for row in rows):
        return None, None
    extra = SUFFIX_TOKEN_COUNT if suffix else 0
    biases: list[list[float]] = []
    scales: list[list[float]] = []
    for row in rows:
        width = row.length - SUFFIX_TOKEN_COUNT + extra
        match row.emphasis:
            case TokenEmphasis() as weights:
                biases.append([*weights.key_bias, *([0.0] * extra)])
                scales.append([*weights.value_scale, *([1.0] * extra)])
            case None:
                biases.append([0.0] * width)
                scales.append([1.0] * width)
    has_bias = any(
        row.emphasis is not None and row.emphasis.has_key_bias() for row in rows
    )
    has_scale = any(
        row.emphasis is not None and row.emphasis.has_value_scale() for row in rows
    )
    return (
        torch.tensor(biases, dtype=torch.float32, device=device) if has_bias else None,
        torch.tensor(scales, dtype=torch.float32, device=device) if has_scale else None,
    )