Download modeling_spam.py from Pannuru/Spam-Detection-SLM: direct link, hf CLI and curl.
- Browser
- Download file 5.06 kB
-
https://huggingface.co/Pannuru/Spam-Detection-SLM/resolve/main/modeling_spam.py
- Command line
-
hf download hf://Pannuru/Spam-Detection-SLM/modeling_spam.py
-
curl -L -o modeling_spam.py https://huggingface.co/Pannuru/Spam-Detection-SLM/resolve/main/modeling_spam.py
5.06 kB
| import math | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| def compute_rope_params(head_dim, context_length, theta_base=10000): | |
| inv_freq = 1.0 / ( | |
| theta_base ** ( | |
| torch.arange(0, head_dim, 2).float() / head_dim | |
| ) | |
| ) | |
| positions = torch.arange(context_length) | |
| angles = torch.outer(positions, inv_freq) | |
| return torch.cos(angles), torch.sin(angles) | |
| def apply_rope(x, cos, sin): | |
| half = x.shape[-1] // 2 | |
| x1 = x[..., :half] | |
| x2 = x[..., half:] | |
| rotated = torch.cat((-x2, x1), dim=-1) | |
| cos = torch.cat((cos, cos), dim=-1) | |
| sin = torch.cat((sin, sin), dim=-1) | |
| return x * cos + rotated * sin | |
| class RMSNorm(nn.Module): | |
| def __init__(self, dim, eps=1e-6): | |
| super().__init__() | |
| self.eps = eps | |
| self.scale = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x): | |
| mean_square = x.pow(2).mean(dim=-1, keepdim=True) | |
| x = x * torch.rsqrt(mean_square + self.eps) | |
| return x * self.scale | |
| class GroupedQueryAttention(nn.Module): | |
| def __init__(self, d_model, num_heads, num_kv_groups, max_length): | |
| super().__init__() | |
| self.num_heads = num_heads | |
| self.num_kv_groups = num_kv_groups | |
| self.head_dim = d_model // num_heads | |
| self.q_proj = nn.Linear(d_model, d_model) | |
| self.k_proj = nn.Linear(d_model, num_kv_groups * self.head_dim) | |
| self.v_proj = nn.Linear(d_model, num_kv_groups * self.head_dim) | |
| self.out_proj = nn.Linear(d_model, d_model) | |
| cos, sin = compute_rope_params(self.head_dim, max_length) | |
| self.register_buffer("cos", cos, persistent=False) | |
| self.register_buffer("sin", sin, persistent=False) | |
| def forward(self, x, attention_mask): | |
| batch_size, seq_length, d_model = x.shape | |
| q = self.q_proj(x).view( | |
| batch_size, seq_length, self.num_heads, self.head_dim | |
| ) | |
| k = self.k_proj(x).view( | |
| batch_size, seq_length, self.num_kv_groups, self.head_dim | |
| ) | |
| v = self.v_proj(x).view( | |
| batch_size, seq_length, self.num_kv_groups, self.head_dim | |
| ) | |
| q = q.transpose(1, 2) | |
| k = k.transpose(1, 2) | |
| v = v.transpose(1, 2) | |
| q = apply_rope(q, self.cos[:seq_length], self.sin[:seq_length]) | |
| k = apply_rope(k, self.cos[:seq_length], self.sin[:seq_length]) | |
| groups = self.num_heads // self.num_kv_groups | |
| k = k.repeat_interleave(groups, dim=1) | |
| v = v.repeat_interleave(groups, dim=1) | |
| scores = torch.matmul(q, k.transpose(-2, -1)) | |
| scores = scores / math.sqrt(self.head_dim) | |
| mask = attention_mask[:, None, None, :] == 0 | |
| scores = scores.masked_fill( | |
| mask, torch.finfo(scores.dtype).min | |
| ) | |
| weights = torch.softmax(scores, dim=-1) | |
| context = torch.matmul(weights, v) | |
| context = context.transpose(1, 2).contiguous() | |
| context = context.view(batch_size, seq_length, d_model) | |
| return self.out_proj(context) | |
| class SwiGLU(nn.Module): | |
| def __init__(self, d_model, d_ff): | |
| super().__init__() | |
| self.gate_proj = nn.Linear(d_model, d_ff) | |
| self.up_proj = nn.Linear(d_model, d_ff) | |
| self.down_proj = nn.Linear(d_ff, d_model) | |
| def forward(self, x): | |
| gate = F.silu(self.gate_proj(x)) | |
| value = self.up_proj(x) | |
| return self.down_proj(gate * value) | |
| class TransformerBlock(nn.Module): | |
| def __init__(self, d_model, num_heads, num_kv_groups, d_ff, max_length): | |
| super().__init__() | |
| self.norm1 = RMSNorm(d_model) | |
| self.attention = GroupedQueryAttention( | |
| d_model, num_heads, num_kv_groups, max_length | |
| ) | |
| self.norm2 = RMSNorm(d_model) | |
| self.feed_forward = SwiGLU(d_model, d_ff) | |
| def forward(self, x, attention_mask): | |
| x = x + self.attention(self.norm1(x), attention_mask) | |
| x = x + self.feed_forward(self.norm2(x)) | |
| return x | |
| class SpamTransformerClassifier(nn.Module): | |
| def __init__(self, config): | |
| super().__init__() | |
| self.token_embedding = nn.Embedding( | |
| config["vocab_size"], config["d_model"] | |
| ) | |
| self.transformer_blocks = nn.ModuleList([ | |
| TransformerBlock( | |
| config["d_model"], | |
| config["num_heads"], | |
| config["num_kv_groups"], | |
| config["d_ff"], | |
| config["max_length"] | |
| ) | |
| for _ in range(config["num_layers"]) | |
| ]) | |
| self.final_norm = RMSNorm(config["d_model"]) | |
| self.classifier = nn.Linear( | |
| config["d_model"], config["num_classes"] | |
| ) | |
| def forward(self, input_ids, attention_mask): | |
| x = self.token_embedding(input_ids) | |
| for block in self.transformer_blocks: | |
| x = block(x, attention_mask) | |
| x = self.final_norm(x) | |
| mask = attention_mask.unsqueeze(-1).to(x.dtype) | |
| x = (x * mask).sum(dim=1) | |
| x = x / mask.sum(dim=1).clamp(min=1) | |
| return self.classifier(x) | |