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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.utils.checkpoint
|
| 11 |
+
from safetensors.torch import load_file
|
| 12 |
+
from transformers.activations import ACT2FN
|
| 13 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
| 14 |
+
|
| 15 |
+
from .gpt2_decoder import PackedSequenceMetadata, MossTTSNanoGPT2Model
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 19 |
+
from flash_attn.bert_padding import pad_input, unpad_input
|
| 20 |
+
|
| 21 |
+
_FLASH_ATTN_AVAILABLE = True
|
| 22 |
+
except Exception:
|
| 23 |
+
flash_attn_func = None
|
| 24 |
+
flash_attn_varlen_func = None
|
| 25 |
+
pad_input = None
|
| 26 |
+
unpad_input = None
|
| 27 |
+
_FLASH_ATTN_AVAILABLE = False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class MossQwen3RMSNorm(nn.Module):
|
| 31 |
+
def __init__(self, hidden_size: int, eps: float = 1e-6) -> None:
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 34 |
+
self.variance_epsilon = eps
|
| 35 |
+
|
| 36 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 37 |
+
input_dtype = hidden_states.dtype
|
| 38 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 39 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 40 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 41 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class MossQwen3RotaryEmbedding(nn.Module):
|
| 45 |
+
def __init__(self, config) -> None:
|
| 46 |
+
super().__init__()
|
| 47 |
+
head_dim = int(getattr(config, "head_dim", config.hidden_size // config.num_attention_heads))
|
| 48 |
+
rope_theta = getattr(config, "rope_theta", None)
|
| 49 |
+
if rope_theta is None:
|
| 50 |
+
rope_scaling = getattr(config, "rope_scaling", None)
|
| 51 |
+
if isinstance(rope_scaling, dict):
|
| 52 |
+
rope_theta = rope_scaling.get("rope_theta")
|
| 53 |
+
if rope_theta is None:
|
| 54 |
+
rope_theta = 1000000.0
|
| 55 |
+
rope_theta = float(rope_theta)
|
| 56 |
+
self.head_dim = head_dim
|
| 57 |
+
self.rope_theta = rope_theta
|
| 58 |
+
self.register_buffer("inv_freq", self._compute_inv_freq(), persistent=False)
|
| 59 |
+
|
| 60 |
+
def _compute_inv_freq(self, device: Optional[torch.device] = None) -> torch.Tensor:
|
| 61 |
+
return 1.0 / (
|
| 62 |
+
self.rope_theta ** (torch.arange(0, self.head_dim, 2, device=device, dtype=torch.float32) / self.head_dim)
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def forward(
|
| 66 |
+
self,
|
| 67 |
+
hidden_states: torch.Tensor,
|
| 68 |
+
position_ids: torch.LongTensor,
|
| 69 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 70 |
+
inv_freq = self._compute_inv_freq(device=hidden_states.device)
|
| 71 |
+
freqs = torch.einsum(
|
| 72 |
+
"bs,d->bsd",
|
| 73 |
+
position_ids.to(device=hidden_states.device, dtype=inv_freq.dtype),
|
| 74 |
+
inv_freq,
|
| 75 |
+
)
|
| 76 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 77 |
+
return emb.cos().to(dtype=hidden_states.dtype), emb.sin().to(dtype=hidden_states.dtype)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def rotate_half(hidden_states: torch.Tensor) -> torch.Tensor:
|
| 81 |
+
first_half = hidden_states[..., : hidden_states.shape[-1] // 2]
|
| 82 |
+
second_half = hidden_states[..., hidden_states.shape[-1] // 2 :]
|
| 83 |
+
return torch.cat((-second_half, first_half), dim=-1)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def apply_rotary_pos_emb(
|
| 87 |
+
query: torch.Tensor,
|
| 88 |
+
key: torch.Tensor,
|
| 89 |
+
cos: torch.Tensor,
|
| 90 |
+
sin: torch.Tensor,
|
| 91 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 92 |
+
cos = cos.unsqueeze(-2)
|
| 93 |
+
sin = sin.unsqueeze(-2)
|
| 94 |
+
query = (query * cos) + (rotate_half(query) * sin)
|
| 95 |
+
key = (key * cos) + (rotate_half(key) * sin)
|
| 96 |
+
return query, key
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 100 |
+
if n_rep == 1:
|
| 101 |
+
return hidden_states
|
| 102 |
+
batch, seq_len, num_key_value_heads, head_dim = hidden_states.shape
|
| 103 |
+
hidden_states = hidden_states[:, :, :, None, :].expand(batch, seq_len, num_key_value_heads, n_rep, head_dim)
|
| 104 |
+
return hidden_states.reshape(batch, seq_len, num_key_value_heads * n_rep, head_dim)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class MossQwen3MLP(nn.Module):
|
| 108 |
+
def __init__(self, config) -> None:
|
| 109 |
+
super().__init__()
|
| 110 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 111 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 112 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 113 |
+
self.act_fn = ACT2FN[getattr(config, "hidden_act", "silu")]
|
| 114 |
+
|
| 115 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 116 |
+
return self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class MossQwen3Attention(nn.Module):
|
| 120 |
+
def __init__(self, config, layer_idx: int) -> None:
|
| 121 |
+
super().__init__()
|
| 122 |
+
self.config = config
|
| 123 |
+
self.layer_idx = int(layer_idx)
|
| 124 |
+
self.hidden_size = int(config.hidden_size)
|
| 125 |
+
self.num_heads = int(config.num_attention_heads)
|
| 126 |
+
self.num_key_value_heads = int(config.num_key_value_heads)
|
| 127 |
+
self.head_dim = int(getattr(config, "head_dim", self.hidden_size // self.num_heads))
|
| 128 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 129 |
+
self.scaling = self.head_dim ** -0.5
|
| 130 |
+
self.attention_dropout = float(getattr(config, "attention_dropout", 0.0))
|
| 131 |
+
self.attn_implementation = str(getattr(config, "_attn_implementation", "eager"))
|
| 132 |
+
|
| 133 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=bool(config.attention_bias))
|
| 134 |
+
self.k_proj = nn.Linear(
|
| 135 |
+
self.hidden_size,
|
| 136 |
+
self.num_key_value_heads * self.head_dim,
|
| 137 |
+
bias=bool(config.attention_bias),
|
| 138 |
+
)
|
| 139 |
+
self.v_proj = nn.Linear(
|
| 140 |
+
self.hidden_size,
|
| 141 |
+
self.num_key_value_heads * self.head_dim,
|
| 142 |
+
bias=bool(config.attention_bias),
|
| 143 |
+
)
|
| 144 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=bool(config.attention_bias))
|
| 145 |
+
self.q_norm = MossQwen3RMSNorm(self.head_dim, eps=float(config.rms_norm_eps))
|
| 146 |
+
self.k_norm = MossQwen3RMSNorm(self.head_dim, eps=float(config.rms_norm_eps))
|
| 147 |
+
|
| 148 |
+
def _causal_attention_mask(
|
| 149 |
+
self,
|
| 150 |
+
attention_mask: Optional[torch.Tensor],
|
| 151 |
+
query_length: int,
|
| 152 |
+
key_length: int,
|
| 153 |
+
device: torch.device,
|
| 154 |
+
) -> torch.Tensor:
|
| 155 |
+
query_positions = torch.arange(query_length, device=device, dtype=torch.long)
|
| 156 |
+
query_positions = query_positions + max(key_length - query_length, 0)
|
| 157 |
+
key_positions = torch.arange(key_length, device=device, dtype=torch.long)
|
| 158 |
+
causal = key_positions.unsqueeze(0) <= query_positions.unsqueeze(1)
|
| 159 |
+
causal = causal.unsqueeze(0).unsqueeze(0)
|
| 160 |
+
if attention_mask is None:
|
| 161 |
+
return causal
|
| 162 |
+
key_mask = attention_mask[:, None, None, :].to(dtype=torch.bool)
|
| 163 |
+
return causal & key_mask
|
| 164 |
+
|
| 165 |
+
def _eager_attention(
|
| 166 |
+
self,
|
| 167 |
+
query: torch.Tensor,
|
| 168 |
+
key: torch.Tensor,
|
| 169 |
+
value: torch.Tensor,
|
| 170 |
+
attention_mask: Optional[torch.Tensor],
|
| 171 |
+
) -> torch.Tensor:
|
| 172 |
+
key = repeat_kv(key, self.num_key_value_groups)
|
| 173 |
+
value = repeat_kv(value, self.num_key_value_groups)
|
| 174 |
+
query = query.transpose(1, 2)
|
| 175 |
+
key = key.transpose(1, 2)
|
| 176 |
+
value = value.transpose(1, 2)
|
| 177 |
+
scores = torch.matmul(query, key.transpose(-1, -2)) * self.scaling
|
| 178 |
+
mask = self._causal_attention_mask(
|
| 179 |
+
attention_mask=attention_mask,
|
| 180 |
+
query_length=query.shape[-2],
|
| 181 |
+
key_length=key.shape[-2],
|
| 182 |
+
device=query.device,
|
| 183 |
+
)
|
| 184 |
+
scores = scores.masked_fill(~mask, torch.finfo(scores.dtype).min)
|
| 185 |
+
probs = torch.softmax(scores, dim=-1)
|
| 186 |
+
if self.training and self.attention_dropout > 0:
|
| 187 |
+
probs = torch.dropout(probs, self.attention_dropout, train=True)
|
| 188 |
+
output = torch.matmul(probs, value)
|
| 189 |
+
return output.transpose(1, 2).contiguous()
|
| 190 |
+
|
| 191 |
+
def _sdpa_attention(
|
| 192 |
+
self,
|
| 193 |
+
query: torch.Tensor,
|
| 194 |
+
key: torch.Tensor,
|
| 195 |
+
value: torch.Tensor,
|
| 196 |
+
attention_mask: Optional[torch.Tensor],
|
| 197 |
+
) -> torch.Tensor:
|
| 198 |
+
key = repeat_kv(key, self.num_key_value_groups)
|
| 199 |
+
value = repeat_kv(value, self.num_key_value_groups)
|
| 200 |
+
query = query.transpose(1, 2)
|
| 201 |
+
key = key.transpose(1, 2)
|
| 202 |
+
value = value.transpose(1, 2)
|
| 203 |
+
mask = None
|
| 204 |
+
if attention_mask is not None or query.shape[-2] != key.shape[-2]:
|
| 205 |
+
mask = self._causal_attention_mask(
|
| 206 |
+
attention_mask=attention_mask,
|
| 207 |
+
query_length=query.shape[-2],
|
| 208 |
+
key_length=key.shape[-2],
|
| 209 |
+
device=query.device,
|
| 210 |
+
)
|
| 211 |
+
output = torch.nn.functional.scaled_dot_product_attention(
|
| 212 |
+
query,
|
| 213 |
+
key,
|
| 214 |
+
value,
|
| 215 |
+
attn_mask=mask,
|
| 216 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 217 |
+
is_causal=mask is None,
|
| 218 |
+
scale=self.scaling,
|
| 219 |
+
)
|
| 220 |
+
return output.transpose(1, 2).contiguous()
|
| 221 |
+
|
| 222 |
+
def _flash_attention(
|
| 223 |
+
self,
|
| 224 |
+
query: torch.Tensor,
|
| 225 |
+
key: torch.Tensor,
|
| 226 |
+
value: torch.Tensor,
|
| 227 |
+
attention_mask: Optional[torch.Tensor],
|
| 228 |
+
packed_metadata: Optional[PackedSequenceMetadata],
|
| 229 |
+
) -> torch.Tensor:
|
| 230 |
+
if not _FLASH_ATTN_AVAILABLE:
|
| 231 |
+
raise ImportError("flash_attn is not installed, but attn_implementation='flash_attention_2' was requested.")
|
| 232 |
+
if query.device.type != "cuda":
|
| 233 |
+
raise ValueError("flash_attention_2 requires CUDA tensors.")
|
| 234 |
+
if query.dtype not in (torch.float16, torch.bfloat16):
|
| 235 |
+
raise ValueError(f"flash_attention_2 requires fp16/bf16 tensors, got dtype={query.dtype}.")
|
| 236 |
+
|
| 237 |
+
dropout_p = self.attention_dropout if self.training else 0.0
|
| 238 |
+
if packed_metadata is not None:
|
| 239 |
+
if packed_metadata.indices is not None:
|
| 240 |
+
query = query.reshape(-1, self.num_heads, self.head_dim).index_select(0, packed_metadata.indices)
|
| 241 |
+
key = key.reshape(-1, self.num_key_value_heads, self.head_dim).index_select(0, packed_metadata.indices)
|
| 242 |
+
value = value.reshape(-1, self.num_key_value_heads, self.head_dim).index_select(0, packed_metadata.indices)
|
| 243 |
+
output = flash_attn_varlen_func(
|
| 244 |
+
query,
|
| 245 |
+
key,
|
| 246 |
+
value,
|
| 247 |
+
packed_metadata.cu_seqlens,
|
| 248 |
+
packed_metadata.cu_seqlens,
|
| 249 |
+
packed_metadata.max_seqlen,
|
| 250 |
+
packed_metadata.max_seqlen,
|
| 251 |
+
dropout_p=dropout_p,
|
| 252 |
+
causal=True,
|
| 253 |
+
)
|
| 254 |
+
if packed_metadata.indices is None:
|
| 255 |
+
return output
|
| 256 |
+
return pad_input(
|
| 257 |
+
output,
|
| 258 |
+
packed_metadata.indices,
|
| 259 |
+
packed_metadata.batch_size,
|
| 260 |
+
packed_metadata.seq_len,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
if attention_mask is None or bool(attention_mask.all()):
|
| 264 |
+
return flash_attn_func(query, key, value, dropout_p=dropout_p, causal=True)
|
| 265 |
+
|
| 266 |
+
if query.shape[1] != key.shape[1]:
|
| 267 |
+
query_attention_mask = attention_mask[:, -query.shape[1] :]
|
| 268 |
+
unpadded_query, query_indices, cu_seqlens_q, max_seqlen_q, _ = unpad_input(
|
| 269 |
+
query,
|
| 270 |
+
query_attention_mask,
|
| 271 |
+
)
|
| 272 |
+
unpadded_key, _, cu_seqlens_k, max_seqlen_k, _ = unpad_input(key, attention_mask)
|
| 273 |
+
unpadded_value, _, _, _, _ = unpad_input(value, attention_mask)
|
| 274 |
+
output = flash_attn_varlen_func(
|
| 275 |
+
unpadded_query,
|
| 276 |
+
unpadded_key,
|
| 277 |
+
unpadded_value,
|
| 278 |
+
cu_seqlens_q,
|
| 279 |
+
cu_seqlens_k,
|
| 280 |
+
max_seqlen_q,
|
| 281 |
+
max_seqlen_k,
|
| 282 |
+
dropout_p=dropout_p,
|
| 283 |
+
causal=True,
|
| 284 |
+
)
|
| 285 |
+
return pad_input(output, query_indices, query.shape[0], query.shape[1])
|
| 286 |
+
|
| 287 |
+
unpadded_query, indices, cu_seqlens, max_seqlen, _ = unpad_input(query, attention_mask)
|
| 288 |
+
unpadded_key, _, _, _, _ = unpad_input(key, attention_mask)
|
| 289 |
+
unpadded_value, _, _, _, _ = unpad_input(value, attention_mask)
|
| 290 |
+
output = flash_attn_varlen_func(
|
| 291 |
+
unpadded_query,
|
| 292 |
+
unpadded_key,
|
| 293 |
+
unpadded_value,
|
| 294 |
+
cu_seqlens,
|
| 295 |
+
cu_seqlens,
|
| 296 |
+
max_seqlen,
|
| 297 |
+
max_seqlen,
|
| 298 |
+
dropout_p=dropout_p,
|
| 299 |
+
causal=True,
|
| 300 |
+
)
|
| 301 |
+
return pad_input(output, indices, query.shape[0], query.shape[1])
|
| 302 |
+
|
| 303 |
+
def forward(
|
| 304 |
+
self,
|
| 305 |
+
hidden_states: torch.Tensor,
|
| 306 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 307 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 308 |
+
packed_metadata: Optional[PackedSequenceMetadata] = None,
|
| 309 |
+
layer_past: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 310 |
+
use_cache: bool = False,
|
| 311 |
+
) -> tuple[torch.Tensor, Optional[tuple[torch.Tensor, torch.Tensor]]]:
|
| 312 |
+
input_shape = hidden_states.shape[:-1]
|
| 313 |
+
query_states = self.q_norm(
|
| 314 |
+
self.q_proj(hidden_states).view(*input_shape, self.num_heads, self.head_dim)
|
| 315 |
+
)
|
| 316 |
+
key_states = self.k_norm(
|
| 317 |
+
self.k_proj(hidden_states).view(*input_shape, self.num_key_value_heads, self.head_dim)
|
| 318 |
+
)
|
| 319 |
+
value_states = self.v_proj(hidden_states).view(*input_shape, self.num_key_value_heads, self.head_dim)
|
| 320 |
+
|
| 321 |
+
cos, sin = position_embeddings
|
| 322 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 323 |
+
|
| 324 |
+
if layer_past is not None:
|
| 325 |
+
past_key, past_value = layer_past
|
| 326 |
+
key_states = torch.cat([past_key.to(device=key_states.device, dtype=key_states.dtype), key_states], dim=1)
|
| 327 |
+
value_states = torch.cat(
|
| 328 |
+
[past_value.to(device=value_states.device, dtype=value_states.dtype), value_states],
|
| 329 |
+
dim=1,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
present = (key_states, value_states) if use_cache else None
|
| 333 |
+
if self.attn_implementation == "flash_attention_2":
|
| 334 |
+
attn_output = self._flash_attention(
|
| 335 |
+
query=query_states,
|
| 336 |
+
key=key_states,
|
| 337 |
+
value=value_states,
|
| 338 |
+
attention_mask=attention_mask,
|
| 339 |
+
packed_metadata=packed_metadata,
|
| 340 |
+
)
|
| 341 |
+
elif self.attn_implementation == "sdpa":
|
| 342 |
+
attn_output = self._sdpa_attention(
|
| 343 |
+
query=query_states,
|
| 344 |
+
key=key_states,
|
| 345 |
+
value=value_states,
|
| 346 |
+
attention_mask=attention_mask,
|
| 347 |
+
)
|
| 348 |
+
else:
|
| 349 |
+
attn_output = self._eager_attention(
|
| 350 |
+
query=query_states,
|
| 351 |
+
key=key_states,
|
| 352 |
+
value=value_states,
|
| 353 |
+
attention_mask=attention_mask,
|
| 354 |
+
)
|
| 355 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 356 |
+
return self.o_proj(attn_output), present
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class MossQwen3DecoderLayer(nn.Module):
|
| 360 |
+
def __init__(self, config, layer_idx: int) -> None:
|
| 361 |
+
super().__init__()
|
| 362 |
+
self.self_attn = MossQwen3Attention(config=config, layer_idx=layer_idx)
|
| 363 |
+
self.mlp = MossQwen3MLP(config)
|
| 364 |
+
self.input_layernorm = MossQwen3RMSNorm(config.hidden_size, eps=float(config.rms_norm_eps))
|
| 365 |
+
self.post_attention_layernorm = MossQwen3RMSNorm(config.hidden_size, eps=float(config.rms_norm_eps))
|
| 366 |
+
|
| 367 |
+
def forward(
|
| 368 |
+
self,
|
| 369 |
+
hidden_states: torch.Tensor,
|
| 370 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 371 |
+
packed_metadata: Optional[PackedSequenceMetadata] = None,
|
| 372 |
+
layer_past: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 373 |
+
use_cache: bool = False,
|
| 374 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 375 |
+
) -> tuple[torch.Tensor, Optional[tuple[torch.Tensor, torch.Tensor]]]:
|
| 376 |
+
residual = hidden_states
|
| 377 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 378 |
+
attn_output, present = self.self_attn(
|
| 379 |
+
hidden_states=hidden_states,
|
| 380 |
+
position_embeddings=position_embeddings,
|
| 381 |
+
attention_mask=attention_mask,
|
| 382 |
+
packed_metadata=packed_metadata,
|
| 383 |
+
layer_past=layer_past,
|
| 384 |
+
use_cache=use_cache,
|
| 385 |
+
)
|
| 386 |
+
hidden_states = residual + attn_output
|
| 387 |
+
|
| 388 |
+
residual = hidden_states
|
| 389 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 390 |
+
hidden_states = residual + self.mlp(hidden_states)
|
| 391 |
+
return hidden_states, present
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
class MossQwen3Model(nn.Module):
|
| 395 |
+
def __init__(self, config) -> None:
|
| 396 |
+
super().__init__()
|
| 397 |
+
self.config = config
|
| 398 |
+
self.attn_implementation = str(getattr(config, "_attn_implementation", "eager"))
|
| 399 |
+
self.padding_idx = getattr(config, "pad_token_id", None)
|
| 400 |
+
self.vocab_size = int(config.vocab_size)
|
| 401 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 402 |
+
self.layers = nn.ModuleList(
|
| 403 |
+
[MossQwen3DecoderLayer(config, layer_idx=index) for index in range(config.num_hidden_layers)]
|
| 404 |
+
)
|
| 405 |
+
self.norm = MossQwen3RMSNorm(config.hidden_size, eps=float(config.rms_norm_eps))
|
| 406 |
+
self.rotary_emb = MossQwen3RotaryEmbedding(config)
|
| 407 |
+
self.gradient_checkpointing = False
|
| 408 |
+
self.gradient_checkpointing_use_reentrant = bool(
|
| 409 |
+
getattr(config, "gradient_checkpointing_use_reentrant", False)
|
| 410 |
+
)
|
| 411 |
+
self._reset_parameters()
|
| 412 |
+
|
| 413 |
+
def _reset_parameters(self) -> None:
|
| 414 |
+
init_std = float(getattr(self.config, "initializer_range", 0.02))
|
| 415 |
+
for module in self.modules():
|
| 416 |
+
if isinstance(module, nn.Linear):
|
| 417 |
+
nn.init.normal_(module.weight, mean=0.0, std=init_std)
|
| 418 |
+
if module.bias is not None:
|
| 419 |
+
nn.init.zeros_(module.bias)
|
| 420 |
+
elif isinstance(module, nn.Embedding):
|
| 421 |
+
nn.init.normal_(module.weight, mean=0.0, std=init_std)
|
| 422 |
+
|
| 423 |
+
def get_input_embeddings(self):
|
| 424 |
+
return self.embed_tokens
|
| 425 |
+
|
| 426 |
+
def set_input_embeddings(self, value):
|
| 427 |
+
self.embed_tokens = value
|
| 428 |
+
|
| 429 |
+
def load_qwen3_pretrained_weights(self, pretrained_path: str) -> None:
|
| 430 |
+
model_dir = Path(pretrained_path)
|
| 431 |
+
index_path = model_dir / "model.safetensors.index.json"
|
| 432 |
+
if not index_path.exists():
|
| 433 |
+
raise FileNotFoundError(f"Missing Qwen3 safetensors index: {index_path}")
|
| 434 |
+
with index_path.open("r", encoding="utf-8") as handle:
|
| 435 |
+
index = json.load(handle)
|
| 436 |
+
weight_map = index.get("weight_map", {})
|
| 437 |
+
shard_to_keys: dict[str, list[str]] = {}
|
| 438 |
+
for key, shard in weight_map.items():
|
| 439 |
+
if not key.startswith("model."):
|
| 440 |
+
continue
|
| 441 |
+
shard_to_keys.setdefault(str(shard), []).append(key)
|
| 442 |
+
|
| 443 |
+
state_dict = self.state_dict()
|
| 444 |
+
loaded_state = {}
|
| 445 |
+
for shard, keys in sorted(shard_to_keys.items()):
|
| 446 |
+
shard_tensors = load_file(str(model_dir / shard), device="cpu")
|
| 447 |
+
for key in keys:
|
| 448 |
+
target_key = key[len("model.") :]
|
| 449 |
+
if target_key not in state_dict:
|
| 450 |
+
continue
|
| 451 |
+
tensor = shard_tensors[key]
|
| 452 |
+
if tuple(tensor.shape) != tuple(state_dict[target_key].shape):
|
| 453 |
+
raise ValueError(
|
| 454 |
+
f"Shape mismatch while loading Qwen3 weight {key}: "
|
| 455 |
+
f"checkpoint={tuple(tensor.shape)} model={tuple(state_dict[target_key].shape)}"
|
| 456 |
+
)
|
| 457 |
+
loaded_state[target_key] = tensor
|
| 458 |
+
|
| 459 |
+
missing, unexpected = self.load_state_dict(loaded_state, strict=False)
|
| 460 |
+
unexpected = [key for key in unexpected if key]
|
| 461 |
+
if unexpected:
|
| 462 |
+
raise RuntimeError(f"Unexpected Qwen3 pretrained keys after load: {unexpected[:10]}")
|
| 463 |
+
missing = [key for key in missing if key not in loaded_state]
|
| 464 |
+
if missing:
|
| 465 |
+
raise RuntimeError(f"Missing Qwen3 pretrained keys after load: {missing[:10]}")
|
| 466 |
+
|
| 467 |
+
def forward(
|
| 468 |
+
self,
|
| 469 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 470 |
+
past_key_values: Optional[tuple[tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
| 471 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 472 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 473 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 474 |
+
use_cache: Optional[bool] = None,
|
| 475 |
+
output_attentions: Optional[bool] = None,
|
| 476 |
+
output_hidden_states: Optional[bool] = None,
|
| 477 |
+
return_dict: bool = True,
|
| 478 |
+
cu_seqlens: Optional[torch.Tensor] = None,
|
| 479 |
+
num_sequences: Optional[torch.Tensor] = None,
|
| 480 |
+
) -> BaseModelOutputWithPast:
|
| 481 |
+
del input_ids, output_attentions
|
| 482 |
+
if inputs_embeds is None:
|
| 483 |
+
raise ValueError("inputs_embeds must be provided.")
|
| 484 |
+
|
| 485 |
+
use_cache = bool(use_cache)
|
| 486 |
+
if use_cache and cu_seqlens is not None:
|
| 487 |
+
raise ValueError("use_cache=True is not supported together with cu_seqlens packing.")
|
| 488 |
+
|
| 489 |
+
hidden_states = inputs_embeds
|
| 490 |
+
if attention_mask is None:
|
| 491 |
+
attention_mask = torch.ones(hidden_states.shape[:2], dtype=torch.bool, device=hidden_states.device)
|
| 492 |
+
else:
|
| 493 |
+
attention_mask = attention_mask.to(dtype=torch.bool, device=hidden_states.device)
|
| 494 |
+
query_attention_mask = attention_mask[:, -hidden_states.shape[1] :]
|
| 495 |
+
|
| 496 |
+
packed_metadata = None
|
| 497 |
+
if position_ids is None:
|
| 498 |
+
if cu_seqlens is not None:
|
| 499 |
+
position_ids = MossTTSNanoGPT2Model.build_packed_position_ids(
|
| 500 |
+
attention_mask=attention_mask,
|
| 501 |
+
cu_seqlens=cu_seqlens.to(device=hidden_states.device),
|
| 502 |
+
num_sequences=num_sequences.to(device=hidden_states.device) if num_sequences is not None else None,
|
| 503 |
+
sequence_length=hidden_states.shape[1],
|
| 504 |
+
)
|
| 505 |
+
elif attention_mask is not None:
|
| 506 |
+
position_ids = attention_mask.long().cumsum(dim=-1) - 1
|
| 507 |
+
position_ids = position_ids.masked_fill(~attention_mask, 0)
|
| 508 |
+
position_ids = position_ids[:, -hidden_states.shape[1] :]
|
| 509 |
+
else:
|
| 510 |
+
past_length = 0
|
| 511 |
+
if past_key_values is not None and len(past_key_values) > 0:
|
| 512 |
+
past_length = past_key_values[0][0].shape[1]
|
| 513 |
+
position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device, dtype=torch.long)
|
| 514 |
+
position_ids = position_ids + past_length
|
| 515 |
+
position_ids = position_ids.unsqueeze(0).expand(hidden_states.shape[0], -1)
|
| 516 |
+
|
| 517 |
+
if cu_seqlens is not None and self.attn_implementation == "flash_attention_2":
|
| 518 |
+
packed_metadata = MossTTSNanoGPT2Model.build_packed_metadata(
|
| 519 |
+
hidden_states=hidden_states,
|
| 520 |
+
cu_seqlens=cu_seqlens.to(device=hidden_states.device),
|
| 521 |
+
num_sequences=num_sequences.to(device=hidden_states.device) if num_sequences is not None else None,
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
hidden_states = hidden_states * query_attention_mask.unsqueeze(-1).to(dtype=hidden_states.dtype)
|
| 525 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 526 |
+
|
| 527 |
+
all_hidden_states = () if output_hidden_states else None
|
| 528 |
+
presents = [] if use_cache else None
|
| 529 |
+
for layer_index, decoder_layer in enumerate(self.layers):
|
| 530 |
+
if output_hidden_states:
|
| 531 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 532 |
+
|
| 533 |
+
if self.gradient_checkpointing and self.training:
|
| 534 |
+
if use_cache:
|
| 535 |
+
raise ValueError("use_cache=True is not supported when gradient checkpointing is enabled during training.")
|
| 536 |
+
|
| 537 |
+
def custom_forward(*inputs):
|
| 538 |
+
output, _ = decoder_layer(
|
| 539 |
+
hidden_states=inputs[0],
|
| 540 |
+
attention_mask=inputs[1],
|
| 541 |
+
packed_metadata=packed_metadata,
|
| 542 |
+
layer_past=None,
|
| 543 |
+
use_cache=False,
|
| 544 |
+
position_embeddings=position_embeddings,
|
| 545 |
+
)
|
| 546 |
+
return output
|
| 547 |
+
|
| 548 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
| 549 |
+
custom_forward,
|
| 550 |
+
hidden_states,
|
| 551 |
+
attention_mask,
|
| 552 |
+
use_reentrant=self.gradient_checkpointing_use_reentrant,
|
| 553 |
+
)
|
| 554 |
+
present = None
|
| 555 |
+
else:
|
| 556 |
+
hidden_states, present = decoder_layer(
|
| 557 |
+
hidden_states=hidden_states,
|
| 558 |
+
attention_mask=attention_mask,
|
| 559 |
+
packed_metadata=packed_metadata,
|
| 560 |
+
layer_past=None if past_key_values is None else past_key_values[layer_index],
|
| 561 |
+
use_cache=use_cache,
|
| 562 |
+
position_embeddings=position_embeddings,
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
hidden_states = hidden_states * query_attention_mask.unsqueeze(-1).to(dtype=hidden_states.dtype)
|
| 566 |
+
if presents is not None:
|
| 567 |
+
presents.append(present)
|
| 568 |
+
|
| 569 |
+
hidden_states = self.norm(hidden_states)
|
| 570 |
+
hidden_states = hidden_states * query_attention_mask.unsqueeze(-1).to(dtype=hidden_states.dtype)
|
| 571 |
+
if output_hidden_states:
|
| 572 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 573 |
+
|
| 574 |
+
if not return_dict:
|
| 575 |
+
return (hidden_states, tuple(presents) if presents is not None else None, all_hidden_states, None)
|
| 576 |
+
|
| 577 |
+
return BaseModelOutputWithPast(
|
| 578 |
+
last_hidden_state=hidden_states,
|
| 579 |
+
past_key_values=tuple(presents) if presents is not None else None,
|
| 580 |
+
hidden_states=all_hidden_states,
|
| 581 |
+
attentions=None,
|
| 582 |
+
)
|