import inspect from transformers import PreTrainedModel, PretrainedConfig from dataclasses import dataclass import torch import torch.nn as nn from torch.nn import functional as F from .configuration_tlama import TlamaConfig # ----------------------------------------------------------------------------- class SelfAttention(nn.Module): def __init__(self, config): super().__init__() assert config.n_embd % config.n_head == 0 # key, query, value projections for all heads, but in a batch self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd) # output projection self.c_proj = nn.Linear(config.n_embd, config.n_embd) self.c_proj.TLAMA124M_SCALE_INIT = 1 # regularization self.n_head = config.n_head self.n_embd = config.n_embd def forward(self, x): B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd) # calculate query, key, values for all heads in batch and move head forward to be the batch dim # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer qkv = self.c_attn(x) q, k, v = qkv.split(self.n_embd, dim=2) k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) y = F.scaled_dot_product_attention(q, k, v, is_causal=True) # flash attention y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side # output projection y = self.c_proj(y) return y class MLP(nn.Module): def __init__(self, config): super().__init__() self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd) self.gelu = nn.GELU(approximate='tanh') self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd) self.c_proj.TLAMA124M_SCALE_INIT = 1 def forward(self, x): x = self.c_fc(x) x = self.gelu(x) x = self.c_proj(x) return x class Block(nn.Module): def __init__(self, config): super().__init__() self.ln_1 = nn.LayerNorm(config.n_embd) self.attn = SelfAttention(config) self.ln_2 = nn.LayerNorm(config.n_embd) self.mlp = MLP(config) def forward(self, x): # attention block with residual connection x = x + self.attn(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class Tlama(PreTrainedModel): config_class = TlamaConfig def __init__(self, config): super().__init__(config) self.config = config self.transformer = nn.ModuleDict(dict( wte = nn.Embedding(config.vocab_size, config.n_embd), # token embedding wpe = nn.Embedding(config.block_size, config.n_embd), # positional embedding h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]), # transformer blocks ln_f = nn.LayerNorm(config.n_embd), # final layer norm )) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # language model head # Weight sharing scheme self.transformer.wte.weight = self.lm_head.weight # Initialize weights self.apply(self._init_weights) def _init_weights(self, module): if isinstance(module, nn.Linear): std = 0.02 if hasattr(module, 'TLAMA124M_SCALE_INIT'): std *= (2 * self.config.n_layer) ** -0.5 torch.nn.init.normal_(module.weight, mean=0.0, std=std) if module.bias is not None: torch.nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) def forward(self, idx, targets=None): B, T = idx.size() assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}" pos = torch.arange(0, T, dtype=torch.long, device=idx.device) pos_emb = self.transformer.wpe(pos) tok_emb = self.transformer.wte(idx) x = tok_emb + pos_emb for block in self.transformer.h: x = block(x) x = self.transformer.ln_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)) return logits, loss def configure_optimizers(self, weight_decay, learning_rate, device_type, master_process=True): param_dict = {pn: p for pn, p in self.named_parameters() if p.requires_grad} decay_params = [p for n, p in param_dict.items() if p.dim() >= 2] nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2] optim_groups = [ {'params': decay_params, 'weight_decay': weight_decay}, {'params': nodecay_params, 'weight_decay': 0.0} ] optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=(0.9, 0.95), eps=1e-8) return optimizer class TlamaForCausalLM(PreTrainedModel): config_class = TlamaConfig def __init__(self, config): super().__init__(config) self.model = Tlama(config) # Tu modelo personalizado def forward(self, input_ids, attention_mask=None, **kwargs): logits, _ = self.model(input_ids) return logits def generate(self, input_ids, max_length=50, top_k=50, top_p=0.9, temperature=1.0, **kwargs): return self._generate_text(input_ids, max_length, top_k, top_p, temperature) def _generate_text(self, input_ids, max_length, top_k, top_p, temperature): tokens = input_ids.to(self.device) with torch.no_grad(): for _ in range(max_length): logits, _ = self.model(tokens) logits = logits[:, -1, :] / temperature # Aplicar temperatura probs = torch.softmax(logits, dim=-1) # Implementación de nucleus sampling (top-p) if top_p < 1.0: sorted_probs, sorted_indices = torch.sort(probs, descending=True) cumulative_probs = torch.cumsum(sorted_probs, dim=-1) sorted_indices_to_remove = cumulative_probs > top_p sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() sorted_indices_to_remove[..., 0] = 0 indices_to_remove = sorted_indices[sorted_indices_to_remove] probs[:, indices_to_remove] = 0 probs = probs / probs.sum(dim=-1, keepdim=True) # Sampling top-k topk_probs, topk_indices = torch.topk(probs, top_k) next_token = torch.multinomial(topk_probs, 1) next_token = topk_indices.gather(-1, next_token) tokens = torch.cat((tokens, next_token), dim=1) return tokens