tune
darts_segmentation.training.tune
¶
More advanced hyper-parameter tuning.
CrossValidationConfig
dataclass
¶
CrossValidationConfig(
n_folds: int | None = None,
n_randoms: int = 3,
scoring_metric: list[str] = lambda: [
"val/JaccardIndex",
"val/Recall",
](),
multi_score_strategy: typing.Literal[
"harmonic", "arithmetic", "geometric", "min"
] = "harmonic",
)
Configuration for cross-validation.
This is used to configure the cross-validation process.
It is used by the cross_validation_smp
function.
Attributes:
-
n_folds
(int | None
) –Number of folds to perform in cross-validation. If None, all folds (total_folds) will be used. Defaults to None.
-
n_randoms
(int
) –Number of random seeds to perform in cross-validation. First three seeds are always 42, 21, 69, further seeds are deterministic generated. Defaults to 3.
-
scoring_metric
(list[str]
) –Metric(s) to use for scoring. Defaults to ["val/JaccardIndex", "val/Recall"].
-
multi_score_strategy
(typing.Literal['harmonic', 'arithmetic', 'geometric', 'min']
) –Strategy for combining multiple metrics. Defaults to "harmonic".
DataConfig
dataclass
¶
DataConfig(
train_data_dir: pathlib.Path = pathlib.Path("train"),
data_split_method: typing.Literal[
"random", "region", "sample"
]
| None = None,
data_split_by: list[str | float] | None = None,
fold_method: typing.Literal[
"kfold",
"shuffle",
"stratified",
"region",
"region-stratified",
] = "kfold",
total_folds: int = 5,
subsample: int | None = None,
)
Data related parameters for training.
Defines the script inputs for the training script and can be propagated by the cross-validation and tuning scripts.
Attributes:
-
train_data_dir
(pathlib.Path
) –The path (top-level) to the data to be used for training. Expects a directory containing: 1. a zarr group called "data.zarr" containing a "x" and "y" array 2. a geoparquet file called "metadata.parquet" containing the metadata for the data. This metadata should contain at least the following columns: - "sample_id": The id of the sample - "region": The region the sample belongs to - "empty": Whether the image is empty The index should refer to the index of the sample in the zarr data. This directory should be created by a preprocessing script. Defaults to "train".
-
batch_size
(int
) –Batch size for training and validation.
-
data_split_method
(typing.Literal['random', 'region', 'sample'] | None
) –The method to use for splitting the data into a train and a test set. "random" will split the data randomly, the seed is always 42 and the test size can be specified by providing a list with a single a float between 0 and 1 to data_split_by This will be the fraction of the data to be used for testing. E.g. [0.2] will use 20% of the data for testing. "region" will split the data by one or multiple regions, which can be specified by providing a str or list of str to data_split_by. "sample" will split the data by sample ids, which can also be specified similar to "region". If None, no split is done and the complete dataset is used for both training and testing. The train split will further be split in the cross validation process. Defaults to None.
-
data_split_by
(list[str | float] | None
) –Select by which regions/samples to split or the size of test set. Defaults to None.
-
fold_method
(typing.Literal['kfold', 'shuffle', 'stratified', 'region', 'region-stratified']
) –Method for cross-validation split. Defaults to "kfold".
-
total_folds
(int
) –Total number of folds in cross-validation. Defaults to 5.
-
subsample
(int | None
) –If set, will subsample the dataset to this number of samples. This is useful for debugging and testing. Defaults to None.
DeviceConfig
dataclass
¶
DeviceConfig(
accelerator: typing.Literal[
"auto", "cpu", "gpu", "mps", "tpu"
] = "auto",
strategy: typing.Literal[
"auto",
"ddp",
"ddp_fork",
"ddp_notebook",
"fsdp",
"cv-parallel",
"tune-parallel",
] = "auto",
devices: list[int | str] = lambda: ["auto"](),
num_nodes: int = 1,
)
Device and Distributed Strategy related parameters.
Attributes:
-
accelerator
(typing.Literal['auto', 'cpu', 'gpu', 'mps', 'tpu']
) –Accelerator to use. Defaults to "auto".
-
strategy
(typing.Literal['auto', 'ddp', 'ddp_fork', 'ddp_notebook', 'fsdp', 'cv-parallel', 'tune-parallel', 'cv-parallel', 'tune-parallel']
) –Distributed strategy to use. Defaults to "auto".
-
devices
(list[int | str]
) –List of devices to use. Defaults to ["auto"].
-
num_nodes
(int
) –Number of nodes to use for distributed training. Defaults to 1.
accelerator
class-attribute
instance-attribute
¶
devices
class-attribute
instance-attribute
¶
devices: list[int | str] = dataclasses.field(
default_factory=lambda: ["auto"]
)
lightning_strategy
property
¶
lightning_strategy: str
Get the Lightning strategy for the current configuration.
Returns:
-
str
(str
) –The Lightning strategy to use.
strategy
class-attribute
instance-attribute
¶
strategy: typing.Literal[
"auto",
"ddp",
"ddp_fork",
"ddp_notebook",
"fsdp",
"cv-parallel",
"tune-parallel",
] = "auto"
in_parallel
¶
in_parallel(
device: int | str | None = None,
) -> darts_segmentation.training.train.DeviceConfig
Turn the current configuration into a suitable configuration for parallel training.
Parameters:
-
device
(int | str | None
, default:None
) –The device to use for parallel training. If None, assumes non-multiprocessing parallel training and propagate all devices. Defaults to None.
Returns:
-
DeviceConfig
(darts_segmentation.training.train.DeviceConfig
) –A new DeviceConfig instance that is suitable for parallel training.
Source code in darts-segmentation/src/darts_segmentation/training/train.py
Hyperparameters
dataclass
¶
Hyperparameters(
model_arch: str = "Unet",
model_encoder: str = "dpn107",
model_encoder_weights: str | None = None,
augment: list[
darts_segmentation.training.augmentations.Augmentation
]
| None = None,
learning_rate: float = 0.001,
gamma: float = 0.9,
focal_loss_alpha: float | None = None,
focal_loss_gamma: float = 2.0,
batch_size: int = 8,
bands: list[str] | None = None,
)
Hyperparameters for Cyclopts CLI.
Attributes:
-
model_arch
(str
) –Architecture of the model to use.
-
model_encoder
(str
) –Encoder type for the model.
-
model_encoder_weights
(str | None
) –Weights for the encoder, if any.
-
augment
(list[darts_segmentation.training.augmentations.Augmentation] | None
) –List of augmentations to apply.
-
learning_rate
(float
) –Learning rate for training.
-
gamma
(float
) –Decay factor for learning rate.
-
focal_loss_alpha
(float | None
) –Alpha parameter for focal loss, if using.
-
focal_loss_gamma
(float
) –Gamma parameter for focal loss.
-
batch_size
(int
) –Batch size for training.
-
bands
(list[str] | None
) –List of bands to use. Defaults to None.
augment
class-attribute
instance-attribute
¶
augment: (
list[
darts_segmentation.training.augmentations.Augmentation
]
| None
) = None
LoggingConfig
dataclass
¶
LoggingConfig(
artifact_dir: pathlib.Path = pathlib.Path("artifacts"),
log_every_n_steps: int = 10,
check_val_every_n_epoch: int = 3,
plot_every_n_val_epochs: int = 5,
wandb_entity: str | None = None,
wandb_project: str | None = None,
)
Logging related parameters for training.
Defines the script inputs for the training script and can be propagated by the cross-validation and tuning scripts.
Attributes:
-
artifact_dir
(pathlib.Path
) –Top-level path to the training output directory. Will contain checkpoints and metrics. Defaults to Path("artifacts").
-
log_every_n_steps
(int
) –Log every n steps. Defaults to 10.
-
check_val_every_n_epoch
(int
) –Check validation every n epochs. Defaults to 3.
-
plot_every_n_val_epochs
(int
) –Plot validation samples every n epochs. Defaults to 5.
-
wandb_entity
(str | None
) –Weights and Biases Entity. Defaults to None.
-
wandb_project
(str | None
) –Weights and Biases Project. Defaults to None.
artifact_dir
class-attribute
instance-attribute
¶
artifact_dir_at_cv
¶
Nest the artifact directory for cross-validation runs.
Similar to parse_artifact_dir_for_run
, but meant to be used by the cross-validation script.
Also creates the directory if it does not exist.
Parameters:
-
tune_name
(str | None
) –Name of the tuning, if applicable.
Returns:
Source code in darts-segmentation/src/darts_segmentation/training/train.py
artifact_dir_at_run
¶
Nest the artifact directory to avoid cluttering the root directory.
For cv it is expected that the cv function already nests the artifact directory Meaning for cv the artifact_dir of this function should be either {artifact_dir}/_cross_validations/{cv_name} or {artifact_dir}/{tune_name}/{cv_name}
Also creates the directory if it does not exist.
Parameters:
Raises:
-
ValueError
–If tune_name is specified, but cv_name is not, which is invalid.
Returns:
Source code in darts-segmentation/src/darts_segmentation/training/train.py
TrainRunConfig
dataclass
¶
TrainRunConfig(
name: str | None = None,
cv_name: str | None = None,
tune_name: str | None = None,
fold: int = 0,
random_seed: int = 42,
)
Run related parameters for training.
Defines the script inputs for the training script. Must be build by the cross-validation and tuning scripts.
Attributes:
-
name
(str | None
) –Name of the run. If None is generated automatically. Defaults to None.
-
cv_name
(str | None
) –Name of the cross-validation. Should only be specified by a cross-validation script. Defaults to None.
-
tune_name
(str | None
) –Name of the tuning. Should only be specified by a tuning script. Defaults to None.
-
fold
(int
) –Index of the current fold. Defaults to 0.
-
random_seed
(int
) –Random seed for deterministic training. Defaults to 42.
TrainingConfig
dataclass
¶
TrainingConfig(
continue_from_checkpoint: pathlib.Path | None = None,
max_epochs: int = 100,
early_stopping_patience: int = 5,
num_workers: int = 0,
)
Training related parameters for training.
Defines the script inputs for the training script and can be propagated by the cross-validation and tuning scripts.
Attributes:
-
continue_from_checkpoint
(pathlib.Path | None
) –Path to a checkpoint to continue training from. Defaults to None.
-
max_epochs
(int
) –Maximum number of epochs to train. Defaults to 100.
-
early_stopping_patience
(int
) –Number of epochs to wait for improvement before stopping. Defaults to 5.
-
num_workers
(int
) –Number of Dataloader workers. Defaults to 0.
continue_from_checkpoint
class-attribute
instance-attribute
¶
_ProcessInputs
dataclass
¶
_ProcessInputs(
current: int,
total: int,
tune_name: str,
cv: darts_segmentation.training.cv.CrossValidationConfig,
training_config: darts_segmentation.training.train.TrainingConfig,
logging_config: darts_segmentation.training.train.LoggingConfig,
data_config: darts_segmentation.training.train.DataConfig,
device_config: darts_segmentation.training.train.DeviceConfig,
hparams: darts_segmentation.training.hparams.Hyperparameters,
)
device_config
instance-attribute
¶
device_config: (
darts_segmentation.training.train.DeviceConfig
)
logging_config
instance-attribute
¶
logging_config: (
darts_segmentation.training.train.LoggingConfig
)
training_config
instance-attribute
¶
training_config: (
darts_segmentation.training.train.TrainingConfig
)
_ProcessOutputs
dataclass
¶
_run_cv
¶
_run_cv(
inp: darts_segmentation.training.tune._ProcessInputs,
)
Source code in darts-segmentation/src/darts_segmentation/training/tune.py
check_score_is_unstable
¶
Check the stability of the scoring metric.
If any metric value is not finite or equal to zero, the scoring metric is considered unstable.
Parameters:
Returns:
-
bool
(bool
) –True if the scoring metric is unstable, False otherwise.
Raises:
-
ValueError
–If an unknown scoring metric type is provided.
Source code in darts-segmentation/src/darts_segmentation/training/scoring.py
tune_smp
¶
tune_smp(
*,
name: str | None = None,
n_trials: int | typing.Literal["grid"] = 100,
retrain_and_test: bool = False,
cv_config: darts_segmentation.training.cv.CrossValidationConfig = darts_segmentation.training.cv.CrossValidationConfig(),
training_config: darts_segmentation.training.train.TrainingConfig = darts_segmentation.training.train.TrainingConfig(),
data_config: darts_segmentation.training.train.DataConfig = darts_segmentation.training.train.DataConfig(),
device_config: darts_segmentation.training.train.DeviceConfig = darts_segmentation.training.train.DeviceConfig(),
logging_config: darts_segmentation.training.train.LoggingConfig = darts_segmentation.training.train.LoggingConfig(),
hpconfig: pathlib.Path | None = None,
config_file: pathlib.Path | None = None,
)
Tune the hyper-parameters of the model using cross-validation and random states.
Please see https://smp.readthedocs.io/en/latest/index.html for model configurations of architecture and encoder.
Please also consider reading our training guide (docs/guides/training.md).
This tuning script is designed to sweep over hyperparameters with a cross-validation
used to evaluate each hyperparameter configuration.
Optionally, by setting retrain_and_test
to True, the best hyperparameters are then selected based on the
cross-validation scores and a new model is trained on the entire train-split and tested on the test-split.
Hyperparameters can be configured using a hpconfig
file (YAML or Toml).
Please consult the training guide or the documentation of
darts_segmentation.training.hparams.parse_hyperparameters
to learn how such a file should be structured.
Per default, a random search is performed, where the number of samples can be specified by n_trials
.
If n_trials
is set to "grid", a grid search is performed instead.
However, this expects to be every hyperparameter to be configured as either constant value or a choice / list.
To specify on which metric(s) the cv score is calculated, the scoring_metric
parameter can be specified.
Each score can be provided by either ":higher" or ":lower" to indicate the direction of the metrics.
This allows to correctly combine multiple metrics by doing 1/metric before calculation if a metric is ":lower".
If no direction is provided, it is assumed to be ":higher".
Has no real effect on the single score calculation, since only the mean is calculated there.
In a multi-score setting, the score is calculated by combine-then-reduce the metrics. Meaning that first for each fold the metrics are combined using the specified strategy, and then the results are reduced via mean. Please refer to the documentation to understand the different multi-score strategies.
If one of the metrics of any of the runs contains NaN, Inf, -Inf or is 0 the score is reported to be "unstable". In such cases, the configuration is not considered for further evaluation.
Artifacts are stored under {artifact_dir}/{tune_name}
.
You can specify the frequency on how often logs will be written and validation will be performed.
- log_every_n_steps
specifies how often train-logs will be written. This does not affect validation.
- check_val_every_n_epoch
specifies how often validation will be performed.
This will also affect early stopping.
- early_stopping_patience
specifies how many epochs to wait for improvement before stopping.
In epochs, this would be check_val_every_n_epoch * early_stopping_patience
.
- plot_every_n_val_epochs
specifies how often validation samples will be plotted.
Since plotting is quite costly, you can reduce the frequency. Works similar like early stopping.
In epochs, this would be check_val_every_n_epoch * plot_every_n_val_epochs
.
Example: There are 400 training samples and the batch size is 2, resulting in 200 training steps per epoch.
If log_every_n_steps
is set to 50 then the training logs and metrics will be logged 4 times per epoch.
If check_val_every_n_epoch
is set to 5 then validation will be performed every 5 epochs.
If plot_every_n_val_epochs
is set to 2 then validation samples will be plotted every 10 epochs.
If early_stopping_patience
is set to 3 then early stopping will be performed after 15 epochs without improvement.
The data structure of the training data expects the "preprocessing" step to be done beforehand, which results in the following data structure:
preprocessed-data/ # the top-level directory
├── config.toml
├── data.zarr/ # this zarr group contains the dataarrays x and y
├── metadata.parquet # this contains information necessary to split the data into train, val, and test sets.
└── labels.geojson
Parameters:
-
name
(str | None
, default:None
) –Name of the tuning run. Will be generated based on the number of existing directories in the artifact directory if None. Defaults to None.
-
n_trials
(int | typing.Literal['grid']
, default:100
) –Number of trials to perform in hyperparameter tuning. If "grid", span a grid search over all configured hyperparameters. In a grid search, only constant or choice hyperparameters are allowed. Defaults to 100.
-
retrain_and_test
(bool
, default:False
) –Whether to retrain the model with the best hyperparameters and test it. Defaults to False.
-
cv_config
(darts_segmentation.training.cv.CrossValidationConfig
, default:darts_segmentation.training.cv.CrossValidationConfig()
) –Configuration for cross-validation. Defaults to CrossValidationConfig().
-
training_config
(darts_segmentation.training.train.TrainingConfig
, default:darts_segmentation.training.train.TrainingConfig()
) –Configuration for training. Defaults to TrainingConfig().
-
data_config
(darts_segmentation.training.train.DataConfig
, default:darts_segmentation.training.train.DataConfig()
) –Configuration for data. Defaults to DataConfig().
-
device_config
(darts_segmentation.training.train.DeviceConfig
, default:darts_segmentation.training.train.DeviceConfig()
) –Configuration for device. Defaults to DeviceConfig().
-
logging_config
(darts_segmentation.training.train.LoggingConfig
, default:darts_segmentation.training.train.LoggingConfig()
) –Configuration for logging. Defaults to LoggingConfig().
-
hpconfig
(pathlib.Path | None
, default:None
) –Path to the hyperparameter configuration file. Please see the documentation of
hyperparameters
for more information. Defaults to None. -
config_file
(pathlib.Path | None
, default:None
) –Path to the configuration file. If provided, it will be used instead of
hpconfig
ifhpconfig
is None. Defaults to None.
Returns:
-
–
tuple[float, pd.DataFrame]: The best score (if retrained and tested) and the run infos of all runs.
Raises:
-
ValueError
–If no hyperparameter configuration file is provided.
Source code in darts-segmentation/src/darts_segmentation/training/tune.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
|