| 4 | |
| 5 | |
| 6 | class CpuOffloader: |
| 7 | def __init__(self, model, device="cpu"): |
| 8 | self.model = model |
| 9 | self.original_device = device |
| 10 | self.original_dtype = model.dtype |
| 11 | |
| 12 | def __enter__(self): |
| 13 | if not hasattr(self.model,"torchao_quantized"): |
| 14 | self.model.to(self.original_device, dtype=self.original_dtype) |
| 15 | return self.model |
| 16 | |
| 17 | def __exit__(self, *args): |
| 18 | if not hasattr(self.model,"torchao_quantized"): |
| 19 | self.model.to("cpu") |
| 20 | if torch.cuda.is_available(): |
| 21 | torch.cuda.empty_cache() |
| 22 | torch.cuda.synchronize() |
| 23 | |
| 24 | |
| 25 | T = TypeVar('T') |