snapshot before cleanup
Browse filesCo-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- .gitignore+2-4
- 01_data.ipynbAdded
- 02_inputs.ipynbAdded
- 03_results.ipynbAdded+231
- EXPERIMENT.mdAdded+27
- README.mdAdded+93
- configs/clay-large-dpt.yamlAdded+141
- configs/dinov3-7b-dpt.yamlAdded+107
- configs/dinov3-7b-sat-dpt.yamlAdded+107
- configs/dinov3-base-dpt-cutmix.yamlAdded+107
- configs/dinov3-base-dpt-experts.yamlAdded+108
- configs/dinov3-base-dpt-google.yamlAdded+107
- configs/dinov3-base-dpt-lr-low.yamlAdded+107
- configs/dinov3-base-dpt-noaug.yamlAdded+99
- configs/dinov3-base-dpt-ohem.yamlAdded+107
- configs/dinov3-base-dpt-rotate.yamlAdded+114
- configs/dinov3-base-dpt.yamlAdded+107
- configs/dinov3-base-qkvb-dpt.yamlAdded+107
- configs/dinov3-base-unet.yamlAdded+107
- configs/dinov3-huge-plus-dpt.yamlAdded+107
- configs/dinov3-huge-plus-qkvb-dpt.yamlAdded+107
- configs/dinov3-large-dpt.yamlAdded+107
- configs/dinov3-large-qkvb-dpt.yamlAdded+107
- configs/dinov3-large-qkvb-sat-dpt.yamlAdded+107
- configs/dinov3-large-sat-dpt.yamlAdded+107
- configs/dinov3-small-dpt.yamlAdded+107
- configs/dinov3-small-plus-dpt.yamlAdded+107
- configs/dinov3-small-plus-qkvb-dpt.yamlAdded+107
- configs/dinov3-small-qkvb-dpt.yamlAdded+107
- configs/dynamic-world/model_spec.yamlDeleted-29
- configs/prithvi-v1-100-dpt.yamlAdded+124
- configs/prithvi-v2-300-dpt.yamlAdded+124
- configs/prithvi-v2-300-tl-dpt.yamlAdded+125
- configs/prithvi-v2-600-dpt.yamlAdded+124
- configs/prithvi-v2-600-tl-dpt.yamlAdded+125
- main.py+7-3
- modules/__init__.pyAdded
- modules/segmentation/__init__.pyAdded
- modules/segmentation/supervised/__init__.pyAdded
- modules/segmentation/supervised/data.pyAdded+106
- modules/segmentation/supervised/datasets.pyAdded+116
- modules/segmentation/supervised/module.pyAdded+138
- requirements.lockAdded+245
- requirements.txt+19-12
- scripts/check_data.pyAdded+68
- scripts/download_dynamic_world.py+59-26
- scripts/ingest_dynamic_world.py+331-157
- scripts/smoke.pyAdded+125
- tests/conftest.pyAdded+8
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.whl filter=lfs diff=lfs merge=lfs -text
123456.envdata/*.ckpt__pycache__/.ipynb_checkpoints/.venv/1234data/artifacts/__pycache__/*.pyc
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231{ "cells": [ { "cell_type": "markdown", "id": "efe3f70a", "metadata": {}, "source": [ "# Experiment results\n", "\n", "Read TensorBoard events from the current complete experiment configurations. Historical U-Net pilot runs are excluded. CPU smoke runs establish execution only and are never ranked as scientific model results." ] }, { "cell_type": "code", "execution_count": 1, "id": "763e87d3", "metadata": { "execution": { "iopub.execute_input": "2026-11-06T14:24:50.705279Z", "iopub.status.busy": "2026-11-06T14:24:50.705044Z", "iopub.status.idle": "2026-11-06T14:24:51.456353Z", "shell.execute_reply": "2026-11-06T14:24:51.455418Z" } }, "outputs": [], "source": [ "from pathlib import Path\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import rasterio\n", "import yaml\n", "from IPython.display import display\n", "ROOT = Path.cwd()\n", "assert (ROOT / \"data/labels.yaml\").exists(), \"Run this notebook from the project root\"\n", "labels = yaml.safe_load((ROOT / \"data/labels.yaml\").read_text())\n", "from tensorboard.backend.event_processing.event_accumulator import EventAccumulator\n", "studies = yaml.safe_load(Path(\"studies.yaml\").read_text())\n", "configs = {}\n", "for study in studies.values():\n", " for filename in study[\"experiments\"]:\n", " configs[Path(filename).stem] = filename\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "3449a87a", "metadata": { "execution": { "iopub.execute_input": "2026-11-06T14:24:51.458315Z", "iopub.status.busy": "2026-11-06T14:24:51.458005Z", "iopub.status.idle": "2026-11-06T14:24:51.464736Z", "shell.execute_reply": "2026-11-06T14:24:51.464178Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "No current GPU study results are available. No best model can be selected.\n" ] } ], "source": [ "records = []\n", "for name, filename in configs.items():\n", " target = yaml.safe_load(Path(filename).read_text())[\"model\"][\"target\"]\n", " for folder in sorted((Path(\"artifacts/runs\") / name).glob(\"version_*\")):\n", " if not list(folder.glob(\"events.out.tfevents.*\")):\n", " continue\n", " events = EventAccumulator(str(folder), size_guidance={\"scalars\": 0})\n", " events.Reload()\n", " for tag in events.Tags()[\"scalars\"]:\n", " for point in events.Scalars(tag):\n", " records.append({\"experiment\": name, \"version\": folder.name, \"metric\": tag, \"target\": target, \"step\": point.step, \"value\": point.value})\n", "results = pd.DataFrame(records)\n", "if results.empty:\n", " print(\"No current GPU study results are available. No best model can be selected.\")\n", "else:\n", " display(results.groupby([\"experiment\", \"version\", \"metric\"]).size().rename(\"observations\").to_frame())\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "2682c46a", "metadata": { "execution": { "iopub.execute_input": "2026-11-06T14:24:51.466157Z", "iopub.status.busy": "2026-11-06T14:24:51.466022Z", "iopub.status.idle": "2026-11-06T14:24:51.477573Z", "shell.execute_reply": "2026-11-06T14:24:51.476760Z" } }, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>study</th>\n", " <th>configs</th>\n", " <th>seeds</th>\n", " <th>question</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>screening</td>\n", " <td>6</td>\n", " <td>[42]</td>\n", " <td>Compare pretrained families with their documen...</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>capacity</td>\n", " <td>14</td>\n", " <td>[42]</td>\n", " <td>Remaining supported pretrained capacities and ...</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>decoder</td>\n", " <td>2</td>\n", " <td>[42, 43, 44]</td>\n", " <td>DPT versus U-Net with the same pretrained DINO...</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>recipe</td>\n", " <td>7</td>\n", " <td>[42]</td>\n", " <td>Controlled reference-model ablations; base is ...</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>targets</td>\n", " <td>1</td>\n", " <td>[42]</td>\n", " <td>Separate 9-class task; never rank against 8-cl...</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " study configs seeds \\\n", "0 screening 6 [42] \n", "1 capacity 14 [42] \n", "2 decoder 2 [42, 43, 44] \n", "3 recipe 7 [42] \n", "4 targets 1 [42] \n", "\n", " question \n", "0 Compare pretrained families with their documen... \n", "1 Remaining supported pretrained capacities and ... \n", "2 DPT versus U-Net with the same pretrained DINO... \n", "3 Controlled reference-model ablations; base is ... \n", "4 Separate 9-class task; never rank against 8-cl... " ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "if not results.empty:\n", " iou = results[results.metric == \"val_iou_macro\"]\n", " for target, task in iou.groupby(\"target\"):\n", " fig, axis = plt.subplots()\n", " for (name, version), group in task.groupby([\"experiment\", \"version\"]):\n", " axis.plot(group.step, group.value, label=f\"{name}/{version}\")\n", " axis.set_title(target)\n", " axis.set_xlabel(\"Training step\")\n", " axis.set_ylabel(\"Validation macro IoU\")\n", " axis.legend()\n", " fig.tight_layout()\n", "else:\n", " display(pd.DataFrame([{\"study\": name, \"configs\": len(study[\"experiments\"]), \"seeds\": study[\"seeds\"], \"question\": study[\"description\"]} for name, study in studies.items()]))" ] }, { "cell_type": "markdown", "id": "8561f08c", "metadata": {}, "source": [ "Before ranking, verify that each intended run completed its planned budget, used the same cohort and target, and has the expected seed/configuration. Compare eight-class and nine-class targets separately. Choose models on development validation; reserve consensus test for final confirmation. Event records from interrupted runs are useful learning curves but do not establish a completed comparison." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.9" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627# Experiment requirements
Publish semantic-segmentation models and investigate speed–accuracy trade-offs.Start with DINOv3 and Prithvi across the agreed size range; confirm exact Prithvicheckpoints before treating parameter counts as small/base/large equivalents.Build a baseline first and add configuration comparisons incrementally.
Use the existing GeoSave segmentation template, LightningCLI, library metrics,and standard Lightning logging/checkpoint behavior. Run ordinary YAML configsdirectly. Existing configs are drafts, not a required model inventory.
The Dataset owns source-specific annotation selection. The DataModule forwardsconfiguration and owns loaders and training augmentation. All label modes andremapping come from data/labels.yaml; ignored targets are always 255.
Training must use paired random crops. Only validation/test use deterministicchips. Merge raw output logits onto each original scene grid before updatingGeoSave metrics, excluding padding and counting each evaluated pixel once.These training/evaluation changes are not implemented in the foundation pass.
Published source memberships overlap. Evaluation membership and the selectedvalidation composite must be resolved before claiming generalization or choosinga best model. The four composite variants belong to validation only.
EDA must be auditable: one question per section, visible calculations, simpleDataFrames, and direct GeoSave plot/explore calls. Preserve original annotationsand source metadata. Do not hide the analysis in custom scripts or dashboards.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# Dynamic World segmentation
Build publishable semantic-segmentation models and compare speed and accuracy,starting with DINOv3 and Prithvi. Keep one readable working path before addingexperiment automation. Training uses GeoSave's LightningCLI and library metrics.
## Current foundation
- `scripts/download_dynamic_world.py` downloads annotation archives, the separate training metadata workbook, and the source README. Existing archives are skipped; missing metadata is still fetched.- `scripts/ingest_dynamic_world.py` pairs imagery using the label's GeoRegion and writes image/label COGs with source metadata in GeoParquet. Original product IDs are provenance, not retrieval requirements.- `modules/segmentation/supervised/datasets.py` owns Dataset selection and label remapping. `data.py` passes options through and constructs loaders.- `data/labels.yaml` owns all three label modes. Every mode uses ignore index 255. Source nodata 0 becomes 255 on loading; stored annotation pixels remain unchanged.
The Dataset uses the workspace's `data/processed/catalog.parquet`; no arbitrarypath or filename-glob settings are needed. The catalog records the paired assets.Training can include both annotation sources or only experts. Shared scene IDs arenot silently deduplicated. Validation selects one published composite; test usesits supplied human annotation band.
```yamldata: include_non_expert: true validation_composite: consensus target: land_cover```
`validation_composite` accepts `strict`, `simple_majority`, `majority`, and`consensus`. It applies only to validation. EDA will explain and compare thesealternatives rather than selecting a winner automatically.
## Metadata
The downloader includes `v1_dw_tile_metadata_for_public_release.xlsx` from the[PANGAEA release](https://doi.pangaea.de/10.1594/PANGAEA.933475).Validation contains two XLSX files, including individual expert annotations for EDA.The [test release](https://zenodo.org/records/4766508) supplies `meta.csv`.
Source column names and values are retained, including labeler, hemisphere, biome,class statistics, dates and original Sentinel-2 references. The sole spatial-namemapping is `geometry` → `source_geometry`: it preserves the original local-CRS WKTalongside `crs`, while GeoParquet's active geometry contains the geographic footprint.Metadata joins use annotation source and identifier, preserving expert/non-expertrecords with the same scene ID. CSV `filename` remains `filename`.
Additional provenance columns use plain names: `annotation_source`, `split`,`raw_label`, `validation_composite`, and the actual retrieved imagery IDs and dates.There is no invented metadata namespace.
## Commands
Run from this workspace with the current GeoSave development environment:
```bashpython scripts/download_dynamic_world.py --subset expertspython scripts/download_dynamic_world.py --subset validationpython scripts/download_dynamic_world.py --subset testpython main.py fit --config configs/dinov3-base-dpt.yaml```
Each training configuration is passed directly to LightningCLI. Resume with thesaved Lightning configuration and `--ckpt_path`; no custom launcher is required.Existing configurations are retained as drafts, not an approved experiment matrix.The bundled wheel and lock have not been rebuilt for this foundation change.
## Existing data and remaining work
The existing prepared catalog uses the obsolete `dw:*` schema and custom geographicsplits, including `processed/excluded`. It has deliberately not been migrated,rewritten or deleted. Dataset construction and ingestion reject that legacy catalog.New ingestion can be inspected separately using `--out` pointing to a fresh folder;replacing the canonical prepared corpus is a separate decision.
Source `experts` and `non_expert` belong to train, `validation` to val, and `test` totest. These are source memberships, **not independent evaluation cohorts**: sceneidentifiers overlap. Do not use these memberships to claim held-out performance.No hashed geographic split or exclusion policy is applied by new ingestion.
Training random crops, validation/test-only chipping, merged-logit evaluation,evaluation membership, notebook revisions and final model configurations remainnext steps. The current sample reader still chips all splits, and the currentmodule still scores chips. This foundation is not yet the agreed training pipeline.
Focused regression checks (from the parent GeoSave checkout):
```bash.venv/bin/python -m pytest workspace/dynamicworld/tests --confcutdir=workspace/dynamicworld/tests```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141seed_everything: 42model_name: clay-large-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: clay-large-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: clay init_args: pretrained: true input_size: 224 model_name: clay_v15_large in_channels: 10 waves: - 0.493 - 0.56 - 0.665 - 0.704 - 0.74 - 0.783 - 0.842 - 0.865 - 1.61 - 2.19 gsd: 10.0 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B02 - B03 - B04 - B05 - B06 - B07 - B08 - B8A - B11 - B12 mean: - 0.1105 - 0.1355 - 0.1552 - 0.1887 - 0.2422 - 0.263 - 0.2743 - 0.2785 - 0.2388 - 0.1835 std: - 0.1809 - 0.1757 - 0.1888 - 0.187 - 0.1732 - 0.1697 - 0.1742 - 0.1648 - 0.147 - 0.1379 context: clay123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-7b-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-7b-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_7b_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-7b-sat-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-7b-sat-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_7b_patch16_dinov3.sat493m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.43 - 0.411 - 0.296 std: - 0.213 - 0.156 - 0.143123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-base-dpt-cutmixtrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-dpt-cutmix version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.5 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108seed_everything: 42model_name: dinov3-base-dpt-expertstrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-dpt-experts version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 include_non_expert: false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-base-dpt-googletrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-dpt-google version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 9 hidden_channels: null dropout: 0.1 target: google criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: google augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-base-dpt-lr-lowtrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-dpt-lr-low version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.0003 weight_decay: 0.01 groups: encoder: lr: 3.0e-05 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899seed_everything: 42model_name: dinov3-base-dpt-noaugtrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-dpt-noaug version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: [] cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-base-dpt-ohemtrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-dpt-ohem version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: ohem init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114seed_everything: 42model_name: dinov3-base-dpt-rotatetrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-dpt-rotate version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false - name: RandomRotation90 init_args: times: - 1 - 3 p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-base-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-base-qkvb-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-qkvb-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3_qkvb.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-base-unettrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-base-unet version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_base_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: unet init_args: decoder_channels: - 256 - 128 - 64 - 32 use_norm: true vit_adapter: true head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-huge-plus-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-huge-plus-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_huge_plus_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-huge-plus-qkvb-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-huge-plus-qkvb-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_huge_plus_patch16_dinov3_qkvb.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-large-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-large-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_large_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-large-qkvb-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-large-qkvb-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_large_patch16_dinov3_qkvb.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-large-qkvb-sat-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-large-qkvb-sat-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_large_patch16_dinov3_qkvb.sat493m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.43 - 0.411 - 0.296 std: - 0.213 - 0.156 - 0.143123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-large-sat-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-large-sat-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_large_patch16_dinov3.sat493m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.43 - 0.411 - 0.296 std: - 0.213 - 0.156 - 0.143123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-small-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-small-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_small_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-small-plus-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-small-plus-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_small_plus_patch16_dinov3.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-small-plus-qkvb-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-small-plus-qkvb-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_small_plus_patch16_dinov3_qkvb.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107seed_everything: 42model_name: dinov3-small-qkvb-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: dinov3-small-qkvb-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: dinov3 init_args: pretrained: true input_size: 224 model_name: vit_small_patch16_dinov3_qkvb.lvd1689m in_channels: 3 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B04 - B03 - B02 mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.2251234567891011121314151617181920212223242526272829schema_version: 2# The 10 m and 20 m bands the Dynamic World model reads (Brown et al., 2022).rasters: sentinel_2_l2a: variables: [B02, B03, B04, B05, B06, B07, B08, B11, B12] coordinates: [x, y] require_crs: true stac: collection: sentinel-2-l2a endpoints: [planetary_computer] load: bands: [B02, B03, B04, B05, B06, B07, B08, B11, B12] dtype: uint16 nodata: 0# Planetary Computer publishes no scale or offset. Labels date from 2017-2019,# before processing baseline 04.00 added an offset of -0.1 in January 2022.preprocessing: packed: call: !ref sentinel_2_l2a.gs.write_packing kwargs: {scale_factor: 0.0001} image: call: !ref packed.gs.mask_and_scalechips: size: 224 overlap: 32 mode: reflect window: hanninputs: image: !ref image123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124seed_everything: 42model_name: prithvi-v1-100-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: prithvi-v1-100-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: prithvi init_args: pretrained: true input_size: 224 model_name: prithvi_eo_v1_100 bands: - BLUE - GREEN - RED - NIR_NARROW - SWIR_1 - SWIR_2 num_frames: 1 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B02 - B03 - B04 - B8A - B11 - B12 mean: - 0.0775 - 0.1081 - 0.1229 - 0.2497 - 0.2204 - 0.1611 std: - 0.1282 - 0.127 - 0.1399 - 0.1368 - 0.1292 - 0.1155 temporal: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124seed_everything: 42model_name: prithvi-v2-300-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: prithvi-v2-300-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: prithvi init_args: pretrained: true input_size: 224 model_name: prithvi_eo_v2_300 bands: - BLUE - GREEN - RED - NIR_NARROW - SWIR_1 - SWIR_2 num_frames: 1 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B02 - B03 - B04 - B8A - B11 - B12 mean: - 0.1087 - 0.1342 - 0.1433 - 0.2734 - 0.1958 - 0.1363 std: - 0.2248 - 0.2179 - 0.2178 - 0.185 - 0.1242 - 0.1049 temporal: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125seed_everything: 42model_name: prithvi-v2-300-tl-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: prithvi-v2-300-tl-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: prithvi_tl init_args: pretrained: true input_size: 224 model_name: prithvi_eo_v2_300_tl bands: - BLUE - GREEN - RED - NIR_NARROW - SWIR_1 - SWIR_2 num_frames: 1 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B02 - B03 - B04 - B8A - B11 - B12 mean: - 0.1087 - 0.1342 - 0.1433 - 0.2734 - 0.1958 - 0.1363 std: - 0.2248 - 0.2179 - 0.2178 - 0.185 - 0.1242 - 0.1049 temporal: true context: prithvi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124seed_everything: 42model_name: prithvi-v2-600-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: prithvi-v2-600-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: prithvi init_args: pretrained: true input_size: 224 model_name: prithvi_eo_v2_600 bands: - BLUE - GREEN - RED - NIR_NARROW - SWIR_1 - SWIR_2 num_frames: 1 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B02 - B03 - B04 - B8A - B11 - B12 mean: - 0.1087 - 0.1342 - 0.1433 - 0.2734 - 0.1958 - 0.1363 std: - 0.2248 - 0.2179 - 0.2178 - 0.185 - 0.1242 - 0.1049 temporal: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125seed_everything: 42model_name: prithvi-v2-600-tl-dpttrainer: accelerator: gpu devices: 1 precision: 16-mixed max_epochs: 50 deterministic: warn log_every_n_steps: 10 logger: class_path: lightning.pytorch.loggers.TensorBoardLogger init_args: save_dir: artifacts/runs name: prithvi-v2-600-tl-dpt version: null callbacks: - class_path: lightning.pytorch.callbacks.ModelCheckpoint init_args: monitor: val_iou_macro mode: max save_top_k: 1 save_last: true filename: epoch{epoch:03d}-iou{val_iou_macro:.4f} auto_insert_metric_name: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val_iou_macro mode: max patience: 10 - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epochmodel: model_chain: encoder: name: prithvi_tl init_args: pretrained: true input_size: 224 model_name: prithvi_eo_v2_600_tl bands: - BLUE - GREEN - RED - NIR_NARROW - SWIR_1 - SWIR_2 num_frames: 1 decoder: name: dpt init_args: readout: cat intermediate_channels: - 128 - 256 - 512 - 512 fusion_channels: 128 head: name: segmentation init_args: num_classes: 8 hidden_channels: null dropout: 0.1 target: land_cover criterion: name: cross_entropy init_args: ignore_index: 255 optimizer: name: adamw init_args: lr: 0.001 weight_decay: 0.01 groups: encoder: lr: 0.0001 lr_scheduler: name: cosine_annealing init_args: T_max: 50 eta_min: 1.0e-06 interval: epoch metrics: - iou.macro - iou.per_class - f1.macrodata: size: 224 target: land_cover augmentations: - name: RandomHorizontalFlip init_args: p: 0.5 same_on_batch: false - name: RandomVerticalFlip init_args: p: 0.5 same_on_batch: false cutmix: 0.0 batch_size: 8 num_workers: 4 bands: - B02 - B03 - B04 - B8A - B11 - B12 mean: - 0.1087 - 0.1342 - 0.1433 - 0.2734 - 0.1958 - 0.1363 std: - 0.2248 - 0.2179 - 0.2178 - 0.185 - 0.1242 - 0.1049 temporal: true context: prithvi123456789from geosave.ml.cli import GeosaveCLIif __name__ == "__main__":GeosaveCLI(auto_configure_optimizers=False,subclass_mode_model=True,subclass_mode_data=True,)12345678910111213"""Run a complete experiment configuration through GeoSave's LightningCLI."""from geosave.ml.cli import GeosaveCLIfrom modules.segmentation.supervised.data import DataModulefrom modules.segmentation.supervised.module import Moduleif __name__ == "__main__":GeosaveCLI(Module,DataModule,auto_configure_optimizers=False,save_config_kwargs={"overwrite": True},)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Batch segmentation samples, augment paired pixels, then normalize."""
from typing import Literal
from lightning import LightningDataModulefrom torch.utils.data import DataLoader
from geosave.ml.transforms import ImageAugmenter, CutMixfrom geosave.model.processing import normalize
from .datasets import DynamicWorld, read_target
class DataModule(LightningDataModule): """Configure bands, normalization and optional encoder context for training."""
def __init__( self, bands: list[str], mean: list[float] | None = None, std: list[float] | None = None, context: Literal["clay", "prithvi"] | None = None, temporal: bool = False, size: int = 256, target: str = "land_cover", include_non_expert: bool = True, validation_composite: Literal[ "strict", "simple_majority", "majority", "consensus" ] = "consensus", cutmix: float = 0.0, batch_size: int = 8, num_workers: int = 0, augmentations: list[dict] | None = None, ): super().__init__() self.save_hyperparameters()
if cutmix and context is not None: raise ValueError("CutMix mixes scenes and cannot preserve time/location") if (mean is None) != (std is None): raise ValueError("Supply both mean and std for normalization")
self.datasets = {} self.ignore_index = read_target(target)["ignore_index"] self.augmenter = ImageAugmenter(augmentations or [], size) self.cutmix = CutMix(cutmix)
def setup(self, stage: str | None = None): splits = { None: ("train", "val", "test"), "fit": ("train", "val"), "validate": ("val",), "test": ("test",), } for split in splits[stage]: self.datasets[split] = DynamicWorld( split, bands=self.hparams.bands, size=self.hparams.size, target=self.hparams.target, context=self.hparams.context, include_non_expert=self.hparams.include_non_expert, validation_composite=self.hparams.validation_composite, )
def _loader(self, split, shuffle=False): workers = self.hparams.num_workers
return DataLoader( self.datasets[split], batch_size=self.hparams.batch_size, shuffle=shuffle, num_workers=workers, persistent_workers=workers > 0, multiprocessing_context="spawn" if workers else None, )
def train_dataloader(self): return self._loader("train", shuffle=True)
def val_dataloader(self): return self._loader("val")
def test_dataloader(self): return self._loader("test")
def on_after_batch_transfer(self, batch, dataloader_idx): image, target = batch["image"], batch["target"]
if self.trainer is not None and self.trainer.training: # Reserve zero for ignored labels and borders introduced by rotation. mask = (target + 1).masked_fill(target == self.ignore_index, 0).float() image, mask = self.augmenter(image, mask, data_keys=["input", "mask"]) target = mask.round().long() - 1 target = target.masked_fill(target < 0, self.ignore_index) image, target = self.cutmix(image, target)
# Normalize after augmentation. Prithvi expects a one-frame time axis. if self.hparams.mean is not None: image = normalize( image, mean=self.hparams.mean, std=self.hparams.std, dim=-3 ) if self.hparams.temporal: image = image.unsqueeze(1)
return {**batch, "image": image, "target": target}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Paired TIFFs become segmentation samples through GeoSave Chips."""
from pathlib import Pathfrom typing import Literal
import geopandas as gpdimport numpy as npimport pandas as pdimport torchimport yamlimport xarray as xrfrom torch.utils.data import Dataset
import geosave as gs
DATA = Path(__file__).resolve().parents[3] / "data"
def read_target(name: str) -> dict: """Read class names, colors and label remapping from data/labels.yaml.""" return yaml.safe_load((DATA / "labels.yaml").read_text())[name]
class DynamicWorld(Dataset): """Select prepared annotations and remap source codes when reading samples.
Source splits describe the releases, not independent evaluation cohorts. Training crops and stitched evaluation are a separate implementation step. """
def __init__( self, split: Literal["train", "val", "test"], bands: list[str], size: int = 256, target: str = "land_cover", context: Literal["clay", "prithvi"] | None = None, include_non_expert: bool = True, validation_composite: Literal[ "strict", "simple_majority", "majority", "consensus" ] = "consensus", ): catalog = DATA / "processed" / "catalog.parquet" records = gpd.read_parquet(catalog) if "dw:split" in records: raise ValueError( "The legacy catalog uses an obsolete split policy. " "Preserve it and prepare a new source-metadata catalog first." )
records = records.loc[records["split"] == split] if split == "train" and not include_non_expert: records = records.loc[records["labeler"] == "Experts"] if split == "val": records = records.loc[ records["validation_composite"] == validation_composite ] if records.empty: raise ValueError(f"No prepared annotations match {split!r}")
self.records = records.reset_index(drop=True) self.context = context self.policy = read_target(target) self.ignore_index = self.policy["ignore_index"] self.lookup = torch.full((256,), self.ignore_index, dtype=torch.long) for source, destination in self.policy["remap"].items(): self.lookup[source] = destination
images = [] labels = [] for assets in self.records["assets"]: path = catalog.parent / assets["image"]["href"] label_path = catalog.parent / assets["label"]["href"] with ( gs.open_raster(path, chunks=None, mask_and_scale=True) as image, gs.open_raster(label_path, chunks=None) as label, ): if image.gs.geobox != label.gs.geobox: raise ValueError(f"image/label grid mismatch: {path.name}")
# Derived arrays retain lazy backend indexing; workers reopen files. images.append(image[bands]) labels.append(label[list(label.data_vars)])
# Chips owns window indexing, reads and padding for both aligned sources. self.images = gs.Chips( images, size=size, constant_value=np.nan, dtype="float32" ) self.labels = gs.Chips(labels, size=size, constant_value=0)
def __len__(self): return len(self.images)
def __getitem__(self, index): image = torch.from_numpy(self.images[index]) raw = torch.from_numpy(self.labels[index][0]).long() target = self.lookup[raw]
target[~torch.isfinite(image).all(dim=0)] = self.ignore_index image = image.nan_to_num(nan=0, posinf=0, neginf=0) sample = {"image": image, "target": target}
if self.context is not None: # Context uses the chip's grid and the image's actual acquisition time. scene, _ = self.images.key(index) when = pd.Timestamp(self.images.xarray[scene].attrs["acquisition_time"]) raster = xr.Dataset(coords={"time": when.to_datetime64()}) raster = raster.gs.write_extent(self.images.geobox(index).extent) if self.context == "clay": from geosave.model.stages.encoder.clay import model_context else: from geosave.model.stages.encoder.prithvi import model_context
sample.update(model_context(raster))
return sample123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Project-owned supervised recipe using GeoSave's training builders."""
from copy import deepcopy
import torchfrom lightning import LightningModulefrom torchmetrics import MeanMetric
from geosave.ml.builders import build_criterion, build_optimizer, build_schedulerfrom geosave.ml.metrics import MulticlassMetricsfrom geosave.model.registry import build_model
from .datasets import read_target
class Module(LightningModule): """Train a configured model on flat image, context, and target batches."""
def __init__( self, model_chain: dict, target: str = "land_cover", criterion: dict | None = None, optimizer: dict | None = None, lr_scheduler: dict | None = None, metrics: list[str] | None = None, policy: dict | None = None, ): super().__init__() policy = read_target(target) if policy is None else deepcopy(policy) criterion = deepcopy(criterion or {"name": "cross_entropy"}) optimizer = optimizer or {"name": "adamw", "init_args": {"lr": 1e-3}} metrics = metrics or ["iou.macro.per_class", "f1.macro"] self.save_hyperparameters() self.policy = policy self.ignore_index = policy["ignore_index"] self.num_classes = len(policy["class_map"])
# Loss and metrics share the Dataset's ignored label value. options = criterion.setdefault("init_args", {}) options["ignore_index"] = self.ignore_index self.criterion = build_criterion(criterion)
def configure_model(self): """Build the chain and metrics in Lightning's model construction hook.""" if hasattr(self, "model"): return self.model = build_model(deepcopy(self.hparams.model_chain)) last = list(self.hparams.model_chain)[-1] if self.model.get_submodule(last).num_classes != self.num_classes: raise ValueError("head num_classes must match the label policy") metrics = MulticlassMetrics( self.num_classes, ignore_index=self.ignore_index, labels=list(self.policy["class_map"].values()), metrics=self.hparams.metrics, ) self.train_metrics = metrics.clone(prefix="train_") self.val_metrics = metrics.clone(prefix="val_") self.test_metrics = metrics.clone(prefix="test_") self.train_loss = MeanMetric() self.val_loss = MeanMetric() self.test_loss = MeanMetric()
def configure_optimizers(self): optimizer = build_optimizer(self.hparams.optimizer, self.model) if self.hparams.lr_scheduler is None: return optimizer return { "optimizer": optimizer, "lr_scheduler": build_scheduler(self.hparams.lr_scheduler, optimizer), }
def forward(self, **inputs): return self.model(**inputs)
def on_load_checkpoint(self, checkpoint): if checkpoint["hyper_parameters"]["policy"] != self.policy: raise ValueError("Cannot resume with a different target policy")
def setup(self, stage): if self.trainer.world_size != 1: raise ValueError("These experiments support one training device") for dataset in self.trainer.datamodule.datasets.values(): if dataset.policy != self.policy: raise ValueError("Dataset and model target policies differ")
def _step(self, batch, stage): target = batch["target"] count = target.ne(self.ignore_index).sum() if count == 0: # Skip optimization too: AdamW would otherwise decay parameters. return None inputs = {name: value for name, value in batch.items() if name != "target"} logits = self(**inputs) loss = self.criterion(logits, target) if getattr(self.criterion, "reduction", None) == "sum": loss = loss / count
# Weight epoch loss by usable pixels, so padded windows do not dominate. getattr(self, f"{stage}_metrics").update(logits, target) getattr(self, f"{stage}_loss").update(loss.detach(), weight=count) return loss
def _log_epoch(self, stage): metrics = getattr(self, f"{stage}_metrics") average = getattr(self, f"{stage}_loss") loss = average.compute() if not torch.isfinite(loss): raise ValueError(f"{stage} epoch has no usable labels or a nonfinite loss") self.log(f"{stage}_loss", loss, on_epoch=True) for name, value in metrics.compute().items(): self.log(name, value, on_epoch=True, prog_bar=name == "val_iou_macro") with torch.inference_mode(False): metrics.reset() average.reset()
def training_step(self, batch, batch_idx): return self._step(batch, "train")
def validation_step(self, batch, batch_idx): return self._step(batch, "val")
def test_step(self, batch, batch_idx): return self._step(batch, "test")
def predict_step(self, batch, batch_idx): inputs = {name: value for name, value in batch.items() if name != "target"} return self(**inputs)
def on_train_epoch_end(self): self._log_epoch("train")
def on_validation_epoch_end(self): self._log_epoch("val")
def on_test_epoch_end(self): self._log_epoch("test")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245absl-py==2.4.0aenum==3.1.17affine==2.4.0aiohappyeyeballs==2.6.1aiohttp==3.13.5aiosignal==1.4.0albucore==0.0.24albumentations==2.0.8annotated-doc==0.0.4annotated-types==0.7.0antlr4-python3-runtime==4.9.3anyio==4.13.0arro3-core==0.9.0asttokens==3.0.1attrs==26.1.0bokeh==3.10.1cachetools==7.0.6cartopy==0.26.0certifi==2026.4.22cftime==1.6.5charset-normalizer==3.4.7ciso8601==2.3.3click==8.3.3cligj==0.7.2cloudpickle==3.1.2colorcet==3.2.1comm==0.2.3contourpy==1.3.3cql2==0.5.6cuda-bindings==13.2.0cuda-pathfinder==1.5.4cuda-toolkit==13.0.2cycler==0.12.1dask==2026.3.0dataclasses-json==0.6.7datashader==0.19.1debugpy==1.8.22decorator==5.3.1diffusers==0.37.1docstring-parser==0.18.0donfig==0.8.1.post1einops==0.7.0et-xmlfile==2.0.0executing==2.2.1fastjsonschema==2.22.2filelock==3.29.0fonttools==4.62.1frozenlist==1.8.0fsspec==2026.3.0geographiclib==2.1geopandas==1.1.3geopy==2.4.1./artifacts/dependencies/geosave-0.3.0-py3-none-any.whlgeoviews==1.15.1google-crc32c==1.8.0grpcio==1.84.0h11==0.16.0h5py==3.16.0hf-xet==1.4.3holoviews==1.23.2httpcore==1.0.9httpx==0.28.1huggingface-hub==1.12.0hvplot==0.12.2hydra-core==1.3.2idna==3.18imageio==2.37.3importlib-metadata==8.7.1importlib-resources==7.1.0ipykernel==7.4.0ipython==9.15.0ipython-pygments-lexers==1.1.1ipywidgets==8.1.8jedi==0.20.0jinja2==3.1.6joblib==1.5.3jsonargparse==4.48.0jsonschema==4.26.0jsonschema-specifications==2025.9.1jupyter-bokeh==4.1.0jupyter-client==8.10.0jupyter-core==5.9.1jupyterlab-widgets==3.0.16kiwisolver==1.5.0kornia==0.8.2kornia-rs==0.1.10lazy-loader==0.5lightgbm==4.6.0lightly==1.5.22lightly-utils==0.0.2lightning==2.6.1lightning-utilities==0.15.3linkify-it-py==2.2.0llvmlite==0.50.0locket==1.0.0markdown==3.10.2markdown-it-py==4.0.0markupsafe==3.0.3marshmallow==3.26.2matplotlib==3.10.9matplotlib-inline==0.2.2mdit-py-plugins==0.6.1mdurl==0.1.2mpmath==1.3.0multidict==6.7.1multipledispatch==1.0.0mypy-extensions==1.1.0narwhals==2.25.0nbclient==0.11.0nbformat==5.11.1nest-asyncio2==1.7.4netcdf4==1.7.4networkx==3.6.1nh3==0.3.7numba==0.68.0numcodecs==0.16.5numpy==2.4.4nvidia-cublas==13.1.0.3nvidia-cuda-cupti==13.0.85nvidia-cuda-nvrtc==13.0.88nvidia-cuda-runtime==13.0.96nvidia-cudnn-cu13==9.19.0.56nvidia-cufft==12.0.0.61nvidia-cufile==1.15.1.6nvidia-curand==10.4.0.35nvidia-cusolver==12.0.4.66nvidia-cusparse==12.6.3.3nvidia-cusparselt-cu13==0.8.0nvidia-nccl-cu13==2.28.9nvidia-nvjitlink==13.0.88nvidia-nvshmem-cu13==3.4.5nvidia-nvtx==13.0.85oauthlib==3.3.1odc-geo==0.5.1odc-loader==0.6.4odc-stac==0.5.2omegaconf==2.3.0opencv-python-headless==4.13.0.92openpyxl==3.1.5orjson==3.12.0packaging==26.2pandas==2.3.3panel==1.10.0panel-material-ui==0.16.6param==2.4.2parso==0.8.7partd==1.4.2pathlib-abc==0.5.2pexpect==4.9.0pillow==12.2.0planetary-computer==1.0.0platformdirs==4.9.6prompt-toolkit==3.0.52propcache==0.4.1protobuf==6.33.6psutil==7.2.2ptyprocess==0.7.0pure-eval==0.2.3pyarrow==23.0.1pycocotools==2.0.11pyct==0.6.0pydantic==2.13.3pydantic-core==2.46.3pygments==2.20.0pyogrio==0.12.1pyparsing==3.3.2pyproj==3.7.2pyshp==3.1.6pystac==1.14.3pystac-client==0.9.0python-box==7.4.1python-dateutil==2.9.0.post0python-dotenv==1.2.2pytorch-lightning==2.6.1pytz==2026.1.post1pyviz-comms==3.0.6pyyaml==6.0.3pyzmq==27.2.0questionary==2.1.1rasterio==1.5.0referencing==0.37.0regex==2026.5.9requests==2.33.1requests-oauthlib==2.0.0retrying==1.4.2rich==15.0.0rioxarray==0.22.0rpds-py==0.30.0rustac==0.9.17s2cloudless==1.7.3safetensors==0.8.0scikit-image==0.26.0scikit-learn==1.8.0scipy==1.17.1segmentation-models-pytorch==0.5.0sentinelhub==3.11.5setuptools==81.0.0shapely==2.1.2shellingham==1.5.4simsimd==6.5.16six==1.17.0spatialpandas==0.6.0stac-geoparquet==0.8.2stack-data==0.6.3stringzilla==4.6.0sympy==1.14.0tacoreader==0.5.6tensorboard==2.20.0tensorboard-data-server==0.7.2termcolor==3.3.0terratorch==1.2.7threadpoolctl==3.6.0tifffile==2026.4.11tiler==0.6.0timm==1.0.26tomli==2.4.1tomli-w==1.2.0tomlkit==0.15.1toolz==1.1.0torch==2.11.0torchgeo==0.9.0torchmetrics==1.9.0torchvision==0.26.0tornado==6.5.8tqdm==4.67.3traitlets==5.15.1triton==3.6.0typer==0.25.0types-psutil==7.2.2.20260906typeshed-client==2.10.0typing-extensions==4.15.0typing-inspect==0.9.0typing-inspection==0.4.2tzdata==2026.2universal-pathlib==0.3.10urllib3==2.6.3utm==0.8.1wcwidth==0.8.2werkzeug==3.1.8widgetsnbextension==4.0.15xarray==2026.4.0xyzservices==2026.9.1yarl==1.23.0zarr==3.2.1zipp==3.23.1123456789101112aiohappyeyeballs==2.7.1aiohttp==3.14.5aiosignal==1.4.0attrs==26.1.0frozenlist==1.8.0fsspec==2026.9.0idna==3.20multidict==7.1.0propcache==0.5.4tqdm==4.70.1typing_extensions==4.16.0yarl==1.25.112345678910111213141516171819# Install from the workspace root. The wheel captures the tested local GeoSave source../artifacts/dependencies/geosave-0.3.0-py3-none-any.whl[ml]lightning==2.6.1torch==2.11.0torchmetrics==1.9.0tensorboard==2.20.0rasterio==1.5.0numpy==2.4.4pandas==2.3.3pyyaml==6.0.3typer==0.25.0fsspec==2026.3.0aiohttp==3.13.5tqdm==4.67.3openpyxl==3.1.5nbformat==5.11.1nbclient==0.11.0ipykernel==7.4.0jsonargparse[signatures]==4.48.0
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Check prepared pairs without claiming that source splits are independent."""
from pathlib import Path
import geopandas as gpdimport numpy as npimport rasterioimport typer
from ingest_dynamic_world import BANDS
ROOT = Path(__file__).resolve().parents[1] / "data" / "processed"
def main(root: Path = ROOT): """Check grids, unchanged annotation pixels and readable image assets.""" catalog = gpd.read_parquet(root / "catalog.parquet") if "dw:split" in catalog: raise ValueError("Preserve the legacy catalog; prepare source metadata first")
raw = ROOT.parent / "raw" for _, row in catalog.iterrows(): image_path = root / row["assets"]["image"]["href"] label_path = root / row["assets"]["label"]["href"] original_path = raw / row["raw_label"]
with rasterio.open(image_path) as image, rasterio.open(label_path) as label: grid = (label.crs, label.transform, label.shape) if (image.crs, image.transform, image.shape) != grid: raise ValueError(f"image/label grid mismatch: {image_path}")
for source in (image, label): if source.tags(ns="IMAGE_STRUCTURE").get("LAYOUT") != "COG": raise ValueError(f"not a COG: {source.name}") if list(image.descriptions) != BANDS: raise ValueError(f"unexpected band order: {image_path}") if not np.allclose(image.res, (10, 10)): raise ValueError(f"not a 10 m grid: {image_path}")
scales = [] offsets = [] for band in BANDS: scale, offset = row["calibration"][band] scales.append(scale) offsets.append(offset) if not np.allclose(image.scales, scales) or not np.allclose( image.offsets, offsets ): raise ValueError(f"calibration differs from catalog: {image_path}") if set(row["source_datetimes"]) != {image.tags().get("acquisition_time")}: raise ValueError(f"acquisition time differs from source: {image_path}")
values = label.read(1) if not np.isin(values, range(11)).all(): raise ValueError(f"unexpected source label codes: {label_path}") with rasterio.open(original_path) as original: band = 2 if original.count == 2 else 1 if (original.crs, original.transform, original.shape) != grid: raise ValueError(f"annotation grid changed: {label_path}") if not np.array_equal(values, original.read(band)): raise ValueError(f"annotation pixels changed: {label_path}")
print(catalog.groupby(["split", "annotation_source"]).size()) print("Source membership only; evaluation independence remains unresolved.")
if __name__ == "__main__": typer.run(main)12345678910111213141516174 unmodified lines2223242526272810 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273"""Download every Dynamic World label release.uv run python workspace/scripts/download_dynamic_world.pywrites workspace/data/dynamic_world_raw/<subset>/; a subset already downloadedis skipped. Each label is extracted straight from the remote archive, so thetest release's model probabilities, 3.9 of its 3.9 GB, are never fetched."""import timefrom pathlib import Pathfrom zipfile import ZipFile, ZipInfoimport fsspecfrom aiohttp import ClientResponseErrorfrom tqdm import tqdm4 unmodified lines"validation": f"{PANGAEA}/validation_set_tiles.zip","test": "https://zenodo.org/records/4766508/files/dw_test.zip?download=1",}RAW = Path(__file__).resolve().parents[1] / "data" / "dynamic_world_raw"def extract(files: ZipFile, member: ZipInfo, folder: Path) -> None:10 unmodified linesdef download(url: str, folder: Path) -> None:"""Extract the archive's labels, reading only their bytes over HTTP ranges."""partial = folder.with_suffix(".partial")# Labels are tens of kilobytes, so small range reads fetch little else.remote = fsspec.filesystem("https").open(url, block_size=2**16)with remote, ZipFile(remote) as files:members = []# In archive order, neighbouring labels can share one range read.for member in sorted(files.infolist(), key=lambda info: info.header_offset):# macOS resource forks mirror every tile as `__MACOSX/.../._<tile>.tif`;# the test release keeps model probabilities, `probs_*`, beside its labels.if member.is_dir() or member.filename.startswith("__MACOSX"):continueif Path(member.filename).name.startswith("probs_"):continuemembers.append(member)size = sum(member.compress_size for member in members)with tqdm(total=size, unit="B", unit_scale=True, desc=folder.name) as bar:for member in members:extract(files, member, partial)bar.update(member.compress_size)partial.rename(folder)if __name__ == "__main__":RAW.mkdir(parents=True, exist_ok=True)for subset, url in URLS.items():folder = RAW / subsetif folder.exists():print(f"already downloaded: {folder}")continuedownload(url, folder)1234567891011121314151617181920214 unmodified lines2627282930313210 unmodified lines434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Download every Dynamic World label release.uv run python workspace/dynamicworld/scripts/download_dynamic_world.pywrites workspace/dynamicworld/data/raw/<subset>/; a subset already downloadedis skipped. Each label is extracted straight from the remote archive, so thetest release's model probabilities, 3.9 of its 3.9 GB, are never fetched."""import timefrom tempfile import TemporaryDirectoryimport requestsfrom pathlib import Pathfrom zipfile import ZipFile, ZipInfoimport fsspecimport typerfrom aiohttp import ClientResponseErrorfrom tqdm import tqdm4 unmodified lines"validation": f"{PANGAEA}/validation_set_tiles.zip","test": "https://zenodo.org/records/4766508/files/dw_test.zip?download=1",}RAW = Path(__file__).resolve().parents[1] / "data" / "raw"def extract(files: ZipFile, member: ZipInfo, folder: Path) -> None:10 unmodified linesdef download(url: str, folder: Path) -> None:"""Download annotation archives; range-read only the probability-heavy test ZIP."""partial = folder.with_suffix(".partial")with TemporaryDirectory(dir=folder.parent) as temporary:if "dw_test.zip" in url:remote = fsspec.filesystem("https").open(url, block_size=2**16)else:archive = Path(temporary) / "labels.zip"with requests.get(url, stream=True, timeout=120) as response:response.raise_for_status()with archive.open("wb") as output:for chunk in response.iter_content(2**20):output.write(chunk)remote = archive.open("rb")with remote, ZipFile(remote) as files:members = []for member in files.infolist():if member.is_dir() or member.filename.startswith("__MACOSX"):continueif Path(member.filename).name.startswith("probs_"):continuemembers.append(member)for member in tqdm(members, desc=folder.name, unit="file"):extract(files, member, partial)partial.rename(folder)def download_metadata(raw: Path) -> None:"""Fetch the separately published training workbook and source README."""for name in ("v1_dw_tile_metadata_for_public_release.xlsx", "README.txt"):path = raw / nameif path.exists():continuepartial = path.with_suffix(path.suffix + ".partial")with requests.get(f"{PANGAEA}/{name}", stream=True, timeout=120) as response:response.raise_for_status()with partial.open("wb") as output:for chunk in response.iter_content(2**20):output.write(chunk)partial.replace(path)def main(raw: Path = RAW, subset: str | None = None) -> None:"""Download all releases, or one named subset, into RAW."""if subset is not None and subset not in URLS:raise typer.BadParameter(f"choose one of {', '.join(URLS)}")raw.mkdir(parents=True, exist_ok=True)download_metadata(raw)urls = URLS if subset is None else {subset: URLS[subset]}for name, url in urls.items():folder = raw / nameif folder.exists():print(f"already downloaded: {folder}")continuedownload(url, folder)if __name__ == "__main__":typer.run(main)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021037 unmodified lines111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237"""Pair each downloaded Dynamic World label with its Sentinel-2 scene.Run download_dynamic_world.py first, thenuv run python workspace/scripts/ingest_dynamic_world.py --threads 8writes <out>/<subset>/<id>/, one sample per label: the Sentinel-2 scene of thelabel's day as published, sentinel_2_l2a.tif with one band per variable, andthe label, label/label.tif, each listed in the sample's items.parquet. It also writesclasses.yaml, manifest.json recording each label as "ok" or its error, andcatalog.parquet listing every ingested sample. Label Items carry thereleases' own metadata as `dw:` properties, such as `dw:biome_name`, so thecatalog can be queried by them; reading the spreadsheets needs openpyxl. Arerun skips the "ok" labels and retries the rest."""import jsonimport refrom concurrent.futures import ThreadPoolExecutor, as_completedfrom pathlib import Pathimport numpy as npimport pandas as pdimport typerimport xarray as xrimport yamlfrom tqdm import tqdmimport geosave as gsfrom geosave.geodata import stac, treefrom geosave.geodata.stac import StacClient, StacSourceWORKSPACE = Path(__file__).resolve().parents[1]ITEMS = "items.parquet"# The image collection keeps the name the model spec declares.S2_COLLECTION = stac.create_collection("sentinel_2_l2a",description="Sentinel-2 Level-2A surface reflectance from Microsoft ""Planetary Computer, as published, on each label's grid and day.",license="proprietary",)DW_COLLECTION = stac.create_collection("label",description="Dynamic World land cover labels (Brown et al., 2022), ""remapped to start at 0 with no data as the ignore index.",license="CC-BY-4.0",)# The 10 m and 20 m bands the Dynamic World model reads (Brown et al., 2022).BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B11", "B12"]# Release codes, from the label README: 0 No data (left unmarked), 1 Water,# 2 Trees, 3 Grass, 4 Flooded Vegetation, 5 Crops, 6 Scrub, 7 Built Area,# 8 Bare Ground, 9 Snow/Ice, 10 Cloud. Remapped to start at 0, with no data# as the ignore index.IGNORE_INDEX = 255REMAP = {0: IGNORE_INDEX, 1: 0, 2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7, 9: 8, 10: 9}CLASS_MAP = {0: "water",1: "trees",2: "grass",3: "flooded_vegetation",4: "crops",5: "scrub",6: "built_area",7: "bare_ground",8: "snow_ice",9: "cloud",}COLOR_MAP = {0: "#419bdf",1: "#397d49",2: "#88b053",3: "#7a87c6",4: "#e49635",5: "#dfc35a",6: "#c4281b",7: "#a59b8f",8: "#b39fe1",9: "#d3d3d3",}def read_label(path: Path) -> xr.Dataset:label = gs.open_raster(path)# Test labels hold the model's prediction in band 1, the human label in band 2.band = "band_2" if "band_2" in label else "band_1"label = label[[band]].rename({band: "label"}).compute()lookup = np.full(256, IGNORE_INDEX, dtype="uint8")for code, index in REMAP.items():lookup[code] = indexlabel["label"].values = lookup[label["label"].values]# A date label covers its whole day, so the label's anchor searches that day.label = label.expand_dims(time=[read_date(path)])label = label.gs.write_nodata(IGNORE_INDEX)return label.gs.write_legend(CLASS_MAP, COLOR_MAP)7 unmodified linesreturn pd.Timestamp(match.group(1))def read_metadata(raw: Path) -> dict[str, dict]:"""Read the label metadata the releases ship, as Item properties by label id.The validation release describes its labels in two spreadsheets, the testrelease in meta.csv; the others ship none."""tables = []for path in sorted(raw.rglob("*.xlsx")):tables.append(pd.read_excel(path))for path in sorted(raw.rglob("meta.csv")):tables.append(pd.read_csv(path).rename(columns={"filename": "dw_id"}))metadata = {}for table in tables:# The outline and date repeat the Item's own geometry and datetime.table = table.drop(columns=["geometry", "date", "timestamp"], errors="ignore")for record in json.loads(table.to_json(orient="records")):label_id = record.pop("dw_id")metadata[label_id] = {f"dw:{name.lower()}": value for name, value in record.items()}return metadatadef ingest_label(source: StacSource, path: Path, folder: Path, item_id: str, properties: dict) -> None:"""Save the scene of the label's day on its grid, the label beside it, as Items.`item_id` names both Items; experts labelled some tiles more than once,so place and day do not. The label Item carries `properties`."""label = read_label(path)image = source.load(label.gs.anchor)# The raster keeps the collection name the model spec declares.images = tree({"sentinel_2_l2a": image}).gs.to_cog(f"{folder}/{{collection}}.tif", overwrite=True)labels = label.gs.to_cog(folder / "label" / "label.tif", overwrite=True)items = list(stac.create_items(images, id_format=item_id))for item in stac.create_items(labels, id_format=item_id, collection="label"):item.properties.update(properties)items.append(item)catalog = stac.create_catalog(items, collections=[S2_COLLECTION, DW_COLLECTION])catalog.gs.to_geoparquet(folder / ITEMS, overwrite=True)def write_catalog(out: Path, manifest: dict[str, str]) -> None:"""List every ingested sample in one item table."""items = []for key, status in tqdm(manifest.items(), desc="catalog", unit="label"):if status == "ok":sample = gs.open_vector(out / Path(key).with_suffix("") / ITEMS)items.extend(sample.gs.to_items())if items:catalog = stac.create_catalog(items, collections=[S2_COLLECTION, DW_COLLECTION])catalog.gs.to_geoparquet(out / "catalog.parquet", overwrite=True)def main(raw: Path = WORKSPACE / "data" / "dynamic_world_raw",out: Path = WORKSPACE / "data" / "dynamic_world",threads: int = 8,) -> None:"""Ingest every label under RAW into OUT, THREADS labels at a time."""# One reader per band, so a tile's bands arrive together.source = StacClient.planetary_computer().source("sentinel-2-l2a")source = source.set_config(bands=BANDS, chunks=None, dtype="uint16", nodata=0, pool=len(BANDS))out.mkdir(parents=True, exist_ok=True)classes = {"ignore_index": IGNORE_INDEX,"class_map": CLASS_MAP,"color_map": COLOR_MAP,}(out / "classes.yaml").write_text(yaml.safe_dump(classes, sort_keys=False))metadata = read_metadata(raw)manifest_path = out / "manifest.json"manifest = json.loads(manifest_path.read_text()) if manifest_path.exists() else {}# The test release keeps model probabilities, `probs_*`, beside its labels.pending = {}for path in sorted(raw.rglob("*.tif")):key = path.relative_to(raw).as_posix()if not path.name.startswith("probs_") and manifest.get(key) != "ok":pending[key] = pathwith ThreadPoolExecutor(threads) as pool:futures = {}for key, path in pending.items():folder = out / Path(key).with_suffix("")# Experts and non-experts labelled some of the same tiles, under# the same file name, so the subset keeps their Items apart.item_id = "_".join(folder.relative_to(out).parts)# Test labels are named `label_<id>`; their metadata names `<id>`.properties = metadata.get(path.stem.removeprefix("label_"), {})future = pool.submit(ingest_label, source, path, folder, item_id, properties)futures[future] = keyfor future in tqdm(as_completed(futures), total=len(futures), unit="label"):key = futures[future]try:future.result()manifest[key] = "ok"except Exception as error: # a scene Planetary Computer cannot servemanifest[key] = f"{type(error).__name__}: {error}"tqdm.write(f"{key}: {manifest[key]}")manifest_path.write_text(json.dumps(manifest, indent=2))write_catalog(out, manifest)if __name__ == "__main__":123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707 unmodified lines78798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411"""Download matching Sentinel-2 pixels for the local Dynamic World labels.uv run python workspace/dynamicworld/scripts/ingest_dynamic_world.py --threads 8Search each label's footprint and acquisition day, mosaic that day's matcheson its exact grid, and save matching TIFFs in train, val and test folders.Published digital numbers and band metadata are retained; training decodes scale and offset.The catalog records complete pairs; failures.csv records unsuccessful source matches."""import reimport randomfrom xml.etree import ElementTreeimport requestsimport rasteriofrom rasterio.shutil import copy as copy_rasterimport pystacfrom upath import UPathfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom pathlib import Pathfrom tempfile import TemporaryDirectoryimport numpy as npimport pandas as pdimport geopandas as gpdimport typerimport xarray as xrimport yamlfrom tqdm import tqdmimport geosave as gsfrom geosave.geodata.io import load_datasetfrom geosave.geodata.stac import StacClient, StacQuery, from_itemsfrom geosave.geodata.stac.asset import build_assetWORKSPACE = Path(__file__).resolve().parents[1]SPLITS = {"experts": "train","non_expert": "train","validation": "val","test": "test",}# The 10 m and 20 m bands the Dynamic World model reads (Brown et al., 2022).BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B11", "B12"]ORIGINAL = yaml.safe_load((WORKSPACE / "data" / "labels.yaml").read_text())["original"]CLASS_MAP = ORIGINAL["class_map"]COLOR_MAP = ORIGINAL["color_map"]def read_label(path: Path) -> xr.Dataset:"""Read the human annotation band without changing its class codes."""with gs.open_raster(path) as raster:# Test files put predictions first and human labels second.names = list(raster.data_vars)band = names[1] if len(names) == 2 else names[0]if len(names) not in (1, 2):raise ValueError(f"expected one or two label bands in {path}")label = raster[[band]].rename({band: "label"}).compute()if not np.isin(label["label"].values, list(CLASS_MAP)).all():raise ValueError(f"unknown label codes in {path}")label = label.expand_dims(time=[read_date(path)])label = label.gs.write_nodata(0)return label.gs.write_legend(CLASS_MAP, COLOR_MAP)7 unmodified linesreturn pd.Timestamp(match.group(1))def read_metadata(raw: Path) -> dict[tuple[str, str], dict]:"""Preserve release fields, keyed by source and annotation identifier.Source WKT is stored as source_geometry because GeoParquet geometry is thegeographic footprint. Source crs remains alongside the original WKT."""metadata = {}paths = sorted(raw.rglob("*.xlsx")) + sorted(raw.rglob("meta.csv"))for path in paths:if path.suffix == ".xlsx":table = pd.read_excel(path)else:table = pd.read_csv(path)table = table.rename(columns={"geometry": "source_geometry"})table = table.astype(object).where(table.notna(), None)for record in table.to_dict(orient="records"):for name, value in record.items():if isinstance(value, pd.Timestamp):record[name] = value.isoformat()if "labeler" in record:source = {"Experts": "experts", "Non-expert": "non_expert"}[record["labeler"]]label_id = record["dw_id"]elif "filename" in record:source = "test"label_id = record["filename"]else:source = "validation"label_id = record["dw_id"]key = (source, label_id)if key in metadata:raise ValueError(f"Duplicate annotation metadata: {key}")metadata[key] = recordreturn metadatadef read_calibration(client: StacClient, item: pystac.Item) -> dict[str, tuple[float, float]]:"""Read reflectance calibration from Sentinel product XML, absent in PC STAC."""href = item.assets["product-metadata"].hrefresponse = requests.get(client.patch_url(href), timeout=60)response.raise_for_status()root = ElementTree.fromstring(response.content)quantification = Noneoffsets = {}for element in root.iter():name = element.tag.split("}")[-1]if name == "BOA_QUANTIFICATION_VALUE":quantification = float(element.text)elif name == "BOA_ADD_OFFSET":offsets[int(element.attrib["band_id"])] = float(element.text)if quantification is None or quantification <= 0:raise ValueError(f"missing BOA quantification: {item.id}")if float(item.properties["s2:processing_baseline"]) >= 4 and not offsets:raise ValueError(f"missing BOA offsets for baseline >= 4: {item.id}")ids = {"B02": 1,"B03": 2,"B04": 3,"B05": 4,"B06": 5,"B07": 6,"B08": 7,"B8A": 8,"B11": 11,"B12": 12,}calibration = {}if (float(item.properties["s2:processing_baseline"]) >= 4and not set(ids.values()) <= offsets.keys()):raise ValueError(f"incomplete BOA offsets for requested bands: {item.id}")for band in BANDS:calibration[band] = (1 / quantification,offsets.get(ids[band], 0) / quantification,)return calibrationdef ingest_label(client: StacClient, path: Path, folder: Path, item_id: str, properties: dict) -> pystac.Item:"""Load the label's day and grid, then write a pair of equally named TIFFs."""label = read_label(path)region = label.gs.region.replace(timespan=read_date(path).strftime("%Y-%m-%d"))query = StacQuery(collections=["sentinel-2-l2a"]).set_region(region)items = client.search_items(query)if not items:raise ValueError(f"no Sentinel-2 imagery for {path.name}")# Stable overlap precedence when neighbouring tiles cover the label.items.sort(key=lambda item: item.id)calibration = read_calibration(client, items[0])for item in items[1:]:if read_calibration(client, item) != calibration:raise ValueError("cannot mosaic source digital numbers with different calibration")image = load_dataset(items,collection=client.collection("sentinel-2-l2a"),geobox=label.gs.geobox,bands=BANDS,groupby=lambda item, parsed, index: 0,preserve_original_order=True,resampling="bilinear",dtype="uint16",nodata=0,chunks=None,pool=2,patch_url=client.patch_url,)for band, (scale, offset) in calibration.items():image[band].attrs.update(scale_factor=scale, add_offset=offset, long_name=band, units="1")if not image.to_array().any().item():raise ValueError(f"imagery contains only nodata for {path.name}")properties = {**properties,"source_ids": [item.id for item in items],"datetime": read_date(path).tz_localize("UTC").isoformat(),"source_datetimes": [item.datetime.isoformat() for item in items],"processing_level": "L2A","resampling": "bilinear","matching": "same-day mosaic; not exact original product recovery","bands": BANDS,"label_codes": "original-0-10","calibration": calibration,}dates = sorted(set(properties["source_datetimes"]))if len(dates) != 1:raise ValueError("model context requires one acquisition time per mosaic")image.attrs["acquisition_time"] = dates[0]folder.mkdir(parents=True, exist_ok=True)with TemporaryDirectory(dir=folder) as temporary:stage = Path(temporary)image.gs.to_cog(stage, path_format="image.tif")label.gs.to_cog(stage, path_format="label.tif", overview_resampling="NEAREST")write_time(stage / "image.tif", dates[0])# Publish the image last: the loader's glob must only discover complete pairs.for source, destination in [("label.tif", folder / "labels" / f"{item_id}.tif"),("image.tif", folder / "images" / f"{item_id}.tif"),]:destination.parent.mkdir(parents=True, exist_ok=True)(stage / source).replace(destination)return make_item(folder / "images" / f"{item_id}.tif",folder / "labels" / f"{item_id}.tif",properties,)def write_time(path: Path, date: str) -> None:"""Add actual acquisition time while retaining Cloud Optimized TIFF layout."""with rasterio.open(path) as source:if source.tags().get("acquisition_time") == date:returnwith TemporaryDirectory(dir=path.parent) as temporary:editable = Path(temporary) / "image.tif"cog = Path(temporary) / "image-cog.tif"copy_raster(path, editable, driver="GTiff")with rasterio.open(editable, "r+") as image:image.update_tags(acquisition_time=date)copy_raster(editable, cog, driver="COG", compress="DEFLATE")cog.replace(path)def main(raw: Path = WORKSPACE / "data" / "raw",out: Path = WORKSPACE / "data" / "processed",threads: int = 2,subset: str | None = None,limit: int | None = None,seed: int = 0,) -> None:"""Ingest every label under RAW into OUT, THREADS labels at a time."""raw, out = raw.resolve(), out.resolve()if subset is not None and subset not in SPLITS:raise ValueError(f"unknown subset: {subset}")if limit is not None and limit < 1:raise ValueError("limit must be positive")if not raw.is_dir():raise ValueError(f"label folder does not exist: {raw}")if threads < 1:raise ValueError("threads must be positive")catalog_path = out / "catalog.parquet"items = {}if catalog_path.exists():table = gpd.read_parquet(catalog_path)if "dw:split" in table:raise ValueError("Refusing to modify the legacy catalog or its files. ""Use a fresh --out directory to prepare source metadata.")for item in table.gs.to_items():items[item.id] = itemmetadata = read_metadata(raw)client = StacClient.planetary_computer()client.collection("sentinel-2-l2a")out.mkdir(parents=True, exist_ok=True)failures_path = out / "failures.csv"failures = {}if failures_path.exists():failures = pd.read_csv(failures_path).set_index("source")["error"].to_dict()# The test release keeps model probabilities, `probs_*`, beside its labels.pending = {}paths = []for path in sorted(raw.rglob("*.tif")):source = path.relative_to(raw).parts[0]if source not in SPLITS or (subset is not None and source != subset):continueif path.name.startswith("probs_"):continueif source == "validation" and "expert_composites" not in path.parts:continuepaths.append(path)random.Random(seed).shuffle(paths)if limit is not None:paths = paths[:limit]for path in paths:key = path.relative_to(raw).as_posix()if path.name.startswith("probs_"):continuefolder = out / SPLITS[path.relative_to(raw).parts[0]]item_id = "_".join(Path(key).with_suffix("").parts)image = folder / "images" / f"{item_id}.tif"label = folder / "labels" / f"{item_id}.tif"if item_id not in items or not image.exists() or not label.exists():pending[key] = pathwith ThreadPoolExecutor(threads) as pool:futures = {}for key, path in pending.items():folder = out / SPLITS[path.relative_to(raw).parts[0]]# Experts and non-experts labelled some of the same tiles, under# the same file name, so the subset keeps their Items apart.item_id = "_".join(Path(key).with_suffix("").parts)# Test labels are named `label_<id>`; their metadata names `<id>`.source = path.relative_to(raw).parts[0]label_id = path.stem.removeprefix("label_")properties = dict(metadata[source, label_id])properties["annotation_source"] = sourceproperties["split"] = SPLITS[source]properties["raw_label"] = keyif source == "validation":for composite in ("simple_majority", "strict", "majority", "consensus"):if label_id.endswith("_" + composite):properties["validation_composite"] = compositebreakfuture = pool.submit(ingest_label, client, path, folder, item_id, properties)futures[future] = keyfor future in tqdm(as_completed(futures), total=len(futures), unit="label"):key = futures[future]try:item = future.result()items[item.id] = itemwrite_catalog(out, list(items.values()))failures.pop(key, None)except Exception as error:failures[key] = f"{type(error).__name__}: {error}"tqdm.write(f"{key}: {failures[key]}")pd.DataFrame(list(failures.items()), columns=["source", "error"]).to_csv(failures_path, index=False)failed = sum(path.relative_to(raw).as_posix() in failures for path in paths)print(f"Selected {len(paths)} samples; {len(paths) - failed} complete; {failed} failed")if failed:raise typer.Exit(code=1)def make_item(image_path: Path, label_path: Path, properties: dict) -> pystac.Item:"""Describe a completed pair using source provenance and raster headers."""properties = dict(properties)date = pd.Timestamp(properties.pop("datetime")).to_pydatetime()with gs.open_raster(image_path) as image, gs.open_raster(label_path) as label:geometry = label.gs.geobox.geographic_extentitem = pystac.Item(image_path.stem, geometry.json, list(geometry.boundingbox), date, properties)item.collection_id = "dynamic-world-l2a"item.add_asset("image", build_asset(UPath(image_path), image, owner=item))item.add_asset("label", build_asset(UPath(label_path), label, owner=item))item.assets["label"].roles = ["labels"]return itemdef write_catalog(out: Path, items: list[pystac.Item]) -> None:"""Persist complete pairs and their provenance in one STAC GeoParquet table."""if not items:returncollection = pystac.Collection("dynamic-world-l2a","L2A images paired with original Dynamic World human annotations",pystac.Extent.from_items(items),license="CC-BY-4.0",)table = from_items(items, collections=[collection])# Hrefs are relative to catalog.parquet so the dataset can move between machines.for assets in table["assets"]:for asset in assets.values():href = Path(asset["href"])asset["href"] = (href.relative_to(out).as_posix()if href.is_absolute()else href.as_posix())partial = out / "catalog.partial.parquet"table.gs.to_geoparquet(partial)partial.replace(out / "catalog.parquet")if __name__ == "__main__":
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""Bounded CPU lifecycle checks; the tiny random CNN is only a test fixture."""
import argparsefrom copy import deepcopyimport jsonfrom pathlib import Pathimport sys
import torchfrom lightning import Trainer, seed_everythingfrom lightning.pytorch.callbacks import ModelCheckpointfrom lightning.pytorch.loggers import TensorBoardLoggerfrom tensorboard.backend.event_processing.event_accumulator import EventAccumulator
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from modules.segmentation.supervised.data import DataModulefrom modules.segmentation.supervised.module import Module
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, default=Path("artifacts/smoke")) parser.add_argument("--num-workers", type=int, default=0) args = parser.parse_args() torch.set_num_threads(2) seed_everything(0, workers=True) args.output.mkdir(parents=True, exist_ok=True) chain = { "encoder": { "name": "small_cnn", "init_args": {"in_channels": 3, "width": 4, "input_size": 64}, }, "decoder": { "name": "unet", "init_args": {"decoder_channels": [32, 16, 8, 4], "vit_adapter": False}, }, "head": {"name": "segmentation", "init_args": {"num_classes": 8}}, } options = dict( accelerator="cpu", devices=1, precision="32-true", max_epochs=1, limit_train_batches=2, limit_val_batches=2, limit_test_batches=2, num_sanity_val_steps=1, log_every_n_steps=1, enable_progress_bar=False, ) data = DataModule( bands=["B02", "B03", "B04"], size=64, batch_size=2, num_workers=args.num_workers, include_non_expert=False, augmentations=[{"name": "RandomHorizontalFlip", "init_args": {"p": 0.5}}], ) model = Module( chain, optimizer={"name": "adamw", "init_args": {"lr": 0.001}}, lr_scheduler={ "name": "reduce_on_plateau", "init_args": {"mode": "max", "patience": 1}, "monitor": "val_iou_macro", }, ) logger = TensorBoardLogger(str(args.output), name="lifecycle") checkpoint = ModelCheckpoint(monitor="val_iou_macro", mode="max", save_last=True) trainer = Trainer(**options, logger=logger, callbacks=[checkpoint]) trainer.fit(model, datamodule=data) restored = Module.load_from_checkpoint(checkpoint.best_model_path).eval() model.eval() batch = next(iter(data.val_dataloader())) with torch.no_grad(): torch.testing.assert_close( model(image=batch["image"]), restored(image=batch["image"]) ) assert restored.policy == model.policy trainer.validate(restored, datamodule=data) trainer.test(restored, datamodule=data) log_dir = Path(logger.log_dir) assert Path(checkpoint.dirpath) == log_dir / "checkpoints" before = EventAccumulator(str(log_dir), size_guidance={"scalars": 0}).Reload() events = len(before.Scalars("val_iou_macro")) resumed_logger = TensorBoardLogger( str(args.output), name="lifecycle", version=logger.version ) options.update(max_epochs=2, limit_train_batches=1) resumed = Trainer( **options, logger=resumed_logger, callbacks=[ ModelCheckpoint(monitor="val_iou_macro", mode="max", save_last=True) ], ) resumed.fit( Module(**dict(model.hparams)), datamodule=data, ckpt_path=checkpoint.last_model_path, ) assert Path(resumed.log_dir) == log_dir assert resumed.global_step == 3 after = EventAccumulator(str(log_dir), size_guidance={"scalars": 0}).Reload() assert len(after.Scalars("val_iou_macro")) > events # An ignored batch must not execute the model or advance optimizer state. ignored = deepcopy(batch) ignored["target"].fill_(255) trained = resumed.lightning_module count = resumed.global_step assert trained.training_step(ignored, 0) is None assert resumed.global_step == count result = { "checkpoint": checkpoint.best_model_path, "global_step": resumed.global_step, "log_dir": str(log_dir), "event_history_preserved": True, "purpose": "CPU engineering check, not a model experiment", } (args.output / "result.json").write_text(json.dumps(result, indent=2) + "\n") print(json.dumps(result, indent=2))
if __name__ == "__main__": main()12345678"""Import project modules without installing the consumer workspace."""
from pathlib import Pathimport sys
WORKSPACE = Path(__file__).resolve().parents[1]sys.path.insert(0, str(WORKSPACE))sys.path.insert(0, str(WORKSPACE / "scripts")).gitattributes+1
.gitignore+2-4
01_data.ipynbAdded
02_inputs.ipynbAdded
03_results.ipynbAdded+231
EXPERIMENT.mdAdded+27
README.mdAdded+93
configs/clay-large-dpt.yamlAdded+141
configs/dinov3-7b-dpt.yamlAdded+107
configs/dinov3-7b-sat-dpt.yamlAdded+107
configs/dinov3-base-dpt-cutmix.yamlAdded+107
configs/dinov3-base-dpt-experts.yamlAdded+108
configs/dinov3-base-dpt-google.yamlAdded+107
configs/dinov3-base-dpt-lr-low.yamlAdded+107
configs/dinov3-base-dpt-noaug.yamlAdded+99
configs/dinov3-base-dpt-ohem.yamlAdded+107
configs/dinov3-base-dpt-rotate.yamlAdded+114
configs/dinov3-base-dpt.yamlAdded+107
configs/dinov3-base-qkvb-dpt.yamlAdded+107
configs/dinov3-base-unet.yamlAdded+107
configs/dinov3-huge-plus-dpt.yamlAdded+107
configs/dinov3-huge-plus-qkvb-dpt.yamlAdded+107
configs/dinov3-large-dpt.yamlAdded+107
configs/dinov3-large-qkvb-dpt.yamlAdded+107
configs/dinov3-large-qkvb-sat-dpt.yamlAdded+107
configs/dinov3-large-sat-dpt.yamlAdded+107
configs/dinov3-small-dpt.yamlAdded+107
configs/dinov3-small-plus-dpt.yamlAdded+107
configs/dinov3-small-plus-qkvb-dpt.yamlAdded+107
configs/dinov3-small-qkvb-dpt.yamlAdded+107
configs/dynamic-world/model_spec.yamlDeleted-29
configs/prithvi-v1-100-dpt.yamlAdded+124
configs/prithvi-v2-300-dpt.yamlAdded+124
configs/prithvi-v2-300-tl-dpt.yamlAdded+125
configs/prithvi-v2-600-dpt.yamlAdded+124
configs/prithvi-v2-600-tl-dpt.yamlAdded+125
main.py+7-3
modules/__init__.pyAdded
modules/segmentation/__init__.pyAdded
modules/segmentation/supervised/__init__.pyAdded
modules/segmentation/supervised/data.pyAdded+106
modules/segmentation/supervised/datasets.pyAdded+116
modules/segmentation/supervised/module.pyAdded+138
requirements.lockAdded+245
requirements.txt+19-12
scripts/check_data.pyAdded+68
scripts/download_dynamic_world.py+59-26
scripts/ingest_dynamic_world.py+331-157
scripts/smoke.pyAdded+125
tests/conftest.pyAdded+8