Spaces:
Running
Running
File size: 14,389 Bytes
afb6251 | 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 | """Portable retrospective forecast challenge. No remote inference or customer data.
Prediction bytes establish submitted evidence, never authenticate a model identity.
The archived test has four six-month blocks: all rankings are descriptive.
"""
from functools import lru_cache
from io import BytesIO
from pathlib import Path
from zipfile import ZipFile, ZIP_DEFLATED
import csv
import hashlib
import json
import math
ROOT = Path(__file__).resolve().parent
VERSION = "electrocheap-challenge-v1"
SYSTEM = ("Forecast monthly aggregate electricity demand in GWh using only the supplied "
"history. Return JSON with predictions: an array of {id, forecast}. Preserve "
"every requested id. Use finite nonnegative numbers. Do not retrieve later "
"observations, use tools to find answers, or invent a model identity.")
ARCHIVE = ROOT / "evidence/full_model_benchmark"
MODELS = {
"seasonal_naive": "Seasonal naive · archived CPU baseline",
"fl_grokked_sarima__bias": "Grokked SARIMA + frozen bias · archived CPU",
"gpt_6_astra_delegated": "Astra · archived delegated diagnostic",
"gpt_6_1_sol_delegated": "Sol · archived delegated diagnostic",
"timesfm_2_5": "TimesFM 2.5 · archived inference",
"chronos_2": "Chronos-2 · archived inference",
}
def canonical(value):
return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
def digest(value):
return hashlib.sha256(canonical(value)).hexdigest()
def country_of(payload):
if not isinstance(payload, dict) or not isinstance(payload.get("country", "PT"), str) or payload.get("country", "PT") not in {"PT", "DE", "AU"}:
raise ValueError("Supply country PT, DE or AU.")
return payload.get("country", "PT")
def _id(country, origin, target):
return f"{country}:{origin[:7]}:{target[:7]}"
@lru_cache(maxsize=3)
def _data(country):
path = ROOT / f"data/{country.lower()}_monthly.csv"
with path.open() as f:
history = [{"timestamp": r["timestamp"][:10], "value": float(r["value"])}
for r in csv.DictReader(f)]
protocol = json.loads((ARCHIVE / "protocol.json").read_text())
with (ARCHIVE / "outputs/test_predictions_with_truth.csv").open() as f:
evidence = [r for r in csv.DictReader(f) if r["country"] == country.lower()]
return history, protocol, evidence, hashlib.sha256(path.read_bytes()).hexdigest()
def _tasks(country, split):
history, protocol, _, _ = _data(country)
tasks = []
for origin in protocol["origins"]:
if origin["split"] != split:
continue
end = origin["train_end"]
context = [r.copy() for r in history if r["timestamp"] <= end]
future = [r for r in history if r["timestamp"] > end][:origin["horizon"]]
targets = [{"id": _id(country, end, r["timestamp"]), "timestamp": r["timestamp"]}
for r in future]
tasks.append({"origin": end, "unit": "GWh", "history": context, "targets": targets})
return tasks
def challenge_packet(payload):
country = country_of(payload)
history, _, _, source_hash = _data(country)
tasks = _tasks(country, "test")
panel = {"protocol": VERSION, "country": country, "source_sha256": source_hash, "tasks": tasks}
examples = [{"id": t["id"], "forecast": next(r["value"] for r in task["history"]
if r["timestamp"][:7] == f"{int(t['timestamp'][:4])-1}{t['timestamp'][4:7]}")}
for task in tasks for t in task["targets"]]
return {**panel, "panel_sha256": digest(panel), "system_prompt": SYSTEM,
"status": "public_retrospective_challenge", "targets": len(examples),
"training_cutoff": "2022-09-01", "validation_window": "2022-10 through 2024-09",
"test_window": "2024-10 through 2026-09",
"response_template": {"country": country, "panel_sha256": digest(panel),
"model": {"id": "replace-with-actual-model", "revision": "record-exact-revision",
"adapter_revision": "none", "prompt_sha256": "record-actual-prompt-hash"},
"predictions": [{"id": r["id"], "forecast": None} for r in examples]},
"demo_submission": {"country": country, "panel_sha256": digest(panel),
"model": {"id": "seasonal_naive_demo", "revision": VERSION}, "predictions": examples},
"comparators": [{"id": k, "label": v} for k, v in MODELS.items()],
"limits": ["Public revised historical data, already exposed outcomes: no protected holdout.",
"Astra/Sol are archived delegated diagnostics, not new authenticated API calls.",
"Fine-tuning exports stop before validation; no training job is started.",
"No ranking proves superiority, household accuracy or bill savings.",
"Later origins include earlier observed test months as rolling context; do not train on these evaluation prompts."]}
def _number(value, name, nonnegative=False):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
raise ValueError(f"{name} must be a finite number.")
if abs(value) > 1e12:
raise ValueError(f"{name} exceeds the supported GWh range.")
if nonnegative and value < 0:
raise ValueError(f"{name} must be nonnegative.")
return float(value)
def _metrics(rows):
complete = [r for r in rows if r["forecast"] is not None]
n = len(rows)
if not complete:
return {"eligible": n, "completed": 0, "completion_rate": 0, "mae_gwh": None,
"rmse_gwh": None, "wape_pct": None, "mase": None, "bias_gwh": None}
errors = [r["forecast"]-r["actual"] for r in complete]
return {"eligible": n, "completed": len(complete), "completion_rate": len(complete)/n,
"mae_gwh": sum(abs(e) for e in errors)/len(complete),
"rmse_gwh": math.sqrt(sum(e*e for e in errors)/len(complete)),
"wape_pct": 100*sum(abs(e) for e in errors)/sum(r["actual"] for r in complete),
"mase": sum(abs(e)/r["mase_scale"] for e, r in zip(errors, complete))/len(complete),
"bias_gwh": sum(errors)/len(complete)}
def challenge_score(payload):
country = country_of(payload)
packet = challenge_packet({"country": country})
if payload.get("panel_sha256") != packet["panel_sha256"]:
raise ValueError("Panel hash mismatch. Download the current challenge packet first.")
model = payload.get("model")
if not isinstance(model, dict) or any(not isinstance(model.get(k), str) or
not model[k].strip() or len(model[k]) > 240 for k in ("id", "revision")):
raise ValueError("Record model.id and model.revision (strings, 1–240 characters).")
# Retain a small declared lineage object; never accept arbitrary files, URLs or credentials.
allowed = {"id", "revision", "adapter_revision", "prompt_sha256", "tools_sha256", "decoding_sha256"}
if set(model)-allowed or any(not isinstance(v, str) or len(v)>240 for v in model.values()):
raise ValueError("Model metadata permits only short identity, revision and hash fields.")
submitted = payload.get("predictions")
roster = {t["id"] for task in packet["tasks"] for t in task["targets"]}
if not isinstance(submitted, list) or len(submitted) != len(roster):
raise ValueError(f"Submit exactly {len(roster)} rows, including explicit failed outcomes.")
by_id = {}
for row in submitted:
if not isinstance(row, dict) or not isinstance(row.get("id"), str) or row["id"] not in roster or row["id"] in by_id:
raise ValueError("Prediction IDs must be unique and match every requested target exactly.")
outcome = row.get("status", "ok")
if not isinstance(outcome, str) or outcome not in {"ok", "timeout", "refusal", "schema_error", "error"}:
raise ValueError("Use status ok, timeout, refusal, schema_error or error.")
forecast = _number(row.get("forecast"), "forecast", True) if outcome == "ok" else None
if outcome != "ok" and row.get("forecast") is not None:
raise ValueError("Failed outcomes must not contain a forecast.")
by_id[row["id"]] = {"id": row["id"], "forecast": forecast, "status": outcome}
_, _, archive, _ = _data(country)
truth = {}
baselines = {key: [] for key in MODELS}
for r in archive:
rid = _id(country, r["train_end"], r["ds"])
if rid not in roster:
continue
truth[rid] = {"actual": float(r["y"]), "mase_scale": float(r["mase_scale"]),
"origin": r["train_end"], "horizon_step": int(r["horizon_step"])}
if r["model"] in baselines:
baselines[r["model"]].append({"id": rid, "forecast": float(r["yhat"]), **truth[rid]})
if set(truth) != roster or any(len(rows) != len(roster) or len({r['id'] for r in rows}) != len(roster) for rows in baselines.values()):
raise ValueError("Archived comparator coverage does not match the frozen target panel.")
paired = [{**by_id[rid], **truth[rid]} for rid in sorted(roster)]
score = _metrics(paired)
comparators = []
for key, rows in baselines.items():
summary = _metrics(rows)
comparators.append({"id": key, "label": MODELS[key], **summary,
"candidate_mae_gain_gwh": summary["mae_gwh"]-score["mae_gwh"] if score["completed"] == score["eligible"] else None})
slices = [{"origin": origin, **_metrics([r for r in paired if r["origin"] == origin])}
for origin in sorted({r["origin"] for r in paired})]
horizons = [{"horizon_step": h, **_metrics([r for r in paired if r["horizon_step"] == h])} for h in range(1, 7)]
return {"status": "complete" if score["completion_rate"] == 1 else "incomplete_predictions",
"protocol": VERSION, "country": country, "panel_sha256": packet["panel_sha256"],
"submission_sha256": digest({"model": model, "predictions": [by_id[k] for k in sorted(by_id)]}),
"archive_predictions_sha256": hashlib.sha256((ARCHIVE/"outputs/test_predictions_with_truth.csv").read_bytes()).hexdigest(),
"evaluator_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
"model": model, "model_identity_verified": False, "candidate": score,
"comparators": comparators, "origin_slices": slices, "horizon_slices": horizons,
"paired_predictions": paired, "promotion": "not_evaluated",
"superiority": "inconclusive: four dependent six-month origin blocks; no significance claim",
"metric_scope": "MAE/RMSE/WAPE/MASE condition on completed predictions; completion uses every requested target. Partial submissions cannot receive a comparative gain.",
"evidence_tier": "caller_submitted_predictions_against_public_retrospective_archive",
"limits": packet["limits"]}
def _messages(task, answers=None):
messages = [{"role": "system", "content": SYSTEM},
{"role": "user", "content": json.dumps(task, separators=(",", ":"))}]
if answers is not None:
messages.append({"role": "assistant", "content": json.dumps({"predictions": answers}, separators=(",", ":"))})
return {"messages": messages}
def challenge_export(country):
country = country_of({"country": country})
packet = challenge_packet({"country": country})
history, _, _, _ = _data(country)
train = []
# Non-overlapping six-month targets with a minimum three-year context.
# Every training target ends before 2022-10, the first validation target.
for i in range(36, len(history)-5, 6):
future = history[i:i+6]
if future[-1]["timestamp"] >= "2022-10-01":
break
origin = history[i-1]["timestamp"]
targets = [{"id": _id(country, origin, r["timestamp"]), "timestamp": r["timestamp"]} for r in future]
task = {"origin": origin, "unit": "GWh", "history": history[:i], "targets": targets}
answers = [{"id": t["id"], "forecast": r["value"]} for t, r in zip(targets, future)]
train.append(_messages(task, answers))
validation = []
truth = {r["timestamp"]: r["value"] for r in history}
for task in _tasks(country, "validation"):
validation.append(_messages(task, [{"id": t["id"], "forecast": truth[t["timestamp"]]} for t in task["targets"]]))
files = {"packet.json": json.dumps(packet, indent=2).encode(),
"submission-template.json": json.dumps(packet["response_template"], indent=2).encode(),
"seasonal-naive-demo.json": json.dumps(packet["demo_submission"], indent=2).encode()}
for name, items in [("train.jsonl", train), ("validation.jsonl", validation),
("test-prompts.jsonl", [_messages(t) for t in packet["tasks"]])]:
files[name] = ("\n".join(json.dumps(item, separators=(",", ":")) for item in items)+"\n").encode()
files["README.md"] = ("# Electrocheap portable challenge\n\n"
"1. Run each task in packet.json with your plugin, model or fine-tuned adapter.\n"
"2. Fill submission-template.json with every returned target and actual model lineage.\n"
"3. POST it to /api/challenge_score or use the LLM challenge tab.\n\n"
"train.jsonl uses measured targets before October 2022 only. validation.jsonl is separate "
"and may guide model selection. test-prompts.jsonl must not be used for training. "
"These are tiny public historical grid datasets, unsuitable for a protected holdout claim. "
"No provider training/inference job starts on download. The seasonal naive file is a "
"harness demo, not an Astra response. No original unavailable TSF source is reconstructed.\n").encode()
files["manifest.json"] = json.dumps({"protocol": VERSION, "country": country,
"panel_sha256": packet["panel_sha256"], "training_examples": len(train),
"validation_examples": len(validation), "test_examples": len(packet["tasks"]),
"training_target_end_exclusive": "2022-10-01",
"files_sha256": {name: hashlib.sha256(body).hexdigest() for name, body in files.items()}}, indent=2).encode()
out = BytesIO()
with ZipFile(out, "w", ZIP_DEFLATED) as z:
for name, body in files.items():
z.writestr(name, body)
return out.getvalue()
|