File size: 4,665 Bytes
7f1e014 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | """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()
|