tahamajs's picture
download
raw
21.8 kB
import time
import json
import numpy as np
from typing import List, Dict, Any, Optional, Tuple, Union
from dataclasses import dataclass, field
from pathlib import Path
try:
import matplotlib.pyplot as plt
import seaborn as sns
except ImportError:
plt = None
sns = None
try:
from .core.data_structures import ThoughtState, ReasoningProblem, SearchResult
from .core.base_classes import EvaluationMetric, BenchmarkSuite, ReasoningComponent
except ImportError:
from core.data_structures import ThoughtState, ReasoningProblem, SearchResult
from core.base_classes import EvaluationMetric, BenchmarkSuite, ReasoningComponent
@dataclass
class EvaluationResult:
system_name: str
problem_name: str
solution_found: bool
solution_quality: float
computational_cost: float
execution_time: float
reasoning_metrics: Dict[str, float] = field(default_factory=dict)
efficiency_metrics: Dict[str, float] = field(default_factory=dict)
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
return {
"system_name": self.system_name,
"problem_name": self.problem_name,
"solution_found": self.solution_found,
"solution_quality": self.solution_quality,
"computational_cost": self.computational_cost,
"execution_time": self.execution_time,
"reasoning_metrics": self.reasoning_metrics,
"efficiency_metrics": self.efficiency_metrics,
"metadata": self.metadata,
}
class SolutionQualityMetric(EvaluationMetric):
def __init__(self, name: str = "SolutionQualityMetric"):
super().__init__(name)
self.metric_type = "quality"
def evaluate(self, result: Any, ground_truth: Any = None) -> float:
if hasattr(result, "best_solution") and result.best_solution:
return result.best_solution.value
elif hasattr(result, "solution_quality"):
return result.solution_quality
else:
return 0.0
class ReasoningDepthMetric(EvaluationMetric):
def __init__(self, name: str = "ReasoningDepthMetric"):
super().__init__(name)
self.metric_type = "depth"
def evaluate(self, result: Any, ground_truth: Any = None) -> float:
if hasattr(result, "best_solution") and result.best_solution:
path = result.best_solution.get_path_to_root()
return len(path)
elif hasattr(result, "max_depth_reached"):
return result.max_depth_reached
else:
return 0.0
class PathEfficiencyMetric(EvaluationMetric):
def __init__(self, name: str = "PathEfficiencyMetric", optimal_depth: int = 4):
super().__init__(name)
self.metric_type = "efficiency"
self.optimal_depth = optimal_depth
def evaluate(self, result: Any, ground_truth: Any = None) -> float:
if hasattr(result, "best_solution") and result.best_solution:
actual_depth = len(result.best_solution.get_path_to_root())
return min(1.0, self.optimal_depth / max(actual_depth, 1))
elif hasattr(result, "max_depth_reached"):
return min(1.0, self.optimal_depth / max(result.max_depth_reached, 1))
else:
return 0.0
class ConsistencyMetric(EvaluationMetric):
def __init__(self, name: str = "ConsistencyMetric"):
super().__init__(name)
self.metric_type = "consistency"
def evaluate(self, result: Any, ground_truth: Any = None) -> float:
if hasattr(result, "best_solution") and result.best_solution:
return self._check_reasoning_consistency(result.best_solution)
else:
return 0.0
def _check_reasoning_consistency(self, solution: ThoughtState) -> float:
path = solution.get_path_to_root()
if len(path) < 2:
return 1.0
consistency_score = 1.0
for i in range(len(path) - 1):
current = path[i].content.lower()
next_content = path[i + 1].content.lower()
if "wrong" in current and "correct" in next_content:
consistency_score -= 0.2
if "impossible" in current and "solution" in next_content:
consistency_score -= 0.3
return max(0.0, consistency_score)
class CompletenessMetric(EvaluationMetric):
def __init__(self, name: str = "CompletenessMetric"):
super().__init__(name)
self.metric_type = "completeness"
def evaluate(self, result: Any, ground_truth: Any = None) -> float:
if hasattr(result, "best_solution") and result.best_solution:
return self._check_solution_completeness(result.best_solution)
else:
return 0.0
def _check_solution_completeness(self, solution: ThoughtState) -> float:
content = solution.content.lower()
completeness_score = 0.5
if any(word in content for word in ["result", "answer", "solution"]):
completeness_score += 0.2
if any(char.isdigit() for char in content):
completeness_score += 0.2
if len(content) > 20:
completeness_score += 0.1
return min(1.0, completeness_score)
class ReasoningEvaluator:
def __init__(self, results_dir: str = "results"):
self.results_dir = Path(results_dir)
self.results_dir.mkdir(exist_ok=True)
self.metrics = {
"solution_quality": SolutionQualityMetric(),
"reasoning_depth": ReasoningDepthMetric(),
"path_efficiency": PathEfficiencyMetric(),
"consistency": ConsistencyMetric(),
"completeness": CompletenessMetric(),
}
self.evaluation_history = []
def evaluate_reasoning_system(
self,
system: ReasoningComponent,
problem_set: List[ReasoningProblem],
system_name: str = "Unknown",
) -> Dict:
print(f"๐Ÿงช Evaluating {system_name} on {len(problem_set)} problems")
results = {
"system_name": system_name,
"problem_results": [],
"aggregate_metrics": {},
"performance_analysis": {},
"computational_analysis": {},
}
total_compute = 0
total_quality = 0
successful_solutions = 0
for i, problem in enumerate(problem_set):
print(
f" Problem {i+1}/{len(problem_set)}: {problem.problem_statement[:50]}..."
)
problem_result = self._evaluate_single_problem(system, problem, system_name)
results["problem_results"].append(problem_result)
total_compute += problem_result.computational_cost
total_quality += problem_result.solution_quality
if problem_result.solution_found:
successful_solutions += 1
results["aggregate_metrics"] = {
"success_rate": successful_solutions / len(problem_set),
"average_quality": total_quality / len(problem_set),
"average_compute": total_compute / len(problem_set),
"quality_per_compute": (total_quality / max(total_compute, 1)),
"problems_solved": successful_solutions,
"total_problems": len(problem_set),
}
results["performance_analysis"] = self._analyze_performance(
results["problem_results"]
)
results["computational_analysis"] = self._analyze_computation(
results["problem_results"]
)
self.evaluation_history.append(results)
return results
def _evaluate_single_problem(
self, system: ReasoningComponent, problem: ReasoningProblem, system_name: str
) -> EvaluationResult:
start_time = time.time()
try:
if hasattr(system, "reason_hierarchically"):
system_result = system.reason_hierarchically()
solution = system_result.get("final_result", {}).get("final_solution")
compute_cost = system_result.get("final_result", {}).get(
"total_computation", 0
)
elif hasattr(system, "scale_inference"):
system_result = system.scale_inference(problem, compute_budget=2.0)
solution = (
system_result.get("best_solution")
or system_result.get("verified_solution")
or system_result.get("final_solution")
)
compute_cost = system_result.get("compute_used", 0)
elif hasattr(system, "search"):
system_result = system.search()
solution = system_result.best_solution
compute_cost = system_result.total_states_explored
else:
system_result = system.process(problem)
solution = system_result.get("solution")
compute_cost = system_result.get("computational_cost", 0)
execution_time = time.time() - start_time
solution_quality = 0
solution_found = False
if solution:
solution_quality = problem.evaluate_state(solution)
solution_found = problem.is_solution(solution)
reasoning_metrics = self._compute_reasoning_metrics(solution, problem)
efficiency_metrics = self._compute_efficiency_metrics(
compute_cost, execution_time, solution_quality
)
return EvaluationResult(
system_name=system_name,
problem_name=problem.problem_statement[:50],
solution_found=solution_found,
solution_quality=solution_quality,
computational_cost=compute_cost,
execution_time=execution_time,
reasoning_metrics=reasoning_metrics,
efficiency_metrics=efficiency_metrics,
metadata={"system_result": system_result},
)
except Exception as e:
execution_time = time.time() - start_time
return EvaluationResult(
system_name=system_name,
problem_name=problem.problem_statement[:50],
solution_found=False,
solution_quality=0.0,
computational_cost=0,
execution_time=execution_time,
reasoning_metrics={},
efficiency_metrics={},
metadata={"error": str(e)},
)
def _compute_reasoning_metrics(
self, solution: ThoughtState, problem: ReasoningProblem
) -> Dict[str, float]:
if not solution:
return {
"reasoning_depth": 0,
"path_efficiency": 0,
"consistency_score": 0,
"completeness_score": 0,
}
path = solution.get_path_to_root()
reasoning_depth = len(path)
if isinstance(problem, type) and hasattr(problem, "optimal_depth"):
optimal_depth = getattr(problem, "optimal_depth", 4)
else:
optimal_depth = 4
path_efficiency = min(1.0, optimal_depth / max(reasoning_depth, 1))
consistency_score = self.metrics["consistency"].evaluate(
{"best_solution": solution}
)
completeness_score = self.metrics["completeness"].evaluate(
{"best_solution": solution}
)
return {
"reasoning_depth": reasoning_depth,
"path_efficiency": path_efficiency,
"consistency_score": consistency_score,
"completeness_score": completeness_score,
}
def _compute_efficiency_metrics(
self, compute_cost: float, execution_time: float, solution_quality: float
) -> Dict[str, float]:
quality_per_compute = solution_quality / max(compute_cost, 1)
quality_per_time = solution_quality / max(execution_time, 0.001)
efficiency_score = (quality_per_compute + quality_per_time) / 2
return {
"quality_per_compute": quality_per_compute,
"quality_per_time": quality_per_time,
"efficiency_score": efficiency_score,
"compute_cost": compute_cost,
"execution_time": execution_time,
}
def _analyze_performance(self, problem_results: List[EvaluationResult]) -> Dict:
if not problem_results:
return {}
depths = [
result.reasoning_metrics.get("reasoning_depth", 0)
for result in problem_results
]
qualities = [result.solution_quality for result in problem_results]
if len(depths) > 1 and len(qualities) > 1:
depth_quality_correlation = np.corrcoef(depths, qualities)[0, 1]
else:
depth_quality_correlation = 0
quality_variance = np.var(qualities) if qualities else 0
consistency_score = 1.0 / (1.0 + quality_variance)
return {
"depth_quality_correlation": depth_quality_correlation,
"performance_consistency": consistency_score,
"quality_range": [min(qualities), max(qualities)] if qualities else [0, 0],
"depth_range": [min(depths), max(depths)] if depths else [0, 0],
}
def _analyze_computation(self, problem_results: List[EvaluationResult]) -> Dict:
if not problem_results:
return {}
compute_costs = [result.computational_cost for result in problem_results]
execution_times = [result.execution_time for result in problem_results]
qualities = [result.solution_quality for result in problem_results]
if len(compute_costs) > 1 and len(qualities) > 1:
cost_quality_correlation = np.corrcoef(compute_costs, qualities)[0, 1]
else:
cost_quality_correlation = 0
if len(execution_times) > 1 and len(qualities) > 1:
time_quality_correlation = np.corrcoef(execution_times, qualities)[0, 1]
else:
time_quality_correlation = 0
return {
"average_compute_cost": np.mean(compute_costs),
"average_execution_time": np.mean(execution_times),
"cost_quality_correlation": cost_quality_correlation,
"time_quality_correlation": time_quality_correlation,
"compute_efficiency": np.mean(
[
result.efficiency_metrics.get("efficiency_score", 0)
for result in problem_results
]
),
}
def compare_systems(self, system_results: List[Dict]) -> Dict:
print(f"๐Ÿ† Comparing {len(system_results)} reasoning systems")
comparison = {
"systems_compared": len(system_results),
"metric_comparisons": {},
"rankings": {},
"statistical_significance": {},
}
metrics_to_compare = [
"success_rate",
"average_quality",
"average_compute",
"quality_per_compute",
"performance_consistency",
]
for metric in metrics_to_compare:
metric_values = []
system_names = []
for system_result in system_results:
system_names.append(system_result["system_name"])
if metric in system_result["aggregate_metrics"]:
metric_values.append(system_result["aggregate_metrics"][metric])
elif metric in system_result.get("performance_analysis", {}):
metric_values.append(system_result["performance_analysis"][metric])
else:
metric_values.append(0)
ranked_indices = np.argsort(metric_values)[::-1]
rankings = [(system_names[i], metric_values[i]) for i in ranked_indices]
comparison["metric_comparisons"][metric] = metric_values
comparison["rankings"][metric] = rankings
weights = {
"success_rate": 0.3,
"average_quality": 0.25,
"quality_per_compute": 0.2,
"performance_consistency": 0.25,
}
overall_scores = []
for i, system_result in enumerate(system_results):
score = 0
for metric, weight in weights.items():
if metric in comparison["metric_comparisons"]:
normalized_value = comparison["metric_comparisons"][metric][i]
score += weight * normalized_value
overall_scores.append(score)
overall_ranked_indices = np.argsort(overall_scores)[::-1]
overall_rankings = [
(system_results[i]["system_name"], overall_scores[i])
for i in overall_ranked_indices
]
comparison["overall_rankings"] = overall_rankings
return comparison
def save_results(self, results: Dict, filename: str = None):
if filename is None:
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f"evaluation_results_{timestamp}.json"
filepath = self.results_dir / filename
serializable_results = self._make_serializable(results)
with open(filepath, "w") as f:
json.dump(serializable_results, f, indent=2)
print(f"๐Ÿ’พ Results saved to {filepath}")
return filepath
def _make_serializable(self, obj):
if isinstance(obj, dict):
return {k: self._make_serializable(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [self._make_serializable(item) for item in obj]
elif hasattr(obj, "to_dict"):
return obj.to_dict()
elif isinstance(obj, (int, float, str, bool)) or obj is None:
return obj
else:
return str(obj)
class AdvancedReasoningBenchmark(BenchmarkSuite):
def __init__(self, name: str = "AdvancedReasoningBenchmark"):
super().__init__(name)
self.evaluator = ReasoningEvaluator()
def run_benchmark(self, system: ReasoningComponent, **kwargs) -> Dict[str, Any]:
print(f"๐Ÿƒ Running benchmark for {system.name}")
benchmark_problems = self._create_benchmark_problems()
results = self.evaluator.evaluate_reasoning_system(
system, benchmark_problems, system.name
)
analysis = self._generate_comprehensive_analysis(results)
if kwargs.get("save_results", True):
self.evaluator.save_results(results, f"benchmark_{system.name}.json")
return {
"benchmark_name": self.name,
"system_name": system.name,
"evaluation_results": results,
"comprehensive_analysis": analysis,
"benchmark_problems": len(benchmark_problems),
}
def _create_benchmark_problems(self) -> List[ReasoningProblem]:
try:
from .tree_of_thought import Game24Problem, MathWordProblem
except ImportError:
from tree_of_thought import Game24Problem, MathWordProblem
problems = []
game24_problems = [
Game24Problem([1, 1, 8, 8]),
Game24Problem([3, 3, 8, 8]),
Game24Problem([1, 5, 5, 5]),
Game24Problem([4, 7, 8, 8]),
]
problems.extend(game24_problems)
math_problems = [
MathWordProblem("If 5 apples cost $2, how much do 15 apples cost?", 6.0),
MathWordProblem(
"A car travels 60 miles in 1.5 hours. What is its average speed?", 40.0
),
MathWordProblem(
"Find the area of a rectangle with length 8 and width 5.", 40.0
),
]
problems.extend(math_problems)
return problems
def _generate_comprehensive_analysis(self, results: Dict) -> Dict:
analysis = {
"summary": {},
"strengths": [],
"weaknesses": [],
"recommendations": [],
}
aggregate = results["aggregate_metrics"]
analysis["summary"] = {
"overall_performance": (
"excellent"
if aggregate["success_rate"] > 0.8
else "good" if aggregate["success_rate"] > 0.6 else "needs_improvement"
),
"success_rate": aggregate["success_rate"],
"average_quality": aggregate["average_quality"],
"efficiency": aggregate["quality_per_compute"],
}
if aggregate["success_rate"] > 0.7:
analysis["strengths"].append("High success rate")
if aggregate["average_quality"] > 0.7:
analysis["strengths"].append("High solution quality")
if aggregate["quality_per_compute"] > 0.1:
analysis["strengths"].append("Good computational efficiency")
if aggregate["success_rate"] < 0.5:
analysis["weaknesses"].append("Low success rate")
if aggregate["average_quality"] < 0.5:
analysis["weaknesses"].append("Low solution quality")
if aggregate["quality_per_compute"] < 0.05:
analysis["weaknesses"].append("Poor computational efficiency")
if aggregate["success_rate"] < 0.6:
analysis["recommendations"].append(
"Consider using more sophisticated reasoning strategies"
)
if aggregate["average_quality"] < 0.6:
analysis["recommendations"].append(
"Improve solution validation and verification"
)
if aggregate["quality_per_compute"] < 0.05:
analysis["recommendations"].append("Optimize computational efficiency")
return analysis

Xet Storage Details

Size:
21.8 kB
ยท
Xet hash:
9f47f432b6ad76d604d7f03f7958dbc0baef90092f030c242b881ea5293c288e

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.