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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AAM Diffusion LLM — MCTS Reasoning Engine
|
| 2 |
+
|
| 3 |
+
AlphaZero-style tree search for reasoning about narrative arrangement
|
| 4 |
+
from graph evidence. AAM-specific: each node = a sentence arrangement,
|
| 5 |
+
value = narrative coherence, policy = next arrangement step.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import math
|
| 11 |
+
from dataclasses import dataclass, field
|
| 12 |
+
from typing import Optional, List, Dict, Any, Tuple
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MCTSConfig:
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
num_simulations: int = 64,
|
| 23 |
+
c_puct: float = 1.5,
|
| 24 |
+
temperature: float = 1.0,
|
| 25 |
+
max_depth: int = 10,
|
| 26 |
+
use_value_network: bool = True,
|
| 27 |
+
use_progressive_widening: bool = True,
|
| 28 |
+
max_children: int = 8,
|
| 29 |
+
) -> None:
|
| 30 |
+
self.num_simulations = num_simulations
|
| 31 |
+
self.c_puct = c_puct
|
| 32 |
+
self.temperature = temperature
|
| 33 |
+
self.max_depth = max_depth
|
| 34 |
+
self.use_value_network = use_value_network
|
| 35 |
+
self.use_progressive_widening = use_progressive_widening
|
| 36 |
+
self.max_children = max_children
|
| 37 |
+
|
| 38 |
+
if num_simulations <= 0:
|
| 39 |
+
raise ValueError(f"num_simulations must be positive, got {num_simulations}")
|
| 40 |
+
if c_puct <= 0:
|
| 41 |
+
raise ValueError(f"c_puct must be positive, got {c_puct}")
|
| 42 |
+
if max_depth <= 0:
|
| 43 |
+
raise ValueError(f"max_depth must be positive, got {max_depth}")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class MCTSNode:
|
| 48 |
+
state: Optional[torch.Tensor] = None
|
| 49 |
+
parent: Optional["MCTSNode"] = None
|
| 50 |
+
children: List["MCTSNode"] = field(default_factory=list)
|
| 51 |
+
visit_count: int = 0
|
| 52 |
+
total_value: float = 0.0
|
| 53 |
+
prior: float = 0.0
|
| 54 |
+
depth: int = 0
|
| 55 |
+
is_expanded: bool = False
|
| 56 |
+
action: Optional[int] = None
|
| 57 |
+
hidden_state: Optional[torch.Tensor] = None
|
| 58 |
+
|
| 59 |
+
@property
|
| 60 |
+
def q_value(self) -> float:
|
| 61 |
+
if self.visit_count == 0:
|
| 62 |
+
return 0.0
|
| 63 |
+
return self.total_value / self.visit_count
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def is_leaf(self) -> bool:
|
| 67 |
+
return not self.is_expanded
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def is_root(self) -> bool:
|
| 71 |
+
"""Whether this node is the root."""
|
| 72 |
+
return self.parent is None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class ValueNetwork(nn.Module):
|
| 76 |
+
"""Evaluate narrative coherence of a state."""
|
| 77 |
+
def __init__(self, d_model: int, hidden_dim: int = 256) -> None:
|
| 78 |
+
super().__init__()
|
| 79 |
+
self.network = nn.Sequential(
|
| 80 |
+
nn.Linear(d_model, hidden_dim, bias=False),
|
| 81 |
+
nn.SiLU(),
|
| 82 |
+
nn.Linear(hidden_dim, hidden_dim // 2, bias=False),
|
| 83 |
+
nn.SiLU(),
|
| 84 |
+
nn.Linear(hidden_dim // 2, 1, bias=False),
|
| 85 |
+
nn.Tanh(),
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 89 |
+
return self.network(x)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class PolicyNetwork(nn.Module):
|
| 93 |
+
"""Suggest next arrangement step."""
|
| 94 |
+
def __init__(self, d_model: int, num_actions: int = 8) -> None:
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.network = nn.Sequential(
|
| 97 |
+
nn.Linear(d_model, d_model // 2, bias=False),
|
| 98 |
+
nn.SiLU(),
|
| 99 |
+
nn.Linear(d_model // 2, num_actions, bias=False),
|
| 100 |
+
)
|
| 101 |
+
self.num_actions = num_actions
|
| 102 |
+
|
| 103 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 104 |
+
return self.network(x)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class MCTSReasoner(nn.Module):
|
| 108 |
+
"""MCTS Reasoning Engine for AAM sentence arrangement."""
|
| 109 |
+
|
| 110 |
+
def __init__(
|
| 111 |
+
self,
|
| 112 |
+
d_model: int,
|
| 113 |
+
num_actions: int = 8,
|
| 114 |
+
config: Optional[MCTSConfig] = None,
|
| 115 |
+
) -> None:
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.d_model = d_model
|
| 118 |
+
self.num_actions = num_actions
|
| 119 |
+
self.config = config or MCTSConfig()
|
| 120 |
+
|
| 121 |
+
if self.config.use_value_network:
|
| 122 |
+
self.value_network = ValueNetwork(d_model)
|
| 123 |
+
else:
|
| 124 |
+
self.value_network = None
|
| 125 |
+
|
| 126 |
+
self.policy_network = PolicyNetwork(d_model, num_actions)
|
| 127 |
+
|
| 128 |
+
self.state_encoder = nn.Sequential(
|
| 129 |
+
nn.Linear(d_model, d_model, bias=False),
|
| 130 |
+
nn.SiLU(),
|
| 131 |
+
nn.Linear(d_model, d_model, bias=False),
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def forward(
|
| 135 |
+
self,
|
| 136 |
+
x: torch.Tensor,
|
| 137 |
+
num_simulations: Optional[int] = None,
|
| 138 |
+
) -> Tuple[torch.Tensor, Dict[str, Any]]:
|
| 139 |
+
batch_size = x.shape[0]
|
| 140 |
+
n_sims = num_simulations or self.config.num_simulations
|
| 141 |
+
|
| 142 |
+
encoded_state = self.state_encoder(x)
|
| 143 |
+
# Pool over sequence dimension if 3D input
|
| 144 |
+
if encoded_state.dim() == 3:
|
| 145 |
+
pooled_state = encoded_state.mean(dim=1) # (batch, d_model)
|
| 146 |
+
else:
|
| 147 |
+
pooled_state = encoded_state # (batch, d_model)
|
| 148 |
+
|
| 149 |
+
policy_logits = self.policy_network(pooled_state) # (batch, num_actions)
|
| 150 |
+
policy_probs = F.softmax(policy_logits / self.config.temperature, dim=-1) # (batch, num_actions)
|
| 151 |
+
|
| 152 |
+
if self.value_network is not None:
|
| 153 |
+
root_value = self.value_network(pooled_state) # (batch, 1)
|
| 154 |
+
else:
|
| 155 |
+
root_value = torch.zeros(batch_size, 1, device=x.device)
|
| 156 |
+
|
| 157 |
+
visit_counts = torch.zeros(batch_size, self.num_actions, device=x.device, dtype=torch.float32)
|
| 158 |
+
total_values = torch.zeros(batch_size, self.num_actions, device=x.device, dtype=torch.float32)
|
| 159 |
+
|
| 160 |
+
for sim_idx in range(n_sims):
|
| 161 |
+
ucb_scores = self._compute_ucb(visit_counts, total_values, policy_probs, n_sims)
|
| 162 |
+
selected_actions = ucb_scores.argmax(dim=-1)
|
| 163 |
+
|
| 164 |
+
if self.value_network is not None:
|
| 165 |
+
action_onehot = F.one_hot(selected_actions, self.num_actions).float()
|
| 166 |
+
action_proj = action_onehot @ self.policy_network.network[-1].weight
|
| 167 |
+
padding = torch.zeros(batch_size, self.d_model - action_proj.shape[-1], device=x.device)
|
| 168 |
+
action_embedding = torch.cat([action_proj, padding], dim=-1)
|
| 169 |
+
state_action = pooled_state + action_embedding
|
| 170 |
+
sim_values = self.value_network(state_action)
|
| 171 |
+
else:
|
| 172 |
+
sim_values = torch.rand(batch_size, 1, device=x.device) * 2 - 1
|
| 173 |
+
|
| 174 |
+
visit_counts.scatter_add_(1, selected_actions.unsqueeze(1),
|
| 175 |
+
torch.ones(batch_size, 1, device=x.device, dtype=visit_counts.dtype))
|
| 176 |
+
total_values.scatter_add_(1, selected_actions.unsqueeze(1), sim_values)
|
| 177 |
+
|
| 178 |
+
if self.config.temperature > 0:
|
| 179 |
+
action_probs = F.softmax(visit_counts.log() / self.config.temperature, dim=-1)
|
| 180 |
+
action_probs = torch.where(visit_counts > 0, action_probs, torch.zeros_like(action_probs))
|
| 181 |
+
row_sums = action_probs.sum(dim=-1, keepdim=True)
|
| 182 |
+
action_probs = torch.where(
|
| 183 |
+
row_sums > 1e-6,
|
| 184 |
+
action_probs / (row_sums + 1e-8),
|
| 185 |
+
torch.full_like(action_probs, 1.0 / self.num_actions),
|
| 186 |
+
)
|
| 187 |
+
else:
|
| 188 |
+
action_probs = F.one_hot(visit_counts.argmax(dim=-1), self.num_actions).float()
|
| 189 |
+
|
| 190 |
+
info = {
|
| 191 |
+
"total_simulations": n_sims,
|
| 192 |
+
"root_value": root_value.mean().item(),
|
| 193 |
+
"max_visit_count": visit_counts.max().item(),
|
| 194 |
+
"entropy": -(action_probs * (action_probs + 1e-8).log()).sum(-1).mean().item(),
|
| 195 |
+
"visit_distribution": visit_counts / (visit_counts.sum(-1, keepdim=True) + 1e-8),
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
return action_probs, info
|
| 199 |
+
|
| 200 |
+
def _compute_ucb(self, visit_counts, total_values, priors, total_simulations):
|
| 201 |
+
q_values = torch.where(
|
| 202 |
+
visit_counts > 0,
|
| 203 |
+
total_values / (visit_counts + 1e-8),
|
| 204 |
+
torch.zeros_like(total_values),
|
| 205 |
+
)
|
| 206 |
+
parent_visits = visit_counts.sum(dim=-1, keepdim=True)
|
| 207 |
+
exploration = self.config.c_puct * priors * torch.sqrt(parent_visits + 1) / (1 + visit_counts)
|
| 208 |
+
return q_values + exploration
|
| 209 |
+
|
| 210 |
+
def compute_thinking_budget(self, complexity_score: float, base_simulations: int = 16, max_simulations: int = 256) -> int:
|
| 211 |
+
"""Compute number of MCTS simulations based on complexity.
|
| 212 |
+
|
| 213 |
+
Adaptive compute budget: more complex inputs get more simulations.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
complexity_score: Complexity score [0, 1] from ThinkingToggle.
|
| 217 |
+
base_simulations: Minimum number of simulations.
|
| 218 |
+
max_simulations: Maximum number of simulations.
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
Recommended number of simulations.
|
| 222 |
+
"""
|
| 223 |
+
return int(base_simulations + (max_simulations - base_simulations) * (complexity_score ** 2))
|
| 224 |
+
|
| 225 |
+
def get_reasoning_summary(self, info: Dict[str, Any]) -> str:
|
| 226 |
+
"""Summary of reasoning for logging.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
info: Dictionary from forward output.
|
| 230 |
+
|
| 231 |
+
Returns:
|
| 232 |
+
Summary string.
|
| 233 |
+
"""
|
| 234 |
+
return (
|
| 235 |
+
f"MCTS(sims={info['total_simulations']}, "
|
| 236 |
+
f"root_val={info['root_value']:.3f}, "
|
| 237 |
+
f"max_visits={info['max_visit_count']:.0f}, "
|
| 238 |
+
f"entropy={info['entropy']:.3f})"
|
| 239 |
+
)
|