Skip to content

Add static graph embedding caching across autoregressive rollouts - #817

Open
Sharkyii wants to merge 9 commits into
mllam:mainfrom
Sharkyii:feat/cache-static-embeddings
Open

Sharkyii wants to merge 9 commits into
mllam:mainfrom
Sharkyii:feat/cache-static-embeddings

Conversation

@Sharkyii

Copy link
Copy Markdown
Contributor

Describe your changes

Precomputes static mesh node and edge embeddings (g2m, m2g, m2m, and hierarchical mesh levels/edges) once per rollout in ARForecaster instead of re-embedding them at every autoregressive step. Static graph embeddings depend only on static buffers and trainable embedder MLPs, caching them avoids duplicate embedder forward passes and eliminates duplicate activation storage during rollout steps while preserving mathematical parity for predictions and parameter gradients.

Issue Link

Part of #70

Type of change

  • 🐛 Bug fix (non-breaking change that fixes an issue)
  • ✨ New feature (non-breaking change that adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📖 Documentation (Addition or improvements to documentation)

Checklist before requesting a review

  • My branch is up-to-date with the target branch - if not update your fork with the changes from the target branch (use pull with --rebase option if possible).
  • I have performed a self-review of my code
  • For any new/modified functions/classes I have added docstrings that clearly describe its purpose, expected inputs and returned values
  • I have placed in-line comments to clarify the intent of any hard-to-understand passages of my code
  • I have updated the README to cover introduced code changes
  • If this PR changes contributor workflow, I've updated CONTRIBUTING.md / AGENTS.md
  • I have added tests that prove my fix is effective or that my feature works
  • I have given the PR a name that clearly describes the change, written in imperative form (context).
  • I have requested a reviewer and an assignee (assignee is responsible for merging). This applies only if you have write access to the repo, otherwise feel free to tag a maintainer to add a reviewer and assignee.

Checklist for reviewers

Each PR comes with its own improvements and flaws. The reviewer should check the following:

  • the code is readable
  • the code is well tested
  • the code is documented (including return types and parameters)
  • the code is easy to maintain

Author checklist after completed review

  • I have added a line to the CHANGELOG describing this change, in a section
    reflecting type of change (add section where missing):
    • added: when you have added new functionality
    • changed: when default behaviour of the code has been changed
    • fixes: when your contribution fixes a bug
    • maintenance: when your contribution is relates to repo maintenance, e.g. CI/CD or documentation

Checklist for assignee

  • PR is up to date with the base branch
  • the tests pass
  • (if the PR is not just maintenance/bugfix) the PR is assigned to the next milestone. If it is not, propose it for a future milestone.
  • author has added an entry to the changelog (and designated the change as added, changed, fixed or maintenance)
  • Once the PR is ready to be merged, squash commits and merge the PR.

@sadamov sadamov left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @Sharkyii, nice and small. #807 is ready and goes first, so this needs a rebase onto main once #807 is merged. Here is how I would combine the two, since both touch the same predictor call.

Caching has no flag, it is always on. --gradient_checkpointing from #807 stays the only flag:

  • off (default): the static embeddings are computed once per rollout and reused in every step. Nothing is recomputed.
  • on: same caching, plus every step and the one embed_static_features call are recomputed in the backward pass instead of stored.

The second part matters: if only the steps are checkpointed, the embedder activations are stored for the whole rollout instead of being recomputed inside each step, and flag-on ends up worse than main on memory (11.8 vs 10.7 GiB at ar=8). After the rebase, ARForecaster.forward would then look like this (use_reentrant=False is fine with a function without tensor inputs and with kwargs):

        # Embed static features once and reuse them in every step
        checkpointing = self.gradient_checkpointing and self.training
        if checkpointing:
            static_embeddings = torch.utils.checkpoint.checkpoint(
                self.predictor.embed_static_features, use_reentrant=False
            )
        else:
            static_embeddings = self.predictor.embed_static_features()
        step_kwargs = (
            {}
            if static_embeddings is None
            else {"static_embeddings": static_embeddings}
        )

        for i in range(pred_steps):
            forcing = forcing_features[:, i]
            boundary_state = boundary_states[:, i]

            if checkpointing:
                pred_state, pred_std = torch.utils.checkpoint.checkpoint(
                    self.predictor,
                    prev_state,
                    prev_prev_state,
                    forcing,
                    use_reentrant=False,
                    **step_kwargs,
                )
            else:
                pred_state, pred_std = self.predictor(
                    prev_state, prev_prev_state, forcing, **step_kwargs
                )

I would also mention the embed_static_features call in the gradient_checkpointing docstring, and add @pytest.mark.parametrize("gradient_checkpointing", [False, True]) to the parity test, since the #807 tests use a mock predictor without static features. test_ar_forecaster_checkpoint_called_only_during_training then expects 5 checkpoint calls instead of 4 (4 steps + embed_static_features).

I ran this combined version on 1x GH200 with the same GraphLAM setup as in #70 and #807 (keisler graph on a 512x512 DummyDatastore, 70 state / 10 forcing, hidden_dim=64, 4 processor layers, batch size 1).

Flag off, main -> this PR:

  • ar=1: 7.2 -> 7.3 GiB, 0.04 -> 0.04 s
  • ar=4: 26.0 -> 22.3 GiB, 0.15 -> 0.12 s
  • ar=8: 51.3 -> 42.6 GiB, 0.29 -> 0.24 s, i.e. ~1.2 GiB less per extra AR step as estimated in #70

Flag on, #807 alone -> #807 + this PR:

  • ar=1: 7.5 -> 6.3 GiB, 0.05 -> 0.05 s
  • ar=4: 8.9 -> 8.8 GiB, 0.21 -> 0.18 s
  • ar=8: 10.7 -> 10.5 GiB, 0.42 -> 0.35 s

Eval forward (no grad) at ar=8 also goes from 0.13 to 0.11 s.

GraphEFM / GraphEFMMultiScale still embed the static features in every step, the NOTE in BaseGraphEFM.embedd_grid_and_graph already anticipates moving this out of the AR loop. I would do that in a follow-up PR with the same embed_static_features hook. Would you be up for it?

The inline comments are mostly about keeping static_embeddings opt-in instead of adding it to every StepPredictor.forward, the rest is dead fallbacks, stale comments and one duplicate test.

Comment thread tests/test_static_edge_caching.py Resolved
Comment thread tests/test_static_edge_caching.py Resolved
Comment thread tests/test_static_edge_caching.py Resolved
@Sharkyii

Copy link
Copy Markdown
Contributor Author

Thanks @sadamov i have pushed the commit from your review on static feature caching, now i will open a PR for moving static feature embedding out of the loop for GraphEFM.

@Sharkyii
Sharkyii force-pushed the feat/cache-static-embeddings branch from 5b96487 to 8953c1d Compare October 22, 2026 11:57
Sharkyii and others added 3 commits October 31, 2026 16:13
…ecast refactor

- Update test imports from ARForecaster to DeterministicARForecaster
- Compute embed_static_features once per rollout inside unroll_forecast
- Add gradient_checkpointing parameter to DeterministicARForecaster
- Avoid dictionary unpacking into torch.utils.checkpoint to satisfy ty

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
@sadamov

sadamov commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@Sharkyii this one is affected by #700 merger. and #807 is also outdated now.

@Sharkyii

Sharkyii commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

yeah i will fix the conflicts in #807 then later this..

Sharkyii and others added 2 commits November 14, 2026 11:56
Resolve merge conflicts with main (mllam#807, mllam#700) and update test expectations for gradient checkpointing.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
@Sharkyii

Copy link
Copy Markdown
Contributor Author

@joeloskarsson could you please take a look at this :)
Thanks!

Comment on lines +116 to +132
if static_embeddings is not None:
pred_state, pred_std = torch.utils.checkpoint.checkpoint(
predictor,
prev_state,
prev_prev_state,
forcing,
use_reentrant=False,
static_embeddings=static_embeddings,
)
else:
pred_state, pred_std = torch.utils.checkpoint.checkpoint(
predictor,
prev_state,
prev_prev_state,
forcing,
use_reentrant=False,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks unnecessary, why can't static_embedding just be fed directly when it is None? If this does not work for some reason with the checkpoint, pls add a comment to clarify.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Predictors that return None from embed_static_features() (such as PersistencePredictor, BaseGraphEFM, and TrainableStepPredictor) do not accept static_embeddings in forward(), so passing static_embeddings=None raises TypeError

("training", "checkpointing", "expected_calls"),
[
(True, True, 4),
(True, True, 5),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this change? Worth documenting with a comment?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rollout now also wraps predictor.embed_static_features in checkpoint once before the pred_steps = 4 loop, making it 1 + 4 = 5 calls. will add a comment documenting that breakdown.

@joeloskarsson joeloskarsson added this to the v0.9.0 (proposed) milestone Dec 1, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants