File size: 4,431 Bytes
ccbd209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bd725a
ccbd209
 
9bd725a
 
 
ccbd209
 
 
 
 
 
 
 
9bd725a
ccbd209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bd725a
 
ccbd209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bd725a
 
ccbd209
 
 
 
 
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
"""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          # path/name of the live policy (weights only)
    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}"

        # 1. curate web data (raw discarded inside curate())
        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 = []

        # 2. critique -> revise (learn from criticism)
        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()

        # 3. RL: GRPO with per-modality verifier+judge reward
        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)

        # 4. distill curated + revised into weights, discard raw
        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

        # 5. eval gate -- keep only if no regression on frozen held-out tasks
        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)
    # record the exact kept policy so the runner uploads THIS (not an -rl intermediate)
    (ROOT / "FINAL_POLICY.txt").write_text(current, encoding="utf-8")
    return current


if __name__ == "__main__":
    main()