Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Record memory and exit class when a generation worker ends unexpectedly
Bowen Xue6935bb6651cc
diff --git a/freevideo_engine/adaptive.py b/freevideo_engine/adaptive.pyindex ea166ea..102a6ad 100644--- a/freevideo_engine/adaptive.py+++ b/freevideo_engine/adaptive.py@@ -101,6 +101,13 @@ def classify_failure(error, metrics=None):result['ram_guard'] = {key: telemetry['ram_guard'].get(key) for key in('reasons', 'working_bytes', 'budget_bytes', 'available_bytes', 'emergency_floor_bytes','physical_available_bytes', 'commit_available_bytes') if key in telemetry['ram_guard']}+ if isinstance(error, WorkerExit) and isinstance(telemetry, dict):+ # The worker is gone; these are the controller's readings at its start and at its exit.+ from .exit_diagnostics import clean_reading, clean_sample+ if isinstance(telemetry.get('worker_exit'), dict):+ result['worker_exit'] = clean_reading(telemetry['worker_exit'])+ if isinstance(telemetry.get('memory_at_start'), dict):+ result['memory_at_start'] = clean_sample(telemetry['memory_at_start'])if cleanup:result['cleanup_evidence'] = [str(item) for item in cleanup]if getattr(error, 'worker_stop_confirmed', None) is False:diff --git a/freevideo_engine/diagnostic_resources.py b/freevideo_engine/diagnostic_resources.pyindex 495137c..cf4ed69 100644--- a/freevideo_engine/diagnostic_resources.py+++ b/freevideo_engine/diagnostic_resources.py@@ -681,6 +681,11 @@ def failure(value):if isinstance(value.get('memory_collection_error'), list):result['memory_collection_error'] = [trace(row) for row in value['memory_collection_error'][:4]]result['allocation'] = numbers(value.get('allocation'), ('fp8_ff_activation_stash_bytes',))+ from .exit_diagnostics import clean_reading, clean_sample+ if isinstance(value.get('worker_exit'), dict):+ result['worker_exit'] = clean_reading(value['worker_exit'])+ if isinstance(value.get('memory_at_start'), dict):+ result['memory_at_start'] = clean_sample(value['memory_at_start'])if value.get('kind') in ('gpu_oom', 'ram_pressure', 'cuda_error', 'timeout', 'cancelled','code_error', 'unknown_worker_exit', 'worker_stop_unconfirmed'):result['kind'] = value['kind']diff --git a/freevideo_engine/diagnostic_summary.py b/freevideo_engine/diagnostic_summary.pyindex 0405480..dd9b232 100644--- a/freevideo_engine/diagnostic_summary.py+++ b/freevideo_engine/diagnostic_summary.py@@ -151,8 +151,12 @@ def summary_report(report):for row in failures:kind = row.get('kind')if kind in ('gpu_oom','ram_pressure','cuda_error','timeout','cancelled','code_error','unknown_worker_exit'):- result['errors'].append(dict(kind=kind, ram_guard=_measurements(row.get('ram_guard'),- ('working_bytes','budget_bytes','available_bytes','emergency_floor_bytes'))))+ error = dict(kind=kind, ram_guard=_measurements(row.get('ram_guard'),+ ('working_bytes','budget_bytes','available_bytes','emergency_floor_bytes')))+ if isinstance(row.get('worker_exit'), dict):+ from .exit_diagnostics import clean_reading+ error['worker_exit'] = clean_reading(row['worker_exit'])+ result['errors'].append(error)# Frame names from our own source help locate failures without retaining# arbitrary exception messages (which may contain a prompt or access key).known = {p.name for p in Path(__file__).parent.glob('*.py')}diff --git a/freevideo_engine/exit_diagnostics.py b/freevideo_engine/exit_diagnostics.pynew file mode 100644index 0000000..e51349c--- /dev/null+++ b/freevideo_engine/exit_diagnostics.py@@ -0,0 +1,127 @@+"""Memory readings and a fixed-word reading of how a generation worker ended.++A worker that the system ends cannot report its own memory, so the process that+started it takes the readings: once when the request starts and once when the+exit is seen. Only numbers and fixed words leave this module, never text from+the worker, so a diagnostic report stays free of user data.+"""+from .system import windows++# Exit codes of a Windows process that the system, not the program, ended.+_SYSTEM_STATUS = {+ 0xC000012D: 'commit_limit', # STATUS_COMMITMENT_LIMIT+ 0xC0000017: 'no_memory', # STATUS_NO_MEMORY+ 0xC00000FD: 'stack_overflow', # STATUS_STACK_OVERFLOW+}+_CRASH_PREFIXES = (0xC0000000, 0x80000000)+_FIELDS = ('physical_available_bytes', 'commit_available_bytes', 'commit_limit_bytes', 'total_bytes')+++def _count(value):+ return value if type(value) is int and value >= 0 else None+++def memory_sample(pid=None):+ """Free physical memory, commit headroom and the working set of one process.++ The process is this one unless a pid is given. A value the system does not+ report is None; the function never raises.+ """+ import os+ sample = dict.fromkeys(_FIELDS)+ sample.update(process_working_set_bytes=None, process_private_commit_bytes=None)+ try:+ from .system import system_memory+ sample.update({key: _count(value) for key, value in system_memory().items() if key in _FIELDS})+ except Exception:+ pass+ pid = os.getpid() if pid is None else pid+ try:+ if windows():+ from .win32 import process_memory+ row = process_memory(pid)+ if row and 'rss_bytes' in row:+ sample['process_working_set_bytes'] = _count(row['rss_bytes'])+ sample['process_private_commit_bytes'] = _count(row['private_commit_bytes'])+ else:+ # Linux has no private commit figure: statm's first column is the whole address+ # space, tens of GB for a CUDA process, so only the resident size is recorded.+ with open('/proc/%d/statm' % pid, encoding='ascii') as stream:+ resident = stream.read().split()[1]+ sample['process_working_set_bytes'] = int(resident) * os.sysconf('SC_PAGE_SIZE')+ except Exception:+ pass+ return {key: sample[key] for key in sample if sample[key] is not None}+++def exit_reading(code, *, requested_stop=False, system=None):+ """The exit code as given, a fixed-word class and whether the system probably ended it.++ requested_stop is true when this program asked the worker to stop: its own+ stop is never counted as the system ending it.+ """+ on_windows = windows() if system is None else system == 'Windows'+ result = dict(exit_code=code if type(code) is int else None)+ if type(code) is not int:+ result.update(exit_class='unknown', suspected_system_kill=False)+ return result+ unsigned = code & 0xFFFFFFFF+ if on_windows or code > 255:+ result['exit_code_unsigned'] = unsigned+ if code == 0:+ kind, suspected = 'clean', False+ elif requested_stop:+ kind, suspected = 'stopped_by_us', False+ elif on_windows or code > 255:+ if unsigned == 0xFFFFFFFF:+ # TerminateProcess(-1): our own stop ends workers with 1, so this came from outside.+ kind, suspected = 'terminated_externally', True+ elif unsigned in _SYSTEM_STATUS:+ kind, suspected = 'system_' + _SYSTEM_STATUS[unsigned], True+ elif unsigned == 0xC000013A:+ kind, suspected = 'interrupted', False+ elif unsigned & 0xF0000000 in _CRASH_PREFIXES:+ kind, suspected = 'native_crash', False+ else:+ kind, suspected = 'error_exit', False+ elif code < 0 or code > 128:+ # Python reports a signal as -N; a shell-style status is 128 + N.+ signal = -code if code < 0 else code - 128+ if signal in (9, 15):+ kind, suspected = 'killed_by_signal', True+ elif signal in (4, 6, 7, 8, 11):+ kind, suspected = 'native_crash', False+ else:+ kind, suspected = 'signal', False+ else:+ kind, suspected = 'error_exit', False+ result.update(exit_class=kind, suspected_system_kill=suspected)+ return result+++_SAMPLE_KEYS = _FIELDS + ('process_working_set_bytes', 'process_private_commit_bytes')+_CLASSES = frozenset({'clean', 'stopped_by_us', 'terminated_externally', 'interrupted', 'native_crash',+ 'error_exit', 'killed_by_signal', 'signal', 'unknown'}+ | {'system_' + name for name in _SYSTEM_STATUS.values()})+++def clean_sample(value):+ value = value if isinstance(value, dict) else {}+ return {key: value[key] for key in _SAMPLE_KEYS if _count(value.get(key)) is not None}+++def clean_reading(value):+ """Only the numbers and fixed words of an exit reading, for any report."""+ value = value if isinstance(value, dict) else {}+ result = {}+ for key in ('exit_code', 'exit_code_unsigned', 'earlier_exit_code'):+ if type(value.get(key)) is int and -2**63 <= value[key] < 2**64:+ result[key] = value[key]+ if value.get('exit_class') in _CLASSES:+ result['exit_class'] = value['exit_class']+ if type(value.get('suspected_system_kill')) is bool:+ result['suspected_system_kill'] = value['suspected_system_kill']+ memory = clean_sample(value.get('memory'))+ if memory:+ result['memory'] = memory+ return resultdiff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.pyindex 910120c..d4fbaa1 100644--- a/freevideo_engine/generate.py+++ b/freevideo_engine/generate.py@@ -35,6 +35,9 @@ def child(command, env, descriptor, log, *, ram_budget_bytes=None, gpu=None, on_memory = ProcessMemory() if ram_budget_bytes is not None else Nonetelemetry = {}monitor = None+ from .exit_diagnostics import exit_reading, memory_sample+ # A worker that the system ends cannot report its own memory: this process reads it.+ telemetry['memory_at_start'] = memory_sample()with log.open('w', encoding='utf-8') as stream:from .resident_process import ENV, RemoteProcess, SessionRestartedmodule = command[command.index('-m')+1] if '-m' in command else None@@ -92,6 +95,7 @@ def child(command, env, descriptor, log, *, ram_budget_bytes=None, gpu=None, on_passcode = process.returncodeif code:+ telemetry['worker_exit'] = dict(exit_reading(code), memory=memory_sample())raise WorkerExit(code, log)except BaseException as error:pending_error = errordiff --git a/freevideo_engine/image_gen/failure.py b/freevideo_engine/image_gen/failure.pyindex 0035919..ff30ff5 100644--- a/freevideo_engine/image_gen/failure.py+++ b/freevideo_engine/image_gen/failure.py@@ -9,6 +9,7 @@ import timeimport tracebackfrom .. import __version__+from ..exit_diagnostics import clean_reading, clean_samplefrom ..failure_details import Redactor@@ -185,8 +186,14 @@ class Context:self.machine = {}self.plan = Noneself.pack = None+ self.start_memory = Noneself.update_request(value)+ def note_start(self):+ """Memory readings when the request begins; the worker's own are lost if it is ended."""+ from ..exit_diagnostics import memory_sample+ self.start_memory = memory_sample()+def update_request(self, value):if not isinstance(value, dict):return@@ -273,4 +280,14 @@ class Context:analysis=dict(version=__version__, hardware=hardware, geometry=geometry),summary=dict(request_seconds=self.timing.seconds()), request=dict(self.request),plan=plan, stages=stages, stage_at_failure=stage, error=details, pack=clean(pack, self.redactor),- service=dict(video_busy=bool(video_busy), worker_restarts=worker_restarts))+ service=self.service(video_busy, worker_restarts, error))++ def service(self, video_busy, worker_restarts, error):+ service = dict(video_busy=bool(video_busy), worker_restarts=worker_restarts)+ if self.start_memory:+ service['memory_at_request_start'] = clean_sample(self.start_memory)+ # Numbers and fixed words only, taken by the service when it saw the worker end.+ reading = clean_reading(getattr(error, 'exit_reading', None))+ if reading:+ service['worker_exit'] = reading+ return servicediff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.pyindex 92ebc1b..c3ac98c 100644--- a/freevideo_engine/image_gen/service.py+++ b/freevideo_engine/image_gen/service.py@@ -178,6 +178,7 @@ class Service:if action not in ('generate', 'compose'):raise ValueError('invalid_request')context = Context(action, value)+ context.note_start()with self.mutex:if self.closed:raise ValueError('closed')@@ -586,7 +587,11 @@ class Service:self.infer(session, value)except RuntimeError as second:if earlier.startswith('worker_exit (') and str(second).startswith('worker_exit'):- raise RuntimeError('%s; first try: %s' % (second, earlier[len('worker_exit '):])) from None+ combined = RuntimeError('%s; first try: %s' % (second, earlier[len('worker_exit '):]))+ reading = getattr(second, 'exit_reading', None)+ if isinstance(reading, dict):+ combined.exit_reading = dict(reading, earlier_exit_code=getattr(error, 'exit_code', None))+ raise combined from Noneraisefinally:# Keep the parent's lease until the whole owned process tree exits.@@ -658,14 +663,26 @@ class Service:return True@staticmethod- def worker_gone(session, heard):+ def worker_gone(session, heard, requested_stop=False):"""The error for a worker pipe that ended; it carries the exit code for the report."""+ error = Service.worker_gone_error(session, heard)+ code = getattr(error, 'exit_code', None)+ if code is not None:+ # The worker cannot report its memory once it is gone: read this process's view now.+ from ..exit_diagnostics import exit_reading, memory_sample+ error.exit_reading = dict(exit_reading(code, requested_stop=requested_stop), memory=memory_sample())+ return error++ @staticmethod+ def worker_gone_error(session, heard):try:code = session.process.wait(timeout=2)except subprocess.TimeoutExpired:code = Noneif code == 0 and not heard:- return WorkerIdleExit('worker_exit (exit code 0, before any answer)')+ idle = WorkerIdleExit('worker_exit (exit code 0, before any answer)')+ idle.exit_code = 0+ return idleif code is None:return RuntimeError('worker_exit')session.error_reader.join(timeout=1)@@ -676,7 +693,9 @@ class Service:message = 'worker_exit (exit code %d%s)' % (code, ', ' + kind if kind else '')# A worker that ended with an error before answering never ran the request; one# fresh worker gets it, and a second exit is reported with its own last words.- return (WorkerEarlyExit if not heard and code > 0 else RuntimeError)(message)+ error = (WorkerEarlyExit if not heard and code > 0 else RuntimeError)(message)+ error.exit_code = code+ return errordef infer(self, session, value):context = self.context or Context('generate', value)@@ -684,7 +703,7 @@ class Service:try:session.send(action='generate', **value)except OSError:- raise self.worker_gone(session, heard)+ raise self.worker_gone(session, heard, self.stop.is_set())cancelled_at = Nonedeadline = time.monotonic() + INFERENCE_TIMEOUTwhile True:@@ -702,7 +721,7 @@ class Service:except queue.Empty:continueif row is None:- raise self.worker_gone(session, heard)+ raise self.worker_gone(session, heard, self.stop.is_set())heard = Truephase = row.get('phase')if phase == 'progress':