Download dflow/text_conditioning.py from data-archetype/dflow_2b: direct link, hf CLI and curl.
- Browser
- Download file 14.7 kB
-
https://huggingface.co/data-archetype/dflow_2b/resolve/main/dflow/text_conditioning.py
- Command line
-
hf download hf://data-archetype/dflow_2b/dflow/text_conditioning.py
-
curl -L -o text_conditioning.py https://huggingface.co/data-archetype/dflow_2b/resolve/main/dflow/text_conditioning.py
14.7 kB
| """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_uncompiled_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() | |
| 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 | |
| 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 | |
| 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 | |
| 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 layout or MOSS draft (uncompiled). | |
| PromptTooLongError: If the prompt is too long. | |
| """ | |
| if not prompt.strip(): | |
| return _PreparedPrompt(ids=None, emphasis=None) | |
| if is_compiled_layout(prompt): | |
| if is_uncompiled_layout(prompt): | |
| raise ValueError( | |
| "This layout is not compiled; 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 | |
| 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, | |
| ) | |