3838class GemmaRMSNormFunc (torch .autograd .Function ):
3939 @staticmethod
4040 def forward (hidden_states : torch .Tensor , weight : torch .Tensor , epsilon : float ):
41- hidden_states = hidden_states .to (torch .float32 )
42- div_first = hidden_states * torch .rsqrt (torch .tensor (hidden_states .shape [- 1 ], dtype = torch .float32 ))
41+ div_first = hidden_states * torch .rsqrt (torch .tensor (hidden_states .shape [- 1 ], dtype = hidden_states .dtype ))
4342 variance = div_first .pow (2 ).sum (- 1 , keepdim = True )
4443 hidden_states = hidden_states * torch .rsqrt (variance + epsilon )
4544 return weight * hidden_states
@@ -61,7 +60,7 @@ class QEffGemma3CustomRMSNormAIC(nn.Module):
6160 def forward (self , hidden_states ):
6261 return GemmaRMSNormFunc .apply (
6362 hidden_states ,
64- self .weight . float ( ) + 1.0 ,
63+ ( self .weight ). to ( hidden_states . dtype ) + 1.0 ,
6564 self .variance_epsilon if hasattr (self , "variance_epsilon" ) else self .eps ,
6665 )
6766
@@ -164,7 +163,7 @@ def eager_attention_forward(
164163
165164 if attention_mask is not None :
166165 attn_weights = torch .where (
167- attention_mask , torch .tensor (MIN_MASKED_ATTENTION_VALUE , dtype = torch . float32 ), attn_weights
166+ attention_mask , torch .tensor (MIN_MASKED_ATTENTION_VALUE , dtype = module . config . torch_dtype ), attn_weights
168167 )
169168
170169 attn_weights = nn .functional .softmax (attn_weights , dim = - 1 , dtype = torch .float32 ).to (query .dtype )
@@ -198,7 +197,7 @@ def __qeff_init__(self):
198197 config = copy .deepcopy (self .config )
199198 config .rope_theta = config .rope_local_base_freq
200199 config .rope_scaling = {"rope_type" : "default" , "factor" : 1.0 }
201- self .is_local = _is_local (self .layer_idx , self .config .sliding_window_pattern )
200+ self .is_local = _is_local (self .layer_idx , self .config ._sliding_window_pattern )
202201 self .window = self .config .sliding_window if self .is_local else None
203202
204203 self .rotary_emb_local = QEffGemma3RotaryEmbedding (
@@ -253,7 +252,7 @@ def forward(
253252 "batch_index" : batch_index ,
254253 "position_ids" : position_ids ,
255254 "is_sliding" : self .is_sliding ,
256- "sliding_window_pattern" : self .config .sliding_window_pattern ,
255+ "sliding_window_pattern" : self .config ._sliding_window_pattern ,
257256 "sliding_window" : past_key_values .sliding_window_len ,
258257 }
259258 if comp_ctx_lengths is not None :
@@ -272,7 +271,9 @@ def forward(
272271
273272 if attention_mask is not None : # no matter the length, we just slice it
274273 attn_weights = torch .where (
275- attention_mask .bool (), torch .tensor (MIN_MASKED_ATTENTION_VALUE , dtype = torch .float32 ), attn_weights
274+ attention_mask .bool (),
275+ torch .tensor (MIN_MASKED_ATTENTION_VALUE , dtype = self .config .torch_dtype ),
276+ attn_weights ,
276277 )
277278
278279 # upcast attention to fp32
@@ -322,7 +323,7 @@ def forward(
322323 else :
323324 attention_mask = _create_causal_mask (
324325 position_ids = position_ids ,
325- target_length = past_key_value .key_cache [self .config .sliding_window_pattern - 1 ].shape [- 2 ],
326+ target_length = past_key_value .key_cache [self .config ._sliding_window_pattern - 1 ].shape [- 2 ],
326327 )
327328
328329 hidden_states , self_attn_weights = self .self_attn (
@@ -534,6 +535,9 @@ def forward(
534535 )
535536 return_dict = return_dict if return_dict is not None else self .config .use_return_dict
536537
538+ if self .config .torch_dtype == torch .float16 :
539+ logger .warning ("Accuracy might drop with float16 as torch_dtype" )
540+
537541 outputs = self .model (
538542 input_ids = input_ids ,
539543 attention_mask = attention_mask ,
@@ -551,7 +555,7 @@ def forward(
551555 )
552556 logit_index = position_ids .to (torch .int32 ).argmax (1 , keepdim = True )
553557 hidden_states = outputs [0 ][torch .arange (position_ids .shape [0 ]).view (- 1 , 1 ), logit_index ]
554- logits = self .lm_head (hidden_states )
558+ logits = self .lm_head (hidden_states ). float ()
555559
556560 if self .config .final_logit_softcapping is not None :
557561 logits = logits / self .config .final_logit_softcapping
@@ -569,7 +573,9 @@ def forward(
569573 def get_dummy_pkv_cache (self , config , batch_size , seq_len ):
570574 n_heads = config .num_key_value_heads
571575 d_head = config .head_dim
572- layer_switch = config .sliding_window_pattern if hasattr (config , "sliding_window_pattern" ) else 2 # 2 is for BC
576+ layer_switch = (
577+ config ._sliding_window_pattern if hasattr (config , "_sliding_window_pattern" ) else 2
578+ ) # 2 is for BC
573579 is_sliding = torch .tensor (
574580 [bool ((i + 1 ) % layer_switch ) for i in range (config .num_hidden_layers )], dtype = torch .bool
575581 )
@@ -581,8 +587,8 @@ def get_dummy_pkv_cache(self, config, batch_size, seq_len):
581587 for i in range (config .num_hidden_layers ):
582588 if hasattr (config , "sliding_window" ):
583589 cache_shape = global_cache_shape if not is_sliding [i ] else sliding_cache_shape
584- new_layer_key_cache = torch .zeros (cache_shape , dtype = torch . float32 )
585- new_layer_value_cache = torch .zeros (cache_shape , dtype = torch . float32 )
590+ new_layer_key_cache = torch .zeros (cache_shape , dtype = self . config . torch_dtype )
591+ new_layer_value_cache = torch .zeros (cache_shape , dtype = self . config . torch_dtype )
586592 pkv = (new_layer_key_cache , new_layer_value_cache )
587593 past_key_values .append (pkv )
588594 return past_key_values
@@ -835,15 +841,15 @@ def get_onnx_dynamic_axes(
835841 pkv_dynamic_axes = {0 : "full_batch_size" if continuous_batching else "batch_size" , 2 : "ctx_len" }
836842 pkv_dynamic_sliding_axes = {0 : "full_batch_size" if continuous_batching else "batch_size" , 2 : "sliding_window" }
837843 layer_switch = (
838- self .language_model .config .sliding_window_pattern
839- if hasattr (self .language_model .config , "sliding_window_pattern " )
844+ self .language_model .config ._sliding_window_pattern
845+ if hasattr (self .language_model .config , "_sliding_window_pattern " )
840846 else 2
841847 )
842848 for i in range (self .language_model .config .num_hidden_layers ):
843849 for kv in ["key" , "value" ]:
844850 apply_dynamic_axes = (
845851 pkv_dynamic_sliding_axes
846- if ((i + 1 ) % layer_switch and hasattr (self .language_model .config , "sliding_window_pattern " ))
852+ if ((i + 1 ) % layer_switch and hasattr (self .language_model .config , "_sliding_window_pattern " ))
847853 else pkv_dynamic_axes
848854 )
849855 lang_dynamic_axes [f"past_{ kv } .{ i } " ] = apply_dynamic_axes
@@ -881,7 +887,9 @@ def get_output_names(self, kv_offload: bool = False):
881887 def get_dummy_pkv_cache (self , config , batch_size , seq_len ):
882888 n_heads = config .num_key_value_heads
883889 d_head = config .head_dim
884- layer_switch = config .sliding_window_pattern if hasattr (config , "sliding_window_pattern" ) else 2 # 2 is for BC
890+ layer_switch = (
891+ config ._sliding_window_pattern if hasattr (config , "_sliding_window_pattern" ) else 2
892+ ) # 2 is for BC
885893 is_sliding = torch .tensor (
886894 [bool ((i + 1 ) % layer_switch ) for i in range (config .num_hidden_layers )], dtype = torch .bool
887895 )
@@ -893,8 +901,8 @@ def get_dummy_pkv_cache(self, config, batch_size, seq_len):
893901 for i in range (config .num_hidden_layers ):
894902 if hasattr (config , "sliding_window" ):
895903 cache_shape = global_cache_shape if not is_sliding [i ] else sliding_cache_shape
896- new_layer_key_cache = torch .zeros (cache_shape , dtype = torch . float32 )
897- new_layer_value_cache = torch .zeros (cache_shape , dtype = torch . float32 )
904+ new_layer_key_cache = torch .zeros (cache_shape , dtype = self . config . torch_dtype )
905+ new_layer_value_cache = torch .zeros (cache_shape , dtype = self . config . torch_dtype )
898906 pkv = (new_layer_key_cache , new_layer_value_cache )
899907 past_key_values .append (pkv )
900908 return past_key_values
@@ -931,9 +939,9 @@ def get_dummy_inputs(
931939 # Define inputs
932940 vision_inputs = {}
933941 lang_inputs = {}
934- vision_inputs ["pixel_values" ] = torch .zeros ((inputs_shapes ["pixel_values" ]), dtype = torch . float32 )
942+ vision_inputs ["pixel_values" ] = torch .zeros ((inputs_shapes ["pixel_values" ]), dtype = self . config . torch_dtype )
935943 lang_inputs ["input_ids" ] = torch .zeros ((inputs_shapes ["input_ids" ]), dtype = torch .int64 )
936- lang_inputs ["vision_embeds" ] = torch .zeros ((inputs_shapes ["vision_embeds" ]), dtype = torch . float32 )
944+ lang_inputs ["vision_embeds" ] = torch .zeros ((inputs_shapes ["vision_embeds" ]), dtype = self . config . torch_dtype )
937945 lang_inputs ["position_ids" ] = (
938946 torch .arange (constants .ONNX_EXPORT_EXAMPLE_SEQ_LEN , dtype = torch .int64 )
939947 .view (1 , constants .ONNX_EXPORT_EXAMPLE_SEQ_LEN )
@@ -972,7 +980,7 @@ def get_inputs_info(self):
972980 IOInfo (name = "attention_mask" , datatype = torch .int64 , shape = ("batch_size" , "seq_len" )),
973981 IOInfo (
974982 name = "pixel_values" ,
975- datatype = torch . float32 ,
983+ datatype = self . config . torch_dtype ,
976984 shape = ("batch_size" , 3 , "img_size" , "img_size" ),
977985 ),
978986 ]
0 commit comments