~test conditional workarounds (#1)
Browse files- ~test conditional workarounds (313919b82c1de187baaba2e5222c326e7b2d4400)
22 unmodified lines23242526272828293030313233343536373839344041425 unmodified lines48495046475152535455565758495960515253545556616263645960656662636768697071727374757677787980818283848586878889909192939495966667979899100101102103104701051061071081091107 unmodified lines1181191208485861211221231241251261271281291301311329091133134931351361375 unmodified lines14314414510510610710810911014614714814915015115215315411711815515615715815916016112516216316416531 unmodified lines19719819916316420020120220315 unmodified lines2192202211861871881892222232242252267 unmodified lines2342352362032042372382392403 unmodified lines2442452462142152162172182192202212222232242252472482492502512522532542552312322332342352562572582599 unmodified lines26927027125125225325425525625725827227327427527626126227727827928026626728128228328427127227327428528628727628828929029118 unmodified lines3103113123013133143033153163173063183193203213 unmodified lines3253263273163283293183303313323333343233353363373382 unmodified lines3413423433323443453463353473483373493503513523423433443453463473483493503513533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913543553563573583923933943953963973983999 unmodified lines4094104113743753763773783793803813823833844124134144154164174186 unmodified lines42542642739739842842943043161 unmodified lines4934944954664674964974984992 unmodified lines5025035044764775055065075081 unmodified line5105115124854865135145154894905165174924935185195205218 unmodified lines53053153250850951051151251353353453553653724 unmodified lines5625635645445455655465665675685505515695705715545555565725735745755765615625775785795802 unmodified lines58358458557157257357457558658758858959056 unmodified lines64764864963863965065165265310 unmodified lines6646656666566676686696706716726733 unmodified lines67767867966666768068166967068268368467367467567667768568668768811 unmodified lines7007017026956966976986997037047057067 unmodified lines71471571671371471571671771871771871972072272372172272372434 unmodified lines7597607617647657667677687697627637647657667677687757767777787697707717817827727737747757767777887897907787797927937947807817827837987997847857867876 unmodified lines79479579681281379779879980051 unmodified lines85285385487187285587385685785811 unmodified lines8708718728918928738748758767 unmodified lines8848858869069078878888898908 unmodified lines89990090192290222 unmodified lines
from typing import Callable, Optional, Tuple, Union
from nnll.init_gpu import deviceimport torchfrom torch import nn
import torch.nn.functional as Ffrom transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCachefrom 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_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 transformers.utils import ( LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging,)
from flash_attn.ops.triton.layer_norm import rms_norm_fn as flash_rms_normfrom divisor.trado.configuration_sdar import SDARConfig
import torch.nn.functional as Ftry: from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_inputexcept: passlogger = logging.get_logger(__name__)
# Make FlashAttentionKwargs available for all devices (used in type hints)try: from liger_kernel.ops.swiglu import LigerSiLUMulFunction # noqa: F401 liger_kernel_is_available = True from transformers.modeling_flash_attention_utils import FlashAttentionKwargsexcept ImportError: liger_kernel_is_available = False
# Fallback if not available from typing import TypedDict
FlashAttentionKwargs = 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 = None
if device.type == "cuda": try: from flash_attn.ops.triton.layer_norm import rms_norm_fn as flash_rms_norm except (ImportError, ModuleNotFoundError): logger.warning("Flash attention RMS norm not available. Falling back to standard implementation.") flash_rms_norm = None
try: from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input except (ImportError, ModuleNotFoundError): logger.warning("Flash attention not available. Falling back to standard attention.") flash_attn_func = None flash_attn_varlen_func = None
if is_torch_flex_attn_available(): try: from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attention from transformers.integrations.flex_attention import make_flex_block_causal_mask from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attention from transformers.integrations.flex_attention import make_flex_block_causal_mask except ImportError: pass
try: from liger_kernel.ops.swiglu import LigerSiLUMulFunction # noqa: F401
logger = logging.get_logger(__name__) liger_kernel_is_available = Trueexcept ImportError: liger_kernel_is_available = False
@use_kernel_forward_from_hub("RMSNorm")7 unmodified lines self.variance_epsilon = eps
def forward(self, hidden_states): return flash_rms_norm( hidden_states, weight=self.weight, bias=None, eps=self.variance_epsilon) ''' # Use flash RMS norm if available (CUDA only), otherwise fall back to standard implementation if 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.dtype hidden_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) 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 lines self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.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.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)) down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return down_proj
def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2:] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
31 unmodified lines batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand( batch, num_key_value_heads, n_rep, slen, head_dim) hidden_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 lines causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask
attn_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_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 lines super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr( config, "head_dim", config.hidden_size // config.num_attention_heads) self.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_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout3 unmodified lines self.num_attention_heads = config.num_attention_heads self.num_key_value_heads = config.num_key_value_heads
self.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 ) self.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 reshape self.k_norm = SDARRMSNorm(self.head_dim, eps=config.rms_norm_eps) self.sliding_window = config.sliding_window if 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 ): if 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 = None
def forward(9 unmodified lines bsz, q_len = input_shape hidden_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) 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_embeddings query_states, key_states = apply_rotary_pos_emb( query_states, key_states, cos, sin) query_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 cache key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx) key_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 kv past_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) 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 None if torch.all(attention_mask): # decoding query_states = query_states.transpose(1, 2)18 unmodified lines enable_gqa=True ) attn_output = attn_output.transpose(1, 2).contiguous() ''' """
#print(query_states.shape, key_states.shape, value_states.shape) # 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] 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 lines am = 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] am = am[:, None, None, :k_len] # -> [B,1,1,K] else: am = am[:, :, :, :k_len] # -> [B,1/H,Q,K] 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->-inf if am.dtype == torch.bool: zero = torch.zeros((), dtype=query_states.dtype, device=am.device) 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 lines am = 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: # 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 = am.contiguous() attn_mask = am
bsz, q_len = input_shape
if 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=True softmax_scale=self.scaling ) attn_output = attn_output.transpose(1, 2).contiguous() # --- 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=True softmax_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 below 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 mask is_causal=False, # All constraints are already encoded in the mask scale=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 available 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 mask is_causal=False, # All constraints are already encoded in the mask scale=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 mask is_causal=False, # All constraints are already encoded in the mask 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 mask is_causal=False, # All constraints are already encoded in the mask scale=self.scaling, ) attn_output = attn_output.transpose(1, 2).contiguous() # -> [B,Q,H,D]9 unmodified lines self.hidden_size = config.hidden_size self.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 warning logger.warning_once( f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; " "unexpected results may be encountered." ) 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 warning logger.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 lines store_kv: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, # necessary, but kept here for BC position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: residual = hidden_states61 unmodified lines super().__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")) 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 lines self.config = config self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = self.rope_init_fn( self.config, device) 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_freq
1 unmodified line # power user: used with advanced RoPE types (e.g. dynamic rope) @dynamic_rope_update def forward(self, x, position_ids): inv_freq_expanded = self.inv_freq[None, :, None].float().expand( position_ids.shape[0], -1, 1).to(x.device) 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" 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 float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling8 unmodified lines self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size
self.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.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_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states output_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_cache
if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError( "You must specify exactly one of input_ids or inputs_embeds") 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`." ) 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 cache if not isinstance(past_key_values, (type(None), Cache)): raise ValueError( "The `past_key_values` should be either a `Cache` object or `None`.") 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 lines past_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 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_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] 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 lines attention_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, 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 0 past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 using_static_cache = isinstance(past_key_values, StaticCache) using_sliding_window_cache = isinstance( past_key_values, SlidingWindowCache) using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward if ( self.config._attn_implementation == "sdpa" and not (using_static_cache or using_sliding_window_cache) and not output_attentions ): if 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 lines target_length = past_key_values.get_max_cache_shape() # DynamicCache or no cache else: target_length = ( attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else past_seen_tokens + sequence_length + 1 ) 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 lines past_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"] and not output_attentions ): 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/110213 causal_mask = AttentionMaskConverter._unmask_unattended( causal_mask, min_dtype) causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
return causal_mask
34 unmodified lines causal_mask = attention_mask else: min_dtype = torch.finfo(dtype).min causal_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 ) causal_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 not if 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 ) 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_mask causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) causal_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 edit if 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 = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device) padding_mask = padding_mask == 0 causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( padding_mask, min_dtype ) causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(padding_mask, min_dtype) return causal_mask
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
@auto_docstring6 unmodified lines super().__init__(config) self.model = SDARModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear( config.hidden_size, config.vocab_size, bias=False) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing self.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_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states output_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 lines
hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep hidden_states = hidden_states[:, slice_indices, :].contiguous() fuse_linear_and_cross_entropy = self.config.fuse_cross_entropy and self.training if fuse_linear_and_cross_entropy:7 unmodified lines # FusedLinearCrossEntropyLoss will be implemented by monkey patch when training # We don't use it when inferencing loss_fct = nn.CrossEntropyLoss() # nn.CE loss = loss_fct( logits.view(-1, self.config.vocab_size), labels.view(-1)) loss = 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