> Agents: page URLs you remember may be outdated. Fetch https://huggingface.co/docs/transformers/main/llms.txt to find the right page first, and add `.md` to a page's path (before any `#`) to get Markdown instead of HTML. To search these docs, use the Hugging Face MCP server: https://huggingface.co/mcp

# WeatherNext 2

Google DeepMind and Google Research developed WeatherNext 2, published the [technical report](https://huggingface.co/papers/2506.10772),
and released the original JAX checkpoints on [Google Cloud Storage](https://console.cloud.google.com/storage/browser/dm_graphcast/weathernext2).
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](https://github.com/google-deepmind/weathernext) is on GitHub. The converted PyTorch checkpoints
are available in the
[WeatherNext2 collection](https://huggingface.co/collections/weathernext-community/weathernext2-6b116717b61e0de8575b5508).

| Checkpoint | Resolution | Params | Notes |
|---|---|---|---|
| [weathernext-community/weathernext2-mini](https://huggingface.co/weathernext-community/weathernext2-mini) | 1° | 56.7M | runs on modest hardware; `main` and `<2023` revisions |
| [weathernext-community/weathernext2](https://huggingface.co/weathernext-community/weathernext2) | 0.25° | 183.8M | also predicts 100m winds |
| [weathernext-community/weathernext-cyclones](https://huggingface.co/weathernext-community/weathernext-cyclones) | 0.25° | 183.8M | operational 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.

| Checkpoint | Training runs |
|---|---|
| WeatherNext 2 | [1 (default)](https://huggingface.co/weathernext-community/weathernext2), [2](https://huggingface.co/weathernext-community/weathernext2-model2), [3](https://huggingface.co/weathernext-community/weathernext2-model3), [4](https://huggingface.co/weathernext-community/weathernext2-model4) |
| WeatherNext Cyclones | [1 (default)](https://huggingface.co/weathernext-community/weathernext-cyclones), [2](https://huggingface.co/weathernext-community/weathernext-cyclones-model2), [3](https://huggingface.co/weathernext-community/weathernext-cyclones-model3), [4](https://huggingface.co/weathernext-community/weathernext-cyclones-model4) |

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](https://github.com/NVIDIA/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()](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2FeatureExtractor.compute_forcings) derives the clock forcings; they do not need fetching.

```python
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](/docs/transformers/main/en/model_doc/weathernext2#transformers.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](https://github.com/google-deepmind/weathernext/blob/main/docs/weathernext2/wn2_demo.ipynb), also used
by Earth2Studio. Install the dependencies to read it:

```bash
pip install h5netcdf xarray
```

```python
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()](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2GenerationMixin.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.

```python
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:

```python
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()](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2GenerationMixin.generate) prepares inputs, runs the model, postprocesses each forecast and advances
the conditioning state. Each 6-hour step draws fresh noise.

```python
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](#usage),
the following uses the 0.25° HRES sample to generate one 6-hour forecast in physical units:

```python
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)`:

```python
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](/docs/transformers/main/en/model_doc/weathernext2#transformers.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](https://github.com/Raymondlol/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`](https://github.com/huggingface/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.

```python
from transformers import WeatherNext2ForWeatherForecasting

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

## WeatherNext2Config[[transformers.WeatherNext2Config]]

#### transformers.WeatherNext2Config[[transformers.WeatherNext2Config]]

```python
transformers.WeatherNext2Config(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, graph_config: dict | transformers.models.weathernext2.configuration_weathernext2.WeatherNext2GraphConfig | None = None, hidden_size: int = 768, intermediate_size: int = 3072, num_hidden_layers: int = 24, num_attention_heads: int = 6, num_node_spatial_features: int = 3, noise_channels: int = 32, hidden_act: str = 'gelu_pytorch_tanh', mesh_splits: int = 6, attention_k_hop: int = 32, ball_query_radius_fraction: float = 0.6, num_grid_to_mesh_edges: int = 1618841, attention_bandwidth: int = 10273, grid_latitudes: int = 721, grid_longitudes: int = 1440, input_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 = 2, time_step_hours: int = 6, sigmoid_shifted_outputs: dict[str, float] | None = None, initializer_range: float = 0.02, layer_norm_eps: float = 1e-05, attention_dropout: float = 0.0, chunk_size: int | None = 32768, loss_weights: dict[str, float | int] | None = None, vars_with_nan_targets: list[str] | tuple[str, ...] | None = None)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/configuration_weathernext2.py#L131)

**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](https://huggingface.co/weathernext-community/weathernext2)

Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the
documentation from [PreTrainedConfig](/docs/transformers/main/en/main_classes/configuration#transformers.PreTrainedConfig) for more information.

```python
>>> from transformers import WeatherNext2Config, WeatherNext2Model

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

## WeatherNext2FeatureExtractor[[transformers.WeatherNext2FeatureExtractor]]

#### transformers.WeatherNext2FeatureExtractor[[transformers.WeatherNext2FeatureExtractor]]

```python
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 = None, num_input_timesteps: int = 2, time_step_hours: int = 6, grid_latitudes: int = 721, grid_longitudes: int = 1440, noise_channels: int = 32, attention_mask: torch.Tensor | None = None, **kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/feature_extraction_weathernext2.py#L122)

**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()](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2FeatureExtractor.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__[[transformers.WeatherNext2FeatureExtractor.__call__]]

```python
__call__(state: collections.abc.Mapping[str, typing.Any], seconds_since_epoch: torch.Tensor | None = None, forcings: collections.abc.Mapping[str, typing.Any] | None = None, return_tensors: str | transformers.utils.generic.TensorType | None = <TensorType.PYTORCH: 'pt'>, device: torch.device | str | None = None, attention_mask: torch.Tensor | None = None, num_members: int = 1, noise: torch.Tensor | None = None, generator: torch.Generator | None = None, targets: collections.abc.Mapping[str, typing.Any] | None = None)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/feature_extraction_weathernext2.py#L368)

**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](/docs/transformers/main/en/internal/file_utils#transformers.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.

**Returns:**

[BatchFeature](/docs/transformers/main/en/main_classes/feature_extractor#transformers.BatchFeature) with `grid_features` of shape `[batch, channels, latitudes, longitudes]` and
`global_features` of shape `[batch, global_channels]`, and `noise` of shape `[batch, noise_channels]`.

Encodes a physical state into model inputs.

#### postprocess_forecasts[[transformers.WeatherNext2FeatureExtractor.postprocess_forecasts]]

```python
postprocess_forecasts(prediction: Any, state: collections.abc.Mapping[str, typing.Any] | None = None)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/feature_extraction_weathernext2.py#L508)

**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[[transformers.WeatherNext2FeatureExtractor.advance_state]]

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

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/feature_extraction_weathernext2.py#L578)

**Parameters:**

state (`Mapping[str, array]`) : The state the forecast was produced from.

forecast (`Mapping[str, array]`) : Physical values from [postprocess_forecasts()](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2FeatureExtractor.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[[transformers.WeatherNext2FeatureExtractor.compute_forcings]]

```python
compute_forcings(seconds_since_epoch: torch.Tensor)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/feature_extraction_weathernext2.py#L298)

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[[transformers.WeatherNext2GenerationConfig]]

#### transformers.WeatherNext2GenerationConfig[[transformers.WeatherNext2GenerationConfig]]

```python
transformers.WeatherNext2GenerationConfig(num_steps: int | None = None, num_members: int | None = None, **kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/generation_weathernext2.py#L33)

**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()](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2GenerationMixin.generate).

## WeatherNext2GenerationMixin[[transformers.WeatherNext2GenerationMixin]]

#### transformers.WeatherNext2GenerationMixin[[transformers.WeatherNext2GenerationMixin]]

```python
transformers.WeatherNext2GenerationMixin()
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/generation_weathernext2.py#L85)

Autoregressive generation methods for WeatherNext 2.

#### generate[[transformers.WeatherNext2GenerationMixin.generate]]

```python
generate(state: collections.abc.Mapping[str, typing.Any], feature_extractor: WeatherNext2FeatureExtractor, seconds_since_epoch: Tensor, num_steps: int | None = None, num_members: int | None = None, noise: typing.Optional[torch.Tensor] = None, generator: typing.Optional[torch.Generator] = None, attention_mask: typing.Optional[torch.Tensor] = None, batch_size: int | None = None, generation_config: transformers.models.weathernext2.generation_weathernext2.WeatherNext2GenerationConfig | None = None, **model_kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/generation_weathernext2.py#L88)

**Parameters:**

state (`Mapping[str, array]`) : Physical conditioning state in the format accepted by [WeatherNext2FeatureExtractor.__call__()](/docs/transformers/main/en/model_doc/weathernext2#transformers.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.

**Returns:**

[WeatherNext2GenerationOutput](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2GenerationOutput) containing each forecast in physical units, the final conditioning
state, and the valid time of the next forecast.

Generates an autoregressive weather forecast.

## WeatherNext2GenerationOutput[[transformers.WeatherNext2GenerationOutput]]

#### transformers.WeatherNext2GenerationOutput[[transformers.WeatherNext2GenerationOutput]]

```python
transformers.WeatherNext2GenerationOutput(forecasts: list[dict[str, torch.Tensor]] | None = None, state: dict[str, torch.Tensor] | None = None, valid_time: typing.Optional[torch.Tensor] = None)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/modeling_weathernext2.py#L519)

**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()](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2GenerationMixin.generate).

## WeatherNext2Model[[transformers.WeatherNext2Model]]

#### transformers.WeatherNext2Model[[transformers.WeatherNext2Model]]

```python
transformers.WeatherNext2Model(config: WeatherNext2Config)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/modeling_weathernext2.py#L578)

**Parameters:**

config ([WeatherNext2Config](/docs/transformers/main/en/model_doc/weathernext2#transformers.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()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.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](/docs/transformers/main/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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[[transformers.WeatherNext2Model.forward]]

```python
forward(grid_features: Tensor, global_features: Tensor, noise: Tensor, attention_mask: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/modeling_weathernext2.py#L590)

**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](/docs/transformers/main/en/model_doc/weathernext2#transformers.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](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2Config)) and inputs.

The [WeatherNext2Model](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2Model) forward method, overrides the `__call__` special method.

> [!TIP]
> 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[[transformers.WeatherNext2ForWeatherForecasting]]

#### transformers.WeatherNext2ForWeatherForecasting[[transformers.WeatherNext2ForWeatherForecasting]]

```python
transformers.WeatherNext2ForWeatherForecasting(config: WeatherNext2Config)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/modeling_weathernext2.py#L690)

**Parameters:**

config ([WeatherNext2Config](/docs/transformers/main/en/model_doc/weathernext2#transformers.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()](/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.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](/docs/transformers/main/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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[[transformers.WeatherNext2ForWeatherForecasting.forward]]

```python
forward(grid_features: Tensor, global_features: Tensor, attention_mask: Tensor, noise: Tensor, labels: typing.Optional[torch.Tensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/weathernext2/modeling_weathernext2.py#L699)

**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](/docs/transformers/main/en/model_doc/weathernext2#transformers.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](/docs/transformers/main/en/model_doc/weathernext2#transformers.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](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2Config)) and inputs.

The [WeatherNext2ForWeatherForecasting](/docs/transformers/main/en/model_doc/weathernext2#transformers.WeatherNext2ForWeatherForecasting) forward method, overrides the `__call__` special method.

> [!TIP]
> 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()](/docs/transformers/main/en/model_doc/weathernext2#transformers.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:

```python
>>> 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]
```
