~test conditional workarounds (#1)
Browse files- ~test conditional workarounds (313919b82c1de187baaba2e5222c326e7b2d4400)
22 unmodified lines2324252627282930313233343536375 unmodified lines434445464748495051525354555657585960616263646566676869707172737 unmodified lines818283848586878889909192939495965 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712831 unmodified lines16016116216316416516616715 unmodified lines1831841851861871881891901911927 unmodified lines2002012022032042052062073 unmodified lines2112122132142152162172182192202212222232242252262272282292302312322332342352362372389 unmodified lines24824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827918 unmodified lines2982993003013023033043053063073083093 unmodified lines3133143153163173183193203213223233243253262 unmodified lines3293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603619 unmodified lines3713723733743753763773783793803813823833843853863876 unmodified lines39439539639739839940040161 unmodified lines4634644654664674684694702 unmodified lines4734744754764774784794801 unmodified line4824834844854864874884894904914924934944954968 unmodified lines50550650750850951051151251351451551624 unmodified lines5415425435445455465475485495505515525535545555565575585595605615625635645652 unmodified lines56856957057157257357457557657757856 unmodified lines63563663763863964064164210 unmodified lines6536546556566576586593 unmodified lines66366466566666766866967067167267367467567667767867968011 unmodified lines6926936946956966976986997007017027 unmodified lines71071171271371471571671771871972072172272372472572634 unmodified lines7617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018026 unmodified lines80981081181281381481581651 unmodified lines86886987087187287387487587611 unmodified lines8888898908918928938948957 unmodified lines9039049059069079089099108 unmodified lines91992092192222 unmodified linesfrom typing import Callable, Optional, Tuple, Unionimport torchfrom torch import nnfrom transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCachefrom transformers.generation import GenerationMixinfrom transformers.integrations import use_kernel_forward_from_hubfrom transformers.modeling_attn_mask_utils import AttentionMaskConverterfrom transformers.modeling_flash_attention_utils import FlashAttentionKwargsfrom transformers.modeling_layers import GradientCheckpointingLayerfrom transformers.modeling_outputs import (BaseModelOutputWithPast,5 unmodified linesfrom transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_updatefrom transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModelfrom transformers.processing_utils import Unpackfrom transformers.utils import LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, loggingfrom .configuration_sdar import SDARConfigfrom flash_attn.ops.triton.layer_norm import rms_norm_fn as flash_rms_normimport torch.nn.functional as Ftry:from flash_attn import flash_attn_func, flash_attn_varlen_funcfrom flash_attn.bert_padding import index_first_axis, pad_input, unpad_inputexcept:passtry:from liger_kernel.ops.swiglu import LigerSiLUMulFunction # noqa: F401liger_kernel_is_available = Trueexcept ImportError:liger_kernel_is_available = Falseif is_torch_flex_attn_available():from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attentionfrom transformers.integrations.flex_attention import make_flex_block_causal_masklogger = logging.get_logger(__name__)@use_kernel_forward_from_hub("RMSNorm")7 unmodified linesself.variance_epsilon = epsdef forward(self, hidden_states):return flash_rms_norm(hidden_states, weight=self.weight, bias=None, eps=self.variance_epsilon)'''input_dtype = hidden_states.dtypehidden_states = hidden_states.to(torch.float32)variance = hidden_states.pow(2).mean(-1, keepdim=True)hidden_states = hidden_states * \torch.rsqrt(variance + self.variance_epsilon)return self.weight * hidden_states.to(input_dtype)'''def extra_repr(self):return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"5 unmodified linesself.config = configself.hidden_size = config.hidden_sizeself.intermediate_size = config.intermediate_sizeself.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)self.act_fn = ACT2FN[config.hidden_act]def forward(self, x):if liger_kernel_is_available:return self.down_proj(LigerSiLUMulFunction.apply(self.gate_proj(x), self.up_proj(x)))else:down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))return down_projdef rotate_half(x):"""Rotates half the hidden dims of the input."""x1 = x[..., : x.shape[-1] // 2]x2 = x[..., x.shape[-1] // 2:]return torch.cat((-x2, x1), dim=-1)31 unmodified linesbatch, num_key_value_heads, slen, head_dim = hidden_states.shapeif n_rep == 1:return hidden_stateshidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)15 unmodified linescausal_mask = attention_mask[:, :, :, : key_states.shape[-2]]attn_weights = attn_weights + causal_maskattn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)attn_output = torch.matmul(attn_weights, value_states)attn_output = attn_output.transpose(1, 2).contiguous()7 unmodified linessuper().__init__()self.config = configself.layer_idx = layer_idxself.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)self.num_key_value_groups = config.num_attention_heads // config.num_key_value_headsself.scaling = self.head_dim**-0.5self.attention_dropout = config.attention_dropout3 unmodified linesself.num_attention_heads = config.num_attention_headsself.num_key_value_heads = config.num_key_value_headsself.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias)self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)# unlike olmo, only on the head dim!self.q_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)# thus post q_norm does not need reshapeself.k_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)self.sliding_window = config.sliding_windowif not (self.config.use_sliding_windowand getattr(self.config, "sliding_window", None) is not Noneand self.layer_idx >= self.config.max_window_layers):self.sliding_window = Nonedef forward(9 unmodified linesbsz, q_len = input_shapehidden_shape = (*input_shape, -1, self.head_dim)query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)cos, sin = position_embeddingsquery_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)if past_key_value is not None and kwargs.get("store_kv", False):# sin and cos are specific to RoPE models; cache_position needed for the static cachekey_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)elif past_key_value is not None and not kwargs.get("store_kv", False) and len(past_key_value) > self.layer_idx:# only retrive, do not store kvpast_key_states, past_value_states = past_key_value[self.layer_idx]key_states = torch.cat([past_key_states, key_states], dim=-2)value_states = torch.cat([past_value_states, value_states], dim=-2)'''attention_mask = attention_mask.bool() if attention_mask is not None else Noneif torch.all(attention_mask): # decodingquery_states = query_states.transpose(1, 2)18 unmodified linesenable_gqa=True)attn_output = attn_output.transpose(1, 2).contiguous()'''#print(query_states.shape, key_states.shape, value_states.shape)# --- After RoPE and KV-cache handling, expand KV to all heads ---key_states = repeat_kv(key_states, self.num_key_value_groups) # [B, H, K, D]value_states = repeat_kv(value_states, self.num_key_value_groups) # [B, H, K, D]# --- Convert a 0/1 or bool 4D mask into an *additive* mask, and align to [B, H, Q, K] ---3 unmodified linesam = attention_mask# Support either 2D [B, K] or 4D [B, 1/H, Q, K]if am.dim() == 2:am = am[:, None, None, :k_len] # -> [B,1,1,K]else:am = am[:, :, :, :k_len] # -> [B,1/H,Q,K]finfo_min = torch.finfo(query_states.dtype).min# 0/1 or bool -> float additive mask: 1->0, 0->-infif am.dtype == torch.bool:zero = torch.zeros((), dtype=query_states.dtype, device=am.device)neginf = torch.full((), finfo_min, dtype=query_states.dtype, device=am.device)am = torch.where(am, zero, neginf)else:2 unmodified linesam = torch.where(am > 0, torch.zeros_like(am), torch.full_like(am, finfo_min))# Expand to all heads#if am.shape[1] == 1 and self.num_attention_heads > 1:# am = am.expand(am.shape[0], self.num_attention_heads, am.shape[2], am.shape[3])#attn_mask = am.contiguous()attn_mask = ambsz, q_len = input_shapeif q_len == 1 and past_key_value is not None:# --- Decoding: flash-attn ---q = query_states.transpose(1, 2) # [B,Q,H,D]k = key_states.transpose(1, 2)v = value_states.transpose(1, 2)attn_output = flash_attn_func(q, k, v,causal=True, # For decoding, explicitly set causal=Truesoftmax_scale=self.scaling)attn_output = attn_output.transpose(1, 2).contiguous()else:attn_output = F.scaled_dot_product_attention(query=query_states, # [B,H,Q,D]key=key_states, # [B,H,K,D]value=value_states, # [B,H,K,D]attn_mask=attn_mask, # float additive maskis_causal=False, # All constraints are already encoded in the maskscale=self.scaling,)attn_output = attn_output.transpose(1, 2).contiguous() # -> [B,Q,H,D]9 unmodified linesself.hidden_size = config.hidden_sizeself.self_attn = SDARAttention(config=config, layer_idx=layer_idx)self.mlp = SDARMLP(config)self.input_layernorm = SDARRMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.post_attention_layernorm = SDARRMSNorm(config.hidden_size, eps=config.rms_norm_eps)if (config.sliding_window and config._attn_implementation != "flash_attention_2"): # diff with Llama is this warninglogger.warning_once(f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; ""unexpected results may be encountered.")def forward(self,6 unmodified linesstore_kv: Optional[bool] = False,cache_position: Optional[torch.LongTensor] = None,# necessary, but kept here for BCposition_embeddings: Optional[Tuple[torch.Tensor,torch.Tensor]] = None,**kwargs: Unpack[FlashAttentionKwargs],) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:residual = hidden_states61 unmodified linessuper().__init__()# BC: "rope_type" was originally "type"if hasattr(config, "rope_scaling") and config.rope_scaling is not None:self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))else:self.rope_type = "default"self.max_seq_len_cached = config.max_position_embeddings2 unmodified linesself.config = configself.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)self.register_buffer("inv_freq", inv_freq, persistent=False)self.original_inv_freq = self.inv_freq1 unmodified line# power user: used with advanced RoPE types (e.g. dynamic rope)@dynamic_rope_updatedef forward(self, x, position_ids):inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)position_ids_expanded = position_ids[:, None, :].float()device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"with torch.autocast(device_type=device_type, enabled=False): # Force float32freqs = (inv_freq_expanded.float() @position_ids_expanded.float()).transpose(1, 2)emb = torch.cat((freqs, freqs), dim=-1)cos = emb.cos() * self.attention_scalingsin = emb.sin() * self.attention_scaling8 unmodified linesself.padding_idx = config.pad_token_idself.vocab_size = config.vocab_sizeself.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)self.layers = nn.ModuleList([SDARDecoderLayer(config, layer_idx)for layer_idx in range(config.num_hidden_layers)])self.norm = SDARRMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.rotary_emb = SDARRotaryEmbedding(config=config)self.gradient_checkpointing = False24 unmodified lines**flash_attn_kwargs: Unpack[FlashAttentionKwargs],) -> BaseModelOutputWithPast:output_attentions = output_attentions if output_attentions is not None else self.config.output_attentionsoutput_hidden_states = (output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states)use_cache = use_cache if use_cache is not None else self.config.use_cacheif (input_ids is None) ^ (inputs_embeds is not None):raise ValueError("You must specify exactly one of input_ids or inputs_embeds")if self.gradient_checkpointing and self.training and use_cache:logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.")use_cache = False# TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cacheif not isinstance(past_key_values, (type(None), Cache)):raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")if inputs_embeds is None:inputs_embeds = self.embed_tokens(input_ids)2 unmodified linespast_key_values = DynamicCache()if cache_position is None:past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0cache_position = torch.arange(past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device)if position_ids is None:position_ids = cache_position.unsqueeze(0)56 unmodified lines):if self.config._attn_implementation == "flash_attention_2":if attention_mask is not None and past_key_values is not None:is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]if is_padding_right:raise ValueError("You are attempting to perform batched generation with padding_side='right'"10 unmodified linesattention_mask = create_block_mask(# 2d bool tensor, shape: [2*seqlen, 2*seqlen]lambda b, h, q_idx, kv_idx: attention_mask[q_idx, kv_idx],B=None, H=None, Q_LEN=seq_len_q, KV_LEN=seq_len_kv,)else:# Here we pass in flex mask computed externally3 unmodified lines# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail# to infer the attention mask.past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0using_static_cache = isinstance(past_key_values, StaticCache)using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forwardif (self.config._attn_implementation == "sdpa"and not (using_static_cache or using_sliding_window_cache)and not output_attentions):if AttentionMaskConverter._ignore_causal_mask_sdpa(attention_mask,inputs_embeds=input_tensor,11 unmodified linestarget_length = past_key_values.get_max_cache_shape()# DynamicCache or no cacheelse:target_length = (attention_mask.shape[-1]if isinstance(attention_mask, torch.Tensor)else past_seen_tokens + sequence_length + 1)# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(7 unmodified linespast_key_values=past_key_values,)if (self.config._attn_implementation == "sdpa"and attention_mask is not Noneand attention_mask.device.type in ["cuda", "xpu", "npu"]and not output_attentions):# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.# Details: https://github.com/pytorch/pytorch/issues/110213causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)return causal_mask34 unmodified linescausal_mask = attention_maskelse:min_dtype = torch.finfo(dtype).mincausal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device)diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)text_config = config.get_text_config()if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:# if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also# the check is needed to verify is current checkpoint was trained with sliding window or notif not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (cache_position.reshape(-1, 1) -text_config.sliding_window)diagonal_attend_mask.bitwise_or_(sliding_attend_mask)causal_mask *= diagonal_attend_maskcausal_mask = causal_mask[None, None,:, :].expand(batch_size, 1, -1, -1)if attention_mask is not None:causal_mask = causal_mask.clone() # copy to contiguous memory for in-place editif attention_mask.shape[-1] > target_length:attention_mask = attention_mask[:, :target_length]mask_length = attention_mask.shape[-1]padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)padding_mask = padding_mask == 0causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(padding_mask, min_dtype)return causal_maskclass KwargsForCausalLM(FlashAttentionKwargs, LossKwargs):...@auto_docstring6 unmodified linessuper().__init__(config)self.model = SDARModel(config)self.vocab_size = config.vocab_sizeself.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)# Initialize weights and apply final processingself.post_init()51 unmodified lines"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."```"""output_attentions = output_attentions if output_attentions is not None else self.config.output_attentionsoutput_hidden_states = (output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states)# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)outputs: BaseModelOutputWithPast = self.model(11 unmodified lineshidden_states = outputs.last_hidden_state# Only compute necessary logits, and do not upcast them to float if we are not computing the lossslice_indices = slice(-logits_to_keep,None) if isinstance(logits_to_keep, int) else logits_to_keephidden_states = hidden_states[:, slice_indices, :].contiguous()fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.trainingif fuse_linear_and_cross_entropy:7 unmodified lines# FusedLinearCrossEntropyLoss will be implemented by monkey patch when training# We don't use it when inferencingloss_fct = nn.CrossEntropyLoss() # nn.CEloss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))return CausalLMOutputWithPast(loss=loss,8 unmodified lines"SDARForCausalLM","SDARModel","SDARPreTrainedModel",]22 unmodified lines23242526272829303132333435363738394041425 unmodified lines484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091107 unmodified lines1181191201211221231241251261271281291301311321331341351361375 unmodified lines14314414514614714814915015115215315415515615715815916016116216316416531 unmodified lines19719819920020120220315 unmodified lines2192202212222232242252267 unmodified lines2342352362372382392403 unmodified lines2442452462472482492502512522532542552562572582599 unmodified lines26927027127227327427527627727827928028128228328428528628728828929029118 unmodified lines3103113123133143153163173183193203213 unmodified lines3253263273283293303313323333343353363373382 unmodified lines3413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983999 unmodified lines4094104114124134144154164174186 unmodified lines42542642742842943043161 unmodified lines4934944954964974984992 unmodified lines5025035045055065075081 unmodified line5105115125135145155165175185195205218 unmodified lines53053153253353453553653724 unmodified lines5625635645655665675685695705715725735745755765775785795802 unmodified lines58358458558658758858959056 unmodified lines64764864965065165265310 unmodified lines6646656666676686696706716726733 unmodified lines67767867968068168268368468568668768811 unmodified lines7007017027037047057067 unmodified lines71471571671771871972072172272372434 unmodified lines7597607617627637647657667677687697707717727737747757767777787797807817827837847857867876 unmodified lines79479579679779879980051 unmodified lines85285385485585685785811 unmodified lines8708718728738748758767 unmodified lines8848858868878888898908 unmodified lines89990090190222 unmodified linesfrom typing import Callable, Optional, Tuple, Unionfrom nnll.init_gpu import deviceimport torchfrom torch import nnimport torch.nn.functional as Ffrom transformers.activations import ACT2FNfrom transformers.cache_utils import (Cache,DynamicCache,SlidingWindowCache,StaticCache,)from transformers.generation import GenerationMixinfrom transformers.integrations import use_kernel_forward_from_hubfrom transformers.modeling_attn_mask_utils import AttentionMaskConverterfrom transformers.modeling_layers import GradientCheckpointingLayerfrom transformers.modeling_outputs import (BaseModelOutputWithPast,5 unmodified linesfrom transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_updatefrom transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModelfrom transformers.processing_utils import Unpackfrom transformers.utils import (LossKwargs,auto_docstring,can_return_tuple,is_torch_flex_attn_available,logging,)from divisor.trado.configuration_sdar import SDARConfiglogger = logging.get_logger(__name__)# Make FlashAttentionKwargs available for all devices (used in type hints)try:from transformers.modeling_flash_attention_utils import FlashAttentionKwargsexcept ImportError:# Fallback if not availablefrom typing import TypedDictFlashAttentionKwargs = TypedDict("FlashAttentionKwargs", {})# Conditionally import flash attention components (CUDA only)flash_rms_norm = Noneflash_attn_func = Noneflash_attn_varlen_func = Noneindex_first_axis = Nonepad_input = Noneunpad_input = Noneif device.type == "cuda":try:from flash_attn.ops.triton.layer_norm import rms_norm_fn as flash_rms_normexcept (ImportError, ModuleNotFoundError):logger.warning("Flash attention RMS norm not available. Falling back to standard implementation.")flash_rms_norm = Nonetry:from flash_attn import flash_attn_func, flash_attn_varlen_funcfrom flash_attn.bert_padding import index_first_axis, pad_input, unpad_inputexcept (ImportError, ModuleNotFoundError):logger.warning("Flash attention not available. Falling back to standard attention.")flash_attn_func = Noneflash_attn_varlen_func = Noneif is_torch_flex_attn_available():try:from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attentionfrom transformers.integrations.flex_attention import make_flex_block_causal_maskexcept ImportError:passtry:from liger_kernel.ops.swiglu import LigerSiLUMulFunction # noqa: F401liger_kernel_is_available = Trueexcept ImportError:liger_kernel_is_available = False@use_kernel_forward_from_hub("RMSNorm")7 unmodified linesself.variance_epsilon = epsdef forward(self, hidden_states):# Use flash RMS norm if available (CUDA only), otherwise fall back to standard implementationif flash_rms_norm is not None and hidden_states.device.type == "cuda":try:return flash_rms_norm(hidden_states, weight=self.weight, bias=None, eps=self.variance_epsilon)except Exception as e:logger.warning(f"Flash RMS norm failed ({e}). Falling back to standard implementation.")# Fall through to standard implementation# Standard RMS norm implementation (fallback for MPS, CPU, or when flash_rms_norm fails)input_dtype = hidden_states.dtypehidden_states = hidden_states.to(torch.float32)variance = hidden_states.pow(2).mean(-1, keepdim=True)hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)return self.weight * hidden_states.to(input_dtype)def extra_repr(self):return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"5 unmodified linesself.config = configself.hidden_size = config.hidden_sizeself.intermediate_size = config.intermediate_sizeself.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)self.act_fn = ACT2FN[config.hidden_act]def forward(self, x):if liger_kernel_is_available:return self.down_proj(LigerSiLUMulFunction.apply(self.gate_proj(x), self.up_proj(x)))else:down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))return down_projdef rotate_half(x):"""Rotates half the hidden dims of the input."""x1 = x[..., : x.shape[-1] // 2]x2 = x[..., x.shape[-1] // 2 :]return torch.cat((-x2, x1), dim=-1)31 unmodified linesbatch, num_key_value_heads, slen, head_dim = hidden_states.shapeif n_rep == 1:return hidden_stateshidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)15 unmodified linescausal_mask = attention_mask[:, :, :, : key_states.shape[-2]]attn_weights = attn_weights + causal_maskattn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)attn_output = torch.matmul(attn_weights, value_states)attn_output = attn_output.transpose(1, 2).contiguous()7 unmodified linessuper().__init__()self.config = configself.layer_idx = layer_idxself.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)self.num_key_value_groups = config.num_attention_heads // config.num_key_value_headsself.scaling = self.head_dim**-0.5self.attention_dropout = config.attention_dropout3 unmodified linesself.num_attention_heads = config.num_attention_headsself.num_key_value_heads = config.num_key_value_headsself.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias)self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)# unlike olmo, only on the head dim!self.q_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)# thus post q_norm does not need reshapeself.k_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps)self.sliding_window = config.sliding_windowif not (self.config.use_sliding_window and getattr(self.config, "sliding_window", None) is not None and self.layer_idx >= self.config.max_window_layers):self.sliding_window = Nonedef forward(9 unmodified linesbsz, q_len = input_shapehidden_shape = (*input_shape, -1, self.head_dim)query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)cos, sin = position_embeddingsquery_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)if past_key_value is not None and kwargs.get("store_kv", False):# sin and cos are specific to RoPE models; cache_position needed for the static cachekey_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)elif past_key_value is not None and not kwargs.get("store_kv", False) and len(past_key_value) > self.layer_idx:# only retrive, do not store kvpast_key_states, past_value_states = past_key_value[self.layer_idx]key_states = torch.cat([past_key_states, key_states], dim=-2)value_states = torch.cat([past_value_states, value_states], dim=-2)"""attention_mask = attention_mask.bool() if attention_mask is not None else Noneif torch.all(attention_mask): # decodingquery_states = query_states.transpose(1, 2)18 unmodified linesenable_gqa=True)attn_output = attn_output.transpose(1, 2).contiguous()"""# print(query_states.shape, key_states.shape, value_states.shape)# --- After RoPE and KV-cache handling, expand KV to all heads ---key_states = repeat_kv(key_states, self.num_key_value_groups) # [B, H, K, D]value_states = repeat_kv(value_states, self.num_key_value_groups) # [B, H, K, D]# --- Convert a 0/1 or bool 4D mask into an *additive* mask, and align to [B, H, Q, K] ---3 unmodified linesam = attention_mask# Support either 2D [B, K] or 4D [B, 1/H, Q, K]if am.dim() == 2:am = am[:, None, None, :k_len] # -> [B,1,1,K]else:am = am[:, :, :, :k_len] # -> [B,1/H,Q,K]finfo_min = torch.finfo(query_states.dtype).min# 0/1 or bool -> float additive mask: 1->0, 0->-infif am.dtype == torch.bool:zero = torch.zeros((), dtype=query_states.dtype, device=am.device)neginf = torch.full((), finfo_min, dtype=query_states.dtype, device=am.device)am = torch.where(am, zero, neginf)else:2 unmodified linesam = torch.where(am > 0, torch.zeros_like(am), torch.full_like(am, finfo_min))# Expand to all heads# if am.shape[1] == 1 and self.num_attention_heads > 1:# am = am.expand(am.shape[0], self.num_attention_heads, am.shape[2], am.shape[3])# attn_mask = am.contiguous()attn_mask = ambsz, q_len = input_shapeif q_len == 1 and past_key_value is not None:# --- Decoding: try flash-attn if available (CUDA only), otherwise fall back to SDPA ---if flash_attn_func is not None and query_states.device.type == "cuda":try:q = query_states.transpose(1, 2) # [B,Q,H,D]k = key_states.transpose(1, 2)v = value_states.transpose(1, 2)attn_output = flash_attn_func(q,k,v,causal=True, # For decoding, explicitly set causal=Truesoftmax_scale=self.scaling,)attn_output = attn_output.transpose(1, 2).contiguous()except Exception as e:logger.warning(f"Flash attention failed during decoding ({e}). Falling back to SDPA.")# Fall through to SDPA implementation belowattn_output = F.scaled_dot_product_attention(query=query_states, # [B,H,Q,D]key=key_states, # [B,H,K,D]value=value_states, # [B,H,K,D]attn_mask=attn_mask, # float additive maskis_causal=False, # All constraints are already encoded in the maskscale=self.scaling,)attn_output = attn_output.transpose(1, 2).contiguous() # -> [B,Q,H,D]else:# Fallback to SDPA for MPS, CPU, or when flash_attn_func is not availableattn_output = F.scaled_dot_product_attention(query=query_states, # [B,H,Q,D]key=key_states, # [B,H,K,D]value=value_states, # [B,H,K,D]attn_mask=attn_mask, # float additive maskis_causal=False, # All constraints are already encoded in the maskscale=self.scaling,)attn_output = attn_output.transpose(1, 2).contiguous() # -> [B,Q,H,D]else:attn_output = F.scaled_dot_product_attention(query=query_states, # [B,H,Q,D]key=key_states, # [B,H,K,D]value=value_states, # [B,H,K,D]attn_mask=attn_mask, # float additive maskis_causal=False, # All constraints are already encoded in the maskscale=self.scaling,)attn_output = attn_output.transpose(1, 2).contiguous() # -> [B,Q,H,D]9 unmodified linesself.hidden_size = config.hidden_sizeself.self_attn = SDARAttention(config=config, layer_idx=layer_idx)self.mlp = SDARMLP(config)self.input_layernorm = SDARRMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.post_attention_layernorm = SDARRMSNorm(config.hidden_size, eps=config.rms_norm_eps)if config.sliding_window and config._attn_implementation != "flash_attention_2": # diff with Llama is this warninglogger.warning_once(f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; unexpected results may be encountered.")def forward(self,6 unmodified linesstore_kv: Optional[bool] = False,cache_position: Optional[torch.LongTensor] = None,# necessary, but kept here for BCposition_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,**kwargs: Unpack[FlashAttentionKwargs],) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:residual = hidden_states61 unmodified linessuper().__init__()# BC: "rope_type" was originally "type"if hasattr(config, "rope_scaling") and config.rope_scaling is not None:self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))else:self.rope_type = "default"self.max_seq_len_cached = config.max_position_embeddings2 unmodified linesself.config = configself.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)self.register_buffer("inv_freq", inv_freq, persistent=False)self.original_inv_freq = self.inv_freq1 unmodified line# power user: used with advanced RoPE types (e.g. dynamic rope)@dynamic_rope_updatedef forward(self, x, position_ids):inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)position_ids_expanded = position_ids[:, None, :].float()device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"with torch.autocast(device_type=device_type, enabled=False): # Force float32freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)emb = torch.cat((freqs, freqs), dim=-1)cos = emb.cos() * self.attention_scalingsin = emb.sin() * self.attention_scaling8 unmodified linesself.padding_idx = config.pad_token_idself.vocab_size = config.vocab_sizeself.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)self.layers = nn.ModuleList([SDARDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])self.norm = SDARRMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.rotary_emb = SDARRotaryEmbedding(config=config)self.gradient_checkpointing = False24 unmodified lines**flash_attn_kwargs: Unpack[FlashAttentionKwargs],) -> BaseModelOutputWithPast:output_attentions = output_attentions if output_attentions is not None else self.config.output_attentionsoutput_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_statesuse_cache = use_cache if use_cache is not None else self.config.use_cacheif (input_ids is None) ^ (inputs_embeds is not None):raise ValueError("You must specify exactly one of input_ids or inputs_embeds")if self.gradient_checkpointing and self.training and use_cache:logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.")use_cache = False# TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cacheif not isinstance(past_key_values, (type(None), Cache)):raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")if inputs_embeds is None:inputs_embeds = self.embed_tokens(input_ids)2 unmodified linespast_key_values = DynamicCache()if cache_position is None:past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0cache_position = torch.arange(past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device)if position_ids is None:position_ids = cache_position.unsqueeze(0)56 unmodified lines):if self.config._attn_implementation == "flash_attention_2":if attention_mask is not None and past_key_values is not None:is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]if is_padding_right:raise ValueError("You are attempting to perform batched generation with padding_side='right'"10 unmodified linesattention_mask = create_block_mask(# 2d bool tensor, shape: [2*seqlen, 2*seqlen]lambda b, h, q_idx, kv_idx: attention_mask[q_idx, kv_idx],B=None,H=None,Q_LEN=seq_len_q,KV_LEN=seq_len_kv,)else:# Here we pass in flex mask computed externally3 unmodified lines# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail# to infer the attention mask.past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0using_static_cache = isinstance(past_key_values, StaticCache)using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forwardif self.config._attn_implementation == "sdpa" and not (using_static_cache or using_sliding_window_cache) and not output_attentions:if AttentionMaskConverter._ignore_causal_mask_sdpa(attention_mask,inputs_embeds=input_tensor,11 unmodified linestarget_length = past_key_values.get_max_cache_shape()# DynamicCache or no cacheelse:target_length = attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else past_seen_tokens + sequence_length + 1# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(7 unmodified linespast_key_values=past_key_values,)if self.config._attn_implementation == "sdpa" and attention_mask is not None and attention_mask.device.type in ["cuda", "xpu", "npu", "mps"] and not output_attentions:# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.# Details: https://github.com/pytorch/pytorch/issues/110213causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)return causal_mask34 unmodified linescausal_mask = attention_maskelse:min_dtype = torch.finfo(dtype).mincausal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device)diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)text_config = config.get_text_config()if getattr(text_config, "use_sliding_window", True) and text_config.sliding_window is not None:# if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also# the check is needed to verify is current checkpoint was trained with sliding window or notif not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= (cache_position.reshape(-1, 1) - text_config.sliding_window)diagonal_attend_mask.bitwise_or_(sliding_attend_mask)causal_mask *= diagonal_attend_maskcausal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)if attention_mask is not None:causal_mask = causal_mask.clone() # copy to contiguous memory for in-place editif attention_mask.shape[-1] > target_length:attention_mask = attention_mask[:, :target_length]mask_length = attention_mask.shape[-1]padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)padding_mask = padding_mask == 0causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(padding_mask, min_dtype)return causal_maskclass KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...@auto_docstring6 unmodified linessuper().__init__(config)self.model = SDARModel(config)self.vocab_size = config.vocab_sizeself.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)# Initialize weights and apply final processingself.post_init()51 unmodified lines"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."```"""output_attentions = output_attentions if output_attentions is not None else self.config.output_attentionsoutput_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)outputs: BaseModelOutputWithPast = self.model(11 unmodified lineshidden_states = outputs.last_hidden_state# Only compute necessary logits, and do not upcast them to float if we are not computing the lossslice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keephidden_states = hidden_states[:, slice_indices, :].contiguous()fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.trainingif fuse_linear_and_cross_entropy:7 unmodified lines# FusedLinearCrossEntropyLoss will be implemented by monkey patch when training# We don't use it when inferencingloss_fct = nn.CrossEntropyLoss() # nn.CEloss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))return CausalLMOutputWithPast(loss=loss,8 unmodified lines"SDARForCausalLM","SDARModel","SDARPreTrainedModel",]
modeling_sdar.py+179-199