### Setup environment and install dependencies Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/tools/generate_embeddings.ipynb Clones the olmoearth_pretrain repository, installs it, and imports required libraries including rasterio, torch, and the OlmoEarth modules. Assumes a Google Colab environment with GPU access. ```python # 2 minutes to setup import math import time from datetime import datetime as dt import numpy as np import pandas as pd import torch if not Path("/content/olmoearth_pretrain").exists(): !git clone https://github.com/allenai/olmoearth_pretrain.git %cd /content/olmoearth_pretrain !pip install -q . import rasterio as rio from torch.utils.data import DataLoader, Dataset from olmoearth_pretrain.data.normalize import Normalizer, Strategy from olmoearth_pretrain.model_loader import ModelID, load_model_from_id from olmoearth_pretrain.train.masking import MaskedOlmoEarthSample, Modality ``` -------------------------------- ### Set up Python environment with uv Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Inference-Quickstart.md Install uv and sync the project dependencies. Run these commands in the project directory. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh cd /path/to/olmoearth_pretrain/ uv sync ``` -------------------------------- ### Example Dataset Path Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Example path illustrating the dataset directory structure with gzip compression level 9, shuffle filter, and 256x16 tiles. ```text /path/to/data/h5py_data_w_missing_timesteps_gzip_9_shuffle_256_x_16/era5_10_naip_sentinel2/4096/ ``` -------------------------------- ### Full development installation with uv Source: https://github.com/allenai/olmoearth_pretrain/blob/main/README.md Clones the repository and installs all dependencies with uv, including development tools like pre-commit. Requires Python 3.12. After installation, activate the venv with 'source .venv/bin/activate' or use 'uv run python'. ```bash git clone git@github.com:allenai/olmoearth_pretrain.git cd olmoearth_pretrain uv sync --locked --all-extras --python 3.12 # only necessary for development uv tool install pre-commit --with pre-commit-uv --force-reinstall ``` -------------------------------- ### Install rslearn via pip Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Install the rslearn package using pip. This is the prerequisite for all subsequent dataset materialization commands. ```bash pip install rslearn ``` -------------------------------- ### Flash attention setup in Beaker session Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Setup-Internal.md Sets up a conda environment for flash attention in a Beaker session. Requires using beaker://petew/olmo-core-tch270cu128 as the base image. ```bash conda init exec bash conda shell.bash activate base pip install -e '.[all]' ``` -------------------------------- ### Single-GPU Training for Debugging Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Example of single-GPU training using torchrun with the nano script. Sets dataset path and global batch size. ```bash torchrun scripts/official/nano.py train my_debug_run local \ --dataset.h5py_dir=/path/to/data \ --data_loader.global_batch_size=64 ``` -------------------------------- ### Setup and remaining tiles function Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/tools/generate_embeddings.ipynb Configures the inference run (name, dates, GCP project, buckets), authenticates the user, initializes storage clients, defines band orders for Sentinel-1, Sentinel-2, and Landsat, and provides a function to list tiles that exist in the input bucket but not the output bucket. ```python from pathlib import Path from google.cloud import storage from google.colab import auth from tqdm.notebook import tqdm # Inference run configuration # ------------------------------------------------------------------------------- NAME = "Togo_v2_nano" START_DATE = "2019-03-01" END_DATE = "2020-03-01" RUN = f"{NAME}_{START_DATE}_{END_DATE}" GCLOUD_PROJECT = "ai2-ivan" IN_BUCKET = "ai2-ivan-helios-input-data" # Bucket for GEE input data OUT_BUCKET = "ai2-ivan-helios-output-data" # Bucket for embedding outputs # General setup # ------------------------------------------------------------------------------- auth.authenticate_user() client = storage.Client(project=GCLOUD_PROJECT) in_bucket = client.bucket(IN_BUCKET) out_bucket = client.bucket(OUT_BUCKET) # For querying bands from Google Earth Engine exported geotiffs BANDS = { # Matches Modality.SENTINEL1.band_order: ['vv', 'vh'] "sentinel1": ["VV", "VH"], # Matches Modality.SENTINEL2_L2A.band_order # ['B02', 'B03', 'B04', 'B08', 'B05', 'B06', 'B07', 'B8A', 'B11', 'B12', 'B01', 'B09'] "sentinel2": [ "B2", "B3", "B4", "B8", "B5", "B6", "B7", "B8A", "B11", "B12", "B1", "B9", ], # Matches Modality.LANDSAT.band_order # ['B8', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B9', 'B10', 'B11'] "landsat": ["B8", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B9", "B10", "B11"], } def remaining_tiles(mod=None, index=None): """Returns tiles that exist in the input bucket but not the output bucket.""" in_tifs = {b.name for b in in_bucket.list_blobs(prefix=RUN)} out_tifs = {b.name for b in out_bucket.list_blobs(prefix=RUN)} print(f"Embeddings generated: {len(out_tifs)}/{len(in_tifs)}") remaining = list(in_tifs - out_tifs) if (mod is not None) and (index is not None): remaining = [t for t in remaining if ((int(Path(t).stem) % mod) == index)] return remaining ``` -------------------------------- ### Submitting a Beaker Job (AI2 Only) Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Example of submitting a Beaker job using the launch subcommand with the large script. Sets trainer max duration and number of GPUs. ```bash python scripts/official/large.py launch my_large_model ai2/saturn \ --trainer.max_duration.value=300 --launch.num_gpus=8 ``` -------------------------------- ### Inference-only installation with uv Source: https://github.com/allenai/olmoearth_pretrain/blob/main/README.md Installs only the dependencies needed for inference and model loading, without training dependencies. Use this when you only need to load and run OlmoEarth models. ```bash uv sync --locked ``` -------------------------------- ### Create H5 Files for Training Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Converts the OlmoEarth dataset into H5 files optimized for training. Splits each 256x256 example into four 128x128 examples. Specify supported modalities, compression (zstd level 3), and tile size. ```bash python -m olmoearth_pretrain.internal.run_h5_conversion --tile_path=$OLMOEARTH_PATH --supported_modality_names='[cdl,era5_10,landsat,naip_10,openstreetmap_raster,sentinel1,sentinel2_l2a,srtm,worldcereal,worldcover,wri_canopy_height_map]' --compression=zstd --compression_opts=3 --tile_size=128 ``` -------------------------------- ### Start GEE export tasks Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/tools/generate_embeddings.ipynb Starts all pending Earth Engine export tasks that were created in the previous cell. Prints the number of started tasks and a link to the Earth Engine task manager. ```python # Start gee tasks for tiles not yet exported for task in tqdm(tasks): task.start() print( f"Started {len(tasks)} export tasks, see: https://code.earthengine.google.com/tasks" ) ``` -------------------------------- ### Multi-GPU Training with torchrun Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Example of multi-GPU training using torchrun with --nproc_per_node=4 on the base script. Sets dataset path and global batch size. ```bash torchrun --nproc_per_node=4 scripts/official/base.py train my_pretrain_run local \ --dataset.h5py_dir=/path/to/data \ --data_loader.global_batch_size=512 ``` -------------------------------- ### Specify container arguments for Cloud Run job Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/tools/cloud_run/README.md Example container arguments for the Cloud Run job, specifying the run name and tiles file. ```text --run Togo_v2_nano_2019-03-01_2020-03-01 --tiles 10.tif ``` -------------------------------- ### Launch script targeting specific Beaker host Source: https://github.com/allenai/olmoearth_pretrain/blob/main/olmoearth_pretrain/internal/override_examples.md Example of launching a script with a specific Beaker hostname list. Replace the hostnames with actual ones. ```bash python scripts/X.py launch [name] ai2/titan-cirrascale --launch.hostnames=["titan-cs-aus-465.reviz.ai2.in","titan-cs-aus-466.reviz.ai2.in"] ``` -------------------------------- ### Run no contrastive loss ablation with torchrun Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Example command to run the no contrastive loss ablation, setting the contrastive loss weight to 0.0 and specifying the data directory. ```bash torchrun --nproc_per_node=8 scripts/official/base.py train base_no_contrastive local \ --train_module.contrastive_config.loss_config.weight=0.0 \ --dataset.h5py_dir=/path/to/data ``` -------------------------------- ### Get Beaker token Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/EXPERIMENT_REPORTS.md Run this command to retrieve your personal Beaker token. Copy the output for use as a GitHub secret. ```bash beaker account token ``` -------------------------------- ### Add user to experiment report list Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/EXPERIMENT_REPORTS.md Edit .github/experiment-report-users.json to include your username. The example shows the JSON structure with a users array. ```json { "users": [ "henryh", "joer", "your_username" ] } ``` -------------------------------- ### Run S2-only modality ablation with torchrun Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Example command to run the S2-only modality ablation, setting training modalities to Sentinel-2 L2A and clearing decode-only modalities. ```bash torchrun --nproc_per_node=8 scripts/official/base.py train base_s2_only local \ --common.training_modalities='[sentinel2_l2a]' \ --train_module.masking_config.strategy_config.only_decode_modalities='[]' \ --dataset.h5py_dir=/path/to/data ``` -------------------------------- ### Prepare and materialize Google Satellite Embedding v1 data Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Commands to set up and process Google Satellite Embedding v1 data. The prepare step downloads a CSV of image geometries from the GEE ImageCollection, and materialization starts GEE export tasks that take ~20 seconds each, monitorable from the GCP console. ```bash cp data/rslearn_dataset_configs/config_google_satembedding.json $DATASET_PATH/config.json rslearn dataset prepare --root $DATASET_PATH --group res_10 --workers 64 rslearn dataset materialize --root $DATASET_PATH --workers 32 --load-workers 128 --group res_10 --no-use-initial-job --ignore-errors ``` -------------------------------- ### Set Beaker Secrets Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Setup-Internal.md Writes WANDB, Beaker, and GitHub tokens as Beaker secrets using the current account name. Requires jq to be installed. ```bash ACCOUNT=$(beaker account whoami --format json | jq -r '.[0].name') beaker secret write ${ACCOUNT}_WANDB_API_KEY beaker secret write ${ACCOUNT}_BEAKER_TOKEN beaker secret write ${ACCOUNT}_GITHUB_TOKEN ``` -------------------------------- ### Load OlmoEarth model and run inference with synthetic data Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Inference-Quickstart.md Minimal example that loads the model from HuggingFace, creates a synthetic Sentinel-2 input, and computes embeddings. Run with uv run. Output shape is (B, H', W', T, S, D). ```bash uv run --with olmoearth-pretrain --with torch --python 3.12 - <<'EOF' import torch from olmoearth_pretrain.model_loader import ModelID, load_model_from_id from olmoearth_pretrain.datatypes import MaskedOlmoEarthSample, MaskValue # Load model from HuggingFace model = load_model_from_id(ModelID.OLMOEARTH_V1_BASE) model.eval() # Create synthetic input (B=1, H=64, W=64, T=1, C=12 for Sentinel-2) dummy_image = torch.randn(1, 64, 64, 1, 12) dummy_mask = torch.ones(1, 64, 64, 1, 3) * MaskValue.ONLINE_ENCODER.value dummy_timestamps = torch.tensor([[[15, 6, 2024]]]) # day, month (0-indexed), year sample = MaskedOlmoEarthSample( sentinel2_l2a=dummy_image, sentinel2_l2a_mask=dummy_mask, timestamps=dummy_timestamps, ) with torch.no_grad(): output = model.encoder(sample, fast_pass=True, patch_size=4) features = output["tokens_and_masks"].sentinel2_l2a print(f"Output shape: {features.shape}") # (B, H', W', T, S, D) EOF ``` -------------------------------- ### Validate Configuration Without Training Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Example of using the dry_run subcommand to validate configuration without running training. Sets trainer max duration value. ```bash python scripts/official/base.py dry_run my_config_test local \ --trainer.max_duration.value=100 ``` -------------------------------- ### Build and push Sentinel-2 L1C Docker image Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Builds and pushes a Docker image for Sentinel-2 L1C materialization. The tag is an example and must be adjusted to push to your GCP project. ```bash # The tag is just an example, and needs to be adjusted so the image is pushed to GCP. docker build -f olmoearth_pretrain/dataset_creation/Dockerfile -t us-west1-docker.pkg.dev/GCP_PROJECT/olmoearth/olmoearth-sentinel2-l1c . docker image push us-west1-docker.pkg.dev/GCP_PROJECT/olmoearth/olmoearth-sentinel2-l1c ``` -------------------------------- ### Launch Nano Model with torchrun Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Launches the Nano model training with 4 GPUs using torchrun. ```bash torchrun --nproc_per_node=4 scripts/official/nano.py train nano_run local ``` -------------------------------- ### Launch Tiny Model with torchrun Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Launches the Tiny model training with 4 GPUs using torchrun. ```bash torchrun --nproc_per_node=4 scripts/official/tiny.py train tiny_run local ``` -------------------------------- ### Create Beaker session for window creation and data materialization Source: https://github.com/allenai/olmoearth_pretrain/blob/main/olmoearth_pretrain/dataset_creation/internal_docs.md Creates a Beaker session with 1 GPU, 128GiB shared memory, and mounts the weka dataset. Use this to run most window creation and data materialization steps. ```bash beaker session create --budget ai2/atec-olmoearth --workspace ai2/earth-systems --priority high --gpus 1 --shared-memory 128GiB --bare --mount src=weka,ref=dfive-default,dst=/weka/dfive-default ``` -------------------------------- ### Launch Nano Model with Dataset Path Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Launches the Nano model with a specified HDF5 dataset directory. ```bash torchrun --nproc_per_node=4 scripts/official/nano.py train nano_run local \ --dataset.h5py_dir=/path/to/h5py_dir ``` -------------------------------- ### Prepare, ingest, and materialize WorldPop data at 10 m/pixel Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Commands to set up and process WorldPop population data at 10 m/pixel resolution. Copies the WorldPop config, then runs prepare, ingest, and materialize steps with 64 workers. ```bash cp data/rslearn_dataset_configs/config_worldpop.json $DATASET_PATH/config.json rslearn dataset prepare --root $DATASET_PATH --group res_10 --workers 64 rslearn dataset ingest --root $DATASET_PATH --group res_10 --workers 64 --no-use-initial-job rslearn dataset materialize --root $DATASET_PATH --group res_10 --workers 64 --no-use-initial-job ``` -------------------------------- ### Initialize rslearn dataset from longitude/latitude list Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Command to create windows in an rslearn dataset from a JSON file of longitudes/latitudes. Requires a dataset folder with config.json (e.g., copied from data/rslearn_dataset_configs/config_init.json) and AWS credentials for NAIP data source. ```bash python -m olmoearth_pretrain.dataset_creation.create_windows.from_lon_lat_list --ds_path dataset/ --fname openstreetmap_lonlats.json ``` -------------------------------- ### Launch Base Model with Dataset Path Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Launches the Base model with a specified HDF5 dataset directory. ```bash torchrun --nproc_per_node=8 scripts/official/base.py train base_run local \ --dataset.h5py_dir=/path/to/your/h5data/num_samples ``` -------------------------------- ### Run training in Beaker session Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Setup-Internal.md Runs training with torchrun in a Beaker session for debugging. Add additional overrides as needed. ```bash torchrun --nproc_per_node=8 scripts/official/base.py train test_run local ``` -------------------------------- ### Run deploy.sh script Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/tools/cloud_run/README.md Executes the deployment script to build the Docker container and deploy it to Google Cloud. ```bash sh scripts/tools/cloud_run/deploy.sh ``` -------------------------------- ### Derive timestamps from date range Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/tools/generate_embeddings.ipynb Converts start and end date strings to date objects, generates monthly timestamps, and formats them as [day, month-1, year] lists. ```python # Derive timestamps def to_date_obj(d): """Converts date string to date object.""" return dt.strptime(d, "%Y-%m-%d").date() timestamps_pd = pd.date_range( to_date_obj(START_DATE), to_date_obj(END_DATE), freq="MS" )[:-1] timestamps = [[t.day, t.month - 1, t.year] for t in timestamps_pd] ``` -------------------------------- ### Show Help Message: python scripts/official/base.py Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Run any script without arguments to see the help message and a complete list of subcommands. ```bash python scripts/official/base.py ``` -------------------------------- ### Prepare and materialize NAIP data at 0.625 m/pixel windows Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Commands to set up and process NAIP data at 0.625 m/pixel resolution. Copies the NAIP config, then runs prepare and materialize steps with retry settings for robustness. ```bash cp data/rslearn_dataset_configs/config_naip.json $DATASET_PATH/config.json rslearn dataset prepare --root $DATASET_PATH --group res_0.625 --workers 64 --no-use-initial-job --retry-max-attempts 8 --retry-backoff-seconds 60 --jobs-per-process 16 rslearn dataset materialize --root $DATASET_PATH --group res_0.625 --workers 64 --no-use-initial-job --retry-max-attempts 8 --retry-backoff-seconds 60 ``` -------------------------------- ### Launch Large Model with torchrun Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Launches the Large model training with 8 GPUs using torchrun. ```bash torchrun --nproc_per_node=8 scripts/official/large.py train large_run local ``` -------------------------------- ### Load model and get embedding size Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/tools/generate_embeddings.ipynb Loads the OLMOEARTH_V1_NANO model, moves its encoder to the available device (CUDA or CPU), and prints the embedding size from the projection layer. ```python device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Load model model = load_model_from_id(ModelID.OLMOEARTH_V1_NANO) model.eval() model = model.encoder.to(device) EMBEDDINGS_SIZE = model.project_and_aggregate.projection[0].out_features print("Embedding size: ", EMBEDDINGS_SIZE) ``` -------------------------------- ### Build Docker image and launch Beaker job for WorldCover histograms Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/archived/worldcover_sampling/README.md Run from the worldcover_sampling directory. Builds the Docker image, creates it in Beaker, then launches parallel jobs to compute histograms. The output directory must be on a shared filesystem. ```bash cd helios/scripts/worldcover_sampling docker build -t helios-worldcover-sampling . beaker image create --name helios-worldcover-sampling helios-worldcover-sampling python launch_beaker.py --out_dir /weka/dfive-default/helios/dataset_creation/worldcover_histogram_csvs/ --beaker_image favyen/helios-worldcover-sampling ``` -------------------------------- ### Launch speed-optimized training scripts Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/vnext/speedups/README.md Bash commands to dry-run and launch the contrastive (base_speedup.py) and non-contrastive (base_speedup_latent_mim.py) training scripts. The non-contrastive script is ~2x cheaper per step and uses a single forward pass. ```bash # Dry run first python scripts/vnext/speedups/base_speedup.py dry_run base_speedup_test local ``` ```bash # Contrastive (2-view) python scripts/vnext/speedups/base_speedup.py launch base_speedup ai2/jupiter \ --launch.num_gpus=8 \ --launch.clusters=[ai2/ceres,ai2/jupiter,ai2/titan] \ --trainer.callbacks.wandb.project=YYYY_MM_DD_speed_optimizations ``` ```bash # Non-contrastive (1-view, single forward pass) python scripts/vnext/speedups/base_speedup_latent_mim.py launch base_speedup_latentmim ai2/jupiter \ --launch.num_gpus=8 \ --launch.clusters=[ai2/ceres,ai2/jupiter,ai2/titan] \ --trainer.callbacks.wandb.project=YYYY_MM_DD_speed_optimizations ``` -------------------------------- ### Extract dataset from tar files Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Extracts all tar files in the download directory to the specified H5 directory, using parallel extraction with one tar per core. Tune -P if disk gets saturated. ```bash export H5_DIR=/path/to/extraction/location/ export TAR_DIR=/path/to/save/location/ mkdir -p "$H5_DIR" cd "$TAR_DIR" # run one tar per core; tune -P if disk gets saturated find . -maxdepth 1 -name '*.tar' -print0 \ | xargs -0 -n1 -P"$(nproc)" -I{} \ tar -xf "{}" -C "$H5_DIR" \ --no-same-owner --numeric-owner --delay-directory-restore echo "Dataset downloaded at ${H5_DIR}h5py_data_w_missing_timesteps_zstd_3_128_x_4/cdl_gse_landsat_openstreetmap_raster_sentinel1_sentinel2_l2a_srtm_worldcereal_worldcover_worldpop_wri_canopy_height_map/1138828" ``` -------------------------------- ### Create windows with random sampling Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Alternative sampling strategy: creates windows with random sampling, specifying dataset path and count (e.g., 50000). ```bash python -m olmoearth_pretrain.dataset_creation.create_windows.random --ds_path dataset/ --count 50000 ``` -------------------------------- ### Increase Epochs for 1K-Example Subset Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Sets the trainer max duration to 3000 epochs, recommended for the 1K-Example Subset. ```bash --trainer.max_duration='{"unit": "epochs", "value": 3000}' ``` -------------------------------- ### Prepare Sentinel-1 Image Collection Source: https://github.com/allenai/olmoearth_pretrain/blob/main/scripts/tools/generate_embeddings.ipynb Filters the Sentinel-1 GRD collection to the ROI and date range, selects the orbit pass and instrument mode, and separates VV and VH polarizations. Includes helper functions to get close images and create a median mosaic. ```python # Sentinel-1 Data # ------------------------------------------------------------------------------- S1_all = ( ee.ImageCollection("COPERNICUS/S1_GRD") .filterBounds(roi) .filterDate(start.advance(-31, "days"), end.advance(31, "days")) ) S1 = S1_all.filter( ee.Filter.eq("orbitProperties_pass", S1_all.first().get("orbitProperties_pass")) ).filter(ee.Filter.eq("instrumentMode", "IW")) S1_VV = S1.filter(ee.Filter.listContains("transmitterReceiverPolarisation", "VV")) S1_VH = S1.filter(ee.Filter.listContains("transmitterReceiverPolarisation", "VH")) def getCloseImages(middleDate, imageCollection): """Helper function for getting Sentinel-1 images.""" def setDate(img): dateDist = ( ee.Number(img.get("system:time_start")).subtract(middleDate.millis()).abs() ) return img.set("dateDist", dateDist) fromMiddleDate = imageCollection.map(setDate).sort("dateDist", True) fifteenDaysInMs = ee.Number(1296000000) maxDiff = ee.Number(fromMiddleDate.first().get("dateDist")).max(fifteenDaysInMs) return fromMiddleDate.filterMetadata("dateDist", "not_greater_than", maxDiff) def get_S1_img(date1, date2): """Obtains Sentinel-1 median mosaic.""" daysBetween = date2.difference(date1, "days") middleDate = date1.advance(daysBetween.divide(2), "days") kept_vv = getCloseImages(middleDate, S1_VV).select("VV") kept_vh = getCloseImages(middleDate, S1_VH).select("VH") S1_composite = ee.Image.cat([kept_vv.median(), kept_vh.median()]) return ( S1_composite.select(BANDS["sentinel1"]).clip(roi).float() ) # S1 ranges from -50 to 1 ``` -------------------------------- ### Launch Beaker Session with torchrun Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Launches an interactive Beaker session using torchrun with 8 processes for the base model. ```bash torchrun --nproc_per_node=8 scripts/official/base.py train base_run local ``` -------------------------------- ### Materialize OpenStreetMap and WorldCereal on one machine Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Copy the configuration file and run prepare, ingest, and materialize commands with 16 workers for prepare and ingest, and 64 for materialize. Use 16 workers because processing PBF (OpenStreetMap) or GeoTIFF (WorldCereal) can use a lot of memory. ```bash cp data/rslearn_dataset_configs/config_{openstreetmap,worldcereal}.json $DATASET_PATH/config.json rslearn dataset prepare --root $DATASET_PATH --group res_10 --workers 16 --load-workers 64 rslearn dataset ingest --root $DATASET_PATH --group res_10 --workers 16 --load-workers 64 --no-use-initial-job rslearn dataset materialize --root $DATASET_PATH --group res_10 --workers 64 --no-use-initial-job ``` -------------------------------- ### Materialize Landsat data on AWS machine Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Set DATASET_PATH to the AWS location, copy the Landsat configuration file, and run prepare and materialize commands with 64 workers. Includes --ignore-errors and retry options to handle failures. ```bash export DATASET_PATH=/mnt/rslearn_dataset cp data/rslearn_dataset_configs/config_landsat.json $DATASET_PATH/config.json rslearn dataset prepare --root $DATASET_PATH --group res_10 --workers 64 --no-use-initial-job rslearn dataset materialize --root $DATASET_PATH --group res_10 --workers 64 --no-use-initial-job --ignore-errors --retry-max-attempts 4 --retry-backoff-seconds 1 ``` -------------------------------- ### Materialize Sentinel-1, Sentinel-2 L2A, and NAIP from Planetary Computer Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Set DATASET_PATH, copy the appropriate configuration file, and run rslearn prepare and materialize commands with 64 workers. These datasets are ingested from Microsoft Planetary Computer with random access support. ```bash # Set DATASET_PATH to the location of your rslearn dataset from the previous step. export DATASET_PATH=./dataset/ # Choose one configuration file to copy and run the rslearn commands with at a time. cp data/rslearn_dataset_configs/config_{sentinel1,sentinel2_l2a,naip_10}.json $DATASET_PATH/config.json rslearn dataset prepare --root $DATASET_PATH --group res_10 --workers 64 --no-use-initial-job --retry-max-attempts 8 --retry-backoff-seconds 60 --jobs-per-process 16 rslearn dataset materialize --root $DATASET_PATH --group res_10 --workers 64 --no-use-initial-job --retry-max-attempts 8 --retry-backoff-seconds 60 ``` -------------------------------- ### Custom Training Run with Multiple Overrides Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Launch a custom training run with torchrun using 8 processes per node. Override configuration parameters via CLI dotted notation, including global batch size, number of workers, rank microbatch size, learning rate, warmup steps, and max duration. Optionally set the dataset H5 directory with --dataset.h5py_dir. ```bash torchrun --nproc_per_node=8 scripts/official/base.py train custom_experiment local \ --data_loader.global_batch_size=256 \ --data_loader.num_workers=8 \ --train_module.rank_microbatch_size=8 \ --train_module.optim_config.lr=0.0002 \ --train_module.scheduler.warmup_steps=5000 \ --trainer.max_duration.epochs=100 # Optionally --dataset.h5py_dir=/your/path/to/data \ ``` -------------------------------- ### Launch pre-emptible job with base.py Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Setup-Internal.md Launches a Beaker job and streams logs to the console until cancelled. Ensure code is committed and pushed before launching. Use --launch.priority= to configure scheduling priority (default is high). ```bash python3 scripts/official/base.py launch my_run_name ai2/saturn ``` -------------------------------- ### Prepare, ingest, and materialize ERA5 data at 160 m/pixel Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Dataset-Creation.md Commands to set up and process an ERA5 dataset group at 160 m/pixel resolution. Copies the ERA5 config, then runs prepare, ingest, and materialize steps with 64 workers. ```bash cp data/rslearn_dataset_configs/config_era5.json $DATASET_PATH/config.json rslearn dataset prepare --root $DATASET_PATH --group res_160 --workers 64 rslearn dataset ingest --root $DATASET_PATH --group res_160 --workers 64 --no-use-initial-job rslearn dataset materialize --root $DATASET_PATH --group res_160 --workers 64 --no-use-initial-job ``` -------------------------------- ### Launch Beaker Batch Job with base.py Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Launches a Beaker batch job using the launch subcommand with 8 GPUs on the specified cluster. ```bash python3 scripts/official/base.py launch base_run ai2/saturn --launch.num_gpus=8 ``` -------------------------------- ### General Usage with torchrun for Multi-GPU Source: https://github.com/allenai/olmoearth_pretrain/blob/main/docs/Pretraining.md Command structure for multi-GPU training using torchrun. Add torchrun options before the script invocation. ```bash torchrun [TORCHRUN_OPTIONS] scripts/official/