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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Sources/BasaltCore/Chat/BailingHybridProfile.swift
Original file line number Diff line number Diff line change
@@ -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: ["<think>"], close: ["</think>"])
}

public var defaultMaxTokens: Int { 16_384 }

public var defaultMinP: Float? { nil }
}
15 changes: 11 additions & 4 deletions Sources/BasaltCore/Chat/ModelProfile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
22 changes: 19 additions & 3 deletions Sources/BasaltCore/KVCacheGeometry+Loop.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
Expand Down
2 changes: 1 addition & 1 deletion Sources/BasaltCore/KVCacheGeometry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions Sources/BasaltInference/MLXInferenceEngine+Loading.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 MambaCache } || context.model is BailingHybridModel)
}) ?? (hybrid: false, recurrent: false)
record(.learned(epoch) { ($0.isHybrid, $0.hasRecurrentState) = (kinds.hybrid, kinds.recurrent) })
return kinds.hybrid
Expand Down
10 changes: 7 additions & 3 deletions Sources/BasaltInference/MLXInferenceEngine+Research.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions Sources/BasaltInference/ModelCapabilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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]))),
Expand Down
Loading