File size: 8,839 Bytes
101858b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""

Unified Memory Manager Module

Main memory management system integrating all components.

"""
import torch
import torch.nn as nn
import logging
from typing import Dict, Any, Optional, Tuple, List
from .config import MemoryOptimizationConfig
from .tensor_pool import TensorPool
from .model_cache import ModelCache
from .cleanup import MemoryCleanup

logger = logging.getLogger(__name__)

class UnifiedMemoryManager:
    """

    Unified Memory Manager - Central memory optimization system.

    

    Integrates tensor pooling, model caching, and cleanup utilities.

    Uses shared Qwen model for zero memory overhead.

    """
    
    _instance = None
    _initialized = False
    
    def __new__(cls, config: Optional[MemoryOptimizationConfig] = None):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self, config: Optional[MemoryOptimizationConfig] = None):
        if not self._initialized:
            self.config = config or MemoryOptimizationConfig()
            self._initialize_memory_manager()
            UnifiedMemoryManager._initialized = True
    
    def _initialize_memory_manager(self):
        """Initialize the unified memory manager with optimal settings."""
        self.device = torch.device(self.config.device)
        
        # Initialize components
        self.tensor_pool = TensorPool(
            max_pool_size=self.config.max_pool_size,
            max_tensor_size=self.config.max_tensor_size
        )
        
        self.model_cache = ModelCache(
            use_shared_model=self.config.use_shared_model,
            shared_model_name=self.config.shared_model_name
        )
        
        self.cleanup = MemoryCleanup(
            memory_threshold=self.config.memory_threshold,
            cleanup_threshold=self.config.cleanup_threshold
        )
        
        # Lazy loading registry
        self.lazy_modules = {}
        self.active_modules = set()
        
        logger.info("[MANAGER] Unified Memory Manager initialized")
        logger.info(f"[MANAGER] Device: {self.device}")
        logger.info(f"[MANAGER] Shared Model: {self.config.use_shared_model}")
    
    def get_shared_model(self, model_name: str, model_type: str = "transformer",

                        device: Optional[str] = None, **kwargs) -> Any:
        """

        Get or create a shared model instance.

        

        Args:

            model_name: Name of the model to load

            model_type: Type of model (transformer, tokenizer, etc.)

            device: Device to load model on

            **kwargs: Additional model loading parameters

            

        Returns:

            Shared model instance

        """
        if device is None:
            device = str(self.device)
        
        return self.model_cache.get_shared_model(
            model_name, model_type, device, **kwargs
        )
    
    def get_tensor(self, shape: Tuple[int, ...], dtype: torch.dtype = torch.float32,

                   requires_grad: bool = False, module_name: str = "default") -> torch.Tensor:
        """

        Get tensor from unified pool or create new one.

        

        Args:

            shape: Tensor shape

            dtype: Tensor data type

            requires_grad: Whether tensor requires gradients

            module_name: Name of requesting module for tracking

            

        Returns:

            Optimized tensor

        """
        # Check memory pressure and cleanup if needed
        if self.tensor_pool.operation_count % self.config.cleanup_frequency == 0:
            self.cleanup.adaptive_cleanup(self.tensor_pool)
        
        # Check memory pressure before creating new tensor
        if self.cleanup.check_memory_pressure():
            self.cleanup.emergency_cleanup(self.tensor_pool)
        
        return self.tensor_pool.get_tensor(shape, dtype, requires_grad, self.device)
    
    def return_tensor(self, tensor: torch.Tensor, module_name: str = "default") -> None:
        """

        Return tensor to unified pool for reuse.

        

        Args:

            tensor: Tensor to return to pool

            module_name: Name of returning module

        """
        self.tensor_pool.return_tensor(tensor)
    
    def register_lazy_module(self, module_name: str, module_class: type,

                           init_args: tuple = (), init_kwargs: dict = None) -> None:
        """

        Register a module for lazy loading.

        

        Args:

            module_name: Name of the module

            module_class: Module class to instantiate

            init_args: Positional arguments for initialization

            init_kwargs: Keyword arguments for initialization

        """
        if init_kwargs is None:
            init_kwargs = {}
        
        self.lazy_modules[module_name] = {
            'class': module_class,
            'args': init_args,
            'kwargs': init_kwargs
        }
    
    def get_lazy_module(self, module_name: str) -> Optional[Any]:
        """

        Get lazy-loaded module, creating it if necessary.

        

        Args:

            module_name: Name of the module to get

            

        Returns:

            Module instance or None if not found

        """
        if module_name in self.active_modules:
            return getattr(self, module_name, None)
        
        if module_name in self.lazy_modules:
            config = self.lazy_modules[module_name]
            module = config['class'](*config['args'], **config['kwargs'])
            setattr(self, module_name, module)
            self.active_modules.add(module_name)
            
            # Check memory pressure after loading
            if self.cleanup.check_memory_pressure():
                self.cleanup.adaptive_cleanup(self.tensor_pool)
            
            return module
        
        return None
    
    def optimize_for_inference(self, model: nn.Module) -> nn.Module:
        """

        Optimize model for inference with memory efficiency.

        

        Args:

            model: Model to optimize

            

        Returns:

            Optimized model

        """
        # Set to evaluation mode
        model.eval()
        
        # Enable gradient checkpointing if available
        if self.config.use_gradient_checkpointing and hasattr(model, 'gradient_checkpointing_enable'):
            model.gradient_checkpointing_enable()
        
        # Optimize for inference
        if hasattr(model, 'half') and torch.cuda.is_available():
            model = model.half()
        
        return model
    
    def register_memory(self, embedding_tensor: torch.Tensor, metadata: Optional[Dict[str, Any]] = None) -> None:
        """

        Register a memory embedding tensor with the optimization system.

        

        Args:

            embedding_tensor: Memory embedding tensor to register

            metadata: Optional metadata dictionary

        """
        # Track memory usage for optimization
        if metadata is None:
            metadata = {}
        
        # Check memory pressure and cleanup if needed
        if self.cleanup.check_memory_pressure():
            self.cleanup.adaptive_cleanup(self.tensor_pool)
        
        # Store metadata for tracking (if needed for future optimization)
        # This is a no-op for now but allows the interface to exist
        # The actual memory is managed by the tensor pool and cleanup system
        pass
    
    def get_memory_stats(self) -> Dict[str, Any]:
        """Get comprehensive memory statistics."""
        stats = {
            'tensor_pool': self.tensor_pool.get_stats(),
            'model_cache': self.model_cache.get_stats(),
            'cleanup': self.cleanup.get_memory_stats(),
            'active_modules': list(self.active_modules),
            'lazy_modules': list(self.lazy_modules.keys())
        }
        
        return stats
    
    def clear_all_memory(self) -> None:
        """Clear all memory and reset the manager."""
        logger.info("[MANAGER] Clearing all memory")
        
        # Clear tensor pools
        self.tensor_pool.clear_all()
        
        # Clear model cache
        self.model_cache.clear_cache()
        
        # Clear active modules
        self.active_modules.clear()
        self.lazy_modules.clear()
        
        # Clear PyTorch cache
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        
        # Force garbage collection
        import gc
        gc.collect()
        
        logger.info("[MANAGER] All memory cleared")