Spaces:
Sleeping
Sleeping
File size: 11,123 Bytes
5da0109 |
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 |
#
# SPDX-FileCopyrightText: Hadad <hadad@linuxmail.org>
# SPDX-License-Identifier: Apache-2.0
#
import os
import gc
import time
import atexit
import threading
import torch
from config import (
TEMPORARY_FILE_LIFETIME_SECONDS,
BACKGROUND_CLEANUP_INTERVAL,
MEMORY_WARNING_THRESHOLD,
MEMORY_CRITICAL_THRESHOLD,
MEMORY_CHECK_INTERVAL,
MEMORY_IDLE_TARGET,
MAXIMUM_MEMORY_USAGE
)
from ..core.state import (
temporary_files_registry,
temporary_files_lock,
memory_enforcement_lock,
background_cleanup_thread,
background_cleanup_stop_event,
background_cleanup_trigger_event,
check_if_generation_is_currently_active,
get_text_to_speech_manager
)
def get_current_memory_usage():
try:
with open('/proc/self/status', 'r') as status_file:
for line in status_file:
if line.startswith('VmRSS:'):
memory_value_kb = int(line.split()[1])
return memory_value_kb * 1024
except Exception:
pass
try:
with open('/proc/self/statm', 'r') as statm_file:
statm_values = statm_file.read().split()
resident_pages = int(statm_values[1])
page_size = os.sysconf('SC_PAGE_SIZE')
return resident_pages * page_size
except Exception:
pass
try:
import resource
import platform
memory_usage_kilobytes = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
if platform.system() == "Darwin":
return memory_usage_kilobytes
else:
return memory_usage_kilobytes * 1024
except Exception:
pass
return 0
def is_memory_usage_within_limit():
current_memory_usage = get_current_memory_usage()
return current_memory_usage < MAXIMUM_MEMORY_USAGE
def is_memory_usage_approaching_limit():
current_memory_usage = get_current_memory_usage()
return current_memory_usage >= MEMORY_WARNING_THRESHOLD
def is_memory_usage_critical():
current_memory_usage = get_current_memory_usage()
return current_memory_usage >= MEMORY_CRITICAL_THRESHOLD
def is_memory_above_idle_target():
current_memory_usage = get_current_memory_usage()
return current_memory_usage > MEMORY_IDLE_TARGET
def force_garbage_collection():
gc.collect(0)
gc.collect(1)
gc.collect(2)
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
def memory_cleanup():
force_garbage_collection()
try:
import ctypes
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)
except Exception:
pass
force_garbage_collection()
def perform_memory_cleanup():
force_garbage_collection()
tts_manager = get_text_to_speech_manager()
if tts_manager is not None:
tts_manager.evict_least_recently_used_voice_states()
memory_cleanup()
def cleanup_expired_temporary_files():
current_timestamp = time.time()
expired_files = []
with temporary_files_lock:
for file_path, creation_timestamp in list(temporary_files_registry.items()):
if current_timestamp - creation_timestamp > TEMPORARY_FILE_LIFETIME_SECONDS:
expired_files.append(file_path)
for file_path in expired_files:
try:
if os.path.exists(file_path):
os.remove(file_path)
del temporary_files_registry[file_path]
except Exception:
pass
def cleanup_all_temporary_files_immediately():
with temporary_files_lock:
for file_path in list(temporary_files_registry.keys()):
try:
if os.path.exists(file_path):
os.remove(file_path)
del temporary_files_registry[file_path]
except Exception:
pass
def has_temporary_files_pending_cleanup():
with temporary_files_lock:
if len(temporary_files_registry) == 0:
return False
current_timestamp = time.time()
for file_path, creation_timestamp in temporary_files_registry.items():
if current_timestamp - creation_timestamp > TEMPORARY_FILE_LIFETIME_SECONDS:
return True
return False
def has_any_temporary_files_registered():
with temporary_files_lock:
return len(temporary_files_registry) > 0
def calculate_time_until_next_file_expiration():
with temporary_files_lock:
if len(temporary_files_registry) == 0:
return None
current_timestamp = time.time()
minimum_time_until_expiration = None
for file_path, creation_timestamp in temporary_files_registry.items():
time_since_creation = current_timestamp - creation_timestamp
time_until_expiration = TEMPORARY_FILE_LIFETIME_SECONDS - time_since_creation
if time_until_expiration <= 0:
return 0
if minimum_time_until_expiration is None or time_until_expiration < minimum_time_until_expiration:
minimum_time_until_expiration = time_until_expiration
return minimum_time_until_expiration
def enforce_memory_limit_if_exceeded():
with memory_enforcement_lock:
generation_is_active = check_if_generation_is_currently_active()
current_memory_usage = get_current_memory_usage()
if current_memory_usage < MEMORY_WARNING_THRESHOLD:
return True
force_garbage_collection()
current_memory_usage = get_current_memory_usage()
if current_memory_usage < MEMORY_WARNING_THRESHOLD:
return True
tts_manager = get_text_to_speech_manager()
if tts_manager is not None:
tts_manager.evict_least_recently_used_voice_states()
memory_cleanup()
current_memory_usage = get_current_memory_usage()
if current_memory_usage < MEMORY_CRITICAL_THRESHOLD:
return True
if tts_manager is not None:
tts_manager.clear_voice_state_cache_completely()
cleanup_all_temporary_files_immediately()
memory_cleanup()
current_memory_usage = get_current_memory_usage()
if current_memory_usage < MAXIMUM_MEMORY_USAGE:
return True
if generation_is_active:
return current_memory_usage < MAXIMUM_MEMORY_USAGE
if tts_manager is not None:
tts_manager.unload_model_completely()
memory_cleanup()
current_memory_usage = get_current_memory_usage()
return current_memory_usage < MAXIMUM_MEMORY_USAGE
def perform_idle_memory_reduction():
if check_if_generation_is_currently_active():
return
with memory_enforcement_lock:
current_memory_usage = get_current_memory_usage()
if current_memory_usage <= MEMORY_IDLE_TARGET:
return
force_garbage_collection()
current_memory_usage = get_current_memory_usage()
if current_memory_usage <= MEMORY_IDLE_TARGET:
return
if check_if_generation_is_currently_active():
return
tts_manager = get_text_to_speech_manager()
if tts_manager is not None:
tts_manager.evict_least_recently_used_voice_states()
memory_cleanup()
current_memory_usage = get_current_memory_usage()
if current_memory_usage <= MEMORY_IDLE_TARGET:
return
if check_if_generation_is_currently_active():
return
if tts_manager is not None:
tts_manager.clear_voice_state_cache_completely()
memory_cleanup()
current_memory_usage = get_current_memory_usage()
if current_memory_usage <= MEMORY_IDLE_TARGET:
return
if check_if_generation_is_currently_active():
return
if tts_manager is not None:
tts_manager.unload_model_completely()
memory_cleanup()
def perform_background_cleanup_cycle():
last_memory_check_timestamp = 0
while not background_cleanup_stop_event.is_set():
time_until_next_expiration = calculate_time_until_next_file_expiration()
current_timestamp = time.time()
time_since_last_memory_check = current_timestamp - last_memory_check_timestamp
if time_until_next_expiration is not None:
if time_until_next_expiration <= 0:
wait_duration = 1
else:
wait_duration = min(
time_until_next_expiration + 1,
MEMORY_CHECK_INTERVAL,
BACKGROUND_CLEANUP_INTERVAL
)
else:
if is_memory_above_idle_target() and not check_if_generation_is_currently_active():
wait_duration = MEMORY_CHECK_INTERVAL
else:
background_cleanup_trigger_event.clear()
triggered = background_cleanup_trigger_event.wait(timeout=BACKGROUND_CLEANUP_INTERVAL)
if background_cleanup_stop_event.is_set():
break
if triggered:
continue
else:
if not check_if_generation_is_currently_active():
perform_idle_memory_reduction()
continue
background_cleanup_stop_event.wait(timeout=wait_duration)
if background_cleanup_stop_event.is_set():
break
if has_temporary_files_pending_cleanup():
cleanup_expired_temporary_files()
current_timestamp = time.time()
time_since_last_memory_check = current_timestamp - last_memory_check_timestamp
if time_since_last_memory_check >= MEMORY_CHECK_INTERVAL:
if not check_if_generation_is_currently_active():
if is_memory_usage_critical():
enforce_memory_limit_if_exceeded()
elif is_memory_above_idle_target():
perform_idle_memory_reduction()
last_memory_check_timestamp = current_timestamp
def trigger_background_cleanup_check():
background_cleanup_trigger_event.set()
def start_background_cleanup_thread():
global background_cleanup_thread
from ..core import state as global_state
if global_state.background_cleanup_thread is None or not global_state.background_cleanup_thread.is_alive():
background_cleanup_stop_event.clear()
background_cleanup_trigger_event.clear()
global_state.background_cleanup_thread = threading.Thread(
target=perform_background_cleanup_cycle,
daemon=True,
name="BackgroundCleanupThread"
)
global_state.background_cleanup_thread.start()
def stop_background_cleanup_thread():
from ..core import state as global_state
background_cleanup_stop_event.set()
background_cleanup_trigger_event.set()
if global_state.background_cleanup_thread is not None and global_state.background_cleanup_thread.is_alive():
global_state.background_cleanup_thread.join(timeout=5)
atexit.register(stop_background_cleanup_thread) |