Update configuration_sdar.py

#3
by exdysa - opened
Files changed (1) hide show
  1. configuration_sdar.py +171 -205
configuration_sdar.py CHANGED
@@ -1,205 +1,171 @@
1
- # coding=utf-8
2
- # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
- """SDAR model configuration"""
16
-
17
- from transformers.configuration_utils import PretrainedConfig
18
- from transformers.modeling_rope_utils import rope_config_validation
19
- from transformers.utils import logging
20
-
21
-
22
- logger = logging.get_logger(__name__)
23
-
24
-
25
- class SDARConfig(PretrainedConfig):
26
- r"""
27
- This is the configuration class to store the configuration of a [`SDARModel`]. It is used to instantiate a
28
- SDAR model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
- with the defaults will yield a similar configuration to that of
30
- SDAR-1.7B [DiffuOpen/SDAR-1.7B-Chat](https://huggingface.co/DiffuOpen/SDAR-1.7B-Chat/).
31
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
- documentation from [`PretrainedConfig`] for more information.
33
- Args:
34
- vocab_size (`int`, *optional*, defaults to 151936):
35
- Vocabulary size of the SDAR model. Defines the number of different tokens that can be represented by the
36
- `inputs_ids` passed when calling [`SDARModel`]
37
- hidden_size (`int`, *optional*, defaults to 4096):
38
- Dimension of the hidden representations.
39
- intermediate_size (`int`, *optional*, defaults to 22016):
40
- Dimension of the MLP representations.
41
- num_hidden_layers (`int`, *optional*, defaults to 32):
42
- Number of hidden layers in the Transformer encoder.
43
- num_attention_heads (`int`, *optional*, defaults to 32):
44
- Number of attention heads for each attention layer in the Transformer encoder.
45
- num_key_value_heads (`int`, *optional*, defaults to 32):
46
- This is the number of key_value heads that should be used to implement Grouped Query Attention. If
47
- `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
48
- `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
49
- converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
50
- by meanpooling all the original heads within that group. For more details checkout [this
51
- paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
52
- head_dim (`int`, *optional*, defaults to 128):
53
- The attention head dimension.
54
- hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
- The non-linear activation function (function or string) in the decoder.
56
- max_position_embeddings (`int`, *optional*, defaults to 32768):
57
- The maximum sequence length that this model might ever be used with.
58
- initializer_range (`float`, *optional*, defaults to 0.02):
59
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
- rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
- The epsilon used by the rms normalization layers.
62
- use_cache (`bool`, *optional*, defaults to `True`):
63
- Whether or not the model should return the last key/values attentions (not used by all models). Only
64
- relevant if `config.is_decoder=True`.
65
- tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
- Whether the model's input and output word embeddings should be tied.
67
- rope_theta (`float`, *optional*, defaults to 10000.0):
68
- The base period of the RoPE embeddings.
69
- rope_scaling (`Dict`, *optional*):
70
- Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
71
- and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
72
- accordingly.
73
- Expected contents:
74
- `rope_type` (`str`):
75
- The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
76
- 'llama3'], with 'default' being the original RoPE implementation.
77
- `factor` (`float`, *optional*):
78
- Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
79
- most scaling types, a `factor` of x will enable the model to handle sequences of length x *
80
- original maximum pre-trained length.
81
- `original_max_position_embeddings` (`int`, *optional*):
82
- Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
83
- pretraining.
84
- `attention_factor` (`float`, *optional*):
85
- Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
86
- computation. If unspecified, it defaults to value recommended by the implementation, using the
87
- `factor` field to infer the suggested value.
88
- `beta_fast` (`float`, *optional*):
89
- Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
90
- ramp function. If unspecified, it defaults to 32.
91
- `beta_slow` (`float`, *optional*):
92
- Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
93
- ramp function. If unspecified, it defaults to 1.
94
- `short_factor` (`List[float]`, *optional*):
95
- Only used with 'longrope'. The scaling factor to be applied to short contexts (<
96
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
97
- size divided by the number of attention heads divided by 2
98
- `long_factor` (`List[float]`, *optional*):
99
- Only used with 'longrope'. The scaling factor to be applied to long contexts (<
100
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
101
- size divided by the number of attention heads divided by 2
102
- `low_freq_factor` (`float`, *optional*):
103
- Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
104
- `high_freq_factor` (`float`, *optional*):
105
- Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
106
- attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
107
- Whether to use a bias in the query, key, value and output projection layers during self-attention.
108
- use_sliding_window (`bool`, *optional*, defaults to `False`):
109
- Whether to use sliding window attention.
110
- sliding_window (`int`, *optional*, defaults to 4096):
111
- Sliding window attention (SWA) window size. If not specified, will default to `4096`.
112
- max_window_layers (`int`, *optional*, defaults to 28):
113
- The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
114
- attention_dropout (`float`, *optional*, defaults to 0.0):
115
- The dropout ratio for the attention probabilities.
116
- ```python
117
- >>> from transformers import SDARModel, SDARConfig
118
- >>> # Initializing a SDAR style configuration
119
- >>> configuration = SDARConfig()
120
- >>> # Initializing a model from the SDAR-8B style configuration
121
- >>> model = SDARModel(configuration)
122
- >>> # Accessing the model configuration
123
- >>> configuration = model.config
124
- ```"""
125
-
126
- model_type = "sdar"
127
- keys_to_ignore_at_inference = ["past_key_values"]
128
-
129
- # Default tensor parallel plan for base model `SDAR`
130
- base_model_tp_plan = {
131
- "layers.*.self_attn.q_proj": "colwise",
132
- "layers.*.self_attn.k_proj": "colwise",
133
- "layers.*.self_attn.v_proj": "colwise",
134
- "layers.*.self_attn.o_proj": "rowwise",
135
- "layers.*.mlp.gate_proj": "colwise",
136
- "layers.*.mlp.up_proj": "colwise",
137
- "layers.*.mlp.down_proj": "rowwise",
138
- }
139
- base_model_pp_plan = {
140
- "embed_tokens": (["input_ids"], ["inputs_embeds"]),
141
- "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
142
- "norm": (["hidden_states"], ["hidden_states"]),
143
- }
144
-
145
- def __init__(
146
- self,
147
- vocab_size=151936,
148
- hidden_size=4096,
149
- intermediate_size=22016,
150
- num_hidden_layers=32,
151
- num_attention_heads=32,
152
- num_key_value_heads=32,
153
- head_dim=128,
154
- hidden_act="silu",
155
- max_position_embeddings=32768,
156
- initializer_range=0.02,
157
- rms_norm_eps=1e-6,
158
- use_cache=True,
159
- tie_word_embeddings=False,
160
- rope_theta=10000.0,
161
- rope_scaling=None,
162
- attention_bias=False,
163
- use_sliding_window=False,
164
- sliding_window=4096,
165
- max_window_layers=28,
166
- attention_dropout=0.0,
167
- **kwargs,
168
- ):
169
- self.vocab_size = vocab_size
170
- self.max_position_embeddings = max_position_embeddings
171
- self.hidden_size = hidden_size
172
- self.intermediate_size = intermediate_size
173
- self.num_hidden_layers = num_hidden_layers
174
- self.num_attention_heads = num_attention_heads
175
- self.use_sliding_window = use_sliding_window
176
- self.sliding_window = sliding_window # we check `use_sliding_window` in the modeling code
177
- self.max_window_layers = max_window_layers
178
-
179
- # for backward compatibility
180
- if num_key_value_heads is None:
181
- num_key_value_heads = num_attention_heads
182
-
183
- self.num_key_value_heads = num_key_value_heads
184
- self.head_dim = head_dim
185
- self.hidden_act = hidden_act
186
- self.initializer_range = initializer_range
187
- self.rms_norm_eps = rms_norm_eps
188
- self.use_cache = use_cache
189
- self.rope_theta = rope_theta
190
- self.rope_scaling = rope_scaling
191
- self.attention_bias = attention_bias
192
- self.attention_dropout = attention_dropout
193
- # Validate the correctness of rotary position embeddings parameters
194
- # BC: if there is a 'type' field, move it to 'rope_type'.
195
- if self.rope_scaling is not None and "type" in self.rope_scaling:
196
- self.rope_scaling["rope_type"] = self.rope_scaling["type"]
197
- rope_config_validation(self)
198
-
199
- super().__init__(
200
- tie_word_embeddings=tie_word_embeddings,
201
- **kwargs,
202
- )
203
-
204
-
205
- __all__ = ["SDARConfig"]
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # adapted fromhttps://github.com/Gen-Verse/dLLM-RL
3
+ # adapted from SADR https://github.com/JetAstra/SDAR/blob/main/generate.py
4
+
5
+ import torch
6
+ from torch.nn import functional as F
7
+ from transformers.cache_utils import DynamicCache
8
+
9
+
10
+ def top_k_logits(logits, k):
11
+ if k <= 0:
12
+ return logits
13
+ else:
14
+ values, _ = torch.topk(logits, k)
15
+ min_values = values[..., -1, None]
16
+ return torch.where(logits < min_values, torch.full_like(logits, float("-inf")), logits)
17
+
18
+
19
+ def top_p_logits(logits, p):
20
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
21
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
22
+ sorted_mask = cumulative_probs > p
23
+ sorted_mask[..., 1:] = sorted_mask[..., :-1].clone()
24
+ sorted_mask[..., 0] = False
25
+ mask_indices = torch.scatter(torch.full_like(logits, False, dtype=torch.bool), -1, sorted_indices, sorted_mask)
26
+ logits = logits.masked_fill(mask_indices, float("-inf"))
27
+ return logits
28
+
29
+
30
+ def sample_with_temperature_topk_topp(logits, temperature=1.0, top_k=0, top_p=1.0):
31
+ orig_shape = logits.shape[:-1] # [batch, block]
32
+ vocab_size = logits.shape[-1]
33
+
34
+ logits = logits.reshape(-1, vocab_size) # [batch*block, vocab]
35
+
36
+ if temperature != 1.0:
37
+ logits = logits / temperature
38
+ if top_k > 0:
39
+ logits = top_k_logits(logits, top_k)
40
+ if top_p < 1.0:
41
+ logits = top_p_logits(logits, top_p)
42
+ probs = F.softmax(logits, dim=-1) # shape: [batch*block, vocab]
43
+ assert probs.dim() == 2
44
+ token = torch.multinomial(probs, num_samples=1) # [batch*block, 1]
45
+ token_prob = torch.gather(probs, -1, token) # [batch*block, 1]
46
+
47
+ return token.view(*orig_shape), token_prob.view(*orig_shape)
48
+
49
+
50
+ def get_num_transfer_tokens(block_length, steps):
51
+ base = block_length // steps
52
+ remainder = block_length % steps
53
+ num_transfer_tokens = torch.zeros(steps, dtype=torch.int64) + base
54
+ num_transfer_tokens[:remainder] += 1
55
+ return num_transfer_tokens
56
+
57
+
58
+ @torch.no_grad()
59
+ def block_diffusion_generate(
60
+ model,
61
+ prompt,
62
+ mask_id,
63
+ gen_length=128,
64
+ block_length=8,
65
+ denoising_steps=8,
66
+ temperature=1.0,
67
+ top_k=0,
68
+ top_p=1.0,
69
+ remasking_strategy="low_confidence_dynamic",
70
+ confidence_threshold=0.85,
71
+ stopping_criteria_idx=None,
72
+ ):
73
+ model.eval()
74
+ input_ids = prompt["input_ids"]
75
+ prompt_length = input_ids.shape[1]
76
+ past_key_values = DynamicCache()
77
+
78
+ num_blocks = (prompt_length + gen_length + block_length - 1) // block_length
79
+ total_length = num_blocks * block_length
80
+
81
+ block_mask = torch.tril(torch.ones(num_blocks, num_blocks, device=model.device))
82
+ block_diffusion_attention_mask = block_mask.repeat_interleave(block_length, dim=0).repeat_interleave(block_length, dim=1).unsqueeze(0)
83
+ position_ids = torch.arange(total_length, device=model.device).unsqueeze(0)
84
+
85
+ x = torch.full((1, total_length), mask_id, dtype=torch.long, device=model.device)
86
+ x[:, :prompt_length] = input_ids
87
+ prefill_blocks = prompt_length // block_length
88
+ prefill_length = prefill_blocks * block_length
89
+
90
+ # Prefill stage
91
+ if prefill_length > 0:
92
+ cur_x = x[:, :prefill_length]
93
+ cur_attn_mask = block_diffusion_attention_mask[:, :prefill_length, :prefill_length]
94
+ if cur_attn_mask.dim() == 3:
95
+ cur_attn_mask = cur_attn_mask[:, None, :, :]
96
+ cur_position_ids = position_ids[:, :prefill_length]
97
+ model(cur_x, attention_mask=cur_attn_mask, position_ids=cur_position_ids, past_key_values=past_key_values, use_cache=True, store_kv=True)
98
+
99
+ num_transfer_tokens = get_num_transfer_tokens(block_length, denoising_steps)
100
+
101
+ # Decode stage
102
+ for num_block in range(prefill_blocks, num_blocks):
103
+ cur_x = x[:, num_block * block_length : (num_block + 1) * block_length].clone()
104
+ cur_attn_mask = block_diffusion_attention_mask[:, num_block * block_length : (num_block + 1) * block_length, : (num_block + 1) * block_length]
105
+ if cur_attn_mask.dim() == 3:
106
+ cur_attn_mask = cur_attn_mask[:, None, :, :]
107
+ cur_position_ids = position_ids[:, num_block * block_length : (num_block + 1) * block_length]
108
+ for step in range(denoising_steps + 1):
109
+ mask_index = cur_x == mask_id
110
+ if mask_index.sum() == 0:
111
+ # Store kv cache
112
+ model(cur_x, attention_mask=cur_attn_mask, position_ids=cur_position_ids, past_key_values=past_key_values, use_cache=True, store_kv=True)
113
+ break
114
+
115
+ # Denosing
116
+ output = model(cur_x, attention_mask=cur_attn_mask, position_ids=cur_position_ids, past_key_values=past_key_values, use_cache=True, store_kv=False)
117
+ # Extract logits from the output - handle both CausalLMOutputWithPast and BaseModelOutputWithPast
118
+ if hasattr(output, "logits") and output.logits is not None:
119
+ logits = output.logits
120
+ elif hasattr(output, "last_hidden_state"):
121
+ # If logits don't exist but we have hidden states, compute logits from the model's lm_head
122
+ # This can happen if the model returns BaseModelOutputWithPast instead of CausalLMOutputWithPast
123
+ if hasattr(model, "lm_head"):
124
+ hidden_states = output.last_hidden_state
125
+ logits = model.lm_head(hidden_states)
126
+ else:
127
+ raise ValueError("Model output does not contain logits and model does not have lm_head to compute them.")
128
+ else:
129
+ raise ValueError(f"Unexpected model output type: {type(output)}. Expected CausalLMOutputWithPast or BaseModelOutputWithPast with logits or last_hidden_state.")
130
+
131
+ # Sampling
132
+ x0, x0_p = sample_with_temperature_topk_topp(logits, temperature=temperature, top_k=top_k, top_p=top_p)
133
+
134
+ # Sampling strategy
135
+ if remasking_strategy == "sequential":
136
+ transfer_index = torch.zeros_like(x0, dtype=torch.bool)
137
+ for j in range(cur_x.shape[0]):
138
+ if mask_index[j].any():
139
+ first_mask_index = mask_index[j].nonzero(as_tuple=True)[0].min().item()
140
+ transfer_index[j, first_mask_index : first_mask_index + num_transfer_tokens[step]] = True
141
+ else:
142
+ raise ValueError("No mask tokens found in the current block.")
143
+
144
+ elif remasking_strategy == "low_confidence_static":
145
+ confidence = torch.where(mask_index, x0_p, -torch.inf)
146
+ transfer_index = torch.zeros_like(x0, dtype=torch.bool)
147
+ for j in range(confidence.shape[0]):
148
+ _, idx = torch.topk(confidence[j], num_transfer_tokens[step])
149
+ transfer_index[j, idx] = True
150
+
151
+ elif remasking_strategy == "low_confidence_dynamic":
152
+ confidence = torch.where(mask_index, x0_p, -torch.inf)
153
+ transfer_index = torch.zeros_like(x0, dtype=torch.bool)
154
+ for j in range(confidence.shape[0]):
155
+ high_conf_mask = confidence[j] > confidence_threshold
156
+ num_high_confidence = high_conf_mask.sum()
157
+ if num_high_confidence >= num_transfer_tokens[step]:
158
+ transfer_index[j] = high_conf_mask
159
+ else:
160
+ _, idx = torch.topk(confidence[j], num_transfer_tokens[step])
161
+ transfer_index[j, idx] = True
162
+ else:
163
+ raise ValueError(f"Unknown remasking strategy: {remasking_strategy}")
164
+
165
+ cur_x[transfer_index] = x0[transfer_index]
166
+
167
+ x[:, num_block * block_length : (num_block + 1) * block_length] = cur_x
168
+ if stopping_criteria_idx is not None and any(stop_idx in x[:, prompt_length:] for stop_idx in stopping_criteria_idx):
169
+ break
170
+
171
+ return x