guychuk commited on
Commit
202b43e
·
verified ·
1 Parent(s): cde67fc

v8: multi-airport pretrain (comma-separated airports)

Browse files
Files changed (1) hide show
  1. pretrain_v8.py +616 -0
pretrain_v8.py ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = ["torch>=2.1","numpy","pandas","scikit-learn","huggingface-hub","trackio"]
4
+ # ///
5
+ """
6
+ Flight-JEPA v7 — past-track masked JEPA pretraining.
7
+
8
+ Adapted from Forecast-MAE (arxiv:2308.09882) and I-JEPA (arxiv:2301.08243):
9
+ mask contiguous blocks of *past-track* patches and train an encoder +
10
+ EMA target + predictor to reconstruct masked-patch latents from visible
11
+ context. Encoder weights then transfer to v6 fine-tuning.
12
+
13
+ Key differences from v6's JEPA aux:
14
+ - Pretraining-only objective (no forecasting head, no Δ conditioning).
15
+ - Masks past-track patches, not future segments.
16
+ - Trains on the same RKSIa data — this is small-scale demo, not OpenSky-scale.
17
+ - Output: a `pretrained_encoder.pt` checkpoint loadable by v6 fine-tune.
18
+
19
+ Decision criterion at fine-tune time:
20
+ - Significant FDE improvement at ≥30% past-track dropout (test-time).
21
+ - No regression at 0% dropout.
22
+ """
23
+ from __future__ import annotations
24
+ import argparse
25
+ import copy
26
+ import json
27
+ import math
28
+ import os
29
+ import shutil
30
+ import time
31
+
32
+ import numpy as np
33
+ import pandas as pd
34
+ import torch
35
+ import torch.nn as nn
36
+ import torch.nn.functional as F
37
+ from torch.utils.data import Dataset, DataLoader
38
+
39
+ try:
40
+ import trackio
41
+ HAS_TRACKIO = True
42
+ except ImportError:
43
+ HAS_TRACKIO = False
44
+
45
+
46
+ # ============================================================================
47
+ # DATA UTILITIES (inlined from train_v2_prod.py for self-contained job)
48
+ # ============================================================================
49
+
50
+ def load_atfm(dset_name, mode, path):
51
+ variables = ["X", "Y", "Z"]
52
+ data, labels = [], None
53
+ for var in variables:
54
+ df = pd.read_csv(os.path.join(path, f"{dset_name}_{mode}_{var}.tsv"),
55
+ sep="\t", header=None, na_values="NaN")
56
+ if labels is None:
57
+ labels = df.values[:, 0]
58
+ data.append(df.values[:, 1:])
59
+ return np.stack(data, axis=-1), labels.astype(int)
60
+
61
+
62
+ def compute_features(traj_xyz: np.ndarray) -> np.ndarray:
63
+ if traj_xyz.shape[0] < 2:
64
+ T = traj_xyz.shape[0]
65
+ return np.concatenate([
66
+ traj_xyz, np.zeros((T, 3), dtype=traj_xyz.dtype),
67
+ np.zeros((T, 3), dtype=traj_xyz.dtype)
68
+ ], axis=1)
69
+ x, y, z = traj_xyz[:, 0], traj_xyz[:, 1], traj_xyz[:, 2]
70
+ diff = np.diff(traj_xyz, axis=0)
71
+ norms = np.maximum(np.linalg.norm(diff, axis=1, keepdims=True), 1e-8)
72
+ u = diff / norms
73
+ u = np.vstack([u, u[-1:]])
74
+ r = np.sqrt(x ** 2 + y ** 2)
75
+ theta = np.arctan2(y, x)
76
+ return np.column_stack([
77
+ traj_xyz, u,
78
+ r[:, None], np.sin(theta)[:, None], np.cos(theta)[:, None]
79
+ ]).astype(np.float32)
80
+
81
+
82
+ def ensure_data(airport: str, data_dir: str = "data"):
83
+ target = os.path.join(data_dir, airport)
84
+ if os.path.isdir(target) and any(f.endswith(".tsv") for f in os.listdir(target)):
85
+ return target
86
+ print(f"[data] downloading {airport} from HF ...")
87
+ from huggingface_hub import snapshot_download
88
+ snap = snapshot_download(
89
+ "petchthwr/ATFMTraj",
90
+ repo_type="dataset",
91
+ allow_patterns=[f"{airport}/*"],
92
+ )
93
+ os.makedirs(data_dir, exist_ok=True)
94
+ src = os.path.join(snap, airport)
95
+ if not os.path.isdir(target):
96
+ shutil.copytree(src, target)
97
+ return target
98
+
99
+
100
+ # ============================================================================
101
+ # DATASET — full past-track windows (no Δ / target)
102
+ # ============================================================================
103
+
104
+ class PastTrackDataset(Dataset):
105
+ """
106
+ Yields fixed-length past-track windows for masked-prediction pretraining.
107
+
108
+ Per __getitem__:
109
+ - sample a random window of length past_len from a trajectory
110
+ - return its 9-dim features padded to past_max
111
+ """
112
+
113
+ def __init__(self, airport, mode, data_dir,
114
+ past_max=256, past_min=128,
115
+ seed=0, epoch_multiplier=4):
116
+ # `airport` may be a single string ("RKSIa") or comma-separated
117
+ # ("RKSId,ESSA,LSZH") for v8 multi-airport pretraining. We union
118
+ # the trajectories without preserving airport-id (pretraining only
119
+ # uses features, not labels or airport tokens).
120
+ airports = [a.strip() for a in airport.split(",")]
121
+ all_positions = []
122
+ for ap in airports:
123
+ ensure_data(ap, data_dir)
124
+ ap_dir = os.path.join(data_dir, ap)
125
+ raw, _ = load_atfm(ap, mode, ap_dir)
126
+ lengths = np.array(
127
+ [int(np.sum(~np.isnan(raw[i, :, 0]))) for i in range(raw.shape[0])],
128
+ dtype=np.int64,
129
+ )
130
+ keep = lengths >= past_min + 1
131
+ raw = raw[keep]
132
+ lengths = lengths[keep]
133
+ n_kept = 0
134
+ for i in range(raw.shape[0]):
135
+ L = int(lengths[i])
136
+ all_positions.append(
137
+ np.nan_to_num(raw[i, :L], nan=0.0).astype(np.float32)
138
+ )
139
+ n_kept += 1
140
+ print(f"[data] {ap}/{mode}: {n_kept} trajectories")
141
+
142
+ self.past_max = past_max
143
+ self.past_min = past_min
144
+ self.epoch_multiplier = epoch_multiplier
145
+ self.rng_seed = seed
146
+ self.positions = all_positions
147
+ self.n_traj = len(self.positions)
148
+ if len(airports) > 1:
149
+ print(f"[data] union total: {self.n_traj} trajectories from "
150
+ f"{airports}")
151
+
152
+ def __len__(self):
153
+ return self.n_traj * self.epoch_multiplier
154
+
155
+ def __getitem__(self, idx):
156
+ traj_idx = idx % self.n_traj
157
+ rng = np.random.default_rng(self.rng_seed + idx * 9173)
158
+ positions = self.positions[traj_idx]
159
+ L = positions.shape[0]
160
+ past_len = min(self.past_max, L)
161
+ start = int(rng.integers(0, max(1, L - past_len + 1)))
162
+ window = positions[start:start + past_len]
163
+ feats = compute_features(window)
164
+ T = feats.shape[0]
165
+ feat_pad = np.zeros((self.past_max, 9), dtype=np.float32)
166
+ feat_pad[:T] = feats
167
+ return {
168
+ "features": torch.from_numpy(feat_pad),
169
+ "length": torch.tensor(T, dtype=torch.long),
170
+ }
171
+
172
+
173
+ # ============================================================================
174
+ # MODEL — encoder + EMA target + predictor (no decoder, no Δ)
175
+ # ============================================================================
176
+
177
+ class LearnablePosEnc(nn.Module):
178
+ def __init__(self, max_len, d_model):
179
+ super().__init__()
180
+ self.pe = nn.Parameter(torch.randn(1, max_len, d_model) * 0.02)
181
+ def forward(self, x):
182
+ return x + self.pe[:, :x.size(1)]
183
+
184
+
185
+ class PatchTokenizer(nn.Module):
186
+ def __init__(self, in_channels=9, d_model=256, patch_size=8, max_patches=64):
187
+ super().__init__()
188
+ self.patch_size = patch_size
189
+ self.d_model = d_model
190
+ self.embed = nn.Sequential(
191
+ nn.Conv1d(in_channels, d_model // 2, 5, padding=2),
192
+ nn.GELU(),
193
+ nn.Conv1d(d_model // 2, d_model, 3, padding=1),
194
+ nn.GELU(),
195
+ )
196
+ self.pos_enc = LearnablePosEnc(max_patches, d_model)
197
+ self.norm = nn.LayerNorm(d_model)
198
+
199
+ def forward(self, features, lengths):
200
+ B, T, C = features.shape
201
+ h = self.embed(features.transpose(1, 2))
202
+ N = max(1, T // self.patch_size)
203
+ h = h[:, :, :N * self.patch_size]
204
+ h = h.reshape(B, self.d_model, N, self.patch_size).mean(-1)
205
+ h = h.transpose(1, 2)
206
+ h = self.norm(self.pos_enc(h))
207
+ patch_lengths = (lengths.float() / self.patch_size).clamp(min=1).long()
208
+ patch_lengths = patch_lengths.clamp(max=N)
209
+ return h, patch_lengths
210
+
211
+
212
+ class CausalEncoder(nn.Module):
213
+ def __init__(self, d_model=256, n_heads=8, n_layers=4, d_ff=1024, dropout=0.1):
214
+ super().__init__()
215
+ layer = nn.TransformerEncoderLayer(
216
+ d_model=d_model, nhead=n_heads, dim_feedforward=d_ff,
217
+ dropout=dropout, activation="gelu", batch_first=True,
218
+ norm_first=True,
219
+ )
220
+ self.tf = nn.TransformerEncoder(layer, num_layers=n_layers)
221
+ self.norm = nn.LayerNorm(d_model)
222
+
223
+ def forward(self, x, key_padding_mask, attn_mask=None):
224
+ N = x.size(1)
225
+ if attn_mask is None:
226
+ # Default: causal. For pretraining we may pass full bidirectional.
227
+ attn_mask = torch.triu(
228
+ torch.ones(N, N, dtype=torch.bool, device=x.device), diagonal=1
229
+ )
230
+ return self.norm(
231
+ self.tf(x, mask=attn_mask, src_key_padding_mask=key_padding_mask)
232
+ )
233
+
234
+
235
+ class JEPAPredictor(nn.Module):
236
+ """Predict target patch latents from context patch latents.
237
+ Adds a query token per masked position via positional embedding."""
238
+ def __init__(self, d_model=256, pred_dim=128, max_patches=64, dropout=0.1):
239
+ super().__init__()
240
+ self.proj_in = nn.Linear(d_model, pred_dim)
241
+ self.target_pe = nn.Parameter(torch.randn(1, max_patches, pred_dim) * 0.02)
242
+ layer = nn.TransformerEncoderLayer(
243
+ d_model=pred_dim, nhead=4, dim_feedforward=pred_dim * 2,
244
+ dropout=dropout, activation="gelu", batch_first=True, norm_first=True,
245
+ )
246
+ self.tf = nn.TransformerEncoder(layer, num_layers=2)
247
+ self.proj_out = nn.Linear(pred_dim, d_model)
248
+ self.norm = nn.LayerNorm(d_model)
249
+
250
+ def forward(self, ctx_latents, ctx_idx, tgt_idx):
251
+ """
252
+ ctx_latents: (B, N_ctx, d_model)
253
+ ctx_idx: (B, N_ctx) original positions of context patches
254
+ tgt_idx: (B, N_tgt) original positions of target patches
255
+ returns: (B, N_tgt, d_model) predicted target latents
256
+ """
257
+ B = ctx_latents.size(0)
258
+ d_pred = self.target_pe.size(-1)
259
+ # Project context to pred_dim and add target positional embeddings
260
+ ctx_p = self.proj_in(ctx_latents) # (B, N_ctx, d_pred)
261
+ # Gather target PEs at the masked positions
262
+ tgt_pe = self.target_pe.expand(B, -1, -1) # (B, max_patches, d_pred)
263
+ tgt_idx_expanded = tgt_idx.unsqueeze(-1).expand(-1, -1, d_pred)
264
+ tgt_q = torch.gather(tgt_pe, 1, tgt_idx_expanded) # (B, N_tgt, d_pred)
265
+ # Concatenate and run transformer
266
+ h = torch.cat([ctx_p, tgt_q], dim=1) # (B, N_ctx+N_tgt, d_pred)
267
+ h = self.tf(h)
268
+ # Take only the target-position outputs
269
+ N_ctx = ctx_p.size(1)
270
+ h_tgt = h[:, N_ctx:]
271
+ return self.norm(self.proj_out(h_tgt))
272
+
273
+
274
+ def make_block_mask(B: int, N: int, mask_ratio: float, rng: np.random.Generator,
275
+ device, min_visible: int = 4):
276
+ """
277
+ Sample a contiguous block mask per batch element.
278
+ Returns:
279
+ ctx_idx: list of LongTensors (variable length per sample)
280
+ tgt_idx: list of LongTensors
281
+ For batched processing we'll right-pad and provide separate masks.
282
+ """
283
+ ctx_idxs = []
284
+ tgt_idxs = []
285
+ for _ in range(B):
286
+ n_mask = max(1, int(round(N * mask_ratio)))
287
+ n_mask = min(n_mask, N - min_visible)
288
+ # Random contiguous block start
289
+ if N - n_mask <= 0:
290
+ start = 0
291
+ n_mask = N - min_visible
292
+ else:
293
+ start = int(rng.integers(0, N - n_mask + 1))
294
+ all_idx = np.arange(N)
295
+ tgt_mask = (all_idx >= start) & (all_idx < start + n_mask)
296
+ ctx_idxs.append(torch.tensor(all_idx[~tgt_mask], dtype=torch.long, device=device))
297
+ tgt_idxs.append(torch.tensor(all_idx[tgt_mask], dtype=torch.long, device=device))
298
+ return ctx_idxs, tgt_idxs
299
+
300
+
301
+ def gather_by_indices(x: torch.Tensor, idx_list: list[torch.Tensor], pad_value=0.0):
302
+ """x: (B, N, D). idx_list: per-batch index tensors. Returns (B, N_max, D) padded
303
+ plus a (B, N_max) mask of which entries are real."""
304
+ B = x.size(0); D = x.size(-1)
305
+ N_max = max((idx.numel() for idx in idx_list), default=1)
306
+ out = torch.full((B, N_max, D), pad_value, device=x.device, dtype=x.dtype)
307
+ mask = torch.zeros((B, N_max), dtype=torch.bool, device=x.device)
308
+ for b in range(B):
309
+ idx = idx_list[b]
310
+ n = idx.numel()
311
+ if n > 0:
312
+ out[b, :n] = x[b, idx]
313
+ mask[b, :n] = True
314
+ return out, mask
315
+
316
+
317
+ def gather_indices_only(idx_list: list[torch.Tensor], device):
318
+ """Pack a list of LongTensors into (B, N_max) padded with zeros."""
319
+ B = len(idx_list)
320
+ N_max = max((idx.numel() for idx in idx_list), default=1)
321
+ out = torch.zeros((B, N_max), dtype=torch.long, device=device)
322
+ mask = torch.zeros((B, N_max), dtype=torch.bool, device=device)
323
+ for b in range(B):
324
+ idx = idx_list[b]
325
+ n = idx.numel()
326
+ if n > 0:
327
+ out[b, :n] = idx
328
+ mask[b, :n] = True
329
+ return out, mask
330
+
331
+
332
+ # ============================================================================
333
+ # PRETRAIN MODULE
334
+ # ============================================================================
335
+
336
+ class FlightJEPAPretrain(nn.Module):
337
+ def __init__(self, cfg):
338
+ super().__init__()
339
+ self.cfg = cfg
340
+ d = cfg.get("d_model", 256)
341
+ h_ = cfg.get("n_heads", 8)
342
+ n_l = cfg.get("n_layers", 4)
343
+ d_ff = cfg.get("d_ff", 1024)
344
+ dr = cfg.get("dropout", 0.1)
345
+ ps = cfg.get("patch_size", 8)
346
+ past_max = cfg.get("past_max", 256)
347
+ max_patches = past_max // ps
348
+ pred_dim = cfg.get("pred_dim", 128)
349
+ self.ema_decay = cfg.get("ema_decay", 0.998)
350
+ self.max_patches = max_patches
351
+
352
+ self.tokenizer = PatchTokenizer(9, d, ps, max_patches)
353
+ self.encoder = CausalEncoder(d, h_, n_l, d_ff, dr)
354
+ self.predictor = JEPAPredictor(d, pred_dim, max_patches, dr)
355
+
356
+ self.target_tokenizer = copy.deepcopy(self.tokenizer)
357
+ self.target_encoder = copy.deepcopy(self.encoder)
358
+ for p in self.target_tokenizer.parameters():
359
+ p.requires_grad = False
360
+ for p in self.target_encoder.parameters():
361
+ p.requires_grad = False
362
+
363
+ @torch.no_grad()
364
+ def update_ema(self):
365
+ m = self.ema_decay
366
+ for online, target in [(self.tokenizer, self.target_tokenizer),
367
+ (self.encoder, self.target_encoder)]:
368
+ for po, pt in zip(online.parameters(), target.parameters()):
369
+ pt.data.mul_(m).add_(po.data, alpha=1.0 - m)
370
+
371
+ def forward(self, features, lengths, mask_ratio: float, rng: np.random.Generator):
372
+ """
373
+ Mask a contiguous block of patches per sample. Encode visible context.
374
+ Predict masked-patch latents. Compare to EMA target encoder over the
375
+ full sequence at masked positions.
376
+
377
+ Pretraining uses *bidirectional* attention (no causal mask) — at
378
+ fine-tune time we restore the causal mask. This gives the encoder
379
+ more signal during pretraining; the encoder's transformer layers are
380
+ not architecturally causal, only the mask passed in changes the mode.
381
+ """
382
+ B = features.size(0)
383
+ device = features.device
384
+
385
+ # Tokenize for online (will be partially masked) and target (full).
386
+ patches_full, patch_lens = self.tokenizer(features, lengths)
387
+ N = patches_full.size(1)
388
+
389
+ # Padding mask (token absent because past sequence shorter than N*patch).
390
+ pad_mask = (torch.arange(N, device=device).unsqueeze(0)
391
+ >= patch_lens.unsqueeze(1)) # True where padded
392
+
393
+ # Sample contiguous masks per sample (drawing only from valid patches).
394
+ ctx_idx_list, tgt_idx_list = [], []
395
+ for b in range(B):
396
+ n_valid = int(patch_lens[b].item())
397
+ if n_valid < 8: # too short to mask meaningfully
398
+ ctx_idx_list.append(torch.arange(n_valid, device=device))
399
+ tgt_idx_list.append(torch.tensor([], dtype=torch.long, device=device))
400
+ continue
401
+ n_mask = max(2, int(round(n_valid * mask_ratio)))
402
+ n_mask = min(n_mask, n_valid - 4) # keep at least 4 visible
403
+ start = int(rng.integers(0, n_valid - n_mask + 1))
404
+ all_idx = torch.arange(n_valid, device=device)
405
+ tgt_mask = (all_idx >= start) & (all_idx < start + n_mask)
406
+ ctx_idx_list.append(all_idx[~tgt_mask])
407
+ tgt_idx_list.append(all_idx[tgt_mask])
408
+
409
+ # Skip if any batch element produced no targets (e.g., very short sequences)
410
+ n_targets = sum(int(t.numel()) for t in tgt_idx_list)
411
+ if n_targets == 0:
412
+ return torch.tensor(0.0, device=device, requires_grad=True)
413
+
414
+ # Pack context indices and gather context tokens. We pass through
415
+ # the same encoder with a key_padding_mask that hides the masked
416
+ # positions plus the original padding.
417
+ # Easier: re-run encoder on a *new* tensor consisting only of context
418
+ # tokens with bidirectional attention.
419
+ N_ctx_max = max((idx.numel() for idx in ctx_idx_list), default=1)
420
+ ctx_tokens = torch.zeros((B, N_ctx_max, patches_full.size(-1)),
421
+ device=device, dtype=patches_full.dtype)
422
+ ctx_kpm = torch.ones((B, N_ctx_max), dtype=torch.bool, device=device) # True=pad
423
+ for b in range(B):
424
+ idx = ctx_idx_list[b]
425
+ n = idx.numel()
426
+ if n > 0:
427
+ ctx_tokens[b, :n] = patches_full[b, idx]
428
+ ctx_kpm[b, :n] = False
429
+
430
+ # Bidirectional attention for pretraining (full mask).
431
+ bi_mask = torch.zeros((N_ctx_max, N_ctx_max), dtype=torch.bool, device=device)
432
+ ctx_encoded = self.encoder(ctx_tokens, key_padding_mask=ctx_kpm,
433
+ attn_mask=bi_mask)
434
+
435
+ # Build target-index packed tensors
436
+ tgt_idx_packed, tgt_idx_mask = gather_indices_only(tgt_idx_list, device)
437
+ # Build dummy "context indices in original layout" — we need to tell
438
+ # the predictor where the context tokens live (their original patch
439
+ # positions). Add positional info to ctx through a side embedding —
440
+ # we can use the same target_pe table for context too.
441
+ # Simpler: encode their original position as a query-like input by
442
+ # *pre-adding* a positional token to ctx encoded representation.
443
+ # The predictor only needs target PEs — context already carries pos
444
+ # info via the patch tokenizer's pos_enc, so we don't need to add
445
+ # context indices.
446
+
447
+ # Predict target latents.
448
+ pred = self.predictor(ctx_encoded, ctx_idx=None, tgt_idx=tgt_idx_packed)
449
+ # Pad target predictions to N_tgt_max already done by gather_indices_only
450
+
451
+ # Targets: run the EMA target encoder on the *full* sequence
452
+ # (causal mask, like fine-tune time) and gather at target positions.
453
+ with torch.no_grad():
454
+ tgt_patches, _ = self.target_tokenizer(features, lengths)
455
+ tgt_encoded = self.target_encoder(tgt_patches, key_padding_mask=pad_mask)
456
+ tgt_latents, _ = gather_by_indices(tgt_encoded, tgt_idx_list)
457
+
458
+ # L1 loss in latent space, masked over valid targets
459
+ loss_per = F.l1_loss(pred, tgt_latents, reduction="none").mean(-1) # (B, N_tgt_max)
460
+ loss = (loss_per * tgt_idx_mask.float()).sum() / tgt_idx_mask.sum().clamp(min=1)
461
+ return loss
462
+
463
+
464
+ # ============================================================================
465
+ # TRAIN LOOP
466
+ # ============================================================================
467
+
468
+ def device_pick(arg=None):
469
+ if arg:
470
+ return arg
471
+ if torch.cuda.is_available():
472
+ return "cuda"
473
+ if torch.backends.mps.is_available():
474
+ return "mps"
475
+ return "cpu"
476
+
477
+
478
+ def train_one_epoch(model, loader, optimizer, device, mask_ratio_lo, mask_ratio_hi,
479
+ log_every=50, grad_clip=1.0, rng=None):
480
+ model.train()
481
+ sums = {"loss": 0.0, "n": 0}
482
+ t0 = time.time()
483
+ rng = rng or np.random.default_rng()
484
+ n_batches = len(loader) if hasattr(loader, "__len__") else 0
485
+ for bi, batch in enumerate(loader):
486
+ feats = batch["features"].to(device)
487
+ lens = batch["length"].to(device)
488
+ mr = float(rng.uniform(mask_ratio_lo, mask_ratio_hi))
489
+ loss = model(feats, lens, mask_ratio=mr, rng=rng)
490
+ optimizer.zero_grad()
491
+ loss.backward()
492
+ torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
493
+ optimizer.step()
494
+ model.update_ema()
495
+ bs = feats.size(0)
496
+ sums["loss"] += loss.item() * bs
497
+ sums["n"] += bs
498
+ if (bi + 1) % log_every == 0 or bi == 0:
499
+ dt = time.time() - t0
500
+ print(f" [batch {bi+1}/{n_batches}] {dt:.1f}s elapsed, "
501
+ f"mr={mr:.2f}, loss={loss.item():.4f}", flush=True)
502
+ n = max(sums["n"], 1)
503
+ return {"loss": sums["loss"] / n}
504
+
505
+
506
+ def main():
507
+ p = argparse.ArgumentParser()
508
+ p.add_argument("--airport", default="RKSIa")
509
+ p.add_argument("--data-dir", default="data")
510
+ p.add_argument("--tag", default="v7-pretrain")
511
+ p.add_argument("--out-dir", default="runs")
512
+ p.add_argument("--epochs", type=int, default=60)
513
+ p.add_argument("--batch-size", type=int, default=64)
514
+ p.add_argument("--lr", type=float, default=1.5e-4)
515
+ p.add_argument("--weight-decay", type=float, default=1e-4)
516
+ p.add_argument("--past-max", type=int, default=256)
517
+ p.add_argument("--past-min", type=int, default=128)
518
+ p.add_argument("--epoch-multiplier", type=int, default=2)
519
+ p.add_argument("--ema-decay", type=float, default=0.998)
520
+ p.add_argument("--d-model", type=int, default=256)
521
+ p.add_argument("--n-layers", type=int, default=4)
522
+ p.add_argument("--n-heads", type=int, default=8)
523
+ p.add_argument("--patch-size", type=int, default=8)
524
+ p.add_argument("--pred-dim", type=int, default=128)
525
+ p.add_argument("--mask-ratio-lo", type=float, default=0.3)
526
+ p.add_argument("--mask-ratio-hi", type=float, default=0.7)
527
+ p.add_argument("--seed", type=int, default=0)
528
+ p.add_argument("--num-workers", type=int, default=2)
529
+ p.add_argument("--push-to-hub", action="store_true")
530
+ p.add_argument("--hub-model-id", default=None)
531
+ p.add_argument("--trackio-name", default=None)
532
+ args = p.parse_args()
533
+
534
+ torch.manual_seed(args.seed)
535
+ np.random.seed(args.seed)
536
+ rng = np.random.default_rng(args.seed)
537
+
538
+ device = device_pick()
539
+ print(f"[v7-pretrain] device={device} tag={args.tag}", flush=True)
540
+ if device == "cuda":
541
+ print(f"[v7-pretrain] cuda: {torch.cuda.get_device_name(0)} "
542
+ f"vram={torch.cuda.get_device_properties(0).total_memory/1e9:.1f}GB",
543
+ flush=True)
544
+ if HAS_TRACKIO and args.trackio_name:
545
+ trackio.init(project="flight-jepa-v7-pretrain",
546
+ name=args.trackio_name, config=vars(args))
547
+
548
+ train_ds = PastTrackDataset(
549
+ airport=args.airport, mode="TRAIN", data_dir=args.data_dir,
550
+ past_max=args.past_max, past_min=args.past_min,
551
+ seed=args.seed, epoch_multiplier=args.epoch_multiplier,
552
+ )
553
+ train_dl = DataLoader(train_ds, batch_size=args.batch_size, shuffle=True,
554
+ num_workers=args.num_workers, pin_memory=True,
555
+ drop_last=True)
556
+
557
+ cfg = {
558
+ "d_model": args.d_model, "n_heads": args.n_heads,
559
+ "n_layers": args.n_layers, "d_ff": args.d_model * 4,
560
+ "dropout": 0.1, "patch_size": args.patch_size,
561
+ "past_max": args.past_max, "ema_decay": args.ema_decay,
562
+ "pred_dim": args.pred_dim,
563
+ }
564
+ model = FlightJEPAPretrain(cfg).to(device)
565
+ n_params = sum(p.numel() for p in model.parameters())
566
+ print(f"[v7-pretrain] params={n_params/1e6:.2f}M")
567
+
568
+ optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr,
569
+ weight_decay=args.weight_decay)
570
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
571
+
572
+ os.makedirs(args.out_dir, exist_ok=True)
573
+ history = []
574
+ for epoch in range(args.epochs):
575
+ t0 = time.time()
576
+ stats = train_one_epoch(
577
+ model, train_dl, optimizer, device,
578
+ mask_ratio_lo=args.mask_ratio_lo,
579
+ mask_ratio_hi=args.mask_ratio_hi,
580
+ rng=rng,
581
+ )
582
+ scheduler.step()
583
+ elapsed = time.time() - t0
584
+ print(f"[v7-pretrain] ep {epoch+1:03d} loss={stats['loss']:.4f} | {elapsed:.0f}s",
585
+ flush=True)
586
+ history.append({"epoch": epoch + 1, "loss": stats["loss"], "elapsed_s": elapsed})
587
+ if HAS_TRACKIO and args.trackio_name:
588
+ trackio.log({"pretrain/loss": stats["loss"]}, step=epoch + 1)
589
+
590
+ out_path = os.path.join(args.out_dir, f"{args.tag}.pt")
591
+ torch.save({
592
+ "encoder_state_dict": model.encoder.state_dict(),
593
+ "tokenizer_state_dict": model.tokenizer.state_dict(),
594
+ "config": cfg, "args": vars(args),
595
+ "history": history,
596
+ }, out_path)
597
+ print(f"[v7-pretrain] saved {out_path}")
598
+
599
+ if args.push_to_hub and args.hub_model_id:
600
+ try:
601
+ from huggingface_hub import HfApi
602
+ api = HfApi()
603
+ api.create_repo(args.hub_model_id, exist_ok=True)
604
+ api.upload_file(path_or_fileobj=out_path,
605
+ path_in_repo=f"{args.tag}.pt",
606
+ repo_id=args.hub_model_id)
607
+ print(f"[v7-pretrain] uploaded to {args.hub_model_id}")
608
+ except Exception as e:
609
+ print(f"[v7-pretrain] hub upload failed: {e}")
610
+
611
+ if HAS_TRACKIO and args.trackio_name:
612
+ trackio.finish()
613
+
614
+
615
+ if __name__ == "__main__":
616
+ main()