Sometimes OOM errors occur, and typically a way I do to handle this is the following:
for data, iter_idx in zip(data_loader, range(start_iter, total_iter)):
    try:
        iteration_output = _do_iteration(...)
        output = iteration_output.output_image
        loss_dict = iteration_output.data_dict
    except RuntimeError as e:
        # Maybe string can change
        if "out of memory" in str(e):
            if fail_counter == 3:
                raise TrainingException(
                    f"OOM, could not recover after 3 tries: {e}."
                )
            fail_counter += 1
            logger.info(
                f"OOM Error: {e}. Skipping batch. Retry {fail_counter}/3."
            )
            optimizer.zero_grad()
            gc.collect()
            torch.cuda.empty_cache()
            continue
        logger.info(f"Cannot recover from exception {e}. Exiting.")
        raise RuntimeError(e)
    fail_counter = 0

Note: While parsing the error string is suboptimal, it does not appear there is an alternative (I opened an issue about that in GitHub: https://github.com/pytorch/pytorch/issues/48365 1).
This above works well in the forward pass, but if the error occurs somewhere in the backward pass, and you use DistributedDataParallel, you get an exception such as:
RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by (1) passing the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`; (2) making sure all `forward` function outputs participate in calculating loss. If you already have done the above two steps, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's `forward` function. Please include the loss function and the structure of the return value of `forward` of your module when reporting this issue (e.g. list, dict, iterable).
Likely some parameters have already a computed derivative and then the model ran out of memory somewhere in the backward pass. Since this is very tricky to debug, I would appreciate any pointers where to look.