Add WeatherNext 2 weather forecasting model (#47874)
* Add WeatherNext 2 weather forecasting model
Ports Google DeepMind's WeatherNext 2 (FGN) to PyTorch: encode-process-decode
graph network over an icosahedral mesh, made probabilistic by a single global
noise vector that modulates every norm layer.
Adds a weather-forecasting task and AutoModelForWeatherForecasting, since this
is the first weather model in the library.
* Fix aggregate_normalization typing for the 0.25 degree configs
The fiddle configs store it as an int, which tripped the strict float|None
validation. Only the 0.25 degree checkpoints set it, so the mini model never
hit this.
* Make scipy a lazy import and fix decorator order
scipy is only needed to build the mesh at init, so importing it at module
level broke the doc build. Also swaps @dataclass below @auto_docstring, and
points the paper link at hf.co/papers.
* Follow the usual test conventions
Adds PipelineTesterMixin, a create_and_check_model on the tester, and a slow
integration test against the released checkpoint.
* Keep the geometry helper out of the public API
It imports scipy at module level, so exporting it made `from transformers
import *` require scipy.
* Document the auto class and register the base model
check_repo wants every public object in the docs, and every model in at least
one auto mapping.
* Point the docs at the released checkpoints
Adds a checkpoint link to the config docstring, which check_config_docstrings
requires, and switches the examples and the slow test to the 1 degree Mini so
they run on modest hardware.
* Allow the config's variable-list attributes
They are read through the channel-layout properties rather than directly in
the modeling file, which is what check_config_attributes scans for.
* Add the release dates to the model card
* Follow library conventions more closely
- Fix base_model_tp_plan: the paths were copied from Llama and matched nothing,
which is what the test I had skipped was telling me.
- Wire output capturing the way the library does it, so output_attentions
works, and let the head propagate what the base model recorded.
- Rename WeatherNext2Processor to WeatherNext2FeatureExtractor: it subclasses
FeatureExtractionMixin, and it was the only such class named Processor.
- Override test_attention_outputs instead of skipping it, and give every
remaining skip a precise reason.
* Infer the attention head count so tensor parallelism works
* Address review: drop the auto task, test the feature extractor
* Refresh the model card date
* Lead the ensemble docs with the per-member loop
* Register the forecasting head as intentionally unmapped
* Run the feature extractor in torch so rollouts stay on device
* Note which attention backend to use
* Be precise about the flash attention kernels
* Declare attention backend support
* Trim the attention notes
* Stamp the appended frame with the forecast's own valid time
* Record the measured effect of the tie-break
* Use trimesh for the grid-to-mesh connectivity, as upstream does
* Drop an unrelated file committed by mistake
* Ask for trimesh only where the geometry is built
* Fill missing values the way the original NaNCleaner does
* Ship the geometry with the checkpoint instead of caching it on disk
* Drop unrelated files committed by mistake
* Leave trimesh out of the requirements and refresh the card date
* Give the tests a mesh fixture so they run without trimesh
* Answer what mlinter asks of the WeatherNext 2 modeling file
The width these modules are built at is not `config.hidden_size`: they are
instantiated at the edge width and at each MLP's output width too, so naming the
argument after a config field claimed a single source of truth that was never
there. `num_features` says what it is.
The three config-gated branches now carry the CODEPATH note the rule asks for,
naming which checkpoints take which path.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* Build the WeatherNext 2 mesh mask through masking_utils
The mesh transformer chose between a BlockMask and a dense tensor by reading
_attn_implementation, which puts the backend's shape conventions in the model
body and breaks as soon as a new backend registers. create_bidirectional_mask
makes that choice instead: the banded geometry mask goes in as an
and_mask_function, and the key side declares its length, three blocks to the
query's one, through encoder_hidden_states.
Eager now takes either mask, since masking_utils hands it the additive float one
where sdpa still gets the boolean one that keeps the mask small at 0.25 degrees.
Against the JAX reference on the same inputs, 2m_temperature is unchanged at
2.65e-4 K mean and geopotential at 2.4e-7 relative.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* Register WeatherNext2FeatureExtractor with AutoFeatureExtractor
AutoFeatureExtractor.from_pretrained on a WeatherNext 2 checkpoint had nothing
to resolve to.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* Correct the WeatherNext 2 docs on geometry and ensembles
The geometry note described the old behaviour: the mesh and graphs are stored as
buffers in the checkpoint now, and the HF_HOME cache that the note pointed at no
longer exists. Deriving them instead is what needs scipy and trimesh.
The ensemble section led with the loop and showed batching as a fallback that
drew every member from one stream, giving up the per-member seeding it had just
recommended. Stacking one noise vector per member gets both: a single forward
and members that stay the same as the ensemble grows.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* Document tropical cyclone tracking with the WeatherNext 2 cyclones checkpoint
The cyclones checkpoint predicts 17 diagnostics that the upstream tracker reads
under exactly the names postprocess returns, so a rollout can be tracked with no
renaming. What is not obvious is the shape of the dataset it wants: lead time
rather than valid time on the time coordinate, lead 0 present, and the storms to
initialize from passed in, since cyclogenesis only picks up ones that appear
later.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* Build the geometry at conversion time and drop trimesh
* Skip the common test instead of patching it
* Register the feature extractor in the missing-names map
* Test the real mesh against a tiny checkpoint
* Expose the grid latitudes alongside the longitudes
* Say what the training loss is and check gradients reach the model
* Fix WeatherNext2
* assign the sigmoid buffers instead of registering them
* refresh the contribution date
* register the banded attention kernel for inference
* document the kernel and register it for every backend it builds for
* refresh the contribution date
* point the kernel at kernels-community now that it is merged
* trim comments
* fold the geometry into the conversion script and name the feature counts
* pin the integration test against reference values
The integration test only checked shape, finiteness and determinism. It
now also pins two slices and the mean of a forecast from a fixed seed,
which is what catches a silent change to the forward pass.
Doing that on a GPU exposed the determinism check: the graph aggregation
is an index_add, whose CUDA kernel accumulates with atomics, so two
identical passes differed by 1e-4. It now runs under deterministic
algorithms.
Also expands HRES on first use and says which ranks the FiLM broadcast
has to cover.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* record hidden states, and drop the feature extractor's defensive casts
The mesh transformer had a stack of layers and nothing recording it, so
output_hidden_states did nothing. WeatherNext2Layer now feeds
_can_record_outputs, with tie_last_hidden_states off because
last_hidden_state is the grid representation rather than the last mesh
layer. That lets test_hidden_states_output and
test_retain_grad_hidden_states_attentions stop being skipped; the first
is overridden for the blocked mesh shape, the shared one now applies.
The feature extractor copied every sequence and mapping it was handed.
Nothing downstream needs a list rather than an iterable, so the
annotations say list and dict and the copies are gone.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* drop the feature extractor from the auto mapping
WeatherNext 2 was the only non-audio entry in FEATURE_EXTRACTOR_MAPPING_NAMES,
which is the part that would have to move if that mapping narrows to audio
processors. MarkupLM is the other non-audio feature extractor and is
deliberately not in the mapping either.
Nothing is lost: every example in the model doc names the class directly, and
AutoFeatureExtractor.from_pretrained still resolves it, because
feature_extractor_class_from_name falls back to the main init and all four
checkpoint repos carry feature_extractor_type in preprocessor_config.json.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* resolve the attention interface before the flatten helper
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fold FiLM into the conditioned norm, and give the MLP and head their own shapes
Four of vasqu's review points, all pure renamings of checkpoint keys:
- WeatherNext2FiLM is gone; WeatherNext2ConditionedNorm owns the linear
it used to hold, so the noise enters the network in one place instead
of two modules.
- The shared bias of the edge update's split first matmul is now the
bias of edge_proj, the one part of that matmul always present, rather
than a bare Parameter needing its own _init_weights branch.
- WeatherNext2ConditionedMlp is WeatherNext2MLP plus a conditioned norm,
so it reuses that forward and names its projections fc1/fc2 like every
other MLP in the library.
- The decoder projection, output projection and the sigmoid gating move
into WeatherNext2ForecastHead.
Verified by remapping the released Mini checkpoint's keys and checking it
loads with no missing or unexpected keys and reproduces the pinned
integration values exactly.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* skip the flash dispatch test, which this model cannot satisfy
The shared test forces SDPA's flash-only backend, and every forward here
passes a mesh-adjacency mask that flash cannot take. It is the same
reason the model already sets _supports_flash_attn = False.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* Polish WeatherNext2
* Clean eager mask
* Add rollout mixin
* Fix model date
* Fix WeatherNext2 checks
* Fix WeatherNext2 review
* Fix WeatherNext2 docs
* Fix geometry init
* Chunk WeatherNext
* Add mask preparer
* Map mask kernel
* Gate flex options
* Fix flex
* Chunk bf16
* Fix bf16 parity
* Align kernels
* Single kernel hook and simpler chunking
* Torch-only feature extractor and num_members in generate
* Reject dataset grids the feature extractor can't describe
* Drop host sync in mesh-to-grid
* Update date
* Prepare mask once and use standard flex
* Validate num_members
* Update src/transformers/models/weathernext2/modular_weathernext2.py
Co-authored-by: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com>
* Split graphs
* Use grid kernels
* Use mask inputs
* Init buffers
* Guard tests
* Keep mask dispatch
* Move geometry
* Use mask helper
* Trim docs
* Clean memory
* Pass masks
* Move mask
* Cast inputs
* Trim tests
* Batch members
* Trim workaround
* Rename mask
* Trim docs
* Trim tests
* Align tests
* Tidy rollout
* Tidy modules
* Own mesh outputs
* Align graph forwards
* Use encoder patterns
* Move noise sampling
* Reuse MLP init
* Split graph config
* Own input prep
* Own masks
* Reuse head MLP
* Sum grid messages
* Group grid messages
* Fix kernel notes
* Trim data example
* Trim tests
* Use loader hook
* Add forecast config
* Keep geometry frozen
* Use default reviewer
* Simplify MLP
* Simplify head
* Update cyclone docs
* Simplify attention
* Move gather helper
* Use MIC fixture
* Add loss
* Shrink fixture
* Use buffers
* Move fixture
* Fix fixture
* Load mask in from_pretrained
* Address review
* Register feature extractor in auto and drop redundant revision resolve
* Trim feature extractor tests
* Drop unused generation config metadata
* Restore no-split norms, split one-liners, compile training test
* Check node and edge feature flags in the converter
* Fix accumulation
* Trim tests
* Move helpers
* Simplify layers
* Name forecasts
* Tidy docs
* Document outputs
* Use graph config
* Tidy tests
* Share MLP
* Link checkpoints
* Use default run
* Document default kernels
* Fetch source weights
* Restore converter
* Move Hub links
* Clarify checkpoint sources
* Match config defaults to the Hub checkpoint
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com>