rslearn 0.0.12__py3-none-any.whl → 0.0.14__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rslearn/config/dataset.py +23 -14
- rslearn/data_sources/planetary_computer.py +52 -0
- rslearn/dataset/handler_summaries.py +1 -0
- rslearn/dataset/manage.py +16 -2
- rslearn/lightning_cli.py +67 -0
- rslearn/main.py +8 -62
- rslearn/models/olmoearth_pretrain/model.py +1 -0
- rslearn/train/all_patches_dataset.py +458 -0
- rslearn/train/data_module.py +4 -2
- rslearn/train/dataset.py +10 -446
- rslearn/train/prediction_writer.py +25 -8
- rslearn/train/tasks/embedding.py +116 -0
- rslearn/utils/array.py +6 -4
- rslearn/utils/raster_format.py +38 -0
- {rslearn-0.0.12.dist-info → rslearn-0.0.14.dist-info}/METADATA +2 -2
- {rslearn-0.0.12.dist-info → rslearn-0.0.14.dist-info}/RECORD +21 -18
- {rslearn-0.0.12.dist-info → rslearn-0.0.14.dist-info}/WHEEL +0 -0
- {rslearn-0.0.12.dist-info → rslearn-0.0.14.dist-info}/entry_points.txt +0 -0
- {rslearn-0.0.12.dist-info → rslearn-0.0.14.dist-info}/licenses/LICENSE +0 -0
- {rslearn-0.0.12.dist-info → rslearn-0.0.14.dist-info}/licenses/NOTICE +0 -0
- {rslearn-0.0.12.dist-info → rslearn-0.0.14.dist-info}/top_level.txt +0 -0
rslearn/train/dataset.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"""Default Dataset for rslearn."""
|
|
2
2
|
|
|
3
3
|
import hashlib
|
|
4
|
-
import itertools
|
|
5
4
|
import json
|
|
6
5
|
import multiprocessing
|
|
7
6
|
import os
|
|
@@ -9,10 +8,8 @@ import random
|
|
|
9
8
|
import tempfile
|
|
10
9
|
import time
|
|
11
10
|
import uuid
|
|
12
|
-
from collections.abc import Iterable, Iterator
|
|
13
11
|
from typing import Any
|
|
14
12
|
|
|
15
|
-
import shapely
|
|
16
13
|
import torch
|
|
17
14
|
import tqdm
|
|
18
15
|
from rasterio.warp import Resampling
|
|
@@ -29,7 +26,7 @@ from rslearn.dataset.window import Window, get_layer_and_group_from_dir_name
|
|
|
29
26
|
from rslearn.log_utils import get_logger
|
|
30
27
|
from rslearn.train.tasks import Task
|
|
31
28
|
from rslearn.utils.feature import Feature
|
|
32
|
-
from rslearn.utils.geometry import PixelBounds
|
|
29
|
+
from rslearn.utils.geometry import PixelBounds
|
|
33
30
|
from rslearn.utils.mp import star_imap_unordered
|
|
34
31
|
from rslearn.utils.raster_format import load_raster_format
|
|
35
32
|
from rslearn.utils.vector_format import load_vector_format
|
|
@@ -39,70 +36,14 @@ from .transforms import Sequential
|
|
|
39
36
|
logger = get_logger(__name__)
|
|
40
37
|
|
|
41
38
|
|
|
42
|
-
def
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
patch_size: the size of the patches to extract.
|
|
51
|
-
overlap_size: the size of the overlap between patches.
|
|
52
|
-
bounds: the window bounds to divide up into smaller patches.
|
|
53
|
-
|
|
54
|
-
Returns:
|
|
55
|
-
a list of patch bounds within the overall bounds. The rightmost and
|
|
56
|
-
bottommost patches may extend beyond the provided bounds.
|
|
57
|
-
"""
|
|
58
|
-
# We stride the patches by patch_size - overlap_size until the last patch.
|
|
59
|
-
# We handle the last patch with a special case to ensure it does not exceed the
|
|
60
|
-
# window bounds. Instead, it may overlap the previous patch.
|
|
61
|
-
cols = list(
|
|
62
|
-
range(
|
|
63
|
-
bounds[0],
|
|
64
|
-
bounds[2] - patch_size[0],
|
|
65
|
-
patch_size[0] - overlap_size[0],
|
|
66
|
-
)
|
|
67
|
-
) + [bounds[2] - patch_size[0]]
|
|
68
|
-
rows = list(
|
|
69
|
-
range(
|
|
70
|
-
bounds[1],
|
|
71
|
-
bounds[3] - patch_size[1],
|
|
72
|
-
patch_size[1] - overlap_size[1],
|
|
73
|
-
)
|
|
74
|
-
) + [bounds[3] - patch_size[1]]
|
|
75
|
-
|
|
76
|
-
patch_bounds: list[PixelBounds] = []
|
|
77
|
-
for col in cols:
|
|
78
|
-
for row in rows:
|
|
79
|
-
patch_bounds.append((col, row, col + patch_size[0], row + patch_size[1]))
|
|
80
|
-
return patch_bounds
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
def pad_slice_protect(
|
|
84
|
-
raw_inputs: dict[str, Any],
|
|
85
|
-
passthrough_inputs: dict[str, Any],
|
|
86
|
-
patch_size: tuple[int, int],
|
|
87
|
-
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
88
|
-
"""Pad tensors in-place by patch size to protect slicing near right/bottom edges.
|
|
89
|
-
|
|
90
|
-
Args:
|
|
91
|
-
raw_inputs: the raw inputs to pad.
|
|
92
|
-
passthrough_inputs: the passthrough inputs to pad.
|
|
93
|
-
patch_size: the size of the patches to extract.
|
|
94
|
-
|
|
95
|
-
Returns:
|
|
96
|
-
a tuple of (raw_inputs, passthrough_inputs).
|
|
97
|
-
"""
|
|
98
|
-
for d in [raw_inputs, passthrough_inputs]:
|
|
99
|
-
for input_name, value in list(d.items()):
|
|
100
|
-
if not isinstance(value, torch.Tensor):
|
|
101
|
-
continue
|
|
102
|
-
d[input_name] = torch.nn.functional.pad(
|
|
103
|
-
value, pad=(0, patch_size[0], 0, patch_size[1])
|
|
104
|
-
)
|
|
105
|
-
return raw_inputs, passthrough_inputs
|
|
39
|
+
def get_torch_dtype(dtype: DType) -> torch.dtype:
|
|
40
|
+
"""Convert rslearn DType to torch dtype."""
|
|
41
|
+
if dtype == DType.INT32:
|
|
42
|
+
return torch.int32
|
|
43
|
+
elif dtype == DType.FLOAT32:
|
|
44
|
+
return torch.float32
|
|
45
|
+
else:
|
|
46
|
+
raise ValueError(f"unable to handle {dtype} as a torch dtype")
|
|
106
47
|
|
|
107
48
|
|
|
108
49
|
class SamplerFactory:
|
|
@@ -296,7 +237,7 @@ def read_raster_layer_for_data_input(
|
|
|
296
237
|
|
|
297
238
|
image = torch.zeros(
|
|
298
239
|
(len(needed_bands), bounds[3] - bounds[1], bounds[2] - bounds[0]),
|
|
299
|
-
dtype=data_input.dtype
|
|
240
|
+
dtype=get_torch_dtype(data_input.dtype),
|
|
300
241
|
)
|
|
301
242
|
|
|
302
243
|
for band_set, src_indexes, dst_indexes in needed_sets_and_indexes:
|
|
@@ -893,383 +834,6 @@ class ModelDataset(torch.utils.data.Dataset):
|
|
|
893
834
|
self.name = name
|
|
894
835
|
|
|
895
836
|
|
|
896
|
-
class IterableAllPatchesDataset(torch.utils.data.IterableDataset):
|
|
897
|
-
"""This wraps a ModelDataset to iterate over all patches in that dataset.
|
|
898
|
-
|
|
899
|
-
This should be used when SplitConfig.load_all_patches is enabled. The ModelDataset
|
|
900
|
-
is configured with no patch size (load entire windows), and the dataset is wrapped
|
|
901
|
-
in an AllPatchesDataset.
|
|
902
|
-
|
|
903
|
-
Similar to DistributedSampler, we add extra samples at each rank to ensure
|
|
904
|
-
consistent number of batches across all ranks.
|
|
905
|
-
"""
|
|
906
|
-
|
|
907
|
-
def __init__(
|
|
908
|
-
self,
|
|
909
|
-
dataset: ModelDataset,
|
|
910
|
-
patch_size: tuple[int, int],
|
|
911
|
-
overlap_ratio: float = 0.0,
|
|
912
|
-
rank: int = 0,
|
|
913
|
-
world_size: int = 1,
|
|
914
|
-
):
|
|
915
|
-
"""Create a new IterableAllPatchesDataset.
|
|
916
|
-
|
|
917
|
-
Args:
|
|
918
|
-
dataset: the ModelDataset to wrap.
|
|
919
|
-
patch_size: the size of the patches to extract.
|
|
920
|
-
overlap_ratio: whether to include overlap between the patches. Note that
|
|
921
|
-
the right/bottom-most patches may still overlap since we ensure that
|
|
922
|
-
all patches are contained in the window bounds.
|
|
923
|
-
rank: the global rank of this train worker process.
|
|
924
|
-
world_size: the total number of train worker processes.
|
|
925
|
-
"""
|
|
926
|
-
super().__init__()
|
|
927
|
-
self.dataset = dataset
|
|
928
|
-
self.patch_size = patch_size
|
|
929
|
-
self.overlap_size = (
|
|
930
|
-
round(self.patch_size[0] * overlap_ratio),
|
|
931
|
-
round(self.patch_size[1] * overlap_ratio),
|
|
932
|
-
)
|
|
933
|
-
self.rank = rank
|
|
934
|
-
self.world_size = world_size
|
|
935
|
-
self.windows = self.dataset.get_dataset_examples()
|
|
936
|
-
|
|
937
|
-
def set_name(self, name: str) -> None:
|
|
938
|
-
"""Sets dataset name.
|
|
939
|
-
|
|
940
|
-
Args:
|
|
941
|
-
name: dataset name
|
|
942
|
-
"""
|
|
943
|
-
self.dataset.set_name(name)
|
|
944
|
-
|
|
945
|
-
def get_window_num_patches(self, bounds: PixelBounds) -> int:
|
|
946
|
-
"""Get the number of patches for these bounds.
|
|
947
|
-
|
|
948
|
-
This corresponds to the length of the list returned by get_patch_options.
|
|
949
|
-
"""
|
|
950
|
-
num_cols = (
|
|
951
|
-
len(
|
|
952
|
-
range(
|
|
953
|
-
bounds[0],
|
|
954
|
-
bounds[2] - self.patch_size[0],
|
|
955
|
-
self.patch_size[0] - self.overlap_size[0],
|
|
956
|
-
)
|
|
957
|
-
)
|
|
958
|
-
+ 1
|
|
959
|
-
)
|
|
960
|
-
num_rows = (
|
|
961
|
-
len(
|
|
962
|
-
range(
|
|
963
|
-
bounds[1],
|
|
964
|
-
bounds[3] - self.patch_size[1],
|
|
965
|
-
self.patch_size[1] - self.overlap_size[1],
|
|
966
|
-
)
|
|
967
|
-
)
|
|
968
|
-
+ 1
|
|
969
|
-
)
|
|
970
|
-
return num_cols * num_rows
|
|
971
|
-
|
|
972
|
-
def _get_worker_iteration_data(self) -> tuple[Iterable[int], int]:
|
|
973
|
-
"""Get the windows we should iterate over.
|
|
974
|
-
|
|
975
|
-
This is split both by training worker (self.rank) and data loader worker (via
|
|
976
|
-
get_worker_info).
|
|
977
|
-
|
|
978
|
-
We also compute the total number of samples that each data loader worker should
|
|
979
|
-
yield. This is important for DDP to ensure that all ranks see the same number
|
|
980
|
-
of batches.
|
|
981
|
-
|
|
982
|
-
Returns:
|
|
983
|
-
a tuple (window_ids, num_samples_per_worker).
|
|
984
|
-
"""
|
|
985
|
-
# Figure out the total number of data loader workers and our worker ID.
|
|
986
|
-
worker_info = torch.utils.data.get_worker_info()
|
|
987
|
-
if worker_info is None:
|
|
988
|
-
worker_id = 0
|
|
989
|
-
num_workers = 1
|
|
990
|
-
else:
|
|
991
|
-
worker_id = worker_info.id
|
|
992
|
-
num_workers = worker_info.num_workers
|
|
993
|
-
global_worker_id = self.rank * num_workers + worker_id
|
|
994
|
-
global_num_workers = self.world_size * num_workers
|
|
995
|
-
|
|
996
|
-
# Split up the windows evenly among the workers.
|
|
997
|
-
# We compute this for all workers since we will need to see the maximum number
|
|
998
|
-
# of samples under this assignment across workers.
|
|
999
|
-
window_indexes = range(len(self.windows))
|
|
1000
|
-
windows_by_worker = [
|
|
1001
|
-
window_indexes[cur_rank :: self.world_size][cur_worker_id::num_workers]
|
|
1002
|
-
for cur_rank in range(self.world_size)
|
|
1003
|
-
for cur_worker_id in range(num_workers)
|
|
1004
|
-
]
|
|
1005
|
-
|
|
1006
|
-
# Now compute the maximum number of samples across workers.
|
|
1007
|
-
max_num_patches = 0
|
|
1008
|
-
for worker_windows in windows_by_worker:
|
|
1009
|
-
worker_num_patches = 0
|
|
1010
|
-
for window_id in worker_windows:
|
|
1011
|
-
worker_num_patches += self.get_window_num_patches(
|
|
1012
|
-
self.windows[window_id].bounds
|
|
1013
|
-
)
|
|
1014
|
-
max_num_patches = max(max_num_patches, worker_num_patches)
|
|
1015
|
-
|
|
1016
|
-
# Each worker needs at least one window, otherwise it won't be able to pad.
|
|
1017
|
-
# Unless there are zero windows total, which is fine.
|
|
1018
|
-
# Previously we would address this by borrowing the windows from another
|
|
1019
|
-
# worker, but this causes issues with RslearnWriter: if we yield the same
|
|
1020
|
-
# window from parallel workers, it may end up writing an empty output for that
|
|
1021
|
-
# window in the end.
|
|
1022
|
-
# So now we raise an error instead, and require the number of workers to be
|
|
1023
|
-
# less than the number of windows.
|
|
1024
|
-
if len(windows_by_worker[global_worker_id]) == 0 and max_num_patches > 0:
|
|
1025
|
-
raise ValueError(
|
|
1026
|
-
f"the number of workers {global_num_workers} must be <= the number of windows {len(self.windows)}"
|
|
1027
|
-
)
|
|
1028
|
-
|
|
1029
|
-
return (windows_by_worker[global_worker_id], max_num_patches)
|
|
1030
|
-
|
|
1031
|
-
def __iter__(
|
|
1032
|
-
self,
|
|
1033
|
-
) -> Iterator[tuple[dict[str, Any], dict[str, Any], dict[str, Any]]]:
|
|
1034
|
-
"""Iterate over all patches in each element of the underlying ModelDataset."""
|
|
1035
|
-
# Iterate over the window IDs until we have returned enough samples.
|
|
1036
|
-
window_ids, num_samples_needed = self._get_worker_iteration_data()
|
|
1037
|
-
num_samples_returned = 0
|
|
1038
|
-
|
|
1039
|
-
for iteration_idx in itertools.count():
|
|
1040
|
-
for window_id in window_ids:
|
|
1041
|
-
raw_inputs, passthrough_inputs, metadata = self.dataset.get_raw_inputs(
|
|
1042
|
-
window_id
|
|
1043
|
-
)
|
|
1044
|
-
bounds = metadata["bounds"]
|
|
1045
|
-
|
|
1046
|
-
# For simplicity, pad tensors by patch size to ensure that any patch bounds
|
|
1047
|
-
# extending outside the window bounds will not have issues when we slice
|
|
1048
|
-
# the tensors later.
|
|
1049
|
-
pad_slice_protect(raw_inputs, passthrough_inputs, self.patch_size)
|
|
1050
|
-
|
|
1051
|
-
# Now iterate over the patches and extract/yield the crops.
|
|
1052
|
-
# Note that, in case user is leveraging RslearnWriter, it is important that
|
|
1053
|
-
# the patch_idx be increasing (as we iterate) within one window.
|
|
1054
|
-
patches = get_window_patch_options(
|
|
1055
|
-
self.patch_size, self.overlap_size, bounds
|
|
1056
|
-
)
|
|
1057
|
-
for patch_idx, patch_bounds in enumerate(patches):
|
|
1058
|
-
cur_geom = STGeometry(
|
|
1059
|
-
metadata["projection"], shapely.box(*patch_bounds), None
|
|
1060
|
-
)
|
|
1061
|
-
start_offset = (
|
|
1062
|
-
patch_bounds[0] - bounds[0],
|
|
1063
|
-
patch_bounds[1] - bounds[1],
|
|
1064
|
-
)
|
|
1065
|
-
end_offset = (
|
|
1066
|
-
patch_bounds[2] - bounds[0],
|
|
1067
|
-
patch_bounds[3] - bounds[1],
|
|
1068
|
-
)
|
|
1069
|
-
|
|
1070
|
-
# Define a helper function to handle each input dict.
|
|
1071
|
-
def crop_input_dict(d: dict[str, Any]) -> dict[str, Any]:
|
|
1072
|
-
cropped = {}
|
|
1073
|
-
for input_name, value in d.items():
|
|
1074
|
-
if isinstance(value, torch.Tensor):
|
|
1075
|
-
# Crop the CHW tensor.
|
|
1076
|
-
cropped[input_name] = value[
|
|
1077
|
-
:,
|
|
1078
|
-
start_offset[1] : end_offset[1],
|
|
1079
|
-
start_offset[0] : end_offset[0],
|
|
1080
|
-
].clone()
|
|
1081
|
-
elif isinstance(value, list):
|
|
1082
|
-
cropped[input_name] = [
|
|
1083
|
-
feat
|
|
1084
|
-
for feat in value
|
|
1085
|
-
if cur_geom.intersects(feat.geometry)
|
|
1086
|
-
]
|
|
1087
|
-
else:
|
|
1088
|
-
raise ValueError(
|
|
1089
|
-
"got input that is neither tensor nor feature list"
|
|
1090
|
-
)
|
|
1091
|
-
return cropped
|
|
1092
|
-
|
|
1093
|
-
cur_raw_inputs = crop_input_dict(raw_inputs)
|
|
1094
|
-
cur_passthrough_inputs = crop_input_dict(passthrough_inputs)
|
|
1095
|
-
|
|
1096
|
-
# Adjust the metadata as well.
|
|
1097
|
-
cur_metadata = metadata.copy()
|
|
1098
|
-
cur_metadata["bounds"] = patch_bounds
|
|
1099
|
-
cur_metadata["patch_idx"] = patch_idx
|
|
1100
|
-
cur_metadata["num_patches"] = len(patches)
|
|
1101
|
-
|
|
1102
|
-
# Now we can compute input and target dicts via the task.
|
|
1103
|
-
input_dict, target_dict = self.dataset.task.process_inputs(
|
|
1104
|
-
cur_raw_inputs,
|
|
1105
|
-
metadata=cur_metadata,
|
|
1106
|
-
load_targets=not self.dataset.split_config.get_skip_targets(),
|
|
1107
|
-
)
|
|
1108
|
-
input_dict.update(cur_passthrough_inputs)
|
|
1109
|
-
input_dict, target_dict = self.dataset.transforms(
|
|
1110
|
-
input_dict, target_dict
|
|
1111
|
-
)
|
|
1112
|
-
input_dict["dataset_source"] = self.dataset.name
|
|
1113
|
-
|
|
1114
|
-
if num_samples_returned < num_samples_needed:
|
|
1115
|
-
yield input_dict, target_dict, cur_metadata
|
|
1116
|
-
num_samples_returned += 1
|
|
1117
|
-
else:
|
|
1118
|
-
assert iteration_idx > 0
|
|
1119
|
-
|
|
1120
|
-
if num_samples_returned >= num_samples_needed:
|
|
1121
|
-
break
|
|
1122
|
-
|
|
1123
|
-
def get_dataset_examples(self) -> list[Window]:
|
|
1124
|
-
"""Returns a list of windows in this dataset."""
|
|
1125
|
-
return self.dataset.get_dataset_examples()
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
class InMemoryAllPatchesDataset(torch.utils.data.Dataset):
|
|
1129
|
-
"""This wraps a ModelDataset to iterate over all patches in that dataset.
|
|
1130
|
-
|
|
1131
|
-
This should be used when SplitConfig.load_all_patches is enabled.
|
|
1132
|
-
|
|
1133
|
-
This is a simpler version of IterableAllPatchesDataset that caches all windows in memory.
|
|
1134
|
-
This is useful for small datasets that fit in memory.
|
|
1135
|
-
"""
|
|
1136
|
-
|
|
1137
|
-
def __init__(
|
|
1138
|
-
self,
|
|
1139
|
-
dataset: ModelDataset,
|
|
1140
|
-
patch_size: tuple[int, int],
|
|
1141
|
-
overlap_ratio: float = 0.0,
|
|
1142
|
-
):
|
|
1143
|
-
"""Create a new InMemoryAllPatchesDataset.
|
|
1144
|
-
|
|
1145
|
-
Args:
|
|
1146
|
-
dataset: the ModelDataset to wrap.
|
|
1147
|
-
patch_size: the size of the patches to extract.
|
|
1148
|
-
overlap_ratio: whether to include overlap between the patches. Note that
|
|
1149
|
-
the right/bottom-most patches may still overlap since we ensure that
|
|
1150
|
-
all patches are contained in the window bounds.
|
|
1151
|
-
"""
|
|
1152
|
-
super().__init__()
|
|
1153
|
-
self.dataset = dataset
|
|
1154
|
-
self.patch_size = patch_size
|
|
1155
|
-
self.overlap_size = (
|
|
1156
|
-
round(self.patch_size[0] * overlap_ratio),
|
|
1157
|
-
round(self.patch_size[1] * overlap_ratio),
|
|
1158
|
-
)
|
|
1159
|
-
self.windows = self.dataset.get_dataset_examples()
|
|
1160
|
-
self.window_cache: dict[
|
|
1161
|
-
int, tuple[dict[str, Any], dict[str, Any], dict[str, Any]]
|
|
1162
|
-
] = {}
|
|
1163
|
-
|
|
1164
|
-
# Precompute the batch boundaries for each window
|
|
1165
|
-
self.patches = []
|
|
1166
|
-
for window_id, window in enumerate(self.windows):
|
|
1167
|
-
patch_bounds = get_window_patch_options(
|
|
1168
|
-
self.patch_size, self.overlap_size, window.bounds
|
|
1169
|
-
)
|
|
1170
|
-
for i, patch_bound in enumerate(patch_bounds):
|
|
1171
|
-
self.patches.append((window_id, patch_bound, (i, len(patch_bounds))))
|
|
1172
|
-
|
|
1173
|
-
def get_raw_inputs(
|
|
1174
|
-
self, index: int
|
|
1175
|
-
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
|
|
1176
|
-
"""Get the raw inputs for a single patch. Retrieve from cache if possible.
|
|
1177
|
-
|
|
1178
|
-
Also crops/pads the tensors by patch size to protect slicing near right/bottom edges.
|
|
1179
|
-
|
|
1180
|
-
Args:
|
|
1181
|
-
index: the index of the patch.
|
|
1182
|
-
|
|
1183
|
-
Returns:
|
|
1184
|
-
a tuple of (raw_inputs, passthrough_inputs, metadata).
|
|
1185
|
-
"""
|
|
1186
|
-
if index in self.window_cache:
|
|
1187
|
-
return self.window_cache[index]
|
|
1188
|
-
|
|
1189
|
-
raw_inputs, passthrough_inputs, metadata = self.dataset.get_raw_inputs(index)
|
|
1190
|
-
pad_slice_protect(raw_inputs, passthrough_inputs, self.patch_size)
|
|
1191
|
-
|
|
1192
|
-
self.window_cache[index] = (raw_inputs, passthrough_inputs, metadata)
|
|
1193
|
-
return self.window_cache[index]
|
|
1194
|
-
|
|
1195
|
-
@staticmethod
|
|
1196
|
-
def _crop_input_dict(
|
|
1197
|
-
d: dict[str, Any],
|
|
1198
|
-
start_offset: tuple[int, int],
|
|
1199
|
-
end_offset: tuple[int, int],
|
|
1200
|
-
cur_geom: STGeometry,
|
|
1201
|
-
) -> dict[str, Any]:
|
|
1202
|
-
"""Crop a dictionary of inputs to the given bounds."""
|
|
1203
|
-
cropped = {}
|
|
1204
|
-
for input_name, value in d.items():
|
|
1205
|
-
if isinstance(value, torch.Tensor):
|
|
1206
|
-
cropped[input_name] = value[
|
|
1207
|
-
:,
|
|
1208
|
-
start_offset[1] : end_offset[1],
|
|
1209
|
-
start_offset[0] : end_offset[0],
|
|
1210
|
-
].clone()
|
|
1211
|
-
elif isinstance(value, list):
|
|
1212
|
-
cropped[input_name] = [
|
|
1213
|
-
feat for feat in value if cur_geom.intersects(feat.geometry)
|
|
1214
|
-
]
|
|
1215
|
-
else:
|
|
1216
|
-
raise ValueError("got input that is neither tensor nor feature list")
|
|
1217
|
-
return cropped
|
|
1218
|
-
|
|
1219
|
-
def __len__(self) -> int:
|
|
1220
|
-
"""Return the total number of patches in the dataset."""
|
|
1221
|
-
return len(self.patches)
|
|
1222
|
-
|
|
1223
|
-
def __getitem__(
|
|
1224
|
-
self, index: int
|
|
1225
|
-
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
|
|
1226
|
-
"""Return (input_dict, target_dict, metadata) for a single flattened patch."""
|
|
1227
|
-
(window_id, patch_bounds, (patch_idx, num_patches)) = self.patches[index]
|
|
1228
|
-
raw_inputs, passthrough_inputs, metadata = self.get_raw_inputs(window_id)
|
|
1229
|
-
bounds = metadata["bounds"]
|
|
1230
|
-
|
|
1231
|
-
cur_geom = STGeometry(metadata["projection"], shapely.box(*patch_bounds), None)
|
|
1232
|
-
start_offset = (patch_bounds[0] - bounds[0], patch_bounds[1] - bounds[1])
|
|
1233
|
-
end_offset = (patch_bounds[2] - bounds[0], patch_bounds[3] - bounds[1])
|
|
1234
|
-
|
|
1235
|
-
cur_raw_inputs = self._crop_input_dict(
|
|
1236
|
-
raw_inputs, start_offset, end_offset, cur_geom
|
|
1237
|
-
)
|
|
1238
|
-
cur_passthrough_inputs = self._crop_input_dict(
|
|
1239
|
-
passthrough_inputs, start_offset, end_offset, cur_geom
|
|
1240
|
-
)
|
|
1241
|
-
|
|
1242
|
-
# Adjust the metadata as well.
|
|
1243
|
-
cur_metadata = metadata.copy()
|
|
1244
|
-
cur_metadata["bounds"] = patch_bounds
|
|
1245
|
-
cur_metadata["patch_idx"] = patch_idx
|
|
1246
|
-
cur_metadata["num_patches"] = num_patches
|
|
1247
|
-
|
|
1248
|
-
# Now we can compute input and target dicts via the task.
|
|
1249
|
-
input_dict, target_dict = self.dataset.task.process_inputs(
|
|
1250
|
-
cur_raw_inputs,
|
|
1251
|
-
metadata=cur_metadata,
|
|
1252
|
-
load_targets=not self.dataset.split_config.get_skip_targets(),
|
|
1253
|
-
)
|
|
1254
|
-
input_dict.update(cur_passthrough_inputs)
|
|
1255
|
-
input_dict, target_dict = self.dataset.transforms(input_dict, target_dict)
|
|
1256
|
-
input_dict["dataset_source"] = self.dataset.name
|
|
1257
|
-
|
|
1258
|
-
return input_dict, target_dict, cur_metadata
|
|
1259
|
-
|
|
1260
|
-
def get_dataset_examples(self) -> list[Window]:
|
|
1261
|
-
"""Returns a list of windows in this dataset."""
|
|
1262
|
-
return self.dataset.get_dataset_examples()
|
|
1263
|
-
|
|
1264
|
-
def set_name(self, name: str) -> None:
|
|
1265
|
-
"""Sets dataset name.
|
|
1266
|
-
|
|
1267
|
-
Args:
|
|
1268
|
-
name: dataset name
|
|
1269
|
-
"""
|
|
1270
|
-
self.dataset.set_name(name)
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
837
|
class RetryDataset(torch.utils.data.Dataset):
|
|
1274
838
|
"""A dataset wrapper that retries getitem upon encountering error."""
|
|
1275
839
|
|
|
@@ -22,7 +22,11 @@ from rslearn.log_utils import get_logger
|
|
|
22
22
|
from rslearn.utils.array import copy_spatial_array
|
|
23
23
|
from rslearn.utils.feature import Feature
|
|
24
24
|
from rslearn.utils.geometry import PixelBounds
|
|
25
|
-
from rslearn.utils.raster_format import
|
|
25
|
+
from rslearn.utils.raster_format import (
|
|
26
|
+
RasterFormat,
|
|
27
|
+
adjust_projection_and_bounds_for_array,
|
|
28
|
+
load_raster_format,
|
|
29
|
+
)
|
|
26
30
|
from rslearn.utils.vector_format import VectorFormat, load_vector_format
|
|
27
31
|
|
|
28
32
|
from .lightning_module import RslearnLightningModule
|
|
@@ -68,15 +72,18 @@ class VectorMerger(PatchPredictionMerger):
|
|
|
68
72
|
class RasterMerger(PatchPredictionMerger):
|
|
69
73
|
"""Merger for raster data that copies the rasters to the output."""
|
|
70
74
|
|
|
71
|
-
def __init__(self, padding: int | None = None):
|
|
75
|
+
def __init__(self, padding: int | None = None, downsample_factor: int = 1):
|
|
72
76
|
"""Create a new RasterMerger.
|
|
73
77
|
|
|
74
78
|
Args:
|
|
75
79
|
padding: the padding around the individual patch outputs to remove. This is
|
|
76
80
|
typically used when leveraging overlapping patches. Portions of outputs
|
|
77
81
|
at the border of the window will still be retained.
|
|
82
|
+
downsample_factor: the factor by which the rasters output by the task are
|
|
83
|
+
lower in resolution relative to the window resolution.
|
|
78
84
|
"""
|
|
79
85
|
self.padding = padding
|
|
86
|
+
self.downsample_factor = downsample_factor
|
|
80
87
|
|
|
81
88
|
def merge(
|
|
82
89
|
self, window: Window, outputs: Sequence[PendingPatchOutput]
|
|
@@ -87,8 +94,8 @@ class RasterMerger(PatchPredictionMerger):
|
|
|
87
94
|
merged_image = np.zeros(
|
|
88
95
|
(
|
|
89
96
|
num_channels,
|
|
90
|
-
window.bounds[3] - window.bounds[1],
|
|
91
|
-
window.bounds[2] - window.bounds[0],
|
|
97
|
+
(window.bounds[3] - window.bounds[1]) // self.downsample_factor,
|
|
98
|
+
(window.bounds[2] - window.bounds[0]) // self.downsample_factor,
|
|
92
99
|
),
|
|
93
100
|
dtype=dtype,
|
|
94
101
|
)
|
|
@@ -104,7 +111,10 @@ class RasterMerger(PatchPredictionMerger):
|
|
|
104
111
|
# If the output is not on the left or top boundary, then we should apply
|
|
105
112
|
# the padding (if set).
|
|
106
113
|
src = output.output
|
|
107
|
-
src_offset = (
|
|
114
|
+
src_offset = (
|
|
115
|
+
output.bounds[0] // self.downsample_factor,
|
|
116
|
+
output.bounds[1] // self.downsample_factor,
|
|
117
|
+
)
|
|
108
118
|
if self.padding is not None and output.bounds[0] != window.bounds[0]:
|
|
109
119
|
src = src[:, :, self.padding :]
|
|
110
120
|
src_offset = (src_offset[0] + self.padding, src_offset[1])
|
|
@@ -116,7 +126,10 @@ class RasterMerger(PatchPredictionMerger):
|
|
|
116
126
|
src=src,
|
|
117
127
|
dst=merged_image,
|
|
118
128
|
src_offset=src_offset,
|
|
119
|
-
dst_offset=(
|
|
129
|
+
dst_offset=(
|
|
130
|
+
window.bounds[0] // self.downsample_factor,
|
|
131
|
+
window.bounds[1] // self.downsample_factor,
|
|
132
|
+
),
|
|
120
133
|
)
|
|
121
134
|
|
|
122
135
|
return merged_image
|
|
@@ -330,9 +343,13 @@ class RslearnWriter(BasePredictionWriter):
|
|
|
330
343
|
self.output_layer, self.layer_config.band_sets[0].bands
|
|
331
344
|
)
|
|
332
345
|
assert isinstance(self.format, RasterFormat)
|
|
333
|
-
|
|
334
|
-
|
|
346
|
+
|
|
347
|
+
# In case the merged_output is at a different resolution than the window,
|
|
348
|
+
# get adjusted projection and bounds for writing it.
|
|
349
|
+
projection, bounds = adjust_projection_and_bounds_for_array(
|
|
350
|
+
window.projection, window.bounds, merged_output
|
|
335
351
|
)
|
|
352
|
+
self.format.encode_raster(raster_dir, projection, bounds, merged_output)
|
|
336
353
|
|
|
337
354
|
elif self.layer_config.layer_type == LayerType.VECTOR:
|
|
338
355
|
layer_dir = window.get_layer_dir(self.output_layer)
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Embedding task."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import numpy.typing as npt
|
|
6
|
+
import torch
|
|
7
|
+
from torchmetrics import MetricCollection
|
|
8
|
+
|
|
9
|
+
from rslearn.utils import Feature
|
|
10
|
+
|
|
11
|
+
from .task import Task
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class EmbeddingTask(Task):
|
|
15
|
+
"""A dummy task for computing embeddings.
|
|
16
|
+
|
|
17
|
+
This task does not compute any targets or loss. Instead, it is just set up for
|
|
18
|
+
inference, to save embeddings from the configured model.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def process_inputs(
|
|
22
|
+
self,
|
|
23
|
+
raw_inputs: dict[str, torch.Tensor],
|
|
24
|
+
metadata: dict[str, Any],
|
|
25
|
+
load_targets: bool = True,
|
|
26
|
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
27
|
+
"""Processes the data into targets.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
raw_inputs: raster or vector data to process
|
|
31
|
+
metadata: metadata about the patch being read
|
|
32
|
+
load_targets: whether to load the targets or only inputs
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
tuple (input_dict, target_dict) containing the processed inputs and targets
|
|
36
|
+
that are compatible with both metrics and loss functions
|
|
37
|
+
"""
|
|
38
|
+
return {}, {}
|
|
39
|
+
|
|
40
|
+
def process_output(
|
|
41
|
+
self, raw_output: Any, metadata: dict[str, Any]
|
|
42
|
+
) -> npt.NDArray[Any] | list[Feature]:
|
|
43
|
+
"""Processes an output into raster or vector data.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
raw_output: the output from prediction head.
|
|
47
|
+
metadata: metadata about the patch being read
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
either raster or vector data.
|
|
51
|
+
"""
|
|
52
|
+
# Just convert the raw output to numpy array that can be saved to GeoTIFF.
|
|
53
|
+
return raw_output.cpu().numpy()
|
|
54
|
+
|
|
55
|
+
def visualize(
|
|
56
|
+
self,
|
|
57
|
+
input_dict: dict[str, Any],
|
|
58
|
+
target_dict: dict[str, Any] | None,
|
|
59
|
+
output: Any,
|
|
60
|
+
) -> dict[str, npt.NDArray[Any]]:
|
|
61
|
+
"""Visualize the outputs and targets.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
input_dict: the input dict from process_inputs
|
|
65
|
+
target_dict: the target dict from process_inputs
|
|
66
|
+
output: the prediction
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
a dictionary mapping image name to visualization image
|
|
70
|
+
"""
|
|
71
|
+
# EmbeddingTask is only set up to support `model predict`.
|
|
72
|
+
raise NotImplementedError
|
|
73
|
+
|
|
74
|
+
def get_metrics(self) -> MetricCollection:
|
|
75
|
+
"""Get the metrics for this task."""
|
|
76
|
+
return MetricCollection({})
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class EmbeddingHead(torch.nn.Module):
|
|
80
|
+
"""Head for embedding task.
|
|
81
|
+
|
|
82
|
+
This picks one feature map from the input list of feature maps to output. It also
|
|
83
|
+
returns a dummy loss.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(self, feature_map_index: int | None = 0):
|
|
87
|
+
"""Create a new EmbeddingHead.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
feature_map_index: the index of the feature map to choose from the input
|
|
91
|
+
list of multi-scale feature maps (default 0). If the input is already
|
|
92
|
+
a single feature map, then set to None.
|
|
93
|
+
"""
|
|
94
|
+
super().__init__()
|
|
95
|
+
self.feature_map_index = feature_map_index
|
|
96
|
+
|
|
97
|
+
def forward(
|
|
98
|
+
self,
|
|
99
|
+
features: torch.Tensor,
|
|
100
|
+
inputs: list[dict[str, Any]],
|
|
101
|
+
targets: list[dict[str, Any]] | None = None,
|
|
102
|
+
) -> tuple[torch.Tensor, dict[str, Any]]:
|
|
103
|
+
"""Select the desired feature map and return it along with a dummy loss.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
features: list of BCHW feature maps (or one feature map, if feature_map_index is None).
|
|
107
|
+
inputs: original inputs (ignored).
|
|
108
|
+
targets: should contain classes key that stores the per-pixel class labels.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
tuple of outputs and loss dict
|
|
112
|
+
"""
|
|
113
|
+
if self.feature_map_index is not None:
|
|
114
|
+
features = features[self.feature_map_index]
|
|
115
|
+
|
|
116
|
+
return features, {"loss": 0}
|