dagcert 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dagcert/__init__.py +195 -0
- dagcert/_core/__init__.py +1 -0
- dagcert/_core/_interval_utils.py +136 -0
- dagcert/_core/_samegame_engine.py +179 -0
- dagcert/_core/_uct_families.py +79 -0
- dagcert/_core/application_search.py +220 -0
- dagcert/_core/backprop_problems.py +42 -0
- dagcert/_core/batched_witness_cab.py +151 -0
- dagcert/_core/benchmark.py +253 -0
- dagcert/_core/certificate_batch.py +198 -0
- dagcert/_core/certificates.py +275 -0
- dagcert/_core/certified_uct.py +367 -0
- dagcert/_core/compiled_retirement.py +191 -0
- dagcert/_core/completion_accuracy.py +275 -0
- dagcert/_core/demand_benchmark.py +196 -0
- dagcert/_core/demand_bounds.py +511 -0
- dagcert/_core/demand_threshold.py +147 -0
- dagcert/_core/graph.py +145 -0
- dagcert/_core/local_buckets.py +238 -0
- dagcert/_core/maintenance_regimes.py +83 -0
- dagcert/_core/maintenance_replay.py +223 -0
- dagcert/_core/onpolicy_backup.py +131 -0
- dagcert/_core/persistent_queries.py +94 -0
- dagcert/_core/puct.py +393 -0
- dagcert/_core/quotient_range.py +62 -0
- dagcert/_core/retired_bounds.py +214 -0
- dagcert/_core/root_flat_control.py +113 -0
- dagcert/_core/routing.py +143 -0
- dagcert/_core/search.py +307 -0
- dagcert/_core/shared_backprop.py +274 -0
- dagcert/_core/uct_problems.py +37 -0
- dagcert/_core/v12_bed_acquisition.py +1338 -0
- dagcert/_core/v2_benchmarks.py +352 -0
- dagcert/_core/v2_monitors.py +1218 -0
- dagcert/_core/v3_extensions.py +898 -0
- dagcert/_core/v4_baselines.py +915 -0
- dagcert/_core/v5_hybrid_and_os.py +451 -0
- dagcert/_core/v6_bayesian_opt.py +1025 -0
- dagcert/_core/v6_real_world.py +836 -0
- dagcert/_core/v7_bayesian_ucd.py +2089 -0
- dagcert/_core/v7_benchmarks.py +734 -0
- dagcert/_core/v8_unified_experiments.py +1503 -0
- dagcert/_core/v9_v34_tracker.py +2556 -0
- dagcert/_core/witness_cab.py +239 -0
- dagcert/_native/__init__.py +1 -0
- dagcert/_native/_cpp_kernels.cpp +1026 -0
- dagcert/_native/_cpp_samegame.cpp +265 -0
- dagcert/_native/_cpp_v12_kg.cpp +328 -0
- dagcert/_native/_cpp_v34_bnb.cpp +706 -0
- dagcert/acquisition.py +625 -0
- dagcert/benchmarks/__init__.py +119 -0
- dagcert/benchmarks/data/gb1_wu2016_measured.npz +0 -0
- dagcert/benchmarks/data/samegame/StandardTestset.txt +321 -0
- dagcert/benchmarks/data/trpb_johnston2024_measured.npz +0 -0
- dagcert/benchmarks/data/worfbench_qwen3_81x64.npz +0 -0
- dagcert/benchmarks/data/worfbench_qwen3_test_81x32.npz +0 -0
- dagcert/benchmarks/proteins.py +63 -0
- dagcert/benchmarks/synthetic.py +86 -0
- dagcert/benchmarks/workflows.py +22 -0
- dagcert/certificates.py +182 -0
- dagcert/graph.py +113 -0
- dagcert/posteriors.py +189 -0
- dagcert/search.py +52 -0
- dagcert/tracking.py +94 -0
- dagcert-1.0.0.dist-info/METADATA +347 -0
- dagcert-1.0.0.dist-info/RECORD +69 -0
- dagcert-1.0.0.dist-info/WHEEL +5 -0
- dagcert-1.0.0.dist-info/licenses/LICENSE +21 -0
- dagcert-1.0.0.dist-info/top_level.txt +1 -0
dagcert/__init__.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""dagcert: Joint Root Certification and Decision-Aware Bayesian Experimental Design.
|
|
2
|
+
|
|
3
|
+
Official Python library accompanying:
|
|
4
|
+
*Certify the Decision, Not the Outcome: Bayesian Experimental Design on Search Graphs*
|
|
5
|
+
|
|
6
|
+
Quick start
|
|
7
|
+
-----------
|
|
8
|
+
>>> import numpy as np
|
|
9
|
+
>>> from dagcert import SearchDAG, certify_root_action
|
|
10
|
+
>>> dag = SearchDAG.from_supports([[0, 1, 2], [1, 2, 3]])
|
|
11
|
+
>>> true_means = np.array([0.82, 0.70, 0.65, 0.50])
|
|
12
|
+
>>> rng = np.random.default_rng(0)
|
|
13
|
+
>>> res = certify_root_action(
|
|
14
|
+
... dag=dag,
|
|
15
|
+
... observe_fn=lambda z: float(true_means[z] + 0.1 * rng.standard_normal()),
|
|
16
|
+
... kernel=0.05 * np.eye(4),
|
|
17
|
+
... prior_mean=0.6,
|
|
18
|
+
... obs_std=0.1,
|
|
19
|
+
... policy="cd_joint",
|
|
20
|
+
... stopping="credible_ellipsoid",
|
|
21
|
+
... epsilon=0.05,
|
|
22
|
+
... delta=0.05,
|
|
23
|
+
... )
|
|
24
|
+
>>> assert res.certified and res.action == 0
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
__version__ = "1.0.0"
|
|
29
|
+
|
|
30
|
+
from dagcert.acquisition import (
|
|
31
|
+
ALL_V12_POLICIES,
|
|
32
|
+
AcquisitionPolicy,
|
|
33
|
+
BayesianVOIPolicy,
|
|
34
|
+
CDJointPolicy,
|
|
35
|
+
CertificationResult,
|
|
36
|
+
CorrelatedKGPolicy,
|
|
37
|
+
GPOSPolicy,
|
|
38
|
+
GPTSPolicy,
|
|
39
|
+
GPUCBPolicy,
|
|
40
|
+
MatchedModelBEDSession,
|
|
41
|
+
NoisyGPEIPolicy,
|
|
42
|
+
certify_root_action,
|
|
43
|
+
correlated_kg_log_scores,
|
|
44
|
+
default_check_schedule,
|
|
45
|
+
exact_correlated_kg_single,
|
|
46
|
+
make_policy,
|
|
47
|
+
noisy_gp_ei_log_scores,
|
|
48
|
+
select_bayesian_root_voi,
|
|
49
|
+
select_gp_arm_with_beta,
|
|
50
|
+
)
|
|
51
|
+
from dagcert.certificates import (
|
|
52
|
+
ActionCertificate,
|
|
53
|
+
ChallengerResult,
|
|
54
|
+
CharacteristicRateResult,
|
|
55
|
+
DualWitnessCovers,
|
|
56
|
+
HullDominanceReport,
|
|
57
|
+
JointEllipsoidCertifier,
|
|
58
|
+
NestedIntervals,
|
|
59
|
+
RobustAwareJointCertifier,
|
|
60
|
+
ScheduledConicCertifier,
|
|
61
|
+
caratheodory_prune,
|
|
62
|
+
check_ellipsoid_stopping,
|
|
63
|
+
compute_hull_discrepancy,
|
|
64
|
+
exact_rectangular_regret,
|
|
65
|
+
solve_ellipsoid_challenger,
|
|
66
|
+
)
|
|
67
|
+
from dagcert.graph import (
|
|
68
|
+
DAG,
|
|
69
|
+
LeafOracle,
|
|
70
|
+
Problem,
|
|
71
|
+
SearchDAG,
|
|
72
|
+
SupportStructure,
|
|
73
|
+
)
|
|
74
|
+
from dagcert.posteriors import (
|
|
75
|
+
CalibratedGPPosteriorModel,
|
|
76
|
+
DiscreteGPPosteriorModel,
|
|
77
|
+
DiscreteGPSurrogate,
|
|
78
|
+
LinearFeatureModel,
|
|
79
|
+
SharedGaussianPosterior,
|
|
80
|
+
chi2_credible_beta,
|
|
81
|
+
clopper_pearson_upper,
|
|
82
|
+
contrast_ellipsoid_coverage,
|
|
83
|
+
contrast_rank_of_kernel,
|
|
84
|
+
cp_upper_exact,
|
|
85
|
+
estimate_posterior_root_risks,
|
|
86
|
+
eval_direct_posterior_risk_valid,
|
|
87
|
+
mc_postrisk_schedule,
|
|
88
|
+
nominal_gp_beta,
|
|
89
|
+
pointwise_coverage_diag,
|
|
90
|
+
)
|
|
91
|
+
from dagcert.search import (
|
|
92
|
+
CertifiedSearchSession,
|
|
93
|
+
CircuitMonitor,
|
|
94
|
+
CppKernelRunner,
|
|
95
|
+
CppSameGameRunner,
|
|
96
|
+
RecursivePUCT,
|
|
97
|
+
RootPUCT,
|
|
98
|
+
TrajectoryCoupledUCT,
|
|
99
|
+
)
|
|
100
|
+
from dagcert.tracking import (
|
|
101
|
+
ActiveDAGLUCBSession,
|
|
102
|
+
AdaptiveHardRegimeSession,
|
|
103
|
+
CorrelationAwareCertSession,
|
|
104
|
+
CppV34BnBRunner,
|
|
105
|
+
HybridWitnessDAGLUCBSession,
|
|
106
|
+
RegularizedInfoTrackerSession,
|
|
107
|
+
SmartHybridCertSession,
|
|
108
|
+
V34RunResult,
|
|
109
|
+
compute_characteristic_rate,
|
|
110
|
+
compute_exact_nuisance_kl_rate,
|
|
111
|
+
run_indep_heteroscedastic_os,
|
|
112
|
+
run_known_sigma_info_tracker,
|
|
113
|
+
run_v34_tracker,
|
|
114
|
+
solve_action_design_certified,
|
|
115
|
+
solve_profiled_loss_certified,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
__all__ = [
|
|
119
|
+
"ALL_V12_POLICIES",
|
|
120
|
+
"AcquisitionPolicy",
|
|
121
|
+
"ActionCertificate",
|
|
122
|
+
"ActiveDAGLUCBSession",
|
|
123
|
+
"AdaptiveHardRegimeSession",
|
|
124
|
+
"BayesianVOIPolicy",
|
|
125
|
+
"CDJointPolicy",
|
|
126
|
+
"CalibratedGPPosteriorModel",
|
|
127
|
+
"CertificationResult",
|
|
128
|
+
"CertifiedSearchSession",
|
|
129
|
+
"ChallengerResult",
|
|
130
|
+
"CharacteristicRateResult",
|
|
131
|
+
"CircuitMonitor",
|
|
132
|
+
"CorrelatedKGPolicy",
|
|
133
|
+
"CorrelationAwareCertSession",
|
|
134
|
+
"CppKernelRunner",
|
|
135
|
+
"CppSameGameRunner",
|
|
136
|
+
"CppV34BnBRunner",
|
|
137
|
+
"DAG",
|
|
138
|
+
"DiscreteGPPosteriorModel",
|
|
139
|
+
"DiscreteGPSurrogate",
|
|
140
|
+
"DualWitnessCovers",
|
|
141
|
+
"GPOSPolicy",
|
|
142
|
+
"GPTSPolicy",
|
|
143
|
+
"GPUCBPolicy",
|
|
144
|
+
"HullDominanceReport",
|
|
145
|
+
"HybridWitnessDAGLUCBSession",
|
|
146
|
+
"JointEllipsoidCertifier",
|
|
147
|
+
"LeafOracle",
|
|
148
|
+
"LinearFeatureModel",
|
|
149
|
+
"MatchedModelBEDSession",
|
|
150
|
+
"NestedIntervals",
|
|
151
|
+
"NoisyGPEIPolicy",
|
|
152
|
+
"Problem",
|
|
153
|
+
"RecursivePUCT",
|
|
154
|
+
"RegularizedInfoTrackerSession",
|
|
155
|
+
"RobustAwareJointCertifier",
|
|
156
|
+
"RootPUCT",
|
|
157
|
+
"ScheduledConicCertifier",
|
|
158
|
+
"SearchDAG",
|
|
159
|
+
"SharedGaussianPosterior",
|
|
160
|
+
"SmartHybridCertSession",
|
|
161
|
+
"SupportStructure",
|
|
162
|
+
"TrajectoryCoupledUCT",
|
|
163
|
+
"V34RunResult",
|
|
164
|
+
"__version__",
|
|
165
|
+
"caratheodory_prune",
|
|
166
|
+
"certify_root_action",
|
|
167
|
+
"check_ellipsoid_stopping",
|
|
168
|
+
"chi2_credible_beta",
|
|
169
|
+
"clopper_pearson_upper",
|
|
170
|
+
"compute_characteristic_rate",
|
|
171
|
+
"compute_exact_nuisance_kl_rate",
|
|
172
|
+
"compute_hull_discrepancy",
|
|
173
|
+
"contrast_ellipsoid_coverage",
|
|
174
|
+
"contrast_rank_of_kernel",
|
|
175
|
+
"correlated_kg_log_scores",
|
|
176
|
+
"cp_upper_exact",
|
|
177
|
+
"default_check_schedule",
|
|
178
|
+
"estimate_posterior_root_risks",
|
|
179
|
+
"eval_direct_posterior_risk_valid",
|
|
180
|
+
"exact_correlated_kg_single",
|
|
181
|
+
"exact_rectangular_regret",
|
|
182
|
+
"make_policy",
|
|
183
|
+
"mc_postrisk_schedule",
|
|
184
|
+
"noisy_gp_ei_log_scores",
|
|
185
|
+
"nominal_gp_beta",
|
|
186
|
+
"pointwise_coverage_diag",
|
|
187
|
+
"run_indep_heteroscedastic_os",
|
|
188
|
+
"run_known_sigma_info_tracker",
|
|
189
|
+
"run_v34_tracker",
|
|
190
|
+
"select_bayesian_root_voi",
|
|
191
|
+
"select_gp_arm_with_beta",
|
|
192
|
+
"solve_action_design_certified",
|
|
193
|
+
"solve_ellipsoid_challenger",
|
|
194
|
+
"solve_profiled_loss_certified",
|
|
195
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Internal verified numerical engines for dagcert."""
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Paid interval merging and max/count tournament tree utilities for graph certification."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from functools import cmp_to_key
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def merge(xs, w):
|
|
8
|
+
"""Merge sorted half-open leaf intervals while charging comparison/write work."""
|
|
9
|
+
def cmp(a, b):
|
|
10
|
+
w.heap_comparisons += 1
|
|
11
|
+
return (a > b) - (a < b)
|
|
12
|
+
|
|
13
|
+
out = []
|
|
14
|
+
for lo, hi in sorted(xs, key=cmp_to_key(cmp)):
|
|
15
|
+
w.query_reads += 2
|
|
16
|
+
w.statistic_writes += 1
|
|
17
|
+
if out and lo <= out[-1][1]:
|
|
18
|
+
out[-1] = (out[-1][0], max(hi, out[-1][1]))
|
|
19
|
+
w.heap_comparisons += 2
|
|
20
|
+
else:
|
|
21
|
+
out.append((lo, hi))
|
|
22
|
+
w.heap_comparisons += 1
|
|
23
|
+
return tuple(out)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CountTree:
|
|
27
|
+
"""Charged max/count tournament tree over leaf rank intervals."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, values, w):
|
|
30
|
+
self.w = w
|
|
31
|
+
self.n = len(values)
|
|
32
|
+
self.size = 1 << (self.n - 1).bit_length()
|
|
33
|
+
self.value = [-1] * (2 * self.size)
|
|
34
|
+
self.count = [0] * (2 * self.size)
|
|
35
|
+
w.initialization += 4 * self.size + 3
|
|
36
|
+
for i, v in enumerate(values):
|
|
37
|
+
self.value[self.size + i] = v
|
|
38
|
+
self.count[self.size + i] = int(v >= 0)
|
|
39
|
+
w.statistic_writes += 2
|
|
40
|
+
for p in range(self.size - 1, 0, -1):
|
|
41
|
+
self._pull(p)
|
|
42
|
+
|
|
43
|
+
def _pull(self, p):
|
|
44
|
+
v = self.value
|
|
45
|
+
c = self.count
|
|
46
|
+
l = 2 * p
|
|
47
|
+
r = l + 1
|
|
48
|
+
m = max(v[l], v[r])
|
|
49
|
+
n = (c[l] if v[l] == m else 0) + (c[r] if v[r] == m else 0)
|
|
50
|
+
self.w.query_reads += 6
|
|
51
|
+
self.w.heap_comparisons += 4
|
|
52
|
+
changed = m != v[p] or n != c[p]
|
|
53
|
+
v[p] = m
|
|
54
|
+
c[p] = n
|
|
55
|
+
self.w.heap_writes += 2
|
|
56
|
+
return changed
|
|
57
|
+
|
|
58
|
+
def update(self, i, v):
|
|
59
|
+
p = self.size + i
|
|
60
|
+
self.w.query_reads += 1
|
|
61
|
+
if self.value[p] == v:
|
|
62
|
+
return
|
|
63
|
+
self.value[p] = v
|
|
64
|
+
self.count[p] = int(v >= 0)
|
|
65
|
+
self.w.heap_writes += 2
|
|
66
|
+
p //= 2
|
|
67
|
+
while p:
|
|
68
|
+
if not self._pull(p):
|
|
69
|
+
break
|
|
70
|
+
p //= 2
|
|
71
|
+
|
|
72
|
+
def cover(self, ranges):
|
|
73
|
+
out = []
|
|
74
|
+
for a, b in reversed(ranges):
|
|
75
|
+
left = []
|
|
76
|
+
right = []
|
|
77
|
+
a += self.size
|
|
78
|
+
b += self.size
|
|
79
|
+
self.w.query_reads += 2
|
|
80
|
+
while a < b:
|
|
81
|
+
self.w.query_reads += 2
|
|
82
|
+
self.w.heap_comparisons += 2
|
|
83
|
+
if a & 1:
|
|
84
|
+
left.append(a)
|
|
85
|
+
a += 1
|
|
86
|
+
self.w.statistic_writes += 1
|
|
87
|
+
if b & 1:
|
|
88
|
+
b -= 1
|
|
89
|
+
right.append(b)
|
|
90
|
+
self.w.statistic_writes += 1
|
|
91
|
+
a //= 2
|
|
92
|
+
b //= 2
|
|
93
|
+
out.extend(right)
|
|
94
|
+
out.extend(reversed(left))
|
|
95
|
+
self.w.statistic_writes += len(left) + len(right)
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
def select(self, nodes, rng=None, rank=None):
|
|
99
|
+
maximum = -1
|
|
100
|
+
total = 0
|
|
101
|
+
w = self.w
|
|
102
|
+
for p in nodes:
|
|
103
|
+
v = self.value[p]
|
|
104
|
+
w.query_reads += 2
|
|
105
|
+
w.heap_comparisons += 2
|
|
106
|
+
if v > maximum:
|
|
107
|
+
maximum = v
|
|
108
|
+
total = self.count[p]
|
|
109
|
+
elif v == maximum:
|
|
110
|
+
total += self.count[p]
|
|
111
|
+
if total == 0:
|
|
112
|
+
return -1, None
|
|
113
|
+
k = rng.randrange(total) if rank is None else rank
|
|
114
|
+
w.score_evaluations += int(rank is None)
|
|
115
|
+
if not 0 <= k < total:
|
|
116
|
+
raise IndexError(k)
|
|
117
|
+
for p in nodes:
|
|
118
|
+
w.query_reads += 2
|
|
119
|
+
w.heap_comparisons += 2
|
|
120
|
+
if self.value[p] != maximum:
|
|
121
|
+
continue
|
|
122
|
+
if k >= self.count[p]:
|
|
123
|
+
k -= self.count[p]
|
|
124
|
+
continue
|
|
125
|
+
while p < self.size:
|
|
126
|
+
r = 2 * p + 1
|
|
127
|
+
n = self.count[r] if self.value[r] == maximum else 0
|
|
128
|
+
w.query_reads += 2
|
|
129
|
+
w.heap_comparisons += 2
|
|
130
|
+
if k < n:
|
|
131
|
+
p = r
|
|
132
|
+
else:
|
|
133
|
+
k -= n
|
|
134
|
+
p = r - 1
|
|
135
|
+
return maximum, p - self.size
|
|
136
|
+
raise AssertionError("bad max/count tree")
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Audited SameGame engine and reachable-endgame DAG generator over the 20 standard boards."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections import Counter
|
|
5
|
+
from fractions import Fraction
|
|
6
|
+
from functools import lru_cache
|
|
7
|
+
import hashlib
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import random
|
|
10
|
+
|
|
11
|
+
from dagcert._core.graph import DAG
|
|
12
|
+
|
|
13
|
+
HASH = "d20270c2d3ddff9add5d77fa85593574f85de7fbf8b0db0729e6d8c85b2a4d35"
|
|
14
|
+
STANDARD_PATH = Path(__file__).resolve().parents[1] / "benchmarks" / "data" / "samegame" / "StandardTestset.txt"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def standard():
|
|
18
|
+
if hashlib.sha256(STANDARD_PATH.read_bytes()).hexdigest() != HASH:
|
|
19
|
+
raise ValueError("wrong benchmark revision")
|
|
20
|
+
rows = [list(map(int, l.split())) for l in STANDARD_PATH.read_text().splitlines() if l.strip()]
|
|
21
|
+
if len(rows) != 300 or any(len(r) != 15 for r in rows):
|
|
22
|
+
raise ValueError("board format")
|
|
23
|
+
return [tuple(tuple(col) for col in zip(*rows[i : i + 15][::-1])) for i in range(0, 300, 15)]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def tiles(board):
|
|
27
|
+
return sum(map(len, board))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def finish(board):
|
|
31
|
+
if not board:
|
|
32
|
+
return 1000
|
|
33
|
+
counts = Counter(c for col in board for c in col)
|
|
34
|
+
return -sum(max(n - 2, 0) ** 2 for n in counts.values())
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Moves:
|
|
38
|
+
def __init__(self):
|
|
39
|
+
self.cache = {}
|
|
40
|
+
self.cost = 0
|
|
41
|
+
self.entries = 0
|
|
42
|
+
|
|
43
|
+
def __call__(self, board):
|
|
44
|
+
self.cost += 1
|
|
45
|
+
if board in self.cache:
|
|
46
|
+
return self.cache[board]
|
|
47
|
+
seen = set()
|
|
48
|
+
actions = []
|
|
49
|
+
cells = tiles(board)
|
|
50
|
+
self.cost += 12 * cells + len(board) + 4
|
|
51
|
+
for x, col in enumerate(board):
|
|
52
|
+
for y, color in enumerate(col):
|
|
53
|
+
if (x, y) in seen:
|
|
54
|
+
continue
|
|
55
|
+
group = {(x, y)}
|
|
56
|
+
seen.add((x, y))
|
|
57
|
+
todo = [(x, y)]
|
|
58
|
+
while todo:
|
|
59
|
+
i, j = todo.pop()
|
|
60
|
+
for a, b in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
|
|
61
|
+
if 0 <= a < len(board) and 0 <= b < len(board[a]) and (a, b) not in seen and board[a][b] == color:
|
|
62
|
+
seen.add((a, b))
|
|
63
|
+
group.add((a, b))
|
|
64
|
+
todo.append((a, b))
|
|
65
|
+
if len(group) < 2:
|
|
66
|
+
continue
|
|
67
|
+
child = tuple(
|
|
68
|
+
tuple(c for j, c in enumerate(column) if (i, j) not in group)
|
|
69
|
+
for i, column in enumerate(board)
|
|
70
|
+
)
|
|
71
|
+
child = tuple(column for column in child if column)
|
|
72
|
+
actions.append((child, (len(group) - 2) ** 2))
|
|
73
|
+
self.cost += 4 * cells + 3 * len(board)
|
|
74
|
+
self.cache[board] = tuple(actions)
|
|
75
|
+
self.entries += 1 + sum(2 + len(b) + tiles(b) for b, _ in actions)
|
|
76
|
+
return self.cache[board]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def game_cases():
|
|
80
|
+
cases = []
|
|
81
|
+
for k, initial in enumerate(standard(), 1):
|
|
82
|
+
rng = random.Random(226000 + k)
|
|
83
|
+
moves = Moves()
|
|
84
|
+
board = initial
|
|
85
|
+
path = []
|
|
86
|
+
choices = []
|
|
87
|
+
while actions := moves(board):
|
|
88
|
+
if len(actions) >= 2:
|
|
89
|
+
choices.append((board, list(path)))
|
|
90
|
+
index = rng.randrange(len(actions))
|
|
91
|
+
path.append(index)
|
|
92
|
+
board = actions[index][0]
|
|
93
|
+
eligible = [item for item in choices if len(moves(item[0])) >= 4]
|
|
94
|
+
if not eligible:
|
|
95
|
+
raise ValueError("standard board has no four-way decision")
|
|
96
|
+
board, path = next((item for item in eligible if tiles(item[0]) <= 54), eligible[-1])
|
|
97
|
+
cases.append(dict(family="standard_end", seed=226000 + k, board=board, path=path, source=k, h=3, eps=0.02))
|
|
98
|
+
for seed in range(227101, 227113):
|
|
99
|
+
rng = random.Random(seed)
|
|
100
|
+
while True:
|
|
101
|
+
board = tuple(tuple(rng.randrange(3) for _ in range(5)) for _ in range(5))
|
|
102
|
+
if len(Moves()(board)) >= 2:
|
|
103
|
+
break
|
|
104
|
+
cases.append(dict(family="small", seed=seed, board=board, h=3, eps=0.05))
|
|
105
|
+
return cases
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class Game:
|
|
109
|
+
def __init__(self, board, h):
|
|
110
|
+
self.start = board
|
|
111
|
+
self.h = h
|
|
112
|
+
counts = Counter(c for col in board for c in col).values()
|
|
113
|
+
self.B = sum(max(k - 2, 0) ** 2 for k in counts)
|
|
114
|
+
self.scale = max(1, (0 if 1 in counts else 1000) + 2 * self.B)
|
|
115
|
+
self.moves = Moves()
|
|
116
|
+
self.states = [(board, 0, h)]
|
|
117
|
+
rank = {self.states[0]: 0}
|
|
118
|
+
rows = []
|
|
119
|
+
for b, points, left in self.states:
|
|
120
|
+
actions = self.moves(b) if left else ()
|
|
121
|
+
children = []
|
|
122
|
+
for nxt, gain in actions:
|
|
123
|
+
state = nxt, points + gain, left - 1
|
|
124
|
+
if state not in rank:
|
|
125
|
+
rank[state] = len(rank)
|
|
126
|
+
self.states.append(state)
|
|
127
|
+
children.append(rank[state])
|
|
128
|
+
rows.append(tuple(dict.fromkeys(children)))
|
|
129
|
+
root_moves = self.moves(board)
|
|
130
|
+
aliases = []
|
|
131
|
+
for nxt, gain in root_moves:
|
|
132
|
+
child = rank[nxt, gain, h - 1]
|
|
133
|
+
aliases.append(len(rows))
|
|
134
|
+
rows.append((child,))
|
|
135
|
+
rows[0] = tuple(aliases)
|
|
136
|
+
self.graph = DAG(rows)
|
|
137
|
+
self.build = self.moves.cost + 5 * sum(map(len, rows)) + 5 * len(rows) + self.moves.entries
|
|
138
|
+
|
|
139
|
+
def oracle(self, seed):
|
|
140
|
+
return GameOracle(self, seed)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class GameOracle:
|
|
144
|
+
def __init__(self, p, seed):
|
|
145
|
+
self.p = p
|
|
146
|
+
self.moves = Moves()
|
|
147
|
+
self.calls = 0
|
|
148
|
+
self.extra = 0
|
|
149
|
+
self.tapes = {j: random.Random(1000003 * (seed + 1) + 9176 * j) for j in p.graph.leaves}
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def operations(self):
|
|
153
|
+
return self.moves.cost + self.extra + self.moves.entries
|
|
154
|
+
|
|
155
|
+
def sample(self, j):
|
|
156
|
+
self.calls += 1
|
|
157
|
+
b, score, _ = self.p.states[j]
|
|
158
|
+
rng = self.tapes[j]
|
|
159
|
+
while actions := self.moves(b):
|
|
160
|
+
b, points = actions[rng.randrange(len(actions))]
|
|
161
|
+
score += points
|
|
162
|
+
self.extra += 4
|
|
163
|
+
self.extra += 6 + tiles(b)
|
|
164
|
+
return (score + finish(b) + self.p.B) / self.p.scale
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def exact(board, h):
|
|
168
|
+
moves = Moves()
|
|
169
|
+
|
|
170
|
+
@lru_cache(None)
|
|
171
|
+
def value(b, left):
|
|
172
|
+
actions = moves(b)
|
|
173
|
+
if not actions:
|
|
174
|
+
return Fraction(finish(b))
|
|
175
|
+
vals = [g + value(nxt, max(0, left - 1)) for nxt, g in actions]
|
|
176
|
+
return max(vals) if left else sum(vals, Fraction()) / len(vals)
|
|
177
|
+
|
|
178
|
+
vals = [g + value(nxt, h - 1) for nxt, g in moves(board)]
|
|
179
|
+
return max(vals), vals
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Cold DAG fixture generators for passive UCT/PUCT certification benchmarks."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import random
|
|
5
|
+
|
|
6
|
+
from dagcert._core.backprop_problems import reconvergent
|
|
7
|
+
from dagcert._core.graph import DAG, Problem, feature_lattice
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def binary_root(rows, nodes):
|
|
11
|
+
"""Join a power of two equally deep children without changing action order."""
|
|
12
|
+
while len(nodes) > 1:
|
|
13
|
+
parents = []
|
|
14
|
+
for j in range(0, len(nodes), 2):
|
|
15
|
+
parents.append(len(rows))
|
|
16
|
+
rows.append((nodes[j], nodes[j + 1]))
|
|
17
|
+
nodes = parents
|
|
18
|
+
return nodes[0]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def funnel(width, seed, noisy=False, placement="low", exits=1, gap=None):
|
|
22
|
+
if width < 2 or width & (width - 1):
|
|
23
|
+
raise ValueError("power-of-two funnel width required")
|
|
24
|
+
gap = 0.25 * width ** (-1 / 16) if gap is None else gap
|
|
25
|
+
rows = [(), (), (), ()]
|
|
26
|
+
means = {1: 0.75, 2: 0.75 - gap, 3: 0.25}
|
|
27
|
+
if exits == 2:
|
|
28
|
+
rows.append(())
|
|
29
|
+
means.update({3: 0.125, 4: 0.375})
|
|
30
|
+
bottom = []
|
|
31
|
+
for i in range(width):
|
|
32
|
+
target = 1 if placement == "best" else 3 + int(exits == 2 and i >= width // 2)
|
|
33
|
+
bottom.append(len(rows))
|
|
34
|
+
rows.append((target,))
|
|
35
|
+
top = binary_root(rows, bottom)
|
|
36
|
+
actions = [top, 2, 3] if placement == "best" else [1, 2, top]
|
|
37
|
+
random.Random(seed).shuffle(actions)
|
|
38
|
+
rows[0] = actions
|
|
39
|
+
graph = DAG(rows)
|
|
40
|
+
problem = Problem("funnel", graph, means, () if noisy else graph.leaves)
|
|
41
|
+
return problem, gap / 2
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def wide_core(r, seed):
|
|
45
|
+
if r < 2 or r & (r - 1):
|
|
46
|
+
raise ValueError("power-of-two core factor required")
|
|
47
|
+
rows = [(), ()]
|
|
48
|
+
leaves = list(range(2, r * r + 2))
|
|
49
|
+
rows.extend([()] * (r * r))
|
|
50
|
+
hub = binary_root(rows, leaves)
|
|
51
|
+
actions = [1]
|
|
52
|
+
for _ in range(r):
|
|
53
|
+
own = len(rows)
|
|
54
|
+
rows.append(())
|
|
55
|
+
actions.append(len(rows))
|
|
56
|
+
rows.append((hub, own))
|
|
57
|
+
random.Random(seed).shuffle(actions)
|
|
58
|
+
rows[0] = actions
|
|
59
|
+
graph = DAG(rows)
|
|
60
|
+
means = {leaf: float(leaf == 1) for leaf in graph.leaves}
|
|
61
|
+
return Problem("wide core", graph, means, graph.leaves), 0.20
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def fixture(family, size, seed):
|
|
65
|
+
if family in ("funnel", "noisy"):
|
|
66
|
+
return funnel(size, seed, noisy=(family == "noisy"))
|
|
67
|
+
if family == "two-exit":
|
|
68
|
+
return funnel(size, seed, exits=2)
|
|
69
|
+
if family == "live-best":
|
|
70
|
+
return funnel(size, seed, placement="best")
|
|
71
|
+
if family == "fixed-gap":
|
|
72
|
+
return funnel(size, seed, gap=0.10)
|
|
73
|
+
if family == "core":
|
|
74
|
+
return wide_core(size, seed)
|
|
75
|
+
if family == "lattice":
|
|
76
|
+
return feature_lattice(size, True), 0.08
|
|
77
|
+
if family == "merge":
|
|
78
|
+
return reconvergent(size, 6), 0.08
|
|
79
|
+
raise ValueError(family)
|