Skip to content

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.

Retry a Metal command buffer failure once on Mac

Bowen Xue0c3d3256830d
diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py
index d52a373..b782693 100644
--- a/freevideo_engine/failure_details.py
+++ b/freevideo_engine/failure_details.py
@@ -801,6 +801,73 @@ WRAPPING_ERROR = re.compile(r'(?:subprocess\.)?CalledProcessError\b')
ANSI = re.compile(r'\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\))')
+PLAIN_FIELD = re.compile(r'[^\w .+()/-]')
+
+
+def _plain(value, limit=40):
+ return PLAIN_FIELD.sub('', '' if value is None else str(value))[:limit].strip()
+
+
+def _mac_run(report, run, redactor):
+ """The machine, size, length and settings of a Mac failure, and whether its stage was retried.
+
+ One line of fixed fields; typed text is not part of it. The retried error is redacted whole
+ before it is shortened: a prompt or credential is only recognized in full.
+ """
+ hardware = report.get('runtime_hardware')
+ if report.get('device_backend') != 'mps' or not isinstance(hardware, dict):
+ return ''
+ ram = hardware.get('ram_total')
+ machine = [_plain(hardware.get('gpu_name')) or 'Apple GPU']
+ if type(ram) is int and ram > 0:
+ machine.append('%d GiB' % round(ram / 2**30))
+ software = report.get('runtime_software')
+ if isinstance(software, dict):
+ for key, label in (('macos', 'macOS'), ('mlx', 'MLX'), ('torch', 'torch')):
+ if software.get(key):
+ machine.append('%s %s' % (label, _plain(software[key], 20)))
+ parts = [', '.join(machine)]
+ canvas, plan = report.get('geometry'), report.get('sampling_plan')
+ if isinstance(canvas, dict) and type(canvas.get('width')) is int and type(canvas.get('height')) is int:
+ size = '%dx%d' % (canvas['width'], canvas['height'])
+ if isinstance(canvas.get('seconds'), (int, float)):
+ size += ' %.1f s' % canvas['seconds']
+ first = plan.get('first') if isinstance(plan, dict) and plan.get('enabled') is True else None
+ if isinstance(first, dict) and type(first.get('width')) is int and type(first.get('height')) is int:
+ size += ' (first pass %dx%d)' % (first['width'], first['height'])
+ parts.append(size)
+ if isinstance(plan, dict) and type(plan.get('base_steps')) is int:
+ two = plan.get('enabled') is True and type(plan.get('refine_steps')) is int
+ parts.append('two-pass %d+%d' % (plan['base_steps'], plan['refine_steps']) if two else '%d steps' % plan['base_steps'])
+ engine = (report.get('profile') or {}).get('engine') if isinstance(report.get('profile'), dict) else None
+ if isinstance(engine, dict) and engine.get('task'):
+ parts.append(_plain(engine['task']))
+ if report.get('step_cache'):
+ parts.append('step cache ' + _plain(report['step_cache']))
+ metrics = _read(Path(run) / 'video.engine.json', 512*1024)
+ try:
+ metrics = json.loads(metrics)
+ except ValueError:
+ metrics = {}
+ retries = metrics.get('memory_retries') if isinstance(metrics, dict) else None
+ row = retries[0] if isinstance(retries, list) and retries and isinstance(retries[0], dict) else None
+ if row is None:
+ parts.append('not retried')
+ else:
+ stages = metrics.get('stages') if isinstance(metrics.get('stages'), dict) else {}
+ key = row.get('phase')
+ joined = stages.get(key)
+ if (key == 'first-pass' and isinstance(joined, dict) and joined.get('joined_sampling') is True
+ and joined.get('success') is False and joined.get('sampling_phase') in ('upscale', 'refinement')):
+ # A joined child failed in a later pass; the retry ran that pass on its own.
+ key = joined['sampling_phase']
+ stage = stages.get(key)
+ passed = isinstance(stage, dict) and stage.get('success') is True
+ error = (redactor.text(str(row.get('error_message') or '')).strip().splitlines() or [''])[0][:160].replace('"', "'")
+ parts.append('%s retried once after "%s"; the retry %s' % (_plain(key, 20), error, 'passed' if passed else 'failed too'))
+ return 'Run: ' + '; '.join(parts)
+
+
def generation_failure(run, exit_code=None, *, repair=None):
"""Surface the cause, including a child traceback, even without a report.
@@ -892,6 +959,9 @@ def generation_failure(run, exit_code=None, *, repair=None):
lines.insert(1, 'Cause: ' + causes[-1][:300])
if len(lines) == 1:
lines.append('The worker ended without a readable error report.')
+ summary = _mac_run(report, run, redactor)
+ if summary:
+ lines.insert(2 if promoted else 1, summary)
lines.append('\nRetained outputs: ' + str(run))
# The table failure can be in a retained child log rather than the report.
# Keep its numeric metadata ahead of technical output for all interactive callers.
diff --git a/freevideo_engine/macos_generate.py b/freevideo_engine/macos_generate.py
index ccd5ebf..85dd616 100644
--- a/freevideo_engine/macos_generate.py
+++ b/freevideo_engine/macos_generate.py
@@ -143,7 +143,7 @@ def run(args):
resource = policy(args)
hardware = inventory()['hardware']
resource['hardware'] = hardware
- report.update(runtime_hardware=hardware, runtime_code=code_identity())
+ report.update(runtime_hardware=hardware, runtime_code=code_identity(), runtime_software=runtime_software())
print(json.dumps(dict(event='compute_device', backend='MPS', name=hardware['gpu_name'],
memory_model='unified', ram_total_bytes=hardware['ram_total'])), flush=True)
from .continuation import validate_frames, summary as continuation_summary
@@ -342,7 +342,7 @@ def run(args):
if hide_tail_frames:
engine['hide_tail_frames'] = hide_tail_frames
if getattr(args, 'step_cache', None) == 'easycache-av':
- engine['step_cache'] = args.step_cache
+ engine['step_cache'] = report['step_cache'] = args.step_cache
if output_size:
engine['output_size'] = [output_size['width'], output_size['height']]
if preview:
@@ -372,6 +372,17 @@ def run(args):
write_debug(output)
+def runtime_software():
+ """The system and library versions a Metal failure depends on."""
+ versions = dict(macos=platform.mac_ver()[0])
+ for name in ('mlx', 'torch'):
+ try:
+ versions[name] = importlib.metadata.version(name)
+ except importlib.metadata.PackageNotFoundError:
+ versions[name] = None
+ return versions
+
+
def worker(value):
from .macos_bootstrap import require_native
require_native()
diff --git a/freevideo_engine/macos_stages.py b/freevideo_engine/macos_stages.py
index 8f5dffc..25e7763 100644
--- a/freevideo_engine/macos_stages.py
+++ b/freevideo_engine/macos_stages.py
@@ -39,11 +39,15 @@ def read_receipt(receipt):
return observed
+METAL_FAILURE = '[METAL] Command buffer execution failed'
+
+
def memory_exhausted(stage, observed):
- """A sampling pass that stopped because MPS reached its allocator limit."""
+ """A sampling pass that stopped because MPS reached its allocator limit or Metal failed a command buffer."""
# The physical RAM floor protects the whole machine, and the outer guard also ends the request.
+ message = str(observed.get('error_message', ''))
return (stage in ('first-pass', 'refinement') and observed.get('success') is False
- and 'MPS backend out of memory' in str(observed.get('error_message', '')))
+ and ('MPS backend out of memory' in message or METAL_FAILURE in message))
def joined_admission(engine, value):
@@ -195,7 +199,8 @@ def run(value):
if retry or not memory_exhausted(stage, failed):
raise
# Unified memory taken by other applications can leave a
- # sampling pass short of its plan. Retry it once in a fresh
+ # sampling pass short of its plan, and Metal can fail a command
+ # buffer without naming memory. Retry it once in a fresh
# process with the smallest grouped-projection partitions.
# Keeping a saved first pass avoids changing its latents
# with those new partitions.
@@ -210,12 +215,14 @@ def run(value):
and len(rows[0]['step_seconds']) == sampling['base_steps']):
retain_joined_progress(result, failed)
retained_joined = failed
+ metal = METAL_FAILURE in str(failed.get('error_message', ''))
result.setdefault('memory_retries', []).append(dict(phase=stage,
+ kind='metal_command_buffer' if metal else 'unified_memory',
error_type=failed.get('error_type'), error_message=failed.get('error_message'),
compute=failed.get('compute'), process_seconds=time.monotonic() - tick))
print(json.dumps(dict(event='resource_retry', retry=dict(
failed_phase='refinement' if stage == 'refinement' or retained_joined else 'sampling',
- kind='unified_memory', attempt=2, max_attempts=2,
+ kind='metal_command_buffer' if metal else 'unified_memory', attempt=2, max_attempts=2,
reuse_first_pass=stage == 'refinement' or bool(retained_joined)))), flush=True)
if retained_joined:
break
diff --git a/web/failure_issue.js b/web/failure_issue.js
index 26a7a0d..88a3b7b 100644
--- a/web/failure_issue.js
+++ b/web/failure_issue.js
@@ -23,13 +23,20 @@ export function failureStage(report) {
}
const TAIL = 1500, TAIL_HEAD = 500;
+// The engine's one-line summary of a Mac run (machine, size, length, settings, retry). It travels as its
+// own field, so a long traceback cannot cut it and it does not take room from the tail.
+const RUN_LINE = /^Run: .*(?:\r?\n|$)/m;
// The engine's failure text, not ComfyUI's traceback after it: details end with
// the bridge's own frames. The error and stage lead that text and the child
// log's error ends it, so a long one gives up its middle.
-function cause(report) {
+function failureText(report) {
const message = String(report?.message || '');
- const text = message.includes('\n') ? message : String(report?.details || '');
+ return message.includes('\n') ? message : String(report?.details || '');
+}
+
+function cause(report) {
+ const text = failureText(report).replace(RUN_LINE, '');
if (text.length <= TAIL) return text;
return text.slice(0, TAIL_HEAD) + '\n...\n' + text.slice(-(TAIL - TAIL_HEAD - 5));
}
@@ -44,9 +51,10 @@ export function failureIssue(report, kind, {lora = false, t = en => en} = {}) {
`Stage: ${stage ? stage[0] : report?.stage || 'unknown'}`, `Error: ${first.trim().slice(0, 300)}`,
`Kind: ${kind || 'unknown'}`].join('\n');
const types = (report?.nodes || []).map(node => node.type).filter(Boolean);
+ const run = RUN_LINE.exec(failureText(report))?.[0].trim().slice(5, 505);
const summary = JSON.stringify({kind: kind || 'unknown', stage: report?.stage, exception_type: report?.exception_type,
known_error: report?.known_error, nodes: types, settings: report?.settings, progress: report?.progress,
- tail: cause(report)});
+ run, tail: cause(report)});
const title = lora ? t('[Feedback] LoRA compatibility misjudged', '[Feedback] LoRA 兼容判断有误')
: t('[Feedback] Generation did not finish', '[Feedback] 生成未完成') + (stage ? t(`: ${stage[0]}`, `:${stage[1]}`) : '');
return {title, text, summary};