Download inference.py from Yo272727/victus-tiny-v0.4: direct link, hf CLI and curl.
- Browser
- Download file 6.44 kB
-
https://huggingface.co/Yo272727/victus-tiny-v0.4/resolve/main/inference.py
- Command line
-
hf download hf://Yo272727/victus-tiny-v0.4/inference.py
-
curl -L -o inference.py https://huggingface.co/Yo272727/victus-tiny-v0.4/resolve/main/inference.py
6.44 kB
| """Load Victus Tiny v0.4 and generate text (PyTorch). | |
| Usage: | |
| python inference.py "What is gravity?" | |
| python inference.py "Hello" --temperature 0 --max-new-tokens 48 | |
| Victus Tiny is a custom PyTorch model (model.py) with a custom tokenizer | |
| (tokenizer.py). It is NOT a Hugging Face `transformers` model: load it with this | |
| script, not with AutoModel. Prompt building and stop logic follow the project's | |
| own engine (models/victus-tiny/inference.py in the Nova AI Platform repo). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import sys | |
| from pathlib import Path | |
| from typing import Optional | |
| # absolute(), not resolve(): keeps working when files are symlinks (Hugging Face cache). | |
| HERE = Path(__file__).absolute().parent | |
| sys.path.insert(0, str(HERE)) | |
| from tokenizer import decode, encode, tokenize | |
| DEFAULT_CHECKPOINT = HERE / "victus-tiny-v0.4.pt" | |
| UNK_TOKEN = "<unk>" | |
| CONFIG_KEYS = ("vocab_size", "block_size", "d_model", "n_heads", "n_layers", "dropout") | |
| class PromptPlan: | |
| def __init__(self, ids, truncated=False, unknown_tokens=0): | |
| self.ids = ids | |
| self.prompt_tokens = len(ids) | |
| self.truncated_input = truncated | |
| self.unknown_tokens = unknown_tokens | |
| def build_prompt_plan(messages, vocab, block_size, max_new_tokens) -> PromptPlan: | |
| """Format one user message in the training format ('### User: ...\\n### Victus:') | |
| and fit it into the context window, keeping a reserve for the reply. | |
| `messages` is [{"role": "user", "content": "..."}]; the model was trained on | |
| single-turn User/Victus pairs only, so only the last user message is used.""" | |
| user = [m["content"].strip() for m in messages if m.get("role") == "user" and m.get("content", "").strip()] | |
| if not user: | |
| raise ValueError("messages must contain a non-empty user message") | |
| reserve = max(1, min(int(max_new_tokens), block_size // 2)) | |
| budget = block_size - reserve | |
| header = encode("### User:", vocab) | |
| middle = encode("\n### Victus:", vocab) | |
| user_ids = encode(user[-1], vocab) | |
| room = budget - len(header) - len(middle) | |
| if room < 1: | |
| raise ValueError("context window too small for this generation length") | |
| truncated = len(user_ids) > room | |
| if truncated: | |
| user_ids = user_ids[-room:] | |
| ids = header + user_ids + middle | |
| return PromptPlan(ids, truncated, sum(1 for i in ids if i == 0)) | |
| def _ends_turn(tokens: list) -> int: | |
| """Number of trailing tokens forming a turn boundary (0 if none).""" | |
| if len(tokens) >= 3 and tokens[-3:] == ["#", "#", "#"]: | |
| return 3 | |
| if len(tokens) >= 2 and tokens[-2:] == ["<nl>", "<nl>"]: | |
| return 2 | |
| return 0 | |
| def finalize_text(tokens: list, max_chars: int = 2000) -> str: | |
| """Decode generated tokens, cut at any role marker, cap the length.""" | |
| text = decode([t for t in tokens if t != UNK_TOKEN]) | |
| marker = text.find("###") | |
| if marker != -1: | |
| text = text[:marker] | |
| text = text.strip() | |
| if len(text) > max_chars: | |
| cut = text[:max_chars] | |
| space = cut.rfind(" ") | |
| text = (cut[:space] if space > max_chars // 2 else cut).rstrip() | |
| return text | |
| def load_model(checkpoint_path: Path | str = DEFAULT_CHECKPOINT, device: str = "cpu"): | |
| """Return (model, vocab, config). Uses torch.load(weights_only=True) and a strict state_dict load.""" | |
| import torch | |
| from model import VictusTinyLM | |
| path = Path(checkpoint_path) | |
| if not path.is_file(): | |
| raise FileNotFoundError(f"Checkpoint not found: {path}") | |
| ckpt = torch.load(path, map_location="cpu", weights_only=True) | |
| config, vocab = ckpt["config"], ckpt["vocab"] | |
| if int(config["vocab_size"]) != len(vocab): | |
| raise ValueError("Checkpoint vocab size does not match its config") | |
| model = VictusTinyLM(**{k: config[k] for k in CONFIG_KEYS}) | |
| model.load_state_dict(ckpt["state_dict"]) # strict | |
| model.to(device).eval() | |
| return model, vocab, config | |
| def generate(model, vocab, config, prompt: str, max_new_tokens: int = 64, | |
| temperature: float = 0.7, top_k: int = 25, seed: Optional[int] = None) -> str: | |
| """Generate a reply. temperature <= 0 means greedy decoding. <unk> is never emitted.""" | |
| import torch | |
| block = int(config["block_size"]) | |
| plan = build_prompt_plan([{"role": "user", "content": prompt}], vocab, block, max_new_tokens) | |
| inverse = {i: t for t, i in vocab.items()} | |
| device = next(model.parameters()).device | |
| gen = None | |
| if seed is not None and temperature > 0: | |
| gen = torch.Generator(device=device) | |
| gen.manual_seed(int(seed)) | |
| ids = torch.tensor([plan.ids], dtype=torch.long, device=device) | |
| out: list = [] | |
| with torch.inference_mode(): | |
| for _ in range(int(max_new_tokens)): | |
| logits = model(ids[:, -block:])[:, -1, :] | |
| logits[:, 0] = float("-inf") | |
| if temperature <= 0: | |
| nxt = logits.argmax(dim=-1, keepdim=True) | |
| else: | |
| logits = logits / temperature | |
| if top_k > 0: | |
| k = min(int(top_k), logits.shape[-1]) | |
| logits = logits.masked_fill(logits < torch.topk(logits, k).values[:, [-1]], float("-inf")) | |
| nxt = torch.multinomial(torch.softmax(logits, dim=-1), 1, generator=gen) | |
| ids = torch.cat((ids, nxt), dim=1) | |
| out.append(inverse.get(int(nxt.item()), UNK_TOKEN)) | |
| b = _ends_turn(out) | |
| if b: | |
| del out[-b:] | |
| break | |
| return finalize_text(out) | |
| def main() -> None: | |
| p = argparse.ArgumentParser(description="Run a prompt through Victus Tiny v0.4 (experimental).") | |
| p.add_argument("prompt", nargs="?", default="What is gravity?") | |
| p.add_argument("--checkpoint", type=Path, default=DEFAULT_CHECKPOINT) | |
| p.add_argument("--max-new-tokens", type=int, default=64) | |
| p.add_argument("--temperature", type=float, default=0.7) | |
| p.add_argument("--top-k", type=int, default=25) | |
| p.add_argument("--seed", type=int, default=None) | |
| a = p.parse_args() | |
| model, vocab, config = load_model(a.checkpoint) | |
| n = sum(x.numel() for x in model.parameters()) | |
| print(f"[loaded {a.checkpoint.name}: {n:,} parameters, vocab {len(vocab):,}, block_size {config['block_size']}]") | |
| text = generate(model, vocab, config, a.prompt, a.max_new_tokens, a.temperature, a.top_k, a.seed) | |
| print(text or "[no text generated]") | |
| if __name__ == "__main__": | |
| main() | |