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 b7cad9a..03335ed 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. product_root: /Net/Groups/BGI/work_5/scratch/WeatherGenerator/data/deep_lst -preload_cache_root: null -preload_cache_parent: /Net/Groups/BGI/tscratch +preload_cache_root: ./cache # Only list stores that 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..a76fb3c --- /dev/null +++ b/conf/paths/local.yaml @@ -0,0 +1,4 @@ +# Use a different cache from the BGC profile. +product_root: ./data +preload_cache_root: ./cache/local +store_roots: {} diff --git a/conf/statistics.yaml b/conf/statistics.yaml index 449d65e..39aabc6 100644 --- a/conf/statistics.yaml +++ b/conf/statistics.yaml @@ -1,7 +1,7 @@ defaults: - _self_ - - paths + - paths: bgc - sources: product modality: ??? diff --git a/conf/train.yaml b/conf/train.yaml index f7906ea..04da85e 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: product - model: mlp - objective: rollout diff --git a/deep_lst/dataset/dataset.py b/deep_lst/dataset/dataset.py index 3bf5c06..5a233a8 100644 --- a/deep_lst/dataset/dataset.py +++ b/deep_lst/dataset/dataset.py @@ -16,8 +16,6 @@ # Modality carrying the global time features (doy/hod); the finest / target grid. _ANCHOR_MODALITY = "seviri" -PATHS = ExperimentPaths() - # time_indices_*.npz are hours since the data start (2016-01-01); the 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). @@ -55,7 +53,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)) @@ -210,7 +208,7 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs): read (deep_lst/dataset/preload.py). Columns depend only on (anchors, stores), 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) @@ -265,7 +263,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 3e1250e..3eb3c5a 100644 --- a/deep_lst/utils/full_store.py +++ b/deep_lst/utils/full_store.py @@ -7,20 +7,21 @@ import numpy as np -from deep_lst.dataset.dataset import PATHS, _load_anchor_ids +from deep_lst.dataset.dataset import _load_anchor_ids from deep_lst.dataset.preload import open_readers, preload_modality -from deep_lst.utils.io import default_sources +from deep_lst.utils.io import ExperimentPaths, default_sources from deep_lst.utils.spatial import store_grid -def stores_of(modality, load): +def stores_of(modality, load, *, paths=None): """{store name: [variables]} for the variables of `load`. A variable is taken from the first store of the modality (in the order of conf/sources/product.yaml) that holds it. It does not have to be listed there, so an analysis can read variables that training does not load. """ - readers = open_readers(default_sources()[modality], PATHS) + paths = paths or ExperimentPaths() + readers = open_readers(default_sources()[modality], paths) stores = {} for variables in load.values(): for variable in variables: @@ -31,7 +32,7 @@ def stores_of(modality, load): return stores -def load_store_columns(modality, spatial, load, anchor="mtg", day_range=None, num_workers=8): +def load_store_columns(modality, spatial, load, anchor="mtg", day_range=None, num_workers=8, *, paths=None): """Raw store columns of one modality for one spatial selection. Args: @@ -42,6 +43,7 @@ def load_store_columns(modality, spatial, load, anchor="mtg", day_range=None, nu anchor: "mtg", or the modality whose grid rows the anchor ids are. day_range: (start_day, end_day) in days since 1970, end exclusive. Default: 2016 to 2025. num_workers: Threads that read time blocks in parallel. + paths: Paths for the selection, product stores and their grids. Returns: columns: {leaf: tensor}; leaves on the hourly axis (n_unique, n_days * 24, C), static @@ -52,11 +54,12 @@ def load_store_columns(modality, spatial, load, anchor="mtg", day_range=None, nu to per-anchor order. anchor_ids: The anchor ids of the selection. """ - anchor_ids = _load_anchor_ids(spatial) - source = {"stores": stores_of(modality, load), "load": load} - anchor_grid = None if anchor == "mtg" else store_grid(anchor) + paths = paths or ExperimentPaths() + anchor_ids = _load_anchor_ids(spatial, paths) + source = {"stores": stores_of(modality, load, paths=paths), "load": load} + anchor_grid = None if anchor == "mtg" else store_grid(anchor, paths) columns, inverse, cell_lonlat = preload_modality( - source, anchor, anchor_ids, PATHS, anchor_grid=anchor_grid, day_range=day_range, num_workers=num_workers + source, anchor, anchor_ids, paths, anchor_grid=anchor_grid, day_range=day_range, num_workers=num_workers ) - unique_rows = store_grid(modality).nearest_rows(cell_lonlat[:, 0], cell_lonlat[:, 1]) + unique_rows = store_grid(modality, paths).nearest_rows(cell_lonlat[:, 0], cell_lonlat[:, 1]) return columns, np.asarray(unique_rows), inverse, anchor_ids diff --git a/deep_lst/utils/io.py b/deep_lst/utils/io.py index 634ad88..62b1179 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 @@ -21,13 +19,6 @@ def default_sources() -> dict: return OmegaConf.to_container(OmegaConf.load(CONF_DIR / "sources" / "product.yaml"), resolve=True) -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.""" @@ -35,7 +26,7 @@ class ExperimentPaths: experiment_root: Path = field(default_factory=lambda: Path("./experiments")) config_root: Path = field(default_factory=lambda: Path("./configs")) assets_root: Path = field(default_factory=lambda: Path("./assets")) - 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"])) product_root: Path = field(default_factory=lambda: Path(_default_paths()["product_root"])) store_roots: dict[str, str | None] = field( default_factory=lambda: dict(_default_paths()["store_roots"]), kw_only=True @@ -45,10 +36,8 @@ class ExperimentPaths: def from_config(cls, config) -> "ExperimentPaths": settings = {**_default_paths(), **{key: value for key, value in (config or {}).items() if value is not None}} settings.pop("eozarr_root", None) # root of the .eozarr stores, in configs saved before the product stores - 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 887a194..9205636 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -58,9 +58,12 @@ 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. `product_root` is the common directory of the stores; every store is read +Training, fine-tuning, inference, sensitivity, statistics and baseline generation select +a paths profile. The default `paths=bgc` reads the site settings from `conf/paths.yaml`. +Use `paths=local` for stores under `./data` and a separate cache at `./cache/local`. +The baseline script uses `--paths local`. + +`product_root` is the common directory of the stores; every store is read from `/.zarr`. Add an entry to `store_roots` for a store that lives elsewhere: @@ -73,11 +76,14 @@ Here the LST store is read from the separate directory and all other stores from `product_root`. A null entry explicitly selects the common root. The store names of every modality are in `conf/sources/product.yaml` (section 3.1). -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` in the paths config or override it on the command line. +The BGC default is `./cache`. The previous per-user scratch directory and +`DEEP_LST_CACHE_ROOT` are no longer selected automatically. To keep using an existing +product-store cache, set `preload_cache_root` to its directory. Relative paths start at +the working directory. ``` +uv run python deep_lst/train.py paths=local uv run python deep_lst/train.py paths.product_root=/data/stores paths.preload_cache_root=/scratch/deep_lst-cache uv run python scripts/assets/compute_statistics.py modality=seviri +paths.store_roots.seviri_product_hourly_lst=/data/other ``` diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index 646cc8a..1123fff 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -86,9 +86,9 @@ 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. +1. Check `conf/paths.yaml` for the common store directory, any store-specific directories + and the preload cache. The BGC cache defaults to `./cache`. On the cluster, set + `preload_cache_root` to your scratch directory to keep using your existing product-store 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 f955be2..8bb7480 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -25,6 +25,19 @@ def test_entrypoints_use_the_shared_paths_file(entrypoint): assert paths.product_root == ExperimentPaths().product_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_product_hourly_lst=local-lst"], + ) + paths = ExperimentPaths.from_config(cfg.paths) + assert paths.product_root == Path("data") + assert paths.preload_cache_root == Path("cache/local") + assert paths.store_roots == {"seviri_product_hourly_lst": "local-lst"} + + @pytest.fixture def paths(tmp_path): return ExperimentPaths( @@ -34,35 +47,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", "null", "string", "path", "relative"]) diff --git a/tests/test_reader_store_roots.py b/tests/test_reader_store_roots.py index 9e5507c..d4ed6b4 100644 --- a/tests/test_reader_store_roots.py +++ b/tests/test_reader_store_roots.py @@ -1,15 +1,18 @@ """The statistics script and the baselines with the configured stores and store roots.""" +from pathlib import Path + import numpy as np import pytest from omegaconf import OmegaConf from deep_lst import stores from deep_lst.baselines.era5land import Era5LandExtractor -from deep_lst.stores import T1H, CubeReader +from deep_lst.stores import T1D, T1H, CubeReader +from deep_lst.utils import full_store, spatial from deep_lst.utils.io import ExperimentPaths, load_computed_stats, load_inc_variances from deep_lst.utils.statistics import read_variable_statistics -from scripts.assets import compute_statistics +from scripts.assets import compute_statistics, run_baselines class TinyLSTReader(CubeReader): @@ -95,3 +98,37 @@ def test_baseline_attributes_come_from_the_variable_table(): assert extractor._metadata_attrs("unlisted") == dict( variable="unlisted", units="", long_name="unlisted", 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.product_root == Path("data") + assert paths.preload_cache_root == Path("cache/local") + assert config["test_dataset"]["spatial"] == "eval_gobabeb" + + +def test_full_store_reads_the_selection_stores_and_grids_from_the_same_paths(tmp_path, monkeypatch, hourly_store): + monkeypatch.setitem(stores.READERS, "synthetic_hourly", TinyLSTReader) + sources = {"seviri": {"stores": {"synthetic_hourly": ["LST"]}}} + monkeypatch.setattr(full_store, "default_sources", lambda: sources) + monkeypatch.setattr(spatial, "default_sources", lambda: sources) + paths = ExperimentPaths( + assets_root=tmp_path / "chosen-assets", + product_root=tmp_path / "unused-root", + store_roots={"synthetic_hourly": str(hourly_store.path.parent)}, + ) + rows = [3, 19] + selection = paths.spatial_indices_path("tiny") + selection.parent.mkdir(parents=True) + np.savez(selection, src_indices=rows) + day = T1D.date_to_index("2016-01-01") + + columns, unique_rows, inverse, anchors = full_store.load_store_columns( + "seviri", "tiny", {"data": ["LST"]}, anchor="seviri", day_range=(day, day + 1), num_workers=1, paths=paths + ) + expected = hourly_store.values["LST"][:24].reshape(24, -1)[:, rows].T + np.testing.assert_array_equal(columns["data"][:, :, 0].numpy(), expected) + np.testing.assert_array_equal(unique_rows, rows) + np.testing.assert_array_equal(inverse, [0, 1]) + np.testing.assert_array_equal(anchors, rows) diff --git a/tests/test_training_paths.py b/tests/test_training_paths.py index 417000d..429c669 100644 --- a/tests/test_training_paths.py +++ b/tests/test_training_paths.py @@ -41,7 +41,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) @@ -86,8 +85,7 @@ def test_configured_stores_and_cache_preserve_samples_on_cold_and_warm_load( groups = {"data": dict(plain, variables=["LST"]), "computed": dict(plain, variables=["solar_zenith"])} write_statistics(paths.stats_zarr_path("seviri", "mtg_new"), groups) if not explicit_paths: - monkeypatch.setattr(dataset, "PATHS", paths) - original_paths = dataset.PATHS + monkeypatch.setattr(dataset, "ExperimentPaths", lambda: paths) split = dict( spatial="tiny", @@ -114,7 +112,6 @@ def test_configured_stores_and_cache_preserve_samples_on_cold_and_warm_load( np.testing.assert_array_equal(data.indices[:, 1], dataset.STORE_EPOCH_OFFSET + np.array([2, 3])) torch.testing.assert_close(data[0]["seviri", "LST"].flatten(), expected) assert len(list(paths.preload_cache_root.glob("preload_tiny_*.pt"))) == 1 - assert dataset.PATHS is original_paths if explicit_paths: # the same store under a root of its own: read again, cached under another key changed_values = hourly_store.values.copy()