Download model.py from Raqia32/sac-1: direct link, hf CLI and curl.
- Browser
- Download file 17.5 kB
-
https://huggingface.co/Raqia32/sac-1/resolve/main/model.py
- Command line
-
hf download hf://Raqia32/sac-1/model.py
-
curl -L -o model.py https://huggingface.co/Raqia32/sac-1/resolve/main/model.py
17.5 kB
| """ | |
| Mini MoE (Mixture of Experts) Language Model - Construido do zero. | |
| Arquitetura: | |
| - Transformer Decoder com Causal Attention | |
| - Camadas alternadas entre Dense FFN e MoE FFN | |
| - 8 experts, top-2 routing por token | |
| - ~5M parametros totais | |
| """ | |
| import math | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from config import ModelConfig | |
| # --------------------------------------------------------------------------- | |
| # Componentes basicos | |
| # --------------------------------------------------------------------------- | |
| class RMSNorm(nn.Module): | |
| """Root Mean Square Layer Normalization (mais eficiente que LayerNorm).""" | |
| def __init__(self, d_model: int, eps: float = 1e-6): | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.ones(d_model)) | |
| self.eps = eps | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| rms = torch.sqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + self.eps) | |
| return x / rms * self.weight | |
| class RotaryPositionalEmbedding(nn.Module): | |
| """RoPE - Rotary Position Embedding.""" | |
| def __init__(self, d_head: int, max_seq_len: int = 512): | |
| super().__init__() | |
| inv_freq = 1.0 / (10000 ** (torch.arange(0, d_head, 2).float() / d_head)) | |
| self.register_buffer("inv_freq", inv_freq) | |
| self._build_cache(max_seq_len) | |
| def _build_cache(self, seq_len: int): | |
| t = torch.arange(seq_len, dtype=self.inv_freq.dtype) | |
| freqs = torch.outer(t, self.inv_freq) | |
| emb = torch.cat([freqs, freqs], dim=-1) | |
| self.register_buffer("cos_cache", emb.cos(), persistent=False) | |
| self.register_buffer("sin_cache", emb.sin(), persistent=False) | |
| def forward(self, x: torch.Tensor, seq_len: int): | |
| if seq_len > self.cos_cache.size(0): | |
| self._build_cache(seq_len) | |
| return ( | |
| self.cos_cache[:seq_len].to(x.device), | |
| self.sin_cache[:seq_len].to(x.device), | |
| ) | |
| def rotate_half(x: torch.Tensor) -> torch.Tensor: | |
| x1, x2 = x.chunk(2, dim=-1) | |
| return torch.cat([-x2, x1], dim=-1) | |
| def apply_rotary_emb(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor): | |
| # cos/sin shape: (seq_len, d_head) | |
| cos = cos.unsqueeze(0).unsqueeze(0) # (1, 1, seq_len, d_head) | |
| sin = sin.unsqueeze(0).unsqueeze(0) | |
| q_rot = q * cos + rotate_half(q) * sin | |
| k_rot = k * cos + rotate_half(k) * sin | |
| return q_rot, k_rot | |
| # --------------------------------------------------------------------------- | |
| # Attention | |
| # --------------------------------------------------------------------------- | |
| class CausalSelfAttention(nn.Module): | |
| """Multi-Head Causal Self-Attention com RoPE.""" | |
| def __init__(self, config: ModelConfig): | |
| super().__init__() | |
| self.n_heads = config.n_heads | |
| self.d_head = config.d_head | |
| self.d_model = config.d_model | |
| self.q_proj = nn.Linear(config.d_model, config.d_model, bias=False) | |
| self.k_proj = nn.Linear(config.d_model, config.d_model, bias=False) | |
| self.v_proj = nn.Linear(config.d_model, config.d_model, bias=False) | |
| self.o_proj = nn.Linear(config.d_model, config.d_model, bias=False) | |
| self.rope = RotaryPositionalEmbedding(config.d_head, config.max_seq_len) | |
| self.attn_dropout = nn.Dropout(config.dropout) | |
| self.resid_dropout = nn.Dropout(config.dropout) | |
| def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor: | |
| B, T, C = x.shape | |
| q = self.q_proj(x).view(B, T, self.n_heads, self.d_head).transpose(1, 2) | |
| k = self.k_proj(x).view(B, T, self.n_heads, self.d_head).transpose(1, 2) | |
| v = self.v_proj(x).view(B, T, self.n_heads, self.d_head).transpose(1, 2) | |
| cos, sin = self.rope(q, T) | |
| q, k = apply_rotary_emb(q, k, cos, sin) | |
| # Scaled dot-product attention | |
| scale = math.sqrt(self.d_head) | |
| attn = (q @ k.transpose(-2, -1)) / scale | |
| # Mascara causal | |
| causal_mask = torch.triu( | |
| torch.ones(T, T, device=x.device, dtype=torch.bool), diagonal=1 | |
| ) | |
| attn = attn.masked_fill(causal_mask.unsqueeze(0).unsqueeze(0), float("-inf")) | |
| if mask is not None: | |
| attn = attn.masked_fill(mask.unsqueeze(1).unsqueeze(2) == 0, float("-inf")) | |
| attn = F.softmax(attn, dim=-1) | |
| attn = self.attn_dropout(attn) | |
| out = (attn @ v).transpose(1, 2).contiguous().view(B, T, C) | |
| return self.resid_dropout(self.o_proj(out)) | |
| # --------------------------------------------------------------------------- | |
| # Feed-Forward Networks (Dense e Expert) | |
| # --------------------------------------------------------------------------- | |
| class DenseFFN(nn.Module): | |
| """Feed-forward padrao com SwiGLU activation.""" | |
| def __init__(self, d_model: int, d_ff: int, dropout: float = 0.1): | |
| super().__init__() | |
| self.w1 = nn.Linear(d_model, d_ff, bias=False) | |
| self.w2 = nn.Linear(d_ff, d_model, bias=False) | |
| self.w3 = nn.Linear(d_model, d_ff, bias=False) # gate | |
| self.dropout = nn.Dropout(dropout) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| # SwiGLU: (swish(xW1) * xW3) W2 | |
| return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x))) | |
| class Expert(nn.Module): | |
| """Um expert individual - e basicamente um FFN.""" | |
| def __init__(self, d_model: int, d_ff: int, dropout: float = 0.05): | |
| super().__init__() | |
| self.ffn = DenseFFN(d_model, d_ff, dropout) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| return self.ffn(x) | |
| # --------------------------------------------------------------------------- | |
| # Mixture of Experts Layer | |
| # --------------------------------------------------------------------------- | |
| class MoELayer(nn.Module): | |
| """ | |
| Mixture of Experts com top-k routing. | |
| Router aprende a distribuir cada token para os top-k experts. | |
| Inclui load balancing loss para evitar que todos os tokens | |
| caiam no mesmo expert. | |
| """ | |
| def __init__(self, config: ModelConfig): | |
| super().__init__() | |
| self.n_experts = config.n_experts | |
| self.top_k = config.top_k | |
| self.d_model = config.d_model | |
| # Router: projeta cada token para scores sobre os experts | |
| self.router = nn.Linear(config.d_model, config.n_experts, bias=False) | |
| # Os experts | |
| self.experts = nn.ModuleList([ | |
| Expert(config.d_model, config.d_ff, config.expert_dropout) | |
| for _ in range(config.n_experts) | |
| ]) | |
| # Para armazenar o load balancing loss | |
| self.aux_loss = 0.0 | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| B, T, C = x.shape | |
| x_flat = x.view(-1, C) # (B*T, C) | |
| N = x_flat.size(0) | |
| # Router logits | |
| router_logits = self.router(x_flat) # (N, n_experts) | |
| router_probs = F.softmax(router_logits, dim=-1) | |
| # Top-k selection | |
| top_k_probs, top_k_indices = torch.topk(router_probs, self.top_k, dim=-1) | |
| # Normaliza probabilidades do top-k | |
| top_k_probs = top_k_probs / (top_k_probs.sum(dim=-1, keepdim=True) + 1e-8) | |
| # Calcula load balancing loss (auxiliar) | |
| # Queremos que cada expert receba aproximadamente N * top_k / n_experts tokens | |
| tokens_per_expert = torch.zeros(self.n_experts, device=x.device) | |
| for i in range(self.top_k): | |
| tokens_per_expert.scatter_add_( | |
| 0, top_k_indices[:, i], torch.ones(N, device=x.device) | |
| ) | |
| fraction_tokens = tokens_per_expert / N | |
| mean_probs = router_probs.mean(dim=0) | |
| self.aux_loss = (fraction_tokens * mean_probs).sum() * self.n_experts | |
| # Dispatch para experts | |
| output = torch.zeros_like(x_flat) | |
| for k in range(self.top_k): | |
| expert_indices = top_k_indices[:, k] # (N,) | |
| expert_weights = top_k_probs[:, k] # (N,) | |
| for e_idx in range(self.n_experts): | |
| mask = (expert_indices == e_idx) | |
| if mask.any(): | |
| expert_input = x_flat[mask] | |
| expert_output = self.experts[e_idx](expert_input) | |
| output[mask] += expert_weights[mask].unsqueeze(-1) * expert_output | |
| return output.view(B, T, C) | |
| # --------------------------------------------------------------------------- | |
| # Transformer Block | |
| # --------------------------------------------------------------------------- | |
| class TransformerBlock(nn.Module): | |
| """Bloco do Transformer: Attention + (Dense FFN ou MoE).""" | |
| def __init__(self, config: ModelConfig, use_moe: bool = False): | |
| super().__init__() | |
| self.use_moe = use_moe | |
| self.norm1 = RMSNorm(config.d_model) | |
| self.attn = CausalSelfAttention(config) | |
| self.norm2 = RMSNorm(config.d_model) | |
| if use_moe: | |
| self.ffn = MoELayer(config) | |
| else: | |
| self.ffn = DenseFFN(config.d_model, config.d_ff, config.dropout) | |
| def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor: | |
| # Pre-norm residual connections | |
| x = x + self.attn(self.norm1(x), mask) | |
| x = x + self.ffn(self.norm2(x)) | |
| return x | |
| # --------------------------------------------------------------------------- | |
| # Modelo Completo | |
| # --------------------------------------------------------------------------- | |
| class MiniMoELM(nn.Module): | |
| """ | |
| Mini Mixture of Experts Language Model. | |
| Arquitetura: | |
| - Token Embedding + RoPE (sem position embedding separado) | |
| - N camadas de Transformer (alternando Dense e MoE) | |
| - RMSNorm final | |
| - LM Head (compartilha pesos com embedding) | |
| """ | |
| def __init__(self, config: ModelConfig): | |
| super().__init__() | |
| self.config = config | |
| # Embeddings | |
| self.token_emb = nn.Embedding(config.vocab_size, config.d_model) | |
| self.emb_dropout = nn.Dropout(config.dropout) | |
| # Transformer blocks | |
| self.layers = nn.ModuleList([ | |
| TransformerBlock( | |
| config, | |
| use_moe=(i in config.moe_layers) | |
| ) | |
| for i in range(config.n_layers) | |
| ]) | |
| self.norm = RMSNorm(config.d_model) | |
| # LM Head - compartilha pesos com embedding (weight tying) | |
| self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False) | |
| self.lm_head.weight = self.token_emb.weight | |
| # Inicializa pesos | |
| self.apply(self._init_weights) | |
| 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) | |
| def forward( | |
| self, | |
| input_ids: torch.Tensor, | |
| targets: torch.Tensor = None, | |
| mask: torch.Tensor = None, | |
| ) -> dict: | |
| B, T = input_ids.shape | |
| assert T <= self.config.max_seq_len, f"Sequencia {T} > max {self.config.max_seq_len}" | |
| # Embeddings | |
| x = self.token_emb(input_ids) | |
| x = self.emb_dropout(x) | |
| # Transformer layers | |
| for layer in self.layers: | |
| x = layer(x, mask) | |
| x = self.norm(x) | |
| logits = self.lm_head(x) # (B, T, vocab_size) | |
| result = {"logits": logits} | |
| if targets is not None: | |
| # Language modeling loss | |
| lm_loss = F.cross_entropy( | |
| logits.view(-1, logits.size(-1)), | |
| targets.view(-1), | |
| ignore_index=0, # ignora padding | |
| ) | |
| # MoE auxiliary loss (load balancing) | |
| aux_loss = 0.0 | |
| n_moe_layers = 0 | |
| for layer in self.layers: | |
| if layer.use_moe: | |
| aux_loss += layer.ffn.aux_loss | |
| n_moe_layers += 1 | |
| if n_moe_layers > 0: | |
| aux_loss = aux_loss / n_moe_layers | |
| total_loss = lm_loss + self.config.load_balance_coeff * aux_loss | |
| result["loss"] = total_loss | |
| result["lm_loss"] = lm_loss | |
| result["aux_loss"] = aux_loss | |
| return result | |
| def generate( | |
| self, | |
| input_ids: torch.Tensor, | |
| max_new_tokens: int = 128, | |
| temperature: float = 0.8, | |
| top_p: float = 0.9, | |
| top_k: int = 40, | |
| eos_token_id: int = 3, | |
| ) -> torch.Tensor: | |
| """Gera texto autoregressivamente.""" | |
| self.eval() | |
| for _ in range(max_new_tokens): | |
| # Trunca se necessario | |
| idx_cond = input_ids if input_ids.size(1) <= self.config.max_seq_len else \ | |
| input_ids[:, -self.config.max_seq_len:] | |
| result = self.forward(idx_cond) | |
| logits = result["logits"][:, -1, :] # ultimo token | |
| # Temperature | |
| if temperature > 0: | |
| logits = logits / temperature | |
| # Top-k filtering | |
| if top_k > 0: | |
| v, _ = torch.topk(logits, min(top_k, logits.size(-1))) | |
| logits[logits < v[:, [-1]]] = float("-inf") | |
| # Top-p (nucleus) filtering | |
| if top_p < 1.0: | |
| sorted_logits, sorted_indices = torch.sort(logits, descending=True) | |
| cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) | |
| sorted_mask = cumulative_probs - F.softmax(sorted_logits, dim=-1) > top_p | |
| sorted_logits[sorted_mask] = float("-inf") | |
| logits = sorted_logits.scatter(1, sorted_indices, sorted_logits) | |
| probs = F.softmax(logits, dim=-1) | |
| next_token = torch.multinomial(probs, num_samples=1) | |
| else: | |
| next_token = logits.argmax(dim=-1, keepdim=True) | |
| input_ids = torch.cat([input_ids, next_token], dim=1) | |
| if next_token.item() == eos_token_id: | |
| break | |
| return input_ids | |
| def count_parameters(self) -> dict: | |
| """Conta parametros do modelo detalhadamente.""" | |
| total = sum(p.numel() for p in self.parameters()) | |
| trainable = sum(p.numel() for p in self.parameters() if p.requires_grad) | |
| # Conta por componente | |
| emb_params = sum(p.numel() for p in self.token_emb.parameters()) | |
| attn_params = 0 | |
| ffn_dense_params = 0 | |
| moe_params = 0 | |
| for layer in self.layers: | |
| attn_params += sum(p.numel() for p in layer.attn.parameters()) | |
| if layer.use_moe: | |
| moe_params += sum(p.numel() for p in layer.ffn.parameters()) | |
| else: | |
| ffn_dense_params += sum(p.numel() for p in layer.ffn.parameters()) | |
| return { | |
| "total": total, | |
| "trainable": trainable, | |
| "embedding": emb_params, | |
| "attention": attn_params, | |
| "ffn_dense": ffn_dense_params, | |
| "moe": moe_params, | |
| "norm_and_other": total - emb_params - attn_params - ffn_dense_params - moe_params, | |
| } | |
| def build_model(config: ModelConfig = None) -> MiniMoELM: | |
| """Constroi o modelo e mostra informacoes.""" | |
| if config is None: | |
| config = ModelConfig() | |
| model = MiniMoELM(config) | |
| params = model.count_parameters() | |
| print("=" * 60) | |
| print(" MINI MoE LANGUAGE MODEL") | |
| print("=" * 60) | |
| print(f" Layers: {config.n_layers}") | |
| print(f" d_model: {config.d_model}") | |
| print(f" Heads: {config.n_heads}") | |
| print(f" d_ff: {config.d_ff}") | |
| print(f" Experts: {config.n_experts} (top-{config.top_k})") | |
| print(f" MoE layers: {config.moe_layers}") | |
| print(f" Vocab: {config.vocab_size}") | |
| print(f" Max seq len: {config.max_seq_len}") | |
| print("-" * 60) | |
| print(f" Total params: {params['total']:>12,}") | |
| print(f" Trainable: {params['trainable']:>12,}") | |
| print(f" Embedding: {params['embedding']:>12,}") | |
| print(f" Attention: {params['attention']:>12,}") | |
| print(f" FFN Dense: {params['ffn_dense']:>12,}") | |
| print(f" MoE (all exp): {params['moe']:>12,}") | |
| print(f" Norm/Other: {params['norm_and_other']:>12,}") | |
| print("=" * 60) | |
| return model | |
| if __name__ == "__main__": | |
| config = ModelConfig() | |
| model = build_model(config) | |
| # Teste rapido | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| model = model.to(device) | |
| dummy_input = torch.randint(0, config.vocab_size, (2, 32)).to(device) | |
| dummy_target = torch.randint(0, config.vocab_size, (2, 32)).to(device) | |
| result = model(dummy_input, targets=dummy_target) | |
| print(f"\n Test forward pass:") | |
| print(f" Logits shape: {result['logits'].shape}") | |
| print(f" LM Loss: {result['lm_loss'].item():.4f}") | |
| print(f" Aux Loss: {result['aux_loss']:.4f}") | |
| print(f" Total Loss: {result['loss'].item():.4f}") | |