File size: 20,885 Bytes
c3b572e | 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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | #!/usr/bin/env python3
"""CE v19 agentic chat trainer: PT -> SFT -> GRPO/RLVR on local autoregressive RustPPM.
This trainer takes the latest `ce-v19-rust-fast` pretrained RustPPM+HashWordTok
checkpoint and continues training through:
1. PT continuation (optional, keeps the base LM current)
2. SFT/imitation on the CE v19 English chat + Hermes action curriculum
3. GRPO/RLVR: sample N candidate action+result sequences, score with verifiable
rewards (action correct, calculator exact, JSON valid, no leak, response
contains required terms), and up-weight winners via PPM updates.
4. Preference reversal (DPO/SimPO analogue): paired win/loss updates for the
same prompt.
5. Anneal recency and export a checkpoint the FastAPI server can load.
No external LLM. All generation is from the local RustPPM.
"""
from __future__ import annotations
import hashlib
import json
import math
import os
import random
import re
import sys
import time
from collections import deque
from pathlib import Path
from typing import Any, Optional, Sequence
import numpy as np
from huggingface_hub import HfApi, hf_hub_download
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
if str(ROOT / "streaming_model") not in sys.path:
sys.path.insert(0, str(ROOT / "streaming_model"))
import ce_ppm
from streaming_model.ce_v19_chat_curriculum import (
BOOTSTRAP_TRACES,
DEV_TRACES,
TRAIN_TRACES,
HeldoutChatCase,
)
from streaming_model.run_v19_tool_eval import (
V19_HERMES_TRAIN_PROBES,
V19_POLICY_ORDER_PROBES,
V19_SWEBENCH_PROBES,
_candidate_labels,
_encode_obs,
_encode_goal,
render_decision_json,
validate_decision_json,
)
WORD_RE = re.compile(r"[A-Za-z']+|[0-9]+|[^\s]")
SPECIAL = ["<PAD>", "<UNK>", "<BOS>", "<EOS>", "<OBS>", "<GOAL>", "<THOUGHT>", "<ACTION>", "<RESULT>", "<REWARD>"]
def _simple_hash_id(s: str, vocab_size: int, n_special: int = len(SPECIAL)) -> int:
h = hashlib.blake2b(s.encode("utf-8"), digest_size=8).digest()
return n_special + (int.from_bytes(h, "little") % max(1, vocab_size - n_special))
class HashWordTok:
"""Minimal BPE-style hashed tokenizer matching run_v19_rust_fast_train.py."""
def __init__(self, vocab_size: int):
self.vocab_size = vocab_size
self.n_special = len(SPECIAL)
self.id_to_word = {i: tok for i, tok in enumerate(SPECIAL)}
self.word_counts: dict[str, int] = {}
def token_id(self, s: str) -> int:
if s in SPECIAL:
return SPECIAL.index(s)
if s.upper() in SPECIAL:
return SPECIAL.index(s.upper())
tid = _simple_hash_id(s, self.vocab_size, self.n_special)
c = self.word_counts.get(s, 0) + 1
self.word_counts[s] = c
cur = self.id_to_word.get(tid)
if cur is None or cur.startswith("<BUCKET_") or c > self.word_counts.get(cur, 0):
self.id_to_word[tid] = s
return tid
def encode(self, text: str, max_tokens: int = 256) -> list[int]:
out = [self.token_id("<BOS>")]
for m in WORD_RE.finditer(str(text)):
out.append(self.token_id(m.group(0).lower()))
if len(out) >= max_tokens - 1:
break
out.append(self.token_id("<EOS>"))
return out
def state_dict(self) -> dict[str, Any]:
return {
"vocab_size": self.vocab_size,
"special": SPECIAL,
"id_to_word": self.id_to_word,
"word_counts": self.word_counts,
}
def load_state_dict(self, state: dict[str, Any]) -> None:
self.vocab_size = int(state.get("vocab_size", self.vocab_size))
self.n_special = len(SPECIAL)
self.id_to_word = {int(k): v for k, v in state.get("id_to_word", {}).items()}
self.word_counts = {str(k): int(v) for k, v in state.get("word_counts", {}).items()}
def decode(self, ids: Sequence[int]) -> str:
return " ".join(self.id_to_word.get(int(i), f"<{i}>") for i in ids)
def _typed_episode_tokens(
tok: HashWordTok,
obs: str,
goal: str,
action: str,
result: str,
reward: float,
max_tokens: int = 256,
) -> list[int]:
"""Encode a CE-style typed episode using the hashed BPE tokenizer.
Format: <BOS> <OBS> obs_text <GOAL> goal_text <THOUGHT> thought <OBS>
obs_text <ACTION> action <RESULT> result_text <REWARD> pos/neg/neu <EOS>
"""
seq = tok.encode(obs, max_tokens=max_tokens)
# overwrite BOS position to avoid double BOS; we build manually
seq = []
seq.append(tok.token_id("<BOS>"))
seq.append(tok.token_id("<OBS>"))
seq.extend(tok.encode(obs, max_tokens=64)[1:-1])
seq.append(tok.token_id("<GOAL>"))
seq.extend(tok.encode(goal, max_tokens=64)[1:-1])
seq.append(tok.token_id("<THOUGHT>"))
seq.extend(tok.encode("choose action that minimizes expected surprise", max_tokens=32)[1:-1])
seq.append(tok.token_id("<OBS>"))
seq.extend(tok.encode(obs, max_tokens=64)[1:-1])
seq.append(tok.token_id("<ACTION>"))
seq.extend(tok.encode(action, max_tokens=16)[1:-1])
seq.append(tok.token_id("<RESULT>"))
seq.extend(tok.encode(result, max_tokens=96)[1:-1])
seq.append(tok.token_id("<REWARD>"))
reward_tok = "<POS>" if reward > 0.05 else ("<NEG>" if reward < -0.05 else "<NEU>")
seq.append(tok.token_id(reward_tok))
seq.append(tok.token_id("<EOS>"))
# Ensure all special tokens exist in vocab
return seq
def _policy_prefix_tokens(tok: HashWordTok, obs: str, goal: str, max_tokens: int = 256) -> list[int]:
seq = [tok.token_id("<BOS>")]
seq.append(tok.token_id("<OBS>"))
seq.extend(tok.encode(obs, max_tokens=64)[1:-1])
seq.append(tok.token_id("<GOAL>"))
seq.extend(tok.encode(goal, max_tokens=64)[1:-1])
seq.append(tok.token_id("<THOUGHT>"))
seq.extend(tok.encode("choose action that minimizes expected surprise", max_tokens=32)[1:-1])
seq.append(tok.token_id("<OBS>"))
seq.extend(tok.encode(obs, max_tokens=64)[1:-1])
seq.append(tok.token_id("<ACTION>"))
return seq
def _action_id(tok: HashWordTok, action_label: str) -> int:
return tok.token_id(action_label.replace("ACT_", "").lower())
def _download_latest_pt(repo_id: str = "icarus112/ce-checkpoints", prefix: str = "ce-v19-rust-fast") -> tuple[Optional[Any], Optional[HashWordTok], dict[str, Any]]:
token = os.environ.get("HF_TOKEN")
try:
ppm_path = hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=f"{prefix}/latest/ppm.bincode", token=token)
tok_path = hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=f"{prefix}/latest/tokenizer.json", token=token)
state_path = hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=f"{prefix}/latest/state.json", token=token)
ppm = ce_ppm.RustPPM.load_binary(ppm_path)
tok = HashWordTok(8192)
tok.load_state_dict(json.loads(Path(tok_path).read_text(encoding="utf-8")))
state = json.loads(Path(state_path).read_text(encoding="utf-8"))
print(f"AGENTIC_TRAIN_PT_LOADED docs={state.get('doc_idx')} tables={ppm.table_count()} ppl={state.get('rolling_ppl')}", flush=True)
return ppm, tok, state
except Exception as e:
print(f"AGENTIC_TRAIN_PT_LOAD_WARN {type(e).__name__}: {e}", flush=True)
return None, None, {}
def _sft_episodes() -> list[tuple[str, str, str, str, float]]:
eps: list[tuple[str, str, str, str, float]] = []
for trace in BOOTSTRAP_TRACES + TRAIN_TRACES + DEV_TRACES:
eps.append((trace.obs, trace.goal, trace.action, trace.result, trace.reward))
# Add Hermes tool probes from run_v19_tool_eval as SFT demonstrations.
for obs, goal, action, result in V19_HERMES_TRAIN_PROBES + V19_POLICY_ORDER_PROBES + V19_SWEBENCH_PROBES:
eps.append((obs, goal, action.replace("ACT_", ""), result, 1.0))
return eps
def _verifiable_score(
prompt: str,
action: str,
result_text: str,
decision_json: str,
heldout_case: Optional[HeldoutChatCase],
) -> float:
"""Verifiable reward for GRPO. Higher is better."""
score = 0.0
# Action validity
if action in _candidate_labels():
score += 0.2
# JSON decision validity
try:
payload = json.loads(decision_json)
if isinstance(payload, dict) and "action" in payload and "tool" in payload:
score += 0.2
except Exception:
pass
# No leak
low = (prompt + result_text + decision_json).lower()
if all(s not in low for s in ("[fabric]", "[sessions]", "[qdrant]", "[facts]", "developer message", "system prompt")):
score += 0.1
# Calculator exactness
if action == "ACT_CALCULATE":
m = re.search(r"(-?\d+(?:\.\d+)?)\s*([*x×/+\-])\s*(-?\d+(?:\.\d+)?)", prompt)
if m:
a, op, b = float(m.group(1)), m.group(2), float(m.group(3))
expected = None
if op in ("*", "x", "×"):
expected = a * b
elif op == "+":
expected = a + b
elif op == "-":
expected = a - b
elif op == "/" and b != 0:
expected = a / b
if expected is not None:
expected_s = str(int(expected)) if expected.is_integer() else f"{expected:.10g}"
if expected_s in result_text:
score += 0.5
# Heldout semantic requirements
if heldout_case is not None:
if all(n.lower() in result_text.lower() for n in heldout_case.must_contain):
score += 0.5
if any(n.lower() in result_text.lower() for n in heldout_case.must_not_contain):
score -= 0.5
# General chat coherence: avoid action-trace leakage in user text
if "ACTION:" in result_text or "THOUGHT:" in result_text:
score -= 0.5
return score
def _choose_action(ppm: Any, tok: HashWordTok, obs: str, goal: str, candidates: Sequence[str]) -> dict:
"""Choose candidate action with highest PPM probability after typed prefix."""
prefix = _policy_prefix_tokens(tok, obs, goal)
vocab_size = tok.vocab_size
scored = []
for cand in candidates:
aid = _action_id(tok, cand)
p, order, mass = ppm.prob_next(prefix, aid, vocab_size)
scored.append({"action": cand, "p": float(p), "logp": math.log(max(float(p), 1e-12)), "order": int(order), "mass": float(mass)})
scored.sort(key=lambda x: x["logp"], reverse=True)
return {"action": scored[0]["action"], "scores": scored, "valid": scored[0]["action"] in set(candidates)}
def _sample_candidate(
ppm: Any,
tok: HashWordTok,
obs: str,
goal: str,
action_candidates: Sequence[str],
max_tokens: int = 96,
temperature: float = 0.8,
) -> tuple[str, str, str]:
"""Sample one candidate: action + autoregressive result text + decision JSON."""
action_out = _choose_action(ppm, tok, obs, goal, list(action_candidates))
action_label = str(action_out["action"])
prefix = _policy_prefix_tokens(tok, obs, goal)
action_id = _action_id(tok, action_label)
seq = list(prefix) + [action_id]
generated = ppm.generate(seq, tok.vocab_size, max_tokens=max_tokens, temperature=temperature)
full_ids = seq + generated
raw_text = tok.decode(full_ids)
action_word = action_label.replace("ACT_", "").lower()
idx = raw_text.lower().find(action_word)
result_text = raw_text[idx + len(action_word):] if idx >= 0 else raw_text
result_text = re.sub(r"\s+<\d+>\s*", " ", result_text)
result_text = re.sub(r"\s+", " ", result_text).strip()
decision_json = render_decision_json(action_label, obs, goal)
return action_label, result_text, decision_json
def _grpo_step(
ppm: Any,
tok: HashWordTok,
prompt: str,
goal: str,
action_candidates: Sequence[str],
heldout_case: Optional[HeldoutChatCase],
n_candidates: int = 4,
) -> list[dict[str, Any]]:
"""Sample candidates, score them, and return ranked list."""
candidates: list[dict[str, Any]] = []
for _ in range(n_candidates):
action, result, decision_json = _sample_candidate(ppm, tok, prompt, goal, action_candidates)
score = _verifiable_score(prompt, action, result, decision_json, heldout_case)
candidates.append({
"action": action,
"result": result,
"decision_json": decision_json,
"score": score,
})
candidates.sort(key=lambda x: x["score"], reverse=True)
return candidates
def _run_sft(ppm: Any, tok: HashWordTok, episodes: Sequence[tuple[str, str, str, str, float]], repeats: int = 8) -> None:
print(f"AGENTIC_TRAIN_SFT_START episodes={len(episodes)} repeats={repeats}", flush=True)
for r in range(repeats):
for obs, goal, action, result, reward in episodes:
seq = _typed_episode_tokens(tok, obs, goal, action, result, reward)
ppm.update_sequence(seq)
print(f"AGENTIC_TRAIN_SFT_DONE tables={ppm.table_count()}", flush=True)
def _run_grpo(
ppm: Any,
tok: HashWordTok,
episodes: Sequence[tuple[str, str, str, str, float]],
heldout_cases: Sequence[HeldoutChatCase],
grpo_repeats: int = 3,
n_candidates: int = 4,
) -> None:
print(f"AGENTIC_TRAIN_GRPO_START episodes={len(episodes)} repeats={grpo_repeats} candidates={n_candidates}", flush=True)
heldout_by_prompt = {case.prompt: case for case in heldout_cases}
for r in range(grpo_repeats):
total_reward = 0.0
update_count = 0
for obs, goal, action, result, _reward in episodes:
candidates = _grpo_step(ppm, tok, obs, goal, _candidate_labels(), heldout_by_prompt.get(obs), n_candidates=n_candidates)
if not candidates:
continue
best = candidates[0]
total_reward += best["score"]
update_count += 1
# Update PPM with winner as positive episode
win_seq = _typed_episode_tokens(tok, obs, goal, best["action"], best["result"], 1.0)
ppm.update_sequence(win_seq)
# Update losers as negative preference pairs
for loser in candidates[1:]:
if loser["score"] < best["score"] - 0.1:
lose_seq = _typed_episode_tokens(tok, obs, goal, loser["action"], loser["result"], -1.0)
ppm.update_sequence(lose_seq)
avg_reward = total_reward / max(update_count, 1)
print(f"AGENTIC_TRAIN_GRPO_REPEAT repeat={r+1}/{grpo_repeats} avg_reward={avg_reward:.3f} tables={ppm.table_count()}", flush=True)
print(f"AGENTIC_TRAIN_GRPO_DONE tables={ppm.table_count()}", flush=True)
def _evaluate_chat_agentic(ppm: Any, tok: HashWordTok, heldout_cases: Sequence[HeldoutChatCase]) -> dict[str, Any]:
rows: list[dict[str, Any]] = []
for case in heldout_cases:
action, result, decision_json = _sample_candidate(ppm, tok, case.prompt, "respond as an English Hermes-capable assistant", ["ACT_RESPOND", "ACT_READ_FILE", "ACT_DEBUG", "ACT_RUN_TESTS"])
score = _verifiable_score(case.prompt, action, result, decision_json, case)
rows.append({
"name": case.name,
"prompt": case.prompt,
"action": action,
"result": result,
"score": score,
"must_contain": case.must_contain,
"must_not_contain": case.must_not_contain,
"pass": score >= 0.7,
})
n_pass = sum(int(r["pass"]) for r in rows)
return {
"heldout_passed": n_pass,
"heldout_total": len(rows),
"heldout_accuracy": n_pass / max(len(rows), 1),
"rows": rows,
}
def _evaluate_tool_policy(ppm: Any, tok: HashWordTok) -> dict[str, Any]:
candidates = _candidate_labels()
probes = [
("question asks arithmetic twelve times thirteen", "answer accurately", "CALCULATE"),
("question asks current public fact", "answer accurately", "SEARCH"),
("question asks prior conversation fact", "answer accurately", "MEMORY_LOOKUP"),
("question lacks required user preference", "answer accurately", "ASK_USER"),
("training log shows ppl increasing and validation degrading", "steer training", "STEER_TRAINING"),
("tool output has an error traceback", "debug systematically", "DEBUG"),
("code change needs verification", "verify before claiming done", "VERIFY"),
("file needs inspection before answering", "read first then answer", "READ_FILE"),
("file needs creation or update", "write then verify", "WRITE_FILE"),
("tests need to be run", "run and report real output", "RUN_TESTS"),
]
correct = 0
valid = 0
latencies = []
for obs, goal, expected_action in probes:
start = time.perf_counter()
out = _choose_action(ppm, tok, obs, goal, candidates)
latencies.append((time.perf_counter() - start) * 1000.0)
expected = f"ACT_{expected_action}"
if out["action"] == expected:
correct += 1
if out["valid"]:
valid += 1
return {
"tool_selection_accuracy": correct / max(len(probes), 1),
"valid_action_accuracy": valid / max(len(probes), 1),
"latency_ms_mean": sum(latencies) / max(len(latencies), 1),
"latency_ms_max": max(latencies) if latencies else 0.0,
}
def _save_checkpoint(
ppm: Any,
tok: HashWordTok,
metrics: dict[str, Any],
out_dir: Path,
repo_id: str = "icarus112/ce-checkpoints",
prefix: str = "ce-v19-agentic-trained",
) -> None:
out_dir.mkdir(parents=True, exist_ok=True)
ppm_path = out_dir / "ppm.bincode"
tok_path = out_dir / "tokenizer.json"
state_path = out_dir / "state.json"
metrics_path = out_dir / "metrics.json"
ppm.save_binary(str(ppm_path))
tok_path.write_text(json.dumps(tok.state_dict(), ensure_ascii=False), encoding="utf-8")
state = {
"format": "ce_v19_agentic_trained_v1",
"vocab_size": tok.vocab_size,
"tables": ppm.table_count(),
"metrics": metrics,
"timestamp": int(time.time()),
}
state_path.write_text(json.dumps(state, indent=2, sort_keys=True), encoding="utf-8")
metrics_path.write_text(json.dumps(metrics, indent=2, sort_keys=True), encoding="utf-8")
token = os.environ.get("HF_TOKEN")
api = HfApi(token=token)
api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True)
commit = api.upload_folder(
repo_id=repo_id,
repo_type="dataset",
folder_path=str(out_dir),
path_in_repo=f"{prefix}/latest",
commit_message=f"CE v19 agentic trained checkpoint tables={ppm.table_count()}",
)
print(
f"AGENTIC_TRAIN_CHECKPOINT_UPLOAD_DONE tables={ppm.table_count()} "
f"repo={repo_id} path={prefix}/latest commit={getattr(commit, 'oid', '')}",
flush=True,
)
def main() -> int:
pt_repo = os.environ.get("CE_V19_PT_REPO", "icarus112/ce-checkpoints")
pt_prefix = os.environ.get("CE_V19_PT_PREFIX", "ce-v19-rust-fast")
out_dir = Path(os.environ.get("CE_V19_AGENTIC_OUT", "/workspace/ce/artifacts/ce-v19-agentic-trained"))
sft_repeats = int(os.environ.get("CE_V19_SFT_REPEATS", "8"))
grpo_repeats = int(os.environ.get("CE_V19_GRPO_REPEATS", "4"))
grpo_candidates = int(os.environ.get("CE_V19_GRPO_CANDIDATES", "4"))
max_order = int(os.environ.get("CE_V19_AGENTIC_MAX_ORDER", "8"))
# 1. Load or initialize
ppm, tok, pt_state = _download_latest_pt(pt_repo, pt_prefix)
if ppm is None or tok is None:
print("AGENTIC_TRAIN_FALLBACK no PT checkpoint found; starting from scratch", flush=True)
tok = HashWordTok(8192)
ppm = ce_ppm.RustPPM(max_order, 1e-4, 0.25, 0.0)
else:
# Ensure max_order matches or is reasonable
print(f"AGENTIC_TRAIN_USING_PT tables={ppm.table_count()} vocab={tok.vocab_size}", flush=True)
# 2. SFT
sft_eps = _sft_episodes()
_run_sft(ppm, tok, sft_eps, repeats=sft_repeats)
# 3. GRPO / RLVR
from streaming_model.ce_v19_chat_curriculum import HELDOUT_CASES
_run_grpo(ppm, tok, sft_eps, HELDOUT_CASES, grpo_repeats=grpo_repeats, n_candidates=grpo_candidates)
# 4. Evaluate
chat_eval = _evaluate_chat_agentic(ppm, tok, HELDOUT_CASES)
tool_eval = _evaluate_tool_policy(ppm, tok)
metrics = {
"chat_eval": chat_eval,
"tool_eval": tool_eval,
"tables": ppm.table_count(),
"vocab_size": tok.vocab_size,
}
print(
f"AGENTIC_TRAIN_EVAL chat={chat_eval['heldout_passed']}/{chat_eval['heldout_total']} "
f"tool={tool_eval.get('tool_selection_accuracy')} "
f"tables={ppm.table_count()}",
flush=True,
)
# 5. Save and upload
_save_checkpoint(ppm, tok, metrics, out_dir)
return 0
if __name__ == "__main__":
raise SystemExit(main())
|