From 3c793c4cb0b2d897d92415f1bd519237e4c0bb67 Mon Sep 17 00:00:00 2001
From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com>
Date: Tue, 24 Nov 2026 08:50:14 +0100
Subject: [PATCH 1/2] feat(bailing_hybrid): implement Ling-3.0 KDA + MLA hybrid
MoE P0 (#672)
---
.../Chat/BailingHybridProfile.swift | 45 +++
Sources/BasaltCore/Chat/ModelProfile.swift | 15 +-
Sources/BasaltCore/KVCacheGeometry+Loop.swift | 22 +-
Sources/BasaltCore/KVCacheGeometry.swift | 2 +-
.../MLXInferenceEngine+Loading.swift | 3 +
.../MLXInferenceEngine+PromptCache.swift | 2 +-
.../MLXInferenceEngine+Research.swift | 10 +-
.../BasaltInference/ModelCapabilities.swift | 2 +
.../BailingHybridConfiguration.swift | 274 +++++++++++++++++
.../BailingHybrid/BailingHybridKDA.swift | 281 +++++++++++++++++
.../BailingHybrid/BailingHybridMLA.swift | 159 ++++++++++
.../BailingHybrid/BailingHybridMoE.swift | 178 +++++++++++
.../BailingHybrid/BailingHybridModel.swift | 260 ++++++++++++++++
.../BailingHybridIntegrationTests.swift | 274 +++++++++++++++++
Tests/BasaltTests/BailingHybridTests.swift | 284 ++++++++++++++++++
.../BatchedDecodingIsolationTests.swift | 6 +-
Tests/BasaltTests/FeatureMatrixTests.swift | 2 +-
Tests/BasaltTests/Fixtures/TinyModels.swift | 180 ++++++-----
Tests/BasaltTests/GenerationPlanTests.swift | 50 +--
Tests/BasaltTests/TokenTraceTests.swift | 4 +-
20 files changed, 1937 insertions(+), 116 deletions(-)
create mode 100644 Sources/BasaltCore/Chat/BailingHybridProfile.swift
create mode 100644 Sources/BasaltInference/Models/BailingHybrid/BailingHybridConfiguration.swift
create mode 100644 Sources/BasaltInference/Models/BailingHybrid/BailingHybridKDA.swift
create mode 100644 Sources/BasaltInference/Models/BailingHybrid/BailingHybridMLA.swift
create mode 100644 Sources/BasaltInference/Models/BailingHybrid/BailingHybridMoE.swift
create mode 100644 Sources/BasaltInference/Models/BailingHybrid/BailingHybridModel.swift
create mode 100644 Tests/BasaltTests/BailingHybridIntegrationTests.swift
create mode 100644 Tests/BasaltTests/BailingHybridTests.swift
diff --git a/Sources/BasaltCore/Chat/BailingHybridProfile.swift b/Sources/BasaltCore/Chat/BailingHybridProfile.swift
new file mode 100644
index 000000000..6d9b20050
--- /dev/null
+++ b/Sources/BasaltCore/Chat/BailingHybridProfile.swift
@@ -0,0 +1,45 @@
+import Foundation
+
+public struct BailingHybridProfile: ModelProfile {
+ public let name = "bailing_hybrid"
+
+ public init() {}
+
+ public func templateContext(for reasoning: ReasoningPolicy) -> [String: any Sendable] {
+ switch reasoning {
+ case .modelDefault:
+ return [:]
+ case .disabled:
+ return ["enable_thinking": false]
+ case .effort(let level):
+ return ["enable_thinking": level != "none"]
+ }
+ }
+
+ public func turns(_ turns: [ChatMessageInput], for reasoning: ReasoningPolicy) -> [ChatMessageInput] {
+ let directive: String
+ switch reasoning {
+ case .modelDefault:
+ return turns
+ case .disabled:
+ directive = "detailed thinking off"
+ case .effort(let level):
+ directive = level == "none" ? "detailed thinking off" : "detailed thinking on"
+ }
+ guard let first = turns.first, first.role == .system else {
+ return [ChatMessageInput(role: .system, text: directive)] + turns
+ }
+ if first.text.contains("detailed thinking on") || first.text.contains("detailed thinking off") {
+ return turns
+ }
+ return [ChatMessageInput(role: .system, text: first.text + "\n" + directive)] + turns.dropFirst()
+ }
+
+ public var thinkingMarkers: ThinkingMarkers {
+ ThinkingMarkers(open: [""], close: [""])
+ }
+
+ public var defaultMaxTokens: Int { 16_384 }
+
+ public var defaultMinP: Float? { nil }
+}
diff --git a/Sources/BasaltCore/Chat/ModelProfile.swift b/Sources/BasaltCore/Chat/ModelProfile.swift
index b45db1134..68ad5e98d 100644
--- a/Sources/BasaltCore/Chat/ModelProfile.swift
+++ b/Sources/BasaltCore/Chat/ModelProfile.swift
@@ -276,15 +276,22 @@ public struct SamplingDefaults: Sendable, Equatable {
}
public enum ModelProfileRegistry {
+ private static let exactProfiles: [String: any ModelProfile] = [
+ "flint": FlintProfile(),
+ "ricursive": RicursiveProfile(),
+ "ripple": RicursiveProfile(),
+ "muse-glimmer": MuseGlimmerProfile(),
+ "gpt_oss": GPTOSSProfile(),
+ "bailing_hybrid": BailingHybridProfile(),
+ ]
+
public static func profile(forModelType modelType: String?, chatTemplate: String? = nil) -> any ModelProfile {
guard let t = modelType?.lowercased() else { return GenericProfile() }
+ if let exact = exactProfiles[t] { return exact }
if t.hasPrefix("qwen3") { return qwenProfile(t, chatTemplate: chatTemplate) }
if t.hasPrefix("gemma") { return GemmaProfile() }
if t.hasPrefix("lfm2") { return LiquidProfile() }
- if t == "flint" { return FlintProfile() }
- if t == "ricursive" || t == "ripple" { return RicursiveProfile() }
- if t.hasPrefix("muse_glimmer") || t == "muse-glimmer" { return MuseGlimmerProfile() }
- if t == "gpt_oss" { return GPTOSSProfile() }
+ if t.hasPrefix("muse_glimmer") { return MuseGlimmerProfile() }
if t.hasPrefix("inkling2") { return InklingProfile() }
if t == "nemotron_h" || t == "nemotron_lightning" || t == "nemotron-lightning" {
return NemotronProfile(switchesThinkingInConversation: chatTemplate?.contains("/no_think") == true)
diff --git a/Sources/BasaltCore/KVCacheGeometry+Loop.swift b/Sources/BasaltCore/KVCacheGeometry+Loop.swift
index 83a008e02..82ca84ed0 100644
--- a/Sources/BasaltCore/KVCacheGeometry+Loop.swift
+++ b/Sources/BasaltCore/KVCacheGeometry+Loop.swift
@@ -2,9 +2,25 @@ import Foundation
extension KVCacheGeometry {
static func localLayerKinds(_ c: [String: Any], layers: Int) -> [LayerKind]? {
- guard let local = c["local_layer_ids"] as? [Int], c["sliding_window_size"] is Int else { return nil }
- let windowed = Set(local)
- return (0 ..< layers).map { windowed.contains($0) ? .windowed : .full }
+ if let local = c["local_layer_ids"] as? [Int], c["sliding_window_size"] is Int {
+ let windowed = Set(local)
+ return (0 ..< layers).map { windowed.contains($0) ? .windowed : .full }
+ }
+ if let group = c["layer_group_size"] as? Int, group > 0, c["kv_lora_rank"] is Int {
+ let full = (layers / group) * group
+ return (0 ..< layers).map { ($0 + 1).isMultiple(of: group) || $0 >= full ? .full : .linear }
+ }
+ return nil
+ }
+
+ static func bailingLinearStateBytes(_ c: [String: Any]) -> Int64 {
+ guard c["layer_group_size"] is Int, c["kv_lora_rank"] is Int,
+ let heads = c["num_attention_heads"] as? Int, heads > 0,
+ let headDim = c["head_dim"] as? Int, headDim > 0 else { return 0 }
+ let kernel = c["short_conv_kernel_size"] as? Int ?? c["conv_kernel_size"] as? Int ?? 4
+ let conv = Double(3 * max(0, kernel - 1) * heads * headDim) * activationBytes
+ let recurrent = Double(heads * headDim * headDim) * recurrentStateBytes
+ return Int64(conv + recurrent)
}
static func visits(_ kinds: [LayerKind], _ c: [String: Any]) -> [LayerKind] {
diff --git a/Sources/BasaltCore/KVCacheGeometry.swift b/Sources/BasaltCore/KVCacheGeometry.swift
index c7f706d56..ec0b688fc 100644
--- a/Sources/BasaltCore/KVCacheGeometry.swift
+++ b/Sources/BasaltCore/KVCacheGeometry.swift
@@ -350,7 +350,7 @@ extension KVCacheGeometry {
guard let keyHeads = c["linear_num_key_heads"] as? Int,
let valueHeads = c["linear_num_value_heads"] as? Int,
let keyDim = c["linear_key_head_dim"] as? Int,
- let valueDim = c["linear_value_head_dim"] as? Int else { return 0 }
+ let valueDim = c["linear_value_head_dim"] as? Int else { return bailingLinearStateBytes(c) }
let kernel = c["linear_conv_kernel_dim"] as? Int ?? 4
let convChannels = 2 * keyHeads * keyDim + valueHeads * valueDim
let conv = Double(max(0, kernel - 1) * convChannels) * activationBytes
diff --git a/Sources/BasaltInference/MLXInferenceEngine+Loading.swift b/Sources/BasaltInference/MLXInferenceEngine+Loading.swift
index 7a50683bb..380099a3d 100644
--- a/Sources/BasaltInference/MLXInferenceEngine+Loading.swift
+++ b/Sources/BasaltInference/MLXInferenceEngine+Loading.swift
@@ -112,12 +112,15 @@ extension MLXInferenceEngine {
}
VLMProcessorLoadingRegistry.shared.register(ModelTypeProcessorResolver(processorTypes: [DeepSeekOCR2.modelType: DeepSeekOCRProcessor.ocr2ProcessorType]))
await registerMuseGlimmerAliases()
+ await registerBailingHybridAliases()
}
public static func registerAliases() async {
await aliasRegistration.value
}
+}
+extension MLXInferenceEngine {
public var isLoaded: Bool { container != nil }
static func imageToken(in config: [String: Any]?) -> Int? {
diff --git a/Sources/BasaltInference/MLXInferenceEngine+PromptCache.swift b/Sources/BasaltInference/MLXInferenceEngine+PromptCache.swift
index 79597def9..0a16ab4d1 100644
--- a/Sources/BasaltInference/MLXInferenceEngine+PromptCache.swift
+++ b/Sources/BasaltInference/MLXInferenceEngine+PromptCache.swift
@@ -35,7 +35,7 @@ extension MLXInferenceEngine {
if let known = modelIsHybrid { return known }
let kinds = (try? await container.perform { context -> (hybrid: Bool, recurrent: Bool) in
let cache = try context.model.newCache(parameters: nil)
- return (PromptCache(cache).isHybrid, cache.contains { $0 is MambaCache })
+ return (PromptCache(cache).isHybrid, cache.contains { $0 is ArraysCache })
}) ?? (hybrid: false, recurrent: false)
record(.learned(epoch) { ($0.isHybrid, $0.hasRecurrentState) = (kinds.hybrid, kinds.recurrent) })
return kinds.hybrid
diff --git a/Sources/BasaltInference/MLXInferenceEngine+Research.swift b/Sources/BasaltInference/MLXInferenceEngine+Research.swift
index 9cceb95cc..e4e54c70f 100644
--- a/Sources/BasaltInference/MLXInferenceEngine+Research.swift
+++ b/Sources/BasaltInference/MLXInferenceEngine+Research.swift
@@ -74,12 +74,14 @@ struct AnatomyScan: Sendable {
modules[index, default: ""] += name + " "
if name.contains("attention"), heads[index] == nil { heads[index] = Self.reflectedHeads(module) }
}
- if hiddenSize == nil, let embedding = module as? Embedding, path.hasSuffix("embed_tokens") {
+ if hiddenSize == nil, let embedding = module as? Embedding,
+ path.hasSuffix("embed_tokens") || path.hasSuffix("word_embeddings")
+ {
hiddenSize = (embedding as? QuantizedEmbedding).map { (embedding.weight.dim(-1) * 32) / $0.bits } ?? embedding.weight.dim(-1)
}
}
var experts: [Int: Int] = [:]
- for (path, array) in parameters where array.ndim == 3 && path.contains("switch") {
+ for (path, array) in parameters where array.ndim == 3 && (path.contains("switch") || path.contains(".experts.")) {
if let index = Self.layerIndex(path) { experts[index] = array.dim(0) }
}
var layers = (0 ..< ((modules.keys.max() ?? -1) + 1)).map { index in
@@ -177,7 +179,9 @@ struct AnatomyConfig {
layer.kvHeads = int("num_key_value_heads") == nil ? scan.heads.kvHeads ?? layer.kvHeads : layer.kvHeads
layer.headDim = layer.headDim ?? scan.heads.headDim
case .linearAttention?:
- (layer.heads, layer.kvHeads, layer.headDim) = (int("linear_num_value_heads"), int("linear_num_key_heads"), int("linear_key_head_dim"))
+ layer.heads = int("linear_num_value_heads") ?? scan.heads.heads
+ layer.kvHeads = int("linear_num_key_heads") ?? scan.heads.kvHeads
+ layer.headDim = int("linear_key_head_dim") ?? scan.heads.headDim
case .mamba?:
(layer.heads, layer.headDim) = (int("mamba_num_heads"), int("mamba_head_dim"))
case .conv?, nil:
diff --git a/Sources/BasaltInference/ModelCapabilities.swift b/Sources/BasaltInference/ModelCapabilities.swift
index 899a0a536..7961de95d 100644
--- a/Sources/BasaltInference/ModelCapabilities.swift
+++ b/Sources/BasaltInference/ModelCapabilities.swift
@@ -100,6 +100,7 @@ struct ModelCapabilities: Equatable, Sendable {
let gemma4 = ModelCapabilities(verified: all.subtracting([.mtp, .quest]))
let flint = ModelCapabilities(verified: [.speculativeLookup, .batchedDecode, .promptCacheReuse, .kvQuantization, .grammarJumpForward])
let falconH1 = ModelCapabilities(verified: [.speculativeLookup, .promptCacheReuse, .kvQuantization, .grammarJumpForward])
+ let bailingHybrid = ModelCapabilities(verified: [.batchedDecode, .promptCacheReuse, .grammarJumpForward])
let table: [([String], ModelCapabilities)] = [
(["llama", "qwen3", "qwen3_moe", "mimo", "minimax", "minimax_m1", "minimax-m1", "minimax_m2", "minimax-m2", "hunyuan", "hunyuan_mt", "hunyuan-mt", "hunyuan_v1_dense"], attention),
(["qwen3_5", "qwen3_6", "qwen3.6", "qwen3_8", "qwen3.8", PrismHadamard.modelType], qwen35),
@@ -110,6 +111,7 @@ struct ModelCapabilities: Equatable, Sendable {
(["gemma4", "gemma4_text", "gemma4_unified", "gemma4_unified_text"], gemma4),
([FlintModel.modelType], flint),
(["falcon_h1", "falcon-h1"], falconH1),
+ ([BailingHybridModel.modelType], bailingHybrid),
(Inkling2Model.modelTypes, ModelCapabilities(verified: [.speculativeLookup, .mtp, .promptCacheReuse, .grammarJumpForward])),
([PaddleOCRVL.modelType], ModelCapabilities(verified: all.subtracting([.mtp, .cacheBlend, .kvQuantization, .kvZones, .kvHeadSplit, .quest]))),
([DeepSeekOCR.modelType, DeepSeekOCR2.modelType], ModelCapabilities(verified: all.subtracting([.mtp, .cacheBlend, .kvQuantization, .kvZones, .kvHeadSplit, .quest]))),
diff --git a/Sources/BasaltInference/Models/BailingHybrid/BailingHybridConfiguration.swift b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridConfiguration.swift
new file mode 100644
index 000000000..8e6e2facf
--- /dev/null
+++ b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridConfiguration.swift
@@ -0,0 +1,274 @@
+import BasaltCore
+import Foundation
+import MLXLMCommon
+
+public struct BailingHybridConfiguration: Codable, Sendable, Equatable {
+ public var modelType: String
+ public var hiddenSize: Int
+ public var numHiddenLayers: Int
+ public var intermediateSize: Int
+ public var numAttentionHeads: Int
+ public var numKeyValueHeads: Int
+ public var headDim: Int
+ public var rmsNormEps: Float
+ public var vocabSize: Int
+ public var maxPositionEmbeddings: Int
+ public var tieWordEmbeddings: Bool
+ public var layerGroupSize: Int
+ public var firstKDenseReplace: Int
+ public var convKernelSize: Int
+ public var noKDALoRA: Bool
+ public var kdaSafeGate: Bool
+ public var kdaLowerBound: Float
+ public var qLoraRank: Int?
+ public var kvLoraRank: Int
+ public var qkNopeHeadDim: Int
+ public var qkRopeHeadDim: Int
+ public var vHeadDim: Int
+ public var ropeTheta: Float
+ public var ropeInterleave: Bool
+ public var ropeScaling: [String: StringOrNumber]?
+ public var useQKVBias: Bool
+ public var useBias: Bool
+ public var useQKNorm: Bool
+ public var gatedAttentionGranularity: String?
+ public var numExperts: Int
+ public var numExpertsPerTok: Int
+ public var numSharedExperts: Int
+ public var moeIntermediateSize: Int
+ public var moeSharedExpertIntermediateSize: Int?
+ public var nGroup: Int
+ public var topkGroup: Int
+ public var normTopkProb: Bool
+ public var routedScalingFactor: Float
+ public var moeRouterEnableExpertBias: Bool
+
+ enum CodingKeys: String, CodingKey {
+ case modelType = "model_type"
+ case hiddenSize = "hidden_size"
+ case numHiddenLayers = "num_hidden_layers"
+ case intermediateSize = "intermediate_size"
+ case numAttentionHeads = "num_attention_heads"
+ case numKeyValueHeads = "num_key_value_heads"
+ case headDim = "head_dim"
+ case rmsNormEps = "rms_norm_eps"
+ case vocabSize = "vocab_size"
+ case maxPositionEmbeddings = "max_position_embeddings"
+ case tieWordEmbeddings = "tie_word_embeddings"
+ case layerGroupSize = "layer_group_size"
+ case firstKDenseReplace = "first_k_dense_replace"
+ case convKernelSize = "short_conv_kernel_size"
+ case noKDALoRA = "no_kda_lora"
+ case kdaSafeGate = "kda_safe_gate"
+ case kdaLowerBound = "kda_lower_bound"
+ case qLoraRank = "q_lora_rank"
+ case kvLoraRank = "kv_lora_rank"
+ case qkNopeHeadDim = "qk_nope_head_dim"
+ case qkRopeHeadDim = "qk_rope_head_dim"
+ case vHeadDim = "v_head_dim"
+ case ropeTheta = "rope_theta"
+ case ropeInterleave = "rope_interleave"
+ case ropeScaling = "rope_scaling"
+ case useQKVBias = "use_qkv_bias"
+ case useBias = "use_bias"
+ case useQKNorm = "use_qk_norm"
+ case gatedAttentionGranularity = "gated_attention_proj_granularity_type"
+ case numExperts = "num_experts"
+ case numExpertsPerTok = "num_experts_per_tok"
+ case numSharedExperts = "num_shared_experts"
+ case moeIntermediateSize = "moe_intermediate_size"
+ case moeSharedExpertIntermediateSize = "moe_shared_expert_intermediate_size"
+ case nGroup = "n_group"
+ case topkGroup = "topk_group"
+ case normTopkProb = "norm_topk_prob"
+ case routedScalingFactor = "routed_scaling_factor"
+ case moeRouterEnableExpertBias = "moe_router_enable_expert_bias"
+ }
+
+ private enum AliasKeys: String, CodingKey {
+ case convKernelSize = "conv_kernel_size"
+ case useKDALoRA = "use_kda_lora"
+ }
+
+ public init(from decoder: any Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ let alias = try decoder.container(keyedBy: AliasKeys.self)
+ modelType = try Self.value(c, .modelType, default: BailingHybridModel.modelType)
+ hiddenSize = try c.decode(Int.self, forKey: .hiddenSize)
+ numHiddenLayers = try c.decode(Int.self, forKey: .numHiddenLayers)
+ intermediateSize = try c.decode(Int.self, forKey: .intermediateSize)
+ numAttentionHeads = try c.decode(Int.self, forKey: .numAttentionHeads)
+ numKeyValueHeads = try Self.value(c, .numKeyValueHeads, default: numAttentionHeads)
+ headDim = try Self.value(c, .headDim, default: hiddenSize / max(numAttentionHeads, 1))
+ rmsNormEps = try Self.value(c, .rmsNormEps, default: 1e-6)
+ vocabSize = try c.decode(Int.self, forKey: .vocabSize)
+ maxPositionEmbeddings = try Self.value(c, .maxPositionEmbeddings, default: 131_072)
+ tieWordEmbeddings = try Self.value(c, .tieWordEmbeddings, default: false)
+ layerGroupSize = try Self.value(c, .layerGroupSize, default: 4)
+ firstKDenseReplace = try Self.value(c, .firstKDenseReplace, default: 1)
+ convKernelSize = try Self.decodeConvKernel(c, alias)
+ noKDALoRA = try Self.decodeNoKDALoRA(c, alias)
+ kdaSafeGate = try Self.value(c, .kdaSafeGate, default: true)
+ kdaLowerBound = try Self.value(c, .kdaLowerBound, default: -5.0)
+ qLoraRank = try c.decodeIfPresent(Int.self, forKey: .qLoraRank)
+ kvLoraRank = try Self.value(c, .kvLoraRank, default: 512)
+ qkNopeHeadDim = try Self.value(c, .qkNopeHeadDim, default: 128)
+ qkRopeHeadDim = try Self.value(c, .qkRopeHeadDim, default: 64)
+ vHeadDim = try Self.value(c, .vHeadDim, default: 128)
+ ropeTheta = try Self.value(c, .ropeTheta, default: 6_000_000.0)
+ ropeInterleave = try Self.value(c, .ropeInterleave, default: true)
+ ropeScaling = try c.decodeIfPresent([String: StringOrNumber].self, forKey: .ropeScaling)
+ useQKVBias = try Self.value(c, .useQKVBias, default: false)
+ useBias = try Self.value(c, .useBias, default: false)
+ useQKNorm = try Self.value(c, .useQKNorm, default: false)
+ gatedAttentionGranularity = try Self.decodeGranularity(c)
+ numExperts = try Self.value(c, .numExperts, default: 0)
+ numExpertsPerTok = try Self.value(c, .numExpertsPerTok, default: 8)
+ numSharedExperts = try Self.value(c, .numSharedExperts, default: 0)
+ moeIntermediateSize = try Self.value(c, .moeIntermediateSize, default: 512)
+ moeSharedExpertIntermediateSize = try c.decodeIfPresent(Int.self, forKey: .moeSharedExpertIntermediateSize)
+ nGroup = try Self.value(c, .nGroup, default: 1)
+ topkGroup = try Self.value(c, .topkGroup, default: 1)
+ normTopkProb = try Self.value(c, .normTopkProb, default: true)
+ routedScalingFactor = try Self.value(c, .routedScalingFactor, default: 1.0)
+ moeRouterEnableExpertBias = try Self.value(c, .moeRouterEnableExpertBias, default: true)
+ }
+
+ private static func value(
+ _ container: KeyedDecodingContainer,
+ _ key: CodingKeys,
+ default fallback: T
+ ) throws -> T {
+ try container.decodeIfPresent(T.self, forKey: key) ?? fallback
+ }
+
+ private static func decodeConvKernel(
+ _ container: KeyedDecodingContainer,
+ _ alias: KeyedDecodingContainer
+ ) throws -> Int {
+ if let primary = try container.decodeIfPresent(Int.self, forKey: .convKernelSize) {
+ return primary
+ }
+ return try alias.decodeIfPresent(Int.self, forKey: .convKernelSize) ?? 4
+ }
+
+ private static func decodeNoKDALoRA(
+ _ container: KeyedDecodingContainer,
+ _ alias: KeyedDecodingContainer
+ ) throws -> Bool {
+ if let explicit = try container.decodeIfPresent(Bool.self, forKey: .noKDALoRA) {
+ return explicit
+ }
+ if let useLoRA = try alias.decodeIfPresent(Bool.self, forKey: .useKDALoRA) {
+ return !useLoRA
+ }
+ return true
+ }
+
+ private static func decodeGranularity(_ container: KeyedDecodingContainer) throws -> String? {
+ guard container.contains(.gatedAttentionGranularity) else {
+ return "head_wise"
+ }
+ return try container.decodeIfPresent(String.self, forKey: .gatedAttentionGranularity)
+ }
+}
+
+extension BailingHybridConfiguration {
+ public var qkHeadDim: Int {
+ qkNopeHeadDim + qkRopeHeadDim
+ }
+
+ public var sharedExpertIntermediateSize: Int {
+ (moeSharedExpertIntermediateSize ?? moeIntermediateSize) * numSharedExperts
+ }
+
+ public func isMLALayer(_ index: Int) -> Bool {
+ let group = max(layerGroupSize, 1)
+ let full = (numHiddenLayers / group) * group
+ return (index + 1).isMultiple(of: group) || index >= full
+ }
+
+ public func isMoELayer(_ index: Int) -> Bool {
+ numExperts > 0 && index >= firstKDenseReplace
+ }
+
+ public func validated() throws(BasaltError) -> BailingHybridConfiguration {
+ try validateCoreGeometry()
+ try validateMLAGeometry()
+ try validateMoEGeometry()
+ return self
+ }
+
+ private func validateCoreGeometry() throws(BasaltError) {
+ guard vocabSize > 0, hiddenSize > 0, numHiddenLayers > 0, intermediateSize > 0 else {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid requires positive vocab_size, hidden_size, num_hidden_layers and intermediate_size"
+ )
+ }
+ guard numAttentionHeads > 0, numKeyValueHeads > 0, headDim > 0, layerGroupSize > 0, convKernelSize > 0 else {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid requires positive head counts, head_dim, layer_group_size and short_conv_kernel_size"
+ )
+ }
+ guard firstKDenseReplace >= 0 else {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid first_k_dense_replace (\(firstKDenseReplace)) must be non-negative"
+ )
+ }
+ }
+
+ private func validateMLAGeometry() throws(BasaltError) {
+ guard kvLoraRank > 0, qkNopeHeadDim >= 0, qkRopeHeadDim > 0, qkRopeHeadDim.isMultiple(of: 2),
+ qkHeadDim > 0, vHeadDim > 0
+ else {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid MLA requires positive kv_lora_rank, even positive qk_rope_head_dim and positive v_head_dim"
+ )
+ }
+ if let qLoraRank, qLoraRank <= 0 {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid q_lora_rank (\(qLoraRank)) must be positive when set"
+ )
+ }
+ if let granularity = gatedAttentionGranularity, granularity != "head_wise" && granularity != "element_wise" {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid unsupported gated_attention_proj_granularity_type '\(granularity)'"
+ )
+ }
+ }
+
+ private func validateMoEGeometry() throws(BasaltError) {
+ guard numExperts >= 0, numSharedExperts >= 0 else {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid num_experts and num_shared_experts must be non-negative"
+ )
+ }
+ guard numExperts > 0 else { return }
+ guard moeIntermediateSize > 0, (1 ... numExperts).contains(numExpertsPerTok) else {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid num_experts_per_tok (\(numExpertsPerTok)) must be in 1...\(numExperts)"
+ )
+ }
+ guard nGroup > 0, numExperts.isMultiple(of: nGroup), (1 ... nGroup).contains(topkGroup) else {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid n_group (\(nGroup)) must divide num_experts (\(numExperts)) with topk_group (\(topkGroup)) in 1...\(nGroup)"
+ )
+ }
+ let maxSelectable = topkGroup * (numExperts / nGroup)
+ guard numExpertsPerTok <= maxSelectable else {
+ throw .modelConfigurationInvalid(
+ path: modelType,
+ reason: "bailing_hybrid num_experts_per_tok (\(numExpertsPerTok)) exceeds topk_group capacity (\(maxSelectable))"
+ )
+ }
+ }
+}
diff --git a/Sources/BasaltInference/Models/BailingHybrid/BailingHybridKDA.swift b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridKDA.swift
new file mode 100644
index 000000000..aa656f76b
--- /dev/null
+++ b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridKDA.swift
@@ -0,0 +1,281 @@
+import Foundation
+import MLX
+import MLXLMCommon
+import MLXNN
+
+package struct BailingHybridKDAInputs {
+ package let q: MLXArray
+ package let k: MLXArray
+ package let v: MLXArray
+ package let decay: MLXArray
+ package let beta: MLXArray
+
+ package init(q: MLXArray, k: MLXArray, v: MLXArray, decay: MLXArray, beta: MLXArray) {
+ self.q = q
+ self.k = k
+ self.v = v
+ self.decay = decay
+ self.beta = beta
+ }
+
+ func slice(at step: Int) -> BailingHybridKDAInputs {
+ BailingHybridKDAInputs(
+ q: q[0..., step],
+ k: k[0..., step],
+ v: v[0..., step],
+ decay: decay[0..., step],
+ beta: beta[0..., step]
+ )
+ }
+}
+
+package enum BailingHybridKDAOps {
+ package static func decayLogGate(
+ f: MLXArray,
+ aLog: MLXArray,
+ dtBias: MLXArray,
+ safeGate: Bool,
+ lowerBound: Float
+ ) -> MLXArray {
+ let pre = f.asType(.float32) + dtBias.asType(.float32)
+ let alpha = exp(aLog.asType(.float32)).expandedDimensions(axis: -1)
+ if safeGate {
+ return MLXArray(lowerBound, dtype: .float32) * sigmoid(alpha * pre)
+ }
+ return -alpha * softplus(pre)
+ }
+
+ package static func l2Normalize(_ x: MLXArray, eps: Float = 1e-6) -> MLXArray {
+ let xf = x.asType(.float32)
+ let norm = sqrt((xf * xf).sum(axis: -1, keepDims: true))
+ return xf / (norm + eps)
+ }
+
+ package static func recurrentUpdate(
+ _ inputs: BailingHybridKDAInputs,
+ state: MLXArray?,
+ mask: MLXArray? = nil
+ ) -> (MLXArray, MLXArray) {
+ let batch = inputs.q.dim(0)
+ let steps = inputs.q.dim(1)
+ let heads = inputs.v.dim(2)
+ let headVDim = inputs.v.dim(3)
+ let headKDim = inputs.k.dim(3)
+ var current = (state ?? MLXArray.zeros([batch, heads, headVDim, headKDim], dtype: .float32)).asType(.float32)
+ guard steps > 0 else {
+ return (MLXArray.zeros([batch, 0, heads, headVDim], dtype: .float32), current)
+ }
+ var outputs: [MLXArray] = []
+ outputs.reserveCapacity(steps)
+ for step in 0 ..< steps {
+ let stepMask = mask.map { $0[0..., step] }
+ let (y, nextState) = recurrentStep(inputs.slice(at: step), state: current, mask: stepMask)
+ outputs.append(y)
+ current = nextState
+ }
+ return (MLX.stacked(outputs, axis: 1), current)
+ }
+
+ private static func recurrentStep(
+ _ step: BailingHybridKDAInputs,
+ state: MLXArray,
+ mask: MLXArray?
+ ) -> (MLXArray, MLXArray) {
+ let previous = state
+ let g = step.decay.ndim == 2
+ ? step.decay.expandedDimensions(axes: [2, 3])
+ : step.decay.expandedDimensions(axis: -2)
+ var updated = state * g.asType(.float32)
+ let kExpanded = step.k.asType(.float32).expandedDimensions(axis: -2)
+ let kvMem = (updated * kExpanded).sum(axis: -1)
+ let delta = (step.v.asType(.float32) - kvMem) * step.beta.asType(.float32).expandedDimensions(axis: -1)
+ updated = updated + kExpanded * delta.expandedDimensions(axis: -1)
+ var y = (updated * step.q.asType(.float32).expandedDimensions(axis: -2)).sum(axis: -1)
+ if let mask {
+ y = MLX.where(mask.expandedDimensions(axes: [1, 2]), y, MLXArray.zeros(like: y))
+ updated = MLX.where(mask.expandedDimensions(axes: [1, 2, 3]), updated, previous)
+ }
+ return (y, updated)
+ }
+}
+
+package final class BailingHybridShortConv1d: Module {
+ let kernelSize: Int
+ @ModuleInfo(key: "conv") var conv: Conv1d
+
+ package init(channels: Int, kernelSize: Int) {
+ self.kernelSize = kernelSize
+ self._conv.wrappedValue = Conv1d(
+ inputChannels: channels,
+ outputChannels: channels,
+ kernelSize: kernelSize,
+ stride: 1,
+ padding: 0,
+ dilation: 1,
+ groups: channels,
+ bias: false
+ )
+ }
+
+ package func callAsFunction(_ x: MLXArray, state: MLXArray?) -> (MLXArray, MLXArray) {
+ let batch = x.dim(0)
+ let steps = x.dim(1)
+ let channels = x.dim(2)
+ let history = max(kernelSize - 1, 0)
+ let previous = state ?? MLXArray.zeros([batch, history, channels], dtype: x.dtype)
+ guard steps > 0 else {
+ return (MLXArray.zeros([batch, 0, channels], dtype: x.dtype), previous)
+ }
+ let convInput = concatenated([previous, x], axis: 1)
+ let out = silu(conv(convInput))
+ let newState: MLXArray
+ if history == 0 {
+ newState = MLXArray.zeros([batch, 0, channels], dtype: x.dtype)
+ } else {
+ let total = convInput.dim(1)
+ newState = contiguous(convInput[0..., (total - history)..., 0...])
+ }
+ return (out, newState)
+ }
+}
+
+package final class BailingHybridLinearAttention: Module {
+ let layerIdx: Int
+ let numHeads: Int
+ let kvHeads: Int
+ let headDim: Int
+ let safeGate: Bool
+ let lowerBound: Float
+ let noKDALoRA: Bool
+ let scale: Float
+
+ @ModuleInfo(key: "q_proj") var qProj: Linear
+ @ModuleInfo(key: "k_proj") var kProj: Linear
+ @ModuleInfo(key: "v_proj") var vProj: Linear
+ @ModuleInfo(key: "q_conv1d") var qConv1d: BailingHybridShortConv1d
+ @ModuleInfo(key: "k_conv1d") var kConv1d: BailingHybridShortConv1d
+ @ModuleInfo(key: "v_conv1d") var vConv1d: BailingHybridShortConv1d
+ @ModuleInfo(key: "f_proj") var fProj: Linear?
+ @ModuleInfo(key: "g_proj") var gProj: Linear?
+ @ModuleInfo(key: "f_a_proj") var fAProj: Linear?
+ @ModuleInfo(key: "f_b_proj") var fBProj: Linear?
+ @ModuleInfo(key: "g_a_proj") var gAProj: Linear?
+ @ModuleInfo(key: "g_b_proj") var gBProj: Linear?
+ @ModuleInfo(key: "b_proj") var bProj: Linear
+ @ParameterInfo(key: "A_log") var aLog: MLXArray
+ @ParameterInfo(key: "dt_bias") var dtBias: MLXArray
+ @ModuleInfo(key: "o_norm") var oNorm: RMSNorm
+ @ModuleInfo(key: "o_proj") var oProj: Linear
+
+ package init(_ config: BailingHybridConfiguration, layerIdx: Int) {
+ self.layerIdx = layerIdx
+ self.numHeads = config.numAttentionHeads
+ self.kvHeads = config.numAttentionHeads
+ self.headDim = config.headDim
+ self.safeGate = config.kdaSafeGate
+ self.lowerBound = config.kdaLowerBound
+ self.noKDALoRA = config.noKDALoRA
+ self.scale = pow(Float(config.headDim), -0.5)
+
+ let hidden = config.hiddenSize
+ let projDim = config.numAttentionHeads * config.headDim
+ self._qProj.wrappedValue = Linear(hidden, projDim, bias: false)
+ self._kProj.wrappedValue = Linear(hidden, projDim, bias: false)
+ self._vProj.wrappedValue = Linear(hidden, projDim, bias: false)
+ self._qConv1d.wrappedValue = BailingHybridShortConv1d(channels: projDim, kernelSize: config.convKernelSize)
+ self._kConv1d.wrappedValue = BailingHybridShortConv1d(channels: projDim, kernelSize: config.convKernelSize)
+ self._vConv1d.wrappedValue = BailingHybridShortConv1d(channels: projDim, kernelSize: config.convKernelSize)
+
+ if config.noKDALoRA {
+ self._fProj.wrappedValue = Linear(hidden, projDim, bias: false)
+ self._gProj.wrappedValue = Linear(hidden, projDim, bias: false)
+ } else {
+ self._fAProj.wrappedValue = Linear(hidden, config.headDim, bias: false)
+ self._fBProj.wrappedValue = Linear(config.headDim, projDim, bias: false)
+ self._gAProj.wrappedValue = Linear(hidden, config.headDim, bias: false)
+ self._gBProj.wrappedValue = Linear(config.headDim, projDim, bias: false)
+ }
+
+ self._bProj.wrappedValue = Linear(hidden, config.numAttentionHeads, bias: false)
+ self._aLog.wrappedValue = MLXArray.zeros([config.numAttentionHeads], dtype: .float32)
+ self._dtBias.wrappedValue = MLXArray.zeros([projDim], dtype: .float32)
+ self._oNorm.wrappedValue = RMSNorm(dimensions: config.headDim, eps: config.rmsNormEps)
+ self._oProj.wrappedValue = Linear(projDim, hidden, bias: false)
+ }
+
+ package func callAsFunction(
+ _ x: MLXArray,
+ cache: ArraysCache?,
+ probe: (any ForwardProbe)? = nil
+ ) -> MLXArray {
+ let batch = x.dim(0)
+ let steps = x.dim(1)
+ let dtype = x.dtype
+ let ssmMask = cache?.makeMask(N: steps)
+
+ let (qConv, kConv, vConv) = convolveQKV(x, cache: cache, mask: ssmMask)
+ let q = BailingHybridKDAOps.l2Normalize(qConv.reshaped(batch, steps, numHeads, headDim)) * scale
+ let k = BailingHybridKDAOps.l2Normalize(kConv.reshaped(batch, steps, numHeads, headDim))
+ let v = vConv.reshaped(batch, steps, numHeads, headDim)
+
+ let (fRaw, gRaw) = projectGates(x)
+ let f = fRaw.reshaped(batch, steps, numHeads, headDim)
+ let gLog = BailingHybridKDAOps.decayLogGate(
+ f: f,
+ aLog: aLog,
+ dtBias: dtBias.reshaped(numHeads, headDim),
+ safeGate: safeGate,
+ lowerBound: lowerBound
+ )
+ let beta = sigmoid(bProj(x).asType(.float32))
+ let inputs = BailingHybridKDAInputs(q: q, k: k, v: v, decay: exp(gLog), beta: beta)
+ let (recurrenceOut, nextState) = BailingHybridKDAOps.recurrentUpdate(inputs, state: cache?[3], mask: ssmMask)
+ if let cache {
+ cache[3] = nextState
+ cache.advance(steps)
+ }
+
+ let gate = sigmoid(gRaw.reshaped(batch, steps, numHeads, headDim).asType(.float32)).asType(dtype)
+ var gated = oNorm(recurrenceOut.asType(dtype)) * gate
+ if let probe {
+ var perHead = gated.transposed(0, 2, 1, 3)
+ if let headMask = probe.headMask(layer: layerIdx) {
+ perHead = perHead * headMask.reshaped(1, numHeads, 1, 1).asType(perHead.dtype)
+ }
+ probe.headOutputs(layer: layerIdx, perHead)
+ gated = perHead.transposed(0, 2, 1, 3)
+ }
+ return oProj(gated.reshaped(batch, steps, -1))
+ }
+
+ private func convolveQKV(_ x: MLXArray, cache: ArraysCache?, mask: MLXArray?) -> (MLXArray, MLXArray, MLXArray) {
+ var qIn = qProj(x)
+ var kIn = kProj(x)
+ var vIn = vProj(x)
+ if let mask {
+ let expanded = mask.expandedDimensions(axis: -1)
+ qIn = MLX.where(expanded, qIn, MLXArray.zeros(like: qIn))
+ kIn = MLX.where(expanded, kIn, MLXArray.zeros(like: kIn))
+ vIn = MLX.where(expanded, vIn, MLXArray.zeros(like: vIn))
+ }
+ let (qOut, qState) = qConv1d(qIn, state: cache?[0])
+ let (kOut, kState) = kConv1d(kIn, state: cache?[1])
+ let (vOut, vState) = vConv1d(vIn, state: cache?[2])
+ if let cache {
+ cache[0] = qState
+ cache[1] = kState
+ cache[2] = vState
+ }
+ return (qOut, kOut, vOut)
+ }
+
+ private func projectGates(_ x: MLXArray) -> (MLXArray, MLXArray) {
+ if noKDALoRA, let fProj, let gProj {
+ return (fProj(x), gProj(x))
+ }
+ guard let fAProj, let fBProj, let gAProj, let gBProj else {
+ preconditionFailure("BailingHybridLinearAttention gate projections not initialized")
+ }
+ return (fBProj(fAProj(x)), gBProj(gAProj(x)))
+ }
+}
diff --git a/Sources/BasaltInference/Models/BailingHybrid/BailingHybridMLA.swift b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridMLA.swift
new file mode 100644
index 000000000..192db3bb7
--- /dev/null
+++ b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridMLA.swift
@@ -0,0 +1,159 @@
+import Foundation
+import MLX
+import MLXLMCommon
+import MLXNN
+
+package final class BailingHybridMLAAttention: Module {
+ let layerIdx: Int
+ let numHeads: Int
+ let kvHeads: Int
+ let headDim: Int
+ let qkNopeHeadDim: Int
+ let qkRopeHeadDim: Int
+ let qkHeadDim: Int
+ let vHeadDim: Int
+ let kvLoraRank: Int
+ let gateGranularity: String?
+ let scale: Float
+ let rope: RoPELayer
+
+ @ModuleInfo(key: "q_proj") var qProj: Linear?
+ @ModuleInfo(key: "q_a_proj") var qAProj: Linear?
+ @ModuleInfo(key: "q_a_layernorm") var qALayerNorm: RMSNorm?
+ @ModuleInfo(key: "q_b_proj") var qBProj: Linear?
+ @ModuleInfo(key: "kv_a_proj_with_mqa") var kvAProjWithMqa: Linear
+ @ModuleInfo(key: "kv_a_layernorm") var kvALayerNorm: RMSNorm
+ @ModuleInfo(key: "kv_b_proj") var kvBProj: Linear
+ @ModuleInfo(key: "g_proj") var gProj: Linear?
+ @ModuleInfo(key: "dense") var dense: Linear
+
+ package init(_ config: BailingHybridConfiguration, layerIdx: Int) {
+ self.layerIdx = layerIdx
+ self.numHeads = config.numAttentionHeads
+ self.kvHeads = config.numAttentionHeads
+ self.qkNopeHeadDim = config.qkNopeHeadDim
+ self.qkRopeHeadDim = config.qkRopeHeadDim
+ self.qkHeadDim = config.qkHeadDim
+ self.headDim = config.vHeadDim
+ self.vHeadDim = config.vHeadDim
+ self.kvLoraRank = config.kvLoraRank
+ self.gateGranularity = config.gatedAttentionGranularity
+ self.scale = Self.attentionScale(qkHeadDim: config.qkHeadDim, ropeScaling: config.ropeScaling)
+
+ let hidden = config.hiddenSize
+ let bias = config.useQKVBias
+ if let qLoraRank = config.qLoraRank {
+ self._qAProj.wrappedValue = Linear(hidden, qLoraRank, bias: bias)
+ self._qALayerNorm.wrappedValue = RMSNorm(dimensions: qLoraRank, eps: config.rmsNormEps)
+ self._qBProj.wrappedValue = Linear(qLoraRank, config.numAttentionHeads * config.qkHeadDim, bias: false)
+ } else {
+ self._qProj.wrappedValue = Linear(hidden, config.numAttentionHeads * config.qkHeadDim, bias: false)
+ }
+
+ self._kvAProjWithMqa.wrappedValue = Linear(hidden, config.kvLoraRank + config.qkRopeHeadDim, bias: bias)
+ self._kvALayerNorm.wrappedValue = RMSNorm(dimensions: config.kvLoraRank, eps: config.rmsNormEps)
+ self._kvBProj.wrappedValue = Linear(
+ config.kvLoraRank,
+ config.numAttentionHeads * (config.qkNopeHeadDim + config.vHeadDim),
+ bias: false
+ )
+
+ if config.gatedAttentionGranularity == "head_wise" {
+ self._gProj.wrappedValue = Linear(hidden, config.numAttentionHeads, bias: false)
+ } else if config.gatedAttentionGranularity == "element_wise" {
+ self._gProj.wrappedValue = Linear(hidden, config.numAttentionHeads * config.vHeadDim, bias: false)
+ }
+
+ self._dense.wrappedValue = Linear(config.numAttentionHeads * config.vHeadDim, hidden, bias: bias)
+ self.rope = initializeRope(
+ dims: config.qkRopeHeadDim,
+ base: config.ropeTheta,
+ traditional: config.ropeInterleave,
+ scalingConfig: config.ropeScaling,
+ maxPositionEmbeddings: config.maxPositionEmbeddings
+ )
+ }
+
+ package func callAsFunction(
+ _ x: MLXArray,
+ mask: MLXFast.ScaledDotProductAttentionMaskMode,
+ cache: KVCache?,
+ probe: (any ForwardProbe)? = nil
+ ) -> MLXArray {
+ let batch = x.dim(0)
+ let length = x.dim(1)
+
+ let rawQ = projectQuery(x).reshaped(batch, length, numHeads, qkHeadDim).transposed(0, 2, 1, 3)
+ let splitQ = split(rawQ, indices: [qkNopeHeadDim], axis: -1)
+ let (qNope, qPeRaw) = (splitQ[0], splitQ[1])
+
+ let compressed = kvAProjWithMqa(x)
+ let splitCompressed = split(compressed, indices: [kvLoraRank], axis: -1)
+ let kvLatent = kvALayerNorm(splitCompressed[0])
+ let kPeRaw = splitCompressed[1].reshaped(batch, length, 1, qkRopeHeadDim).transposed(0, 2, 1, 3)
+
+ let kv = kvBProj(kvLatent)
+ .reshaped(batch, length, numHeads, qkNopeHeadDim + vHeadDim)
+ .transposed(0, 2, 1, 3)
+ let splitKV = split(kv, indices: [qkNopeHeadDim], axis: -1)
+ let (kNope, values) = (splitKV[0], splitKV[1])
+
+ let offset = cache?.ropeOffset
+ let qPe = applyRotaryPosition(rope, to: qPeRaw, offset: offset)
+ let kPeRotated = applyRotaryPosition(rope, to: kPeRaw, offset: offset)
+ let kPe = broadcast(kPeRotated, to: [batch, numHeads, length, qkRopeHeadDim])
+
+ let queries = concatenated([qNope, qPe], axis: -1)
+ let keys = concatenated([kNope, kPe], axis: -1)
+
+ let attended = attentionWithCacheUpdate(
+ queries: queries,
+ keys: keys,
+ values: values,
+ cache: cache,
+ scale: scale,
+ mask: mask
+ )
+ var merged = attended.transposed(0, 2, 1, 3)
+ if let gProj {
+ let gate = sigmoid(gProj(x).asType(.float32)).asType(x.dtype)
+ if gateGranularity == "head_wise" {
+ merged = merged * gate.expandedDimensions(axis: -1)
+ } else {
+ merged = merged * gate.reshaped(batch, length, numHeads, vHeadDim)
+ }
+ }
+ if let probe {
+ var perHead = merged.transposed(0, 2, 1, 3)
+ if let headMask = probe.headMask(layer: layerIdx) {
+ perHead = perHead * headMask.reshaped(1, numHeads, 1, 1).asType(perHead.dtype)
+ }
+ probe.headOutputs(layer: layerIdx, perHead)
+ merged = perHead.transposed(0, 2, 1, 3)
+ }
+ return dense(merged.reshaped(batch, length, -1))
+ }
+
+ private func projectQuery(_ x: MLXArray) -> MLXArray {
+ if let qAProj, let qALayerNorm, let qBProj {
+ return qBProj(qALayerNorm(qAProj(x)))
+ }
+ guard let qProj else {
+ preconditionFailure("BailingHybridMLAAttention query projection not initialized")
+ }
+ return qProj(x)
+ }
+
+ private static func attentionScale(qkHeadDim: Int, ropeScaling: [String: StringOrNumber]?) -> Float {
+ var scale = pow(Float(qkHeadDim), -0.5)
+ guard let ropeScaling,
+ let mscaleAllDim = ropeScaling["mscale_all_dim"]?.asFloat(), mscaleAllDim != 0,
+ let factor = ropeScaling["factor"]?.asFloat(), factor > 1
+ else {
+ return scale
+ }
+ let mscale = 0.1 * mscaleAllDim * log(factor) + 1.0
+ scale *= mscale * mscale
+ return scale
+ }
+}
diff --git a/Sources/BasaltInference/Models/BailingHybrid/BailingHybridMoE.swift b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridMoE.swift
new file mode 100644
index 000000000..9c17724c6
--- /dev/null
+++ b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridMoE.swift
@@ -0,0 +1,178 @@
+import Foundation
+import MLX
+import MLXLMCommon
+import MLXNN
+
+package enum BailingHybridRouter {
+ package struct Config: Sendable, Equatable {
+ package let topK: Int
+ package let nGroup: Int
+ package let topkGroup: Int
+ package let normTopkProb: Bool
+ package let routedScalingFactor: Float
+ package let enableExpertBias: Bool
+
+ package init(
+ topK: Int,
+ nGroup: Int,
+ topkGroup: Int,
+ normTopkProb: Bool,
+ routedScalingFactor: Float,
+ enableExpertBias: Bool
+ ) {
+ self.topK = topK
+ self.nGroup = nGroup
+ self.topkGroup = topkGroup
+ self.normTopkProb = normTopkProb
+ self.routedScalingFactor = routedScalingFactor
+ self.enableExpertBias = enableExpertBias
+ }
+
+ package init(_ config: BailingHybridConfiguration) {
+ self.init(
+ topK: config.numExpertsPerTok,
+ nGroup: config.nGroup,
+ topkGroup: config.topkGroup,
+ normTopkProb: config.normTopkProb,
+ routedScalingFactor: config.routedScalingFactor,
+ enableExpertBias: config.moeRouterEnableExpertBias
+ )
+ }
+ }
+
+ package static func route(
+ logits: MLXArray,
+ expertBias: MLXArray?,
+ config: Config,
+ expertMask: MLXArray? = nil
+ ) -> (indices: MLXArray, weights: MLXArray) {
+ var scores = sigmoid(logits.asType(.float32))
+ var selection = config.enableExpertBias
+ ? (expertBias.map { scores + $0.asType(.float32) } ?? scores)
+ : scores
+ if let expertMask {
+ let keep = expertMask .> 0
+ scores = MLX.where(keep, scores, MLXArray(Float(0), dtype: scores.dtype))
+ selection = MLX.where(keep, selection, MLXArray(-Float.infinity, dtype: selection.dtype))
+ }
+
+ let dropGroups = config.nGroup - config.topkGroup
+ if dropGroups > 0 {
+ let numExperts = selection.dim(-1)
+ let expertsPerGroup = numExperts / config.nGroup
+ let prefixShape = Array(selection.shape.dropLast())
+ let grouped = selection.reshaped(prefixShape + [config.nGroup, expertsPerGroup])
+ let groupScores = MLX.top(grouped, k: min(2, expertsPerGroup), axis: -1).sum(axis: -1, keepDims: true)
+ let dropIdx = stopGradient(
+ argPartition(groupScores, kth: dropGroups - 1, axis: -2)[.ellipsis, .. 1, config.normTopkProb {
+ let denominator = weights.sum(axis: -1, keepDims: true) + MLXArray(Float(1e-20))
+ weights = weights / denominator
+ }
+ weights = weights * config.routedScalingFactor
+ return (indices, weights)
+ }
+}
+
+package final class BailingHybridMLP: Module, UnaryLayer {
+ @ModuleInfo(key: "gate_proj") var gateProj: Linear
+ @ModuleInfo(key: "up_proj") var upProj: Linear
+ @ModuleInfo(key: "down_proj") var downProj: Linear
+
+ package init(hiddenSize: Int, intermediateSize: Int, bias: Bool = false) {
+ self._gateProj.wrappedValue = Linear(hiddenSize, intermediateSize, bias: bias)
+ self._upProj.wrappedValue = Linear(hiddenSize, intermediateSize, bias: bias)
+ self._downProj.wrappedValue = Linear(intermediateSize, hiddenSize, bias: bias)
+ }
+
+ package func callAsFunction(_ x: MLXArray) -> MLXArray {
+ downProj(silu(gateProj(x)) * upProj(x))
+ }
+}
+
+package final class BailingHybridGate: Module {
+ let routerConfig: BailingHybridRouter.Config
+
+ @ParameterInfo(key: "weight") var weight: MLXArray
+ @ParameterInfo(key: "expert_bias") var expertBias: MLXArray?
+
+ package init(_ config: BailingHybridConfiguration) {
+ self.routerConfig = BailingHybridRouter.Config(config)
+ self._weight.wrappedValue = MLXArray.zeros([config.numExperts, config.hiddenSize], dtype: .float32)
+ if config.moeRouterEnableExpertBias {
+ self._expertBias.wrappedValue = MLXArray.zeros([config.numExperts], dtype: .float32)
+ }
+ }
+
+ package func callAsFunction(
+ _ x: MLXArray,
+ layerIdx: Int = 0,
+ probe: (any ForwardProbe)? = nil
+ ) -> (indices: MLXArray, weights: MLXArray) {
+ let logits = matmul(x.asType(.float32), weight.asType(.float32).T)
+ probe?.routerLogits(layer: layerIdx, logits)
+ let routed = BailingHybridRouter.route(
+ logits: logits,
+ expertBias: expertBias,
+ config: routerConfig,
+ expertMask: probe?.expertMask(layer: layerIdx)
+ )
+ probe?.routerTopK(layer: layerIdx, indices: routed.indices, gates: routed.weights)
+ return routed
+ }
+}
+
+package final class BailingHybridSparseMoE: Module, UnaryLayer {
+ let layerIdx: Int
+
+ @ModuleInfo(key: "gate") var gate: BailingHybridGate
+ @ModuleInfo(key: "experts") var experts: SwitchGLU
+ @ModuleInfo(key: "shared_experts") var sharedExperts: BailingHybridMLP?
+
+ package init(_ config: BailingHybridConfiguration, layerIdx: Int = 0) {
+ self.layerIdx = layerIdx
+ self._gate.wrappedValue = BailingHybridGate(config)
+ self._experts.wrappedValue = SwitchGLU(
+ inputDims: config.hiddenSize,
+ hiddenDims: config.moeIntermediateSize,
+ numExperts: config.numExperts,
+ bias: config.useBias
+ )
+ if config.numSharedExperts > 0 {
+ self._sharedExperts.wrappedValue = BailingHybridMLP(
+ hiddenSize: config.hiddenSize,
+ intermediateSize: config.sharedExpertIntermediateSize,
+ bias: config.useBias
+ )
+ }
+ }
+
+ package func callAsFunction(_ x: MLXArray) -> MLXArray {
+ callAsFunction(x, probe: nil)
+ }
+
+ package func callAsFunction(_ x: MLXArray, probe: (any ForwardProbe)?) -> MLXArray {
+ let (indices, weights) = gate(x, layerIdx: layerIdx, probe: probe)
+ let routed = experts(x, indices)
+ var out = (routed.asType(.float32) * weights.expandedDimensions(axis: -1))
+ .sum(axis: -2)
+ .asType(x.dtype)
+ if let sharedExperts {
+ out = out + sharedExperts(x)
+ }
+ return out
+ }
+}
diff --git a/Sources/BasaltInference/Models/BailingHybrid/BailingHybridModel.swift b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridModel.swift
new file mode 100644
index 000000000..48c84a1e0
--- /dev/null
+++ b/Sources/BasaltInference/Models/BailingHybrid/BailingHybridModel.swift
@@ -0,0 +1,260 @@
+import BasaltCore
+import Foundation
+import MLX
+import MLXLLM
+import MLXLMCommon
+import MLXNN
+import MLXVLM
+
+package final class BailingHybridDecoderLayer: Module {
+ let isMLA: Bool
+
+ @ModuleInfo(key: "attention") var attention: Module
+ @ModuleInfo(key: "mlp") var mlp: Module
+ @ModuleInfo(key: "input_layernorm") var inputLayerNorm: RMSNorm
+ @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: RMSNorm
+
+ package init(_ config: BailingHybridConfiguration, layerIdx: Int) {
+ self.isMLA = config.isMLALayer(layerIdx)
+ if isMLA {
+ self._attention.wrappedValue = BailingHybridMLAAttention(config, layerIdx: layerIdx)
+ } else {
+ self._attention.wrappedValue = BailingHybridLinearAttention(config, layerIdx: layerIdx)
+ }
+ if config.isMoELayer(layerIdx) {
+ self._mlp.wrappedValue = BailingHybridSparseMoE(config, layerIdx: layerIdx)
+ } else {
+ self._mlp.wrappedValue = BailingHybridMLP(
+ hiddenSize: config.hiddenSize,
+ intermediateSize: config.intermediateSize,
+ bias: config.useBias
+ )
+ }
+ self._inputLayerNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps)
+ self._postAttentionLayerNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps)
+ }
+
+ package func callAsFunction(
+ _ x: MLXArray,
+ mask: MLXFast.ScaledDotProductAttentionMaskMode,
+ cache: KVCache?,
+ probe: (any ForwardProbe)? = nil
+ ) -> MLXArray {
+ let normedInput = inputLayerNorm(x)
+ let attnOut: MLXArray
+ if let mla = attention as? BailingHybridMLAAttention {
+ attnOut = mla(normedInput, mask: mask, cache: cache, probe: probe)
+ } else if let kda = attention as? BailingHybridLinearAttention {
+ attnOut = kda(normedInput, cache: cache as? ArraysCache, probe: probe)
+ } else {
+ preconditionFailure("Unexpected attention module in BailingHybridDecoderLayer")
+ }
+ let hidden = x + attnOut
+ let normedPost = postAttentionLayerNorm(hidden)
+ let mlpOut: MLXArray
+ if let moe = mlp as? BailingHybridSparseMoE {
+ mlpOut = moe(normedPost, probe: probe)
+ } else if let dense = mlp as? BailingHybridMLP {
+ mlpOut = dense(normedPost)
+ } else {
+ preconditionFailure("Unexpected MLP module in BailingHybridDecoderLayer")
+ }
+ return hidden + mlpOut
+ }
+}
+
+public final class BailingHybridModelInner: Module {
+ @ModuleInfo(key: "word_embeddings") var wordEmbeddings: Embedding
+ @ModuleInfo(key: "layers") var layers: [BailingHybridDecoderLayer]
+ @ModuleInfo(key: "norm") var norm: RMSNorm
+
+ let firstMLAIndex: Int?
+
+ public init(_ config: BailingHybridConfiguration) {
+ self._wordEmbeddings.wrappedValue = Embedding(
+ embeddingCount: config.vocabSize,
+ dimensions: config.hiddenSize
+ )
+ let builtLayers = (0 ..< config.numHiddenLayers).map { index in
+ BailingHybridDecoderLayer(config, layerIdx: index)
+ }
+ self._layers.wrappedValue = builtLayers
+ self._norm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps)
+ self.firstMLAIndex = builtLayers.firstIndex(where: \.isMLA)
+ }
+
+ public func callAsFunction(
+ _ inputs: MLXArray,
+ cache: [KVCache]? = nil,
+ probe: (any ForwardProbe)? = nil
+ ) -> MLXArray {
+ var hidden = wordEmbeddings(inputs)
+ let mlaCache = firstMLAIndex.flatMap { slot in
+ cache.flatMap { slot < $0.count ? $0[slot] : nil }
+ }
+ let mlaMask = createAttentionMask(h: hidden, cache: mlaCache)
+ for (index, layer) in layers.enumerated() {
+ let layerCache = cache.flatMap { index < $0.count ? $0[index] : nil }
+ let layerMask: MLXFast.ScaledDotProductAttentionMaskMode = layer.isMLA ? mlaMask : .none
+ hidden = layer(hidden, mask: layerMask, cache: layerCache, probe: probe)
+ if let probe {
+ hidden = probe.residual(layer: index, hidden)
+ }
+ }
+ return norm(hidden)
+ }
+}
+
+public final class BailingHybridModel: Module, LLMModel, KVCacheDimensionProvider, LoRAModel, BasaltProbableModel {
+ public static let modelType = "bailing_hybrid"
+
+ public let vocabularySize: Int
+ public let kvHeads: [Int]
+ public let configuration: BailingHybridConfiguration
+
+ @ModuleInfo(key: "model") public var model: BailingHybridModelInner
+ @ModuleInfo(key: "lm_head") var lmHead: Linear?
+
+ public init(_ config: BailingHybridConfiguration) {
+ self.configuration = config
+ self.vocabularySize = config.vocabSize
+ self.kvHeads = Array(repeating: config.numAttentionHeads, count: config.numHiddenLayers)
+ self._model.wrappedValue = BailingHybridModelInner(config)
+ if !config.tieWordEmbeddings {
+ self._lmHead.wrappedValue = Linear(config.hiddenSize, config.vocabSize, bias: false)
+ }
+ }
+
+ public convenience init(configurationData data: Data) throws {
+ let config = try JSONDecoder.json5().decode(BailingHybridConfiguration.self, from: data).validated()
+ self.init(config)
+ }
+
+ public var loraLayers: [Module] {
+ model.layers
+ }
+
+ public var toolCallFormat: ToolCallFormat? {
+ .glm4
+ }
+
+ public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray {
+ forwardWithProbe(inputs, cache: cache, probe: nil)
+ }
+
+ package func forwardWithProbe(_ inputs: MLXArray, cache: [KVCache]?, probe: (any ForwardProbe)?) -> MLXArray {
+ let hidden = model(inputs, cache: cache, probe: probe)
+ if let lmHead {
+ return lmHead(hidden)
+ }
+ return model.wordEmbeddings.asLinear(hidden)
+ }
+
+ public func newCache(parameters: GenerateParameters?) throws -> [any KVCache] {
+ try model.layers.map { layer in
+ layer.isMLA ? try makeAttentionKVCache(parameters: parameters) : ArraysCache(size: 4)
+ }
+ }
+
+ public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
+ let mapped = BailingHybridCheckpoint.sanitize(weights, config: configuration)
+ FlintModel.quantizeModulesMatchingPackedWeights(in: self, weights: mapped)
+ return mapped
+ }
+}
+
+enum BailingHybridCheckpoint {
+ private static let projections = ["gate_proj", "up_proj", "down_proj"]
+ private static let quantParts = ["weight", "scales", "biases"]
+
+ static func sanitize(_ weights: [String: MLXArray], config: BailingHybridConfiguration) -> [String: MLXArray] {
+ var out = weights.filter { key, _ in !shouldDrop(key, config: config) }
+ stackExpertsIfUnmerged(&out, config: config)
+ canonicalizeShortConvs(&out, kernelSize: config.convKernelSize)
+ return out
+ }
+
+ private static func shouldDrop(_ key: String, config: BailingHybridConfiguration) -> Bool {
+ if config.tieWordEmbeddings && key.hasPrefix("lm_head.") {
+ return true
+ }
+ if !config.moeRouterEnableExpertBias && key.hasSuffix(".mlp.gate.expert_bias") {
+ return true
+ }
+ if key.contains("rotary_emb.inv_freq")
+ || key.hasPrefix("mtp_")
+ || key.contains(".mtp_")
+ || key.hasPrefix("mtp.")
+ || key.contains(".mtp.")
+ {
+ return true
+ }
+ let parts = key.split(separator: ".", maxSplits: 3)
+ if parts.count >= 3, parts[0] == "model", parts[1] == "layers",
+ let layerIndex = Int(parts[2]), layerIndex >= config.numHiddenLayers
+ {
+ return true
+ }
+ return false
+ }
+
+ private static func stackExpertsIfUnmerged(
+ _ out: inout [String: MLXArray],
+ config: BailingHybridConfiguration
+ ) {
+ for layerIdx in 0 ..< config.numHiddenLayers where config.isMoELayer(layerIdx) {
+ let prefix = "model.layers.\(layerIdx).mlp.experts"
+ for projection in projections {
+ for part in quantParts {
+ stackExpertPart(&out, prefix: prefix, projection: projection, part: part, count: config.numExperts)
+ }
+ }
+ }
+ }
+
+ private static func stackExpertPart(
+ _ out: inout [String: MLXArray],
+ prefix: String,
+ projection: String,
+ part: String,
+ count: Int
+ ) {
+ guard count > 0, out["\(prefix).0.\(projection).\(part)"] != nil else { return }
+ let keys = (0 ..< count).map { "\(prefix).\($0).\(projection).\(part)" }
+ guard keys.allSatisfy({ out[$0] != nil }) else { return }
+ let slices = keys.compactMap { out.removeValue(forKey: $0) }
+ out["\(prefix).\(projection).\(part)"] = MLX.stacked(slices)
+ }
+
+ private static func canonicalizeShortConvs(_ out: inout [String: MLXArray], kernelSize: Int) {
+ for key in Array(out.keys) {
+ if key.hasSuffix("_conv1d.weight"), let weight = out.removeValue(forKey: key) {
+ let target = String(key.dropLast(".weight".count)) + ".conv.weight"
+ out[target] = normalizeConvWeight(weight, kernelSize: kernelSize)
+ } else if key.hasSuffix("_conv1d.conv.weight"), let weight = out[key] {
+ out[key] = normalizeConvWeight(weight, kernelSize: kernelSize)
+ }
+ }
+ }
+
+ private static func normalizeConvWeight(_ weight: MLXArray, kernelSize: Int) -> MLXArray {
+ if weight.ndim == 2 {
+ return weight.expandedDimensions(axis: -1)
+ }
+ if weight.ndim == 3 && weight.dim(1) == 1 && weight.dim(2) == kernelSize && kernelSize != 1 {
+ return weight.swappedAxes(1, 2)
+ }
+ return weight
+ }
+}
+
+extension MLXInferenceEngine {
+ static func registerBailingHybridAliases() async {
+ await LLMTypeRegistry.shared.registerModelType(BailingHybridModel.modelType) { data in
+ try BailingHybridModel(configurationData: data)
+ }
+ await VLMTypeRegistry.shared.registerModelType(BailingHybridModel.modelType) { data in
+ try BailingHybridModel(configurationData: data)
+ }
+ }
+}
diff --git a/Tests/BasaltTests/BailingHybridIntegrationTests.swift b/Tests/BasaltTests/BailingHybridIntegrationTests.swift
new file mode 100644
index 000000000..f649719ba
--- /dev/null
+++ b/Tests/BasaltTests/BailingHybridIntegrationTests.swift
@@ -0,0 +1,274 @@
+import Foundation
+import MLX
+import MLXLLM
+import MLXLMCommon
+import MLXNN
+import MLXVLM
+import Testing
+@testable import BasaltCore
+@testable import BasaltInference
+
+@Suite("BailingHybrid (Ling-3.0) P0: decode parity, sanitize, disk cache and capabilities (#672)", .serialized)
+struct BailingHybridIntegrationTests {
+ static let sequenceTokens: [Int32] = [5, 19, 42, 7, 88, 13, 64, 21, 9, 31, 200, 3, 3, 150, 77, 12, 44, 101, 6, 250]
+
+ @Test("Tiny bailing_hybrid cache layout has 4-slot ArraysCache on KDA layers and KVCacheSimple on MLA layers")
+ func cacheLayoutAndAnatomy() throws {
+ let model = try #require(try TinyModel.make(.bailingHybrid) as? BailingHybridModel)
+ #expect(model.loraLayers.count == 6 && model.toolCallFormat == .glm4)
+ let caches = try model.newCache(parameters: nil)
+ #expect(caches.count == 6)
+ #expect(caches.map { $0 is ArraysCache } == [true, true, false, true, true, false])
+ #expect(caches[2] is KVCacheSimple && caches[5] is KVCacheSimple)
+
+ _ = model(MLXArray(Self.sequenceTokens)[.newAxis], cache: caches)
+ eval(caches.flatMap { $0.innerState() })
+ for idx in [0, 1, 3, 4] {
+ let kdaCache = try #require(caches[idx] as? ArraysCache)
+ #expect(kdaCache[0]?.shape == [1, 3, 128])
+ #expect(kdaCache[1]?.shape == [1, 3, 128])
+ #expect(kdaCache[2]?.shape == [1, 3, 128])
+ #expect(kdaCache[3]?.shape == [1, 4, 32, 32])
+ #expect(kdaCache[3]?.dtype == .float32)
+ }
+
+ let scan = AnatomyScan(model: model, caches: try model.newCache(parameters: nil))
+ let configJSON = try #require(try JSONSerialization.jsonObject(with: Data(TinyModel.Family.bailingHybrid.config.utf8)) as? [String: Any])
+ let anatomy = scan.anatomy(config: configJSON)
+ #expect(anatomy.hiddenSize == 64 && anatomy.layers.count == 6)
+ #expect(anatomy.layers.map(\.kind) == ["linear attention", "linear attention", "full attention", "linear attention", "linear attention", "full attention"])
+ #expect(anatomy.layers[0].heads == 4 && anatomy.layers[0].kvHeads == 4 && anatomy.layers[0].headDim == 32)
+ #expect(anatomy.layers[0].experts == nil && anatomy.layers[1].experts == 8 && anatomy.layers[5].experts == 8)
+ }
+
+ @Test("Full forward matches token-by-token and chunked (1, 3, 7) cached decode with exact greedy ids and logits within 1e-4",
+ arguments: [1, 3, 7])
+ func decodeParityAcrossChunks(chunk: Int) throws {
+ let model = try TinyModel.make(.bailingHybrid)
+ let full = model(MLXArray(Self.sequenceTokens)[.newAxis], cache: nil).asType(.float32)
+ let caches = try model.newCache(parameters: nil)
+ var pieces: [MLXArray] = []
+ var cursor = 0
+ while cursor < Self.sequenceTokens.count {
+ let end = min(Self.sequenceTokens.count, cursor + chunk)
+ let slice = Array(Self.sequenceTokens[cursor ..< end])
+ pieces.append(model(MLXArray(slice)[.newAxis], cache: caches).asType(.float32))
+ cursor = end
+ }
+ let stepped = concatenated(pieces, axis: 1)
+ let gap = abs(stepped - full).max().item(Float.self)
+ #expect(stepped.shape == [1, Self.sequenceTokens.count, 256])
+ #expect(gap < 1e-4, "chunk \(chunk) max logit gap \(gap)")
+ #expect(argMax(stepped, axis: -1).asArray(Int32.self) == argMax(full, axis: -1).asArray(Int32.self))
+ }
+
+ @Test("Optional variants (KDA LoRA, no q_lora_rank, element_wise/nil gate, tied embeddings, kernel 1, rope scaling) decode identically full vs T=1")
+ func optionalArchitectureVariants() throws {
+ let variants: [String] = [
+ #""no_kda_lora": false, "q_lora_rank": null, "gated_attention_proj_granularity_type": "element_wise", "tie_word_embeddings": true, "#,
+ #""short_conv_kernel_size": 1, "gated_attention_proj_granularity_type": null, "kda_safe_gate": false, "num_shared_experts": 0, "#,
+ #""rope_scaling": {"type": "yarn", "factor": 4.0, "mscale_all_dim": 1.0, "original_max_position_embeddings": 4096}, "moe_router_enable_expert_bias": false, "#,
+ ]
+ for extra in variants {
+ let model = try TinyModel.make(.bailingHybrid, adding: extra)
+ let tokens = Array(Self.sequenceTokens.prefix(8))
+ let full = model(MLXArray(tokens)[.newAxis], cache: nil).asType(.float32)
+ let caches = try model.newCache(parameters: nil)
+ let steps = tokens.map { model(MLXArray([$0]).reshaped(1, 1), cache: caches).asType(.float32) }
+ let stepped = concatenated(steps, axis: 1)
+ let gap = abs(stepped - full).max().item(Float.self)
+ #expect(gap < 1e-4, "variant gap \(gap)")
+ #expect(argMax(stepped, axis: -1).asArray(Int32.self) == argMax(full, axis: -1).asArray(Int32.self))
+ }
+ }
+
+ @Test("Packed-weight sanitize round-trip keeps router, short-conv, A_log and dt_bias in fp while quantizing packed linear and switch layers")
+ func packedWeightSanitizeRoundTrip() throws {
+ let source = try Self.makePackedTinyModel()
+ let expectedLogits = source(MLXArray(Self.sequenceTokens)[.newAxis], cache: nil).asType(.float32)
+ let hfStyleWeights = try Self.unmergeIntoHFCheckpoint(Dictionary(uniqueKeysWithValues: source.parameters().flattened()))
+
+ let restored = try BailingHybridModel(configurationData: Data(TinyModel.Family.bailingHybrid.config.utf8))
+ let sanitized = restored.sanitize(weights: hfStyleWeights)
+ try restored.update(parameters: ModuleParameters.unflattened(sanitized), verify: [.all])
+ eval(restored)
+
+ let modules = Dictionary(uniqueKeysWithValues: restored.namedModules())
+ #expect(!(modules["model.layers.1.mlp.gate"] is any Quantized))
+ #expect(!(modules["model.layers.0.attention.q_conv1d.conv"] is any Quantized))
+ #expect(modules["model.layers.0.attention.q_proj"] is any Quantized)
+ #expect(modules["model.layers.2.attention.dense"] is any Quantized)
+ #expect(modules["model.layers.1.mlp.experts.gate_proj"] is any Quantized)
+
+ let params = Dictionary(uniqueKeysWithValues: restored.parameters().flattened())
+ #expect(params["model.layers.1.mlp.gate.weight"]?.dtype != .uint32)
+ #expect(params["model.layers.1.mlp.gate.expert_bias"]?.dtype != .uint32)
+ #expect(params["model.layers.0.attention.q_conv1d.conv.weight"]?.dtype != .uint32)
+ #expect(params["model.layers.0.attention.A_log"]?.dtype == .float32)
+ #expect(params["model.layers.0.attention.dt_bias"]?.dtype == .float32)
+
+ let restoredLogits = restored(MLXArray(Self.sequenceTokens)[.newAxis], cache: nil).asType(.float32)
+ #expect(abs(restoredLogits - expectedLogits).max().item(Float.self) == 0)
+ }
+
+ @Test("Sanitize handles 2D conv weights, tied embeddings, unused expert_bias, and preserves incomplete unmerged experts")
+ func sanitizeEdgeCases() throws {
+ var config = try JSONDecoder.json5().decode(BailingHybridConfiguration.self, from: Data(TinyModel.Family.bailingHybrid.config.utf8))
+ config.tieWordEmbeddings = true
+ config.moeRouterEnableExpertBias = false
+
+ let raw: [String: MLXArray] = [
+ "lm_head.weight": MLXArray.zeros([256, 64]),
+ "model.layers.1.mlp.gate.expert_bias": MLXArray.zeros([8]),
+ "model.layers.0.attention.q_conv1d.weight": MLXArray.zeros([128, 4]),
+ "model.layers.0.attention.k_conv1d.conv.weight": MLXArray.zeros([128, 1, 4]),
+ "model.layers.1.mlp.experts.0.gate_proj.weight": MLXArray.zeros([32, 64]),
+ "model.layers.1.mlp.experts.1.gate_proj.weight": MLXArray.zeros([32, 64]),
+ "mtp_head.weight": MLXArray.zeros([8, 8]),
+ ]
+ let sanitized = BailingHybridCheckpoint.sanitize(raw, config: config)
+ #expect(sanitized["lm_head.weight"] == nil)
+ #expect(sanitized["model.layers.1.mlp.gate.expert_bias"] == nil)
+ #expect(sanitized["mtp_head.weight"] == nil)
+ #expect(sanitized["model.layers.0.attention.q_conv1d.conv.weight"]?.shape == [128, 4, 1])
+ #expect(sanitized["model.layers.0.attention.k_conv1d.conv.weight"]?.shape == [128, 4, 1])
+ #expect(sanitized["model.layers.1.mlp.experts.gate_proj.weight"] == nil)
+ #expect(sanitized["model.layers.1.mlp.experts.0.gate_proj.weight"] != nil)
+ #expect(sanitized["model.layers.1.mlp.experts.1.gate_proj.weight"] != nil)
+ }
+
+ @Test("ModelDeepCheck and ModelInspector handle quantization_config-only and dual quantization configs without double-quantizing")
+ func deepCheckAndInspectorRecognizeQuantizedCheckpoints() async throws {
+ let source = try Self.makePackedTinyModel()
+ let rawWeights = Dictionary(uniqueKeysWithValues: source.parameters().flattened())
+ let tensors = Dictionary(uniqueKeysWithValues: rawWeights.map { key, arr in
+ (key, ModelInspector.Tensor(dtype: arr.dtype == .uint32 ? "U32" : "F32", shape: arr.shape, end: 0))
+ })
+ let quantOnly = TinyModel.Family.bailingHybrid.config.replacingOccurrences(
+ of: #""model_type""#,
+ with: #""quantization_config": {"bits": 4, "group_size": 32, "quant_method": "mlx"}, "model_type""#
+ )
+ let dualQuant = TinyModel.Family.bailingHybrid.config.replacingOccurrences(
+ of: #""model_type""#,
+ with: #""quantization": {"bits": 4, "group_size": 32}, "quantization_config": {"bits": 4, "group_size": 32}, "model_type""#
+ )
+ for cfg in [quantOnly, dualQuant] {
+ let problems = await ModelDeepCheck.loadProblems(configuration: Data(cfg.utf8), tensors: tensors, metadata: [:])
+ #expect(problems.isEmpty, "ModelDeepCheck reported \(problems)")
+ }
+
+ let json = try #require(try JSONSerialization.jsonObject(with: Data(quantOnly.utf8)) as? [String: Any])
+ let bitWidth = ModelInspector.bitWidth(
+ tensors: tensors, dtypes: ["U32", "F32"], config: ModelInspector.QuantizationConfig(json: json), modelId: "Ling-3.0-tiny-MLX-4bit"
+ )
+ #expect(bitWidth.bits == 4 && bitWidth.mismatch == nil)
+ }
+}
+
+extension BailingHybridIntegrationTests {
+ @Test("ModelCapabilities, ModelProfile, registry registration, recurrent state probe, and disk snapshot round-trip work for bailing_hybrid")
+ func capabilitiesProfileRegistryAndSnapshot() async throws {
+ await MLXInferenceEngine.registerAliases()
+ #expect(await LLMTypeRegistry.shared.contains("bailing_hybrid"))
+ #expect(await VLMTypeRegistry.shared.contains("bailing_hybrid"))
+
+ let capabilities = try #require(ModelCapabilities.of(modelType: "bailing_hybrid"))
+ #expect(capabilities.allows(.promptCacheReuse) && capabilities.allows(.grammarJumpForward) && capabilities.allows(.batchedDecode))
+ #expect(!capabilities.allows(.speculativeLookup) && !capabilities.allows(.kvZones) && !capabilities.allows(.kvHeadSplit))
+ #expect(!capabilities.allows(.kvQuantization) && !capabilities.allows(.quest) && !capabilities.allows(.mtp) && !capabilities.allows(.cacheBlend))
+ #expect(throws: BasaltError.self) {
+ try ModelCapabilities.refuseUnverifiedKVBits(.q4, modelType: "bailing_hybrid", path: "ling3")
+ }
+
+ let profile = ModelProfileRegistry.profile(forModelType: "bailing_hybrid")
+ #expect(profile.name == "bailing_hybrid" && profile.defaultMaxTokens == 16_384 && profile.defaultMinP == nil)
+ #expect(profile.thinkingMarkers.open == [""] && profile.thinkingMarkers.close == [""])
+ #expect(profile.templateContext(for: .modelDefault).isEmpty)
+ #expect(profile.templateContext(for: .disabled)["enable_thinking"] as? Bool == false)
+ #expect(profile.templateContext(for: .effort("high"))["enable_thinking"] as? Bool == true)
+ #expect(profile.templateContext(for: .effort("none"))["enable_thinking"] as? Bool == false)
+
+ let userTurn = [ChatMessageInput(role: .user, text: "hi")]
+ #expect(profile.turns(userTurn, for: .modelDefault).map(\.text) == ["hi"])
+ #expect(profile.turns(userTurn, for: .disabled).first?.text == "detailed thinking off")
+ #expect(profile.turns(userTurn, for: .effort("high")).first?.text == "detailed thinking on")
+ let withSystem = [ChatMessageInput(role: .system, text: "Be brief."), ChatMessageInput(role: .user, text: "hi")]
+ #expect(profile.turns(withSystem, for: .disabled).first?.text == "Be brief.\ndetailed thinking off")
+ let alreadyExplicit = [ChatMessageInput(role: .system, text: "detailed thinking off"), ChatMessageInput(role: .user, text: "hi")]
+ #expect(profile.turns(alreadyExplicit, for: .effort("high")).first?.text == "detailed thinking off")
+
+ let engine = try await TinyModel.engine(.bailingHybrid)
+ let container = try #require(await engine.container)
+ let epoch = await engine.modelEpoch
+ #expect(await engine.cacheIsHybrid(container, epoch: epoch))
+ #expect(await engine.modelHasRecurrentState == true)
+ }
+
+ @Test("Recurrent prompt-cache snapshots replay identically from memory tree and PromptCacheDiskStore")
+ func promptCacheTreeAndDiskRoundTrip() throws {
+ let model = try TinyModel.make(.bailingHybrid)
+ let first = TinyModel.tokens(Conversation.firstTurn)
+ let second = TinyModel.tokens(Conversation.afterToolCall)
+ let boundary = first.count - 1
+ let snapshot = try TinyHybrid.snapshotted(model, first)
+ #expect(snapshot.isHybrid && snapshot.isSnapshot(of: boundary))
+
+ var tree = PromptCacheTree(byteBudget: ByteCount(1 << 30))
+ tree.checkedStore("ns", tokens: Array(first.prefix(boundary)), cache: snapshot)
+ let lease = try tree.required("ns", for: second)
+ let tail = model(TinyHybrid.row(Array(second[boundary...])), cache: lease.cache.layers)
+ eval(tail)
+ _ = consume lease
+ let expected = model(TinyHybrid.row(second), cache: try model.newCache(parameters: nil))[0..., boundary..., 0...]
+ #expect(allClose(tail, expected, rtol: 1e-4, atol: 1e-4).item(Bool.self))
+
+ let directory = DiskFixture.directory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let prefix = Array(first.prefix(boundary))
+ let memoryLease = try tree.required("ns", for: first)
+ var writer = DiskFixture.store(directory)
+ #expect(writer.store(fingerprint: "fp", model: "tiny", namespace: "ns", tokens: prefix, cache: memoryLease.cache) != nil)
+ var reader = DiskFixture.store(directory)
+ let layout = try model.newCache(parameters: nil).map(PromptCacheDiskStore.layoutName)
+ let found = reader.longestPrefix(fingerprint: "fp", namespace: "ns", of: prefix, longerThan: 0, maxBytes: ByteCount(1 << 26))?.entry
+ let entry = try #require(found)
+ let loaded = try reader.load(entry, layout: layout)
+ #expect(loaded.isSnapshot(of: prefix.count))
+ let fromDisk = DiskFixture.nextLogits(model, first[boundary], loaded)
+ let fromMemory = DiskFixture.nextLogits(model, first[boundary], memoryLease.cache)
+ #expect(DiskFixture.identical(fromDisk, fromMemory))
+ _ = consume memoryLease
+ }
+
+ static func makePackedTinyModel() throws -> BailingHybridModel {
+ let source = try #require(try TinyModel.make(.bailingHybrid) as? BailingHybridModel)
+ quantize(model: source, groupSize: 32, bits: 4, mode: .affine) { path, module in
+ guard !path.contains("_conv1d"), !path.contains("mlp.gate") else { return false }
+ return module is Linear || module is Embedding || module is SwitchLinear
+ }
+ eval(source)
+ return source
+ }
+
+ static func unmergeIntoHFCheckpoint(_ raw: [String: MLXArray]) throws -> [String: MLXArray] {
+ var out = raw
+ for key in Array(out.keys) where key.hasSuffix("_conv1d.conv.weight") {
+ let removed = out.removeValue(forKey: key)
+ let weight = try #require(removed)
+ let hfKey = key.replacingOccurrences(of: "_conv1d.conv.weight", with: "_conv1d.weight")
+ out[hfKey] = weight.swappedAxes(1, 2)
+ }
+ for proj in ["gate_proj", "up_proj", "down_proj"] {
+ for part in ["weight", "scales", "biases"] {
+ let removed = out.removeValue(forKey: "model.layers.1.mlp.experts.\(proj).\(part)")
+ let stacked = try #require(removed)
+ for expert in 0 ..< 8 {
+ out["model.layers.1.mlp.experts.\(expert).\(proj).\(part)"] = stacked[expert]
+ }
+ }
+ }
+ out["model.layers.6.attention.dense.weight"] = MLXArray.zeros([64, 64])
+ out["mtp.head.weight"] = MLXArray.zeros([16, 16])
+ return out
+ }
+}
diff --git a/Tests/BasaltTests/BailingHybridTests.swift b/Tests/BasaltTests/BailingHybridTests.swift
new file mode 100644
index 000000000..f60782531
--- /dev/null
+++ b/Tests/BasaltTests/BailingHybridTests.swift
@@ -0,0 +1,284 @@
+import Foundation
+import MLX
+import MLXLMCommon
+import Testing
+@testable import BasaltCore
+@testable import BasaltInference
+
+@Suite("BailingHybrid (Ling-3.0) P0: config, KDA math and noaux_tc router (#672)", .serialized)
+struct BailingHybridTests {
+ static let ling3TinyConfigJSON = """
+ {"model_type": "bailing_hybrid", "hidden_size": 1536, "num_hidden_layers": 24,
+ "intermediate_size": 4608, "num_attention_heads": 16, "num_key_value_heads": 16,
+ "head_dim": 128, "rms_norm_eps": 1e-6, "vocab_size": 157184, "max_position_embeddings": 131072,
+ "tie_word_embeddings": false, "layer_group_size": 4, "first_k_dense_replace": 1,
+ "short_conv_kernel_size": 4, "no_kda_lora": true, "kda_safe_gate": true, "kda_lower_bound": -5,
+ "q_lora_rank": 256, "kv_lora_rank": 512, "qk_nope_head_dim": 128, "qk_rope_head_dim": 64,
+ "v_head_dim": 128, "rope_theta": 6000000, "rope_interleave": true,
+ "gated_attention_proj_granularity_type": "head_wise", "num_experts": 128,
+ "num_experts_per_tok": 8, "num_shared_experts": 1, "moe_intermediate_size": 512,
+ "moe_shared_expert_intermediate_size": 512, "n_group": 8, "topk_group": 4,
+ "norm_topk_prob": true, "routed_scaling_factor": 2.5, "moe_router_enable_expert_bias": true,
+ "use_qk_norm": true}
+ """
+
+ @Test("Ling-3.0-tiny config decodes, computes MLA layer schedule with trailing remainders, validates, and reports exact KV geometry")
+ func configurationAndGeometry() throws {
+ let config = try JSONDecoder.json5().decode(BailingHybridConfiguration.self, from: Data(Self.ling3TinyConfigJSON.utf8)).validated()
+ #expect(config.modelType == "bailing_hybrid")
+ #expect(config.qkHeadDim == 192)
+ #expect(config.convKernelSize == 4)
+ #expect(config.noKDALoRA)
+ #expect((0 ..< config.numHiddenLayers).filter { config.isMLALayer($0) } == [3, 7, 11, 15, 19, 23])
+ #expect(!config.isMoELayer(0) && config.isMoELayer(1) && config.isMoELayer(23))
+
+ var remainder = config
+ remainder.numHiddenLayers = 7
+ remainder.layerGroupSize = 3
+ #expect((0 ..< 7).filter { remainder.isMLALayer($0) } == [2, 5, 6])
+
+ let json = try #require(try JSONSerialization.jsonObject(with: Data(Self.ling3TinyConfigJSON.utf8)) as? [String: Any])
+ let geometry = try #require(KVCacheGeometry(config: json))
+ #expect(geometry.bytesPerToken(nil) == 61_440)
+ #expect(geometry.fixedStateBytes == 19_537_920)
+ }
+
+ @Test("Configuration aliases decode conv_kernel_size, use_kda_lora and null granularity, and validation rejects invalid shapes")
+ func configurationAliasesAndValidation() throws {
+ let aliasJSON = """
+ {"hidden_size": 64, "num_hidden_layers": 3, "intermediate_size": 128,
+ "num_attention_heads": 4, "vocab_size": 256, "conv_kernel_size": 3,
+ "use_kda_lora": true, "gated_attention_proj_granularity_type": null,
+ "kv_lora_rank": 32, "qk_nope_head_dim": 16, "qk_rope_head_dim": 16, "v_head_dim": 16}
+ """
+ let alias = try JSONDecoder.json5().decode(BailingHybridConfiguration.self, from: Data(aliasJSON.utf8)).validated()
+ #expect(alias.convKernelSize == 3 && !alias.noKDALoRA && alias.gatedAttentionGranularity == nil && alias.qLoraRank == nil)
+
+ let mutations: [(inout BailingHybridConfiguration) -> Void] = [
+ { $0.vocabSize = 0 },
+ { $0.layerGroupSize = 0 },
+ { $0.firstKDenseReplace = -1 },
+ { $0.qLoraRank = 0 },
+ { $0.qkRopeHeadDim = 15 },
+ { $0.gatedAttentionGranularity = "unknown" },
+ { $0.numExperts = -1 },
+ { $0.numExperts = 8; $0.nGroup = 3; $0.topkGroup = 2; $0.numExpertsPerTok = 2 },
+ { $0.numExperts = 8; $0.nGroup = 4; $0.topkGroup = 1; $0.numExpertsPerTok = 3 },
+ { $0.numExperts = 8; $0.numExpertsPerTok = 0 },
+ ]
+ for mutate in mutations {
+ var bad = alias
+ mutate(&bad)
+ #expect(throws: BasaltError.self) { _ = try bad.validated() }
+ }
+ }
+
+ @Test("KDA per-channel safe gate, softplus fallback, and L2 norm match an explicit CPU Swift reference within 1e-5")
+ func kdaSafeGateMatchesCPUReference() throws {
+ let (batch, steps, heads, headDim) = (2, 3, 4, 8)
+ let fValues: [Float] = (0 ..< batch * steps * heads * headDim).map { Float(($0 * 17) % 41 - 20) * 0.15 }
+ let aLogValues: [Float] = [-0.8, 0.2, 1.1, -1.5]
+ let dtBiasValues: [Float] = (0 ..< heads * headDim).map { Float(($0 * 7) % 19 - 9) * 0.2 }
+ let lowerBound: Float = -5.0
+
+ let fArr = MLXArray(fValues, [batch, steps, heads, headDim])
+ let aLogArr = MLXArray(aLogValues, [heads])
+ let dtBiasArr = MLXArray(dtBiasValues, [heads, headDim])
+
+ let safeGot = BailingHybridKDAOps.decayLogGate(
+ f: fArr, aLog: aLogArr, dtBias: dtBiasArr, safeGate: true, lowerBound: lowerBound
+ ).asArray(Float.self)
+ let softplusGot = BailingHybridKDAOps.decayLogGate(
+ f: fArr, aLog: aLogArr, dtBias: dtBiasArr, safeGate: false, lowerBound: lowerBound
+ ).asArray(Float.self)
+
+ var (maxSafeErr, maxSoftplusErr): (Float, Float) = (0, 0)
+ for idx in 0 ..< fValues.count {
+ let h = (idx / headDim) % heads
+ let d = idx % headDim
+ let alpha = exp(Double(aLogValues[h]))
+ let pre = Double(fValues[idx]) + Double(dtBiasValues[h * headDim + d])
+ let expectedSafe = Float(Double(lowerBound) / (1.0 + exp(-(alpha * pre))))
+ let expectedSoft = Float(-alpha * (pre > 20 ? pre : log(1.0 + exp(pre))))
+ #expect(safeGot[idx] > lowerBound && safeGot[idx] < 0)
+ maxSafeErr = max(maxSafeErr, abs(safeGot[idx] - expectedSafe))
+ maxSoftplusErr = max(maxSoftplusErr, abs(softplusGot[idx] - expectedSoft))
+ }
+ #expect(maxSafeErr < 1e-5 && maxSoftplusErr < 1e-5)
+
+ let normGot = BailingHybridKDAOps.l2Normalize(fArr).asArray(Float.self)
+ var maxNormErr: Float = 0
+ for row in 0 ..< (batch * steps * heads) {
+ let base = row * headDim
+ let sq = (0 ..< headDim).reduce(0.0) { $0 + Double(fValues[base + $1]) * Double(fValues[base + $1]) }
+ let denom = sq.squareRoot() + 1e-6
+ for d in 0 ..< headDim {
+ maxNormErr = max(maxNormErr, abs(normGot[base + d] - Float(Double(fValues[base + d]) / denom)))
+ }
+ }
+ #expect(maxNormErr < 1e-5)
+ }
+
+ @Test("KDA per-channel recurrent update and short conv match CPU reference, zero masked outputs, and handle empty slices")
+ func kdaRecurrenceMatchesCPUReference() throws {
+ let (batch, steps, heads, dim) = (1, 4, 2, 4)
+ let sample = CPURecurrenceCase(
+ steps: steps,
+ heads: heads,
+ dim: dim,
+ q: (0 ..< batch * steps * heads * dim).map { Float(($0 * 13) % 23 - 11) * 0.1 },
+ k: (0 ..< batch * steps * heads * dim).map { Float(($0 * 11) % 19 - 9) * 0.1 },
+ v: (0 ..< batch * steps * heads * dim).map { Float(($0 * 7) % 17 - 8) * 0.15 },
+ decay: (0 ..< batch * steps * heads * dim).map { exp(Float(-0.2 - Double($0 % 7) * 0.3)) },
+ beta: (0 ..< batch * steps * heads).map { Float(0.2 + Double($0 % 5) * 0.15) },
+ mask: [true, false, true, true]
+ )
+ let inputs = BailingHybridKDAInputs(
+ q: MLXArray(sample.q, [batch, steps, heads, dim]),
+ k: MLXArray(sample.k, [batch, steps, heads, dim]),
+ v: MLXArray(sample.v, [batch, steps, heads, dim]),
+ decay: MLXArray(sample.decay, [batch, steps, heads, dim]),
+ beta: MLXArray(sample.beta, [batch, steps, heads])
+ )
+ let (outArr, stateArr) = BailingHybridKDAOps.recurrentUpdate(
+ inputs, state: nil, mask: MLXArray(sample.mask, [batch, steps])
+ )
+ let (cpuOut, cpuState) = Self.cpuKDARecurrence(sample)
+ let maxOutErr = zip(outArr.asArray(Float.self), cpuOut).map { abs($0 - Float($1)) }.max() ?? 0
+ let maxStateErr = zip(stateArr.asArray(Float.self), cpuState).map { abs($0 - Float($1)) }.max() ?? 0
+ #expect(maxOutErr < 1e-5 && maxStateErr < 1e-5)
+
+ let emptyInputs = BailingHybridKDAInputs(
+ q: MLXArray.zeros([1, 0, heads, dim]), k: MLXArray.zeros([1, 0, heads, dim]),
+ v: MLXArray.zeros([1, 0, heads, dim]), decay: MLXArray.zeros([1, 0, heads, dim]),
+ beta: MLXArray.zeros([1, 0, heads])
+ )
+ let (emptyOut, emptyState) = BailingHybridKDAOps.recurrentUpdate(emptyInputs, state: stateArr)
+ #expect(emptyOut.shape == [1, 0, heads, dim])
+ #expect(allClose(emptyState, stateArr).item(Bool.self))
+
+ let shortConv = BailingHybridShortConv1d(channels: 8, kernelSize: 4)
+ let (convEmpty, convState) = shortConv(MLXArray.zeros([1, 0, 8]), state: nil)
+ #expect(convEmpty.shape == [1, 0, 8] && convState.shape == [1, 3, 8])
+ }
+
+ @Test("noaux_tc group router matches CPU reference for exact indices, unbiased weights, and expertMask under positive bias")
+ func groupRouterMatchesCPUReference() throws {
+ let logitsRows: [[Float]] = [
+ [2.0, 1.5, -0.4, 0.2, 1.1, 0.9, -1.2, 0.5],
+ [-3.0, -2.5, 4.0, 3.5, -0.5, -0.2, -0.1, -0.3],
+ [0.4, -0.8, 1.2, 0.3, -1.5, 2.1, 0.7, -0.6],
+ ]
+ let bias: [Float] = [-2.0, -2.0, -5.0, -5.0, 0.1, 0.3, 0.2, 0.4]
+ let config = BailingHybridRouter.Config(
+ topK: 2, nGroup: 4, topkGroup: 2, normTopkProb: true, routedScalingFactor: 2.5, enableExpertBias: true
+ )
+ let (idxArr, weightArr) = BailingHybridRouter.route(
+ logits: MLXArray(logitsRows.flatMap { $0 }, [1, logitsRows.count, 8]),
+ expertBias: MLXArray(bias, [8]),
+ config: config
+ )
+ let gotIdx = idxArr.asArray(Int32.self).map(Int.init)
+ let gotWeights = weightArr.asArray(Float.self)
+ for (token, row) in logitsRows.enumerated() {
+ let (expectedIdx, expectedWeights) = Self.cpuNoauxTC(logits: row, bias: bias, config: config)
+ let tokenIdx = Array(gotIdx[(token * 2) ..< ((token + 1) * 2)])
+ let tokenWeights = Array(gotWeights[(token * 2) ..< ((token + 1) * 2)])
+ #expect(tokenIdx == expectedIdx)
+ #expect((zip(tokenWeights, expectedWeights).map { abs($0 - $1) }.max() ?? 0) < 1e-5)
+ #expect(abs(tokenWeights.reduce(0, +) - 2.5) < 1e-5)
+ }
+
+ let noDropConfig = BailingHybridRouter.Config(
+ topK: 2, nGroup: 4, topkGroup: 4, normTopkProb: true, routedScalingFactor: 2.5, enableExpertBias: false
+ )
+ let (noDropIdx, noDropW) = BailingHybridRouter.route(
+ logits: MLXArray(logitsRows[0], [1, 1, 8]), expertBias: nil, config: noDropConfig
+ )
+ let (expIdx, expW) = Self.cpuNoauxTC(logits: logitsRows[0], bias: nil, config: noDropConfig)
+ #expect(noDropIdx.asArray(Int32.self).map(Int.init) == expIdx)
+ #expect((zip(noDropW.asArray(Float.self), expW).map { abs($0 - $1) }.max() ?? 0) < 1e-5)
+
+ let hugeBias: [Float] = [50.0, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
+ let mask = MLXArray([Float](arrayLiteral: 0, 0, 1, 1, 1, 1, 1, 1), [8])
+ let (maskedIdx, _) = BailingHybridRouter.route(
+ logits: MLXArray(logitsRows[0], [1, 1, 8]),
+ expertBias: MLXArray(hugeBias, [8]),
+ config: config,
+ expertMask: mask
+ )
+ let chosen = maskedIdx.asArray(Int32.self).map(Int.init)
+ #expect(!chosen.contains(0) && !chosen.contains(1))
+ }
+}
+
+extension BailingHybridTests {
+ struct CPURecurrenceCase {
+ let steps: Int
+ let heads: Int
+ let dim: Int
+ let q: [Float]
+ let k: [Float]
+ let v: [Float]
+ let decay: [Float]
+ let beta: [Float]
+ let mask: [Bool]
+ }
+
+ static func cpuKDARecurrence(_ sample: CPURecurrenceCase) -> ([Double], [Double]) {
+ let (steps, heads, dim) = (sample.steps, sample.heads, sample.dim)
+ var state = Array(repeating: 0.0, count: heads * dim * dim)
+ var out = Array(repeating: 0.0, count: steps * heads * dim)
+ for t in 0 ..< steps where sample.mask[t] {
+ for h in 0 ..< heads {
+ let stateSlice = (h * dim * dim) ..< ((h + 1) * dim * dim)
+ var updated = Array(state[stateSlice])
+ for dv in 0 ..< dim {
+ var kvMem = 0.0
+ for dk in 0 ..< dim {
+ let idx = (t * heads + h) * dim + dk
+ updated[dv * dim + dk] *= Double(sample.decay[idx])
+ kvMem += updated[dv * dim + dk] * Double(sample.k[idx])
+ }
+ let delta = (Double(sample.v[(t * heads + h) * dim + dv]) - kvMem) * Double(sample.beta[t * heads + h])
+ for dk in 0 ..< dim {
+ updated[dv * dim + dk] += Double(sample.k[(t * heads + h) * dim + dk]) * delta
+ }
+ out[(t * heads + h) * dim + dv] = (0 ..< dim).reduce(0.0) { acc, dk in
+ acc + updated[dv * dim + dk] * Double(sample.q[(t * heads + h) * dim + dk])
+ }
+ }
+ state.replaceSubrange(stateSlice, with: updated)
+ }
+ }
+ return (out, state)
+ }
+
+ static func cpuNoauxTC(
+ logits: [Float],
+ bias: [Float]?,
+ config: BailingHybridRouter.Config
+ ) -> ([Int], [Float]) {
+ let rawScores = logits.map { Float(1.0 / (1.0 + exp(-Double($0)))) }
+ let biased = (0 ..< logits.count).map { idx in
+ config.enableExpertBias ? rawScores[idx] + (bias?[idx] ?? 0) : rawScores[idx]
+ }
+ let perGroup = logits.count / config.nGroup
+ let groupScores = (0 ..< config.nGroup).map { group -> (Int, Float) in
+ let slice = Array(biased[(group * perGroup) ..< ((group + 1) * perGroup)]).sorted(by: >)
+ return (group, slice.prefix(min(2, perGroup)).reduce(0, +))
+ }
+ let keptGroups = Set(groupScores.sorted { $0.1 > $1.1 }.prefix(config.topkGroup).map(\.0))
+ let candidates = (0 ..< logits.count).map { idx -> (Int, Float) in
+ (idx, keptGroups.contains(idx / perGroup) ? biased[idx] : -Float.infinity)
+ }
+ let chosen = candidates.sorted { $0.1 > $1.1 }.prefix(config.topK).map(\.0)
+ var weights = chosen.map { rawScores[$0] }
+ if config.topK > 1, config.normTopkProb {
+ let sum = weights.reduce(0, +) + 1e-20
+ weights = weights.map { $0 / sum }
+ }
+ weights = weights.map { $0 * config.routedScalingFactor }
+ return (chosen, weights)
+ }
+}
diff --git a/Tests/BasaltTests/BatchedDecodingIsolationTests.swift b/Tests/BasaltTests/BatchedDecodingIsolationTests.swift
index 45cd1d7d5..43c91b291 100644
--- a/Tests/BasaltTests/BatchedDecodingIsolationTests.swift
+++ b/Tests/BasaltTests/BatchedDecodingIsolationTests.swift
@@ -221,7 +221,7 @@ struct BatchRotatingKVCacheTests {
struct BatchedDecoderTests {
@Test("Four prompts of different lengths decoded together match their solo greedy decode for 32 steps, on plain attention, recurrent hybrids and sliding-window models",
- .timeLimit(.minutes(10)), arguments: [TinyModel.Family.qwen3Small, .qwen35, .nemotronH, .lfm2, .gemma4, .gemma4Moe])
+ .timeLimit(.minutes(10)), arguments: [TinyModel.Family.qwen3Small, .qwen35, .nemotronH, .lfm2, .gemma4, .gemma4Moe, .bailingHybrid])
func fourRowsMatchSolo(family: TinyModel.Family) async throws {
let model = try TinyModel.make(family)
let expected = try BatchFixture.prompts.map { BatchFixture.text(try BatchFixture.soloGreedy(model, $0, steps: 32)) }
@@ -235,7 +235,7 @@ struct BatchedDecoderTests {
}
@Test("A row joining mid-flight and rows retiring on EOS or max tokens leave the other rows' tokens unchanged, on plain attention, recurrent hybrids and sliding-window models",
- .timeLimit(.minutes(10)), arguments: [TinyModel.Family.qwen3Small, .qwen35, .nemotronH, .lfm2, .gemma4, .gemma4Moe])
+ .timeLimit(.minutes(10)), arguments: [TinyModel.Family.qwen3Small, .qwen35, .nemotronH, .lfm2, .gemma4, .gemma4Moe, .bailingHybrid])
func joinAndRetire(family: TinyModel.Family) async throws {
let model = try TinyModel.make(family)
let prompts = BatchFixture.prompts
@@ -330,7 +330,7 @@ struct BatchedRoutingTests {
}
@Test("With 4 batch slots and 4 concurrent generations, streaming or not, each request gets its solo output and telemetry, on plain attention and on recurrent hybrids",
- .timeLimit(.minutes(10)), arguments: [TinyModel.Family.qwen3Small, .qwen35, .nemotronH, .lfm2])
+ .timeLimit(.minutes(10)), arguments: [TinyModel.Family.qwen3Small, .qwen35, .nemotronH, .lfm2, .bailingHybrid])
func orchestratorBatchesFourRequests(family: TinyModel.Family) async throws {
let expected = try await Self.solo(4, family: family)
let engine = await BatchFixture.engine(try TinyModel.make(family), id: "tiny-\(family)", batchSlots: 4)
diff --git a/Tests/BasaltTests/FeatureMatrixTests.swift b/Tests/BasaltTests/FeatureMatrixTests.swift
index 3855481f9..8957618f4 100644
--- a/Tests/BasaltTests/FeatureMatrixTests.swift
+++ b/Tests/BasaltTests/FeatureMatrixTests.swift
@@ -12,7 +12,7 @@ struct FeatureMatrixTests {
func applies(to family: TinyModel.Family) -> Bool {
switch self {
- case .lookup: ![.qwen35Moe, .qwen3Next, .lfm2Moe, .sigmoidMoe].contains(family)
+ case .lookup: ![.qwen35Moe, .qwen3Next, .lfm2Moe, .sigmoidMoe, .bailingHybrid].contains(family)
case .mtp: [.qwen35, .prism].contains(family)
case .cacheBlend: [.qwen3, .qwen3HeadDim32].contains(family)
case .kvZones, .headSplit, .headSplitZoned: [.qwen3HeadDim32, .qwen3Next].contains(family)
diff --git a/Tests/BasaltTests/Fixtures/TinyModels.swift b/Tests/BasaltTests/Fixtures/TinyModels.swift
index 3b287a003..938e342ba 100644
--- a/Tests/BasaltTests/Fixtures/TinyModels.swift
+++ b/Tests/BasaltTests/Fixtures/TinyModels.swift
@@ -8,7 +8,7 @@ import MLXVLM
enum TinyModel {
enum Family: String, CaseIterable, Sendable {
- case qwen3Small, qwen3, qwen3HeadDim32, qwen35, qwen35Moe, qwen3Next, gemma3, gemma4, gemma4Moe, gemma4KEqV, gemma4Unified, inkling2Loop, qwen3Moe, sigmoidMoe, nemotronH, lfm2, lfm2Moe, prism, paddleOCR, deepSeekOCR, deepSeekOCR2, flint, ricursive, museGlimmer, museGlimmerText, ltxVideo, kandinskyCrossDiT, moeVideoDiT
+ case qwen3Small, qwen3, qwen3HeadDim32, qwen35, qwen35Moe, qwen3Next, gemma3, gemma4, gemma4Moe, gemma4KEqV, gemma4Unified, inkling2Loop, qwen3Moe, sigmoidMoe, nemotronH, lfm2, lfm2Moe, prism, paddleOCR, deepSeekOCR, deepSeekOCR2, flint, ricursive, museGlimmer, museGlimmerText, ltxVideo, kandinskyCrossDiT, moeVideoDiT, bailingHybrid
func model(_ config: Data) throws -> any LanguageModel {
let decoder = JSONDecoder.json5()
@@ -26,7 +26,7 @@ enum TinyModel {
case .ricursive: RicursiveModel(try decoder.decode(RicursiveConfiguration.self, from: config).validated())
case .museGlimmerText: MuseGlimmerTextModel(try MuseGlimmerTextConfiguration.decodeFlexible(from: config))
case .ltxVideo, .kandinskyCrossDiT, .moeVideoDiT: try videoModel(config, decoder: decoder)
- case .gemma4Unified, .paddleOCR, .deepSeekOCR, .deepSeekOCR2, .museGlimmer, .inkling2Loop, .qwen3Next: try multimodalModel(config, decoder: decoder)
+ case .gemma4Unified, .paddleOCR, .deepSeekOCR, .deepSeekOCR2, .museGlimmer, .inkling2Loop, .qwen3Next, .bailingHybrid: try multimodalModel(config, decoder: decoder)
}
}
@@ -41,6 +41,7 @@ enum TinyModel {
if self == .gemma4Unified { return try TinyGemma4Unified.model(config) }
if self == .inkling2Loop { return try Inkling2Model(configurationData: config) }
if self == .qwen3Next { return Qwen3NextModel(try decoder.decode(Qwen3NextConfiguration.self, from: config)) }
+ if self == .bailingHybrid { return try BailingHybridModel(configurationData: config) }
if self == .paddleOCR { return PaddleOCRVL(try decoder.decode(PaddleOCRVLConfiguration.self, from: config)) }
if self == .deepSeekOCR { return DeepSeekOCR(try decoder.decode(DeepSeekOCRConfiguration.self, from: config).validated()) }
if self == .museGlimmer { return MuseGlimmerVLM(try decoder.decode(MuseGlimmerConfiguration.self, from: config)) }
@@ -71,13 +72,14 @@ enum TinyModel {
case .ltxVideo: 584
case .kandinskyCrossDiT: 585
case .moeVideoDiT: 586
+ case .bailingHybrid: 672
}
}
var weightScale: Float {
switch self {
case .qwen3Small, .gemma3: 4
- case .qwen3, .qwen3HeadDim32, .gemma4, .gemma4Moe, .gemma4KEqV, .gemma4Unified, .inkling2Loop, .qwen35, .qwen35Moe, .qwen3Next, .qwen3Moe, .sigmoidMoe, .nemotronH, .lfm2, .lfm2Moe, .prism, .paddleOCR, .deepSeekOCR, .deepSeekOCR2, .flint, .ricursive, .museGlimmer, .museGlimmerText, .ltxVideo, .kandinskyCrossDiT, .moeVideoDiT: 1
+ case .qwen3, .qwen3HeadDim32, .gemma4, .gemma4Moe, .gemma4KEqV, .gemma4Unified, .inkling2Loop, .qwen35, .qwen35Moe, .qwen3Next, .qwen3Moe, .sigmoidMoe, .nemotronH, .lfm2, .lfm2Moe, .prism, .paddleOCR, .deepSeekOCR, .deepSeekOCR2, .flint, .ricursive, .museGlimmer, .museGlimmerText, .ltxVideo, .kandinskyCrossDiT, .moeVideoDiT, .bailingHybrid: 1
}
}
@@ -219,56 +221,8 @@ enum TinyModel {
"qwen2-0-5b": {"dim": 64, "layers": 2, "heads": 4, "kv_heads": 2, "intermediate_size": 128}}},
"projector_config": {"input_dim": 64, "n_embed": 64, "projector_type": "linear"}}
"""
- case .flint: """
- {"model_type": "flint", "hidden_size": 64, "num_hidden_layers": 4, "intermediate_size": 128,
- "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, "vocab_size": 256,
- "sliding_window": \(slidingWindow), "use_sliding_window": true,
- "layer_types": ["full_attention", "sliding_attention", "sliding_attention", "full_attention"],
- "no_rope_layer_indices": [0, 3], "mlp_only_layers": [0, 1],
- "num_experts": 8, "num_experts_per_tok": 2, "moe_intermediate_size": 32,
- "shared_expert_intermediate_size": 32, "router_score_function": "sigmoid",
- "norm_topk_prob": true, "router_expert_bias": true, "softmax_type": "learnable",
- "rms_norm_eps": 1e-6, "rope_theta": 10000.0, "tie_word_embeddings": false}
- """
- case .ricursive: """
- {"model_type": "ricursive", "hidden_size": 64, "num_hidden_layers": 5, "intermediate_size": 128,
- "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, "vocab_size": 256,
- "sliding_window": \(slidingWindow),
- "layer_types": ["sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention"],
- "use_gated_attention": true, "gate_full_precision": true, "use_valres": true,
- "ffn_clamp_threshold": 20.0, "embed_scale": 8.0, "rms_norm_eps": 1e-6, "rope_theta": 10000.0,
- "tie_word_embeddings": false}
- """
- case .museGlimmerText: """
- {"model_type": "muse_glimmer_text", "hidden_size": 64, "num_hidden_layers": 4, "intermediate_size": 128,
- "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, "vocab_size": 256,
- "sliding_window": \(slidingWindow), "qk_scale_factor": 3.87, "output_multiplier": 0.19611613,
- "final_logit_softcapping": 20.0, "rms_norm_eps": 1e-5, "post_norm_eps": 1e-8,
- "layer_types": ["sliding_attention", "sliding_attention", "sliding_attention", "full_attention"],
- "layer_rope_theta": [500000.0, 500000.0, 500000.0, 0.0], "tie_word_embeddings": false}
- """
- case .museGlimmer: """
- {"model_type": "muse_glimmer", "image_token_id": 254, "video_token_id": 253,
- "out_hidden_size": 64, "projector_hidden_size": 64,
- "text_config": \(Self.museGlimmerText.config),
- "vision_config": {"model_type": "muse_glimmer_vision", "hidden_size": 16, "intermediate_size": 32,
- "num_hidden_layers": 2, "num_attention_heads": 2, "patch_size": 14, "patch_temporal": 2, "merge_size": 2,
- "max_position_embeddings": 16, "pos_emb_height": 4, "pos_emb_width": 4, "layer_norm_eps": 1e-5,
- "layer_types": ["window_attention", "full_attention"]}}
- """
- case .ltxVideo: """
- {"model_type": "ltx_video", "vocab_size": 256, "hidden_size": 64, "num_hidden_layers": 2,
- "num_attention_heads": 4, "intermediate_size": 128, "video_channels": 16, "audio_channels": 8}
- """
- case .kandinskyCrossDiT: """
- {"model_type": "kandinsky_cross_dit", "vocab_size": 256, "hidden_size": 64, "num_hidden_layers": 2,
- "num_attention_heads": 4, "intermediate_size": 128, "video_channels": 16, "audio_channels": 8}
- """
- case .moeVideoDiT: """
- {"model_type": "moe_video_dit", "vocab_size": 256, "hidden_size": 64, "num_hidden_layers": 2,
- "num_attention_heads": 4, "intermediate_size": 64, "video_channels": 16, "audio_channels": 8,
- "num_experts": 4, "num_experts_per_tok": 2}
- """
+ case .flint, .ricursive, .museGlimmerText, .museGlimmer, .ltxVideo, .kandinskyCrossDiT, .moeVideoDiT, .bailingHybrid:
+ extendedConfig
}
}
}
@@ -281,28 +235,7 @@ enum TinyModel {
let config = "{" + extra + family.config.dropFirst()
let model = try withRandomState(MLXRandom.RandomState(seed: family.seed)) {
let model = try family.model(Data(config.utf8))
- if family == .sigmoidMoe {
- let router = model.parameters().flattened().filter { $0.0.hasSuffix(".gate.weight") || $0.0.hasSuffix(".e_score_correction_bias") }
- model.update(parameters: ModuleParameters.unflattened(router.map { ($0.0, MLXRandom.normal($0.1.shape)) }))
- } else if family == .flint {
- let specialized = model.parameters().flattened().filter {
- $0.0.hasSuffix(".gate.weight") || $0.0.hasSuffix(".expert_bias") || $0.0.hasSuffix(".softmax_offset")
- }
- model.update(parameters: ModuleParameters.unflattened(specialized.map { ($0.0, MLXRandom.normal($0.1.shape) * 0.25) }))
- } else if family == .inkling2Loop {
- let zeroed = model.parameters().flattened().filter { key, _ in
- [".query", ".proj", ".static_weight", "conv1d.weight", ".gate.weight", ".e_score_correction_bias"].contains { key.hasSuffix($0) }
- }
- model.update(parameters: ModuleParameters.unflattened(zeroed.map { ($0.0, MLXRandom.normal($0.1.shape) * 0.25) }))
- } else if family == .ricursive {
- let lambdas = model.parameters().flattened().filter { $0.0.hasSuffix(".value_res_lambda") }
- model.update(parameters: ModuleParameters.unflattened(lambdas.map { ($0.0, MLXRandom.normal($0.1.shape) * 0.5) }))
- } else if family == .museGlimmer || family == .museGlimmerText {
- let centered = model.parameters().flattened().filter {
- $0.0.hasSuffix("_layernorm.weight")
- }
- model.update(parameters: ModuleParameters.unflattened(centered.map { ($0.0, MLXRandom.normal($0.1.shape) * 0.2) }))
- }
+ seedSpecialParameters(model, family: family)
return model
}
if family.weightScale != 1 {
@@ -336,3 +269,100 @@ enum TinyModel {
ByteTokenizer().encode(text: prompt, addSpecialTokens: false) + [ByteTokenizer.endOfUserTurn]
}
}
+
+extension TinyModel.Family {
+ var extendedConfig: String {
+ switch self {
+ case .flint: """
+ {"model_type": "flint", "hidden_size": 64, "num_hidden_layers": 4, "intermediate_size": 128,
+ "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, "vocab_size": 256,
+ "sliding_window": \(TinyModel.slidingWindow), "use_sliding_window": true,
+ "layer_types": ["full_attention", "sliding_attention", "sliding_attention", "full_attention"],
+ "no_rope_layer_indices": [0, 3], "mlp_only_layers": [0, 1],
+ "num_experts": 8, "num_experts_per_tok": 2, "moe_intermediate_size": 32,
+ "shared_expert_intermediate_size": 32, "router_score_function": "sigmoid",
+ "norm_topk_prob": true, "router_expert_bias": true, "softmax_type": "learnable",
+ "rms_norm_eps": 1e-6, "rope_theta": 10000.0, "tie_word_embeddings": false}
+ """
+ case .ricursive: """
+ {"model_type": "ricursive", "hidden_size": 64, "num_hidden_layers": 5, "intermediate_size": 128,
+ "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, "vocab_size": 256,
+ "sliding_window": \(TinyModel.slidingWindow),
+ "layer_types": ["sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention"],
+ "use_gated_attention": true, "gate_full_precision": true, "use_valres": true,
+ "ffn_clamp_threshold": 20.0, "embed_scale": 8.0, "rms_norm_eps": 1e-6, "rope_theta": 10000.0,
+ "tie_word_embeddings": false}
+ """
+ case .museGlimmerText: """
+ {"model_type": "muse_glimmer_text", "hidden_size": 64, "num_hidden_layers": 4, "intermediate_size": 128,
+ "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 16, "vocab_size": 256,
+ "sliding_window": \(TinyModel.slidingWindow), "qk_scale_factor": 3.87, "output_multiplier": 0.19611613,
+ "final_logit_softcapping": 20.0, "rms_norm_eps": 1e-5, "post_norm_eps": 1e-8,
+ "layer_types": ["sliding_attention", "sliding_attention", "sliding_attention", "full_attention"],
+ "layer_rope_theta": [500000.0, 500000.0, 500000.0, 0.0], "tie_word_embeddings": false}
+ """
+ case .museGlimmer: """
+ {"model_type": "muse_glimmer", "image_token_id": 254, "video_token_id": 253,
+ "out_hidden_size": 64, "projector_hidden_size": 64,
+ "text_config": \(Self.museGlimmerText.config),
+ "vision_config": {"model_type": "muse_glimmer_vision", "hidden_size": 16, "intermediate_size": 32,
+ "num_hidden_layers": 2, "num_attention_heads": 2, "patch_size": 14, "patch_temporal": 2, "merge_size": 2,
+ "max_position_embeddings": 16, "pos_emb_height": 4, "pos_emb_width": 4, "layer_norm_eps": 1e-5,
+ "layer_types": ["window_attention", "full_attention"]}}
+ """
+ case .ltxVideo: """
+ {"model_type": "ltx_video", "vocab_size": 256, "hidden_size": 64, "num_hidden_layers": 2,
+ "num_attention_heads": 4, "intermediate_size": 128, "video_channels": 16, "audio_channels": 8}
+ """
+ case .kandinskyCrossDiT: """
+ {"model_type": "kandinsky_cross_dit", "vocab_size": 256, "hidden_size": 64, "num_hidden_layers": 2,
+ "num_attention_heads": 4, "intermediate_size": 128, "video_channels": 16, "audio_channels": 8}
+ """
+ case .moeVideoDiT: """
+ {"model_type": "moe_video_dit", "vocab_size": 256, "hidden_size": 64, "num_hidden_layers": 2,
+ "num_attention_heads": 4, "intermediate_size": 64, "video_channels": 16, "audio_channels": 8,
+ "num_experts": 4, "num_experts_per_tok": 2}
+ """
+ case .bailingHybrid: """
+ {"model_type": "bailing_hybrid", "vocab_size": 256, "hidden_size": 64, "num_hidden_layers": 6,
+ "layer_group_size": 3, "intermediate_size": 128, "num_attention_heads": 4, "num_key_value_heads": 4,
+ "head_dim": 32, "short_conv_kernel_size": 4, "no_kda_lora": true, "kda_safe_gate": true,
+ "kda_lower_bound": -5.0, "q_lora_rank": 32, "kv_lora_rank": 32, "qk_nope_head_dim": 32,
+ "qk_rope_head_dim": 16, "v_head_dim": 32, "rope_theta": 6000000.0, "rope_interleave": true,
+ "gated_attention_proj_granularity_type": "head_wise", "num_experts": 8, "num_experts_per_tok": 2,
+ "n_group": 4, "topk_group": 2, "num_shared_experts": 1, "moe_intermediate_size": 32,
+ "moe_shared_expert_intermediate_size": 32, "first_k_dense_replace": 1, "routed_scaling_factor": 2.5,
+ "norm_topk_prob": true, "moe_router_enable_expert_bias": true, "rms_norm_eps": 1e-6,
+ "tie_word_embeddings": false}
+ """
+ default:
+ preconditionFailure("Unexpected TinyModel.Family in extendedConfig: \(self)")
+ }
+ }
+}
+
+extension TinyModel {
+ static func seedSpecialParameters(_ model: any LanguageModel, family: Family) {
+ let suffixes: [String]
+ let scale: Float
+ switch family {
+ case .sigmoidMoe:
+ (suffixes, scale) = ([".gate.weight", ".e_score_correction_bias"], 1.0)
+ case .flint:
+ (suffixes, scale) = ([".gate.weight", ".expert_bias", ".softmax_offset"], 0.25)
+ case .inkling2Loop:
+ (suffixes, scale) = ([".query", ".proj", ".static_weight", "conv1d.weight", ".gate.weight", ".e_score_correction_bias"], 0.25)
+ case .ricursive:
+ (suffixes, scale) = ([".value_res_lambda"], 0.5)
+ case .museGlimmer, .museGlimmerText:
+ (suffixes, scale) = (["_layernorm.weight"], 0.2)
+ case .bailingHybrid:
+ (suffixes, scale) = ([".gate.weight", ".gate.expert_bias", ".A_log", ".dt_bias"], 0.25)
+ default:
+ return
+ }
+ let matching = model.parameters().flattened().filter { key, _ in suffixes.contains { key.hasSuffix($0) } }
+ let values = matching.map { ($0.0, scale == 1 ? MLXRandom.normal($0.1.shape) : MLXRandom.normal($0.1.shape) * scale) }
+ model.update(parameters: ModuleParameters.unflattened(values))
+ }
+}
diff --git a/Tests/BasaltTests/GenerationPlanTests.swift b/Tests/BasaltTests/GenerationPlanTests.swift
index 14f4f8f47..013a684f5 100644
--- a/Tests/BasaltTests/GenerationPlanTests.swift
+++ b/Tests/BasaltTests/GenerationPlanTests.swift
@@ -156,29 +156,6 @@ struct GenerationPlanTests {
zoned, GenerationPlan.Settings(kvHeadMask: KVHeadMask(retrieval: [[0, 1]]), questTopK: 16), GenerationPlan.Settings(questTopK: 16),
]
- @Test("Every known family keeps today's plan for the facts its caches produce", arguments: mtp + batch + cache)
- func knownFamiliesKeepTodaysPlan(_ row: Case) {
- for (modelType, capabilities) in ModelCapabilities.families {
- for base in [row.settings] + Self.layouts {
- var (today, facts) = (base, row.facts)
- if !capabilities.allows(.mtp) { facts.hasMTPDrafter = false }
- if !capabilities.allows(.cacheBlend) { facts.modelIsHybrid = true }
- if !capabilities.allows(.quest) { today.questTopK = nil }
- if !capabilities.allows(.kvHeadSplit) { today.kvHeadMask = nil }
- if !capabilities.allows(.kvZones) { today.kvZones = nil }
- var verified = today
- verified.capabilities = capabilities
- var expected = GenerationPlan.make(row.request, today, facts)
- if !capabilities.allows(.batchedDecode) { expected.batchable = false }
- #expect(GenerationPlan.make(row.request, verified, facts) == expected, "\(modelType)")
- #expect(GenerationPlan.plainPrompt(row.request, verified, carriesMoreThanTokens: facts.carriesMoreThanTokens)
- == GenerationPlan.plainPrompt(row.request, today, carriesMoreThanTokens: facts.carriesMoreThanTokens), "\(modelType)")
- #expect(GenerationPlan.cacheNamespace(row.request, verified, cacheEnabled: true, media: .text, sameEpoch: true)
- == GenerationPlan.cacheNamespace(row.request, today, cacheEnabled: true, media: .text, sameEpoch: true), "\(modelType)")
- }
- }
- }
-
@Test("Each feature a known family leaves out is one the runtime already refuses for that family's caches",
arguments: [
(TinyModel.Family.qwen3Small, "qwen3"), (.qwen3, "qwen3"), (.qwen3Moe, "qwen3_moe"), (.qwen35, "qwen3_5"), (.qwen35Moe, "qwen3_5_moe"),
@@ -220,6 +197,33 @@ struct GenerationPlanTests {
}
extension GenerationPlanTests {
+ @Test("Every known family keeps today's plan for the facts its caches produce", arguments: mtp + batch + cache)
+ func knownFamiliesKeepTodaysPlan(_ row: Case) {
+ for (modelType, capabilities) in ModelCapabilities.families {
+ for base in [row.settings] + Self.layouts {
+ var (today, facts, request) = (base, row.facts, row.request)
+ if !capabilities.allows(.mtp) { facts.hasMTPDrafter = false }
+ if !capabilities.allows(.cacheBlend) { facts.modelIsHybrid = true }
+ if !capabilities.allows(.quest) { today.questTopK = nil }
+ if !capabilities.allows(.kvHeadSplit) { today.kvHeadMask = nil }
+ if !capabilities.allows(.kvZones) { today.kvZones = nil }
+ if !capabilities.allows(.speculativeLookup) {
+ today.speculativeLookup = false
+ if request.speculativeLookup == true { request = request.withSpeculativeLookup(false) }
+ }
+ var verified = today
+ verified.capabilities = capabilities
+ var expected = GenerationPlan.make(request, today, facts)
+ if !capabilities.allows(.batchedDecode) { expected.batchable = false }
+ #expect(GenerationPlan.make(row.request, verified, facts) == expected, "\(modelType)")
+ #expect(GenerationPlan.plainPrompt(row.request, verified, carriesMoreThanTokens: facts.carriesMoreThanTokens)
+ == GenerationPlan.plainPrompt(row.request, today, carriesMoreThanTokens: facts.carriesMoreThanTokens), "\(modelType)")
+ #expect(GenerationPlan.cacheNamespace(row.request, verified, cacheEnabled: true, media: .text, sameEpoch: true)
+ == GenerationPlan.cacheNamespace(row.request, today, cacheEnabled: true, media: .text, sameEpoch: true), "\(modelType)")
+ }
+ }
+ }
+
@Test("Head split runs on the full-precision cache or inside zones, never under uniform quantization; Quest steps aside for head split")
func headSplitAndQuest() {
let mask = KVHeadMask(retrieval: [[0, 1]])
diff --git a/Tests/BasaltTests/TokenTraceTests.swift b/Tests/BasaltTests/TokenTraceTests.swift
index e51f483e9..92f3ee1d2 100644
--- a/Tests/BasaltTests/TokenTraceTests.swift
+++ b/Tests/BasaltTests/TokenTraceTests.swift
@@ -58,7 +58,7 @@ struct TraceParity: Sendable {
@Suite("trace_tokens records heads, experts and projections per token with the stock graph's output (#405)", .serialized)
struct TokenTraceParityTests {
static let prompt = "the cat sat on the mat"
- static let families: [TinyModel.Family] = [.qwen3, .qwen3Moe, .qwen35, .qwen35Moe, .gemma4, .gemma4Moe, .lfm2, .lfm2Moe, .nemotronH, .sigmoidMoe]
+ static let families: [TinyModel.Family] = [.qwen3, .qwen3Moe, .qwen35, .qwen35Moe, .gemma4, .gemma4Moe, .lfm2, .lfm2Moe, .nemotronH, .sigmoidMoe, .bailingHybrid]
static let softmaxRouters: Set = [.qwen3Moe, .qwen35Moe, .gemma4Moe]
static func parity(_ family: TinyModel.Family, maxTokens: Int = 8) async throws -> TraceParity {
@@ -108,7 +108,7 @@ struct TokenTraceParityTests {
#expect(result.tokens == ByteTokenizer().encode(text: Self.prompt, addSpecialTokens: true).count + result.traced.count)
#expect(result.headLayers > 0)
#expect(result.headError < 1e-4)
- let moe: Set = [.qwen3Moe, .qwen35Moe, .gemma4Moe, .lfm2Moe, .sigmoidMoe]
+ let moe: Set = [.qwen3Moe, .qwen35Moe, .gemma4Moe, .lfm2Moe, .sigmoidMoe, .bailingHybrid]
#expect((result.expertLayers > 0) == moe.contains(family))
#expect(result.idsMatch)
#expect(result.gateError < 1e-5)
From b2a9b0ef0e7c2571f435bcdbc3c5686cd3bf26d2 Mon Sep 17 00:00:00 2001
From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com>
Date: Tue, 24 Nov 2026 11:21:43 +0100
Subject: [PATCH 2/2] fix(bailing_hybrid): only MambaCache and Bailing's KDA
cache count as recurrent state, so Inkling 2's conv ArraysCache does not turn
on anchor search (#672 review)
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_012cicguZMN3jhNGmf5327oh
---
Sources/BasaltInference/MLXInferenceEngine+PromptCache.swift | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Sources/BasaltInference/MLXInferenceEngine+PromptCache.swift b/Sources/BasaltInference/MLXInferenceEngine+PromptCache.swift
index 0a16ab4d1..6562b7be9 100644
--- a/Sources/BasaltInference/MLXInferenceEngine+PromptCache.swift
+++ b/Sources/BasaltInference/MLXInferenceEngine+PromptCache.swift
@@ -35,7 +35,7 @@ extension MLXInferenceEngine {
if let known = modelIsHybrid { return known }
let kinds = (try? await container.perform { context -> (hybrid: Bool, recurrent: Bool) in
let cache = try context.model.newCache(parameters: nil)
- return (PromptCache(cache).isHybrid, cache.contains { $0 is ArraysCache })
+ return (PromptCache(cache).isHybrid, cache.contains { $0 is MambaCache } || context.model is BailingHybridModel)
}) ?? (hybrid: false, recurrent: false)
record(.learned(epoch) { ($0.isHybrid, $0.hasRecurrentState) = (kinds.hybrid, kinds.recurrent) })
return kinds.hybrid