Skip to content

Batched LLM inference part 1 - consolidating RoPE calls - #178

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
ronaldmannak:claude/split-large-pr-T996Z
Apr 3, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
ronaldmannak:claude/split-large-pr-T996Z

Conversation

@ronaldmannak

Copy link
Copy Markdown
Contributor

Proposed changes

As discussed in #150, this PR is the first PR continuous batching feature.

  • Introduce applyRotaryPosition(_:to:cache:) helper in MLXLMCommon that replaces the repeated conditional offset pattern (if let cache { rope(x, offset: cache.offset) } else { rope(x, offset: 0) }) with a single call site
  • Migrate all 45 model attention layers to use the unified helper, removing ~160 lines of boilerplate
  • Standardize rope property types to RoPELayer (OffsetLayer & ArrayOffsetLayer), removing ad-hoc wrapper enums and protocols

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

claude added 2 commits April 3, 2026 00:02
Replace verbose conditional rope offset patterns across 45 model files
with a single `applyRotaryPosition(rope, to:, cache:)` helper function.

This is a pure refactoring with no behavior change for single-request
inference. The helper centralizes the `cache?.offset ?? 0` pattern,
reducing boilerplate and making models ready for future batch-aware
RoPE dispatch.

Key changes:
- Add RoPEApplication.swift with the applyRotaryPosition helper
- Migrate 45 model attention layers to use the unified helper
- SmolLM3: Replace custom SmolLM3PositionEmbedding protocol with
  standard RoPELayer; add ArrayOffsetLayer conformance to NoPE
- Internlm2: Add OffsetLayer/ArrayOffsetLayer conformance to
  DynamicNTKScalingRoPE; extract computeBase helper
- NanoChat: Wrap MLXFast.RoPE in NanoChatRoPE class conforming to
  RoPELayer protocols
- Phi3: Remove PositionalEncoding enum; use RoPELayer directly
- GPTOSS: Unify quantized and regular rope paths
- Gemma3nText: Change rope type from OffsetLayer to RoPELayer

https://claude.ai/code/session_01R2RLMzHoCdxLzQUKRczD8G
The applyRotaryPosition helper requires ArrayOffsetLayer conformance.
Change the stored property type to RoPELayer (OffsetLayer & ArrayOffsetLayer)
to match what initializeRope() already returns.

https://claude.ai/code/session_01R2RLMzHoCdxLzQUKRczD8G
Comment on lines -67 to +53
self.rope = .suScaledRoPE(
self.rope =

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.

This probably predates the new rope factory on the mlx-lm side and thus here too. I wonder if everything could just use the new rope factory? Probably best to keep it consistent with mlx-lm, but I wonder if they should?

@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.

Well, the easy part looks good :-)

@davidkoski
davidkoski merged commit 7c2e956 into ml-explore:main Apr 3, 2026
2 checks passed
@DePasqualeOrg

DePasqualeOrg commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor

@ronaldmannak, it's very hard for people like me following along to understand what you're doing when you name your PR something like "Claude/split large pr t996 z".

I get the impression that you're letting Claude act on your behalf, but please actually read and edit what you post so that it's legible to everyone.

@ronaldmannak

Copy link
Copy Markdown
Contributor Author

Excellent police work there. Was it the Claude name in the directory that gave it away?

I indeed let Claude act on my behalf to split a massive PR in manageable chunks.

This particular chunk was suggested by @davidkoski and is just a small refactor to remove duplicate code. There is no change in functionality. If there had been, I would have updated the skills.md ;)

That said, since you commented twice now in a few weeks about not understanding my PRs, I will make an effort to ask Claude to write a comprehensive PR message.

@DePasqualeOrg

Copy link
Copy Markdown
Contributor

Please respect everyone else's time and attention by making your work legible and not just leaving cryptic, auto-generated text. Not editing the final result indicates that you're not in the loop and other aspects of your work might not have been carefully reviewed by you. I think that's actually quite likely, given that you're submitting tens of thousands of lines of code here and already submitted thousands of lines of AI slop summaries that now get injected into everyone's dev environment.

@ronaldmannak

Copy link
Copy Markdown
Contributor Author

@DePasqualeOrg You’re absolutely right to call me out on that in this closed and merged PR because I forgot to update the title. I’m also truly sorry to have wasted your time by submitting tens of thousands of lines of AI slop. Ultimately, I think I, and probably many others, can only aspire to be not just as strong a developer as you, but also as helpful and positive a contributor to the community. Maybe one day we’ll all get there.

@DePasqualeOrg

Copy link
Copy Markdown
Contributor

@ronaldmannak, the reason I'm calling this out is because I've noticed a pattern of careless behavior by you across several projects in this space. Your carelessness affects many other people in a project like this. I've already had to waste time cleaning up the mess you made with thousands of lines of error-ridden summaries. Instead of replying with a sarcastic comment like this, which indicates that you don't really care about these issues, please reflect on the impact you're having on others and try to do better.

@davidkoski

Copy link
Copy Markdown
Member

@DePasqualeOrg and @ronaldmannak I appreciate both of your contributions. We are all (except me I guess) volunteers here -- people contributing their time and efforts to help each other.

Yes, the title on this was not ideal. I didn't even notice that as I was expecting this PR and knew what it was about -- my bad on not catching and correcting that and perhaps on Ronald for submitting it. I think it is best to assume mistakes rather than intent.

Please use "PR phrasing": review the code, not the person. Use softening phrases like "I think" or "maybe we should" for matters of opinion. If something is wrong then it is fine to use factual and non-emotional sentences: "this will leak memory if called concurrently". I try to stick to this but it is a manual effort and I probably don't always succeed.

Anyway, let's keep it professional and constructive.

I appreciate both of you and I want everybody to feel safe to contribute. If there is a problem in the quality of the contributions, that is on me -- give me feedback. My personal style is more "move it forward". Everything should build and run: no regressions and if we find some they should be fixed quickly.

Thank you!

@davidkoski davidkoski changed the title Claude/split large pr t996 z Batched LLM inference part 1 - consolidating RoPE calls Apr 3, 2026
@davidkoski

Copy link
Copy Markdown
Member

Renamed the PR to better reflect content for history purpose

@DePasqualeOrg

Copy link
Copy Markdown
Contributor

@davidkoski, I recognize you're in a difficult position, since you represent Apple and need to foster a positive community, and also have to review the incoming PRs, which seem to be increasing in volume. But I think there needs to be more pushback against the slopocalypse.

This is part of a larger problem in open source that hasn't yet been sorted out. Part of the solution could be more automated code review and certification by contributors that they've thoroughly reviewed and understand what they're submitting.

GoodOlClint added a commit to GoodOlClint/mlx-swift-lm that referenced this pull request Jul 6, 2026
Port the continuous-batching generation path from ml-explore#263
(cross-checked against the Python sibling mlx-lm#443): BatchGenerator scheduler
(insert/next/cancel/close), SequenceStateMachine, per-row samplers, ragged
prompt prefill, stop-sequence handling, and the BatchedCache protocol with
BatchKVCache / BatchRotatingKVCache / ArraysCache conformances.

Adapted onto our current RoPE substrate rather than ml-explore#263's divergent base:
- Kept our RoPEOffset / BatchPositionedKVCache mechanism (from merged ml-explore#178/ml-explore#212);
  ml-explore#263's BatchKVCache exposes batchOffset and conforms with no shim.
- KVCache.swift: took only the additive `leftPadding` param on createCausalMask
  and ported ArraysCache.extract(_:); did NOT take ml-explore#263's KVCache.swift refactor
  (it removes ropeOffset, used in 51 files, and adds a nonexistent Updatable).
- Dropped ml-explore#263's bundled Gemma4Text.swift changes (separable; our Gemma4 is MLXVLM).
- Package.swift: added MLXRandom to MLXLMCommon; kept our mlx-swift 0.31.4 pin.

Reconciliation vs our BaseKVCache: `override` on BatchKVCache/BatchRotatingKVCache
finalize().

Tests: ContinuousBatchingTests (10) pass via xcodebuild on macOS. Full package
builds clean; verify-docs.sh green; swift-format clean.

See docs/decisions/0011 (workspace root).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
davidtai pushed a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
…ml-explore#178)

* Preserve QuickTime audio in memory-backed video assets

* Keep JPEG orientation metadata integer in the regression fixture

* Honor cumulative coverage and deferred retirement in paged test owner

---------

Co-authored-by: jonathan308 <5055076+jonathan308@users.noreply.github.com>
davidtai added a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
…xplore#192)

Since eeba2af (ml-explore#178), 31 XCTest cases in five MiMo suites throw
nativeLaneRequired on the hosted CI runner, so every run of Fork Tests
on main fails. The tests need the exclusive native GPU lane, which the
runner does not have.

This change turns each of those throws into an XCTSkipUnless on the
same environment variables. The tests now skip, with the reason, on a
machine without the lane, and run as before where the variables are
set. The unused nativeLaneRequired enum case is removed from each
suite.

Tests only. No production code change.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
davidtai added a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
ml-explore#289)

* fix(cache): preserve demanded fork checkpoints and bound short capture

* test: let expected paged work refusals reach the caller (ml-explore#209)

PagedWorkFixture.prepare wrapped prepareAttentionWork in XCTUnwrap.
XCTUnwrap records a test failure when its expression throws, also
when the caller expects the throw with XCTAssertThrowsError. Three
tests expect prepare to refuse, so each expected refusal was recorded
as a failure. prepare now throws the refusal to the caller and fails
only when prepareAttentionWork returns nil.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit b7bbdc2)

* fix(paged): write a full destination for broadcast direct KV (ml-explore#210)

Materialize broadcast retained KV into a complete contiguous destination while preserving bit values, ownership validation, and reservation bounds. Focused differential paging, lifetime, and bit-exact validation completed during review.

(cherry picked from commit 3799b11)

* test(mimo): skip native-lane tests on machines without the lane (ml-explore#192)

Since eeba2af (ml-explore#178), 31 XCTest cases in five MiMo suites throw
nativeLaneRequired on the hosted CI runner, so every run of Fork Tests
on main fails. The tests need the exclusive native GPU lane, which the
runner does not have.

This change turns each of those throws into an XCTSkipUnless on the
same environment variables. The tests now skip, with the reason, on a
machine without the lane, and run as before where the variables are
set. The unused nativeLaneRequired enum case is removed from each
suite.

Tests only. No production code change.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit c288f53)

* test(mimo): assert the MiMo contracts that ml-explore#171 shipped (ml-explore#211)

Three assertions in the MiMo tests disagree with the code that the same
PR (ml-explore#171) added:

- The MiMo cache conforms to CBv2MTPRectangularSerializing, and
  MiMoV26RectangularVerifyTests asserts that the bank supports
  rectangular MTP verification. The test asserted the opposite.
- CBv2PrefillRequirement.evaluationOnly returns a [B, 1] handle
  (EngineLoopV2.prefillOutput). The test expected shape [1].
- MiMoV26MTPAssistant conforms to
  CBv2HistoricalMTPPrefixCheckpointCoding (MiMoV26MTPPrefixCheckpoint).
  The test asserted that it is not a prefix checkpoint drafter.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 5e9d268)

* test: run bit-exact reference tests only on reference hardware (ml-explore#174)

* style: format DiffusionGemmaVisionOracleTests.swift

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: format DiffusionGemmaFactoryTests.swift

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: run bit-exact reference tests only on reference hardware

Nine DiffusionGemma tests compare float bits with frozen references.
On the hosted macos-26 runner (Apple M1 VM) they differ in the low bits,
with no change in shape, dtype or sign. Add a `.referenceHardware`
Swift Testing trait that runs a test only when MLX_REFERENCE_HARDWARE=1,
and mark the nine tests with it. Elsewhere they report as skipped with
the reason. No assertion, tolerance or reference changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: gate only the bit comparisons of mixed DiffusionGemma tests

Three gated tests also held checks that pass on any hardware. Split them
so only the bit-for-bit comparison is gated:

- prefixIdentityTokensOwnerAndEmptyStateFailClosed() runs its
  fail-closed probes on all hardware. The donor-logits bit comparison
  moves to failClosedProbesLeaveDonorLogitsBitExact().
- nativeFactoryLoadsExactStateAndReleasesItsModel() keeps the load and
  model-release checks on all hardware. The logits bit comparison moves
  to nativeFactoryDenoiseMatchesReferenceBits().
- The two parameterized vision tests run their bf16 case on all
  hardware. The fp32 case moves to a separate gated test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: gate only the reference comparisons of three more DiffusionGemma tests

Split the three tests that were still gated whole, so their checks that
pass on any hardware run everywhere:

- chunkedSessionBoundsPrefillAndCanCancelAfterPrefill() keeps the
  prefill bounds, the complete flag, the counters, cancel, the emitted
  checkpoint and the released cache for widths 1, 3 and 7. The KV and
  logits bit comparisons move to chunkedSessionMatchesIndependentNativeReference().
- sharedWeightsConditioningKeepsCommittedCacheState() keeps the fixture
  checks, both cache positions and the unchanged encoder KV after the
  provisional canvas. The reference comparisons stay in
  sharedWeightsConditioningAndCommittedCacheMatchReference().
- committedPrefixRestoreKeepsPositionsAfterDonorRetirement() keeps the
  token count, retained bytes, donor release and both positions. The
  reference comparisons stay in
  committedPrefixRestoreIsExactAfterDonorAppendAndRetirement().

Each pair shares one helper. The fixture reference, case-count and
parameter-count checks of the block and fp32 vision fixtures also run
everywhere now, in blockOracleFixtureIsPinned() and fp32FixtureIsPinned().
CONTRIBUTING.md says which comparisons the gate covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit a046367)

* docs: describe demanded checkpoints and their shared fixture

* fix(cache): honor request participation in short checkpoint scheduling

* Preserve demanded checkpoint eligibility through preemption and packing

* test: size the slot-cap request from what the ledger accepts

slotCapLeavesRoomForServing() sized its request from bytesReserved.
bytesReserved includes the paged pool's physical-floor overhead, which a
request's target KV replaces when it reserves. The overhead depends on
the buffer sizes the MLX allocator returns: a 36,864-byte segment gets a
49,152-byte buffer, or a 65,536-byte buffer reused from the process-wide
cache. When earlier work left 64 KiB buffers in the cache, the capped
arm left more than 5.5 windows of real slack instead of half a window,
and the uncapped arm's reservation fit.

Find the largest request the ledger accepts beside the capped set with
trial reservations, then take half a window off it. The assertions do
not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 06224a8)

* Retain demanded native frontiers and preserve observed prefill endpoints

* Document current SDK parameters and generation links

* Disambiguate the task generation documentation link

---------

Co-authored-by: David Tai <dtaipublic@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
GoodOlClint added a commit to GoodOlClint/mlx-swift-lm that referenced this pull request Oct 14, 2026
Port the continuous-batching generation path from ml-explore#263
(cross-checked against the Python sibling mlx-lm#443): BatchGenerator scheduler
(insert/next/cancel/close), SequenceStateMachine, per-row samplers, ragged
prompt prefill, stop-sequence handling, and the BatchedCache protocol with
BatchKVCache / BatchRotatingKVCache / ArraysCache conformances.

Adapted onto our current RoPE substrate rather than ml-explore#263's divergent base:
- Kept our RoPEOffset / BatchPositionedKVCache mechanism (from merged ml-explore#178/ml-explore#212);
  ml-explore#263's BatchKVCache exposes batchOffset and conforms with no shim.
- KVCache.swift: took only the additive `leftPadding` param on createCausalMask
  and ported ArraysCache.extract(_:); did NOT take ml-explore#263's KVCache.swift refactor
  (it removes ropeOffset, used in 51 files, and adds a nonexistent Updatable).
- Dropped ml-explore#263's bundled Gemma4Text.swift changes (separable; our Gemma4 is MLXVLM).
- Package.swift: added MLXRandom to MLXLMCommon; kept our mlx-swift 0.31.4 pin.

Reconciliation vs our BaseKVCache: `override` on BatchKVCache/BatchRotatingKVCache
finalize().

Tests: ContinuousBatchingTests (10) pass via xcodebuild on macOS. Full package
builds clean; verify-docs.sh green; swift-format clean.

See docs/decisions/0011 (workspace root).

Co-Authored-By: Claude Opus 4.8 (1M context) <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.

4 participants