Aluode/PerceptionLabPortable
0
1# ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ2# This file was automatically generated from src/transformers/models/olmo2/modular_olmo2.py.3# Do NOT edit this file manually as any edits will be overwritten by the generation of4# the file from the modular. If any change should be done, please apply the change to the5# modular_olmo2.py file directly. One of our CI enforces this.6# ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ๐จ7from typing import Callable, Optional, Union8 9import torch10import torch.nn as nn11 12from transformers.utils.generic import TransformersKwargs13 14from ...activations import ACT2FN15from ...cache_utils import Cache, DynamicCache16from ...generation import GenerationMixin17from ...integrations import use_kernel_forward_from_hub18from ...masking_utils import create_causal_mask19from ...modeling_layers import GradientCheckpointingLayer20from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast21from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update22from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel23from ...processing_utils import Unpack24from ...utils import auto_docstring, can_return_tuple25from ...utils.deprecation import deprecate_kwarg26from ...utils.generic import check_model_inputs27from .configuration_olmo2 import Olmo2Config28 29 30@use_kernel_forward_from_hub("RMSNorm")31class Olmo2RMSNorm(nn.Module):32 def __init__(self, hidden_size, eps=1e-6):33 """34 Olmo2RMSNorm is equivalent to T5LayerNorm35 """36 super().__init__()37 self.weight = nn.Parameter(torch.ones(hidden_size))38 self.variance_epsilon = eps39 40 def forward(self, hidden_states):41 input_dtype = hidden_states.dtype42 hidden_states = hidden_states.to(torch.float32)43 variance = hidden_states.pow(2).mean(-1, keepdim=True)44 hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)45 return (self.weight * hidden_states).to(input_dtype)46 47 def extra_repr(self):48 return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"49 50 51def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:52 """53 This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,54 num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)55 """56 batch, num_key_value_heads, slen, head_dim = hidden_states.shape57 if n_rep == 1:58 return hidden_states59 hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)60 return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)61 62 63def eager_attention_forward(64 module: nn.Module,65 query: torch.Tensor,66 key: torch.Tensor,67 value: torch.Tensor,68 attention_mask: Optional[torch.Tensor],69 scaling: float,70 dropout: float = 0.0,71 **kwargs: Unpack[TransformersKwargs],72):73 key_states = repeat_kv(key, module.num_key_value_groups)74 value_states = repeat_kv(value, module.num_key_value_groups)75 76 attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling77 if attention_mask is not None:78 causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]79 attn_weights = attn_weights + causal_mask80 81 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)82 attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)83 attn_output = torch.matmul(attn_weights, value_states)84 attn_output = attn_output.transpose(1, 2).contiguous()85 86 return attn_output, attn_weights87 88 89def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):90 """Applies Rotary Position Embedding to the query and key tensors.91 92 Args:93 q (`torch.Tensor`): The query tensor.94 k (`torch.Tensor`): The key tensor.95 cos (`torch.Tensor`): The cosine part of the rotary embedding.96 sin (`torch.Tensor`): The sine part of the rotary embedding.97 position_ids (`torch.Tensor`, *optional*):98 Deprecated and unused.99 unsqueeze_dim (`int`, *optional*, defaults to 1):100 The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and101 sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note102 that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and103 k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes104 cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have105 the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.106 Returns:107 `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.108 """109 q_type, k_type = q.dtype, k.dtype110 cos = cos.unsqueeze(unsqueeze_dim)111 sin = sin.unsqueeze(unsqueeze_dim)112 q_embed = (q * cos) + (rotate_half(q) * sin)113 k_embed = (k * cos) + (rotate_half(k) * sin)114 return q_embed.to(q_type), k_embed.to(k_type)115 116 117def rotate_half(x):118 """Rotates half the hidden dims of the input."""119 x1 = x[..., : x.shape[-1] // 2]120 x2 = x[..., x.shape[-1] // 2 :]121 return torch.cat((-x2, x1), dim=-1)122 123 124class Olmo2Attention(nn.Module):125 """Multi-headed attention from 'Attention Is All You Need' paper"""126 127 def __init__(self, config: Olmo2Config, layer_idx: Optional[int] = None):128 super().__init__()129 self.config = config130 self.layer_idx = layer_idx131 self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)132 self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads133 self.scaling = self.head_dim**-0.5134 self.attention_dropout = config.attention_dropout135 self.is_causal = True136 137 self.q_proj = nn.Linear(138 config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias139 )140 self.k_proj = nn.Linear(141 config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias142 )143 self.v_proj = nn.Linear(144 config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias145 )146 self.o_proj = nn.Linear(147 config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias148 )149 self.q_norm = Olmo2RMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps)150 self.k_norm = Olmo2RMSNorm(config.num_key_value_heads * self.head_dim, config.rms_norm_eps)151 152 @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")153 def forward(154 self,155 hidden_states: torch.Tensor,156 position_embeddings: tuple[torch.Tensor, torch.Tensor],157 attention_mask: Optional[torch.Tensor],158 past_key_values: Optional[Cache] = None,159 cache_position: Optional[torch.LongTensor] = None,160 **kwargs: Unpack[TransformersKwargs],161 ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:162 input_shape = hidden_states.shape[:-1]163 hidden_shape = (*input_shape, -1, self.head_dim)164 165 query_states = self.q_norm(self.q_proj(hidden_states))166 key_states = self.k_norm(self.k_proj(hidden_states))167 value_states = self.v_proj(hidden_states)168 169 query_states = query_states.view(hidden_shape).transpose(1, 2)170 key_states = key_states.view(hidden_shape).transpose(1, 2)171 value_states = value_states.view(hidden_shape).transpose(1, 2)172 173 cos, sin = position_embeddings174 query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)175 176 if past_key_values is not None:177 # sin and cos are specific to RoPE models; cache_position needed for the static cache178 cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}179 key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)180 181 attention_interface: Callable = eager_attention_forward182 if self.config._attn_implementation != "eager":183 attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]184 185 attn_output, attn_weights = attention_interface(186 self,187 query_states,188 key_states,189 value_states,190 attention_mask,191 dropout=0.0 if not self.training else self.attention_dropout,192 scaling=self.scaling,193 **kwargs,194 )195 196 attn_output = attn_output.reshape(*input_shape, -1).contiguous()197 attn_output = self.o_proj(attn_output)198 return attn_output, attn_weights199 200 201class Olmo2MLP(nn.Module):202 def __init__(self, config):203 super().__init__()204 self.config = config205 self.hidden_size = config.hidden_size206 self.intermediate_size = config.intermediate_size207 self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)208 self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)209 self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)210 self.act_fn = ACT2FN[config.hidden_act]211 212 def forward(self, x):213 down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))214 return down_proj215 216 217class Olmo2DecoderLayer(GradientCheckpointingLayer):218 def __init__(self, config: Olmo2Config, layer_idx: int):219 super().__init__()220 self.hidden_size = config.hidden_size221 self.self_attn = Olmo2Attention(config=config, layer_idx=layer_idx)222 223 self.mlp = Olmo2MLP(config)224 self.post_attention_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)225 self.post_feedforward_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)226 227 @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")228 def forward(229 self,230 hidden_states: torch.Tensor,231 attention_mask: Optional[torch.Tensor] = None,232 position_ids: Optional[torch.LongTensor] = None,233 past_key_values: Optional[Cache] = None,234 use_cache: Optional[bool] = False,235 cache_position: Optional[torch.LongTensor] = None,236 position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC237 **kwargs: Unpack[TransformersKwargs],238 ) -> torch.Tensor:239 residual = hidden_states240 hidden_states, _ = self.self_attn(241 hidden_states=hidden_states,242 attention_mask=attention_mask,243 position_ids=position_ids,244 past_key_values=past_key_values,245 use_cache=use_cache,246 cache_position=cache_position,247 position_embeddings=position_embeddings,248 **kwargs,249 )250 hidden_states = self.post_attention_layernorm(hidden_states)251 hidden_states = residual + hidden_states252 253 # Fully Connected254 residual = hidden_states255 hidden_states = self.mlp(hidden_states)256 hidden_states = self.post_feedforward_layernorm(hidden_states)257 hidden_states = residual + hidden_states258 return hidden_states259 260 261class Olmo2RotaryEmbedding(nn.Module):262 inv_freq: torch.Tensor # fix linting for `register_buffer`263 264 def __init__(self, config: Olmo2Config, device=None):265 super().__init__()266 # BC: "rope_type" was originally "type"267 if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):268 self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))269 else:270 self.rope_type = "default"271 self.max_seq_len_cached = config.max_position_embeddings272 self.original_max_seq_len = config.max_position_embeddings273 274 self.config = config275 self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]276 277 inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)278 self.register_buffer("inv_freq", inv_freq, persistent=False)279 self.original_inv_freq = self.inv_freq280 281 @torch.no_grad()282 @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)283 def forward(self, x, position_ids):284 inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)285 position_ids_expanded = position_ids[:, None, :].float()286 287 device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"288 with torch.autocast(device_type=device_type, enabled=False): # Force float32289 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)290 emb = torch.cat((freqs, freqs), dim=-1)291 cos = emb.cos() * self.attention_scaling292 sin = emb.sin() * self.attention_scaling293 return cos, sin294 295 296@auto_docstring297class Olmo2PreTrainedModel(PreTrainedModel):298 config: Olmo2Config299 base_model_prefix = "model"300 supports_gradient_checkpointing = True301 _no_split_modules = ["Olmo2DecoderLayer"]302 _skip_keys_device_placement = ["past_key_values"]303 _supports_flash_attn = True304 _supports_sdpa = True305 _supports_flex_attn = True306 307 _can_compile_fullgraph = True308 _supports_attention_backend = True309 _can_record_outputs = {310 "hidden_states": Olmo2DecoderLayer,311 "attentions": Olmo2Attention,312 }313 314 315@auto_docstring316class Olmo2Model(Olmo2PreTrainedModel):317 def __init__(self, config: Olmo2Config):318 super().__init__(config)319 self.padding_idx = config.pad_token_id320 self.vocab_size = config.vocab_size321 322 self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)323 self.layers = nn.ModuleList(324 [Olmo2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]325 )326 self.norm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)327 self.rotary_emb = Olmo2RotaryEmbedding(config=config)328 self.gradient_checkpointing = False329 330 # Initialize weights and apply final processing331 self.post_init()332 333 @check_model_inputs()334 @auto_docstring335 def forward(336 self,337 input_ids: Optional[torch.LongTensor] = None,338 attention_mask: Optional[torch.Tensor] = None,339 position_ids: Optional[torch.LongTensor] = None,340 past_key_values: Optional[Cache] = None,341 inputs_embeds: Optional[torch.FloatTensor] = None,342 cache_position: Optional[torch.LongTensor] = None,343 use_cache: Optional[bool] = None,344 **kwargs: Unpack[TransformersKwargs],345 ) -> BaseModelOutputWithPast:346 if (input_ids is None) ^ (inputs_embeds is not None):347 raise ValueError("You must specify exactly one of input_ids or inputs_embeds")348 349 if inputs_embeds is None:350 inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)351 352 if use_cache and past_key_values is None:353 past_key_values = DynamicCache(config=self.config)354 355 if cache_position is None:356 past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0357 cache_position: torch.Tensor = torch.arange(358 past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device359 )360 361 if position_ids is None:362 position_ids = cache_position.unsqueeze(0)363 364 causal_mask = create_causal_mask(365 config=self.config,366 input_embeds=inputs_embeds,367 attention_mask=attention_mask,368 cache_position=cache_position,369 past_key_values=past_key_values,370 position_ids=position_ids,371 )372 373 hidden_states = inputs_embeds374 position_embeddings = self.rotary_emb(hidden_states, position_ids)375 376 for decoder_layer in self.layers[: self.config.num_hidden_layers]:377 hidden_states = decoder_layer(378 hidden_states,379 attention_mask=causal_mask,380 position_ids=position_ids,381 past_key_values=past_key_values,382 cache_position=cache_position,383 position_embeddings=position_embeddings,384 **kwargs,385 )386 387 hidden_states = self.norm(hidden_states)388 return BaseModelOutputWithPast(389 last_hidden_state=hidden_states,390 past_key_values=past_key_values,391 )392 393 394@auto_docstring395class Olmo2ForCausalLM(Olmo2PreTrainedModel, GenerationMixin):396 _tied_weights_keys = ["lm_head.weight"]397 _tp_plan = {"lm_head": "colwise_rep"}398 _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}399 400 def __init__(self, config):401 super().__init__(config)402 self.model = Olmo2Model(config)403 self.vocab_size = config.vocab_size404 self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)405 406 # Initialize weights and apply final processing407 self.post_init()408 409 @can_return_tuple410 @auto_docstring411 def forward(412 self,413 input_ids: Optional[torch.LongTensor] = None,414 attention_mask: Optional[torch.Tensor] = None,415 position_ids: Optional[torch.LongTensor] = None,416 past_key_values: Optional[Cache] = None,417 inputs_embeds: Optional[torch.FloatTensor] = None,418 labels: Optional[torch.LongTensor] = None,419 use_cache: Optional[bool] = None,420 cache_position: Optional[torch.LongTensor] = None,421 logits_to_keep: Union[int, torch.Tensor] = 0,422 **kwargs: Unpack[TransformersKwargs],423 ) -> CausalLMOutputWithPast:424 r"""425 Example:426 427 ```python428 >>> from transformers import AutoTokenizer, Olmo2ForCausalLM429 430 >>> model = Olmo2ForCausalLM.from_pretrained("meta-olmo2/Olmo2-2-7b-hf")431 >>> tokenizer = AutoTokenizer.from_pretrained("meta-olmo2/Olmo2-2-7b-hf")432 433 >>> prompt = "Hey, are you conscious? Can you talk to me?"434 >>> inputs = tokenizer(prompt, return_tensors="pt")435 436 >>> # Generate437 >>> generate_ids = model.generate(inputs.input_ids, max_length=30)438 >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]439 "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."440 ```"""441 outputs: BaseModelOutputWithPast = self.model(442 input_ids=input_ids,443 attention_mask=attention_mask,444 position_ids=position_ids,445 past_key_values=past_key_values,446 inputs_embeds=inputs_embeds,447 use_cache=use_cache,448 cache_position=cache_position,449 **kwargs,450 )451 452 hidden_states = outputs.last_hidden_state453 # Only compute necessary logits, and do not upcast them to float if we are not computing the loss454 slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep455 logits = self.lm_head(hidden_states[:, slice_indices, :])456 457 loss = None458 if labels is not None:459 loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)460 461 return CausalLMOutputWithPast(462 loss=loss,463 logits=logits,464 past_key_values=outputs.past_key_values,465 hidden_states=outputs.hidden_states,466 attentions=outputs.attentions,467 )468 469 470__all__ = ["Olmo2ForCausalLM", "Olmo2Model", "Olmo2PreTrainedModel"]471 