Micro-llm / llm.py
Valeztiro's picture
Micro-llm V1.0.1
673d750 verified
Raw History Blame Contribute Delete
6.07 kB
"""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()