nvalchemi.training.FineTuningStrategy#
- pydantic model nvalchemi.training.FineTuningStrategy[source]#
Training strategy for patching modules and selecting trainable parameters.
FineTuningStrategyis intended for workflows where a pretrained model is loaded first and then adapted in-place before optimizer construction. The strategy keeps the baseTrainingStrategyloop, but prepends registration-time hooks derived from its convenience fields before any explicithooks=supplied by the user:peft_configbecomes PEFT-specific registration hooks, for example LoRA adapter injection.module_patchesbecomes aModulePatchHook.freeze_patterns/trainable_patternsbecome aTrainableParameterHook.
PEFT methods are configured with
peft_config; for example,nvalchemi.training.peft.lora.LoRAConfiginjects LoRA adapters into matching linear modules. Whenpeft_configis provided,freeze_patternsmust be empty since the base model is considered frozen by default and PEFT hooks register adapter parameters as trainable. Usetrainable_patternsto 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 existingtorch.nn.Moduleor added when missing. Usenvalchemi.training.create_model_spec()for module patches that must round-trip throughto_spec_dict(); directtorch.nn.Moduleinstances 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 andfreeze_patternsdo not exclude them.Parameter patterns are matched against fully-qualified names such as
"main.model.readouts.1.linear.weight".trainable_patternsalone 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. Whenfreeze_patternsis also supplied, matching parameters are excluded first, thentrainable_patternsare re-included. With the defaultfreeze_mode="requires_grad", excluded parameters are temporarily markedrequires_grad=Falseduringrun()and restored afterward. Usefreeze_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 whenpeft_configis 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, whenpeft_configis 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=Falseor 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.