File size: 12,663 Bytes
5fed0fc |
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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 |
"""
Persistent state tracking for incremental batch evaluation.
Tracks completed pairs to enable resume functionality.
"""
import json
import csv
from dataclasses import dataclass, field, asdict
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Set
from .pair import Pair
@dataclass
class PairResult:
"""Result of evaluating a single pair."""
pair_id: str # "solution:problem"
score: Optional[float] = None
status: str = "pending" # pending, running, success, error, timeout, skipped
message: Optional[str] = None
duration_seconds: Optional[float] = None
timestamp: Optional[str] = None
@property
def is_complete(self) -> bool:
"""Whether this pair has finished evaluation (success or failure)."""
return self.status in ("success", "error", "timeout", "skipped")
@property
def is_success(self) -> bool:
return self.status == "success"
@dataclass
class EvaluationState:
"""
Persistent state for batch evaluation.
Tracks which pairs have been evaluated, their results, and metadata.
"""
results: Dict[str, PairResult] = field(default_factory=dict)
started_at: Optional[str] = None
updated_at: Optional[str] = None
total_pairs: int = 0
backend: str = "docker" # docker or skypilot
config: Dict = field(default_factory=dict) # Evaluation configuration
@classmethod
def load(cls, path: Path) -> "EvaluationState":
"""Load state from a JSON file."""
if not path.exists():
return cls()
try:
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
except (json.JSONDecodeError, IOError):
return cls()
state = cls(
started_at=data.get("started_at"),
updated_at=data.get("updated_at"),
total_pairs=data.get("total_pairs", 0),
backend=data.get("backend", "docker"),
config=data.get("config", {}),
)
# Load results
for pair_id, result_data in data.get("results", {}).items():
state.results[pair_id] = PairResult(
pair_id=pair_id,
score=result_data.get("score"),
status=result_data.get("status", "pending"),
message=result_data.get("message"),
duration_seconds=result_data.get("duration_seconds"),
timestamp=result_data.get("timestamp"),
)
return state
def save(self, path: Path) -> None:
"""Save state to a JSON file."""
self.updated_at = datetime.now().isoformat()
data = {
"started_at": self.started_at,
"updated_at": self.updated_at,
"total_pairs": self.total_pairs,
"backend": self.backend,
"config": self.config,
"results": {
pair_id: {
"score": r.score,
"status": r.status,
"message": r.message,
"duration_seconds": r.duration_seconds,
"timestamp": r.timestamp,
}
for pair_id, r in self.results.items()
},
}
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
def get_pending_pairs(self, pairs: List[Pair]) -> List[Pair]:
"""Get pairs that haven't been successfully evaluated yet."""
return [p for p in pairs if not self.is_complete(p)]
def is_complete(self, pair: Pair) -> bool:
"""Check if a pair has been evaluated."""
result = self.results.get(pair.id)
return result is not None and result.is_complete
def mark_running(self, pair: Pair) -> None:
"""Mark a pair as currently running."""
self.results[pair.id] = PairResult(
pair_id=pair.id,
status="running",
timestamp=datetime.now().isoformat(),
)
def record_result(
self,
pair: Pair,
score: Optional[float],
status: str,
message: Optional[str] = None,
duration_seconds: Optional[float] = None,
) -> None:
"""Record the result of evaluating a pair."""
self.results[pair.id] = PairResult(
pair_id=pair.id,
score=score,
status=status,
message=message,
duration_seconds=duration_seconds,
timestamp=datetime.now().isoformat(),
)
@property
def completed_count(self) -> int:
"""Number of completed evaluations."""
return sum(1 for r in self.results.values() if r.is_complete)
@property
def success_count(self) -> int:
"""Number of successful evaluations."""
return sum(1 for r in self.results.values() if r.is_success)
@property
def error_count(self) -> int:
"""Number of failed evaluations."""
return sum(1 for r in self.results.values() if r.status in ("error", "timeout"))
def export_csv(self, path: Path) -> None:
"""Export results to a CSV file."""
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["solution", "problem", "score", "status", "message", "duration_seconds", "timestamp"])
for pair_id, result in sorted(self.results.items()):
solution, problem = pair_id.split(":", 1)
writer.writerow([
solution,
problem,
result.score if result.score is not None else "",
result.status,
result.message or "",
result.duration_seconds or "",
result.timestamp or "",
])
def export_summary(self, path: Path) -> None:
"""Export a human-readable summary."""
path.parent.mkdir(parents=True, exist_ok=True)
lines = [
f"Evaluation Summary - {datetime.now().isoformat()}",
"=" * 50,
f"Total pairs: {self.total_pairs}",
f"Completed: {self.completed_count}",
f"Successful: {self.success_count}",
f"Errors: {self.error_count}",
"",
"Results:",
"-" * 50,
]
for pair_id, result in sorted(self.results.items()):
solution, problem = pair_id.split(":", 1)
if result.is_success:
lines.append(f"{solution} -> {problem}: {result.score}")
else:
lines.append(f"{solution} -> {problem}: {result.status} - {result.message or 'N/A'}")
path.write_text("\n".join(lines), encoding="utf-8")
def export_failed(self, path: Path) -> int:
"""Export failed pairs to a file (solution:problem format). Returns count."""
path.parent.mkdir(parents=True, exist_ok=True)
failed = [
pair_id for pair_id, r in self.results.items()
if r.status in ("error", "timeout")
]
path.write_text("\n".join(sorted(failed)) + "\n" if failed else "", encoding="utf-8")
return len(failed)
def export_pending(self, path: Path, all_pairs: Optional[List[Pair]] = None) -> int:
"""Export pending/incomplete pairs. Returns count."""
path.parent.mkdir(parents=True, exist_ok=True)
if all_pairs:
# Export pairs not in results or not complete
pending = [p.id for p in all_pairs if not self.is_complete(p)]
else:
# Export pairs that are in results but not complete
pending = [
pair_id for pair_id, r in self.results.items()
if not r.is_complete
]
path.write_text("\n".join(sorted(pending)) + "\n" if pending else "", encoding="utf-8")
return len(pending)
def export_skipped(self, path: Path) -> int:
"""Export skipped pairs. Returns count."""
path.parent.mkdir(parents=True, exist_ok=True)
skipped = [
pair_id for pair_id, r in self.results.items()
if r.status == "skipped"
]
path.write_text("\n".join(sorted(skipped)) + "\n" if skipped else "", encoding="utf-8")
return len(skipped)
def get_failed_pairs(self) -> List[Pair]:
"""Get list of failed pairs."""
return [
Pair(solution=pair_id.split(":")[0], problem=pair_id.split(":")[1])
for pair_id, r in self.results.items()
if r.status in ("error", "timeout")
]
def get_successful_pairs(self) -> List[Pair]:
"""Get list of successful pairs."""
return [
Pair(solution=pair_id.split(":")[0], problem=pair_id.split(":")[1])
for pair_id, r in self.results.items()
if r.is_success
]
def aggregate_by_model(self) -> Dict[str, Dict[str, any]]:
"""Aggregate results by model (solution prefix before first _)."""
by_model: Dict[str, List[PairResult]] = {}
for pair_id, result in self.results.items():
solution = pair_id.split(":")[0]
# Extract model prefix (e.g., "gpt5_flash_attn" -> "gpt5")
model = solution.split("_")[0] if "_" in solution else solution
if model not in by_model:
by_model[model] = []
by_model[model].append(result)
aggregated = {}
for model, results in by_model.items():
successful = [r for r in results if r.is_success]
scores = [r.score for r in successful if r.score is not None]
aggregated[model] = {
"total": len(results),
"successful": len(successful),
"failed": len(results) - len(successful),
"avg_score": sum(scores) / len(scores) if scores else None,
"min_score": min(scores) if scores else None,
"max_score": max(scores) if scores else None,
}
return aggregated
def aggregate_by_problem(self) -> Dict[str, Dict[str, any]]:
"""Aggregate results by problem."""
by_problem: Dict[str, List[PairResult]] = {}
for pair_id, result in self.results.items():
problem = pair_id.split(":")[1]
if problem not in by_problem:
by_problem[problem] = []
by_problem[problem].append(result)
aggregated = {}
for problem, results in by_problem.items():
successful = [r for r in results if r.is_success]
scores = [r.score for r in successful if r.score is not None]
aggregated[problem] = {
"total": len(results),
"successful": len(successful),
"failed": len(results) - len(successful),
"avg_score": sum(scores) / len(scores) if scores else None,
"min_score": min(scores) if scores else None,
"max_score": max(scores) if scores else None,
}
return aggregated
def export_aggregated_csv(self, path: Path, by: str = "model") -> None:
"""Export aggregated results to CSV (by 'model' or 'problem')."""
path.parent.mkdir(parents=True, exist_ok=True)
if by == "model":
data = self.aggregate_by_model()
key_name = "model"
else:
data = self.aggregate_by_problem()
key_name = "problem"
with path.open("w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow([key_name, "total", "successful", "failed", "avg_score", "min_score", "max_score"])
for key, stats in sorted(data.items()):
writer.writerow([
key,
stats["total"],
stats["successful"],
stats["failed"],
f"{stats['avg_score']:.4f}" if stats["avg_score"] is not None else "",
stats["min_score"] if stats["min_score"] is not None else "",
stats["max_score"] if stats["max_score"] is not None else "",
])
|