DatPySci commited on
Commit
6bb1db3
·
verified ·
1 Parent(s): b50c53e

Upload folder using huggingface_hub

Browse files
models/dLMs-block8-epoch1/chat_template.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% endif %}{% if system_message is defined %}{{ system_message }}{% endif %}{% for message in loop_messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ content }}{% elif message['role'] == 'assistant' %}{{ content }}{% endif %}{% endfor %}
models/dLMs-block8-epoch1/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.SDARForCausalLM",
10
+ "AutoModelForCausalLM": "modeling_sdar.SDARForCausalLM"
11
+ },
12
+ "block_size": 8,
13
+ "bos_token_id": 2,
14
+ "debug": false,
15
+ "eos_token_id": 3,
16
+ "ep_size": 1,
17
+ "fuse_cross_entropy": true,
18
+ "head_dim": 128,
19
+ "hidden_act": "silu",
20
+ "hidden_size": 768,
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 3072,
23
+ "mask_token_id": 2196,
24
+ "max_position_embeddings": 2048,
25
+ "max_window_layers": 24,
26
+ "micro_forward": false,
27
+ "model_type": "sdar",
28
+ "num_attention_heads": 12,
29
+ "num_hidden_layers": 12,
30
+ "num_key_value_heads": 2,
31
+ "rms_norm_eps": 1e-06,
32
+ "rope_scaling": null,
33
+ "rope_theta": 1000000,
34
+ "skip_checkpoint": false,
35
+ "sliding_window": 2048,
36
+ "tie_word_embeddings": true,
37
+ "torch_dtype": "bfloat16",
38
+ "transformers_version": "4.52.4",
39
+ "use_cache": false,
40
+ "use_deepep": false,
41
+ "use_sliding_window": false,
42
+ "vocab_size": 2200
43
+ }
models/dLMs-block8-epoch1/configuration_sdar.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 151936):
38
+ Vocabulary size of the SDAR model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`SDARModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 22016):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 32):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
55
+ head_dim (`int`, *optional*, defaults to 128):
56
+ The attention head dimension.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ rope_scaling (`Dict`, *optional*):
73
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
74
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
75
+ accordingly.
76
+ Expected contents:
77
+ `rope_type` (`str`):
78
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
79
+ 'llama3'], with 'default' being the original RoPE implementation.
80
+ `factor` (`float`, *optional*):
81
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
82
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
83
+ original maximum pre-trained length.
84
+ `original_max_position_embeddings` (`int`, *optional*):
85
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
86
+ pretraining.
87
+ `attention_factor` (`float`, *optional*):
88
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
89
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
90
+ `factor` field to infer the suggested value.
91
+ `beta_fast` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 32.
94
+ `beta_slow` (`float`, *optional*):
95
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
96
+ ramp function. If unspecified, it defaults to 1.
97
+ `short_factor` (`List[float]`, *optional*):
98
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
99
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
100
+ size divided by the number of attention heads divided by 2
101
+ `long_factor` (`List[float]`, *optional*):
102
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
103
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
104
+ size divided by the number of attention heads divided by 2
105
+ `low_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
107
+ `high_freq_factor` (`float`, *optional*):
108
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
109
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
110
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
111
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
112
+ Whether to use sliding window attention.
113
+ sliding_window (`int`, *optional*, defaults to 4096):
114
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
115
+ max_window_layers (`int`, *optional*, defaults to 28):
116
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
117
+ attention_dropout (`float`, *optional*, defaults to 0.0):
118
+ The dropout ratio for the attention probabilities.
119
+
120
+ ```python
121
+ >>> from transformers import SDARModel, SDARConfig
122
+
123
+ >>> # Initializing a SDAR style configuration
124
+ >>> configuration = SDARConfig()
125
+
126
+ >>> # Initializing a model from the SDAR-8B style configuration
127
+ >>> model = SDARModel(configuration)
128
+
129
+ >>> # Accessing the model configuration
130
+ >>> configuration = model.config
131
+ ```"""
132
+
133
+ model_type = "sdar"
134
+ keys_to_ignore_at_inference = ["past_key_values"]
135
+
136
+ # Default tensor parallel plan for base model `SDAR`
137
+ base_model_tp_plan = {
138
+ "layers.*.self_attn.q_proj": "colwise",
139
+ "layers.*.self_attn.k_proj": "colwise",
140
+ "layers.*.self_attn.v_proj": "colwise",
141
+ "layers.*.self_attn.o_proj": "rowwise",
142
+ "layers.*.mlp.gate_proj": "colwise",
143
+ "layers.*.mlp.up_proj": "colwise",
144
+ "layers.*.mlp.down_proj": "rowwise",
145
+ }
146
+ base_model_pp_plan = {
147
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
148
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
149
+ "norm": (["hidden_states"], ["hidden_states"]),
150
+ }
151
+
152
+ def __init__(
153
+ self,
154
+ vocab_size=151936,
155
+ hidden_size=4096,
156
+ intermediate_size=22016,
157
+ num_hidden_layers=32,
158
+ num_attention_heads=32,
159
+ num_key_value_heads=32,
160
+ head_dim=128,
161
+ hidden_act="silu",
162
+ max_position_embeddings=32768,
163
+ initializer_range=0.02,
164
+ rms_norm_eps=1e-6,
165
+ use_cache=True,
166
+ tie_word_embeddings=False,
167
+ rope_theta=10000.0,
168
+ rope_scaling=None,
169
+ attention_bias=False,
170
+ use_sliding_window=False,
171
+ sliding_window=4096,
172
+ max_window_layers=28,
173
+ attention_dropout=0.0,
174
+ **kwargs,
175
+ ):
176
+ self.vocab_size = vocab_size
177
+ self.max_position_embeddings = max_position_embeddings
178
+ self.hidden_size = hidden_size
179
+ self.intermediate_size = intermediate_size
180
+ self.num_hidden_layers = num_hidden_layers
181
+ self.num_attention_heads = num_attention_heads
182
+ self.use_sliding_window = use_sliding_window
183
+ self.sliding_window = sliding_window # we check `use_sliding_window` in the modeling code
184
+ self.max_window_layers = max_window_layers
185
+
186
+ # for backward compatibility
187
+ if num_key_value_heads is None:
188
+ num_key_value_heads = num_attention_heads
189
+
190
+ self.num_key_value_heads = num_key_value_heads
191
+ self.head_dim = head_dim
192
+ self.hidden_act = hidden_act
193
+ self.initializer_range = initializer_range
194
+ self.rms_norm_eps = rms_norm_eps
195
+ self.use_cache = use_cache
196
+ self.rope_theta = rope_theta
197
+ self.rope_scaling = rope_scaling
198
+ self.attention_bias = attention_bias
199
+ self.attention_dropout = attention_dropout
200
+ # Validate the correctness of rotary position embeddings parameters
201
+ # BC: if there is a 'type' field, move it to 'rope_type'.
202
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
203
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
204
+ rope_config_validation(self)
205
+
206
+ super().__init__(
207
+ tie_word_embeddings=tie_word_embeddings,
208
+ **kwargs,
209
+ )
210
+
211
+
212
+ __all__ = ["SDARConfig"]
models/dLMs-block8-epoch1/fused_linear_diffusion_cross_entropy.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Code adapted from
4
+ # https://github.com/fla-org/flash-linear-attention/blob/main/fla/modules/fused_linear_cross_entropy.py
5
+ # Implementation of element-wise division of cross entropy loss
6
+
7
+
8
+ # Code adapted from
9
+ # https://github.com/linkedin/Liger-Kernel/blob/main/src/liger_kernel/ops/fused_linear_cross_entropy.py
10
+
11
+ from functools import partial
12
+ from typing import Optional, Tuple
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import triton
18
+ import triton.language as tl
19
+ from torch.distributed import DeviceMesh
20
+ from torch.distributed.tensor import DTensor, Replicate, Shard, distribute_module
21
+ from torch.distributed.tensor.parallel import ParallelStyle
22
+
23
+ # The hard limit of TRITON_MAX_TENSOR_NUMEL is 1048576
24
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/language/core.py#L19
25
+ # However, setting limit as 65536 as in LayerNorm tutorial is faster because of less register spilling
26
+ # The optimal maximum block size depends on your hardware, your kernel, and your dtype
27
+ MAX_FUSED_SIZE = 65536 // 2
28
+
29
+
30
+ @triton.heuristics({
31
+ 'HAS_SCALE': lambda args: args['scale'] is not None
32
+ })
33
+ @triton.autotune(
34
+ configs=[
35
+ triton.Config({}, num_warps=num_warps)
36
+ for num_warps in [1, 2, 4, 8, 16, 32]
37
+ ],
38
+ key=['D']
39
+ )
40
+ @triton.jit
41
+ def logsumexp_fwd_kernel(
42
+ x,
43
+ z,
44
+ scale,
45
+ D: tl.constexpr,
46
+ B: tl.constexpr,
47
+ HAS_SCALE: tl.constexpr
48
+ ):
49
+ i_n, i_d = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64)
50
+ o_d = i_d * B + tl.arange(0, B)
51
+ m_d = o_d < D
52
+
53
+ b_x = tl.load(x + i_n * D + o_d, mask=m_d, other=-float('inf'))
54
+ if HAS_SCALE:
55
+ b_x = b_x * scale
56
+ b_m = tl.max(b_x, 0)
57
+ b_z = tl.log(tl.sum(tl.exp(b_x - b_m), 0)) + b_m
58
+ tl.store(z + i_n * tl.cdiv(D, B) + i_d, b_z)
59
+
60
+
61
+ def logsumexp_fwd(
62
+ x,
63
+ scale: Optional[float] = None,
64
+ dtype: Optional[torch.dtype] = None
65
+ ):
66
+ r"""
67
+ Compute the logsumexp of the input tensor over the last dimension.
68
+
69
+ Args:
70
+ x (Tensor):
71
+ The input tensor of any shape.
72
+ scale (Optional[float]):
73
+ The scale applied to the input tensor. Default: `None`.
74
+ dtype (Optional[torch.dtype]):
75
+ The data type of the output tensor. Default: `None`.
76
+ Returns:
77
+ Tensor: The logsumexp of the input tensor.
78
+ """
79
+
80
+ shape = x.shape
81
+ x = x.view(-1, shape[-1])
82
+ N, D = x.shape
83
+ B = min(triton.next_power_of_2(D), 64 * 1024)
84
+ ND = triton.cdiv(D, B)
85
+
86
+ z = x.new_empty(N, ND, dtype=torch.float)
87
+ logsumexp_fwd_kernel[(N, ND)](
88
+ x=x,
89
+ z=z,
90
+ scale=scale,
91
+ D=D,
92
+ B=B
93
+ )
94
+ z = z.logsumexp(-1).view(*shape[:-1])
95
+ if dtype is not None and dtype != torch.float:
96
+ z = z.to(dtype)
97
+ return z
98
+
99
+ @triton.jit
100
+ def cross_entropy_kernel(
101
+ logits,
102
+ lse,
103
+ target,
104
+ p_mask,
105
+ loss,
106
+ total,
107
+ ignore_index,
108
+ label_smoothing: tl.constexpr,
109
+ logit_scale: tl.constexpr,
110
+ reduction: tl.constexpr,
111
+ V: tl.constexpr,
112
+ BV: tl.constexpr
113
+ ):
114
+ """
115
+ This kernel computes both cross entropy loss and the gradient of the input.
116
+ We only consider hard label + mean reduction for now.
117
+ Please refer to https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html for the math.
118
+
119
+ Args:
120
+ logits:
121
+ Pointer to logits tensor.
122
+ lse:
123
+ Pointer to logsumexp tensor.
124
+ target: Pointer to target tensor.
125
+ loss:
126
+ Pointer to tensor to store the loss.
127
+ V (int):
128
+ The number of columns in the input tensor.
129
+ total (int):
130
+ The number of non-ignored classes.
131
+ ignore_index (int):
132
+ The index to ignore in the target.
133
+ label_smoothing (float):
134
+ The amount of smoothing when computing the loss, where 0.0 means no smoothing.
135
+ reduction (str):
136
+ The string for the reduction to apply
137
+ BV (int):
138
+ The block size for vocab.
139
+ """
140
+
141
+ # https://github.com/triton-lang/triton/issues/1058
142
+ # If B*T*V is too large, i_n * stride will overflow out of int32, so we convert to int64
143
+ i_n = tl.program_id(0).to(tl.int64)
144
+ NV = tl.cdiv(V, BV)
145
+
146
+ # 1. Load target first because if the target is ignore_index, we can return right away
147
+ b_y = tl.load(target + i_n)
148
+ # load p_mask
149
+ b_p_mask = tl.load(p_mask + i_n)
150
+
151
+ # 2. locate the start index
152
+ logits += i_n * V
153
+
154
+ if b_y == ignore_index:
155
+ # set all x as 0
156
+ for i in range(0, V, BV):
157
+ o_v = i + tl.arange(0, BV)
158
+ tl.store(logits + o_v, 0.0, mask=o_v < V)
159
+ return
160
+
161
+ # Online softmax: 2 loads + 1 store (compared with 3 loads + 1 store for the safe softmax)
162
+ # Refer to Algorithm 3 in the paper: https://arxiv.org/pdf/1805.02867
163
+
164
+ # 3. [Online softmax] first pass: compute logsumexp
165
+ # we did this in anouter kernel
166
+ b_l = tl.load(logits + b_y) * logit_scale
167
+ b_lse = tl.load(lse + i_n)
168
+
169
+ # 4. Calculate the loss
170
+ # loss = lse - logits_l
171
+ # celoss = -log(q_y) = -log(softmax(x_y))
172
+ b_loss = (b_lse - b_l) / b_p_mask # Diffusion Scaled '1/t'
173
+
174
+ # Label smoothing is a general case of normal cross entropy
175
+ # See the full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issue-2503665310
176
+ b_z = 0.0
177
+ eps = label_smoothing / V
178
+
179
+ # We need tl.debug_barrier() as mentioned in
180
+ # https://github.com/triton-lang/triton/blob/ba42a5c68fd0505f8c42f4202d53be0f8d9a5fe0/python/triton/ops/cross_entropy.py#L34
181
+ tl.debug_barrier()
182
+
183
+ # 5. [Online Softmax] Second pass: compute gradients
184
+ # For 'mean' reduction, gradients are normalized by number of non-ignored elements
185
+ # dx_y = (softmax(x_y) - 1) / N
186
+ # dx_i = softmax(x_i) / N, i != y
187
+ # For label smoothing:
188
+ # dx_i = (softmax(x_y) - label_smoothing / V) / N, i != y
189
+ # dx_y = (softmax(x_y) - label_smoothing / V - (1 - label_smoothing)) / N
190
+ # = dx_i - (1 - label_smoothing) / N
191
+ for iv in range(0, NV):
192
+ o_v = iv * BV + tl.arange(0, BV)
193
+ b_logits = tl.load(logits + o_v, mask=o_v < V, other=float('-inf')) * logit_scale
194
+ if label_smoothing > 0:
195
+ # scale X beforehand to avoid overflow
196
+ b_z += tl.sum(tl.where(o_v < V, -eps * b_logits, 0.0))
197
+ b_p = (tl.exp(b_logits - b_lse) - eps) * logit_scale
198
+ b_p /= b_p_mask # 修改
199
+ if reduction == "mean":
200
+ b_p = b_p / total
201
+ tl.store(logits + o_v, b_p, mask=o_v < V)
202
+
203
+ tl.debug_barrier()
204
+
205
+ # Orginal loss = H(q, p), with label smoothing regularization = H(q', p) and (label_smoothing / V) = eps
206
+ # H(q', p) = (1 - label_smoothing) * H(q, p) + label_smoothing * H(u, p)
207
+ # = (1 - label_smoothing) * H(q, p) + eps * sum(logsoftmax(x_i))
208
+ # By using m (global max of xi) and d (sum of e^(xi-m)), we can simplify as:
209
+ # = (1 - label_smoothing) * H(q, p) + (-sum(x_i * eps) + label_smoothing * (m + logd))
210
+ # Refer to H(q', p) in section 7 of the paper:
211
+ # https://arxiv.org/pdf/1512.00567
212
+ # pytorch:
213
+ # https://github.com/pytorch/pytorch/blob/2981534f54d49fa3a9755c9b0855e7929c2527f0/aten/src/ATen/native/LossNLL.cpp#L516
214
+ # See full derivation at https://github.com/linkedin/Liger-Kernel/pull/198#issuecomment-2333753087
215
+ if label_smoothing > 0:
216
+ b_loss = b_loss * (1 - label_smoothing) + (b_z + label_smoothing * b_lse)
217
+
218
+ # 6. Specially handle the i==y case where `dx_y = (softmax(x_y) - (1 - label_smoothing) / N`
219
+ b_l = tl.load(logits + b_y)
220
+
221
+ # Normalize the loss by the number of non-ignored elements if reduction is "mean"
222
+ if reduction == 'mean':
223
+ b_loss = b_loss / total
224
+ # b_l += (label_smoothing - 1) / total * logit_scale
225
+ # b_l has already been divided by b_p_mask and total
226
+ b_l += (label_smoothing - 1) / b_p_mask / total * logit_scale
227
+ else:
228
+ # b_l += (label_smoothing - 1) * logit_scale
229
+ b_l += (label_smoothing - 1) / b_p_mask * logit_scale
230
+
231
+ tl.store(loss + i_n, b_loss)
232
+ tl.store(logits + b_y, b_l)
233
+
234
+
235
+ @triton.jit
236
+ def elementwise_mul_kernel(
237
+ x,
238
+ g,
239
+ N: tl.constexpr,
240
+ B: tl.constexpr
241
+ ):
242
+ """
243
+ This function multiplies each element of the tensor pointed by x with the value pointed by g.
244
+ The multiplication is performed in-place on the tensor pointed by x.
245
+
246
+ Parameters:
247
+ x:
248
+ Pointer to the input tensor.
249
+ g:
250
+ Pointer to the gradient output value.
251
+ N (int):
252
+ The number of columns in the input tensor.
253
+ B (int):
254
+ The block size for Triton operations.
255
+ """
256
+
257
+ # Get the program ID and convert it to int64 to avoid overflow
258
+ i_x = tl.program_id(0).to(tl.int64)
259
+ o_x = i_x * B + tl.arange(0, B)
260
+
261
+ # Load the gradient output value
262
+ b_g = tl.load(g)
263
+ b_x = tl.load(x + o_x, mask=o_x < N)
264
+ tl.store(x + o_x, b_x * b_g, mask=o_x < N)
265
+
266
+
267
+ def fused_linear_cross_entropy_forward(
268
+ x: torch.Tensor,
269
+ target: torch.LongTensor,
270
+ weight: torch.Tensor,
271
+ bias: torch.Tensor = None,
272
+ p_mask: torch.Tensor = None,
273
+ ignore_index: int = -100,
274
+ label_smoothing: float = 0.0,
275
+ logit_scale: float = 1.0,
276
+ num_chunks: int = 8,
277
+ reduction: str = "mean"
278
+ ):
279
+ device = x.device
280
+ # inputs have shape: [N, H]
281
+ # materialized activations will have shape: [N, V]
282
+ # the increase in memory = [N, V]
283
+ # reduction can be achieved by partitioning the number of tokens N into smaller chunks.
284
+
285
+ # ideally, we would like to achieve the same memory consumption as [N, H],
286
+ # so the expected chunk size should be:
287
+ # NC = ceil(V / H)
288
+ # C = ceil(N / NC)
289
+ # for ex: N = 4096*4, V = 32000, H = 4096 ==> NC = 8, C = ceil(N / NC) = 2048
290
+ N, H, V = *x.shape, weight.shape[0]
291
+ BV = min(MAX_FUSED_SIZE, triton.next_power_of_2(V))
292
+ # TODO: in real cases, we may need to limit the number of chunks NC to
293
+ # ensure the precisions of accumulated gradients
294
+ NC = min(num_chunks, triton.cdiv(V, H))
295
+ C = triton.next_power_of_2(triton.cdiv(N, NC))
296
+ NC = triton.cdiv(N, C)
297
+
298
+ # [N, H]
299
+ dx = torch.zeros_like(x, device=device)
300
+ # [V, H]
301
+ dw = torch.zeros_like(weight, device=device, dtype=torch.float) if weight is not None else None
302
+ # [V]
303
+ db = torch.zeros_like(bias, device=device, dtype=torch.float) if bias is not None else None
304
+ # [N]
305
+ loss = torch.zeros(N, device=device, dtype=torch.float)
306
+
307
+ total = target.ne(ignore_index).sum().item()
308
+
309
+ for ic in range(NC):
310
+ start, end = ic * C, min((ic + 1) * C, N)
311
+ # [C, N]
312
+ c_x = x[start:end]
313
+ # when doing matmul, use the original precision
314
+ # [C, V]
315
+ c_logits = F.linear(c_x, weight, bias)
316
+ c_target = target[start:end]
317
+ c_p_mask = p_mask[start:end]
318
+ # [C]
319
+ # keep lse in fp32 to maintain precision
320
+ c_lse = logsumexp_fwd(c_logits, scale=logit_scale, dtype=torch.float)
321
+
322
+ # unreduced loss
323
+ c_loss = loss[start:end]
324
+
325
+ # Here we calculate the gradient of c_logits in place so we can save memory.
326
+ cross_entropy_kernel[(c_logits.shape[0],)](
327
+ logits=c_logits,
328
+ lse=c_lse,
329
+ target=c_target,
330
+ p_mask=c_p_mask,
331
+ loss=c_loss,
332
+ total=total,
333
+ ignore_index=ignore_index,
334
+ label_smoothing=label_smoothing,
335
+ logit_scale=logit_scale,
336
+ reduction=reduction,
337
+ V=V,
338
+ BV=BV,
339
+ num_warps=32
340
+ )
341
+
342
+ # gradient of logits is computed in-place by the above triton kernel and is of shape: C x V
343
+ # thus dx should be of shape: C x H
344
+ dx[start:end] = torch.mm(c_logits, weight)
345
+
346
+ # keep dw in fp32 to maintain precision
347
+ if weight is not None:
348
+ dw += c_logits.t() @ c_x
349
+
350
+ if bias is not None:
351
+ torch.add(input=db, other=c_logits.sum(0), out=db)
352
+
353
+ loss = loss.sum()
354
+ if dw is not None:
355
+ dw = dw.to(weight)
356
+ if db is not None:
357
+ db = db.to(bias)
358
+ return loss, dx, dw, db
359
+
360
+
361
+ def fused_linear_cross_entropy_backward(
362
+ do: torch.Tensor,
363
+ dx: torch.Tensor,
364
+ dw: torch.Tensor,
365
+ db: torch.Tensor
366
+ ):
367
+ # If cross entropy is the last layer, do is 1.0. Skip the mul to save time
368
+ if torch.ne(do, torch.tensor(1.0, device=do.device)):
369
+ # We use a Triton kernel instead of a PyTorch operation because modifying inputs in-place
370
+ # for gradient storage and backward multiple times causes anomalies with PyTorch but not with Triton.
371
+ N, H = dx.shape
372
+ B = min(MAX_FUSED_SIZE, triton.next_power_of_2(H))
373
+
374
+ elementwise_mul_kernel[(triton.cdiv(N * H, B),)](
375
+ x=dx,
376
+ g=do,
377
+ N=N*H,
378
+ B=B,
379
+ num_warps=32,
380
+ )
381
+
382
+ # handle dw
383
+ if dw is not None:
384
+ V, H = dw.shape
385
+ elementwise_mul_kernel[(triton.cdiv(V * H, B),)](
386
+ x=dw,
387
+ g=do,
388
+ N=V*H,
389
+ B=B,
390
+ num_warps=32,
391
+ )
392
+
393
+ if db is not None:
394
+ V = db.shape[0]
395
+ elementwise_mul_kernel[(triton.cdiv(V, B),)](
396
+ x=db,
397
+ g=do,
398
+ N=V,
399
+ B=B,
400
+ num_warps=32,
401
+ )
402
+ return dx, dw, db
403
+
404
+
405
+ class FusedLinearCrossEntropyFunction(torch.autograd.Function):
406
+
407
+ @staticmethod
408
+ def forward(
409
+ ctx,
410
+ x: torch.Tensor,
411
+ target: torch.LongTensor,
412
+ weight: torch.Tensor,
413
+ bias: torch.Tensor = None,
414
+ p_mask: torch.Tensor = None,
415
+ ignore_index: int = -100,
416
+ label_smoothing: float = 0.0,
417
+ logit_scale: float = 1.0,
418
+ num_chunks: int = 8,
419
+ reduction: str = "mean"
420
+ ):
421
+ """
422
+ Fusing the last linear layer with cross-entropy loss
423
+ Reference: https://github.com/mgmalek/efficient_cross_entropy
424
+
425
+ Handle the forward and backward pass of the final linear layer via cross-entropy loss by avoiding
426
+ the materialization of the large logits tensor. Since Cross Entropy Loss is the last layer, we can
427
+ compute the gradient at the forward pass. By doing so, we don't have to store the x and target
428
+ for the backward pass.
429
+
430
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
431
+ target (torch.LongTensor): [batch_size * seq_len]
432
+ where each value is in [0, vocab_size).
433
+ weight (torch.Tensor): [vocab_size, hidden_size]
434
+ where `vocab_size` is the number of classes.
435
+ bias (Optional[torch.Tensor]): [vocab_size]
436
+ where `vocab_size` is the number of classes.
437
+ p_mask(torch.Tensor): [batch_size * seq_len]
438
+ Its shape should be same as target.
439
+ ignore_index:
440
+ the index to ignore in the target.
441
+ label_smoothing:
442
+ the amount of smoothing when computing the loss, where 0.0 means no smoothing.
443
+ logit_scale: float = 1.0,
444
+ A scaling factor applied to the logits. Default: 1.0
445
+ num_chunks: int
446
+ The number of chunks to split the input tensor into for processing.
447
+ This can help optimize memory usage and computation speed.
448
+ Default: 8
449
+ reduction:
450
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
451
+ 'mean': the weighted mean of the output is taken,
452
+ 'sum': the output will be summed.
453
+ Default: 'mean'.
454
+ """
455
+ loss, dx, dw, db = fused_linear_cross_entropy_forward(
456
+ x,
457
+ target,
458
+ weight,
459
+ bias,
460
+ p_mask,
461
+ ignore_index,
462
+ label_smoothing,
463
+ logit_scale,
464
+ num_chunks,
465
+ reduction
466
+ )
467
+ # downcast to dtype and store for backward
468
+ ctx.save_for_backward(
469
+ dx.detach(),
470
+ dw.detach() if weight is not None else None,
471
+ db.detach() if bias is not None else None,
472
+ )
473
+ return loss
474
+
475
+ @staticmethod
476
+ def backward(ctx, do):
477
+ dx, dw, db = ctx.saved_tensors
478
+ dx, dw, db = fused_linear_cross_entropy_backward(do, dx, dw, db)
479
+ # 10 gradients should be returned, with `p_mask` having no grads
480
+ # Check the number of arguments in the `forward` method
481
+ return dx, None, dw, db, None, None, None, None, None, None
482
+
483
+
484
+ def fused_linear_cross_entropy_loss(
485
+ x: torch.Tensor,
486
+ target: torch.LongTensor,
487
+ weight: torch.Tensor,
488
+ bias: torch.Tensor = None,
489
+ p_mask: torch.Tensor = None,
490
+ ignore_index: int = -100,
491
+ label_smoothing: float = 0.0,
492
+ logit_scale: float = 1.0,
493
+ num_chunks: int = 8,
494
+ reduction: str = "mean"
495
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
496
+ """
497
+ Args:
498
+ x (torch.Tensor): [batch_size * seq_len, hidden_size]
499
+ target (torch.LongTensor): [batch_size * seq_len]
500
+ where each value is in [0, vocab_size).
501
+ weight (torch.Tensor): [vocab_size, hidden_size]
502
+ where `vocab_size` is the number of classes.
503
+ bias (Optional[torch.Tensor]): [vocab_size]
504
+ where `vocab_size` is the number of classes.
505
+ p_mask(torch.Tensor): [batch_size * seq_len]
506
+ Its shape should be same as target.
507
+ ignore_index: int.
508
+ If target == ignore_index, the loss is set to 0.0.
509
+ label_smoothing: float
510
+ logit_scale: float
511
+ A scaling factor applied to the logits. Default: 1.0
512
+ num_chunks: int
513
+ The number of chunks to split the input tensor into for processing.
514
+ This can help optimize memory usage and computation speed.
515
+ Default: 8
516
+ reduction:
517
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
518
+ 'mean': the weighted mean of the output is taken,
519
+ 'sum': the output will be summed.
520
+ Default: 'mean'.
521
+ Returns:
522
+ losses: [batch,], float
523
+ """
524
+ return FusedLinearCrossEntropyFunction.apply(
525
+ x,
526
+ target,
527
+ weight,
528
+ bias,
529
+ p_mask,
530
+ ignore_index,
531
+ label_smoothing,
532
+ logit_scale,
533
+ num_chunks,
534
+ reduction
535
+ )
536
+
537
+
538
+ class FusedLinearDiffusionCrossEntropyLoss(nn.Module):
539
+
540
+ def __init__(
541
+ self,
542
+ ignore_index: int = -100,
543
+ label_smoothing: float = 0.0,
544
+ logit_scale: float = 1.0,
545
+ num_chunks: int = 8,
546
+ reduction: str = "mean"
547
+ ):
548
+ """
549
+ Args:
550
+ ignore_index: int.
551
+ If target == ignore_index, the loss is set to 0.0.
552
+ label_smoothing: float
553
+ logit_scale: float
554
+ A scaling factor applied to the logits. Default: 1.0
555
+ num_chunks: int
556
+ The number of chunks to split the input tensor into for processing.
557
+ This can help optimize memory usage and computation speed.
558
+ Default: 8
559
+ reduction:
560
+ Specifies the reduction to apply to the output: 'mean' | 'sum'.
561
+ 'mean': the weighted mean of the output is taken,
562
+ 'sum': the output will be summed.
563
+ Default: 'mean'.
564
+ """
565
+ super().__init__()
566
+
567
+ assert reduction in ["mean", "sum"], f"reduction: {reduction} is not supported"
568
+
569
+ self.ignore_index = ignore_index
570
+ self.label_smoothing = label_smoothing
571
+ self.logit_scale = logit_scale
572
+ self.num_chunks = num_chunks
573
+ self.reduction = reduction
574
+
575
+ @torch.compiler.disable
576
+ def forward(
577
+ self,
578
+ x: torch.Tensor,
579
+ target: torch.LongTensor,
580
+ weight: torch.Tensor,
581
+ bias: Optional[torch.Tensor] = None,
582
+ p_mask: torch.Tensor = None
583
+ ):
584
+ """
585
+ Args:
586
+ x (torch.Tensor): [batch_size, seq_len, hidden_size]
587
+ target (torch.LongTensor): [batch_size, seq_len]
588
+ where each value is in [0, V).
589
+ weight (torch.Tensor): [vocab_size, hidden_size]
590
+ where `vocab_size` is the number of classes.
591
+ bias (Optional[torch.Tensor]): [vocab_size]
592
+ where `vocab_size` is the number of classes.
593
+ p_mask(torch.Tensor): [batch_size, seq_len]
594
+ Its shape is same as target.
595
+ Shape: (1, packed_length) when varlen attn is used.
596
+ Returns:
597
+ loss
598
+
599
+ TODO:
600
+ follow https://github.com/ML-GSAI/LLaDA/blob/main/GUIDELINES.md#pre-training
601
+ ```py
602
+ unreduced_loss /= p_mask
603
+ ```
604
+ Scale the values of `unreduced_loss at different positions
605
+ """
606
+ if p_mask is None:
607
+ p_mask = torch.ones_like(target, dtype=torch.float, device=x.device)
608
+
609
+ x = x.contiguous().view(-1, x.shape[-1])
610
+ target = target.contiguous().view(-1)
611
+ weight = weight.contiguous()
612
+ bias = bias.contiguous() if bias else None
613
+ p_mask = p_mask.contiguous().view(-1)
614
+ l, d = x.shape
615
+ assert l == target.shape[0] == p_mask.shape[0], f"{x.shape=}, {target.shape=}, {p_mask.shape=}"
616
+
617
+ loss = fused_linear_cross_entropy_loss(
618
+ x,
619
+ target,
620
+ weight=weight,
621
+ bias=bias,
622
+ p_mask=p_mask,
623
+ ignore_index=self.ignore_index,
624
+ label_smoothing=self.label_smoothing,
625
+ logit_scale=self.logit_scale,
626
+ num_chunks=self.num_chunks,
627
+ reduction=self.reduction
628
+ )
629
+ return loss
630
+
631
+
632
+ class LinearLossParallel(ParallelStyle):
633
+ def __init__(
634
+ self,
635
+ *,
636
+ sequence_dim: int = 1,
637
+ use_local_output: bool = False,
638
+ ):
639
+ super().__init__()
640
+
641
+ self.sequence_sharding = (Shard(sequence_dim),)
642
+ self.use_local_output = use_local_output
643
+
644
+ @staticmethod
645
+ def _prepare_input_fn(sequence_sharding, mod, inputs, device_mesh):
646
+ x, target, weight, bias = inputs
647
+
648
+ if not isinstance(x, DTensor):
649
+ # assume the input passed in already sharded on the sequence dim and create the DTensor
650
+ x = DTensor.from_local(x, device_mesh, sequence_sharding)
651
+ if x.placements != sequence_sharding:
652
+ x = x.redistribute(placements=sequence_sharding, async_op=True)
653
+ if not isinstance(target, DTensor):
654
+ target = DTensor.from_local(target, device_mesh, [Replicate()])
655
+ if target.placements != sequence_sharding:
656
+ target = target.redistribute(placements=sequence_sharding, async_op=True)
657
+
658
+ if not isinstance(weight, DTensor):
659
+ weight = DTensor.from_local(weight, device_mesh, [Replicate()])
660
+ if weight.placements != [Replicate()]:
661
+ # we replicate the weight/bias in FLCE
662
+ weight = weight.redistribute(placements=[Replicate()], async_op=True)
663
+
664
+ if bias is not None and not isinstance(bias, DTensor):
665
+ bias = DTensor.from_local(bias, device_mesh, [Replicate()])
666
+ if bias is not None and bias.placements != [Replicate()]:
667
+ bias = bias.redistribute(placements=[Replicate()], async_op=True)
668
+
669
+ return x.to_local(), target.to_local(), weight.to_local(), bias.to_local() if bias is not None else bias
670
+
671
+ @staticmethod
672
+ def _prepare_output_fn(use_local_output, mod, outputs, device_mesh):
673
+ return outputs.to_local() if use_local_output else outputs
674
+
675
+ def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
676
+ return distribute_module(
677
+ module,
678
+ device_mesh,
679
+ partition_fn=None,
680
+ input_fn=partial(self._prepare_input_fn, self.sequence_sharding),
681
+ output_fn=partial(self._prepare_output_fn, self.use_local_output)
682
+ )
models/dLMs-block8-epoch1/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 2,
4
+ "eos_token_id": 3,
5
+ "transformers_version": "4.52.4",
6
+ "use_cache": false
7
+ }
models/dLMs-block8-epoch1/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b9a39079f03d3b6dd7e82255a17991ff736b35183d6f6307ffb9275063274fa
3
+ size 242747504
models/dLMs-block8-epoch1/modeling_sdar.py ADDED
@@ -0,0 +1,1256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, List
25
+
26
+ import torch
27
+ from torch import nn
28
+ from einops import rearrange
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
32
+ from transformers.generation import GenerationMixin
33
+ from transformers.integrations import use_kernel_forward_from_hub
34
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
35
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
36
+ from transformers.modeling_layers import GradientCheckpointingLayer
37
+ from transformers.modeling_outputs import (
38
+ BaseModelOutputWithPast,
39
+ CausalLMOutputWithPast,
40
+ QuestionAnsweringModelOutput,
41
+ SequenceClassifierOutputWithPast,
42
+ TokenClassifierOutput,
43
+ )
44
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
45
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
46
+ from transformers.processing_utils import Unpack
47
+ try:
48
+ from transformers.utils import LossKwargs
49
+ except ImportError:
50
+ from transformers.utils import TransformersKwargs as LossKwargs
51
+ from transformers.utils import auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
52
+ from .configuration_sdar import SDARConfig
53
+ from .fused_linear_diffusion_cross_entropy import FusedLinearDiffusionCrossEntropyLoss
54
+
55
+ from flash_attn.ops.triton.layer_norm import rms_norm_fn as flash_rms_norm
56
+
57
+ import torch.nn.functional as F
58
+ try:
59
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
60
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
61
+ except:
62
+ pass
63
+
64
+ try:
65
+ from liger_kernel.ops.swiglu import LigerSiLUMulFunction # noqa: F401
66
+ liger_kernel_is_available = True
67
+ except ImportError:
68
+ liger_kernel_is_available = False
69
+
70
+
71
+ if is_torch_flex_attn_available():
72
+ from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attention
73
+ from transformers.integrations.flex_attention import make_flex_block_causal_mask
74
+
75
+
76
+ logger = logging.get_logger(__name__)
77
+
78
+
79
+ def modify_padded_position_ids_2d(position_ids: torch.LongTensor) -> torch.LongTensor:
80
+ """
81
+ 使用完全向量化的 PyTorch 操作修改一个 batch 的 packed position_ids。
82
+ 这个函数假设输入是一个 2D Tensor,形状为 (batch_size, sequence_length)。
83
+ 它会独立地处理 batch 中的每一行。
84
+
85
+ Args:
86
+ position_ids: 二维 PyTorch Tensor, shape (batch_size, sequence_length).
87
+
88
+ Returns:
89
+ 修改后的 position_ids Tensor, shape (batch_size, sequence_length).
90
+ """
91
+ if position_ids.dim() != 2:
92
+ raise ValueError(f"Input tensor must be 2D, but got {position_ids.dim()} dimensions.")
93
+
94
+ batch_size, seq_len = position_ids.shape
95
+ device = position_ids.device
96
+
97
+ col_indices = torch.arange(seq_len, device=device, dtype=position_ids.dtype).expand(batch_size, -1)
98
+ mask = (position_ids != 0)
99
+
100
+ masked_indices = col_indices * mask
101
+ last_nonzero_idx = torch.max(masked_indices, dim=1).values
102
+ has_nonzero = torch.any(mask, dim=1)
103
+ pad_start_idx = torch.where(has_nonzero, last_nonzero_idx + 1, torch.tensor(0, device=device, dtype=position_ids.dtype))
104
+
105
+ padding_mask = col_indices >= pad_start_idx.unsqueeze(1)
106
+ new_pad_values = col_indices - pad_start_idx.unsqueeze(1)
107
+ position_ids = torch.where(padding_mask, new_pad_values, position_ids)
108
+
109
+ return position_ids
110
+
111
+
112
+ def calculate_token_nums(position_ids: torch.Tensor):
113
+ """
114
+ 使用 PyTorch 高效计算一个批次中每个打包序列的长度。
115
+
116
+ Args:
117
+ position_ids (torch.Tensor): 一个 2D Tensor,形状为 (batch_size, sequence_length)。
118
+ 例如:tensor([[0,1,2,3,4,0,1,2,3,4,5,0,1,2,3,0,0,0]])
119
+ Returns:
120
+ list[list[int]]: 一个嵌套列表,包含每个批次项中各个序列的长度。
121
+ 例如:[[5, 6, 4, 1, 1, 1]]
122
+ """
123
+ # 检查输入是否为 2D Tensor
124
+ if position_ids.dim() != 2:
125
+ raise ValueError(f"输入必须是 2D Tensor,但得到了 {position_ids.dim()}D")
126
+
127
+ all_lengths = []
128
+
129
+ # 我们按批次逐行处理。因为每行的序列长度数量不同(ragged),
130
+ # 所以 Python 循环在批次维度上是最高效且最清晰的写法。
131
+ # 循环内部的操作是完全向量化的。
132
+ for pids_row in position_ids:
133
+ # 获取当前行的总长度
134
+ seq_len = pids_row.shape[0]
135
+
136
+ # 1. 找到所有值为 0 的元素的索引
137
+ # pids_row == 0 会返回一个布尔 Tensor: [True, False, ..., True, ...]
138
+ # torch.nonzero 会返回这些 True 值的索引
139
+ # .flatten() 将其从 (N, 1) 形状的 Tensor 变为 (N,) 形状
140
+ zero_indices = torch.nonzero(pids_row == 0).flatten()
141
+
142
+ # 2. 将序列的总长度作为一个额外的切分点添加到末尾
143
+ # 这对于计算最后一个序列的长度至关重要
144
+ # 注意:要确保新创建的 tensor 和原始 tensor 在同一个设备上 (cpu/cuda)
145
+ split_points = torch.cat([
146
+ zero_indices,
147
+ torch.tensor([seq_len], device=pids_row.device, dtype=zero_indices.dtype)
148
+ ])
149
+
150
+ # 3. 计算相邻切分点之间的差值,这就是我们想要的长度
151
+ # torch.diff([a, b, c, d]) 会返回 [b-a, c-b, d-c]
152
+ lengths = torch.diff(split_points)
153
+
154
+ all_lengths.append(lengths)
155
+
156
+ return all_lengths
157
+
158
+
159
+ def forward_add_noise_packed(
160
+ inputs_ids: torch.Tensor,
161
+ num_tokens_list: List[torch.Tensor],
162
+ prompt_mask: torch.Tensor,
163
+ mask_id: int,
164
+ eps: float = 1e-3,
165
+ max_tries: int = 10,
166
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
167
+ """
168
+ 为一批打包(packed)序列的 token ID 添加噪声。
169
+
170
+ 此函数保留了为每个逻辑样本(在每个批次项内拼接)生成独立随机噪声率的逻辑。
171
+ 它会随机将一部分 token 的 ID 替换为 mask_id。
172
+ 这个过程会避开被 prompt_mask 标记的位置。
173
+
174
+ Args:
175
+ inputs_ids (torch.Tensor):
176
+ 输入的 token ID 张量,形状为 (bsz, total_tokens)。
177
+ num_tokens_list (List[torch.Tensor]):
178
+ 一个张量列表,长度为 bsz。列表中的每个张量记录了对应批次项中
179
+ 每个逻辑样本的长度。例如: [tensor([len1, len2]), tensor([len3, len4, len5])].
180
+ prompt_mask (torch.Tensor):
181
+ 布尔型张量,形状为 (bsz, total_tokens),值为 True 的位置表示是 prompt,
182
+ 不应添加噪声。
183
+ mask_id (int):
184
+ 用于替换的 mask token 的 ID。
185
+ eps (float):
186
+ 微小值,用于防止噪声率 t 恰好为 0,确保 p_mask > 0。
187
+ max_tries (int):
188
+ 为确保至少一个非 prompt token 被 mask,对每个批次项尝试的最大次数。
189
+
190
+ Returns:
191
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
192
+ - noisy_input_ids (torch.Tensor):
193
+ 添加噪声后的 token ID 张量,形状为 (bsz, total_tokens)。
194
+ - final_masked_indices (torch.Tensor):
195
+ 布尔型张量,标记了哪些位置被实际 mask 了,形状为 (bsz, total_tokens)。
196
+ - p_masks (torch.Tensor):
197
+ 一个一维张量,包含了被 mask 的 token 对应的实际噪声率。
198
+ """
199
+ # 1. 验证和获取形状
200
+ bsz, total_tokens = inputs_ids.shape
201
+ device = inputs_ids.device
202
+
203
+ # 检查输入的一致性
204
+ assert len(num_tokens_list) == bsz, f"num_tokens_list 的长度 ({len(num_tokens_list)}) 必须等于 bsz ({bsz})"
205
+ assert prompt_mask.shape == (bsz, total_tokens), f"prompt_mask 形状不匹配, 期望 {(bsz, total_tokens)}, 得到 {prompt_mask.shape}"
206
+
207
+ # 准备结果容器
208
+ noisy_ids_list = []
209
+ final_masked_indices_list = []
210
+ p_masks_per_token_list = []
211
+
212
+ # 2. 在批次维度上迭代
213
+ # 这是处理不同打包结构最直接有效的方法
214
+ for i in range(bsz):
215
+ # 提取当前批次项的数据
216
+ current_ids = inputs_ids[i:i+1] # shape: (1, total_tokens)
217
+ current_num_tokens = num_tokens_list[i]
218
+ current_prompt_mask = prompt_mask[i:i+1] # shape: (1, total_tokens)
219
+
220
+ num_samples_in_item = len(current_num_tokens)
221
+ # 验证当前批次项的 token 总数���否匹配
222
+ assert total_tokens == torch.sum(current_num_tokens), \
223
+ f"批次项 {i} 的 num_tokens 之和 ({torch.sum(current_num_tokens)}) 与 total_tokens ({total_tokens}) 不匹配"
224
+
225
+ eligible_for_masking = ~current_prompt_mask
226
+
227
+ # 如果没有任何 token 可以被 mask,直接使用原始输入,并设置 p_mask 为 eps
228
+ if not eligible_for_masking.any():
229
+ noisy_ids_list.append(current_ids)
230
+ final_masked_indices_list.append(torch.zeros_like(current_prompt_mask, dtype=torch.bool))
231
+ # p_mask_per_token 的形状应为 (1, total_tokens) 以便后续拼接
232
+ p_masks_per_token_list.append(torch.full((1, total_tokens), eps, device=device, dtype=torch.float))
233
+ continue
234
+
235
+ # --- 尝试生成 mask,确保至少 mask 一个 token ---
236
+ final_masked_indices_item = torch.zeros_like(current_prompt_mask, dtype=torch.bool)
237
+ p_mask_per_token = None
238
+
239
+ for _ in range(max_tries):
240
+ # 为每个逻辑样本生成一个独立的噪声率 t
241
+ t = torch.rand(num_samples_in_item, device=device)
242
+ p_mask_per_sample = (1 - eps) * t + eps
243
+
244
+ # 将每个样本的噪声率扩展到其所有 token 上
245
+ p_mask_per_token_1d = torch.repeat_interleave(p_mask_per_sample, current_num_tokens)
246
+ p_mask_per_token = p_mask_per_token_1d.unsqueeze(0) # shape: (1, total_tokens)
247
+
248
+ # 根据噪声率生成随机 mask
249
+ masked_indices = torch.rand_like(p_mask_per_token) < p_mask_per_token
250
+ # 应用 prompt mask,确保 prompt 不被 mask
251
+ final_masked_indices_item = masked_indices & eligible_for_masking
252
+
253
+ # 如果成功 mask 了至少一个 token,则跳出尝试循环
254
+ if final_masked_indices_item.any():
255
+ break
256
+
257
+ # 如果 max_tries 之后仍然没有 mask 任何 token (极小概率),就强制 mask 一个可 mask 的 token
258
+ if not final_masked_indices_item.any():
259
+ eligible_indices = torch.nonzero(eligible_for_masking.squeeze(0), as_tuple=True)[0]
260
+ if len(eligible_indices) > 0:
261
+ # 随机选择一个可 mask 的位置
262
+ random_choice = torch.randint(0, len(eligible_indices), (1,)).item()
263
+ force_mask_idx = eligible_indices[random_choice]
264
+ final_masked_indices_item[0, force_mask_idx] = True
265
+
266
+
267
+ # --- 根据最终的 mask 生成带噪声的 IDs ---
268
+ noisy_ids_item = torch.where(
269
+ final_masked_indices_item,
270
+ mask_id,
271
+ current_ids
272
+ )
273
+
274
+ # 保存这个批次项的结果
275
+ noisy_ids_list.append(noisy_ids_item)
276
+ final_masked_indices_list.append(final_masked_indices_item)
277
+ p_masks_per_token_list.append(p_mask_per_token)
278
+
279
+ # 3. 将列表中的结果堆叠成最终的批处理张量
280
+ noisy_input_ids = torch.cat(noisy_ids_list, dim=0)
281
+ final_masked_indices = torch.cat(final_masked_indices_list, dim=0)
282
+ p_mask_full = torch.cat(p_masks_per_token_list, dim=0)
283
+
284
+ # 4. 提取被 mask 位置对应的噪声率
285
+ p_masks = p_mask_full[final_masked_indices]
286
+
287
+ return noisy_input_ids, final_masked_indices, p_masks
288
+
289
+
290
+ def block_diff_mask(b, h, q_idx, kv_idx, block_size=None, n=None):
291
+ """
292
+ Constructs the specialized block diffusion attention mask for training
293
+ composed of three masks:
294
+ - **Block Diagonal Mask (M_BD)**: Self-attention within noised blocks
295
+ - **Offset Block Causal Mask (M_OBC)**: Cross-attention for conditional context
296
+ - **Block Causal Mask (M_BC)**: Attention to update x0
297
+
298
+ Args:
299
+ b, h: Batch and head indices (ignored for mask logic).
300
+ q_idx, kv_idx: Query and Key indices.
301
+ seq_len: Total sequence length.
302
+ block_size: Defines the block structure.
303
+
304
+ Returns:
305
+ A boolean attention mask.
306
+ """
307
+
308
+ # Indicate whether token belongs to xt or x0
309
+ x0_flag_q = q_idx >= n
310
+ x0_flag_kv = kv_idx >= n
311
+
312
+ # Compute block indices
313
+ block_q = torch.where(
314
+ x0_flag_q == 1, (q_idx - n) // block_size, q_idx // block_size
315
+ )
316
+ block_kv = torch.where(
317
+ x0_flag_kv == 1, (kv_idx - n) // block_size, kv_idx // block_size
318
+ )
319
+
320
+ # **1. Block Diagonal Mask (M_BD) **
321
+ block_diagonal = (block_q == block_kv) & (x0_flag_q == x0_flag_kv)
322
+
323
+ # **2. Offset Block-Causal Mask (M_OBC) **
324
+ offset_block_causal = (block_q > block_kv) & (
325
+ x0_flag_kv == 1) & (x0_flag_q == 0)
326
+
327
+ # **3. Block-Causal Mask (M_BC) **
328
+ block_causal = (block_q >= block_kv) & (x0_flag_kv == 1) & (x0_flag_q == 1)
329
+
330
+ # **4. Combine Masks **
331
+ return block_diagonal | offset_block_causal | block_causal
332
+
333
+
334
+ def block_attn_mask(num_tokens, block_size, device):
335
+ masks = []
336
+ for i in range(len(num_tokens)):
337
+ cur_masks = []
338
+ for num in num_tokens[i]:
339
+ # 全部返回 n*n 而非 2n*2n
340
+ single_mask = block_diff_mask(
341
+ b=None,
342
+ h=None,
343
+ q_idx=torch.arange(num * 2, device=device)[:, None],
344
+ kv_idx=torch.arange(num * 2, device=device)[None, :],
345
+ block_size=block_size,
346
+ n=num,
347
+ )
348
+ cur_masks.append(single_mask)
349
+ masks.append(torch.block_diag(*cur_masks))
350
+ masks = torch.stack(masks, dim=0)
351
+ return masks
352
+
353
+
354
+ @torch.compile(fullgraph=True, mode="max-autotune-no-cudagraphs")
355
+ def _fused_flex_attention(query, key, value, attention_mask, **kwargs):
356
+ return flex_attention(query, key, value, block_mask=attention_mask, **kwargs)
357
+
358
+
359
+ def fused_flex_attention(query, key, value, attention_mask, **kwargs):
360
+ # Cast outside torch.compile: q/k RMSNorm often returns fp32 under bf16 while v stays bf16.
361
+ dtype = value.dtype
362
+ return _fused_flex_attention(
363
+ query.to(dtype), key.to(dtype), value, attention_mask, **kwargs
364
+ )
365
+
366
+
367
+ @use_kernel_forward_from_hub("RMSNorm")
368
+ class SDARRMSNorm(nn.Module):
369
+ def __init__(self, hidden_size, eps=1e-6):
370
+ """
371
+ SDARRMSNorm is equivalent to T5LayerNorm
372
+ """
373
+ super().__init__()
374
+ self.weight = nn.Parameter(torch.ones(hidden_size))
375
+ self.variance_epsilon = eps
376
+
377
+ def forward(self, hidden_states):
378
+ # flash_rms_norm may return fp32; cast back so Q/K match V under bf16 training.
379
+ input_dtype = hidden_states.dtype
380
+ return flash_rms_norm(
381
+ hidden_states, weight=self.weight, bias=None, eps=self.variance_epsilon
382
+ ).to(input_dtype)
383
+ '''
384
+ input_dtype = hidden_states.dtype
385
+ hidden_states = hidden_states.to(torch.float32)
386
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
387
+ hidden_states = hidden_states * \
388
+ torch.rsqrt(variance + self.variance_epsilon)
389
+ return self.weight * hidden_states.to(input_dtype)
390
+ '''
391
+
392
+ def extra_repr(self):
393
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
394
+
395
+
396
+ class SDARMLP(nn.Module):
397
+ def __init__(self, config):
398
+ super().__init__()
399
+ self.config = config
400
+ self.hidden_size = config.hidden_size
401
+ self.intermediate_size = config.intermediate_size
402
+ self.gate_proj = nn.Linear(
403
+ self.hidden_size, self.intermediate_size, bias=False)
404
+ self.up_proj = nn.Linear(
405
+ self.hidden_size, self.intermediate_size, bias=False)
406
+ self.down_proj = nn.Linear(
407
+ self.intermediate_size, self.hidden_size, bias=False)
408
+ self.act_fn = ACT2FN[config.hidden_act]
409
+
410
+ def forward(self, x):
411
+ if liger_kernel_is_available:
412
+ return self.down_proj(LigerSiLUMulFunction.apply(self.gate_proj(x), self.up_proj(x)))
413
+ else:
414
+ down_proj = self.down_proj(self.act_fn(
415
+ self.gate_proj(x)) * self.up_proj(x))
416
+ return down_proj
417
+
418
+
419
+ def rotate_half(x):
420
+ """Rotates half the hidden dims of the input."""
421
+ x1 = x[..., : x.shape[-1] // 2]
422
+ x2 = x[..., x.shape[-1] // 2:]
423
+ return torch.cat((-x2, x1), dim=-1)
424
+
425
+
426
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
427
+ """Applies Rotary Position Embedding to the query and key tensors.
428
+
429
+ Args:
430
+ q (`torch.Tensor`): The query tensor.
431
+ k (`torch.Tensor`): The key tensor.
432
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
433
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
434
+ position_ids (`torch.Tensor`, *optional*):
435
+ Deprecated and unused.
436
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
437
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
438
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
439
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
440
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
441
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
442
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
443
+ Returns:
444
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
445
+ """
446
+ cos = cos.unsqueeze(unsqueeze_dim)
447
+ sin = sin.unsqueeze(unsqueeze_dim)
448
+ q_embed = (q * cos) + (rotate_half(q) * sin)
449
+ k_embed = (k * cos) + (rotate_half(k) * sin)
450
+ return q_embed, k_embed
451
+
452
+
453
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
454
+ """
455
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
456
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
457
+ """
458
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
459
+ if n_rep == 1:
460
+ return hidden_states
461
+ hidden_states = hidden_states[:, :, None, :, :].expand(
462
+ batch, num_key_value_heads, n_rep, slen, head_dim)
463
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
464
+
465
+
466
+ def eager_attention_forward(
467
+ module: nn.Module,
468
+ query: torch.Tensor,
469
+ key: torch.Tensor,
470
+ value: torch.Tensor,
471
+ attention_mask: Optional[torch.Tensor],
472
+ scaling: float,
473
+ dropout: float = 0.0,
474
+ **kwargs,
475
+ ):
476
+ key_states = repeat_kv(key, module.num_key_value_groups)
477
+ value_states = repeat_kv(value, module.num_key_value_groups)
478
+
479
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
480
+ if attention_mask is not None:
481
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
482
+ attn_weights = attn_weights + causal_mask
483
+
484
+ attn_weights = nn.functional.softmax(
485
+ attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
486
+ attn_weights = nn.functional.dropout(
487
+ attn_weights, p=dropout, training=module.training)
488
+ attn_output = torch.matmul(attn_weights, value_states)
489
+ attn_output = attn_output.transpose(1, 2).contiguous()
490
+
491
+ return attn_output, attn_weights
492
+
493
+
494
+ class SDARAttention(nn.Module):
495
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
496
+
497
+ def __init__(self, config: SDARConfig, layer_idx: int):
498
+ super().__init__()
499
+ self.config = config
500
+ self.layer_idx = layer_idx
501
+ self.head_dim = getattr(
502
+ config, "head_dim", config.hidden_size // config.num_attention_heads)
503
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
504
+ self.scaling = self.head_dim**-0.5
505
+ self.attention_dropout = config.attention_dropout
506
+ self.is_causal = True
507
+
508
+ self.hidden_size = config.hidden_size
509
+ self.num_attention_heads = config.num_attention_heads
510
+ self.num_key_value_heads = config.num_key_value_heads
511
+
512
+ self.q_proj = nn.Linear(
513
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
514
+ )
515
+ self.k_proj = nn.Linear(
516
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
517
+ )
518
+ self.v_proj = nn.Linear(
519
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
520
+ )
521
+ self.o_proj = nn.Linear(
522
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
523
+ )
524
+ # unlike olmo, only on the head dim!
525
+ self.q_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)
526
+ # thus post q_norm does not need reshape
527
+ self.k_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)
528
+ self.sliding_window = config.sliding_window
529
+ if not (
530
+ self.config.use_sliding_window
531
+ and getattr(self.config, "sliding_window", None) is not None
532
+ and self.layer_idx >= self.config.max_window_layers
533
+ ):
534
+ self.sliding_window = None
535
+
536
+ def forward(
537
+ self,
538
+ hidden_states: torch.Tensor,
539
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
540
+ attention_mask: Optional[torch.Tensor],
541
+ past_key_value: Optional[Cache] = None,
542
+ cache_position: Optional[torch.LongTensor] = None,
543
+ **kwargs: Unpack[FlashAttentionKwargs],
544
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
545
+ input_shape = hidden_states.shape[:-1]
546
+ bsz, q_len = input_shape
547
+ hidden_shape = (*input_shape, -1, self.head_dim)
548
+
549
+ query_states = self.q_norm(self.q_proj(
550
+ hidden_states).view(hidden_shape)).transpose(1, 2)
551
+ key_states = self.k_norm(self.k_proj(
552
+ hidden_states).view(hidden_shape)).transpose(1, 2)
553
+ value_states = self.v_proj(hidden_states).view(
554
+ hidden_shape).transpose(1, 2)
555
+
556
+ cos, sin = position_embeddings
557
+ query_states, key_states = apply_rotary_pos_emb(
558
+ query_states, key_states, cos, sin)
559
+
560
+ if past_key_value is not None and kwargs.get("store_kv", False):
561
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
562
+ key_states, value_states = past_key_value.update(
563
+ key_states, value_states, self.layer_idx)
564
+ elif past_key_value is not None and not kwargs.get("store_kv", False) and len(past_key_value) > self.layer_idx:
565
+ # only retrive, do not store kv
566
+ past_key_states, past_value_states = past_key_value[self.layer_idx]
567
+ key_states = torch.cat(
568
+ [past_key_states, key_states], dim=-2)
569
+ value_states = torch.cat(
570
+ [past_value_states, value_states], dim=-2)
571
+
572
+ if self.training:
573
+ attn_output, attn_weights = fused_flex_attention(
574
+ query=query_states,
575
+ key=key_states,
576
+ value=value_states,
577
+ attention_mask=attention_mask,
578
+ enable_gqa=True,
579
+ scale=self.scaling,
580
+ return_lse=True
581
+ )
582
+ attn_weights = attn_weights.to(
583
+ value_states.dtype) if attn_weights is not None else None
584
+ attn_output = rearrange(attn_output, 'b h l d -> b l (h d)')
585
+ else:
586
+ attention_mask = attention_mask.bool() if attention_mask is not None else None
587
+ attn_weights = None
588
+ if torch.all(attention_mask): # decoding
589
+ query_states = query_states.transpose(1, 2)
590
+ key_states = key_states.transpose(1, 2)
591
+ value_states = value_states.transpose(1, 2)
592
+ attn_output = flash_attn_func(
593
+ query_states,
594
+ key_states,
595
+ value_states,
596
+ causal=False,
597
+ softmax_scale=self.scaling
598
+ )
599
+ attn_output = rearrange(attn_output, 'b l h d -> b l (h d)')
600
+ else: # prefilling
601
+ attn_output = F.scaled_dot_product_attention(
602
+ query=query_states,
603
+ key=key_states,
604
+ value=value_states,
605
+ attn_mask=attention_mask,
606
+ is_causal=False,
607
+ scale=self.scaling,
608
+ enable_gqa=True
609
+ )
610
+ attn_output = rearrange(attn_output, 'b h l d -> b l (h d)')
611
+ attn_output = self.o_proj(attn_output)
612
+ return attn_output, attn_weights # , attn_weights
613
+
614
+
615
+ class SDARDecoderLayer(GradientCheckpointingLayer):
616
+ def __init__(self, config: SDARConfig, layer_idx: int):
617
+ super().__init__()
618
+ self.hidden_size = config.hidden_size
619
+ self.self_attn = SDARAttention(config=config, layer_idx=layer_idx)
620
+ self.mlp = SDARMLP(config)
621
+ self.input_layernorm = SDARRMSNorm(
622
+ config.hidden_size, eps=config.rms_norm_eps)
623
+ self.post_attention_layernorm = SDARRMSNorm(
624
+ config.hidden_size, eps=config.rms_norm_eps)
625
+ if (
626
+ config.sliding_window and config._attn_implementation != "flash_attention_2"
627
+ ): # diff with Llama is this warning
628
+ logger.warning_once(
629
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
630
+ "unexpected results may be encountered."
631
+ )
632
+
633
+ def forward(
634
+ self,
635
+ hidden_states: torch.Tensor,
636
+ attention_mask: Optional[torch.Tensor] = None,
637
+ position_ids: Optional[torch.LongTensor] = None,
638
+ past_key_value: Optional[Cache] = None,
639
+ output_attentions: Optional[bool] = False,
640
+ use_cache: Optional[bool] = False,
641
+ store_kv: Optional[bool] = False,
642
+ cache_position: Optional[torch.LongTensor] = None,
643
+ # necessary, but kept here for BC
644
+ position_embeddings: Optional[Tuple[torch.Tensor,
645
+ torch.Tensor]] = None,
646
+ **kwargs: Unpack[FlashAttentionKwargs],
647
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
648
+ residual = hidden_states
649
+ hidden_states = self.input_layernorm(hidden_states)
650
+
651
+ # Self Attention
652
+ hidden_states, self_attn_weights = self.self_attn(
653
+ hidden_states=hidden_states,
654
+ attention_mask=attention_mask,
655
+ position_ids=position_ids,
656
+ past_key_value=past_key_value,
657
+ output_attentions=output_attentions,
658
+ use_cache=use_cache,
659
+ store_kv=store_kv,
660
+ cache_position=cache_position,
661
+ position_embeddings=position_embeddings,
662
+ **kwargs,
663
+ )
664
+ hidden_states = residual + hidden_states
665
+
666
+ # Fully Connected
667
+ residual = hidden_states
668
+ hidden_states = self.post_attention_layernorm(hidden_states)
669
+ hidden_states = self.mlp(hidden_states)
670
+ hidden_states = residual + hidden_states
671
+
672
+ outputs = (hidden_states,)
673
+ if output_attentions:
674
+ outputs += (self_attn_weights,)
675
+
676
+ return outputs
677
+
678
+
679
+ @auto_docstring
680
+ class SDARPreTrainedModel(PreTrainedModel):
681
+ config_class = SDARConfig
682
+ base_model_prefix = "model"
683
+ supports_gradient_checkpointing = True
684
+ _no_split_modules = ["SDARDecoderLayer"]
685
+ _skip_keys_device_placement = ["past_key_values"]
686
+ _supports_flash_attn_2 = True
687
+ _supports_sdpa = True
688
+ _supports_flex_attn = True
689
+ _supports_cache_class = True
690
+ _supports_quantized_cache = True
691
+ _supports_static_cache = True
692
+ _supports_attention_backend = True
693
+
694
+ def _init_weights(self, module):
695
+ std = self.config.initializer_range
696
+ if isinstance(module, nn.Linear):
697
+ module.weight.data.normal_(mean=0.0, std=std)
698
+ if module.bias is not None:
699
+ module.bias.data.zero_()
700
+ elif isinstance(module, nn.Embedding):
701
+ module.weight.data.normal_(mean=0.0, std=std)
702
+ if module.padding_idx is not None:
703
+ module.weight.data[module.padding_idx].zero_()
704
+ elif isinstance(module, SDARRMSNorm):
705
+ module.weight.data.fill_(1.0)
706
+
707
+
708
+ class SDARRotaryEmbedding(nn.Module):
709
+ def __init__(self, config: SDARConfig, device=None):
710
+ super().__init__()
711
+ # BC: "rope_type" was originally "type"
712
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
713
+ self.rope_type = config.rope_scaling.get(
714
+ "rope_type", config.rope_scaling.get("type"))
715
+ else:
716
+ self.rope_type = "default"
717
+ self.max_seq_len_cached = config.max_position_embeddings
718
+ self.original_max_seq_len = config.max_position_embeddings
719
+
720
+ self.config = config
721
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
722
+
723
+ inv_freq, self.attention_scaling = self.rope_init_fn(
724
+ self.config, device)
725
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
726
+ self.original_inv_freq = self.inv_freq
727
+
728
+ @torch.no_grad()
729
+ # power user: used with advanced RoPE types (e.g. dynamic rope)
730
+ @dynamic_rope_update
731
+ def forward(self, x, position_ids):
732
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(
733
+ position_ids.shape[0], -1, 1).to(x.device)
734
+ position_ids_expanded = position_ids[:, None, :].float()
735
+
736
+ device_type = x.device.type if isinstance(
737
+ x.device.type, str) and x.device.type != "mps" else "cpu"
738
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
739
+ freqs = (inv_freq_expanded.float() @
740
+ position_ids_expanded.float()).transpose(1, 2)
741
+ emb = torch.cat((freqs, freqs), dim=-1)
742
+ cos = emb.cos() * self.attention_scaling
743
+ sin = emb.sin() * self.attention_scaling
744
+
745
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
746
+
747
+
748
+ @auto_docstring
749
+ class SDARModel(SDARPreTrainedModel):
750
+ def __init__(self, config: SDARConfig):
751
+ super().__init__(config)
752
+ self.padding_idx = config.pad_token_id
753
+ self.vocab_size = config.vocab_size
754
+
755
+ self.embed_tokens = nn.Embedding(
756
+ config.vocab_size, config.hidden_size, self.padding_idx)
757
+ self.layers = nn.ModuleList(
758
+ [SDARDecoderLayer(config, layer_idx)
759
+ for layer_idx in range(config.num_hidden_layers)]
760
+ )
761
+ self.norm = SDARRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
762
+ self.rotary_emb = SDARRotaryEmbedding(config=config)
763
+ self.gradient_checkpointing = False
764
+
765
+ # Initialize weights and apply final processing
766
+ self.post_init()
767
+
768
+ def get_input_embeddings(self):
769
+ return self.embed_tokens
770
+
771
+ def set_input_embeddings(self, value):
772
+ self.embed_tokens = value
773
+
774
+ @can_return_tuple
775
+ @auto_docstring
776
+ def forward(
777
+ self,
778
+ input_ids: Optional[torch.LongTensor] = None,
779
+ attention_mask: Optional[torch.Tensor] = None,
780
+ position_ids: Optional[torch.LongTensor] = None,
781
+ past_key_values: Optional[Cache] = None,
782
+ inputs_embeds: Optional[torch.FloatTensor] = None,
783
+ use_cache: Optional[bool] = None,
784
+ store_kv: Optional[bool] = None,
785
+ output_attentions: Optional[bool] = None,
786
+ output_hidden_states: Optional[bool] = None,
787
+ cache_position: Optional[torch.LongTensor] = None,
788
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
789
+ ) -> BaseModelOutputWithPast:
790
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
791
+ output_hidden_states = (
792
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
793
+ )
794
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
795
+
796
+ if (input_ids is None) ^ (inputs_embeds is not None):
797
+ raise ValueError(
798
+ "You must specify exactly one of input_ids or inputs_embeds")
799
+
800
+ if self.gradient_checkpointing and self.training and use_cache:
801
+ logger.warning_once(
802
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
803
+ )
804
+ use_cache = False
805
+
806
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
807
+ if not isinstance(past_key_values, (type(None), Cache)):
808
+ raise ValueError(
809
+ "The `past_key_values` should be either a `Cache` object or `None`.")
810
+
811
+ if inputs_embeds is None:
812
+ inputs_embeds = self.embed_tokens(input_ids)
813
+
814
+ if use_cache and past_key_values is None:
815
+ past_key_values = DynamicCache()
816
+
817
+ if cache_position is None:
818
+ past_seen_tokens = past_key_values.get_seq_length(
819
+ ) if past_key_values is not None else 0
820
+ cache_position = torch.arange(
821
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
822
+ )
823
+
824
+ if position_ids is None:
825
+ position_ids = cache_position.unsqueeze(0)
826
+
827
+ # causal_mask = self._update_causal_mask(
828
+ # attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
829
+ # )
830
+
831
+ hidden_states = inputs_embeds
832
+
833
+ # create position embeddings to be shared across the decoder layers
834
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
835
+
836
+ # decoder layers
837
+ all_hidden_states = () if output_hidden_states else None
838
+ all_self_attns = () if output_attentions else None
839
+
840
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
841
+ if output_hidden_states:
842
+ all_hidden_states += (hidden_states,)
843
+
844
+ layer_outputs = decoder_layer(
845
+ hidden_states,
846
+ attention_mask=attention_mask,
847
+ position_ids=position_ids,
848
+ past_key_value=past_key_values,
849
+ output_attentions=output_attentions,
850
+ use_cache=use_cache,
851
+ store_kv=store_kv,
852
+ cache_position=cache_position,
853
+ position_embeddings=position_embeddings,
854
+ **flash_attn_kwargs,
855
+ )
856
+
857
+ hidden_states = layer_outputs[0]
858
+
859
+ if output_attentions:
860
+ all_self_attns += (layer_outputs[1],)
861
+
862
+ hidden_states = self.norm(hidden_states)
863
+
864
+ # add hidden states from the last decoder layer
865
+ if output_hidden_states:
866
+ all_hidden_states += (hidden_states,)
867
+
868
+ return BaseModelOutputWithPast(
869
+ last_hidden_state=hidden_states,
870
+ past_key_values=past_key_values if use_cache else None,
871
+ hidden_states=all_hidden_states,
872
+ attentions=all_self_attns,
873
+ )
874
+
875
+ def _update_causal_mask(
876
+ self,
877
+ attention_mask: Union[torch.Tensor, "BlockMask"],
878
+ input_tensor: torch.Tensor,
879
+ cache_position: torch.Tensor,
880
+ past_key_values: Cache,
881
+ output_attentions: bool = False,
882
+ ):
883
+ if self.config._attn_implementation == "flash_attention_2":
884
+ if attention_mask is not None and past_key_values is not None:
885
+ is_padding_right = attention_mask[:, -
886
+ 1].sum().item() != input_tensor.size()[0]
887
+ if is_padding_right:
888
+ raise ValueError(
889
+ "You are attempting to perform batched generation with padding_side='right'"
890
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen3. Make sure to "
891
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
892
+ )
893
+ if attention_mask is not None and 0.0 in attention_mask:
894
+ return attention_mask
895
+ return None
896
+ if self.config._attn_implementation == "flex_attention":
897
+ if isinstance(attention_mask, torch.Tensor):
898
+ seq_len_q, seq_len_kv = attention_mask.shape
899
+ assert seq_len_q == seq_len_kv, f"got {attention_mask.shape=}"
900
+ attention_mask = create_block_mask(
901
+ # 2d bool tensor, shape: [2*seqlen, 2*seqlen]
902
+ lambda b, h, q_idx, kv_idx: attention_mask[q_idx, kv_idx],
903
+ B=None, H=None, Q_LEN=seq_len_q, KV_LEN=seq_len_kv,
904
+ )
905
+ else:
906
+ # Here we pass in flex mask computed externally
907
+ assert isinstance(attention_mask, BlockMask)
908
+ return attention_mask
909
+
910
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
911
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
912
+ # to infer the attention mask.
913
+ past_seen_tokens = past_key_values.get_seq_length(
914
+ ) if past_key_values is not None else 0
915
+ using_static_cache = isinstance(past_key_values, StaticCache)
916
+ using_sliding_window_cache = isinstance(
917
+ past_key_values, SlidingWindowCache)
918
+
919
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
920
+ if (
921
+ self.config._attn_implementation == "sdpa"
922
+ and not (using_static_cache or using_sliding_window_cache)
923
+ and not output_attentions
924
+ ):
925
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
926
+ attention_mask,
927
+ inputs_embeds=input_tensor,
928
+ past_key_values_length=past_seen_tokens,
929
+ sliding_window=self.config.sliding_window,
930
+ is_training=self.training,
931
+ ):
932
+ return None
933
+
934
+ dtype = input_tensor.dtype
935
+ min_dtype = torch.finfo(dtype).min
936
+ sequence_length = input_tensor.shape[1]
937
+ # SlidingWindowCache or StaticCache
938
+ if using_sliding_window_cache or using_static_cache:
939
+ target_length = past_key_values.get_max_cache_shape()
940
+ # DynamicCache or no cache
941
+ else:
942
+ target_length = (
943
+ attention_mask.shape[-1]
944
+ if isinstance(attention_mask, torch.Tensor)
945
+ else past_seen_tokens + sequence_length + 1
946
+ )
947
+
948
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
949
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
950
+ attention_mask,
951
+ sequence_length=sequence_length,
952
+ target_length=target_length,
953
+ dtype=dtype,
954
+ cache_position=cache_position,
955
+ batch_size=input_tensor.shape[0],
956
+ config=self.config,
957
+ past_key_values=past_key_values,
958
+ )
959
+
960
+ if (
961
+ self.config._attn_implementation == "sdpa"
962
+ and attention_mask is not None
963
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
964
+ and not output_attentions
965
+ ):
966
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
967
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
968
+ # Details: https://github.com/pytorch/pytorch/issues/110213
969
+ causal_mask = AttentionMaskConverter._unmask_unattended(
970
+ causal_mask, min_dtype)
971
+
972
+ return causal_mask
973
+
974
+ @staticmethod
975
+ def _prepare_4d_causal_attention_mask_with_cache_position(
976
+ attention_mask: torch.Tensor,
977
+ sequence_length: int,
978
+ target_length: int,
979
+ dtype: torch.dtype,
980
+ cache_position: torch.Tensor,
981
+ batch_size: int,
982
+ config: SDARConfig,
983
+ past_key_values: Cache,
984
+ ):
985
+ """
986
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
987
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
988
+
989
+ Args:
990
+ attention_mask (`torch.Tensor`):
991
+ 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)`.
992
+ sequence_length (`int`):
993
+ The sequence length being processed.
994
+ target_length (`int`):
995
+ 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.
996
+ dtype (`torch.dtype`):
997
+ The dtype to use for the 4D attention mask.
998
+ cache_position (`torch.Tensor`):
999
+ Indices depicting the position of the input sequence tokens in the sequence.
1000
+ batch_size (`torch.Tensor`):
1001
+ Batch size.
1002
+ config (`SDARConfig`):
1003
+ The model's configuration class
1004
+ past_key_values (`Cache`):
1005
+ The cache class that is being used currently to generate
1006
+ """
1007
+ if attention_mask is not None and attention_mask.dim() == 4:
1008
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1009
+ causal_mask = attention_mask
1010
+ else:
1011
+ min_dtype = torch.finfo(dtype).min
1012
+ causal_mask = torch.full(
1013
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
1014
+ )
1015
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
1016
+ -1, 1
1017
+ )
1018
+ text_config = config.get_text_config()
1019
+ if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:
1020
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1021
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1022
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
1023
+ sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (
1024
+ cache_position.reshape(-1, 1) -
1025
+ text_config.sliding_window
1026
+ )
1027
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1028
+ causal_mask *= diagonal_attend_mask
1029
+ causal_mask = causal_mask[None, None,
1030
+ :, :].expand(batch_size, 1, -1, -1)
1031
+ if attention_mask is not None:
1032
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1033
+ if attention_mask.shape[-1] > target_length:
1034
+ attention_mask = attention_mask[:, :target_length]
1035
+ mask_length = attention_mask.shape[-1]
1036
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
1037
+ causal_mask.device
1038
+ )
1039
+ padding_mask = padding_mask == 0
1040
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1041
+ padding_mask, min_dtype
1042
+ )
1043
+ return causal_mask
1044
+
1045
+
1046
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs):
1047
+ ...
1048
+
1049
+
1050
+ @auto_docstring
1051
+ class SDARForCausalLM(SDARPreTrainedModel, GenerationMixin):
1052
+ _tied_weights_keys = ["lm_head.weight"]
1053
+ _tp_plan = {"lm_head": "colwise_rep"}
1054
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1055
+
1056
+ def __init__(self, config):
1057
+ super().__init__(config)
1058
+ self.model = SDARModel(config)
1059
+ self.vocab_size = config.vocab_size
1060
+ self.lm_head = nn.Linear(
1061
+ config.hidden_size, config.vocab_size, bias=False)
1062
+
1063
+ # Initialize weights and apply final processing
1064
+ self.post_init()
1065
+
1066
+ def get_input_embeddings(self):
1067
+ return self.model.embed_tokens
1068
+
1069
+ def set_input_embeddings(self, value):
1070
+ self.model.embed_tokens = value
1071
+
1072
+ def get_output_embeddings(self):
1073
+ return self.lm_head
1074
+
1075
+ def set_output_embeddings(self, new_embeddings):
1076
+ self.lm_head = new_embeddings
1077
+
1078
+ def set_decoder(self, decoder):
1079
+ self.model = decoder
1080
+
1081
+ def get_decoder(self):
1082
+ return self.model
1083
+
1084
+ def prepare_for_bd_training(self, inputs_ids, position_ids, prompt_mask):
1085
+ bsz, seq_len = inputs_ids.shape
1086
+ num_tokens = calculate_token_nums(position_ids) # List[torch.Tensor]
1087
+ noisy_inputs_ids, logits_to_keep_half, p_mask = forward_add_noise_packed(
1088
+ inputs_ids=inputs_ids,
1089
+ num_tokens_list=num_tokens,
1090
+ prompt_mask=prompt_mask,
1091
+ mask_id=self.config.mask_token_id,
1092
+ )
1093
+ router_noisy_part_list = []
1094
+ for i in range(bsz):
1095
+ cur_router_noisy_part = (torch.arange(num_tokens[i].shape[0] *2) % 2 == 0).to(inputs_ids.device)
1096
+ cur_router_noisy_part = cur_router_noisy_part.repeat_interleave(num_tokens[i].repeat_interleave(2))
1097
+ router_noisy_part_list.append(cur_router_noisy_part)
1098
+ router_noisy_part = torch.stack(router_noisy_part_list, dim=0)
1099
+
1100
+ # concated inputs_ids: (bzs, seq_len x 2)
1101
+ concat_inputs_ids = inputs_ids.repeat(1, 2)
1102
+ # concated logits_to_keep: (bsz, seq_len x 2)
1103
+ logits_to_keep = torch.zeros(
1104
+ bsz, 2 * seq_len, dtype=torch.bool, device=inputs_ids.device)
1105
+ # concated position_ids: (bsz, seq_len x 2)
1106
+ concat_position_ids = torch.zeros(
1107
+ bsz, 2 * seq_len, dtype=position_ids.dtype, device=position_ids.device)
1108
+ for i in range(bsz):
1109
+ concat_inputs_ids[i][router_noisy_part[i]] = noisy_inputs_ids[i]
1110
+ concat_inputs_ids[i][~router_noisy_part[i]] = inputs_ids[i]
1111
+
1112
+ logits_to_keep[i][router_noisy_part[i]] = logits_to_keep_half[i]
1113
+
1114
+ concat_position_ids[i][router_noisy_part[i]] = position_ids[i]
1115
+ concat_position_ids[i][~router_noisy_part[i]] = position_ids[i]
1116
+
1117
+ # create flex_attention mask
1118
+ attention_mask = block_attn_mask(num_tokens, self.config.block_size, inputs_ids.device)
1119
+ flex_attention_mask_3d = create_block_mask(
1120
+ lambda b, h, q_idx, kv_idx: attention_mask[b, q_idx, kv_idx],
1121
+ B=attention_mask.size(0), H=None,
1122
+ Q_LEN=attention_mask.size(1), KV_LEN=attention_mask.size(2),
1123
+ device=inputs_ids.device,
1124
+ )
1125
+
1126
+ return concat_inputs_ids, concat_position_ids, flex_attention_mask_3d, logits_to_keep_half, logits_to_keep, p_mask
1127
+
1128
+ @can_return_tuple
1129
+ @auto_docstring
1130
+ def forward(
1131
+ self,
1132
+ input_ids: Optional[torch.LongTensor] = None,
1133
+ attention_mask: Optional[torch.Tensor] = None,
1134
+ position_ids: Optional[torch.LongTensor] = None,
1135
+ past_key_values: Optional[Cache] = None,
1136
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1137
+ labels: Optional[torch.LongTensor] = None,
1138
+ use_cache: Optional[bool] = None,
1139
+ output_attentions: Optional[bool] = None,
1140
+ output_hidden_states: Optional[bool] = None,
1141
+ cache_position: Optional[torch.LongTensor] = None,
1142
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1143
+ **kwargs: Unpack[KwargsForCausalLM],
1144
+ ) -> CausalLMOutputWithPast:
1145
+ r"""
1146
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1147
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1148
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1149
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1150
+
1151
+ Example:
1152
+
1153
+ ```python
1154
+ >>> from transformers import AutoTokenizer, SDARForCausalLM
1155
+
1156
+ >>> model = SDARForCausalLM.from_pretrained("DiffuOpen/SDAR-1.7B-Chat")
1157
+ >>> tokenizer = AutoTokenizer.from_pretrained("DiffuOpen/SDAR-1.7B-Chat")
1158
+
1159
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1160
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1161
+
1162
+ >>> # Generate
1163
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1164
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1165
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1166
+ ```"""
1167
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1168
+ output_hidden_states = (
1169
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1170
+ )
1171
+ if self.training:
1172
+ assert inputs_embeds is None, "only support input_ids during training"
1173
+ prompt_mask = (labels == -100) if labels is not None else None
1174
+ # PT packing / some collators omit position_ids; SDAR BD mask needs them.
1175
+ if position_ids is None:
1176
+ position_ids = torch.arange(
1177
+ input_ids.shape[-1], device=input_ids.device, dtype=torch.long
1178
+ ).unsqueeze(0).repeat(input_ids.shape[0], 1)
1179
+ position_ids = modify_padded_position_ids_2d(position_ids)
1180
+ concat_inputs_ids, concat_position_ids, flex_attention_mask_3d, logits_to_keep_half, logits_to_keep, p_mask = self.prepare_for_bd_training(input_ids, position_ids, prompt_mask)
1181
+ # Do not let trainer/collator attention_mask overwrite the BlockMask.
1182
+ kwargs.pop("attention_mask", None)
1183
+ outputs = self.model(
1184
+ input_ids=concat_inputs_ids,
1185
+ attention_mask=flex_attention_mask_3d,
1186
+ position_ids=concat_position_ids,
1187
+ output_attentions=output_attentions,
1188
+ output_hidden_states=output_hidden_states,
1189
+ return_dict=True,
1190
+ cache_position=cache_position,
1191
+ **kwargs,
1192
+ )
1193
+ hidden_states = outputs.last_hidden_state
1194
+ hidden_states = hidden_states[logits_to_keep].contiguous()
1195
+ assert labels is not None, "Labels must be provided for training."
1196
+ answer_len = (labels != -100).sum()
1197
+ loss_fct = FusedLinearDiffusionCrossEntropyLoss(reduction='sum')
1198
+ loss = loss_fct( # it will return (sum_loss, unreduced_loss)
1199
+ # conduct `view(-1, V)` inside the function
1200
+ x=hidden_states,
1201
+ target=labels[logits_to_keep_half].contiguous(),
1202
+ weight=self.lm_head.weight,
1203
+ bias=self.lm_head.bias,
1204
+ p_mask=p_mask,
1205
+ )
1206
+ loss = loss / answer_len
1207
+ logits = None
1208
+ else:
1209
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1210
+ outputs: BaseModelOutputWithPast = self.model(
1211
+ input_ids=input_ids,
1212
+ attention_mask=attention_mask,
1213
+ position_ids=position_ids,
1214
+ past_key_values=past_key_values,
1215
+ inputs_embeds=inputs_embeds,
1216
+ use_cache=use_cache,
1217
+ output_attentions=output_attentions,
1218
+ output_hidden_states=output_hidden_states,
1219
+ cache_position=cache_position,
1220
+ **kwargs,
1221
+ )
1222
+
1223
+ hidden_states = outputs.last_hidden_state
1224
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1225
+ slice_indices = slice(-logits_to_keep,
1226
+ None) if isinstance(logits_to_keep, int) else logits_to_keep
1227
+ hidden_states = hidden_states[:, slice_indices, :].contiguous()
1228
+ fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.training
1229
+ if fuse_linear_and_cross_entropy:
1230
+ # When using fused_linear_ce_loss, we do not compute the whole logits on HBM
1231
+ logits = None
1232
+ else:
1233
+ logits = self.lm_head(hidden_states)
1234
+
1235
+ loss = None
1236
+ if labels is not None:
1237
+ # FusedLinearCrossEntropyLoss will be implemented by monkey patch when training
1238
+ # We don't use it when inferencing
1239
+ loss_fct = nn.CrossEntropyLoss() # nn.CE
1240
+ loss = loss_fct(
1241
+ logits.view(-1, self.config.vocab_size), labels.view(-1))
1242
+
1243
+ return CausalLMOutputWithPast(
1244
+ loss=loss,
1245
+ logits=logits,
1246
+ past_key_values=outputs.past_key_values,
1247
+ hidden_states=outputs.hidden_states,
1248
+ attentions=outputs.attentions,
1249
+ )
1250
+
1251
+
1252
+ __all__ = [
1253
+ "SDARForCausalLM",
1254
+ "SDARModel",
1255
+ "SDARPreTrainedModel",
1256
+ ]
models/dLMs-block8-epoch1/special_tokens_map.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<question>",
4
+ "</question>",
5
+ "<solution>",
6
+ "</solution>",
7
+ "<answer>",
8
+ "</answer>",
9
+ "[MASK]"
10
+ ],
11
+ "bos_token": {
12
+ "content": "[BOS]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ },
18
+ "eos_token": {
19
+ "content": "[EOS]",
20
+ "lstrip": false,
21
+ "normalized": false,
22
+ "rstrip": false,
23
+ "single_word": false
24
+ },
25
+ "mask_token": {
26
+ "content": "[MASK]",
27
+ "lstrip": false,
28
+ "normalized": false,
29
+ "rstrip": false,
30
+ "single_word": false
31
+ },
32
+ "pad_token": {
33
+ "content": "[PAD]",
34
+ "lstrip": false,
35
+ "normalized": false,
36
+ "rstrip": false,
37
+ "single_word": false
38
+ },
39
+ "unk_token": {
40
+ "content": "[UNK]",
41
+ "lstrip": false,
42
+ "normalized": false,
43
+ "rstrip": false,
44
+ "single_word": false
45
+ }
46
+ }
models/dLMs-block8-epoch1/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
models/dLMs-block8-epoch1/tokenizer_config.json ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "0": {
5
+ "content": "[UNK]",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "1": {
13
+ "content": "[PAD]",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "2": {
21
+ "content": "[BOS]",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "3": {
29
+ "content": "[EOS]",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "4": {
37
+ "content": "<question>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "5": {
45
+ "content": "</question>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "6": {
53
+ "content": "<solution>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "7": {
61
+ "content": "</solution>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "8": {
69
+ "content": "<answer>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "9": {
77
+ "content": "</answer>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "2196": {
85
+ "content": "[MASK]",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "2197": {
93
+ "content": "<special_token_1>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "2198": {
101
+ "content": "<special_token_2>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "2199": {
109
+ "content": "<special_token_3>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "2200": {
117
+ "content": "<special_token_4>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": true
123
+ }
124
+ },
125
+ "additional_special_tokens": [
126
+ "<question>",
127
+ "</question>",
128
+ "<solution>",
129
+ "</solution>",
130
+ "<answer>",
131
+ "</answer>",
132
+ "[MASK]"
133
+ ],
134
+ "bos_token": "[BOS]",
135
+ "clean_up_tokenization_spaces": false,
136
+ "eos_token": "[EOS]",
137
+ "extra_special_tokens": {},
138
+ "mask_token": "[MASK]",
139
+ "model_max_length": 1000000000000000019884624838656,
140
+ "pad_token": "[PAD]",
141
+ "padding_side": "right",
142
+ "split_special_tokens": false,
143
+ "tokenizer_class": "PreTrainedTokenizer",
144
+ "unk_token": "[UNK]"
145
+ }