1414
1515# pylint: disable=C0115,C0116,C0301
1616
17+ import copy
1718from dataclasses import dataclass
1819from typing import Optional , Union
1920
@@ -65,10 +66,16 @@ def __init__(self, config: TransformerConfig):
6566
6667 setattr (self .modulation , "sequence_parallel" , config .sequence_parallel )
6768
69+ @jit_fuser
6870 def forward (self , timestep_emb ):
69- e = (self .modulation + timestep_emb ).chunk (6 , dim = 1 )
71+ e = (self .modulation + timestep_emb ).transpose (0 , 1 )
72+ e = e .chunk (6 , dim = 0 )
7073 return e
7174
75+ @jit_fuser
76+ def normalize_modulate (self , norm , hidden_states , shift , scale ):
77+ return self .modulate (norm (hidden_states ), shift , scale )
78+
7279 @jit_fuser
7380 def modulate (self , x , shift , scale ):
7481 return x * (1 + scale ) + shift
@@ -96,19 +103,31 @@ def __init__(
96103 pg_collection : Optional [ProcessGroupCollection ] = None ,
97104 vp_stage : Optional [int ] = None ,
98105 ):
106+ def _replace_no_cp_submodules (submodules ):
107+ modified_submods = copy .deepcopy (submodules )
108+ modified_submods .cross_attention = IdentityOp
109+ return modified_submods
110+
111+ # Replace any submodules that will have CP disabled and build them manually later after TransformerLayer init.
112+ # modified_submods = _replace_no_cp_submodules(submodules)
99113 super ().__init__ (
100114 config = config , submodules = submodules , layer_number = layer_number , hidden_dropout = hidden_dropout
101115 )
102116
103- # # TODO: Override Cross Attention to disable TP Comm overlap as well. ???
104- # # Not disabling will attempt re-use of buffer size same as Q and lead to incorrect tensor shapes.
105- # cp_override_config = copy.deepcopy(config)
106- # cp_override_config.tp_comm_overlap = False
107- # self.cross_attention = build_module(
108- # submodules.cross_attention,
109- # config=cp_override_config,
110- # layer_number=layer_number,
111- # )
117+ # TODO (pmannan): Override Cross Attention to disable CP.
118+ # Disable TP Comm overlap as well. Not disabling will attempt re-use of buffer size same as
119+ # Q and lead to incorrect tensor shapes.
120+ # if submodules.cross_attention != IdentityOp:
121+ # cp_override_config = copy.deepcopy(config)
122+ # cp_override_config.context_parallel_size = 1
123+ # cp_override_config.tp_comm_overlap = False
124+ # self.cross_attention = build_module(
125+ # submodules.cross_attention,
126+ # config=cp_override_config,
127+ # layer_number=layer_number,
128+ # )
129+ # else:
130+ # self.cross_attention = None
112131
113132 self .full_self_attention = build_module (
114133 submodules .full_self_attention ,
@@ -148,6 +167,10 @@ def _mark_trainable_params_for_tp_grad_avg(self, modules: Optional[list] = None)
148167 if isinstance (param , nn .Parameter ) and param .requires_grad :
149168 setattr (param , "average_gradients_across_tp_domain" , True )
150169
170+ @jit_fuser
171+ def add_residual (self , x : torch .Tensor , residual : torch .Tensor ) -> torch .Tensor :
172+ return x + residual
173+
151174 def forward (
152175 self ,
153176 hidden_states ,
@@ -169,19 +192,13 @@ def forward(
169192 rope_emb = rotary_pos_emb
170193
171194 shift_full , scale_full , gate_full , shift_mlp , scale_mlp , gate_mlp = self .adaLN (timestep_emb )
172- # transpose to bring it to [1, b, ...] format
173- shift_full = shift_full .transpose (0 , 1 )
174- scale_full = scale_full .transpose (0 , 1 )
175- gate_full = gate_full .transpose (0 , 1 )
176- shift_mlp = shift_mlp .transpose (0 , 1 )
177- scale_mlp = scale_mlp .transpose (0 , 1 )
178- gate_mlp = gate_mlp .transpose (0 , 1 )
179195
180196 # ******************************************** full self attention *******************************************
181197
182198 # adaLN with scale + shift + gate
183- pre_full_attn_layernorm_output_ada = self .adaLN .modulate (
184- self .norm1 (hidden_states ),
199+ pre_full_attn_layernorm_output_ada = self .adaLN .normalize_modulate (
200+ self .norm1 ,
201+ hidden_states ,
185202 shift = shift_full ,
186203 scale = scale_full ,
187204 )
@@ -201,6 +218,12 @@ def forward(
201218
202219 # ******************************************** cross attention ******************************************************
203220
221+ # TODO (pmannan): Disable CP for CrossAttention as KV context is small.
222+ # But needs better support for packed sequences and padding to ensure correct calculations
223+ # packed_seq_params['cross_attention'].cu_seqlens_q = torch.tensor(
224+ # [0, hidden_states.shape[0]],
225+ # device=packed_seq_params['cross_attention'].cu_seqlens_kv.device,
226+ # dtype=torch.int32)
204227 attention_output , bias = self .cross_attention (
205228 self .norm3 (hidden_states ),
206229 attention_mask = context_mask ,
@@ -210,12 +233,13 @@ def forward(
210233 if bias is not None :
211234 attention_output = attention_output + bias
212235
213- hidden_states = hidden_states + attention_output
236+ hidden_states = self . add_residual ( hidden_states , attention_output )
214237
215238 # ******************************************** mlp ******************************************************
216239
217- pre_mlp_layernorm_output_ada = self .adaLN .modulate (
218- self .norm2 (hidden_states ),
240+ pre_mlp_layernorm_output_ada = self .adaLN .normalize_modulate (
241+ self .norm2 ,
242+ hidden_states ,
219243 shift = shift_mlp ,
220244 scale = scale_mlp ,
221245 )
0 commit comments