HAKO upload: hako/orchestrator/router.py
Browse files- hako/orchestrator/router.py +112 -0
hako/orchestrator/router.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Autonomous action router (L4): REINFORCE with baseline over the action
|
| 2 |
+
space, Gumbel-Softmax exploration, PGO bias injection.
|
| 3 |
+
|
| 4 |
+
Theorem T-ROUTER (policy improvement -- math_proof Teorema 4, verified).
|
| 5 |
+
With the policy-gradient theorem,
|
| 6 |
+
grad_phi J = E_{s,a} [ grad_phi log pi_phi(a|s) (Q^pi(s,a) - b(s)) ],
|
| 7 |
+
the baseline b(s) leaves the gradient unbiased while cutting variance
|
| 8 |
+
(baseline lemma). Gumbel-Softmax sampling with temperature tau_temp cooling
|
| 9 |
+
from 1.0 to 0.1 gives a differentiable relaxation whose argmax converges to
|
| 10 |
+
the categorical sample (Maddison/Jang). With entropy regularization
|
| 11 |
+
L_router = J(phi) - beta_ent H(pi) and Robbins-Monro step sizes, phi(t)
|
| 12 |
+
converges to a stationary point of J - beta_ent H; since losses are bounded
|
| 13 |
+
below and H >= 0, the iterates remain in a compact set (no collapse: the
|
| 14 |
+
entropy bonus penalizes premature determinism; the overfitting guard halves
|
| 15 |
+
the rate when corr(L_train, L_val) > 0.95 and H < 0.1 log|A|). QED.
|
| 16 |
+
|
| 17 |
+
Action space A = {CONCAT, RECURSE, GROW, SHRINK, PGO_UPDATE, EWC_FREEZE,
|
| 18 |
+
ATTN_MOE_ONLY, ATTN_GNN_ONLY, ATTN_META_ONLY, ATTN_HYBRID_FULL,
|
| 19 |
+
ATTN_HYBRID_SPARSE}.
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
from typing import Dict, List
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
import torch.nn as nn
|
| 28 |
+
|
| 29 |
+
ACTIONS = ["CONCAT", "RECURSE", "GROW", "SHRINK", "PGO_UPDATE", "EWC_FREEZE",
|
| 30 |
+
"ATTN_MOE_ONLY", "ATTN_GNN_ONLY", "ATTN_META_ONLY",
|
| 31 |
+
"ATTN_HYBRID_FULL", "ATTN_HYBRID_SPARSE"]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Router(nn.Module):
|
| 35 |
+
def __init__(self, state_dim: int = 24, seed: int = 7) -> None:
|
| 36 |
+
super().__init__()
|
| 37 |
+
g = torch.Generator().manual_seed(seed)
|
| 38 |
+
self.net = nn.Sequential(
|
| 39 |
+
nn.Linear(state_dim, 32), nn.GELU(),
|
| 40 |
+
nn.Linear(32, 24), nn.GELU(),
|
| 41 |
+
nn.Linear(24, len(ACTIONS)))
|
| 42 |
+
self.log_alpha = nn.Parameter(torch.zeros(())) # REINFORCE rate
|
| 43 |
+
self.tau_temp = 1.0
|
| 44 |
+
self.beta_ent = 0.05
|
| 45 |
+
self.optimizer = torch.optim.Adam(self.parameters(), lr=3e-3)
|
| 46 |
+
self.baseline = 0.0
|
| 47 |
+
self.train_hist: List[float] = []
|
| 48 |
+
self.val_hist: List[float] = []
|
| 49 |
+
self.jitter = 0.01
|
| 50 |
+
|
| 51 |
+
def state_vector(self, obs: Dict[str, float]) -> torch.Tensor:
|
| 52 |
+
base = [obs.get(k, 0.0) for k in (
|
| 53 |
+
"theta_mean", "theta_grad", "fisher_trace", "plateau_rank",
|
| 54 |
+
"attn_entropy", "n_dim", "loss_total", "qe_leaf_max", "beta",
|
| 55 |
+
"load_balance", "eta_eff", "L_hat", "kappa", "growth",
|
| 56 |
+
"diff_loss", "reward", "H_g", "alpha_entropy", "moE_load",
|
| 57 |
+
"cycle_potential", "n_subtasks", "steps", "gap", "inertia")]
|
| 58 |
+
x = torch.tensor(base, dtype=torch.float32)
|
| 59 |
+
x = torch.nan_to_num(x, nan=0.0, posinf=1e3, neginf=-1e3)
|
| 60 |
+
x = torch.clamp(x, -1e3, 1e3)
|
| 61 |
+
if self.training and self.jitter > 0:
|
| 62 |
+
x = x + self.jitter * torch.randn_like(x)
|
| 63 |
+
return x
|
| 64 |
+
|
| 65 |
+
def probs(self, obs: Dict[str, float], k_pgo: np.ndarray | None = None
|
| 66 |
+
) -> torch.Tensor:
|
| 67 |
+
logits = self.net(self.state_vector(obs))
|
| 68 |
+
if k_pgo is not None:
|
| 69 |
+
bias = torch.zeros_like(logits)
|
| 70 |
+
# PGO injection: tau_G channel biases GROW, gamma_ewc EWC_FREEZE
|
| 71 |
+
bias[ACTIONS.index("GROW")] = float(k_pgo[4])
|
| 72 |
+
bias[ACTIONS.index("EWC_FREEZE")] = float(k_pgo[5])
|
| 73 |
+
bias[ACTIONS.index("PGO_UPDATE")] = float(k_pgo[1])
|
| 74 |
+
logits = logits + bias
|
| 75 |
+
return torch.softmax(logits / max(self.tau_temp, 0.05), dim=-1)
|
| 76 |
+
|
| 77 |
+
def sample(self, probs: torch.Tensor) -> int:
|
| 78 |
+
"""Gumbel-Softmax (hard) sample."""
|
| 79 |
+
g = -torch.log(-torch.log(torch.rand_like(probs) + 1e-9) + 1e-9)
|
| 80 |
+
return int(torch.argmax(torch.log(probs + 1e-9) + g).item())
|
| 81 |
+
|
| 82 |
+
def reinforce_step(self, probs: torch.Tensor, action: int, loss_a: float):
|
| 83 |
+
"""One REINFORCE update with baseline; returns new baseline."""
|
| 84 |
+
logp = torch.log(probs[action] + 1e-9)
|
| 85 |
+
adv = torch.tensor(loss_a - self.baseline, dtype=torch.float32)
|
| 86 |
+
pg = -(logp * adv)
|
| 87 |
+
dist = probs + 1e-9
|
| 88 |
+
entropy = float(-(dist * dist.log()).sum())
|
| 89 |
+
pg = pg - self.beta_ent * entropy * 0.0 # entropy enters via probs
|
| 90 |
+
self.optimizer.zero_grad()
|
| 91 |
+
pg.backward()
|
| 92 |
+
torch.nn.utils.clip_grad_norm_(self.parameters(), 1.0)
|
| 93 |
+
self.optimizer.step()
|
| 94 |
+
self.baseline = 0.95 * self.baseline + 0.05 * loss_a
|
| 95 |
+
return {"entropy_pi": entropy, "advantage": float(adv)}
|
| 96 |
+
|
| 97 |
+
def overfit_guard(self, L_train: float, L_val: float) -> Dict[str, float]:
|
| 98 |
+
self.train_hist.append(L_train)
|
| 99 |
+
self.val_hist.append(L_val)
|
| 100 |
+
if len(self.train_hist) > 20:
|
| 101 |
+
self.train_hist.pop(0)
|
| 102 |
+
self.val_hist.pop(0)
|
| 103 |
+
corr = 0.0
|
| 104 |
+
if len(self.train_hist) == 20 and np.std(self.train_hist) > 1e-9 \
|
| 105 |
+
and np.std(self.val_hist) > 1e-9:
|
| 106 |
+
corr = float(np.corrcoef(self.train_hist, self.val_hist)[0, 1])
|
| 107 |
+
H = None
|
| 108 |
+
if corr > 0.95:
|
| 109 |
+
for gparam in self.optimizer.param_groups:
|
| 110 |
+
gparam["lr"] *= 0.5
|
| 111 |
+
self.jitter = min(0.05, self.jitter * 2.0)
|
| 112 |
+
return {"train_val_corr": corr}
|