r""" Transformer block introduced in [Sana](https://huggingface.co/papers/2410.10629).
| 191 | |
| 192 | |
| 193 | class SanaTransformerBlock(nn.Module): |
| 194 | r""" |
| 195 | Transformer block introduced in [Sana](https://huggingface.co/papers/2410.10629). |
| 196 | """ |
| 197 | |
| 198 | def __init__( |
| 199 | self, |
| 200 | dim: int = 2240, |
| 201 | num_attention_heads: int = 70, |
| 202 | attention_head_dim: int = 32, |
| 203 | dropout: float = 0.0, |
| 204 | num_cross_attention_heads: Optional[int] = 20, |
| 205 | cross_attention_head_dim: Optional[int] = 112, |
| 206 | cross_attention_dim: Optional[int] = 2240, |
| 207 | attention_bias: bool = True, |
| 208 | norm_elementwise_affine: bool = False, |
| 209 | norm_eps: float = 1e-6, |
| 210 | attention_out_bias: bool = True, |
| 211 | mlp_ratio: float = 2.5, |
| 212 | qk_norm: Optional[str] = None, |
| 213 | ) -> None: |
| 214 | super().__init__() |
| 215 | |
| 216 | # 1. Self Attention |
| 217 | self.norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=norm_eps) |
| 218 | self.attn1 = Attention( |
| 219 | query_dim=dim, |
| 220 | heads=num_attention_heads, |
| 221 | dim_head=attention_head_dim, |
| 222 | kv_heads=num_attention_heads if qk_norm is not None else None, |
| 223 | qk_norm=qk_norm, |
| 224 | dropout=dropout, |
| 225 | bias=attention_bias, |
| 226 | cross_attention_dim=None, |
| 227 | processor=SanaLinearAttnProcessor2_0(), |
| 228 | ) |
| 229 | |
| 230 | # 2. Cross Attention |
| 231 | if cross_attention_dim is not None: |
| 232 | self.norm2 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps) |
| 233 | self.attn2 = Attention( |
| 234 | query_dim=dim, |
| 235 | qk_norm=qk_norm, |
| 236 | kv_heads=num_cross_attention_heads if qk_norm is not None else None, |
| 237 | cross_attention_dim=cross_attention_dim, |
| 238 | heads=num_cross_attention_heads, |
| 239 | dim_head=cross_attention_head_dim, |
| 240 | dropout=dropout, |
| 241 | bias=True, |
| 242 | out_bias=attention_out_bias, |
| 243 | processor=SanaAttnProcessor2_0(), |
| 244 | ) |
| 245 | # 3. Feed-forward |
| 246 | self.ff = GLUMBConv(dim, dim, mlp_ratio, norm_type=None, residual_connection=False) |
| 247 | |
| 248 | self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5) |
| 249 | |
| 250 | def forward( |