Skip to content

Remove temporal coupling in applyRotaryPosition - #234

Closed
DePasqualeOrg wants to merge 1 commit into
ml-explore:mainfrom
DePasqualeOrg:fix-rope-application
Closed

DePasqualeOrg wants to merge 1 commit into
ml-explore:mainfrom
DePasqualeOrg:fix-rope-application

Conversation

@DePasqualeOrg

Copy link
Copy Markdown
Contributor

applyRotaryPosition(_:to:cache:), which was introduced in #178 (cc @ronaldmannak), reads cache.offset implicitly. Because cache.update(...) advances the offset, the helper's result depends on call ordering relative to cache updates, and that dependency is invisible at the call site.

44 of the 45 attention layers using this helper call it for queries and keys back to back before any cache.update, so both reads return the same value and the coupling stays hidden. Gemma 3n is the exception: its KV-sharing branch calls cache.update between the key and query RoPE calls, so queries get rotated at cache.offset + L while keys use cache.offset. That mismatch produces garbled output (see #233).

Gemma 4 had the same interleaving and worked around it with file-local helpers that corresponded to this PR's API, which is now uniformly applied.

MLX LM in Python avoids this by making offset an explicit argument to nn.RoPE. Callers that interleave cache.update_and_fetch snapshot offset = cache.offset first, making the timing visible.

Solution

Make the offset explicit in Swift too. Preserve the batch polymorphism the helper was introduced for, but move the cache read out of the helper and into a one-line snapshot at the top of each callAsFunction.

New API (additive)

In Libraries/MLXLMCommon/RoPEApplication.swift, add a RoPEOffset enum (.scalar(Int) / .array(MLXArray)), a KVCache.ropeOffset snapshot property that defensively copies the batched variant, and a new applyRotaryPosition(_:to:offset:) overload.

Deprecated shim

Mark the existing applyRotaryPosition(_:to:cache:) @available(*, deprecated) and forward it to the new overload via cache?.ropeOffset ?? .scalar(0), so downstream callers get a warning, not a compile error, during migration.

Call site example

Before:

queries = applyRotaryPosition(rope, to: queries, cache: cache)
keys    = applyRotaryPosition(rope, to: keys,    cache: cache)

After:

let ropeOffset = cache?.ropeOffset ?? .scalar(0)
...
queries = applyRotaryPosition(rope, to: queries, offset: ropeOffset)
keys    = applyRotaryPosition(rope, to: keys,    offset: ropeOffset)

The snapshot goes at the top of callAsFunction, or at the narrowest scope containing the RoPE calls when branches or conditionals require it (Gemma 3n, GPTOSS, and AfMoE).

@ronaldmannak

Copy link
Copy Markdown
Contributor

Thanks @DePasqualeOrg
This was a real bug and this PR simplifies Gemma4Text as well, which is great.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very interesting -- thank you for the fix!

Comment on lines +46 to +50
if let batched = self as? BatchPositionedKVCache {
return .array(batched.batchOffset + 0)
} else {
return .scalar(offset)
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if it matters, but see also:

I don't know if batchOffset[.ellipsis] is more idiomatic or cheaper. The comment explains what it is doing well, enough.

@DePasqualeOrg
DePasqualeOrg deleted the fix-rope-application branch May 10, 2026 07:00
@davidkoski davidkoski mentioned this pull request May 10, 2026
4 tasks done
davidtai added a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
ChunkedKVCache.maybeTrimFront() compared the buffer length with the
chunk size and kept the last chunkSize buffer rows. The buffer grows in
steps, so its last rows can be unused. The cache then kept fewer valid
tokens than mlx-lm, or moved startPosition past the offset. The trim now
counts the valid tokens (offset - startPosition) and keeps the newest
chunkSize of them, as mlx-lm cache.py does.

Fixes ml-explore#234

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

3 participants