| 86 | |
| 87 | |
| 88 | class TemporalTransformer3DModel(nn.Module): |
| 89 | def __init__( |
| 90 | self, |
| 91 | in_channels, |
| 92 | num_attention_heads, |
| 93 | attention_head_dim, |
| 94 | |
| 95 | num_layers, |
| 96 | attention_block_types = ( "Temporal_Self", "Temporal_Self", ), |
| 97 | dropout = 0.0, |
| 98 | norm_num_groups = 32, |
| 99 | cross_attention_dim = 768, |
| 100 | activation_fn = "geglu", |
| 101 | attention_bias = False, |
| 102 | upcast_attention = False, |
| 103 | |
| 104 | cross_frame_attention_mode = None, |
| 105 | temporal_position_encoding = False, |
| 106 | temporal_position_encoding_max_len = 24, |
| 107 | ): |
| 108 | super().__init__() |
| 109 | |
| 110 | inner_dim = num_attention_heads * attention_head_dim |
| 111 | |
| 112 | self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True) |
| 113 | self.proj_in = nn.Linear(in_channels, inner_dim) |
| 114 | |
| 115 | self.transformer_blocks = nn.ModuleList( |
| 116 | [ |
| 117 | TemporalTransformerBlock( |
| 118 | dim=inner_dim, |
| 119 | num_attention_heads=num_attention_heads, |
| 120 | attention_head_dim=attention_head_dim, |
| 121 | attention_block_types=attention_block_types, |
| 122 | dropout=dropout, |
| 123 | norm_num_groups=norm_num_groups, |
| 124 | cross_attention_dim=cross_attention_dim, |
| 125 | activation_fn=activation_fn, |
| 126 | attention_bias=attention_bias, |
| 127 | upcast_attention=upcast_attention, |
| 128 | cross_frame_attention_mode=cross_frame_attention_mode, |
| 129 | temporal_position_encoding=temporal_position_encoding, |
| 130 | temporal_position_encoding_max_len=temporal_position_encoding_max_len, |
| 131 | ) |
| 132 | for d in range(num_layers) |
| 133 | ] |
| 134 | ) |
| 135 | self.proj_out = nn.Linear(inner_dim, in_channels) |
| 136 | |
| 137 | def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None): |
| 138 | assert hidden_states.dim() == 5, f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}." |
| 139 | video_length = hidden_states.shape[2] |
| 140 | hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w") |
| 141 | |
| 142 | batch, channel, height, weight = hidden_states.shape |
| 143 | residual = hidden_states |
| 144 | |
| 145 | hidden_states = self.norm(hidden_states) |