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
1 change: 1 addition & 0 deletions conf/infer.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
defaults:
- _self_
- paths
- eval: gobabeb

# --- required ---
Expand Down
9 changes: 9 additions & 0 deletions conf/paths.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# @package paths
# 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

# Only list modalities whose stores live under a different root.
store_roots: {}
1 change: 1 addition & 0 deletions conf/statistics.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@

defaults:
- _self_
- paths
- sources: eozarr

modality: ???
Expand Down
5 changes: 1 addition & 4 deletions conf/train.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
defaults:
- _self_ # base applies first; groups below have higher priority
- paths
- sources: eozarr
- model: mlp
- objective: rollout
Expand All @@ -11,10 +12,6 @@ defaults:

config_version: 2

paths:
eozarr_root: null
preload_cache_root: null

# --- derived keys (resolved lazily by OmegaConf) ---
_spatial: mtg_new
_spatial_val: eval_mtg_new_val
Expand Down
7 changes: 6 additions & 1 deletion deep_lst/baselines/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ def output_path(self) -> Path:
def run(self, shared: dict, config: dict, store_key: str) -> None:
self.store_key = store_key
self.config = config
if "paths" in config:
self.paths = ExperimentPaths.from_config(config["paths"])
if self.output_path().exists() and not self.overwrite:
print(f"Output already exists for '{store_key}'. Pass overwrite=True to refresh.")
return
Expand Down Expand Up @@ -86,7 +88,10 @@ def _preload_series(self, shared: dict, modality: str, var_name: str):

def _metadata_attrs(self, modality: str, store_name: str, var_name: str) -> dict:
"""Baseline attrs sourced from the store's own per-variable metadata scheme."""
reader = get_data_reader(modality, store=str(self.paths.eozarr_store_path(store_name)), average_hourly=False)
store_root = self.paths.store_roots.get(modality, self.config["test_dataset"][modality].get("store_root"))
reader = get_data_reader(
modality, store=str(self.paths.eozarr_store_path(store_name, store_root)), average_hourly=False
)
variable_meta = reader.data_arr.attrs.get("metadata", {}).get(var_name, {})
return dict(
variable=var_name,
Expand Down
23 changes: 18 additions & 5 deletions deep_lst/dataset/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import json
import os
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import eodata
import numpy as np
Expand Down Expand Up @@ -242,11 +243,12 @@ def __getitem__(self, index):
return leaves

@classmethod
def from_config(cls, modality, store, spatial, anchor, temporal, workers=1):
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)."""
anchor_ids = _load_anchor_ids(spatial)
paths = paths or PATHS

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we still need PATHS?

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)
stat_hours = np.load(paths.temporal_indices_path(temporal))["time_indices"].astype(np.int64)
stat_days = np.unique((stat_hours + STORE_EPOCH_OFFSET) // 24) # store days; each read in full (24 h)

# Enable the full continuous leaves (data + data_daily + data_static), raw. Categoricals and
Expand All @@ -260,7 +262,10 @@ def from_config(cls, modality, store, spatial, anchor, temporal, workers=1):
}
accepted = inspect.signature(get_data_reader_class(modality)).parameters
reader_kwargs = {key: value for key, value in reader_kwargs.items() if key in accepted}
reader = eodata.get_data_reader(modality, store=str(PATHS.eozarr_store_path(store)), **reader_kwargs)
store_root = paths.store_roots.get(modality, store_root)
reader = eodata.get_data_reader(
modality, store=str(paths.eozarr_store_path(store, store_root)), **reader_kwargs
)
return cls(reader, rows, stat_days)


Expand Down Expand Up @@ -388,6 +393,9 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs):
anchor_ids = _load_anchor_ids(spatial_name, paths)
src_grid = anchor_grid(kwargs.get("anchor", "mtg"))
num_workers = kwargs.get("preload_workers", 8)
store_roots = {
modality: paths.store_roots.get(modality, kwargs[modality].get("store_root")) for modality in modality_ids
}

# Disk cache: the preload is deterministic given the anchors, stores, load specs and
# statistics, so later runs (restarts, HP/architecture sweeps) skip the store reads.
Expand All @@ -406,6 +414,9 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs):
},
}
for modality in modality_ids:
store_root = store_roots[modality]
if store_root is not None:
fingerprint_spec["modalities"][modality]["store_root"] = str(Path(store_root).resolve())
transform = kwargs[modality].get("transform")
if transform is not None: # only when set, so caches built before the key existed stay valid
fingerprint_spec["modalities"][modality]["transform"] = transform
Expand Down Expand Up @@ -433,7 +444,9 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs):
accepted = inspect.signature(get_data_reader_class(modality)).parameters
reader_kwargs = {key: value for key, value in reader_kwargs.items() if key in accepted}
reader = eodata.get_data_reader(
modality, store=str(paths.eozarr_store_path(kwargs[modality]["store"])), **reader_kwargs
modality,
store=str(paths.eozarr_store_path(kwargs[modality]["store"], store_roots[modality])),
**reader_kwargs,
)

normalizer = ModalityNormalizer.from_spec(
Expand Down
4 changes: 2 additions & 2 deletions deep_lst/finetune.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def main(cfg: DictConfig) -> None:
name = f"{name}_smoke"
config["name"] = name

paths = ExperimentPaths()
paths = ExperimentPaths.from_config(config.get("paths"))
from_parts = from_run.split("/")
if len(from_parts) != 2:
raise ValueError(f"from_run must be EXPERIMENT/VERSION, got: {from_run!r}")
Expand Down Expand Up @@ -178,7 +178,7 @@ def main(cfg: DictConfig) -> None:
check_stats_transform(paths.stats_zarr_path(modality, stats_tag), transform)

data_module = LitDataModule(
**config, train_dataset=train_view, val_dataset=views["val"], test_dataset=views["test"]
experiment_paths=paths, **config, train_dataset=train_view, val_dataset=views["val"], test_dataset=views["test"]
)
data_module.setup()

Expand Down
8 changes: 5 additions & 3 deletions deep_lst/sensitivity/forecast.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,18 @@ def sensitivity_dir(paths, experiment, version, eval_name, method, block):
class PerturbedInference:
"""Holds the loaded model and the preloaded dataset of one (experiment, eval)."""

def __init__(self, cfg, config):
def __init__(self, cfg, config, paths=None):
self.cfg = cfg # hydra: experiment, version, best, land_water_mask
self.config = config # resolved run config
self.test_view = split_views(config)["test"]
self.td_keys = get_keys_from_config(self.test_view)
self.model, self.device = load_model(
config, self.td_keys, experiment=cfg.experiment, version=cfg.version, prefer_best=cfg.best
)
self.shared = MultimodalDataset.preload_shared(config["modality_ids"], **self.test_view)
self.dataset = MultimodalDataset.from_modalities(config["modality_ids"], self.shared, **self.test_view)
self.shared = MultimodalDataset.preload_shared(config["modality_ids"], paths=paths, **self.test_view)
self.dataset = MultimodalDataset.from_modalities(
config["modality_ids"], self.shared, paths=paths, **self.test_view
)

def forecast(self, path):
"""One pass over the dataset as it is now (perturbed or not) into a forecast store.
Expand Down
2 changes: 1 addition & 1 deletion deep_lst/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def main(cfg: DictConfig) -> None:
config = OmegaConf.to_container(cfg, resolve=True)
choices = HydraConfig.get().runtime.choices
validate_config(config)
paths = ExperimentPaths(**{key: Path(value) for key, value in config.get("paths", {}).items() if value is not None})
paths = ExperimentPaths.from_config(config.get("paths"))
pl.seed_everything(config["seed"], workers=True)

smoke = config.pop("smoke", False)
Expand Down
3 changes: 2 additions & 1 deletion deep_lst/utils/full_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ 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}
return eodata.get_data_reader(modality, store=str(PATHS.eozarr_store_path(store)), **reader_kwargs)
store_path = PATHS.eozarr_store_path(store, PATHS.store_roots.get(modality))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see above, do we still need PATHS?

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):
Expand Down
48 changes: 35 additions & 13 deletions deep_lst/utils/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,25 @@
import os
import re
from dataclasses import dataclass, field
from functools import cache
from pathlib import Path

from omegaconf import OmegaConf


@cache
def _default_paths() -> dict:
return OmegaConf.to_container(
OmegaConf.load(Path(__file__).resolve().parents[2] / "conf" / "paths.yaml"), resolve=True
)


def _preload_cache_root(settings: dict) -> Path:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to change this such that we also set this path manually in the paths.yaml

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:
Expand All @@ -12,17 +29,21 @@ 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"))
# Full eodata stores. Moved off tscratch (90-day purge) in October 2026.
eozarr_root: Path = field(
default_factory=lambda: Path("/Net/Groups/BGI/work_5/scratch/WeatherGenerator/data/lowres_old")
)
preload_cache_root: Path = field(
default_factory=lambda: Path(
os.environ.get("DEEP_LST_CACHE_ROOT")
or f"/Net/Groups/BGI/tscratch/{os.environ.get('USER') or getpass.getuser()}/tmp"
)
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()))
store_roots: dict[str, str | None] = field(
default_factory=lambda: dict(_default_paths()["store_roots"]), kw_only=True
)

@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")
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:
return self.experiment_root / experiment

Expand Down Expand Up @@ -50,14 +71,15 @@ def config_path(self, experiment: str) -> Path:
def statistics_path(self, modality, name) -> Path:
return self.assets_root / modality / "statistics" / f"statistics_{name}.npz"

def eozarr_store_path(self, store_name: str) -> Path:
def eozarr_store_path(self, store_name: str, store_root: str | Path | None = None) -> Path:
"""Resolve a full eodata .eozarr store from its config-provided name.

Prefers the directory store when it is readable and falls back to the .zip sibling:
under eozarr_root the era5, era5_land, glofas and swe stores exist only as zips, while
under the selected root the era5, era5_land, glofas and swe stores exist only as zips, while
seviri is a directory store."""
directory = self.eozarr_root / f"{store_name}.eozarr"
archive = self.eozarr_root / f"{store_name}.eozarr.zip"
root = self.eozarr_root if store_root is None else Path(store_root)
directory = root / f"{store_name}.eozarr"
archive = root / f"{store_name}.eozarr.zip"
directory_is_readable = (directory / "data" / "zarr.json").exists()
if not directory_is_readable and archive.exists():
return archive
Expand Down
40 changes: 26 additions & 14 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,27 +56,34 @@ be edited.

## 2. `conf/train.yaml`

### Training data and cache paths
### Data and cache paths

`paths.eozarr_root` and `paths.preload_cache_root` override the data-store and preload-cache
roots used by `deep_lst/train.py`, for all three training/validation/test splits. The defaults
are defined in `ExperimentPaths` in `deep_lst/utils/io.py`, also used by the `PATHS` singleton
in `deep_lst/dataset/dataset.py`. Both config values default to `null`, so these defaults apply.
`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
`store_roots` for modalities that live elsewhere:

The cache default uses `DEEP_LST_CACHE_ROOT` when it is nonempty; otherwise it uses
`/Net/Groups/BGI/tscratch/$USER/tmp` (the login name is used if `USER` is unset or empty).
An explicit `paths.preload_cache_root` takes priority over this default. Relative paths remain
relative to the repository working directory. The overrides are saved in the run's `config.yml`.
```yaml
store_roots:
seviri: /data/deep_lst
```

Here SEVIRI uses the separate directory and the other modalities use `eozarr_root`.
A null entry explicitly selects the common root. An older saved run can still provide
`sources.<modality>.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 `<preload_cache_parent>/<user>/tmp`. The login name is used when `USER` is unset
or empty. Relative paths are resolved from the working directory.

```
uv run python deep_lst/train.py paths.eozarr_root=/data/eozarr paths.preload_cache_root=/scratch/deep_lst-cache
uv run python scripts/assets/compute_statistics.py modality=seviri +paths.store_roots.seviri=/data/deep_lst
```

Cache keys are unchanged; use a separate cache root when the source data content differs.

These Hydra overrides apply to training. Standalone inference, statistics and fine-tuning use
the shared `ExperimentPaths` defaults, including the cache default described above.
Model, loss and data-processing settings are unchanged.
Use `+` to add a modality to `store_roots` and leave it off to override an existing entry.
If you change the common `eozarr_root`, set a separate `preload_cache_root` to avoid reusing
a cache generated from the old stores. A modality-specific root is included in the cache key.

### 2.1 Selections and splits

Expand Down Expand Up @@ -172,6 +179,9 @@ that training, inference, the baselines and the statistics script share.
| `increment_vars` | variables for which the statistics script also computes the statistics of the 1-hour increment. Read by `scripts/assets/compute_statistics.py` only. Listing a variable here does not make it a prognostic of the model. |
| `quality_mask` | optional and not set: `{field, se_max, target}` sets `target` to missing where the metadata variable `field` exceeds `se_max` |

The root comes from `conf/paths.yaml`. Each store is read from `<store>.eozarr` or its ZIP sibling
under the selected root.

Data types under `load`:

| Data type | Holds |
Expand All @@ -197,6 +207,8 @@ only in the data options that name it.

Changing `store`, `load` or `transform` changes the preload cache key, so the cache is rebuilt
(`docs/RUNBOOK.md`, section 4.6). Changing the `data` option does not.
A modality-specific root from `paths.store_roots` is included in that key using its resolved path.
Without a modality-specific root, the existing cache key is preserved.

### 3.2 `data`

Expand Down
13 changes: 4 additions & 9 deletions docs/RUNBOOK.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,10 @@ assets/baselines/<kind>/<name>.nc persistence / climatology / ERA5(-Land

Check these locations in a new clone:

1. `ExperimentPaths.preload_cache_root` in `deep_lst/utils/io.py` uses `DEEP_LST_CACHE_ROOT`
when it is nonempty, otherwise `/Net/Groups/BGI/tscratch/$USER/tmp` (using the login name if
`USER` is unset or empty). For training, `paths.preload_cache_root=<your-tscratch>` on the command
line or in the config file takes priority; `paths.eozarr_root` can also override the store
root. Other entry points use the shared `ExperimentPaths` defaults, including this cache
fallback. See `docs/CONFIGURATION.md`.
The data stores (`ExperimentPaths.eozarr_root`,
`/Net/Groups/BGI/work_5/scratch/WeatherGenerator/data/lowres_old`) are group-readable and
stay as they are.
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.
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.

Expand Down
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,8 @@ quote-style = "double"

[tool.setuptools.packages.find]
where = ["."]
include = ["deep_lst*"]
include = ["deep_lst*", "conf"]
exclude = ["plots*", "wandb*", "assets*", "configs*", "notebooks*", "checkpoints*", "experiments*"]

[tool.setuptools.package-data]
conf = ["paths.yaml"]
7 changes: 4 additions & 3 deletions scripts/assets/compute_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
from deep_lst.utils.io import ExperimentPaths
from deep_lst.utils.spatial import store_grid

PATHS = ExperimentPaths()

# On-the-fly features that get statistics. The doy/hod cos/sin encodings are bounded in
# [-1, 1] by construction and stay raw — z-scoring the components of a cyclic pair
# separately would distort the encoding.
Expand Down Expand Up @@ -92,6 +90,7 @@ def computed_feature_statistics(rows, stat_days, modality) -> ArrayStatistics:
@hydra.main(config_path="../../conf", config_name="statistics", version_base="1.3")
def main(cfg: DictConfig) -> None:
config = OmegaConf.to_container(cfg, resolve=True)
paths = ExperimentPaths.from_config(config.get("paths"))
modality = config["modality"]
source = config["sources"][modality] # the same definition train.yaml composes
increment_vars = source.get("increment_vars", [])
Expand All @@ -101,6 +100,8 @@ def main(cfg: DictConfig) -> None:
dataset = UnimodalDataset.from_config(
modality=modality,
store=source["store"],
store_root=source.get("store_root"),
paths=paths,
spatial=config["spatial"],
anchor=config["anchor"],
temporal=config["temporal"],
Expand Down Expand Up @@ -129,7 +130,7 @@ def _array_stats(stats):
if increment_vars:
modality_stats["increments"] = _array_stats(increment_stats)

out_path = PATHS.stats_zarr_path(modality, config["spatial"])
out_path = paths.stats_zarr_path(modality, config["spatial"])
ModalityStatistics(modality_stats).to_zarr(str(out_path))

# Record variable names next to the positional statistics: base data types carry the
Expand Down
Loading
Loading