From ad8ab4946ffb303cc63751928beb607e7d7f6164 Mon Sep 17 00:00:00 2001 From: ramin_yz Date: Tue, 24 Nov 2026 12:48:00 +0100 Subject: [PATCH 1/2] Set the preload cache path in paths.yaml Use the configured directory directly. Document how to keep an existing scratch cache and let older saved configs still load. Refs #17 --- .gitignore | 1 + conf/paths.yaml | 3 +-- deep_lst/utils/io.py | 15 ++----------- docs/CONFIGURATION.md | 7 +++--- docs/RUNBOOK.md | 4 ++-- tests/test_io.py | 43 ++++++++++++------------------------ tests/test_training_paths.py | 1 - 7 files changed, 24 insertions(+), 50 deletions(-) diff --git a/.gitignore b/.gitignore index c779875..718d5f7 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,7 @@ wheels/ # experiments outputs/ /data/ +/cache/ *.ckpt .ipynb_checkpoints/ __pycache__/ diff --git a/conf/paths.yaml b/conf/paths.yaml index 8f1b31b..2e6878e 100644 --- a/conf/paths.yaml +++ b/conf/paths.yaml @@ -2,8 +2,7 @@ # Site paths shared by training, inference and asset generation. # Use a separate preload cache when changing the common store root. eozarr_root: /Net/Groups/BGI/work_5/scratch/WeatherGenerator/data/lowres_old -preload_cache_root: null -preload_cache_parent: /Net/Groups/BGI/tscratch +preload_cache_root: ./cache # Only list modalities whose stores live under a different root. store_roots: {} diff --git a/deep_lst/utils/io.py b/deep_lst/utils/io.py index ec3b20a..19327a7 100644 --- a/deep_lst/utils/io.py +++ b/deep_lst/utils/io.py @@ -1,5 +1,3 @@ -import getpass -import os import re from dataclasses import dataclass, field from functools import cache @@ -15,13 +13,6 @@ def _default_paths() -> dict: ) -def _preload_cache_root(settings: dict) -> Path: - root = settings["preload_cache_root"] or os.environ.get("DEEP_LST_CACHE_ROOT") - if root: - return Path(root) - return Path(settings["preload_cache_parent"]) / (os.environ.get("USER") or getpass.getuser()) / "tmp" - - @dataclass class ExperimentPaths: """Centralised path resolution for experiment artifacts.""" @@ -30,7 +21,7 @@ class ExperimentPaths: config_root: Path = field(default_factory=lambda: Path("./configs")) assets_root: Path = field(default_factory=lambda: Path("./assets")) eozarr_root: Path = field(default_factory=lambda: Path(_default_paths()["eozarr_root"])) - preload_cache_root: Path = field(default_factory=lambda: _preload_cache_root(_default_paths())) + preload_cache_root: Path = field(default_factory=lambda: Path(_default_paths()["preload_cache_root"])) store_roots: dict[str, str | None] = field( default_factory=lambda: dict(_default_paths()["store_roots"]), kw_only=True ) @@ -38,10 +29,8 @@ class ExperimentPaths: @classmethod def from_config(cls, config) -> "ExperimentPaths": settings = {**_default_paths(), **{key: value for key, value in (config or {}).items() if value is not None}} - cache_root = _preload_cache_root(settings) - settings.pop("preload_cache_parent") + settings.pop("preload_cache_parent", None) # old saved configs store_roots = dict(settings.pop("store_roots")) - settings["preload_cache_root"] = cache_root return cls(store_roots=store_roots, **{key: Path(value) for key, value in settings.items()}) def experiment_dir(self, experiment: str) -> Path: diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 9c4472b..8b80949 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -72,9 +72,10 @@ Here SEVIRI uses the separate directory and the other modalities use `eozarr_roo A null entry explicitly selects the common root. An older saved run can still provide `sources..store_root` if the current paths file has no entry for that modality. -If `preload_cache_root` is unset, the cache uses `DEEP_LST_CACHE_ROOT` when nonempty, -otherwise `//tmp`. The login name is used when `USER` is unset -or empty. Relative paths are resolved from the working directory. +Set `preload_cache_root` directly in `conf/paths.yaml` or override it on the command line. +The default is `./cache`. The previous per-user scratch directory and +`DEEP_LST_CACHE_ROOT` are no longer selected automatically. To keep using an existing +cache, set `preload_cache_root` to its directory. Relative paths start at the working directory. ``` uv run python deep_lst/train.py paths.eozarr_root=/data/eozarr paths.preload_cache_root=/scratch/deep_lst-cache diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index a3c4a3c..979a34f 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -109,8 +109,8 @@ assets/baselines//.nc persistence / climatology / ERA5(-Land Check these locations in a new clone: 1. Check `conf/paths.yaml` for the common store directory, any modality-specific directories - and the preload cache. The defaults keep the existing BGC store and scratch locations. - Set `preload_cache_root` explicitly or use `DEEP_LST_CACHE_ROOT` to choose another cache. + and the preload cache. The cache defaults to `./cache`. On the cluster, set + `preload_cache_root` to your scratch directory to keep using your existing cache. See `docs/CONFIGURATION.md` for precedence and examples. 2. The SLURM launchers under `scripts/` hard-code the path of the maintainer's clone, most of them as `WORKDIR=` near the top; replace it with the path of your clone. diff --git a/tests/test_io.py b/tests/test_io.py index 4443550..36103ee 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -34,35 +34,20 @@ def paths(tmp_path): ) -def test_cache_root_uses_environment_without_user(monkeypatch, tmp_path): - monkeypatch.setenv("DEEP_LST_CACHE_ROOT", str(tmp_path / "cache")) - monkeypatch.delenv("USER", raising=False) - assert ExperimentPaths().preload_cache_root == tmp_path / "cache" - - -@pytest.mark.parametrize("cache_root", [None, ""]) -def test_cache_root_defaults_to_current_user(monkeypatch, cache_root): - if cache_root is None: - monkeypatch.delenv("DEEP_LST_CACHE_ROOT", raising=False) - else: - monkeypatch.setenv("DEEP_LST_CACHE_ROOT", cache_root) - monkeypatch.setenv("USER", "test-user") - assert ExperimentPaths().preload_cache_root.as_posix() == "/Net/Groups/BGI/tscratch/test-user/tmp" - - -def test_cache_root_uses_account_name_when_user_is_unset(monkeypatch): - monkeypatch.delenv("DEEP_LST_CACHE_ROOT", raising=False) - monkeypatch.delenv("USER", raising=False) - monkeypatch.setattr("getpass.getuser", lambda: "test-user") - assert ExperimentPaths().preload_cache_root.as_posix() == "/Net/Groups/BGI/tscratch/test-user/tmp" - - -def test_explicit_cache_root_overrides_environment(monkeypatch, tmp_path): - monkeypatch.setenv("DEEP_LST_CACHE_ROOT", str(tmp_path / "environment-cache")) - assert ( - ExperimentPaths(preload_cache_root=tmp_path / "explicit-cache").preload_cache_root - == tmp_path / "explicit-cache" - ) +def test_cache_root_uses_the_configured_directory(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("DEEP_LST_CACHE_ROOT", str(tmp_path / "old-env-cache")) + with initialize_config_dir(config_dir=str(CONF_DIR), version_base="1.3"): + cfg = compose(config_name="train", overrides=["paths.preload_cache_root=chosen-cache"]) + assert ExperimentPaths().preload_cache_root == Path("cache") + paths = ExperimentPaths.from_config(cfg.paths) + assert paths.preload_cache_path("fingerprint").resolve() == tmp_path / "chosen-cache/preload_fingerprint.pt" + assert not (tmp_path / "old-env-cache").exists() + + +def test_legacy_cache_parent_uses_the_yaml_default(): + paths = ExperimentPaths.from_config({"preload_cache_root": None, "preload_cache_parent": "/old/scratch"}) + assert paths.preload_cache_root == Path("cache") @pytest.mark.parametrize("root_kind", ["default", "string", "path", "relative"]) diff --git a/tests/test_training_paths.py b/tests/test_training_paths.py index d795a6f..f8e63d2 100644 --- a/tests/test_training_paths.py +++ b/tests/test_training_paths.py @@ -33,7 +33,6 @@ def test_training_passes_paths_to_data_module_and_saves_overrides(tmp_path, monk config_name="train", overrides=["wandb_logger=false", *[f"paths.{k}={v}" for k, v in overrides.items()]] ) monkeypatch.chdir(tmp_path) - monkeypatch.setenv("DEEP_LST_CACHE_ROOT", str(tmp_path / "environment-cache")) choices = dict(model="mlp", objective="rollout", loss="smoothl1", horizon="h24", data="full") monkeypatch.setattr(train.HydraConfig, "get", lambda: SimpleNamespace(runtime=SimpleNamespace(choices=choices))) monkeypatch.setattr(train, "check_stats_transform", lambda *args: None) From 56641688dd68a7c7a451878d40b19cc1ad2d508f Mon Sep 17 00:00:00 2001 From: ramin_yz Date: Tue, 24 Nov 2026 12:48:48 +0100 Subject: [PATCH 2/2] Pass paths to the dataset and store readers Use the paths supplied by the caller, with defaults at the call site. Use the same paths for the indices and store in full-store reads. Refs #17 --- deep_lst/dataset/dataset.py | 10 ++++------ deep_lst/utils/full_store.py | 14 ++++++++------ tests/test_reader_store_roots.py | 28 +++++++++++++++++++++++++++- tests/test_training_paths.py | 4 +--- 4 files changed, 40 insertions(+), 16 deletions(-) diff --git a/deep_lst/dataset/dataset.py b/deep_lst/dataset/dataset.py index b78650c..d29e370 100644 --- a/deep_lst/dataset/dataset.py +++ b/deep_lst/dataset/dataset.py @@ -38,8 +38,6 @@ "data_static_categorical": "data_static_categorical_arr", } -PATHS = ExperimentPaths() - # time_indices_*.npz are hours since the data start (2016-01-01); the new full stores are indexed # on the 1970 epoch, so a time index must be shifted by this offset to address the store. # FLAGGED for later: cleaner to regenerate the indices as absolute T1H (see migration notes). @@ -79,7 +77,7 @@ def load_samples( def _load_anchor_ids(spatial_name, paths=None): """Anchor cell ids for a split: global MTG ids for training, seviri equiangular pixels for an eval holdout region.""" - paths = paths or PATHS + paths = paths or ExperimentPaths() return np.sort(np.load(paths.spatial_indices_path(spatial_name))["src_indices"].astype(np.int64)) @@ -245,7 +243,7 @@ def __getitem__(self, index): @classmethod def from_config(cls, modality, store, spatial, anchor, temporal, workers=1, store_root=None, paths=None): """Stream the MTG pixel selection (spatial) over the statistics timestep subset (temporal).""" - paths = paths or PATHS + paths = paths or ExperimentPaths() anchor_ids = _load_anchor_ids(spatial, paths) rows = np.unique(map_to_store_rows(anchor_grid(anchor), anchor_ids, store_grid(modality))) stat_hours = np.load(paths.temporal_indices_path(temporal))["time_indices"].astype(np.int64) @@ -387,7 +385,7 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs): are read. Columns depend only on (anchors, store), not the temporal split, so this runs once — a full-axis cache per split would not fit in RAM. """ - paths = paths or PATHS + paths = paths or ExperimentPaths() spatial_name = kwargs["spatial"] stats_tag = stats_spatial(kwargs) anchor_ids = _load_anchor_ids(spatial_name, paths) @@ -479,7 +477,7 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs): @classmethod def from_modalities(cls, modality_ids, shared, paths=None, **kwargs): """Build one split's dataset from the shared preloaded columns + this split's anchors.""" - paths = paths or PATHS + paths = paths or ExperimentPaths() stats_tag = stats_spatial(kwargs) computed_stats = {m: load_computed_stats(paths.stats_zarr_path(m, stats_tag)) for m in modality_ids} diff --git a/deep_lst/utils/full_store.py b/deep_lst/utils/full_store.py index 7782f1a..99a5c49 100644 --- a/deep_lst/utils/full_store.py +++ b/deep_lst/utils/full_store.py @@ -15,10 +15,10 @@ from deep_lst.dataset.dataset import ( DATA_TYPES, DATA_TYPES_ENABLE, - PATHS, _load_anchor_ids, _preload_columns, ) +from deep_lst.utils.io import ExperimentPaths from deep_lst.utils.spatial import anchor_grid, map_to_store_rows, store_grid # Full-store names, mirroring the data version pinned in conf/train.yaml. @@ -27,7 +27,7 @@ ERA5_LAND_STORE = "era5_land_2016_2025" -def open_store_reader(modality, store, data_types): +def open_store_reader(modality, store, data_types, *, paths=None): """Full-store reader with exactly the `data_types` enabled (data is always read). Enable-flags for data types this modality's reader doesn't accept (ERA5 has no @@ -38,11 +38,12 @@ def open_store_reader(modality, store, data_types): reader_kwargs[flag] = data_type in data_types accepted = inspect.signature(get_data_reader_class(modality)).parameters reader_kwargs = {key: value for key, value in reader_kwargs.items() if key in accepted} - store_path = PATHS.eozarr_store_path(store, PATHS.store_roots.get(modality)) + paths = paths or ExperimentPaths() + store_path = paths.eozarr_store_path(store, paths.store_roots.get(modality)) return eodata.get_data_reader(modality, store=str(store_path), **reader_kwargs) -def load_store_columns(modality, store, spatial, load, anchor="mtg", day_range=None, num_workers=8): +def load_store_columns(modality, store, spatial, load, anchor="mtg", day_range=None, num_workers=8, *, paths=None): """Raw full-store columns for one spatial selection. Anchor ids from indices_{spatial}.npz are mapped to the modality's native store @@ -56,10 +57,11 @@ def load_store_columns(modality, store, spatial, load, anchor="mtg", day_range=N columns[data_type][inverse] expands back to per-anchor order. Cell lon/lat: store_grid(modality).centers[unique_rows]. """ - anchor_ids = _load_anchor_ids(spatial) + paths = paths or ExperimentPaths() + anchor_ids = _load_anchor_ids(spatial, paths) rows = map_to_store_rows(anchor_grid(anchor), anchor_ids, store_grid(modality)) unique_rows, inverse = np.unique(rows, return_inverse=True) - reader = open_store_reader(modality, store, load) + reader = open_store_reader(modality, store, load, paths=paths) select = { data_type: [list(getattr(reader, DATA_TYPES[data_type]).dtype.fields).index(var) for var in names] for data_type, names in load.items() diff --git a/tests/test_reader_store_roots.py b/tests/test_reader_store_roots.py index 55798b6..46e1410 100644 --- a/tests/test_reader_store_roots.py +++ b/tests/test_reader_store_roots.py @@ -1,4 +1,4 @@ -"""Per-modality store roots for statistics and baseline metadata readers.""" +"""Per-modality store roots for statistics, baselines and full-store readers.""" from pathlib import Path from types import SimpleNamespace @@ -11,10 +11,36 @@ from deep_lst.baselines import base # noqa: E402 from deep_lst.baselines.era5land import Era5LandExtractor # noqa: E402 from deep_lst.dataset import dataset # noqa: E402 +from deep_lst.utils import full_store # noqa: E402 from deep_lst.utils.io import ExperimentPaths # noqa: E402 from scripts.assets import compute_statistics # noqa: E402 +def test_full_store_reads_indices_and_columns_with_the_same_paths(tmp_path, monkeypatch): + paths = ExperimentPaths(assets_root=tmp_path / "assets", store_roots={"seviri": str(tmp_path / "seviri")}) + indices = paths.spatial_indices_path("tiny") + indices.parent.mkdir(parents=True) + np.savez(indices, src_indices=[0]) + monkeypatch.setattr(full_store, "anchor_grid", lambda _: None) + monkeypatch.setattr(full_store, "store_grid", lambda _: None) + monkeypatch.setattr(full_store, "map_to_store_rows", lambda *args: np.array([4])) + monkeypatch.setattr(full_store, "get_data_reader_class", lambda _: lambda store, average_hourly: None) + + def open_reader(modality, store, **kwargs): + assert store == str(tmp_path / "seviri/tiny.eozarr") + return SimpleNamespace(data_arr=np.empty(0, dtype=[("LST", "f4")])) + + monkeypatch.setattr(full_store.eodata, "get_data_reader", open_reader) + monkeypatch.setattr(full_store, "_preload_columns", lambda *args, **kwargs: {"data": np.array([[281.0]])}) + columns, rows, inverse, anchors = full_store.load_store_columns( + "seviri", "tiny", "tiny", {"data": ["LST"]}, paths=paths + ) + np.testing.assert_array_equal(columns["data"], [[281.0]]) + np.testing.assert_array_equal(rows, [4]) + np.testing.assert_array_equal(inverse, [0]) + np.testing.assert_array_equal(anchors, [0]) + + @pytest.mark.parametrize( "store_roots, legacy", [({}, None), ({"seviri": "custom-store"}, "old-store"), ({}, "old-store")] ) diff --git a/tests/test_training_paths.py b/tests/test_training_paths.py index f8e63d2..59072d5 100644 --- a/tests/test_training_paths.py +++ b/tests/test_training_paths.py @@ -74,8 +74,7 @@ def test_configured_reader_and_cache_preserve_samples_on_cold_and_warm_load(tmp_ stats.mkdir(parents=True) (stats / "zarr.json").write_text("{}") if not explicit_paths: - monkeypatch.setattr(dataset, "PATHS", paths) - original_paths = dataset.PATHS + monkeypatch.setattr(dataset, "ExperimentPaths", lambda: paths) grid = SimpleNamespace(centers=np.array([[20.0, 10.0]])) monkeypatch.setattr(dataset, "anchor_grid", lambda _: grid) monkeypatch.setattr(dataset, "store_grid", lambda _: grid) @@ -130,7 +129,6 @@ def computed_stats(path): assert normalizers == [f"zscore:{stats}"] assert computed == [stats] * 6 assert len(list(paths.preload_cache_root.glob("preload_tiny_*.pt"))) == 1 - assert dataset.PATHS is original_paths if explicit_paths: paths.store_roots["seviri"] = "changed-data" changed = LitDataModule(experiment_paths=paths, **module.kwargs)