File size: 4,358 Bytes
a5943fd | 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 | # Hard-mode CFP reference solution for the Classification Fields RL
# environment (arXiv:2605.07119, mode="hard"). Expected reward: ~1.0.
#
# Implements the paper's Classification Field Predictor exactly as the
# official repo does at cb52f15: an MLP r_hat: R^d -> R^{d*K} (3 hidden layers
# of width 64 with ReLU), trained with Adam (lr 1e-3, 2000 epochs) on the
# observed parent->child edges of levels 0-2 with the official
# hierarchy_loss (sum of squared errors), then rolled out AUTOREGRESSIVELY to
# levels 3-5 — each level's parents are the model's own predictions.
#
# The server's CFP anchor uses this same protocol, so this solution lands at
# the reward=1 reference of the normalized scale.
#
# Usage:
# python scripts/hard/cfp_reference.py --base-url http://localhost:8000
# python scripts/hard/cfp_reference.py --base-url http://localhost:8000 --seeds eval
import argparse
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from hard_common import parse_seeds, run_batch
torch.set_num_threads(1)
# Anchor seed (published by the server, get_paper_summary): re-seeded before
# EVERY fit so multi-seed runs reproduce the server's anchors exactly.
ANCHOR_TORCH_SEED = 0
class HRGMLP(nn.Module):
"""MLP residual generator (official HRGMLP): 3x(Linear(64)+ReLU) -> Linear(2K)."""
def __init__(self, d: int = 2, K: int = 3, hidden_width: int = 64, depth: int = 3):
super().__init__()
layers = []
in_dim = d
for _ in range(depth):
layers.append(nn.Linear(in_dim, hidden_width))
layers.append(nn.ReLU())
in_dim = hidden_width
layers.append(nn.Linear(in_dim, d * K))
self.net = nn.Sequential(*layers)
self.d = d
self.K = K
def forward(self, x):
out = self.net(x)
return out.view(-1, self.K, self.d)
def observed_training_data(info: dict):
"""Parent -> children tensors from the observed levels 0-2 (scale=1)."""
K = info["K"]
l0 = np.asarray(info["levels"]["0"], dtype=np.float32)
l1 = np.asarray(info["levels"]["1"], dtype=np.float32)
l2 = np.asarray(info["levels"]["2"], dtype=np.float32)
X = np.vstack([l0, l1])
Y = np.vstack([l1.reshape(1, K, -1), l2.reshape(K, K, -1)])
return (
torch.tensor(X, dtype=torch.float32),
torch.tensor(Y, dtype=torch.float32),
)
def rollout(model, x0, K: int, max_level: int = 5):
"""Autoregressive rollout: each level's parents are the model's own predictions."""
levels = [np.asarray(x0, dtype=np.float32).reshape(1, -1)]
with torch.no_grad():
for _ in range(1, max_level + 1):
parents = levels[-1]
residuals = model(torch.tensor(parents)).numpy() # (n, K, d)
children = (parents[:, None, :] + residuals).reshape(-1, parents.shape[1])
levels.append(children)
return levels
def solve(info: dict) -> dict:
torch.manual_seed(ANCHOR_TORCH_SEED) # mirrors the server's anchor fit
K = info["K"]
X, Y = observed_training_data(info)
model = HRGMLP(d=2, K=K)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
for _ in range(2000):
model.train()
optimizer.zero_grad()
pred_children = X.unsqueeze(1) + model(X) # scale = 1.0
loss = ((pred_children - Y) ** 2).sum() # official hierarchy_loss
loss.backward()
optimizer.step()
model.eval()
rolled = rollout(model, info["x0"], K)
return {
"3": rolled[3].tolist(),
"4": rolled[4].tolist(),
"5": rolled[5].tolist(),
}
def main() -> int:
parser = argparse.ArgumentParser(
description=(
"Hard-mode CFP reference solution (expect reward ~1.0) for "
"arXiv:2605.07119 classification fields, mode=hard."
)
)
parser.add_argument("--base-url", required=True)
parser.add_argument("--seeds", default="eval", help="'eval', 'practice', '100-109' or a comma list")
args = parser.parse_args()
seeds = parse_seeds(args.seeds)
print(f"cfp_reference solution on {len(seeds)} seeds: {seeds}")
run_batch(args.base_url, solve, seeds, label="cfp_reference")
return 0
if __name__ == "__main__":
sys.exit(main())
|