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
10 changes: 5 additions & 5 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 10 additions & 16 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ let substrateDep: Package.Dependency =
// moving an old one). The verified guarantee is the paragraph below.
//
// Belt-and-braces regardless: Package.resolved records the resolved
// SHA, so even a moved tag forces 5b892140 or fails loudly under
// SHA, so even a moved tag forces the recorded revision or fails loudly under
// `swift build` / `swift test` — it never silently follows. Verified
// by reproducing #86 in a scratch repo (force-move + GC ⇒ hard error,
// never silent drift).
Expand All @@ -63,7 +63,7 @@ let substrateDep: Package.Dependency =
// Package.resolved — its pin state for any non-SHA `revision:`. It is
// a tag, not a branch; the reproducibility guarantee comes from the
// sibling `"revision"` field.
revision: "integration-2026-07-31", // 5b892140 — successor to 751aaed (integration force-pushed); TriAttention (MLXLMCommon) + Qwen3.5 MTP separate-drafter
revision: "integration-2026-10-14", // 29dcb353 — upstream c53d7d4 + batch-generate, DSpark, prompt-cache-lru; NO TriAttention (ADR 028 amendment)
traits: substrateTraits)
let hubDep: Package.Dependency =
athenaLocalDev
Expand Down Expand Up @@ -147,25 +147,19 @@ let package = Package(
// below; the ranges are not identical.
.package(
url: "https://github.com/ml-explore/mlx-swift",
// Floor is 0.31.6, not 0.31.3: the substrate at
// integration-2026-07-31 calls `MLXArray.maskFill` and
// `DType.greatestFiniteMagnitudeArray`, which land in mlx-swift
// 0.31.5 (bb0399d, #429) — 0.31.4 fails with two missing-member
// errors that look like a substrate bug (#86 CI, run
// 30724316996). The floor is 0.31.6 rather than the minimal
// 0.31.5 because 0.31.6 is what the #91 bump was actually built
// and verified against (and what Package.resolved pins); relax to
// 0.31.5 only with a re-verification. The substrate's OWN
// manifest still declares `.upToNextMinor(from: "0.31.4")` — a
// floor it does not itself compile against — so Athena states the
// real requirement rather than leaving Package.resolved as the
// only thing holding it. Note the toolchain floor this imposes
// Floor is 0.32.3: the substrate at integration-2026-10-14
// declares `.upToNextMinor(from: "0.32.3")`, and 0.32.3 is what
// this pin was cold-built and verified against. The floor is
// stated here rather than left to Package.resolved because the
// substrate's manifest floor has been wrong before (it declared
// 0.31.4 while needing 0.31.5 — #86 CI, run 30724316996). Note
// the toolchain floor this imposes
// is invisible in Athena's own `swift-tools-version: 6.1` header:
// mlx-swift 0.31.5+ ships a swift-tools-version 6.3 manifest, so
// building Athena needs Swift 6.3 (Xcode 26.5+, the verified floor) even though this
// manifest itself parses under 6.1 — an older toolchain fails at
// RESOLUTION with an error naming mlx-swift's tools version.
.upToNextMinor(from: "0.31.6")),
.upToNextMinor(from: "0.32.3")),
// swift-transformers (Jinja chat templates + tokenizers) and
// swift-huggingface (Hub client) are NOT transitive deps of
// mlx-swift-lm — the MLXHuggingFace macros expand into code that
Expand Down
28 changes: 26 additions & 2 deletions Sources/AthenaCore/KVCompression.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,31 @@ import Foundation
///
/// Precedence: env `ATHENA_KV_COMPRESSION` > TOML `kv_compression` >
/// built-in default `none`. An unrecognized value is a hard error at
/// daemon start (fail-closed — never a silent fallback to `none`).
/// daemon start (fail-closed — never a silent fallback to `none`), and so is a
/// recognized codec the pinned substrate cannot serve (`unavailableReason`).
public enum KVCompression: String, Sendable, CaseIterable, Equatable {
case none
case triattention

/// Why this codec cannot run at the pinned substrate, or nil if it can.
/// The substrate fails every generation whose `kvScheme` it does not
/// recognize, so an unavailable codec is refused here, once, by name.
public var unavailableReason: String? {
switch self {
case .none: return nil
case .triattention:
return "kv_compression 'triattention' is unavailable: the pinned "
+ "MLX substrate (integration-2026-10-14) does not include "
+ "TriAttention eviction. Set kv_compression = none "
+ "(ADR 028, 2026-10-14 amendment)."
}
}

public struct UnavailableError: Error, CustomStringConvertible {
public let reason: String
public var description: String { reason }
}

public struct ResolutionError: Error, CustomStringConvertible {
public let value: String
public var description: String {
Expand All @@ -33,7 +53,8 @@ public enum KVCompression: String, Sendable, CaseIterable, Equatable {
}

/// Pure resolver (inject env + TOML values). Precedence env > TOML >
/// `none`; empty/whitespace is treated as unset; unknown ⇒ throw.
/// `none`; empty/whitespace is treated as unset; unknown or unavailable ⇒
/// throw.
public static func resolve(env: String?, toml: String?) throws -> KVCompression {
func clean(_ s: String?) -> String? {
guard let t = s?.trimmingCharacters(in: .whitespacesAndNewlines),
Expand All @@ -45,6 +66,9 @@ public enum KVCompression: String, Sendable, CaseIterable, Equatable {
guard let v = KVCompression(rawValue: raw.lowercased()) else {
throw ResolutionError(value: raw)
}
if let reason = v.unavailableReason {
throw UnavailableError(reason: reason)
}
return v
}

Expand Down
14 changes: 8 additions & 6 deletions Sources/AthenaCore/ModelClass.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public enum ModelClass: String, Sendable, Equatable {
/// detector stays MLX-free; mirrors `EmbedderTypeRegistry`'s encoder set.
public static let embedderOnlyTypes: Set<String> = [
"bert", "roberta", "xlm-roberta", "distilbert", "nomic_bert",
"embedding_gemma2", "embedding_gemma2_text",
]

/// Repo-root filenames whose presence marks a sentence-transformers
Expand All @@ -41,18 +42,19 @@ public enum ModelClass: String, Sendable, Equatable {
]

/// Classify from parsed config + whether the snapshot carries
/// sentence-transformers markers. Order matters: vision wins first (an
/// image tower must load through the VLM factory), then embedding (ST
/// markers OR an embedder-only `model_type`), then any named generative
/// type, else unknown.
/// sentence-transformers markers. Order matters: an embedder-only
/// `model_type` wins first (EmbeddingGemma 2 ships vision and audio towers
/// but loads only through the embedder factory), then vision (an image
/// tower must load through the VLM factory), then ST markers, then any
/// named generative type, else unknown.
public static func classify(
info: ModelConfigInfo?,
hasSentenceTransformerMarkers: Bool
) -> ModelClass {
if info?.hasVisionConfig == true { return .vision }
let type = info?.modelType?.lowercased()
if hasSentenceTransformerMarkers { return .embedding }
if let type, embedderOnlyTypes.contains(type) { return .embedding }
if info?.hasVisionConfig == true { return .vision }
if hasSentenceTransformerMarkers { return .embedding }
return type == nil ? .unknown : .generative
}

Expand Down
10 changes: 8 additions & 2 deletions Sources/AthenaDeploy/ConfigEditor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,14 @@ public enum ConfigEditor {
throw Failure.badValue(
key,
"one of "
+ KVCompression.allCases.map(\.rawValue)
.joined(separator: ", "))
+ KVCompression.allCases
.filter { $0.unavailableReason == nil }
.map(\.rawValue).joined(separator: ", "))
}
if key == "kv_compression",
let reason = KVCompression(rawValue: value)?.unavailableReason
{
throw Failure.badValue(key, "none — \(reason)")
}
// ADR 023 G2 — admission mode is an enum-ish string; reject a typo
// at set-time against the source-of-truth case list (mirrors
Expand Down
3 changes: 2 additions & 1 deletion Sources/AthenaDeploy/DefaultConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ public enum DefaultConfig {
# max_tokens = 1024
# temperature = 0.7
# speculative = false
# KV-cache compression: "none" | "triattention".
# KV-cache compression: "none" ("triattention" is refused while the
# MLX substrate pin lacks it).
# kv_compression = "none"


Expand Down
19 changes: 14 additions & 5 deletions Sources/AthenaEmbedding/MLXEmbeddingModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,17 @@ public actor MLXEmbeddingModule: EmbeddingModule, ModelSelectable {
/// driving an unbounded O(L²) forward pass via a singleton bucket.
static let maxInputTokens = 32_768

/// EmbeddingGemma 2 slices its input to its context length, so a longer
/// input would embed only its prefix while usage counts all of it.
// ponytail: scoped to EmbeddingGemma 2. BERT-family models also report a
// smaller `maxPositionEmbeddings` (512) and accept longer input today;
// applying the cap to every model is a client-visible change (#235).
static func inputCeiling(for model: any EmbeddingModel) -> Int {
guard model is EmbeddingGemma2, let limit = model.maxPositionEmbeddings
else { return maxInputTokens }
return min(maxInputTokens, limit)
}

public func embed(_ texts: [String], model: String? = nil) async throws
-> EmbeddingBatch
{
Expand Down Expand Up @@ -346,12 +357,10 @@ public actor MLXEmbeddingModule: EmbeddingModule, ModelSelectable {
// O(L²) forward pass on a RoPE embedder (remote OOM/compute
// DoS); OpenAI likewise 400s over-length input rather than
// returning a silently-truncated vector.
if let longest = encoded.map(\.count).max(),
longest > Self.maxInputTokens
{
let cap = Self.inputCeiling(for: ctx.model)
if let longest = encoded.map(\.count).max(), longest > cap {
throw AthenaError.inputTooLong(
module: .textEmbedding, tokens: longest,
maxTokens: Self.maxInputTokens)
module: .textEmbedding, tokens: longest, maxTokens: cap)
}
let promptTokens = encoded.reduce(0) { $0 + $1.count }
let pad = tokenizer.eosTokenId ?? 0
Expand Down
8 changes: 7 additions & 1 deletion Sources/AthenaLLM/GuidedSubstrate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ import MLXLMCommon
/// needed here. The vendored Qwen3.5 path is untouched (faster MTP +
/// optional thinking prefix), so this is purely additive for other arches.
enum GuidedSubstrate {
/// The prefill window of the serve and guided paths. ADR 030's prompt
/// ceiling reasons about the O(seq²) score buffer per 512-token chunk, so
/// the step is pinned (#88) and so is the chunking: the substrate's default
/// became `.balanced` at integration-2026-10-14, which re-divides the prompt
/// into equal chunks; `.remainder` keeps the exact 512-token boundaries.
static let prefill = PrefillParameters(stepSize: 512, chunking: .remainder)

/// A `LogitProcessor` that constrains every step to the Guide's
/// currently-allowed token set and advances the Guide on each
Expand Down Expand Up @@ -83,7 +89,7 @@ enum GuidedSubstrate {
var iterator = try TokenIterator(
input: input, model: model, cache: nil,
processor: processor, sampler: ArgMaxSampler(),
prefillStepSize: 512, maxTokens: maxTokens)
prefill: prefill, maxTokens: maxTokens)

var out: [Int] = []
while let token = iterator.next() {
Expand Down
75 changes: 53 additions & 22 deletions Sources/AthenaLLM/MLXLLMModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -626,12 +626,15 @@ public actor MLXLLMModule: LLMModule, ModelSelectable {
mtpDrafterName = nil
guard params.speculative else { return }
guard let mt = modelType?.lowercased() else { return }
// Qwen3.5 MTP (publication S0): the fused `mtp.*` head ships inside the
// TARGET checkpoint, so the substrate drafter loads from the same
// directory — no separate drafter repo / pairing map. Inert when the
// checkpoint carries no `mtp.*` weights.
if mt.hasPrefix("qwen3_5") {
await loadQwen35MTPDrafter(targetName: targetName)
// ponytail: Qwen3.5 MTP stays inert at integration-2026-10-14. Its
// substrate iterator prefills the whole prompt in one unchunked
// forward (full-vocab logits per position), outside Athena's
// 512-token window and the ADR 030 ceiling; re-enable after that is
// measured (#92).
Self.log.notice(
"Qwen3.5 MTP speculative is disabled at this substrate pin (#92); decoding without a drafter",
metadata: ["function": "loadMTPDrafterIfEligible"])
return
}
// The substrate drafter (`Gemma4AssistantDraftModel`) only drafts for a
Expand Down Expand Up @@ -865,6 +868,7 @@ public actor MLXLLMModule: LLMModule, ModelSelectable {
requestSpeculative: speculative)
continuation.yield(
.startsInReasoning(begun.startsInReasoning))
var truncatedRejection: RejectedToolCall?
for await event in begun.stream {
switch event {
case .chunk(let text):
Expand All @@ -883,6 +887,32 @@ public actor MLXLLMModule: LLMModule, ModelSelectable {
tc.function.arguments
.mapValues { $0.anyValue }
)))
case .rejectedToolCall(let r):
// Tool-call-shaped output the substrate
// could not turn into a call. Before
// integration-2026-10-14 malformed and
// incomplete calls flushed as content,
// and that is kept; a call to an
// undeclared tool, which used to pass
// through as a tool call, also lands
// here now. The preview may hold
// argument values, so the log line
// carries the reason only.
Self.log.notice(
"rejected tool call: \(r.reason.rawValue) (\(r.rawTextByteCount) bytes, preview truncated: \(r.isPreviewTruncated))"
)
// A truncated preview has lost its
// middle bytes; returning it as
// content would corrupt the answer.
// The stream is drained before the
// throw so the producer has stopped
// before the inference gate opens.
if r.isPreviewTruncated {
truncatedRejection = r
} else {
continuation.yield(
.text(r.rawTextPreview))
}
case .info(let info):
// Substrate's terminal completion
// record carries the token geometry.
Expand All @@ -904,6 +934,9 @@ public actor MLXLLMModule: LLMModule, ModelSelectable {
break
}
}
if let truncatedRejection {
throw RejectedToolCallError(truncatedRejection)
}
continuation.yield(.usage(u))
}
return u
Expand Down Expand Up @@ -1272,26 +1305,13 @@ public actor MLXLLMModule: LLMModule, ModelSelectable {
let requestSeed: UInt64? = seed.flatMap {
$0 >= 0 ? UInt64($0) : nil
}
// #88 — the substrate's prefillStepSize default became `nil`
// (model-chosen) at integration-2026-07-31. Pin 512 explicitly so the
// prefill chunk — the window over which the O(seq²) score buffer ADR
// 030's prompt ceiling reasons about is materialised — is chosen by
// Athena, not inherited, and so this path agrees with
// GuidedSubstrate's literal 512. Adopting a model-chosen window is
// #88 — the prefill window is Athena's, not the substrate default
// (see `GuidedSubstrate.prefill`). Adopting a model-chosen window is
// #88 direction 2 and requires the peak-prefill-memory measurement.
let gp = GenerateParameters(
let gp = Self.serveParameters(
maxTokens: Self.effectiveMaxTokens(maxTokens, params.maxTokens),
kvScheme: params.kvCompression.kvScheme,
temperature: temp,
topP: tp,
prefillStepSize: 512,
seed: requestSeed)
// Publication S0 — TriAttention eviction now rides the substrate's
// `kvScheme` hook on `gp` (upstream `applyKVScheme` swaps each
// `KVCacheSimple` for a `TriAttentionKVCache` when the cache is built
// inside `generate`); no task-local, no vendored model. The substrate
// deliberately skips eviction on the MTP/speculative path, matching the
// old inert-on-MTP behavior.
temperature: temp, topP: tp, seed: requestSeed)
do {
let userInput = UserInput(
chat: Self.chatMessages(messages), tools: tools,
Expand Down Expand Up @@ -1340,6 +1360,17 @@ public actor MLXLLMModule: LLMModule, ModelSelectable {
}
}

/// The standard serve path's generation parameters. The prefill window is
/// `GuidedSubstrate.prefill`, never the substrate default (#88).
static func serveParameters(
maxTokens: Int, kvScheme: String?, temperature: Float, topP: Float,
seed: UInt64?
) -> GenerateParameters {
GenerateParameters(
maxTokens: maxTokens, kvScheme: kvScheme, temperature: temperature,
topP: topP, prefill: GuidedSubstrate.prefill, seed: seed)
}

/// A positive per-request `max_tokens` override wins; otherwise the
/// loaded default. Guards against 0/negative overrides truncating to
/// nothing.
Expand Down
Loading
Loading