Skip to content

feat(kvcache): spec 006 PR 4 — eliminate maybeQuantizeKVCache swap - #166

Merged
ekryski merged 4 commits into
alphafrom
ek/spec-006-pr4-eliminate-swap
May 6, 2026
Merged

ekryski merged 4 commits into
alphafrom
ek/spec-006-pr4-eliminate-swap

Conversation

@ekryski

@ekryski ekryski commented May 5, 2026 •

Copy link
Copy Markdown
Owner

Summary

PR 4/4 of spec 006 — KVCache architecture refactor that addresses #73.

Closes the self-transition cleanup pass: every model factory now constructs the right cache class up-front, making the per-step maybeQuantizeKVCache swap dead code. Built on top of #PR3-self-transition (typed compressionAlgorithm), #PR2-cleanup, and #PR1-typed-surface.

  • Adds makeAttentionCache(parameters:maxSize:keep:) helper — one canonical entry point for every model factory's attention-layer cache slot.
  • Migrates every newCache(parameters:) (~24 model factories + the KVCacheDimensionProvider default) to use the helper. Hybrids retain SSMStateCache() on the SSM slot.
  • Deletes maybeQuantizeKVCache and the per-iterator closure indirection (quantizeKVCache: (inout [KVCache]) -> Void); 6 call sites removed.
  • Adds GenerateParameters.draftCompressionAlgorithm so SpeculativeTokenIterator can run main + draft with different algorithms (e.g. turbo on main, affine4 on draft).
  • Turbo boundary-layer skip preserved (review feedback): adds skipBoundaryLayerCompression: Bool = true and boundaryLayersToSkip: Int = 2 to KVCache.CompressionAlgorithm.turbo. Defaults match v3's maybeQuantizeKVCache behavior. Shared turboBoundarySkipSet(...) helper exposed for any model factory that constructs TurboQuantizedKVCache.

Behaviour vs PR 3

  • Turbo boundary-skip kept (and improved): the v3 default of "skip first 2 + last 2 attention layers under turbo" is restored, but now exposed as a per-call config on KVCache.CompressionAlgorithm.turbo (and a shared turboBoundarySkipSet(...) helper) rather than buried in maybeQuantizeKVCache. Qwen 3.5 and NemotronH (the only two models that construct TurboQuantizedKVCache directly) honor the knobs in their newCache(parameters:). Default behavior matches v3 byte-for-byte.
  • Speculative gating simplification: the prior "if either main or draft doesn't support turbo, disable on both" gate is gone. Each model's factory makes its own decision based on supportsTurboQuantization; draftCompressionAlgorithm lets the caller force a different draft algorithm.

Test plan

  • swift build --build-tests clean (zero warnings).
  • swift test --filter KVCacheTests — 47 tests pass (40 prior + 10 new boundary-skip cases — testTurboBoundarySkipSet*).
  • Full swift test --skip Benchmarks — 174 tests in 14 suites pass.
  • Smoke matrix:
    • Qwen3.5 0.8B: kv=none, affine4, turbo4v2 × ctx=1k, 4k, 32k — coherent output across all 9 cells.
    • Gemma 4 E2B: kv=none, affine4, turbo4v2 × ctx=1k, 4k, 32k — coherent output across all 9 cells.
    • Nemotron Cascade 2 30B-A3B (hybrid Mamba+attention): kv=none, affine4 × ctx=1k, 32k — coherent output. (Turbo not supported on hybrids; SSM slot routes to SSMStateCache.)

Every model factory now constructs the right cache class up-front via
makeAttentionCache(parameters:maxSize:keep:), making the per-step
maybeQuantizeKVCache swap dead code.

Changes:
- Add makeAttentionCache(parameters:maxSize:keep:) helper in KVCacheTypes
  — returns AffineQuantizedKVCache when parameters.compressionAlgorithm
  is .affine, else StandardKVCache. One canonical entry point for every
  model factory's attention-layer cache slot.
- Migrate every model's newCache(parameters:) to makeAttentionCache:
  dense LLMs (AfMoE, Exaone4, GPTOSS, MiMoV2Flash, Mistral3Text, Olmo3,
  Gemma3Text, Gemma3nText, Gemma4 LLM + VLM, Pixtral, Mistral3 VLM,
  Qwen35 VLM) and hybrids (BaichuanM1, FalconH1, GraniteMoeHybrid,
  Jamba, LFM2, LFM2MoE, LFM2VL, Qwen3Next). Plus the
  LanguageModel where Self: KVCacheDimensionProvider default. Hybrids
  use makeAttentionCache only on the attention slot of the CacheList;
  SSM slot stays SSMStateCache().
- Delete maybeQuantizeKVCache entirely. Remove the closure indirection
  (quantizeKVCache: (inout [KVCache]) -> Void) and stored
  compressionAlgorithm/turboBoundarySkip fields from TokenIterator and
  SpeculativeTokenIterator. Remove the 6 call sites (Evaluate.swift
  step + reset, NgramSpeculativeDecoding.swift x4, WiredMemoryUtils.swift
  x2, InferenceBenchmark.swift wikitext PPL).
- Per-cache compression scheme in SpeculativeTokenIterator: add
  GenerateParameters.draftCompressionAlgorithm: KVCache.CompressionAlgorithm?
  (defaults to nil, falls back to compressionAlgorithm). When set
  differently, the iterator constructs draft-specific GenerateParameters
  and passes them to draftModel.newCache(...). Unblocks main-turbo +
  draft-affine combinations.
- Update spec 006 to reflect 4-PR plan (was 2) and PR 4 deletion of
  maybeQuantizeKVCache.

Behaviour deltas vs PR 3:
- turbo boundary-skip (skip first/last 2 layers) is dropped: Qwen35 +
  NemotronH factories construct turbo for every attention layer. PR 3
  already shipped without boundary-skip on the up-front turbo path; this
  removes the dead maybeQuantizeKVCache.turbo codepath that would never
  have fired (early-return on existing TurboQuantizedKVCache).
- Speculative decoding: the prior gate "if either main or draft doesn't
  support turbo, disable on both" goes away. Each model's factory makes
  its own decision; draftCompressionAlgorithm lets the caller force a
  different draft algorithm.

Verified:
- swift test --filter KVCacheTests: 40 tests pass.
- Smoke matrix:
  - Qwen3.5 0.8B: kv=none, affine4, turbo4v2 — coherent output, all
    contexts (1k, 4k, 32k).
  - Gemma 4 E2B: kv=none, affine4, turbo4v2 — coherent output, all
    contexts.
  - Nemotron Cascade 2 30B-A3B (hybrid Mamba+attention): kv=none,
    affine4 — coherent output (turbo not supported).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski and others added 3 commits May 5, 2026 18:42
Final pre-rebase in the spec 006 stack so the chain stays mergeable
after PR #167 lands on alpha.

Conflict resolved:

- `Libraries/MLXVLM/Models/Gemma4.swift` (Gemma4Text newCache):
  PR 4 introduced the `makeAttentionCache(parameters:maxSize:)` factory
  to handle the `.affine` compressionAlgorithm path (returns an
  `AffineQuantizedKVCache` instead of a plain `StandardKVCache` when
  set). The forward-merge brings PR 3's main-version newCache that
  uses direct `StandardKVCache(...)` construction with a
  `prefix(hiddenLayers - numKVSharedLayers)` filter (KV-shared layers
  reuse an earlier layer's cache and don't allocate their own).
  Resolution: keep PR 3's filter (correctness — KV-shared layers
  shouldn't double-allocate) AND PR 4's factory (correctness — affine
  quantization needs the right cache class up front). Compose them.

Auto-merged cleanly:
- `Libraries/MLXLLM/Models/MiMoV2Flash.swift`
- `Libraries/MLXLMCommon/KVCache.swift`
- `Libraries/MLXLMCommon/LanguageModel.swift`
- `Libraries/MLXVLM/Models/LFM2VL.swift`
- `Tests/Benchmarks/InferenceBenchmark.swift`

Bench log (`benchmarks/m1-max-64gb-2026-05-05.md`): took the incoming
side (PR 3's runs are the most recent in the chain).

Verification on the final branch:
- `swift build` clean.
- `make` clean (metallib copied to test bundle).
- `swift test --skip Benchmarks` passes 164 tests in 14 suites.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
… rewrite

The four spec 006 PRs (#163–#166) collectively make the breaking
changes for v4. This doc gives downstream consumers a single place to
look up what they need to change.

Coverage:

- **Type renames** (v3 names retired in PR #164's typealias removal):
  `KVCacheSimple` → `StandardKVCache`, `RotatingKVCache` →
  `StandardKVCache(maxSize:)` (windowed), `QuantizedKVCache` →
  `AffineQuantizedKVCache`, `TurboQuantKVCache` → `TurboQuantizedKVCache`,
  `MambaCache` → `SSMStateCache`, `ChunkedKVCache` deleted,
  `QuantizedKVCacheProtocol` removed.

- **Cache architecture**: introduces the two-axis model (`KVStorage` ×
  `KVEviction`), the `makeKVCache(scheme:eviction:)` factory, the
  `makeAttentionCache(parameters:maxSize:keep:)` thin helper used by
  every model factory, and the new `storageKind` protocol property
  for type dispatch.

- **`GenerateParameters` cleanup** (PR #165 + PR #166): four legacy
  fields (`kvBits` / `kvGroupSize` / `quantizedKVStart` / `kvScheme`)
  collapsed into one typed `compressionAlgorithm:
  KVCache.CompressionAlgorithm?`. New `draftCompressionAlgorithm`
  field for per-cache compression in speculative decoding.

- **`maybeQuantizeKVCache` deletion** (PR #166): every model factory
  constructs the right cache class up-front; the per-step swap is gone.

- **Persistence is unchanged**: on-disk class-name strings stay legacy
  (`"KVCache"`, `"RotatingKVCache"`, `"QuantizedKVCache"`,
  `"MambaCache"`) so v3-saved checkpoints continue to load. The loader
  maps each legacy name to the v4 concrete type.

- **Migration examples**: side-by-side v3-vs-v4 snippets for the four
  most common touchpoints — setting KV compression, parsing a CLI
  flag, type-checking a quantized cache, and writing a custom model
  factory. Plus the new speculative-decoding `draftCompressionAlgorithm`.

- **Removed APIs reference**: grep-able list of every v3 symbol
  (types, functions, fields) that no longer compiles in v4.

Wired into the docc index (`Articles` section) and the README's
`## Upgrading` section gets a `### Migrating to Version 4` subsection
above v3.

The README's existing `### Migrating to Version 3` link kept as-is —
v2-to-v3 is still a valid trail for callers further behind.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…lper

PR review feedback on #166: dropping the v3 "skip first 2 + last 2
attention layers under TurboQuant" behavior was the wrong call. Those
layers are the most PPL-sensitive; leaving them uncompressed costs
~2 layers' worth of KV bytes and preserves measurable quality.

Restoring the behavior, controllable per-call:

1. **`KVCache.CompressionAlgorithm.turbo` gains two parameters**:
   ```swift
   case turbo(
       keyBits: Int,
       valueBits: Int,
       skipBoundaryLayerCompression: Bool = true,
       boundaryLayersToSkip: Int = 2
   )
   ```
   Defaults match v3's `maybeQuantizeKVCache` (skip on, count = 2, with
   the small-model gate). The two knobs are separated — bool toggle +
   count — so the call site reads explicitly. Both are API-only; the
   wire-format string ("turbo4v2") continues to ignore them.

2. **`turboBoundarySkipSet(attentionLayerIndices:algorithm:)` helper
   in `MLXLMCommon/KVCacheTypes.swift`**: shared math for any model
   factory that constructs `TurboQuantizedKVCache`. Caller passes the
   ordered list of attention-layer indices (computed from its own
   layer-type discovery — Qwen 3.5 walks `model.layers`, NemotronH
   walks `hybridOverridePattern`), helper returns the subset to leave
   uncompressed. Empty when:
   - algorithm is nil or non-`.turbo`
   - `skipBoundaryLayerCompression` is `false`
   - `boundaryLayersToSkip` is `0`
   - `attentionLayerIndices.count < 4 * boundaryLayersToSkip` (small
     model — don't strip half the layers)

3. **`Qwen35.newCache` and `NemotronH.newCache` updated** to compute
   their attention-layer index list and call the helper. Boundary
   indices route to `makeAttentionCache(...)` (full-precision); the
   rest get `TurboQuantizedKVCache`. Today only these two models
   construct turbo caches, but any future factory that adds turbo
   support gets the same boundary-skip behavior by calling the helper.

4. **Tests**: 10 new unit tests in `Tests/MLXLMTests/KVCacheTests.swift`
   covering `turboBoundarySkipSet` end-to-end:
   - nil algorithm, `.none`/`.affine` algorithm → empty
   - `skipBoundaryLayerCompression: false` → empty
   - `boundaryLayersToSkip: 0` → empty
   - small-model gate (n < 4 * count) → empty
   - exactly-at-threshold (n = 4 * count) → activates
   - default config (count=2) on 16-layer model → {0, 1, 14, 15}
   - custom count=4 on 24-layer model → {0..3, 20..23}
   - sparse / non-contiguous attention indices (NemotronH-style hybrid
     pattern) → boundary set is by *attention-layer ordering*, not
     absolute cache position
   - empty input → empty

5. **`v3-to-v4-migration.md`** updated to document the new knobs and
   the helper.

Other minor follow-ups in this commit:
- `BenchmarkWriter.kvCacheStrategyLine` updated to `case let .turbo(
  keyBits, valueBits, _, _)` to match the new associated-value
  arity.
- `Qwen35` + `NemotronH` switch from per-element pattern matching
  back to using the `_, _` wildcards on `.turbo` since they now
  only need the bit widths (skip semantics are encapsulated in the
  helper).

Verification:
- `swift build` clean, `make` clean.
- `swift test --skip Benchmarks` passes 174 tests in 14 suites
  (was 164; +10 new boundary-skip tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski ekryski added the feature New feature (auto-applied from feat: prefix) label May 6, 2026
@ekryski
ekryski changed the base branch from ek/spec-006-pr3-self-transition to alpha May 6, 2026 06:17
@ekryski
ekryski merged commit f46f1b0 into alpha May 6, 2026
3 checks passed
ekryski added a commit that referenced this pull request May 6, 2026
GPT-OSS uses attention sinks. Turbo's compressed-domain decode path
(path B) doesn't handle sinks coherently yet; tracked as the four-repo
β-path stack in #130. The α-path runs sinks-bearing attention without
crashing (dequant V → standard SDPA fallback) but at valueBits=2 the
output is silently incoherent — Harmony channel markers (<|channel|>,
<|message|>) never appear, so downstream parsers see empty content.

Two things conspire to make this *no longer reproduce* on alpha
post-spec-006 (see PR #166):

  1. `maybeQuantizeKVCache` was deleted (PR 4); caches are now
     constructed up-front in each model's `newCache(parameters:)`.
  2. GPT-OSS's `newCache` calls `makeAttentionCache(...)`, which
     handles `.affine` and `.none` but falls through to StandardKVCache
     for `.turbo` — so turbo silently doesn't reach GPT-OSS even when
     requested.

Verified on the May 5 smoke log: `--kv turbo4v2` on GPT-OSS-20B emits
coherent Harmony output (`<|channel|>analysis<|message|>...`). The bug
described in #171 was a v3 codebase artifact.

This override makes the intent explicit at the model level so the
contract survives future refactors of `makeAttentionCache` or
GPT-OSS's `newCache`. Also lets `effectiveAlgorithm` (used for memory-
budget estimation in WiredMemoryUtils) skip turbo when sizing wired
memory tickets for GPT-OSS.

Closes #171. Path-B sinks β stack (#130) tracked separately.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 6, 2026
GPT-OSS uses attention sinks. Turbo's compressed-domain decode path
(path B) doesn't handle sinks coherently yet; tracked as the four-repo
β-path stack in #130. The α-path runs sinks-bearing attention without
crashing (dequant V → standard SDPA fallback) but at valueBits=2 the
output is silently incoherent — Harmony channel markers (<|channel|>,
<|message|>) never appear, so downstream parsers see empty content.

Two things conspire to make this *no longer reproduce* on alpha
post-spec-006 (see PR #166):

  1. `maybeQuantizeKVCache` was deleted (PR 4); caches are now
     constructed up-front in each model's `newCache(parameters:)`.
  2. GPT-OSS's `newCache` calls `makeAttentionCache(...)`, which
     handles `.affine` and `.none` but falls through to StandardKVCache
     for `.turbo` — so turbo silently doesn't reach GPT-OSS even when
     requested.

Verified on the May 5 smoke log: `--kv turbo4v2` on GPT-OSS-20B emits
coherent Harmony output (`<|channel|>analysis<|message|>...`). The bug
described in #171 was a v3 codebase artifact.

This override makes the intent explicit at the model level so the
contract survives future refactors of `makeAttentionCache` or
GPT-OSS's `newCache`. Also lets `effectiveAlgorithm` (used for memory-
budget estimation in WiredMemoryUtils) skip turbo when sizing wired
memory tickets for GPT-OSS.

Closes #171. Path-B sinks β stack (#130) tracked separately.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 6, 2026
feat(kvcache): spec 006 PR 4 — eliminate maybeQuantizeKVCache swap
ekryski added a commit that referenced this pull request May 12, 2026
…urface

IMPLEMENTATION-PLAN.md — perf backlog tables get a Status column:
- Six-emoji legend: 🟢/🔵/🟡/🟣/⚪/✅. Status applies per-row.
- Audited every issue (#61 / #73 / #74 / #77 / #89 / #114-#162) against
  GitHub. Found exactly one stale row: **#73 (KVCache refactor)** —
  already CLOSED on GitHub (spec 006 shipped via PRs #163-#166); the
  plan now reflects that. Every other row is OPEN with the appropriate
  blocked / investigation / re-bench / partial-progress sub-state.
- **#133 (prefix caching across sessions)** marked as partially
  addressed by spec 017 phase 4. Left a comment on the issue
  explaining the opaque-snapshot vs. zero-copy distinction and what's
  still pending (PagedKVCache + actor wrapping for concurrent serving).
  See issue thread.

documentation/generate-parameters.md — new spec 017 fields documented:
- New "Cross-request prefix KV cache (spec 017)" section covering
  `prefixCacheEnabled`, `prefixCachePolicy`, `prefixCacheModelID`,
  `prefixCacheDiskEnabled` — all default false / nil. Quick example
  showing a chat-mode setup with `FixedTrimPolicy(trimSuffix: 4)`.
- Extended the n-gram speculative section with `ngramDraftMin`,
  `ngramMinHits`, `minNgramSize` (which were missing from the public
  reference but shipped already).
- Added a "Prefix-cache env knobs" subsection covering
  `MLX_PREFIX_CACHE` / `MLX_PREFIX_CACHE_DISK` /
  `MLX_PREFIX_CACHE_DEBUG`.
- Cross-ref note on the n-gram + hybrid models section pointing at
  spec 020 coverage in speculative-decoding.md.

documentation/kv-cache.md — spec 020 + 017 user-facing surface:
- New "What's shipped recently" section covering spec 020
  (`StateReplayCache` protocol + `SSMStateCache` conformance +
  `canStateReplay` opt-out for Mamba) and spec 017 (cross-request
  prefix cache + quantisation-kind hydrate guard + opt-in L2 disk).
- Trimmable-cache section extended with a note on hybrid models'
  `canRollbackPromptCache(_:)` predicate.
- Cross-ref to the prefix-cache parameter section in
  generate-parameters.md so users don't manually thread caches across
  `generate(...)` calls when the prefix-cache opt-in does it
  transparently.

documentation/speculative-decoding.md — hybrid model coverage now live:
- Per-model table flipped Qwen 3.5 / 3.6 rows from "🔁 Auto-fallback"
  to "✅ Engages (spec 020)" with the measured 1.37x-1.64x numbers
  from PR #143 inlined. Mamba (Nemotron-H, Jamba) stays on auto-
  fallback per the per-cache `canStateReplay = false` opt-out.
- Compatibility-condition table updated to reference
  `canRollbackPromptCache(_:)` (the spec-020 predicate) instead of
  the legacy `canTrimPromptCache(_:)`.
- New "Hybrid model coverage (spec 020)" subsection explaining the
  `StateReplayCache` opt-in/opt-out model and how to set
  `canStateReplay` per-instance when wiring a new model factory.

Status-snapshot in the plan reflects the captured-reply bench numbers
(replaced the inflated stub-based ~10.9× headline with the honest
~4.3× number) and notes #73's closure.
ekryski added a commit that referenced this pull request May 12, 2026
…urface

IMPLEMENTATION-PLAN.md — perf backlog tables get a Status column:
- Six-emoji legend: 🟢/🔵/🟡/🟣/⚪/✅. Status applies per-row.
- Audited every issue (#61 / #73 / #74 / #77 / #89 / #114-#162) against
  GitHub. Found exactly one stale row: **#73 (KVCache refactor)** —
  already CLOSED on GitHub (spec 006 shipped via PRs #163-#166); the
  plan now reflects that. Every other row is OPEN with the appropriate
  blocked / investigation / re-bench / partial-progress sub-state.
- **#133 (prefix caching across sessions)** marked as partially
  addressed by spec 017 phase 4. Left a comment on the issue
  explaining the opaque-snapshot vs. zero-copy distinction and what's
  still pending (PagedKVCache + actor wrapping for concurrent serving).
  See issue thread.

documentation/generate-parameters.md — new spec 017 fields documented:
- New "Cross-request prefix KV cache (spec 017)" section covering
  `prefixCacheEnabled`, `prefixCachePolicy`, `prefixCacheModelID`,
  `prefixCacheDiskEnabled` — all default false / nil. Quick example
  showing a chat-mode setup with `FixedTrimPolicy(trimSuffix: 4)`.
- Extended the n-gram speculative section with `ngramDraftMin`,
  `ngramMinHits`, `minNgramSize` (which were missing from the public
  reference but shipped already).
- Added a "Prefix-cache env knobs" subsection covering
  `MLX_PREFIX_CACHE` / `MLX_PREFIX_CACHE_DISK` /
  `MLX_PREFIX_CACHE_DEBUG`.
- Cross-ref note on the n-gram + hybrid models section pointing at
  spec 020 coverage in speculative-decoding.md.

documentation/kv-cache.md — spec 020 + 017 user-facing surface:
- New "What's shipped recently" section covering spec 020
  (`StateReplayCache` protocol + `SSMStateCache` conformance +
  `canStateReplay` opt-out for Mamba) and spec 017 (cross-request
  prefix cache + quantisation-kind hydrate guard + opt-in L2 disk).
- Trimmable-cache section extended with a note on hybrid models'
  `canRollbackPromptCache(_:)` predicate.
- Cross-ref to the prefix-cache parameter section in
  generate-parameters.md so users don't manually thread caches across
  `generate(...)` calls when the prefix-cache opt-in does it
  transparently.

documentation/speculative-decoding.md — hybrid model coverage now live:
- Per-model table flipped Qwen 3.5 / 3.6 rows from "🔁 Auto-fallback"
  to "✅ Engages (spec 020)" with the measured 1.37x-1.64x numbers
  from PR #143 inlined. Mamba (Nemotron-H, Jamba) stays on auto-
  fallback per the per-cache `canStateReplay = false` opt-out.
- Compatibility-condition table updated to reference
  `canRollbackPromptCache(_:)` (the spec-020 predicate) instead of
  the legacy `canTrimPromptCache(_:)`.
- New "Hybrid model coverage (spec 020)" subsection explaining the
  `StateReplayCache` opt-in/opt-out model and how to set
  `canStateReplay` per-instance when wiring a new model factory.

Status-snapshot in the plan reflects the captured-reply bench numbers
(replaced the inflated stub-based ~10.9× headline with the honest
~4.3× number) and notes #73's closure.
@ekryski
ekryski deleted the ek/spec-006-pr4-eliminate-swap branch May 15, 2026 03:40
ekryski added a commit that referenced this pull request May 15, 2026
…to Tier 2 (#222)

* docs(specs + skills): refresh status against alpha (specs 040/041/043, spec 006/017/020/023 shipped; skills/kv-cache rewrite)

Spec status headers:
- 006: ✅ Shipped via PRs #163–#166 (KV cache type consolidation)
- 014/015/016/019/021/022: 🚧 Phase 1 scaffolds landed; phase 2+ open
- 017: ✅ All phases (1, 1B, 2, 3, 4, 5 Option A) shipped via #144 + #198
- 023: ✅ Phase 1 shipped via #154; Phase 3 subsumed by #153
- 041: ✅ Phases 1, 1.1, 1.2, 2, 4, 5 shipped via #212→#213→#214→#215;
  Phase 1.2 perf uplift moved to spec 042 Phase 1b; Phase 3 deferred
  to spec 039

IMPLEMENTATION-PLAN.md:
- Last-updated bump 2026-05-13 → 2026-05-14
- New 2026-05-14 update note covering the spec 040/041/6c/043 ship wave
- Row 6c (GPT-OSS sinks) rewritten with actual landing PRs (#213 + #215
  chain — prior row cited fabricated commit SHAs)
- Row 6d (spec 043) updated to "doc shipped via #219; impl not started"
- Spec 041 promoted from Tier 4 row 25 to Tier 2 row 10g (landed early
  as a gate-keeper for spec 040, Tier 1 row 6c, Gemma 4 KV-sharing
  fallback retirement, spec 042/043 kernel-uplift wave)
- Tier 4 renumbered: 042 is now row 25 (was row 26)
- Status snapshot rewritten: Tier 2 row 10g spec 041 ship state,
  Tier 1 row 6b spec 040 ship state, Tier 1 row 6d spec 043 doc ship,
  expanded closed-issue list, new Kernel-uplift-wave priority bullet
- Dependency graph: spec 040 reframed from "future work" to "shipped";
  spec 017 phase 3 marked shipped
- Issue #185 marked ✅ CLOSED (was 🟡 OPEN); resolution path cited
- Issue #77 cross-linked to #160 + spec 043 Phase 1
- Issue #61 confirmed still relevant
- Fixed stale "Tier 4 row 26 spec 042" refs across the doc to "Tier 4 row 25"

Skills directory:
- references/kv-cache.md: major rewrite. Old text had AffineQuantizedKVCache
  as "unbounded only" (now rotating-window via spec 041 phase 1.2),
  TurboQuantizedKVCache windowed eviction "until #185 is fixed" (#185
  closed 2026-05-12), stale "Gemma 4 produces incoherent output under
  windowed turbo", wrong makeAttentionCache signature. Added sections
  for AffineSDPAStrategy + MLX_AFFINE_SDPA env var, useBias/DC-bias
  correction, TurboFlash A/B decode paths, state-replay rollback
  (specs 020 + 040), cross-request prefix cache (spec 017),
  prefillStep parameter threading.
- references/supported-models.md: GPT-OSS row no longer claims
  supportsTurboQuantization: false; documents DC-bias + hybrid
  sliding-FP16 policy + turbo_flash_sdpa_v sinks kernel.
- SKILL.md: GenerateParameters maxKVSize comment updated to reflect
  uniform rotating-eviction across .none/.affine/.turbo; added
  prefixCacheEnabled to example + Optional Configuration table.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(specs): bulletize Status / Branch / Depends-on frontmatter blocks

Convert the **Field:** paragraph blocks at the top of each spec to a bullet
list (`- **Field:** ...`). Same content, easier to scan — fields render as
a unified list instead of stacked bold-prefix lines.

Sub-bullets under "Depends on:" indent under their parent. Wrapped
continuation lines indent to align with the bullet body.

Spec 040 also restructured: the multi-paragraph ship details that lived
under the Status field moved to a new "## Ship details (2026-05-13)"
section below the metadata bullets, so Status / Branch / Depends-on
form a clean top-of-file block.

Spec 020 closed the blank line that separated Status from Branch so the
metadata renders as a single tight bullet list.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
* ci: build the fork and run its Metal test suites

Add the Fork Tests workflow. It builds the package on a macos-26
runner, builds the full MLX Metal library with cmake, copies it next
to the test binaries, and runs six CBv2 paged suites one step each.
A suite step fails when the suite executes zero tests or skips a test.

Port the scripts from d-inference and add them to fork.yaml.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: remove the empty GPU listing from Fork Tests

system_profiler SPDisplaysDataType prints nothing on the hosted
macos-26 VM. The CPU, memory and disk lines stay.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: select the newest release of Xcode 26 in Fork Tests

Pick the newest Xcode_26.x app whose name is only a version number.
Beta and release candidate apps are left out, so a new beta on the
runner image cannot change CI without a pull request. The step still
fails when the selected Swift is older than 6.3.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: correct the Metal library notes in build-metallib.sh

swift build makes no Metal library. The pinned mlx-swift excludes the
MLX kernel sources and nojit_kernels.cpp from Cmlx, so SwiftPM builds
MLX in JIT mode, and every MLX operation traps without a staged
mlx.metallib. The partial 459-symbol library comes from xcodebuild,
which this workflow does not use.

State that the 10,000-symbol floor rejects a JIT-mode or incomplete
cmake build.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: key the SwiftPM cache on the commit and clean it before saving

End the cache key with the commit SHA, as d-inference does, so each
push to main saves a new entry. The prefix restore key still restores
the newest entry for the same Xcode.

Before the save, delete the staged mlx.metallib copies and the
coverage data, so the cache keeps only SwiftPM output.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: fix wording in the Fork Tests files

- run-nested-suite.sh: the suites need no model weights, but one test
  needs DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST=1, which the caller sets.
- fork-tests.yml: runs on main are not cancelled once they start.
- Say "self-contained" instead of "hermetic" in the workflow and in
  fork.yaml.
- fork.yaml: write the Fork Tests paragraph as one sentence per line,
  so later pull requests can add a sentence without touching the same
  lines.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test: hold the hog in the waiting-queue backstop test

testWaitingQueueBackstopEmitsCanonicalQueueFullMarker polled every
5 ms for the hog request to show as running, but the hog finished its
60 scripted tokens in milliseconds. A late poll missed the window and
the test failed after 10 s (Fork Tests run 36182132297, attempt 1).

Set eventBufferCapacity to 4, as testDuplicateSubmitThrowsAndFirst-
StreamStillDelivers does. The unread hog stream hits backpressure, so
the hog pauses with its slot retained until the test drains it. The
wait now also requires the hog to be paused. Only this test changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* style: format CBv2SchedulerLoopTests.swift

Run swift format format with .swift-format on the whole file, so the
format check of ekryski#160 passes. It changes four places outside the
backstop test: two nested CBv2Request calls and three comment
alignments in CBv2EngineLoopConfig arguments. No code changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: run the scheduler loop suite through the no-skip runner

Add a Fork Tests step that runs CBv2SchedulerLoopTests with
scripts/run-nested-suite.sh, after the six Metal suites. The step
fails when the class executes zero tests or skips a test, so CI runs
the backstop fix instead of only compiling it.

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

* test: make the capacity-loser scheduler test deterministic

testCapacityLoserIsRequeuedNotErrored minted its two requests inside
two async let children. Both children increment the unsynchronized
CBv2SchedFixtures.nextID at the same time, so both requests can get
the same id. The second submit then throws duplicateRequestID. XCTest
reports the last error thrown during the test, which is the
CancellationError from the cbv2SchedCollect watchdog sleep, so the
failure showed as "CancellationError" at CBv2SchedulerTestSupport.swift:533.

The test now mints and submits both requests on its own task. It also
holds the step loop until both requests wait, so both requests compete
for the single KV slot in the same step and the requeue always happens.

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

* test: release the step gate if a submit throws

A defer releases suspendStepExecutionAtCountForTesting on the engine
queue, so a throwing submit in testCapacityLoserIsRequeuedNotErrored
cannot leave the step loop held.

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

* test: mint fixture request ids under a lock

CBv2SchedFixtures.request incremented a static counter and read it
again. Concurrent callers could get the same id. An NSLock now does the
increment and the read in one step. The comment no longer says that ids
come from the main thread.

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

* test: drop the stale id race from the capacity-loser comment

The fixture now mints ids under a lock, so minting in two async let
children no longer races. The comment keeps the reason that stays true:
the test holds the step loop so both requests wait. nextID is now
private, so no caller can bypass the lock.

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature (auto-applied from feat: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant