1111
1212logger = logging .getLogger (__name__ )
1313
14+
15+ class AdaLNTransformerEncoderLayer (TransformerEncoderLayer ):
16+ def __init__ (self , d_model , nhead , condition_dim = 1 , layer_norm_eps = 1e-5 , ** kwargs ):
17+ super ().__init__ (d_model , nhead , layer_norm_eps = layer_norm_eps , ** kwargs )
18+ # AdaLN provides the affine; strip it from the parent's LayerNorms.
19+ self .norm1 = nn .LayerNorm (d_model , eps = layer_norm_eps , elementwise_affine = False )
20+ self .norm2 = nn .LayerNorm (d_model , eps = layer_norm_eps , elementwise_affine = False )
21+ # DiT-style (1 + gamma) modulation; zero-init weights/biases => identity at init.
22+ self .adaLN_modulation1 = nn .Linear (condition_dim , 2 * d_model )
23+ self .adaLN_modulation2 = nn .Linear (condition_dim , 2 * d_model )
24+ for m in (self .adaLN_modulation1 , self .adaLN_modulation2 ):
25+ nn .init .zeros_ (m .weight )
26+ nn .init .zeros_ (m .bias )
27+
28+ def forward (self , src , cond , src_mask = None , src_key_padding_mask = None , is_causal = False ):
29+ gamma1 , beta1 = self .adaLN_modulation1 (cond ).chunk (2 , dim = - 1 )
30+ gamma2 , beta2 = self .adaLN_modulation2 (cond ).chunk (2 , dim = - 1 )
31+
32+ x = src
33+ if self .norm_first :
34+ x_norm = self .norm1 (x ) * (1 + gamma1 .unsqueeze (1 )) + beta1 .unsqueeze (1 )
35+ x = x + self .dropout1 (self .self_attn (x_norm , x_norm , x_norm , attn_mask = src_mask ,
36+ key_padding_mask = src_key_padding_mask , need_weights = False , is_causal = is_causal )[0 ])
37+ x_norm2 = self .norm2 (x ) * (1 + gamma2 .unsqueeze (1 )) + beta2 .unsqueeze (1 )
38+ x = x + self .dropout2 (self .linear2 (self .dropout (self .activation (self .linear1 (x_norm2 )))))
39+ else :
40+ x2 = self .self_attn (x , x , x , attn_mask = src_mask ,
41+ key_padding_mask = src_key_padding_mask , need_weights = False , is_causal = is_causal )[0 ]
42+ x = x + self .dropout1 (x2 )
43+ x = self .norm1 (x ) * (1 + gamma1 .unsqueeze (1 )) + beta1 .unsqueeze (1 )
44+
45+ x2 = self .linear2 (self .dropout (self .activation (self .linear1 (x ))))
46+ x = x + self .dropout2 (x2 )
47+ x = self .norm2 (x ) * (1 + gamma2 .unsqueeze (1 )) + beta2 .unsqueeze (1 )
48+ return x
49+
50+ class AdaLNTransformerEncoder (TransformerEncoder ):
51+ """`nn.TransformerEncoder` that threads a conditioning tensor to each AdaLN layer."""
52+ def forward (self , src , cond , mask = None , src_key_padding_mask = None , is_causal = False ):
53+ output = src
54+ for mod in self .layers :
55+ output = mod (output , cond = cond , src_mask = mask ,
56+ src_key_padding_mask = src_key_padding_mask , is_causal = is_causal )
57+ if self .norm is not None :
58+ output = self .norm (output )
59+ return output
60+
1461class SpecialEmbedding (torch .nn .Module ):
1562 ScalarPassThrough = 0
1663 VectorPassThrough = 1
@@ -199,7 +246,8 @@ def __init__(self,
199246 aggregation_weight : Optional [int ] = None ,
200247 emebdding_dropout : Optional [float ] = None ,
201248 prediction_perceptron_dropout : Optional [float ] = None ,
202- concat_start_to_prediction_input_embedding_dim : Optional [int ] = None ):
249+ concat_start_to_prediction_input_embedding_dim : Optional [int ] = None ,
250+ condition_dim : Optional [int ] = None ):
203251 """
204252 Expects tokens in the following format:
205253 START_k -> [] -> STOP -> PAD
@@ -250,8 +298,16 @@ def __init__(self,
250298 if "nhead" in TransformerEncoderLayer_args and self .d_model % TransformerEncoderLayer_args ["nhead" ]:
251299 logger .warning ("d_model is not divisible by nhead, padding to the next multiple" )
252300 self .d_model += TransformerEncoderLayer_args ["nhead" ] - self .d_model % TransformerEncoderLayer_args ["nhead" ]
253- self .encoder_layers = TransformerEncoderLayer (self .d_model , batch_first = True , ** TransformerEncoderLayer_args )
254- self .transformer_encoder = TransformerEncoder (self .encoder_layers , ** TransformerEncoder_args )
301+
302+ self .condition_dim = condition_dim
303+ if condition_dim is not None :
304+ self .encoder_layers = AdaLNTransformerEncoderLayer (
305+ self .d_model , batch_first = True , condition_dim = condition_dim , ** TransformerEncoderLayer_args )
306+ self .transformer_encoder = AdaLNTransformerEncoder (self .encoder_layers , ** TransformerEncoder_args )
307+ else :
308+ self .encoder_layers = TransformerEncoderLayer (self .d_model , batch_first = True , ** TransformerEncoderLayer_args )
309+ self .transformer_encoder = TransformerEncoder (self .encoder_layers , ** TransformerEncoder_args )
310+
255311 self .start_type = start_type
256312 if start_type == "categorial" :
257313 self .start_embedding = nn .Embedding (n_start , self .d_model )
@@ -347,7 +403,8 @@ def forward(self,
347403 start : Tensor ,
348404 cascade : List [Tensor ],
349405 padding_mask : Tensor | None ,
350- prediction_head : int | None ) -> Tensor :
406+ prediction_head : int | None ,
407+ cond : Tensor | None = None ) -> Tensor :
351408 """
352409 Arguments:
353410 start: Tensor of shape ``[batch_size]`` with the start token.
@@ -356,6 +413,7 @@ def forward(self,
356413 prediction_head: Index of the prediction head to use. If None, use the only one. The
357414 model works in two stages. Firstly, a vector is prepared wih Encoder and
358415 various tweaks. Then, the vector is passed to a perceptron aka prediction head.
416+ cond: Tensor of shape ``[batch_size, condition_dim]`` with the conditioning vector for AdaLN.
359417 Returns:
360418 Tensor of shape ``[batch_size, seq_len, output_dim]`` with the predictions.
361419 """
@@ -377,7 +435,12 @@ def forward(self,
377435 data = torch .cat ([self .start_embedding (start ).unsqueeze (1 ), cascade_embedding ], dim = 1 )
378436 logger .debug ("Data size: %s" , data .size ())
379437 logger .debug ("Padding mask size: %s" , padding_mask .size () if padding_mask is not None else "None" )
380- transformer_output = self .transformer_encoder (data , src_key_padding_mask = padding_mask )
438+ if getattr (self , "condition_dim" , None ) is not None :
439+ if cond is None :
440+ raise ValueError ("condition_dim is set but cond is not provided" )
441+ transformer_output = self .transformer_encoder (data , src_key_padding_mask = padding_mask , cond = cond )
442+ else :
443+ transformer_output = self .transformer_encoder (data , src_key_padding_mask = padding_mask )
381444
382445 logging .debug ("Transformer output size: %s" , transformer_output .size ())
383446 if self .aggregate_after_encoder :
0 commit comments