2121import jax .numpy as jnp
2222
2323from flax import linen as nn
24+ from flax import nnx
2425
25- from MaxText .layers .linears import mlp_block
26- from MaxText .layers import models
26+ from MaxText import max_utils
27+ from MaxText .layers import nnx_wrappers , initializers
28+ from MaxText .layers .linears import Dropout , MlpBlock
29+ from MaxText .layers .models import Config
30+ from MaxText .layers .attentions import Attention
2731from MaxText .layers import quantizations
28- from MaxText .layers .attentions import attention_as_linen
2932from MaxText .layers .quantizations import AqtQuantization as Quant
30- from MaxText .layers .normalizations import rms_norm
33+ from MaxText .layers .normalizations import RMSNorm
3134
3235
3336# -----------------------------------------
3437# The Decoder Layer for Mistral
3538# -----------------------------------------
3639
3740
38- class MistralDecoderLayer (nn .Module ):
41+ class MistralDecoderLayer (nnx .Module ):
3942 """Transformer decoder layer that attends to the encoder."""
4043
41- config : models .Config
42- mesh : Mesh
43- model_mode : str
44- quant : None | Quant = None
44+ def __init__ (
45+ self ,
46+ config : Config ,
47+ model_mode : str ,
48+ mesh : Mesh ,
49+ * ,
50+ rngs : nnx .Rngs ,
51+ quant : None | Quant = None ,
52+ ):
53+ self .config = config
54+ self .mesh = mesh
55+ self .quant = quant
56+ self .rngs = rngs
57+
58+ batch_size , seq_len = max_utils .get_batch_seq_len_for_mode (config , model_mode )
59+ dummy_inputs_shape = (batch_size , seq_len , config .emb_dim )
60+
61+ self .pre_self_attention_layer_norm = RMSNorm (
62+ num_features = config .emb_dim ,
63+ dtype = config .dtype ,
64+ weight_dtype = config .weight_dtype ,
65+ kernel_axes = ("norm" ,),
66+ epsilon = config .normalization_layer_epsilon ,
67+ rngs = self .rngs ,
68+ )
69+
70+ self .self_attention = Attention (
71+ config = config ,
72+ num_query_heads = config .num_query_heads ,
73+ num_kv_heads = config .num_kv_heads ,
74+ head_dim = config .head_dim ,
75+ max_target_length = config .max_target_length ,
76+ max_prefill_predict_length = config .max_prefill_predict_length ,
77+ attention_kernel = config .attention ,
78+ inputs_q_shape = dummy_inputs_shape ,
79+ inputs_kv_shape = dummy_inputs_shape ,
80+ mesh = mesh ,
81+ dtype = config .dtype ,
82+ weight_dtype = config .weight_dtype ,
83+ dropout_rate = config .dropout_rate ,
84+ float32_qk_product = config .float32_qk_product ,
85+ float32_logits = config .float32_logits ,
86+ quant = self .quant ,
87+ kv_quant = quantizations .configure_kv_quant (config ),
88+ prefill_cache_axis_order = tuple (map (int , config .prefill_cache_axis_order .split ("," ))),
89+ ar_cache_axis_order = tuple (map (int , config .ar_cache_axis_order .split ("," ))),
90+ compute_axis_order = tuple (map (int , config .compute_axis_order .split ("," ))),
91+ reshape_q = config .reshape_q ,
92+ use_ragged_attention = config .use_ragged_attention ,
93+ ragged_block_size = config .ragged_block_size ,
94+ model_mode = model_mode ,
95+ rngs = self .rngs ,
96+ )
97+
98+ self .post_self_attention_layer_norm = RMSNorm (
99+ num_features = config .emb_dim ,
100+ dtype = config .dtype ,
101+ weight_dtype = config .weight_dtype ,
102+ kernel_axes = ("norm" ,),
103+ epsilon = config .normalization_layer_epsilon ,
104+ rngs = self .rngs ,
105+ )
106+
107+ self .mlp = MlpBlock (
108+ in_features = config .emb_dim ,
109+ intermediate_dim = config .mlp_dim ,
110+ activations = config .mlp_activations ,
111+ intermediate_dropout_rate = config .dropout_rate ,
112+ dtype = config .dtype ,
113+ weight_dtype = config .weight_dtype ,
114+ config = config ,
115+ quant = self .quant ,
116+ model_mode = model_mode ,
117+ rngs = self .rngs ,
118+ )
119+
120+ self .dropout = Dropout (rate = config .dropout_rate , broadcast_dims = (- 2 ,), rngs = self .rngs )
121+
122+ self .activation_axis_names = ("activation_batch" , "activation_norm_length" , "activation_embed" )
45123
46- @nn .compact
47124 def __call__ (
48125 self ,
49126 inputs ,
50127 decoder_segment_ids ,
51128 decoder_positions ,
52129 deterministic ,
53130 model_mode ,
131+ page_state : None | int = None ,
132+ slot : None | int = None ,
54133 previous_chunk = None ,
55- page_state = None ,
56- slot = None ,
57134 ):
135+
58136 cfg = self .config
59- mesh = self .mesh
60137
61- inputs = nn .with_logical_constraint (inputs , ( "activation_batch" , "activation_norm_length" , "activation_embed" ) )
138+ inputs = nn .with_logical_constraint (inputs , self . activation_axis_names )
62139 inputs = checkpoint_name (inputs , "decoder_layer_input" )
63- lnx_rms = rms_norm (
64- num_features = inputs .shape [- 1 ],
65- dtype = cfg .dtype ,
66- weight_dtype = cfg .weight_dtype ,
67- name = "pre_self_attention_layer_norm" ,
68- kernel_axes = ("norm" ,),
69- epsilon = cfg .normalization_layer_epsilon ,
70- )
71- lnx = lnx_rms (inputs )
72-
73- lnx = nn .with_logical_constraint (lnx , ("activation_batch" , "activation_norm_length" , "activation_embed" ))
74-
75- # Self-attention block
76- attention_layer = attention_as_linen (
77- config = cfg ,
78- num_query_heads = cfg .num_query_heads ,
79- num_kv_heads = cfg .num_kv_heads ,
80- head_dim = cfg .head_dim ,
81- max_target_length = cfg .max_target_length ,
82- max_prefill_predict_length = cfg .max_prefill_predict_length ,
83- attention_kernel = cfg .attention ,
84- inputs_q_shape = lnx .shape ,
85- inputs_kv_shape = lnx .shape ,
86- mesh = mesh ,
87- dtype = cfg .dtype ,
88- weight_dtype = cfg .weight_dtype ,
89- dropout_rate = cfg .dropout_rate ,
90- name = "self_attention" ,
91- float32_qk_product = cfg .float32_qk_product ,
92- float32_logits = cfg .float32_logits ,
93- quant = self .quant ,
94- kv_quant = quantizations .configure_kv_quant (cfg ),
95- prefill_cache_axis_order = tuple (map (int , cfg .prefill_cache_axis_order .split ("," ))),
96- ar_cache_axis_order = tuple (map (int , cfg .ar_cache_axis_order .split ("," ))),
97- compute_axis_order = tuple (map (int , cfg .compute_axis_order .split ("," ))),
98- model_mode = model_mode ,
99- )
140+ lnx = self .pre_self_attention_layer_norm (inputs )
141+ lnx = nn .with_logical_constraint (lnx , self .activation_axis_names )
100142
101- attention_lnx = attention_layer (
143+ attention_lnx = self . self_attention (
102144 lnx ,
103145 lnx ,
104146 decoder_positions ,
105147 decoder_segment_ids = decoder_segment_ids ,
106148 deterministic = deterministic ,
107149 model_mode = model_mode ,
150+ slot = slot ,
151+ page_state = page_state ,
108152 previous_chunk = previous_chunk ,
109153 )
110154
111- attention_lnx = nn .with_logical_constraint (
112- attention_lnx , ("activation_batch" , "activation_norm_length" , "activation_embed" )
113- )
155+ attention_lnx = nn .with_logical_constraint (attention_lnx , self .activation_axis_names )
114156 intermediate_inputs = inputs + attention_lnx
115157
116158 # Fully Connected
117- hidden_states = rms_norm (
118- num_features = intermediate_inputs .shape [- 1 ],
119- dtype = cfg .dtype ,
120- weight_dtype = cfg .weight_dtype ,
121- name = "post_self_attention_layer_norm" ,
122- kernel_axes = ("norm" ,),
123- epsilon = cfg .normalization_layer_epsilon ,
124- )(intermediate_inputs )
125- hidden_states = nn .with_logical_constraint (
126- hidden_states , ("activation_batch" , "activation_norm_length" , "activation_embed" )
127- )
159+ hidden_states = self .post_self_attention_layer_norm (intermediate_inputs )
160+ hidden_states = nn .with_logical_constraint (hidden_states , self .activation_axis_names )
128161
129- mlp_lnx = mlp_block (
130- in_features = hidden_states .shape [- 1 ],
131- intermediate_dim = cfg .mlp_dim ,
132- activations = cfg .mlp_activations ,
133- intermediate_dropout_rate = cfg .dropout_rate ,
134- dtype = cfg .dtype ,
135- weight_dtype = cfg .weight_dtype ,
136- name = "mlp" ,
137- config = cfg ,
138- quant = self .quant ,
139- )(hidden_states , deterministic = deterministic )
140- mlp_lnx = nn .with_logical_constraint (mlp_lnx , ("activation_batch" , "activation_norm_length" , "activation_embed" ))
162+ # MLP block.
163+ mlp_lnx = self .mlp (hidden_states , deterministic = deterministic )
164+ mlp_lnx = nn .with_logical_constraint (mlp_lnx , self .activation_axis_names )
141165
142166 layer_output = mlp_lnx + intermediate_inputs
143- layer_output = nn .Dropout (rate = cfg .dropout_rate , broadcast_dims = (- 2 ,))(layer_output , deterministic = deterministic )
144-
145- layer_output = nn .with_logical_constraint (
146- layer_output ,
147- ("activation_batch" , "activation_norm_length" , "activation_embed" ),
148- )
167+ layer_output = self .dropout (layer_output , deterministic = deterministic )
168+ layer_output = nn .with_logical_constraint (layer_output , self .activation_axis_names )
149169
150170 if cfg .record_internal_nn_metrics :
151171 self .sow ("intermediates" , "activation_mean" , jnp .mean (layer_output ))
@@ -160,3 +180,9 @@ def __call__(
160180 return layer_output , None
161181 else :
162182 return layer_output
183+
184+
185+ MistralDecoderLayerToLinen = nnx_wrappers .to_linen_class (
186+ MistralDecoderLayer ,
187+ base_metadata_fn = initializers .variable_to_logically_partitioned ,
188+ )
0 commit comments