#!/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 = ["", "", "", "", "", "", "", "", "", ""] 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(" 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("")] 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("")) 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: obs_text goal_text thought obs_text action result_text pos/neg/neu """ seq = tok.encode(obs, max_tokens=max_tokens) # overwrite BOS position to avoid double BOS; we build manually seq = [] seq.append(tok.token_id("")) seq.append(tok.token_id("")) seq.extend(tok.encode(obs, max_tokens=64)[1:-1]) seq.append(tok.token_id("")) seq.extend(tok.encode(goal, max_tokens=64)[1:-1]) seq.append(tok.token_id("")) seq.extend(tok.encode("choose action that minimizes expected surprise", max_tokens=32)[1:-1]) seq.append(tok.token_id("")) seq.extend(tok.encode(obs, max_tokens=64)[1:-1]) seq.append(tok.token_id("")) seq.extend(tok.encode(action, max_tokens=16)[1:-1]) seq.append(tok.token_id("")) seq.extend(tok.encode(result, max_tokens=96)[1:-1]) seq.append(tok.token_id("")) reward_tok = "" if reward > 0.05 else ("" if reward < -0.05 else "") seq.append(tok.token_id(reward_tok)) seq.append(tok.token_id("")) # 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("")] seq.append(tok.token_id("")) seq.extend(tok.encode(obs, max_tokens=64)[1:-1]) seq.append(tok.token_id("")) seq.extend(tok.encode(goal, max_tokens=64)[1:-1]) seq.append(tok.token_id("")) seq.extend(tok.encode("choose action that minimizes expected surprise", max_tokens=32)[1:-1]) seq.append(tok.token_id("")) seq.extend(tok.encode(obs, max_tokens=64)[1:-1]) seq.append(tok.token_id("")) 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())