Make modeling_minireasoner.py compatible with standalone importlib loading and update README snippet
ccb909e verified Download modeling_minireasoner.py from sampath017/MiniReasoner: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/sampath017/MiniReasoner/resolve/main/modeling_minireasoner.py
- Command line
-
hf download hf://sampath017/MiniReasoner/modeling_minireasoner.py
-
curl -L -o modeling_minireasoner.py https://huggingface.co/sampath017/MiniReasoner/resolve/main/modeling_minireasoner.py
12 kB
| """Standalone PyTorch inference module for MiniReasoner (32M RoPE Transformer).""" | |
| from dataclasses import dataclass | |
| import json | |
| from pathlib import Path | |
| import re | |
| from typing import Optional, Union | |
| from tokenizers import Tokenizer | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| EOS = "<|eos|>" | |
| _SCRATCHPAD_RE = re.compile(r"^Work:\s*([^\r\n]+)\r?\nAnswer:\s*(-?\d+)$") | |
| class GPTConfig: | |
| vocab_size: int = 1024 | |
| context_length: int = 1024 | |
| n_layer: int = 10 | |
| n_head: int = 8 | |
| n_embd: int = 512 | |
| rope_theta: float = 10000.0 | |
| pos_encoding: str = "rope" | |
| def _rotate_half(x: torch.Tensor) -> torch.Tensor: | |
| half = x.shape[-1] // 2 | |
| return torch.cat((-x[..., half:], x[..., :half]), dim=-1) | |
| def _apply_rotary_pos_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: | |
| x_fp32 = x.float() | |
| out = (x_fp32 * cos) + (_rotate_half(x_fp32) * sin) | |
| return out.to(dtype=x.dtype) | |
| class RotaryEmbedding(nn.Module): | |
| def __init__(self, dim: int, max_seq_len: int = 1024, theta: float = 10000.0): | |
| super().__init__() | |
| self.dim = dim | |
| self.theta = float(theta) | |
| self.max_seq_len = 0 | |
| self._build_cache(max_seq_len) | |
| def _build_cache(self, seq_len: int, device: Optional[torch.device] = None) -> None: | |
| inv_freq = 1.0 / ( | |
| self.theta ** (torch.arange(0, self.dim, 2, dtype=torch.float32, device=device) / self.dim) | |
| ) | |
| t = torch.arange(seq_len, dtype=torch.float32, device=device) | |
| freqs = torch.outer(t, inv_freq) | |
| emb = torch.cat([freqs, freqs], dim=-1) | |
| self.register_buffer("cos", emb.cos()[None, None, :, :], persistent=False) | |
| self.register_buffer("sin", emb.sin()[None, None, :, :], persistent=False) | |
| self.max_seq_len = seq_len | |
| def forward(self, q: torch.Tensor, k: torch.Tensor, *, offset: int = 0) -> tuple[torch.Tensor, torch.Tensor]: | |
| seq_len = q.size(2) | |
| total_len = offset + seq_len | |
| if total_len > self.max_seq_len: | |
| self._build_cache(max(total_len, self.max_seq_len * 2), device=q.device) | |
| elif self.cos.device != q.device: | |
| self._build_cache(self.max_seq_len, device=q.device) | |
| cos = self.cos[:, :, offset:total_len, :] | |
| sin = self.sin[:, :, offset:total_len, :] | |
| return _apply_rotary_pos_emb(q, cos, sin), _apply_rotary_pos_emb(k, cos, sin) | |
| class CausalSelfAttention(nn.Module): | |
| def __init__(self, config: GPTConfig): | |
| super().__init__() | |
| self.n_head = config.n_head | |
| self.head_dim = config.n_embd // config.n_head | |
| self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd) | |
| self.c_proj = nn.Linear(config.n_embd, config.n_embd) | |
| self.rotary = RotaryEmbedding(self.head_dim, max_seq_len=config.context_length, theta=config.rope_theta) | |
| def forward( | |
| self, | |
| x: torch.Tensor, | |
| *, | |
| past_kv: Optional[tuple[torch.Tensor, torch.Tensor]] = None, | |
| use_cache: bool = False, | |
| ): | |
| batch, length, n_embd = x.shape | |
| if past_kv is not None and length > 1: | |
| raise ValueError("Incremental KV caching expects single-token decode steps (length == 1).") | |
| qkv = self.c_attn(x).reshape(batch, length, 3, self.n_head, self.head_dim) | |
| query, key, value = qkv.permute(2, 0, 3, 1, 4).unbind() | |
| offset = past_kv[0].size(2) if past_kv is not None else 0 | |
| q, k = self.rotary(query, key, offset=offset) | |
| if past_kv is not None: | |
| k = torch.cat((past_kv[0], k), dim=2) | |
| v = torch.cat((past_kv[1], value), dim=2) | |
| else: | |
| v = value | |
| attended = F.scaled_dot_product_attention(q, k, v, is_causal=(past_kv is None)) | |
| out = self.c_proj(attended.transpose(1, 2).reshape(batch, length, n_embd)) | |
| return (out, (k, v)) if use_cache else out | |
| class MLP(nn.Module): | |
| def __init__(self, config: GPTConfig): | |
| 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) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| return self.c_proj(self.gelu(self.c_fc(x))) | |
| class Block(nn.Module): | |
| def __init__(self, config: GPTConfig): | |
| super().__init__() | |
| self.ln_1 = nn.LayerNorm(config.n_embd) | |
| self.attn = CausalSelfAttention(config) | |
| self.ln_2 = nn.LayerNorm(config.n_embd) | |
| self.mlp = MLP(config) | |
| def forward( | |
| self, | |
| x: torch.Tensor, | |
| *, | |
| past_kv: Optional[tuple[torch.Tensor, torch.Tensor]] = None, | |
| use_cache: bool = False, | |
| ): | |
| if use_cache: | |
| attn_out, present_kv = self.attn(self.ln_1(x), past_kv=past_kv, use_cache=True) | |
| x = x + attn_out | |
| return x + self.mlp(self.ln_2(x)), present_kv | |
| x = x + self.attn(self.ln_1(x), past_kv=past_kv) | |
| return x + self.mlp(self.ln_2(x)) | |
| class GPT(nn.Module): | |
| def __init__(self, config: GPTConfig): | |
| super().__init__() | |
| self.config = config | |
| self.transformer = nn.ModuleDict({ | |
| "wte": nn.Embedding(config.vocab_size, config.n_embd), | |
| "h": nn.ModuleList(Block(config) for _ in range(config.n_layer)), | |
| "ln_f": nn.LayerNorm(config.n_embd), | |
| }) | |
| self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) | |
| self.lm_head.weight = self.transformer.wte.weight | |
| def forward( | |
| self, | |
| input_ids: torch.Tensor, | |
| *, | |
| past_kvs: Optional[list[tuple[torch.Tensor, torch.Tensor]]] = None, | |
| use_cache: bool = False, | |
| ): | |
| offset = past_kvs[0][0].size(2) if past_kvs is not None else 0 | |
| if offset + input_ids.size(1) > self.config.context_length: | |
| raise ValueError("Input exceeds the configured context length") | |
| hidden = self.transformer.wte(input_ids) | |
| next_kvs = [] if use_cache else None | |
| for idx, block in enumerate(self.transformer.h): | |
| layer_past = past_kvs[idx] if past_kvs is not None else None | |
| if use_cache: | |
| hidden, present_kv = block(hidden, past_kv=layer_past, use_cache=True) | |
| next_kvs.append(present_kv) | |
| else: | |
| hidden = block(hidden, past_kv=layer_past) | |
| logits = self.lm_head(self.transformer.ln_f(hidden)) | |
| return (logits, next_kvs) if use_cache else logits | |
| def _sample_next_token(logits: torch.Tensor, *, temperature: float = 0.0, top_k: int = 0, top_p: float = 1.0) -> int: | |
| logits = logits.float().clone() | |
| if temperature <= 0.0 or top_k == 1: | |
| return int(logits.argmax().item()) | |
| scaled = logits / temperature | |
| if top_k > 0: | |
| v, _ = torch.topk(scaled, min(top_k, scaled.size(-1))) | |
| scaled[scaled < v[-1]] = -float("Inf") | |
| if 0.0 < top_p < 1.0: | |
| sorted_logits, sorted_indices = torch.sort(scaled, descending=True) | |
| cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1) | |
| remove = cumulative_probs > top_p | |
| remove[..., 1:] = remove[..., :-1].clone() | |
| remove[..., 0] = 0 | |
| scaled[sorted_indices[remove]] = -float("Inf") | |
| return int(torch.multinomial(torch.softmax(scaled, dim=-1), num_samples=1).item()) | |
| class MiniReasoner: | |
| """High-level wrapper for standalone MiniReasoner CoT SFT inference.""" | |
| def __init__(self, model: GPT, tokenizer: Tokenizer, device: torch.device): | |
| self.model = model | |
| self.tokenizer = tokenizer | |
| self.device = device | |
| self.eos_id = tokenizer.token_to_id(EOS) | |
| def from_pretrained( | |
| cls, | |
| repo_id_or_dir: Union[str, Path] = "sampath017/MiniReasoner", | |
| *, | |
| filename: str = "model.pt", | |
| device: str = "auto", | |
| dtype: Optional[torch.dtype] = None, | |
| revision: Optional[str] = None, | |
| ) -> "MiniReasoner": | |
| local_dir = Path(repo_id_or_dir) | |
| if local_dir.is_dir(): | |
| ckpt_path = local_dir / filename | |
| tok_path = local_dir / "tokenizer.json" | |
| cfg_path = local_dir / "config.json" | |
| else: | |
| from huggingface_hub import hf_hub_download | |
| ckpt_path = Path(hf_hub_download(str(repo_id_or_dir), filename=filename, revision=revision)) | |
| tok_path = Path(hf_hub_download(str(repo_id_or_dir), filename="tokenizer.json", revision=revision)) | |
| cfg_path = Path(hf_hub_download(str(repo_id_or_dir), filename="config.json", revision=revision)) | |
| payload = torch.load(ckpt_path, map_location="cpu", weights_only=True) | |
| state = payload["model"] if isinstance(payload, dict) and "model" in payload else payload | |
| if isinstance(payload, dict) and "model_config" in payload: | |
| cfg_dict = payload["model_config"] | |
| else: | |
| raw_cfg = json.loads(cfg_path.read_text(encoding="utf-8")) | |
| cfg_dict = {k: raw_cfg[k] for k in ("vocab_size", "context_length", "n_layer", "n_head", "n_embd", "rope_theta", "pos_encoding")} | |
| tokenizer = ( | |
| Tokenizer.from_str(payload["tokenizer_json"]) | |
| if isinstance(payload, dict) and "tokenizer_json" in payload | |
| else Tokenizer.from_file(str(tok_path)) | |
| ) | |
| if device == "auto": | |
| target_device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| else: | |
| target_device = torch.device(device) | |
| if dtype is None: | |
| if target_device.type == "cuda" and torch.cuda.is_bf16_supported(): | |
| dtype = torch.bfloat16 | |
| else: | |
| dtype = torch.float32 | |
| model = GPT(GPTConfig(**cfg_dict)) | |
| model.load_state_dict(state) | |
| model.to(device=target_device, dtype=dtype).eval() | |
| return cls(model, tokenizer, target_device) | |
| def generate( | |
| self, | |
| prompt: str, | |
| *, | |
| max_new_tokens: int = 180, | |
| temperature: float = 0.0, | |
| top_k: int = 0, | |
| top_p: float = 1.0, | |
| use_cache: bool = True, | |
| ) -> str: | |
| context_length = self.model.config.context_length | |
| ids = self.tokenizer.encode(prompt, add_special_tokens=False).ids | |
| if not ids: | |
| ids = [self.eos_id] | |
| ids = ids[-context_length:] | |
| generated: list[int] = [] | |
| past_kvs = None | |
| for step in range(max_new_tokens): | |
| if use_cache and past_kvs is not None and past_kvs[0][0].size(2) < context_length: | |
| x = torch.tensor([[ids[-1]]], dtype=torch.long, device=self.device) | |
| logits, past_kvs = self.model(x, past_kvs=past_kvs, use_cache=True) | |
| else: | |
| window = ids[-context_length:] | |
| x = torch.tensor([window], dtype=torch.long, device=self.device) | |
| if use_cache and len(window) < context_length: | |
| logits, past_kvs = self.model(x, use_cache=True) | |
| else: | |
| logits = self.model(x) | |
| past_kvs = None | |
| next_id = _sample_next_token(logits[0, -1], temperature=temperature, top_k=top_k, top_p=top_p) | |
| if next_id == self.eos_id: | |
| break | |
| ids.append(next_id) | |
| generated.append(next_id) | |
| if step == max_new_tokens - 1: | |
| break | |
| return self.tokenizer.decode(generated) | |
| def solve(self, question: str, *, max_new_tokens: int = 180) -> dict: | |
| prompt = question if question.endswith("\n") else f"{question}\n" | |
| output = self.generate(prompt, max_new_tokens=max_new_tokens, temperature=0.0, use_cache=True) | |
| match = _SCRATCHPAD_RE.fullmatch(output.strip()) | |
| return { | |
| "prompt": prompt, | |
| "output": output, | |
| "work": match.group(1).strip() if match else None, | |
| "answer": int(match.group(2)) if match else None, | |
| } | |