DenseForestViT / model_v13.py
TMayer77's picture
DenseForestViT v_1_3 final model (P2_L2_seed2)
a91db25 verified
Raw History Blame Contribute Delete
10.6 kB
#!/usr/bin/env python3
"""
DenseForestViT v_1_3 -- aux-waveform ViT with GEOMETRY switches for the Stage 1 ablation.
Defaults reproduce v_1_2 EXACTLY (same modules, same state_dict keys, loads the v_1_2 checkpoint strict=True):
coarse_mods=('dem',) patch_size_24m=12 centred=False cross_alibi=False
G1 (geometry fix; data and Stage 2 unchanged, native resolution kept):
coarse_mods=('dem','hls','landsat','landsatidx','tcap') all 30 m products in the coarse stream
patch_size_24m=2 16x16 coarse tokens (60 m); 12 did not divide 32
centred=True token coordinates measured from the chip centre,
so 10 m and 30 m tokens share one ground frame
cross_alibi=True distance bias on cross-attention (fine <-> coarse)
Self-test (CPU ok): python model_v13.py [path/to/v_1_2/best_model.pt]
"""
import torch
import torch.nn as nn
GSD_8M, GSD_24M = 8.0, 24.0 # names kept from v_1_2; only the 1:3 ratio matters for ALiBi
PATCH_SIZE_8M_DEFAULT, PATCH_SIZE_24M = 1, 12
SUP_R0, SUP_R1, SUP_C0, SUP_C1 = 15, 18, 15, 18
ALL_MODS = ['s1', 's2', 's2idx', 'hls', 'landsat', 'landsatidx', 'tcap', 'dem'] # v_1_2 encoder order
V12_COARSE = ('dem',)
G1_COARSE = ('dem', 'hls', 'landsat', 'landsatidx', 'tcap')
TASK_CEILINGS = {'rh': 60.0, 'pai': 10.0, 'fhd': 4.0}
WAVE_LEN = 1420
PRESETS = {
'A0': dict(coarse_mods=V12_COARSE, patch_size_24m=12, centred=False, cross_alibi=False),
'G1': dict(coarse_mods=G1_COARSE, patch_size_24m=2, centred=True, cross_alibi=True),
}
def get_patch_centers(gsd, patch_size, n_modalities_stacked=1, centred=False):
n = 32 // patch_size
coords = torch.arange(n, dtype=torch.float32) * (patch_size * gsd) + (patch_size * gsd) / 2.0
if centred:
coords = coords - 16.0 * gsd # chip centre = corner of pixel 16 = (0, 0) in both streams
xs, ys = torch.meshgrid(coords, coords, indexing='xy')
return torch.stack([xs.flatten(), ys.flatten()], dim=1).repeat(n_modalities_stacked, 1)
def compute_alibi_bias(centers_q, centers_k, num_heads):
d = torch.cdist(centers_q, centers_k, p=2)
slopes = torch.tensor([1.0 / (2 ** (i + 1)) for i in range(num_heads)])
return -slopes.view(-1, 1, 1) * d.unsqueeze(0)
def _expand(bias, B):
return bias.unsqueeze(0).expand(B, -1, -1, -1).reshape(B * bias.size(0), bias.size(1), bias.size(2))
class GSDPatchEncoder(nn.Module):
def __init__(self, in_channels, embed_dim, patch_size):
super().__init__()
self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
self.norm = nn.LayerNorm(embed_dim)
def forward(self, x):
return self.norm(self.proj(x).flatten(2).transpose(1, 2))
class CrossModalLayer(nn.Module):
def __init__(self, embed_dim, num_heads):
super().__init__()
self.self_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
self.cross_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
self.ffn = nn.Sequential(nn.Linear(embed_dim, embed_dim * 2), nn.GELU(), nn.Linear(embed_dim * 2, embed_dim))
self.norm1, self.norm2, self.norm3 = nn.LayerNorm(embed_dim), nn.LayerNorm(embed_dim), nn.LayerNorm(embed_dim)
def forward(self, x, context, alibi_self=None, alibi_cross=None):
B = x.size(0)
x_sa, _ = self.self_attn(x, x, x, attn_mask=None if alibi_self is None else _expand(alibi_self.to(x.dtype), B))
x = self.norm1(x + x_sa)
x_ca, _ = self.cross_attn(x, context, context,
attn_mask=None if alibi_cross is None else _expand(alibi_cross.to(x.dtype), B))
x = self.norm2(x + x_ca)
return self.norm3(x + self.ffn(x))
class ConvBlock(nn.Module):
def __init__(self, in_c, out_c):
super().__init__()
self.block = nn.Sequential(nn.Conv2d(in_c, out_c, 3, padding=1), nn.BatchNorm2d(out_c), nn.GELU(),
nn.Conv2d(out_c, out_c, 3, padding=1), nn.BatchNorm2d(out_c), nn.GELU())
def forward(self, x): return self.block(x)
class UNetDecoder(nn.Module):
def __init__(self, embed_dim, patch_size_8m):
super().__init__()
self.grid = 32 // patch_size_8m
self.up_blocks = nn.ModuleList([ConvBlock(embed_dim, 32)] if patch_size_8m == 1 else
[ConvBlock(embed_dim, 64), nn.ConvTranspose2d(64, 32, 2, stride=2), ConvBlock(32, 32)])
def forward(self, tokens_8m):
B, N, E = tokens_8m.shape; n_per = self.grid * self.grid
x = tokens_8m.view(B, N // n_per, n_per, E).mean(dim=1) # average co-registered fine modalities
x = x.transpose(1, 2).reshape(B, E, self.grid, self.grid)
for blk in self.up_blocks: x = blk(x)
return x
class ScaledTaskHead(nn.Module):
def __init__(self, in_channels, ceiling):
super().__init__()
self.conv = nn.Conv2d(in_channels, 1, kernel_size=1); self.ceiling = ceiling
def forward(self, x): return torch.sigmoid(self.conv(x).squeeze(1)) * self.ceiling
class DenseForestViT(nn.Module):
def __init__(self, bands_per_cov, embed_dim=96, num_layers=3, num_heads=4,
patch_size_8m=PATCH_SIZE_8M_DEFAULT, patch_size_24m=PATCH_SIZE_24M,
coarse_mods=V12_COARSE, centred=False, cross_alibi=False, verbose=True):
super().__init__()
assert 32 % patch_size_8m == 0, 'patch_size_8m must divide 32'
coarse_mods = tuple(coarse_mods)
if coarse_mods != V12_COARSE: assert 32 % patch_size_24m == 0, 'patch_size_24m must divide 32'
self.cfg = dict(embed_dim=embed_dim, num_layers=num_layers, num_heads=num_heads, patch_size_8m=patch_size_8m,
patch_size_24m=patch_size_24m, coarse_mods=list(coarse_mods), centred=centred, cross_alibi=cross_alibi)
self.num_layers = num_layers
fine = [m for m in ALL_MODS if m not in coarse_mods and m in bands_per_cov]
coarse = [m for m in ALL_MODS if m in coarse_mods and m in bands_per_cov]
self.encoders_8m = nn.ModuleDict({m: GSDPatchEncoder(bands_per_cov[m], embed_dim, patch_size_8m) for m in fine})
self.encoders_24m = nn.ModuleDict({m: GSDPatchEncoder(bands_per_cov[m], embed_dim, patch_size_24m) for m in coarse})
self.layers_8m = nn.ModuleList([CrossModalLayer(embed_dim, num_heads) for _ in range(num_layers)])
self.layers_24m = nn.ModuleList([CrossModalLayer(embed_dim, num_heads) for _ in range(num_layers)])
c8 = get_patch_centers(GSD_8M, patch_size_8m, len(fine), centred)
self.register_buffer('alibi_8m', compute_alibi_bias(c8, c8, num_heads)) # persistent (v_1_2 key)
if coarse:
c24 = get_patch_centers(GSD_24M, patch_size_24m, len(coarse), centred)
self.register_buffer('alibi_24m', compute_alibi_bias(c24, c24, num_heads))
if cross_alibi: # new in v_1_3: not saved in checkpoints (rebuilt from cfg)
self.register_buffer('alibi_x8', compute_alibi_bias(c8, c24, num_heads), persistent=False)
self.register_buffer('alibi_x24', compute_alibi_bias(c24, c8, num_heads), persistent=False)
self.decoder = UNetDecoder(embed_dim, patch_size_8m)
self.head_rh = ScaledTaskHead(32, TASK_CEILINGS['rh'])
self.head_pai = ScaledTaskHead(32, TASK_CEILINGS['pai'])
self.head_fhd = ScaledTaskHead(32, TASK_CEILINGS['fhd'])
self.wave_head = nn.Linear(embed_dim, WAVE_LEN)
if verbose:
n = 32 // patch_size_8m; nc = 32 // patch_size_24m
print(f'DenseForestViT v_1_3 fine={fine} ({len(fine)}x{n * n} tokens) coarse={coarse} '
f'({len(coarse)}x{nc * nc} tokens, patch {patch_size_24m}) centred={centred} cross_alibi={cross_alibi} '
f'params={sum(p.numel() for p in self.parameters()):,}')
def forward(self, batch_dict, return_embeddings=False, return_waveform=True):
all_8m = torch.cat([enc(batch_dict[m]) for m, enc in self.encoders_8m.items() if m in batch_dict], dim=1)
t24 = [enc(batch_dict[m]) for m, enc in self.encoders_24m.items() if m in batch_dict]
all_24m = torch.cat(t24, dim=1) if t24 else all_8m
xa = self.cfg['cross_alibi'] and bool(t24)
ctx8, ctx24 = all_24m, all_8m
for i in range(self.num_layers):
all_8m = self.layers_8m[i](all_8m, ctx8, alibi_self=self.alibi_8m if i == 0 else None,
alibi_cross=self.alibi_x8 if xa else None)
if t24:
all_24m = self.layers_24m[i](all_24m, ctx24, alibi_self=self.alibi_24m if i == 0 else None,
alibi_cross=self.alibi_x24 if xa else None)
ctx8, ctx24 = all_24m, all_8m
if return_embeddings:
return {'embeddings': all_8m.mean(dim=1)}
d = self.decoder(all_8m)
out = {'rh': self.head_rh(d), 'pai': self.head_pai(d), 'fhd': self.head_fhd(d)}
if return_waveform:
out['waveform_pred'] = self.wave_head(all_8m.mean(dim=1))
return out
if __name__ == '__main__':
import sys
NB = {'dem': 2, 'hls': 6, 'landsat': 5, 'landsatidx': 6, 's1': 4, 'tcap': 6, 's2': 5, 's2idx': 7}
torch.manual_seed(0)
x = {m: torch.rand(1, b, 32, 32) for m, b in NB.items()}
for name, kw in PRESETS.items():
m = DenseForestViT(NB, **kw).eval()
with torch.no_grad(): o = m(x, return_waveform=True)
print(f' {name}: rh{tuple(o["rh"].shape)} wave{tuple(o["waveform_pred"].shape)} OK')
if len(sys.argv) > 1: # A0 must load the v_1_2 checkpoint strictly and match the v_1_2 model output
sd = torch.load(sys.argv[1], map_location='cpu', weights_only=False)
a0 = DenseForestViT(NB, **PRESETS['A0']).eval(); a0.load_state_dict(sd, strict=True)
sys.path.insert(0, '/nas/rstor/tmayer/gedi/scripts/Pipeline_1_2_3_v_1_2_aux_waveform/Stage_1_Dense')
from model_dense_vit_v4_patchsweep import DenseForestViT as V12
v12 = V12(NB, embed_dim=96, num_layers=3, num_heads=4, patch_size_8m=1).eval(); v12.load_state_dict(sd, strict=True)
with torch.no_grad(): d = (a0(x, return_waveform=False)['rh'] - v12(x, return_waveform=False)['rh']).abs().max().item()
print(f' A0 vs v_1_2 (same checkpoint): max |diff| RH = {d:.2e} {"PASS" if d < 1e-5 else "FAIL"}')