CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
modeling_olmo3.py510 linesDownload Raw Back to olmo3
1#                ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ2#           This file was automatically generated from src/transformers/models/olmo3/modular_olmo3.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_olmo3.py file directly. One of our CI enforces this.6#                ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ7# coding=utf-88# Copyright 2025 the HuggingFace Team. All rights reserved.9#10# Licensed under the Apache License, Version 2.0 (the "License");11# you may not use this file except in compliance with the License.12# You may obtain a copy of the License at13#14#     http://www.apache.org/licenses/LICENSE-2.015#16# Unless required by applicable law or agreed to in writing, software17# distributed under the License is distributed on an "AS IS" BASIS,18# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.19# See the License for the specific language governing permissions and20# limitations under the License.21 22from typing import Callable, Optional, Union23 24import torch25import torch.nn as nn26 27from transformers.utils.generic import TransformersKwargs28 29from ...activations import ACT2FN30from ...cache_utils import Cache, DynamicCache31from ...generation import GenerationMixin32from ...integrations import use_kernel_forward_from_hub33from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask34from ...modeling_layers import GradientCheckpointingLayer35from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast36from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update37from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel38from ...processing_utils import Unpack39from ...utils import auto_docstring, can_return_tuple40from ...utils.deprecation import deprecate_kwarg41from ...utils.generic import check_model_inputs42from .configuration_olmo3 import Olmo3Config43 44 45@use_kernel_forward_from_hub("RMSNorm")46class Olmo3RMSNorm(nn.Module):47    def __init__(self, hidden_size, eps=1e-6):48        """49        Olmo3RMSNorm is equivalent to T5LayerNorm50        """51        super().__init__()52        self.weight = nn.Parameter(torch.ones(hidden_size))53        self.variance_epsilon = eps54 55    def forward(self, hidden_states):56        input_dtype = hidden_states.dtype57        hidden_states = hidden_states.to(torch.float32)58        variance = hidden_states.pow(2).mean(-1, keepdim=True)59        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)60        return (self.weight * hidden_states).to(input_dtype)61 62    def extra_repr(self):63        return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"64 65 66def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:67    """68    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,69    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)70    """71    batch, num_key_value_heads, slen, head_dim = hidden_states.shape72    if n_rep == 1:73        return hidden_states74    hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)75    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)76 77 78def eager_attention_forward(79    module: nn.Module,80    query: torch.Tensor,81    key: torch.Tensor,82    value: torch.Tensor,83    attention_mask: Optional[torch.Tensor],84    scaling: float,85    dropout: float = 0.0,86    **kwargs: Unpack[TransformersKwargs],87):88    key_states = repeat_kv(key, module.num_key_value_groups)89    value_states = repeat_kv(value, module.num_key_value_groups)90 91    attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling92    if attention_mask is not None:93        causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]94        attn_weights = attn_weights + causal_mask95 96    attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)97    attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)98    attn_output = torch.matmul(attn_weights, value_states)99    attn_output = attn_output.transpose(1, 2).contiguous()100 101    return attn_output, attn_weights102 103 104def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):105    """Applies Rotary Position Embedding to the query and key tensors.106 107    Args:108        q (`torch.Tensor`): The query tensor.109        k (`torch.Tensor`): The key tensor.110        cos (`torch.Tensor`): The cosine part of the rotary embedding.111        sin (`torch.Tensor`): The sine part of the rotary embedding.112        position_ids (`torch.Tensor`, *optional*):113            Deprecated and unused.114        unsqueeze_dim (`int`, *optional*, defaults to 1):115            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and116            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note117            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and118            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes119            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have120            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.121    Returns:122        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.123    """124    q_type, k_type = q.dtype, k.dtype125    cos = cos.unsqueeze(unsqueeze_dim)126    sin = sin.unsqueeze(unsqueeze_dim)127    q_embed = (q * cos) + (rotate_half(q) * sin)128    k_embed = (k * cos) + (rotate_half(k) * sin)129    return q_embed.to(q_type), k_embed.to(k_type)130 131 132def rotate_half(x):133    """Rotates half the hidden dims of the input."""134    x1 = x[..., : x.shape[-1] // 2]135    x2 = x[..., x.shape[-1] // 2 :]136    return torch.cat((-x2, x1), dim=-1)137 138 139class Olmo3Attention(nn.Module):140    """Multi-headed attention from 'Attention Is All You Need' paper"""141 142    def __init__(self, config: Olmo3Config, layer_idx: int):143        super().__init__()144        self.config = config145        self.layer_idx = layer_idx146        self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)147        self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads148        self.scaling = self.head_dim**-0.5149        self.attention_dropout = config.attention_dropout150        self.is_causal = True151 152        self.q_proj = nn.Linear(153            config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias154        )155        self.k_proj = nn.Linear(156            config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias157        )158        self.v_proj = nn.Linear(159            config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias160        )161        self.o_proj = nn.Linear(162            config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias163        )164        self.q_norm = Olmo3RMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps)165        self.k_norm = Olmo3RMSNorm(config.num_key_value_heads * self.head_dim, config.rms_norm_eps)166        assert config.layer_types is not None167        self.attention_type = config.layer_types[layer_idx]168        self.sliding_window = config.sliding_window if self.attention_type == "sliding_attention" else None169 170    @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")171    def forward(172        self,173        hidden_states: torch.Tensor,174        position_embeddings: tuple[torch.Tensor, torch.Tensor],175        attention_mask: Optional[torch.Tensor],176        past_key_values: Optional[Cache] = None,177        cache_position: Optional[torch.LongTensor] = None,178        **kwargs: Unpack[TransformersKwargs],179    ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:180        input_shape = hidden_states.shape[:-1]181        hidden_shape = (*input_shape, -1, self.head_dim)182 183        query_states = self.q_norm(self.q_proj(hidden_states))184        key_states = self.k_norm(self.k_proj(hidden_states))185        value_states = self.v_proj(hidden_states)186 187        query_states = query_states.view(hidden_shape).transpose(1, 2)188        key_states = key_states.view(hidden_shape).transpose(1, 2)189        value_states = value_states.view(hidden_shape).transpose(1, 2)190 191        cos, sin = position_embeddings192        query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)193 194        if past_key_values is not None:195            # sin and cos are specific to RoPE models; cache_position needed for the static cache196            cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}197            key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)198 199        attention_interface: Callable = eager_attention_forward200        if self.config._attn_implementation != "eager":201            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]202 203        attn_output, attn_weights = attention_interface(204            self,205            query_states,206            key_states,207            value_states,208            attention_mask,209            dropout=0.0 if not self.training else self.attention_dropout,210            scaling=self.scaling,211            sliding_window=self.sliding_window,212            **kwargs,213        )214 215        attn_output = attn_output.reshape(*input_shape, -1).contiguous()216        attn_output = self.o_proj(attn_output)217        return attn_output, attn_weights218 219 220class Olmo3MLP(nn.Module):221    def __init__(self, config):222        super().__init__()223        self.config = config224        self.hidden_size = config.hidden_size225        self.intermediate_size = config.intermediate_size226        self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)227        self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)228        self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)229        self.act_fn = ACT2FN[config.hidden_act]230 231    def forward(self, x):232        down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))233        return down_proj234 235 236class Olmo3DecoderLayer(GradientCheckpointingLayer):237    def __init__(self, config: Olmo3Config, layer_idx: int):238        super().__init__()239        self.hidden_size = config.hidden_size240        self.self_attn = Olmo3Attention(config=config, layer_idx=layer_idx)241 242        self.mlp = Olmo3MLP(config)243        self.post_attention_layernorm = Olmo3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)244        self.post_feedforward_layernorm = Olmo3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)245 246    @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")247    def forward(248        self,249        hidden_states: torch.Tensor,250        attention_mask: Optional[torch.Tensor] = None,251        position_ids: Optional[torch.LongTensor] = None,252        past_key_values: Optional[Cache] = None,253        use_cache: Optional[bool] = False,254        cache_position: Optional[torch.LongTensor] = None,255        position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,  # necessary, but kept here for BC256        **kwargs: Unpack[TransformersKwargs],257    ) -> torch.Tensor:258        residual = hidden_states259        hidden_states, _ = self.self_attn(260            hidden_states=hidden_states,261            attention_mask=attention_mask,262            position_ids=position_ids,263            past_key_values=past_key_values,264            use_cache=use_cache,265            cache_position=cache_position,266            position_embeddings=position_embeddings,267            **kwargs,268        )269        hidden_states = self.post_attention_layernorm(hidden_states)270        hidden_states = residual + hidden_states271 272        # Fully Connected273        residual = hidden_states274        hidden_states = self.mlp(hidden_states)275        hidden_states = self.post_feedforward_layernorm(hidden_states)276        hidden_states = residual + hidden_states277        return hidden_states278 279 280class Olmo3RotaryEmbedding(nn.Module):281    inv_freq: torch.Tensor  # fix linting for `register_buffer`282 283    def __init__(self, config: Olmo3Config, device=None, rope_type: Optional[str] = None):284        super().__init__()285        if rope_type is not None:286            self.rope_type = rope_type287        elif hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):288            # BC: "rope_type" was originally "type"289            self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))290        else:291            self.rope_type = "default"292        assert self.rope_type is not None293 294        self.max_seq_len_cached = config.max_position_embeddings295        self.original_max_seq_len = config.max_position_embeddings296 297        self.config = config298        self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]299 300        inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)301        self.register_buffer("inv_freq", inv_freq, persistent=False)302        self.original_inv_freq = self.inv_freq303 304    @torch.no_grad()305    @dynamic_rope_update  # power user: used with advanced RoPE types (e.g. dynamic rope)306    def forward(self, x, position_ids):307        inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)308        position_ids_expanded = position_ids[:, None, :].float()309 310        device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"311        with torch.autocast(device_type=device_type, enabled=False):  # Force float32312            freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)313            emb = torch.cat((freqs, freqs), dim=-1)314            cos = emb.cos() * self.attention_scaling315            sin = emb.sin() * self.attention_scaling316            return cos, sin317 318 319@auto_docstring320class Olmo3PreTrainedModel(PreTrainedModel):321    config: Olmo3Config322    base_model_prefix = "model"323    supports_gradient_checkpointing = True324    _no_split_modules = ["Olmo3DecoderLayer"]325    _skip_keys_device_placement = ["past_key_values"]326    _supports_flash_attn = True327    _supports_sdpa = True328    _supports_flex_attn = True329 330    _can_compile_fullgraph = True331    _supports_attention_backend = True332    _can_record_outputs = {333        "hidden_states": Olmo3DecoderLayer,334        "attentions": Olmo3Attention,335    }336 337 338@auto_docstring339class Olmo3Model(Olmo3PreTrainedModel):340    def __init__(self, config: Olmo3Config):341        super().__init__(config)342        self.padding_idx = config.pad_token_id343        self.vocab_size = config.vocab_size344 345        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)346        self.layers = nn.ModuleList(347            [Olmo3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]348        )349        self.norm = Olmo3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)350        self.gradient_checkpointing = False351        self.rotary_embs = nn.ModuleDict(352            {353                "sliding_attention": Olmo3RotaryEmbedding(config=config, rope_type="default"),354                "full_attention": Olmo3RotaryEmbedding(config=config),355            }356        )357 358        # Initialize weights and apply final processing359        self.post_init()360 361    @check_model_inputs()362    @auto_docstring363    def forward(364        self,365        input_ids: Optional[torch.LongTensor] = None,366        attention_mask: Optional[torch.Tensor] = None,367        position_ids: Optional[torch.LongTensor] = None,368        past_key_values: Optional[Cache] = None,369        inputs_embeds: Optional[torch.FloatTensor] = None,370        cache_position: Optional[torch.LongTensor] = None,371        use_cache: Optional[bool] = None,372        **kwargs: Unpack[TransformersKwargs],373    ) -> BaseModelOutputWithPast:374        if (input_ids is None) ^ (inputs_embeds is not None):375            raise ValueError("You must specify exactly one of input_ids or inputs_embeds")376 377        if inputs_embeds is None:378            inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)379 380        if use_cache and past_key_values is None:381            past_key_values = DynamicCache(config=self.config)382 383        if cache_position is None:384            past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0385            cache_position: torch.Tensor = torch.arange(386                past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device387            )388 389        if position_ids is None:390            position_ids = cache_position.unsqueeze(0)391 392        # It may already have been prepared by e.g. `generate`393        if not isinstance(causal_mask_mapping := attention_mask, dict):394            # Prepare mask arguments395            mask_kwargs = {396                "config": self.config,397                "input_embeds": inputs_embeds,398                "attention_mask": attention_mask,399                "cache_position": cache_position,400                "past_key_values": past_key_values,401                "position_ids": position_ids,402            }403            # Create the masks404            causal_mask_mapping = {405                "full_attention": create_causal_mask(**mask_kwargs),406                "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),407            }408 409        hidden_states = inputs_embeds410        position_embeddings_mapping = {411            "sliding_attention": self.rotary_embs["sliding_attention"](hidden_states, position_ids),412            "full_attention": self.rotary_embs["full_attention"](hidden_states, position_ids),413        }414 415        for decoder_layer in self.layers[: self.config.num_hidden_layers]:416            hidden_states = decoder_layer(417                hidden_states,418                attention_mask=causal_mask_mapping[decoder_layer.self_attn.attention_type],419                position_ids=position_ids,420                past_key_values=past_key_values,421                cache_position=cache_position,422                position_embeddings=position_embeddings_mapping[decoder_layer.self_attn.attention_type],423                **kwargs,424            )425 426        hidden_states = self.norm(hidden_states)427        return BaseModelOutputWithPast(428            last_hidden_state=hidden_states,429            past_key_values=past_key_values,430        )431 432 433@auto_docstring434class Olmo3ForCausalLM(Olmo3PreTrainedModel, GenerationMixin):435    _tied_weights_keys = ["lm_head.weight"]436    _tp_plan = {"lm_head": "colwise_rep"}437    _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}438 439    def __init__(self, config):440        super().__init__(config)441        self.model = Olmo3Model(config)442        self.vocab_size = config.vocab_size443        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)444 445        # Initialize weights and apply final processing446        self.post_init()447 448    @can_return_tuple449    @auto_docstring450    def forward(451        self,452        input_ids: Optional[torch.LongTensor] = None,453        attention_mask: Optional[torch.Tensor] = None,454        position_ids: Optional[torch.LongTensor] = None,455        past_key_values: Optional[Cache] = None,456        inputs_embeds: Optional[torch.FloatTensor] = None,457        labels: Optional[torch.LongTensor] = None,458        use_cache: Optional[bool] = None,459        cache_position: Optional[torch.LongTensor] = None,460        logits_to_keep: Union[int, torch.Tensor] = 0,461        **kwargs: Unpack[TransformersKwargs],462    ) -> CausalLMOutputWithPast:463        r"""464        Example:465 466        ```python467        >>> from transformers import AutoTokenizer, Olmo3ForCausalLM468 469        >>> model = Olmo3ForCausalLM.from_pretrained("meta-olmo3/Olmo3-2-7b-hf")470        >>> tokenizer = AutoTokenizer.from_pretrained("meta-olmo3/Olmo3-2-7b-hf")471 472        >>> prompt = "Hey, are you conscious? Can you talk to me?"473        >>> inputs = tokenizer(prompt, return_tensors="pt")474 475        >>> # Generate476        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)477        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]478        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."479        ```"""480        outputs: BaseModelOutputWithPast = self.model(481            input_ids=input_ids,482            attention_mask=attention_mask,483            position_ids=position_ids,484            past_key_values=past_key_values,485            inputs_embeds=inputs_embeds,486            use_cache=use_cache,487            cache_position=cache_position,488            **kwargs,489        )490 491        hidden_states = outputs.last_hidden_state492        # Only compute necessary logits, and do not upcast them to float if we are not computing the loss493        slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep494        logits = self.lm_head(hidden_states[:, slice_indices, :])495 496        loss = None497        if labels is not None:498            loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)499 500        return CausalLMOutputWithPast(501            loss=loss,502            logits=logits,503            past_key_values=outputs.past_key_values,504            hidden_states=outputs.hidden_states,505            attentions=outputs.attentions,506        )507 508 509__all__ = ["Olmo3ForCausalLM", "Olmo3Model", "Olmo3PreTrainedModel"]510 
Aluode/PerceptionLabPortable ยท CoolFace