Update configuration_sdar.py (#3)
Browse files- Update configuration_sdar.py (6daf6b2351df599efb36d8903c4d54ddfb6dd30f)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205# coding=utf-8# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""SDAR model configuration"""from transformers.configuration_utils import PretrainedConfigfrom transformers.modeling_rope_utils import rope_config_validationfrom transformers.utils import logginglogger = logging.get_logger(__name__)class SDARConfig(PretrainedConfig):r"""This is the configuration class to store the configuration of a [`SDARModel`]. It is used to instantiate aSDAR model according to the specified arguments, defining the model architecture. Instantiating a configurationwith the defaults will yield a similar configuration to that ofSDAR-1.7B [DiffuOpen/SDAR-1.7B-Chat](https://huggingface.co/DiffuOpen/SDAR-1.7B-Chat/).Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read thedocumentation from [`PretrainedConfig`] for more information.Args:vocab_size (`int`, *optional*, defaults to 151936):Vocabulary size of the SDAR model. Defines the number of different tokens that can be represented by the`inputs_ids` passed when calling [`SDARModel`]hidden_size (`int`, *optional*, defaults to 4096):Dimension of the hidden representations.intermediate_size (`int`, *optional*, defaults to 22016):Dimension of the MLP representations.num_hidden_layers (`int`, *optional*, defaults to 32):Number of hidden layers in the Transformer encoder.num_attention_heads (`int`, *optional*, defaults to 32):Number of attention heads for each attention layer in the Transformer encoder.num_key_value_heads (`int`, *optional*, defaults to 32):This is the number of key_value heads that should be used to implement Grouped Query Attention. If`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. Whenconverting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructedby meanpooling all the original heads within that group. For more details checkout [thispaper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.head_dim (`int`, *optional*, defaults to 128):The attention head dimension.hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):The non-linear activation function (function or string) in the decoder.max_position_embeddings (`int`, *optional*, defaults to 32768):The maximum sequence length that this model might ever be used with.initializer_range (`float`, *optional*, defaults to 0.02):The standard deviation of the truncated_normal_initializer for initializing all weight matrices.rms_norm_eps (`float`, *optional*, defaults to 1e-06):The epsilon used by the rms normalization layers.use_cache (`bool`, *optional*, defaults to `True`):Whether or not the model should return the last key/values attentions (not used by all models). Onlyrelevant if `config.is_decoder=True`.tie_word_embeddings (`bool`, *optional*, defaults to `False`):Whether the model's input and output word embeddings should be tied.rope_theta (`float`, *optional*, defaults to 10000.0):The base period of the RoPE embeddings.rope_scaling (`Dict`, *optional*):Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope typeand you expect the model to work on longer `max_position_embeddings`, we recommend you to update this valueaccordingly.Expected contents:`rope_type` (`str`):The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope','llama3'], with 'default' being the original RoPE implementation.`factor` (`float`, *optional*):Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. Inmost scaling types, a `factor` of x will enable the model to handle sequences of length x *original maximum pre-trained length.`original_max_position_embeddings` (`int`, *optional*):Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used duringpretraining.`attention_factor` (`float`, *optional*):Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attentioncomputation. If unspecified, it defaults to value recommended by the implementation, using the`factor` field to infer the suggested value.`beta_fast` (`float`, *optional*):Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linearramp function. If unspecified, it defaults to 32.`beta_slow` (`float`, *optional*):Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linearramp function. If unspecified, it defaults to 1.`short_factor` (`List[float]`, *optional*):Only used with 'longrope'. The scaling factor to be applied to short contexts (<`original_max_position_embeddings`). Must be a list of numbers with the same length as the hiddensize divided by the number of attention heads divided by 2`long_factor` (`List[float]`, *optional*):Only used with 'longrope'. The scaling factor to be applied to long contexts (<`original_max_position_embeddings`). Must be a list of numbers with the same length as the hiddensize divided by the number of attention heads divided by 2`low_freq_factor` (`float`, *optional*):Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE`high_freq_factor` (`float`, *optional*):Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPEattention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):Whether to use a bias in the query, key, value and output projection layers during self-attention.use_sliding_window (`bool`, *optional*, defaults to `False`):Whether to use sliding window attention.sliding_window (`int`, *optional*, defaults to 4096):Sliding window attention (SWA) window size. If not specified, will default to `4096`.max_window_layers (`int`, *optional*, defaults to 28):The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.attention_dropout (`float`, *optional*, defaults to 0.0):The dropout ratio for the attention probabilities.```python>>> from transformers import SDARModel, SDARConfig>>> # Initializing a SDAR style configuration>>> configuration = SDARConfig()>>> # Initializing a model from the SDAR-8B style configuration>>> model = SDARModel(configuration)>>> # Accessing the model configuration>>> configuration = model.config```"""model_type = "sdar"keys_to_ignore_at_inference = ["past_key_values"]# Default tensor parallel plan for base model `SDAR`base_model_tp_plan = {"layers.*.self_attn.q_proj": "colwise","layers.*.self_attn.k_proj": "colwise","layers.*.self_attn.v_proj": "colwise","layers.*.self_attn.o_proj": "rowwise","layers.*.mlp.gate_proj": "colwise","layers.*.mlp.up_proj": "colwise","layers.*.mlp.down_proj": "rowwise",}base_model_pp_plan = {"embed_tokens": (["input_ids"], ["inputs_embeds"]),"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),"norm": (["hidden_states"], ["hidden_states"]),}def __init__(self,vocab_size=151936,hidden_size=4096,intermediate_size=22016,num_hidden_layers=32,num_attention_heads=32,num_key_value_heads=32,head_dim=128,hidden_act="silu",max_position_embeddings=32768,initializer_range=0.02,rms_norm_eps=1e-6,use_cache=True,tie_word_embeddings=False,rope_theta=10000.0,rope_scaling=None,attention_bias=False,use_sliding_window=False,sliding_window=4096,max_window_layers=28,attention_dropout=0.0,**kwargs,):self.vocab_size = vocab_sizeself.max_position_embeddings = max_position_embeddingsself.hidden_size = hidden_sizeself.intermediate_size = intermediate_sizeself.num_hidden_layers = num_hidden_layersself.num_attention_heads = num_attention_headsself.use_sliding_window = use_sliding_windowself.sliding_window = sliding_window # we check `use_sliding_window` in the modeling codeself.max_window_layers = max_window_layers# for backward compatibilityif num_key_value_heads is None:num_key_value_heads = num_attention_headsself.num_key_value_heads = num_key_value_headsself.head_dim = head_dimself.hidden_act = hidden_actself.initializer_range = initializer_rangeself.rms_norm_eps = rms_norm_epsself.use_cache = use_cacheself.rope_theta = rope_thetaself.rope_scaling = rope_scalingself.attention_bias = attention_biasself.attention_dropout = attention_dropout# Validate the correctness of rotary position embeddings parameters# BC: if there is a 'type' field, move it to 'rope_type'.if self.rope_scaling is not None and "type" in self.rope_scaling:self.rope_scaling["rope_type"] = self.rope_scaling["type"]rope_config_validation(self)super().__init__(tie_word_embeddings=tie_word_embeddings,**kwargs,)__all__ = ["SDARConfig"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171# SPDX-License-Identifier: Apache-2.0# adapted fromhttps://github.com/Gen-Verse/dLLM-RL# adapted from SADR https://github.com/JetAstra/SDAR/blob/main/generate.pyimport torchfrom torch.nn import functional as Ffrom transformers.cache_utils import DynamicCachedef top_k_logits(logits, k):if k <= 0:return logitselse:values, _ = torch.topk(logits, k)min_values = values[..., -1, None]return torch.where(logits < min_values, torch.full_like(logits, float("-inf")), logits)def top_p_logits(logits, p):sorted_logits, sorted_indices = torch.sort(logits, descending=True)cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)sorted_mask = cumulative_probs > psorted_mask[..., 1:] = sorted_mask[..., :-1].clone()sorted_mask[..., 0] = Falsemask_indices = torch.scatter(torch.full_like(logits, False, dtype=torch.bool), -1, sorted_indices, sorted_mask)logits = logits.masked_fill(mask_indices, float("-inf"))return logitsdef sample_with_temperature_topk_topp(logits, temperature=1.0, top_k=0, top_p=1.0):orig_shape = logits.shape[:-1] # [batch, block]vocab_size = logits.shape[-1]logits = logits.reshape(-1, vocab_size) # [batch*block, vocab]if temperature != 1.0:logits = logits / temperatureif top_k > 0:logits = top_k_logits(logits, top_k)if top_p < 1.0:logits = top_p_logits(logits, top_p)probs = F.softmax(logits, dim=-1) # shape: [batch*block, vocab]assert probs.dim() == 2token = torch.multinomial(probs, num_samples=1) # [batch*block, 1]token_prob = torch.gather(probs, -1, token) # [batch*block, 1]return token.view(*orig_shape), token_prob.view(*orig_shape)def get_num_transfer_tokens(block_length, steps):base = block_length // stepsremainder = block_length % stepsnum_transfer_tokens = torch.zeros(steps, dtype=torch.int64) + basenum_transfer_tokens[:remainder] += 1return num_transfer_tokens@torch.no_grad()def block_diffusion_generate(model,prompt,mask_id,gen_length=128,block_length=8,denoising_steps=8,temperature=1.0,top_k=0,top_p=1.0,remasking_strategy="low_confidence_dynamic",confidence_threshold=0.85,stopping_criteria_idx=None,):model.eval()input_ids = prompt["input_ids"]prompt_length = input_ids.shape[1]past_key_values = DynamicCache()num_blocks = (prompt_length + gen_length + block_length - 1) // block_lengthtotal_length = num_blocks * block_lengthblock_mask = torch.tril(torch.ones(num_blocks, num_blocks, device=model.device))block_diffusion_attention_mask = block_mask.repeat_interleave(block_length, dim=0).repeat_interleave(block_length, dim=1).unsqueeze(0)position_ids = torch.arange(total_length, device=model.device).unsqueeze(0)x = torch.full((1, total_length), mask_id, dtype=torch.long, device=model.device)x[:, :prompt_length] = input_idsprefill_blocks = prompt_length // block_lengthprefill_length = prefill_blocks * block_length# Prefill stageif prefill_length > 0:cur_x = x[:, :prefill_length]cur_attn_mask = block_diffusion_attention_mask[:, :prefill_length, :prefill_length]if cur_attn_mask.dim() == 3:cur_attn_mask = cur_attn_mask[:, None, :, :]cur_position_ids = position_ids[:, :prefill_length]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)num_transfer_tokens = get_num_transfer_tokens(block_length, denoising_steps)# Decode stagefor num_block in range(prefill_blocks, num_blocks):cur_x = x[:, num_block * block_length : (num_block + 1) * block_length].clone()cur_attn_mask = block_diffusion_attention_mask[:, num_block * block_length : (num_block + 1) * block_length, : (num_block + 1) * block_length]if cur_attn_mask.dim() == 3:cur_attn_mask = cur_attn_mask[:, None, :, :]cur_position_ids = position_ids[:, num_block * block_length : (num_block + 1) * block_length]for step in range(denoising_steps + 1):mask_index = cur_x == mask_idif mask_index.sum() == 0:# Store kv cachemodel(cur_x, attention_mask=cur_attn_mask, position_ids=cur_position_ids, past_key_values=past_key_values, use_cache=True, store_kv=True)break# Denosingoutput = 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)# Extract logits from the output - handle both CausalLMOutputWithPast and BaseModelOutputWithPastif hasattr(output, "logits") and output.logits is not None:logits = output.logitselif hasattr(output, "last_hidden_state"):# If logits don't exist but we have hidden states, compute logits from the model's lm_head# This can happen if the model returns BaseModelOutputWithPast instead of CausalLMOutputWithPastif hasattr(model, "lm_head"):hidden_states = output.last_hidden_statelogits = model.lm_head(hidden_states)else:raise ValueError("Model output does not contain logits and model does not have lm_head to compute them.")else:raise ValueError(f"Unexpected model output type: {type(output)}. Expected CausalLMOutputWithPast or BaseModelOutputWithPast with logits or last_hidden_state.")# Samplingx0, x0_p = sample_with_temperature_topk_topp(logits, temperature=temperature, top_k=top_k, top_p=top_p)# Sampling strategyif remasking_strategy == "sequential":transfer_index = torch.zeros_like(x0, dtype=torch.bool)for j in range(cur_x.shape[0]):if mask_index[j].any():first_mask_index = mask_index[j].nonzero(as_tuple=True)[0].min().item()transfer_index[j, first_mask_index : first_mask_index + num_transfer_tokens[step]] = Trueelse:raise ValueError("No mask tokens found in the current block.")elif remasking_strategy == "low_confidence_static":confidence = torch.where(mask_index, x0_p, -torch.inf)transfer_index = torch.zeros_like(x0, dtype=torch.bool)for j in range(confidence.shape[0]):_, idx = torch.topk(confidence[j], num_transfer_tokens[step])transfer_index[j, idx] = Trueelif remasking_strategy == "low_confidence_dynamic":confidence = torch.where(mask_index, x0_p, -torch.inf)transfer_index = torch.zeros_like(x0, dtype=torch.bool)for j in range(confidence.shape[0]):high_conf_mask = confidence[j] > confidence_thresholdnum_high_confidence = high_conf_mask.sum()if num_high_confidence >= num_transfer_tokens[step]:transfer_index[j] = high_conf_maskelse:_, idx = torch.topk(confidence[j], num_transfer_tokens[step])transfer_index[j, idx] = Trueelse:raise ValueError(f"Unknown remasking strategy: {remasking_strategy}")cur_x[transfer_index] = x0[transfer_index]x[:, num_block * block_length : (num_block + 1) * block_length] = cur_xif stopping_criteria_idx is not None and any(stop_idx in x[:, prompt_length:] for stop_idx in stopping_criteria_idx):breakreturn x
configuration_sdar.py+171-205