78 lines
4.0 KiB
Python
78 lines
4.0 KiB
Python
"""Conservative cgroup-v2 admission; reservations include model loading/offload.
|
||
|
||
Working memory excludes reclaimable inactive file cache. Without reliable per-job
|
||
attribution, observed memory cannot be credited against model reservations: other
|
||
container-local workloads may grow during execution. Add active reservations in
|
||
full to observed working memory, then reserve the next job and global headroom.
|
||
This deliberately overcounts already-loaded model memory and can reduce slots.
|
||
SHM pages are already charged to memory.current, but full SHM independently blocks
|
||
admission. Unreadable/unlimited production budgets fail closed.
|
||
"""
|
||
from pathlib import Path
|
||
import shutil
|
||
|
||
from .video_profiles import H3_TP2_PROFILE
|
||
|
||
GIB = 1024 ** 3
|
||
|
||
|
||
def memory_reservation_gib(settings, task_type, parameters=None):
|
||
"""只为准确的TP2视频请求应用独立预留;历史/未知profile沿用任务预算。"""
|
||
if (task_type == 'video.generate' and isinstance(parameters, dict)
|
||
and parameters.get('profile') == H3_TP2_PROFILE):
|
||
return settings.video_generation_tp2_memory_gib
|
||
return settings.memory_estimates_gib[task_type]
|
||
|
||
|
||
class MemoryAdmission:
|
||
def __init__(self, settings, *, cgroup=Path('/sys/fs/cgroup'), shm_usage=None):
|
||
self.settings = settings
|
||
self.cgroup = Path(cgroup)
|
||
self.last_sample = None
|
||
self.shm_usage = shm_usage or self._shm
|
||
|
||
@staticmethod
|
||
def _shm():
|
||
usage = shutil.disk_usage('/dev/shm')
|
||
return usage.used, usage.total
|
||
|
||
def running_pressure(self):
|
||
"""Check container working memory without double-counting a running job's reservation."""
|
||
try:
|
||
maximum = int((self.cgroup / 'memory.max').read_text())
|
||
current = int((self.cgroup / 'memory.current').read_text())
|
||
stats = dict(line.split() for line in (self.cgroup / 'memory.stat').read_text().splitlines())
|
||
inactive = int(stats['inactive_file'])
|
||
if maximum <= 0 or not 0 <= inactive <= current:
|
||
raise ValueError("Invalid cgroup memory counters")
|
||
except (OSError, ValueError, KeyError):
|
||
return 'Container memory budget unavailable during TP2 execution'
|
||
headroom = max(16, self.settings.memory_headroom_gib) * GIB
|
||
if current - inactive > maximum - headroom:
|
||
return 'Container memory pressure during TP2 execution'
|
||
return None
|
||
|
||
def check(self, task_type, reservations, *, parameters=None):
|
||
try:
|
||
maximum = int((self.cgroup / 'memory.max').read_text().strip())
|
||
current = int((self.cgroup / 'memory.current').read_text().strip())
|
||
stats = dict(line.split() for line in (self.cgroup / 'memory.stat').read_text().splitlines())
|
||
working = max(0, current - int(stats.get('inactive_file', 0)))
|
||
used, total = self.shm_usage()
|
||
events_path = self.cgroup / 'memory.events'
|
||
events = dict(line.split() for line in events_path.read_text().splitlines()) if events_path.exists() else {}
|
||
required = (working + sum(reservations) * GIB
|
||
+ (memory_reservation_gib(self.settings, task_type, parameters)
|
||
+ self.settings.memory_headroom_gib) * GIB)
|
||
self.last_sample = {'memory_current_bytes': current, 'memory_max_bytes': maximum,
|
||
'working_bytes': working, 'reserved_bytes': sum(reservations) * GIB,
|
||
'admission_required_bytes': required, 'shm_used_bytes': used, 'shm_total_bytes': total,
|
||
'memory_events': {name: int(value) for name, value in events.items()}}
|
||
if total <= 0 or total - used < min(GIB, total * .05):
|
||
return 'Shared memory pressure; waiting for /dev/shm capacity'
|
||
if required > maximum:
|
||
return 'Container memory budget insufficient; FIFO head waiting'
|
||
except (OSError, ValueError, KeyError, TypeError):
|
||
return 'Container memory budget unavailable; dispatch blocked'
|
||
return None
|