Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 41 additions & 8 deletions cascade/eval/lane_d_bench_sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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/<digest>-c<context>``: 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/<digest>-c<context>``: 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)
Expand All @@ -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"]),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"]
3 changes: 2 additions & 1 deletion cascade/eval/lane_d_public_cut.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
66 changes: 55 additions & 11 deletions cascade/eval/lane_d_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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,
Expand All @@ -342,19 +374,22 @@ 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)
rows = np.asarray(rows)
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)
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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")
Expand All @@ -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
Expand Down Expand Up @@ -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"]
43 changes: 37 additions & 6 deletions cascade/validator/lane_d_public.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -353,14 +364,33 @@ 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
``(None, drop reason)``. Deterministic in (data, block hash).

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"])
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)})
Expand All @@ -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"]
17 changes: 17 additions & 0 deletions docs/MINER_LANE_D.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
5 changes: 5 additions & 0 deletions tests/accept/w3b6a/PATHS
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Loading
Loading