Publish Trackformer 1.2 field model, weights and research comparison
Browse filesPreserve 1.1 assets; add verified 1.2 field weights, exact source, architecture documentation, TIP comparison bars and model-generated MSLP examples.
- LICENSE +21 -0
- README.md +40 -43
- RELEASE_NOTES_TRACKFORMER_1_2.md +9 -0
- docs/trackformer_1_2_evaluation.md +21 -0
- models/trackformer_1_2_field/README.md +31 -0
- models/trackformer_1_2_field/baseline_model.py +158 -0
- models/trackformer_1_2_field/manifest.json +369 -0
- models/trackformer_1_2_field/model.py +74 -0
- models/trackformer_1_2_field/predict.py +91 -0
- models/trackformer_1_2_field/v165_base.py +657 -0
- models/trackformer_1_2_field/weights.pt +3 -0
- paper/trackformer_1_2_pressure_map_example.png +0 -0
- paper/trackformer_1_2_vs_1_1_tip_bars.png +0 -0
- paper/trackformer_1_2_vs_1_1_tip_metrics.json +28 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Yu Yao-Hsing (yu314-coder)
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
CHANGED
|
@@ -1,59 +1,56 @@
|
|
| 1 |
-
|
| 2 |
-
library_name: pytorch
|
| 3 |
-
tags:
|
| 4 |
-
- weather-forecasting
|
| 5 |
-
- tropical-cyclone
|
| 6 |
-
- time-series-forecasting
|
| 7 |
-
- causal-inference
|
| 8 |
-
---
|
| 9 |
|
| 10 |
-
|
| 11 |
|
| 12 |
-
|
| 13 |
-
model. It predicts position, maximum sustained wind, central pressure, radius
|
| 14 |
-
of maximum wind, and R34/R50/R64 wind radii at six-hour leads through +120 h.
|
| 15 |
|
| 16 |
-
|
| 17 |
-
aviation, maritime, emergency-management, or other safety-critical decisions.
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
- [Live interactive demo](https://yu314-coder.github.io/typhoon-tracks.html)
|
| 23 |
|
| 24 |
-
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
|
| 30 |
-
|
| 31 |
-
- atmospheric analysis fields available at or before the issue time;
|
| 32 |
-
- causal nearby-storm and basin-context summaries;
|
| 33 |
-
- static geography and land/sea features in the prepared packet.
|
| 34 |
|
| 35 |
-
|
| 36 |
-
agency's forecast track or positive-lead weather field as an input. Later
|
| 37 |
-
observations and best-track labels are verification data only.
|
| 38 |
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
sustained wind, central pressure, radius of maximum wind, and four-quadrant
|
| 43 |
-
R34/R50/R64 radii. Radius values are non-negative and the structure head
|
| 44 |
-
preserves R34 >= R50 >= R64.
|
| 45 |
|
| 46 |
-
|
| 47 |
|
| 48 |
-
The
|
| 49 |
-
statistics, and seed checkpoints. The GitHub release archive is the
|
| 50 |
-
authoritative packaged-weight download.
|
| 51 |
|
| 52 |
-
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Trackformer 1.2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
Trackformer 1.2 is a **research-only Western Pacific tropical-cyclone forecast model**. It evolves a sea-level-pressure (MSLP) field and a moving storm-centred pressure core every six hours through +120 h. A track and central-pressure estimate are extracted from the evolving core, not independently drawn on top of a pressure image. The prior [Trackformer 1.1 release](https://github.com/yu314-coder/typhoon-predict/releases/tag/trackformer-1.1) remains available and unchanged.
|
| 4 |
|
| 5 |
+
**Not an operational warning system.** Do not use these forecasts for evacuation, aviation, maritime, or other safety-critical decisions. The public 1.2 name identifies one selected development checkpoint; a genuinely untouched storm-level holdout has not yet established generalization.
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
## What changed from 1.1
|
|
|
|
| 8 |
|
| 9 |
+
| | Trackformer 1.1 | Trackformer 1.2 |
|
| 10 |
+
| --- | --- | --- |
|
| 11 |
+
| Main representation | Observed history and weather features to track/intensity/structure outputs | Autoregressive basin MSLP plus storm-centred moving pressure core |
|
| 12 |
+
| Six-hour outputs | Track, maximum wind, central pressure, RMW, R34/R50/R64 | Track, central pressure, basin and regional MSLP; auxiliary maximum-wind scalar |
|
| 13 |
+
| Pressure-map capability | No native evolving MSLP forecast field in released model | Model-generated MSLP fields at every lead |
|
| 14 |
+
| Forecast horizon | +6 to +120 h | +6 to +120 h |
|
| 15 |
+
| Meaning of “50-member mean” | Not part of the 1.1 comparison | Same weights on 50 distinct, smoothly perturbed **causal input histories**; separately averaged routes, pressures and common-grid fields. Not 50 trained networks or learned latent members. |
|
| 16 |
|
| 17 |
+
The two models use different input pipelines. A direct chart is therefore a *forecast-output comparison on common cases and leads*, not a controlled architecture ablation.
|
|
|
|
| 18 |
|
| 19 |
+
## How the 1.2 model works
|
| 20 |
|
| 21 |
+
1. **Causal initialization.** Nine six-hour analyses ending at issue time provide eight basin channels on a 25×33 grid: MSLP, 500-hPa height, and 850/500/200-hPa winds. Where stored native detail exists, nine 121×121 regional MSLP patches supplement the coarse field. Static geography, current observed centre, recent motion, current intensity and masks are issue-time inputs. A compact pressure correction initializes the regional core from current observations; it is a reconstruction, not future weather.
|
| 22 |
+
2. **Environmental transport.** A convolutional recurrent state evolves the basin field. Estimated steering flow and a departure grid advect it, with learned pressure tendencies. Two pooled spatial scales feed a two-block transformer encoder; cross-attention conditions the environmental memory. Its output starts at zero so the added component initially matches its warm-start baseline.
|
| 23 |
+
3. **Moving pressure core.** A 65×65 storm-centred internal grid at approximately 20-km spacing moves with the storm. Its pressure anomaly is transported relative to the environmental flow and updated by learned tendencies. The displayed 121×121 regional field is a resampled composite; the moving core is authoritative for centre and central pressure.
|
| 24 |
+
4. **Coupled outputs.** A local low-pressure association within 300 km identifies the forecast centre. Central pressure is sampled from the predicted core **at that centre**. Maximum wind is an auxiliary scalar, not a resolved wind field or wind radii.
|
| 25 |
+
5. **Autoregression.** The transition runs 20 times for +6, +12, …, +120 h. Training combines basin-field, regional/core-field, track, central-pressure and auxiliary-wind losses, plus masked pressure-change and displacement losses. Future truth is a training/evaluation target only, never an inference input.
|
| 26 |
|
| 27 |
+
The implementation is in [`models/trackformer_1_2_field/`](models/trackformer_1_2_field/); its [`manifest.json`](models/trackformer_1_2_field/manifest.json) records exact grids, normalization, architecture and SHA-256 provenance. Internally the selected checkpoint came from experiment version `1.2.73`, epoch 4. The public model is **Trackformer 1.2**; that internal identifier is retained only for reproducibility.
|
| 28 |
|
| 29 |
+
## Saved comparison with 1.1
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
Both rows use the **same ten overlapping TIP issue times**, 1979-10-12 00 UTC through 1979-10-14 06 UTC, at six-hour leads through +120 h. Lower is better. The 1.2 row is the 50-input-member mean; 1.1 is its released prediction pipeline, so this is not a same-member-count experiment.
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
| TIP ten-start development diagnostic | 1.1 | 1.2, mean of 50 causal input members |
|
| 34 |
+
| --- | ---: | ---: |
|
| 35 |
+
| Mean track error | 383.9 km | **370.5 km** |
|
| 36 |
+
| Central-pressure MAE | **20.1 hPa** | 30.7 hPa |
|
| 37 |
|
| 38 |
+

|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
The track gain is small (about 3.5%); central-pressure error is substantially worse. TIP's ten starts are one storm with overlapping forecasts, not ten independent holdout storms. They do **not** establish that 1.2 is better overall or resistant to overfitting.
|
| 41 |
|
| 42 |
+
The saved Dolphin example below uses 1.2's **forecast basin MSLP**, not a post-drawn or borrowed pressure map. It shows +24, +72 and +120 h fields with the extracted route. Trackformer 1.1 does not emit an equivalent evolving MSLP field, so no fake 1.1 field comparison is shown.
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+

|
| 45 |
|
| 46 |
+
On a separate, repeatedly inspected 270-case development cohort (90 storms × three issues), the 1.2 mean-of-50 result was 714.4 km mean track error, 15.73 hPa central-pressure MAE and 2.54 hPa area-weighted regional MSLP MAE; **there is no directly matched 1.1 field score**. The TIP and 270-case results must not be mixed into a single ranking. See [evaluation notes](docs/trackformer_1_2_evaluation.md).
|
| 47 |
+
|
| 48 |
+
## Get the model and run it
|
| 49 |
+
|
| 50 |
+
- [GitHub release and source](https://github.com/yu314-coder/typhoon-predict/releases/tag/trackformer-1.2)
|
| 51 |
+
- [Hugging Face weights and model card](https://huggingface.co/euler314/typhoon-predict)
|
| 52 |
+
- [Input schema and inference instructions](models/trackformer_1_2_field/README.md)
|
| 53 |
+
|
| 54 |
+
The inference-only `weights.pt` is hosted in the release/Hugging Face model folder, **not committed to GitHub source**. The manifest records its SHA-256 and the original training-checkpoint SHA-256. The three source modules are copied unchanged from the verified training implementation. The root-level `trackformer_1_2.py` and older `examples/predict_trackformer_1_2.py` are legacy artifacts from a withdrawn, unrelated 1.2 candidate; **do not use them with these field weights**.
|
| 55 |
+
|
| 56 |
+
Only issue-time and earlier analyses are permitted. The prediction wrapper rejects future-dated history and unexpected input keys, but cannot certify an externally built packet's data provenance. The operator must verify source timestamps and training-only normalization. The included wrapper runs one unperturbed forecast; it does not reproduce the saved 50-member mean automatically.
|
RELEASE_NOTES_TRACKFORMER_1_2.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Trackformer 1.2 — research candidate
|
| 2 |
+
|
| 3 |
+
This release packages a verified moving-pressure-core model as **Trackformer 1.2**. It supersedes the withdrawn, unrelated route/scalar 1.2 candidate; the older root-level `trackformer_1_2.py` is not compatible with these field weights. Trackformer 1.1 remains available as a separate release.
|
| 4 |
+
|
| 5 |
+
The attached archive includes inference-only weights, the exact source modules, a strict input wrapper, a data-contract/provenance manifest, model documentation, saved TIP comparison bars and a real model-generated Dolphin pressure-map example. The training checkpoint was internally labelled version `1.2.73`, epoch 4; its SHA-256 is `f194a23d3f91ea76ad776dfad942fabd669eeae8b3fd665815463095367e9ee0`. The exported inference weights SHA-256 is `db49f36e85a3766defc4c172746897a1f783705d1ce8e6f9dfb8e87ae1d902cb`.
|
| 6 |
+
|
| 7 |
+
On ten overlapping TIP starts, the 50-input-member mean reduced mean track error from 383.9 km (1.1) to 370.5 km, **but raised central-pressure MAE from 20.1 to 30.7 hPa**. These are development diagnostics, not proof of generalization. Trackformer 1.1 does not output a native MSLP forecast field, so the 1.2 pressure map is an example rather than a paired 1.1 field comparison.
|
| 8 |
+
|
| 9 |
+
This is not an operational warning service. Do not use for safety-critical decisions. A genuinely untouched storm-level holdout is still required before generalization claims.
|
docs/trackformer_1_2_evaluation.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Trackformer 1.2 evaluation notes
|
| 2 |
+
|
| 3 |
+
These are archived development results, not an untouched generalization test.
|
| 4 |
+
|
| 5 |
+
## TIP 1.1 comparison
|
| 6 |
+
|
| 7 |
+
The bars in the [main README](../README.md) were rendered from saved local reports `benchmark_tip_ten/v11.json` and `benchmark_ensemble50/v173_e4/tip_ten/v173_e4_ensemble50.json`. The plotting script asserts that both reports have the same ten issue timestamps. The 1.1 pipeline is one released forecast; 1.2 is a mean of 50 runs of one weight set with different smoothly perturbed causal historical inputs. Both use +6 to +120 h outputs. Unlike 1.2, 1.1 has no native MSLP-field forecast to compare in the pressure-map figure.
|
| 8 |
+
|
| 9 |
+
The TIP cohort consists of one storm and ten overlapping starts. It has been repeatedly inspected and is development evidence only. Central-pressure error regresses for 1.2 even though mean route error is slightly lower.
|
| 10 |
+
|
| 11 |
+
## 270-case field benchmark
|
| 12 |
+
|
| 13 |
+
The saved `benchmark_ensemble50/v173_e4/report.json` has 270 development cases (90 storms with three issue times each), 20 six-hour leads, checkpoint SHA-256 `f194a23d3f91ea76ad776dfad942fabd669eeae8b3fd665815463095367e9ee0`, 50 distinct input-perturbation member IDs and deterministic seed base 2043. Each member uses separate Gaussian fields smoothed with kernel sizes 5 (basin) and 9 (regional), centred and unit-scaled per map, with normalized amplitudes 0.025 and 0.015 respectively. Only `global_history` and `regional_history` are perturbed. Means are taken of routes, central pressures and fields on the same grids. These are neither 50 trained models nor learned latent members, and their spread is not a calibrated probability.
|
| 14 |
+
|
| 15 |
+
The mean-of-50 result is 714.4 km all-lead mean track error, 1433.4 km +120 h track error, 15.73 hPa central-pressure MAE and 2.536 hPa area-weighted regional MSLP MAE. The regional field metric is on a fixed grid; only 2627 of 5400 case-leads (48.6%) had valid in-domain centres for the separately reported centre-local metric. Do not conflate low area-weighted field error with accurate cyclone-core placement. The TIP pressure error is much higher than the 270-case aggregate.
|
| 16 |
+
|
| 17 |
+
The basin-pressure example is a saved Dolphin forecast from `benchmark_ensemble50/v173_e4/showcase_four.npz` and is model-generated. It is not a paired 1.1 map. Both figures can be reproduced with `release_tools/plot_field_1_2.py` if the original local reports are available.
|
| 18 |
+
|
| 19 |
+
## Validation boundary
|
| 20 |
+
|
| 21 |
+
Training used whole-storm year partitions: 2000–2021 training, 2022–2023 validation, 2024–2025 test in the original pipeline, with 13,949 / 1,041 / 1,195 windows respectively; native-pressure windows total 800 / 100 / 100. Repeatedly viewed benchmarks, TIP and calibration cases have become development evidence. Freeze a genuinely unused storm-level holdout with matched issue-time data before claiming generalization. Evaluate route, central pressure and pressure fields at every lead on common cases and masks; a lower map average alone is not a model win.
|
models/trackformer_1_2_field/README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Trackformer 1.2 field-model inference
|
| 2 |
+
|
| 3 |
+
This folder contains the exact source, input contract and inference-only weights for the research model in the [main README](../../README.md). `model.py`, `baseline_model.py` and `v165_base.py` are source-identical to the selected training implementation. The weight file is distributed via the [GitHub release](https://github.com/yu314-coder/typhoon-predict/releases/tag/trackformer-1.2) and [Hugging Face](https://huggingface.co/euler314/typhoon-predict/tree/main/models/trackformer_1_2_field), not Git.
|
| 4 |
+
|
| 5 |
+
Use Python with PyTorch and NumPy. The export environment used PyTorch 2.13.0; the source was evaluated on macOS MPS. Example:
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
python models/trackformer_1_2_field/predict.py causal_issue_packet.npz forecast.npz --device cpu
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
The `.npz` packet must contain exactly these arrays, with no object/pickle content:
|
| 12 |
+
|
| 13 |
+
| Key | Shape | Meaning |
|
| 14 |
+
| --- | --- | --- |
|
| 15 |
+
| `global_history` | `(9, 8, 25, 33)` | Past/issue-time basin analyses in manifest channel order, normalized with manifest means/stds. |
|
| 16 |
+
| `regional_history` | `(9, 1, 121, 121)` | Native MSLP patches when present, otherwise benchmark's coarse fallback; normalized using MSLP statistics. |
|
| 17 |
+
| `global_static` | `(4, 25, 33)` | Latitude/90, longitude/180−1, land fraction, elevation metres/8000. |
|
| 18 |
+
| `regional_static` | `(4, 121, 121)` | Same four static channels on the regional grid. |
|
| 19 |
+
| `detail_available` | `(1,)` | One when native history exists, otherwise zero. |
|
| 20 |
+
| `center` | `(2,)` | Issue-time latitude and longitude in degrees. |
|
| 21 |
+
| `motion` | `(2,)` | Previous six-hour east/north displacement in km. |
|
| 22 |
+
| `issue_intensity` | `(2,)` | Issue-time maximum wind in knots and central pressure in hPa. |
|
| 23 |
+
| `issue_mask` | `(2,)` | Validity flags for issue-time wind and pressure. |
|
| 24 |
+
| `issue_time_ns` | scalar | Forecast issue timestamp in Unix nanoseconds. |
|
| 25 |
+
| `history_time_ns` | `(9,)` | Nine consecutive six-hour timestamps ending at issue time. |
|
| 26 |
+
|
| 27 |
+
Output `.npz` contains `lead_hours`, `track_lat_lon`, `central_pressure_hpa`, `basin_mslp_hpa` and `regional_mslp_hpa`. Pressure arrays are physical hPa. The regional grid is issue-relative and must be located using the static coordinate channels, not interpreted as a fixed global map.
|
| 28 |
+
|
| 29 |
+
**Causality:** Never populate arrays from positive-lead analysis, later best track, agency forecast or future pressure field. The wrapper checks timestamp order and shapes, but cannot authenticate the upstream archive. Do not silently replace missing values with future data. This is not a raw-weather downloader or live warning service.
|
| 30 |
+
|
| 31 |
+
The published 50-member mean is a separate evaluation policy: 50 deterministic seeds perturb only normalized historical basin/regional fields with smooth zero-centred noise, then average routes, central pressures and common-grid fields. `predict.py` computes one clean forecast; do not label it a 50-member mean.
|
models/trackformer_1_2_field/baseline_model.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Observation-initialized moving pressure state; no independent pressure head."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
|
| 9 |
+
import v165_base as base
|
| 10 |
+
|
| 11 |
+
VERSION = '1.2.68'
|
| 12 |
+
ARCHITECTURE = 'moving-pressure-core-v168-prototype'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def weighted(value, mask):
|
| 16 |
+
return (value * mask).sum() / mask.expand_as(value).sum().clamp_min(1)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class CoreForecaster(base.TransportForecaster):
|
| 20 |
+
def __init__(self, manifest, tiny=False):
|
| 21 |
+
super().__init__(manifest, tiny)
|
| 22 |
+
del self.fine, self.fine_memory, self.wind
|
| 23 |
+
self.core_net = base.EvolutionNet(1 + 8 + 32 + 4, 3, 8 if tiny else 64, tiny)
|
| 24 |
+
self.core_memory = base.RecurrentFeatures(9)
|
| 25 |
+
self.motion_net = nn.Sequential(nn.Linear(32 + 8 + 4, 64), nn.GELU(), nn.Linear(64, 3))
|
| 26 |
+
nn.init.zeros_(self.motion_net[-1].weight)
|
| 27 |
+
nn.init.zeros_(self.motion_net[-1].bias)
|
| 28 |
+
# 20 km internal grid is a reconstruction, not new resolved observations.
|
| 29 |
+
yy, xx = torch.meshgrid(torch.linspace(640, -640, 65), torch.linspace(-640, 640, 65), indexing='ij')
|
| 30 |
+
self.register_buffer('east', xx[None])
|
| 31 |
+
self.register_buffer('north', yy[None])
|
| 32 |
+
radius = (xx.square() + yy.square()).sqrt()
|
| 33 |
+
self.register_buffer('taper', ((640-radius)/160).clamp(0, 1)[None, None])
|
| 34 |
+
|
| 35 |
+
def coordinates(self, center):
|
| 36 |
+
lat = center[:, 0, None, None] + self.north / 111.2
|
| 37 |
+
lon = center[:, 1, None, None] + self.east / (111.2 * center[:, 0, None, None].deg2rad().cos().clamp_min(.2))
|
| 38 |
+
return lat, lon
|
| 39 |
+
|
| 40 |
+
def basin_grid(self, lat, lon):
|
| 41 |
+
return torch.stack([(lon-100)/40-1, 1-lat/30], -1)
|
| 42 |
+
|
| 43 |
+
def core_grid(self, lat, lon, origin):
|
| 44 |
+
east = (lon-origin[:, 1, None, None])*111.2*origin[:, 0, None, None].deg2rad().cos().clamp_min(.2)
|
| 45 |
+
north = (lat-origin[:, 0, None, None])*111.2
|
| 46 |
+
return torch.stack([east/640, -north/640], -1)
|
| 47 |
+
|
| 48 |
+
def initial(self, inputs):
|
| 49 |
+
required = {'global_history','regional_history','global_static','regional_static','detail_available','center','motion','issue_intensity','issue_mask'}
|
| 50 |
+
if set(inputs) != required:
|
| 51 |
+
raise ValueError('Only declared past and issue-time inputs are allowed')
|
| 52 |
+
history = inputs['global_history']
|
| 53 |
+
lat, lon = self.coordinates(inputs['center'])
|
| 54 |
+
grid = self.basin_grid(lat, lon)
|
| 55 |
+
regional = inputs['regional_static']
|
| 56 |
+
rlat, rlon = regional[:, 0]*90, (regional[:, 1]+1)*180
|
| 57 |
+
native_grid = torch.stack([2*(lon-rlon[:, :1, :1])/(rlon[:, :1, -1:]-rlon[:, :1, :1])-1,
|
| 58 |
+
2*(lat-rlat[:, :1, :1])/(rlat[:, -1:, :1]-rlat[:, :1, :1])-1], -1)
|
| 59 |
+
parent = base.sample_field(history[:, -1, :1], grid)
|
| 60 |
+
available = inputs['detail_available'][:, :, None, None].bool()
|
| 61 |
+
past = []
|
| 62 |
+
for i in range(9):
|
| 63 |
+
coarse = base.sample_field(history[:, i, :1], grid)
|
| 64 |
+
native = base.sample_field(inputs['regional_history'][:, i], native_grid)
|
| 65 |
+
past.append(torch.where(available, native, coarse))
|
| 66 |
+
core = past[-1]
|
| 67 |
+
observed = (inputs['issue_intensity'][:, 1] - self.mean[0, 0, 0, 0]) / self.std[0, 0, 0, 0]
|
| 68 |
+
# Only initialization uses an explicit compact core prior. Subsequent
|
| 69 |
+
# changes are learned field tendencies, not repeated scalar insertion.
|
| 70 |
+
radius2 = self.east.square() + self.north.square()
|
| 71 |
+
prior = torch.exp(-radius2/(2*100**2))[:, None] * self.taper
|
| 72 |
+
difference = observed-core[:, 0, 32, 32]
|
| 73 |
+
core = core + difference[:, None, None, None]*prior*inputs['issue_mask'][:, 1, None, None, None]
|
| 74 |
+
return dict(g=history[:, -1], gh=self.coarse_memory.encode(history.flatten(1, 2)),
|
| 75 |
+
core=core, ch=self.core_memory.encode(torch.cat(past, 1)),
|
| 76 |
+
anomaly=core-parent, origin=inputs['center'], center=inputs['center'], motion=inputs['motion'],
|
| 77 |
+
vmax=inputs['issue_intensity'][:, 0], gs=inputs['global_static'], rs=regional,
|
| 78 |
+
issue=inputs['issue_intensity'], issue_mask=inputs['issue_mask'])
|
| 79 |
+
|
| 80 |
+
def step(self, s):
|
| 81 |
+
delta, features = self.coarse(torch.cat([s['g'], s['gh'], s['gs']], 1))
|
| 82 |
+
velocity = self.steering(s['g']) + 15*torch.tanh(delta[:, 8:])
|
| 83 |
+
departure = base.departure_grid(s['g'], velocity, self.lat, 2.5)
|
| 84 |
+
g = base.sample_field(s['g'], departure) + .2*torch.tanh(delta[:, :8])
|
| 85 |
+
gh = self.coarse_memory(base.sample_field(s['gh'], departure), features)
|
| 86 |
+
at = self.basin_grid(s['center'][:, 0, None, None], s['center'][:, 1, None, None])
|
| 87 |
+
local = base.sample_field(torch.cat([gh, g], 1), at)[:, :, 0, 0]
|
| 88 |
+
conditioning = torch.cat([s['motion']/100, s['issue_mask']], 1)
|
| 89 |
+
tendencies = self.motion_net(torch.cat([local, conditioning], 1))
|
| 90 |
+
flow = base.sample_field(velocity, at)[:, :, 0, 0]
|
| 91 |
+
motion = .7*flow*21.6 + .3*s['motion'] + 100*torch.tanh(tendencies[:, :2])
|
| 92 |
+
origin = s['center'] + torch.stack([motion[:, 1]/111.2,
|
| 93 |
+
motion[:, 0]/(111.2*s['center'][:, 0].deg2rad().cos().clamp_min(.2))], 1)
|
| 94 |
+
lat, lon = self.coordinates(origin)
|
| 95 |
+
grid = self.basin_grid(lat, lon)
|
| 96 |
+
environment = base.sample_field(g, grid)
|
| 97 |
+
static = base.sample_field(s['gs'], grid)
|
| 98 |
+
# Translate the moving frame without resampling away bulk storm motion.
|
| 99 |
+
old_lat, old_lon = self.coordinates(s['origin'])
|
| 100 |
+
old_grid = self.basin_grid(old_lat, old_lon)
|
| 101 |
+
old_environment = base.sample_field(s['g'], old_grid)
|
| 102 |
+
rd, rf = self.core_net(torch.cat([s['core'], old_environment, s['ch'], static], 1))
|
| 103 |
+
local_flow = base.sample_field(velocity, grid) + 5*torch.tanh(rd[:, 1:])
|
| 104 |
+
relative = local_flow - (motion/21.6)[:, :, None, None]
|
| 105 |
+
shift = (s['center']-s['origin'])
|
| 106 |
+
source_lat = old_lat + shift[:, 0, None, None] - relative[:, 1]*21.6/111.2
|
| 107 |
+
source_lon = old_lon + shift[:, 1, None, None] - relative[:, 0]*21.6/(111.2*old_lat.deg2rad().cos().clamp_min(.2))
|
| 108 |
+
dep = self.core_grid(source_lat, source_lon, s['origin'])
|
| 109 |
+
anomaly = base.sample_field(s['anomaly'], dep, 'zeros') + .1*rd[:, :1]
|
| 110 |
+
core = environment[:, :1] + anomaly*self.taper
|
| 111 |
+
ch = self.core_memory(base.sample_field(s['ch'], dep, 'zeros'), rf)
|
| 112 |
+
physical = core*self.std[:, :1]+self.mean[:, :1]
|
| 113 |
+
# Field-based association, constrained to this storm's local neighborhood.
|
| 114 |
+
score = -physical[:, 0]/2 - (self.east.square()+self.north.square())/(2*180**2)
|
| 115 |
+
score = score.masked_fill((self.east.square()+self.north.square()) > 300**2, -1e9)
|
| 116 |
+
pdf = score.flatten(1).softmax(1).reshape_as(score)
|
| 117 |
+
center = torch.stack([(pdf*lat).sum((1,2)), (pdf*lon).sum((1,2))], 1)
|
| 118 |
+
cg = self.core_grid(center[:, 0, None, None], center[:, 1, None, None], origin)
|
| 119 |
+
pressure = base.sample_field(physical, cg)[:, 0, 0, 0]
|
| 120 |
+
rlat, rlon = s['rs'][:, 0]*90, (s['rs'][:, 1]+1)*180
|
| 121 |
+
rg = self.basin_grid(rlat, rlon)
|
| 122 |
+
sampling = self.core_grid(rlat, rlon, origin)
|
| 123 |
+
reconstructed = base.sample_field(g[:, :1], rg) + base.sample_field(anomaly*self.taper, sampling, 'zeros')
|
| 124 |
+
# Resolved basin output remains at source resolution; reconstruction has
|
| 125 |
+
# separate provenance and is never relabeled as raw coarse analysis.
|
| 126 |
+
vmax = (s['vmax']+5*tendencies[:, 2]).clamp_min(0)
|
| 127 |
+
valid = (grid.abs()<=1).all(-1)[:, None]
|
| 128 |
+
out = dict(global_=g, regional=reconstructed, regional_valid=(rg.abs()<=1).all(-1)[:,None],
|
| 129 |
+
core=core, core_lat=lat, core_lon=lon, core_valid=valid,
|
| 130 |
+
center=center, pressure=pressure, grid_pressure=pressure, vmax=vmax,
|
| 131 |
+
track_valid=(center[:,0]>0)&(center[:,0]<60)&(center[:,1]>100)&(center[:,1]<180),
|
| 132 |
+
native_route=torch.ones_like(pressure,dtype=torch.bool),
|
| 133 |
+
pressure_tendency=pressure-base.sample_field(s['core']*self.std[:,:1]+self.mean[:,:1],
|
| 134 |
+
self.core_grid(s['center'][:,0,None,None],s['center'][:,1,None,None],s['origin']))[:,0,0,0])
|
| 135 |
+
out['global']=out.pop('global_')
|
| 136 |
+
return dict(s,g=g,gh=gh,core=core,ch=ch,anomaly=anomaly,origin=origin,center=center,motion=motion,vmax=vmax), out
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def objective(out, target, inputs, manifest):
|
| 140 |
+
terms={}
|
| 141 |
+
area=inputs['global_static'][:,:1].mul(90).deg2rad().cos().clamp_min(0)
|
| 142 |
+
terms['environment']=weighted(F.smooth_l1_loss(out['global'],target['global'],reduction='none'),area*target['global_mask'])
|
| 143 |
+
# Reanalysis does not resolve the observed central pressure. Exclude the
|
| 144 |
+
# inner 150 km from absolute reconstruction targets instead of erasing it.
|
| 145 |
+
lat,lon=inputs['regional_static'][:,0]*90,(inputs['regional_static'][:,1]+1)*180
|
| 146 |
+
ct=target['center']
|
| 147 |
+
d2=((lat-ct[:,0,None,None])*111.2).square()+((lon-ct[:,1,None,None])*111.2*ct[:,0,None,None].deg2rad().cos()).square()
|
| 148 |
+
mask=target['regional_mask']*out['regional_valid']*(d2>=150**2)[:,None]
|
| 149 |
+
terms['regional']=weighted(F.smooth_l1_loss(out['regional'],target['regional'],reduction='none'),mask)
|
| 150 |
+
for axis in (-2,-1):
|
| 151 |
+
pred=out['regional'].diff(dim=axis);truth=target['regional'].diff(dim=axis)
|
| 152 |
+
w=mask.narrow(axis,0,pred.shape[axis])*mask.narrow(axis,1,pred.shape[axis])
|
| 153 |
+
terms['regional']=terms['regional']+.2*weighted((pred-truth).abs(),w)
|
| 154 |
+
displacement=(out['center']-ct)*torch.stack([torch.full_like(ct[:,0],111.2),111.2*ct[:,0].deg2rad().cos()],1)
|
| 155 |
+
terms['route']=weighted(F.smooth_l1_loss(displacement/100,torch.zeros_like(displacement),reduction='none'),target['storm_mask'][:,None])
|
| 156 |
+
terms['pressure']=weighted(F.smooth_l1_loss(out['pressure']/20,target['pressure']/20,reduction='none'),target['pressure_mask'])
|
| 157 |
+
terms['wind']=weighted(F.smooth_l1_loss(out['vmax']/30,target['vmax']/30,reduction='none'),target['vmax_mask'])
|
| 158 |
+
return terms['environment']+terms['regional']+.2*terms['route']+.5*terms['pressure']+.05*terms['wind'],terms
|
models/trackformer_1_2_field/manifest.json
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"public_version": "1.2",
|
| 3 |
+
"release_status": "research_candidate_not_operational",
|
| 4 |
+
"source_checkpoint_version": "1.2.73",
|
| 5 |
+
"source_checkpoint_epoch": 4,
|
| 6 |
+
"architecture": "v173-moving-core-multiscale-attention",
|
| 7 |
+
"source_checkpoint_sha256": "f194a23d3f91ea76ad776dfad942fabd669eeae8b3fd665815463095367e9ee0",
|
| 8 |
+
"inference_weights_sha256": "db49f36e85a3766defc4c172746897a1f783705d1ce8e6f9dfb8e87ae1d902cb",
|
| 9 |
+
"dataset_sha256": "04fd0d30620137aad20173dcd59e22da2a6c20fae2f17de593e91a59517459c1",
|
| 10 |
+
"source_module_sha256": {
|
| 11 |
+
"model.py": "5dab06c20224cf48c51302122455ee7e16948f977bf4b760fd8aff5d443ab0bc",
|
| 12 |
+
"baseline_model.py": "6c05941fd93baaca04508877edc69f8f0394b70e0a64e734ef0d2c1e8832246a",
|
| 13 |
+
"v165_base.py": "5c9473993a19d0fed00055494b5c1f50c1006aaf46551ff50145f67048c3374a"
|
| 14 |
+
},
|
| 15 |
+
"data_contract": {
|
| 16 |
+
"channels": [
|
| 17 |
+
"mslp",
|
| 18 |
+
"hgt500",
|
| 19 |
+
"uwnd850",
|
| 20 |
+
"vwnd850",
|
| 21 |
+
"uwnd500",
|
| 22 |
+
"vwnd500",
|
| 23 |
+
"uwnd200",
|
| 24 |
+
"vwnd200"
|
| 25 |
+
],
|
| 26 |
+
"units": [
|
| 27 |
+
"hPa",
|
| 28 |
+
"m",
|
| 29 |
+
"m/s",
|
| 30 |
+
"m/s",
|
| 31 |
+
"m/s",
|
| 32 |
+
"m/s",
|
| 33 |
+
"m/s",
|
| 34 |
+
"m/s"
|
| 35 |
+
],
|
| 36 |
+
"global_lat": [
|
| 37 |
+
60.0,
|
| 38 |
+
57.5,
|
| 39 |
+
55.0,
|
| 40 |
+
52.5,
|
| 41 |
+
50.0,
|
| 42 |
+
47.5,
|
| 43 |
+
45.0,
|
| 44 |
+
42.5,
|
| 45 |
+
40.0,
|
| 46 |
+
37.5,
|
| 47 |
+
35.0,
|
| 48 |
+
32.5,
|
| 49 |
+
30.0,
|
| 50 |
+
27.5,
|
| 51 |
+
25.0,
|
| 52 |
+
22.5,
|
| 53 |
+
20.0,
|
| 54 |
+
17.5,
|
| 55 |
+
15.0,
|
| 56 |
+
12.5,
|
| 57 |
+
10.0,
|
| 58 |
+
7.5,
|
| 59 |
+
5.0,
|
| 60 |
+
2.5,
|
| 61 |
+
0.0
|
| 62 |
+
],
|
| 63 |
+
"global_lon": [
|
| 64 |
+
100.0,
|
| 65 |
+
102.5,
|
| 66 |
+
105.0,
|
| 67 |
+
107.5,
|
| 68 |
+
110.0,
|
| 69 |
+
112.5,
|
| 70 |
+
115.0,
|
| 71 |
+
117.5,
|
| 72 |
+
120.0,
|
| 73 |
+
122.5,
|
| 74 |
+
125.0,
|
| 75 |
+
127.5,
|
| 76 |
+
130.0,
|
| 77 |
+
132.5,
|
| 78 |
+
135.0,
|
| 79 |
+
137.5,
|
| 80 |
+
140.0,
|
| 81 |
+
142.5,
|
| 82 |
+
145.0,
|
| 83 |
+
147.5,
|
| 84 |
+
150.0,
|
| 85 |
+
152.5,
|
| 86 |
+
155.0,
|
| 87 |
+
157.5,
|
| 88 |
+
160.0,
|
| 89 |
+
162.5,
|
| 90 |
+
165.0,
|
| 91 |
+
167.5,
|
| 92 |
+
170.0,
|
| 93 |
+
172.5,
|
| 94 |
+
175.0,
|
| 95 |
+
177.5,
|
| 96 |
+
180.0
|
| 97 |
+
],
|
| 98 |
+
"regional_lat": [
|
| 99 |
+
15.0,
|
| 100 |
+
14.75,
|
| 101 |
+
14.5,
|
| 102 |
+
14.25,
|
| 103 |
+
14.0,
|
| 104 |
+
13.75,
|
| 105 |
+
13.5,
|
| 106 |
+
13.25,
|
| 107 |
+
13.0,
|
| 108 |
+
12.75,
|
| 109 |
+
12.5,
|
| 110 |
+
12.25,
|
| 111 |
+
12.0,
|
| 112 |
+
11.75,
|
| 113 |
+
11.5,
|
| 114 |
+
11.25,
|
| 115 |
+
11.0,
|
| 116 |
+
10.75,
|
| 117 |
+
10.5,
|
| 118 |
+
10.25,
|
| 119 |
+
10.0,
|
| 120 |
+
9.75,
|
| 121 |
+
9.5,
|
| 122 |
+
9.25,
|
| 123 |
+
9.0,
|
| 124 |
+
8.75,
|
| 125 |
+
8.5,
|
| 126 |
+
8.25,
|
| 127 |
+
8.0,
|
| 128 |
+
7.75,
|
| 129 |
+
7.5,
|
| 130 |
+
7.25,
|
| 131 |
+
7.0,
|
| 132 |
+
6.75,
|
| 133 |
+
6.5,
|
| 134 |
+
6.25,
|
| 135 |
+
6.0,
|
| 136 |
+
5.75,
|
| 137 |
+
5.5,
|
| 138 |
+
5.25,
|
| 139 |
+
5.0,
|
| 140 |
+
4.75,
|
| 141 |
+
4.5,
|
| 142 |
+
4.25,
|
| 143 |
+
4.0,
|
| 144 |
+
3.75,
|
| 145 |
+
3.5,
|
| 146 |
+
3.25,
|
| 147 |
+
3.0,
|
| 148 |
+
2.75,
|
| 149 |
+
2.5,
|
| 150 |
+
2.25,
|
| 151 |
+
2.0,
|
| 152 |
+
1.75,
|
| 153 |
+
1.5,
|
| 154 |
+
1.25,
|
| 155 |
+
1.0,
|
| 156 |
+
0.75,
|
| 157 |
+
0.5,
|
| 158 |
+
0.25,
|
| 159 |
+
0.0,
|
| 160 |
+
-0.25,
|
| 161 |
+
-0.5,
|
| 162 |
+
-0.75,
|
| 163 |
+
-1.0,
|
| 164 |
+
-1.25,
|
| 165 |
+
-1.5,
|
| 166 |
+
-1.75,
|
| 167 |
+
-2.0,
|
| 168 |
+
-2.25,
|
| 169 |
+
-2.5,
|
| 170 |
+
-2.75,
|
| 171 |
+
-3.0,
|
| 172 |
+
-3.25,
|
| 173 |
+
-3.5,
|
| 174 |
+
-3.75,
|
| 175 |
+
-4.0,
|
| 176 |
+
-4.25,
|
| 177 |
+
-4.5,
|
| 178 |
+
-4.75,
|
| 179 |
+
-5.0,
|
| 180 |
+
-5.25,
|
| 181 |
+
-5.5,
|
| 182 |
+
-5.75,
|
| 183 |
+
-6.0,
|
| 184 |
+
-6.25,
|
| 185 |
+
-6.5,
|
| 186 |
+
-6.75,
|
| 187 |
+
-7.0,
|
| 188 |
+
-7.25,
|
| 189 |
+
-7.5,
|
| 190 |
+
-7.75,
|
| 191 |
+
-8.0,
|
| 192 |
+
-8.25,
|
| 193 |
+
-8.5,
|
| 194 |
+
-8.75,
|
| 195 |
+
-9.0,
|
| 196 |
+
-9.25,
|
| 197 |
+
-9.5,
|
| 198 |
+
-9.75,
|
| 199 |
+
-10.0,
|
| 200 |
+
-10.25,
|
| 201 |
+
-10.5,
|
| 202 |
+
-10.75,
|
| 203 |
+
-11.0,
|
| 204 |
+
-11.25,
|
| 205 |
+
-11.5,
|
| 206 |
+
-11.75,
|
| 207 |
+
-12.0,
|
| 208 |
+
-12.25,
|
| 209 |
+
-12.5,
|
| 210 |
+
-12.75,
|
| 211 |
+
-13.0,
|
| 212 |
+
-13.25,
|
| 213 |
+
-13.5,
|
| 214 |
+
-13.75,
|
| 215 |
+
-14.0,
|
| 216 |
+
-14.25,
|
| 217 |
+
-14.5,
|
| 218 |
+
-14.75,
|
| 219 |
+
-15.0
|
| 220 |
+
],
|
| 221 |
+
"regional_lon": [
|
| 222 |
+
-15.0,
|
| 223 |
+
-14.75,
|
| 224 |
+
-14.5,
|
| 225 |
+
-14.25,
|
| 226 |
+
-14.0,
|
| 227 |
+
-13.75,
|
| 228 |
+
-13.5,
|
| 229 |
+
-13.25,
|
| 230 |
+
-13.0,
|
| 231 |
+
-12.75,
|
| 232 |
+
-12.5,
|
| 233 |
+
-12.25,
|
| 234 |
+
-12.0,
|
| 235 |
+
-11.75,
|
| 236 |
+
-11.5,
|
| 237 |
+
-11.25,
|
| 238 |
+
-11.0,
|
| 239 |
+
-10.75,
|
| 240 |
+
-10.5,
|
| 241 |
+
-10.25,
|
| 242 |
+
-10.0,
|
| 243 |
+
-9.75,
|
| 244 |
+
-9.5,
|
| 245 |
+
-9.25,
|
| 246 |
+
-9.0,
|
| 247 |
+
-8.75,
|
| 248 |
+
-8.5,
|
| 249 |
+
-8.25,
|
| 250 |
+
-8.0,
|
| 251 |
+
-7.75,
|
| 252 |
+
-7.5,
|
| 253 |
+
-7.25,
|
| 254 |
+
-7.0,
|
| 255 |
+
-6.75,
|
| 256 |
+
-6.5,
|
| 257 |
+
-6.25,
|
| 258 |
+
-6.0,
|
| 259 |
+
-5.75,
|
| 260 |
+
-5.5,
|
| 261 |
+
-5.25,
|
| 262 |
+
-5.0,
|
| 263 |
+
-4.75,
|
| 264 |
+
-4.5,
|
| 265 |
+
-4.25,
|
| 266 |
+
-4.0,
|
| 267 |
+
-3.75,
|
| 268 |
+
-3.5,
|
| 269 |
+
-3.25,
|
| 270 |
+
-3.0,
|
| 271 |
+
-2.75,
|
| 272 |
+
-2.5,
|
| 273 |
+
-2.25,
|
| 274 |
+
-2.0,
|
| 275 |
+
-1.75,
|
| 276 |
+
-1.5,
|
| 277 |
+
-1.25,
|
| 278 |
+
-1.0,
|
| 279 |
+
-0.75,
|
| 280 |
+
-0.5,
|
| 281 |
+
-0.25,
|
| 282 |
+
0.0,
|
| 283 |
+
0.25,
|
| 284 |
+
0.5,
|
| 285 |
+
0.75,
|
| 286 |
+
1.0,
|
| 287 |
+
1.25,
|
| 288 |
+
1.5,
|
| 289 |
+
1.75,
|
| 290 |
+
2.0,
|
| 291 |
+
2.25,
|
| 292 |
+
2.5,
|
| 293 |
+
2.75,
|
| 294 |
+
3.0,
|
| 295 |
+
3.25,
|
| 296 |
+
3.5,
|
| 297 |
+
3.75,
|
| 298 |
+
4.0,
|
| 299 |
+
4.25,
|
| 300 |
+
4.5,
|
| 301 |
+
4.75,
|
| 302 |
+
5.0,
|
| 303 |
+
5.25,
|
| 304 |
+
5.5,
|
| 305 |
+
5.75,
|
| 306 |
+
6.0,
|
| 307 |
+
6.25,
|
| 308 |
+
6.5,
|
| 309 |
+
6.75,
|
| 310 |
+
7.0,
|
| 311 |
+
7.25,
|
| 312 |
+
7.5,
|
| 313 |
+
7.75,
|
| 314 |
+
8.0,
|
| 315 |
+
8.25,
|
| 316 |
+
8.5,
|
| 317 |
+
8.75,
|
| 318 |
+
9.0,
|
| 319 |
+
9.25,
|
| 320 |
+
9.5,
|
| 321 |
+
9.75,
|
| 322 |
+
10.0,
|
| 323 |
+
10.25,
|
| 324 |
+
10.5,
|
| 325 |
+
10.75,
|
| 326 |
+
11.0,
|
| 327 |
+
11.25,
|
| 328 |
+
11.5,
|
| 329 |
+
11.75,
|
| 330 |
+
12.0,
|
| 331 |
+
12.25,
|
| 332 |
+
12.5,
|
| 333 |
+
12.75,
|
| 334 |
+
13.0,
|
| 335 |
+
13.25,
|
| 336 |
+
13.5,
|
| 337 |
+
13.75,
|
| 338 |
+
14.0,
|
| 339 |
+
14.25,
|
| 340 |
+
14.5,
|
| 341 |
+
14.75,
|
| 342 |
+
15.0
|
| 343 |
+
],
|
| 344 |
+
"normalization": {
|
| 345 |
+
"mean": [
|
| 346 |
+
1012.6534350724769,
|
| 347 |
+
5702.17255505101,
|
| 348 |
+
0.6556878249021729,
|
| 349 |
+
0.07710723631313336,
|
| 350 |
+
6.437907875944145,
|
| 351 |
+
-0.22113481896089796,
|
| 352 |
+
14.724588065342962,
|
| 353 |
+
-0.2013532977844505
|
| 354 |
+
],
|
| 355 |
+
"std": [
|
| 356 |
+
8.265883617782512,
|
| 357 |
+
233.83147357071002,
|
| 358 |
+
7.441798736924629,
|
| 359 |
+
5.2934176921269875,
|
| 360 |
+
13.162218957604635,
|
| 361 |
+
7.578773743787778,
|
| 362 |
+
22.626341660579083,
|
| 363 |
+
11.05678874016786
|
| 364 |
+
],
|
| 365 |
+
"fit_split": "train",
|
| 366 |
+
"end_year": 2021
|
| 367 |
+
}
|
| 368 |
+
}
|
| 369 |
+
}
|
models/trackformer_1_2_field/model.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""v173: moving pressure core with multiscale environmental attention.
|
| 2 |
+
|
| 3 |
+
The public track and central pressure are extracted from the evolving core.
|
| 4 |
+
Wind is an auxiliary scalar estimate, not a resolved wind field.
|
| 5 |
+
"""
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
from baseline_model import CoreForecaster as Baseline, objective as baseline_loss, weighted, base
|
| 10 |
+
|
| 11 |
+
VERSION = '1.2.73'
|
| 12 |
+
ARCHITECTURE = 'v173-moving-core-multiscale-attention'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class EnvironmentalAttention(nn.Module):
|
| 16 |
+
def __init__(self):
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.project = nn.Conv2d(44, 64, 1)
|
| 19 |
+
layer = nn.TransformerEncoderLayer(64, 4, 128, dropout=0., batch_first=True,
|
| 20 |
+
norm_first=True)
|
| 21 |
+
self.encoder = nn.TransformerEncoder(layer, 2, enable_nested_tensor=False)
|
| 22 |
+
self.query = nn.Linear(32, 64)
|
| 23 |
+
self.cross = nn.MultiheadAttention(64, 4, dropout=0., batch_first=True)
|
| 24 |
+
self.output = nn.Linear(64, 32)
|
| 25 |
+
nn.init.zeros_(self.output.weight)
|
| 26 |
+
nn.init.zeros_(self.output.bias)
|
| 27 |
+
|
| 28 |
+
def forward(self, state):
|
| 29 |
+
h, w = state['gh'].shape[-2:]
|
| 30 |
+
features = self.project(torch.cat([state['g'], state['gh'], state['gs']], 1))
|
| 31 |
+
tokens = torch.cat([F.avg_pool2d(features, kernel_size=size, stride=size,
|
| 32 |
+
ceil_mode=True).flatten(2)
|
| 33 |
+
for size in (3, 5)], 2).transpose(1, 2)
|
| 34 |
+
tokens = self.encoder(tokens)
|
| 35 |
+
queries = self.query(state['gh'].flatten(2).transpose(1, 2))
|
| 36 |
+
context, _ = self.cross(queries, tokens, tokens, need_weights=False)
|
| 37 |
+
return self.output(context).transpose(1, 2).reshape(-1, 32, h, w)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class CoreForecaster(Baseline):
|
| 41 |
+
def __init__(self, manifest, tiny=False):
|
| 42 |
+
super().__init__(manifest, tiny)
|
| 43 |
+
# Meshgrid views overlap on CPU; checkpoint loading requires owned storage.
|
| 44 |
+
self.east = self.east.clone()
|
| 45 |
+
self.north = self.north.clone()
|
| 46 |
+
self.context = EnvironmentalAttention()
|
| 47 |
+
|
| 48 |
+
def step(self, state):
|
| 49 |
+
conditioned = dict(state, gh=state['gh'] + self.context(state))
|
| 50 |
+
next_state, out = super().step(conditioned)
|
| 51 |
+
out['previous_center'] = state['center']
|
| 52 |
+
out['previous_pressure'] = out['pressure'] - out['pressure_tendency']
|
| 53 |
+
return next_state, out
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def objective(out, target, inputs, manifest):
|
| 57 |
+
loss, terms = baseline_loss(out, target, inputs, manifest)
|
| 58 |
+
if 'previous_pressure' in target:
|
| 59 |
+
mask = target['pressure_mask'] * target['previous_pressure_mask']
|
| 60 |
+
true_delta = target['pressure'] - target['previous_pressure']
|
| 61 |
+
terms['pressure_change'] = weighted(F.smooth_l1_loss(
|
| 62 |
+
out['pressure_tendency']/10, true_delta/10, reduction='none'), mask)
|
| 63 |
+
loss = loss + .25 * terms['pressure_change']
|
| 64 |
+
if 'previous_center' in target:
|
| 65 |
+
center = target['center']
|
| 66 |
+
scale = torch.stack([torch.full_like(center[:, 0], 111.2),
|
| 67 |
+
111.2*center[:, 0].deg2rad().cos()], 1)
|
| 68 |
+
predicted = (out['center']-out['previous_center'])*scale
|
| 69 |
+
truth = (center-target['previous_center'])*scale
|
| 70 |
+
mask = target['storm_mask']*target['previous_storm_mask']
|
| 71 |
+
terms['motion_change'] = weighted(F.smooth_l1_loss(
|
| 72 |
+
predicted/100, truth/100, reduction='none'), mask[:, None])
|
| 73 |
+
loss = loss + .1 * terms['motion_change']
|
| 74 |
+
return loss, terms
|
models/trackformer_1_2_field/predict.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trackformer 1.2 research inference from a causal, normalized issue packet.
|
| 2 |
+
|
| 3 |
+
This wrapper deliberately does not fetch or construct weather inputs. The caller
|
| 4 |
+
must supply past/issue-time analyses on the exact grids in manifest.json.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
from model import CoreForecaster
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
INPUT_SHAPES = {
|
| 19 |
+
"global_history": (9, 8, 25, 33),
|
| 20 |
+
"regional_history": (9, 1, 121, 121),
|
| 21 |
+
"global_static": (4, 25, 33),
|
| 22 |
+
"regional_static": (4, 121, 121),
|
| 23 |
+
"detail_available": (1,),
|
| 24 |
+
"center": (2,),
|
| 25 |
+
"motion": (2,),
|
| 26 |
+
"issue_intensity": (2,),
|
| 27 |
+
"issue_mask": (2,),
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def load_packet(path: Path) -> dict[str, np.ndarray]:
|
| 32 |
+
with np.load(path, allow_pickle=False) as packet:
|
| 33 |
+
if set(packet.files) != set(INPUT_SHAPES) | {"issue_time_ns", "history_time_ns"}:
|
| 34 |
+
raise ValueError("Packet keys must match the documented causal input schema exactly")
|
| 35 |
+
issue = int(packet["issue_time_ns"])
|
| 36 |
+
history = np.asarray(packet["history_time_ns"], dtype=np.int64)
|
| 37 |
+
if history.shape != (9,) or history[-1] != issue or np.any(history > issue):
|
| 38 |
+
raise ValueError("History must contain nine times ending at issue time; future inputs forbidden")
|
| 39 |
+
if not np.array_equal(np.diff(history), np.full(8, 6 * 3600 * 10**9)):
|
| 40 |
+
raise ValueError("History must use consecutive six-hour analyses")
|
| 41 |
+
arrays = {}
|
| 42 |
+
for key, shape in INPUT_SHAPES.items():
|
| 43 |
+
value = np.asarray(packet[key], dtype=np.float32)
|
| 44 |
+
if value.shape != shape or not np.isfinite(value).all():
|
| 45 |
+
raise ValueError(f"{key}: expected finite array of shape {shape}, got {value.shape}")
|
| 46 |
+
arrays[key] = value[None]
|
| 47 |
+
return arrays
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def forecast(packet: Path, model_dir: Path, device: str = "cpu") -> dict[str, np.ndarray]:
|
| 51 |
+
metadata = json.loads((model_dir / "manifest.json").read_text())
|
| 52 |
+
if metadata["public_version"] != "1.2":
|
| 53 |
+
raise ValueError("Unexpected public model version")
|
| 54 |
+
contract = metadata["data_contract"]
|
| 55 |
+
model = CoreForecaster(contract).to(device).eval()
|
| 56 |
+
state = torch.load(model_dir / "weights.pt", map_location="cpu", weights_only=True)
|
| 57 |
+
model.load_state_dict(state, strict=True)
|
| 58 |
+
inputs = {key: torch.from_numpy(value).to(device) for key, value in load_packet(packet).items()}
|
| 59 |
+
with torch.inference_mode():
|
| 60 |
+
running = model.initial(inputs)
|
| 61 |
+
outputs = []
|
| 62 |
+
for _ in range(20):
|
| 63 |
+
running, output = model.step(running)
|
| 64 |
+
outputs.append(output)
|
| 65 |
+
scale = float(contract["normalization"]["std"][0])
|
| 66 |
+
offset = float(contract["normalization"]["mean"][0])
|
| 67 |
+
result = {
|
| 68 |
+
"lead_hours": np.arange(6, 121, 6, dtype=np.int16),
|
| 69 |
+
"track_lat_lon": torch.stack([o["center"][0] for o in outputs]).cpu().numpy(),
|
| 70 |
+
"central_pressure_hpa": torch.stack([o["pressure"][0] for o in outputs]).cpu().numpy(),
|
| 71 |
+
"basin_mslp_hpa": torch.stack([o["global"][0, 0] for o in outputs]).cpu().numpy() * scale + offset,
|
| 72 |
+
"regional_mslp_hpa": torch.stack([o["regional"][0, 0] for o in outputs]).cpu().numpy() * scale + offset,
|
| 73 |
+
}
|
| 74 |
+
if not all(np.isfinite(value).all() for value in result.values()):
|
| 75 |
+
raise ValueError("Non-finite forecast")
|
| 76 |
+
return result
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def main() -> None:
|
| 80 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 81 |
+
parser.add_argument("packet", type=Path, help="Causal normalized .npz issue packet")
|
| 82 |
+
parser.add_argument("output", type=Path, help="Output .npz path")
|
| 83 |
+
parser.add_argument("--device", default="cpu", choices=("cpu", "mps", "cuda"))
|
| 84 |
+
args = parser.parse_args()
|
| 85 |
+
result = forecast(args.packet, Path(__file__).resolve().parent, args.device)
|
| 86 |
+
np.savez_compressed(args.output, **result)
|
| 87 |
+
print(f"Saved 20 six-hour forecasts to {args.output}")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
main()
|
models/trackformer_1_2_field/v165_base.py
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Standalone v1.2.65. Existing full archives; no web downloads or pilot fallback."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import random
|
| 12 |
+
import socket
|
| 13 |
+
import time
|
| 14 |
+
from contextlib import nullcontext
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from torch import nn
|
| 19 |
+
from torch.nn import functional as F
|
| 20 |
+
from torch.utils.checkpoint import checkpoint
|
| 21 |
+
from torch.utils.data import Dataset, DataLoader
|
| 22 |
+
|
| 23 |
+
ROOT = Path(__file__).resolve().parent
|
| 24 |
+
HOUR = 3_600_000_000_000
|
| 25 |
+
|
| 26 |
+
def digest(path):
|
| 27 |
+
h = hashlib.sha256()
|
| 28 |
+
with Path(path).open("rb") as f:
|
| 29 |
+
for block in iter(lambda: f.read(8 * 1024**2), b""):
|
| 30 |
+
h.update(block)
|
| 31 |
+
return h.hexdigest()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def atomic_json(path, data):
|
| 35 |
+
path = Path(path)
|
| 36 |
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
| 37 |
+
tmp.write_text(json.dumps(data, indent=2, allow_nan=False) + "\n")
|
| 38 |
+
tmp.replace(path)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def atomic_checkpoint(path, data):
|
| 42 |
+
path = Path(path)
|
| 43 |
+
tmp = path.with_suffix(".tmp")
|
| 44 |
+
with tmp.open("wb") as f:
|
| 45 |
+
torch.save(data, f)
|
| 46 |
+
f.flush()
|
| 47 |
+
os.fsync(f.fileno())
|
| 48 |
+
tmp.replace(path)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def device_for(name):
|
| 52 |
+
if name == "auto":
|
| 53 |
+
name = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 54 |
+
if name == "cuda" and not torch.cuda.is_available():
|
| 55 |
+
raise RuntimeError("CUDA unavailable in this Python. Install a CUDA PyTorch wheel before training.")
|
| 56 |
+
if name == "mps" and not torch.backends.mps.is_available():
|
| 57 |
+
raise RuntimeError("MPS requested but unavailable")
|
| 58 |
+
return torch.device(name)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
"""Embedded in the standalone v164 trainer: coarse archive plus native MSLP patches."""
|
| 62 |
+
REUSE_ARCH = 'wp-coarse8-native-pressure1-v164'
|
| 63 |
+
REUSE_CHANNELS = ['mslp', 'hgt500', 'uwnd850', 'vwnd850', 'uwnd500', 'vwnd500', 'uwnd200', 'vwnd200']
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def load_reuse(path):
|
| 67 |
+
path = Path(path)
|
| 68 |
+
if not path.is_file():
|
| 69 |
+
raise FileNotFoundError('Combined dataset missing. Run the updated Drive setup cell first: '+str(path))
|
| 70 |
+
m = json.loads(path.read_text())
|
| 71 |
+
if m.get('schema') != 'v164-reuse-pressure-v1' or m.get('pilot', True):
|
| 72 |
+
raise ValueError('Combined non-pilot archive required; no pilot fallback')
|
| 73 |
+
for name, entry in m['files'].items():
|
| 74 |
+
p = path.parent/entry['path']
|
| 75 |
+
print('Checking dataset file:', name, flush=True)
|
| 76 |
+
if digest(p) != entry['sha256']:
|
| 77 |
+
raise ValueError('Dataset checksum mismatch: '+name)
|
| 78 |
+
entry['resolved'] = str(p)
|
| 79 |
+
with np.load(m['files']['basin']['resolved'], allow_pickle=False) as z:
|
| 80 |
+
if z['channels'].tolist() != REUSE_CHANNELS[1:]:
|
| 81 |
+
raise ValueError('Coarse channel order mismatch')
|
| 82 |
+
times, lat, lon = z['time'], z['lat'], z['lon']
|
| 83 |
+
q = z['q']
|
| 84 |
+
scale, offset = z['scale'], z['offset']
|
| 85 |
+
if q.shape != (len(times),7,25,33) or not np.all(np.diff(times) == 6*HOUR):
|
| 86 |
+
raise ValueError('Coarse grid/time mismatch')
|
| 87 |
+
qpath = path.parent/'basin_q_verified.npy'
|
| 88 |
+
# Refresh the compact worker mmap from the checksum-verified source every preflight.
|
| 89 |
+
temporary = qpath.with_suffix('.pending.npy')
|
| 90 |
+
np.save(temporary, q)
|
| 91 |
+
os.replace(temporary, qpath)
|
| 92 |
+
slp = np.load(m['files']['slp']['resolved'], mmap_mode='r')
|
| 93 |
+
if slp.shape != (len(times),25,33) or not np.isfinite(slp).all():
|
| 94 |
+
raise ValueError('Coarse pressure coverage invalid')
|
| 95 |
+
with np.load(m['files']['track']['resolved'], allow_pickle=False) as z:
|
| 96 |
+
track = {k:z[k] for k in ['base_time','storm_id','base_lat','base_lon','target','target_mask']}
|
| 97 |
+
issue_intensity = z['track'][:,-1,4:6]*z['track_std'][4:6]+z['track_mean'][4:6]
|
| 98 |
+
plan = json.loads(Path(m['files']['plan']['resolved']).read_text())
|
| 99 |
+
if len(plan['rows']) != 1000 or plan['shape'] != [1000,29,121,121] or plan['lead_hours'] != list(range(-48,121,6)):
|
| 100 |
+
raise ValueError('Expected the verified 1000-window native pressure package, not the six-sample pilot')
|
| 101 |
+
pressure = np.load(m['files']['pressure']['resolved'], mmap_mode='r')
|
| 102 |
+
if pressure.shape != (1000,29,121,121):
|
| 103 |
+
raise ValueError('Native pressure shape mismatch')
|
| 104 |
+
patches = {}
|
| 105 |
+
for pi,row in enumerate(plan['rows']):
|
| 106 |
+
ti = row['track_archive_row']
|
| 107 |
+
if int(track['base_time'][ti]) != row['issue_ns'] or str(track['storm_id'][ti]) != row['storm_id']:
|
| 108 |
+
raise ValueError('Native patch/track identity mismatch')
|
| 109 |
+
patches[ti] = pi
|
| 110 |
+
first_year = {}
|
| 111 |
+
years = track['base_time'].astype('datetime64[ns]').astype('datetime64[Y]').astype(int)+1970
|
| 112 |
+
for sid,y in zip(track['storm_id'],years):
|
| 113 |
+
first_year[str(sid)] = min(first_year.get(str(sid),9999),int(y))
|
| 114 |
+
lookup = {(str(s),int(t)):i for i,(s,t) in enumerate(zip(track['storm_id'],track['base_time']))}
|
| 115 |
+
rows = []
|
| 116 |
+
for i,ns in enumerate(track['base_time']):
|
| 117 |
+
sid = str(track['storm_id'][i])
|
| 118 |
+
y = first_year[sid]
|
| 119 |
+
split = 'train' if 2000 <= y <= 2021 else 'validation' if 2022 <= y <= 2023 else 'test' if 2024 <= y <= 2025 else None
|
| 120 |
+
if split is None:
|
| 121 |
+
continue
|
| 122 |
+
low,high = {'train':(2000,2021),'validation':(2022,2023),'test':(2024,2025)}[split]
|
| 123 |
+
bounds = np.array([ns-48*HOUR,ns+120*HOUR],dtype='int64').astype('datetime64[ns]').astype('datetime64[Y]').astype(int)+1970
|
| 124 |
+
ai = int(np.searchsorted(times,ns))
|
| 125 |
+
center = [float(track['base_lat'][i]),float(track['base_lon'][i])%360]
|
| 126 |
+
if bounds[0] < low or bounds[1] > high or ai < 8 or ai+20 >= len(times) or times[ai] != ns:
|
| 127 |
+
continue
|
| 128 |
+
if not np.isfinite(center).all() or not (0 < center[0] < 60 and 100 < center[1] < 180):
|
| 129 |
+
continue
|
| 130 |
+
previous = lookup.get((sid,int(ns-6*HOUR)))
|
| 131 |
+
motion = [0.,0.]
|
| 132 |
+
if previous is not None:
|
| 133 |
+
old = [float(track['base_lat'][previous]),float(track['base_lon'][previous])%360]
|
| 134 |
+
if np.isfinite(old).all():
|
| 135 |
+
motion = [(center[1]-old[1])*111.2*np.cos(np.deg2rad(center[0])),(center[0]-old[0])*111.2]
|
| 136 |
+
future = [lookup.get((sid,int(ns+j*6*HOUR))) for j in range(1,21)]
|
| 137 |
+
target_centers = [[float(track['base_lat'][j]),float(track['base_lon'][j])%360] if j is not None else [0.,0.] for j in future]
|
| 138 |
+
rm = [float(j is not None and np.isfinite(target_centers[k]).all()) for k,j in enumerate(future)]
|
| 139 |
+
target_centers = np.nan_to_num(target_centers).tolist()
|
| 140 |
+
wind,p = track['target'][i,:,2],track['target'][i,:,3]
|
| 141 |
+
wm = track['target_mask'][i,:,2].astype(bool)&np.isfinite(wind)&(wind>=0)&(wind<250)
|
| 142 |
+
pm = track['target_mask'][i,:,3].astype(bool)&np.isfinite(p)&(p>800)&(p<1100)
|
| 143 |
+
pi = patches.get(i,-1)
|
| 144 |
+
if pi >= 0 and plan['rows'][pi]['split'] != split:
|
| 145 |
+
raise ValueError('Patch split mismatch')
|
| 146 |
+
issue = issue_intensity[i]
|
| 147 |
+
iv = [bool(np.isfinite(issue[0]) and 0<=issue[0]<250),bool(np.isfinite(issue[1]) and 800<issue[1]<1100)]
|
| 148 |
+
rows.append({'split':split,'storm_id':sid,'atlas':ai,'patch':pi,'center':center,'motion':motion,
|
| 149 |
+
'issue_intensity':[float(issue[k]) if iv[k] else 0. for k in range(2)],'issue_mask':iv,
|
| 150 |
+
'target_centers':target_centers,'route_mask':rm,
|
| 151 |
+
'pressure':np.where(pm,p,0).tolist(),'pressure_mask':pm.tolist(),
|
| 152 |
+
'vmax':np.where(wm,wind,0).tolist(),'vmax_mask':wm.tolist()})
|
| 153 |
+
counts = {s:sum(r['split']==s for r in rows) for s in ['train','validation','test']}
|
| 154 |
+
patch_counts = {s:sum(r['split']==s and r['patch']>=0 for r in rows) for s in counts}
|
| 155 |
+
if counts['train'] < 10000 or patch_counts != {'train':800,'validation':100,'test':100}:
|
| 156 |
+
raise ValueError(f'Incomplete combined coverage: {counts}, native patches {patch_counts}')
|
| 157 |
+
train_times = np.flatnonzero((times.astype('datetime64[ns]').astype('datetime64[Y]').astype(int)+1970>=2000)&
|
| 158 |
+
(times.astype('datetime64[ns]').astype('datetime64[Y]').astype(int)+1970<=2021))
|
| 159 |
+
sums,squares = np.zeros(8),np.zeros(8)
|
| 160 |
+
n = 0
|
| 161 |
+
for start in range(0,len(train_times),256):
|
| 162 |
+
ii = train_times[start:start+256]
|
| 163 |
+
b = np.concatenate([np.asarray(slp[ii],dtype='float32')[:,None],q[ii].astype('float32')*scale[None,:,None,None]+offset[None,:,None,None]],1).astype('float64')
|
| 164 |
+
if not np.isfinite(b).all():
|
| 165 |
+
raise ValueError('Nonfinite coarse training fields')
|
| 166 |
+
sums += b.sum((0,2,3)); squares += (b*b).sum((0,2,3)); n += len(ii)*25*33
|
| 167 |
+
mean = sums/n
|
| 168 |
+
std = np.maximum(np.sqrt(np.maximum(squares/n-mean*mean,0)),1e-4)
|
| 169 |
+
m.update(rows=rows, plan=plan, qpath=str(qpath), scale=scale.tolist(), offset=offset.tolist(),
|
| 170 |
+
channels=REUSE_CHANNELS,units=['hPa','m','m/s','m/s','m/s','m/s','m/s','m/s'],
|
| 171 |
+
global_lat=lat.tolist(),global_lon=lon.tolist(),regional_lat=list(np.linspace(15,-15,121)),
|
| 172 |
+
regional_lon=list(np.linspace(-15,15,121)),normalization={'mean':mean.tolist(),'std':std.tolist(),'fit_split':'train','end_year':2021},
|
| 173 |
+
identity=digest(path),counts=counts,patch_counts=patch_counts)
|
| 174 |
+
print(json.dumps({'all_archive_windows':counts,'native_pressure_windows':patch_counts,'architecture':REUSE_ARCH}),flush=True)
|
| 175 |
+
return m
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class ReuseDataset(Dataset):
|
| 179 |
+
def __init__(self,m,split,training=False):
|
| 180 |
+
self.m = m
|
| 181 |
+
self.rows = [r for r in m['rows'] if r['split']==split]
|
| 182 |
+
self.arrays = None
|
| 183 |
+
|
| 184 |
+
def __len__(self):
|
| 185 |
+
return len(self.rows)
|
| 186 |
+
|
| 187 |
+
def __getitem__(self,i):
|
| 188 |
+
m,row = self.m,self.rows[i]
|
| 189 |
+
if self.arrays is None:
|
| 190 |
+
self.arrays = {k:np.load(m['files'][k]['resolved'],mmap_mode='r') for k in ['slp','pressure']}
|
| 191 |
+
self.arrays['q'] = np.load(m['qpath'],mmap_mode='r')
|
| 192 |
+
with np.load(m['files']['geography']['resolved'],allow_pickle=False) as geo:
|
| 193 |
+
self.arrays['land'] = geo['land_fraction']
|
| 194 |
+
self.arrays['height'] = geo['elevation_m']/8000
|
| 195 |
+
ai = row['atlas']
|
| 196 |
+
ii = slice(ai-8,ai+21)
|
| 197 |
+
coarse = np.concatenate([np.array(self.arrays['slp'][ii],dtype='float32')[:,None],
|
| 198 |
+
np.array(self.arrays['q'][ii],dtype='float32')*np.array(m['scale'],dtype='float32')[None,:,None,None]+np.array(m['offset'],dtype='float32')[None,:,None,None]],1)
|
| 199 |
+
mean,std = np.array(m['normalization']['mean'],dtype='float32'),np.array(m['normalization']['std'],dtype='float32')
|
| 200 |
+
coarse = (coarse-mean[None,:,None,None])/std[None,:,None,None]
|
| 201 |
+
pi = row['patch']
|
| 202 |
+
anchor = m['plan']['rows'][pi] if pi>=0 else {'center_lat':round(row['center'][0]*4)/4,'center_lon':round(row['center'][1]*4)/4}
|
| 203 |
+
lat = anchor['center_lat']+np.linspace(15,-15,121,dtype='float32')
|
| 204 |
+
lon = anchor['center_lon']+np.linspace(-15,15,121,dtype='float32')
|
| 205 |
+
yy,xx = np.meshgrid(lat,lon,indexing='ij')
|
| 206 |
+
y = np.rint((90-yy)*4).astype(int); x = np.rint(xx*4).astype(int)%1440
|
| 207 |
+
rs = np.stack([yy/90,xx/180-1,self.arrays['land'][y,x],self.arrays['height'][y,x]]).astype('float32')
|
| 208 |
+
cy,cx = np.meshgrid(m['global_lat'],m['global_lon'],indexing='ij')
|
| 209 |
+
iy = np.rint((90-cy)*4).astype(int); ix = np.rint(cx*4).astype(int)%1440
|
| 210 |
+
gs = np.stack([cy/90,cx/180-1,self.arrays['land'][iy,ix],self.arrays['height'][iy,ix]]).astype('float32')
|
| 211 |
+
detail = np.zeros((29,1,121,121),dtype='float32')
|
| 212 |
+
if pi>=0:
|
| 213 |
+
detail[:,0] = (np.array(self.arrays['pressure'][pi],dtype='float32')-mean[0])/std[0]
|
| 214 |
+
if not np.isfinite(detail).all():
|
| 215 |
+
raise ValueError('Native pressure contains nonfinite fields')
|
| 216 |
+
inputs = {'global_history':coarse[:9], 'regional_history':detail[:9],
|
| 217 |
+
'global_static':gs,'regional_static':rs,'detail_available':np.array([pi>=0],dtype='float32'),
|
| 218 |
+
'center':np.array(row['center'],dtype='float32'),'motion':np.array(row['motion'],dtype='float32'),
|
| 219 |
+
'issue_intensity':np.array(row['issue_intensity'],dtype='float32'),'issue_mask':np.array(row['issue_mask'],dtype='float32')}
|
| 220 |
+
targets = {'global':coarse[9:],'global_mask':np.ones_like(coarse[9:]),
|
| 221 |
+
'regional_lat_weight':np.broadcast_to(np.cos(np.deg2rad(lat))[None,None,:,None],(20,1,121,1)).astype('float32'),
|
| 222 |
+
'regional':detail[9:],'regional_mask':np.full_like(detail[9:],float(pi>=0)),
|
| 223 |
+
'center':np.array(row['target_centers'],dtype='float32'),
|
| 224 |
+
'storm_mask':np.array(row['route_mask'],dtype='float32')}
|
| 225 |
+
for k in ['pressure','pressure_mask','vmax','vmax_mask']:
|
| 226 |
+
targets[k] = np.array(row[k],dtype='float32')
|
| 227 |
+
return {k:torch.from_numpy(v.copy()) for k,v in inputs.items()},{k:torch.from_numpy(v.copy()) for k,v in targets.items()}
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
"""v165 implementation, embedded with verified archive readers by the builder."""
|
| 231 |
+
VERSION = '1.2.65'
|
| 232 |
+
ARCHITECTURE = REUSE_ARCH = 'wp-causal-transport-evolution-field-tracker-v165'
|
| 233 |
+
TRAIN_HORIZONS = [4, 8, 12, 20]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def sample_field(field, grid, padding='border'):
|
| 237 |
+
# Geometry and interpolation stay FP32, including under CUDA autocast.
|
| 238 |
+
with torch.autocast(device_type=field.device.type, enabled=False):
|
| 239 |
+
return F.grid_sample(field.float(), grid.float(), align_corners=True,
|
| 240 |
+
mode='bilinear', padding_mode=padding)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def identity_grid(field):
|
| 244 |
+
h, w = field.shape[-2:]
|
| 245 |
+
yy, xx = torch.meshgrid(torch.linspace(-1, 1, h, device=field.device),
|
| 246 |
+
torch.linspace(-1, 1, w, device=field.device), indexing='ij')
|
| 247 |
+
return torch.stack([xx, yy], -1)[None].expand(field.shape[0], -1, -1, -1)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def departure_grid(field, velocity, latitude, spacing):
|
| 251 |
+
# East/north m/s -> backward departure coordinates on a north-to-south grid.
|
| 252 |
+
h, w = field.shape[-2:]
|
| 253 |
+
u, v = velocity.float().unbind(1)
|
| 254 |
+
dx = u * 21.6 / (111.2 * latitude.float().deg2rad().cos().clamp_min(.2) * spacing)
|
| 255 |
+
dy = -v * 21.6 / (111.2 * spacing)
|
| 256 |
+
return identity_grid(field) - torch.stack([2*dx/(w-1), 2*dy/(h-1)], -1)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class TransportBlock(nn.Module):
|
| 260 |
+
def __init__(self, width):
|
| 261 |
+
super().__init__()
|
| 262 |
+
self.net = nn.Sequential(nn.Conv2d(width, width, 5, padding=2, groups=width),
|
| 263 |
+
nn.GroupNorm(8, width), nn.Conv2d(width, width*4, 1),
|
| 264 |
+
nn.GELU(), nn.Conv2d(width*4, width, 1))
|
| 265 |
+
self.scale = nn.Parameter(torch.full((1, width, 1, 1), .01))
|
| 266 |
+
|
| 267 |
+
def forward(self, x):
|
| 268 |
+
return x + self.scale * self.net(x)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class EvolutionNet(nn.Module):
|
| 272 |
+
def __init__(self, channels, outputs, base=72, tiny=False):
|
| 273 |
+
super().__init__()
|
| 274 |
+
widths = [base, base*2, base*4, base*6]
|
| 275 |
+
depths = [1]*4 if tiny else [2, 2, 4, 4]
|
| 276 |
+
self.stem = nn.Conv2d(channels, base, 3, padding=1)
|
| 277 |
+
self.enc = nn.ModuleList(nn.Sequential(*[TransportBlock(w) for _ in range(d)])
|
| 278 |
+
for w, d in zip(widths, depths))
|
| 279 |
+
self.down = nn.ModuleList(nn.Conv2d(a, b, 3, stride=2, padding=1)
|
| 280 |
+
for a, b in zip(widths, widths[1:]))
|
| 281 |
+
self.up = nn.ModuleList(nn.Conv2d(widths[i+1], widths[i], 1) for i in (2, 1, 0))
|
| 282 |
+
self.dec = nn.ModuleList(TransportBlock(widths[i]) for i in (2, 1, 0))
|
| 283 |
+
self.out = nn.Conv2d(base, outputs, 1)
|
| 284 |
+
self.features = nn.Conv2d(base, 32, 1)
|
| 285 |
+
nn.init.zeros_(self.out.weight)
|
| 286 |
+
nn.init.zeros_(self.out.bias)
|
| 287 |
+
|
| 288 |
+
def block(self, module, x):
|
| 289 |
+
return checkpoint(module, x, use_reentrant=False) if self.training and torch.is_grad_enabled() else module(x)
|
| 290 |
+
|
| 291 |
+
def forward(self, x):
|
| 292 |
+
x = self.stem(x)
|
| 293 |
+
skips = []
|
| 294 |
+
for i, layer in enumerate(self.enc):
|
| 295 |
+
x = self.block(layer, x)
|
| 296 |
+
skips.append(x)
|
| 297 |
+
if i < 3:
|
| 298 |
+
x = self.down[i](x)
|
| 299 |
+
for up, layer, skip in zip(self.up, self.dec, reversed(skips[:-1])):
|
| 300 |
+
x = F.interpolate(up(x), size=skip.shape[-2:], mode='bilinear', align_corners=False)+skip
|
| 301 |
+
x = self.block(layer, x)
|
| 302 |
+
return self.out(x).float(), self.features(x).float()
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class RecurrentFeatures(nn.Module):
|
| 306 |
+
def __init__(self, history_channels):
|
| 307 |
+
super().__init__()
|
| 308 |
+
self.encode = nn.Sequential(nn.Conv2d(history_channels, 32, 3, padding=1),
|
| 309 |
+
nn.GELU(), TransportBlock(32))
|
| 310 |
+
self.gates = nn.Conv2d(64, 64, 3, padding=1)
|
| 311 |
+
self.candidate = nn.Conv2d(64, 32, 3, padding=1)
|
| 312 |
+
|
| 313 |
+
def forward(self, old, features):
|
| 314 |
+
reset, update = torch.sigmoid(self.gates(torch.cat([old, features], 1))).chunk(2, 1)
|
| 315 |
+
proposal = torch.tanh(self.candidate(torch.cat([old*reset, features], 1)))
|
| 316 |
+
return ((1-update)*old + update*proposal).float()
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def track_field(pressure, lat, lon, prior, domain=None):
|
| 320 |
+
"""Associate a local pressure minimum; no independent learned route head."""
|
| 321 |
+
lat0, lon0 = prior[:, 0, None, None], prior[:, 1, None, None]
|
| 322 |
+
distance2 = ((lat-lat0)*111.2).square()+((lon-lon0)*111.2*lat0.deg2rad().cos()).square()
|
| 323 |
+
candidate = distance2 <= 650**2
|
| 324 |
+
if domain is not None:
|
| 325 |
+
candidate = candidate & domain
|
| 326 |
+
score = -pressure/3 - distance2/(2*650**2)
|
| 327 |
+
peak = score.masked_fill(~candidate, -1e9).flatten(1).argmax(1)
|
| 328 |
+
h, w = pressure.shape[-2:]
|
| 329 |
+
y, x = torch.arange(h, device=pressure.device)[None, :, None], torch.arange(w, device=pressure.device)[None, None, :]
|
| 330 |
+
local = ((y-(peak//w)[:, None, None]).abs() <= 1) & ((x-(peak%w)[:, None, None]).abs() <= 1) & candidate
|
| 331 |
+
pdf = torch.softmax(score.masked_fill(~local, -1e9).flatten(1), 1).reshape_as(score)
|
| 332 |
+
center = torch.stack([(pdf*lat).sum((1, 2)), (pdf*lon).sum((1, 2))], 1)
|
| 333 |
+
grid = torch.stack([2*(center[:, 1]-lon[:, 0, 0])/(lon[:, 0, -1]-lon[:, 0, 0])-1,
|
| 334 |
+
2*(center[:, 0]-lat[:, 0, 0])/(lat[:, -1, 0]-lat[:, 0, 0])-1], -1)[:, None, None]
|
| 335 |
+
central = sample_field(pressure[:, None], grid)[:, 0, 0, 0]
|
| 336 |
+
annulus = (distance2 >= 300**2) & (distance2 <= 650**2)
|
| 337 |
+
background = (pressure*annulus).sum((1, 2))/annulus.sum((1, 2)).clamp_min(1)
|
| 338 |
+
interior = (peak//w > 0) & (peak//w < h-1) & (peak%w > 0) & (peak%w < w-1)
|
| 339 |
+
valid = candidate.flatten(1).any(1) & interior & (background-central > 1.)
|
| 340 |
+
return center, central, valid, background-central
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class TransportForecaster(nn.Module):
|
| 344 |
+
def __init__(self, manifest, tiny=False):
|
| 345 |
+
super().__init__()
|
| 346 |
+
base = 8 if tiny else 72
|
| 347 |
+
self.coarse_memory, self.fine_memory = RecurrentFeatures(72), RecurrentFeatures(9)
|
| 348 |
+
self.coarse = EvolutionNet(8+32+4, 8+2, base, tiny)
|
| 349 |
+
self.fine = EvolutionNet(1+8+32+4+1, 1+2, base, tiny)
|
| 350 |
+
self.steering_logits = nn.Parameter(torch.tensor([.4, .4, .2]).log())
|
| 351 |
+
# Wind intensity is explicitly a scalar estimate, not a resolved 10-m wind map.
|
| 352 |
+
self.wind = nn.Sequential(nn.Linear(32+2, 64), nn.GELU(), nn.Linear(64, 1))
|
| 353 |
+
self.register_buffer('mean', torch.tensor(manifest['normalization']['mean'], dtype=torch.float32)[None, :, None, None])
|
| 354 |
+
self.register_buffer('std', torch.tensor(manifest['normalization']['std'], dtype=torch.float32)[None, :, None, None])
|
| 355 |
+
yy, xx = np.meshgrid(manifest['global_lat'], manifest['global_lon'], indexing='ij')
|
| 356 |
+
self.register_buffer('lat', torch.tensor(yy, dtype=torch.float32)[None])
|
| 357 |
+
self.register_buffer('lon', torch.tensor(xx, dtype=torch.float32)[None])
|
| 358 |
+
|
| 359 |
+
def initial(self, inputs):
|
| 360 |
+
required = {'global_history', 'regional_history', 'global_static', 'regional_static',
|
| 361 |
+
'detail_available', 'center', 'motion', 'issue_intensity', 'issue_mask'}
|
| 362 |
+
if set(inputs) != required:
|
| 363 |
+
raise ValueError('Only declared issue-time and historical inputs are allowed')
|
| 364 |
+
gh, rh, rs = inputs['global_history'], inputs['regional_history'], inputs['regional_static']
|
| 365 |
+
grid = torch.stack([((rs[:, 1]+1)*180-100)/40-1, 1-rs[:, 0]*3], -1)
|
| 366 |
+
parent = sample_field(gh[:, -1, :1], grid)
|
| 367 |
+
available = inputs['detail_available'][:, :, None, None]
|
| 368 |
+
r = torch.where(available.bool(), rh[:, -1], parent)
|
| 369 |
+
return dict(g=gh[:, -1], r=r, gh=self.coarse_memory.encode(gh.flatten(1, 2)).float(),
|
| 370 |
+
rh=self.fine_memory.encode(rh.flatten(1, 2)).float(), gs=inputs['global_static'], rs=rs,
|
| 371 |
+
grid=grid, available=available, anchor=(r-parent)*available,
|
| 372 |
+
coordinates=identity_grid(r).permute(0, 3, 1, 2), source=torch.zeros_like(r),
|
| 373 |
+
center=inputs['center'], motion=inputs['motion'], issue=inputs['issue_intensity'],
|
| 374 |
+
issue_mask=inputs['issue_mask'])
|
| 375 |
+
|
| 376 |
+
def steering(self, g):
|
| 377 |
+
physical = g.float()*self.std+self.mean
|
| 378 |
+
winds = physical[:, 2:].reshape(g.shape[0], 3, 2, *g.shape[-2:])
|
| 379 |
+
return (winds*torch.softmax(self.steering_logits, 0)[None, :, None, None, None]).sum(1)
|
| 380 |
+
|
| 381 |
+
def step(self, s):
|
| 382 |
+
delta, features = self.coarse(torch.cat([s['g'], s['gh'], s['gs']], 1))
|
| 383 |
+
velocity = self.steering(s['g']) + 15*torch.tanh(delta[:, 8:])
|
| 384 |
+
departure = departure_grid(s['g'], velocity, self.lat, 2.5)
|
| 385 |
+
g = sample_field(s['g'], departure) + .2*torch.tanh(delta[:, :8])
|
| 386 |
+
gh = self.coarse_memory(sample_field(s['gh'], departure), features)
|
| 387 |
+
parent = sample_field(g, s['grid'])
|
| 388 |
+
fine_velocity = sample_field(velocity, s['grid'])
|
| 389 |
+
r, rh, coordinates, source = s['r'], s['rh'], s['coordinates'], s['source']
|
| 390 |
+
parent_valid = (s['grid'].abs() <= 1).all(-1)[:, None].float()
|
| 391 |
+
if bool(s['available'].any()):
|
| 392 |
+
rd, rf = self.fine(torch.cat([r, parent, rh, s['rs'], parent_valid], 1))
|
| 393 |
+
fine_velocity = fine_velocity + 10*torch.tanh(rd[:, 1:])
|
| 394 |
+
dep = departure_grid(r, fine_velocity, s['rs'][:, 0]*90, .25)
|
| 395 |
+
# Compose material coordinates and sample the ORIGINAL anomaly once per lead.
|
| 396 |
+
# This avoids repeatedly interpolating away its core. Learned source terms
|
| 397 |
+
# can strengthen, weaken or deform it; survival is not hard-coded.
|
| 398 |
+
displacement = coordinates-identity_grid(r).permute(0, 3, 1, 2)
|
| 399 |
+
coordinates = dep.permute(0, 3, 1, 2)+sample_field(displacement, dep)
|
| 400 |
+
source = sample_field(source, dep, 'zeros') + .2*torch.tanh(rd[:, :1])
|
| 401 |
+
anomaly = sample_field(s['anchor'], coordinates.permute(0, 2, 3, 1), 'zeros')+source
|
| 402 |
+
proposed = parent[:, :1]+anomaly*parent_valid
|
| 403 |
+
r = torch.where(s['available'].bool(), proposed, parent[:, :1])
|
| 404 |
+
rh = self.fine_memory(sample_field(rh, dep), rf)
|
| 405 |
+
else:
|
| 406 |
+
r = parent[:, :1]
|
| 407 |
+
# Association prior uses only predicted circulation, never a future center.
|
| 408 |
+
at = torch.stack([(s['center'][:, 1]-100)/40-1, 1-s['center'][:, 0]/30], -1)[:, None, None]
|
| 409 |
+
steering = sample_field(velocity, at)[:, :, 0, 0]
|
| 410 |
+
displacement_km = .7*steering*21.6 + .3*s['motion']
|
| 411 |
+
prior = s['center']+torch.stack([displacement_km[:, 1]/111.2,
|
| 412 |
+
displacement_km[:, 0]/(111.2*s['center'][:, 0].deg2rad().cos().clamp_min(.2))], 1)
|
| 413 |
+
gp, rp = (g*self.std+self.mean)[:, 0], (r*self.std[:, :1]+self.mean[:, :1])[:, 0]
|
| 414 |
+
coarse_center, coarse_p, coarse_ok, coarse_depth = track_field(gp, self.lat, self.lon, prior)
|
| 415 |
+
fine_lat, fine_lon = s['rs'][:, 0]*90, (s['rs'][:, 1]+1)*180
|
| 416 |
+
fine_center, fine_p, fine_ok, fine_depth = track_field(rp, fine_lat, fine_lon, prior, parent_valid[:, 0].bool())
|
| 417 |
+
inside = (prior[:, 0] < fine_lat[:, 0, 0]) & (prior[:, 0] > fine_lat[:, -1, 0]) & \
|
| 418 |
+
(prior[:, 1] > fine_lon[:, 0, 0]) & (prior[:, 1] < fine_lon[:, 0, -1])
|
| 419 |
+
inside = inside & (prior[:, 0] >= 0) & (prior[:, 0] <= 60) & (prior[:, 1] >= 100) & (prior[:, 1] <= 180)
|
| 420 |
+
use_fine = s['available'][:, 0, 0, 0].bool() & inside
|
| 421 |
+
center = torch.where(use_fine[:, None], fine_center, coarse_center)
|
| 422 |
+
pressure = torch.where(use_fine, fine_p, coarse_p)
|
| 423 |
+
ok = torch.where(use_fine, fine_ok, coarse_ok)
|
| 424 |
+
wind_features = torch.cat([gh.mean((2, 3)), s['issue'][:, :1]/100, s['issue_mask'][:, :1]], 1)
|
| 425 |
+
vmax = F.softplus(self.wind(wind_features)[:, 0])*30
|
| 426 |
+
motion = torch.stack([(center[:, 1]-s['center'][:, 1])*111.2*((center[:, 0]+s['center'][:, 0])/2).deg2rad().cos(),
|
| 427 |
+
(center[:, 0]-s['center'][:, 0])*111.2], 1)
|
| 428 |
+
out = dict(global_=g, regional=r, center=center, pressure=pressure, grid_pressure=pressure,
|
| 429 |
+
vmax=vmax, track_valid=ok, native_route=use_fine, regional_valid=parent_valid.bool(),
|
| 430 |
+
pressure_depth=torch.where(use_fine, fine_depth, coarse_depth),
|
| 431 |
+
global_velocity=velocity, regional_velocity=fine_velocity)
|
| 432 |
+
out['global'] = out.pop('global_')
|
| 433 |
+
return dict(s, g=g, r=r, gh=gh, rh=rh, coordinates=coordinates, source=source,
|
| 434 |
+
center=center, motion=motion), out
|
| 435 |
+
|
| 436 |
+
def forward(self, inputs, steps=20):
|
| 437 |
+
state, outputs = self.initial(inputs), []
|
| 438 |
+
for _ in range(steps):
|
| 439 |
+
state, output = self.step(state)
|
| 440 |
+
outputs.append(output)
|
| 441 |
+
return {k: torch.stack([o[k] for o in outputs], 1) for k in outputs[0]}
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def weighted_mean(value, weight):
|
| 445 |
+
return (value*weight).sum()/weight.expand_as(value).sum().clamp_min(1)
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def objective165(output, target, inputs, manifest):
|
| 449 |
+
terms = {}
|
| 450 |
+
for key in ('global', 'regional'):
|
| 451 |
+
pred, truth, mask = output[key].float(), target[key].float(), target[key+'_mask'].float()
|
| 452 |
+
if key == 'regional':
|
| 453 |
+
mask = mask*output['regional_valid']
|
| 454 |
+
latitude = inputs['global_static' if key == 'global' else 'regional_static'][:, :1]*90
|
| 455 |
+
area = latitude.deg2rad().cos().clamp_min(0)*mask
|
| 456 |
+
terms[key] = weighted_mean(F.smooth_l1_loss(pred, truth, reduction='none'), area)
|
| 457 |
+
for axis in (-2, -1):
|
| 458 |
+
a, b = pred.diff(dim=axis), truth.diff(dim=axis)
|
| 459 |
+
w = area.narrow(axis, 0, a.shape[axis])
|
| 460 |
+
terms[key] = terms[key]+.2*weighted_mean((a-b).abs(), w)
|
| 461 |
+
# Labels localize supervision only. They are never passed to initial()/step().
|
| 462 |
+
lat, lon = inputs['regional_static'][:, 0]*90, (inputs['regional_static'][:, 1]+1)*180
|
| 463 |
+
ct = target['center']
|
| 464 |
+
dist2 = ((lat-ct[:, 0, None, None])*111.2).square()+ \
|
| 465 |
+
((lon-ct[:, 1, None, None])*111.2*ct[:, 0, None, None].deg2rad().cos()).square()
|
| 466 |
+
region = (dist2 < 600**2)[:, None]*target['regional_mask']*output['regional_valid']*target['storm_mask'][:, None, None, None]
|
| 467 |
+
p, truth = output['regional'].float(), target['regional'].float()
|
| 468 |
+
terms['storm_field'] = weighted_mean((p-truth).abs(), region)
|
| 469 |
+
# Compare resolved native pressure minima against the SAME resolved target field,
|
| 470 |
+
# not subgrid best-track pressure (e.g. Tip's 875 hPa is absent in this archive).
|
| 471 |
+
local = region.flatten(1).bool()
|
| 472 |
+
pmin = p.flatten(1).masked_fill(~local, 1e4).min(1).values
|
| 473 |
+
tmin = truth.flatten(1).masked_fill(~local, 1e4).min(1).values
|
| 474 |
+
terms['resolved_core'] = weighted_mean((pmin-tmin).abs(), local.any(1).float())
|
| 475 |
+
# Radial-band pressure contrasts retain size/asymmetry information without
|
| 476 |
+
# imposing an idealized vortex or forcing a storm to survive.
|
| 477 |
+
terms['radial_structure'] = 0
|
| 478 |
+
for low, high in ((0, 150), (150, 300), (300, 600)):
|
| 479 |
+
band = ((dist2 >= low**2) & (dist2 < high**2))[:, None]*region
|
| 480 |
+
den = band.sum((1, 2, 3)).clamp_min(1)
|
| 481 |
+
contrast = ((p-truth)*band).sum((1, 2, 3))/den
|
| 482 |
+
terms['radial_structure'] = terms['radial_structure']+weighted_mean(contrast.abs(), (den > 1).float())/3
|
| 483 |
+
displacement = (output['center']-ct)*torch.stack([torch.ones_like(ct[:, 0])*111.2,
|
| 484 |
+
111.2*ct[:, 0].deg2rad().cos()], 1)
|
| 485 |
+
terms['route'] = weighted_mean(F.smooth_l1_loss(displacement/100, torch.zeros_like(displacement), reduction='none'),
|
| 486 |
+
target['storm_mask'][:, None])
|
| 487 |
+
terms['wind'] = weighted_mean(F.smooth_l1_loss(output['vmax']/30, target['vmax']/30, reduction='none'), target['vmax_mask'])
|
| 488 |
+
terms['flow_smooth'] = sum(v.diff(dim=a).abs().mean()/30 for v in
|
| 489 |
+
[output['global_velocity'], output['regional_velocity']] for a in [-2, -1])
|
| 490 |
+
loss = terms['global']+terms['regional']+.5*terms['storm_field']+.2*terms['resolved_core']+ \
|
| 491 |
+
.1*terms['radial_structure']+.1*terms['route']+.05*terms['wind']+.002*terms['flow_smooth']
|
| 492 |
+
return loss, terms
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def training_indices(rows, epoch):
|
| 496 |
+
"""Every coarse window once, plus storm-balanced native replays (~25% native)."""
|
| 497 |
+
rng = np.random.default_rng(165000+epoch)
|
| 498 |
+
indices = list(range(len(rows)))
|
| 499 |
+
groups = {}
|
| 500 |
+
for i, row in enumerate(rows):
|
| 501 |
+
if row['patch'] >= 0:
|
| 502 |
+
groups.setdefault(row['storm_id'], []).append(i)
|
| 503 |
+
native = sum(len(v) for v in groups.values())
|
| 504 |
+
extra = max(0, math.ceil((.25*len(rows)-native)/.75))
|
| 505 |
+
keys = sorted(groups)
|
| 506 |
+
for j in range(extra):
|
| 507 |
+
# Round-robin storms, random window within each storm.
|
| 508 |
+
indices.append(int(rng.choice(groups[keys[j % len(keys)]])))
|
| 509 |
+
rng.shuffle(indices)
|
| 510 |
+
return indices
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def save_training_state(path, model, optimizer, scaler, manifest, epoch, history, best):
|
| 514 |
+
atomic_checkpoint(path, dict(version=VERSION, architecture=ARCHITECTURE, dataset_sha256=manifest['identity'],
|
| 515 |
+
data_contract={k:manifest[k] for k in ('channels', 'units', 'global_lat', 'global_lon', 'regional_lat', 'regional_lon', 'normalization')},
|
| 516 |
+
epoch=epoch, model=model.state_dict(), optimizer=optimizer.state_dict(), scaler=scaler.state_dict(),
|
| 517 |
+
history=history, best_value=best, python_rng=random.getstate(), numpy_rng=np.random.get_state(),
|
| 518 |
+
torch_rng=torch.get_rng_state(), cuda_rng=torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None))
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def restore_training_state(path, model, optimizer, scaler, manifest):
|
| 522 |
+
saved = torch.load(path, map_location='cpu', weights_only=False)
|
| 523 |
+
if saved['architecture'] != ARCHITECTURE or saved['dataset_sha256'] != manifest['identity']:
|
| 524 |
+
raise ValueError('Resume requires the identical v165 architecture and dataset; v164 is not compatible')
|
| 525 |
+
model.load_state_dict(saved['model'])
|
| 526 |
+
optimizer.load_state_dict(saved['optimizer'])
|
| 527 |
+
scaler.load_state_dict(saved['scaler'])
|
| 528 |
+
random.setstate(saved['python_rng']); np.random.set_state(saved['numpy_rng']); torch.set_rng_state(saved['torch_rng'])
|
| 529 |
+
if torch.cuda.is_available() and saved.get('cuda_rng') is not None:
|
| 530 |
+
torch.cuda.set_rng_state_all(saved['cuda_rng'])
|
| 531 |
+
return saved['epoch']+1, saved['history'], saved['best_value']
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def train165(model, m, args, device):
|
| 535 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=.01)
|
| 536 |
+
scaler = torch.amp.GradScaler('cuda', enabled=device.type == 'cuda' and bool(args.amp))
|
| 537 |
+
last, best_path = args.output/'last.pt', args.output/'best.pt'
|
| 538 |
+
start, history, best = 1, [], float('inf')
|
| 539 |
+
if last.is_file():
|
| 540 |
+
start, history, best = restore_training_state(last, model, optimizer, scaler, m)
|
| 541 |
+
print('Resuming completed epoch', start-1, flush=True)
|
| 542 |
+
atomic_json(args.output/'manifest.json', dict(version=VERSION, architecture=ARCHITECTURE,
|
| 543 |
+
parameters=sum(p.numel() for p in model.parameters()), dataset_sha256=m['identity'],
|
| 544 |
+
script_sha256=digest(__file__), samples=m['counts'], native_samples=m['patch_counts'],
|
| 545 |
+
future_weather_as_inputs=False, official_forecasts_as_inputs=False, input_hours=list(range(-48, 1, 6)),
|
| 546 |
+
forecast_hours=list(range(6, 121, 6)), pressure='resolved field at the reported field-derived center',
|
| 547 |
+
native_sampling='all coarse windows plus storm-balanced native replays to 25 percent',
|
| 548 |
+
validation='fixed 120h joint loss, balanced native/coarse strata; no test-set selection',
|
| 549 |
+
physical_microbatch=1, effective_batch=args.batch, tbptt_steps=4,
|
| 550 |
+
limitations=['regional WP, not global', 'native MSLP only on 1000 windows',
|
| 551 |
+
'no fine upper-air variables', 'not an exact conservation solver', 'Tip is a development case']))
|
| 552 |
+
for epoch in range(start, args.epochs+1):
|
| 553 |
+
horizon = TRAIN_HORIZONS[min(epoch-1, len(TRAIN_HORIZONS)-1)]
|
| 554 |
+
metrics = {}
|
| 555 |
+
for split in ('train', 'validation'):
|
| 556 |
+
training = split == 'train'
|
| 557 |
+
model.train(training)
|
| 558 |
+
data = ReuseDataset(m, split)
|
| 559 |
+
sampler = training_indices(data.rows, epoch) if training else None
|
| 560 |
+
loader = DataLoader(data, batch_size=1, sampler=sampler, num_workers=min(args.workers, 2),
|
| 561 |
+
**({'prefetch_factor':1} if args.workers else {}))
|
| 562 |
+
groups, failures = {False:[], True:[]}, []
|
| 563 |
+
optimizer.zero_grad(set_to_none=True)
|
| 564 |
+
began = time.time()
|
| 565 |
+
for index, (inputs, targets) in enumerate(loader, 1):
|
| 566 |
+
inputs = {k:v.to(device) for k, v in inputs.items()}
|
| 567 |
+
steps = horizon if training else 20
|
| 568 |
+
total, block_loss = 0., 0
|
| 569 |
+
with torch.set_grad_enabled(training):
|
| 570 |
+
state = model.initial(inputs)
|
| 571 |
+
for step in range(steps):
|
| 572 |
+
with torch.autocast('cuda', dtype=torch.float16) if scaler.is_enabled() else nullcontext():
|
| 573 |
+
state, output = model.step(state)
|
| 574 |
+
frame = {k:v[:, step].to(device) for k, v in targets.items()}
|
| 575 |
+
loss, terms = objective165(output, frame, inputs, m)
|
| 576 |
+
if not torch.isfinite(loss):
|
| 577 |
+
raise RuntimeError(f'Nonfinite loss epoch={epoch} sample={index} step={step}; no checkpoint advanced')
|
| 578 |
+
total += float(loss.detach())/steps
|
| 579 |
+
failures.append(float((~output['track_valid']).float().mean()))
|
| 580 |
+
if training:
|
| 581 |
+
block_loss = block_loss+loss/(steps*args.batch)
|
| 582 |
+
if (step+1) % 4 == 0 or step+1 == steps:
|
| 583 |
+
scaler.scale(block_loss).backward()
|
| 584 |
+
state = {k:v.detach() for k, v in state.items()}
|
| 585 |
+
block_loss = 0
|
| 586 |
+
if training and (index % args.batch == 0 or index == len(loader)):
|
| 587 |
+
scaler.unscale_(optimizer)
|
| 588 |
+
remainder = index % args.batch
|
| 589 |
+
if index == len(loader) and remainder:
|
| 590 |
+
for parameter in model.parameters():
|
| 591 |
+
if parameter.grad is not None:
|
| 592 |
+
parameter.grad.mul_(args.batch/remainder)
|
| 593 |
+
norm = nn.utils.clip_grad_norm_(model.parameters(), 1.)
|
| 594 |
+
if not torch.isfinite(norm):
|
| 595 |
+
raise RuntimeError('Nonfinite gradient; checkpoint unchanged. Retry with AMP=0.')
|
| 596 |
+
scaler.step(optimizer); scaler.update(); optimizer.zero_grad(set_to_none=True)
|
| 597 |
+
groups[bool(inputs['detail_available'][0, 0])].append(total)
|
| 598 |
+
if index == 1 or index % 10 == 0:
|
| 599 |
+
print(f'{split} epoch={epoch}/{args.epochs} sample={index}/{len(loader)} horizon={steps} loss={total:.5f} elapsed_s={time.time()-began:.0f}', flush=True)
|
| 600 |
+
# Keep rare native examples visible in selection, rather than 5.7% dilution.
|
| 601 |
+
metrics[split+'_native'] = float(np.mean(groups[True]))
|
| 602 |
+
metrics[split+'_coarse'] = float(np.mean(groups[False]))
|
| 603 |
+
metrics[split] = (metrics[split+'_native']+metrics[split+'_coarse'])/2
|
| 604 |
+
metrics[split+'_association_failure_fraction'] = float(np.mean(failures))
|
| 605 |
+
promote = metrics['validation'] < best
|
| 606 |
+
if promote:
|
| 607 |
+
best = metrics['validation']
|
| 608 |
+
history.append(dict(epoch=epoch, horizon=horizon, **metrics))
|
| 609 |
+
save_training_state(last, model, optimizer, scaler, m, epoch, history, best)
|
| 610 |
+
save_training_state(args.output/f'epoch_{epoch:03d}.pt', model, optimizer, scaler, m, epoch, history, best)
|
| 611 |
+
if promote:
|
| 612 |
+
save_training_state(best_path, model, optimizer, scaler, m, epoch, history, best)
|
| 613 |
+
atomic_json(args.output/'history.json', history)
|
| 614 |
+
print(f'Saved epoch {epoch} directly to {args.output}; best={promote}', flush=True)
|
| 615 |
+
print('Training complete. Test set untouched; best.pt selected by full-120h validation.', flush=True)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def main165():
|
| 619 |
+
parser = argparse.ArgumentParser(description='v1.2.65 causal pressure transport and evolution; Drive-only data')
|
| 620 |
+
parser.add_argument('batch', type=int, nargs='?', default=10)
|
| 621 |
+
parser.add_argument('workers', type=int, nargs='?', default=3)
|
| 622 |
+
parser.add_argument('amp', type=int, nargs='?', default=1, choices=[0, 1])
|
| 623 |
+
parser.add_argument('--manifest', type=Path, default=ROOT/'data/v164_reuse/manifest.json')
|
| 624 |
+
persistent = Path('/content/drive/MyDrive/typhoon_predict') if Path('/content').is_dir() else ROOT
|
| 625 |
+
parser.add_argument('--output', type=Path, default=persistent/'training/v165_transport_pressure')
|
| 626 |
+
parser.add_argument('--epochs', type=int, default=12)
|
| 627 |
+
parser.add_argument('--device', choices=['auto', 'cpu', 'mps', 'cuda'], default='auto')
|
| 628 |
+
parser.add_argument('--preflight', action='store_true')
|
| 629 |
+
args = parser.parse_args()
|
| 630 |
+
if args.batch < 1 or args.workers < 0 or args.epochs < 1:
|
| 631 |
+
parser.error('Invalid batch, workers or epochs')
|
| 632 |
+
if Path('/content').is_dir() and (not (persistent.parent).is_dir() or not args.output.resolve().is_relative_to(persistent.resolve())):
|
| 633 |
+
raise ValueError('Mount Google Drive first; Colab checkpoints must persist under MyDrive/typhoon_predict')
|
| 634 |
+
manifest = load_reuse(args.manifest)
|
| 635 |
+
for split in ('train', 'validation', 'test'):
|
| 636 |
+
data = ReuseDataset(manifest, split)
|
| 637 |
+
data[0]; data[next(i for i, r in enumerate(data.rows) if r['patch'] >= 0)]
|
| 638 |
+
if args.preflight:
|
| 639 |
+
print('PASS full existing archive checksums, splits and native samples. No training started.', flush=True)
|
| 640 |
+
return
|
| 641 |
+
device = device_for(args.device)
|
| 642 |
+
random.seed(165); np.random.seed(165); torch.manual_seed(165)
|
| 643 |
+
model = TransportForecaster(manifest).to(device)
|
| 644 |
+
print(json.dumps(dict(version=VERSION, architecture=ARCHITECTURE, parameters=sum(p.numel() for p in model.parameters()),
|
| 645 |
+
device=str(device), samples=manifest['counts'], native_samples=manifest['patch_counts'], output=str(args.output))), flush=True)
|
| 646 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 647 |
+
lock = args.output/'training.lock'
|
| 648 |
+
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
| 649 |
+
os.write(fd, json.dumps(dict(pid=os.getpid(), host=socket.gethostname())).encode()); os.close(fd)
|
| 650 |
+
try:
|
| 651 |
+
train165(model, manifest, args, device)
|
| 652 |
+
finally:
|
| 653 |
+
lock.unlink(missing_ok=True)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
if __name__ == '__main__':
|
| 657 |
+
main165()
|
models/trackformer_1_2_field/weights.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:db49f36e85a3766defc4c172746897a1f783705d1ce8e6f9dfb8e87ae1d902cb
|
| 3 |
+
size 85997315
|
paper/trackformer_1_2_pressure_map_example.png
ADDED
|
paper/trackformer_1_2_vs_1_1_tip_bars.png
ADDED
|
paper/trackformer_1_2_vs_1_1_tip_metrics.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"title": "Trackformer 1.2 versus 1.1 TIP ten-start development diagnostic",
|
| 3 |
+
"issue_times_utc": [
|
| 4 |
+
"1979-10-12T00:00:00", "1979-10-12T06:00:00",
|
| 5 |
+
"1979-10-12T12:00:00", "1979-10-12T18:00:00",
|
| 6 |
+
"1979-10-13T00:00:00", "1979-10-13T06:00:00",
|
| 7 |
+
"1979-10-13T12:00:00", "1979-10-13T18:00:00",
|
| 8 |
+
"1979-10-14T00:00:00", "1979-10-14T06:00:00"
|
| 9 |
+
],
|
| 10 |
+
"lead_hours": [6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 102, 108, 114, 120],
|
| 11 |
+
"trackformer_1_1": {
|
| 12 |
+
"mean_track_error_km": 383.851708984375,
|
| 13 |
+
"central_pressure_mae_hpa": 20.0993,
|
| 14 |
+
"member_policy": "released prediction pipeline"
|
| 15 |
+
},
|
| 16 |
+
"trackformer_1_2": {
|
| 17 |
+
"mean_track_error_km": 370.4600524902344,
|
| 18 |
+
"central_pressure_mae_hpa": 30.722952880859374,
|
| 19 |
+
"member_policy": "mean of 50 distinct causal historical-input perturbations",
|
| 20 |
+
"inference_weights_sha256": "db49f36e85a3766defc4c172746897a1f783705d1ce8e6f9dfb8e87ae1d902cb"
|
| 21 |
+
},
|
| 22 |
+
"limitations": [
|
| 23 |
+
"Ten overlapping starts of one storm, not ten independent storms",
|
| 24 |
+
"Repeatedly inspected development cohort, not untouched holdout",
|
| 25 |
+
"Different input and member pipelines; this is not a controlled architecture ablation",
|
| 26 |
+
"Trackformer 1.2 improves mean track error slightly but worsens central-pressure MAE"
|
| 27 |
+
]
|
| 28 |
+
}
|