old sam cleanup

This commit is contained in:
2025-07-26 13:21:39 -07:00
parent 3af16df71e
commit e7e9c5597b

View File

@@ -256,12 +256,33 @@ class SAM2VideoMatting:
"""Clean up resources""" """Clean up resources"""
if self.inference_state is not None: if self.inference_state is not None:
try: try:
if hasattr(self.predictor, 'cleanup_state'): # Reset SAM2 state first (critical for memory cleanup)
if hasattr(self.predictor, 'reset_state'):
self.predictor.reset_state(self.inference_state)
# Fallback to cleanup_state if available
elif hasattr(self.predictor, 'cleanup_state'):
self.predictor.cleanup_state(self.inference_state) self.predictor.cleanup_state(self.inference_state)
# Explicitly delete inference state and video segments
del self.inference_state
if hasattr(self, 'video_segments') and self.video_segments:
del self.video_segments
self.video_segments = {}
except Exception as e: except Exception as e:
warnings.warn(f"Failed to cleanup SAM2 state: {e}") warnings.warn(f"Failed to cleanup SAM2 state: {e}")
finally:
self.inference_state = None
self.inference_state = None # Explicitly delete predictor
if self.predictor is not None:
try:
del self.predictor
except Exception as e:
warnings.warn(f"Failed to delete predictor: {e}")
finally:
self.predictor = None
# Clean up temporary video file # Clean up temporary video file
if self.temp_video_path is not None: if self.temp_video_path is not None:
@@ -277,6 +298,10 @@ class SAM2VideoMatting:
if torch.cuda.is_available(): if torch.cuda.is_available():
torch.cuda.empty_cache() torch.cuda.empty_cache()
# Force garbage collection (critical for memory leak prevention)
import gc
gc.collect()
def __del__(self): def __del__(self):
"""Destructor to ensure cleanup""" """Destructor to ensure cleanup"""
self.cleanup() self.cleanup()