Download model.py from delvek/researcherbot-1: direct link, hf CLI and curl.
- Browser
- Download file 28.7 kB
-
https://huggingface.co/delvek/researcherbot-1/resolve/main/model.py
- Command line
-
hf download hf://delvek/researcherbot-1/model.py
-
curl -L -o model.py https://huggingface.co/delvek/researcherbot-1/resolve/main/model.py
28.7 kB
| """ | |
| Multimodal 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 | |
| - Vision Encoder: Patch Embedding do zero | |
| - Audio Encoder: Mel Spectrogram -> Patch Embedding do zero | |
| - ~20M parametros totais, ~10M ativos | |
| """ | |
| 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.""" | |
| 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, k, cos, sin): | |
| cos = cos.unsqueeze(0).unsqueeze(0) | |
| 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) | |
| scale = math.sqrt(self.d_head) | |
| attn = (q @ k.transpose(-2, -1)) / scale | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| class DenseFFN(nn.Module): | |
| """Feed-forward com SwiGLU.""" | |
| 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) | |
| self.dropout = nn.Dropout(dropout) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x))) | |
| class Expert(nn.Module): | |
| 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): | |
| """MoE com top-k routing e load balancing loss.""" | |
| 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 | |
| self.router = nn.Linear(config.d_model, config.n_experts, bias=False) | |
| self.experts = nn.ModuleList([ | |
| Expert(config.d_model, config.d_ff, config.expert_dropout) | |
| for _ in range(config.n_experts) | |
| ]) | |
| self.aux_loss = 0.0 | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| B, T, C = x.shape | |
| x_flat = x.view(-1, C) | |
| N = x_flat.size(0) | |
| router_logits = self.router(x_flat) | |
| router_probs = F.softmax(router_logits, dim=-1) | |
| top_k_probs, top_k_indices = torch.topk(router_probs, self.top_k, dim=-1) | |
| top_k_probs = top_k_probs / (top_k_probs.sum(dim=-1, keepdim=True) + 1e-8) | |
| 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 | |
| output = torch.zeros_like(x_flat) | |
| for k in range(self.top_k): | |
| expert_indices = top_k_indices[:, k] | |
| expert_weights = top_k_probs[:, k] | |
| 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) | |
| # --------------------------------------------------------------------------- | |
| # Vision Encoder (patch embedding do zero) | |
| # --------------------------------------------------------------------------- | |
| class VisionEncoder(nn.Module): | |
| """ | |
| Encoder de imagens com patch embedding. | |
| Divide a imagem em patches, projeta pra d_model, passa por self-attention. | |
| """ | |
| def __init__(self, config: ModelConfig): | |
| super().__init__() | |
| self.patch_size = config.patch_size | |
| self.img_size = config.img_size | |
| n_patches = (config.img_size // config.patch_size) ** 2 | |
| # Patch projection: Conv2d que faz unfold + linear de uma vez | |
| self.patch_proj = nn.Conv2d( | |
| config.img_channels, | |
| config.d_model, | |
| kernel_size=config.patch_size, | |
| stride=config.patch_size, | |
| bias=False, | |
| ) | |
| # CLS token e position embeddings | |
| self.cls_token = nn.Parameter(torch.randn(1, 1, config.d_model) * 0.02) | |
| self.pos_emb = nn.Parameter(torch.randn(1, n_patches + 1, config.d_model) * 0.02) | |
| self.dropout = nn.Dropout(config.dropout) | |
| # Mini transformer encoder (1 camada) | |
| self.layers = nn.ModuleList([ | |
| nn.ModuleDict({ | |
| "norm1": RMSNorm(config.d_model), | |
| "attn": SelfAttention(config), | |
| "norm2": RMSNorm(config.d_model), | |
| "ffn": DenseFFN(config.d_model, config.d_ff, config.dropout), | |
| }) | |
| for _ in range(config.n_vis_layers) | |
| ]) | |
| self.norm = RMSNorm(config.d_model) | |
| self.out_proj = nn.Linear(config.d_model, config.d_model, bias=False) | |
| def forward(self, images: torch.Tensor) -> torch.Tensor: | |
| """ | |
| images: (B, C, H, W) com H=W=img_size | |
| returns: (B, n_patches+1, d_model) | |
| """ | |
| B = images.size(0) | |
| # Patch embedding: (B, d_model, H/P, W/P) -> (B, n_patches, d_model) | |
| x = self.patch_proj(images) | |
| x = x.flatten(2).transpose(1, 2) | |
| # Prepend CLS token | |
| cls = self.cls_token.expand(B, -1, -1) | |
| x = torch.cat([cls, x], dim=1) | |
| x = x + self.pos_emb[:, :x.size(1)] | |
| x = self.dropout(x) | |
| # Mini transformer | |
| for layer in self.layers: | |
| x = x + layer["attn"](layer["norm1"](x)) | |
| x = x + layer["ffn"](layer["norm2"](x)) | |
| x = self.norm(x) | |
| return self.out_proj(x) | |
| # --------------------------------------------------------------------------- | |
| # Audio Encoder (mel spectrogram -> patches) | |
| # --------------------------------------------------------------------------- | |
| class AudioEncoder(nn.Module): | |
| """ | |
| Encoder de audio com mel spectrogram -> patch embedding. | |
| Divide o spectrogram em patches temporais, projeta pra d_model. | |
| """ | |
| def __init__(self, config: ModelConfig): | |
| super().__init__() | |
| self.audio_patch_size = config.audio_patch_size | |
| self.n_mels = config.n_mels | |
| self.max_patches = config.max_audio_patches | |
| # Patch projection: projeta cada frame de (n_mels * patch_size) -> d_model | |
| self.patch_proj = nn.Linear( | |
| config.n_mels * config.audio_patch_size, | |
| config.d_model, | |
| bias=False, | |
| ) | |
| # CLS token e position embeddings | |
| self.cls_token = nn.Parameter(torch.randn(1, 1, config.d_model) * 0.02) | |
| self.pos_emb = nn.Parameter(torch.randn(1, config.max_audio_patches + 1, config.d_model) * 0.02) | |
| self.dropout = nn.Dropout(config.dropout) | |
| # Mini transformer encoder (1 camada) | |
| self.layers = nn.ModuleList([ | |
| nn.ModuleDict({ | |
| "norm1": RMSNorm(config.d_model), | |
| "attn": SelfAttention(config), | |
| "norm2": RMSNorm(config.d_model), | |
| "ffn": DenseFFN(config.d_model, config.d_ff, config.dropout), | |
| }) | |
| for _ in range(config.n_aud_layers) | |
| ]) | |
| self.norm = RMSNorm(config.d_model) | |
| self.out_proj = nn.Linear(config.d_model, config.d_model, bias=False) | |
| def forward(self, mel_spec: torch.Tensor) -> torch.Tensor: | |
| """ | |
| mel_spec: (B, n_mels, T_frames) mel spectrogram | |
| returns: (B, n_patches+1, d_model) | |
| """ | |
| B, M, T = mel_spec.shape | |
| # Pad temporal dimension to multiple of patch_size | |
| pad_len = (self.audio_patch_size - T % self.audio_patch_size) % self.audio_patch_size | |
| if pad_len > 0: | |
| mel_spec = F.pad(mel_spec, (0, pad_len)) | |
| T_padded = mel_spec.size(2) | |
| # Reshape into patches: (B, n_patches, n_mels * patch_size) | |
| n_patches = T_padded // self.audio_patch_size | |
| n_patches = min(n_patches, self.max_patches) | |
| mel_spec = mel_spec[:, :, :n_patches * self.audio_patch_size] | |
| x = mel_spec.transpose(1, 2).reshape(B, n_patches, M * self.audio_patch_size) | |
| # Project | |
| x = self.patch_proj(x) | |
| # Prepend CLS | |
| cls = self.cls_token.expand(B, -1, -1) | |
| x = torch.cat([cls, x], dim=1) | |
| x = x + self.pos_emb[:, :x.size(1)] | |
| x = self.dropout(x) | |
| # Mini transformer | |
| for layer in self.layers: | |
| x = x + layer["attn"](layer["norm1"](x)) | |
| x = x + layer["ffn"](layer["norm2"](x)) | |
| x = self.norm(x) | |
| return self.out_proj(x) | |
| # --------------------------------------------------------------------------- | |
| # Bidirectional Self-Attention (for encoders, no causal mask) | |
| # --------------------------------------------------------------------------- | |
| class SelfAttention(nn.Module): | |
| """Multi-Head Self-Attention sem mascara causal (para encoders).""" | |
| 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.attn_dropout = nn.Dropout(config.dropout) | |
| def forward(self, x: torch.Tensor) -> 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) | |
| scale = math.sqrt(self.d_head) | |
| attn = (q @ k.transpose(-2, -1)) / scale | |
| attn = F.softmax(attn, dim=-1) | |
| attn = self.attn_dropout(attn) | |
| out = (attn @ v).transpose(1, 2).contiguous().view(B, T, C) | |
| return self.o_proj(out) | |
| # --------------------------------------------------------------------------- | |
| # 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: | |
| x = x + self.attn(self.norm1(x), mask) | |
| x = x + self.ffn(self.norm2(x)) | |
| return x | |
| # --------------------------------------------------------------------------- | |
| # Modelo Multimodal Completo | |
| # --------------------------------------------------------------------------- | |
| class MultimodalMoELM(nn.Module): | |
| """ | |
| Multimodal Mixture of Experts Language Model. | |
| Modalidades: Texto + Imagem + Audio | |
| Arquitetura: | |
| - Vision Encoder (patch embedding) -> tokens visuais | |
| - Audio Encoder (mel patches) -> tokens de audio | |
| - Token Embedding para texto | |
| - Transformer Decoder com MoE (backbone compartilhado) | |
| - LM Head com weight tying | |
| """ | |
| def __init__(self, config: ModelConfig): | |
| super().__init__() | |
| self.config = config | |
| # Text embedding | |
| self.token_emb = nn.Embedding(config.vocab_size, config.d_model) | |
| self.emb_dropout = nn.Dropout(config.dropout) | |
| # Modality encoders | |
| self.vision_encoder = VisionEncoder(config) | |
| self.audio_encoder = AudioEncoder(config) | |
| # Modality type embeddings (text=0, vision=1, audio=2) | |
| self.modality_emb = nn.Embedding(3, config.d_model) | |
| # Transformer backbone | |
| 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 (weight tying) | |
| self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False) | |
| self.lm_head.weight = self.token_emb.weight | |
| 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) | |
| elif isinstance(module, nn.Conv2d): | |
| nn.init.normal_(module.weight, mean=0.0, std=0.02) | |
| def encode_text(self, input_ids: torch.Tensor) -> torch.Tensor: | |
| """Codifica tokens de texto.""" | |
| x = self.token_emb(input_ids) | |
| mod = self.modality_emb(torch.zeros(x.size(1), dtype=torch.long, device=x.device)) | |
| return x + mod | |
| def encode_image(self, images: torch.Tensor) -> torch.Tensor: | |
| """Codifica imagens em tokens visuais.""" | |
| x = self.vision_encoder(images) | |
| mod = self.modality_emb(torch.ones(x.size(1), dtype=torch.long, device=x.device)) | |
| return x + mod | |
| def encode_audio(self, mel_spec: torch.Tensor) -> torch.Tensor: | |
| """Codifica audio (mel spectrogram) em tokens.""" | |
| x = self.audio_encoder(mel_spec) | |
| mod = self.modality_emb(2 * torch.ones(x.size(1), dtype=torch.long, device=x.device)) | |
| return x + mod | |
| def forward( | |
| self, | |
| input_ids: torch.Tensor, | |
| targets: torch.Tensor = None, | |
| mask: torch.Tensor = None, | |
| images: torch.Tensor = None, | |
| mel_specs: torch.Tensor = None, | |
| ) -> dict: | |
| """ | |
| Forward pass multimodal. | |
| Se images ou mel_specs forem fornecidos, seus embeddings sao | |
| prepended aos embeddings de texto antes do decoder. | |
| """ | |
| B, T = input_ids.shape | |
| # Encode texto | |
| text_emb = self.encode_text(input_ids) | |
| # Concatena modalidades: [image_tokens | audio_tokens | text_tokens] | |
| parts = [] | |
| if images is not None: | |
| img_emb = self.encode_image(images) # (B, n_img, d) | |
| parts.append(img_emb) | |
| if mel_specs is not None: | |
| aud_emb = self.encode_audio(mel_specs) # (B, n_aud, d) | |
| parts.append(aud_emb) | |
| parts.append(text_emb) | |
| x = torch.cat(parts, dim=1) if len(parts) > 1 else text_emb | |
| x = self.emb_dropout(x) | |
| # Trunca se total exceder max_seq_len (prefix + text) | |
| total_len = x.size(1) | |
| if total_len > self.config.max_seq_len: | |
| # Mantém prefix inteiro, trunca texto | |
| n_prefix = total_len - T | |
| keep_text = self.config.max_seq_len - n_prefix | |
| text_emb_trunc = text_emb[:, :keep_text] | |
| prefix_parts = [p for p in parts[:-1]] | |
| x = torch.cat(prefix_parts + [text_emb_trunc], dim=1) if prefix_parts else text_emb_trunc | |
| T = keep_text | |
| if targets is not None: | |
| targets = targets[:, :keep_text] | |
| total_len = x.size(1) | |
| # Transformer layers | |
| for layer in self.layers: | |
| x = layer(x, mask) | |
| x = self.norm(x) | |
| logits = self.lm_head(x) | |
| # So calcula loss nos tokens de texto (ultimas T posicoes) | |
| n_prefix = total_len - T | |
| text_logits = logits[:, n_prefix:, :] | |
| result = {"logits": text_logits, "full_logits": logits} | |
| if targets is not None: | |
| lm_loss = F.cross_entropy( | |
| text_logits.reshape(-1, text_logits.size(-1)), | |
| targets.reshape(-1), | |
| ignore_index=0, | |
| ) | |
| 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, | |
| images: torch.Tensor = None, | |
| mel_specs: torch.Tensor = None, | |
| ) -> torch.Tensor: | |
| """Gera texto autoregressivamente, opcionalmente condicionado em imagem/audio.""" | |
| self.eval() | |
| # Calcula prefixo multimodal uma vez | |
| prefix_parts = [] | |
| if images is not None: | |
| prefix_parts.append(self.encode_image(images)) | |
| if mel_specs is not None: | |
| prefix_parts.append(self.encode_audio(mel_specs)) | |
| prefix_emb = torch.cat(prefix_parts, dim=1) if prefix_parts else None | |
| prefix_len = prefix_emb.size(1) if prefix_emb is not None else 0 | |
| for _ in range(max_new_tokens): | |
| text_emb = self.encode_text(input_ids) | |
| if prefix_emb is not None: | |
| x = torch.cat([prefix_emb, text_emb], dim=1) | |
| else: | |
| x = text_emb | |
| # Trunca se necessario | |
| if x.size(1) > self.config.max_seq_len: | |
| # Mantém prefix + ultimos tokens | |
| keep_text = self.config.max_seq_len - prefix_len | |
| text_emb = text_emb[:, -keep_text:] | |
| if prefix_emb is not None: | |
| x = torch.cat([prefix_emb, text_emb], dim=1) | |
| else: | |
| x = text_emb | |
| x = self.emb_dropout(x) | |
| for layer in self.layers: | |
| x = layer(x) | |
| x = self.norm(x) | |
| logits = self.lm_head(x)[:, -1, :] | |
| if temperature > 0: | |
| logits = logits / temperature | |
| if top_k > 0: | |
| v, _ = torch.topk(logits, min(top_k, logits.size(-1))) | |
| logits[logits < v[:, [-1]]] = float("-inf") | |
| 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 detalhadamente.""" | |
| total = sum(p.numel() for p in self.parameters()) | |
| trainable = sum(p.numel() for p in self.parameters() if p.requires_grad) | |
| emb_params = sum(p.numel() for p in self.token_emb.parameters()) | |
| emb_params += sum(p.numel() for p in self.modality_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()) | |
| vision_params = sum(p.numel() for p in self.vision_encoder.parameters()) | |
| audio_params = sum(p.numel() for p in self.audio_encoder.parameters()) | |
| return { | |
| "total": total, | |
| "trainable": trainable, | |
| "embedding": emb_params, | |
| "attention": attn_params, | |
| "ffn_dense": ffn_dense_params, | |
| "moe": moe_params, | |
| "vision_encoder": vision_params, | |
| "audio_encoder": audio_params, | |
| "norm_and_other": total - emb_params - attn_params - ffn_dense_params - moe_params - vision_params - audio_params, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Alias para compatibilidade | |
| # --------------------------------------------------------------------------- | |
| MiniMoELM = MultimodalMoELM | |
| def build_model(config: ModelConfig = None) -> MultimodalMoELM: | |
| """Constroi o modelo e mostra informacoes.""" | |
| if config is None: | |
| config = ModelConfig() | |
| model = MultimodalMoELM(config) | |
| params = model.count_parameters() | |
| print("=" * 60) | |
| print(" MULTIMODAL 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(f" Image: {config.img_size}x{config.img_size}, patch {config.patch_size}") | |
| print(f" Audio: {config.n_mels} mels, patch {config.audio_patch_size}") | |
| 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" Vision Encoder: {params['vision_encoder']:>12,}") | |
| print(f" Audio Encoder: {params['audio_encoder']:>12,}") | |
| print(f" Norm/Other: {params['norm_and_other']:>12,}") | |
| print("=" * 60) | |
| return model | |
| if __name__ == "__main__": | |
| config = ModelConfig() | |
| model = build_model(config) | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| model = model.to(device) | |
| # Teste text-only | |
| dummy_ids = torch.randint(0, config.vocab_size, (2, 32)).to(device) | |
| dummy_tgt = torch.randint(0, config.vocab_size, (2, 32)).to(device) | |
| result = model(dummy_ids, targets=dummy_tgt) | |
| print(f"\n [Text only] Logits: {result['logits'].shape} | Loss: {result['loss'].item():.4f}") | |
| # Teste text + image | |
| dummy_img = torch.randn(2, 3, config.img_size, config.img_size).to(device) | |
| dummy_ids2 = torch.randint(0, config.vocab_size, (2, 16)).to(device) | |
| dummy_tgt2 = torch.randint(0, config.vocab_size, (2, 16)).to(device) | |
| result2 = model(dummy_ids2, targets=dummy_tgt2, images=dummy_img) | |
| print(f" [Text+Image] Logits: {result2['logits'].shape} | Loss: {result2['loss'].item():.4f}") | |
| # Teste text + audio | |
| dummy_mel = torch.randn(2, config.n_mels, 256).to(device) | |
| result3 = model(dummy_ids2, targets=dummy_tgt2, mel_specs=dummy_mel) | |
| print(f" [Text+Audio] Logits: {result3['logits'].shape} | Loss: {result3['loss'].item():.4f}") | |
| # Teste full multimodal | |
| result4 = model(dummy_ids2, targets=dummy_tgt2, images=dummy_img, mel_specs=dummy_mel) | |
| print(f" [Full Multi] Logits: {result4['logits'].shape} | Loss: {result4['loss'].item():.4f}") | |