Generated banner for Earth2studio Create Prognostic
Generated logo for Earth2studio Create Prognostic

Earth2studio Create Prognostic

NVIDIAOfficialCreated by NVIDIA Earth-2 Team

  • Skill
  • Workflow
  • Software development
  • Apache-2.0
  • Medium risk
  • Has scripts

From the author

Create Earth2Studio prognostic (time-stepping forecast) model wrappers. Do NOT use for diagnostic models, data sources, or installation.
— the description by NVIDIA Earth-2 Team

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured, step-by-step procedure for implementing prognostic (time-stepping) model wrappers within the Earth2Studio ecosystem. It guides developers through dependency management, model file creation using required inheritance patterns, coordinate system implementation, forward pass logic, and rigorous testing. The workflow ensures consistency across model integrations by enforcing specific method order, SPDX headers, and documentation standards, while providing templates for pull requests and validation comparisons against vanilla implementations.

What it does

  • Generates prognostic model wrappers for Earth2Studio.
  • Manages Python dependencies and model-specific extras in pyproject.toml.
  • Enforces standard inheritance and method structures for model classes.
  • Provides templates for coordinate systems and iterative forecasting logic.
  • Facilitates automated testing and validation against reference implementations.
  • Standardizes documentation and changelog updates for new model integrations.

When to use it

  • When integrating a new third-party ML weather model into Earth2Studio.
  • When you need to ensure a model wrapper adheres to the framework's architectural standards.
  • When you need to validate a new model wrapper against a vanilla reference implementation.
  • When preparing a pull request for a new prognostic model contribution.

Advantages

  • Ensures architectural consistency across all prognostic models.
  • Reduces boilerplate through provided templates and skeletons.
  • Standardizes testing and validation procedures.
  • Simplifies dependency management and documentation requirements.

Usage examples

“Create IdentityModel - returns input unchanged, 6h step, 181x360, vars: t2m, u10m, v10m, msl”
The agent generates the identity.py file with the required triple inheritance, implements the coordinate system, creates the corresponding test file, and runs the full verification suite.
“Add Pangu-Weather wrapper from https://github.com/198808xc/Pangu-Weather”
The agent fetches the inference script, sets up the model wrapper with appropriate dependencies, implements the forward pass and iterator, and executes the test suite.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/nvidia/earth2studio-create-prognostic/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip earth2studio-create-prognostic.zip -d .agents/skills

Documentation by NVIDIA Earth-2 Team

Quick Start Checklist

Do these steps IN ORDER. Do not skip any step.

  • [ ] Read this SKILL.md completely first

  • [ ] Get reference script (Step 0)

  • [ ] Create earth2studio/models/px/<name>.py with triple inheritance

  • [ ] Create test/models/px/test_<name>.py with mock tests

  • [ ] Run: uv run pytest test/models/px/test_<name>.py -v

  • [ ] Add/update model extra, install docs, API docs, and changelog (Steps 1-2, 9)

  • [ ] Run: make format && make lint

⚠️ CRITICAL: Always use uv run for Python commands:

  • ✅ uv run pytest ... / uv run python ...

  • ❌ pytest ... / python ... (missing dependencies)

Stuck or wrong output: Do not keep retrying the same fix. Follow Self-Improvement to patch this skill before continuing.

Purpose

Implement a prognostic model wrapper connecting third-party ML weather models to Earth2Studio. Prognostic models time-integrate forward—given initial state, they predict future states by stepping through time (e.g., 6-hour increments).

Workspace

ContextLocation
Harbor evalWrite to /workspace/output/earth2studio/models/px/...
Harbor + --copy-repoFull checkout at /workspace/repo
Local cloneDirectory with pyproject.toml

Never read evals/targets/ — grader references only.

Reference Files

Load on demand during the matching step:

FileContentLoad at
references/skeleton-template.pyFull model skeleton with FILL commentsSteps 3–6
references/method-templates.pyCanonical method implementationsSteps 4–6
references/testing-guide.pyTest skeleton and mock patternsStep 7
references/validation-guide.mdComparison scripts, PR, code reviewSteps 10–11

Workflow Steps

Step 0 — Get Reference Script

If $ARGUMENTS provided, use it. Otherwise ask:

Please provide a reference inference script URL/path.

Step 1 — Analyze & Propose Dependencies

Analyze: packages, architecture, I/O shapes, time step, resolution, checkpoint.

Propose pyproject.toml group (alphabetical, add to all). Every prognostic model must have an optional dependency extra, even when no packages are required:

model-name = ["package1>=version", "package2"]
# or, when no additional packages are required:
model-name = []

[CONFIRM] Present dependencies and ask user to approve.

Step 2 — Add Dependencies

Edit pyproject.toml: add the model extra alphabetically, even if it is empty, and update the all aggregate.

Step 3 — Create Model File

File: earth2studio/models/px/<lowercase>.py

Required inheritance (all three):

class ModelName(torch.nn.Module, AutoModelMixin, PrognosticMixin):

Required imports:

import numpy as np
import torch
from earth2studio.models.auto import AutoModelMixin, Package
from earth2studio.models.batch import batch_coords, batch_func
from earth2studio.models.px.base import PrognosticMixin
from earth2studio.models.utils import create_coords_from_lat_lon, handshake_dim
from earth2studio.lexicon import E2STUDIO_VOCAB
from earth2studio.utils import check_optional_dependencies
from loguru import logger

SPDX header (required at top of every .py file):

# SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: Apache-2.0

Canonical method order:

  1. __init__ 2. input_coords 3. output_coords (@batch_coords)

  2. load_default_package 5. load_model 6. to (optional)

  3. Private methods 8. __call__ (@batch_func) 9. _default_generator

  4. create_iterator

Step 4 — Implement Coordinates

input_coords rules:

  • batch: np.empty(0)

  • time: np.empty(0) (dynamic)

  • lead_time: starts at np.timedelta64(0, "h")

  • lat: 90 to -90 (north to south); this is the public Earth2Studio convention even if the source model uses the opposite order

  • lon: 0 to 360

  • If a checkpoint/model core expects south-to-north latitude, flip tensors internally before/after the core model; do not expose flipped latitude in input_coords or output_coords

  • Map variables to E2STUDIO_VOCAB (282 entries in earth2studio/lexicon/base.py)

output_coords: Use handshake_dim/handshake_coords for input validation, then increment lead_time. Prefer a shared coordinate-check helper and call it from output_coords, __call__, and iterator setup before model execution.

Step 5 — Implement Forward Pass

__call__: @batch_func decorated, shape (batch, time, lead_time, var, lat, lon). Reshape to model format → call model → reshape back.

create_iterator: MUST yield initial condition first (step 0). Use front_hook/rear_hook for perturbation injection.

Step 6 — Implement Model Loading

load_default_package: Lock HuggingFace URLs: hf://org/repo@commit

load_model: Use package.resolve(), map_location="cpu", eval() mode, decorate with @check_optional_dependencies().

Step 7 — Write Tests

File: test/models/px/test_<name>.py

Required tests:

FunctionPurpose
test_<model>_callSingle forward pass (parametrize device/time)
test_<model>_iterIterator produces sequence
test_<model>_exceptionsInvalid coords raise errors
test_<model>_packageReal weights (@pytest.mark.package)

Create PhooModelName dummy matching interface for mock tests.

Run tests:

uv run pytest test/models/px/test_<name>.py -m "not package" -v
uv run pytest test/models/px/test_<name>.py::test_<model>_package --package -v

Do not omit the package test. If arbitrary random inputs are not physically valid for the real checkpoint, use a stable model-appropriate synthetic input while still loading real weights and running a forward pass.

Step 8 — Register Model (if requested)
  • Add to earth2studio/models/px/__init__.py (alphabetical)

  • Verify deps in pyproject.toml

Step 9 — Documentation
  • Add to docs/modules/models_px.rst (alphabetical). This is required for every new prognostic model so the API docs include the generated page.

  • Add to docs/userguide/about/install.md (alphabetical tab) for the model extra, even when the extra is empty. Include model-specific notes plus both pip install earth2studio[model-name] and uv add earth2studio --extra model-name instructions.

  • Update CHANGELOG.md under ### Added. This is required for every new prognostic model.

Format and lint:

make format && make lint && make license
Step 10 - Validation (if requested)

Follow references/validation-guide.md. Create uncommitted vanilla, E2S, comparison, and sanity-check scripts; do not commit generated outputs or images. Use PR-safe placeholders for plots so the user can upload images manually.

[CONFIRM] User must visually inspect plots before proceeding.

Step 11 - PR (if requested)

Follow references/validation-guide.md and use:

  • references/pr-body-template.md

  • references/pr-comment-template.md

Before creating the PR, verify pyproject.toml has the model extra, the all extra includes it, install docs include both pip and uv commands, and docs/modules/models_px.rst plus CHANGELOG.md are updated.

Do not include machine names, absolute paths, device inventory, or uploaded image links in PR text. Use plot placeholders instead.


Examples

Simple Identity Model
User: Create IdentityModel - returns input unchanged, 6h step, 181x360, vars: t2m, u10m, v10m, msl

Agent: [reads SKILL.md, creates identity.py with triple inheritance,
        creates test_identity.py, runs pytest, runs make format && lint]
External Model (Pangu)
User: Add Pangu-Weather wrapper
      GitHub: https://github.com/198808xc/Pangu-Weather

Agent: [reads SKILL.md, fetches inference.py, creates pangu.py,
        creates test_pangu.py, runs pytest]

Key Patterns

Coordinate Template
@property
def input_coords(self) -> CoordSystem:
    return CoordSystem({
        "batch": np.empty(0),
        "time": np.empty(0),
        "lead_time": np.array([np.timedelta64(0, "h")]),
        "variable": np.array(["t2m", "u10m", ...]),
        # Public Earth2Studio convention is north-to-south latitude.
        "lat": np.linspace(90, -90, 181),
        "lon": np.linspace(0, 359, 360),
    })

@batch_coords()
def output_coords(self, input_coords: CoordSystem) -> CoordSystem:
    output = input_coords.copy()
    output["lead_time"] = input_coords["lead_time"] + np.timedelta64(6, "h")
    return output
Iterator Template
def create_iterator(self, x, coords):
    yield x, coords  # Initial condition (step 0)
    while True:
        x, coords = self.front_hook(x, coords)
        x, coords = self(x, coords)
        x, coords = self.rear_hook(x, coords)
        yield x, coords

Troubleshooting

ErrorSolution
OptionalDependencyFailureuv add --optional <group> <pkg>
Coordinate handshake failsCheck handshake_dim indices match dim position
Iterator wrong shapesDebug reshape logic with random input
ModuleNotFoundError: pytestUse uv run pytest not pytest

Reminders

DO:

  • Use uv run python for ALL Python commands

  • Use loguru.logger, never print()

  • Inherit torch.nn.Module + AutoModelMixin + PrognosticMixin

  • Yield initial condition first in create_iterator

  • Use front_hook()/rear_hook() in _default_generator

  • Include SPDX header in every .py file

DON'T:

  • Create general base classes for reuse

  • Commit API keys or comparison scripts

  • Read from evals/targets/

Files

references/method-templates.py

# SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES.
# SPDX-FileCopyrightText: All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Method Implementation Templates for Prognostic Model Wrappers.

This file contains fully-documented method templates with complete docstrings
following NumPy style. Use these as reference when implementing specific methods.

Key patterns:
- input_coords: Define coordinate system with batch, time, lead_time, variable, lat, lon
- output_coords: Validate inputs with handshake_*, increment lead_time
- __call__: Reshape E2S format → model format → run inference → reshape back
- create_iterator: Yield initial condition first, then loop with hooks
- load_model: Resolve from package, load to CPU, set eval mode
"""

from collections import OrderedDict
from collections.abc import Iterator

import numpy as np
import torch

from earth2studio.models.auto import Package
from earth2studio.models.batch import batch_coords, batch_func
from earth2studio.models.px.base import PrognosticModel
from earth2studio.utils import handshake_coords, handshake_dim
from earth2studio.utils.imports import check_optional_dependencies
from earth2studio.utils.type import CoordSystem

# =============================================================================
# COORDINATE TEMPLATES
# =============================================================================

# Example variable list (from E2STUDIO_VOCAB)
VARIABLES = ["t2m", "u10m", "v10m", "msl", "z500", "t850"]


def input_coords_template(self) -> CoordSystem:
    """Input coordinate system of the prognostic model.

    The coordinate system MUST follow this exact order:
    1. batch - np.empty(0), placeholder for batch dimension
    2. time - np.empty(0), filled at runtime
    3. lead_time - starts at 0h, incremented each step
    4. variable - model input variables from E2STUDIO_VOCAB
    5. lat - latitude array, 90 to -90 (north to south). Keep this
       public convention even when the source checkpoint expects south-to-north.
    6. lon - longitude array, 0 to 360

    Returns
    -------
    CoordSystem
        Coordinate system dictionary.
    """
    return OrderedDict(
        {
            "batch": np.empty(0),
            "time": np.empty(0),
            "lead_time": np.array([np.timedelta64(0, "h")]),
            "variable": np.array(VARIABLES),
            # Common grid sizes:
            # 0.25° global: 721 x 1440
            # 0.5° global: 361 x 720
            # 1° global: 181 x 360
            # Public Earth2Studio convention is north-to-south latitude.
            "lat": np.linspace(90, -90, 721, endpoint=True),
            "lon": np.linspace(0, 360, 1440, endpoint=False),
        }
    )


def input_coords_with_history_template(self) -> CoordSystem:
    """Input coords for models requiring history (e.g., -6h and 0h).

    Some models need multiple time steps as input. Use negative timedeltas
    for history requirements.

    Returns
    -------
    CoordSystem
        Coordinate system with history in lead_time.
    """
    return OrderedDict(
        {
            "batch": np.empty(0),
            "time": np.empty(0),
            "lead_time": np.array(
                [
                    np.timedelta64(-6, "h"),  # History: 6h before init time
                    np.timedelta64(0, "h"),  # Current time
                ]
            ),
            "variable": np.array(VARIABLES),
            "lat": np.linspace(90, -90, 721, endpoint=True),
            "lon": np.linspace(0, 360, 1440, endpoint=False),
        }
    )


@batch_coords()
def output_coords_template(self, input_coords: CoordSystem) -> CoordSystem:
    """Output coordinate system of the prognostic model.

    Parameters
    ----------
    input_coords : CoordSystem
        Input coordinates to validate and transform.

    Returns
    -------
    CoordSystem
        Output coordinates with updated lead_time.

    Raises
    ------
    ValueError
        If input coordinates are invalid.
    """
    target_input_coords = self.input_coords()

    # handshake_dim validates dimension exists at the expected index
    # Indices match position in OrderedDict:
    # batch=0, time=1, lead_time=2, variable=3, lat=4, lon=5
    handshake_dim(input_coords, "lead_time", 2)
    handshake_dim(input_coords, "variable", 3)
    handshake_dim(input_coords, "lat", 4)
    handshake_dim(input_coords, "lon", 5)

    # handshake_coords validates coordinate values match
    handshake_coords(input_coords, target_input_coords, "variable")
    handshake_coords(input_coords, target_input_coords, "lat")
    handshake_coords(input_coords, target_input_coords, "lon")

    output_coords = input_coords.copy()
    # Increment lead_time by model's time step
    output_coords["lead_time"] = input_coords["lead_time"] + np.array([self._time_step])
    return output_coords


# =============================================================================
# FORWARD PASS TEMPLATES
# =============================================================================


@batch_func()
def call_template(
    self,
    x: torch.Tensor,
    coords: CoordSystem,
) -> tuple[torch.Tensor, CoordSystem]:
    """Run prognostic model 1 step.

    Parameters
    ----------
    x : torch.Tensor
        Input tensor with shape (batch, time, lead_time, variable, lat, lon).
    coords : CoordSystem
        Input coordinate system.

    Returns
    -------
    tuple[torch.Tensor, CoordSystem]
        Output tensor and coordinates one time step ahead.
    """
    target_input_coords = self.input_coords()
    handshake_dim(coords, "lead_time", 2)
    handshake_dim(coords, "variable", 3)
    handshake_dim(coords, "lat", 4)
    handshake_dim(coords, "lon", 5)
    handshake_coords(coords, target_input_coords, "lead_time")
    handshake_coords(coords, target_input_coords, "variable")
    handshake_coords(coords, target_input_coords, "lat")
    handshake_coords(coords, target_input_coords, "lon")

    device = self.device_buffer.device
    x = x.to(device)

    # Common reshape patterns:
    #
    # Pattern 1: Model expects (batch, channel, lat, lon)
    # E2S: (batch, time, lead_time, variable, lat, lon)
    # Flatten batch*time*lead_time, variable becomes channel
    # batch_size = x.shape[0] * x.shape[1] * x.shape[2]
    # x_model = x.view(batch_size, x.shape[3], x.shape[4], x.shape[5])
    #
    # Pattern 2: Model expects (batch, time, channel, lat, lon)
    # x_model = x.squeeze(2)  # Remove lead_time dim
    #
    # Pattern 3: Model expects dict with named tensors
    # x_model = {"surface": x[..., :4, :, :], "pressure": x[..., 4:, :, :]}

    # If the source model expects a different latitude order, flip internally only.
    # Example for south-to-north model cores with public north-to-south coords:
    # x_model = torch.flip(x_model, dims=(-2,))

    # Normalize (if model requires)
    # x_model = (x_model - self.center) / self.scale

    with torch.no_grad():
        # y_model = self.model(x_model)
        pass

    # Denormalize (if model requires)
    # y_model = y_model * self.scale + self.center

    # Flip model output latitude back to public Earth2Studio order if needed.
    # y_model = torch.flip(y_model, dims=(-2,))

    # Reshape back to E2S format
    # output = y_model.view(x.shape[0], x.shape[1], x.shape[2], -1, x.shape[4], x.shape[5])

    out_coords = self.output_coords(coords)
    return x, out_coords  # Replace x with actual output


@batch_func()
def default_generator_template(
    self,
    x: torch.Tensor,
    coords: CoordSystem,
) -> Iterator[tuple[torch.Tensor, CoordSystem]]:
    """Batch-decorated generator for time integration.

    IMPORTANT: Must yield initial condition first (step 0).
    Must use front_hook and rear_hook for perturbation support.

    Parameters
    ----------
    x : torch.Tensor
        Initial condition tensor.
    coords : CoordSystem
        Initial coordinate system.

    Yields
    ------
    tuple[torch.Tensor, CoordSystem]
        Predicted state and coordinates at each time step.
    """
    # CRITICAL: Yield initial condition first (step 0)
    # This ensures the first output has lead_time = 0h
    yield x, coords

    current_x = x
    current_coords = coords
    while True:
        # front_hook: Apply perturbations before model step
        # Used by ensemble methods to inject noise
        current_x, current_coords = self.front_hook(current_x, current_coords)

        # Forward step
        current_x, current_coords = self.__call__(current_x, current_coords)

        # rear_hook: Post-processing after model step
        # Used for output transformations
        current_x, current_coords = self.rear_hook(current_x, current_coords)

        yield current_x, current_coords


def create_iterator_template(
    self,
    x: torch.Tensor,
    coords: CoordSystem,
) -> Iterator[tuple[torch.Tensor, CoordSystem]]:
    """Create time-integration iterator.

    Parameters
    ----------
    x : torch.Tensor
        Initial condition tensor.
    coords : CoordSystem
        Initial coordinate system.

    Yields
    ------
    tuple[torch.Tensor, CoordSystem]
        Predicted state and coordinates at each time step.
    """
    yield from self._default_generator(x, coords)


# =============================================================================
# MODEL LOADING TEMPLATES
# =============================================================================


@classmethod
def load_default_package_template(cls) -> Package:
    """Default pre-trained model package.

    Returns
    -------
    Package
        Model package with checkpoint files.

    Notes
    -----
    Always lock HuggingFace URLs to a specific commit:
    - Good: hf://organization/model@abc123def456
    - Bad: hf://organization/model (may change)

    Supported URL schemes:
    - hf:// - HuggingFace Hub
    - ngc:// - NVIDIA NGC
    - s3:// - AWS S3
    - gs:// - Google Cloud Storage
    - Local paths

    Warning
    -------
    NEVER commit credentials, API keys, or secrets to this file.
    If authentication is required, use environment variables:
    - HF_TOKEN for HuggingFace
    - NGC_API_KEY for NVIDIA NGC
    - AWS credentials via standard AWS environment variables
    """
    return Package(
        "hf://organization/model-name@commit_hash",
        cache_options={
            "cache_storage": Package.default_cache("model_name"),
            "same_names": True,
        },
    )


@classmethod
@check_optional_dependencies()
def load_model_template(
    cls,
    package: Package,
) -> PrognosticModel:
    """Load prognostic model from package.

    Parameters
    ----------
    package : Package
        Model package with checkpoint files.

    Returns
    -------
    PrognosticModel
        Loaded model instance.

    Notes
    -----
    Key patterns:
    1. Use package.resolve() to get local file paths
    2. Load with map_location="cpu" first
    3. Set model to eval() mode
    4. Use weights_only=False only if needed for custom classes
    """
    # Resolve files from package
    model_path = package.resolve("model.pt")

    # Load to CPU first (user moves to GPU with .to())
    core_model = torch.load(
        model_path,
        map_location="cpu",
        weights_only=False,  # Set True if no custom classes
    )
    core_model.eval()

    # Load additional files if needed
    # config = json.loads(package.resolve("config.json").read_text())
    # center = torch.from_numpy(np.load(package.resolve("center.npy")))

    return cls(core_model)


def to_template(self, device: torch.device | str) -> PrognosticModel:
    """Move model to device.

    NOTE: Only implement this if you have non-PyTorch state to manage.
    For pure PyTorch models, the inherited .to() method is sufficient.

    Use cases for custom .to():
    - ONNX Runtime: Destroy session, recreate on new device
    - JAX: Handle device placement
    - Mixed backends: Coordinate multiple frameworks

    Parameters
    ----------
    device : torch.device | str
        Target device.

    Returns
    -------
    PrognosticModel
        Model on target device.
    """
    super().to(device)
    # Handle non-PyTorch state here
    # Example for ONNX:
    # self._destroy_onnx_session()
    # self._create_onnx_session(device)
    return self

Requirements and compatibility

Written for: Claude Code

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Claude Code frontmatter, Needs an API key, Needs Python

Security

What our scanner noticed· Medium risk

  • Large base64-encoded blobs
  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
NVIDIA Earth-2 Team
Publisher
NVIDIA (Official)
Source
NVIDIA/skills · skills/earth2studio-create-prognostic · commit fce3cca
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE-APACHE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by NVIDIA Earth-2 Team or NVIDIA.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download earth2studio-create-prognostic.zip