Download generate.py from bala5046/UltraSparse-10M: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/bala5046/UltraSparse-10M/resolve/main/generate.py
- Command line
-
hf download hf://bala5046/UltraSparse-10M/generate.py
-
curl -L -o generate.py https://huggingface.co/bala5046/UltraSparse-10M/resolve/main/generate.py
18 kB
| import argparse | |
| import random | |
| import re | |
| import torch | |
| import torch.nn.functional as F | |
| from ultrasparse.config import LedgerConfig, ModelConfig | |
| from ultrasparse.ledger import LedgerController | |
| from ultrasparse.model import UltraSparseLM | |
| from ultrasparse.tokenizer import BPETokenizer | |
| # ============================================================ | |
| # Output cleanup | |
| # ============================================================ | |
| def clean_output(text: str) -> str: | |
| """ | |
| Clean pathological whitespace produced by a small ByteLevel BPE LM. | |
| Important: | |
| This only affects DISPLAYED text. | |
| The underlying generated token sequence is unchanged. | |
| """ | |
| text = text.replace("\r\n", "\n").replace("\r", "\n") | |
| # Remove zero-width/control characters except newline/tab. | |
| text = "".join( | |
| ch | |
| for ch in text | |
| if ch == "\n" | |
| or ch == "\t" | |
| or ch == " " | |
| or ord(ch) >= 32 | |
| ) | |
| # Remove trailing spaces from every line. | |
| text = "\n".join(line.rstrip() for line in text.split("\n")) | |
| # Collapse excessive blank lines. | |
| text = re.sub(r"\n[ \t]*\n[ \t]*\n+", "\n\n", text) | |
| # Collapse pathological runs of spaces. | |
| text = re.sub(r"[ \t]{4,}", " ", text) | |
| # Remove spaces immediately before common punctuation. | |
| text = re.sub(r"[ \t]+([,.;:!?])", r"\1", text) | |
| # Avoid leading/trailing whitespace. | |
| return text.strip() | |
| # ============================================================ | |
| # Sampling | |
| # ============================================================ | |
| def apply_repetition_penalty( | |
| logits: torch.Tensor, | |
| generated_ids, | |
| penalty: float, | |
| window: int = 64, | |
| ): | |
| """ | |
| Apply a standard repetition penalty to recently generated tokens. | |
| """ | |
| if penalty <= 1.0: | |
| return logits | |
| recent = set(generated_ids[-window:]) | |
| for token_id in recent: | |
| value = logits[0, token_id] | |
| if value < 0: | |
| logits[0, token_id] *= penalty | |
| else: | |
| logits[0, token_id] /= penalty | |
| return logits | |
| def apply_top_k( | |
| logits: torch.Tensor, | |
| top_k: int, | |
| ): | |
| if top_k <= 0: | |
| return logits | |
| k = min(top_k, logits.size(-1)) | |
| values, _ = torch.topk(logits, k) | |
| cutoff = values[:, -1].unsqueeze(-1) | |
| return torch.where( | |
| logits < cutoff, | |
| torch.full_like(logits, -float("inf")), | |
| logits, | |
| ) | |
| def apply_top_p( | |
| logits: torch.Tensor, | |
| top_p: float, | |
| ): | |
| if not 0.0 < top_p < 1.0: | |
| return logits | |
| sorted_logits, sorted_indices = torch.sort( | |
| logits, | |
| descending=True, | |
| dim=-1, | |
| ) | |
| sorted_probs = torch.softmax(sorted_logits, dim=-1) | |
| cumulative_probs = torch.cumsum( | |
| sorted_probs, | |
| dim=-1, | |
| ) | |
| remove = cumulative_probs > top_p | |
| # Keep at least the most probable token. | |
| remove[:, 1:] = remove[:, :-1].clone() | |
| remove[:, 0] = False | |
| sorted_logits = sorted_logits.masked_fill( | |
| remove, | |
| -float("inf"), | |
| ) | |
| filtered = torch.full_like(logits, -float("inf")) | |
| filtered.scatter_( | |
| 1, | |
| sorted_indices, | |
| sorted_logits, | |
| ) | |
| return filtered | |
| def sample_token( | |
| logits: torch.Tensor, | |
| temperature: float, | |
| top_k: int, | |
| top_p: float, | |
| repetition_penalty: float, | |
| generated_ids, | |
| ): | |
| """ | |
| Robust temperature + repetition penalty + top-k + top-p sampler. | |
| """ | |
| logits = logits.clone() | |
| logits = apply_repetition_penalty( | |
| logits, | |
| generated_ids, | |
| repetition_penalty, | |
| ) | |
| temperature = max(float(temperature), 1e-5) | |
| logits = logits / temperature | |
| logits = apply_top_k( | |
| logits, | |
| top_k, | |
| ) | |
| logits = apply_top_p( | |
| logits, | |
| top_p, | |
| ) | |
| probs = F.softmax(logits, dim=-1) | |
| # Numerical safety. | |
| if not torch.isfinite(probs).all(): | |
| probs = F.softmax( | |
| torch.nan_to_num( | |
| logits, | |
| nan=0.0, | |
| posinf=0.0, | |
| neginf=-1e9, | |
| ), | |
| dim=-1, | |
| ) | |
| token = torch.multinomial( | |
| probs, | |
| num_samples=1, | |
| ) | |
| return int(token.item()) | |
| # ============================================================ | |
| # Model step | |
| # ============================================================ | |
| def generate_step( | |
| model, | |
| x, | |
| controller, | |
| policy, | |
| generated_ids, | |
| ): | |
| """ | |
| One autoregressive generation step. | |
| Architecture: | |
| input | |
| β | |
| embedding | |
| β | |
| block 0 | |
| β | |
| difficulty + demand heads | |
| β | |
| persistent ledger controller | |
| β | |
| selected depth | |
| β | |
| remaining Transformer blocks | |
| β | |
| RMSNorm | |
| β | |
| tied LM head | |
| β | |
| next-token logits | |
| """ | |
| # -------------------------------------------------------- | |
| # Safety: keep context inside model capacity. | |
| # -------------------------------------------------------- | |
| max_seq_len = model.cfg.max_seq_len | |
| if x.size(1) > max_seq_len: | |
| x = x[:, -max_seq_len:] | |
| # -------------------------------------------------------- | |
| # Embedding | |
| # -------------------------------------------------------- | |
| hidden = model.embed(x) | |
| # -------------------------------------------------------- | |
| # Mandatory probe layer | |
| # -------------------------------------------------------- | |
| hidden = model.blocks[0](hidden) | |
| probe_state = model.norm( | |
| hidden[:, -1] | |
| ) | |
| # -------------------------------------------------------- | |
| # Difficulty prediction | |
| # -------------------------------------------------------- | |
| difficulty = torch.sigmoid( | |
| model.difficulty_head(probe_state) | |
| ).squeeze(-1) | |
| # -------------------------------------------------------- | |
| # Future demand prediction | |
| # -------------------------------------------------------- | |
| demand = torch.sigmoid( | |
| model.demand_head(probe_state) | |
| ).squeeze(-1) | |
| # -------------------------------------------------------- | |
| # Persistent computation controller | |
| # -------------------------------------------------------- | |
| depth = controller.decide_depth( | |
| float(difficulty.item()), | |
| float(demand.item()), | |
| policy, | |
| model.cfg.n_layers, | |
| ) | |
| # Clamp for safety. | |
| depth = max( | |
| 1, | |
| min( | |
| int(depth), | |
| model.cfg.n_layers, | |
| ), | |
| ) | |
| # -------------------------------------------------------- | |
| # Execute selected remaining layers | |
| # | |
| # block 0 already executed. | |
| # Therefore execute [1:depth]. | |
| # -------------------------------------------------------- | |
| for block in model.blocks[1:depth]: | |
| hidden = block(hidden) | |
| # -------------------------------------------------------- | |
| # Final normalization | |
| # -------------------------------------------------------- | |
| state = model.norm( | |
| hidden[:, -1] | |
| ) | |
| # -------------------------------------------------------- | |
| # Tied output projection | |
| # -------------------------------------------------------- | |
| logits = F.linear( | |
| state, | |
| model.tok.weight, | |
| ) | |
| return ( | |
| logits, | |
| float(difficulty.item()), | |
| float(demand.item()), | |
| depth, | |
| ) | |
| # ============================================================ | |
| # Main | |
| # ============================================================ | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="UltraSparse adaptive CPU text generation" | |
| ) | |
| # -------------------------------------------------------- | |
| # Model | |
| # -------------------------------------------------------- | |
| parser.add_argument( | |
| "--checkpoint", | |
| required=True, | |
| ) | |
| parser.add_argument( | |
| "--tokenizer", | |
| default="", | |
| ) | |
| # -------------------------------------------------------- | |
| # Prompt | |
| # -------------------------------------------------------- | |
| parser.add_argument( | |
| "--prompt", | |
| default="UltraSparse is", | |
| ) | |
| parser.add_argument( | |
| "--tokens", | |
| type=int, | |
| default=128, | |
| ) | |
| # -------------------------------------------------------- | |
| # Runtime | |
| # -------------------------------------------------------- | |
| parser.add_argument( | |
| "--threads", | |
| type=int, | |
| default=4, | |
| ) | |
| parser.add_argument( | |
| "--seed", | |
| type=int, | |
| default=42, | |
| ) | |
| # -------------------------------------------------------- | |
| # Adaptive policy | |
| # -------------------------------------------------------- | |
| parser.add_argument( | |
| "--policy", | |
| choices=[ | |
| "fixed", | |
| "difficulty", | |
| "ledger", | |
| "predictive_ledger", | |
| ], | |
| default="predictive_ledger", | |
| ) | |
| parser.add_argument( | |
| "--budget-ratio", | |
| type=float, | |
| default=0.50, | |
| ) | |
| # -------------------------------------------------------- | |
| # Sampling | |
| # -------------------------------------------------------- | |
| parser.add_argument( | |
| "--temperature", | |
| type=float, | |
| default=0.70, | |
| ) | |
| parser.add_argument( | |
| "--top-k", | |
| type=int, | |
| default=40, | |
| ) | |
| parser.add_argument( | |
| "--top-p", | |
| type=float, | |
| default=0.90, | |
| ) | |
| parser.add_argument( | |
| "--repetition-penalty", | |
| type=float, | |
| default=1.10, | |
| ) | |
| # -------------------------------------------------------- | |
| # Output | |
| # -------------------------------------------------------- | |
| parser.add_argument( | |
| "--raw", | |
| action="store_true", | |
| help="Print decoded output without whitespace cleanup", | |
| ) | |
| parser.add_argument( | |
| "--verbose", | |
| action="store_true", | |
| help="Print controller statistics", | |
| ) | |
| args = parser.parse_args() | |
| # ======================================================== | |
| # Reproducibility | |
| # ======================================================== | |
| random.seed(args.seed) | |
| torch.manual_seed(args.seed) | |
| torch.set_num_threads( | |
| max(1, args.threads) | |
| ) | |
| # ======================================================== | |
| # Load checkpoint | |
| # ======================================================== | |
| checkpoint = torch.load( | |
| args.checkpoint, | |
| map_location="cpu", | |
| ) | |
| cfg = ModelConfig( | |
| **checkpoint["config"] | |
| ) | |
| # ======================================================== | |
| # Load tokenizer | |
| # ======================================================== | |
| tokenizer_path = ( | |
| args.tokenizer | |
| if args.tokenizer | |
| else checkpoint["tokenizer"] | |
| ) | |
| tokenizer = BPETokenizer( | |
| tokenizer_path | |
| ) | |
| if tokenizer.vocab_size != cfg.vocab_size: | |
| raise ValueError( | |
| f"Tokenizer/model vocab mismatch: " | |
| f"{tokenizer.vocab_size} != {cfg.vocab_size}" | |
| ) | |
| # ======================================================== | |
| # Load model | |
| # ======================================================== | |
| model = UltraSparseLM(cfg) | |
| model.load_state_dict( | |
| checkpoint["model"] | |
| ) | |
| model.eval() | |
| # ======================================================== | |
| # Encode prompt | |
| # ======================================================== | |
| prompt_ids = tokenizer.encode( | |
| args.prompt, | |
| add_bos=True, | |
| ) | |
| if not prompt_ids: | |
| raise ValueError( | |
| "Prompt produced zero tokens." | |
| ) | |
| # Respect model context. | |
| prompt_ids = prompt_ids[ | |
| -cfg.max_seq_len: | |
| ] | |
| x = torch.tensor( | |
| [prompt_ids], | |
| dtype=torch.long, | |
| ) | |
| generated_ids = list( | |
| prompt_ids | |
| ) | |
| # ======================================================== | |
| # Validate generation settings | |
| # ======================================================== | |
| if args.tokens < 1: | |
| raise ValueError( | |
| "--tokens must be >= 1" | |
| ) | |
| if args.budget_ratio <= 0: | |
| raise ValueError( | |
| "--budget-ratio must be > 0" | |
| ) | |
| if args.top_p <= 0 or args.top_p > 1: | |
| raise ValueError( | |
| "--top-p must be in (0, 1]" | |
| ) | |
| if args.temperature <= 0: | |
| raise ValueError( | |
| "--temperature must be > 0" | |
| ) | |
| if args.repetition_penalty < 1: | |
| raise ValueError( | |
| "--repetition-penalty should be >= 1" | |
| ) | |
| # ======================================================== | |
| # Persistent computation ledger | |
| # ======================================================== | |
| ledger_config = LedgerConfig( | |
| base_budget=args.budget_ratio, | |
| min_compute=1.0 / cfg.n_layers, | |
| normal_compute=max( | |
| 1, | |
| (cfg.n_layers + 1) // 2, | |
| ) / cfg.n_layers, | |
| max_compute=1.0, | |
| max_debt=0.0, | |
| ) | |
| controller = LedgerController( | |
| ledger_config | |
| ) | |
| # ======================================================== | |
| # Generation | |
| # ======================================================== | |
| generated_new_tokens = 0 | |
| eos_reached = False | |
| with torch.no_grad(): | |
| for _ in range(args.tokens): | |
| ( | |
| logits, | |
| difficulty, | |
| demand, | |
| depth, | |
| ) = generate_step( | |
| model=model, | |
| x=x, | |
| controller=controller, | |
| policy=args.policy, | |
| generated_ids=generated_ids, | |
| ) | |
| next_token = sample_token( | |
| logits=logits, | |
| temperature=args.temperature, | |
| top_k=args.top_k, | |
| top_p=args.top_p, | |
| repetition_penalty=args.repetition_penalty, | |
| generated_ids=generated_ids, | |
| ) | |
| generated_ids.append( | |
| next_token | |
| ) | |
| generated_new_tokens += 1 | |
| # ------------------------------------------------ | |
| # EOS | |
| # ------------------------------------------------ | |
| if next_token == tokenizer.eos_id: | |
| eos_reached = True | |
| break | |
| # ------------------------------------------------ | |
| # Append token | |
| # ------------------------------------------------ | |
| next_tensor = torch.tensor( | |
| [[next_token]], | |
| dtype=torch.long, | |
| ) | |
| x = torch.cat( | |
| [x, next_tensor], | |
| dim=1, | |
| ) | |
| # ------------------------------------------------ | |
| # Hard context limit | |
| # ------------------------------------------------ | |
| if x.size(1) > cfg.max_seq_len: | |
| x = x[:, -cfg.max_seq_len:] | |
| # ======================================================== | |
| # Decode | |
| # ======================================================== | |
| decoded = tokenizer.decode( | |
| generated_ids | |
| ) | |
| # Only clean presentation. | |
| if args.raw: | |
| output = decoded | |
| else: | |
| output = clean_output( | |
| decoded | |
| ) | |
| # ======================================================== | |
| # Output | |
| # ======================================================== | |
| print() | |
| print(output) | |
| print() | |
| # ======================================================== | |
| # Statistics | |
| # ======================================================== | |
| if args.verbose: | |
| stats = controller.stats() | |
| print("=" * 60) | |
| print("UltraSparse Generation Statistics") | |
| print("=" * 60) | |
| print( | |
| f"policy : {args.policy}" | |
| ) | |
| print( | |
| f"budget ratio : {args.budget_ratio:.3f}" | |
| ) | |
| print( | |
| f"temperature : {args.temperature:.3f}" | |
| ) | |
| print( | |
| f"top-k : {args.top_k}" | |
| ) | |
| print( | |
| f"top-p : {args.top_p:.3f}" | |
| ) | |
| print( | |
| f"repetition penalty : " | |
| f"{args.repetition_penalty:.3f}" | |
| ) | |
| print( | |
| f"new tokens : " | |
| f"{generated_new_tokens}" | |
| ) | |
| print( | |
| f"EOS reached : " | |
| f"{eos_reached}" | |
| ) | |
| print( | |
| f"low steps : " | |
| f"{stats.low_steps}" | |
| ) | |
| print( | |
| f"normal steps : " | |
| f"{stats.normal_steps}" | |
| ) | |
| print( | |
| f"high steps : " | |
| f"{stats.high_steps}" | |
| ) | |
| print( | |
| f"allocated compute : " | |
| f"{stats.total_compute:.3f}" | |
| f"/{stats.total_budget:.3f}" | |
| ) | |
| print( | |
| f"prevented overspend : " | |
| f"{stats.prevented_overspend}" | |
| ) | |
| print( | |
| f"final ledger : " | |
| f"{controller.ledger.value:.3f}" | |
| ) | |
| print("=" * 60) | |
| if __name__ == "__main__": | |
| main() |