File size: 8,453 Bytes
b630916 6b7050a b630916 6b7050a b630916 | 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | import json
import hashlib
from flask import Blueprint, request, jsonify
from datasets import load_dataset
bp = Blueprint("rlm_eval_datasets", __name__, url_prefix="/api/rlm-eval/datasets")
_cache: dict[str, dict] = {}
def _make_id(repo: str, config: str, split: str) -> str:
key = f"{repo}:{config}:{split}"
return hashlib.md5(key.encode()).hexdigest()[:12]
def _build_hierarchy(rows: list[dict]) -> dict:
"""Reconstruct hierarchy from flat rows: examples -> iterations."""
examples: dict[int, dict] = {}
for row in rows:
ei = row.get("example_idx", 0)
ri = row.get("rlm_iter", 0)
if ei not in examples:
examples[ei] = {
"example_idx": ei,
"question_text": row.get("question_text", ""),
"eval_correct": row.get("eval_correct"),
"iterations": {},
"total_input_tokens": 0,
"total_output_tokens": 0,
"total_execution_time": 0.0,
"final_answer": None,
"final_answer_preview": "",
}
ex = examples[ei]
# Parse code blocks, flattening result.stdout -> stdout
code_blocks = []
cbj = row.get("code_blocks_json", "")
if cbj and cbj != "[]":
try:
raw_blocks = json.loads(cbj) if isinstance(cbj, str) else cbj
for cb in raw_blocks:
block = {"code": cb.get("code", "")}
result = cb.get("result", {})
if isinstance(result, dict) and result.get("stdout"):
block["stdout"] = result["stdout"]
elif cb.get("stdout"):
block["stdout"] = cb["stdout"]
code_blocks.append(block)
except (json.JSONDecodeError, TypeError):
code_blocks = []
iteration = {
"rlm_iter": ri,
"prompt": row.get("prompt", ""),
"response": row.get("response", ""),
"model": row.get("model", ""),
"input_tokens": row.get("input_tokens", 0),
"output_tokens": row.get("output_tokens", 0),
"execution_time": row.get("execution_time", 0.0),
"has_code_blocks": row.get("has_code_blocks", False),
"code_blocks": code_blocks,
"final_answer": row.get("final_answer"),
"timestamp": row.get("timestamp", ""),
}
ex["iterations"][ri] = iteration
ex["total_input_tokens"] += iteration["input_tokens"] or 0
ex["total_output_tokens"] += iteration["output_tokens"] or 0
ex["total_execution_time"] += iteration["execution_time"] or 0.0
if iteration["final_answer"]:
ex["final_answer"] = iteration["final_answer"]
ex["final_answer_preview"] = (iteration["final_answer"] or "")[:200]
# Sort and convert dicts to lists
result = []
for ei_key in sorted(examples.keys()):
ex = examples[ei_key]
iters_list = []
for ri_key in sorted(ex["iterations"].keys()):
iters_list.append(ex["iterations"][ri_key])
ex["iterations"] = iters_list
result.append(ex)
return {"examples": result}
@bp.route("/load", methods=["POST"])
def load_dataset_endpoint():
data = request.get_json()
repo = data.get("repo", "").strip()
if not repo:
return jsonify({"error": "repo is required"}), 400
config = data.get("config", "rlm_call_traces")
split = data.get("split", "train")
try:
ds = load_dataset(repo, config, split=split)
except Exception as e:
return jsonify({"error": f"Failed to load dataset: {e}"}), 400
ds_id = _make_id(repo, config, split)
rows = [ds[i] for i in range(len(ds))]
hierarchy = _build_hierarchy(rows)
# Extract metadata from first row
first_row = rows[0] if rows else {}
metadata = {
"run_id": first_row.get("run_id", ""),
"method": first_row.get("method", ""),
"model": first_row.get("model", ""),
}
_cache[ds_id] = {
"repo": repo,
"config": config,
"split": split,
"hierarchy": hierarchy,
"metadata": metadata,
"n_rows": len(rows),
}
short_name = repo.rsplit("/", 1)[-1] if "/" in repo else repo
return jsonify({
"id": ds_id,
"repo": repo,
"name": short_name,
"config": config,
"split": split,
"metadata": metadata,
"n_examples": len(hierarchy["examples"]),
"n_rows": len(rows),
})
@bp.route("/", methods=["GET"])
def list_datasets():
result = []
for ds_id, info in _cache.items():
result.append({
"id": ds_id,
"repo": info["repo"],
"name": info["repo"].rsplit("/", 1)[-1] if "/" in info["repo"] else info["repo"],
"config": info["config"],
"split": info["split"],
"metadata": info["metadata"],
"n_rows": info["n_rows"],
"n_examples": len(info["hierarchy"]["examples"]),
})
return jsonify(result)
@bp.route("/<ds_id>/overview", methods=["GET"])
def get_overview(ds_id):
"""Level 1: Summary of all examples."""
if ds_id not in _cache:
return jsonify({"error": "Dataset not loaded"}), 404
info = _cache[ds_id]
hierarchy = info["hierarchy"]
summaries = []
for ex in hierarchy["examples"]:
summaries.append({
"example_idx": ex["example_idx"],
"question_text": (ex["question_text"] or "")[:300],
"eval_correct": ex["eval_correct"],
"n_iterations": len(ex["iterations"]),
"total_input_tokens": ex["total_input_tokens"],
"total_output_tokens": ex["total_output_tokens"],
"total_execution_time": ex["total_execution_time"],
"final_answer_preview": ex["final_answer_preview"],
})
return jsonify({
"metadata": info["metadata"],
"examples": summaries,
})
@bp.route("/<ds_id>/example/<int:example_idx>", methods=["GET"])
def get_example_detail(ds_id, example_idx):
"""Level 2: Iteration timeline for one example."""
if ds_id not in _cache:
return jsonify({"error": "Dataset not loaded"}), 404
info = _cache[ds_id]
hierarchy = info["hierarchy"]
ex_data = None
for ex in hierarchy["examples"]:
if ex["example_idx"] == example_idx:
ex_data = ex
break
if ex_data is None:
return jsonify({"error": f"Example {example_idx} not found"}), 404
iters = []
for it in ex_data["iterations"]:
iters.append({
"rlm_iter": it["rlm_iter"],
"model": it["model"],
"input_tokens": it["input_tokens"],
"output_tokens": it["output_tokens"],
"execution_time": it["execution_time"],
"has_code_blocks": it["has_code_blocks"],
"n_code_blocks": len(it["code_blocks"]),
"response_preview": (it["response"] or "")[:300],
"has_final_answer": it["final_answer"] is not None,
"timestamp": it["timestamp"],
})
return jsonify({
"example_idx": example_idx,
"question_text": ex_data["question_text"],
"eval_correct": ex_data["eval_correct"],
"total_input_tokens": ex_data["total_input_tokens"],
"total_output_tokens": ex_data["total_output_tokens"],
"total_execution_time": ex_data["total_execution_time"],
"final_answer": ex_data["final_answer"],
"iterations": iters,
})
@bp.route("/<ds_id>/example/<int:example_idx>/iter/<int:rlm_iter>", methods=["GET"])
def get_iter_detail(ds_id, example_idx, rlm_iter):
"""Full detail for a specific RLM iteration within an example."""
if ds_id not in _cache:
return jsonify({"error": "Dataset not loaded"}), 404
info = _cache[ds_id]
hierarchy = info["hierarchy"]
for ex in hierarchy["examples"]:
if ex["example_idx"] != example_idx:
continue
for it in ex["iterations"]:
if it["rlm_iter"] == rlm_iter:
return jsonify(it)
return jsonify({"error": "Iteration not found"}), 404
@bp.route("/<ds_id>", methods=["DELETE"])
def unload_dataset(ds_id):
if ds_id in _cache:
del _cache[ds_id]
return jsonify({"status": "ok"})
|