File size: 6,072 Bytes
673d750
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""Chat with a trained GPT checkpoint."""

from __future__ import annotations

import argparse
from pathlib import Path

import torch
from tokenizers import Tokenizer

from model import GPT, GPTConfig
from hf_retrieval import retrieve_examples


MicroLLM = GPT
ModelConfig = GPTConfig
PROJECT_DIR = Path(__file__).resolve().parent
END_OF_TEXT = "<|endoftext|>"
AGENT_SYSTEM_PROMPT = (
	"You are a practical, proactive assistant. Address the user's current goal directly "
	"with an answer or a concrete next step. Do not narrate or repeat the conversation "
	"history. Be honest about uncertainty and limitations. Do not claim to use external "
	"tools or take actions that are not available in this chat."
)
UNCERTAINTY_MARKERS = (
	"i don't know",
	"i do not know",
	"i'm not sure",
	"i am not sure",
	"i'm unsure",
	"i am unsure",
	"i'm uncertain",
	"i am uncertain",
	"i can't answer",
	"i cannot answer",
	"i can't determine",
	"i cannot determine",
	"unable to answer",
	"not certain",
	"hard to say",
	"don't have enough information",
	"do not have enough information",
)


def load_checkpoint(path: Path, device: torch.device) -> tuple[dict, GPT]:
	if not path.is_file():
		raise FileNotFoundError(f"Checkpoint not found: {path}; train the model first")
	checkpoint = torch.load(path, map_location=device, weights_only=False)
	config = GPTConfig(**checkpoint["config"])
	model = GPT(config).to(device)
	model.load_state_dict(checkpoint["model"])
	model.eval()
	return checkpoint, model


def seems_uncertain(response: str) -> bool:
	normalized = response.lower()
	return any(marker in normalized for marker in UNCERTAINTY_MARKERS)


def generate_response(
	model: GPT,
	tokenizer: Tokenizer,
	device: torch.device,
	prompt: str,
	max_new_tokens: int,
	temperature: float,
	top_k: int,
	eos_token_id: int,
) -> str:
	prompt_ids = tokenizer.encode(prompt).ids
	input_ids = torch.tensor(
		[prompt_ids[-model.config.context_length :]], dtype=torch.long, device=device
	)
	prompt_length = input_ids.size(1)
	with torch.inference_mode(), torch.autocast(
		device_type=device.type, dtype=torch.float16, enabled=device.type == "cuda"
	):
		output = model.generate(
			input_ids,
			max_new_tokens=max_new_tokens,
			temperature=temperature,
			top_k=top_k,
			eos_token_id=eos_token_id,
		)
	return tokenizer.decode(
		output[0, prompt_length:].tolist(), skip_special_tokens=True
	).strip()


def parse_args() -> argparse.Namespace:
	parser = argparse.ArgumentParser(description=__doc__)
	parser.add_argument("--checkpoint", type=Path, default=PROJECT_DIR / "agent-checkpoints" / "latest.pt")
	parser.add_argument("--tokenizer", type=Path, default=PROJECT_DIR / "agent-tokenizer.json")
	parser.add_argument("--max-new-tokens", type=int, default=120)
	parser.add_argument("--temperature", type=float, default=0.8)
	parser.add_argument("--top-k", type=int, default=40)
	parser.add_argument("--device", choices=("auto", "cuda", "cpu"), default="auto")
	return parser.parse_args()


def main() -> None:
	args = parse_args()
	if not args.checkpoint.is_file():
		raise SystemExit(f"Checkpoint not found: {args.checkpoint}; train the model first")
	if not args.tokenizer.is_file():
		raise SystemExit(f"Tokenizer not found: {args.tokenizer}")
	if args.max_new_tokens < 1 or args.temperature <= 0 or args.top_k < 1:
		raise SystemExit("max-new-tokens, temperature, and top-k must be positive")
	if args.device == "cuda" and not torch.cuda.is_available():
		raise SystemExit("CUDA was requested but is unavailable")
	device = torch.device(
		"cuda" if args.device == "cuda" or (args.device == "auto" and torch.cuda.is_available()) else "cpu"
	)
	checkpoint, model = load_checkpoint(args.checkpoint, device)
	tokenizer = Tokenizer.from_file(str(args.tokenizer))
	eos_token_id = tokenizer.token_to_id(END_OF_TEXT)
	if eos_token_id is None:
		raise SystemExit(f"Tokenizer is missing {END_OF_TEXT}")

	print(f"Loaded {args.checkpoint} at step {checkpoint.get('step', 'unknown')} on {device}.")
	print("Type /reload to load the latest checkpoint, /reset to clear the conversation, or /quit to exit.")
	history = ""
	while True:
		try:
			user_text = input("You: ").strip()
		except (EOFError, KeyboardInterrupt):
			print()
			break
		if not user_text:
			continue
		if user_text.lower() in {"/quit", "/exit"}:
			break
		if user_text.lower() == "/reset":
			history = ""
			print("Conversation cleared.")
			continue
		if user_text.lower() == "/reload":
			try:
				checkpoint, updated_model = load_checkpoint(args.checkpoint, device)
			except (FileNotFoundError, RuntimeError, KeyError, ValueError) as error:
				print(f"Could not reload checkpoint: {error}")
				continue
			model = updated_model
			print(f"Loaded checkpoint at step {checkpoint.get('step', 'unknown')}.")
			continue

		prompt = f"System: {AGENT_SYSTEM_PROMPT}\n{history}User: {user_text}\nAssistant:"
		response = generate_response(
			model,
			tokenizer,
			device,
			prompt,
			args.max_new_tokens,
			args.temperature,
			args.top_k,
			eos_token_id,
		)
		if seems_uncertain(response):
			examples = retrieve_examples(user_text)
			if examples:
				examples_text = "\n\n".join(
					f"Example user request: {example_user[:700]}\n"
					f"Example assistant response: {example_assistant[:700]}"
					for example_user, example_assistant in examples
				)
				retry_prompt = (
					f"System: {AGENT_SYSTEM_PROMPT} Retrieved examples are demonstrations, "
					"not verified sources of facts. Use them only as helpful patterns; answer "
					"the current request directly and remain honest if uncertain.\n"
					f"{history}Related examples from the No Robots training data:\n"
					f"{examples_text}\n\nUser: {user_text}\nAssistant:"
				)
				retry_response = generate_response(
					model,
					tokenizer,
					device,
					retry_prompt,
					args.max_new_tokens,
					args.temperature,
					args.top_k,
					eos_token_id,
				)
				if retry_response:
					response = retry_response
		print(f"Model: {response}")
		history += f"User: {user_text}\nAssistant: {response}\n"


if __name__ == "__main__":
	main()