-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathsingle_file_galileo.py
More file actions
1952 lines (1740 loc) · 66 KB
/
single_file_galileo.py
File metadata and controls
1952 lines (1740 loc) · 66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# mypy: ignore-errors
# fmt: off
"""Copied from https://github.com/nasaharvest/galileo/blob/main/single_file_galileo.py."""
import collections.abc
import itertools
import json
import logging
import math
from collections import OrderedDict
from collections import OrderedDict as OrderedDictType
from collections.abc import Sequence
from contextlib import nullcontext
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange, repeat
from olmo_core.config import Config
from olmo_core.utils import get_default_device
from torch import Tensor, vmap
from torch.jit import Final
from upath import UPath
from olmoearth_pretrain.data.constants import Modality
from olmoearth_pretrain.nn.flexi_vit import PoolingType
from olmoearth_pretrain.train.masking import MaskedOlmoEarthSample
logger = logging.getLogger(__name__)
# constants
CONFIG_FILENAME = "config.json"
ENCODER_FILENAME = "encoder.pt"
BASE_GSD = 10
# band information
S1_BANDS = ["vv", "vh"]
S2_BANDS = [
"B02",
"B03",
"B04",
"B05",
"B06",
"B07",
"B08",
"B8A",
"B11",
"B12",
]
ERA5_BANDS = ["temperature_2m", "total_precipitation_sum"]
TC_BANDS = ["def", "soil", "aet"]
VIIRS_BANDS = ["avg_rad"]
SRTM_BANDS = ["elevation", "slope"]
DW_BANDS = [
"DW_water",
"DW_trees",
"DW_grass",
"DW_flooded_vegetation",
"DW_crops",
"DW_shrub_and_scrub",
"DW_built",
"DW_bare",
"DW_snow_and_ice",
]
WC_BANDS = [
"WC_temporarycrops",
"WC_maize",
"WC_wintercereals",
"WC_springcereals",
"WC_irrigation",
]
STATIC_DW_BANDS = [f"{x}_static" for x in DW_BANDS]
STATIC_WC_BANDS = [f"{x}_static" for x in WC_BANDS]
LANDSCAN_BANDS = ["b1"]
LOCATION_BANDS = ["x", "y", "z"]
SPACE_TIME_BANDS = S1_BANDS + S2_BANDS + ["NDVI"]
TIME_BANDS = ERA5_BANDS + TC_BANDS + VIIRS_BANDS
SPACE_BANDS = SRTM_BANDS + DW_BANDS + WC_BANDS
STATIC_BANDS = LANDSCAN_BANDS + LOCATION_BANDS + STATIC_DW_BANDS + STATIC_WC_BANDS
SPACE_TIME_BANDS_GROUPS_IDX: OrderedDictType[str, list[int]] = OrderedDict(
{
"S1": [SPACE_TIME_BANDS.index(b) for b in S1_BANDS],
"S2_RGB": [SPACE_TIME_BANDS.index(b) for b in ["B02", "B03", "B04"]],
"S2_Red_Edge": [SPACE_TIME_BANDS.index(b) for b in ["B05", "B06", "B07"]],
"S2_NIR_10m": [SPACE_TIME_BANDS.index(b) for b in ["B08"]],
"S2_NIR_20m": [SPACE_TIME_BANDS.index(b) for b in ["B8A"]],
"S2_SWIR": [SPACE_TIME_BANDS.index(b) for b in ["B11", "B12"]],
"NDVI": [SPACE_TIME_BANDS.index("NDVI")],
}
)
TIME_BAND_GROUPS_IDX: OrderedDictType[str, list[int]] = OrderedDict(
{
"ERA5": [TIME_BANDS.index(b) for b in ERA5_BANDS],
"TC": [TIME_BANDS.index(b) for b in TC_BANDS],
"VIIRS": [TIME_BANDS.index(b) for b in VIIRS_BANDS],
}
)
SPACE_BAND_GROUPS_IDX: OrderedDictType[str, list[int]] = OrderedDict(
{
"SRTM": [SPACE_BANDS.index(b) for b in SRTM_BANDS],
"DW": [SPACE_BANDS.index(b) for b in DW_BANDS],
"WC": [SPACE_BANDS.index(b) for b in WC_BANDS],
}
)
STATIC_BAND_GROUPS_IDX: OrderedDictType[str, list[int]] = OrderedDict(
{
"LS": [STATIC_BANDS.index(b) for b in LANDSCAN_BANDS],
"location": [STATIC_BANDS.index(b) for b in LOCATION_BANDS],
"DW_static": [STATIC_BANDS.index(b) for b in STATIC_DW_BANDS],
"WC_static": [STATIC_BANDS.index(b) for b in STATIC_WC_BANDS],
}
)
class Normalizer:
"""Galileo Normalizer."""
# these are the bands we will replace with the 2*std computation
# if std = True
std_bands: dict[int, list] = {
len(SPACE_TIME_BANDS): [b for b in SPACE_TIME_BANDS if b != "NDVI"],
len(SPACE_BANDS): SRTM_BANDS,
len(TIME_BANDS): TIME_BANDS,
len(STATIC_BANDS): LANDSCAN_BANDS,
}
def __init__(
self, std: bool = True, normalizing_dicts: dict | None = None, std_multiplier: float = 2
):
"""Initialize the Normalizer."""
self.normalizing_dicts = normalizing_dicts
self.shift_div_dict = {}
if std:
name_to_bands = {
len(SPACE_TIME_BANDS): SPACE_TIME_BANDS,
len(SPACE_BANDS): SPACE_BANDS,
len(TIME_BANDS): TIME_BANDS,
len(STATIC_BANDS): STATIC_BANDS,
}
#log names to bands
logger.info(f"Names to bands: {name_to_bands}")
assert normalizing_dicts is not None
for key, val in normalizing_dicts.items():
if isinstance(key, str):
continue
bands_to_replace = self.std_bands[key]
for band in bands_to_replace:
band_idx = name_to_bands[key].index(band)
mean = val["mean"][band_idx]
std = val["std"][band_idx]
min_value = mean - (std_multiplier * std)
max_value = mean + (std_multiplier * std)
div = max_value - min_value
if div == 0:
raise ValueError(f"{band} has div value of 0")
# if key not in shift_div_dict, add it
if key not in self.shift_div_dict:
self.shift_div_dict[key] = {"shift": {}, "div": {}}
self.shift_div_dict[key]["shift"][band_idx] = min_value
self.shift_div_dict[key]["div"][band_idx] = div
else:
raise ValueError("std must be True, default eo shift and div values are not supported")
@staticmethod
def _normalize(x: np.ndarray, shift_values: np.ndarray, div_values: np.ndarray) -> np.ndarray:
x = (x - shift_values) / div_values
return x
def __call__(self, x: np.ndarray):
"""Call the normalizer."""
# get the band idxs from the x shape
band_idxs = [i for i in range(x.shape[-1]) if i in self.shift_div_dict[x.shape[-1]]["div"]]
div_values = torch.tensor([self.shift_div_dict[x.shape[-1]]["div"][band_idx] for band_idx in band_idxs] + [1.0], device=x.device) # extra number is for the NDVI band
shift_values = torch.tensor([self.shift_div_dict[x.shape[-1]]["shift"][band_idx] for band_idx in band_idxs] + [0.0], device=x.device) # extra number is for the NDVI band
return self._normalize(x, shift_values, div_values)
def get_2d_sincos_pos_embed_with_resolution(
embed_dim, grid_size, res, cls_token=False, device="cpu"
):
"""get_2d_sincos_pos_embed_with_resolution.
grid_size: int of the grid height and width.
res: array of size n, representing the resolution of a pixel (say, in meters),
Return:
pos_embed: [n,grid_size*grid_size, embed_dim] or [n,1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
"""
res = res.to(device)
grid_h = torch.arange(grid_size, device=device)
grid_w = torch.arange(grid_size, device=device)
grid = torch.meshgrid(
grid_w, grid_h, indexing="xy"
) # here h goes first,direction reversed for numpy
grid = torch.stack(grid, dim=0) # 2 x h x w
# grid = grid.reshape([2, 1, grid_size, grid_size])
grid = torch.einsum("chw,n->cnhw", grid, res) # 2 x n x h x w
_, n, h, w = grid.shape
pos_embed = get_2d_sincos_pos_embed_from_grid_torch(
embed_dim, grid
) # # (nxH*W, D/2)
pos_embed = pos_embed.reshape(n, h * w, embed_dim)
if cls_token:
pos_embed = torch.cat(
[
torch.zeros([n, 1, embed_dim], device=pos_embed.device),
pos_embed,
],
dim=1,
)
return pos_embed
def get_2d_sincos_pos_embed_from_grid_torch(embed_dim, grid):
"""get_2d_sincos_pos_embed_from_grid_torch."""
assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h
emb_h = get_1d_sincos_pos_embed_from_grid_torch(
embed_dim // 2, grid[0]
) # (H*W, D/2)
emb_w = get_1d_sincos_pos_embed_from_grid_torch(
embed_dim // 2, grid[1]
) # (H*W, D/2)
emb = torch.cat([emb_h, emb_w], dim=1) # (H*W, D)
return emb
def get_1d_sincos_pos_embed_from_grid_torch(embed_dim, pos):
"""get_1d_sincos_pos_embed_from_grid_torch.
embed_dim: output dimension for each position
pos: a list of positions to be encoded: size (M,)
out: (M, D)
"""
assert embed_dim % 2 == 0
omega = torch.arange(embed_dim // 2, device=pos.device) / embed_dim / 2.0
omega = 1.0 / 10000**omega # (D/2,)
pos = pos.reshape(-1) # (M,)
out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product
emb_sin = torch.sin(out) # (M, D/2)
emb_cos = torch.cos(out) # (M, D/2)
emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D)
return emb
def get_month_encoding_table(embed_dim):
"""Sinusoid month encoding table, for 12 months indexed from 0-11."""
assert embed_dim % 2 == 0
angles = torch.arange(0, 13) / (12 / (2 * np.pi))
sin_table = torch.sin(torch.stack([angles for _ in range(embed_dim // 2)], axis=-1))
cos_table = torch.cos(torch.stack([angles for _ in range(embed_dim // 2)], axis=-1))
month_table = torch.concatenate([sin_table[:-1], cos_table[:-1]], axis=-1)
return month_table # (M, D)
def adjust_learning_rate(
optimizer,
epoch,
warmup_epochs,
total_epochs,
max_lr,
min_lr,
):
"""Decay the learning rate with half-cycle cosine after warmup."""
if epoch < warmup_epochs:
lr = max_lr * epoch / warmup_epochs
else:
lr = min_lr + (max_lr - min_lr) * 0.5 * (
1.0
+ math.cos(
math.pi * (epoch - warmup_epochs) / (total_epochs - warmup_epochs)
)
)
for group in optimizer.param_groups:
group["lr"] = lr
return lr
def load_normalization_values(path: Path):
"""Load the normalization values from a json file."""
if not path.exists():
raise ValueError(f"No file found at path {path}")
with path.open("r") as f:
norm_dict = json.load(f)
# we computed the normalizing dict using the same datset
output_dict = {}
for key, val in norm_dict.items():
if "n" not in key:
output_dict[int(key)] = val
else:
output_dict[key] = val
return output_dict
# thanks to https://github.com/bwconrad/flexivit/ for this nice implementation
# of the FlexiPatchEmbed module
def to_2tuple(x: Any) -> tuple:
"""to_2tuple."""
if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
return tuple(x)
return tuple(itertools.repeat(x, 2))
class FlexiPatchEmbed(nn.Module):
"""FlexiPatchEmbed."""
def __init__(
self,
patch_size: int | tuple[int, int],
in_chans: int = 3,
embed_dim: int = 128,
norm_layer: nn.Module | None = None,
bias: bool = True,
patch_size_seq: Sequence[int] = (1, 2, 3, 4, 5, 6),
interpolation: str = "bicubic",
antialias: bool = True,
) -> None:
"""2D image to patch embedding w/ flexible patch sizes.
Extended from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/patch_embed.py#L24
by https://github.com/bwconrad/flexivit/
Args:
patch_size: Base patch size. i.e the size of the parameter buffer
in_chans: Number of input image channels
embed_dim: Network embedding dimension size
norm_layer: Optional normalization layer
bias: Whether to use bias in convolution
patch_size_seq: List of patch sizes to randomly sample from
interpolation: Resize interpolation type
antialias: Whether to apply antialiasing resizing
"""
super().__init__()
self.patch_size = to_2tuple(patch_size)
self.proj = nn.Conv2d(
in_chans,
embed_dim,
kernel_size=self.patch_size,
stride=self.patch_size,
bias=bias,
)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
# Flexi specific attributes
self.interpolation = interpolation
self.antialias = antialias
self.patch_size_seq = patch_size_seq
# Pre-calculate pinvs
self.pinvs = self._cache_pinvs()
def _cache_pinvs(self) -> dict:
"""Pre-calculate all pinv matrices."""
pinvs = {}
for ps in self.patch_size_seq:
tuple_ps = to_2tuple(ps)
pinvs[tuple_ps] = self._calculate_pinv(self.patch_size, tuple_ps)
return pinvs
def _resize(self, x: Tensor, shape: tuple[int, int]) -> Tensor:
x_resized = F.interpolate(
x[None, None, ...],
shape,
mode=self.interpolation,
antialias=self.antialias,
)
return x_resized[0, 0, ...]
def _calculate_pinv(
self, old_shape: tuple[int, int], new_shape: tuple[int, int]
) -> Tensor:
mat = []
for i in range(np.prod(old_shape)):
basis_vec = torch.zeros(old_shape)
basis_vec[np.unravel_index(i, old_shape)] = 1.0
mat.append(self._resize(basis_vec, new_shape).reshape(-1))
resize_matrix = torch.stack(mat)
return torch.linalg.pinv(resize_matrix)
def resize_patch_embed(self, patch_embed: Tensor, new_patch_size: tuple[int, int]):
"""Resize patch_embed to target resolution via pseudo-inverse resizing."""
# Return original kernel if no resize is necessary
if self.patch_size == new_patch_size:
return patch_embed
# Calculate pseudo-inverse of resize matrix
if new_patch_size not in self.pinvs:
self.pinvs[new_patch_size] = self._calculate_pinv(
self.patch_size, new_patch_size
)
pinv = self.pinvs[new_patch_size]
pinv = pinv.to(patch_embed.device)
def resample_patch_embed(patch_embed: Tensor):
h, w = new_patch_size
resampled_kernel = pinv @ patch_embed.reshape(-1)
return rearrange(resampled_kernel, "(h w) -> h w", h=h, w=w)
v_resample_patch_embed = vmap(vmap(resample_patch_embed, 0, 0), 1, 1)
return v_resample_patch_embed(patch_embed)
def forward(
self,
x: Tensor,
patch_size: int | tuple[int, int] | None = None,
) -> Tensor | tuple[Tensor, tuple[int, int]]:
"""Forward."""
# x has input shape [b, h, w, (t), c]
batch_size = x.shape[0]
has_time_dimension = False
num_timesteps = 0 # ignored if has_time_dimension is False
if len(x.shape) == 5:
has_time_dimension = True
num_timesteps = x.shape[3]
x = rearrange(x, "b h w t c -> (b t) c h w")
else:
x = rearrange(x, "b h w c -> b c h w")
if not patch_size:
# During evaluation use base patch size if not specified
patch_size = self.patch_size
patch_size = to_2tuple(patch_size)
# Resize conv weights
if patch_size == self.patch_size:
weight = self.proj.weight
else:
weight = self.resize_patch_embed(self.proj.weight, patch_size)
# Apply conv with resized weights
x = F.conv2d(x, weight, bias=self.proj.bias, stride=patch_size)
if has_time_dimension:
x = rearrange(x, "(b t) c h w -> b h w t c", b=batch_size, t=num_timesteps)
else:
x = rearrange(x, "b c h w -> b h w c")
x = self.norm(x)
return x
class Attention(nn.Module):
"""Attention."""
# https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py
fast_attn: Final[bool]
def __init__(
self,
dim,
num_heads=8,
qkv_bias=False,
qk_norm=False,
attn_drop=0.0,
proj_drop=0.0,
norm_layer=nn.LayerNorm,
cross_attn: bool = False,
):
"""Attention init."""
super().__init__()
assert dim % num_heads == 0, "dim should be divisible by num_heads"
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.scale = self.head_dim**-0.5
self.fast_attn = hasattr(
torch.nn.functional, "scaled_dot_product_attention"
) # FIXME
self.cross_attn = cross_attn
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.k = nn.Linear(dim, dim, bias=qkv_bias)
self.v = nn.Linear(dim, dim, bias=qkv_bias)
self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, y=None, attn_mask=None):
"""Forward."""
B, N, C = x.shape
q = self.q(x)
if y is None:
assert not self.cross_attn
k = self.k(x)
v = self.v(x)
else:
assert self.cross_attn
k = self.k(y)
v = self.v(y)
q = rearrange(q, "b n (h d) -> b h n d", h=self.num_heads)
k = rearrange(k, "b n (h d) -> b h n d", h=self.num_heads)
v = rearrange(v, "b n (h d) -> b h n d", h=self.num_heads)
q, k = self.q_norm(q), self.k_norm(k)
if self.fast_attn:
if attn_mask is not None:
attn_mask = attn_mask[:, None, None].repeat((1, self.num_heads, N, 1))
x = F.scaled_dot_product_attention(
q,
k,
v,
# a value of True indicates that the element should take part in attention
attn_mask=attn_mask,
dropout_p=self.attn_drop.p,
)
else:
if attn_mask is not None:
raise NotImplementedError
q = q * self.scale
attn = q @ k.transpose(-2, -1)
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = attn @ v
x = x.transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Mlp(nn.Module):
"""MLP as used in Vision Transformer, MLP-Mixer and related networks."""
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
bias=True,
drop=0.0,
):
"""MLP as used in Vision Transformer, MLP-Mixer and related networks."""
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
self.act = act_layer()
self.drop1 = nn.Dropout(drop)
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
self.drop2 = nn.Dropout(drop)
def forward(self, x):
"""Forward."""
x = self.fc1(x)
x = self.act(x)
x = self.drop1(x)
x = self.fc2(x)
x = self.drop2(x)
return x
class LayerScale(nn.Module):
"""LayerScale."""
def __init__(self, dim, init_values=1e-5, inplace=False):
"""LayerScale."""
super().__init__()
self.inplace = inplace
self.gamma = nn.Parameter(init_values * torch.ones(dim))
def forward(self, x):
"""Forward."""
return x.mul_(self.gamma) if self.inplace else x * self.gamma
def drop_path(x, drop_prob: float = 0.0, training: bool = False):
"""drop_path."""
if drop_prob == 0.0 or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (
x.ndim - 1
) # work with diff dim tensors, not just 2D ConvNets
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
random_tensor.floor_() # binarize
output = x.div(keep_prob) * random_tensor
return output
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob=None):
"""Drop Path."""
super().__init__()
self.drop_prob = drop_prob
def forward(self, x):
"""Forward."""
return drop_path(x, self.drop_prob, self.training)
class Block(nn.Module):
"""Block."""
def __init__(
self,
dim,
num_heads,
mlp_ratio=4.0,
qkv_bias=False,
qk_norm=False,
drop=0.0,
attn_drop=0.0,
drop_path=0.0,
init_values=None,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm,
cross_attn: bool = False,
):
"""Block."""
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
qk_norm=qk_norm,
attn_drop=attn_drop,
proj_drop=drop,
norm_layer=norm_layer,
cross_attn=cross_attn,
)
self.ls1 = (
LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
self.mlp = Mlp(
in_features=dim,
hidden_features=int(dim * mlp_ratio),
act_layer=act_layer,
drop=drop,
)
self.ls2 = (
LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
)
def forward(self, x, y, attn_mask):
"""Forward."""
x = x + self.drop_path(self.ls1(self.attn(self.norm1(x), y, attn_mask)))
x = x + self.drop_path(self.ls2(self.mlp(self.norm2(x))))
return x
class ModuleListWithInit(nn.ModuleList):
"""ModuleListWithInit."""
def _init_weights(self, m):
if isinstance(m, nn.Linear):
# we use xavier_uniform following official JAX ViT:
torch.nn.init.xavier_uniform_(m.weight)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
class GalileoBase(nn.Module):
"""GalileoBase."""
cross_attn: bool
def __init__(
self,
embedding_size: int = 128,
depth=2,
mlp_ratio=2,
num_heads=8,
max_sequence_length=24,
base_patch_size: int = 4,
use_channel_embs: bool = True,
drop_path: float = 0.0,
):
"""Init GalileoBase."""
super().__init__()
self.space_time_groups = SPACE_TIME_BANDS_GROUPS_IDX
self.space_groups = SPACE_BAND_GROUPS_IDX
self.time_groups = TIME_BAND_GROUPS_IDX
self.static_groups = STATIC_BAND_GROUPS_IDX
self.embedding_size = embedding_size
self.base_patch_size = base_patch_size
self.blocks = ModuleListWithInit(
[
Block(
embedding_size,
num_heads,
mlp_ratio,
qkv_bias=True,
norm_layer=nn.LayerNorm,
cross_attn=self.cross_attn,
drop_path=drop_path,
)
for _ in range(depth)
]
)
self.max_sequence_length = max_sequence_length
# we have 4 embeddings (pos_in_time, pos_in_space, month, channel) so each get
# 0.25 of the dimension. This will change soon anyway
self.pos_embed = nn.Parameter(
get_1d_sincos_pos_embed_from_grid_torch(
int(embedding_size * 0.25), torch.arange(max_sequence_length)
),
requires_grad=False,
)
month_tab = get_month_encoding_table(int(embedding_size * 0.25))
self.month_embed = nn.Embedding.from_pretrained(month_tab, freeze=True)
if use_channel_embs:
args = {"requires_grad": True}
else:
args = {"requires_grad": False}
self.s_t_channel_embed = nn.Parameter(
torch.zeros(len(SPACE_TIME_BANDS_GROUPS_IDX), int(embedding_size * 0.25)),
**args,
)
self.sp_channel_embed = nn.Parameter(
torch.zeros(len(SPACE_BAND_GROUPS_IDX), int(embedding_size * 0.25)), **args
)
self.t_channel_embed = nn.Parameter(
torch.zeros(len(TIME_BAND_GROUPS_IDX), int(embedding_size * 0.25)), **args
)
self.st_channel_embed = nn.Parameter(
torch.zeros(len(STATIC_BAND_GROUPS_IDX), int(embedding_size * 0.25)), **args
)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
# we use xavier_uniform following official JAX ViT:
torch.nn.init.xavier_uniform_(m.weight)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
@classmethod
def collapse_and_combine_hwtc(
cls,
s_t_x: torch.Tensor,
sp_x: torch.Tensor,
t_x: torch.Tensor,
st_x: torch.Tensor,
s_t_m: torch.Tensor,
sp_m: torch.Tensor,
t_m: torch.Tensor,
st_m: torch.Tensor,
):
"""collapse_and_combine_hwtc."""
s_t_x = rearrange(s_t_x, "b h w t c_g d -> b (h w t c_g) d")
sp_x = rearrange(sp_x, "b h w c_g d -> b (h w c_g) d")
t_x = rearrange(t_x, "b t c_g d -> b (t c_g) d")
s_t_m = rearrange(s_t_m, "b h w t c_g-> b (h w t c_g)")
sp_m = rearrange(sp_m, "b h w c_g-> b (h w c_g)")
t_m = rearrange(t_m, "b t c_g -> b (t c_g)")
x = torch.cat(
[
s_t_x,
sp_x,
t_x,
st_x,
],
dim=1,
)
m = torch.cat([s_t_m, sp_m, t_m, st_m], dim=1)
return x, m
@classmethod
def split_and_expand_hwtc(
cls,
x: torch.Tensor,
h: int,
w: int,
t: int,
s_t_c_g: int,
sp_c_g: int,
t_c_g: int,
st_c_g: int,
):
"""split_and_expand_hwtc."""
n_s_t_t = h * w * t * s_t_c_g
n_t_t = t * t_c_g
s_t_x = rearrange(
x[:, :n_s_t_t], "b (h w t c) d -> b h w t c d", h=h, w=w, t=t, c=s_t_c_g
)
sp_x = rearrange(
x[:, n_s_t_t : -(n_t_t + st_c_g)],
"b (h w c) d -> b h w c d",
h=h,
w=w,
c=sp_c_g,
)
t_x = rearrange(
x[:, -(n_t_t + st_c_g) : -st_c_g], "b (t c) d -> b t c d", t=t, c=t_c_g
)
st_x = x[:, -st_c_g:]
return s_t_x, sp_x, t_x, st_x
def apply_encodings(self, s_t_x, sp_x, t_x, st_x, months, patch_size, input_res):
"""apply_encodings."""
b, h, w, t, s_t_c_g, _ = s_t_x.shape
sp_c_g, t_c_g = sp_x.shape[-2], t_x.shape[-2]
st_c_g = st_x.shape[-2]
s_t_channel = repeat(
self.s_t_channel_embed, "c_g d -> b h w t c_g d", b=b, h=h, w=w, t=t
)
t_channel = repeat(self.t_channel_embed, "c_g d -> b t c_g d", b=b, t=t)
st_channel = repeat(self.st_channel_embed, "c_g d -> b c_g d", b=b)
sp_channel = repeat(
self.sp_channel_embed, "c_g d -> b h w c_g d", b=b, h=h, w=w
)
pos_embed_s_t = repeat(
self.pos_embed[:t], "t d -> b h w t c_g d", b=b, h=h, w=w, c_g=s_t_c_g
)
m_embed_s_t = repeat(
self.month_embed(months), "b t d -> b h w t c_g d", h=h, w=w, c_g=s_t_c_g
)
pos_embed_t = repeat(self.pos_embed[:t], "t d -> b t c_g d", b=b, c_g=t_c_g)
m_embed_t = repeat(self.month_embed(months), "b t d -> b t c_g d", c_g=t_c_g)
t_zeros = torch.zeros(
b, t, t_c_g, int(self.embedding_size * 0.25), device=t_x.device
)
sp_zeros = torch.zeros(
b,
h,
w,
sp_c_g,
sp_channel.shape[-1] * 2,
device=sp_channel.device,
)
st_zeros = torch.zeros(
b, st_c_g, st_channel.shape[-1] * 3, device=st_channel.device
)
# find the resolution that each token represents, which will be
# the number of pixels in a patch * the resolution of each pixel
if patch_size is None:
patch_size = self.base_patch_size
token_res = input_res * patch_size
gsd_ratio = token_res / BASE_GSD
assert h == w, (
"get_2d_sincos_pos_embed_with_resolution currently requires that h==w"
)
spatial_embed = get_2d_sincos_pos_embed_with_resolution(
int(self.embedding_size * 0.25),
h,
torch.ones(b).to(s_t_x.device) * gsd_ratio,
device=s_t_x.device,
)
spatial_embed = rearrange(spatial_embed, "b (h w) d -> b h w d", h=h, w=w)
spatial_embed_s_t = repeat(
spatial_embed, "b h w d -> b h w t c_g d", h=h, w=w, t=t, c_g=s_t_c_g
)
spatial_embed_s = repeat(
spatial_embed, "b h w d -> b h w c_g d", h=h, w=w, c_g=sp_c_g
)
s_t_embed = torch.cat(
[s_t_channel, pos_embed_s_t, m_embed_s_t, spatial_embed_s_t], dim=-1
)
sp_embed = torch.cat([sp_channel, sp_zeros, spatial_embed_s], dim=-1)
t_embed = torch.cat([t_channel, pos_embed_t, m_embed_t, t_zeros], dim=-1)
st_embed = torch.cat([st_channel, st_zeros], dim=-1)
return s_t_x + s_t_embed, sp_x + sp_embed, t_x + t_embed, st_x + st_embed
class Encoder(GalileoBase):
"""Encoder."""
cross_attn = False
def __init__(
self,
max_patch_size: int = 8,
embedding_size: int = 128,
depth=2,
mlp_ratio=2,
num_heads=8,
max_sequence_length=24,
freeze_projections: bool = False,
drop_path: float = 0.0,
):
"""Init Encoder."""
super().__init__(
embedding_size,
depth,
mlp_ratio,
num_heads,
max_sequence_length,
max_patch_size,
use_channel_embs=True,
drop_path=drop_path,
)
self.space_time_embed = nn.ModuleDict(
{
group_name: FlexiPatchEmbed(
in_chans=len(group),
embed_dim=embedding_size,
patch_size=max_patch_size,
)
for group_name, group in self.space_time_groups.items()
}
)
self.space_embed = nn.ModuleDict(
{
group_name: FlexiPatchEmbed(
in_chans=len(group),
embed_dim=embedding_size,
patch_size=max_patch_size,
)
for group_name, group in self.space_groups.items()
}
)
self.time_embed = nn.ModuleDict(
{
group_name: nn.Linear(
in_features=len(group), out_features=embedding_size
)
for group_name, group in self.time_groups.items()
}
)
self.static_embed = nn.ModuleDict(
{
group_name: nn.Linear(
in_features=len(group), out_features=embedding_size
)
for group_name, group in self.static_groups.items()
}
)
if freeze_projections:
self.space_time_embed.requires_grad_(False)
self.space_embed.requires_grad_(False)
self.time_embed.requires_grad_(False)
self.static_embed.requires_grad_(False)
self.norm = nn.LayerNorm(embedding_size)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
# we use xavier_uniform following official JAX ViT:
torch.nn.init.xavier_uniform_(m.weight)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
def apply_linear_projection(
self,
s_t_x: torch.Tensor,
sp_x: torch.Tensor,
t_x: torch.Tensor,
st_x: torch.Tensor,
s_t_m: torch.Tensor,
sp_m: torch.Tensor,
t_m: torch.Tensor,
st_m: torch.Tensor,
patch_size: int,
):
"""Given a [B, H, W, (T), C] inputs, returns a [B, H, W, (T), C_G, D] output.
We assume that the spatial masks are consistent for the given patch size,
so that if patch_size == 2 then one possible mask would be
[0, 0, 1, 1]
[0, 0, 1, 1]
[1, 1, 0, 0]
[1, 1, 0, 0]
for the H, W dimensions
"""