Upload 4 files
Browse filesFiles changed (4)
- README.mdAdded+59
- config.yamlAdded+182
- model_inference.pyAdded+344
- requirements.txtAdded+6
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859---
license: apache-2.0
language:
- en
tags:
- Pytorch
- segmentation
- Flood mapping
- Sentinel-2
- Geospatial
- Foundation model
---
### Model and Inputs
The pretrained [Prithvi-EO-2.0-300M-TL](https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL) model is finetuned to segment the extent of floods on Sentinel-2 images from the [Sen1Floods11 dataset](https://github.com/cloudtostreet/Sen1Floods11).
The dataset consists of 446 labeled 512x512 chips that span all 14 biomes, 357 ecoregions, and 6 continents of the world across 11 flood events. The benchmark associated to Sen1Floods11 provides results for fully convolutional neural networks trained in various input/labeled data setups, considering Sentinel-1 and Sentinel-2 imagery.
We use the following six bands for flood mapping: Blue, Green, Red, Narrow NIR, SWIR, SWIR 2.
Labels represent no water (class 0), water/flood (class 1), and no data/clouds (class -1).
The Prithvi-EO-2.0-300M-TL model was initially pretrained using a sequence length of 4 timestamps. Based on the characteristics of this benchmark dataset, we focus on single-timestamp segmentation. This demonstrates that our model can be utilized with an arbitrary number of timestamps during fine-tuning.
### Fine-tuning
The model was fine-tuned using [TerraTorch](https://github.com/IBM/terratorch):
```shell
terratorch fit -c sen1floods11.yaml
```
The configuration used for finetuning is available through this [config](https://github.com/NASA-IMPACT/Prithvi-EO-2.0/blob/main/configs/sen1floods11.yaml).
### Inference and demo
A **demo** running this model is available **[here](https://huggingface.co/spaces/ibm-nasa-geospatial/Prithvi-EO-2.0-Sen1Floods11-demo)**.
This repo includes an inference script that allows running the flood model for inference on Sentinel-2 L1C images.
```shell
python inference.py --data_file examples/India_900498_S2Hand.tif
```
### Feedback
Your feedback is invaluable to us. If you have any feedback about the model, please feel free to share it with us. You can do this by submitting issues on GitHub or start a discussion on HuggingFace.
### Citation
If this model helped your research, please cite [Prithvi-EO-2.0](https://arxiv.org/abs/2412.02732) in your publications.
```
@article{Prithvi-EO-V2-preprint,
author = {Szwarcman, Daniela and Roy, Sujit and Fraccaro, Paolo and Gíslason, Þorsteinn Elí and Blumenstiel, Benedikt and Ghosal, Rinki and de Oliveira, Pedro Henrique and de Sousa Almeida, João Lucas and Sedona, Rocco and Kang, Yanghui and Chakraborty, Srija and Wang, Sizhe and Kumar, Ankur and Truong, Myscon and Godwin, Denys and Lee, Hyunho and Hsu, Chia-Yu and Akbari Asanjan, Ata and Mujeci, Besart and Keenan, Trevor and Arévolo, Paulo and Li, Wenwen and Alemohammad, Hamed and Olofsson, Pontus and Hain, Christopher and Kennedy, Robert and Zadrozny, Bianca and Cavallaro, Gabriele and Watson, Campbell and Maskey, Manil and Ramachandran, Rahul and Bernabe Moreno, Juan},
title = {{Prithvi-EO-2.0: A Versatile Multi-Temporal Foundation Model for Earth Observation Applications}},
journal = {arXiv preprint arXiv:2412.02732},
year = {2024}
}
```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182# lightning.pytorch==2.4.0seed_everything: 0trainer: accelerator: auto strategy: auto devices: auto num_nodes: 1 precision: 16-mixed logger: true callbacks: - class_path: lightning.pytorch.callbacks.RichProgressBar init_args: refresh_rate: 1 leave: false theme: description: white progress_bar: '#6206E0' progress_bar_finished: '#6206E0' progress_bar_pulse: '#6206E0' batch_progress: white time: grey54 processing_speed: grey70 metrics: white metrics_text_delimiter: ' ' metrics_format: .3f - class_path: lightning.pytorch.callbacks.LearningRateMonitor init_args: logging_interval: epoch log_momentum: false log_weight_decay: false - class_path: lightning.pytorch.callbacks.EarlyStopping init_args: monitor: val/loss min_delta: 0.0 patience: 20 verbose: false mode: min strict: true check_finite: true log_rank_zero_only: false fast_dev_run: false max_epochs: 50 max_steps: -1 overfit_batches: 0.0 check_val_every_n_epoch: 2 log_every_n_steps: 10 enable_checkpointing: true accumulate_grad_batches: 1 inference_mode: true use_distributed_sampler: true detect_anomaly: false barebones: false sync_batchnorm: false reload_dataloaders_every_n_epochs: 0 default_root_dir: /dccstor/geofm-finetuning/benchmark-geo-bench-paolo/model: class_path: terratorch.tasks.SemanticSegmentationTask init_args: model_args: backbone_pretrained: true backbone: prithvi_eo_v2_300_tl decoder: UperNetDecoder decoder_channels: 256 decoder_scale_modules: true num_classes: 2 rescale: true backbone_bands: - BLUE - GREEN - RED - NIR_NARROW - SWIR_1 - SWIR_2 head_dropout: 0.1 necks: - name: SelectIndices indices: - 5 - 11 - 17 - 23 - name: ReshapeTokensToImage model_factory: EncoderDecoderFactory loss: ce ignore_index: -1 lr: 0.001 freeze_backbone: false freeze_decoder: false plot_on_val: 10data: class_path: terratorch.datamodules.Sen1Floods11NonGeoDataModule init_args: data_root: /dccstor/geofm-finetuning/datasets/sen1floods11 batch_size: 16 num_workers: 8 bands: - BLUE - GREEN - RED - NIR_NARROW - SWIR_1 - SWIR_2 train_transform: - class_path: albumentations.Resize init_args: height: 448 width: 448 interpolation: 1 always_apply: false p: 1 - class_path: albumentations.RandomCrop init_args: height: 224 width: 224 always_apply: false p: 1.0 - class_path: albumentations.HorizontalFlip init_args: always_apply: false p: 0.5 - class_path: albumentations.VerticalFlip init_args: always_apply: false p: 0.5 - class_path: albumentations.pytorch.ToTensorV2 init_args: transpose_mask: false always_apply: true p: 1.0 val_transform: - class_path: albumentations.Resize init_args: height: 448 width: 448 interpolation: 1 always_apply: false p: 1 - class_path: albumentations.pytorch.ToTensorV2 init_args: transpose_mask: false always_apply: true p: 1.0 test_transform: - class_path: albumentations.Resize init_args: height: 448 width: 448 interpolation: 1 always_apply: false p: 1 - class_path: albumentations.pytorch.ToTensorV2 init_args: transpose_mask: false always_apply: true p: 1.0 drop_last: true constant_scale: 0.0001 no_data_replace: 0.0 no_label_replace: -1 use_metadata: falseout_dtype: int16deploy_config_file: trueoptimizer: class_path: torch.optim.AdamW init_args: lr: 5.0e-05 betas: - 0.9 - 0.999 eps: 1.0e-08 weight_decay: 0.05 amsgrad: false maximize: false capturable: false differentiable: falselr_scheduler: class_path: torch.optim.lr_scheduler.CosineAnnealingLR init_args: T_max: 50 eta_min: 0 last_epoch: -1 verbose: deprecated123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
import argparseimport osfrom typing import List, Unionimport reimport datetimeimport numpy as npimport rasterioimport torchimport yamlfrom einops import rearrangefrom terratorch.cli_tools import LightningInferenceModel
NO_DATA = -9999NO_DATA_FLOAT = 0.0001OFFSET = 0PERCENTILE = 99
def process_channel_group(orig_img, channels): """ Args: orig_img: torch.Tensor representing original image (reference) with shape = (bands, H, W). channels: list of indices representing RGB channels.
Returns: torch.Tensor with shape (num_channels, height, width) for original image """
orig_img = orig_img[channels, ...] valid_mask = torch.ones_like(orig_img, dtype=torch.bool) valid_mask[orig_img == NO_DATA_FLOAT] = False
# Rescale (enhancing contrast) max_value = max(3000, np.percentile(orig_img[valid_mask], PERCENTILE)) min_value = OFFSET
orig_img = torch.clamp((orig_img - min_value) / (max_value - min_value), 0, 1)
# No data as zeros orig_img[~valid_mask] = 0
return orig_img
def read_geotiff(file_path: str): """Read all bands from *file_path* and return image + meta info.
Args: file_path: path to image file.
Returns: np.ndarray with shape (bands, height, width) meta info dict """
with rasterio.open(file_path) as src: img = src.read() meta = src.meta try: coords = src.lnglat() except: # Cannot read coords coords = None
return img, meta, coords
def save_geotiff(image, output_path: str, meta: dict): """Save multi-band image in Geotiff file.
Args: image: np.ndarray with shape (bands, height, width) output_path: path where to save the image meta: dict with meta info. """
with rasterio.open(output_path, "w", **meta) as dest: for i in range(image.shape[0]): dest.write(image[i, :, :], i + 1)
return
def _convert_np_uint8(float_image: torch.Tensor): image = float_image.numpy() * 255.0 image = image.astype(dtype=np.uint8)
return image
def load_example( file_paths: List[str], mean: List[float] = None, std: List[float] = None, indices: Union[list[int], None] = None,): """Build an input example by loading images in *file_paths*.
Args: file_paths: list of file paths . mean: list containing mean values for each band in the images in *file_paths*. std: list containing std values for each band in the images in *file_paths*.
Returns: np.array containing created example list of meta info for each image in *file_paths* """
imgs = [] metas = [] temporal_coords = [] location_coords = []
for file in file_paths: img, meta, coords = read_geotiff(file)
# Rescaling (don't normalize on nodata) img = np.moveaxis(img, 0, -1) # channels last for rescaling if indices is not None: img = img[..., indices] if mean is not None and std is not None: img = np.where(img == NO_DATA, NO_DATA_FLOAT, (img - mean) / std)
imgs.append(img) metas.append(meta) if coords is not None: location_coords.append(coords)
try: match = re.search(r'(\d{7,8}T\d{6})', file) if match: year = int(match.group(1)[:4]) julian_day = match.group(1).split('T')[0][4:] if len(julian_day) == 3: julian_day = int(julian_day) else: julian_day = datetime.datetime.strptime(julian_day, '%m%d').timetuple().tm_yday temporal_coords.append([year, julian_day]) except Exception as e: print(f'Could not extract timestamp for {file} ({e})')
imgs = np.stack(imgs, axis=0) # num_frames, H, W, C imgs = np.moveaxis(imgs, -1, 0).astype("float32") # C, num_frames, H, W imgs = np.expand_dims(imgs, axis=0) # add batch di
return imgs, temporal_coords, location_coords, metas
def run_model(input_data, temporal_coords, location_coords, model, datamodule, img_size): # Reflect pad if not divisible by img_size original_h, original_w = input_data.shape[-2:] pad_h = (img_size - (original_h % img_size)) % img_size pad_w = (img_size - (original_w % img_size)) % img_size input_data = np.pad( input_data, ((0, 0), (0, 0), (0, 0), (0, pad_h), (0, pad_w)), mode="reflect" )
# Build sliding window
batch_size = 1 batch = torch.tensor(input_data, device="cpu") windows = batch.unfold(3, img_size, img_size).unfold(4, img_size, img_size) h1, w1 = windows.shape[3:5] windows = rearrange( windows, "b c t h1 w1 h w -> (b h1 w1) c t h w", h=img_size, w=img_size )
# Split into batches if number of windows > batch_size num_batches = windows.shape[0] // batch_size if windows.shape[0] > batch_size else 1 windows = torch.tensor_split(windows, num_batches, dim=0)
if temporal_coords: temporal_coords = torch.Tensor(temporal_coords, device=model.device).unsqueeze(0) else: temporal_coords = None if location_coords: location_coords = torch.Tensor(location_coords[0], device=model.device).unsqueeze(0) else: location_coords = None
# Run model pred_imgs = [] for x in windows: # Apply standardization x = datamodule.test_transform(image=x.squeeze().numpy().transpose(1,2,0)) x = datamodule.aug(x['image'])
with torch.no_grad(): x = x.to(model.device) pred = model(x, temporal_coords=temporal_coords, location_coords=location_coords) pred = pred.output.detach().cpu()
y_hat = pred.argmax(dim=1)
y_hat = torch.nn.functional.interpolate(y_hat.unsqueeze(1).float(), size=img_size, mode="nearest")
pred_imgs.append(y_hat)
pred_imgs = torch.concat(pred_imgs, dim=0)
# Build images from patches pred_imgs = rearrange( pred_imgs, "(b h1 w1) c h w -> b c (h1 h) (w1 w)", h=img_size, w=img_size, b=1, c=1, h1=h1, w1=w1, )
# Cut padded area back to original size pred_imgs = pred_imgs[..., :original_h, :original_w]
# Squeeze (batch size 1) pred_imgs = pred_imgs[0]
return pred_imgs
def main( data_file: str, config: str, checkpoint: str, output_dir: str, rgb_outputs: bool, input_indices: list[int] = None,): os.makedirs(output_dir, exist_ok=True)
with open(config, "r") as f: config_dict = yaml.safe_load(f)
# Load model ---------------------------------------------------------------------------------
lightning_model = LightningInferenceModel.from_config(config, checkpoint) img_size = 512 # Size of Sen1Floods11
# Loading data ---------------------------------------------------------------------------------
input_data, temporal_coords, location_coords, meta_data = load_example( file_paths=[data_file], indices=input_indices, )
meta_data = meta_data[0] # only one image
if input_data.mean() > 1: input_data = input_data / 10000 # Convert to range 0-1
# Running model --------------------------------------------------------------------------------
lightning_model.model.eval()
channels = [config_dict['data']['init_args']['bands'].index(b) for b in ["RED", "GREEN", "BLUE"]] # BGR -> RGB
pred = run_model(input_data, temporal_coords, location_coords, lightning_model.model, lightning_model.datamodule, img_size)
# Save pred meta_data.update(count=1, dtype="uint8", compress="lzw", nodata=0) pred_file = os.path.join(output_dir, f"pred_{os.path.splitext(os.path.basename(data_file))[0]}.tiff") save_geotiff(_convert_np_uint8(pred), pred_file, meta_data)
# Save image + pred meta_data.update(count=3, dtype="uint8", compress="lzw", nodata=0)
if input_data.mean() < 1: input_data = input_data * 10000 # Scale to 0-10000
rgb_orig = process_channel_group( orig_img=torch.Tensor(input_data[0, :, 0, ...]), channels=channels, )
pred[pred == 0.] = np.nan img_pred = rgb_orig * 0.7 + pred * 0.3 img_pred[img_pred.isnan()] = rgb_orig[img_pred.isnan()]
img_pred_file = os.path.join(output_dir, f"rgb_pred_{os.path.splitext(os.path.basename(data_file))[0]}.tiff") save_geotiff( image=_convert_np_uint8(img_pred), output_path=img_pred_file, meta=meta_data, )
# Save image rgb if rgb_outputs: rgb_file = os.path.join(output_dir, f"original_rgb_{os.path.splitext(os.path.basename(data_file))[0]}.tiff") save_geotiff( image=_convert_np_uint8(rgb_orig), output_path=rgb_file, meta=meta_data, )
print("Done!")
if __name__ == "__main__": parser = argparse.ArgumentParser("MAE run inference", add_help=False)
parser.add_argument( "--data_file", type=str, default="examples/India_900498_S2Hand.tif", help="Path to the file.", ) parser.add_argument( "--config", "-c", type=str, default="config.yaml", help="Path to yaml file containing model parameters.", ) parser.add_argument( "--checkpoint", type=str, default="Prithvi-EO-V2-300M-TL-Sen1Floods11.pt", help="Path to a checkpoint file to load from.", ) parser.add_argument( "--output_dir", type=str, default="output", help="Path to the directory where to save outputs.", ) parser.add_argument( "--input_indices", default=[1,2,3,8,11,12], type=int, nargs="+", help="0-based indices of the six Prithvi channels to be selected from the input. By default selects [1,2,3,8,11,12] for S2L1C data.", ) parser.add_argument( "--rgb_outputs", action="store_true", help="If present, output files will only contain RGB channels. " "Otherwise, all bands will be saved.", ) args = parser.parse_args()
main(**vars(args))123456torchtorchvisiontimmeinopsrasteriogit+https://github.com/IBM/terratorch.gitREADME.mdAdded+59
config.yamlAdded+182
model_inference.pyAdded+344
requirements.txtAdded+6