Spaces:
Sleeping
Sleeping
File size: 11,416 Bytes
40ee6b4 |
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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
"""
MCTS Configuration Module - Parameter management and presets.
Provides:
- MCTSConfig dataclass with all parameters
- Validation of parameter bounds
- Preset configurations (fast, balanced, thorough)
- Serialization support for experiment tracking
"""
from __future__ import annotations
import json
from dataclasses import asdict, dataclass
from enum import Enum
from typing import Any
from .policies import SelectionPolicy
class ConfigPreset(Enum):
"""Preset configuration names."""
FAST = "fast"
BALANCED = "balanced"
THOROUGH = "thorough"
EXPLORATION_HEAVY = "exploration_heavy"
EXPLOITATION_HEAVY = "exploitation_heavy"
@dataclass
class MCTSConfig:
"""
Complete configuration for MCTS engine.
All MCTS parameters are centralized here with validation.
Supports serialization for experiment tracking and reproducibility.
"""
# Core MCTS parameters
num_iterations: int = 100
"""Number of MCTS iterations to run."""
seed: int = 42
"""Random seed for deterministic behavior."""
exploration_weight: float = 1.414
"""UCB1 exploration constant (c). Higher = more exploration."""
# Progressive widening
progressive_widening_k: float = 1.0
"""Progressive widening coefficient. Higher = more conservative."""
progressive_widening_alpha: float = 0.5
"""Progressive widening exponent. Lower = more aggressive expansion."""
# Rollout configuration
max_rollout_depth: int = 10
"""Maximum depth for rollout simulations."""
rollout_policy: str = "hybrid"
"""Rollout policy: 'random', 'greedy', 'hybrid'."""
# Action selection
selection_policy: SelectionPolicy = SelectionPolicy.MAX_VISITS
"""Policy for final action selection."""
# Parallelization
max_parallel_rollouts: int = 4
"""Maximum concurrent rollout simulations."""
# Caching
enable_cache: bool = True
"""Enable simulation result caching."""
cache_size_limit: int = 10000
"""Maximum number of cached simulation results."""
# Tree structure
max_tree_depth: int = 20
"""Maximum depth of MCTS tree."""
max_children_per_node: int = 50
"""Maximum children per node (action branching limit)."""
# Early termination
early_termination_threshold: float = 0.95
"""Stop if best action has this fraction of total visits."""
min_iterations_before_termination: int = 50
"""Minimum iterations before early termination check."""
# Value bounds
min_value: float = 0.0
"""Minimum value for normalization."""
max_value: float = 1.0
"""Maximum value for normalization."""
# Metadata
name: str = "default"
"""Configuration name for tracking."""
description: str = ""
"""Description of this configuration."""
def __post_init__(self):
"""Validate configuration parameters after initialization."""
self.validate()
def validate(self) -> None:
"""
Validate all configuration parameters.
Raises:
ValueError: If any parameter is out of valid bounds.
"""
errors = []
# Core parameters
if self.num_iterations < 1:
errors.append("num_iterations must be >= 1")
if self.num_iterations > 100000:
errors.append("num_iterations should be <= 100000 for practical use")
if self.exploration_weight < 0:
errors.append("exploration_weight must be >= 0")
if self.exploration_weight > 10:
errors.append("exploration_weight should be <= 10")
# Progressive widening
if self.progressive_widening_k <= 0:
errors.append("progressive_widening_k must be > 0")
if not 0 < self.progressive_widening_alpha < 1:
errors.append("progressive_widening_alpha must be in (0, 1)")
# Rollout
if self.max_rollout_depth < 1:
errors.append("max_rollout_depth must be >= 1")
if self.rollout_policy not in ["random", "greedy", "hybrid", "llm"]:
errors.append("rollout_policy must be one of: random, greedy, hybrid, llm")
# Parallelization
if self.max_parallel_rollouts < 1:
errors.append("max_parallel_rollouts must be >= 1")
if self.max_parallel_rollouts > 100:
errors.append("max_parallel_rollouts should be <= 100")
# Caching
if self.cache_size_limit < 0:
errors.append("cache_size_limit must be >= 0")
# Tree structure
if self.max_tree_depth < 1:
errors.append("max_tree_depth must be >= 1")
if self.max_children_per_node < 1:
errors.append("max_children_per_node must be >= 1")
# Early termination
if not 0 < self.early_termination_threshold <= 1:
errors.append("early_termination_threshold must be in (0, 1]")
if self.min_iterations_before_termination < 1:
errors.append("min_iterations_before_termination must be >= 1")
if self.min_iterations_before_termination > self.num_iterations:
errors.append("min_iterations_before_termination must be <= num_iterations")
# Value bounds
if self.min_value >= self.max_value:
errors.append("min_value must be < max_value")
if errors:
raise ValueError("Invalid MCTS configuration:\n" + "\n".join(f" - {e}" for e in errors))
def to_dict(self) -> dict[str, Any]:
"""
Convert configuration to dictionary for serialization.
Returns:
Dictionary representation of config.
"""
d = asdict(self)
# Convert enum to string
d["selection_policy"] = self.selection_policy.value
return d
def to_json(self, indent: int = 2) -> str:
"""
Serialize configuration to JSON string.
Args:
indent: JSON indentation level
Returns:
JSON string representation
"""
return json.dumps(self.to_dict(), indent=indent)
@classmethod
def from_dict(cls, data: dict[str, Any]) -> MCTSConfig:
"""
Create configuration from dictionary.
Args:
data: Dictionary with configuration parameters
Returns:
MCTSConfig instance
"""
# Convert selection_policy string back to enum
if "selection_policy" in data and isinstance(data["selection_policy"], str):
data["selection_policy"] = SelectionPolicy(data["selection_policy"])
return cls(**data)
@classmethod
def from_json(cls, json_str: str) -> MCTSConfig:
"""
Deserialize configuration from JSON string.
Args:
json_str: JSON string
Returns:
MCTSConfig instance
"""
data = json.loads(json_str)
return cls.from_dict(data)
def copy(self, **overrides) -> MCTSConfig:
"""
Create a copy with optional parameter overrides.
Args:
**overrides: Parameters to override
Returns:
New MCTSConfig instance
"""
data = self.to_dict()
data.update(overrides)
return self.from_dict(data)
def __repr__(self) -> str:
return (
f"MCTSConfig(name={self.name!r}, "
f"iterations={self.num_iterations}, "
f"c={self.exploration_weight}, "
f"widening_k={self.progressive_widening_k}, "
f"widening_alpha={self.progressive_widening_alpha})"
)
def create_preset_config(preset: ConfigPreset) -> MCTSConfig:
"""
Create a preset configuration.
Args:
preset: Preset type to create
Returns:
MCTSConfig with preset parameters
"""
if preset == ConfigPreset.FAST:
return MCTSConfig(
name="fast",
description="Fast search with minimal iterations",
num_iterations=25,
exploration_weight=1.414,
progressive_widening_k=0.5, # Aggressive widening
progressive_widening_alpha=0.5,
max_rollout_depth=5,
rollout_policy="random",
selection_policy=SelectionPolicy.MAX_VISITS,
max_parallel_rollouts=8,
cache_size_limit=1000,
early_termination_threshold=0.8,
min_iterations_before_termination=10,
)
elif preset == ConfigPreset.BALANCED:
return MCTSConfig(
name="balanced",
description="Balanced search for typical use cases",
num_iterations=100,
exploration_weight=1.414,
progressive_widening_k=1.0,
progressive_widening_alpha=0.5,
max_rollout_depth=10,
rollout_policy="hybrid",
selection_policy=SelectionPolicy.MAX_VISITS,
max_parallel_rollouts=4,
cache_size_limit=10000,
early_termination_threshold=0.9,
min_iterations_before_termination=50,
)
elif preset == ConfigPreset.THOROUGH:
return MCTSConfig(
name="thorough",
description="Thorough search for high-stakes decisions",
num_iterations=500,
exploration_weight=1.414,
progressive_widening_k=2.0, # Conservative widening
progressive_widening_alpha=0.6,
max_rollout_depth=20,
rollout_policy="hybrid",
selection_policy=SelectionPolicy.ROBUST_CHILD,
max_parallel_rollouts=4,
cache_size_limit=50000,
early_termination_threshold=0.95,
min_iterations_before_termination=200,
)
elif preset == ConfigPreset.EXPLORATION_HEAVY:
return MCTSConfig(
name="exploration_heavy",
description="High exploration for diverse action discovery",
num_iterations=200,
exploration_weight=2.5, # High exploration
progressive_widening_k=0.8, # More widening
progressive_widening_alpha=0.4, # Aggressive
max_rollout_depth=15,
rollout_policy="random",
selection_policy=SelectionPolicy.MAX_VISITS,
max_parallel_rollouts=6,
cache_size_limit=20000,
early_termination_threshold=0.95,
min_iterations_before_termination=100,
)
elif preset == ConfigPreset.EXPLOITATION_HEAVY:
return MCTSConfig(
name="exploitation_heavy",
description="High exploitation for known-good action refinement",
num_iterations=150,
exploration_weight=0.5, # Low exploration
progressive_widening_k=3.0, # Conservative
progressive_widening_alpha=0.7, # Very conservative
max_rollout_depth=10,
rollout_policy="greedy",
selection_policy=SelectionPolicy.MAX_VALUE,
max_parallel_rollouts=4,
cache_size_limit=10000,
early_termination_threshold=0.85,
min_iterations_before_termination=75,
)
else:
raise ValueError(f"Unknown preset: {preset}")
# Default configurations for easy access
DEFAULT_CONFIG = MCTSConfig()
FAST_CONFIG = create_preset_config(ConfigPreset.FAST)
BALANCED_CONFIG = create_preset_config(ConfigPreset.BALANCED)
THOROUGH_CONFIG = create_preset_config(ConfigPreset.THOROUGH)
|