Repository navigation
Add transfer learning support for GraphLAM - #856
Karvy-Singh wants to merge 17 commits into
Conversation
There was a problem hiding this comment.
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.
|
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 neural-lam/neural_lam/models/modules/base.py Line 1024 in 5310fe8 |
|
Thanks for the feedback @joeloskarsson !!
My initial reason for keeping selective initialization in a separate utility was to distinguish it from Lightning's full checkpoint-resume path. Using I also considered using 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 How do you feel about the same ? |
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.
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. |
|
From just reading through your reasoning I see that you considered what needs to be rebuilt vs reused, so that is great :)
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. |
|
Hi @joeloskarsson and @sadamov Completed the major transfer learning support for GraphLAM. Once we are on the same page regarding this, will proceed ahead with other models. |
| ### Transfer learning | ||
|
|
||
| Selected model components can initialize a fresh training run from a trusted | ||
| Lightning checkpoint. Components are identified by their dotted module paths; |
There was a problem hiding this comment.
(Also in other places) Clarify what "dotted" means in this context. Maybe easiest with a small example.
There was a problem hiding this comment.
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
| def _get_pretrained_compatibility_metadata( | ||
| self, | ||
| ) -> dict[str, dict[str, str]]: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
|
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 pathSelective initialization follows this path: The source checkpoint initializes selected model state but is not passed to Normal Configuration forwardingThe transfer settings are represented in
Selective initialization cannot be combined with:
Both compatibility overrides require selective initialization. Freezing is training-only but can be used independently of transfer initialization. Supported predictorsTransfer support is an explicit predictor capability: StepPredictor.supports_pretrained_transfer = FalseGraphLAM opts in: GraphLAM.supports_pretrained_transfer = TrueBoth 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 constructionThe 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 pathsComponents are identified by nested module paths relative to the forecasting module. For example: means: Paths are resolved with: torch.nn.Module.get_submodule()Path validation rejects:
Selecting both: is rejected because the parent already contains the child. Existing checkpoint migrations
This includes moving older flat predictor keys under: and preserving the special migrations for: Selective initialization therefore uses the same legacy migration path as ordinary checkpoint restoration. Atomic component validation
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:
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_stateThe returned dictionary is complete: Lightning then performs its normal strict state load. The implementation does not use One-time initialization lifecycleThe transfer settings are transient constructor state: self._pretrained_components
self._allow_missing_compatibility_metadata
self._allow_incompatible_pretrained_behaviorThey are not saved through 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 = FalseThis 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:
Compatibility metadataCompatibility 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 Provider contractCompatibility providers are discovered through A component opts in by defining: get_pretrained_compatibility_metadata()The provider must:
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 validationPresent metadata is structurally validated before source and target values are compared or an override is considered. The validator rejects:
Source and target provider paths and claim names must match exactly. Construction-time graph identityGraph tensors are non-persistent buffers and are absent from the normal Graph identity is computed immediately after 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_fingerprintRuntime device or precision conversion cannot alter it. Fingerprint inputsThe graph fingerprint includes: For each tensor, the hash includes:
Bytes are obtained through a tensor_cpu = tensor.detach().cpu().contiguous()
tensor_bytes = tensor_cpu.view(torch.uint8).numpy().tobytes()This works for BF16 without asking NumPy to represent SHA-256 is used as a compact deterministic identifier, not as a security mechanism. Precision guaranteesBecause identity is computed during model construction:
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 policyThe 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 compatibilityGraph and parameter-shape equality do not guarantee equivalent execution. For example: can produce identical parameter keys and shapes while applying those parameters differently. GraphLAM therefore provides a separate
A behavior mismatch fails by default. For an intentional behavior-changing experiment, the caller can use: The warning identifies the differing fields. This override applies only to a valid
Missing metadata policyA metadata-free checkpoint is treated as a legacy checkpoint. Selective initialization rejects it by default. The caller can use: 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 Ordinary full restoration still accepts metadata-free legacy checkpoints. Full restoration behaviorCompatibility 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:
Metadata-free legacy checkpoints remain supported for ordinary full restoration. FreezingFreezing is applied after checkpoint initialization and before 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 Guarantee boundaryA 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:
Scientific suitability remains the experimenter's responsibility. Current scopeGraphLAM is the only predictor enabled for selective transfer. The following remain intentionally unsupported:
The generic loading mechanism can support these later, but each predictor must provide complete behavior claims and architecture-specific regression tests before opting in. VerificationThe implementation is covered by regressions for:
|
|
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:
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. |
|
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:
|
Sir-Sloth-The-Lazy
left a comment
There was a problem hiding this comment.
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.
…nreachable parts and unrequired version feilds remove
Sir-Sloth-The-Lazy
left a comment
There was a problem hiding this comment.
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.
|
Hi @Sir-Sloth-The-Lazy, |
|
|
||
| variable = "TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD" | ||
| previous_value = os.environ.get(variable) | ||
| os.environ[variable] = "1" |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 ?
|
Hi @Sir-Sloth-The-Lazy |
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=Falsedoes not ignore shape mismatches.The implementation:
load_from_checkpoint()andon_load_checkpoint()mechanisms.processor,mesh_embedder, andm2m_embedder, while preserving newly initialized target layers.requires_grad_(False).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-emptygraphfingerprint string and amodel_behaviormapping 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_behaviorpermits 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_metadatapermits 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
Checklist before requesting a review
pullwith--rebaseoption if possible).Checklist for reviewers
Each PR comes with its own improvements and flaws. The reviewer should check the following:
Author checklist after completed review
reflecting type of change (add section where missing):
Checklist for assignee