Download eval.py from madhusudhan234/NEO: direct link, hf CLI and curl.
- Browser
- Download file 5.13 kB
-
https://huggingface.co/madhusudhan234/NEO/resolve/main/eval.py
- Command line
-
hf download hf://madhusudhan234/NEO/eval.py
-
curl -L -o eval.py https://huggingface.co/madhusudhan234/NEO/resolve/main/eval.py
5.13 kB
| """Diagnostic: load the SFT checkpoint and generate from test prompts | |
| using the exact same code path as Generate.py (KV cache, samplers). | |
| Prints raw output so we can see what the model actually emits.""" | |
| import os | |
| import sys | |
| import torch | |
| import sentencepiece as spm | |
| from model.config import neo_500m | |
| from model.transformer import Transformer | |
| # Prevent the broken Windows Store Python alias hang. | |
| if ( | |
| "WindowsApps" in sys.executable | |
| or ".venv" not in sys.prefix | |
| ): | |
| print("ERROR: run with the project venv, not the " | |
| "Windows Store Python alias.") | |
| sys.exit(1) | |
| # Windows consoles default to cp1252; force UTF-8 so | |
| # SentencePiece pieces (with the ▁ mark) print fine. | |
| if hasattr(sys.stdout, "reconfigure"): | |
| sys.stdout.reconfigure(encoding="utf-8", errors="replace") | |
| if hasattr(sys.stderr, "reconfigure"): | |
| sys.stderr.reconfigure(encoding="utf-8", errors="replace") | |
| config = neo_500m() | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| print(f"device: {device}") | |
| tokenizer = spm.SentencePieceProcessor( | |
| model_file="tokenizer/neo_final.model" | |
| ) | |
| # --- how are the special tags tokenized? --- | |
| for tag in [ | |
| "<|begin_of_thought|>", | |
| "<|end_of_thought|>", | |
| "<|begin_of_solution|>", | |
| "<|end_of_solution|>", | |
| ]: | |
| ids = tokenizer.encode(tag, out_type=int) | |
| pieces = tokenizer.encode(tag, out_type=str) | |
| print(f"TAG: {tag!r} -> {len(ids)} tokens -> {pieces}") | |
| model = Transformer(config).to(device) | |
| for candidate in [ | |
| "checkpoints/neo_500m_sft_final.pt", | |
| "checkpoints/neo_500m_sft_latest.pt", | |
| "checkpoints/neo_500m_latest.pt", | |
| ]: | |
| if os.path.exists(candidate): | |
| path = candidate | |
| break | |
| print(f"loading: {path}") | |
| checkpoint = torch.load(path, map_location="cpu", weights_only=False) | |
| model.load_state_dict(checkpoint["model_state_dict"]) | |
| print(f"step: {checkpoint.get('step', '?')}") | |
| del checkpoint | |
| model.eval() | |
| model = model.to(torch.bfloat16) | |
| def top_k_filter(logits, top_k=40): | |
| top_k = min(top_k, logits.size(-1)) | |
| values, _ = torch.topk(logits, top_k, dim=-1) | |
| threshold = values[:, -1].unsqueeze(-1) | |
| return torch.where(logits < threshold, torch.full_like(logits, float("-inf")), logits) | |
| def top_p_filter(logits, top_p=0.9): | |
| sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1) | |
| sorted_probs = torch.softmax(sorted_logits, dim=-1) | |
| cumulative = torch.cumsum(sorted_probs, dim=-1) | |
| remove = cumulative > top_p | |
| remove[:, 0] = False | |
| sorted_logits[remove] = float("-inf") | |
| filtered = torch.full_like(logits, float("-inf")) | |
| filtered.scatter_(-1, sorted_indices, sorted_logits) | |
| return filtered | |
| def _detect_repeat(tokens, window=10, min_repeats=3): | |
| if len(tokens) < window * min_repeats: | |
| return False | |
| tail = tokens[-window * min_repeats:] | |
| gram = tuple(tail[-window:]) | |
| for i in range(min_repeats - 1): | |
| start = -window * (i + 2) | |
| end = -window * (i + 1) | |
| if tuple(tail[start:end]) != gram: | |
| return False | |
| return True | |
| def generate(prompt, max_new_tokens=200, temperature=0.3, top_k=20, top_p=0.8, penalty=1.5): | |
| tokens = tokenizer.encode(prompt, out_type=int) | |
| prompt_len = len(tokens) | |
| if prompt_len > config.max_seq_len - max_new_tokens: | |
| tokens = tokens[-(config.max_seq_len - max_new_tokens):] | |
| prompt_len = len(tokens) | |
| input_ids = torch.tensor([tokens], dtype=torch.long, device=device) | |
| logits, _, past_kvs = model(input_ids, use_cache=True) | |
| logits = logits[:, -1, :].float() | |
| generated = [] | |
| for _ in range(max_new_tokens): | |
| prev = set(input_ids[0].tolist()) | |
| for tid in prev: | |
| v = logits[0, tid] | |
| logits[0, tid] = v / penalty if v > 0 else v * penalty | |
| logits = logits / max(temperature, 0.01) | |
| logits = top_k_filter(logits, top_k) | |
| logits = top_p_filter(logits, top_p) | |
| probs = torch.softmax(logits, dim=-1) | |
| nxt = torch.multinomial(probs, num_samples=1) | |
| tid = nxt.item() | |
| if tid == config.eos_token_id: | |
| break | |
| generated.append(tid) | |
| if _detect_repeat(generated, window=10, min_repeats=3): | |
| break | |
| logits, _, past_kvs = model(nxt, past_kvs=past_kvs, use_cache=True) | |
| logits = logits[:, -1, :].float() | |
| input_ids = torch.cat([input_ids, nxt], dim=1) | |
| if prompt_len + len(generated) >= config.max_seq_len: | |
| break | |
| return tokenizer.decode(generated).strip() | |
| prompts = [ | |
| "User: What is 12 + 15?\nNeo:", | |
| "User: Write a Python function named count_vowels that counts vowels in a string.\nNeo:", | |
| "User: What is the capital of France?\nNeo:", | |
| "User: Hi, how are you doing today?\nNeo:", | |
| ] | |
| for p in prompts: | |
| print("\n" + "=" * 70) | |
| print("PROMPT:", p.replace("\n", " | ")) | |
| out = generate(p) | |
| print("RAW OUTPUT:", out) | |
| print("=" * 70) | |
| print("\nEVAL DONE") |