forgeproof-cli 0.2.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.
- forge_gate/__init__.py +44 -0
- forge_gate/_deprecated_cli.py +16 -0
- forgeproof/__init__.py +3 -0
- forgeproof/catalog.py +110 -0
- forgeproof/cli.py +560 -0
- forgeproof/config.py +339 -0
- forgeproof/data/gate_catalog.json +66 -0
- forgeproof/data/host_sets.json +7 -0
- forgeproof/debug_caller.py +271 -0
- forgeproof/debug_core.py +368 -0
- forgeproof/fixture_engine.py +81 -0
- forgeproof/fixtures/__init__.py +19 -0
- forgeproof/fixtures/decision_tree_id3.py +90 -0
- forgeproof/fixtures/gradient_descent_momentum.py +73 -0
- forgeproof/fixtures/kmeans_clustering.py +98 -0
- forgeproof/fixtures/knn_classifier.py +79 -0
- forgeproof/fixtures/linear_regression_gd.py +77 -0
- forgeproof/fixtures/logistic_regression.py +85 -0
- forgeproof/fixtures/naive_bayes_text.py +114 -0
- forgeproof/fixtures/perceptron.py +84 -0
- forgeproof/fixtures/polynomial_regression.py +67 -0
- forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
- forgeproof/ledger.py +633 -0
- forgeproof/lens_tools/__init__.py +11 -0
- forgeproof/lens_tools/guard_lens.py +1250 -0
- forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
- forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
- forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
- forgeproof/lens_tools/invariant_gate.py +199 -0
- forgeproof/lens_tools/metamorphic/__init__.py +9 -0
- forgeproof/lens_tools/metamorphic/relations.py +962 -0
- forgeproof/lens_tools/metamorphic/runner.py +112 -0
- forgeproof/lens_tools/twin_consensus.py +395 -0
- forgeproof/lenses.py +923 -0
- forgeproof/paths.py +56 -0
- forgeproof/reference/ORIGIN.md +29 -0
- forgeproof/reference/decision_tree_id3.py +197 -0
- forgeproof/reference/gradient_descent_momentum.py +141 -0
- forgeproof/reference/kmeans_clustering.py +139 -0
- forgeproof/reference/knn_classifier.py +118 -0
- forgeproof/reference/linear_regression_gd.py +106 -0
- forgeproof/reference/logistic_regression.py +141 -0
- forgeproof/reference/naive_bayes_text.py +152 -0
- forgeproof/reference/perceptron.py +123 -0
- forgeproof/reference/polynomial_regression.py +125 -0
- forgeproof/reference/ridge_regression_normal_eq.py +165 -0
- forgeproof/runner.py +147 -0
- forgeproof/scout/__init__.py +7 -0
- forgeproof/scout/behaviour.py +365 -0
- forgeproof/scout/box.py +581 -0
- forgeproof/scout/cards.py +180 -0
- forgeproof/scout/contract.py +37 -0
- forgeproof/scout/corpus.py +104 -0
- forgeproof/scout/embed.py +217 -0
- forgeproof/scout/engines/__init__.py +1 -0
- forgeproof/scout/engines/chaos.py +454 -0
- forgeproof/scout/engines/chaos_port.py +1331 -0
- forgeproof/scout/engines/chaos_runner.py +178 -0
- forgeproof/scout/engines/executor_port.py +239 -0
- forgeproof/scout/envfit.py +54 -0
- forgeproof/scout/experience.py +161 -0
- forgeproof/scout/fetchproxy.py +368 -0
- forgeproof/scout/ghcache.py +395 -0
- forgeproof/scout/ghpool.py +253 -0
- forgeproof/scout/ghsearch.py +248 -0
- forgeproof/scout/ids.py +82 -0
- forgeproof/scout/intent_lens.py +170 -0
- forgeproof/scout/learn.py +583 -0
- forgeproof/scout/meaning_lens.py +231 -0
- forgeproof/scout/outcomes.py +42 -0
- forgeproof/scout/plant.py +327 -0
- forgeproof/scout/ratify.py +214 -0
- forgeproof/scout/report.py +448 -0
- forgeproof/scout/rule2.py +177 -0
- forgeproof/scout/shape.py +107 -0
- forgeproof/scout/shape_lens.py +71 -0
- forgeproof/scout/signature.py +52 -0
- forgeproof/scout/slots.py +39 -0
- forgeproof/scout/upstream_facts.py +536 -0
- forgeproof/unsupported.py +83 -0
- forgeproof/verifier.py +208 -0
- forgeproof/view_coverage.py +166 -0
- forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
- forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
- forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
- forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
- forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
- forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
- forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,962 @@
|
|
|
1
|
+
"""Signed metamorphic (transform, comparator) relations per pattern category.
|
|
2
|
+
|
|
3
|
+
A Relation is a named callable that takes a user module (the implementation under
|
|
4
|
+
verification), produces one or more source/follow-up input pairs, runs the
|
|
5
|
+
implementation on both, and checks a deterministic property.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
import random
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Callable, Dict, List, Tuple
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
random.seed(0) # module-level determinism
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class RelationResult:
|
|
20
|
+
name: str
|
|
21
|
+
passed: bool
|
|
22
|
+
reason: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Relation:
|
|
27
|
+
name: str
|
|
28
|
+
pattern_category: str
|
|
29
|
+
check: Callable[[Any], RelationResult]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _predict_linear(mod, X, params):
|
|
33
|
+
weights, bias = params
|
|
34
|
+
return [bias + sum(weights[j] * x[j] for j in range(len(weights))) for x in X]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _approx(a, b, tol=1e-6):
|
|
38
|
+
if isinstance(a, float) and isinstance(b, (int, float)):
|
|
39
|
+
return abs(a - float(b)) <= tol
|
|
40
|
+
if isinstance(a, list) and isinstance(b, list):
|
|
41
|
+
return len(a) == len(b) and all(_approx(x, y, tol) for x, y in zip(a, b))
|
|
42
|
+
return a == b
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _linreg_scale_target(mod) -> RelationResult:
|
|
46
|
+
"""Scaling all targets by k scales all predictions by k."""
|
|
47
|
+
random.seed(42)
|
|
48
|
+
n = 30
|
|
49
|
+
X = [[random.uniform(-5, 5), random.uniform(-5, 5)] for _ in range(n)]
|
|
50
|
+
y = [2.0 * X[i][0] + 3.0 * X[i][1] + random.gauss(0, 0.5) for i in range(n)]
|
|
51
|
+
k = 2.5
|
|
52
|
+
|
|
53
|
+
fit = getattr(mod, "linear_regression_gd")
|
|
54
|
+
source = _predict_linear(mod, X, fit(X, y, 0.05, 500))
|
|
55
|
+
y_scaled = [k * v for v in y]
|
|
56
|
+
follow = _predict_linear(mod, X, fit(X, y_scaled, 0.05, 500))
|
|
57
|
+
expected = [k * v for v in source]
|
|
58
|
+
ok = _approx(follow, expected, tol=1e-3)
|
|
59
|
+
return RelationResult(
|
|
60
|
+
"linreg_scale_target", ok,
|
|
61
|
+
"scaled predictions match" if ok else f"expected {expected[:3]}..., got {follow[:3]}..."
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _linreg_shift_target(mod) -> RelationResult:
|
|
66
|
+
"""Adding a constant to all targets shifts predictions by that constant."""
|
|
67
|
+
random.seed(43)
|
|
68
|
+
n = 30
|
|
69
|
+
X = [[random.uniform(-5, 5), random.uniform(-5, 5)] for _ in range(n)]
|
|
70
|
+
y = [2.0 * X[i][0] + 3.0 * X[i][1] + random.gauss(0, 0.5) for i in range(n)]
|
|
71
|
+
c = 7.0
|
|
72
|
+
|
|
73
|
+
fit = getattr(mod, "linear_regression_gd")
|
|
74
|
+
source = _predict_linear(mod, X, fit(X, y, 0.05, 500))
|
|
75
|
+
y_shifted = [v + c for v in y]
|
|
76
|
+
follow = _predict_linear(mod, X, fit(X, y_shifted, 0.05, 500))
|
|
77
|
+
expected = [v + c for v in source]
|
|
78
|
+
ok = _approx(follow, expected, tol=1e-3)
|
|
79
|
+
return RelationResult(
|
|
80
|
+
"linreg_shift_target", ok,
|
|
81
|
+
"shifted predictions match" if ok else f"expected {expected[:3]}..., got {follow[:3]}..."
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _linreg_feature_permutation(mod) -> RelationResult:
|
|
86
|
+
"""Permuting feature columns preserves predictions up to column reordering."""
|
|
87
|
+
random.seed(44)
|
|
88
|
+
n = 30
|
|
89
|
+
X = [[random.uniform(-5, 5), random.uniform(-5, 5)] for _ in range(n)]
|
|
90
|
+
y = [2.0 * X[i][0] + 3.0 * X[i][1] + random.gauss(0, 0.5) for i in range(n)]
|
|
91
|
+
|
|
92
|
+
fit = getattr(mod, "linear_regression_gd")
|
|
93
|
+
weights, bias = fit(X, y, 0.01, 1000)
|
|
94
|
+
perm = [1, 0]
|
|
95
|
+
X_perm = [[row[perm[j]] for j in range(len(row))] for row in X]
|
|
96
|
+
weights_perm, bias_perm = fit(X_perm, y, 0.01, 1000)
|
|
97
|
+
|
|
98
|
+
source_pred = [bias + weights[0] * X[i][0] + weights[1] * X[i][1] for i in range(n)]
|
|
99
|
+
follow_pred = [bias_perm + weights_perm[0] * X_perm[i][0] + weights_perm[1] * X_perm[i][1] for i in range(n)]
|
|
100
|
+
ok = _approx(source_pred, follow_pred, tol=1e-3)
|
|
101
|
+
return RelationResult(
|
|
102
|
+
"linreg_feature_permutation", ok,
|
|
103
|
+
"permuted-feature predictions match" if ok else f"expected {source_pred[:3]}..., got {follow_pred[:3]}..."
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _poly_scale_target(mod) -> RelationResult:
|
|
108
|
+
"""Scaling targets by k scales polynomial evaluations by k."""
|
|
109
|
+
random.seed(45)
|
|
110
|
+
true_coeffs = [2.0, 3.0, 0.5]
|
|
111
|
+
x_vals = [float(i) * 0.5 for i in range(20)]
|
|
112
|
+
eval_poly = getattr(mod, "eval_poly")
|
|
113
|
+
y_vals = [eval_poly(true_coeffs, x) + random.gauss(0, 0.1) for x in x_vals]
|
|
114
|
+
k = 2.0
|
|
115
|
+
|
|
116
|
+
fit = getattr(mod, "fit_polynomial")
|
|
117
|
+
source = [eval_poly(fit(x_vals, y_vals, 2), x) for x in x_vals]
|
|
118
|
+
y_scaled = [k * v for v in y_vals]
|
|
119
|
+
follow = [eval_poly(fit(x_vals, y_scaled, 2), x) for x in x_vals]
|
|
120
|
+
expected = [k * v for v in source]
|
|
121
|
+
ok = _approx(follow, expected, tol=1e-3)
|
|
122
|
+
return RelationResult(
|
|
123
|
+
"poly_scale_target", ok,
|
|
124
|
+
"scaled polynomial predictions match" if ok else f"expected {expected[:3]}..., got {follow[:3]}..."
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _poly_shift_target(mod) -> RelationResult:
|
|
129
|
+
"""Adding a constant to targets shifts polynomial intercept by that constant."""
|
|
130
|
+
random.seed(46)
|
|
131
|
+
true_coeffs = [2.0, 3.0, 0.5]
|
|
132
|
+
x_vals = [float(i) * 0.5 for i in range(20)]
|
|
133
|
+
eval_poly = getattr(mod, "eval_poly")
|
|
134
|
+
y_vals = [eval_poly(true_coeffs, x) + random.gauss(0, 0.1) for x in x_vals]
|
|
135
|
+
c = 5.0
|
|
136
|
+
|
|
137
|
+
fit = getattr(mod, "fit_polynomial")
|
|
138
|
+
source = [eval_poly(fit(x_vals, y_vals, 2), x) for x in x_vals]
|
|
139
|
+
y_shifted = [v + c for v in y_vals]
|
|
140
|
+
follow = [eval_poly(fit(x_vals, y_shifted, 2), x) for x in x_vals]
|
|
141
|
+
expected = [v + c for v in source]
|
|
142
|
+
ok = _approx(follow, expected, tol=1e-3)
|
|
143
|
+
return RelationResult(
|
|
144
|
+
"poly_shift_target", ok,
|
|
145
|
+
"shifted polynomial predictions match" if ok else f"expected {expected[:3]}..., got {follow[:3]}..."
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _ridge_scale_target(mod) -> RelationResult:
|
|
150
|
+
"""Scaling targets by k scales ridge predictions by k."""
|
|
151
|
+
random.seed(47)
|
|
152
|
+
n = 30
|
|
153
|
+
X = [[random.uniform(-5, 5), random.uniform(-5, 5)] for _ in range(n)]
|
|
154
|
+
y = [2.0 * X[i][0] + 3.0 * X[i][1] + random.gauss(0, 0.5) for i in range(n)]
|
|
155
|
+
k = 2.0
|
|
156
|
+
|
|
157
|
+
fit = getattr(mod, "ridge_regression_normal_eq")
|
|
158
|
+
weights = fit(X, y, 0.01)
|
|
159
|
+
source = [sum(weights[j] * X[i][j] for j in range(len(weights))) for i in range(n)]
|
|
160
|
+
y_scaled = [k * v for v in y]
|
|
161
|
+
weights2 = fit(X, y_scaled, 0.01)
|
|
162
|
+
follow = [sum(weights2[j] * X[i][j] for j in range(len(weights2))) for i in range(n)]
|
|
163
|
+
expected = [k * v for v in source]
|
|
164
|
+
ok = _approx(follow, expected, tol=1e-3)
|
|
165
|
+
return RelationResult(
|
|
166
|
+
"ridge_scale_target", ok,
|
|
167
|
+
"scaled ridge predictions match" if ok else f"expected {expected[:3]}..., got {follow[:3]}..."
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _ridge_ols_approx(mod) -> RelationResult:
|
|
172
|
+
"""With lambda near zero, ridge predictions should match ordinary least squares."""
|
|
173
|
+
random.seed(48)
|
|
174
|
+
n = 30
|
|
175
|
+
X = [[random.uniform(-5, 5), random.uniform(-5, 5), random.uniform(-5, 5)] for _ in range(n)]
|
|
176
|
+
true_w = [2.0, 3.0, -1.0]
|
|
177
|
+
y = [sum(true_w[j] * X[i][j] for j in range(3)) + random.gauss(0, 0.5) for i in range(n)]
|
|
178
|
+
|
|
179
|
+
fit = getattr(mod, "ridge_regression_normal_eq")
|
|
180
|
+
w_ols = fit(X, y, 1e-12)
|
|
181
|
+
w_ridge = fit(X, y, 1e-6)
|
|
182
|
+
|
|
183
|
+
pred_ols = [sum(w_ols[j] * X[i][j] for j in range(3)) for i in range(n)]
|
|
184
|
+
pred_ridge = [sum(w_ridge[j] * X[i][j] for j in range(3)) for i in range(n)]
|
|
185
|
+
|
|
186
|
+
ok = _approx(pred_ridge, pred_ols, tol=1e-2)
|
|
187
|
+
return RelationResult(
|
|
188
|
+
"ridge_ols_approx", ok,
|
|
189
|
+
"ridge ≈ OLS for tiny lambda" if ok else f"expected {pred_ols[:3]}..., got {pred_ridge[:3]}..."
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
# ---------------------------------------------------------------------------
|
|
194
|
+
# Classification relations
|
|
195
|
+
# ---------------------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
def _swap_labels(y: List[int]) -> List[int]:
|
|
198
|
+
return [1 - v for v in y]
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _make_binary_classification_data(seed: int, n: int = 80, sep: float = 1.5):
|
|
202
|
+
random.seed(seed)
|
|
203
|
+
X, y = [], []
|
|
204
|
+
for _ in range(n):
|
|
205
|
+
label = random.choice([0, 1])
|
|
206
|
+
x1 = random.uniform(-3, 3)
|
|
207
|
+
noise = random.gauss(0, 0.8)
|
|
208
|
+
x2 = (x1 + sep + noise) if label == 1 else (x1 - sep + noise)
|
|
209
|
+
X.append([x1, x2])
|
|
210
|
+
y.append(label)
|
|
211
|
+
return X, y
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _logreg_label_permutation(mod) -> RelationResult:
|
|
215
|
+
"""Swapping class labels should swap predicted labels."""
|
|
216
|
+
X, y = _make_binary_classification_data(50)
|
|
217
|
+
fit = getattr(mod, "logistic_regression_fit")
|
|
218
|
+
predict = getattr(mod, "logistic_regression_predict")
|
|
219
|
+
|
|
220
|
+
w, b = fit(X, y, 0.1, 200)
|
|
221
|
+
source_preds = predict(X, w, b)
|
|
222
|
+
y_swapped = _swap_labels(y)
|
|
223
|
+
w2, b2 = fit(X, y_swapped, 0.1, 200)
|
|
224
|
+
follow_preds = predict(X, w2, b2)
|
|
225
|
+
expected = _swap_labels(source_preds)
|
|
226
|
+
ok = follow_preds == expected
|
|
227
|
+
return RelationResult(
|
|
228
|
+
"logreg_label_permutation", ok,
|
|
229
|
+
"label swap reflected in predictions" if ok else f"expected {_swap_labels(source_preds[:5])}, got {follow_preds[:5]}"
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _logreg_duplicate_invariance(mod) -> RelationResult:
|
|
234
|
+
"""Duplicating a training point should not flip its prediction."""
|
|
235
|
+
X, y = _make_binary_classification_data(51)
|
|
236
|
+
fit = getattr(mod, "logistic_regression_fit")
|
|
237
|
+
predict = getattr(mod, "logistic_regression_predict")
|
|
238
|
+
|
|
239
|
+
probe = X[0]
|
|
240
|
+
w, b = fit(X, y, 0.1, 200)
|
|
241
|
+
pred_source = predict([probe], w, b)[0]
|
|
242
|
+
|
|
243
|
+
X_dup = X + [probe]
|
|
244
|
+
y_dup = y + [y[0]]
|
|
245
|
+
w2, b2 = fit(X_dup, y_dup, 0.1, 200)
|
|
246
|
+
pred_follow = predict([probe], w2, b2)[0]
|
|
247
|
+
ok = pred_source == pred_follow
|
|
248
|
+
return RelationResult(
|
|
249
|
+
"logreg_duplicate_invariance", ok,
|
|
250
|
+
"duplicate point prediction unchanged" if ok else f"source={pred_source}, follow={pred_follow}"
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _logreg_feature_permutation(mod) -> RelationResult:
|
|
255
|
+
"""Permuting feature columns consistently preserves predictions."""
|
|
256
|
+
X, y = _make_binary_classification_data(52)
|
|
257
|
+
fit = getattr(mod, "logistic_regression_fit")
|
|
258
|
+
predict = getattr(mod, "logistic_regression_predict")
|
|
259
|
+
|
|
260
|
+
w, b = fit(X, y, 0.1, 200)
|
|
261
|
+
source_preds = predict(X, w, b)
|
|
262
|
+
|
|
263
|
+
perm = [1, 0]
|
|
264
|
+
X_perm = [[row[perm[j]] for j in range(len(row))] for row in X]
|
|
265
|
+
w2, b2 = fit(X_perm, y, 0.1, 200)
|
|
266
|
+
follow_preds = predict(X_perm, w2, b2)
|
|
267
|
+
ok = follow_preds == source_preds
|
|
268
|
+
return RelationResult(
|
|
269
|
+
"logreg_feature_permutation", ok,
|
|
270
|
+
"feature permutation preserves predictions" if ok else f"source[:5]={source_preds[:5]}, follow[:5]={follow_preds[:5]}"
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _knn_label_permutation(mod) -> RelationResult:
|
|
275
|
+
"""Swapping class labels should swap predicted labels."""
|
|
276
|
+
random.seed(53)
|
|
277
|
+
X_train, y_train = _make_binary_classification_data(53, n=60)
|
|
278
|
+
X_test, y_test = _make_binary_classification_data(54, n=30)
|
|
279
|
+
predict = getattr(mod, "knn_predict_batch")
|
|
280
|
+
|
|
281
|
+
source_preds = predict(X_test, X_train, y_train, k=5)
|
|
282
|
+
y_train_swapped = _swap_labels(y_train)
|
|
283
|
+
follow_preds = predict(X_test, X_train, y_train_swapped, k=5)
|
|
284
|
+
expected = _swap_labels(source_preds)
|
|
285
|
+
ok = follow_preds == expected
|
|
286
|
+
return RelationResult(
|
|
287
|
+
"knn_label_permutation", ok,
|
|
288
|
+
"label swap reflected in predictions" if ok else f"expected {_swap_labels(source_preds[:5])}, got {follow_preds[:5]}"
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _knn_duplicate_invariance(mod) -> RelationResult:
|
|
293
|
+
"""Duplicating a training point should not flip its own prediction."""
|
|
294
|
+
random.seed(55)
|
|
295
|
+
X_train, y_train = _make_binary_classification_data(55, n=60)
|
|
296
|
+
X_test, y_test = _make_binary_classification_data(56, n=30)
|
|
297
|
+
predict = getattr(mod, "knn_predict_batch")
|
|
298
|
+
|
|
299
|
+
probe = X_train[0]
|
|
300
|
+
pred_source = predict([probe], X_train, y_train, k=5)[0]
|
|
301
|
+
|
|
302
|
+
X_train_dup = X_train + [probe]
|
|
303
|
+
y_train_dup = y_train + [y_train[0]]
|
|
304
|
+
pred_follow = predict([probe], X_train_dup, y_train_dup, k=5)[0]
|
|
305
|
+
ok = pred_source == pred_follow
|
|
306
|
+
return RelationResult(
|
|
307
|
+
"knn_duplicate_invariance", ok,
|
|
308
|
+
"duplicate point prediction unchanged" if ok else f"source={pred_source}, follow={pred_follow}"
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _knn_feature_permutation(mod) -> RelationResult:
|
|
313
|
+
"""Permuting feature columns consistently preserves predictions."""
|
|
314
|
+
random.seed(57)
|
|
315
|
+
X_train, y_train = _make_binary_classification_data(57, n=60)
|
|
316
|
+
X_test, y_test = _make_binary_classification_data(58, n=30)
|
|
317
|
+
predict = getattr(mod, "knn_predict_batch")
|
|
318
|
+
|
|
319
|
+
perm = [1, 0]
|
|
320
|
+
X_train_perm = [[row[perm[j]] for j in range(len(row))] for row in X_train]
|
|
321
|
+
X_test_perm = [[row[perm[j]] for j in range(len(row))] for row in X_test]
|
|
322
|
+
source_preds = predict(X_test, X_train, y_train, k=5)
|
|
323
|
+
follow_preds = predict(X_test_perm, X_train_perm, y_train, k=5)
|
|
324
|
+
ok = follow_preds == source_preds
|
|
325
|
+
return RelationResult(
|
|
326
|
+
"knn_feature_permutation", ok,
|
|
327
|
+
"feature permutation preserves predictions" if ok else f"source[:5]={source_preds[:5]}, follow[:5]={follow_preds[:5]}"
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _tree_label_permutation(mod) -> RelationResult:
|
|
332
|
+
"""Swapping class labels should swap predicted labels."""
|
|
333
|
+
random.seed(59)
|
|
334
|
+
X_train, y_train = _make_binary_classification_data(59, n=70)
|
|
335
|
+
X_test, y_test = _make_binary_classification_data(60, n=30)
|
|
336
|
+
build = getattr(mod, "build_tree")
|
|
337
|
+
predict = getattr(mod, "predict_tree")
|
|
338
|
+
|
|
339
|
+
tree = build(X_train, y_train, max_depth=5)
|
|
340
|
+
source_preds = [predict(X_test[i], tree) for i in range(len(X_test))]
|
|
341
|
+
tree2 = build(X_train, _swap_labels(y_train), max_depth=5)
|
|
342
|
+
follow_preds = [predict(X_test[i], tree2) for i in range(len(X_test))]
|
|
343
|
+
expected = _swap_labels(source_preds)
|
|
344
|
+
ok = follow_preds == expected
|
|
345
|
+
return RelationResult(
|
|
346
|
+
"tree_label_permutation", ok,
|
|
347
|
+
"label swap reflected in predictions" if ok else f"expected {_swap_labels(source_preds[:5])}, got {follow_preds[:5]}"
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _tree_duplicate_invariance(mod) -> RelationResult:
|
|
352
|
+
"""Duplicating a training point should not flip its prediction."""
|
|
353
|
+
random.seed(61)
|
|
354
|
+
X_train, y_train = _make_binary_classification_data(61, n=70)
|
|
355
|
+
build = getattr(mod, "build_tree")
|
|
356
|
+
predict = getattr(mod, "predict_tree")
|
|
357
|
+
|
|
358
|
+
probe = X_train[0]
|
|
359
|
+
tree = build(X_train, y_train, max_depth=5)
|
|
360
|
+
pred_source = predict(probe, tree)
|
|
361
|
+
|
|
362
|
+
X_train_dup = X_train + [probe]
|
|
363
|
+
y_train_dup = y_train + [y_train[0]]
|
|
364
|
+
tree2 = build(X_train_dup, y_train_dup, max_depth=5)
|
|
365
|
+
pred_follow = predict(probe, tree2)
|
|
366
|
+
ok = pred_source == pred_follow
|
|
367
|
+
return RelationResult(
|
|
368
|
+
"tree_duplicate_invariance", ok,
|
|
369
|
+
"duplicate point prediction unchanged" if ok else f"source={pred_source}, follow={pred_follow}"
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _tree_noise_feature_invariance(mod) -> RelationResult:
|
|
374
|
+
"""Adding a pure-noise feature should not change predictions."""
|
|
375
|
+
random.seed(63)
|
|
376
|
+
X_train, y_train = _make_binary_classification_data(63, n=70)
|
|
377
|
+
X_test, y_test = _make_binary_classification_data(64, n=30)
|
|
378
|
+
build = getattr(mod, "build_tree")
|
|
379
|
+
predict = getattr(mod, "predict_tree")
|
|
380
|
+
|
|
381
|
+
tree = build(X_train, y_train, max_depth=5)
|
|
382
|
+
source_preds = [predict(X_test[i], tree) for i in range(len(X_test))]
|
|
383
|
+
|
|
384
|
+
X_train_noise = [row + [random.gauss(0, 10.0)] for row in X_train]
|
|
385
|
+
X_test_noise = [row + [random.gauss(0, 10.0)] for row in X_test]
|
|
386
|
+
tree2 = build(X_train_noise, y_train, max_depth=5)
|
|
387
|
+
follow_preds = [predict(X_test_noise[i], tree2) for i in range(len(X_test_noise))]
|
|
388
|
+
ok = follow_preds == source_preds
|
|
389
|
+
return RelationResult(
|
|
390
|
+
"tree_noise_feature_invariance", ok,
|
|
391
|
+
"noise feature ignored" if ok else f"source[:5]={source_preds[:5]}, follow[:5]={follow_preds[:5]}"
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _make_tree_data(seed: int, n: int = 100, leak: float = 0.15):
|
|
396
|
+
"""Generate ID3-style data with a clean x0 boundary and optional leak."""
|
|
397
|
+
random.seed(seed)
|
|
398
|
+
X, y = [], []
|
|
399
|
+
for _ in range(n // 2):
|
|
400
|
+
x0 = random.uniform(0, 2.5) if random.random() < (1 - leak) else random.uniform(2.5, 5)
|
|
401
|
+
x1 = random.uniform(0, 5)
|
|
402
|
+
X.append([x0, x1])
|
|
403
|
+
y.append(0)
|
|
404
|
+
for _ in range(n // 2):
|
|
405
|
+
x0 = random.uniform(2.5, 5) if random.random() < (1 - leak) else random.uniform(0, 2.5)
|
|
406
|
+
x1 = random.uniform(0, 5)
|
|
407
|
+
X.append([x0, x1])
|
|
408
|
+
y.append(1)
|
|
409
|
+
indices = list(range(n))
|
|
410
|
+
random.shuffle(indices)
|
|
411
|
+
train_idx, test_idx = indices[: 70 * n // 100], indices[70 * n // 100 :]
|
|
412
|
+
X_train = [X[i] for i in train_idx]
|
|
413
|
+
y_train = [y[i] for i in train_idx]
|
|
414
|
+
X_test = [X[i] for i in test_idx]
|
|
415
|
+
y_test = [y[i] for i in test_idx]
|
|
416
|
+
return X_train, y_train, X_test, y_test
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _tree_clean_separable(mod) -> RelationResult:
|
|
420
|
+
"""Removing class overlap should let a correct tree separate classes perfectly."""
|
|
421
|
+
random.seed(72)
|
|
422
|
+
X_train_src, y_train_src, X_test_src, y_test_src = _make_tree_data(72, n=100, leak=0.15)
|
|
423
|
+
X_train_fol, y_train_fol, X_test_fol, y_test_fol = _make_tree_data(73, n=100, leak=0.0)
|
|
424
|
+
build = getattr(mod, "build_tree")
|
|
425
|
+
predict = getattr(mod, "predict_tree")
|
|
426
|
+
|
|
427
|
+
tree_src = build(X_train_src, y_train_src, max_depth=5)
|
|
428
|
+
src_acc = sum(
|
|
429
|
+
predict(X_test_src[i], tree_src) == y_test_src[i] for i in range(len(X_test_src))
|
|
430
|
+
) / len(X_test_src)
|
|
431
|
+
|
|
432
|
+
tree_fol = build(X_train_fol, y_train_fol, max_depth=5)
|
|
433
|
+
fol_acc = sum(
|
|
434
|
+
predict(X_test_fol[i], tree_fol) == y_test_fol[i] for i in range(len(X_test_fol))
|
|
435
|
+
) / len(X_test_fol)
|
|
436
|
+
|
|
437
|
+
ok = fol_acc >= 0.95 and fol_acc >= src_acc - 0.05
|
|
438
|
+
return RelationResult(
|
|
439
|
+
"tree_clean_separable", ok,
|
|
440
|
+
f"clean accuracy {fol_acc:.2f} (source {src_acc:.2f})" if ok
|
|
441
|
+
else f"expected >=0.95 after removing overlap, got {fol_acc:.2f} (source {src_acc:.2f})"
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _nb_label_permutation(mod) -> RelationResult:
|
|
446
|
+
"""Swapping class labels should swap predicted labels."""
|
|
447
|
+
random.seed(65)
|
|
448
|
+
spam = ["cheap", "free", "buy", "offer", "click"]
|
|
449
|
+
ham = ["meeting", "report", "data", "project", "deadline"]
|
|
450
|
+
texts, labels = [], []
|
|
451
|
+
for _ in range(20):
|
|
452
|
+
words = [random.choice(spam) for _ in range(random.randint(3, 5))]
|
|
453
|
+
texts.append(words)
|
|
454
|
+
labels.append(1)
|
|
455
|
+
for _ in range(20):
|
|
456
|
+
words = [random.choice(ham) for _ in range(random.randint(3, 5))]
|
|
457
|
+
texts.append(words)
|
|
458
|
+
labels.append(0)
|
|
459
|
+
|
|
460
|
+
train = getattr(mod, "naive_bayes_train")
|
|
461
|
+
predict = getattr(mod, "naive_bayes_predict")
|
|
462
|
+
|
|
463
|
+
priors, probs = train(texts, labels)
|
|
464
|
+
source_preds = [predict(texts[i], priors, probs) for i in range(len(texts))]
|
|
465
|
+
priors2, probs2 = train(texts, _swap_labels(labels))
|
|
466
|
+
follow_preds = [predict(texts[i], priors2, probs2) for i in range(len(texts))]
|
|
467
|
+
expected = _swap_labels(source_preds)
|
|
468
|
+
ok = follow_preds == expected
|
|
469
|
+
return RelationResult(
|
|
470
|
+
"nb_label_permutation", ok,
|
|
471
|
+
"label swap reflected in predictions" if ok else f"expected {_swap_labels(source_preds[:5])}, got {follow_preds[:5]}"
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _nb_duplicate_invariance(mod) -> RelationResult:
|
|
476
|
+
"""Duplicating a training document should not flip its prediction."""
|
|
477
|
+
random.seed(66)
|
|
478
|
+
spam = ["cheap", "free", "buy", "offer", "click"]
|
|
479
|
+
ham = ["meeting", "report", "data", "project", "deadline"]
|
|
480
|
+
texts, labels = [], []
|
|
481
|
+
for _ in range(20):
|
|
482
|
+
words = [random.choice(spam) for _ in range(random.randint(3, 5))]
|
|
483
|
+
texts.append(words)
|
|
484
|
+
labels.append(1)
|
|
485
|
+
for _ in range(20):
|
|
486
|
+
words = [random.choice(ham) for _ in range(random.randint(3, 5))]
|
|
487
|
+
texts.append(words)
|
|
488
|
+
labels.append(0)
|
|
489
|
+
|
|
490
|
+
train = getattr(mod, "naive_bayes_train")
|
|
491
|
+
predict = getattr(mod, "naive_bayes_predict")
|
|
492
|
+
|
|
493
|
+
probe = texts[0]
|
|
494
|
+
priors, probs = train(texts, labels)
|
|
495
|
+
pred_source = predict(probe, priors, probs)
|
|
496
|
+
|
|
497
|
+
texts_dup = texts + [probe]
|
|
498
|
+
labels_dup = labels + [labels[0]]
|
|
499
|
+
priors2, probs2 = train(texts_dup, labels_dup)
|
|
500
|
+
pred_follow = predict(probe, priors2, probs2)
|
|
501
|
+
ok = pred_source == pred_follow
|
|
502
|
+
return RelationResult(
|
|
503
|
+
"nb_duplicate_invariance", ok,
|
|
504
|
+
"duplicate document prediction unchanged" if ok else f"source={pred_source}, follow={pred_follow}"
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _nb_word_order_invariance(mod) -> RelationResult:
|
|
509
|
+
"""Shuffling word order in a document should not change Naive Bayes prediction."""
|
|
510
|
+
random.seed(67)
|
|
511
|
+
spam = ["cheap", "free", "buy", "offer", "click"]
|
|
512
|
+
ham = ["meeting", "report", "data", "project", "deadline"]
|
|
513
|
+
texts, labels = [], []
|
|
514
|
+
for _ in range(20):
|
|
515
|
+
words = [random.choice(spam) for _ in range(random.randint(3, 5))]
|
|
516
|
+
texts.append(words)
|
|
517
|
+
labels.append(1)
|
|
518
|
+
for _ in range(20):
|
|
519
|
+
words = [random.choice(ham) for _ in range(random.randint(3, 5))]
|
|
520
|
+
texts.append(words)
|
|
521
|
+
labels.append(0)
|
|
522
|
+
|
|
523
|
+
train = getattr(mod, "naive_bayes_train")
|
|
524
|
+
predict = getattr(mod, "naive_bayes_predict")
|
|
525
|
+
|
|
526
|
+
priors, probs = train(texts, labels)
|
|
527
|
+
probe = list(texts[0])
|
|
528
|
+
random.shuffle(probe)
|
|
529
|
+
pred_source = predict(texts[0], priors, probs)
|
|
530
|
+
pred_follow = predict(probe, priors, probs)
|
|
531
|
+
ok = pred_source == pred_follow
|
|
532
|
+
return RelationResult(
|
|
533
|
+
"nb_word_order_invariance", ok,
|
|
534
|
+
"word order does not change prediction" if ok else f"source={pred_source}, follow={pred_follow}"
|
|
535
|
+
)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _perceptron_label_permutation(mod) -> RelationResult:
|
|
539
|
+
"""Swapping class labels should swap predicted labels."""
|
|
540
|
+
X, y = _make_binary_classification_data(68)
|
|
541
|
+
fit = getattr(mod, "perceptron_fit")
|
|
542
|
+
predict = getattr(mod, "perceptron_predict")
|
|
543
|
+
|
|
544
|
+
w, b = fit(X, y, 1.0, 100)
|
|
545
|
+
source_preds = predict(X, w, b)
|
|
546
|
+
w2, b2 = fit(X, _swap_labels(y), 1.0, 100)
|
|
547
|
+
follow_preds = predict(X, w2, b2)
|
|
548
|
+
expected = _swap_labels(source_preds)
|
|
549
|
+
ok = follow_preds == expected
|
|
550
|
+
return RelationResult(
|
|
551
|
+
"perceptron_label_permutation", ok,
|
|
552
|
+
"label swap reflected in predictions" if ok else f"expected {_swap_labels(source_preds[:5])}, got {follow_preds[:5]}"
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _perceptron_duplicate_invariance(mod) -> RelationResult:
|
|
557
|
+
"""Duplicating a correctly-classified training point should not flip its prediction."""
|
|
558
|
+
random.seed(69)
|
|
559
|
+
X, y = _make_binary_classification_data(69, n=80, sep=1.2)
|
|
560
|
+
fit = getattr(mod, "perceptron_fit")
|
|
561
|
+
predict = getattr(mod, "perceptron_predict")
|
|
562
|
+
|
|
563
|
+
w, b = fit(X, y, 1.0, 100)
|
|
564
|
+
preds = predict(X, w, b)
|
|
565
|
+
# Pick a correctly-classified point to duplicate.
|
|
566
|
+
correct_idx = next((i for i in range(len(X)) if preds[i] == y[i]), 0)
|
|
567
|
+
probe = X[correct_idx]
|
|
568
|
+
probe_label = y[correct_idx]
|
|
569
|
+
pred_source = predict([probe], w, b)[0]
|
|
570
|
+
|
|
571
|
+
X_dup = X + [probe]
|
|
572
|
+
y_dup = y + [probe_label]
|
|
573
|
+
w2, b2 = fit(X_dup, y_dup, 1.0, 100)
|
|
574
|
+
pred_follow = predict([probe], w2, b2)[0]
|
|
575
|
+
ok = pred_source == pred_follow
|
|
576
|
+
return RelationResult(
|
|
577
|
+
"perceptron_duplicate_invariance", ok,
|
|
578
|
+
"duplicate point prediction unchanged" if ok else f"source={pred_source}, follow={pred_follow}"
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def _perceptron_feature_permutation(mod) -> RelationResult:
|
|
583
|
+
"""Permuting feature columns consistently preserves predictions."""
|
|
584
|
+
X, y = _make_binary_classification_data(70)
|
|
585
|
+
fit = getattr(mod, "perceptron_fit")
|
|
586
|
+
predict = getattr(mod, "perceptron_predict")
|
|
587
|
+
|
|
588
|
+
w, b = fit(X, y, 1.0, 100)
|
|
589
|
+
source_preds = predict(X, w, b)
|
|
590
|
+
|
|
591
|
+
perm = [1, 0]
|
|
592
|
+
X_perm = [[row[perm[j]] for j in range(len(row))] for row in X]
|
|
593
|
+
w2, b2 = fit(X_perm, y, 1.0, 100)
|
|
594
|
+
follow_preds = predict(X_perm, w2, b2)
|
|
595
|
+
ok = follow_preds == source_preds
|
|
596
|
+
return RelationResult(
|
|
597
|
+
"perceptron_feature_permutation", ok,
|
|
598
|
+
"feature permutation preserves predictions" if ok else f"source[:5]={source_preds[:5]}, follow[:5]={follow_preds[:5]}"
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
# ---------------------------------------------------------------------------
|
|
603
|
+
# Discriminating classification relations: catch sign-flip / directional bugs
|
|
604
|
+
# Structural relations (label swap, duplicate invariance, feature permutation)
|
|
605
|
+
# pass global sign flips; these deep-region relations force correct orientation.
|
|
606
|
+
# ---------------------------------------------------------------------------
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _logreg_deep_class_region(mod) -> RelationResult:
|
|
610
|
+
"""A correct logistic-regression classifier puts deep points in the right class."""
|
|
611
|
+
random.seed(80)
|
|
612
|
+
X, y = [], []
|
|
613
|
+
for _ in range(40):
|
|
614
|
+
X.append([random.gauss(-3.0, 0.6), random.gauss(0.0, 0.6)])
|
|
615
|
+
y.append(0)
|
|
616
|
+
X.append([random.gauss(3.0, 0.6), random.gauss(0.0, 0.6)])
|
|
617
|
+
y.append(1)
|
|
618
|
+
|
|
619
|
+
fit = getattr(mod, "logistic_regression_fit")
|
|
620
|
+
predict = getattr(mod, "logistic_regression_predict")
|
|
621
|
+
w, b = fit(X, y, 0.1, 200)
|
|
622
|
+
deep = [[-5.0, 0.0], [5.0, 0.0]]
|
|
623
|
+
preds = predict(deep, w, b)
|
|
624
|
+
ok = preds == [0, 1]
|
|
625
|
+
return RelationResult(
|
|
626
|
+
"logreg_deep_class_region", ok,
|
|
627
|
+
f"deep points predicted {preds}" if ok else f"expected [0, 1], got {preds}"
|
|
628
|
+
)
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def _knn_deep_class_region(mod) -> RelationResult:
|
|
632
|
+
"""A correct kNN puts deep points in the class of their nearest cluster."""
|
|
633
|
+
random.seed(82)
|
|
634
|
+
X_train, y_train = [], []
|
|
635
|
+
for _ in range(40):
|
|
636
|
+
X_train.append([random.gauss(-3.0, 0.6), random.gauss(0.0, 0.6)])
|
|
637
|
+
y_train.append(0)
|
|
638
|
+
X_train.append([random.gauss(3.0, 0.6), random.gauss(0.0, 0.6)])
|
|
639
|
+
y_train.append(1)
|
|
640
|
+
|
|
641
|
+
predict = getattr(mod, "knn_predict_batch")
|
|
642
|
+
deep = [[-5.0, 0.0], [5.0, 0.0]]
|
|
643
|
+
preds = predict(deep, X_train, y_train, k=5)
|
|
644
|
+
ok = preds == [0, 1]
|
|
645
|
+
return RelationResult(
|
|
646
|
+
"knn_deep_class_region", ok,
|
|
647
|
+
f"deep points predicted {preds}" if ok else f"expected [0, 1], got {preds}"
|
|
648
|
+
)
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _tree_deep_class_region(mod) -> RelationResult:
|
|
652
|
+
"""A correct decision tree puts deep points on the correct side of its split."""
|
|
653
|
+
random.seed(83)
|
|
654
|
+
X_train, y_train = [], []
|
|
655
|
+
for _ in range(40):
|
|
656
|
+
X_train.append([random.uniform(0.0, 2.5), random.uniform(0.0, 5.0)])
|
|
657
|
+
y_train.append(0)
|
|
658
|
+
X_train.append([random.uniform(2.5, 5.0), random.uniform(0.0, 5.0)])
|
|
659
|
+
y_train.append(1)
|
|
660
|
+
|
|
661
|
+
build = getattr(mod, "build_tree")
|
|
662
|
+
predict = getattr(mod, "predict_tree")
|
|
663
|
+
tree = build(X_train, y_train, max_depth=5)
|
|
664
|
+
deep = [[-1.0, 2.5], [6.0, 2.5]]
|
|
665
|
+
preds = [predict(p, tree) for p in deep]
|
|
666
|
+
ok = preds == [0, 1]
|
|
667
|
+
return RelationResult(
|
|
668
|
+
"tree_deep_class_region", ok,
|
|
669
|
+
f"deep points predicted {preds}" if ok else f"expected [0, 1], got {preds}"
|
|
670
|
+
)
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _nb_deep_class_region(mod) -> RelationResult:
|
|
674
|
+
"""A correct Naive Bayes classifier labels class-typical documents correctly."""
|
|
675
|
+
random.seed(84)
|
|
676
|
+
spam = ["cheap", "free", "buy", "offer", "click"]
|
|
677
|
+
ham = ["meeting", "report", "data", "project", "deadline"]
|
|
678
|
+
texts, labels = [], []
|
|
679
|
+
for _ in range(20):
|
|
680
|
+
texts.append([random.choice(spam) for _ in range(random.randint(3, 5))])
|
|
681
|
+
labels.append(1)
|
|
682
|
+
for _ in range(20):
|
|
683
|
+
texts.append([random.choice(ham) for _ in range(random.randint(3, 5))])
|
|
684
|
+
labels.append(0)
|
|
685
|
+
|
|
686
|
+
train = getattr(mod, "naive_bayes_train")
|
|
687
|
+
predict = getattr(mod, "naive_bayes_predict")
|
|
688
|
+
priors, probs = train(texts, labels)
|
|
689
|
+
pred_spam = predict(["cheap", "free", "buy", "offer", "click"], priors, probs)
|
|
690
|
+
pred_ham = predict(["meeting", "report", "data", "project", "deadline"], priors, probs)
|
|
691
|
+
ok = pred_spam == 1 and pred_ham == 0
|
|
692
|
+
return RelationResult(
|
|
693
|
+
"nb_deep_class_region", ok,
|
|
694
|
+
f"deep docs predicted spam={pred_spam}, ham={pred_ham}" if ok
|
|
695
|
+
else f"expected spam=1, ham=0; got spam={pred_spam}, ham={pred_ham}"
|
|
696
|
+
)
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _perceptron_deep_class_region(mod) -> RelationResult:
|
|
700
|
+
"""A correct perceptron puts deep points on the correct side of the boundary."""
|
|
701
|
+
random.seed(85)
|
|
702
|
+
X, y = [], []
|
|
703
|
+
for _ in range(40):
|
|
704
|
+
x1 = random.uniform(-3.0, 3.0)
|
|
705
|
+
x2 = x1 - random.uniform(1.2, 2.5)
|
|
706
|
+
X.append([x1, x2])
|
|
707
|
+
y.append(0)
|
|
708
|
+
x1 = random.uniform(-3.0, 3.0)
|
|
709
|
+
x2 = x1 + random.uniform(1.2, 2.5)
|
|
710
|
+
X.append([x1, x2])
|
|
711
|
+
y.append(1)
|
|
712
|
+
|
|
713
|
+
fit = getattr(mod, "perceptron_fit")
|
|
714
|
+
predict = getattr(mod, "perceptron_predict")
|
|
715
|
+
w, b = fit(X, y, 1.0, 200)
|
|
716
|
+
deep = [[0.0, -4.0], [0.0, 4.0]]
|
|
717
|
+
preds = predict(deep, w, b)
|
|
718
|
+
ok = preds == [0, 1]
|
|
719
|
+
return RelationResult(
|
|
720
|
+
"perceptron_deep_class_region", ok,
|
|
721
|
+
f"deep points predicted {preds}" if ok else f"expected [0, 1], got {preds}"
|
|
722
|
+
)
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
# ---------------------------------------------------------------------------
|
|
726
|
+
# Clustering relations
|
|
727
|
+
# ---------------------------------------------------------------------------
|
|
728
|
+
|
|
729
|
+
def _make_kmeans_data(seed: int, n_per_cluster: int = 20):
|
|
730
|
+
random.seed(seed)
|
|
731
|
+
X = []
|
|
732
|
+
for _ in range(n_per_cluster):
|
|
733
|
+
X.append([random.gauss(0, 0.5), random.gauss(0, 0.5)])
|
|
734
|
+
for _ in range(n_per_cluster):
|
|
735
|
+
X.append([random.gauss(5, 0.5), random.gauss(0, 0.5)])
|
|
736
|
+
for _ in range(n_per_cluster):
|
|
737
|
+
X.append([random.gauss(2.5, 0.5), random.gauss(4, 0.5)])
|
|
738
|
+
return X
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def _best_label_mapping(source_labels: List[int], follow_labels: List[int]) -> Dict[int, int]:
|
|
742
|
+
"""Find a source-label -> follow-label permutation that maximizes agreement."""
|
|
743
|
+
counts: Dict[Tuple[int, int], int] = {}
|
|
744
|
+
for s, f in zip(source_labels, follow_labels):
|
|
745
|
+
counts[(s, f)] = counts.get((s, f), 0) + 1
|
|
746
|
+
source_set = sorted(set(source_labels))
|
|
747
|
+
follow_set = sorted(set(follow_labels))
|
|
748
|
+
mapping: Dict[int, int] = {}
|
|
749
|
+
used: set = set()
|
|
750
|
+
for s in source_set:
|
|
751
|
+
best_f, best_count = None, -1
|
|
752
|
+
for f in follow_set:
|
|
753
|
+
if f in used:
|
|
754
|
+
continue
|
|
755
|
+
c = counts.get((s, f), 0)
|
|
756
|
+
if c > best_count:
|
|
757
|
+
best_f, best_count = f, c
|
|
758
|
+
if best_f is None:
|
|
759
|
+
best_f = follow_set[0]
|
|
760
|
+
mapping[s] = best_f
|
|
761
|
+
used.add(best_f)
|
|
762
|
+
return mapping
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def _kmeans_shift_invariance(mod) -> RelationResult:
|
|
766
|
+
"""Translating all points by a constant vector preserves cluster assignments."""
|
|
767
|
+
X = _make_kmeans_data(80)
|
|
768
|
+
fit = getattr(mod, "kmeans")
|
|
769
|
+
|
|
770
|
+
random.seed(80)
|
|
771
|
+
_, source_assignments = fit(X, k=3, max_iterations=100, tolerance=1e-4)
|
|
772
|
+
|
|
773
|
+
shift = [10.0, -7.0]
|
|
774
|
+
X_shifted = [[x[0] + shift[0], x[1] + shift[1]] for x in X]
|
|
775
|
+
random.seed(80)
|
|
776
|
+
_, follow_assignments = fit(X_shifted, k=3, max_iterations=100, tolerance=1e-4)
|
|
777
|
+
|
|
778
|
+
mapping = _best_label_mapping(source_assignments, follow_assignments)
|
|
779
|
+
remapped = [mapping[s] for s in source_assignments]
|
|
780
|
+
ok = remapped == follow_assignments
|
|
781
|
+
return RelationResult(
|
|
782
|
+
"kmeans_shift_invariance", ok,
|
|
783
|
+
"shifted assignments match" if ok else f"source[:10]={source_assignments[:10]}, follow[:10]={follow_assignments[:10]}"
|
|
784
|
+
)
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def _kmeans_scale_invariance(mod) -> RelationResult:
|
|
788
|
+
"""Uniformly scaling all features preserves cluster assignments."""
|
|
789
|
+
X = _make_kmeans_data(82)
|
|
790
|
+
fit = getattr(mod, "kmeans")
|
|
791
|
+
|
|
792
|
+
random.seed(82)
|
|
793
|
+
_, source_assignments = fit(X, k=3, max_iterations=100, tolerance=1e-4)
|
|
794
|
+
|
|
795
|
+
scale = 3.0
|
|
796
|
+
X_scaled = [[x[0] * scale, x[1] * scale] for x in X]
|
|
797
|
+
random.seed(82)
|
|
798
|
+
_, follow_assignments = fit(X_scaled, k=3, max_iterations=100, tolerance=1e-4)
|
|
799
|
+
|
|
800
|
+
mapping = _best_label_mapping(source_assignments, follow_assignments)
|
|
801
|
+
remapped = [mapping[s] for s in source_assignments]
|
|
802
|
+
ok = remapped == follow_assignments
|
|
803
|
+
return RelationResult(
|
|
804
|
+
"kmeans_scale_invariance", ok,
|
|
805
|
+
"scaled assignments match" if ok else f"source[:10]={source_assignments[:10]}, follow[:10]={follow_assignments[:10]}"
|
|
806
|
+
)
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def _kmeans_duplicate_invariance(mod) -> RelationResult:
|
|
810
|
+
"""Duplicating the full dataset should not change original-point assignments."""
|
|
811
|
+
X = _make_kmeans_data(81)
|
|
812
|
+
fit = getattr(mod, "kmeans")
|
|
813
|
+
|
|
814
|
+
random.seed(81)
|
|
815
|
+
_, source_assignments = fit(X, k=3, max_iterations=100, tolerance=1e-4)
|
|
816
|
+
|
|
817
|
+
X_dup = X + [[x[0], x[1]] for x in X]
|
|
818
|
+
random.seed(81)
|
|
819
|
+
_, follow_assignments_all = fit(X_dup, k=3, max_iterations=100, tolerance=1e-4)
|
|
820
|
+
follow_assignments = follow_assignments_all[: len(X)]
|
|
821
|
+
|
|
822
|
+
mapping = _best_label_mapping(source_assignments, follow_assignments)
|
|
823
|
+
remapped = [mapping.get(s, s) for s in source_assignments]
|
|
824
|
+
agreement = sum(r == f for r, f in zip(remapped, follow_assignments)) / len(X)
|
|
825
|
+
ok = agreement >= 0.95
|
|
826
|
+
return RelationResult(
|
|
827
|
+
"kmeans_duplicate_invariance", ok,
|
|
828
|
+
f"duplicate agreement {agreement:.2f}" if ok else f"expected >=0.95, got {agreement:.2f}"
|
|
829
|
+
)
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
# ---------------------------------------------------------------------------
|
|
833
|
+
# Optimization relations
|
|
834
|
+
# ---------------------------------------------------------------------------
|
|
835
|
+
|
|
836
|
+
def _gd_momentum_faster(mod) -> RelationResult:
|
|
837
|
+
"""Momentum GD should converge at least as fast as vanilla GD on the bowl."""
|
|
838
|
+
x0, y0 = 10.0, 10.0
|
|
839
|
+
vanilla = getattr(mod, "vanilla_gd")
|
|
840
|
+
momentum = getattr(mod, "momentum_gd")
|
|
841
|
+
|
|
842
|
+
iters_vanilla, fx_vanilla = vanilla(x0, y0)
|
|
843
|
+
iters_momentum, fx_momentum = momentum(x0, y0)
|
|
844
|
+
|
|
845
|
+
ok = fx_momentum < 1e-6 and fx_vanilla < 1e-6 and iters_momentum < iters_vanilla
|
|
846
|
+
return RelationResult(
|
|
847
|
+
"gd_momentum_faster", ok,
|
|
848
|
+
f"momentum {iters_momentum} iters vs vanilla {iters_vanilla}" if ok
|
|
849
|
+
else f"momentum iters={iters_momentum}, fx={fx_momentum}; vanilla iters={iters_vanilla}, fx={fx_vanilla}"
|
|
850
|
+
)
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
REGISTRY: Dict[str, List[Relation]] = {
|
|
854
|
+
"regression": [
|
|
855
|
+
Relation("linreg_scale_target", "regression", _linreg_scale_target),
|
|
856
|
+
Relation("linreg_shift_target", "regression", _linreg_shift_target),
|
|
857
|
+
Relation("linreg_feature_permutation", "regression", _linreg_feature_permutation),
|
|
858
|
+
Relation("poly_scale_target", "regression", _poly_scale_target),
|
|
859
|
+
Relation("poly_shift_target", "regression", _poly_shift_target),
|
|
860
|
+
Relation("ridge_scale_target", "regression", _ridge_scale_target),
|
|
861
|
+
Relation("ridge_ols_approx", "regression", _ridge_ols_approx),
|
|
862
|
+
],
|
|
863
|
+
"classification": [
|
|
864
|
+
Relation("logreg_label_permutation", "classification", _logreg_label_permutation),
|
|
865
|
+
Relation("logreg_duplicate_invariance", "classification", _logreg_duplicate_invariance),
|
|
866
|
+
Relation("logreg_feature_permutation", "classification", _logreg_feature_permutation),
|
|
867
|
+
Relation("logreg_deep_class_region", "classification", _logreg_deep_class_region),
|
|
868
|
+
Relation("knn_label_permutation", "classification", _knn_label_permutation),
|
|
869
|
+
Relation("knn_duplicate_invariance", "classification", _knn_duplicate_invariance),
|
|
870
|
+
Relation("knn_feature_permutation", "classification", _knn_feature_permutation),
|
|
871
|
+
Relation("knn_deep_class_region", "classification", _knn_deep_class_region),
|
|
872
|
+
Relation("tree_label_permutation", "classification", _tree_label_permutation),
|
|
873
|
+
Relation("tree_duplicate_invariance", "classification", _tree_duplicate_invariance),
|
|
874
|
+
Relation("tree_noise_feature_invariance", "classification", _tree_noise_feature_invariance),
|
|
875
|
+
Relation("tree_clean_separable", "classification", _tree_clean_separable),
|
|
876
|
+
Relation("tree_deep_class_region", "classification", _tree_deep_class_region),
|
|
877
|
+
Relation("nb_label_permutation", "classification", _nb_label_permutation),
|
|
878
|
+
Relation("nb_duplicate_invariance", "classification", _nb_duplicate_invariance),
|
|
879
|
+
Relation("nb_word_order_invariance", "classification", _nb_word_order_invariance),
|
|
880
|
+
Relation("nb_deep_class_region", "classification", _nb_deep_class_region),
|
|
881
|
+
Relation("perceptron_label_permutation", "classification", _perceptron_label_permutation),
|
|
882
|
+
Relation("perceptron_duplicate_invariance", "classification", _perceptron_duplicate_invariance),
|
|
883
|
+
Relation("perceptron_feature_permutation", "classification", _perceptron_feature_permutation),
|
|
884
|
+
Relation("perceptron_deep_class_region", "classification", _perceptron_deep_class_region),
|
|
885
|
+
],
|
|
886
|
+
"clustering": [
|
|
887
|
+
Relation("kmeans_shift_invariance", "clustering", _kmeans_shift_invariance),
|
|
888
|
+
Relation("kmeans_scale_invariance", "clustering", _kmeans_scale_invariance),
|
|
889
|
+
Relation("kmeans_duplicate_invariance", "clustering", _kmeans_duplicate_invariance),
|
|
890
|
+
],
|
|
891
|
+
"optimization": [
|
|
892
|
+
Relation("gd_momentum_faster", "optimization", _gd_momentum_faster),
|
|
893
|
+
],
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
# ---------------------------------------------------------------------------
|
|
898
|
+
# RELATION SOUNDNESS LAW
|
|
899
|
+
# ---------------------------------------------------------------------------
|
|
900
|
+
# A relation may only GATE (downgrade a property-primary PASS to FAIL) if the
|
|
901
|
+
# CANONICAL ORACLE ITSELF satisfies it across seed variation. A relation the
|
|
902
|
+
# oracle violates is a false-FAIL generator: it rejects correct code depending
|
|
903
|
+
# on nothing but the input data.
|
|
904
|
+
#
|
|
905
|
+
# The four below were measured violating their own oracle in a seed-offset
|
|
906
|
+
# sweep (tests/test_relation_soundness.py reproduces this). They still RUN and
|
|
907
|
+
# still REPORT -- they are informative -- but they must never fail a build.
|
|
908
|
+
#
|
|
909
|
+
# perceptron_label_permutation oracle failed 4/8 offsets (1,5,6,7)
|
|
910
|
+
# kmeans_duplicate_invariance oracle failed 2/8 offsets (2,6)
|
|
911
|
+
# tree_noise_feature_invariance oracle failed 2/8 offsets (4,6)
|
|
912
|
+
# tree_clean_separable oracle failed 1/8 offsets (2)
|
|
913
|
+
#
|
|
914
|
+
# Root cause for the two *_invariance cases: these transforms change the sample
|
|
915
|
+
# count, which changes index-sampled random initialisation, which lands the
|
|
916
|
+
# algorithm in a different (legitimately valid) local optimum.
|
|
917
|
+
ADVISORY_RELATIONS = frozenset({
|
|
918
|
+
"perceptron_label_permutation",
|
|
919
|
+
"kmeans_duplicate_invariance",
|
|
920
|
+
"tree_noise_feature_invariance",
|
|
921
|
+
"tree_clean_separable",
|
|
922
|
+
})
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
def is_gating(relation_name: str) -> bool:
|
|
926
|
+
"""True if this relation is allowed to turn a PASS into a FAIL."""
|
|
927
|
+
return relation_name not in ADVISORY_RELATIONS
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def _prefix_for_pattern(pattern: str) -> str:
|
|
931
|
+
mapping = {
|
|
932
|
+
"linear_regression_gd": "linreg_",
|
|
933
|
+
"polynomial_regression": "poly_",
|
|
934
|
+
"ridge_regression_normal_eq": "ridge_",
|
|
935
|
+
"logistic_regression": "logreg_",
|
|
936
|
+
"knn_classifier": "knn_",
|
|
937
|
+
"decision_tree_id3": "tree_",
|
|
938
|
+
"naive_bayes_text": "nb_",
|
|
939
|
+
"perceptron": "perceptron_",
|
|
940
|
+
"kmeans_clustering": "kmeans_",
|
|
941
|
+
"gradient_descent_momentum": "gd_",
|
|
942
|
+
}
|
|
943
|
+
return mapping.get(pattern, "")
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
def evaluate_relations(category: str, mod: Any, pattern: str = "") -> List[RelationResult]:
|
|
947
|
+
"""Run all relations for a category against a loaded user module.
|
|
948
|
+
|
|
949
|
+
If pattern is provided, skip relations whose name doesn't start with the
|
|
950
|
+
pattern prefix (e.g. 'linreg_' for linear_regression_gd). This avoids
|
|
951
|
+
requiring unrelated functions from alternative implementations.
|
|
952
|
+
"""
|
|
953
|
+
prefix = _prefix_for_pattern(pattern)
|
|
954
|
+
return [
|
|
955
|
+
rel.check(mod)
|
|
956
|
+
for rel in REGISTRY.get(category, [])
|
|
957
|
+
if not prefix or rel.name.startswith(prefix)
|
|
958
|
+
]
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
def registry() -> Dict[str, List[Relation]]:
|
|
962
|
+
return dict(REGISTRY)
|