Skip to content

Fix threadgroup memory race in fused KL and JS Metal kernels (fixes #1700) - #1719

Closed
AxelNoun wants to merge 5 commits into
ml-explore:mainfrom
AxelNoun:fix/metal-kl-js-race
Closed

AxelNoun wants to merge 5 commits into
ml-explore:mainfrom
AxelNoun:fix/metal-kl-js-race

Conversation

@AxelNoun

Copy link
Copy Markdown
Contributor

Recreates #1714, which was closed automatically on 12 Aug when the fork
hosting its branch was detached during an account cleanup on my side —
my mistake, apologies for the noise.

The head commit is byte-identical to the original PR (ee4fae4ec8).
All prior context and discussion: #1714


Problem

#1700 reports that during DWQ on models above roughly 1B parameters, the
backward pass of the fused Metal KL divergence kernel intermittently
saturates to -3.39e38 (about -FLT_MAX) and corrupts training on the first
step. The failure is nondeterministic and load dependent; forcing the
reference KL path avoids it entirely.

Root cause

The four fused kernels in mlx_lm/tuner/losses.py reduce across simdgroups
through a single threadgroup buffer, first for the row max, then for the
sum of exponentials. After the barrier, every thread reads the maxes back
from shared, and lane 0 of each simdgroup then writes its partial sum
into the same slots. There is no barrier between those reads and writes.
Simdgroups make independent progress, so a fast group can overwrite a slot
before a slow group has read it. The affected thread folds a partial sum
into what it believes is a max, the row logsumexp collapses, and
exp(vals - lse) saturates in the gradient write. The forward pass shares
the hazard but reduces to a single scalar per row, which is why the
corruption surfaces in the backward first.

Two related issues in the same kernels are fixed alongside the race.
Several barriers separating accesses to shared used
mem_flags::mem_none, which orders execution but does not fence
threadgroup memory. And the tail block feeds a -1e30 sentinel into
metal::fast::exp, outside the documented input range of the fast math
functions; that did not appear to be the trigger here (the forward pass
performs the same out of range call on every row and computes correctly),
but those sites are now guarded as hardening in a separate commit that
can be dropped if preferred.

Additional finding: deterministic JS softplus overflow

While validating the race fix on the diagnostic suite, a second, fully
deterministic bug showed up in the JS kernels only. They evaluated
log(1 + exp(logq - logp)) directly. At logit scale 20 the log-ratio
reaches several hundred, exp overflows to inf, and the reduction yields
-inf or NaN (including via 0 * inf when a probability underflows). That
matched the residual scale-20 saturation that remained after the barrier
fix alone: same on every retry of identical inputs, independent of
scheduling. The JS softplus sites now use the standard stable form
(mathematically identical for in-range inputs, finite where the naive
form overflowed). This is a separate commit from the race fix and from
the fast-math hardening; unlike the hardening, it intentionally changes
outputs exactly on the overflowing inputs.

Changes

  1. Add a threadgroup_barrier(mem_flags::mem_threadgroup) between the max
    read back and the sum exchange, in all four kernels.
  2. Promote the mem_none barriers guarding shared to mem_threadgroup.
  3. Hardening (separate commit): bounds guard on tail block accumulation,
    zero guard on the rescale factor below the f32 underflow range, and
    clamping of the exp arguments in the gradient writes to their
    mathematical range. Exact no ops for in range inputs.
  4. Stable softplus in the JS kernels (separate commit): replaces the
    naive log(1+exp(x)) that overflowed at large log-ratios.
  5. Regression tests: large non-block-aligned vocabulary determinism for
    KL and JS vjp, plus a JS scale-20 softplus case that asserts finite
    outputs and parity with the CPU reference path.

Validation

Measured on a GitHub hosted macos-15 arm64 runner (virtualized Apple
M series, Metal available), mlx 0.32.0, mlx-lm 0.31.3.

Determinism, repeated backward on identical inputs, worst KL
configuration (float32, scale 6, shape (512, 151936)):
before: 50/50 nondeterministic, 0 saturated
after: 0/50 nondeterministic, 0 saturated

Pipelined stress (bf16, 8 concurrent backwards of shape (256, 151936)):
before: 3/400 nondeterministic
after: 0/400 nondeterministic

Parity with the reference path after the fix (max abs difference on the
gradient): float32 7.4e-6, bfloat16 2.0e-3 across vocabularies of 17,
4095, 4097, 100003 and 151936. Finite cells are small but nonzero, so
the fused Metal path is the one under test rather than a silent fallback
to the reference implementation.

No measurable performance regression on the same runner class for the
(512, 151936) bf16 backward; run to run variance on virtualized hosts
dominates any barrier cost on the once-per-row reduction path.

I do not have access to Apple hardware beyond CI runners, so I could
not run the DWQ recipe end to end. The reporter of #1700 offered to
test candidate patches on the M5 Max where the failure reproduces;
exact commands are posted in the issue. The new regression tests in
tests/test_losses.py will also exercise the fix on the project CI.

The inter simdgroup reduction reuses the same shared buffer for the max
exchange and the sum exchange with no barrier between the read back of
the maxes and the write of the partial sums. A fast simdgroup could
overwrite a slot before a slow one had read it, collapsing the row
logsumexp and saturating exp(vals - lse) in the gradient. Also promote
the mem_none barriers guarding shared to mem_threadgroup.

Fixes ml-explore#1700
Guard tail block accumulation, zero the rescale factor below the f32
underflow range, and clamp exp arguments in the gradient writes to
their mathematical range. All changes are exact no ops for in range
inputs; they only remove calls to metal::fast functions outside their
documented input domain.
Replace log(1+exp(x)) with a stable softplus so extreme logit scales
do not overflow float32 in the JS forward and backward reductions.
Guard the deterministic log(1+exp) overflow fix with a finite-output and
reference-parity check at logit scale 20, using tolerances from CI.
@zcbenz

zcbenz commented Aug 21, 2026

Copy link
Copy Markdown
Member

Thanks for the PR but at the moment the number of PRs is way beyond our capacity to review so I'm closing the non-essential ones so we can actually work on this repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants