Spaces:
Running on Zero
Running on Zero
Download dflow/modeling.py from hugging-apps/dflow-2b: direct link, hf CLI and curl.
- Browser
- Download file 31 kB
-
https://huggingface.co/spaces/hugging-apps/dflow-2b/resolve/main/dflow/modeling.py
- Command line
-
hf download hf://spaces/hugging-apps/dflow-2b/dflow/modeling.py
-
curl -L -o modeling.py https://huggingface.co/spaces/hugging-apps/dflow-2b/resolve/main/dflow/modeling.py
31 kB
| """The dflow_2b denoiser: a single-stream text-image flow-matching transformer. | |
| Time and velocity convention | |
| ---------------------------- | |
| The model is trained on the linear path | |
| x_t = (1 - t) * x_0 + t * eps, eps ~ N(0, I), t in [0, 1], | |
| where ``x_0`` is a whitened dinac3_96 latent: ``t = 1`` is pure noise and | |
| ``t = 0`` is data. ``forward`` returns the velocity | |
| v = dx_t / dt = eps - x_0, | |
| so an Euler step towards data is ``x_{t - h} = x_t - h * v``. The timestep | |
| enters as a float32 ``t`` in ``[0, 1]``; the time embedding reads | |
| ``sin``/``cos`` of ``1000 * t * f_k`` (128 log-spaced frequencies ``f_k`` | |
| from 1 to 1/10000). Log-SNR shifts and schedules are the sampler's business: | |
| the model takes the plain ``t`` of the path above. | |
| Stream and routing | |
| ------------------ | |
| Each sample is one sequence ``[image tokens, text tokens]`` (row-major | |
| ``H x W`` latent grid, then the ``L`` refined prompt tokens) with joint | |
| self-attention in every layer. The text goes through two unmodulated refiner | |
| blocks once per prompt (``prepare_text``); it does not depend on the image | |
| size or the timestep, so one ``PreparedText`` serves every sampling step and | |
| size. Image layers: 6 prefix, 18 middle, a tail join, 6 suffix. ``DFlowPath`` | |
| picks what the middle sees (``DFlowPath`` docstring); the tail join | |
| concatenates the prefix output ``p`` with the middle output ``m`` (the learned | |
| mask token where the middle did not run), scales both halves by ``1 + s(t)``, | |
| projects back to the width, and adds a separate projection of the scaled | |
| prefix at the rows the middle skipped. | |
| Precision | |
| --------- | |
| Weights are bfloat16 with float32 norm weights and velocity head. Both entry | |
| points run under CUDA bfloat16 autocast and ``torch.no_grad``. The text | |
| refiner keeps a float32 residual stream (its input is float32); the joint | |
| stream is bfloat16. Norm weights and the velocity head are cast to their | |
| input's dtype at use, as in training under autocast. AdaLN scales and gates, | |
| RoPE and the returned velocity are float32. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from dataclasses import dataclass, replace | |
| from typing import TYPE_CHECKING | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import Tensor, nn | |
| from .blocks import DFlowBlock, RMSNorm | |
| from .rope3d import joint_rope_rows, text_rope_rows, validate_rope_capacity | |
| from .types import SUFFIX_TOKEN_COUNT, DFlowPath, TextConditioning | |
| if TYPE_CHECKING: | |
| from .configuration import DFlowConfig | |
| AUTOCAST_DTYPE = torch.bfloat16 | |
| SELF_ATTENTION_GAIN_RANGE = (-0.5, 0.1) | |
| """Supported self-attention logit gains (inclusive).""" | |
| class PreparedText: | |
| """A prompt batch after the text refiner, reusable across steps and sizes. | |
| Attributes: | |
| tokens: ``[B, L, width]`` refined tokens (float32). | |
| key_bias: ``[B, L]`` float32 prompt-emphasis key bias, or None. | |
| value_scale: ``[B, L]`` float32 prompt-emphasis value scale, or None. | |
| """ | |
| tokens: Tensor | |
| key_bias: Tensor | None | |
| value_scale: Tensor | None | |
| def length(self) -> int: | |
| """Tokens per prompt ``L``.""" | |
| return int(self.tokens.shape[1]) | |
| def self_attention_gain_tensor(gain: float, *, device: torch.device) -> Tensor: | |
| """The 0-dim float32 tensor ``forward`` takes as ``self_attention_gain``. | |
| The gain ``g`` multiplies the image layers' queries by ``exp(g)`` (an | |
| attention-logit temperature); 0 leaves the model unchanged. | |
| Raises: | |
| ValueError: If ``gain`` is not finite or outside | |
| ``SELF_ATTENTION_GAIN_RANGE``. | |
| """ | |
| low, high = SELF_ATTENTION_GAIN_RANGE | |
| if not math.isfinite(gain) or not low <= gain <= high: | |
| raise ValueError( | |
| f"self-attention gain must be finite and within [{low}, {high}], got {gain}" | |
| ) | |
| return torch.tensor(gain, dtype=torch.float32, device=device) | |
| class TimeEmbedding(nn.Module): | |
| """Sinusoidal timestep features through a SiLU MLP to the AdaLN width.""" | |
| proj_in: nn.Linear | |
| proj_out: nn.Linear | |
| frequency_width: int | |
| time_scale: float | |
| max_period: float | |
| def __init__(self, config: DFlowConfig) -> None: | |
| """Build the two projections.""" | |
| super().__init__() | |
| self.frequency_width = config.time_frequency_width | |
| self.time_scale = config.time_scale | |
| self.max_period = config.time_max_period | |
| self.proj_in = nn.Linear(config.time_frequency_width, config.time_hidden_width) | |
| self.proj_out = nn.Linear(config.time_hidden_width, config.time_embed_width) | |
| def forward(self, t: Tensor) -> Tensor: | |
| """Embed float32 ``t`` ``[B]`` into ``[B, time_embed_width]``.""" | |
| half = self.frequency_width // 2 | |
| freqs = torch.exp( | |
| -math.log(self.max_period) | |
| * torch.arange(half, device=t.device, dtype=torch.float32) | |
| / max(float(half - 1), 1.0) | |
| ) | |
| angles = (t.to(dtype=torch.float32) * self.time_scale)[:, None] * freqs[None] | |
| features = torch.cat([torch.sin(angles), torch.cos(angles)], dim=-1) | |
| hidden = F.silu(self.proj_in(features.to(dtype=self.proj_in.weight.dtype))) | |
| return self.proj_out(hidden.to(dtype=self.proj_out.weight.dtype)) | |
| class TailJoin(nn.Module): | |
| """Concat join of the prefix and middle streams with time-dependent gains.""" | |
| mask_token: nn.Parameter | |
| adascale: nn.Linear | |
| proj: nn.Linear | |
| dropped_skip_proj: nn.Linear | |
| def __init__(self, config: DFlowConfig) -> None: | |
| """Build the mask token and the three projections.""" | |
| super().__init__() | |
| self.mask_token = nn.Parameter(torch.zeros(1, config.width)) | |
| self.adascale = nn.Linear(config.time_embed_width, 2 * config.width) | |
| self.proj = nn.Linear(2 * config.width, config.width) | |
| self.dropped_skip_proj = nn.Linear(config.width, config.width, bias=False) | |
| def forward( | |
| self, | |
| prefix: Tensor, | |
| middle: Tensor, | |
| dropped: Tensor | None, | |
| time_act: Tensor, | |
| ) -> Tensor: | |
| """Fuse ``[B, S, D]`` streams: ``W [g_p p ; g_m m] + b`` with | |
| ``g = 1 + s(t)``, plus ``dropped * dropped_skip_proj(g_p p)``. | |
| Args: | |
| prefix: Prefix output. | |
| middle: Middle output, the mask token where the middle did not run. | |
| dropped: ``[B, S, 1]`` 1 at rows the middle skipped and 0 elsewhere; | |
| None when the middle ran on every row. | |
| time_act: SiLU of the timestep vector ``[B, time_embed_width]``. | |
| """ | |
| batch, length, width = prefix.shape | |
| concat = torch.cat([prefix, middle], dim=-1) | |
| scale = self.adascale(time_act).to(dtype=torch.float32) | |
| scaled = concat.to(dtype=torch.float32) * (1.0 + scale[:, None, :]) | |
| # Row-major [B * S, 2D] matrices: the projections see the token rows | |
| # exactly as the trained model's packed stream does. | |
| rows = scaled.to(dtype=concat.dtype).reshape(batch * length, 2 * width) | |
| fused = self.proj(rows) | |
| if dropped is not None: | |
| fused = fused + dropped.reshape(batch * length, 1) * self.dropped_skip_proj( | |
| rows[:, :width] | |
| ) | |
| return fused.reshape(batch, length, width) | |
| class _StreamInputs: | |
| """Per-forward inputs shared by every image layer.""" | |
| rope_sin: Tensor | |
| rope_cos: Tensor | |
| query_scale: Tensor | |
| key_bias: Tensor | None | |
| value_scale: Tensor | None | |
| time_act: Tensor | |
| class DFlowModel(nn.Module): | |
| """The denoiser (see the module docstring for conventions).""" | |
| config: DFlowConfig | |
| patch_embed: nn.Conv2d | |
| time_embed: TimeEmbedding | |
| text_refiner_layers: nn.ModuleList | |
| prefix_layers: nn.ModuleList | |
| middle_layers: nn.ModuleList | |
| suffix_layers: nn.ModuleList | |
| prefix_adaln: nn.ModuleList | |
| middle_adaln: nn.ModuleList | |
| suffix_adaln: nn.ModuleList | |
| tail_join: TailJoin | |
| final_norm: RMSNorm | |
| final_modulation: nn.Linear | |
| velocity_head: nn.Linear | |
| def __init__(self, config: DFlowConfig) -> None: | |
| """Build every module of ``config`` (weights are loaded separately).""" | |
| super().__init__() | |
| self.config = config | |
| self.patch_embed = nn.Conv2d(config.latent_channels, config.width, 1) | |
| self.time_embed = TimeEmbedding(config) | |
| self.text_refiner_layers = _blocks(config, config.text_refiner_depth) | |
| self.prefix_layers = _blocks(config, config.prefix_depth) | |
| self.middle_layers = _blocks(config, config.middle_depth) | |
| self.suffix_layers = _blocks(config, config.suffix_depth) | |
| self.prefix_adaln = _adaln(config, config.prefix_depth) | |
| self.middle_adaln = _adaln(config, config.middle_depth) | |
| self.suffix_adaln = _adaln(config, config.suffix_depth) | |
| self.tail_join = TailJoin(config) | |
| self.final_norm = RMSNorm(config.width, eps=config.norm_eps) | |
| self.final_modulation = nn.Linear(config.time_embed_width, 2 * config.width) | |
| self.velocity_head = nn.Linear(config.width, config.latent_channels) | |
| def compile_blocks(self, *, dynamic: bool) -> None: | |
| """Compile every transformer block with ``torch.compile(fullgraph=True)``. | |
| Graphs build on first use; a graph break or compiler error raises | |
| then. Path, gain value and emphasis tensors stay outside the graphs. | |
| Raises: | |
| RuntimeError: If Dynamo is set to suppress errors, or a block is | |
| already compiled. | |
| """ | |
| if torch._dynamo.config.suppress_errors: | |
| raise RuntimeError( | |
| "torch._dynamo.config.suppress_errors is set: dflow compiles with " | |
| "errors raised, never with an eager fallback" | |
| ) | |
| for layers in ( | |
| self.text_refiner_layers, | |
| self.prefix_layers, | |
| self.middle_layers, | |
| self.suffix_layers, | |
| ): | |
| for block in _block_list(layers): | |
| block.compile_block(dynamic=dynamic) | |
| def prepare_text(self, text: TextConditioning) -> PreparedText: | |
| """Run the text refiner once for a prompt batch. | |
| Args: | |
| text: Encoder tokens ``[B, L, width]`` float32 and optional | |
| emphasis tensors ``[B, L]`` float32, on the model's device. | |
| Returns: | |
| The refined tokens with the emphasis tensors carried along. | |
| Raises: | |
| ValueError: For wrong shapes, dtypes or devices, or a prompt too | |
| long for the RoPE capacity. | |
| """ | |
| self._validate_text(text) | |
| batch, length, _ = text.tokens.shape | |
| validate_rope_capacity( | |
| self.config, text_length=length, grid_height=1, grid_width=1 | |
| ) | |
| device = text.tokens.device | |
| sin, cos = text_rope_rows(self.config, length, device=device) | |
| key_bias = _key_bias(text.key_bias, dtype=AUTOCAST_DTYPE) | |
| value_scale = _value_scale(text.value_scale, dtype=AUTOCAST_DTYPE) | |
| rope_sin = _batched(sin, batch) | |
| rope_cos = _batched(cos, batch) | |
| x = _owned(text.tokens) | |
| with torch.autocast(device_type=device.type, dtype=AUTOCAST_DTYPE): | |
| for block in _block_list(self.text_refiner_layers): | |
| x = block( | |
| x, | |
| rope_sin=rope_sin, | |
| rope_cos=rope_cos, | |
| modulation=None, | |
| query_scale=None, | |
| key_bias=key_bias, | |
| value_scale=value_scale, | |
| ) | |
| return PreparedText( | |
| tokens=x, key_bias=text.key_bias, value_scale=text.value_scale | |
| ) | |
| def forward( | |
| self, | |
| latents: Tensor, | |
| timestep: Tensor, | |
| prepared: PreparedText, | |
| *, | |
| path: DFlowPath, | |
| self_attention_gain: Tensor, | |
| suffix_caption_bias: float, | |
| generator: torch.Generator | None, | |
| ) -> Tensor: | |
| """Predict the velocity ``eps - x_0`` at ``(x_t, t)``. | |
| Args: | |
| latents: ``x_t`` ``[B, 96, H, W]`` float32 (whitened latent grid). | |
| timestep: ``t`` ``[B]`` float32 in ``[0, 1]`` (1 = noise). | |
| prepared: ``prepare_text`` output with batch ``B``. | |
| path: Middle routing (``DFlowPath``). | |
| self_attention_gain: 0-dim float32 tensor on the latents' device | |
| (``self_attention_gain_tensor``); scales the image layers' | |
| queries by ``exp(gain)``, never the refiner's. | |
| suffix_caption_bias: Additive attention-logit bias on the prompt's | |
| token keys (every text row but the learned suffix) in the six | |
| suffix layers, for every query; 0 for none. The PDG reference | |
| forward uses it (``PdgGuidance.suffix_caption_bias``). | |
| generator: For ``THREE_QUARTER``, the CUDA generator that picks the | |
| one kept token of each 2x2 group (uniformly, per sample and | |
| step); it draws exactly what the training code | |
| draws, so a generator seeded alike keeps the same tokens. | |
| None for the other paths. | |
| Returns: | |
| Velocity ``[B, 96, H, W]`` float32. | |
| Raises: | |
| ValueError: For inconsistent shapes, dtypes or devices, a grid | |
| beyond the RoPE capacity, an odd grid side with | |
| ``THREE_QUARTER``, a generator given or missing for the | |
| path, or a non-finite suffix caption bias. | |
| """ | |
| self._validate_forward( | |
| latents, | |
| timestep, | |
| prepared, | |
| path=path, | |
| self_attention_gain=self_attention_gain, | |
| suffix_caption_bias=suffix_caption_bias, | |
| generator=generator, | |
| ) | |
| with torch.autocast(device_type=latents.device.type, dtype=AUTOCAST_DTYPE): | |
| return self._velocity( | |
| latents, | |
| timestep, | |
| prepared, | |
| path=path, | |
| self_attention_gain=self_attention_gain, | |
| suffix_caption_bias=suffix_caption_bias, | |
| generator=generator, | |
| ) | |
| def _velocity( | |
| self, | |
| latents: Tensor, | |
| timestep: Tensor, | |
| prepared: PreparedText, | |
| *, | |
| path: DFlowPath, | |
| self_attention_gain: Tensor, | |
| suffix_caption_bias: float, | |
| generator: torch.Generator | None, | |
| ) -> Tensor: | |
| """``forward`` after validation, inside autocast.""" | |
| batch, _, grid_height, grid_width = latents.shape | |
| image = self.patch_embed(latents).flatten(2).transpose(1, 2) | |
| image_count = int(image.shape[1]) | |
| x = torch.cat([image, prepared.tokens.to(dtype=image.dtype)], dim=1) | |
| sin, cos = joint_rope_rows( | |
| self.config, | |
| text_length=prepared.length, | |
| grid_height=grid_height, | |
| grid_width=grid_width, | |
| device=latents.device, | |
| ) | |
| time_act = F.silu(self.time_embed(timestep)) | |
| stream = _StreamInputs( | |
| rope_sin=_batched(sin, batch), | |
| rope_cos=_batched(cos, batch), | |
| query_scale=torch.exp(self_attention_gain.to(dtype=torch.float64)).to( | |
| dtype=torch.float32 | |
| ), | |
| key_bias=_key_bias( | |
| _pad_image_rows(prepared.key_bias, image_count, fill=0.0), | |
| dtype=x.dtype, | |
| ), | |
| value_scale=_value_scale( | |
| _pad_image_rows(prepared.value_scale, image_count, fill=1.0), | |
| dtype=x.dtype, | |
| ), | |
| time_act=time_act, | |
| ) | |
| x = self._run_layers(x, self.prefix_layers, self.prefix_adaln, stream) | |
| x = self._middle_and_join( | |
| x, | |
| stream, | |
| path=path, | |
| grid=(grid_height, grid_width), | |
| image_count=image_count, | |
| generator=generator, | |
| ) | |
| suffix_stream = ( | |
| stream | |
| if suffix_caption_bias == 0.0 | |
| else _with_caption_key_bias( | |
| stream, | |
| bias=suffix_caption_bias, | |
| image_count=image_count, | |
| text_length=prepared.length, | |
| batch=batch, | |
| dtype=x.dtype, | |
| ) | |
| ) | |
| x = self._run_layers(x, self.suffix_layers, self.suffix_adaln, suffix_stream) | |
| return self._final_layer(x[:, :image_count], time_act, grid_height, grid_width) | |
| def _middle_and_join( | |
| self, | |
| prefix: Tensor, | |
| stream: _StreamInputs, | |
| *, | |
| path: DFlowPath, | |
| grid: tuple[int, int], | |
| image_count: int, | |
| generator: torch.Generator | None, | |
| ) -> Tensor: | |
| """Run ``path``'s middle on the prefix output and fuse it in the tail join.""" | |
| mask = self.tail_join.mask_token.to(dtype=prefix.dtype).expand_as(prefix) | |
| match path: | |
| case DFlowPath.FULL: | |
| middle = self._run_layers( | |
| prefix, self.middle_layers, self.middle_adaln, stream | |
| ) | |
| return self.tail_join(prefix, middle, None, stream.time_act) | |
| case DFlowPath.PATH_DROP: | |
| dropped = prefix.new_ones(prefix.shape[0], prefix.shape[1], 1) | |
| return self.tail_join(prefix, mask, dropped, stream.time_act) | |
| case DFlowPath.THREE_QUARTER: | |
| if generator is None: | |
| raise ValueError("THREE_QUARTER needs a generator") | |
| rows = three_quarter_middle_rows( | |
| grid=grid, | |
| image_count=image_count, | |
| text_length=prefix.shape[1] - image_count, | |
| batch=prefix.shape[0], | |
| generator=generator, | |
| device=prefix.device, | |
| ) | |
| kept = self._run_layers( | |
| _gather_rows(prefix, rows), | |
| self.middle_layers, | |
| self.middle_adaln, | |
| _gather_stream(stream, rows), | |
| ) | |
| middle = mask.contiguous().scatter( | |
| 1, _row_index(rows, prefix.shape[-1]), kept | |
| ) | |
| dropped = prefix.new_ones(prefix.shape[0], prefix.shape[1], 1).scatter( | |
| 1, rows.unsqueeze(-1), prefix.new_zeros((*rows.shape, 1)) | |
| ) | |
| return self.tail_join(prefix, middle, dropped, stream.time_act) | |
| case _ as unsupported: | |
| raise ValueError(f"Unsupported DFlowPath: {unsupported}") | |
| def _run_layers( | |
| x: Tensor, layers: nn.ModuleList, adaln: nn.ModuleList, stream: _StreamInputs | |
| ) -> Tensor: | |
| """Run modulated image ``layers`` with their AdaLN projections.""" | |
| for block, projection in zip( | |
| _block_list(layers), _linear_list(adaln), strict=True | |
| ): | |
| x = block( | |
| x, | |
| rope_sin=stream.rope_sin, | |
| rope_cos=stream.rope_cos, | |
| modulation=projection(stream.time_act).to(dtype=torch.float32), | |
| query_scale=stream.query_scale, | |
| key_bias=stream.key_bias, | |
| value_scale=stream.value_scale, | |
| ) | |
| return x | |
| def _final_layer( | |
| self, image: Tensor, time_act: Tensor, grid_height: int, grid_width: int | |
| ) -> Tensor: | |
| """Final norm, timestep shift/scale and the velocity head, as a | |
| float32 ``[B, C, H, W]`` grid.""" | |
| normed = self.final_norm(image) | |
| shift, scale = ( | |
| self.final_modulation(time_act).to(dtype=torch.float32).chunk(2, dim=-1) | |
| ) | |
| out = normed.to(dtype=torch.float32) * (1.0 + scale.unsqueeze(1)) | |
| out = (out + shift.unsqueeze(1)).to(dtype=normed.dtype) | |
| velocity = F.linear( | |
| out, | |
| self.velocity_head.weight.to(dtype=out.dtype), | |
| self.velocity_head.bias.to(dtype=out.dtype), | |
| ).to(dtype=torch.float32) | |
| batch = velocity.shape[0] | |
| return velocity.transpose(1, 2).reshape( | |
| batch, self.config.latent_channels, grid_height, grid_width | |
| ) | |
| def _validate_text(self, text: TextConditioning) -> None: | |
| """Check ``TextConditioning`` shapes, dtypes and device. | |
| Raises: | |
| ValueError: On any mismatch. | |
| """ | |
| tokens = text.tokens | |
| if tokens.dim() != 3 or tokens.shape[2] != self.config.width: | |
| raise ValueError( | |
| f"text tokens must be [B, L, {self.config.width}], got " | |
| f"{tuple(tokens.shape)}" | |
| ) | |
| if tokens.dtype != torch.float32: | |
| raise ValueError(f"text tokens must be float32, got {tokens.dtype}") | |
| if tokens.device != self.patch_embed.weight.device: | |
| raise ValueError( | |
| f"text tokens are on {tokens.device}; the model is on " | |
| f"{self.patch_embed.weight.device}" | |
| ) | |
| for name, values in ( | |
| ("key_bias", text.key_bias), | |
| ("value_scale", text.value_scale), | |
| ): | |
| if values is None: | |
| continue | |
| if values.shape != tokens.shape[:2] or values.dtype != torch.float32: | |
| raise ValueError( | |
| f"text {name} must be float32 {tuple(tokens.shape[:2])}, got " | |
| f"{values.dtype} {tuple(values.shape)}" | |
| ) | |
| if values.device != tokens.device: | |
| raise ValueError(f"text {name} must be on the tokens' device") | |
| def _validate_forward( | |
| self, | |
| latents: Tensor, | |
| timestep: Tensor, | |
| prepared: PreparedText, | |
| *, | |
| path: DFlowPath, | |
| self_attention_gain: Tensor, | |
| suffix_caption_bias: float, | |
| generator: torch.Generator | None, | |
| ) -> None: | |
| """Check ``forward``'s inputs (host-side metadata only, no device reads). | |
| Raises: | |
| ValueError: On any mismatch (see ``forward``). | |
| """ | |
| config = self.config | |
| if not math.isfinite(suffix_caption_bias): | |
| raise ValueError( | |
| f"suffix_caption_bias must be finite, got {suffix_caption_bias}" | |
| ) | |
| if latents.dim() != 4 or latents.shape[1] != config.latent_channels: | |
| raise ValueError( | |
| f"latents must be [B, {config.latent_channels}, H, W], got " | |
| f"{tuple(latents.shape)}" | |
| ) | |
| batch, _, grid_height, grid_width = latents.shape | |
| device = self.patch_embed.weight.device | |
| expected = { | |
| "latents": ( | |
| latents, | |
| (batch, config.latent_channels, grid_height, grid_width), | |
| ), | |
| "timestep": (timestep, (batch,)), | |
| "prepared tokens": ( | |
| prepared.tokens, | |
| (batch, prepared.length, config.width), | |
| ), | |
| "self_attention_gain": (self_attention_gain, ()), | |
| } | |
| for name, (tensor, shape) in expected.items(): | |
| if tuple(tensor.shape) != shape or tensor.dtype != torch.float32: | |
| raise ValueError( | |
| f"{name} must be float32 {shape}, got {tensor.dtype} " | |
| f"{tuple(tensor.shape)}" | |
| ) | |
| if tensor.device != device: | |
| raise ValueError( | |
| f"{name} is on {tensor.device}; the model is on {device}" | |
| ) | |
| validate_rope_capacity( | |
| config, | |
| text_length=prepared.length, | |
| grid_height=grid_height, | |
| grid_width=grid_width, | |
| ) | |
| match path: | |
| case DFlowPath.THREE_QUARTER: | |
| if generator is None or not _generator_on(generator, device): | |
| raise ValueError( | |
| f"THREE_QUARTER needs a torch.Generator on {device}" | |
| ) | |
| if grid_height % 2 or grid_width % 2: | |
| raise ValueError( | |
| "THREE_QUARTER needs even token-grid sides, got " | |
| f"{grid_height}x{grid_width}" | |
| ) | |
| case DFlowPath.FULL | DFlowPath.PATH_DROP: | |
| if generator is not None: | |
| raise ValueError(f"{path} draws nothing: pass generator=None") | |
| case _ as unsupported: | |
| raise ValueError(f"Unsupported DFlowPath: {unsupported}") | |
| def three_quarter_middle_rows( | |
| *, | |
| grid: tuple[int, int], | |
| image_count: int, | |
| text_length: int, | |
| batch: int, | |
| generator: torch.Generator, | |
| device: torch.device, | |
| ) -> Tensor: | |
| """Stream rows ``[B, H * W / 4 + L]`` the THREE_QUARTER middle runs on. | |
| One uniformly drawn token of every 2x2 group of the row-major ``H x W`` | |
| grid (groups in raster order), then every text row. After the group | |
| choice it draws (and discards) one float64 uniform per text token, as the | |
| training code does for its all-kept text subset, so a shared | |
| generator advances identically. | |
| """ | |
| grid_height, grid_width = grid | |
| group_y = torch.arange(grid_height // 2, device=device, dtype=torch.int64) | |
| group_x = torch.arange(grid_width // 2, device=device, dtype=torch.int64) | |
| base = (2 * group_y.view(-1, 1) * grid_width + 2 * group_x.view(1, -1)).reshape( | |
| -1, 1 | |
| ) | |
| slot = torch.arange(4, device=device, dtype=torch.int64) | |
| groups = base + (slot % 2 + (slot // 2) * grid_width).view(1, 4) | |
| choice = torch.randint( | |
| 0, 4, (batch, groups.shape[0]), device=device, generator=generator | |
| ) | |
| kept = groups.unsqueeze(0).expand(batch, -1, -1).gather(2, choice.unsqueeze(-1)) | |
| torch.rand( | |
| (batch * text_length,), device=device, dtype=torch.float64, generator=generator | |
| ) | |
| text = image_count + torch.arange(text_length, device=device, dtype=torch.int64) | |
| return torch.cat([kept.squeeze(-1), text.expand(batch, -1)], dim=1) | |
| def _generator_on(generator: torch.Generator, device: torch.device) -> bool: | |
| """Whether ``generator`` draws on ``device`` (an index-less generator | |
| device means the current device of its type).""" | |
| found = generator.device | |
| if found.type != device.type: | |
| return False | |
| if found.index is None or device.index is None: | |
| return found.index is None and ( | |
| device.index is None or device.index == torch.cuda.current_device() | |
| ) | |
| return found.index == device.index | |
| def _row_index(rows: Tensor, width: int) -> Tensor: | |
| """``rows`` ``[B, K]`` expanded to gather/scatter ``[B, K, width]``.""" | |
| return rows.unsqueeze(-1).expand(-1, -1, width) | |
| def _gather_rows(values: Tensor, rows: Tensor) -> Tensor: | |
| """Rows ``[B, K, D]`` of ``values`` ``[B, S, D]``.""" | |
| return values.gather(1, _row_index(rows, values.shape[-1])) | |
| def _gather_stream(stream: _StreamInputs, rows: Tensor) -> _StreamInputs: | |
| """``stream`` restricted to ``rows`` ``[B, K]``.""" | |
| batch, count = rows.shape | |
| return _StreamInputs( | |
| rope_sin=_gather_rows(stream.rope_sin, rows), | |
| rope_cos=_gather_rows(stream.rope_cos, rows), | |
| query_scale=stream.query_scale, | |
| key_bias=None | |
| if stream.key_bias is None | |
| else stream.key_bias.gather(3, rows.view(batch, 1, 1, count)), | |
| value_scale=None | |
| if stream.value_scale is None | |
| else stream.value_scale.gather(2, rows.view(batch, 1, count, 1)), | |
| time_act=stream.time_act, | |
| ) | |
| def _with_caption_key_bias( | |
| stream: _StreamInputs, | |
| *, | |
| bias: float, | |
| image_count: int, | |
| text_length: int, | |
| batch: int, | |
| dtype: torch.dtype, | |
| ) -> _StreamInputs: | |
| """``stream`` with ``bias`` added to the key bias of the prompt's token | |
| rows: the ``text_length - SUFFIX_TOKEN_COUNT`` rows after the image rows | |
| (the learned suffix rows keep their bias).""" | |
| caption = torch.zeros( | |
| (batch, image_count + text_length), dtype=dtype, device=stream.time_act.device | |
| ) | |
| caption[:, image_count : image_count + text_length - SUFFIX_TOKEN_COUNT] = bias | |
| added = caption[:, None, None, :] | |
| key_bias = added if stream.key_bias is None else stream.key_bias + added | |
| return replace(stream, key_bias=_owned(key_bias)) | |
| def _pad_image_rows( | |
| values: Tensor | None, image_count: int, *, fill: float | |
| ) -> Tensor | None: | |
| """``[B, L]`` text values prefixed by ``fill`` for ``image_count`` image rows.""" | |
| if values is None: | |
| return None | |
| pad = values.new_full((values.shape[0], image_count), fill) | |
| return torch.cat([pad, values], dim=1) | |
| def _key_bias(values: Tensor | None, *, dtype: torch.dtype) -> Tensor | None: | |
| """``[B, S]`` key bias as an additive SDPA mask ``[B, 1, 1, S]``.""" | |
| if values is None: | |
| return None | |
| return _owned(values.to(dtype=dtype)[:, None, None, :]) | |
| def _value_scale(values: Tensor | None, *, dtype: torch.dtype) -> Tensor | None: | |
| """``[B, S]`` value scale as ``[B, 1, S, 1]``.""" | |
| if values is None: | |
| return None | |
| return _owned(values.to(dtype=dtype)[:, None, :, None]) | |
| def _owned(values: Tensor) -> Tensor: | |
| """A contiguous copy of ``values`` that is not a view. | |
| Compiled blocks guard on whether an input is a view, so every block input | |
| is built as an owned tensor: one graph serves every call site. | |
| """ | |
| return values.clone(memory_format=torch.contiguous_format) | |
| def _batched(rows: Tensor, batch: int) -> Tensor: | |
| """``[N, D]`` rows repeated over a batch as an owned ``[B, N, D]`` tensor.""" | |
| return _owned(rows.unsqueeze(0).expand(batch, -1, -1)) | |
| def _blocks(config: DFlowConfig, count: int) -> nn.ModuleList: | |
| """``count`` transformer blocks.""" | |
| return nn.ModuleList(DFlowBlock(config) for _ in range(count)) | |
| def _adaln(config: DFlowConfig, count: int) -> nn.ModuleList: | |
| """``count`` AdaLN projections ``time_embed_width -> 4 * width``.""" | |
| return nn.ModuleList( | |
| nn.Linear(config.time_embed_width, 4 * config.width) for _ in range(count) | |
| ) | |
| def _block_list(layers: nn.ModuleList) -> list[DFlowBlock]: | |
| """The blocks of ``layers``, typed. | |
| Raises: | |
| TypeError: If an entry is not a DFlowBlock. | |
| """ | |
| blocks: list[DFlowBlock] = [] | |
| for layer in layers: | |
| match layer: | |
| case DFlowBlock() as block: | |
| blocks.append(block) | |
| case _ as other: | |
| raise TypeError(f"expected DFlowBlock, got {type(other).__name__}") | |
| return blocks | |
| def _linear_list(layers: nn.ModuleList) -> list[nn.Linear]: | |
| """The linears of ``layers``, typed. | |
| Raises: | |
| TypeError: If an entry is not an nn.Linear. | |
| """ | |
| linears: list[nn.Linear] = [] | |
| for layer in layers: | |
| match layer: | |
| case nn.Linear() as linear: | |
| linears.append(linear) | |
| case _ as other: | |
| raise TypeError(f"expected nn.Linear, got {type(other).__name__}") | |
| return linears | |