TMayer77 commited on
Commit
a91db25
·
verified ·
1 Parent(s): 051994f

DenseForestViT v_1_3 final model (P2_L2_seed2)

Browse files
Files changed (8) hide show
  1. README.md +92 -0
  2. best_model.pt +3 -0
  3. config.json +48 -0
  4. example_inference.py +17 -0
  5. final_val_metrics.json +23 -0
  6. model_v13.py +187 -0
  7. stage2_windows.py +69 -0
  8. train_loss.csv +11 -0
README.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - remote-sensing
4
+ - earth-observation
5
+ - forest-structure
6
+ - gedi
7
+ - vision-transformer
8
+ - multi-task
9
+ - pytorch
10
+ pipeline_tag: image-to-image
11
+ library_name: pytorch
12
+ ---
13
+
14
+ # DenseForestViT — native-resolution multi-task forest structure from GEDI and multi-modal EO
15
+
16
+ DenseForestViT predicts three forest-structure variables at 10 m from one model:
17
+
18
+ | Output | Meaning | Unit | Output range |
19
+ |---|---|---|---|
20
+ | RH | canopy height (GEDI RH98) | m | 0–60 |
21
+ | PAI | plant area index | m² of plant surface per m² of ground | 0–10 |
22
+ | FHD | foliage height diversity (Shannon diversity of the vertical foliage profile) | – | 0–4 |
23
+
24
+ It was trained on GEDI L2A/L2B labels and eight Earth observation modalities (41 bands, 2024 composites), each
25
+ kept at its native resolution: Sentinel-1, Sentinel-2 and Sentinel-2 indices at 10 m; HLS indices, Landsat,
26
+ Landsat indices, Landsat tasseled cap and SRTM terrain at 30 m.
27
+
28
+ Paper: Mayer, T., Persello, C., Willemen, L., Griffin, R. (in review). *Mapping Forest Structure with a
29
+ Native-Resolution Vision Transformer Employing GEDI and Multi-modal Earth Observation Data.*
30
+ Code: <https://github.com/MayerT1/DenseForestViT>
31
+
32
+ ## Model
33
+
34
+ - Two token streams: 10 m inputs give one token per pixel (3 × 1,024 tokens); 30 m inputs give one token per
35
+ 2 × 2 pixels = 60 m (5 × 256 tokens).
36
+ - Three layers of self-attention within a stream and cross-attention between streams (96-d, 4 heads), with an
37
+ ALiBi bias by ground distance between token centres.
38
+ - Convolutional decoder to three sigmoid-bounded heads. An auxiliary head reconstructs the GEDI L1B waveform
39
+ during training only; inference needs EO data alone.
40
+ - 861,679 parameters. Checkpoint `best_model.pt` (state dict; most of its size is the precomputed distance-bias
41
+ buffers). Architecture arguments in `config.json`; code in `model_v13.py`.
42
+
43
+ ## Training
44
+
45
+ 152,308 GEDI-centred 32 × 32 chips from 200 sample areas in 24 Appalachian Level IV ecoregions (42,820 test,
46
+ 22,628 held-out validation; split by 1 km blocks). Huber loss on the 3 × 3 pixels under each GEDI footprint,
47
+ equal task weights, + 0.2 × waveform loss + 0.001 × total variation. AdamW (lr 2 × 10⁻⁴), effective batch 32,
48
+ early stopping on GEDI test loss. Selected run: `P2_L2_seed2` (Native-30m geometry, equal task weights).
49
+
50
+ ## Evaluation (airborne lidar, 10 m; 95% block-bootstrap intervals in the paper)
51
+
52
+ | Site | RH R² | PAI R² | FHD R² |
53
+ |---|---|---|---|
54
+ | Sewanee, TN | 0.60 | 0.23 | 0.40 |
55
+ | MLBS, VA | 0.55 | 0.33 | 0.41 |
56
+ | ORNL, TN | 0.72 | 0.50 | 0.49 |
57
+
58
+ Held-out GEDI validation R²: RH 0.55, PAI 0.28, FHD 0.61. Matched a U-Net for height, exceeded it for PAI at all
59
+ sites, similar for FHD.
60
+
61
+ ## Use
62
+
63
+ ```bash
64
+ pip install torch huggingface_hub
65
+ python example_inference.py <this repo id>
66
+ ```
67
+
68
+ Inputs must be prepared exactly as in training with `stage2_windows.py`: for each chip centre, a 32 × 32 window
69
+ of every modality at its native resolution, bands selected by name in the order given in that file, missing
70
+ values filled with the window median, each band stretched 0–1 within the window. The trained prediction is the
71
+ centre 3 × 3 pixels (30 m) of the output; wall-to-wall maps tile one chip per 3 × 3 block (see
72
+ `Stage_2_Inference/stage2_run_v13.py` in the code repository).
73
+
74
+ ## Limitations
75
+
76
+ - Trained and evaluated only in the Appalachian ecoregions of the eastern United States; do not apply elsewhere
77
+ without retraining and independent validation.
78
+ - Predictions regress toward the mean: stands taller than about 30 m are predicted at 22–28 m, and PAI saturates
79
+ near 3 m² m⁻².
80
+ - Expects 2024-style annual composites built with the recipe in the paper; other compositing will shift inputs.
81
+
82
+ ## Citation
83
+
84
+ ```bibtex
85
+ @article{Mayer_DenseForestViT,
86
+ author = {Mayer, Timothy and Persello, Claudio and Willemen, Louise and Griffin, Robert},
87
+ title = {Mapping Forest Structure with a Native-Resolution Vision Transformer Employing GEDI and Multi-modal Earth Observation Data},
88
+ note = {In review}
89
+ }
90
+ ```
91
+
92
+ Funding: NASA Cooperative Agreement 80MSFC22M004 (University of Alabama in Huntsville, NASA Earth Action).
best_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:865245d46fef39a70ca227f085dea91070c44e827afebf40b2aad4614a4b4064
3
+ size 180714210
config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_kwargs": {
3
+ "embed_dim": 96,
4
+ "num_layers": 3,
5
+ "num_heads": 4,
6
+ "patch_size_8m": 1,
7
+ "coarse_mods": [
8
+ "dem",
9
+ "hls",
10
+ "landsat",
11
+ "landsatidx",
12
+ "tcap"
13
+ ],
14
+ "patch_size_24m": 2,
15
+ "centred": true,
16
+ "cross_alibi": true
17
+ },
18
+ "bands_per_cov": {
19
+ "dem": 2,
20
+ "hls": 6,
21
+ "landsat": 5,
22
+ "landsatidx": 6,
23
+ "s1": 4,
24
+ "tcap": 6,
25
+ "s2": 5,
26
+ "s2idx": 7
27
+ },
28
+ "train": {
29
+ "run": "P2_L2_seed2",
30
+ "variant": "G1",
31
+ "seed": 2,
32
+ "train_frac": 1.0,
33
+ "epochs": 50,
34
+ "lr": 0.0002,
35
+ "batch": 2,
36
+ "grad_accum": 16,
37
+ "task_weights": {
38
+ "rh": 1.0,
39
+ "pai": 1.0,
40
+ "fhd": 1.0
41
+ },
42
+ "lambda_wave": 0.2,
43
+ "tv_weight": 0.001,
44
+ "es_patience": 6,
45
+ "sample_w": "none",
46
+ "trainer": "train_v13.py (from v_1_2 train_stage1_dense_singlegpu.py)"
47
+ }
48
+ }
example_inference.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Minimal inference with the published DenseForestViT: download, rebuild from config.json, predict one chip.
3
+ Real inputs must be built with stage2_windows.py (32x32 window per modality at native resolution, NaN -> window
4
+ median, per-band 0-1 stretch); random numbers are used here only to show shapes."""
5
+ import json, sys, torch
6
+ from huggingface_hub import hf_hub_download
7
+ REPO = sys.argv[1] if len(sys.argv) > 1 else 'MayerT1/DenseForestViT' # change to your Hub repo id
8
+ files = {f: hf_hub_download(REPO, f) for f in ['config.json', 'best_model.pt', 'model_v13.py']}
9
+ sys.path.insert(0, str(__import__('pathlib').Path(files['model_v13.py']).parent))
10
+ from model_v13 import DenseForestViT, SUP_R0, SUP_R1
11
+ cfg = json.load(open(files['config.json']))
12
+ model = DenseForestViT(bands_per_cov=cfg['bands_per_cov'], **cfg['model_kwargs']).eval()
13
+ model.load_state_dict(torch.load(files['best_model.pt'], map_location='cpu', weights_only=False), strict=True)
14
+ chip = {m: torch.rand(1, c, 32, 32) for m, c in cfg['bands_per_cov'].items()} # replace with stage2_windows.chip(...)
15
+ with torch.no_grad(): out = model(chip, return_waveform=False)
16
+ for t in ['rh', 'pai', 'fhd']: # the trained output is the centre 3x3 (30 m) under the chip centre
17
+ print(t, round(float(out[t][0, SUP_R0:SUP_R1, SUP_R0:SUP_R1].mean()), 3))
final_val_metrics.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "rh": {
3
+ "r2": 0.5504175531875878,
4
+ "bias": -0.10463162511587143,
5
+ "rmse": 7.097187519073486,
6
+ "slope": 0.6028131069900539,
7
+ "n": 22628
8
+ },
9
+ "pai": {
10
+ "r2": 0.27928021182182017,
11
+ "bias": -0.1023998111486435,
12
+ "rmse": 1.5529906749725342,
13
+ "slope": 0.2877121631985449,
14
+ "n": 21982
15
+ },
16
+ "fhd": {
17
+ "r2": 0.6098342005989205,
18
+ "bias": 0.037768665701150894,
19
+ "rmse": 0.4305706322193146,
20
+ "slope": 0.6727707427434952,
21
+ "n": 21982
22
+ }
23
+ }
model_v13.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ DenseForestViT v_1_3 -- aux-waveform ViT with GEOMETRY switches for the Stage 1 ablation.
4
+
5
+ Defaults reproduce v_1_2 EXACTLY (same modules, same state_dict keys, loads the v_1_2 checkpoint strict=True):
6
+ coarse_mods=('dem',) patch_size_24m=12 centred=False cross_alibi=False
7
+
8
+ G1 (geometry fix; data and Stage 2 unchanged, native resolution kept):
9
+ coarse_mods=('dem','hls','landsat','landsatidx','tcap') all 30 m products in the coarse stream
10
+ patch_size_24m=2 16x16 coarse tokens (60 m); 12 did not divide 32
11
+ centred=True token coordinates measured from the chip centre,
12
+ so 10 m and 30 m tokens share one ground frame
13
+ cross_alibi=True distance bias on cross-attention (fine <-> coarse)
14
+
15
+ Self-test (CPU ok): python model_v13.py [path/to/v_1_2/best_model.pt]
16
+ """
17
+ import torch
18
+ import torch.nn as nn
19
+
20
+ GSD_8M, GSD_24M = 8.0, 24.0 # names kept from v_1_2; only the 1:3 ratio matters for ALiBi
21
+ PATCH_SIZE_8M_DEFAULT, PATCH_SIZE_24M = 1, 12
22
+ SUP_R0, SUP_R1, SUP_C0, SUP_C1 = 15, 18, 15, 18
23
+ ALL_MODS = ['s1', 's2', 's2idx', 'hls', 'landsat', 'landsatidx', 'tcap', 'dem'] # v_1_2 encoder order
24
+ V12_COARSE = ('dem',)
25
+ G1_COARSE = ('dem', 'hls', 'landsat', 'landsatidx', 'tcap')
26
+ TASK_CEILINGS = {'rh': 60.0, 'pai': 10.0, 'fhd': 4.0}
27
+ WAVE_LEN = 1420
28
+ PRESETS = {
29
+ 'A0': dict(coarse_mods=V12_COARSE, patch_size_24m=12, centred=False, cross_alibi=False),
30
+ 'G1': dict(coarse_mods=G1_COARSE, patch_size_24m=2, centred=True, cross_alibi=True),
31
+ }
32
+
33
+
34
+ def get_patch_centers(gsd, patch_size, n_modalities_stacked=1, centred=False):
35
+ n = 32 // patch_size
36
+ coords = torch.arange(n, dtype=torch.float32) * (patch_size * gsd) + (patch_size * gsd) / 2.0
37
+ if centred:
38
+ coords = coords - 16.0 * gsd # chip centre = corner of pixel 16 = (0, 0) in both streams
39
+ xs, ys = torch.meshgrid(coords, coords, indexing='xy')
40
+ return torch.stack([xs.flatten(), ys.flatten()], dim=1).repeat(n_modalities_stacked, 1)
41
+
42
+
43
+ def compute_alibi_bias(centers_q, centers_k, num_heads):
44
+ d = torch.cdist(centers_q, centers_k, p=2)
45
+ slopes = torch.tensor([1.0 / (2 ** (i + 1)) for i in range(num_heads)])
46
+ return -slopes.view(-1, 1, 1) * d.unsqueeze(0)
47
+
48
+
49
+ def _expand(bias, B):
50
+ return bias.unsqueeze(0).expand(B, -1, -1, -1).reshape(B * bias.size(0), bias.size(1), bias.size(2))
51
+
52
+
53
+ class GSDPatchEncoder(nn.Module):
54
+ def __init__(self, in_channels, embed_dim, patch_size):
55
+ super().__init__()
56
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
57
+ self.norm = nn.LayerNorm(embed_dim)
58
+
59
+ def forward(self, x):
60
+ return self.norm(self.proj(x).flatten(2).transpose(1, 2))
61
+
62
+
63
+ class CrossModalLayer(nn.Module):
64
+ def __init__(self, embed_dim, num_heads):
65
+ super().__init__()
66
+ self.self_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
67
+ self.cross_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
68
+ self.ffn = nn.Sequential(nn.Linear(embed_dim, embed_dim * 2), nn.GELU(), nn.Linear(embed_dim * 2, embed_dim))
69
+ self.norm1, self.norm2, self.norm3 = nn.LayerNorm(embed_dim), nn.LayerNorm(embed_dim), nn.LayerNorm(embed_dim)
70
+
71
+ def forward(self, x, context, alibi_self=None, alibi_cross=None):
72
+ B = x.size(0)
73
+ x_sa, _ = self.self_attn(x, x, x, attn_mask=None if alibi_self is None else _expand(alibi_self.to(x.dtype), B))
74
+ x = self.norm1(x + x_sa)
75
+ x_ca, _ = self.cross_attn(x, context, context,
76
+ attn_mask=None if alibi_cross is None else _expand(alibi_cross.to(x.dtype), B))
77
+ x = self.norm2(x + x_ca)
78
+ return self.norm3(x + self.ffn(x))
79
+
80
+
81
+ class ConvBlock(nn.Module):
82
+ def __init__(self, in_c, out_c):
83
+ super().__init__()
84
+ self.block = nn.Sequential(nn.Conv2d(in_c, out_c, 3, padding=1), nn.BatchNorm2d(out_c), nn.GELU(),
85
+ nn.Conv2d(out_c, out_c, 3, padding=1), nn.BatchNorm2d(out_c), nn.GELU())
86
+
87
+ def forward(self, x): return self.block(x)
88
+
89
+
90
+ class UNetDecoder(nn.Module):
91
+ def __init__(self, embed_dim, patch_size_8m):
92
+ super().__init__()
93
+ self.grid = 32 // patch_size_8m
94
+ self.up_blocks = nn.ModuleList([ConvBlock(embed_dim, 32)] if patch_size_8m == 1 else
95
+ [ConvBlock(embed_dim, 64), nn.ConvTranspose2d(64, 32, 2, stride=2), ConvBlock(32, 32)])
96
+
97
+ def forward(self, tokens_8m):
98
+ B, N, E = tokens_8m.shape; n_per = self.grid * self.grid
99
+ x = tokens_8m.view(B, N // n_per, n_per, E).mean(dim=1) # average co-registered fine modalities
100
+ x = x.transpose(1, 2).reshape(B, E, self.grid, self.grid)
101
+ for blk in self.up_blocks: x = blk(x)
102
+ return x
103
+
104
+
105
+ class ScaledTaskHead(nn.Module):
106
+ def __init__(self, in_channels, ceiling):
107
+ super().__init__()
108
+ self.conv = nn.Conv2d(in_channels, 1, kernel_size=1); self.ceiling = ceiling
109
+
110
+ def forward(self, x): return torch.sigmoid(self.conv(x).squeeze(1)) * self.ceiling
111
+
112
+
113
+ class DenseForestViT(nn.Module):
114
+ def __init__(self, bands_per_cov, embed_dim=96, num_layers=3, num_heads=4,
115
+ patch_size_8m=PATCH_SIZE_8M_DEFAULT, patch_size_24m=PATCH_SIZE_24M,
116
+ coarse_mods=V12_COARSE, centred=False, cross_alibi=False, verbose=True):
117
+ super().__init__()
118
+ assert 32 % patch_size_8m == 0, 'patch_size_8m must divide 32'
119
+ coarse_mods = tuple(coarse_mods)
120
+ if coarse_mods != V12_COARSE: assert 32 % patch_size_24m == 0, 'patch_size_24m must divide 32'
121
+ self.cfg = dict(embed_dim=embed_dim, num_layers=num_layers, num_heads=num_heads, patch_size_8m=patch_size_8m,
122
+ patch_size_24m=patch_size_24m, coarse_mods=list(coarse_mods), centred=centred, cross_alibi=cross_alibi)
123
+ self.num_layers = num_layers
124
+ fine = [m for m in ALL_MODS if m not in coarse_mods and m in bands_per_cov]
125
+ coarse = [m for m in ALL_MODS if m in coarse_mods and m in bands_per_cov]
126
+ self.encoders_8m = nn.ModuleDict({m: GSDPatchEncoder(bands_per_cov[m], embed_dim, patch_size_8m) for m in fine})
127
+ self.encoders_24m = nn.ModuleDict({m: GSDPatchEncoder(bands_per_cov[m], embed_dim, patch_size_24m) for m in coarse})
128
+ self.layers_8m = nn.ModuleList([CrossModalLayer(embed_dim, num_heads) for _ in range(num_layers)])
129
+ self.layers_24m = nn.ModuleList([CrossModalLayer(embed_dim, num_heads) for _ in range(num_layers)])
130
+ c8 = get_patch_centers(GSD_8M, patch_size_8m, len(fine), centred)
131
+ self.register_buffer('alibi_8m', compute_alibi_bias(c8, c8, num_heads)) # persistent (v_1_2 key)
132
+ if coarse:
133
+ c24 = get_patch_centers(GSD_24M, patch_size_24m, len(coarse), centred)
134
+ self.register_buffer('alibi_24m', compute_alibi_bias(c24, c24, num_heads))
135
+ if cross_alibi: # new in v_1_3: not saved in checkpoints (rebuilt from cfg)
136
+ self.register_buffer('alibi_x8', compute_alibi_bias(c8, c24, num_heads), persistent=False)
137
+ self.register_buffer('alibi_x24', compute_alibi_bias(c24, c8, num_heads), persistent=False)
138
+ self.decoder = UNetDecoder(embed_dim, patch_size_8m)
139
+ self.head_rh = ScaledTaskHead(32, TASK_CEILINGS['rh'])
140
+ self.head_pai = ScaledTaskHead(32, TASK_CEILINGS['pai'])
141
+ self.head_fhd = ScaledTaskHead(32, TASK_CEILINGS['fhd'])
142
+ self.wave_head = nn.Linear(embed_dim, WAVE_LEN)
143
+ if verbose:
144
+ n = 32 // patch_size_8m; nc = 32 // patch_size_24m
145
+ print(f'DenseForestViT v_1_3 fine={fine} ({len(fine)}x{n * n} tokens) coarse={coarse} '
146
+ f'({len(coarse)}x{nc * nc} tokens, patch {patch_size_24m}) centred={centred} cross_alibi={cross_alibi} '
147
+ f'params={sum(p.numel() for p in self.parameters()):,}')
148
+
149
+ def forward(self, batch_dict, return_embeddings=False, return_waveform=True):
150
+ all_8m = torch.cat([enc(batch_dict[m]) for m, enc in self.encoders_8m.items() if m in batch_dict], dim=1)
151
+ t24 = [enc(batch_dict[m]) for m, enc in self.encoders_24m.items() if m in batch_dict]
152
+ all_24m = torch.cat(t24, dim=1) if t24 else all_8m
153
+ xa = self.cfg['cross_alibi'] and bool(t24)
154
+ ctx8, ctx24 = all_24m, all_8m
155
+ for i in range(self.num_layers):
156
+ all_8m = self.layers_8m[i](all_8m, ctx8, alibi_self=self.alibi_8m if i == 0 else None,
157
+ alibi_cross=self.alibi_x8 if xa else None)
158
+ if t24:
159
+ all_24m = self.layers_24m[i](all_24m, ctx24, alibi_self=self.alibi_24m if i == 0 else None,
160
+ alibi_cross=self.alibi_x24 if xa else None)
161
+ ctx8, ctx24 = all_24m, all_8m
162
+ if return_embeddings:
163
+ return {'embeddings': all_8m.mean(dim=1)}
164
+ d = self.decoder(all_8m)
165
+ out = {'rh': self.head_rh(d), 'pai': self.head_pai(d), 'fhd': self.head_fhd(d)}
166
+ if return_waveform:
167
+ out['waveform_pred'] = self.wave_head(all_8m.mean(dim=1))
168
+ return out
169
+
170
+
171
+ if __name__ == '__main__':
172
+ import sys
173
+ NB = {'dem': 2, 'hls': 6, 'landsat': 5, 'landsatidx': 6, 's1': 4, 'tcap': 6, 's2': 5, 's2idx': 7}
174
+ torch.manual_seed(0)
175
+ x = {m: torch.rand(1, b, 32, 32) for m, b in NB.items()}
176
+ for name, kw in PRESETS.items():
177
+ m = DenseForestViT(NB, **kw).eval()
178
+ with torch.no_grad(): o = m(x, return_waveform=True)
179
+ print(f' {name}: rh{tuple(o["rh"].shape)} wave{tuple(o["waveform_pred"].shape)} OK')
180
+ if len(sys.argv) > 1: # A0 must load the v_1_2 checkpoint strictly and match the v_1_2 model output
181
+ sd = torch.load(sys.argv[1], map_location='cpu', weights_only=False)
182
+ a0 = DenseForestViT(NB, **PRESETS['A0']).eval(); a0.load_state_dict(sd, strict=True)
183
+ sys.path.insert(0, '/nas/rstor/tmayer/gedi/scripts/Pipeline_1_2_3_v_1_2_aux_waveform/Stage_1_Dense')
184
+ from model_dense_vit_v4_patchsweep import DenseForestViT as V12
185
+ v12 = V12(NB, embed_dim=96, num_layers=3, num_heads=4, patch_size_8m=1).eval(); v12.load_state_dict(sd, strict=True)
186
+ with torch.no_grad(): d = (a0(x, return_waveform=False)['rh'] - v12(x, return_waveform=False)['rh']).abs().max().item()
187
+ print(f' A0 vs v_1_2 (same checkpoint): max |diff| RH = {d:.2e} {"PASS" if d < 1e-5 else "FAIL"}')
stage2_windows.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # stage2_windows.py -- the ONE rule for building Stage 2 model inputs (Colab + HPC)
3
+ import numpy as np, rasterio
4
+ from scipy.ndimage import map_coordinates
5
+ ORDER = ['dem', 'hls', 'landsat', 'landsatidx', 's1', 'tcap', 's2', 's2idx'] # == stage1 meta.json eo_list
6
+ PRODUCT = {'s1': 's1Ascending', 'dem': 'DEMindices', 'hls': 'HLS', 'landsat': 'LandsatComposite',
7
+ 'landsatidx': 'LandsatIndices', 'tcap': 'landsatTasseledCapIndices', 's2': 'S2Composite', 's2idx': 'S2Indices'}
8
+ BANDS = {'s1': ['VV', 'VH', 'ratio', 'ndratio'], 'dem': ['dem', 'slope'],
9
+ 'hls': ['NDVI', 'NDWI', 'MNDWI', 'SAVI', 'NDMI', 'NDBI'], 'landsat': ['red', 'green', 'blue', 'nir', 'swir1'],
10
+ 'landsatidx': ['NDVI', 'NDWI', 'MNDWI', 'SAVI', 'NDMI', 'NDBI'],
11
+ 'tcap': ['brightness', 'greenness', 'wetness', 'fourth', 'fifth', 'sixth'],
12
+ 's2': ['red', 'green', 'blue', 'nir', 'swir1'],
13
+ 's2idx': ['S2_NDVI', 'S2_NDWI', 'S2_EVI', 'S2_MNDWI', 'S2_SAVI', 'S2_NDMI', 'S2_NDBI']}
14
+ CHIP, S0 = 32, 15 # 32x32 window; supervised 3x3 = rows/cols 15:18
15
+
16
+ def load_site(site_dir):
17
+ # Read the 8 full-AOI tifs; select bands BY NAME; NaN for nodata.
18
+ out = {}
19
+ for m in ORDER:
20
+ with rasterio.open(f'{site_dir}/{PRODUCT[m]}_2024.tif') as s:
21
+ desc = list(s.descriptions)
22
+ idx = [desc.index(b) + 1 for b in BANDS[m]] if all(desc) else list(range(1, len(BANDS[m]) + 1))
23
+ a = s.read(idx).astype(np.float32)
24
+ if s.nodata is not None: a[a == s.nodata] = np.nan
25
+ out[m] = dict(a=a, T=s.transform, crs=s.crs)
26
+ return out
27
+
28
+ def centers(site, aoi_bounds=None, stride=3):
29
+ # Chip centres on the s1 10 m grid: one chip per output 3x3 block (rows r..r+2, cols c..c+2).
30
+ # Centre = top-left corner of s1 pixel (r+1, c+1), so window rows/cols 15:18 land exactly on r..r+2 / c..c+2.
31
+ T = site['s1']['T']; H, W = site['s1']['a'].shape[1:]
32
+ r0 = c0 = 0; r1, c1 = H - 3, W - 3
33
+ if aoi_bounds is not None: # (lon0, lat0, lon1, lat1)
34
+ c0 = max(0, int((aoi_bounds[0] - T.c) / T.a)); c1 = min(W - 3, int((aoi_bounds[2] - T.c) / T.a))
35
+ r0 = max(0, int((aoi_bounds[3] - T.f) / T.e)); r1 = min(H - 3, int((aoi_bounds[1] - T.f) / T.e))
36
+ rr, cc = np.meshgrid(np.arange(r0, r1 + 1, stride), np.arange(c0, c1 + 1, stride), indexing='ij')
37
+ rr, cc = rr.ravel(), cc.ravel()
38
+ return rr, cc, T.c + (cc + 1) * T.a, T.f + (rr + 1) * T.e
39
+
40
+ def window(prod, lon, lat):
41
+ # 32x32 window at the product's NATIVE resolution centred on (lon, lat); nearest sampling (GEE default);
42
+ # NaN -> window median; per-band 0-1 stretch (== training chips).
43
+ a, T = prod['a'], prod['T']; j = np.arange(CHIP) - (CHIP / 2 - 0.5)
44
+ xs = lon + j * T.a; ys = lat + j * T.e
45
+ col = (xs - T.c) / T.a - 0.5; row = (ys - T.f) / T.e - 0.5
46
+ R, C = np.meshgrid(row, col, indexing='ij')
47
+ out = np.empty((a.shape[0], CHIP, CHIP), np.float32)
48
+ for b in range(a.shape[0]):
49
+ v = map_coordinates(a[b], [R, C], order=0, mode='constant', cval=np.nan)
50
+ v = np.zeros_like(v) if np.isnan(v).all() else np.where(np.isnan(v), np.nanmedian(v), v)
51
+ mn, mx = v.min(), v.max()
52
+ out[b] = 0 if mx == mn else (v - mn) / (mx - mn)
53
+ return out
54
+
55
+ def chip(site, lon, lat):
56
+ return {m: window(site[m], lon, lat) for m in ORDER}
57
+
58
+ # ---- validity (added 2026-11-10) ----
59
+ def raw_window(prod, lon, lat):
60
+ # same sampling as window(), no fill/stretch: NaN where there is no data
61
+ a, T = prod['a'], prod['T']; j = np.arange(CHIP) - (CHIP / 2 - 0.5)
62
+ R, C = np.meshgrid((lat + j * T.e - T.f) / T.e - 0.5, (lon + j * T.a - T.c) / T.a - 0.5, indexing='ij')
63
+ return np.stack([map_coordinates(a[b], [R, C], order=0, mode='constant', cval=np.nan) for b in range(a.shape[0])])
64
+
65
+ def chip_valid(site, lon, lat):
66
+ # centre_ok: supervised 3x3 (10 m) has data in s1 and S2; context: min fraction of valid pixels over the 8 windows
67
+ cen = all(np.isfinite(raw_window(site[m], lon, lat)[:, S0:S0 + 3, S0:S0 + 3]).all() for m in ['s1', 's2', 's2idx'])
68
+ ctx = min(float(np.isfinite(raw_window(site[m], lon, lat)).all(0).mean()) for m in ORDER)
69
+ return cen, ctx
train_loss.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ epoch,train_task_loss,train_wave_loss,test_task_loss,train_tv_loss,epoch_time_min,best_val,es_counter
2
+ 1,2.100514896388425,0.07252742704190915,2.1387112363971097,2.096090117334759,180.79919542074202,2.1387112363971097,0
3
+ 2,1.8935642207904073,0.06615729268643361,1.9304685030851143,1.891825518189012,180.89091833035152,1.9304685030851143,0
4
+ 3,1.836561233905427,0.06542776211293276,1.952636826688764,1.7602108556576774,180.6580882469813,1.9304685030851143,1
5
+ 4,1.8021757243649579,0.06493874907941777,1.8852588328364532,1.6788672976522387,180.6606025616328,1.8852588328364532,0
6
+ 5,1.770951931482812,0.064652385168263,1.9804361123131873,1.62517184002261,180.73742399215698,1.8852588328364532,1
7
+ 6,1.7422434072465327,0.06439851696671754,1.9681513538902529,1.59145622292067,180.87989513476688,1.8852588328364532,2
8
+ 7,1.7180796954360307,0.06416271190456517,1.895523019906504,1.5742100782536483,180.87317779461543,1.8852588328364532,3
9
+ 8,1.691776431817148,0.06399564962488956,1.906246764006616,1.5758121032073604,180.62047794262568,1.8852588328364532,4
10
+ 9,1.6655188395087712,0.06385947474833654,1.8969597245174616,1.5847337628478786,180.6670950293541,1.8852588328364532,5
11
+ 10,1.63717071139436,0.06363350084807222,1.8909126323236727,1.5719216233938498,180.87514660358428,1.8852588328364532,6