|
| 1 | +"""Online CPU forecast learner over independently settled, audited goal labels. |
| 2 | +
|
| 3 | +This shadow policy is separate from Gemma adapters and never places orders. |
| 4 | +Prequential scores use only outcomes available before each forecast commitment. |
| 5 | +""" |
| 6 | + |
| 7 | +import json |
| 8 | +import math |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +from rlm.v100.common import atomic_json |
| 12 | +from rlm.v100.goal_learning import database, digest, observation, records |
| 13 | +from rlm.v100.goals import load_goal |
| 14 | + |
| 15 | +FEATURES = ("bias", "last_change", "mean_change", "change_deviation", "history_count", "horizon") |
| 16 | + |
| 17 | + |
| 18 | +def vector(root: Path, target: dict, horizon: int, threshold: float) -> list[float]: |
| 19 | + if type(horizon) is not int or not 60 <= horizon <= 604800: |
| 20 | + raise ValueError("Use the goal forecast horizon budget") |
| 21 | + if type(threshold) not in (int, float) or not math.isfinite(threshold) or threshold <= 0: |
| 22 | + raise ValueError("Use a positive finite absolute threshold") |
| 23 | + with database(root) as db: |
| 24 | + # Evidence is host-observed and strictly no later than the target snapshot. |
| 25 | + rows = db.execute( |
| 26 | + "SELECT id, data FROM observations WHERE time<=? ORDER BY time DESC, id DESC", |
| 27 | + (target["acquired"],), |
| 28 | + ) |
| 29 | + history = [] |
| 30 | + for row in rows: |
| 31 | + candidate = json.loads(row["data"]) |
| 32 | + if (candidate["url"], candidate["field"]) == (target["url"], target["field"]): |
| 33 | + history.append(observation(root, row["id"])) |
| 34 | + if len(history) == 8: |
| 35 | + break |
| 36 | + history.sort(key=lambda row: row["acquired"]) |
| 37 | + changes = [ |
| 38 | + (later["value"] - earlier["value"]) / threshold |
| 39 | + for earlier, later in zip(history, history[1:], strict=False) |
| 40 | + if later["acquired"] > earlier["acquired"] |
| 41 | + ] |
| 42 | + mean = sum(changes) / len(changes) if changes else 0.0 |
| 43 | + deviation = math.sqrt(sum((x - mean) ** 2 for x in changes) / len(changes)) if changes else 0.0 |
| 44 | + values = [ |
| 45 | + 1.0, |
| 46 | + changes[-1] if changes else 0.0, |
| 47 | + mean, |
| 48 | + deviation, |
| 49 | + len(changes) / 7, |
| 50 | + math.log1p(horizon / 300), |
| 51 | + ] |
| 52 | + if any(not math.isfinite(value) for value in values): |
| 53 | + raise ValueError("Nonfinite causal forecast feature") |
| 54 | + return [max(-10.0, min(10.0, value)) for value in values] |
| 55 | + |
| 56 | + |
| 57 | +def probabilities(weights: list[list[float]], features: list[float]) -> list[float]: |
| 58 | + scores = [sum(w * x for w, x in zip(row, features, strict=True)) for row in weights] |
| 59 | + peak = max(scores) |
| 60 | + exponents = [math.exp(score - peak) for score in scores] |
| 61 | + total = sum(exponents) |
| 62 | + return [value / total for value in exponents] |
| 63 | + |
| 64 | + |
| 65 | +def update_weights(weights: list[list[float]], features: list[float], actual: int) -> None: |
| 66 | + predicted = probabilities(weights, features) |
| 67 | + for label, row in enumerate(weights): |
| 68 | + for index, value in enumerate(features): |
| 69 | + row[index] = max( |
| 70 | + -5.0, |
| 71 | + min( |
| 72 | + 5.0, |
| 73 | + row[index] |
| 74 | + + 0.03 * ((label == actual) - predicted[label]) * value |
| 75 | + - 0.0003 * row[index], |
| 76 | + ), |
| 77 | + ) |
| 78 | + |
| 79 | + |
| 80 | +def update(root: Path) -> dict: |
| 81 | + verified = records(root)[-512:] |
| 82 | + goal_id = (load_goal(root) or {}).get("id") |
| 83 | + identity = digest({"goal": goal_id, "records": verified, "features": FEATURES, "version": 1}) |
| 84 | + folder = root / "research/goal-policy" |
| 85 | + path = folder / "status.json" |
| 86 | + if path.exists(): |
| 87 | + prior = json.loads(path.read_text()) |
| 88 | + checksum = prior.pop("state_sha256") |
| 89 | + if digest(prior) != checksum: |
| 90 | + raise ValueError("Shadow policy artifact changed") |
| 91 | + if prior.get("data_sha256") == identity: |
| 92 | + return prior |
| 93 | + samples = [] |
| 94 | + with database(root) as db: |
| 95 | + for row in verified: |
| 96 | + forecast = json.loads( |
| 97 | + db.execute( |
| 98 | + "SELECT data FROM forecasts WHERE id=?", (row["verification"]["forecast_id"],) |
| 99 | + ).fetchone()[0] |
| 100 | + ) |
| 101 | + spec = forecast["specification"] |
| 102 | + outcome = json.loads( |
| 103 | + db.execute( |
| 104 | + "SELECT outcome FROM forecasts WHERE id=?", |
| 105 | + (row["verification"]["forecast_id"],), |
| 106 | + ).fetchone()[0] |
| 107 | + ) |
| 108 | + target = observation(root, spec["target"]) |
| 109 | + resolved = observation(root, outcome["observation"]) |
| 110 | + samples.append( |
| 111 | + { |
| 112 | + "commitment": digest( |
| 113 | + [spec["target"], spec["horizon_seconds"], spec["threshold"]] |
| 114 | + ), |
| 115 | + "created": forecast["created"], |
| 116 | + "resolved": resolved["acquired"], |
| 117 | + "features": vector(root, target, spec["horizon_seconds"], spec["threshold"]), |
| 118 | + "actual": ("down", "flat", "up").index(row["messages"][-1]["content"]), |
| 119 | + "id": row["verification"]["forecast_id"], |
| 120 | + } |
| 121 | + ) |
| 122 | + # Reference and shadow forecasts on the same target are one training label, |
| 123 | + # not two independent observations. Retain the first available resolution. |
| 124 | + unique = {} |
| 125 | + for sample in sorted(samples, key=lambda row: row["resolved"]): |
| 126 | + unique.setdefault(sample["commitment"], sample) |
| 127 | + samples = list(unique.values()) |
| 128 | + # Predict before applying labels that arrive later. Overlapping horizons cannot |
| 129 | + # leak their future labels into another earlier forecast's score. |
| 130 | + events = sorted( |
| 131 | + [(row["created"], 0, row["id"], row) for row in samples] |
| 132 | + + [(row["resolved"], 1, row["id"], row) for row in samples], |
| 133 | + key=lambda event: event[:3], |
| 134 | + ) |
| 135 | + weights = [[0.0] * len(FEATURES) for _ in range(3)] |
| 136 | + seen, scores, flat_scores, frequency_scores = 0, [], [], [] |
| 137 | + counts = [0, 0, 0] |
| 138 | + for _, kind, _, row in events: |
| 139 | + if kind == 0: |
| 140 | + if seen >= 8: |
| 141 | + prediction = probabilities(weights, row["features"]) |
| 142 | + scores.append( |
| 143 | + sum((p - (i == row["actual"])) ** 2 for i, p in enumerate(prediction)) |
| 144 | + ) |
| 145 | + flat_scores.append(0.0 if row["actual"] == 1 else 2.0) |
| 146 | + frequency = [(count + 1) / (seen + 3) for count in counts] |
| 147 | + frequency_scores.append( |
| 148 | + sum((p - (i == row["actual"])) ** 2 for i, p in enumerate(frequency)) |
| 149 | + ) |
| 150 | + else: |
| 151 | + update_weights(weights, row["features"], row["actual"]) |
| 152 | + counts[row["actual"]] += 1 |
| 153 | + seen += 1 |
| 154 | + result = { |
| 155 | + "schema": "synta-goal-policy-v1", |
| 156 | + "goal_id": goal_id, |
| 157 | + "data_sha256": identity, |
| 158 | + "features": list(FEATURES), |
| 159 | + "weights": weights, |
| 160 | + "trained_outcomes": seen, |
| 161 | + "weights_changed": bool(seen), |
| 162 | + "prequential_samples": len(scores), |
| 163 | + "prequential_brier": sum(scores) / len(scores) if scores else None, |
| 164 | + "uniform_baseline_brier": 2 / 3, |
| 165 | + "prequential_flat_baseline_brier": sum(flat_scores) / len(flat_scores) |
| 166 | + if flat_scores |
| 167 | + else None, |
| 168 | + "prequential_frequency_baseline_brier": sum(frequency_scores) / len(frequency_scores) |
| 169 | + if frequency_scores |
| 170 | + else None, |
| 171 | + "state": "shadow learning" if seen else "waiting for verified outcomes", |
| 172 | + "scope": "Online supervised CPU shadow policy; losses and failed forecasts included. This is not Gemma weight training, a trading signal or verified income. Prequential replay is exploratory; new shadow forecasts are prospective tests.", |
| 173 | + } |
| 174 | + atomic_json(path, {**result, "state_sha256": digest(result)}) |
| 175 | + return result |
| 176 | + |
| 177 | + |
| 178 | +def suggest(root: Path, target: str, horizon_seconds: int, threshold: float) -> dict: |
| 179 | + state = update(root) |
| 180 | + value = observation(root, target) |
| 181 | + if value["value"] is None: |
| 182 | + raise ValueError("Learned forecast needs a numeric target") |
| 183 | + return { |
| 184 | + "target": target, |
| 185 | + "probabilities": probabilities( |
| 186 | + state["weights"], vector(root, value, horizon_seconds, threshold) |
| 187 | + ), |
| 188 | + "trained_outcomes": state["trained_outcomes"], |
| 189 | + "policy_data_sha256": state["data_sha256"], |
| 190 | + "prequential_brier": state["prequential_brier"], |
| 191 | + "scope": state["scope"], |
| 192 | + } |
0 commit comments