NEO / Generate.py
madhusudhan234's picture
Upload Generate.py
5fad297 verified
Raw History Blame Contribute Delete
22.3 kB
"""
Usage:
.venv/Scripts/python.exe Generate.py
(or) run.bat Generate.py
Options:
--base chat with the pretrained base
(checkpoints/neo_500m_latest.pt) instead of the
fine-tuned chat checkpoint
--checkpoint PATH chat with any specific checkpoint file
--no-learn do not fine-tune on this session's conversations
--learn force self-learning on even when chatting from a
non-chat checkpoint
Chat commands:
/model - list checkpoints, or switch live:
/model base|chat|backup|checkpoints/<file>.pt
/clear - clear conversation history
/think - toggle reasoning-display on/off
/learn - fine-tune on new conversations right now
/forget - delete the saved chat log (unlearned data only)
/exit - quit
Every exchange is logged, and Neo automatically fine-tunes on new
conversations every 5 replies (plus a final catch-up on exit) - but only
while chatting from the fine-tuned chat checkpoint, because self-learning
writes that file and nothing else.
"""
import argparse
import json
import os
import sys
import torch
import sentencepiece as spm
from model.config import neo_500m
from model.transformer import Transformer
# Prevent the broken Windows Store Python alias hang.
if "WindowsApps" in sys.executable or ".venv" not in sys.prefix:
print("ERROR: run with the project venv, not the "
"Windows Store Python alias.")
print(" Use: run.bat Generate.py")
sys.exit(1)
# Windows consoles default to cp1252; Neo's output can contain any Unicode.
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except (AttributeError, ValueError):
pass
parser = argparse.ArgumentParser(
description="Chat with Neo 500M.",
epilog=(
"Examples: run.bat Generate.py --base | "
"run.bat Generate.py --checkpoint "
"checkpoints/neo_500m_sft_final_backup.pt"
),
)
parser.add_argument(
"--checkpoint", "-c",
default=None,
help="Explicit checkpoint file to load (default: best available, "
"preferring the fine-tuned chat checkpoint).",
)
parser.add_argument(
"--base",
action="store_true",
help="Chat with the pretrained base checkpoint "
"(checkpoints/neo_500m_latest.pt) instead of the fine-tuned "
"chat model.",
)
parser.add_argument(
"--no-learn",
action="store_true",
help="Do not fine-tune on this session's conversations.",
)
parser.add_argument(
"--learn",
action="store_true",
help="Force self-learning on even when chatting from a non-chat "
"checkpoint. Updates are still written to the fine-tuned chat "
"checkpoint.",
)
args = parser.parse_args()
# Checkpoint roles. Self-learning (learn_core) always writes CHAT_CHECKPOINT
# and backs it up to CHAT_BACKUP_CHECKPOINT, so those two names must stay in
# sync with learn_core.CHECKPOINT_PATH / CHECKPOINT_BACKUP.
CHAT_CHECKPOINT = "checkpoints/neo_500m_sft_final.pt"
BASE_CHECKPOINT = "checkpoints/neo_500m_latest.pt"
CHAT_BACKUP_CHECKPOINT = "checkpoints/neo_500m_sft_final_backup.pt"
DEFAULT_CHECKPOINTS = [
CHAT_CHECKPOINT,
"checkpoints/neo_500m_sft_latest.pt",
BASE_CHECKPOINT,
]
config = neo_500m()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
if device.type == "cuda":
print(f"GPU: {torch.cuda.get_device_name(0)}")
tokenizer = spm.SentencePieceProcessor(model_file="tokenizer/neo_final.model")
print(f"Tokenizer vocabulary: {tokenizer.vocab_size()}")
print(
"Building model "
f"({config.num_layers} layers, {config.vocab_size} vocab) "
"- initializing weights and moving to GPU, please wait..."
)
model = Transformer(config).to(device)
def find_checkpoint():
"""Checkpoint to chat with: --checkpoint, then --base, then best-first."""
if args.checkpoint:
if not os.path.exists(args.checkpoint):
raise FileNotFoundError(
f"--checkpoint file not found: {args.checkpoint}"
)
return args.checkpoint
if args.base:
if not os.path.exists(BASE_CHECKPOINT):
raise FileNotFoundError(
f"No pretrained base checkpoint at {BASE_CHECKPOINT}. "
"Run `run.bat train.py` first."
)
return BASE_CHECKPOINT
for path in DEFAULT_CHECKPOINTS:
if os.path.exists(path):
return path
raise FileNotFoundError(
"No Neo 500M checkpoint found. Run "
"`run.bat train.py` (then `run.bat train_sft.py` "
"for reasoning) first."
)
def load_weights(model, path):
"""Load a checkpoint's weights into `model` in place; return its step.
Memory-maps the file so training checkpoints (which carry ~2 GB of
optimizer state we never touch here) open cheaply. Non-zipfile (very
old) checkpoints cannot be mapped, so fall back to a normal load.
"""
try:
checkpoint = torch.load(
path, map_location="cpu", weights_only=False, mmap=True
)
except RuntimeError:
checkpoint = torch.load(
path, map_location="cpu", weights_only=False
)
model.load_state_dict(checkpoint["model_state_dict"])
step = checkpoint.get("step", "unknown")
del checkpoint
model.eval()
return step
def peek_step(path):
"""Read only the 'step' field of a checkpoint, without loading weights."""
try:
checkpoint = torch.load(
path, map_location="cpu", weights_only=False, mmap=True
)
except RuntimeError:
checkpoint = torch.load(
path, map_location="cpu", weights_only=False
)
step = checkpoint.get("step", "unknown")
del checkpoint
return step
try:
checkpoint_path = find_checkpoint()
except FileNotFoundError as exc:
print(f"ERROR: {exc}")
sys.exit(1)
print(f"Loading checkpoint: {checkpoint_path}")
step = load_weights(model, checkpoint_path)
model = model.to(
torch.bfloat16
if device.type == "cuda" and torch.cuda.is_bf16_supported()
else torch.float32
)
print(f"Neo 500M loaded from step {step} ({checkpoint_path}).")
if checkpoint_path != CHAT_CHECKPOINT:
print(
"NOTE: this is not the fine-tuned chat checkpoint"
+ (" (it is the pretrained base)"
if checkpoint_path == BASE_CHECKPOINT else "")
+ " - expect raw text continuation, not a chat reply."
)
if checkpoint_path == BASE_CHECKPOINT and isinstance(step, int):
# train.py's default effective batch is 4 * 4 * 512 = 8192 tokens/step.
tokens_seen = (step + 1) * 8192
print(
f"Pretraining progress: ~{tokens_seen / 1e9:.2f}B tokens "
f"({100.0 * tokens_seen / 3_000_000_000:.1f}% of the 3B target) | "
f"resume with: run.bat train.py (continues at step {step + 1:,})."
)
# Self-learning (learn_core) always writes CHAT_CHECKPOINT - and backs it up
# to CHAT_BACKUP_CHECKPOINT - no matter which weights are loaded. So it stays
# off whenever we are chatting from something else, otherwise a chat on the
# pretrained base would overwrite the fine-tuned model with base + a few chat
# updates. `--learn` overrides that deliberately.
def learn_enabled():
"""Is chat self-learning allowed for the currently loaded checkpoint?"""
return (
not args.no_learn
and (checkpoint_path == CHAT_CHECKPOINT or args.learn)
)
LEARN_ALLOWED = learn_enabled()
if args.learn and checkpoint_path != CHAT_CHECKPOINT:
print(
"[learn] forced on: updates are written to "
f"{CHAT_CHECKPOINT} and its backup will be overwritten "
f"({CHAT_BACKUP_CHECKPOINT})."
)
print()
print("Neo is ready.")
print()
print("Commands:")
print(" /model - list checkpoints, or /model base|chat|backup to switch")
print(" /clear - clear conversation")
print(" /think - toggle reasoning display")
print(" /learn - fine-tune on new chats now")
print(" /forget - delete chat log (unlearned data only)")
print(" /exit - quit")
if LEARN_ALLOWED:
print("Auto-learning is ON: Neo fine-tunes on new chats every 5 replies.")
else:
print(
"Auto-learning is OFF for this session (self-learning only writes "
f"{CHAT_CHECKPOINT}, and this session chats from {checkpoint_path}). "
"Exchanges are not logged for learning."
)
print()
show_thinking = True
conversation = []
CHAT_LOG = "data/chat_logs.jsonl"
def log_exchange(user_message, assistant_output):
"""Append one exchange to the learning log (JSON lines)."""
os.makedirs(os.path.dirname(CHAT_LOG), exist_ok=True)
with open(CHAT_LOG, "a", encoding="utf-8") as log_file:
log_file.write(
json.dumps(
{"user": user_message, "assistant": assistant_output},
ensure_ascii=False,
)
+ "\n"
)
# ---- Automatic learning during chat ----
import learn_core # noqa: E402
LEARN_EVERY = 5 # auto-fine-tune after this many new exchanges
LEARN_STEPS = 15 # gradient steps per auto-learning session
exchanges_since_learn = 0
backup_done = False
def auto_learn(trigger="auto"):
"""Fine-tune Neo in-place on newly logged conversations."""
global exchanges_since_learn, backup_done, step
if not LEARN_ALLOWED:
conversations, _, _ = learn_core.load_new_conversations()
if conversations and trigger == "manual":
print(
"[learning] skipped: this session chats from "
f"{checkpoint_path}, but self-learning only writes "
f"{CHAT_CHECKPOINT}. Restart with --learn to override."
)
return
conversations, hashes, _ = learn_core.load_new_conversations()
if not conversations:
if trigger == "manual":
print("[learning] nothing new to learn.")
return
print(f"[learning] fine-tuning on {len(conversations)} new "
"conversation(s) ...")
try:
if not backup_done:
learn_core.backup_checkpoint()
backup_done = True
print("[learning] checkpoint backed up.")
stats = learn_core.fine_tune(
model, config, tokenizer, conversations,
steps=LEARN_STEPS, progress=True,
)
if stats is None:
print("[learning] nothing trainable - skipping.")
return
learn_core.append_corpus(conversations)
learn_core.record_learned(hashes)
if isinstance(step, int):
step += stats["steps"]
learn_core.save_weights(model, step)
exchanges_since_learn = 0
rounds = stats.get("rounds", 1)
extra = f" ({rounds} round(s), wrong answers penalised)" \
if rounds > 1 else ""
print(f"[learning] done - loss {stats['loss_before']:.4f} -> "
f"{stats['loss_after']:.4f}{extra} (saved at step {step})")
except Exception as exc: # never let learning break the chat
print(f"[learning] failed, continuing without it: {exc}")
THOUGHT_START = "<|begin_of_thought|>"
THOUGHT_END = "<|end_of_thought|>"
SOLUTION_START = "<|begin_of_solution|>"
SOLUTION_END = "<|end_of_solution|>"
_SOLUTION_END_IDS = tuple(tokenizer.encode(SOLUTION_END, out_type=int))
_THOUGHT_START_IDS = tuple(tokenizer.encode(THOUGHT_START, out_type=int))
def _apply_repetition_penalty(logits, seen_tokens, penalty):
"""Vectorized repetition penalty over previously seen token IDs."""
if penalty <= 1.0 or not seen_tokens:
return
idx = torch.tensor(list(seen_tokens), device=logits.device)
vals = logits[0, idx]
logits[0, idx] = torch.where(
vals > 0, vals / penalty, vals * penalty
)
def _top_k_filter(logits, top_k=40):
"""Keep only the top-k highest-logit tokens."""
if top_k <= 0:
return logits
top_k = min(top_k, logits.size(-1))
threshold = torch.topk(logits, top_k, dim=-1).values[:, -1].unsqueeze(-1)
return torch.where(
logits < threshold,
torch.full_like(logits, float("-inf")),
logits,
)
def _top_p_filter(logits, top_p=0.90):
"""Nucleus sampling: keep the smallest set with cumulative prob >= top_p."""
if top_p >= 1.0:
return logits
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
cumulative = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens beyond the nucleus, but always keep the top token
# (shift the mask right so the token that crosses top_p survives).
mask = cumulative > top_p
mask[..., 1:] = mask[..., :-1].clone()
mask[..., 0] = False
sorted_logits = sorted_logits.masked_fill(mask, float("-inf"))
filtered = torch.full_like(logits, float("-inf"))
filtered.scatter_(-1, sorted_indices, sorted_logits)
return filtered
def build_prompt(conversation):
"""Format the conversation list into a single prompt string."""
parts = [
f"{'User' if m['role'] == 'user' else 'Neo'}: {m['content']}"
for m in conversation
]
parts.append("Neo:")
return "\n".join(parts)
@torch.inference_mode()
def generate(prompt, max_new_tokens=200, temperature=0.8,
top_k=50, top_p=0.95, repetition_penalty=1.15):
"""Autoregressive generation with KV-cache single-token decoding."""
tokens = tokenizer.encode(prompt, out_type=int)
if not tokens:
return ""
max_ctx = config.max_seq_len - max_new_tokens
if len(tokens) > max_ctx:
tokens = tokens[-max_ctx:]
input_ids = torch.tensor([tokens], dtype=torch.long, device=device)
prompt_length = input_ids.shape[1]
logits, _, past_kvs = model(input_ids, use_cache=True)
logits = logits[:, -1, :].float()
generated = []
seen_tokens = set(tokens)
for _ in range(max_new_tokens):
_apply_repetition_penalty(logits, seen_tokens, repetition_penalty)
logits = logits / max(temperature, 0.01)
logits = _top_k_filter(logits, top_k)
logits = _top_p_filter(logits, top_p)
probabilities = torch.softmax(logits, dim=-1)
next_token = torch.multinomial(probabilities, num_samples=1)
token_id = next_token.item()
if token_id == config.eos_token_id:
break
generated.append(token_id)
seen_tokens.add(token_id)
if len(generated) >= 24 and generated[-12:] == generated[-24:-12]:
break
se_len = len(_SOLUTION_END_IDS)
if se_len > 0 and len(generated) >= se_len:
if generated[-se_len:] == _SOLUTION_END_IDS:
break
ts_len = len(_THOUGHT_START_IDS)
if ts_len > 0 and len(generated) >= ts_len:
if generated[-ts_len:] == _THOUGHT_START_IDS:
text_so_far = tokenizer.decode(generated)
if text_so_far.count(THOUGHT_START) > 1:
break
if prompt_length + len(generated) >= config.max_seq_len:
break
logits, _, past_kvs = model(
next_token, past_kvs=past_kvs, use_cache=True
)
logits = logits[:, -1, :].float()
text = tokenizer.decode(generated).strip()
if SOLUTION_END in text:
text = text.split(SOLUTION_END, 1)[0] + SOLUTION_END
return text
def split_thinking(text):
"""Split model output into (reasoning_thought, final_answer)."""
thought = None
answer = text
if THOUGHT_START in text:
if THOUGHT_END in text:
_, rest = text.split(THOUGHT_START, 1)
thought, rest = rest.split(THOUGHT_END, 1)
thought = thought.strip()
if SOLUTION_START in rest:
answer = rest.split(SOLUTION_START, 1)[1]
if SOLUTION_END in answer:
answer = answer.split(SOLUTION_END, 1)[0]
answer = answer.strip()
else:
thought = text.split(THOUGHT_START, 1)[1].strip()
answer = "..."
return thought, answer
# ---- Main chat loop ----
while True:
try:
user_message = input("You: ")
except (KeyboardInterrupt, EOFError):
print()
print("Exiting...")
break
user_message = user_message.strip()
if not user_message:
continue
cmd = user_message.lower()
if cmd in {"/exit", "/quit", "exit", "quit"}:
print("Exiting...")
break
if cmd == "/model" or cmd.startswith("/model "):
# No `global` needed: the chat loop runs at module level, so the
# assignments below simply rebind the module names that
# learn_enabled() / auto_learn() read.
argument = user_message[len("/model"):].strip()
if not argument:
print("Checkpoints (use /model <name|path>):")
for path in DEFAULT_CHECKPOINTS + [
CHAT_BACKUP_CHECKPOINT,
]:
if not os.path.exists(path):
continue
marker = " (loaded)" if path == checkpoint_path else ""
role = {
BASE_CHECKPOINT: "pretrained base",
CHAT_CHECKPOINT: "fine-tuned chat model",
CHAT_BACKUP_CHECKPOINT: "chat backup",
}.get(path, "fine-tuned (training state)")
try:
shown_step = peek_step(path)
except (RuntimeError, EOFError, KeyError) as exc:
shown_step = f"unreadable ({exc})"
print(f" {path} step={shown_step} [{role}]{marker}")
print(" aliases: base, chat, backup")
print()
else:
name = argument.lower()
target = {
"base": BASE_CHECKPOINT,
"chat": CHAT_CHECKPOINT,
"backup": CHAT_BACKUP_CHECKPOINT,
}.get(name, argument)
if not os.path.exists(target):
print(f"No checkpoint at: {target}")
print("Run /model with no argument to list the options.")
print()
continue
if target == checkpoint_path:
print(f"Already loaded: {target}")
print()
continue
print(f"Loading {target} ...")
try:
new_step = load_weights(model, target)
except (RuntimeError, KeyError, EOFError) as exc:
print(f"Could not load {target}: {exc}")
print("Keeping the currently loaded checkpoint.")
print()
continue
# Drop the conversation so the next reply starts clean under the
# newly loaded weights. learn_enabled() reads checkpoint_path, so
# rebind it before recomputing the guard.
conversation.clear()
checkpoint_path = target
step = new_step
LEARN_ALLOWED = learn_enabled()
print(f"Switched to {target} (step {step}).")
if checkpoint_path == BASE_CHECKPOINT and isinstance(step, int):
tokens_seen = (step + 1) * 8192
print(
f" Pretraining progress: ~{tokens_seen / 1e9:.2f}B "
f"tokens "
f"({100.0 * tokens_seen / 3_000_000_000:.1f}% of 3B) | "
f"resume with: run.bat train.py."
)
print(f" Auto-learning is "
f"{'ON' if LEARN_ALLOWED else 'OFF'} for this session.")
if not LEARN_ALLOWED:
print(" (self-learning only writes "
f"{CHAT_CHECKPOINT})")
print()
continue
if cmd == "/clear":
conversation.clear()
print("Conversation cleared.")
print()
continue
if cmd == "/think":
show_thinking = not show_thinking
print(f"Reasoning display: {show_thinking}")
print()
continue
if cmd == "/learn":
auto_learn("manual")
print()
continue
if cmd == "/forget":
if os.path.exists(CHAT_LOG):
os.remove(CHAT_LOG)
print("Chat log deleted - unlearned conversations forgotten.")
else:
print("No chat log exists.")
print()
continue
conversation.append({"role": "user", "content": user_message})
prompt = build_prompt(conversation)
output = generate(
prompt,
max_new_tokens=200,
temperature=0.8,
top_k=50,
top_p=0.95,
repetition_penalty=1.15,
)
thought, answer = split_thinking(output)
if show_thinking and thought:
print()
print(f"[thinking] {thought}")
conversation.append({"role": "assistant", "content": output})
# Only log exchanges that can teach the model. Logging while learning is
# off (e.g. a chat on the pretrained base) would leave Neo's raw output
# sitting in data/chat_logs.jsonl as "unlearned" data for the next
# Learn.py run to fine-tune the chat checkpoint on.
if LEARN_ALLOWED:
try:
log_exchange(user_message, output)
exchanges_since_learn += 1
except OSError as exc:
print(f"[warning] could not save chat log: {exc}")
print()
print(f"Neo: {answer}")
print()
if exchanges_since_learn >= LEARN_EVERY:
auto_learn()
# Final catch-up learning when the session ends.
print()
auto_learn("manual")
print("Goodbye!")