Skip to content
Closed
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
2 changes: 1 addition & 1 deletion Libraries/MLXLLM/Models/NemotronH.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1691,7 +1691,7 @@ public class NemotronHModel:
/// caches. This performs no eval and never installs probe state in a
/// serving request. Packed integer embedding weights are not activation
/// dtypes, and Mamba's fp32 path can promote later attention layers.
func observedAttentionKVDTypes() -> [DType]? {
public func observedAttentionKVDTypes() -> [DType]? {
let caches = newCache(parameters: nil)
_ = backbone(MLXArray([0]).reshaped(1, 1), cache: caches)
var result: [DType] = []
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import Cmlx
import MLX
import MLXLMCommon

/// Durable prompt-history checkpoints of the Super assistant, for complete
/// (SSD) prefix checkpoints. A checkpoint at `count` target inputs is a
/// `PrefixCheckpoint`: the FP8 history codes of every whole
/// `historyChunkRows` block, the queued partial block and the frontier. The
/// split depends only on `count`, so the tensor layout does too. The codes
/// are stored widened to float16 integers in 0...255, which is exact: the
/// generic recurrent manifest admits only floating assistant tensors. Decode
/// checks every value before narrowing it back, so a restored request writes
/// the same codes, and the mirror decoded from them, as the request the
/// checkpoint was taken from.
extension NemotronSuperMTPAssistant: CBv2MTPPrefixCheckpointCoding {
public var prefixCheckpointCodecID: String {
let c = target.configuration
let (heads, headDim) = historyGeometry
return "nemotron-super-mtp-fp8-history-v1:h\(c.hiddenSize):v\(c.vocabSize)"
+ ":kv\(heads)x\(headDim):rows\(workspace.graph.historyChunkRows)"
+ ":\(head.weightDType):codes-f16"
}

/// K and V codes when whole blocks were drained (layer tags 0 and 1 keep
/// the two roles distinct), the queued pairs when any, then the frontier.
public func prefixCheckpointTensorDescriptors(targetInputCount count: Int)
-> [CBv2CheckpointTensorDescriptor]?
{
guard let split = historySplit(targetInputCount: count),
let activation = CBv2CheckpointDType(head.weightDType), activation.isFloatingPoint
else { return nil }
let width = target.configuration.hiddenSize
let (heads, headDim) = historyGeometry
var descriptors: [CBv2CheckpointTensorDescriptor] = []
do {
if split.drained > 0 {
for layer in 0 ..< 2 {
descriptors.append(
try .init(
role: .assistantHidden, layer: layer,
shape: [1, heads, split.drained, headDim], dtype: .float16))
}
}
if split.queued > 0 {
descriptors.append(
try .init(
role: .assistantHidden, shape: [1, split.queued, width], dtype: activation))
descriptors.append(
try .init(role: .assistantTokens, shape: [1, split.queued], dtype: .int32))
}
descriptors.append(
try .init(role: .assistantFrontier, shape: [1, 1, width], dtype: activation))
} catch {
return nil
}
return descriptors
}

public func encodePrefixCheckpoint(_ checkpoint: any CBv2MTPPrefixCheckpoint) -> [MLXArray]? {
guard let checkpoint = checkpoint as? PrefixCheckpoint,
checkpoint.owner == ObjectIdentifier(self),
let descriptors = prefixCheckpointTensorDescriptors(
targetInputCount: checkpoint.targetInputCount)
else { return nil }
let arrays =
checkpoint.codes.map { $0.asType(.float16) }
+ [checkpoint.hidden, checkpoint.tokens, checkpoint.frontier].compactMap { $0 }
return Self.conforms(arrays, to: descriptors) ? arrays : nil
}

/// The arrays are the evaluated host buffers of an authenticated import.
/// Nil unless they match this assistant's layout at `prefixTokens.count`,
/// every code is an integer in 0...255 and the queued tokens are the
/// prompt's own.
public func decodePrefixCheckpoint(tensors: [MLXArray], prefixTokens: [Int])
-> (any CBv2MTPPrefixCheckpoint)?
{
let count = prefixTokens.count
guard let split = historySplit(targetInputCount: count),
let descriptors = prefixCheckpointTensorDescriptors(targetInputCount: count),
Self.conforms(tensors, to: descriptors),
prefixTokens.allSatisfy({ $0 >= 0 && $0 < target.configuration.vocabSize })
else { return nil }
var cursor = 0
var codes: [MLXArray] = []
if split.drained > 0 {
for _ in 0 ..< 2 {
guard let narrowed = Self.narrowedCodes(tensors[cursor]) else { return nil }
codes.append(narrowed)
cursor += 1
}
}
var hidden: MLXArray?
var tokens: MLXArray?
if split.queued > 0 {
// Pair i holds input i + 1: the queue starts after the drained pairs.
guard Self.tokens(tensors[cursor + 1], equal: prefixTokens[(split.drained + 1)...])
else { return nil }
hidden = tensors[cursor]
tokens = tensors[cursor + 1]
cursor += 2
}
return PrefixCheckpoint(
owner: ObjectIdentifier(self), targetInputCount: count, codes: codes,
hidden: hidden, tokens: tokens, frontier: tensors[cursor])
}

private var historyGeometry: (heads: Int, headDim: Int) {
let c = target.configuration
return (c.numKeyValueHeads, c.headDim ?? (c.hiddenSize / c.numAttentionHeads))
}

/// Pairs drained into whole history blocks, and pairs still queued, at
/// `count` target inputs: the invariant `capturePrefixCheckpoint` holds.
private func historySplit(targetInputCount count: Int) -> (drained: Int, queued: Int)? {
let chunk = workspace.graph.historyChunkRows
guard count > 1, chunk > 0 else { return nil }
let pairs = count - 1
return (pairs / chunk * chunk, pairs % chunk)
}

private static func conforms(
_ arrays: [MLXArray], to descriptors: [CBv2CheckpointTensorDescriptor]
) -> Bool {
arrays.count == descriptors.count
&& zip(arrays, descriptors).allSatisfy {
$0.shape == $1.shape && $0.dtype == $1.dtype.mlxDType
}
}

/// The uint8 codes of a widened tensor, read from its evaluated host
/// buffer without GPU work; nil unless every value is an integer in 0...255.
private static func narrowedCodes(_ widened: MLXArray) -> MLXArray? {
guard widened.dtype == .float16, let info = try? widened.evaluatedBufferInfo(),
info.isRowContiguous, info.dataElements == widened.size,
let pointer = mlx_array_data_float16(widened.ctx)
else { return nil }
return withExtendedLifetime(widened) {
var codes = [UInt8](repeating: 0, count: widened.size)
for index in 0 ..< widened.size {
let value = Float(pointer[index])
guard value >= 0, value <= 255, value == value.rounded() else { return nil }
codes[index] = UInt8(value)
}
return MLXArray(codes, widened.shape)
}
}

private static func tokens(_ tokens: MLXArray, equal expected: ArraySlice<Int>) -> Bool {
guard tokens.size == expected.count, let info = try? tokens.evaluatedBufferInfo(),
info.isRowContiguous, info.dataElements == tokens.size,
let pointer = mlx_array_data_int32(tokens.ctx)
else { return false }
return withExtendedLifetime(tokens) {
for (index, token) in expected.enumerated() where Int(pointer[index]) != token {
return false
}
return true
}
}
}
3 changes: 2 additions & 1 deletion Libraries/MLXVLM/Models/NemotronSuperMTPTextTarget.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class NemotronSuperMTPTextTarget: Module, LanguageModel,
CBv2RecurrentLanguageModelForwardable, CBv2RecurrentLanguageModelPrefillForwardable,
CBv2RecurrentMTPForwardable, CBv2RecurrentPrefillHiddenForwardable,
CBv2CausalPositionRequirementProviding, CBv2MTPPolicyTopTwoProviding,
CBv2RecurrentMTPRequestScopedMediaFallback
CBv2RecurrentMTPRequestScopedMediaFallback, CBv2CompleteCheckpointKVTypeProviding
{
@ModuleInfo public var base: NemotronSuperRecurrentAdapter

Expand Down Expand Up @@ -55,6 +55,7 @@ public class NemotronSuperMTPTextTarget: Module, LanguageModel,
public var cbv2LayerKinds: [CBv2LayerKind] { base.cbv2LayerKinds }
public var cbv2SupportsPackedPrefill: Bool { false }
public var calibratedPrefillTokenLimit: Int? { base.calibratedPrefillTokenLimit }
public var cbv2CompleteCheckpointKVDTypes: [DType]? { base.cbv2CompleteCheckpointKVDTypes }

public func newCache(parameters: GenerateParameters?) -> [KVCache] {
base.newCache(parameters: parameters)
Expand Down
39 changes: 26 additions & 13 deletions Libraries/MLXVLM/Models/NemotronSuperRecurrentAdapter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ public final class NemotronSuperRecurrentAdapter: Module, LanguageModel,
/// `cbv2RecurrentStateSpec`, resolved once: the language model derives it
/// from a lazy probe forward of the whole trunk (no evaluation, but a full
/// graph construction), and the engine reads it on every step.
private let recurrentSpec = NemotronSuperRecurrentSpecCache()
private let recurrentSpec = NemotronSuperProbeCache<CBv2RecurrentStateSpec>()
/// `cbv2CompleteCheckpointKVDTypes`, resolved once by the same kind of probe.
private let attentionKVDTypes = NemotronSuperProbeCache<[DType]?>()
public enum Failure: Error { case position, batch, recurrentOwnership, caches }

/// How a decode step with several rows computes its products.
Expand Down Expand Up @@ -225,21 +227,32 @@ public final class NemotronSuperRecurrentAdapter: Module, LanguageModel,
}
}

/// One adapter's recurrent-state spec, computed on first use and then
/// returned as is. The engine asks for the spec on its hot paths (every
/// forward, plan and MTP eligibility check), while the language model
/// resolves it from a lazy probe forward of the whole trunk; the result
/// depends only on the loaded configuration and projection types.
final class NemotronSuperRecurrentSpecCache: @unchecked Sendable {
/// One adapter's value that the language model resolves from a lazy probe
/// forward of the whole trunk (the recurrent-state spec, the attention KV
/// types), computed on first use, nil included, and then returned as is. The
/// engine asks for the spec on its hot paths (every forward, plan and MTP
/// eligibility check); each value depends only on the loaded configuration
/// and projection types.
final class NemotronSuperProbeCache<Value>: @unchecked Sendable {
private let lock = NSLock()
private var spec: CBv2RecurrentStateSpec?
private var resolved: Value?

func value(_ compute: () -> CBv2RecurrentStateSpec) -> CBv2RecurrentStateSpec {
func value(_ compute: () -> Value) -> Value {
lock.lock()
defer { lock.unlock() }
if let spec { return spec }
let resolved = compute()
spec = resolved
return resolved
if let resolved { return resolved }
let value = compute()
resolved = value
return value
}
}

/// Complete checkpoints store the attention KV at the loaded composite's own
/// types: the engine builds the durable codec only when they equal its paged
/// pool's observed layer types, and the host binds them into the checkpoint
/// identity. Opting into exact prefix reuse is still `exactPrefixCheckpoints`.
extension NemotronSuperRecurrentAdapter: CBv2CompleteCheckpointKVTypeProviding {
public var cbv2CompleteCheckpointKVDTypes: [DType]? {
attentionKVDTypes.value { composite.languageModel.observedAttentionKVDTypes() }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import Foundation
import MLX
import MLXNN
import Testing

@testable import MLXLLM
@testable import MLXLMCommon
@testable import MLXVLM

/// The Super assistant's durable prompt-history codec on synthetic weights: a
/// checkpoint encoded to its declared tensors, carried through host bytes as a
/// complete SSD checkpoint is, decodes to the same codes and queue, and a
/// request restored from it drafts exactly as the cold one. Decode refuses a
/// foreign prompt, a code that is not an integer byte and a mismatched layout.
/// The adapter and the MTP target declare their attention KV types.
@Suite(.tags(.integration))
struct NemotronSuperMTPCompleteCheckpointTests {
typealias Fixture = NemotronSuperMTPFixture
typealias Tests = NemotronSuperMTPAssistantTests

static let prompt = (0 ..< 23).map { ($0 * 3 + 7) % 60 + 1 }

/// Each array through host bytes, as an authenticated import yields it.
static func throughHost(_ arrays: [MLXArray]) -> [MLXArray] {
eval(arrays)
return arrays.map { MLXArray($0.asData(access: .copy).data, $0.shape, dtype: $0.dtype) }
}

@Test(arguments: [9, 16, 17, 20])
func encodedCheckpointRestoresThroughHostBytesExactly(count: Int) throws {
let stack = try Fixture.stack(kind: .random, depth: 2)
let assistant = stack.assistant
let hidden = Tests.rows(Self.prompt.count, seed: 61)
func observe(_ state: any CBv2MTPRequestState, _ range: Range<Int>) {
assistant.observeCommittedTarget(
.init(
tokens: Tests.tokens(Array(Self.prompt[range])),
hidden: hidden[0..., range, 0...]),
requestState: state)
}
func finish(_ state: any CBv2MTPRequestState) throws -> [MLXArray] {
let draft = assistant.draftStep(
tokens: Tests.tokens([5]), hidden: hidden[0..., 22 ..< 23, 0...], shortlist: nil,
requestState: state)
eval([draft.tokens, draft.hidden] + assistant.evaluationTargets(for: state))
return [draft.tokens, draft.hidden]
+ (try #require(try Tests.typed(state).history)).committedCodes()
}
let cold = assistant.makeRequestState()
try assistant.configureRequestState(cold, maximumSequenceLength: 64)
observe(cold, 0 ..< 5)
observe(cold, 5 ..< count)
let checkpoint = try #require(
assistant.capturePrefixCheckpoint(requestState: cold, targetInputCount: count))
let descriptors = try #require(
assistant.prefixCheckpointTensorDescriptors(targetInputCount: count))
let drained = (count - 1) / 8 * 8
let queued = (count - 1) % 8
#expect(descriptors.count == (drained > 0 ? 2 : 0) + (queued > 0 ? 2 : 0) + 1)
let encoded = try #require(assistant.encodePrefixCheckpoint(checkpoint))
#expect(encoded.count == descriptors.count)
for (array, descriptor) in zip(encoded, descriptors) {
#expect(array.shape == descriptor.shape && array.dtype == descriptor.dtype.mlxDType)
}
// Widened codes cost two bytes per code; the queue keeps its types.
#expect(
descriptors.reduce(0) { $0 + $1.byteCount }
== 2 * 2 * drained * 16 + queued * (Fixture.hidden * 4 + 4) + Fixture.hidden * 4)
let decoded = try #require(
assistant.decodePrefixCheckpoint(
tensors: Self.throughHost(encoded),
prefixTokens: Array(Self.prompt.prefix(count)))
as? NemotronSuperMTPAssistant.PrefixCheckpoint)
let original = try #require(checkpoint as? NemotronSuperMTPAssistant.PrefixCheckpoint)
eval(original.evaluationTargets)
Tests.exact(decoded.evaluationTargets, original.evaluationTargets)
#expect(decoded.targetInputCount == count && decoded.historyRows == drained)

observe(cold, count ..< 23)
let expected = try finish(cold)
let restored = try #require(assistant.restorePrefixCheckpoint(decoded))
try assistant.configureRequestState(restored, maximumSequenceLength: 64)
#expect(try Tests.typed(restored).history?.offset == drained)
observe(restored, count ..< 23)
Tests.exact(try finish(restored), expected)
assistant.releaseRequestState(cold)
assistant.releaseRequestState(restored)
}

@Test func decodeRefusesForeignPromptsCodesAndLayouts() throws {
let stack = try Fixture.stack(kind: .random, depth: 2)
let assistant = stack.assistant
let count = 20
let hidden = Tests.rows(Self.prompt.count, seed: 62)
let state = assistant.makeRequestState()
try assistant.configureRequestState(state, maximumSequenceLength: 64)
assistant.observeCommittedTarget(
.init(
tokens: Tests.tokens(Array(Self.prompt.prefix(count))),
hidden: hidden[0..., 0 ..< count, 0...]),
requestState: state)
let checkpoint = try #require(
assistant.capturePrefixCheckpoint(requestState: state, targetInputCount: count))
let encoded = Self.throughHost(try #require(assistant.encodePrefixCheckpoint(checkpoint)))
let prefix = Array(Self.prompt.prefix(count))
#expect(assistant.decodePrefixCheckpoint(tensors: encoded, prefixTokens: prefix) != nil)
// A queued token that is not the prompt's own.
var foreign = prefix
foreign[count - 1] = (foreign[count - 1] % 60) + 1
#expect(assistant.decodePrefixCheckpoint(tensors: encoded, prefixTokens: foreign) == nil)
// A widened code that is not an integer byte.
var corrupt = encoded
corrupt[0] = Self.throughHost([encoded[0] + MLXArray(Float16(0.5))])[0]
#expect(assistant.decodePrefixCheckpoint(tensors: corrupt, prefixTokens: prefix) == nil)
corrupt[0] = Self.throughHost([encoded[0] + MLXArray(Float16(256))])[0]
#expect(assistant.decodePrefixCheckpoint(tensors: corrupt, prefixTokens: prefix) == nil)
// Another count's layout, and a missing tensor.
#expect(
assistant.decodePrefixCheckpoint(
tensors: encoded, prefixTokens: Array(prefix.prefix(17))) == nil)
#expect(
assistant.decodePrefixCheckpoint(
tensors: Array(encoded.dropLast()), prefixTokens: prefix) == nil)
// No layout below two inputs.
#expect(assistant.prefixCheckpointTensorDescriptors(targetInputCount: 1) == nil)
assistant.releaseRequestState(state)
}

/// Complete checkpoints keep the attention KV at the composite's own
/// types, which the plain adapter and the MTP target declare alike.
@Test func adapterAndTargetDeclareTheirAttentionKVTypes() throws {
let stack = try Fixture.stack(kind: .random, depth: 2)
let adapter = try NemotronSuperRecurrentAdapter(
stack.model, maximumDecodeRows: 1, exactPrefixCheckpoints: true)
let types = try #require(adapter.cbv2CompleteCheckpointKVDTypes)
#expect(types.count == adapter.cbv2LayerKinds.count && !types.isEmpty)
#expect(types == stack.model.languageModel.observedAttentionKVDTypes())
let target = try NemotronSuperMTPTextTarget(
stack.model, maximumRequests: 1, exactPrefixCheckpoints: true)
#expect(target.cbv2CompleteCheckpointKVDTypes == types)
#expect(
stack.assistant.prefixCheckpointCodecID.hasPrefix("nemotron-super-mtp-fp8-history-v1:"))
}
}
Loading
Loading