Download modeling_sovythos.py from sovythos/Sovythos-303M-Base: direct link, hf CLI and curl.
- Browser
- Download file 6.93 kB
-
https://huggingface.co/sovythos/Sovythos-303M-Base/resolve/main/modeling_sovythos.py
- Command line
-
hf download hf://sovythos/Sovythos-303M-Base/modeling_sovythos.py
-
curl -L -o modeling_sovythos.py https://huggingface.co/sovythos/Sovythos-303M-Base/resolve/main/modeling_sovythos.py
6.93 kB
| import math | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from transformers import PreTrainedModel | |
| from transformers.modeling_outputs import CausalLMOutputWithPast | |
| from .configuration_sovythos import SovythosConfig | |
| class RMSNorm(nn.Module): | |
| def __init__(self, dim, eps=1e-06): | |
| super().__init__() | |
| self.eps = eps | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x): | |
| dtype = x.dtype | |
| x = x.float() | |
| rms = x.pow(2).mean(-1, keepdim=True) | |
| x = x * torch.rsqrt(rms + self.eps) | |
| return self.weight * x.to(dtype) | |
| def precompute_rope(head_dim, max_seq_len, theta, device, dtype=torch.float32): | |
| inv_freq = 1.0 / theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim) | |
| t = torch.arange(max_seq_len, device=device).float() | |
| freqs = torch.outer(t, inv_freq) | |
| emb = torch.cat((freqs, freqs), dim=-1) | |
| return emb.cos().to(dtype), emb.sin().to(dtype) | |
| def rotate_half(x): | |
| x1, x2 = x.chunk(2, dim=-1) | |
| return torch.cat((-x2, x1), dim=-1) | |
| def apply_rope(x, cos, sin, offset=0): | |
| T = x.shape[-2] | |
| cos = cos[offset:offset + T][None, None, :, :] | |
| sin = sin[offset:offset + T][None, None, :, :] | |
| return x * cos + rotate_half(x) * sin | |
| def repeat_kv(x, n_rep): | |
| if n_rep == 1: | |
| return x | |
| B, Hkv, T, D = x.shape | |
| return x[:, :, None, :, :].expand(B, Hkv, n_rep, T, D).reshape(B, Hkv * n_rep, T, D) | |
| class Attention(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.n_heads = cfg.n_heads | |
| self.n_kv_heads = cfg.n_kv_heads | |
| self.n_rep = self.n_heads // self.n_kv_heads | |
| self.head_dim = cfg.dim // cfg.n_heads | |
| self.dropout = cfg.dropout | |
| self.q_proj = nn.Linear(cfg.dim, cfg.n_heads * self.head_dim, bias=False) | |
| self.k_proj = nn.Linear(cfg.dim, cfg.n_kv_heads * self.head_dim, bias=False) | |
| self.v_proj = nn.Linear(cfg.dim, cfg.n_kv_heads * self.head_dim, bias=False) | |
| self.o_proj = nn.Linear(cfg.n_heads * self.head_dim, cfg.dim, bias=False) | |
| self.q_norm = RMSNorm(self.head_dim, cfg.norm_eps) | |
| self.k_norm = RMSNorm(self.head_dim, cfg.norm_eps) | |
| def forward(self, x, cos, sin): | |
| B, T, C = x.shape | |
| q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2) | |
| k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2) | |
| v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2) | |
| q, k = self.q_norm(q), self.k_norm(k) | |
| q = apply_rope(q, cos, sin) | |
| k = apply_rope(k, cos, sin) | |
| k = repeat_kv(k, self.n_rep) | |
| v = repeat_kv(v, self.n_rep) | |
| out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=self.dropout if self.training else 0.0) | |
| out = out.transpose(1, 2).contiguous().view(B, T, -1) | |
| return self.o_proj(out) | |
| class FeedForward(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| hidden = int(2 * (4 * cfg.dim) / 3) | |
| if cfg.ffn_dim_multiplier is not None: | |
| hidden = int(cfg.ffn_dim_multiplier * hidden) | |
| hidden = cfg.ffn_multiple_of * ((hidden + cfg.ffn_multiple_of - 1) // cfg.ffn_multiple_of) | |
| self.gate_proj = nn.Linear(cfg.dim, hidden, bias=False) | |
| self.up_proj = nn.Linear(cfg.dim, hidden, bias=False) | |
| self.down_proj = nn.Linear(hidden, cfg.dim, bias=False) | |
| def forward(self, x): | |
| return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x)) | |
| class DecoderBlock(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.input_layernorm = RMSNorm(cfg.dim, cfg.norm_eps) | |
| self.self_attn = Attention(cfg) | |
| self.post_attention_layernorm = RMSNorm(cfg.dim, cfg.norm_eps) | |
| self.mlp = FeedForward(cfg) | |
| def forward(self, x, cos, sin): | |
| x = x + self.self_attn(self.input_layernorm(x), cos, sin) | |
| x = x + self.mlp(self.post_attention_layernorm(x)) | |
| return x | |
| class SovythosPreTrainedModel(PreTrainedModel): | |
| config_class = SovythosConfig | |
| base_model_prefix = "model" | |
| supports_gradient_checkpointing = True | |
| def _init_weights(self, module): | |
| if isinstance(module, nn.Linear): | |
| nn.init.normal_(module.weight, mean=0.0, std=0.02) | |
| if module.bias is not None: | |
| nn.init.zeros_(module.bias) | |
| elif isinstance(module, nn.Embedding): | |
| nn.init.normal_(module.weight, mean=0.0, std=0.02) | |
| class SovythosForCausalLM(SovythosPreTrainedModel): | |
| def __init__(self, config): | |
| super().__init__(config) | |
| self.embed_tokens = nn.Embedding(config.vocab_size, config.dim) | |
| self.layers = nn.ModuleList([DecoderBlock(config) for _ in range(config.n_layers)]) | |
| self.norm = RMSNorm(config.dim, config.norm_eps) | |
| self.lm_head = nn.Linear(config.dim, config.vocab_size, bias=False) | |
| if config.tie_embeddings: | |
| self.lm_head.weight = self.embed_tokens.weight | |
| self.head_dim = config.dim // config.n_heads | |
| self._rope_cache = {} | |
| self.post_init() | |
| def get_input_embeddings(self): | |
| return self.embed_tokens | |
| def set_input_embeddings(self, value): | |
| self.embed_tokens = value | |
| def get_output_embeddings(self): | |
| return self.lm_head | |
| def _rope_for(self, device, dtype): | |
| # ملاحظة: بنحسب rope live بدل ما نعتمد على register_buffer، لأن | |
| # transformers بيحمل الموديل عادةً عبر meta-device (low_cpu_mem_usage) | |
| # وأي buffer معمول persistent=False ومش موجود في checkpoint بيفضل | |
| # ذاكرة غير مهيأة (garbage) بدل القيم الحقيقية بعد النقل من meta لـ real. | |
| key = str(device) | |
| if key not in self._rope_cache: | |
| cos, sin = precompute_rope(self.head_dim, self.config.max_seq_len, self.config.rope_theta, device=device) | |
| self._rope_cache[key] = (cos, sin) | |
| return self._rope_cache[key] | |
| def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs): | |
| cos, sin = self._rope_for(input_ids.device, torch.float32) | |
| h = self.embed_tokens(input_ids) | |
| for layer in self.layers: | |
| h = layer(h, cos, sin) | |
| h = self.norm(h) | |
| logits = self.lm_head(h) | |
| loss = None | |
| if labels is not None: | |
| shift_logits = logits[:, :-1, :].contiguous() | |
| shift_labels = labels[:, 1:].contiguous() | |
| loss = F.cross_entropy( | |
| shift_logits.view(-1, shift_logits.size(-1)), | |
| shift_labels.view(-1), | |
| ignore_index=-100, | |
| ) | |
| return CausalLMOutputWithPast(loss=loss, logits=logits) | |
| def prepare_inputs_for_generation(self, input_ids, **kwargs): | |
| return {"input_ids": input_ids} |