Download src/generate.py from mlvar/tinystories-gpt-124m: direct link, hf CLI and curl.
- Browser
- Download file 4.67 kB
-
https://huggingface.co/mlvar/tinystories-gpt-124m/resolve/main/src/generate.py
- Command line
-
hf download hf://mlvar/tinystories-gpt-124m/src/generate.py
-
curl -L -o generate.py https://huggingface.co/mlvar/tinystories-gpt-124m/resolve/main/src/generate.py
4.67 kB
| """Text generation using a trained model.""" | |
| import torch | |
| from .config import Config | |
| from .model import GPT | |
| from .tokenizer import Tokenizer | |
| from .utils import load_checkpoint | |
| def generate_from_checkpoint( | |
| checkpoint_path: str, | |
| prompt: str, | |
| max_new_tokens: int = 200, | |
| temperature: float = 0.8, | |
| top_k: int | None = 40, | |
| device: str = "cuda", | |
| dtype_str: str = "bfloat16", | |
| ) -> str: | |
| """Load a checkpoint and generate text from a prompt. | |
| Args: | |
| checkpoint_path: path to a .pt checkpoint. | |
| prompt: starting text for generation. | |
| max_new_tokens: how many tokens to generate. | |
| temperature: sampling temperature (0.0 = greedy). | |
| top_k: restrict sampling to top-k tokens. None to disable. | |
| device: torch device string. | |
| dtype_str: precision for inference. | |
| Returns: | |
| The generated text (prompt + completion). | |
| """ | |
| # Load checkpoint | |
| checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False) | |
| config: Config = checkpoint["config"] | |
| dtype = torch.bfloat16 if dtype_str == "bfloat16" else torch.float32 | |
| if device == "cuda" and not torch.cuda.is_available(): | |
| device = "cpu" | |
| # Build model and load weights | |
| model = GPT(config.model) | |
| model.load_state_dict(checkpoint["model"]) | |
| model.to(device) | |
| if dtype == torch.bfloat16: | |
| model = model.bfloat16() | |
| step = checkpoint.get("step", "unknown") | |
| print(f"Loaded checkpoint from step {step}") | |
| # Tokenize prompt | |
| tokenizer = Tokenizer() | |
| input_ids = torch.tensor([tokenizer.encode(prompt)], device=device) | |
| print(f"Generating {max_new_tokens} tokens (temp={temperature}, top_k={top_k})...") | |
| print() | |
| # Generate | |
| output_ids = model.generate( | |
| input_ids, | |
| max_new_tokens=max_new_tokens, | |
| temperature=temperature, | |
| top_k=top_k, | |
| ) | |
| generated = tokenizer.decode(output_ids[0].tolist()) | |
| return generated | |
| def generate_interactive( | |
| checkpoint_path: str, | |
| device: str = "cuda", | |
| dtype_str: str = "bfloat16", | |
| ): | |
| """Interactive generation loop. | |
| Loads a model and enters a REPL where you can type prompts | |
| and see completions. | |
| Commands: | |
| /temp <value> - change temperature | |
| /topk <value> - change top_k | |
| /len <value> - change max_new_tokens | |
| /quit - exit | |
| """ | |
| # Load model once | |
| checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False) | |
| config: Config = checkpoint["config"] | |
| dtype = torch.bfloat16 if dtype_str == "bfloat16" else torch.float32 | |
| if device == "cuda" and not torch.cuda.is_available(): | |
| device = "cpu" | |
| model = GPT(config.model) | |
| model.load_state_dict(checkpoint["model"]) | |
| model.to(device) | |
| if dtype == torch.bfloat16: | |
| model = model.bfloat16() | |
| model.eval() | |
| step = checkpoint.get("step", "unknown") | |
| tokenizer = Tokenizer() | |
| temperature = 0.8 | |
| top_k = 40 | |
| max_new_tokens = 200 | |
| print(f"Model loaded (step {step}). Type a prompt and press Enter.") | |
| print('Commands: /temp N | /topk N | /len N | /greedy | /quit') | |
| print() | |
| while True: | |
| try: | |
| prompt = input("> ").strip() | |
| except (EOFError, KeyboardInterrupt): | |
| print() | |
| break | |
| if not prompt: | |
| continue | |
| # Handle commands | |
| if prompt.startswith("/"): | |
| parts = prompt.split() | |
| cmd = parts[0].lower() | |
| if cmd == "/quit" or cmd == "/exit": | |
| break | |
| elif cmd == "/temp" and len(parts) == 2: | |
| temperature = float(parts[1]) | |
| print(f" Temperature = {temperature}") | |
| elif cmd == "/topk" and len(parts) == 2: | |
| top_k = int(parts[1]) | |
| print(f" top_k = {top_k}") | |
| elif cmd == "/len" and len(parts) == 2: | |
| max_new_tokens = int(parts[1]) | |
| print(f" max_new_tokens = {max_new_tokens}") | |
| elif cmd == "/greedy": | |
| temperature = 0.0 | |
| top_k = None | |
| print(" Greedy mode (temperature=0)") | |
| else: | |
| print(f" Unknown command: {cmd}") | |
| continue | |
| # Generate | |
| input_ids = torch.tensor([tokenizer.encode(prompt)], device=device) | |
| output_ids = model.generate( | |
| input_ids, | |
| max_new_tokens=max_new_tokens, | |
| temperature=temperature, | |
| top_k=top_k, | |
| ) | |
| generated = tokenizer.decode(output_ids[0].tolist()) | |
| print() | |
| print(generated) | |
| print() | |