CoolFace
Modelpublic

lucaswychan/Qwen-2.5-0.5B-SimpleRL-Zoo-checkpoint-200-Reasoning-Embedding

sourceHugging Faceapache-2.0updated 8mo agoView on Hugging Face
0likes23downloads
modeling_qwen2.py542 linesDownload Raw Back to root
1# Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14 15from collections.abc import Callable16from typing import Optional17 18import torch19from torch import nn20 21from transformers.activations import ACT2FN22from transformers.cache_utils import Cache, DynamicCache23from transformers.generation import GenerationMixin24from transformers.integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func25from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask26from transformers.modeling_flash_attention_utils import FlashAttentionKwargs27from transformers.modeling_layers import (28    GenericForQuestionAnswering,29    GenericForSequenceClassification,30    GenericForTokenClassification,31    GradientCheckpointingLayer,32)33from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast34from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update35from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel36from transformers.processing_utils import Unpack37from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple38from transformers.utils.generic import check_model_inputs, maybe_autocast39from transformers.models.qwen2.configuration_qwen2 import Qwen2Config40 41 42class Qwen2MLP(nn.Module):43    def __init__(self, config):44        super().__init__()45        self.config = config46        self.hidden_size = config.hidden_size47        self.intermediate_size = config.intermediate_size48        self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)49        self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)50        self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)51        self.act_fn = ACT2FN[config.hidden_act]52 53    def forward(self, x):54        down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))55        return down_proj56 57 58class Qwen2RotaryEmbedding(nn.Module):59    inv_freq: torch.Tensor  # fix linting for `register_buffer`60 61    def __init__(self, config: Qwen2Config, device=None):62        super().__init__()63        self.max_seq_len_cached = config.max_position_embeddings64        self.original_max_seq_len = config.max_position_embeddings65 66        self.config = config67 68        self.rope_type = self.config.rope_parameters["rope_type"]69        rope_init_fn: Callable = self.compute_default_rope_parameters70        if self.rope_type != "default":71            rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]72        inv_freq, self.attention_scaling = rope_init_fn(self.config, device)73 74        self.register_buffer("inv_freq", inv_freq, persistent=False)75        self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)76 77    @staticmethod78    def compute_default_rope_parameters(79        config: Qwen2Config | None = None,80        device: Optional["torch.device"] = None,81        seq_len: int | None = None,82    ) -> tuple["torch.Tensor", float]:83        """84        Computes the inverse frequencies according to the original RoPE implementation85        Args:86            config ([`~transformers.PreTrainedConfig`]):87                The model configuration.88            device (`torch.device`):89                The device to use for initialization of the inverse frequencies.90            seq_len (`int`, *optional*):91                The current sequence length. Unused for this type of RoPE.92        Returns:93            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the94            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).95        """96        base = config.rope_parameters["rope_theta"]97        dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads98 99        attention_factor = 1.0  # Unused in this type of RoPE100 101        # Compute the inverse frequencies102        inv_freq = 1.0 / (103            base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)104        )105        return inv_freq, attention_factor106 107    @torch.no_grad()108    @dynamic_rope_update  # power user: used with advanced RoPE types (e.g. dynamic rope)109    def forward(self, x, position_ids):110        inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)111        position_ids_expanded = position_ids[:, None, :].float()112 113        device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"114        with maybe_autocast(device_type=device_type, enabled=False):  # Force float32115            freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)116            emb = torch.cat((freqs, freqs), dim=-1)117            cos = emb.cos() * self.attention_scaling118            sin = emb.sin() * self.attention_scaling119 120        return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)121 122 123def rotate_half(x):124    """Rotates half the hidden dims of the input."""125    x1 = x[..., : x.shape[-1] // 2]126    x2 = x[..., x.shape[-1] // 2 :]127    return torch.cat((-x2, x1), dim=-1)128 129 130@use_kernel_func_from_hub("rotary_pos_emb")131def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):132    """Applies Rotary Position Embedding to the query and key tensors.133 134    Args:135        q (`torch.Tensor`): The query tensor.136        k (`torch.Tensor`): The key tensor.137        cos (`torch.Tensor`): The cosine part of the rotary embedding.138        sin (`torch.Tensor`): The sine part of the rotary embedding.139        unsqueeze_dim (`int`, *optional*, defaults to 1):140            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and141            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note142            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and143            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes144            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have145            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.146    Returns:147        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.148    """149    cos = cos.unsqueeze(unsqueeze_dim)150    sin = sin.unsqueeze(unsqueeze_dim)151    q_embed = (q * cos) + (rotate_half(q) * sin)152    k_embed = (k * cos) + (rotate_half(k) * sin)153    return q_embed, k_embed154 155 156def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:157    """158    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,159    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)160    """161    batch, num_key_value_heads, slen, head_dim = hidden_states.shape162    if n_rep == 1:163        return hidden_states164    hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)165    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)166 167 168def eager_attention_forward(169    module: nn.Module,170    query: torch.Tensor,171    key: torch.Tensor,172    value: torch.Tensor,173    attention_mask: torch.Tensor | None,174    scaling: float,175    dropout: float = 0.0,176    is_causal: bool = True,177    **kwargs: Unpack[TransformersKwargs],178):179    key_states = repeat_kv(key, module.num_key_value_groups)180    value_states = repeat_kv(value, module.num_key_value_groups)181 182    attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling183    if attention_mask is not None and is_causal:184        causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]185        attn_weights = attn_weights + causal_mask186 187    attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)188    attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)189    attn_output = torch.matmul(attn_weights, value_states)190    attn_output = attn_output.transpose(1, 2).contiguous()191 192    return attn_output, attn_weights193 194 195@use_kernelized_func(apply_rotary_pos_emb)196class Qwen2Attention(nn.Module):197    """Multi-headed attention from 'Attention Is All You Need' paper"""198 199    def __init__(self, config: Qwen2Config, layer_idx: int):200        super().__init__()201        self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None202        self.config = config203        self.layer_idx = layer_idx204        self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)205        self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads206        self.scaling = self.head_dim**-0.5207        self.attention_dropout = config.attention_dropout208        self.is_causal = True209        self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)210        self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)211        self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)212        self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)213        self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None214 215    def forward(216        self,217        hidden_states: torch.Tensor,218        position_embeddings: tuple[torch.Tensor, torch.Tensor],219        attention_mask: torch.Tensor | None,220        past_key_values: Cache | None = None,221        cache_position: torch.LongTensor | None = None,222        is_causal: bool = True,223        **kwargs: Unpack[FlashAttentionKwargs],224    ) -> tuple[torch.Tensor, torch.Tensor | None]:225        input_shape = hidden_states.shape[:-1]226        hidden_shape = (*input_shape, -1, self.head_dim)227 228        query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)229        key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)230        value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)231 232        cos, sin = position_embeddings233        query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)234 235        if past_key_values is not None:236            # sin and cos are specific to RoPE models; cache_position needed for the static cache237            cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}238            key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)239 240        attention_interface: Callable = eager_attention_forward241        if self.config._attn_implementation != "eager":242            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]243 244        attn_output, attn_weights = attention_interface(245            self,246            query_states,247            key_states,248            value_states,249            attention_mask,250            dropout=0.0 if not self.training else self.attention_dropout,251            scaling=self.scaling,252            sliding_window=self.sliding_window,  # main diff with Llama253            is_causal=is_causal,254            **kwargs,255        )256 257        attn_output = attn_output.reshape(*input_shape, -1).contiguous()258        attn_output = self.o_proj(attn_output)259        return attn_output, attn_weights260 261 262@use_kernel_forward_from_hub("RMSNorm")263class Qwen2RMSNorm(nn.Module):264    def __init__(self, hidden_size, eps: float = 1e-6) -> None:265        """266        Qwen2RMSNorm is equivalent to T5LayerNorm267        """268        super().__init__()269        self.weight = nn.Parameter(torch.ones(hidden_size))270        self.variance_epsilon = eps271 272    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:273        input_dtype = hidden_states.dtype274        hidden_states = hidden_states.to(torch.float32)275        variance = hidden_states.pow(2).mean(-1, keepdim=True)276        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)277        return self.weight * hidden_states.to(input_dtype)278 279    def extra_repr(self):280        return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"281 282 283class Qwen2DecoderLayer(GradientCheckpointingLayer):284    def __init__(self, config: Qwen2Config, layer_idx: int):285        super().__init__()286        self.hidden_size = config.hidden_size287 288        self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)289 290        self.mlp = Qwen2MLP(config)291        self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)292        self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)293        self.attention_type = config.layer_types[layer_idx]294 295    def forward(296        self,297        hidden_states: torch.Tensor,298        attention_mask: torch.Tensor | None = None,299        position_ids: torch.LongTensor | None = None,300        past_key_values: Cache | None = None,301        use_cache: bool | None = False,302        cache_position: torch.LongTensor | None = None,303        position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,304        is_causal: bool = True,305        **kwargs: Unpack[TransformersKwargs],306    ) -> torch.Tensor:307        residual = hidden_states308        hidden_states = self.input_layernorm(hidden_states)309        # Self Attention310        hidden_states, _ = self.self_attn(311            hidden_states=hidden_states,312            attention_mask=attention_mask,313            position_ids=position_ids,314            past_key_values=past_key_values,315            use_cache=use_cache,316            cache_position=cache_position,317            position_embeddings=position_embeddings,318            is_causal=is_causal,319            **kwargs,320        )321        hidden_states = residual + hidden_states322 323        # Fully Connected324        residual = hidden_states325        hidden_states = self.post_attention_layernorm(hidden_states)326        hidden_states = self.mlp(hidden_states)327        hidden_states = residual + hidden_states328        return hidden_states329 330 331@auto_docstring332class Qwen2PreTrainedModel(PreTrainedModel):333    config: Qwen2Config334    base_model_prefix = "model"335    supports_gradient_checkpointing = True336    _no_split_modules = ["Qwen2DecoderLayer"]337    _skip_keys_device_placement = ["past_key_values"]338    _supports_flash_attn = True339    _supports_sdpa = True340    _supports_flex_attn = True341 342    _can_compile_fullgraph = True343    _supports_attention_backend = True344    _can_record_outputs = {345        "hidden_states": Qwen2DecoderLayer,346        "attentions": Qwen2Attention,347    }348 349 350@auto_docstring351class Qwen2Model(Qwen2PreTrainedModel):352    def __init__(self, config: Qwen2Config):353        super().__init__(config)354        self.padding_idx = config.pad_token_id355        self.vocab_size = config.vocab_size356 357        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)358        self.layers = nn.ModuleList(359            [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]360        )361        self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)362        self.rotary_emb = Qwen2RotaryEmbedding(config=config)363        self.gradient_checkpointing = False364        self.has_sliding_layers = "sliding_attention" in self.config.layer_types365 366        # Initialize weights and apply final processing367        self.post_init()368 369    @check_model_inputs370    @auto_docstring371    def forward(372        self,373        input_ids: torch.LongTensor | None = None,374        attention_mask: torch.Tensor | None = None,375        position_ids: torch.LongTensor | None = None,376        past_key_values: Cache | None = None,377        inputs_embeds: torch.FloatTensor | None = None,378        use_cache: bool | None = None,379        cache_position: torch.LongTensor | None = None,380        is_causal: bool = False,381        **kwargs: Unpack[TransformersKwargs],382    ) -> BaseModelOutputWithPast:383        if (input_ids is None) ^ (inputs_embeds is not None):384            raise ValueError("You must specify exactly one of input_ids or inputs_embeds")385 386        if inputs_embeds is None:387            inputs_embeds = self.embed_tokens(input_ids)388 389        if use_cache and past_key_values is None:390            past_key_values = DynamicCache(config=self.config)391 392        if cache_position is None:393            past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0394            cache_position = torch.arange(395                past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device396            )397 398        if position_ids is None:399            position_ids = cache_position.unsqueeze(0)400 401        # It may already have been prepared by e.g. `generate`402        if not isinstance(causal_mask_mapping := attention_mask, dict):403            # Prepare mask arguments404            mask_kwargs = {405                "config": self.config,406                "input_embeds": inputs_embeds,407                "attention_mask": attention_mask,408                "cache_position": cache_position,409                "past_key_values": past_key_values,410                "position_ids": position_ids,411            }412            # Create the masks413            causal_mask_mapping = {414                "full_attention": create_causal_mask(**mask_kwargs),415            }416            # The sliding window alternating layers are not always activated depending on the config417            if self.has_sliding_layers:418                causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)419 420        hidden_states = inputs_embeds421        position_embeddings = self.rotary_emb(hidden_states, position_ids)422 423        for decoder_layer in self.layers[: self.config.num_hidden_layers]:424            hidden_states = decoder_layer(425                hidden_states,426                attention_mask=causal_mask_mapping[decoder_layer.attention_type],427                position_embeddings=position_embeddings,428                position_ids=position_ids,429                past_key_values=past_key_values,430                use_cache=use_cache,431                cache_position=cache_position,432                is_causal=is_causal,433                **kwargs,434            )435 436        hidden_states = self.norm(hidden_states)437        return BaseModelOutputWithPast(438            last_hidden_state=hidden_states,439            past_key_values=past_key_values if use_cache else None,440        )441 442 443@auto_docstring444class Qwen2ForCausalLM(Qwen2PreTrainedModel, GenerationMixin):445    _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}446    _tp_plan = {"lm_head": "colwise_rep"}447    _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}448 449    def __init__(self, config):450        super().__init__(config)451        self.model = Qwen2Model(config)452        self.vocab_size = config.vocab_size453        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)454 455        # Initialize weights and apply final processing456        self.post_init()457 458    @can_return_tuple459    @auto_docstring460    def forward(461        self,462        input_ids: torch.LongTensor | None = None,463        attention_mask: torch.Tensor | None = None,464        position_ids: torch.LongTensor | None = None,465        past_key_values: Cache | None = None,466        inputs_embeds: torch.FloatTensor | None = None,467        labels: torch.LongTensor | None = None,468        use_cache: bool | None = None,469        cache_position: torch.LongTensor | None = None,470        logits_to_keep: int | torch.Tensor = 0,471        is_causal: bool = True,472        **kwargs: Unpack[TransformersKwargs],473    ) -> CausalLMOutputWithPast:474        r"""475        Example:476 477        ```python478        >>> from transformers import AutoTokenizer, Qwen2ForCausalLM479 480        >>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")481        >>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")482 483        >>> prompt = "Hey, are you conscious? Can you talk to me?"484        >>> inputs = tokenizer(prompt, return_tensors="pt")485 486        >>> # Generate487        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)488        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]489        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."490        ```"""491        outputs: BaseModelOutputWithPast = self.model(492            input_ids=input_ids,493            attention_mask=attention_mask,494            position_ids=position_ids,495            past_key_values=past_key_values,496            inputs_embeds=inputs_embeds,497            use_cache=use_cache,498            cache_position=cache_position,499            is_causal=is_causal,500            **kwargs,501        )502 503        hidden_states = outputs.last_hidden_state504        # Only compute necessary logits, and do not upcast them to float if we are not computing the loss505        slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep506        logits = self.lm_head(hidden_states[:, slice_indices, :])507 508        loss = None509        if labels is not None:510            loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)511 512        return CausalLMOutputWithPast(513            loss=loss,514            logits=logits,515            past_key_values=outputs.past_key_values,516            hidden_states=outputs.hidden_states,517            attentions=outputs.attentions,518        )519 520 521class Qwen2ForSequenceClassification(GenericForSequenceClassification, Qwen2PreTrainedModel):522    pass523 524 525class Qwen2ForTokenClassification(GenericForTokenClassification, Qwen2PreTrainedModel):526    pass527 528 529class Qwen2ForQuestionAnswering(GenericForQuestionAnswering, Qwen2PreTrainedModel):530    base_model_prefix = "transformer"  # For BC, where `transformer` was used instead of `model`531 532 533__all__ = [534    "Qwen2PreTrainedModel",535    "Qwen2Model",536    "Qwen2ForCausalLM",537    "Qwen2RMSNorm",538    "Qwen2ForSequenceClassification",539    "Qwen2ForTokenClassification",540    "Qwen2ForQuestionAnswering",541]542