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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Speculative Tool Actions — Full End-to-End Pipeline (single script)
|
| 4 |
+
====================================================================
|
| 5 |
+
Runs inside HF Jobs GPU instance. Steps:
|
| 6 |
+
1. Build datasets from SWE-smith + ToolBench
|
| 7 |
+
2. Train cheap proposer (Qwen3-1.7B LoRA SFT)
|
| 8 |
+
3. Train verifier (Qwen3-4B LoRA Reward)
|
| 9 |
+
4. Evaluate configs A-E on held-out set
|
| 10 |
+
5. Generate cost-quality frontier + ablation report
|
| 11 |
+
"""
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import json
|
| 15 |
+
import re
|
| 16 |
+
import subprocess
|
| 17 |
+
from collections import Counter, defaultdict
|
| 18 |
+
from random import Random
|
| 19 |
+
|
| 20 |
+
# Ensure deps
|
| 21 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "--quiet", "datasets", "transformers", "trl", "peft", "accelerate", "huggingface_hub", "trackio"])
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from datasets import load_dataset, Dataset
|
| 25 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
|
| 26 |
+
from trl import SFTTrainer, SFTConfig, RewardTrainer, RewardConfig
|
| 27 |
+
from peft import LoraConfig
|
| 28 |
+
|
| 29 |
+
set_seed(42)
|
| 30 |
+
|
| 31 |
+
HUB_ORG = "narcolepticchicken"
|
| 32 |
+
ACTION_TYPES = [
|
| 33 |
+
"tool_call", "retrieval", "file_read", "file_write",
|
| 34 |
+
"repair", "verifier", "ask_clarification", "final_answer", "BLOCKED",
|
| 35 |
+
]
|
| 36 |
+
COST = {"strong_in": 1.0, "strong_out": 1.0, "cheap_in": 0.2, "cheap_out": 0.2}
|
| 37 |
+
|
| 38 |
+
# ========================================================================
|
| 39 |
+
# Dataset building
|
| 40 |
+
# ========================================================================
|
| 41 |
+
def classify_action(content, tool_calls=None):
|
| 42 |
+
c = (content or "").lower()
|
| 43 |
+
tc = json.dumps(tool_calls).lower() if tool_calls else ""
|
| 44 |
+
combined = c + " " + tc
|
| 45 |
+
if re.search(r'\b(final answer|conclusion|summary:|in conclusion|the answer is)\b', combined):
|
| 46 |
+
return "final_answer"
|
| 47 |
+
if re.search(r'\b(ask for clarification|need more info|could you clarify|what do you mean)\b', combined):
|
| 48 |
+
return "ask_clarification"
|
| 49 |
+
if re.search(r'\b(blocked|unsafe|i cannot|i\'m sorry, but|refuse|not allowed|harmful)\b', combined):
|
| 50 |
+
return "BLOCKED"
|
| 51 |
+
if re.search(r'\b(write.*file|save.*file|edit.*file|patch|diff)\b', combined):
|
| 52 |
+
return "file_write"
|
| 53 |
+
if re.search(r'\b(read.*file|view.*file|cat |head |tail |open.*file|get_content)\b', combined):
|
| 54 |
+
return "file_read"
|
| 55 |
+
if re.search(r'\b(repair|fix.*bug|correct.*error|debug|resolve|try.*again with)\b', combined):
|
| 56 |
+
return "repair"
|
| 57 |
+
if re.search(r'\b(verify|check|validate|test|assert|review)\b', combined):
|
| 58 |
+
return "verifier"
|
| 59 |
+
if re.search(r'\b(search|retrieve|find|lookup|query|google|bing)\b', combined):
|
| 60 |
+
return "retrieval"
|
| 61 |
+
if tool_calls or re.search(r'\b(function call|tool call|invoke|execute)\b', combined):
|
| 62 |
+
return "tool_call"
|
| 63 |
+
return "tool_call"
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def build_datasets(max_swe=3000, max_toolbench=2000):
|
| 67 |
+
print("\n=== STEP 1: Building Datasets ===")
|
| 68 |
+
ds_swe = load_dataset("SWE-bench/SWE-smith-trajectories", "tool", split="train", streaming=True)
|
| 69 |
+
p_rows, v_rows, e_rows = [], [], []
|
| 70 |
+
count = 0
|
| 71 |
+
for ex in ds_swe:
|
| 72 |
+
count += 1
|
| 73 |
+
if count > max_swe:
|
| 74 |
+
break
|
| 75 |
+
msgs = ex.get("messages", [])
|
| 76 |
+
resolved = ex.get("resolved", False)
|
| 77 |
+
state = []
|
| 78 |
+
for msg in msgs:
|
| 79 |
+
role = msg.get("role", "")
|
| 80 |
+
if role in ("assistant", "agent"):
|
| 81 |
+
atype = classify_action(msg.get("content", ""), msg.get("tool_calls"))
|
| 82 |
+
comp = [{"role": "assistant", "content": msg.get("content", "")}]
|
| 83 |
+
if msg.get("tool_calls"):
|
| 84 |
+
comp[0]["tool_calls"] = msg["tool_calls"]
|
| 85 |
+
p_rows.append({"prompt": [m.copy() for m in state], "completion": comp, "action_type": atype})
|
| 86 |
+
v_rows.append({"prompt": [m.copy() for m in state], "completion": comp, "label": bool(resolved), "action_type": atype})
|
| 87 |
+
e_rows.append({"messages": [m.copy() for m in state] + comp, "resolved": resolved, "action_type": atype})
|
| 88 |
+
state.append(msg)
|
| 89 |
+
|
| 90 |
+
ds_tb = load_dataset("tuandunghcmut/toolbench-v1", split="train", streaming=True)
|
| 91 |
+
count = 0
|
| 92 |
+
for ex in ds_tb:
|
| 93 |
+
count += 1
|
| 94 |
+
if count > max_toolbench:
|
| 95 |
+
break
|
| 96 |
+
conv = ex.get("conversations", {})
|
| 97 |
+
state = []
|
| 98 |
+
for role, content in zip(conv.get("from", []), conv.get("value", [])):
|
| 99 |
+
msg = {"role": role, "content": content}
|
| 100 |
+
if role == "assistant":
|
| 101 |
+
atype = classify_action(content)
|
| 102 |
+
p_rows.append({"prompt": [m.copy() for m in state], "completion": [msg.copy()], "action_type": atype})
|
| 103 |
+
v_rows.append({"prompt": [m.copy() for m in state], "completion": [msg.copy()], "label": True, "action_type": atype})
|
| 104 |
+
e_rows.append({"messages": [m.copy() for m in state] + [msg.copy()], "resolved": True, "action_type": atype})
|
| 105 |
+
state.append(msg)
|
| 106 |
+
|
| 107 |
+
print(f"Rows: proposer={len(p_rows)}, verifier={len(v_rows)}, eval={len(e_rows)}")
|
| 108 |
+
print("Action distribution:", Counter(r["action_type"] for r in p_rows).most_common())
|
| 109 |
+
|
| 110 |
+
def fmt_proposer(r):
|
| 111 |
+
sys_msg = {"role": "system", "content": (
|
| 112 |
+
"You are an agent action predictor. Predict the next action from: "
|
| 113 |
+
+ ", ".join(ACTION_TYPES) + ". Respond with exactly the action name and brief justification.")}
|
| 114 |
+
prompt = [sys_msg] + r["prompt"]
|
| 115 |
+
if prompt:
|
| 116 |
+
prompt[-1]["content"] += "\n\n[Next Action Prediction] Choose one: " + ", ".join(ACTION_TYPES)
|
| 117 |
+
comp = r["completion"]
|
| 118 |
+
comp[0]["content"] = f"Action: {r['action_type']}\n" + comp[0]["content"]
|
| 119 |
+
return {"prompt": prompt, "completion": comp}
|
| 120 |
+
|
| 121 |
+
proposer_ds = Dataset.from_list([fmt_proposer(r) for r in p_rows]).shuffle(seed=42).train_test_split(test_size=0.1)
|
| 122 |
+
proposer_ds.push_to_hub(f"{HUB_ORG}/speculative-actions-proposer-sft")
|
| 123 |
+
print("Pushed proposer dataset")
|
| 124 |
+
|
| 125 |
+
rng = Random(42)
|
| 126 |
+
good = [r for r in v_rows if r["label"]]
|
| 127 |
+
bad = [r for r in v_rows if not r["label"]]
|
| 128 |
+
if len(bad) < len(good) * 0.2:
|
| 129 |
+
for r in good:
|
| 130 |
+
wa = rng.choice([a for a in ACTION_TYPES if a != r["action_type"]])
|
| 131 |
+
bad.append({
|
| 132 |
+
"prompt": [m.copy() for m in r["prompt"]],
|
| 133 |
+
"completion": [{"role": "assistant", "content": f"Action: {wa}\n(synthetic incorrect action)"}],
|
| 134 |
+
"label": False, "action_type": wa,
|
| 135 |
+
})
|
| 136 |
+
pairs = []
|
| 137 |
+
for g in good:
|
| 138 |
+
b = rng.choice(bad)
|
| 139 |
+
pairs.append({"prompt": [m.copy() for m in g["prompt"]], "chosen": g["completion"], "rejected": b["completion"], "action_type": g["action_type"]})
|
| 140 |
+
verifier_ds = Dataset.from_list(pairs).shuffle(seed=42).train_test_split(test_size=0.1)
|
| 141 |
+
verifier_ds.push_to_hub(f"{HUB_ORG}/speculative-actions-verifier-pref")
|
| 142 |
+
print("Pushed verifier dataset")
|
| 143 |
+
|
| 144 |
+
eval_ds = Dataset.from_list(e_rows).shuffle(seed=42).select(range(min(1000, len(e_rows))))
|
| 145 |
+
eval_ds.push_to_hub(f"{HUB_ORG}/speculative-actions-eval")
|
| 146 |
+
print("Pushed eval dataset")
|
| 147 |
+
|
| 148 |
+
return proposer_ds, verifier_ds, eval_ds
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# ========================================================================
|
| 152 |
+
# Train proposer
|
| 153 |
+
# ========================================================================
|
| 154 |
+
def train_proposer():
|
| 155 |
+
print("\n=== STEP 2: Training Proposer ===")
|
| 156 |
+
ds = load_dataset(f"{HUB_ORG}/speculative-actions-proposer-sft")
|
| 157 |
+
peft_config = LoraConfig(
|
| 158 |
+
r=16, lora_alpha=32,
|
| 159 |
+
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
|
| 160 |
+
modules_to_save=["embed_tokens", "lm_head"],
|
| 161 |
+
)
|
| 162 |
+
config = SFTConfig(
|
| 163 |
+
output_dir="/tmp/proposer-out",
|
| 164 |
+
hub_model_id=f"{HUB_ORG}/speculative-proposer-qwen3-1.7b",
|
| 165 |
+
push_to_hub=True,
|
| 166 |
+
learning_rate=2e-4,
|
| 167 |
+
per_device_train_batch_size=4,
|
| 168 |
+
gradient_accumulation_steps=4,
|
| 169 |
+
num_train_epochs=2,
|
| 170 |
+
max_seq_length=2048,
|
| 171 |
+
bf16=True,
|
| 172 |
+
gradient_checkpointing=True,
|
| 173 |
+
logging_strategy="steps",
|
| 174 |
+
logging_steps=10,
|
| 175 |
+
logging_first_step=True,
|
| 176 |
+
disable_tqdm=True,
|
| 177 |
+
report_to="trackio",
|
| 178 |
+
run_name="proposer-sft-qwen3-1.7b",
|
| 179 |
+
)
|
| 180 |
+
trainer = SFTTrainer(
|
| 181 |
+
model="Qwen/Qwen3-1.7B",
|
| 182 |
+
train_dataset=ds["train"],
|
| 183 |
+
eval_dataset=ds["test"],
|
| 184 |
+
args=config,
|
| 185 |
+
peft_config=peft_config,
|
| 186 |
+
)
|
| 187 |
+
trainer.train()
|
| 188 |
+
trainer.push_to_hub()
|
| 189 |
+
print("Proposer training done.")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# ========================================================================
|
| 193 |
+
# Train verifier
|
| 194 |
+
# ========================================================================
|
| 195 |
+
def train_verifier():
|
| 196 |
+
print("\n=== STEP 3: Training Verifier ===")
|
| 197 |
+
ds = load_dataset(f"{HUB_ORG}/speculative-actions-verifier-pref")
|
| 198 |
+
peft_config = LoraConfig(
|
| 199 |
+
r=16, lora_alpha=32,
|
| 200 |
+
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
|
| 201 |
+
modules_to_save=["score"],
|
| 202 |
+
)
|
| 203 |
+
config = RewardConfig(
|
| 204 |
+
output_dir="/tmp/verifier-out",
|
| 205 |
+
hub_model_id=f"{HUB_ORG}/speculative-verifier-qwen3-4b",
|
| 206 |
+
push_to_hub=True,
|
| 207 |
+
learning_rate=1e-3,
|
| 208 |
+
per_device_train_batch_size=2,
|
| 209 |
+
gradient_accumulation_steps=8,
|
| 210 |
+
num_train_epochs=2,
|
| 211 |
+
max_seq_length=2048,
|
| 212 |
+
bf16=True,
|
| 213 |
+
gradient_checkpointing=True,
|
| 214 |
+
logging_strategy="steps",
|
| 215 |
+
logging_steps=10,
|
| 216 |
+
logging_first_step=True,
|
| 217 |
+
disable_tqdm=True,
|
| 218 |
+
report_to="trackio",
|
| 219 |
+
run_name="verifier-reward-qwen3-4b",
|
| 220 |
+
)
|
| 221 |
+
trainer = RewardTrainer(
|
| 222 |
+
model="Qwen/Qwen3-4B",
|
| 223 |
+
train_dataset=ds["train"],
|
| 224 |
+
eval_dataset=ds["test"],
|
| 225 |
+
args=config,
|
| 226 |
+
peft_config=peft_config,
|
| 227 |
+
)
|
| 228 |
+
trainer.train()
|
| 229 |
+
trainer.push_to_hub()
|
| 230 |
+
print("Verifier training done.")
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# ========================================================================
|
| 234 |
+
# Evaluation
|
| 235 |
+
# ========================================================================
|
| 236 |
+
def parse_action(text):
|
| 237 |
+
for a in ACTION_TYPES:
|
| 238 |
+
if a.lower() in text.lower():
|
| 239 |
+
return a
|
| 240 |
+
return "tool_call"
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class EvalRunner:
|
| 244 |
+
def __init__(self, strong_name, cheap_name, verifier_name, device="cuda"):
|
| 245 |
+
self.device = device
|
| 246 |
+
self.strong_tok = AutoTokenizer.from_pretrained(strong_name, trust_remote_code=True)
|
| 247 |
+
self.strong_model = AutoModelForCausalLM.from_pretrained(
|
| 248 |
+
strong_name, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True)
|
| 249 |
+
self.cheap_tok = AutoTokenizer.from_pretrained(cheap_name, trust_remote_code=True)
|
| 250 |
+
self.cheap_model = AutoModelForCausalLM.from_pretrained(
|
| 251 |
+
cheap_name, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True)
|
| 252 |
+
self.verifier_name = verifier_name
|
| 253 |
+
if verifier_name:
|
| 254 |
+
self.v_tok = AutoTokenizer.from_pretrained(verifier_name, trust_remote_code=True)
|
| 255 |
+
self.v_model = AutoModelForCausalLM.from_pretrained(
|
| 256 |
+
verifier_name, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True)
|
| 257 |
+
|
| 258 |
+
def _gen(self, model, tokenizer, messages, max_new=128, temp=0.0):
|
| 259 |
+
inputs = tokenizer.apply_chat_template(messages, tokenize=True, return_tensors="pt", add_generation_prompt=True).to(model.device)
|
| 260 |
+
with torch.no_grad():
|
| 261 |
+
out = model.generate(inputs, max_new_tokens=max_new, do_sample=temp > 0,
|
| 262 |
+
temperature=temp if temp > 0 else None,
|
| 263 |
+
pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id)
|
| 264 |
+
return tokenizer.decode(out[0][inputs.shape[1]:], skip_special_tokens=True), inputs.shape[1], out.shape[1] - inputs.shape[1]
|
| 265 |
+
|
| 266 |
+
def run_a(self, messages):
|
| 267 |
+
s = {"role": "system", "content": f"Predict next action from: {', '.join(ACTION_TYPES)}"}
|
| 268 |
+
out, i, o = self._gen(self.strong_model, self.strong_tok, [s] + messages)
|
| 269 |
+
return parse_action(out), i, o, "strong"
|
| 270 |
+
|
| 271 |
+
def run_b(self, messages):
|
| 272 |
+
s = {"role": "system", "content": f"Predict next action from: {', '.join(ACTION_TYPES)}"}
|
| 273 |
+
out, i, o = self._gen(self.cheap_model, self.cheap_tok, [s] + messages)
|
| 274 |
+
return parse_action(out), i, o, "cheap"
|
| 275 |
+
|
| 276 |
+
def run_c(self, messages):
|
| 277 |
+
s = {"role": "system", "content": f"Predict next action from: {', '.join(ACTION_TYPES)}"}
|
| 278 |
+
prop, i1, o1 = self._gen(self.cheap_model, self.cheap_tok, [s] + messages)
|
| 279 |
+
vp = messages + [{"role": "assistant", "content": prop}, {"role": "user", "content": "Is this action correct? Answer ONLY yes or no."}]
|
| 280 |
+
ver, i2, o2 = self._gen(self.strong_model, self.strong_tok, vp, max_new=10)
|
| 281 |
+
if "yes" in ver.lower():
|
| 282 |
+
return parse_action(prop), i1 + i2, o1 + o2, "mixed"
|
| 283 |
+
out, i3, o3 = self._gen(self.strong_model, self.strong_tok, [s] + messages)
|
| 284 |
+
return parse_action(out), i1 + i2 + i3, o1 + o2 + o3, "mixed"
|
| 285 |
+
|
| 286 |
+
def run_d(self, messages):
|
| 287 |
+
if not self.verifier_name:
|
| 288 |
+
raise ValueError("Need verifier")
|
| 289 |
+
s = {"role": "system", "content": f"Predict next action from: {', '.join(ACTION_TYPES)}"}
|
| 290 |
+
prop, i1, o1 = self._gen(self.cheap_model, self.cheap_tok, [s] + messages)
|
| 291 |
+
vp = messages + [{"role": "assistant", "content": prop}, {"role": "user", "content": "Rate this action: good or bad."}]
|
| 292 |
+
ver, i2, o2 = self._gen(self.v_model, self.v_tok, vp, max_new=10)
|
| 293 |
+
if "good" in ver.lower():
|
| 294 |
+
return parse_action(prop), i1 + i2, o1 + o2, "cheap"
|
| 295 |
+
out, i3, o3 = self._gen(self.strong_model, self.strong_tok, [s] + messages)
|
| 296 |
+
return parse_action(out), i1 + i2 + i3, o1 + o2 + o3, "mixed"
|
| 297 |
+
|
| 298 |
+
def run_e(self, messages, n=3):
|
| 299 |
+
s = {"role": "system", "content": f"Predict next action from: {', '.join(ACTION_TYPES)}"}
|
| 300 |
+
props = []
|
| 301 |
+
ti, to = 0, 0
|
| 302 |
+
for _ in range(n):
|
| 303 |
+
p, i, o = self._gen(self.cheap_model, self.cheap_tok, [s] + messages, temp=0.7)
|
| 304 |
+
props.append(p); ti += i; to += o
|
| 305 |
+
best = props[0]; best_score = -1
|
| 306 |
+
for p in props:
|
| 307 |
+
rp = messages + [{"role": "assistant", "content": p}, {"role": "user", "content": "Score 1-10."}]
|
| 308 |
+
st, i, o = self._gen(self.strong_model, self.strong_tok, rp, max_new=5)
|
| 309 |
+
ti += i; to += o
|
| 310 |
+
m = re.search(r'(\d+)', st)
|
| 311 |
+
if m:
|
| 312 |
+
sc = int(m.group(1))
|
| 313 |
+
if sc > best_score:
|
| 314 |
+
best_score = sc; best = p
|
| 315 |
+
return parse_action(best), ti, to, "mixed"
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def evaluate(limit=200):
|
| 319 |
+
print("\n=== STEP 4: Evaluation ===")
|
| 320 |
+
ds = load_dataset(f"{HUB_ORG}/speculative-actions-eval", split="train")
|
| 321 |
+
ds = ds.shuffle(seed=42).select(range(min(limit, len(ds))))
|
| 322 |
+
|
| 323 |
+
runner = EvalRunner(
|
| 324 |
+
strong_name="Qwen/Qwen2.5-7B-Instruct",
|
| 325 |
+
cheap_name="Qwen/Qwen3-1.7B",
|
| 326 |
+
verifier_name=f"{HUB_ORG}/speculative-verifier-qwen3-4b",
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
results = defaultdict(lambda: {"correct": 0, "total": 0, "cost": 0.0, "unsafe": 0})
|
| 330 |
+
for idx, ex in enumerate(ds):
|
| 331 |
+
msgs = ex["messages"]; gold = ex["action_type"]
|
| 332 |
+
for cfg, func in [("A", runner.run_a), ("B", runner.run_b), ("C", runner.run_c), ("D", runner.run_d), ("E", runner.run_e)]:
|
| 333 |
+
try:
|
| 334 |
+
if cfg == "E":
|
| 335 |
+
pred, i_t, o_t, mtype = func(msgs, n=3)
|
| 336 |
+
else:
|
| 337 |
+
pred, i_t, o_t, mtype = func(msgs)
|
| 338 |
+
except Exception as e:
|
| 339 |
+
print(f"Error {cfg} idx {idx}: {e}")
|
| 340 |
+
pred, i_t, o_t, mtype = "tool_call", 0, 0, "unknown"
|
| 341 |
+
results[cfg]["total"] += 1
|
| 342 |
+
if pred == gold:
|
| 343 |
+
results[cfg]["correct"] += 1
|
| 344 |
+
if pred == "BLOCKED" and gold != "BLOCKED":
|
| 345 |
+
results[cfg]["unsafe"] += 1
|
| 346 |
+
if pred != "BLOCKED" and gold == "BLOCKED":
|
| 347 |
+
results[cfg]["unsafe"] += 1
|
| 348 |
+
results[cfg]["cost"] += i_t * COST.get(f"{mtype}_in", 1.0) + o_t * COST.get(f"{mtype}_out", 1.0)
|
| 349 |
+
if (idx + 1) % 50 == 0:
|
| 350 |
+
print(f" Evaluated {idx + 1}/{min(limit, len(ds))}")
|
| 351 |
+
|
| 352 |
+
for cfg in results:
|
| 353 |
+
t = max(results[cfg]["total"], 1)
|
| 354 |
+
results[cfg]["accuracy"] = results[cfg]["correct"] / t
|
| 355 |
+
results[cfg]["avg_cost"] = results[cfg]["cost"] / t
|
| 356 |
+
results[cfg]["unsafe_rate"] = results[cfg]["unsafe"] / t
|
| 357 |
+
|
| 358 |
+
summary = {k: dict(v) for k, v in results.items()}
|
| 359 |
+
with open("/tmp/eval_results.json", "w") as f:
|
| 360 |
+
json.dump(summary, f, indent=2)
|
| 361 |
+
print(json.dumps(summary, indent=2))
|
| 362 |
+
return summary
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
# ========================================================================
|
| 366 |
+
# Report
|
| 367 |
+
# ========================================================================
|
| 368 |
+
def generate_report(eval_results):
|
| 369 |
+
print("\n=== STEP 5: Generating Report ===")
|
| 370 |
+
lines = ["# Speculative Tool Actions — Ablation Report\n"]
|
| 371 |
+
lines.append("## Configurations\n")
|
| 372 |
+
lines.append("- **A**: Always strong model (Qwen2.5-7B)\n")
|
| 373 |
+
lines.append("- **B**: Cheap model only (Qwen3-1.7B)\n")
|
| 374 |
+
lines.append("- **C**: Cheap proposer + strong verifier\n")
|
| 375 |
+
lines.append("- **D**: Cheap proposer + trained trace judge (Qwen3-4B reward model)\n")
|
| 376 |
+
lines.append("- **E**: Multi-proposal reranking (3 cheap + strong scoring)\n\n")
|
| 377 |
+
|
| 378 |
+
lines.append("## Results\n\n")
|
| 379 |
+
lines.append("| Config | Accuracy | Avg Cost | Unsafe-Action Rate |\n")
|
| 380 |
+
lines.append("|--------|----------|----------|-------------------|\n")
|
| 381 |
+
for cfg in sorted(eval_results):
|
| 382 |
+
r = eval_results[cfg]
|
| 383 |
+
lines.append(f"| {cfg} | {r['accuracy']:.3f} | {r['avg_cost']:.2f} | {r['unsafe_rate']:.3f} |\n")
|
| 384 |
+
|
| 385 |
+
lines.append("\n## Cost-Quality Frontier\n\n")
|
| 386 |
+
points = [(r["avg_cost"], r["accuracy"], cfg) for cfg, r in eval_results.items()]
|
| 387 |
+
points.sort()
|
| 388 |
+
frontier = []
|
| 389 |
+
max_acc = -1
|
| 390 |
+
for cost, acc, cfg in points:
|
| 391 |
+
if acc > max_acc:
|
| 392 |
+
frontier.append((cost, acc, cfg)); max_acc = acc
|
| 393 |
+
lines.append("Pareto-optimal configs:\n")
|
| 394 |
+
for cost, acc, cfg in frontier:
|
| 395 |
+
lines.append(f"- **{cfg}**: cost={cost:.2f}, accuracy={acc:.3f}\n")
|
| 396 |
+
|
| 397 |
+
lines.append("\n## Recommendations\n")
|
| 398 |
+
best_ratio = None; best_cfg = None
|
| 399 |
+
for cfg, r in eval_results.items():
|
| 400 |
+
ratio = r["accuracy"] / max(r["avg_cost"], 0.01)
|
| 401 |
+
if best_ratio is None or ratio > best_ratio:
|
| 402 |
+
best_ratio = ratio; best_cfg = cfg
|
| 403 |
+
lines.append(f"- **Best accuracy/cost ratio**: Config {best_cfg} (ratio={best_ratio:.3f})\n")
|
| 404 |
+
|
| 405 |
+
best_acc_cfg = max(eval_results, key=lambda c: eval_results[c]["accuracy"])
|
| 406 |
+
lines.append(f"- **Highest accuracy**: Config {best_acc_cfg} ({eval_results[best_acc_cfg]['accuracy']:.3f})\n")
|
| 407 |
+
|
| 408 |
+
best_acc = eval_results[best_acc_cfg]["accuracy"]
|
| 409 |
+
threshold = best_acc * 0.9
|
| 410 |
+
cheap = {c: r for c, r in eval_results.items() if r["accuracy"] >= threshold}
|
| 411 |
+
if cheap:
|
| 412 |
+
cheapest = min(cheap, key=lambda c: cheap[c]["avg_cost"])
|
| 413 |
+
lines.append(f"- **Cheapest within 90% of best accuracy**: Config {cheapest} "
|
| 414 |
+
f"(cost={cheap[cheapest]['avg_cost']:.2f}, acc={cheap[cheapest]['accuracy']:.3f})\n")
|
| 415 |
+
|
| 416 |
+
report = "".join(lines)
|
| 417 |
+
with open("/tmp/ablation_report.md", "w") as f:
|
| 418 |
+
f.write(report)
|
| 419 |
+
print(report)
|
| 420 |
+
return report
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
# ========================================================================
|
| 424 |
+
# Main
|
| 425 |
+
# ========================================================================
|
| 426 |
+
def main():
|
| 427 |
+
proposer_ds, verifier_ds, eval_ds = build_datasets()
|
| 428 |
+
train_proposer()
|
| 429 |
+
train_verifier()
|
| 430 |
+
results = evaluate(limit=200)
|
| 431 |
+
generate_report(results)
|
| 432 |
+
print("\n=== Pipeline Complete ===")
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
if __name__ == "__main__":
|
| 436 |
+
main()
|