File size: 23,852 Bytes
a64600b | 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 | """Independent-token null for the interaction of control and commitment timing.
This is an analytical/synthetic experiment, not a generative-model evaluation.
Every unforced token independently matches its reference with probability b;
there is no context dependence and no learned model. If the reference is copied
at commitment, E[match_i] = b + (1-b) * g(alpha, p_commit_i). Without that copy,
showing the reference as context has no effect on this independent predictor.
Run: python -m suite.null_commitment --output artifacts/method_v2_local/null
"""
from __future__ import annotations
import argparse
import csv
import json
import math
import time
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
ORDERS = ("target_first", "target_last", "random", "balanced")
SCHEDULES = ("duration", "amplitude")
def target_support(tokens: int, fraction: float = 0.25) -> np.ndarray:
if tokens < 8 or not 0 < fraction < 1:
raise ValueError("tokens >= 8 and 0 < target fraction < 1 are required")
count = max(1, min(tokens - 1, int(tokens * fraction)))
start = (tokens - count) // 2
mask = np.zeros(tokens, dtype=bool)
mask[start:start + count] = True
return mask
def fixed_order(mask: np.ndarray, name: str, order_seed: int = 5678) -> np.ndarray:
"""Fixed global priorities; balanced distributes target ranks uniformly."""
mask = np.asarray(mask, dtype=bool)
priority = np.random.default_rng(order_seed).random(len(mask))
ranked = np.argsort(priority, kind="stable")
target = ranked[mask[ranked]]
outside = ranked[~mask[ranked]]
if name == "target_first":
return np.concatenate((target, outside))
if name == "target_last":
return np.concatenate((outside, target))
if name == "random":
return ranked
if name != "balanced":
raise ValueError(f"Unknown order: {name}")
result = np.empty(len(mask), dtype=int)
ti = oi = 0
for rank in range(len(mask)):
# Exactly floor(k * target_fraction) target positions in the first k.
wanted = (rank + 1) * len(target) // len(mask)
if wanted > ti:
result[rank] = target[ti]
ti += 1
else:
result[rank] = outside[oi]
oi += 1
return result
def commitment_steps(permutation: np.ndarray, steps: int) -> np.ndarray:
"""Same cosine cumulative reveal and final-step completion as masked_decode."""
if steps < 2:
raise ValueError("steps >= 2 are required")
n = len(permutation)
if not np.array_equal(np.sort(permutation), np.arange(n)):
raise ValueError("permutation must contain each global position once")
committed = np.full(n, -1, dtype=int)
current = 0
for step in range(steps):
reveal = 1 - math.cos((step + 1) / steps * math.pi / 2)
wanted = n if step == steps - 1 else min(n, max(current, int(n * reveal)))
committed[permutation[current:wanted]] = step
current = wanted
return committed
def control_gate(alpha, progress, steps: int, schedule: str) -> np.ndarray:
a = np.asarray(alpha, dtype=float)
p = np.asarray(progress, dtype=float)
if np.any((a < 0) | (a > 1)):
raise ValueError("alpha must lie in [0, 1]")
if schedule == "duration":
return np.clip((a - p) * steps, 0, 1)
if schedule == "amplitude":
return a * np.clip((1 - p) * steps, 0, 1)
raise ValueError(f"Unknown schedule: {schedule}")
def exact_curve(alpha, commit: np.ndarray, mask: np.ndarray, steps: int,
baseline_match: float = 0.15, schedule: str = "duration",
reference_copy: bool = True) -> dict:
"""Integrates both independent token sampling and reference-copy uniforms."""
if not 0 < baseline_match < 1:
raise ValueError("baseline match probability must lie strictly in (0,1)")
a = np.atleast_1d(alpha).astype(float)
p = 1 - np.cos(np.asarray(commit) / steps * np.pi / 2)
gate = control_gate(a[:, None], p[None, :], steps, schedule)
gate[:, ~mask] = 0
if not reference_copy:
gate = np.zeros_like(gate)
match = baseline_match + (1 - baseline_match) * gate
return {
"target_match": match[:, mask].mean(axis=1),
"outside_match": match[:, ~mask].mean(axis=1),
"direct_copy_fraction_target": gate[:, mask].mean(axis=1),
"direct_copy_count_target": gate[:, mask].sum(axis=1),
"direct_copy_count_outside": gate[:, ~mask].sum(axis=1),
}
def response_statistics(alpha, response) -> dict:
a = np.asarray(alpha, dtype=float)
y = np.asarray(response, dtype=float)
gain = float(y[-1] - y[0])
result = {"endpoint_gain": gain, "alpha10": None, "alpha50": None,
"alpha90": None, "width80": None}
if gain <= 1e-12:
return result
z = np.maximum.accumulate((y - y[0]) / gain)
for q, name in ((0.1, "alpha10"), (0.5, "alpha50"), (0.9, "alpha90")):
result[name] = float(np.interp(q, z, a))
result["width80"] = result["alpha90"] - result["alpha10"]
return result
def oracle_remap(levels, commit: np.ndarray, mask: np.ndarray, steps: int,
baseline_match: float, schedule: str = "duration") -> dict:
"""Exact per-curve generalized inverse; illustration, NOT held-out calibration.
Continuous gates make every intermediate expectation reachable, even if the
original alpha response is narrow. Plateaus do not prevent this inversion.
This uses the same curve at evaluation time and provides no generalization
evidence, robustness guarantee, or statement about perceptual intermediate
states of an actual generator.
"""
q = np.asarray(levels, dtype=float)
low, high = np.zeros_like(q), np.ones_like(q)
for _ in range(60):
mid = (low + high) / 2
match = exact_curve(mid, commit, mask, steps, baseline_match, schedule)["target_match"]
normalized = (match - baseline_match) / (1 - baseline_match)
high = np.where(normalized >= q, mid, high)
low = np.where(normalized < q, mid, low)
alpha = (low + high) / 2
alpha[q == 0] = 0
achieved = exact_curve(alpha, commit, mask, steps, baseline_match, schedule)["target_match"]
achieved = (achieved - baseline_match) / (1 - baseline_match)
return {"requested_level": q, "remapped_alpha": alpha,
"achieved_level": achieved,
"max_absolute_error": float(np.max(np.abs(achieved - q))),
"caveat": "Oracle same-curve inversion only; not held-out calibration or learned-model evidence."}
def monte_carlo(alpha, commit: np.ndarray, mask: np.ndarray, steps: int,
baseline_match: float, schedule: str, seeds: int,
seed_start: int = 0, reference_copy: bool = True) -> dict:
"""Paired global-position noise across alpha/orders, independent across seeds."""
if seeds < 2:
raise ValueError("at least two independent Monte Carlo seeds are required")
a = np.asarray(alpha, dtype=float)
p = 1 - np.cos(commit / steps * np.pi / 2)
gates = control_gate(a[:, None], p[None, :], steps, schedule)
gates[:, ~mask] = 0
if not reference_copy:
gates = np.zeros_like(gates)
observations = np.empty((seeds, len(a)), dtype=float)
copy_observations = np.empty_like(observations)
outside_observations = np.empty(seeds, dtype=float)
outside_changed = 0
for si, seed in enumerate(range(seed_start, seed_start + seeds)):
# These streams are paired across configurations, not fitted to outcomes.
base_rng = np.random.default_rng(np.random.SeedSequence([seed, 0]))
ref_rng = np.random.default_rng(np.random.SeedSequence([seed, 1]))
global_uniforms = base_rng.random((steps, len(mask)))
baseline = global_uniforms[commit, np.arange(len(mask))] < baseline_match
copies = ref_rng.random(len(mask))[None, :] < gates
matches = baseline[None, :] | copies
observations[si] = matches[:, mask].mean(axis=1)
copy_observations[si] = copies[:, mask].mean(axis=1)
outside_observations[si] = baseline[~mask].mean()
outside_changed += int(np.count_nonzero(matches[:, ~mask] != baseline[None, ~mask]))
return {"target_match_mean": observations.mean(axis=0),
"target_match_seed_std": observations.std(axis=0, ddof=1),
"target_match_se": observations.std(axis=0, ddof=1) / np.sqrt(seeds),
"direct_copy_fraction_target_mean": copy_observations.mean(axis=0),
"outside_match_mean": float(outside_observations.mean()),
"outside_changed_token_observations": outside_changed}
def _jsonable(value):
if isinstance(value, dict):
return {k: _jsonable(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [_jsonable(v) for v in value]
if isinstance(value, np.ndarray):
return value.tolist()
if isinstance(value, np.generic):
return value.item()
return value
def _write_json(path: Path, data):
path.write_text(json.dumps(_jsonable(data), indent=2, ensure_ascii=False,
allow_nan=False), encoding="utf8")
def _write_csv(path: Path, rows: list[dict]):
with path.open("w", newline="", encoding="utf8") as handle:
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
def make_plots(output: Path, curves: list[dict], oracle: list[dict], config: dict) -> dict:
try:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
except ImportError as exc:
return {"status": "unavailable", "reason": str(exc)}
colors = {"target_first": "#d95f02", "target_last": "#1b9e77",
"random": "#7570b3", "balanced": "#1f78b4"}
styles = {"target_first": "-", "target_last": "--", "random": "-.", "balanced": ":"}
fig, axes = plt.subplots(2, 2, figsize=(11.2, 7.5))
for c in curves:
if not c["reference_copy"]:
continue
panel = 0 if c["schedule"] == "duration" else 1
ax = axes.flat[panel]
a = np.asarray(c["alpha"])
y = np.asarray(c["exact"]["target_match"])
mc = np.asarray(c["monte_carlo"]["target_match_mean"])
name = c["order"]
ax.plot(a, y, color=colors[name], ls=styles[name], lw=2.2, label=name.replace("_", " "))
ax.scatter(a[::8], mc[::8], color=colors[name], s=13, marker="o", alpha=0.65)
if panel == 0:
p = np.array(c["commitment"]["target_progress"])
axes[1, 0].plot(a, [(p <= x).mean() for x in a], color=colors[name],
ls=styles[name], lw=2, label=name.replace("_", " "))
axes[1, 1].plot(a, mc - y, color=colors[name], ls=styles[name], lw=1.5)
b = config["baseline_match"]
for ax in axes.flat[:2]:
ax.axhline(b, color="#555555", lw=1, ls=":", label="no direct copy (exact)")
ax.set(xlabel="Control parameter alpha", ylabel="Reference-match probability",
xlim=(0, 1), ylim=(max(0, b - .05), 1.025))
ax.grid(alpha=.15)
axes[0, 0].set_title("A. Alpha changes exposure duration")
axes[0, 1].set_title("B. Alpha changes amplitude: all orders coincide")
axes[0, 0].legend(fontsize=8, loc="lower right")
axes[0, 1].legend(fontsize=8, loc="lower right")
axes[1, 0].set(title="C. Target commitment-time distribution", xlabel="Cosine progress",
ylabel="Fraction of target already committed", xlim=(0, 1), ylim=(0, 1.025))
axes[1, 1].axhline(0, color="#555555", lw=1)
axes[1, 1].set(title=f"D. Duration: MC minus exact ({config['seeds']} seeds)",
xlabel="Control parameter alpha", ylabel="Match-probability error", xlim=(0, 1))
for ax in axes.flat[2:]:
ax.grid(alpha=.15)
fig.suptitle(f"Independent-token analytical null: no model coupling ({config['steps']} steps)", fontsize=13)
fig.text(.5, .012, "Lines: exact expectation. Dots: Monte Carlo. Synthetic diagnostic; no generated media or model performance.",
ha="center", fontsize=9)
fig.tight_layout(rect=(0, .035, 1, .955))
files = []
for ext in ("png", "pdf"):
name = f"independent_token_null.{ext}"
fig.savefig(output / name, dpi=190, bbox_inches="tight")
files.append(name)
plt.close(fig)
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.8))
for rec in oracle:
name = rec["order"]
axes[0].plot(rec["requested_level"], rec["remapped_alpha"], color=colors[name],
ls=styles[name], lw=2, label=name.replace("_", " "))
axes[1].plot(rec["requested_level"], rec["achieved_level"], color=colors[name],
ls=styles[name], lw=2)
axes[0].set(xlabel="Requested normalized response", ylabel="Oracle remapped alpha", title="A. Exact inverse of each duration curve")
axes[1].set(xlabel="Requested normalized response", ylabel="Achieved normalized response", title="B. Every intermediate expectation remains reachable")
axes[0].legend(fontsize=8)
for ax in axes:
ax.set(xlim=(0, 1), ylim=(0, 1))
ax.grid(alpha=.15)
fig.suptitle("Oracle illustration only: same-curve access, no held-out calibration evidence", fontsize=11)
fig.tight_layout(rect=(0, 0, 1, .94))
for ext in ("png", "pdf"):
name = f"oracle_remapping_illustration.{ext}"
fig.savefig(output / name, dpi=190, bbox_inches="tight")
files.append(name)
plt.close(fig)
return {"status": "complete", "matplotlib_version": matplotlib.__version__, "files": files}
def run(output: Path, steps: int = 18, tokens: int = 256, seeds: int = 256,
baseline_match: float = .15, order_seed: int = 5678, seed_start: int = 0,
plots: bool = True) -> dict:
start = time.perf_counter()
output = Path(output)
output.mkdir(parents=True, exist_ok=True)
mask = target_support(tokens)
config = {"experiment": "independent_token_analytical_null", "synthetic": True,
"learned_model_used": False, "steps": steps, "tokens": tokens, "seeds": seeds,
"seed_start": seed_start, "baseline_match": baseline_match, "order_seed": order_seed,
"target_fraction": float(mask.mean()), "target_indices": np.flatnonzero(mask),
"alpha_points": 65, "gap": 1 / steps, "orders": ORDERS, "schedules": SCHEDULES,
"reference_copy_conditions": [True, False], "numpy_version": np.__version__,
"started_at_utc": datetime.now(timezone.utc).isoformat(),
"expectation_over": "independent categorical-match noise and reference-copy uniforms",
"formula": "E[match_i]=b+(1-b)*g(alpha,p_commit_i) with direct copy; b otherwise",
"scope": "Fixed commitment orders; does not simulate adaptive confidence ordering or real-model quality."}
_write_json(output / "config.json", config)
alpha = np.linspace(0, 1, 65)
curves, curve_rows, commitment_rows, oracle_records, oracle_rows = [], [], [], [], []
for order in ORDERS:
commit = commitment_steps(fixed_order(mask, order, order_seed), steps)
progress = 1 - np.cos(commit / steps * np.pi / 2)
target_p = progress[mask]
commitment = {"target_progress_mean": float(target_p.mean()),
"target_progress_std": float(target_p.std()),
"target_progress_min": float(target_p.min()),
"target_progress_max": float(target_p.max()),
"target_progress": target_p, "target_commit_steps": commit[mask],
"newly_committed_per_step": np.bincount(commit, minlength=steps),
"target_committed_per_step": np.bincount(commit[mask], minlength=steps)}
for i in range(tokens):
commitment_rows.append({"order": order, "position": i, "target": int(mask[i]),
"commit_step": int(commit[i]), "commit_progress": float(progress[i])})
for schedule in SCHEDULES:
for copy in (True, False):
exact = exact_curve(alpha, commit, mask, steps, baseline_match, schedule, copy)
mc = monte_carlo(alpha, commit, mask, steps, baseline_match, schedule, seeds, seed_start, copy)
error = mc["target_match_mean"] - exact["target_match"]
se = mc["target_match_se"]
stats = response_statistics(alpha, exact["target_match"])
stats.update({"mc_max_absolute_error": float(np.abs(error).max()),
"mc_rmse": float(np.sqrt(np.mean(error ** 2))),
"mc_max_absolute_zscore": float(np.max(np.abs(error[se > 1e-12] / se[se > 1e-12]))) if np.any(se > 1e-12) else 0.,
"outside_unchanged": mc["outside_changed_token_observations"] == 0})
record = {"order": order, "schedule": schedule, "reference_copy": copy,
"alpha": alpha, "exact": exact, "monte_carlo": mc,
"statistics": stats, "commitment": commitment}
curves.append(record)
for j, a in enumerate(alpha):
curve_rows.append({"order": order, "schedule": schedule, "reference_copy": copy,
"alpha": float(a), "target_match_exact": float(exact["target_match"][j]),
"target_match_mc": float(mc["target_match_mean"][j]),
"target_match_mc_se": float(se[j]),
"target_match_mc_seed_std": float(mc["target_match_seed_std"][j]),
"direct_copy_fraction_target_exact": float(exact["direct_copy_fraction_target"][j]),
"direct_copy_count_target_exact": float(exact["direct_copy_count_target"][j]),
"direct_copy_fraction_target_mc": float(mc["direct_copy_fraction_target_mean"][j]),
"outside_match_exact": float(exact["outside_match"][j]),
"direct_copy_count_outside_exact": float(exact["direct_copy_count_outside"][j])})
oracle = oracle_remap(alpha, commit, mask, steps, baseline_match)
oracle["order"] = order
oracle_records.append(oracle)
for q, a, achieved in zip(oracle["requested_level"], oracle["remapped_alpha"], oracle["achieved_level"]):
oracle_rows.append({"order": order, "requested_level": float(q), "remapped_alpha": float(a),
"achieved_level": float(achieved), "oracle_same_curve_only": True})
_write_json(output / "curves.json", curves)
_write_csv(output / "curves.csv", curve_rows)
_write_csv(output / "commitments.csv", commitment_rows)
_write_json(output / "oracle_remapping.json", oracle_records)
_write_csv(output / "oracle_remapping.csv", oracle_rows)
plot_result = make_plots(output, curves, oracle_records, config) if plots else {"status": "disabled"}
summary = {"synthetic": True, "learned_model_used": False,
"conditions": len(curves), "alpha_points_per_condition": len(alpha),
"elapsed_seconds": time.perf_counter() - start, "device": "CPU (NumPy)",
"model_evaluations": 0, "monte_carlo_seeds_per_condition": seeds,
"max_mc_absolute_error": max(c["statistics"]["mc_max_absolute_error"] for c in curves),
"max_mc_absolute_zscore": max(c["statistics"]["mc_max_absolute_zscore"] for c in curves),
"outside_unchanged_all_conditions": all(c["statistics"]["outside_unchanged"] for c in curves),
"oracle_max_error": max(x["max_absolute_error"] for x in oracle_records),
"plots": plot_result,
"statistics": [{"order": c["order"], "schedule": c["schedule"],
"reference_copy": c["reference_copy"], **c["statistics"]} for c in curves],
"interpretation": [
"Narrow raw-alpha response can arise from direct reference copying and fixed commitment timing with zero context coupling.",
"This null does not quantify how much of any learned-model effect it explains.",
"Amplitude control is linear in expectation for all orders; context-only control is dormant in an independent predictor.",
"Oracle inversion illustrates reachable intermediate expectations, not held-out calibration or perceptual states."]}
_write_json(output / "summary.json", summary)
lines = ["# Independent-token analytical null", "", "This is a synthetic CPU diagnostic. No learned model or generated media is used.", "",
"Every unforced token independently matches its reference with probability b. Context has no effect.",
"With direct reference copying at commitment, E[match_i] = b + (1-b) g(alpha, p_commit_i).", "",
"The two schedules use the same cosine reveal budget and fixed orders. Duration changes the release time; amplitude changes the copy probability over a fixed window.", "",
"`curves.csv/json` contain all exact and independent-seed Monte Carlo results, including no-copy controls and direct-copy doses.",
"`commitments.csv` records every position's commitment time. `config.json` records reproducibility settings; `summary.json` records statistics and CPU wall time.", "",
"`oracle_remapping.*` use exact access to the evaluation curve. They only illustrate that a continuous compressed curve can be reparameterized; they are not evidence of held-out calibration.", "",
"Width is measured in the original alpha coordinate and does not establish missing perceptual intermediate states.", "",
f"Steps: {steps}. Tokens: {tokens}. Target tokens: {int(mask.sum())}. Independent seeds: {seeds}. b: {baseline_match}.",
f"Maximum Monte Carlo absolute error: {summary['max_mc_absolute_error']:.6f}. Outside support unchanged: {summary['outside_unchanged_all_conditions']}.", ""]
(output / "README.md").write_text("\n".join(lines), encoding="utf8")
return summary
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--steps", type=int, default=18)
parser.add_argument("--tokens", type=int, default=256)
parser.add_argument("--seeds", type=int, default=256)
parser.add_argument("--baseline-match", type=float, default=.15)
parser.add_argument("--order-seed", type=int, default=5678)
parser.add_argument("--seed-start", type=int, default=0)
parser.add_argument("--no-plots", action="store_true")
args = parser.parse_args()
summary = run(args.output, args.steps, args.tokens, args.seeds, args.baseline_match,
args.order_seed, args.seed_start, not args.no_plots)
for record in summary["statistics"]:
if record["reference_copy"]:
print(f"{record['schedule']:9s} {record['order']:12s} width80={record['width80']:.6f} alpha50={record['alpha50']:.6f} gain={record['endpoint_gain']:.6f}")
print(f"MC maximum absolute error: {summary['max_mc_absolute_error']:.6f}; max |z|: {summary['max_mc_absolute_zscore']:.3f}")
print(f"Outside unchanged: {summary['outside_unchanged_all_conditions']}; oracle error: {summary['oracle_max_error']:.3g}")
print(f"Saved {summary['conditions']} conditions to {args.output}; CPU wall time {summary['elapsed_seconds']:.2f}s")
if __name__ == "__main__":
main()
|