File size: 27,628 Bytes
d9b9e9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#!/usr/bin/env python3
"""Numerical core for the v3 learned acquisition/action-controller experiment.

The learning scaffold is fixed. Exported regression trees are executable policies.
All solver-facing information comes from paired value-gradient observations.
"""
from __future__ import annotations
import os
for _variable in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
    os.environ[_variable] = "1"
import copy
import hashlib
import json
import math
import time
import warnings
from dataclasses import dataclass
from pathlib import Path
import numpy as np
from scipy.optimize import line_search, minimize, SR1
from scipy.special import expit, logsumexp
from sklearn.tree import DecisionTreeRegressor

TRAIN_FAMILIES = ["pseudo_huber", "softplus_squared", "smooth_max", "asinh_squared"]
FINAL_FAMILIES = ["cauchy", "gaussian_saturation", "matrix_gram"]
ACTION_NAMES = ["bfgs_wolfe", "bb_trial", "preconditioned_trial", "curvature_probe", "reset_bfgs"]
FEATURE_NAMES = ["log_dimension", "log_gradient_ratio", "log_current_loss_ratio",
    "log_best_loss_ratio", "relative_last_loss_change", "log_iteration", "log_mean_inverse_scale",
    "log_preconditioned_gradient_scale", "gradient_preconditioned_cosine", "last_gradient_cosine",
    "last_secant_cosine", "log_bb_scale", "log_last_step_norm", "last_trial_rejected",
    "last_curvature_update", "log_current_x_norm"]


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False)


def digest(value):
    return hashlib.sha256(canonical(value).encode()).hexdigest()


def array_digest(*arrays):
    h = hashlib.sha256()
    for array in arrays:
        array = np.asarray(array)
        h.update(str(array.dtype).encode()); h.update(str(array.shape).encode()); h.update(array.tobytes())
    return h.hexdigest()


@dataclass
class Task:
    family: str
    seed: int
    dimension: int
    matrix: np.ndarray
    target: np.ndarray
    ridge: float
    parameter: float
    offset: np.ndarray

    def value_gradient(self, x):
        error = x - self.target
        u = self.matrix @ error
        d = self.dimension
        penalty = 0.5 * self.ridge * float(error @ error)
        if self.family == "pseudo_huber":
            delta = self.parameter
            hyp = np.hypot(u, delta)
            value = np.mean(delta * (hyp - delta))
            derivative = delta * u / hyp
        elif self.family == "softplus_squared":
            shifted = u + self.offset
            residual = np.logaddexp(0., shifted) - np.logaddexp(0., self.offset)
            value = np.mean(residual * residual)
            derivative = 2 * residual * expit(shifted)
        elif self.family == "smooth_max":
            temperature = self.parameter
            terms = temperature * u * u
            normalizer = logsumexp(terms)
            value = (normalizer - math.log(d)) / temperature
            derivative = d * 2 * u * np.exp(terms - normalizer)
        elif self.family == "asinh_squared":
            transformed = np.arcsinh(u)
            value = np.mean(transformed * transformed)
            derivative = 2 * transformed / np.hypot(1., u)
        elif self.family == "cauchy":
            value = np.mean(np.log1p(u * u))
            derivative = 2 * u / (1 + u * u)
        elif self.family == "gaussian_saturation":
            value = np.mean(-np.expm1(-0.5 * u * u))
            derivative = u * np.exp(-0.5 * u * u)
        elif self.family == "matrix_gram":
            columns = d // 4
            y = self.offset.reshape(4, columns) + (self.matrix @ x).reshape(4, columns)
            optimum = self.offset.reshape(4, columns) + (self.matrix @ self.target).reshape(4, columns)
            residual = y.T @ y - optimum.T @ optimum
            value = np.mean(residual * residual)
            gradient = self.matrix.T @ (4 * y @ residual).reshape(-1) / (columns * columns)
            return max(float(value + penalty), 0.), gradient + self.ridge * error
        else:
            raise ValueError(self.family)
        gradient = self.matrix.T @ derivative / d + self.ridge * error
        return max(float(value + penalty), 0.), gradient


def make_task(family, seed, dimension):
    rng = np.random.default_rng(seed)
    q, _ = np.linalg.qr(rng.normal(size=(dimension, dimension)))
    condition = 10 ** rng.uniform(0.4, 2.5)
    scale = 10 ** rng.uniform(-0.4, 0.3)
    singular = scale * np.geomspace(1., math.sqrt(condition), dimension)
    matrix = singular[:, None] * q
    target = rng.normal(size=dimension)
    target *= rng.uniform(0.8, 2.5) / np.linalg.norm(target)
    ridge = 10 ** rng.uniform(-3.5, -1.5)
    parameter = float(rng.uniform(0.3, 1.5))
    offset = rng.normal(scale=0.5, size=dimension)
    if family == "matrix_gram":
        matrix *= 0.25
        ridge = float(10 ** rng.uniform(-2.5, -1.2))
    return Task(family, seed, dimension, matrix, target, float(ridge), parameter, offset)


def tasks_for(stage, pilot=False):
    if stage not in ("train", "development", "final"):
        raise ValueError(stage)
    if pilot and stage == "final":
        raise ValueError("Pilot must never call final generators")
    families = FINAL_FAMILIES if stage == "final" else TRAIN_FAMILIES
    repetitions = 24 if stage == "final" else (1 if pilot else 3)
    base = {"train": 7100000, "development": 7200000, "final": 7900000}[stage]
    tasks = []
    for family_index, family in enumerate(families):
        for replicate in range(repetitions):
            dimension = (16, 32, 64)[replicate % 3] if stage == "final" else (8, 16, 32)[replicate % 3]
            tasks.append(make_task(family, base + 1000 * family_index + replicate, dimension))
    return tasks


class BudgetExhausted(Exception):
    pass


class Oracle:
    def __init__(self, task, budget, initial_value=None, previous_best=None):
        self.task, self.budget, self.calls = task, int(budget), 0
        self.initial_value = initial_value
        self.best_value = math.inf if previous_best is None else previous_best
        self.best_curve, self.current_curve = [], []
        self.nonfinite = 0

    def query(self, x):
        if self.calls >= self.budget:
            raise BudgetExhausted()
        self.calls += 1
        with np.errstate(over="ignore", invalid="ignore", divide="ignore", under="ignore"):
            value, gradient = self.task.value_gradient(np.asarray(x))
        if not np.isfinite(value) or not np.isfinite(gradient).all():
            self.nonfinite += 1
            value = 1e100
            gradient = np.nan_to_num(gradient, nan=0., posinf=1e50, neginf=-1e50)
            gradient = np.clip(gradient, -1e50, 1e50)
        if self.initial_value is None:
            self.initial_value = max(float(value), 1e-300)
        self.best_value = min(self.best_value, float(value))
        self.best_curve.append(self.best_value / self.initial_value)
        self.current_curve.append(float(value) / self.initial_value)
        return float(value), np.asarray(gradient)

    def result(self):
        return {"calls": self.calls, "best_curve": np.asarray(self.best_curve),
                "current_curve": np.asarray(self.current_curve), "nonfinite": self.nonfinite}


class PairedLineAdapter:
    """One paired query supplies both f and g when SciPy requests them separately."""
    def __init__(self, oracle, state):
        self.oracle = oracle
        self.cached_x, self.cached_f, self.cached_g = state.x.copy(), state.value, state.gradient.copy()
        self.trials = []

    def pair(self, x):
        if not np.array_equal(x, self.cached_x):
            self.cached_f, self.cached_g = self.oracle.query(x)
            self.cached_x = np.array(x, copy=True)
            self.trials.append((self.cached_x.copy(), self.cached_f, self.cached_g.copy()))
        return self.cached_f, self.cached_g

    def value(self, x): return self.pair(x)[0]
    def gradient(self, x): return self.pair(x)[1]


@dataclass
class State:
    x: np.ndarray
    value: float
    gradient: np.ndarray
    inverse: np.ndarray
    initial_value: float
    initial_gradient_norm: float
    previous_value: float
    best_value: float
    iteration: int = 0
    bb_scale: float = 1.
    last_gradient_cosine: float = 0.
    last_secant_cosine: float = 0.
    last_step_norm: float = 0.
    last_rejected: float = 0.
    last_updated: float = 0.

    def clone(self): return copy.deepcopy(self)

    def signature(self):
        scalars = [self.value, self.initial_value, self.initial_gradient_norm, self.previous_value,
                   self.best_value, self.iteration, self.bb_scale, self.last_gradient_cosine,
                   self.last_secant_cosine, self.last_step_norm, self.last_rejected, self.last_updated]
        return array_digest(self.x, self.gradient, self.inverse, np.asarray(scalars))


def initial_state(oracle, inverse_scale=1.):
    x = np.zeros(oracle.task.dimension)
    value, gradient = oracle.query(x)
    norm = max(float(np.linalg.norm(gradient)), 1e-300)
    return State(x, value, gradient, np.eye(len(x)) * inverse_scale,
                 oracle.initial_value, norm, value + norm / 2, value,
                 bb_scale=float(np.clip(1 / norm, 1e-6, 10.)))


def safe_log(value): return math.log10(max(min(float(value), 1e100), 1e-12))


def state_features(state):
    g, h = state.gradient, state.inverse
    gn = max(float(np.linalg.norm(g)), 1e-300)
    direction = h @ g
    dn = max(float(np.linalg.norm(direction)), 1e-300)
    features = [math.log1p(len(g)), safe_log(gn / state.initial_gradient_norm),
        safe_log(state.value / state.initial_value), safe_log(state.best_value / state.initial_value),
        float(np.clip((state.value - state.previous_value) / max(abs(state.previous_value), state.initial_value * 1e-12), -10, 10)),
        math.log1p(state.iteration), safe_log(abs(float(np.trace(h))) / len(g)), safe_log(dn / gn),
        float(np.clip(float(g @ direction) / (gn * dn), -1, 1)), state.last_gradient_cosine,
        state.last_secant_cosine, safe_log(state.bb_scale), math.log1p(state.last_step_norm),
        state.last_rejected, state.last_updated, math.log1p(float(np.linalg.norm(state.x)))]
    return np.nan_to_num(np.asarray(features), nan=0., posinf=100., neginf=-100.)


def update_from_trial(state, x, value, gradient, accept=True):
    s, y = x - state.x, gradient - state.gradient
    sn, yn = float(np.linalg.norm(s)), float(np.linalg.norm(y))
    sy = float(s @ y)
    state.last_step_norm = sn
    state.last_secant_cosine = float(np.clip(sy / max(sn * yn, 1e-300), -1, 1))
    state.last_gradient_cosine = float(np.clip(float(state.gradient @ gradient) /
        max(float(np.linalg.norm(state.gradient) * np.linalg.norm(gradient)), 1e-300), -1, 1))
    state.last_updated = 0.
    if sy > 1e-10 * max(sn * yn, 1e-20):
        hy = state.inverse @ y
        candidate = state.inverse + ((sy + float(y @ hy)) / (sy * sy)) * np.outer(s, s)
        candidate -= (np.outer(hy, s) + np.outer(s, hy)) / sy
        candidate = (candidate + candidate.T) / 2
        if np.isfinite(candidate).all() and np.max(np.abs(candidate)) < 1e12:
            state.inverse = candidate
            state.last_updated = 1.
        state.bb_scale = float(np.clip(float(s @ s) / sy, 1e-6, 10.))
    state.last_rejected = float(not accept)
    if accept:
        state.previous_value = state.value
        state.x, state.value, state.gradient = np.array(x, copy=True), float(value), np.array(gradient, copy=True)


def bfgs_action(state, oracle, reset=False, c2=0.9):
    if reset:
        state.inverse = np.eye(len(state.x)) * state.bb_scale
        state.previous_value = state.value + float(np.linalg.norm(state.gradient)) / 2
    direction = -(state.inverse @ state.gradient)
    if not np.isfinite(direction).all() or float(direction @ state.gradient) >= -1e-14 * float(state.gradient @ state.gradient):
        direction = -state.gradient
    adapter = PairedLineAdapter(oracle, state)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        answer = line_search(adapter.value, adapter.gradient, state.x, direction,
            gfk=state.gradient, old_fval=state.value, old_old_fval=state.previous_value,
            c1=1e-4, c2=c2, maxiter=12)
    alpha = answer[0]
    if alpha is not None and np.isfinite(alpha):
        point = state.x + alpha * direction
        value, gradient = adapter.pair(point)
        update_from_trial(state, point, value, gradient)
    elif adapter.trials:
        point, value, gradient = min(adapter.trials, key=lambda row: row[1])
        update_from_trial(state, point, value, gradient, accept=value < state.value)
    else:
        point = state.x - min(state.bb_scale, 1.) * state.gradient
        value, gradient = oracle.query(point)
        update_from_trial(state, point, value, gradient, accept=value < state.value)


def execute_action(state, oracle, action):
    if action in (0, 4):
        bfgs_action(state, oracle, reset=action == 4)
    elif action in (1, 2):
        step = state.bb_scale * state.gradient if action == 1 else state.inverse @ state.gradient
        norm = float(np.linalg.norm(step))
        step *= min(1., 1.5 / max(norm, 1e-300))
        point = state.x - step
        value, gradient = oracle.query(point)
        update_from_trial(state, point, value, gradient, accept=action == 1 or value < state.value)
    elif action == 3:
        direction = np.zeros(len(state.x)); direction[(7 * state.iteration + 3) % len(direction)] = 1.
        g = state.gradient
        direction -= g * (float(direction @ g) / max(float(g @ g), 1e-300))
        direction /= max(float(np.linalg.norm(direction)), 1e-12)
        radius = 0.1 * max(1., float(np.linalg.norm(state.x))) / math.sqrt(len(direction))
        point = state.x + radius * direction
        value, gradient = oracle.query(point)
        update_from_trial(state, point, value, gradient, accept=value < state.value)
    else:
        raise ValueError(action)
    state.iteration += 1
    state.best_value = min(state.best_value, oracle.best_value)


def serialize_tree(fitted):
    t = fitted.tree_
    return {"feature": t.feature.tolist(), "threshold": t.threshold.tolist(),
            "left": t.children_left.tolist(), "right": t.children_right.tolist(),
            "value": t.value[:, :, 0].tolist()}


def tree_predict(tree, features):
    features = np.asarray(features, dtype=np.float32)
    node = 0
    while tree["left"][node] != -1:
        node = tree["left"][node] if features[tree["feature"][node]] <= tree["threshold"][node] else tree["right"][node]
    return np.asarray(tree["value"][node], dtype=float)


def initial_policy(): return {"kind": "constant", "action": 0, "description": "Initial strong-Wolfe BFGS controller"}


def policy_predictions(policy, features):
    if policy["kind"] == "constant":
        scores = np.zeros((1, len(ACTION_NAMES)))
        return scores.mean(axis=0), np.zeros(len(ACTION_NAMES)), scores
    scores = np.asarray([tree_predict(t, features) for t in policy["trees"]])
    return scores.mean(axis=0), scores.std(axis=0), scores


def policy_action(policy, features):
    if policy["kind"] == "constant": return int(policy["action"])
    mean, std, values = policy_predictions(policy, features)
    best = int(np.argmin(mean))
    uncertainty = float(np.std(values[:, 0] - values[:, best]))
    if mean[0] - mean[best] <= policy["switch_margin"] + policy["uncertainty_multiplier"] * uncertainty:
        return 0
    return best


def fit_policy(features, labels, seed):
    rng = np.random.default_rng(seed)
    features, labels = np.asarray(features), np.asarray(labels)
    # Only action contrasts determine the decision. Centering removes the shared
    # state-dependent loss level from the regression-tree splitting objective.
    labels = labels - labels[:, [0]]
    trees = []
    for tree_index in range(5):
        indices = rng.integers(len(features), size=len(features))
        model = DecisionTreeRegressor(max_depth=4, min_samples_leaf=8, random_state=seed + tree_index)
        model.fit(features[indices], labels[indices])
        trees.append(serialize_tree(model))
    return {"kind": "tree_ensemble", "trees": trees, "switch_margin": 0.02,
            "uncertainty_multiplier": 0.5, "features": FEATURE_NAMES,
            "actions": ACTION_NAMES, "training_examples": len(features),
            "regression_target": "counterfactual terminal log-loss minus BFGS-action terminal log-loss"}


def acquisition_features(policy, features):
    mean, std, predictions = policy_predictions(policy, features)
    actions = np.argmin(predictions, axis=1)
    disagreement = 1 - max(np.mean(actions == a) for a in range(len(ACTION_NAMES)))
    ordered = np.sort(mean)
    return np.concatenate([features, mean, std, [disagreement, ordered[1] - ordered[0], np.max(std)]])


def fit_selector(features, regrets, seed):
    model = DecisionTreeRegressor(max_depth=3, min_samples_leaf=8, random_state=seed)
    model.fit(np.asarray(features), np.asarray(regrets))
    return {"kind": "regret_tree", "tree": serialize_tree(model), "training_examples": len(features),
            "target": "observed finite-horizon regret of current action versus best labeled action"}


def solve_policy(task, policy, budget, collect=False, start_state=None, first_action=None):
    started_cpu, started_wall = time.process_time(), time.perf_counter()
    oracle = Oracle(task, budget, initial_value=start_state.initial_value if start_state else None,
                    previous_best=start_state.best_value if start_state else None)
    state = start_state.clone() if start_state else initial_state(oracle)
    pool, action_counts = [], np.zeros(len(ACTION_NAMES), dtype=int)
    forced = first_action
    while oracle.calls < budget:
        if float(np.linalg.norm(state.gradient)) <= 1e-12 * max(1., state.initial_gradient_norm):
            break
        features = state_features(state)
        if collect:
            pool.append({"task": task, "state": state.clone(), "features": features.copy(),
                         "query_prefix": oracle.calls, "state_sha256": state.signature()})
        action = int(forced) if forced is not None else policy_action(policy, features)
        forced = None
        action_counts[action] += 1
        previous_calls = oracle.calls
        try:
            execute_action(state, oracle, action)
        except BudgetExhausted:
            break
        if oracle.calls == previous_calls:
            break
    result = oracle.result()
    if result["calls"] == 0:
        result["best_curve"] = np.asarray([state.best_value / state.initial_value])
        result["current_curve"] = np.asarray([state.value / state.initial_value])
    result.update({"action_counts": action_counts.tolist(), "pool": pool,
                   "cpu_seconds": time.process_time() - started_cpu,
                   "wall_seconds": time.perf_counter() - started_wall})
    return result


def padded_curve(result, budget):
    values = result["best_curve"]
    return np.pad(values, (0, max(0, budget - len(values))), mode="edge")[:budget]


def solve_classical(task, config, budget):
    started_cpu, started_wall = time.process_time(), time.perf_counter()
    oracle = Oracle(task, budget)
    kind = config["kind"]
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            if kind == "bfgs":
                minimize(oracle.query, np.zeros(task.dimension), jac=True, method="BFGS",
                    options={"gtol": 1e-12, "maxiter": budget * 4, "c1": config["c1"], "c2": config["c2"],
                             "hess_inv0": np.eye(task.dimension) * config["initial_scale"]})
            elif kind == "lbfgs":
                scale = config["objective_scale"]
                def scaled_query(x):
                    value, gradient = oracle.query(x)
                    return scale * value, scale * gradient
                minimize(scaled_query, np.zeros(task.dimension), jac=True, method="L-BFGS-B",
                    options={"gtol": 1e-12, "ftol": 1e-15, "maxiter": budget * 4,
                             "maxcor": config["memory"], "maxls": config["maxls"]})
            elif kind == "trust_sr1":
                minimize(oracle.query, np.zeros(task.dimension), jac=True, method="trust-constr", hess=SR1(),
                    options={"gtol": 1e-12, "xtol": 1e-14, "maxiter": budget * 4,
                             "initial_tr_radius": config["radius"]})
            elif kind == "spg":
                x = np.zeros(task.dimension); value, gradient = oracle.query(x)
                alpha = config["initial_scale"]; history = [value]
                while oracle.calls < budget and np.linalg.norm(gradient) > 1e-12:
                    direction = -alpha * gradient
                    step = 1.
                    reference = max(history[-config["window"]:])
                    while True:
                        candidate = x + step * direction
                        new_value, new_gradient = oracle.query(candidate)
                        if new_value <= reference + config["c1"] * step * float(gradient @ direction): break
                        step *= 0.5
                        if step < 1e-14: break
                    s, y = candidate - x, new_gradient - gradient
                    sy = float(s @ y)
                    if sy > 1e-20:
                        alpha = float(s @ s) / sy if config["bb_variant"] == 1 else sy / max(float(y @ y), 1e-300)
                        alpha = float(np.clip(alpha, 1e-8, 100.))
                    x, value, gradient = candidate, new_value, new_gradient
                    history.append(value)
            else:
                raise ValueError(kind)
    except BudgetExhausted:
        pass
    result = oracle.result()
    result.update({"cpu_seconds": time.process_time() - started_cpu,
                   "wall_seconds": time.perf_counter() - started_wall})
    return result


def default_classical(method):
    if method == "tuned_bfgs": return {"kind": "bfgs", "initial_scale": 1., "c1": 1e-4, "c2": .9}
    if method == "tuned_lbfgs": return {"kind": "lbfgs", "objective_scale": 1., "memory": 10, "maxls": 20}
    if method == "tuned_spg": return {"kind": "spg", "initial_scale": 1., "window": 10, "c1": 1e-4, "bb_variant": 1}
    if method == "tuned_trust_sr1": return {"kind": "trust_sr1", "radius": 1.}
    raise ValueError(method)


def random_classical(method, rng):
    if method == "tuned_bfgs":
        return {"kind": "bfgs", "initial_scale": float(10 ** rng.uniform(-2, 2)),
                "c1": float(10 ** rng.uniform(-5, -2)), "c2": float(rng.uniform(.2, .95))}
    if method == "tuned_lbfgs":
        return {"kind": "lbfgs", "objective_scale": float(10 ** rng.uniform(-2, 2)),
                "memory": int(rng.choice([3, 5, 10, 20, 40])), "maxls": int(rng.choice([10, 20, 40]))}
    if method == "tuned_spg":
        return {"kind": "spg", "initial_scale": float(10 ** rng.uniform(-2, 1)),
                "window": int(rng.choice([1, 5, 10, 20])), "c1": float(10 ** rng.uniform(-5, -2)),
                "bb_variant": int(rng.choice([1, 2]))}
    if method == "tuned_trust_sr1": return {"kind": "trust_sr1", "radius": float(10 ** rng.uniform(-2, 2))}
    raise ValueError(method)


def run_solver(task, program, budget, collect=False):
    if program["kind"] in ("constant", "tree_ensemble"):
        return solve_policy(task, program, budget, collect=collect)
    return solve_classical(task, program, budget)


def assess(program, tasks, budget=64, collect=False):
    records, curves, pool = [], [], []
    calls = nonfinite = 0; cpu = wall = 0.
    prefixes = np.asarray([budget // 8, budget // 4, budget // 2, budget]) - 1
    for task in tasks:
        result = run_solver(task, program, budget, collect=collect)
        curve = padded_curve(result, budget)
        score = float(np.dot([.1, .15, .25, .5], np.log10(np.maximum(curve[prefixes], 1e-12))))
        records.append({"family": task.family, "task_seed": task.seed, "dimension": task.dimension,
                        "score": score, "calls": result["calls"], "final_relative_objective": float(curve[-1]),
                        "nonfinite": result["nonfinite"]})
        curves.append(curve); pool.extend(result.get("pool", []))
        calls += result["calls"]; nonfinite += result["nonfinite"]
        cpu += result["cpu_seconds"]; wall += result["wall_seconds"]
    scores = np.asarray([r["score"] for r in records])
    return {"fitness": float(.8 * np.mean(scores) + .2 * np.quantile(scores, .9)),
            "calls": calls, "records": records, "trace_sha256": array_digest(np.asarray(curves)),
            "cpu_seconds": cpu, "wall_seconds": wall, "nonfinite": nonfinite, "pool": pool}


def without_pool(assessment):
    return {key: value for key, value in assessment.items() if key != "pool"}


def export_policy_python(policy, path):
    """Export actual branch functions; no runtime dependency on sklearn or our interpreter."""
    lines = ["# Generated from a frozen executable controller; do not edit.", "import numpy as np", ""]
    if policy["kind"] == "constant":
        lines += ["def choose_action(features):", f"    return {int(policy['action'])}"]
    else:
        for index, tree in enumerate(policy["trees"]):
            lines += [f"def tree_{index}(features):", "    features = np.asarray(features, dtype=np.float32)"]
            def emit(node, indent):
                prefix = "    " * indent
                if tree["left"][node] == -1:
                    lines.append(prefix + "return np.asarray(" + repr(tree["value"][node]) + ", dtype=float)")
                else:
                    lines.append(prefix + f"if features[{tree['feature'][node]}] <= {tree['threshold'][node]!r}:")
                    emit(tree["left"][node], indent + 1)
                    lines.append(prefix + "else:")
                    emit(tree["right"][node], indent + 1)
            emit(0, 1); lines.append("")
        lines += ["def choose_action(features):", "    values = np.asarray([" + ", ".join(f"tree_{i}(features)" for i in range(len(policy['trees']))) + "])",
                  "    mean = values.mean(axis=0)", "    best = int(np.argmin(mean))",
                  "    uncertainty = float(np.std(values[:, 0] - values[:, best]))",
                  f"    if mean[0] - mean[best] <= {policy['switch_margin']!r} + {policy['uncertainty_multiplier']!r} * uncertainty:",
                  "        return 0", "    return best"]
    Path(path).write_text("\n".join(lines) + "\n")


def export_selector_python(selector, path):
    """Export the learned labeling-priority tree as actual Python branches."""
    if selector is None or selector.get("kind") != "regret_tree":
        return
    tree = selector["tree"]
    lines = ["# Generated learned decision-regret selector; fixed training scaffold.",
             "import numpy as np", "", "def score_acquisition(features):",
             "    features = np.asarray(features, dtype=np.float32)"]
    def emit(node, indent):
        prefix = "    " * indent
        if tree["left"][node] == -1:
            lines.append(prefix + f"return max({float(tree['value'][node][0])!r}, 0.0)")
        else:
            lines.append(prefix + f"if features[{tree['feature'][node]}] <= {tree['threshold'][node]!r}:")
            emit(tree["left"][node], indent + 1)
            lines.append(prefix + "else:")
            emit(tree["right"][node], indent + 1)
    emit(0, 1)
    Path(path).write_text("\n".join(lines) + "\n")