Transformers documentation

WeatherNext 2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.25.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

This model was published in HF papers on 2025-06-12 and contributed to Hugging Face Transformers on 2026-12-03.

WeatherNext 2

Google DeepMind and Google Research developed WeatherNext 2, published the technical report, and released the original JAX checkpoints on Google Cloud Storage. The Transformers port is a community effort. This model was contributed by the Hugging Face team.

WeatherNext 2 is a global medium-range weather forecasting model. It advances the atmosphere by 6 hours per forward pass on a 0.25° latitude/longitude grid (1° for Mini). It predicts temperature, geopotential, wind, and humidity at 13 pressure levels, along with surface fields, precipitation, and tropical cyclone diagnostics.

The model encodes the grid, projects it onto an icosahedral mesh, applies local transformer attention, and decodes back onto the grid. Geometry carries positional information. Each ensemble member is defined by a 32-dimensional noise vector that conditions the normalization layers.

The original code is on GitHub. The converted PyTorch checkpoints are available in the WeatherNext2 collection.

CheckpointResolutionParamsNotes
weathernext-community/weathernext2-mini1°56.7Mruns on modest hardware; main and <2023 revisions
weathernext-community/weathernext20.25°183.8Malso predicts 100m winds
weathernext-community/weathernext-cyclones0.25°183.8Moperational cyclone model; main, <2024, <2023 revisions

Each 0.25° release has four independently trained checkpoints. The default repositories above serve run 1, and the numbered repositories serve runs 2–4. Load both the model and feature extractor from the same repository and revision.

CheckpointTraining runs
WeatherNext 21 (default), 2, 3, 4
WeatherNext Cyclones1 (default), 2, 3, 4

For a multi-model ensemble, load each run in turn and pool its forecasts. Each Cyclones run supports the same revisions as the default Cyclones repository. The examples below use the smaller Mini checkpoint.

Getting initial conditions

The checkpoints are fine-tuned for ECMWF HRES analysis. For other initialization times, Earth2Studio provides weather data sources. Supply two chronological frames six hours apart, on the checkpoint’s grid with ascending latitude and the configured pressure levels. Include all configured input variables. Provide geopotential_at_surface and land_sea_mask once as static fields of shape [latitudes, longitudes], aligned with the forecast inputs. The land-sea mask describes the surface on that grid. The feature extractor loads the model’s separate mesh attention mask from the checkpoint. compute_forcings() derives the clock forcings; they do not need fetching.

import numpy as np
from transformers import WeatherNext2FeatureExtractor

processor = WeatherNext2FeatureExtractor.from_pretrained("weathernext-community/weathernext2-mini")
conditioning_times = np.array([["2024-10-06T18:00", "2024-10-07T00:00"]], dtype="datetime64[s]").astype(np.int64)
forcings = processor.compute_forcings(conditioning_times)

Usage

WeatherNext2FeatureExtractor normalizes physical inputs, derives forecast-time forcings, and decodes predictions back into physical units. It accepts NumPy arrays or tensors and returns PyTorch tensors by default.

The example below downloads the 1° HRES sample from the official demo, also used by Earth2Studio. Install the dependencies to read it:

pip install h5netcdf xarray
from urllib.parse import quote

import numpy as np
import torch
import xarray
from transformers import WeatherNext2FeatureExtractor, WeatherNext2ForWeatherForecasting


def load_example(processor, resolution):
    """Downloads an HRES sample and returns the conditioning state and the valid time of the first forecast."""
    data_path = (
        "weathernext2/dataset/source-hres_forecast_init-2024-10-07 00:00:00_"
        f"res-{resolution}_levels-13_steps-01.nc"
    )
    data_file = f"weathernext2-example-{resolution}.nc"
    torch.hub.download_url_to_file("https://storage.googleapis.com/dm_graphcast/" + quote(data_path), data_file)
    example_batch = xarray.load_dataset(data_file).sortby("lat")

    # Two chronological conditioning frames, with the model's pressure levels and axis order.
    frames = slice(0, processor.num_input_timesteps)
    initial = example_batch.isel(time=frames).sel(level=processor.pressure_levels)
    initial = initial.transpose("batch", "time", "level", "lat", "lon")
    state = {}
    for name in processor.input_variables:
        if name not in processor.forcing_variables:
            state[name] = initial[name].values.astype(np.float32)
    conditioning_times = initial.datetime.values.astype("datetime64[s]").astype(np.int64)
    state.update(processor.compute_forcings(conditioning_times))

    # Forcings use the predicted step's timestamp, not the last input frame's.
    valid_time = example_batch.datetime.isel(time=processor.num_input_timesteps).values
    return state, valid_time.astype("datetime64[s]").astype(np.int64)


model = WeatherNext2ForWeatherForecasting.from_pretrained("weathernext-community/weathernext2-mini", device_map="auto")
processor = WeatherNext2FeatureExtractor.from_pretrained("weathernext-community/weathernext2-mini")
state, valid_time = load_example(processor, resolution="1.0")

inputs = processor(
    state, seconds_since_epoch=valid_time, generator=torch.Generator().manual_seed(0)
).to(device=model.device, dtype=model.dtype)
with torch.no_grad():
    outputs = model(**inputs)

forecast = processor.postprocess_forecasts(outputs.prediction, state)
print(forecast["2m_temperature"].shape)  # torch.Size([1, 181, 360])

Ensembles

Each member is one draw of the 32-dimensional noise vector through the same weights, so an ensemble is a batch. generate() builds it: num_members repeats every initial condition and gives each member its own noise. By default, all members run together in one forward pass per forecast step.

outputs = model.generate(
    state=state,
    feature_extractor=processor,
    seconds_since_epoch=valid_time,
    num_steps=1,
    num_members=8,
    generator=torch.Generator().manual_seed(0),
)
print(outputs.forecasts[0]["2m_temperature"].shape)  # torch.Size([8, 181, 360])

For a direct model forward, the processor can repeat the normalized inputs instead:

inputs = processor(
    state, seconds_since_epoch=valid_time, num_members=8, generator=torch.Generator().manual_seed(0)
).to(device=model.device, dtype=model.dtype)
with torch.no_grad():
    outputs = model(**inputs)

To run members sequentially, pass batch_size=1 to generate. This limits the rows evaluated together without changing their order or noise draws. The returned forecasts and conditioning states still hold the full ensemble.

Autoregressive rollout

generate() prepares inputs, runs the model, postprocesses each forecast and advances the conditioning state. Each 6-hour step draws fresh noise.

state = {name: torch.as_tensor(values).to(model.device) for name, values in state.items()}

outputs = model.generate(
    state=state,
    feature_extractor=processor,
    seconds_since_epoch=valid_time,
    num_steps=20,  # 5 days
)
frames = outputs.forecasts
state = outputs.state

seconds_since_epoch is the valid time of the first generated forecast, not the last conditioning frame.

Tropical cyclones

weathernext-community/weathernext-cyclones predicts 17 cyclone diagnostics, including existence probability, intensity and wind radii, alongside the weather fields. With the imports and load_example from Usage, the following uses the 0.25° HRES sample to generate one 6-hour forecast in physical units:

model = WeatherNext2ForWeatherForecasting.from_pretrained("weathernext-community/weathernext-cyclones", device_map="auto")
processor = WeatherNext2FeatureExtractor.from_pretrained("weathernext-community/weathernext-cyclones")
state, valid_time = load_example(processor, resolution="0.25")

inputs = processor(
    state, seconds_since_epoch=valid_time, generator=torch.Generator().manual_seed(0)
).to(device=model.device, dtype=model.dtype)
with torch.no_grad():
    outputs = model(**inputs)
forecast = processor.postprocess_forecasts(outputs.prediction, state)
print(forecast["cyclone_exists_gaussian_unit_mode"].shape)  # torch.Size([1, 721, 1440])

Fine-tuning

The loss is the original unbiased ensemble CRPS, with latitude, pressure-level and checkpoint-specific variable weights. Pass physical target fields for the next step, shaped (batch, (levels,) latitudes, longitudes):

inputs = processor(state, seconds_since_epoch=valid_time, targets=targets, num_members=2).to(model.device)
model.train()
loss = model(**inputs).loss
loss.backward()

The processor normalizes targets as residuals where appropriate and groups at least two independent members per initial condition. Missing cyclone targets are masked in both CRPS terms. The conversion script preserves the checkpoint’s loss_weights and vars_with_nan_targets.

Notes

  • Member m of initial condition i is row i * num_members + m. Forecast steps and members can be set in model.generation_config or a WeatherNext2GenerationConfig passed to generate; explicit arguments override them. For fixed per-member draws, pass noise shaped (num_steps, initial_batch_size * num_members, noise_channels) to generate.
  • With Hub kernels enabled, graph networks and conditioned encoders use graph_config.chunk_size, while the forecasting head uses chunk_size, following Faster-WeatherNext. Set both to None to disable kernel tiling. The regular PyTorch path is not tiled.
  • The grid-to-mesh and mesh-to-grid graphs are persistent buffers in model.geometry, and the banded mesh mask is attention_mask.safetensors, which the feature extractor loads and adds to the model inputs. Building them needs scipy and trimesh and takes minutes at 0.25°, so the conversion script does it once and loading needs neither. A model built from a config gets placeholder geometry.
  • Attention and graph aggregation accumulate in fp32. Lower-precision inference is not reference-equivalent and should be validated against forecast metrics. The released checkpoints use fp32; for optional bf16 inference, load with dtype=torch.bfloat16. generate casts its inputs to model.dtype; for a direct forward, cast the processor outputs yourself.
  • The 1° Mini checkpoints need substantially less memory than the 0.25° checkpoints. Use generate(batch_size=1) to bound per-forward working memory. Retaining the full ensemble’s state and forecasts still scales with its size.
  • The forecasting head reads only the grid output, so model.mesh_to_grid.mesh_node_update receives no gradient, matching the unused final mesh update in the original implementation.
  • Model weights are released by Google DeepMind under CC-BY-4.0, separately from the Apache-2.0 code.

Faster inference with a fused kernel

With a compatible version of kernels installed, loading on a supported accelerator enables tiled grid operations and fused banded mesh attention by default. The fused attention kernel is used with sdpa. These inference kernels fall back to PyTorch on CPU or under autograd. Pass use_kernels=False to use the PyTorch implementation.

from transformers import WeatherNext2ForWeatherForecasting

model = WeatherNext2ForWeatherForecasting.from_pretrained("weathernext-community/weathernext2", device_map="auto")

WeatherNext2Config

class transformers.WeatherNext2Config

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonegraph_config: dict | transformers.models.weathernext2.configuration_weathernext2.WeatherNext2GraphConfig | None = Nonehidden_size: int = 768intermediate_size: int = 3072num_hidden_layers: int = 24num_attention_heads: int = 6num_node_spatial_features: int = 3noise_channels: int = 32hidden_act: str = 'gelu_pytorch_tanh'mesh_splits: int = 6attention_k_hop: int = 32ball_query_radius_fraction: float = 0.6num_grid_to_mesh_edges: int = 1618841attention_bandwidth: int = 10273grid_latitudes: int = 721grid_longitudes: int = 1440input_variables: list[str] | tuple[str, ...] = ('temperature', 'geopotential', 'u_component_of_wind', 'v_component_of_wind', 'vertical_velocity', 'specific_humidity', '2m_temperature', 'mean_sea_level_pressure', '10m_v_component_of_wind', '10m_u_component_of_wind', 'sea_surface_temperature', '100m_u_component_of_wind', '100m_v_component_of_wind', 'geopotential_at_surface', 'land_sea_mask', 'year_progress_sin', 'year_progress_cos', 'day_progress_sin', 'day_progress_cos')target_variables: list[str] | tuple[str, ...] = ('temperature', 'geopotential', 'u_component_of_wind', 'v_component_of_wind', 'vertical_velocity', 'specific_humidity', '2m_temperature', 'mean_sea_level_pressure', '10m_v_component_of_wind', '10m_u_component_of_wind', 'sea_surface_temperature', '100m_u_component_of_wind', '100m_v_component_of_wind', 'total_precipitation_6hr', 'cyclone_exists_gaussian_unit_mode', 'cyclone_all_wind_disc', 'cyclone_usa_wind_disc', 'cyclone_usa_r34_ne_radius_disc', 'cyclone_usa_r34_se_radius_disc', 'cyclone_usa_r34_sw_radius_disc', 'cyclone_usa_r34_nw_radius_disc', 'cyclone_usa_r50_ne_radius_disc', 'cyclone_usa_r50_se_radius_disc', 'cyclone_usa_r50_sw_radius_disc', 'cyclone_usa_r50_nw_radius_disc', 'cyclone_usa_r64_ne_radius_disc', 'cyclone_usa_r64_se_radius_disc', 'cyclone_usa_r64_sw_radius_disc', 'cyclone_usa_r64_nw_radius_disc', 'cyclone_usa_rmw_disc', 'cyclone_usa_pres_disc')forcing_variables: list[str] | tuple[str, ...] = ('year_progress_sin', 'year_progress_cos', 'day_progress_sin', 'day_progress_cos')atmospheric_variables: list[str] | tuple[str, ...] = ('temperature', 'geopotential', 'u_component_of_wind', 'v_component_of_wind', 'vertical_velocity', 'specific_humidity')static_variables: list[str] | tuple[str, ...] = ('geopotential_at_surface', 'land_sea_mask')global_variables: list[str] | tuple[str, ...] = ('year_progress_sin', 'year_progress_cos')pressure_levels: list[int] | tuple[int, ...] = (50, 100, 150, 200, 250, 300, 400, 500, 600, 700, 850, 925, 1000)num_input_timesteps: int = 2time_step_hours: int = 6sigmoid_shifted_outputs: dict[str, float] | None = Noneinitializer_range: float = 0.02layer_norm_eps: float = 1e-05attention_dropout: float = 0.0chunk_size: int | None = 32768loss_weights: dict[str, float | int] | None = Nonevars_with_nan_targets: list[str] | tuple[str, ...] | None = None )

Parameters

  • graph_config (WeatherNext2GraphConfig or dict, optional) — Configuration of the graph networks and conditioned encoder/decoder MLPs.
  • hidden_size (int, optional, defaults to 768) — Dimension of the hidden representations.
  • intermediate_size (int, optional, defaults to 3072) — Dimension of the MLP representations.
  • num_hidden_layers (int, optional, defaults to 24) — Number of hidden layers in the Transformer decoder.
  • num_attention_heads (int, optional, defaults to 6) — Number of attention heads for each attention layer in the Transformer decoder.
  • num_node_spatial_features (int, optional, defaults to 3) — Number of spatial features describing each grid or mesh node.
  • noise_channels (int, optional, defaults to 32) — Dimension of the global noise vector, and of the conditioning vector it is projected to.
  • hidden_act (str, optional, defaults to "gelu_pytorch_tanh") — Activation of the mesh transformer feed-forward layer. The original implementation calls jax.nn.gelu, which defaults to the tanh approximation.
  • mesh_splits (int, optional, defaults to 6) — Number of times the base icosahedron is subdivided. n splits give 10 * 4**n + 2 mesh nodes, so 5 gives 10242 nodes and 6 gives 40962.
  • attention_k_hop (int, optional, defaults to 32) — Radius, in mesh edges, of the local attention neighbourhood. Each mesh node attends to every node reachable within this many hops.
  • ball_query_radius_fraction (float, optional, defaults to 0.6) — Radius used to connect grid points to mesh nodes, as a fraction of the longest mesh edge.
  • num_grid_to_mesh_edges (int, optional, defaults to 1618841) — Number of grid-to-mesh edges the ball query produces. Follows from the mesh and the grid, but cannot be derived in closed form, so checkpoints record it: it is the shape the geometry buffers are allocated with before they are loaded.
  • attention_bandwidth (int, optional, defaults to 10273) — Width of the banded mesh adjacency after the reverse Cuthill-McKee ordering, recorded for the same reason.
  • grid_latitudes (int, optional, defaults to 721) — Number of latitudes, from -90 to 90 inclusive.
  • grid_longitudes (int, optional, defaults to 1440) — Number of longitudes, from 0 eastwards.
  • input_variables (tuple(str), optional) — Variables fed to the model, in the channel order the model expects.
  • target_variables (tuple(str), optional) — Variables the model predicts, in the channel order it produces.
  • forcing_variables (tuple(str), optional) — Variables known ahead of time and supplied for the predicted time step.
  • atmospheric_variables (tuple(str), optional) — Subset of the variables that has a pressure-level dimension.
  • static_variables (tuple(str), optional) — Subset of the input variables that is constant in time.
  • global_variables (tuple(str), optional) — Subset of the variables that has neither a latitude nor a longitude dimension. These are broadcast over the grid and additionally fed to the mesh encoder.
  • pressure_levels (tuple(int), optional) — Pressure levels in hPa, ascending.
  • num_input_timesteps (int, optional, defaults to 2) — Number of past states the model conditions on.
  • time_step_hours (int, optional, defaults to 6) — Hours advanced by one forward pass.
  • sigmoid_shifted_outputs (dict[str, float], optional) — Target variables that get sigmoid(x - shift) applied after decoding, mapped to their shift.
  • initializer_range (float, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  • layer_norm_eps (float, optional, defaults to 1e-05) — The epsilon used by the layer normalization layers.
  • attention_dropout (float, optional, defaults to 0.0) — The dropout ratio for the attention probabilities.
  • chunk_size (int, optional, defaults to 32768) — Number of grid points per forecasting-head inference tile when use_kernels=True. None disables head tiling. Graph networks and conditioned encoders use graph_config.chunk_size.
  • loss_weights (dict[str, float], optional) — Per-variable CRPS weights. Unspecified variables have weight 1, and an empty dictionary requests uniform weights. Defaults to the original checkpoint’s weights for the variables in target_variables.
  • vars_with_nan_targets (list[str], optional) — Variables whose missing targets are excluded from both CRPS terms. Defaults to the cyclone diagnostics other than existence that are in target_variables.

This is the configuration class to store the configuration of a WeatherNext2Model. It is used to instantiate a Weathernext2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the weathernext-community/weathernext2

Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.

>>> from transformers import WeatherNext2Config, WeatherNext2Model

>>> configuration = WeatherNext2Config()
>>> model = WeatherNext2Model(configuration)
>>> configuration = model.config

WeatherNext2FeatureExtractor

class transformers.WeatherNext2FeatureExtractor

< >

( input_variables: list[str]target_variables: list[str]forcing_variables: list[str]atmospheric_variables: list[str]static_variables: list[str]global_variables: list[str]pressure_levels: list[int]mean_by_level: dict[str, float | list[float]]stddev_by_level: dict[str, float | list[float]]diffs_stddev_by_level: dict[str, float | list[float]]nan_fill_values: dict[str, float] | None = Nonenum_input_timesteps: int = 2time_step_hours: int = 6grid_latitudes: int = 721grid_longitudes: int = 1440noise_channels: int = 32attention_mask: torch.Tensor | None = None**kwargs )

Parameters

  • input_variables (list[str]) — Variables the model consumes, in channel order.
  • target_variables (list[str]) — Variables the model predicts, in channel order.
  • forcing_variables (list[str]) — Variables supplied for the predicted time step. These are all derived from the clock, so this class computes them itself in compute_forcings().
  • atmospheric_variables (list[str]) — Variables that carry a pressure-level dimension.
  • static_variables (list[str]) — Input variables that do not change over time.
  • global_variables (list[str]) — Variables with neither a latitude nor a longitude dimension.
  • pressure_levels (list[int]) — Pressure levels in hPa, ascending.
  • mean_by_level (dict[str, float | list[float]]) — Per-variable mean used to normalize inputs, and to unnormalize predictions of variables that are not themselves inputs.
  • stddev_by_level (dict[str, float | list[float]]) — Per-variable standard deviation, used the same way.
  • diffs_stddev_by_level (dict[str, float | list[float]]) — Per-variable standard deviation of the one-step difference. Predictions of variables that are also inputs are residuals scaled by this.
  • nan_fill_values (dict[str, float], optional) — Value substituted for missing data, per variable, before normalization; the prediction is masked out again wherever the input was missing. sea_surface_temperature is undefined over land and the network cannot ingest NaNs, so it is filled with a fixed temperature rather than with its own mean.
  • num_input_timesteps (int, optional, defaults to 2) — Number of past states the model conditions on.
  • time_step_hours (int, optional, defaults to 6) — Hours advanced by one forward pass.
  • grid_latitudes (int, optional, defaults to 721) — Number of latitudes, from -90 to 90 inclusive.
  • grid_longitudes (int, optional, defaults to 1440) — Number of longitudes, from 0 eastwards.
  • noise_channels (int, optional, defaults to 32) — Size of the noise vector defining each ensemble member.
  • attention_mask (torch.BoolTensor, optional) — Exact banded mesh mask, saved separately as attention_mask.safetensors.

Constructs a WeatherNext 2 feature extractor.

__call__

< >

( state: collections.abc.Mapping[str, typing.Any]seconds_since_epoch: torch.Tensor | None = Noneforcings: collections.abc.Mapping[str, typing.Any] | None = Nonereturn_tensors: str | transformers.utils.generic.TensorType | None = <TensorType.PYTORCH: 'pt'>device: torch.device | str | None = Noneattention_mask: torch.Tensor | None = Nonenum_members: int = 1noise: torch.Tensor | None = Nonegenerator: torch.Generator | None = Nonetargets: collections.abc.Mapping[str, typing.Any] | None = None )

Parameters

  • state (Mapping[str, array]) — Physical values keyed by variable name. Time-varying variables have shape [batch, num_input_timesteps, (levels,) latitudes, longitudes], static variables [latitudes, longitudes], and variables with no spatial extent [batch, num_input_timesteps]. Longitude-only variables such as day_progress_sin may be [batch, num_input_timesteps, longitudes].
  • seconds_since_epoch (torch.Tensor of shape (batch,), optional) — Valid time of the predicted step, as Unix seconds, used to derive the forcings. Required unless forcings is given.
  • forcings (Mapping[str, array], optional) — Precomputed forcings for the predicted step, overriding seconds_since_epoch.
  • return_tensors (str or TensorType, optional, defaults to "pt") — Framework of the returned tensors.
  • device (torch.device or str, optional) — Device to encode on. Defaults to the device of state when it holds tensors, and to the CPU otherwise, so an autoregressive rollout that starts on an accelerator stays there.
  • attention_mask (torch.BoolTensor of shape (num_blocks, 1, block_size, 3 * block_size), optional) — Exact banded mesh geometry, shared by all ensemble members. Defaults to the processor’s mask. It is moved to the input device without normalization or ensemble repetition.
  • num_members (int, optional, defaults to 1) — Repeat each initial condition along the batch axis for an ensemble. The geometry mask is shared.
  • noise (torch.FloatTensor of shape (batch * num_members, noise_channels), optional) — Noise defining each ensemble member. Independent standard normal vectors are sampled if omitted.
  • generator (torch.Generator, optional) — Generator used to sample noise. Draws are made on its device and transferred to the input device.
  • targets (Mapping[str, array], optional) — Physical target fields for one forecast step, shaped [batch, (levels,) latitudes, longitudes]. With at least two members, returns normalized labels shaped [batch, num_members, channels, latitudes, longitudes] for ensemble CRPS training.

Encodes a physical state into model inputs.

postprocess_forecasts

< >

( prediction: Anystate: collections.abc.Mapping[str, typing.Any] | None = None ) → dict[str, torch.Tensor]

Parameters

  • prediction (array of shape (batch, channels, latitudes, longitudes)) — WeatherNext2ForecastOutput.prediction.
  • state (Mapping[str, array], optional) — The same state that was passed to __call__. Required when an input variable is also a forecast target because those targets are decoded as residuals.

Returns

dict[str, torch.Tensor]

physical values keyed by variable, shaped [batch, (levels,) lat, lon], on the device of prediction.

Decodes the model’s normalized output into physical units.

Variables that also appear in the inputs are predicted as normalized residuals and need the last conditioning frame added back, so state is required whenever any target is also an input.

advance_state

< >

( state: collections.abc.Mapping[str, typing.Any]forecast: collections.abc.Mapping[str, 'torch.Tensor']seconds_since_epoch: torch.Tensor )

Parameters

  • state (Mapping[str, array]) — The state the forecast was produced from.
  • forecast (Mapping[str, array]) — Physical values from postprocess_forecasts().
  • seconds_since_epoch (torch.Tensor of shape (batch,)) — Valid time of forecast, which is the same value that was passed to __call__ to produce it. The appended frame is stamped with it, so advancing the clock before calling this puts the physical fields and the clock variables a step out of sync.

Builds the conditioning state for the next autoregressive step.

Drops the oldest frame, appends the forecast, and recomputes the clock variables. Targets that are not also inputs (precipitation, the cyclone diagnostics) are simply discarded.

compute_forcings

< >

( seconds_since_epoch: torch.Tensor )

Clock-derived variables at the given times.

year_progress_* is a single number per time; day_progress_* varies with longitude, since it encodes local solar time. They are computed on the CPU, in float64 where it matters (not every accelerator has float64), and are moved to the state’s device by the callers.

WeatherNext2GenerationConfig

class transformers.WeatherNext2GenerationConfig

< >

( num_steps: int | None = Nonenum_members: int | None = None**kwargs )

Parameters

  • num_steps (int, optional) — Number of autoregressive forecast steps. Defaults to 1 when unset by the model or the user.
  • num_members (int, optional) — Number of ensemble members per initial condition. Defaults to 1 when unset by the model or the user.

Configuration for WeatherNext2GenerationMixin.generate().

WeatherNext2GenerationMixin

class transformers.WeatherNext2GenerationMixin

< >

( )

Autoregressive generation methods for WeatherNext 2.

generate

< >

( state: collections.abc.Mapping[str, typing.Any]feature_extractor: WeatherNext2FeatureExtractorseconds_since_epoch: Tensornum_steps: int | None = Nonenum_members: int | None = Nonenoise: typing.Optional[torch.Tensor] = Nonegenerator: typing.Optional[torch.Generator] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonebatch_size: int | None = Nonegeneration_config: transformers.models.weathernext2.generation_weathernext2.WeatherNext2GenerationConfig | None = None**model_kwargs )

Parameters

  • state (Mapping[str, array]) — Physical conditioning state in the format accepted by WeatherNext2FeatureExtractor.call().
  • feature_extractor (WeatherNext2FeatureExtractor) — Feature extractor used to normalize inputs, decode predictions and advance the state.
  • seconds_since_epoch (torch.Tensor of shape (batch_size,)) — Valid time of the first generated forecast, as Unix seconds.
  • num_steps (int, optional) — Number of autoregressive time steps to generate. Overrides generation_config.num_steps.
  • num_members (int, optional) — Number of ensemble members drawn from each initial condition. Each one is repeated num_members times along the batch axis, and every member gets its own noise. Overrides generation_config.num_members.
  • noise (torch.Tensor of shape (num_steps, batch_size * num_members, noise_channels), optional) — Explicit noise vector for every step and ensemble member. When omitted, a fresh vector is sampled at every step.
  • generator (torch.Generator, optional) — Generator used to sample noise when noise is omitted.
  • attention_mask (torch.BoolTensor of shape (num_blocks, 1, block_size, 3 * block_size), optional) — Exact banded mesh geometry, shared across ensemble members and reused at every forecast step.
  • batch_size (int, optional) — Maximum number of ensemble rows evaluated together. Defaults to the whole ensemble. Set to 1 to run members sequentially. Returned forecasts and conditioning states still contain every member.
  • generation_config (WeatherNext2GenerationConfig, optional) — Forecast configuration. Unset values fall back to model.generation_config, then to 1.
  • model_kwargs (dict, optional) — Additional arguments forwarded to the model at every step.

Generates an autoregressive weather forecast.

WeatherNext2GenerationOutput

class transformers.WeatherNext2GenerationOutput

< >

( forecasts: list[dict[str, torch.Tensor]] | None = Nonestate: dict[str, torch.Tensor] | None = Nonevalid_time: typing.Optional[torch.Tensor] = None )

Parameters

  • forecasts (list[dict[str, torch.Tensor]]) — One postprocessed forecast in physical units per generated time step. With num_members > 1 the batch axis holds every member of every initial condition: member m of initial condition i is row i * num_members + m.
  • state (dict[str, torch.Tensor]) — Conditioning state after the final forecast has been appended.
  • valid_time (torch.Tensor, optional) — Valid time, as Unix seconds, of the next forecast that would be generated.

Output of WeatherNext2GenerationMixin.generate().

WeatherNext2Model

class transformers.WeatherNext2Model

< >

( config: WeatherNext2Config )

Parameters

  • config (WeatherNext2Config) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

The bare Weathernext2 Model outputting raw hidden-states without any specific head on top.

This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

< >

( grid_features: Tensorglobal_features: Tensornoise: Tensorattention_mask: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → WeatherNext2ModelOutput or tuple(torch.Tensor)

Parameters

  • grid_features (torch.FloatTensor of shape (batch_size, num_channels, num_latitudes, num_longitudes)) — Normalized input fields, with channels ordered as in WeatherNext2Config.input_channel_layout. Variables with no spatial extent must already be broadcast over the grid.
  • global_features (torch.FloatTensor of shape (batch_size, num_global_channels)) — Normalized values of the variables with no spatial extent, ordered as in WeatherNext2Config.mesh_channel_layout. These reach the mesh encoder directly, which is how the mesh learns anything about the state of the calendar.
  • noise (torch.FloatTensor of shape (batch_size, noise_channels)) — One standard normal draw per ensemble member.
  • attention_mask (torch.BoolTensor of shape (num_blocks, 1, block_size, 3 * block_size)) — Exact banded mesh geometry returned by WeatherNext2FeatureExtractor, shared by all ensemble members.

Returns

WeatherNext2ModelOutput or tuple(torch.Tensor)

A WeatherNext2ModelOutput or a tuple of torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WeatherNext2Config) and inputs.

The WeatherNext2Model forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

  • last_hidden_state (torch.Tensor of shape (batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.
  • hidden_states (tuple(torch.FloatTensor), optional) — Mesh-node features entering the transformer and leaving each of its layers, shaped (batch_size, num_blocks, block_size, hidden_size). The tail of the last block is padding.
  • attentions (tuple(torch.FloatTensor), optional) — Attention weights of each block over its neighbouring blocks, shaped (batch_size * num_blocks, num_attention_heads, block_size, 3 * block_size).
  • mesh_hidden_state (torch.FloatTensor of shape (batch_size, num_mesh_nodes, hidden_size)) — Mesh-node features after the transformer.

WeatherNext2ForWeatherForecasting

class transformers.WeatherNext2ForWeatherForecasting

< >

( config: WeatherNext2Config )

Parameters

  • config (WeatherNext2Config) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

WeatherNext 2 with its forecasting head: advances the global atmospheric state by one time step.

This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)

This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

forward

< >

( grid_features: Tensorglobal_features: Tensorattention_mask: Tensornoise: Tensorlabels: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → WeatherNext2ForecastOutput or tuple(torch.Tensor)

Parameters

  • grid_features (torch.FloatTensor of shape (batch_size, num_channels, num_latitudes, num_longitudes)) — Normalized input fields, with channels ordered as in WeatherNext2Config.input_channel_layout.
  • global_features (torch.FloatTensor of shape (batch_size, num_global_channels)) — Normalized values of the variables with no spatial extent.
  • attention_mask (torch.BoolTensor of shape (num_blocks, 1, block_size, 3 * block_size)) — Exact banded mesh geometry returned by WeatherNext2FeatureExtractor, shared by all ensemble members.
  • noise (torch.FloatTensor of shape (batch_size, noise_channels)) — Standard normal draw defining the ensemble member, returned by WeatherNext2FeatureExtractor.
  • labels (torch.FloatTensor of shape (batch_size, num_members, num_output_channels, num_latitudes, num_longitudes), optional) — Targets in the same normalized space as prediction. Inputs flatten the first two axes in initial-condition-major order, as returned by the feature extractor with num_members > 1. At least two independently sampled members are required. The loss uses the checkpoint’s loss_weights and vars_with_nan_targets.

Returns

WeatherNext2ForecastOutput or tuple(torch.Tensor)

A WeatherNext2ForecastOutput or a tuple of torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (WeatherNext2Config) and inputs.

The WeatherNext2ForWeatherForecasting forward method, overrides the __call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

  • loss (torch.FloatTensor of shape (), optional, returned when labels is provided) — Unbiased ensemble CRPS, see WeatherNext2ForWeatherForecastingLoss().
  • prediction (torch.FloatTensor of shape (batch_size, num_output_channels, num_latitudes, num_longitudes)) — Predicted state for the next time step, in the model’s normalized space, with channels ordered as in WeatherNext2Config.target_channel_layout. For variables that are also inputs this is a normalized residual on the last input frame; for the others it is the normalized value itself. Use WeatherNext2FeatureExtractor.postprocess_forecasts() to get physical units.
  • last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the model.
  • hidden_states (tuple(torch.FloatTensor), optional) — Mesh-node features, shaped as in WeatherNext2ModelOutput.
  • attentions (tuple(torch.FloatTensor), optional) — Mesh attention weights, shaped as in WeatherNext2ModelOutput.

Example:

>>> import torch
>>> from transformers import WeatherNext2Config, WeatherNext2ForWeatherForecasting

>>> config = WeatherNext2Config(
...     mesh_splits=2, hidden_size=32, graph_config={"hidden_size": 32}, num_hidden_layers=2, num_attention_heads=2,
...     grid_latitudes=19, grid_longitudes=36,
...     num_grid_to_mesh_edges=2048, attention_bandwidth=64,
... )
>>> model = WeatherNext2ForWeatherForecasting(config)

>>> grid = torch.randn(2, config.num_grid_input_channels - 3, 19, 36, dtype=model.dtype)
>>> global_features = torch.randn(2, config.num_mesh_input_channels - 3, dtype=model.dtype)
>>> blocks = -(-config.num_mesh_nodes // config.attention_bandwidth)
>>> mask = torch.ones(blocks, 1, config.attention_bandwidth, 3 * config.attention_bandwidth, dtype=torch.bool)
>>> noise = torch.randn(2, config.noise_channels, dtype=model.dtype)
>>> outputs = model(grid_features=grid, global_features=global_features, attention_mask=mask, noise=noise)
>>> list(outputs.prediction.shape)
[2, 103, 19, 36]
Update on GitHub