Feature Extraction
Transformers
Safetensors
English
remote-sensing
earth-observation
self-supervised-learning
satellite
multispectral
vision
satmae
satmae-pp
vit
mae
Instructions to use BiliSakura/SATMAE-PP-transformers with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use BiliSakura/SATMAE-PP-transformers with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="BiliSakura/SATMAE-PP-transformers")# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("BiliSakura/SATMAE-PP-transformers", dtype="auto") - Notebooks
- Google Colab
- Kaggle
Upload SatMAE++ transformers checkpoints with model card metadata
Browse files- README.md +119 -0
- satmae-pp-vit-large-patch16-fmow-rgb-pretrain/config.json +71 -0
- satmae-pp-vit-large-patch16-fmow-rgb-pretrain/image_processing_satmae_pp.py +189 -0
- satmae-pp-vit-large-patch16-fmow-rgb-pretrain/model.safetensors +3 -0
- satmae-pp-vit-large-patch16-fmow-rgb-pretrain/modeling_satmae_pp.py +285 -0
- satmae-pp-vit-large-patch16-fmow-rgb-pretrain/pipeline_satmae_pp.py +79 -0
- satmae-pp-vit-large-patch16-fmow-rgb-pretrain/preprocessor_config.json +25 -0
- satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/config.json +85 -0
- satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/image_processing_satmae_pp.py +189 -0
- satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/model.safetensors +3 -0
- satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/modeling_satmae_pp.py +285 -0
- satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/pipeline_satmae_pp.py +79 -0
- satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/preprocessor_config.json +39 -0
README.md
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
tags:
|
| 6 |
+
- remote-sensing
|
| 7 |
+
- earth-observation
|
| 8 |
+
- self-supervised-learning
|
| 9 |
+
- satellite
|
| 10 |
+
- multispectral
|
| 11 |
+
- feature-extraction
|
| 12 |
+
- vision
|
| 13 |
+
- satmae
|
| 14 |
+
- satmae-pp
|
| 15 |
+
- vit
|
| 16 |
+
- mae
|
| 17 |
+
- transformers
|
| 18 |
+
library_name: transformers
|
| 19 |
+
pipeline_tag: feature-extraction
|
| 20 |
+
datasets:
|
| 21 |
+
- fMoW
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
# SatMAE++ Transformers Models
|
| 25 |
+
|
| 26 |
+
Hugging Face–compatible checkpoints converted from the official [SatMAE++](https://arxiv.org/abs/2403.05419) pretrained weights. Each subfolder is a standalone model repo layout (`config.json`, `model.safetensors`, preprocessor, and remote code) for feature extraction on FMoW satellite imagery.
|
| 27 |
+
|
| 28 |
+
## Model Description
|
| 29 |
+
|
| 30 |
+
These models are ViT-Large encoders pretrained with multi-scale masked autoencoding (SatMAE++) on [fMoW-RGB](https://github.com/fMoW/dataset) and [fMoW-Sentinel](https://github.com/sustainlab-group/SatMAE) imagery.
|
| 31 |
+
|
| 32 |
+
This collection currently bundles **2 converted pretrain checkpoints**:
|
| 33 |
+
|
| 34 |
+
- **FMoW-RGB:** vanilla ViT-L/16, 3-channel BGR, 224×224
|
| 35 |
+
- **FMoW-Sentinel:** grouped-channel ViT-L/8, 10-band multispectral, 96×96
|
| 36 |
+
|
| 37 |
+
All folders ship self-contained remote code (`modeling_satmae_pp.py`, processor, pipeline) and load with `trust_remote_code=True`.
|
| 38 |
+
|
| 39 |
+
**Developed by:** [techmn / SatMAE++](https://github.com/techmn/satmae_pp)
|
| 40 |
+
**Converted for Hugging Face by:** BiliSakura
|
| 41 |
+
**License (weights):** MIT
|
| 42 |
+
**Original paper:** [Rethinking Transformers Pre-training for Multi-Spectral Satellite Imagery](https://arxiv.org/abs/2403.05419) (CVPR 2024)
|
| 43 |
+
|
| 44 |
+
## Available checkpoints
|
| 45 |
+
|
| 46 |
+
| Folder | Dataset | Encoder | Channels | Image | Patch | Legacy file |
|
| 47 |
+
|--------|---------|---------|----------|-------|-------|-------------|
|
| 48 |
+
| `satmae-pp-vit-large-patch16-fmow-rgb-pretrain` | FMoW-RGB | vanilla ViT | 3 (BGR) | 224 | 16 | `checkpoint_ViT-L_pretrain_fmow_rgb.pth` |
|
| 49 |
+
| `satmae-pp-vit-large-patch8-fmow-sentinel-pretrain` | FMoW-Sentinel | group-channel ViT | 10 | 96 | 8 | `checkpoint_ViT-L_pretrain_fmow_sentinel.pth` |
|
| 50 |
+
|
| 51 |
+
Legacy `.pth` filename mapping is in [`conversion_manifest.json`](conversion_manifest.json).
|
| 52 |
+
|
| 53 |
+
## Usage
|
| 54 |
+
|
| 55 |
+
```python
|
| 56 |
+
from transformers import pipeline
|
| 57 |
+
import numpy as np
|
| 58 |
+
|
| 59 |
+
REPO = "BiliSakura/SATMAE-PP-transformers"
|
| 60 |
+
SUBFOLDER = "satmae-pp-vit-large-patch8-fmow-sentinel-pretrain"
|
| 61 |
+
|
| 62 |
+
pipe = pipeline(
|
| 63 |
+
task="satmae-pp-feature-extraction",
|
| 64 |
+
model=REPO,
|
| 65 |
+
trust_remote_code=True,
|
| 66 |
+
model_kwargs={"subfolder": SUBFOLDER},
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# FMoW-Sentinel: 10 bands after dropping bands 0, 9, 10
|
| 70 |
+
image = np.random.randint(0, 255, (96, 96, 10), dtype=np.uint8)
|
| 71 |
+
features = pipe(image, pool=True, return_tensors=True)
|
| 72 |
+
print(features.shape) # [1, 1024]
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
FMoW-RGB (BGR channel order):
|
| 76 |
+
|
| 77 |
+
```python
|
| 78 |
+
SUBFOLDER = "satmae-pp-vit-large-patch16-fmow-rgb-pretrain"
|
| 79 |
+
pipe = pipeline(
|
| 80 |
+
task="satmae-pp-feature-extraction",
|
| 81 |
+
model=REPO,
|
| 82 |
+
trust_remote_code=True,
|
| 83 |
+
model_kwargs={"subfolder": SUBFOLDER},
|
| 84 |
+
)
|
| 85 |
+
image = np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)
|
| 86 |
+
features = pipe(image, pool=True, return_tensors=True)
|
| 87 |
+
print(features.shape) # [1, 1024]
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
Load components directly:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
from transformers import AutoModel, AutoImageProcessor
|
| 94 |
+
|
| 95 |
+
model = AutoModel.from_pretrained(REPO, subfolder=SUBFOLDER, trust_remote_code=True)
|
| 96 |
+
processor = AutoImageProcessor.from_pretrained(REPO, subfolder=SUBFOLDER, trust_remote_code=True)
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
## Normalization
|
| 100 |
+
|
| 101 |
+
The bundled image processor applies per-channel FMoW mean/std normalization by default (`do_normalize=True`). FMoW-RGB models expect **BGR** channel order; the processor swaps RGB→BGR when `channel_order="bgr"`.
|
| 102 |
+
|
| 103 |
+
For FMoW-Sentinel, inputs should be 10-band reflectance arrays (bands 0, 9, 10 already dropped) with FMoW-Sentinel statistics baked into the preprocessor config.
|
| 104 |
+
|
| 105 |
+
## Dependencies
|
| 106 |
+
|
| 107 |
+
- `transformers`, `torch`, `timm`, `safetensors`
|
| 108 |
+
- `opencv-python` (multispectral resize with more than 4 channels)
|
| 109 |
+
|
| 110 |
+
## Citation
|
| 111 |
+
|
| 112 |
+
```bibtex
|
| 113 |
+
@inproceedings{satmaepp2024rethinking,
|
| 114 |
+
title={Rethinking Transformers Pre-training for Multi-Spectral Satellite Imagery},
|
| 115 |
+
author={Mubashir Noman and Muzammal Naseer and Hisham Cholakkal and Rao Muhammad Anwar and Salman Khan and Fahad Shahbaz Khan},
|
| 116 |
+
year={2024},
|
| 117 |
+
booktitle={CVPR}
|
| 118 |
+
}
|
| 119 |
+
```
|
satmae-pp-vit-large-patch16-fmow-rgb-pretrain/config.json
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SatMAEppModel"
|
| 4 |
+
],
|
| 5 |
+
"attention_probs_dropout_prob": 0.0,
|
| 6 |
+
"channel_embed_dim": 256,
|
| 7 |
+
"channel_groups": [
|
| 8 |
+
[
|
| 9 |
+
0,
|
| 10 |
+
1,
|
| 11 |
+
2,
|
| 12 |
+
6
|
| 13 |
+
],
|
| 14 |
+
[
|
| 15 |
+
3,
|
| 16 |
+
4,
|
| 17 |
+
5,
|
| 18 |
+
7
|
| 19 |
+
],
|
| 20 |
+
[
|
| 21 |
+
8,
|
| 22 |
+
9
|
| 23 |
+
]
|
| 24 |
+
],
|
| 25 |
+
"channel_order": "bgr",
|
| 26 |
+
"checkpoint_stage": "pretrain",
|
| 27 |
+
"dataset": "fmow_rgb",
|
| 28 |
+
"dtype": "float32",
|
| 29 |
+
"encoder_type": "vanilla",
|
| 30 |
+
"global_pool": true,
|
| 31 |
+
"hidden_act": "gelu",
|
| 32 |
+
"hidden_dropout_prob": 0.0,
|
| 33 |
+
"hidden_size": 1024,
|
| 34 |
+
"id2label": {},
|
| 35 |
+
"image_mean": [
|
| 36 |
+
0.4182007312774658,
|
| 37 |
+
0.4214799106121063,
|
| 38 |
+
0.3991275727748871
|
| 39 |
+
],
|
| 40 |
+
"image_size": 224,
|
| 41 |
+
"image_std": [
|
| 42 |
+
0.28774282336235046,
|
| 43 |
+
0.27541765570640564,
|
| 44 |
+
0.2764017581939697
|
| 45 |
+
],
|
| 46 |
+
"initializer_range": 0.02,
|
| 47 |
+
"intermediate_size": 4096,
|
| 48 |
+
"label2id": {},
|
| 49 |
+
"layer_norm_eps": 1e-06,
|
| 50 |
+
"mlp_ratio": 4.0,
|
| 51 |
+
"model_type": "satmae_pp",
|
| 52 |
+
"num_attention_heads": 16,
|
| 53 |
+
"num_channels": 3,
|
| 54 |
+
"num_hidden_layers": 24,
|
| 55 |
+
"patch_size": 16,
|
| 56 |
+
"qkv_bias": true,
|
| 57 |
+
"transformers_version": "5.0.0",
|
| 58 |
+
"auto_map": {
|
| 59 |
+
"AutoConfig": "modeling_satmae_pp.SatMAEppConfig",
|
| 60 |
+
"AutoModel": "modeling_satmae_pp.SatMAEppModel",
|
| 61 |
+
"AutoModelForImageClassification": "modeling_satmae_pp.SatMAEppForImageClassification"
|
| 62 |
+
},
|
| 63 |
+
"custom_pipelines": {
|
| 64 |
+
"satmae-pp-feature-extraction": {
|
| 65 |
+
"impl": "pipeline_satmae_pp.SatMAEppImageFeatureExtractionPipeline",
|
| 66 |
+
"pt": [
|
| 67 |
+
"AutoModel"
|
| 68 |
+
]
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
}
|
satmae-pp-vit-large-patch16-fmow-rgb-pretrain/image_processing_satmae_pp.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 SatMAE++ Authors and The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
"""Image processor for SatMAE++ models."""
|
| 6 |
+
|
| 7 |
+
from typing import Optional, Union
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 12 |
+
from transformers.image_transforms import resize, to_channel_dimension_format
|
| 13 |
+
from transformers.image_utils import (
|
| 14 |
+
ChannelDimension,
|
| 15 |
+
ImageInput,
|
| 16 |
+
PILImageResampling,
|
| 17 |
+
infer_channel_dimension_format,
|
| 18 |
+
make_flat_list_of_images,
|
| 19 |
+
to_numpy_array,
|
| 20 |
+
valid_images,
|
| 21 |
+
validate_preprocess_arguments,
|
| 22 |
+
)
|
| 23 |
+
from transformers.utils import TensorType, filter_out_non_signature_kwargs, logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _resize_multispectral(image: np.ndarray, size: dict[str, int], input_data_format: ChannelDimension) -> np.ndarray:
|
| 30 |
+
target_height, target_width = size["height"], size["width"]
|
| 31 |
+
|
| 32 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 33 |
+
image = np.transpose(image, (1, 2, 0))
|
| 34 |
+
|
| 35 |
+
height, width, _ = image.shape
|
| 36 |
+
if height == target_height and width == target_width:
|
| 37 |
+
resized = image
|
| 38 |
+
else:
|
| 39 |
+
try:
|
| 40 |
+
import cv2
|
| 41 |
+
except ImportError as exc:
|
| 42 |
+
raise ImportError(
|
| 43 |
+
"Multispectral resize requires OpenCV (`opencv-python`) when input has more than 4 channels."
|
| 44 |
+
) from exc
|
| 45 |
+
resized = cv2.resize(image, (target_width, target_height), interpolation=cv2.INTER_LINEAR)
|
| 46 |
+
|
| 47 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 48 |
+
return np.transpose(resized, (2, 0, 1))
|
| 49 |
+
return resized
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _reorder_channels(image: np.ndarray, channel_order: str, input_data_format: ChannelDimension) -> np.ndarray:
|
| 53 |
+
if channel_order != "bgr":
|
| 54 |
+
return image
|
| 55 |
+
|
| 56 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 57 |
+
if image.shape[0] < 3:
|
| 58 |
+
return image
|
| 59 |
+
return image[[2, 1, 0], ...]
|
| 60 |
+
if image.shape[-1] < 3:
|
| 61 |
+
return image
|
| 62 |
+
return image[..., [2, 1, 0]]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class SatMAEppImageProcessor(BaseImageProcessor):
|
| 66 |
+
"""
|
| 67 |
+
Image processor for SatMAE++ satellite encoders.
|
| 68 |
+
|
| 69 |
+
FMoW-RGB checkpoints were trained with BGR channel order. Set `channel_order="bgr"` (default for RGB models)
|
| 70 |
+
to swap the first three channels from RGB to BGR before inference.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
model_input_names = ["pixel_values"]
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
do_resize: bool = True,
|
| 78 |
+
size: Optional[dict[str, int]] = None,
|
| 79 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 80 |
+
do_rescale: bool = False,
|
| 81 |
+
rescale_factor: float = 1.0,
|
| 82 |
+
do_normalize: bool = True,
|
| 83 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 84 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 85 |
+
do_convert_rgb: bool = False,
|
| 86 |
+
channel_order: str = "rgb",
|
| 87 |
+
**kwargs,
|
| 88 |
+
):
|
| 89 |
+
super().__init__(**kwargs)
|
| 90 |
+
size = size if size is not None else {"height": 224, "width": 224}
|
| 91 |
+
self.do_resize = do_resize
|
| 92 |
+
self.size = size
|
| 93 |
+
self.resample = resample
|
| 94 |
+
self.do_rescale = do_rescale
|
| 95 |
+
self.rescale_factor = rescale_factor
|
| 96 |
+
self.do_normalize = do_normalize
|
| 97 |
+
self.image_mean = image_mean
|
| 98 |
+
self.image_std = image_std
|
| 99 |
+
self.do_convert_rgb = do_convert_rgb
|
| 100 |
+
self.channel_order = channel_order
|
| 101 |
+
|
| 102 |
+
@filter_out_non_signature_kwargs()
|
| 103 |
+
def preprocess(
|
| 104 |
+
self,
|
| 105 |
+
images: ImageInput,
|
| 106 |
+
do_resize: Optional[bool] = None,
|
| 107 |
+
size: Optional[dict[str, int]] = None,
|
| 108 |
+
resample: Optional[PILImageResampling] = None,
|
| 109 |
+
do_rescale: Optional[bool] = None,
|
| 110 |
+
rescale_factor: Optional[float] = None,
|
| 111 |
+
do_normalize: Optional[bool] = None,
|
| 112 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 113 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 114 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 115 |
+
data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
|
| 116 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 117 |
+
do_convert_rgb: Optional[bool] = None,
|
| 118 |
+
channel_order: Optional[str] = None,
|
| 119 |
+
):
|
| 120 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 121 |
+
size = size if size is not None else self.size
|
| 122 |
+
size = get_size_dict(size, default_to_square=True)
|
| 123 |
+
resample = resample if resample is not None else self.resample
|
| 124 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 125 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 126 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 127 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 128 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 129 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 130 |
+
channel_order = channel_order if channel_order is not None else self.channel_order
|
| 131 |
+
|
| 132 |
+
if do_normalize and (image_mean is None or image_std is None):
|
| 133 |
+
raise ValueError("Normalization requires `image_mean` and `image_std` with one value per channel.")
|
| 134 |
+
|
| 135 |
+
images = make_flat_list_of_images(images)
|
| 136 |
+
if not valid_images(images):
|
| 137 |
+
raise ValueError("Invalid image type. Must be PIL, numpy, or torch tensor.")
|
| 138 |
+
|
| 139 |
+
validate_preprocess_arguments(
|
| 140 |
+
do_rescale=do_rescale,
|
| 141 |
+
rescale_factor=rescale_factor,
|
| 142 |
+
do_normalize=do_normalize,
|
| 143 |
+
image_mean=image_mean,
|
| 144 |
+
image_std=image_std,
|
| 145 |
+
do_resize=do_resize,
|
| 146 |
+
size=size,
|
| 147 |
+
resample=resample,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
processed_images = []
|
| 151 |
+
for image in images:
|
| 152 |
+
image = to_numpy_array(image)
|
| 153 |
+
if do_convert_rgb:
|
| 154 |
+
image = self._convert_image_to_rgb(image)
|
| 155 |
+
|
| 156 |
+
if input_data_format is None:
|
| 157 |
+
try:
|
| 158 |
+
input_data_format = infer_channel_dimension_format(image)
|
| 159 |
+
except ValueError:
|
| 160 |
+
input_data_format = ChannelDimension.LAST
|
| 161 |
+
|
| 162 |
+
image = _reorder_channels(image, channel_order=channel_order, input_data_format=input_data_format)
|
| 163 |
+
|
| 164 |
+
if do_resize:
|
| 165 |
+
num_channels = image.shape[0] if input_data_format == ChannelDimension.FIRST else image.shape[-1]
|
| 166 |
+
if num_channels > 4:
|
| 167 |
+
image = _resize_multispectral(image, size=size, input_data_format=input_data_format)
|
| 168 |
+
else:
|
| 169 |
+
image = resize(
|
| 170 |
+
image,
|
| 171 |
+
size=(size["height"], size["width"]),
|
| 172 |
+
resample=resample,
|
| 173 |
+
input_data_format=input_data_format,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
if do_rescale:
|
| 177 |
+
image = image * rescale_factor
|
| 178 |
+
|
| 179 |
+
if do_normalize:
|
| 180 |
+
image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 181 |
+
|
| 182 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 183 |
+
processed_images.append(image)
|
| 184 |
+
|
| 185 |
+
data = {"pixel_values": processed_images}
|
| 186 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
__all__ = ["SatMAEppImageProcessor"]
|
satmae-pp-vit-large-patch16-fmow-rgb-pretrain/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fc037acaba43f824bb725ffa30469084956c334fae10a110d7fd28ff62211c33
|
| 3 |
+
size 1213234544
|
satmae-pp-vit-large-patch16-fmow-rgb-pretrain/modeling_satmae_pp.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 SatMAE++ Authors and The HuggingFace Inc. team.
|
| 2 |
+
"""Self-contained SatMAE++ model and config for trust_remote_code loading."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from functools import partial
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from timm.models.vision_transformer import Block, PatchEmbed
|
| 12 |
+
from torch import nn
|
| 13 |
+
|
| 14 |
+
from transformers.configuration_utils import PretrainedConfig as PreTrainedConfig
|
| 15 |
+
from transformers.modeling_outputs import BaseModelOutputWithPooling, ImageClassifierOutput
|
| 16 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 17 |
+
from transformers.processing_utils import Unpack
|
| 18 |
+
from transformers.utils import TransformersKwargs, logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
FMOW_RGB_MEAN = [0.4182007312774658, 0.4214799106121063, 0.3991275727748871]
|
| 24 |
+
FMOW_RGB_STD = [0.28774282336235046, 0.27541765570640564, 0.2764017581939697]
|
| 25 |
+
FMOW_SENTINEL_MEAN_10 = [
|
| 26 |
+
1184.3824625, 1120.77120066, 1136.26026392, 1263.73947144, 1645.40315151,
|
| 27 |
+
1846.87040806, 1762.59530783, 1972.62420416, 1732.16362238, 1247.91870117,
|
| 28 |
+
]
|
| 29 |
+
FMOW_SENTINEL_STD_10 = [
|
| 30 |
+
650.2842772, 712.12507725, 965.23119807, 948.9819932, 1108.06650639,
|
| 31 |
+
1258.36394548, 1233.1492281, 1364.38688993, 1310.36996126, 1087.6020813,
|
| 32 |
+
]
|
| 33 |
+
DEFAULT_CHANNEL_GROUPS = [[0, 1, 2, 6], [3, 4, 5, 7], [8, 9]]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_2d_sincos_pos_embed(embed_dim: int, grid_size: int, cls_token: bool = False) -> np.ndarray:
|
| 37 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 38 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 39 |
+
grid = np.meshgrid(grid_w, grid_h)
|
| 40 |
+
grid = np.stack(grid, axis=0).reshape([2, 1, grid_size, grid_size])
|
| 41 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 42 |
+
if cls_token:
|
| 43 |
+
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
|
| 44 |
+
return pos_embed
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim: int, grid: np.ndarray) -> np.ndarray:
|
| 48 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0])
|
| 49 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1])
|
| 50 |
+
return np.concatenate([emb_h, emb_w], axis=1)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim: int, pos: np.ndarray) -> np.ndarray:
|
| 54 |
+
omega = np.arange(embed_dim // 2, dtype=np.float32)
|
| 55 |
+
omega /= embed_dim / 2.0
|
| 56 |
+
omega = 1.0 / 10000**omega
|
| 57 |
+
pos = pos.reshape(-1)
|
| 58 |
+
out = np.einsum("m,d->md", pos, omega)
|
| 59 |
+
return np.concatenate([np.sin(out), np.cos(out)], axis=1)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class SatMAEppConfig(PreTrainedConfig):
|
| 63 |
+
model_type = "satmae_pp"
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
hidden_size: int = 1024,
|
| 68 |
+
num_hidden_layers: int = 24,
|
| 69 |
+
num_attention_heads: int = 16,
|
| 70 |
+
intermediate_size: int | None = None,
|
| 71 |
+
hidden_act: str = "gelu",
|
| 72 |
+
hidden_dropout_prob: float = 0.0,
|
| 73 |
+
attention_probs_dropout_prob: float = 0.0,
|
| 74 |
+
initializer_range: float = 0.02,
|
| 75 |
+
layer_norm_eps: float = 1e-6,
|
| 76 |
+
image_size: int = 224,
|
| 77 |
+
patch_size: int = 16,
|
| 78 |
+
num_channels: int = 3,
|
| 79 |
+
qkv_bias: bool = True,
|
| 80 |
+
mlp_ratio: float = 4.0,
|
| 81 |
+
global_pool: bool = True,
|
| 82 |
+
encoder_type: str = "vanilla",
|
| 83 |
+
channel_embed_dim: int = 256,
|
| 84 |
+
channel_groups: list[list[int]] | None = None,
|
| 85 |
+
channel_order: str = "bgr",
|
| 86 |
+
dataset: str = "fmow_rgb",
|
| 87 |
+
checkpoint_stage: str = "finetune",
|
| 88 |
+
image_mean: list[float] | None = None,
|
| 89 |
+
image_std: list[float] | None = None,
|
| 90 |
+
num_labels: int = 0,
|
| 91 |
+
**kwargs,
|
| 92 |
+
):
|
| 93 |
+
super().__init__(**kwargs)
|
| 94 |
+
self.hidden_size = hidden_size
|
| 95 |
+
self.num_hidden_layers = num_hidden_layers
|
| 96 |
+
self.num_attention_heads = num_attention_heads
|
| 97 |
+
self.hidden_act = hidden_act
|
| 98 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 99 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 100 |
+
self.initializer_range = initializer_range
|
| 101 |
+
self.layer_norm_eps = layer_norm_eps
|
| 102 |
+
self.image_size = image_size
|
| 103 |
+
self.patch_size = patch_size
|
| 104 |
+
self.num_channels = num_channels
|
| 105 |
+
self.qkv_bias = qkv_bias
|
| 106 |
+
self.mlp_ratio = mlp_ratio
|
| 107 |
+
self.global_pool = global_pool
|
| 108 |
+
self.encoder_type = encoder_type
|
| 109 |
+
self.channel_embed_dim = channel_embed_dim
|
| 110 |
+
self.channel_groups = channel_groups if channel_groups is not None else list(DEFAULT_CHANNEL_GROUPS)
|
| 111 |
+
self.channel_order = channel_order
|
| 112 |
+
self.dataset = dataset
|
| 113 |
+
self.checkpoint_stage = checkpoint_stage
|
| 114 |
+
self.num_labels = num_labels
|
| 115 |
+
self.intermediate_size = int(hidden_size * mlp_ratio) if intermediate_size is None else intermediate_size
|
| 116 |
+
if image_mean is None or image_std is None:
|
| 117 |
+
if encoder_type == "group_channel":
|
| 118 |
+
self.image_mean = FMOW_SENTINEL_MEAN_10
|
| 119 |
+
self.image_std = FMOW_SENTINEL_STD_10
|
| 120 |
+
else:
|
| 121 |
+
self.image_mean = FMOW_RGB_MEAN
|
| 122 |
+
self.image_std = FMOW_RGB_STD
|
| 123 |
+
else:
|
| 124 |
+
self.image_mean = image_mean
|
| 125 |
+
self.image_std = image_std
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class SatMAEppPreTrainedModel(PreTrainedModel):
|
| 129 |
+
config_class = SatMAEppConfig
|
| 130 |
+
config: SatMAEppConfig
|
| 131 |
+
base_model_prefix = "satmae_pp"
|
| 132 |
+
main_input_name = "pixel_values"
|
| 133 |
+
input_modalities = ("image",)
|
| 134 |
+
supports_gradient_checkpointing = True
|
| 135 |
+
_no_split_modules = ["Block"]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class SatMAEppModel(SatMAEppPreTrainedModel):
|
| 139 |
+
def __init__(self, config: SatMAEppConfig, add_pooling_layer: bool = True):
|
| 140 |
+
super().__init__(config)
|
| 141 |
+
self.config = config
|
| 142 |
+
self.add_pooling_layer = add_pooling_layer
|
| 143 |
+
if config.encoder_type == "group_channel":
|
| 144 |
+
self._init_group_channel_encoder(config)
|
| 145 |
+
else:
|
| 146 |
+
self._init_vanilla_encoder(config)
|
| 147 |
+
self.post_init()
|
| 148 |
+
|
| 149 |
+
def _init_vanilla_encoder(self, config: SatMAEppConfig) -> None:
|
| 150 |
+
image_size = config.image_size if isinstance(config.image_size, int) else config.image_size[0]
|
| 151 |
+
norm_layer = partial(nn.LayerNorm, eps=config.layer_norm_eps)
|
| 152 |
+
self.patch_embed = PatchEmbed(image_size, config.patch_size, config.num_channels, config.hidden_size)
|
| 153 |
+
self.num_patches = self.patch_embed.num_patches
|
| 154 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 155 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + 1, config.hidden_size))
|
| 156 |
+
pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.num_patches**0.5), cls_token=True)
|
| 157 |
+
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 158 |
+
self.blocks = nn.ModuleList([
|
| 159 |
+
Block(config.hidden_size, config.num_attention_heads, config.mlp_ratio, qkv_bias=config.qkv_bias, norm_layer=norm_layer)
|
| 160 |
+
for _ in range(config.num_hidden_layers)
|
| 161 |
+
])
|
| 162 |
+
self.global_pool = config.global_pool
|
| 163 |
+
if self.global_pool:
|
| 164 |
+
self.fc_norm = norm_layer(config.hidden_size)
|
| 165 |
+
self.norm = None
|
| 166 |
+
else:
|
| 167 |
+
self.fc_norm = None
|
| 168 |
+
self.norm = norm_layer(config.hidden_size)
|
| 169 |
+
|
| 170 |
+
def _init_group_channel_encoder(self, config: SatMAEppConfig) -> None:
|
| 171 |
+
image_size = config.image_size if isinstance(config.image_size, int) else config.image_size[0]
|
| 172 |
+
norm_layer = partial(nn.LayerNorm, eps=config.layer_norm_eps)
|
| 173 |
+
self.channel_groups = tuple(tuple(group) for group in config.channel_groups)
|
| 174 |
+
self.patch_embed = nn.ModuleList([
|
| 175 |
+
PatchEmbed(image_size, config.patch_size, len(group), config.hidden_size)
|
| 176 |
+
for group in self.channel_groups
|
| 177 |
+
])
|
| 178 |
+
self.num_patches = self.patch_embed[0].num_patches
|
| 179 |
+
pos_dim = config.hidden_size - config.channel_embed_dim
|
| 180 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + 1, pos_dim))
|
| 181 |
+
pos_embed = get_2d_sincos_pos_embed(pos_dim, int(self.num_patches**0.5), cls_token=True)
|
| 182 |
+
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 183 |
+
num_groups = len(self.channel_groups)
|
| 184 |
+
self.channel_embed = nn.Parameter(torch.zeros(1, num_groups, config.channel_embed_dim))
|
| 185 |
+
chan_embed = get_1d_sincos_pos_embed_from_grid(self.channel_embed.shape[-1], np.arange(num_groups))
|
| 186 |
+
self.channel_embed.data.copy_(torch.from_numpy(chan_embed).float().unsqueeze(0))
|
| 187 |
+
self.channel_cls_embed = nn.Parameter(torch.zeros(1, 1, config.channel_embed_dim))
|
| 188 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 189 |
+
self.blocks = nn.ModuleList([
|
| 190 |
+
Block(config.hidden_size, config.num_attention_heads, config.mlp_ratio, qkv_bias=config.qkv_bias, norm_layer=norm_layer)
|
| 191 |
+
for _ in range(config.num_hidden_layers)
|
| 192 |
+
])
|
| 193 |
+
self.global_pool = config.global_pool
|
| 194 |
+
if self.global_pool:
|
| 195 |
+
self.fc_norm = norm_layer(config.hidden_size)
|
| 196 |
+
self.norm = None
|
| 197 |
+
else:
|
| 198 |
+
self.fc_norm = None
|
| 199 |
+
self.norm = norm_layer(config.hidden_size)
|
| 200 |
+
|
| 201 |
+
def _forward_vanilla(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 202 |
+
batch_size = pixel_values.shape[0]
|
| 203 |
+
patch_tokens = self.patch_embed(pixel_values)
|
| 204 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 205 |
+
hidden_states = torch.cat((cls_tokens, patch_tokens), dim=1) + self.pos_embed
|
| 206 |
+
for block in self.blocks:
|
| 207 |
+
hidden_states = block(hidden_states)
|
| 208 |
+
if self.global_pool:
|
| 209 |
+
pooled_output = self.fc_norm(hidden_states[:, 1:, :].mean(dim=1))
|
| 210 |
+
else:
|
| 211 |
+
hidden_states = self.norm(hidden_states)
|
| 212 |
+
pooled_output = hidden_states[:, 0]
|
| 213 |
+
return hidden_states, pooled_output
|
| 214 |
+
|
| 215 |
+
def _forward_group_channel(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 216 |
+
batch_size = pixel_values.shape[0]
|
| 217 |
+
group_tokens = [self.patch_embed[i](pixel_values[:, group, :, :]) for i, group in enumerate(self.channel_groups)]
|
| 218 |
+
hidden_states = torch.stack(group_tokens, dim=1)
|
| 219 |
+
channel_embed = self.channel_embed.unsqueeze(2).expand(-1, -1, self.pos_embed[:, 1:, :].shape[1], -1)
|
| 220 |
+
pos_embed = self.pos_embed[:, 1:, :].unsqueeze(1).expand(-1, channel_embed.shape[1], -1, -1)
|
| 221 |
+
hidden_states = (hidden_states + torch.cat((pos_embed, channel_embed), dim=-1)).view(batch_size, -1, hidden_states.shape[-1])
|
| 222 |
+
cls_pos_channel = torch.cat((self.pos_embed[:, :1, :], self.channel_cls_embed), dim=-1)
|
| 223 |
+
hidden_states = torch.cat((cls_pos_channel + self.cls_token.expand(batch_size, -1, -1), hidden_states), dim=1)
|
| 224 |
+
for block in self.blocks:
|
| 225 |
+
hidden_states = block(hidden_states)
|
| 226 |
+
if self.global_pool:
|
| 227 |
+
pooled_output = self.fc_norm(hidden_states[:, 1:, :].mean(dim=1))
|
| 228 |
+
else:
|
| 229 |
+
hidden_states = self.norm(hidden_states)
|
| 230 |
+
pooled_output = hidden_states[:, 0]
|
| 231 |
+
return hidden_states, pooled_output
|
| 232 |
+
|
| 233 |
+
def forward(
|
| 234 |
+
self,
|
| 235 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 236 |
+
return_dict: Optional[bool] = None,
|
| 237 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 238 |
+
) -> BaseModelOutputWithPooling:
|
| 239 |
+
if pixel_values is None:
|
| 240 |
+
raise ValueError("You must specify `pixel_values`")
|
| 241 |
+
pixel_values = pixel_values.to(dtype=self.dtype)
|
| 242 |
+
if return_dict is None:
|
| 243 |
+
return_dict = self.config.use_return_dict
|
| 244 |
+
if self.config.encoder_type == "group_channel":
|
| 245 |
+
last_hidden_state, pooled_output = self._forward_group_channel(pixel_values)
|
| 246 |
+
else:
|
| 247 |
+
last_hidden_state, pooled_output = self._forward_vanilla(pixel_values)
|
| 248 |
+
if not self.add_pooling_layer:
|
| 249 |
+
pooled_output = None
|
| 250 |
+
if not return_dict:
|
| 251 |
+
return (last_hidden_state, pooled_output)
|
| 252 |
+
return BaseModelOutputWithPooling(last_hidden_state=last_hidden_state, pooler_output=pooled_output)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class SatMAEppForImageClassification(SatMAEppPreTrainedModel):
|
| 256 |
+
def __init__(self, config: SatMAEppConfig):
|
| 257 |
+
super().__init__(config)
|
| 258 |
+
self.satmae_pp = SatMAEppModel(config, add_pooling_layer=True)
|
| 259 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 260 |
+
self.post_init()
|
| 261 |
+
|
| 262 |
+
def forward(
|
| 263 |
+
self,
|
| 264 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 265 |
+
labels: Optional[torch.Tensor] = None,
|
| 266 |
+
return_dict: Optional[bool] = None,
|
| 267 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 268 |
+
) -> ImageClassifierOutput:
|
| 269 |
+
outputs = self.satmae_pp(pixel_values=pixel_values, return_dict=True, **kwargs)
|
| 270 |
+
logits = self.classifier(outputs.pooler_output)
|
| 271 |
+
loss = None
|
| 272 |
+
if labels is not None:
|
| 273 |
+
loss = self.loss_function(labels, logits, self.config, **kwargs)
|
| 274 |
+
if not return_dict:
|
| 275 |
+
output = (logits,) + outputs[1:]
|
| 276 |
+
return ((loss,) + output) if loss is not None else output
|
| 277 |
+
return ImageClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
__all__ = [
|
| 281 |
+
"SatMAEppConfig",
|
| 282 |
+
"SatMAEppForImageClassification",
|
| 283 |
+
"SatMAEppModel",
|
| 284 |
+
"SatMAEppPreTrainedModel",
|
| 285 |
+
]
|
satmae-pp-vit-large-patch16-fmow-rgb-pretrain/pipeline_satmae_pp.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 SatMAE++ Authors and The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
"""SatMAE++ image feature extraction pipeline."""
|
| 6 |
+
|
| 7 |
+
from typing import Any, Union
|
| 8 |
+
|
| 9 |
+
from transformers.pipelines.base import GenericTensor, build_pipeline_init_args
|
| 10 |
+
from transformers.pipelines.image_feature_extraction import ImageFeatureExtractionPipeline
|
| 11 |
+
from transformers.utils import add_end_docstrings, is_vision_available
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if is_vision_available():
|
| 15 |
+
from transformers.image_utils import load_image
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@add_end_docstrings(
|
| 19 |
+
build_pipeline_init_args(has_image_processor=True),
|
| 20 |
+
"""
|
| 21 |
+
pool (`bool`, *optional*, defaults to `False`):
|
| 22 |
+
Whether or not to return the pooled output. If `False`, the model will return the raw hidden states.
|
| 23 |
+
""",
|
| 24 |
+
)
|
| 25 |
+
class SatMAEppImageFeatureExtractionPipeline(ImageFeatureExtractionPipeline):
|
| 26 |
+
"""
|
| 27 |
+
SatMAE++ image feature extraction pipeline.
|
| 28 |
+
|
| 29 |
+
This pipeline wraps [`SatMAEppModel`] for RGB and multispectral satellite feature extraction.
|
| 30 |
+
|
| 31 |
+
Example:
|
| 32 |
+
|
| 33 |
+
```python
|
| 34 |
+
>>> from transformers import pipeline
|
| 35 |
+
|
| 36 |
+
>>> pipe = pipeline(
|
| 37 |
+
... task="image-feature-extraction",
|
| 38 |
+
... model="/path/to/satmae-pp-vit-large-patch16-fmow-rgb-finetune",
|
| 39 |
+
... trust_remote_code=True,
|
| 40 |
+
... )
|
| 41 |
+
>>> features = pipe(image_array, pool=True, return_tensors=True)
|
| 42 |
+
```
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def _sanitize_parameters(
|
| 46 |
+
self,
|
| 47 |
+
image_processor_kwargs=None,
|
| 48 |
+
return_tensors=None,
|
| 49 |
+
pool=None,
|
| 50 |
+
**kwargs,
|
| 51 |
+
):
|
| 52 |
+
preprocess_params = {} if image_processor_kwargs is None else dict(image_processor_kwargs)
|
| 53 |
+
if "timeout" in kwargs:
|
| 54 |
+
preprocess_params["timeout"] = kwargs["timeout"]
|
| 55 |
+
|
| 56 |
+
postprocess_params = {}
|
| 57 |
+
if pool is not None:
|
| 58 |
+
postprocess_params["pool"] = pool
|
| 59 |
+
if return_tensors is not None:
|
| 60 |
+
postprocess_params["return_tensors"] = return_tensors
|
| 61 |
+
|
| 62 |
+
return preprocess_params, {}, postprocess_params
|
| 63 |
+
|
| 64 |
+
def preprocess(self, image, timeout=None, **image_processor_kwargs) -> dict[str, GenericTensor]:
|
| 65 |
+
if not isinstance(image, (list, tuple)) and not hasattr(image, "shape"):
|
| 66 |
+
image = load_image(image, timeout=timeout)
|
| 67 |
+
model_inputs = self.image_processor(image, return_tensors="pt", **image_processor_kwargs)
|
| 68 |
+
model_inputs = model_inputs.to(self.dtype)
|
| 69 |
+
return model_inputs
|
| 70 |
+
|
| 71 |
+
def __call__(
|
| 72 |
+
self,
|
| 73 |
+
*args: Union[str, Any, list[Any]],
|
| 74 |
+
**kwargs: Any,
|
| 75 |
+
) -> list[Any]:
|
| 76 |
+
return super().__call__(*args, **kwargs)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
__all__ = ["SatMAEppImageFeatureExtractionPipeline"]
|
satmae-pp-vit-large-patch16-fmow-rgb-pretrain/preprocessor_config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"image_processor_type": "SatMAEppImageProcessor",
|
| 3 |
+
"size": {
|
| 4 |
+
"height": 224,
|
| 5 |
+
"width": 224
|
| 6 |
+
},
|
| 7 |
+
"do_resize": true,
|
| 8 |
+
"do_rescale": false,
|
| 9 |
+
"do_normalize": true,
|
| 10 |
+
"do_convert_rgb": false,
|
| 11 |
+
"channel_order": "bgr",
|
| 12 |
+
"image_mean": [
|
| 13 |
+
0.4182007312774658,
|
| 14 |
+
0.4214799106121063,
|
| 15 |
+
0.3991275727748871
|
| 16 |
+
],
|
| 17 |
+
"image_std": [
|
| 18 |
+
0.28774282336235046,
|
| 19 |
+
0.27541765570640564,
|
| 20 |
+
0.2764017581939697
|
| 21 |
+
],
|
| 22 |
+
"auto_map": {
|
| 23 |
+
"AutoImageProcessor": "image_processing_satmae_pp.SatMAEppImageProcessor"
|
| 24 |
+
}
|
| 25 |
+
}
|
satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/config.json
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SatMAEppModel"
|
| 4 |
+
],
|
| 5 |
+
"attention_probs_dropout_prob": 0.0,
|
| 6 |
+
"channel_embed_dim": 256,
|
| 7 |
+
"channel_groups": [
|
| 8 |
+
[
|
| 9 |
+
0,
|
| 10 |
+
1,
|
| 11 |
+
2,
|
| 12 |
+
6
|
| 13 |
+
],
|
| 14 |
+
[
|
| 15 |
+
3,
|
| 16 |
+
4,
|
| 17 |
+
5,
|
| 18 |
+
7
|
| 19 |
+
],
|
| 20 |
+
[
|
| 21 |
+
8,
|
| 22 |
+
9
|
| 23 |
+
]
|
| 24 |
+
],
|
| 25 |
+
"channel_order": "rgb",
|
| 26 |
+
"checkpoint_stage": "pretrain",
|
| 27 |
+
"dataset": "fmow_sentinel",
|
| 28 |
+
"dtype": "float32",
|
| 29 |
+
"encoder_type": "group_channel",
|
| 30 |
+
"global_pool": true,
|
| 31 |
+
"hidden_act": "gelu",
|
| 32 |
+
"hidden_dropout_prob": 0.0,
|
| 33 |
+
"hidden_size": 1024,
|
| 34 |
+
"id2label": {},
|
| 35 |
+
"image_mean": [
|
| 36 |
+
1184.3824625,
|
| 37 |
+
1120.77120066,
|
| 38 |
+
1136.26026392,
|
| 39 |
+
1263.73947144,
|
| 40 |
+
1645.40315151,
|
| 41 |
+
1846.87040806,
|
| 42 |
+
1762.59530783,
|
| 43 |
+
1972.62420416,
|
| 44 |
+
1732.16362238,
|
| 45 |
+
1247.91870117
|
| 46 |
+
],
|
| 47 |
+
"image_size": 96,
|
| 48 |
+
"image_std": [
|
| 49 |
+
650.2842772,
|
| 50 |
+
712.12507725,
|
| 51 |
+
965.23119807,
|
| 52 |
+
948.9819932,
|
| 53 |
+
1108.06650639,
|
| 54 |
+
1258.36394548,
|
| 55 |
+
1233.1492281,
|
| 56 |
+
1364.38688993,
|
| 57 |
+
1310.36996126,
|
| 58 |
+
1087.6020813
|
| 59 |
+
],
|
| 60 |
+
"initializer_range": 0.02,
|
| 61 |
+
"intermediate_size": 4096,
|
| 62 |
+
"label2id": {},
|
| 63 |
+
"layer_norm_eps": 1e-06,
|
| 64 |
+
"mlp_ratio": 4.0,
|
| 65 |
+
"model_type": "satmae_pp",
|
| 66 |
+
"num_attention_heads": 16,
|
| 67 |
+
"num_channels": 10,
|
| 68 |
+
"num_hidden_layers": 24,
|
| 69 |
+
"patch_size": 8,
|
| 70 |
+
"qkv_bias": true,
|
| 71 |
+
"transformers_version": "5.0.0",
|
| 72 |
+
"auto_map": {
|
| 73 |
+
"AutoConfig": "modeling_satmae_pp.SatMAEppConfig",
|
| 74 |
+
"AutoModel": "modeling_satmae_pp.SatMAEppModel",
|
| 75 |
+
"AutoModelForImageClassification": "modeling_satmae_pp.SatMAEppForImageClassification"
|
| 76 |
+
},
|
| 77 |
+
"custom_pipelines": {
|
| 78 |
+
"satmae-pp-feature-extraction": {
|
| 79 |
+
"impl": "pipeline_satmae_pp.SatMAEppImageFeatureExtractionPipeline",
|
| 80 |
+
"pt": [
|
| 81 |
+
"AutoModel"
|
| 82 |
+
]
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
}
|
satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/image_processing_satmae_pp.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 SatMAE++ Authors and The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
"""Image processor for SatMAE++ models."""
|
| 6 |
+
|
| 7 |
+
from typing import Optional, Union
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 12 |
+
from transformers.image_transforms import resize, to_channel_dimension_format
|
| 13 |
+
from transformers.image_utils import (
|
| 14 |
+
ChannelDimension,
|
| 15 |
+
ImageInput,
|
| 16 |
+
PILImageResampling,
|
| 17 |
+
infer_channel_dimension_format,
|
| 18 |
+
make_flat_list_of_images,
|
| 19 |
+
to_numpy_array,
|
| 20 |
+
valid_images,
|
| 21 |
+
validate_preprocess_arguments,
|
| 22 |
+
)
|
| 23 |
+
from transformers.utils import TensorType, filter_out_non_signature_kwargs, logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _resize_multispectral(image: np.ndarray, size: dict[str, int], input_data_format: ChannelDimension) -> np.ndarray:
|
| 30 |
+
target_height, target_width = size["height"], size["width"]
|
| 31 |
+
|
| 32 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 33 |
+
image = np.transpose(image, (1, 2, 0))
|
| 34 |
+
|
| 35 |
+
height, width, _ = image.shape
|
| 36 |
+
if height == target_height and width == target_width:
|
| 37 |
+
resized = image
|
| 38 |
+
else:
|
| 39 |
+
try:
|
| 40 |
+
import cv2
|
| 41 |
+
except ImportError as exc:
|
| 42 |
+
raise ImportError(
|
| 43 |
+
"Multispectral resize requires OpenCV (`opencv-python`) when input has more than 4 channels."
|
| 44 |
+
) from exc
|
| 45 |
+
resized = cv2.resize(image, (target_width, target_height), interpolation=cv2.INTER_LINEAR)
|
| 46 |
+
|
| 47 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 48 |
+
return np.transpose(resized, (2, 0, 1))
|
| 49 |
+
return resized
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _reorder_channels(image: np.ndarray, channel_order: str, input_data_format: ChannelDimension) -> np.ndarray:
|
| 53 |
+
if channel_order != "bgr":
|
| 54 |
+
return image
|
| 55 |
+
|
| 56 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 57 |
+
if image.shape[0] < 3:
|
| 58 |
+
return image
|
| 59 |
+
return image[[2, 1, 0], ...]
|
| 60 |
+
if image.shape[-1] < 3:
|
| 61 |
+
return image
|
| 62 |
+
return image[..., [2, 1, 0]]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class SatMAEppImageProcessor(BaseImageProcessor):
|
| 66 |
+
"""
|
| 67 |
+
Image processor for SatMAE++ satellite encoders.
|
| 68 |
+
|
| 69 |
+
FMoW-RGB checkpoints were trained with BGR channel order. Set `channel_order="bgr"` (default for RGB models)
|
| 70 |
+
to swap the first three channels from RGB to BGR before inference.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
model_input_names = ["pixel_values"]
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
do_resize: bool = True,
|
| 78 |
+
size: Optional[dict[str, int]] = None,
|
| 79 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 80 |
+
do_rescale: bool = False,
|
| 81 |
+
rescale_factor: float = 1.0,
|
| 82 |
+
do_normalize: bool = True,
|
| 83 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 84 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 85 |
+
do_convert_rgb: bool = False,
|
| 86 |
+
channel_order: str = "rgb",
|
| 87 |
+
**kwargs,
|
| 88 |
+
):
|
| 89 |
+
super().__init__(**kwargs)
|
| 90 |
+
size = size if size is not None else {"height": 224, "width": 224}
|
| 91 |
+
self.do_resize = do_resize
|
| 92 |
+
self.size = size
|
| 93 |
+
self.resample = resample
|
| 94 |
+
self.do_rescale = do_rescale
|
| 95 |
+
self.rescale_factor = rescale_factor
|
| 96 |
+
self.do_normalize = do_normalize
|
| 97 |
+
self.image_mean = image_mean
|
| 98 |
+
self.image_std = image_std
|
| 99 |
+
self.do_convert_rgb = do_convert_rgb
|
| 100 |
+
self.channel_order = channel_order
|
| 101 |
+
|
| 102 |
+
@filter_out_non_signature_kwargs()
|
| 103 |
+
def preprocess(
|
| 104 |
+
self,
|
| 105 |
+
images: ImageInput,
|
| 106 |
+
do_resize: Optional[bool] = None,
|
| 107 |
+
size: Optional[dict[str, int]] = None,
|
| 108 |
+
resample: Optional[PILImageResampling] = None,
|
| 109 |
+
do_rescale: Optional[bool] = None,
|
| 110 |
+
rescale_factor: Optional[float] = None,
|
| 111 |
+
do_normalize: Optional[bool] = None,
|
| 112 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 113 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 114 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 115 |
+
data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
|
| 116 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 117 |
+
do_convert_rgb: Optional[bool] = None,
|
| 118 |
+
channel_order: Optional[str] = None,
|
| 119 |
+
):
|
| 120 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 121 |
+
size = size if size is not None else self.size
|
| 122 |
+
size = get_size_dict(size, default_to_square=True)
|
| 123 |
+
resample = resample if resample is not None else self.resample
|
| 124 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 125 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 126 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 127 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 128 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 129 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 130 |
+
channel_order = channel_order if channel_order is not None else self.channel_order
|
| 131 |
+
|
| 132 |
+
if do_normalize and (image_mean is None or image_std is None):
|
| 133 |
+
raise ValueError("Normalization requires `image_mean` and `image_std` with one value per channel.")
|
| 134 |
+
|
| 135 |
+
images = make_flat_list_of_images(images)
|
| 136 |
+
if not valid_images(images):
|
| 137 |
+
raise ValueError("Invalid image type. Must be PIL, numpy, or torch tensor.")
|
| 138 |
+
|
| 139 |
+
validate_preprocess_arguments(
|
| 140 |
+
do_rescale=do_rescale,
|
| 141 |
+
rescale_factor=rescale_factor,
|
| 142 |
+
do_normalize=do_normalize,
|
| 143 |
+
image_mean=image_mean,
|
| 144 |
+
image_std=image_std,
|
| 145 |
+
do_resize=do_resize,
|
| 146 |
+
size=size,
|
| 147 |
+
resample=resample,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
processed_images = []
|
| 151 |
+
for image in images:
|
| 152 |
+
image = to_numpy_array(image)
|
| 153 |
+
if do_convert_rgb:
|
| 154 |
+
image = self._convert_image_to_rgb(image)
|
| 155 |
+
|
| 156 |
+
if input_data_format is None:
|
| 157 |
+
try:
|
| 158 |
+
input_data_format = infer_channel_dimension_format(image)
|
| 159 |
+
except ValueError:
|
| 160 |
+
input_data_format = ChannelDimension.LAST
|
| 161 |
+
|
| 162 |
+
image = _reorder_channels(image, channel_order=channel_order, input_data_format=input_data_format)
|
| 163 |
+
|
| 164 |
+
if do_resize:
|
| 165 |
+
num_channels = image.shape[0] if input_data_format == ChannelDimension.FIRST else image.shape[-1]
|
| 166 |
+
if num_channels > 4:
|
| 167 |
+
image = _resize_multispectral(image, size=size, input_data_format=input_data_format)
|
| 168 |
+
else:
|
| 169 |
+
image = resize(
|
| 170 |
+
image,
|
| 171 |
+
size=(size["height"], size["width"]),
|
| 172 |
+
resample=resample,
|
| 173 |
+
input_data_format=input_data_format,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
if do_rescale:
|
| 177 |
+
image = image * rescale_factor
|
| 178 |
+
|
| 179 |
+
if do_normalize:
|
| 180 |
+
image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 181 |
+
|
| 182 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 183 |
+
processed_images.append(image)
|
| 184 |
+
|
| 185 |
+
data = {"pixel_values": processed_images}
|
| 186 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
__all__ = ["SatMAEppImageProcessor"]
|
satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8fb26efc283ba33e345aef826afffbe4e6b0e3f1eb00f1a3852e36ca5ba3e8aa
|
| 3 |
+
size 1212361656
|
satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/modeling_satmae_pp.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 SatMAE++ Authors and The HuggingFace Inc. team.
|
| 2 |
+
"""Self-contained SatMAE++ model and config for trust_remote_code loading."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from functools import partial
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from timm.models.vision_transformer import Block, PatchEmbed
|
| 12 |
+
from torch import nn
|
| 13 |
+
|
| 14 |
+
from transformers.configuration_utils import PretrainedConfig as PreTrainedConfig
|
| 15 |
+
from transformers.modeling_outputs import BaseModelOutputWithPooling, ImageClassifierOutput
|
| 16 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 17 |
+
from transformers.processing_utils import Unpack
|
| 18 |
+
from transformers.utils import TransformersKwargs, logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
FMOW_RGB_MEAN = [0.4182007312774658, 0.4214799106121063, 0.3991275727748871]
|
| 24 |
+
FMOW_RGB_STD = [0.28774282336235046, 0.27541765570640564, 0.2764017581939697]
|
| 25 |
+
FMOW_SENTINEL_MEAN_10 = [
|
| 26 |
+
1184.3824625, 1120.77120066, 1136.26026392, 1263.73947144, 1645.40315151,
|
| 27 |
+
1846.87040806, 1762.59530783, 1972.62420416, 1732.16362238, 1247.91870117,
|
| 28 |
+
]
|
| 29 |
+
FMOW_SENTINEL_STD_10 = [
|
| 30 |
+
650.2842772, 712.12507725, 965.23119807, 948.9819932, 1108.06650639,
|
| 31 |
+
1258.36394548, 1233.1492281, 1364.38688993, 1310.36996126, 1087.6020813,
|
| 32 |
+
]
|
| 33 |
+
DEFAULT_CHANNEL_GROUPS = [[0, 1, 2, 6], [3, 4, 5, 7], [8, 9]]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_2d_sincos_pos_embed(embed_dim: int, grid_size: int, cls_token: bool = False) -> np.ndarray:
|
| 37 |
+
grid_h = np.arange(grid_size, dtype=np.float32)
|
| 38 |
+
grid_w = np.arange(grid_size, dtype=np.float32)
|
| 39 |
+
grid = np.meshgrid(grid_w, grid_h)
|
| 40 |
+
grid = np.stack(grid, axis=0).reshape([2, 1, grid_size, grid_size])
|
| 41 |
+
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
|
| 42 |
+
if cls_token:
|
| 43 |
+
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
|
| 44 |
+
return pos_embed
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_2d_sincos_pos_embed_from_grid(embed_dim: int, grid: np.ndarray) -> np.ndarray:
|
| 48 |
+
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0])
|
| 49 |
+
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1])
|
| 50 |
+
return np.concatenate([emb_h, emb_w], axis=1)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_1d_sincos_pos_embed_from_grid(embed_dim: int, pos: np.ndarray) -> np.ndarray:
|
| 54 |
+
omega = np.arange(embed_dim // 2, dtype=np.float32)
|
| 55 |
+
omega /= embed_dim / 2.0
|
| 56 |
+
omega = 1.0 / 10000**omega
|
| 57 |
+
pos = pos.reshape(-1)
|
| 58 |
+
out = np.einsum("m,d->md", pos, omega)
|
| 59 |
+
return np.concatenate([np.sin(out), np.cos(out)], axis=1)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class SatMAEppConfig(PreTrainedConfig):
|
| 63 |
+
model_type = "satmae_pp"
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
hidden_size: int = 1024,
|
| 68 |
+
num_hidden_layers: int = 24,
|
| 69 |
+
num_attention_heads: int = 16,
|
| 70 |
+
intermediate_size: int | None = None,
|
| 71 |
+
hidden_act: str = "gelu",
|
| 72 |
+
hidden_dropout_prob: float = 0.0,
|
| 73 |
+
attention_probs_dropout_prob: float = 0.0,
|
| 74 |
+
initializer_range: float = 0.02,
|
| 75 |
+
layer_norm_eps: float = 1e-6,
|
| 76 |
+
image_size: int = 224,
|
| 77 |
+
patch_size: int = 16,
|
| 78 |
+
num_channels: int = 3,
|
| 79 |
+
qkv_bias: bool = True,
|
| 80 |
+
mlp_ratio: float = 4.0,
|
| 81 |
+
global_pool: bool = True,
|
| 82 |
+
encoder_type: str = "vanilla",
|
| 83 |
+
channel_embed_dim: int = 256,
|
| 84 |
+
channel_groups: list[list[int]] | None = None,
|
| 85 |
+
channel_order: str = "bgr",
|
| 86 |
+
dataset: str = "fmow_rgb",
|
| 87 |
+
checkpoint_stage: str = "finetune",
|
| 88 |
+
image_mean: list[float] | None = None,
|
| 89 |
+
image_std: list[float] | None = None,
|
| 90 |
+
num_labels: int = 0,
|
| 91 |
+
**kwargs,
|
| 92 |
+
):
|
| 93 |
+
super().__init__(**kwargs)
|
| 94 |
+
self.hidden_size = hidden_size
|
| 95 |
+
self.num_hidden_layers = num_hidden_layers
|
| 96 |
+
self.num_attention_heads = num_attention_heads
|
| 97 |
+
self.hidden_act = hidden_act
|
| 98 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 99 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 100 |
+
self.initializer_range = initializer_range
|
| 101 |
+
self.layer_norm_eps = layer_norm_eps
|
| 102 |
+
self.image_size = image_size
|
| 103 |
+
self.patch_size = patch_size
|
| 104 |
+
self.num_channels = num_channels
|
| 105 |
+
self.qkv_bias = qkv_bias
|
| 106 |
+
self.mlp_ratio = mlp_ratio
|
| 107 |
+
self.global_pool = global_pool
|
| 108 |
+
self.encoder_type = encoder_type
|
| 109 |
+
self.channel_embed_dim = channel_embed_dim
|
| 110 |
+
self.channel_groups = channel_groups if channel_groups is not None else list(DEFAULT_CHANNEL_GROUPS)
|
| 111 |
+
self.channel_order = channel_order
|
| 112 |
+
self.dataset = dataset
|
| 113 |
+
self.checkpoint_stage = checkpoint_stage
|
| 114 |
+
self.num_labels = num_labels
|
| 115 |
+
self.intermediate_size = int(hidden_size * mlp_ratio) if intermediate_size is None else intermediate_size
|
| 116 |
+
if image_mean is None or image_std is None:
|
| 117 |
+
if encoder_type == "group_channel":
|
| 118 |
+
self.image_mean = FMOW_SENTINEL_MEAN_10
|
| 119 |
+
self.image_std = FMOW_SENTINEL_STD_10
|
| 120 |
+
else:
|
| 121 |
+
self.image_mean = FMOW_RGB_MEAN
|
| 122 |
+
self.image_std = FMOW_RGB_STD
|
| 123 |
+
else:
|
| 124 |
+
self.image_mean = image_mean
|
| 125 |
+
self.image_std = image_std
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class SatMAEppPreTrainedModel(PreTrainedModel):
|
| 129 |
+
config_class = SatMAEppConfig
|
| 130 |
+
config: SatMAEppConfig
|
| 131 |
+
base_model_prefix = "satmae_pp"
|
| 132 |
+
main_input_name = "pixel_values"
|
| 133 |
+
input_modalities = ("image",)
|
| 134 |
+
supports_gradient_checkpointing = True
|
| 135 |
+
_no_split_modules = ["Block"]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class SatMAEppModel(SatMAEppPreTrainedModel):
|
| 139 |
+
def __init__(self, config: SatMAEppConfig, add_pooling_layer: bool = True):
|
| 140 |
+
super().__init__(config)
|
| 141 |
+
self.config = config
|
| 142 |
+
self.add_pooling_layer = add_pooling_layer
|
| 143 |
+
if config.encoder_type == "group_channel":
|
| 144 |
+
self._init_group_channel_encoder(config)
|
| 145 |
+
else:
|
| 146 |
+
self._init_vanilla_encoder(config)
|
| 147 |
+
self.post_init()
|
| 148 |
+
|
| 149 |
+
def _init_vanilla_encoder(self, config: SatMAEppConfig) -> None:
|
| 150 |
+
image_size = config.image_size if isinstance(config.image_size, int) else config.image_size[0]
|
| 151 |
+
norm_layer = partial(nn.LayerNorm, eps=config.layer_norm_eps)
|
| 152 |
+
self.patch_embed = PatchEmbed(image_size, config.patch_size, config.num_channels, config.hidden_size)
|
| 153 |
+
self.num_patches = self.patch_embed.num_patches
|
| 154 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 155 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + 1, config.hidden_size))
|
| 156 |
+
pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.num_patches**0.5), cls_token=True)
|
| 157 |
+
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 158 |
+
self.blocks = nn.ModuleList([
|
| 159 |
+
Block(config.hidden_size, config.num_attention_heads, config.mlp_ratio, qkv_bias=config.qkv_bias, norm_layer=norm_layer)
|
| 160 |
+
for _ in range(config.num_hidden_layers)
|
| 161 |
+
])
|
| 162 |
+
self.global_pool = config.global_pool
|
| 163 |
+
if self.global_pool:
|
| 164 |
+
self.fc_norm = norm_layer(config.hidden_size)
|
| 165 |
+
self.norm = None
|
| 166 |
+
else:
|
| 167 |
+
self.fc_norm = None
|
| 168 |
+
self.norm = norm_layer(config.hidden_size)
|
| 169 |
+
|
| 170 |
+
def _init_group_channel_encoder(self, config: SatMAEppConfig) -> None:
|
| 171 |
+
image_size = config.image_size if isinstance(config.image_size, int) else config.image_size[0]
|
| 172 |
+
norm_layer = partial(nn.LayerNorm, eps=config.layer_norm_eps)
|
| 173 |
+
self.channel_groups = tuple(tuple(group) for group in config.channel_groups)
|
| 174 |
+
self.patch_embed = nn.ModuleList([
|
| 175 |
+
PatchEmbed(image_size, config.patch_size, len(group), config.hidden_size)
|
| 176 |
+
for group in self.channel_groups
|
| 177 |
+
])
|
| 178 |
+
self.num_patches = self.patch_embed[0].num_patches
|
| 179 |
+
pos_dim = config.hidden_size - config.channel_embed_dim
|
| 180 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + 1, pos_dim))
|
| 181 |
+
pos_embed = get_2d_sincos_pos_embed(pos_dim, int(self.num_patches**0.5), cls_token=True)
|
| 182 |
+
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
| 183 |
+
num_groups = len(self.channel_groups)
|
| 184 |
+
self.channel_embed = nn.Parameter(torch.zeros(1, num_groups, config.channel_embed_dim))
|
| 185 |
+
chan_embed = get_1d_sincos_pos_embed_from_grid(self.channel_embed.shape[-1], np.arange(num_groups))
|
| 186 |
+
self.channel_embed.data.copy_(torch.from_numpy(chan_embed).float().unsqueeze(0))
|
| 187 |
+
self.channel_cls_embed = nn.Parameter(torch.zeros(1, 1, config.channel_embed_dim))
|
| 188 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 189 |
+
self.blocks = nn.ModuleList([
|
| 190 |
+
Block(config.hidden_size, config.num_attention_heads, config.mlp_ratio, qkv_bias=config.qkv_bias, norm_layer=norm_layer)
|
| 191 |
+
for _ in range(config.num_hidden_layers)
|
| 192 |
+
])
|
| 193 |
+
self.global_pool = config.global_pool
|
| 194 |
+
if self.global_pool:
|
| 195 |
+
self.fc_norm = norm_layer(config.hidden_size)
|
| 196 |
+
self.norm = None
|
| 197 |
+
else:
|
| 198 |
+
self.fc_norm = None
|
| 199 |
+
self.norm = norm_layer(config.hidden_size)
|
| 200 |
+
|
| 201 |
+
def _forward_vanilla(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 202 |
+
batch_size = pixel_values.shape[0]
|
| 203 |
+
patch_tokens = self.patch_embed(pixel_values)
|
| 204 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 205 |
+
hidden_states = torch.cat((cls_tokens, patch_tokens), dim=1) + self.pos_embed
|
| 206 |
+
for block in self.blocks:
|
| 207 |
+
hidden_states = block(hidden_states)
|
| 208 |
+
if self.global_pool:
|
| 209 |
+
pooled_output = self.fc_norm(hidden_states[:, 1:, :].mean(dim=1))
|
| 210 |
+
else:
|
| 211 |
+
hidden_states = self.norm(hidden_states)
|
| 212 |
+
pooled_output = hidden_states[:, 0]
|
| 213 |
+
return hidden_states, pooled_output
|
| 214 |
+
|
| 215 |
+
def _forward_group_channel(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 216 |
+
batch_size = pixel_values.shape[0]
|
| 217 |
+
group_tokens = [self.patch_embed[i](pixel_values[:, group, :, :]) for i, group in enumerate(self.channel_groups)]
|
| 218 |
+
hidden_states = torch.stack(group_tokens, dim=1)
|
| 219 |
+
channel_embed = self.channel_embed.unsqueeze(2).expand(-1, -1, self.pos_embed[:, 1:, :].shape[1], -1)
|
| 220 |
+
pos_embed = self.pos_embed[:, 1:, :].unsqueeze(1).expand(-1, channel_embed.shape[1], -1, -1)
|
| 221 |
+
hidden_states = (hidden_states + torch.cat((pos_embed, channel_embed), dim=-1)).view(batch_size, -1, hidden_states.shape[-1])
|
| 222 |
+
cls_pos_channel = torch.cat((self.pos_embed[:, :1, :], self.channel_cls_embed), dim=-1)
|
| 223 |
+
hidden_states = torch.cat((cls_pos_channel + self.cls_token.expand(batch_size, -1, -1), hidden_states), dim=1)
|
| 224 |
+
for block in self.blocks:
|
| 225 |
+
hidden_states = block(hidden_states)
|
| 226 |
+
if self.global_pool:
|
| 227 |
+
pooled_output = self.fc_norm(hidden_states[:, 1:, :].mean(dim=1))
|
| 228 |
+
else:
|
| 229 |
+
hidden_states = self.norm(hidden_states)
|
| 230 |
+
pooled_output = hidden_states[:, 0]
|
| 231 |
+
return hidden_states, pooled_output
|
| 232 |
+
|
| 233 |
+
def forward(
|
| 234 |
+
self,
|
| 235 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 236 |
+
return_dict: Optional[bool] = None,
|
| 237 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 238 |
+
) -> BaseModelOutputWithPooling:
|
| 239 |
+
if pixel_values is None:
|
| 240 |
+
raise ValueError("You must specify `pixel_values`")
|
| 241 |
+
pixel_values = pixel_values.to(dtype=self.dtype)
|
| 242 |
+
if return_dict is None:
|
| 243 |
+
return_dict = self.config.use_return_dict
|
| 244 |
+
if self.config.encoder_type == "group_channel":
|
| 245 |
+
last_hidden_state, pooled_output = self._forward_group_channel(pixel_values)
|
| 246 |
+
else:
|
| 247 |
+
last_hidden_state, pooled_output = self._forward_vanilla(pixel_values)
|
| 248 |
+
if not self.add_pooling_layer:
|
| 249 |
+
pooled_output = None
|
| 250 |
+
if not return_dict:
|
| 251 |
+
return (last_hidden_state, pooled_output)
|
| 252 |
+
return BaseModelOutputWithPooling(last_hidden_state=last_hidden_state, pooler_output=pooled_output)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class SatMAEppForImageClassification(SatMAEppPreTrainedModel):
|
| 256 |
+
def __init__(self, config: SatMAEppConfig):
|
| 257 |
+
super().__init__(config)
|
| 258 |
+
self.satmae_pp = SatMAEppModel(config, add_pooling_layer=True)
|
| 259 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 260 |
+
self.post_init()
|
| 261 |
+
|
| 262 |
+
def forward(
|
| 263 |
+
self,
|
| 264 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 265 |
+
labels: Optional[torch.Tensor] = None,
|
| 266 |
+
return_dict: Optional[bool] = None,
|
| 267 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 268 |
+
) -> ImageClassifierOutput:
|
| 269 |
+
outputs = self.satmae_pp(pixel_values=pixel_values, return_dict=True, **kwargs)
|
| 270 |
+
logits = self.classifier(outputs.pooler_output)
|
| 271 |
+
loss = None
|
| 272 |
+
if labels is not None:
|
| 273 |
+
loss = self.loss_function(labels, logits, self.config, **kwargs)
|
| 274 |
+
if not return_dict:
|
| 275 |
+
output = (logits,) + outputs[1:]
|
| 276 |
+
return ((loss,) + output) if loss is not None else output
|
| 277 |
+
return ImageClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
__all__ = [
|
| 281 |
+
"SatMAEppConfig",
|
| 282 |
+
"SatMAEppForImageClassification",
|
| 283 |
+
"SatMAEppModel",
|
| 284 |
+
"SatMAEppPreTrainedModel",
|
| 285 |
+
]
|
satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/pipeline_satmae_pp.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 SatMAE++ Authors and The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
"""SatMAE++ image feature extraction pipeline."""
|
| 6 |
+
|
| 7 |
+
from typing import Any, Union
|
| 8 |
+
|
| 9 |
+
from transformers.pipelines.base import GenericTensor, build_pipeline_init_args
|
| 10 |
+
from transformers.pipelines.image_feature_extraction import ImageFeatureExtractionPipeline
|
| 11 |
+
from transformers.utils import add_end_docstrings, is_vision_available
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if is_vision_available():
|
| 15 |
+
from transformers.image_utils import load_image
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@add_end_docstrings(
|
| 19 |
+
build_pipeline_init_args(has_image_processor=True),
|
| 20 |
+
"""
|
| 21 |
+
pool (`bool`, *optional*, defaults to `False`):
|
| 22 |
+
Whether or not to return the pooled output. If `False`, the model will return the raw hidden states.
|
| 23 |
+
""",
|
| 24 |
+
)
|
| 25 |
+
class SatMAEppImageFeatureExtractionPipeline(ImageFeatureExtractionPipeline):
|
| 26 |
+
"""
|
| 27 |
+
SatMAE++ image feature extraction pipeline.
|
| 28 |
+
|
| 29 |
+
This pipeline wraps [`SatMAEppModel`] for RGB and multispectral satellite feature extraction.
|
| 30 |
+
|
| 31 |
+
Example:
|
| 32 |
+
|
| 33 |
+
```python
|
| 34 |
+
>>> from transformers import pipeline
|
| 35 |
+
|
| 36 |
+
>>> pipe = pipeline(
|
| 37 |
+
... task="image-feature-extraction",
|
| 38 |
+
... model="/path/to/satmae-pp-vit-large-patch16-fmow-rgb-finetune",
|
| 39 |
+
... trust_remote_code=True,
|
| 40 |
+
... )
|
| 41 |
+
>>> features = pipe(image_array, pool=True, return_tensors=True)
|
| 42 |
+
```
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def _sanitize_parameters(
|
| 46 |
+
self,
|
| 47 |
+
image_processor_kwargs=None,
|
| 48 |
+
return_tensors=None,
|
| 49 |
+
pool=None,
|
| 50 |
+
**kwargs,
|
| 51 |
+
):
|
| 52 |
+
preprocess_params = {} if image_processor_kwargs is None else dict(image_processor_kwargs)
|
| 53 |
+
if "timeout" in kwargs:
|
| 54 |
+
preprocess_params["timeout"] = kwargs["timeout"]
|
| 55 |
+
|
| 56 |
+
postprocess_params = {}
|
| 57 |
+
if pool is not None:
|
| 58 |
+
postprocess_params["pool"] = pool
|
| 59 |
+
if return_tensors is not None:
|
| 60 |
+
postprocess_params["return_tensors"] = return_tensors
|
| 61 |
+
|
| 62 |
+
return preprocess_params, {}, postprocess_params
|
| 63 |
+
|
| 64 |
+
def preprocess(self, image, timeout=None, **image_processor_kwargs) -> dict[str, GenericTensor]:
|
| 65 |
+
if not isinstance(image, (list, tuple)) and not hasattr(image, "shape"):
|
| 66 |
+
image = load_image(image, timeout=timeout)
|
| 67 |
+
model_inputs = self.image_processor(image, return_tensors="pt", **image_processor_kwargs)
|
| 68 |
+
model_inputs = model_inputs.to(self.dtype)
|
| 69 |
+
return model_inputs
|
| 70 |
+
|
| 71 |
+
def __call__(
|
| 72 |
+
self,
|
| 73 |
+
*args: Union[str, Any, list[Any]],
|
| 74 |
+
**kwargs: Any,
|
| 75 |
+
) -> list[Any]:
|
| 76 |
+
return super().__call__(*args, **kwargs)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
__all__ = ["SatMAEppImageFeatureExtractionPipeline"]
|
satmae-pp-vit-large-patch8-fmow-sentinel-pretrain/preprocessor_config.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"image_processor_type": "SatMAEppImageProcessor",
|
| 3 |
+
"size": {
|
| 4 |
+
"height": 96,
|
| 5 |
+
"width": 96
|
| 6 |
+
},
|
| 7 |
+
"do_resize": true,
|
| 8 |
+
"do_rescale": false,
|
| 9 |
+
"do_normalize": true,
|
| 10 |
+
"do_convert_rgb": false,
|
| 11 |
+
"channel_order": "rgb",
|
| 12 |
+
"image_mean": [
|
| 13 |
+
1184.3824625,
|
| 14 |
+
1120.77120066,
|
| 15 |
+
1136.26026392,
|
| 16 |
+
1263.73947144,
|
| 17 |
+
1645.40315151,
|
| 18 |
+
1846.87040806,
|
| 19 |
+
1762.59530783,
|
| 20 |
+
1972.62420416,
|
| 21 |
+
1732.16362238,
|
| 22 |
+
1247.91870117
|
| 23 |
+
],
|
| 24 |
+
"image_std": [
|
| 25 |
+
650.2842772,
|
| 26 |
+
712.12507725,
|
| 27 |
+
965.23119807,
|
| 28 |
+
948.9819932,
|
| 29 |
+
1108.06650639,
|
| 30 |
+
1258.36394548,
|
| 31 |
+
1233.1492281,
|
| 32 |
+
1364.38688993,
|
| 33 |
+
1310.36996126,
|
| 34 |
+
1087.6020813
|
| 35 |
+
],
|
| 36 |
+
"auto_map": {
|
| 37 |
+
"AutoImageProcessor": "image_processing_satmae_pp.SatMAEppImageProcessor"
|
| 38 |
+
}
|
| 39 |
+
}
|