dflow_2b / dflow /blocks.py
data-archetype's picture
dflow_2b 0.2
6daffc2
Raw History Blame Contribute Delete
10.6 kB
"""The transformer block of the dflow denoiser: dense joint self-attention.
One block class serves the text refiner (unmodulated) and the prefix, middle
and suffix image layers (scale-and-gate AdaLN from the timestep). Every block
is a sandwich-norm residual block::
h = norm2(attention(modulate(norm1(x), s_a)))
x = x + tanh(g_a) * h
h = norm2'(mlp(modulate(norm1'(x), s_m)))
x = x + tanh(g_m) * h
with ``modulate(n, s) = n * (1 + s)`` (no shift); the refiner adds ``h``
directly. Attention is fused-QKV multi-head attention with RMSNorm on queries
and keys, adjacent-pair 3-axis RoPE, and dense scaled-dot-product attention.
Extra attention inputs, all built once per forward outside the blocks:
- ``query_scale``: a 0-dim float32 tensor multiplying the queries after RoPE,
``exp(self-attention logit gain)``; a tensor so a new value reuses the
compiled graph. None leaves the queries unchanged (the text refiner).
- ``key_bias``: an additive ``[B, 1, 1, S]`` attention-logit bias on every
key (prompt emphasis on text keys, zero elsewhere), or None for the
mask-free (flash) path.
- ``value_scale``: a ``[B, 1, S, 1]`` multiplier on every value, or None.
Blocks hold no validation: shapes are checked where the model builds inputs.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Protocol
import torch
import torch.nn.functional as F
from torch import Tensor, nn
if TYPE_CHECKING:
from .configuration import DFlowConfig
class BlockCall(Protocol):
"""The eager or compiled block implementation."""
def __call__(
self,
x: Tensor,
*,
rope_sin: Tensor,
rope_cos: Tensor,
modulation: Tensor | None,
query_scale: Tensor | None,
key_bias: Tensor | None,
value_scale: Tensor | None,
) -> Tensor:
"""Run the block."""
...
class RMSNorm(nn.Module):
"""RMSNorm with an affine weight cast to the input dtype at use.
The output keeps the input dtype (autocast computes the norm in float32
and the result is cast back).
"""
weight: nn.Parameter
width: int
eps: float
def __init__(self, width: int, *, eps: float) -> None:
"""Build a unit-initialised ``[width]`` weight."""
super().__init__()
self.width = width
self.eps = eps
self.weight = nn.Parameter(torch.ones(width))
def forward(self, x: Tensor) -> Tensor:
"""Normalise the last dimension of ``x``."""
out = F.rms_norm(x, (self.width,), self.weight.to(dtype=x.dtype), self.eps)
return out if out.dtype == x.dtype else out.to(dtype=x.dtype)
def _rotate_adjacent_pairs(x: Tensor) -> Tensor:
"""Rotate channel pairs ``(x0, x1) -> (-x1, x0)`` along the last dim."""
pairs = x.reshape(*x.shape[:-1], x.shape[-1] // 2, 2)
return torch.stack((-pairs[..., 1], pairs[..., 0]), dim=-1).reshape_as(x)
def _apply_rope(x: Tensor, sin: Tensor, cos: Tensor) -> Tensor:
"""Rotate ``x`` ``[B, S, H, D]`` by float32 ``sin``/``cos`` ``[B, S, 1, D]``
in float32, returning ``x``'s dtype."""
rotated = x.to(dtype=sin.dtype)
return (rotated * cos + _rotate_adjacent_pairs(rotated) * sin).to(dtype=x.dtype)
class JointSelfAttention(nn.Module):
"""Fused-QKV multi-head self-attention with QK RMSNorm and 3-axis RoPE."""
qkv: nn.Linear
q_norm: RMSNorm
k_norm: RMSNorm
proj_out: nn.Linear
heads: int
head_width: int
def __init__(self, config: DFlowConfig) -> None:
"""Build the bias-free projections and the per-head norms."""
super().__init__()
self.heads = config.heads
self.head_width = config.head_width
self.qkv = nn.Linear(config.width, 3 * config.width, bias=False)
self.q_norm = RMSNorm(config.head_width, eps=config.norm_eps)
self.k_norm = RMSNorm(config.head_width, eps=config.norm_eps)
self.proj_out = nn.Linear(config.width, config.width, bias=False)
def forward(
self,
x: Tensor,
*,
rope_sin: Tensor,
rope_cos: Tensor,
query_scale: Tensor | None,
key_bias: Tensor | None,
value_scale: Tensor | None,
) -> Tensor:
"""Attend over ``x`` ``[B, S, width]``.
Args:
x: Normalised (and modulated) tokens.
rope_sin: ``[B, S, head_width]`` float32.
rope_cos: ``[B, S, head_width]`` float32.
query_scale: 0-dim float32 query multiplier, or None.
key_bias: ``[B, 1, 1, S]`` additive logit bias (query dtype), or None.
value_scale: ``[B, 1, S, 1]`` value multiplier (value dtype), or None.
Returns:
``[B, S, width]`` attention output after the output projection.
"""
batch, length, width = x.shape
qkv = self.qkv(x).view(batch, length, 3, self.heads, self.head_width)
q, k, v = qkv.unbind(2)
sin = rope_sin.unsqueeze(2)
cos = rope_cos.unsqueeze(2)
q = _apply_rope(self.q_norm(q), sin, cos)
k = _apply_rope(self.k_norm(k), sin, cos)
if query_scale is not None:
q = (q.to(dtype=torch.float32) * query_scale).to(dtype=k.dtype)
v = v.transpose(1, 2)
if value_scale is not None:
v = v * value_scale
out = F.scaled_dot_product_attention(
q.transpose(1, 2), k.transpose(1, 2), v, attn_mask=key_bias
)
return self.proj_out(out.transpose(1, 2).reshape(batch, length, width))
class GeluMlp(nn.Module):
"""``down(gelu(up(x)))`` with biases and the exact (erf) GELU."""
up: nn.Linear
down: nn.Linear
def __init__(self, config: DFlowConfig) -> None:
"""Build the two biased projections."""
super().__init__()
self.up = nn.Linear(config.width, config.mlp_hidden_width, bias=True)
self.down = nn.Linear(config.mlp_hidden_width, config.width, bias=True)
def forward(self, x: Tensor) -> Tensor:
"""Apply the MLP to ``[..., width]`` tokens."""
return self.down(F.gelu(self.up(x)))
def _modulate(normed: Tensor, scale: Tensor) -> Tensor:
"""``normed * (1 + scale)`` in float32 with per-sample ``scale`` ``[B, D]``,
returned in ``normed``'s dtype."""
out = normed.to(dtype=torch.float32) * (1.0 + scale.unsqueeze(1))
return out.to(dtype=normed.dtype)
def _gate(gate: Tensor, values: Tensor) -> Tensor:
"""``tanh(gate) * values`` in float32 with per-sample ``gate`` ``[B, D]``,
returned in ``values``' dtype."""
out = torch.tanh(gate).unsqueeze(1) * values.to(dtype=torch.float32)
return out.to(dtype=values.dtype)
class DFlowBlock(nn.Module):
"""One sandwich-norm transformer block (refiner or image layer)."""
attn_norm1: RMSNorm
attn_norm2: RMSNorm
mlp_norm1: RMSNorm
mlp_norm2: RMSNorm
attn: JointSelfAttention
mlp: GeluMlp
_implementation: BlockCall
_compiled: bool
def __init__(self, config: DFlowConfig) -> None:
"""Build the four norms, the attention and the MLP."""
super().__init__()
self.attn_norm1 = RMSNorm(config.width, eps=config.norm_eps)
self.attn_norm2 = RMSNorm(config.width, eps=config.norm_eps)
self.mlp_norm1 = RMSNorm(config.width, eps=config.norm_eps)
self.mlp_norm2 = RMSNorm(config.width, eps=config.norm_eps)
self.attn = JointSelfAttention(config)
self.mlp = GeluMlp(config)
self._implementation = self._forward_impl
self._compiled = False
def forward(
self,
x: Tensor,
*,
rope_sin: Tensor,
rope_cos: Tensor,
modulation: Tensor | None,
query_scale: Tensor | None,
key_bias: Tensor | None,
value_scale: Tensor | None,
) -> Tensor:
"""Run the block, compiled once ``compile_block`` was called.
Args:
x: Residual stream ``[B, S, width]``.
rope_sin: ``[B, S, head_width]`` float32 RoPE sines.
rope_cos: ``[B, S, head_width]`` float32 RoPE cosines.
modulation: Float32 ``[B, 4 * width]`` AdaLN projection, chunked as
(attention scale, attention gate, MLP scale, MLP gate); None for
the unmodulated refiner.
query_scale: See the module docstring.
key_bias: See the module docstring.
value_scale: See the module docstring.
Returns:
The updated residual stream, in ``x``'s dtype.
"""
return self._implementation(
x,
rope_sin=rope_sin,
rope_cos=rope_cos,
modulation=modulation,
query_scale=query_scale,
key_bias=key_bias,
value_scale=value_scale,
)
def compile_block(self, *, dynamic: bool) -> None:
"""Replace the eager implementation by ``torch.compile(fullgraph=True)``.
Compilation happens on the first call; a graph break or compiler
error raises there.
Raises:
RuntimeError: If the block is already compiled.
"""
if self._compiled:
raise RuntimeError("DFlowBlock is already compiled")
self._implementation = torch.compile(
self._forward_impl, fullgraph=True, dynamic=dynamic
)
self._compiled = True
def _forward_impl(
self,
x: Tensor,
*,
rope_sin: Tensor,
rope_cos: Tensor,
modulation: Tensor | None,
query_scale: Tensor | None,
key_bias: Tensor | None,
value_scale: Tensor | None,
) -> Tensor:
"""The block math (see ``forward``)."""
if modulation is None:
h = self.attn(
self.attn_norm1(x),
rope_sin=rope_sin,
rope_cos=rope_cos,
query_scale=query_scale,
key_bias=key_bias,
value_scale=value_scale,
)
x = x + self.attn_norm2(h)
return x + self.mlp_norm2(self.mlp(self.mlp_norm1(x)))
scale_a, gate_a, scale_m, gate_m = modulation.chunk(4, dim=-1)
h = self.attn(
_modulate(self.attn_norm1(x), scale_a),
rope_sin=rope_sin,
rope_cos=rope_cos,
query_scale=query_scale,
key_bias=key_bias,
value_scale=value_scale,
)
x = x + _gate(gate_a, self.attn_norm2(h))
h = self.mlp(_modulate(self.mlp_norm1(x), scale_m))
return x + _gate(gate_m, self.mlp_norm2(h))