Repository navigation
Expand file tree
/
Copy pathosmac_optimizer.py
More file actions
1439 lines (1222 loc) · 54.1 KB
/
Copy pathosmac_optimizer.py
File metadata and controls
1439 lines (1222 loc) · 54.1 KB
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
"""
osmac_optimizer.py
==================
Streaming fairness-constrained OSMAC-style optimizer for DFE-AutoML.
Purpose
-------
Implements a practical streaming constrained Bayesian optimization layer for
DFE-AutoML.
This optimizer:
- keeps separate local surrogates for objective and fairness constraint behavior
- updates these surrogates each window / period
- ranks candidate configurations with constrained acquisition
- returns the next candidate set and current incumbent
Designed to align with:
- config_space.py
- candidate_evaluator.py
- dynamic fairness envelope / DFE logic
- streaming search requirements inspired by OSMAC
- constrained BO logic inspired by FairBO / CBO
Core design
-----------
For each candidate x, we model:
1) Objective surrogate
f_t(x): predictive utility on current / recent windows
2) Constraint surrogate
c_t(x): unfairness proxy and/or feasibility probability
Then rank candidates with one of these modes:
A) feasibility_first
Used when we do not yet have a feasible recent incumbent.
Select x maximizing P(feasible)
B) cei_static
Constrained expected improvement with fixed fairness threshold:
cEI(x) = EI(x) * P(c(x) <= epsilon)
C) cei_envelope
Constrained expected improvement with dynamic fairness envelope:
cEI_t(x) = EI_t(x) * P(c_t(x) in E(t))
In practice, candidate_evaluator.py already returns:
- predictive metrics
- fairness metrics
- sfm payload
- feasibility probability
- fairness risk
- constrained utility proxy
This optimizer consumes those outputs and proposes next configurations.
Notes
-----
- This module does not directly evaluate candidates.
- It consumes outputs from candidate_evaluator.py via register_observation().
- Surrogates are lightweight distance-weighted local regressors over encoded configs.
- This keeps the implementation deterministic, stable, and dependency-light.
"""
import copy
import math
import random
from dataclasses import dataclass, field
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
import numpy as np
from config_space import PipelineConfig, StreamingConfigSpace
from candidate_evaluator import CandidateEvaluationResult
# ============================================================
# Helpers
# ============================================================
def _safe_float(x: Any, default: float = 0.0) -> float:
try:
v = float(x)
if not math.isfinite(v):
return float(default)
return float(v)
except Exception:
return float(default)
def _safe_int(x: Any, default: int = 0) -> int:
try:
if isinstance(x, bool):
return int(x)
return int(float(x))
except Exception:
return int(default)
def _clip(x: float, lo: float, hi: float) -> float:
return max(float(lo), min(float(hi), float(x)))
def _clip01(x: Any) -> float:
return _clip(_safe_float(x, 0.0), 0.0, 1.0)
def _normal_pdf(z: float) -> float:
return math.exp(-0.5 * z * z) / math.sqrt(2.0 * math.pi)
def _normal_cdf(z: float) -> float:
return 0.5 * (1.0 + math.erf(z / math.sqrt(2.0)))
def _euclidean_distance(a: np.ndarray, b: np.ndarray) -> float:
return float(np.linalg.norm(a - b))
def _stable_sigmoid(x: float) -> float:
x = float(_clip(x, -60.0, 60.0))
return 1.0 / (1.0 + math.exp(-x))
# ============================================================
# Dataclasses
# ============================================================
@dataclass(frozen=True)
class OSMACOptimizerConfig:
seed: int = 42
streaming_method: str = "online_fairbo_ensemble"
# Candidate generation
pool_size: int = 64
n_propose: int = 8
initial_design_size: int = 12
random_fraction: float = 0.20
mutation_fraction: float = 0.55
crossover_fraction: float = 0.25
# Local surrogates
neighborhood_size: int = 15
min_points_for_surrogate: int = 6
uncertainty_floor: float = 1e-6
distance_temperature: float = 2.0
# Acquisition setup
acquisition_mode: str = "auto" # auto | feasibility_first | cei_static | cei_envelope
use_expected_improvement: bool = True
objective_mode: str = "maximize_accuracy" # maximize_accuracy | maximize_constrained_utility | minimize_log_loss
incumbent_metric: str = "constrained_utility"
# Constraint interpretation
static_fairness_threshold: float = 0.05
hard_feasibility_floor: float = 0.05
use_recent_feasibility_horizon: bool = True
feasible_horizon_windows: int = 5
# Acquisition weights
utility_weight: float = 1.0
feasibility_weight: float = 1.5
risk_penalty_weight: float = 0.85
novelty_weight: float = 0.10
incumbent_bias: float = 0.05
reliability_penalty_weight: float = 0.20
low_support_penalty_weight: float = 0.15
# Streaming adaptation
recency_decay: float = 0.98
drift_reactivity: float = 0.50
fairness_pressure_scale: float = 1.00
max_history: int = 2000
# Diversity
enforce_unique_configs: bool = True
diversity_min_distance: float = 0.05
# Envelope preference / policy
envelope_violation_penalty: float = 1.00
recent_feasible_bonus: float = 0.25
feasible_priority_bonus: float = 2.0
infeasible_priority_penalty: float = 1.0
no_feasible_fallback_to_feasibility_first: bool = True
version: str = "osmac_optimizer.v2"
@dataclass
class ObservationRecord:
config: Dict[str, Any]
config_id: str
x: List[float]
# Objective and acquisition-facing pieces
utility_score: float
cost_score: float
fairness_score: float
feasibility_probability: float
fairness_risk: float
constrained_utility: float
# Explicit CBO fields
objective_value: float = 0.0
constraint_value: float = 0.0
constraint_feasible: bool = False
feasibility_mode: str = "unknown" # static_threshold | envelope | unknown
# Predictive / fairness details
accuracy: float = 0.0
log_loss: float = 0.0
fm_smooth: float = 0.0
fm_raw: float = 0.0
fm_drift: float = 0.0
fm_uncertainty: float = 1.0
envelope_lower: float = 0.0
envelope_upper: float = 0.1
envelope_violation: bool = False
envelope_severity: float = 0.0
is_reliable: bool = False
insufficient_support: bool = True
effective_support: int = 0
timestep: int = 0
window_index: int = 0
recency_weight: float = 1.0
raw_result: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
return {
"config": copy.deepcopy(self.config),
"config_id": str(self.config_id),
"x": list(self.x),
"utility_score": float(self.utility_score),
"cost_score": float(self.cost_score),
"fairness_score": float(self.fairness_score),
"feasibility_probability": float(self.feasibility_probability),
"fairness_risk": float(self.fairness_risk),
"constrained_utility": float(self.constrained_utility),
"objective_value": float(self.objective_value),
"constraint_value": float(self.constraint_value),
"constraint_feasible": bool(self.constraint_feasible),
"feasibility_mode": str(self.feasibility_mode),
"accuracy": float(self.accuracy),
"log_loss": float(self.log_loss),
"fm_smooth": float(self.fm_smooth),
"fm_raw": float(self.fm_raw),
"fm_drift": float(self.fm_drift),
"fm_uncertainty": float(self.fm_uncertainty),
"envelope_lower": float(self.envelope_lower),
"envelope_upper": float(self.envelope_upper),
"envelope_violation": bool(self.envelope_violation),
"envelope_severity": float(self.envelope_severity),
"is_reliable": bool(self.is_reliable),
"insufficient_support": bool(self.insufficient_support),
"effective_support": int(self.effective_support),
"timestep": int(self.timestep),
"window_index": int(self.window_index),
"recency_weight": float(self.recency_weight),
"raw_result": copy.deepcopy(self.raw_result),
}
@dataclass
class AcquisitionRecord:
config: Dict[str, Any]
config_id: str
x: List[float]
# Objective surrogate
pred_objective_mean: float = 0.0
pred_objective_std: float = 0.0
# Constraint surrogate
pred_constraint_mean: float = 0.0
pred_constraint_std: float = 0.0
pred_feasibility_mean: float = 0.0
pred_feasibility_std: float = 0.0
# Auxiliary surrogates
pred_risk_mean: float = 0.0
pred_risk_std: float = 0.0
pred_fairness_mean: float = 0.0
pred_fairness_std: float = 0.0
# Acquisition
acquisition_mode: str = "unknown"
best_reference: float = 0.0
improvement_mean: float = 0.0
ei_like: float = 0.0
p_feasible: float = 0.0
novelty: float = 0.0
constrained_acquisition: float = 0.0
reliability_penalty: float = 0.0
low_support_penalty: float = 0.0
final_score: float = 0.0
rationale: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
return {
"config": copy.deepcopy(self.config),
"config_id": str(self.config_id),
"x": list(self.x),
"pred_objective_mean": float(self.pred_objective_mean),
"pred_objective_std": float(self.pred_objective_std),
"pred_constraint_mean": float(self.pred_constraint_mean),
"pred_constraint_std": float(self.pred_constraint_std),
"pred_feasibility_mean": float(self.pred_feasibility_mean),
"pred_feasibility_std": float(self.pred_feasibility_std),
"pred_risk_mean": float(self.pred_risk_mean),
"pred_risk_std": float(self.pred_risk_std),
"pred_fairness_mean": float(self.pred_fairness_mean),
"pred_fairness_std": float(self.pred_fairness_std),
"acquisition_mode": str(self.acquisition_mode),
"best_reference": float(self.best_reference),
"improvement_mean": float(self.improvement_mean),
"ei_like": float(self.ei_like),
"p_feasible": float(self.p_feasible),
"novelty": float(self.novelty),
"constrained_acquisition": float(self.constrained_acquisition),
"reliability_penalty": float(self.reliability_penalty),
"low_support_penalty": float(self.low_support_penalty),
"final_score": float(self.final_score),
"rationale": copy.deepcopy(self.rationale),
}
@dataclass
class ProposalBatch:
proposed_configs: List[Dict[str, Any]]
acquisition_records: List[Dict[str, Any]]
incumbent: Optional[Dict[str, Any]]
optimizer_state: Dict[str, Any]
def to_dict(self) -> Dict[str, Any]:
return {
"proposed_configs": copy.deepcopy(self.proposed_configs),
"acquisition_records": copy.deepcopy(self.acquisition_records),
"incumbent": copy.deepcopy(self.incumbent),
"optimizer_state": copy.deepcopy(self.optimizer_state),
}
# ============================================================
# OSMAC optimizer
# ============================================================
class OSMACOptimizer:
"""
Streaming fairness-constrained optimizer for DFE-AutoML.
Workflow
--------
1. Create optimizer with a shared StreamingConfigSpace
2. Ask for candidates with propose_next()
3. Evaluate them externally with candidate_evaluator.py
4. Feed results back via register_observation()
5. Repeat each window
"""
def __init__(
self,
config_space: StreamingConfigSpace,
config: Optional[OSMACOptimizerConfig] = None,
) -> None:
self.config_space = config_space
self.cfg = config or OSMACOptimizerConfig()
self.rng = random.Random(int(self.cfg.seed))
self.window_index: int = 0
self.observations: List[ObservationRecord] = []
self.observation_by_id: Dict[str, List[ObservationRecord]] = {}
self.incumbent: Optional[ObservationRecord] = None
self.last_optimizer_state: Dict[str, Any] = {}
self._vector_schema = self.config_space.get_vector_schema()
# --------------------------------------------------------
# Public API
# --------------------------------------------------------
def reset(self) -> None:
self.window_index = 0
self.observations.clear()
self.observation_by_id.clear()
self.incumbent = None
self.last_optimizer_state = {}
def step_window(self) -> None:
self.window_index += 1
self._refresh_recency_weights()
def register_observation(
self,
evaluation_result: Union[CandidateEvaluationResult, Mapping[str, Any]],
*,
timestep: Optional[int] = None,
window_index: Optional[int] = None,
) -> Dict[str, Any]:
"""
Register one evaluated candidate.
"""
payload = evaluation_result.to_dict() if isinstance(evaluation_result, CandidateEvaluationResult) else dict(evaluation_result or {})
config = dict(payload.get("config", {}) or {})
config_id = str(payload.get("config_id", "")) or PipelineConfig.from_dict(config).stable_id()
x = [float(v) for v in payload.get("config_vector", [])]
predictive = dict(payload.get("predictive_metrics", {}) or {})
fairness = dict(payload.get("fairness_metrics", {}) or {})
feasibility = dict(payload.get("feasibility", {}) or {})
score_payload = dict(payload.get("score_payload", {}) or {})
sfm_payload = dict(payload.get("sfm_payload", {}) or {})
envelope = dict(payload.get("envelope", {}) or {})
raw_artifacts = dict(payload.get("raw_artifacts", {}) or {})
fm_smooth = _safe_float(fairness.get("fm_smooth", sfm_payload.get("fm_smooth", fairness.get("primary_metric", 0.0))), 0.0)
fm_raw = _safe_float(fairness.get("fm_raw", sfm_payload.get("fm_raw", fm_smooth)), fm_smooth)
feasible_prob = _clip01(score_payload.get("feasibility_probability", feasibility.get("feasibility_probability", 0.0)))
envelope_lower = _safe_float(
envelope.get("lower", envelope.get("envelope_lower", 0.0)),
0.0,
)
envelope_upper = _safe_float(
envelope.get("upper", envelope.get("envelope_upper", self.cfg.static_fairness_threshold)),
self.cfg.static_fairness_threshold,
)
envelope_violation = bool(fairness.get("envelope_violation", envelope.get("envelope_violation", False)))
constraint_feasible = bool(feasibility.get("feasible_hard", not envelope_violation))
feasibility_mode = "envelope" if ("upper" in envelope or "envelope_upper" in envelope) else "static_threshold"
rec = ObservationRecord(
config=copy.deepcopy(config),
config_id=config_id,
x=list(x),
utility_score=_safe_float(score_payload.get("utility_score", predictive.get("accuracy", 0.0)), 0.0),
cost_score=_safe_float(score_payload.get("cost_score", predictive.get("log_loss", 0.0)), 0.0),
fairness_score=_safe_float(score_payload.get("fairness_score", 1.0 - fm_smooth), 0.0),
feasibility_probability=feasible_prob,
fairness_risk=_clip01(score_payload.get("fairness_risk", feasibility.get("fairness_risk", 1.0))),
constrained_utility=_safe_float(score_payload.get("constrained_utility", 0.0), 0.0),
objective_value=self._extract_objective_from_payload(
predictive=predictive,
score_payload=score_payload,
),
constraint_value=fm_smooth,
constraint_feasible=constraint_feasible,
feasibility_mode=feasibility_mode,
accuracy=_safe_float(predictive.get("accuracy", 0.0), 0.0),
log_loss=_safe_float(predictive.get("log_loss", 0.0), 0.0),
fm_smooth=fm_smooth,
fm_raw=fm_raw,
fm_drift=_safe_float(fairness.get("fm_drift", sfm_payload.get("fm_drift", 0.0)), 0.0),
fm_uncertainty=_clip01(fairness.get("fm_uncertainty", sfm_payload.get("fm_uncertainty", 1.0))),
envelope_lower=envelope_lower,
envelope_upper=envelope_upper,
envelope_violation=envelope_violation,
envelope_severity=_safe_float(
fairness.get("envelope_severity", envelope.get("envelope_severity", envelope.get("severity", 0.0))),
0.0,
),
is_reliable=bool(fairness.get("is_reliable", sfm_payload.get("is_reliable", False))),
insufficient_support=bool(fairness.get("insufficient_support", sfm_payload.get("insufficient_support", True))),
effective_support=_safe_int(fairness.get("effective_support", sfm_payload.get("effective_support", 0)), 0),
timestep=int(self.window_index if timestep is None else timestep),
window_index=int(self.window_index if window_index is None else window_index),
raw_result=copy.deepcopy(payload),
)
# Optional standardized payload from candidate_evaluator, if present.
objective_block = dict(raw_artifacts.get("optimizer_targets", {}) or {})
if objective_block:
rec.objective_value = _safe_float(objective_block.get("objective_value", rec.objective_value), rec.objective_value)
rec.constraint_value = _safe_float(objective_block.get("constraint_value", rec.constraint_value), rec.constraint_value)
rec.constraint_feasible = bool(objective_block.get("constraint_feasible", rec.constraint_feasible))
rec.feasibility_mode = str(objective_block.get("constraint_probability_target", rec.feasibility_mode))
self.observations.append(rec)
self.observation_by_id.setdefault(rec.config_id, []).append(rec)
if len(self.observations) > int(self.cfg.max_history):
excess = len(self.observations) - int(self.cfg.max_history)
self.observations = self.observations[excess:]
self._rebuild_observation_index()
self._refresh_recency_weights()
self._update_incumbent()
return {
"n_observations": int(len(self.observations)),
"incumbent": self.get_incumbent_summary(),
"has_recent_feasible": bool(self._has_recent_feasible()),
}
def register_batch(
self,
evaluation_results: Sequence[Union[CandidateEvaluationResult, Mapping[str, Any]]],
*,
timestep: Optional[int] = None,
window_index: Optional[int] = None,
) -> Dict[str, Any]:
for res in evaluation_results:
self.register_observation(res, timestep=timestep, window_index=window_index)
return {
"n_observations": int(len(self.observations)),
"incumbent": self.get_incumbent_summary(),
"has_recent_feasible": bool(self._has_recent_feasible()),
}
def propose_next(
self,
*,
n_propose: Optional[int] = None,
include_incumbent: bool = True,
fairness_context: Optional[Mapping[str, Any]] = None,
force_exploration: bool = False,
) -> ProposalBatch:
"""
Propose the next candidate set.
"""
n_propose_eff = max(1, int(n_propose if n_propose is not None else self.cfg.n_propose))
fairness_context = dict(fairness_context or {})
if len(self.observations) < int(self.cfg.initial_design_size):
proposals = self._initial_design(n=n_propose_eff, include_incumbent=include_incumbent)
self.last_optimizer_state = {
"mode": "initial_design",
"window_index": int(self.window_index),
"n_observations": int(len(self.observations)),
"has_recent_feasible": bool(self._has_recent_feasible()),
"version": str(self.cfg.version),
}
return ProposalBatch(
proposed_configs=[p["config"] for p in proposals],
acquisition_records=proposals,
incumbent=self.get_incumbent_summary(),
optimizer_state=copy.deepcopy(self.last_optimizer_state),
)
candidate_pool = self._generate_candidate_pool(
pool_size=max(n_propose_eff, int(self.cfg.pool_size)),
fairness_context=fairness_context,
force_exploration=force_exploration,
)
ranked = self.rank_candidates(
candidate_pool=candidate_pool,
fairness_context=fairness_context,
)
selected = self._select_diverse_topk(
ranked=ranked,
k=n_propose_eff,
include_incumbent=include_incumbent,
)
acquisition_mode = self._resolve_acquisition_mode(fairness_context=fairness_context)
optimizer_state = self._build_optimizer_state(
fairness_context=fairness_context,
candidate_pool_size=len(candidate_pool),
mode=acquisition_mode,
)
self.last_optimizer_state = optimizer_state
return ProposalBatch(
proposed_configs=[r["config"] for r in selected],
acquisition_records=selected,
incumbent=self.get_incumbent_summary(),
optimizer_state=optimizer_state,
)
def rank_candidates(
self,
*,
candidate_pool: Sequence[Union[PipelineConfig, Mapping[str, Any]]],
fairness_context: Optional[Mapping[str, Any]] = None,
) -> List[Dict[str, Any]]:
fairness_context = dict(fairness_context or {})
acquisition_mode = self._resolve_acquisition_mode(fairness_context=fairness_context)
records: List[AcquisitionRecord] = []
best_reference = self._get_best_reference()
for cand in candidate_pool:
cfg = self.config_space.validate_config(cand)
x = np.asarray(self.config_space.encode_config(cfg, as_numpy=True), dtype=float)
obj_mean, obj_std = self._predict_target(x=x, target="objective")
cons_mean, cons_std = self._predict_target(x=x, target="constraint")
feas_mean, feas_std = self._predict_target(x=x, target="feasibility")
risk_mean, risk_std = self._predict_target(x=x, target="risk")
fair_mean, fair_std = self._predict_target(x=x, target="fairness")
feas_mean = max(float(feas_mean), float(self.cfg.hard_feasibility_floor))
risk_mean = _clip01(risk_mean)
fair_mean = max(0.0, float(fair_mean))
fairness_pressure = self._compute_fairness_pressure(fairness_context)
envelope_upper = _safe_float(
fairness_context.get("envelope_upper", fairness_context.get("upper", self.cfg.static_fairness_threshold)),
self.cfg.static_fairness_threshold,
)
static_eps = _safe_float(
fairness_context.get("static_fairness_threshold", self.cfg.static_fairness_threshold),
self.cfg.static_fairness_threshold,
)
# Derive p_feasible according to mode
if acquisition_mode == "cei_static":
p_feasible = self._probability_feasible_static(
constraint_mean=cons_mean,
constraint_std=cons_std,
epsilon=static_eps,
)
elif acquisition_mode == "cei_envelope":
lower = _safe_float(fairness_context.get("envelope_lower", fairness_context.get("lower", 0.0)), 0.0)
upper = _safe_float(fairness_context.get("envelope_upper", fairness_context.get("upper", envelope_upper)), envelope_upper)
p_feasible = self._probability_feasible_envelope(
constraint_mean=cons_mean,
constraint_std=cons_std,
lower=lower,
upper=upper,
)
else:
p_feasible = feas_mean
p_feasible = float(max(self.cfg.hard_feasibility_floor, _clip01(p_feasible)))
improvement_mean = float(obj_mean - best_reference)
ei_like = self._compute_ei_like(
mean=float(obj_mean),
std=float(obj_std),
best=float(best_reference),
)
novelty = self._compute_novelty(x)
reliability_penalty = float(
self.cfg.reliability_penalty_weight *
max(0.0, fair_mean - p_feasible)
)
low_support_penalty = float(
self.cfg.low_support_penalty_weight *
max(0.0, fairness_pressure * risk_mean)
)
if acquisition_mode == "feasibility_first":
constrained_acquisition = float(
p_feasible
+ 0.10 * novelty
- 0.25 * risk_mean
)
else:
constrained_acquisition = float(
self.cfg.utility_weight * ei_like *
(p_feasible ** self.cfg.feasibility_weight)
)
final_score = float(
constrained_acquisition
- self.cfg.risk_penalty_weight * (1.0 + fairness_pressure) * risk_mean
- reliability_penalty
- low_support_penalty
+ self.cfg.novelty_weight * novelty
)
if self.incumbent is not None and cfg.stable_id() == self.incumbent.config_id:
final_score += float(self.cfg.incumbent_bias)
rec = AcquisitionRecord(
config=cfg.to_dict(),
config_id=cfg.stable_id(),
x=[float(v) for v in x.tolist()],
pred_objective_mean=float(obj_mean),
pred_objective_std=float(obj_std),
pred_constraint_mean=float(cons_mean),
pred_constraint_std=float(cons_std),
pred_feasibility_mean=float(feas_mean),
pred_feasibility_std=float(feas_std),
pred_risk_mean=float(risk_mean),
pred_risk_std=float(risk_std),
pred_fairness_mean=float(fair_mean),
pred_fairness_std=float(fair_std),
acquisition_mode=acquisition_mode,
best_reference=float(best_reference),
improvement_mean=float(improvement_mean),
ei_like=float(ei_like),
p_feasible=float(p_feasible),
novelty=float(novelty),
constrained_acquisition=float(constrained_acquisition),
reliability_penalty=float(reliability_penalty),
low_support_penalty=float(low_support_penalty),
final_score=float(final_score),
rationale={
"fairness_pressure": float(fairness_pressure),
"objective_mode": str(self.cfg.objective_mode),
"incumbent_metric": str(self.cfg.incumbent_metric),
"static_fairness_threshold": float(static_eps),
"envelope_upper": float(envelope_upper),
"has_recent_feasible": bool(self._has_recent_feasible()),
},
)
records.append(rec)
records.sort(key=lambda r: r.final_score, reverse=True)
return [r.to_dict() for r in records]
def get_incumbent_summary(self) -> Optional[Dict[str, Any]]:
if self.incumbent is None:
return None
return self.incumbent.to_dict()
def get_history(self) -> List[Dict[str, Any]]:
return [obs.to_dict() for obs in self.observations]
def get_recent_history(self, horizon_windows: Optional[int] = None) -> List[Dict[str, Any]]:
records = self._get_recent_observations(horizon_windows=horizon_windows)
return [obs.to_dict() for obs in records]
def get_state(self) -> Dict[str, Any]:
return {
"window_index": int(self.window_index),
"n_observations": int(len(self.observations)),
"has_recent_feasible": bool(self._has_recent_feasible()),
"incumbent": self.get_incumbent_summary(),
"last_optimizer_state": copy.deepcopy(self.last_optimizer_state),
"config": {
"seed": int(self.cfg.seed),
"pool_size": int(self.cfg.pool_size),
"n_propose": int(self.cfg.n_propose),
"initial_design_size": int(self.cfg.initial_design_size),
"objective_mode": str(self.cfg.objective_mode),
"incumbent_metric": str(self.cfg.incumbent_metric),
"acquisition_mode": str(self.cfg.acquisition_mode),
"static_fairness_threshold": float(self.cfg.static_fairness_threshold),
"version": str(self.cfg.version),
},
}
# --------------------------------------------------------
# Payload parsing helpers
# --------------------------------------------------------
def _extract_objective_from_payload(
self,
*,
predictive: Mapping[str, Any],
score_payload: Mapping[str, Any],
) -> float:
mode = str(self.cfg.objective_mode).strip().lower()
if mode == "maximize_accuracy":
return _safe_float(predictive.get("accuracy", score_payload.get("utility_score", 0.0)), 0.0)
if mode == "maximize_constrained_utility":
return _safe_float(score_payload.get("constrained_utility", 0.0), 0.0)
if mode == "minimize_log_loss":
return -_safe_float(predictive.get("log_loss", score_payload.get("cost_score", 0.0)), 0.0)
return _safe_float(score_payload.get("constrained_utility", predictive.get("accuracy", 0.0)), 0.0)
# --------------------------------------------------------
# Surrogate core
# --------------------------------------------------------
def _predict_target(self, x: np.ndarray, target: str) -> Tuple[float, float]:
"""
Distance-weighted neighborhood regression.
target:
objective -> predictive objective target
constraint -> unfairness constraint value
feasibility -> feasibility probability
risk -> fairness risk
fairness -> fm_smooth-like fairness burden proxy
"""
if len(self.observations) < max(2, int(self.cfg.min_points_for_surrogate)):
return self._cold_start_prediction(target=target)
neighbors = self._get_neighbors(x=x, k=int(self.cfg.neighborhood_size))
if not neighbors:
return self._cold_start_prediction(target=target)
vals: List[float] = []
weights: List[float] = []
for dist, obs in neighbors:
val = self._extract_target(obs=obs, target=target)
rec_w = float(obs.recency_weight)
sim_w = math.exp(-float(self.cfg.distance_temperature) * dist)
w = max(self.cfg.uncertainty_floor, rec_w * sim_w)
vals.append(float(val))
weights.append(float(w))
if not vals:
return self._cold_start_prediction(target=target)
arr_vals = np.asarray(vals, dtype=float)
arr_w = np.asarray(weights, dtype=float)
arr_w = np.maximum(arr_w, self.cfg.uncertainty_floor)
arr_w = arr_w / np.maximum(arr_w.sum(), self.cfg.uncertainty_floor)
mean = float(np.sum(arr_w * arr_vals))
var = float(np.sum(arr_w * ((arr_vals - mean) ** 2)))
std = float(max(math.sqrt(max(var, 0.0)), self.cfg.uncertainty_floor))
if target in {"feasibility", "risk"}:
mean = _clip01(mean)
if target == "constraint":
mean = max(0.0, mean)
return mean, std
def _cold_start_prediction(self, target: str) -> Tuple[float, float]:
if target == "objective":
if self.cfg.objective_mode == "maximize_accuracy":
return 0.50, 0.25
if self.cfg.objective_mode == "maximize_constrained_utility":
return 0.25, 0.25
if self.cfg.objective_mode == "minimize_log_loss":
return -0.69, 0.25
if target == "constraint":
return self.cfg.static_fairness_threshold, 0.10
if target == "feasibility":
return 0.50, 0.25
if target == "risk":
return 0.50, 0.25
if target == "fairness":
return self.cfg.static_fairness_threshold, 0.10
return 0.0, 1.0
def _extract_target(self, obs: ObservationRecord, target: str) -> float:
if target == "objective":
return float(self._observation_objective(obs))
if target == "constraint":
return float(obs.constraint_value)
if target == "feasibility":
return float(obs.feasibility_probability)
if target == "risk":
return float(obs.fairness_risk)
if target == "fairness":
return float(obs.fm_smooth)
return 0.0
def _observation_objective(self, obs: ObservationRecord) -> float:
mode = str(self.cfg.objective_mode).strip().lower()
if mode == "maximize_accuracy":
return float(obs.accuracy)
if mode == "maximize_constrained_utility":
return float(obs.constrained_utility)
if mode == "minimize_log_loss":
return float(-obs.log_loss)
return float(obs.constrained_utility)
def _get_best_reference(self) -> float:
obs_list = self._get_reference_observations_for_best()
if not obs_list:
return 0.0
metric = str(self.cfg.incumbent_metric).strip().lower()
vals: List[float] = []
for obs in obs_list:
if metric == "accuracy":
vals.append(float(obs.accuracy))
elif metric == "constrained_utility":
vals.append(float(obs.constrained_utility))
elif metric == "utility":
vals.append(float(obs.utility_score))
elif metric == "negative_log_loss":
vals.append(float(-obs.log_loss))
else:
vals.append(float(obs.constrained_utility))
return max(vals) if vals else 0.0
def _get_reference_observations_for_best(self) -> List[ObservationRecord]:
if not self.observations:
return []
if self._has_recent_feasible():
recent = self._get_recent_observations()
feasible_recent = [obs for obs in recent if obs.constraint_feasible]
if feasible_recent:
return feasible_recent
return list(self.observations)
def _compute_ei_like(self, mean: float, std: float, best: float) -> float:
if not self.cfg.use_expected_improvement:
return max(0.0, mean - best)
sigma = max(float(std), self.cfg.uncertainty_floor)
delta = float(mean - best)
z = delta / sigma
ei = delta * _normal_cdf(z) + sigma * _normal_pdf(z)
return float(max(ei, 0.0))
def _get_neighbors(self, x: np.ndarray, k: int) -> List[Tuple[float, ObservationRecord]]:
scored: List[Tuple[float, ObservationRecord]] = []
denom = max(1.0, math.sqrt(len(x)))
for obs in self.observations:
xo = np.asarray(obs.x, dtype=float)
dist = _euclidean_distance(x, xo) / denom
scored.append((float(dist), obs))
scored.sort(key=lambda t: t[0])
return scored[:max(1, int(k))]
def _compute_novelty(self, x: np.ndarray) -> float:
if not self.observations:
return 1.0
denom = max(1.0, math.sqrt(len(x)))
dists = []
for obs in self.observations:
xo = np.asarray(obs.x, dtype=float)
d = _euclidean_distance(x, xo) / denom
dists.append(float(d))
if not dists:
return 1.0
min_dist = min(dists)
return float(_clip(min_dist / max(self.cfg.diversity_min_distance, 1e-6), 0.0, 1.0))
# --------------------------------------------------------
# Feasibility / acquisition logic
# --------------------------------------------------------
def _probability_feasible_static(
self,
*,
constraint_mean: float,
constraint_std: float,
epsilon: float,
) -> float:
sigma = max(float(constraint_std), self.cfg.uncertainty_floor)
z = (float(epsilon) - float(constraint_mean)) / sigma
return float(_clip01(_normal_cdf(z)))
def _probability_feasible_envelope(
self,
*,
constraint_mean: float,
constraint_std: float,
lower: float,
upper: float,
) -> float:
sigma = max(float(constraint_std), self.cfg.uncertainty_floor)
z_upper = (float(upper) - float(constraint_mean)) / sigma
z_lower = (float(lower) - float(constraint_mean)) / sigma
return float(_clip01(_normal_cdf(z_upper) - _normal_cdf(z_lower)))
def _resolve_acquisition_mode(
self,
*,
fairness_context: Mapping[str, Any],
) -> str:
mode = str(self.cfg.acquisition_mode).strip().lower()
if mode in {"feasibility_first", "cei_static", "cei_envelope"}:
return mode
# auto mode
has_recent_feasible = self._has_recent_feasible()
has_envelope = (
"envelope_upper" in fairness_context or
"upper" in fairness_context or
(self.incumbent is not None and self.incumbent.feasibility_mode == "envelope")
)
if self.cfg.no_feasible_fallback_to_feasibility_first and not has_recent_feasible:
return "feasibility_first"
if has_envelope:
return "cei_envelope"
return "cei_static"
def _has_recent_feasible(self) -> bool:
recent = self._get_recent_observations()
return any(obs.constraint_feasible for obs in recent)
def _get_recent_observations(self, horizon_windows: Optional[int] = None) -> List[ObservationRecord]:
if not self.observations:
return []
if not self.cfg.use_recent_feasibility_horizon:
return list(self.observations)
horizon = int(self.cfg.feasible_horizon_windows if horizon_windows is None else horizon_windows)
current = max(obs.window_index for obs in self.observations)
lo = current - max(0, horizon) + 1
return [obs for obs in self.observations if int(obs.window_index) >= lo]