Arulkumar03/Fox_Sheep_Detector_Computer_Vision_model
0
1# Copyright (c) Facebook, Inc. and its affiliates.2 3import logging4from contextlib import contextmanager5from functools import wraps6import torch7 8__all__ = ["retry_if_cuda_oom"]9 10 11@contextmanager12def _ignore_torch_cuda_oom():13 """14 A context which ignores CUDA OOM exception from pytorch.15 """16 try:17 yield18 except RuntimeError as e:19 # NOTE: the string may change?20 if "CUDA out of memory. " in str(e):21 pass22 else:23 raise24 25 26def retry_if_cuda_oom(func):27 """28 Makes a function retry itself after encountering29 pytorch's CUDA OOM error.30 It will first retry after calling `torch.cuda.empty_cache()`.31 32 If that still fails, it will then retry by trying to convert inputs to CPUs.33 In this case, it expects the function to dispatch to CPU implementation.34 The return values may become CPU tensors as well and it's user's35 responsibility to convert it back to CUDA tensor if needed.36 37 Args:38 func: a stateless callable that takes tensor-like objects as arguments39 40 Returns:41 a callable which retries `func` if OOM is encountered.42 43 Examples:44 ::45 output = retry_if_cuda_oom(some_torch_function)(input1, input2)46 # output may be on CPU even if inputs are on GPU47 48 Note:49 1. When converting inputs to CPU, it will only look at each argument and check50 if it has `.device` and `.to` for conversion. Nested structures of tensors51 are not supported.52 53 2. Since the function might be called more than once, it has to be54 stateless.55 """56 57 def maybe_to_cpu(x):58 try:59 like_gpu_tensor = x.device.type == "cuda" and hasattr(x, "to")60 except AttributeError:61 like_gpu_tensor = False62 if like_gpu_tensor:63 return x.to(device="cpu")64 else:65 return x66 67 @wraps(func)68 def wrapped(*args, **kwargs):69 with _ignore_torch_cuda_oom():70 return func(*args, **kwargs)71 72 # Clear cache and retry73 torch.cuda.empty_cache()74 with _ignore_torch_cuda_oom():75 return func(*args, **kwargs)76 77 # Try on CPU. This slows down the code significantly, therefore print a notice.78 logger = logging.getLogger(__name__)79 logger.info("Attempting to copy inputs of {} to CPU due to CUDA OOM".format(str(func)))80 new_args = (maybe_to_cpu(x) for x in args)81 new_kwargs = {k: maybe_to_cpu(v) for k, v in kwargs.items()}82 return func(*new_args, **new_kwargs)83 84 return wrapped85 