| """Handicate self-refinement orchestrator. |
| |
| One round = |
| 1. CURATE : pull web data -> judge rates+compresses -> keep >= threshold (raw discarded) |
| 2. CRITIQUE: policy answers seed prompts -> judge criticizes -> policy revises -> keep better |
| 3. RL : GRPO on seed prompts with the judge as reward (constant improvement) |
| 4. DISTILL : fold curated + revised pairs into weights (LoRA SFT), then DISCARD raw |
| 5. GATE : score on frozen held-out eval; KEEP the round only if it didn't regress |
| Repeat for ROUNDS. The model carries knowledge in weights; data does not pile up on disk. |
| |
| This is a research framework, not an AGI. It improves a small model on a rubric-defined |
| slice -- with diminishing returns and a hard collapse guard. See README for honest scope. |
| """ |
| import json |
| from pathlib import Path |
|
|
| import config as C |
| from core.judge import Judge |
| from core import curator, critique_revise, refine_rl, distill, evalgate |
|
|
| ROOT = Path(__file__).resolve().parent |
|
|
|
|
| def load_seed_prompts(): |
| """Returns (prompts, types). type tags route each task to its modality verifier.""" |
| p = ROOT / "data" / "seed_prompts.jsonl" |
| if not p.exists(): |
| return ["Write a Python function to debounce calls."], ["python"] |
| rows = [json.loads(l) for l in p.read_text(encoding="utf-8").splitlines() if l.strip()] |
| return [r["prompt"] for r in rows], [r.get("type", "python") for r in rows] |
|
|
|
|
| def main(): |
| import torch |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
|
|
| judge = Judge() |
| tok = AutoTokenizer.from_pretrained(C.BASE_MODEL) |
| seed_prompts, seed_types = load_seed_prompts() |
| eval_items = evalgate.load_eval(C.EVAL_SET) |
|
|
| current = C.BASE_MODEL |
| prev_score = None |
|
|
| for rnd in range(1, C.ROUNDS + 1): |
| print(f"\n===== ROUND {rnd}/{C.ROUNDS} =====", flush=True) |
| out_dir = f"./handicate-r{rnd}" |
|
|
| |
| try: |
| docs = curator.web_pull([p[:60] for p in seed_prompts], per_query=C.CURATE_PER_ROUND // max(1, len(seed_prompts))) |
| curated = curator.curate(docs, judge, C.ACCEPT_THRESHOLD, C.CURATE_PER_ROUND) |
| except NotImplementedError: |
| print("web_pull not wired -- skipping curation this round", flush=True) |
| curated = [] |
|
|
| |
| policy = AutoModelForCausalLM.from_pretrained(current, torch_dtype=torch.bfloat16, device_map="cuda") |
| revised = critique_revise.critique_revise_batch(policy, tok, judge, seed_prompts) |
| del policy; torch.cuda.empty_cache() |
|
|
| |
| rl_dir = refine_rl.run_grpo(current, seed_prompts, seed_types, judge, out_dir + "-rl", |
| C.GRPO_STEPS_PER_ROUND, C.GRPO_NUM_GENERATIONS, |
| C.LEARNING_RATE, C.LORA_R, C.LORA_ALPHA) |
|
|
| |
| pairs = [p for p in (curated + revised) if p.get("score", 0) >= C.ACCEPT_THRESHOLD] |
| if pairs: |
| distill.keep_replay(pairs, C.REPLAY_FRACTION, "data/replay.jsonl") |
| cand = distill.distill(rl_dir, pairs, out_dir, C.LEARNING_RATE, C.LORA_R, C.LORA_ALPHA, |
| discard_raw=C.DISCARD_RAW_AFTER_DISTILL) |
| else: |
| cand = rl_dir |
|
|
| |
| pol = AutoModelForCausalLM.from_pretrained(cand, torch_dtype=torch.bfloat16, device_map="cuda") |
| score = evalgate.evaluate(pol, tok, judge, eval_items) |
| del pol; torch.cuda.empty_cache() |
| print(f"round {rnd} held-out score: {score:.4f} (prev {prev_score})", flush=True) |
|
|
| if prev_score is None or evalgate.keep_round(score, prev_score, C.EVAL_REGRESS_TOLERANCE): |
| current, prev_score = cand, score |
| print(f"KEEP round {rnd} -> {current}", flush=True) |
| else: |
| print(f"REVERT round {rnd} (regressed); keeping {current}", flush=True) |
|
|
| print(f"\nFinal policy: {current} (held-out {prev_score})", flush=True) |
| |
| (ROOT / "FINAL_POLICY.txt").write_text(current, encoding="utf-8") |
| return current |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|