Rohan03 commited on
Commit
ccbf192
·
verified ·
1 Parent(s): 08321e5

V2 merge: purpose_agent/meta_rewarding.py

Browse files
Files changed (1) hide show
  1. purpose_agent/meta_rewarding.py +211 -0
purpose_agent/meta_rewarding.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ meta_rewarding.py — Self-improving critic via meta-judge loop.
3
+
4
+ From Meta-Rewarding LLMs (arxiv:2407.19594):
5
+ The Purpose Function judges agent actions. But who judges the judge?
6
+ A meta-judge evaluates the Purpose Function's own judgments, creating
7
+ preference pairs (good judgment vs bad judgment) that improve the critic.
8
+
9
+ Adaptation for Purpose Agent (no weight updates):
10
+ Instead of DPO fine-tuning, we store high-quality judgment examples
11
+ as critic_calibration memories. The Purpose Function's prompt gets
12
+ augmented with these calibration examples, improving scoring quality
13
+ over time through in-context learning.
14
+
15
+ Meta-judge loop:
16
+ 1. Purpose Function scores a transition → produces (score, reasoning, evidence)
17
+ 2. Meta-judge evaluates the judgment: was the reasoning sound? was evidence cited?
18
+ 3. Good judgments → stored as critic_calibration memories (positive examples)
19
+ 4. Bad judgments → stored as failure_pattern memories (negative examples)
20
+ 5. Next time the Purpose Function runs, calibration memories are in its prompt
21
+
22
+ Result: the critic gets better at scoring without any weight updates.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import logging
28
+ from typing import Any
29
+
30
+ from purpose_agent.llm_backend import LLMBackend, ChatMessage
31
+ from purpose_agent.types import PurposeScore
32
+ from purpose_agent.memory import MemoryCard, MemoryKind, MemoryStatus
33
+ from purpose_agent.v2_types import MemoryScope
34
+ from purpose_agent.memory_ci import MemoryCI
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ META_JUDGE_PROMPT = """\
39
+ You are a META-JUDGE. You evaluate the QUALITY of another AI's evaluation.
40
+
41
+ You will see:
42
+ - A state transition (before → action → after)
43
+ - The Purpose Function's judgment (Φ scores, reasoning, evidence)
44
+
45
+ Rate the judgment quality on these criteria:
46
+ 1. EVIDENCE GROUNDING: Did the judgment cite specific, verifiable state changes? (0-10)
47
+ 2. REASONING COHERENCE: Is the chain of reasoning logically sound? (0-10)
48
+ 3. CALIBRATION: Are the Φ scores proportional to actual progress? (0-10)
49
+ 4. ANTI-SYCOPHANCY: Did the judgment avoid inflating scores to be encouraging? (0-10)
50
+ 5. CONSISTENCY: Would an identical state get the same score? (0-10)
51
+
52
+ Respond with JSON:
53
+ {
54
+ "evidence_grounding": <0-10>,
55
+ "reasoning_coherence": <0-10>,
56
+ "calibration": <0-10>,
57
+ "anti_sycophancy": <0-10>,
58
+ "consistency": <0-10>,
59
+ "overall": <0-10>,
60
+ "feedback": "<specific feedback on what was good or bad about this judgment>"
61
+ }
62
+ """
63
+
64
+ META_JUDGE_SCHEMA = {
65
+ "type": "object",
66
+ "properties": {
67
+ "evidence_grounding": {"type": "number"},
68
+ "reasoning_coherence": {"type": "number"},
69
+ "calibration": {"type": "number"},
70
+ "anti_sycophancy": {"type": "number"},
71
+ "consistency": {"type": "number"},
72
+ "overall": {"type": "number"},
73
+ "feedback": {"type": "string"},
74
+ },
75
+ "required": ["overall", "feedback"],
76
+ }
77
+
78
+
79
+ class MetaRewardingLoop:
80
+ """
81
+ Evaluates and improves the Purpose Function through meta-judgment.
82
+
83
+ Usage:
84
+ meta = MetaRewardingLoop(meta_llm=strong_model, memory_ci=ci)
85
+
86
+ # After each Purpose Function evaluation:
87
+ meta.evaluate_judgment(
88
+ state_before_desc="Position (0,0)",
89
+ action_desc="move_east",
90
+ state_after_desc="Position (1,0)",
91
+ purpose="Reach (4,4)",
92
+ judgment=purpose_score,
93
+ )
94
+
95
+ # Good judgments become calibration examples in memory.
96
+ # Bad judgments become failure patterns.
97
+ # Purpose Function improves via in-context learning.
98
+ """
99
+
100
+ def __init__(
101
+ self,
102
+ meta_llm: LLMBackend,
103
+ memory_ci: MemoryCI,
104
+ quality_threshold: float = 7.0,
105
+ ):
106
+ self.meta_llm = meta_llm
107
+ self.memory_ci = memory_ci
108
+ self.quality_threshold = quality_threshold
109
+ self._eval_log: list[dict] = []
110
+
111
+ def evaluate_judgment(
112
+ self,
113
+ state_before_desc: str,
114
+ action_desc: str,
115
+ state_after_desc: str,
116
+ purpose: str,
117
+ judgment: PurposeScore,
118
+ trace_id: str = "",
119
+ ) -> dict[str, Any]:
120
+ """
121
+ Have the meta-judge evaluate a Purpose Function judgment.
122
+
123
+ If the judgment is high quality → create a positive calibration memory.
124
+ If low quality → create a negative calibration memory.
125
+ """
126
+ context = (
127
+ f"Purpose: {purpose}\n"
128
+ f"State before: {state_before_desc}\n"
129
+ f"Action: {action_desc}\n"
130
+ f"State after: {state_after_desc}\n\n"
131
+ f"Purpose Function's judgment:\n"
132
+ f" Φ_before={judgment.phi_before:.1f}, Φ_after={judgment.phi_after:.1f}, Δ={judgment.delta:+.2f}\n"
133
+ f" Confidence: {judgment.confidence:.2f}\n"
134
+ f" Reasoning: {judgment.reasoning}\n"
135
+ f" Evidence: {judgment.evidence}"
136
+ )
137
+
138
+ messages = [
139
+ ChatMessage(role="system", content=META_JUDGE_PROMPT),
140
+ ChatMessage(role="user", content=context),
141
+ ]
142
+
143
+ try:
144
+ result = self.meta_llm.generate_structured(messages, schema=META_JUDGE_SCHEMA)
145
+ except Exception as e:
146
+ logger.warning(f"Meta-judge failed: {e}")
147
+ return {"error": str(e)}
148
+
149
+ overall = float(result.get("overall", 5.0))
150
+ feedback = str(result.get("feedback", ""))
151
+
152
+ log_entry = {
153
+ "trace_id": trace_id,
154
+ "overall_quality": overall,
155
+ "feedback": feedback,
156
+ "components": {k: result.get(k, 0) for k in META_JUDGE_SCHEMA["properties"] if k not in ("overall", "feedback")},
157
+ }
158
+ self._eval_log.append(log_entry)
159
+
160
+ # Create calibration memory
161
+ if overall >= self.quality_threshold:
162
+ card = MemoryCard(
163
+ kind=MemoryKind.CRITIC_CALIBRATION,
164
+ status=MemoryStatus.CANDIDATE,
165
+ content=(
166
+ f"GOOD judgment example (quality={overall:.0f}/10): "
167
+ f"For Δ={judgment.delta:+.2f}, evidence was: '{judgment.evidence[:200]}'. "
168
+ f"Meta-judge feedback: {feedback[:200]}"
169
+ ),
170
+ pattern=f"When scoring transitions with delta ~{judgment.delta:+.1f}",
171
+ strategy=f"Follow this example: {judgment.reasoning[:200]}",
172
+ trust_score=min(overall / 10.0, 1.0),
173
+ source_trace_id=trace_id,
174
+ created_by="meta_judge",
175
+ )
176
+ self.memory_ci.submit(card)
177
+ logger.info(f"MetaRewarding: Good judgment (quality={overall:.0f}) → calibration memory")
178
+ elif overall < 4.0:
179
+ card = MemoryCard(
180
+ kind=MemoryKind.FAILURE_PATTERN,
181
+ status=MemoryStatus.CANDIDATE,
182
+ content=(
183
+ f"BAD judgment example (quality={overall:.0f}/10): "
184
+ f"Avoid this pattern: {feedback[:300]}"
185
+ ),
186
+ pattern="When scoring state transitions",
187
+ strategy=f"Do NOT: {feedback[:200]}",
188
+ trust_score=0.8,
189
+ source_trace_id=trace_id,
190
+ created_by="meta_judge",
191
+ scope=MemoryScope(agent_roles=["critic"]),
192
+ )
193
+ self.memory_ci.submit(card)
194
+ logger.info(f"MetaRewarding: Bad judgment (quality={overall:.0f}) → failure pattern memory")
195
+
196
+ return log_entry
197
+
198
+ @property
199
+ def eval_log(self) -> list[dict]:
200
+ return self._eval_log
201
+
202
+ def summary(self) -> dict[str, Any]:
203
+ if not self._eval_log:
204
+ return {"evaluations": 0}
205
+ scores = [e["overall_quality"] for e in self._eval_log]
206
+ return {
207
+ "evaluations": len(scores),
208
+ "avg_quality": round(sum(scores) / len(scores), 2),
209
+ "min_quality": min(scores),
210
+ "max_quality": max(scores),
211
+ }