Skip to content

Add transfer learning support for GraphLAM - #856

Open
Karvy-Singh wants to merge 17 commits into
mllam:mainfrom
Karvy-Singh:gnn_transfer_learning
Open

Karvy-Singh wants to merge 17 commits into
mllam:mainfrom
Karvy-Singh:gnn_transfer_learning

Conversation

@Karvy-Singh

@Karvy-Singh Karvy-Singh commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Describe your changes

This PR adds selective pretrained component initialization and freezing for GraphLAM transfer learning.

A pretrained GraphLAM model may have useful learned representations even when the target dataset has different input/output weather variables. Full checkpoint loading fails when parameter shapes differ, and strict=False does not ignore shape mismatches.

The implementation:

  • Integrates selective weight initialization with Lightning's existing load_from_checkpoint() and on_load_checkpoint() mechanisms.
  • Supports transferring compatible components such as processor, mesh_embedder, and m2m_embedder, while preserving newly initialized target layers.
  • Validates selected component paths, state keys, and tensor shapes before loading.
  • Supports freezing selected components with requires_grad_(False).
  • Exposes transfer learning through the training CLI, Python API, and configuration.
  • Starts a fresh training run without restoring the source checkpoint's optimizer or training progress.
  • Validates graph and model-behavior compatibility metadata before loading, with separate explicit overrides for trusted legacy metadata and intentional behavior changes.
  • Adds regressions for selective loading, one-shot restoration, freezing, malformed metadata, behavior mismatches, BF16/FP64 graph identity, and full resume behavior.
  • Updates the README, quickstart documentation.

Compatibility metadata design

Why it exists: graph topology and graph features are non-persistent buffers, so parameter names and shapes can match even when source and target graphs or execution behavior differ.

Checkpoint schema: checkpoints store provider metadata under checkpoint["neural_lam_pretrained_compatibility"], keyed by nested module path. Each GraphLAM provider contains a non-empty graph fingerprint string and a model_behavior mapping with the required predictor, mesh aggregation and grid/mesh GNN fields. Malformed values, missing providers and unknown claims fail before any override is considered.

Graph identity lifecycle: GraphLAM computes its SHA-256 graph fingerprint eagerly from the normalized construction-time graph representation, before Lightning can cast buffers for runtime precision. Tensor names, collection positions, original dtypes, shapes and bytes plus the grid-node count contribute to the fingerprint. This keeps identity stable across FP32, BF16 and FP64 execution and avoids BF16 NumPy conversion failures.

Behavior compatibility: GraphLAM records execution settings that can preserve parameter shapes while changing behavior, currently predictor identity, mesh aggregation and grid/mesh GNN types. A mismatch fails by default. --allow_incompatible_pretrained_behavior permits an intentional experiment with a warning listing the accepted differences; it applies only after both behavior mappings pass structural validation and cannot bypass a graph, metadata, key or shape mismatch.

Loading lifecycle: selective initialization validates metadata and all selected state before replacing entries in a fresh complete target state. The selection and its overrides are consumed after this one initialization, so every later restore on the same instance performs ordinary full restoration. Full restores also validate metadata when it is present, while metadata-free legacy checkpoints remain loadable through the normal resume path.

Missing metadata: selective initialization rejects metadata-free checkpoints by default. --allow_missing_compatibility_metadata permits a trusted legacy checkpoint with a rank-zero warning after the caller manually verifies both graph and model-behavior compatibility. Present malformed or mismatched metadata cannot use this override.

Guarantee boundary: matching graph identity proves equality only for the registered normalized graph tensors and grid-node count included in the fingerprint. It does not prove dataset-variable meaning, ordering, units, normalization compatibility or scientific usefulness. The current release requires complete graph equality; component-specific and cross-topology compatibility remain out of scope.

One-model scope: predictors must explicitly opt into selective transfer. GraphLAM is currently enabled; HiLAM, HiLAMParallel and Graph-EFM remain rejected until their behavior claims and architecture-specific tests are implemented.

Scope: This PR focuses on GraphLAM. The underlying loading mechanism is generic, but support for HiLAM and HiLAMParallel will be implemented and tested later. Cross-topology transfer is not supported.

Dependencies: No new runtime dependencies. Only trusted Lightning checkpoints should be loaded.

Issue Link

Closes #823

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](https://www.gitkraken.com/learn/git/best-practices/git-commit-message#using-imperative-verb-form)).
  • 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.

Copilot AI balanced review requested due to automatic review settings November 4, 2026 10:57

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@Karvy-Singh
Karvy-Singh marked this pull request as draft November 4, 2026 11:03
@joeloskarsson

Copy link
Copy Markdown
Contributor

In general this seems reasonable to me. I don't follow exactly how this would fit and be called from the rest of the codebase, in particular when using a LightningModule and the standard training script, but I am sure there is some good solution. I'd focus on that before going into different models. Also avoid anything model-specific in this, since that is hard to maintain.

Without looking too much into it, I am wondering if we need to rebuild so much of this machinery, and if not

def on_load_checkpoint(self, checkpoint: dict[str, Any]) -> None:
could be used here to augment the loading based on which components to load. If you already thought about this then no worries, but if not maybe it's worth investigating.

@Karvy-Singh

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback @joeloskarsson !!

I am wondering if we need to rebuild so much of this machinery, and if not [the existing on_load_checkpoint implementation] could be used here to augment the loading based on which components to load.

My initial reason for keeping selective initialization in a separate utility was to distinguish it from Lightning's full checkpoint-resume path. Using trainer.fit(ckpt_path=...) can also restore optimizer, epoch, and loop state, whereas transfer learning should only initialize selected weights and start a fresh training run.

I also considered using on_load_checkpoint(), but simply filtering the checkpoint's state_dict would result in missing keys during Lightning's subsequent strict loading. One possibility would be to merge selected pretrained weights with the target model's initialized state, but that seemed to introduce additional complexity into the existing checkpoint-loading path.

I think a reasonable direction would be to keep selective initialization as a separate step after constructing the target predictor and before starting training, while extracting and reusing the existing checkpoint key-remapping logic from on_load_checkpoint(). This would avoid duplicating compatibility handling without changing the behavior of normal checkpoint restoration.

How do you feel about the same ?
Also I will investigate this approach and prioritize integration with the existing training workflow before expanding support to other models and components.

@Karvy-Singh

Copy link
Copy Markdown
Contributor Author

I don't follow exactly how this would fit and be called from the rest of the codebase, in particular when using a LightningModule and the standard training script

yes, this needs to be integrated into the existing training workflow. As mentioned in the PR description, I kept this as a draft to first validate the selective weight initialization mechanism before wiring it into the training configuration, CLI, and Python API. The plan was to integrate it after establishing that the initial approach was reasonable.

Also avoid anything model-specific in this, since that is hard to maintain.

again the initial GraphLAM-specific implementation was intentional, as I wanted to validate the approach for one architecture before extending it to HiLAM and HiLAMParallel. That said, agreed and will take of the same.

@joeloskarsson joeloskarsson added this to the v0.8.0 (proposed) milestone Nov 7, 2026
@joeloskarsson

Copy link
Copy Markdown
Contributor

From just reading through your reasoning I see that you considered what needs to be rebuilt vs reused, so that is great :)

I think a reasonable direction would be to keep selective initialization as a separate step after constructing the target predictor and before starting training, while extracting and reusing the existing checkpoint key-remapping logic from on_load_checkpoint(). This would avoid duplicating compatibility handling without changing the behavior of normal checkpoint restoration.

This seems like a good direction to me.

I have still not looked at all the details here, and would probably want someone else to also properly review this later on. But that is for down the line.

@Karvy-Singh

Copy link
Copy Markdown
Contributor Author

Hi @joeloskarsson and @sadamov

Completed the major transfer learning support for GraphLAM.
Please have a look and let me know anything that needs to be changed.

Once we are on the same page regarding this, will proceed ahead with other models.
Thank you.

Comment thread README.md Outdated
### Transfer learning

Selected model components can initialize a fresh training run from a trusted
Lightning checkpoint. Components are identified by their dotted module paths;

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.

(Also in other places) Clarify what "dotted" means in this context. Maybe easiest with a small example.

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.

dotted path here refers to components such as forecaster.predictor.processor and such
also agreed, my bad, passed this very example in the docstrings all across so that it is clearer

Comment thread neural_lam/models/modules/base.py Outdated
Comment on lines +558 to +560
def _get_pretrained_compatibility_metadata(
self,
) -> dict[str, dict[str, str]]:

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.

I feel like there is this whole system of compatability metadata introduced here that is a bit opaque. It would be best to 1. Add some explanation of this in the PR, as probably a main concern of reviews here is the design of this system, but reading the code is not an efficient way to discuss this. 2. Make sure that some clear documentation around this metadata system is implemented together with the code. There is documentation added, but I don't think it enough to fully grasp it.

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.

will add more details in the comments, updated the PR/code with few changes in the docstrings.
apologies if it is still not descriptive/clear enough, do let me know if that's the case

@Karvy-Singh

Karvy-Singh commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

This comment records the complete implementation lifecycle and compatibility policy after addressing the review findings. Permanent local contracts are also documented in the relevant method docstrings.

Execution path

Selective initialization follows this path:

CLI / Python API
    |
    v
TrainRunConfig
    |
    v
train_model.fit()
    |
    +--> Validate option combinations
    +--> Construct target predictor and forecaster
    +--> Verify predictor transfer capability
    |
    +--> DeterministicForecastingModule.load_from_checkpoint()
             |
             +--> Construct target forecasting module
             +--> Apply existing checkpoint key migrations
             +--> Validate compatibility metadata
             +--> Validate every selected component
             +--> Merge selected source state into fresh target state
             +--> Consume the transfer instruction
             +--> Lightning performs strict state loading
    |
    +--> Freeze requested components
    +--> Log frozen component paths
    +--> Trainer.fit(ckpt_path=None)

The source checkpoint initializes selected model state but is not passed to Trainer.fit(). The new run therefore receives a fresh optimizer, epoch, global step, scheduler and trainer-loop state.

Normal --load resume remains separate and passes its checkpoint to Trainer.fit().

Configuration forwarding

The transfer settings are represented in TrainRunConfig and exposed through both the CLI and Python API:

Option Purpose
pretrained_checkpoint Source Lightning checkpoint
pretrained_components Nested module paths to initialize
freeze_components Nested module paths to freeze
allow_missing_compatibility_metadata Permit a trusted checkpoint created before compatibility metadata
allow_incompatible_pretrained_behavior Permit intentional model-behavior differences

pretrained_checkpoint and pretrained_components must be supplied together.

Selective initialization cannot be combined with:

  • --load
  • Evaluation
  • --restore_opt

Both compatibility overrides require selective initialization.

Freezing is training-only but can be used independently of transfer initialization.

Supported predictors

Transfer support is an explicit predictor capability:

StepPredictor.supports_pretrained_transfer = False

GraphLAM opts in:

GraphLAM.supports_pretrained_transfer = True

Both train_model.fit() and BaseForecastingModule reject selective initialization when the target predictor has not opted in.

This prevents HiLAM, HiLAMParallel, Graph-EFM or future models from silently inheriting partial compatibility behavior before their architecture-specific claims and tests exist.

The component-loading machinery remains model-independent. Supporting another model requires that predictor to opt in and provide complete compatibility metadata.

Target-first construction

The target predictor and forecaster are constructed before loading the source checkpoint:

predictor = build_predictor(
    predictor_class,
    target_hparams,
    target_config,
    target_datastore,
)

forecaster = DeterministicARForecaster(
    predictor,
    target_datastore,
    config=target_config,
    loss=train_config.loss,
)

These target objects are passed explicitly to Lightning:

DeterministicForecastingModule.load_from_checkpoint(
    source_checkpoint,
    forecaster=forecaster,
    config=target_config,
    datastore=target_datastore,
    pretrained_components=...,
    strict=True,
)

This preserves freshly constructed target layers whose shapes depend on the target dataset while allowing compatible internal components to receive source values.

Component paths

Components are identified by nested module paths relative to the forecasting module.

For example:

forecaster.predictor.processor

means:

BaseForecastingModule
    -> forecaster
        -> predictor
            -> processor

Paths are resolved with:

torch.nn.Module.get_submodule()

Path validation rejects:

  • A single string instead of a sequence
  • Non-string values
  • Empty paths
  • Leading or trailing periods
  • Repeated periods
  • Duplicate paths
  • Parent and child paths selected together

Selecting both:

forecaster.predictor
forecaster.predictor.processor

is rejected because the parent already contains the child.

Existing checkpoint migrations

BaseForecastingModule.on_load_checkpoint() continues to apply the existing key migrations before selective validation.

This includes moving older flat predictor keys under:

forecaster.predictor.

and preserving the special migrations for:

per_var_std
g2m_gnn.grid_mlp
interior_mask_bool

Selective initialization therefore uses the same legacy migration path as ordinary checkpoint restoration.

Atomic component validation

_merge_pretrained_component_state() starts from the complete fresh target state:

target_state = self.state_dict()

For each selected path, it obtains the target component's expected state:

component = self.get_submodule(path)
component_state = component.state_dict()

It then validates:

  • The component exists
  • The component contains state
  • Source and target state-key sets match exactly
  • Corresponding values agree on whether they are tensors
  • Corresponding tensors have identical shapes

All selected components are validated before any source values are added to the returned state.

Conceptually:

selected_source_state = {}

for path in selected_components:
    validate_complete_component(path)
    selected_source_state.update(source_values)

target_state.update(selected_source_state)
return target_state

The returned dictionary is complete:

Unselected entries = fresh target values
Selected entries   = validated source values

Lightning then performs its normal strict state load. The implementation does not use strict=False and does not directly assign parameters outside Lightning.

One-time initialization lifecycle

The transfer settings are transient constructor state:

self._pretrained_components
self._allow_missing_compatibility_metadata
self._allow_incompatible_pretrained_behavior

They are not saved through save_hyperparameters().

After compatibility and component validation succeed and the merged state has been prepared, the settings are consumed:

self._pretrained_components = ()
self._allow_missing_compatibility_metadata = False
self._allow_incompatible_pretrained_behavior = False

This ensures selective initialization runs exactly once.

A later restore on the same module instance performs ordinary full restoration rather than retaining the instance's current unselected weights.

A regression now covers:

  1. Selectively initializing a processor.
  2. Mutating an unselected output layer on that same instance.
  3. Restoring a complete checkpoint through Lightning's checkpoint connector.
  4. Verifying the unselected output layer is restored from the requested checkpoint.

Compatibility metadata

Compatibility metadata is stored under:

checkpoint["neural_lam_pretrained_compatibility"]

The checkpoint value is keyed directly by provider module path:

{
    "forecaster.predictor": {
        "graph": "<sha256 fingerprint>",
        "model_behavior": {
            "predictor": "graph_lam",
            "mesh_aggr": "sum",
            "g2m_gnn_type": "InteractionNet",
            "m2g_gnn_type": "InteractionNet",
        },
    },
}

The outer key identifies the component that owns the compatibility requirements. The two supported claims are graph and model_behavior.

Provider contract

Compatibility providers are discovered through named_modules().

A component opts in by defining:

get_pretrained_compatibility_metadata()

The provider must:

  • Be callable without arguments
  • Return a non-empty plain mapping
  • Use only the supported graph and model_behavior claim names
  • Return a non-empty fingerprint string for graph
  • Return exactly the required non-empty string fields for model_behavior
  • Produce deterministic results for the model lifetime
  • Remain independent of device, training mode and runtime precision

Provider failures are wrapped with the owning module path. The forecasting module owns collection, checkpoint storage and common validation, while the predictor owns the claim values relevant to its execution.

Metadata validation

Present metadata is structurally validated before source and target values are compared or an override is considered.

The validator rejects:

  • Non-mapping metadata
  • Invalid or empty provider paths
  • Empty provider records
  • Missing or unexpected providers
  • Unsupported claim names
  • Missing or unexpected claims
  • Empty or non-string graph fingerprints
  • Missing, extra, empty or non-string model-behavior fields

Source and target provider paths and claim names must match exactly. allow_incompatible_pretrained_behavior is considered only after both behavior mappings pass this validation.

Construction-time graph identity

Graph tensors are non-persistent buffers and are absent from the normal state_dict, even though they affect model execution.

Graph identity is computed immediately after load_and_register_graph() produces the normalized graph representation.

It is therefore calculated before Lightning can cast buffers for FP16, BF16 or FP64 training.

The immutable fingerprint is stored as a Python string:

self._graph_compatibility_fingerprint

Runtime device or precision conversion cannot alter it.

Fingerprint inputs

The graph fingerprint includes:

num_grid_nodes
g2m_edge_index
m2g_edge_index
m2m_edge_index
mesh_up_edge_index
mesh_down_edge_index
g2m_features
m2g_features
m2m_features
mesh_up_features
mesh_down_features
mesh_static_features

For each tensor, the hash includes:

  • Attribute name
  • Position within a tensor collection
  • Construction-time dtype
  • Shape
  • Exact contiguous CPU bytes

Bytes are obtained through a torch.uint8 view:

tensor_cpu = tensor.detach().cpu().contiguous()
tensor_bytes = tensor_cpu.view(torch.uint8).numpy().tobytes()

This works for BF16 without asking NumPy to represent torch.bfloat16.

SHA-256 is used as a compact deterministic identifier, not as a security mechanism.

Precision guarantees

Because identity is computed during model construction:

  • An ordinary BF16 checkpoint can be saved without conversion errors.
  • An FP64-trained source retains the same graph identity as a fresh target constructed from the same graph.
  • Device movement does not change identity.
  • Runtime precision conversion does not change identity.

Graph tensors are treated as immutable model structure after construction. In-place graph mutation after identity creation is outside the supported model lifecycle.

Graph compatibility policy

The current policy requires equality of the complete normalized graph representation.

The policy is global rather than selected-component-specific.

A graph mismatch is always an error and cannot be overridden.

This intentionally does not attempt to infer whether a particular selected component could theoretically work across graph topologies. Component-specific and cross-topology compatibility require separate definitions and tests.

Model-behavior compatibility

Graph and parameter-shape equality do not guarantee equivalent execution.

For example:

mesh_aggr="sum"
mesh_aggr="mean"

can produce identical parameter keys and shapes while applying those parameters differently.

GraphLAM therefore provides a separate model_behavior claim containing:

  • Stable predictor identity
  • Mesh aggregation
  • Grid-to-mesh GNN type
  • Mesh-to-grid GNN type

A behavior mismatch fails by default.

For an intentional behavior-changing experiment, the caller can use:

--allow_incompatible_pretrained_behavior

The warning identifies the differing fields.

This override applies only to a valid model_behavior value mismatch. It cannot bypass:

  • Graph mismatches
  • Metadata schema errors
  • Missing providers
  • Unknown versions
  • Component key mismatches
  • Tensor shape mismatches

Missing metadata policy

A metadata-free checkpoint is treated as a legacy checkpoint.

Selective initialization rejects it by default.

The caller can use:

--allow_missing_compatibility_metadata

after manually verifying both graph and model-behavior compatibility.

The warning is emitted on rank zero.

The override applies only when the metadata field is genuinely absent. Present None, malformed metadata or known mismatches remain errors.

Ordinary full restoration still accepts metadata-free legacy checkpoints.

Full restoration behavior

Compatibility validation is no longer limited to selective initialization.

When a complete checkpoint contains compatibility metadata, ordinary full restoration validates it against the constructed target before loading.

This prevents the following sequence:

  1. Construct a model with a different same-shaped graph.
  2. Restore weights from an incompatible checkpoint.
  3. Save a new checkpoint.
  4. Incorrectly label those weights with the new target graph metadata.

Metadata-free legacy checkpoints remain supported for ordinary full restoration.

Freezing

Freezing is applied after checkpoint initialization and before Trainer.fit():

model.freeze_components(train_config.freeze_components)

Every path is resolved before any parameter is changed.

Each valid component is frozen recursively with:

component.requires_grad_(False)

Training is rejected if freezing leaves no trainable parameters.

The normalized frozen component paths are logged prominently on rank zero.

Freezing remains runtime configuration rather than checkpoint state. Users must repeat --freeze_components when resuming a run that should remain frozen.

Guarantee boundary

A matching graph claim establishes equality only for the normalized graph tensors and grid-node count included in the fingerprint.

A matching behavior claim establishes equality only for the recorded GraphLAM execution settings.

State validation establishes compatible keys, tensor status and shapes for selected components.

These checks do not establish compatibility of:

  • Dataset-variable meaning
  • Dataset-variable ordering
  • Physical units
  • Normalization statistics
  • Forcing semantics
  • Static feature semantics
  • External datastore metadata
  • Scientific interpretation
  • Scientific usefulness of transferred weights

Scientific suitability remains the experimenter's responsibility.

Current scope

GraphLAM is the only predictor enabled for selective transfer.

The following remain intentionally unsupported:

  • HiLAM transfer
  • HiLAMParallel transfer
  • Graph-EFM transfer
  • Cross-topology transfer
  • Component-specific graph compatibility
  • Automatic persistence of freezing settings

The generic loading mechanism can support these later, but each predictor must provide complete behavior claims and architecture-specific regression tests before opting in.

Verification

The implementation is covered by regressions for:

  • Selective loading across dataset dimensions
  • Preservation of unselected target state
  • Exact selected-state loading
  • Atomic multi-component validation
  • Invalid and overlapping component paths
  • Missing and unexpected state keys
  • Shape mismatches
  • Metadata-free legacy checkpoints
  • Malformed metadata
  • Unsupported document and claim versions
  • Provider contract failures
  • Graph topology and feature mismatches
  • Non-overridable graph mismatches
  • GraphLAM behavior mismatches
  • Explicit behavior override warnings
  • BF16 ordinary checkpoint saving
  • FP64 source transfer
  • Precision-stable graph identity
  • One-shot initialization
  • Same-instance full restoration
  • Full-restore graph mismatch rejection
  • Fresh optimizer and trainer state
  • Full optimizer and loop-state resume
  • Unsupported predictor rejection
  • Frozen-path logging
  • CLI/API/config parity

@Sir-Sloth-The-Lazy Sir-Sloth-The-Lazy left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Three reproduced checkpoint bugs are recorded inline, including a regression in ordinary training without transfer enabled. I have found some gaps, thank you for the contribution and the work

Comment thread neural_lam/models/modules/base.py Resolved
@Sir-Sloth-The-Lazy

Copy link
Copy Markdown
Collaborator

The core design is reasonable for a first version, but I would ask for changes before approving it. After reading the [design explanation](#856 (comment)), my main concern is the definition and lifecycle of “compatibility.”

The strongest decisions are constructing the target model first, validating selected components before loading, preserving unselected target weights, reusing Lightning’s checkpoint migrations, and starting transfer runs with fresh optimizer state; these fit the existing architecture and the stated use case.

My critique is:

  1. Requiring identical graphs is an acceptable scope restriction.
    The author explicitly limits this version to the same graph, so I would accept that restriction without demanding cross-topology support; however, the documentation should describe it as the supported policy for this release, because matching graph bytes alone does not establish whether transferred weights are scientifically appropriate.

  2. Graph identity needs to be independent of training precision.
    The design treats graph buffers as immutable, but Lightning can change their dtype, making a lazily computed fingerprint depend on when it is first requested; compute identity from the normalized graph representation before runtime precision conversion, which addresses the underlying design flaw behind both precision bugs already reported.

  3. The compatibility guarantee omits model behavior.
    For example, mesh_aggr="sum" and "mean" can have matching graph fingerprints and parameter shapes while applying those weights differently; the design should explicitly decide whether such architectural changes are allowed experiments, reported warnings, or errors, and document that graph equality plus shape equality does not establish behavioral equivalence.

  4. Versioning the metadata key does not yet provide an evolution policy.
    Comparing the entire metadata dictionary means adding a new provider or schema key can reject an otherwise usable checkpoint; before this becomes a persistent checkpoint format, document how supported versions are compared, how unknown versions are handled, and what happens when a module path changes, while retaining conservative rejection where compatibility cannot be established.

  5. Selective initialization must be a one-time operation.
    Keeping transfer instructions active on the module couples initialization to every later checkpoint restore, which caused the silent partial-restoration bug; reusing on_load_checkpoint() remains reasonable provided the selection is consumed after initialization and subsequent loads follow normal full-restoration behavior.

  6. The provider abstraction is sensible, but its contract needs tightening.
    Letting graph components own their metadata keeps GraphLAM-specific logic out of the forecasting module, but the current implementation should state precisely what providers return, when their results are stable, and how failures are reported; I would keep this small rather than build a general compatibility framework before another model needs it.

The freezing policy is also defensible for this version: the README explicitly requires users to repeat the setting when resuming, although logging the frozen component paths prominently would make accidental unfreezing easier to detect.

My recommendation is to retain the overall architecture, fix the fingerprint and initialization lifecycles before merging, and add a short repository design document specifying the compatibility guarantees and schema-evolution policy; cross-topology transfer and automatic restoration of freezing settings can remain follow-up work.

@Karvy-Singh

Karvy-Singh commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@Sir-Sloth-The-Lazy

updated the prev comment which is acting as docs. Please check the same.

also ddressed the review findings while retaining the target-first Lightning architecture:

  1. Graph identity is now computed eagerly from the normalized construction-time graph, before Lightning precision conversion.
  2. BF16 checkpoint saving uses a uint8 byte view, and FP64 transfer now retains the same graph identity.
  3. GraphLAM now records a separate model-behavior claim for predictor identity, mesh aggregation, and grid/mesh GNN types.
  4. Behavior mismatches fail by default; --allow_incompatible_pretrained_behavior permits an intentional experiment with a detailed warning.
  5. Compatibility metadata now uses validated provider records with strict graph and model-behavior value schemas; malformed values fail before overrides are considered.
  6. Provider output is validated for callable behavior, required claim fields and types, and deterministic ownership by module path.
  7. Transfer selection and both overrides are consumed after successful initialization, so later restores on the same instance perform full restoration.
  8. Full checkpoint restores now validate present metadata, while metadata-free legacy checkpoints remain supported for normal resume.
  9. Missing-metadata warnings now cover both graph and model-behavior responsibility and are emitted on rank zero.
  10. Frozen component paths are logged explicitly.
  11. Transfer support is now an explicit predictor capability. GraphLAM opts in; HiLAM, HiLAMParallel and Graph-EFM remain rejected until their compatibility claims and tests are implemented.
  12. Added regressions for the three reproduced checkpoint bugs, malformed metadata, behavior overrides, same-instance restoration, full-restore mismatches, unsupported predictors, and logging.

@Sir-Sloth-The-Lazy Sir-Sloth-The-Lazy added the enhancement New feature or request label Nov 22, 2026
@Sir-Sloth-The-Lazy Sir-Sloth-The-Lazy self-assigned this Nov 22, 2026

@Sir-Sloth-The-Lazy Sir-Sloth-The-Lazy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working through the earlier feedback, @Karvy-Singh :)

The 69 focused transfer, checkpoint, CLI/API and persistence tests passed locally, including the regressions for the three checkpoint bugs from my earlier review.

I left one remaining metadata validation edge case inline, with a reproduction.

Please also add the required CHANGELOG.md entry under Added, linking #856 and crediting yourself, before marking this ready for review.

Comment thread neural_lam/models/modules/base.py Resolved

@Sir-Sloth-The-Lazy Sir-Sloth-The-Lazy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working through this, @Karvy-Singh. I reviewed GraphLAM as the foundation for the other models, and I’d keep #856 and #823 scoped to GraphLAM while we address the checkpoint issues below. Once that’s ready for review, please open a linked follow-up for HiLAM and HiLAMParallel.

Comment thread neural_lam/models/modules/base.py Resolved
Comment thread neural_lam/train_model.py Resolved
Comment thread neural_lam/config.py Resolved
Comment thread neural_lam/train_model.py Resolved
Comment thread docs/user-guide/training.md Resolved
@Karvy-Singh

Copy link
Copy Markdown
Contributor Author

Hi @Sir-Sloth-The-Lazy,
Thank you for your guidance and suggestions all along, this PR is ready for review now.

Comment thread neural_lam/train_model.py

variable = "TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"
previous_value = os.environ.get(variable)
os.environ[variable] = "1"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I reproduced two overlapping calls through the older-Lightning fallback leaving TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1 after both returned. That changes the default for unrelated torch.load calls in the same process. Could we scope weights_only=False to the requested checkpoint, even if that means raising the Lightning minimum?

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.

The project currently supports pytorch-lightning>=2.0.3, so the unsafe fallback was intended to preserve that range with PyTorch 2.6+. Since weights_only=False cannot be scoped safely through the older Lightning API, we will have to change the minimum version req in pyproject.toml and i am not sure how it will affect the rest of the repo.

Do you have any suggestions what can be done ?

Comment thread neural_lam/models/modules/base.py Resolved
Comment thread neural_lam/models/modules/base.py Resolved
@Karvy-Singh

Karvy-Singh commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @Sir-Sloth-The-Lazy
Please let me know the final decision about the lightning module version (as described in the inline review), will fix this particular issues + others.

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

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Support selective pretrained weight loading for GraphLAM transfer learning

4 participants