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
1 change: 1 addition & 0 deletions Sources/BasaltCLI/ComposeFile+Options.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ extension ComposeFile.Walk {
out.expertCacheGB = number(field["expert_cache_gb"], "\(path).expert_cache_gb")
out.kvHeadSplit = number(field["kv_head_split"], "\(path).kv_head_split")
out.questTopK = integer(field["quest_top_k"], "\(path).quest_top_k")
out.ropeYarn = number(field["rope_yarn"], "\(path).rope_yarn")
spec.experimental = out
}

Expand Down
4 changes: 4 additions & 0 deletions Sources/BasaltCLI/KVCacheOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,13 @@ struct KVCacheOptions: ParsableArguments {
@Option(name: .customLong("moba-top-k"), help: ArgumentHelp("With --attention-backend moba, number of 64-token middle blocks selected per query head alongside sink and recent blocks (1...4096, default 8)"))
var mobaTopK: Int = 8

@Option(name: .customLong("rope-yarn"), help: ArgumentHelp("Extend the context of Qwen 3.5, 3.6 and 3.8 (qwen3_5) with YaRN by this factor (e.g. 2 for about 512K tokens, 4 for about 1M); the model's config is staged with rope_type yarn and original_max_position_embeddings set to its native context. YaRN is static: short prompts pay its small cost too, so use it only for contexts past the native one. Other models, Gemma 4 included, load with their stock RoPE and a warning"))
var ropeYarn: Double?

var zones: KVZones? { KVBitsSetting.zones(zoned, evicting: evict) }

func validateCombination() throws {
if let ropeYarn, !(ropeYarn > 1 && ropeYarn <= 64) { throw ValidationError("--rope-yarn takes a factor in (1, 64]") }
try KVBitsSetting.validate(zones: zoned, bits: bits, evict: evict)
if let headSplit {
guard (0.05 ... 1).contains(headSplit) else { throw ValidationError("--kv-head-split takes a share of heads in 0.05...1") }
Expand Down
1 change: 1 addition & 0 deletions Sources/BasaltCLI/ServeCommand+Compose.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ extension ServeCommand {
if expertStreaming.cacheGB == nil, let cacheGB = exp.expertCacheGB { expertStreaming.cacheGB = cacheGB }
if kvCache.headSplit == nil, let split = exp.kvHeadSplit { kvCache.headSplit = split }
if kvCache.questTopK == nil, let topK = exp.questTopK { kvCache.questTopK = topK }
if kvCache.ropeYarn == nil, let factor = exp.ropeYarn { kvCache.ropeYarn = factor }
}

private mutating func applyComposeMCP(_ specMCP: ComposeSpec.MCP) {
Expand Down
1 change: 1 addition & 0 deletions Sources/BasaltCLI/ServeCommand+Launch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ extension ServeCommand {
speculative.configure(&configuration)
(configuration.kvPrecision, configuration.kvZones) = (kvCache.bits?.fixedPrecision, kvCache.zones)
(configuration.kvHeadSplit, configuration.questTopK) = (kvCache.headSplit, kvCache.questTopK)
configuration.ropeYarn = kvCache.ropeYarn
(configuration.attentionBackend, configuration.mobaTopK) = (kvCache.attentionBackend, kvCache.mobaTopK)
configuration.batchSlots = maxConcurrent >= 2 ? batchSlots : 1
configuration.wiresWorkingSet = wiredLimit
Expand Down
1 change: 1 addition & 0 deletions Sources/BasaltCLI/ServeConfigFile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ extension ServeConfigFile {
"serve.kv.evict": .number("--kv-evict"),
"serve.kv.head_split": .number("--kv-head-split"),
"serve.kv.quest_top_k": .int("--quest-top-k"),
"serve.rope_yarn": .number("--rope-yarn"),
"serve.prompt_cache.mb": .int("--prompt-cache-mb"),
"serve.prompt_cache.disk_mb": .int("--prompt-cache-disk-mb"),
"serve.prompt_cache.disk_days": .int("--prompt-cache-disk-days"),
Expand Down
2 changes: 1 addition & 1 deletion Sources/BasaltCore/ComposeSchema.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public enum ComposeSchema {
Field("telemetry_confidence_every", .integer), Field("adaptive_thinking_budget", .boolean),
Field("samplers", .boolean), Field("mtp_draft_head", .boolean),
Field("expert_streaming", .boolean), Field("expert_cache_gb", .number),
Field("kv_head_split", .number), Field("quest_top_k", .integer),
Field("kv_head_split", .number), Field("quest_top_k", .integer), Field("rope_yarn", .number),
],
"mcp": [
Field("enabled", .boolean), Field("rest", .boolean), Field("research_tools", .boolean),
Expand Down
6 changes: 6 additions & 0 deletions Sources/BasaltCore/ComposeSpec+Options.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ extension ComposeSpec {
public var expertCacheGB: Double?
public var kvHeadSplit: Double?
public var questTopK: Int?
public var ropeYarn: Double?

public init() {}
}
Expand Down Expand Up @@ -55,6 +56,9 @@ extension ComposeSpec {
issues.append(Issue("experimental.expert_cache_gb", "must be positive"))
}
}
if let factor = experimental.ropeYarn, !(factor > 1 && factor <= 64) {
issues.append(Issue("experimental.rope_yarn", "must lie in (1, 64]"))
}
if let split = experimental.kvHeadSplit, !(0.05 ... 1).contains(split) {
issues.append(Issue("experimental.kv_head_split", "must lie between 0.05 and 1"))
}
Expand Down Expand Up @@ -115,6 +119,7 @@ extension ComposeSpec {
if let cacheGB = experimental.expertCacheGB { arguments += ["--expert-cache-gb", String(cacheGB)] }
if let split = experimental.kvHeadSplit { arguments += ["--kv-head-split", String(split)] }
if let topK = experimental.questTopK { arguments += ["--quest-top-k", String(topK)] }
if let factor = experimental.ropeYarn { arguments += ["--rope-yarn", String(factor)] }
arguments += mcp.enable.flatMap { ["--mcp-enable", $0] }
arguments += mcp.disable.flatMap { ["--mcp-disable", $0] }
arguments += mcp.imageDirs.flatMap { ["--image-dir", ($0 as NSString).expandingTildeInPath] }
Expand Down Expand Up @@ -147,6 +152,7 @@ extension ComposeSpec {
"experimental.expert_streaming is bound to the engine configuration at start"),
(experimental.kvHeadSplit != next.experimental.kvHeadSplit, "experimental.kv_head_split is bound to the engine configuration at start"),
(experimental.questTopK != next.experimental.questTopK, "experimental.quest_top_k is bound to the engine configuration at start"),
(experimental.ropeYarn != next.experimental.ropeYarn, "experimental.rope_yarn is bound to the model load at start"),
(mcp != next.mcp, "mcp options are bound to the server transport at start"),
]
return checks.first(where: \.0)?.1
Expand Down
1 change: 1 addition & 0 deletions Sources/BasaltInference/EngineConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public struct EngineConfiguration: Sendable {
public var smallMKernel = false
public var q3Kernel = false
public var kvSharedRow = false
public var ropeYarn: Double?
}

extension EngineConfiguration {
Expand Down
19 changes: 17 additions & 2 deletions Sources/BasaltInference/MLXInferenceEngine+Loading.swift
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ extension MLXInferenceEngine {
do {
try faults.check(.load)
if let gpuCacheLimit = configuration.gpuCacheLimit { Memory.cacheLimit = gpuCacheLimit }
let loaded = try await loadContainer(from: directory)
let source = ropeSource(directory, modelType: modelType, modelPath: modelPath)
let loaded = try await loadContainer(from: source)
let smallM = configuration.smallMKernel
let q3 = configuration.q3Kernel
try await loaded.perform {
Expand All @@ -165,7 +166,7 @@ extension MLXInferenceEngine {
profile: ModelProfileRegistry.profile(forModelAt: modelPath),
samplingDefaults: SamplingDefaults(generationConfig: ModelCache.generationConfig(at: directory)),
controlTokens: ControlTokenGuard(modelDirectory: directory),
fingerprint: promptCacheDisk == nil ? nil : PromptCacheDiskStore.fingerprint(modelDirectory: directory),
fingerprint: promptCacheDisk == nil ? nil : PromptCacheDiskStore.fingerprint(modelDirectory: source),
description: modelPath, hasMTPDrafter: drafts, expertReserve: await Self.expertReserve(loaded), capabilities: capabilities ?? .conservative,
imageToken: Self.imageToken(in: ModelCache.config(at: directory)),
transcribesAudio: transcribes)
Expand Down Expand Up @@ -251,6 +252,20 @@ extension MLXInferenceEngine {
return drafts
}

static let ropeStagingRoot = FileManager.default.homeDirectoryForCurrentUser.appending(path: ".basalt/rope-yarn")

func ropeSource(_ directory: URL, modelType: String?, modelPath: String) -> URL {
guard let factor = configuration.ropeYarn else { return directory }
do throws(RopeYarnStage.Refusal) {
let staged = try RopeYarnStage.stage(directory: directory, modelType: modelType, factor: factor, root: Self.ropeStagingRoot)
logger.info("--rope-yarn \(factor): YaRN over \(staged.nativeContext) native tokens, effective context \(staged.effectiveContext) (config staged at \(staged.directory.path))")
return staged.directory
} catch {
logger.warn("--rope-yarn \(factor) does not apply to \(modelPath): \(error.reason); the model loads with its stock RoPE")
return directory
}
}

func loadMTPDrafter(for loaded: ModelContainer, directory: URL, modelPath: String) async -> Bool {
let logger = self.logger, speculativeLookup = configuration.speculativeLookup, draftHead = configuration.mtpDraftHead
return await useMTPDrafter(in: loaded) { context in
Expand Down
95 changes: 95 additions & 0 deletions Sources/BasaltInference/RopeYarnStage.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import CryptoKit
import Foundation

enum RopeYarnStage {
struct Refusal: Error, Equatable {
let reason: String
}

struct Staged: Equatable {
let directory: URL
let nativeContext: Int
let effectiveContext: Int
}

static let modelTypes: Set<String> = ["qwen3_5", "qwen3_5_text", "qwen3_5_moe", "qwen3_5_moe_text"]

static func refusal(modelType: String?) -> Refusal? {
guard let modelType else { return Refusal(reason: "config.json names no model_type") }
if modelType.hasPrefix("gemma4") {
return Refusal(reason: "Gemma 4 uses proportional RoPE (p-RoPE) on its global layers and takes no RoPE scaling (#729)")
}
return modelTypes.contains(modelType) ? nil : Refusal(reason: "YaRN is wired for Qwen 3.5, 3.6 and 3.8 (qwen3_5) only, not \(modelType)")
}

static func rewritten(_ root: [String: Any], factor: Double) throws(Refusal) -> (config: [String: Any], native: Int, effective: Int) {
let nested = root["text_config"] as? [String: Any]
var text = nested ?? root
guard let native = text["max_position_embeddings"] as? Int, native > 0 else {
throw Refusal(reason: "config.json has no max_position_embeddings to scale")
}
if let scaling = text["rope_scaling"], !(scaling is NSNull) { throw Refusal(reason: "config.json already sets rope_scaling") }
var rope = text["rope_parameters"] as? [String: Any] ?? [:]
if let type = (rope["rope_type"] ?? rope["type"]) as? String, type != "default" {
throw Refusal(reason: "rope_parameters already uses rope_type \(type)")
}
for key in ["rope_theta", "partial_rotary_factor"] where rope[key] == nil { rope[key] = text[key] }
rope["rope_type"] = "yarn"
rope["factor"] = factor
rope["original_max_position_embeddings"] = native
let effective = Int((Double(native) * factor).rounded())
text["rope_parameters"] = rope
text["max_position_embeddings"] = effective
var config = root
if nested != nil { config["text_config"] = text } else { config = text }
return (config, native, effective)
}

static func stagingDirectory(for directory: URL, factor: Double, root: URL) -> URL {
let digest = SHA256.hash(data: Data(directory.standardizedFileURL.path.utf8)).map { String(format: "%02x", $0) }.joined()
return root.appending(component: "\(digest.prefix(16))-yarn-x\(factor)")
}

static func stage(directory: URL, modelType: String?, factor: Double, root: URL) throws(Refusal) -> Staged {
if let refusal = refusal(modelType: modelType) { throw refusal }
guard factor > 1, factor <= 64 else { throw Refusal(reason: "the factor must lie in (1, 64], got \(factor)") }
guard let data = try? Data(contentsOf: directory.appending(component: "config.json")),
let root0 = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
throw Refusal(reason: "config.json is unreadable")
}
let (config, native, effective) = try rewritten(root0, factor: factor)
let staging = stagingDirectory(for: directory, factor: factor, root: root)
do {
try publish(config: JSONSerialization.data(withJSONObject: config, options: [.sortedKeys]), source: directory, at: staging)
} catch {
throw Refusal(reason: "the staged config could not be written to \(staging.path): \(error.localizedDescription)")
}
return Staged(directory: staging, nativeContext: native, effectiveContext: effective)
}

static func publish(config: Data, source: URL, at staging: URL) throws {
let fm = FileManager.default
let names = try fm.contentsOfDirectory(atPath: source.path).filter { $0 != "config.json" && !$0.hasPrefix(".") }
if matches(staging, config: config, names: names, source: source) { return }
try fm.createDirectory(at: staging.deletingLastPathComponent(), withIntermediateDirectories: true)
let temporary = staging.deletingLastPathComponent().appending(component: "\(staging.lastPathComponent).\(UUID().uuidString)")
try fm.createDirectory(at: temporary, withIntermediateDirectories: false)
try config.write(to: temporary.appending(component: "config.json"))
for name in names {
try fm.createSymbolicLink(at: temporary.appending(component: name), withDestinationURL: source.appending(component: name).resolvingSymlinksInPath())
}
guard rename(temporary.path, staging.path) != 0 else { return }
if matches(staging, config: config, names: names, source: source) {
try? fm.removeItem(at: temporary)
} else {
_ = try fm.replaceItemAt(staging, withItemAt: temporary)
}
}

static func matches(_ staging: URL, config: Data, names: [String], source: URL) -> Bool {
guard (try? Data(contentsOf: staging.appending(component: "config.json"))) == config else { return false }
return names.allSatisfy { name in
staging.appending(component: name).resolvingSymlinksInPath() == source.appending(component: name).resolvingSymlinksInPath()
}
}
}
4 changes: 4 additions & 0 deletions Sources/PerformanceBenchmark/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ struct Benchmark: AsyncParsableCommand {
@Option(name: .customLong("quest-top-k"), help: "Experimental: decode attends to sinks, a recent window and this many 64-token blocks between them (Quest)")
var questTopK: Int?

@Option(name: .customLong("rope-yarn"), help: "Extend a Qwen 3.5/3.6/3.8 context with YaRN by this factor; other models load with stock RoPE and a warning")
var ropeYarn: Double?

@Flag(name: .customLong("experimental-kv-shared-row"), help: "Experimental: on Gemma 4 K=V global layers, store one 640-value row per KV head instead of 512 keys + 512 values (#645)")
var kvSharedRow = false

Expand Down Expand Up @@ -271,6 +274,7 @@ extension Benchmark {
configuration.kvHeadSplit = kvHeadSplit
configuration.questTopK = questTopK
configuration.kvSharedRow = kvSharedRow
configuration.ropeYarn = ropeYarn
configuration.repetitionPenalty = repetitionPenalty
(configuration.topK, configuration.minP, configuration.seed) = (topK, minP, seed)
(configuration.speculativeLookup, configuration.speculativeRecycling) = (speculativeLookup, speculativeRecycling)
Expand Down
Loading