| """Stage-3 hold-out skip pattern generator for the HareSkip experiment. |
| |
| Offline reproduction of the skip patterns the HareSkip extension would emit at |
| inference time, using the measured ERSDE-Beta trajectory (t_now per step) from |
| analysis-phase1-02/outputs/tables/master_long.csv. |
| |
| Two independent implementations are run and compared: |
| 1) SELF -- a from-scratch re-implementation of the extension logic in this |
| file (_self_generate), written from reading the source. |
| 2) EXT -- the actual extension modules imported read-only from |
| forge-neo-Anima-HareSkip (hareskip.skip_pattern). |
| If they disagree on any candidate, the script aborts. Nothing is written |
| outside this scratchpad directory; the extension repo and experiment data are |
| opened read-only. |
| |
| Usage: python simulate_patterns.py |
| """ |
|
|
| import csv |
| import hashlib |
| import math |
| import os |
| import random |
| import sys |
|
|
| |
|
|
| EXT_ROOT = r"S:\30_OriginalApps\16_HareSkip\forge-neo-Anima-HareSkip" |
| EXP_ROOT = r"S:\30_OriginalApps\16_HareSkip\experiment-HareSkip" |
| MASTER_LONG = os.path.join( |
| EXP_ROOT, "analysis-phase1-02", "outputs", "tables", "master_long.csv" |
| ) |
| STAGE2_PATTERNS = os.path.join( |
| EXP_ROOT, "patterns", "stage2-interaction-patterns.txt" |
| ) |
| STAGE1_PATTERNS = os.path.join( |
| EXP_ROOT, "patterns", "layer1-single-skip-sweep-30steps.txt" |
| ) |
| OUT_DIR = os.path.dirname(os.path.abspath(__file__)) |
|
|
| NUM_STEPS = 30 |
| IMAGE_SEEDS = [3000995193, 2455776111, 2767019676] |
| SKIP_WINDOW = (0.05, 0.95) |
| ZONE_BOUNDARIES = (-4.0, 0.0) |
| ZONE_MAX_STREAK = {"danger": 1, "middle": 2, "safe": 3} |
| MODEL = "sigmoid_band_v0.1" |
|
|
| |
|
|
| sys.path.insert(0, EXT_ROOT) |
| from hareskip import skip_pattern as ext_sp |
| from hareskip import probability_models as ext_pm |
|
|
|
|
| |
|
|
|
|
| def _sigmoid(x): |
| if x >= 0.0: |
| return 1.0 / (1.0 + math.exp(-x)) |
| e = math.exp(x) |
| return e / (1.0 + e) |
|
|
|
|
| def _clamp(x, lo, hi): |
| return max(lo, min(hi, x)) |
|
|
|
|
| def self_params(a): |
| a = _clamp(a, 0.0, 1.0) |
| return { |
| "p_cap": 0.40 + 0.40 * a, |
| "z_enter": -1.8 - 5.0 * (a ** 1.35), |
| "tau_enter": 0.55 + 0.35 * a, |
| "z_exit": 4.2 + 1.0 * a, |
| "tau_exit": 0.45, |
| } |
|
|
|
|
| def self_p(z, prm): |
| p = ( |
| prm["p_cap"] |
| * _sigmoid((z - prm["z_enter"]) / prm["tau_enter"]) |
| * _sigmoid((prm["z_exit"] - z) / prm["tau_exit"]) |
| ) |
| return _clamp(p, 0.0, 1.0) |
|
|
|
|
| def self_z(t_now, eps=1e-6): |
| t = max(eps, min(1.0 - eps, t_now)) |
| return 2.0 * math.log((1.0 - t) / t) |
|
|
|
|
| def self_zone(z, boundaries=ZONE_BOUNDARIES): |
| low, high = boundaries |
| if z < low: |
| return "danger" |
| if z < high: |
| return "middle" |
| return "safe" |
|
|
|
|
| def self_skip_seed(image_seed, offset): |
| digest = hashlib.sha256( |
| "{}|hareskip|{}".format(int(image_seed), int(offset)).encode("utf-8") |
| ).hexdigest() |
| return int(digest, 16) % (2 ** 63) |
|
|
|
|
| def self_apply_streak(skip, z_by_step, p_by_step, boundaries=ZONE_BOUNDARIES): |
| while True: |
| n = len(skip) |
| i = 0 |
| violated = None |
| while i < n: |
| if not skip[i]: |
| i += 1 |
| continue |
| j = i |
| while j < n and skip[j]: |
| j += 1 |
| allowed = min( |
| ZONE_MAX_STREAK[self_zone(z_by_step[k], boundaries)] |
| for k in range(i, j) |
| ) |
| if (j - i) > allowed: |
| violated = (i, j) |
| break |
| i = j |
| if violated is None: |
| return |
| start, end = violated |
| best = None |
| for k in range(start, end): |
| key = (p_by_step[k], z_by_step[k], k) |
| if best is None or key < best[0]: |
| best = (key, k) |
| skip[best[1]] = False |
|
|
|
|
| def self_generate(t_now_by_step, a, skip_seed, |
| skip_window=SKIP_WINDOW, boundaries=ZONE_BOUNDARIES): |
| """Independent reproduction of hareskip.generate_skip_pattern (no target).""" |
| n = len(t_now_by_step) |
| prm = self_params(a) |
| rng = random.Random(skip_seed) |
| ws, we = skip_window |
| z_by_step, p_by_step, skip = [], [], [] |
| for idx, t_now in enumerate(t_now_by_step): |
| progress = 0.0 if n <= 1 else idx / float(n - 1) |
| eligible = ws <= progress <= we |
| z = self_z(t_now) |
| p = self_p(z, prm) if eligible else 0.0 |
| z_by_step.append(z) |
| p_by_step.append(p) |
| |
| |
| |
| skip.append((rng.random() < p) if eligible else False) |
| self_apply_streak(skip, z_by_step, p_by_step, boundaries) |
| return skip, z_by_step, p_by_step, prm |
|
|
|
|
| |
|
|
|
|
| def load_trajectory(): |
| """Return (t_now_by_step[30], z_by_step[30], audit) from master_long.csv. |
| |
| master_long uses mapA: skip_step k <-> traj_step k-1, columns `z`/`tnow`. |
| skip_step 2..30 are present; step 1 (idx 0) has no measured t_now and is |
| extrapolated (log-linear in z) -- it is outside the skip window and |
| residual-less at inference, so it can never be skipped either way. |
| """ |
| by_step = {} |
| with open(MASTER_LONG, newline="", encoding="utf-8") as fh: |
| for r in csv.DictReader(fh): |
| if r["sampler"] != "ERSDE-Beta": |
| continue |
| k = int(float(r["skip_step"])) |
| rec = (float(r["tnow"]), float(r["z"]), float(r["traj_step"])) |
| by_step.setdefault(k, set()).add(rec) |
|
|
| audit = {} |
| conflicts = {k: v for k, v in by_step.items() if len(v) != 1} |
| audit["steps_present"] = sorted(by_step) |
| audit["conflicts"] = conflicts |
| assert not conflicts, "z/tnow differ across ERSDE-Beta conditions: %r" % conflicts |
| assert audit["steps_present"] == list(range(2, 31)) |
|
|
| t_now = [None] * NUM_STEPS |
| z_meas = [None] * NUM_STEPS |
| for k, v in by_step.items(): |
| tn, z, _ts = next(iter(v)) |
| |
| assert abs(ext_sp.logsnr_proxy_from_t_now(tn) - z) < 1e-9, k |
| assert abs(self_z(tn) - z) < 1e-9, k |
| t_now[k - 1] = tn |
| z_meas[k - 1] = z |
| |
| z1 = z_meas[1] - (z_meas[2] - z_meas[1]) |
| t_now[0] = 1.0 / (1.0 + math.exp(z1 / 2.0)) |
| z_meas[0] = self_z(t_now[0]) |
| audit["z1_extrapolated"] = z_meas[0] |
| return t_now, z_meas, audit |
|
|
|
|
| |
|
|
|
|
| def load_known(): |
| known = set() |
| with open(STAGE2_PATTERNS, encoding="utf-8") as fh: |
| for line in fh: |
| line = line.strip() |
| if line: |
| known.add(frozenset(int(x) for x in line.split(","))) |
| with open(STAGE1_PATTERNS, encoding="utf-8") as fh: |
| for line in fh: |
| line = line.strip() |
| if line: |
| known.add(frozenset(int(x) for x in line.split(","))) |
| return known |
|
|
|
|
| |
|
|
|
|
| def hamming(a, b): |
| """Hamming distance between two skip sets over the 30-step vector.""" |
| return len(set(a) ^ set(b)) |
|
|
|
|
| def max_streak(skip): |
| best = cur = 0 |
| for s in skip: |
| cur = cur + 1 if s else 0 |
| best = max(best, cur) |
| return best |
|
|
|
|
| def zone_breakdown(steps, z_by_step): |
| out = {"danger": 0, "middle": 0, "safe": 0} |
| for s in steps: |
| out[self_zone(z_by_step[s - 1])] += 1 |
| return out |
|
|
|
|
| def make_candidate(t_now, z_by_step, a, image_seed, offset, checks): |
| """Generate one candidate with SELF and cross-check against EXT.""" |
| seed = self_skip_seed(image_seed, offset) |
| assert seed == ext_sp.derive_skip_seed(image_seed, offset) |
|
|
| s_skip, s_z, s_p, s_prm = self_generate(t_now, a, seed) |
| e_pat = ext_sp.generate_skip_pattern( |
| t_now, aggressiveness=a, skip_seed=seed, |
| probability_model=MODEL, |
| skip_window=SKIP_WINDOW, zone_boundaries=ZONE_BOUNDARIES, |
| ) |
| |
| assert s_prm == e_pat.params, (s_prm, e_pat.params) |
| assert all(abs(x - y) < 1e-12 for x, y in zip(s_z, e_pat.z_by_step)) |
| assert all(abs(x - y) < 1e-12 for x, y in zip(s_p, e_pat.p_by_step)) |
| assert s_skip == e_pat.skip, (a, image_seed, offset) |
| checks["compared"] += 1 |
|
|
| steps = [i + 1 for i, s in enumerate(s_skip) if s] |
| assert steps == e_pat.skipped_steps |
| return { |
| "a": a, |
| "image_seed": image_seed, |
| "offset": offset, |
| "skip_seed": seed, |
| "steps": steps, |
| "count": len(steps), |
| "zones": zone_breakdown(steps, s_z), |
| "max_streak": max_streak(s_skip), |
| "expected": e_pat.expected_skips_before_streak, |
| "manual_added": [], |
| } |
|
|
|
|
| def select_for_level(a, t_now, z_by_step, known, chosen_so_far, checks, |
| n_want=3, max_offset=400): |
| """Pick n_want candidates at aggressiveness a satisfying the constraints.""" |
| picked = [] |
| for offset in range(0, max_offset): |
| for image_seed in IMAGE_SEEDS: |
| cand = make_candidate(t_now, z_by_step, a, image_seed, offset, checks) |
| steps = cand["steps"] |
| if len(steps) < 2: |
| continue |
| key = frozenset(steps) |
| if key in known: |
| continue |
| if any(key == frozenset(p["steps"]) for p in picked + chosen_so_far): |
| continue |
| if any(hamming(steps, p["steps"]) < 3 |
| for p in picked + chosen_so_far): |
| continue |
| picked.append(cand) |
| if len(picked) == n_want: |
| return picked |
| raise RuntimeError("could not find %d candidates at a=%s" % (n_want, a)) |
|
|
|
|
| |
|
|
|
|
| def main(): |
| t_now, z_meas, audit = load_trajectory() |
| known = load_known() |
|
|
| checks = {"compared": 0} |
| chosen = [] |
| for a in (0.3, 0.6, 0.9): |
| picked = select_for_level(a, t_now, z_meas, known, chosen, checks) |
| chosen.extend(picked) |
|
|
| |
| base = chosen[-1] |
| stress_steps = sorted(set(base["steps"]) | {3, 5}) |
| stress = dict(base) |
| stress["steps"] = stress_steps |
| stress["count"] = len(stress_steps) |
| stress["zones"] = zone_breakdown(stress_steps, z_meas) |
| sv = [False] * NUM_STEPS |
| for s in stress_steps: |
| sv[s - 1] = True |
| stress["max_streak"] = max_streak(sv) |
| stress["manual_added"] = [3, 5] |
| stress["label"] = "stress" |
| chosen.append(stress) |
|
|
| |
| problems = [] |
| if len(chosen) != 10: |
| problems.append("expected 10 patterns, got %d" % len(chosen)) |
| seen = set() |
| for i, p in enumerate(chosen): |
| st = p["steps"] |
| if st != sorted(st): |
| problems.append("pattern %d not sorted" % i) |
| if not all(2 <= s <= 30 for s in st): |
| problems.append("pattern %d out of range 2..30: %r" % (i, st)) |
| if 1 in st: |
| problems.append("pattern %d contains step 1" % i) |
| k = tuple(st) |
| if k in seen: |
| problems.append("duplicate pattern %d" % i) |
| seen.add(k) |
| if frozenset(st) in known: |
| problems.append("pattern %d collides with stage1/2" % i) |
| |
| for i in range(9): |
| for j in range(i + 1, 9): |
| d = hamming(chosen[i]["steps"], chosen[j]["steps"]) |
| if d < 3: |
| problems.append("hamming(%d,%d)=%d < 3" % (i, j, d)) |
|
|
| |
| txt = os.path.join(OUT_DIR, "stage3-holdout-patterns.txt") |
| with open(txt, "w", encoding="utf-8", newline="\n") as fh: |
| for p in chosen: |
| fh.write(", ".join(str(s) for s in p["steps"]) + "\n") |
|
|
| write_report(chosen, audit, checks, problems, z_meas, known) |
|
|
| print("cross-implementation comparisons: %d (all identical)" % checks["compared"]) |
| print("validation problems:", problems or "none") |
| for i, p in enumerate(chosen, 1): |
| print("%2d a=%.1f seed=%d off=%d n=%2d %s%s" % ( |
| i, p["a"], p["image_seed"], p["offset"], p["count"], |
| p["steps"], " (+manual 3,5)" if p["manual_added"] else "")) |
|
|
|
|
| def write_report(chosen, audit, checks, problems, z_meas, known): |
| lines = [] |
| A = lines.append |
| A("# Stage-3 hold-out skip patterns -- generation report") |
| A("") |
| A("Generated by `simulate_patterns.py` (this directory). Inputs are read-only:") |
| A("") |
| A("- Extension logic: `%s\\hareskip\\{skip_pattern,probability_models}.py`" % EXT_ROOT) |
| A("- Trajectory: `%s`" % MASTER_LONG) |
| A("- Exclusion sets: `%s`, `%s`" % (STAGE2_PATTERNS, STAGE1_PATTERNS)) |
| A("") |
| A("## Configuration") |
| A("") |
| A("| item | value |") |
| A("|---|---|") |
| A("| num_steps | %d |" % NUM_STEPS) |
| A("| probability model | `%s` |" % MODEL) |
| A("| skip_window | %s (extension default) |" % (SKIP_WINDOW,)) |
| A("| zone_boundaries | %s (extension default) |" % (ZONE_BOUNDARIES,)) |
| A("| zone max streak | danger 1 / middle 2 / safe 3 |") |
| A("| skip_seed | `sha256(f\"{image_seed}|hareskip|{offset}\")` mod 2**63 |") |
| A("| image seeds | %s |" % ", ".join(str(s) for s in IMAGE_SEEDS)) |
| A("") |
| A("## Verification") |
| A("") |
| A("Two independent implementations were compared on **every candidate drawn**") |
| A("(not just the 9 selected ones):") |
| A("") |
| A("1. `self_generate` in this script -- written from scratch by reading the") |
| A(" extension source (probability formula, window eligibility, z proxy,") |
| A(" zone/streak trimming with the `(p, z, index)` argmin flip rule, and the") |
| A(" RNG consumption order: `rng.random()` is drawn **only for eligible") |
| A(" steps**, because in `_draw_pattern` the call sits inside the") |
| A(" `if eligible` conditional expression).") |
| A("2. `hareskip.skip_pattern.generate_skip_pattern` imported directly from the") |
| A(" extension repo (`sys.path.insert`, read-only; nothing installed or") |
| A(" modified).") |
| A("") |
| A("Compared per candidate: `params`, `z_by_step`, `p_by_step`, the boolean") |
| A("`skip` vector and `skipped_steps`. Any mismatch aborts the script.") |
| A("") |
| A("- Candidates cross-checked: **%d** -- all identical." % checks["compared"]) |
| A("- `derive_skip_seed` also cross-checked per candidate (SHA-256, not `hash()`).") |
| A("- The extension's own suite `tests/test_skip_pattern.py` was run against the") |
| A(" same modules: **42 passed** (including the pinned literal") |
| A(" `derive_skip_seed(12345, 0) == 3695650839502921262`).") |
| A("") |
| A("Validation of the final 10 patterns: **%s**" % ( |
| "; ".join(problems) if problems else "no problems (all steps in 2..30, " |
| "no step 1, no duplicates, no collision with stage-1/2, pairwise " |
| "Hamming >= 3 among the 9 simulated)")) |
| A("") |
| A("## z(step) correspondence") |
| A("") |
| A("`master_long.csv` columns `z` / `tnow` follow **mapA**") |
| A("(`traj_step = skip_step - 1`), the default in analysis-phase1-02/REPORT.md.") |
| A("For the ERSDE-Beta sampler all **15 conditions carry identical `z`/`tnow`**") |
| A("for every `skip_step` 2..30 (verified: zero conflicting values).") |
| A("Each recorded `z` reproduces `logsnr_proxy_from_t_now(tnow)` to < 1e-9, so") |
| A("the measured `tnow` column is fed straight into the extension as") |
| A("`t_now_by_step`.") |
| A("") |
| A("Step 1 has no measured trajectory row (skip_step starts at 2); its z is") |
| A("extrapolated linearly backwards to z = %.4f. It is irrelevant to the" % audit["z1_extrapolated"]) |
| A("result: idx 0 has progress 0.0 < 0.05 so it is outside the skip window,") |
| A("and at inference the first call has no residual, so it is never skipped.") |
| A("") |
| A("| step | t_now | z | zone |") |
| A("|---:|---:|---:|---|") |
| for i in range(NUM_STEPS): |
| z = z_meas[i] |
| A("| %d%s | %.9f | %.5f | %s |" % ( |
| i + 1, " (extrap.)" if i == 0 else "", |
| 1.0 / (1.0 + math.exp(z / 2.0)), z, self_zone(z))) |
| A("") |
| A("## Patterns") |
| A("") |
| A("| # | a | image_seed | offset | skip_seed | n | skipped steps | danger | middle | safe | max streak | E[skips] |") |
| A("|---:|---:|---:|---:|---|---:|---|---:|---:|---:|---:|---:|") |
| for i, p in enumerate(chosen, 1): |
| note = " **(+manual 3, 5)**" if p["manual_added"] else "" |
| A("| %d | %.1f | %d | %d | %d | %d | %s%s | %d | %d | %d | %d | %.2f |" % ( |
| i, p["a"], p["image_seed"], p["offset"], p["skip_seed"], p["count"], |
| ", ".join(str(s) for s in p["steps"]), note, |
| p["zones"]["danger"], p["zones"]["middle"], p["zones"]["safe"], |
| p["max_streak"], p["expected"])) |
| A("") |
| A("Rows 1-3: a=0.3. Rows 4-6: a=0.6. Rows 7-9: a=0.9. Row 10: extreme-stress.") |
| A("") |
| A("### Row 10 (extreme stress)") |
| A("") |
| st = chosen[-1] |
| A("Row 10 is **not** a plain simulator output. It takes the realised a=0.9") |
| A("pattern of row 9 (image_seed %d, offset %d) and **manually adds steps 3") |
| A("and 5**. Those two steps sit in the danger band (z = %.2f and %.2f, both" % ( |
| z_meas[2], z_meas[4])) |
| A("z < -4), which the probability model almost never selects and where the") |
| A("danger-zone streak cap is 1 -- so this row is a deliberate out-of-sample") |
| A("probe of the prediction formula's limit, not a reachable extension output.") |
| A("Its max streak (%d) may therefore exceed what the extension would emit." % st["max_streak"]) |
| A("") |
| A("## Output grammar") |
| A("") |
| A("`stage3-holdout-patterns.txt` -- 10 lines, one pattern per line,") |
| A("comma-separated 1-based step numbers in ascending order; same grammar as") |
| A("`stage2-interaction-patterns.txt` and the stage-1 sweep file.") |
| A("") |
| with open(os.path.join(OUT_DIR, "generation_report.md"), "w", |
| encoding="utf-8", newline="\n") as fh: |
| fh.write("\n".join(lines)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|