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.

Check MLX image attention against Torch once and report why it fell back

Bowen Xueff735cd047fb
diff --git a/freevideo_engine/image_gen/failure.py b/freevideo_engine/image_gen/failure.py
index c2b738e..9055e01 100644
--- a/freevideo_engine/image_gen/failure.py
+++ b/freevideo_engine/image_gen/failure.py
@@ -287,7 +287,10 @@ class Context:
hardware = {key: clean(value, self.redactor) for key, value in hardware.items()}
geometry = {key: self.request[key] for key in ('width', 'height') if key in self.request}
plan = safe_plan(row.get('plan') if row.get('plan') is not None else self.plan, self.redactor)
- return dict(schema='freevideo.image-report', schema_version=1,
+ # Macs only: which attention kernel ran and why it left MLX (mlx_attention.summary).
+ attention = row.get('attention')
+ extra = dict(attention=clean(attention, self.redactor)) if isinstance(attention, dict) else {}
+ return dict(schema='freevideo.image-report', schema_version=1, **extra,
created_at=datetime.now(timezone.utc).isoformat(), kind=self.kind,
analysis=dict(version=__version__, hardware=hardware, geometry=geometry),
summary=dict(request_seconds=self.timing.seconds()), request=dict(self.request),
diff --git a/freevideo_engine/image_gen/mlx_attention.py b/freevideo_engine/image_gen/mlx_attention.py
index ad4573d..31a2fed 100644
--- a/freevideo_engine/image_gen/mlx_attention.py
+++ b/freevideo_engine/image_gen/mlx_attention.py
@@ -10,6 +10,12 @@ import torch
from ..backends.mps_mlx_attention import to_mlx_many, to_torch
+# The first MLX call with and without a mask is compared with the fallback on this many
+# queries; each query attends independently, so the slice is exact. Measured MLX-to-Torch
+# differences on M-series Macs were 0.004-0.0098; a wrong kernel is off by far more.
+CHECK_QUERIES = 64
+TOLERANCE = .05
+
def available():
try:
@@ -22,16 +28,26 @@ def available():
def routed(fallback, *, min_queries=256):
"""``attention`` for image-sized calls; short text segments, where the hand-over costs more, keep ``fallback``.
- A call MLX cannot run goes to ``fallback`` instead of failing the picture, and so does
- every later call of the process.
+ A call MLX cannot run, or whose first result disagrees with ``fallback``, goes to
+ ``fallback`` instead of failing or spoiling the picture, and so does every later call of
+ the process. ``failed`` keeps why, for the image report.
"""
failed = []
+ checked = set()
def run(query, key, value, attn_mask=None):
if failed or query.shape[1] < min_queries:
return fallback(query, key, value, attn_mask=attn_mask)
try:
- return attention(query, key, value, attn_mask=attn_mask)
+ out = attention(query, key, value, attn_mask=attn_mask)
+ kind = attn_mask is not None
+ if kind not in checked:
+ reason = differs(query, key, value, attn_mask, out, fallback)
+ checked.add(kind)
+ if reason:
+ failed.append(reason)
+ return fallback(query, key, value, attn_mask=attn_mask)
+ return out
except Exception as error:
failed.append(f'{type(error).__name__}: {error}'[:300])
return fallback(query, key, value, attn_mask=attn_mask)
@@ -39,6 +55,31 @@ def routed(fallback, *, min_queries=256):
return run
+def differs(query, key, value, attn_mask, out, fallback):
+ """Why ``out`` cannot be trusted, or None when its first queries match ``fallback``."""
+ count = min(CHECK_QUERIES, query.shape[1])
+ mask = attn_mask
+ if mask is not None and mask.dim() >= 2 and mask.shape[-2] == query.shape[1]:
+ mask = mask[..., :count, :]
+ reference = fallback(query[:, :count], key, value, attn_mask=mask).float()
+ got = out[:, :count].float()
+ if not torch.isfinite(got).all():
+ # Non-finite values the fallback also gives come from the inputs, not from MLX.
+ return 'mismatch: non-finite output' if torch.isfinite(reference).all() else None
+ difference = (got - reference).abs().max().item()
+ if difference > TOLERANCE * max(1., reference.abs().max().item()):
+ return 'mismatch: max difference %.3g over %d queries' % (difference, count)
+ return None
+
+
+def summary(function):
+ """What the image report says about attention: None unless ``function`` came from routed()."""
+ failed = getattr(function, 'failed', None)
+ if failed is None:
+ return None
+ return dict(kernel='torch' if failed else 'mlx', **({'fallback_reason': failed[0]} if failed else {}))
+
+
def attention(query, key, value, attn_mask=None):
"""Same contract as ``qwen_dit.attention``: (batch, sequence, heads, dim), boolean mask or None."""
import mlx.core as mx
diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py
index 1f70c92..1b4d5cd 100644
--- a/freevideo_engine/image_gen/service.py
+++ b/freevideo_engine/image_gen/service.py
@@ -1089,6 +1089,8 @@ class Service:
raise RuntimeError('worker_exit')
result = dict(phase='complete', file='freevideo-image/' + path.name,
seconds=seconds, plan=row.get('plan'))
+ if isinstance(row.get('attention'), dict):
+ result['attention'] = row['attention']
with self.mutex:
if 'fitted' in self.state:
result['fitted'] = self.state['fitted']
diff --git a/freevideo_engine/image_gen/worker.py b/freevideo_engine/image_gen/worker.py
index f45022d..469acf6 100644
--- a/freevideo_engine/image_gen/worker.py
+++ b/freevideo_engine/image_gen/worker.py
@@ -152,6 +152,11 @@ def serve(pack_dir, *, device='cuda', idle_seconds=45., stream=None, output=None
if back_check is not None:
plan = dict(plan or {}, back_check=back_check)
result = dict(phase='result', path=value['path'], seconds=time.monotonic() - started, plan=plan)
+ try:
+ result.update(attention_report(runner, context.redactor))
+ except Exception:
+ # Diagnostics must not turn a saved picture into an error.
+ pass
except Exception as error:
code = classify_exception(error, stage=context.timing.stage, cancelled=inbox.cancel.is_set())
plan = None
@@ -165,6 +170,10 @@ def serve(pack_dir, *, device='cuda', idle_seconds=45., stream=None, output=None
result = dict(phase='error', code=code, stage=context.timing.stage, reloaded=reload,
seconds=context.timing.seconds(), stages=context.timing.snapshot(), plan=plan,
error=exception_details(error, context.redactor, code))
+ try:
+ result.update(attention_report(runner, context.redactor))
+ except Exception:
+ pass
finally:
if result is not None and result.get('reloaded'):
# A failure inside a layer pass leaves the weights streamer part-way through it and the
@@ -192,6 +201,19 @@ def serve(pack_dir, *, device='cuda', idle_seconds=45., stream=None, output=None
runner.close()
+def attention_report(runner, redactor=None):
+ """{'attention': ...} on Macs where MLX attention was installed (why it fell back, if it did); {} elsewhere."""
+ if runner is None:
+ return {}
+ from . import mlx_attention, qwen_dit
+ value = mlx_attention.summary(qwen_dit.attention)
+ if value is None:
+ return {}
+ if redactor is not None and 'fallback_reason' in value:
+ value['fallback_reason'] = redactor.text(value['fallback_reason'])[:300]
+ return dict(attention=value)
+
+
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('pack_dir', type=Path)