Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,11 @@ public final class EngineV2: CBv2Engine, CBv2NativeWorkShutdownReporting, @unche
public func selectiveKVStatistics() -> CBv2SelectiveKVStatistics? {
(backend as? CBv2ContiguousKVBackend)?.selectiveKVStatistics
}
/// Immutable experiment configuration; observing it does not read live rows.
@_spi(Diagnostics)
public func selectiveKVPolicy() -> CBv2SelectiveKVPolicy? {
(backend as? CBv2ContiguousKVBackend)?.config.selectiveRetention
}
let schedulerConfig: CBv2SchedulerConfig
private let loopConfig: CBv2EngineLoopConfig
private let gauges: CBv2EngineGauges
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,31 @@ public struct CBv2SelectiveKVPolicy: Sendable, Equatable {
public let chunkTokens: Int
public let pruneInterval: Int
public let anchorTokens: Int
/// A separately qualified instruction prefix, bounded independently of
/// sink anchors. Zero preserves the original half-retention experiment.
public let protectedPrefixTokens: Int
public static let maximumProtectedPrefixTokens = 256

public init(
olderHistoryFraction: Double = 0.5, recentTokens: Int = 512,
minimumTokens: Int = 4096, chunkTokens: Int = 16,
pruneInterval: Int = 256, anchorTokens: Int = 4
pruneInterval: Int = 256, anchorTokens: Int = 4,
protectedPrefixTokens: Int = 0
) {
precondition(
olderHistoryFraction.isFinite && olderHistoryFraction > 0
&& olderHistoryFraction <= 1)
precondition(
recentTokens > 0 && minimumTokens > recentTokens
&& chunkTokens > 0 && pruneInterval > 0 && anchorTokens >= 0)
precondition((0 ... Self.maximumProtectedPrefixTokens).contains(protectedPrefixTokens))
self.olderHistoryFraction = olderHistoryFraction
self.recentTokens = recentTokens
self.minimumTokens = minimumTokens
self.chunkTokens = chunkTokens
self.pruneInterval = pruneInterval
self.anchorTokens = anchorTokens
self.protectedPrefixTokens = protectedPrefixTokens
}
}

Expand Down Expand Up @@ -118,13 +125,14 @@ final class CBv2SelectiveSequenceKV: CBv2SequenceKV, CBv2InnerStateProviding {
absoluteOffset >= policy.minimumTokens,
lastPruneOffset == 0 || absoluteOffset - lastPruneOffset >= policy.pruneInterval
else { return }
let anchorCount = min(policy.anchorTokens, retainedCount)
let protectedCount = min(
max(policy.anchorTokens, policy.protectedPrefixTokens), retainedCount)
let olderChunkCount = max(
0,
(retainedCount - anchorCount - policy.recentTokens)
(retainedCount - protectedCount - policy.recentTokens)
/ policy.chunkTokens)
let olderTokenBudget = Int(
Double(max(0, absoluteOffset - anchorCount - policy.recentTokens))
Double(max(0, absoluteOffset - protectedCount - policy.recentTokens))
* policy.olderHistoryFraction)
let retainedChunkCount = min(olderChunkCount, olderTokenBudget / policy.chunkTokens)
guard olderChunkCount > 0, retainedChunkCount > 0, retainedChunkCount < olderChunkCount
Expand All @@ -137,7 +145,7 @@ final class CBv2SelectiveSequenceKV: CBv2SequenceKV, CBv2InnerStateProviding {
queries: queries, keys: history.keys,
scale: scale, sinks: sinks, softcap: softcap)
let indices = retainedIndices(
importance: importance, anchorCount: anchorCount,
importance: importance, protectedCount: protectedCount,
olderChunkCount: olderChunkCount,
retainedChunkCount: retainedChunkCount)
// take owns compact buffers: slicing alone would keep the dense source.
Expand Down Expand Up @@ -189,10 +197,10 @@ final class CBv2SelectiveSequenceKV: CBv2SequenceKV, CBv2InnerStateProviding {
}

private func retainedIndices(
importance: MLXArray, anchorCount: Int, olderChunkCount: Int, retainedChunkCount: Int
importance: MLXArray, protectedCount: Int, olderChunkCount: Int, retainedChunkCount: Int
) -> MLXArray {
let tailStart = anchorCount + olderChunkCount * policy.chunkTokens
let chunkScores = importance[anchorCount ..< tailStart]
let tailStart = protectedCount + olderChunkCount * policy.chunkTokens
let chunkScores = importance[protectedCount ..< tailStart]
.reshaped([olderChunkCount, policy.chunkTokens]).sum(axis: 1)
// Spend one quarter of the retained budget on evenly-spaced coverage.
// Attention scoring cannot predict a later question's evidence needs.
Expand All @@ -206,10 +214,10 @@ final class CBv2SelectiveSequenceKV: CBv2SequenceKV, CBv2InnerStateProviding {
let offsets = MLXArray(0 ..< policy.chunkTokens)
let selected =
(selectedChunks[0..., .newAxis] * policy.chunkTokens
+ offsets[.newAxis, 0...] + anchorCount).reshaped([-1])
+ offsets[.newAxis, 0...] + protectedCount).reshaped([-1])
return concatenated(
[
MLXArray(0 ..< anchorCount), selected, MLXArray(tailStart ..< retainedCount),
MLXArray(0 ..< protectedCount), selected, MLXArray(tailStart ..< retainedCount),
], axis: 0)
}
}
Expand Down
71 changes: 71 additions & 0 deletions Tests/MLXLMTests/CBv2InstructionPrefixRetentionTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import MLX
import Testing

@testable import MLXLMCommon

@Suite("CBv2 protected instruction prefix", .serialized)
struct CBv2InstructionPrefixRetentionTests {
private func row(prefix: Int) -> CBv2SelectiveSequenceKV {
CBv2SelectiveSequenceKV(
promptLength: 2048, maxLength: 4096,
kvHeads: 1, headDim: 1, valueHeadDim: 1,
policy: .init(minimumTokens: 1024, protectedPrefixTokens: prefix))
}

private func positions(_ range: Range<Int>) -> MLXArray {
MLXArray(range.map(Float.init)).reshaped([1, 1, range.count, 1])
}

@Test func prefixSurvivesRankedPruningRepeatedUpdatesAndRejection() {
let ordinary = row(prefix: 0)
let protected = row(prefix: 128)
let query = MLXArray.ones([1, 1, 1, 1])
for state in [ordinary, protected] {
_ = state.update(keys: positions(0 ..< 2048), values: positions(0 ..< 2048))
state.prepareForAttention(queries: query, scale: 0.01, sinks: nil, softcap: nil)
}
let original = ordinary.snapshot().keys.asArray(Float.self).map(Int.init)
#expect(!Set(0 ..< 128).isSubset(of: Set(original)))
var kept = protected.snapshot().keys.asArray(Float.self).map(Int.init)
#expect(Array(kept.prefix(128)) == Array(0 ..< 128))
#expect(kept == kept.sorted() && Set(kept).count == kept.count)
#expect(Array(kept.suffix(512)) == Array(1536 ..< 2048))

_ = protected.update(keys: positions(2048 ..< 2304), values: positions(2048 ..< 2304))
protected.prepareForAttention(queries: query, scale: 0.01, sinks: nil, softcap: nil)
#expect(protected.statistics.pruningEvents == 2)
#expect(protected.absoluteOffset == 2304)
kept = protected.snapshot().keys.asArray(Float.self).map(Int.init)
#expect(Array(kept.prefix(128)) == Array(0 ..< 128))
#expect(Array(kept.suffix(512)) == Array(1792 ..< 2304))
let confirmed = protected.snapshot().keys.asArray(Float.self)
protected.beginSpeculativeWrite()
_ = protected.update(keys: positions(2304 ..< 2307), values: positions(2304 ..< 2307))
protected.prepareForAttention(queries: query, scale: 0.01, sinks: nil, softcap: nil)
protected.rollback(3)
protected.commitSpeculativeWrite()
#expect(protected.statistics.pruningEvents == 2)
#expect(protected.absoluteOffset == 2304)
#expect(protected.snapshot().keys.asArray(Float.self) == confirmed)
}

@Test func boundedProtectionKeepsNativeAdmissionReservation() throws {
#expect(CBv2SelectiveKVPolicy().protectedPrefixTokens == 0)
#expect(CBv2SelectiveKVPolicy.maximumProtectedPrefixTokens == 256)
let kind = CBv2LayerKind(attention: .full, headDim: 1, kvHeads: 1, queryHeads: 1)
let dense = CBv2ContiguousKVBackend(config: .init(bytesCapacity: 1 << 20))
let protected = CBv2ContiguousKVBackend(
config: .init(
bytesCapacity: 1 << 20,
selectiveRetention: .init(protectedPrefixTokens: 256)))
let denseRows = try dense.makeSequenceState(
layerKinds: [kind], promptLength: 2048, maxLength: 4096)
let protectedRows = try protected.makeSequenceState(
layerKinds: [kind], promptLength: 2048, maxLength: 4096)
#expect(dense.bytesReserved == protected.bytesReserved)
#expect(protected.prefixReuseBackend == .unknown)
dense.release(denseRows)
protected.release(protectedRows)
#expect(protected.bytesReserved == 0)
}
}
3 changes: 3 additions & 0 deletions fork.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ def:
mass plus coverage. Original absolute positions and native windows remain
intact; exact prefix reuse and MTP are fenced. Provider activation remains
benchmark-only pending quality and transient-allocation qualification.
A separate typed instruction-prefix budget is capped at 256 tokens;
its fixed 128-token benchmark candidate preserves early structured
headers while keeping the original half policy unchanged.
globs:
- "Libraries/MLXLMCommon/ContinuousBatchingV2/*.swift"
- "Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/**"
Expand Down
Loading