fix: merge modular_smallthinker and modeling_smallthinker in case of import error
Browse files- modeling_smallthinker.py +396 -4
modeling_smallthinker.py
CHANGED
|
@@ -1,22 +1,414 @@
|
|
| 1 |
# coding=utf-8
|
| 2 |
-
from typing import List, Optional, Union
|
| 3 |
|
| 4 |
import torch
|
| 5 |
import torch.nn.functional as F
|
| 6 |
from torch import nn
|
| 7 |
|
| 8 |
-
from transformers.cache_utils import HybridCache, StaticCache
|
| 9 |
from transformers.generation import GenerationMixin
|
| 10 |
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 11 |
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 12 |
from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
|
|
|
|
|
|
| 13 |
from transformers.processing_utils import Unpack
|
| 14 |
from transformers.utils import LossKwargs, can_return_tuple, logging
|
|
|
|
| 15 |
from .configuration_smallthinker import SmallThinkerConfig
|
| 16 |
-
from .modular_smallthinker import *
|
| 17 |
|
| 18 |
logger = logging.get_logger(__name__)
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
class SmallThinkerModel(SmallThinkerPreTrainedModel):
|
| 22 |
def __init__(self, config: SmallThinkerConfig):
|
|
@@ -284,4 +676,4 @@ __all__ = [
|
|
| 284 |
"SmallThinkerForCausalLM",
|
| 285 |
"SmallThinkerModel",
|
| 286 |
"SmallThinkerPreTrainedModel"
|
| 287 |
-
]
|
|
|
|
| 1 |
# coding=utf-8
|
| 2 |
+
from typing import List, Optional, Union, Callable, Tuple
|
| 3 |
|
| 4 |
import torch
|
| 5 |
import torch.nn.functional as F
|
| 6 |
from torch import nn
|
| 7 |
|
| 8 |
+
from transformers.cache_utils import Cache, HybridCache, StaticCache
|
| 9 |
from transformers.generation import GenerationMixin
|
| 10 |
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 11 |
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 12 |
from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
| 13 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 14 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 15 |
from transformers.processing_utils import Unpack
|
| 16 |
from transformers.utils import LossKwargs, can_return_tuple, logging
|
| 17 |
+
|
| 18 |
from .configuration_smallthinker import SmallThinkerConfig
|
|
|
|
| 19 |
|
| 20 |
logger = logging.get_logger(__name__)
|
| 21 |
|
| 22 |
+
@torch.jit.script
|
| 23 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 24 |
+
"""
|
| 25 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 26 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 27 |
+
"""
|
| 28 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 29 |
+
if n_rep == 1:
|
| 30 |
+
return hidden_states
|
| 31 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 32 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def rotate_half(x):
|
| 36 |
+
"""Rotates half the hidden dims of the input."""
|
| 37 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 38 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 39 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 43 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
q (`torch.Tensor`): The query tensor.
|
| 47 |
+
k (`torch.Tensor`): The key tensor.
|
| 48 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 49 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 50 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 51 |
+
Deprecated and unused.
|
| 52 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 53 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 54 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 55 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 56 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 57 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 58 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 59 |
+
Returns:
|
| 60 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 61 |
+
"""
|
| 62 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 63 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 64 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 65 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 66 |
+
return q_embed, k_embed
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def check_is_swa_layer(config, layer_idx):
|
| 70 |
+
"""
|
| 71 |
+
Check if the current layer is a sliding window attention layer.
|
| 72 |
+
"""
|
| 73 |
+
if not hasattr(config, "sliding_window_layout"):
|
| 74 |
+
return False
|
| 75 |
+
elif config.sliding_window_layout is None:
|
| 76 |
+
return False
|
| 77 |
+
else:
|
| 78 |
+
return config.sliding_window_layout[layer_idx] == 1
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class SmallThinkerRMSNorm(nn.Module):
|
| 82 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 83 |
+
"""
|
| 84 |
+
SmallThinkerRMSNorm is equivalent to T5LayerNorm
|
| 85 |
+
"""
|
| 86 |
+
super().__init__()
|
| 87 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 88 |
+
self.variance_epsilon = eps
|
| 89 |
+
|
| 90 |
+
def forward(self, hidden_states):
|
| 91 |
+
input_dtype = hidden_states.dtype
|
| 92 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 93 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 94 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 95 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 96 |
+
|
| 97 |
+
def extra_repr(self):
|
| 98 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class SmallThinkerRotaryEmbedding(nn.Module):
|
| 102 |
+
def __init__(self, config: SmallThinkerConfig, device=None):
|
| 103 |
+
super().__init__()
|
| 104 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
| 105 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 106 |
+
else:
|
| 107 |
+
self.rope_type = "default"
|
| 108 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 109 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 110 |
+
|
| 111 |
+
self.config = config
|
| 112 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 113 |
+
|
| 114 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 115 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 116 |
+
self.original_inv_freq = self.inv_freq
|
| 117 |
+
|
| 118 |
+
@torch.no_grad()
|
| 119 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 120 |
+
def forward(self, x, position_ids):
|
| 121 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 122 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 123 |
+
|
| 124 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 125 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 126 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 127 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 128 |
+
cos = emb.cos() * self.attention_scaling
|
| 129 |
+
sin = emb.sin() * self.attention_scaling
|
| 130 |
+
|
| 131 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class SmallThinkerExpert(nn.Module):
|
| 135 |
+
def __init__(self, config: SmallThinkerConfig):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.hidden_dim = config.hidden_size
|
| 138 |
+
self.ffn_dim = config.moe_ffn_hidden_size
|
| 139 |
+
|
| 140 |
+
self.up = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
|
| 141 |
+
self.gate = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
|
| 142 |
+
self.down = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
|
| 143 |
+
|
| 144 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 145 |
+
current_hidden_states = self.up(hidden_states) * F.relu(self.gate(hidden_states))
|
| 146 |
+
batch_size, _ = current_hidden_states.shape
|
| 147 |
+
current_hidden_states = current_hidden_states.view(batch_size, -1)
|
| 148 |
+
current_hidden_states = self.down(current_hidden_states)
|
| 149 |
+
return current_hidden_states
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class SmallThinkerMoeBlock(nn.Module):
|
| 153 |
+
def __init__(self, config: SmallThinkerConfig):
|
| 154 |
+
super().__init__()
|
| 155 |
+
self.hidden_dim = config.hidden_size
|
| 156 |
+
self.num_primary_experts = config.moe_num_primary_experts
|
| 157 |
+
self.moe_primary_router_apply_softmax = config.moe_primary_router_apply_softmax
|
| 158 |
+
self.num_active_primary_experts = config.moe_num_active_primary_experts
|
| 159 |
+
self.primary_router = nn.Linear(self.hidden_dim, self.num_primary_experts, bias=False)
|
| 160 |
+
self.experts = nn.ModuleList([SmallThinkerExpert(config) for _ in range(self.num_primary_experts)])
|
| 161 |
+
|
| 162 |
+
def forward(self, router_input: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 163 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
| 164 |
+
# Flatten the tokens into (bs * sl, hidden_dim)
|
| 165 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
| 166 |
+
router_input = router_input.view(-1, hidden_dim)
|
| 167 |
+
# Primary router logits: (bs * sl, n_experts)
|
| 168 |
+
router_logits = self.primary_router(router_input)
|
| 169 |
+
|
| 170 |
+
router_logits, selected_experts = torch.topk(router_logits, self.num_active_primary_experts, dim=-1)
|
| 171 |
+
|
| 172 |
+
if self.moe_primary_router_apply_softmax:
|
| 173 |
+
routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
|
| 174 |
+
else:
|
| 175 |
+
routing_weights = F.sigmoid(router_logits)
|
| 176 |
+
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
|
| 177 |
+
|
| 178 |
+
routing_weights = routing_weights.to(hidden_states.dtype)
|
| 179 |
+
|
| 180 |
+
# Prepare the final tensor
|
| 181 |
+
final_hidden_states = torch.zeros(
|
| 182 |
+
(batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
# One hot encode the selected experts to create an expert mask
|
| 186 |
+
# this will be used to easily index which expert is going to be sollicitated
|
| 187 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_primary_experts).permute(2, 1, 0)
|
| 188 |
+
expert_hitted = (expert_mask.sum(dim=(-1, -2)) > 0).nonzero(as_tuple=True)[0].tolist()
|
| 189 |
+
|
| 190 |
+
for expert_idx in expert_hitted:
|
| 191 |
+
expert_layer = self.experts[expert_idx]
|
| 192 |
+
idx, top_x = torch.where(expert_mask[expert_idx])
|
| 193 |
+
# Index the correct hidden states and compute the expert hidden state for
|
| 194 |
+
# the current expert. We need to make sure to multiply the output hidden
|
| 195 |
+
# states by `routing_weights` on the corresponding tokens (top-1 and top-2)
|
| 196 |
+
current_state = hidden_states[top_x].reshape(-1, hidden_dim)
|
| 197 |
+
current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
|
| 198 |
+
|
| 199 |
+
# However `index_add_` only support torch tensors for indexing so we'll use the `top_x` tensor here.
|
| 200 |
+
final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
|
| 201 |
+
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
| 202 |
+
return final_hidden_states, router_logits
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def eager_attention_forward(
|
| 206 |
+
module: nn.Module,
|
| 207 |
+
query: torch.Tensor,
|
| 208 |
+
key: torch.Tensor,
|
| 209 |
+
value: torch.Tensor,
|
| 210 |
+
attention_mask: Optional[torch.Tensor],
|
| 211 |
+
scaling: float,
|
| 212 |
+
dropout: float = 0.0,
|
| 213 |
+
**kwargs,
|
| 214 |
+
):
|
| 215 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 216 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 217 |
+
|
| 218 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 219 |
+
if attention_mask is not None:
|
| 220 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 221 |
+
attn_weights = attn_weights + causal_mask
|
| 222 |
+
|
| 223 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 224 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 225 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 226 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 227 |
+
|
| 228 |
+
return attn_output, attn_weights
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class SmallThinkerAttention(nn.Module):
|
| 232 |
+
def __init__(self, config: SmallThinkerConfig, layer_idx: int):
|
| 233 |
+
super().__init__()
|
| 234 |
+
self.config = config
|
| 235 |
+
self.layer_idx = layer_idx
|
| 236 |
+
self.head_dim = config.head_dim
|
| 237 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 238 |
+
self.scaling = self.head_dim**-0.5
|
| 239 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
|
| 240 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
|
| 241 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
|
| 242 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 243 |
+
self.sliding_window = config.sliding_window_size if config.sliding_window_layout[layer_idx] else None
|
| 244 |
+
|
| 245 |
+
def forward(
|
| 246 |
+
self,
|
| 247 |
+
hidden_states: torch.Tensor,
|
| 248 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 249 |
+
attention_mask: Optional[torch.Tensor],
|
| 250 |
+
past_key_value: Optional[Cache] = None,
|
| 251 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 252 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 253 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 254 |
+
|
| 255 |
+
input_shape = hidden_states.shape[:-1]
|
| 256 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 257 |
+
|
| 258 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 259 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 260 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 261 |
+
|
| 262 |
+
if position_embeddings:
|
| 263 |
+
cos, sin = position_embeddings
|
| 264 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 265 |
+
else:
|
| 266 |
+
cos, sin = None, None
|
| 267 |
+
|
| 268 |
+
if past_key_value is not None:
|
| 269 |
+
cache_kwargs = {
|
| 270 |
+
"sin": sin,
|
| 271 |
+
"cos": cos,
|
| 272 |
+
"cache_position": cache_position,
|
| 273 |
+
"sliding_window": self.sliding_window,
|
| 274 |
+
}
|
| 275 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 276 |
+
|
| 277 |
+
attention_interface: Callable = eager_attention_forward
|
| 278 |
+
if self.config._attn_implementation != "eager":
|
| 279 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
| 280 |
+
logger.warning_once(
|
| 281 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
| 282 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 283 |
+
)
|
| 284 |
+
else:
|
| 285 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 286 |
+
|
| 287 |
+
attn_output, attn_weights = attention_interface(
|
| 288 |
+
self,
|
| 289 |
+
query_states,
|
| 290 |
+
key_states,
|
| 291 |
+
value_states,
|
| 292 |
+
attention_mask,
|
| 293 |
+
dropout=0.0,
|
| 294 |
+
scaling=self.scaling,
|
| 295 |
+
sliding_window=self.sliding_window,
|
| 296 |
+
**kwargs,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 300 |
+
attn_output = self.o_proj(attn_output)
|
| 301 |
+
return attn_output, attn_weights
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class SmallThinkerDecoderLayer(nn.Module):
|
| 305 |
+
def __init__(self, config: SmallThinkerConfig, layer_idx: int):
|
| 306 |
+
super().__init__()
|
| 307 |
+
self.hidden_size = config.hidden_size
|
| 308 |
+
self.self_attn = SmallThinkerAttention(config, layer_idx)
|
| 309 |
+
self.block_sparse_moe = SmallThinkerMoeBlock(config)
|
| 310 |
+
self.input_layernorm = SmallThinkerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 311 |
+
self.post_attention_layernorm = SmallThinkerRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 312 |
+
self.is_swa = check_is_swa_layer(config, layer_idx)
|
| 313 |
+
|
| 314 |
+
if self.is_swa and config._attn_implementation == "sdpa":
|
| 315 |
+
logger.warning_once(
|
| 316 |
+
f"Sliding Window Attention is enabled but not optimized for `{config._attn_implementation}`; "
|
| 317 |
+
"unexpected results may be encountered."
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
def forward(
|
| 321 |
+
self,
|
| 322 |
+
hidden_states: torch.Tensor,
|
| 323 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 324 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 325 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 326 |
+
output_attentions: Optional[bool] = False,
|
| 327 |
+
output_router_logits: Optional[bool] = False,
|
| 328 |
+
use_cache: Optional[bool] = False,
|
| 329 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 330 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 331 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 332 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 333 |
+
"""
|
| 334 |
+
Args:
|
| 335 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 336 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 337 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
| 338 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 339 |
+
output_attentions (`bool`, *optional*):
|
| 340 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 341 |
+
returned tensors for more detail.
|
| 342 |
+
output_router_logits (`bool`, *optional*):
|
| 343 |
+
Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
|
| 344 |
+
should not be returned during inference.
|
| 345 |
+
use_cache (`bool`, *optional*):
|
| 346 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 347 |
+
(see `past_key_values`).
|
| 348 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 349 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 350 |
+
kwargs (`dict`, *optional*):
|
| 351 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 352 |
+
into the model
|
| 353 |
+
"""
|
| 354 |
+
residual = hidden_states
|
| 355 |
+
router_input = hidden_states
|
| 356 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 357 |
+
# Self Attention
|
| 358 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 359 |
+
hidden_states=hidden_states,
|
| 360 |
+
position_embeddings=position_embeddings,
|
| 361 |
+
attention_mask=attention_mask,
|
| 362 |
+
position_ids=position_ids,
|
| 363 |
+
past_key_value=past_key_value,
|
| 364 |
+
output_attentions=output_attentions,
|
| 365 |
+
use_cache=use_cache,
|
| 366 |
+
cache_position=cache_position,
|
| 367 |
+
**kwargs,
|
| 368 |
+
)
|
| 369 |
+
hidden_states = residual + hidden_states
|
| 370 |
+
|
| 371 |
+
# Fully Connected
|
| 372 |
+
residual = hidden_states
|
| 373 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 374 |
+
hidden_states, router_logits = self.block_sparse_moe(router_input, hidden_states)
|
| 375 |
+
hidden_states = residual + hidden_states
|
| 376 |
+
|
| 377 |
+
outputs = (hidden_states,)
|
| 378 |
+
if output_attentions:
|
| 379 |
+
outputs += (self_attn_weights,)
|
| 380 |
+
if output_router_logits:
|
| 381 |
+
outputs += (router_logits,)
|
| 382 |
+
return outputs
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
class SmallThinkerPreTrainedModel(PreTrainedModel):
|
| 386 |
+
config_class = SmallThinkerConfig
|
| 387 |
+
base_model_prefix = "model"
|
| 388 |
+
supports_gradient_checkpointing = False
|
| 389 |
+
_no_split_modules = ["SmallThinkerDecoderLayer"]
|
| 390 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 391 |
+
_supports_flash_attn_2 = True
|
| 392 |
+
_supports_sdpa = True
|
| 393 |
+
_supports_flex_attn = False
|
| 394 |
+
_supports_cache_class = True
|
| 395 |
+
_supports_quantized_cache = True
|
| 396 |
+
_supports_static_cache = False
|
| 397 |
+
_supports_attention_backend = True
|
| 398 |
+
|
| 399 |
+
def _init_weights(self, module):
|
| 400 |
+
std = self.config.initializer_range
|
| 401 |
+
if isinstance(module, nn.Linear):
|
| 402 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 403 |
+
if module.bias is not None:
|
| 404 |
+
module.bias.data.zero_()
|
| 405 |
+
elif isinstance(module, nn.Embedding):
|
| 406 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 407 |
+
if module.padding_idx is not None:
|
| 408 |
+
module.weight.data[module.padding_idx].zero_()
|
| 409 |
+
elif isinstance(module, SmallThinkerRMSNorm):
|
| 410 |
+
module.weight.data.fill_(1.0)
|
| 411 |
+
|
| 412 |
|
| 413 |
class SmallThinkerModel(SmallThinkerPreTrainedModel):
|
| 414 |
def __init__(self, config: SmallThinkerConfig):
|
|
|
|
| 676 |
"SmallThinkerForCausalLM",
|
| 677 |
"SmallThinkerModel",
|
| 678 |
"SmallThinkerPreTrainedModel"
|
| 679 |
+
]
|