Spaces:
Running
Running
File size: 6,053 Bytes
ab4e093 |
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 |
#!/usr/bin/env python3
"""
Optimized runner for AI Knowledge Distillation Platform
Configured for CPU-only training with memory constraints
"""
import os
import sys
import logging
import asyncio
import uvicorn
from pathlib import Path
# Add src directory to Python path
sys.path.insert(0, str(Path(__file__).parent / "src"))
def setup_environment():
"""Setup environment variables for optimal CPU performance"""
# CPU optimization settings
os.environ['OMP_NUM_THREADS'] = str(min(os.cpu_count(), 8))
os.environ['MKL_NUM_THREADS'] = str(min(os.cpu_count(), 8))
os.environ['NUMEXPR_NUM_THREADS'] = str(min(os.cpu_count(), 8))
os.environ['OPENBLAS_NUM_THREADS'] = str(min(os.cpu_count(), 8))
# Memory optimization
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'
os.environ['TOKENIZERS_PARALLELISM'] = 'false' # Avoid tokenizer warnings
# Disable GPU if available (force CPU-only)
os.environ['CUDA_VISIBLE_DEVICES'] = ''
# Set memory limits for Hugging Face
os.environ['HF_DATASETS_CACHE'] = './cache/datasets'
os.environ['TRANSFORMERS_CACHE'] = './cache/transformers'
print("β
Environment optimized for CPU-only training")
print(f"π§ CPU threads: {os.environ['OMP_NUM_THREADS']}")
print(f"πΎ Memory optimization enabled")
def setup_logging():
"""Setup logging configuration"""
# Create logs directory
logs_dir = Path("logs")
logs_dir.mkdir(exist_ok=True)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(logs_dir / "app.log"),
logging.StreamHandler(sys.stdout)
]
)
# Set specific log levels
logging.getLogger("uvicorn").setLevel(logging.INFO)
logging.getLogger("transformers").setLevel(logging.WARNING)
logging.getLogger("datasets").setLevel(logging.WARNING)
print("π Logging configured")
def check_system_requirements():
"""Check system requirements and provide recommendations"""
import psutil
# Check available memory
memory = psutil.virtual_memory()
memory_gb = memory.total / (1024**3)
print(f"\nπ₯οΈ System Information:")
print(f" πΎ Total Memory: {memory_gb:.1f} GB")
print(f" π Available Memory: {memory.available / (1024**3):.1f} GB")
print(f" π§ CPU Cores: {os.cpu_count()}")
# Recommendations
if memory_gb < 8:
print("β οΈ Warning: Less than 8GB RAM detected. Consider using smaller models.")
elif memory_gb < 16:
print("βΉοΈ Note: 8-16GB RAM detected. Chunked loading will be used for large models.")
else:
print("β
Sufficient memory for most operations.")
# Check disk space
disk = psutil.disk_usage('.')
disk_free_gb = disk.free / (1024**3)
print(f" πΏ Free Disk Space: {disk_free_gb:.1f} GB")
if disk_free_gb < 10:
print("β οΈ Warning: Less than 10GB free disk space. Consider cleaning up.")
return memory_gb >= 4 # Minimum 4GB required
def create_directories():
"""Create necessary directories"""
directories = [
"cache",
"cache/datasets",
"cache/transformers",
"cache/medical_datasets",
"database",
"logs",
"models",
"backups"
]
for directory in directories:
Path(directory).mkdir(parents=True, exist_ok=True)
print("π Directories created")
def check_dependencies():
"""Check if required dependencies are installed"""
required_packages = [
'torch',
'transformers',
'fastapi',
'uvicorn',
'datasets',
'safetensors',
'psutil'
]
missing_packages = []
for package in required_packages:
try:
__import__(package)
except ImportError:
missing_packages.append(package)
if missing_packages:
print(f"β Missing packages: {', '.join(missing_packages)}")
print("π¦ Install with: pip install -r requirements.txt")
return False
print("β
All required packages installed")
return True
def main():
"""Main function to run the optimized server"""
print("π Starting AI Knowledge Distillation Platform (Optimized)")
print("=" * 60)
# Setup environment
setup_environment()
setup_logging()
create_directories()
# Check system requirements
if not check_system_requirements():
print("β System requirements not met. Exiting.")
sys.exit(1)
# Check dependencies
if not check_dependencies():
print("β Dependencies not satisfied. Exiting.")
sys.exit(1)
print("\nπ― Starting server with optimized settings...")
print("π Access the application at: http://localhost:8000")
print("π Token management: http://localhost:8000/tokens")
print("π₯ Medical datasets: http://localhost:8000/medical-datasets")
print("\n" + "=" * 60)
# Import and start the app
try:
from app import app
# Configure uvicorn for optimal performance
config = uvicorn.Config(
app=app,
host="0.0.0.0",
port=8000,
log_level="info",
access_log=True,
workers=1, # Single worker for memory efficiency
loop="asyncio",
http="httptools",
ws="websockets",
lifespan="on",
reload=False # Disable reload for production
)
server = uvicorn.Server(config)
# Start server
asyncio.run(server.serve())
except KeyboardInterrupt:
print("\nπ Server stopped by user")
except Exception as e:
print(f"β Error starting server: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
|