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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/qwen2/modular_qwen2.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_qwen2.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
from typing import Callable, Optional, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch import nn
|
| 11 |
+
|
| 12 |
+
from transformers.activations import ACT2FN
|
| 13 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 14 |
+
from transformers.generation import GenerationMixin
|
| 15 |
+
from transformers.integrations import use_kernel_forward_from_hub
|
| 16 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 17 |
+
from transformers.modeling_layers import (
|
| 18 |
+
GenericForQuestionAnswering,
|
| 19 |
+
GenericForSequenceClassification,
|
| 20 |
+
GenericForTokenClassification,
|
| 21 |
+
GradientCheckpointingLayer,
|
| 22 |
+
)
|
| 23 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 24 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 25 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 26 |
+
from transformers.processing_utils import Unpack
|
| 27 |
+
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 28 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 29 |
+
from transformers.utils.generic import check_model_inputs
|
| 30 |
+
from transformers import Qwen2Config
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Qwen2MLP(nn.Module):
|
| 34 |
+
def __init__(self, config):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.config = config
|
| 37 |
+
self.hidden_size = config.hidden_size
|
| 38 |
+
self.intermediate_size = config.intermediate_size
|
| 39 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 40 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 41 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 42 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 43 |
+
|
| 44 |
+
def forward(self, x):
|
| 45 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 46 |
+
return down_proj
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def rotate_half(x):
|
| 50 |
+
"""Rotates half the hidden dims of the input."""
|
| 51 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 52 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 53 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 57 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
q (`torch.Tensor`): The query tensor.
|
| 61 |
+
k (`torch.Tensor`): The key tensor.
|
| 62 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 63 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 64 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 65 |
+
Deprecated and unused.
|
| 66 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 67 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 68 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 69 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 70 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 71 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 72 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 73 |
+
Returns:
|
| 74 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 75 |
+
"""
|
| 76 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 77 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 78 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 79 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 80 |
+
return q_embed, k_embed
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 84 |
+
"""
|
| 85 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 86 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 87 |
+
"""
|
| 88 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 89 |
+
if n_rep == 1:
|
| 90 |
+
return hidden_states
|
| 91 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 92 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def eager_attention_forward(
|
| 96 |
+
module: nn.Module,
|
| 97 |
+
query: torch.Tensor,
|
| 98 |
+
key: torch.Tensor,
|
| 99 |
+
value: torch.Tensor,
|
| 100 |
+
attention_mask: Optional[torch.Tensor],
|
| 101 |
+
scaling: float,
|
| 102 |
+
dropout: float = 0.0,
|
| 103 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 104 |
+
):
|
| 105 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 106 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 107 |
+
|
| 108 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 109 |
+
|
| 110 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 111 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 112 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 113 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 114 |
+
|
| 115 |
+
return attn_output, attn_weights
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class Qwen2Attention(nn.Module):
|
| 119 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 120 |
+
|
| 121 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
| 122 |
+
super().__init__()
|
| 123 |
+
self.config = config
|
| 124 |
+
self.layer_idx = layer_idx
|
| 125 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 126 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 127 |
+
self.scaling = self.head_dim**-0.5
|
| 128 |
+
self.attention_dropout = config.attention_dropout
|
| 129 |
+
self.is_causal = False
|
| 130 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
|
| 131 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
| 132 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
| 133 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 134 |
+
self.sliding_window = None
|
| 135 |
+
|
| 136 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 137 |
+
def forward(
|
| 138 |
+
self,
|
| 139 |
+
hidden_states: torch.Tensor,
|
| 140 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 141 |
+
attention_mask: Optional[torch.Tensor],
|
| 142 |
+
past_key_values: Optional[Cache] = None,
|
| 143 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 144 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 145 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 146 |
+
input_shape = hidden_states.shape[:-1]
|
| 147 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 148 |
+
|
| 149 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 150 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 151 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 152 |
+
|
| 153 |
+
cos, sin = position_embeddings
|
| 154 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 155 |
+
|
| 156 |
+
if past_key_values is not None:
|
| 157 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 158 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 159 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 160 |
+
|
| 161 |
+
attention_interface: Callable = eager_attention_forward
|
| 162 |
+
if self.config._attn_implementation != "eager":
|
| 163 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 164 |
+
|
| 165 |
+
attn_output, attn_weights = attention_interface(
|
| 166 |
+
self,
|
| 167 |
+
query_states,
|
| 168 |
+
key_states,
|
| 169 |
+
value_states,
|
| 170 |
+
attention_mask,
|
| 171 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 172 |
+
scaling=self.scaling,
|
| 173 |
+
sliding_window=self.sliding_window, # main diff with Llama
|
| 174 |
+
**kwargs,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 178 |
+
attn_output = self.o_proj(attn_output)
|
| 179 |
+
return attn_output, attn_weights
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 183 |
+
class Qwen2RMSNorm(nn.Module):
|
| 184 |
+
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
|
| 185 |
+
"""
|
| 186 |
+
Qwen2RMSNorm is equivalent to T5LayerNorm
|
| 187 |
+
"""
|
| 188 |
+
super().__init__()
|
| 189 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 190 |
+
self.variance_epsilon = eps
|
| 191 |
+
|
| 192 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 193 |
+
input_dtype = hidden_states.dtype
|
| 194 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 195 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 196 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 197 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 198 |
+
|
| 199 |
+
def extra_repr(self):
|
| 200 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class Qwen2DecoderLayer(GradientCheckpointingLayer):
|
| 204 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
| 205 |
+
super().__init__()
|
| 206 |
+
self.hidden_size = config.hidden_size
|
| 207 |
+
|
| 208 |
+
self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
|
| 209 |
+
|
| 210 |
+
self.mlp = Qwen2MLP(config)
|
| 211 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 212 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 213 |
+
self.attention_type = config.layer_types[layer_idx]
|
| 214 |
+
|
| 215 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 216 |
+
def forward(
|
| 217 |
+
self,
|
| 218 |
+
hidden_states: torch.Tensor,
|
| 219 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 220 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 221 |
+
past_key_values: Optional[Cache] = None,
|
| 222 |
+
use_cache: Optional[bool] = False,
|
| 223 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 224 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 225 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 226 |
+
) -> torch.Tensor:
|
| 227 |
+
residual = hidden_states
|
| 228 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 229 |
+
# Self Attention
|
| 230 |
+
hidden_states, _ = self.self_attn(
|
| 231 |
+
hidden_states=hidden_states,
|
| 232 |
+
attention_mask=attention_mask,
|
| 233 |
+
position_ids=position_ids,
|
| 234 |
+
past_key_values=past_key_values,
|
| 235 |
+
use_cache=use_cache,
|
| 236 |
+
cache_position=cache_position,
|
| 237 |
+
position_embeddings=position_embeddings,
|
| 238 |
+
**kwargs,
|
| 239 |
+
)
|
| 240 |
+
hidden_states = residual + hidden_states
|
| 241 |
+
|
| 242 |
+
# Fully Connected
|
| 243 |
+
residual = hidden_states
|
| 244 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 245 |
+
hidden_states = self.mlp(hidden_states)
|
| 246 |
+
hidden_states = residual + hidden_states
|
| 247 |
+
return hidden_states
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@auto_docstring
|
| 251 |
+
class Qwen2PreTrainedModel(PreTrainedModel):
|
| 252 |
+
config: Qwen2Config
|
| 253 |
+
base_model_prefix = "model"
|
| 254 |
+
supports_gradient_checkpointing = True
|
| 255 |
+
_no_split_modules = ["Qwen2DecoderLayer"]
|
| 256 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 257 |
+
_supports_flash_attn = True
|
| 258 |
+
_supports_sdpa = True
|
| 259 |
+
_supports_flex_attn = True
|
| 260 |
+
|
| 261 |
+
_can_compile_fullgraph = True
|
| 262 |
+
_supports_attention_backend = True
|
| 263 |
+
_can_record_outputs = {
|
| 264 |
+
"hidden_states": Qwen2DecoderLayer,
|
| 265 |
+
"attentions": Qwen2Attention,
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class Qwen2RotaryEmbedding(nn.Module):
|
| 270 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 271 |
+
|
| 272 |
+
def __init__(self, config: Qwen2Config, device=None):
|
| 273 |
+
super().__init__()
|
| 274 |
+
# BC: "rope_type" was originally "type"
|
| 275 |
+
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
| 276 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 277 |
+
else:
|
| 278 |
+
self.rope_type = "default"
|
| 279 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 280 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 281 |
+
|
| 282 |
+
self.config = config
|
| 283 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 284 |
+
|
| 285 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 286 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 287 |
+
self.original_inv_freq = self.inv_freq
|
| 288 |
+
|
| 289 |
+
@torch.no_grad()
|
| 290 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 291 |
+
def forward(self, x, position_ids):
|
| 292 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 293 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 294 |
+
|
| 295 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 296 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 297 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 298 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 299 |
+
cos = emb.cos() * self.attention_scaling
|
| 300 |
+
sin = emb.sin() * self.attention_scaling
|
| 301 |
+
|
| 302 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
@auto_docstring
|
| 306 |
+
class Qwen2Model(Qwen2PreTrainedModel):
|
| 307 |
+
def __init__(self, config: Qwen2Config):
|
| 308 |
+
super().__init__(config)
|
| 309 |
+
self.padding_idx = config.pad_token_id
|
| 310 |
+
self.vocab_size = config.vocab_size
|
| 311 |
+
|
| 312 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 313 |
+
self.layers = nn.ModuleList(
|
| 314 |
+
[Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 315 |
+
)
|
| 316 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 317 |
+
self.rotary_emb = Qwen2RotaryEmbedding(config=config)
|
| 318 |
+
self.gradient_checkpointing = False
|
| 319 |
+
self.has_sliding_layers = "sliding_attention" in self.config.layer_types
|
| 320 |
+
|
| 321 |
+
# Initialize weights and apply final processing
|
| 322 |
+
self.post_init()
|
| 323 |
+
|
| 324 |
+
@check_model_inputs
|
| 325 |
+
@auto_docstring
|
| 326 |
+
def forward(
|
| 327 |
+
self,
|
| 328 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 329 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 330 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 331 |
+
past_key_values: Optional[Cache] = None,
|
| 332 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 333 |
+
use_cache: Optional[bool] = None,
|
| 334 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 335 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 336 |
+
) -> BaseModelOutputWithPast:
|
| 337 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 338 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 339 |
+
|
| 340 |
+
if inputs_embeds is None:
|
| 341 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 342 |
+
|
| 343 |
+
# Disable key/value caching for bidirectional attention
|
| 344 |
+
if use_cache and past_key_values is None:
|
| 345 |
+
past_key_values = None
|
| 346 |
+
use_cache = False
|
| 347 |
+
|
| 348 |
+
if cache_position is None:
|
| 349 |
+
cache_position = torch.arange(0, inputs_embeds.shape[1], device=inputs_embeds.device)
|
| 350 |
+
|
| 351 |
+
if position_ids is None:
|
| 352 |
+
position_ids = cache_position.unsqueeze(0)
|
| 353 |
+
|
| 354 |
+
# Disable causal/sliding masks: make attention fully bidirectional
|
| 355 |
+
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
| 356 |
+
causal_mask_mapping = {
|
| 357 |
+
"full_attention": None,
|
| 358 |
+
"sliding_attention": None,
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
hidden_states = inputs_embeds
|
| 362 |
+
|
| 363 |
+
# create position embeddings to be shared across the decoder layers
|
| 364 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 365 |
+
|
| 366 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 367 |
+
hidden_states = decoder_layer(
|
| 368 |
+
hidden_states,
|
| 369 |
+
attention_mask=None,
|
| 370 |
+
position_ids=position_ids,
|
| 371 |
+
past_key_values=past_key_values,
|
| 372 |
+
use_cache=use_cache,
|
| 373 |
+
cache_position=cache_position,
|
| 374 |
+
position_embeddings=position_embeddings,
|
| 375 |
+
**kwargs,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
hidden_states = self.norm(hidden_states)
|
| 379 |
+
return BaseModelOutputWithPast(
|
| 380 |
+
last_hidden_state=hidden_states,
|
| 381 |
+
past_key_values=past_key_values if use_cache else None,
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
@auto_docstring
|
| 386 |
+
class Qwen2ForCausalLM(Qwen2PreTrainedModel, GenerationMixin):
|
| 387 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 388 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 389 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 390 |
+
|
| 391 |
+
def __init__(self, config):
|
| 392 |
+
super().__init__(config)
|
| 393 |
+
self.model = Qwen2Model(config)
|
| 394 |
+
self.vocab_size = config.vocab_size
|
| 395 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 396 |
+
|
| 397 |
+
# Initialize weights and apply final processing
|
| 398 |
+
self.post_init()
|
| 399 |
+
|
| 400 |
+
@can_return_tuple
|
| 401 |
+
@auto_docstring
|
| 402 |
+
def forward(
|
| 403 |
+
self,
|
| 404 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 405 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 406 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 407 |
+
past_key_values: Optional[Cache] = None,
|
| 408 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 409 |
+
labels: Optional[torch.LongTensor] = None,
|
| 410 |
+
use_cache: Optional[bool] = None,
|
| 411 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 412 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 413 |
+
loss_weight: Optional[torch.Tensor] = None,
|
| 414 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 415 |
+
) -> CausalLMOutputWithPast:
|
| 416 |
+
r"""
|
| 417 |
+
Example:
|
| 418 |
+
|
| 419 |
+
```python
|
| 420 |
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
| 421 |
+
|
| 422 |
+
>>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
| 423 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
| 424 |
+
|
| 425 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 426 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 427 |
+
|
| 428 |
+
>>> # Generate
|
| 429 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 430 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 431 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 432 |
+
```"""
|
| 433 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 434 |
+
input_ids=input_ids,
|
| 435 |
+
attention_mask=attention_mask,
|
| 436 |
+
position_ids=position_ids,
|
| 437 |
+
past_key_values=past_key_values,
|
| 438 |
+
inputs_embeds=inputs_embeds,
|
| 439 |
+
use_cache=use_cache,
|
| 440 |
+
cache_position=cache_position,
|
| 441 |
+
**kwargs,
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
hidden_states = outputs.last_hidden_state
|
| 445 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 446 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 447 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 448 |
+
|
| 449 |
+
loss = None
|
| 450 |
+
if labels is not None:
|
| 451 |
+
# Ensure Trainer receives a scalar loss
|
| 452 |
+
base_loss = self.loss_function(
|
| 453 |
+
logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs
|
| 454 |
+
)
|
| 455 |
+
if loss_weight is not None:
|
| 456 |
+
# Accept vector weights (per-sample) or scalar; reduce to a scalar multiplier
|
| 457 |
+
try:
|
| 458 |
+
weight = loss_weight.mean()
|
| 459 |
+
except Exception:
|
| 460 |
+
weight = loss_weight
|
| 461 |
+
loss = base_loss * weight
|
| 462 |
+
else:
|
| 463 |
+
loss = base_loss
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
return CausalLMOutputWithPast(
|
| 467 |
+
loss=loss,
|
| 468 |
+
logits=logits,
|
| 469 |
+
past_key_values=outputs.past_key_values,
|
| 470 |
+
hidden_states=outputs.hidden_states,
|
| 471 |
+
attentions=outputs.attentions,
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
class Qwen2ForMaskedLM(Qwen2PreTrainedModel):
|
| 475 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 476 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 477 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 478 |
+
|
| 479 |
+
def __init__(self, config):
|
| 480 |
+
super().__init__(config)
|
| 481 |
+
self.model = Qwen2Model(config)
|
| 482 |
+
self.vocab_size = config.vocab_size
|
| 483 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 484 |
+
|
| 485 |
+
# Initialize weights and apply final processing
|
| 486 |
+
self.post_init()
|
| 487 |
+
|
| 488 |
+
@can_return_tuple
|
| 489 |
+
@auto_docstring
|
| 490 |
+
def forward(
|
| 491 |
+
self,
|
| 492 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 493 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 494 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 495 |
+
past_key_values: Optional[Cache] = None,
|
| 496 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 497 |
+
labels: Optional[torch.LongTensor] = None,
|
| 498 |
+
use_cache: Optional[bool] = None,
|
| 499 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 500 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 501 |
+
loss_weight: Optional[torch.Tensor] = None,
|
| 502 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 503 |
+
) -> CausalLMOutputWithPast:
|
| 504 |
+
r"""
|
| 505 |
+
Example:
|
| 506 |
+
|
| 507 |
+
```python
|
| 508 |
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
| 509 |
+
|
| 510 |
+
>>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
| 511 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
| 512 |
+
|
| 513 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 514 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 515 |
+
|
| 516 |
+
>>> # Generate
|
| 517 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 518 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 519 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 520 |
+
```"""
|
| 521 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 522 |
+
input_ids=input_ids,
|
| 523 |
+
attention_mask=attention_mask,
|
| 524 |
+
position_ids=position_ids,
|
| 525 |
+
past_key_values=past_key_values,
|
| 526 |
+
inputs_embeds=inputs_embeds,
|
| 527 |
+
use_cache=use_cache,
|
| 528 |
+
cache_position=cache_position,
|
| 529 |
+
**kwargs,
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
hidden_states = outputs.last_hidden_state
|
| 533 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 534 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 535 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 536 |
+
|
| 537 |
+
loss = None
|
| 538 |
+
if labels is not None:
|
| 539 |
+
# Ensure Trainer receives a scalar loss
|
| 540 |
+
base_loss = self.loss_function(
|
| 541 |
+
logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs
|
| 542 |
+
)
|
| 543 |
+
if loss_weight is not None:
|
| 544 |
+
# Accept vector weights (per-sample) or scalar; reduce to a scalar multiplier
|
| 545 |
+
try:
|
| 546 |
+
weight = loss_weight.mean()
|
| 547 |
+
except Exception:
|
| 548 |
+
weight = loss_weight
|
| 549 |
+
loss = base_loss * weight
|
| 550 |
+
else:
|
| 551 |
+
loss = base_loss
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
return CausalLMOutputWithPast(
|
| 555 |
+
loss=loss,
|
| 556 |
+
logits=logits,
|
| 557 |
+
past_key_values=outputs.past_key_values,
|
| 558 |
+
hidden_states=outputs.hidden_states,
|
| 559 |
+
attentions=outputs.attentions,
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
class Qwen2ForSequenceClassification(GenericForSequenceClassification, Qwen2PreTrainedModel):
|
| 564 |
+
pass
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
class Qwen2ForTokenClassification(GenericForTokenClassification, Qwen2PreTrainedModel):
|
| 568 |
+
pass
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
class Qwen2ForQuestionAnswering(GenericForQuestionAnswering, Qwen2PreTrainedModel):
|
| 572 |
+
base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
__all__ = [
|
| 576 |
+
"Qwen2PreTrainedModel",
|
| 577 |
+
"Qwen2Model",
|
| 578 |
+
"Qwen2ForCausalLM",
|
| 579 |
+
"Qwen2RMSNorm",
|
| 580 |
+
"Qwen2ForSequenceClassification",
|
| 581 |
+
"Qwen2ForTokenClassification",
|
| 582 |
+
"Qwen2ForQuestionAnswering",
|
| 583 |
+
]
|