Skip to content

Fix generation loop blocking Swift cooperative workers - #611

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/fix-generation-cooperative-pool
Sep 10, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/fix-generation-cooperative-pool

Conversation

@aleroot

@aleroot aleroot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

Fixes #600.

generateLoopTask runs its token loop in an unstructured Task. Although asyncEval schedules GPU evaluation asynchronously, it can block the calling thread when MLX applies backpressure to bound outstanding work. That wait occupies a Swift cooperative worker and prevents it from running unrelated async work.

The fix

Run the synchronous generation loop on a private actor backed by DispatchSerialQueue, using its built-in SerialExecutor conformance. Each generation has its own queue. The same Swift task hops onto that executor, preserving cancellation and task-local values. Iteration, speculative iterator finalization, and the final Stream().synchronize() all stay on that executor until cleanup finishes. One blocked generation does not serialize other generations.

MLX's backpressure remains necessary. This change gives the blocking work an appropriate execution context. Synchronous iterator construction and prefill before generateLoopTask remain in the caller's context.

Dependency

The investigation also exposed wired-memory ticket lifecycle defects in mlx-swift, addressed separately in ml-explore/mlx-swift#471. Cancellation could release a ticket before generation cleanup finished, and cancellation while waiting for admission could trigger a debug assertion.

Complete wired-memory cancellation correctness depends on #471. The scheduling fix works with the currently resolved mlx-swift 0.31.6, but that release still contains those lifecycle defects.

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)

AI usage

  • I have read this PR description in full and approve it as my own, and it accurately describes the code changes.
  • AI usage disclosure:

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

Change looks good, thank you!

@davidkoski
davidkoski merged commit 9ce5b4f into ml-explore:main Sep 10, 2026
4 checks passed
ronaldmannak pushed a commit to ronaldmannak/mlx-swift-lm that referenced this pull request Sep 12, 2026
Brings the fork mirror's 19 upstream commits (2026-08-31 to 2026-09-11)
onto the batched-cache layer plus the VLM stack (#38
to #48, absorbed by fast-forward). The dry-run merge was conflict-free;
both sides touched KVCache.swift and Evaluate.swift in disjoint hunks.

Upstream changes that sit under the batching work: ml-explore#584 (RotatingKVCache:
wrap-aware trim) and ml-explore#611 (generation loop no longer blocks cooperative
workers). The batch and wrapped-cache tests must be re-run on Apple
silicon; the fork's CI skips every job.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RT2yoDKAz695YTHR6hDuoC
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Sep 14, 2026
Apply the upstream commits e3d4a20..3e6ea1e as a 3-way patch. CLAUDE.md is
excluded.

- db05290 Let training differentiate the gated-delta recurrence (ml-explore#616)
- 4c3d793 Emit only the new scalars when a token extends the previous character (ml-explore#613)
- 1012230 Gemma 4 VLM: fuse float32 logit softcapping (ml-explore#615)
- 9ce5b4f Fix generation loop blocking Swift cooperative workers (ml-explore#611)
- 238ad74 Add configuration-based LoRA metadata discovery (ml-explore#597)
- 604fae7 RotatingKVCache: make trim wrap-aware instead of corrupting the ring (ml-explore#584)
- a56aee3 Add bounded cross-dialect tool-call recovery (ml-explore#548)
- 3e6ea1e Reuse the KV cache for append-only media turns (ml-explore#515)

Conflict resolutions:

- Evaluate.swift: keep the shared generateSpeculativeStream helper. It now
  receives parameters and tools, and passes tools and toolCallPolicy to
  TextToolTokenLoopHandler for the draft-model and MTP paths.
- PromptCacheReusePolicy.swift: keep the package access of the turn fields,
  and make canSplitPreparedMedia package also. reconcilePromptCache has no
  prepared input to split, thus it answers .appendMediaSuffix with nil.
- ToolCallFormat.swift: keep buffersEntireResponse and add supportsBareJSON.
- ToolCallProcessor.swift: the buffersEntireResponse check stays first in
  processChunk. The recovery scanner path comes after it.

Follow-up changes:

- AllowedToolOutputRouter: join adjacent response outputs into one event.
  The recovery scanner can divide response text at a "<" that does not
  start a call.
- Gemma4FusionTests: delete testFusionLatency. It runs only when an
  environment variable is set, and stable runs no skipped tests.

Tests: all five bundles pass with no skipped test (MLXLMTests 1170 Swift
Testing + 693 XCTest, MLXGuidedGenerationTests 70, MLXFoundationModelsTests
213, CXGrammarTests 7, MLXHuggingFaceMacrosTests 5).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TEgdBA8Ap14pU1EfmHkazD
djandrewgibbons pushed a commit to djandrewgibbons/mlx-swift-lm that referenced this pull request Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

generateLoopTask parks a Swift cooperative-pool worker inside asyncEval

3 participants