Ruby/model/trainer.py
2025-04-27 11:45:27 -04:00

68 lines
2.0 KiB
Python

import torch
import time
from model.dynamic_expand import expand_model_if_needed, _last_expansion_time, get_optimizer, expand_lock
from model.brain_state import model, tokenizer, DEVICE, loss_fn
from context.context import add_to_context, get_recent_context
LOSS_FILE = "data/logs/loss.log"
VOCAB_GROWTH_FILE = "data/logs/vocab_growth.log"
scheduler = torch.optim.lr_scheduler.StepLR(get_optimizer(), step_size=500, gamma=0.95)
def log_vocab_growth():
with open(VOCAB_GROWTH_FILE, "a", encoding="utf-8") as f:
f.write(f"{time.time()},{len(tokenizer.vocab)}\n")
def log_loss(value: float):
with open(LOSS_FILE, "a", encoding="utf-8") as f:
f.write(f"{time.time()},{round(value, 4)}\n")
def train_on_message(text: str, source: str = "user"):
expand_model_if_needed()
now = time.time()
if now - _last_expansion_time < 5: # If expansion happened within the last 5 seconds
print("[Train] Skipping to stabilize after expansion.")
return
if not expand_lock.acquire(timeout=0.5):
print("[Train] Skipped training due to active expansion.")
return
try:
model.train()
context_texts = get_recent_context(10)
augmented_text = " ".join(context_texts + [text])
tokens = tokenizer.tokenize(augmented_text)
if len(tokens) < 2:
return
max_token_id = model.head.out_features - 1
tokens = [min(t, max_token_id) for t in tokens]
if len(tokens) < 2:
return
tokens = tokens[:128]
input_tensor = torch.tensor(tokens[:-1], dtype=torch.long, device=DEVICE).unsqueeze(0)
target_tensor = torch.tensor(tokens[1:], dtype=torch.long, device=DEVICE).unsqueeze(0)
opt = get_optimizer()
output = model(input_tensor)
loss = loss_fn(output.view(-1, output.size(-1)), target_tensor.view(-1))
opt.zero_grad()
loss.backward()
opt.step()
log_loss(loss.item())
log_vocab_growth()
add_to_context(text, source=source)
finally:
expand_lock.release()