""" PersianGPT-20M: Upgraded ~20M-parameter Decoder-Only Transformer built from scratch in PyTorch. Architecture upgrades: - Pre-RMSNorm - Grouped-Query Attention (GQA: 8 Q-heads, 4 KV-heads) - QK-Norm (RMSNorm on Query & Key heads for deep stability) - Rotary Positional Embeddings (RoPE) - SwiGLU Feed-Forward Network - Weight Tying (tok_emb <-> lm_head) Zero pretrained weights. Zero hardcoded responses. """ from __future__ import annotations import json import math from dataclasses import asdict, dataclass from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F @dataclass class ModelConfig: vocab_size: int = 3200 d_model: int = 512 n_heads: int = 8 n_kv_heads: int = 4 n_layers: int = 6 d_ff: int = 1472 max_seq_len: int = 256 dropout: float = 0.08 pad_token_id: int = 0 bos_token_id: int = 1 eos_token_id: int = 2 user_token_id: int = 3 assistant_token_id: int = 4 eot_token_id: int = 5 def to_json(self, path: str) -> None: with open(path, "w", encoding="utf-8") as f: json.dump(asdict(self), f, indent=2, ensure_ascii=False) @classmethod def from_json(cls, path: str) -> "ModelConfig": with open(path, "r", encoding="utf-8") as f: data = json.load(f) return cls(**data) class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x: torch.Tensor) -> torch.Tensor: norm = torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps) return x * norm * self.weight def precompute_rope_cache(seq_len: int, head_dim: int, base: float = 10000.0): theta = 1.0 / (base ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim)) positions = torch.arange(seq_len, dtype=torch.float32) freqs = torch.outer(positions, theta) return torch.cos(freqs), torch.sin(freqs) def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: T = x.size(2) cos = cos[:T].unsqueeze(0).unsqueeze(0) sin = sin[:T].unsqueeze(0).unsqueeze(0) x1 = x[..., 0::2] x2 = x[..., 1::2] out1 = x1 * cos - x2 * sin out2 = x1 * sin + x2 * cos return torch.stack((out1, out2), dim=-1).flatten(-2) class GroupedQueryAttention(nn.Module): def __init__(self, config: ModelConfig): super().__init__() assert config.d_model % config.n_heads == 0 assert config.n_heads % config.n_kv_heads == 0 self.n_heads = config.n_heads self.n_kv_heads = config.n_kv_heads self.n_rep = config.n_heads // config.n_kv_heads self.head_dim = config.d_model // config.n_heads self.wq = nn.Linear(config.d_model, self.n_heads * self.head_dim, bias=False) self.wk = nn.Linear(config.d_model, self.n_kv_heads * self.head_dim, bias=False) self.wv = nn.Linear(config.d_model, self.n_kv_heads * self.head_dim, bias=False) self.wo = nn.Linear(config.d_model, config.d_model, bias=False) # QK-Norm for training stability self.q_norm = RMSNorm(self.head_dim) self.k_norm = RMSNorm(self.head_dim) self.dropout = config.dropout self.resid_drop = nn.Dropout(config.dropout) def forward( self, x: torch.Tensor, rope_cos: torch.Tensor, rope_sin: torch.Tensor, ) -> torch.Tensor: B, T, C = x.shape q = self.wq(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2) k = self.wk(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2) v = self.wv(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2) q = self.q_norm(q) k = self.k_norm(k) q = apply_rope(q, rope_cos, rope_sin) k = apply_rope(k, rope_cos, rope_sin) # Repeat KV heads for GQA if self.n_rep > 1: k = k.repeat_interleave(self.n_rep, dim=1) v = v.repeat_interleave(self.n_rep, dim=1) attn_out = F.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0.0, is_causal=True, ) attn_out = attn_out.transpose(1, 2).contiguous().view(B, T, C) return self.resid_drop(self.wo(attn_out)) class SwiGLU(nn.Module): def __init__(self, config: ModelConfig): super().__init__() self.w_gate = nn.Linear(config.d_model, config.d_ff, bias=False) self.w_up = nn.Linear(config.d_model, config.d_ff, bias=False) self.w_down = nn.Linear(config.d_ff, config.d_model, bias=False) self.drop = nn.Dropout(config.dropout) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.drop(self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))) class TransformerBlock(nn.Module): def __init__(self, config: ModelConfig): super().__init__() self.norm1 = RMSNorm(config.d_model) self.attn = GroupedQueryAttention(config) self.norm2 = RMSNorm(config.d_model) self.ffn = SwiGLU(config) def forward( self, x: torch.Tensor, rope_cos: torch.Tensor, rope_sin: torch.Tensor, ) -> torch.Tensor: x = x + self.attn(self.norm1(x), rope_cos, rope_sin) x = x + self.ffn(self.norm2(x)) return x class PersianMiniGPT(nn.Module): def __init__(self, config: ModelConfig): super().__init__() self.config = config self.tok_emb = nn.Embedding(config.vocab_size, config.d_model) self.emb_drop = nn.Dropout(config.dropout) self.blocks = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)]) self.norm_f = RMSNorm(config.d_model) self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False) self.lm_head.weight = self.tok_emb.weight cos, sin = precompute_rope_cache(config.max_seq_len, config.d_model // config.n_heads) self.register_buffer("rope_cos", cos, persistent=False) self.register_buffer("rope_sin", sin, persistent=False) self.apply(self._init_weights) for name, p in self.named_parameters(): if name.endswith("wo.weight") or name.endswith("w_down.weight"): nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layers)) @staticmethod def _init_weights(module: nn.Module) -> None: 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) def count_parameters(self) -> int: return sum(p.numel() for p in self.parameters() if p.requires_grad) def forward( self, input_ids: torch.Tensor, targets: Optional[torch.Tensor] = None, ): B, T = input_ids.shape assert T <= self.config.max_seq_len, f"Sequence length {T} > max_seq_len {self.config.max_seq_len}" x = self.emb_drop(self.tok_emb(input_ids)) for block in self.blocks: x = block(x, self.rope_cos, self.rope_sin) x = self.norm_f(x) logits = self.lm_head(x) loss = None if targets is not None: loss = F.cross_entropy( logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100, ) return logits, loss @torch.no_grad() def generate( self, input_ids: torch.Tensor, max_new_tokens: int = 128, temperature: float = 0.55, top_k: int = 40, top_p: float = 0.9, repetition_penalty: float = 1.12, stop_token_ids: Optional[list[int]] = None, ) -> torch.Tensor: self.eval() if stop_token_ids is None: stop_token_ids = [self.config.eot_token_id, self.config.eos_token_id] generated = input_ids.clone() prompt_len = generated.size(1) for _ in range(max_new_tokens): ctx = generated[:, -self.config.max_seq_len :] logits, _ = self(ctx) next_logits = logits[:, -1, :] if repetition_penalty != 1.0 and generated.size(1) > prompt_len: recent = generated[0, prompt_len:].tolist() for tok in set(recent): if next_logits[0, tok] > 0: next_logits[0, tok] /= repetition_penalty else: next_logits[0, tok] *= repetition_penalty for forbidden in ( self.config.pad_token_id, self.config.bos_token_id, self.config.user_token_id, self.config.assistant_token_id, ): next_logits[:, forbidden] = -float("inf") if temperature <= 0.0: next_token = torch.argmax(next_logits, dim=-1, keepdim=True) else: next_logits = next_logits / temperature if top_k > 0: v, _ = torch.topk(next_logits, min(top_k, next_logits.size(-1))) next_logits[next_logits < v[:, [-1]]] = -float("inf") if 0.0 < top_p < 1.0: sorted_logits, sorted_indices = torch.sort(next_logits, descending=True) probs = F.softmax(sorted_logits, dim=-1) cumulative_probs = torch.cumsum(probs, dim=-1) sorted_mask = cumulative_probs > top_p sorted_mask[..., 1:] = sorted_mask[..., :-1].clone() sorted_mask[..., 0] = False indices_to_remove = sorted_mask.scatter(1, sorted_indices, sorted_mask) next_logits[indices_to_remove] = -float("inf") probs = F.softmax(next_logits, dim=-1) next_token = torch.multinomial(probs, num_samples=1) generated = torch.cat([generated, next_token], dim=1) if next_token.item() in stop_token_ids: break return generated