# Buggy code
def __init__(
    self,
    filepath,
    monitor="val_loss",
    verbose=0,
    save_top_k=1,
    save_weights_only=False,
    mode="auto",
    period=1,
    prefix="",
):
    super(ModelCheckpoint, self).__init__()
    if save_top_k and os.path.isdir(filepath) and len(os.listdir(filepath)) > 0:
        warnings.warn(
            f"Checkpoint directory {filepath} exists and is not empty with save_top_k != 0."
            "All files in this directory will be deleted when a checkpoint is saved!"
        )

    self.monitor = monitor
    self.verbose = verbose
    self.filepath = filepath
    if not os.path.exists(filepath):
        os.makedirs(filepath)
    self.save_top_k = save_top_k
    self.save_weights_only = save_weights_only
    self.period = period
    self.epochs_since_last_check = 0
    self.prefix = prefix
    self.best_k_models = {}
    # {filename: monitor}
    self.kth_best_model = ""
    self.best = 0

    if mode not in ["auto", "min", "max"]:
        warnings.warn(
            f"ModelCheckpoint mode {mode} is unknown, fallback to auto mode.",
            RuntimeWarning,
        )
        mode = "auto"

    if mode == "min":
        self.monitor_op = np.less
        self.kth_value = np.Inf
        self.mode = "min"
    elif mode == "max":
        self.monitor_op = np.greater
        self.kth_value = -np.Inf
        self.mode = "max"
    else:
        if "acc" in self.monitor or self.monitor.startswith("fmeasure"):
            self.monitor_op = np.greater
            self.kth_value = -np.Inf
            self.mode = "max"
        else:
            self.monitor_op = np.less
            self.kth_value = np.Inf
            self.mode = "min"


# Traceback (FileExistsError)
Traceback (most recent call last):
File "train.py", line 109, in <module>
main(hyperparams)
File "train.py", line 62, in main
trainer.fit(model)
File "/home/tanel/miniconda3/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 343, in fit
mp.spawn(self.ddp_train, nprocs=self.num_gpus, args=(model,))
File "/home/tanel/miniconda3/lib/python3.7/site-packages/torch/multiprocessing/spawn.py", line 171, in spawn
while not spawn_context.join():
File "/home/tanel/miniconda3/lib/python3.7/site-packages/torch/multiprocessing/spawn.py", line 118, in join
raise Exception(msg)
Exception:

-- Process 1 terminated with the following error:
Traceback (most recent call last):
File "/home/tanel/miniconda3/lib/python3.7/site-packages/torch/multiprocessing/spawn.py", line 19, in _wrap
fn(i, *args)
File "/home/tanel/miniconda3/lib/python3.7/site-packages/pytorch_lightning/trainer/ddp_mixin.py", line 181, in ddp_train
self.run_pretrain_routine(model)
File "/home/tanel/miniconda3/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 415, in run_pretrain_routine
self.configure_checkpoint_callback()
File "/home/tanel/miniconda3/lib/python3.7/site-packages/pytorch_lightning/trainer/callback_config_mixin.py", line 28, in configure_checkpoint_callback
filepath=ckpt_path
File "/home/tanel/miniconda3/lib/python3.7/site-packages/pytorch_lightning/callbacks/pt_callbacks.py", line 202, in __init__
os.makedirs(filepath)
File "/home/tanel/miniconda3/lib/python3.7/os.py", line 221, in makedirs
mkdir(name, mode)
FileExistsError: [Errno 17] File exists: '/home/tanel/devel/torch-xvectors/lightning_logs/version_151/checkpoints'

# Fixed code
def __init__(
    self,
    filepath,
    monitor="val_loss",
    verbose=0,
    save_top_k=1,
    save_weights_only=False,
    mode="auto",
    period=1,
    prefix="",
):
    super(ModelCheckpoint, self).__init__()
    if save_top_k and os.path.isdir(filepath) and len(os.listdir(filepath)) > 0:
        warnings.warn(
            f"Checkpoint directory {filepath} exists and is not empty with save_top_k != 0."
            "All files in this directory will be deleted when a checkpoint is saved!"
        )

    self.monitor = monitor
    self.verbose = verbose
    self.filepath = filepath
    os.makedirs(filepath, exist_ok=True)
    self.save_top_k = save_top_k
    self.save_weights_only = save_weights_only
    self.period = period
    self.epochs_since_last_check = 0
    self.prefix = prefix
    self.best_k_models = {}
    # {filename: monitor}
    self.kth_best_model = ""
    self.best = 0

    if mode not in ["auto", "min", "max"]:
        warnings.warn(
            f"ModelCheckpoint mode {mode} is unknown, fallback to auto mode.",
            RuntimeWarning,
        )
        mode = "auto"

    if mode == "min":
        self.monitor_op = np.less
        self.kth_value = np.Inf
        self.mode = "min"
    elif mode == "max":
        self.monitor_op = np.greater
        self.kth_value = -np.Inf
        self.mode = "max"
    else:
        if "acc" in self.monitor or self.monitor.startswith("fmeasure"):
            self.monitor_op = np.greater
            self.kth_value = -np.Inf
            self.mode = "max"
        else:
            self.monitor_op = np.less
            self.kth_value = np.Inf
            self.mode = "min"