Spaces:
Paused
Paused
File size: 25,430 Bytes
56c063a | 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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 | """
Memory management system for large dataset processing.
Provides memory monitoring, chunked processing, and memory optimization.
"""
import asyncio
import logging
import gc
import os
import psutil
import tempfile
import pickle
import mmap
from typing import Any, Dict, List, Optional, Iterator, Callable, Union, Tuple
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
import pandas as pd
import numpy as np
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import threading
import weakref
from contextlib import contextmanager
from .config import settings
from .monitoring import monitoring_system
logger = logging.getLogger(__name__)
@dataclass
class MemoryStats:
"""Memory usage statistics."""
total_mb: float
available_mb: float
used_mb: float
percent_used: float
process_memory_mb: float
swap_used_mb: float
memory_pressure: str # 'low', 'medium', 'high', 'critical'
def to_dict(self) -> Dict[str, Any]:
return {
'total_mb': self.total_mb,
'available_mb': self.available_mb,
'used_mb': self.used_mb,
'percent_used': self.percent_used,
'process_memory_mb': self.process_memory_mb,
'swap_used_mb': self.swap_used_mb,
'memory_pressure': self.memory_pressure
}
@dataclass
class DatasetChunk:
"""Represents a chunk of a dataset."""
chunk_id: int
start_row: int
end_row: int
data: Optional[pd.DataFrame]
file_path: Optional[str]
size_bytes: int
def __post_init__(self):
if self.data is not None and self.size_bytes == 0:
self.size_bytes = self.data.memory_usage(deep=True).sum()
class MemoryMonitor:
"""Monitors system and process memory usage."""
def __init__(self):
self._monitoring = False
self._monitor_task: Optional[asyncio.Task] = None
self._callbacks: List[Callable[[MemoryStats], None]] = []
self._thresholds = {
'medium': 70.0, # 70% memory usage
'high': 85.0, # 85% memory usage
'critical': 95.0 # 95% memory usage
}
async def start_monitoring(self, interval_seconds: int = 30):
"""Start memory monitoring."""
if self._monitoring:
return
self._monitoring = True
self._monitor_task = asyncio.create_task(self._monitor_loop(interval_seconds))
logger.info("Memory monitoring started")
async def stop_monitoring(self):
"""Stop memory monitoring."""
self._monitoring = False
if self._monitor_task:
self._monitor_task.cancel()
try:
await self._monitor_task
except asyncio.CancelledError:
pass
logger.info("Memory monitoring stopped")
async def _monitor_loop(self, interval_seconds: int):
"""Memory monitoring loop."""
while self._monitoring:
try:
stats = self.get_memory_stats()
# Record metrics
monitoring_system.metrics_collector.record_metric(
"memory.usage_percent", stats.percent_used
)
monitoring_system.metrics_collector.record_metric(
"memory.available_mb", stats.available_mb
)
monitoring_system.metrics_collector.record_metric(
"memory.process_mb", stats.process_memory_mb
)
# Notify callbacks
for callback in self._callbacks:
try:
callback(stats)
except Exception as e:
logger.error(f"Memory monitor callback failed: {e}")
await asyncio.sleep(interval_seconds)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Memory monitoring error: {e}")
await asyncio.sleep(interval_seconds)
def get_memory_stats(self) -> MemoryStats:
"""Get current memory statistics."""
try:
# System memory
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
# Process memory
process = psutil.Process()
process_memory = process.memory_info()
# Determine memory pressure
pressure = 'low'
if memory.percent >= self._thresholds['critical']:
pressure = 'critical'
elif memory.percent >= self._thresholds['high']:
pressure = 'high'
elif memory.percent >= self._thresholds['medium']:
pressure = 'medium'
return MemoryStats(
total_mb=memory.total / (1024 * 1024),
available_mb=memory.available / (1024 * 1024),
used_mb=memory.used / (1024 * 1024),
percent_used=memory.percent,
process_memory_mb=process_memory.rss / (1024 * 1024),
swap_used_mb=swap.used / (1024 * 1024),
memory_pressure=pressure
)
except Exception as e:
logger.error(f"Failed to get memory stats: {e}")
return MemoryStats(0, 0, 0, 0, 0, 0, 'unknown')
def add_callback(self, callback: Callable[[MemoryStats], None]):
"""Add memory monitoring callback."""
self._callbacks.append(callback)
def remove_callback(self, callback: Callable[[MemoryStats], None]):
"""Remove memory monitoring callback."""
if callback in self._callbacks:
self._callbacks.remove(callback)
class ChunkedDataProcessor:
"""Processes large datasets in chunks to manage memory usage."""
def __init__(self, chunk_size: int = 10000, max_memory_mb: float = 500):
self.chunk_size = chunk_size
self.max_memory_mb = max_memory_mb
self.temp_dir = Path(tempfile.gettempdir()) / "mcp_data_chunks"
self.temp_dir.mkdir(exist_ok=True)
self._chunk_cache: Dict[str, DatasetChunk] = {}
self._cache_lock = threading.Lock()
def chunk_dataframe(self, df: pd.DataFrame, chunk_id_prefix: str = "chunk") -> List[DatasetChunk]:
"""Split DataFrame into chunks."""
chunks = []
total_rows = len(df)
for i in range(0, total_rows, self.chunk_size):
start_row = i
end_row = min(i + self.chunk_size, total_rows)
chunk_data = df.iloc[start_row:end_row].copy()
chunk = DatasetChunk(
chunk_id=len(chunks),
start_row=start_row,
end_row=end_row,
data=chunk_data,
file_path=None,
size_bytes=chunk_data.memory_usage(deep=True).sum()
)
chunks.append(chunk)
logger.info(f"Split DataFrame into {len(chunks)} chunks")
return chunks
async def process_chunks_async(
self,
chunks: List[DatasetChunk],
processor_func: Callable[[pd.DataFrame], pd.DataFrame],
max_concurrent: int = 3
) -> List[pd.DataFrame]:
"""Process chunks asynchronously with memory management."""
semaphore = asyncio.Semaphore(max_concurrent)
results = []
async def process_chunk(chunk: DatasetChunk) -> pd.DataFrame:
async with semaphore:
# Check memory before processing
memory_stats = memory_monitor.get_memory_stats()
if memory_stats.memory_pressure in ['high', 'critical']:
logger.warning(f"High memory pressure ({memory_stats.percent_used}%), waiting...")
await asyncio.sleep(1)
gc.collect()
# Process chunk in thread pool
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None, processor_func, chunk.data
)
return result
# Process all chunks
tasks = [process_chunk(chunk) for chunk in chunks]
results = await asyncio.gather(*tasks)
return results
def save_chunk_to_disk(self, chunk: DatasetChunk, chunk_id: str) -> str:
"""Save chunk to disk and return file path."""
file_path = self.temp_dir / f"{chunk_id}.parquet"
try:
chunk.data.to_parquet(file_path, compression='snappy')
chunk.file_path = str(file_path)
chunk.data = None # Free memory
with self._cache_lock:
self._chunk_cache[chunk_id] = chunk
logger.debug(f"Saved chunk {chunk_id} to disk: {file_path}")
return str(file_path)
except Exception as e:
logger.error(f"Failed to save chunk to disk: {e}")
raise
def load_chunk_from_disk(self, chunk_id: str) -> Optional[DatasetChunk]:
"""Load chunk from disk."""
with self._cache_lock:
if chunk_id not in self._chunk_cache:
return None
chunk = self._chunk_cache[chunk_id]
if chunk.data is None and chunk.file_path:
try:
chunk.data = pd.read_parquet(chunk.file_path)
logger.debug(f"Loaded chunk {chunk_id} from disk")
except Exception as e:
logger.error(f"Failed to load chunk from disk: {e}")
return None
return chunk
def cleanup_chunks(self, chunk_ids: List[str] = None):
"""Clean up chunk files and cache."""
with self._cache_lock:
if chunk_ids is None:
chunk_ids = list(self._chunk_cache.keys())
for chunk_id in chunk_ids:
if chunk_id in self._chunk_cache:
chunk = self._chunk_cache[chunk_id]
# Delete file if exists
if chunk.file_path and os.path.exists(chunk.file_path):
try:
os.remove(chunk.file_path)
logger.debug(f"Deleted chunk file: {chunk.file_path}")
except Exception as e:
logger.error(f"Failed to delete chunk file: {e}")
# Remove from cache
del self._chunk_cache[chunk_id]
# Force garbage collection
gc.collect()
class MemoryEfficientDataLoader:
"""Loads large datasets efficiently with memory management."""
def __init__(self, memory_limit_mb: float = 1000):
self.memory_limit_mb = memory_limit_mb
self.chunk_processor = ChunkedDataProcessor()
async def load_large_dataset(
self,
file_path: str,
file_format: str = 'auto',
chunk_size: int = 10000
) -> Iterator[pd.DataFrame]:
"""Load large dataset in chunks."""
if file_format == 'auto':
file_format = Path(file_path).suffix.lower().lstrip('.')
try:
if file_format == 'csv':
chunk_iter = pd.read_csv(file_path, chunksize=chunk_size)
elif file_format in ['xlsx', 'xls']:
# Excel files need to be loaded entirely first, then chunked
df = pd.read_excel(file_path)
chunks = self.chunk_processor.chunk_dataframe(df)
chunk_iter = (chunk.data for chunk in chunks)
elif file_format == 'parquet':
# Parquet supports native chunking
parquet_file = pd.read_parquet(file_path)
chunks = self.chunk_processor.chunk_dataframe(parquet_file)
chunk_iter = (chunk.data for chunk in chunks)
else:
raise ValueError(f"Unsupported file format: {file_format}")
chunk_count = 0
for chunk in chunk_iter:
# Monitor memory before yielding chunk
memory_stats = memory_monitor.get_memory_stats()
if memory_stats.memory_pressure == 'critical':
logger.warning("Critical memory pressure, forcing garbage collection")
gc.collect()
await asyncio.sleep(0.1) # Allow other tasks to run
chunk_count += 1
logger.debug(f"Loaded chunk {chunk_count}, shape: {chunk.shape}")
yield chunk
except Exception as e:
logger.error(f"Failed to load dataset: {e}")
raise
async def process_large_dataset(
self,
file_path: str,
processor_func: Callable[[pd.DataFrame], pd.DataFrame],
output_path: Optional[str] = None,
chunk_size: int = 10000
) -> Optional[str]:
"""Process large dataset with memory management."""
processed_chunks = []
chunk_count = 0
async for chunk in self.load_large_dataset(file_path, chunk_size=chunk_size):
# Process chunk
try:
processed_chunk = processor_func(chunk)
processed_chunks.append(processed_chunk)
chunk_count += 1
# Check memory usage
memory_stats = memory_monitor.get_memory_stats()
if memory_stats.memory_pressure in ['high', 'critical']:
logger.info(f"High memory pressure, saving intermediate results")
# Save intermediate results and clear memory
if output_path:
temp_path = f"{output_path}.temp_{chunk_count}"
combined = pd.concat(processed_chunks, ignore_index=True)
combined.to_parquet(temp_path)
processed_chunks = []
gc.collect()
except Exception as e:
logger.error(f"Failed to process chunk {chunk_count}: {e}")
raise
# Combine all processed chunks
if processed_chunks:
result_df = pd.concat(processed_chunks, ignore_index=True)
if output_path:
result_df.to_parquet(output_path)
logger.info(f"Saved processed dataset to: {output_path}")
return output_path
else:
return result_df
return None
class MemoryOptimizer:
"""Optimizes memory usage for DataFrames and other objects."""
@staticmethod
def optimize_dataframe_memory(df: pd.DataFrame) -> pd.DataFrame:
"""Optimize DataFrame memory usage by downcasting numeric types."""
original_memory = df.memory_usage(deep=True).sum()
# Optimize numeric columns
for col in df.select_dtypes(include=['int64']).columns:
df[col] = pd.to_numeric(df[col], downcast='integer')
for col in df.select_dtypes(include=['float64']).columns:
df[col] = pd.to_numeric(df[col], downcast='float')
# Optimize object columns (strings)
for col in df.select_dtypes(include=['object']).columns:
if df[col].dtype == 'object':
try:
# Try to convert to category if it has few unique values
unique_ratio = df[col].nunique() / len(df)
if unique_ratio < 0.5: # Less than 50% unique values
df[col] = df[col].astype('category')
except:
pass
optimized_memory = df.memory_usage(deep=True).sum()
reduction = (original_memory - optimized_memory) / original_memory * 100
logger.info(f"Memory optimization: {reduction:.1f}% reduction "
f"({original_memory / 1024**2:.1f}MB -> {optimized_memory / 1024**2:.1f}MB)")
return df
@staticmethod
def get_object_size(obj: Any) -> int:
"""Get approximate size of Python object in bytes."""
try:
return len(pickle.dumps(obj))
except:
# Fallback for non-picklable objects
return len(str(obj).encode('utf-8'))
class MemoryManager:
"""Main memory management coordinator."""
def __init__(self):
self.monitor = MemoryMonitor()
self.chunk_processor = ChunkedDataProcessor()
self.data_loader = MemoryEfficientDataLoader()
self.optimizer = MemoryOptimizer()
self._memory_callbacks: List[Callable] = []
self._cleanup_threshold = 85.0 # Trigger cleanup at 85% memory usage
async def start(self):
"""Start memory management system."""
await self.monitor.start_monitoring()
# Add memory pressure callback
self.monitor.add_callback(self._handle_memory_pressure)
logger.info("Memory manager started")
async def stop(self):
"""Stop memory management system."""
await self.monitor.stop_monitoring()
self.chunk_processor.cleanup_chunks()
logger.info("Memory manager stopped")
def _handle_memory_pressure(self, stats: MemoryStats):
"""Handle memory pressure situations."""
if stats.percent_used >= self._cleanup_threshold:
logger.warning(f"Memory pressure detected ({stats.percent_used}%), triggering cleanup")
# Force garbage collection
gc.collect()
# Notify callbacks
for callback in self._memory_callbacks:
try:
callback(stats)
except Exception as e:
logger.error(f"Memory pressure callback failed: {e}")
def add_memory_callback(self, callback: Callable[[MemoryStats], None]):
"""Add callback for memory pressure events."""
self._memory_callbacks.append(callback)
@contextmanager
def memory_context(self, operation_name: str = "operation"):
"""Context manager for monitoring memory usage during operations."""
start_stats = self.monitor.get_memory_stats()
start_time = datetime.utcnow()
logger.info(f"Starting {operation_name} - Memory: {start_stats.percent_used:.1f}%")
try:
yield
finally:
end_stats = self.monitor.get_memory_stats()
end_time = datetime.utcnow()
duration = (end_time - start_time).total_seconds()
memory_change = end_stats.process_memory_mb - start_stats.process_memory_mb
logger.info(f"Completed {operation_name} in {duration:.1f}s - "
f"Memory: {end_stats.percent_used:.1f}% "
f"(change: {memory_change:+.1f}MB)")
async def process_large_dataset_safely(
self,
file_path: str,
processor_func: Callable[[pd.DataFrame], pd.DataFrame],
output_path: Optional[str] = None
) -> Any:
"""Process large dataset with comprehensive memory management."""
with self.memory_context(f"processing {Path(file_path).name}"):
# Check available memory
stats = self.monitor.get_memory_stats()
if stats.memory_pressure == 'critical':
raise MemoryError("Insufficient memory to process dataset")
# Determine optimal chunk size based on available memory
available_mb = stats.available_mb
chunk_size = min(50000, max(1000, int(available_mb * 100))) # Heuristic
logger.info(f"Processing with chunk size: {chunk_size}")
return await self.data_loader.process_large_dataset(
file_path, processor_func, output_path, chunk_size
)
def get_memory_report(self) -> Dict[str, Any]:
"""Get comprehensive memory usage report."""
stats = self.monitor.get_memory_stats()
chunk_stats = self.chunk_processor.get_stats() if hasattr(self.chunk_processor, 'get_stats') else {}
return {
'timestamp': datetime.utcnow().isoformat(),
'system_memory': stats.to_dict(),
'chunk_processor': chunk_stats,
'recommendations': self._get_memory_recommendations(stats)
}
def _get_memory_recommendations(self, stats: MemoryStats) -> List[str]:
"""Get memory optimization recommendations."""
recommendations = []
if stats.memory_pressure == 'critical':
recommendations.append("Critical memory usage - consider reducing dataset size or increasing system memory")
recommendations.append("Enable aggressive garbage collection and memory cleanup")
recommendations.append("Consider processing data in smaller chunks")
elif stats.memory_pressure == 'high':
recommendations.append("High memory usage - enable aggressive chunking and caching")
recommendations.append("Consider offloading data to disk storage")
if stats.swap_used_mb > 100:
recommendations.append("Swap usage detected - consider increasing RAM or optimizing memory usage")
recommendations.append("Review memory-intensive operations and optimize algorithms")
if stats.process_memory_mb > 1000:
recommendations.append("High process memory usage - consider memory optimization techniques")
recommendations.append("Review DataFrame memory usage and apply optimizations")
if stats.available_mb < 500:
recommendations.append("Low available memory - consider freeing unused resources")
return recommendations
async def trigger_memory_cleanup(self, aggressive: bool = False):
"""Trigger memory cleanup operations."""
logger.info(f"Triggering {'aggressive' if aggressive else 'standard'} memory cleanup")
# Clear chunk processor cache
self.chunk_processor.cleanup_chunks()
# Clear data loader cache if available
if hasattr(self.data_loader, 'clear_cache'):
self.data_loader.clear_cache()
# Force garbage collection
if aggressive:
# Multiple GC passes for aggressive cleanup
for _ in range(3):
gc.collect()
await asyncio.sleep(0.1)
else:
gc.collect()
# Log memory stats after cleanup
stats = self.monitor.get_memory_stats()
logger.info(f"Memory cleanup completed - Usage: {stats.percent_used:.1f}%")
async def optimize_for_large_dataset(self, estimated_size_mb: float) -> Dict[str, Any]:
"""Optimize system settings for large dataset processing."""
current_stats = self.monitor.get_memory_stats()
# Calculate optimal settings
available_memory = current_stats.available_mb
recommended_chunk_size = min(50000, max(1000, int(available_memory * 50))) # 50 rows per MB available
# Adjust chunk processor settings
self.chunk_processor.chunk_size = recommended_chunk_size
self.chunk_processor.max_memory_mb = min(available_memory * 0.7, 1000) # Use 70% of available memory
# Adjust data loader settings
self.data_loader.memory_limit_mb = min(available_memory * 0.8, 2000) # Use 80% of available memory
optimization_settings = {
'estimated_dataset_size_mb': estimated_size_mb,
'available_memory_mb': available_memory,
'recommended_chunk_size': recommended_chunk_size,
'chunk_processor_memory_limit_mb': self.chunk_processor.max_memory_mb,
'data_loader_memory_limit_mb': self.data_loader.memory_limit_mb,
'memory_pressure': current_stats.memory_pressure
}
logger.info(f"Optimized settings for {estimated_size_mb}MB dataset: {optimization_settings}")
return optimization_settings
# Global memory manager instance
memory_monitor = MemoryMonitor()
memory_manager = MemoryManager() |