YuE2 on Apple Silicon: pinned torch==2.10.0 silently corrupts causal prefill attention in BF16 (MPS)
Summary
yue2-infer 0.1.6 pins torch==2.10.0, and its code explicitly supports MPS (device="auto" selects it; sdpa, nar.attention and sampling all have MPS branches). On MPS, PyTorch ≤ 2.12.1 has a silent bug in scaled_dot_product_attention(..., is_causal=True) for float16/bfloat16: the causal mask is applied per block of four query positions, so a query can attend up to three future keys (pytorch/pytorch#195910, fixed in PyTorch 2.13.0). No error, warning or NaN is raised.
YuE2 runs its AR/NAR model in BF16 and reaches that kernel in two places:
modeling_yue2.sdpa(..., is_causal=True)for every multi-token prefill — the style/lyrics prompt before ABC planning and the prompt + score prefix before semantic generation.nar.attention(..., causal=True)for the first 256-row block of the acoustic stage's AR-prefix prefill (later blocks already pass an explicit mask, so they are correct).
Single-token decode is unaffected (query length 1, is_causal=False), as is FP32.
Environment
- Apple M5 Max, 128 GB, macOS 27.0 (26A428)
- Python 3.12.11,
yue2-infer0.1.6 installed frommain@ 88da114,torch2.10.0 (as pinned) - Weights:
m-a-p/YuE2-3B,m-a-p/YuE2-Vae
Reproduction (standalone, torch only)
repro_mps_causal.py (below) uses YuE2's AR attention shapes — 16 query heads, 8 KV heads, head_dim 128 — and mirrors modeling_yue2.sdpa:
torch 2.10.0 | macOS 27.0 | arm64
relative error vs CPU float32 is_causal
length mps bf16 is_causal mps bf16 explicit tril mps fp32 is_causal
16 0.003 0.003 0.000
17 0.572 0.003 0.000
128 0.452 0.003 0.000
705 0.384 0.003 0.000
3113 0.322 0.003 0.000
torch.bfloat16 rows 0-5 mean visible key index: [1.5, 1.5, 1.5, 1.5, 3.5, 3.5] (causal: [0.0, 0.5, 1.0, 1.5, 2.0, 2.5])
torch.float32 rows 0-5 mean visible key index: [0.0, 0.5, 1.0, 1.5, 2.0, 2.5] (causal: [0.0, 0.5, 1.0, 1.5, 2.0, 2.5])Lengths ≤ 16 are correct; from 17 on, query rows 0–3 see keys 0–3, rows 4–7 see keys 0–7, and so on. The same attention with an explicit boolean lower-triangular mask is correct in BF16.
Effect on the real model
Using the examples/song.json request (City Lights, seed 831001) and its saved tokens:
- A teacher-forced one-shot BF16 MPS prefill over the 705-token prefix plus 1,000 semantic tokens diverged from a CPU FP32 reference: mean per-position KL of 0.035–0.21 across 100-token windows.
- Replaying the same tokens through the token-by-token decode path (the one that uses
StaticKVCache) matched CPU FP32 closely: KL ≈ 0.002. - I haven't measured how much this changes finished songs. I re-synthesized one song's saved tokens in FP32 and in BF16, and the two came out with nearly identical loudness and spectrum. So the audible effect may be modest, but prompt conditioning is currently computed through a kernel that leaks future tokens.
Suggested fix
Either raise the torch pin to ≥ 2.13.0 (your call given the CUDA reproducibility pins), or keep 2.10.0 and pass an explicit mask on MPS half precision. mps-causal-mask.patch (below) does the latter, in 16 lines. It adds mps_half() to modeling_yue2.py; sdpa then swaps is_causal=True for a tril bool mask, and nar.attention builds its mask for the first block too. CUDA/CPU paths are unchanged.
With the patch on macOS:
- The repo test suite passes (
172 passed, 11 skipped). - Kernel error falls from 0.32–0.57 to 0.003 (ordinary BF16 rounding).
- Full
yue2 generateruns complete. The patched run ofexamples/song.jsonproduced 79.4 s of audio in 367 s end to end, with no truncation.
Related Mac notes (smaller)
examples/generate.pyhardcodesdevice="cuda".skills/yue2-music/scripts/run_yue2.pyandtranscribe.pydefault to--device cuda.autowould match the package default.
"""YuE2 on Apple Silicon: half-precision is_causal attention is wrong under the pinned torch==2.10.0.
Standalone (needs only torch). Run on an Apple Silicon Mac inside the yue2-infer environment:
python repro_mps_causal.py
"""
import platform
import torch
import torch.nn.functional as F
assert torch.backends.mps.is_available(), "needs an Apple Silicon GPU"
print(f"torch {torch.__version__} | macOS {platform.mac_ver()[0]} | {platform.machine()}")
torch.manual_seed(0)
def upstream_sdpa(query, key, value, *, attn_mask=None, is_causal=False):
"""Same as yue2-infer 0.1.6 modeling_yue2.sdpa (MPS GQA fallback, then native SDPA)."""
if query.shape[1] != key.shape[1] and query.device.type == "mps":
groups = query.shape[1] // key.shape[1]
key, value = key.repeat_interleave(groups, dim=1), value.repeat_interleave(groups, dim=1)
return F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, is_causal=is_causal,
enable_gqa=query.shape[1] != key.shape[1])
def rel_err(out, ref):
return ((out.float().cpu() - ref).norm() / ref.norm()).item()
# 1. YuE2's AR attention shapes (16 query heads, 8 KV heads, head_dim 128) at prompt-prefill lengths.
print("\nrelative error vs CPU float32 is_causal")
print(f"{'length':>7} {'mps bf16 is_causal':>19} {'mps bf16 explicit tril':>23} {'mps fp32 is_causal':>19}")
for length in (16, 17, 128, 705, 3113):
q, k, v = torch.randn(1, 16, length, 128), torch.randn(1, 8, length, 128), torch.randn(1, 8, length, 128)
ref = upstream_sdpa(q, k, v, is_causal=True)
half = [t.to("mps", torch.bfloat16) for t in (q, k, v)]
full = [t.to("mps", torch.float32) for t in (q, k, v)]
mask = torch.ones(length, length, dtype=torch.bool, device="mps").tril()
print(f"{length:>7} {rel_err(upstream_sdpa(*half, is_causal=True), ref):>19.3f} "
f"{rel_err(upstream_sdpa(*half, attn_mask=mask), ref):>23.3f} "
f"{rel_err(upstream_sdpa(*full, is_causal=True), ref):>19.3f}")
# 2. What query 0 can see. Uniform attention (q=0) over values equal to their key index:
# the output is the mean index of visible keys, 0.0 when correctly causal.
L = 32
q = torch.zeros(1, 1, L, 64)
k = torch.randn(1, 1, L, 64)
v = torch.arange(L, dtype=torch.float32).view(1, 1, L, 1).repeat(1, 1, 1, 64)
for dtype in (torch.bfloat16, torch.float32):
out = F.scaled_dot_product_attention(*(t.to("mps", dtype) for t in (q, k, v)), is_causal=True)
seen = [round(out[0, 0, i, 0].float().item(), 2) for i in range(6)]
print(f"{str(dtype):>15} rows 0-5 mean visible key index: {seen} (causal: [0.0, 0.5, 1.0, 1.5, 2.0, 2.5])")diff --git a/src/yue2/modeling_yue2.py b/src/yue2/modeling_yue2.py
index 9e2b992..2e59f0a 100644
--- a/src/yue2/modeling_yue2.py
+++ b/src/yue2/modeling_yue2.py
@@ -17,6 +17,15 @@ from transformers.cache_utils import DynamicCache
from transformers.modeling_outputs import CausalLMOutputWithPast
+def mps_half(tensor):
+ """True where torch<2.13's MPS is_causal SDPA leaks future tokens (pytorch/pytorch#195910).
+
+ In FP16/BF16 it masks per block of four queries. An explicit lower-triangular boolean
+ mask is correct, so causal callers pass one instead on these tensors.
+ """
+ return tensor.device.type == "mps" and tensor.dtype in (torch.float16, torch.bfloat16)
+
+
def sdpa(query, key, value, *, attn_mask=None, is_causal=False):
"""Use native grouped-query attention, including a portable MPS fallback."""
grouped = query.shape[1] != key.shape[1]
@@ -26,6 +35,9 @@ def sdpa(query, key, value, *, attn_mask=None, is_causal=False):
key = key.repeat_interleave(groups, dim=1)
value = value.repeat_interleave(groups, dim=1)
grouped = False
+ if is_causal and mps_half(query):
+ attn_mask = torch.ones(query.shape[-2], key.shape[-2], dtype=torch.bool, device=query.device).tril()
+ is_causal = False
return F.scaled_dot_product_attention(
query, key, value, attn_mask=attn_mask, is_causal=is_causal,
enable_gqa=grouped,
diff --git a/src/yue2/nar.py b/src/yue2/nar.py
index cb0bccc..630d1f7 100644
--- a/src/yue2/nar.py
+++ b/src/yue2/nar.py
@@ -14,6 +14,7 @@ from typing import Callable, Sequence
import torch
import torch.nn.functional as F
+from .modeling_yue2 import mps_half
from .protocol import CODEC_OFFSET, CODEC_SIZE, CONTEXT, MUSIC_END, chunk_ranges
@@ -88,13 +89,14 @@ def attention(q, k, v, *, causal=False, backend="sdpa", query_chunk_size=None):
used_value = value[..., :end, :] if causal else value
# is_causal on a rectangular Q/K uses an upper-left triangle, so a
# later query block needs its absolute query positions explicitly.
+ # MPS half precision also needs it for the first block; see mps_half.
mask = None
- if causal and start:
+ if causal and (start or mps_half(q)):
mask = (torch.arange(end, device=q.device)[None, :] <=
torch.arange(start, end, device=q.device)[:, None])
outputs.append(F.scaled_dot_product_attention(
query[..., start:end, :], used_key, used_value,
- attn_mask=mask, is_causal=causal and start == 0, enable_gqa=grouped,
+ attn_mask=mask, is_causal=causal and mask is None, enable_gqa=grouped,
))
return torch.cat(outputs, dim=-2)[0].transpose(0, 1)
Source: multimodal-art-projection/YuE