Add Trackformer 1.2 Python inference API
Browse files
README.md
CHANGED
|
@@ -120,9 +120,45 @@ the benchmark.
|
|
| 120 |
- `manifest.json` with the input boundary, outputs, splits, and metrics.
|
| 121 |
|
| 122 |
GGUF is not an appropriate format for this CNN/Transformer weather model. The
|
| 123 |
-
matching public inference adapter is
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
## Links
|
| 128 |
|
|
|
|
| 120 |
- `manifest.json` with the input boundary, outputs, splits, and metrics.
|
| 121 |
|
| 122 |
GGUF is not an appropriate format for this CNN/Transformer weather model. The
|
| 123 |
+
matching public inference adapter is included as `trackformer_1_2.py`.
|
| 124 |
+
|
| 125 |
+
## Python Inference
|
| 126 |
+
|
| 127 |
+
Install the runtime dependencies from the GitHub repository:
|
| 128 |
+
|
| 129 |
+
```bash
|
| 130 |
+
python -m pip install -r requirements.txt
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
Then load the model directly from this repository:
|
| 134 |
+
|
| 135 |
+
```python
|
| 136 |
+
from trackformer_1_2 import Trackformer12, local_position_to_latlon
|
| 137 |
+
|
| 138 |
+
model = Trackformer12.from_pretrained(device="cuda")
|
| 139 |
+
route = model.predict_route(field, context, base_position)
|
| 140 |
+
intensity = model.predict_intensity(causal_features, anchor_structure)
|
| 141 |
+
latitude, longitude = local_position_to_latlon(
|
| 142 |
+
route["position_100km"], issue_latitude, issue_longitude
|
| 143 |
+
)
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
The route inputs are `field [B,6,25,61]`, `context [B,647]`, and
|
| 147 |
+
`base_position [B,20,2]`. The field channels are normalized SLP/500-hPa
|
| 148 |
+
analysis pairs for current, -12 h, and -24 h. The intensity inputs are
|
| 149 |
+
`causal_features [B,1020]` and `anchor_structure [B,20,15]`, with channels
|
| 150 |
+
`vmax, pressure, RMW, R34[4], R50[4], R64[4]`. The optional
|
| 151 |
+
`predict_ocean_structure(...)` method additionally accepts
|
| 152 |
+
`ocean_features [B,66]` and `ocean_available [B]` for the causal OHC/D26/D20
|
| 153 |
+
calibration. See [`trackformer_1_2.py`](trackformer_1_2.py) and
|
| 154 |
+
[`examples/predict_trackformer_1_2.py`](examples/predict_trackformer_1_2.py)
|
| 155 |
+
for the complete checked input contract and `.npz` command-line example.
|
| 156 |
+
|
| 157 |
+
The wrapper does not download raw weather data or official forecast products.
|
| 158 |
+
The feature tensors must be prepared from issue-time/current and earlier data;
|
| 159 |
+
this keeps future-field leakage out of the public inference path. The ocean
|
| 160 |
+
calibration is returned separately from the neural intensity residual and is
|
| 161 |
+
not silently stacked into an unvalidated new model.
|
| 162 |
|
| 163 |
## Links
|
| 164 |
|
__pycache__/trackformer_1_2.cpython-314.pyc
ADDED
|
Binary file (41.5 kB). View file
|
|
|
examples/__pycache__/predict_trackformer_1_2.cpython-314.pyc
ADDED
|
Binary file (4.01 kB). View file
|
|
|
examples/predict_trackformer_1_2.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run the public Trackformer 1.2 API on a causal issue packet.
|
| 3 |
+
|
| 4 |
+
The NPZ must contain either the route group:
|
| 5 |
+
field [B,6,25,61], context [B,647], base_position [B,20,2]
|
| 6 |
+
or the intensity group:
|
| 7 |
+
causal_features [B,1020], anchor_structure [B,20,15]
|
| 8 |
+
|
| 9 |
+
For the optional ocean calibration, also provide ocean_features [B,66] and
|
| 10 |
+
ocean_available [B]. All arrays must be constructed from data available at
|
| 11 |
+
the forecast issue time or earlier. This script never downloads official
|
| 12 |
+
forecast products.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from trackformer_1_2 import Trackformer12, local_position_to_latlon
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main() -> None:
|
| 26 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 27 |
+
parser.add_argument("--input", required=True, type=Path, help="causal issue packet .npz")
|
| 28 |
+
parser.add_argument("--output", required=True, type=Path, help="output .npz")
|
| 29 |
+
parser.add_argument("--model-root", type=Path, help="extracted models/trackformer_1_2 directory")
|
| 30 |
+
parser.add_argument("--device", default=None, help="auto, cpu, mps, or cuda")
|
| 31 |
+
parser.add_argument("--issue-latitude", type=float, help="optional latitude for route conversion")
|
| 32 |
+
parser.add_argument("--issue-longitude", type=float, help="optional longitude for route conversion")
|
| 33 |
+
args = parser.parse_args()
|
| 34 |
+
|
| 35 |
+
with np.load(args.input, allow_pickle=False) as source:
|
| 36 |
+
packet = {key: source[key] for key in source.files}
|
| 37 |
+
model = Trackformer12.from_pretrained(args.model_root, device=None if args.device in (None, "auto") else args.device)
|
| 38 |
+
result = model.predict_issue_packet(packet)
|
| 39 |
+
flat: dict[str, np.ndarray] = {}
|
| 40 |
+
for head, values in result.items():
|
| 41 |
+
for key, value in values.items():
|
| 42 |
+
flat[f"{head}_{key}"] = np.asarray(value)
|
| 43 |
+
if "route" in result and args.issue_latitude is not None and args.issue_longitude is not None:
|
| 44 |
+
latitude, longitude = local_position_to_latlon(result["route"]["position_100km"], args.issue_latitude, args.issue_longitude)
|
| 45 |
+
flat["route_latitude"] = latitude
|
| 46 |
+
flat["route_longitude"] = longitude
|
| 47 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 48 |
+
np.savez_compressed(args.output, **flat)
|
| 49 |
+
print(f"wrote {args.output}")
|
| 50 |
+
print("heads:", ", ".join(result))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
main()
|
requirements.txt
CHANGED
|
@@ -1,3 +1,5 @@
|
|
| 1 |
numpy>=1.26
|
| 2 |
torch>=2.1
|
| 3 |
scipy>=1.11
|
|
|
|
|
|
|
|
|
| 1 |
numpy>=1.26
|
| 2 |
torch>=2.1
|
| 3 |
scipy>=1.11
|
| 4 |
+
joblib>=1.3
|
| 5 |
+
huggingface_hub>=0.24
|
trackformer_1_2.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public Trackformer 1.2 inference API.
|
| 2 |
+
|
| 3 |
+
The release checkpoints are trained on causal issue-time inputs. This module
|
| 4 |
+
does not download or accept JMA/JTWC/ECMWF/GFS/GEFS forecast products. It
|
| 5 |
+
expects the same preprocessed arrays used by the released checkpoints:
|
| 6 |
+
|
| 7 |
+
* route: a six-channel [SLP, 500-hPa height] analysis field for three times,
|
| 8 |
+
a 647-dimensional causal context vector, and a 20-step base route in 100-km
|
| 9 |
+
local displacement units;
|
| 10 |
+
* intensity: the 1,020-dimensional causal feature vector and the frozen
|
| 11 |
+
20-lead physical anchor structure;
|
| 12 |
+
* ocean structure calibration: the 66-dimensional three-time ocean summary,
|
| 13 |
+
the same causal feature vector, and the physical anchor structure.
|
| 14 |
+
|
| 15 |
+
The explicit contracts are intentional. They prevent a convenience wrapper
|
| 16 |
+
from silently substituting a forecast field for an issue-time analysis.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import json
|
| 22 |
+
import math
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Any, Iterable
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn as nn
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
LEADS = 20
|
| 32 |
+
LEAD_HOURS = tuple(range(6, 121, 6))
|
| 33 |
+
STRUCTURE_DIM = 15
|
| 34 |
+
ROUTE_CONTEXT_DIM = 647
|
| 35 |
+
INTENSITY_FEATURE_DIM = 1020
|
| 36 |
+
INTENSITY_INPUT_DIM = 1320
|
| 37 |
+
OCEAN_FEATURE_DIM = 66
|
| 38 |
+
FIELD_HEIGHT = 25
|
| 39 |
+
FIELD_WIDTH = 61
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _select_device(value: str | torch.device | None) -> torch.device:
|
| 43 |
+
if value is not None:
|
| 44 |
+
device = torch.device(value)
|
| 45 |
+
if device.type == "cuda" and not torch.cuda.is_available():
|
| 46 |
+
raise RuntimeError("CUDA was requested but is not available")
|
| 47 |
+
if device.type == "mps" and not torch.backends.mps.is_available():
|
| 48 |
+
raise RuntimeError("MPS was requested but is not available")
|
| 49 |
+
return device
|
| 50 |
+
if torch.cuda.is_available():
|
| 51 |
+
return torch.device("cuda")
|
| 52 |
+
if torch.backends.mps.is_available():
|
| 53 |
+
return torch.device("mps")
|
| 54 |
+
return torch.device("cpu")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _batch(value: np.ndarray, trailing: tuple[int, ...], name: str) -> np.ndarray:
|
| 58 |
+
array = np.asarray(value, dtype="float32")
|
| 59 |
+
if array.shape == trailing:
|
| 60 |
+
array = array[None, ...]
|
| 61 |
+
if array.ndim != len(trailing) + 1 or array.shape[1:] != trailing:
|
| 62 |
+
raise ValueError(f"{name} must have shape [batch, {', '.join(map(str, trailing))}], got {array.shape}")
|
| 63 |
+
if not np.isfinite(array).all():
|
| 64 |
+
raise ValueError(f"{name} contains NaN or infinity")
|
| 65 |
+
return array
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _same_batch(*arrays: np.ndarray) -> None:
|
| 69 |
+
sizes = {int(value.shape[0]) for value in arrays}
|
| 70 |
+
if len(sizes) != 1:
|
| 71 |
+
raise ValueError(f"all inputs must have the same batch size, got {sorted(sizes)}")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def prepare_route_field(
|
| 75 |
+
slp: np.ndarray,
|
| 76 |
+
hgt500: np.ndarray,
|
| 77 |
+
slp_valid: np.ndarray | None = None,
|
| 78 |
+
hgt500_valid: np.ndarray | None = None,
|
| 79 |
+
) -> np.ndarray:
|
| 80 |
+
"""Encode physical three-time SLP/H500 analysis grids for the route head.
|
| 81 |
+
|
| 82 |
+
``slp`` and ``hgt500`` are physical arrays with shape ``[B, 3, H, W]``.
|
| 83 |
+
The channel order is ``SLP_t0, H500_t0, SLP_t1, H500_t1, SLP_t2,
|
| 84 |
+
H500_t2``. Missing-frame masks are 0/1 arrays with shape ``[B, 3]`` or
|
| 85 |
+
``[B, 3, 1, 1]``. The route checkpoint was trained with SLP in hPa and
|
| 86 |
+
H500 in geopotential metres.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
slp = _batch(slp, (3, slp.shape[-2], slp.shape[-1]) if np.asarray(slp).ndim == 4 else (3, FIELD_HEIGHT, FIELD_WIDTH), "slp")
|
| 90 |
+
hgt500 = _batch(hgt500, (3, slp.shape[-2], slp.shape[-1]), "hgt500")
|
| 91 |
+
_same_batch(slp, hgt500)
|
| 92 |
+
if slp.shape[1:] != hgt500.shape[1:]:
|
| 93 |
+
raise ValueError(f"slp and hgt500 grids must match, got {slp.shape} and {hgt500.shape}")
|
| 94 |
+
slp_valid = np.ones((slp.shape[0], 3), dtype="float32") if slp_valid is None else np.asarray(slp_valid, dtype="float32").reshape(slp.shape[0], 3)
|
| 95 |
+
hgt500_valid = np.ones((slp.shape[0], 3), dtype="float32") if hgt500_valid is None else np.asarray(hgt500_valid, dtype="float32").reshape(slp.shape[0], 3)
|
| 96 |
+
field = np.empty((slp.shape[0], 6, slp.shape[2], slp.shape[3]), dtype="float32")
|
| 97 |
+
for frame in range(3):
|
| 98 |
+
field[:, 2 * frame] = ((slp[:, frame] - 1010.0) / 20.0) * slp_valid[:, frame, None, None]
|
| 99 |
+
field[:, 2 * frame + 1] = ((hgt500[:, frame] - 5500.0) / 300.0) * hgt500_valid[:, frame, None, None]
|
| 100 |
+
return field
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def local_position_to_latlon(
|
| 104 |
+
position_100km: np.ndarray,
|
| 105 |
+
issue_latitude: np.ndarray | float,
|
| 106 |
+
issue_longitude: np.ndarray | float,
|
| 107 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 108 |
+
"""Convert model local displacement output to latitude/longitude degrees."""
|
| 109 |
+
|
| 110 |
+
position = _batch(position_100km, (LEADS, 2), "position_100km")
|
| 111 |
+
lat0 = np.asarray(issue_latitude, dtype="float32").reshape(-1)
|
| 112 |
+
lon0 = np.asarray(issue_longitude, dtype="float32").reshape(-1)
|
| 113 |
+
if len(lat0) == 1 and len(position) > 1:
|
| 114 |
+
lat0 = np.repeat(lat0, len(position))
|
| 115 |
+
if len(lon0) == 1 and len(position) > 1:
|
| 116 |
+
lon0 = np.repeat(lon0, len(position))
|
| 117 |
+
if len(lat0) != len(position) or len(lon0) != len(position):
|
| 118 |
+
raise ValueError("issue latitude/longitude must have one value per batch item")
|
| 119 |
+
latitude = lat0[:, None] + position[..., 1] * 100.0 / 111.0
|
| 120 |
+
longitude = lon0[:, None] + position[..., 0] * 100.0 / (
|
| 121 |
+
111.0 * np.maximum(np.cos(np.deg2rad(latitude)), 0.2)
|
| 122 |
+
)
|
| 123 |
+
return latitude.astype("float32"), np.mod(longitude, 360.0).astype("float32")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _structure_transform(value: np.ndarray) -> np.ndarray:
|
| 127 |
+
value = np.asarray(value, dtype="float32")
|
| 128 |
+
result = np.zeros_like(value, dtype="float32")
|
| 129 |
+
result[..., 0] = (value[..., 0] - 50.0) / 35.0
|
| 130 |
+
result[..., 1] = (value[..., 1] - 1000.0) / 20.0
|
| 131 |
+
result[..., 2:] = np.log1p(np.maximum(value[..., 2:], 0.0) / 50.0)
|
| 132 |
+
return np.nan_to_num(result, nan=0.0, posinf=0.0, neginf=0.0).astype("float32")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _structure_inverse(value: np.ndarray) -> np.ndarray:
|
| 136 |
+
result = np.zeros_like(value, dtype="float32")
|
| 137 |
+
result[..., 0] = value[..., 0] * 35.0 + 50.0
|
| 138 |
+
result[..., 1] = value[..., 1] * 20.0 + 1000.0
|
| 139 |
+
result[..., 2:] = np.expm1(np.maximum(value[..., 2:], 0.0)) * 50.0
|
| 140 |
+
return result
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _project_structure(value: np.ndarray) -> np.ndarray:
|
| 144 |
+
output = value.astype("float32", copy=True)
|
| 145 |
+
output[..., 0] = np.clip(output[..., 0], 0.0, 250.0)
|
| 146 |
+
output[..., 1] = np.clip(output[..., 1], 850.0, 1060.0)
|
| 147 |
+
output[..., 2:] = np.clip(output[..., 2:], 0.0, 1000.0)
|
| 148 |
+
output[..., 7:11] = np.minimum(output[..., 7:11], output[..., 3:7])
|
| 149 |
+
output[..., 11:15] = np.minimum(output[..., 11:15], output[..., 7:11])
|
| 150 |
+
return output
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class _WholePacificRouteModel(nn.Module):
|
| 154 |
+
def __init__(self, config: dict[str, Any], context_dim: int) -> None:
|
| 155 |
+
super().__init__()
|
| 156 |
+
width = int(config["width"])
|
| 157 |
+
field_width = int(config["field_width"])
|
| 158 |
+
context_width = int(config["context_width"])
|
| 159 |
+
dropout = float(config["dropout"])
|
| 160 |
+
layers = int(config["layers"])
|
| 161 |
+
heads = int(config["heads"])
|
| 162 |
+
self.max_correction = float(config["max_correction_100km"])
|
| 163 |
+
self.field = nn.Sequential(
|
| 164 |
+
nn.Conv2d(6, 32, 3, padding=1), nn.GroupNorm(8, 32), nn.GELU(), nn.MaxPool2d(2),
|
| 165 |
+
nn.Conv2d(32, 64, 3, padding=1), nn.GroupNorm(8, 64), nn.GELU(), nn.MaxPool2d(2),
|
| 166 |
+
nn.Conv2d(64, field_width, 3, padding=1), nn.GroupNorm(8, field_width), nn.GELU(),
|
| 167 |
+
nn.AdaptiveAvgPool2d((1, 1)),
|
| 168 |
+
)
|
| 169 |
+
self.field_projection = nn.Linear(field_width, field_width)
|
| 170 |
+
self.context = nn.Sequential(
|
| 171 |
+
nn.LayerNorm(context_dim), nn.Linear(context_dim, context_width), nn.GELU(),
|
| 172 |
+
nn.Dropout(dropout), nn.Linear(context_width, width), nn.GELU(),
|
| 173 |
+
)
|
| 174 |
+
self.fusion = nn.Sequential(nn.Linear(field_width + width, width), nn.LayerNorm(width), nn.GELU())
|
| 175 |
+
self.lead = nn.Parameter(torch.randn(1, LEADS, width) * 0.02)
|
| 176 |
+
start = max(0, min(LEADS, int(config.get("lead_start", 0))))
|
| 177 |
+
ramp = torch.zeros(LEADS, dtype=torch.float32)
|
| 178 |
+
if start < LEADS:
|
| 179 |
+
ramp[start:] = torch.linspace(0.0, 1.0, LEADS - start) ** float(config.get("lead_ramp_power", 1.0))
|
| 180 |
+
self.register_buffer("correction_ramp", ramp.view(1, LEADS, 1))
|
| 181 |
+
position = torch.arange(LEADS, dtype=torch.float32).view(LEADS, 1)
|
| 182 |
+
divisor = torch.exp(torch.arange(0, width, 2, dtype=torch.float32) * (-math.log(10000.0) / width))
|
| 183 |
+
encoding = torch.zeros(LEADS, width)
|
| 184 |
+
encoding[:, 0::2] = torch.sin(position * divisor)
|
| 185 |
+
encoding[:, 1::2] = torch.cos(position * divisor)
|
| 186 |
+
self.register_buffer("position_encoding", encoding.unsqueeze(0))
|
| 187 |
+
block = nn.TransformerEncoderLayer(width, heads, width * 4, dropout=dropout, batch_first=True, norm_first=True, activation="gelu")
|
| 188 |
+
self.temporal = nn.TransformerEncoder(block, layers)
|
| 189 |
+
self.route_head = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, 2))
|
| 190 |
+
self.land_head = nn.Sequential(nn.LayerNorm(width), nn.Linear(width, 1))
|
| 191 |
+
|
| 192 |
+
def forward(self, field: torch.Tensor, context: torch.Tensor, base_position: torch.Tensor):
|
| 193 |
+
field_embedding = self.field_projection(self.field(field).flatten(1))
|
| 194 |
+
context_embedding = self.context(context)
|
| 195 |
+
fused = self.fusion(torch.cat([field_embedding, context_embedding], dim=1))
|
| 196 |
+
tokens = self.temporal(fused[:, None, :] + self.lead + self.position_encoding)
|
| 197 |
+
correction = torch.tanh(self.route_head(tokens)) * self.max_correction * self.correction_ramp
|
| 198 |
+
position = base_position + correction
|
| 199 |
+
land_probability = torch.sigmoid(self.land_head(tokens)).squeeze(-1)
|
| 200 |
+
return position, land_probability, correction
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class _ResidualCurveModel(nn.Module):
|
| 204 |
+
def __init__(self, config: dict[str, Any]):
|
| 205 |
+
super().__init__()
|
| 206 |
+
width = int(config["width"])
|
| 207 |
+
input_dim = INTENSITY_INPUT_DIM
|
| 208 |
+
dropout = float(config["dropout"])
|
| 209 |
+
self.input = nn.Sequential(nn.LayerNorm(input_dim), nn.Linear(input_dim, width), nn.GELU(), nn.Dropout(dropout), nn.Linear(width, width), nn.GELU())
|
| 210 |
+
self.lead = nn.Parameter(torch.randn(1, LEADS, width) * 0.02)
|
| 211 |
+
position = torch.arange(LEADS, dtype=torch.float32).view(LEADS, 1)
|
| 212 |
+
divisor = torch.exp(torch.arange(0, width, 2, dtype=torch.float32) * (-math.log(10000.0) / width))
|
| 213 |
+
encoding = torch.zeros(LEADS, width)
|
| 214 |
+
encoding[:, 0::2] = torch.sin(position * divisor)
|
| 215 |
+
encoding[:, 1::2] = torch.cos(position * divisor)
|
| 216 |
+
self.register_buffer("position", encoding.unsqueeze(0))
|
| 217 |
+
block = nn.TransformerEncoderLayer(width, int(config["heads"]), width * 4, dropout=dropout, batch_first=True, norm_first=True, activation="gelu")
|
| 218 |
+
self.temporal = nn.TransformerEncoder(block, int(config["layers"]))
|
| 219 |
+
self.output = nn.Linear(width, STRUCTURE_DIM)
|
| 220 |
+
self.register_buffer("residual_limit", torch.tensor([1.20, 1.20, 0.90] + [1.05] * 12, dtype=torch.float32).view(1, 1, -1))
|
| 221 |
+
|
| 222 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 223 |
+
context = self.input(features)
|
| 224 |
+
tokens = self.temporal(context[:, None, :] + self.lead + self.position)
|
| 225 |
+
return torch.tanh(self.output(tokens)) * self.residual_limit
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class Trackformer12:
|
| 229 |
+
"""Load and run the released Trackformer 1.2 causal members."""
|
| 230 |
+
|
| 231 |
+
def __init__(self, model_root: str | Path, device: str | torch.device | None = None):
|
| 232 |
+
self.model_root = self._resolve_root(Path(model_root))
|
| 233 |
+
self.device = _select_device(device)
|
| 234 |
+
manifest_path = self.model_root / "manifest.json"
|
| 235 |
+
self.manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else {}
|
| 236 |
+
stats_path = self.model_root / "trackformer_1_2_feature_stats.npz"
|
| 237 |
+
if not stats_path.exists():
|
| 238 |
+
raise FileNotFoundError(f"missing feature statistics: {stats_path}")
|
| 239 |
+
with np.load(stats_path, allow_pickle=False) as stats:
|
| 240 |
+
self.feature_mean = stats["feature_mean"].astype("float32")
|
| 241 |
+
self.feature_std = np.maximum(stats["feature_std"].astype("float32"), 1.0e-4)
|
| 242 |
+
self.route_members = self._load_route_members()
|
| 243 |
+
self.intensity_members = self._load_intensity_members()
|
| 244 |
+
ocean_path = self.model_root / "trackformer_1_2_ocean_structure.joblib"
|
| 245 |
+
self.ocean_structure = None
|
| 246 |
+
if ocean_path.exists():
|
| 247 |
+
try:
|
| 248 |
+
import joblib
|
| 249 |
+
self.ocean_structure = joblib.load(ocean_path)
|
| 250 |
+
except ImportError as exc:
|
| 251 |
+
raise ImportError("joblib is required for ocean structure calibration") from exc
|
| 252 |
+
|
| 253 |
+
@staticmethod
|
| 254 |
+
def _resolve_root(path: Path) -> Path:
|
| 255 |
+
direct = path / "manifest.json"
|
| 256 |
+
nested = path / "models" / "trackformer_1_2" / "manifest.json"
|
| 257 |
+
if direct.exists():
|
| 258 |
+
return path
|
| 259 |
+
if nested.exists():
|
| 260 |
+
return nested.parent
|
| 261 |
+
raise FileNotFoundError(f"could not find Trackformer 1.2 manifest below {path}")
|
| 262 |
+
|
| 263 |
+
@classmethod
|
| 264 |
+
def from_pretrained(cls, model_root: str | Path | None = None, repo_id: str = "euler314/typhoon-predict", device: str | torch.device | None = None) -> "Trackformer12":
|
| 265 |
+
"""Load from an extracted release bundle or the Hugging Face model repo."""
|
| 266 |
+
if model_root is None:
|
| 267 |
+
try:
|
| 268 |
+
from huggingface_hub import snapshot_download
|
| 269 |
+
except ImportError as exc:
|
| 270 |
+
raise ImportError("install huggingface_hub or pass model_root to from_pretrained") from exc
|
| 271 |
+
model_root = snapshot_download(repo_id=repo_id, allow_patterns=["models/trackformer_1_2/*", "README.md"])
|
| 272 |
+
return cls(model_root, device=device)
|
| 273 |
+
|
| 274 |
+
def _load_route_members(self) -> list[_WholePacificRouteModel]:
|
| 275 |
+
members = []
|
| 276 |
+
for seed in (0, 1):
|
| 277 |
+
payload = torch.load(self.model_root / f"trackformer_1_2_route_seed{seed}.pt", map_location="cpu", weights_only=False)
|
| 278 |
+
model = _WholePacificRouteModel(payload["config"], int(payload["context_dim"]))
|
| 279 |
+
missing, unexpected = model.load_state_dict(payload["model"], strict=False)
|
| 280 |
+
# The published route checkpoints predate serialization of the
|
| 281 |
+
# non-learned correction ramp. Their config has no lead-ramp
|
| 282 |
+
# fields, so preserve the checkpoint behavior with an all-one
|
| 283 |
+
# ramp rather than silently applying a new schedule.
|
| 284 |
+
if missing == ["correction_ramp"] and not unexpected and "lead_start" not in payload["config"]:
|
| 285 |
+
model.correction_ramp.fill_(1.0)
|
| 286 |
+
elif missing or unexpected:
|
| 287 |
+
raise RuntimeError(f"incompatible route checkpoint {seed}: missing={missing}, unexpected={unexpected}")
|
| 288 |
+
members.append(model.to(self.device).eval())
|
| 289 |
+
return members
|
| 290 |
+
|
| 291 |
+
def _load_intensity_members(self) -> list[_ResidualCurveModel]:
|
| 292 |
+
members = []
|
| 293 |
+
for seed in (0, 1):
|
| 294 |
+
payload = torch.load(self.model_root / f"trackformer_1_2_intensity_seed{seed}.pt", map_location="cpu", weights_only=False)
|
| 295 |
+
model = _ResidualCurveModel(payload["config"])
|
| 296 |
+
model.load_state_dict(payload["model"], strict=True)
|
| 297 |
+
members.append(model.to(self.device).eval())
|
| 298 |
+
return members
|
| 299 |
+
|
| 300 |
+
@torch.no_grad()
|
| 301 |
+
def predict_route(self, field: np.ndarray, context: np.ndarray, base_position: np.ndarray, batch_size: int = 64) -> dict[str, np.ndarray]:
|
| 302 |
+
"""Predict the 20-lead route from issue-time causal route tensors.
|
| 303 |
+
|
| 304 |
+
``field`` is normalized by :func:`prepare_route_field` and has shape
|
| 305 |
+
``[B, 6, H, W]``; ``context`` is ``[B, 647]``; and ``base_position``
|
| 306 |
+
is ``[B, 20, 2]`` in cumulative 100-km local displacement units.
|
| 307 |
+
"""
|
| 308 |
+
field = _batch(field, (6, np.asarray(field).shape[-2], np.asarray(field).shape[-1]), "field")
|
| 309 |
+
context = _batch(context, (ROUTE_CONTEXT_DIM,), "context")
|
| 310 |
+
base_position = _batch(base_position, (LEADS, 2), "base_position")
|
| 311 |
+
if field.shape[-2:] != (FIELD_HEIGHT, FIELD_WIDTH):
|
| 312 |
+
raise ValueError(f"field must be the released [25, 61] Pacific grid, got {field.shape[-2:]}")
|
| 313 |
+
_same_batch(field, context, base_position)
|
| 314 |
+
positions: list[np.ndarray] = []
|
| 315 |
+
land: list[np.ndarray] = []
|
| 316 |
+
for start in range(0, len(field), batch_size):
|
| 317 |
+
stop = min(start + batch_size, len(field))
|
| 318 |
+
inputs = (torch.from_numpy(field[start:stop]).to(self.device), torch.from_numpy(context[start:stop]).to(self.device), torch.from_numpy(base_position[start:stop]).to(self.device))
|
| 319 |
+
members = [model(*inputs) for model in self.route_members]
|
| 320 |
+
positions.append(torch.stack([item[0] for item in members]).mean(0).cpu().numpy())
|
| 321 |
+
land.append(torch.stack([item[1] for item in members]).mean(0).cpu().numpy())
|
| 322 |
+
return {"position_100km": np.concatenate(positions).astype("float32"), "land_probability": np.concatenate(land).astype("float32"), "lead_hours": np.asarray(LEAD_HOURS, dtype="int32")}
|
| 323 |
+
|
| 324 |
+
@torch.no_grad()
|
| 325 |
+
def predict_intensity(self, causal_features: np.ndarray, anchor_structure: np.ndarray, batch_size: int = 256) -> dict[str, np.ndarray]:
|
| 326 |
+
"""Predict wind, pressure, RMW, and quadrant radii.
|
| 327 |
+
|
| 328 |
+
``causal_features`` is the exact pre-residual 1,020-dimensional vector
|
| 329 |
+
built from current/past observations and analysis summaries. The
|
| 330 |
+
``anchor_structure`` is a physical ``[B, 20, 15]`` frozen causal
|
| 331 |
+
Trackformer 1.2.26 curve ordered as ``vmax, pressure, RMW, R34[4],
|
| 332 |
+
R50[4], R64[4]``.
|
| 333 |
+
"""
|
| 334 |
+
causal_features = _batch(causal_features, (INTENSITY_FEATURE_DIM,), "causal_features")
|
| 335 |
+
anchor = _batch(anchor_structure, (LEADS, STRUCTURE_DIM), "anchor_structure")
|
| 336 |
+
_same_batch(causal_features, anchor)
|
| 337 |
+
anchor_transformed = _structure_transform(anchor)
|
| 338 |
+
features = np.concatenate([causal_features, anchor_transformed.reshape(len(anchor), -1)], axis=1)
|
| 339 |
+
if features.shape[1] != len(self.feature_mean):
|
| 340 |
+
raise ValueError(f"feature vector plus anchor must have {len(self.feature_mean)} columns, got {features.shape[1]}")
|
| 341 |
+
normalized = ((features - self.feature_mean) / self.feature_std).astype("float32")
|
| 342 |
+
members: list[np.ndarray] = []
|
| 343 |
+
for start in range(0, len(normalized), batch_size):
|
| 344 |
+
stop = min(start + batch_size, len(normalized))
|
| 345 |
+
tensor = torch.from_numpy(normalized[start:stop]).to(self.device)
|
| 346 |
+
delta = torch.stack([model(tensor) for model in self.intensity_members]).mean(0).cpu().numpy()
|
| 347 |
+
members.append(_project_structure(_structure_inverse(anchor_transformed[start:stop] + delta)))
|
| 348 |
+
return {"structure": np.concatenate(members).astype("float32"), "lead_hours": np.asarray(LEAD_HOURS, dtype="int32")}
|
| 349 |
+
|
| 350 |
+
def predict_ocean_structure(self, causal_features: np.ndarray, ocean_features: np.ndarray, anchor_structure: np.ndarray, ocean_available: np.ndarray | float = 1.0) -> dict[str, np.ndarray]:
|
| 351 |
+
"""Apply the released causal OHC/D26/D20 calibration to the anchor.
|
| 352 |
+
|
| 353 |
+
This is a separately validated calibration head trained around the
|
| 354 |
+
frozen 1.2.26 structure anchor. It is intentionally returned as its
|
| 355 |
+
own forecast rather than silently stacking it on the neural residual
|
| 356 |
+
head, which would be an unvalidated model change.
|
| 357 |
+
"""
|
| 358 |
+
if self.ocean_structure is None:
|
| 359 |
+
raise FileNotFoundError("trackformer_1_2_ocean_structure.joblib is not present")
|
| 360 |
+
causal_features = _batch(causal_features, (INTENSITY_FEATURE_DIM,), "causal_features")
|
| 361 |
+
ocean_features = _batch(ocean_features, (OCEAN_FEATURE_DIM,), "ocean_features")
|
| 362 |
+
anchor = _batch(anchor_structure, (LEADS, STRUCTURE_DIM), "anchor_structure")
|
| 363 |
+
_same_batch(causal_features, ocean_features, anchor)
|
| 364 |
+
available = np.asarray(ocean_available, dtype="float32").reshape(-1)
|
| 365 |
+
if len(available) == 1:
|
| 366 |
+
available = np.repeat(available, len(anchor))
|
| 367 |
+
if len(available) != len(anchor):
|
| 368 |
+
raise ValueError("ocean_available must have one value per batch item")
|
| 369 |
+
raw = np.concatenate([ocean_features, _structure_transform(anchor[:, -1]), causal_features], axis=1)
|
| 370 |
+
fitted = self.ocean_structure
|
| 371 |
+
normalized = ((raw - fitted["feature_mean"]) / np.maximum(fitted["feature_std"], 1.0e-4)).astype("float32")
|
| 372 |
+
output = anchor.copy()
|
| 373 |
+
groups = {"vmax": np.asarray([0]), "pressure": np.asarray([1]), "r34": np.arange(3, 7), "r50": np.arange(7, 11), "r64": np.arange(11, 15)}
|
| 374 |
+
for group, columns in groups.items():
|
| 375 |
+
meta = fitted["selection"][group]
|
| 376 |
+
corrections = np.zeros((len(anchor), LEADS), dtype="float32")
|
| 377 |
+
for lead, item in enumerate(fitted["models"][group]):
|
| 378 |
+
selected = np.asarray(item["features"], dtype="int64")
|
| 379 |
+
corrections[:, lead] = item["model"].predict(normalized[:, selected]).astype("float32")
|
| 380 |
+
fraction = np.linspace(0.0, 1.0, LEADS, dtype="float32")
|
| 381 |
+
ramp = np.zeros(LEADS, dtype="float32")
|
| 382 |
+
start = int(meta["start"])
|
| 383 |
+
ramp[start:] = fraction[start:] ** float(meta["power"])
|
| 384 |
+
trusted = available[:, None] * ramp[None, :]
|
| 385 |
+
if group in ("vmax", "pressure"):
|
| 386 |
+
output[..., columns] += float(meta["alpha"]) * trusted[..., None] * corrections[..., None]
|
| 387 |
+
else:
|
| 388 |
+
log_value = np.log1p(np.maximum(output[..., columns], 0.0) / 50.0)
|
| 389 |
+
log_value += float(meta["alpha"]) * trusted[..., None] * corrections[..., None]
|
| 390 |
+
output[..., columns] = np.expm1(np.maximum(log_value, 0.0)) * 50.0
|
| 391 |
+
output = _project_structure(output)
|
| 392 |
+
return {"structure": output.astype("float32"), "lead_hours": np.asarray(LEAD_HOURS, dtype="int32"), "ocean_available": available.astype("float32")}
|
| 393 |
+
|
| 394 |
+
def predict_issue_packet(self, packet: dict[str, np.ndarray]) -> dict[str, Any]:
|
| 395 |
+
"""Run every head present in an issue packet.
|
| 396 |
+
|
| 397 |
+
Required route keys are ``field``, ``context``, and ``base_position``.
|
| 398 |
+
Required intensity keys are ``causal_features`` and
|
| 399 |
+
``anchor_structure``. Ocean calibration additionally accepts
|
| 400 |
+
``ocean_features`` and ``ocean_available``.
|
| 401 |
+
"""
|
| 402 |
+
result: dict[str, Any] = {}
|
| 403 |
+
if {"field", "context", "base_position"}.issubset(packet):
|
| 404 |
+
result["route"] = self.predict_route(packet["field"], packet["context"], packet["base_position"])
|
| 405 |
+
if {"causal_features", "anchor_structure"}.issubset(packet):
|
| 406 |
+
result["intensity"] = self.predict_intensity(packet["causal_features"], packet["anchor_structure"])
|
| 407 |
+
if "ocean_features" in packet:
|
| 408 |
+
result["ocean_structure"] = self.predict_ocean_structure(packet["causal_features"], packet["ocean_features"], packet["anchor_structure"], packet.get("ocean_available", 1.0))
|
| 409 |
+
if not result:
|
| 410 |
+
raise ValueError("packet has no complete route or intensity input group")
|
| 411 |
+
return result
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
__all__ = [
|
| 415 |
+
"FIELD_HEIGHT", "FIELD_WIDTH", "INTENSITY_FEATURE_DIM", "INTENSITY_INPUT_DIM", "LEADS", "LEAD_HOURS",
|
| 416 |
+
"OCEAN_FEATURE_DIM", "ROUTE_CONTEXT_DIM", "STRUCTURE_DIM", "Trackformer12",
|
| 417 |
+
"local_position_to_latlon", "prepare_route_field",
|
| 418 |
+
]
|