Repository navigation
Add an opt-in plain-chunk ceiling for bidirectional media requests - #331
Merged
Merged
Conversation
`CBv2SchedulerConfig.bidirectionalMediaPrefillChunkCeiling` (nil by default) caps the plain prefill chunk of a request whose multimodal input carries bidirectional blocks. A paged span-bearing chunk attends in one unblocked call, so its score tensor grows with the chunk length times the history; the ceiling lets a host widen text chunks without widening that tensor. Both chunk-cap sites in SchedulerV2 (the ordinary plan and the deferred block-row admission) read `plainPrefillChunkSize(hasBidirectionalBlocks:)`. A chunk that begins at a block still extends over the whole block, the solo stripe still never arms for these requests, and causal media keeps `prefillChunkSize`. First-token projection already refuses to price block-bearing rows (`multimodalWork`), so it needs no mirror. Unit tests cover the ceiling beside a wide text chunk, block snap-over, unset and non-binding values, causal media, deferred admission and serialized prefill beside decode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SDK main keeps scheduler unit tests in Tests/MLXLMTests/Unit/Scheduling (CBv2PrefillInterleaveTests). Use the same folder so the merge does not leave a parallel Unit/Scheduler directory. No test or code change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Refresh before review: d-inference master now pins SDK 889fe3c. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gajesh2007
added a commit
to Layr-Labs/d-inference
that referenced
this pull request
Oct 22, 2026
Layr-Labs/mlx-swift-lm#331 squash-merged as c8dce97d ("Add an opt-in plain-chunk ceiling for bidirectional media requests (#331)"). Move the gitlink from the PR branch head 204771c4 to that commit on SDK main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308
added a commit
that referenced
this pull request
Oct 22, 2026
Brings #322 (Flint), #324, #326-#330 (CBv2 paged/MTP/SDPA, GPT-OSS), #325 and the Nemotron Super fused MTP verify window: SDK main up to the commit d-inference master pins (889fe3c). Main's later #331/#332 are left out until the provider adopts #332's streamed tool-call type. Package.swift pins the cluster mlx-swift 9fe34405 instead of main's 67dc7528; that was the only conflict. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Oct 22, 2026
Gajesh2007
added a commit
to Layr-Labs/d-inference
that referenced
this pull request
Oct 22, 2026
* Raise CBv2 mixed-step prefill geometry for GPT-OSS, dense Qwen and Gemma 4 With one partial prefill a busy engine prefills only its plain chunk beside decode rows, so production fed every mixed step 512 prompt tokens. GPT-OSS, dense Qwen3.5/3.8 and Gemma 4 now default to a 2,048-token plain chunk and a 4,096-token step budget (EngineV2Factory.prefillGeometry). The chunk replaces the 2,048-token GPT-OSS and Gemma stripes and stays below dense Qwen's 4,096-token stripe, so paged ring sizes, KV charges and load quotations are unchanged. Other families keep 512 / 2,048. Gemma 4 image and video requests keep 512-token chunks through the SDK's new bidirectionalMediaPrefillChunkCeiling (libs/mlx-swift-lm moves to the commit that adds it): a paged span-bearing chunk attends in one unblocked call, so its score tensor grows with the chunk length times the history. DARKBLOOM_CBV2_PREFILL_CHUNK and DARKBLOOM_CBV2_STEP_TOKENS override the geometry for every family and reach the launchd provider job; 512 / 2048 rolls back. Scheduler-prefill receipts record the geometry (schema 5), the decision live runner pins its simulated geometry, and fixtures that pin a stripe also pin the SDK chunk. Docs, a dated measurement report and a changelog fragment record the load, inter-token latency and activation evidence and its limits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Document the Gemma 4 block ring bound and tighten geometry comments Behavior-preserving refactor-pass follow-up to the prompt geometry change. - inference.md invariant 9: a Gemma 4 block chunk stays within the 2,048-token ring because Gemma4Processor delimits every image and video frame, not because submit validation bounds blocks, which now admits them up to the 4,096-token step. - configuration.md: a solo stripe that does not exceed the plain chunk, including an equal one, is disabled. - productionSchedulerConfig: the media ceiling comment names bidirectional media, which is all the ceiling applies to. - SegmentedFleetGeometry: window rings follow the largest schedulable chunk, which for GPT-OSS and Gemma is now the plain chunk, not a stripe. - libs/mlx-swift-lm moves to the SDK commit that files the ceiling tests under Unit/Scheduling, matching SDK main; no library change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Record why the Gemma benchmark wrapper schema stays at 6 Raw scheduler-prefill schema 5 adds the plain chunk and step budget. Like the raw sweep 8 / arrival 6 note, say why the wrapper schema does not move: the default workload's prompts each fit one chunk and no step exceeds 2,048 tokens, so the Gemma 4 geometry change does not alter its chunking; longer prompts beside decode rows do not compare across the change. Comment only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: untangle the recurrent-bank paragraph after the master merge The merge kept both sides of the conflicting prefix-cache.md paragraph, which repeated two sentences. Keep this branch's 2,048-token plain chunk and master's Nemotron Super alignment sentence once each. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Re-pin libs/mlx-swift-lm to the merged SDK change (#331) Layr-Labs/mlx-swift-lm#331 squash-merged as c8dce97d ("Add an opt-in plain-chunk ceiling for bidirectional media requests (#331)"). Move the gitlink from the PR branch head 204771c4 to that commit on SDK main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Re-pin the SDK to f77b384c and adapt to its tool-call delta type The previous pin, c8dce97d (#331), also carries SDK #332: chunk deltas now carry [OpenAIToolCallDelta] and MLXServerGenerationEvent gains .toolCallDelta, so ProviderLoop+SSEParser.swift no longer compiled. Pin f77b384c, the merged SDK main commit that adds #333's MLXLMServerTests build fix on top of #331 (same library tree). The SSE parser and the six test-file hunks are copied byte for byte from #1549 (ttft/stream-auto-tool-calls), so whichever of the two lands second merges cleanly. They change types only; this branch does not request streamed fragments, so complete calls hash and encode as before. Flint response-format code added by master's #1552 also switches over MLXServerGenerationEvent; it ignores .toolCallDelta like .toolCall, and its tests count a completed delta as a call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Fill the schema-5 geometry in the merged prompt-mode receipt test Master's #1535 added SchedulerPrefillPromptTests against schema 4. After the merge its receipt fixture omitted this branch's new required prefillChunkTokens and maxBatchedTokensPerStep and expected schema 4 from a current-version report, so the test target failed to compile. The fixture now records the SDK geometry and expects the current schema; the legacy case decodes a faithful schema-4 payload without the geometry fields. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Carry the schema-5 prompt geometry into gptoss_profile summaries summarize_cell copied only soloPrefillStripeTokens from a scheduler-prefill receipt. Under the wide plain chunk a nil stripe no longer means 512-token chunks, so derived summaries could not tell a default run from an explicit chunk or step-budget arm. Prefill rows now also keep prefillChunkTokens and maxBatchedTokensPerStep (None for schema-4 receipts, which lack them). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the wide prompt geometry default for Gemma 4 only The PR's own KV-subtracted activation probe at eight rows of 32,768-token prompts, inside the floors' measurement range of eight rows at 4k tokens or more, shows 2,048 / 4,096 pushing GPT-OSS from its 3.5 GiB floor to 3.62 GiB and Qwen3.5-9B from 5.73 to 6.03 GiB against the 5.5 GiB default. No margin absorbs that: UnifiedMemoryCap.liveKVHeadroomBytes grants KV until MLX usage plus the reserve reaches the cap, so activation above the reserve lands past the cap once the KV budget is full. Floors are measured constants that move only with platform admission, so they stay unchanged here. usesWidePrefillChunk now selects Gemma 4 alone (3.73 GiB at 32k against 5.5). GPT-OSS and dense Qwen3.5/3.8, including the unmeasured Qwen3.8-27B, keep 512 / 2,048 and their stripes; DARKBLOOM_CBV2_PREFILL_CHUNK=2048 with DARKBLOOM_CBV2_STEP_TOKENS=4096 still opts them in for measurement. Tests pin GPT-OSS and dense Qwen to the SDK geometry and drive the GPT-OSS busy-engine and pool-lockstep cases through the opt-in. The GPT-OSS and Qwen live checkpoint fixtures no longer need to pin the SDK geometry and return to master's form; prefix-cache.md returns to master because no recurrent family takes the wide chunk by default. The report gains a default-scope section with the per-cell margins and names the SDK revision the probes ran on (cef662176, before SDK #326's GPT-OSS bf16 activations). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Raise undersized Gemma 4 chunk overrides to cover a whole media block A Gemma 4 chunk that starts at a bidirectional media block extends over the whole block, and submit validation bounds blocks only by the step budget, but the paged window rings hold max(chunk, stripe) tokens. With DARKBLOOM_CBV2_PREFILL_CHUNK=256 and DARKBLOOM_CBV2_SOLO_PREFILL_STRIPE=0 the rings held 256 tokens and a 280-token image block tripped the PagedSequenceKV precondition, killing the provider. prefillGeometry now raises a Gemma 4 chunk to 1,120 tokens, the vision family's largest image budget, whenever the override leaves max(chunk, stripe) below it. The default 2,048-token chunk, the documented 512 / 2,048 rollback (its 2,048-token stripe re-arms) and other families are unchanged. A geometry test pins the raised values; an engine test prefills a 300-token block beside decode under chunk 256 with the stripe off. With the guard disabled the first fails and the second stops on "windowed update of 300 tokens exceeds maxPrefillChunk 256". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Record the prompt geometry the built engines actually ran in receipts The scheduler-prefill receipt took prefillChunkTokens, maxBatchedTokensPerStep and soloPrefillStripeTokens from EngineV2Factory.prefillGeometry before production applied later policy: glm5NextServingScheduler (2,048 / 2,048, stripe off), the calibrated Nemotron clamp and any dedicated scheduler policy. A GLM or Nemotron run could therefore be attributed to the generic geometry. ProductionBuild now carries prefillGeometry, taken from the scheduler configuration assembleProductionBuild hands the engine. The benchmark records the warm-up engine's value and fails the run if a measured engine was built with different geometry, so one report-level field never describes samples it does not cover. A test builds a tiny paged GPT-OSS engine with and without a scheduler policy that narrows the chunk, step and stripe, and checks the build reports the narrowed geometry rather than prefillGeometry(model:). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Count only completed tool-call deltas in the Flint test helpers, as #1549 does FlintResponseFormatTests counted every .toolCallDelta event as a call, so it disagreed with FlintAnswerStopTests and with #1549 (ttft/stream-auto-tool-calls), which count a delta only when it completes a call. Both helpers now match #1549's files byte for byte, so this branch and #1549 merge without conflicts in either file. Behavior is unchanged: this branch does not request streamed fragments, so its engines emit only whole .toolCall events. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Raise undersized Gemma 4 step budgets to cover a whole media block e19f138 kept the windowed rings at least one Gemma 4 media block wide, but submit validation also refuses a block longer than the step budget (CBv2MultimodalPlan.validate). With a chunk below the block, a stripe that already covers it and an explicit step budget equal to the small chunk (for example 256 / 1,120 / 256), the ring guard did not fire and every image request failed with spanTooLong although the rings could hold the block. prefillGeometry now raises a Gemma 4 step budget below 1,120 tokens (gemma4MaximumMediaBlockTokens) to 1,120. Defaults, the 512 / 2,048 rollback and other families are unchanged. A geometry test pins the raised budget and that other families keep theirs. A real paged Gemma 4 engine test submits a 300-token block under chunk 256, stripe 1,120 and step 256. With the clamp removed, the geometry test fails and the engine test catches .spanTooLong(blockTokens: 300, maxBatchedTokensPerStep: 256). inference.md invariant 9 records the budget bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Name the families whose policy replaces the prompt geometry overrides The prompt-geometry docs said an explicit DARKBLOOM_CBV2_PREFILL_CHUNK applies to every family. Three later policies replace or cap it: glm5NextServingScheduler sets GLM5Next's own 2,048-token chunk and step; NemotronSuperLocalPrefill.Policy.apply sets Nemotron Super local serving's chunk (DARKBLOOM_NEMOTRON_SUPER_PREFILL_CHUNK) and step; and calibratedPrefillTokenLimit caps calibrated Nemotron chunks. inference.md and the configuration rows now name these exceptions, and point to the receipts' built geometry. The STEP_TOKENS row also records the Gemma 4 media-block budget raise. The changelog said solo prefill is unchanged. Solo chunking is, but the 2,048-token Gemma stripe used to shrink to 512 tokens once when KV could not be reserved, and a plain chunk does not. On contiguous KV (Gemma 4 artifacts other than the catalog's paged gemma-4-26b-qat-4bit, or with paging disabled), such a prompt now waits or is preempted. The fragment now says so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Place prefill-geometry passthrough test apart from sibling PRs' insertions Move forwardsPrefillGeometryRollbackToProviderJob up beside forwardsPrefillOperationalControlsUnchanged, mirroring the key order in inferencePassthroughEnvKeys, so it no longer shares an insertion point with the serving-stalls test after the deadline-admission test. Pure move; the test body is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
3 of 5 tasks
javiech1
pushed a commit
to javiech1/mlx-swift-lm
that referenced
this pull request
Oct 24, 2026
Update Falcon H1/H1R inference behavior to match current mlx-lm more closely. This fixes tied embedding output projection and scaling, routes attention through the common cache-aware causal path, advances Mamba cache metadata during generation, reports per-layer KV head counts correctly, and chunks SSM prefill to reduce long-prompt memory and latency. Also mirror upstream ArraysCache length handling for hybrid and batched paths: preserve left padding and lengths through filter, extend, copy, and serialization; forward length preparation through CacheList; and use per-row lengths in Falcon H1 convolution plus chunked SSM state updates. Add regression coverage for the shared causal attention mask path, SSM mask metadata, nested hybrid cache length propagation, and Mamba metadata copy behavior.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Opt-in plain-chunk ceiling for bidirectional media requests
Summary
CBv2SchedulerConfig.bidirectionalMediaPrefillChunkCeiling: Int?(defaultnil, so SDK behavior is unchanged unless a host sets it). When set, a request whose multimodal input has bidirectional blocks (Gemma 4 images and video frames) usesmin(prefillChunkSize, ceiling)as its plain prefill chunk.PagedLayerCache.prefillAttend), so its materialized score tensor grows with the chunk length times the history. The d-inference provider is raising Gemma 4's plain chunk from 512 to 2,048 for text (Layr-Labs/d-inferencettft/mixed-prefill-chunk); without a ceiling a long-history image request would carry a ~4x larger score tensor (measured +1.84 GiB peak at a 32k-token history) that the provider's activation reserve does not bound.plainPrefillChunkSize(hasBidirectionalBlocks:): the ordinary plan (prefillChunkCap) and the deferred block-row admission (admitDeferredBlockRow). A chunk that begins at a block still snaps over the whole block (bounded by the step budget), the solo stripe still never arms for block-bearing rows, and causal media keepsprefillChunkSize.multimodalWork), so it needs no mirror.Before / After: observable behavior
flowchart TB subgraph BEFORE["Before"] direction TB r1["Engine configured with a<br/>2,048-token plain chunk"]:::state --> r2["Paged image request,<br/>32k-token history"]:::req r2 --> r3["span-bearing chunk of 2,048 queries<br/>attends unblocked"]:::old r3 --> r4["score tensor ~4x larger than at 512:<br/>+1.84 GiB peak measured (Gemma 4)"]:::bad end subgraph AFTER["After"] direction TB q1["Same engine, ceiling 512"]:::state --> q2["Paged image request,<br/>32k-token history"]:::req q2 --> q3["512-token chunks; image block<br/>still rides one chunk"]:::new q3 --> q4["peak equal to the 512-chunk engine<br/>(2.124 GiB both arms)"]:::good q1 --> q5["Text request"]:::req --> q6["2,048-token chunks"]:::new end BEFORE ~~~ AFTER style BEFORE fill:#fff7f6,stroke:#c0392b,color:#111111 style AFTER fill:#f4fbf6,stroke:#1e8449,color:#111111 classDef state fill:#e8eef7,stroke:#4a6fa5,color:#111111 classDef req fill:#f3e8fd,stroke:#7d3c98,color:#111111 classDef old fill:#fde2e1,stroke:#c0392b,color:#111111 classDef bad fill:#f9c9c6,stroke:#922b21,color:#111111 classDef new fill:#dcf5e3,stroke:#1e8449,color:#111111 classDef good fill:#b9ecc8,stroke:#196f3d,color:#111111Before / After: code flow
flowchart TB subgraph BEFORE["Before"] direction TB s1["SchedulerV2.plan via prefillChunkCap(for:);<br/>admitDeferredBlockRow via its own cap"]:::code s1 --> s3["recurrent plan, armed stripe (plan only),<br/>else config.prefillChunkSize"]:::old s3 --> s4["text and bidirectional media<br/>share one plain chunk"]:::old end subgraph AFTER["After"] direction TB t1["SchedulerV2.plan via prefillChunkCap(for:);<br/>admitDeferredBlockRow via its own cap"]:::code t1 --> t2["recurrent plan, armed stripe (plan only),<br/>else config.plainPrefillChunkSize(hasBidirectionalBlocks:)"]:::new t2 --> t3{"row has bidirectional<br/>blocks and a ceiling?"}:::decide t3 -->|no| t4["prefillChunkSize<br/>(unchanged; nil ceiling is the default)"]:::same t3 -->|yes| t5["min(prefillChunkSize, ceiling)"]:::new t5 --> t6["block snap-over unchanged;<br/>stripe still never arms"]:::same end BEFORE ~~~ AFTER style BEFORE fill:#fff7f6,stroke:#c0392b,color:#111111 style AFTER fill:#f4fbf6,stroke:#1e8449,color:#111111 classDef code fill:#e3ecfa,stroke:#2e5c9e,color:#111111 classDef old fill:#fde2e1,stroke:#c0392b,color:#111111 classDef new fill:#dcf5e3,stroke:#1e8449,color:#111111 classDef decide fill:#fff3c4,stroke:#b7950b,color:#111111 classDef same fill:#ececec,stroke:#7f8c8d,color:#111111Legend: red = previous path, green = new behavior, yellow = decision, grey = unchanged.
Evidence
Gemma 4 26B QAT, paged production engine built by the provider factory, one 280-token image 768 tokens before the end of the prompt, prefilled alone (M5 Ultra; MLX peak above pre-request active memory):
Validation
nice -n 15 swift build --build-tests(CLT toolchain, copied XCTest)swift test --skip-build --filter '\.UnitTests/'BidirectionalMediaChunkCeilingTests(6 tests, 10 cases); same counts atcef662176after the refactor pass moved the file toUnit/Scheduling/bash scripts/check-unit-test-files.shcef662176)prefillChunkSizefails 4 of the 6 ceiling tests: the plan path, snap-over, serialized prefill beside decode and the deferred admission'splannedPrefillChunkSize; the unset or non-binding and causal tests pass by designswift-format format --configuration .swift-formaton the three changed filesxctestagent (shared GPU ticket):CBv2SoloStripeTests,CBv2SchedulerTests,CBv2MultimodalTests,CBv2MixedStepPrefillQuotaTests,CBv2FirstTokenDeadlineAdmissionTests,CBv2DemandedShortCheckpointRangeTests,CBv2SchedulerLoopTests,CBv2PackedPrefillTests,Qwen35VisionCBv2SemanticsTests,CBv2VideoSeamTestsba090f7ce(cef662176changes no library code);CBv2PackedPrefillTests.testGemma4AdapterAdvertisesAndHonorsPackedPrefillfails (4 assertions) and fails identically on the clean pin14661d9baon this M5 Ultragit merge-tree --write-tree origin/main HEAD19634dd8b(rechecked atcef662176)Limitations
CBv2AttentionV1.attendQueryBlocksdoes on contiguous KV) would let media use wide chunks too; both change more code and the latter changes numerics.14661d9ba; merges cleanly intomain(19634dd8b).CBv2PackedPrefillTests.testGemma4AdapterAdvertisesAndHonorsPackedPrefillfails on this M5 Ultra both with and without this change (clean14661d9ba); unrelated.ba090f7ce,cef662176) are unsigned and must be re-signed before publication.Refactor pass
AGENTS.mdgate) onba090f7ce. One behavior-preserving commit,cef662176:BidirectionalMediaChunkCeilingTestsmoved from a newTests/MLXLMTests/Unit/Scheduler/folder toUnit/Scheduling/, wheremainkeeps scheduler unit tests (CBv2PrefillInterleaveTests), so the merge leaves one folder. No library or test content changed. The code-flow diagram above now showsadmitDeferredBlockRowcomputing its own cap rather than callingprefillChunkCap(for:).plainPrefillChunkSize(hasBidirectionalBlocks:)stays onCBv2SchedulerConfigbeside its sibling policyresolvedSoloPrefillStripeTokens(isMultimodal:); the field stays besidesoloPrefillStripeMediaCeiling, which keeps the merge intomainclean; both cap sites pass!rec.multimodalBlocks.isEmpty, which is exactly the bidirectional case.multimodalBlocksis non-empty only for.bidirectionalSpans; only Gemma 4 supports bidirectional span prefill (supportsVisionSpanPrefill);FirstTokenDeadlineAdmissionV2returnsmultimodalWorkfor any live block-bearing row, so projection needs no mirror; paged attention stays unblocked only while a span context is bound (PagedLayerCache.prefillAttend), so text-only chunks of a media request remain query-blocked (the conservative cost under Limitations); snap-over stays bounded by the step budget (snappedChunkTokens).boi/eoi-delimited blocks (at most a few hundred tokens) to stay inside it (itsinference.mdinvariant 9).🤖 Generated with Claude Code