hendrydong commited on
Commit
a1152aa
·
verified ·
1 Parent(s): 7540857

Upload SDARForCausalLM

Browse files
Files changed (6) hide show
  1. README.md +199 -0
  2. config.json +41 -0
  3. configuration_sdar.py +205 -0
  4. generation_config.json +7 -0
  5. model.safetensors +3 -0
  6. modeling_sdar.py +922 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "SDARForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_sdar.SDARConfig",
9
+ "AutoModel": "modeling_sdar.SDARModel",
10
+ "AutoModelForCausalLM": "modeling_sdar.SDARForCausalLM"
11
+ },
12
+ "bos_token_id": 151643,
13
+ "debug": false,
14
+ "eos_token_id": 151643,
15
+ "ep_size": 1,
16
+ "fuse_cross_entropy": false,
17
+ "head_dim": 128,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 512,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 1536,
22
+ "max_position_embeddings": 32768,
23
+ "max_window_layers": 12,
24
+ "micro_forward": false,
25
+ "model_type": "sdar",
26
+ "num_attention_heads": 4,
27
+ "num_hidden_layers": 12,
28
+ "num_key_value_heads": 8,
29
+ "rms_norm_eps": 1e-06,
30
+ "rope_scaling": null,
31
+ "rope_theta": 1000000,
32
+ "skip_checkpoint": false,
33
+ "sliding_window": null,
34
+ "tie_word_embeddings": false,
35
+ "torch_dtype": "bfloat16",
36
+ "transformers_version": "4.53.3",
37
+ "use_cache": false,
38
+ "use_deepep": false,
39
+ "use_sliding_window": false,
40
+ "vocab_size": 151936
41
+ }
configuration_sdar.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """SDAR model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.modeling_rope_utils import rope_config_validation
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class SDARConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`SDARModel`]. It is used to instantiate a
28
+ SDAR model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of
30
+ SDAR-1.7B [DiffuOpen/SDAR-1.7B-Chat](https://huggingface.co/DiffuOpen/SDAR-1.7B-Chat/).
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+ Args:
34
+ vocab_size (`int`, *optional*, defaults to 151936):
35
+ Vocabulary size of the SDAR model. Defines the number of different tokens that can be represented by the
36
+ `inputs_ids` passed when calling [`SDARModel`]
37
+ hidden_size (`int`, *optional*, defaults to 4096):
38
+ Dimension of the hidden representations.
39
+ intermediate_size (`int`, *optional*, defaults to 22016):
40
+ Dimension of the MLP representations.
41
+ num_hidden_layers (`int`, *optional*, defaults to 32):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 32):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ num_key_value_heads (`int`, *optional*, defaults to 32):
46
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
47
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
48
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
49
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
50
+ by meanpooling all the original heads within that group. For more details checkout [this
51
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
52
+ head_dim (`int`, *optional*, defaults to 128):
53
+ The attention head dimension.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether the model's input and output word embeddings should be tied.
67
+ rope_theta (`float`, *optional*, defaults to 10000.0):
68
+ The base period of the RoPE embeddings.
69
+ rope_scaling (`Dict`, *optional*):
70
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
71
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
72
+ accordingly.
73
+ Expected contents:
74
+ `rope_type` (`str`):
75
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
76
+ 'llama3'], with 'default' being the original RoPE implementation.
77
+ `factor` (`float`, *optional*):
78
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
79
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
80
+ original maximum pre-trained length.
81
+ `original_max_position_embeddings` (`int`, *optional*):
82
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
83
+ pretraining.
84
+ `attention_factor` (`float`, *optional*):
85
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
86
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
87
+ `factor` field to infer the suggested value.
88
+ `beta_fast` (`float`, *optional*):
89
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
90
+ ramp function. If unspecified, it defaults to 32.
91
+ `beta_slow` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 1.
94
+ `short_factor` (`List[float]`, *optional*):
95
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
96
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
97
+ size divided by the number of attention heads divided by 2
98
+ `long_factor` (`List[float]`, *optional*):
99
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
100
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
101
+ size divided by the number of attention heads divided by 2
102
+ `low_freq_factor` (`float`, *optional*):
103
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
104
+ `high_freq_factor` (`float`, *optional*):
105
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
106
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
107
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
108
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
109
+ Whether to use sliding window attention.
110
+ sliding_window (`int`, *optional*, defaults to 4096):
111
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
112
+ max_window_layers (`int`, *optional*, defaults to 28):
113
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
114
+ attention_dropout (`float`, *optional*, defaults to 0.0):
115
+ The dropout ratio for the attention probabilities.
116
+ ```python
117
+ >>> from transformers import SDARModel, SDARConfig
118
+ >>> # Initializing a SDAR style configuration
119
+ >>> configuration = SDARConfig()
120
+ >>> # Initializing a model from the SDAR-8B style configuration
121
+ >>> model = SDARModel(configuration)
122
+ >>> # Accessing the model configuration
123
+ >>> configuration = model.config
124
+ ```"""
125
+
126
+ model_type = "sdar"
127
+ keys_to_ignore_at_inference = ["past_key_values"]
128
+
129
+ # Default tensor parallel plan for base model `SDAR`
130
+ base_model_tp_plan = {
131
+ "layers.*.self_attn.q_proj": "colwise",
132
+ "layers.*.self_attn.k_proj": "colwise",
133
+ "layers.*.self_attn.v_proj": "colwise",
134
+ "layers.*.self_attn.o_proj": "rowwise",
135
+ "layers.*.mlp.gate_proj": "colwise",
136
+ "layers.*.mlp.up_proj": "colwise",
137
+ "layers.*.mlp.down_proj": "rowwise",
138
+ }
139
+ base_model_pp_plan = {
140
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
141
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
142
+ "norm": (["hidden_states"], ["hidden_states"]),
143
+ }
144
+
145
+ def __init__(
146
+ self,
147
+ vocab_size=151936,
148
+ hidden_size=4096,
149
+ intermediate_size=22016,
150
+ num_hidden_layers=32,
151
+ num_attention_heads=32,
152
+ num_key_value_heads=32,
153
+ head_dim=128,
154
+ hidden_act="silu",
155
+ max_position_embeddings=32768,
156
+ initializer_range=0.02,
157
+ rms_norm_eps=1e-6,
158
+ use_cache=True,
159
+ tie_word_embeddings=False,
160
+ rope_theta=10000.0,
161
+ rope_scaling=None,
162
+ attention_bias=False,
163
+ use_sliding_window=False,
164
+ sliding_window=4096,
165
+ max_window_layers=28,
166
+ attention_dropout=0.0,
167
+ **kwargs,
168
+ ):
169
+ self.vocab_size = vocab_size
170
+ self.max_position_embeddings = max_position_embeddings
171
+ self.hidden_size = hidden_size
172
+ self.intermediate_size = intermediate_size
173
+ self.num_hidden_layers = num_hidden_layers
174
+ self.num_attention_heads = num_attention_heads
175
+ self.use_sliding_window = use_sliding_window
176
+ self.sliding_window = sliding_window # we check `use_sliding_window` in the modeling code
177
+ self.max_window_layers = max_window_layers
178
+
179
+ # for backward compatibility
180
+ if num_key_value_heads is None:
181
+ num_key_value_heads = num_attention_heads
182
+
183
+ self.num_key_value_heads = num_key_value_heads
184
+ self.head_dim = head_dim
185
+ self.hidden_act = hidden_act
186
+ self.initializer_range = initializer_range
187
+ self.rms_norm_eps = rms_norm_eps
188
+ self.use_cache = use_cache
189
+ self.rope_theta = rope_theta
190
+ self.rope_scaling = rope_scaling
191
+ self.attention_bias = attention_bias
192
+ self.attention_dropout = attention_dropout
193
+ # Validate the correctness of rotary position embeddings parameters
194
+ # BC: if there is a 'type' field, move it to 'rope_type'.
195
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
196
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
197
+ rope_config_validation(self)
198
+
199
+ super().__init__(
200
+ tie_word_embeddings=tie_word_embeddings,
201
+ **kwargs,
202
+ )
203
+
204
+
205
+ __all__ = ["SDARConfig"]
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151643,
5
+ "transformers_version": "4.53.3",
6
+ "use_cache": false
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85ccefca8cf8d9b56463c3ed8cb3262d946b7c6891268b13c41ea6106015562a
3
+ size 405583592
modeling_sdar.py ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is modified based on https://github.com/huggingface/transformers/blob/v4.52.4/src/transformers/models/qwen3/modeling_qwen3.py.
2
+ #
3
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
4
+ # This file was automatically generated from src/transformers/models/qwen3/modular_qwen3.py.
5
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
6
+ # the file from the modular. If any change should be done, please apply the change to the
7
+ # modular_qwen3.py file directly. One of our CI enforces this.
8
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
9
+ # coding=utf-8
10
+ # Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
11
+ #
12
+ # Licensed under the Apache License, Version 2.0 (the "License");
13
+ # you may not use this file except in compliance with the License.
14
+ # You may obtain a copy of the License at
15
+ #
16
+ # http://www.apache.org/licenses/LICENSE-2.0
17
+ #
18
+ # Unless required by applicable law or agreed to in writing, software
19
+ # distributed under the License is distributed on an "AS IS" BASIS,
20
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ # See the License for the specific language governing permissions and
22
+ # limitations under the License.
23
+
24
+ from typing import Callable, Optional, Tuple, Union
25
+
26
+ import torch
27
+ from torch import nn
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.integrations import use_kernel_forward_from_hub
33
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
34
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
35
+ from transformers.modeling_layers import GradientCheckpointingLayer
36
+ from transformers.modeling_outputs import (
37
+ BaseModelOutputWithPast,
38
+ CausalLMOutputWithPast,
39
+ QuestionAnsweringModelOutput,
40
+ SequenceClassifierOutputWithPast,
41
+ TokenClassifierOutput,
42
+ )
43
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
44
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
45
+ from transformers.processing_utils import Unpack
46
+ from transformers.utils import LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
47
+ from .configuration_sdar import SDARConfig
48
+
49
+ from flash_attn.ops.triton.layer_norm import rms_norm_fn as flash_rms_norm
50
+
51
+ import torch.nn.functional as F
52
+ try:
53
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
55
+ except:
56
+ pass
57
+
58
+ try:
59
+ from liger_kernel.ops.swiglu import LigerSiLUMulFunction # noqa: F401
60
+ liger_kernel_is_available = True
61
+ except ImportError:
62
+ liger_kernel_is_available = False
63
+
64
+
65
+ if is_torch_flex_attn_available():
66
+ from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attention
67
+ from transformers.integrations.flex_attention import make_flex_block_causal_mask
68
+
69
+
70
+ logger = logging.get_logger(__name__)
71
+
72
+
73
+ @use_kernel_forward_from_hub("RMSNorm")
74
+ class SDARRMSNorm(nn.Module):
75
+ def __init__(self, hidden_size, eps=1e-6):
76
+ """
77
+ SDARRMSNorm is equivalent to T5LayerNorm
78
+ """
79
+ super().__init__()
80
+ self.weight = nn.Parameter(torch.ones(hidden_size))
81
+ self.variance_epsilon = eps
82
+
83
+ def forward(self, hidden_states):
84
+ return flash_rms_norm(
85
+ hidden_states, weight=self.weight, bias=None, eps=self.variance_epsilon)
86
+ '''
87
+ input_dtype = hidden_states.dtype
88
+ hidden_states = hidden_states.to(torch.float32)
89
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
90
+ hidden_states = hidden_states * \
91
+ torch.rsqrt(variance + self.variance_epsilon)
92
+ return self.weight * hidden_states.to(input_dtype)
93
+ '''
94
+
95
+ def extra_repr(self):
96
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
97
+
98
+
99
+ class SDARMLP(nn.Module):
100
+ def __init__(self, config):
101
+ super().__init__()
102
+ self.config = config
103
+ self.hidden_size = config.hidden_size
104
+ self.intermediate_size = config.intermediate_size
105
+ self.gate_proj = nn.Linear(
106
+ self.hidden_size, self.intermediate_size, bias=False)
107
+ self.up_proj = nn.Linear(
108
+ self.hidden_size, self.intermediate_size, bias=False)
109
+ self.down_proj = nn.Linear(
110
+ self.intermediate_size, self.hidden_size, bias=False)
111
+ self.act_fn = ACT2FN[config.hidden_act]
112
+
113
+ def forward(self, x):
114
+ if liger_kernel_is_available:
115
+ return self.down_proj(LigerSiLUMulFunction.apply(self.gate_proj(x), self.up_proj(x)))
116
+ else:
117
+ down_proj = self.down_proj(self.act_fn(
118
+ self.gate_proj(x)) * self.up_proj(x))
119
+ return down_proj
120
+
121
+
122
+ def rotate_half(x):
123
+ """Rotates half the hidden dims of the input."""
124
+ x1 = x[..., : x.shape[-1] // 2]
125
+ x2 = x[..., x.shape[-1] // 2:]
126
+ return torch.cat((-x2, x1), dim=-1)
127
+
128
+
129
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
130
+ """Applies Rotary Position Embedding to the query and key tensors.
131
+ Args:
132
+ q (`torch.Tensor`): The query tensor.
133
+ k (`torch.Tensor`): The key tensor.
134
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
135
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
136
+ position_ids (`torch.Tensor`, *optional*):
137
+ Deprecated and unused.
138
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
139
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
140
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
141
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
142
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
143
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
144
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
145
+ Returns:
146
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
147
+ """
148
+ cos = cos.unsqueeze(unsqueeze_dim)
149
+ sin = sin.unsqueeze(unsqueeze_dim)
150
+ q_embed = (q * cos) + (rotate_half(q) * sin)
151
+ k_embed = (k * cos) + (rotate_half(k) * sin)
152
+ return q_embed, k_embed
153
+
154
+
155
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
156
+ """
157
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
158
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
159
+ """
160
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
161
+ if n_rep == 1:
162
+ return hidden_states
163
+ hidden_states = hidden_states[:, :, None, :, :].expand(
164
+ batch, num_key_value_heads, n_rep, slen, head_dim)
165
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
166
+
167
+
168
+ def eager_attention_forward(
169
+ module: nn.Module,
170
+ query: torch.Tensor,
171
+ key: torch.Tensor,
172
+ value: torch.Tensor,
173
+ attention_mask: Optional[torch.Tensor],
174
+ scaling: float,
175
+ dropout: float = 0.0,
176
+ **kwargs,
177
+ ):
178
+ key_states = repeat_kv(key, module.num_key_value_groups)
179
+ value_states = repeat_kv(value, module.num_key_value_groups)
180
+
181
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
182
+ if attention_mask is not None:
183
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
184
+ attn_weights = attn_weights + causal_mask
185
+
186
+ attn_weights = nn.functional.softmax(
187
+ attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
188
+ attn_weights = nn.functional.dropout(
189
+ attn_weights, p=dropout, training=module.training)
190
+ attn_output = torch.matmul(attn_weights, value_states)
191
+ attn_output = attn_output.transpose(1, 2).contiguous()
192
+
193
+ return attn_output, attn_weights
194
+
195
+
196
+ class SDARAttention(nn.Module):
197
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
198
+
199
+ def __init__(self, config: SDARConfig, layer_idx: int):
200
+ super().__init__()
201
+ self.config = config
202
+ self.layer_idx = layer_idx
203
+ self.head_dim = getattr(
204
+ config, "head_dim", config.hidden_size // config.num_attention_heads)
205
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
206
+ self.scaling = self.head_dim**-0.5
207
+ self.attention_dropout = config.attention_dropout
208
+ self.is_causal = True
209
+
210
+ self.hidden_size = config.hidden_size
211
+ self.num_attention_heads = config.num_attention_heads
212
+ self.num_key_value_heads = config.num_key_value_heads
213
+
214
+ self.q_proj = nn.Linear(
215
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
216
+ )
217
+ self.k_proj = nn.Linear(
218
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
219
+ )
220
+ self.v_proj = nn.Linear(
221
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
222
+ )
223
+ self.o_proj = nn.Linear(
224
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
225
+ )
226
+ # unlike olmo, only on the head dim!
227
+ self.q_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)
228
+ # thus post q_norm does not need reshape
229
+ self.k_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)
230
+ self.sliding_window = config.sliding_window
231
+ if not (
232
+ self.config.use_sliding_window
233
+ and getattr(self.config, "sliding_window", None) is not None
234
+ and self.layer_idx >= self.config.max_window_layers
235
+ ):
236
+ self.sliding_window = None
237
+
238
+ def forward(
239
+ self,
240
+ hidden_states: torch.Tensor,
241
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
242
+ attention_mask: Optional[torch.Tensor],
243
+ past_key_value: Optional[Cache] = None,
244
+ cache_position: Optional[torch.LongTensor] = None,
245
+ **kwargs: Unpack[FlashAttentionKwargs],
246
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
247
+ input_shape = hidden_states.shape[:-1]
248
+ bsz, q_len = input_shape
249
+ hidden_shape = (*input_shape, -1, self.head_dim)
250
+
251
+ query_states = self.q_norm(self.q_proj(
252
+ hidden_states).view(hidden_shape)).transpose(1, 2)
253
+ key_states = self.k_norm(self.k_proj(
254
+ hidden_states).view(hidden_shape)).transpose(1, 2)
255
+ value_states = self.v_proj(hidden_states).view(
256
+ hidden_shape).transpose(1, 2)
257
+
258
+
259
+
260
+ cos, sin = position_embeddings
261
+ query_states, key_states = apply_rotary_pos_emb(
262
+ query_states, key_states, cos, sin)
263
+
264
+ if past_key_value is not None and kwargs.get("store_kv", False):
265
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
266
+ key_states, value_states = past_key_value.update(
267
+ key_states, value_states, self.layer_idx)
268
+ elif past_key_value is not None and not kwargs.get("store_kv", False) and len(past_key_value) > self.layer_idx:
269
+ # only retrive, do not store kv
270
+ past_key_states, past_value_states = past_key_value[self.layer_idx]
271
+ key_states = torch.cat(
272
+ [past_key_states, key_states], dim=-2)
273
+ value_states = torch.cat(
274
+ [past_value_states, value_states], dim=-2)
275
+
276
+ '''
277
+ attention_mask = attention_mask.bool() if attention_mask is not None else None
278
+ if torch.all(attention_mask): # decoding
279
+ query_states = query_states.transpose(1, 2)
280
+ key_states = key_states.transpose(1, 2)
281
+ value_states = value_states.transpose(1, 2)
282
+ attn_output = flash_attn_func(
283
+ query_states,
284
+ key_states,
285
+ value_states,
286
+ causal=False,
287
+ softmax_scale=self.scaling
288
+ )
289
+
290
+ else: # prefilling
291
+ attn_output = F.scaled_dot_product_attention(
292
+ query=query_states,
293
+ key=key_states,
294
+ value=value_states,
295
+ attn_mask=attention_mask,
296
+ is_causal=False,
297
+ scale=self.scaling,
298
+ enable_gqa=True
299
+ )
300
+ attn_output = attn_output.transpose(1, 2).contiguous()
301
+ '''
302
+
303
+ #print(query_states.shape, key_states.shape, value_states.shape)
304
+
305
+ # --- After RoPE and KV-cache handling, expand KV to all heads ---
306
+ key_states = repeat_kv(key_states, self.num_key_value_groups) # [B, H, K, D]
307
+ value_states = repeat_kv(value_states, self.num_key_value_groups) # [B, H, K, D]
308
+
309
+ # --- Convert a 0/1 or bool 4D mask into an *additive* mask, and align to [B, H, Q, K] ---
310
+ attn_mask = None
311
+ if attention_mask is not None:
312
+ k_len = key_states.shape[-2]
313
+ am = attention_mask
314
+ # Support either 2D [B, K] or 4D [B, 1/H, Q, K]
315
+ if am.dim() == 2:
316
+ am = am[:, None, None, :k_len] # -> [B,1,1,K]
317
+ else:
318
+ am = am[:, :, :, :k_len] # -> [B,1/H,Q,K]
319
+
320
+ finfo_min = torch.finfo(query_states.dtype).min
321
+ # 0/1 or bool -> float additive mask: 1->0, 0->-inf
322
+ if am.dtype == torch.bool:
323
+ zero = torch.zeros((), dtype=query_states.dtype, device=am.device)
324
+ neginf = torch.full((), finfo_min, dtype=query_states.dtype, device=am.device)
325
+ am = torch.where(am, zero, neginf)
326
+ else:
327
+ # For 0/1 float masks: values > 0 are treated as visible
328
+ am = am.to(query_states.dtype)
329
+ am = torch.where(am > 0, torch.zeros_like(am), torch.full_like(am, finfo_min))
330
+
331
+ # Expand to all heads
332
+ #if am.shape[1] == 1 and self.num_attention_heads > 1:
333
+ # am = am.expand(am.shape[0], self.num_attention_heads, am.shape[2], am.shape[3])
334
+
335
+ #attn_mask = am.contiguous()
336
+ attn_mask = am
337
+
338
+
339
+ bsz, q_len = input_shape
340
+
341
+ if q_len == 1 and past_key_value is not None:
342
+ # --- Decoding: flash-attn ---
343
+ q = query_states.transpose(1, 2) # [B,Q,H,D]
344
+ k = key_states.transpose(1, 2)
345
+ v = value_states.transpose(1, 2)
346
+ attn_output = flash_attn_func(
347
+ q, k, v,
348
+ causal=True, # For decoding, explicitly set causal=True
349
+ softmax_scale=self.scaling
350
+ )
351
+ attn_output = attn_output.transpose(1, 2).contiguous()
352
+ else:
353
+ attn_output = F.scaled_dot_product_attention(
354
+ query=query_states, # [B,H,Q,D]
355
+ key=key_states, # [B,H,K,D]
356
+ value=value_states, # [B,H,K,D]
357
+ attn_mask=attn_mask, # float additive mask
358
+ is_causal=False, # All constraints are already encoded in the mask
359
+ scale=self.scaling,
360
+ )
361
+ attn_output = attn_output.transpose(1, 2).contiguous() # -> [B,Q,H,D]
362
+
363
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
364
+ attn_output = self.o_proj(attn_output)
365
+ return attn_output, None # , attn_weights
366
+
367
+
368
+ class SDARDecoderLayer(GradientCheckpointingLayer):
369
+ def __init__(self, config: SDARConfig, layer_idx: int):
370
+ super().__init__()
371
+ self.hidden_size = config.hidden_size
372
+ self.self_attn = SDARAttention(config=config, layer_idx=layer_idx)
373
+ self.mlp = SDARMLP(config)
374
+ self.input_layernorm = SDARRMSNorm(
375
+ config.hidden_size, eps=config.rms_norm_eps)
376
+ self.post_attention_layernorm = SDARRMSNorm(
377
+ config.hidden_size, eps=config.rms_norm_eps)
378
+ if (
379
+ config.sliding_window and config._attn_implementation != "flash_attention_2"
380
+ ): # diff with Llama is this warning
381
+ logger.warning_once(
382
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
383
+ "unexpected results may be encountered."
384
+ )
385
+
386
+ def forward(
387
+ self,
388
+ hidden_states: torch.Tensor,
389
+ attention_mask: Optional[torch.Tensor] = None,
390
+ position_ids: Optional[torch.LongTensor] = None,
391
+ past_key_value: Optional[Cache] = None,
392
+ output_attentions: Optional[bool] = False,
393
+ use_cache: Optional[bool] = False,
394
+ store_kv: Optional[bool] = False,
395
+ cache_position: Optional[torch.LongTensor] = None,
396
+ # necessary, but kept here for BC
397
+ position_embeddings: Optional[Tuple[torch.Tensor,
398
+ torch.Tensor]] = None,
399
+ **kwargs: Unpack[FlashAttentionKwargs],
400
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
401
+ residual = hidden_states
402
+ hidden_states = self.input_layernorm(hidden_states)
403
+
404
+ # Self Attention
405
+ hidden_states, self_attn_weights = self.self_attn(
406
+ hidden_states=hidden_states,
407
+ attention_mask=attention_mask,
408
+ position_ids=position_ids,
409
+ past_key_value=past_key_value,
410
+ output_attentions=output_attentions,
411
+ use_cache=use_cache,
412
+ store_kv=store_kv,
413
+ cache_position=cache_position,
414
+ position_embeddings=position_embeddings,
415
+ **kwargs,
416
+ )
417
+ hidden_states = residual + hidden_states
418
+
419
+ # Fully Connected
420
+ residual = hidden_states
421
+ hidden_states = self.post_attention_layernorm(hidden_states)
422
+ hidden_states = self.mlp(hidden_states)
423
+ hidden_states = residual + hidden_states
424
+
425
+ outputs = (hidden_states,)
426
+ if output_attentions:
427
+ outputs += (self_attn_weights,)
428
+
429
+ return outputs
430
+
431
+
432
+ @auto_docstring
433
+ class SDARPreTrainedModel(PreTrainedModel):
434
+ config_class = SDARConfig
435
+ base_model_prefix = "model"
436
+ supports_gradient_checkpointing = True
437
+ _no_split_modules = ["SDARDecoderLayer"]
438
+ _skip_keys_device_placement = ["past_key_values"]
439
+ _supports_flash_attn_2 = True
440
+ _supports_sdpa = True
441
+ _supports_flex_attn = True
442
+ _supports_cache_class = True
443
+ _supports_quantized_cache = True
444
+ _supports_static_cache = True
445
+ _supports_attention_backend = True
446
+
447
+ def _init_weights(self, module):
448
+ std = self.config.initializer_range
449
+ if isinstance(module, nn.Linear):
450
+ module.weight.data.normal_(mean=0.0, std=std)
451
+ if module.bias is not None:
452
+ module.bias.data.zero_()
453
+ elif isinstance(module, nn.Embedding):
454
+ module.weight.data.normal_(mean=0.0, std=std)
455
+ if module.padding_idx is not None:
456
+ module.weight.data[module.padding_idx].zero_()
457
+ elif isinstance(module, SDARRMSNorm):
458
+ module.weight.data.fill_(1.0)
459
+
460
+
461
+ class SDARRotaryEmbedding(nn.Module):
462
+ def __init__(self, config: SDARConfig, device=None):
463
+ super().__init__()
464
+ # BC: "rope_type" was originally "type"
465
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
466
+ self.rope_type = config.rope_scaling.get(
467
+ "rope_type", config.rope_scaling.get("type"))
468
+ else:
469
+ self.rope_type = "default"
470
+ self.max_seq_len_cached = config.max_position_embeddings
471
+ self.original_max_seq_len = config.max_position_embeddings
472
+
473
+ self.config = config
474
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
475
+
476
+ inv_freq, self.attention_scaling = self.rope_init_fn(
477
+ self.config, device)
478
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
479
+ self.original_inv_freq = self.inv_freq
480
+
481
+ @torch.no_grad()
482
+ # power user: used with advanced RoPE types (e.g. dynamic rope)
483
+ @dynamic_rope_update
484
+ def forward(self, x, position_ids):
485
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(
486
+ position_ids.shape[0], -1, 1).to(x.device)
487
+ position_ids_expanded = position_ids[:, None, :].float()
488
+
489
+ device_type = x.device.type if isinstance(
490
+ x.device.type, str) and x.device.type != "mps" else "cpu"
491
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
492
+ freqs = (inv_freq_expanded.float() @
493
+ position_ids_expanded.float()).transpose(1, 2)
494
+ emb = torch.cat((freqs, freqs), dim=-1)
495
+ cos = emb.cos() * self.attention_scaling
496
+ sin = emb.sin() * self.attention_scaling
497
+
498
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
499
+
500
+
501
+ @auto_docstring
502
+ class SDARModel(SDARPreTrainedModel):
503
+ def __init__(self, config: SDARConfig):
504
+ super().__init__(config)
505
+ self.padding_idx = config.pad_token_id
506
+ self.vocab_size = config.vocab_size
507
+
508
+ self.embed_tokens = nn.Embedding(
509
+ config.vocab_size, config.hidden_size, self.padding_idx)
510
+ self.layers = nn.ModuleList(
511
+ [SDARDecoderLayer(config, layer_idx)
512
+ for layer_idx in range(config.num_hidden_layers)]
513
+ )
514
+ self.norm = SDARRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
515
+ self.rotary_emb = SDARRotaryEmbedding(config=config)
516
+ self.gradient_checkpointing = False
517
+
518
+ # Initialize weights and apply final processing
519
+ self.post_init()
520
+
521
+ def get_input_embeddings(self):
522
+ return self.embed_tokens
523
+
524
+ def set_input_embeddings(self, value):
525
+ self.embed_tokens = value
526
+
527
+ @can_return_tuple
528
+ @auto_docstring
529
+ def forward(
530
+ self,
531
+ input_ids: Optional[torch.LongTensor] = None,
532
+ attention_mask: Optional[torch.Tensor] = None,
533
+ position_ids: Optional[torch.LongTensor] = None,
534
+ past_key_values: Optional[Cache] = None,
535
+ inputs_embeds: Optional[torch.FloatTensor] = None,
536
+ use_cache: Optional[bool] = None,
537
+ store_kv: Optional[bool] = None,
538
+ output_attentions: Optional[bool] = None,
539
+ output_hidden_states: Optional[bool] = None,
540
+ cache_position: Optional[torch.LongTensor] = None,
541
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
542
+ ) -> BaseModelOutputWithPast:
543
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
544
+ output_hidden_states = (
545
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
546
+ )
547
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
548
+
549
+ if (input_ids is None) ^ (inputs_embeds is not None):
550
+ raise ValueError(
551
+ "You must specify exactly one of input_ids or inputs_embeds")
552
+
553
+ if self.gradient_checkpointing and self.training and use_cache:
554
+ logger.warning_once(
555
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
556
+ )
557
+ use_cache = False
558
+
559
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
560
+ if not isinstance(past_key_values, (type(None), Cache)):
561
+ raise ValueError(
562
+ "The `past_key_values` should be either a `Cache` object or `None`.")
563
+
564
+ if inputs_embeds is None:
565
+ inputs_embeds = self.embed_tokens(input_ids)
566
+
567
+ if use_cache and past_key_values is None:
568
+ past_key_values = DynamicCache()
569
+
570
+ if cache_position is None:
571
+ past_seen_tokens = past_key_values.get_seq_length(
572
+ ) if past_key_values is not None else 0
573
+ cache_position = torch.arange(
574
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
575
+ )
576
+
577
+ if position_ids is None:
578
+ position_ids = cache_position.unsqueeze(0)
579
+
580
+ # causal_mask = self._update_causal_mask(
581
+ # attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
582
+ # )
583
+
584
+ hidden_states = inputs_embeds
585
+
586
+ # create position embeddings to be shared across the decoder layers
587
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
588
+
589
+ # decoder layers
590
+ all_hidden_states = () if output_hidden_states else None
591
+ all_self_attns = () if output_attentions else None
592
+
593
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
594
+ if output_hidden_states:
595
+ all_hidden_states += (hidden_states,)
596
+
597
+ layer_outputs = decoder_layer(
598
+ hidden_states,
599
+ attention_mask=attention_mask,
600
+ position_ids=position_ids,
601
+ past_key_value=past_key_values,
602
+ output_attentions=output_attentions,
603
+ use_cache=use_cache,
604
+ store_kv=store_kv,
605
+ cache_position=cache_position,
606
+ position_embeddings=position_embeddings,
607
+ **flash_attn_kwargs,
608
+ )
609
+
610
+ hidden_states = layer_outputs[0]
611
+
612
+ if output_attentions:
613
+ all_self_attns += (layer_outputs[1],)
614
+
615
+ hidden_states = self.norm(hidden_states)
616
+
617
+ # add hidden states from the last decoder layer
618
+ if output_hidden_states:
619
+ all_hidden_states += (hidden_states,)
620
+
621
+ return BaseModelOutputWithPast(
622
+ last_hidden_state=hidden_states,
623
+ past_key_values=past_key_values if use_cache else None,
624
+ hidden_states=all_hidden_states,
625
+ attentions=all_self_attns,
626
+ )
627
+
628
+ def _update_causal_mask(
629
+ self,
630
+ attention_mask: Union[torch.Tensor, "BlockMask"],
631
+ input_tensor: torch.Tensor,
632
+ cache_position: torch.Tensor,
633
+ past_key_values: Cache,
634
+ output_attentions: bool = False,
635
+ ):
636
+ if self.config._attn_implementation == "flash_attention_2":
637
+ if attention_mask is not None and past_key_values is not None:
638
+ is_padding_right = attention_mask[:, -
639
+ 1].sum().item() != input_tensor.size()[0]
640
+ if is_padding_right:
641
+ raise ValueError(
642
+ "You are attempting to perform batched generation with padding_side='right'"
643
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen3. Make sure to "
644
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
645
+ )
646
+ if attention_mask is not None and 0.0 in attention_mask:
647
+ return attention_mask
648
+ return None
649
+ if self.config._attn_implementation == "flex_attention":
650
+ if isinstance(attention_mask, torch.Tensor):
651
+ seq_len_q, seq_len_kv = attention_mask.shape
652
+ assert seq_len_q == seq_len_kv, f"got {attention_mask.shape=}"
653
+ attention_mask = create_block_mask(
654
+ # 2d bool tensor, shape: [2*seqlen, 2*seqlen]
655
+ lambda b, h, q_idx, kv_idx: attention_mask[q_idx, kv_idx],
656
+ B=None, H=None, Q_LEN=seq_len_q, KV_LEN=seq_len_kv,
657
+ )
658
+ else:
659
+ # Here we pass in flex mask computed externally
660
+ assert isinstance(attention_mask, BlockMask)
661
+ return attention_mask
662
+
663
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
664
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
665
+ # to infer the attention mask.
666
+ past_seen_tokens = past_key_values.get_seq_length(
667
+ ) if past_key_values is not None else 0
668
+ using_static_cache = isinstance(past_key_values, StaticCache)
669
+ using_sliding_window_cache = isinstance(
670
+ past_key_values, SlidingWindowCache)
671
+
672
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
673
+ if (
674
+ self.config._attn_implementation == "sdpa"
675
+ and not (using_static_cache or using_sliding_window_cache)
676
+ and not output_attentions
677
+ ):
678
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
679
+ attention_mask,
680
+ inputs_embeds=input_tensor,
681
+ past_key_values_length=past_seen_tokens,
682
+ sliding_window=self.config.sliding_window,
683
+ is_training=self.training,
684
+ ):
685
+ return None
686
+
687
+ dtype = input_tensor.dtype
688
+ min_dtype = torch.finfo(dtype).min
689
+ sequence_length = input_tensor.shape[1]
690
+ # SlidingWindowCache or StaticCache
691
+ if using_sliding_window_cache or using_static_cache:
692
+ target_length = past_key_values.get_max_cache_shape()
693
+ # DynamicCache or no cache
694
+ else:
695
+ target_length = (
696
+ attention_mask.shape[-1]
697
+ if isinstance(attention_mask, torch.Tensor)
698
+ else past_seen_tokens + sequence_length + 1
699
+ )
700
+
701
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
702
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
703
+ attention_mask,
704
+ sequence_length=sequence_length,
705
+ target_length=target_length,
706
+ dtype=dtype,
707
+ cache_position=cache_position,
708
+ batch_size=input_tensor.shape[0],
709
+ config=self.config,
710
+ past_key_values=past_key_values,
711
+ )
712
+
713
+ if (
714
+ self.config._attn_implementation == "sdpa"
715
+ and attention_mask is not None
716
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
717
+ and not output_attentions
718
+ ):
719
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
720
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
721
+ # Details: https://github.com/pytorch/pytorch/issues/110213
722
+ causal_mask = AttentionMaskConverter._unmask_unattended(
723
+ causal_mask, min_dtype)
724
+
725
+ return causal_mask
726
+
727
+ @staticmethod
728
+ def _prepare_4d_causal_attention_mask_with_cache_position(
729
+ attention_mask: torch.Tensor,
730
+ sequence_length: int,
731
+ target_length: int,
732
+ dtype: torch.dtype,
733
+ cache_position: torch.Tensor,
734
+ batch_size: int,
735
+ config: SDARConfig,
736
+ past_key_values: Cache,
737
+ ):
738
+ """
739
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
740
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
741
+ Args:
742
+ attention_mask (`torch.Tensor`):
743
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
744
+ sequence_length (`int`):
745
+ The sequence length being processed.
746
+ target_length (`int`):
747
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
748
+ dtype (`torch.dtype`):
749
+ The dtype to use for the 4D attention mask.
750
+ cache_position (`torch.Tensor`):
751
+ Indices depicting the position of the input sequence tokens in the sequence.
752
+ batch_size (`torch.Tensor`):
753
+ Batch size.
754
+ config (`SDARConfig`):
755
+ The model's configuration class
756
+ past_key_values (`Cache`):
757
+ The cache class that is being used currently to generate
758
+ """
759
+ if attention_mask is not None and attention_mask.dim() == 4:
760
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
761
+ causal_mask = attention_mask
762
+ else:
763
+ min_dtype = torch.finfo(dtype).min
764
+ causal_mask = torch.full(
765
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
766
+ )
767
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
768
+ -1, 1
769
+ )
770
+ text_config = config.get_text_config()
771
+ if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:
772
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
773
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
774
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
775
+ sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (
776
+ cache_position.reshape(-1, 1) -
777
+ text_config.sliding_window
778
+ )
779
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
780
+ causal_mask *= diagonal_attend_mask
781
+ causal_mask = causal_mask[None, None,
782
+ :, :].expand(batch_size, 1, -1, -1)
783
+ if attention_mask is not None:
784
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
785
+ if attention_mask.shape[-1] > target_length:
786
+ attention_mask = attention_mask[:, :target_length]
787
+ mask_length = attention_mask.shape[-1]
788
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
789
+ causal_mask.device
790
+ )
791
+ padding_mask = padding_mask == 0
792
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
793
+ padding_mask, min_dtype
794
+ )
795
+ return causal_mask
796
+
797
+
798
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs):
799
+ ...
800
+
801
+
802
+ @auto_docstring
803
+ class SDARForCausalLM(SDARPreTrainedModel, GenerationMixin):
804
+ _tied_weights_keys = ["lm_head.weight"]
805
+ _tp_plan = {"lm_head": "colwise_rep"}
806
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
807
+
808
+ def __init__(self, config):
809
+ super().__init__(config)
810
+ self.model = SDARModel(config)
811
+ self.vocab_size = config.vocab_size
812
+ self.lm_head = nn.Linear(
813
+ config.hidden_size, config.vocab_size, bias=False)
814
+
815
+ # Initialize weights and apply final processing
816
+ self.post_init()
817
+
818
+ def get_input_embeddings(self):
819
+ return self.model.embed_tokens
820
+
821
+ def set_input_embeddings(self, value):
822
+ self.model.embed_tokens = value
823
+
824
+ def get_output_embeddings(self):
825
+ return self.lm_head
826
+
827
+ def set_output_embeddings(self, new_embeddings):
828
+ self.lm_head = new_embeddings
829
+
830
+ def set_decoder(self, decoder):
831
+ self.model = decoder
832
+
833
+ def get_decoder(self):
834
+ return self.model
835
+
836
+ @can_return_tuple
837
+ @auto_docstring
838
+ def forward(
839
+ self,
840
+ input_ids: Optional[torch.LongTensor] = None,
841
+ attention_mask: Optional[torch.Tensor] = None,
842
+ position_ids: Optional[torch.LongTensor] = None,
843
+ past_key_values: Optional[Cache] = None,
844
+ inputs_embeds: Optional[torch.FloatTensor] = None,
845
+ labels: Optional[torch.LongTensor] = None,
846
+ use_cache: Optional[bool] = None,
847
+ output_attentions: Optional[bool] = None,
848
+ output_hidden_states: Optional[bool] = None,
849
+ cache_position: Optional[torch.LongTensor] = None,
850
+ logits_to_keep: Union[int, torch.Tensor] = 0,
851
+ **kwargs: Unpack[KwargsForCausalLM],
852
+ ) -> CausalLMOutputWithPast:
853
+ r"""
854
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
855
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
856
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
857
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
858
+ Example:
859
+ ```python
860
+ >>> from transformers import AutoTokenizer, SDARForCausalLM
861
+ >>> model = SDARForCausalLM.from_pretrained("DiffuOpen/SDAR-1.7B-Chat")
862
+ >>> tokenizer = AutoTokenizer.from_pretrained("DiffuOpen/SDAR-1.7B-Chat")
863
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
864
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
865
+ >>> # Generate
866
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
867
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
868
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
869
+ ```"""
870
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
871
+ output_hidden_states = (
872
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
873
+ )
874
+
875
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
876
+ outputs: BaseModelOutputWithPast = self.model(
877
+ input_ids=input_ids,
878
+ attention_mask=attention_mask,
879
+ position_ids=position_ids,
880
+ past_key_values=past_key_values,
881
+ inputs_embeds=inputs_embeds,
882
+ use_cache=use_cache,
883
+ output_attentions=output_attentions,
884
+ output_hidden_states=output_hidden_states,
885
+ cache_position=cache_position,
886
+ **kwargs,
887
+ )
888
+
889
+ hidden_states = outputs.last_hidden_state
890
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
891
+ slice_indices = slice(-logits_to_keep,
892
+ None) if isinstance(logits_to_keep, int) else logits_to_keep
893
+ hidden_states = hidden_states[:, slice_indices, :].contiguous()
894
+ fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.training
895
+ if fuse_linear_and_cross_entropy:
896
+ # When using fused_linear_ce_loss, we do not compute the whole logits on HBM
897
+ logits = None
898
+ else:
899
+ logits = self.lm_head(hidden_states)
900
+
901
+ loss = None
902
+ if labels is not None:
903
+ # FusedLinearCrossEntropyLoss will be implemented by monkey patch when training
904
+ # We don't use it when inferencing
905
+ loss_fct = nn.CrossEntropyLoss() # nn.CE
906
+ loss = loss_fct(
907
+ logits.view(-1, self.config.vocab_size), labels.view(-1))
908
+
909
+ return CausalLMOutputWithPast(
910
+ loss=loss,
911
+ logits=logits,
912
+ past_key_values=outputs.past_key_values,
913
+ hidden_states=outputs.hidden_states,
914
+ attentions=outputs.attentions,
915
+ )
916
+
917
+
918
+ __all__ = [
919
+ "SDARForCausalLM",
920
+ "SDARModel",
921
+ "SDARPreTrainedModel",
922
+ ]