CoolFace
Modelpublic

SlitherCode/tiny-edu-166m

sourceHugging Facemitupdated 4mo agoView on Hugging Face
0likes8downloads
modeling_parchment.py203 linesDownload Raw Back to root
1import math2import torch3import torch.nn as nn4import torch.nn.functional as F5from transformers import PreTrainedModel6from transformers.generation import GenerationMixin7from transformers.modeling_outputs import CausalLMOutputWithPast8 9from .configuration_parchment import ParchmentConfig10 11 12class Embeddings(nn.Module):13    def __init__(self, vocab_size, d_model):14        super().__init__()15        self.embeds = nn.Embedding(vocab_size, d_model)16        nn.init.normal_(self.embeds.weight, mean=0, std=d_model ** -0.5)17 18    def forward(self, token_ids):19        return self.embeds(token_ids)20 21 22class RoPE(nn.Module):23    def __init__(self, d_k, max_seq_len, base=10000.0):24        super().__init__()25        self.max_seq_len = max_seq_len26        # persistent=True so inv_freq is saved/loaded via from_pretrained27        inv_freq = 1.0 / (base ** (torch.arange(0, d_k, 2).float() / d_k))28        self.register_buffer("inv_freq", inv_freq, persistent=True)29        self._cos_cache: torch.Tensor | None = None30        self._sin_cache: torch.Tensor | None = None31 32    def _build_cache(self, device: torch.device, dtype: torch.dtype):33        t = torch.arange(self.max_seq_len, device=device, dtype=torch.float32)34        freqs = torch.outer(t, self.inv_freq.to(device, torch.float32))35        emb = torch.cat([freqs, freqs], dim=-1)36        self._cos_cache = emb.cos()[None, None].to(dtype)37        self._sin_cache = emb.sin()[None, None].to(dtype)38 39    def rotate_half(self, x):40        x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]41        return torch.cat([-x2, x1], dim=-1)42 43    def forward(self, q, k):44        if self._cos_cache is None or self._cos_cache.device != q.device or self._cos_cache.dtype != q.dtype:45            self._build_cache(q.device, q.dtype)46        seq = q.shape[2]47        cos = self._cos_cache[:, :, :seq]48        sin = self._sin_cache[:, :, :seq]49        q = (q * cos) + (self.rotate_half(q) * sin)50        k = (k * cos) + (self.rotate_half(k) * sin)51        return q, k52 53 54class RMSNorm(nn.Module):55    def __init__(self, d_model, eps=1e-6):56        super().__init__()57        self.scale = nn.Parameter(torch.ones(d_model))58        self.eps = eps59 60    def forward(self, x):61        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.scale62 63 64class MultiHeadAttention(nn.Module):65    def __init__(self, n_heads, d_model, max_seq_len, rope_base):66        super().__init__()67        self.n_heads = n_heads68        self.d_k = d_model // n_heads69        self.d_model = d_model70        self.W_Q = nn.Linear(d_model, d_model, bias=False)71        self.W_K = nn.Linear(d_model, d_model, bias=False)72        self.W_V = nn.Linear(d_model, d_model, bias=False)73        self.W_O = nn.Linear(d_model, d_model, bias=False)74        self.rope = RoPE(self.d_k, max_seq_len, base=rope_base)75        self.W_O.RESIDUAL_SCALE_INIT = True76 77    def forward(self, x):78        B, T, _ = x.shape79        Q = self.W_Q(x).view(B, T, self.n_heads, self.d_k).permute(0, 2, 1, 3)80        K = self.W_K(x).view(B, T, self.n_heads, self.d_k).permute(0, 2, 1, 3)81        V = self.W_V(x).view(B, T, self.n_heads, self.d_k).permute(0, 2, 1, 3)82        Q, K = self.rope(Q, K)83        out = F.scaled_dot_product_attention(Q, K, V, is_causal=True)84        out = out.permute(0, 2, 1, 3).contiguous().view(B, T, self.d_model)85        return self.W_O(out)86 87 88class SwiGLU(nn.Module):89    def __init__(self, d_model):90        super().__init__()91        hidden = int(2 / 3 * 4 * d_model)92        hidden = (hidden + 63) // 64 * 6493        self.w1 = nn.Linear(d_model, hidden, bias=False)94        self.w2 = nn.Linear(hidden, d_model, bias=False)95        self.w3 = nn.Linear(d_model, hidden, bias=False)96        self.w2.RESIDUAL_SCALE_INIT = True97 98    def forward(self, x):99        return self.w2(F.silu(self.w1(x)) * self.w3(x))100 101 102class TransformerBlock(nn.Module):103    def __init__(self, d_model, n_heads, max_seq_len, rope_base):104        super().__init__()105        self.attn = MultiHeadAttention(n_heads, d_model, max_seq_len, rope_base)106        self.ff = SwiGLU(d_model)107        self.norm1 = RMSNorm(d_model)108        self.norm2 = RMSNorm(d_model)109 110    def forward(self, x):111        x = x + self.attn(self.norm1(x))112        x = x + self.ff(self.norm2(x))113        return x114 115 116class ParchmentModel(PreTrainedModel):117    config_class = ParchmentConfig118    base_model_prefix = "model"119 120    def __init__(self, config: ParchmentConfig):121        super().__init__(config)122        self.embeddings = Embeddings(config.vocab_size, config.d_model)123        self.blocks = nn.ModuleList([124            TransformerBlock(config.d_model, config.n_heads, config.max_seq_len, config.rope_base)125            for _ in range(config.n_layers)126        ])127        self.norm = RMSNorm(config.d_model, eps=config.rms_norm_eps)128        self.post_init()129 130    def _init_weights(self, module):131        if isinstance(module, nn.Linear):132            std = 0.02133            if hasattr(module, "RESIDUAL_SCALE_INIT"):134                std /= math.sqrt(2 * self.config.n_layers)135            nn.init.normal_(module.weight, mean=0.0, std=std)136            if module.bias is not None:137                nn.init.zeros_(module.bias)138        elif isinstance(module, nn.Embedding):139            nn.init.normal_(module.weight, mean=0, std=self.config.d_model ** -0.5)140 141    def forward(self, input_ids: torch.LongTensor) -> torch.Tensor:142        x = self.embeddings(input_ids)143        for block in self.blocks:144            x = block(x)145        return self.norm(x)146 147 148class ParchmentForCausalLM(PreTrainedModel, GenerationMixin):149    config_class = ParchmentConfig150    base_model_prefix = "model"151    _tied_weights_keys = {"lm_head.weight": "model.embeddings.embeds.weight"}152    _keys_to_ignore_on_load_missing = [r"lm_head\.weight", r".*\.rope\."]153    _supports_cache_class = False154    _supports_static_cache = False155 156    def __init__(self, config: ParchmentConfig):157        super().__init__(config)158        self.model = ParchmentModel(config)159        self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)160        self.post_init()161 162    def get_input_embeddings(self):163        return self.model.embeddings.embeds164 165    def set_input_embeddings(self, value):166        self.model.embeddings.embeds = value167 168    def get_output_embeddings(self):169        return self.lm_head170 171    def set_output_embeddings(self, value):172        self.lm_head = value173 174    def _init_weights(self, module):175        self.model._init_weights(module)176 177    def forward(178        self,179        input_ids: torch.LongTensor,180        attention_mask: torch.Tensor | None = None,181        labels: torch.LongTensor | None = None,182        **kwargs,183    ) -> CausalLMOutputWithPast:184        hidden = self.model(input_ids)185        logits = self.lm_head(hidden)186 187        loss = None188        if labels is not None:189            shift_logits = logits[:, :-1, :].contiguous()190            shift_labels = labels[:, 1:].contiguous()191            loss = F.cross_entropy(192                shift_logits.view(-1, self.config.vocab_size),193                shift_labels.view(-1),194            )195 196        return CausalLMOutputWithPast(loss=loss, logits=logits)197 198    def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):199        return {200            "input_ids": input_ids[:, -self.config.max_seq_len:],201            "attention_mask": attention_mask,202        }203