FastSurferCNN.utils.checkpoint

exception FastSurferCNN.utils.checkpoint.CorruptedCheckpointError(mismatches, config_file=None)[source]

Checkpoints on disk whose md5 does not match the published file.

class FastSurferCNN.utils.checkpoint.CheckpointConfigDict[source]

Methods

clear()

copy()

fromkeys(iterable[, value])

Create a new dictionary with keys from iterable and values set to value.

get(key[, default])

Return the value for key if key is in the dictionary, else default.

items()

keys()

pop(key[, default])

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem(/)

Remove and return a (key, value) pair as a 2-tuple.

setdefault(key[, default])

Insert key with a value of default if key is not in the dictionary.

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values()

class FastSurferCNN.utils.checkpoint.CheckpointFile(path, md5=None)[source]

A checkpoint file and the md5 of the published file, None where there is none to check against.

Methods

count(value, /)

Return number of occurrences of value.

index(value[, start, stop])

Return first index of value.

md5[source]

Alias for field number 1

path[source]

Alias for field number 0

FastSurferCNN.utils.checkpoint.check_and_download_ckpts(checkpoint=None, urls=(), on_mismatch='raise', *, checkpoint_path=None)[source]

Check and download a checkpoint file, if it does not exist.

A checkpoint that already exists is not downloaded again. If the existing checkpoint does not match the md5, the action depends on on_mismatch: “raise” (default) raises a CorruptedCheckpointError, “replace” downloads the published file and replaces the existing one, and “ignore” uses it without checking.

Parameters:
checkpointCheckpointFile

The file in which the checkpoint will be saved, and the md5 the download is checked against. Passing a Path or str is deprecated, their downloads are not checked.

urlsSequence of str

URLs of checkpoint hosting sites, at least one.

on_mismatch{“raise”, “replace”, “ignore”}, default=”raise”

What to do if an existing checkpoint does not match the md5. “raise” raises CorruptedCheckpointError; “replace” downloads the published file and replaces the existing one; “ignore” uses it anyway.

checkpoint_pathPath, str, optional

Deprecated, use checkpoint. The former name of checkpoint, raises a DeprecationWarning.

FastSurferCNN.utils.checkpoint.create_checkpoint_dir(expr_dir, expr_num)[source]

Create the checkpoint dir if not exists.

Parameters:
expr_dirUnion[os.PathLike]

Directory to create.

expr_numint

Experiment number.

Returns:
checkpoint_dir

Directory of the checkpoint.

FastSurferCNN.utils.checkpoint.download_checkpoint(checkpoint_name, checkpoint_path, urls, md5=None)[source]

Download a checkpoint file.

Each url is tried up to DOWNLOAD_ATTEMPTS times, backing off between attempts, for a broken transfer or a status in DOWNLOAD_RETRY_STATUS. A file that does not match md5 is retried once, a second mismatch moves to the next url, as does any other status. Raises an ExceptionGroup, or a RuntimeError whenever no host answered with an error status, once every url has been exhausted. The file is only written to checkpoint_path once it matches md5, so a failed download leaves an existing file in place.

Parameters:
checkpoint_namestr

Name of checkpoint.

checkpoint_pathPath, str

Path of the file in which the checkpoint will be saved.

urlsSequence[str]

URLs of checkpoint hosting sites.

md5str, optional

The md5 of the published file. None accepts any file, with a warning.

Raises:
ExceptionGroup

If any host returned an HTTP error status. The exception group contains the HTTPError exceptions from raise_for_status() for each host that answered with an error.

RuntimeError

If no host answered with an HTTP error status (all either failed in transport, served a file without matching md5, or were unreachable). The message names each url tried and what happened with it (mismatched md5, timeout, unreachable).

FastSurferCNN.utils.checkpoint.get_checkpoint(ckpt_dir, epoch)[source]

Find the standardizes checkpoint name for the checkpoint in the directory ckpt_dir for the given epoch.

Parameters:
ckpt_dirstr

Checkpoint directory.

epochint

Number of the epoch.

Returns:
checkpoint_dir

Standardizes checkpoint name.

FastSurferCNN.utils.checkpoint.get_checkpoint_path(log_dir, resume_experiment=None)[source]

Find the paths to checkpoints from the experiment directory.

Parameters:
log_dirPath, str

Experiment directory.

resume_experimentUnion[str, int, None]

Sub-experiment to search in for a model (Default value = None).

Returns:
prior_model_pathsMutableSequence[Path]

A list of filenames for checkpoints.

FastSurferCNN.utils.checkpoint.get_checkpoints(*checkpoints, urls, on_mismatch='raise')[source]

Check and download checkpoint files if not exist.

The checkpoints are checked and downloaded in parallel, one thread per checkpoint. Downloads are always checked against the md5 of their CheckpointFile, see download_checkpoint. If a checkpoint that already exists does not match, the action depends on on_mismatch, see check_and_download_ckpts.

Parameters:
*checkpointsCheckpointFile

The files in which the checkpoints will be saved, and the md5 they are checked against, see to_checkpoint_files. Passing a Path or str is deprecated, their downloads are not checked.

urlslist of str

URLs of checkpoint hosting sites.

on_mismatch{“raise”, “replace”, “ignore”}, default=”raise”

What to do if an existing checkpoint does not match the md5, see check_and_download_ckpts.

Returns:
list[Path]

The path of each checkpoint, relative paths resolved against the FastSurfer root directory.

Raises:
CorruptedCheckpointError

If on_mismatch is “raise” and existing checkpoints do not match, listing all of them.

Exception

If one checkpoint failed otherwise, the error of check_and_download_ckpts.

ExceptionGroup

If several checkpoints failed otherwise, the errors of each one.

FastSurferCNN.utils.checkpoint.get_config_file(module)[source]

Returns the path to the checkpoint_paths.yaml file of module.

Parameters:
modulestr

The FastSurfer module name.

Returns:
Path

The path to the checkpoint_paths.yaml file of module.

FastSurferCNN.utils.checkpoint.get_module_checkpoints(module, *paths, on_mismatch='raise')[source]

Check and download checkpoint files of a FastSurfer module if not exist.

The urls and the md5 of the published checkpoints are those in the checkpoint_paths.yaml of module, see get_config_file. Each path gets the md5 of the published checkpoint of the same file name, see to_checkpoint_files.

Parameters:
modulestr

The FastSurfer module the checkpoints belong to, e.g. “FastSurferCNN”.

*pathsPath, str

Paths of the checkpoint files, relative paths are relative to the FastSurfer root directory.

on_mismatch{“raise”, “replace”, “ignore”}, default=”raise”

What to do if an existing checkpoint does not match the md5, see check_and_download_ckpts.

Returns:
list[Path]

The path of each checkpoint, relative paths resolved against the FastSurfer root directory.

Raises:
CorruptedCheckpointError

If on_mismatch is “raise” and existing checkpoints do not match, naming the checkpoint_paths.yaml of module.

FastSurferCNN.utils.checkpoint.load_checkpoint_config(filename)[source]

Load the plane dictionary from the yaml file.

Parameters:
filenamePath, str

Path to the yaml file. Either absolute or relative to the FastSurfer root directory.

Returns:
CheckpointConfigDict

A dictionary representing the contents of the yaml file, with the entries of checkpoint ({"path": ..., "md5": ...}) as CheckpointFile.

FastSurferCNN.utils.checkpoint.load_checkpoint_config_defaults(configtype, filename)[source]

Get the default value for a specific plane or the url.

Parameters:
configtype“checkpoint”, “config”, “url”

Type of value.

filenamestr, Path

The path to the yaml file. Either absolute or relative to the FastSurfer root directory.

Returns:
dict[str, CheckpointFile], dict[Plane, Path], list[str]

The checkpoint files with their md5, the config files, or the urls.

FastSurferCNN.utils.checkpoint.load_from_checkpoint(checkpoint_path, model, optimizer=None, scheduler=None, fine_tune=False, drop_classifier=False)[source]

Load the model from the given experiment number.

Parameters:
checkpoint_pathstr, Path

Path to the checkpoint.

modeltorch.nn.Module

Network model.

optimizerOptional[torch.optim.Optimizer]

Network optimizer (Default value = None).

schedulerOptional[Scheduler]

Network scheduler (Default value = None).

fine_tunebool

Whether to fine tune or not (Default value = False).

drop_classifierbool

Whether to drop the classifier or not (Default value = False).

Returns:
loaded_epochint

Epoch number.

FastSurferCNN.utils.checkpoint.remove_ckpt(ckpt)[source]

Remove the checkpoint.

Parameters:
ckptstr, Path

Path and filename to the checkpoint.

FastSurferCNN.utils.checkpoint.save_checkpoint(checkpoint_dir, epoch, best_metric, num_gpus, cfg, model, optimizer, scheduler=None, best=False)[source]

Save the state of training for resume or fine-tune.

Parameters:
checkpoint_dirstr, Path

Path to the checkpoint directory.

epochint

Current epoch.

best_metricbest_metric

Best calculated metric.

num_gpusint

Number of used gpus.

cfgyacs.config.CfgNode

Configuration node.

modeltorch.nn.Module

Used network model.

optimizertorch.optim.Optimizer

Used network optimizer.

schedulerOptional[Scheduler]

Used network scheduler. Optional (Default value = None).

bestbool, default=False

Whether this was the best checkpoint so far (Default value = False).

FastSurferCNN.utils.checkpoint.to_checkpoint_files(*paths, published)[source]

Pair each path with the md5 of the published checkpoint of the same file name.

The file name is what the download requests from the hosts, so a checkpoint path from the command line that points to another folder still gets the md5 of the published file.

Parameters:
*pathsPath, str

Paths of the checkpoint files.

publishedIterable[CheckpointFile]

The published checkpoints, see load_checkpoint_config_defaults.

Returns:
list[CheckpointFile]

One CheckpointFile per path, the md5 is None, if no published checkpoint has its file name.