Download tiny_model_core.py from fox007j/codewiz-ai-tiny-model-training-data: direct link, hf CLI and curl.
- Browser
- Download file 9.71 kB
-
https://huggingface.co/datasets/fox007j/codewiz-ai-tiny-model-training-data/resolve/main/tiny_model_core.py
- Command line
-
hf download hf://datasets/fox007j/codewiz-ai-tiny-model-training-data/tiny_model_core.py
-
curl -L -o tiny_model_core.py https://huggingface.co/datasets/fox007j/codewiz-ai-tiny-model-training-data/resolve/main/tiny_model_core.py
9.71 kB
| import math | |
| import re | |
| from collections import Counter | |
| from dataclasses import dataclass | |
| from typing import Dict, List, Optional, Tuple | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_]+|[^\w\s]", re.UNICODE) | |
| class WordTokenizer: | |
| PAD_TOKEN = "<pad>" | |
| BOS_TOKEN = "<bos>" | |
| EOS_TOKEN = "<eos>" | |
| UNK_TOKEN = "<unk>" | |
| def __init__(self): | |
| self.token_to_id: Dict[str, int] = {} | |
| self.id_to_token: Dict[int, str] = {} | |
| self.pad_id = -1 | |
| self.bos_id = -1 | |
| self.eos_id = -1 | |
| self.unk_id = -1 | |
| def vocab_size(self) -> int: | |
| return len(self.token_to_id) | |
| def _split(text: str) -> List[str]: | |
| return TOKEN_PATTERN.findall((text or "").strip()) | |
| def fit(self, texts: List[str], vocab_size: int = 8000, min_freq: int = 2): | |
| counts = Counter() | |
| for text in texts: | |
| counts.update(self._split(text)) | |
| special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN] | |
| for token in special_tokens: | |
| self._add_token(token) | |
| for token, freq in counts.most_common(max(0, vocab_size - len(special_tokens))): | |
| if freq < min_freq: | |
| continue | |
| if token not in self.token_to_id: | |
| self._add_token(token) | |
| self.pad_id = self.token_to_id[self.PAD_TOKEN] | |
| self.bos_id = self.token_to_id[self.BOS_TOKEN] | |
| self.eos_id = self.token_to_id[self.EOS_TOKEN] | |
| self.unk_id = self.token_to_id[self.UNK_TOKEN] | |
| def _add_token(self, token: str): | |
| idx = len(self.token_to_id) | |
| self.token_to_id[token] = idx | |
| self.id_to_token[idx] = token | |
| def encode(self, text: str, add_bos: bool = False, add_eos: bool = False) -> List[int]: | |
| ids = [self.token_to_id.get(tok, self.unk_id) for tok in self._split(text)] | |
| if add_bos: | |
| ids = [self.bos_id] + ids | |
| if add_eos: | |
| ids = ids + [self.eos_id] | |
| return ids | |
| def decode(self, ids: List[int]) -> str: | |
| tokens = [] | |
| for idx in ids: | |
| token = self.id_to_token.get(int(idx), self.UNK_TOKEN) | |
| if token in {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}: | |
| continue | |
| tokens.append(token) | |
| text = " ".join(tokens) | |
| text = re.sub(r"\s+([.,!?;:)\]\}])", r"\1", text) | |
| text = re.sub(r"([([\{])\s+", r"\1", text) | |
| text = re.sub(r"\s+", " ", text) | |
| return text.strip() | |
| def to_state(self) -> Dict: | |
| return { | |
| "token_to_id": self.token_to_id, | |
| "id_to_token": {str(k): v for k, v in self.id_to_token.items()}, | |
| "pad_id": self.pad_id, | |
| "bos_id": self.bos_id, | |
| "eos_id": self.eos_id, | |
| "unk_id": self.unk_id, | |
| } | |
| def from_state(cls, state: Dict): | |
| tok = cls() | |
| tok.token_to_id = dict(state.get("token_to_id", {})) | |
| tok.id_to_token = {int(k): v for k, v in state.get("id_to_token", {}).items()} | |
| tok.pad_id = int(state.get("pad_id", -1)) | |
| tok.bos_id = int(state.get("bos_id", -1)) | |
| tok.eos_id = int(state.get("eos_id", -1)) | |
| tok.unk_id = int(state.get("unk_id", -1)) | |
| return tok | |
| class TinyConfig: | |
| vocab_size: int | |
| block_size: int = 256 | |
| n_layer: int = 4 | |
| n_head: int = 4 | |
| n_embd: int = 256 | |
| dropout: float = 0.1 | |
| class CausalSelfAttention(nn.Module): | |
| def __init__(self, config: TinyConfig): | |
| super().__init__() | |
| assert config.n_embd % config.n_head == 0 | |
| self.n_head = config.n_head | |
| self.head_dim = config.n_embd // config.n_head | |
| self.qkv = nn.Linear(config.n_embd, 3 * config.n_embd) | |
| self.proj = nn.Linear(config.n_embd, config.n_embd) | |
| self.attn_drop = nn.Dropout(config.dropout) | |
| self.resid_drop = nn.Dropout(config.dropout) | |
| self.register_buffer( | |
| "mask", | |
| torch.tril(torch.ones(config.block_size, config.block_size)).view( | |
| 1, 1, config.block_size, config.block_size | |
| ), | |
| ) | |
| def forward(self, x): | |
| b, t, c = x.size() | |
| qkv = self.qkv(x) | |
| q, k, v = qkv.split(c, dim=2) | |
| q = q.view(b, t, self.n_head, self.head_dim).transpose(1, 2) | |
| k = k.view(b, t, self.n_head, self.head_dim).transpose(1, 2) | |
| v = v.view(b, t, self.n_head, self.head_dim).transpose(1, 2) | |
| att = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim) | |
| att = att.masked_fill(self.mask[:, :, :t, :t] == 0, float("-inf")) | |
| att = F.softmax(att, dim=-1) | |
| att = self.attn_drop(att) | |
| y = att @ v | |
| y = y.transpose(1, 2).contiguous().view(b, t, c) | |
| y = self.resid_drop(self.proj(y)) | |
| return y | |
| class MLP(nn.Module): | |
| def __init__(self, config: TinyConfig): | |
| super().__init__() | |
| self.fc = nn.Linear(config.n_embd, 4 * config.n_embd) | |
| self.proj = nn.Linear(4 * config.n_embd, config.n_embd) | |
| self.drop = nn.Dropout(config.dropout) | |
| def forward(self, x): | |
| x = self.fc(x) | |
| x = F.gelu(x) | |
| x = self.proj(x) | |
| x = self.drop(x) | |
| return x | |
| class Block(nn.Module): | |
| def __init__(self, config: TinyConfig): | |
| super().__init__() | |
| self.ln1 = nn.LayerNorm(config.n_embd) | |
| self.attn = CausalSelfAttention(config) | |
| self.ln2 = nn.LayerNorm(config.n_embd) | |
| self.mlp = MLP(config) | |
| def forward(self, x): | |
| x = x + self.attn(self.ln1(x)) | |
| x = x + self.mlp(self.ln2(x)) | |
| return x | |
| class TinyCausalLM(nn.Module): | |
| def __init__(self, config: TinyConfig): | |
| super().__init__() | |
| self.config = config | |
| self.token_emb = nn.Embedding(config.vocab_size, config.n_embd) | |
| self.pos_emb = nn.Embedding(config.block_size, config.n_embd) | |
| self.drop = nn.Dropout(config.dropout) | |
| self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)]) | |
| self.ln_f = nn.LayerNorm(config.n_embd) | |
| self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) | |
| self.apply(self._init_weights) | |
| def _init_weights(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, idx: torch.Tensor, targets: Optional[torch.Tensor] = None | |
| ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: | |
| b, t = idx.size() | |
| if t > self.config.block_size: | |
| raise ValueError("Sequence length exceeds block size.") | |
| pos = torch.arange(0, t, dtype=torch.long, device=idx.device).unsqueeze(0) | |
| x = self.token_emb(idx) + self.pos_emb(pos) | |
| x = self.drop(x) | |
| for block in self.blocks: | |
| x = block(x) | |
| x = self.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), | |
| ignore_index=-100, | |
| ) | |
| return logits, loss | |
| def generate( | |
| self, | |
| idx: torch.Tensor, | |
| max_new_tokens: int = 128, | |
| temperature: float = 0.8, | |
| top_k: int = 40, | |
| top_p: float = 0.95, | |
| repetition_penalty: float = 1.12, | |
| min_new_tokens: int = 0, | |
| eos_id: int = 2, | |
| stop_token_ids: Optional[List[int]] = None, | |
| ) -> torch.Tensor: | |
| stop_ids = set(stop_token_ids or []) | |
| if eos_id >= 0: | |
| stop_ids.add(eos_id) | |
| start_len = idx.size(1) | |
| for _ in range(max_new_tokens): | |
| idx_cond = idx[:, -self.config.block_size :] | |
| logits, _ = self(idx_cond) | |
| logits = logits[:, -1, :] / max(temperature, 1e-6) | |
| if repetition_penalty > 1.0: | |
| for b in range(idx.size(0)): | |
| seen = set(int(t) for t in idx[b].tolist()) | |
| for token_id in seen: | |
| value = logits[b, token_id] | |
| if value >= 0: | |
| logits[b, token_id] = value / repetition_penalty | |
| else: | |
| logits[b, token_id] = value * repetition_penalty | |
| if top_k > 0: | |
| v, _ = torch.topk(logits, min(top_k, logits.size(-1))) | |
| logits[logits < v[:, [-1]]] = -float("inf") | |
| if 0.0 < top_p < 1.0: | |
| sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1) | |
| sorted_probs = F.softmax(sorted_logits, dim=-1) | |
| cumulative_probs = torch.cumsum(sorted_probs, dim=-1) | |
| sorted_mask = cumulative_probs > top_p | |
| sorted_mask[..., 0] = False | |
| mask = torch.zeros_like(sorted_mask, dtype=torch.bool) | |
| mask.scatter_(dim=-1, index=sorted_indices, src=sorted_mask) | |
| logits = logits.masked_fill(mask, -float("inf")) | |
| probs = F.softmax(logits, dim=-1) | |
| next_token = torch.multinomial(probs, num_samples=1) | |
| idx = torch.cat((idx, next_token), dim=1) | |
| generated = idx.size(1) - start_len | |
| if generated < max(0, int(min_new_tokens)): | |
| continue | |
| if int(next_token.item()) in stop_ids: | |
| break | |
| return idx | |