nvalchemi.training.FineTuningStrategy#

pydantic model nvalchemi.training.FineTuningStrategy[source]#

Training strategy for patching modules and selecting trainable parameters.

FineTuningStrategy is intended for workflows where a pretrained model is loaded first and then adapted in-place before optimizer construction. The strategy keeps the base TrainingStrategy loop, but prepends registration-time hooks derived from its convenience fields before any explicit hooks= supplied by the user:

  • peft_config becomes PEFT-specific registration hooks, for example LoRA adapter injection.

  • module_patches becomes a ModulePatchHook.

  • freeze_patterns / trainable_patterns become a TrainableParameterHook.

PEFT methods are configured with peft_config; for example, nvalchemi.training.peft.lora.LoRAConfig injects LoRA adapters into matching linear modules. When peft_config is provided, freeze_patterns must be empty since the base model is considered frozen by default and PEFT hooks register adapter parameters as trainable. Use trainable_patterns to select any additional existing model parameters that should remain trainable.

Module patch targets are fully-qualified paths of the form "<model_key>.<module_path>.<child>", for example "main.model.readouts.1.linear". The parent path must already exist. The final child is replaced when it is an existing torch.nn.Module or added when missing. Use nvalchemi.training.create_model_spec() for module patches that must round-trip through to_spec_dict(); direct torch.nn.Module instances are supported at runtime but are rejected by serialization. Module patches register their parameters as trainable by default, so pattern filters do not need to include them and freeze_patterns do not exclude them.

Parameter patterns are matched against fully-qualified names such as "main.model.readouts.1.linear.weight". trainable_patterns alone is an allow-list: only matching parameters remain trainable and enter optimizers. Module patch parameters and PEFT adapter parameters are registered as trainable separately, as described above. When freeze_patterns is also supplied, matching parameters are excluded first, then trainable_patterns are re-included. With the default freeze_mode="requires_grad", excluded parameters are temporarily marked requires_grad=False during run() and restored afterward. Use freeze_mode="optimizer_only" when excluded parameters should still receive gradients but must not be updated by optimizers.

Examples

Replace a readout head, train only that head, and serialize the workflow by declaring the replacement as a BaseSpec:

import torch

from nvalchemi.training import (
    EnergyMSELoss,
    FineTuningStrategy,
    ForceMSELoss,
    OptimizerConfig,
    create_model_spec,
    default_training_fn,
)

strategy = FineTuningStrategy(
    models=pretrained_model,
    module_patches={
        "main.model.readouts.1.linear": create_model_spec(
            torch.nn.Linear,
            in_features=128,
            out_features=1,
        )
    },
    trainable_patterns=("main.model.readouts.1.linear.*",),
    freeze_mode="requires_grad",
    optimizer_configs=OptimizerConfig(
        optimizer_cls=torch.optim.AdamW,
        optimizer_kwargs={"lr": 1e-4},
    ),
    training_fn=default_training_fn,
    loss_fn=EnergyMSELoss() + ForceMSELoss(normalize_by_atom_count=True),
    num_epochs=10,
    devices=[torch.device("cuda")],
)

strategy.run(train_loader)

Use optimizer-only filtering when excluded parameters should still receive gradients but must not be updated:

strategy = FineTuningStrategy(
    models=pretrained_model,
    freeze_patterns=("main.model.*",),
    trainable_patterns=("main.model.readouts.*",),
    freeze_mode="optimizer_only",
    optimizer_configs=optimizer_config,
    training_fn=default_training_fn,
    loss_fn=loss_fn,
    num_steps=1000,
)
field peft_config: PeftConfig | None = None#

Parameter-efficient fine-tuning configuration. When provided, its setup hooks run before module patches and trainable parameter selection.

field module_patches: dict[str, BaseSpec | Module] [Optional]#

Ordered module patches applied before optimizer construction.

field freeze_patterns: tuple[str, ...] = ()#

Glob patterns excluded from training. Exclusions can be re-included by trainable_patterns. Must be empty when peft_config is provided.

field trainable_patterns: tuple[str, ...] = ()#

Glob patterns for model parameters to keep trainable. Without freeze_patterns, matching parameters form the allow-list, together with parameters registered as trainable by setup hooks. Module patches and, when peft_config is configured, PEFT adapters register their parameters automatically; use these patterns to select any additional existing model parameters.

field freeze_mode: Literal['requires_grad', 'optimizer_only'] = 'requires_grad'#

Whether excluded parameters are temporarily frozen via requires_grad=False or only excluded from optimizers. Defaults to "requires_grad".

field compute_base_fingerprints: bool = True#

Used only when peft_config is provided. If True, compute base-model fingerprints and include them in strategy metadata for compatibility checks when loading PEFT checkpoints into a fresh base model.