Download hf_core/model_player.py from Aselionism/ASEL1: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/Aselionism/ASEL1/resolve/main/hf_core/model_player.py
- Command line
-
hf download hf://Aselionism/ASEL1/hf_core/model_player.py
-
curl -L -o model_player.py https://huggingface.co/Aselionism/ASEL1/resolve/main/hf_core/model_player.py
10.5 kB
| """ | |
| hf_core/model_player.py | |
| βββββββββββββββββββββββ | |
| ModelPlayer β plays a HuggingFace model with rich token streaming: | |
| β’ Live token-by-token printing with colour + speed bar | |
| β’ Token probability / logprob display | |
| β’ Per-token timing heatmap | |
| β’ Replay mode (re-play saved results) | |
| β’ Batch play from a prompt list | |
| """ | |
| from __future__ import annotations | |
| import sys | |
| import time | |
| import math | |
| from typing import List, Optional, Callable, Dict, Any | |
| from .engine import AICore, GenerationConfig, GenerationResult, TokenEvent | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # ANSI helpers | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class _C: | |
| RESET = "\033[0m" | |
| BOLD = "\033[1m" | |
| DIM = "\033[2m" | |
| CYAN = "\033[96m" | |
| GREEN = "\033[92m" | |
| YELLOW = "\033[93m" | |
| RED = "\033[91m" | |
| MAGENTA= "\033[95m" | |
| BLUE = "\033[94m" | |
| WHITE = "\033[97m" | |
| BG_DK = "\033[40m" | |
| def _prob_colour(logprob: float) -> str: | |
| """Map logprob β colour (green = confident, red = uncertain).""" | |
| p = math.exp(logprob) | |
| if p > 0.7: return _C.GREEN | |
| if p > 0.3: return _C.CYAN | |
| if p > 0.1: return _C.YELLOW | |
| return _C.RED | |
| def _speed_bar(ms: float, max_ms: float = 200.0, width: int = 8) -> str: | |
| filled = int(min(ms / max_ms, 1.0) * width) | |
| bar = "β" * filled + "β" * (width - filled) | |
| colour = _C.GREEN if ms < 50 else _C.YELLOW if ms < 150 else _C.RED | |
| return f"{colour}{bar}{_C.RESET}" | |
| def _header(title: str, width: int = 62) -> str: | |
| pad = (width - len(title) - 2) // 2 | |
| return (f"\n{_C.BOLD}{_C.CYAN}" | |
| f"{'β'*pad} {title} {'β'*pad}" | |
| f"{_C.RESET}\n") | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # ModelPlayer | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class ModelPlayer: | |
| """ | |
| Wraps an AICore and provides rich interactive streaming playback. | |
| Parameters | |
| ---------- | |
| core : Loaded AICore instance. | |
| show_probs : Colour tokens by their log-probability. | |
| show_timing : Show per-token timing bar. | |
| show_ids : Print token IDs inline (verbose mode). | |
| delay : Extra sleep between tokens (seconds) β makes output readable. | |
| """ | |
| def __init__( | |
| self, | |
| core: AICore, | |
| show_probs: bool = True, | |
| show_timing: bool = True, | |
| show_ids: bool = False, | |
| delay: float = 0.0, | |
| ): | |
| self.core = core | |
| self.show_probs = show_probs | |
| self.show_timing = show_timing | |
| self.show_ids = show_ids | |
| self.delay = delay | |
| self._history: List[GenerationResult] = [] | |
| # ββ main play method ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def play( | |
| self, | |
| prompt: str, | |
| config: Optional[GenerationConfig] = None, | |
| label: str = "Generation", | |
| ) -> GenerationResult: | |
| """ | |
| Stream the model output for `prompt` with live rich display. | |
| Returns the full GenerationResult when done. | |
| """ | |
| cfg = config or self.core.config | |
| # ββ header ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(_header(f"π€ {label}")) | |
| print(f" {_C.DIM}Model :{_C.RESET} {_C.BOLD}{self.core.model_name}{_C.RESET}") | |
| print(f" {_C.DIM}Prompt :{_C.RESET} {_C.YELLOW}{prompt[:80]}{'β¦' if len(prompt)>80 else ''}{_C.RESET}") | |
| print(f" {_C.DIM}Temp :{_C.RESET} {cfg.temperature} " | |
| f"{_C.DIM}top_p:{_C.RESET} {cfg.top_p} " | |
| f"{_C.DIM}max_tok:{_C.RESET} {cfg.max_new_tokens}") | |
| print(f"\n {_C.DIM}ββ streaming tokens ββββββββββββββββββββββββββββββββββ{_C.RESET}\n") | |
| print(f" {_C.CYAN}{prompt}{_C.RESET}", end="", flush=True) | |
| collected: List[TokenEvent] = [] | |
| def _render(event: TokenEvent): | |
| collected.append(event) | |
| if event.is_special: | |
| return # skip <|endoftext|> etc. | |
| text = event.token | |
| # colour by probability | |
| if self.show_probs: | |
| col = _prob_colour(event.logprob) | |
| sys.stdout.write(f"{col}{text}{_C.RESET}") | |
| else: | |
| sys.stdout.write(text) | |
| sys.stdout.flush() | |
| if self.delay > 0: | |
| time.sleep(self.delay) | |
| # ββ consume stream ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| t0 = time.perf_counter() | |
| for ev in self.core.stream(prompt, config=cfg): | |
| _render(ev) | |
| elapsed = time.perf_counter() - t0 | |
| result = self.core.last_result | |
| self._history.append(result) | |
| # ββ footer ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| self._print_summary(result) | |
| # optional per-token timing heatmap | |
| if self.show_timing and collected: | |
| self._print_timing_heatmap(collected) | |
| return result | |
| # ββ batch play ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def play_batch( | |
| self, | |
| prompts: List[str], | |
| config: Optional[GenerationConfig] = None, | |
| ) -> List[GenerationResult]: | |
| """Run `play` for each prompt and return all results.""" | |
| results = [] | |
| for i, p in enumerate(prompts, 1): | |
| r = self.play(p, config=config, label=f"Batch {i}/{len(prompts)}") | |
| results.append(r) | |
| return results | |
| # ββ replay from saved result ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def replay(self, result: GenerationResult, speed: float = 1.0) -> None: | |
| """Re-play a saved GenerationResult without hitting the model.""" | |
| print(_header(f"βΆ Replay ({result.model_name})")) | |
| print(f" {_C.CYAN}{result.prompt}{_C.RESET}", end="", flush=True) | |
| for ev in result.tokens: | |
| if ev.is_special: | |
| continue | |
| col = _prob_colour(ev.logprob) if self.show_probs else "" | |
| rst = _C.RESET if self.show_probs else "" | |
| sys.stdout.write(f"{col}{ev.token}{rst}") | |
| sys.stdout.flush() | |
| wait = (ev.elapsed_ms / 1000) / speed | |
| time.sleep(min(wait, 0.15)) # cap replay delay | |
| self._print_summary(result) | |
| # ββ token inspector βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def inspect_tokens(self, text: str) -> None: | |
| """Use the core tokenizer to show token breakdown.""" | |
| self.core.tokenizer.show_tokens(text) | |
| # ββ history βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def history(self) -> List[GenerationResult]: | |
| return list(self._history) | |
| def print_history_summary(self) -> None: | |
| print(_header("π Session History")) | |
| if not self._history: | |
| print(" (empty)\n") | |
| return | |
| for i, r in enumerate(self._history, 1): | |
| trunc = r.prompt[:50].replace("\n", " ") | |
| print(f" [{i}] {_C.YELLOW}{trunc}β¦{_C.RESET} " | |
| f"β {r.total_tokens} tok " | |
| f"@ {r.tokens_per_sec:.1f} t/s " | |
| f"stop={r.stop_reason}") | |
| print() | |
| # ββ internal helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _print_summary(self, r: GenerationResult) -> None: | |
| print(f"\n\n {'β'*58}") | |
| print(f" {_C.BOLD}Summary{_C.RESET}") | |
| print(f" {'β'*58}") | |
| print(f" Tokens generated : {_C.GREEN}{r.total_tokens}{_C.RESET}") | |
| print(f" Elapsed : {_C.CYAN}{r.elapsed_sec:.2f}s{_C.RESET}") | |
| print(f" Speed : {_C.CYAN}{r.tokens_per_sec:.1f} tok/s{_C.RESET}") | |
| print(f" Stop reason : {_C.YELLOW}{r.stop_reason}{_C.RESET}") | |
| print(f" {'β'*58}\n") | |
| def _print_timing_heatmap(self, events: List[TokenEvent]) -> None: | |
| """One-liner heatmap of per-token speed.""" | |
| non_special = [e for e in events if not e.is_special] | |
| if not non_special: | |
| return | |
| max_ms = max(e.elapsed_ms for e in non_special) | |
| print(f" {_C.DIM}Token timing heatmap (green=fast, red=slow):{_C.RESET}") | |
| print(" ", end="") | |
| for e in non_special[:64]: # show first 64 tokens | |
| print(_speed_bar(e.elapsed_ms, max_ms, width=1), end="") | |
| if len(non_special) > 64: | |
| print(f" {_C.DIM}β¦+{len(non_special)-64} more{_C.RESET}", end="") | |
| print() | |
| avg = sum(e.elapsed_ms for e in non_special) / len(non_special) | |
| print(f" {_C.DIM}avg {avg:.1f}ms/tok max {max_ms:.1f}ms/tok{_C.RESET}\n") |