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/infer.yaml b/conf/infer.yaml index 4a97006..300d18d 100644 --- a/conf/infer.yaml +++ b/conf/infer.yaml @@ -1,6 +1,6 @@ defaults: - _self_ - - paths + - paths: bgc - eval: gobabeb # --- required --- 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/conf/paths/bgc.yaml b/conf/paths/bgc.yaml new file mode 100644 index 0000000..2e22836 --- /dev/null +++ b/conf/paths/bgc.yaml @@ -0,0 +1,2 @@ +defaults: + - /paths diff --git a/conf/paths/local.yaml b/conf/paths/local.yaml new file mode 100644 index 0000000..aad0ffe --- /dev/null +++ b/conf/paths/local.yaml @@ -0,0 +1,4 @@ +# Use a different cache from the BGC profile. +eozarr_root: ./data +preload_cache_root: ./cache/local +store_roots: {} diff --git a/conf/statistics.yaml b/conf/statistics.yaml index 4e86daf..0a21d67 100644 --- a/conf/statistics.yaml +++ b/conf/statistics.yaml @@ -1,7 +1,7 @@ defaults: - _self_ - - paths + - paths: bgc - sources: eozarr modality: ??? diff --git a/conf/train.yaml b/conf/train.yaml index 4d3d8d5..c79c2b9 100644 --- a/conf/train.yaml +++ b/conf/train.yaml @@ -1,6 +1,6 @@ defaults: - _self_ # base applies first; groups below have higher priority - - paths + - paths: bgc - sources: eozarr - model: mlp - objective: rollout 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/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..f6cbc6b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -58,9 +58,16 @@ be edited. ### Data and cache paths -`conf/paths.yaml` is the shared file for the data and preload-cache locations. Training, -fine-tuning, inference, sensitivity, statistics and baseline generation read it from the -current checkout. Set `eozarr_root` for the common store directory and add entries to +Training, fine-tuning, inference, sensitivity, statistics and baseline generation select +a paths profile. The default `paths=bgc` reads the shared site settings from +`conf/paths.yaml`. Choose `paths=local` for stores under `./data` and a separate cache at +`./cache/local`. The baseline script uses `--paths local`. + +``` +uv run python deep_lst/train.py paths=local +``` + +Set `eozarr_root` for the common store directory and add entries to `store_roots` for modalities that live elsewhere: ```yaml @@ -72,9 +79,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/scripts/assets/run_baselines.py b/scripts/assets/run_baselines.py index f83659b..67dfa63 100644 --- a/scripts/assets/run_baselines.py +++ b/scripts/assets/run_baselines.py @@ -27,6 +27,7 @@ def parse_args(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--region", type=str, required=True, help="Eval config name, e.g. passage, dahra, train_mtg.") p.add_argument("--test_year", type=int, required=True, help="Year the baselines forecast (train years precede it).") + p.add_argument("--paths", choices=("bgc", "local"), default="bgc", help="Site paths profile.") p.add_argument("--window_days", type=int, default=7, help="Circular DOY window for the smoothed climatology.") p.add_argument( "--reference_modality", @@ -46,12 +47,12 @@ def parse_args(): return p.parse_args() -def build_config(region: str): +def build_config(region: str, paths_profile: str = "bgc"): """Full data config for a region: train.yaml's test split (stores/load) with the eval region's spatial/anchor/temporal overlaid — the same inputs preload_shared saw at inference. The test dataset dict the extractors read is attached as config["test_dataset"].""" with initialize_config_dir(version_base=None, config_dir=str(CONF_DIR)): - cfg = compose(config_name="train") + cfg = compose(config_name="train", overrides=[f"paths={paths_profile}"]) region_cfg = OmegaConf.load(CONF_DIR / "eval" / f"{region}.yaml") cfg.splits.test = OmegaConf.merge(cfg.splits.test, region_cfg.splits.test) config = OmegaConf.to_container(cfg, resolve=True) @@ -61,7 +62,7 @@ def build_config(region: str): def main(): args = parse_args() - config = build_config(args.region) + config = build_config(args.region, args.paths) store_key = args.out_key or config["test_dataset"]["spatial"] paths = ExperimentPaths.from_config(config.get("paths")) diff --git a/tests/test_io.py b/tests/test_io.py index 4443550..35131c9 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -25,6 +25,17 @@ def test_entrypoints_use_the_shared_paths_file(entrypoint): assert paths.eozarr_root == ExperimentPaths().eozarr_root +@pytest.mark.parametrize("entrypoint", ["train", "finetune", "infer", "statistics", "sensitivity"]) +def test_local_paths_profile_uses_a_separate_cache(entrypoint): + with initialize_config_dir(config_dir=str(CONF_DIR), version_base="1.3"): + cfg = compose(config_name=entrypoint, overrides=["paths=local", "+paths.store_roots.seviri=local-seviri"]) + paths = ExperimentPaths.from_config(cfg.paths) + assert paths.eozarr_root == Path("data") + assert paths.preload_cache_root == Path("cache/local") + assert paths.preload_cache_root != ExperimentPaths().preload_cache_root + assert paths.store_roots == {"seviri": "local-seviri"} + + @pytest.fixture def paths(tmp_path): return ExperimentPaths( @@ -34,35 +45,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_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_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_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_reader_store_roots.py b/tests/test_reader_store_roots.py index 55798b6..7cbfbcc 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,8 +11,34 @@ 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 +from scripts.assets import compute_statistics, run_baselines # 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( @@ -95,3 +121,11 @@ def open_reader(modality, store, **kwargs): expected_root = extractor.paths.eozarr_root if store_root is None else Path(store_root) assert stores == [str(expected_root / "tiny.eozarr")] assert attrs == dict(variable="skt", units="K", long_name="skt", description="", test_year="2024") + + +def test_baselines_read_the_selected_paths_profile(): + config = run_baselines.build_config("gobabeb", "local") + paths = ExperimentPaths.from_config(config["paths"]) + assert paths.eozarr_root == Path("data") + assert paths.preload_cache_root == Path("cache/local") + assert config["test_dataset"]["spatial"] == "eval_gobabeb" diff --git a/tests/test_training_paths.py b/tests/test_training_paths.py index d795a6f..59072d5 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) @@ -75,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) @@ -131,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)