File size: 10,571 Bytes
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
"""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))