Skip to content

Commit d0d286b

Browse files
committed
--model support for finetuning/resume
1 parent 68880bd commit d0d286b

47 files changed

Lines changed: 588 additions & 279 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/source/user-guide/datasets.rst‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,12 @@ Common configuration
3030
* ``root`` is required and stores the processed samples.
3131
* ``preload`` loads processed samples into memory instead of reading them on demand.
3232
* ``skip_prepare`` reuses existing processed samples.
33-
* ``split_ratios`` creates data splits and must sum to ``1.0`` when ``split_indexfile`` is ``null``.
34-
* ``split_indexfile`` provides fixed split indices instead of ratio-based splitting.
33+
* ``split_ratios`` creates the base train/validation split and must sum to ``1.0``.
34+
* ``split_indexfile`` loads a split index file. It takes precedence over ``split_ratios``.
35+
36+
For ``single`` and ``deep_ensemble``, one configured plan can be shared across all models.
37+
``bootstrap`` and ``kfold`` require one explicit plan per model when using ``split_indexfile``.
38+
3539
* Descriptor datasets require a non-empty ``descriptors`` list; see :doc:`descriptors` for the available descriptor types.
3640
* Graph datasets require ``graph_builder``; see :doc:`graphs` for the available builders.
3741

‎docs/source/user-guide/running.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ Training a model
1616
Common options:
1717

1818
* ``-i, --in_file`` - Path to input YAML configuration file (required).
19+
* ``-m, --model`` - Optional minimal or full checkpoint used to initialize or continue training.
20+
* ``--restart-training-state`` - Load checkpoint model weights but use fresh optimizer and scheduler state (optional).
1921
* ``-o, --out_dir`` - Path to output directory (optional, default: ``./runs``).
2022
* ``-n, --name`` - Name for the training run used for logging and saving (optional).
2123
* ``-t, --tensorboard`` - Enable training metrics in TensorBoard logs (optional).

‎docs/source/user-guide/strategies.rst‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ Available implementations
2626

2727
* ``single`` (:class:`~xanesnet.strategies.single.Single`) trains one model on the configured training and validation split.
2828
It uses ``inferencer_type: basic`` for inference.
29-
* ``kfold`` (:class:`~xanesnet.strategies.kfold.KFold`) splits the full dataset into folds and trains one model for each fold.
29+
* ``kfold`` (:class:`~xanesnet.strategies.kfold.KFold`) splits the full dataset into folds by default and trains one model for each fold.
3030
All fold models are retained and combined with ``inferencer_type: ensemble``.
3131
* ``bootstrap`` (:class:`~xanesnet.strategies.bootstrap.Bootstrap`) trains several models on bootstrap resamples of the training subset. \
3232
The ensemble inferencer combines their predictions.
@@ -62,11 +62,12 @@ Model-specific data and encodings
6262
---------------------------------
6363

6464
Every training strategy writes one ``split_indices.json`` file containing the train and validation indices for each model, in model order.
65+
Set ``dataset.split_indexfile`` to this file to explicitly reuse those plans in another training run.
6566
Strategies with shared data, such as ``single`` and ``deep_ensemble``, record the same configured split for each model.
6667
``bootstrap`` records each resample, while ``kfold`` records each fold.
6768
Multi-device Lightning workers reuse these exact plans instead of drawing their own.
6869

69-
K-fold training creates folds from the full dataset and ignores the configured dataset splits.
70+
K-fold training creates folds from the full dataset. A configured file must provide one fold plan per model.
7071
``n_splits`` must not exceed the number of dataset samples.
7172
All fold models share one encoding, whose automatic fields are resolved from the full dataset before the folds are trained.
7273
Thus each fold's validation samples contribute to the shared encoding statistics; this is an intentional transductive choice rather than a fold-isolated preprocessing estimate.

‎docs/source/user-guide/training.rst‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,27 @@ The following shows a trainer section with commonly changed options:
6969
min_delta: 0.001
7070
restore_best: true
7171
72+
Starting from a checkpoint (Fine-tuning or Resuming)
73+
----------------------------------------------------
74+
75+
Pass ``-m, --model <checkpoint.pth>`` to initialize a training run from either a minimal checkpoint or a full checkpoint.
76+
Both forms load model weights. By default, a full checkpoint restores optimizer, epoch-scheduler, and warm-up-scheduler state together; a minimal checkpoint starts all three fresh.
77+
Pass ``--restart-training-state`` with a full checkpoint to keep loading its model weights while starting fresh optimizer and scheduler state.
78+
Before validation, XANESNET merges the checkpoint's ``dataset``, ``model``, and ``encodings`` signature sections into the training configuration.
79+
Signature fields can be omitted to use the checkpoint values; explicitly supplied values must match exactly.
80+
In particular, do not specify ``"auto"`` for a model or encoding field when using ``--model``.
81+
Dataset settings not stored in the signature, such as ``root``, remain user-supplied.
82+
For full checkpoints, optimizer and scheduler type settings are merged from the checkpoint along with their states unless ``--restart-training-state`` is set.
83+
With that option, the optimizer and scheduler settings from YAML are used instead.
84+
85+
The configured ``trainer.epochs`` is the number of additional epochs for this invocation, not the total target epoch count.
86+
To reuse the source run's exact split plan, set ``dataset.split_indexfile`` in the resume configuration to its ``split_indices.json``.
87+
Multi-model runs also write ``split_indices_<index>.json`` files; to resume an individual member checkpoint, point ``split_indexfile`` to the matching single-plan file.
88+
Remember: without a configured split file, the current configuration or strategy creates a new plan.
89+
90+
Stopper state and random-number-generator state are not restored.
91+
Every invocation starts with fresh early-stopping and best-model bookkeeping and resumed training is not guaranteed to match an uninterrupted run bit for bit.
92+
7293
.. _multi-device-lightning-training:
7394

7495
Multi-device Lightning training

‎xanesnet/checkpointing/checkpointer.py‎

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ def __init__(
7070
self.trainer_provider = trainer_provider
7171

7272
self._optimizer_signature: dict[str, Any] | None = None
73-
self._epoch_scheduler_signature: dict[str, Any] | None = None
74-
self._warmup_scheduler_signature: dict[str, Any] | None = None
73+
self._scheduler_signature: dict[str, Any] | None = None
7574

7675
self._finished_states: dict[int, dict[str, Any]] = {}
7776
self._member_index = 0
@@ -112,9 +111,8 @@ def snapshot(self) -> Checkpoint:
112111
"epochs": [member["epochs"] for member in member_states],
113112
"optimizer_signature": self._optimizer_signature,
114113
"optimizer_states": [member["optimizer_state"] for member in member_states],
115-
"epoch_scheduler_signature": self._epoch_scheduler_signature,
114+
"scheduler_signature": self._scheduler_signature,
116115
"epoch_scheduler_states": [member["epoch_scheduler_state"] for member in member_states],
117-
"warmup_scheduler_signature": self._warmup_scheduler_signature,
118116
"warmup_scheduler_states": [member["warmup_scheduler_state"] for member in member_states],
119117
},
120118
)
@@ -129,14 +127,16 @@ def _collect_member_state(self, trainer: Trainer) -> dict[str, Any]:
129127
Mapping containing the model state, completed epochs, optimizer state, and scheduler states.
130128
"""
131129
if self._optimizer_signature is None:
132-
self._optimizer_signature = trainer.optimizer.signature.as_dict()
133-
self._epoch_scheduler_signature = trainer.epoch_lr_scheduler.signature.as_dict()
134-
self._warmup_scheduler_signature = (
135-
None if trainer.warmup_lr_scheduler is None else trainer.warmup_lr_scheduler.signature.as_dict()
136-
)
130+
self._optimizer_signature = {"trainer": trainer.optimizer.signature.as_dict()}
131+
self._scheduler_signature = {
132+
"trainer": {
133+
"lr_scheduler": trainer.epoch_lr_scheduler.signature.as_dict(),
134+
"lr_warmup": trainer.warmup_lr_scheduler is not None,
135+
}
136+
}
137137

138138
warmup_state = None if trainer.warmup_lr_scheduler is None else trainer.warmup_lr_scheduler.state_dict()
139-
return _state_to_cpu(
139+
return state_to_cpu(
140140
{
141141
"model_state": trainer.model.state_dict(),
142142
"epochs": trainer.completed_epochs,
@@ -184,7 +184,7 @@ def step(self, epoch: int, force_save: bool = False) -> str | None:
184184
return checkpoint_name
185185

186186

187-
def _state_to_cpu(value: Any) -> Any:
187+
def state_to_cpu(value: Any) -> Any:
188188
"""Recursively detach, clone, and move tensors in nested state to CPU.
189189
190190
Args:
@@ -197,9 +197,9 @@ def _state_to_cpu(value: Any) -> Any:
197197
if torch.is_tensor(value):
198198
return value.detach().cpu().clone()
199199
if isinstance(value, Mapping):
200-
return {key: _state_to_cpu(subvalue) for key, subvalue in value.items()}
200+
return {key: state_to_cpu(subvalue) for key, subvalue in value.items()}
201201
if isinstance(value, list):
202-
return [_state_to_cpu(subvalue) for subvalue in value]
202+
return [state_to_cpu(subvalue) for subvalue in value]
203203
if isinstance(value, tuple):
204-
return tuple(_state_to_cpu(subvalue) for subvalue in value)
204+
return tuple(state_to_cpu(subvalue) for subvalue in value)
205205
return value

‎xanesnet/cli.py‎

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -53,30 +53,32 @@
5353
Commands (mutually exclusive):
5454
train Train a model using a configuration file.
5555
Arguments:
56-
-i, --in_file Path to input YAML configuration file. (Required)
57-
-o, --out_dir Path to output directory. (Optional, default: ./runs )
58-
-n, --name Name for the training run used for logging and saving (Optional).
59-
-t, --tensorboard Whether to write training metrics to TensorBoard logs (Optional).
60-
--log-weights Log model parameter and gradient histograms to TensorBoard (Optional).
61-
--dry-run Run one real training epoch and save model_profile.json (Optional).
62-
-y, --yes Automatically answer yes to confirmation prompts (Optional).
56+
-i, --in_file Path to input YAML configuration file. (Required)
57+
-m, --model Path to a minimal or full checkpoint to initialize or resume training from (Optional).
58+
--restart-training-state Use fresh optimizer and schedulers instead of restoring full checkpoint training state (Optional).
59+
-o, --out_dir Path to output directory. (Optional, default: ./runs )
60+
-n, --name Name for the training run used for logging and saving (Optional).
61+
-t, --tensorboard Whether to write training metrics to TensorBoard logs (Optional).
62+
--log-weights Log model parameter and gradient histograms to TensorBoard (Optional).
63+
--dry-run Run one real training epoch and save model_profile.json (Optional).
64+
-y, --yes Automatically answer yes to confirmation prompts (Optional).
6365
6466
infer Run inference on data using a trained model.
6567
Arguments:
66-
-i, --in_file Path to input YAML configuration file. (Required)
67-
-m, --in_model Path to a trained model .pth file. (Required)
68-
-o, --out_dir Path to output directory. (Optional, default: ./runs )
69-
-n, --name Name for the inference run used for logging and saving (Optional).
70-
-y, --yes Automatically answer yes to confirmation prompts (Optional).
68+
-i, --in_file Path to input YAML configuration file. (Required)
69+
-m, --in_model Path to a trained model .pth file. (Required)
70+
-o, --out_dir Path to output directory. (Optional, default: ./runs )
71+
-n, --name Name for the inference run used for logging and saving (Optional).
72+
-y, --yes Automatically answer yes to confirmation prompts (Optional).
7173
7274
analyze Analyze predictions from inference runs.
7375
Arguments:
74-
-i, --in_file Path to input YAML configuration file. (Required)
75-
-r, --inference-runs Path(s) to inference run directories. Repeatable and/or space separated. (Required)
76-
-d, --prediction-names Display names for inference run directories, in the same order as -r. Repeatable and/or space separated. (Optional)
77-
-o, --out_dir Path to output directory. (Optional, default: ./runs )
78-
-n, --name Name for the analysis run used for logging and saving (Optional).
79-
-y, --yes Automatically answer yes to confirmation prompts (Optional).
76+
-i, --in_file Path to input YAML configuration file. (Required)
77+
-r, --inference-runs Path(s) to inference run directories. Repeatable and/or space separated. (Required)
78+
-d, --prediction-names Display names for inference run directories, in the same order as -r. Repeatable and/or space separated. (Optional)
79+
-o, --out_dir Path to output directory. (Optional, default: ./runs )
80+
-n, --name Name for the analysis run used for logging and saving (Optional).
81+
-y, --yes Automatically answer yes to confirmation prompts (Optional).
8082
"""
8183

8284
TRAIN = r"""

‎xanesnet/components/lrscheduler.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,12 @@ def state_dict(self) -> dict[str, Any]:
7474
return state
7575

7676
def _set_scheduler_type(self, lr_scheduler_type: str) -> None:
77-
"""Store the scheduler type and its reconstruction signature.
77+
"""Store the configured scheduler type and its reconstruction signature.
7878
7979
Args:
80-
lr_scheduler_type: Registry key identifying the scheduler type.
80+
lr_scheduler_type: Configured name identifying this scheduler type.
8181
"""
82-
normalized_type = lr_scheduler_type.lower()
83-
self.lr_scheduler_type = "none" if normalized_type == "no" else normalized_type
82+
self.lr_scheduler_type = lr_scheduler_type
8483
self._signature = Config({"lr_scheduler_type": self.lr_scheduler_type})
8584

8685

‎xanesnet/components/optim.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,11 @@ class Optimizer(ABC):
4646

4747
@abstractmethod
4848
def state_dict(self) -> dict[str, Any]:
49-
"""Return the native optimizer state for checkpointing."""
49+
"""Return the native optimizer state for checkpointing.
50+
51+
Returns:
52+
Native optimizer state dictionary.
53+
"""
5054
...
5155

5256
@property
@@ -68,12 +72,12 @@ def torch_optimizer(self) -> optim.Optimizer:
6872
return cast(optim.Optimizer, self)
6973

7074
def _set_optimizer_type(self, optimizer_type: str) -> None:
71-
"""Store the optimizer type and its reconstruction signature.
75+
"""Store the configured optimizer type and its reconstruction signature.
7276
7377
Args:
74-
optimizer_type: Registry key identifying the optimizer type.
78+
optimizer_type: Configured name identifying this optimizer type.
7579
"""
76-
self.optimizer_type = optimizer_type.lower()
80+
self.optimizer_type = optimizer_type
7781
self._signature = Config({"optimizer": self.optimizer_type})
7882

7983

0 commit comments

Comments
 (0)