diff --git a/cascade/eval/lane_d_bench_sweep.py b/cascade/eval/lane_d_bench_sweep.py index 319032ef6..ed26a152e 100644 --- a/cascade/eval/lane_d_bench_sweep.py +++ b/cascade/eval/lane_d_bench_sweep.py @@ -25,6 +25,19 @@ :func:`cascade.eval.benchmarks.run_bench_reports`), each report parsed by :func:`~cascade.eval.benchmarks.item_rows_from_report`. +**Masked, canonical, the same for every entry (owner 2026-12-01: "it's meant +to mask NaN").** The materialised ``model.py`` / ``forecast_wrapper.py`` are +this release's own bytes (:func:`canonical_code`), never the entry's copies +(W4 already admits only those bytes; writing them from the release makes the +rule independent of when an entry was admitted). The pass runs under +:data:`~cascade.eval.benchmarks.BENCH_METHOD` passed EXPLICITLY (never the +host's ``$CASCADE_BENCH_METHOD``): the sidecar wraps the pyramid wrapper in +:class:`cascade.eval.pad_mask.ObservedMaskWrapper`, so NaN / inf and left +padding are filled with 0.0 and passed to the model as unobserved (scaler, +patch mask; fully padded patches never attention keys) on every suite, the +gate's and the king full bench's alike. A report stamped with another method +fails the sweep (``sweep_failed``, the gate holds): never a silent impute. + **Faults.** Infrastructure fails the whole sweep (:class:`LaneDBenchSweepError`, nothing swept; the box raises, the gate holds): a miss without a grant or a house source, a failed fetch or house build (or one that does not hash to its @@ -177,10 +190,20 @@ def _checked_settings(s) -> dict: return {k: s[k] for k in SETTINGS_KEYS} -def materialise(entry_dir, work_dir, *, digest: str, context: int) -> Path: - """``work_dir/-c``: the entry's sidecar files with - ``config.json``'s ``context_length`` set to ``context`` (rebuilt each - call; the entry is only read).""" +def canonical_code() -> dict[str, bytes]: + """The release's ``model.py`` / ``forecast_wrapper.py`` bytes (every lane + D entry's code, :func:`cascade.miner.lane_d.repo_code`).""" + from ..miner.lane_d import repo_code + + return repo_code() + + +def materialise(entry_dir, work_dir, *, digest: str, context: int, + code: Mapping[str, bytes] | None = None) -> Path: + """``work_dir/-c``: the entry's ``config.json`` (its + ``context_length`` set to ``context``) and ``weights.safetensors``, with + the release's code files (``code``, default :func:`canonical_code`) in + place of the entry's copies (rebuilt each call; the entry is only read).""" src, out = Path(entry_dir), Path(work_dir) / f"{digest}-c{int(context)}" if out.exists(): shutil.rmtree(out) @@ -191,16 +214,21 @@ def materialise(entry_dir, work_dir, *, digest: str, context: int) -> Path: cfg["context_length"] = int(context) (out / "config.json").write_text(json.dumps(cfg, sort_keys=True, indent=1), encoding="utf-8") + code = canonical_code() if code is None else code for name in SIDECAR_FILES[1:]: - shutil.copyfile(src / name, out / name) + if name in code: + (out / name).write_bytes(bytes(code[name])) + else: + shutil.copyfile(src / name, out / name) return out def _default_sidecar(device: str = "cuda") -> Callable: def run(dirs, suites, settings): - from .benchmarks import run_bench_reports + from .benchmarks import BENCH_METHOD, run_bench_reports return run_bench_reports(list(dirs), project_dir=_REPO / "benchmarks", + bench_method=BENCH_METHOD, suites=tuple(suites), device=device, num_samples=int(settings["num_samples"]), max_series=int(settings["max_series"]), @@ -321,9 +349,14 @@ def serve_sweep(request, *, cache, work_dir, contract=None, expect=None, reports = list(run([d for _, d in dirs], tuple(names[s] for s in suites), settings)) if len(reports) != len(dirs) or all(r is None for r in reports): raise LaneDBenchSweepError("sweep_failed", "the sidecar pass returned no report") - from .benchmarks import item_rows_from_report + from .benchmarks import BENCH_METHOD, item_rows_from_report for (dg, _), rep in zip(dirs, reports, strict=True): + stamp = rep.get("bench_method") if isinstance(rep, Mapping) else None + if stamp is not None and stamp != BENCH_METHOD: + raise LaneDBenchSweepError("sweep_failed", + f"{dg[:16]}: the sidecar ran {stamp!r}, not the " + f"masked {BENCH_METHOD!r}") got = item_rows_from_report(rep) rows[dg] = _error_rows(suites) if got is None else got agg = suite_aggregates(rep) @@ -389,4 +422,4 @@ def main(argv: list[str] | None = None) -> int: __all__ = ["REPLY_SCHEMA", "REQUEST_SCHEMA", "SWEEP_ERROR_CODES", "LaneDBenchSweepError", - "materialise", "probe_fingerprint", "serve_sweep", "suite_aggregates"] + "canonical_code", "materialise", "probe_fingerprint", "serve_sweep", "suite_aggregates"] diff --git a/cascade/eval/lane_d_public_cut.py b/cascade/eval/lane_d_public_cut.py index 2cee81317..f8494f0d6 100644 --- a/cascade/eval/lane_d_public_cut.py +++ b/cascade/eval/lane_d_public_cut.py @@ -53,7 +53,8 @@ # Bump when read_public_windows / build_window / keep_public change what a # cut window holds: old files then stop matching any key. -CUT_SCHEMA = "lane-d-public-cut/1" +# /2 (2026-12-01): a kept window's history is its whole masked history. +CUT_SCHEMA = "lane-d-public-cut/2" MAGIC = b"LANEDCUT\x01\n" SUFFIX = ".cut" DEFAULT_BUDGET_BYTES = 16 * 2**30 diff --git a/cascade/eval/lane_d_scorer.py b/cascade/eval/lane_d_scorer.py index 4685639d8..8a7ed2c93 100644 --- a/cascade/eval/lane_d_scorer.py +++ b/cascade/eval/lane_d_scorer.py @@ -23,6 +23,18 @@ input length, horizon, patch size and :data:`MAX_FORWARD_TOKENS`. The pinned wrapper's edge-pad is never used, so a 4k model and a declared-128k copy of it score identically on windows with ≤ 4096 history (T7). +* **Missing values are masked, never refused (owner 2026-12-01: "it's meant + to mask NaN").** A non-finite history point (NaN / ±inf) is filled with + :data:`~cascade.eval.pad_mask.FILL_VALUE` and marked UNOBSERVED in the + point mask the pyramid already takes for the horizon: the scaler + (``causal_standardize``) counts observed points only and the stem reads + ``values * (1 - mask)``. A patch whose points are more than half missing + is unobserved as a whole. It is the GluonTS observed-mask rule of the + public bench and the lane A / B scoring paths, one implementation + (:func:`cascade.eval.pad_mask.observed_context`, via + :func:`observed_rows`). An all-finite input is bit-identical to before (the + same mask). A window with no finite point in its model input is a + ``ValueError`` before anything loads, like a history shorter than a patch. * **Context is scorer-side.** The model is built from the checkpoint's own ``config.json`` with ``context_length`` set to the declared context; the weights fit any context (non-persistent positional buffers). @@ -334,6 +346,26 @@ def _load_model(checkpoint_dir: Path, context: int, device: str): return pm, cfg, model.to(device) +def observed_rows(rows, patch_size: int) -> tuple[np.ndarray, np.ndarray]: + """``(values, observed)`` of ``(B, L)`` / ``(B, C, L)`` histories (``L`` a + patch multiple, the model input): ``values`` float64 with every non-finite + point set to :data:`~cascade.eval.pad_mask.FILL_VALUE`, ``observed`` bool, + False on a non-finite point and on every point of a patch more than half + missing (:func:`cascade.eval.pad_mask.observed_context` per row; no + padding here, the input is real history). Numpy only. An all-finite input + gives its own values and an all-True mask.""" + from .pad_mask import observed_context + + a = np.asarray(rows, dtype=np.float64) + if a.ndim not in (2, 3): + raise ValueError(f"observed_rows takes (B, L) or (B, C, L), got {a.shape}") + flat = a.reshape(-1, a.shape[-1]) + if np.isfinite(flat).all(): + return a.copy(), np.ones(a.shape, dtype=bool) + values, observed, _ = observed_context(list(flat), int(a.shape[-1]), int(patch_size)) + return values.reshape(a.shape), observed.reshape(a.shape) + + def _forward(pm, cfg, model, rows: np.ndarray, horizon: int, device: str) -> np.ndarray: """``(B, L)`` univariate or ``(B, C, L)`` multichannel float64 histories (L a patch multiple) → ``(B, horizon, Q21)`` resp. ``(B, C, horizon, @@ -342,7 +374,9 @@ def _forward(pm, cfg, model, rows: np.ndarray, horizon: int, device: str) -> np. are one joint forecast (the model's variate axis); each channel is standardized on its own, as in training. ``(B, L)`` is exactly the ``C = 1`` case, so a univariate batch runs the same arithmetic as before - F2 (rev6.18 A4: bit-identical).""" + F2 (rev6.18 A4: bit-identical). Unobserved history points + (:func:`observed_rows`) are masked as the horizon is: in the scaler and + in the model's patch mask.""" import torch ps = int(cfg.patch_size) @@ -350,11 +384,12 @@ def _forward(pm, cfg, model, rows: np.ndarray, horizon: int, device: str) -> np. uni = rows.ndim == 2 b, c, length = (rows.shape[0], 1, rows.shape[1]) if uni else rows.shape count = (int(horizon) + ps - 1) // ps - context = torch.as_tensor(rows, dtype=torch.float64, device=device) - context = context[:, None] if uni else context + values, observed = observed_rows(rows, ps) + context = torch.as_tensor(values, dtype=torch.float64, device=device) + seen = torch.as_tensor(observed, dtype=torch.bool, device=device) + context, seen = (context[:, None], seen[:, None]) if uni else (context, seen) x = torch.cat([context, context.new_zeros(b, c, count * ps)], -1) - mask = torch.zeros_like(x, dtype=torch.bool) - mask[..., length:] = True + mask = torch.cat([~seen, seen.new_ones(b, c, count * ps)], -1) flat = x.reshape(b * c, -1) z, loc, scale = pm.causal_standardize(flat, mask.reshape_as(flat)) z = z.masked_fill(mask.reshape_as(flat), 0).float().reshape(b, c, -1, ps) @@ -404,8 +439,10 @@ def _as_window(hist, i: int) -> np.ndarray: row = a.reshape(-1) else: raise ValueError(f"window {i}: history shape {a.shape} is neither (L,) nor (C, L)") - if not np.isfinite(row).all(): - raise ValueError(f"window {i}: non-finite history") + # Missing points are masked (observed_rows), never refused; a window + # with nothing observed at all cannot be forecast. + if not np.isfinite(row).any(): + raise ValueError(f"window {i}: no finite history point") return row @@ -443,9 +480,10 @@ def forecast_quantiles(checkpoint_dir: str | os.PathLike, histories, *, context: window's model input is its last :func:`batch_plan` length points plus ``ceil(h/32)`` masked horizon patches, one batch per length, run in micro-batches of :func:`forward_batch_size` windows (``max_tokens`` - patch tokens per forward; #785). Raises - ``ValueError`` on a history shorter than one patch, a non-finite history - or a non-finite forecast.""" + patch tokens per forward; #785). A non-finite history point is masked + (:func:`observed_rows`). Raises ``ValueError`` on a history shorter than + one patch, a window with no finite point in its model input, or a + non-finite forecast.""" ctx = declared_context(context, SCORER_CONTEXTS if contexts is None else contexts) h = _checked_horizon(horizon) tokens = _as_int(max_tokens, "max_tokens") @@ -467,6 +505,12 @@ def forecast_quantiles(checkpoint_dir: str | os.PathLike, histories, *, context: members = [i for i, k in enumerate(n_ch) if k == c] sub = batch_plan([rows[i].shape[-1] for i in members], context=ctx, patch_size=ps) plans[c] = {length: [members[j] for j in idx] for length, idx in sub.items()} + for plan in plans.values(): + for length, idx in plan.items(): + for i in idx: + if not np.isfinite(rows[i][..., -length:]).any(): + raise ValueError(f"window {i}: no finite point in its last {length} " + f"history points") offsets = np.concatenate([[0], np.cumsum(n_ch)]).astype(np.int64) import torch @@ -546,4 +590,4 @@ def _score_multichannel(q: np.ndarray, target, history, seasonal_period: int __all__ = ["MAX_FORWARD_TOKENS", "MAX_HORIZON", "MEDIAN_INDEX", "SCORER_CONTEXTS", "SCORING_LEVELS", "SCORING_METHOD", "batch_plan", "declared_context", "forecast_quantiles", "forecast_rows", "forward_batch_size", "level_indices", - "score_window", "usable_length"] + "observed_rows", "score_window", "usable_length"] diff --git a/cascade/validator/lane_d_public.py b/cascade/validator/lane_d_public.py index a04a25e46..77865c374 100644 --- a/cascade/validator/lane_d_public.py +++ b/cascade/validator/lane_d_public.py @@ -56,6 +56,17 @@ (non-finite) target point is MASKED, never a reason to drop: the scorers average over the points that exist (:func:`~cascade.eval.crps.pinball_components`, :func:`~cascade.eval.mase.mase`). A short history is used at its own length. + +Owner 2026-12-01 ("it's meant to mask NaN"): a kept window's history is the +WHOLE history before the cut (at most :data:`PUBLIC_MAX_HISTORY` points, +leading columns with no finite value trimmed), its missing points left in as +NaN: the scorer fills them and passes them to the model as unobserved +(:func:`cascade.eval.lane_d_scorer.observed_rows`). The drop decisions below +are unchanged, byte for byte: they still read the finite suffix (so +``public.dropped``, and the judged set the checker re-derives from it, are +what they were), and the MASE scale is still the finite suffix's +(:func:`scale_history`). Only what the model receives inside a kept window +changed. A window is dropped only when it cannot be scored at all: its target has no finite point (``public_nonfinite_target``), its finite history suffix is shorter than one model patch (:data:`PUBLIC_MIN_FINITE_HISTORY` points, @@ -353,6 +364,21 @@ def _finite_suffix(hist: np.ndarray) -> int: return int(bad[-1]) + 1 if bad.size else 0 +def _first_observed(hist: np.ndarray) -> int: + """Index of the first column holding a finite value (in any channel).""" + seen = np.flatnonzero(np.isfinite(hist).any(axis=0)) + return int(seen[0]) if seen.size else int(hist.shape[1]) + + +def scale_history(history) -> np.ndarray: + """The finite suffix of a window history: what the MASE scale is + computed on (the pre-2026-12-01 window history, so MASE is unchanged).""" + h = np.asarray(history, dtype=np.float64) + h2 = h.reshape(1, -1) if h.ndim == 1 else h + out = h2[:, _finite_suffix(h2):] + return out[0] if h.ndim == 1 else out + + def build_window(series: np.ndarray, w: Mapping, *, block_hash: str | None, max_channels: int, min_history: int = PUBLIC_MIN_FINITE_HISTORY) -> tuple[dict | None, str | None]: """One drawn window from its ``(C, L)`` series: ``(window, None)`` or @@ -360,7 +386,11 @@ def build_window(series: np.ndarray, w: Mapping, *, block_hash: str | None, max_ Owner 2026-11-30: the target keeps its missing points (the scorers mask them) and the history is its finite suffix at whatever length it has, as - long as it holds ``min_history`` points (one model patch).""" + long as it holds ``min_history`` points (one model patch). + + Owner 2026-12-01: that rule still decides the drop, but a kept window + carries its whole history (NaN included, leading all-missing columns + trimmed); the scorer masks the missing points.""" a = np.asarray(series, dtype=np.float64) a = a.reshape(1, -1) if a.ndim == 1 else a cut, h = int(w["cut"]), int(w["h"]) @@ -392,9 +422,9 @@ def build_window(series: np.ndarray, w: Mapping, *, block_hash: str | None, max_ seen = np.isfinite(tgt) if not seen.any(): return None, "public_nonfinite_target" - hist = hist[:, _finite_suffix(hist):] - if hist.shape[1] < int(min_history): + if hist.shape[1] - _finite_suffix(hist) < int(min_history): return None, "public_short_history" + hist = hist[:, _first_observed(hist):] if not (np.where(seen, np.abs(tgt), 0.0).sum(axis=1) > 0).any(): return None, "public_no_scale" uni = hist.shape[0] == 1 @@ -501,7 +531,8 @@ def score_public_windows(windows: list[dict], forecasts: Mapping[str, Mapping]) if w["window_id"] not in fc: raise ValueError(f"{dg}: no forecast for public window {w['window_id']}") crps, mase = score_window(np.asarray(fc[w["window_id"]], dtype=np.float64), - w["target"], w["history"], int(w["seasonal_period"])) + w["target"], scale_history(w["history"]), + int(w["seasonal_period"])) per.setdefault(w["source"], []).append( {"window_id": w["window_id"], "family": w["family"], "crps": float(crps), "mase": float(mase)}) @@ -514,5 +545,5 @@ def score_public_windows(windows: list[dict], forecasts: Mapping[str, Mapping]) "PUBLIC_MIN_FINITE_HISTORY", "PUBLIC_MIN_HISTORY", "PUBLIC_SCHEMA", "PUBLIC_SEED_TAG", "PUBLIC_WINDOWS_PER_SOURCE", "build_window", "cell_of", "draw_public", "draw_series", "keep_public", "keep_quotas", "keep_record", - "pick_cut", "public_record", "public_seed", "read_public_windows", "series_band", - "score_public_windows", "seasonal_period", "series_slots"] + "pick_cut", "public_record", "public_seed", "read_public_windows", "scale_history", + "series_band", "score_public_windows", "seasonal_period", "series_slots"] diff --git a/docs/MINER_LANE_D.md b/docs/MINER_LANE_D.md index d3e181e4c..7534f78ba 100644 --- a/docs/MINER_LANE_D.md +++ b/docs/MINER_LANE_D.md @@ -230,6 +230,23 @@ blocks, about 24 h) of `submit`, or the entry expires (`ready_expired`). you are scored at, never padded: a window with 20,000 stored points gives a 32768 entry 20,000. A window that older pinned snapshots also hold keeps its 16384-point copy until those snapshots retire. +- **Missing values are masked (owner 2026-12-01).** A NaN or inf in a + window's history is never a refusal and is never cut away. The scorer + fills it with 0.0 and passes it to your model as unobserved, in the same + point mask the model already takes for the forecast horizon. The scaler + then counts observed points only, and a patch that is more than half + missing is unobserved as a whole (the GluonTS observed-mask rule of the + public bench). A public window keeps its whole history before the cut, + gaps included. Before this, it was cut to the points after its last gap. + Which windows are judged did not change, and neither did the MASE scale, + which still uses that finite suffix. The public bench suites (the gate's + rotating suites and the king's full bench) run every entry with the + release's own `forecast_wrapper.py` / `model.py` under the + `observed_mask/3` method. That method masks left padding and missing + values the same way, so the wrapper's own refusal of a non-finite history + is never reached. `cascade lane-d test` uses the same scorer. Private pool + histories have their gaps interpolated when the pool_d snapshot is built, + so they reach the model finite. - **The bar.** Your gain's LCB must clear the crown bar against the lane D king (KING_D). The house (the current lane A king) exists only for lane D's genesis (owner 2026-11-24, DEC-CA-0076). diff --git a/tests/accept/w3b6a/PATHS b/tests/accept/w3b6a/PATHS index 1362d9326..e3431b4ef 100644 --- a/tests/accept/w3b6a/PATHS +++ b/tests/accept/w3b6a/PATHS @@ -24,3 +24,8 @@ cascade/validator/eval_offload.py # .source.json names (HouseSidecarSource, wired in lane_d_inputs.py); the # bench host builds it as the eval host's house_source build step does (Hub # fetch + D47 cast) and admits it only when it hashes to the digest. +# Owner 2026-12-01 ("it's meant to mask NaN"): materialise writes the release's +# canonical model.py / forecast_wrapper.py (canonical_code), the sidecar pass +# pins --bench-method observed_mask/3 (pad_mask.ObservedMaskWrapper: NaN and +# left padding masked on every gate / full-bench suite), and a report of +# another method fails the sweep; test_w3b6a_masked_bench.py. diff --git a/tests/accept/w3b6a/test_w3b6a_masked_bench.py b/tests/accept/w3b6a/test_w3b6a_masked_bench.py new file mode 100644 index 000000000..8d5193487 --- /dev/null +++ b/tests/accept/w3b6a/test_w3b6a_masked_bench.py @@ -0,0 +1,83 @@ +"""W3b6a, owner 2026-12-01 ("it's meant to mask NaN"): every lane D bench +suite (the per-settlement gate sweep and the king's full bench) forecasts +through the masked wrapper, with the release's canonical code, for every +entry alike. + +* the materialised dir holds the release's ``model.py`` / + ``forecast_wrapper.py``, never the entry's copies; +* the sidecar pass is run with the masked bench method passed explicitly + (``observed_mask/3``: ``pad_mask.ObservedMaskWrapper``: NaN / inf and left + padding filled with 0.0 and unobserved), never the host's env default; +* a report stamped with another method fails the sweep (the gate holds). + +Torch-free: the sidecar is a stand-in; the canonical model's attention source +is checked by hash (the hook refuses an unknown one). +""" + +from __future__ import annotations + +import json + +import pytest + +from . import helpers as h + + +def test_materialise_writes_the_releases_code_not_the_entrys(tmp_path): + m = h.sweep_mod() + from cascade.miner.lane_d import repo_code + + src = tmp_path / "entry" + src.mkdir() + (src / "config.json").write_text(json.dumps({"context_length": 4096, "patch_size": 32})) + (src / "weights.safetensors").write_bytes(b"w" * 64) + (src / "forecast_wrapper.py").write_bytes(b"# an older wrapper that refuses NaN\n") + (src / "model.py").write_bytes(b"# an older model\n") + d = m.materialise(src, tmp_path / "work", digest="d" * 64, context=8192) + code = repo_code() + assert (d / "forecast_wrapper.py").read_bytes() == code["forecast_wrapper.py"], ( + "the bench must run the release's canonical wrapper for every entry") + assert (d / "model.py").read_bytes() == code["model.py"] + assert (d / "weights.safetensors").read_bytes() == b"w" * 64, "the entry's weights" + assert json.loads((d / "config.json").read_text())["context_length"] == 8192 + + +def test_the_sidecar_pass_is_pinned_to_the_masked_method(monkeypatch): + from cascade.eval import benchmarks, pad_mask + from cascade.miner.lane_d import repo_code + + m = h.sweep_mod() + seen = {} + + def fake(dirs, **kw): + seen.update(kw) + return [None for _ in dirs] + + monkeypatch.setattr(benchmarks, "run_bench_reports", fake) + monkeypatch.setenv("CASCADE_BENCH_METHOD", "impute/0") + run = m._default_sidecar("cpu") + run(["x"], ("gift-eval",), dict(h.SETTINGS)) + assert seen.get("bench_method") == benchmarks.BENCH_METHOD == "observed_mask/3", ( + "the lane D sweep passes the masked bench method explicitly") + assert benchmarks.bench_method_arg(seen["bench_method"]) == [ + "--bench-method", "observed_mask/3"], "so the host's env cannot pick impute/0" + sha = pad_mask.attention_source_sha256(repo_code()["model.py"].decode("utf-8")) + assert sha in pad_mask.KNOWN_ATTENTION_SHA256, ( + "the canonical model.py is one the leading-pad key hook knows") + + +def test_a_report_of_another_method_fails_the_sweep(tmp_path): + m = h.sweep_mod() + assert callable(getattr(m, "canonical_code", None)), ( + "the lane D sweep runs the release's canonical code and checks the bench method") + e = h.Entry(41) + cache = h.cache(tmp_path, e) + rep = dict(h.report_for(41), bench_method="impute/0") + with pytest.raises(m.LaneDBenchSweepError) as ei: + m.serve_sweep(h.request([e.digest]), cache=cache, work_dir=tmp_path / "work", + sidecar=h.Sidecar({e.digest: rep}), fingerprint=dict(h.FINGERPRINT)) + assert ei.value.code == "sweep_failed" + ok = dict(h.report_for(41), bench_method="observed_mask/3") + got = m.serve_sweep(h.request([e.digest]), cache=cache, work_dir=tmp_path / "work", + sidecar=h.Sidecar({e.digest: ok}), fingerprint=dict(h.FINGERPRINT)) + assert got["rows"][e.digest], "a masked report is used" diff --git a/tests/accept/w5d/PATHS b/tests/accept/w5d/PATHS index c438e559d..fef19d918 100644 --- a/tests/accept/w5d/PATHS +++ b/tests/accept/w5d/PATHS @@ -18,3 +18,9 @@ cascade/lane_d/ops_jobs.py # Lane D ops gaps PR: the T7 pod command (1000 and 5000 windows per variant; # writes the laned_t7/1 the evidence job installs). cascade/eval/lane_d_t7_pod.py +# Owner 2026-12-01 ("it's meant to mask NaN"): the scorer masks a non-finite +# history point (filled, unobserved in the scaler and the model's point mask: +# observed_rows, pad_mask.observed_context's rule) instead of refusing it; +# test_w5d_nan_mask.py. The miner guide's "Missing values are masked" bullet +# rides along. +docs/MINER_LANE_D.md diff --git a/tests/accept/w5d/test_w5d_nan_mask.py b/tests/accept/w5d/test_w5d_nan_mask.py new file mode 100644 index 000000000..2887e7970 --- /dev/null +++ b/tests/accept/w5d/test_w5d_nan_mask.py @@ -0,0 +1,217 @@ +"""Lane D masks missing history values (owner 2026-12-01: "it's meant to mask +NaN"; README "Missing values are masked"). + +The scorer (live and public judging, ``cascade lane-d test``, the T7 and +env-qual runs: every lane D forecast through +:func:`cascade.eval.lane_d_scorer.forecast_quantiles`) fills a non-finite +history point with 0.0 and passes it to the model as UNOBSERVED in the point +mask it already takes for the horizon (the scaler and the stem read it). The +torch-free tests pin the numpy mask construction and the pre-load rules; the +``torch`` ones (CI only, never on the box) pin that the mask reaches the +model call and that an all-finite input is unchanged. +""" + +from __future__ import annotations + +import sys + +import numpy as np +import pytest + +from .helpers import HORIZON, LAUNCH_CONTEXTS, PATCH, series + +torch_mark = pytest.mark.torch + + +@pytest.fixture +def no_torch(monkeypatch): + monkeypatch.setitem(sys.modules, "torch", None) + monkeypatch.setitem(sys.modules, "safetensors.torch", None) + + +def _observed_rows(): + import cascade.eval.lane_d_scorer as scorer + + fn = getattr(scorer, "observed_rows", None) + assert callable(fn), ("lane_d_scorer.observed_rows(rows, patch_size) builds the " + "(values, observed) pair the model call masks with") + return fn + + +def _config_dir(tmp_path): + d = tmp_path / "ckpt" + d.mkdir() + (d / "config.json").write_text(f'{{"moe": {{"patch_size": {PATCH}}}}}', encoding="utf-8") + return d + + +# ── torch-free: the mask construction ──────────────────────────────────────── + + +def test_a_nan_point_is_filled_and_unobserved(): + fn = _observed_rows() + row = series(4 * PATCH, seed=1) + row[5] = np.nan + row[70] = np.inf + values, observed = fn(row[None], PATCH) + assert values.shape == observed.shape == (1, 4 * PATCH) + assert np.isfinite(values).all(), "every non-finite point is filled" + assert values[0, 5] == 0.0 and values[0, 70] == 0.0, "the fill is the inert 0.0" + assert not observed[0, 5] and not observed[0, 70], "a missing point is unobserved" + assert observed[0].sum() == 4 * PATCH - 2, "scattered NaN stays per point" + keep = np.isfinite(row) + assert np.array_equal(values[0, keep], row[keep]), "observed values are untouched" + + +def test_a_mostly_missing_patch_is_unobserved_as_a_whole(): + fn = _observed_rows() + row = series(3 * PATCH, seed=2) + row[PATCH:PATCH + PATCH // 2 + 1] = np.nan # > half of patch 1 + values, observed = fn(row[None], PATCH) + assert not observed[0, PATCH:2 * PATCH].any(), "the patch's real points go too" + assert (values[0, PATCH:2 * PATCH] == 0.0).all() + assert observed[0, :PATCH].all() and observed[0, 2 * PATCH:].all() + + +def test_an_all_finite_input_is_its_own_values_and_fully_observed(): + fn = _observed_rows() + rows = np.stack([series(2 * PATCH, seed=s) for s in range(3)]) + values, observed = fn(rows, PATCH) + assert np.array_equal(values, rows) and observed.all() + multi = np.stack([rows, rows + 1.0]) # (B, C, L) + multi[1, 2, 7] = np.nan + values, observed = fn(multi, PATCH) + assert values.shape == observed.shape == multi.shape + assert not observed[1, 2, 7] and observed.sum() == multi.size - 1, "per channel" + + +def test_a_nan_history_is_masked_not_refused(no_torch, tmp_path): + """A NaN in a history no longer refuses the window: it gets past every + pre-load check and reaches the model load (``import torch`` is blocked + here, so the load is where it stops).""" + from cascade.eval.lane_d_scorer import forecast_quantiles + + h = series(4 * PATCH, seed=3) + h[10] = np.nan + d = _config_dir(tmp_path) + try: + forecast_quantiles(d, [h], context=4096, horizon=HORIZON, contexts=LAUNCH_CONTEXTS) + except ImportError: + pass # past the history checks + except ValueError as e: + raise AssertionError(f"a NaN history point was refused ({e}); it must be masked") from e + + +def test_a_history_with_nothing_observed_is_refused_before_loading(no_torch, tmp_path): + from cascade.eval.lane_d_scorer import forecast_quantiles + + d = _config_dir(tmp_path) + with pytest.raises(ValueError, match="no finite"): + forecast_quantiles(d, [np.full(4 * PATCH, np.nan)], context=4096, horizon=HORIZON) + tail = np.concatenate([series(PATCH, seed=4), np.full(4096, np.nan)]) + with pytest.raises(ValueError, match="no finite"): # nothing in the model input + forecast_quantiles(d, [tail], context=4096, horizon=HORIZON) + + +# ── torch (CI only): the mask reaches the model ────────────────────────────── + + +@pytest.fixture +def entry(tmp_path_factory): + import torch + + from .test_w5d_scorer import _checkpoints + + threads = torch.get_num_threads() + torch.set_num_threads(2) + try: + yield _checkpoints(str(tmp_path_factory.getbasetemp() / "w5d_ckpts"))["entry"] + finally: + torch.set_num_threads(threads) + + +@torch_mark +def test_the_observed_mask_reaches_the_model_call(entry, monkeypatch): + _observed_rows() # the seam exists (fails on base by assertion) + from cascade.eval.lane_d_scorer import forecast_quantiles + from cascade.trainer import pyramid_model as pm + + masks = [] + orig = pm.CascadeMoEModel.forward + + def spy(self, patches, mask=None, *a, **k): + masks.append(None if mask is None else mask.detach().clone()) + return orig(self, patches, mask, *a, **k) + + monkeypatch.setattr(pm.CascadeMoEModel, "forward", spy) + h = series(4 * PATCH, seed=5) + h[[3, 40]] = np.nan + q = forecast_quantiles(entry, [h], context=4096, horizon=HORIZON) + assert np.isfinite(q).all() + (mask,) = masks + flat = mask.reshape(-1) + assert bool(flat[3]) and bool(flat[40]), "the NaN points are masked in the model call" + assert int(flat[:4 * PATCH].sum()) == 2, "the observed points are not" + assert bool(flat[4 * PATCH:].all()), "the horizon stays masked" + + +@torch_mark +def test_an_all_finite_forecast_is_unchanged_and_the_fill_value_is_inert(entry): + _observed_rows() # the seam exists (fails on base by assertion) + from cascade.eval.lane_d_scorer import forecast_quantiles + + h = series(4 * PATCH, seed=6) + base = forecast_quantiles(entry, [h], context=4096, horizon=HORIZON) + again = forecast_quantiles(entry, [h.copy()], context=4096, horizon=HORIZON) + assert np.array_equal(base, again) + a, b = h.copy(), h.copy() + a[17], b[17] = np.nan, -np.inf + qa = forecast_quantiles(entry, [a], context=4096, horizon=HORIZON) + qb = forecast_quantiles(entry, [b], context=4096, horizon=HORIZON) + assert np.array_equal(qa, qb), "NaN and inf are the same unobserved point" + c = h.copy() + c[17] = 0.0 + assert not np.array_equal(qa, forecast_quantiles(entry, [c], context=4096, + horizon=HORIZON)), ( + "a masked point must not score like an observed 0.0") + + +@torch_mark +def test_the_scorer_masks_exactly_as_the_shared_observed_mask_wrapper(tmp_path_factory): + """One rule, not a new one: on a full-context history (nothing to pad) + with NaN, the scorer's forecast equals ``pad_mask.ObservedMaskWrapper`` + around the checkpoint's byte-pinned wrapper (the bench sidecar's + ``observed_mask/3`` path) at the nine scoring levels.""" + import importlib.util + import json + + import torch + + from cascade.eval.lane_d_scorer import SCORING_LEVELS, forecast_quantiles, level_indices + from cascade.eval.pad_mask import ObservedMaskWrapper + + from .test_w5d_scorer import _checkpoints + + house = _checkpoints(str(tmp_path_factory.getbasetemp() / "w5d_ckpts"))["house"] + ctx = int(json.loads((house / "config.json").read_text())["moe"]["context_length"]) + h = series(ctx, seed=7) + h[[11, 500, 501, ctx - 40]] = np.nan + h[64:64 + PATCH // 2 + 3] = np.nan # one mostly-missing patch + spec = importlib.util.spec_from_file_location("w5d_pinned_wrapper", + house / "forecast_wrapper.py") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + threads = torch.get_num_threads() + torch.set_num_threads(2) + try: + wrapped = ObservedMaskWrapper(mod.Wrapper(str(house)), pad_keys=True) + want = wrapped.forecast_quantiles_batch([h], HORIZON)[0] + try: + got = forecast_quantiles(house, [h], context=ctx, horizon=HORIZON)[0] + except ValueError as e: + raise AssertionError(f"the scorer refused a NaN history ({e})") from e + finally: + torch.set_num_threads(threads) + picks = level_indices(wrapped.quantile_levels, SCORING_LEVELS) + assert np.allclose(got, want[:, picks], rtol=1e-5, atol=1e-5), ( + "the lane D scorer's mask is the shared observed-mask rule") diff --git a/tests/accept/w5k/PATHS b/tests/accept/w5k/PATHS index 94a2f3aab..1b8fe9c07 100644 --- a/tests/accept/w5k/PATHS +++ b/tests/accept/w5k/PATHS @@ -7,3 +7,7 @@ cascade/validator/lane_d_public.py # report's `public` block (the same windows for KING_D, the house and every # challenger). cascade/validator/lane_d.py +# Owner 2026-12-01 ("it's meant to mask NaN"): a kept public window carries its +# whole history (NaN left for the scorer to mask) instead of its finite +# suffix; the drop decisions and the MASE scale (scale_history) still read the +# finite suffix, so public.dropped and the judged set are unchanged. diff --git a/tests/accept/w5k/test_w5k_draw.py b/tests/accept/w5k/test_w5k_draw.py index de6b3a541..87044103c 100644 --- a/tests/accept/w5k/test_w5k_draw.py +++ b/tests/accept/w5k/test_w5k_draw.py @@ -232,9 +232,11 @@ def build(a): assert why is None, "a target with a missing point is judged on the points it has" assert np.isnan(win["target"][10]) and np.isfinite(win["target"]).sum() == H - 1 a = good.copy() - a[150] = np.nan # finite suffix 49: used as it is + a[150] = np.nan # finite suffix 49: kept, masked win, why = build(a) - assert why is None and win["history"].shape == (49,), "a short history is used" + assert why is None, "a finite suffix of one patch or more keeps the window" + assert win["history"].shape == (200,) and np.isnan(win["history"][150]), ( + "owner 2026-12-01: the whole history reaches the model, the NaN masked") assert pub.PUBLIC_MIN_FINITE_HISTORY == 32, "the floor is one model patch" a = good.copy() a[180] = np.nan # finite suffix 19 < one patch @@ -336,3 +338,39 @@ def test_one_draw_serves_the_king_the_house_and_every_challenger(): # never a per-entry input: still one draw for every model. assert params == {"index_dir", "source", "boundary_block_hash", "horizon", "n_windows", "min_history", "bands", "max_horizon"} + + +def test_a_kept_window_carries_its_whole_masked_history_with_drops_unchanged(tmp_path): + """Owner 2026-12-01 ("it's meant to mask NaN"): a kept public window's + history is everything before the cut (leading all-missing columns + trimmed), its NaN left for the scorer to mask, instead of the finite + suffix. The drop decision still reads the finite suffix (``public.dropped`` + and the judged set the checker re-derives are unchanged) and so does the + MASE scale.""" + pub = _pub() + from cascade.eval.lane_d_scorer import score_window + + base = {"window_id": "gift_eval_pretrain:x/y#0:300:h64", "series_id": "x/y#0", + "family": "x", "freq": "H", "cut": 300, "h": H} + a = 50.0 + np.sin(np.arange(500) / 5.0) + a[:20] = np.nan # leading missing: trimmed + a[[100, 101, 160]] = np.nan # gaps: kept, masked + win, why = pub.build_window(a, base, block_hash=fx.BLOCK_HASH, max_channels=32) + assert why is None + assert win["history"].shape == (280,), "the whole history, not the 139-point suffix" + assert np.isfinite(win["history"][0]) and np.isnan(win["history"][[80, 81, 140]]).all() + assert np.array_equal(pub.scale_history(win["history"]), a[161:300]), ( + "the MASE scale is still the finite suffix") + q = _quantiles(win["target"] + 0.1, 0.5) + (row,) = pub.score_public_windows([win], {"m": {win["window_id"]: q}})["m"][GIFT] + want = score_window(q, win["target"], a[161:300], win["seasonal_period"]) + assert np.allclose((row["crps"], row["mase"]), want) and np.isfinite(row["mase"]) + a[290] = np.nan # suffix 9 < one patch: dropped as before + assert pub.build_window(a, base, block_hash=fx.BLOCK_HASH, + max_channels=32) == (None, "public_short_history") + m = np.vstack([50.0 + np.sin(np.arange(500) / 5.0), 60.0 + np.cos(np.arange(500) / 7.0)]) + m[1, 50] = np.nan + win, why = pub.build_window(m, {**base, "window_id": "rmisc:x/y#0:300:h64"}, + block_hash=fx.BLOCK_HASH, max_channels=32) + assert why is None and win["history"].shape == (2, 300) and np.isnan(win["history"][1, 50]) + assert pub.scale_history(win["history"]).shape == (2, 249) diff --git a/tests/accept/w8c/PATHS b/tests/accept/w8c/PATHS index d65db7d55..65fc9d7d0 100644 --- a/tests/accept/w8c/PATHS +++ b/tests/accept/w8c/PATHS @@ -29,3 +29,5 @@ docs/OPERATOR.md # live 2026-12-01 (public half cut once per settlement): the eval host's cut # public window cache, used by lane_d_forecasts public_scores_entry. cascade/eval/lane_d_public_cut.py +# Owner 2026-12-01: CUT_SCHEMA lane-d-public-cut/2 (a cut window now holds its +# whole masked history; a finite-suffix cut file is never served). diff --git a/tests/accept/w8c/test_w8c_public_cut.py b/tests/accept/w8c/test_w8c_public_cut.py index f83c35bbe..4ec7f582a 100644 --- a/tests/accept/w8c/test_w8c_public_cut.py +++ b/tests/accept/w8c/test_w8c_public_cut.py @@ -280,3 +280,21 @@ def test_the_public_command_caches_beside_the_mirrors_blob_cache(tmp_path): ["public", "--cache-dir", str(tmp_path), "--budget-bytes", "1", "--public-root", str(tmp_path), "--cut-cache-dir", str(tmp_path / "x")]) assert fc._cut_cache(args, None).root == tmp_path / "x" + + +def test_masked_histories_get_a_new_cut_schema_and_round_trip_with_their_nan(tmp_path): + """Owner 2026-12-01 ("it's meant to mask NaN"): a kept public window now + carries its whole history with its NaN (the scorer masks them), so a cut + file of the finite-suffix era must never be served: the schema moved.""" + cut = _cutmod() + assert cut.CUT_SCHEMA == "lane-d-public-cut/2", ( + "build_window changed what a cut window holds; CUT_SCHEMA must be bumped") + wins, drops = _source_windows("rmisc", 12, 7) + gappy = [w for w in wins if np.isnan(w["history"]).any()] + assert gappy, "a gappy history reaches the cut window (masked later, not cut away)" + cc = cut.CutCache(tmp_path) + assert cc.store("m" * 64, wins, {"rmisc": drops}) + got, _ = cc.load("m" * 64) + by_id = {w["window_id"]: w for w in got} + for w in gappy: + assert by_id[w["window_id"]]["history"].tobytes() == w["history"].tobytes()