(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
timestep: Optional[torch.LongTensor] = None,
height: int = None,
width: int = None,
)
| 248 | self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5) |
| 249 | |
| 250 | def forward( |
| 251 | self, |
| 252 | hidden_states: torch.Tensor, |
| 253 | attention_mask: Optional[torch.Tensor] = None, |
| 254 | encoder_hidden_states: Optional[torch.Tensor] = None, |
| 255 | encoder_attention_mask: Optional[torch.Tensor] = None, |
| 256 | timestep: Optional[torch.LongTensor] = None, |
| 257 | height: int = None, |
| 258 | width: int = None, |
| 259 | ) -> torch.Tensor: |
| 260 | batch_size = hidden_states.shape[0] |
| 261 | |
| 262 | # 1. Modulation |
| 263 | shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( |
| 264 | self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1) |
| 265 | ).chunk(6, dim=1) |
| 266 | |
| 267 | # 2. Self Attention |
| 268 | norm_hidden_states = self.norm1(hidden_states) |
| 269 | norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa |
| 270 | norm_hidden_states = norm_hidden_states.to(hidden_states.dtype) |
| 271 | |
| 272 | attn_output = self.attn1(norm_hidden_states) |
| 273 | hidden_states = hidden_states + gate_msa * attn_output |
| 274 | |
| 275 | # 3. Cross Attention |
| 276 | if self.attn2 is not None: |
| 277 | attn_output = self.attn2( |
| 278 | hidden_states, |
| 279 | encoder_hidden_states=encoder_hidden_states, |
| 280 | attention_mask=encoder_attention_mask, |
| 281 | ) |
| 282 | hidden_states = attn_output + hidden_states |
| 283 | |
| 284 | # 4. Feed-forward |
| 285 | norm_hidden_states = self.norm2(hidden_states) |
| 286 | norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp |
| 287 | |
| 288 | norm_hidden_states = norm_hidden_states.unflatten(1, (height, width)).permute(0, 3, 1, 2) |
| 289 | ff_output = self.ff(norm_hidden_states) |
| 290 | ff_output = ff_output.flatten(2, 3).permute(0, 2, 1) |
| 291 | hidden_states = hidden_states + gate_mlp * ff_output |
| 292 | |
| 293 | return hidden_states |
| 294 | |
| 295 | |
| 296 | class SanaTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin): |
nothing calls this directly
no outgoing calls
no test coverage detected