diff --git a/.github/workflows/build-wheels.yml b/.github/workflows/build-wheels.yml
index 9c67a168fe..156f03fea6 100644
--- a/.github/workflows/build-wheels.yml
+++ b/.github/workflows/build-wheels.yml
@@ -45,7 +45,7 @@ jobs:
# we build against the job's Python and pin it for CMake explicitly.
run: |
python -m pip install --upgrade pip
- python -m pip install build setuptools wheel "cmake>=3.27" "nanobind==2.13.0" "mlx==0.32.0"
+ python -m pip install build setuptools wheel "cmake>=3.27" "nanobind==2.15.0" "mlx==0.32.2"
export CMAKE_ARGS="-DPython_EXECUTABLE=$(python -c 'import sys; print(sys.executable)')"
python -m build --wheel --no-isolation
@@ -60,14 +60,46 @@ jobs:
cd /tmp
/tmp/wheel-smoke/bin/python - <<'PY'
import importlib
+ import mlx.core as mx
+
failed = []
- for pkg in ("bonsai", "glm_moe_dsa", "minimax_m3", "qwen35_prefill"):
+ for pkg in (
+ "bonsai",
+ "decode_fast",
+ "glm_moe_dsa",
+ "minimax_m3",
+ "qwen35_prefill",
+ ):
fast = importlib.import_module(f"omlx.custom_kernels.{pkg}.fast")
ok = bool(fast.is_native_available())
print(f"{pkg}: native_available={ok} import_error={fast.import_error()}")
if not ok:
failed.append(pkg)
- raise SystemExit(f"native kernels missing from wheel: {failed}" if failed else 0)
+ if failed:
+ raise SystemExit(f"native kernels missing from wheel: {failed}")
+
+ # Exercise a real primitive from the newest native package, not just
+ # its nanobind ABI probe, so the wheel also proves dylib/metallib
+ # lookup and MLX 0.32.2 runtime dispatch.
+ from omlx.custom_kernels.decode_fast import fast as decode_fast
+
+ mx.random.seed(3142)
+ q = mx.random.normal((1, 4, 1, 64)).astype(mx.float16)
+ k = mx.random.normal((1, 2, 128, 64)).astype(mx.float16)
+ v = mx.random.normal((1, 2, 128, 64)).astype(mx.float16)
+ if not decode_fast._ext.sdpa_decode_supported(q, k, v):
+ raise SystemExit("decode_fast rejected the wheel smoke shape")
+ out = decode_fast.sdpa_decode(q, k, v, 64 ** -0.5)
+ ref = mx.fast.scaled_dot_product_attention(
+ q, k, v, scale=64 ** -0.5
+ )
+ mx.eval(out, ref)
+ error = mx.max(
+ mx.abs(out.astype(mx.float32) - ref.astype(mx.float32))
+ ).item()
+ print(f"decode_fast: shape={out.shape} max_abs={error}")
+ if error >= 5e-3:
+ raise SystemExit(f"decode_fast mismatch: max_abs={error}")
PY
- name: Upload wheel artifact
diff --git a/Formula/omlx.rb b/Formula/omlx.rb
index d28365edb9..e35b1876bb 100644
--- a/Formula/omlx.rb
+++ b/Formula/omlx.rb
@@ -1,16 +1,16 @@
class Omlx < Formula
- CUSTOM_KERNELS = %w[bonsai glm_moe_dsa minimax_m3 qwen35_prefill].freeze
+ CUSTOM_KERNELS = %w[bonsai decode_fast glm_moe_dsa minimax_m3 qwen35_prefill].freeze
desc "LLM inference server optimized for Apple Silicon"
homepage "https://github.com/jundot/omlx"
- url "https://github.com/jundot/omlx/archive/refs/tags/v0.6.3rc3.tar.gz"
- sha256 "1d08ff4585eb796f34f56d266b69cae65b51a48d98a4b213caca094d7c82a839"
+ url "https://github.com/jundot/omlx/archive/refs/tags/v0.6.4.tar.gz"
+ sha256 "5d8781c0c6a782e9b90f071d36b0d8dbe6161fafb5fef5e3f0d8ac71da214b70"
license "Apache-2.0"
head "https://github.com/jundot/omlx.git", branch: "main"
option "with-custom-kernel",
- "Build native custom kernels for Bonsai, GLM-5.2, MiniMax M3 and Qwen3.5/3.6 acceleration"
+ "Build native custom kernels for Bonsai, GLM-5.2, MiniMax M3 and Qwen3.5/3.6/4 acceleration"
option "with-grammar", "Install xgrammar for structured output (requires torch, ~2GB)"
depends_on "rust" => :build
diff --git a/README.md b/README.md
index 10c14359d4..fff77a9242 100644
--- a/README.md
+++ b/README.md
@@ -435,5 +435,5 @@ Contributions are welcome! See [Contributing Guide](docs/CONTRIBUTING.md) for de
- [mlx-embeddings](https://github.com/Blaizzy/mlx-embeddings) - Embedding model support for Apple Silicon
- [dflash-mlx](https://github.com/bstnxbt/dflash-mlx) - Block diffusion speculative decoding on Apple Silicon
- [MTPLX](https://github.com/youssofal/mtplx) - Lightning MTP's verify-shape Metal kernels are powered by MTPLX by Youssof Altoukhi, which also inspired the depth-k pipeline
-- [mlx-serve](https://github.com/ddalcu/mlx-serve) - The fused GDN verify prework kernel is adapted from mlx-serve's port of the mlxfast-challenge qwen35_packed_gdn_prework kernel
+- [mlx-serve](https://github.com/ddalcu/mlx-serve) - The fused GDN verify prework kernel is adapted from mlx-serve's port of the mlxfast-challenge qwen35_packed_gdn_prework kernel; Qwen4 QSA's 128-bit K/V staging is adapted from mlx-serve's MIT-licensed `msv_attn_p256` kernel
- [SiliconScope](https://github.com/kennss/SiliconScope) - The menu bar statistics take their design and rendering approach from SiliconScope by Kennt Kim, which also inspired the energy-efficient re-render gating
diff --git a/apps/omlx-mac/Resources/Localizable.xcstrings b/apps/omlx-mac/Resources/Localizable.xcstrings
index 3e8efc8978..afa047f50a 100644
--- a/apps/omlx-mac/Resources/Localizable.xcstrings
+++ b/apps/omlx-mac/Resources/Localizable.xcstrings
@@ -17102,6 +17102,54 @@
}
}
},
+ "server.advanced.max_audio_upload_size" : {
+ "comment" : "Advanced row label for the audio upload size limit",
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Maximum Audio Upload Size"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Максимальный размер загрузки аудио"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "最大音频上传大小"
+ }
+ }
+ }
+ },
+ "server.advanced.max_audio_upload_size.sub" : {
+ "comment" : "Sublabel describing the audio upload size limit",
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Максимальный размер файла для расшифровки и обработки аудио. Большие значения могут увеличить использование памяти при одновременных запросах."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "音频转录和处理接口接受的最大文件大小。较大的值可能会增加并发请求的内存使用量。"
+ }
+ }
+ }
+ },
"server.advanced.sse_keepalive" : {
"comment" : "Advanced row label for the SSE keep-alive mode picker",
"extractionState" : "manual",
@@ -17342,6 +17390,30 @@
}
}
},
+ "server.error.audio_upload_size_invalid" : {
+ "comment" : "Server screen error when the audio upload size is invalid",
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Maximum Audio Upload Size must be a positive value such as 100MB or 1GB."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Максимальный размер загрузки аудио должен быть положительным значением, например 100MB или 1GB."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "最大音频上传大小必须是正值,例如 100MB 或 1GB。"
+ }
+ }
+ }
+ },
"server.error.base_path_empty" : {
"comment" : "Server screen error when Base Path is empty on Apply",
"extractionState" : "manual",
@@ -19991,6 +20063,42 @@
}
}
},
+ "settings.advanced.qwen4_ssd_offload.forced" : {
+ "comment" : "Sublabel when Qwen4 PLE SSD offload is forced by memory limits",
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Required because resident loading exceeds the configured model-memory limit."
+ }
+ }
+ }
+ },
+ "settings.advanced.qwen4_ssd_offload.label" : {
+ "comment" : "Row label for the Qwen4 PLE SSD mmap toggle",
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "SSD N-gram Offload (Qwen4 only)"
+ }
+ }
+ }
+ },
+ "settings.advanced.qwen4_ssd_offload.sub" : {
+ "comment" : "Sublabel for the Qwen4 PLE SSD mmap toggle",
+ "extractionState" : "manual",
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Keep the PLE N-gram table on SSD to save memory. Prefill can be slower after context changes."
+ }
+ }
+ }
+ },
"settings.advanced.experimental.section" : {
"comment" : "Section header above the Experimental settings group",
"extractionState" : "manual",
diff --git a/apps/omlx-mac/Sources/AppView/AppView.swift b/apps/omlx-mac/Sources/AppView/AppView.swift
index 0f5b667624..8f5d6172cb 100644
--- a/apps/omlx-mac/Sources/AppView/AppView.swift
+++ b/apps/omlx-mac/Sources/AppView/AppView.swift
@@ -21,8 +21,12 @@ struct AppView: View {
let theme = scheme == .dark ? OMLXTheme.dark : OMLXTheme.light
let section = selectedSection
- NavigationSplitView {
+ // The sidebar is the only way to switch screens, so it must never
+ // collapse: pin visibility to `.all` and remove the toolbar toggle,
+ // matching System Settings.
+ NavigationSplitView(columnVisibility: .constant(.all)) {
SettingsSidebar(selection: bindingForSelection())
+ .toolbar(removing: .sidebarToggle)
} detail: {
ContentScaffold(section: section, detailTitle: detailTitle) {
screen(for: section)
@@ -557,10 +561,37 @@ private struct ContentScaffold: View {
}
}
.navigationTitle(titleText)
+ .modifier(ToolbarHeightKeeper())
.background(theme.windowBg)
}
}
+/// macOS collapses the unified toolbar to a compact title bar on panes
+/// that contribute no toolbar items. With the sidebar toggle removed,
+/// only screens with their own items (Logs, Model Settings) kept the
+/// full-height bar — so every screen contributes an invisible item to
+/// keep the height uniform. On macOS 26 the Liquid Glass capsule that
+/// toolbars draw around every item must be hidden explicitly, or the
+/// invisible item shows up as a small vertical bar.
+private struct ToolbarHeightKeeper: ViewModifier {
+ func body(content: Content) -> some View {
+ if #available(macOS 26.0, *) {
+ content.toolbar {
+ ToolbarItem {
+ Color.clear.frame(width: 1, height: 1)
+ }
+ .sharedBackgroundVisibility(.hidden)
+ }
+ } else {
+ content.toolbar {
+ ToolbarItem {
+ Color.clear.frame(width: 1, height: 1)
+ }
+ }
+ }
+ }
+}
+
/// Composite identity used by `ContentScaffold`'s deep-link scroll
/// `.task(id:)` so the scroll fires whenever either the section or the
/// anchor changes — and re-fires if the same anchor is requested twice.
diff --git a/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift
index 22cbad00ad..eab82ee08d 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift
@@ -69,9 +69,9 @@ private struct HeroCard: View {
.padding(18)
.frame(maxWidth: .infinity, alignment: .leading)
.background(theme.groupBg)
- .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
+ .clipShape(RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous))
.overlay(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
+ RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous)
.strokeBorder(theme.groupBorder, lineWidth: 0.5)
)
.padding(.horizontal, 14)
diff --git a/apps/omlx-mac/Sources/AppView/Screens/AccuracyBenchScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/AccuracyBenchScreen.swift
index 99e6f72620..775e3517e0 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/AccuracyBenchScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/AccuracyBenchScreen.swift
@@ -198,7 +198,7 @@ private struct ConfigurationSection: View {
comment: "Sublabel under the Accuracy Bench model picker")) {
Popup(
selection: $selectedModelId,
- width: 320,
+ width: .controlWide,
options: modelOptions
)
}
@@ -222,7 +222,7 @@ private struct ConfigurationSection: View {
defaultValue: "Enable per-question reasoning traces (slower)",
comment: "Sublabel under the Accuracy Bench extended-thinking toggle")
) {
- Toggle("", isOn: $enableThinking).labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $enableThinking)
}
FreeRow {
@@ -417,7 +417,7 @@ private struct BenchmarkCard: View {
.foregroundStyle(theme.textTertiary)
Popup(
selection: $sampleSize,
- width: 90,
+ width: .controlNarrow,
options: sampleSizeOptions
)
}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/AppearanceScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/AppearanceScreen.swift
index e01562084d..ca04ecb69c 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/AppearanceScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/AppearanceScreen.swift
@@ -46,7 +46,7 @@ struct AppearanceScreen: View {
comment: "Appearance row sublabel for the menubar refresh cadence picker"
)
) {
- Popup(selection: $refreshInterval, width: 110, options: [
+ Popup(selection: $refreshInterval, width: .controlCompact, options: [
(0.5, "0.5 s"),
(1.0, "1 s"),
(2.0, "2 s"),
@@ -65,9 +65,7 @@ struct AppearanceScreen: View {
comment: "Appearance row sublabel for the permanent Dock icon toggle"
)
) {
- Toggle("", isOn: $showDockIcon)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $showDockIcon)
}
// Sits right under the Dock toggle because that's where people
// look for it — the Dock icon and the menu bar icon read as one
@@ -140,7 +138,6 @@ struct AppearanceScreen: View {
)
),
])
- .frame(width: 200)
}
}
@@ -170,9 +167,7 @@ struct AppearanceScreen: View {
comment: "Appearance row sublabel for the LIV menubar item toggle"
)
) {
- Toggle("", isOn: $showLiveActivity)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $showLiveActivity)
}
Row(
label: String(
@@ -186,9 +181,7 @@ struct AppearanceScreen: View {
comment: "Appearance row sublabel for the AVG menubar item toggle"
)
) {
- Toggle("", isOn: $showAverageActivity)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $showAverageActivity)
}
Row(
label: String(
@@ -202,9 +195,7 @@ struct AppearanceScreen: View {
comment: "Appearance row sublabel for the ALL menubar item toggle"
)
) {
- Toggle("", isOn: $showAlltimeActivity)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $showAlltimeActivity)
}
Row(
label: String(
@@ -218,9 +209,7 @@ struct AppearanceScreen: View {
comment: "Appearance row sublabel for the CPU usage bar menubar item toggle"
)
) {
- Toggle("", isOn: $showCPUItem)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $showCPUItem)
}
Row(
label: String(
@@ -234,9 +223,7 @@ struct AppearanceScreen: View {
comment: "Appearance row sublabel for the GPU usage bar menubar item toggle"
)
) {
- Toggle("", isOn: $showGPUItem)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $showGPUItem)
}
Row(
label: String(
@@ -251,9 +238,7 @@ struct AppearanceScreen: View {
),
isLast: true
) {
- Toggle("", isOn: $showMemoryItem)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $showMemoryItem)
}
}
}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/ContextBenchScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ContextBenchScreen.swift
index 4738ce18cc..de5adb7bb3 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/ContextBenchScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/ContextBenchScreen.swift
@@ -118,7 +118,7 @@ private struct ConfigurationSection: View {
comment: "Sublabel under the Context Bench model picker")) {
Popup(
selection: $selectedModelId,
- width: 320,
+ width: .controlWide,
options: modelOptions
)
}
@@ -135,7 +135,6 @@ private struct ConfigurationSection: View {
(value: $0, label: "\($0 / 1024)k")
}
)
- .frame(width: 320)
.disabled(running)
}
@@ -162,7 +161,6 @@ private struct ConfigurationSection: View {
],
icons: ["arrow.up.left.and.arrow.down.right", "speedometer"]
)
- .frame(width: 240)
.disabled(running)
}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/DownloadsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/DownloadsScreen.swift
index 8d51ab91f0..a936cc52bb 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/DownloadsScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/DownloadsScreen.swift
@@ -107,13 +107,7 @@ struct DownloadsScreen: View {
onShowCard: { repo in vm.showModelCard(repoId: repo) }
)
- if let error = vm.lastError {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(.red)
- .padding(.horizontal, 18)
- .padding(.top, 8)
- }
+ FooterBar(error: vm.lastError)
}
.task { await vm.start(client: services.client) }
.onDisappear { vm.stop() }
@@ -134,9 +128,11 @@ struct DownloadsScreen: View {
// MARK: - Source switcher
-/// Segmented HF / ModelScope toggle pinned at the top of Downloads. When
-/// the server's modelscope SDK isn't installed (`/admin/api/ms/status`
-/// returns `available: false`), the MS option is disabled with a tooltip
+/// HF / ModelScope tabs pinned at the top of Downloads, rendered as a
+/// centered segmented control — the macOS convention for top-of-pane tabs
+/// (System Settings › Trackpad, Finder settings). When the server's
+/// modelscope SDK isn't installed (`/admin/api/ms/status` returns
+/// `available: false`), the MS option is disabled with a note underneath
/// rather than hidden — so a user looking for it can see why it's not
/// usable.
private struct SourceSwitcher: View {
@@ -144,21 +140,24 @@ private struct SourceSwitcher: View {
let msAvailable: Bool
var body: some View {
- HStack(spacing: 8) {
+ VStack(spacing: 6) {
Segmented(
selection: $source,
options: DownloadSource.allCases.map { ($0, $0.label) }
)
.disabled(!msAvailable)
+ // A fixed frame makes the picker split the width into equal
+ // tab-sized segments instead of hugging the labels.
+ .frame(width: 280)
if !msAvailable {
Text(String(localized: "downloads.source.ms_unavailable",
defaultValue: "ModelScope SDK unavailable in this build",
- comment: "Inline note shown beside the source switcher when the ModelScope SDK isn't installed"))
+ comment: "Note shown under the source switcher when the ModelScope SDK isn't installed"))
.font(.omlxText(10.5))
.foregroundStyle(.secondary)
}
- Spacer(minLength: 0)
}
+ .frame(maxWidth: .infinity)
.padding(.horizontal, 14)
.padding(.top, 4)
.padding(.bottom, 8)
@@ -803,7 +802,7 @@ private struct SuggestedSection: View {
HStack(spacing: 6) {
Popup(
selection: $sort,
- width: 170,
+ width: .controlMedium,
options: SuggestedSort.allCases.map { ($0, $0.label) }
)
Button {
diff --git a/apps/omlx-mac/Sources/AppView/Screens/IntegrationsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/IntegrationsScreen.swift
index c67f516977..ccc08aba16 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/IntegrationsScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/IntegrationsScreen.swift
@@ -25,13 +25,7 @@ struct IntegrationsScreen: View {
OtherIntegrationsSection(vm: vm, client: services.client)
MCPSection(vm: vm, client: services.client)
- if let error = vm.lastError {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(.red)
- .padding(.horizontal, 18)
- .padding(.top, 8)
- }
+ FooterBar(error: vm.lastError)
}
.task { await vm.load(client: services.client) }
}
@@ -79,7 +73,7 @@ private struct ClaudeCodeSection: View {
selection: vm.bind($vm.opusModel, save: {
Task { await vm.save(.opusModel, client: client) }
}),
- width: 220,
+ width: .controlMedium,
options: vm.modelOptions
)
}
@@ -90,7 +84,7 @@ private struct ClaudeCodeSection: View {
selection: vm.bind($vm.sonnetModel, save: {
Task { await vm.save(.sonnetModel, client: client) }
}),
- width: 220,
+ width: .controlMedium,
options: vm.modelOptions
)
}
@@ -106,7 +100,7 @@ private struct ClaudeCodeSection: View {
selection: vm.bind($vm.haikuModel, save: {
Task { await vm.save(.haikuModel, client: client) }
}),
- width: 220,
+ width: .controlMedium,
options: vm.modelOptions
)
}
@@ -120,10 +114,9 @@ private struct ClaudeCodeSection: View {
comment: "Sublabel for the context scaling toggle"),
isLast: !vm.contextScaling
) {
- Toggle("", isOn: vm.bind($vm.contextScaling, save: {
+ RowSwitch(isOn: vm.bind($vm.contextScaling, save: {
Task { await vm.save(.contextScaling, client: client) }
}))
- .labelsHidden().toggleStyle(.switch)
}
if vm.contextScaling {
Row(
@@ -139,14 +132,13 @@ private struct ClaudeCodeSection: View {
text: $vm.targetContextSizeText,
mono: true,
suffix: "tk",
- width: 130
+ width: .controlCompact
)
}
}
}
if vm.contextScaling {
- HStack {
- Spacer()
+ FooterBar {
Button(String(localized: "integrations.target_context.apply",
defaultValue: "Apply",
comment: "Apply button for the Claude Code target context size field")) {
@@ -155,8 +147,6 @@ private struct ClaudeCodeSection: View {
.buttonStyle(.omlx(.primary))
.disabled(!vm.hasPendingContextSizeChange)
}
- .padding(.horizontal, 18)
- .padding(.top, 6)
}
}
}
@@ -237,36 +227,18 @@ private struct CommandBlock: View {
.strokeBorder(theme.groupBorder, lineWidth: 0.5)
)
- CopyButton(value: command)
- .padding(.top, 6)
- .padding(.trailing, 8)
- }
- }
-}
-
-private struct CopyButton: View {
- let value: String
- @State private var copied = false
- @Environment(\.omlxTheme) private var theme
-
- var body: some View {
- Button {
- let pb = NSPasteboard.general
- pb.clearContents()
- pb.setString(value, forType: .string)
- copied = true
- DispatchQueue.main.asyncAfter(deadline: .now() + 1.4) {
- copied = false
- }
- } label: {
- Image(systemName: copied ? "checkmark" : "document.on.document")
- .font(.system(size: 11, weight: .medium))
- .foregroundStyle(copied ? theme.successText : theme.textSecondary)
- .padding(5)
- .background(theme.controlBg)
- .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous))
+ // Same quiet copy affordance as `CodeChip`/`CopyIconButton`
+ // everywhere else — the previous locally-drawn boxed button was a
+ // second copy-button style.
+ CopyIconButton(
+ value: command,
+ helpText: String(localized: "integrations.command.copy",
+ defaultValue: "Copy command",
+ comment: "Tooltip for the copy button on a shell command block")
+ )
+ .padding(.top, 4)
+ .padding(.trailing, 4)
}
- .buttonStyle(.plain)
}
}
@@ -392,7 +364,7 @@ private struct IntegrationRow: View {
Spacer(minLength: 12)
Popup(
selection: modelBinding,
- width: 220,
+ width: .controlMedium,
options: modelOptions
)
}
@@ -413,7 +385,7 @@ private struct IntegrationRow: View {
Spacer(minLength: 12)
Popup(
selection: profileBinding,
- width: 160,
+ width: .controlMedium,
options: [
("minimal", String(localized: "integrations.openclaw.profile.minimal",
defaultValue: "Minimal",
@@ -478,12 +450,11 @@ private struct MCPSection: View {
text: $vm.mcpConfigPath,
placeholder: "/path/to/mcp.json",
mono: true,
- width: 320
+ width: .controlWide
)
}
}
- HStack {
- Spacer()
+ FooterBar {
Button(String(localized: "integrations.mcp.apply",
defaultValue: "Apply",
comment: "Apply button for the MCP config path")) {
@@ -492,7 +463,5 @@ private struct MCPSection: View {
.buttonStyle(.omlx(.primary))
.disabled(!vm.hasPendingMCPChanges)
}
- .padding(.horizontal, 18)
- .padding(.top, 6)
}
}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/LogsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/LogsScreen.swift
index 5b6478728c..fb32b41e90 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/LogsScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/LogsScreen.swift
@@ -32,7 +32,7 @@ struct LogsScreen: View {
isLast: true) {
Popup(
selection: $vm.selectedFile,
- width: 220,
+ width: .controlMedium,
options: vm.fileOptions
)
}
@@ -45,13 +45,7 @@ struct LogsScreen: View {
.padding(.bottom, 8)
.frame(maxWidth: .infinity, maxHeight: .infinity)
- if let error = vm.lastError {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(.red)
- .padding(.horizontal, 18)
- .padding(.top, 4)
- }
+ FooterBar(error: vm.lastError)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
.toolbar {
@@ -95,7 +89,7 @@ struct LogsScreen: View {
Popup(
selection: $vm.lines,
- width: 110,
+ width: .controlCompact,
options: lineOptions
)
}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/ModelCardSheet.swift b/apps/omlx-mac/Sources/AppView/Screens/ModelCardSheet.swift
index 2a8e6c4e78..f0d585442d 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/ModelCardSheet.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/ModelCardSheet.swift
@@ -491,7 +491,7 @@ struct ModelCardSheet: View {
.keyboardShortcut(.defaultAction)
}
}
- .padding(.horizontal, 18)
+ .padding(.horizontal, 20)
.padding(.vertical, 12)
}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/ModelSettingsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ModelSettingsScreen.swift
index 52154a9d34..886e03d632 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/ModelSettingsScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/ModelSettingsScreen.swift
@@ -53,13 +53,7 @@ struct ModelSettingsScreen: View {
AdvancedTab(vm: vm, client: services.client)
}
- if let error = vm.lastError {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(.red)
- .padding(.horizontal, 18)
- .padding(.top, 8)
- }
+ FooterBar(error: vm.lastError)
}
.toolbar {
ToolbarItem(placement: .navigation) {
@@ -514,7 +508,7 @@ private struct BasicTab: View {
sublabel: String(localized: "settings.basic.alias.sub",
defaultValue: "Falls back to the model id",
comment: "Sublabel for the model alias field")) {
- TextInput(text: $vm.alias, placeholder: vm.modelID, mono: true, width: 220)
+ TextInput(text: $vm.alias, placeholder: vm.modelID, mono: true, width: .controlMedium)
.onSubmit { Task { await vm.save(.alias, client: client) } }
}
Row(label: String(localized: "settings.basic.model_type.label",
@@ -522,7 +516,7 @@ private struct BasicTab: View {
comment: "Row label for the model type override popup")) {
Popup(
selection: vm.bind($vm.modelTypeOverride, save: { Task { await vm.save(.modelType, client: client) } }),
- width: 170,
+ width: .controlMedium,
options: ModelSettingsScreenVM.modelTypeOptions
)
}
@@ -532,7 +526,7 @@ private struct BasicTab: View {
sublabel: String(localized: "settings.basic.context_window.sub",
defaultValue: "Maximum tokens per request",
comment: "Sublabel for the context window field")) {
- TextInput(text: vm.bindProfile($vm.contextLength), mono: true, suffix: "tk", width: 110)
+ TextInput(text: vm.bindProfile($vm.contextLength), mono: true, suffix: "tk", width: .controlCompact)
}
Row(label: String(localized: "settings.basic.max_tokens.label",
defaultValue: "Max Tokens",
@@ -544,7 +538,7 @@ private struct BasicTab: View {
placeholder: String(localized: "settings.basic.max_tokens.placeholder",
defaultValue: "Default",
comment: "Placeholder shown when Max Tokens is empty (server default applies)"),
- mono: true, width: 110)
+ mono: true, width: .controlCompact)
}
Row(label: String(localized: "settings.basic.temperature.label",
defaultValue: "Temperature",
@@ -552,7 +546,7 @@ private struct BasicTab: View {
sublabel: String(localized: "settings.basic.temperature.sub",
defaultValue: "Sampling randomness (≥ 0). 0 = deterministic.",
comment: "Sublabel describing the temperature field range")) {
- TextInput(text: vm.bindProfile($vm.temperature), placeholder: "0.7", mono: true, width: 90)
+ TextInput(text: vm.bindProfile($vm.temperature), placeholder: "0.7", mono: true, width: .controlNarrow)
}
if !vm.isDiffusionModel {
Row(label: String(localized: "settings.basic.top_p.label",
@@ -561,7 +555,7 @@ private struct BasicTab: View {
sublabel: String(localized: "settings.basic.top_p.sub",
defaultValue: "Nucleus sampling cutoff (0 < p ≤ 1).",
comment: "Sublabel describing the top-p valid range")) {
- TextInput(text: vm.bindProfile($vm.topP), mono: true, width: 90)
+ TextInput(text: vm.bindProfile($vm.topP), mono: true, width: .controlNarrow)
}
Row(label: String(localized: "settings.basic.top_k.label",
defaultValue: "Top K",
@@ -569,7 +563,7 @@ private struct BasicTab: View {
sublabel: String(localized: "settings.basic.top_k.sub",
defaultValue: "Limit candidates to top K (positive integer).",
comment: "Sublabel describing the top-k field")) {
- TextInput(text: vm.bindProfile($vm.topK), mono: true, width: 90)
+ TextInput(text: vm.bindProfile($vm.topK), mono: true, width: .controlNarrow)
}
Row(label: String(localized: "settings.basic.min_p.label",
defaultValue: "Min P",
@@ -577,7 +571,7 @@ private struct BasicTab: View {
sublabel: String(localized: "settings.basic.min_p.sub",
defaultValue: "Minimum probability floor (0 ≤ p ≤ 1).",
comment: "Sublabel describing the min-p field range")) {
- TextInput(text: vm.bindProfile($vm.minP), mono: true, width: 90)
+ TextInput(text: vm.bindProfile($vm.minP), mono: true, width: .controlNarrow)
}
Row(label: String(localized: "settings.basic.repetition_penalty.label",
defaultValue: "Repetition Penalty",
@@ -587,7 +581,7 @@ private struct BasicTab: View {
: String(localized: "settings.basic.repetition_penalty.sub",
defaultValue: "Penalize repeated tokens (−2 to 2).",
comment: "Sublabel describing repetition-penalty range")) {
- TextInput(text: vm.bindProfile($vm.repetitionPenalty), mono: true, width: 90)
+ TextInput(text: vm.bindProfile($vm.repetitionPenalty), mono: true, width: .controlNarrow)
.disabled(vm.vlmMtpEnabled)
.help(vm.vlmMtpEnabled ? vm.vlmMtpProcessorLockedReason : "")
}
@@ -599,7 +593,7 @@ private struct BasicTab: View {
: String(localized: "settings.basic.presence_penalty.sub",
defaultValue: "Penalize tokens already present (−2 to 2).",
comment: "Sublabel describing presence-penalty range")) {
- TextInput(text: vm.bindProfile($vm.presencePenalty), mono: true, width: 90)
+ TextInput(text: vm.bindProfile($vm.presencePenalty), mono: true, width: .controlNarrow)
.disabled(vm.vlmMtpEnabled)
.help(vm.vlmMtpEnabled ? vm.vlmMtpProcessorLockedReason : "")
}
@@ -617,7 +611,7 @@ private struct BasicTab: View {
placeholder: String(localized: "settings.basic.ttl.placeholder",
defaultValue: "No TTL",
comment: "Placeholder shown when no TTL is configured"),
- mono: true, suffix: "s", width: 110)
+ mono: true, suffix: "s", width: .controlCompact)
.onSubmit { Task { await vm.save(.ttl, client: client) } }
}
}
@@ -708,8 +702,29 @@ private struct AdvancedTab: View {
sublabel: String(localized: "settings.advanced.enable_thinking.sub",
defaultValue: "Enable reasoning/thinking mode for this model",
comment: "Sublabel for the enable-thinking toggle")) {
- Toggle("", isOn: vm.bindProfile($vm.enableThinking))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.enableThinking))
+ }
+ if vm.isQwen4Exp && vm.qwen4PleSsdOffloadSupported {
+ Row(label: String(localized: "settings.advanced.qwen4_ssd_offload.label",
+ defaultValue: "SSD N-gram Offload (Qwen4 only)",
+ comment: "Row label for the Qwen4 PLE SSD mmap toggle"),
+ sublabel: vm.qwen4PleSsdOffloadForced
+ ? String(localized: "settings.advanced.qwen4_ssd_offload.forced",
+ defaultValue: "Required because resident loading exceeds the configured model-memory limit.",
+ comment: "Sublabel when Qwen4 PLE SSD offload is forced by memory limits")
+ : String(localized: "settings.advanced.qwen4_ssd_offload.sub",
+ defaultValue: "Keep the PLE N-gram table on SSD to save memory. Prefill can be slower after context changes.",
+ comment: "Sublabel for the Qwen4 PLE SSD mmap toggle")) {
+ RowSwitch(isOn: vm.bind(
+ $vm.qwen4PleSsdOffload,
+ save: {
+ Task {
+ await vm.save(.qwen4PleSsdOffload, client: client)
+ }
+ }
+ ))
+ .disabled(vm.qwen4PleSsdOffloadForced)
+ }
}
Row(label: String(localized: "settings.advanced.thinking_budget.label",
defaultValue: "Thinking Budget",
@@ -720,10 +735,9 @@ private struct AdvancedTab: View {
HStack(spacing: 8) {
if vm.thinkingBudgetEnabled {
TextInput(text: vm.bindProfile($vm.thinkingBudgetTokens),
- mono: true, suffix: "tk", width: 110)
+ mono: true, suffix: "tk", width: .controlCompact)
}
- Toggle("", isOn: vm.bindProfile($vm.thinkingBudgetEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.thinkingBudgetEnabled))
}
}
Row(label: String(localized: "settings.advanced.tool_result_limit.label",
@@ -736,10 +750,9 @@ private struct AdvancedTab: View {
if vm.limitToolResults {
TextInput(text: vm.bindProfile($vm.toolResultLimitTokens),
placeholder: "4096",
- mono: true, suffix: "tk", width: 110)
+ mono: true, suffix: "tk", width: .controlCompact)
}
- Toggle("", isOn: vm.bindProfile($vm.limitToolResults))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.limitToolResults))
}
}
Row(label: String(localized: "settings.advanced.force_sampling.label",
@@ -748,8 +761,7 @@ private struct AdvancedTab: View {
sublabel: String(localized: "settings.advanced.force_sampling.sub",
defaultValue: "Override request sampling parameters with configured values",
comment: "Sublabel for the force-sampling toggle")) {
- Toggle("", isOn: vm.bindProfile($vm.forceSampling))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.forceSampling))
}
Row(label: String(localized: "settings.advanced.reasoning_parser.label",
defaultValue: "Reasoning Parser",
@@ -758,7 +770,7 @@ private struct AdvancedTab: View {
defaultValue: "Override the chain-of-thought parser. Leave empty to use the model's default.",
comment: "Sublabel for the reasoning-parser override field")) {
TextInput(text: vm.bindProfile($vm.reasoningParser),
- placeholder: "auto", mono: true, width: 150)
+ placeholder: "auto", mono: true, width: .controlCompact)
}
}
Row(label: String(localized: "settings.advanced.pin_memory.label",
@@ -767,10 +779,9 @@ private struct AdvancedTab: View {
sublabel: String(localized: "settings.advanced.pin_memory.sub",
defaultValue: "Keep this model resident between requests",
comment: "Sublabel for the pin-in-memory toggle")) {
- Toggle("", isOn: vm.bind($vm.isPinned, save: {
+ RowSwitch(isOn: vm.bind($vm.isPinned, save: {
Task { await vm.save(.isPinned, client: client) }
}))
- .labelsHidden().toggleStyle(.switch)
}
Row(label: String(localized: "settings.advanced.favorite.label",
defaultValue: "Favorite",
@@ -778,10 +789,9 @@ private struct AdvancedTab: View {
sublabel: String(localized: "settings.advanced.favorite.sub",
defaultValue: "List this model first in model lists",
comment: "Sublabel for the favorite toggle")) {
- Toggle("", isOn: vm.bind($vm.isFavorite, save: {
+ RowSwitch(isOn: vm.bind($vm.isFavorite, save: {
Task { await vm.save(.isFavorite, client: client) }
}))
- .labelsHidden().toggleStyle(.switch)
}
// Security-sensitive row — flagged red to match the HTML
// editor's visual treatment. HF custom-code execution gives
@@ -794,10 +804,9 @@ private struct AdvancedTab: View {
defaultValue: "Execute HuggingFace custom model code. Only enable for models you trust. Per-model only — never inherited from profiles.",
comment: "Sublabel describing the security implications of trust-remote-code"),
isLast: true) {
- Toggle("", isOn: vm.bind($vm.trustRemoteCode, save: {
+ RowSwitch(isOn: vm.bind($vm.trustRemoteCode, save: {
Task { await vm.save(.trustRemoteCode, client: client) }
}))
- .labelsHidden().toggleStyle(.switch)
.tint(theme.redDot)
}
}
@@ -914,7 +923,7 @@ private struct EntryEditor: View {
let client: OMLXClient
let entryID: UUID
- private static let reasoningEffortValueWidth: CGFloat = 130
+ private static let reasoningEffortValueWidth: CGFloat = .controlCompact
@Environment(\.omlxTheme) private var theme
@@ -985,7 +994,7 @@ private struct EntryEditor: View {
HStack(spacing: 8) {
Popup(
selection: vm.bindProfile(binding.value),
- width: 130,
+ width: .controlCompact,
options: [("true", "true"), ("false", "false")]
)
forceCheckbox
@@ -1052,7 +1061,6 @@ private struct EntryEditor: View {
Popup(
selection: vm.bindProfile(binding.value),
width: Self.reasoningEffortValueWidth,
- fillsWidth: true,
options: ChatTemplateKwargsCodec.reasoningEffortPresets.map {
($0, $0)
}
@@ -1091,8 +1099,7 @@ private struct AccelerationSection: View {
comment: "Row label for the Lightning MTP toggle"),
sublabel: mtpSublabel,
isLast: true) {
- Toggle("", isOn: vm.bindProfile($vm.mtpEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.mtpEnabled))
.disabled(mtpToggleDisabled)
.help(vm.mtpConflictReason ?? vm.model?.mtpCompatibilityReason ?? "")
}
@@ -1138,8 +1145,7 @@ private struct ExperimentalSection: View {
sublabel: String(localized: "settings.experimental.qwen_ane.sub",
defaultValue: "Split fixed-shape Qwen 3.5/3.6/3.8 prompt processing across both ANEs and the GPU. Experimental private API; takes effect after the model reloads.",
comment: "Sublabel describing Qwen ANE/GPU prefill acceleration")) {
- Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillEnabled))
}
Row(label: String(localized: "settings.experimental.qwen_ane.tuner.label",
defaultValue: "Tune ANE Split",
@@ -1267,7 +1273,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillSequenceLength),
placeholder: "2048", mono: true,
isNumeric: true, range: 1024...262_144,
- step: 64, width: 190)
+ step: 64, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.qwen_ane.tail_padding.label",
defaultValue: "Pad Intermediate Tails From",
@@ -1278,7 +1284,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillTailPaddingMinTokens),
placeholder: "0", mono: true,
isNumeric: true, range: 0...262_143,
- step: 1, width: 190)
+ step: 1, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.qwen_ane.mlp_fraction.label",
defaultValue: "MLP on ANE",
@@ -1289,7 +1295,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillFraction),
placeholder: "0.53", mono: true,
isNumeric: true, range: 0.05...0.90,
- step: 0.005, width: 190)
+ step: 0.005, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.qwen_ane.mlp_layers.label",
defaultValue: "MLP Layer Limit",
@@ -1300,7 +1306,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillMaxLayers),
placeholder: "64", mono: true,
isNumeric: true, range: 1...256,
- step: 1, width: 190)
+ step: 1, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.qwen_ane.dual.label",
defaultValue: "Use Both ANEs",
@@ -1308,8 +1314,7 @@ private struct ExperimentalSection: View {
sublabel: String(localized: "settings.experimental.qwen_ane.dual.sub",
defaultValue: "Pin one resident procedure bank to each physical ANE. Recommended on M3 Ultra.",
comment: "Sublabel describing dual-ANE Qwen prefill")) {
- Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillDualAne))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillDualAne))
}
Row(label: String(localized: "settings.experimental.qwen_ane.cpu.label",
defaultValue: "Share MLP Work with CPU",
@@ -1317,8 +1322,7 @@ private struct ExperimentalSection: View {
sublabel: String(localized: "settings.experimental.qwen_ane.cpu.sub",
defaultValue: "Requires a separate q4 checkpoint clone whose floating tensors are FP16. Retune the ANE MLP share when enabled.",
comment: "Constraint and tuning guidance for Qwen CPU prefill sharing")) {
- Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillCpuEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillCpuEnabled))
}
if vm.qwen35AnePrefillCpuEnabled {
Row(label: String(localized: "settings.experimental.qwen_ane.cpu_fraction.label",
@@ -1330,7 +1334,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillCpuFraction),
placeholder: "0.135", mono: true,
isNumeric: true, range: 0...0.25,
- step: 0.005, width: 190)
+ step: 0.005, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.qwen_ane.cpu_threads.label",
defaultValue: "CPU Workers",
@@ -1341,7 +1345,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillCpuThreads),
placeholder: "8", mono: true,
isNumeric: true, range: 0...64,
- step: 1, width: 190)
+ step: 1, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.qwen_ane.cpu_down_fraction.label",
defaultValue: "Down Projection on CPU",
@@ -1352,7 +1356,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillCpuDownFraction),
placeholder: "0", mono: true,
isNumeric: true, range: 0...0.50,
- step: 0.005, width: 190)
+ step: 0.005, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.qwen_ane.cpu_gdn_fraction.label",
defaultValue: "GDN on CPU",
@@ -1363,7 +1367,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillCpuGdnFraction),
placeholder: "0", mono: true,
isNumeric: true, range: 0...0.50,
- step: 0.005, width: 190)
+ step: 0.005, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.qwen_ane.cpu_scheduler.label",
defaultValue: "Performance-Aware Scheduling",
@@ -1371,8 +1375,7 @@ private struct ExperimentalSection: View {
sublabel: String(localized: "settings.experimental.qwen_ane.cpu_scheduler.sub",
defaultValue: "Distributes independent CPU shards across processor clusters and falls back automatically when unsupported.",
comment: "Sublabel explaining performance-aware CPU scheduling")) {
- Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillCpuSharedResource))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillCpuSharedResource))
}
}
Row(label: String(localized: "settings.experimental.qwen_ane.gdn.label",
@@ -1381,8 +1384,7 @@ private struct ExperimentalSection: View {
sublabel: String(localized: "settings.experimental.qwen_ane.gdn.sub",
defaultValue: "Also split eligible GDN z+qkv input projections across ANE and GPU.",
comment: "Sublabel describing Qwen GDN ANE acceleration")) {
- Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillGdn))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillGdn))
}
if vm.qwen35AnePrefillGdn {
Row(label: String(localized: "settings.experimental.qwen_ane.gdn_fraction.label",
@@ -1394,7 +1396,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillGdnFraction),
placeholder: "0.5", mono: true,
isNumeric: true, range: 0.05...0.90,
- step: 0.005, width: 190)
+ step: 0.005, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.qwen_ane.gdn_layers.label",
defaultValue: "GDN Layer Limit",
@@ -1405,7 +1407,7 @@ private struct ExperimentalSection: View {
TextInput(text: vm.bindProfile($vm.qwen35AnePrefillGdnMaxLayers),
placeholder: "48", mono: true,
isNumeric: true, range: 0...256,
- step: 1, width: 190)
+ step: 1, width: .controlCompact)
}
}
}
@@ -1420,12 +1422,11 @@ private struct ExperimentalSection: View {
if vm.turboquantKvEnabled {
Popup(
selection: vm.bindProfile($vm.turboquantKvBits),
- width: 120,
+ width: .controlCompact,
options: ModelSettingsScreenVM.turboquantKvBitsOptions
)
}
- Toggle("", isOn: vm.bindProfile($vm.turboquantKvEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.turboquantKvEnabled))
.disabled(vm.vlmMtpEnabled)
.help(vm.vlmMtpEnabled ? vlmMtpOwnsSpeculativePathReason : "")
}
@@ -1443,10 +1444,9 @@ private struct ExperimentalSection: View {
HStack(spacing: 8) {
if vm.indexCacheEnabled {
TextInput(text: vm.bindProfile($vm.indexCacheFreq),
- placeholder: "4", mono: true, width: 80)
+ placeholder: "4", mono: true, width: .controlNarrow)
}
- Toggle("", isOn: vm.bindProfile($vm.indexCacheEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.indexCacheEnabled))
}
}
}
@@ -1456,8 +1456,7 @@ private struct ExperimentalSection: View {
defaultValue: "SpecPrefill",
comment: "Row label for the SpecPrefill toggle"),
sublabel: specprefillSublabel) {
- Toggle("", isOn: vm.bindProfile($vm.specprefillEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.specprefillEnabled))
.disabled(vm.vlmMtpEnabled)
.help(vm.vlmMtpEnabled ? vlmMtpOwnsSpeculativePathReason : "")
}
@@ -1470,7 +1469,7 @@ private struct ExperimentalSection: View {
comment: "Sublabel for the SpecPrefill draft-model picker")) {
Popup(
selection: vm.bindProfile($vm.specprefillDraftModel),
- width: 260,
+ width: .controlWide,
options: vm.draftModelOptions()
)
}
@@ -1479,7 +1478,7 @@ private struct ExperimentalSection: View {
comment: "Row label for the SpecPrefill keep-rate dropdown")) {
Popup(
selection: vm.bindProfile($vm.specprefillKeepPct),
- width: 320,
+ width: .controlWide,
options: ModelSettingsScreenVM.specprefillKeepPctOptions
)
}
@@ -1490,7 +1489,7 @@ private struct ExperimentalSection: View {
defaultValue: "Min prompt tokens to trigger (shorter prompts use full prefill).",
comment: "Sublabel for the SpecPrefill threshold field")) {
TextInput(text: vm.bindProfile($vm.specprefillThreshold),
- placeholder: "8192", mono: true, suffix: "tk", width: 110)
+ placeholder: "8192", mono: true, suffix: "tk", width: .controlCompact)
}
}
@@ -1499,8 +1498,7 @@ private struct ExperimentalSection: View {
defaultValue: "DFlash",
comment: "Row label for the DFlash toggle"),
sublabel: dflashSublabel) {
- Toggle("", isOn: vm.bindProfile($vm.dflashEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.dflashEnabled))
.disabled(dflashToggleDisabled)
.help(dflashHelp)
}
@@ -1510,7 +1508,7 @@ private struct ExperimentalSection: View {
comment: "Row label for the DFlash draft-model picker")) {
Popup(
selection: vm.bindProfile($vm.dflashDraftModel),
- width: 260,
+ width: .controlWide,
options: vm.draftModelOptions()
)
}
@@ -1520,8 +1518,7 @@ private struct ExperimentalSection: View {
sublabel: String(localized: "settings.experimental.dflash.draft_quant.sub",
defaultValue: "Enable quantization for the draft model (weight, activation bits & group size).",
comment: "Sublabel for the DFlash draft quantization toggle")) {
- Toggle("", isOn: vm.bindProfile($vm.dflashDraftQuantEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.dflashDraftQuantEnabled))
}
if vm.dflashDraftQuantEnabled {
Row(label: String(localized: "settings.experimental.dflash.draft_quant_weight.label",
@@ -1529,7 +1526,7 @@ private struct ExperimentalSection: View {
comment: "Row label for the DFlash draft quantization weight bits picker")) {
Popup(
selection: vm.bindProfile($vm.dflashDraftQuantWeightBits),
- width: 110,
+ width: .controlCompact,
options: ModelSettingsScreenVM.dflashDraftQuantWeightBitsOptions
)
}
@@ -1538,7 +1535,7 @@ private struct ExperimentalSection: View {
comment: "Row label for the DFlash draft quantization activation bits picker")) {
Popup(
selection: vm.bindProfile($vm.dflashDraftQuantActivationBits),
- width: 110,
+ width: .controlCompact,
options: ModelSettingsScreenVM.dflashDraftQuantActivationBitsOptions
)
}
@@ -1547,7 +1544,7 @@ private struct ExperimentalSection: View {
comment: "Row label for the DFlash draft quantization group size picker")) {
Popup(
selection: vm.bindProfile($vm.dflashDraftQuantGroupSize),
- width: 110,
+ width: .controlCompact,
options: ModelSettingsScreenVM.dflashDraftQuantGroupSizeOptions
)
}
@@ -1562,7 +1559,7 @@ private struct ExperimentalSection: View {
placeholder: String(localized: "settings.experimental.dflash.max_ctx.placeholder",
defaultValue: "unlimited",
comment: "Placeholder shown when DFlash max-context is unset (no cap)"),
- mono: true, suffix: "tk", width: 130)
+ mono: true, suffix: "tk", width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.dflash.verify_mode.label",
defaultValue: "Verify Mode",
@@ -1572,7 +1569,7 @@ private struct ExperimentalSection: View {
comment: "Sublabel for the DFlash verify mode picker")) {
Popup(
selection: vm.bindProfile($vm.dflashVerifyMode),
- width: 140,
+ width: .controlMedium,
options: ModelSettingsScreenVM.dflashVerifyModeOptions
)
}
@@ -1583,7 +1580,7 @@ private struct ExperimentalSection: View {
defaultValue: "Draft model sliding-attention window. Empty = dflash default (2048).",
comment: "Sublabel for the DFlash draft window size field")) {
TextInput(text: vm.bindProfile($vm.dflashDraftWindowSize),
- placeholder: "2048", mono: true, width: 110)
+ placeholder: "2048", mono: true, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.dflash.sink_size.label",
defaultValue: "Draft Sink Size",
@@ -1592,7 +1589,7 @@ private struct ExperimentalSection: View {
defaultValue: "Attention-sink tokens always kept in the window. Empty = dflash default (0).",
comment: "Sublabel for the DFlash draft sink size field")) {
TextInput(text: vm.bindProfile($vm.dflashDraftSinkSize),
- placeholder: "0", mono: true, width: 110)
+ placeholder: "0", mono: true, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.dflash.block_size.label",
defaultValue: "Runtime Block Size",
@@ -1601,7 +1598,7 @@ private struct ExperimentalSection: View {
defaultValue: "Maximum draft and verify tokens per cycle. Empty = checkpoint default.",
comment: "Sublabel for the DFlash runtime block size field")) {
TextInput(text: vm.bindProfile($vm.dflashBlockSize),
- placeholder: "checkpoint", mono: true, width: 110)
+ placeholder: "checkpoint", mono: true, width: .controlCompact)
}
Row(label: String(localized: "settings.experimental.dflash.mem_cache.label",
defaultValue: "DFlash in-memory cache",
@@ -1612,10 +1609,9 @@ private struct ExperimentalSection: View {
HStack(spacing: 8) {
if vm.dflashInMemoryCache {
TextInput(text: vm.bindProfile($vm.dflashInMemoryCacheGib),
- placeholder: "8", mono: true, suffix: "GiB", width: 110)
+ placeholder: "8", mono: true, suffix: "GiB", width: .controlCompact)
}
- Toggle("", isOn: vm.bindProfile($vm.dflashInMemoryCache))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.dflashInMemoryCache))
}
}
if vm.dflashInMemoryCache {
@@ -1626,15 +1622,14 @@ private struct ExperimentalSection: View {
defaultValue: "Maximum prefix snapshots kept in RAM. Each entry stores KV + draft GDN state.",
comment: "Sublabel for the DFlash L1 cache max entries field")) {
TextInput(text: vm.bindProfile($vm.dflashInMemoryCacheMaxEntries),
- placeholder: "4", mono: true, width: 110)
+ placeholder: "4", mono: true, width: .controlCompact)
}
}
Row(label: String(localized: "settings.experimental.dflash.ssd_cache.label",
defaultValue: "DFlash SSD cache",
comment: "Row label for the DFlash L2 SSD cache toggle"),
sublabel: dflashSsdSublabel) {
- Toggle("", isOn: vm.bindProfile($vm.dflashSsdCache))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.dflashSsdCache))
.disabled(!(vm.model?.dflashSsdCacheAvailable ?? false) || !vm.dflashInMemoryCache)
}
if vm.dflashSsdCache && (vm.model?.dflashSsdCacheAvailable ?? false) {
@@ -1645,7 +1640,7 @@ private struct ExperimentalSection: View {
defaultValue: "Disk budget for L2 spill; oldest entries are evicted when exceeded.",
comment: "Sublabel for the DFlash SSD cache size field")) {
TextInput(text: vm.bindProfile($vm.dflashSsdCacheGib),
- placeholder: "20", mono: true, suffix: "GiB", width: 110)
+ placeholder: "20", mono: true, suffix: "GiB", width: .controlCompact)
}
}
}
@@ -1657,8 +1652,7 @@ private struct ExperimentalSection: View {
comment: "Row label for the VLM MTP toggle"),
sublabel: vlmMtpSublabel,
isLast: !vm.vlmMtpEnabled) {
- Toggle("", isOn: vm.bindProfile($vm.vlmMtpEnabled))
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: vm.bindProfile($vm.vlmMtpEnabled))
.disabled(vlmMtpToggleDisabled)
.help(vm.vlmMtpConflictReason ?? "")
}
@@ -1671,7 +1665,7 @@ private struct ExperimentalSection: View {
comment: "Sublabel for the VLM MTP draft-model picker")) {
Popup(
selection: vm.bindProfile($vm.vlmMtpDraftModel),
- width: 260,
+ width: .controlWide,
options: vm.vlmMtpDraftModelOptions()
)
}
@@ -1683,7 +1677,7 @@ private struct ExperimentalSection: View {
comment: "Sublabel for the VLM MTP draft block-size field"),
isLast: true) {
TextInput(text: vm.bindProfile($vm.vlmMtpDraftBlockSize),
- placeholder: "4", mono: true, width: 80)
+ placeholder: "4", mono: true, width: .controlNarrow)
}
}
}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/ModelsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ModelsScreen.swift
index 91f551ac77..98fa75cc62 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/ModelsScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/ModelsScreen.swift
@@ -34,13 +34,7 @@ struct ModelsScreen: View {
onToggleFavorite: { id, fav in vm.setFavorite(id: id, favorite: fav, client: services.client) }
)
- if let error = vm.lastError {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(.red)
- .padding(.horizontal, 18)
- .padding(.top, 8)
- }
+ FooterBar(error: vm.lastError)
}
.task { await vm.start(client: services.client) }
.onDisappear { vm.stop() }
diff --git a/apps/omlx-mac/Sources/AppView/Screens/NetworkScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/NetworkScreen.swift
index ba16982fd6..1380c15fa2 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/NetworkScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/NetworkScreen.swift
@@ -25,8 +25,7 @@ struct NetworkScreen: View {
ProxiesSection(vm: vm)
TLSSection(vm: vm)
- HStack {
- Spacer()
+ FooterBar(error: vm.lastError) {
Button(String(localized: "network.button.apply",
defaultValue: "Apply",
comment: "Footer button on the Network screen that commits the edited proxy/TLS values to the server")) {
@@ -35,10 +34,6 @@ struct NetworkScreen: View {
.buttonStyle(.omlx(.primary))
.disabled(!vm.hasPendingChanges || vm.isSaving)
}
- .padding(.horizontal, 18)
- .padding(.top, 6)
-
- HintFooter(error: vm.lastError)
}
.task { await vm.load(client: services.client) }
}
@@ -67,7 +62,7 @@ private struct ProxiesSection: View {
text: $vm.httpProxy,
placeholder: "http://proxy.local:8080",
mono: true,
- width: 320
+ width: .controlWide
)
}
Row(label: String(localized: "network.row.https_proxy.label",
@@ -77,7 +72,7 @@ private struct ProxiesSection: View {
text: $vm.httpsProxy,
placeholder: "http://proxy.local:8080",
mono: true,
- width: 320
+ width: .controlWide
)
}
Row(
@@ -93,7 +88,7 @@ private struct ProxiesSection: View {
text: $vm.noProxy,
placeholder: "localhost,127.0.0.1,*.internal",
mono: true,
- width: 320
+ width: .controlWide
)
}
}
@@ -129,25 +124,11 @@ private struct TLSSection: View {
text: $vm.caBundle,
placeholder: "/etc/ssl/certs/ca-bundle.pem",
mono: true,
- width: 320
+ width: .controlWide
)
}
}
}
}
-// MARK: - Hint footer
-
-private struct HintFooter: View {
- let error: String?
- var body: some View {
- if let error {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(.red)
- .padding(.horizontal, 18)
- .padding(.top, 8)
- }
- }
-}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/PerformanceScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/PerformanceScreen.swift
index 586f96e6f9..bbc4a4cabd 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/PerformanceScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/PerformanceScreen.swift
@@ -27,8 +27,7 @@ struct PerformanceScreen: View {
MemoryLifecycleSection(vm: vm)
CacheSection(vm: vm)
- HStack {
- Spacer()
+ FooterBar(error: vm.lastError) {
Button(String(localized: "performance.button.apply",
defaultValue: "Apply",
comment: "Apply button at the bottom of the Performance screen")) {
@@ -37,16 +36,6 @@ struct PerformanceScreen: View {
.buttonStyle(.omlx(.primary))
.disabled(!vm.hasPendingChanges || vm.isSaving)
}
- .padding(.horizontal, 18)
- .padding(.top, 6)
-
- if let error = vm.lastError {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(.red)
- .padding(.horizontal, 18)
- .padding(.top, 8)
- }
}
.task { await vm.load(client: services.client) }
}
@@ -76,7 +65,7 @@ private struct SchedulerSection: View {
defaultValue: "Cap on simultaneous /v1 requests.",
comment: "Sublabel for max concurrent requests")
) {
- TextInput(text: $vm.maxConcurrentText, mono: true, width: 90)
+ TextInput(text: $vm.maxConcurrentText, mono: true, width: .controlNarrow)
}
Row(
label: String(localized: "performance.scheduler.embedding_batch_size",
@@ -86,7 +75,7 @@ private struct SchedulerSection: View {
defaultValue: "Max input texts per embedding forward pass.",
comment: "Sublabel for embedding batch size")
) {
- TextInput(text: $vm.embeddingBatchSizeText, mono: true, width: 90)
+ TextInput(text: $vm.embeddingBatchSizeText, mono: true, width: .controlNarrow)
}
Row(
label: String(localized: "performance.scheduler.chunked_prefill",
@@ -96,8 +85,7 @@ private struct SchedulerSection: View {
defaultValue: "Split long prompts across scheduler ticks so other requests can interleave.",
comment: "Sublabel for chunked prefill toggle")
) {
- Toggle("", isOn: $vm.chunkedPrefill)
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $vm.chunkedPrefill)
}
Row(
label: String(localized: "performance.scheduler.prefill_priority",
@@ -122,7 +110,6 @@ private struct SchedulerSection: View {
],
icons: ["arrow.up.left.and.arrow.down.right", "speedometer"]
)
- .frame(width: 240)
}
}
}
@@ -153,8 +140,7 @@ private struct MemoryLifecycleSection: View {
defaultValue: "Preflight prefill memory before kicking the engine and defer generation scheduling near the ceiling.",
comment: "Sublabel for prefill memory guard")
) {
- Toggle("", isOn: $vm.prefillMemoryGuard)
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $vm.prefillMemoryGuard)
}
Row(
label: String(localized: "performance.memory.guard_tier",
@@ -164,7 +150,7 @@ private struct MemoryLifecycleSection: View {
) {
Popup(
selection: $vm.memoryGuardTier,
- width: 150,
+ width: .controlMedium,
options: [
("safe",
String(localized: "performance.memory.guard_tier.safe",
@@ -202,7 +188,7 @@ private struct MemoryLifecycleSection: View {
comment: "Placeholder for custom memory guard ceiling"),
mono: true,
suffix: "GB",
- width: 110
+ width: .controlCompact
)
}
}
@@ -224,7 +210,7 @@ private struct MemoryLifecycleSection: View {
comment: "Placeholder text for the idle timeout field when disabled"),
mono: true,
suffix: "s",
- width: 110
+ width: .controlCompact
)
}
Row(
@@ -236,8 +222,7 @@ private struct MemoryLifecycleSection: View {
comment: "Sublabel for model fallback toggle"),
isLast: true
) {
- Toggle("", isOn: $vm.modelFallback)
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $vm.modelFallback)
}
}
}
@@ -307,8 +292,7 @@ private struct CacheSection: View {
defaultValue: "Master switch for the engine's KV cache subsystem.",
comment: "Sublabel for the master cache enable toggle")
) {
- Toggle("", isOn: $vm.cacheEnabled)
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $vm.cacheEnabled)
}
Row(
label: String(localized: "performance.cache.hot_only",
@@ -318,8 +302,7 @@ private struct CacheSection: View {
defaultValue: "Skip SSD spillover. Useful on fast machines with abundant RAM.",
comment: "Sublabel for hot cache only toggle")
) {
- Toggle("", isOn: $vm.hotCacheOnly)
- .labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $vm.hotCacheOnly)
.disabled(!vm.cacheEnabled)
}
Row(
@@ -334,7 +317,7 @@ private struct CacheSection: View {
text: $vm.hotCacheMaxSize,
placeholder: "0",
mono: true,
- width: 140
+ width: .controlCompact
)
.disabled(!vm.cacheEnabled)
}
@@ -350,7 +333,7 @@ private struct CacheSection: View {
text: $vm.ssdCacheDir,
placeholder: "/cache",
mono: true,
- width: 280
+ width: .controlWide
)
.disabled(!vm.cacheEnabled || vm.hotCacheOnly)
}
@@ -368,7 +351,7 @@ private struct CacheSection: View {
defaultValue: "auto",
comment: "Memory field placeholder meaning automatic"),
mono: true,
- width: 140
+ width: .controlCompact
)
.disabled(!vm.cacheEnabled || vm.hotCacheOnly)
}
@@ -387,7 +370,7 @@ private struct CacheSection: View {
defaultValue: "auto",
comment: "Memory field placeholder meaning automatic"),
mono: true,
- width: 110
+ width: .controlCompact
)
.disabled(!vm.cacheEnabled)
}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/ProfileViews.swift b/apps/omlx-mac/Sources/AppView/Screens/ProfileViews.swift
index 077d8cf347..62becedafb 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/ProfileViews.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/ProfileViews.swift
@@ -324,10 +324,10 @@ struct ActiveProfileBanner: View {
.padding(.vertical, isSlim ? 10 : 12)
.background(bannerBackground)
.overlay(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
+ RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous)
.strokeBorder(bannerBorder, lineWidth: 0.5)
)
- .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
+ .clipShape(RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous))
.padding(.horizontal, 14)
.padding(.bottom, 12)
}
@@ -491,10 +491,10 @@ struct SaveAsPopover: View {
.padding(12)
.background(theme.groupBg)
.overlay(
- RoundedRectangle(cornerRadius: 12, style: .continuous)
+ RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous)
.strokeBorder(theme.groupBorder, lineWidth: 0.5)
)
- .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
+ .clipShape(RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous))
.padding(.horizontal, 14)
.padding(.bottom, 12)
.onAppear { nameFocused = true }
@@ -1067,7 +1067,9 @@ struct ProfileDetailCard: View {
.foregroundStyle(theme.textSecondary)
}
.toggleStyle(.switch)
- .controlSize(.mini)
+ // Same switch size as `RowSwitch` so every switch in the
+ // app reads as one control.
+ .controlSize(.small)
if exposeAsModel, let exposedModelId {
Text(exposedModelId)
.font(.omlxMono(11))
diff --git a/apps/omlx-mac/Sources/AppView/Screens/QuantizationScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/QuantizationScreen.swift
index 8d85271ca7..6f5f465b0a 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/QuantizationScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/QuantizationScreen.swift
@@ -103,7 +103,11 @@ struct QuantizationScreen: View {
MessageBanner(error: vm.lastError, success: vm.lastSuccess)
if vm.modelsLoaded && vm.models.isEmpty {
- EmptyModelsBanner()
+ HintLine(text: String(localized: "quant.empty_models",
+ defaultValue: "No full-precision models found on disk. Download one from the Downloads tab first.",
+ comment: "Banner shown when no full-precision models are available to quantize"))
+ .padding(.horizontal, 14)
+ .padding(.top, 6)
}
QueueSection(
@@ -179,7 +183,7 @@ private struct SourceModelSection: View {
) {
Popup(
selection: $selectedModelPath,
- width: 320,
+ width: .controlWide,
options: modelOptions
)
}
@@ -195,7 +199,7 @@ private struct SourceModelSection: View {
) {
Popup(
selection: $sensitivityModelPath,
- width: 320,
+ width: .controlWide,
options: sensitivityOptions
)
}
@@ -209,7 +213,7 @@ private struct SourceModelSection: View {
comment: "Row sublabel explaining the oQ level tradeoff")) {
Popup(
selection: $oqLevel,
- width: 120,
+ width: .controlCompact,
options: levelOptions
)
}
@@ -308,7 +312,7 @@ private struct EstimateStrip: View {
defaultValue: "Output size: ~\(outputSizeText)",
comment: "Estimate pill: predicted on-disk size of the quantized output. Placeholder is the formatted byte string"))
}
- .padding(.horizontal, 18)
+ .padding(.horizontal, 14)
.padding(.top, 4)
.padding(.bottom, 10)
}
@@ -373,7 +377,7 @@ private struct AdvancedSection: View {
defaultValue: "Exclude vision encoder weights (~2-3% smaller, text-only output)",
comment: "Toggle row sublabel: text-only quantization effect")
) {
- Toggle("", isOn: $textOnly).labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $textOnly)
}
}
@@ -389,9 +393,7 @@ private struct AdvancedSection: View {
defaultValue: "Unavailable — source model has no MTP heads",
comment: "Toggle row sublabel when MTP isn't supported by the chosen source")
) {
- Toggle("", isOn: $preserveMtp)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $preserveMtp)
.disabled(!selectedHasMTP)
}
@@ -446,7 +448,7 @@ private struct EnhancedQuantizationSection: View {
comment: "Toggle sublabel explaining what enabling oQe does"),
isLast: !enabled
) {
- Toggle("", isOn: $enabled).labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $enabled)
}
if enabled {
@@ -458,7 +460,7 @@ private struct EnhancedQuantizationSection: View {
defaultValue: "Use a compatible cached imatrix when available; otherwise collect a new one.",
comment: "Toggle sublabel for the oQe imatrix cache reuse option")
) {
- Toggle("", isOn: $reuseCache).labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $reuseCache)
}
Row(
@@ -475,7 +477,7 @@ private struct EnhancedQuantizationSection: View {
defaultValue: "Automatic",
comment: "Placeholder for an automatically selected oQe imatrix cache path"),
mono: true,
- width: 320
+ width: .controlWide
)
}
@@ -488,36 +490,13 @@ private struct EnhancedQuantizationSection: View {
comment: "Toggle sublabel for strict oQe imatrix coverage"),
isLast: true
) {
- Toggle("", isOn: $strictCoverage).labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $strictCoverage)
}
}
}
}
}
-private struct EmptyModelsBanner: View {
- @Environment(\.omlxTheme) private var theme
-
- var body: some View {
- HStack(spacing: 8) {
- Image(systemName: "info.circle")
- .font(.system(size: 11))
- .foregroundStyle(theme.textTertiary)
- Text(String(localized: "quant.empty_models",
- defaultValue: "No full-precision models found on disk. Download one from the Downloads tab first.",
- comment: "Banner shown when no full-precision models are available to quantize"))
- .font(.omlxText(11.5))
- .foregroundStyle(theme.textSecondary)
- Spacer(minLength: 0)
- }
- .padding(10)
- .background(theme.codeBg)
- .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
- .padding(.horizontal, 18)
- .padding(.top, 6)
- }
-}
-
// MARK: - Queue
private struct QueueSection: View {
@@ -973,7 +952,7 @@ private struct UploadModalView: View {
placeholder: "hf_…",
isSecure: true,
mono: true,
- width: 220
+ width: .controlMedium
)
Button {
Task { await vm.validateUploadToken(client: client) }
@@ -1010,7 +989,7 @@ private struct UploadModalView: View {
) {
Popup(
selection: $vm.uploadNamespace,
- width: 220,
+ width: .controlMedium,
options: namespaceOptions
)
}
@@ -1063,7 +1042,7 @@ private struct UploadModalView: View {
text: $repoName,
placeholder: "model-id",
mono: true,
- width: 240
+ width: .controlMedium
)
}
}
@@ -1077,7 +1056,7 @@ private struct UploadModalView: View {
comment: "Toggle row sublabel explaining the private flag"),
isLast: true
) {
- Toggle("", isOn: $isPrivate).labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $isPrivate)
}
}
}
@@ -1101,7 +1080,7 @@ private struct UploadModalView: View {
) {
Popup(
selection: $readmeSourcePath,
- width: 260,
+ width: .controlWide,
options: readmeOptions
)
}
@@ -1115,7 +1094,7 @@ private struct UploadModalView: View {
comment: "Toggle row sublabel for the re-download notice"),
isLast: true
) {
- Toggle("", isOn: $addRedownloadNotice).labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $addRedownloadNotice)
}
} else {
// Trailing row stays flush even when the toggle is hidden.
diff --git a/apps/omlx-mac/Sources/AppView/Screens/SecurityScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/SecurityScreen.swift
index b525ded717..24a5d8772e 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/SecurityScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/SecurityScreen.swift
@@ -27,13 +27,7 @@ struct SecurityScreen: View {
AuthenticationSection(vm: vm, client: services.client)
SubKeysSection(vm: vm, client: services.client)
- if let error = vm.lastError {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(.red)
- .padding(.horizontal, 18)
- .padding(.top, 8)
- }
+ FooterBar(error: vm.lastError)
}
.task { await vm.load(client: services.client) }
}
@@ -103,7 +97,7 @@ private struct APIKeyEditorRow: View {
comment: "Row label for the API key editor"),
sublabel: sublabel, isLast: true) {
HStack(spacing: 6) {
- TextInput("security.api_key.row_label", text: $draft, placeholder: "sk-omlx-…", isSecure: !showKey, mono: true, width: 260)
+ TextInput("security.api_key.row_label", text: $draft, placeholder: "sk-omlx-…", isSecure: !showKey, mono: true, width: .controlMedium)
.onSubmit { Task { await save() } }
iconButton(systemName: showKey ? "eye.slash" : "eye",
help: showKey
@@ -216,10 +210,9 @@ private struct AuthenticationSection: View {
comment: "Sublabel for the disable API key verification toggle"),
isLast: true
) {
- Toggle("", isOn: vm.bind($vm.skipApiKeyVerification, save: {
+ RowSwitch(isOn: vm.bind($vm.skipApiKeyVerification, save: {
Task { await vm.saveSkipApiKeyVerification(client: client) }
}))
- .labelsHidden().toggleStyle(.switch)
}
}
}
@@ -270,7 +263,7 @@ private struct SubKeysSection: View {
placeholder: String(localized: "security.sub_keys.name_placeholder",
defaultValue: "Claude Code on laptop",
comment: "Placeholder text for sub-key name input"),
- width: 220)
+ width: .controlMedium)
}
Row(label: String(localized: "security.sub_keys.key_label",
defaultValue: "Key",
@@ -280,7 +273,7 @@ private struct SubKeysSection: View {
placeholder: String(localized: "security.sub_keys.key_placeholder",
defaultValue: "sk-omlx-sub-…",
comment: "Placeholder text inside the sub-key value input"),
- mono: true, width: 220)
+ mono: true, width: .controlMedium)
Button {
newKey = APIKeyGenerator.random()
} label: {
diff --git a/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift
index 406c82c487..236e86f083 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift
@@ -27,7 +27,7 @@ struct ServerScreen: View {
comment: "Row label for the listen-address picker in Server screen")) {
Popup(
selection: vm.bind($vm.host, save: { vm.saveHost(services: services) }),
- width: 220,
+ width: .controlMedium,
options: [
("127.0.0.1", String(localized: "server.host.local_only",
defaultValue: "127.0.0.1 (Local only)",
@@ -53,7 +53,7 @@ struct ServerScreen: View {
comment: "Sublabel under the Port field"),
isLast: true
) {
- TextInput(text: $vm.portText, mono: true, width: 90)
+ TextInput(text: $vm.portText, mono: true, width: .controlNarrow)
}
}
@@ -88,11 +88,9 @@ struct ServerScreen: View {
comment: "Sublabel explaining the auto-start on launch setting"),
isLast: true
) {
- Toggle("", isOn: vm.bind($vm.autoStartOnLaunch, save: {
+ RowSwitch(isOn: vm.bind($vm.autoStartOnLaunch, save: {
vm.saveAutoStartOnLaunch(services: services)
}))
- .labelsHidden()
- .toggleStyle(.switch)
}
}
@@ -106,7 +104,7 @@ struct ServerScreen: View {
isLast: true) {
Popup(
selection: vm.bind($vm.logLevel, save: vm.saveLogLevel),
- width: 130,
+ width: .controlCompact,
options: [
("error", String(localized: "server.log_level.error",
defaultValue: "Error",
@@ -145,7 +143,7 @@ struct ServerScreen: View {
defaultValue: "OMLX_BASE_PATH. Files move and the server restarts when this changes.",
comment: "Sublabel under the Base Path field")
) {
- TextInput(text: $vm.basePathText, mono: true, width: 280)
+ TextInput(text: $vm.basePathText, mono: true, width: .controlWide)
}
FreeRow {
ModelDirectoriesEditor(vm: vm)
@@ -159,15 +157,17 @@ struct ServerScreen: View {
comment: "Sublabel for enabling Hugging Face local cache discovery"),
isLast: true
) {
- Toggle("", isOn: $vm.hfCacheEnabled)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $vm.hfCacheEnabled)
}
}
ServerAdvancedSection(vm: vm)
- HStack {
- Spacer()
+ FooterBar(
+ hint: String(localized: "server.footer.hint",
+ defaultValue: "Listen Address, Log Level, and SSE Keep-Alive Mode apply the moment you change them. The rest (port, default profile, storage, aliases) commits when you click Apply. Port and storage changes take effect after a server restart.",
+ comment: "Hint footer text under the Server screen explaining which controls apply immediately vs. via the Apply button"),
+ error: vm.lastError
+ ) {
Button(String(localized: "server.button.apply",
defaultValue: "Apply",
comment: "Button to apply pending server settings: port, default profile, storage, and aliases")) {
@@ -177,10 +177,6 @@ struct ServerScreen: View {
.disabled(!vm.hasPendingServerChanges(services: services)
|| vm.isMovingBasePath)
}
- .padding(.horizontal, 18)
- .padding(.top, 6)
-
- HintFooter(error: vm.lastError)
}
.task {
// services.config is already populated by AppDelegate before this
@@ -253,7 +249,7 @@ private struct ModelDirectoriesEditor: View {
TextInput(text: Binding(
get: { vm.modelDirText(at: index) },
set: { vm.setModelDirText($0, at: index) }
- ), mono: true, width: 340)
+ ), mono: true, width: .controlWide)
Button {
vm.browseModelDirectory(at: index)
@@ -320,7 +316,7 @@ struct ServerHeroCard: View {
// Hero card surface follows the grouped Settings style. Status is
// carried by the pill/actions, not by a colored background wash.
.background(heroBackground)
- .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
+ .clipShape(RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous))
.padding(.horizontal, 14)
.padding(.bottom, 14)
}
@@ -461,7 +457,7 @@ private struct ServerDefaultProfileEditor: View {
sublabel: String(localized: "server.profile.context_window.sub",
defaultValue: "Maximum prompt + completion tokens.",
comment: "Sublabel for the context window field")) {
- TextInput(text: $vm.samplingContextText, mono: true, suffix: "tk", width: 110)
+ TextInput(text: $vm.samplingContextText, mono: true, suffix: "tk", width: .controlCompact)
}
Row(label: String(localized: "server.profile.max_tokens",
defaultValue: "Max Tokens",
@@ -469,7 +465,7 @@ private struct ServerDefaultProfileEditor: View {
sublabel: String(localized: "server.profile.max_tokens.sub",
defaultValue: "Server-wide cap on generated tokens.",
comment: "Sublabel for the max tokens field")) {
- TextInput(text: $vm.samplingMaxTokensText, mono: true, suffix: "tk", width: 110)
+ TextInput(text: $vm.samplingMaxTokensText, mono: true, suffix: "tk", width: .controlCompact)
}
Row(label: String(localized: "server.profile.temperature",
defaultValue: "Temperature",
@@ -477,7 +473,7 @@ private struct ServerDefaultProfileEditor: View {
sublabel: String(localized: "server.profile.temperature.sub",
defaultValue: "Sampling randomness (0–2).",
comment: "Sublabel for the temperature field")) {
- TextInput(text: $vm.samplingTemperatureText, placeholder: "0.7", mono: true, width: 90)
+ TextInput(text: $vm.samplingTemperatureText, placeholder: "0.7", mono: true, width: .controlNarrow)
}
Row(label: String(localized: "server.profile.top_p",
defaultValue: "Top P",
@@ -485,7 +481,7 @@ private struct ServerDefaultProfileEditor: View {
sublabel: String(localized: "server.profile.top_p.sub",
defaultValue: "Nucleus sampling cutoff (0–1).",
comment: "Sublabel for the Top P field")) {
- TextInput(text: $vm.samplingTopPText, mono: true, width: 90)
+ TextInput(text: $vm.samplingTopPText, mono: true, width: .controlNarrow)
}
Row(label: String(localized: "server.profile.top_k",
defaultValue: "Top K",
@@ -493,7 +489,7 @@ private struct ServerDefaultProfileEditor: View {
sublabel: String(localized: "server.profile.top_k.sub",
defaultValue: "Limit candidates to top K. 0 = disabled.",
comment: "Sublabel for the Top K field")) {
- TextInput(text: $vm.samplingTopKText, mono: true, width: 90)
+ TextInput(text: $vm.samplingTopKText, mono: true, width: .controlNarrow)
}
Row(label: String(localized: "server.profile.repetition_penalty",
defaultValue: "Repetition Penalty",
@@ -503,7 +499,7 @@ private struct ServerDefaultProfileEditor: View {
comment: "Sublabel for the repetition penalty field"),
isLast: !expanded
) {
- TextInput(text: $vm.samplingRepetitionPenaltyText, mono: true, width: 90)
+ TextInput(text: $vm.samplingRepetitionPenaltyText, mono: true, width: .controlNarrow)
}
if expanded {
// The remaining design rows aren't server-backed yet —
@@ -640,10 +636,10 @@ private struct APIEndpointsList: View {
// MARK: - Advanced disclosure
/// Phase 4 — Server identity / protocol knobs that the average user never
-/// touches: `server_aliases` (extra host names the server identifies as for
-/// cookie + host-header purposes) and `sse_keepalive_mode`. Hidden behind a
-/// chevron so they don't crowd the main ServerScreen surface, but rendered
-/// inline (not in a popover) so power users can scroll-find them.
+/// touches: request limits, `server_aliases` (extra host names the server
+/// identifies as for cookie + host-header purposes), and SSE keep-alive.
+/// Hidden behind a chevron so they don't crowd the main ServerScreen surface,
+/// but rendered inline (not in a popover) so power users can scroll-find them.
private struct ServerAdvancedSection: View {
@Bindable var vm: ServerScreenVM
@@ -677,12 +673,28 @@ private struct ServerAdvancedSection: View {
.contentShape(Rectangle())
}
.buttonStyle(.plain)
- .padding(.horizontal, 18)
+ // Matches SectionHeader's indent (card gutter + row inset).
+ .padding(.horizontal, 28)
.padding(.top, 22)
.padding(.bottom, 8)
if expanded {
ListGroup {
+ Row(
+ label: String(localized: "server.advanced.max_audio_upload_size",
+ defaultValue: "Maximum Audio Upload Size",
+ comment: "Advanced row label for the audio upload size limit"),
+ sublabel: String(localized: "server.advanced.max_audio_upload_size.sub",
+ defaultValue: "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
+ comment: "Sublabel describing the audio upload size limit")
+ ) {
+ TextInput(
+ text: $vm.maxAudioUploadSizeText,
+ placeholder: "100MB",
+ mono: true,
+ width: .controlCompact
+ )
+ }
Row(
label: String(localized: "server.advanced.sse_keepalive",
defaultValue: "SSE Keep-Alive Mode",
@@ -693,7 +705,7 @@ private struct ServerAdvancedSection: View {
) {
Popup(
selection: vm.bind($vm.sseKeepaliveMode, save: vm.saveSseKeepaliveMode),
- width: 130,
+ width: .controlCompact,
options: [
("chunk", String(localized: "server.advanced.sse_keepalive.chunk",
defaultValue: "Chunk",
@@ -720,7 +732,7 @@ private struct ServerAdvancedSection: View {
text: $vm.serverAliasesText,
placeholder: "omlx.local, oMLX.lan",
mono: true,
- width: 320
+ width: .controlWide
)
}
}
@@ -729,24 +741,4 @@ private struct ServerAdvancedSection: View {
}
}
-// MARK: - Footer hint
-
-private struct HintFooter: View {
- let error: String?
- @Environment(\.omlxTheme) private var theme
- var body: some View {
- VStack(alignment: .leading, spacing: 4) {
- HintLine(text: String(localized: "server.footer.hint",
- defaultValue: "Listen Address, Log Level, and SSE Keep-Alive Mode apply the moment you change them. The rest (port, default profile, storage, aliases) commits when you click Apply. Port and storage changes take effect after a server restart.",
- comment: "Hint footer text under the Server screen explaining which controls apply immediately vs. via the Apply button"))
- if let error {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(theme.redDot)
- }
- }
- .padding(.horizontal, 18)
- .padding(.top, 8)
- }
-}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/StatusScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/StatusScreen.swift
index 56cd127a32..c55e4f6521 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/StatusScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/StatusScreen.swift
@@ -125,12 +125,7 @@ struct StatusScreen: View {
comment: "Section header for the updates section"))
UpdatesSection(updates: services.updates)
- if let error = vm.lastError {
- Text(error)
- .font(.omlxText(11))
- .foregroundStyle(.red)
- .padding(.horizontal, 18).padding(.top, 8)
- }
+ FooterBar(error: vm.lastError)
}
.task(id: vm.scope) {
await vm.start(client: services.client)
@@ -619,7 +614,7 @@ private struct UpdatesSection: View {
get: { updates.channel },
set: { updates.channel = $0 }
),
- width: 190,
+ width: .controlMedium,
options: UpdateChannel.allCases.map { ($0, $0.displayName) }
)
}
@@ -631,12 +626,10 @@ private struct UpdatesSection: View {
defaultValue: "Look for updates daily in the background",
comment: "Sublabel for the auto-check toggle")
) {
- Toggle("", isOn: Binding(
+ RowSwitch(isOn: Binding(
get: { updates.autoCheck },
set: { updates.autoCheck = $0 }
))
- .labelsHidden()
- .toggleStyle(.switch)
}
Row(
label: String(localized: "status.updates.auto_download",
@@ -647,12 +640,10 @@ private struct UpdatesSection: View {
comment: "Sublabel for the automatic update notification toggle"),
isLast: true
) {
- Toggle("", isOn: Binding(
+ RowSwitch(isOn: Binding(
get: { updates.autoNotify },
set: { updates.autoNotify = $0 }
))
- .labelsHidden()
- .toggleStyle(.switch)
}
}
}
diff --git a/apps/omlx-mac/Sources/AppView/Screens/ThroughputBenchScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ThroughputBenchScreen.swift
index d6b1c6c49c..63040d3ecc 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/ThroughputBenchScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/ThroughputBenchScreen.swift
@@ -129,7 +129,7 @@ private struct DeviceChip: View {
.foregroundStyle(theme.textSecondary)
Spacer(minLength: 0)
}
- .padding(.horizontal, 18)
+ .padding(.horizontal, 14)
.padding(.top, 2)
.padding(.bottom, 8)
}
@@ -197,7 +197,7 @@ private struct ConfigurationSection: View {
comment: "Sublabel under the Throughput Bench model picker")) {
Popup(
selection: $selectedModelId,
- width: 320,
+ width: .controlWide,
options: modelOptions
)
}
@@ -210,7 +210,7 @@ private struct ConfigurationSection: View {
comment: "Sublabel under the Throughput Bench context picker")) {
Popup(
selection: $contextProfile,
- width: 220,
+ width: .controlMedium,
options: BenchmarkContextProfile.allCases.map {
PopupOption(value: $0, label: $0.localizedLabel)
}
@@ -232,7 +232,6 @@ private struct ConfigurationSection: View {
defaultValue: "Full · 2,048",
comment: "Full 2048-token ANE benchmark warm-up option")),
])
- .frame(width: 260)
.disabled(running)
}
@@ -242,24 +241,22 @@ private struct ConfigurationSection: View {
sublabel: String(localized: "bench.throughput.row.ane_alignment.sub",
defaultValue: "Add one prompt token so PP4097 produces exactly 4,096 prefill rows. Aligned results remain local.",
comment: "Explanation of the ANE-aligned throughput benchmark option")) {
- Toggle("", isOn: $alignPromptToAne)
- .labelsHidden()
- .toggleStyle(.switch)
+ RowSwitch(isOn: $alignPromptToAne)
.disabled(running)
}
- FreeRow {
- ChipRow(
- title: String(localized: "bench.throughput.row.context_lengths.title",
- defaultValue: "Context lengths",
- comment: "Inline title above the prompt-length chip row"),
- sublabel: String(localized: "bench.throughput.row.context_lengths.sub",
- defaultValue: "Prompt tokens to feed for each single-request trial",
- comment: "Sublabel under the prompt-length chip row"),
+ Row(label: String(localized: "bench.throughput.row.context_lengths.title",
+ defaultValue: "Context lengths",
+ comment: "Inline title above the prompt-length chip row"),
+ sublabel: String(localized: "bench.throughput.row.context_lengths.sub",
+ defaultValue: "Prompt tokens to feed for each single-request trial",
+ comment: "Sublabel under the prompt-length chip row")) {
+ ChipGroup(
options: Self.promptLengthOptions,
selection: $promptLengths,
format: Self.formatPromptLength
)
+ .disabled(running)
}
Row(label: String(localized: "bench.throughput.row.gen_length.label",
@@ -272,22 +269,22 @@ private struct ConfigurationSection: View {
text: $genLength,
placeholder: "128",
mono: true,
- width: 110
+ width: .controlCompact
)
}
- FreeRow {
- ChipRow(
- title: String(localized: "bench.throughput.row.batch_sizes.title",
- defaultValue: "Batch sizes",
- comment: "Inline title above the batch-size chip row"),
- sublabel: String(localized: "bench.throughput.row.batch_sizes.sub",
- defaultValue: "Concurrent requests per batch in the continuous-batching phase",
- comment: "Sublabel under the batch-size chip row"),
+ Row(label: String(localized: "bench.throughput.row.batch_sizes.title",
+ defaultValue: "Batch sizes",
+ comment: "Inline title above the batch-size chip row"),
+ sublabel: String(localized: "bench.throughput.row.batch_sizes.sub",
+ defaultValue: "Concurrent requests per batch in the continuous-batching phase",
+ comment: "Sublabel under the batch-size chip row")) {
+ ChipGroup(
options: Self.batchSizeOptions,
selection: $batchSizes,
format: { "\($0)" }
)
+ .disabled(running)
}
Row(isLast: true) {
@@ -357,36 +354,24 @@ private struct ConfigurationSection: View {
}
}
-// MARK: - Chip row
+// MARK: - Chip group
-private struct ChipRow: View {
- let title: String
- let sublabel: String
+/// Multi-select strip of toggle chips, used as a `Row` trailing. Styled to
+/// echo the segmented control — quiet fill, accent when selected — but with
+/// detached segments and gaps because multiple values can be active at once.
+private struct ChipGroup: View {
let options: [Int]
@Binding var selection: Set
let format: (Int) -> String
- @Environment(\.omlxTheme) private var theme
-
var body: some View {
- VStack(alignment: .leading, spacing: 8) {
- VStack(alignment: .leading, spacing: 2) {
- Text(title)
- .font(.omlxText(13, weight: .medium))
- .foregroundStyle(theme.text)
- Text(sublabel)
- .font(.omlxText(11.5))
- .foregroundStyle(theme.textSecondary)
- }
- HStack(spacing: 6) {
- ForEach(options, id: \.self) { value in
- Chip(
- label: format(value),
- isSelected: selection.contains(value),
- onTap: { toggle(value) }
- )
- }
- Spacer(minLength: 0)
+ HStack(spacing: 5) {
+ ForEach(options, id: \.self) { value in
+ Chip(
+ label: format(value),
+ isSelected: selection.contains(value),
+ onTap: { toggle(value) }
+ )
}
}
}
@@ -411,19 +396,16 @@ private struct Chip: View {
Button(action: onTap) {
Text(label)
.font(.omlxText(11.5, weight: .medium))
- .foregroundStyle(isSelected ? theme.accentText : theme.textSecondary)
+ // Chips must never compress: under width pressure SwiftUI
+ // would otherwise wrap "128K" to "12/8K". The label column
+ // absorbs the squeeze instead.
+ .fixedSize()
+ .foregroundStyle(isSelected ? theme.accentText : theme.text)
.padding(.horizontal, 10)
.padding(.vertical, 4)
.background(
RoundedRectangle(cornerRadius: 6, style: .continuous)
- .fill(isSelected ? theme.accent : theme.controlBg)
- .overlay(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .strokeBorder(
- isSelected ? Color.clear : theme.inputBorder,
- lineWidth: 0.5
- )
- )
+ .fill(isSelected ? theme.accent : theme.hoverBg)
)
.contentShape(Rectangle())
}
@@ -917,7 +899,7 @@ private struct OwnerHashRow: View {
}
.buttonStyle(.omlx(.plain, size: .small))
}
- .padding(.horizontal, 18)
+ .padding(.horizontal, 14)
.padding(.top, 4)
.padding(.bottom, 10)
}
diff --git a/apps/omlx-mac/Sources/AppView/ViewModels/ModelSettingsScreenVM.swift b/apps/omlx-mac/Sources/AppView/ViewModels/ModelSettingsScreenVM.swift
index 403b2aa4f0..b1286154e9 100644
--- a/apps/omlx-mac/Sources/AppView/ViewModels/ModelSettingsScreenVM.swift
+++ b/apps/omlx-mac/Sources/AppView/ViewModels/ModelSettingsScreenVM.swift
@@ -28,7 +28,8 @@ final class ModelSettingsScreenVM {
case alias, modelType, contextLength, maxTokens
case temperature, topP, topK, minP
case repetitionPenalty, presencePenalty, ttl
- case enableThinking, thinkingBudgetEnabled, thinkingBudgetTokens
+ case enableThinking, qwen4PleSsdOffload
+ case thinkingBudgetEnabled, thinkingBudgetTokens
case limitToolResults, toolResultLimitTokens
case forceSampling, isPinned, isFavorite
case trustRemoteCode
@@ -237,6 +238,9 @@ final class ModelSettingsScreenVM {
// Advanced
var enableThinking: Bool = true
+ var qwen4PleSsdOffload: Bool = false
+ var qwen4PleSsdOffloadSupported: Bool = false
+ var qwen4PleSsdOffloadForced: Bool = false
var thinkingBudgetEnabled: Bool = false
var thinkingBudgetTokens: String = "8192"
var limitToolResults: Bool = false
@@ -368,11 +372,18 @@ final class ModelSettingsScreenVM {
return Self.diffusionConfigModelTypes.contains(type)
}
+ var isQwen4Exp: Bool {
+ (model?.configModelType ?? "")
+ .lowercased()
+ .replacingOccurrences(of: "-", with: "_") == "qwen4_exp"
+ }
+
private func isDiffusionUnsupportedField(_ field: Field) -> Bool {
switch field {
case .topP, .topK, .minP, .repetitionPenalty, .presencePenalty:
return true
- case .enableThinking, .thinkingBudgetEnabled, .thinkingBudgetTokens:
+ case .enableThinking, .qwen4PleSsdOffload,
+ .thinkingBudgetEnabled, .thinkingBudgetTokens:
return true
case .limitToolResults, .toolResultLimitTokens:
return true
@@ -499,6 +510,12 @@ final class ModelSettingsScreenVM {
self.presencePenalty = s?.presencePenalty.map { String($0) } ?? ""
self.ttlSeconds = s?.ttlSeconds.map(String.init) ?? ""
self.enableThinking = s?.enableThinking ?? true
+ self.qwen4PleSsdOffloadForced =
+ m.qwen4PleSsdOffloadForced ?? false
+ self.qwen4PleSsdOffloadSupported =
+ m.qwen4PleSsdOffloadSupported ?? false
+ self.qwen4PleSsdOffload = self.qwen4PleSsdOffloadForced
+ || (s?.qwen4PleSsdOffload ?? false)
self.thinkingBudgetEnabled = s?.thinkingBudgetEnabled ?? false
self.thinkingBudgetTokens = s?.thinkingBudgetTokens.map(String.init) ?? "8192"
self.limitToolResults = (s?.maxToolResultTokens ?? 0) > 0
@@ -639,6 +656,10 @@ final class ModelSettingsScreenVM {
}
case .ttl: patch.ttlSeconds = Int(ttlSeconds)
case .enableThinking: patch.enableThinking = enableThinking
+ case .qwen4PleSsdOffload:
+ guard isQwen4Exp, qwen4PleSsdOffloadSupported,
+ !qwen4PleSsdOffloadForced else { return }
+ patch.qwen4PleSsdOffload = qwen4PleSsdOffload
case .thinkingBudgetEnabled: patch.thinkingBudgetEnabled = thinkingBudgetEnabled
case .thinkingBudgetTokens: patch.thinkingBudgetTokens = Int(thinkingBudgetTokens)
case .limitToolResults:
@@ -992,19 +1013,15 @@ final class ModelSettingsScreenVM {
|| type.hasPrefix("qwen3_8")
}
- /// MTP can't co-exist with DFlash or TurboQuant KV. The toggle uses
- /// this to disable itself and surface the conflict reason.
+ /// Native Lightning MTP can't co-exist with the other speculative
+ /// decoders. TurboQuant KV supports its decode-shaped multi-row verify
+ /// path, so it is intentionally not a conflict here.
var mtpConflictReason: String? {
if dflashEnabled {
return String(localized: "settings.mtp.conflict.dflash",
defaultValue: "Disable DFlash before enabling MTP.",
comment: "Tooltip / sublabel shown when MTP can't be enabled because DFlash is on")
}
- if turboquantKvEnabled {
- return String(localized: "settings.mtp.conflict.turboquant",
- defaultValue: "Disable TurboQuant KV before enabling MTP.",
- comment: "Tooltip / sublabel shown when MTP can't be enabled because TurboQuant KV is on")
- }
if vlmMtpEnabled {
return String(localized: "settings.mtp.conflict.vlm_mtp",
defaultValue: "Disable VLM MTP before enabling Lightning MTP.",
diff --git a/apps/omlx-mac/Sources/AppView/ViewModels/ServerScreenVM.swift b/apps/omlx-mac/Sources/AppView/ViewModels/ServerScreenVM.swift
index a9a97c1c5a..15ba43abf1 100644
--- a/apps/omlx-mac/Sources/AppView/ViewModels/ServerScreenVM.swift
+++ b/apps/omlx-mac/Sources/AppView/ViewModels/ServerScreenVM.swift
@@ -10,6 +10,7 @@ final class ServerScreenVM {
// Phase 4 — Advanced disclosure.
var sseKeepaliveMode: String = "chunk"
+ var maxAudioUploadSizeText: String = "100MB"
/// Comma-separated text shown in the input. Parsed to `[String]` on save
/// so the user can edit incrementally without intermediate trips to the
/// server. Empty string clears all aliases.
@@ -50,6 +51,7 @@ final class ServerScreenVM {
private var baselineSamplingTopKText: String = "0"
private var baselineSamplingRepetitionPenaltyText: String = "1.0"
private var baselineServerAliasesText: String = ""
+ private var baselineMaxAudioUploadSizeText: String = "100MB"
private var baselineModelDirs: [String] = []
private var baselineHfCacheEnabled: Bool = true
@@ -70,6 +72,7 @@ final class ServerScreenVM {
self.effectiveHost = AppConfig.connectableHost(for: dto.server.host)
self.effectivePort = dto.server.port
self.sseKeepaliveMode = dto.server.sseKeepaliveMode ?? "chunk"
+ self.maxAudioUploadSizeText = dto.server.maxAudioUploadSize ?? "100MB"
self.serverAliasesText = dto.server.serverAliases.joined(separator: ", ")
let modelDirs = Self.cleanedModelDirs(
dto.model?.modelDirs ?? dto.model?.modelDir.map { [$0] } ?? []
@@ -108,6 +111,7 @@ final class ServerScreenVM {
baselineSamplingTopKText = t(samplingTopKText)
baselineSamplingRepetitionPenaltyText = t(samplingRepetitionPenaltyText)
baselineServerAliasesText = serverAliasesText
+ baselineMaxAudioUploadSizeText = t(maxAudioUploadSizeText)
baselineModelDirs = Self.normalizedModelDirs(from: modelDirTexts)
baselineHfCacheEnabled = hfCacheEnabled
}
@@ -126,6 +130,7 @@ final class ServerScreenVM {
if t(samplingTopKText) != baselineSamplingTopKText { return true }
if t(samplingRepetitionPenaltyText) != baselineSamplingRepetitionPenaltyText { return true }
if parseAliases(serverAliasesText) != parseAliases(baselineServerAliasesText) { return true }
+ if t(maxAudioUploadSizeText) != baselineMaxAudioUploadSizeText { return true }
if hfCacheEnabled != baselineHfCacheEnabled { return true }
return hasPendingStorageChanges(services: services)
}
@@ -206,6 +211,18 @@ final class ServerScreenVM {
}
patch.samplingRepetitionPenalty = v
}
+ if t(maxAudioUploadSizeText) != baselineMaxAudioUploadSizeText {
+ let value = t(maxAudioUploadSizeText)
+ guard Self.isValidAudioUploadSize(value) else {
+ self.lastError = String(
+ localized: "server.error.audio_upload_size_invalid",
+ defaultValue: "Maximum Audio Upload Size must be a positive value such as 100MB or 1GB.",
+ comment: "Server screen error when the audio upload size is invalid"
+ )
+ return
+ }
+ patch.maxAudioUploadSize = value
+ }
let newAliases = parseAliases(serverAliasesText)
if newAliases != parseAliases(baselineServerAliasesText) {
@@ -239,6 +256,7 @@ final class ServerScreenVM {
|| patch.samplingTopP != nil
|| patch.samplingTopK != nil
|| patch.samplingRepetitionPenalty != nil
+ || patch.maxAudioUploadSize != nil
|| patch.serverAliases != nil
|| patch.hfCacheEnabled != nil
|| patch.modelDirs != nil
@@ -317,6 +335,31 @@ final class ServerScreenVM {
return parts.filter { seen.insert($0).inserted }
}
+ /// Mirror the server's human-readable size grammar closely enough to
+ /// reject incomplete edits before sending a multi-field settings patch.
+ static func isValidAudioUploadSize(_ raw: String) -> Bool {
+ let text = raw
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ .uppercased()
+ let units: [(suffix: String, multiplier: Double)] = [
+ ("TB", 1024 * 1024 * 1024 * 1024),
+ ("GB", 1024 * 1024 * 1024),
+ ("MB", 1024 * 1024),
+ ("KB", 1024),
+ ("B", 1),
+ ]
+
+ for unit in units where text.hasSuffix(unit.suffix) {
+ let number = String(text.dropLast(unit.suffix.count))
+ guard let value = Double(number), value.isFinite else { return false }
+ let bytes = value * unit.multiplier
+ return bytes.isFinite && bytes >= 1
+ }
+
+ guard let bytes = Int(text) else { return false }
+ return bytes > 0
+ }
+
func modelDirText(at index: Int) -> String {
guard modelDirTexts.indices.contains(index) else { return "" }
return modelDirTexts[index]
diff --git a/apps/omlx-mac/Sources/Menubar/MenubarMetricPopover.swift b/apps/omlx-mac/Sources/Menubar/MenubarMetricPopover.swift
index c89c1cca8a..053909a074 100644
--- a/apps/omlx-mac/Sources/Menubar/MenubarMetricPopover.swift
+++ b/apps/omlx-mac/Sources/Menubar/MenubarMetricPopover.swift
@@ -206,12 +206,19 @@ struct MetricSparkline: View {
let isFlat = span <= .ulpOfOne
let stepX = size.width / CGFloat(values.count - 1)
+ // Inset the plot range by half the stroke width so a series
+ // pinned to the floor (0%) or ceiling doesn't center its stroke
+ // on the canvas edge and render half-clipped.
+ let lineWidth: CGFloat = 1.2
+ let plotTop = lineWidth / 2
+ let plotHeight = size.height - lineWidth
+
var trace = Path()
for (index, value) in values.enumerated() {
let normalized = isFlat ? 0.5 : (value - low) / span
let point = CGPoint(
x: CGFloat(index) * stepX,
- y: size.height * (1 - CGFloat(normalized))
+ y: plotTop + plotHeight * (1 - CGFloat(normalized))
)
if index == 0 {
trace.move(to: point)
@@ -235,7 +242,7 @@ struct MetricSparkline: View {
context.stroke(
trace,
with: .color(color),
- style: StrokeStyle(lineWidth: 1.2, lineJoin: .round)
+ style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round)
)
}
.frame(height: height)
diff --git a/apps/omlx-mac/Sources/Net/DTO/GlobalSettingsDTO.swift b/apps/omlx-mac/Sources/Net/DTO/GlobalSettingsDTO.swift
index c0f40bb20a..f2fe269944 100644
--- a/apps/omlx-mac/Sources/Net/DTO/GlobalSettingsDTO.swift
+++ b/apps/omlx-mac/Sources/Net/DTO/GlobalSettingsDTO.swift
@@ -58,6 +58,7 @@ struct GlobalSettingsDTO: Codable, Equatable, Sendable {
let serverAliases: [String]
let sseKeepaliveMode: String?
let autoStartOnLaunch: Bool?
+ let maxAudioUploadSize: String?
}
struct ModelSettings: Codable, Equatable, Sendable {
@@ -212,6 +213,8 @@ struct GlobalSettingsPatch: Encodable, Equatable, Sendable {
/// `"off"`. Server rejects anything else with a 400.
var sseKeepaliveMode: String? = nil
var autoStartOnLaunch: Bool? = nil
+ /// Human-readable cap such as `100MB` or `1GB`. Applied immediately.
+ var maxAudioUploadSize: String? = nil
// Claude Code (PR 9)
var claudeCodeContextScalingEnabled: Bool? = nil
diff --git a/apps/omlx-mac/Sources/Net/DTO/ModelsDTO.swift b/apps/omlx-mac/Sources/Net/DTO/ModelsDTO.swift
index 0a40ecc88c..6db7e338d3 100644
--- a/apps/omlx-mac/Sources/Net/DTO/ModelsDTO.swift
+++ b/apps/omlx-mac/Sources/Net/DTO/ModelsDTO.swift
@@ -52,6 +52,11 @@ struct ModelDTO: Codable, Equatable, Sendable, Identifiable {
/// True when the model is structurally compatible with native MTP.
let mtpCompatible: Bool?
let mtpCompatibilityReason: String?
+ /// Qwen4-Exp PLE mmap capability and server-side forced residency decision.
+ let qwen4PleSsdOffloadSupported: Bool?
+ let qwen4PleSsdOffloadForced: Bool?
+ let qwen4PleResidentBytes: Int64?
+ let qwen4PleMmapBytes: Int64?
/// True for builtin virtual entries (e.g. the MarkItDown document
/// converter) that have no real load/unload lifecycle.
let virtual: Bool?
@@ -83,6 +88,7 @@ struct ModelSettingsDTO: Codable, Equatable, Sendable {
let forceSampling: Bool?
let maxToolResultTokens: Int?
let enableThinking: Bool?
+ let qwen4PleSsdOffload: Bool?
let thinkingBudgetEnabled: Bool?
let thinkingBudgetTokens: Int?
let reasoningParser: String?
@@ -169,6 +175,7 @@ struct ModelSettingsPatch: Encodable, Equatable, Sendable {
var repetitionPenalty: Double? = nil
var ttlSeconds: Int? = nil
var enableThinking: Bool? = nil
+ var qwen4PleSsdOffload: Bool? = nil
var thinkingBudgetEnabled: Bool? = nil
var thinkingBudgetTokens: Int? = nil
var maxToolResultTokens: Int? = nil
diff --git a/apps/omlx-mac/Sources/Theme/Components/Button.swift b/apps/omlx-mac/Sources/Theme/Components/Button.swift
index bfd1954708..d5fc428e5f 100644
--- a/apps/omlx-mac/Sources/Theme/Components/Button.swift
+++ b/apps/omlx-mac/Sources/Theme/Components/Button.swift
@@ -1,15 +1,18 @@
-// PR 3 — button styles for primary / destructive / plain / regular.
+// Button styles for primary / destructive / normal / plain.
//
// Use:
// Button("Save") { … }
// .buttonStyle(.omlx(.primary))
//
-// The plain kind is the JSX "kind=plain" — borderless action label, e.g. the
-// chevron-only row buttons in screens.
+// primary / destructive / normal delegate to the native bordered styles so
+// buttons share bezel metrics, fonts, and disabled/pressed treatment with
+// the native fields and pickers they sit next to. plain stays a quiet
+// custom label (text-colored, hover-highlight only) because the native
+// borderless style would accent-tint the many icon-only row buttons.
import SwiftUI
-struct OMLXButtonStyle: ButtonStyle {
+struct OMLXButtonStyle: PrimitiveButtonStyle {
enum Kind: Sendable { case primary, destructive, normal, plain }
enum Size: Sendable { case small, regular }
@@ -17,72 +20,46 @@ struct OMLXButtonStyle: ButtonStyle {
let size: Size
@Environment(\.omlxTheme) private var theme
- /// Without this, a `.disabled()` button keeps its enabled paint because the
- /// custom background ignores SwiftUI's default isEnabled tint. Users then
- /// click an enabled-looking primary button and see no press animation
- /// (SwiftUI suppresses `isPressed` on disabled buttons) — leading to the
- /// "Apply only animates the first time" report. Reading `isEnabled` here
- /// dims the whole label so disabled state is visually unmistakable.
- @Environment(\.isEnabled) private var isEnabled
-
- func makeBody(configuration: Configuration) -> some View {
- let labelFont = Font.omlxText(size == .small ? 11.5 : 13, weight: .medium)
- let hPad: CGFloat = size == .small ? 10 : 12
- let vPad: CGFloat = size == .small ? 4 : 6
-
- return configuration.label
- .font(labelFont)
- .padding(.horizontal, hPad)
- .padding(.vertical, vPad)
- .foregroundStyle(foreground(configuration))
- .background(background(configuration))
- .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))
- .overlay(border(configuration))
- .opacity(opacity(configuration))
- .contentShape(Rectangle())
- }
-
- /// Disabled state wins over press feedback. 0.45 is the macOS-feeling
- /// "this control is inert" tint — tested against `.primary` (blue),
- /// `.destructive` (red), `.normal` (themed control bg), and `.plain`
- /// (transparent + dimmed text).
- private func opacity(_ cfg: Configuration) -> Double {
- guard isEnabled else { return 0.45 }
- return cfg.isPressed ? 0.78 : 1.0
- }
@ViewBuilder
- private func background(_ cfg: Configuration) -> some View {
+ func makeBody(configuration: Configuration) -> some View {
+ let button = Button(configuration)
+ .controlSize(size == .small ? .small : .regular)
switch kind {
case .primary:
- theme.accent
+ button.buttonStyle(.borderedProminent)
case .destructive:
- theme.redDot
+ button.buttonStyle(.borderedProminent).tint(theme.redDot)
case .normal:
- theme.controlBg
+ button.buttonStyle(.bordered)
case .plain:
- cfg.isPressed ? theme.hoverBg : Color.clear
+ button.buttonStyle(QuietButtonStyle(theme: theme, size: size))
}
}
+}
- private func foreground(_ cfg: Configuration) -> Color {
- switch kind {
- case .primary, .destructive: return theme.accentText
- case .normal: return theme.text
- case .plain: return theme.text
- }
- }
+/// The former custom "plain" rendering: label in text color, hover-style
+/// highlight while pressed, dimmed when disabled.
+private struct QuietButtonStyle: ButtonStyle {
+ let theme: OMLXTheme
+ let size: OMLXButtonStyle.Size
- @ViewBuilder
- private func border(_ cfg: Configuration) -> some View {
- if kind == .normal {
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .strokeBorder(theme.inputBorder, lineWidth: 0.5)
- }
+ @Environment(\.isEnabled) private var isEnabled
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .font(.omlxText(size == .small ? 11.5 : 13, weight: .medium))
+ .padding(.horizontal, size == .small ? 10 : 12)
+ .padding(.vertical, size == .small ? 4 : 6)
+ .foregroundStyle(theme.text)
+ .background(configuration.isPressed ? theme.hoverBg : Color.clear)
+ .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))
+ .opacity(isEnabled ? (configuration.isPressed ? 0.78 : 1.0) : 0.45)
+ .contentShape(Rectangle())
}
}
-extension ButtonStyle where Self == OMLXButtonStyle {
+extension PrimitiveButtonStyle where Self == OMLXButtonStyle {
static func omlx(
_ kind: OMLXButtonStyle.Kind = .normal,
size: OMLXButtonStyle.Size = .regular
diff --git a/apps/omlx-mac/Sources/Theme/Components/Popup.swift b/apps/omlx-mac/Sources/Theme/Components/Popup.swift
index 72e845e908..e834dce3a4 100644
--- a/apps/omlx-mac/Sources/Theme/Components/Popup.swift
+++ b/apps/omlx-mac/Sources/Theme/Components/Popup.swift
@@ -1,4 +1,5 @@
-// PR 3 — dropdown picker styled to match the JSX `Popup`.
+// PR 3 — dropdown picker. Renders the native macOS menu picker so selects
+// share one bezel, height, and font with the rest of the system controls.
import SwiftUI
@@ -13,78 +14,35 @@ struct Popup: View {
var titleKey: LocalizedStringKey
let options: [PopupOption]
let width: CGFloat?
- let fillsWidth: Bool
- @Environment(\.omlxTheme) private var theme
-
- init(_ titleKey: LocalizedStringKey = "", selection: Binding, width: CGFloat? = nil, fillsWidth: Bool = false, options: [PopupOption]) {
+ init(_ titleKey: LocalizedStringKey = "", selection: Binding, width: CGFloat? = nil, options: [PopupOption]) {
self.titleKey = titleKey
self._selection = selection
self.options = options
self.width = width
- self.fillsWidth = fillsWidth
}
- init(_ titleKey: LocalizedStringKey = "", selection: Binding, width: CGFloat? = nil, fillsWidth: Bool = false, options: [(Value, String)]) {
+ init(_ titleKey: LocalizedStringKey = "", selection: Binding, width: CGFloat? = nil, options: [(Value, String)]) {
self.titleKey = titleKey
self._selection = selection
self.options = options.map { PopupOption(value: $0.0, label: $0.1) }
self.width = width
- self.fillsWidth = fillsWidth
}
var body: some View {
- if fillsWidth, let width {
- Menu {
- ForEach(options) { opt in
- Button {
- selection = opt.value
- } label: {
- if opt.value == selection {
- Label(opt.label, systemImage: "checkmark")
- } else {
- Text(opt.label)
- }
- }
- }
- } label: {
- HStack(spacing: 8) {
- Text(selectedOption?.label ?? "")
- .lineLimit(1)
- Spacer(minLength: 0)
- Image(systemName: "chevron.up.chevron.down")
- .font(.system(size: 10, weight: .semibold))
- }
- .font(.omlxText(13, weight: .medium))
- .foregroundStyle(theme.text)
- .padding(.horizontal, 10)
- .padding(.vertical, 4)
- .frame(width: width)
- .background(theme.controlBg)
- .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))
- .overlay {
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .strokeBorder(theme.inputBorder, lineWidth: 0.5)
- }
- .contentShape(Rectangle())
- }
- .menuStyle(.borderlessButton)
- .accessibilityValue(selectedOption?.label ?? "")
- } else {
- Picker(titleKey, selection: $selection) {
- ForEach(options) { opt in
- Text(opt.label)
- .tag(opt.value)
- }
+ Picker(titleKey, selection: $selection) {
+ ForEach(options) { opt in
+ Text(opt.label)
+ .tag(opt.value)
}
- .labelsHidden()
- .pickerStyle(.menu)
- .frame(maxWidth: width)
}
- }
-
- private var selectedOption: PopupOption? {
- options.first { $0.value == selection }
+ .labelsHidden()
+ .pickerStyle(.menu)
+ // The native popup bezel hugs its label, and a bare `maxWidth` frame
+ // would center it — leaving air on both sides. Pin it trailing so
+ // select bezels end flush with the other controls in the column;
+ // `width` stays the cap that keeps long labels from sprawling.
+ .frame(maxWidth: width, alignment: .trailing)
}
}
@@ -93,13 +51,13 @@ struct Popup: View {
@Previewable @State var quant = "q4"
VStack(alignment: .leading, spacing: 14) {
- Popup(selection: $host, width: 220, options: [
+ Popup(selection: $host, width: .controlMedium, options: [
("127.0.0.1", "127.0.0.1 (Local only)"),
("0.0.0.0", "0.0.0.0 (IPv4 only)"),
("::", "0.0.0.0 & :: (All Networks)"),
("localhost", "localhost"),
])
- Popup(selection: $quant, width: 120, options: [
+ Popup(selection: $quant, width: .controlCompact, options: [
("auto", "Auto"), ("q4", "q4"), ("q5", "q5"), ("q6", "q6"), ("q8", "q8"), ("fp16", "fp16"),
])
}
diff --git a/apps/omlx-mac/Sources/Theme/Components/Row.swift b/apps/omlx-mac/Sources/Theme/Components/Row.swift
index 087f703108..ec10000fe2 100644
--- a/apps/omlx-mac/Sources/Theme/Components/Row.swift
+++ b/apps/omlx-mac/Sources/Theme/Components/Row.swift
@@ -59,6 +59,24 @@ struct Row: View {
}
}
+/// Trailing on/off switch for a `Row`. One shared control so every screen
+/// gets the same size: `.small`, matching System Settings rows — the default
+/// regular switch reads oversized next to 13 pt row labels.
+struct RowSwitch: View {
+ @Binding var isOn: Bool
+
+ init(isOn: Binding) {
+ self._isOn = isOn
+ }
+
+ var body: some View {
+ Toggle("", isOn: $isOn)
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ }
+}
+
extension Row where Trailing == EmptyView {
/// Label-only row (no trailing slot).
init(label: String, sublabel: String? = nil, isLast: Bool = false) {
@@ -140,8 +158,16 @@ struct LinkRow: View {
)
}
+ @State private var hovering = false
+
+ // The whole row is one button (System Settings convention for rows
+ // that open a URL); the trailing ↗ is a passive indicator, not a
+ // separate control. Hover feedback replaces FreeRow so the highlight
+ // spans the full row width.
var body: some View {
- FreeRow(isLast: isLast) {
+ Button {
+ NSWorkspace.shared.open(url)
+ } label: {
HStack(spacing: 10) {
iconView
.foregroundStyle(theme.textSecondary)
@@ -158,13 +184,24 @@ struct LinkRow: View {
Spacer(minLength: 8)
- Button {
- NSWorkspace.shared.open(url)
- } label: {
- Label("common.open", systemImage: "arrow.up.right.square")
- .labelStyle(.iconOnly)
- }
- .buttonStyle(.omlx(.plain, size: .small))
+ Image(systemName: "arrow.up.right.square")
+ .font(.system(size: 14))
+ .foregroundStyle(theme.textSecondary)
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 10)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .background(hovering ? theme.hoverBg : .clear)
+ .onHover { hovering = $0 }
+ .overlay(alignment: .bottom) {
+ if !isLast {
+ Rectangle()
+ .fill(theme.rowSep)
+ .frame(height: 0.5)
+ .padding(.horizontal, 14)
}
}
}
@@ -182,14 +219,14 @@ struct LinkRow: View {
CodeChip(value: "127.0.0.1:8000")
}
Row(label: "Auto-start on launch") {
- Toggle("", isOn: $autoStart).labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $autoStart)
}
Row(
label: "Require API Key",
sublabel: "Reject unauthenticated /v1 requests",
isLast: true
) {
- Toggle("", isOn: $requireKey).labelsHidden().toggleStyle(.switch)
+ RowSwitch(isOn: $requireKey)
}
}
.padding(.vertical, 14)
diff --git a/apps/omlx-mac/Sources/Theme/Components/ScreenScaffold.swift b/apps/omlx-mac/Sources/Theme/Components/ScreenScaffold.swift
index 54969d3148..b70f295ec4 100644
--- a/apps/omlx-mac/Sources/Theme/Components/ScreenScaffold.swift
+++ b/apps/omlx-mac/Sources/Theme/Components/ScreenScaffold.swift
@@ -66,7 +66,7 @@ struct MessageBanner: View {
row(icon: "checkmark.circle.fill", text: success, color: theme.greenDot)
}
}
- .padding(.horizontal, 18)
+ .padding(.horizontal, 14)
.padding(.top, (hasError || hasSuccess) ? 6 : 0)
}
@@ -106,6 +106,54 @@ struct HintLine: View {
Text(text)
.font(.omlxText(11))
.foregroundStyle(theme.textTertiary)
+ .fixedSize(horizontal: false, vertical: true)
}
}
}
+
+/// Bottom action bar shared by screens with a trailing primary action
+/// (Apply and friends): optional hint on the left that wraps under width
+/// pressure, action buttons flush right, optional error line underneath.
+/// One component so the button/note relationship is identical everywhere.
+struct FooterBar: View {
+ var hint: String? = nil
+ var error: String? = nil
+ @ViewBuilder var actions: () -> Actions
+
+ @Environment(\.omlxTheme) private var theme
+
+ private var hasHint: Bool { !(hint ?? "").isEmpty }
+ private var hasError: Bool { !(error ?? "").isEmpty }
+ private var hasActions: Bool { Actions.self != EmptyView.self }
+
+ var body: some View {
+ if hasHint || hasError || hasActions {
+ VStack(alignment: .leading, spacing: 6) {
+ if hasHint || hasActions {
+ HStack(alignment: .center, spacing: 12) {
+ if let hint, hasHint {
+ HintLine(text: hint)
+ }
+ Spacer(minLength: 0)
+ actions()
+ }
+ }
+ if let error, hasError {
+ Text(error)
+ .font(.omlxText(11))
+ .foregroundStyle(theme.redDot)
+ }
+ }
+ .padding(.horizontal, 14)
+ .padding(.top, 8)
+ }
+ }
+}
+
+extension FooterBar where Actions == EmptyView {
+ /// Error-only (or hint-only) footer — the standard trailing status line
+ /// under a screen. Renders nothing while there is nothing to show.
+ init(hint: String? = nil, error: String? = nil) {
+ self.init(hint: hint, error: error) { EmptyView() }
+ }
+}
diff --git a/apps/omlx-mac/Sources/Theme/Components/SectionHeader.swift b/apps/omlx-mac/Sources/Theme/Components/SectionHeader.swift
index 8a414ffde7..a8ccd19fee 100644
--- a/apps/omlx-mac/Sources/Theme/Components/SectionHeader.swift
+++ b/apps/omlx-mac/Sources/Theme/Components/SectionHeader.swift
@@ -36,7 +36,9 @@ struct SectionHeader: View {
Spacer(minLength: 0)
trailing
}
- .padding(.horizontal, 14)
+ // 28 = card gutter (14) + row inset (14): header text lines up with
+ // the row text inside the ListGroup below, like System Settings.
+ .padding(.horizontal, 28)
.padding(.top, 14)
.padding(.bottom, 6)
}
diff --git a/apps/omlx-mac/Sources/Theme/Components/TextInput.swift b/apps/omlx-mac/Sources/Theme/Components/TextInput.swift
index f548ea6ae6..f565d17ef0 100644
--- a/apps/omlx-mac/Sources/Theme/Components/TextInput.swift
+++ b/apps/omlx-mac/Sources/Theme/Components/TextInput.swift
@@ -40,7 +40,9 @@ struct TextInput: View {
field
.lineLimit(1)
.textFieldStyle(.roundedBorder)
- .font(mono ? .omlxMono(13, weight: .medium) : .omlxText(13, weight: .medium))
+ // Regular weight: native macOS fields never render medium-weight
+ // content, and the bolder text read as a foreign control.
+ .font(mono ? .omlxMono(13) : .omlxText(13))
.foregroundStyle(theme.text)
.overlay(alignment: .trailing) {
HStack(spacing: 0) {
@@ -55,7 +57,10 @@ struct TextInput: View {
}
}
}
- .frame(maxWidth: width)
+ // Fixed, not max: under `maxWidth` a long row label squeezes the
+ // field, so fields sharing a width token rendered ragged widths.
+ // A fixed frame makes equal tokens render equal; labels wrap.
+ .frame(width: width)
}
private var field: some View {
@@ -93,11 +98,11 @@ struct TextInput: View {
@Previewable @State var showKey = false
@Previewable @State var alias = ""
VStack(alignment: .leading, spacing: 14) {
- TextInput(text: $port, placeholder: "Port", mono: true, width: 110)
- TextInput(text: $qty, placeholder: "Quantity", isNumeric: true, suffix: "qty", width: 160)
- TextInput(text: $temperature, placeholder: "Temperature", isNumeric: true, range: 0...2, step: 0.1, width: 160)
+ TextInput(text: $port, placeholder: "Port", mono: true, width: .controlCompact)
+ TextInput(text: $qty, placeholder: "Quantity", isNumeric: true, suffix: "qty", width: .controlCompact)
+ TextInput(text: $temperature, placeholder: "Temperature", isNumeric: true, range: 0...2, step: 0.1, width: .controlCompact)
HStack {
- TextInput(text: $pwd, placeholder: "Admin password", isSecure: !showKey, width: 200)
+ TextInput(text: $pwd, placeholder: "Admin password", isSecure: !showKey, width: .controlMedium)
Button {
showKey.toggle()
} label: {
@@ -107,7 +112,7 @@ struct TextInput: View {
.buttonStyle(.plain)
}
TextInput(text: $alias, placeholder: "model-id-suffix", mono: true,
- suffix: "alias", width: 240)
+ suffix: "alias", width: .controlMedium)
}
.padding(24)
.omlxThemed()
diff --git a/apps/omlx-mac/Sources/Theme/Theme.swift b/apps/omlx-mac/Sources/Theme/Theme.swift
index 97b5b3e9c3..f4cf04e006 100644
--- a/apps/omlx-mac/Sources/Theme/Theme.swift
+++ b/apps/omlx-mac/Sources/Theme/Theme.swift
@@ -261,6 +261,23 @@ extension View {
func omlxThemed() -> some View { modifier(OMLXThemeBinder()) }
}
+// MARK: - Control metrics
+
+/// Standard widths for trailing controls (text inputs, selects) in settings
+/// rows. Every `TextInput`/`Popup` picks the smallest token that fits its
+/// content instead of hand-tuning a per-row width, so control edges line up
+/// between rows and across screens.
+extension CGFloat {
+ /// Bare numbers: ports, counts, factors.
+ static let controlNarrow: CGFloat = 90
+ /// Numbers with a suffix or stepper, short enum selects.
+ static let controlCompact: CGFloat = 130
+ /// Names, keys, typical selects.
+ static let controlMedium: CGFloat = 220
+ /// Paths, URLs, model-id selects.
+ static let controlWide: CGFloat = 320
+}
+
// MARK: - Color helpers
extension Color {
diff --git a/apps/omlx-mac/Sources/Updater/AppUpdater.swift b/apps/omlx-mac/Sources/Updater/AppUpdater.swift
index e536e5bb6c..be1d10fc81 100644
--- a/apps/omlx-mac/Sources/Updater/AppUpdater.swift
+++ b/apps/omlx-mac/Sources/Updater/AppUpdater.swift
@@ -20,6 +20,8 @@ final class AppUpdater {
case notWritable(String)
case downloadFailed(String)
case mountFailed(String)
+ case unmountFailed(String)
+ case cleanupFailed(String)
case appNotFoundInVolume
case stageFailed(String)
case cancelled
@@ -30,6 +32,8 @@ final class AppUpdater {
return "Cannot write to \(path). Move oMLX.app to a writable location and try again."
case .downloadFailed(let m): return "Download failed: \(m)"
case .mountFailed(let m): return "Could not mount DMG: \(m)"
+ case .unmountFailed(let m): return "Could not unmount DMG: \(m)"
+ case .cleanupFailed(let m): return "Could not clean up update files: \(m)"
case .appNotFoundInVolume: return "oMLX.app not found inside the downloaded DMG"
case .stageFailed(let m): return "Could not stage the update: \(m)"
case .cancelled: return "Update cancelled"
@@ -124,7 +128,12 @@ final class AppUpdater {
onError(.downloadFailed("Could not create temp dir: \(error.localizedDescription)"))
return
}
- defer { try? FileManager.default.removeItem(at: tmpDir) }
+ var temporaryDirectoryNeedsCleanup = true
+ defer {
+ if temporaryDirectoryNeedsCleanup {
+ try? FileManager.default.removeItem(at: tmpDir)
+ }
+ }
let dmgPath = tmpDir.appendingPathComponent("oMLX-\(version).dmg")
@@ -150,7 +159,12 @@ final class AppUpdater {
onError(.mountFailed(error.localizedDescription)); return
}
- defer { _ = try? unmountDMG(at: mountPoint) }
+ var mountedDMGNeedsCleanup = true
+ defer {
+ if mountedDMGNeedsCleanup {
+ try? unmountDMG(at: mountPoint)
+ }
+ }
if cancelled { return }
onProgress(.staging)
@@ -165,8 +179,40 @@ final class AppUpdater {
}
if cancelled { return }
- onProgress(.ready)
- onReady()
+ do {
+ try Self.finishStagedUpdate(
+ detach: {
+ try unmountDMG(at: mountPoint)
+ mountedDMGNeedsCleanup = false
+ },
+ removeTemporaryFiles: {
+ try FileManager.default.removeItem(at: tmpDir)
+ temporaryDirectoryNeedsCleanup = false
+ },
+ notifyReady: {
+ onProgress(.ready)
+ onReady()
+ }
+ )
+ } catch let err as UpdateError {
+ onError(err)
+ } catch {
+ onError(.cleanupFailed(error.localizedDescription))
+ }
+ }
+
+ /// Releases every resource owned by a staged update before notifying the
+ /// controller. `notifyReady` may synchronously terminate the process, so
+ /// moving either cleanup step after it would leak the mounted image and
+ /// its downloaded backing file.
+ static func finishStagedUpdate(
+ detach: () throws -> Void,
+ removeTemporaryFiles: () throws -> Void,
+ notifyReady: () -> Void
+ ) throws {
+ try detach()
+ try removeTemporaryFiles()
+ notifyReady()
}
// MARK: - Download
@@ -313,13 +359,16 @@ final class AppUpdater {
throw UpdateError.mountFailed("Could not parse hdiutil output")
}
- @discardableResult
- private func unmountDMG(at mountPoint: URL) throws -> Bool {
+ private func unmountDMG(at mountPoint: URL) throws {
let result = try runProcess(
"/usr/bin/hdiutil",
args: ["detach", mountPoint.path, "-force"]
)
- return result.status == 0
+ guard result.status == 0 else {
+ throw UpdateError.unmountFailed(
+ result.stderr.isEmpty ? result.stdout : result.stderr
+ )
+ }
}
// MARK: - Stage
diff --git a/apps/omlx-mac/Sources/Welcome/WelcomeWindow.swift b/apps/omlx-mac/Sources/Welcome/WelcomeWindow.swift
index e552b2aede..66d5d104c1 100644
--- a/apps/omlx-mac/Sources/Welcome/WelcomeWindow.swift
+++ b/apps/omlx-mac/Sources/Welcome/WelcomeWindow.swift
@@ -566,7 +566,7 @@ private struct WelcomeSetupBody: View {
defaultValue: "Default 8000. Change this only if the port is already in use.",
comment: "Sublabel for the port field with the recommended default")
) {
- TextInput(text: $vm.portText, mono: true, width: 96)
+ TextInput(text: $vm.portText, mono: true, width: .controlNarrow)
}
WelcomeDivider()
@@ -615,7 +615,7 @@ private struct WelcomeSetupBody: View {
comment: "Sublabel explaining API key usage")
) {
HStack(spacing: 0) {
- TextInput("welcome.api_key.placeholder", text: $vm.apiKey, placeholder: "sk-omlx-…", isSecure: !keyVisible, mono: true, width: 210)
+ TextInput("welcome.api_key.placeholder", text: $vm.apiKey, placeholder: "sk-omlx-…", isSecure: !keyVisible, mono: true, width: .controlMedium)
Button {
keyVisible.toggle()
} label: {
diff --git a/apps/omlx-mac/Tests/oMLXTests/AppUpdaterTests.swift b/apps/omlx-mac/Tests/oMLXTests/AppUpdaterTests.swift
new file mode 100644
index 0000000000..1b899e0cb1
--- /dev/null
+++ b/apps/omlx-mac/Tests/oMLXTests/AppUpdaterTests.swift
@@ -0,0 +1,64 @@
+import XCTest
+@testable import oMLX
+
+@MainActor
+final class AppUpdaterTests: XCTestCase {
+ private enum TestError: Error, Equatable {
+ case detachFailed
+ case removalFailed
+ }
+
+ func testReadyIsNotifiedOnlyAfterMountedResourcesAreReleased() throws {
+ var events: [String] = []
+
+ try AppUpdater.finishStagedUpdate(
+ detach: { events.append("detach") },
+ removeTemporaryFiles: { events.append("remove temporary files") },
+ notifyReady: { events.append("ready") }
+ )
+
+ XCTAssertEqual(events, [
+ "detach",
+ "remove temporary files",
+ "ready",
+ ])
+ }
+
+ func testDetachFailurePreventsTemporaryRemovalAndReadyNotification() {
+ var events: [String] = []
+
+ XCTAssertThrowsError(
+ try AppUpdater.finishStagedUpdate(
+ detach: {
+ events.append("detach")
+ throw TestError.detachFailed
+ },
+ removeTemporaryFiles: { events.append("remove temporary files") },
+ notifyReady: { events.append("ready") }
+ )
+ ) { error in
+ XCTAssertEqual(error as? TestError, .detachFailed)
+ }
+
+ XCTAssertEqual(events, ["detach"])
+ }
+
+ func testTemporaryRemovalFailurePreventsReadyNotification() {
+ var events: [String] = []
+
+ XCTAssertThrowsError(
+ try AppUpdater.finishStagedUpdate(
+ detach: { events.append("detach") },
+ removeTemporaryFiles: {
+ events.append("remove temporary files")
+ throw TestError.removalFailed
+ },
+ notifyReady: { events.append("ready") }
+ )
+ ) { error in
+ XCTAssertEqual(error as? TestError, .removalFailed)
+ }
+
+ XCTAssertEqual(events, ["detach", "remove temporary files"])
+ }
+}
diff --git a/apps/omlx-mac/Tests/oMLXTests/GlobalSettingsSamplingTests.swift b/apps/omlx-mac/Tests/oMLXTests/GlobalSettingsSamplingTests.swift
index 603bf33a36..46f1d0ce59 100644
--- a/apps/omlx-mac/Tests/oMLXTests/GlobalSettingsSamplingTests.swift
+++ b/apps/omlx-mac/Tests/oMLXTests/GlobalSettingsSamplingTests.swift
@@ -201,4 +201,31 @@ final class GlobalSettingsSamplingTests: XCTestCase {
XCTAssertTrue(str.contains("\"port\":9000"))
XCTAssertFalse(str.contains("sampling_"))
}
+
+ func testServerDecodesAudioUploadSize() throws {
+ let json = """
+ {
+ "server": {
+ "host": "127.0.0.1",
+ "port": 8080,
+ "log_level": "info",
+ "server_aliases": [],
+ "max_audio_upload_size": "500MB"
+ }
+ }
+ """.data(using: .utf8)!
+
+ let dto = try decoder.decode(GlobalSettingsDTO.self, from: json)
+ XCTAssertEqual(dto.server.maxAudioUploadSize, "500MB")
+ }
+
+ func testPatchEncodesAudioUploadSizeAsFlatSnakeCaseKey() throws {
+ var patch = GlobalSettingsPatch()
+ patch.maxAudioUploadSize = "1GB"
+
+ let data = try encoder.encode(patch)
+ let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
+
+ XCTAssertEqual(json["max_audio_upload_size"] as? String, "1GB")
+ }
}
diff --git a/apps/omlx-mac/Tests/oMLXTests/MenubarControllerModelsTests.swift b/apps/omlx-mac/Tests/oMLXTests/MenubarControllerModelsTests.swift
index 80390f3134..df3dcaa440 100644
--- a/apps/omlx-mac/Tests/oMLXTests/MenubarControllerModelsTests.swift
+++ b/apps/omlx-mac/Tests/oMLXTests/MenubarControllerModelsTests.swift
@@ -222,6 +222,10 @@ final class MenubarControllerModelsTests: XCTestCase {
dflashSsdCacheAvailable: nil,
mtpCompatible: nil,
mtpCompatibilityReason: nil,
+ qwen4PleSsdOffloadSupported: nil,
+ qwen4PleSsdOffloadForced: nil,
+ qwen4PleResidentBytes: nil,
+ qwen4PleMmapBytes: nil,
virtual: virtual,
settings: nil
)
diff --git a/apps/omlx-mac/Tests/oMLXTests/ModelSettingsScreenVMTests.swift b/apps/omlx-mac/Tests/oMLXTests/ModelSettingsScreenVMTests.swift
index 846391e81a..b92e7c829f 100644
--- a/apps/omlx-mac/Tests/oMLXTests/ModelSettingsScreenVMTests.swift
+++ b/apps/omlx-mac/Tests/oMLXTests/ModelSettingsScreenVMTests.swift
@@ -23,6 +23,18 @@ final class ModelSettingsScreenVMTests: XCTestCase {
)
}
+ func testLightningMtpAllowsTurboQuantInWorkingProfile() {
+ let vm = ModelSettingsScreenVM()
+ vm.mtpEnabled = true
+ vm.turboquantKvEnabled = true
+
+ XCTAssertNil(vm.mtpConflictReason)
+
+ let settings = vm.currentSettingsDict()
+ XCTAssertEqual(settings["mtp_enabled"]?.value as? Bool, true)
+ XCTAssertEqual(settings["turboquant_kv_enabled"]?.value as? Bool, true)
+ }
+
func testVlmMtpDraftModelOptionsIncludeQwenMtpConfigType() {
let vm = ModelSettingsScreenVM()
vm.modelID = "Qwopus3.6-35B-A3B-v1-4bit-MLXVLM-Target"
@@ -225,6 +237,29 @@ final class ModelSettingsScreenVMTests: XCTestCase {
XCTAssertFalse(vm.isQwen35AnePrefillModel)
}
+ func testQwen4SsdOffloadWireKeysAndCompatibility() throws {
+ let vm = ModelSettingsScreenVM()
+ vm.model = makeModel(id: "qwen4", configModelType: "qwen4_exp")
+ XCTAssertTrue(vm.isQwen4Exp)
+
+ let decoder = JSONDecoder()
+ decoder.keyDecodingStrategy = .convertFromSnakeCase
+ let dto = try decoder.decode(
+ ModelSettingsDTO.self,
+ from: Data(#"{"qwen4_ple_ssd_offload":true}"#.utf8)
+ )
+ XCTAssertEqual(dto.qwen4PleSsdOffload, true)
+
+ var patch = ModelSettingsPatch()
+ patch.qwen4PleSsdOffload = true
+ let encoder = JSONEncoder()
+ encoder.keyEncodingStrategy = .convertToSnakeCase
+ let object = try JSONSerialization.jsonObject(
+ with: encoder.encode(patch)
+ ) as? [String: Any]
+ XCTAssertEqual(object?["qwen4_ple_ssd_offload"] as? Bool, true)
+ }
+
func testQwenAneSettingsDecodeFromServerAndEncodeForPatch() throws {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
@@ -328,6 +363,10 @@ final class ModelSettingsScreenVMTests: XCTestCase {
dflashSsdCacheAvailable: nil,
mtpCompatible: nil,
mtpCompatibilityReason: nil,
+ qwen4PleSsdOffloadSupported: nil,
+ qwen4PleSsdOffloadForced: nil,
+ qwen4PleResidentBytes: nil,
+ qwen4PleMmapBytes: nil,
virtual: nil,
settings: nil
)
diff --git a/apps/omlx-mac/Tests/oMLXTests/ModelsScreenSortingTests.swift b/apps/omlx-mac/Tests/oMLXTests/ModelsScreenSortingTests.swift
index 1cacb58bca..7efa85b341 100644
--- a/apps/omlx-mac/Tests/oMLXTests/ModelsScreenSortingTests.swift
+++ b/apps/omlx-mac/Tests/oMLXTests/ModelsScreenSortingTests.swift
@@ -64,6 +64,10 @@ final class ModelsScreenSortingTests: XCTestCase {
dflashSsdCacheAvailable: nil,
mtpCompatible: nil,
mtpCompatibilityReason: nil,
+ qwen4PleSsdOffloadSupported: nil,
+ qwen4PleSsdOffloadForced: nil,
+ qwen4PleResidentBytes: nil,
+ qwen4PleMmapBytes: nil,
virtual: nil,
settings: nil
)
diff --git a/apps/omlx-mac/Tests/oMLXTests/ServerScreenVMStorageDiffTests.swift b/apps/omlx-mac/Tests/oMLXTests/ServerScreenVMStorageDiffTests.swift
index 5d2c59c030..144490c4de 100644
--- a/apps/omlx-mac/Tests/oMLXTests/ServerScreenVMStorageDiffTests.swift
+++ b/apps/omlx-mac/Tests/oMLXTests/ServerScreenVMStorageDiffTests.swift
@@ -228,4 +228,24 @@ final class ServerScreenVMStorageDiffTests: XCTestCase {
XCTAssertFalse(vm.autoStartOnLaunch)
}
+
+ func testAudioUploadSizeValidation() {
+ for valid in ["1B", "100MB", "1.5GB", "1024"] {
+ XCTAssertTrue(ServerScreenVM.isValidAudioUploadSize(valid), valid)
+ }
+ for invalid in ["", "0MB", "-1MB", "100 MB", "infMB", "bogus"] {
+ XCTAssertFalse(ServerScreenVM.isValidAudioUploadSize(invalid), invalid)
+ }
+ }
+
+ func testAudioUploadChangeEnablesApply() {
+ let services = makeServices(basePath: "/Users/Fido/.omlx",
+ modelDir: "/Users/Fido/.omlx/models")
+ let vm = ServerScreenVM()
+ vm.basePathText = "/Users/Fido/.omlx"
+ vm.modelDirTexts = ["/Users/Fido/.omlx/models"]
+ vm.maxAudioUploadSizeText = "250MB"
+
+ XCTAssertTrue(vm.hasPendingServerChanges(services: services))
+ }
}
diff --git a/apps/omlx-mac/oMLX.xcodeproj/project.pbxproj b/apps/omlx-mac/oMLX.xcodeproj/project.pbxproj
index 5d08e07a02..acba9ef7b9 100644
--- a/apps/omlx-mac/oMLX.xcodeproj/project.pbxproj
+++ b/apps/omlx-mac/oMLX.xcodeproj/project.pbxproj
@@ -133,6 +133,7 @@
DBB000000000000000000108 /* ModelSettingsScreenVMTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCC000000000000000000108 /* ModelSettingsScreenVMTests.swift */; };
DBB000000000000000000113 /* PerformanceScreenVMTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCC000000000000000000113 /* PerformanceScreenVMTests.swift */; };
DBB000000000000000000114 /* UpdateInstallerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCC000000000000000000114 /* UpdateInstallerTests.swift */; };
+ DBB000000000000000000115 /* AppUpdaterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCC000000000000000000115 /* AppUpdaterTests.swift */; };
EBB000000000000000000001 /* MarkdownUI in Frameworks */ = {isa = PBXBuildFile; productRef = ECC000000000000000000001 /* MarkdownUI */; };
/* End PBXBuildFile section */
@@ -277,6 +278,7 @@
DCC000000000000000000108 /* ModelSettingsScreenVMTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelSettingsScreenVMTests.swift; sourceTree = ""; };
DCC000000000000000000113 /* PerformanceScreenVMTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerformanceScreenVMTests.swift; sourceTree = ""; };
DCC000000000000000000114 /* UpdateInstallerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateInstallerTests.swift; sourceTree = ""; };
+ DCC000000000000000000115 /* AppUpdaterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppUpdaterTests.swift; sourceTree = ""; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -347,6 +349,7 @@
DCC000000000000000000108 /* ModelSettingsScreenVMTests.swift */,
DCC000000000000000000113 /* PerformanceScreenVMTests.swift */,
DCC000000000000000000114 /* UpdateInstallerTests.swift */,
+ DCC000000000000000000115 /* AppUpdaterTests.swift */,
);
path = oMLXTests;
sourceTree = "";
@@ -815,6 +818,7 @@
DBB000000000000000000108 /* ModelSettingsScreenVMTests.swift in Sources */,
DBB000000000000000000113 /* PerformanceScreenVMTests.swift in Sources */,
DBB000000000000000000114 /* UpdateInstallerTests.swift in Sources */,
+ DBB000000000000000000115 /* AppUpdaterTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --git a/benchmarks/bench_m5_sorted_gather_chunk.py b/benchmarks/bench_m5_sorted_gather_chunk.py
new file mode 100644
index 0000000000..6dd29f7c77
--- /dev/null
+++ b/benchmarks/bench_m5_sorted_gather_chunk.py
@@ -0,0 +1,135 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Per-layer MoE prefill cost vs chunk width on M5 (sorted gather_qmm paths).
+
+Reproduces one routed-expert MoE layer at a configurable geometry (default:
+Qwen4-Exp, 512 experts / top-10 / hidden 2560 / inter 640, 4-bit gs64 with
+the fused gate+up layout) and times the sorted SwitchGLU path for several
+prefill chunk widths under three dispatch modes:
+
+- ``sorted`` raw ``sorted_indices=True`` (NAX rhs kernel; corrupt past
+ 32768 rows on mlx <= 0.32.2, timed for reference only)
+- ``unsorted`` what the pre-segmenting M5 reroute did past the row cap
+- ``segmented`` the oMLX reroute with <=32768-row sorted slices
+
+Prints ms per layer call and derived tokens/s so the chunk-width policy can
+be judged on numbers. Run from a checkout with the reroute installed::
+
+ python benchmarks/bench_m5_sorted_gather_chunk.py --chunks 2048 4096 8192
+"""
+
+from __future__ import annotations
+
+import argparse
+import time
+
+import mlx.core as mx
+from mlx_lm.models.switch_layers import _gather_sort, _scatter_unsort
+
+import omlx.patches.m5_gather_qmm as reroute
+
+
+def _build(experts, hidden, inter, bits, group_size, key):
+ k1, k2 = mx.random.split(key)
+ gate_up = mx.random.normal((experts, 2 * inter, hidden), key=k1) * 0.02
+ down = mx.random.normal((experts, hidden, inter), key=k2) * 0.02
+ gu = mx.quantize(gate_up.astype(mx.bfloat16), group_size=group_size, bits=bits)
+ dn = mx.quantize(down.astype(mx.bfloat16), group_size=group_size, bits=bits)
+ mx.eval(*gu, *dn)
+ return gu, dn
+
+
+def _layer(x, inds, gu, dn, bits, group_size, sorted_flag, gather_qmm):
+ x5 = mx.expand_dims(x, (-2, -3))
+ xs, idx, inv = _gather_sort(x5, inds)
+ h = gather_qmm(
+ xs,
+ *gu,
+ rhs_indices=idx,
+ transpose=True,
+ group_size=group_size,
+ bits=bits,
+ sorted_indices=sorted_flag,
+ )
+ g, u = mx.split(h, 2, axis=-1)
+ a = mx.sigmoid(g) * g * u
+ y = gather_qmm(
+ a,
+ *dn,
+ rhs_indices=idx,
+ transpose=True,
+ group_size=group_size,
+ bits=bits,
+ sorted_indices=sorted_flag,
+ )
+ return _scatter_unsort(y, inv, inds.shape).squeeze(-2)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--experts", type=int, default=512)
+ ap.add_argument("--topk", type=int, default=10)
+ ap.add_argument("--hidden", type=int, default=2560)
+ ap.add_argument("--inter", type=int, default=640)
+ ap.add_argument("--bits", type=int, default=4)
+ ap.add_argument("--group-size", type=int, default=64)
+ ap.add_argument("--chunks", type=int, nargs="+", default=[2048, 4096, 8192])
+ ap.add_argument("--iters", type=int, default=5)
+ ap.add_argument("--modes", nargs="+", default=["sorted", "unsorted", "segmented"])
+ args = ap.parse_args()
+
+ reroute.apply_m5_gather_qmm_workaround()
+ raw = reroute._original_gather_qmm or mx.gather_qmm
+ print(
+ f"mlx {mx.__version__} device {mx.device_info().get('device_name')} "
+ f"sorted rhs kernel defective: {reroute._sorted_gather_qmm_defective()}"
+ )
+ gu, dn = _build(
+ args.experts,
+ args.hidden,
+ args.inter,
+ args.bits,
+ args.group_size,
+ mx.random.key(0),
+ )
+ print(
+ f"geometry: E={args.experts} topk={args.topk} hidden={args.hidden} "
+ f"inter={args.inter} q{args.bits}/gs{args.group_size}"
+ )
+ print(f"{'chunk':>6} {'rows':>7} {'mode':>10} {'ms/layer':>9} {'tok/s':>10}")
+ for chunk in args.chunks:
+ kx, ki = mx.random.split(mx.random.key(chunk))
+ x = mx.random.normal((1, chunk, args.hidden), key=kx).astype(mx.bfloat16)
+ inds = mx.random.randint(0, args.experts, (1, chunk, args.topk), key=ki)
+ inds = inds.astype(mx.uint32)
+ mx.eval(x, inds)
+ for mode in args.modes:
+ if mode == "sorted":
+ sorted_flag, gather = True, raw
+ elif mode == "unsorted":
+ sorted_flag, gather = False, raw
+ elif mode == "segmented":
+ sorted_flag, gather = True, reroute._gather_qmm_rerouted
+ else:
+ raise SystemExit(f"unknown mode {mode}")
+
+ def fn(x=x, inds=inds, sorted_flag=sorted_flag, gather=gather):
+ return _layer(
+ x, inds, gu, dn, args.bits, args.group_size, sorted_flag, gather
+ )
+
+ for _ in range(2):
+ mx.eval(fn())
+ mx.synchronize()
+ t0 = time.perf_counter()
+ for _ in range(args.iters):
+ mx.eval(fn())
+ mx.synchronize()
+ ms = (time.perf_counter() - t0) / args.iters * 1e3
+ print(
+ f"{chunk:>6} {chunk * args.topk:>7} {mode:>10} {ms:>9.2f} "
+ f"{chunk / ms * 1e3:>10.0f}"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/bench_qwen4_qsa_sparse_gqa.py b/benchmarks/bench_qwen4_qsa_sparse_gqa.py
new file mode 100644
index 0000000000..c4e99ec627
--- /dev/null
+++ b/benchmarks/bench_qwen4_qsa_sparse_gqa.py
@@ -0,0 +1,146 @@
+#!/usr/bin/env python3
+"""Benchmark Qwen4 direct-index sparse GQA against the gathered MLX path."""
+
+# SPDX-License-Identifier: Apache-2.0
+
+from __future__ import annotations
+
+import argparse
+import statistics
+import time
+
+import mlx.core as mx
+import numpy as np
+
+from omlx.custom_kernels.glm_moe_dsa import fast
+from omlx.patches import mlx_vlm_qwen4_exp_compat as compat
+
+
+compat.apply_mlx_vlm_qwen4_exp_compat_patch()
+from mlx_vlm.models.qwen4_exp import qsa_fast # noqa: E402
+
+
+def _time(call, repetitions: int):
+ samples = []
+ output = None
+ for _ in range(repetitions):
+ start = time.perf_counter()
+ output = call()
+ mx.eval(output)
+ mx.synchronize()
+ samples.append((time.perf_counter() - start) * 1000.0)
+ return samples, output
+
+
+def _portable(queries, keys, values, selected, selected_valid):
+ query_tokens = queries.shape[2]
+ selected_keys = qsa_fast._batch_gather_tokens(
+ keys.transpose(0, 2, 1, 3), selected
+ ).transpose(0, 1, 3, 2, 4)
+ selected_values = qsa_fast._batch_gather_tokens(
+ values.transpose(0, 2, 1, 3), selected
+ ).transpose(0, 1, 3, 2, 4)
+ grouped_queries = queries.transpose(0, 2, 1, 3).reshape(
+ 1, query_tokens, 2, 12, 256
+ )
+ scores = (
+ grouped_queries.astype(mx.float32)
+ @ selected_keys.astype(mx.float32).swapaxes(-1, -2)
+ ) / (256**0.5)
+ scores = mx.where(
+ selected_valid[:, :, None, None, :],
+ scores,
+ mx.finfo(scores.dtype).min,
+ )
+ probabilities = mx.softmax(scores, axis=-1).astype(queries.dtype)
+ return (probabilities @ selected_values).reshape(
+ 1, query_tokens, 24, 256
+ )
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--key-tokens", type=int, default=50_000)
+ parser.add_argument("--query-tokens", type=int, default=128)
+ parser.add_argument("--repetitions", type=int, default=10)
+ parser.add_argument("--seed", type=int, default=927)
+ args = parser.parse_args()
+ if not fast.is_native_available() or not fast.has_symbol(
+ "qwen4_qsa_sparse_gqa_attention"
+ ):
+ raise SystemExit("rebuild glm_moe_dsa with the Qwen4 sparse GQA ABI")
+ if args.key_tokens - args.query_tokens < 2048:
+ raise SystemExit("benchmark needs at least 2,048 visible prefix tokens")
+
+ mx.random.seed(args.seed)
+ rng = np.random.default_rng(args.seed)
+ q_offset = args.key_tokens - args.query_tokens
+ queries = mx.random.normal((1, 24, args.query_tokens, 256)).astype(mx.bfloat16)
+ keys = mx.random.normal((1, 2, args.key_tokens, 256)).astype(mx.bfloat16)
+ values = mx.random.normal((1, 2, args.key_tokens, 256)).astype(mx.bfloat16)
+ blocks = []
+ expanded = []
+ expanded_valid = []
+ for row in range(args.query_tokens):
+ complete = (q_offset + row + 1) // 4
+ chosen = np.sort(rng.choice(complete, size=512, replace=False)).astype(
+ np.uint32
+ )
+ blocks.append(chosen)
+ tokens = (chosen[:, None] * 4 + np.arange(4, dtype=np.uint32)).reshape(-1)
+ tail_start = complete * 4
+ tail = np.arange(tail_start, q_offset + row + 1, dtype=np.uint32)
+ expanded.append(np.pad(np.concatenate((tokens, tail)), (0, 3 - len(tail))))
+ expanded_valid.append(
+ np.concatenate(
+ (
+ np.ones(2048 + len(tail), dtype=np.bool_),
+ np.zeros(3 - len(tail), dtype=np.bool_),
+ )
+ )
+ )
+ selected_blocks = mx.array(np.stack(blocks)[None])
+ selected_tokens = mx.array(np.stack(expanded)[None])
+ valid = mx.array(np.stack(expanded_valid)[None])
+ selected_tokens = mx.where(valid, selected_tokens, 0)
+ mx.eval(queries, keys, values, selected_blocks, selected_tokens)
+
+ reference = _portable(queries, keys, values, selected_tokens, valid)
+ mx.eval(reference)
+ for key_tile, dimension_tile in ((128, 32), (64, 64)):
+ def call(key_tile=key_tile, dimension_tile=dimension_tile):
+ return fast.qwen4_qsa_sparse_gqa_attention(
+ queries,
+ keys,
+ values,
+ selected_blocks[:, None],
+ 256**-0.5,
+ q_offset,
+ key_tile=key_tile,
+ dimension_tile=dimension_tile,
+ )
+
+ mx.eval(call())
+ samples, native = _time(call, args.repetitions)
+ native_rows = native.transpose(0, 2, 1, 3)
+ error = mx.abs(native_rows.astype(mx.float32) - reference.astype(mx.float32))
+ mx.eval(error)
+ print(
+ f"native BK={key_tile} DC={dimension_tile}: "
+ f"median={statistics.median(samples):.3f} ms "
+ f"min={min(samples):.3f} max={max(samples):.3f} "
+ f"max_error={float(mx.max(error).item()):.7f}"
+ )
+
+ samples, _ = _time(
+ lambda: _portable(queries, keys, values, selected_tokens, valid),
+ args.repetitions,
+ )
+ print(
+ f"portable gathered: median={statistics.median(samples):.3f} ms "
+ f"min={min(samples):.3f} max={max(samples):.3f}"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/qwen35_ane_gdn_split_poc.py b/benchmarks/qwen35_ane_gdn_split_poc.py
index 1a7e098853..0649b85499 100644
--- a/benchmarks/qwen35_ane_gdn_split_poc.py
+++ b/benchmarks/qwen35_ane_gdn_split_poc.py
@@ -76,30 +76,47 @@ def gpu_call():
gpu_seconds, gpu_samples, reference = _measure(gpu_call, args.repeats)
prepared = []
+ prepared_outputs = set()
+ qkv, z, _, _ = linears
+ z_outputs = int(z.weight.shape[0])
+ qkv_outputs = int(qkv.weight.shape[0])
+ total_outputs = z_outputs + qkv_outputs
for fraction in args.fractions:
+ ane_outputs = patch._recurrent_safe_gdn_ane_outputs(
+ z_outputs, qkv_outputs, fraction, 128
+ )
+ if not ane_outputs or ane_outputs in prepared_outputs:
+ continue
config = patch._AneGDNConfig(args.tokens, fraction, 8, True)
value = patch._prepare_gdn_for_bank(gdn, config)
if value is not None:
state, dense0, dense1 = value
- prepared.append((fraction, state, dense0, dense1))
+ prepared.append(
+ (fraction, ane_outputs / total_outputs, state, dense0, dense1)
+ )
+ prepared_outputs.add(ane_outputs)
+ if not prepared:
+ raise RuntimeError("No recurrent-safe GDN ANE width could be prepared")
mx.eval(
- *[entry[2] for entry in prepared],
*[entry[3] for entry in prepared],
+ *[entry[4] for entry in prepared],
)
banks = patch._compile_dual_banks(
- [entry[2] for entry in prepared],
[entry[3] for entry in prepared],
+ [entry[4] for entry in prepared],
args.tokens,
)
if banks is None:
raise RuntimeError("GDN calibration bank failed to compile")
models0, models1, programs = banks
results = []
- for index, (fraction, _state, _, _) in enumerate(prepared):
+ for index, (requested_fraction, effective_fraction, _state, _, _) in enumerate(
+ prepared
+ ):
for cpu_fraction in args.cpu_fractions:
config = patch._AneGDNConfig(
args.tokens,
- fraction,
+ requested_fraction,
8,
True,
cpu_fraction=cpu_fraction,
@@ -118,7 +135,8 @@ def gpu_call():
lambda: patch._gdn_backend_exact(gdn, x), args.repeats
)
result = {
- "ane_fraction": fraction,
+ "ane_fraction": effective_fraction,
+ "requested_ane_fraction": requested_fraction,
"cpu_fraction": cpu_fraction,
"median_ms": seconds * 1000,
"samples_ms": [sample * 1000 for sample in samples],
diff --git a/docs/TESTING.md b/docs/TESTING.md
new file mode 100644
index 0000000000..d6a53d5fdc
--- /dev/null
+++ b/docs/TESTING.md
@@ -0,0 +1,15 @@
+# QSA reservation tests
+
+Run `python -m pytest -q tests/test_qwen4_qsa_reservation_integration.py tests/test_qwen4_qsa_reserved_capacity.py` to check QSA capacity reservations.
+
+The integration tests cover restored-prefix lengths with boundary snapshots enabled and disabled, the first allocation after cache restoration, and prefill/decode output equivalence using a small Qwen4 model.
+
+Related regression suites are `test_qwen4_qsa_incremental_cache.py`, `test_qwen4_qsa_decode_gather.py`, and `test_prefill_oom_graceful.py`.
+
+# Prefill memory accounting tests
+
+Run `python -m pytest -q tests/test_prefill_transient_tracker.py tests/test_prefill_oom_graceful.py` to check retained versus reclaimed overhead, configured chunk sizes, and abort-cap enforcement. The loop tests run a small initialized MLX model with controlled footprint readings through external and chunked prefill; they do not load a checkpoint.
+
+# Prefix cache completion tests
+
+Run `python -m pytest -q tests/test_scheduler.py tests/test_scheduler_boundary_completion.py tests/test_prefix_cache_gdn_split.py` to check cache-freshness admission and completed boundary recovery. The completion tests use a small initialized Qwen3.5 hybrid model and the real BatchGenerator, then compare restored-prefix logits with a fresh forward pass. They cover embedded snapshots, GDN sidecars, off-boundary completion, and unknown or inconsistent cache positions.
diff --git a/docs/experimental/qwen35_ane_prefill.md b/docs/experimental/qwen35_ane_prefill.md
index 37854af93d..c5e8131841 100644
--- a/docs/experimental/qwen35_ane_prefill.md
+++ b/docs/experimental/qwen35_ane_prefill.md
@@ -9,11 +9,15 @@ by default.
At the default 53% MLP request, alignment gives the two ANEs 26.5% of gate and
up channels each (52.9% total) and leaves 47.1% on GPU. A native merge applies
SwiGLU without materializing the full gate/up result. The GDN z+qkv input
-projection is split 50/50 between the ANEs and GPU by default. Optional FP16
-CPU sharing can take independent gate/up, down-projection, and residual GDN
-qkv slices; all three branches run in parallel and are merged natively. GDN
-recurrence, b/a and output projections, normalization, embeddings, and logits
-remain on GPU.
+projection uses a precision-aware split: ANE computes only the token-local z
+gate, while every recurrent qkv row stays off the approximate ANE path and
+normally uses checkpoint-precision GPU projection. The configured GDN fraction
+is a ceiling; a wider request is capped at the model's z boundary (37.5% on the
+validated Qwen3.6/3.8 27B layout). Optional FP16 CPU sharing can take
+independent gate/up, down-projection, and residual GDN qkv slices; all three
+branches run in parallel and are merged natively.
+GDN recurrence, b/a and output projections, normalization, embeddings, and
+logits remain on GPU.
## Requirements and limits
@@ -26,8 +30,9 @@ remain on GPU.
weights are retained for every GPU suffix. The down projection may use
compatible affine q2/q4/q5/q6/q8 weights.
- Optional GDN acceleration accepts affine q4/q5/q6/q8 projections with group
- size 64 or 128. Mixed q4/q5/q6/q8 layouts are supported when the ANE prefix
- covers the full z projection, leaving a homogeneous qkv suffix on the GPU.
+ size 64 or 128. The z width must align exactly to the selected single- or
+ dual-ANE output granularity. Mixed q4/q5/q6/q8 layouts are supported because
+ ANE covers exactly z and leaves a homogeneous qkv suffix on the GPU.
- CPU sharing requires a separately preprocessed FP16 clone of the model. It
does not modify or dequantize the source checkpoint in place. The CPU GDN
slice applies only to residual qkv outputs after the ANE prefix; z remains
@@ -47,7 +52,9 @@ remain on GPU.
The implementation uses undocumented APIs and can stop working after a macOS
update. It also requantizes the selected weights to per-output-channel INT8,
-so it is an approximate acceleration path rather than bit-exact inference.
+so ANE results are approximate rather than bit-exact. The approximation is
+kept out of recurrent GDN qkv state specifically to prevent long-context error
+accumulation; the MLP and token-local GDN z branches remain approximate.
On NAX GPUs (the M5 family) the hybrid GPU suffix runs on dedicated NAX
qmm kernels (group sizes 64 and 128), which resolves the prefill regression
@@ -120,8 +127,9 @@ The macOS app exposes the same controls under **Models → model settings →
Advanced → Experimental → Qwen ANE Prefill** for detected Qwen3.5/3.6/3.8
models. Enabling or changing a control reloads a resident model when the
working profile is applied. The editor starts from the measured 2,048-token,
-53% MLP / 50% GDN, dual-ANE, 64/48-layer configuration above; the feature
-itself stays off until explicitly enabled.
+53% MLP / 50% GDN ceiling, dual-ANE, 64/48-layer configuration above; the
+feature itself stays off until explicitly enabled. The runtime reports when it
+caps that requested GDN fraction at the model-specific z boundary.
The split tuner calibrates five workload controls: MLP gate/up work on ANE,
MLP gate/up work on CPU, MLP down-projection work on CPU, GDN work on ANE, and
@@ -203,6 +211,24 @@ FP16 gate/up and GDN rows, the down-projection GPU suffix, and bounded
materialization scratch. This projected size participates in the normal memory
guard before the model begins loading.
+## Recurrent-safe GDN validation
+
+The current z-only policy was selected from a controlled 32K comparison on
+`Qwen3.6-27B-oQ4e-mtp`. A 50% ANE slice that included 2,048 of 10,240 recurrent
+qkv rows deterministically failed ordering and exact-format summarization tasks
+that distinguished the GPU baseline. Capping ANE at all 6,144 z rows (37.5% of
+z+qkv) restored all four baseline-discriminating retrieval, ordering, code, and
+summary checks. Six varied generations all ended normally without a suspected
+loop, and their output hashes repeated exactly in a second pass.
+
+The precision cap preserved nearly all of the useful acceleration. A direct
+2,048-token GDN projection measured 9.61 ms for z-only ANE/GPU versus 14.73 ms
+on GPU (1.53x). In an isolated real-server 32K cold/cache-hit pair, subtracting
+the hit time from the cold time gave about 507 prompt tok/s, approximately 22%
+above the matched 416 tok/s GPU baseline and slightly above the earlier 50%
+full-GDN result. These figures are specific to the tested M3 Ultra and model,
+but the recurrent-versus-token-local boundary is enforced for every model.
+
## Qwen3.8-27B-oQ4e validation
The group-size-64 and mixed q4/q5 path was validated on an M3 Ultra with
@@ -263,6 +289,8 @@ version lacked the anticipated backend-registration function. Those older
4.80-4.96 second "GDN" figures therefore measured the MLP-only path and are
superseded. The compatibility hook now intercepts mlx-vlm's projection helper,
and the benchmark verifies 64 MLP plus 48 GDN procedure dispatches per prompt.
+The throughput-only GDN measurements below predate the recurrent-safe z-only
+policy and are retained as implementation history, not current tuning advice.
With the corrected hook and the retuned 53% MLP / 50% GDN request, the final
deterministic paired run measured:
@@ -295,19 +323,22 @@ fixed, so it was useful for validating branch timing but did not predict the
best complete application split. The subsequent in-app five-way tuner jointly
selected 45% MLP on ANE, 45% GDN on ANE, 14% gate/up on CPU, 20% down on CPU,
and 13% GDN qkv on CPU. It measured 517.9 prompt tok/s, 45.8% above its GPU-only
-baseline. The application result is authoritative for the reference M3 Ultra;
-the standalone table above illustrates why CPU GDN must be tuned jointly rather
-than accepted or rejected from an isolated fixed-split sweep. Hidden-state and
-last-token logit cosine similarity at the validated CPU GDN point were 0.999989
-and 0.999999, and top-1 matched the GPU path.
+baseline. That application result was authoritative for the earlier
+throughput study; the current tuner fixes the ANE portion at z and only tunes
+the residual CPU/GPU qkv split. The standalone table illustrates why CPU GDN
+must be tuned jointly rather than accepted or rejected from an isolated
+fixed-split sweep. Hidden-state and last-token logit cosine similarity at the
+validated CPU GDN point were 0.999989 and 0.999999, and top-1 matched the GPU
+path.
That layout issues two ANE evaluations for each accelerated operation: one
request pinned to each physical ANE. Across 64 MLP and 48 GDN operations this
is 224 evaluations per 2,048-token prompt, or 112 sequential evaluations on
each ANE. The two evaluations belonging to an operation are launched in
-parallel. Gate and up are already combined in each MLP evaluation, and z and
-qkv are already combined in each GDN evaluation, so splitting either group
-would increase dispatch count.
+parallel. Gate and up are already combined in each MLP evaluation. In the
+historical GDN layout, z and qkv were also combined in each evaluation; the
+current layout compiles the same number of GDN procedures but ends each one at
+the z boundary.
A single unpinned procedure containing the same 55% MLP slice took 57.90 ms
for a representative layer, versus 41.51 ms for the two pinned evaluations.
@@ -317,7 +348,8 @@ procedure across both ANEs. Replacing the two short-lived dispatch threads
with persistent high-priority workers also regressed throughput, so the
existing paired launch was retained.
-Profiling identified 53% MLP / 50% GDN as the best measured split. At 50% GDN,
+Historical profiling identified 53% MLP / 50% GDN as the best measured split.
+At 50% GDN,
the ANE and GPU GDN portions take about 10.1 ms and 9.95 ms respectively. The
53% MLP point measured 4.4768 s in its seven-run tuning pass, versus 4.5172 s
at 54% and 4.5370 s at 55%. Larger 60% banks were slower, and a monolithic
diff --git a/docs/heterogeneous-cluster.md b/docs/heterogeneous-cluster.md
index 31af302c50..7951ba573d 100644
--- a/docs/heterogeneous-cluster.md
+++ b/docs/heterogeneous-cluster.md
@@ -77,9 +77,9 @@ contiguous-layer and physical-memory checks may adjust or refuse.
## Current platform reality
This design no longer depends on treating CUDA support as an unofficial MLX
-experiment. [MLX 0.32.0 officially supports CUDA 12 and CUDA 13](https://ml-explore.github.io/mlx/build/html/install.html),
+experiment. [MLX 0.32.2 officially supports CUDA 12 and CUDA 13](https://ml-explore.github.io/mlx/build/html/install.html),
including Linux ARM wheels relevant to DGX Spark. oMLX already pins
-`mlx==0.32.0` in this branch.
+`mlx==0.32.2` in this branch.
MLX provides several distributed transports:
@@ -337,7 +337,7 @@ The Mac application remains a Metal distribution. The GUI bootstrap creates a
headless Linux ARM64 environment using the official CUDA wheel set:
```text
-mlx[cuda13]==0.32.0
+mlx[cuda13]==0.32.2
same pinned MLX-LM revision
same oMLX cluster/runtime code
no macOS app, Metal-only extension, or Mac authorization dependency
diff --git a/docs/laguna-mlxfast-port-correctness.md b/docs/laguna-mlxfast-port-correctness.md
index 4875d1e6f0..36ba0c994b 100644
--- a/docs/laguna-mlxfast-port-correctness.md
+++ b/docs/laguna-mlxfast-port-correctness.md
@@ -39,7 +39,7 @@ migration `4799830` and are not part of the current model surface).
- **Optimization:** compile `[sigmoid(logits), -(sigmoid(logits)+bias)]` into one kernel (four elementwise launches per router call, 39 per token).
- **Token-exactness issue:** a compiled function returning TWO outputs that consume the same `sigmoid(a)` intermediate is bit-exact on the GitHub `macos-14-arm64` runner but diverges from eager at ULP on an M3 Ultra (5.96e-8–2.38e-7, deterministic, isolated to the multi-consumer shape). Single-output compiled fusions reusing the same sigmoid are bit-exact, so the trigger is the two-output shape on affected GPUs. It feeds `argpartition` expert selection — a ULP flip at a near-tie boundary changes WHICH experts are gathered (a different forward, not a small perturbation), i.e. the challenge's own documented correctness cliff ("Rank is the wrong metric").
- **Mitigation:** kept eager in the port for portable token exactness; bounded numerical parity is pinned by `test_two_output_compiled_tail_is_numerically_close` on both bit-exact and ULP-divergent GPUs.
-- **Hardware and MLX-version dependence:** property of MLX 0.32.0 compiled kernels varies by Apple GPU; re-verify across supported GPU generations after any MLX bump.
+- **Hardware and MLX-version dependence:** property of MLX 0.32.2 compiled kernels varies by Apple GPU; re-verify across supported GPU generations after any MLX bump.
### C2 — `logits_last_only` head slicing is ULP-divergent (frame divergence)
diff --git a/omlx/_hf_download_worker.py b/omlx/_hf_download_worker.py
new file mode 100644
index 0000000000..8beeb7027c
--- /dev/null
+++ b/omlx/_hf_download_worker.py
@@ -0,0 +1,70 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Isolated Hugging Face HTTP download worker.
+
+The parent sends one JSON request over stdin. Keeping the token off argv and
+setting ``HF_HUB_DISABLE_XET`` before importing huggingface_hub isolates the
+fallback transport choice from the long-running oMLX server process.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from collections.abc import Callable
+from typing import Any
+
+_ALLOWED_DOWNLOAD_KWARGS = {
+ "endpoint",
+ "etag_timeout",
+ "ignore_patterns",
+ "local_dir",
+ "repo_id",
+ "token",
+}
+
+
+def _download_without_xet(
+ kwargs: dict[str, Any],
+ download_fn: Callable[..., Any] | None = None,
+) -> None:
+ """Run snapshot_download after disabling xet before its first import."""
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
+ if download_fn is None:
+ from huggingface_hub import snapshot_download
+
+ download_fn = snapshot_download
+ download_fn(**kwargs)
+
+
+def _read_request() -> dict[str, Any]:
+ request = json.load(sys.stdin)
+ if not isinstance(request, dict) or not isinstance(request.get("kwargs"), dict):
+ raise ValueError("Invalid download worker request")
+ kwargs = request["kwargs"]
+ unknown = set(kwargs) - _ALLOWED_DOWNLOAD_KWARGS
+ if unknown:
+ names = ", ".join(sorted(unknown))
+ raise ValueError(f"Unsupported download arguments: {names}")
+ return kwargs
+
+
+def main() -> int:
+ try:
+ kwargs = _read_request()
+ _download_without_xet(kwargs)
+ except Exception as error: # noqa: BLE001 - report child failure to parent
+ response = {
+ "ok": False,
+ "error_type": type(error).__name__,
+ "message": str(error),
+ }
+ print(json.dumps(response), flush=True)
+ return 1
+
+ print(json.dumps({"ok": True}), flush=True)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/omlx/_version.py b/omlx/_version.py
index 3ca6e74483..364e7baed0 100644
--- a/omlx/_version.py
+++ b/omlx/_version.py
@@ -1 +1 @@
-__version__ = "0.6.3rc3"
+__version__ = "0.6.4"
diff --git a/omlx/admin/ane_tuning.py b/omlx/admin/ane_tuning.py
index 98fab936b0..30598c8a58 100644
--- a/omlx/admin/ane_tuning.py
+++ b/omlx/admin/ane_tuning.py
@@ -776,21 +776,27 @@ def _profile_refinement(
float(gdn.get("ane1_eval_ns", 0.0)),
) / gdn_ops
gpu_time = float(gdn.get("gpu_completion_ns", 0.0)) / gdn_ops
- widths = [float(gdn_fraction)]
+ # The production GDN path precision-caps ANE at the token-local z
+ # projection. Its structural floor is therefore also its only real
+ # ANE width; larger requested fractions compile the same z-only slice.
+ effective_gdn_fraction = (
+ float(gdn_floor) if gdn_floor is not None else float(gdn_fraction)
+ )
+ widths = [effective_gdn_fraction]
times = [ane_time]
- # Below the structural floor a fraction compiles 0 GDN procedures at
- # apply time, so the refinement must not pick one (issue #2899).
- gdn_grid = sorted(
- set([*_gdn_fraction_grid(), 0.35, 0.40, 0.465, 0.50, 0.53, 0.55])
+ gdn_grid = (
+ [float(gdn_floor)]
+ if gdn_floor is not None
+ else sorted(
+ set([*_gdn_fraction_grid(), 0.35, 0.40, 0.465, 0.50, 0.53, 0.55])
+ )
)
- if gdn_floor is not None:
- gdn_grid = [value for value in gdn_grid if value >= gdn_floor]
choices = [gdn_grid or [float(gdn_fraction)]]
if cpu_gdn_fraction > 0:
widths.append(cpu_gdn_fraction)
times.append(float(gdn.get("cpu_completion_ns", 0.0)) / gdn_ops)
choices.append(_cpu_gdn_fraction_grid())
- widths.append(1.0 - float(gdn_fraction) - cpu_gdn_fraction)
+ widths.append(1.0 - effective_gdn_fraction - cpu_gdn_fraction)
times.append(gpu_time)
choices.append([widths[-1]])
balanced = _balanced_fractions(widths, times, choices)
@@ -1025,7 +1031,11 @@ def _calibrate_fused_components_sync(
calibration_threads = _CALIBRATION_CPU_THREADS
fractions = _fused_fraction_grid()
cpu_fractions = _fused_cpu_fraction_grid() if cpu_supported else [0.0]
- gdn_fractions = _gdn_fraction_grid() if gdn is not None else []
+ gdn_fractions = (
+ [float(run.gdn_floor)]
+ if gdn is not None and run.gdn_floor is not None
+ else []
+ )
gdn_cpu_fractions = _cpu_gdn_fraction_grid() if gdn_cpu_supported else [0.0]
run.phase = "compiling_calibration"
@@ -1723,8 +1733,8 @@ def _calibrate_components_sync(
if value is not None:
state, dense0, dense1 = value
prepared.append(("mlp", fraction, state, dense0, dense1))
- if gdn is not None:
- for fraction in fractions:
+ if gdn is not None and run.gdn_floor is not None:
+ for fraction in [float(run.gdn_floor)]:
config = patch._AneGDNConfig(
run.request.sequence_length, fraction, 8, dual_ane
)
@@ -1766,7 +1776,9 @@ def _calibrate_components_sync(
fraction for fraction in fractions if ("mlp", fraction) in ane_models
]
valid_gdn_fractions = [
- fraction for fraction in fractions if ("gdn", fraction) in ane_models
+ fraction
+ for fraction in ([float(run.gdn_floor)] if run.gdn_floor is not None else [])
+ if ("gdn", fraction) in ane_models
]
# The loaded private programs own their compiled weight blobs. Release the
# much larger temporary FP32 source slices before allocating CPU variants.
diff --git a/omlx/admin/context_benchmark.py b/omlx/admin/context_benchmark.py
index efc01bc740..c4bccd74d8 100644
--- a/omlx/admin/context_benchmark.py
+++ b/omlx/admin/context_benchmark.py
@@ -244,7 +244,7 @@ def _guard_ready(scheduler: Any) -> bool:
def _make_fits(scheduler: Any) -> Callable[[int], bool]:
def fits(n: int) -> bool:
try:
- scheduler.preflight_or_raise(num_prompt_tokens=n)
+ scheduler.preflight_or_raise(num_prompt_tokens=n, text_only=True)
except PrefillMemoryExceededError:
return False
return True
diff --git a/omlx/admin/hf_downloader.py b/omlx/admin/hf_downloader.py
index b14ddb69e6..d426af5c8b 100644
--- a/omlx/admin/hf_downloader.py
+++ b/omlx/admin/hf_downloader.py
@@ -1,24 +1,29 @@
# SPDX-License-Identifier: Apache-2.0
"""HuggingFace model downloader for oMLX admin panel.
-Downloads models from HuggingFace Hub using huggingface_hub's snapshot_download
-with directory-size-based progress polling.
+Downloads models with huggingface_hub's snapshot_download, filesystem-based
+progress polling, and an isolated HTTP retry for xet transport failures.
"""
import asyncio
import enum
+import errno
+import json
import logging
+import os
import shutil
+import signal
+import sys
import time
import uuid
+from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Callable, Optional
+from typing import Optional
from urllib.parse import urlparse
from huggingface_hub import HfApi, hf_hub_download, snapshot_download
from huggingface_hub.utils import (
- EntryNotFoundError,
GatedRepoError,
HfHubHTTPError,
RepositoryNotFoundError,
@@ -38,6 +43,26 @@
# Seconds with no download progress before considering the download stalled.
_STALL_TIMEOUT = 300
+# A separate first-activity deadline catches xet token/CAS hangs that never
+# create a payload file. Once any write is observed, the more tolerant stall
+# timeout above applies so slow but active connections are left alone.
+_STARTUP_STALL_TIMEOUT = 120
+
+_PROGRESS_POLL_INTERVAL = 2
+_SUBPROCESS_TERMINATE_TIMEOUT = 5
+
+_NON_XET_WORKER_MODULE = "omlx._hf_download_worker"
+
+_XET_ERROR_MARKERS = (
+ "cas service error",
+ "cas client",
+ "hf_xet",
+ "reqwestmiddleware",
+ "xet-read-token",
+ "xet storage",
+ "/xet-",
+)
+
# Cache of (configured_endpoint -> resolved_endpoint) so we only probe each
# endpoint once per process lifetime. Mirrors like hf-mirror.com permanently
# 308-redirect to huggingface.co when accessed from IPs outside their region;
@@ -112,6 +137,56 @@ class _DownloadCancelled(Exception):
"""Raised inside the download thread to interrupt a cancelled download."""
+class _DownloadStalledError(RuntimeError):
+ """Raised when a monitored transfer stops making observable progress."""
+
+ def __init__(self, *, transport: str, phase: str, timeout: float):
+ self.transport = transport
+ self.phase = phase
+ self.timeout = timeout
+ if phase == "startup":
+ detail = "no initial download activity"
+ else:
+ detail = "no download progress"
+ super().__init__(f"{transport} download stalled: {detail} for {timeout:g}s")
+
+
+class _NonXetDownloadError(RuntimeError):
+ """Raised when the isolated HTTP fallback process fails."""
+
+
+@dataclass(frozen=True)
+class _DownloadActivity:
+ """Filesystem signals used to distinguish slow transfers from stalls."""
+
+ file_count: int = 0
+ logical_size: int = 0
+ allocated_size: int = 0
+ latest_mtime_ns: int = 0
+
+
+def _is_xet_transport_error(error: BaseException) -> bool:
+ """Return whether an exception identifies the xet/CAS transport path."""
+ if isinstance(
+ error,
+ (
+ _DownloadCancelled,
+ _DownloadStalledError,
+ GatedRepoError,
+ RepositoryNotFoundError,
+ ),
+ ):
+ return False
+ if isinstance(error, OSError) and error.errno in {
+ errno.EACCES,
+ errno.ENOSPC,
+ errno.EROFS,
+ }:
+ return False
+ detail = f"{type(error).__name__}: {error}".lower()
+ return any(marker in detail for marker in _XET_ERROR_MARKERS)
+
+
def _make_cancellable_tqdm(should_cancel: Callable[[], bool]) -> type:
"""Build a tqdm subclass that aborts the download when cancelled.
@@ -607,6 +682,8 @@ def __init__(
self._progress_tasks: dict[str, asyncio.Task] = {}
self._on_complete = on_complete
self._cancelled: set[str] = set()
+ self._stalled: dict[str, _DownloadStalledError] = {}
+ self._fallback_processes: dict[str, asyncio.subprocess.Process] = {}
self._download_sem = asyncio.Semaphore(1)
@property
@@ -887,23 +964,59 @@ async def _run_download(self, task_id: str, hf_token: str) -> None:
f"Dry run failed for {task.repo_id}: {e}. {detail}"
)
- # Start progress polling
self._progress_tasks[task_id] = asyncio.create_task(
self._poll_progress(task_id, target_dir)
)
- # Run snapshot_download in a thread (blocking call). Cancel
- # reaches the thread two ways: the cancellable tqdm raises on
- # the next chunk of the http_get path, and abort_xet_session()
- # (called by cancel/stall/shutdown) unwinds the xet path with
- # a RuntimeError (the thread itself can't be force-killed).
- await asyncio.to_thread(
- snapshot_download,
- **dl_kwargs,
- tqdm_class=_make_cancellable_tqdm(
- lambda: task_id in self._cancelled
- ),
- )
+ xet_error: Exception | None = None
+ try:
+ # Awaiting the thread here is intentional: after a stall,
+ # fallback cannot start until abort_xet_session() has made
+ # the original writer return.
+ await asyncio.to_thread(
+ snapshot_download,
+ **dl_kwargs,
+ tqdm_class=_make_cancellable_tqdm(
+ lambda: task_id in self._cancelled
+ ),
+ )
+ except Exception as error:
+ stalled = self._stalled.pop(task_id, None)
+ if stalled is not None:
+ xet_error = stalled
+ elif _is_xet_transport_error(error):
+ xet_error = error
+ else:
+ raise
+ else:
+ xet_error = self._stalled.pop(task_id, None)
+
+ if xet_error is not None:
+ if task_id in self._cancelled:
+ raise _DownloadCancelled()
+ logger.warning(
+ "Xet download failed for %s: %s. "
+ "Retrying once over HTTP.",
+ task.repo_id,
+ xet_error,
+ )
+ progress_task = self._progress_tasks.pop(task_id, None)
+ if progress_task and not progress_task.done():
+ progress_task.cancel()
+ self._progress_tasks[task_id] = asyncio.create_task(
+ self._poll_progress(task_id, target_dir)
+ )
+ try:
+ await self._run_http_fallback(task_id, dl_kwargs)
+ except asyncio.CancelledError:
+ raise
+ except Exception as error:
+ fallback_error = self._stalled.pop(task_id, None) or error
+ raise _NonXetDownloadError(
+ "Xet download failed "
+ f"({xet_error}); HTTP fallback also failed "
+ f"({fallback_error})"
+ ) from error
# Check if cancelled while downloading
if task_id in self._cancelled:
@@ -961,9 +1074,7 @@ async def _run_download(self, task_id: str, hf_token: str) -> None:
)
logger.error(f"Gated repo access denied: {task.repo_id}")
except Exception as e:
- # Skip when already cancelled (the xet abort surfaces here as a
- # RuntimeError) or already FAILED by the stall detector, whose
- # error message would otherwise be clobbered by the abort error.
+ # Do not clobber an earlier terminal error or a user cancellation.
if (
task_id not in self._cancelled
and task.status != DownloadStatus.FAILED
@@ -976,10 +1087,79 @@ async def _run_download(self, task_id: str, hf_token: str) -> None:
progress_task = self._progress_tasks.pop(task_id, None)
if progress_task and not progress_task.done():
progress_task.cancel()
+ self._stalled.pop(task_id, None)
# Remove from active tasks
self._active_tasks.pop(task_id, None)
+ async def _run_http_fallback(
+ self,
+ task_id: str,
+ dl_kwargs: dict,
+ ) -> None:
+ env = os.environ.copy()
+ env["HF_HUB_DISABLE_XET"] = "1"
+ payload = json.dumps({"kwargs": dl_kwargs}).encode()
+ process = await asyncio.create_subprocess_exec(
+ sys.executable,
+ "-m",
+ _NON_XET_WORKER_MODULE,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=env,
+ )
+ self._fallback_processes[task_id] = process
+
+ try:
+ stdout, _ = await process.communicate(input=payload)
+ try:
+ response = json.loads(stdout.decode())
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
+ raise _NonXetDownloadError(
+ f"HTTP fallback process exited with code {process.returncode}"
+ ) from error
+ if process.returncode != 0 or not response.get("ok"):
+ error_type = response.get("error_type", "DownloadError")
+ message = response.get("message", "unknown error")
+ raise _NonXetDownloadError(f"{error_type}: {message}")
+ except asyncio.CancelledError:
+ await self._stop_subprocess(process)
+ raise
+ finally:
+ self._fallback_processes.pop(task_id, None)
+
+ @staticmethod
+ async def _stop_subprocess(process: asyncio.subprocess.Process) -> None:
+ if process.returncode is not None:
+ return
+ try:
+ process.send_signal(signal.SIGINT)
+ except ProcessLookupError:
+ return
+ try:
+ await asyncio.wait_for(
+ process.wait(),
+ timeout=_SUBPROCESS_TERMINATE_TIMEOUT,
+ )
+ return
+ except TimeoutError:
+ try:
+ process.terminate()
+ except ProcessLookupError:
+ return
+ try:
+ await asyncio.wait_for(
+ process.wait(),
+ timeout=_SUBPROCESS_TERMINATE_TIMEOUT,
+ )
+ except TimeoutError:
+ try:
+ process.kill()
+ except ProcessLookupError:
+ return
+ await process.wait()
+
async def _poll_progress(self, task_id: str, target_dir: Path) -> None:
"""Poll the target directory to estimate download progress.
@@ -993,59 +1173,96 @@ async def _poll_progress(self, task_id: str, target_dir: Path) -> None:
if task is None:
return
- last_size = 0
- last_activity_at = time.time()
+ last_activity = self._get_download_activity(target_dir)
+ last_activity_at = time.monotonic()
+ observed_activity = False
try:
while task.status == DownloadStatus.DOWNLOADING:
- await asyncio.sleep(2)
+ await asyncio.sleep(_PROGRESS_POLL_INTERVAL)
if task.status != DownloadStatus.DOWNLOADING:
break
- current_size = self._get_dir_size(target_dir)
- task.downloaded_size = current_size
+ activity = self._get_download_activity(target_dir)
+ task.downloaded_size = activity.logical_size
if task.total_size > 0:
# Cap at 99% until snapshot_download confirms completion
task.progress = min(
- (current_size / task.total_size) * 100, 99.0
+ (activity.logical_size / task.total_size) * 100,
+ 99.0,
)
- # Activity detection: size change OR file mtime change
- if current_size != last_size:
- last_size = current_size
- last_activity_at = time.time()
- else:
- latest_mtime = self._get_latest_mtime(target_dir)
- if latest_mtime > last_activity_at:
- last_activity_at = latest_mtime
-
- # Stall detection
- if (
- current_size > 0
- and (time.time() - last_activity_at) > _STALL_TIMEOUT
- ):
- task.status = DownloadStatus.FAILED
- task.error = (
- f"Download stalled: no progress for {_STALL_TIMEOUT}s. "
- "Try retrying the download."
+ if activity != last_activity:
+ # A zero-byte temp file or metadata touch is not payload
+ # progress. APFS allocated blocks increase when bytes are
+ # actually written, including into sparse/preallocated files.
+ if activity.allocated_size > last_activity.allocated_size:
+ observed_activity = True
+ last_activity = activity
+ last_activity_at = time.monotonic()
+ continue
+
+ timeout = (
+ _STALL_TIMEOUT
+ if observed_activity
+ else _STARTUP_STALL_TIMEOUT
+ )
+ if time.monotonic() - last_activity_at > timeout:
+ phase = "active" if observed_activity else "startup"
+ process = self._fallback_processes.get(task_id)
+ transport = "HTTP fallback" if process else "Xet"
+ stalled = _DownloadStalledError(
+ transport=transport,
+ phase=phase,
+ timeout=timeout,
)
+ self._stalled[task_id] = stalled
logger.warning(
- f"Download stalled for {task.repo_id} "
- f"(task_id={task_id})"
+ "%s for %s (task_id=%s)",
+ stalled,
+ task.repo_id,
+ task_id,
)
- # Cancel the snapshot_download thread. The task cancel
- # only unblocks the awaiting coroutine; aborting the xet
- # session is what actually reaps a wedged transfer thread.
- active_task = self._active_tasks.get(task_id)
- if active_task and not active_task.done():
- active_task.cancel()
- abort_xet_session()
+ if process is not None:
+ await self._stop_subprocess(process)
+ else:
+ abort_xet_session()
break
except asyncio.CancelledError:
pass
+ @staticmethod
+ def _get_download_activity(path: Path) -> _DownloadActivity:
+ """Return size, allocation, and mtime signals including Hub temp files."""
+ if not path.exists():
+ return _DownloadActivity()
+ file_count = 0
+ logical_size = 0
+ allocated_size = 0
+ latest_mtime_ns = 0
+ try:
+ for file_path in path.rglob("*"):
+ if not file_path.is_file():
+ continue
+ try:
+ stat = file_path.stat()
+ except OSError:
+ continue
+ file_count += 1
+ logical_size += stat.st_size
+ allocated_size += getattr(stat, "st_blocks", 0) * 512
+ latest_mtime_ns = max(latest_mtime_ns, stat.st_mtime_ns)
+ except OSError:
+ pass
+ return _DownloadActivity(
+ file_count=file_count,
+ logical_size=logical_size,
+ allocated_size=allocated_size,
+ latest_mtime_ns=latest_mtime_ns,
+ )
+
@staticmethod
def _get_latest_mtime(path: Path) -> float:
"""Return the most recent modification time of any file in a directory."""
diff --git a/omlx/admin/i18n/en.json b/omlx/admin/i18n/en.json
index f42172c732..b1b708735c 100644
--- a/omlx/admin/i18n/en.json
+++ b/omlx/admin/i18n/en.json
@@ -519,6 +519,9 @@
"settings.advanced.gdn_sidecar_state_precision_bf16": "BF16",
"settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)",
"settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)",
+ "settings.advanced.uploads": "Uploads",
+ "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size",
+ "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
"settings.advanced.streaming": "Streaming",
"settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode",
"settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.",
@@ -608,6 +611,9 @@
"modal.model_settings.enable_thinking_hint": "Enable reasoning/thinking mode for this model.",
"modal.model_settings.enable_thinking_default": "Using model default",
"modal.model_settings.enable_thinking_reset": "Reset to model default",
+ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)",
+ "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.",
+ "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.",
"modal.model_settings.thinking_budget": "Thinking Budget",
"modal.model_settings.thinking_budget_hint": "Limit thinking tokens for reasoning models. Forces end of thinking when exceeded.",
"modal.model_settings.thinking_budget_placeholder": "e.g. 4096",
diff --git a/omlx/admin/i18n/es.json b/omlx/admin/i18n/es.json
index ecd5756c36..6b26d6cd59 100644
--- a/omlx/admin/i18n/es.json
+++ b/omlx/admin/i18n/es.json
@@ -519,6 +519,9 @@
"settings.advanced.gdn_sidecar_state_precision_bf16": "BF16",
"settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)",
"settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)",
+ "settings.advanced.uploads": "Uploads",
+ "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size",
+ "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
"settings.advanced.streaming": "Streaming",
"settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode",
"settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.",
@@ -608,6 +611,9 @@
"modal.model_settings.enable_thinking_hint": "Habilitar modo de razonamiento/pensamiento para este modelo.",
"modal.model_settings.enable_thinking_default": "Usando el predeterminado del modelo",
"modal.model_settings.enable_thinking_reset": "Restablecer al predeterminado del modelo",
+ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)",
+ "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.",
+ "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.",
"modal.model_settings.thinking_budget": "Presupuesto de Pensamiento",
"modal.model_settings.thinking_budget_hint": "Limitar tokens de pensamiento para modelos de razonamiento. Fuerza el fin del pensamiento al excederse.",
"modal.model_settings.thinking_budget_placeholder": "ej. 4096",
diff --git a/omlx/admin/i18n/fr.json b/omlx/admin/i18n/fr.json
index a05e4c9b46..ef70826afc 100644
--- a/omlx/admin/i18n/fr.json
+++ b/omlx/admin/i18n/fr.json
@@ -519,6 +519,9 @@
"settings.advanced.gdn_sidecar_state_precision_bf16": "BF16",
"settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)",
"settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)",
+ "settings.advanced.uploads": "Uploads",
+ "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size",
+ "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
"settings.advanced.streaming": "Streaming",
"settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode",
"settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.",
@@ -608,6 +611,9 @@
"modal.model_settings.enable_thinking_hint": "Activez le mode raisonnement/réflexion pour ce modèle.",
"modal.model_settings.enable_thinking_default": "Utilisant la valeur par défaut du modèle",
"modal.model_settings.enable_thinking_reset": "Réinitialiser à la valeur par défaut du modèle",
+ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)",
+ "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.",
+ "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.",
"modal.model_settings.thinking_budget": "Budget de réflexion",
"modal.model_settings.thinking_budget_hint": "Limitez les tokens de réflexion pour les modèles de raisonnement. Force la fin de la réflexion lorsque dépassé.",
"modal.model_settings.thinking_budget_placeholder": "par ex. 4096",
diff --git a/omlx/admin/i18n/ja.json b/omlx/admin/i18n/ja.json
index 87412f77ce..9cfe98aff7 100644
--- a/omlx/admin/i18n/ja.json
+++ b/omlx/admin/i18n/ja.json
@@ -519,6 +519,9 @@
"settings.advanced.gdn_sidecar_state_precision_bf16": "BF16",
"settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)",
"settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)",
+ "settings.advanced.uploads": "Uploads",
+ "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size",
+ "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
"settings.advanced.streaming": "Streaming",
"settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode",
"settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.",
@@ -608,6 +611,9 @@
"modal.model_settings.enable_thinking_hint": "このモデルの推論/思考モードを設定します。",
"modal.model_settings.enable_thinking_default": "モデルのデフォルトを使用中",
"modal.model_settings.enable_thinking_reset": "モデルのデフォルトに戻す",
+ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)",
+ "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.",
+ "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.",
"modal.model_settings.thinking_budget": "思考トークン制限",
"modal.model_settings.thinking_budget_hint": "推論モデルの思考トークン数を制限します。超過時に思考を強制終了します。",
"modal.model_settings.thinking_budget_placeholder": "例: 4096",
diff --git a/omlx/admin/i18n/ko.json b/omlx/admin/i18n/ko.json
index ce69bb27df..68254c74ef 100644
--- a/omlx/admin/i18n/ko.json
+++ b/omlx/admin/i18n/ko.json
@@ -519,6 +519,9 @@
"settings.advanced.gdn_sidecar_state_precision_bf16": "BF16",
"settings.advanced.gdn_sidecar_state_precision_int8": "Int8(행 단위)",
"settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8(행 단위)",
+ "settings.advanced.uploads": "Uploads",
+ "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size",
+ "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
"settings.advanced.streaming": "Streaming",
"settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode",
"settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.",
@@ -608,6 +611,9 @@
"modal.model_settings.enable_thinking_hint": "이 모델의 추론/thinking 모드를 설정합니다.",
"modal.model_settings.enable_thinking_default": "모델 기본값 사용 중",
"modal.model_settings.enable_thinking_reset": "모델 기본값으로 재설정",
+ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram 오프로딩 (Qwen4 전용)",
+ "modal.model_settings.qwen4_ple_ssd_offload_hint": "큰 PLE N-gram 테이블을 SSD에 두고 필요한 행만 읽습니다. 메모리를 절약하지만 컨텍스트가 바뀐 뒤 prefill이 느려질 수 있습니다.",
+ "modal.model_settings.qwen4_ple_ssd_offload_forced": "resident 로드가 설정된 모델 메모리 한도를 초과하므로 이 옵션이 필요합니다.",
"modal.model_settings.thinking_budget": "Thinking 토큰 제한",
"modal.model_settings.thinking_budget_hint": "추론 모델의 thinking 토큰 수를 제한합니다. 초과 시 thinking을 강제 종료합니다.",
"modal.model_settings.thinking_budget_placeholder": "예: 4096",
diff --git a/omlx/admin/i18n/pt-BR.json b/omlx/admin/i18n/pt-BR.json
index 5a2caf9328..53a8596f9c 100644
--- a/omlx/admin/i18n/pt-BR.json
+++ b/omlx/admin/i18n/pt-BR.json
@@ -519,6 +519,9 @@
"settings.advanced.gdn_sidecar_state_precision_bf16": "BF16",
"settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)",
"settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)",
+ "settings.advanced.uploads": "Uploads",
+ "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size",
+ "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
"settings.advanced.streaming": "Streaming",
"settings.advanced.sse_keepalive_mode": "Modo SSE Keepalive",
"settings.advanced.sse_keepalive_mode_hint": "Como as conexões HTTP de streaming permanecem ativas durante prefills longos. 'Chunk' é mais compatível (padrão). Mude para 'Comment' para o formato legado ': keep-alive', ou 'Off' para desativar.",
@@ -608,6 +611,9 @@
"modal.model_settings.enable_thinking_hint": "Ativar modo de raciocínio/thinking para este modelo.",
"modal.model_settings.enable_thinking_default": "Usando padrão do modelo",
"modal.model_settings.enable_thinking_reset": "Redefinir para padrão do modelo",
+ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)",
+ "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.",
+ "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.",
"modal.model_settings.thinking_budget": "Orçamento de Raciocínio",
"modal.model_settings.thinking_budget_hint": "Limitar tokens de raciocínio para modelos de reasoning. Força o fim do raciocínio quando excedido.",
"modal.model_settings.thinking_budget_placeholder": "ex: 4096",
diff --git a/omlx/admin/i18n/ru.json b/omlx/admin/i18n/ru.json
index de4ce8a69c..a4ae7312cf 100644
--- a/omlx/admin/i18n/ru.json
+++ b/omlx/admin/i18n/ru.json
@@ -519,6 +519,9 @@
"settings.advanced.gdn_sidecar_state_precision_bf16": "BF16",
"settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)",
"settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)",
+ "settings.advanced.uploads": "Uploads",
+ "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size",
+ "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
"settings.advanced.streaming": "Стриминг",
"settings.advanced.sse_keepalive_mode": "Режим keep-alive для SSE",
"settings.advanced.sse_keepalive_mode_hint": "Определяет, как потоковые HTTP-соединения остаются активными во время долгого prefill. «Chunk» наиболее совместим (по умолчанию). Переключитесь на «Comment» для устаревшего формата «: keep-alive» или выберите «Off», чтобы отключить keep-alive.",
@@ -608,6 +611,9 @@
"modal.model_settings.enable_thinking_hint": "Включить режим рассуждения для этой модели.",
"modal.model_settings.enable_thinking_default": "Использовать значение модели по умолчанию",
"modal.model_settings.enable_thinking_reset": "Сбросить к значению модели по умолчанию",
+ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)",
+ "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.",
+ "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.",
"modal.model_settings.thinking_budget": "Бюджет мышления",
"modal.model_settings.thinking_budget_hint": "Ограничьте число токенов мышления для моделей рассуждения. Принудительно завершает мышление при превышении лимита.",
"modal.model_settings.thinking_budget_placeholder": "например, 4096",
diff --git a/omlx/admin/i18n/zh-TW.json b/omlx/admin/i18n/zh-TW.json
index 787e339a29..2cf42fad4a 100644
--- a/omlx/admin/i18n/zh-TW.json
+++ b/omlx/admin/i18n/zh-TW.json
@@ -519,6 +519,9 @@
"settings.advanced.gdn_sidecar_state_precision_bf16": "BF16",
"settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)",
"settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)",
+ "settings.advanced.uploads": "Uploads",
+ "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size",
+ "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
"settings.advanced.streaming": "串流",
"settings.advanced.sse_keepalive_mode": "SSE 保持連線模式",
"settings.advanced.sse_keepalive_mode_hint": "串流 HTTP 連線在長時間預填充期間如何保持連線。「Chunk」相容性最佳(預設)。切換為「Comment」使用舊版 ': keep-alive' 格式,或「關閉」以停用。",
@@ -608,6 +611,9 @@
"modal.model_settings.enable_thinking_hint": "設定此模型的推理/思考模式。",
"modal.model_settings.enable_thinking_default": "使用模型預設值",
"modal.model_settings.enable_thinking_reset": "重設為模型預設值",
+ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)",
+ "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.",
+ "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.",
"modal.model_settings.thinking_budget": "思考 Token 限制",
"modal.model_settings.thinking_budget_hint": "限制推理模型的思考 Token 數量,超出時強制結束思考",
"modal.model_settings.thinking_budget_placeholder": "例如 4096",
diff --git a/omlx/admin/i18n/zh.json b/omlx/admin/i18n/zh.json
index a898c5b9ae..a09a9b86ef 100644
--- a/omlx/admin/i18n/zh.json
+++ b/omlx/admin/i18n/zh.json
@@ -519,6 +519,9 @@
"settings.advanced.gdn_sidecar_state_precision_bf16": "BF16",
"settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)",
"settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)",
+ "settings.advanced.uploads": "Uploads",
+ "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size",
+ "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.",
"settings.advanced.streaming": "流式传输",
"settings.advanced.sse_keepalive_mode": "SSE 保活模式",
"settings.advanced.sse_keepalive_mode_hint": "流式 HTTP 连接在长时间预填充期间如何保持连接。'Chunk' 兼容性最好(默认)。切换为 'Comment' 使用旧版 ': keep-alive' 格式,或 'Off' 禁用。",
@@ -608,6 +611,9 @@
"modal.model_settings.enable_thinking_hint": "设置此模型的推理/思考模式。",
"modal.model_settings.enable_thinking_default": "使用模型默认值",
"modal.model_settings.enable_thinking_reset": "重置为模型默认值",
+ "modal.model_settings.qwen4_ple_ssd_offload": "SSD N-gram Offload (Qwen4 only)",
+ "modal.model_settings.qwen4_ple_ssd_offload_hint": "Keep the large PLE N-gram table on SSD and read only the required rows. This saves memory but can slow prefill after context changes.",
+ "modal.model_settings.qwen4_ple_ssd_offload_forced": "Required because resident loading exceeds the configured model-memory limit.",
"modal.model_settings.thinking_budget": "思考 Token 限制",
"modal.model_settings.thinking_budget_hint": "限制推理模型的思考 Token 数量,超出时强制结束思考",
"modal.model_settings.thinking_budget_placeholder": "例如 4096",
diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py
index 30781c6732..479b00e104 100644
--- a/omlx/admin/routes.py
+++ b/omlx/admin/routes.py
@@ -28,14 +28,17 @@
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, ConfigDict, Field, field_validator
from ..api.markitdown import MARKITDOWN_MODEL_ID, markitdown_model_visible
from ..api.openai_models import _coerce_tool_call_arguments
from ..api.utils import _try_parse_json
from ..model_discovery import model_display_name as _model_display_name
from ..model_profiles import EXCLUDED_FROM_PROFILES
-from ..model_settings import merge_chat_template_kwargs
+from ..model_settings import (
+ MAX_LIGHTNING_MTP_DRAFT_TOKENS,
+ merge_chat_template_kwargs,
+)
from ..settings import BURST_DECODE_MODES, SubKeyEntry, burst_decode_env
from ..utils.release_check import normalize_update_channel, select_latest_release
from ..websearch import (
@@ -112,6 +115,8 @@ class CacheProbeRequest(BaseModel):
class ModelSettingsRequest(BaseModel):
"""Request model for updating per-model settings."""
+ model_config = ConfigDict(extra="forbid")
+
model_alias: str | None = None
model_type_override: str | None = None
max_context_window: int | None = None
@@ -129,11 +134,18 @@ class ModelSettingsRequest(BaseModel):
ttl_seconds: int | None = None
index_cache_freq: int | None = None
enable_thinking: bool | None = None
+ # Keep thinking blocks in historical turns (None = auto, True when the
+ # template supports it). Mirrors ModelSettings.preserve_thinking.
+ preserve_thinking: bool | None = None
+ qwen4_ple_ssd_offload: bool | None = None
thinking_budget_enabled: bool | None = None
thinking_budget_tokens: int | None = None
+ # MTP draft tokens per cycle for legacy MTP (None = adaptive default).
+ mtp_num_draft_tokens: int | None = None
# TurboQuant KV cache (mlx-vlm backend)
turboquant_kv_enabled: bool | None = None
turboquant_kv_bits: float | None = None
+ turboquant_skip_last: bool | None = None
# Private Qwen3.5/3.6/3.8 ANE/GPU fixed-shape prefill
qwen35_ane_prefill_enabled: bool | None = None
qwen35_ane_prefill_sequence_length: int | None = None
@@ -247,6 +259,7 @@ class GlobalSettingsRequest(BaseModel):
burst_decode_mode: str | None = None # "off" / "light" / "balanced" / "aggressive"
preserve_mid_system_cache: bool | None = None
distributed_inference_enabled: bool | None = None
+ max_audio_upload_size: str | None = None
# Model settings
model_dirs: list[str] | None = None
@@ -673,8 +686,9 @@ def _mtp_compat_for_model(model_info: dict) -> tuple[bool, str]:
converter actually preserved the MTP tensors, using the loader's
``_checkpoint_has_mtp_weights`` so native nextn layouts
(``model.layers..*``, e.g. GLM-5.2) count as
- present (issue #2326). Default mlx-lm converters strip ``mtp.*``;
- PR 990 ships a separate path that keeps them.
+ present (issue #2326). Qwen4-Exp uses its narrower runtime detector,
+ which accepts only embedded ``mtp.*`` tensors. Default mlx-lm converters
+ strip ``mtp.*``; PR 990 ships a separate path that keeps them.
"""
import json
from pathlib import Path
@@ -702,7 +716,14 @@ def _mtp_compat_for_model(model_info: dict) -> tuple[bool, str]:
model_type = cfg.get("model_type")
if not _has_mtp_heads(cfg):
return False, "model has no MTP heads in config"
- if not _is_mtp_compatible(cfg, model_type):
+ # qwen4_exp (Qwen3.8 Flash Next) attaches its Lightning MTP head through
+ # the dedicated VLM path in omlx.utils.model_loading (vendored mlx-vlm
+ # qwen4_exp model + mlx_lm_mtp dispatch patch) and never goes through the
+ # mlx-lm ``_is_mtp_compatible`` whitelist, which gates the generic
+ # text-model patch. Mirroring the runtime, the admin gate accepts
+ # qwen4_exp and relies on the embedded ``mtp.*`` weight check below —
+ # the same condition the runtime path uses.
+ if model_type != "qwen4_exp" and not _is_mtp_compatible(cfg, model_type):
return False, (
f"model_type={model_type!r} is not on the MTP whitelist "
"(supported: qwen3_5*, qwen3_6*, deepseek_v4*, glm_moe_dsa, "
@@ -718,6 +739,11 @@ def _mtp_compat_for_model(model_info: dict) -> tuple[bool, str]:
"MTPLX side-car detected but not imported. Import it to "
"merge the MTP head into the checkpoint index."
)
+ if model_type == "qwen4_exp":
+ return False, (
+ "Qwen4-Exp Lightning MTP requires embedded mtp.* tensors; "
+ "native nextn layers are not supported by its dedicated runtime."
+ )
return False, (
"Config declares MTP layers but the weight files contain neither "
"mtp.* tensors nor native nextn layers. Re-convert from HF with a "
@@ -1878,6 +1904,15 @@ async def list_models(is_admin: bool = Depends(require_admin)):
# Get engine pool status
status = engine_pool.get_status()
models_status = status.get("models", [])
+ residency_ceiling = int(status.get("final_ceiling", 0) or 0)
+ fallback_ceiling = getattr(engine_pool, "_fallback_admission_ceiling", None)
+ if callable(fallback_ceiling):
+ try:
+ candidate = fallback_ceiling()
+ if isinstance(candidate, (int, float)) and candidate > 0:
+ residency_ceiling = int(candidate)
+ except Exception: # noqa: BLE001
+ pass
# Get all model settings
all_settings = settings_manager.get_all_settings() if settings_manager else {}
@@ -1912,6 +1947,33 @@ async def list_models(is_admin: bool = Depends(require_admin)):
is_paroquant, paroquant_reason = _paroquant_compat_for_model(model_info)
compat_ok, compat_reason = _dflash_compat_for_model(model_info)
mtp_compat_ok, mtp_compat_reason = _mtp_compat_for_model(model_info)
+ qwen4_ple_ssd_offload_supported = False
+ qwen4_ple_ssd_offload_forced = False
+ qwen4_resident_bytes = 0
+ qwen4_mmap_bytes = 0
+ if (model_info.get("config_model_type") or "").replace(
+ "-", "_"
+ ).lower() == "qwen4_exp":
+ try:
+ from ..patches.mlx_vlm_qwen4_exp_compat.residency import (
+ qwen4_exp_residency_estimate,
+ )
+
+ estimate = qwen4_exp_residency_estimate(
+ model_info.get("model_path", "")
+ )
+ qwen4_ple_ssd_offload_supported = estimate.supported
+ qwen4_ple_ssd_offload_forced = estimate.force_ssd_offload(
+ residency_ceiling
+ )
+ qwen4_resident_bytes = estimate.resident_bytes
+ qwen4_mmap_bytes = estimate.mmap_bytes
+ except (OSError, TypeError, ValueError):
+ logger.debug(
+ "Could not inspect Qwen4-Exp PLE residency for %s",
+ model_id,
+ exc_info=True,
+ )
model_data = {
"id": model_id,
@@ -1962,6 +2024,10 @@ async def list_models(is_admin: bool = Depends(require_admin)):
"dflash_ssd_cache_available": dflash_ssd_cache_available,
"mtp_compatible": mtp_compat_ok,
"mtp_compatibility_reason": mtp_compat_reason,
+ "qwen4_ple_ssd_offload_supported": qwen4_ple_ssd_offload_supported,
+ "qwen4_ple_ssd_offload_forced": qwen4_ple_ssd_offload_forced,
+ "qwen4_ple_resident_bytes": qwen4_resident_bytes,
+ "qwen4_ple_mmap_bytes": qwen4_mmap_bytes,
"is_paroquant": is_paroquant,
"paroquant_reason": paroquant_reason,
}
@@ -2286,6 +2352,13 @@ async def update_model_settings(
)
if "enable_thinking" in sent:
current_settings.enable_thinking = request.enable_thinking
+ if "qwen4_ple_ssd_offload" in sent:
+ is_qwen4_exp = (entry.config_model_type or "").replace(
+ "-", "_"
+ ).lower() == "qwen4_exp"
+ current_settings.qwen4_ple_ssd_offload = bool(
+ request.qwen4_ple_ssd_offload and is_qwen4_exp
+ )
if "thinking_budget_enabled" in sent:
current_settings.thinking_budget_enabled = (
request.thinking_budget_enabled or False
@@ -2296,6 +2369,19 @@ async def update_model_settings(
if request.thinking_budget_tokens and request.thinking_budget_tokens > 0
else None
)
+ if "mtp_num_draft_tokens" in sent:
+ value = request.mtp_num_draft_tokens
+ if value is not None and not 1 <= value <= MAX_LIGHTNING_MTP_DRAFT_TOKENS:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ "mtp_num_draft_tokens must be between 1 and "
+ f"{MAX_LIGHTNING_MTP_DRAFT_TOKENS} (or null)."
+ ),
+ )
+ current_settings.mtp_num_draft_tokens = value
+ if "preserve_thinking" in sent:
+ current_settings.preserve_thinking = request.preserve_thinking
if "chat_template_kwargs" in sent:
current_settings.chat_template_kwargs = request.chat_template_kwargs
if "forced_ct_kwargs" in sent:
@@ -2314,6 +2400,13 @@ async def update_model_settings(
current_settings.turboquant_kv_enabled = request.turboquant_kv_enabled or False
if "turboquant_kv_bits" in sent:
current_settings.turboquant_kv_bits = request.turboquant_kv_bits or 4
+ if "turboquant_skip_last" in sent:
+ # null = clear to the model default (True); bool(None) would flip it
+ # to False and silently disable the skip-last corruption guard.
+ current_settings.turboquant_skip_last = (
+ True if request.turboquant_skip_last is None
+ else bool(request.turboquant_skip_last)
+ )
# Private Qwen3.5/3.6/3.8 ANE/GPU fixed-shape prefill. These are all load-time
# controls; the runtime signature below causes a loaded model to be
# re-created when the user applies a changed profile.
@@ -2637,7 +2730,10 @@ async def update_model_settings(
detail=f"MTP enabled but failed to read model config: {e}",
)
model_type = cfg.get("model_type")
- if not _is_mtp_compatible(cfg, model_type):
+ # qwen4_exp routes through the dedicated VLM Lightning MTP path
+ # (see _mtp_compat_for_model); skip the mlx-lm whitelist here but
+ # keep the mtp.* weight check below.
+ if model_type != "qwen4_exp" and not _is_mtp_compatible(cfg, model_type):
raise HTTPException(
status_code=400,
detail=(
@@ -2649,6 +2745,15 @@ async def update_model_settings(
),
)
if not _checkpoint_has_mtp_weights(entry.model_path):
+ if model_type == "qwen4_exp":
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ "Qwen4-Exp Lightning MTP requires embedded mtp.* "
+ "tensors; native nextn layers are not supported by "
+ "its dedicated runtime."
+ ),
+ )
raise HTTPException(
status_code=400,
detail=(
@@ -3471,6 +3576,7 @@ async def get_global_settings(is_admin: bool = Depends(require_admin)):
False,
)
),
+ "max_audio_upload_size": global_settings.server.max_audio_upload_size,
},
"model": {
"model_dirs": [
@@ -3717,6 +3823,23 @@ async def update_global_settings(
global_settings.server.distributed_inference_enabled = (
request.distributed_inference_enabled
)
+ if request.max_audio_upload_size is not None:
+ from ..config import parse_size
+
+ try:
+ audio_upload_size = parse_size(request.max_audio_upload_size)
+ except (AttributeError, TypeError, ValueError) as exc:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Invalid max_audio_upload_size: {exc}",
+ ) from exc
+ if audio_upload_size <= 0:
+ raise HTTPException(
+ status_code=400,
+ detail="max_audio_upload_size must be positive",
+ )
+ global_settings.server.max_audio_upload_size = request.max_audio_upload_size
+ runtime_applied.append("max_audio_upload_size")
if request.server_aliases is not None:
from ..utils.network import is_valid_alias
@@ -4961,6 +5084,12 @@ def _build_runtime_cache_observability(
gdn_last_restore = prefix_stats.get("gdn_last_restore")
if not isinstance(gdn_last_restore, dict):
gdn_last_restore = None
+ boundary_snapshots = runtime_stats.get("boundary_snapshots")
+ if not isinstance(boundary_snapshots, dict):
+ boundary_snapshots = None
+ last_prefix_lookup = runtime_stats.get("last_prefix_lookup")
+ if not isinstance(last_prefix_lookup, dict):
+ last_prefix_lookup = None
# Keep the cache fields at the model-row level so the dashboard and
# external admin clients can inspect them without knowing scheduler's
@@ -5036,6 +5165,11 @@ def _build_runtime_cache_observability(
"gdn_staging": gdn_staging_payload,
}
+ if boundary_snapshots is not None:
+ model_payload["boundary_snapshots"] = boundary_snapshots
+ if last_prefix_lookup is not None:
+ model_payload["last_prefix_lookup"] = last_prefix_lookup
+
for field in ssd_counter_fields:
if field in ssd_stats:
model_payload[field] = int(ssd_stats.get(field, 0) or 0)
diff --git a/omlx/admin/static/js/dashboard.js b/omlx/admin/static/js/dashboard.js
index 94ee35fff4..22ebee3e0a 100644
--- a/omlx/admin/static/js/dashboard.js
+++ b/omlx/admin/static/js/dashboard.js
@@ -121,7 +121,7 @@
// Global settings
globalSettings: {
base_path: '',
- server: { host: '127.0.0.1', port: 8000, log_level: 'info', sse_keepalive_mode: 'chunk', burst_decode_mode: 'balanced', preserve_mid_system_cache: true, distributed_inference_enabled: false, distributed_inference_active: false },
+ server: { host: '127.0.0.1', port: 8000, log_level: 'info', sse_keepalive_mode: 'chunk', burst_decode_mode: 'balanced', preserve_mid_system_cache: true, distributed_inference_enabled: false, distributed_inference_active: false, max_audio_upload_size: '100MB' },
model: { model_dirs: [''], model_fallback: false, hide_helper_models: false },
memory: { prefill_memory_guard: true, memory_guard_tier: 'balanced', memory_guard_custom_ceiling_gb: 0 },
scheduler: { max_concurrent_requests: 8, embedding_batch_size: 32, chunked_prefill: false, prefill_priority: 'context', decode_fairness: true },
@@ -6665,6 +6665,7 @@
const s = this.globalSettings;
if (!s.server.host) errors.push('Host');
if (!s.server.port) errors.push('Port');
+ if (!s.server.max_audio_upload_size) errors.push('Maximum Audio Upload Size');
if (!s.model.model_dirs || !s.model.model_dirs.some(d => d.trim())) errors.push('Model Directory');
if (!s.scheduler.max_concurrent_requests) errors.push('Max Concurrent Requests');
if (!s.scheduler.embedding_batch_size) errors.push('Embedding Batch Size');
@@ -6707,6 +6708,7 @@
burst_decode_mode: this.globalSettings.server.burst_decode_mode,
preserve_mid_system_cache: this.globalSettings.server.preserve_mid_system_cache,
distributed_inference_enabled: this.globalSettings.server.distributed_inference_enabled,
+ max_audio_upload_size: this.globalSettings.server.max_audio_upload_size,
model_dirs: this.globalSettings.model.model_dirs.filter(d => d.trim()),
model_fallback: this.globalSettings.model.model_fallback,
hide_helper_models: this.globalSettings.model.hide_helper_models,
@@ -7370,6 +7372,12 @@
force_sampling: s.force_sampling || false,
enable_thinking: s.enable_thinking ?? null,
thinking_default: model?.thinking_default ?? null,
+ qwen4_ple_ssd_offload: model?.qwen4_ple_ssd_offload_forced === true
+ || s.qwen4_ple_ssd_offload === true,
+ qwen4_ple_ssd_offload_supported:
+ model?.qwen4_ple_ssd_offload_supported === true,
+ qwen4_ple_ssd_offload_forced:
+ model?.qwen4_ple_ssd_offload_forced === true,
enableThinkingBudget: !!(s.thinking_budget_tokens),
thinking_budget_tokens: s.thinking_budget_tokens || null,
guided_grammar_enabled: s.guided_grammar_enabled || false,
@@ -8290,6 +8298,8 @@
? (this.modelSettings.index_cache_freq || 4)
: 0,
enable_thinking: this.modelSettings.enable_thinking,
+ qwen4_ple_ssd_offload:
+ !!this.modelSettings.qwen4_ple_ssd_offload,
thinking_budget_enabled: this.modelSettings.enableThinkingBudget,
thinking_budget_tokens: this.modelSettings.enableThinkingBudget
? (this.modelSettings.thinking_budget_tokens || null)
diff --git a/omlx/admin/templates/chat.html b/omlx/admin/templates/chat.html
index 598c4bf901..d5a9da095e 100644
--- a/omlx/admin/templates/chat.html
+++ b/omlx/admin/templates/chat.html
@@ -5255,9 +5255,12 @@ {{ t('chat.key
}
},
- async startNewChat() {
+ async startNewChat(options = {}) {
this.cancelPersistModelSettingsTimer();
const prevChatId = this.currentChatId;
+ const preserveDraft = options.preserveDraft === true && !prevChatId;
+ const draftSystemPrompt = this.systemPrompt;
+ const draftActiveProfile = this.activePromptProfile;
if (prevChatId) {
const prevSession = this.getChatSession(prevChatId, false);
if (prevSession) {
@@ -5274,13 +5277,18 @@ {{ t('chat.key
const chatId = 'chat_' + Date.now();
const sysDefault = this.promptProfiles.find(p => p.name === 'System Default');
- const systemPrompt = sysDefault ? sysDefault.content : '';
+ const systemPrompt = preserveDraft
+ ? draftSystemPrompt
+ : (sysDefault ? sysDefault.content : '');
+ const activeProfile = preserveDraft
+ ? draftActiveProfile
+ : (sysDefault ? sysDefault.name : null);
this.currentChatId = chatId;
this.uploadImages = [];
this.uploadDocuments = [];
this.inputMessage = '';
this.systemPrompt = systemPrompt;
- this.activePromptProfile = sysDefault ? sysDefault.name : null;
+ this.activePromptProfile = activeProfile;
this.editingIndex = null;
this.editContent = '';
this.editImages = [];
@@ -5292,7 +5300,7 @@ {{ t('chat.key
messages: [],
model: this.currentModel,
systemPrompt,
- activeProfile: this.activePromptProfile,
+ activeProfile,
modelSettings: null,
speculativeEngine: null,
speculativeDraftModel: null,
@@ -5300,7 +5308,15 @@ {{ t('chat.key
};
this.chatSessions[chatId] = session;
this.messages = session.messages;
- await this.ensureSessionModelSettings(session, this.currentModel);
+ if (preserveDraft && this.modelSettingsDirty) {
+ this.syncSessionModelSettingsFromUi(session);
+ await this.loadModelCapabilities(
+ this.resolveGatewayModelId(this.currentModel)
+ );
+ this.modelSettingsDirty = false;
+ } else {
+ await this.ensureSessionModelSettings(session, this.currentModel);
+ }
if (this.currentModel) {
this.saveModelSettingsForModel(session, this.currentModel);
}
@@ -5536,7 +5552,7 @@ {{ t('chat.key
});
if (!this.currentChatId) {
- await this.startNewChat();
+ await this.startNewChat({ preserveDraft: true });
}
const chatId = this.currentChatId;
@@ -5589,7 +5605,7 @@ {{ t('chat.key
this.uploadAudio = null;
if (!this.currentChatId) {
- await this.startNewChat();
+ await this.startNewChat({ preserveDraft: true });
}
const chatId = this.currentChatId;
const sourceModel = this.currentModel;
@@ -5780,7 +5796,7 @@ {{ t('chat.key
}
if (!this.currentChatId) {
- await this.startNewChat();
+ await this.startNewChat({ preserveDraft: true });
}
const chatId = this.currentChatId;
const sourceModel = this.currentModel;
diff --git a/omlx/admin/templates/dashboard/_modal_model_settings.html b/omlx/admin/templates/dashboard/_modal_model_settings.html
index 46ba4d039e..3631de9de7 100644
--- a/omlx/admin/templates/dashboard/_modal_model_settings.html
+++ b/omlx/admin/templates/dashboard/_modal_model_settings.html
@@ -451,6 +451,30 @@ {{
x-text="'{{ t('modal.model_settings.enable_thinking_reset')|replace('\\', '\\\\')|replace("'", "\\'") }}'">
+
+
+
+
+
{{ t('modal.model_settings.qwen4_ple_ssd_offload') }}
+
{{ t('modal.model_settings.qwen4_ple_ssd_offload_hint') }}
+
+
+
+
{{ t('modal.model_settings.qwen4_ple_ssd_offload_forced') }}
+
+
diff --git a/omlx/admin/templates/dashboard/_settings.html b/omlx/admin/templates/dashboard/_settings.html
index fb6bb2913b..786f057a23 100644
--- a/omlx/admin/templates/dashboard/_settings.html
+++ b/omlx/admin/templates/dashboard/_settings.html
@@ -970,6 +970,26 @@
{{ t('settings.gl
+
+
+
+
+ {{ t('settings.advanced.uploads') }}
+
+
+
+
+
+
+
{{ t('settings.advanced.max_audio_upload_size_hint') }}
+
+
+
+
+
diff --git a/omlx/api/audio_routes.py b/omlx/api/audio_routes.py
index 438c4fe64b..19c0c13752 100644
--- a/omlx/api/audio_routes.py
+++ b/omlx/api/audio_routes.py
@@ -47,7 +47,8 @@
# {"type": "start"} message instead.
realtime_router = APIRouter()
-# Maximum upload size for audio files (100 MB).
+# Maximum upload size for audio files (100 MB). Used as the default when
+# server settings are not initialized.
MAX_AUDIO_UPLOAD_BYTES = 100 * 1024 * 1024
# Maximum base64-encoded ref_audio size (~15 MB raw audio, enough for ~60s).
@@ -134,8 +135,26 @@ def _record_audio_request(model_id: str) -> None:
logger.warning("Failed to record audio metrics for %s: %s", model_id, exc)
+def _max_audio_upload_bytes() -> int:
+ """Return the configured audio upload limit, falling back to the default."""
+ try:
+ from omlx.settings import get_settings
+
+ return get_settings().server.max_audio_upload_bytes()
+ except RuntimeError:
+ return MAX_AUDIO_UPLOAD_BYTES
+ except (AttributeError, TypeError, ValueError) as exc:
+ logger.warning(
+ "Invalid max_audio_upload_size; using %s byte default: %s",
+ MAX_AUDIO_UPLOAD_BYTES,
+ exc,
+ )
+ return MAX_AUDIO_UPLOAD_BYTES
+
+
async def _read_upload(file: UploadFile) -> bytes:
"""Read an uploaded file in chunks, bailing early if it exceeds the limit."""
+ limit = _max_audio_upload_bytes()
chunks: list[bytes] = []
total = 0
while True:
@@ -143,12 +162,12 @@ async def _read_upload(file: UploadFile) -> bytes:
if not chunk:
break
total += len(chunk)
- if total > MAX_AUDIO_UPLOAD_BYTES:
+ if total > limit:
raise HTTPException(
status_code=413,
detail=(
f"Audio file exceeds maximum allowed size "
- f"({MAX_AUDIO_UPLOAD_BYTES} bytes)"
+ f"({limit} bytes)"
),
)
chunks.append(chunk)
diff --git a/omlx/api/utils.py b/omlx/api/utils.py
index 9cda71ddf3..34514a7cd8 100644
--- a/omlx/api/utils.py
+++ b/omlx/api/utils.py
@@ -8,6 +8,7 @@
import re
from typing import Any, List
+from ..exceptions import InvalidRequestError
from .openai_models import Message
# Model families whose chat templates consume message.reasoning_content directly.
@@ -239,6 +240,11 @@ def _extract_multimodal_content_list(content: list) -> list:
"input_audio": input_audio,
}
)
+ elif item_type in ("video_url", "input_video"):
+ raise InvalidRequestError(
+ "Video input is not supported by oMLX.",
+ field="messages",
+ )
return parts
diff --git a/omlx/cache/boundary_snapshot_store.py b/omlx/cache/boundary_snapshot_store.py
index 09ae91a0d0..fa7452b21f 100644
--- a/omlx/cache/boundary_snapshot_store.py
+++ b/omlx/cache/boundary_snapshot_store.py
@@ -425,7 +425,15 @@ def load(
arrays, metadata = data
else:
return None
- return self._reconstruct_from_safetensors(arrays, metadata)
+ reconstructed = self._reconstruct_from_safetensors(arrays, metadata)
+ if reconstructed is None:
+ return None
+ # mx.load returns file-backed lazy arrays. Materialize them while
+ # this ephemeral snapshot still exists so the reconstructed cache
+ # cannot retain a read primitive past cleanup or promotion.
+ if arrays:
+ mx.eval(*arrays.values())
+ return reconstructed
except Exception as e:
logger.debug(
"Failed to load boundary snapshot %s/%d: %s",
@@ -456,7 +464,15 @@ def load_file(self, file_path: Path) -> list[dict[str, Any]] | None:
if not (isinstance(data, tuple) and len(data) == 2):
return None
arrays, metadata = data
- return self._reconstruct_from_safetensors(arrays, metadata)
+ reconstructed = self._reconstruct_from_safetensors(arrays, metadata)
+ if reconstructed is None:
+ return None
+ # ``take_staged_file`` transfers this path to a caller that may
+ # move or unlink it immediately after load_file returns. Detach
+ # every lazy input from the file before returning cache state.
+ if arrays:
+ mx.eval(*arrays.values())
+ return reconstructed
except Exception as e:
logger.debug("Failed to load committed boundary snapshot %s: %s", file_path, e)
return None
diff --git a/omlx/cache/observability.py b/omlx/cache/observability.py
index f42d4e8ba3..ca7bd95b74 100644
--- a/omlx/cache/observability.py
+++ b/omlx/cache/observability.py
@@ -76,6 +76,106 @@ def clear(self) -> None:
self._snapshots.clear()
+class BoundarySnapshotDiagnostics:
+ """Thread-safe counters for hybrid-cache boundary snapshot decisions.
+
+ The scheduler writes these counters on its inference thread while the
+ admin endpoint can read them concurrently. Reasons are intentionally
+ stable, content-free identifiers so operators can tell whether a cache
+ store was missed because capture never ran, positional alignment failed,
+ or a persisted snapshot could not be restored.
+ """
+
+ _COUNTERS = (
+ "capture_attempts",
+ "captures",
+ "captures_ssd",
+ "captures_memory",
+ "ssd_fallbacks",
+ "override_attempts",
+ "override_hits",
+ "override_misses",
+ "store_skips",
+ )
+
+ def __init__(self) -> None:
+ self._counters = {name: 0 for name in self._COUNTERS}
+ self._reasons: dict[str, int] = {}
+ self._last_event: dict[str, Any] | None = None
+ self._lock = threading.Lock()
+
+ def record(
+ self,
+ event: str,
+ *,
+ reason: str | None = None,
+ request_id: str | None = None,
+ token_count: int | None = None,
+ block_size: int | None = None,
+ source: str | None = None,
+ storage: str | None = None,
+ available_boundaries: int | None = None,
+ ) -> None:
+ counter = {
+ "capture_attempt": "capture_attempts",
+ "capture_success": "captures",
+ "ssd_fallback": "ssd_fallbacks",
+ "override_attempt": "override_attempts",
+ "override_hit": "override_hits",
+ "override_miss": "override_misses",
+ "store_skip": "store_skips",
+ }.get(event)
+
+ with self._lock:
+ cause = None
+ if (
+ event == "store_skip"
+ and self._last_event is not None
+ and self._last_event.get("event") == "override_miss"
+ and self._last_event.get("request_id") == request_id
+ ):
+ cause = self._last_event.get("reason")
+
+ if counter is not None:
+ self._counters[counter] += 1
+ if event == "capture_success" and storage in {"ssd", "memory"}:
+ self._counters[f"captures_{storage}"] += 1
+ if reason:
+ self._reasons[reason] = self._reasons.get(reason, 0) + 1
+
+ last_event: dict[str, Any] = {"event": event}
+ for key, value in (
+ ("reason", reason),
+ ("request_id", request_id),
+ ("token_count", token_count),
+ ("block_size", block_size),
+ ("source", source),
+ ("storage", storage),
+ ("available_boundaries", available_boundaries),
+ ("cause", cause),
+ ):
+ if value is not None:
+ last_event[key] = value
+ self._last_event = last_event
+
+ def snapshot(self) -> dict[str, Any]:
+ with self._lock:
+ return {
+ **self._counters,
+ "reasons": dict(sorted(self._reasons.items())),
+ "last_event": (
+ dict(self._last_event) if self._last_event is not None else None
+ ),
+ }
+
+ def clear(self) -> None:
+ with self._lock:
+ for name in self._counters:
+ self._counters[name] = 0
+ self._reasons.clear()
+ self._last_event = None
+
+
def _window_label(seconds: int) -> str:
if seconds < 60:
return f"{seconds}s"
diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py
index aac44d034b..ae2700e0fb 100644
--- a/omlx/cache/prefix_cache.py
+++ b/omlx/cache/prefix_cache.py
@@ -8,7 +8,9 @@
import logging
import math
+import threading
import time
+from collections import OrderedDict
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
@@ -98,6 +100,16 @@ def cachelist_pm_member_plan(
# lineage map.
_BACKFILL_CHECKED_MAX_ENTRIES = 4096
+# Lightning-MTP prompt priming has one small attention cache of its own. The
+# normal prefix cache stores only the backbone cache, so a warm trunk restore
+# used to lose the MTP history and restart speculative decode unprimed. Keep a
+# deliberately tiny in-memory sidecar of full-block boundary snapshots. Four
+# entries bounds the worst-case Qwen4 100K-context footprint to roughly the
+# same order as one ordinary request cache while covering the recent branches
+# of an interactive conversation. The entries are keyed by the *same* chain
+# hash as the backbone block and are dropped with that block/hash lifecycle.
+_MTP_PREFIX_SNAPSHOT_MAX_ENTRIES = 4
+
def _wrap_cachelist_sub_marker(
sub_idx: int,
@@ -247,6 +259,16 @@ def __init__(
# rewrite saved). Each hash is inspected at most once per run.
self._backfill_checked_hashes: set[bytes] = set()
+ # Full-block Lightning-MTP prompt-history snapshots. Values are
+ # opaque to the generic prefix cache; prompt_priming owns their shape.
+ # Access can race with the asynchronous backbone store worker's hash
+ # callbacks, so use a private lock rather than relying on the GIL for
+ # the multi-step LRU operations.
+ self._mtp_prefix_snapshots: OrderedDict[bytes, tuple[int, Any]] = (
+ OrderedDict()
+ )
+ self._mtp_prefix_snapshot_lock = threading.RLock()
+
# Callback for restoring cold blocks (deprecated in paged SSD-only mode)
# Kept for API compatibility
self._cold_restore_callback: Callable[[int, bytes], bool] | None = None
@@ -1933,7 +1955,16 @@ def _maybe_backfill_dedup_block_payload(
if self.paged_ssd_cache is None or not HAS_MLX:
return True
try:
- data, meta = self.paged_ssd_cache.load_block_with_metadata(block_hash)
+ # Inspection load only: do not promote into the hot cache. A
+ # legacy-cumulative block (pm-ineligible CacheList layouts, e.g.
+ # CacheList(KVCache, PoolingCache)) carries the full cumulative
+ # KV prefix; promoting every inspected block retains those
+ # oversized payloads in RAM for nothing when the common outcome
+ # is "payload already real, no rewrite" (#3226).
+ data, meta = self.paged_ssd_cache.load_block_with_metadata(
+ block_hash,
+ promote_to_hot_cache=False,
+ )
if not data or not meta:
return False
types = meta.get("layer_cache_types") or []
@@ -4748,10 +4779,113 @@ def _on_block_hash_dropped(self, block_hash: bytes) -> None:
from any thread; it must not call back into the paged cache.
"""
self._prefix_index.pop(block_hash, None)
+ with self._mtp_prefix_snapshot_lock:
+ self._mtp_prefix_snapshots.pop(block_hash, None)
def _on_hash_map_cleared(self) -> None:
"""Drop all prefix-index entries after a wholesale hash-map clear."""
self._prefix_index.clear()
+ with self._mtp_prefix_snapshot_lock:
+ self._mtp_prefix_snapshots.clear()
+
+ def _mtp_prefix_chain_tip(
+ self,
+ tokens: list[int],
+ boundary_tokens: int,
+ *,
+ extra_keys: tuple[Any, ...] | None = None,
+ extra_key_token_start: int | None = None,
+ extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None,
+ ) -> bytes | None:
+ """Return the ordinary full-block chain hash for an MTP sidecar.
+
+ VLM requests can change hidden states without changing token ids. The
+ generic prefix cache supports per-range media keys, but
+ ``compute_chain_hashes`` cannot reproduce that resolution from a lone
+ boundary snapshot. Fail closed for those two complex forms; text-only
+ requests and a single request-wide ``extra_keys`` tuple remain exact.
+ """
+ boundary_tokens = int(boundary_tokens)
+ if (
+ boundary_tokens <= 0
+ or boundary_tokens > len(tokens)
+ or boundary_tokens % self.block_size != 0
+ or extra_key_token_start is not None
+ or extra_key_ranges is not None
+ ):
+ return None
+ parent_hash: BlockHash | None = None
+ for start in range(0, boundary_tokens, self.block_size):
+ parent_hash = compute_block_hash(
+ parent_hash,
+ tokens[start : start + self.block_size],
+ extra_keys=extra_keys,
+ model_name=self.paged_cache.model_name,
+ )
+ return parent_hash
+
+ def store_mtp_prefix_snapshot(
+ self,
+ tokens: list[int],
+ boundary_tokens: int,
+ snapshot: Any,
+ *,
+ extra_keys: tuple[Any, ...] | None = None,
+ extra_key_token_start: int | None = None,
+ extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None,
+ ) -> bool:
+ """Keep an exact Lightning-MTP history at one backbone block boundary.
+
+ This is intentionally memory-only. SSD persistence would require a
+ versioned serialization contract for every model family's MTP cache;
+ an unsupported or stale sidecar must merely fall back to unprimed MTP,
+ never make the target model consume an invented history.
+ """
+ tip = self._mtp_prefix_chain_tip(
+ tokens,
+ boundary_tokens,
+ extra_keys=extra_keys,
+ extra_key_token_start=extra_key_token_start,
+ extra_key_ranges=extra_key_ranges,
+ )
+ if tip is None or snapshot is None:
+ return False
+ with self._mtp_prefix_snapshot_lock:
+ self._mtp_prefix_snapshots[tip] = (int(boundary_tokens), snapshot)
+ self._mtp_prefix_snapshots.move_to_end(tip)
+ while len(self._mtp_prefix_snapshots) > _MTP_PREFIX_SNAPSHOT_MAX_ENTRIES:
+ self._mtp_prefix_snapshots.popitem(last=False)
+ return True
+
+ def restore_mtp_prefix_snapshot(
+ self,
+ tokens: list[int],
+ boundary_tokens: int,
+ *,
+ extra_keys: tuple[Any, ...] | None = None,
+ extra_key_token_start: int | None = None,
+ extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None,
+ ) -> Any | None:
+ """Return the exact MTP sidecar matching a reconstructed trunk prefix."""
+ tip = self._mtp_prefix_chain_tip(
+ tokens,
+ boundary_tokens,
+ extra_keys=extra_keys,
+ extra_key_token_start=extra_key_token_start,
+ extra_key_ranges=extra_key_ranges,
+ )
+ if tip is None:
+ return None
+ # A snapshot published before completion is not reusable until the
+ # matching backbone block has actually been stored and remains live.
+ if self.paged_cache.cached_block_hash_to_block.get_block(tip) is None:
+ return None
+ with self._mtp_prefix_snapshot_lock:
+ entry = self._mtp_prefix_snapshots.get(tip)
+ if entry is None or entry[0] != int(boundary_tokens):
+ return None
+ self._mtp_prefix_snapshots.move_to_end(tip)
+ return entry[1]
def get_stats(self) -> PrefixCacheStats:
"""
@@ -4849,9 +4983,15 @@ def clear(self) -> int:
Returns:
Number of entries cleared.
"""
- cleared_count = len(self._request_tables) + len(self._prefix_index)
+ with self._mtp_prefix_snapshot_lock:
+ mtp_snapshot_count = len(self._mtp_prefix_snapshots)
+ cleared_count = (
+ len(self._request_tables) + len(self._prefix_index) + mtp_snapshot_count
+ )
self._request_tables.clear()
self._prefix_index.clear()
+ with self._mtp_prefix_snapshot_lock:
+ self._mtp_prefix_snapshots.clear()
self.paged_cache.clear()
self.reset_stats()
return cleared_count
diff --git a/omlx/cache/type_handlers.py b/omlx/cache/type_handlers.py
index 9c36bd3491..a6a7f22c45 100644
--- a/omlx/cache/type_handlers.py
+++ b/omlx/cache/type_handlers.py
@@ -40,6 +40,9 @@ class CacheType(Enum):
BATCH_POOLING_CACHE = "BatchPoolingCache"
MINIMAX_M3_KVCACHE = "MiniMaxM3KVCache"
MINIMAX_M3_BATCH_KVCACHE = "MiniMaxM3BatchKVCache"
+ QWEN4_QSA_KVCACHE = "QSAKVCache"
+ QWEN4_QSA_QUANTIZED_KVCACHE = "QSAQuantizedKVCache"
+ QWEN4_BATCH_QSA_KVCACHE = "BatchQSAKVCache"
@dataclass
@@ -1421,6 +1424,434 @@ def reconstruct_cache(
return self.deserialize_state(tuple(elements), meta_state)
+def _serialize_qsa_positions(position_ids: Any) -> Any:
+ """Normalize text/MRoPE positions to a fixed ``[B, C, S]`` layout."""
+ if position_ids is None or not hasattr(position_ids, "ndim"):
+ return position_ids
+ if position_ids.ndim == 2:
+ return position_ids[:, None, :]
+ if position_ids.ndim == 3:
+ return position_ids.transpose(1, 0, 2)
+ raise ValueError(
+ "QSA position IDs must be [B, S] or [3, B, S], got " f"{position_ids.shape}."
+ )
+
+
+def _deserialize_qsa_positions(position_ids: Any) -> Any:
+ """Restore the model-facing text/MRoPE position layout."""
+ if position_ids is None or not hasattr(position_ids, "ndim"):
+ return position_ids
+ if position_ids.ndim != 3:
+ raise ValueError(
+ "Serialized QSA position IDs must be [B, C, S], got "
+ f"{position_ids.shape}."
+ )
+ channels = int(position_ids.shape[1])
+ if channels not in (1, 3):
+ raise ValueError(
+ "Serialized QSA position IDs require 1 text channel or 3 "
+ f"MRoPE channels, got {position_ids.shape}."
+ )
+ if channels == 1:
+ return position_ids[:, 0, :]
+ return position_ids.transpose(1, 0, 2)
+
+
+def _normalize_qsa_position_states(position_states: list[Any]) -> list[Any]:
+ """Promote mixed text/MRoPE QSA positions to [B, 3, S].
+
+ Qwen4 represents text positions as [B, S] and MRoPE positions as
+ [3, B, S]. Serialization stores those as [B, 1, S] and [B, 3, S]
+ respectively. The model's indexer cache promotes the text form by
+ broadcasting it across all three MRoPE coordinates when the two forms
+ meet, so block reconstruction must perform the equivalent operation
+ before concatenating along the sequence axis.
+ """
+ if not position_states:
+ return position_states
+
+ batch_size = None
+ channels: set[int] = set()
+ for position_state in position_states:
+ if not hasattr(position_state, "ndim") or position_state.ndim != 3:
+ shape = getattr(position_state, "shape", None)
+ raise ValueError(
+ "Serialized QSA position IDs must be [B, C, S], " f"got {shape}."
+ )
+ current_batch, current_channels, _ = position_state.shape
+ if current_channels not in (1, 3):
+ raise ValueError(
+ "Serialized QSA position IDs require 1 text channel or 3 "
+ f"MRoPE channels, got {position_state.shape}."
+ )
+ if batch_size is None:
+ batch_size = current_batch
+ elif current_batch != batch_size:
+ raise ValueError(
+ "Serialized QSA position IDs must have a consistent batch "
+ f"dimension, got {batch_size} and {current_batch}."
+ )
+ channels.add(current_channels)
+
+ # Preserve both homogeneous paths without introducing broadcast views.
+ if len(channels) == 1:
+ return position_states
+
+ return [
+ (
+ mx.broadcast_to(state, (state.shape[0], 3, state.shape[2]))
+ if state.shape[1] == 1
+ else state
+ )
+ for state in position_states
+ ]
+
+
+class Qwen4QSAKVCacheHandler(CacheTypeHandler):
+ """Handler for Qwen4 QSA caches with raw index keys and positions."""
+
+ @property
+ def cache_type(self) -> CacheType:
+ return CacheType.QWEN4_QSA_KVCACHE
+
+ @property
+ def supports_block_slicing(self) -> bool:
+ return True
+
+ def get_state_axis_info(self) -> tuple[CacheStateAxisInfo, ...]:
+ return (
+ CacheStateAxisInfo("keys", 2, True),
+ CacheStateAxisInfo("values", 2, True),
+ CacheStateAxisInfo("index_keys", 1, True),
+ CacheStateAxisInfo("index_position_ids", 2, True),
+ )
+
+ def _get_state_keys(self) -> tuple[str, ...]:
+ return tuple(info.name for info in self.get_state_axis_info())
+
+ @staticmethod
+ def _validate_serialized_state(elements: tuple[Any, ...]) -> int:
+ """Validate one complete, serialized QSA cache state."""
+ if len(elements) != 4:
+ raise ValueError(
+ "Serialized QSA cache state requires keys, values, index keys, "
+ "and index positions"
+ )
+
+ keys, values, index_keys, position_ids = elements
+ present = tuple(element is not None for element in elements)
+ if not any(present):
+ return 0
+ if not all(present):
+ raise ValueError(
+ "Non-empty QSA cache blocks require complete QSA auxiliary state"
+ )
+
+ shapes = tuple(getattr(element, "shape", None) for element in elements)
+ if any(shape is None for shape in shapes):
+ raise ValueError("Serialized QSA cache state must contain tensors")
+ if len(shapes[3]) != 3:
+ raise ValueError(
+ "Serialized QSA position IDs must be [B, C, S], got " f"{shapes[3]}."
+ )
+ if len(shapes[0]) != 4 or len(shapes[1]) != 4 or len(shapes[2]) != 3:
+ raise ValueError(
+ "Serialized QSA cache state requires 4-D K/V and 3-D index "
+ f"keys, got {shapes[:3]}"
+ )
+
+ channels = int(shapes[3][1])
+ if channels not in (1, 3):
+ raise ValueError(
+ "Serialized QSA position IDs require 1 text channel or 3 "
+ f"MRoPE channels, got {shapes[3]}."
+ )
+
+ batch_sizes = tuple(int(shape[0]) for shape in shapes)
+ if len(set(batch_sizes)) != 1:
+ raise ValueError(
+ "Serialized QSA state requires a consistent batch dimension, "
+ f"got {batch_sizes}."
+ )
+
+ lengths = (
+ int(shapes[0][2]),
+ int(shapes[1][2]),
+ int(shapes[2][1]),
+ int(shapes[3][2]),
+ )
+ if len(set(lengths)) != 1:
+ raise ValueError(
+ "Serialized QSA K/V and auxiliary state must have the same "
+ f"sequence length, got {lengths}."
+ )
+ return lengths[0]
+
+ def get_state_seq_len_from_tuple(self, state_tuple: tuple[Any, ...]) -> int:
+ return self._validate_serialized_state(tuple(state_tuple))
+
+ def serialize_state(self, cache_obj: Any) -> tuple[Any, ...]:
+ keys, values, index_keys, position_ids = cache_obj.state
+ elements = (
+ keys,
+ values,
+ index_keys,
+ _serialize_qsa_positions(position_ids),
+ )
+ self._validate_serialized_state(elements)
+ return elements
+
+ def extract_state(self, cache_obj: Any) -> dict[str, Any]:
+ elements = self.serialize_state(cache_obj)
+ return {
+ "keys": elements[0],
+ "values": elements[1],
+ "index_keys": elements[2],
+ "index_position_ids": elements[3],
+ "states": elements,
+ "offset": getattr(cache_obj, "offset", 0),
+ "cache_type": self.cache_type.value,
+ }
+
+ def get_seq_len(self, state: dict[str, Any]) -> int:
+ keys = state.get("keys")
+ return int(keys.shape[2]) if keys is not None else 0
+
+ def slice_state(
+ self,
+ state: dict[str, Any],
+ start_idx: int,
+ end_idx: int,
+ ) -> dict[str, Any] | None:
+ if not HAS_MLX:
+ return None
+ elements = state.get("states")
+ if elements is None:
+ elements = tuple(
+ state.get(info.name) for info in self.get_state_axis_info()
+ )
+ seq_len = self.get_state_seq_len_from_tuple(tuple(elements))
+ actual_end = min(end_idx, seq_len)
+ if seq_len <= 0 or start_idx >= actual_end:
+ return None
+ sliced = []
+ for info, element in zip(self.get_state_axis_info(), elements):
+ if element is None:
+ sliced.append(None)
+ continue
+ slices = [slice(None)] * element.ndim
+ slices[info.sequence_axis] = slice(start_idx, actual_end)
+ sliced.append(element[tuple(slices)])
+ return {
+ **{
+ info.name: value
+ for info, value in zip(self.get_state_axis_info(), sliced)
+ },
+ "states": tuple(sliced),
+ "cache_type": self.cache_type.value,
+ }
+
+ def concatenate_states(self, states: list[dict[str, Any]]) -> dict[str, Any]:
+ if not HAS_MLX or not states:
+ return {}
+ grouped: list[list[Any]] = [[] for _ in self.get_state_axis_info()]
+ state_lengths = []
+ for state in states:
+ elements = state.get("states")
+ if elements is None:
+ elements = tuple(
+ state.get(info.name) for info in self.get_state_axis_info()
+ )
+ elements = tuple(elements)
+ state_lengths.append(self._validate_serialized_state(elements))
+ for index, element in enumerate(elements):
+ if element is not None:
+ grouped[index].append(element)
+ if any(length == 0 for length in state_lengths) and any(
+ length > 0 for length in state_lengths
+ ):
+ raise ValueError(
+ "Non-empty QSA prefix chains cannot contain empty cache blocks"
+ )
+ concatenated = []
+ for info, elements in zip(self.get_state_axis_info(), grouped):
+ if info.name == "index_position_ids":
+ elements = _normalize_qsa_position_states(elements)
+ concatenated.append(
+ mx.concatenate(elements, axis=info.sequence_axis) if elements else None
+ )
+ return {
+ **{
+ info.name: value
+ for info, value in zip(self.get_state_axis_info(), concatenated)
+ },
+ "states": tuple(concatenated),
+ "cache_type": self.cache_type.value,
+ }
+
+ def deserialize_state(
+ self,
+ elements: tuple[Any, ...],
+ meta_state: Any | None = None,
+ ) -> Any:
+ del meta_state
+ try:
+ from ..patches.mlx_vlm_qwen4_exp_compat import (
+ apply_mlx_vlm_qwen4_exp_compat_patch,
+ )
+
+ apply_mlx_vlm_qwen4_exp_compat_patch()
+ from mlx_vlm.models.qwen4_exp.language import QSAKVCache
+ except Exception as exc: # noqa: BLE001
+ logger.error("Qwen4 QSAKVCache unavailable: %s", exc)
+ return None
+
+ elements = tuple(elements)
+ self._validate_serialized_state(elements)
+ keys, values, index_keys, position_ids = elements
+ cache = QSAKVCache()
+ cache.state = (
+ keys,
+ values,
+ index_keys,
+ _deserialize_qsa_positions(position_ids),
+ )
+ return cache
+
+ def reconstruct_cache(
+ self,
+ state: dict[str, Any],
+ meta_state: tuple | None = None,
+ ) -> Any:
+ elements = state.get("states")
+ if elements is None:
+ elements = tuple(
+ state.get(info.name) for info in self.get_state_axis_info()
+ )
+ return self.deserialize_state(tuple(elements), meta_state)
+
+
+class Qwen4QSAQuantizedKVCacheHandler(Qwen4QSAKVCacheHandler):
+ """Store Qwen4 quantized QSA caches as dense APC-compatible blocks."""
+
+ @property
+ def cache_type(self) -> CacheType:
+ return CacheType.QWEN4_QSA_QUANTIZED_KVCACHE
+
+ def serialize_state(self, cache_obj: Any) -> tuple[Any, ...]:
+ keys, values = cache_obj.dequantize_for_apc()
+ elements = (
+ keys,
+ values,
+ cache_obj.index_keys,
+ _serialize_qsa_positions(cache_obj.index_position_ids),
+ )
+ self._validate_serialized_state(elements)
+ return elements
+
+
+class Qwen4BatchQSAKVCacheHandler(CacheTypeHandler):
+ """Full-state handler for batched Qwen4 QSA caches."""
+
+ @property
+ def cache_type(self) -> CacheType:
+ return CacheType.QWEN4_BATCH_QSA_KVCACHE
+
+ @property
+ def supports_block_slicing(self) -> bool:
+ return False
+
+ def get_state_axis_info(self) -> tuple[CacheStateAxisInfo, ...]:
+ return (
+ CacheStateAxisInfo("keys", 2, False),
+ CacheStateAxisInfo("values", 2, False),
+ CacheStateAxisInfo("offset", None, False),
+ CacheStateAxisInfo("left_padding", None, False),
+ CacheStateAxisInfo("index_keys", 1, False),
+ CacheStateAxisInfo("index_position_ids", 2, False),
+ )
+
+ def serialize_state(self, cache_obj: Any) -> tuple[Any, ...]:
+ kv_state, index_keys, position_ids = cache_obj.state
+ keys, values, offset, left_padding = kv_state
+ return (
+ keys,
+ values,
+ offset,
+ left_padding,
+ index_keys,
+ _serialize_qsa_positions(position_ids),
+ )
+
+ def extract_state(self, cache_obj: Any) -> dict[str, Any]:
+ elements = self.serialize_state(cache_obj)
+ return {
+ **{
+ info.name: value
+ for info, value in zip(self.get_state_axis_info(), elements)
+ },
+ "states": elements,
+ "is_full_state": True,
+ "cache_type": self.cache_type.value,
+ }
+
+ def get_seq_len(self, state: dict[str, Any]) -> int:
+ keys = state.get("keys")
+ return int(keys.shape[2]) if keys is not None else 0
+
+ def slice_state(
+ self,
+ state: dict[str, Any],
+ start_idx: int,
+ end_idx: int,
+ ) -> dict[str, Any] | None:
+ del start_idx, end_idx
+ return {**state, "is_full_state": True}
+
+ def concatenate_states(self, states: list[dict[str, Any]]) -> dict[str, Any]:
+ return states[-1] if states else {}
+
+ def deserialize_state(
+ self,
+ elements: tuple[Any, ...],
+ meta_state: Any | None = None,
+ ) -> Any:
+ del meta_state
+ try:
+ from ..patches.mlx_vlm_qwen4_exp_compat import (
+ apply_mlx_vlm_qwen4_exp_compat_patch,
+ )
+
+ apply_mlx_vlm_qwen4_exp_compat_patch()
+ from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache
+ except Exception as exc: # noqa: BLE001
+ logger.error("Qwen4 BatchQSAKVCache unavailable: %s", exc)
+ return None
+
+ padded = tuple(elements) + (None,) * max(0, 6 - len(elements))
+ keys, values, offset, left_padding, index_keys, position_ids = padded[:6]
+ left_padding_arg = left_padding if left_padding is not None else [0]
+ cache = BatchQSAKVCache(left_padding_arg)
+ cache.state = (
+ (keys, values, offset, left_padding_arg),
+ index_keys,
+ _deserialize_qsa_positions(position_ids),
+ )
+ return cache
+
+ def reconstruct_cache(
+ self,
+ state: dict[str, Any],
+ meta_state: tuple | None = None,
+ ) -> Any:
+ elements = state.get("states")
+ if elements is None:
+ elements = tuple(
+ state.get(info.name) for info in self.get_state_axis_info()
+ )
+ return self.deserialize_state(tuple(elements), meta_state)
+
+
# Default handler for unknown types - falls back to KVCache behavior
class DefaultCacheHandler(KVCacheHandler):
"""Default handler that assumes KVCache-like behavior.
diff --git a/omlx/cache/type_registry.py b/omlx/cache/type_registry.py
index 2cc926d445..c2922d7166 100644
--- a/omlx/cache/type_registry.py
+++ b/omlx/cache/type_registry.py
@@ -18,6 +18,9 @@
KVCacheHandler,
MiniMaxM3BatchKVCacheHandler,
MiniMaxM3KVCacheHandler,
+ Qwen4BatchQSAKVCacheHandler,
+ Qwen4QSAKVCacheHandler,
+ Qwen4QSAQuantizedKVCacheHandler,
RotatingKVCacheHandler,
SizedArraysCache,
)
@@ -73,6 +76,9 @@ class CacheTypeRegistry:
"BatchPoolingCache": CacheType.BATCH_POOLING_CACHE,
"MiniMaxM3KVCache": CacheType.MINIMAX_M3_KVCACHE,
"MiniMaxM3BatchKVCache": CacheType.MINIMAX_M3_BATCH_KVCACHE,
+ "QSAKVCache": CacheType.QWEN4_QSA_KVCACHE,
+ "QSAQuantizedKVCache": CacheType.QWEN4_QSA_QUANTIZED_KVCACHE,
+ "BatchQSAKVCache": CacheType.QWEN4_BATCH_QSA_KVCACHE,
}
# Default handler instance
@@ -263,6 +269,9 @@ def _initialize_default_handlers() -> None:
CacheTypeRegistry.register(CacheListHandler())
CacheTypeRegistry.register(MiniMaxM3KVCacheHandler())
CacheTypeRegistry.register(MiniMaxM3BatchKVCacheHandler())
+ CacheTypeRegistry.register(Qwen4QSAKVCacheHandler())
+ CacheTypeRegistry.register(Qwen4QSAQuantizedKVCacheHandler())
+ CacheTypeRegistry.register(Qwen4BatchQSAKVCacheHandler())
# Initialize handlers when module is imported
diff --git a/omlx/cli.py b/omlx/cli.py
index 362c26abc1..6653c264f3 100644
--- a/omlx/cli.py
+++ b/omlx/cli.py
@@ -54,6 +54,7 @@ def _has_cli_overrides(args) -> bool:
"host",
"log_level",
"sse_keepalive_mode",
+ "max_audio_upload_size",
"max_concurrent_requests",
"embedding_batch_size",
"memory_guard",
@@ -1070,6 +1071,15 @@ def main():
"OpenClaw / WorkBuddy; 'comment' emits the legacy ': keep-alive' SSE "
"comment; 'off' disables keepalive entirely",
)
+ serve_parser.add_argument(
+ "--max-audio-upload-size",
+ type=str,
+ default=None,
+ help="Maximum audio upload size for /v1/audio/transcriptions and "
+ "/v1/audio/process (e.g. '100MB', '500MB'). Overrides the value "
+ "in settings.json (built-in default: 100MB). Uploads are buffered "
+ "in memory, so this is also a per-request RAM cap",
+ )
# Scheduler options (for BatchedEngine)
serve_parser.add_argument(
diff --git a/omlx/cluster/catalogue.py b/omlx/cluster/catalogue.py
index 4aae39864e..3507147cad 100644
--- a/omlx/cluster/catalogue.py
+++ b/omlx/cluster/catalogue.py
@@ -117,9 +117,7 @@ def context_is_limited(self) -> bool:
"""Does memory, not the model, set the usable context?"""
declared = self.declared_context_tokens
- return bool(
- self.fits and declared and self.max_context_tokens < declared
- )
+ return bool(self.fits and declared and self.max_context_tokens < declared)
def describe(self) -> str:
"""One line a person can act on."""
@@ -175,12 +173,17 @@ def _splits(
*,
tensor_parallel_ok: bool,
pipeline_ok: bool = True,
+ prefer_tensor: bool = False,
) -> tuple[tuple[int, int], ...]:
"""Every (tensor_parallel_size, pipeline_stages) this cluster can form.
- Ordered fewest-nodes-first, then pipeline before tensor parallelism at
- equal width: pipeline loads faster, uses less memory, and survives a
- slow link, so it is the better answer when both fit.
+ Ordered fewest-nodes-first. At equal width the default is pipeline before
+ tensor parallelism: pipeline loads faster, uses less memory, and survives
+ a slow link, so it is the better answer when both fit and nothing is
+ known about the link. ``prefer_tensor`` flips the tie-break for callers
+ that know every link is fast (JACCL/Thunderbolt): there, splitting each
+ layer's compute across the group cuts per-token latency, which is what a
+ user who just cabled two Macs together is after.
"""
options: list[tuple[int, int]] = []
@@ -196,7 +199,15 @@ def _splits(
# weights and then fail at load.
continue
options.append((tp, used // tp))
- return tuple(sorted(options, key=lambda item: (item[0] * item[1], item[0])))
+ return tuple(
+ sorted(
+ options,
+ key=lambda item: (
+ item[0] * item[1],
+ -item[0] if prefer_tensor else item[0],
+ ),
+ )
+ )
_SHORTFALL_RE = re.compile(r"\bat least (\d+) additional bytes required\b")
@@ -340,11 +351,14 @@ def assess_model(
tensor_parallel_ok: bool | None = None,
pipeline_ok: bool | None = None,
workload_profile: str = "balanced",
+ prefer_tensor: bool = False,
) -> ModelFit:
"""Whether this model runs here, using the fewest nodes that work.
``tensor_parallel_ok`` defaults to what the layout already determined, so
a model mlx-lm cannot shard is never offered a tensor-parallel plan.
+ ``prefer_tensor`` requests the tensor-parallel split when both strategies
+ fit at equal width — callers set it when every link is known-fast.
"""
if tensor_parallel_ok is None:
@@ -361,6 +375,7 @@ def assess_model(
len(nodes),
tensor_parallel_ok=tensor_parallel_ok,
pipeline_ok=pipeline_ok,
+ prefer_tensor=prefer_tensor,
)
for tp_size, stages in splits:
used = tp_size * stages
@@ -368,9 +383,7 @@ def assess_model(
# them, which is where the fast links were placed. Ranks are positional
# to the planner and must be contiguous from zero, so a subset — or a
# caller's single node that happened to be rank 1 — is renumbered.
- subset = [
- replace(node, rank=index) for index, node in enumerate(nodes[:used])
- ]
+ subset = [replace(node, rank=index) for index, node in enumerate(nodes[:used])]
plan, reason = _plan_or_none(
layout,
subset,
@@ -466,9 +479,7 @@ def assess_model(
if standalone_node_id:
failure_kind = "single_node_only"
context = (
- f" at up to {standalone_context:,} tokens"
- if standalone_context
- else ""
+ f" at up to {standalone_context:,} tokens" if standalone_context else ""
)
last_reason = (
"This model cannot combine Macs because mlx-lm supports neither "
@@ -508,6 +519,7 @@ def assess_model_path(
nodes: Sequence[NodeBudget],
*,
workload_profile: str = "balanced",
+ prefer_tensor: bool = False,
) -> ModelFit:
"""Assess a model directory, reading its real layout and config."""
@@ -536,6 +548,7 @@ def assess_model_path(
model_id=root.name,
declared_context_tokens=declared,
workload_profile=workload_profile,
+ prefer_tensor=prefer_tensor,
)
@@ -544,6 +557,7 @@ def catalogue_for_cluster(
nodes: Sequence[NodeBudget],
*,
workload_profile: str = "balanced",
+ prefer_tensor: bool = False,
) -> tuple[ModelFit, ...]:
"""Assess every model, largest first among those that fit.
@@ -553,7 +567,12 @@ def catalogue_for_cluster(
"""
fits = [
- assess_model_path(path, nodes, workload_profile=workload_profile)
+ assess_model_path(
+ path,
+ nodes,
+ workload_profile=workload_profile,
+ prefer_tensor=prefer_tensor,
+ )
for path in model_paths
]
runnable = sorted(
diff --git a/omlx/cluster/cuda_worker_bootstrap.py b/omlx/cluster/cuda_worker_bootstrap.py
index f38399c4a6..895c0fa63e 100644
--- a/omlx/cluster/cuda_worker_bootstrap.py
+++ b/omlx/cluster/cuda_worker_bootstrap.py
@@ -37,8 +37,8 @@
MAX_SOURCE_MEMBERS = 4096
WORKER_REQUIREMENTS = (
"numpy>=1.24.0,<2.4",
- "mlx==0.32.0",
- "mlx-cuda-13==0.32.0",
+ "mlx==0.32.2",
+ "mlx-cuda-13==0.32.2",
"mlx-lm @ git+https://github.com/ml-explore/mlx-lm@ab1806e8f5d6aa035973af194a1b9198ab4754dc",
"transformers>=5.12.1,<5.13",
"mistral-common>=1.10",
diff --git a/omlx/cluster/deployment.py b/omlx/cluster/deployment.py
index 8f7f637abc..cb14c0a5f2 100644
--- a/omlx/cluster/deployment.py
+++ b/omlx/cluster/deployment.py
@@ -27,6 +27,15 @@
DistributedBackend = Literal["ring", "jaccl", "jaccl-ring"]
+# Version 2 adds ``path_map``: an optional per-node absolute model path, so
+# nodes no longer need the model at the same absolute path on every Mac.
+# Version 1 payloads decode with an empty map, which reproduces the legacy
+# shared-path behavior exactly.
+DEPLOYMENT_SCHEMA_VERSION = 2
+_SUPPORTED_DEPLOYMENT_SCHEMAS = (1, DEPLOYMENT_SCHEMA_VERSION)
+_MAX_PATH_MAP_ENTRIES = 64
+_MAX_MODEL_PATH_BYTES = 4096
+
_SSH_TARGET = re.compile(
r"^(?:[A-Za-z0-9._-]+@)?(?:[A-Za-z0-9._-]+|\[[0-9A-Fa-f:]+\])$"
)
@@ -54,6 +63,11 @@ def validate_ssh_target(value: str) -> str:
def _validate_ip(value: str) -> str:
value = value.strip()
+ # macOS reports Thunderbolt/link-local addresses with a zone id
+ # (fe80::…%en10). mlx's address parser cannot read the suffix — a rank
+ # died at startup on exactly that — and a zone only means something on
+ # the machine that named it, so it never belongs on the wire.
+ value = value.split("%", 1)[0]
try:
ipaddress.ip_address(value)
except ValueError as exc:
@@ -61,6 +75,22 @@ def _validate_ip(value: str) -> str:
return value
+def _hostfile_ips(host: ClusterHost) -> list[str]:
+ """Communication IPs in the order a rank should try them.
+
+ Routable addresses first: a link-local IPv6 without its (machine-local)
+ zone id is ambiguous, so it can only ever be a fallback. This is what
+ keeps a Mac that announces fe80:: Thunderbolt addresses alongside its
+ configured link IPs from advertising the unusable one first.
+ """
+
+ def _link_local(ip: str) -> bool:
+ return ipaddress.ip_address(ip).is_link_local
+
+ routable = [ip for ip in host.ips if not _link_local(ip)]
+ return routable + [ip for ip in host.ips if _link_local(ip)]
+
+
def _validate_rdma_path(value: Any) -> RDMAPath:
if value is None:
return None
@@ -79,6 +109,48 @@ def _validate_rdma_path(value: Any) -> RDMAPath:
raise ValueError("RDMA entries must be a device, a device list, or null")
+def validate_model_path_map(
+ path_map: Any,
+ node_ids: tuple[str, ...] | None = None,
+) -> dict[str, str]:
+ """Validate an optional per-node model path override map.
+
+ Keys are cluster node IDs; values are absolute paths that exist only on
+ the node that resolves them, so no existence check happens here. An empty
+ map is the legacy "same absolute path on every node" behavior.
+ """
+
+ if path_map is None:
+ return {}
+ if not isinstance(path_map, dict):
+ raise ValueError("path_map must be an object mapping node IDs to paths")
+ if len(path_map) > _MAX_PATH_MAP_ENTRIES:
+ raise ValueError("path_map cannot hold more than 64 nodes")
+ known = set(node_ids) if node_ids is not None else None
+ validated: dict[str, str] = {}
+ for node_id, raw_path in path_map.items():
+ if not isinstance(node_id, str) or _NODE_ID.fullmatch(node_id) is None:
+ raise ValueError(f"invalid path_map node ID: {node_id!r}")
+ if known is not None and node_id not in known:
+ raise ValueError(
+ f"path_map names a node outside the deployment: {node_id!r}"
+ )
+ if not isinstance(raw_path, str):
+ raise ValueError(f"path_map path for {node_id!r} must be a string")
+ path = raw_path.strip()
+ if (
+ not path
+ or "\x00" in path
+ or "\n" in path
+ or "\r" in path
+ or len(path.encode()) > _MAX_MODEL_PATH_BYTES
+ or not Path(path).is_absolute()
+ ):
+ raise ValueError(f"path_map path for {node_id!r} must be absolute")
+ validated[node_id] = path
+ return validated
+
+
@dataclass(frozen=True)
class ClusterHost:
"""One rank in an MLX hostfile."""
@@ -248,6 +320,10 @@ class ClusterDeployment:
performance_profiles: tuple[NodePerformanceProfile, ...] = ()
tensor_parallel_size: int = 1
target_context_tokens: int = 8192
+ # node_id → absolute model path on that node. Empty means every node uses
+ # ``model`` — the pre-v2 same-absolute-path requirement. Entries override
+ # only the nodes they name; the coordinator path stays the fallback.
+ path_map: dict[str, str] = field(default_factory=dict)
def __post_init__(self) -> None:
if _NODE_ID.fullmatch(self.deployment_id) is None:
@@ -268,23 +344,27 @@ def __post_init__(self) -> None:
"tensor_parallel_size must be between 1 and the host count"
)
if len(self.hosts) % self.tensor_parallel_size != 0:
- raise ValueError(
- "host count must be divisible by tensor_parallel_size"
- )
+ raise ValueError("host count must be divisible by tensor_parallel_size")
if (
not isinstance(self.target_context_tokens, int)
or isinstance(self.target_context_tokens, bool)
or not 1 <= self.target_context_tokens <= 1_048_576
):
- raise ValueError(
- "target_context_tokens must be between 1 and 1,048,576"
- )
+ raise ValueError("target_context_tokens must be between 1 and 1,048,576")
if len(self.assignments) != len(self.hosts):
raise ValueError("host count must match pipeline assignment count")
if self.hosts[0].ssh != "127.0.0.1":
raise ValueError("rank 0 must use SSH target 127.0.0.1")
if len({host.node_id for host in self.hosts}) != len(self.hosts):
raise ValueError("cluster node IDs must be unique")
+ object.__setattr__(
+ self,
+ "path_map",
+ validate_model_path_map(
+ self.path_map,
+ tuple(host.node_id for host in self.hosts),
+ ),
+ )
if len(self.plan_hash) != 64 or any(
char not in "0123456789abcdef" for char in self.plan_hash
):
@@ -340,6 +420,15 @@ def world_size(self) -> int:
def distributed_init_backend(self) -> str:
return "jaccl" if self.backend.startswith("jaccl") else "ring"
+ def model_path_for(self, node_id: str) -> str:
+ """The model directory one rank loads, honouring per-node overrides.
+
+ Nodes absent from ``path_map`` keep the coordinator's shared path,
+ which is exactly the legacy same-absolute-path behavior.
+ """
+
+ return self.path_map.get(node_id, self.model)
+
def hostfile_dict(self) -> dict[str, Any]:
return {
"backend": self.backend,
@@ -347,7 +436,7 @@ def hostfile_dict(self) -> dict[str, Any]:
"hosts": [
{
"ssh": host.ssh,
- "ips": list(host.ips),
+ "ips": _hostfile_ips(host),
"rdma": [
list(path) if isinstance(path, tuple) else path
for path in host.rdma
@@ -359,7 +448,7 @@ def hostfile_dict(self) -> dict[str, Any]:
def to_dict(self) -> dict[str, Any]:
return {
- "schema_version": 1,
+ "schema_version": DEPLOYMENT_SCHEMA_VERSION,
"deployment_id": self.deployment_id,
"model": self.model,
"backend": self.backend,
@@ -373,11 +462,15 @@ def to_dict(self) -> dict[str, Any]:
],
"tensor_parallel_size": self.tensor_parallel_size,
"target_context_tokens": self.target_context_tokens,
+ "path_map": dict(sorted(self.path_map.items())),
}
@classmethod
def from_dict(cls, payload: dict[str, Any]) -> ClusterDeployment:
- if not isinstance(payload, dict) or payload.get("schema_version", 1) != 1:
+ if (
+ not isinstance(payload, dict)
+ or payload.get("schema_version", 1) not in _SUPPORTED_DEPLOYMENT_SCHEMAS
+ ):
raise ValueError("unsupported cluster deployment schema")
hosts = payload.get("hosts")
assignments = payload.get("assignments")
@@ -414,6 +507,9 @@ def from_dict(cls, payload: dict[str, Any]) -> ClusterDeployment:
),
tensor_parallel_size=int(payload.get("tensor_parallel_size", 1)),
target_context_tokens=int(payload.get("target_context_tokens", 8192)),
+ # Schema 1 payloads predate per-node paths; they decode to the
+ # empty map, which is the shared-path behavior they ran with.
+ path_map=validate_model_path_map(payload.get("path_map")),
)
def encode_worker_plan(self) -> str:
@@ -421,7 +517,7 @@ def encode_worker_plan(self) -> str:
raw = json.dumps(
{
- "schema_version": 1,
+ "schema_version": DEPLOYMENT_SCHEMA_VERSION,
"plan_hash": self.plan_hash,
"assignments": [
assignment.to_dict() for assignment in self.assignments
@@ -430,6 +526,7 @@ def encode_worker_plan(self) -> str:
profile.to_dict() for profile in self.performance_profiles
],
"tensor_parallel_size": self.tensor_parallel_size,
+ "path_map": dict(sorted(self.path_map.items())),
},
sort_keys=True,
separators=(",", ":"),
@@ -439,15 +536,8 @@ def encode_worker_plan(self) -> str:
return base64.urlsafe_b64encode(zlib.compress(raw, level=9)).decode()
-def decode_worker_contract(
- encoded: str,
-) -> tuple[
- str,
- tuple[PipelineAssignment, ...],
- tuple[NodePerformanceProfile, ...],
- int,
-]:
- """Decode and validate the full worker contract without accepting code."""
+def _decode_worker_payload(encoded: str) -> dict[str, Any]:
+ """Inflate and validate a worker plan payload without accepting code."""
if not isinstance(encoded, str) or len(encoded) > _MAX_PLAN_BYTES * 2:
raise ValueError("encoded pipeline plan is too large")
@@ -470,7 +560,10 @@ def decode_worker_contract(
payload = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise ValueError("pipeline plan is not valid JSON") from exc
- if not isinstance(payload, dict) or payload.get("schema_version") != 1:
+ if (
+ not isinstance(payload, dict)
+ or payload.get("schema_version") not in _SUPPORTED_DEPLOYMENT_SCHEMAS
+ ):
raise ValueError("unsupported pipeline plan schema")
plan_hash = payload.get("plan_hash")
assignments = payload.get("assignments")
@@ -485,13 +578,28 @@ def decode_worker_contract(
char not in "0123456789abcdef" for char in plan_hash
):
raise ValueError("pipeline plan hash is invalid")
- parsed = tuple(_assignment_from_dict(item) for item in assignments)
+ return payload
+
+
+def decode_worker_contract(
+ encoded: str,
+) -> tuple[
+ str,
+ tuple[PipelineAssignment, ...],
+ tuple[NodePerformanceProfile, ...],
+ int,
+]:
+ """Decode and validate the full worker contract without accepting code."""
+
+ payload = _decode_worker_payload(encoded)
+ parsed = tuple(_assignment_from_dict(item) for item in payload["assignments"])
if [item.rank for item in sorted(parsed, key=lambda item: item.rank)] != list(
range(len(parsed))
):
raise ValueError("pipeline plan ranks must be contiguous from zero")
profiles = tuple(
- NodePerformanceProfile.from_dict(item) for item in performance_profiles
+ NodePerformanceProfile.from_dict(item)
+ for item in payload.get("performance_profiles", [])
)
if profiles and (
len(profiles) != len(parsed)
@@ -501,8 +609,22 @@ def decode_worker_contract(
raise ValueError("worker performance profiles do not match the shard plan")
tensor_parallel_size = int(payload.get("tensor_parallel_size", 1))
if not 1 <= tensor_parallel_size <= len(parsed):
- raise ValueError("tensor_parallel_size must be between 1 and the assignment count")
- return plan_hash, parsed, profiles, tensor_parallel_size
+ raise ValueError(
+ "tensor_parallel_size must be between 1 and the assignment count"
+ )
+ return payload["plan_hash"], parsed, profiles, tensor_parallel_size
+
+
+def decode_worker_path_map(encoded: str) -> dict[str, str]:
+ """Per-node model path overrides carried inside the worker contract.
+
+ Schema 1 contracts predate per-node paths and decode to an empty map;
+ callers then fall back to the shared ``--model`` argument, which is the
+ legacy behavior those contracts ran with.
+ """
+
+ payload = _decode_worker_payload(encoded)
+ return validate_model_path_map(payload.get("path_map"))
def decode_worker_plan(encoded: str) -> tuple[str, tuple[PipelineAssignment, ...]]:
diff --git a/omlx/cluster/discovery.py b/omlx/cluster/discovery.py
index 65de3c0fb7..b3656fef3d 100644
--- a/omlx/cluster/discovery.py
+++ b/omlx/cluster/discovery.py
@@ -181,7 +181,9 @@ def capture_dns_sd(args: Sequence[str], timeout: float) -> DiscoveryOutput:
return DiscoveryOutput(raw.decode(errors="replace"), error)
-def parse_browse_instances(output: str, service_type: str = "_ssh._tcp.") -> tuple[str, ...]:
+def parse_browse_instances(
+ output: str, service_type: str = "_ssh._tcp."
+) -> tuple[str, ...]:
"""Parse service instance names without trusting their display text."""
instances: list[str] = []
@@ -249,10 +251,7 @@ def resolve(instance: str) -> dict[str, Any] | None:
if target is None:
return None
hostname, port = target
- if (
- port != 22
- or _bonjour_host_label(hostname) == local_hostname
- ):
+ if port != 22 or _bonjour_host_label(hostname) == local_hostname:
return None
return {
"name": instance,
@@ -305,10 +304,7 @@ def verify_pairing_token(encoded_token: str, *, shared_secret: str) -> bool:
except (binascii.Error, json.JSONDecodeError, KeyError, TypeError, ValueError):
return False
- if (
- not isinstance(expires_at, (int, float))
- or isinstance(expires_at, bool)
- ):
+ if not isinstance(expires_at, (int, float)) or isinstance(expires_at, bool):
return False
if time.time() > expires_at:
@@ -498,3 +494,1576 @@ def _enrich_peer_transports(
peer["transport"] = known["transport"] if known else "detecting"
peer["link_speed_gbps"] = known["link_speed_gbps"] if known else None
peer["rdma_available"] = known["rdma_available"] if known else False
+
+
+# ---------------------------------------------------------------------------
+# Cluster v2: PeerRecord + DiscoveryService
+#
+# Layered peer discovery (see ops/notes/cluster_discovery_onboarding_comparison.md):
+# 1. mDNS (_omlx._tcp.local.) via python-zeroconf — optional; absence or any
+# mDNS failure disables only mDNS, never the process.
+# 2. IPv6 link-local multicast fallback (exo-style): HELLO/WASSUP on
+# ff12::6f6d:6c78 udp/53413 with per-interface joins and nonce self-drop.
+# 3. Manual peer add (add_manual) for multicast-filtered networks.
+# 4. Tailscale opportunistic candidates when the tailscale CLI exists.
+# Every announced address is verified against GET /api/cluster/node_id before
+# it is trusted; peers never graduate from "discovered" without that probe.
+# ---------------------------------------------------------------------------
+
+import errno # noqa: E402
+import hashlib # noqa: E402
+import http.client # noqa: E402
+import ipaddress # noqa: E402
+import logging # noqa: E402
+import os # noqa: E402
+import platform # noqa: E402
+import struct # noqa: E402
+import sys # noqa: E402
+import threading # noqa: E402
+import urllib.request # noqa: E402
+from collections import deque # noqa: E402
+from contextlib import suppress # noqa: E402
+from dataclasses import dataclass, field # noqa: E402
+from pathlib import Path # noqa: E402
+
+from .._version import __version__ as _omlx_version # noqa: E402
+
+logger = logging.getLogger(__name__) # noqa: E402
+_probe_diagnostics = threading.local()
+
+MDNS_SERVICE_TYPE = "_omlx._tcp.local."
+MULTICAST_GROUP = "ff12::6f6d:6c78"
+MULTICAST_PORT = 53413
+_HELLO_MAGIC = b"OMLX"
+_WASSUP_MAGIC = b"OMLXW"
+_HELLO_STRUCT = struct.Struct(">4sQQ") # magic, nonce, cluster_hash
+_MAX_DATAGRAM = 2048
+_RECENT_NONCES = 64
+_MAX_CANDIDATES = 256
+_MACOS_TAILSCALE_CLI = "/Applications/Tailscale.app/Contents/MacOS/Tailscale"
+
+# Multicast-join failures we tolerate per-interface (macOS gotcha #3: skip
+# interfaces that do not support multicast instead of dying).
+_JOIN_IGNORED_ERRNOS = {
+ errno.EAFNOSUPPORT,
+ errno.EADDRNOTAVAIL,
+ errno.ENODEV,
+ errno.ENXIO,
+ errno.EINVAL,
+}
+
+# HELLO-send and WASSUP-reply failure logs are rate-limited per interface /
+# peer (a down Thunderbolt bridge otherwise spams one line per second per
+# interface forever — 7k lines in nine minutes observed in the field).
+_TX_FAIL_LOG_INTERVAL = 60.0
+# After this many consecutive HELLO rounds in which every send failed, the
+# multicast socket is discarded and rebuilt. macOS gotcha #6: Thunderbolt
+# hotplug renumbers interfaces, which wedges a bound socket's per-interface
+# multicast state; rebuilding is the only reliable escape.
+_TX_FAIL_RESET_ROUNDS = 3
+
+
+def cluster_hash_u64(cluster_name: str) -> int:
+ """blake2s(cluster_name)[:8] as a big-endian u64."""
+
+ digest = hashlib.blake2s(str(cluster_name).encode("utf-8")).digest()
+ return int.from_bytes(digest[:8], "big")
+
+
+def encode_hello(nonce: int, cluster_hash: int) -> bytes:
+ return _HELLO_STRUCT.pack(_HELLO_MAGIC, nonce & 0xFFFFFFFFFFFFFFFF, cluster_hash)
+
+
+def decode_hello(data: bytes) -> tuple[int, int] | None:
+ """Decode a HELLO datagram to (nonce, cluster_hash); ``None`` if invalid."""
+
+ if len(data) != _HELLO_STRUCT.size:
+ return None
+ magic, nonce, cluster_hash = _HELLO_STRUCT.unpack(data)
+ if magic != _HELLO_MAGIC:
+ return None
+ return nonce, cluster_hash
+
+
+def encode_wassup(nonce: int, node_id: str, http_port: int) -> bytes:
+ payload = json.dumps(
+ {"nonce": nonce, "node_id": node_id, "http_port": int(http_port)},
+ separators=(",", ":"),
+ ).encode("utf-8")
+ return _WASSUP_MAGIC + payload
+
+
+def decode_wassup(data: bytes) -> dict[str, Any] | None:
+ """Decode a WASSUP datagram; ``None`` if invalid."""
+
+ if not data.startswith(_WASSUP_MAGIC):
+ return None
+ try:
+ payload = json.loads(data[len(_WASSUP_MAGIC) :].decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ nonce = payload.get("nonce")
+ node_id = payload.get("node_id")
+ http_port = payload.get("http_port")
+ if not isinstance(nonce, int) or not 0 <= nonce < 1 << 64:
+ return None
+ if not isinstance(node_id, str) or not node_id or len(node_id) > 255:
+ return None
+ if not isinstance(http_port, int) or not 1 <= http_port <= 65535:
+ return None
+ return {"nonce": nonce, "node_id": node_id, "http_port": http_port}
+
+
+@dataclass
+class PeerCaps:
+ chip: str = ""
+ ram_gb: float = 0.0
+ backends: list[str] = field(default_factory=list)
+ thunderbolt: bool = False
+ jaccl: bool = False
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "chip": self.chip,
+ "ram_gb": self.ram_gb,
+ "backends": list(self.backends),
+ "thunderbolt": self.thunderbolt,
+ "jaccl": self.jaccl,
+ }
+
+ @classmethod
+ def from_dict(cls, payload: Any) -> PeerCaps:
+ if not isinstance(payload, dict):
+ return cls()
+ backends = payload.get("backends")
+ return cls(
+ chip=str(payload.get("chip") or "")[:128],
+ ram_gb=float(payload.get("ram_gb") or 0.0),
+ backends=[str(b) for b in backends][:8]
+ if isinstance(backends, list)
+ else [],
+ thunderbolt=bool(payload.get("thunderbolt")),
+ jaccl=bool(payload.get("jaccl")),
+ )
+
+
+def _rdma_fabric_caps(
+ caps: PeerCaps, runner: Callable[..., Any] = subprocess.run
+) -> None:
+ """Detect the Thunderbolt RDMA fabric and set ``thunderbolt``/``jaccl``.
+
+ macOS-only, best-effort, never raises: ``rdma_ctl status`` reports
+ whether RDMA is enabled and ``ibv_devices`` lists the ``rdma_*`` devices,
+ which exist only on the Thunderbolt fabric. The wizard's RDMA check row
+ and the JACCL-vs-ring backend choice both key off these flags.
+ """
+
+ if sys.platform != "darwin":
+ return
+ rdma_ctl = "/usr/bin/rdma_ctl"
+ ibv_devices = "/usr/bin/ibv_devices"
+ # A supplied runner is an explicit probe seam (used by offline tests and
+ # embedders); only the production subprocess runner depends on these paths
+ # existing on the current host.
+ if runner is subprocess.run and not (
+ os.path.exists(rdma_ctl) and os.path.exists(ibv_devices)
+ ):
+ return
+ try:
+ status = runner( # noqa: S603 - fixed system executable
+ [rdma_ctl, "status"],
+ capture_output=True,
+ text=True,
+ timeout=5.0,
+ check=False,
+ )
+ enabled = (
+ status.returncode == 0
+ and status.stdout.strip().splitlines()
+ and status.stdout.strip().splitlines()[0].strip().lower() == "enabled"
+ )
+ devices = runner( # noqa: S603 - fixed system executable
+ [ibv_devices], capture_output=True, text=True, timeout=5.0, check=False
+ )
+ # Same shape as probe.py's _RDMA_DEVICE_RE: device lines are
+ # whitespace-indented under a two-row header.
+ rdma_devs = (
+ [
+ stripped.split()[0]
+ for line in devices.stdout.splitlines()
+ if (stripped := line.strip()).startswith("rdma_")
+ ]
+ if devices.returncode == 0
+ else []
+ )
+ caps.thunderbolt = bool(rdma_devs)
+ caps.jaccl = bool(enabled and rdma_devs)
+ except (OSError, subprocess.SubprocessError):
+ pass
+
+
+def local_caps() -> PeerCaps:
+ """Best-effort local capability snapshot; never raises."""
+
+ caps = PeerCaps()
+ try:
+ if sys.platform == "darwin":
+ chip = subprocess.run( # noqa: S603 - fixed system executable
+ ["/usr/sbin/sysctl", "-n", "machdep.cpu.brand_string"],
+ capture_output=True,
+ text=True,
+ timeout=2.0,
+ check=False,
+ )
+ if chip.returncode == 0:
+ caps.chip = chip.stdout.strip()[:128]
+ mem = subprocess.run( # noqa: S603 - fixed system executable
+ ["/usr/sbin/sysctl", "-n", "hw.memsize"],
+ capture_output=True,
+ text=True,
+ timeout=2.0,
+ check=False,
+ )
+ if mem.returncode == 0:
+ caps.ram_gb = round(int(mem.stdout.strip()) / (1 << 30), 1)
+ else:
+ caps.chip = platform.machine()
+ with suppress(OSError, ValueError):
+ caps.ram_gb = round(
+ os.sysconf("SC_PAGE_SIZE")
+ * os.sysconf("SC_PHYS_PAGES")
+ / (1 << 30),
+ 1,
+ )
+ except (OSError, subprocess.SubprocessError):
+ pass
+ _rdma_fabric_caps(caps)
+ return caps
+
+
+PeerLink = str # "tb" | "ethernet" | "wifi" | "tailscale" | "unknown"
+PeerState = str # "discovered" | "suspect" | "dead"
+
+
+@dataclass
+class PeerRecord:
+ node_id: str
+ friendly_name: str = ""
+ version: str = ""
+ cluster_name: str = ""
+ caps: PeerCaps = field(default_factory=PeerCaps)
+ addrs: list[dict[str, str]] = field(default_factory=list)
+ http_port: int = 0
+ paired: bool = False
+ last_seen: float = 0.0
+ link: PeerLink = "unknown"
+ state: PeerState = "discovered"
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "node_id": self.node_id,
+ "friendly_name": self.friendly_name,
+ "version": self.version,
+ "cluster_name": self.cluster_name,
+ "caps": self.caps.to_dict(),
+ "addrs": [dict(a) for a in self.addrs],
+ "http_port": self.http_port,
+ "paired": self.paired,
+ "last_seen": self.last_seen,
+ "link": self.link,
+ "state": self.state,
+ }
+
+
+@dataclass
+class DiscoveryConfig:
+ cluster_name: str = "omlx"
+ http_port: int = 8000
+ version: str = _omlx_version
+ caps: PeerCaps = field(default_factory=local_caps)
+ hello_interval: float = 1.0
+ heartbeat_interval: float = 2.0
+ probe_interval: float = 10.0
+ probe_timeout: float = 3.0
+ suspect_after: float = 6.0
+ dead_after: float = 30.0
+ multicast_window: float = 5.0
+ iface_poll_interval: float = 5.0
+ tailscale_interval: float = 30.0
+ enable_mdns: bool = True
+ enable_multicast: bool = True
+ enable_tailscale: bool = True
+
+
+def default_cluster_config_path(base_path: Path | str | None = None) -> Path:
+ """On-disk location of the persisted cluster config (cluster.json)."""
+
+ if base_path is not None:
+ base = Path(base_path)
+ else:
+ env_value = os.environ.get("OMLX_BASE_PATH")
+ base = Path(env_value).expanduser() if env_value else Path.home() / ".omlx"
+ return base / "cluster" / "cluster.json"
+
+
+def load_cluster_name(base_path: Path | str | None = None) -> str:
+ """Persisted settings-level cluster name, defaulting to ``"omlx"``.
+
+ Read from ``
/cluster/cluster.json`` (``{"cluster_name": ...}``).
+ A missing or malformed file never fails startup — the default keeps the
+ pre-config behavior, and nodes only discover each other when the names
+ (and therefore the cluster hashes) match.
+ """
+
+ try:
+ payload = json.loads(
+ default_cluster_config_path(base_path).read_text(encoding="utf-8")
+ )
+ except (OSError, ValueError):
+ return DiscoveryConfig.cluster_name
+ if not isinstance(payload, dict):
+ return DiscoveryConfig.cluster_name
+ name = payload.get("cluster_name")
+ if isinstance(name, str) and name.strip():
+ return name.strip()
+ return DiscoveryConfig.cluster_name
+
+
+def _default_interface_lister() -> list[str]:
+ """Names of multicast-capable candidate interfaces (never raises)."""
+
+ names: list[str] = []
+ if sys.platform == "darwin":
+ try:
+ result = subprocess.run( # noqa: S603 - fixed system executable
+ ["/sbin/ifconfig", "-l"],
+ capture_output=True,
+ text=True,
+ timeout=2.0,
+ check=False,
+ )
+ if result.returncode == 0:
+ names = result.stdout.split()
+ except (OSError, subprocess.SubprocessError):
+ names = []
+ if not names:
+ with suppress(OSError):
+ names = [name for _, name in socket.if_nameindex()]
+ return [n for n in names if not n.startswith("lo")]
+
+
+def local_addr_dicts() -> list[dict[str, str]]:
+ """Addresses this node considers its own, for the devices ``self`` row.
+
+ Best-effort and never raises. Thunderbolt bridge addresses (typically
+ the self-assigned 10.0.0.0/24 pair on a direct link) are included so the
+ UI can show the direct-link path next to LAN and Tailscale ones.
+ """
+
+ addrs: list[dict[str, str]] = []
+ if sys.platform == "darwin":
+ try:
+ result = subprocess.run( # noqa: S603 - fixed system executable
+ ["/sbin/ifconfig", "-a"],
+ capture_output=True,
+ text=True,
+ timeout=3.0,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ result = None
+ if result is not None and result.returncode == 0:
+ current: str | None = None
+ for line in result.stdout.splitlines():
+ header = re.match(r"^([a-z0-9]+): ", line)
+ if header:
+ current = header.group(1)
+ continue
+ if current is None or current.startswith(
+ ("lo", "awdl", "llw", "anpi", "ap", "gif", "stf")
+ ):
+ continue
+ match = re.match(r"^\s+inet6?\s+(\S+)", line)
+ if match is None:
+ continue
+ ip = match.group(1)
+ if_type = "vpn" if current.startswith("utun") else "lan"
+ if ip.startswith("100."):
+ if_type = "tailscale"
+ addrs.append({"ip": ip, "if_type": if_type})
+ return addrs[:16]
+ # Portable fallback: primary IPv4 via the routing table (no traffic is
+ # actually sent to TEST-NET-1).
+ with suppress(OSError):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ try:
+ sock.connect(("192.0.2.1", 80))
+ addrs.append({"ip": sock.getsockname()[0], "if_type": "lan"})
+ finally:
+ sock.close()
+ return addrs
+
+
+def _http_probe_node_id(ip: str, port: int, timeout: float) -> dict[str, Any] | None:
+ """GET http://ip:port/api/cluster/node_id; ``None`` on any failure."""
+
+ host = f"[{ip}]" if ":" in ip else ip
+ url = f"http://{host}:{port}/api/cluster/node_id"
+ _probe_diagnostics.value = {"transport": "direct", "error": ""}
+ try:
+ with urllib.request.urlopen(url, timeout=timeout) as response: # noqa: S310 - cluster LAN probe of an announced address
+ payload = json.loads(response.read(65536).decode("utf-8"))
+ except ValueError as exc:
+ _probe_diagnostics.value = {
+ "transport": "direct",
+ "error": f"invalid response: {exc}",
+ }
+ return None
+ except OSError as direct_exc:
+ # Some macOS installations deny Homebrew Python outbound access to a
+ # direct Thunderbolt subnet while Apple's system Python can reach the
+ # same address. Rank control and JACCL bootstrap already use this
+ # bounded carrier. Reuse it for persisted-pair reboot recovery so a
+ # verified 10.0.0.x address does not require another manual seed.
+ try:
+ is_tailscale = ipaddress.ip_address(ip) in ipaddress.ip_network(
+ "100.64.0.0/10"
+ )
+ except ValueError:
+ is_tailscale = False
+ if is_tailscale:
+ _probe_diagnostics.value = {
+ "transport": "direct",
+ "error": str(direct_exc),
+ }
+ return None
+ try:
+ payload = _system_proxy_probe_node_id(ip, port, timeout)
+ except (OSError, RuntimeError, TimeoutError, ValueError) as proxy_exc:
+ _probe_diagnostics.value = {
+ "transport": "system-proxy",
+ "error": f"direct={direct_exc}; proxy={proxy_exc}",
+ }
+ return None
+ if payload is None:
+ _probe_diagnostics.value = {
+ "transport": "system-proxy",
+ "error": f"direct={direct_exc}; proxy returned no identity",
+ }
+ return None
+ _probe_diagnostics.value = {"transport": "system-proxy", "error": ""}
+ if not isinstance(payload, dict) or not isinstance(payload.get("node_id"), str):
+ return None
+ return payload
+
+
+def _system_proxy_probe_node_id(
+ ip: str,
+ port: int,
+ timeout: float,
+) -> dict[str, Any] | None:
+ """Probe one peer through the bounded macOS system-Python carrier."""
+
+ from .system_socket_proxy import (
+ open_system_tcp_proxy,
+ should_proxy_control_socket,
+ )
+
+ if not should_proxy_control_socket(ip):
+ return None
+ proxy = open_system_tcp_proxy(ip, port, timeout=timeout)
+ try:
+ host = f"[{ip}]" if ":" in ip else ip
+ request = (
+ "GET /api/cluster/node_id HTTP/1.1\r\n"
+ f"Host: {host}:{port}\r\n"
+ "Accept: application/json\r\n"
+ "Connection: close\r\n\r\n"
+ ).encode("ascii")
+ proxy.stream.sendall(request)
+ response = http.client.HTTPResponse(proxy.stream)
+ response.begin()
+ if response.status != 200:
+ return None
+ payload = json.loads(response.read(65536).decode("utf-8"))
+ if response.read(1):
+ return None
+ return payload if isinstance(payload, dict) else None
+ finally:
+ proxy.close()
+
+
+def _classify_link(ip: str, if_type: str, rtt: float | None) -> PeerLink:
+ """Best-effort link classification.
+
+ Tailscale is certain (100.64.0.0/10); Thunderbolt vs ethernet vs wifi is
+ an RTT heuristic over the verified address until interface metadata says
+ otherwise.
+ """
+
+ if if_type == "tailscale":
+ return "tailscale"
+ with suppress(ValueError):
+ if ipaddress.ip_address(ip) in ipaddress.ip_network("100.64.0.0/10"):
+ return "tailscale"
+ if rtt is None:
+ return "unknown"
+ if rtt < 0.001:
+ return "tb"
+ if rtt < 0.010:
+ return "ethernet"
+ return "wifi"
+
+
+def _load_zeroconf() -> Any | None:
+ """Import python-zeroconf if installed; ``None`` disables only mDNS."""
+
+ try:
+ import zeroconf
+ except ImportError:
+ return None
+ return zeroconf
+
+
+def _tailscale_executable() -> str | None:
+ """Return the CLI from PATH or the normal signed macOS app bundle."""
+
+ discovered = shutil.which("tailscale")
+ if discovered:
+ return discovered
+ candidate = Path(
+ os.environ.get("OMLX_TAILSCALE_CLI", _MACOS_TAILSCALE_CLI)
+ ).expanduser()
+ if (
+ sys.platform == "darwin"
+ and candidate.is_file()
+ and os.access(candidate, os.X_OK)
+ ):
+ return str(candidate)
+ return None
+
+
+class DiscoveryService:
+ """Always-on peer discovery for cluster v2.
+
+ All network-touching seams are injectable (``socket_factory``,
+ ``prober``, ``interface_lister``, ``tailscale_status``,
+ ``zeroconf_module``) so unit tests run fully offline.
+ """
+
+ def __init__(
+ self,
+ identity: Any,
+ registry: Any,
+ config: DiscoveryConfig | None = None,
+ *,
+ socket_factory: Callable[[], Any] | None = None,
+ prober: Callable[[str, int, float], dict[str, Any] | None] | None = None,
+ clock: Callable[[], float] = time.monotonic,
+ interface_lister: Callable[[], list[str]] = _default_interface_lister,
+ tailscale_status: Callable[[], dict[str, Any] | None] | None = None,
+ zeroconf_module: Any = "auto",
+ ) -> None:
+ self.identity = identity
+ self.registry = registry
+ self.config = config or DiscoveryConfig()
+ self._clock = clock
+ self._prober = prober or _http_probe_node_id
+ self._socket_factory = socket_factory or self._open_multicast_socket
+ self._interface_lister = interface_lister
+ self._tailscale_status = tailscale_status or self._read_tailscale_status
+ if zeroconf_module == "auto":
+ self._zc = _load_zeroconf() if self.config.enable_mdns else None
+ else:
+ self._zc = zeroconf_module or None
+
+ self._cluster_hash = cluster_hash_u64(self.config.cluster_name)
+ self._peers: dict[str, PeerRecord] = {}
+ # (ip, port) -> {node_id hint, if_type, last_probe, rtt, verified}
+ self._candidates: dict[tuple[str, int], dict[str, Any]] = {}
+ self._nonces: deque[int] = deque(maxlen=_RECENT_NONCES)
+ self._callbacks: list[Callable[[PeerRecord], None]] = []
+ self._hash_mismatch_logged = False
+ self._last_hello_at: float | None = None
+ self._last_hello_wall: float | None = None
+ self._lock = threading.RLock()
+ self._stop = threading.Event()
+ self._threads: list[threading.Thread] = []
+ self._socket: Any | None = None
+ self._joined: dict[str, int] = {} # ifname -> ifindex
+ self._tx_fail_logged_at: dict[int, float] = {} # ifindex -> monotonic
+ self._reply_fail_logged_at: dict[str, float] = {} # peer_ip -> monotonic
+ self._consecutive_tx_fail_rounds = 0
+ self._last_tx_ok_wall: float | None = None
+ self._last_tx_error: str | None = None
+ self._needs_socket_reset = False
+ self._consecutive_socket_resets = 0
+ self._last_socket_reset_at = 0.0
+ self._local_network_blocked_suspected = False
+ self._zc_instance: Any | None = None
+ self._zc_browser: Any | None = None
+ self._zc_info: Any | None = None
+ self._rehydrate_paired_candidates()
+
+ # -- public API ----------------------------------------------------------
+
+ @property
+ def mdns_available(self) -> bool:
+ return self._zc is not None
+
+ @property
+ def multicast_ok(self) -> bool:
+ """True when a foreign HELLO arrived within the multicast window.
+
+ The UI uses this to warn about macOS Local Network permission
+ denial: discovery silently finds nothing when the OS blocks us.
+ """
+
+ last = self._last_hello_at
+ return (
+ last is not None and (self._clock() - last) < self.config.multicast_window
+ )
+
+ @property
+ def last_multicast_rx_at(self) -> float | None:
+ """Wall-clock time of the last foreign HELLO, or None if never."""
+
+ return self._last_hello_wall
+
+ @property
+ def mdns_active(self) -> bool:
+ """True when our mDNS service announcement is actually registered."""
+
+ return self._zc_info is not None
+
+ def transport_summary(self) -> str:
+ """Active discovery transports, e.g. ``"mdns+multicast"``."""
+
+ parts: list[str] = []
+ if self.mdns_active:
+ parts.append("mdns")
+ if self.config.enable_multicast:
+ parts.append("multicast")
+ return "+".join(parts) if parts else "none"
+
+ def peers(self) -> list[PeerRecord]:
+ with self._lock:
+ return [self._peers[key] for key in sorted(self._peers)]
+
+ def mark_paired(self, node_id: str) -> None:
+ """Immediately suppress an approved peer from unpaired discovery."""
+
+ with self._lock:
+ peer = self._peers.get(node_id)
+ if peer is not None:
+ peer.paired = True
+
+ def health(self) -> dict[str, Any]:
+ """Extended self-diagnostics for the discovery health detail route.
+
+ The base health endpoint only reports inbound multicast state; when
+ discovery silently dies (a crashed loop thread, a wedged socket,
+ interfaces renumbered by Thunderbolt hotplug) these fields are how
+ the UI and field debugging tell those apart from "no peers nearby".
+ """
+
+ with self._lock:
+ threads = {t.name: t.is_alive() for t in self._threads}
+ joined = sorted(self._joined)
+ candidate_states = [
+ {
+ "ip": ip,
+ "port": port,
+ "node_id": value.get("node_id"),
+ "if_type": value.get("if_type"),
+ "verified": bool(value.get("verified", False)),
+ "last_transport": value.get("last_transport"),
+ "last_error": str(value.get("last_error") or "")[:1000],
+ }
+ for (ip, port), value in sorted(self._candidates.items())
+ ]
+ return {
+ "multicast_loop_alive": threads.get("omlx-discovery-mcast", False),
+ "maintenance_loop_alive": threads.get("omlx-discovery-maint", False),
+ "socket_open": self._socket is not None,
+ "joined_interfaces": joined,
+ "last_hello_tx_ok_at": self._last_tx_ok_wall,
+ "last_hello_tx_error": self._last_tx_error,
+ "consecutive_tx_fail_rounds": self._consecutive_tx_fail_rounds,
+ "socket_resets": self._consecutive_socket_resets,
+ "local_network_blocked_suspected": (self._local_network_blocked_suspected),
+ "candidates": len(self._candidates),
+ "candidate_states": candidate_states,
+ "peers": len(self._peers),
+ }
+
+ def on_change(self, callback: Callable[[PeerRecord], None]) -> None:
+ with self._lock:
+ self._callbacks.append(callback)
+
+ def add_manual(self, ip: str, port: int) -> None:
+ """Manually added peer candidate; verified via the same probe path."""
+
+ self._add_candidate(str(ip), int(port), node_id=None, if_type="manual")
+ # Probe on the next maintenance tick; tests may call probe_now().
+
+ def _rehydrate_paired_candidates(self) -> None:
+ """Seed probes from trusted addresses that survived a server restart.
+
+ Discovery announcements are deliberately best-effort on macOS. A peer
+ that was manually added over a direct Thunderbolt address must remain
+ reachable when multicast is blocked, so paired registry rows retain the
+ verified address and HTTP port. Unpaired discoveries are never read here
+ because the registry keeps them memory-only.
+ """
+
+ paired = getattr(self.registry, "paired", None)
+ if not callable(paired):
+ return
+ try:
+ records = paired()
+ except Exception:
+ logger.debug("paired discovery seeds could not be read", exc_info=True)
+ return
+ for record in records:
+ if not isinstance(record, dict):
+ continue
+ node_id = record.get("node_id")
+ # Schema-v1 rows written before endpoint persistence have no port.
+ # oMLX nodes conventionally share the configured server port (the
+ # same documented heuristic as Tailscale discovery); a successful
+ # probe writes the exact value back for subsequent restarts.
+ port = record.get("http_port") or self.config.http_port
+ if (
+ not isinstance(node_id, str)
+ or not node_id
+ or not isinstance(port, int)
+ or isinstance(port, bool)
+ or not 1 <= port <= 65535
+ ):
+ continue
+ for raw_ip in record.get("last_addrs") or ():
+ if not isinstance(raw_ip, str):
+ continue
+ try:
+ # Scope identifiers are process/interface-local and cannot
+ # safely survive a reboot. Retain the address itself; a
+ # routable/manual IPv4 remains the deterministic path.
+ parsed = ipaddress.ip_address(raw_ip.split("%", 1)[0])
+ except ValueError:
+ continue
+ # A persisted IPv6 scope identifier cannot be trusted after
+ # interface renumbering, and link-local IPv6 without a scope is
+ # not dialable. Multicast can rediscover it with a fresh scope;
+ # deterministic reboot recovery uses the routable/manual path.
+ if parsed.version == 6 and parsed.is_link_local:
+ continue
+ ip = str(parsed)
+ self._add_candidate(
+ ip,
+ port,
+ node_id=node_id,
+ if_type="paired",
+ )
+
+ def start(self) -> None:
+ with self._lock:
+ if self._threads:
+ return
+ self._stop.clear()
+ if self.config.enable_multicast:
+ self._spawn(self._multicast_loop, "omlx-discovery-mcast")
+ self._spawn(self._maintenance_loop, "omlx-discovery-maint")
+ if self._zc is not None:
+ try:
+ self._start_mdns()
+ except Exception as exc: # mDNS must never kill the process
+ logger.warning("mDNS announce/browse disabled: %s", exc)
+ self._zc_instance = None
+
+ def stop(self) -> None:
+ self._stop.set()
+ for thread in list(self._threads):
+ thread.join(timeout=2.0)
+ self._threads = []
+ with suppress(Exception):
+ if self._socket is not None:
+ self._socket.close()
+ self._socket = None
+ with suppress(Exception):
+ if self._zc_instance is not None:
+ if self._zc_info is not None:
+ self._zc_instance.unregister_service(self._zc_info)
+ if self._zc_browser is not None:
+ self._zc_browser.cancel()
+ self._zc_instance.close()
+ self._zc_instance = self._zc_browser = self._zc_info = None
+
+ def probe_now(self) -> None:
+ """Run one probe sweep synchronously (maintenance loop does this)."""
+
+ self._probe_sweep()
+
+ def probe_candidate_now(self, ip: str, port: int) -> None:
+ """Probe one explicit candidate now, bypassing periodic dedupe."""
+
+ self._probe_candidate(str(ip), int(port))
+
+ def tick_liveness(self) -> None:
+ """Evaluate suspect/dead transitions synchronously (loop does this)."""
+
+ self._liveness_sweep()
+
+ # -- internals -----------------------------------------------------------
+
+ def _spawn(self, target: Callable[[], None], name: str) -> None:
+ def _supervised() -> None:
+ while not self._stop.is_set():
+ try:
+ target()
+ except BaseException:
+ if self._stop.is_set():
+ return
+ # A daemon thread dying silently is how discovery goes
+ # dark without a trace; log loudly and restart instead.
+ logger.critical(
+ "discovery thread %s crashed; restarting in 2s",
+ name,
+ exc_info=True,
+ )
+ self._stop.wait(2.0)
+ continue
+ if self._stop.is_set():
+ return
+ # Clean return without a stop request is also a bug —
+ # discovery is always-on. Restart rather than going dark.
+ logger.warning(
+ "discovery thread %s exited unexpectedly; restarting in 2s",
+ name,
+ )
+ self._stop.wait(2.0)
+
+ thread = threading.Thread(target=_supervised, name=name, daemon=True)
+ self._threads.append(thread)
+ thread.start()
+
+ def _fire_change(self, peer: PeerRecord) -> None:
+ with self._lock:
+ callbacks = list(self._callbacks)
+ for callback in callbacks:
+ try:
+ callback(peer)
+ except Exception: # a UI callback must never kill discovery
+ logger.exception("discovery on_change callback failed")
+
+ def _open_multicast_socket(self) -> Any:
+ sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ sock.bind(("::", MULTICAST_PORT))
+ sock.settimeout(0.25)
+ return sock
+
+ def _sync_interfaces(self, sock: Any) -> None:
+ """Join the multicast group on every multicast-capable interface.
+
+ Thunderbolt bridges appear/disappear with cable state (macOS gotcha
+ #4), so this is re-run periodically. macOS also *renumbers*
+ interfaces on Thunderbolt hotplug (gotcha #5): a cached ifindex then
+ silently points at the wrong interface and every send fails with
+ EHOSTUNREACH, so stale or renumbered entries are dropped here and
+ re-joined below.
+ """
+
+ try:
+ names = self._interface_lister()
+ except Exception:
+ return
+ current = set(names)
+ for name, ifindex in list(self._joined.items()):
+ if name not in current:
+ # Interface vanished; its group membership dies with it.
+ self._joined.pop(name, None)
+ continue
+ try:
+ now_index = socket.if_nametoindex(name)
+ except OSError:
+ self._joined.pop(name, None)
+ continue
+ if now_index != ifindex:
+ logger.info(
+ "interface %s renumbered (%d -> %d); re-joining multicast group",
+ name,
+ ifindex,
+ now_index,
+ )
+ self._joined.pop(name, None)
+ for name in names:
+ if name in self._joined:
+ continue
+ try:
+ ifindex = socket.if_nametoindex(name)
+ except OSError:
+ continue
+ membership = socket.inet_pton(
+ socket.AF_INET6, MULTICAST_GROUP
+ ) + struct.pack("@I", ifindex)
+ try:
+ sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, membership)
+ except OSError as exc:
+ if exc.errno not in _JOIN_IGNORED_ERRNOS:
+ logger.debug("multicast join on %s failed: %s", name, exc)
+ continue
+ self._joined[name] = ifindex
+
+ def _multicast_loop(self) -> None:
+ try:
+ sock = self._socket_factory()
+ except OSError as exc:
+ logger.warning("cluster multicast discovery unavailable: %s", exc)
+ return
+ self._socket = sock
+ last_hello = 0.0
+ last_ifaces = 0.0
+ last_reset_warn = 0.0
+ try:
+ while not self._stop.is_set():
+ if self._needs_socket_reset:
+ # Exponential backoff: a process-level wedge (e.g. a
+ # denied macOS Local Network permission) survives socket
+ # rebuilds, so rebuilding every second just spams the
+ # log and burns CPU. Back off to at most one rebuild
+ # per 60s; the first success resets the schedule.
+ now_mono = time.monotonic()
+ backoff = min(2.0**self._consecutive_socket_resets, 60.0)
+ if now_mono - self._last_socket_reset_at < backoff:
+ self._stop.wait(1.0)
+ continue
+ self._needs_socket_reset = False
+ self._last_socket_reset_at = now_mono
+ self._consecutive_socket_resets += 1
+ with suppress(Exception):
+ sock.close()
+ with self._lock:
+ self._joined.clear()
+ try:
+ sock = self._socket_factory()
+ except OSError as exc:
+ now_wall = time.monotonic()
+ if now_wall - last_reset_warn >= 60.0:
+ last_reset_warn = now_wall
+ logger.warning(
+ "multicast socket rebuild failed: %s; retrying",
+ exc,
+ )
+ self._needs_socket_reset = True
+ self._stop.wait(1.0)
+ continue
+ self._socket = sock
+ last_ifaces = 0.0 # force an immediate re-join pass
+ if self._consecutive_socket_resets == 6:
+ self._local_network_blocked_suspected = True
+ logger.critical(
+ "cluster multicast still dead after %d socket "
+ "rebuilds — on macOS this is usually a denied "
+ "Local Network permission (System Settings → "
+ "Privacy & Security → Local Network) or a wedged "
+ "process (a server restart clears it); peers can "
+ "always be added manually via POST "
+ "/api/cluster/devices/manual",
+ self._consecutive_socket_resets,
+ )
+ now = self._clock()
+ if now - last_ifaces >= self.config.iface_poll_interval:
+ self._sync_interfaces(sock)
+ last_ifaces = now
+ if now - last_hello >= self.config.hello_interval:
+ self._send_hello(sock)
+ last_hello = now
+ try:
+ data, addr = sock.recvfrom(_MAX_DATAGRAM)
+ except TimeoutError:
+ continue
+ except OSError:
+ if self._stop.is_set():
+ break
+ continue
+ try:
+ self._handle_datagram(data, addr, sock)
+ except Exception:
+ # A malformed datagram or a handler bug must never kill
+ # the loop (and with it, all discovery).
+ logger.exception("discovery datagram handler failed")
+ finally:
+ with suppress(Exception):
+ sock.close()
+ if self._socket is sock:
+ self._socket = None
+ with self._lock:
+ self._joined.clear()
+
+ def _send_hello(self, sock: Any) -> None:
+ nonce = secrets.randbits(64)
+ with self._lock:
+ self._nonces.append(nonce)
+ payload = encode_hello(nonce, self._cluster_hash)
+ with self._lock:
+ joined = list(self._joined.values()) or [0]
+ any_ok = False
+ last_error: str | None = None
+ now = self._clock()
+ for ifindex in joined:
+ # Link-scope multicast needs the egress interface in the
+ # destination's scope id. (The previous design set
+ # IPV6_MULTICAST_IF on the shared socket per round instead; that
+ # state goes stale when macOS renumbers interfaces on
+ # Thunderbolt hotplug and every send then fails EHOSTUNREACH.)
+ target = (
+ (MULTICAST_GROUP, MULTICAST_PORT, 0, ifindex)
+ if ifindex
+ else (MULTICAST_GROUP, MULTICAST_PORT)
+ )
+ try:
+ sock.sendto(payload, target)
+ any_ok = True
+ except OSError as exc:
+ last_error = f"if {ifindex}: {exc}"
+ if exc.errno not in _JOIN_IGNORED_ERRNOS and (
+ now - self._tx_fail_logged_at.get(ifindex, 0.0)
+ >= _TX_FAIL_LOG_INTERVAL
+ ):
+ self._tx_fail_logged_at[ifindex] = now
+ logger.debug("HELLO send on if %d failed: %s", ifindex, exc)
+ if any_ok:
+ self._consecutive_tx_fail_rounds = 0
+ self._consecutive_socket_resets = 0
+ self._local_network_blocked_suspected = False
+ self._last_tx_ok_wall = time.time()
+ self._last_tx_error = None
+ else:
+ self._consecutive_tx_fail_rounds += 1
+ self._last_tx_error = last_error
+ if self._consecutive_tx_fail_rounds >= _TX_FAIL_RESET_ROUNDS and any(
+ joined
+ ):
+ if self._consecutive_tx_fail_rounds == _TX_FAIL_RESET_ROUNDS:
+ # Log once per failure streak; the loop's backoff
+ # schedule paces the actual rebuilds from here.
+ logger.warning(
+ "HELLO sends failed on every joined interface for "
+ "%d rounds; scheduling multicast socket rebuild",
+ self._consecutive_tx_fail_rounds,
+ )
+ self._needs_socket_reset = True
+
+ def _handle_datagram(self, data: bytes, addr: Any, sock: Any = None) -> None:
+ hello = decode_hello(data)
+ if hello is not None:
+ self._handle_hello(hello[0], hello[1], addr, sock)
+ return
+ wassup = decode_wassup(data)
+ if wassup is not None:
+ self._handle_wassup(wassup, addr)
+
+ def _handle_hello(
+ self, nonce: int, cluster_hash: int, addr: Any, sock: Any = None
+ ) -> None:
+ if cluster_hash != self._cluster_hash:
+ # A foreign oMLX cluster shares the LAN; ignore silently for
+ # discovery but make the situation diagnosable (once).
+ if not self._hash_mismatch_logged:
+ self._hash_mismatch_logged = True
+ logger.info(
+ "Ignoring cluster HELLO with a non-matching cluster hash "
+ "(another oMLX cluster on this LAN?)"
+ )
+ return
+ with self._lock:
+ if nonce in self._nonces:
+ return # nonce-echo self-drop: our own HELLO came back
+ self._last_hello_at = self._clock()
+ self._last_hello_wall = time.time()
+ # Inbound multicast works, so any Local Network permission wedge is
+ # definitively over.
+ self._local_network_blocked_suspected = False
+ if isinstance(addr, tuple):
+ peer_ip = addr[0]
+ peer_port = addr[1]
+ scope_id = addr[3] if len(addr) > 3 else 0
+ else:
+ peer_ip, peer_port, scope_id = str(addr), MULTICAST_PORT, 0
+ # Answer unicast so the sender learns our node_id + http_port. A
+ # link-local HELLO source requires the ingress interface as scope id
+ # in the reply destination; without it the kernel has no route and
+ # the handshake silently never completes.
+ reply = encode_wassup(nonce, self.identity.node_id, self.config.http_port)
+ target_sock = sock if sock is not None else self._socket
+ if target_sock is not None:
+ target = (
+ (peer_ip, peer_port, 0, scope_id) if scope_id else (peer_ip, peer_port)
+ )
+ try:
+ target_sock.sendto(reply, target)
+ except OSError as exc:
+ now = self._clock()
+ if (
+ now - self._reply_fail_logged_at.get(peer_ip, 0.0)
+ >= _TX_FAIL_LOG_INTERVAL
+ ):
+ self._reply_fail_logged_at[peer_ip] = now
+ logger.debug("WASSUP reply to %s failed: %s", peer_ip, exc)
+
+ def _handle_wassup(self, payload: dict[str, Any], addr: Any) -> None:
+ with self._lock:
+ if payload["nonce"] not in self._nonces:
+ return # not an echo of a nonce we issued
+ node_id = payload["node_id"]
+ if node_id == self.identity.node_id:
+ return
+ peer_ip = addr[0] if isinstance(addr, tuple) else str(addr)
+ if "%" in peer_ip:
+ peer_ip = peer_ip.split("%", 1)[0]
+ now = self._clock()
+ with self._lock:
+ peer = self._peers.get(node_id)
+ is_new = peer is None
+ if peer is None:
+ peer = PeerRecord(node_id=node_id)
+ self._peers[node_id] = peer
+ peer.http_port = payload["http_port"]
+ peer.last_seen = now
+ if peer.state == "dead":
+ peer.state = "discovered"
+ if not any(a["ip"] == peer_ip for a in peer.addrs):
+ peer.addrs.append({"ip": peer_ip, "if_type": "unknown"})
+ peer.addrs = peer.addrs[-8:]
+ self._merge_registry(peer)
+ self._add_candidate(
+ peer_ip, payload["http_port"], node_id=node_id, if_type="unknown"
+ )
+ if is_new:
+ self._fire_change(peer)
+ # Higher node_id (string compare) initiates contact: the higher node
+ # probes immediately; the lower node's next periodic probe sweep
+ # verifies its own candidate entry.
+ if self.identity.node_id > node_id:
+ self._probe_candidate(peer_ip, payload["http_port"])
+
+ def _add_candidate(
+ self, ip: str, port: int, *, node_id: str | None, if_type: str
+ ) -> None:
+ with self._lock:
+ if len(self._candidates) >= _MAX_CANDIDATES:
+ return
+ key = (ip, port)
+ candidate = self._candidates.get(key)
+ if candidate is None:
+ candidate = {
+ "node_id": node_id,
+ "if_type": if_type,
+ # Due immediately even when oMLX starts within the first
+ # few seconds after boot and the monotonic clock is < the
+ # normal probe interval.
+ "last_probe": float("-inf"),
+ "rtt": None,
+ "verified": False,
+ }
+ self._candidates[key] = candidate
+ else:
+ if node_id:
+ candidate["node_id"] = node_id
+ if if_type != "unknown":
+ candidate["if_type"] = if_type
+
+ def _probe_sweep(self) -> None:
+ now = self._clock()
+ with self._lock:
+ due = [
+ (ip, port)
+ for (ip, port), candidate in self._candidates.items()
+ if now - candidate["last_probe"]
+ >= (
+ self.config.heartbeat_interval
+ if candidate.get("verified")
+ else self.config.probe_interval
+ )
+ ]
+ due.sort(
+ key=lambda key: (
+ not bool(self._candidates[key].get("verified")),
+ self._candidates[key].get("node_id") is None,
+ self._candidates[key].get("if_type") != "paired",
+ )
+ )
+ for ip, port in due:
+ self._probe_candidate(ip, port)
+
+ def _probe_candidate(self, ip: str, port: int) -> None:
+ with self._lock:
+ candidate = self._candidates.get((ip, port))
+ if candidate is None:
+ return
+ candidate["last_probe"] = self._clock()
+ hint = candidate["node_id"]
+ if_type = candidate["if_type"]
+ started = self._clock()
+ _probe_diagnostics.value = None
+ try:
+ result = self._prober(ip, port, self.config.probe_timeout)
+ except Exception as exc:
+ result = None
+ diagnostic = {
+ "transport": "custom",
+ "error": str(exc),
+ }
+ else:
+ diagnostic = getattr(_probe_diagnostics, "value", None) or {
+ "transport": "custom",
+ "error": "" if result is not None else "probe returned no identity",
+ }
+ rtt = self._clock() - started
+ if result is None:
+ with self._lock:
+ candidate = self._candidates.get((ip, port))
+ if candidate is not None:
+ candidate["last_transport"] = diagnostic.get("transport")
+ candidate["last_error"] = diagnostic.get("error")
+ return
+ node_id = result.get("node_id")
+ if hint is not None and node_id != hint:
+ # Announced address does not answer with the announced node_id —
+ # drop it (stale DHCP lease, spoofed announcement, etc.).
+ with self._lock:
+ self._candidates.pop((ip, port), None)
+ peer = self._peers.get(hint)
+ if peer is not None:
+ peer.addrs = [a for a in peer.addrs if a["ip"] != ip]
+ return
+ now = self._clock()
+ with self._lock:
+ candidate = self._candidates.get((ip, port))
+ if candidate is not None:
+ candidate["verified"] = True
+ candidate["rtt"] = rtt
+ candidate["node_id"] = node_id
+ candidate["last_transport"] = diagnostic.get("transport")
+ candidate["last_error"] = ""
+ peer = self._peers.get(node_id)
+ is_new = peer is None
+ if peer is None:
+ peer = PeerRecord(node_id=node_id)
+ self._peers[node_id] = peer
+ peer.version = str(result.get("version") or peer.version)
+ peer.cluster_name = str(result.get("cluster_name") or peer.cluster_name)
+ if result.get("friendly_name"):
+ peer.friendly_name = str(result["friendly_name"])
+ peer.http_port = port
+ peer.last_seen = now
+ if not any(a["ip"] == ip for a in peer.addrs):
+ peer.addrs.append({"ip": ip, "if_type": if_type})
+ peer.addrs = peer.addrs[-8:]
+ peer.link = _classify_link(ip, if_type, rtt)
+ self._merge_registry(peer)
+ if is_new:
+ self._fire_change(peer)
+
+ def _merge_registry(self, peer: PeerRecord) -> None:
+ if self.registry is None:
+ return
+ try:
+ self.registry.merge(
+ {
+ "node_id": peer.node_id,
+ "friendly_name": peer.friendly_name,
+ "caps": peer.caps.to_dict(),
+ "addrs": peer.addrs,
+ "http_port": peer.http_port,
+ }
+ )
+ with self._lock:
+ peer.paired = bool(self.registry.is_paired(peer.node_id))
+ except Exception:
+ logger.debug("device registry merge failed", exc_info=True)
+
+ def _liveness_sweep(self) -> None:
+ now = self._clock()
+ transitions: list[PeerRecord] = []
+ with self._lock:
+ for peer in self._peers.values():
+ silence = now - peer.last_seen
+ if silence >= self.config.dead_after:
+ target = "dead"
+ elif silence >= self.config.suspect_after:
+ target = "suspect"
+ else:
+ target = "discovered"
+ if peer.state != target:
+ peer.state = target
+ transitions.append(peer)
+ for peer in transitions:
+ self._fire_change(peer)
+
+ def _maintenance_loop(self) -> None:
+ last_probe = 0.0
+ last_tailscale = 0.0
+ sweep_interval = min(
+ self.config.probe_interval,
+ self.config.heartbeat_interval,
+ )
+ while not self._stop.is_set():
+ now = self._clock()
+ if now - last_probe >= sweep_interval:
+ self._probe_sweep()
+ last_probe = now
+ self._liveness_sweep()
+ if (
+ self.config.enable_tailscale
+ and now - last_tailscale >= self.config.tailscale_interval
+ ):
+ self._tailscale_sweep()
+ last_tailscale = now
+ self._stop.wait(0.5)
+
+ # -- Tailscale (opportunistic, never required) ---------------------------
+
+ @staticmethod
+ def _read_tailscale_status() -> dict[str, Any] | None:
+ executable = _tailscale_executable()
+ if executable is None:
+ return None
+ try:
+ result = subprocess.run( # noqa: S603 - tailscale CLI lookup
+ [executable, "status", "--json"],
+ capture_output=True,
+ text=True,
+ timeout=5.0,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if result.returncode != 0:
+ return None
+ try:
+ payload = json.loads(result.stdout)
+ except json.JSONDecodeError:
+ return None
+ return payload if isinstance(payload, dict) else None
+
+ def _tailscale_sweep(self) -> None:
+ try:
+ status = self._tailscale_status()
+ except Exception:
+ return
+ if not status:
+ return
+ peers = status.get("Peer")
+ if not isinstance(peers, dict):
+ return
+ for entry in peers.values():
+ if not isinstance(entry, dict):
+ continue
+ if entry.get("Online") is False:
+ continue
+ ips = entry.get("TailscaleIPs")
+ if not isinstance(ips, list):
+ continue
+ for ip in ips:
+ if isinstance(ip, str) and ip.startswith("100."):
+ # Peer's oMLX port is unknown; our own configured port is
+ # the best heuristic (documented — Tailscale is
+ # opportunistic, never required).
+ self._add_candidate(
+ ip,
+ self.config.http_port,
+ node_id=None,
+ if_type="tailscale",
+ )
+
+ # -- mDNS (python-zeroconf, optional) ------------------------------------
+
+ def _start_mdns(self) -> None:
+ zc = self._zc
+ addresses = self._local_addresses()
+ caps_json = json.dumps(self.config.caps.to_dict(), separators=(",", ":"))
+ properties = {
+ "id": self.identity.node_id,
+ "name": self.identity.friendly_name,
+ "ver": self.config.version,
+ "cl": self.config.cluster_name,
+ "caps": caps_json,
+ "port": str(self.config.http_port),
+ }
+ instance = f"{self.identity.friendly_name}.{MDNS_SERVICE_TYPE}"[:255]
+ info = zc.ServiceInfo(
+ MDNS_SERVICE_TYPE,
+ instance,
+ addresses=addresses,
+ port=self.config.http_port,
+ properties=properties,
+ )
+ self._zc_instance = zc.Zeroconf()
+ self._zc_info = info
+ listener = _MdnsListener(self)
+ self._zc_browser = zc.ServiceBrowser(
+ self._zc_instance, MDNS_SERVICE_TYPE, listener
+ )
+ self._zc_instance.register_service(info)
+
+ @staticmethod
+ def _local_addresses() -> list[bytes]:
+ packed: list[bytes] = []
+ with suppress(OSError):
+ hostname = socket.gethostname()
+ for family, _, _, _, sockaddr in socket.getaddrinfo(hostname, None):
+ if family == socket.AF_INET:
+ packed.append(socket.inet_pton(family, sockaddr[0]))
+ elif family == socket.AF_INET6 and not sockaddr[0].startswith(
+ "fe80::1" # skip loopback-ish
+ ):
+ packed.append(
+ socket.inet_pton(family, sockaddr[0].split("%", 1)[0])
+ )
+ return packed[:8]
+
+ def _handle_mdns_service(self, info: Any) -> None:
+ """Process one resolved _omlx._tcp service (zeroconf callback path)."""
+
+ try:
+ props = {
+ (k.decode("utf-8", "replace") if isinstance(k, bytes) else k): (
+ v.decode("utf-8", "replace") if isinstance(v, bytes) else v
+ )
+ for k, v in (info.properties or {}).items()
+ }
+ node_id = str(props.get("id") or "")
+ if not node_id or node_id == self.identity.node_id:
+ return
+ cluster = str(props.get("cl") or "")
+ if cluster != self.config.cluster_name:
+ if not self._hash_mismatch_logged:
+ self._hash_mismatch_logged = True
+ logger.info(
+ "Ignoring mDNS service for a different oMLX cluster (%r != %r)",
+ cluster,
+ self.config.cluster_name,
+ )
+ return
+ try:
+ caps = PeerCaps.from_dict(json.loads(props.get("caps") or "{}"))
+ except json.JSONDecodeError:
+ caps = PeerCaps()
+ port = int(getattr(info, "port", 0) or 0)
+ addresses: list[str] = []
+ parsed = getattr(info, "parsed_addresses", None)
+ if callable(parsed):
+ addresses = [a for a in parsed() if isinstance(a, str)]
+ now = self._clock()
+ with self._lock:
+ peer = self._peers.get(node_id)
+ is_new = peer is None
+ if peer is None:
+ peer = PeerRecord(node_id=node_id)
+ self._peers[node_id] = peer
+ peer.friendly_name = str(props.get("name") or peer.friendly_name)
+ peer.version = str(props.get("ver") or peer.version)
+ peer.cluster_name = cluster
+ peer.caps = caps
+ if port:
+ peer.http_port = port
+ peer.last_seen = now
+ for ip in addresses:
+ if not any(a["ip"] == ip for a in peer.addrs):
+ peer.addrs.append({"ip": ip, "if_type": "mdns"})
+ peer.addrs = peer.addrs[-8:]
+ self._merge_registry(peer)
+ if port:
+ for ip in addresses:
+ self._add_candidate(ip, port, node_id=node_id, if_type="mdns")
+ if is_new:
+ self._fire_change(peer)
+ except Exception:
+ # mDNS callbacks run on zeroconf threads; nothing here may kill
+ # the process (macOS gotcha #3).
+ logger.exception("failed to process mDNS service")
+
+
+class _MdnsListener:
+ """zeroconf ServiceListener adapter; every callback is exception-safe."""
+
+ def __init__(self, service: DiscoveryService) -> None:
+ self._service = service
+
+ def _resolve(self, zc: Any, type_: str, name: str) -> None:
+ try:
+ info = zc.get_service_info(type_, name, timeout=3000)
+ except Exception:
+ return
+ if info is not None:
+ self._service._handle_mdns_service(info)
+
+ # zeroconf >= 0.28 style
+ def add_service(self, zc: Any, type_: str, name: str) -> None:
+ self._resolve(zc, type_, name)
+
+ def update_service(self, zc: Any, type_: str, name: str) -> None:
+ self._resolve(zc, type_, name)
+
+ def remove_service(self, zc: Any, type_: str, name: str) -> None:
+ pass
+
+ # older zeroconf style
+ def update_service_callback(self, *args: Any, **kwargs: Any) -> None:
+ pass
+
+
+_discovery_service_lock = threading.Lock()
+_configured_discovery_service: DiscoveryService | None = None
+
+
+def configure_discovery_service(
+ service: DiscoveryService | None,
+) -> DiscoveryService | None:
+ """Set (or clear) the process-wide discovery service for the endpoints."""
+
+ global _configured_discovery_service
+ with _discovery_service_lock:
+ _configured_discovery_service = service
+ return _configured_discovery_service
+
+
+def get_discovery_service() -> DiscoveryService:
+ with _discovery_service_lock:
+ if _configured_discovery_service is None:
+ raise RuntimeError("cluster discovery service is not configured")
+ return _configured_discovery_service
+
+
+def announced_caps() -> dict[str, Any]:
+ """Return the same best-effort capabilities advertised by discovery."""
+
+ try:
+ service = get_discovery_service()
+ except RuntimeError:
+ service = None
+ if service is not None:
+ try:
+ caps = service.config.caps.to_dict()
+ except Exception: # pragma: no cover - defensive
+ caps = {}
+ if caps:
+ return caps
+ try:
+ return local_caps().to_dict()
+ except Exception: # pragma: no cover - defensive
+ return {}
+
+
+def announced_addrs() -> list[str]:
+ """Validated local addresses included in an approved pairing record."""
+
+ return [
+ str(address["ip"])
+ for address in local_addr_dicts()
+ if isinstance(address, dict) and address.get("ip")
+ ][:8]
diff --git a/omlx/cluster/discovery_routes.py b/omlx/cluster/discovery_routes.py
new file mode 100644
index 0000000000..3f6706d698
--- /dev/null
+++ b/omlx/cluster/discovery_routes.py
@@ -0,0 +1,393 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Cluster v2 discovery/identity HTTP endpoints.
+
+``discovery_router`` is mounted WITHOUT ``require_admin`` in
+``omlx/server.py`` so peers can probe ``/api/cluster/node_id`` before any
+trust exists; it is still gated by the distributed-inference exposure flag
+(``require_distributed_inference_enabled``) like the enrollment router. The
+probe endpoint is rate-limited per source IP. ``/api/cluster/devices``
+carries the trusted inventory and requires admin like the rest of the
+cluster surface.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import ipaddress
+import threading
+import time
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException, Request
+
+from .._version import __version__
+from ..admin.auth import require_admin
+from .discovery import local_addr_dicts
+from .identity import get_node_identity
+from .registry import get_device_registry
+
+discovery_router = APIRouter(prefix="/api/cluster", tags=["cluster-discovery"])
+
+
+class ProbeRateLimiter:
+ """Token-bucket rate limiter for the unauthenticated probe endpoint."""
+
+ def __init__(self, rate_per_second: float = 5.0, burst: int = 10) -> None:
+ self._rate = float(rate_per_second)
+ self._burst = int(burst)
+ self._buckets: dict[str, tuple[float, float]] = {}
+ self._lock = threading.Lock()
+
+ def allow(self, key: str, now: float | None = None) -> bool:
+ now = time.monotonic() if now is None else now
+ with self._lock:
+ tokens, updated = self._buckets.get(key, (float(self._burst), now))
+ tokens = min(float(self._burst), tokens + (now - updated) * self._rate)
+ if tokens < 1.0:
+ self._buckets[key] = (tokens, now)
+ return False
+ self._buckets[key] = (tokens - 1.0, now)
+ # Bound the map: drop idle buckets once it grows past 4096 keys.
+ if len(self._buckets) > 4096:
+ self._buckets = {
+ k: v for k, v in self._buckets.items() if now - v[1] < 600.0
+ }
+ return True
+
+
+probe_rate_limiter = ProbeRateLimiter()
+
+
+def discovery_service_or_none():
+ from .discovery import get_discovery_service
+
+ try:
+ return get_discovery_service()
+ except RuntimeError:
+ return None
+
+
+def _cluster_name() -> str:
+ service = discovery_service_or_none()
+ if service is not None:
+ return service.config.cluster_name
+ # Discovery disabled still reports the persisted settings-level name.
+ from .discovery import load_cluster_name
+
+ return load_cluster_name()
+
+
+@discovery_router.get("/node_id")
+async def cluster_node_id_probe(request: Request):
+ """Public, rate-limited identity probe used by peer verification.
+
+ Deliberately unauthenticated: a discovering node must be able to confirm
+ an announced address belongs to the announced node_id before any pairing
+ trust exists. It reveals only the stable node_id, the oMLX version, and
+ the cluster name — no capabilities, no device inventory.
+ """
+
+ client = request.client.host if request.client else "unknown"
+ if not probe_rate_limiter.allow(client):
+ raise HTTPException(
+ status_code=429,
+ detail="probe rate limit exceeded",
+ headers={"Retry-After": "1"},
+ )
+ try:
+ identity = get_node_identity()
+ except RuntimeError as exc:
+ raise HTTPException(
+ status_code=503, detail="cluster identity is not configured"
+ ) from exc
+ return {
+ "node_id": identity.node_id,
+ "version": __version__,
+ "cluster_name": _cluster_name(),
+ }
+
+
+@discovery_router.get("/discovery/health")
+async def cluster_discovery_health(is_admin: bool = Depends(require_admin)):
+ """Local-network self-test for the wizard's checks row.
+
+ ``multicast_rx_within_5s`` is False when no foreign HELLO arrived in the
+ last five seconds — on macOS that is how a denied Local Network
+ permission presents, so the UI pairs it with actionable guidance instead
+ of a silently empty device list. Shape is pinned by the wizard fixture
+ (tests/ui/fixtures/cluster_v2/discovery_health_ok.json).
+ """
+
+ service = discovery_service_or_none()
+ if service is None:
+ return {
+ "multicast_rx_within_5s": False,
+ "last_multicast_rx_at": None,
+ "mdns_active": False,
+ "transport": "disabled",
+ }
+ return {
+ "multicast_rx_within_5s": bool(service.multicast_ok),
+ "last_multicast_rx_at": service.last_multicast_rx_at,
+ "mdns_active": bool(service.mdns_active),
+ "transport": service.transport_summary(),
+ }
+
+
+@discovery_router.get("/discovery/health/detail")
+async def cluster_discovery_health_detail(
+ is_admin: bool = Depends(require_admin),
+):
+ """Extended discovery self-diagnostics (loop liveness, TX health).
+
+ Separate route so the pinned wizard fixture shape on
+ ``/discovery/health`` stays untouched. This is how "no peers nearby" is
+ distinguished from "discovery loop dead / socket wedged / interface
+ renumbered underneath us" in the field.
+ """
+
+ service = discovery_service_or_none()
+ if service is None:
+ raise HTTPException(status_code=503, detail="discovery is disabled")
+ return service.health()
+
+
+@discovery_router.post("/devices/manual")
+async def cluster_add_manual_peer(
+ request: Request, is_admin: bool = Depends(require_admin)
+):
+ """Manually add a peer by IP — the deterministic path over Thunderbolt.
+
+ Multicast is best-effort on macOS (Local Network permission, interface
+ renumbering, routers that filter v6 multicast). When two machines share
+ a direct Thunderbolt link, pointing each node at the other's link
+ address (typically the 10.0.0.x pair) skips all of that. The candidate
+ is verified through the same HTTP probe path as multicast-discovered
+ peers before it is returned as verified.
+ """
+
+ service = discovery_service_or_none()
+ if service is None:
+ raise HTTPException(status_code=503, detail="discovery is disabled")
+ client = request.client.host if request.client else "unknown"
+ if not probe_rate_limiter.allow(client):
+ raise HTTPException(
+ status_code=429,
+ detail="probe rate limit exceeded",
+ headers={"Retry-After": "1"},
+ )
+ try:
+ body = await request.json()
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail="invalid JSON body") from exc
+ if not isinstance(body, dict):
+ raise HTTPException(status_code=400, detail="invalid JSON body")
+ raw_ip = body.get("ip")
+ try:
+ ip = str(ipaddress.ip_address(str(raw_ip)))
+ except ValueError as exc:
+ raise HTTPException(
+ status_code=400, detail=f"invalid IP address: {raw_ip!r}"
+ ) from exc
+ port = body.get("port", 8000)
+ if not isinstance(port, int) or isinstance(port, bool) or not (1 <= port <= 65535):
+ raise HTTPException(status_code=400, detail="invalid port")
+ service.add_manual(ip, port)
+ # Probe synchronously (bounded by the configured probe timeout) so the
+ # caller learns immediately whether the address answers as an oMLX node.
+ await asyncio.to_thread(service.probe_candidate_now, ip, port)
+ peer = next(
+ (p for p in service.peers() if any(a["ip"] == ip for a in p.addrs)),
+ None,
+ )
+ return {
+ "ok": True,
+ "ip": ip,
+ "port": port,
+ "verified": peer is not None,
+ "peer": peer.to_dict() if peer is not None else None,
+ }
+
+
+def _enrich_paired_row(row: dict[str, Any], record: dict[str, Any] | None) -> None:
+ """Fill gaps on a paired row from the matching discovery record.
+
+ Pairings completed before capabilities were exchanged persisted empty
+ ``caps``; the matching registry/service record carries the announced
+ values. Only fields actually known are merged — nothing is fabricated —
+ and the persisted row is untouched (the route returns copies). The row
+ also gains a normalized ``addrs`` list of ``{"ip", "if_type"}`` dicts,
+ sourced from ``last_addrs`` plus the discovered record, so the UI's
+ address pickers read paired rows the same way as discovered rows.
+ """
+
+ addrs: list[dict[str, str]] = []
+ for ip in row.get("last_addrs") or []:
+ if isinstance(ip, str) and ip and all(a["ip"] != ip for a in addrs):
+ addrs.append({"ip": ip, "if_type": "paired"})
+ if record is not None:
+ for addr in record.get("addrs") or []:
+ if not isinstance(addr, dict) or not addr.get("ip"):
+ continue
+ existing = next((a for a in addrs if a["ip"] == addr["ip"]), None)
+ if existing is not None:
+ # The discovered entry knows the real interface type.
+ existing["if_type"] = addr.get("if_type") or existing["if_type"]
+ elif len(addrs) < 16:
+ addrs.append(
+ {
+ "ip": addr["ip"],
+ "if_type": addr.get("if_type") or "discovered",
+ }
+ )
+ if addrs:
+ row["addrs"] = addrs
+ # Persisted membership is not liveness. Until this process has observed the
+ # peer, render an amber/suspect shell instead of the old implicit green row.
+ row.setdefault("http_port", 0)
+ if record is None:
+ row["state"] = "suspect"
+ row["last_seen"] = None
+ row.setdefault("link", "unknown")
+ return
+ caps = row.get("caps") or {}
+ if not caps.get("ram_gb") or not caps.get("chip"):
+ known_caps = record.get("caps") or {}
+ if known_caps.get("ram_gb") or known_caps.get("chip"):
+ row["caps"] = dict(known_caps)
+ for key in ("version", "friendly_name"):
+ if record.get(key):
+ row[key] = record[key]
+ state = record.get("state")
+ row["state"] = state if state in {"discovered", "suspect", "dead"} else "suspect"
+ last_seen = record.get("last_seen")
+ row["last_seen"] = (
+ float(last_seen)
+ if isinstance(last_seen, (int, float)) and not isinstance(last_seen, bool)
+ else None
+ )
+ row["link"] = str(record.get("link") or "unknown")
+ http_port = record.get("http_port")
+ if (
+ isinstance(http_port, int)
+ and not isinstance(http_port, bool)
+ and 1 <= http_port <= 65535
+ ):
+ row["http_port"] = http_port
+
+
+@discovery_router.get("/devices")
+async def cluster_devices(is_admin: bool = Depends(require_admin)):
+ """Cluster device inventory for the wizard UI.
+
+ ``multicast_ok`` is the macOS Local Network permission signal: it is
+ False when no foreign HELLO was received in the last 5 seconds, which is
+ how a denied/blocked local-network permission presents. The UI should
+ surface "check System Settings → Privacy & Security → Local Network"
+ rather than showing a silently empty device list.
+ """
+
+ try:
+ identity = get_node_identity()
+ except RuntimeError as exc:
+ raise HTTPException(
+ status_code=503, detail="cluster identity is not configured"
+ ) from exc
+
+ try:
+ registry = get_device_registry()
+ except RuntimeError:
+ registry = None
+ service = discovery_service_or_none()
+
+ paired: list[dict[str, Any]] = registry.paired() if registry else []
+ paired_ids = {row["node_id"] for row in paired}
+ # Membership in this list IS the paired state, but the registry rows do
+ # not carry the flag themselves -- the self record below sets it
+ # explicitly. Without it, wizard consumers keyed on device.paired (the
+ # per-Mac role list, the card's Pair/Paired state) treat an already
+ # paired peer as unpaired.
+ for row in paired:
+ row["paired"] = True
+
+ # Seam with Module B's enrollment: a paired device that completed SSH
+ # TOFU enrollment carries its enrolled ssh_target, so the UI probes and
+ # plans against the enrolled target instead of guessing from probe IPs.
+ try:
+ from .enrollment import get_cluster_enrollment
+
+ enrollment = get_cluster_enrollment()
+ except RuntimeError:
+ enrollment = None
+ if enrollment is not None:
+ enrolled = {node.node_id: node for node in enrollment.list_nodes()}
+ for row in paired:
+ node = enrolled.get(row.get("node_id"))
+ if node is not None:
+ row["ssh_target"] = node.ssh
+ observed_records: dict[str, dict[str, Any]] = {}
+ if registry:
+ for entry in registry.discovered():
+ observed_records[entry["node_id"]] = entry
+ if service is not None:
+ for peer in service.peers():
+ # Paired peers still belong in the observation map: their live
+ # state, timestamp, port and interface metadata enrich the durable
+ # paired shell. They are filtered only from the unpaired list.
+ observed_records[peer.node_id] = peer.to_dict()
+ discovered_records = {
+ node_id: record
+ for node_id, record in observed_records.items()
+ if node_id not in paired_ids and not record.get("paired")
+ }
+
+ # Devices paired before caps were exchanged carry empty caps on disk;
+ # enrich them from what discovery has actually seen before suppressing
+ # their node_ids from the discovered list below.
+ for row in paired:
+ _enrich_paired_row(row, observed_records.get(row.get("node_id")))
+
+ # Nothing flips the discovery service's in-memory ``PeerRecord.paired``
+ # the moment pairing completes, so a stale (possibly dead) record for a
+ # now-paired node_id would otherwise render a zombie "Pair" card next
+ # to the paired row. Paired node_ids never appear as discovered.
+ for node_id in paired_ids:
+ discovered_records.pop(node_id, None)
+
+ # Seam with Module B: a posted pair/request must surface in the device
+ # list as an awaiting_approval row so the wizard renders code entry +
+ # approve/deny (fixture: tests/ui/.../devices_pending_approval.json).
+ # Pending state wins over a plain discovered record for the same node.
+ try:
+ from .pairing import get_pairing_manager
+
+ pairing_manager = get_pairing_manager()
+ except RuntimeError:
+ pairing_manager = None
+ if pairing_manager is not None:
+ for pending in pairing_manager.pending_requests():
+ row = dict(discovered_records.get(pending["node_id"], {}))
+ row.update(pending)
+ row["state"] = "awaiting_approval"
+ discovered_records[pending["node_id"]] = row
+
+ self_record: dict[str, Any] = {
+ "node_id": identity.node_id,
+ "friendly_name": identity.friendly_name,
+ "version": __version__,
+ "cluster_name": _cluster_name(),
+ "caps": service.config.caps.to_dict() if service is not None else {},
+ "addrs": local_addr_dicts(),
+ "http_port": service.config.http_port if service is not None else 0,
+ "paired": True,
+ "last_seen": time.time(),
+ "link": "unknown",
+ "state": "discovered",
+ }
+ return {
+ "paired": paired,
+ "discovered": list(discovered_records.values()),
+ "self": self_record,
+ "multicast_ok": bool(service.multicast_ok) if service else False,
+ "mdns_available": bool(service.mdns_available) if service else False,
+ }
diff --git a/omlx/cluster/identity.py b/omlx/cluster/identity.py
new file mode 100644
index 0000000000..07178b4353
--- /dev/null
+++ b/omlx/cluster/identity.py
@@ -0,0 +1,251 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Stable per-node identity for oMLX cluster v2.
+
+Every node owns a ``NodeIdentity`` persisted at
+``~/.omlx/cluster/identity.json`` (mode 0600, atomic write). The ``node_id``
+is an immutable uuid4 string; the ``friendly_name`` is display-only and may
+be renamed or collision-repaired without affecting pairing, discovery, or
+deployments, which all key on ``node_id``.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+import socket
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import uuid
+from collections.abc import Callable, Iterable
+from contextlib import suppress
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+IDENTITY_SCHEMA_VERSION = 1
+_MAX_NAME_LENGTH = 63
+_NAME_SANITIZE = re.compile(r"\s+")
+
+
+def default_identity_path() -> Path:
+ """Default on-disk location, honoring the OMLX_BASE_PATH override."""
+
+ env_value = os.environ.get("OMLX_BASE_PATH")
+ base = Path(env_value).expanduser() if env_value else Path.home() / ".omlx"
+ return base / "cluster" / "identity.json"
+
+
+def _scutil_local_hostname() -> str | None:
+ """Best-effort macOS LocalHostName; ``None`` off-macOS or on failure."""
+
+ if sys.platform != "darwin":
+ return None
+ try:
+ result = subprocess.run( # noqa: S603 - fixed system executable
+ ["/usr/sbin/scutil", "--get", "LocalHostName"],
+ capture_output=True,
+ text=True,
+ timeout=2.0,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if result.returncode != 0:
+ return None
+ name = result.stdout.strip()
+ return name or None
+
+
+def _default_friendly_name() -> str:
+ for candidate in (_scutil_local_hostname(), socket.gethostname()):
+ if candidate:
+ name = _NAME_SANITIZE.sub("-", candidate.strip())[:_MAX_NAME_LENGTH]
+ if name:
+ return name
+ return "omlx-node"
+
+
+def _resolve_collision(name: str, taken: set[str]) -> str:
+ """Suffix ``-2``, ``-3`` ... until the friendly name is unique."""
+
+ if name not in taken:
+ return name
+ for suffix in range(2, 1000):
+ candidate = f"{name}-{suffix}"
+ if candidate not in taken:
+ return candidate
+ # Absurdly unlikely; fall back to a random tail rather than loop forever.
+ return f"{name}-{uuid.uuid4().hex[:6]}"
+
+
+@dataclass
+class NodeIdentity:
+ """A node's stable identity. ``node_id`` never changes once created."""
+
+ node_id: str
+ friendly_name: str
+ created_at: float
+ schema_version: int = IDENTITY_SCHEMA_VERSION
+ _path: Path | None = field(default=None, repr=False, compare=False)
+ load_error: str | None = field(default=None, repr=False, compare=False)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "schema_version": self.schema_version,
+ "node_id": self.node_id,
+ "friendly_name": self.friendly_name,
+ "created_at": self.created_at,
+ }
+
+ @classmethod
+ def from_dict(cls, payload: dict[str, Any]) -> NodeIdentity:
+ if not isinstance(payload, dict):
+ raise ValueError("cluster identity is malformed")
+ if payload.get("schema_version") != IDENTITY_SCHEMA_VERSION:
+ raise ValueError("unsupported cluster identity schema version")
+ node_id = payload.get("node_id")
+ friendly_name = payload.get("friendly_name")
+ created_at = payload.get("created_at")
+ if not isinstance(node_id, str) or not node_id:
+ raise ValueError("cluster identity is missing a node_id")
+ if not isinstance(friendly_name, str) or not friendly_name:
+ raise ValueError("cluster identity is missing a friendly_name")
+ if not isinstance(created_at, (int, float)):
+ raise ValueError("cluster identity is missing created_at")
+ return cls(
+ node_id=node_id,
+ friendly_name=friendly_name,
+ created_at=float(created_at),
+ )
+
+ def rename(self, new_name: str) -> None:
+ """Update the display name and persist it. ``node_id`` is immutable."""
+
+ cleaned = _NAME_SANITIZE.sub("-", str(new_name).strip())[:_MAX_NAME_LENGTH]
+ if not cleaned:
+ raise ValueError("friendly name must not be empty")
+ self.friendly_name = cleaned
+ if self._path is not None:
+ _atomic_save(self._path, self.to_dict())
+
+
+def _atomic_save(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ descriptor, temporary = tempfile.mkstemp(
+ prefix=".identity.", suffix=".tmp", dir=path.parent
+ )
+ try:
+ os.fchmod(descriptor, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ json.dump(payload, stream, indent=2, sort_keys=True)
+ stream.write("\n")
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ os.chmod(path, 0o600)
+ finally:
+ with suppress(FileNotFoundError):
+ os.unlink(temporary)
+
+
+def load_or_create(
+ path: Path | str | None = None,
+ *,
+ taken_names: Iterable[str] = (),
+ clock: Callable[[], float] = time.time,
+) -> NodeIdentity:
+ """Load the persisted identity, creating and persisting one if absent.
+
+ ``taken_names`` lists friendly names already claimed by other cluster
+ members; on collision the loaded/created name gains a ``-2`` suffix
+ (escalating as needed) while ``node_id`` stays untouched.
+
+ A corrupt identity file never rotates ``node_id`` silently: the corrupt
+ file is left on disk for inspection, a fresh in-memory identity is
+ returned with ``load_error`` set, and nothing is written.
+ """
+
+ identity_path = Path(path) if path is not None else default_identity_path()
+ taken = {name for name in taken_names}
+
+ identity: NodeIdentity | None = None
+ load_error: str | None = None
+ if identity_path.exists():
+ try:
+ payload = json.loads(identity_path.read_text(encoding="utf-8"))
+ identity = NodeIdentity.from_dict(payload)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ load_error = f"could not read cluster identity: {exc}"
+ logger.warning(
+ "%s at %s; using a fresh in-memory identity (the corrupt "
+ "file was left untouched)",
+ load_error,
+ identity_path,
+ )
+
+ created = identity is None
+ if identity is None:
+ identity = NodeIdentity(
+ node_id=str(uuid.uuid4()),
+ friendly_name=_default_friendly_name(),
+ created_at=clock(),
+ )
+ identity._path = identity_path
+ identity.load_error = load_error
+
+ repaired = _resolve_collision(identity.friendly_name, taken)
+ collision_repaired = repaired != identity.friendly_name
+ identity.friendly_name = repaired
+
+ # Persist on first creation or when collision repair changed the name —
+ # but never overwrite a file we failed to parse.
+ if load_error is None and (created or collision_repaired):
+ try:
+ _atomic_save(identity_path, identity.to_dict())
+ except OSError as exc:
+ identity.load_error = f"could not persist cluster identity: {exc}"
+ logger.warning("%s", identity.load_error)
+ return identity
+
+
+_identity_lock = threading.Lock()
+_configured_identity: NodeIdentity | None = None
+
+
+def configure_node_identity(
+ base_path: Path | str | None = None,
+ *,
+ taken_names: Iterable[str] = (),
+) -> NodeIdentity:
+ """Configure the process-wide identity used by the discovery endpoints."""
+
+ global _configured_identity
+ path = (
+ Path(base_path) / "cluster" / "identity.json" if base_path is not None else None
+ )
+ identity = load_or_create(path, taken_names=taken_names)
+ with _identity_lock:
+ _configured_identity = identity
+ return identity
+
+
+def get_node_identity() -> NodeIdentity:
+ with _identity_lock:
+ if _configured_identity is None:
+ raise RuntimeError("cluster node identity is not configured")
+ return _configured_identity
+
+
+def reset_configured_identity() -> None:
+ """Test hook: drop the process-wide identity."""
+
+ global _configured_identity
+ with _identity_lock:
+ _configured_identity = None
diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py
index bf17ef5618..2e3e156bbd 100644
--- a/omlx/cluster/inference_worker.py
+++ b/omlx/cluster/inference_worker.py
@@ -20,7 +20,7 @@
from types import SimpleNamespace
from typing import Any
-from .deployment import decode_worker_contract
+from .deployment import decode_worker_contract, decode_worker_path_map
from .liveness import PeerWatchdog
from .memory_guard import (
admission_budget,
@@ -666,9 +666,9 @@ def _validate_loaded_stage(
and start in (None, 0)
and end in (None, len(layers))
)
- if (
- not expected_complete_tensor_stage
- and (start, end) != (assignment.start_layer, assignment.end_layer)
+ if not expected_complete_tensor_stage and (start, end) != (
+ assignment.start_layer,
+ assignment.end_layer,
):
raise RuntimeError(
"loaded model pipeline range does not match the approved plan: "
@@ -970,6 +970,15 @@ def run_worker(args: argparse.Namespace) -> int:
if args.plan_hash != plan_hash:
raise RuntimeError("worker plan hash does not match launch contract")
+ # Cluster v2: a deployment may give each node its own absolute model path.
+ # The rank's path comes from the signed contract's path_map; nodes without
+ # an entry keep the shared --model argument, the pre-v2 behavior.
+ path_map = decode_worker_path_map(args.plan)
+ if path_map:
+ rank_model_path = path_map.get(assignments[rank].node_id)
+ if rank_model_path and rank_model_path != args.model:
+ args.model = rank_model_path
+
marker = RuntimeMarker(
state_dir=args.state_dir,
deployment_id=args.deployment_id,
@@ -1103,25 +1112,28 @@ def run_worker(args: argparse.Namespace) -> int:
# it is checked again against what the rank actually holds, all the
# way through the load. A rank that overruns dies here rather than
# taking the Mac with it.
- with watch_rank_load(
- load_budget,
- rank=rank,
- node_id=getattr(assignment, "node_id", ""),
- on_sample=lambda observed: marker.update(
- "loading",
- load_stage="loading_weights",
- load_memory_bytes=observed,
+ with (
+ watch_rank_load(
+ load_budget,
+ rank=rank,
+ node_id=getattr(assignment, "node_id", ""),
+ on_sample=lambda observed: marker.update(
+ "loading",
+ load_stage="loading_weights",
+ load_memory_bytes=observed,
+ ),
),
- ), install_progressive_loader(
- mlx_server,
- progress=lambda progress: marker.update(
- "loading",
- load_stage=progress.get("phase", "materializing_layers"),
- **{
- key: value
- for key, value in progress.items()
- if key != "phase"
- },
+ install_progressive_loader(
+ mlx_server,
+ progress=lambda progress: marker.update(
+ "loading",
+ load_stage=progress.get("phase", "materializing_layers"),
+ **{
+ key: value
+ for key, value in progress.items()
+ if key != "phase"
+ },
+ ),
),
):
provider.load_default()
@@ -1211,9 +1223,7 @@ def run_worker(args: argparse.Namespace) -> int:
provider.model,
rank=rank,
node_id=getattr(assignment, "node_id", ""),
- layer_count=(
- assignment.end_layer - assignment.start_layer
- ),
+ layer_count=(assignment.end_layer - assignment.start_layer),
tensor_parallel_size=assignment.tensor_parallel_size,
memory_guard_tier=guard_tier,
# The attention peak is set by the prefill chunk, so the
diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py
index f3be0d47c0..523ea4ed3f 100644
--- a/omlx/cluster/launch.py
+++ b/omlx/cluster/launch.py
@@ -227,9 +227,7 @@ def _python_minor(version: str) -> tuple[str, str] | None:
return (parts[0], parts[1])
-def _interpreter_parity(
- local: str, remote: Any
-) -> tuple[str | None, str | None]:
+def _interpreter_parity(local: str, remote: Any) -> tuple[str | None, str | None]:
"""Compare the interpreter two ranks will actually run under (#2695).
Returns ``(blocking, warning)``, at most one of which is set.
@@ -284,8 +282,7 @@ def _rank_python_module_argv(
for rank, executable in enumerate(executables)
)
script = (
- f'case "${{MLX_RANK:-}}" in {cases} *) exit 64;; esac; '
- 'exec "$omlx_python" "$@"'
+ f'case "${{MLX_RANK:-}}" in {cases} *) exit 64;; esac; exec "$omlx_python" "$@"'
)
return ["/bin/sh", "-c", script, "omlx-rank-python", "-m", module]
@@ -690,7 +687,10 @@ def run_cuda_fabric_probe(
raise DistributedLaunchError(
f"CUDA fabric probe exited with code {completed.returncode}{suffix}"
)
- if len(completed.stdout.encode()) + len(completed.stderr.encode()) > _REMOTE_OUTPUT_LIMIT:
+ if (
+ len(completed.stdout.encode()) + len(completed.stderr.encode())
+ > _REMOTE_OUTPUT_LIMIT
+ ):
raise DistributedLaunchError("CUDA fabric probe output exceeded the safe limit")
records: list[dict[str, Any]] = []
for line in completed.stdout.splitlines():
@@ -705,7 +705,9 @@ def run_cuda_fabric_probe(
raise DistributedLaunchError(
"CUDA fabric probe did not return one result from each worker"
)
- observed = min(float(record.get("payload_bytes_per_second") or 0) for record in records)
+ observed = min(
+ float(record.get("payload_bytes_per_second") or 0) for record in records
+ )
verified = observed >= minimum_bytes_per_second
identity = "\0".join(sorted(host.ssh for host in hosts)).encode()
group_id = f"connectx-{hashlib.sha256(identity).hexdigest()[:16]}"
@@ -854,8 +856,7 @@ def discover_remote_python_executable(
# bare command name (``python3``) needs ``sys.executable`` to become an
# absolute path.
script = (
- "import os,omlx; print(os.path.expanduser("
- f"{candidate!r}))"
+ f"import os,omlx; print(os.path.expanduser({candidate!r}))"
if candidate.startswith(("~", "/"))
else "import sys,omlx; print(sys.executable)"
)
@@ -1127,9 +1128,7 @@ def probe_remote_system_host(
"ssh_reachable": True,
"status": payload,
"runtime_compatible": False,
- "runtime_mismatches": [
- _RUNTIME_UNVERIFIED if evidence else _RUNTIME_MISSING
- ],
+ "runtime_mismatches": [_RUNTIME_UNVERIFIED if evidence else _RUNTIME_MISSING],
# Same keys as the healthy path, so a caller never has to know which
# branch produced the result before reading it.
"runtime_warnings": [],
@@ -1458,7 +1457,10 @@ def preflight_remote_hosts(
script = _PREFLIGHT_SCRIPT
local_python_version = platform.python_version()
results: list[dict[str, Any]] = []
- local_model_exists = Path(deployment.model).is_dir()
+ # Cluster v2: each rank validates against its own path_map entry; nodes
+ # without an entry share the coordinator path, as before v2.
+ local_model_path = deployment.model_path_for(deployment.hosts[0].node_id)
+ local_model_exists = Path(local_model_path).is_dir()
assignments = sorted(deployment.assignments, key=lambda item: item.rank)
if len(assignments) != len(deployment.hosts):
raise DistributedLaunchError(
@@ -1466,7 +1468,7 @@ def preflight_remote_hosts(
)
local_validation = (
validate_staged_model(
- deployment.model,
+ local_model_path,
assignments[0].start_layer,
assignments[0].end_layer,
)
@@ -1478,9 +1480,7 @@ def preflight_remote_hosts(
from .memory_guard import ceiling_breakdown
local_admission_ceiling = int(
- ceiling_breakdown(
- assignments[0].memory_guard_tier
- ).get("hard_limit", 0)
+ ceiling_breakdown(assignments[0].memory_guard_tier).get("hard_limit", 0)
)
except Exception as exc:
raise DistributedLaunchError(
@@ -1513,15 +1513,18 @@ def preflight_remote_hosts(
)
continue
remote_python = host.python_executable or python_executable
- # Send the ~-form: deployment.model is the coordinator's absolute path,
- # which names nothing on a peer with a different macOS account. The
- # preflight script expanduser()s it in the peer's own home.
+ # A path_map entry is already absolute on this peer. Without one, send
+ # the portable ~-form so peers with different macOS accounts resolve
+ # the model under their own home directory.
+ remote_model_path = deployment.path_map.get(
+ host.node_id, home_relative_model_path(deployment.model)
+ )
remote_command = shlex.join(
[
remote_python,
"-c",
script,
- home_relative_model_path(deployment.model),
+ remote_model_path,
str(assignment.start_layer),
str(assignment.end_layer),
assignment.memory_guard_tier,
@@ -1573,9 +1576,12 @@ def preflight_remote_hosts(
runtime_warnings = [warning] if warning is not None else []
if versions.get("model-exists") is not True:
mismatches.append(
- f"model directory is missing on remote host: {deployment.model}"
+ f"model directory is missing on remote host: {remote_model_path}"
)
- if local_identity is not None and versions.get("model_identity") != local_identity:
+ if (
+ local_identity is not None
+ and versions.get("model_identity") != local_identity
+ ):
mismatches.append(
"model identity differs from the coordinator "
"(config, tokenizer, processor, or weight index)"
@@ -1641,9 +1647,7 @@ def _validate_deployment_admission(
0.0,
min(
1.0,
- (
- assignment.capacity_bytes - assignment.reserve_bytes
- )
+ (assignment.capacity_bytes - assignment.reserve_bytes)
/ assignment.capacity_bytes,
),
)
@@ -1939,9 +1943,7 @@ def _terminate(self) -> None:
os.killpg(process_group, signal.SIGTERM)
if process.poll() is None:
with suppress(subprocess.TimeoutExpired):
- process.wait(
- timeout=max(0.0, deadline - time.monotonic())
- )
+ process.wait(timeout=max(0.0, deadline - time.monotonic()))
# mlx.launch can exit promptly while a local rank remains blocked
# in a Metal/JACCL collective. Waiting only for the launcher left
@@ -2104,9 +2106,7 @@ def _reap_remote_ranks(self, *, runner: SSHRunner = subprocess.run) -> None:
host.ssh,
)
elif action in ("terminated", "killed"):
- logger.info(
- "reaped remote rank %d on %s (%s)", rank, host.ssh, action
- )
+ logger.info("reaped remote rank %d on %s (%s)", rank, host.ssh, action)
elif action:
logger.debug(
"remote rank reap for rank %d on %s: %s",
@@ -2116,8 +2116,7 @@ def _reap_remote_ranks(self, *, runner: SSHRunner = subprocess.run) -> None:
)
else:
logger.warning(
- "remote rank reap for rank %d on %s returned no report "
- "(exit %s)",
+ "remote rank reap for rank %d on %s returned no report (exit %s)",
rank,
host.ssh,
completed.returncode,
@@ -2148,9 +2147,7 @@ def _runtime_failure_reason(self) -> str | None:
for rank, host in enumerate(self.deployment.hosts):
filename = f"{self.deployment.deployment_id}-rank-{rank}.json"
if host.ssh in _LOOPBACK_TARGETS:
- marker = read_marker(
- Path(self.state_dir).expanduser() / filename
- )
+ marker = read_marker(Path(self.state_dir).expanduser() / filename)
else:
remote_root = self.state_dir.rstrip("/") or "."
marker, _, _, _ = read_remote_marker(
@@ -2163,7 +2160,8 @@ def _runtime_failure_reason(self) -> str | None:
marker.get("deployment_id") != self.deployment.deployment_id
or marker.get("plan_hash") != self.deployment.plan_hash
or marker.get("rank") != rank
- or marker.get("phase") not in {
+ or marker.get("phase")
+ not in {
"failed",
"peer_lost",
"launcher_lost",
@@ -2172,9 +2170,7 @@ def _runtime_failure_reason(self) -> str | None:
continue
error = marker.get("error")
if isinstance(error, str) and error.strip():
- failures.append(
- f"rank {rank} ({host.node_id}): {error.strip()}"
- )
+ failures.append(f"rank {rank} ({host.node_id}): {error.strip()}")
return "; ".join(failures)[:_LOG_LINE_LIMIT] or None
def _failure_reason(self) -> str | None:
diff --git a/omlx/cluster/modelsync.py b/omlx/cluster/modelsync.py
new file mode 100644
index 0000000000..3f71841a9b
--- /dev/null
+++ b/omlx/cluster/modelsync.py
@@ -0,0 +1,863 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Model synchronization and per-node model paths for cluster v2.
+
+Two responsibilities:
+
+* A bounded, content-describing **manifest** for a locally-known model
+ (safetensors index hash + file list + total bytes), served to peers over
+ ``GET /api/cluster/models/{model_id}/manifest`` so a coordinator can answer
+ "does that node have this model?" without SSHing anywhere.
+* A :class:`ModelSyncManager` that compares two manifests and then moves the
+ model, either over the enrolled SSH channel (``rsync``, resumable via
+ ``--partial --append-verify``) or as a per-node Hugging Face download of
+ only the files a shard needs (allow-patterns derived from the weight-map
+ index — the exo pattern). Progress events are emitted for the UI.
+
+All transports are injectable so unit tests never open a socket, run rsync,
+or touch the Hugging Face hub.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+import shlex
+import subprocess
+import threading
+import time
+from collections.abc import Callable, Iterable
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Literal
+
+from fastapi import APIRouter, HTTPException
+
+from ..exceptions import ModelNotFoundError
+from .deployment import validate_ssh_target
+from .ssh_policy import cluster_ssh_options
+from .staging import (
+ index_shards,
+ model_identity_digest,
+ shards_for_stage,
+ sidecar_files,
+)
+
+SyncMethod = Literal["auto", "rsync", "download"]
+SyncState = Literal["present", "missing", "partial", "mismatch"]
+
+#: Above this size ``method="auto"`` prefers a direct rsync over the enrolled
+#: SSH channel; at or below it, each node downloads its own shard files.
+AUTO_RSYNC_THRESHOLD_BYTES = 20 * 1024**3
+
+_MANIFEST_TIMEOUT_SECONDS = 10.0
+_MAX_MODEL_ID_LENGTH = 4096
+_MAX_PROGRESS_EVENTS = 512
+
+# ``rsync --info=progress2`` emits lines such as:
+# " 1,234,567,890 42% 123.45MB/s 0:01:23"
+_PROGRESS2 = re.compile(
+ r"^\s*(?P
[\d,]+)\s+(?P\d+)%\s+"
+ r"(?P[\d.,]+)\s*(?P[KMGTP]?B)/s\s+"
+ r"(?P\d+:\d{2}(?::\d{2})?)"
+)
+_RATE_MULTIPLIERS = {
+ "B": 1,
+ "KB": 1000,
+ "MB": 1000**2,
+ "GB": 1000**3,
+ "TB": 1000**4,
+ "PB": 1000**5,
+}
+
+
+class ModelSyncError(RuntimeError):
+ """A sync operation could not start or finish."""
+
+
+@dataclass(frozen=True)
+class ManifestFile:
+ """One file in a model directory: name and size, nothing else."""
+
+ name: str
+ size_bytes: int
+
+ def to_dict(self) -> dict[str, Any]:
+ return {"name": self.name, "size_bytes": self.size_bytes}
+
+ @classmethod
+ def from_dict(cls, payload: dict[str, Any]) -> ManifestFile:
+ return cls(name=str(payload["name"]), size_bytes=int(payload["size_bytes"]))
+
+
+@dataclass(frozen=True)
+class ModelManifest:
+ """Content description of one model directory, cheap to compute.
+
+ Hashing every weight file would take minutes on a 300 GB model, so the
+ identity rests on the safetensors weight-map index plus the sidecar
+ digest staging already uses, with per-file sizes for drift detection.
+ """
+
+ model_id: str
+ path: str
+ index_sha256: str | None
+ identity_sha256: str
+ files: tuple[ManifestFile, ...]
+ total_bytes: int
+ source_repo_id: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "schema_version": 1,
+ "model_id": self.model_id,
+ "path": self.path,
+ "index_sha256": self.index_sha256,
+ "identity_sha256": self.identity_sha256,
+ "files": [item.to_dict() for item in self.files],
+ "total_bytes": self.total_bytes,
+ "source_repo_id": self.source_repo_id,
+ }
+
+ @classmethod
+ def from_dict(cls, payload: dict[str, Any]) -> ModelManifest:
+ if not isinstance(payload, dict) or payload.get("schema_version") != 1:
+ raise ValueError("unsupported model manifest schema")
+ files = payload.get("files")
+ if not isinstance(files, list):
+ raise ValueError("model manifest files must be an array")
+ return cls(
+ model_id=str(payload.get("model_id") or ""),
+ path=str(payload.get("path") or ""),
+ index_sha256=payload.get("index_sha256"),
+ identity_sha256=str(payload.get("identity_sha256") or ""),
+ files=tuple(ManifestFile.from_dict(item) for item in files),
+ total_bytes=int(payload.get("total_bytes") or 0),
+ source_repo_id=payload.get("source_repo_id"),
+ )
+
+
+@dataclass(frozen=True)
+class SyncProgress:
+ """One progress event for the UI; bytes/s and ETA when measurable."""
+
+ model_id: str
+ peer: str
+ method: str
+ phase: Literal["checking", "transferring", "verifying", "done", "error"]
+ bytes_done: int = 0
+ bytes_total: int = 0
+ bytes_per_second: float | None = None
+ eta_seconds: float | None = None
+ detail: str = ""
+ at: float = field(default_factory=time.time)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "model_id": self.model_id,
+ "peer": self.peer,
+ "method": self.method,
+ "phase": self.phase,
+ "bytes_done": self.bytes_done,
+ "bytes_total": self.bytes_total,
+ "bytes_per_second": self.bytes_per_second,
+ "eta_seconds": self.eta_seconds,
+ "detail": self.detail,
+ "at": self.at,
+ }
+
+
+def build_manifest(
+ model_path: str | Path,
+ *,
+ model_id: str | None = None,
+ source_repo_id: str | None = None,
+) -> ModelManifest:
+ """Describe a local model directory for peer comparison."""
+
+ root = Path(model_path).expanduser()
+ if not root.is_dir():
+ raise ValueError(f"model path is not a directory: {root}")
+ weights = sorted(root.glob("*.safetensors"))
+ if not weights:
+ raise ValueError(f"no safetensors weights found in {root}")
+
+ index_path = root / "model.safetensors.index.json"
+ index_sha256 = (
+ hashlib.sha256(index_path.read_bytes()).hexdigest()
+ if index_path.is_file()
+ else None
+ )
+ files = [
+ ManifestFile(name=path.name, size_bytes=path.stat().st_size) for path in weights
+ ]
+ for name in sidecar_files(root):
+ path = root / name
+ files.append(ManifestFile(name=name, size_bytes=path.stat().st_size))
+ files.sort(key=lambda item: item.name)
+ return ModelManifest(
+ model_id=model_id or root.name,
+ path=str(root),
+ index_sha256=index_sha256,
+ identity_sha256=model_identity_digest(root),
+ files=tuple(files),
+ total_bytes=sum(item.size_bytes for item in files),
+ source_repo_id=source_repo_id,
+ )
+
+
+def allow_patterns_for_shard(
+ model_path: str | Path,
+ start_layer: int | None = None,
+ end_layer: int | None = None,
+) -> tuple[str, ...]:
+ """HF ``allow_patterns`` for only the files one shard needs.
+
+ Derived from the weight-map index (or shard headers when no index ships)
+ via the same layer→file map staging uses: layer-scoped shards for
+ ``[start_layer, end_layer)`` plus the shared sidecars. With no layer
+ range, the pattern list covers the whole model.
+ """
+
+ shards = index_shards(model_path)
+ if start_layer is not None and end_layer is not None:
+ if not 0 <= start_layer < end_layer:
+ raise ValueError("shard layer range must satisfy 0 <= start < end")
+ shards = shards_for_stage(shards, start_layer, end_layer)
+ patterns = {shard.name for shard in shards}
+ patterns.update(sidecar_files(model_path))
+ return tuple(sorted(patterns))
+
+
+def compare_manifests(
+ local: ModelManifest, peer: ModelManifest | None
+) -> dict[str, Any]:
+ """Whether ``peer`` can serve the model ``local`` describes.
+
+ * ``missing`` — the peer answered 404 or is unreachable.
+ * ``mismatch`` — the peer has a different model (weight-map index hash or
+ sidecar identity differs).
+ * ``partial`` — same model, but files are absent or truncated.
+ * ``present`` — every file is there at the expected size.
+ """
+
+ if peer is None:
+ return {
+ "state": "missing",
+ "bytes": 0,
+ "total_bytes": local.total_bytes,
+ "missing": [item.name for item in local.files],
+ }
+ if (
+ local.index_sha256 is not None
+ and peer.index_sha256 is not None
+ and local.index_sha256 != peer.index_sha256
+ ) or local.identity_sha256 != peer.identity_sha256:
+ return {
+ "state": "mismatch",
+ "bytes": 0,
+ "total_bytes": local.total_bytes,
+ "missing": [item.name for item in local.files],
+ }
+ peer_sizes = {item.name: item.size_bytes for item in peer.files}
+ missing = [
+ item.name
+ for item in local.files
+ if peer_sizes.get(item.name) != item.size_bytes
+ ]
+ matched = sum(
+ item.size_bytes for item in local.files if item.name not in set(missing)
+ )
+ return {
+ "state": "partial" if missing else "present",
+ "bytes": matched,
+ "total_bytes": local.total_bytes,
+ "missing": missing,
+ }
+
+
+def parse_rsync_progress(line: str) -> tuple[int, float, float] | None:
+ """Parse one ``--info=progress2`` line → (bytes_done, bytes/s, eta_s)."""
+
+ match = _PROGRESS2.match(line.strip())
+ if match is None:
+ return None
+ done = int(match.group("bytes").replace(",", ""))
+ rate = (
+ float(match.group("rate").replace(",", ""))
+ * _RATE_MULTIPLIERS[match.group("unit")]
+ )
+ parts = [int(part) for part in match.group("eta").split(":")]
+ eta = (
+ parts[0] * 3600 + parts[1] * 60 + parts[2]
+ if len(parts) == 3
+ else (parts[0] * 60 + parts[1])
+ )
+ return done, rate, float(eta)
+
+
+def build_rsync_argv(
+ source_dir: str | Path,
+ ssh_target: str,
+ destination_dir: str | Path,
+ *,
+ ssh_identity: str | Path | None = None,
+) -> list[str]:
+ """A resumable rsync over the enrolled SSH channel.
+
+ ``--partial --append-verify`` resumes interrupted transfers and verifies
+ the appended bytes, the functional equivalent of ``-P --append-verify``
+ without the interactive progress format. The SSH transport uses the one
+ shared non-interactive cluster policy (managed identity, accept-new
+ host keys, BatchMode) — never a hand-rolled option set.
+ """
+
+ ssh_target = validate_ssh_target(ssh_target)
+ target_dir = str(destination_dir)
+ if (
+ not Path(target_dir).is_absolute()
+ or "\x00" in target_dir
+ or "\n" in target_dir
+ or "\r" in target_dir
+ ):
+ raise ValueError("rsync destination must be an absolute single-line path")
+ ssh_argv = ["ssh", *cluster_ssh_options()]
+ if ssh_identity is not None:
+ ssh_argv.extend(["-i", str(ssh_identity)])
+ source = str(Path(source_dir).expanduser()).rstrip("/") + "/"
+ # macOS ships openrsync 2.6.9 without --protect-args/-s. Quote the remote
+ # path inside the host:path operand so the peer shell receives one literal
+ # filename while retaining compatibility with the system binary.
+ destination = f"{ssh_target}:{shlex.quote(target_dir)}"
+ return [
+ "rsync",
+ "-a",
+ "--partial",
+ "--append-verify",
+ "--info=progress2",
+ "-e",
+ shlex.join(ssh_argv),
+ source,
+ destination,
+ ]
+
+
+def _default_ssh_trust(ssh_target: str) -> bool:
+ """Whether the dedicated cluster key exists for non-interactive SSH."""
+
+ del ssh_target # the key is shared; the target itself is probed at launch
+ return (Path.home() / ".ssh" / "omlx_cluster").is_file()
+
+
+def _default_hf_download(
+ *,
+ repo_id: str,
+ allow_patterns: Iterable[str],
+ local_dir: str | Path,
+) -> None:
+ try:
+ from huggingface_hub import snapshot_download
+ except ImportError as exc:
+ raise ModelSyncError(
+ "huggingface_hub is not installed on this node; install it or use "
+ "method='rsync' to copy the model from the coordinator instead"
+ ) from exc
+ snapshot_download(
+ repo_id=repo_id,
+ allow_patterns=list(allow_patterns),
+ local_dir=str(local_dir),
+ )
+
+
+def _normalize_peer_url(peer: str) -> str:
+ peer = peer.strip()
+ if not peer:
+ raise ValueError("peer must be a host:port or http(s) URL")
+ if "://" not in peer:
+ if ":" not in peer.rsplit("]", 1)[-1]:
+ raise ValueError(f"peer {peer!r} has no port; use host:port or a full URL")
+ peer = f"http://{peer}"
+ return peer.rstrip("/")
+
+
+class ModelSyncManager:
+ """Compare and synchronize model files between cluster nodes.
+
+ Every transport is injectable: ``http_fetch`` for peer manifests,
+ ``ssh_trust`` for the auto-method decision, ``rsync_run`` for the copy,
+ and ``hf_download`` for per-node downloads. Tests inject fakes; the
+ defaults are the real thing and are never exercised offline.
+ """
+
+ def __init__(
+ self,
+ *,
+ http_fetch: Callable[[str, float], dict[str, Any] | None] | None = None,
+ ssh_trust: Callable[[str], bool] | None = None,
+ rsync_run: Callable[..., int] | None = None,
+ hf_download: Callable[..., None] | None = None,
+ pool_getter: Callable[[], Any] | None = None,
+ settings_loader: Callable[[], Any] | None = None,
+ manifest_timeout: float = _MANIFEST_TIMEOUT_SECONDS,
+ ) -> None:
+ self._http_fetch = http_fetch or self._default_http_fetch
+ self._ssh_trust = ssh_trust or _default_ssh_trust
+ self._rsync_run = rsync_run or self._default_rsync_run
+ self._hf_download = hf_download or _default_hf_download
+ self._pool_getter = pool_getter
+ self._settings_loader = settings_loader
+ self._manifest_timeout = manifest_timeout
+ self._events: list[SyncProgress] = []
+ self._lock = threading.Lock()
+
+ # -- model resolution ------------------------------------------------
+
+ def resolve_local_model_path(self, model_id: str) -> Path:
+ """Resolve a model ID, repo ID, or path to a local directory."""
+
+ if not model_id or len(model_id) > _MAX_MODEL_ID_LENGTH or "\x00" in model_id:
+ raise ModelNotFoundError(model_id or "", [])
+ candidate = Path(model_id).expanduser()
+ if candidate.is_dir():
+ return candidate.resolve()
+ pool = self._pool_getter() if self._pool_getter is not None else None
+ if pool is not None:
+ status = pool.get_status()
+ for item in status.get("models", []) if isinstance(status, dict) else []:
+ if not isinstance(item, dict):
+ continue
+ if model_id in {
+ item.get("id"),
+ item.get("source_repo_id"),
+ item.get("model_path"),
+ }:
+ path = Path(str(item["model_path"])).expanduser()
+ if path.is_dir():
+ return path.resolve()
+ settings = (
+ self._settings_loader() if self._settings_loader is not None else None
+ )
+ if settings is not None:
+ from ..model_discovery import discover_models_from_dirs
+
+ model_dirs = [
+ Path(entry).expanduser()
+ for entry in settings.get_effective_model_dirs()
+ ]
+ discovered = discover_models_from_dirs(model_dirs)
+ for key, entry in discovered.items():
+ if model_id in {key, entry.model_id, entry.source_repo_id}:
+ path = Path(entry.model_path).expanduser()
+ if path.is_dir():
+ return path.resolve()
+ raise ModelNotFoundError(model_id, [])
+
+ def local_manifest(self, model_id: str) -> ModelManifest:
+ path = self.resolve_local_model_path(model_id)
+ source_repo_id = None if Path(model_id).expanduser().is_dir() else model_id
+ return build_manifest(path, model_id=model_id, source_repo_id=source_repo_id)
+
+ # -- peer manifest ----------------------------------------------------
+
+ @staticmethod
+ def _default_http_fetch(url: str, timeout: float) -> dict[str, Any] | None:
+ import urllib.error
+ import urllib.request
+
+ request = urllib.request.Request(url, headers={"Accept": "application/json"})
+ try:
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ return json.loads(response.read().decode())
+ except urllib.error.HTTPError as exc:
+ if exc.code == 404:
+ return None
+ raise ModelSyncError(
+ f"peer manifest request failed: HTTP {exc.code}"
+ ) from exc
+ except (OSError, urllib.error.URLError) as exc:
+ raise ModelSyncError(f"peer is unreachable: {exc}") from exc
+
+ def peer_manifest(self, peer: str, model_id: str) -> ModelManifest | None:
+ """Fetch a peer's manifest; ``None`` when the model is unknown there."""
+
+ base = _normalize_peer_url(peer)
+ payload = self._http_fetch(
+ f"{base}/api/cluster/models/{model_id}/manifest",
+ self._manifest_timeout,
+ )
+ if payload is None:
+ return None
+ try:
+ return ModelManifest.from_dict(payload)
+ except (KeyError, TypeError, ValueError) as exc:
+ raise ModelSyncError(f"peer returned an invalid manifest: {exc}") from exc
+
+ def status(
+ self,
+ peer: str,
+ model_id: str,
+ *,
+ local: ModelManifest | None = None,
+ ) -> dict[str, Any]:
+ """{state: present|missing|partial|mismatch, bytes} for a peer."""
+
+ local = local or self.local_manifest(model_id)
+ result = compare_manifests(local, self.peer_manifest(peer, model_id))
+ result["peer"] = peer
+ result["model_id"] = model_id
+ return result
+
+ # -- sync --------------------------------------------------------------
+
+ def decide_method(
+ self,
+ ssh_target: str | None,
+ total_bytes: int,
+ ) -> Literal["rsync", "download"]:
+ """auto = rsync when SSH trust exists AND the model is over 20 GB."""
+
+ if (
+ ssh_target
+ and total_bytes > AUTO_RSYNC_THRESHOLD_BYTES
+ and self._ssh_trust(ssh_target)
+ ):
+ return "rsync"
+ return "download"
+
+ def sync(
+ self,
+ peer: str,
+ model_id: str,
+ method: SyncMethod = "auto",
+ *,
+ ssh_target: str | None = None,
+ destination: str | Path | None = None,
+ repo_id: str | None = None,
+ start_layer: int | None = None,
+ end_layer: int | None = None,
+ on_progress: Callable[[SyncProgress], None] | None = None,
+ ) -> dict[str, Any]:
+ """Bring ``peer`` (or a local destination) to ``present`` for a model.
+
+ ``rsync`` copies the local model directory to ``ssh_target:destination``
+ over the enrolled channel. ``download`` fetches only shard-needed files
+ from the Hugging Face hub into ``destination`` on this node (run the
+ same call on each node, exo-style). Progress events are emitted to
+ ``on_progress`` and retained in :attr:`events` for UI polling.
+ """
+
+ if method not in {"auto", "rsync", "download"}:
+ raise ValueError(f"unsupported sync method: {method!r}")
+ local = self.local_manifest(model_id)
+ chosen = (
+ self.decide_method(ssh_target, local.total_bytes)
+ if method == "auto"
+ else method
+ )
+ self._emit(
+ on_progress,
+ local.model_id,
+ peer,
+ chosen,
+ "checking",
+ bytes_total=local.total_bytes,
+ detail="comparing manifests",
+ )
+ try:
+ if chosen == "rsync":
+ result = self._sync_rsync(
+ local, peer, ssh_target, destination, on_progress
+ )
+ else:
+ result = self._sync_download(
+ local,
+ model_id,
+ peer,
+ destination,
+ repo_id,
+ start_layer,
+ end_layer,
+ on_progress,
+ )
+ except Exception as exc:
+ self._emit(
+ on_progress,
+ local.model_id,
+ peer,
+ chosen,
+ "error",
+ bytes_total=local.total_bytes,
+ detail=str(exc)[:500],
+ )
+ raise
+ self._emit(
+ on_progress,
+ local.model_id,
+ peer,
+ chosen,
+ "done",
+ bytes_done=local.total_bytes,
+ bytes_total=local.total_bytes,
+ )
+ return result
+
+ def _sync_rsync(
+ self,
+ local: ModelManifest,
+ peer: str,
+ ssh_target: str | None,
+ destination: str | Path | None,
+ on_progress: Callable[[SyncProgress], None] | None,
+ ) -> dict[str, Any]:
+ if not ssh_target:
+ raise ModelSyncError(
+ "rsync sync needs ssh_target (the enrolled SSH destination)"
+ )
+ if not self._ssh_trust(ssh_target):
+ raise ModelSyncError(
+ f"no enrolled SSH trust for {ssh_target}; pair the nodes first "
+ "or use method='download'"
+ )
+ # Without an explicit destination the peer keeps the coordinator's
+ # absolute path — the legacy shared-path layout, still the default
+ # until a path_map says otherwise.
+ target_dir = str(destination or local.path)
+ argv = build_rsync_argv(local.path, ssh_target, target_dir)
+
+ def progress(done: int, rate: float, eta: float) -> None:
+ self._emit(
+ on_progress,
+ local.model_id,
+ peer,
+ "rsync",
+ "transferring",
+ bytes_done=done,
+ bytes_total=local.total_bytes,
+ bytes_per_second=rate,
+ eta_seconds=eta,
+ )
+
+ rc = self._rsync_run(argv, on_line=self._progress_line_parser(progress))
+ if rc != 0:
+ raise ModelSyncError(f"rsync to {ssh_target} exited with status {rc}")
+ self._emit(
+ on_progress,
+ local.model_id,
+ peer,
+ "rsync",
+ "verifying",
+ bytes_total=local.total_bytes,
+ detail="verifying peer manifest",
+ )
+ return {
+ "method": "rsync",
+ "peer": peer,
+ "ssh_target": ssh_target,
+ "destination": target_dir,
+ "bytes": local.total_bytes,
+ }
+
+ def _sync_download(
+ self,
+ local: ModelManifest,
+ model_id: str,
+ peer: str,
+ destination: str | Path | None,
+ repo_id: str | None,
+ start_layer: int | None,
+ end_layer: int | None,
+ on_progress: Callable[[SyncProgress], None] | None,
+ ) -> dict[str, Any]:
+ repo = repo_id or local.source_repo_id
+ if not repo or Path(repo).expanduser().is_dir():
+ raise ModelSyncError(
+ "download sync needs the model's Hugging Face repo ID; the "
+ "local copy has no repository reference, use method='rsync'"
+ )
+ if destination is None:
+ raise ModelSyncError(
+ "download sync needs a destination directory on this node"
+ )
+ patterns = allow_patterns_for_shard(local.path, start_layer, end_layer)
+ self._emit(
+ on_progress,
+ local.model_id,
+ peer,
+ "download",
+ "transferring",
+ bytes_total=local.total_bytes,
+ detail=f"fetching {len(patterns)} files from {repo}",
+ )
+ self._hf_download(
+ repo_id=repo,
+ allow_patterns=patterns,
+ local_dir=destination,
+ )
+ return {
+ "method": "download",
+ "peer": peer,
+ "repo_id": repo,
+ "destination": str(destination),
+ "allow_patterns": list(patterns),
+ "bytes": local.total_bytes,
+ }
+
+ # -- progress plumbing ---------------------------------------------------
+
+ @staticmethod
+ def _progress_line_parser(
+ progress: Callable[[int, float, float], None],
+ ) -> Callable[[str], None]:
+ def parse(line: str) -> None:
+ parsed = parse_rsync_progress(line)
+ if parsed is not None:
+ progress(*parsed)
+
+ return parse
+
+ @staticmethod
+ def _default_rsync_run(argv: list[str], on_line: Callable[[str], None]) -> int:
+ process = subprocess.Popen(
+ argv,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+ assert process.stdout is not None
+ for line in process.stdout:
+ on_line(line)
+ return process.wait()
+
+ def _emit(
+ self,
+ on_progress: Callable[[SyncProgress], None] | None,
+ model_id: str,
+ peer: str,
+ method: str,
+ phase: str,
+ **fields: Any,
+ ) -> SyncProgress:
+ event = SyncProgress(
+ model_id=model_id,
+ peer=peer,
+ method=method,
+ phase=phase, # type: ignore[arg-type]
+ **fields,
+ )
+ with self._lock:
+ self._events.append(event)
+ if len(self._events) > _MAX_PROGRESS_EVENTS:
+ del self._events[: len(self._events) - _MAX_PROGRESS_EVENTS]
+ if on_progress is not None:
+ on_progress(event)
+ return event
+
+ @property
+ def events(self) -> tuple[SyncProgress, ...]:
+ """Bounded recent progress history for UI polling."""
+
+ with self._lock:
+ return tuple(self._events)
+
+
+# -- manifest endpoint ------------------------------------------------------
+
+manifest_router = APIRouter(prefix="/api/cluster", tags=["cluster-modelsync"])
+
+_pool_getter: Callable[[], Any] | None = None
+_settings_loader: Callable[[], Any] | None = None
+
+
+def set_modelsync_getters(
+ engine_pool_getter: Callable[[], Any] | None = None,
+ settings_loader: Callable[[], Any] | None = None,
+) -> None:
+ """Inject server-owned dependencies without importing ``omlx.server``."""
+
+ global _pool_getter, _settings_loader
+ _pool_getter = engine_pool_getter
+ _settings_loader = settings_loader
+
+
+def _default_settings_loader() -> Any:
+ from ..settings import GlobalSettings
+
+ return GlobalSettings.load()
+
+
+def _manager() -> ModelSyncManager:
+ return ModelSyncManager(
+ pool_getter=_pool_getter,
+ settings_loader=_settings_loader or _default_settings_loader,
+ )
+
+
+def _allowed_model_roots() -> tuple[Path, ...]:
+ try:
+ settings = (_settings_loader or _default_settings_loader)()
+ return tuple(
+ Path(entry).expanduser().resolve()
+ for entry in settings.get_effective_model_dirs()
+ )
+ except Exception: # noqa: BLE001 - a broken settings file must not 500 here
+ return ()
+
+
+def _guard_manifest_path(path: Path) -> None:
+ """Path-typed model IDs stay inside the configured model directories.
+
+ Repo-style IDs are resolved through the engine pool / discovery, which
+ already only surfaces registered models. A raw path must not let an admin
+ token enumerate arbitrary directories.
+ """
+
+ roots = _allowed_model_roots()
+ if not roots:
+ return
+ if not any(root == path or root in path.parents for root in roots):
+ raise HTTPException(
+ status_code=403,
+ detail="model path is outside the configured model directories",
+ )
+
+
+@manifest_router.get("/models/{model_id:path}/manifest")
+async def cluster_model_manifest(model_id: str) -> dict[str, Any]:
+ """Safetensors index hash + file list + total bytes for a local model.
+
+ Peers call this to decide whether they must sync before activation; the
+ payload is names and sizes only — never weights, never credentials.
+ """
+
+ import asyncio
+
+ manager = _manager()
+ try:
+ path = manager.resolve_local_model_path(model_id)
+ except ModelNotFoundError as exc:
+ raise HTTPException(
+ status_code=404, detail=f"unknown model: {model_id}"
+ ) from exc
+ _guard_manifest_path(path)
+ try:
+ manifest = await asyncio.to_thread(build_manifest, path, model_id=model_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ return manifest.to_dict()
+
+
+__all__ = [
+ "AUTO_RSYNC_THRESHOLD_BYTES",
+ "ManifestFile",
+ "ModelManifest",
+ "ModelSyncError",
+ "ModelSyncManager",
+ "SyncProgress",
+ "allow_patterns_for_shard",
+ "build_manifest",
+ "build_rsync_argv",
+ "compare_manifests",
+ "manifest_router",
+ "parse_rsync_progress",
+ "set_modelsync_getters",
+]
diff --git a/omlx/cluster/pairing.py b/omlx/cluster/pairing.py
new file mode 100644
index 0000000000..3cc0ed2a9f
--- /dev/null
+++ b/omlx/cluster/pairing.py
@@ -0,0 +1,1662 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Code-based cluster pairing and enrollment bridge (cluster v2, Module B).
+
+Replaces the 3-step copy-paste relay (shared secret + key-exchange tokens in
+both directions) with an exo-style flow:
+
+1. The JOINER shows a 6-digit code (valid 10 minutes).
+2. The joiner POSTs ``/api/cluster/pair/request`` to the coordinator carrying
+ its identity and a salted, slow code verifier bound to the node and SSH
+ identities — never the code itself.
+3. The coordinator dashboard lists the pending request
+ (``state: "awaiting_approval"``) and the operator types the code shown on
+ the joiner into ``/api/cluster/pair/approve``.
+4. Approval verifies the code-bound identities (3 attempts, then a 10-minute lockout),
+ generates the 32-byte ``cluster_key``, wraps it under a key derived from
+ the code with PBKDF2-HMAC-SHA256 (210k iterations), persists the peer as
+ paired, and drives symmetric, fail-closed SSH enrollment with the
+ authenticated user key and daemon host key.
+5. The joiner polls ``/api/cluster/pair/status/{node_id}`` and unwraps the
+ cluster key locally with the code only it possesses.
+
+``DELETE /api/cluster/devices/{node_id}`` unpairs: the device-store entry and
+the stored cluster key are removed, any legacy ``enrolled-nodes.json`` entry
+is dropped, and the SSH trust installed at approve time is revoked
+best-effort.
+
+Module A (identity + discovery) is built concurrently on another branch.
+Every interaction with it is feature-detected: a real ``DeviceRegistry`` /
+``NodeIdentity`` is used when importable, otherwise schema-compatible local
+fallbacks (same files, same ``schema_version: 1``) keep this module fully
+functional and offline-testable. See ``DeviceRegistryBridge`` for the exact
+method names looked up on Module A's registry.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+import hmac
+import ipaddress
+import json
+import logging
+import os
+import platform
+import secrets
+import socket
+import subprocess
+import tempfile
+import threading
+import time
+import urllib.request
+import uuid
+from collections.abc import Callable, Iterable
+from contextlib import suppress
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+# --- Pairing policy (from ops/notes/omlx_cluster_v2_spec.md, Module B) ------
+
+CODE_DIGITS = 6
+CODE_TTL_SECONDS = 10 * 60
+MAX_CODE_ATTEMPTS = 3
+LOCKOUT_SECONDS = 10 * 60
+PBKDF2_ITERATIONS = 210_000
+CLUSTER_KEY_BYTES = 32
+WRAP_KDF = "PBKDF2-HMAC-SHA256"
+_WRAP_TAG_DOMAIN = b"omlx-cluster-key-v1"
+MAX_PENDING_REQUESTS = 32
+
+DEFAULT_BASE_PATH = Path.home() / ".omlx"
+IDENTITY_SCHEMA_VERSION = 1
+DEVICE_SCHEMA_VERSION = 1
+KEY_SCHEMA_VERSION = 1
+
+
+# --- Errors -----------------------------------------------------------------
+
+
+class PairingError(ValueError):
+ """Base class for pairing refusals; ``reason`` is machine-readable."""
+
+
+class PairingRequestError(PairingError):
+ """A join request payload was malformed or could not be accepted."""
+
+
+class PairingStateError(PairingError):
+ """No such pending request / device, or the state transition is invalid."""
+
+
+class PairingCodeError(PairingError):
+ """The presented code does not match the pending request's code hash."""
+
+
+class PairingLockoutError(PairingError):
+ """Too many wrong codes; approval is locked out until ``retry_after``."""
+
+
+class PairingExpiredError(PairingError):
+ """The pending request outlived the 10-minute code validity window."""
+
+
+class EnrollmentDriveError(PairingError):
+ """The fail-closed SSH TOFU enrollment step failed after code verify."""
+
+
+# --- Code + key-wrapping crypto (stdlib only) --------------------------------
+
+
+def generate_pairing_code() -> str:
+ """Return a zero-padded 6-digit pairing code shown on the joiner."""
+
+ return f"{secrets.randbelow(10**CODE_DIGITS):0{CODE_DIGITS}d}"
+
+
+def validate_pairing_code(code: str) -> str:
+ if not isinstance(code, str) or not code.isdigit() or len(code) != CODE_DIGITS:
+ raise PairingRequestError(f"pairing code must be {CODE_DIGITS} digits")
+ return code
+
+
+def pairing_code_hash(
+ code: str,
+ node_id: str,
+ ssh_public_key: str = "",
+ ssh_host_public_key: str = "",
+ salt: bytes = b"",
+) -> str:
+ """Slowly derive a verifier bound to the node and both SSH identities."""
+
+ payload = json.dumps(
+ {
+ "node_id": node_id,
+ "ssh_public_key": ssh_public_key,
+ "ssh_host_public_key": ssh_host_public_key,
+ },
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ verifier_salt = bytes(salt) + hashlib.sha256(payload).digest()
+ return hashlib.pbkdf2_hmac(
+ "sha256",
+ code.encode("utf-8"),
+ verifier_salt,
+ PBKDF2_ITERATIONS,
+ dklen=32,
+ ).hex()
+
+
+def _derive_wrap_key(code: str, salt: bytes, iterations: int) -> bytes:
+ return hashlib.pbkdf2_hmac(
+ "sha256", code.encode("utf-8"), salt, iterations, dklen=32
+ )
+
+
+def wrap_cluster_key(
+ cluster_key: bytes, code: str, *, iterations: int = PBKDF2_ITERATIONS
+) -> dict[str, Any]:
+ """Encrypt ``cluster_key`` under a key derived from the pairing code.
+
+ The derived key is used exactly once, so XOR is a one-time pad here; an
+ HMAC over the ciphertext detects both tampering and wrong-code unwraps.
+ """
+
+ if len(cluster_key) != CLUSTER_KEY_BYTES:
+ raise PairingError(f"cluster key must be {CLUSTER_KEY_BYTES} bytes")
+ salt = secrets.token_bytes(16)
+ wrap_key = _derive_wrap_key(code, salt, iterations)
+ ciphertext = bytes(a ^ b for a, b in zip(cluster_key, wrap_key))
+ tag = hmac.new(wrap_key, _WRAP_TAG_DOMAIN + ciphertext, hashlib.sha256).digest()
+ return {
+ "kdf": WRAP_KDF,
+ "iterations": iterations,
+ "salt": base64.b64encode(salt).decode(),
+ "ciphertext": base64.b64encode(ciphertext).decode(),
+ "tag": base64.b64encode(tag).decode(),
+ }
+
+
+def unwrap_cluster_key(package: dict[str, Any], code: str) -> bytes:
+ """Recover the cluster key; a wrong code fails closed with PairingCodeError."""
+
+ try:
+ iterations = int(package["iterations"])
+ salt = base64.b64decode(package["salt"], validate=True)
+ ciphertext = base64.b64decode(package["ciphertext"], validate=True)
+ tag = base64.b64decode(package["tag"], validate=True)
+ except (KeyError, TypeError, ValueError) as exc:
+ raise PairingRequestError("malformed wrapped cluster key") from exc
+ if package.get("kdf") != WRAP_KDF or not 1 <= iterations <= 10_000_000:
+ raise PairingRequestError("unsupported cluster-key wrap parameters")
+ wrap_key = _derive_wrap_key(code, salt, iterations)
+ expected = hmac.new(
+ wrap_key, _WRAP_TAG_DOMAIN + ciphertext, hashlib.sha256
+ ).digest()
+ if not hmac.compare_digest(tag, expected):
+ raise PairingCodeError("cluster key unwrap failed (wrong code or tampering)")
+ if len(ciphertext) != CLUSTER_KEY_BYTES:
+ raise PairingRequestError("malformed wrapped cluster key")
+ return bytes(a ^ b for a, b in zip(ciphertext, wrap_key))
+
+
+def coordinator_identity_tag(
+ cluster_key: bytes,
+ coordinator: dict[str, Any],
+) -> str:
+ """Bind the approved coordinator identity to the unwrapped cluster key."""
+
+ payload = json.dumps(
+ coordinator,
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ return hmac.new(
+ cluster_key, b"omlx-coordinator-v1\0" + payload, hashlib.sha256
+ ).hexdigest()
+
+
+# --- Small persisted stores (same conventions as registry.py/enrollment.py) -
+
+
+def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ descriptor, temporary = tempfile.mkstemp(
+ prefix=f".{path.stem}.", suffix=".tmp", dir=path.parent
+ )
+ try:
+ os.fchmod(descriptor, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ json.dump(payload, stream, indent=2, sort_keys=True)
+ stream.write("\n")
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ os.chmod(path, 0o600)
+ finally:
+ with suppress(FileNotFoundError):
+ os.unlink(temporary)
+
+
+def _read_json_object(path: Path, schema_version: int, what: str) -> dict[str, Any]:
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ raise PairingError(f"could not read {what}: {exc}") from exc
+ if not isinstance(payload, dict) or payload.get("schema_version") != schema_version:
+ raise PairingError(f"unsupported {what} schema")
+ return payload
+
+
+class PairingAuditLog:
+ """Append-only JSON-lines audit trail for pairing decisions (0600)."""
+
+ def __init__(self, path: Path) -> None:
+ self.path = Path(path)
+ self._lock = threading.Lock()
+
+ def record(
+ self, event: str, *, node_id: str = "", detail: dict[str, Any] | None = None
+ ) -> dict[str, Any]:
+ entry = {
+ "ts": time.time(),
+ "event": event,
+ "node_id": node_id,
+ "detail": detail or {},
+ }
+ line = json.dumps(entry, sort_keys=True)
+ with self._lock:
+ try:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ fresh = not self.path.exists()
+ with self.path.open("a", encoding="utf-8") as stream:
+ stream.write(line + "\n")
+ if fresh:
+ os.chmod(self.path, 0o600)
+ except OSError:
+ # Auditing must never break a pairing state transition.
+ logger.exception("could not append to the pairing audit log")
+ return entry
+
+
+class PairingKeyStore:
+ """Per-peer cluster keys at ``/cluster/pairing-keys.json`` (0600).
+
+ Written on both sides: the coordinator records the key it issued, the
+ joiner records the key it unwrapped. Also retains the peer's SSH public
+ key and addresses so ``unpair`` can revoke exactly what ``approve``
+ installed.
+ """
+
+ def __init__(self, base_path: Path, *, clock: Callable[[], float] = time.time):
+ self.base_path = Path(base_path)
+ self.path = self.base_path / "cluster" / "pairing-keys.json"
+ self._clock = clock
+ self._lock = threading.RLock()
+ self._records: dict[str, dict[str, Any]] = {}
+ self.load_error: str | None = None
+ try:
+ self._load()
+ except PairingError as exc:
+ # Fail closed, like ClusterRegistry: trust nothing from a corrupt file.
+ self._records = {}
+ self.load_error = str(exc)
+
+ def _load(self) -> None:
+ if not self.path.exists():
+ return
+ payload = _read_json_object(self.path, KEY_SCHEMA_VERSION, "pairing-key store")
+ records = payload.get("keys")
+ if not isinstance(records, dict):
+ raise PairingError("pairing-key store is malformed")
+ self._records = {str(k): dict(v) for k, v in records.items()}
+
+ def _save(self) -> None:
+ _atomic_write_json(
+ self.path,
+ {"schema_version": KEY_SCHEMA_VERSION, "keys": self._records},
+ )
+
+ def set(self, node_id: str, record: dict[str, Any]) -> None:
+ with self._lock:
+ previous = dict(self._records)
+ self._records[node_id] = dict(record)
+ try:
+ self._save()
+ except Exception:
+ self._records = previous
+ raise
+ self.load_error = None
+
+ def get(self, node_id: str) -> dict[str, Any] | None:
+ with self._lock:
+ record = self._records.get(node_id)
+ return dict(record) if record is not None else None
+
+ def remove(self, node_id: str) -> dict[str, Any] | None:
+ with self._lock:
+ record = self._records.pop(node_id, None)
+ if record is None:
+ return None
+ try:
+ self._save()
+ except Exception:
+ self._records[node_id] = record
+ raise
+ return dict(record)
+
+ def list(self) -> dict[str, dict[str, Any]]:
+ with self._lock:
+ return {key: dict(value) for key, value in sorted(self._records.items())}
+
+
+class JsonDeviceStore:
+ """Fallback paired-device store, schema-compatible with Module A.
+
+ Persists to ``/cluster/devices.json`` — the exact file Module A's
+ ``DeviceRegistry`` owns — using the documented shape: paired devices as
+ ``{node_id, friendly_name, caps, paired_at, last_addrs, state}`` under
+ ``schema_version: 1``. Used only when no Module A registry is injected;
+ when Module A lands, the integrator passes its ``DeviceRegistry`` and this
+ class is unused (``DeviceRegistryBridge`` adapts it instead).
+
+ Pending (``awaiting_approval``) requests are deliberately NOT written
+ here: like enrollment.py join keys, they are memory-only so a restart
+ invalidates half-finished pairings.
+ """
+
+ def __init__(self, base_path: Path) -> None:
+ self.base_path = Path(base_path)
+ self.path = self.base_path / "cluster" / "devices.json"
+ self._lock = threading.RLock()
+ self._devices: dict[str, dict[str, Any]] = {}
+ self.load_error: str | None = None
+ try:
+ self._load()
+ except PairingError as exc:
+ self._devices = {}
+ self.load_error = str(exc)
+
+ def _load(self) -> None:
+ if not self.path.exists():
+ return
+ payload = _read_json_object(self.path, DEVICE_SCHEMA_VERSION, "device registry")
+ devices = payload.get("devices")
+ if not isinstance(devices, list):
+ raise PairingError("device registry is malformed")
+ self._devices = {
+ str(item["node_id"]): dict(item)
+ for item in devices
+ if isinstance(item, dict) and "node_id" in item
+ }
+
+ def _save(self) -> None:
+ _atomic_write_json(
+ self.path,
+ {
+ "schema_version": DEVICE_SCHEMA_VERSION,
+ "devices": [self._devices[key] for key in sorted(self._devices)],
+ },
+ )
+
+ # PairingManager device-store protocol ---------------------------------
+
+ def put_paired(self, record: dict[str, Any]) -> None:
+ with self._lock:
+ previous = dict(self._devices)
+ merged = dict(previous.get(record["node_id"], {}))
+ merged.update(record)
+ merged["state"] = "paired"
+ self._devices[record["node_id"]] = merged
+ try:
+ self._save()
+ except Exception:
+ self._devices = previous
+ raise
+ self.load_error = None
+
+ def get(self, node_id: str) -> dict[str, Any] | None:
+ with self._lock:
+ record = self._devices.get(node_id)
+ return dict(record) if record is not None else None
+
+ def list_paired(self) -> list[dict[str, Any]]:
+ with self._lock:
+ return [dict(self._devices[key]) for key in sorted(self._devices)]
+
+ def remove(self, node_id: str) -> bool:
+ with self._lock:
+ if node_id not in self._devices:
+ return False
+ previous = dict(self._devices)
+ del self._devices[node_id]
+ try:
+ self._save()
+ except Exception:
+ self._devices = previous
+ raise
+ return True
+
+
+class DeviceRegistryBridge:
+ """Adapt Module A's ``DeviceRegistry`` to the pairing device-store protocol.
+
+ Module A ships concurrently; its exact merge API is its own deliverable.
+ Each operation feature-detects the documented candidates in order and
+ raises a clear error if none exist, so an API drift fails loudly at
+ integration time rather than silently dropping peers.
+
+ Integration note: the real ``DeviceRegistry.mark_paired`` takes keyword
+ fields, not a record dict, and its ``merge`` only persists *already
+ paired* devices — routing a pairing approval through ``merge`` would
+ leave the new peer memory-only. ``mark_paired`` is therefore detected
+ first and called with the record's fields.
+ """
+
+ _PUT = ("upsert", "merge", "put", "add", "set_paired")
+ _REMOVE = ("remove", "delete", "unpair", "drop")
+ _GET = ("get", "device", "find")
+ _LIST = ("list_paired", "paired", "list", "devices")
+
+ def __init__(self, registry: Any) -> None:
+ self._registry = registry
+
+ def _call(self, names: Iterable[str], *args: Any) -> Any:
+ for name in names:
+ method = getattr(self._registry, name, None)
+ if callable(method):
+ return method(*args)
+ raise PairingStateError(
+ "DeviceRegistry exposes none of "
+ + ", ".join(names)
+ + "; update DeviceRegistryBridge for Module A's API"
+ )
+
+ def put_paired(self, record: dict[str, Any]) -> None:
+ mark_paired = getattr(self._registry, "mark_paired", None)
+ if callable(mark_paired):
+ mark_paired(
+ record["node_id"],
+ friendly_name=record.get("friendly_name") or None,
+ caps=record.get("caps") or None,
+ addrs=record.get("last_addrs") or None,
+ paired_at=record.get("paired_at"),
+ http_port=record.get("http_port"),
+ )
+ return
+ self._call(self._PUT, record)
+
+ def get(self, node_id: str) -> dict[str, Any] | None:
+ result = self._call(self._GET, node_id)
+ return dict(result) if isinstance(result, dict) else None
+
+ def list_paired(self) -> list[dict[str, Any]]:
+ result = self._call(self._LIST)
+ if result is None:
+ return []
+ return [dict(item) for item in result]
+
+ def remove(self, node_id: str) -> bool:
+ return bool(self._call(self._REMOVE, node_id))
+
+
+def _coerce_device_store(registry: Any, base_path: Path) -> Any:
+ """Return a device store: injected Module A registry, protocol object, or fallback."""
+
+ if registry is None:
+ return JsonDeviceStore(base_path)
+ if all(
+ callable(getattr(registry, name, None))
+ for name in ("put_paired", "get", "list_paired", "remove")
+ ):
+ return registry
+ return DeviceRegistryBridge(registry)
+
+
+# --- Local identity (Module A bridge) ---------------------------------------
+
+
+def _default_friendly_name() -> str:
+ if platform.system() == "Darwin":
+ try:
+ result = subprocess.run(
+ ["scutil", "--get", "LocalHostName"],
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=5,
+ )
+ name = result.stdout.strip()
+ if result.returncode == 0 and name:
+ return name
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ return socket.gethostname()
+
+
+def _identity_from_dict(payload: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "node_id": str(payload["node_id"]),
+ "friendly_name": str(payload["friendly_name"]),
+ "created_at": float(payload["created_at"]),
+ "schema_version": IDENTITY_SCHEMA_VERSION,
+ }
+
+
+def _fallback_identity(base_path: Path) -> dict[str, Any]:
+ """``load_or_create`` against the same file Module A's identity.py owns.
+
+ Same path (``~/.omlx/cluster/identity.json``), same schema_version 1,
+ same 0600 atomic write — when Module A merges it adopts this identity
+ instead of minting a second node_id.
+ """
+
+ path = Path(base_path) / "cluster" / "identity.json"
+ if path.exists():
+ payload = _read_json_object(path, IDENTITY_SCHEMA_VERSION, "cluster identity")
+ return _identity_from_dict(payload)
+ identity = {
+ "node_id": str(uuid.uuid4()),
+ "friendly_name": _default_friendly_name(),
+ "created_at": time.time(),
+ "schema_version": IDENTITY_SCHEMA_VERSION,
+ }
+ _atomic_write_json(path, identity)
+ return identity
+
+
+def load_node_identity(base_path: Path) -> dict[str, Any]:
+ """Prefer Module A's ``identity.load_or_create``; fall back locally."""
+
+ try:
+ from .identity import (
+ load_or_create as _load_or_create, # type: ignore[import-not-found]
+ )
+ except ImportError:
+ return _fallback_identity(base_path)
+ identity = _load_or_create(base_path / "cluster" / "identity.json")
+ return {
+ "node_id": identity.node_id,
+ "friendly_name": identity.friendly_name,
+ "created_at": float(getattr(identity, "created_at", time.time())),
+ "schema_version": getattr(identity, "schema_version", IDENTITY_SCHEMA_VERSION),
+ }
+
+
+# --- Pending requests (memory-only, like enrollment.py join keys) ------------
+
+
+@dataclass
+class _PendingRequest:
+ node_id: str
+ friendly_name: str
+ caps: dict[str, Any]
+ code_hash: str
+ code_salt: bytes
+ addrs: list[str]
+ http_port: int | None
+ ssh_public_key: str | None
+ ssh_host_public_key: str
+ created_at: float
+ expires_at: float
+ attempts: int = 0
+ locked_until: float | None = None
+ approving: bool = False
+
+ def to_dict(self, now: float) -> dict[str, Any]:
+ locked = self.locked_until is not None and self.locked_until > now
+ return {
+ "node_id": self.node_id,
+ "friendly_name": self.friendly_name,
+ "caps": self.caps,
+ "addrs": list(self.addrs),
+ "http_port": self.http_port,
+ "state": "awaiting_approval",
+ "created_at": self.created_at,
+ "expires_at": self.expires_at,
+ "attempts": self.attempts,
+ "locked": locked,
+ "locked_until": self.locked_until if locked else None,
+ "approving": self.approving,
+ }
+
+
+# --- SSH TOFU enrollment drivers (defaults drive omlx/cluster/ssh_keys.py) ---
+
+
+def default_enrollment_driver(peer: dict[str, Any]) -> dict[str, Any]:
+ """Drive the existing fail-closed SSH TOFU enrollment for an approved peer.
+
+ Reuses the exact primitives of the legacy 3-step flow instead of
+ reinventing trust stores:
+
+ * ``ssh_keys.get_or_create_ssh_key`` — the coordinator's dedicated
+ ``~/.ssh/omlx_cluster`` identity must exist;
+ * ``ssh_keys.install_authorized_key`` — the joiner's user key (sent in
+ the join request) is authorized locally so the joiner can be a client;
+ * ``ssh_keys.pin_enrolled_host_key`` — pin the code-authenticated daemon
+ host key for each coordinator-observed address, refusing changed hosts.
+ """
+
+ from .ssh_keys import (
+ get_or_create_ssh_key,
+ install_authorized_key,
+ pin_enrolled_host_key,
+ )
+
+ key_pair = get_or_create_ssh_key()
+ result: dict[str, Any] = {
+ "coordinator_fingerprint": key_pair.fingerprint,
+ "authorized_key_installed": False,
+ "host_keys_pinned": [],
+ }
+ peer_public_key = normalize_ssh_public_key(peer.get("ssh_public_key") or "")
+ peer_host_key = normalize_ssh_public_key(peer.get("ssh_host_public_key") or "")
+ addresses = [str(address) for address in (peer.get("addrs") or []) if address]
+ if not addresses:
+ raise EnrollmentDriveError("SSH enrollment requires a verified peer address")
+ for address in addresses:
+ target = ssh_host_target(address)
+ if pin_enrolled_host_key(hostname=target, public_key=peer_host_key):
+ result["host_keys_pinned"].append(address)
+ result["authorized_key_installed"] = install_authorized_key(
+ public_key=peer_public_key
+ )
+ return result
+
+
+def default_revocation_driver(revocation: dict[str, Any]) -> dict[str, Any]:
+ """Best-effort undo of what ``default_enrollment_driver`` installed.
+
+ The device-store removal (the trust anchor) already happened before this
+ runs; here we only retract SSH material: the peer's authorized_keys line
+ and its known_hosts pins. Errors are collected, never raised — a
+ partially cleaned SSH file must not resurrect a removed device.
+ """
+
+ result: dict[str, Any] = {"authorized_key_removed": False, "errors": []}
+ ssh_dir = Path.home() / ".ssh"
+ peer_public_key = (revocation.get("peer_public_key") or "").strip()
+ if peer_public_key:
+ authorized_keys = ssh_dir / "authorized_keys"
+ try:
+ if authorized_keys.exists():
+ lines = authorized_keys.read_text(encoding="utf-8").splitlines()
+ kept = [line for line in lines if line.strip() != peer_public_key]
+ if len(kept) != len(lines):
+ authorized_keys.write_text(
+ "".join(line + "\n" for line in kept), encoding="utf-8"
+ )
+ os.chmod(authorized_keys, 0o600)
+ result["authorized_key_removed"] = True
+ except OSError as exc:
+ result["errors"].append(f"authorized_keys: {exc}")
+ keygen = "/usr/bin/ssh-keygen"
+ for address in revocation.get("addrs") or []:
+ try:
+ subprocess.run(
+ [keygen, "-R", address],
+ capture_output=True,
+ check=False,
+ timeout=10,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ result["errors"].append(f"known_hosts {address}: {exc}")
+ return result
+
+
+def _default_http_post(url: str, payload: dict[str, Any], timeout: float) -> Any:
+ request = urllib.request.Request(
+ url,
+ data=json.dumps(payload).encode("utf-8"),
+ headers={"Content-Type": "application/json"},
+ method="POST",
+ )
+ with urllib.request.urlopen(request, timeout=timeout) as response:
+ return json.loads(response.read().decode("utf-8"))
+
+
+def _default_http_get(url: str, timeout: float) -> Any:
+ with urllib.request.urlopen(url, timeout=timeout) as response:
+ return json.loads(response.read().decode("utf-8"))
+
+
+def _local_ssh_public_key() -> str | None:
+ """Best-effort local cluster pubkey for the join request (never fatal)."""
+
+ try:
+ from .ssh_keys import get_or_create_ssh_key
+ except ImportError:
+ return None
+ try:
+ return get_or_create_ssh_key().public_key
+ except Exception:
+ return None
+
+
+def _local_ssh_host_public_key() -> str | None:
+ """Read the public half of the local SSH daemon host identity."""
+
+ override = os.environ.get("OMLX_CLUSTER_SSH_HOST_PUBLIC_KEY")
+ candidates = (
+ [Path(override).expanduser()]
+ if override
+ else [
+ Path("/etc/ssh/ssh_host_ed25519_key.pub"),
+ Path("/etc/ssh/ssh_host_rsa_key.pub"),
+ ]
+ )
+ for path in candidates:
+ try:
+ return normalize_ssh_public_key(path.read_text(encoding="utf-8").strip())
+ except (OSError, PairingRequestError):
+ continue
+ return None
+
+
+def normalize_ssh_public_key(public_key: str) -> str:
+ """Validate and strip an OpenSSH user key to its type and key data."""
+
+ if not isinstance(public_key, str) or "\n" in public_key or "\r" in public_key:
+ raise PairingRequestError("join request carries an invalid SSH public key")
+ parts = public_key.strip().split()
+ if len(parts) < 2:
+ raise PairingRequestError("join request carries an invalid SSH public key")
+ normalized = " ".join(parts[:2])
+ try:
+ from .ssh_keys import ssh_public_key_fingerprint
+
+ ssh_public_key_fingerprint(normalized)
+ except (ImportError, RuntimeError, ValueError) as exc:
+ raise PairingRequestError(
+ "join request carries an invalid SSH public key"
+ ) from exc
+ return normalized
+
+
+def ssh_host_target(address: str) -> str:
+ """Format one validated IP for the existing known_hosts API."""
+
+ raw = str(address).strip()
+ if "%" in raw:
+ raise EnrollmentDriveError(
+ "SSH enrollment requires an address without an IPv6 scope suffix"
+ )
+ try:
+ parsed = ipaddress.ip_address(raw)
+ except ValueError as exc:
+ raise EnrollmentDriveError(
+ "SSH enrollment received an invalid address"
+ ) from exc
+ return f"[{parsed}]" if parsed.version == 6 else str(parsed)
+
+
+# --- PairingManager -----------------------------------------------------------
+
+
+class PairingManager:
+ """Joiner + coordinator sides of code-based pairing.
+
+ Parameters are dependency-injection seams; every default is production
+ behavior and every test substitutes fakes:
+
+ * ``registry`` — Module A ``DeviceRegistry`` (feature-detected via
+ :class:`DeviceRegistryBridge`), an object already speaking the
+ device-store protocol, or ``None`` for the schema-compatible
+ :class:`JsonDeviceStore` fallback.
+ * ``enrollment_store`` — the legacy ``ClusterEnrollmentStore``; consulted
+ on ``unpair`` so CUDA-enrolled entries with the same node_id are
+ dropped too. Optional.
+ * ``identity`` — dict with ``node_id``/``friendly_name``; default bridges
+ to Module A's identity module (or the compatible local file).
+ * ``enrollment_driver`` / ``revocation_driver`` — SSH TOFU trust
+ install/retract steps; defaults drive ``omlx/cluster/ssh_keys.py``.
+ * ``http_post`` / ``http_get`` — joiner-side transport; loopback fakes
+ in tests, urllib in production.
+ """
+
+ def __init__(
+ self,
+ registry: Any = None,
+ enrollment_store: Any = None,
+ *,
+ base_path: Path | None = None,
+ identity: dict[str, Any] | None = None,
+ key_store: PairingKeyStore | None = None,
+ caps_provider: Callable[[], dict[str, Any]] | None = None,
+ address_provider: Callable[[], list[str]] | None = None,
+ http_port: int = 8000,
+ ssh_key_provider: Callable[[], str | None] | None = None,
+ ssh_host_key_provider: Callable[[], str | None] | None = None,
+ enrollment_driver: Callable[[dict[str, Any]], Any] | None = None,
+ revocation_driver: Callable[[dict[str, Any]], Any] | None = None,
+ http_post: Callable[[str, dict[str, Any], float], Any] | None = None,
+ http_get: Callable[[str, float], Any] | None = None,
+ clock: Callable[[], float] = time.time,
+ audit: PairingAuditLog | Callable[..., Any] | None = None,
+ ) -> None:
+ self.base_path = Path(base_path) if base_path is not None else DEFAULT_BASE_PATH
+ self._identity = (
+ dict(identity)
+ if identity is not None
+ else load_node_identity(self.base_path)
+ )
+ self._devices = _coerce_device_store(registry, self.base_path)
+ self._enrollment_store = enrollment_store
+ self._key_store = (
+ key_store
+ if key_store is not None
+ else PairingKeyStore(self.base_path, clock=clock)
+ )
+ self._caps_provider = caps_provider
+ self._address_provider = address_provider
+ self.http_port = http_port
+ self._ssh_key_provider = ssh_key_provider or _local_ssh_public_key
+ self._ssh_host_key_provider = (
+ ssh_host_key_provider or _local_ssh_host_public_key
+ )
+ self._enrollment_driver = enrollment_driver or default_enrollment_driver
+ self._revocation_driver = revocation_driver or default_revocation_driver
+ self._http_post = http_post or _default_http_post
+ self._http_get = http_get or _default_http_get
+ self._clock = clock
+ if audit is None:
+ audit = PairingAuditLog(self.base_path / "cluster" / "pairing-audit.jsonl")
+ self._audit = audit
+ self._lock = threading.RLock()
+ self._pending: dict[str, _PendingRequest] = {}
+ self._denied: dict[str, float] = {}
+ self._local_code: dict[str, Any] | None = None
+
+ # -- helpers ------------------------------------------------------------
+
+ @property
+ def node_id(self) -> str:
+ return self._identity["node_id"]
+
+ @property
+ def friendly_name(self) -> str:
+ return self._identity["friendly_name"]
+
+ def local_addrs(self) -> list[str]:
+ """Validated local IPs included in the peer's approved trust record."""
+
+ if self._address_provider is None:
+ return []
+ try:
+ candidates = self._address_provider()
+ except Exception:
+ return []
+ addresses: list[str] = []
+ for candidate in candidates or []:
+ raw = str(candidate).strip()
+ try:
+ parsed = ipaddress.ip_address(raw.split("%", 1)[0])
+ except ValueError:
+ continue
+ # The sender's link-local scope is not usable on another Mac.
+ if parsed.version == 6 and parsed.is_link_local:
+ continue
+ normalized = raw
+ if normalized not in addresses:
+ addresses.append(normalized)
+ if len(addresses) >= 8:
+ break
+ return addresses
+
+ def local_ssh_material(self) -> dict[str, Any]:
+ """Complete local trust material the opposite peer must install."""
+
+ addresses = self.local_addrs()
+ if not addresses:
+ raise EnrollmentDriveError(
+ "SSH enrollment requires a verified local address"
+ )
+ return {
+ "node_id": self.node_id,
+ "friendly_name": self.friendly_name,
+ "caps": self._caps_provider() if self._caps_provider else {},
+ "addrs": addresses,
+ "ssh_public_key": normalize_ssh_public_key(self._ssh_key_provider() or ""),
+ "ssh_host_public_key": normalize_ssh_public_key(
+ self._ssh_host_key_provider() or ""
+ ),
+ }
+
+ def _record_audit(
+ self, event: str, *, node_id: str = "", detail: dict[str, Any] | None = None
+ ) -> None:
+ record = getattr(self._audit, "record", None)
+ if callable(record):
+ record(event, node_id=node_id, detail=detail)
+ elif callable(self._audit):
+ self._audit(event, node_id=node_id, detail=detail)
+
+ def _prune_pending(self, now: float, keep: str | None = None) -> None:
+ expired = [
+ node_id
+ for node_id, pending in self._pending.items()
+ if pending.expires_at < now and node_id != keep
+ ]
+ for node_id in expired:
+ del self._pending[node_id]
+ self._record_audit("join_request_expired", node_id=node_id)
+ self._denied = {
+ node_id: ts for node_id, ts in self._denied.items() if ts + 3600 > now
+ }
+
+ # -- joiner side ----------------------------------------------------------
+
+ def start_join(self) -> dict[str, Any]:
+ """Generate the 6-digit code the joiner displays; valid 10 minutes."""
+
+ code = generate_pairing_code()
+ now = self._clock()
+ self._local_code = {
+ "code": code,
+ "created_at": now,
+ "expires_at": now + CODE_TTL_SECONDS,
+ "completing": False,
+ }
+ return {"code": code, "expires_at": self._local_code["expires_at"]}
+
+ def build_join_request(self, code: str | None = None) -> dict[str, Any]:
+ """Assemble the pair/request payload — identity + code hash, no code."""
+
+ if code is None:
+ if self._local_code is None:
+ raise PairingStateError("no join in progress; call start_join first")
+ if self._local_code["expires_at"] < self._clock():
+ raise PairingExpiredError("the displayed pairing code has expired")
+ code = self._local_code["code"]
+ validate_pairing_code(code)
+ caps = self._caps_provider() if self._caps_provider else {}
+ ssh_public_key = normalize_ssh_public_key(self._ssh_key_provider() or "")
+ ssh_host_public_key = normalize_ssh_public_key(
+ self._ssh_host_key_provider() or ""
+ )
+ code_salt = secrets.token_bytes(16)
+ return {
+ "node_id": self.node_id,
+ "friendly_name": self.friendly_name,
+ "caps": dict(caps),
+ "code_hash": pairing_code_hash(
+ code,
+ self.node_id,
+ ssh_public_key,
+ ssh_host_public_key,
+ code_salt,
+ ),
+ "code_salt": base64.b64encode(code_salt).decode("ascii"),
+ "http_port": self.http_port,
+ "addrs": self.local_addrs(),
+ "ssh_public_key": ssh_public_key,
+ "ssh_host_public_key": ssh_host_public_key,
+ }
+
+ def request_join(
+ self,
+ coordinator_addr: str,
+ code: str | None = None,
+ *,
+ timeout: float = 10.0,
+ ) -> dict[str, Any]:
+ """POST ``/api/cluster/pair/request`` to the coordinator."""
+
+ payload = self.build_join_request(code)
+ url = f"http://{coordinator_addr}/api/cluster/pair/request"
+ response = self._http_post(url, payload, timeout)
+ self._record_audit(
+ "join_requested",
+ node_id=self.node_id,
+ detail={"coordinator": coordinator_addr},
+ )
+ return {"state": "awaiting_approval", "response": response}
+
+ def poll_join(
+ self, coordinator_addr: str, *, timeout: float = 5.0
+ ) -> dict[str, Any]:
+ """GET the coordinator's view of this node's pairing status."""
+
+ url = f"http://{coordinator_addr}/api/cluster/pair/status/{self.node_id}"
+ return self._http_get(url, timeout)
+
+ def complete_join(
+ self, status: dict[str, Any], code: str | None = None
+ ) -> dict[str, Any]:
+ """Unwrap the approved cluster key and persist the coordinator as paired.
+
+ ``status`` is the payload from :meth:`poll_join` (or the loopback
+ equivalent). Fail-closed: a wrong code or tampered package raises
+ and nothing is stored.
+ """
+
+ if status.get("state") != "approved":
+ raise PairingStateError(
+ f"coordinator has not approved this node (state={status.get('state')!r})"
+ )
+ package = status.get("cluster_key_package")
+ if not isinstance(package, dict):
+ raise PairingRequestError("approval status is missing the wrapped key")
+ with self._lock:
+ local_code = self._local_code
+ if local_code is None:
+ raise PairingStateError("no join in progress; call start_join first")
+ if local_code["expires_at"] < self._clock():
+ self._local_code = None
+ raise PairingExpiredError("the displayed pairing code has expired")
+ if local_code.get("completing"):
+ raise PairingStateError("join completion is already in progress")
+ if code is None:
+ code = local_code["code"]
+ local_code["completing"] = True
+ try:
+ cluster_key = unwrap_cluster_key(package, code)
+ except Exception:
+ with self._lock:
+ if self._local_code is local_code:
+ local_code["completing"] = False
+ raise
+ coordinator = status.get("coordinator") or {}
+ coordinator_id = str(coordinator.get("node_id") or "")
+ if not coordinator_id:
+ with self._lock:
+ if self._local_code is local_code:
+ local_code["completing"] = False
+ raise PairingRequestError("approval status is missing coordinator identity")
+ coordinator_peer = {
+ "node_id": coordinator_id,
+ "friendly_name": coordinator.get("friendly_name", ""),
+ "caps": coordinator.get("caps") or {},
+ "addrs": list(coordinator.get("addrs") or []),
+ "ssh_public_key": coordinator.get("ssh_public_key"),
+ "ssh_host_public_key": coordinator.get("ssh_host_public_key"),
+ }
+ observed_tag = str(status.get("coordinator_identity_tag") or "")
+ try:
+ expected_tag = coordinator_identity_tag(cluster_key, coordinator_peer)
+ except Exception:
+ with self._lock:
+ if self._local_code is local_code:
+ local_code["completing"] = False
+ raise
+ if not hmac.compare_digest(observed_tag, expected_tag):
+ with self._lock:
+ if self._local_code is local_code:
+ local_code["completing"] = False
+ raise PairingCodeError("approval status coordinator identity was altered")
+ enrolled = False
+ try:
+ self._enrollment_driver(coordinator_peer)
+ enrolled = True
+ except Exception as exc:
+ self._record_audit(
+ "join_enrollment_failed",
+ node_id=coordinator_id,
+ detail={"error": str(exc)},
+ )
+ with self._lock:
+ if self._local_code is local_code:
+ local_code["completing"] = False
+ raise EnrollmentDriveError(
+ f"SSH enrollment failed; coordinator was not paired: {exc}"
+ ) from exc
+ paired_at = self._clock()
+ record = {
+ "node_id": coordinator_id,
+ "friendly_name": coordinator.get("friendly_name", ""),
+ "caps": coordinator.get("caps") or {},
+ "paired_at": paired_at,
+ "last_addrs": coordinator_peer["addrs"],
+ "http_port": status.get("coordinator_http_port"),
+ "state": "paired",
+ "role": "coordinator",
+ }
+ key_record = {
+ "cluster_key": cluster_key.hex(),
+ "peer_public_key": coordinator.get("ssh_public_key"),
+ "addrs": coordinator_peer["addrs"],
+ "paired_at": paired_at,
+ "role": "coordinator",
+ }
+ key_written = False
+ try:
+ with self._lock:
+ if self._local_code is not local_code or not local_code.get(
+ "completing"
+ ):
+ raise PairingStateError(
+ "join state changed while completion was in progress"
+ )
+ self._key_store.set(coordinator_id, key_record)
+ key_written = True
+ self._devices.put_paired(record)
+ self._local_code = None
+ except Exception as exc:
+ rollback_errors: list[str] = []
+ if key_written:
+ try:
+ self._key_store.remove(coordinator_id)
+ except Exception as rollback_exc:
+ rollback_errors.append(f"pairing key: {rollback_exc}")
+ if enrolled:
+ try:
+ self._revocation_driver(
+ {
+ "peer_public_key": coordinator.get("ssh_public_key"),
+ "addrs": coordinator_peer["addrs"],
+ }
+ )
+ except Exception as rollback_exc:
+ rollback_errors.append(f"SSH enrollment: {rollback_exc}")
+ with self._lock:
+ if self._local_code is local_code:
+ local_code["completing"] = False
+ self._record_audit(
+ "join_persistence_failed",
+ node_id=coordinator_id,
+ detail={"error": str(exc), "rollback_errors": rollback_errors},
+ )
+ suffix = (
+ "; rollback issues: " + "; ".join(rollback_errors)
+ if rollback_errors
+ else ""
+ )
+ raise PairingError(
+ "join state could not be persisted; coordinator was not paired: "
+ f"{exc}{suffix}"
+ ) from exc
+ self._record_audit("join_completed", node_id=coordinator_id)
+ return record
+
+ # -- coordinator side -----------------------------------------------------
+
+ def handle_join_request(self, payload: dict[str, Any]) -> dict[str, Any]:
+ """Register a joiner's pair/request as ``awaiting_approval``.
+
+ The code itself never arrives — only a salted PBKDF2 verifier bound to
+ the node and both SSH identities — so this endpoint can stay
+ unauthenticated; the admin's approve step (typing the code shown on the
+ joiner) is the trust decision.
+ """
+
+ if not isinstance(payload, dict):
+ raise PairingRequestError("join request must be an object")
+ node_id = str(payload.get("node_id") or "").strip()
+ friendly_name = str(payload.get("friendly_name") or "").strip()
+ code_hash = str(payload.get("code_hash") or "").strip()
+ code_salt_encoded = str(payload.get("code_salt") or "").strip()
+ caps = payload.get("caps")
+ addrs = payload.get("addrs") or []
+ http_port = payload.get("http_port")
+ ssh_public_key = payload.get("ssh_public_key")
+ ssh_host_public_key = payload.get("ssh_host_public_key")
+ if not node_id or len(node_id) > 255:
+ raise PairingRequestError("join request is missing a node_id")
+ if node_id == self.node_id:
+ raise PairingRequestError("a node cannot join its own cluster")
+ if not friendly_name or len(friendly_name) > 255:
+ raise PairingRequestError("join request is missing a friendly_name")
+ if len(code_hash) != 64 or any(c not in "0123456789abcdef" for c in code_hash):
+ raise PairingRequestError("join request carries a malformed code_hash")
+ try:
+ code_salt = base64.b64decode(code_salt_encoded, validate=True)
+ except (binascii.Error, ValueError, TypeError) as exc:
+ raise PairingRequestError(
+ "join request carries a malformed code_salt"
+ ) from exc
+ if len(code_salt) != 16:
+ raise PairingRequestError("join request carries a malformed code_salt")
+ if not isinstance(caps, dict):
+ raise PairingRequestError("join request caps must be an object")
+ if not isinstance(addrs, list) or not all(isinstance(a, str) for a in addrs):
+ raise PairingRequestError("join request addrs must be a list of strings")
+ normalized_addrs: list[str] = []
+ for address in addrs:
+ raw = address.strip()
+ try:
+ ipaddress.ip_address(raw.split("%", 1)[0])
+ except ValueError as exc:
+ raise PairingRequestError(
+ "join request carries an invalid peer address"
+ ) from exc
+ if raw not in normalized_addrs:
+ normalized_addrs.append(raw)
+ if http_port is not None and not (1 <= int(http_port) <= 65535):
+ raise PairingRequestError("join request http_port is out of range")
+ ssh_public_key = normalize_ssh_public_key(ssh_public_key or "")
+ ssh_host_public_key = normalize_ssh_public_key(ssh_host_public_key or "")
+
+ with self._lock:
+ now = self._clock()
+ self._prune_pending(now)
+ existing = self._pending.get(node_id)
+ if existing is not None:
+ same_request = (
+ hmac.compare_digest(existing.code_hash, code_hash)
+ and hmac.compare_digest(existing.code_salt, code_salt)
+ and existing.ssh_public_key == ssh_public_key
+ and existing.ssh_host_public_key == ssh_host_public_key
+ and existing.addrs == normalized_addrs[:8]
+ )
+ if same_request:
+ return existing.to_dict(now)
+ raise PairingStateError(
+ "a different join request is already pending for this node_id"
+ )
+ live = [p for p in self._pending.values() if p.node_id != node_id]
+ if len(live) >= MAX_PENDING_REQUESTS:
+ raise PairingRequestError(
+ "too many pending join requests; approve or deny one first"
+ )
+ request = _PendingRequest(
+ node_id=node_id,
+ friendly_name=friendly_name,
+ caps=dict(caps),
+ code_hash=code_hash,
+ code_salt=code_salt,
+ addrs=normalized_addrs[:8],
+ http_port=int(http_port) if http_port is not None else None,
+ ssh_public_key=ssh_public_key,
+ ssh_host_public_key=ssh_host_public_key,
+ created_at=now,
+ expires_at=now + CODE_TTL_SECONDS,
+ )
+ self._pending[node_id] = request
+ self._denied.pop(node_id, None)
+ self._record_audit(
+ "join_request_received",
+ node_id=node_id,
+ detail={"friendly_name": friendly_name, "addrs": list(request.addrs)},
+ )
+ return request.to_dict(self._clock())
+
+ def pending_requests(self) -> list[dict[str, Any]]:
+ """Pending requests for the devices list (``state: awaiting_approval``)."""
+
+ with self._lock:
+ now = self._clock()
+ self._prune_pending(now)
+ return [self._pending[key].to_dict(now) for key in sorted(self._pending)]
+
+ def approve(self, node_id: str, code: str) -> dict[str, Any]:
+ """Verify the displayed code, issue the cluster key, enroll the peer.
+
+ Order is fail-closed: code verify → key wrap → SSH TOFU enrollment →
+ only then persist the peer as paired. If enrollment driving raises,
+ the peer is NOT stored; the pending request survives for a retry.
+ """
+
+ validate_pairing_code(code)
+ with self._lock:
+ now = self._clock()
+ # Expire *other* pending requests, but keep this one long enough
+ # to report a precise "expired" instead of a generic "no pending".
+ self._prune_pending(now, keep=node_id)
+ pending = self._pending.get(node_id)
+ if pending is None:
+ if node_id in self._denied:
+ raise PairingStateError("this join request was denied")
+ raise PairingStateError("no pending join request for this node_id")
+ if pending.expires_at < now:
+ del self._pending[node_id]
+ self._record_audit("join_request_expired", node_id=node_id)
+ raise PairingExpiredError("the pairing code has expired")
+ if pending.approving:
+ raise PairingStateError("approval is already in progress")
+ if pending.locked_until is not None and pending.locked_until > now:
+ self._record_audit(
+ "approve_locked_out",
+ node_id=node_id,
+ detail={"retry_after": pending.locked_until},
+ )
+ raise PairingLockoutError(
+ f"too many wrong codes; locked until {pending.locked_until:.0f}"
+ )
+ if pending.locked_until is not None and pending.locked_until <= now:
+ # Lockout served: fresh set of attempts, code still valid by TTL.
+ pending.locked_until = None
+ pending.attempts = 0
+ expected = pairing_code_hash(
+ code,
+ node_id,
+ pending.ssh_public_key or "",
+ pending.ssh_host_public_key,
+ pending.code_salt,
+ )
+ if not hmac.compare_digest(expected, pending.code_hash):
+ pending.attempts += 1
+ detail = {"attempts": pending.attempts}
+ if pending.attempts >= MAX_CODE_ATTEMPTS:
+ pending.locked_until = now + LOCKOUT_SECONDS
+ detail["locked_until"] = pending.locked_until
+ self._record_audit(
+ "approve_lockout", node_id=node_id, detail=detail
+ )
+ raise PairingLockoutError(
+ f"too many wrong codes; locked until {pending.locked_until:.0f}"
+ )
+ self._record_audit("approve_wrong_code", node_id=node_id, detail=detail)
+ raise PairingCodeError(
+ f"code does not match ({MAX_CODE_ATTEMPTS - pending.attempts} "
+ "attempts left)"
+ )
+ # Reserve this exact pending request before leaving the manager
+ # lock for SSH I/O. Deny, unpair, and duplicate approval must not
+ # race an enrollment that has already passed code verification.
+ pending.approving = True
+
+ try:
+ coordinator_material = self.local_ssh_material()
+ except Exception as exc:
+ self._record_audit(
+ "approve_enrollment_failed",
+ node_id=node_id,
+ detail={"error": str(exc)},
+ )
+ with self._lock:
+ if self._pending.get(node_id) is pending:
+ pending.approving = False
+ raise EnrollmentDriveError(
+ f"SSH enrollment failed; peer was not paired: {exc}"
+ ) from exc
+
+ cluster_key = secrets.token_bytes(CLUSTER_KEY_BYTES)
+ package = wrap_cluster_key(cluster_key, code)
+ coordinator_tag = coordinator_identity_tag(
+ cluster_key,
+ coordinator_material,
+ )
+
+ peer = {
+ "node_id": pending.node_id,
+ "friendly_name": pending.friendly_name,
+ "caps": pending.caps,
+ "addrs": list(pending.addrs),
+ "http_port": pending.http_port,
+ "ssh_public_key": pending.ssh_public_key,
+ "ssh_host_public_key": pending.ssh_host_public_key,
+ }
+ try:
+ enrollment = self._enrollment_driver(peer)
+ except Exception as exc:
+ self._record_audit(
+ "approve_enrollment_failed", node_id=node_id, detail={"error": str(exc)}
+ )
+ with self._lock:
+ if self._pending.get(node_id) is pending:
+ pending.approving = False
+ raise EnrollmentDriveError(
+ f"SSH enrollment failed; peer was not paired: {exc}"
+ ) from exc
+
+ paired_at = self._clock()
+ record = {
+ "node_id": pending.node_id,
+ "friendly_name": pending.friendly_name,
+ "caps": pending.caps,
+ "paired_at": paired_at,
+ "last_addrs": list(pending.addrs),
+ "http_port": pending.http_port,
+ "state": "paired",
+ "role": "peer",
+ }
+ key_record = {
+ "cluster_key": cluster_key.hex(),
+ # The joiner retrieves this package via pair/status and unwraps it
+ # with the code; safe to persist (0600) and serve.
+ "cluster_key_package": package,
+ "coordinator": coordinator_material,
+ # Keep endpoint metadata outside the v1 identity tag for compatibility.
+ "coordinator_http_port": self.http_port,
+ "coordinator_identity_tag": coordinator_tag,
+ "peer_public_key": pending.ssh_public_key,
+ "addrs": list(pending.addrs),
+ "paired_at": paired_at,
+ "role": "peer",
+ }
+ key_written = False
+ try:
+ with self._lock:
+ if self._pending.get(node_id) is not pending or not pending.approving:
+ raise PairingStateError(
+ "join request changed while approval was in progress"
+ )
+ self._key_store.set(pending.node_id, key_record)
+ key_written = True
+ self._devices.put_paired(record)
+ self._pending.pop(node_id, None)
+ except Exception as exc:
+ rollback_errors: list[str] = []
+ if key_written:
+ try:
+ self._key_store.remove(pending.node_id)
+ except Exception as rollback_exc:
+ rollback_errors.append(f"pairing key: {rollback_exc}")
+ try:
+ self._revocation_driver(
+ {
+ "peer_public_key": pending.ssh_public_key,
+ "addrs": list(pending.addrs),
+ }
+ )
+ except Exception as rollback_exc:
+ rollback_errors.append(f"SSH enrollment: {rollback_exc}")
+ with self._lock:
+ if self._pending.get(node_id) is pending:
+ pending.approving = False
+ detail = {"error": str(exc), "rollback_errors": rollback_errors}
+ self._record_audit(
+ "approve_persistence_failed",
+ node_id=node_id,
+ detail=detail,
+ )
+ suffix = (
+ "; rollback issues: " + "; ".join(rollback_errors)
+ if rollback_errors
+ else ""
+ )
+ raise PairingError(
+ f"pairing state could not be persisted; peer was not paired: "
+ f"{exc}{suffix}"
+ ) from exc
+ self._record_audit(
+ "approve_success",
+ node_id=node_id,
+ detail={"friendly_name": pending.friendly_name},
+ )
+ return {
+ "node_id": node_id,
+ "state": "paired",
+ "paired_at": paired_at,
+ "cluster_key_package": package,
+ "coordinator": coordinator_material,
+ "coordinator_http_port": self.http_port,
+ "coordinator_identity_tag": coordinator_tag,
+ "enrollment": enrollment,
+ }
+
+ def deny(self, node_id: str) -> bool:
+ """Refuse a pending request; the joiner sees ``denied`` on its next poll."""
+
+ with self._lock:
+ now = self._clock()
+ self._prune_pending(now)
+ pending = self._pending.get(node_id)
+ if pending is None:
+ return False
+ if pending.approving:
+ raise PairingStateError("approval is already in progress")
+ self._pending.pop(node_id, None)
+ self._denied[node_id] = now
+ self._record_audit("join_request_denied", node_id=node_id)
+ return True
+
+ def join_status(self, node_id: str) -> dict[str, Any]:
+ """Coordinator-side status consumed by the joiner's poll loop.
+
+ The wrapped cluster key is safe to serve here: it is encrypted under
+ a PBKDF2 key derived from the code only the joiner operator can see.
+ """
+
+ with self._lock:
+ now = self._clock()
+ self._prune_pending(now)
+ pending = self._pending.get(node_id)
+ denied = node_id in self._denied
+ if pending is not None:
+ return pending.to_dict(now)
+ key_record = self._key_store.get(node_id)
+ if key_record is not None:
+ device = self._devices.get(node_id) or {}
+ status: dict[str, Any] = {
+ "node_id": node_id,
+ "state": "approved",
+ "paired_at": key_record.get("paired_at"),
+ # Same coordinator block approve() returns: the joiner
+ # persists it via complete_join, so caps/ssh key must ride
+ # here too — the poll path is the only one the UI drives.
+ "coordinator": key_record.get("coordinator") or {},
+ "coordinator_http_port": key_record.get("coordinator_http_port"),
+ "coordinator_identity_tag": key_record.get("coordinator_identity_tag"),
+ }
+ package = key_record.get("cluster_key_package")
+ if package is not None:
+ status["cluster_key_package"] = package
+ if device:
+ status["friendly_name"] = device.get("friendly_name")
+ return status
+ if denied:
+ return {"node_id": node_id, "state": "denied"}
+ return {"node_id": node_id, "state": "unknown"}
+
+ def unpair(self, node_id: str) -> dict[str, Any]:
+ """Remove a paired device and revoke the trust installed at pairing.
+
+ Registry removal is the trust anchor and happens first (fail-closed);
+ SSH material retraction is best-effort and reported, never raised.
+ Also drops any legacy ``enrolled-nodes.json`` entry with the same
+ node_id so both trusted-node inventories stay in step.
+ """
+
+ with self._lock:
+ now = self._clock()
+ self._prune_pending(now)
+ pending = self._pending.get(node_id)
+ if pending is not None and pending.approving:
+ raise PairingStateError("approval is already in progress")
+ was_pending = self._pending.pop(node_id, None) is not None
+ device = self._devices.get(node_id)
+ removed_device = self._devices.remove(node_id)
+ key_record = self._key_store.get(node_id)
+ if key_record is not None:
+ self._key_store.remove(node_id)
+ if not (removed_device or key_record or was_pending):
+ raise PairingStateError("unknown device")
+
+ removed_enrollment = False
+ if self._enrollment_store is not None:
+ remove_node = getattr(self._enrollment_store, "remove_node", None)
+ if callable(remove_node):
+ with suppress(Exception):
+ removed_enrollment = bool(remove_node(node_id))
+
+ revocation: dict[str, Any] = {"authorized_key_removed": False, "errors": []}
+ material = {
+ "peer_public_key": (key_record or {}).get("peer_public_key"),
+ "addrs": (key_record or {}).get("addrs")
+ or (device or {}).get("last_addrs")
+ or [],
+ }
+ if material["peer_public_key"] or material["addrs"]:
+ try:
+ revocation = self._revocation_driver(material) or revocation
+ except Exception as exc:
+ revocation["errors"].append(str(exc))
+
+ self._record_audit(
+ "device_unpaired",
+ node_id=node_id,
+ detail={
+ "removed_device": removed_device,
+ "removed_key": key_record is not None,
+ "removed_enrollment": removed_enrollment,
+ "was_pending": was_pending,
+ },
+ )
+ return {
+ "node_id": node_id,
+ "unpaired": True,
+ "removed_device": removed_device,
+ "removed_key": key_record is not None,
+ "removed_enrollment": removed_enrollment,
+ "was_pending": was_pending,
+ "revocation": revocation,
+ }
+
+ def paired_devices(self) -> list[dict[str, Any]]:
+ """Persisted paired devices (discovered-but-unpaired never land here)."""
+
+ return self._devices.list_paired()
+
+ def devices_view(self) -> dict[str, Any]:
+ """Coordinator devices list: paired + awaiting_approval + self."""
+
+ return {
+ "paired": self.paired_devices(),
+ "pending": self.pending_requests(),
+ "self": {
+ "node_id": self.node_id,
+ "friendly_name": self.friendly_name,
+ "caps": self._caps_provider() if self._caps_provider else {},
+ },
+ }
+
+
+# --- Configured singleton (mirrors enrollment.py's configure/get pattern) ----
+
+_manager_lock = threading.Lock()
+_configured_manager: PairingManager | None = None
+
+
+def configure_pairing_manager(
+ base_path: Path,
+ *,
+ registry: Any = None,
+ enrollment_store: Any = None,
+ **kwargs: Any,
+) -> PairingManager:
+ """Create the process-wide manager at server startup.
+
+ ``registry`` should be Module A's ``DeviceRegistry`` once that branch is
+ integrated; until then ``None`` selects the schema-compatible fallback.
+ """
+
+ global _configured_manager
+ with _manager_lock:
+ _configured_manager = PairingManager(
+ registry,
+ enrollment_store,
+ base_path=base_path,
+ **kwargs,
+ )
+ return _configured_manager
+
+
+def get_pairing_manager() -> PairingManager:
+ with _manager_lock:
+ if _configured_manager is None:
+ raise RuntimeError("cluster pairing is not configured")
+ return _configured_manager
+
+
+def reset_pairing_manager() -> None:
+ """Test hook: drop the configured manager so tests stay isolated."""
+
+ global _configured_manager
+ with _manager_lock:
+ _configured_manager = None
diff --git a/omlx/cluster/pairing_routes.py b/omlx/cluster/pairing_routes.py
new file mode 100644
index 0000000000..cd40c2d374
--- /dev/null
+++ b/omlx/cluster/pairing_routes.py
@@ -0,0 +1,184 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Cluster v2 pairing endpoints (Module B).
+
+Two routers, both under ``/api/cluster`` (the v2 surface; the legacy 3-step
+copy-paste endpoints stay untouched under ``/admin/api/cluster`` as
+"Advanced (legacy)"):
+
+* ``pair_router`` — unauthenticated joiner-facing endpoints. The pair request
+ carries a salted PBKDF2 verifier binding the node and both SSH identities,
+ and the coordinator binds enrollment to the HTTP source address. The served
+ cluster key is separately encrypted under a code-derived key, so the admin's
+ approve step remains the sole trust decision.
+* ``pair_admin_router`` — admin-facing approve/deny/unpair. Mounted with
+ ``Depends(require_admin)`` exactly like the existing cluster router.
+
+Both are wired in ``omlx/server.py:_register_cluster_routes``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import ipaddress
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel, ConfigDict, Field
+
+from .discovery_routes import ProbeRateLimiter
+from .pairing import (
+ CODE_DIGITS,
+ EnrollmentDriveError,
+ PairingCodeError,
+ PairingError,
+ PairingExpiredError,
+ PairingLockoutError,
+ PairingManager,
+ PairingStateError,
+ get_pairing_manager,
+)
+
+pair_router = APIRouter(prefix="/api/cluster", tags=["cluster-v2-pairing"])
+pair_admin_router = APIRouter(prefix="/api/cluster", tags=["cluster-v2-pairing-admin"])
+
+_get_pairing_manager: Any = get_pairing_manager
+pair_request_rate_limiter = ProbeRateLimiter(rate_per_second=0.5, burst=8)
+pair_status_rate_limiter = ProbeRateLimiter(rate_per_second=5.0, burst=20)
+
+
+def set_pairing_manager_getter(getter: Any) -> None:
+ """Inject the server-owned manager without importing ``omlx.server``."""
+
+ global _get_pairing_manager
+ _get_pairing_manager = getter
+
+
+def _manager() -> PairingManager:
+ try:
+ return _get_pairing_manager()
+ except RuntimeError as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
+
+
+class PairRequestBody(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ node_id: str = Field(min_length=1, max_length=255)
+ friendly_name: str = Field(min_length=1, max_length=255)
+ caps: dict[str, Any] = Field(default_factory=dict)
+ code_hash: str = Field(pattern=r"^[a-f0-9]{64}$")
+ code_salt: str = Field(min_length=24, max_length=64)
+ http_port: int | None = Field(default=None, ge=1, le=65535)
+ addrs: list[str] = Field(default_factory=list, max_length=8)
+ ssh_public_key: str = Field(min_length=32, max_length=8192)
+ ssh_host_public_key: str = Field(min_length=32, max_length=8192)
+
+
+class PairApproveBody(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ node_id: str = Field(min_length=1, max_length=255)
+ code: str = Field(pattern=rf"^[0-9]{{{CODE_DIGITS}}}$")
+
+
+class PairDenyBody(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ node_id: str = Field(min_length=1, max_length=255)
+
+
+def _pairing_http_error(exc: PairingError) -> HTTPException:
+ if isinstance(exc, PairingLockoutError):
+ return HTTPException(status_code=423, detail=str(exc))
+ if isinstance(exc, PairingExpiredError):
+ return HTTPException(status_code=410, detail=str(exc))
+ if isinstance(exc, PairingCodeError):
+ return HTTPException(status_code=403, detail=str(exc))
+ if isinstance(exc, EnrollmentDriveError):
+ return HTTPException(status_code=502, detail=str(exc))
+ if isinstance(exc, PairingStateError):
+ return HTTPException(status_code=404, detail=str(exc))
+ return HTTPException(status_code=400, detail=str(exc))
+
+
+@pair_router.post("/pair/request", status_code=202)
+async def cluster_pair_request(body: PairRequestBody, request: Request):
+ """Register a joiner's request as awaiting_approval (code never crosses)."""
+
+ manager = _manager()
+ payload = body.model_dump()
+ source = request.client.host if request.client is not None else ""
+ if not pair_request_rate_limiter.allow(source or "unknown"):
+ raise HTTPException(status_code=429, detail="pair request rate limit exceeded")
+ try:
+ ipaddress.ip_address(source.split("%", 1)[0])
+ except ValueError:
+ payload["addrs"] = []
+ else:
+ # Never enroll an arbitrary address supplied in the public JSON body.
+ # The HTTP source is the only coordinator-observed endpoint.
+ payload["addrs"] = [source]
+ try:
+ snapshot = await asyncio.to_thread(manager.handle_join_request, payload)
+ except PairingError as exc:
+ raise _pairing_http_error(exc) from exc
+ return snapshot
+
+
+@pair_router.get("/pair/status/{node_id}")
+async def cluster_pair_status(node_id: str, request: Request):
+ """Joiner poll: pending/approved/denied plus the wrapped cluster key."""
+
+ manager = _manager()
+ source = request.client.host if request.client is not None else ""
+ if not pair_status_rate_limiter.allow(source or "unknown"):
+ raise HTTPException(status_code=429, detail="pair status rate limit exceeded")
+ if not node_id or len(node_id) > 255:
+ raise HTTPException(status_code=400, detail="invalid node_id")
+ return await asyncio.to_thread(manager.join_status, node_id)
+
+
+@pair_admin_router.post("/pair/approve")
+async def cluster_pair_approve(body: PairApproveBody):
+ """Type the code shown on the joiner; verify, issue cluster key, enroll."""
+
+ manager = _manager()
+ try:
+ result = await asyncio.to_thread(manager.approve, body.node_id, body.code)
+ except PairingError as exc:
+ raise _pairing_http_error(exc) from exc
+ try:
+ from .discovery import get_discovery_service
+
+ get_discovery_service().mark_paired(body.node_id)
+ except Exception:
+ # Pairing remains authoritative when discovery is disabled or stopped.
+ pass
+ return result
+
+
+@pair_admin_router.post("/pair/deny")
+async def cluster_pair_deny(body: PairDenyBody):
+ """Refuse a pending join request (audit-logged)."""
+
+ manager = _manager()
+ try:
+ denied = await asyncio.to_thread(manager.deny, body.node_id)
+ except PairingError as exc:
+ raise _pairing_http_error(exc) from exc
+ if not denied:
+ raise HTTPException(status_code=404, detail="no pending join request")
+ return {"ok": True, "node_id": body.node_id, "state": "denied"}
+
+
+@pair_admin_router.delete("/devices/{node_id}")
+async def cluster_unpair_device(node_id: str):
+ """Unpair: drop the registry entry, the cluster key, and SSH trust."""
+
+ manager = _manager()
+ if not node_id or len(node_id) > 255:
+ raise HTTPException(status_code=400, detail="invalid node_id")
+ try:
+ return await asyncio.to_thread(manager.unpair, node_id)
+ except PairingError as exc:
+ raise _pairing_http_error(exc) from exc
diff --git a/omlx/cluster/planner.py b/omlx/cluster/planner.py
index 2b5ae26ff8..31069da1e5 100644
--- a/omlx/cluster/planner.py
+++ b/omlx/cluster/planner.py
@@ -11,7 +11,8 @@
import threading
from collections.abc import Iterator, Sequence
from contextlib import contextmanager
-from dataclasses import dataclass, replace
+from dataclasses import dataclass, field, replace
+from fractions import Fraction
from pathlib import Path
from typing import Any
@@ -54,16 +55,13 @@ def normalize_node_role(value: Any) -> str:
if value is None:
return ""
if not isinstance(value, str):
- raise ValueError(
- f"node role must be a string, got {type(value).__name__}"
- )
+ raise ValueError(f"node role must be a string, got {type(value).__name__}")
text = value.strip().lower()
if not text:
return ""
if text not in ROLES:
raise ValueError(
- f"unknown node role: {value!r} (expected one of "
- f"{', '.join(sorted(ROLES))})"
+ f"unknown node role: {value!r} (expected one of {', '.join(sorted(ROLES))})"
)
return text
@@ -213,8 +211,7 @@ def from_dict(cls, payload: dict[str, Any]) -> ModelLayout:
payload.get("tensor_parallel_kv_heads", 0)
),
tensor_parallel_divisors=tuple(
- int(value)
- for value in payload.get("tensor_parallel_divisors", ())
+ int(value) for value in payload.get("tensor_parallel_divisors", ())
),
kv_bytes_per_token_per_layer=int(
payload.get("kv_bytes_per_token_per_layer", 0)
@@ -426,6 +423,11 @@ class ShardPlan:
# case the per-rank byte reservation is zero, but the operator's requested
# runtime limit must still be visible and part of the plan identity.
target_context_tokens: int = _DEFAULT_CONTEXT_TOKENS
+ # node_id → absolute model path on that node (cluster v2). Display and
+ # staging metadata only: the layer split is path-independent, so the map
+ # is deliberately excluded from ``plan_hash``. Empty means every node
+ # loads the shared coordinator path — the legacy behavior.
+ path_map: dict[str, str] = field(default_factory=dict)
@property
def max_context_tokens(self) -> int:
@@ -458,7 +460,7 @@ def cluster_resident_weight_bytes(self) -> int:
return sum(item.planned_weight_bytes for item in self.assignments)
def to_dict(self) -> dict[str, Any]:
- return {
+ result = {
"plan_version": 1,
"plan_hash": self.plan_hash,
"strategy": (
@@ -484,6 +486,9 @@ def to_dict(self) -> dict[str, Any]:
"tensor_parallel_size": self.tensor_parallel_size,
"pipeline_stages": self.pipeline_stages,
}
+ if self.path_map:
+ result["path_map"] = dict(sorted(self.path_map.items()))
+ return result
def synthetic_model_layout(*, total_weight_bytes: int, layer_count: int) -> ModelLayout:
@@ -581,6 +586,25 @@ def _config_int(
)
+def _config_nonnegative_int(config: dict[str, Any], key: str) -> int | None:
+ """Read an explicitly present, bounded integer that may be zero."""
+ candidates = [config]
+ for nested in ("text_config", "language_config", "llm_config"):
+ value = config.get(nested)
+ if isinstance(value, dict):
+ candidates.append(value)
+ return next(
+ (
+ value
+ for candidate in candidates
+ if isinstance((value := candidate.get(key)), int)
+ and not isinstance(value, bool)
+ and 0 <= value <= 4096
+ ),
+ None,
+ )
+
+
def _supports_tensor_parallel(config: dict[str, Any]) -> bool:
"""Whether this architecture has a runtime-safe tensor strategy.
@@ -658,9 +682,9 @@ def _tensor_parallel_divisors(config: dict[str, Any]) -> tuple[int, ...]:
// max(_config_int(config, "num_attention_heads", 1), 1)
)
attn_dim = _config_int(config, "num_attention_heads", 0) * head_dim
- mamba_dim = _config_int(
- config, "mamba_num_heads", 0
- ) * _config_int(config, "mamba_head_dim", 0)
+ mamba_dim = _config_int(config, "mamba_num_heads", 0) * _config_int(
+ config, "mamba_head_dim", 0
+ )
shared_dim = _config_int(
config,
"moe_shared_expert_intermediate_size",
@@ -796,7 +820,7 @@ def _kv_cache_replicated_across_tp(config: dict[str, Any]) -> bool:
return (
_config_int(config, "kv_lora_rank", 0) > 0
- and _config_int(config, "qk_rope_head_dim", 0) > 0
+ and _config_nonnegative_int(config, "qk_rope_head_dim") is not None
)
@@ -819,7 +843,29 @@ def _kv_bytes_per_token_per_layer(config: dict[str, Any]) -> int:
if _kv_cache_replicated_across_tp(config):
# One KV head holding latent + RoPE, not expanded K/V tensors.
kv_lora_rank = _config_int(config, "kv_lora_rank", 0)
- rope_dim = _config_int(config, "qk_rope_head_dim", 0)
+ rope_dim = _config_nonnegative_int(config, "qk_rope_head_dim") or 0
+ text_config = config.get("text_config")
+ layer_config = text_config if isinstance(text_config, dict) else config
+ layer_types = layer_config.get("layer_types")
+ if config.get("model_type") == "glm5_next" and isinstance(
+ layer_types, list
+ ):
+ num_layers = _config_int(config, "num_hidden_layers", 0)
+ sparse_layers = sum(
+ layer_type != "linear_attention" for layer_type in layer_types
+ )
+ index_dim = _config_int(config, "index_head_dim", 0)
+ index_pool = _config_int(config, "index_kpool", 1)
+ if num_layers > 0 and sparse_layers > 0:
+ # ModelLayout stores one integral average per layer. Keep the
+ # exact full-model total conservative by rounding upward.
+ numerator = (
+ sparse_layers
+ * ((kv_lora_rank + rope_dim) * index_pool + index_dim)
+ * dtype_size
+ )
+ denominator = num_layers * index_pool
+ return (numerator + denominator - 1) // denominator
return (kv_lora_rank + rope_dim) * dtype_size
heads = _config_int(config, "num_attention_heads", 0)
@@ -827,11 +873,7 @@ def _kv_bytes_per_token_per_layer(config: dict[str, Any]) -> int:
head_dim = _config_int(config, "head_dim", 0)
if head_dim <= 0:
hidden = _config_int(config, "hidden_size", 0, maximum=1_000_000)
- head_dim = (
- hidden // heads
- if hidden and heads and hidden % heads == 0
- else 0
- )
+ head_dim = hidden // heads if hidden and heads and hidden % heads == 0 else 0
if head_dim > 4096:
return 0
if kv_heads <= 0 or head_dim <= 0:
@@ -1012,14 +1054,10 @@ def inspect_safetensors_layout(model_path: str | Path) -> ModelLayout:
# the runtime model never instantiates them. Counting them as decoder
# layers put a stage boundary over weights that do not exist at runtime,
# and the last stage failed activation with end_layer beyond the model.
- declared_depth = _config_int(
- _model_config(root), "num_hidden_layers", 0
- )
+ declared_depth = _config_int(_model_config(root), "num_hidden_layers", 0)
if declared_depth > 0 and max(layer_sizes) >= declared_depth:
trimmed = {
- index: size
- for index, size in layer_sizes.items()
- if index < declared_depth
+ index: size for index, size in layer_sizes.items() if index < declared_depth
}
if trimmed:
layer_sizes = trimmed
@@ -1046,12 +1084,8 @@ def inspect_safetensors_layout(model_path: str | Path) -> ModelLayout:
tensor_parallel_divisors=_tensor_parallel_divisors(_model_config(root)),
supports_tensor_parallel=_supports_tensor_parallel(_model_config(root)),
supports_pipeline=_supports_pipeline(_model_config(root)),
- kv_bytes_per_token_per_layer=_kv_bytes_per_token_per_layer(
- _model_config(root)
- ),
- kv_replicated_across_tp=_kv_cache_replicated_across_tp(
- _model_config(root)
- ),
+ kv_bytes_per_token_per_layer=_kv_bytes_per_token_per_layer(_model_config(root)),
+ kv_replicated_across_tp=_kv_cache_replicated_across_tp(_model_config(root)),
)
@@ -1289,9 +1323,7 @@ def _partition_layers(
start = previous_end
for end in range(max(start + 1, minimum_end), maximum_end + 1):
layer_bytes = weight_prefix[end] - weight_prefix[start]
- resident_layer_bytes = (
- resident_prefix[end] - resident_prefix[start]
- )
+ resident_layer_bytes = resident_prefix[end] - resident_prefix[start]
planned_weight_bytes = fixed_weight_bytes + layer_bytes
planned_resident_bytes = fixed_weight_bytes + resident_layer_bytes
if planned_weight_bytes > node.weight_ceiling_bytes:
@@ -1315,14 +1347,12 @@ def _partition_layers(
previous_score[score_offset + 1]
+ stage_seconds * stage_seconds,
max(previous_score[score_offset + 2], utilization),
- previous_score[score_offset + 3]
- + utilization * utilization,
+ previous_score[score_offset + 3] + utilization * utilization,
)
else:
score = (
max(previous_score[score_offset], utilization),
- previous_score[score_offset + 1]
- + utilization * utilization,
+ previous_score[score_offset + 1] + utilization * utilization,
)
if target_aware:
target = node.target_weight_bytes
@@ -1345,8 +1375,7 @@ def _partition_layers(
final = states.get(layer_count)
if final is None:
resident_capacity = sum(
- max(0, node.usable_bytes - fixed_weight_bytes)
- for node in pipeline_nodes
+ max(0, node.usable_bytes - fixed_weight_bytes) for node in pipeline_nodes
)
weight_capacity = sum(
max(0, node.weight_ceiling_bytes - fixed_weight_bytes)
@@ -1402,15 +1431,13 @@ def _predict_stage_seconds(
return compute_seconds, send_seconds, compute_seconds + send_seconds
-def plan_unequal_pipeline(
+def _validate_pipeline_request(
model: ModelLayout,
nodes: Sequence[NodeBudget],
- *,
- workload_profile: ExecutionProfileName = "balanced",
- microbatch_size: int = 1,
- context_tokens: int = _DEFAULT_CONTEXT_TOKENS,
-) -> ShardPlan:
- """Assign contiguous layers in MLX pipeline order across unequal nodes."""
+ workload_profile: ExecutionProfileName,
+ microbatch_size: int,
+) -> None:
+ """The input contract every pipeline planner enforces identically."""
if not nodes:
raise ValueError("at least one node is required")
@@ -1434,6 +1461,19 @@ def plan_unequal_pipeline(
f"replicated fixed weights do not fit node {node.node_id}"
)
+
+def plan_unequal_pipeline(
+ model: ModelLayout,
+ nodes: Sequence[NodeBudget],
+ *,
+ workload_profile: ExecutionProfileName = "balanced",
+ microbatch_size: int = 1,
+ context_tokens: int = _DEFAULT_CONTEXT_TOKENS,
+) -> ShardPlan:
+ """Assign contiguous layers in MLX pipeline order across unequal nodes."""
+
+ _validate_pipeline_request(model, nodes, workload_profile, microbatch_size)
+
# MLX-LM sends activations from the highest rank (early layers) down to
# rank zero (late layers / HTTP coordinator), so partition in reverse rank.
pipeline_nodes = tuple(sorted(nodes, key=lambda item: item.rank, reverse=True))
@@ -1459,6 +1499,132 @@ def plan_unequal_pipeline(
f"fit the supplied per-node budgets: {exc}"
) from exc
raise
+ return _finish_pipeline_plan(
+ model,
+ nodes,
+ pipeline_nodes,
+ ranges,
+ workload_profile=workload_profile,
+ microbatch_size=microbatch_size,
+ context_tokens=context_tokens,
+ optimization="performance" if performance_aware else "memory",
+ )
+
+
+def allocate_layers_proportional(
+ layer_count: int,
+ shares: Sequence[int],
+) -> tuple[int, ...]:
+ """Split ``layer_count`` across nodes proportionally to ``shares``.
+
+ Largest-remainder rounding with a one-layer minimum per node — the
+ allocation rule exo's placement uses, so a 256 GB + 128 GB pair splits
+ roughly ⅔–⅓. Fractions are exact (no float drift) and ties break toward
+ the larger share, then the earlier pipeline position, so the result is
+ deterministic and reproducible across machines.
+ """
+
+ if not isinstance(layer_count, int) or layer_count <= 0:
+ raise ValueError("layer_count must be a positive integer")
+ if not shares:
+ raise ValueError("at least one share is required")
+ for share in shares:
+ if not isinstance(share, int) or isinstance(share, bool) or share <= 0:
+ raise ValueError("shares must be positive integers")
+ node_count = len(shares)
+ if node_count > layer_count:
+ raise PlanningError(
+ f"{node_count} nodes cannot each receive a layer from {layer_count} layers"
+ )
+ total = sum(shares)
+ exact = [Fraction(layer_count * share, total) for share in shares]
+ counts = [max(1, value.numerator // value.denominator) for value in exact]
+ remainder = layer_count - sum(counts)
+ # Σfloor(exact) ≤ layer_count and the one-layer floor adds at most one per
+ # node that floored to zero, so ``remainder`` is never negative.
+ assert remainder >= 0
+ order = sorted(
+ range(node_count),
+ key=lambda index: (
+ -(exact[index] - counts[index]),
+ -shares[index],
+ index,
+ ),
+ )
+ for index in order[:remainder]:
+ counts[index] += 1
+ return tuple(counts)
+
+
+def plan_proportional_pipeline(
+ model: ModelLayout,
+ nodes: Sequence[NodeBudget],
+ *,
+ workload_profile: ExecutionProfileName = "balanced",
+ microbatch_size: int = 1,
+ context_tokens: int = _DEFAULT_CONTEXT_TOKENS,
+) -> ShardPlan:
+ """RAM-proportional N-node pipeline plan (largest-remainder, exo-style).
+
+ Layer counts are proportional to each node's usable memory
+ (``capacity − reserve``), rounded by largest remainder. Unlike the
+ balanced planner this does not optimize for the bottleneck stage or honor
+ soft weight targets — it is the predictable "split by RAM" rule operators
+ expect when generalizing beyond two nodes. Per-node weight ceilings (the
+ split control) and KV reservations are still enforced: a node whose
+ proportional share does not fit fails the plan with its name, rather than
+ being silently rebalanced.
+ """
+
+ _validate_pipeline_request(model, nodes, workload_profile, microbatch_size)
+
+ pipeline_nodes = tuple(sorted(nodes, key=lambda item: item.rank, reverse=True))
+ counts = allocate_layers_proportional(
+ len(model.layer_weight_bytes),
+ [node.usable_bytes for node in pipeline_nodes],
+ )
+ ranges: list[tuple[int, int]] = []
+ start = 0
+ for count in counts:
+ ranges.append((start, start + count))
+ start += count
+ for node, (range_start, range_end) in zip(pipeline_nodes, ranges):
+ layer_weight = sum(model.layer_weight_bytes[range_start:range_end])
+ if model.fixed_weight_bytes + layer_weight > node.weight_ceiling_bytes:
+ raise PlanningError(
+ f"the RAM-proportional split gives node {node.node_id} "
+ f"{range_end - range_start} layers "
+ f"({model.fixed_weight_bytes + layer_weight} bytes with fixed "
+ f"weights) above its weight ceiling of "
+ f"{node.weight_ceiling_bytes}; raise that node's split cap or "
+ "plan with the balanced allocator"
+ )
+ return _finish_pipeline_plan(
+ model,
+ nodes,
+ pipeline_nodes,
+ tuple(ranges),
+ workload_profile=workload_profile,
+ microbatch_size=microbatch_size,
+ context_tokens=context_tokens,
+ optimization="ram-proportional",
+ )
+
+
+def _finish_pipeline_plan(
+ model: ModelLayout,
+ nodes: Sequence[NodeBudget],
+ pipeline_nodes: Sequence[NodeBudget],
+ ranges: tuple[tuple[int, int], ...] | list[tuple[int, int]],
+ *,
+ workload_profile: ExecutionProfileName,
+ microbatch_size: int,
+ context_tokens: int,
+ optimization: str,
+) -> ShardPlan:
+ """Assignments, per-node fit checks, and the signed hash for a partition."""
+
+ performance_aware = all(node.performance is not None for node in pipeline_nodes)
assignments: list[PipelineAssignment] = []
for node, (start, end) in zip(pipeline_nodes, ranges):
layer_weight_bytes = sum(model.layer_weight_bytes[start:end])
@@ -1511,7 +1677,7 @@ def plan_unequal_pipeline(
hash_payload = {
"model": model.to_dict(),
"context_tokens": context_tokens,
- "optimization": "performance" if performance_aware else "memory",
+ "optimization": optimization,
"workload_profile": workload_profile,
"microbatch_size": microbatch_size,
"performance_profiles": [
@@ -1529,9 +1695,7 @@ def plan_unequal_pipeline(
"reserve_bytes": item.reserve_bytes,
"manual_memory_limit": item.manual_memory_limit,
"target_weight_bytes": next(
- node.target_weight_bytes
- for node in nodes
- if node.rank == item.rank
+ node.target_weight_bytes for node in nodes if node.rank == item.rank
),
# Part of the plan's identity: the same layers on the same Mac
# mean a different deployment depending on whether someone is
@@ -1552,7 +1716,7 @@ def plan_unequal_pipeline(
model=model,
assignments=tuple(assignments),
plan_hash=plan_hash,
- optimization="performance" if performance_aware else "memory",
+ optimization=optimization,
workload_profile=workload_profile,
performance_profiles=tuple(
node.performance
@@ -1697,9 +1861,7 @@ def _max_context_for_stage(
"not known" rather than "unlimited".
"""
- per_token = _kv_bytes_per_token_for_stage(
- model, layer_count, tensor_parallel_size
- )
+ per_token = _kv_bytes_per_token_for_stage(model, layer_count, tensor_parallel_size)
if per_token <= 0:
return 0
spare = node.usable_bytes - weight_bytes
@@ -1853,7 +2015,11 @@ def plan_hybrid(
# them, split within each layer by shard_linear.
ordered_nodes = sorted(nodes, key=lambda item: item.rank)
stage_groups = [
- tuple(ordered_nodes[stage * tensor_parallel_size : (stage + 1) * tensor_parallel_size])
+ tuple(
+ ordered_nodes[
+ stage * tensor_parallel_size : (stage + 1) * tensor_parallel_size
+ ]
+ )
for stage in range(pipeline_stages)
]
@@ -1972,10 +2138,13 @@ def plan_hybrid(
assignments.sort(key=lambda a: a.rank)
# Build performance profiles if available
- profiles = tuple(
- node.performance for node in ordered_nodes
- if node.performance is not None
- ) if performance_aware else ()
+ profiles = (
+ tuple(
+ node.performance for node in ordered_nodes if node.performance is not None
+ )
+ if performance_aware
+ else ()
+ )
# Compute plan hash covering all assignment fields
hash_payload = {
diff --git a/omlx/cluster/registry.py b/omlx/cluster/registry.py
index 64fe34ee98..33f6fec496 100644
--- a/omlx/cluster/registry.py
+++ b/omlx/cluster/registry.py
@@ -13,6 +13,11 @@
from .deployment import ClusterDeployment
+# Version 2 persists per-node model paths (``path_map`` on each deployment).
+# Version 1 files are migrated in memory on load and rewritten atomically.
+REGISTRY_SCHEMA_VERSION = 2
+_SUPPORTED_REGISTRY_SCHEMAS = (1, REGISTRY_SCHEMA_VERSION)
+
def _model_key(model: str) -> str:
path = Path(model).expanduser()
@@ -30,6 +35,8 @@ def __init__(self, base_path: Path) -> None:
self._lock = threading.RLock()
self._deployments: dict[str, ClusterDeployment] = {}
self.load_error: str | None = None
+ #: Set when an on-disk legacy schema was upgraded on load.
+ self.migrated_from: int | None = None
try:
self._load()
except ValueError as exc:
@@ -49,7 +56,9 @@ def _load(self) -> None:
raise ValueError(
f"could not read cluster deployment registry: {exc}"
) from exc
- if not isinstance(payload, dict) or payload.get("schema_version") != 1:
+ if not isinstance(payload, dict) or payload.get("schema_version") not in (
+ _SUPPORTED_REGISTRY_SCHEMAS
+ ):
raise ValueError("unsupported cluster deployment registry schema")
raw_deployments = payload.get("deployments")
if not isinstance(raw_deployments, list):
@@ -58,16 +67,23 @@ def _load(self) -> None:
ClusterDeployment.from_dict(item) for item in raw_deployments
]
self._deployments = {
- _model_key(deployment.model): deployment
- for deployment in deployments
+ _model_key(deployment.model): deployment for deployment in deployments
}
if len(self._deployments) != len(deployments):
raise ValueError("cluster deployment registry has duplicate models")
+ if payload.get("schema_version") != REGISTRY_SCHEMA_VERSION:
+ # Legacy files hold no per-node paths; every deployment decoded
+ # above with an empty path_map, which is the exact behavior the
+ # file described. Persist the upgrade so the migration happens
+ # once, but never let an unwritable file block server startup.
+ self.migrated_from = int(payload.get("schema_version", 1))
+ with suppress(OSError):
+ self._save()
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
payload = {
- "schema_version": 1,
+ "schema_version": REGISTRY_SCHEMA_VERSION,
"deployments": [
deployment.to_dict()
for _, deployment in sorted(self._deployments.items())
@@ -94,8 +110,7 @@ def _save(self) -> None:
def list(self) -> tuple[ClusterDeployment, ...]:
with self._lock:
return tuple(
- deployment
- for _, deployment in sorted(self._deployments.items())
+ deployment for _, deployment in sorted(self._deployments.items())
)
def get_for_model(self, model: str) -> ClusterDeployment | None:
@@ -154,9 +169,10 @@ def remove(self, deployment_id: str) -> bool:
def to_dict(self) -> dict[str, Any]:
return {
- "schema_version": 1,
+ "schema_version": REGISTRY_SCHEMA_VERSION,
"deployments": [deployment.to_dict() for deployment in self.list()],
"load_error": self.load_error,
+ "migrated_from": self.migrated_from,
}
@@ -176,3 +192,419 @@ def get_cluster_registry() -> ClusterRegistry:
if _configured_registry is None:
raise RuntimeError("cluster registry is not configured")
return _configured_registry
+
+
+# ---------------------------------------------------------------------------
+# Cluster v2: trusted device inventory (paired nodes) + discovered device cache
+# ---------------------------------------------------------------------------
+
+import time # noqa: E402
+
+
+def default_devices_path() -> Path:
+ """Default on-disk location, honoring the OMLX_BASE_PATH override."""
+
+ env_value = os.environ.get("OMLX_BASE_PATH")
+ base = Path(env_value).expanduser() if env_value else Path.home() / ".omlx"
+ return base / "cluster" / "devices.json"
+
+
+class DeviceRegistry:
+ """Inventory of cluster devices.
+
+ *Paired* devices are trusted and persisted atomically (mode 0600) to
+ ``devices.json`` (schema_version 1). *Discovered-but-unpaired* devices
+ are kept in memory only — an untrusted announcer must never gain a
+ persisted foothold merely by showing up on the LAN.
+
+ The merge API is consumed by both discovery (continuous upserts of
+ announced metadata) and pairing (marking a node trusted). Merge never
+ downgrades a paired device back to discovered, and dedupes on
+ ``node_id``.
+ """
+
+ def __init__(self, path: Path | str | None = None) -> None:
+ self.path = Path(path) if path is not None else default_devices_path()
+ self._lock = threading.RLock()
+ self._paired: dict[str, dict[str, Any]] = {}
+ self._discovered: dict[str, dict[str, Any]] = {}
+ self.load_error: str | None = None
+ try:
+ self._load()
+ except ValueError as exc:
+ # Mirror ClusterRegistry: a corrupt optional file must never
+ # prevent the server from starting. Fail closed, trust nobody.
+ self._paired = {}
+ self.load_error = str(exc)
+
+ def _load(self) -> None:
+ with self._lock:
+ if not self.path.exists():
+ self._paired = {}
+ return
+ try:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ raise ValueError(
+ f"could not read cluster device registry: {exc}"
+ ) from exc
+ if not isinstance(payload, dict) or payload.get("schema_version") != 1:
+ raise ValueError("unsupported cluster device registry schema")
+ raw_devices = payload.get("devices")
+ if not isinstance(raw_devices, list):
+ raise ValueError("cluster device registry is malformed")
+ devices: dict[str, dict[str, Any]] = {}
+ for item in raw_devices:
+ device = self._validate_paired(item)
+ devices[device["node_id"]] = device
+ if len(devices) != len(raw_devices):
+ raise ValueError("cluster device registry has duplicate node_ids")
+ self._paired = devices
+
+ @staticmethod
+ def _validate_paired(item: Any) -> dict[str, Any]:
+ if not isinstance(item, dict):
+ raise ValueError("cluster device entry is malformed")
+ node_id = item.get("node_id")
+ friendly_name = item.get("friendly_name")
+ paired_at = item.get("paired_at")
+ if not isinstance(node_id, str) or not node_id:
+ raise ValueError("cluster device entry is missing a node_id")
+ if not isinstance(friendly_name, str) or not friendly_name:
+ raise ValueError("cluster device entry is missing a friendly_name")
+ if not isinstance(paired_at, (int, float)):
+ raise ValueError("cluster device entry is missing paired_at")
+ caps = item.get("caps")
+ last_addrs = item.get("last_addrs")
+ device = {
+ "node_id": node_id,
+ "friendly_name": friendly_name,
+ "caps": dict(caps) if isinstance(caps, dict) else {},
+ "paired_at": float(paired_at),
+ "last_addrs": [str(a) for a in last_addrs if isinstance(a, str)][:16]
+ if isinstance(last_addrs, list)
+ else [],
+ }
+ http_port = item.get("http_port")
+ if http_port is not None:
+ if (
+ not isinstance(http_port, int)
+ or isinstance(http_port, bool)
+ or not 1 <= http_port <= 65535
+ ):
+ raise ValueError("cluster device entry has an invalid HTTP port")
+ device["http_port"] = http_port
+ return device
+
+ def _save(self) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ payload = {
+ "schema_version": 1,
+ "devices": [self._paired[key] for key in sorted(self._paired)],
+ }
+ descriptor, temporary = tempfile.mkstemp(
+ prefix=".devices.", suffix=".tmp", dir=self.path.parent
+ )
+ try:
+ os.fchmod(descriptor, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ json.dump(payload, stream, indent=2, sort_keys=True)
+ stream.write("\n")
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, self.path)
+ os.chmod(self.path, 0o600)
+ finally:
+ with suppress(FileNotFoundError):
+ os.unlink(temporary)
+
+ # -- merge API (discovery + pairing) ------------------------------------
+
+ @staticmethod
+ def _merge_caps(
+ existing: dict[str, Any], incoming: dict[str, Any]
+ ) -> dict[str, Any]:
+ """Field-wise non-downgrading caps merge.
+
+ A discovery HELLO carries a structurally complete but value-empty
+ caps dict (``{"chip": "", "ram_gb": 0.0, ...}``); a truthiness check
+ would let it clobber the real capabilities exchanged at pairing.
+ Only real values win: non-empty chip, non-zero ram_gb, the union of
+ backends, and sticky-true fabric flags.
+ """
+
+ merged = dict(existing)
+ if incoming.get("chip"):
+ merged["chip"] = incoming["chip"]
+ if incoming.get("ram_gb"):
+ merged["ram_gb"] = incoming["ram_gb"]
+ backends = incoming.get("backends")
+ if backends:
+ merged["backends"] = sorted(
+ set(existing.get("backends") or []) | set(backends)
+ )
+ for flag in ("thunderbolt", "jaccl"):
+ # Sticky-true, but never introduce the key out of nowhere —
+ # records that never had fabric flags keep their shape.
+ if existing.get(flag) or incoming.get(flag) or flag in existing:
+ merged[flag] = bool(existing.get(flag)) or bool(incoming.get(flag))
+ for key, value in incoming.items():
+ if key not in merged and value:
+ merged[key] = value
+ return merged
+
+ @staticmethod
+ def _merge_addrs(existing: list[str], incoming: list[str]) -> list[str]:
+ """Union, preserving order — a later sparse announcement must not
+ drop routable addresses the pairing recorded."""
+
+ merged = list(existing)
+ for ip in incoming:
+ if ip not in merged:
+ merged.append(ip)
+ return merged[:16]
+
+ def merge(
+ self,
+ device: Any,
+ *,
+ paired_at: float | None = None,
+ ) -> dict[str, Any]:
+ """Upsert announced device metadata, keyed on ``node_id``.
+
+ Accepts any object/dict with ``node_id`` and optional
+ ``friendly_name``/``caps``/``addrs`` or ``last_addrs`` (a discovery
+ ``PeerRecord`` works as-is). Updates to an already-paired device are
+ persisted; updates to an unpaired device stay memory-only. Merges
+ never downgrade: empty announced fields cannot erase known ones.
+ """
+
+ record = self._coerce(device)
+ node_id = record["node_id"]
+ with self._lock:
+ if node_id in self._paired:
+ merged = self._paired[node_id]
+ if record.get("friendly_name"):
+ merged["friendly_name"] = record["friendly_name"]
+ if record.get("caps"):
+ merged["caps"] = self._merge_caps(
+ dict(merged.get("caps") or {}), record["caps"]
+ )
+ if record.get("last_addrs"):
+ merged["last_addrs"] = self._merge_addrs(
+ list(merged.get("last_addrs") or []), record["last_addrs"]
+ )
+ if record.get("http_port"):
+ merged["http_port"] = record["http_port"]
+ if paired_at is not None:
+ merged["paired_at"] = float(paired_at)
+ previous = dict(self._paired)
+ try:
+ self._save()
+ except Exception:
+ self._paired = previous
+ raise
+ self.load_error = None
+ return dict(merged)
+ merged = self._discovered.get(node_id, {"node_id": node_id})
+ if record.get("friendly_name"):
+ merged["friendly_name"] = record["friendly_name"]
+ if record.get("caps"):
+ merged["caps"] = self._merge_caps(
+ dict(merged.get("caps") or {}), record["caps"]
+ )
+ if record.get("last_addrs"):
+ merged["last_addrs"] = self._merge_addrs(
+ list(merged.get("last_addrs") or []), record["last_addrs"]
+ )
+ if record.get("http_port"):
+ merged["http_port"] = record["http_port"]
+ self._discovered[node_id] = merged
+ return dict(merged)
+
+ @staticmethod
+ def _coerce(device: Any) -> dict[str, Any]:
+ if isinstance(device, dict):
+ record = dict(device)
+ else:
+ record = {
+ "node_id": getattr(device, "node_id", None),
+ "friendly_name": getattr(device, "friendly_name", None),
+ "caps": getattr(device, "caps", None),
+ "http_port": getattr(device, "http_port", None),
+ }
+ addrs = getattr(device, "addrs", None)
+ if addrs is not None:
+ record["last_addrs"] = [
+ a.get("ip") if isinstance(a, dict) else getattr(a, "ip", None)
+ for a in addrs
+ ]
+ node_id = record.get("node_id")
+ if not isinstance(node_id, str) or not node_id:
+ raise ValueError("device record is missing a node_id")
+ if "last_addrs" not in record and isinstance(record.get("addrs"), list):
+ record["last_addrs"] = [
+ a.get("ip") if isinstance(a, dict) else a for a in record["addrs"]
+ ]
+ caps = record.get("caps")
+ if caps is not None and not isinstance(caps, dict):
+ caps = caps.to_dict() if hasattr(caps, "to_dict") else {}
+ normalized: dict[str, Any] = {"node_id": node_id}
+ if isinstance(record.get("friendly_name"), str):
+ normalized["friendly_name"] = record["friendly_name"]
+ if isinstance(caps, dict):
+ normalized["caps"] = dict(caps)
+ addrs = record.get("last_addrs")
+ if isinstance(addrs, list):
+ normalized["last_addrs"] = [str(a) for a in addrs if isinstance(a, str)][
+ :16
+ ]
+ http_port = record.get("http_port")
+ if http_port is not None and http_port != 0 and http_port != "":
+ if (
+ not isinstance(http_port, int)
+ or isinstance(http_port, bool)
+ or not 1 <= http_port <= 65535
+ ):
+ raise ValueError("device record has an invalid HTTP port")
+ normalized["http_port"] = http_port
+ return normalized
+
+ def mark_paired(
+ self,
+ node_id: str,
+ *,
+ friendly_name: str | None = None,
+ caps: dict[str, Any] | None = None,
+ addrs: list[str] | None = None,
+ http_port: int | None = None,
+ paired_at: float | None = None,
+ ) -> dict[str, Any]:
+ """Promote a device to trusted/paired and persist it."""
+
+ with self._lock:
+ existing = self._paired.get(node_id) or self._discovered.get(node_id, {})
+ if http_port is not None and (
+ not isinstance(http_port, int)
+ or isinstance(http_port, bool)
+ or not 1 <= http_port <= 65535
+ ):
+ raise ValueError("paired device HTTP port is invalid")
+ device = {
+ "node_id": node_id,
+ "friendly_name": friendly_name
+ or existing.get("friendly_name")
+ or node_id,
+ "caps": dict(caps)
+ if caps is not None
+ else dict(existing.get("caps") or {}),
+ "paired_at": float(paired_at if paired_at is not None else time.time()),
+ "last_addrs": list(addrs)
+ if addrs is not None
+ else list(existing.get("last_addrs") or []),
+ }
+ effective_port = http_port or existing.get("http_port")
+ if effective_port:
+ device["http_port"] = int(effective_port)
+ previous = dict(self._paired)
+ self._paired[node_id] = device
+ self._discovered.pop(node_id, None)
+ try:
+ self._save()
+ except Exception:
+ self._paired = previous
+ raise
+ self.load_error = None
+ return dict(device)
+
+ def unpair(self, node_id: str) -> bool:
+ """Revoke trust. The device drops back to memory-only if re-seen."""
+
+ with self._lock:
+ if node_id not in self._paired:
+ return False
+ previous = dict(self._paired)
+ device = self._paired.pop(node_id)
+ try:
+ self._save()
+ except Exception:
+ self._paired = previous
+ raise
+ # Keep a memory-only discovered shell so the UI can still show
+ # the now-untrusted device if it is still announcing.
+ shell = {
+ "node_id": node_id,
+ "friendly_name": device["friendly_name"],
+ "caps": device["caps"],
+ "last_addrs": device["last_addrs"],
+ }
+ if device.get("http_port"):
+ shell["http_port"] = device["http_port"]
+ self._discovered.setdefault(
+ node_id,
+ shell,
+ )
+ return True
+
+ # -- reads ---------------------------------------------------------------
+
+ def paired(self) -> list[dict[str, Any]]:
+ with self._lock:
+ return [dict(self._paired[key]) for key in sorted(self._paired)]
+
+ def discovered(self) -> list[dict[str, Any]]:
+ """Unpaired devices (memory-only), excluding paired node_ids."""
+
+ with self._lock:
+ return [
+ dict(self._discovered[key])
+ for key in sorted(self._discovered)
+ if key not in self._paired
+ ]
+
+ def get(self, node_id: str) -> dict[str, Any] | None:
+ with self._lock:
+ if node_id in self._paired:
+ return dict(self._paired[node_id])
+ found = self._discovered.get(node_id)
+ return dict(found) if found is not None else None
+
+ def is_paired(self, node_id: str) -> bool:
+ with self._lock:
+ return node_id in self._paired
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "schema_version": 1,
+ "paired": self.paired(),
+ "discovered": self.discovered(),
+ "load_error": self.load_error,
+ }
+
+
+_device_registry_lock = threading.Lock()
+_configured_device_registry: DeviceRegistry | None = None
+
+
+def configure_device_registry(
+ path: Path | str | None = None,
+) -> DeviceRegistry:
+ global _configured_device_registry
+ with _device_registry_lock:
+ _configured_device_registry = DeviceRegistry(path)
+ return _configured_device_registry
+
+
+def get_device_registry() -> DeviceRegistry:
+ with _device_registry_lock:
+ if _configured_device_registry is None:
+ raise RuntimeError("cluster device registry is not configured")
+ return _configured_device_registry
+
+
+def reset_configured_device_registry() -> None:
+ """Test hook: drop the process-wide device registry."""
+
+ global _configured_device_registry
+ with _device_registry_lock:
+ _configured_device_registry = None
diff --git a/omlx/cluster/replan.py b/omlx/cluster/replan.py
new file mode 100644
index 0000000000..bd93d8efd6
--- /dev/null
+++ b/omlx/cluster/replan.py
@@ -0,0 +1,122 @@
+# SPDX-License-Identifier: Apache-2.0
+"""One-action cluster re-plan: deactivate → re-plan → reload.
+
+Today a membership or budget change is a manual four-step dance: deactivate
+the deployment, rebuild a plan, approve it, then reload the model. This module
+is the pure/data half of collapsing that into a single ``POST
+/admin/api/cluster/replan`` call (the route handler in
+``omlx/cluster/routes.py`` owns the async orchestration):
+
+- :func:`nodes_from_deployment` / :func:`hosts_from_deployment` derive the
+ plan inputs for the *next* plan from the *current* approved deployment, so
+ a replan with no explicit overrides re-plans the same cluster the operator
+ already trusts. A pairing/membership inventory (the v2 discovery/pairing
+ modules) can later supply overrides for added or removed nodes; until then
+ the explicit ``nodes``/``hosts`` request fields are how membership changes
+ are expressed.
+- :func:`summarize_deployment` produces the compact, secret-free description
+ of what a replan replaced.
+
+Derivation caveats (documented contract, not bugs):
+
+- ``max_weight_bytes`` / ``target_weight_bytes`` are operator preferences that
+ live on the plan *request*, not on the signed assignment, so a derived
+ replan cannot recover them and resets both to "automatic". Operators moving
+ the split control must pass explicit ``nodes``.
+- KV reservations and per-rank context limits are recomputed by the planner
+ from ``target_context_tokens``, never copied forward.
+- Signed performance profiles *are* copied forward. Dropping them silently
+ turns a heterogeneous tensor deployment back into an equal split on every
+ replan, even when the previous activation already measured both ranks.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from .deployment import ClusterDeployment
+
+
+def nodes_from_deployment(deployment: ClusterDeployment) -> list[dict[str, Any]]:
+ """Rank-ordered node-budget payloads equivalent to this deployment.
+
+ The returned dicts match ``ClusterPlanNodeRequest`` fields. Split-control
+ preferences (``max_weight_bytes`` / ``target_weight_bytes``) are not
+ recoverable from a signed plan and are reset to automatic.
+ """
+
+ profiles = {
+ (profile.rank, profile.node_id): profile
+ for profile in deployment.performance_profiles
+ }
+ nodes: list[dict[str, Any]] = []
+ for assignment in sorted(deployment.assignments, key=lambda item: item.rank):
+ payload: dict[str, Any] = {
+ "node_id": assignment.node_id,
+ "capacity_bytes": assignment.capacity_bytes,
+ "reserve_bytes": assignment.reserve_bytes,
+ "manual_memory_limit": assignment.manual_memory_limit,
+ "role": assignment.role or "headless",
+ "memory_guard_tier": assignment.memory_guard_tier,
+ }
+ profile = profiles.get((assignment.rank, assignment.node_id))
+ if profile is not None:
+ payload["performance"] = profile.to_dict()
+ nodes.append(payload)
+ return nodes
+
+
+def hosts_from_deployment(deployment: ClusterDeployment) -> list[dict[str, Any]]:
+ """Rank-ordered host payloads equivalent to this deployment's hostfile."""
+
+ hosts: list[dict[str, Any]] = []
+ for host in deployment.hosts:
+ payload: dict[str, Any] = {
+ "node_id": host.node_id,
+ "ssh": host.ssh,
+ "ips": list(host.ips),
+ "rdma": [
+ list(path) if isinstance(path, tuple) else path for path in host.rdma
+ ],
+ }
+ if host.python_executable:
+ payload["python_executable"] = host.python_executable
+ hosts.append(payload)
+ return hosts
+
+
+def summarize_deployment(deployment: ClusterDeployment) -> dict[str, Any]:
+ """What a replan is replacing, in the terms the plan view displays."""
+
+ return {
+ "deployment_id": deployment.deployment_id,
+ "model": deployment.model,
+ "backend": deployment.backend,
+ "world_size": deployment.world_size,
+ "plan_hash": deployment.plan_hash,
+ "target_context_tokens": deployment.target_context_tokens,
+ "assignments": [
+ {
+ "rank": assignment.rank,
+ "node_id": assignment.node_id,
+ "start_layer": assignment.start_layer,
+ "end_layer": assignment.end_layer,
+ "planned_weight_bytes": assignment.planned_weight_bytes,
+ "kv_cache_bytes": assignment.kv_cache_bytes,
+ }
+ for assignment in sorted(deployment.assignments, key=lambda item: item.rank)
+ ],
+ }
+
+
+def placement_view(deployment: ClusterDeployment) -> dict[str, Any]:
+ """The ``plan``-shaped assignment list used for placement diffs.
+
+ ``_placement_rows`` in the routes module reads ``plan["assignments"]``;
+ this rebuilds that shape from a persisted deployment so a replan can diff
+ the running placement against the proposed one with the exact same code.
+ """
+
+ return {
+ "assignments": [assignment.to_dict() for assignment in deployment.assignments]
+ }
diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py
index 06e59e97b1..2693e20dcd 100644
--- a/omlx/cluster/routes.py
+++ b/omlx/cluster/routes.py
@@ -43,7 +43,12 @@
run_local_collective_smoke,
run_local_pipeline_smoke,
)
-from .deployment import ClusterDeployment, ClusterHost, validate_ssh_target
+from .deployment import (
+ ClusterDeployment,
+ ClusterHost,
+ validate_model_path_map,
+ validate_ssh_target,
+)
from .discovery import (
discover_all_peers,
record_peer_transports,
@@ -84,12 +89,20 @@
ShardPlan,
complete_model_layout,
plan_hybrid,
+ plan_proportional_pipeline,
plan_unequal_pipeline,
remote_model_layout,
synthetic_model_layout,
)
from .probe import collect_cluster_status
-from .registry import get_cluster_registry
+from .registry import get_cluster_registry, get_device_registry
+from .identity import get_node_identity
+from .replan import (
+ hosts_from_deployment,
+ nodes_from_deployment,
+ placement_view,
+ summarize_deployment,
+)
from .runtime import read_runtime_markers
from .staging import (
DEFAULT_REMOTE_PYTHON,
@@ -421,9 +434,15 @@ class ClusterPlanRequest(BaseModel):
layer_count: int = Field(default=80, gt=0, le=2048)
nodes: list[ClusterPlanNodeRequest] = Field(min_length=1, max_length=64)
execution_profile: Literal["interactive", "balanced", "throughput"] = "balanced"
+ # "balanced" runs the bottleneck-minimizing DP planner; "proportional"
+ # splits layers ∝ usable RAM with largest-remainder rounding (exo-style).
+ allocation: Literal["balanced", "proportional"] = "balanced"
pipeline_microbatch_size: int | None = Field(default=None, gt=0, le=256)
tensor_parallel_size: int = Field(default=1, ge=1, le=64)
target_context_tokens: int = Field(default=8192, ge=1, le=1_048_576)
+ # Cluster v2: optional node_id → absolute model path on that node. Empty
+ # keeps the legacy same-absolute-path-on-every-node behavior.
+ path_map: dict[str, str] | None = Field(default=None, max_length=64)
class ClusterHostRequest(BaseModel):
@@ -464,6 +483,7 @@ class ClusterDeploymentRequest(BaseModel):
hosts: list[ClusterHostRequest] = Field(min_length=2, max_length=64)
preflight: Literal[True] = True
execution_profile: Literal["interactive", "balanced", "throughput"] = "balanced"
+ allocation: Literal["balanced", "proportional"] = "balanced"
auto_tune: bool = True
sampling_rank_only: bool = True
async_overlap: bool = True
@@ -479,6 +499,9 @@ class ClusterDeploymentRequest(BaseModel):
# one dropped the role and the split cap without saying so. Activation is a
# GUI workflow: callers must preview and name the placement they approve.
approved_placement: str = Field(min_length=16, max_length=64)
+ # Cluster v2: node_id → absolute model path on that node. Nodes not listed
+ # load ``model_path`` — the pre-v2 shared-path behavior.
+ path_map: dict[str, str] | None = Field(default=None, max_length=64)
class ClusterPeerProbeRequest(BaseModel):
@@ -699,7 +722,14 @@ def _placement_rows(plan: dict[str, Any]) -> list[dict[str, Any]]:
def _placement_signature(plan: dict[str, Any]) -> str:
"""Identity of the plan a user approves, stable across cosmetic re-planning."""
- payload = json.dumps(_placement_rows(plan), sort_keys=True, separators=(",", ":"))
+ rows: Any = _placement_rows(plan)
+ # A per-node path override changes what actually runs, so it is part of
+ # what the user approves. Folded in only when present, keeping signatures
+ # byte-identical to the legacy format for shared-path deployments.
+ path_map = plan.get("path_map")
+ if path_map:
+ rows = {"rows": rows, "path_map": path_map}
+ payload = json.dumps(rows, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(payload.encode()).hexdigest()[:16]
@@ -800,9 +830,18 @@ def _create_cluster_plan(request: ClusterPlanRequest):
f"across {len(nodes)} Macs."
)
raise PlanningError(detail)
+ path_map = validate_model_path_map(
+ request.path_map,
+ tuple(node.node_id.strip() for node in request.nodes),
+ )
defaults = execution_profile(request.execution_profile)
if request.tensor_parallel_size > 1:
- return plan_hybrid(
+ if request.allocation != "balanced":
+ raise PlanningError(
+ "RAM-proportional allocation is a pipeline-only rule; tensor "
+ "parallelism uses the hybrid planner (allocation='balanced')"
+ )
+ plan = plan_hybrid(
model,
nodes,
tensor_parallel_size=request.tensor_parallel_size,
@@ -812,15 +851,29 @@ def _create_cluster_plan(request: ClusterPlanRequest):
),
context_tokens=request.target_context_tokens,
)
- return plan_unequal_pipeline(
- model,
- nodes,
- workload_profile=request.execution_profile,
- microbatch_size=(
- request.pipeline_microbatch_size or defaults.pipeline_microbatch_size
- ),
- context_tokens=request.target_context_tokens,
- )
+ elif request.allocation == "proportional":
+ plan = plan_proportional_pipeline(
+ model,
+ nodes,
+ workload_profile=request.execution_profile,
+ microbatch_size=(
+ request.pipeline_microbatch_size or defaults.pipeline_microbatch_size
+ ),
+ context_tokens=request.target_context_tokens,
+ )
+ else:
+ plan = plan_unequal_pipeline(
+ model,
+ nodes,
+ workload_profile=request.execution_profile,
+ microbatch_size=(
+ request.pipeline_microbatch_size or defaults.pipeline_microbatch_size
+ ),
+ context_tokens=request.target_context_tokens,
+ )
+ if path_map:
+ plan = replace(plan, path_map=path_map)
+ return plan
class ClusterAutoconfigureRequest(BaseModel):
@@ -1585,19 +1638,26 @@ def _run_staging_job(
portable_model_path = home_relative_model_path(deployment.model)
failed_nodes: list[str] = []
for host, assignment in zip(deployment.hosts, assignments):
+ # Cluster v2: files land at the node's path_map entry when one
+ # exists. Otherwise preserve the cross-account behavior by
+ # resolving the portable model path in the remote Mac's home.
+ explicit_destination = deployment.path_map.get(host.node_id)
if _local_ssh_target(host.ssh):
- destination_dir = str(model_path)
+ destination_dir = explicit_destination or str(model_path)
+ destination_path = Path(destination_dir)
present = (
- {
- path.name: path.stat().st_size
- for path in model_path.iterdir()
- if path.is_file()
- }
- if model_path.is_dir()
+ {
+ path.name: path.stat().st_size
+ for path in destination_path.iterdir()
+ if path.is_file()
+ }
+ if destination_path.is_dir()
else {}
)
else:
- destination_dir = remote_model_dir(host.ssh, portable_model_path)
+ destination_dir = explicit_destination or remote_model_dir(
+ host.ssh, portable_model_path
+ )
present = remote_file_sizes(host.ssh, destination_dir)
plan = plan_staging(
model_path,
@@ -1967,7 +2027,12 @@ async def cluster_discover():
@router.post("/pairing-token")
async def cluster_pairing_token(request: ClusterPairingTokenRequest):
- """Generate a pairing token for QR code exchange."""
+ """Generate a pairing token for QR code exchange.
+
+ Advanced (legacy): step 1 of the 3-step copy-paste relay. The cluster v2
+ wizard uses POST /api/cluster/pair/request + /pair/approve instead; this
+ endpoint is kept working unchanged for the legacy flow.
+ """
from .discovery import generate_pairing_token
@@ -1982,7 +2047,11 @@ async def cluster_pairing_token(request: ClusterPairingTokenRequest):
async def cluster_verify_pairing_token(
request: ClusterPairingTokenVerificationRequest,
):
- """Verify a pairing token received via QR code scan."""
+ """Verify a pairing token received via QR code scan.
+
+ Advanced (legacy): part of the 3-step copy-paste relay; superseded by the
+ cluster v2 code-based pairing flow but kept working unchanged.
+ """
return {
"valid": verify_pairing_token(
@@ -2232,7 +2301,12 @@ async def cluster_generate_ssh_key(
async def cluster_generate_key_exchange_token(
request: ClusterKeyExchangeTokenRequest,
):
- """Generate a key exchange token for pairing with a peer."""
+ """Generate a key exchange token for pairing with a peer.
+
+ Advanced (legacy): step 3 of the copy-paste relay. Cluster v2 pairing
+ (POST /api/cluster/pair/approve) drives the same SSH TOFU primitives
+ programmatically; this endpoint remains for the manual flow.
+ """
from .ssh_keys import generate_key_exchange_for_peer
@@ -2252,7 +2326,11 @@ async def cluster_generate_key_exchange_token(
@router.post("/ssh-key/exchange")
async def cluster_exchange_keys(request: ClusterKeyExchangeRequest):
- """Exchange SSH keys with a peer using their exchange token."""
+ """Exchange SSH keys with a peer using their exchange token.
+
+ Advanced (legacy): step 3 of the copy-paste relay; kept working unchanged
+ alongside the cluster v2 code-based pairing flow.
+ """
from .ssh_keys import exchange_keys_with_peer
@@ -2627,9 +2705,11 @@ def _create_deployment(
model_source_python=request.model_source_python,
nodes=request.nodes,
execution_profile=request.execution_profile,
+ allocation=request.allocation,
pipeline_microbatch_size=requested_microbatch,
tensor_parallel_size=request.tensor_parallel_size,
target_context_tokens=request.target_context_tokens,
+ path_map=request.path_map,
)
plan = _create_cluster_plan(plan_request)
execution = _execution_for_request(
@@ -2673,6 +2753,7 @@ def _create_deployment(
performance_profiles=_request_performance_profiles(request.nodes),
tensor_parallel_size=request.tensor_parallel_size,
target_context_tokens=request.target_context_tokens,
+ path_map=validate_model_path_map(request.path_map, tuple(host_ids)),
)
return deployment, plan.to_dict()
@@ -2990,11 +3071,45 @@ async def read_host(
}
+def _requested_links_fast(nodes: list[ClusterPlanNodeRequest]) -> bool:
+ """Whether every requested peer sits on a fast (JACCL/Thunderbolt) link.
+
+ The catalogue's default tie-break prefers pipeline at equal width because
+ it survives slow links; when the paired registry shows every requested
+ peer is reachable over JACCL/Thunderbolt RDMA, tensor parallelism is the
+ better recommendation — it splits per-token compute across the group.
+ The coordinator's own row is not in the paired registry, so only
+ non-self node_ids are consulted. Unknown or unpaired peers fail closed:
+ pipeline stays the recommendation where tensor would crawl.
+ """
+
+ if len(nodes) < 2:
+ return False
+ try:
+ identity = get_node_identity()
+ registry = get_device_registry()
+ except RuntimeError:
+ return False
+ for node in nodes:
+ if node.node_id == identity.node_id:
+ continue
+ if not registry.is_paired(node.node_id):
+ return False
+ record = registry.get(node.node_id) or {}
+ caps = record.get("caps")
+ if not isinstance(caps, dict):
+ return False
+ if not (caps.get("jaccl") or caps.get("thunderbolt")):
+ return False
+ return True
+
+
def _catalogue_for_candidates(
candidates: list[ClusterCatalogueModelRequest],
nodes: list[NodeBudget],
*,
workload_profile: str,
+ prefer_tensor: bool = False,
) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for candidate in candidates:
@@ -3017,6 +3132,7 @@ def _catalogue_for_candidates(
model_id=candidate.id,
declared_context_tokens=candidate.model_context_length,
workload_profile=workload_profile,
+ prefer_tensor=prefer_tensor,
)
except (OSError, PlanningError, RuntimeError, ValueError) as exc:
fit = ModelFit(
@@ -3057,6 +3173,7 @@ async def cluster_catalogue(request: ClusterCatalogueRequest) -> dict[str, Any]:
"""
nodes = _node_budgets(request.nodes)
+ prefer_tensor = _requested_links_fast(request.nodes)
paths = [Path(item) for item in request.model_paths]
if request.model_dir:
@@ -3078,6 +3195,7 @@ async def cluster_catalogue(request: ClusterCatalogueRequest) -> dict[str, Any]:
request.models,
nodes,
workload_profile=request.execution_profile,
+ prefer_tensor=prefer_tensor,
)
else:
catalogue = await asyncio.to_thread(
@@ -3085,6 +3203,7 @@ async def cluster_catalogue(request: ClusterCatalogueRequest) -> dict[str, Any]:
paths,
nodes,
workload_profile=request.execution_profile,
+ prefer_tensor=prefer_tensor,
)
model_rows = [fit.to_dict() for fit in catalogue]
runnable = [row for row in model_rows if row["fits"]]
@@ -3107,9 +3226,20 @@ async def cluster_deployments():
raise HTTPException(status_code=503, detail=str(exc)) from exc
-@router.post("/deployments")
-async def activate_cluster_deployment(request: ClusterDeploymentRequest):
- """Recompute, preflight, eagerly load, and prove one distributed model."""
+async def _activate_and_report(
+ request: ClusterDeploymentRequest,
+) -> dict[str, Any]:
+ """Recompute, preflight, eagerly load, and prove one distributed model.
+
+ This is the single activation pipeline behind both ``POST /deployments``
+ (explicit approval of a previewed plan) and the approve phase of
+ ``POST /replan`` (one-action deactivate → re-plan → reload). The
+ deactivate half of a replan is exactly what this pipeline already does:
+ ``pool.prepare_cluster_reload`` unloads the resident engine under the
+ pool lock — quiescence-gated, and for distributed engines the supervisor's
+ *verified* teardown is the memory barrier — before the registry swap and
+ the eager reload below.
+ """
plan_changes: dict[str, Any] = {
"changed": False,
@@ -3385,6 +3515,233 @@ async def activate_cluster_deployment(request: ClusterDeploymentRequest):
}
+@router.post("/deployments")
+async def activate_cluster_deployment(request: ClusterDeploymentRequest):
+ """Recompute, preflight, eagerly load, and prove one distributed model."""
+
+ return await _activate_and_report(request)
+
+
+class ClusterReplanRequest(BaseModel):
+ """One-action deactivate → re-plan → reload for a clustered model.
+
+ With no ``approved_placement`` this is a dry run: it renders the plan the
+ one-action call would launch, signed, with a diff against the running
+ placement. Posting that signature back performs the whole dance at once.
+
+ ``nodes``/``hosts``/``backend`` default to the current deployment's, so a
+ budget-only or context-only change needs no host details; a membership
+ change (a node joining or leaving the model) is expressed by posting the
+ new explicit ``nodes`` + ``hosts`` lists. ``path_map`` likewise defaults
+ to the current deployment's per-node paths so a replan does not silently
+ revert a heterogeneous-path cluster to same-path resolution.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ deployment_id: str | None = Field(default=None, max_length=128)
+ model_path: str | None = Field(default=None, max_length=4096)
+ model_source: str | None = Field(default=None, max_length=255)
+ model_source_python: str | None = Field(default=None, max_length=4096)
+ backend: Literal["ring", "jaccl", "jaccl-ring"] | None = None
+ nodes: list[ClusterPlanNodeRequest] | None = Field(
+ default=None, min_length=2, max_length=64
+ )
+ hosts: list[ClusterHostRequest] | None = Field(
+ default=None, min_length=2, max_length=64
+ )
+ execution_profile: Literal["interactive", "balanced", "throughput"] = (
+ "balanced"
+ )
+ auto_tune: bool = False
+ sampling_rank_only: bool = True
+ async_overlap: bool = True
+ cache_affinity: bool = True
+ max_kv_size: int | None = Field(default=None, gt=0)
+ ring_connections_per_ip: int | None = Field(default=None, ge=1, le=32)
+ tensor_parallel_size: int | None = Field(default=None, ge=1, le=64)
+ target_context_tokens: int | None = Field(
+ default=None, ge=1, le=1_048_576
+ )
+ path_map: dict[str, str] | None = Field(default=None, max_length=64)
+ approved_placement: str | None = Field(default=None, min_length=16, max_length=64)
+
+
+_REPLAN_STEPS = (
+ "deactivate (quiescence-gated unload with verified teardown)",
+ "re-plan (recomputed server-side and pinned by signature)",
+ "reload (eager distributed load with readiness canary)",
+)
+
+
+@router.post("/replan")
+async def replan_cluster_deployment(request: ClusterReplanRequest):
+ """Collapse deactivate → re-plan → reload into one action.
+
+ The engine-pool quiescence gate (``prepare_cluster_reload``) refuses to
+ interrupt in-flight requests, and the distributed supervisor's verified
+ teardown is the memory barrier between the old world and the new one: if
+ teardown cannot be proven, the old registry record stays and the error
+ says what survived.
+ """
+
+ try:
+ registry = get_cluster_registry()
+ except RuntimeError as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
+
+ current: ClusterDeployment | None = None
+ if request.deployment_id:
+ current = await asyncio.to_thread(registry.get, request.deployment_id)
+ if current is None:
+ raise HTTPException(
+ status_code=404, detail="cluster deployment not found"
+ )
+ elif request.model_path:
+ current = await asyncio.to_thread(
+ registry.get_for_model, request.model_path
+ )
+
+ if current is None and not (
+ request.model_path and request.nodes and request.hosts
+ ):
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ "replan needs an existing deployment (deployment_id or a "
+ "model_path with a registered deployment) or an explicit "
+ "model_path together with nodes and hosts"
+ ),
+ )
+
+ derived: dict[str, bool] = {
+ "nodes": False,
+ "hosts": False,
+ "backend": False,
+ "path_map": False,
+ }
+ nodes = request.nodes
+ if nodes is None:
+ if current is None:
+ raise HTTPException(status_code=400, detail="nodes are required")
+ nodes = [
+ ClusterPlanNodeRequest(**payload)
+ for payload in nodes_from_deployment(current)
+ ]
+ derived["nodes"] = True
+ hosts = request.hosts
+ if hosts is None:
+ if current is None:
+ raise HTTPException(status_code=400, detail="hosts are required")
+ hosts = [
+ ClusterHostRequest(**payload)
+ for payload in hosts_from_deployment(current)
+ ]
+ derived["hosts"] = True
+ backend = request.backend
+ if backend is None:
+ if current is None:
+ raise HTTPException(status_code=400, detail="backend is required")
+ backend = current.backend
+ derived["backend"] = True
+ path_map = request.path_map
+ if path_map is None and current is not None and current.path_map:
+ # Per-node paths are part of the deployment contract: a replan that
+ # dropped them would silently revert workers to the coordinator's
+ # shared path. Carry them forward unless the caller overrides.
+ path_map = dict(current.path_map)
+ derived["path_map"] = True
+ try:
+ _validate_cluster_hosts(hosts)
+ effective = ClusterDeploymentRequest(
+ deployment_id=request.deployment_id,
+ model_path=(request.model_path or (current.model if current else "")),
+ model_source=request.model_source,
+ model_source_python=request.model_source_python,
+ backend=backend,
+ nodes=nodes,
+ hosts=hosts,
+ execution_profile=request.execution_profile,
+ auto_tune=request.auto_tune,
+ sampling_rank_only=request.sampling_rank_only,
+ async_overlap=request.async_overlap,
+ cache_affinity=request.cache_affinity,
+ max_kv_size=request.max_kv_size,
+ ring_connections_per_ip=request.ring_connections_per_ip,
+ tensor_parallel_size=(
+ request.tensor_parallel_size
+ if request.tensor_parallel_size is not None
+ else current.tensor_parallel_size
+ if current is not None
+ else 1
+ ),
+ target_context_tokens=(
+ request.target_context_tokens
+ if request.target_context_tokens is not None
+ else current.target_context_tokens
+ if current is not None
+ else 8192
+ ),
+ path_map=path_map,
+ # Not consulted by planning; activation re-checks the real one
+ # below. Preview callers do not have a signature yet.
+ approved_placement=request.approved_placement or ("0" * 16),
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ try:
+ deployment, plan = await asyncio.to_thread(_create_deployment, effective)
+ except (OSError, PlanningError, ValueError) as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ signed_plan = _plan_with_signature(plan)
+ changes = (
+ _plan_changes(placement_view(current), plan)
+ if current is not None
+ else None
+ )
+
+ if request.approved_placement is None:
+ return {
+ "ok": True,
+ "mode": "preview",
+ "steps": list(_REPLAN_STEPS),
+ "derived": derived,
+ "current": (
+ summarize_deployment(current) if current is not None else None
+ ),
+ "changes": changes,
+ "deployment_id": deployment.deployment_id,
+ "backend": deployment.backend,
+ "plan": signed_plan,
+ }
+
+ if request.approved_placement.strip() != signed_plan["placement_signature"]:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "This is not the plan the replan preview showed — the budgets, "
+ "roles or layer split changed in between. Preview again and "
+ f"approve what it shows. As posted, this request would place: "
+ f"{_describe_placement(plan)}."
+ ),
+ )
+
+ result = await _activate_and_report(effective)
+ return result | {
+ "mode": "applied",
+ "replan": {
+ "steps": list(_REPLAN_STEPS),
+ "derived": derived,
+ "previous": (
+ summarize_deployment(current) if current is not None else None
+ ),
+ "changes": changes,
+ },
+ }
+
+
@router.delete("/deployments/{deployment_id}")
async def deactivate_cluster_deployment(deployment_id: str):
"""Stop the resident cluster, then disable future distributed loads."""
diff --git a/omlx/cluster/staging.py b/omlx/cluster/staging.py
index 4c4846c93f..2e76ca9470 100644
--- a/omlx/cluster/staging.py
+++ b/omlx/cluster/staging.py
@@ -162,9 +162,7 @@ def shards_for_stage(
wanted = set(range(start_layer, end_layer))
return tuple(
- shard
- for shard in shards
- if (shard.layers & wanted) or shard.has_shared_tensors
+ shard for shard in shards if (shard.layers & wanted) or shard.has_shared_tensors
)
@@ -212,6 +210,11 @@ def _model_identity_digest(model_path: str | Path) -> str:
return hasher.hexdigest()
+# Public name for the digest; the manifest endpoint and peer comparison in
+# ``modelsync.py`` share this exact identity definition with staging.
+model_identity_digest = _model_identity_digest
+
+
def _indexed_shards(model_path: str | Path) -> tuple[ShardInfo, ...] | None:
"""Read the full shard map from the index even on a partially staged rank."""
@@ -307,7 +310,9 @@ def validate_staged_model(
indexed = _indexed_shards(root)
shards = indexed if indexed is not None else index_shards(root)
required = shards_for_stage(shards, start_layer, end_layer)
- missing = tuple(shard.name for shard in required if not (root / shard.name).is_file())
+ missing = tuple(
+ shard.name for shard in required if not (root / shard.name).is_file()
+ )
corrupt: list[str] = []
for shard in required:
path = root / shard.name
@@ -347,10 +352,7 @@ def model_staging_inventory(model_path: str | Path) -> dict[str, Any]:
}
for shard in shards
],
- "sidecars": {
- name: (root / name).stat().st_size
- for name in sidecars
- },
+ "sidecars": {name: (root / name).stat().st_size for name in sidecars},
}
@@ -566,9 +568,7 @@ def stage_manifest(
for plan in plans:
present = present_by_node.get(plan.node_id, {})
missing_sidecars = tuple(
- name
- for name, size in sidecar_sizes.items()
- if present.get(name) != size
+ name for name, size in sidecar_sizes.items() if present.get(name) != size
)
missing_sidecar_bytes = sum(sidecar_sizes[name] for name in missing_sidecars)
total_missing_bytes += plan.missing_bytes + missing_sidecar_bytes
@@ -583,9 +583,7 @@ def stage_manifest(
)
return {
"sidecars": list(sidecars),
- "source_host": (
- "127.0.0.1" if source_is_local else source_host
- ),
+ "source_host": ("127.0.0.1" if source_is_local else source_host),
"nodes": nodes,
"total_missing_bytes": total_missing_bytes,
"ready": all(node["ready"] for node in nodes),
@@ -608,9 +606,7 @@ def stage_manifest(
"\nos.replace(temporary,final)"
)
_REMOTE_DISCARD_SNIPPET = (
- "import os,sys;"
- "\ntry: os.unlink(sys.argv[1])"
- "\nexcept FileNotFoundError: pass"
+ "import os,sys;\ntry: os.unlink(sys.argv[1])\nexcept FileNotFoundError: pass"
)
@@ -648,8 +644,7 @@ def _finish_remote_staged_file(
)
if result.returncode != 0:
raise RuntimeError(
- f"could not install staged file on {host}: "
- f"{result.stderr.strip()[:200]}"
+ f"could not install staged file on {host}: {result.stderr.strip()[:200]}"
)
@@ -745,9 +740,7 @@ def scp_push(
f"{str(Path(destination_dir).expanduser()).rstrip('/')}/"
f"{_staging_partial_name()}"
)
- final_path = (
- f"{str(Path(destination_dir).expanduser()).rstrip('/')}/{filename}"
- )
+ final_path = f"{str(Path(destination_dir).expanduser()).rstrip('/')}/{filename}"
installed = False
try:
result = subprocess.run(
@@ -786,11 +779,7 @@ def _local_file_sizes(model_dir: str | Path) -> dict[str, int]:
root = Path(model_dir).expanduser()
if not root.is_dir():
return {}
- return {
- path.name: path.stat().st_size
- for path in root.iterdir()
- if path.is_file()
- }
+ return {path.name: path.stat().st_size for path in root.iterdir() if path.is_file()}
def scp_copy(
@@ -873,9 +862,7 @@ def scp_copy(
f"could not create model directory on {destination_host}: "
f"{mkdir.stderr.strip()[:200]}"
)
- temporary_path = (
- f"{destination_dir.rstrip('/')}/{_staging_partial_name()}"
- )
+ temporary_path = f"{destination_dir.rstrip('/')}/{_staging_partial_name()}"
final_path = f"{destination_dir.rstrip('/')}/{filename}"
installed = False
try:
@@ -946,9 +933,7 @@ def stage_files_from_source(
source_dir = (
str(Path(model_path).expanduser())
if is_local_host(source_host)
- else remote_model_dir(
- source_host, home_relative_model_path(str(model_path))
- )
+ else remote_model_dir(source_host, home_relative_model_path(str(model_path)))
)
destination_dir = destination_dir or source_dir
expected = dict(expected_sizes)
@@ -963,9 +948,7 @@ def stage_files_from_source(
):
raise RuntimeError("staging source returned an unsafe file inventory")
if is_local_host(source_host) and not is_local_host(destination_host):
- common = tuple(
- name for name in expected if name not in set(plan.required)
- )
+ common = tuple(name for name in expected if name not in set(plan.required))
return stage_remote_files(
plan,
model_path=model_path,
diff --git a/omlx/cluster/system_socket_proxy.py b/omlx/cluster/system_socket_proxy.py
new file mode 100644
index 0000000000..66f90419bd
--- /dev/null
+++ b/omlx/cluster/system_socket_proxy.py
@@ -0,0 +1,218 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Carry one local TCP stream through macOS's system Python when required.
+
+Some macOS installations deny a Homebrew Python process outbound access to a
+direct Thunderbolt subnet while Apple's system Python can use the same address.
+A bounded child bridges a loopback socket to that path; the parent retains its
+normal socket API and no model data crosses this helper.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import os
+import select
+import socket
+import subprocess
+import sys
+import time
+from contextlib import suppress
+from dataclasses import dataclass
+from pathlib import Path
+
+_DEFAULT_TIMEOUT_SECONDS = 20.0
+_PROXY_PROGRAM = r"""
+import socket, sys, threading, time
+
+def connect(host, port, timeout):
+ deadline = time.monotonic() + timeout
+ error = None
+ while time.monotonic() < deadline:
+ try:
+ targets = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
+ except OSError as exc:
+ error = exc
+ targets = []
+ for family, socktype, protocol, _, sockaddr in targets:
+ remote = socket.socket(family, socktype, protocol)
+ try:
+ remote.settimeout(min(1.0, max(0.05, deadline - time.monotonic())))
+ remote.connect(sockaddr)
+ remote.settimeout(None)
+ return remote
+ except OSError as exc:
+ error = exc
+ remote.close()
+ time.sleep(0.05)
+ raise RuntimeError("could not reach control coordinator: %s" % error)
+
+def copy(source, target):
+ try:
+ while True:
+ payload = source.recv(65536)
+ if not payload:
+ return
+ target.sendall(payload)
+ finally:
+ try:
+ target.shutdown(socket.SHUT_WR)
+ except OSError:
+ pass
+
+def main():
+ host, port, timeout = sys.argv[1], int(sys.argv[2]), float(sys.argv[3])
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ print("PORT %d" % listener.getsockname()[1], flush=True)
+ remote = connect(host, port, timeout)
+ print("READY", flush=True)
+ local, _ = listener.accept()
+ finally:
+ listener.close()
+ thread = threading.Thread(target=copy, args=(remote, local), daemon=True)
+ thread.start()
+ copy(local, remote)
+ thread.join(timeout=1.0)
+ local.close()
+ remote.close()
+
+if __name__ == "__main__":
+ try:
+ main()
+ except BaseException as exc:
+ print("oMLX control socket helper failed: %s" % exc, file=sys.stderr, flush=True)
+ raise
+"""
+
+
+def _system_python() -> str | None:
+ candidate = Path(
+ os.environ.get("OMLX_CLUSTER_CONTROL_PROXY_PYTHON", "/usr/bin/python3")
+ )
+ if candidate.is_file() and os.access(candidate, os.X_OK):
+ return str(candidate)
+ return None
+
+
+def should_proxy_control_socket(host: str) -> bool:
+ """Whether a non-loopback control socket should use the macOS carrier."""
+
+ mode = os.environ.get("OMLX_CLUSTER_CONTROL_TRANSPORT", "auto").strip().lower()
+ if mode not in {"", "auto", "direct", "system-proxy"}:
+ raise RuntimeError(
+ "OMLX_CLUSTER_CONTROL_TRANSPORT must be auto, direct, or system-proxy"
+ )
+ if mode == "direct":
+ return False
+ if mode == "system-proxy":
+ if _system_python() is None:
+ raise RuntimeError("system Python control proxy is unavailable")
+ return True
+ try:
+ loopback = ipaddress.ip_address(host).is_loopback
+ except ValueError:
+ loopback = host.strip().lower() in {"localhost", "localhost.local"}
+ return sys.platform == "darwin" and not loopback and _system_python() is not None
+
+
+@dataclass
+class SystemSocketProxy:
+ """The parent-visible loopback stream and its helper process."""
+
+ stream: socket.socket
+ process: subprocess.Popen[bytes]
+
+ def close(self) -> None:
+ with suppress(OSError):
+ self.stream.close()
+ if self.process.poll() is None:
+ try:
+ self.process.wait(timeout=1.0)
+ except subprocess.TimeoutExpired:
+ self.process.terminate()
+ try:
+ self.process.wait(timeout=1.0)
+ except subprocess.TimeoutExpired:
+ self.process.kill()
+ self.process.wait(timeout=1.0)
+
+
+def _helper_error(process: subprocess.Popen[bytes]) -> str:
+ status = process.poll()
+ detail = b""
+ if status is not None and process.stderr is not None:
+ detail = process.stderr.read()
+ text = detail.decode("utf-8", "replace").strip()
+ suffix = f": {text[-1000:]}" if text else ""
+ return f"control socket helper stopped (status={status}){suffix}"
+
+
+def _read_line(process: subprocess.Popen[bytes], *, deadline: float) -> bytes:
+ if process.stdout is None:
+ raise RuntimeError("control socket helper has no stdout")
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise TimeoutError("control socket helper did not become ready")
+ ready, _write, _error = select.select([process.stdout], [], [], remaining)
+ if ready:
+ line = process.stdout.readline()
+ if line:
+ return line.rstrip(b"\r\n")
+ raise RuntimeError(_helper_error(process))
+ if process.poll() is not None:
+ raise RuntimeError(_helper_error(process))
+
+
+def open_system_tcp_proxy(
+ host: str,
+ port: int,
+ *,
+ timeout: float = _DEFAULT_TIMEOUT_SECONDS,
+) -> SystemSocketProxy:
+ """Open a local stream bridged to ``host:port`` by system Python."""
+
+ if not 1 <= int(port) <= 65535 or timeout <= 0:
+ raise ValueError("control socket proxy endpoint is invalid")
+ executable = _system_python()
+ if executable is None:
+ raise RuntimeError("system Python control proxy is unavailable")
+ process = subprocess.Popen(
+ [executable, "-u", "-c", _PROXY_PROGRAM, host, str(port), str(timeout)],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ bufsize=0,
+ )
+ stream: socket.socket | None = None
+ try:
+ deadline = time.monotonic() + timeout
+ port_line = _read_line(process, deadline=deadline)
+ label, separator, value = port_line.partition(b" ")
+ if label != b"PORT" or not separator or not value.isdigit():
+ raise RuntimeError("control socket helper returned an invalid port")
+ local_port = int(value)
+ stream = socket.create_connection(
+ ("127.0.0.1", local_port),
+ timeout=max(0.05, deadline - time.monotonic()),
+ )
+ if _read_line(process, deadline=deadline) != b"READY":
+ raise RuntimeError("control socket helper did not reach its coordinator")
+ return SystemSocketProxy(stream=stream, process=process)
+ except BaseException:
+ if stream is not None:
+ stream.close()
+ if process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout=1.0)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=1.0)
+ raise
+
+
+__all__ = ["SystemSocketProxy", "open_system_tcp_proxy", "should_proxy_control_socket"]
diff --git a/omlx/config.py b/omlx/config.py
index e8f08993d5..11dff78d43 100644
--- a/omlx/config.py
+++ b/omlx/config.py
@@ -10,6 +10,7 @@
"""
import logging
+import math
import os
from dataclasses import dataclass, field
from pathlib import Path
@@ -43,7 +44,10 @@ def parse_size(size_str: str) -> int:
if size_str.endswith(unit):
try:
value = float(size_str[: -len(unit)])
- return int(value * multiplier)
+ byte_value = value * multiplier
+ if not math.isfinite(byte_value):
+ raise ValueError
+ return int(byte_value)
except ValueError:
pass
diff --git a/omlx/custom_kernels/__init__.py b/omlx/custom_kernels/__init__.py
index 33ae183b3c..dfcfb6b402 100644
--- a/omlx/custom_kernels/__init__.py
+++ b/omlx/custom_kernels/__init__.py
@@ -5,7 +5,13 @@
import importlib
-NATIVE_KERNEL_PACKAGES = ("bonsai", "glm_moe_dsa", "minimax_m3", "qwen35_prefill")
+NATIVE_KERNEL_PACKAGES = (
+ "bonsai",
+ "decode_fast",
+ "glm_moe_dsa",
+ "minimax_m3",
+ "qwen35_prefill",
+)
def native_kernel_status() -> dict[str, dict[str, object]]:
diff --git a/omlx/custom_kernels/bonsai/csrc/bonsai_quantized.metal b/omlx/custom_kernels/bonsai/csrc/bonsai_quantized.metal
index d1c354cd8a..71a7de8016 100644
--- a/omlx/custom_kernels/bonsai/csrc/bonsai_quantized.metal
+++ b/omlx/custom_kernels/bonsai/csrc/bonsai_quantized.metal
@@ -1,10 +1,9 @@
// Copyright © 2026 oMLX contributors
// SPDX-License-Identifier: Apache-2.0
//
-// Instantiates only the Bonsai-specific kernel variants that are not present
-// in the stock mlx 0.32.0 metallib:
-// - affine_qmv_fast for bits=1 (1-bit path added by Bonsai MLX fork)
-// - affine_qmv_wide for bits=1 and bits=2 (new kernel from Bonsai fork)
+// Instantiates the Bonsai-specific entry points used by the native extension.
+// Stock MLX 0.32.2 now includes generic 2-bit qmv_fast/qmv_wide kernels, while
+// 1-bit support and the extension's symmetric-bias routes remain Bonsai-only.
//
// The vendored quantized.h in this directory is the Bonsai-patched version.
// It must shadow the mlx-installed copy; CMake sets -I for this directory
diff --git a/omlx/custom_kernels/common/csrc/mlx/backend/metal/kernels/steel/attn/params.h b/omlx/custom_kernels/common/csrc/mlx/backend/metal/kernels/steel/attn/params.h
index 4919496da4..7894276ae9 100644
--- a/omlx/custom_kernels/common/csrc/mlx/backend/metal/kernels/steel/attn/params.h
+++ b/omlx/custom_kernels/common/csrc/mlx/backend/metal/kernels/steel/attn/params.h
@@ -164,6 +164,25 @@ struct DeepseekV4SparseAttentionParams {
int64_t O_strides[3]; ///< Output strides (B, H, L, D = 1)
};
+struct Qwen4QSASparseGQAParams {
+ int B; ///< Batch size (the current native ABI fixes this to one)
+ int q_heads; ///< Main-attention query heads
+ int kv_heads; ///< Main-attention key/value heads
+ int qL; ///< Query rows in this prefill tile
+ int kL; ///< Full cached key/value rows
+ int topk; ///< Fixed-width selected four-token block list per query
+ int gqa_factor; ///< Query heads sharing one key/value head
+ int q_offset; ///< Absolute position of query row zero
+
+ float scale; ///< Attention scale
+
+ int64_t Q_strides[3]; ///< Query strides (B, H, L, D = 1)
+ int64_t K_strides[3]; ///< Key strides (B, Hkv, L, D = 1)
+ int64_t V_strides[3]; ///< Value strides (B, Hkv, L, D = 1)
+ int64_t Topk_strides[3]; ///< Selected-token strides (B, 1, L, topk = 1)
+ int64_t O_strides[3]; ///< Output strides (B, H, L, D = 1)
+};
+
struct AttnChunkReduceParams {
int C; ///< Number of key chunks
int H; ///< Heads
diff --git a/omlx/custom_kernels/decode_fast/__init__.py b/omlx/custom_kernels/decode_fast/__init__.py
new file mode 100644
index 0000000000..2e84841edb
--- /dev/null
+++ b/omlx/custom_kernels/decode_fast/__init__.py
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Optional exact decode SDPA kernel used by Qwen4 QSA."""
+
+from .fast import NATIVE_AVAILABLE, sdpa_decode
+
+__all__ = ["NATIVE_AVAILABLE", "sdpa_decode"]
diff --git a/omlx/custom_kernels/decode_fast/csrc/CMakeLists.txt b/omlx/custom_kernels/decode_fast/csrc/CMakeLists.txt
new file mode 100644
index 0000000000..1aca23a68d
--- /dev/null
+++ b/omlx/custom_kernels/decode_fast/csrc/CMakeLists.txt
@@ -0,0 +1,63 @@
+# SPDX-License-Identifier: Apache-2.0
+cmake_minimum_required(VERSION 3.27)
+project(omlx_decode_fast_kernels LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_POSITION_INDEPENDENT_CODE ON)
+option(BUILD_SHARED_LIBS "Build extensions as a shared library" ON)
+
+find_package(Python 3.8 COMPONENTS Interpreter Development.Module REQUIRED)
+execute_process(
+ COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
+ OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT)
+find_package(nanobind CONFIG REQUIRED)
+execute_process(
+ COMMAND "${Python_EXECUTABLE}" -m mlx --cmake-dir
+ OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE MLX_ROOT)
+find_package(MLX CONFIG REQUIRED)
+
+add_library(omlx_decode_fast_kernel_ops)
+target_sources(omlx_decode_fast_kernel_ops PRIVATE
+ ${CMAKE_CURRENT_LIST_DIR}/sdpa_decode.cpp)
+target_include_directories(omlx_decode_fast_kernel_ops PUBLIC
+ ${CMAKE_CURRENT_LIST_DIR})
+target_link_libraries(omlx_decode_fast_kernel_ops PUBLIC mlx)
+
+if(MLX_BUILD_METAL)
+ set(SDPA_METAL ${CMAKE_CURRENT_LIST_DIR}/sdpa_decode.metal)
+ set(SDPA_AIR ${CMAKE_CURRENT_BINARY_DIR}/sdpa_decode.air)
+ set(SDPA_METALLIB
+ ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/omlx_decode_fast_kernels.metallib)
+ set(SDPA_INCLUDE_ARGS -I${CMAKE_CURRENT_LIST_DIR})
+ foreach(INCLUDE_DIR IN LISTS MLX_INCLUDE_DIRS)
+ list(APPEND SDPA_INCLUDE_ARGS -I${INCLUDE_DIR})
+ endforeach()
+ set(SDPA_METAL_FLAGS -x metal -Wall -Wextra -fno-fast-math
+ -Wno-c++17-extensions -Wno-c++20-extensions)
+ if(NOT CMAKE_OSX_DEPLOYMENT_TARGET STREQUAL "")
+ list(APPEND SDPA_METAL_FLAGS
+ "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
+ endif()
+ add_custom_command(
+ OUTPUT ${SDPA_AIR}
+ COMMAND xcrun -sdk macosx metal ${SDPA_METAL_FLAGS} -c ${SDPA_METAL}
+ ${SDPA_INCLUDE_ARGS} -o ${SDPA_AIR}
+ DEPENDS ${SDPA_METAL} ${CMAKE_CURRENT_LIST_DIR}/sdpa_decode_kernels.h
+ VERBATIM)
+ add_custom_command(
+ OUTPUT ${SDPA_METALLIB}
+ COMMAND xcrun -sdk macosx metal ${SDPA_AIR} -o ${SDPA_METALLIB}
+ DEPENDS ${SDPA_AIR} VERBATIM)
+ add_custom_target(omlx_decode_fast_kernels_metallib DEPENDS ${SDPA_METALLIB})
+ add_dependencies(omlx_decode_fast_kernel_ops
+ omlx_decode_fast_kernels_metallib)
+endif()
+
+nanobind_add_module(_ext NB_STATIC STABLE_ABI LTO NOMINSIZE NB_DOMAIN mlx
+ ${CMAKE_CURRENT_LIST_DIR}/bindings.cpp)
+target_link_libraries(_ext PRIVATE omlx_decode_fast_kernel_ops)
+if(BUILD_SHARED_LIBS)
+ target_link_options(_ext PRIVATE -Wl,-rpath,@loader_path
+ -Wl,-rpath,@loader_path/../../../mlx/lib)
+endif()
diff --git a/omlx/custom_kernels/decode_fast/csrc/MLX_LICENSE.txt b/omlx/custom_kernels/decode_fast/csrc/MLX_LICENSE.txt
new file mode 100644
index 0000000000..98ff47b9ef
--- /dev/null
+++ b/omlx/custom_kernels/decode_fast/csrc/MLX_LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright © 2023 Apple Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/omlx/custom_kernels/decode_fast/csrc/bindings.cpp b/omlx/custom_kernels/decode_fast/csrc/bindings.cpp
new file mode 100644
index 0000000000..f587eb0697
--- /dev/null
+++ b/omlx/custom_kernels/decode_fast/csrc/bindings.cpp
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: Apache-2.0
+#include
+#include
+#include
+
+#include "sdpa_decode.h"
+
+namespace nb = nanobind;
+using namespace nb::literals;
+
+NB_MODULE(_ext, m) {
+ m.doc() = "Native exact decode SDPA for Qwen4 QSA";
+ m.def(
+ "abi_probe",
+ [](const mlx::core::array& a) { return static_cast(a.size()); },
+ "a"_a);
+ m.def(
+ "sdpa_decode_supported",
+ &omlx::decode_fast_kernels::sdpa_decode_supported,
+ "q"_a,
+ "k"_a,
+ "v"_a,
+ "stream"_a = nb::none());
+ m.def(
+ "sdpa_decode",
+ &omlx::decode_fast_kernels::sdpa_decode,
+ "q"_a,
+ "k"_a,
+ "v"_a,
+ "scale"_a,
+ "causal"_a,
+ "mask"_a = nb::none(),
+ "sinks"_a = nb::none(),
+ "stream"_a = nb::none());
+}
diff --git a/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.cpp b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.cpp
new file mode 100644
index 0000000000..9ce561505b
--- /dev/null
+++ b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.cpp
@@ -0,0 +1,497 @@
+// SPDX-License-Identifier: Apache-2.0
+// Decode-mode SDPA (query length <= 8) using the omlx_sdpa_decode kernels:
+// a port of ml-explore/mlx#4294 (closed unmerged upstream) — tiled online
+// softmax, vectorized KV loads, context-scaled 2-pass split on 'd'-class
+// GPUs, fp32 partials. Host dispatch mirrors mlx's
+// scaled_dot_product_attention.cpp vector paths, with kernel names and the
+// metallib swapped for the omlx ones.
+//
+// Layout contract matches the other decode_fast ops: realized inputs must
+// satisfy the stride predicates below (KV caches and decode-time queries in
+// omlx always do). A misaligned realized input is a hard error, since
+// neither a nested eval nor an immediate contiguous copy is legal inside
+// eval_gpu; use the mx.fast fallback for exotic layouts.
+
+#include "sdpa_decode.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "mlx/allocator.h"
+#include "mlx/backend/common/utils.h"
+#include "mlx/backend/metal/device.h"
+#include "mlx/backend/metal/metal.h"
+#include "mlx/backend/metal/utils.h"
+#include "mlx/primitives.h"
+#include "mlx/utils.h"
+
+namespace omlx::decode_fast_kernels {
+
+namespace {
+
+using namespace mlx::core;
+
+std::string sdpa_type_name(Dtype dtype) {
+ if (dtype == float32) {
+ return "float";
+ }
+ if (dtype == float16) {
+ return "float16_t";
+ }
+ if (dtype == bfloat16) {
+ return "bfloat16_t";
+ }
+ std::ostringstream msg;
+ msg << "Unsupported sdpa_decode dtype: " << dtype << ".";
+ throw std::invalid_argument(msg.str());
+}
+
+std::string current_binary_dir_sdpa() {
+ static std::string binary_dir = []() {
+ Dl_info info;
+ if (!dladdr(reinterpret_cast(¤t_binary_dir_sdpa), &info)) {
+ throw std::runtime_error("Unable to get omlx_decode_fast binary dir.");
+ }
+ return std::filesystem::path(info.dli_fname).parent_path().string();
+ }();
+ return binary_dir;
+}
+
+// Layout predicates mirrored from ScaledDotProductAttention::eval_gpu.
+bool q_layout_ok(const array& arr) {
+ if (arr.flags().row_contiguous) {
+ return true;
+ }
+ auto& strides = arr.strides();
+ auto& shape = arr.shape();
+ if (shape[0] == 1 || shape[1] == 1) {
+ auto bidx = shape[0] == 1 ? 1 : 0;
+ return (strides[3] == 1) && (strides[2] == shape[3] * shape[bidx]) &&
+ (strides[bidx] == shape[3]);
+ }
+ return false;
+}
+
+bool kv_layout_ok(const array& arr) {
+ auto& strides = arr.strides();
+ auto& shape = arr.shape();
+ if (strides.back() != 1) {
+ return false;
+ }
+ auto per_thread = shape[3] / 32;
+ if ((shape[2] > 1 && strides[2] % per_thread != 0) ||
+ (shape[1] > 1 && strides[1] % per_thread != 0)) {
+ return false;
+ }
+ if (shape[0] == 1 || shape[1] == 1) {
+ return true;
+ }
+ return (strides[0] == strides[1] * shape[1]);
+}
+
+void sdpa_decode_1pass(
+ const Stream& s,
+ metal::Device& d,
+ MTL::Library* lib,
+ const array& q,
+ const array& k,
+ const array& v,
+ array& out,
+ float scale,
+ bool do_causal,
+ const std::optional& mask,
+ const std::optional& sinks) {
+ std::string kname;
+ kname.reserve(64);
+ concatenate(
+ kname,
+ "omlx_sdpa_decode_",
+ sdpa_type_name(q.dtype()),
+ "_",
+ q.shape(-1),
+ "_",
+ v.shape(-1));
+
+ int gqa_factor = q.shape(1) / k.shape(1);
+ int N = k.shape(2);
+ size_t k_head_stride = k.shape(1) == 1 ? k.strides(0) : k.strides(1);
+ size_t k_seq_stride = k.strides()[2];
+ size_t v_head_stride = v.shape(1) == 1 ? v.strides(0) : v.strides(1);
+ size_t v_seq_stride = v.strides()[2];
+
+ MTL::Size group_dims(1024, 1, 1);
+ MTL::Size grid_dims(q.shape(0) * q.shape(1), q.shape(2), 1);
+
+ bool has_mask = mask.has_value();
+ bool bool_mask = has_mask && (*mask).dtype() == bool_;
+ bool float_mask = has_mask && !bool_mask;
+ bool query_transposed = !q.flags().row_contiguous;
+ bool has_sinks = sinks.has_value();
+ metal::MTLFCList func_consts = {
+ {&has_mask, MTL::DataType::DataTypeBool, 20},
+ {&query_transposed, MTL::DataType::DataTypeBool, 21},
+ {&do_causal, MTL::DataType::DataTypeBool, 22},
+ {&bool_mask, MTL::DataType::DataTypeBool, 23},
+ {&float_mask, MTL::DataType::DataTypeBool, 24},
+ {&has_sinks, MTL::DataType::DataTypeBool, 25},
+ };
+ std::string hash_name = kname;
+ hash_name += has_mask ? (bool_mask ? "_boolmask" : "_floatmask") : "_nomask";
+ hash_name += query_transposed ? "_qt" : "_qnt";
+ hash_name += do_causal ? "_c" : "_nc";
+ hash_name += has_sinks ? "_sinks" : "_nosinks";
+
+ auto& compute_encoder = metal::get_command_encoder(s);
+ auto kernel = d.get_kernel(kname, lib, hash_name, func_consts);
+ compute_encoder.set_compute_pipeline_state(kernel);
+
+ compute_encoder.set_input_array(q, 0);
+ compute_encoder.set_input_array(k, 1);
+ compute_encoder.set_input_array(v, 2);
+ compute_encoder.set_output_array(out, 3);
+ compute_encoder.set_bytes(gqa_factor, 4);
+ compute_encoder.set_bytes(N, 5);
+ compute_encoder.set_bytes(k_head_stride, 6);
+ compute_encoder.set_bytes(k_seq_stride, 7);
+ compute_encoder.set_bytes(v_head_stride, 8);
+ compute_encoder.set_bytes(v_seq_stride, 9);
+ compute_encoder.set_bytes(scale, 10);
+ if (has_mask) {
+ auto& m = *mask;
+ compute_encoder.set_input_array(m, 11 + float_mask);
+ int32_t kv_seq_stride = m.shape(3) > 1 ? m.strides(3) : 0;
+ int32_t q_seq_stride = m.shape(2) > 1 ? m.strides(2) : 0;
+ int32_t head_stride =
+ m.shape(1) > 1 ? m.strides(1) : (m.shape(0) > 1 ? m.strides(0) : 0);
+ compute_encoder.set_bytes(kv_seq_stride, 13);
+ compute_encoder.set_bytes(q_seq_stride, 14);
+ compute_encoder.set_bytes(head_stride, 15);
+ }
+ if (has_sinks) {
+ compute_encoder.set_input_array(*sinks, 16);
+ compute_encoder.set_bytes(q.shape(1), 17);
+ }
+
+ compute_encoder.dispatch_threadgroups(grid_dims, group_dims);
+}
+
+void sdpa_decode_2pass(
+ const Stream& s,
+ metal::Device& d,
+ MTL::Library* lib,
+ const array& q,
+ const array& k,
+ const array& v,
+ array& out,
+ float scale,
+ bool do_causal,
+ const std::optional& mask,
+ const std::optional& sinks) {
+ std::string kname;
+ kname.reserve(64);
+ concatenate(
+ kname,
+ "omlx_sdpa_decode_2pass_1_",
+ sdpa_type_name(q.dtype()),
+ "_",
+ q.shape(-1),
+ "_",
+ v.shape(-1));
+
+ int gqa_factor = q.shape(1) / k.shape(1);
+ int n_simds = gqa_factor * q.shape(2);
+
+ char devc = d.get_architecture().back();
+ int N = k.shape(2);
+ int blocks;
+ if (devc == 's') {
+ blocks = 64;
+ if (N > 1024 && n_simds > 4) {
+ if (N <= 8192) {
+ blocks = 128;
+ } else if (N <= 32768) {
+ blocks = 256;
+ } else if (N <= 65536) {
+ blocks = 512;
+ } else {
+ blocks = 1024;
+ }
+ }
+ } else if (devc == 'd') {
+ // Split the KV sequence so that each threadgroup processes a contiguous
+ // chunk of ~256 keys, while keeping at least 32-64 blocks for parallelism
+ // and capping at 256 to bound the partials traffic. Tuned on M3 Ultra.
+ int b = (((N + 255) / 256 + 31) / 32) * 32;
+ blocks = std::min(256, std::max(N >= 4096 ? 64 : 32, b));
+ } else {
+ if (n_simds >= 4) {
+ blocks = 64;
+ } else {
+ blocks = 32;
+ }
+ }
+
+ size_t k_head_stride = k.shape(1) == 1 ? k.strides(0) : k.strides(1);
+ size_t k_seq_stride = k.strides()[2];
+ size_t v_head_stride = v.shape(1) == 1 ? v.strides(0) : v.strides(1);
+ size_t v_seq_stride = v.strides()[2];
+ MTL::Size group_dims(32, gqa_factor, q.shape(2));
+ MTL::Size grid_dims(k.shape(1), q.shape(0), blocks);
+
+ // Partials in float32 for accuracy (PR #4294); tiny vs the KV read.
+ Shape intermediate_shape;
+ intermediate_shape.reserve(out.ndim() + 1);
+ intermediate_shape.insert(
+ intermediate_shape.end(), out.shape().begin(), out.shape().end() - 1);
+ intermediate_shape.push_back(blocks);
+ intermediate_shape.push_back(out.shape().back());
+ array intermediate(intermediate_shape, float32, nullptr, {});
+ intermediate_shape.pop_back();
+ array sums(intermediate_shape, float32, nullptr, {});
+ array maxs(std::move(intermediate_shape), float32, nullptr, {});
+ intermediate.set_data(allocator::malloc(intermediate.nbytes()));
+ sums.set_data(allocator::malloc(sums.nbytes()));
+ maxs.set_data(allocator::malloc(maxs.nbytes()));
+ auto& compute_encoder = metal::get_command_encoder(s);
+ compute_encoder.add_temporary(intermediate);
+ compute_encoder.add_temporary(sums);
+ compute_encoder.add_temporary(maxs);
+
+ bool has_mask = mask.has_value();
+ bool bool_mask = has_mask && (*mask).dtype() == bool_;
+ bool float_mask = has_mask && !bool_mask;
+ bool query_transposed = !q.flags().row_contiguous;
+ bool has_sinks = sinks.has_value();
+ metal::MTLFCList func_consts = {
+ {&has_mask, MTL::DataType::DataTypeBool, 20},
+ {&query_transposed, MTL::DataType::DataTypeBool, 21},
+ {&do_causal, MTL::DataType::DataTypeBool, 22},
+ {&bool_mask, MTL::DataType::DataTypeBool, 23},
+ {&float_mask, MTL::DataType::DataTypeBool, 24},
+ {&has_sinks, MTL::DataType::DataTypeBool, 25},
+ {&blocks, MTL::DataType::DataTypeInt, 26},
+ };
+ std::string hash_name = kname;
+ hash_name += has_mask ? (bool_mask ? "_boolmask" : "_floatmask") : "_nomask";
+ hash_name += query_transposed ? "_qt" : "_qnt";
+ hash_name += do_causal ? "_c" : "_nc";
+ hash_name += has_sinks ? "_sinks_" : "_nosinks_";
+ hash_name += std::to_string(blocks);
+
+ auto kernel = d.get_kernel(kname, lib, hash_name, func_consts);
+ compute_encoder.set_compute_pipeline_state(kernel);
+
+ compute_encoder.set_input_array(q, 0);
+ compute_encoder.set_input_array(k, 1);
+ compute_encoder.set_input_array(v, 2);
+ compute_encoder.set_output_array(intermediate, 3);
+ compute_encoder.set_output_array(sums, 4);
+ compute_encoder.set_output_array(maxs, 5);
+ compute_encoder.set_bytes(N, 7);
+ compute_encoder.set_bytes(k_head_stride, 8);
+ compute_encoder.set_bytes(k_seq_stride, 9);
+ compute_encoder.set_bytes(v_head_stride, 10);
+ compute_encoder.set_bytes(v_seq_stride, 11);
+ compute_encoder.set_bytes(scale, 12);
+ if (has_mask) {
+ auto& m = *mask;
+ compute_encoder.set_input_array(m, 13 + float_mask);
+ int32_t kv_seq_stride = m.shape(3) > 1 ? m.strides(3) : 0;
+ int32_t q_seq_stride = m.shape(2) > 1 ? m.strides(2) : 0;
+ int32_t head_stride =
+ m.shape(1) > 1 ? m.strides(1) : (m.shape(0) > 1 ? m.strides(0) : 0);
+ compute_encoder.set_bytes(kv_seq_stride, 15);
+ compute_encoder.set_bytes(q_seq_stride, 16);
+ compute_encoder.set_bytes(head_stride, 17);
+ }
+ if (has_sinks) {
+ compute_encoder.set_input_array(*sinks, 18);
+ }
+
+ compute_encoder.dispatch_threadgroups(grid_dims, group_dims);
+
+ // Final reduction pass.
+ kname.clear();
+ concatenate(
+ kname,
+ "omlx_sdpa_decode_2pass_2_",
+ sdpa_type_name(q.dtype()),
+ "_",
+ v.shape(-1));
+
+ kernel = d.get_kernel(kname, lib);
+ compute_encoder.set_compute_pipeline_state(kernel);
+
+ compute_encoder.set_input_array(intermediate, 0);
+ compute_encoder.set_input_array(sums, 1);
+ compute_encoder.set_input_array(maxs, 2);
+ compute_encoder.set_output_array(out, 3);
+ compute_encoder.set_bytes(blocks, 4);
+
+ group_dims = MTL::Size(1024, 1, 1);
+ grid_dims = MTL::Size(q.shape(0) * q.shape(1), q.shape(2), 1);
+ compute_encoder.dispatch_threadgroups(grid_dims, group_dims);
+}
+
+class SdpaDecodePrimitive : public Primitive {
+ public:
+ SdpaDecodePrimitive(Stream stream, float scale, bool do_causal)
+ : Primitive(stream), scale_(scale), do_causal_(do_causal) {}
+
+ void eval_cpu(
+ const std::vector& /* inputs */,
+ std::vector& /* outputs */) override {
+ throw std::runtime_error("SdpaDecodePrimitive has no CPU path.");
+ }
+
+ void eval_gpu(
+ const std::vector& inputs,
+ std::vector& outputs) override {
+ auto& s = stream();
+ auto& d = metal::device(s.device);
+
+ auto& q = inputs[0];
+ auto& k = inputs[1];
+ auto& v = inputs[2];
+ auto& o = outputs[0];
+
+ std::optional sinks = std::nullopt;
+ std::optional mask = std::nullopt;
+ if (has_sinks_) {
+ sinks = inputs[3];
+ if (inputs.size() > 4) {
+ mask = inputs[4];
+ }
+ } else if (inputs.size() > 3) {
+ mask = inputs[3];
+ }
+
+ if (!q_layout_ok(q) || !kv_layout_ok(k) || !kv_layout_ok(v) ||
+ (mask && !(*mask).flags().row_contiguous &&
+ !(q.shape(0) == 1 || q.shape(1) == 1 ||
+ (*mask).strides(0) == (*mask).strides(1) * (*mask).shape(1))) ||
+ (sinks && (*sinks).strides(-1) != 1)) {
+ throw std::runtime_error(
+ "[omlx_decode_fast.sdpa_decode] realized input layout is not "
+ "compatible with the vectorized decode kernels; use "
+ "mx.fast.scaled_dot_product_attention for this layout.");
+ }
+
+ o.set_data(allocator::malloc(o.nbytes()));
+
+ bool do_causal = do_causal_ && q.shape(2) > 1;
+ char devc = d.get_architecture().back();
+ bool gqa = k.shape(1) < q.shape(1);
+ bool use_2pass;
+ if (devc == 'd') {
+ use_2pass = gqa ? (k.shape(2) >= 1024) : (k.shape(2) >= 32768);
+ } else {
+ use_2pass =
+ (devc == 's' && k.shape(2) >= 1024) || (gqa && k.shape(2) >= 4096);
+ }
+
+ auto lib = d.get_library(
+ "omlx_decode_fast_kernels", current_binary_dir_sdpa());
+ if (use_2pass) {
+ sdpa_decode_2pass(
+ s, d, lib, q, k, v, o, scale_, do_causal, mask, sinks);
+ } else {
+ sdpa_decode_1pass(s, d, lib, q, k, v, o, scale_, do_causal, mask, sinks);
+ }
+ }
+
+ DEFINE_NAME(OMLXSdpaDecode)
+
+ bool is_equivalent(const Primitive& other) const override {
+ const auto& rhs = static_cast(other);
+ return scale_ == rhs.scale_ && do_causal_ == rhs.do_causal_ &&
+ has_sinks_ == rhs.has_sinks_;
+ }
+
+ bool has_sinks_ = false;
+
+ private:
+ float scale_;
+ bool do_causal_;
+};
+
+} // namespace
+
+bool sdpa_decode_supported(
+ const mx::array& q,
+ const mx::array& k,
+ const mx::array& v,
+ mx::StreamOrDevice s_) {
+ auto s = to_stream(s_);
+ if (s.device == Device::cpu) {
+ return false;
+ }
+ if (q.ndim() != 4 || k.ndim() != 4 || v.ndim() != 4) {
+ return false;
+ }
+ auto t = q.dtype();
+ if (t != float32 && t != float16 && t != bfloat16) {
+ return false;
+ }
+ if (k.dtype() != t || v.dtype() != t) {
+ return false;
+ }
+ const int qk_dim = q.shape(-1);
+ const int v_dim = v.shape(-1);
+ const bool head_dim_ok =
+ (qk_dim == v_dim &&
+ (qk_dim == 64 || qk_dim == 96 || qk_dim == 128 || qk_dim == 256)) ||
+ (qk_dim == 192 && v_dim == 128);
+ if (!head_dim_ok || k.shape(-1) != qk_dim) {
+ return false;
+ }
+ const int qL = q.shape(2);
+ const int kL = k.shape(2);
+ if (qL < 1 || qL > 8 || qL > kL) {
+ return false;
+ }
+ if (k.shape(0) != q.shape(0) || v.shape(0) != q.shape(0) ||
+ v.shape(1) != k.shape(1) || v.shape(2) != kL) {
+ return false;
+ }
+ const int gqa_factor = q.shape(1) / k.shape(1);
+ if (q.shape(1) % k.shape(1) != 0 || qL * gqa_factor > 32) {
+ return false;
+ }
+ return true;
+}
+
+mx::array sdpa_decode(
+ const mx::array& q,
+ const mx::array& k,
+ const mx::array& v,
+ float scale,
+ bool causal,
+ const std::optional& mask,
+ const std::optional& sinks,
+ mx::StreamOrDevice s_) {
+ if (!sdpa_decode_supported(q, k, v, s_)) {
+ throw std::invalid_argument(
+ "[omlx_decode_fast.sdpa_decode] unsupported shapes/dtypes for the "
+ "decode kernels.");
+ }
+ auto s = to_stream(s_);
+ std::vector inputs = {q, k, v};
+ auto primitive = std::make_shared(s, scale, causal);
+ if (sinks.has_value()) {
+ primitive->has_sinks_ = true;
+ inputs.push_back(*sinks);
+ }
+ if (mask.has_value()) {
+ inputs.push_back(*mask);
+ }
+ Shape out_shape{q.shape(0), q.shape(1), q.shape(2), v.shape(-1)};
+ return array(
+ std::move(out_shape), q.dtype(), std::move(primitive), std::move(inputs));
+}
+
+} // namespace omlx::decode_fast_kernels
diff --git a/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.h b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.h
new file mode 100644
index 0000000000..8038732b58
--- /dev/null
+++ b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.h
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: Apache-2.0
+#pragma once
+
+#include
+
+#include "mlx/array.h"
+#include "mlx/stream.h"
+#include "mlx/utils.h"
+
+namespace mx = mlx::core;
+
+namespace omlx::decode_fast_kernels {
+
+// True when the decode SDPA kernels apply: Metal stream, 4-D fp32/fp16/bf16
+// q/k/v, query length <= 8, supported head dims, GQA fan-out within limits.
+bool sdpa_decode_supported(
+ const mx::array& q,
+ const mx::array& k,
+ const mx::array& v,
+ mx::StreamOrDevice s = {});
+
+// Decode-mode scaled dot product attention (port of mlx#4294). Returns an
+// array of shape (B, H, qL, v_head_dim). Optional mask (broadcastable to
+// (B, H, qL, kL), bool or q's dtype) and attention sinks (per query head).
+mx::array sdpa_decode(
+ const mx::array& q,
+ const mx::array& k,
+ const mx::array& v,
+ float scale,
+ bool causal,
+ const std::optional& mask = std::nullopt,
+ const std::optional& sinks = std::nullopt,
+ mx::StreamOrDevice s = {});
+
+} // namespace omlx::decode_fast_kernels
diff --git a/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.metal b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.metal
new file mode 100644
index 0000000000..e51da85550
--- /dev/null
+++ b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.metal
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: Apache-2.0
+// omlx decode SDPA (vector) kernels — port of ml-explore/mlx#4295's sibling
+// PR #4294 (closed unmerged upstream): tiled online softmax, vectorized KV
+// loads, context-scaled 2-pass split for 'd'-class GPUs, fp32 partials.
+// Kernel bodies live in sdpa_decode_kernels.h (omlx_sdpa_decode*, renamed to
+// stay collision-free with mlx's own sdpa_vector kernels).
+
+#include
+
+// clang-format off
+#include "mlx/backend/metal/kernels/utils.h"
+#include "sdpa_decode_kernels.h"
+
+using namespace metal;
+
+#define instantiate_omlx_sdpa_decode_aggregation(type, value_dim) \
+ instantiate_kernel( \
+ "omlx_sdpa_decode_2pass_2_" #type "_" #value_dim, \
+ omlx_sdpa_decode_2pass_2, \
+ type, \
+ value_dim)
+
+#define instantiate_omlx_sdpa_decode(type, qk_dim, value_dim) \
+ instantiate_kernel( \
+ "omlx_sdpa_decode_" #type "_" #qk_dim "_" #value_dim, \
+ omlx_sdpa_decode, \
+ type, \
+ qk_dim, \
+ value_dim) \
+ instantiate_kernel( \
+ "omlx_sdpa_decode_2pass_1_" #type "_" #qk_dim "_" #value_dim, \
+ omlx_sdpa_decode_2pass_1, \
+ type, \
+ qk_dim, \
+ value_dim)
+
+#define instantiate_omlx_sdpa_decode_heads(type) \
+ instantiate_omlx_sdpa_decode(type, 64, 64) \
+ instantiate_omlx_sdpa_decode(type, 96, 96) \
+ instantiate_omlx_sdpa_decode(type, 128, 128) \
+ instantiate_omlx_sdpa_decode(type, 192, 128) \
+ instantiate_omlx_sdpa_decode(type, 256, 256) \
+ instantiate_omlx_sdpa_decode_aggregation(type, 64) \
+ instantiate_omlx_sdpa_decode_aggregation(type, 96) \
+ instantiate_omlx_sdpa_decode_aggregation(type, 128) \
+ instantiate_omlx_sdpa_decode_aggregation(type, 256)
+
+instantiate_omlx_sdpa_decode_heads(float)
+instantiate_omlx_sdpa_decode_heads(bfloat16_t)
+instantiate_omlx_sdpa_decode_heads(float16_t)
+// clang-format on
diff --git a/omlx/custom_kernels/decode_fast/csrc/sdpa_decode_kernels.h b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode_kernels.h
new file mode 100644
index 0000000000..04e2ee0a99
--- /dev/null
+++ b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode_kernels.h
@@ -0,0 +1,602 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright © 2024 Apple Inc.
+
+#include
+
+using namespace metal;
+
+constant bool has_mask [[function_constant(20)]];
+constant bool query_transposed [[function_constant(21)]];
+constant bool do_causal [[function_constant(22)]];
+constant bool bool_mask [[function_constant(23)]];
+constant bool float_mask [[function_constant(24)]];
+constant bool has_sinks [[function_constant(25)]];
+constant int blocks [[function_constant(26)]];
+
+// Load N contiguous elements of type T with as few (and as wide) loads as
+// possible. The address must be aligned to N * sizeof(T) bytes (capped at 16
+// byte transactions), which the caller guarantees via the stride checks in
+// scaled_dot_product_attention.cpp.
+template
+inline void load_vec(thread T (&dst)[N], const device T* p) {
+ if constexpr (N == 2 || N == 4) {
+ *reinterpret_cast*>(dst) =
+ *reinterpret_cast*>(p);
+ } else if constexpr (N == 8 && sizeof(T) == 2) {
+ *reinterpret_cast*>(dst) =
+ *reinterpret_cast*>(p);
+ } else if constexpr (N == 8) {
+ *reinterpret_cast*>(dst) =
+ *reinterpret_cast*>(p);
+ *reinterpret_cast*>(dst + 4) =
+ *reinterpret_cast*>(p + 4);
+ } else {
+#pragma unroll
+ for (int i = 0; i < N; i++) {
+ dst[i] = p[i];
+ }
+ }
+}
+
+template
+[[kernel]] void omlx_sdpa_decode(
+ const device T* queries [[buffer(0)]],
+ const device T* keys [[buffer(1)]],
+ const device T* values [[buffer(2)]],
+ device T* out [[buffer(3)]],
+ const constant int& gqa_factor [[buffer(4)]],
+ const constant int& N [[buffer(5)]],
+ const constant size_t& k_head_stride [[buffer(6)]],
+ const constant size_t& k_seq_stride [[buffer(7)]],
+ const constant size_t& v_head_stride [[buffer(8)]],
+ const constant size_t& v_seq_stride [[buffer(9)]],
+ const constant float& scale [[buffer(10)]],
+ const device bool* bmask [[buffer(11), function_constant(bool_mask)]],
+ const device T* fmask [[buffer(12), function_constant(float_mask)]],
+ const constant int& mask_kv_seq_stride
+ [[buffer(13), function_constant(has_mask)]],
+ const constant int& mask_q_seq_stride
+ [[buffer(14), function_constant(has_mask)]],
+ const constant int& mask_head_stride
+ [[buffer(15), function_constant(has_mask)]],
+ const device T* sinks [[buffer(16), function_constant(has_sinks)]],
+ const constant int& num_q_heads
+ [[buffer(17), function_constant(has_sinks)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 tpg [[threadgroups_per_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ constexpr int BN = 32;
+ constexpr int BD = 32;
+ // Keys are processed in tiles of TK so the online softmax update (max, exp
+ // and rescale of the accumulator) happens once per tile instead of per key.
+ constexpr int TK = 4;
+ constexpr int qk_per_thread = D / BD;
+ constexpr int v_per_thread = V / BD;
+ int inner_k_stride = BN * TK * int(k_seq_stride);
+ int inner_v_stride = BN * TK * int(v_seq_stride);
+
+ typedef float U;
+
+ thread U q[qk_per_thread];
+ thread U o[v_per_thread];
+
+ threadgroup U outputs[BN * BD];
+ threadgroup U max_scores[BN];
+ threadgroup U sum_exp_scores[BN];
+
+ // Adjust positions
+ const int q_batch_head_idx = tid.x;
+ const int q_seq_idx = tid.y;
+ const int kv_head_idx = q_batch_head_idx / gqa_factor;
+ const int o_offset = q_batch_head_idx * tpg.y + q_seq_idx;
+ const int q_offset =
+ query_transposed ? tpg.x * q_seq_idx + q_batch_head_idx : o_offset;
+ queries += q_offset * D + simd_lid * qk_per_thread;
+ keys += kv_head_idx * k_head_stride + simd_gid * TK * k_seq_stride +
+ simd_lid * qk_per_thread;
+ values += kv_head_idx * v_head_stride + simd_gid * TK * v_seq_stride +
+ simd_lid * v_per_thread;
+ if (bool_mask) {
+ bmask += q_batch_head_idx * mask_head_stride +
+ simd_gid * TK * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride;
+ }
+ if (float_mask) {
+ fmask += q_batch_head_idx * mask_head_stride +
+ simd_gid * TK * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride;
+ }
+
+ out += o_offset * V + simd_gid * v_per_thread;
+
+ // Read the query and 0 the output accumulator
+ {
+ thread T qt[qk_per_thread];
+ load_vec(qt, queries);
+ for (int i = 0; i < qk_per_thread; i++) {
+ q[i] = static_cast(scale) * static_cast(qt[i]);
+ }
+ }
+ for (int i = 0; i < v_per_thread; i++) {
+ o[i] = 0;
+ }
+
+ U max_score = Limits::finite_min;
+ U sum_exp_score = 0;
+ if (has_sinks && simd_gid == 0) {
+ max_score = static_cast(sinks[q_batch_head_idx % num_q_heads]);
+ sum_exp_score = 1;
+ }
+
+ // For each tile of TK keys
+ int i = simd_gid * TK;
+ for (; i + TK <= N; i += BN * TK) {
+ // Read the keys and compute the scores
+ thread T ks[TK][qk_per_thread];
+ U scores[TK];
+ bool use_key[TK];
+#pragma unroll
+ for (int t = 0; t < TK; t++) {
+ load_vec(ks[t], keys + t * int(k_seq_stride));
+ }
+#pragma unroll
+ for (int t = 0; t < TK; t++) {
+ U score = 0;
+ for (int j = 0; j < qk_per_thread; j++) {
+ score += q[j] * static_cast(ks[t][j]);
+ }
+ score = simd_sum(score);
+
+ use_key[t] = true;
+ if (do_causal) {
+ use_key[t] = i + t <= (N - int(tpg.y) + int(q_seq_idx));
+ } else if (bool_mask) {
+ use_key[t] = bmask[t * mask_kv_seq_stride];
+ } else if (float_mask) {
+ use_key[t] = fmask[t * mask_kv_seq_stride] >= Limits::finite_min;
+ }
+ if (use_key[t] && float_mask) {
+ score += static_cast(fmask[t * mask_kv_seq_stride]);
+ }
+ scores[t] = use_key[t] ? score : Limits::finite_min;
+ }
+
+ U tile_max = scores[0];
+#pragma unroll
+ for (int t = 1; t < TK; t++) {
+ tile_max = max(tile_max, scores[t]);
+ }
+ U new_max = max(max_score, tile_max);
+
+ // Read the values
+ thread T vs[TK][v_per_thread];
+#pragma unroll
+ for (int t = 0; t < TK; t++) {
+ load_vec(vs[t], values + t * int(v_seq_stride));
+ }
+
+ // Rescale the accumulators only when the running max actually increased
+ if (new_max > max_score) {
+ U factor = fast::exp(max_score - new_max);
+ sum_exp_score *= factor;
+ for (int j = 0; j < v_per_thread; j++) {
+ o[j] *= factor;
+ }
+ max_score = new_max;
+ }
+
+ // Update the accumulators
+#pragma unroll
+ for (int t = 0; t < TK; t++) {
+ U p = use_key[t] ? fast::exp(scores[t] - max_score) : U(0);
+ sum_exp_score += p;
+#pragma unroll
+ for (int j = 0; j < v_per_thread; j++) {
+ o[j] += p * static_cast(vs[t][j]);
+ }
+ }
+
+ // Move the pointers to the next tile
+ keys += inner_k_stride;
+ values += inner_v_stride;
+ if (bool_mask) {
+ bmask += BN * TK * mask_kv_seq_stride;
+ }
+ if (float_mask) {
+ fmask += BN * TK * mask_kv_seq_stride;
+ }
+ }
+
+ // Process the remaining keys of the last partial tile
+ const int tail_end = min(N, i + TK);
+ for (; i < tail_end; i++) {
+ bool use_key = true;
+ if (do_causal) {
+ use_key = i <= (N - int(tpg.y) + int(q_seq_idx));
+ } else if (bool_mask) {
+ use_key = bmask[0];
+ } else if (float_mask) {
+ use_key = (fmask[0] >= Limits::finite_min);
+ }
+ if (use_key) {
+ // Read the key
+ thread T k[qk_per_thread];
+ load_vec(k, keys);
+
+ // Compute the i-th score
+ U score = 0;
+ for (int j = 0; j < qk_per_thread; j++) {
+ score += q[j] * static_cast(k[j]);
+ }
+ score = simd_sum(score);
+ if (float_mask) {
+ score += static_cast(fmask[0]);
+ }
+
+ // Update the accumulators
+ U new_max = max(max_score, score);
+ U factor = fast::exp(max_score - new_max);
+ U exp_score = fast::exp(score - new_max);
+
+ max_score = new_max;
+ sum_exp_score = sum_exp_score * factor + exp_score;
+
+ // Update the output accumulator
+ thread T vt[v_per_thread];
+ load_vec(vt, values);
+ for (int j = 0; j < v_per_thread; j++) {
+ o[j] = o[j] * factor + exp_score * static_cast(vt[j]);
+ }
+ }
+
+ // Move the pointers to the next kv
+ keys += int(k_seq_stride);
+ values += int(v_seq_stride);
+ if (bool_mask) {
+ bmask += mask_kv_seq_stride;
+ }
+ if (float_mask) {
+ fmask += mask_kv_seq_stride;
+ }
+ }
+
+ // Each thread has a partial part of the output so we need to combine them.
+
+ // First let's communicate the max and sum_exp
+ if (simd_lid == 0) {
+ max_scores[simd_gid] = max_score;
+ sum_exp_scores[simd_gid] = sum_exp_score;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ max_score = max_scores[simd_lid];
+ U new_max = simd_max(max_score);
+ U factor = fast::exp(max_score - new_max);
+ sum_exp_score = simd_sum(sum_exp_scores[simd_lid] * factor);
+
+ // Now we need to aggregate all the outputs
+ for (int i = 0; i < v_per_thread; i++) {
+ outputs[simd_lid * BD + simd_gid] = o[i];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ o[i] = simd_sum(outputs[simd_gid * BD + simd_lid] * factor);
+ o[i] = sum_exp_score == 0 ? o[i] : (o[i] / sum_exp_score);
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ // And write the output
+ if (simd_lid == 0) {
+ for (int i = 0; i < v_per_thread; i++) {
+ out[i] = static_cast(o[i]);
+ }
+ }
+}
+
+template
+[[kernel]] void omlx_sdpa_decode_2pass_1(
+ const device T* queries [[buffer(0)]],
+ const device T* keys [[buffer(1)]],
+ const device T* values [[buffer(2)]],
+ device float* out [[buffer(3)]],
+ device float* sums [[buffer(4)]],
+ device float* maxs [[buffer(5)]],
+ const constant int& N [[buffer(7)]],
+ const constant size_t& k_head_stride [[buffer(8)]],
+ const constant size_t& k_seq_stride [[buffer(9)]],
+ const constant size_t& v_head_stride [[buffer(10)]],
+ const constant size_t& v_seq_stride [[buffer(11)]],
+ const constant float& scale [[buffer(12)]],
+ const device bool* bmask [[buffer(13), function_constant(bool_mask)]],
+ const device T* fmask [[buffer(14), function_constant(float_mask)]],
+ const constant int& mask_kv_seq_stride
+ [[buffer(15), function_constant(has_mask)]],
+ const constant int& mask_q_seq_stride
+ [[buffer(16), function_constant(has_mask)]],
+ const constant int& mask_head_stride
+ [[buffer(17), function_constant(has_mask)]],
+ const device T* sinks [[buffer(18), function_constant(has_sinks)]],
+ uint3 tptg [[threads_per_threadgroup]],
+ uint3 tidtg [[thread_position_in_threadgroup]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 tpg [[threadgroups_per_grid]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ constexpr int BD = 32;
+ // Keys are processed in tiles of TK so the online softmax update (max, exp
+ // and rescale of the accumulator) happens once per tile instead of per key.
+ constexpr int TK = 4;
+ constexpr int qk_per_thread = D / BD;
+ constexpr int v_per_thread = V / BD;
+
+ typedef float U;
+
+ thread U q[qk_per_thread];
+ thread U o[v_per_thread] = {0};
+
+ // Adjust positions
+ const int kv_head_idx = tid.x;
+ const int batch_idx = tid.y;
+ const int block_idx = tid.z;
+ const int gqa_factor = tptg.y;
+ const int q_seq_len = tptg.z;
+ const int q_seq_idx = tidtg.z;
+ const int q_head_idx = gqa_factor * kv_head_idx + tidtg.y;
+ const int num_kv_heads = tpg.x;
+ const int num_q_heads = num_kv_heads * gqa_factor;
+ const int q_batch_head_idx = (batch_idx * num_q_heads + q_head_idx);
+ const int o_offset = q_batch_head_idx * q_seq_len + q_seq_idx;
+ const int q_offset =
+ query_transposed ? num_q_heads * q_seq_idx + q_batch_head_idx : o_offset;
+
+ queries += q_offset * D + simd_lid * qk_per_thread;
+
+ // Each block processes a contiguous chunk of the KV sequence.
+ const int chunk = (N + blocks - 1) / blocks;
+ const int k_start = block_idx * chunk;
+ const int k_end = min(N, k_start + chunk);
+
+ const int kv_batch_head_idx = batch_idx * num_kv_heads + kv_head_idx;
+ keys += kv_batch_head_idx * k_head_stride + k_start * k_seq_stride +
+ simd_lid * qk_per_thread;
+ values += kv_batch_head_idx * v_head_stride + k_start * v_seq_stride +
+ simd_lid * v_per_thread;
+ out += o_offset * blocks * V + block_idx * V + simd_lid * v_per_thread;
+ if (bool_mask) {
+ bmask += q_batch_head_idx * mask_head_stride +
+ k_start * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride;
+ }
+ if (float_mask) {
+ fmask += q_batch_head_idx * mask_head_stride +
+ k_start * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride;
+ }
+ sums += o_offset * blocks + block_idx;
+ maxs += o_offset * blocks + block_idx;
+
+ // Read the query
+ {
+ thread T qt[qk_per_thread];
+ load_vec(qt, queries);
+ for (int i = 0; i < qk_per_thread; i++) {
+ q[i] = static_cast(scale) * static_cast(qt[i]);
+ }
+ }
+
+ U max_score = Limits::finite_min;
+ U sum_exp_score = 0;
+ if (has_sinks && block_idx == 0) {
+ max_score = static_cast(sinks[q_head_idx]);
+ sum_exp_score = 1;
+ }
+
+ // For each tile of TK keys in this block's chunk
+ int i = k_start;
+ for (; i + TK <= k_end; i += TK) {
+ // Read the keys and compute the scores
+ thread T ks[TK][qk_per_thread];
+ U scores[TK];
+ bool use_key[TK];
+#pragma unroll
+ for (int t = 0; t < TK; t++) {
+ load_vec(ks[t], keys + t * int(k_seq_stride));
+ }
+#pragma unroll
+ for (int t = 0; t < TK; t++) {
+ U score = 0;
+ for (int j = 0; j < qk_per_thread; j++) {
+ score += q[j] * static_cast(ks[t][j]);
+ }
+ score = simd_sum(score);
+
+ use_key[t] = true;
+ if (do_causal) {
+ use_key[t] = i + t <= (N - q_seq_len + int(q_seq_idx));
+ } else if (bool_mask) {
+ use_key[t] = bmask[t * mask_kv_seq_stride];
+ } else if (float_mask) {
+ use_key[t] = fmask[t * mask_kv_seq_stride] >= Limits::finite_min;
+ }
+ if (use_key[t] && float_mask) {
+ score += static_cast(fmask[t * mask_kv_seq_stride]);
+ }
+ scores[t] = use_key[t] ? score : Limits::finite_min;
+ }
+
+ U tile_max = scores[0];
+#pragma unroll
+ for (int t = 1; t < TK; t++) {
+ tile_max = max(tile_max, scores[t]);
+ }
+ U new_max = max(max_score, tile_max);
+
+ // Read the values
+ thread T vs[TK][v_per_thread];
+#pragma unroll
+ for (int t = 0; t < TK; t++) {
+ load_vec(vs[t], values + t * int(v_seq_stride));
+ }
+
+ // Rescale the accumulators only when the running max actually increased
+ if (new_max > max_score) {
+ U factor = fast::exp(max_score - new_max);
+ sum_exp_score *= factor;
+ for (int j = 0; j < v_per_thread; j++) {
+ o[j] *= factor;
+ }
+ max_score = new_max;
+ }
+
+ // Update the accumulators
+#pragma unroll
+ for (int t = 0; t < TK; t++) {
+ U p = use_key[t] ? fast::exp(scores[t] - max_score) : U(0);
+ sum_exp_score += p;
+#pragma unroll
+ for (int j = 0; j < v_per_thread; j++) {
+ o[j] += p * static_cast(vs[t][j]);
+ }
+ }
+
+ // Move the pointers to the next tile
+ keys += TK * int(k_seq_stride);
+ values += TK * int(v_seq_stride);
+ if (bool_mask) {
+ bmask += TK * mask_kv_seq_stride;
+ }
+ if (float_mask) {
+ fmask += TK * mask_kv_seq_stride;
+ }
+ }
+
+ // Process the remaining keys of the chunk
+ for (; i < k_end; i++) {
+ bool use_key = true;
+ if (do_causal) {
+ use_key = i <= (N - q_seq_len + int(q_seq_idx));
+ } else if (bool_mask) {
+ use_key = bmask[0];
+ } else if (float_mask) {
+ use_key = (fmask[0] >= Limits::finite_min);
+ }
+ if (use_key) {
+ // Compute the i-th score
+ thread T k[qk_per_thread];
+ load_vec(k, keys);
+ U score = 0;
+ for (int j = 0; j < qk_per_thread; j++) {
+ score += q[j] * static_cast(k[j]);
+ }
+ score = simd_sum(score);
+
+ if (float_mask) {
+ score += fmask[0];
+ }
+
+ // Update the accumulators
+ U new_max = max(max_score, score);
+ U factor = fast::exp(max_score - new_max);
+ U exp_score = fast::exp(score - new_max);
+
+ max_score = new_max;
+ sum_exp_score = sum_exp_score * factor + exp_score;
+
+ // Update the output accumulator
+ thread T vt[v_per_thread];
+ load_vec(vt, values);
+ for (int j = 0; j < v_per_thread; j++) {
+ o[j] = o[j] * factor + exp_score * static_cast(vt[j]);
+ }
+ }
+
+ // Move the pointers to the next kv
+ keys += int(k_seq_stride);
+ values += int(v_seq_stride);
+ if (bool_mask) {
+ bmask += mask_kv_seq_stride;
+ }
+ if (float_mask) {
+ fmask += mask_kv_seq_stride;
+ }
+ }
+
+ // Write the sum and max and outputs
+ if (simd_lid == 0) {
+ sums[0] = sum_exp_score;
+ maxs[0] = max_score;
+ }
+
+ for (int i = 0; i < v_per_thread; i++) {
+ out[i] = o[i];
+ }
+}
+
+template
+[[kernel]] void omlx_sdpa_decode_2pass_2(
+ const device float* partials [[buffer(0)]],
+ const device float* sums [[buffer(1)]],
+ const device float* maxs [[buffer(2)]],
+ device T* out [[buffer(3)]],
+ const constant int& blocks [[buffer(4)]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 tpg [[threadgroups_per_grid]],
+ uint simd_gid [[simdgroup_index_in_threadgroup]],
+ uint simd_lid [[thread_index_in_simdgroup]]) {
+ constexpr int BN = 32;
+ constexpr int BD = 32;
+ constexpr int elem_per_thread = D / BD;
+
+ typedef float U;
+
+ thread U o[elem_per_thread] = {0};
+ threadgroup U outputs[BN * BD];
+
+ // Adjust positions
+ const int head_idx = tid.x;
+ const int q_seq_idx = tid.y;
+ const int q_offset = head_idx * tpg.y + q_seq_idx;
+ partials += q_offset * blocks * D + simd_gid * D + simd_lid * elem_per_thread;
+ sums += q_offset * blocks;
+ maxs += q_offset * blocks;
+ out += q_offset * D + simd_gid * elem_per_thread;
+
+ // Set defaults
+ U sum_exp_score = 0.0;
+ U max_score = Limits::finite_min;
+
+ // Reduce the max
+ for (int b = 0; b < blocks / BN; ++b) {
+ max_score = max(max_score, maxs[simd_lid + BN * b]);
+ }
+ max_score = simd_max(max_score);
+
+ // Reduce the d
+ for (int b = 0; b < blocks / BN; ++b) {
+ U factor = fast::exp(maxs[simd_lid + BN * b] - max_score);
+ sum_exp_score += factor * sums[simd_lid + BN * b];
+ }
+ sum_exp_score = simd_sum(sum_exp_score);
+
+ // Reduce the sum exp and partials
+ for (int b = 0; b < blocks / BN; ++b) {
+ U factor = fast::exp(maxs[simd_gid] - max_score);
+
+ // Update the output accumulator
+ for (int i = 0; i < elem_per_thread; i++) {
+ o[i] += factor * partials[i];
+ }
+ maxs += BN;
+ sums += BN;
+ partials += BN * D;
+ }
+
+ // Use shared memory to transpose and reduce the final block
+ for (int i = 0; i < elem_per_thread; i++) {
+ outputs[simd_lid * BD + simd_gid] = o[i];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ o[i] = simd_sum(outputs[simd_gid * BD + simd_lid]);
+ o[i] = sum_exp_score == 0 ? o[i] : (o[i] / sum_exp_score);
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ // And write the output
+ if (simd_lid == 0) {
+ for (int i = 0; i < elem_per_thread; i++) {
+ out[i] = static_cast(o[i]);
+ }
+ }
+}
diff --git a/omlx/custom_kernels/decode_fast/fast.py b/omlx/custom_kernels/decode_fast/fast.py
new file mode 100644
index 0000000000..a7b1327803
--- /dev/null
+++ b/omlx/custom_kernels/decode_fast/fast.py
@@ -0,0 +1,96 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Exact decode-mode SDPA with a fail-closed MLX fallback."""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Optional
+
+import mlx.core as mx
+
+logger = logging.getLogger(__name__)
+
+
+def _detach_import_error(exc: Exception) -> Exception:
+ exc.__traceback__ = None
+ exc.__cause__ = None
+ exc.__context__ = None
+ return exc
+
+
+try:
+ from . import _ext
+except Exception as exc: # pragma: no cover - depends on local native build
+ _ext = None
+ _IMPORT_ERROR = _detach_import_error(exc)
+ if any(Path(__file__).parent.glob("_ext*.so")):
+ logger.warning(
+ "%s: native extension failed to load; using exact MLX SDPA: %s",
+ __name__,
+ _IMPORT_ERROR,
+ )
+else:
+ _IMPORT_ERROR = None
+
+
+def _verify_abi(ext, import_error):
+ """Disable the native symbol when nanobind rejects MLX arrays."""
+ if ext is None:
+ return ext, import_error
+ probe = getattr(ext, "abi_probe", None)
+ if probe is None:
+ return ext, import_error
+ try:
+ probe(mx.zeros((1,)))
+ except TypeError as exc:
+ logger.warning(
+ "%s: native SDPA disabled after nanobind ABI mismatch",
+ __name__,
+ )
+ return None, _detach_import_error(exc)
+ return ext, import_error
+
+
+_ext, _IMPORT_ERROR = _verify_abi(_ext, _IMPORT_ERROR)
+NATIVE_AVAILABLE = _ext is not None
+
+
+def is_native_available() -> bool:
+ return NATIVE_AVAILABLE
+
+
+def import_error() -> Exception | None:
+ return _IMPORT_ERROR
+
+
+def sdpa_decode(
+ q: mx.array,
+ k: mx.array,
+ v: mx.array,
+ scale: float,
+ causal: bool = False,
+ mask: Optional[mx.array] = None,
+ sinks: Optional[mx.array] = None,
+ *,
+ stream: Optional[mx.Stream] = None,
+ force_fallback: bool = False,
+) -> mx.array:
+ """Run native decode SDPA when its exact ABI accepts the inputs."""
+ if (
+ not force_fallback
+ and _ext is not None
+ and _ext.sdpa_decode_supported(q, k, v, stream)
+ ):
+ return _ext.sdpa_decode(q, k, v, scale, causal, mask, sinks, stream)
+ return mx.fast.scaled_dot_product_attention(
+ q,
+ k,
+ v,
+ scale=scale,
+ mask=mask,
+ sinks=sinks,
+ )
+
+
+__all__ = ["NATIVE_AVAILABLE", "is_native_available", "import_error", "sdpa_decode"]
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt b/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt
index a9445df057..ad55edb8d7 100644
--- a/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt
@@ -38,6 +38,7 @@ target_sources(
${CMAKE_CURRENT_LIST_DIR}/dspark_qmv.cpp
${CMAKE_CURRENT_LIST_DIR}/exact_block_attention.cpp
${CMAKE_CURRENT_LIST_DIR}/fused_moe.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/qwen4_qsa_sparse_gqa.cpp
${CMAKE_CURRENT_LIST_DIR}/sparse_mla.cpp)
target_include_directories(
omlx_glm_kernel_ops
@@ -57,6 +58,7 @@ if(MLX_BUILD_METAL)
${CMAKE_CURRENT_LIST_DIR}/dsa_indexer.metal
${CMAKE_CURRENT_LIST_DIR}/exact_block_attention.metal
${CMAKE_CURRENT_LIST_DIR}/fused_moe.metal
+ ${CMAKE_CURRENT_LIST_DIR}/qwen4_qsa_sparse_gqa.metal
${CMAKE_CURRENT_LIST_DIR}/sparse_mla.metal)
file(GLOB_RECURSE OMLX_GLM_METAL_HEADERS CONFIGURE_DEPENDS
${CMAKE_CURRENT_LIST_DIR}/*.h
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_LICENSE.txt b/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_LICENSE.txt
new file mode 100644
index 0000000000..98ff47b9ef
--- /dev/null
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright © 2023 Apple Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_SERVE_LICENSE.txt b/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_SERVE_LICENSE.txt
new file mode 100644
index 0000000000..fa6c781bf4
--- /dev/null
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_SERVE_LICENSE.txt
@@ -0,0 +1,31 @@
+MIT License
+
+Copyright (c) 2026 David Dalcu
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+-------------------------------------------------------------------------------
+
+The MIT terms above cover mlx-serve's own code. This distribution also includes
+third-party software under its own licenses, including the Apache License 2.0,
+the BSD 3-Clause License, and further MIT-licensed components. Those licenses
+continue to apply to those portions.
+
+See NOTICE for the list and the required attributions, and LICENSE-APACHE-2.0
+for the text of the Apache License, Version 2.0.
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp
index 3f962178e1..da6219a9e9 100644
--- a/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp
@@ -9,6 +9,7 @@
#include "dspark_qmv.h"
#include "exact_block_attention.h"
#include "fused_moe.h"
+#include "qwen4_qsa_sparse_gqa.h"
#include "sparse_mla.h"
namespace nb = nanobind;
@@ -51,6 +52,32 @@ NB_MODULE(_ext, m) {
"mask_ratio"_a = 0,
"mask_q_offset"_a = 0,
"stream"_a = nb::none());
+ m.def(
+ "qwen4_qsa_indexer_scores",
+ &omlx::glm_kernels::qwen4_qsa_indexer_scores,
+ "queries"_a,
+ "pooled_keys"_a,
+ "mask_ratio"_a = 4,
+ "mask_q_offset"_a = 0,
+ "stream"_a = nb::none());
+ m.def(
+ "qwen4_qsa_topk_indices",
+ &omlx::glm_kernels::qwen4_qsa_topk_indices,
+ "scores"_a,
+ "topk"_a = 512,
+ "stream"_a = nb::none());
+ m.def(
+ "qwen4_qsa_sparse_gqa_attention",
+ &omlx::glm_kernels::qwen4_qsa_sparse_gqa_attention,
+ "queries"_a,
+ "keys"_a,
+ "values"_a,
+ "selected_blocks"_a,
+ "scale"_a,
+ "q_offset"_a,
+ "key_tile"_a = 128,
+ "dimension_tile"_a = 32,
+ "stream"_a = nb::none());
m.def(
"dsa_topk_indices",
&omlx::glm_kernels::dsa_topk_indices,
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.cpp
index e4b0830bc1..239c90a4ef 100644
--- a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.cpp
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.cpp
@@ -2,6 +2,7 @@
#include "kernels/mma_dsa_indexer_score.h"
+#include
#include
#include
#include
@@ -258,6 +259,133 @@ class DSAIndexerScoresPrimitive : public Primitive {
int mask_q_offset_;
};
+class Qwen4QSAIndexerScoresPrimitive : public Primitive {
+ public:
+ Qwen4QSAIndexerScoresPrimitive(
+ Stream stream,
+ int mask_ratio,
+ int mask_q_offset)
+ : Primitive(stream),
+ mask_ratio_(mask_ratio),
+ mask_q_offset_(mask_q_offset) {}
+
+ static bool unsupported(const array& q, const array& k, Stream s) {
+ if (s.device == Device::cpu || q.dtype() != k.dtype()) {
+ return true;
+ }
+ if (q.dtype() != float16 && q.dtype() != bfloat16) {
+ return true;
+ }
+ if (!row_contiguous(q) || !row_contiguous(k)) {
+ return true;
+ }
+ if (q.ndim() != 4 || k.ndim() != 4) {
+ return true;
+ }
+ // This is intentionally the production Qwen4-Exp geometry only. A stale
+ // config or generalized caller must stay on qsa_fast's fp32 MLX path.
+ return q.shape(0) != 1 || k.shape(0) != 1 || q.shape(1) != 4 ||
+ k.shape(1) != 1 || q.shape(2) <= 0 || k.shape(2) <= 0 ||
+ q.shape(3) != 128 || k.shape(3) != 128;
+ }
+
+ void eval_cpu(
+ const std::vector& /* inputs */,
+ std::vector& /* outputs */) override {
+ throw std::runtime_error(
+ "Qwen4QSAIndexerScoresPrimitive has no CPU path.");
+ }
+
+ void eval_gpu(
+ const std::vector& inputs,
+ std::vector& outputs) override {
+ auto& s = stream();
+ auto& d = metal::device(s.device);
+ auto& out = outputs[0];
+ const auto& q = inputs[0];
+ const auto& k = inputs[1];
+
+ out.set_data(allocator::malloc(out.nbytes()));
+
+ constexpr int bm = 64;
+ constexpr int bn = 64;
+ constexpr int bk = 16;
+ constexpr int wm = 2;
+ constexpr int wn = 2;
+ const int B = q.shape(0);
+ const int H = q.shape(1);
+ const int M = q.shape(2);
+ const int N = k.shape(2);
+ const int D = q.shape(3);
+ const int tiles_m = (M + bm - 1) / bm;
+ const int tiles_n = (N + bn - 1) / bn;
+
+ mlx::steel::GEMMParams params{
+ /* const int M = */ M,
+ /* const int N = */ N,
+ /* const int K = */ D,
+ /* const int lda = */ D,
+ /* const int ldb = */ D,
+ /* const int ldd = */ N,
+ /* const int tiles_n = */ tiles_n,
+ /* const int tiles_m = */ tiles_m,
+ /* const int64_t batch_stride_a = */ int64_t(H) * M * D,
+ /* const int64_t batch_stride_b = */ int64_t(N) * D,
+ /* const int64_t batch_stride_d = */ int64_t(M) * N,
+ /* const int swizzle_log = */ 0,
+ /* const int gemm_k_iterations_aligned = */ D / bk,
+ /* const int batch_ndim = */ 1};
+
+ std::string base_name;
+ concatenate(
+ base_name,
+ "qwen4_qsa_indexer_score_",
+ type_to_name(q),
+ "_bm",
+ bm,
+ "_bn",
+ bn,
+ "_bk",
+ bk,
+ "_wm",
+ wm,
+ "_wn",
+ wn);
+
+ auto lib = d.get_library("omlx_glm_kernels", current_binary_dir());
+ auto kernel = d.get_kernel(base_name, lib);
+ auto& encoder = metal::get_command_encoder(s);
+ encoder.set_compute_pipeline_state(kernel);
+ encoder.set_input_array(q, 0);
+ encoder.set_input_array(k, 1);
+ encoder.set_output_array(out, 2);
+ encoder.set_bytes(params, 3);
+ encoder.set_bytes(mask_ratio_, 4);
+ encoder.set_bytes(mask_q_offset_, 5);
+ const float score_divisor = std::sqrt(static_cast(D));
+ encoder.set_bytes(score_divisor, 6);
+ encoder.dispatch_threadgroups(
+ MTL::Size(tiles_n, tiles_m, B),
+ MTL::Size(wm * wn * 32, 1, 1));
+ }
+
+ DEFINE_NAME(OMLXQwen4QSAIndexerScores)
+ DEFINE_INPUT_OUTPUT_SHAPE()
+ bool is_equivalent(const Primitive& other) const override {
+ const auto& rhs =
+ static_cast(other);
+ return mask_ratio_ == rhs.mask_ratio_ &&
+ mask_q_offset_ == rhs.mask_q_offset_;
+ }
+ auto state() const {
+ return std::make_tuple(mask_ratio_, mask_q_offset_);
+ }
+
+ private:
+ int mask_ratio_;
+ int mask_q_offset_;
+};
+
// ── v25 M2 MMA score kernel (mma_dsa_indexer_score.h) ───────────────────────
// Split dispatch: the interior instantiation runs the unmodified hot loop on
// fully-interior tiles; the boundary instantiation handles partial edge tiles
@@ -558,6 +686,57 @@ class DSparkFP32TopKIndicesPrimitive : public Primitive {
}
};
+class Qwen4QSAFP32TopKIndicesPrimitive : public Primitive {
+ public:
+ explicit Qwen4QSAFP32TopKIndicesPrimitive(Stream stream)
+ : Primitive(stream) {}
+
+ void eval_cpu(
+ const std::vector& /* inputs */,
+ std::vector& /* outputs */) override {
+ throw std::runtime_error("Qwen4 QSA FP32 top-k has no CPU path.");
+ }
+
+ void eval_gpu(
+ const std::vector& inputs,
+ std::vector& outputs) override {
+ auto& s = stream();
+ auto& d = metal::device(s.device);
+ const auto& scores = inputs[0];
+ auto& out = outputs[0];
+ out.set_data(allocator::malloc(out.nbytes()));
+
+ constexpr int topk = 512;
+ constexpr int threads = 256;
+ const int rows = scores.shape(1);
+ DSATopKParams params{
+ /* int rows = */ rows,
+ /* int L = */ rows,
+ /* int K = */ scores.shape(2),
+ /* int topk = */ topk,
+ /* bool causal_valid_prefix = */ false};
+
+ auto lib = d.get_library("omlx_glm_kernels", current_binary_dir());
+ auto kernel =
+ d.get_kernel("qwen4_qsa_fp32_topk_indices_topk512_t256", lib);
+ auto& encoder = metal::get_command_encoder(s);
+ encoder.set_compute_pipeline_state(kernel);
+ encoder.set_input_array(scores, 0);
+ encoder.set_output_array(out, 1);
+ encoder.set_bytes(params, 2);
+ encoder.dispatch_threadgroups(
+ MTL::Size(rows, 1, 1), MTL::Size(threads, 1, 1));
+ }
+
+ DEFINE_NAME(OMLXQwen4QSAFP32TopKIndices)
+ DEFINE_INPUT_OUTPUT_SHAPE()
+ bool is_equivalent(const Primitive& /* other */) const override {
+ return true;
+ }
+ auto state() const {
+ return std::make_tuple(nullptr);
+ }
+};
// ── DC-1: fused decode indexer scan ─────────────────────────────────────────
// One kernel computes the head-summed indexer scores for a single query position
// (s == 1) directly into [B,1,1,S] with fp32 accumulation, replacing the decode
@@ -826,6 +1005,53 @@ array dsa_indexer_scores(
std::move(inputs));
}
+array qwen4_qsa_indexer_scores(
+ const array& queries,
+ const array& pooled_keys,
+ int mask_ratio,
+ int mask_q_offset,
+ StreamOrDevice s) {
+ if (queries.ndim() != 4 || pooled_keys.ndim() != 4) {
+ std::ostringstream msg;
+ msg << "[omlx_glm_kernels.qwen4_qsa_indexer_scores] expected q/k rank "
+ << "4, got " << queries.shape() << " and " << pooled_keys.shape()
+ << ".";
+ throw std::invalid_argument(msg.str());
+ }
+ if (queries.dtype() != pooled_keys.dtype() ||
+ (queries.dtype() != float16 && queries.dtype() != bfloat16)) {
+ throw std::invalid_argument(
+ "[omlx_glm_kernels.qwen4_qsa_indexer_scores] q/k must have matching "
+ "float16 or bfloat16 dtype.");
+ }
+ if (mask_ratio != 4 || mask_q_offset < 0) {
+ std::ostringstream msg;
+ msg << "[omlx_glm_kernels.qwen4_qsa_indexer_scores] requires "
+ << "mask_ratio=4 and a non-negative mask_q_offset, got "
+ << mask_ratio << " and " << mask_q_offset << ".";
+ throw std::invalid_argument(msg.str());
+ }
+
+ auto stream = to_stream(s);
+ auto q = ensure_row_contiguous(queries, stream);
+ auto k = ensure_row_contiguous(pooled_keys, stream);
+ if (Qwen4QSAIndexerScoresPrimitive::unsupported(q, k, stream)) {
+ std::ostringstream msg;
+ msg << "[omlx_glm_kernels.qwen4_qsa_indexer_scores] unsupported shape "
+ << "or layout; expected q [1,4,M,128] and k [1,1,N,128], got "
+ << q.shape() << " and " << k.shape() << ".";
+ throw std::invalid_argument(msg.str());
+ }
+
+ Shape out_shape{1, q.shape(2), k.shape(2)};
+ return array(
+ std::move(out_shape),
+ float32,
+ std::make_shared(
+ stream, mask_ratio, mask_q_offset),
+ std::vector{q, k});
+}
+
array dsa_indexer_scores_mma(
const array& queries,
const array& keys,
@@ -918,6 +1144,31 @@ array dspark_fp32_topk_indices(
std::vector{contiguous_scores});
}
+array qwen4_qsa_topk_indices(
+ const array& scores,
+ int topk,
+ StreamOrDevice s) {
+ if (scores.ndim() != 3 || scores.shape(0) != 1 ||
+ scores.shape(1) < 1 || scores.dtype() != float32 || topk != 512 ||
+ scores.shape(2) < topk) {
+ std::ostringstream msg;
+ msg << "[omlx_glm_kernels.qwen4_qsa_topk_indices] expected FP32 "
+ << "scores [1, M>=1, N>=512] and topk=512, got " << scores.shape()
+ << ", topk=" << topk << ".";
+ throw std::invalid_argument(msg.str());
+ }
+ auto stream = to_stream(s);
+ if (stream.device == Device::cpu) {
+ throw std::invalid_argument("Qwen4 QSA FP32 top-k requires Metal.");
+ }
+ auto contiguous_scores = ensure_row_contiguous(scores, stream);
+ Shape out_shape{1, contiguous_scores.shape(1), topk};
+ return array(
+ std::move(out_shape),
+ uint32,
+ std::make_shared(stream),
+ std::vector{contiguous_scores});
+}
array dsa_decode_scores(
const array& queries,
const array& keys,
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.h b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.h
index d01ed7ff45..acdb83bc8e 100644
--- a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.h
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.h
@@ -39,6 +39,31 @@ mx::array dsa_indexer_scores_mma(
int mask_q_offset = 0,
mx::StreamOrDevice s = {});
+// Qwen4-Exp QSA prefill score fusion. This deliberately narrow ABI consumes
+// q [1,4,M,128] and pooled k [1,1,N,128] in fp16/bf16 and writes the exact
+// selection domain directly as fp32 [1,M,N]:
+//
+// sum_h relu(q_h @ k.T) / sqrt(128)
+//
+// The pooled causal mask is applied in the epilogue, so no [1,4,M,N]
+// intermediate is materialized. Unsupported shapes fail closed at the ABI;
+// the QSA caller retains its portable float32 implementation as fallback.
+mx::array qwen4_qsa_indexer_scores(
+ const mx::array& queries,
+ const mx::array& pooled_keys,
+ int mask_ratio = 4,
+ int mask_q_offset = 0,
+ mx::StreamOrDevice s = {});
+
+// Lossless fixed-width Qwen4 QSA block selection. Scores are the contiguous
+// fp32 [1, M, N] result of qwen4_qsa_indexer_scores; the output is uint32
+// [1, M, 512]. Cutoff ties deliberately retain the highest block indices to
+// match mx.argpartition(scores, kth=-512)[..., -512:] set membership.
+mx::array qwen4_qsa_topk_indices(
+ const mx::array& scores,
+ int topk = 512,
+ mx::StreamOrDevice s = {});
+
mx::array dsa_topk_indices(
const mx::array& scores,
int topk,
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.metal b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.metal
index 9ae186a09b..e3b86da1c3 100644
--- a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.metal
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.metal
@@ -25,6 +25,12 @@ struct OMLXDSATopKParams {
"_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn, \
dsa_indexer_score, itype, bm, bn, bk, wm, wn)
+#define instantiate_qwen4_qsa_indexer_score(iname, itype, bm, bn, bk, wm, wn) \
+ instantiate_kernel( \
+ "qwen4_qsa_indexer_score_" #iname \
+ "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn, \
+ qwen4_qsa_indexer_score, itype, bm, bn, bk, wm, wn)
+
#define instantiate_dsa_topk_indices(iname, itype, topk, threads) \
instantiate_kernel( \
"steel_dsa_topk_indices_" #iname "_topk" #topk "_t" #threads, \
@@ -45,6 +51,12 @@ struct OMLXDSATopKParams {
instantiate_dsa_indexer_score(float16, half, 64, 64, 16, 2, 2);
instantiate_dsa_indexer_score(bfloat16, bfloat16_t, 64, 64, 16, 2, 2);
+// Qwen4 QSA scores use the same validated M3 Steel tile, but write fp32 after
+// reducing the fixed four heads. Keeping this in the existing metallib also
+// lets stale extension builds fail closed at the missing ABI symbol.
+instantiate_qwen4_qsa_indexer_score(float16, half, 64, 64, 16, 2, 2);
+instantiate_qwen4_qsa_indexer_score(bfloat16, bfloat16_t, 64, 64, 16, 2, 2);
+
instantiate_dsa_topk_indices(float16, half, 2048, 1024);
instantiate_dsa_topk_indices(bfloat16, bfloat16_t, 2048, 1024);
instantiate_dsa_topk_indices(float16, half, 512, 1024);
@@ -54,7 +66,19 @@ instantiate_kernel(
"dspark_fp32_topk_indices_topk512_t256",
dspark_fp32_topk_indices,
512,
- 256);
+ 256,
+ false);
+
+// Qwen4's fixed 2048-token budget selects 512 complete four-token blocks.
+// This shares DSpark's O(1)-workspace FP32 radix selector, but reverses the
+// deterministic traversal so cutoff ties match mx.argpartition's highest-index
+// membership exactly.
+instantiate_kernel(
+ "qwen4_qsa_fp32_topk_indices_topk512_t256",
+ dspark_fp32_topk_indices,
+ 512,
+ 256,
+ true);
// ── DC-1: fused decode indexer scan ──────────────────────────────────────────
// One thread per key position: score(key) = sum_h w_h * relu(q_h · k_key), fp32
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_dsa_indexer_score.h b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_dsa_indexer_score.h
index e6ed2a1b04..9e82f074bb 100644
--- a/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_dsa_indexer_score.h
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_dsa_indexer_score.h
@@ -211,15 +211,165 @@ template
}
}
+// Qwen4 QSA's indexer has only four heads, but its portable score expression
+// casts both operands to fp32 and materializes [B,M,H,N] before the ReLU/head
+// reduction. This kernel keeps the same fp32 accumulation and final score
+// dtype while carrying only one MMA tile per thread. The input layout is the
+// natural GEMM-friendly [B,H,M,D] view; the public ABI fixes B=1,H=4,D=128.
+template
+[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void
+qwen4_qsa_indexer_score(
+ const device T* Q [[buffer(0)]],
+ const device T* K [[buffer(1)]],
+ device float* O [[buffer(2)]],
+ const constant GEMMParams* params [[buffer(3)]],
+ const constant int& mask_ratio [[buffer(4)]],
+ const constant int& mask_q_offset [[buffer(5)]],
+ const constant float& score_divisor [[buffer(6)]],
+ uint simd_lane_id [[thread_index_in_simdgroup]],
+ uint simd_group_id [[simdgroup_index_in_threadgroup]],
+ uint3 tid [[threadgroup_position_in_grid]],
+ uint3 lid [[thread_position_in_threadgroup]]) {
+ (void)lid;
+
+ using gemm_kernel = GEMMKernel<
+ T,
+ T,
+ BM,
+ BN,
+ BK,
+ WM,
+ WN,
+ false,
+ true,
+ true,
+ true,
+ float>;
+ using loader_a_t = typename gemm_kernel::loader_a_t;
+ using loader_b_t = typename gemm_kernel::loader_b_t;
+ using mma_t = typename gemm_kernel::mma_t;
+
+ const int tid_y = ((tid.y) << params->swizzle_log) +
+ ((tid.x) & ((1 << params->swizzle_log) - 1));
+ const int tid_x = (tid.x) >> params->swizzle_log;
+ if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) {
+ return;
+ }
+
+ constexpr int H = 4;
+ const int M = params->M;
+ const int N = params->N;
+ const int D = params->K;
+ const int c_row = tid_y * BM;
+ const int c_col = tid_x * BN;
+ const short tgp_bm = short(metal::min(BM, M - c_row));
+ const short tgp_bn = short(metal::min(BN, N - c_col));
+
+ Q += size_t(tid.z) * H * M * D;
+ K += size_t(tid.z) * N * D;
+ O += size_t(tid.z) * M * N + size_t(c_row) * params->ldd + c_col;
+
+ threadgroup T As[gemm_kernel::tgp_mem_size_a];
+ threadgroup T Bs[gemm_kernel::tgp_mem_size_b];
+ thread mma_t mma_op(simd_group_id, simd_lane_id);
+
+ float accum[decltype(mma_op.Ctile)::kElemsPerTile];
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < decltype(mma_op.Ctile)::kElemsPerTile; ++i) {
+ accum[i] = 0.0f;
+ }
+
+ STEEL_PRAGMA_UNROLL
+ for (short h = 0; h < H; ++h) {
+ mma_op.Ctile.clear();
+ const device T* A = Q + size_t(h) * M * D + size_t(c_row) * D;
+ const device T* B = K + size_t(c_col) * D;
+ thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id);
+ thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id);
+
+ for (int d = 0; d < params->gemm_k_iterations_aligned; ++d) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (tgp_bm == BM) {
+ loader_a.load_unsafe();
+ } else {
+ loader_a.load_safe(short2(BK, tgp_bm));
+ }
+ if (tgp_bn == BN) {
+ loader_b.load_unsafe();
+ } else {
+ loader_b.load_safe(short2(BK, tgp_bn));
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ mma_op.mma(As, Bs);
+ loader_a.next();
+ loader_b.next();
+ }
+ threadgroup_barrier(mem_flags::mem_none);
+
+ short ai = 0;
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < decltype(mma_op.Ctile)::kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < decltype(mma_op.Ctile)::kTileCols; ++j) {
+ thread const auto& frag = mma_op.Ctile.frag_at(i, j);
+ STEEL_PRAGMA_UNROLL
+ for (short e = 0; e < decltype(mma_op.Ctile)::kElemsPerFrag; ++e) {
+ accum[ai++] += metal::max(frag[e], 0.0f);
+ }
+ }
+ }
+ }
+
+ const float pooled_sentinel = as_type(uint(0xFF7FFFFF));
+ device float* Dst = O + size_t(mma_op.sm) * params->ldd + mma_op.sn;
+ short ai = 0;
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < decltype(mma_op.Ctile)::kTileRows; ++i) {
+ const int row = c_row + mma_op.sm + i * mma_t::TM_stride;
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < decltype(mma_op.Ctile)::kTileCols; ++j) {
+ const int col_base = c_col + mma_op.sn + j * mma_t::TN_stride;
+ const int out_base =
+ (i * decltype(mma_op.Ctile)::kFragRows) * WM * params->ldd +
+ (j * decltype(mma_op.Ctile)::kFragCols) * WN;
+ STEEL_PRAGMA_UNROLL
+ for (short e = 0; e < decltype(mma_op.Ctile)::kElemsPerFrag; ++e) {
+ const int col = col_base + e;
+ const bool pooled_masked =
+ col >= (mask_q_offset + row + 1) / mask_ratio;
+ const float value = pooled_masked
+ ? pooled_sentinel
+ : accum[ai] / score_divisor;
+ if (row < M && col < N) {
+ Dst[out_base + e] = value;
+ }
+ ai++;
+ }
+ }
+ }
+}
+
+template
METAL_FUNC uint dsa_ordered_key_32(float x) {
- const uint bits = as_type(x);
+ uint bits = as_type(x);
+ if (NUMERIC_ZERO_TIES && (bits & 0x7fffffffu) == 0u) {
+ bits = 0u;
+ }
return (bits & 0x80000000u) ? ~bits : (bits | 0x80000000u);
}
-// Exact FP32 selection for DSpark's decode-consistent index scores. Four
-// byte-wise radix passes identify the cutoff, then a deterministic segmented
-// scan writes the selected set directly in temporal order.
-template
+// Exact FP32 selection for DSpark's decode-consistent index scores and Qwen4
+// QSA block scores. Four byte-wise radix passes identify the cutoff, then a
+// deterministic segmented scan writes the selected set without materializing
+// an O(K) index sheet. DSpark keeps the historical lowest-index-first cutoff
+// tie policy. Qwen4 uses HIGHEST_INDEX_TIES because
+//
+// mx.argpartition(scores, kth=-TOPK)[..., -TOPK:]
+//
+// retains the highest-index members when an exact tie straddles the cutoff.
+// Reversing both segment ownership and each segment's scan makes that policy
+// deterministic without another row pass or a score perturbation.
+template
[[kernel, max_total_threads_per_threadgroup(THREADS)]] void
dspark_fp32_topk_indices(
const device float* scores [[buffer(0)]],
@@ -245,8 +395,10 @@ dspark_fp32_topk_indices(
const uint K = uint(params->K);
const uint segment = (K + THREADS - 1) / THREADS;
- const uint start = tid * segment;
+ const uint logical_tid = HIGHEST_INDEX_TIES ? THREADS - 1 - tid : tid;
+ const uint start = logical_tid * segment;
const uint stop = metal::min(start + segment, K);
+ const uint count = start < K ? stop - start : 0u;
const device float* row_scores = scores + size_t(row) * K;
for (int shift = 24; shift >= 0; shift -= 8) {
@@ -256,8 +408,10 @@ dspark_fp32_topk_indices(
threadgroup_barrier(mem_flags::mem_threadgroup);
const uint prefix = state[0];
- for (uint index = start; index < stop; ++index) {
- const uint key = dsa_ordered_key_32(row_scores[index]);
+ for (uint step = 0; step < count; ++step) {
+ const uint index = HIGHEST_INDEX_TIES ? stop - 1 - step : start + step;
+ const uint key =
+ dsa_ordered_key_32(row_scores[index]);
const bool prefix_match = shift == 24 ||
(key >> uint(shift + 8)) == (prefix >> uint(shift + 8));
if (prefix_match) {
@@ -289,8 +443,10 @@ dspark_fp32_topk_indices(
const uint greater_total = state[1];
uint local_greater = 0;
uint local_ties = 0;
- for (uint index = start; index < stop; ++index) {
- const uint key = dsa_ordered_key_32(row_scores[index]);
+ for (uint step = 0; step < count; ++step) {
+ const uint index = HIGHEST_INDEX_TIES ? stop - 1 - step : start + step;
+ const uint key =
+ dsa_ordered_key_32(row_scores[index]);
local_greater += key > threshold ? 1u : 0u;
local_ties += key == threshold ? 1u : 0u;
}
@@ -343,8 +499,10 @@ dspark_fp32_topk_indices(
uint output_pos = partial_a[simd] + pre_selected;
uint ties_seen = pre_ties;
device uint* row_out = out + size_t(row) * TOPK;
- for (uint index = start; index < stop; ++index) {
- const uint key = dsa_ordered_key_32(row_scores[index]);
+ for (uint step = 0; step < count; ++step) {
+ const uint index = HIGHEST_INDEX_TIES ? stop - 1 - step : start + step;
+ const uint key =
+ dsa_ordered_key_32(row_scores[index]);
bool selected = key > threshold;
if (key == threshold) {
selected = ties_seen < tie_budget;
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_qwen4_qsa_sparse_gqa.h b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_qwen4_qsa_sparse_gqa.h
new file mode 100644
index 0000000000..aba4047d8e
--- /dev/null
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_qwen4_qsa_sparse_gqa.h
@@ -0,0 +1,322 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright © 2026 OpenAI
+
+#pragma once
+
+#include "mlx/backend/metal/kernels/steel/attn/attn.h"
+#include "mlx/backend/metal/kernels/steel/attn/params.h"
+
+using namespace mlx::steel;
+
+struct Qwen4SparseMaxOp {
+ template METAL_FUNC static constexpr T apply(T x, T y) {
+ return metal::max(x, y);
+ }
+};
+
+struct Qwen4SparseSumOp {
+ template METAL_FUNC static constexpr T apply(T x, T y) {
+ return x + y;
+ }
+};
+
+struct Qwen4SparseMulOp {
+ template METAL_FUNC static constexpr T apply(T x, T y) {
+ return x * y;
+ }
+};
+
+struct Qwen4SparseExpSubOp {
+ template METAL_FUNC static constexpr T apply(T x, T y) {
+ return fast::exp2(x - y);
+ }
+};
+
+struct Qwen4SparseDivOp {
+ template METAL_FUNC static constexpr T apply(T x, T y) {
+ return x / y;
+ }
+};
+
+// Exact Qwen4 QSA main attention over query-specific selected four-token
+// blocks.
+//
+// One threadgroup owns one (query row, KV head). Qwen's 12 query heads per
+// KV head are padded to one 16-row Steel MMA tile, letting both main GQA groups
+// reuse each randomly addressed K/V tile without materializing the enormous
+// [query, selected, kv-head, dim] gathered tensors. Invalid early-prefix
+// blocks are masked before online FP32 softmax. The
+// selected block list is chronological, and the zero-to-three causal tail is
+// generated in-kernel, so accumulation follows the checkpoint's dense-mask
+// token order without materializing an expanded 2,051-index tensor.
+// The 128-bit global K/V staging pattern is adapted from mlx-serve's MIT
+// ``msv_attn_p256`` kernel (Copyright 2026 David Dalcu); the query-specific
+// direct-index/GQA organization and Steel MMA implementation are oMLX-specific.
+// clang-format off
+template <
+ typename T,
+ int BK,
+ int DC,
+ int GQA,
+ int H_PAD,
+ int D,
+ int WM,
+ typename IndexT,
+ typename AccumType = float>
+[[kernel, max_total_threads_per_threadgroup(WM * 32)]] void
+qwen4_qsa_sparse_gqa_attention(
+ const device T* Q [[buffer(0)]],
+ const device T* K [[buffer(1)]],
+ const device T* V [[buffer(2)]],
+ const device IndexT* Topk [[buffer(3)]],
+ device T* O [[buffer(4)]],
+ const constant Qwen4QSASparseGQAParams* params [[buffer(5)]],
+ uint simd_lane_id [[thread_index_in_simdgroup]],
+ uint simd_group_id [[simdgroup_index_in_threadgroup]],
+ uint3 tid [[threadgroup_position_in_grid]]) { // clang-format on
+
+ constexpr short kFragSize = 8;
+ constexpr short padQ = 16 / sizeof(T);
+ constexpr short padK = 16 / sizeof(T);
+ constexpr short padV = 16 / sizeof(T);
+
+ constexpr short LDQ = DC + padQ;
+ constexpr short LDK = BK + padK;
+ constexpr short LDV = DC + padV;
+
+ constexpr int kNWarps = WM;
+ constexpr int TQ = H_PAD / (kNWarps * kFragSize);
+ constexpr int TK = BK / kFragSize;
+ constexpr int TDC = DC / kFragSize;
+ constexpr int D_CHUNKS = D / DC;
+
+ static_assert(GQA <= H_PAD, "Qwen GQA heads must fit the padded MMA tile.");
+ static_assert(TQ == 1, "Qwen sparse GQA expects one query-head tile.");
+ static_assert(H_PAD % (kNWarps * kFragSize) == 0,
+ "Padded query heads must divide evenly across simdgroups.");
+ static_assert(BK % kFragSize == 0, "BK must be a multiple of eight.");
+ static_assert(DC % kFragSize == 0, "DC must be a multiple of eight.");
+ static_assert(D % DC == 0, "Head dimension must divide DC.");
+
+ constexpr int tgp_size = WM * 32;
+ const int lane = int(simd_group_id * 32 + simd_lane_id);
+ const int q_pos = int(tid.x);
+ const int kv_head = int(tid.y);
+ const int b = int(tid.z);
+
+ threadgroup T Qs[H_PAD * LDQ];
+ threadgroup T KVs[(BK * LDV > DC * LDK) ? BK * LDV : DC * LDK];
+ threadgroup int selected[BK];
+
+ using MMAFragAcc = BaseMMAFrag;
+ MMATile Qtile;
+ MMATile Ktile;
+ MMATile Stile;
+ MMATile Vtile;
+ MMATile Otile;
+ Otile.clear();
+
+ const short2 simd_coord = MMAFragAcc::get_coord(simd_lane_id);
+ const short sm = simd_coord.y;
+ const short sn = simd_coord.x;
+ const short tm = kFragSize * TQ * simd_group_id;
+ const short Qs_offset = (tm + sm) * LDQ + sn;
+ const short Ks_offset = sm * LDK + sn;
+ const short Vs_offset = sm * LDV + sn;
+
+ const AccumType scale = AccumType(params->scale * M_LOG2E_F);
+ constexpr short rows_per_thread = decltype(Stile)::kRowsPerThread;
+ AccumType max_score[rows_per_thread];
+ AccumType sum_score[rows_per_thread] = {0};
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < rows_per_thread; ++i) {
+ max_score[i] = Limits::finite_min;
+ }
+
+ const int query_head_base = kv_head * GQA;
+ const device T *q_base = Q + size_t(b) * params->Q_strides[0] +
+ size_t(query_head_base) * params->Q_strides[1] +
+ size_t(q_pos) * params->Q_strides[2];
+ const device T *k_base = K + size_t(b) * params->K_strides[0] +
+ size_t(kv_head) * params->K_strides[1];
+ const device T *v_base = V + size_t(b) * params->V_strides[0] +
+ size_t(kv_head) * params->V_strides[1];
+ const device IndexT *topk_base = Topk + size_t(b) * params->Topk_strides[0] +
+ size_t(q_pos) * params->Topk_strides[2];
+
+ const int q_abs = params->q_offset + q_pos;
+ constexpr int kCompressRatio = 4;
+ constexpr int kTail = kCompressRatio - 1;
+ const int selected_tokens = params->topk * kCompressRatio + kTail;
+ const int complete_blocks = (q_abs + 1) / kCompressRatio;
+ const int valid_blocks = metal::min(params->topk, complete_blocks);
+ const int n_tiles = (selected_tokens + BK - 1) / BK;
+
+ for (int ktile = 0; ktile < n_tiles; ++ktile) {
+ const int topk_off = ktile * BK;
+ for (int k = lane; k < BK; k += tgp_size) {
+ const int slot = topk_off + k;
+ int k_pos = -1;
+ if (slot < params->topk * kCompressRatio) {
+ const int block_slot = slot / kCompressRatio;
+ if (block_slot < valid_blocks) {
+ const IndexT raw_block = topk_base[block_slot];
+ const ulong candidate = ulong(raw_block) * ulong(kCompressRatio) +
+ ulong(slot % kCompressRatio);
+ if (candidate < ulong(params->kL) && candidate <= ulong(q_abs)) {
+ k_pos = int(candidate);
+ }
+ }
+ } else if (slot < selected_tokens) {
+ const int tail_offset = slot - params->topk * kCompressRatio;
+ const int candidate = complete_blocks * kCompressRatio + tail_offset;
+ if (candidate < params->kL && candidate <= q_abs) {
+ k_pos = candidate;
+ }
+ }
+ selected[k] = k_pos;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ Stile.clear();
+ STEEL_PRAGMA_UNROLL
+ for (short dchunk = 0; dchunk < D_CHUNKS; ++dchunk) {
+ const int dbase = int(dchunk) * DC;
+ for (int elem = lane; elem < H_PAD * (DC / 8); elem += tgp_size) {
+ const int h = elem / (DC / 8);
+ const int d8 = elem - h * (DC / 8);
+ uint4 word = uint4(0);
+ if (h < GQA) {
+ word = *((const device uint4 *)(q_base +
+ size_t(h) * params->Q_strides[1] +
+ dbase) +
+ d8);
+ }
+ *((threadgroup uint4 *)(Qs + h * LDQ) + d8) = word;
+ }
+ for (int elem = lane; elem < BK * (DC / 8); elem += tgp_size) {
+ const int k = elem / (DC / 8);
+ const int d8 = elem - k * (DC / 8);
+ const int k_pos = selected[k];
+ uint4 word = uint4(0);
+ if (k_pos >= 0) {
+ word = *((const device uint4 *)(k_base +
+ size_t(k_pos) * params->K_strides[2] +
+ dbase) +
+ d8);
+ }
+ thread T *values = (thread T *)&word;
+ const int d = d8 * 8;
+ STEEL_PRAGMA_UNROLL
+ for (short e = 0; e < 8; ++e) {
+ KVs[k + (d + e) * LDK] = values[e];
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ STEEL_PRAGMA_UNROLL
+ for (short dd = 0; dd < TDC; ++dd) {
+ simdgroup_barrier(mem_flags::mem_none);
+ Qtile.template load(&Qs[Qs_offset + dd * kFragSize]);
+ Ktile.template load(
+ &KVs[Ks_offset + dd * kFragSize * LDK]);
+ simdgroup_barrier(mem_flags::mem_none);
+ tile_matmad(Stile, Qtile, Ktile, Stile);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < decltype(Stile)::kElemsPerTile; ++i) {
+ Stile.elems()[i] *= scale;
+ }
+ {
+ using stile_t = decltype(Stile);
+ using selem_t = typename stile_t::elem_type;
+ // Early first-chunk rows can have no complete block, so entire leading
+ // tiles are invalid before the causal tail in the final tile. True
+ // -INFINITY makes those tiles contribute exp2(-inf - finite_max) == 0;
+ // finite_min would incorrectly add one to the softmax denominator.
+ constexpr auto neg_inf = selem_t(-INFINITY);
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < stile_t::kTileRows; ++i) {
+ STEEL_PRAGMA_UNROLL
+ for (short j = 0; j < stile_t::kTileCols; ++j) {
+ const short col_pos = sn + j * stile_t::kFragCols;
+ STEEL_PRAGMA_UNROLL
+ for (short e = 0; e < stile_t::MMAFrag_t::kElemCols; ++e) {
+ if (selected[col_pos + e] < 0) {
+ Stile.frag_at(i, j)[e] = neg_inf;
+ }
+ }
+ }
+ }
+ }
+
+ AccumType new_max[rows_per_thread];
+ AccumType factor[rows_per_thread];
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < rows_per_thread; ++i) {
+ new_max[i] = max_score[i];
+ }
+ Stile.template row_reduce(new_max);
+ Stile.template row_bin_op(new_max);
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < rows_per_thread; ++i) {
+ factor[i] = fast::exp2(max_score[i] - new_max[i]);
+ max_score[i] = new_max[i];
+ }
+ AccumType sum_score_tmp[rows_per_thread] = {0};
+ Stile.template row_reduce(sum_score_tmp);
+ STEEL_PRAGMA_UNROLL
+ for (short i = 0; i < rows_per_thread; ++i) {
+ sum_score[i] = sum_score[i] * factor[i] + sum_score_tmp[i];
+ }
+ Otile.template row_bin_op(factor);
+
+ STEEL_PRAGMA_UNROLL
+ for (short vchunk = 0; vchunk < D_CHUNKS; ++vchunk) {
+ const int dbase = int(vchunk) * DC;
+ for (int elem = lane; elem < BK * (DC / 8); elem += tgp_size) {
+ const int k = elem / (DC / 8);
+ const int d8 = elem - k * (DC / 8);
+ const int k_pos = selected[k];
+ uint4 word = uint4(0);
+ if (k_pos >= 0) {
+ word = *((const device uint4 *)(v_base +
+ size_t(k_pos) * params->V_strides[2] +
+ dbase) +
+ d8);
+ }
+ *((threadgroup uint4 *)(KVs + k * LDV) + d8) = word;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ STEEL_PRAGMA_UNROLL
+ for (short iq = 0; iq < TQ; ++iq) {
+ STEEL_PRAGMA_UNROLL
+ for (short id = 0; id < TDC; ++id) {
+ STEEL_PRAGMA_UNROLL
+ for (short ik = 0; ik < TK; ++ik) {
+ const short kk = ik * kFragSize;
+ const short dd = id * kFragSize;
+ Vtile.template load(
+ &KVs[Vs_offset + kk * LDV + dd]);
+ MMAFragAcc::mma(Otile.frag_at(iq, vchunk * TDC + id),
+ Stile.frag_at(iq, ik), Vtile.frag_at(0, 0),
+ Otile.frag_at(iq, vchunk * TDC + id));
+ }
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+ }
+
+ Otile.template row_bin_op(sum_score);
+ device T *out = O + size_t(b) * params->O_strides[0] +
+ size_t(query_head_base + tm + sm) * params->O_strides[1] +
+ size_t(q_pos) * params->O_strides[2] + sn;
+ const short rows_left = short(GQA - (tm + sm));
+ if (rows_left > 0) {
+ Otile.template store_safe(out, params->O_strides[1],
+ short2(D - sn, rows_left));
+ }
+}
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.cpp
new file mode 100644
index 0000000000..43ab9a909f
--- /dev/null
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.cpp
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: Apache-2.0
+
+#include "qwen4_qsa_sparse_gqa.h"
+
+#include
+#include
+#include
+
+#include "mlx/backend/common/utils.h"
+#include "mlx/backend/metal/device.h"
+#include "mlx/backend/metal/utils.h"
+#include "mlx/ops.h"
+#include "mlx/utils.h"
+
+namespace omlx::glm_kernels {
+
+namespace {
+
+using namespace mlx::core;
+
+std::string current_binary_dir() {
+ static std::string binary_dir = []() {
+ Dl_info info;
+ if (!dladdr(reinterpret_cast(¤t_binary_dir), &info)) {
+ throw std::runtime_error("Unable to get omlx_glm_kernels binary dir.");
+ }
+ return std::filesystem::path(info.dli_fname).parent_path().string();
+ }();
+ return binary_dir;
+}
+
+bool last_dim_contiguous(const array &arr) { return arr.strides(-1) == 1; }
+
+struct Qwen4QSASparseGQAParams {
+ int B;
+ int q_heads;
+ int kv_heads;
+ int qL;
+ int kL;
+ int topk;
+ int gqa_factor;
+ int q_offset;
+
+ float scale;
+
+ int64_t Q_strides[3];
+ int64_t K_strides[3];
+ int64_t V_strides[3];
+ int64_t Topk_strides[3];
+ int64_t O_strides[3];
+};
+
+class Qwen4QSASparseGQAPrimitive : public Primitive {
+public:
+ Qwen4QSASparseGQAPrimitive(Stream stream, float scale, int q_offset,
+ int key_tile, int dimension_tile)
+ : Primitive(stream), scale_(scale), q_offset_(q_offset),
+ key_tile_(key_tile), dimension_tile_(dimension_tile) {}
+
+ static bool unsupported(const array &q, const array &k, const array &v,
+ const array &selected, int q_offset, int key_tile,
+ int dimension_tile, Stream stream) {
+ if (stream.device == Device::cpu || q.dtype() != k.dtype() ||
+ q.dtype() != v.dtype()) {
+ return true;
+ }
+ if (q.dtype() != float16 && q.dtype() != bfloat16) {
+ return true;
+ }
+ if (q.ndim() != 4 || k.ndim() != 4 || v.ndim() != 4 ||
+ selected.ndim() != 4 || selected.dtype() != uint32) {
+ return true;
+ }
+ if (!last_dim_contiguous(q) || !last_dim_contiguous(k) ||
+ !last_dim_contiguous(v) || !last_dim_contiguous(selected)) {
+ return true;
+ }
+ if (q.shape(0) != 1 || k.shape(0) != 1 || v.shape(0) != 1 ||
+ selected.shape(0) != 1 || q.shape(1) != 24 || k.shape(1) != 2 ||
+ v.shape(1) != 2 || q.shape(3) != 256 || k.shape(3) != 256 ||
+ v.shape(3) != 256 || k.shape(2) != v.shape(2) || q.shape(2) <= 0 ||
+ selected.shape(1) != 1 || selected.shape(2) != q.shape(2) ||
+ selected.shape(3) != 512) {
+ return true;
+ }
+ if (q_offset < 0 || q_offset + q.shape(2) > k.shape(2) ||
+ !((dimension_tile == 32 && (key_tile == 128 || key_tile == 256)) ||
+ (dimension_tile == 64 && (key_tile == 64 || key_tile == 128)))) {
+ return true;
+ }
+ return false;
+ }
+
+ void eval_cpu(const std::vector & /* inputs */,
+ std::vector & /* outputs */) override {
+ throw std::runtime_error("Qwen4QSASparseGQAPrimitive has no CPU path.");
+ }
+
+ void eval_gpu(const std::vector &inputs,
+ std::vector &outputs) override {
+ auto &stream = this->stream();
+ auto &device = metal::device(stream.device);
+ const auto &q = inputs[0];
+ const auto &k = inputs[1];
+ const auto &v = inputs[2];
+ const auto &selected = inputs[3];
+ auto &out = outputs[0];
+
+ constexpr int gqa = 12;
+ constexpr int dim = 256;
+ constexpr int wm = 2;
+ constexpr int hpad = 16;
+
+ out.set_data(allocator::malloc(out.nbytes()));
+ Qwen4QSASparseGQAParams params{
+ /* int B = */ 1,
+ /* int q_heads = */ 24,
+ /* int kv_heads = */ 2,
+ /* int qL = */ q.shape(2),
+ /* int kL = */ k.shape(2),
+ /* int topk = */ selected.shape(3),
+ /* int gqa_factor = */ gqa,
+ /* int q_offset = */ q_offset_,
+ /* float scale = */ scale_,
+ /* int64_t Q_strides[3] = */ {q.strides(0), q.strides(1), q.strides(2)},
+ /* int64_t K_strides[3] = */ {k.strides(0), k.strides(1), k.strides(2)},
+ /* int64_t V_strides[3] = */ {v.strides(0), v.strides(1), v.strides(2)},
+ /* int64_t Topk_strides[3] = */
+ {selected.strides(0), selected.strides(1), selected.strides(2)},
+ /* int64_t O_strides[3] = */
+ {out.strides(0), out.strides(1), out.strides(2)}};
+
+ std::string kernel_name;
+ concatenate(kernel_name, "qwen4_qsa_sparse_gqa_", type_to_name(q), "_bk",
+ key_tile_, "_dc", dimension_tile_, "_gqa", gqa, "_hp", hpad,
+ "_d", dim, "_wm", wm);
+
+ auto library = device.get_library("omlx_glm_kernels", current_binary_dir());
+ auto kernel = device.get_kernel(kernel_name, library);
+ auto &encoder = metal::get_command_encoder(stream);
+ encoder.set_compute_pipeline_state(kernel);
+ encoder.set_input_array(q, 0);
+ encoder.set_input_array(k, 1);
+ encoder.set_input_array(v, 2);
+ encoder.set_input_array(selected, 3);
+ encoder.set_output_array(out, 4);
+ encoder.set_bytes(params, 5);
+ encoder.dispatch_threadgroups(MTL::Size(q.shape(2), k.shape(1), 1),
+ MTL::Size(32, wm, 1));
+ }
+
+ DEFINE_NAME(OMLXQwen4QSASparseGQAAttention)
+ DEFINE_INPUT_OUTPUT_SHAPE()
+ bool is_equivalent(const Primitive &other) const override {
+ const auto &rhs = static_cast(other);
+ return scale_ == rhs.scale_ && q_offset_ == rhs.q_offset_ &&
+ key_tile_ == rhs.key_tile_ && dimension_tile_ == rhs.dimension_tile_;
+ }
+ auto state() const {
+ return std::make_tuple(nullptr, scale_, q_offset_, key_tile_,
+ dimension_tile_);
+ }
+
+private:
+ float scale_;
+ int q_offset_;
+ int key_tile_;
+ int dimension_tile_;
+};
+
+} // namespace
+
+array qwen4_qsa_sparse_gqa_attention(const array &queries, const array &keys,
+ const array &values,
+ const array &selected_blocks, float scale,
+ int q_offset, int key_tile,
+ int dimension_tile, StreamOrDevice s) {
+ auto stream = to_stream(s);
+ if (Qwen4QSASparseGQAPrimitive::unsupported(
+ queries, keys, values, selected_blocks, q_offset, key_tile,
+ dimension_tile, stream)) {
+ std::ostringstream msg;
+ msg << "[omlx_glm_kernels.qwen4_qsa_sparse_gqa_attention] expected "
+ << "q=[1,24,M,256], k/v=[1,2,K,256], uint32 selected blocks="
+ << "[1,1,M,512], q_offset>=0, (BK,DC) in "
+ << "{(128,32),(256,32),(64,64),(128,64)}; got " << queries.shape()
+ << ", " << keys.shape() << ", " << values.shape() << ", "
+ << selected_blocks.shape() << ".";
+ throw std::invalid_argument(msg.str());
+ }
+
+ Shape out_shape{queries.shape(0), queries.shape(1), queries.shape(2),
+ queries.shape(3)};
+ return array(std::move(out_shape), queries.dtype(),
+ std::make_shared(
+ stream, scale, q_offset, key_tile, dimension_tile),
+ std::vector{queries, keys, values, selected_blocks});
+}
+
+} // namespace omlx::glm_kernels
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.h b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.h
new file mode 100644
index 0000000000..b62246f4d2
--- /dev/null
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.h
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include "mlx/array.h"
+#include "mlx/stream.h"
+#include "mlx/utils.h"
+
+namespace mx = mlx::core;
+
+namespace omlx::glm_kernels {
+
+mx::array qwen4_qsa_sparse_gqa_attention(
+ const mx::array &queries, const mx::array &keys, const mx::array &values,
+ const mx::array &selected_blocks, float scale, int q_offset,
+ int key_tile = 128, int dimension_tile = 32, mx::StreamOrDevice s = {});
+
+} // namespace omlx::glm_kernels
diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.metal b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.metal
new file mode 100644
index 0000000000..8937e720c0
--- /dev/null
+++ b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.metal
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: Apache-2.0
+
+// Include order is load-bearing: Steel's attention header provides Limits
+// used by the specialized Qwen kernel.
+// clang-format off
+#include "mlx/backend/metal/kernels/utils.h"
+#include "mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.h"
+#include "kernels/steel_qwen4_qsa_sparse_gqa.h"
+// clang-format on
+
+#define instantiate_qwen4_sparse_gqa(tname, dtype, bk, dc) \
+ instantiate_kernel("qwen4_qsa_sparse_gqa_" #tname "_bk" #bk "_dc" #dc \
+ "_gqa12_hp16_d256_wm2", \
+ qwen4_qsa_sparse_gqa_attention, dtype, bk, dc, 12, 16, \
+ 256, 2, uint, float)
+
+instantiate_qwen4_sparse_gqa(float16, half, 128, 32);
+instantiate_qwen4_sparse_gqa(float16, half, 256, 32);
+instantiate_qwen4_sparse_gqa(float16, half, 64, 64);
+instantiate_qwen4_sparse_gqa(float16, half, 128, 64);
+instantiate_qwen4_sparse_gqa(bfloat16, bfloat16_t, 128, 32);
+instantiate_qwen4_sparse_gqa(bfloat16, bfloat16_t, 256, 32);
+instantiate_qwen4_sparse_gqa(bfloat16, bfloat16_t, 64, 64);
+instantiate_qwen4_sparse_gqa(bfloat16, bfloat16_t, 128, 64);
diff --git a/omlx/custom_kernels/glm_moe_dsa/fast.py b/omlx/custom_kernels/glm_moe_dsa/fast.py
index 199c0f2de3..ea4cca56df 100644
--- a/omlx/custom_kernels/glm_moe_dsa/fast.py
+++ b/omlx/custom_kernels/glm_moe_dsa/fast.py
@@ -101,6 +101,9 @@ def _probe_mma_score(ext) -> bool:
NATIVE_SYMBOLS = (
"dsa_decode_scores",
"dsa_indexer_scores",
+ "qwen4_qsa_indexer_scores",
+ "qwen4_qsa_topk_indices",
+ "qwen4_qsa_sparse_gqa_attention",
"dsa_topk_indices",
"dspark_fp32_topk_indices",
"dspark_exact_mxfp8_qmv_pair",
@@ -257,6 +260,95 @@ def dsa_indexer_scores(
return scores
+def qwen4_qsa_indexer_scores(
+ queries: mx.array,
+ pooled_keys: mx.array,
+ mask_ratio: int = 4,
+ mask_q_offset: int = 0,
+ *,
+ stream=None,
+) -> mx.array:
+ """Fused, fp32 Qwen4 QSA block scores for the M3 prefill geometry.
+
+ ``queries`` is ``[1, 4, M, 128]`` and ``pooled_keys`` is
+ ``[1, 1, N, 128]`` in matching bf16/fp16. The result is fp32
+ ``[1, M, N]`` after head-summed ReLU, ``1/sqrt(128)`` scaling, and the
+ pooled-causal mask. The dedicated ABI intentionally has no implicit
+ fallback; ``qsa_fast`` owns the portable float32 fallback.
+ """
+ if _ext is None or not hasattr(_ext, "qwen4_qsa_indexer_scores"):
+ raise RuntimeError(
+ "qwen4_qsa_indexer_scores requires a local extension build that "
+ "exposes the Qwen4 QSA score kernel"
+ )
+ return _ext.qwen4_qsa_indexer_scores(
+ queries,
+ pooled_keys,
+ mask_ratio=mask_ratio,
+ mask_q_offset=mask_q_offset,
+ **_native_stream_kwargs(stream),
+ )
+
+
+def qwen4_qsa_topk_indices(
+ scores: mx.array,
+ topk: int = 512,
+ *,
+ stream=None,
+) -> mx.array:
+ """Select Qwen4's top 512 block indices from fp32 ``[1, M, N]`` scores.
+
+ The native radix path returns only ``[1, M, 512]`` uint32 indices, avoiding
+ the full-width index allocation made by ``mx.argpartition``. Exact cutoff
+ ties retain their highest-index members, matching the set selected by the
+ portable QSA expression. The ABI is deliberately fixed to ``topk=512`` and
+ fails closed when the rebuilt extension or production geometry is absent.
+ """
+ if _ext is None or not hasattr(_ext, "qwen4_qsa_topk_indices"):
+ raise RuntimeError("Qwen4 QSA FP32 top-k kernel is unavailable")
+ return _ext.qwen4_qsa_topk_indices(
+ scores,
+ topk,
+ **_native_stream_kwargs(stream),
+ )
+
+
+def qwen4_qsa_sparse_gqa_attention(
+ queries: mx.array,
+ keys: mx.array,
+ values: mx.array,
+ selected_blocks: mx.array,
+ scale: float,
+ q_offset: int,
+ *,
+ key_tile: int = 128,
+ dimension_tile: int = 32,
+ stream=None,
+) -> mx.array:
+ """Exact Qwen4 main GQA over query-specific selected cache rows.
+
+ The narrow native ABI consumes 512 chronological uint32 block IDs directly,
+ expands each to four tokens, appends the causal tail in-kernel, and
+ keeps QK scores, online softmax state, and the weighted output in fp32.
+ It supports only Qwen3.8-Flash-Next's batch-one ``24q/2kv/D256`` geometry;
+ callers own the portable gathered fallback for every other shape.
+ """
+
+ if _ext is None or not hasattr(_ext, "qwen4_qsa_sparse_gqa_attention"):
+ raise RuntimeError("Qwen4 QSA sparse GQA kernel is unavailable")
+ return _ext.qwen4_qsa_sparse_gqa_attention(
+ queries,
+ keys,
+ values,
+ selected_blocks,
+ scale,
+ q_offset,
+ key_tile,
+ dimension_tile,
+ **_native_stream_kwargs(stream),
+ )
+
+
def dsa_decode_scores(
queries: mx.array,
keys: mx.array,
diff --git a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_ane.mm b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_ane.mm
index 2ce292274c..7ae712c6e2 100644
--- a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_ane.mm
+++ b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_ane.mm
@@ -135,22 +135,20 @@ bool ane_compile_cache_enabled() {
stringByAppendingPathComponent:@"v1"];
}
-// ~/Library/Caches/omlx/ane/v1//.i. The ANE
-// identifier covers weights, shapes, sequence length, and split layout. The
-// remaining path components invalidate artifacts when the cache schema or the
-// OS compiler/runtime changes.
-NSString *ane_compile_cache_directory(NSString *identifier, int ane_instance) {
+// ~/Library/Caches/omlx/ane/v1//. The private ANE
+// runtime keys its compiled-program cache by this descriptor content hash.
+// oMLX only needs a matching cross-process lock; it must not assign this path
+// as the in-memory model URL (#3124).
+NSString *ane_compile_cache_lock_entry(NSString *identifier) {
NSString *os_build =
[[NSProcessInfo processInfo] operatingSystemVersionString];
os_build =
[os_build stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
os_build =
[os_build stringByReplacingOccurrencesOfString:@":" withString:@"_"];
- NSString *entry =
- [NSString stringWithFormat:@"%@.i%d", identifier, ane_instance];
return [[ane_compile_cache_root_directory()
stringByAppendingPathComponent:os_build]
- stringByAppendingPathComponent:entry];
+ stringByAppendingPathComponent:identifier];
}
std::string error_text(NSString *prefix, NSError *error);
@@ -227,39 +225,19 @@ explicit ScopedAneCacheLock(NSString *entry_directory) {
return std::string([value UTF8String]);
}
-void remove_ane_staging_directory(NSString *directory) noexcept {
+void remove_ane_staging_directory(NSString *directory,
+ NSString *cache_lock_entry) noexcept {
if (directory == nil) {
return;
}
- // Resolve before the prefix check: a symlink under the cache root could
- // otherwise redirect the delete outside it while the textual prefix still
- // matched. The resolved path is what removeItemAtPath: will actually touch.
- NSString *root = ane_compile_cache_root_directory();
- NSString *resolved =
- [directory stringByResolvingSymlinksInPath];
- NSString *cache_root = [root stringByResolvingSymlinksInPath];
- NSString *cache_prefix = [cache_root stringByAppendingString:@"/"];
- if (![resolved hasPrefix:cache_prefix]) {
- if ([directory hasPrefix:[root stringByAppendingString:@"/"]]) {
- // A path that sits under the cache root but resolves outside it is not
- // ours to delete: following it would take the delete somewhere this
- // process never staged anything. The temp-directory path below is a
- // different case, it never claimed to be a cache entry.
- NSLog(@"oMLX: ANE compile cache cleanup skipped, %@ resolves outside "
- @"the cache root",
- directory);
- return;
- }
- [[NSFileManager defaultManager] removeItemAtPath:directory error:nil];
- return;
- }
- if (!ane_compile_cache_enabled()) {
+ if (cache_lock_entry == nil) {
[[NSFileManager defaultManager] removeItemAtPath:directory error:nil];
return;
}
try {
- // Compile/load and cleanup mutate the same shared staging path.
- ScopedAneCacheLock cache_lock(directory);
+ // Compile/load and cleanup mutate the same historical temp path. Keep
+ // cleanup in the descriptor-hash lock domain used by cache-enabled loads.
+ ScopedAneCacheLock cache_lock(cache_lock_entry);
[[NSFileManager defaultManager] removeItemAtPath:directory error:nil];
} catch (const std::exception &failure) {
// Cleanup must not make model teardown fail. Leaving staging behind is
@@ -268,37 +246,40 @@ void remove_ane_staging_directory(NSString *directory) noexcept {
}
}
-// Cache-first load for one private-ANE program. When the cache is disabled
-// (the default) this is the historical sequence: staging directory,
-// stage files, compile, load, delete on unload. When enabled, the model URL
-// points at a stable cache path so the private runtime can reuse a program
-// it already compiled in an earlier process; the lock serializes writers,
-// and a restored program whose load fails is invalidated and recompiled
-// exactly once. An unavailable cache root or lock fails open to the
-// historical temp path instead of breaking the load. Apple owns the
-// persistent compiled artifacts; oMLX only stages its MIL and weight inputs,
-// and the caller deletes that staging directory on unload as before. The
-// helper writes `mil` as model.mil and each blob of `weight_files` under
-// weights/ in a directory that has just been cleared.
-NSString *load_or_compile_ane_model(
- id model, NSString *identifier, int ane_instance,
- NSDictionary *execution_options, NSData *mil,
- NSDictionary *weight_files,
- NSString *compile_what, NSString *load_what) {
- NSString *directory = nil;
+struct AneLoadResult {
+ NSString *staging_directory;
+ NSString *cache_lock_entry;
+};
+
+// Cache-first load for one private-ANE program. The in-memory model already
+// derives its model URL and compiled-cache key from the descriptor content
+// hash. Overriding that URL breaks the per-file bundle hash verification added
+// by macOS 27, so both cache modes retain the historical temporary staging
+// path. With caching enabled, compiledModelExists probes Apple's persistent
+// cache directly; a hit skips materialization and compilation. A restored
+// program whose load fails is purged and recompiled exactly once. oMLX owns
+// only temporary MIL and weight inputs, deleting them on unload as before.
+AneLoadResult
+load_or_compile_ane_model(id model, NSString *identifier, int ane_instance,
+ NSDictionary *execution_options, NSData *mil,
+ NSDictionary *weight_files,
+ NSString *compile_what, NSString *load_what) {
+ NSString *directory =
+ [NSTemporaryDirectory() stringByAppendingPathComponent:identifier];
+ NSString *cache_lock_entry = nil;
bool restored = false;
+ bool staged = false;
std::unique_ptr cache_lock;
if (ane_compile_cache_enabled()) {
try {
- directory = ane_compile_cache_directory(identifier, ane_instance);
- // Hold the entry lock from probe through load so a second process
- // compiling the same program waits instead of racing the writes.
- cache_lock = std::make_unique(directory);
- ((void (*)(id, SEL, id))objc_msgSend)(
- model, @selector(setModelURL:),
- [NSURL fileURLWithPath:directory isDirectory:YES]);
- restored = ((BOOL (*)(id, SEL))objc_msgSend)(
- model, @selector(compiledModelExists));
+ cache_lock_entry = ane_compile_cache_lock_entry(identifier);
+ // Hold the descriptor-hash lock from probe through load so a second
+ // process compiling the same program waits instead of racing writes to
+ // the framework-selected temporary staging path.
+ cache_lock = std::make_unique(cache_lock_entry);
+ SEL exists_selector = @selector(compiledModelExists);
+ restored = [model respondsToSelector:exists_selector] &&
+ ((BOOL (*)(id, SEL))objc_msgSend)(model, exists_selector);
if (restored) {
NSLog(@"oMLX: ANE compile cache hit identifier=%@ instance=%d",
identifier, ane_instance);
@@ -313,20 +294,13 @@ void remove_ane_staging_directory(NSString *directory) noexcept {
@"directory",
failure.what());
cache_lock.reset();
- directory = nil;
+ cache_lock_entry = nil;
restored = false;
}
}
- if (directory == nil) {
- directory = [NSTemporaryDirectory()
- stringByAppendingPathComponent:identifier];
- ((void (*)(id, SEL, id))objc_msgSend)(
- model, @selector(setModelURL:),
- [NSURL fileURLWithPath:directory isDirectory:YES]);
- }
auto compile_fresh = [&]() {
// Clear any stale or half-written entry first: a crash mid-compile can
- // leave an incomplete cache entry, and it must never be reused.
+ // leave incomplete staging inputs, and they must never be reused.
[[NSFileManager defaultManager] removeItemAtPath:directory error:nil];
NSString *weight_directory =
[directory stringByAppendingPathComponent:@"weights"];
@@ -352,6 +326,7 @@ void remove_ane_staging_directory(NSString *directory) noexcept {
[compile_what stringByAppendingString:@" compilation failed"],
error));
}
+ staged = true;
};
if (!restored) {
@@ -362,10 +337,15 @@ void remove_ane_staging_directory(NSString *directory) noexcept {
model, @selector(loadWithQoS:options:error:), 21, execution_options,
&error);
if (!ok && restored) {
- // Corrupt or incompatible entry: invalidate it and compile exactly
- // once more before giving up.
+ // Corrupt or incompatible native entry: purge it before compiling exactly
+ // once more, otherwise compiledModelExists would keep returning the same
+ // unusable artifact.
NSLog(@"oMLX: ANE compile cache fallback identifier=%@ instance=%d",
identifier, ane_instance);
+ SEL purge_selector = @selector(purgeCompiledModel);
+ if ([model respondsToSelector:purge_selector]) {
+ ((void (*)(id, SEL))objc_msgSend)(model, purge_selector);
+ }
compile_fresh();
ok = ((BOOL (*)(id, SEL, unsigned int, id, NSError **))objc_msgSend)(
model, @selector(loadWithQoS:options:error:), 21, execution_options,
@@ -376,7 +356,10 @@ void remove_ane_staging_directory(NSString *directory) noexcept {
throw std::runtime_error(error_text(
[load_what stringByAppendingString:@" load failed"], error));
}
- return directory;
+ return {
+ staged ? directory : nil,
+ staged ? cache_lock_entry : nil,
+ };
}
NSData *make_blob(const void *bytes, size_t byte_count) {
@@ -730,8 +713,11 @@ bool row_contiguous(const array &value) {
class SharedAneProgram {
public:
- SharedAneProgram(id model, NSString *directory, NSDictionary *options)
- : model_([model retain]), directory_([directory copy]),
+ SharedAneProgram(id model, const AneLoadResult &load_result,
+ NSDictionary *options)
+ : model_([model retain]),
+ directory_([load_result.staging_directory copy]),
+ cache_lock_entry_([load_result.cache_lock_entry copy]),
execution_options_([options copy]) {}
~SharedAneProgram() {
@@ -741,15 +727,17 @@ bool row_contiguous(const array &value) {
((BOOL (*)(id, SEL, unsigned int, NSError **))objc_msgSend)(
model_, @selector(unloadWithQoS:error:), 21, &error);
}
- remove_ane_staging_directory(directory_);
+ remove_ane_staging_directory(directory_, cache_lock_entry_);
[model_ release];
[directory_ release];
+ [cache_lock_entry_ release];
[execution_options_ release];
}
}
id model_;
NSString *directory_;
+ NSString *cache_lock_entry_;
NSDictionary *execution_options_;
std::mutex evaluation_mutex_;
};
@@ -837,14 +825,14 @@ bool row_contiguous(const array &value) {
id identifier = ((id (*)(id, SEL))objc_msgSend)(
model, @selector(hexStringIdentifier));
- NSString *directory = load_or_compile_ane_model(
- model, identifier, ane_instance, execution_options_, mil,
- @{
+ AneLoadResult load_result = load_or_compile_ane_model(
+ model, identifier, ane_instance, execution_options_, mil, @{
@"weight_data.bin" : data_blob,
@"weight_scale.bin" : scale_blob,
},
@"ANE", @"ANE model");
- directory_ = [directory copy];
+ directory_ = [load_result.staging_directory copy];
+ cache_lock_entry_ = [load_result.cache_lock_entry copy];
model_ = [model retain];
input_surface_ = make_surface(static_cast(input_dim_) *
@@ -939,13 +927,13 @@ bool row_contiguous(const array &value) {
id identifier = ((id (*)(id, SEL))objc_msgSend)(
model, @selector(hexStringIdentifier));
- NSString *directory = load_or_compile_ane_model(
- model, identifier, ane_instance, @{}, mil,
- @{
+ AneLoadResult load_result = load_or_compile_ane_model(
+ model, identifier, ane_instance, @{}, mil, @{
@"weight.bin" : weight_blob,
},
@"ANE", @"ANE model");
- directory_ = [directory copy];
+ directory_ = [load_result.staging_directory copy];
+ cache_lock_entry_ = [load_result.cache_lock_entry copy];
model_ = [model retain];
@@ -1062,7 +1050,7 @@ bool row_contiguous(const array &value) {
((BOOL (*)(id, SEL, unsigned int, NSError **))objc_msgSend)(
model_, @selector(unloadWithQoS:error:), 21, &error);
}
- remove_ane_staging_directory(directory_);
+ remove_ane_staging_directory(directory_, cache_lock_entry_);
[request_ release];
[execution_options_ release];
[event_ release];
@@ -1076,6 +1064,7 @@ bool row_contiguous(const array &value) {
CFRelease(output_surface_);
[model_ release];
[directory_ release];
+ [cache_lock_entry_ release];
}
}
@@ -1240,6 +1229,7 @@ void warmup() {
int sequence_length_;
id model_ = nil;
NSString *directory_ = nil;
+ NSString *cache_lock_entry_ = nil;
IOSurfaceRef input_surface_ = nullptr;
IOSurfaceRef output_surface_ = nullptr;
id input_object_ = nil;
@@ -1561,14 +1551,13 @@ void qwen35_ane_profile_reset() {
}
id identifier = ((id (*)(id, SEL))objc_msgSend)(
model, @selector(hexStringIdentifier));
- NSString *directory = load_or_compile_ane_model(
- model, identifier, ane_instance, execution_options, mil,
- @{
+ AneLoadResult load_result = load_or_compile_ane_model(
+ model, identifier, ane_instance, execution_options, mil, @{
@"weight.bin" : weight_blob,
},
@"ANE procedure bank", @"ANE procedure bank");
- auto program =
- std::make_shared(model, directory, execution_options);
+ auto program = std::make_shared(model, load_result,
+ execution_options);
std::vector> result;
result.reserve(span);
for (int index = 0; index < span; ++index) {
@@ -1750,15 +1739,14 @@ void qwen35_ane_profile_reset() {
}
id identifier = ((id (*)(id, SEL))objc_msgSend)(
model, @selector(hexStringIdentifier));
- NSString *directory = load_or_compile_ane_model(
- model, identifier, ane_instance, execution_options, mil,
- @{
+ AneLoadResult load_result = load_or_compile_ane_model(
+ model, identifier, ane_instance, execution_options, mil, @{
@"weight.bin" : weight_blob,
},
@"ANE SwiGLU/down bank", @"ANE SwiGLU/down bank");
- auto program =
- std::make_shared(model, directory, execution_options);
+ auto program = std::make_shared(model, load_result,
+ execution_options);
std::vector> result;
result.reserve(shapes.size());
for (size_t index = 0; index < shapes.size(); ++index) {
@@ -2418,6 +2406,7 @@ void eval_gpu(const std::vector &inputs,
id qmm_buffer =
(__bridge id)(static_cast(
encoder.get_command_buffer()));
+ [qmm_buffer retain];
if (profiling) {
[qmm_buffer addCompletedHandler:^(id completed) {
const double duration = completed.GPUEndTime - completed.GPUStartTime;
@@ -2429,12 +2418,6 @@ void eval_gpu(const std::vector &inputs,
profile_now_ns() - launch);
}];
}
- id cpu_gpu_buffer = nil;
- if (cpu_weight) {
- cpu_gpu_buffer = qmm_buffer;
- [cpu_gpu_buffer retain];
- }
-
// Keep the wait in a third command buffer. Metal may hold an entire
// command buffer at an encoded wait, even when compute encoders precede
// it, which serializes the otherwise independent GPU remainder behind
@@ -2479,20 +2462,29 @@ void eval_gpu(const std::vector &inputs,
// the GPU is still writing. The detached ANE thread holds its own
// model reference and signals the ticket on its own.
[qmm_buffer waitUntilCompleted];
- if (cpu_gpu_buffer != nil) {
- [cpu_gpu_buffer release];
- }
+ [qmm_buffer release];
throw;
}
- if (cpu_gpu_buffer != nil) {
- [cpu_gpu_buffer waitUntilCompleted];
- [cpu_gpu_buffer release];
- }
+ // ANE completion does not order an independently committed GPU suffix
+ // command buffer before the merge encoder. This is observable on the
+ // first qmm dispatch, when pipeline setup lets ANE finish first: the merge
+ // can otherwise read a partially written suffix. Preserve ANE/GPU overlap,
+ // then join both branches explicitly before consuming either output.
+ const bool gpu_finished_at_ane_done =
+ qmm_buffer.status == MTLCommandBufferStatusCompleted;
+ [qmm_buffer waitUntilCompleted];
+ if (qmm_buffer.status == MTLCommandBufferStatusError) {
+ const std::string error = error_text(
+ @"ANE hybrid GPU suffix command buffer failed", qmm_buffer.error);
+ [qmm_buffer release];
+ throw std::runtime_error(error);
+ }
+ [qmm_buffer release];
if (profiling) {
const uint64_t done = profile_now_ns();
profile_add(profile_category, kAneRegionNs, done - launch);
g_previous_ane_done_ns.store(done, std::memory_order_relaxed);
- if (qmm_buffer.status == MTLCommandBufferStatusCompleted) {
+ if (gpu_finished_at_ane_done) {
profile_add(profile_category, kAneLast, 1);
} else {
profile_add(profile_category, kGpuLast, 1);
@@ -2734,6 +2726,7 @@ AneDispatchGuard ane_guard(producer_buffer, model0_, ticket0, model1_,
id qmm_buffer =
(__bridge id)(static_cast(
encoder.get_command_buffer()));
+ [qmm_buffer retain];
if (profiling) {
[qmm_buffer addCompletedHandler:^(id completed) {
const double duration = completed.GPUEndTime - completed.GPUStartTime;
@@ -2745,11 +2738,6 @@ AneDispatchGuard ane_guard(producer_buffer, model0_, ticket0, model1_,
profile_now_ns() - launch);
}];
}
- id cpu_gpu_buffer = nil;
- if (cpu_weight) {
- cpu_gpu_buffer = qmm_buffer;
- [cpu_gpu_buffer retain];
- }
encoder.commit();
auto model0 = model0_;
@@ -2793,20 +2781,28 @@ AneDispatchGuard ane_guard(producer_buffer, model0_, ticket0, model1_,
// qmm before this frame's MLX arrays can be recycled. The detached ANE
// threads hold their own model references.
[qmm_buffer waitUntilCompleted];
- if (cpu_gpu_buffer != nil) {
- [cpu_gpu_buffer release];
- }
+ [qmm_buffer release];
throw;
}
- if (cpu_gpu_buffer != nil) {
- [cpu_gpu_buffer waitUntilCompleted];
- [cpu_gpu_buffer release];
- }
+ // ANE completion does not order the separately committed GPU suffix
+ // before this primitive's merge. Join the already-overlapped branches so
+ // the merge cannot observe an in-flight qmm output on its first dispatch.
+ const bool gpu_finished_at_ane_done =
+ qmm_buffer.status == MTLCommandBufferStatusCompleted;
+ [qmm_buffer waitUntilCompleted];
+ if (qmm_buffer.status == MTLCommandBufferStatusError) {
+ const std::string error = error_text(
+ @"Dual ANE hybrid GPU suffix command buffer failed",
+ qmm_buffer.error);
+ [qmm_buffer release];
+ throw std::runtime_error(error);
+ }
+ [qmm_buffer release];
if (profiling) {
const uint64_t done = profile_now_ns();
profile_add(profile_category, kAneRegionNs, done - launch);
g_previous_ane_done_ns.store(done, std::memory_order_relaxed);
- if (qmm_buffer.status == MTLCommandBufferStatusCompleted) {
+ if (gpu_finished_at_ane_done) {
profile_add(profile_category, kAneLast, 1);
} else {
profile_add(profile_category, kGpuLast, 1);
diff --git a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp
index b8b5004ecd..5baaf02513 100644
--- a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp
+++ b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp
@@ -131,8 +131,10 @@ QwenQAffineNaxVariant qwen_q_affine_nax_variant(int variant) {
return {/* bm = */ 64, /* bk = */ 32, /* bn = */ 64, 2, 2};
case 5:
return {/* bm = */ 64, /* bk = */ 64, /* bn = */ 64, 4, 1};
- case 6:
- return {/* bm = */ 64, /* bk = */ 64, /* bn = */ 64, 1, 4};
+ // (64, 64, 64, wm=1, wn=4) was variant 6: a 16-column per-simdgroup N
+ // tile that returns wrong output on M5 Max / mlx 0.32.2 (max abs err 5-8
+ // against stock at every shape and bit width; the other tiles match
+ // exactly). Rejected rather than kept as an opt-in footgun.
default: {
std::ostringstream msg;
msg << "Unsupported Qwen affine qmm NAX variant " << variant << ".";
@@ -831,7 +833,7 @@ class Qwen35MoeWeightedSumPrimitive : public Primitive {
} // namespace
bool is_nax_available() {
- // Mirror of mlx::core::metal::is_nax_available() (mlx v0.32.0 device.cpp),
+ // Mirror of mlx::core::metal::is_nax_available() (mlx v0.32.2 device.cpp),
// which libmlx does not export: macOS >= 26.2 and applegpu gen >= 17
// ('p'-suffix parts need gen >= 18).
static bool available = []() {
diff --git a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_qmm_nax.metal b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_qmm_nax.metal
index 038a0d4763..983f7f8ccc 100644
--- a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_qmm_nax.metal
+++ b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_qmm_nax.metal
@@ -99,11 +99,7 @@
instantiate_qwen35_q_affine_qmm_t_nax( \
bits, group_suffix, float16_t, 64, 64, 64, 4, 1); \
instantiate_qwen35_q_affine_qmm_t_nax( \
- bits, group_suffix, bfloat16_t, 64, 64, 64, 4, 1); \
- instantiate_qwen35_q_affine_qmm_t_nax( \
- bits, group_suffix, float16_t, 64, 64, 64, 1, 4); \
- instantiate_qwen35_q_affine_qmm_t_nax( \
- bits, group_suffix, bfloat16_t, 64, 64, 64, 1, 4)
+ bits, group_suffix, bfloat16_t, 64, 64, 64, 4, 1)
define_qwen35_q_affine_qmm_t_nax(4, 64, )
define_qwen35_q_affine_qmm_t_nax(5, 64, )
diff --git a/omlx/custom_kernels/qwen35_prefill/fast.py b/omlx/custom_kernels/qwen35_prefill/fast.py
index 874f070e43..f0b7c80ebf 100644
--- a/omlx/custom_kernels/qwen35_prefill/fast.py
+++ b/omlx/custom_kernels/qwen35_prefill/fast.py
@@ -824,7 +824,34 @@ def qmm_supports_group_size(group_size: int) -> bool:
_stock_nax_cache: bool | None = None
_qmm_nax_cache: bool | None = None
-QMM_NAX_VARIANT = int(os.environ.get("OMLX_QWEN35_QMM_NAX_VARIANT", "0"))
+# Bundled NAX tiles (must match qwen_q_affine_nax_variant in qwen35_prefill.cpp):
+# 0: 64x64x64 wm2 wn2 (stock MLX tile, default) 1: bm 32 2: bm 128
+# 3: bn 128 4: bk 32 5: wm4 wn1
+NAX_QMM_VARIANTS = range(6)
+_qmm_nax_variant_warned = False
+
+
+def _resolve_qmm_nax_variant() -> int:
+ global _qmm_nax_variant_warned
+ raw = os.environ.get("OMLX_QWEN35_QMM_NAX_VARIANT", "0").strip()
+ try:
+ variant = int(raw)
+ except ValueError:
+ variant = -1
+ if variant in NAX_QMM_VARIANTS:
+ return variant
+ if not _qmm_nax_variant_warned:
+ _qmm_nax_variant_warned = True
+ logger.warning(
+ "OMLX_QWEN35_QMM_NAX_VARIANT=%r is not a bundled NAX tile "
+ "(valid: 0-%d); using variant 0",
+ raw,
+ NAX_QMM_VARIANTS[-1],
+ )
+ return 0
+
+
+QMM_NAX_VARIANT = _resolve_qmm_nax_variant()
def _nax_available_fallback(
diff --git a/omlx/engine/base.py b/omlx/engine/base.py
index 8c81dc374c..f8564ad022 100644
--- a/omlx/engine/base.py
+++ b/omlx/engine/base.py
@@ -71,6 +71,7 @@ async def _run_scheduler_preflight_with_cleanup_retry(
request_id: str | None,
eviction_callback: Any | None,
executor: Any | None = None,
+ text_only: bool = False,
) -> None:
"""Run route preflight after transient post-request cleanup settles.
@@ -91,11 +92,13 @@ async def _run_scheduler_preflight_with_cleanup_retry(
eviction_request = scheduler.preflight_eviction_request(
num_prompt_tokens=num_prompt_tokens,
request_id=request_id,
+ text_only=text_only,
)
if eviction_request is None:
scheduler.preflight_or_raise(
num_prompt_tokens=num_prompt_tokens,
request_id=request_id,
+ text_only=text_only,
)
return
@@ -150,6 +153,7 @@ async def _run_scheduler_preflight_with_cleanup_retry(
scheduler.preflight_or_raise(
num_prompt_tokens=num_prompt_tokens,
request_id=request_id,
+ text_only=text_only,
)
return
diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py
index 4cc09001fc..4fc7bfbd1a 100644
--- a/omlx/engine/batched.py
+++ b/omlx/engine/batched.py
@@ -97,6 +97,7 @@ async def _preflight_or_raise_with_eviction(
"_mlx_executor",
None,
),
+ text_only=True,
)
@property
@@ -291,7 +292,7 @@ def _load_model_sync():
get_mlx_executor(), materialize_lazy_state, self._model
)
- # Qwen3.5/3.6 MoE gate+up regroup: concatenate the routed experts'
+ # Supported MoE gate+up regroup: concatenate the routed experts'
# gate and up projections so decode runs 2 gather_qmm launches per
# MoE layer instead of 3 (issue #2238). Bit-exact; runs on the MLX
# executor because it rewrites weights in place.
@@ -310,7 +311,7 @@ def _load_model_sync():
self._model,
)
except Exception:
- logger.debug("Qwen MoE gate+up fusion not applied", exc_info=True)
+ logger.debug("MoE gate+up fusion not applied", exc_info=True)
# Qwen MoE decode router: fuse the top-k select + renormalize chain
# into one launch (the composed argpartition chain is ~2 ms/token on
diff --git a/omlx/engine/dflash.py b/omlx/engine/dflash.py
index a91b3fc7e7..8da9bb5f3a 100644
--- a/omlx/engine/dflash.py
+++ b/omlx/engine/dflash.py
@@ -28,6 +28,7 @@
from ..api.tool_calling import convert_tools_for_template
from ..api.utils import clean_special_tokens, detect_and_strip_partial
from ..cache.observability import CacheRateTracker
+from ..exceptions import PrefillMemoryAbortedError
from ..memory_monitor import (
MemoryMonitor,
raise_if_prefill_exceeds,
@@ -335,7 +336,12 @@ def __init__(
self._tokenizer_obj = None
self._executor_tokenizer = None
self._loaded = False
- self._active_request = False
+ # DFlash runs outside Scheduler, so memory-pressure aborts cannot use
+ # EngineCore's request registry. Keep the stop events for every
+ # submitted generation instead; the process memory enforcer calls
+ # abort_all_requests() to signal them at the next DFlash event boundary.
+ self._stop_events_lock = threading.Lock()
+ self._active_stop_events: set[threading.Event] = set()
self._model_type_str = None
self._fallback_engine: BaseEngine | None = None
self._in_fallback_mode = False
@@ -1286,7 +1292,7 @@ def _run_generate_streaming(
for event in event_iter:
if stop_event.is_set():
- logger.info("DFlash generation aborted by client")
+ logger.info("DFlash generation abort requested")
break
if isinstance(event, TokenEvent):
@@ -1389,7 +1395,6 @@ def _run_generate_streaming(
queue.put(("", [], True, {"aborted": stop_event.is_set()})),
loop,
)
- self._active_request = False
def _tokenize_prompt(self, prompt: str | list[int]) -> list[int]:
"""Return prompt IDs without re-tokenizing an already-tokenized prompt."""
@@ -1397,6 +1402,14 @@ def _tokenize_prompt(self, prompt: str | list[int]) -> list[int]:
return list(prompt)
return list(self._tokenizer_obj.encode(prompt))
+ def _register_stop_event(self, stop_event: threading.Event) -> None:
+ with self._stop_events_lock:
+ self._active_stop_events.add(stop_event)
+
+ def _unregister_stop_event(self, stop_event: threading.Event) -> None:
+ with self._stop_events_lock:
+ self._active_stop_events.discard(stop_event)
+
async def generate(
self,
prompt: str | list[int],
@@ -1461,7 +1474,6 @@ async def generate(
from ..engine_core import get_mlx_executor
- loop = asyncio.get_running_loop()
stop_event = threading.Event()
# Admin visibility: DFlash bypasses the scheduler, so the Active
# Models card reads this activity instead of a scheduler snapshot.
@@ -1501,7 +1513,7 @@ def _run():
parser_final = None
for event in event_iter:
if stop_event.is_set():
- logger.info("DFlash generation aborted by client")
+ logger.info("DFlash generation abort requested")
break
if isinstance(event, TokenEvent):
if first_token_at is None:
@@ -1541,10 +1553,17 @@ def _run():
except Exception as exc:
logger.debug(f"event_iter.close() raised: {exc}")
self._end_runtime_cache_request(cache_manager)
- self._active_request = False
- self._active_request = True
- future = loop.run_in_executor(get_mlx_executor(), _run)
+ self._register_stop_event(stop_event)
+ try:
+ future = get_mlx_executor().submit(_run)
+ except Exception:
+ self._unregister_stop_event(stop_event)
+ self._end_activity(activity_id)
+ raise
+ # Use the executor future: asyncio cancellation can precede worker exit.
+ future.add_done_callback(lambda _: self._unregister_stop_event(stop_event))
+ future = asyncio.wrap_future(future)
try:
try:
(
@@ -1571,6 +1590,11 @@ def _run():
finally:
self._end_activity(activity_id)
+ if stop_event.is_set():
+ raise PrefillMemoryAbortedError(
+ "Request aborted: process memory limit exceeded"
+ )
+
if parser_session is not None:
# Parser already converted protocol markers to ...
# and stripped channel marker tokens, so just join the visible
@@ -1709,24 +1733,31 @@ async def stream_generate(
# Admin visibility: DFlash bypasses the scheduler, so the Active
# Models card reads this activity instead of a scheduler snapshot.
activity_id = self._begin_activity("generate", detail="generating")
- self._active_request = True
- future = loop.run_in_executor(
- get_mlx_executor(),
- self._run_generate_streaming,
- prompt_tokens,
- max_tokens,
- temperature,
- top_p,
- top_k,
- min_p,
- repetition_penalty,
- int(repetition_context_size),
- seed,
- tools,
- queue,
- loop,
- stop_event,
- )
+ self._register_stop_event(stop_event)
+ try:
+ future = get_mlx_executor().submit(
+ self._run_generate_streaming,
+ prompt_tokens,
+ max_tokens,
+ temperature,
+ top_p,
+ top_k,
+ min_p,
+ repetition_penalty,
+ int(repetition_context_size),
+ seed,
+ tools,
+ queue,
+ loop,
+ stop_event,
+ )
+ except Exception:
+ self._unregister_stop_event(stop_event)
+ self._end_activity(activity_id)
+ raise
+ # Use the executor future: asyncio cancellation can precede worker exit.
+ future.add_done_callback(lambda _: self._unregister_stop_event(stop_event))
+ future = asyncio.wrap_future(future)
total_text = ""
total_completion = 0
@@ -1736,6 +1767,11 @@ async def stream_generate(
while True:
new_text, new_tokens, finished, metrics = await queue.get()
+ if metrics and metrics.get("aborted"):
+ raise PrefillMemoryAbortedError(
+ "Request aborted: process memory limit exceeded"
+ )
+
if think_prefix_pending and new_text:
new_text = self._think_prefix_text() + new_text
think_prefix_pending = False
@@ -1973,11 +2009,38 @@ def has_active_requests(self) -> bool:
and self._fallback_engine.has_active_requests()
):
return True
- if self._active_request:
- return True
+ with self._stop_events_lock:
+ if self._active_stop_events:
+ return True
with self._active_lock:
return self._active_count > 0
+ async def abort_all_requests(self) -> int:
+ """Signal every in-flight DFlash generation to stop.
+
+ The process memory enforcer relies on this method at hard pressure.
+ DFlash does not use Scheduler request objects, so its per-generation
+ threading events are the authoritative abort handles.
+ """
+ aborted = 0
+ fallback = self._fallback_engine
+ if fallback is not None:
+ abort_fallback = getattr(fallback, "abort_all_requests", None)
+ if callable(abort_fallback):
+ result = abort_fallback()
+ if hasattr(result, "__await__"):
+ result = await result
+ if isinstance(result, (int, float)):
+ aborted += max(0, int(result))
+
+ with self._stop_events_lock:
+ stop_events = tuple(self._active_stop_events)
+ for stop_event in stop_events:
+ if not stop_event.is_set():
+ stop_event.set()
+ aborted += 1
+ return aborted
+
def get_stats(self) -> dict[str, Any]:
return {
"engine_type": "dflash",
diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py
index f2ca49c7ea..bfda9f6288 100644
--- a/omlx/engine/vlm.py
+++ b/omlx/engine/vlm.py
@@ -102,6 +102,7 @@
VLM_LANGUAGE_PROMPT_KWARGS = ("mm_token_type_ids", "token_type_ids")
COHERE2_MOE_MODEL_TYPE = "cohere2_moe"
+QWEN4_EXP_MODEL_TYPE = "qwen4_exp"
MINIMAX_M3_VL_MODEL_TYPE = "minimax_m3_vl"
MINIMAX_M3_MODEL_TYPES = {"minimax_m3", MINIMAX_M3_VL_MODEL_TYPE}
@@ -170,6 +171,28 @@ def _is_missing_chat_template_error(exc: ValueError) -> bool:
)
+def _capture_vlm_position_state(lm: Any, extra_kwargs: dict[str, Any]) -> None:
+ """Copy the language model's per-request mRoPE state into extra_kwargs.
+
+ get_input_embeddings() leaves ``_position_ids`` and ``_rope_deltas`` lazy
+ on the executor's default stream. They are materialized here because a
+ lazy default-stream input inside the engine-stream prefill graph deadlocks
+ the Qwen ANE prefill primitive on restored-prefix requests (#3305, the
+ same class as the text-only seed in #3279).
+ """
+ if lm is None:
+ return
+ pid = getattr(lm, "_position_ids", None)
+ if pid is not None and "position_ids" not in extra_kwargs:
+ extra_kwargs["position_ids"] = pid
+ rd = getattr(lm, "_rope_deltas", None)
+ if rd is not None:
+ extra_kwargs["_captured_rope_deltas"] = rd
+ lazy_state = [v for v in (pid, rd) if isinstance(v, mx.array)]
+ if lazy_state:
+ mx.eval(*lazy_state)
+
+
def _apply_minimax_m3_thinking_mode(
model_type: str | None,
template_kwargs: dict[str, Any],
@@ -906,6 +929,20 @@ def _should_pack_minimax_m3_shared_expert(args: Any) -> bool:
)
+def _model_shard_matcher(model_dir: Path):
+ """Return a predicate for safetensors shards directly under *model_dir*."""
+ target_dir = model_dir.resolve()
+
+ def matches(filename: object) -> bool:
+ try:
+ path = Path(filename)
+ return path.suffix == ".safetensors" and path.parent.resolve() == target_dir
+ except (TypeError, OSError, RuntimeError):
+ return False
+
+ return matches
+
+
@contextlib.contextmanager
def _force_minimax_m3_moe_sanitize_on_load(model_dir: Path):
"""Force mlx-vlm's MiniMax M3 MoE sanitize path for MLX-format checkpoints.
@@ -932,7 +969,7 @@ def _force_minimax_m3_moe_sanitize_on_load(model_dir: Path):
original_safe_open = safetensors.safe_open
original_sanitize_moe_weights = _minimax_m3_vl._sanitize_moe_weights
- target_dir = model_dir.resolve()
+ is_target_shard = _model_shard_matcher(model_dir)
class _SafeOpenMetadataWrapper:
def __init__(self, inner):
@@ -957,11 +994,7 @@ def metadata(self):
def _patched_safe_open(filename, *args, **kwargs):
handle = original_safe_open(filename, *args, **kwargs)
- try:
- path = Path(filename).resolve()
- except TypeError:
- return handle
- if path.parent == target_dir and path.suffix == ".safetensors":
+ if is_target_shard(filename):
return _SafeOpenMetadataWrapper(handle)
return handle
@@ -1033,6 +1066,67 @@ def _patched_sanitize_moe_weights(weights: dict, args: Any) -> None:
_minimax_m3_vl._sanitize_moe_weights = original_sanitize_moe_weights
+@contextlib.contextmanager
+def _force_qwen4_exp_sanitize_on_load(model_dir: Path):
+ """Run vendored-model key sanitization before quantization selection.
+
+ Converted MLX checkpoints legitimately declare ``format=mlx``, but the
+ published Qwen4 layout still uses ``model.language_model.*`` and
+ ``model.visual.*`` names. mlx-vlm normally skips ``Model.sanitize`` for
+ MLX-format files, which makes its quantization predicate inspect the wrong
+ names and leaves every ``scales``/``biases`` tensor unmatched. Hide only
+ the format marker for this model and this load so sanitization happens at
+ the point expected by the upstream loader: before ``nn.quantize``.
+ """
+ model_type = _read_config_model_type(model_dir)
+ if model_type not in ("qwen4_exp", "glm5_next"):
+ yield
+ return
+
+ import safetensors
+
+ original_safe_open = safetensors.safe_open
+ is_target_shard = _model_shard_matcher(model_dir)
+
+ class _SafeOpenMetadataWrapper:
+ def __init__(self, inner):
+ self._inner = inner
+
+ def __enter__(self):
+ self._inner.__enter__()
+ return self
+
+ def __exit__(self, *args):
+ return self._inner.__exit__(*args)
+
+ def __getattr__(self, name):
+ return getattr(self._inner, name)
+
+ def metadata(self):
+ metadata = self._inner.metadata()
+ if isinstance(metadata, dict) and metadata.get("format") == "mlx":
+ metadata = dict(metadata)
+ metadata.pop("format", None)
+ return metadata
+
+ def _patched_safe_open(filename, *args, **kwargs):
+ handle = original_safe_open(filename, *args, **kwargs)
+ if is_target_shard(filename):
+ return _SafeOpenMetadataWrapper(handle)
+ return handle
+
+ safetensors.safe_open = _patched_safe_open
+ try:
+ logger.info(
+ "%s pre-quantization sanitize active for %s",
+ model_type,
+ model_dir.name,
+ )
+ yield
+ finally:
+ safetensors.safe_open = original_safe_open
+
+
@contextlib.contextmanager
def _remap_nested_visual_on_load(model_dir: Path):
"""Remap ``language_model.model.visual.*`` → ``vision_tower.*`` during
@@ -1117,7 +1211,7 @@ def _uses_mrope(vlm_model) -> bool:
return False
-# Qwen-style VLMs: vision_tower takes (pixel_values, grid_thw)
+# Qwen-style VLMs: vision_tower takes (pixel_values, grid_thw).
_QWEN_VISION_MODELS = {
"qwen3_5",
"qwen3_5_moe",
@@ -1127,6 +1221,9 @@ def _uses_mrope(vlm_model) -> bool:
"qwen2_5_vl",
}
+# Grid-based VLMs whose flat vision features can be split with grid_thw.
+_GRID_VISION_MODELS = _QWEN_VISION_MODELS | {"glm5_next"}
+
# Conservative fallback upper bound on image-placeholder tokens per image
# content part. Used by ``preflight_chat`` only when the actual
@@ -1143,9 +1240,10 @@ def _uses_mrope(vlm_model) -> bool:
def _derive_image_token_upper_bound(processor: Any) -> int:
"""Derive the per-image token upper bound from the processor config.
- Qwen-style image processors expose ``max_pixels`` (an *area*) and
- pack pixels into ``patch_size`` × ``patch_size`` patches, then merge
- ``merge_size`` × ``merge_size`` patches into one model token. The
+ GLM processors expose the final ``max_image_tokens`` bound directly.
+ Qwen-style image processors expose ``max_pixels`` (an *area*) and pack
+ pixels into ``patch_size`` × ``patch_size`` patches, then merge
+ ``merge_size`` × ``merge_size`` patches into one model token. Their
per-image token bound is therefore::
max_tokens = max_pixels / (patch_size**2 * merge_size**2)
@@ -1157,6 +1255,9 @@ def _derive_image_token_upper_bound(processor: Any) -> int:
if processor is None:
return _IMAGE_TOKEN_UPPER_BOUND_FALLBACK
ip = getattr(processor, "image_processor", None) or processor
+ max_image_tokens = getattr(ip, "max_image_tokens", None)
+ if isinstance(max_image_tokens, int) and max_image_tokens > 0:
+ return max(max_image_tokens, _IMAGE_TOKEN_UPPER_BOUND_FALLBACK)
max_pixels = getattr(ip, "max_pixels", None)
patch_size = getattr(ip, "patch_size", None)
merge_size = getattr(ip, "merge_size", None)
@@ -1292,8 +1393,13 @@ def _count_image_tokens_real(
ms = getattr(ip, "merge_size", None)
minp = getattr(ip, "min_pixels", None)
maxp = getattr(ip, "max_pixels", None)
- qwen_ok = all(
- isinstance(x, int) and x > 0 for x in (ps, ms, minp, maxp)
+ qwen_ok = all(isinstance(x, int) and x > 0 for x in (ps, ms, minp, maxp))
+ patch_counter = getattr(ip, "get_number_of_image_patches", None)
+ glm_ok = (
+ callable(patch_counter)
+ and isinstance(ms, int)
+ and ms > 0
+ and isinstance(getattr(ip, "max_image_tokens", None), int)
)
total = 0
@@ -1306,9 +1412,14 @@ def _count_image_tokens_real(
continue
if part.get("type") not in ("image_url", "image", "input_image"):
continue
- wh = _read_image_dims(part) if qwen_ok else None
+ wh = _read_image_dims(part) if qwen_ok or glm_ok else None
if wh is None:
total += upper_bound
+ elif glm_ok:
+ try:
+ total += int(patch_counter(wh[1], wh[0]) // (ms**2))
+ except Exception:
+ total += upper_bound
else:
total += _smart_resize_tokens(wh[1], wh[0], ps, ms, minp, maxp)
return total
@@ -1365,6 +1476,7 @@ async def _preflight_or_raise_with_eviction(
*,
num_prompt_tokens: int,
request_id: str | None,
+ text_only: bool = False,
) -> None:
await _run_scheduler_preflight_with_cleanup_retry(
scheduler,
@@ -1376,6 +1488,7 @@ async def _preflight_or_raise_with_eviction(
"_mlx_executor",
None,
),
+ text_only=text_only,
)
@property
@@ -1568,6 +1681,7 @@ def _load_vlm_sync():
_strip_audio_config_if_orphaned(Path(self._model_name)),
_drop_gemma4_mlx_shared_kv_extras_on_load(Path(self._model_name)),
_force_minimax_m3_moe_sanitize_on_load(Path(self._model_name)),
+ _force_qwen4_exp_sanitize_on_load(Path(self._model_name)),
_remap_nested_visual_on_load(Path(self._model_name)),
_transpose_qwen35_mlx_vision_patch_embed_on_load(
Path(self._model_name)
@@ -1581,19 +1695,25 @@ def _load_vlm_sync():
model, processor = custom_loaded
return model, processor
- if _read_config_model_type(self._model_name) == COHERE2_MOE_MODEL_TYPE:
+ model_type = _read_config_model_type(self._model_name)
+ if model_type == COHERE2_MOE_MODEL_TYPE:
return _load_cohere2_moe_text_model(
self._model_name,
trust_remote_code=self._trust_remote_code,
)
-
with _load_optiq_vision_sidecar_on_load(
Path(self._model_name)
):
- return vlm_load(
+ load_kwargs = {
+ "trust_remote_code": self._trust_remote_code,
+ }
+ if model_type == QWEN4_EXP_MODEL_TYPE:
+ load_kwargs["lazy"] = True
+ loaded = vlm_load(
self._model_name,
- trust_remote_code=self._trust_remote_code,
+ **load_kwargs,
)
+ return loaded
loop = asyncio.get_running_loop()
self._vlm_model, self._processor = await loop.run_in_executor(
@@ -1648,7 +1768,7 @@ def _load_vlm_sync():
except Exception:
logger.debug("t5 bias free skipped", exc_info=True)
- # Qwen3.5/3.6 MoE gate+up regroup: concatenate the routed experts'
+ # Supported MoE gate+up regroup: concatenate the routed experts'
# gate and up projections so decode runs 2 gather_qmm launches per
# MoE layer instead of 3 (issue #2238). Bit-exact; also swaps the
# mlx-vlm target-verify helper for a fused-aware version. Runs on
@@ -1668,7 +1788,7 @@ def _load_vlm_sync():
self._vlm_model,
)
except Exception:
- logger.debug("Qwen MoE gate+up fusion not applied", exc_info=True)
+ logger.debug("MoE gate+up fusion not applied", exc_info=True)
_fix_processor_none_pixels(self._processor)
self._diffusion_family = self._detect_diffusion_family()
@@ -1756,6 +1876,12 @@ def _load_vlm_sync():
scheduler = self._engine.engine.scheduler
if self._model_settings is not None:
tq_enabled = getattr(self._model_settings, "turboquant_kv_enabled", False)
+ if tq_enabled and self.model_type == "glm5_next":
+ logger.warning(
+ "TurboQuant KV cache is not supported for GLM-5.3-Flash's "
+ "composite latent/indexer cache; using the native cache layout"
+ )
+ tq_enabled = False
if tq_enabled:
from ..patches.turboquant_attention import (
apply_turboquant_attention_patch,
@@ -2003,6 +2129,18 @@ def _enable_ane_prefill():
scheduler,
requested_ane_sequence_length,
)
+ # The scheduler snapshotted model info before these
+ # banks existed; price the compiled I/O surfaces now so
+ # admission charges them while the banks are resident.
+ from ..patches.qwen35_ane_prefill import (
+ ane_prefill_transient_bytes,
+ )
+
+ monitor = getattr(scheduler, "memory_monitor", None)
+ if monitor is not None:
+ monitor.set_ane_prefill_transient_bytes(
+ ane_prefill_transient_bytes(self._vlm_model)
+ )
except Exception:
logger.warning("Qwen ANE prefill not enabled", exc_info=True)
@@ -2383,6 +2521,45 @@ def _format_messages_for_vlm_template(
)
):
formatted_messages.append(msg)
+ elif model_type == "glm5_next" and msg_num_images > 0:
+ # mlx-vlm does not yet register glm5_next in MODEL_CONFIG, so
+ # get_message_json() treats it as unsupported and its generic
+ # fallback strips image parts. Preserve their relative order
+ # as template-visible markers; the checkpoint's native chat
+ # template expands each marker to the GLM image token triplet.
+ glm_content: list[Any] = []
+ inserted_images = 0
+ if isinstance(raw_content, list):
+ for item in raw_content:
+ if isinstance(item, dict):
+ item_type = item.get("type", "")
+ item_text = item.get("text", "")
+ else:
+ item_type = getattr(item, "type", "")
+ item_text = getattr(item, "text", "")
+
+ if item_type in image_part_types:
+ if inserted_images < msg_num_images:
+ glm_content.append({"type": "image"})
+ inserted_images += 1
+ elif item_type == "text":
+ glm_content.append({"type": "text", "text": item_text})
+ elif isinstance(item, str):
+ glm_content.append(item)
+
+ if inserted_images < msg_num_images:
+ glm_content[:0] = [
+ {"type": "image"}
+ for _ in range(msg_num_images - inserted_images)
+ ]
+ if not any(
+ isinstance(item, str)
+ or (isinstance(item, dict) and item.get("type") == "text")
+ for item in glm_content
+ ):
+ glm_content.append({"type": "text", "text": content})
+
+ formatted_messages.append({"role": role, "content": glm_content})
else:
formatted = get_message_json(
model_type,
@@ -2395,7 +2572,7 @@ def _format_messages_for_vlm_template(
)
# Collapse text-only list content to plain string so that
# simplified chat templates (without render_content macro)
- # can handle it. Image/audio/video parts stay as list.
+ # can handle it. Image/audio parts stay as a list.
fc = formatted.get("content")
if isinstance(fc, list) and all(
isinstance(p, dict) and p.get("type") == "text" for p in fc
@@ -2488,8 +2665,6 @@ def _compute_vision_features(
# Strategy 2: qwen-style (vision_tower + grid_thw)
if model_type in _QWEN_VISION_MODELS:
grid_thw = extra_model_inputs.get("image_grid_thw")
- if grid_thw is None:
- grid_thw = extra_model_inputs.get("video_grid_thw")
if grid_thw is None:
return None
dtype = model.vision_tower.patch_embed.proj.weight.dtype
@@ -2582,13 +2757,14 @@ def _split_vision_features(
return result
# Qwen: flat (total_merged_tokens, dim) → split using grid_thw
- if model_type in _QWEN_VISION_MODELS and features.ndim == 2:
+ if model_type in _GRID_VISION_MODELS and features.ndim == 2:
grid_thw = extra_model_inputs.get("image_grid_thw")
if grid_thw is None:
return None
- spatial_merge_size = getattr(
- self._vlm_model.vision_tower, "spatial_merge_size", 2
- )
+ vision_tower = getattr(self._vlm_model, "vision_tower", None)
+ if vision_tower is None:
+ vision_tower = getattr(self._vlm_model, "vision_model", None)
+ spatial_merge_size = getattr(vision_tower, "spatial_merge_size", 2)
merge_sq = spatial_merge_size**2
per_image_tokens = []
for i in range(num_images):
@@ -2756,12 +2932,19 @@ def _prepare_vision_inputs(
num_audios = len(audio) if audio else 0
model_type = self.model_type or ""
- if model_type == COHERE2_MOE_MODEL_TYPE and (num_images > 0 or num_audios > 0):
+ if model_type == COHERE2_MOE_MODEL_TYPE and (
+ num_images > 0 or num_audios > 0
+ ):
raise InvalidRequestError(
"Cohere2 MoE is a text-only model and does not support "
"image or audio input.",
field="messages",
)
+ if model_type == QWEN4_EXP_MODEL_TYPE and num_audios > 0:
+ raise InvalidRequestError(
+ "Qwen4-Exp supports text and image input but not audio.",
+ field="messages",
+ )
# Normalize audio to numpy float32 arrays expected by processor.
# Request-facing string paths are rejected before this point; remaining
@@ -2789,7 +2972,9 @@ def _prepare_vision_inputs(
try:
formatted_messages, image_message_ranges = (
self._format_messages_for_vlm_template(
- messages, num_images=num_images, num_audios=num_audios
+ messages,
+ num_images=num_images,
+ num_audios=num_audios,
)
)
except Exception as e:
@@ -2979,7 +3164,11 @@ def _prepare_vision_inputs(
extra_model_inputs = {
k: v
for k, v in inputs.items()
- if k not in ("input_ids", "attention_mask", "pixel_values")
+ if k not in (
+ "input_ids",
+ "attention_mask",
+ "pixel_values",
+ )
and v is not None
}
@@ -3119,14 +3308,9 @@ def _prepare_vision_inputs(
# global state that gets overwritten by subsequent calls.
# Storing per-request ensures correct position computation
# when multiple VLM requests are batched.
- lm = getattr(self._vlm_model, "language_model", None)
- if lm is not None:
- pid = getattr(lm, "_position_ids", None)
- if pid is not None and "position_ids" not in extra_kwargs:
- extra_kwargs["position_ids"] = pid
- rd = getattr(lm, "_rope_deltas", None)
- if rd is not None:
- extra_kwargs["_captured_rope_deltas"] = rd
+ _capture_vlm_position_state(
+ getattr(self._vlm_model, "language_model", None), extra_kwargs
+ )
# Extract token IDs as list
token_ids = (
@@ -3715,19 +3899,23 @@ async def preflight_chat(
return
# Count images from the ORIGINAL messages (the stripped
# ``text_messages`` no longer has the image content-parts).
- num_tokens += _count_image_tokens_real(
+ image_tokens = _count_image_tokens_real(
messages,
getattr(self, "_processor", None),
upper_bound=_derive_image_token_upper_bound(
getattr(self, "_processor", None)
),
)
+ num_tokens += image_tokens
scheduler = getattr(getattr(self._engine, "engine", None), "scheduler", None)
if scheduler is None:
_warn_scheduler_unreachable_once(self, "preflight_chat")
return
await self._preflight_or_raise_with_eviction(
- scheduler, num_prompt_tokens=num_tokens, request_id=request_id
+ scheduler,
+ num_prompt_tokens=num_tokens,
+ request_id=request_id,
+ text_only=image_tokens == 0,
)
async def preflight_completion(
@@ -3760,7 +3948,10 @@ async def preflight_completion(
_warn_scheduler_unreachable_once(self, "preflight_completion")
return
await self._preflight_or_raise_with_eviction(
- scheduler, num_prompt_tokens=num_tokens, request_id=request_id
+ scheduler,
+ num_prompt_tokens=num_tokens,
+ request_id=request_id,
+ text_only=True,
)
async def stream_chat(
diff --git a/omlx/engine_core.py b/omlx/engine_core.py
index 9f99d0e165..bb9aaadabe 100644
--- a/omlx/engine_core.py
+++ b/omlx/engine_core.py
@@ -44,12 +44,9 @@
from .output_collector import RequestOutputCollector, RequestStreamState
from .request import Request, RequestOutput, SamplingParams
from .scheduler import Scheduler, SchedulerConfig, _sync_and_clear_cache
-from .utils.compile_cache import (
- clear_thread_compile_cache,
- compile_cache_clear_available,
-)
from .utils.fatal import FATAL_TEARDOWN_TIMEOUT_S, fatal_exit
from .utils.hardware import format_bytes
+from .utils.metal_sync import clear_thread_streams
logger = logging.getLogger(__name__)
@@ -81,22 +78,21 @@ def _raise_request_output_error(output: RequestOutput) -> None:
_global_mlx_executor: concurrent.futures.ThreadPoolExecutor | None = None
-# Fallback only: used when the MLX compile-cache clear symbol is unavailable
-# (see omlx/utils/compile_cache.py). In that case a per-engine MLX worker
-# thread cannot exit safely (its thread_local ~CompilerCache would free
-# @mx.compile graphs' Python objects without the GIL -> crash), so close()
-# keeps the executor + stream alive here for the process lifetime instead of
-# shutting the thread down. With the clear symbol present (the normal path)
-# these stay empty and the worker threads shut down normally.
-_immortal_mlx_executors: list = []
-_immortal_mlx_streams: list = []
-
def _final_engine_thread_reclaim(stream: Any) -> None:
"""Drop Python cycles and reclaim MLX buffers on the engine worker thread."""
gc.collect()
_sync_and_clear_cache(stream)
gc.collect()
+ clear_thread_streams()
+
+
+def _final_global_mlx_thread_reclaim() -> None:
+ """Reclaim MLX state before the process-wide worker thread exits."""
+ gc.collect()
+ _sync_and_clear_cache()
+ gc.collect()
+ clear_thread_streams()
def _init_mlx_thread() -> None:
@@ -147,6 +143,34 @@ def get_mlx_executor() -> concurrent.futures.ThreadPoolExecutor:
return _global_mlx_executor
+def shutdown_mlx_executor() -> None:
+ """Shut down the global MLX worker after clearing its thread-local streams."""
+ global _global_mlx_executor
+ executor = _global_mlx_executor
+ if executor is None:
+ return
+
+ try:
+ future = executor.submit(_final_global_mlx_thread_reclaim)
+ except RuntimeError:
+ # An embedding application may have shut the executor down directly.
+ future = None
+
+ if future is not None:
+ try:
+ future.result(timeout=FATAL_TEARDOWN_TIMEOUT_S)
+ except concurrent.futures.TimeoutError:
+ fatal_exit(
+ "Global MLX executor teardown timed out after "
+ f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s"
+ )
+ except Exception as exc:
+ fatal_exit(f"Global MLX executor teardown failed: {exc!r}")
+
+ executor.shutdown(wait=False)
+ _global_mlx_executor = None
+
+
@dataclass
class EngineConfig:
"""Configuration for the engine."""
@@ -1215,53 +1239,31 @@ def close(self) -> None:
if self._mlx_executor is not None:
try:
- self._mlx_executor.submit(
+ reclaim_future = self._mlx_executor.submit(
_final_engine_thread_reclaim, self._mlx_stream
- ).result(timeout=FATAL_TEARDOWN_TIMEOUT_S)
- except concurrent.futures.TimeoutError:
- fatal_exit(
- f"Engine teardown timed out after "
- f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s while reclaiming "
- f"MLX memory for engine {self._engine_id}"
)
except RuntimeError:
- pass
- except Exception:
- logger.warning(
- "Engine %s: final MLX reclaim raised during close()",
- self._engine_id,
- exc_info=True,
- )
+ reclaim_future = None
- # MLX's @mx.compile cache is a C++ thread_local CompilerCache. If
- # this worker thread exits with a non-empty cache, ~CompilerCache
- # frees the cached graphs' Python objects from a thread-exit handler
- # WITHOUT the GIL -> "PyThreadState_Get: GIL is released" crash for
- # models with module-scope @mx.compile graphs (DeepSeek V4 unload,
- # ml-explore/mlx #3280). Clear the cache ON this worker thread (GIL
- # held) before the thread is torn down so the destructor runs on an
- # empty cache, then request shutdown without waiting indefinitely.
- # See utils/compile_cache.py.
- if compile_cache_clear_available():
+ if reclaim_future is not None:
try:
- self._mlx_executor.submit(clear_thread_compile_cache).result(
- timeout=FATAL_TEARDOWN_TIMEOUT_S
- )
+ reclaim_future.result(timeout=FATAL_TEARDOWN_TIMEOUT_S)
except concurrent.futures.TimeoutError:
fatal_exit(
f"Engine teardown timed out after "
- f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s while clearing "
- f"MLX compile cache for engine {self._engine_id}"
+ f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s while reclaiming "
+ f"MLX memory for engine {self._engine_id}"
)
- except RuntimeError:
- pass
- self._mlx_executor.shutdown(wait=False)
- else:
- # Fallback: the clear symbol is unavailable, so do NOT exit the
- # worker thread (that would run the unsafe destructor). Keep it
- # alive for the process lifetime via the module-global registry.
- _immortal_mlx_executors.append(self._mlx_executor)
- _immortal_mlx_streams.append(self._mlx_stream)
+ except Exception as exc:
+ fatal_exit(
+ f"Engine {self._engine_id}: final MLX reclaim failed: "
+ f"{exc!r}"
+ )
+
+ # MLX 0.32.2 makes compiled AttachedData destruction GIL-safe, and
+ # _final_engine_thread_reclaim clears the worker's per-thread stream
+ # registry before ThreadPoolExecutor lets that worker exit.
+ self._mlx_executor.shutdown(wait=False)
self._mlx_executor = None
logger.debug(f"Engine {self._engine_id} closed")
diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py
index 7154fe1ece..9f46a0935c 100644
--- a/omlx/engine_pool.py
+++ b/omlx/engine_pool.py
@@ -14,6 +14,7 @@
from __future__ import annotations
import asyncio
+import copy
import gc
import json
import logging
@@ -38,7 +39,7 @@
from .engine.stt import STTEngine
from .engine.tts import TTSEngine
from .engine.vlm import VLMBatchedEngine
-from .engine_core import get_mlx_executor
+from .engine_core import get_mlx_executor, shutdown_mlx_executor
from .exceptions import (
DEFAULT_CEILING_ADVICE,
InsufficientMemoryError,
@@ -284,6 +285,7 @@ def __init__(
self._get_final_ceiling: object | None = None # Set by server
self._get_admission_ceiling: object | None = None # Set by server
self._get_admission_soft_target: object | None = None # Set by server
+ self._get_residency_ceiling: object | None = None # Set by server
self._settings_manager: object | None = None # Set by server
self._cluster_registry: ClusterRegistry | None = None # Set by server
self._suppress_ttl: bool = False # Suppress TTL during benchmarks
@@ -292,12 +294,15 @@ def __init__(
# rung can "succeed" marginally on every pass of a long prompt while
# the durable rung behind it (ANE bank release) is never reached; a
# request coming back for more headroom escalates instead of
- # reclaiming again first. Bounded FIFO — request ids are transient.
- self._prefill_headroom_recurring: OrderedDict[str, None] = OrderedDict()
+ # reclaiming again first. Values count callback attempts per request
+ # (>1 = recurring). Bounded FIFO — request ids are transient.
+ self._prefill_headroom_recurring: OrderedDict[str, int] = OrderedDict()
self._load_seconds_per_gb_ema: float | None = None
self._load_time_observations: int = 0
self._lease_release_tasks: set[asyncio.Task[None]] = set()
self._pending_unload_tasks: dict[str, asyncio.Task[None]] = {}
+ self._failed_load_reclaim_tasks: set[asyncio.Task[None]] = set()
+ self._failed_load_reclaim_task: asyncio.Task[None] | None = None
self._shutting_down = False
self.configure_hot_cache_budget()
@@ -348,6 +353,11 @@ def _entry_runtime_resident_size(
base = self._entry_resident_size(entry) if base_size is None else base_size
if self._distributed_deployment_for_entry(entry) is not None:
return base
+ qwen4_offload, _, qwen4_estimate = self._qwen4_ple_offload_status(
+ entry, runtime_settings
+ )
+ if qwen4_offload and qwen4_estimate is not None:
+ base = min(base, qwen4_estimate.mmap_bytes)
extra = _qwen35_cpu_share_estimated_bytes(entry.model_path, runtime_settings)
if extra is None:
# An enabled CPU path with unreadable geometry must not silently
@@ -367,6 +377,76 @@ def _entry_runtime_resident_size(
)
return base + extra
+ def _qwen4_ple_offload_status(
+ self,
+ entry: EngineEntry,
+ settings: object | None,
+ *,
+ ceiling: int | None = None,
+ ) -> tuple[bool, bool, object | None]:
+ """Resolve requested/forced Qwen4 PLE mmap mode for this process."""
+
+ model_type = (entry.config_model_type or "").replace("-", "_").lower()
+ if model_type != "qwen4_exp":
+ return False, False, None
+ try:
+ from .patches.mlx_vlm_qwen4_exp_compat.residency import (
+ qwen4_exp_residency_estimate,
+ )
+
+ estimate = qwen4_exp_residency_estimate(entry.model_path)
+ except (OSError, TypeError, ValueError):
+ logger.debug(
+ "Could not inspect Qwen4-Exp PLE residency for %s",
+ entry.model_id,
+ exc_info=True,
+ )
+ return False, False, None
+ # Normal residency calls use the stable ceiling so a post-unload
+ # vm_stat dip cannot pin the new engine to SSD. Pre-load admission may
+ # pass its earlier live ceiling explicitly when only mmap fits.
+ if ceiling is None:
+ ceiling = self._residency_ceiling()
+ if ceiling <= 0:
+ ceiling = self._fallback_admission_ceiling()
+ if ceiling <= 0:
+ ceiling = self._current_ceiling()
+ forced = estimate.force_ssd_offload(ceiling)
+ if forced:
+ logger.warning(
+ "Qwen4-Exp PLE forced to SSD for %s: resident %.1fGB exceeds the "
+ "%.1fGB memory ceiling (mmap needs %.1fGB). Decode will be "
+ "roughly 2.5x slower than a resident load.",
+ entry.model_id,
+ estimate.resident_bytes / 1e9,
+ ceiling / 1e9,
+ estimate.mmap_bytes / 1e9,
+ )
+ requested = bool(
+ settings is not None and getattr(settings, "qwen4_ple_ssd_offload", False)
+ )
+ return requested or forced, forced, estimate if estimate.supported else None
+
+ def _effective_qwen4_model_settings(
+ self,
+ entry: EngineEntry,
+ settings: object | None,
+ *,
+ ceiling: int | None = None,
+ ) -> object | None:
+ """Apply a forced mmap decision without mutating persisted settings."""
+
+ enabled, forced, _ = self._qwen4_ple_offload_status(
+ entry,
+ settings,
+ ceiling=ceiling,
+ )
+ if not enabled or not forced or settings is None:
+ return settings
+ effective = copy.copy(settings)
+ setattr(effective, "qwen4_ple_ssd_offload", True)
+ return effective
+
@property
def current_model_memory(self) -> int:
"""Current memory used by loaded models in bytes."""
@@ -418,6 +498,22 @@ def _fallback_admission_ceiling(self) -> int:
except Exception: # noqa: BLE001
return 0
+ def _residency_ceiling(self) -> int:
+ """Stable ceiling for the resident-vs-mmap call (#PLE residency).
+
+ Wired to `enforcer.get_residency_ceiling`, which drops the vm_stat
+ component so a model swap does not push a table that fits onto SSD.
+ Returns 0 when no callback is wired up; callers fall back to the
+ admission ceiling.
+ """
+ cb = self._get_residency_ceiling
+ if cb is None:
+ return 0
+ try:
+ return int(cb())
+ except Exception: # noqa: BLE001
+ return 0
+
def _admission_soft_target(self) -> int:
"""Soft watermark that pre-load eviction targets (#2319).
@@ -534,6 +630,14 @@ def add(key: str, value: object) -> None:
# force a reload when the corresponding feature is disabled.
mtp_active = bool(data.get("mtp_enabled", False))
add("mtp_enabled", mtp_active)
+ # Draft depth is read once at engine construction; it must be in the
+ # signature while Lightning MTP is active so a change reloads the
+ # engine, but a stale value must not force one when MTP is off.
+ if mtp_active:
+ add("mtp_num_draft_tokens", data.get("mtp_num_draft_tokens"))
+ if entry is not None:
+ qwen4_offload, _, _ = self._qwen4_ple_offload_status(entry, settings)
+ add("qwen4_ple_ssd_offload", qwen4_offload)
turboquant_active = bool(data.get("turboquant_kv_enabled", False))
add("turboquant_kv_enabled", turboquant_active)
@@ -1421,6 +1525,16 @@ async def get_engine(
model_id,
runtime_settings,
)
+ qwen4_admission_ceiling = None
+ if (
+ (entry.config_model_type or "").replace("-", "_").lower()
+ == "qwen4_exp"
+ ):
+ candidate = self._current_ceiling()
+ if candidate <= 0:
+ candidate = self._fallback_admission_ceiling()
+ if candidate > 0:
+ qwen4_admission_ceiling = candidate
unloaded_for_admission = False
# Already loaded - just update access time
@@ -1508,9 +1622,18 @@ async def get_engine(
get_settings = getattr(self._settings_manager, "get_settings", None)
if callable(get_settings):
admission_settings = get_settings(model_id)
- admission_size = self._entry_runtime_resident_size(
+ load_settings = self._effective_qwen4_model_settings(
entry,
admission_settings,
+ ceiling=qwen4_admission_ceiling,
+ )
+ qwen4_admission_override = load_settings is not admission_settings
+ runtime_load_settings = (
+ load_settings if qwen4_admission_override else runtime_settings
+ )
+ admission_size = self._entry_runtime_resident_size(
+ entry,
+ load_settings,
base_size=admission_size,
)
admission_kind = "local shard" if deployment is not None else "model"
@@ -1654,10 +1777,15 @@ async def get_engine(
await self._load_engine(
model_id,
force_lm=force_lm,
- runtime_settings=runtime_settings,
+ runtime_settings=runtime_load_settings,
)
loaded = self._entries[model_id]
+ if qwen4_admission_override and expected_signature is not None:
+ # Automatic mmap is local to this admission attempt. Keep the
+ # user's requested variant as the reuse key so the next request
+ # does not reload the model merely because pressure recovered.
+ loaded.runtime_settings_signature = expected_signature
self._validate_llm_engine_ready(model_id, loaded.engine)
if _lease:
loaded.in_use += 1
@@ -1853,43 +1981,61 @@ async def _evict_idle_lru_for_prefill(
return False
evicted_any = False
+ evicted_count = 0
reclaim_attempted = False
ane_release_attempted = False
- # Snapshot once per call: "a PREVIOUS pass for this request already
- # got a reclaim". Marking inside this call must not flip it.
- recurring = request_id in self._prefill_headroom_recurring
+ reason = str(getattr(eviction_request, "reason", "") or "")
async with self._lock:
- while True:
- current = max(
- mx.get_active_memory(),
- get_phys_footprint(),
- self._current_model_memory,
+ attempt = self._prefill_headroom_recurring.get(request_id, 0) + 1
+ self._prefill_headroom_recurring[request_id] = attempt
+ while len(self._prefill_headroom_recurring) > 512:
+ self._prefill_headroom_recurring.popitem(last=False)
+ # Count no-op calls too so another attempt prioritizes bank release.
+ recurring = attempt > 1
+
+ def _log_decision(outcome: str) -> None:
+ if ane_release_attempted:
+ action = "release_ane"
+ elif reclaim_attempted:
+ action = "reclaim_pool"
+ elif evicted_any:
+ action = "evict_model"
+ else:
+ action = "already_fit"
+ logger.info(
+ "[prefill-eviction] request=%s retry=%d reason=%s "
+ "action=%s outcome=%s recurring=%s mx_active=%.2fGB "
+ "phys_footprint=%.2fGB model_memory=%.2fGB "
+ "predicted=%.2fGB target=%.2fGB evicted=%d",
+ request_id,
+ attempt,
+ reason,
+ action,
+ outcome,
+ recurring,
+ active / 1024**3,
+ footprint / 1024**3,
+ self._current_model_memory / 1024**3,
+ predicted / 1024**3,
+ target / 1024**3,
+ evicted_count,
)
+
+ while True:
+ active = mx.get_active_memory()
+ footprint = get_phys_footprint()
+ current = max(active, footprint, self._current_model_memory)
if current + predicted <= target:
- # A model eviction and/or the pooled-buffer reclaim below
- # created enough headroom; signal the caller to re-admit.
- # reclaim_attempted stands in for "the reclaim freed
- # memory": the helper's own footprint delta is
- # process-wide and can be masked by concurrent
- # allocation, but reaching this check with headroom
- # after an attempt means admission will now succeed.
+ # Use the same sample for admission and its decision log.
+ _log_decision("headroom_available")
return evicted_any or reclaim_attempted or ane_release_attempted
victim = self._find_lru_prefill_eviction_victim(
exclude_model_id=exclude_model_id
)
if victim is None:
- # No idle model left to evict -- the "No idle model
- # evicted" case that used to reject outright even when
- # tens of GB were reclaimable. Two rungs remain: the
- # cheap pooled-buffer reclaim, and shedding the
- # requesting model's own ANE prefill banks. Ordering
- # matters: prefill continuously refills MLX's buffer
- # cache, so on a long prompt the reclaim can "succeed"
- # by a marginal few GB on every pass while the durable
- # rung is never reached — a request that already had a
- # reclaim pass and is back for more headroom escalates
- # straight to the bank release instead.
+ # Reclaim pooled buffers first, unless this request has
+ # already tried to obtain headroom in a previous callback.
if recurring and not ane_release_attempted:
ane_release_attempted = True
await self._release_ane_prefill_for_headroom(
@@ -1906,9 +2052,6 @@ async def _evict_idle_lru_for_prefill(
# requesting engine's own MLX thread, then let the
# loop re-measure.
reclaim_attempted = True
- self._prefill_headroom_recurring[request_id] = None
- while len(self._prefill_headroom_recurring) > 512:
- self._prefill_headroom_recurring.popitem(last=False)
await self._reclaim_pooled_buffers_for_prefill(
exclude_model_id, request_id
)
@@ -1946,6 +2089,8 @@ async def _evict_idle_lru_for_prefill(
format_size(predicted),
format_size(target),
)
+ # The scheduler may still fit a smaller chunk.
+ _log_decision("insufficient_headroom")
return evicted_any
logger.info(
@@ -1959,6 +2104,7 @@ async def _evict_idle_lru_for_prefill(
)
await self._unload_engine(victim)
evicted_any = True
+ evicted_count += 1
@staticmethod
def _resolve_engine_core_from_engine(engine: object) -> object | None:
@@ -2371,6 +2517,15 @@ async def _unload_engine(self, model_id: str) -> None:
self._wake_process_memory_enforcer()
+ def _finish_failed_load_reclaim_task(self, task: asyncio.Task[None]) -> None:
+ self._failed_load_reclaim_tasks.discard(task)
+ try:
+ task.result()
+ except asyncio.CancelledError:
+ pass
+ except Exception:
+ logger.exception("Post-failed-load reclaim task failed")
+
def _schedule_failed_load_reclaim(
self, model_id: str, pre_load_memory: int
) -> None:
@@ -2414,11 +2569,15 @@ async def _reclaim() -> None:
)
self._wake_process_memory_enforcer()
- # Keep a reference so the task isn't garbage-collected mid-flight;
- # one slot suffices -- a newer failure supersedes the previous task.
- self._failed_load_reclaim_task = asyncio.get_running_loop().create_task(
- _reclaim()
+ # Keep every task reachable until it finishes. Concurrent load failures
+ # can overlap, and shutdown must cancel/drain all of them before the
+ # process-wide MLX executor is reclaimed.
+ task = asyncio.get_running_loop().create_task(
+ _reclaim(), name=f"engine-failed-load-reclaim:{model_id}"
)
+ self._failed_load_reclaim_task = task
+ self._failed_load_reclaim_tasks.add(task)
+ task.add_done_callback(self._finish_failed_load_reclaim_task)
async def _load_engine(
self,
@@ -2461,6 +2620,7 @@ async def _load_engine(
model_settings = runtime_settings
if model_settings is None and self._settings_manager is not None:
model_settings = self._settings_manager.get_settings(model_id)
+ model_settings = self._effective_qwen4_model_settings(entry, model_settings)
deployment = self._distributed_deployment_for_entry(entry)
base_resident_size = self._entry_resident_size(entry)
@@ -2967,6 +3127,13 @@ async def preload_pinned_models(self) -> None:
async def shutdown(self) -> None:
"""Shutdown all engines gracefully."""
self._shutting_down = True
+ reclaim_tasks = tuple(self._failed_load_reclaim_tasks)
+ for task in reclaim_tasks:
+ task.cancel()
+ if reclaim_tasks:
+ await asyncio.gather(*reclaim_tasks, return_exceptions=True)
+ self._failed_load_reclaim_tasks.clear()
+ self._failed_load_reclaim_task = None
pending_tasks = tuple(self._pending_unload_tasks.values())
if pending_tasks:
await asyncio.gather(*pending_tasks, return_exceptions=True)
@@ -2980,6 +3147,7 @@ async def shutdown(self) -> None:
except Exception as e:
logger.error(f"Error unloading {model_id} during shutdown: {e}")
+ shutdown_mlx_executor()
logger.info("Engine pool shutdown complete")
def get_status(self) -> dict:
diff --git a/omlx/eval/gsm8k.py b/omlx/eval/gsm8k.py
index 53a882ac43..1a5f9b1137 100644
--- a/omlx/eval/gsm8k.py
+++ b/omlx/eval/gsm8k.py
@@ -43,16 +43,23 @@
]
+# A number, with optional thousands separators. The digit anchors at both
+# ends matter: ``[\d,]+`` alone also matches a bare comma, so punctuation
+# after the final digit ("the answer is 18, which is the total") became the
+# last "number" in the text and extraction returned an empty string.
+_NUMBER_PATTERN = r"-?\d(?:[\d,]*\d)?(?:\.\d+)?"
+
+
def _extract_numeric_answer(text: str) -> str:
"""Extract the final numeric answer from a GSM8K-style response.
Looks for #### pattern first, then falls back to the last number.
"""
- match = re.search(r"####\s*(-?[\d,]+(?:\.\d+)?)", text)
+ match = re.search(rf"####\s*({_NUMBER_PATTERN})", text)
if match:
return match.group(1).replace(",", "")
- numbers = re.findall(r"-?[\d,]+(?:\.\d+)?", text)
+ numbers = re.findall(_NUMBER_PATTERN, text)
if numbers:
return numbers[-1].replace(",", "")
diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py
index 98633bea19..5d49351acd 100644
--- a/omlx/memory_monitor.py
+++ b/omlx/memory_monitor.py
@@ -43,7 +43,7 @@
# different head dimensions; unsupported cases fall back to an unfused
# score-matrix allocation.
_SDPA_VECTOR_QUERY_TOKEN_THRESHOLD = 8
-_SDPA_FULL_SUPPORTED_HEAD_DIMS = frozenset({64, 80, 128})
+_SDPA_FULL_SUPPORTED_HEAD_DIMS = frozenset({64, 72, 80, 96, 128})
_SDPA_VECTOR_SUPPORTED_HEAD_DIMS = frozenset({64, 96, 128, 256})
# Default bytes/elem for the materialized unfused score matrix when the model's
# compute dtype is unknown. MLX softmax accumulates in fp32, but the dominant
@@ -54,26 +54,62 @@
# dim-less path and matches the fp16/bf16 majority of MLX inference models.
_SDPA_FALLBACK_SCORE_DTYPE_SIZE = 2
+# Bytes/elem the unfused head-dim-256 fallback actually materializes on
+# Metal: MLX keeps the attention score matrix in fp32 even for bf16/fp16
+# models (measured ~33GiB IOAccelerator spike on a 160k-token VLM prefill at
+# head_dim=256). Shared by the sdpa256 route gate
+# (patches/sdpa256_attention._tiled_route_required) and the Qwen4 prefill
+# profile so the router and the guard price the real fallback identically.
+# Kept separate from _SDPA_FALLBACK_SCORE_DTYPE_SIZE: that default covers
+# the dim-less generic path where the compute dtype is unknown and the
+# fp16/bf16 majority is the better prior; widening it globally would
+# re-price unrelated models without evidence.
+SDPA256_UNFUSED_SCORE_DTYPE_SIZE = 4
+
# Head dims whose multi-token prefill is routed to an O(L) tiled/online-softmax
# kernel instead of the unfused O(L^2) score-matrix fallback. Populated at
# runtime by the kernel patch that installs the route (see
# omlx/patches/sdpa256_attention.py); empty otherwise, so the estimate stays
-# O(L^2) when no such kernel is active. Maps head_dim -> kv_tile (the kernel's
-# KV block width, which bounds the per-chunk score transient).
-_SDPA_TILED_PREFILL_HEAD_DIMS: dict[int, int] = {}
-_SDPA_TILED_MIN_KV_LEN = 8192
+# O(L^2) when no such kernel is active. Each entry records the query/KV shape
+# floor actually covered by the installed route plus a conservative score-tile
+# width for admission accounting.
+
+
+@dataclass(frozen=True)
+class _BoundedSDPAPrefillRoute:
+ min_query_len: int
+ min_kv_len: int
+ kv_tile: int
+ supports_array_mask: bool
+
+
+_SDPA_TILED_PREFILL_HEAD_DIMS: dict[int, tuple[_BoundedSDPAPrefillRoute, ...]] = {}
def register_tiled_prefill_head_dim(
- head_dim: int, *, min_kv_len: int = 8192, kv_tile: int = 1024
+ head_dim: int,
+ *,
+ min_query_len: int = 2,
+ min_kv_len: int = 8192,
+ kv_tile: int = 1024,
+ supports_array_mask: bool = False,
) -> None:
- """Register a head_dim whose long-context prefill now uses an O(L) tiled
- kernel, so the prefill memory estimate stops charging the O(L^2) score
- matrix for it. Must be called in lockstep with installing the kernel route,
- or the guard keeps rejecting valid long-context requests."""
- global _SDPA_TILED_MIN_KV_LEN
- _SDPA_TILED_PREFILL_HEAD_DIMS[int(head_dim)] = int(kv_tile)
- _SDPA_TILED_MIN_KV_LEN = int(min_kv_len)
+ """Register a bounded long-context route installed for one head dim.
+
+ Multiple native routes may cover the same head dimension at different
+ thresholds and mask capabilities. Store them independently so combining
+ registrations cannot invent coverage no individual route guarantees.
+ """
+ head_dim = int(head_dim)
+ route = _BoundedSDPAPrefillRoute(
+ min_query_len=max(2, int(min_query_len)),
+ min_kv_len=max(1, int(min_kv_len)),
+ kv_tile=max(1, int(kv_tile)),
+ supports_array_mask=bool(supports_array_mask),
+ )
+ routes = _SDPA_TILED_PREFILL_HEAD_DIMS.get(head_dim, ())
+ if route not in routes:
+ _SDPA_TILED_PREFILL_HEAD_DIMS[head_dim] = (*routes, route)
# Bytes/elem of a model-built additive attention bias materialized as a
@@ -91,9 +127,7 @@ def register_attention_bias_transient(dtype_size: float | None) -> None:
model load/swap: the setting is process-wide, like the tiled head_dim
registry above."""
global _ATTENTION_BIAS_TRANSIENT_DTYPE_SIZE
- _ATTENTION_BIAS_TRANSIENT_DTYPE_SIZE = (
- float(dtype_size) if dtype_size else None
- )
+ _ATTENTION_BIAS_TRANSIENT_DTYPE_SIZE = float(dtype_size) if dtype_size else None
def estimate_unfused_sdpa_call_bytes(
@@ -230,7 +264,6 @@ def __init__(
# Fixed per-sequence recurrent state (GDN/Mamba ArraysCache),
# measured once from a live cache after the first prefill chunk.
self._fixed_state_bytes: int = 0
-
# PagedCacheManager for KV cache memory measurement
self._paged_cache_manager: Optional["PagedCacheManager"] = None
self._block_size: int = 256 # Default block size
@@ -408,6 +441,10 @@ def clear_ane_prefill_transient(self) -> None:
"""
self._ane_prefill_transient_bytes = 0
+ def set_ane_prefill_transient_bytes(self, value: int) -> None:
+ """Refresh the reservation after VLM ANE compilation."""
+ self._ane_prefill_transient_bytes = max(int(value), 0)
+
def set_model_info(
self,
num_layers: int,
@@ -669,8 +706,11 @@ def estimate_resident_kv_bytes(
if num_tokens <= 0:
return 0
if self._prefill_memory_profile is not None:
- return self._prefill_memory_profile.estimate_resident_kv_bytes(
- num_tokens, chunk_tokens=chunk_tokens
+ return (
+ self._prefill_memory_profile.estimate_resident_kv_bytes(
+ num_tokens, chunk_tokens=chunk_tokens
+ )
+ + self._fixed_state_bytes
)
total = self.estimate_prompt_kv_bytes(num_tokens)
@@ -731,13 +771,17 @@ def _estimate_sdpa_activation_bytes(self, query_tokens: int, kv_len: int) -> int
# [n_q, query_tokens, kv_len] matrix. This matches the kernel's route
# gate (query_len > 1, kv_len >= threshold); any query_len <= 1 already
# returned above via the fused vector path.
- kv_tile = _SDPA_TILED_PREFILL_HEAD_DIMS.get(hd)
- if (
- kv_tile is not None
- and query_tokens > 1
- and kv_len >= _SDPA_TILED_MIN_KV_LEN
- ):
- tile_scores = n_q * query_tokens * min(kv_tile, kv_len) * self._score_dtype_size
+ bounded_routes = _SDPA_TILED_PREFILL_HEAD_DIMS.get(hd, ())
+ matching_routes = [
+ route
+ for route in bounded_routes
+ if query_tokens >= route.min_query_len and kv_len >= route.min_kv_len
+ ]
+ if matching_routes:
+ kv_tile = max(route.kv_tile for route in matching_routes)
+ tile_scores = (
+ n_q * query_tokens * min(kv_tile, kv_len) * self._score_dtype_size
+ )
return output + tile_scores + bias
return (
@@ -760,9 +804,9 @@ def estimate_prefill_peak_bytes(
cache pool / python heap overhead (absorbed by enforcer's hard
threshold margin — see MemorySettings.hard_threshold).
- MLX SDPA only uses fused full-attention kernels for the head dimensions
- supported by ``ScaledDotProductAttention::use_fallback``. Unsupported
- prefill chunks fall back to an unfused fp32 score matrix whose K
+ MLX SDPA uses its fused full-attention kernels only for shapes accepted
+ by ``ScaledDotProductAttention::use_fallback``. Other prefill chunks
+ fall back to an unfused score matrix whose K
dimension spans the full key/value context. With prefix-cache hits,
that context is ``new_tokens + cached_tokens``, not just the new suffix.
Passing only ``new_tokens`` here silently under-counts long-context
@@ -814,7 +858,19 @@ def estimate_prefill_peak_bytes(
kv = self.estimate_resident_kv_bytes(new_tokens, chunk_tokens=eff_chunk)
return attn + kv + self._ane_prefill_transient_bytes
- def estimate_chunk_transient_bytes(self, n_tokens: int, kv_len: int) -> int:
+ def is_qwen4_gathered_prefill_profile(self) -> bool:
+ """True when this monitor prices Qwen4 QSA gathered-core prefill."""
+ return isinstance(
+ self._prefill_memory_profile, _Qwen4ExpPrefillMemoryProfile
+ )
+
+ def estimate_chunk_transient_bytes(
+ self,
+ n_tokens: int,
+ kv_len: int,
+ *,
+ gathered_core: bool = False,
+ ) -> int:
"""Transient SDPA activation bytes for ONE prefill chunk.
Isolates the per-chunk attention transient — the spike that drives
@@ -829,11 +885,19 @@ def estimate_chunk_transient_bytes(self, n_tokens: int, kv_len: int) -> int:
and scale with total ``kv_len``.
Returns 0 when model info is unavailable.
+
+ ``gathered_core`` prices Qwen4 QSA as a gathered core instead of
+ dense Q×kv_len.
"""
if self._prefill_memory_profile is not None:
- return self._prefill_memory_profile.estimate_prefill_transient_bytes(
- n_tokens, kv_len
- )
+ profile = self._prefill_memory_profile
+ if isinstance(profile, _Qwen4ExpPrefillMemoryProfile):
+ return profile.estimate_prefill_transient_bytes(
+ n_tokens,
+ kv_len,
+ gathered_core=gathered_core,
+ )
+ return profile.estimate_prefill_transient_bytes(n_tokens, kv_len)
return self._estimate_sdpa_activation_bytes(n_tokens, kv_len)
def estimate_blocks_to_free(self, bytes_to_free: int, block_size: int) -> int:
@@ -919,6 +983,10 @@ def _pos_int(v: Any) -> bool:
return isinstance(v, int) and not isinstance(v, bool) and v > 0
+def _nonnegative_int(v: Any) -> bool:
+ return isinstance(v, int) and not isinstance(v, bool) and v >= 0
+
+
@dataclass(frozen=True)
class _DeepSeekV4PrefillMemoryProfile:
"""Exact-shape prefill estimator for DeepSeek V4's hybrid attention.
@@ -1057,14 +1125,7 @@ def _indexer_fallback_bytes(self, query_tokens: int, pooled_tokens: int) -> int:
# conservative bound for the unfused MLX path.
topk_workspace = 6 * reduced_scores
selected = query_tokens * min(self.index_topk, pooled_tokens) * 4
- return (
- query
- + keys
- + weights
- + materialized_scores
- + topk_workspace
- + selected
- )
+ return query + keys + weights + materialized_scores + topk_workspace + selected
def _indexer_native_bytes(self, query_tokens: int, pooled_tokens: int) -> int:
"""Bound the fused native indexer score and deterministic top-k path."""
@@ -1201,14 +1262,165 @@ def estimate_prefill_transient_bytes(self, query_tokens: int, kv_len: int) -> in
return max(candidates, default=0)
+@dataclass(frozen=True)
+class _Qwen4ExpPrefillMemoryProfile:
+ """Prefill estimator for Qwen4 / Flash-Next hybrid GDN + QSA.
+
+ GDN layers keep a fixed recurrent state. QSA core attention, once the
+ gathered path is active, attends at most ``indexer_budget`` tokens.
+ The indexer still scores every compressed block (``kv_len / r``).
+ Dense ``Q x kv_len`` SDPA is the wrong price for that core.
+ """
+
+ qsa_layers: int
+ num_attention_heads: int
+ num_kv_heads: int
+ head_dim: int
+ indexer_n_heads: int
+ indexer_head_dim: int
+ indexer_budget: int
+ compress_ratio: int
+ dtype_size: float
+ score_dtype_size: float
+
+ def estimate_resident_kv_bytes(
+ self, num_tokens: int, *, chunk_tokens: int = 1
+ ) -> int:
+ if num_tokens <= 0 or self.qsa_layers <= 0:
+ return 0
+ per_layer = (
+ 2 * self.num_kv_heads * self.head_dim * self.dtype_size
+ + self.indexer_head_dim * self.dtype_size
+ + 3 * 8
+ )
+ return int(self.qsa_layers * per_layer * int(num_tokens))
+
+ def estimate_prefill_transient_bytes(
+ self,
+ query_tokens: int,
+ kv_len: int,
+ *,
+ gathered_core: bool = False,
+ ) -> int:
+ if query_tokens <= 0 or kv_len <= 0:
+ return 0
+ query_tokens = int(query_tokens)
+ kv_len = int(kv_len)
+ pooled = max(kv_len // max(self.compress_ratio, 1), 1)
+ indexer = int(
+ self.indexer_n_heads * query_tokens * pooled * 4
+ + self.indexer_n_heads * query_tokens * self.indexer_head_dim * 4
+ )
+ core_kv = kv_len
+ if gathered_core and kv_len > self.indexer_budget:
+ core_kv = min(kv_len, self.indexer_budget + self.compress_ratio - 1)
+
+ # The head_dim-256 sdpa256 patch keeps long-context prefill O(L):
+ # consult the same bounded-route registry the generic estimator uses
+ # (issue #2204 follow-up). Without it this profile always charges the
+ # dense Q x kv_len matrix, which made the guard shrink VLM chunks to
+ # crawl speed on 160k-context prefills even though the router forces
+ # a bounded kernel there.
+ core = estimate_unfused_sdpa_call_bytes(
+ self.num_attention_heads,
+ query_tokens,
+ core_kv,
+ self.head_dim,
+ SDPA256_UNFUSED_SCORE_DTYPE_SIZE,
+ )
+ bounded_routes = _SDPA_TILED_PREFILL_HEAD_DIMS.get(self.head_dim, ())
+ matching_routes = [
+ route
+ for route in bounded_routes
+ if route.supports_array_mask
+ and query_tokens >= route.min_query_len
+ and core_kv >= route.min_kv_len
+ ]
+ if matching_routes:
+ # Match the generic estimator's O(L) bound: fp32 output plus one
+ # fp32 score tile (largest registered tile). The core_kv is the
+ # K width of the real core-attention call, so a gathered QSA call
+ # whose reduced K is below the route floor stays dense-priced.
+ kv_tile = max(route.kv_tile for route in matching_routes)
+ tile_scores = (
+ self.num_attention_heads
+ * query_tokens
+ * min(kv_tile, core_kv)
+ * SDPA256_UNFUSED_SCORE_DTYPE_SIZE
+ )
+ output = (
+ self.num_attention_heads * query_tokens * self.head_dim * 4
+ )
+ core = int(output + tile_scores)
+ return indexer + core
+
+
+def _make_qwen4_exp_prefill_memory_profile(
+ config: Any,
+ *,
+ compute_dtype_size: float,
+) -> PrefillMemoryProfile | None:
+ num_layers = _cfg_get(config, "num_hidden_layers")
+ num_attention_heads = _cfg_get(config, "num_attention_heads")
+ num_kv_heads = _cfg_get(config, "num_key_value_heads")
+ head_dim = _cfg_get(config, "head_dim")
+ indexer_n_heads = _cfg_get(config, "indexer_n_heads")
+ indexer_head_dim = _cfg_get(config, "indexer_head_dim")
+ indexer_budget = _cfg_get(config, "indexer_budget")
+ compress_ratio = _cfg_get(config, "indexer_compress_ratio")
+ required = (
+ num_layers,
+ num_attention_heads,
+ num_kv_heads,
+ head_dim,
+ indexer_n_heads,
+ indexer_head_dim,
+ indexer_budget,
+ compress_ratio,
+ )
+ if not all(_pos_int(value) for value in required):
+ return None
+ if not isinstance(compute_dtype_size, (int, float)) or compute_dtype_size <= 0:
+ return None
+ layer_types = _cfg_get(config, "layer_types") or ()
+ qsa_layers = sum(
+ 1
+ for kind in layer_types
+ if kind in {"qwen_sparse_attention", "full_attention"}
+ )
+ if qsa_layers <= 0:
+ interval = _cfg_get(config, "full_attention_interval") or 4
+ if not _pos_int(interval):
+ return None
+ qsa_layers = int(num_layers) // int(interval)
+ if qsa_layers <= 0:
+ return None
+ return _Qwen4ExpPrefillMemoryProfile(
+ qsa_layers=qsa_layers,
+ num_attention_heads=int(num_attention_heads),
+ num_kv_heads=int(num_kv_heads),
+ head_dim=int(head_dim),
+ indexer_n_heads=int(indexer_n_heads),
+ indexer_head_dim=int(indexer_head_dim),
+ indexer_budget=int(indexer_budget),
+ compress_ratio=int(compress_ratio),
+ dtype_size=float(compute_dtype_size),
+ score_dtype_size=float(compute_dtype_size),
+ )
+
+
def make_prefill_memory_profile(
config: Any,
*,
compute_dtype_size: float,
wsdpa_dtype_supported: bool = False,
) -> PrefillMemoryProfile | None:
- """Build the one model-specific prefill strategy currently required."""
+ """Build a model-specific prefill strategy when the uniform formulas fail."""
model_type = str(_cfg_get(config, "model_type", "") or "")
+ if model_type.startswith("qwen4_exp"):
+ return _make_qwen4_exp_prefill_memory_profile(
+ config, compute_dtype_size=compute_dtype_size
+ )
if not model_type.startswith("deepseek_v4"):
return None
@@ -1273,8 +1485,9 @@ def make_prefill_memory_profile(
)
# Fixed-state recurrent caches (GDN/Mamba). Matches
# Scheduler._cache_tree_has_arrays_cache plus mlx-lm's MambaCache.
-_ARRAYS_CACHE_CLASS_NAMES = frozenset(
- {"ArraysCache", "SizedArraysCache", "MambaCache"}
+_ARRAYS_CACHE_CLASS_NAMES = frozenset({"ArraysCache", "SizedArraysCache", "MambaCache"})
+_FULL_KV_CACHE_CLASS_NAMES = frozenset(
+ {"QSAKVCache", "QSAQuantizedKVCache", "BatchQSAKVCache"}
)
@@ -1305,7 +1518,7 @@ def collect_kv_layer_specs(
def _walk(c: Any) -> None:
nonlocal full, arrays
- if type(c) is KVCache:
+ if type(c) is KVCache or type(c).__name__ in _FULL_KV_CACHE_CLASS_NAMES:
full += 1
return
if isinstance(c, CacheList):
@@ -1333,6 +1546,48 @@ def _walk(c: Any) -> None:
return full, specs, arrays
+def estimate_qwen4_exp_kv_bytes_per_token(
+ config: Any,
+ cache_list: Any,
+ dtype_size: float,
+) -> float | None:
+ """Price Qwen4 QSA K/V plus its raw index keys and MRoPE positions."""
+ if not str(_cfg_get(config, "model_type", "")).startswith("qwen4_exp"):
+ return None
+ if cache_list is None:
+ return None
+
+ try:
+ qsa_layers = sum(
+ 1
+ for cache in cache_list
+ if type(cache).__name__
+ in {"QSAKVCache", "QSAQuantizedKVCache", "BatchQSAKVCache"}
+ )
+ except Exception:
+ return None
+ if qsa_layers <= 0:
+ return None
+
+ num_kv_heads = _cfg_get(config, "num_key_value_heads")
+ head_dim = _cfg_get(config, "head_dim")
+ indexer_head_dim = _cfg_get(config, "indexer_head_dim")
+ if not all(_pos_int(value) for value in (num_kv_heads, head_dim, indexer_head_dim)):
+ return None
+ if not isinstance(dtype_size, (int, float)) or dtype_size <= 0:
+ return None
+
+ # QSA keeps ordinary K/V, one raw index-key vector, and up to three int64
+ # MRoPE coordinates for every cached token. Text-only positions use one
+ # coordinate, but charging all three keeps image requests conservative.
+ per_layer = (
+ 2 * num_kv_heads * head_dim * float(dtype_size)
+ + indexer_head_dim * float(dtype_size)
+ + 3 * 8
+ )
+ return float(qsa_layers * per_layer)
+
+
def estimate_mla_kv_bytes_per_token(
config: Any,
cache_list: Any,
@@ -1343,20 +1598,21 @@ def estimate_mla_kv_bytes_per_token(
GLM/DeepSeek MLA models do not store expanded ``num_kv_heads * head_dim``
K/V tensors. Their main cache stores a latent key and RoPE value
(``kv_lora_rank + qk_rope_head_dim``) with a single KV head. GLM-5.2's DSA
- indexer adds a second cache on full-indexer layers containing only
- ``index_head_dim`` keys and zero-width values. Falling back to the standard
- uniform KV formula over-counts GLM-5.2 by more than an order of magnitude.
+ indexer adds a second cache on full-indexer layers. GLM-5.2 stores one
+ ``index_head_dim`` key per token, while GLM-5.3 pools those keys by the
+ cache's compression ratio. Falling back to the standard uniform KV formula
+ over-counts these models by more than an order of magnitude.
"""
kv_lora_rank = _cfg_get(config, "kv_lora_rank")
rope_dim = _cfg_get(config, "qk_rope_head_dim")
- if not (_pos_int(kv_lora_rank) and _pos_int(rope_dim)):
+ if not (_pos_int(kv_lora_rank) and _nonnegative_int(rope_dim)):
return None
if cache_list is None:
return None
main_cache_layers = 0
- indexer_cache_layers = 0
+ indexer_cache_token_ratio = 0.0
try:
for layer_cache in cache_list:
caches = getattr(layer_cache, "caches", None)
@@ -1366,7 +1622,11 @@ def estimate_mla_kv_bytes_per_token(
if n_caches >= 1:
main_cache_layers += 1
if n_caches >= 2:
- indexer_cache_layers += 1
+ indexer_cache = caches[1]
+ ratio = getattr(indexer_cache, "ratio", 1)
+ if not _pos_int(ratio):
+ ratio = 1
+ indexer_cache_token_ratio += 1.0 / ratio
except Exception:
return None
@@ -1379,7 +1639,7 @@ def estimate_mla_kv_bytes_per_token(
elems_per_token = (
main_cache_layers * (kv_lora_rank + rope_dim)
- + indexer_cache_layers * index_head_dim
+ + indexer_cache_token_ratio * index_head_dim
)
return float(elems_per_token) * float(dtype_size)
@@ -1497,9 +1757,9 @@ def set_model_info_from_model(monitor: "MemoryMonitor", model: Any) -> None:
except Exception:
pass
- kv_bytes_per_token = estimate_mla_kv_bytes_per_token(
+ kv_bytes_per_token = estimate_qwen4_exp_kv_bytes_per_token(
config, cache_list, dtype_size
- )
+ ) or estimate_mla_kv_bytes_per_token(config, cache_list, dtype_size)
# Truthiness alone isn't enough — MagicMock proxies leaking through the
# descent (test scaffolds that don't fully spec ``model.config``) are
@@ -1619,7 +1879,10 @@ def raise_if_prefill_exceeds(
request_id = f"preflight-{_uuid.uuid4().hex[:8]}"
logger.warning(
"Preflight rejected (%d tokens, cached=%d, request_id=%s): %s",
- num_prompt_tokens, cached_tokens, request_id, message,
+ num_prompt_tokens,
+ cached_tokens,
+ request_id,
+ message,
)
raise PrefillMemoryExceededError(
message=message,
diff --git a/omlx/model_discovery.py b/omlx/model_discovery.py
index 56f2861955..62ff6eb8f0 100644
--- a/omlx/model_discovery.py
+++ b/omlx/model_discovery.py
@@ -68,6 +68,7 @@
"inkling",
"inkling_mm_model", # config model_type of Inkling Small checkpoints
"muse_glimmer",
+ "glm5_next",
}
# Text-only model families that are implemented in mlx-vlm rather than
@@ -75,6 +76,7 @@
# models and adapts their language model to oMLX's scheduler.
VLM_NATIVE_TEXT_MODEL_TYPES = {
"cohere2_moe",
+ "glm5_next",
"minimax_m3",
}
@@ -162,6 +164,7 @@ def is_helper_model_config(config: dict) -> bool:
"UnlimitedOCRForCausalLM", # baidu/Unlimited-OCR
"InklingForConditionalGeneration", # thinkingmachines/Inkling-Small
"MuseGlimmerForConditionalGeneration", # meta-models/Muse-Glimmer-30B
+ "Glm5NextForConditionalGeneration", # zai-org/GLM-5.3-Flash
}
# Known embedding model types from mlx-embeddings
diff --git a/omlx/model_profiles.py b/omlx/model_profiles.py
index db8ab82235..1b6aa32f4a 100644
--- a/omlx/model_profiles.py
+++ b/omlx/model_profiles.py
@@ -102,6 +102,8 @@
"model_type_override",
"active_profile_name",
"ttl_seconds",
+ # Hardware-specific residency choice; never propagate across models.
+ "qwen4_ple_ssd_offload",
# Security flag must be explicit per model — never propagated via profiles.
"trust_remote_code",
}
diff --git a/omlx/model_settings.py b/omlx/model_settings.py
index 686cb0cd9b..9280e09924 100644
--- a/omlx/model_settings.py
+++ b/omlx/model_settings.py
@@ -29,6 +29,10 @@
# Current settings file format version
SETTINGS_VERSION = 1
+# The Lightning MTP runtime clamps deeper requests to this global ceiling.
+# Keep API validation and runtime normalization on the same contract.
+MAX_LIGHTNING_MTP_DRAFT_TOKENS = 8
+
def vlm_mtp_processor_conflicts(data: dict) -> list:
"""Names of settings that need per-request logits processors and
@@ -212,6 +216,10 @@ class ModelSettings:
enable_thinking: Optional[bool] = (
None # Explicit toggle for thinking/reasoning mode (None = auto)
)
+ # Qwen4-Exp only: keep the large PLE N-gram table on SSD and gather rows
+ # through mmap. The runtime may force this on when resident loading cannot
+ # fit under the configured model-memory ceiling but mmap loading can.
+ qwen4_ple_ssd_offload: bool = False
preserve_thinking: Optional[bool] = (
None # Keep blocks in historical turns (None = auto, True when template supports it)
)
diff --git a/omlx/models/embedding.py b/omlx/models/embedding.py
index 821fd89b4b..6cac890c50 100644
--- a/omlx/models/embedding.py
+++ b/omlx/models/embedding.py
@@ -19,7 +19,6 @@
import mlx.core as mx
from mlx.utils import tree_flatten
-from ..utils.compile_cache import clear_thread_compile_cache
from ..utils.image import validate_image_data_uri
from .base_model import last_token_pool, mean_pooling, normalize_embeddings
from .mlx_embeddings_compat import (
@@ -741,7 +740,6 @@ def close(self) -> None:
gc.collect()
mx.synchronize()
mx.clear_cache()
- clear_thread_compile_cache()
gc.collect()
def embed(
diff --git a/omlx/models/reranker.py b/omlx/models/reranker.py
index fb6b9ef227..519d80513e 100644
--- a/omlx/models/reranker.py
+++ b/omlx/models/reranker.py
@@ -27,7 +27,6 @@
_is_causal_lm_reranker,
)
from ..patches.qwen3_sliding_window import apply_qwen3_sliding_window_patch
-from ..utils.compile_cache import clear_thread_compile_cache
from ..utils.image import load_image
from .mlx_embeddings_compat import (
patch_qwen3_vl_processor_for_torch_free_image_loading,
@@ -943,7 +942,6 @@ def close(self) -> None:
gc.collect()
mx.synchronize()
mx.clear_cache()
- clear_thread_compile_cache()
gc.collect()
# Default max_length per model type
diff --git a/omlx/models/vlm.py b/omlx/models/vlm.py
index afcc43d32c..516e5faa16 100644
--- a/omlx/models/vlm.py
+++ b/omlx/models/vlm.py
@@ -67,16 +67,69 @@ def __init__(self, vlm_model: nn.Module):
# from this dict + current batch UIDs before each step.
self._uid_rope_deltas: Dict[int, float] = {}
self._batch_rope_deltas: Optional[mx.array] = None
+ # External/chunked text prefill owns a stronger position-shape proof
+ # than the generic decode binder: the scheduler has already excluded
+ # media embeddings and is advancing one request's scalar cache. Qwen4
+ # uses that proof to keep its position ids rank two, which is exactly
+ # equivalent to three broadcast-identical mRoPE planes and preserves
+ # the qualified gathered-QSA path. Generic/media/batched binds reset
+ # the proof and retain the ordinary rank-three fail-closed path.
+ self._qwen4_text_prefill_positions = False
def release_resources(self) -> None:
"""Drop references to VLM-owned MLX arrays before engine teardown reclaim."""
+ close = getattr(self._vlm_model, "close", None)
+ if callable(close):
+ close()
self._pending_embeds = None
self._pending_kwargs = {}
self._uid_rope_deltas.clear()
self._batch_rope_deltas = None
+ self._qwen4_text_prefill_positions = False
self._language_model = None
self._vlm_model = None
+ @property
+ def mtp(self):
+ """Expose an attached Lightning MTP head, when the model provides one."""
+ language_model = self._language_model
+ getter = getattr(language_model, "get_mtp_module", None)
+ if callable(getter):
+ return getter()
+ return getattr(language_model, "mtp", None)
+
+ def mtp_forward(
+ self,
+ hidden_states,
+ next_token_ids,
+ mtp_cache,
+ return_hidden: bool = False,
+ logits_keep: int = 0,
+ ):
+ return self._language_model.mtp_forward(
+ hidden_states,
+ next_token_ids,
+ mtp_cache,
+ return_hidden=return_hidden,
+ logits_keep=logits_keep,
+ )
+
+ def make_mtp_cache(self):
+ make_cache = getattr(self._language_model, "make_mtp_cache", None)
+ return make_cache() if callable(make_cache) else []
+
+ def rollback_speculative_cache(self, caches, gdn_states, accepted, block_size):
+ return self._language_model.rollback_speculative_cache(
+ caches,
+ gdn_states,
+ accepted,
+ block_size,
+ )
+
+ # Runtime family patches use this marker to avoid installing an older,
+ # model-specific copy of the same adapter plumbing.
+ _omlx_mtp_adapter_patched = True
+
@property
def layers(self):
"""Expose language model layers for cache creation.
@@ -104,6 +157,11 @@ def model_type(self) -> str:
return self._vlm_model.config.model_type
return "vlm"
+ @property
+ def supports_skip_lm_head(self) -> bool:
+ """Whether the wrapped official language model has a cache-only pass."""
+ return self.model_type == "qwen4_exp"
+
@property
def config(self):
"""Expose model config."""
@@ -204,6 +262,7 @@ def clear_vlm_position_state(self) -> None:
self._language_model._position_ids = None
self._language_model._rope_deltas = None
self._batch_rope_deltas = None
+ self._qwen4_text_prefill_positions = False
def register_rope_delta(self, uid: int, delta: float) -> None:
"""Register rope_delta for a UID after VLM prefill."""
@@ -220,6 +279,18 @@ def set_batch_rope_deltas(self, deltas: mx.array) -> None:
an array of rope_deltas aligned to the batch slot order.
"""
self._batch_rope_deltas = deltas
+ self._qwen4_text_prefill_positions = False
+
+ def set_text_prefill_rope_delta(self, delta: float) -> None:
+ """Bind one scheduler-proven text row for an imminent prefill call.
+
+ This seam is intentionally separate from ``set_batch_rope_deltas``.
+ Only the scheduler's external/chunked non-media prefill paths may call
+ it. A later generic decode, media, or batched bind clears the proof.
+ """
+
+ self._batch_rope_deltas = mx.array([delta])
+ self._qwen4_text_prefill_positions = True
def _batch_rope_deltas_for_size(self, batch_size: int) -> Optional[mx.array]:
"""Return rope deltas aligned to the current model input batch size."""
@@ -251,7 +322,12 @@ def _batch_rope_deltas_for_size(self, batch_size: int) -> Optional[mx.array]:
return mx.concatenate([deltas, pad], axis=0)
def _position_ids_from_starts(
- self, starts: mx.array, batch_size: int, seq_len: int
+ self,
+ starts: mx.array,
+ batch_size: int,
+ seq_len: int,
+ *,
+ qwen4_text_prefill_positions: bool = False,
) -> mx.array:
"""Build model-specific decode position_ids from per-row start offsets.
@@ -270,6 +346,18 @@ def _position_ids_from_starts(
seq_positions = starts[:, None] + steps[None, :]
if self._uses_minimax_m3_positions:
return seq_positions
+ if (
+ self.model_type == "qwen4_exp"
+ and qwen4_text_prefill_positions
+ and batch_size == 1
+ ):
+ # Qwen4's gathered-QSA qualification accepts canonical B1 text
+ # positions as (1, T), never general multimodal (3, B, T) mRoPE.
+ # The generic form constructed below is a broadcast of this exact
+ # row across all three planes, so avoiding that broadcast changes
+ # neither rotary values nor logits; it only preserves the proven
+ # text-only fast-path contract.
+ return seq_positions
return mx.broadcast_to(seq_positions[None, :, :], (3, batch_size, seq_len))
def get_last_rope_deltas(self) -> float:
@@ -281,6 +369,8 @@ def get_last_rope_deltas(self) -> float:
rd = getattr(self._language_model, "_rope_deltas", None)
if rd is None:
return 0.0
+ if isinstance(rd, mx.array):
+ return float(rd.reshape(-1)[0].item())
if hasattr(rd, "item"):
return float(rd.item())
return float(rd)
@@ -294,6 +384,7 @@ def __call__(
self,
input_ids: mx.array,
cache: Optional[List[Any]] = None,
+ skip_lm_head: bool = False,
**kwargs,
) -> Any:
"""
@@ -314,7 +405,19 @@ def __call__(
Returns:
Model output (logits as mx.array)
"""
+ # Consume the scheduler proof before doing any work. A failed/cancelled
+ # call therefore cannot leave a text-only capability armed for a later
+ # media or generic request. Each external prefill chunk explicitly
+ # re-arms it at its own model-call boundary.
+ qwen4_text_prefill_positions = self._qwen4_text_prefill_positions
+ self._qwen4_text_prefill_positions = False
return_hidden = bool(kwargs.get("return_hidden", False))
+ if skip_lm_head:
+ # Scheduler prefill chunks discard their logits. Translate the
+ # shared cache-only contract into the official Qwen model hook so
+ # those chunks do not project every token over the full vocabulary.
+ if self.model_type == "qwen4_exp":
+ kwargs["skip_logits"] = True
inputs_embeds = kwargs.pop("inputs_embeds", None)
vlm_extra = kwargs.pop("vlm_extra_kwargs", None) or {}
vlm_extra.pop("_captured_rope_deltas", None)
@@ -350,7 +453,10 @@ def __call__(
if base_offsets is not None and deltas is not None:
positions = base_offsets + deltas.astype(base_offsets.dtype)
position_ids = self._position_ids_from_starts(
- positions, batch_size, seq_len
+ positions,
+ batch_size,
+ seq_len,
+ qwen4_text_prefill_positions=(qwen4_text_prefill_positions),
)
result = self._language_model(
input_ids, cache=cache, position_ids=position_ids, **kwargs
@@ -370,7 +476,10 @@ def __call__(
if offsets is not None:
batch_size, seq_len = input_ids.shape
position_ids = self._position_ids_from_starts(
- offsets, batch_size, seq_len
+ offsets,
+ batch_size,
+ seq_len,
+ qwen4_text_prefill_positions=(qwen4_text_prefill_positions),
)
result = self._language_model(
input_ids, cache=cache, position_ids=position_ids, **kwargs
diff --git a/omlx/oq.py b/omlx/oq.py
index 615c0fb867..41f9f1e37a 100644
--- a/omlx/oq.py
+++ b/omlx/oq.py
@@ -14,6 +14,7 @@
import logging
import re
import shutil
+import struct as _struct
import tempfile
import time as _time
from dataclasses import dataclass
@@ -34,6 +35,7 @@
from omlx.model_discovery import (
MLX_LM_TEXT_ONLY_MODEL_TYPES,
+ VLM_NATIVE_TEXT_MODEL_TYPES,
_has_vision_subconfig,
)
@@ -48,6 +50,43 @@
_GLM_INDEXER_Q8 = {"bits": 8, "group_size": 64, "mode": "affine"}
_GLM_INDEXER_PROJECTIONS = ("wq_b", "wk", "weights_proj")
+_QWEN4_EXP_NGRAM_GROUP_SIZE = 32
+_QWEN4_EXP_NGRAM_SHARD_RE = re.compile(
+ r"\.ple\.ple_embedding\.ngram_embedding\."
+ r"(?:shard_\d+|shards\.\d+)$"
+)
+
+
+def _is_qwen4_exp_config(config: dict) -> bool:
+ """Return whether *config* selects the Qwen4-Exp/Flash-Next family."""
+ text_config = config.get("text_config")
+ if not isinstance(text_config, dict):
+ text_config = {}
+ return any(
+ str(model_type or "").lower().startswith("qwen4_exp")
+ for model_type in (config.get("model_type"), text_config.get("model_type"))
+ )
+
+
+def _configure_qwen4_exp_quantization_runtime(
+ model_path: str | Path,
+ config: dict,
+ *,
+ preserve_mtp: bool,
+) -> bool:
+ """Register Qwen4 and bind its mmap PLE/MTP state for quantization."""
+ if not _is_qwen4_exp_config(config):
+ return False
+ from omlx.patches.mlx_vlm_qwen4_exp_compat import configure_qwen4_exp_runtime
+
+ configure_qwen4_exp_runtime(
+ model_path,
+ mode="mmap",
+ mtp_enabled=bool(preserve_mtp),
+ )
+ return True
+
+
_MAX_MODEL_RAM_FRACTION = 0.75
# Auto-built proxy for sensitivity measurement when the source model
@@ -140,12 +179,34 @@ def _is_vlm_load(config: dict) -> bool:
``mlx_vlm.speculative.drafters.`` lookup and fails.
"""
model_type = str(config.get("model_type", "")).lower().replace("-", "_")
- return (
+ return model_type in VLM_NATIVE_TEXT_MODEL_TYPES or (
_has_vision_subconfig(config)
and model_type not in MLX_LM_TEXT_ONLY_MODEL_TYPES
)
+def _calibration_model_settings(
+ config: dict,
+ *,
+ has_mtp_heads: bool,
+ has_mtp_weights: bool,
+):
+ """Build the temporary serving settings used by calibration loads."""
+ mtp_enabled = bool(has_mtp_heads and has_mtp_weights)
+ if not mtp_enabled and not _is_qwen4_exp_config(config):
+ return None
+ from types import SimpleNamespace
+
+ return SimpleNamespace(
+ mtp_enabled=mtp_enabled,
+ mtp_num_draft_tokens=1,
+ # Calibration executes Qwen4 PLE, but only as sparse row gathers.
+ # Force the existing SSD mmap path even when a compact proxy falls
+ # below serving's automatic offload threshold.
+ qwen4_ple_ssd_offload=_is_qwen4_exp_config(config),
+ )
+
+
def _uses_quantized_source_sensitivity(config: dict) -> bool:
"""Return whether source sensitivity must perturb quantized modules."""
quantization_config = config.get("quantization_config") or {}
@@ -309,7 +370,13 @@ def _glm_indexer_q8_override(path: str, config: dict) -> dict | None:
while making the saved checkpoint incompatible with the fused Q8 loader.
Keep backbone and preserved-MTP indexers on the same explicit format.
"""
- if config.get("model_type") != "glm_moe_dsa":
+ text_config = config.get("text_config")
+ text_model_type = (
+ text_config.get("model_type") if isinstance(text_config, dict) else None
+ )
+ if config.get("model_type") not in ("glm_moe_dsa", "glm5_next") and (
+ text_model_type != "glm5_next_text"
+ ):
return None
path = _normalize_quant_path(path)
if ".self_attn.indexer." not in path:
@@ -319,6 +386,31 @@ def _glm_indexer_q8_override(path: str, config: dict) -> dict | None:
return dict(_GLM_INDEXER_Q8)
+def _is_qwen4_exp_ngram_embedding_tensor(path: str, config: dict) -> bool:
+ """Return whether *path* is one Qwen4-Exp PLE embedding shard.
+
+ The source checkpoint spells shards as ``shard_N`` while the model
+ sanitizer maps them to the runtime module path ``shards.N``. Match both
+ forms so proxy construction and final streaming quantization use the same
+ policy.
+ """
+ if not _is_qwen4_exp_config(config):
+ return False
+ return _QWEN4_EXP_NGRAM_SHARD_RE.search(_normalize_quant_path(path)) is not None
+
+
+def _is_token_embedding_tensor(path: str) -> bool:
+ """Return whether a weight is indexed by token id rather than activations."""
+ return path.lower().endswith(
+ (
+ ".embed_tokens.weight",
+ ".tok_embeddings.weight",
+ ".word_embeddings.weight",
+ ".wte.weight",
+ )
+ )
+
+
def universal_quant_predicate(
path: str, module, config: dict, oq_level: int = 4
) -> Union[bool, dict]:
@@ -688,6 +780,29 @@ def _estimate_effective_bpw(
return total_bits / max(total_params, 1)
+def _structural_quant_overrides(
+ named_shapes: dict[str, tuple], config: dict, oq_level: int
+) -> dict[str, dict]:
+ """Layouts fixed by a model invariant rather than the bit allocator.
+
+ Qwen4-Exp PLE rows are 160 elements wide. The writer always uses group
+ size 32 for them, but pricing them at the default group size 64 makes the
+ planner classify the table as an unquantizable 16-bpw tensor. Since PLE
+ is about 51B parameters, that false cost can exhaust the entire budget and
+ suppress every protection boost even though the writer emits Q4/group32.
+ """
+ base_bits = _base_bits_for_level(oq_level)
+ return {
+ path: {
+ "bits": base_bits,
+ "group_size": _QWEN4_EXP_NGRAM_GROUP_SIZE,
+ "mode": "affine",
+ }
+ for path in named_shapes
+ if _is_qwen4_exp_ngram_embedding_tensor(path, config)
+ }
+
+
def _collect_named_weight_shapes_from_model(model) -> dict[str, tuple]:
"""Collect quantizable weight shapes from the in-memory model."""
named_shapes = {}
@@ -2190,12 +2305,25 @@ def moveaxis(self, src_ax, dst_ax):
new_shape = tuple(self.shape[d] for d in dims)
if self.transform == "nested_unreplayable":
return self._unreplayable(shape=new_shape)
+ op = ("moveaxis", src_ax, dst_ax)
+ if len(self.sources) > 1:
+ expr = self.as_expr()
+ expr = self._wrap_expr_op(expr, op) if expr is not None else None
+ if expr is None:
+ return self._unreplayable(shape=new_shape)
+ return _TrackedTensor(
+ new_shape,
+ self.dtype,
+ list(self.sources),
+ "expr",
+ expr=expr,
+ )
return _TrackedTensor(
new_shape,
self.dtype,
list(self.sources),
f"moveaxis_{src_ax}_{dst_ax}",
- recipe=list(self.recipe) + [("moveaxis", src_ax, dst_ax)],
+ recipe=list(self.recipe) + [op],
)
def transpose(self, *axes):
@@ -2350,6 +2478,7 @@ def _discover_sanitize_plan(sanitize_fn, lazy_index):
"contiguous": getattr(mx, "contiguous", None),
"from_fp8": getattr(mx, "from_fp8", None),
"pad": getattr(mx, "pad", None),
+ "issubdtype": mx.issubdtype,
}
def _is_plain_source(tensor):
@@ -2493,6 +2622,28 @@ def _fake_contiguous(tensor, *args, **kwargs):
def _noop(*a, **kw):
pass
+ def _fake_issubdtype(dtype, category):
+ if isinstance(dtype, str):
+ dtype = {
+ "BF16": mx.bfloat16,
+ "F16": mx.float16,
+ "F32": mx.float32,
+ "F64": mx.float32,
+ "F8_E4M3": mx.float16,
+ "F8_E5M2": mx.float16,
+ "F8_E8M0": mx.uint8,
+ "I8": mx.int8,
+ "I16": mx.int16,
+ "I32": mx.int32,
+ "I64": mx.int64,
+ "U8": mx.uint8,
+ "U16": mx.uint16,
+ "U32": mx.uint32,
+ "U64": mx.uint64,
+ "BOOL": mx.bool_,
+ }.get(dtype.upper(), dtype)
+ return _orig["issubdtype"](dtype, category)
+
mx.stack = _fake_stack
mx.concatenate = _fake_concatenate
mx.split = _fake_split
@@ -2502,6 +2653,7 @@ def _noop(*a, **kw):
mx.moveaxis = _fake_moveaxis
mx.transpose = _fake_transpose
mx.expand_dims = _fake_expand_dims
+ mx.issubdtype = _fake_issubdtype
if _orig["swapaxes"] is not None:
mx.swapaxes = _fake_swapaxes
if _orig["contiguous"] is not None:
@@ -3121,7 +3273,11 @@ def estimate_bpw_and_size(
# the raw header names when discovery is unavailable.
plan_view = None
try:
- _sanitize_fn = _build_model_sanitizer(config)
+ _sanitize_fn = _build_model_sanitizer(
+ config,
+ model_path=source,
+ preserve_mtp=preserve_mtp,
+ )
if _sanitize_fn is not None:
_plan = _discover_sanitize_plan(_sanitize_fn, idx)
if _plan:
@@ -3195,13 +3351,17 @@ def _source_quant_info(name):
pos_sens[str(i)] = 0.01
config["_oq_sensitivity_map"] = pos_sens
+ plan_fixed_overrides = {
+ **fixed_overrides,
+ **_structural_quant_overrides(named_shapes, config, oq_level),
+ }
plan = _build_quant_plan(
named_shapes,
config,
oq_level,
target_bpw=_level_targets[0],
hard_cap_bpw=_level_targets[1],
- fixed_overrides=fixed_overrides,
+ fixed_overrides=plan_fixed_overrides,
)
config["_oq_boost_map"] = plan.boost_map
else:
@@ -3375,6 +3535,51 @@ def _checkpoint_storage_bytes(weight_files) -> int:
return total
+def _calibration_resident_checkpoint_bytes(
+ model_path: str | Path,
+ config: dict,
+) -> int:
+ """Estimate checkpoint bytes touched by calibration model forwards.
+
+ Ordinary architectures retain the historical complete-file accounting.
+ Qwen4-Exp calibration reads PLE rows through SSD mmap and its manual text
+ layer walk invokes neither the vision tower nor the ordinary ``lm_head``.
+ Safetensors headers and every other tensor remain charged to the model.
+ """
+ weight_files = sorted(Path(model_path).glob("*.safetensors"))
+ checkpoint_bytes = _checkpoint_storage_bytes(weight_files)
+ if not _is_qwen4_exp_config(config):
+ return checkpoint_bytes
+
+ deferred_bytes = 0
+ for path in weight_files:
+ try:
+ with path.open("rb") as file:
+ raw_size = file.read(8)
+ if len(raw_size) != 8:
+ continue
+ header_size = _struct.unpack(" int:
# --- chunked-quantize helpers (added for Qwen3.5-397B) ---------------------
-import struct as _struct
-
import numpy as _np
@@ -4336,6 +4620,16 @@ def source_shape(self, key):
meta = self._index.get(key)
return None if meta is None else meta[4]
+ def source_dtype(self, key):
+ """Safetensors dtype spelling for ``key``, or None when absent.
+
+ Model-specific virtual-tensor registrars use this alongside
+ :meth:`source_shape` to distinguish packed storage from an already
+ materialized floating-point checkpoint without reading tensor data.
+ """
+ meta = self._index.get(key)
+ return None if meta is None else meta[5]
+
def load_source(self, key):
"""Load an on-disk tensor verbatim, bypassing fp8 pairing."""
return self._load_raw(key)
@@ -4902,6 +5196,10 @@ def _source_imatrix_signature(
# Invalidate caches produced by the old independent-block walk, which
# captured only q_proj in the shared-KV tail of E2B/E4B.
signature["layer_walk"] = "gemma4_shared_kv_v1"
+ elif str(config.get("model_type", "")).lower() == "glm5_next":
+ # GLM-5.3 needs its mHC-expanded layer walk plus the untied output-head
+ # capture. Older caches completed without either and must not be reused.
+ signature["layer_walk"] = "glm5_next_hc_moe_lm_head_v4"
return signature
@@ -5083,14 +5381,42 @@ def _lookup_imatrix_importance(
tensor_name: str,
shape: tuple[int, ...],
*,
+ config: dict | None = None,
strict: bool,
report: dict[str, Any] | None,
):
if imatrix is None or not tensor_name.endswith(".weight"):
return None
+ if config is not None and _is_qwen4_exp_ngram_embedding_tensor(
+ tensor_name, config
+ ):
+ # The collector measures Linear/SwitchLinear input channels, not
+ # embedding rows. Do not turn the intentionally uniform PLE policy
+ # into a missing-entry error under imatrix_strict.
+ return None
+ if _is_token_embedding_tensor(tensor_name):
+ # Embedding columns are gathered by token id, not consumed as input
+ # activation channels, so a Linear-style imatrix entry cannot exist.
+ return None
base = tensor_name[: -len(".weight")]
entry = imatrix.entries.get(base)
+ if entry is None and config is not None:
+ text_config = config.get("text_config")
+ text_model_type = (
+ text_config.get("model_type") if isinstance(text_config, dict) else None
+ )
+ if (
+ config.get("model_type") == "glm5_next"
+ or text_model_type == "glm5_next_text"
+ ) and base.endswith(".self_attn.indexer.weights_proj"):
+ # The GLM-5.3 indexer feeds the same hidden-state input to wk and
+ # weights_proj. Short calibration sequences bypass sparse scoring
+ # after wk, before weights_proj is called, so its wrapper cannot
+ # collect a separate entry. Reuse the mathematically identical wk
+ # input-channel statistics instead of weakening strict coverage.
+ wk_base = base[: -len("weights_proj")] + "wk"
+ entry = imatrix.entries.get(wk_base)
if entry is None:
if report is not None:
report["missing"].append(base)
@@ -5532,7 +5858,8 @@ def cb(
logger.info(
f"oQ{oq_level:g}: calibration footprint ({_format_size(_calibration_bytes)}) "
f"exceeds {int(_MAX_MODEL_RAM_FRACTION * 100)}% of calibration "
- f"capacity ({_format_size(int(_calibration_budget['capacity_bytes']))}; "
+ "capacity "
+ f"({_format_size(int(_calibration_budget['capacity_bytes']))}; "
f"limit={_format_size(int(_calibration_budget['model_limit_bytes']))}, "
"system available="
f"{_format_size(int(_calibration_budget['system_available_bytes']))}, "
@@ -5573,25 +5900,27 @@ def _ensure_ram_safe_proxy() -> Path:
preserve_mtp=preserve_mtp,
)
proxy_bytes = _checkpoint_storage_bytes(candidate.glob("*.safetensors"))
- proxy_budget = _calibration_memory_budget(
- proxy_bytes,
- fallback_system_bytes=_system_ram,
+ proxy_resident_bytes = _calibration_resident_checkpoint_bytes(
+ candidate,
+ config,
)
- if int(proxy_budget["capacity_bytes"]) > 0 and bool(
- proxy_budget["requires_proxy"]
- ):
+ prebuild_capacity = int(_calibration_budget["capacity_bytes"])
+ prebuild_limit = int(_calibration_budget["model_limit_bytes"])
+ if prebuild_capacity > 0 and proxy_resident_bytes > prebuild_limit:
shutil.rmtree(candidate, ignore_errors=True)
raise RuntimeError(
- "calibration proxy is still too large for the live memory "
- f"budget (proxy={_format_size(proxy_bytes)}, "
- f"limit={_format_size(int(proxy_budget['model_limit_bytes']))}, "
- f"capacity={_format_size(int(proxy_budget['capacity_bytes']))})"
+ "calibration proxy is still too large for the pre-build live "
+ f"memory budget (proxy={_format_size(proxy_bytes)}, "
+ f"resident={_format_size(proxy_resident_bytes)}, "
+ f"limit={_format_size(prebuild_limit)}, "
+ f"capacity={_format_size(prebuild_capacity)})"
)
_ram_safe_proxy_dir = candidate
logger.info(
f"oQ{oq_level:g}: calibration proxy size "
- f"{_format_size(proxy_bytes)} within "
- f"{_format_size(int(proxy_budget['model_limit_bytes']))} limit"
+ f"{_format_size(proxy_bytes)} on disk, resident calibration "
+ f"footprint {_format_size(proxy_resident_bytes)} within "
+ f"{_format_size(prebuild_limit)} pre-build live memory limit"
)
return _ram_safe_proxy_dir
@@ -5791,7 +6120,12 @@ def _imatrix_load_path() -> str:
)
# --- Sanitize-plan discovery ------------------------------------------
- sanitize_fn = _build_model_sanitizer(config, text_only=text_only)
+ sanitize_fn = _build_model_sanitizer(
+ config,
+ text_only=text_only,
+ model_path=source,
+ preserve_mtp=preserve_mtp,
+ )
cast_predicate = getattr(sanitize_fn, "_omlx_cast_predicate", None)
# When preserve_mtp is True, the patched sanitize functions
# (mlx_lm_mtp/qwen35_model.py and mlx_vlm_mtp/qwen35_vlm_model.py)
@@ -5878,13 +6212,17 @@ def _imatrix_load_path() -> str:
if _level_targets is not None:
_t = target_bpw if target_bpw is not None else _level_targets[0]
_c = hard_cap_bpw if hard_cap_bpw is not None else _level_targets[1]
+ plan_fixed_overrides = {
+ **fixed_overrides,
+ **_structural_quant_overrides(named_shapes, config, oq_level),
+ }
plan = _build_quant_plan(
named_shapes,
config,
oq_level,
target_bpw=_t,
hard_cap_bpw=_c,
- fixed_overrides=fixed_overrides,
+ fixed_overrides=plan_fixed_overrides,
)
config["_oq_boost_map"] = plan.boost_map
logger.info(
@@ -5987,6 +6325,7 @@ def _imatrix_load_path() -> str:
imatrix_data,
tensor_name,
tuple(shape),
+ config=config,
strict=imatrix_strict,
report=imatrix_report,
)
@@ -6197,6 +6536,7 @@ def _imatrix_load_path() -> str:
_OQE_MIN_EXPERT_COUNT = 16
_OQE_MIN_EXPERT_COUNT_PERCENTILE = 5
_OQE_SWITCH_LINEAR_CLASSES = {"SwitchLinear", "QuantizedSwitchLinear"}
+_OQE_MULTI_LINEAR_CLASSES = {"MultiLinear", "QuantizedMultiLinear"}
_OQ_CODE_MULTILINGUAL_KEYS = (
"code",
"en",
@@ -6509,6 +6849,8 @@ def _find_model_layers(model):
_GEMMA4_LAYER_STATE_KIND = "gemma4_shared_kv"
+_QWEN4_EXP_LAYER_STATE_KIND = "qwen4_exp"
+_GLM5_NEXT_LAYER_STATE_KIND = "glm5_next"
def _find_layer_model(model, layers):
@@ -6655,6 +6997,57 @@ def _prepare_gemma4_layer_inputs(model, layers, calib_data, inputs):
return inputs, layer_masks, state
+def _prepare_qwen4_exp_layer_inputs(model, layers, calib_data, inputs):
+ """Build Qwen4-Exp's hyper-connection layer-walk inputs.
+
+ Qwen4 decoder blocks do not use the generic Transformer signature. The
+ trunk tiles token embeddings across ``hc_count`` residual streams and each
+ block receives the original token ids before mask/cache/position state.
+ Replaying a block with the generic calibration call silently skips every
+ layer, leaving an installed oQe collector with zero captured entries.
+ """
+ layer_model = _find_layer_model(model, layers)
+ if layer_model is None:
+ return None
+ args = getattr(layer_model, "args", None)
+ model_type = str(getattr(args, "model_type", "")).lower()
+ if not model_type.startswith("qwen4_exp"):
+ return None
+
+ hc_count = _object_config_int(args, "hc_count")
+ hidden_size = _object_config_int(args, "hidden_size")
+ if hc_count <= 0 or hidden_size <= 0:
+ raise RuntimeError(
+ "Qwen4-Exp calibration requires positive hc_count and hidden_size"
+ )
+ expected_width = hc_count * hidden_size
+ if int(inputs.shape[-1]) == hidden_size:
+ inputs = mx.tile(inputs, (1, 1, hc_count))
+ elif int(inputs.shape[-1]) != expected_width:
+ raise RuntimeError(
+ "Qwen4-Exp calibration received an invalid hidden width: "
+ f"{int(inputs.shape[-1])} (expected {hidden_size} or {expected_width})"
+ )
+
+ seq_len = int(calib_data.shape[1])
+ full_attention_mask = nn.MultiHeadAttention.create_additive_causal_mask(seq_len)
+ full_attention_mask = full_attention_mask.astype(inputs.dtype)
+ layer_masks = [
+ None if bool(getattr(layer, "is_linear", False)) else full_attention_mask
+ for layer in layers
+ ]
+ position_ids = mx.broadcast_to(
+ mx.arange(seq_len, dtype=mx.int32)[None],
+ (int(calib_data.shape[0]), seq_len),
+ )
+ state = {
+ "kind": _QWEN4_EXP_LAYER_STATE_KIND,
+ "input_ids": calib_data,
+ "position_ids": position_ids,
+ }
+ return inputs, layer_masks, state
+
+
def _forward_gemma4_layer_result(block, inputs, mask, state, layer_idx: int):
if not 0 <= int(layer_idx) < len(state["previous_kvs"]):
raise RuntimeError(f"Invalid Gemma 4 calibration layer index: {layer_idx}")
@@ -6705,6 +7098,40 @@ def _forward_layer_result(block, inputs, mask, position_ids, layer_idx=None):
return _forward_gemma4_layer_result(
block, inputs, mask, position_ids, int(layer_idx)
)
+ if (
+ isinstance(position_ids, dict)
+ and position_ids.get("kind") == _QWEN4_EXP_LAYER_STATE_KIND
+ ):
+ try:
+ result = block(
+ inputs,
+ position_ids["input_ids"],
+ mask=mask,
+ cache=None,
+ position_ids=position_ids["position_ids"],
+ )
+ except (TypeError, ValueError, RuntimeError, AttributeError) as e:
+ suffix = f" at layer {layer_idx}" if layer_idx is not None else ""
+ raise RuntimeError(
+ f"Qwen4-Exp calibration forward failed{suffix}: {e}"
+ ) from e
+ if isinstance(result, tuple):
+ return result[0], result[1] if len(result) > 1 else None
+ return result, None
+ if (
+ isinstance(position_ids, dict)
+ and position_ids.get("kind") == _GLM5_NEXT_LAYER_STATE_KIND
+ ):
+ try:
+ result = block(inputs, mask=mask, cache=None)
+ except (TypeError, ValueError, RuntimeError, AttributeError) as e:
+ suffix = f" at layer {layer_idx}" if layer_idx is not None else ""
+ raise RuntimeError(
+ f"GLM-5.3 calibration forward failed{suffix}: {e}"
+ ) from e
+ if isinstance(result, tuple):
+ return result[0], result[1] if len(result) > 1 else None
+ return result, None
if isinstance(position_ids, dict) and position_ids.get("kind") == "glm_moe_dsa":
try:
result = block(
@@ -6880,6 +7307,28 @@ def _prepare_layer_inputs(model, layers, calib_data, inputs):
gemma4_inputs = _prepare_gemma4_layer_inputs(model, layers, calib_data, inputs)
if gemma4_inputs is not None:
return gemma4_inputs
+ qwen4_exp_inputs = _prepare_qwen4_exp_layer_inputs(
+ model, layers, calib_data, inputs
+ )
+ if qwen4_exp_inputs is not None:
+ return qwen4_exp_inputs
+ if model_type == "glm5_next":
+ language_model = getattr(model, "language_model", None)
+ args = getattr(language_model, "args", None)
+ hc_mult = _object_config_int(args, "hc_mult")
+ if hc_mult <= 0:
+ raise RuntimeError("GLM-5.3 calibration requires a positive hc_mult")
+ hidden = mx.broadcast_to(
+ inputs[:, :, None, :],
+ (inputs.shape[0], inputs.shape[1], hc_mult, inputs.shape[2]),
+ )
+ hidden = mx.contiguous(hidden)
+ attention_mask = create_attention_mask(inputs, None, return_array=True)
+ masks = [
+ None if bool(getattr(layer, "is_linear", False)) else attention_mask
+ for layer in layers
+ ]
+ return hidden, masks, {"kind": _GLM5_NEXT_LAYER_STATE_KIND}
if model_type.startswith("deepseek_v4"):
args = model.args
h = mx.broadcast_to(
@@ -6939,9 +7388,17 @@ def __call__(self, *args, **kwargs):
self._collector.collect_switch(
self._name, self._module, args[0], args[1]
)
+ elif type(self._module).__name__ in _OQE_MULTI_LINEAR_CLASSES:
+ transpose = kwargs.get("transpose", args[1] if len(args) >= 2 else True)
+ self._collector.collect_multi(
+ self._name, self._module, args[0], transpose=transpose
+ )
else:
self._collector.collect_dense(self._name, self._module, args[0])
- return self._module(*args, **kwargs)
+ result = self._module(*args, **kwargs)
+ if args and self._name.endswith(".self_attn.q_b_proj"):
+ self._collector.collect_glm5_next_embed_q(self._name, result)
+ return result
class OQImatrixCollector:
@@ -6950,6 +7407,7 @@ class OQImatrixCollector:
def __init__(self):
self.entries: dict[str, OQImatrixEntry] = {}
self._original_modules: dict[str, Any] = {}
+ self._saved_attributes: list[tuple[Any, str, Any]] = []
self.capture_module_classes: dict[str, int] = {}
self.switch_capture_modules = 0
@@ -6958,6 +7416,8 @@ def _is_capture_module(module) -> bool:
cls = type(module).__name__
if cls in _OQE_SWITCH_LINEAR_CLASSES:
return hasattr(module, "weight") and getattr(module.weight, "ndim", 0) == 3
+ if cls in _OQE_MULTI_LINEAR_CLASSES:
+ return hasattr(module, "weight") and getattr(module.weight, "ndim", 0) == 3
# QuantizedLinear capture lets imatrix collection run against
# already-quantized checkpoints (e.g. deriving a recalibrated MTP
# head from an oQ8 model when the bf16 source is gone).
@@ -6978,6 +7438,15 @@ def _module_in_dim(module) -> int:
def install(self, model) -> int:
replacements = []
for name, module in model.named_modules():
+ if type(module).__name__ == "Glm5NextLinearAttention" and bool(
+ getattr(module, "fuse_in", False)
+ ):
+ # The fused KDA input projection reads six Linear weights
+ # directly, bypassing their calls and therefore the capture
+ # wrappers. Calibration temporarily takes the equivalent
+ # unfused path so every input-channel statistic is observed.
+ self._saved_attributes.append((module, "fuse_in", module.fuse_in))
+ module.fuse_in = False
if not name or not self._is_capture_module(module):
continue
cls = type(module).__name__
@@ -6999,6 +7468,9 @@ def restore(self, model) -> None:
strict=False,
)
self._original_modules.clear()
+ for module, attribute, value in self._saved_attributes:
+ setattr(module, attribute, value)
+ self._saved_attributes.clear()
def _ensure_entry(self, name: str, sums_shape, counts_shape) -> OQImatrixEntry:
entry = self.entries.get(name)
@@ -7025,6 +7497,65 @@ def collect_dense(self, name: str, module, x) -> None:
except Exception as e:
logger.debug("oQe imatrix dense capture skipped for %s: %s", name, e)
+ def collect_multi(self, name: str, module, x, *, transpose: bool = True) -> None:
+ """Capture per-head input energy for MLA MultiLinear weights."""
+ try:
+ if not transpose:
+ # The same MLA projection may be used in reverse. Quantization
+ # groups the stored weight's last dimension, whose matching
+ # activation is observed by the normal transpose=True call.
+ return
+ weight = module.weight
+ n_heads = int(weight.shape[0])
+ bits = getattr(module, "bits", None)
+ in_dim = (
+ int(weight.shape[-1] * 32 // int(bits))
+ if bits and weight.dtype == mx.uint32
+ else int(weight.shape[-1])
+ )
+ if not getattr(x, "shape", ()) or int(x.shape[-1]) != in_dim:
+ return
+ mx.eval(x)
+ x_np = np.asarray(x.astype(mx.float32))
+ if x_np.ndim >= 2 and x_np.shape[-2] in (1, n_heads):
+ per_head = np.moveaxis(x_np, -2, 0).reshape(x_np.shape[-2], -1, in_dim)
+ if per_head.shape[0] == 1 and n_heads > 1:
+ per_head = np.repeat(per_head, n_heads, axis=0)
+ else:
+ shared = x_np.reshape(-1, in_dim)
+ per_head = np.repeat(shared[None], n_heads, axis=0)
+ entry = self._ensure_entry(name, (n_heads, in_dim), (n_heads,))
+ entry.in_sum2 += np.square(per_head, dtype=np.float32).sum(axis=1)
+ entry.counts += per_head.shape[1]
+ except Exception as e:
+ logger.debug("oQe imatrix multi capture skipped for %s: %s", name, e)
+
+ def collect_glm5_next_embed_q(self, q_b_name: str, q) -> None:
+ """Capture the GLM-5.3 embed_q input from q_b_proj's exact output.
+
+ Short calibration sequences take the algebraically equivalent reverse
+ embed_q path, whose activation width does not match the stored weight's
+ quantization axis. Long sparse-attention requests use the forward path
+ on q_b_proj's reshaped output, so collect that tensor directly without
+ forcing calibration past the production indexer's short-prefix bypass.
+ """
+ embed_name = q_b_name[: -len("q_b_proj")] + "embed_q"
+ module = self._original_modules.get(embed_name)
+ if module is None or type(module).__name__ not in _OQE_MULTI_LINEAR_CLASSES:
+ return
+ try:
+ weight = module.weight
+ n_heads = int(weight.shape[0])
+ in_dim = self._module_in_dim(module)
+ if not getattr(q, "shape", ()) or int(q.shape[-1]) != n_heads * in_dim:
+ return
+ shaped_q = q.reshape(*q.shape[:-1], n_heads, in_dim)
+ self.collect_multi(embed_name, module, shaped_q)
+ except Exception as e:
+ logger.debug(
+ "oQe GLM-5.3 embed_q capture skipped for %s: %s", embed_name, e
+ )
+
@staticmethod
def _accumulate_switch(
entry: OQImatrixEntry,
@@ -7100,6 +7631,29 @@ def collect_switch(self, name: str, module, x, indices) -> None:
logger.debug("oQe imatrix switch capture skipped for %s: %s", name, e)
+def _collect_glm5_next_lm_head_imatrix(model, hidden, collector) -> bool:
+ """Capture the untied GLM-5.3 output head without materializing logits."""
+ if str(getattr(model, "model_type", "")) != "glm5_next":
+ return False
+
+ language_model = getattr(model, "language_model", None)
+ core = getattr(language_model, "model", None)
+ norm = getattr(core, "norm", None)
+ if language_model is None or core is None or norm is None:
+ return False
+
+ name = "language_model.lm_head"
+ module = collector._original_modules.get(name)
+ if module is None:
+ # Tied checkpoints project through embed_tokens and have no lm_head.
+ return False
+
+ if getattr(hidden, "ndim", 0) == 4:
+ hidden = hidden.mean(axis=2)
+ collector.collect_dense(name, module, norm(hidden))
+ return name in collector.entries
+
+
def _collect_mtp_head_imatrix(
model,
batch,
@@ -7117,6 +7671,12 @@ def _collect_mtp_head_imatrix(
"""
inner = getattr(model, "language_model", None) or model
mtp = getattr(inner, "mtp", None)
+ if mtp is None:
+ get_mtp_module = getattr(inner, "get_mtp_module", None)
+ if callable(get_mtp_module):
+ mtp = get_mtp_module()
+ if mtp is None:
+ mtp = getattr(model, "mtp", None)
if mtp is None:
return False
try:
@@ -7130,6 +7690,23 @@ def _collect_mtp_head_imatrix(
out = dspark_calibration(target_hidden, batch)
mx.eval(out)
return True
+ if type(mtp).__name__ == "Qwen4ExpMTPModule":
+ core = getattr(inner, "model", None) or inner
+ embed = getattr(core, "embed_tokens", None)
+ if embed is None:
+ return False
+ make_cache = getattr(inner, "make_mtp_cache", None)
+ mtp_cache = (
+ make_cache()
+ if callable(make_cache)
+ else [None for _ in getattr(mtp, "layers", ())]
+ )
+ out = mtp(hidden[:, :-1, :], batch[:, 1:], embed, mtp_cache)
+ if isinstance(out, tuple):
+ mx.eval(*out)
+ else:
+ mx.eval(out)
+ return True
if isinstance(mtp, (list, tuple)):
# DeepSeek-V4 style: MTPBlock stack consuming the raw (4D)
# trunk hidden; Model.mtp_forward wires mask/cache/embedding.
@@ -7190,11 +7767,33 @@ def _collect_imatrix_from_model(
seq_length=seq_length,
)
if calib_data is None:
- return {}, {"dataset": calib_dataset, "processed_samples": 0}
+ return {}, {
+ "dataset": calib_dataset,
+ "processed_samples": 0,
+ "failure_stage": "dataset",
+ "failure_reason": "calibration dataset produced no usable samples",
+ }
embed_fn, layers = _find_model_layers(model)
if embed_fn is None or layers is None:
- return {}, {"dataset": calib_dataset, "processed_samples": 0}
+ return {}, {
+ "dataset": calib_dataset,
+ "processed_samples": 0,
+ "model_class": f"{type(model).__module__}.{type(model).__name__}",
+ "failure_stage": "layer_discovery",
+ "failure_reason": "no embedding function or decoder layers found",
+ }
+
+ layer_model = _find_layer_model(model, layers)
+ layer_args = getattr(layer_model, "args", None)
+ layer_config = getattr(layer_model, "config", None)
+ layer_model_type = str(
+ getattr(layer_args, "model_type", "")
+ or getattr(layer_config, "model_type", "")
+ or getattr(model, "model_type", "")
+ or ""
+ )
+ layer_count = len(layers)
collector = OQImatrixCollector()
installed = collector.install(model)
@@ -7203,6 +7802,16 @@ def _collect_imatrix_from_model(
"dataset": calib_dataset,
"installed_modules": 0,
"processed_samples": 0,
+ "model_class": f"{type(model).__module__}.{type(model).__name__}",
+ "layer_model_class": (
+ f"{type(layer_model).__module__}.{type(layer_model).__name__}"
+ if layer_model is not None
+ else None
+ ),
+ "layer_model_type": layer_model_type,
+ "layer_count": layer_count,
+ "failure_stage": "collector_install",
+ "failure_reason": "no supported capture modules found",
}
available_samples = int(calib_data.shape[0])
@@ -7225,6 +7834,10 @@ def _collect_imatrix_from_model(
micro_batch_size = int(batch_plan["micro_batch_size"])
processed_samples = 0
micro_batches = 0
+ layer_state_kind = None
+ successful_layer_forwards = 0
+ skipped_layer_forwards = 0
+ mtp_head_forwards = 0
rounds: list[dict[str, Any]] = []
require_expert_counts = _imatrix_requires_expert_counts(
config, collector.switch_capture_modules
@@ -7254,6 +7867,10 @@ def _collect_imatrix_from_model(
inputs, layer_masks, position_ids = _prepare_layer_inputs(
model, layers, batch, inputs
)
+ if isinstance(position_ids, dict):
+ layer_state_kind = position_ids.get("kind")
+ elif layer_state_kind is None:
+ layer_state_kind = "generic"
inner = getattr(model, "language_model", None) or model
args = getattr(inner, "args", None)
@@ -7280,7 +7897,9 @@ def _collect_imatrix_from_model(
layer_idx=layer_idx,
)
if out is None:
+ skipped_layer_forwards += 1
continue
+ successful_layer_forwards += 1
mx.eval(out)
inputs = out
# DSpark config uses one-based completed layer depths,
@@ -7294,6 +7913,8 @@ def _collect_imatrix_from_model(
mx.synchronize()
mx.clear_cache()
+ _collect_glm5_next_lm_head_imatrix(model, inputs, collector)
+
# MTP-head pass: the layer walk above leaves ``inputs`` as
# the final-layer hidden states; feed them (post-norm) plus
# the shifted token ids through the head so its linears
@@ -7304,6 +7925,7 @@ def _collect_imatrix_from_model(
inputs,
dspark_hiddens=dspark_hiddens,
):
+ mtp_head_forwards += 1
mx.synchronize()
mx.clear_cache()
@@ -7403,6 +8025,18 @@ def _collect_imatrix_from_model(
"micro_batches": micro_batches,
"batch_plan": batch_plan,
"processed_samples": processed_samples,
+ "model_class": f"{type(model).__module__}.{type(model).__name__}",
+ "layer_model_class": (
+ f"{type(layer_model).__module__}.{type(layer_model).__name__}"
+ if layer_model is not None
+ else None
+ ),
+ "layer_model_type": layer_model_type,
+ "layer_count": layer_count,
+ "layer_state_kind": layer_state_kind,
+ "successful_layer_forwards": successful_layer_forwards,
+ "skipped_layer_forwards": skipped_layer_forwards,
+ "mtp_head_forwards": mtp_head_forwards,
"installed_modules": installed,
"capture_module_classes": dict(
sorted(collector.capture_module_classes.items())
@@ -7414,6 +8048,19 @@ def _collect_imatrix_from_model(
"coverage": coverage,
"rounds": rounds,
}
+ if not collector.entries:
+ metadata["failure_stage"] = "layer_forward"
+ if successful_layer_forwards == 0:
+ metadata["failure_reason"] = (
+ "no decoder layer forward completed successfully"
+ )
+ else:
+ metadata["failure_stage"] = "capture"
+ metadata["failure_reason"] = (
+ f"{installed} hooks were installed and "
+ f"{successful_layer_forwards} layer forwards completed, "
+ "but no hook captured a compatible activation"
+ )
return collector.entries, metadata
@@ -7437,10 +8084,19 @@ def _collect_imatrix(
is_vlm = _is_vlm_load(config)
has_mtp_weights = _checkpoint_has_mtp_weights(model_path)
- maybe_apply_pre_load_patches(model_path, for_vlm=is_vlm)
+ has_mtp_heads = _has_mtp_heads(config)
+ calibration_settings = _calibration_model_settings(
+ config,
+ has_mtp_heads=has_mtp_heads,
+ has_mtp_weights=has_mtp_weights,
+ )
+ patch_kwargs: dict[str, Any] = {"for_vlm": is_vlm}
+ if calibration_settings is not None:
+ patch_kwargs["model_settings"] = calibration_settings
+ maybe_apply_pre_load_patches(model_path, **patch_kwargs)
restore_mtp_active = None
- if _has_mtp_heads(config) and has_mtp_weights:
+ if has_mtp_heads and has_mtp_weights:
# Attach the MTP head on the temporary calibration model so the
# head-forward pass in _collect_imatrix_from_model can exercise its
# linears (they'd otherwise land in the imatrix "missing" list).
@@ -7467,24 +8123,19 @@ def _restore_mtp_active():
try:
if is_vlm:
- import mlx.nn as _nn
from mlx_vlm.utils import load_model as vlm_load_model
- _orig_lw = _nn.Module.load_weights
-
- def _lenient_load_weights(self, file_or_weights, *args, **kwargs):
- kwargs.pop("strict", None)
- return _orig_lw(self, file_or_weights, *args, strict=False, **kwargs)
-
- _nn.Module.load_weights = _lenient_load_weights
- try:
- model = vlm_load_model(
- Path(model_path),
- lazy=True,
- trust_remote_code=trust_remote_code,
- )
- finally:
- _nn.Module.load_weights = _orig_lw
+ # Calibration proxies deliberately retain SSD-mapped tensors that
+ # are consumed by model-specific mmap modules rather than owned as
+ # normal MLX parameters (Qwen4 PLE shards are the primary case).
+ # mlx-vlm exposes ``strict`` specifically for this final weight
+ # load; pass it directly instead of monkeypatching Module globally.
+ model = vlm_load_model(
+ Path(model_path),
+ lazy=True,
+ trust_remote_code=trust_remote_code,
+ strict=False,
+ )
from mlx_lm.tokenizer_utils import load as load_tokenizer
tokenizer = load_tokenizer(Path(model_path))
@@ -7499,13 +8150,13 @@ def _lenient_load_weights(self, file_or_weights, *args, **kwargs):
)
except Exception as e:
logger.error("oQe imatrix: model load failed (%s)", e)
- return {}, {"dataset": calib_dataset, "processed_samples": 0}
+ raise RuntimeError(f"oQe imatrix model load failed: {e}") from e
finally:
if restore_mtp_active is not None:
restore_mtp_active()
try:
- model_bytes = _checkpoint_storage_bytes(Path(model_path).glob("*.safetensors"))
+ model_bytes = _calibration_resident_checkpoint_bytes(model_path, config)
return _collect_imatrix_from_model(
model,
tokenizer,
@@ -7524,14 +8175,19 @@ def _lenient_load_weights(self, file_or_weights, *args, **kwargs):
mx.clear_cache()
-def _oqe_cache_missing_mtp_entries(cache: OQImatrixData, config: dict) -> bool:
+def _oqe_cache_missing_mtp_entries(
+ cache: OQImatrixData, config: dict, model_path: str
+) -> bool:
"""True when the model declares MTP heads but the cache predates the
MTP-head collection pass (no ``mtp.*`` entries) — force a recollect so
the head gets calibrated quantization instead of landing in "missing"."""
try:
- from omlx.utils.model_loading import _has_mtp_heads
+ from omlx.utils.model_loading import (
+ _checkpoint_has_mtp_weights,
+ _has_mtp_heads,
+ )
- if not _has_mtp_heads(config):
+ if not _has_mtp_heads(config) or not _checkpoint_has_mtp_weights(model_path):
return False
except Exception:
return False
@@ -7568,7 +8224,7 @@ def _load_or_collect_imatrix(
if reuse_cache and path.exists():
cache = _load_oqe_imatrix(path)
if _oqe_cache_matches(cache, expected):
- if _oqe_cache_missing_mtp_entries(cache, config):
+ if _oqe_cache_missing_mtp_entries(cache, config, model_path):
logger.info(
"oQe imatrix: cache predates MTP-head collection "
"(no mtp.* entries), recollecting %s",
@@ -7619,7 +8275,16 @@ def _load_or_collect_imatrix(
progress_end=progress_end,
)
if not entries:
- raise RuntimeError("oQe imatrix collection produced no entries")
+ stage = str(collection_metadata.get("failure_stage", "unknown"))
+ reason = str(
+ collection_metadata.get(
+ "failure_reason", "collector returned no captured activations"
+ )
+ )
+ raise RuntimeError(
+ "oQe imatrix collection produced no entries "
+ f"(stage={stage}: {reason})"
+ )
metadata = {
**expected,
"entry_count": len(entries),
@@ -7756,24 +8421,28 @@ def _measure_sensitivity(
# ship a vision_config but must load through the patched mlx-lm class.
is_vlm = _is_vlm_load(config)
has_mtp_weights = _checkpoint_has_mtp_weights(model_path)
+ has_mtp_heads = _has_mtp_heads(config)
# Reuse the centralised pre-load dispatch so every current and future
# patch (MTP sanitize, DeepSeek V4, nested-visual, load_config, …) is
# applied exactly as in the production load path.
- maybe_apply_pre_load_patches(model_path, for_vlm=is_vlm)
-
- # maybe_apply_pre_load_patches leaves mtp_active False, which is correct
- # for the text path: the patched qwen35_model.sanitize self-consistently
- # strips mtp.* when no head is attached. The VLM path needs both patches.
- # apply_mlx_vlm_mtp_patch fixes Model.sanitize so language_model.mtp.*
- # weights survive the load with the correct keys (stock mlx-vlm sanitize
- # strips them, which is what made the strict load fail with "Missing N
- # parameters" and the measurement silently return {}). The runtime patch
- # then attaches the MTP head so the checkpoint matches the model. Both
- # are idempotent. Sensitivity only reads backbone decoder layers, so this
- # is load-only.
+ calibration_settings = _calibration_model_settings(
+ config,
+ has_mtp_heads=has_mtp_heads,
+ has_mtp_weights=has_mtp_weights,
+ )
+ patch_kwargs: dict[str, Any] = {"for_vlm": is_vlm}
+ if calibration_settings is not None:
+ patch_kwargs["model_settings"] = calibration_settings
+ maybe_apply_pre_load_patches(model_path, **patch_kwargs)
+
+ # The central dispatch receives an explicit MTP calibration setting so
+ # model-specific constructors such as Qwen4's root-owned MTP head are
+ # enabled before load. The VLM patch below also covers the generic
+ # qwen3_5 classes whose MTP module is attached by the shared runtime.
+ # Sensitivity only reads backbone decoder layers, so this is load-only.
restore_mtp_active = None
- if is_vlm and _has_mtp_heads(config) and has_mtp_weights:
+ if is_vlm and has_mtp_heads and has_mtp_weights:
try:
from omlx.patches.mlx_lm_mtp import is_mtp_active, set_mtp_active
from omlx.patches.mlx_vlm_mtp import (
@@ -7791,31 +8460,17 @@ def _measure_sensitivity(
try:
if is_vlm:
- import mlx.nn as _nn
from mlx_vlm.utils import load_model as vlm_load_model
- # mlx_vlm.load_model calls model.load_weights(weights) without strict=False.
- # Shared-KV models (e.g. Gemma 4 2B/4B) omit k/v weights for shared layers,
- # so strict=True raises ValueError. Relax temporarily — sensitivity only needs
- # approximate weights; shared layers receive pre-computed KV at inference time.
- _orig_lw = _nn.Module.load_weights
-
- def _lenient_load_weights(self, file_or_weights, *args, **kwargs):
- kwargs.pop("strict", None)
- return _orig_lw(self, file_or_weights, *args, strict=False, **kwargs)
-
- _nn.Module.load_weights = _lenient_load_weights
- try:
- # No QAT config override needed here: mlx_vlm.utils.load_model
- # uses quantization_config.get("quant_method") rather than direct
- # key access, so a missing quant_method falls through silently.
- model = vlm_load_model(
- Path(model_path),
- lazy=True,
- trust_remote_code=trust_remote_code,
- )
- finally:
- _nn.Module.load_weights = _orig_lw
+ # Sensitivity uses the same proxy representation as imatrix
+ # calibration. Allow intentionally unowned mmap/shared-KV tensors
+ # through mlx-vlm's supported load option.
+ model = vlm_load_model(
+ Path(model_path),
+ lazy=True,
+ trust_remote_code=trust_remote_code,
+ strict=False,
+ )
from mlx_lm.tokenizer_utils import load as load_tokenizer
tokenizer = load_tokenizer(Path(model_path))
@@ -7956,7 +8611,12 @@ def _build_streaming_proxy_for_sensitivity(
raise ValueError(f"No .safetensors files found in {model_path}")
all_weights = _LazyTensorIndex(weight_files, config=config)
- sanitize_fn = _build_model_sanitizer(config, text_only=False)
+ sanitize_fn = _build_model_sanitizer(
+ config,
+ text_only=False,
+ model_path=source,
+ preserve_mtp=preserve_mtp,
+ )
cast_predicate = getattr(sanitize_fn, "_omlx_cast_predicate", None)
if sanitize_fn is not None:
try:
@@ -8044,14 +8704,23 @@ def _flush_shard() -> None:
pred = universal_quant_predicate(
tensor_name, None, config, _PROXY_QUANT_BITS
)
- if pred is not False and len(shape) >= 2 and shape[-1] % base_gs == 0:
+ tensor_gs = (
+ _QWEN4_EXP_NGRAM_GROUP_SIZE
+ if _is_qwen4_exp_ngram_embedding_tensor(tensor_name, config)
+ else base_gs
+ )
+ if (
+ pred is not False
+ and len(shape) >= 2
+ and shape[-1] % tensor_gs == 0
+ ):
if (
mx.issubdtype(w_mx.dtype, mx.floating)
and w_mx.dtype != target_dtype
):
w_mx = w_mx.astype(target_dtype)
qw, scales, biases = _quantize_chunked(
- w_mx, base_gs, base_bits, base_mode
+ w_mx, tensor_gs, base_bits, base_mode
)
base = (
tensor_name[:-7]
@@ -8062,6 +8731,12 @@ def _flush_shard() -> None:
out_shard_data[f"{base}.scales"] = scales
if biases is not None:
out_shard_data[f"{base}.biases"] = biases
+ if tensor_gs != base_gs:
+ per_layer_config[base] = {
+ "bits": base_bits,
+ "group_size": tensor_gs,
+ "mode": base_mode,
+ }
del qw, scales, biases
else:
if cast_predicate is None or cast_predicate(tensor_name):
@@ -8159,12 +8834,21 @@ def _measure_sensitivity_from_quantized_model(
# Idempotent; harmless for plain mlx-lm proxies.
is_vlm = _is_vlm_load(config)
has_mtp_weights = _checkpoint_has_mtp_weights(model_path)
- maybe_apply_pre_load_patches(model_path, for_vlm=is_vlm)
+ has_mtp_heads = _has_mtp_heads(config)
+ calibration_settings = _calibration_model_settings(
+ config,
+ has_mtp_heads=has_mtp_heads,
+ has_mtp_weights=has_mtp_weights,
+ )
+ patch_kwargs: dict[str, Any] = {"for_vlm": is_vlm}
+ if calibration_settings is not None:
+ patch_kwargs["model_settings"] = calibration_settings
+ maybe_apply_pre_load_patches(model_path, **patch_kwargs)
restore_mtp_active = None
try:
if is_vlm:
- if _has_mtp_heads(config) and has_mtp_weights:
+ if has_mtp_heads and has_mtp_weights:
try:
from omlx.patches.mlx_lm_mtp import is_mtp_active, set_mtp_active
from omlx.patches.mlx_vlm_mtp import (
@@ -8192,6 +8876,11 @@ def _measure_sensitivity_from_quantized_model(
Path(model_path),
lazy=True,
trust_remote_code=trust_remote_code,
+ # Quantized calibration proxies may retain model-specific
+ # tensors consumed directly by mmap modules rather than
+ # represented as ordinary MLX parameters (Qwen4 PLE shards).
+ # Match the imatrix and non-proxy sensitivity load paths.
+ strict=False,
)
tokenizer = load_tokenizer(Path(model_path))
else:
diff --git a/omlx/patches/deepseek_v4/__init__.py b/omlx/patches/deepseek_v4/__init__.py
index 1759f70599..fb0ce6a7f3 100644
--- a/omlx/patches/deepseek_v4/__init__.py
+++ b/omlx/patches/deepseek_v4/__init__.py
@@ -46,6 +46,7 @@
PR_URL = "https://github.com/ml-explore/mlx-lm/pull/1192"
_APPLIED = False
+_POOLING_APPLIED = False
def _inject_cache_extras() -> None:
@@ -160,6 +161,28 @@ def _probe_native_indexer_kernels() -> None:
)
+def apply_pooling_cache_support() -> bool:
+ """Install the model-neutral PoolingCache runtime and oMLX handlers."""
+ global _POOLING_APPLIED
+ if _POOLING_APPLIED:
+ return False
+
+ try:
+ import mlx_lm # noqa: F401
+ except ImportError:
+ logger.debug("mlx-lm not importable — pooling cache support skipped")
+ return False
+
+ _inject_cache_extras()
+
+ from .generate_patch import apply_generate_patch
+
+ apply_generate_patch()
+ _register_cache_handlers()
+ _POOLING_APPLIED = True
+ return True
+
+
def apply_deepseek_v4_patch() -> bool:
"""Apply the DeepSeek V4 patch to mlx-lm. Idempotent.
@@ -179,9 +202,9 @@ def apply_deepseek_v4_patch() -> bool:
return False
# Order matters:
- # 1. Inject PoolingCache / BatchPoolingCache so the deepseek_v4 module
- # can ``from .cache import PoolingCache`` at exec time.
- _inject_cache_extras()
+ # 1. Inject PoolingCache / BatchPoolingCache and install their batch/cache
+ # integration. GLM-5.3 also consumes this model-neutral subset.
+ apply_pooling_cache_support()
# 2. Register hyper_connection BEFORE deepseek_v4 (deepseek_v4 imports
# HyperConnection / HyperHead / hc_expand from it).
@@ -196,12 +219,7 @@ def apply_deepseek_v4_patch() -> bool:
apply_utils_patch()
- # 5. Patch generate._make_cache (PoolingCache → BatchPoolingCache).
- from .generate_patch import apply_generate_patch
-
- apply_generate_patch()
-
- # 6. Wrap tokenizer_utils.AutoTokenizer (deepseek_v4 fallback for
+ # 5. Wrap tokenizer_utils.AutoTokenizer (deepseek_v4 fallback for
# transformers releases that pre-date PR 45643 / 2026-05-02).
from .tokenizer_patch import apply_load_patch, apply_tokenizer_patch
@@ -212,13 +230,10 @@ def apply_deepseek_v4_patch() -> bool:
# minimal and lacks tool grammar.
apply_load_patch()
- # 8. Register omlx-side cache handlers.
- _register_cache_handlers()
-
- # 9. One-time native indexer kernel probe (INFO/WARNING only).
+ # 6. One-time native indexer kernel probe (INFO/WARNING only).
_probe_native_indexer_kernels()
- # 10. sanitize() stacks the expert biases, so sharded_load's weight-index
+ # 7. sanitize() stacks the expert biases, so sharded_load's weight-index
# gate would reject a local checkpoint the normal loader handles fine.
from omlx.patches.mlx_lm_sharded_load import install_local_sharded_load_fallback
@@ -233,4 +248,10 @@ def is_applied() -> bool:
return _APPLIED
-__all__ = ["apply_deepseek_v4_patch", "is_applied", "PR_HEAD_SHA", "PR_URL"]
+__all__ = [
+ "PR_HEAD_SHA",
+ "PR_URL",
+ "apply_deepseek_v4_patch",
+ "apply_pooling_cache_support",
+ "is_applied",
+]
diff --git a/omlx/patches/deepseek_v4/generate_patch.py b/omlx/patches/deepseek_v4/generate_patch.py
index f0599e13e0..d3544cce0e 100644
--- a/omlx/patches/deepseek_v4/generate_patch.py
+++ b/omlx/patches/deepseek_v4/generate_patch.py
@@ -5,9 +5,10 @@
``_make_cache``: ``isinstance(c, PoolingCache)`` → ``BatchPoolingCache``.
The closure is not externally hookable, so we replace ``_make_cache``
-itself with a copy whose body is identical to PR 1192. ``_make_cache`` is
-called via the module-level binding from inside ``mlx_lm.generate``, so
-overwriting the attribute is sufficient.
+with a compatible wrapper that adds PR 1192's PoolingCache conversion while
+preserving any previously installed model-owned cache conversion.
+``_make_cache`` is called via the module-level binding from inside
+``mlx_lm.generate``, so overwriting the attribute is sufficient.
When mlx-lm merges PR 1192 upstream this patch should be removed.
"""
@@ -50,13 +51,26 @@ def apply_generate_patch() -> bool:
_gen = importlib.import_module("mlx_lm.generate")
from mlx_lm.models.cache import BatchPoolingCache, PoolingCache
+ previous_make_cache = _gen._make_cache
+
+ def has_pooling_cache(cache_obj):
+ if isinstance(cache_obj, PoolingCache):
+ return True
+ sub_caches = getattr(cache_obj, "caches", None)
+ return isinstance(sub_caches, (list, tuple)) and any(
+ has_pooling_cache(child) for child in sub_caches
+ )
+
def _patched_make_cache(model, left_padding, max_kv_size):
"""Convert a list of regular caches into their corresponding
batch-aware caches.
"""
def to_batch_cache(c):
- if type(c) is KVCache:
+ model_owned_to_batch = getattr(c, "to_batch", None)
+ if callable(model_owned_to_batch):
+ return model_owned_to_batch(left_padding)
+ elif type(c) is KVCache:
return BatchKVCache(left_padding)
elif isinstance(c, ArraysCache):
c.left_padding = mx.array(left_padding)
@@ -76,6 +90,15 @@ def to_batch_cache(c):
if hasattr(model, "make_cache"):
cache = model.make_cache()
+ if not any(has_pooling_cache(c) for c in cache):
+
+ class _CachedModel:
+ layers = getattr(model, "layers", ())
+
+ def make_cache(self):
+ return cache
+
+ return previous_make_cache(_CachedModel(), left_padding, max_kv_size)
return [to_batch_cache(c) for c in cache]
else:
if max_kv_size is not None:
diff --git a/omlx/patches/deepseek_v4/switch_layers.py b/omlx/patches/deepseek_v4/switch_layers.py
index 07d0fa7413..b987107eda 100644
--- a/omlx/patches/deepseek_v4/switch_layers.py
+++ b/omlx/patches/deepseek_v4/switch_layers.py
@@ -21,6 +21,12 @@
_DEEPSEEK_MXFP4_LARGE_BLOCK_BM = 32
_DEEPSEEK_MXFP4_LARGE_BLOCK_VARIANT = 2
_DEEPSEEK_AFFINE_LARGE_BLOCK_MIN_ROUTES = 8192
+# Affine 2/3-bit g64 crossovers measured on M1 Ultra. Other formats keep
+# their existing 64-route sorting threshold.
+_SORT_MIN_ROUTES = int(os.environ.get("OMLX_DEEPSEEK_SORT_MIN_ROUTES", "32"))
+_AFFINE_NATIVE_MIN_ROUTES = int(
+ os.environ.get("OMLX_DEEPSEEK_AFFINE_BLOCK_MIN_ROUTES", "1024")
+)
# Tuned on M3 Ultra. Set this to 8192 to restore the previous crossover on
# other pre-NAX chips; M5 prefill uses the NAX fallback below.
_DEEPSEEK_MXFP4_LARGE_BLOCK_MIN_ROUTES = int(
@@ -49,6 +55,18 @@ def _nax_prefers_stock(num_routes: int) -> bool:
return num_routes >= _NAX_STOCK_MIN_ROUTES
+def _sort_threshold(*projections) -> int:
+ if all(
+ isinstance(p, QuantizedSwitchLinear)
+ and p.mode == "affine"
+ and p.bits in (2, 3)
+ and p.group_size == 64
+ for p in projections
+ ):
+ return _SORT_MIN_ROUTES
+ return 64
+
+
def _gather_sort(x, indices):
*_, M = indices.shape
indices = indices.flatten()
@@ -243,6 +261,7 @@ def _can_use_affine_blocks(self, x, sorted_indices: bool, dtype=None) -> bool:
sorted_indices
and x.ndim == 3
and x.shape[-2] == 1
+ and int(x.shape[0]) >= _AFFINE_NATIVE_MIN_ROUTES
and dtype in (mx.float16, mx.bfloat16)
and self.group_size == 64
and self.bits in (2, 3)
@@ -413,11 +432,13 @@ def __init__(
self.down_proj = SwitchLinear(hidden_dims, input_dims, num_experts, bias=bias)
self.activation = activation
- def __call__(self, x, indices, scores=None) -> mx.array:
+ def __call__(self, x, indices, scores=None, weighted_sum=False) -> mx.array:
x = mx.expand_dims(x, (-2, -3))
original_dtype = x.dtype
- do_sort = indices.size >= 64
+ do_sort = indices.size >= _sort_threshold(
+ self.gate_proj, self.up_proj, self.down_proj
+ )
idx = indices
inv_order = None
if do_sort:
@@ -556,6 +577,18 @@ def __call__(self, x, indices, scores=None) -> mx.array:
block_plan=block_plan,
)
+ if (
+ weighted_sum
+ and scores is not None
+ and do_sort
+ and scores.shape[-1] in (6, 8)
+ and scores.dtype == mx.float32
+ and x.dtype in (mx.float16, mx.bfloat16)
+ and glm_fast.has_symbol("glm_moe_weighted_sum")
+ ):
+ y = glm_fast.glm_moe_weighted_sum(x, inv_order, scores)
+ return y.astype(original_dtype) if use_f16_moe else y
+
if do_sort:
x = _scatter_unsort(x, inv_order, indices.shape)
@@ -583,7 +616,7 @@ def __init__(
def __call__(self, x, indices) -> mx.array:
x = mx.expand_dims(x, (-2, -3))
- do_sort = indices.size >= 64
+ do_sort = indices.size >= _sort_threshold(self.fc1, self.fc2)
idx = indices
inv_order = None
if do_sort:
diff --git a/omlx/patches/dflash_lifecycle.py b/omlx/patches/dflash_lifecycle.py
index f636521337..f20860edcb 100644
--- a/omlx/patches/dflash_lifecycle.py
+++ b/omlx/patches/dflash_lifecycle.py
@@ -36,6 +36,7 @@
from __future__ import annotations
import logging
+from contextlib import suppress
from typing import Any
import mlx.core as mx
@@ -65,6 +66,18 @@ def _wrap_installer(mod: Any, fn_name: str, flag_name: str) -> bool:
def wrapped(module_target: Any) -> Any:
cls = type(module_target)
+ current = cls.__dict__.get("__call__")
+ if getattr(cls, flag_name, False) and getattr(
+ current, "_omlx_mtp_call_marker", False
+ ):
+ # A Lightning MTP self-heal replaced dflash's hook while the
+ # idempotency flag stayed set (issue #2972): dflash's installer
+ # would skip re-installing and the engine would run without its
+ # speculative hook. Clear the stale flag and re-snapshot the
+ # current (MTP) __call__ as the base to restore/fall back to.
+ with suppress(AttributeError):
+ delattr(cls, flag_name)
+ _DFLASH_BACKUP[cls] = {"call": current, "flag": flag_name}
if not getattr(cls, flag_name, False):
# First time dflash installs on this class — snapshot the
# current __call__ so restore can put it back unchanged.
@@ -105,14 +118,41 @@ def _install_batch_cache_guard(cls: type) -> None:
def guarded_call(
self: Any, x: Any, mask: Any = None, cache: Any = None, **kwargs: Any
) -> Any:
- if isinstance(getattr(cache, "offset", None), mx.array):
- return pre_dflash_call(self, x, mask=mask, cache=cache, **kwargs)
+ # Resolve the fallback base dynamically: a Lightning MTP load may
+ # legitimately swap the non-dflash implementation underneath this
+ # guard while a DFlash engine stays resident (issue #2972).
+ live = _DFLASH_BACKUP.get(cls)
+ base = live["call"] if live is not None else pre_dflash_call
+ if kwargs.get("n_confirmed") or isinstance(
+ getattr(cache, "offset", None), mx.array
+ ):
+ return base(self, x, mask=mask, cache=cache, **kwargs)
return dflash_call(self, x, mask=mask, cache=cache, **kwargs)
guarded_call._omlx_dflash_batch_guard = True # type: ignore[attr-defined]
cls.__call__ = guarded_call # type: ignore[method-assign]
+def get_dflash_guard_base(cls: type) -> Any | None:
+ """Return the fallback base owned by an armed dflash guard."""
+ current = cls.__dict__.get("__call__")
+ if not getattr(current, "_omlx_dflash_batch_guard", False):
+ return None
+ info = _DFLASH_BACKUP.get(cls)
+ if info is None:
+ raise RuntimeError("dflash guard has no fallback base")
+ return info["call"]
+
+
+def set_dflash_guard_base(cls: type, new_call: Any) -> None:
+ """Replace the fallback base under an armed dflash guard."""
+ current = cls.__dict__.get("__call__")
+ info = _DFLASH_BACKUP.get(cls)
+ if not getattr(current, "_omlx_dflash_batch_guard", False) or info is None:
+ raise RuntimeError("dflash guard state changed during MTP patching")
+ info["call"] = new_call
+
+
def install_dflash_lifecycle_wrap() -> bool:
"""Monkey-patch dflash's hook installers to record pre-dflash class state.
@@ -179,10 +219,8 @@ def restore_dflash_class_patches() -> None:
continue
flag = info["flag"]
if flag in cls.__dict__:
- try:
+ with suppress(AttributeError):
delattr(cls, flag)
- except AttributeError:
- pass
restored += 1
_DFLASH_BACKUP.clear()
diff --git a/omlx/patches/gemma4_verify_attention.py b/omlx/patches/gemma4_verify_attention.py
index f74de81519..7db23903ee 100644
--- a/omlx/patches/gemma4_verify_attention.py
+++ b/omlx/patches/gemma4_verify_attention.py
@@ -1,12 +1,12 @@
# SPDX-License-Identifier: Apache-2.0
"""Small-L attention route for gemma4 speculative verify forwards.
-MLX's fused SDPA only covers head_dim {64, 80, 128} for multi-token
-queries; gemma4 (head_dim 256 sliding / 512 global) therefore drops to the
-unfused path for any L >= 2 forward. For the global layers that cost grows
-with context — the L=1 -> L=2 step measured +88% at 16k ctx on the 26B MoE
-— and is what makes MTP verify cycles lose to plain decoding on
-low-accept content.
+Gemma4 uses head_dim 256 for sliding layers and 512 for global layers. MLX
+0.32.2 now handles small multi-row head-dim-256 calls with its native vector
+kernel, so this patch explicitly leaves those shapes alone. Head-dim 512 still
+has no fused MLX route; for global layers that unfused cost grows with context
+and is what makes MTP verify cycles lose to plain decoding on low-accept
+content.
Two routes, picked per layer:
@@ -57,6 +57,18 @@
_MAX_L = 3 # per-token route ceiling (sliding layers / kernel fallback)
_KERNEL_MAX_L = 12 # fused kernel ceiling; stock batched wins past ~12
+_MLX0322_FULL_HEAD_DIMS = frozenset({64, 72, 80, 96, 128})
+_MLX0322_VECTOR_HEAD_DIMS = frozenset({64, 96, 128, 256})
+
+
+def _mlx0322_default_fused(head_dim: int, query_len: int, gqa_factor: int) -> bool:
+ if query_len <= 8:
+ return (
+ head_dim in _MLX0322_VECTOR_HEAD_DIMS
+ and query_len * gqa_factor <= 32
+ )
+ return head_dim in _MLX0322_FULL_HEAD_DIMS
+
def apply() -> bool:
"""Wrap ``mlx_vlm.models.gemma4.language.Attention.__call__``. Idempotent."""
@@ -101,6 +113,7 @@ def _kernel_cache_ok(cache, dtype) -> bool:
def __call__(self, x, mask=None, cache=None, shared_kv=None, offset=None):
B, L, _ = x.shape
+ gqa_factor = self.n_heads // self.n_kv_heads
if (
shared_kv is not None
or cache is None
@@ -112,6 +125,14 @@ def __call__(self, x, mask=None, cache=None, shared_kv=None, offset=None):
self, x, mask, cache, shared_kv=shared_kv, offset=offset
)
+ # Do not replace a shape MLX 0.32.2 already sends to a native fused
+ # kernel. This is the common Gemma4 sliding-layer verify path at
+ # head_dim=256 and L<=4.
+ if _mlx0322_default_fused(self.head_dim, L, gqa_factor):
+ return original_call(
+ self, x, mask, cache, shared_kv=shared_kv, offset=offset
+ )
+
use_kernel = (
not self.is_sliding
and L <= _KERNEL_MAX_L
@@ -122,7 +143,7 @@ def __call__(self, x, mask=None, cache=None, shared_kv=None, offset=None):
# GPUs cap below 32 * gqa threads); infeasible geometry falls
# back before the batched cache update commits us to the route.
and gemma4_verify_kernel.kernel_max_rows(
- self.n_heads // self.n_kv_heads, x.dtype
+ gqa_factor, x.dtype
)
> 0
)
diff --git a/omlx/patches/m5_gather_qmm.py b/omlx/patches/m5_gather_qmm.py
index 59ae18815b..2ef3cec75a 100644
--- a/omlx/patches/m5_gather_qmm.py
+++ b/omlx/patches/m5_gather_qmm.py
@@ -4,7 +4,7 @@
On M5-generation GPUs mlx dispatches ``sorted_indices=True`` quantized
gather matmuls (the MoE sorted-prefill path) to the NAX
``*_gather_qmm_rhs_nax`` kernels. Two independent defects corrupt their
-output on mlx <= 0.32.0:
+output through mlx 0.32.2:
- K remainder: the ``align_K=false`` tail bounds the activation tile
load by ``BK`` instead of the K remainder
@@ -15,16 +15,30 @@
issue #2267's bit-exactness test caught: with ``inter=32`` the test's
``down_proj`` runs at K=32. All dtypes are affected (bf16/fp16/fp32),
and the mxfp4 variant carries the same tail bug.
-- Row offsets: the int16 fix that landed in mlx 0.32.0 missed this
+- Row offsets: the int16 fix that landed in mlx 0.32.0 still misses this
kernel, so sorted row counts above 32768 overflow the row offset
- (ml-explore/mlx#3856). Reachable in production: a 4097+ token prefill
- chunk of a top-8 MoE crosses the boundary.
-
-``sorted_indices`` is a pure performance hint, so the wrapper simply
-drops it for calls that match a defect condition. The unsorted gather
-path guards ``K % 64 == 0`` before entering NAX and falls back to the
-verified steel kernels, at some prefill-throughput cost for the
-affected shapes only.
+ (ml-explore/mlx#3856, fixed upstream by ml-explore/mlx#3922 after the
+ 0.32.2 release). Reachable in production: a 4097+ token prefill chunk
+ of a top-8 MoE crosses the boundary, and a top-10 MoE (Qwen4-Exp)
+ crosses it at 3277 tokens.
+
+``sorted_indices`` is a pure performance hint, so the wrapper can always
+fall back to dropping it. The two defects get different treatment:
+
+- ``K % 64 != 0`` drops the flag: the unsorted gather path guards
+ ``K % 64 == 0`` before entering NAX and falls back to the verified
+ steel kernels, at some prefill-throughput cost for the affected
+ shapes only.
+- Row overflow keeps the flag and splits the call instead. The rhs
+ kernel is only wrong because a *single* call exceeds 32768 rows, so
+ an oversized call is issued as balanced ``<= 32768``-row slices of
+ the (already sorted) activations and indices and the partial outputs
+ are concatenated. Each slice stays on the NAX rhs kernel, which is
+ what makes wide prefill chunks (4096+ tokens on a top-8/top-10 MoE)
+ keep their tensor-unit throughput instead of dropping to the
+ per-row gather kernel. Slices are balanced rather than cut at the
+ cap so every slice still clears mlx's ``rows / experts >= 4`` gate
+ for the batched rhs path.
The wrapper self-arms: the first matching call runs a tiny canary
against an fp32 dequantized reference and only intervenes when the
@@ -83,14 +97,18 @@ def _sorted_gather_qmm_defective() -> bool:
if _defective:
logger.warning(
"sorted gather_qmm corrupts on this machine (canary max err "
- "%.3g); rerouting K %% 64 != 0 and >%d-row sorted calls to the "
- "unsorted path (issue #2267)",
+ "%.3g); rerouting K %% 64 != 0 sorted calls to the unsorted "
+ "path and segmenting >%d-row sorted calls (issue #2267)",
err,
_MAX_SORTED_ROWS,
)
return _defective
+def _rhs_indices(args, kwargs):
+ return args[3] if len(args) > 3 else kwargs.get("rhs_indices")
+
+
def _needs_reroute(x, args, kwargs) -> bool:
"""True when this call would select the defective NAX rhs kernel."""
if not kwargs.get("sorted_indices"):
@@ -99,7 +117,7 @@ def _needs_reroute(x, args, kwargs) -> bool:
# rhs_indices, transpose, group_size, bits, mode. sorted_indices is
# keyword-only.
lhs = args[2] if len(args) > 2 else kwargs.get("lhs_indices")
- rhs = args[3] if len(args) > 3 else kwargs.get("rhs_indices")
+ rhs = _rhs_indices(args, kwargs)
transpose = args[4] if len(args) > 4 else kwargs.get("transpose", True)
# The rhs kernel is only selected for the rhs-indices-only sorted
# path with transposed weights (x @ w.T).
@@ -110,8 +128,43 @@ def _needs_reroute(x, args, kwargs) -> bool:
return rhs.size * x.shape[-2] > _MAX_SORTED_ROWS
+def _segment_bounds(rows: int) -> list[tuple[int, int]]:
+ """Balanced ``[start, stop)`` slices with at most ``_MAX_SORTED_ROWS`` each."""
+ count = -(-rows // _MAX_SORTED_ROWS)
+ size = -(-rows // count)
+ return [(start, min(start + size, rows)) for start in range(0, rows, size)]
+
+
+def _segmented_sorted_gather_qmm(x, w, args, kwargs):
+ """Issue an oversized sorted rhs call as ``<= 32768``-row slices.
+
+ Only the layout the MoE sorted path produces is handled: a 3-D
+ ``[rows, 1, K]`` activation with a flat sorted ``rhs_indices`` of the
+ same row count. Anything else returns None and the caller falls back
+ to dropping ``sorted_indices``.
+ """
+ rhs = _rhs_indices(args, kwargs)
+ if x.ndim != 3 or x.shape[1] != 1 or rhs.ndim != 1 or rhs.shape[0] != x.shape[0]:
+ return None
+ rows = int(x.shape[0])
+ outputs = []
+ for start, stop in _segment_bounds(rows):
+ seg_args = list(args)
+ seg_kwargs = kwargs
+ if len(args) > 3:
+ seg_args[3] = rhs[start:stop]
+ else:
+ seg_kwargs = dict(kwargs, rhs_indices=rhs[start:stop])
+ outputs.append(_original_gather_qmm(x[start:stop], w, *seg_args, **seg_kwargs))
+ return mx.concatenate(outputs, axis=0)
+
+
def _gather_qmm_rerouted(x, w, *args, **kwargs):
if _needs_reroute(x, args, kwargs) and _sorted_gather_qmm_defective():
+ if x.shape[-1] % 64 == 0:
+ out = _segmented_sorted_gather_qmm(x, w, args, kwargs)
+ if out is not None:
+ return out
kwargs = dict(kwargs, sorted_indices=False)
return _original_gather_qmm(x, w, *args, **kwargs)
diff --git a/omlx/patches/mlx_lm_mtp/__init__.py b/omlx/patches/mlx_lm_mtp/__init__.py
index 564148fae6..fa79e1ff0f 100644
--- a/omlx/patches/mlx_lm_mtp/__init__.py
+++ b/omlx/patches/mlx_lm_mtp/__init__.py
@@ -30,6 +30,8 @@
import logging
+from ...model_settings import MAX_LIGHTNING_MTP_DRAFT_TOKENS
+
logger = logging.getLogger(__name__)
# Process-wide construction flag read by the patched ``Model.__init__``
@@ -70,7 +72,7 @@ def is_mtp_active() -> bool:
def set_mtp_depth(depth: int) -> None:
global _MTP_DEPTH
- _MTP_DEPTH = max(1, min(8, int(depth)))
+ _MTP_DEPTH = max(1, min(MAX_LIGHTNING_MTP_DRAFT_TOKENS, int(depth)))
def get_mtp_depth() -> int:
diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py
index 66df1bdb95..66b99e62b9 100644
--- a/omlx/patches/mlx_lm_mtp/batch_generator.py
+++ b/omlx/patches/mlx_lm_mtp/batch_generator.py
@@ -271,6 +271,9 @@ def patched_filter(self, keep, *args, **kwargs):
def patched_bg_next(self, *args, **kwargs):
gen_batch = getattr(self, "_generation_batch", None)
if gen_batch is not None:
+ # Reconcile runs on GenerationBatch, which upstream creates
+ # without the owning generator's prefill configuration.
+ gen_batch.prefill_step_size = getattr(self, "prefill_step_size", 512)
gen_batch._omlx_mtp_activation_safe = (
_batch_generator_allows_mtp_activation(self)
)
@@ -1057,6 +1060,7 @@ def _make_row_batch(
next_logprobs = getattr(gen_batch, "_next_logprobs", None)
row = SimpleNamespace(
model=gen_batch.model,
+ prefill_step_size=getattr(gen_batch, "prefill_step_size", 512),
uids=[gen_batch.uids[idx]],
prompt_cache=prompt_cache,
tokens=[gen_batch.tokens[idx]],
@@ -1296,8 +1300,17 @@ def _reconcile_mtp_to_standard(gen_batch: Any, state: _MtpState) -> bool:
procs = _proc_list(gen_batch)
_set_singleton_mrope_delta(gen_batch)
tok_arr = _ensure_uint32(mx.array(list(tokens)))
+ # Bound each rebuild forward by the owning generator's prefill size.
+ step = int(getattr(gen_batch, "prefill_step_size", 0) or 0) or 512
+ total = int(tok_arr.shape[0])
+ logits = None
# Inherits the per-engine stream from the enclosing BatchGenerator context.
- logits, _, _ = _call_backbone(gen_batch.model, tok_arr[None, :], new_cache)
+ for start in range(0, total, step):
+ logits, _, _ = _call_backbone(
+ gen_batch.model, tok_arr[None, start : start + step], new_cache
+ )
+ if start + step < total:
+ mx.eval(logits)
last_logits = logits[:, -1, :] # (1, vocab) — dist after tokens[-1]
if state.queue:
@@ -3201,7 +3214,16 @@ def _chain_rollback(
except Exception as exc:
logger.debug("rollback_speculative_cache failed: %s", exc)
return False
- rollback = getattr(model, "mtp_partial_rollback", None)
+ # VLM adapters keep the rollback hook on the inner language model.
+ rollback = None
+ for candidate in (
+ model,
+ getattr(model, "language_model", None),
+ getattr(model, "_language_model", None),
+ ):
+ rollback = getattr(candidate, "mtp_partial_rollback", None)
+ if callable(rollback):
+ break
if callable(rollback):
try:
return bool(rollback(prompt_cache, accepted, num_drafts))
diff --git a/omlx/patches/mlx_lm_mtp/prompt_priming.py b/omlx/patches/mlx_lm_mtp/prompt_priming.py
index be027a8a39..37d22024f3 100644
--- a/omlx/patches/mlx_lm_mtp/prompt_priming.py
+++ b/omlx/patches/mlx_lm_mtp/prompt_priming.py
@@ -71,6 +71,7 @@
HEAD_HIDDEN_POST_NORM = True
_CTX_ATTR = "_omlx_mtp_prime_ctx"
+_PLAN_ATTR = "_omlx_mtp_prime_plan"
_SUPPRESS = threading.local()
@@ -131,6 +132,52 @@ class _PrimeCtx:
# The current contiguous timeline exceeded OMLX_MTP_PRIME_WINDOW. Keep a
# lightweight marker so later small chunks cannot restart priming.
window_exceeded: bool = False
+ # Absolute MTP history is ``folded``; this counter is only the work folded
+ # by the current request. A warm prefix restore starts at a nonzero
+ # absolute history but must still apply OMLX_MTP_PRIME_WINDOW to the small
+ # uncached suffix, preserving the option's documented meaning.
+ folded_this_request: int = 0
+ # Request/prefix-cache metadata used to publish and restore one exact
+ # full-block MTP boundary snapshot. The cache itself remains generic and
+ # treats the snapshot as an opaque sidecar.
+ request_id: Optional[str] = None
+ prompt_tokens: Optional[tuple[int, ...]] = None
+ block_size: int = 0
+ prefix_cache: Any = None
+ extra_keys: Optional[tuple[Any, ...]] = None
+ extra_key_token_start: Optional[int] = None
+ extra_key_ranges: Optional[list[tuple[int, tuple[Any, ...]]]] = None
+ snapshot_candidate: Any = None
+
+
+@dataclass
+class _PrimePlan:
+ """Scheduler-owned metadata for the next singleton prompt timeline."""
+
+ request_id: str
+ prompt_tokens: tuple[int, ...]
+ block_size: int
+ prefix_cache: Any
+ extra_keys: Optional[tuple[Any, ...]] = None
+ extra_key_token_start: Optional[int] = None
+ extra_key_ranges: Optional[list[tuple[int, tuple[Any, ...]]]] = None
+
+
+@dataclass
+class _MtpPrefixSnapshot:
+ """Detached MTP-head state at a backbone full-block boundary."""
+
+ boundary_tokens: int
+ mtp_cache: List[Any]
+ pending_hidden: Any
+
+
+@dataclass
+class _MtpBoundaryCandidate:
+ """Cheap boundary marker retained until activation publishes a snapshot."""
+
+ boundary_tokens: int
+ pending_hidden: Any
def _read_offset(entry: Any) -> Optional[int]:
@@ -246,26 +293,113 @@ def _find_ctx(model: Any) -> Optional[_PrimeCtx]:
return None
+def _find_plan(model: Any) -> Optional[_PrimePlan]:
+ for host in _host_candidates(model):
+ plan = getattr(host, _PLAN_ATTR, None)
+ if isinstance(plan, _PrimePlan):
+ return plan
+ return None
+
+
def drop_ctx(model: Any) -> None:
- """Remove any priming context from the model's host slot."""
+ """Remove any priming context/plan from the model's host slots."""
if model is None:
return
for host in _host_candidates(model):
- if getattr(host, _CTX_ATTR, None) is not None:
- try:
- delattr(host, _CTX_ATTR)
- except AttributeError:
- pass
+ for attr in (_CTX_ATTR, _PLAN_ATTR):
+ if getattr(host, attr, None) is not None:
+ try:
+ delattr(host, attr)
+ except AttributeError:
+ pass
def _host_eligible(host: Any) -> bool:
- return bool(
- getattr(host, "_omlx_mtp_decode_enabled", False)
- and getattr(host, "_omlx_mtp_chain", False)
- and getattr(host, "mtp", None) is not None
+ get_mtp = getattr(host, "get_mtp_module", None)
+ mtp = get_mtp() if callable(get_mtp) else getattr(host, "mtp", None)
+ return (
+ getattr(host, "_omlx_mtp_decode_enabled", False) is True
+ and getattr(host, "_omlx_mtp_chain", False) is True
+ and mtp is not None
)
+def _eligible_host(model: Any) -> Any | None:
+ for host in _host_candidates(model):
+ if _host_eligible(host):
+ return host
+ return None
+
+
+def _clone_mtp_cache(cache: List[Any]) -> List[Any]:
+ """Detach an MTP cache so later decode writes cannot mutate a snapshot."""
+ import copy
+
+ import mlx.core as mx
+
+ def clone_one(entry: Any) -> Any:
+ if entry is None:
+ return None
+ subs = getattr(entry, "caches", None)
+ if subs is not None:
+ return type(entry)(*[clone_one(sub) for sub in subs])
+ clone = copy.copy(entry)
+ for attr, value in vars(entry).items():
+ if isinstance(value, mx.array):
+ setattr(clone, attr, value + 0)
+ elif isinstance(value, list):
+ setattr(clone, attr, list(value))
+ return clone
+
+ return [clone_one(entry) for entry in cache]
+
+
+def _flat_cache_entries(cache: List[Any]):
+ for entry in cache:
+ subs = getattr(entry, "caches", None)
+ if subs is None:
+ yield entry
+ else:
+ yield from subs
+
+
+def _cache_at_offset(cache: List[Any], target: int) -> Optional[List[Any]]:
+ """Return a detached, exactly trimmed MTP cache or fail closed."""
+ if target < 0 or not cache:
+ return None
+ cloned = _clone_mtp_cache(cache)
+ saw_offset = False
+ for entry in _flat_cache_entries(cloned):
+ current = _read_offset(entry)
+ if current is None:
+ continue
+ saw_offset = True
+ if current < target:
+ return None
+ extra = current - target
+ if extra:
+ trim = getattr(entry, "trim", None)
+ if not callable(trim) or int(trim(extra)) != extra:
+ return None
+ if _read_offset(entry) != target:
+ return None
+ return cloned if saw_offset else None
+
+
+def _snapshot_arrays(snapshot: _MtpPrefixSnapshot) -> list[Any]:
+ """Arrays that must be materialized to sever the live prefill graph."""
+ import mlx.core as mx
+
+ arrays: list[Any] = []
+ if isinstance(snapshot.pending_hidden, mx.array):
+ arrays.append(snapshot.pending_hidden)
+ for entry in _flat_cache_entries(snapshot.mtp_cache):
+ for value in vars(entry).values():
+ if isinstance(value, mx.array):
+ arrays.append(value)
+ return arrays
+
+
def capture_eligible(host: Any, cache: Optional[List[Any]]) -> bool:
"""Cheap pre-check for capture sites that must decide the forward shape.
@@ -283,6 +417,213 @@ def capture_eligible(host: Any, cache: Optional[List[Any]]) -> bool:
)
+def prepare_prefix_context(
+ model: Any,
+ *,
+ request_id: str,
+ prompt_tokens: list[int],
+ cached_tokens: int,
+ prefix_cache: Any,
+ extra_keys: Optional[tuple[Any, ...]] = None,
+ extra_key_token_start: Optional[int] = None,
+ extra_key_ranges: Optional[list[tuple[int, tuple[Any, ...]]]] = None,
+) -> bool:
+ """Prepare exact MTP priming for one scheduler-owned prompt timeline.
+
+ ``cached_tokens`` is the final reconstructed backbone offset (after any
+ exact-hit trim). A matching sidecar restores the MTP-head KV at
+ ``cached_tokens - 1`` plus the pending trunk hidden at the boundary, so
+ the uncached suffix can continue folding without replaying the trunk.
+ Missing, stale, VLM-range-keyed, or shape-incompatible snapshots fail
+ closed to the existing unprimed path.
+
+ Returns True only when a warm sidecar was restored. Repeating the call
+ for the same request is idempotent and never double-primes a live suffix.
+ """
+ host = _eligible_host(model)
+ if host is None or not priming_enabled() or prefix_cache is None:
+ drop_ctx(model)
+ return False
+
+ tokens = tuple(int(token) for token in prompt_tokens)
+ cached_tokens = max(0, int(cached_tokens))
+ existing = _find_ctx(model)
+ plan = _find_plan(model)
+ if (
+ (existing is not None and existing.request_id == request_id)
+ or (
+ plan is not None
+ and plan.request_id == request_id
+ and plan.prompt_tokens == tokens
+ )
+ ):
+ return existing is not None and existing.expected_offset >= cached_tokens
+
+ drop_ctx(model)
+ plan = _PrimePlan(
+ request_id=request_id,
+ prompt_tokens=tokens,
+ block_size=max(0, int(getattr(prefix_cache, "block_size", 0) or 0)),
+ prefix_cache=prefix_cache,
+ extra_keys=extra_keys,
+ extra_key_token_start=extra_key_token_start,
+ extra_key_ranges=(
+ list(extra_key_ranges) if extra_key_ranges is not None else None
+ ),
+ )
+ setattr(host, _PLAN_ATTR, plan)
+ if cached_tokens <= 0:
+ return False
+
+ restore = getattr(prefix_cache, "restore_mtp_prefix_snapshot", None)
+ if not callable(restore):
+ return False
+ try:
+ snapshot = restore(
+ list(tokens),
+ cached_tokens,
+ extra_keys=extra_keys,
+ extra_key_token_start=extra_key_token_start,
+ extra_key_ranges=extra_key_ranges,
+ )
+ except Exception as exc:
+ logger.debug("MTP prefix sidecar lookup failed closed: %s", exc)
+ return False
+ if not isinstance(snapshot, _MtpPrefixSnapshot):
+ return False
+ if snapshot.boundary_tokens != cached_tokens or cached_tokens < 2:
+ return False
+
+ target_offset = cached_tokens - 1
+ try:
+ restored_cache = _cache_at_offset(snapshot.mtp_cache, target_offset)
+ if restored_cache is None or snapshot.pending_hidden is None:
+ return False
+
+ import mlx.core as mx
+
+ pending_hidden = snapshot.pending_hidden + 0
+ except Exception as exc:
+ logger.debug("MTP prefix sidecar restore failed closed: %s", exc)
+ return False
+ ctx = _PrimeCtx(
+ mtp_cache=restored_cache,
+ pending_hidden=pending_hidden,
+ folded=target_offset,
+ expected_offset=cached_tokens,
+ request_id=request_id,
+ prompt_tokens=tokens,
+ block_size=plan.block_size,
+ prefix_cache=prefix_cache,
+ extra_keys=extra_keys,
+ extra_key_token_start=extra_key_token_start,
+ extra_key_ranges=plan.extra_key_ranges,
+ )
+ setattr(host, _CTX_ATTR, ctx)
+ try:
+ arrays = [pending_hidden, *_snapshot_arrays(snapshot)]
+ if arrays:
+ mx.async_eval(arrays)
+ except Exception as exc:
+ drop_ctx(model)
+ logger.debug("MTP prefix sidecar materialization failed closed: %s", exc)
+ return False
+ logger.debug(
+ "MTP prompt history restored at %d cached tokens for %s",
+ cached_tokens,
+ request_id,
+ )
+ return True
+
+
+def _capture_boundary_candidate(
+ ctx: _PrimeCtx,
+ normed: Any,
+ *,
+ seq_start: int,
+ seq_end: int,
+) -> None:
+ """Detach the newest full-block MTP boundary crossed by this chunk."""
+ block = int(ctx.block_size or 0)
+ if (
+ block <= 0
+ or ctx.prefix_cache is None
+ or not ctx.prompt_tokens
+ or seq_end < block
+ ):
+ return
+ boundary = (seq_end // block) * block
+ if boundary <= seq_start or boundary > len(ctx.prompt_tokens):
+ return
+ previous = ctx.snapshot_candidate
+ if (
+ isinstance(previous, _MtpBoundaryCandidate)
+ and previous.boundary_tokens >= boundary
+ ):
+ return
+
+ # A backbone boundary at C tokens needs MTP pairs through C-1 and keeps
+ # hidden(token[C-1]) pending for the next token. ``normed`` spans
+ # [seq_start, seq_end), so the boundary row is available without replay.
+ if boundary <= 1 or ctx.folded < boundary - 1:
+ return
+ row = boundary - seq_start - 1
+ if row < 0 or row >= int(normed.shape[1]):
+ return
+ try:
+ import mlx.core as mx
+
+ candidate = _MtpBoundaryCandidate(
+ boundary_tokens=boundary,
+ pending_hidden=normed[:, row : row + 1] + 0,
+ )
+ mx.async_eval(candidate.pending_hidden)
+ except Exception as exc:
+ logger.debug("MTP prefix boundary capture failed closed: %s", exc)
+ return
+ ctx.snapshot_candidate = candidate
+
+
+def _publish_boundary_candidate(ctx: _PrimeCtx) -> None:
+ candidate = ctx.snapshot_candidate
+ store = getattr(ctx.prefix_cache, "store_mtp_prefix_snapshot", None)
+ if not isinstance(candidate, _MtpBoundaryCandidate) or not callable(store):
+ return
+ try:
+ snapshot_cache = _cache_at_offset(
+ ctx.mtp_cache, candidate.boundary_tokens - 1
+ )
+ if snapshot_cache is None:
+ return
+ snapshot = _MtpPrefixSnapshot(
+ boundary_tokens=candidate.boundary_tokens,
+ mtp_cache=snapshot_cache,
+ pending_hidden=candidate.pending_hidden,
+ )
+ arrays = _snapshot_arrays(snapshot)
+ if arrays:
+ import mlx.core as mx
+
+ mx.async_eval(arrays)
+ stored = store(
+ list(ctx.prompt_tokens or ()),
+ snapshot.boundary_tokens,
+ snapshot,
+ extra_keys=ctx.extra_keys,
+ extra_key_token_start=ctx.extra_key_token_start,
+ extra_key_ranges=ctx.extra_key_ranges,
+ )
+ except Exception as exc:
+ logger.debug("MTP prefix sidecar publish failed closed: %s", exc)
+ return
+ if stored:
+ logger.debug(
+ "MTP prompt history cached at %d-token boundary for %s",
+ snapshot.boundary_tokens,
+ ctx.request_id or "anonymous request",
+ )
+
+
def maybe_capture(
host: Any, inputs: Any, normed: Any, cache: Optional[List[Any]]
) -> None:
@@ -338,7 +679,7 @@ def maybe_capture(
# not the absolute prompt offset: on a warm prefix cache only the
# boundary remainder is ever folded, so a long-context request with a
# small remainder is exactly the cheap case priming is for (#2909).
- folded = ctx.folded if ctx is not None else 0
+ folded = ctx.folded_this_request if ctx is not None else 0
if folded + seq_len > window:
setattr(
host,
@@ -353,16 +694,26 @@ def maybe_capture(
if seq_len <= 1:
# A lone decode step cannot start a prompt timeline.
return
- ctx = _PrimeCtx(mtp_cache=host.make_mtp_cache())
+ plan = _find_plan(host)
+ ctx = _PrimeCtx(
+ mtp_cache=host.make_mtp_cache(),
+ request_id=plan.request_id if plan is not None else None,
+ prompt_tokens=plan.prompt_tokens if plan is not None else None,
+ block_size=plan.block_size if plan is not None else 0,
+ prefix_cache=plan.prefix_cache if plan is not None else None,
+ extra_keys=plan.extra_keys if plan is not None else None,
+ extra_key_token_start=(
+ plan.extra_key_token_start if plan is not None else None
+ ),
+ extra_key_ranges=(plan.extra_key_ranges if plan is not None else None),
+ )
if not ctx.mtp_cache:
return
setattr(host, _CTX_ATTR, ctx)
if ctx.pending_hidden is not None:
if seq_len > 1:
- pairs_hidden = mx.concatenate(
- [ctx.pending_hidden, normed[:, :-1]], axis=1
- )
+ pairs_hidden = mx.concatenate([ctx.pending_hidden, normed[:, :-1]], axis=1)
else:
pairs_hidden = ctx.pending_hidden
pairs_tokens = inputs
@@ -380,8 +731,15 @@ def maybe_capture(
# on them, so the lm_head tail costs nothing.
host.mtp_forward(pairs_hidden, pairs_tokens, ctx.mtp_cache, logits_keep=1)
ctx.folded += int(pairs_tokens.shape[1])
+ ctx.folded_this_request += int(pairs_tokens.shape[1])
ctx.pending_hidden = normed[:, -1:]
ctx.expected_offset = offset_after
+ _capture_boundary_candidate(
+ ctx,
+ normed,
+ seq_start=offset_after - seq_len,
+ seq_end=offset_after,
+ )
# Materialize the head-cache buffers per chunk so the fold graph never
# accumulates across a long prefill; the (1,1,H) pending row is evaluated
# alongside so the chunk's full hidden can be freed.
@@ -457,6 +815,7 @@ def take_primed(
except Exception as exc:
logger.debug("MTP priming discarded: seam fold failed: %s", exc)
return None
+ _publish_boundary_candidate(ctx)
return ctx.mtp_cache, ctx.folded + 1
@@ -470,6 +829,7 @@ def prime_ctx_stats(model: Any) -> Optional[int]:
"HEAD_HIDDEN_POST_NORM",
"priming_enabled",
"prime_window",
+ "prepare_prefix_context",
"suppress_capture",
"maybe_capture",
"take_primed",
diff --git a/omlx/patches/mlx_lm_mtp/qwen35_model.py b/omlx/patches/mlx_lm_mtp/qwen35_model.py
index 08731c7ff9..2540b8e4e6 100644
--- a/omlx/patches/mlx_lm_mtp/qwen35_model.py
+++ b/omlx/patches/mlx_lm_mtp/qwen35_model.py
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
-"""Monkey-patch for ml-explore/mlx-lm PR #990 — Qwen3.5/3.6 native MTP.
+"""Monkey-patch for ml-explore/mlx-lm PR #990 — Qwen3.5/3.6 Lightning MTP.
Adds an MTP head to ``mlx_lm.models.qwen3_5.TextModel`` (the language-model
half) and a pass-through on ``mlx_lm.models.qwen3_5.Model`` (the VLM-outer
@@ -51,6 +51,7 @@
import logging
from typing import Any, Optional
+from ..dflash_lifecycle import get_dflash_guard_base, set_dflash_guard_base
from . import prompt_priming
logger = logging.getLogger(__name__)
@@ -60,7 +61,7 @@ def _is_our_method(cls: Any, attr: str, marker: str) -> bool:
Used as a self-healing idempotency check: when another patch (e.g.
dflash's speculative hook) overwrites ``__call__`` between two
- Native-MTP loads in the same process, the marker disappears and the
+ Lightning MTP loads in the same process, the marker disappears and the
caller knows to re-apply. Reading from ``cls.__dict__`` instead of
``getattr`` avoids resolving inherited attributes — only what is
actually defined on this class counts.
@@ -238,6 +239,15 @@ def _patch_gated_delta_net(q35: Any) -> None:
if _is_our_method(cls, "__call__", "_omlx_mtp_call_marker"):
return
+ # dflash coexistence (issue #2972): if the dflash batch-cache guard owns
+ # ``cls.__call__``, do not clobber it — that silently strips the resident
+ # DFlash engine's speculative hook and its generations degenerate into
+ # repetition loops. Instead install our body as the guard's fallback
+ # base: dflash traffic keeps its hook, MTP/batched traffic gets ours.
+ dflash_base = get_dflash_guard_base(cls)
+ if getattr(dflash_base, "_omlx_mtp_call_marker", False):
+ return # our body already sits under the dflash guard
+
import mlx.core as mx
import mlx.nn as nn
from mlx.nn.layers.distributed import sum_gradients
@@ -356,7 +366,12 @@ def __call__(
cls._process_chunk = _process_chunk
__call__._omlx_mtp_call_marker = True
- cls.__call__ = __call__
+ if dflash_base is not None:
+ # Compose with the armed dflash guard instead of replacing it
+ # (issue #2972): our body becomes the guard's fallback base.
+ set_dflash_guard_base(cls, __call__)
+ else:
+ cls.__call__ = __call__
# ---------------------------------------------------------------------------
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py
new file mode 100644
index 0000000000..4c277cb5c2
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py
@@ -0,0 +1,74 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Register the vendored GLM-5.3-Flash implementation with mlx-vlm."""
+
+from __future__ import annotations
+
+import importlib
+import logging
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+PR_URL = "https://github.com/Blaizzy/mlx-vlm/pull/2030"
+PR_MERGE_SHA = "fa27a9a692770c39fdf57b9a985fad084a90aec2"
+_VENDOR_MLX_VLM = Path(__file__).resolve().parent / "vendor" / "mlx_vlm"
+_APPLIED = False
+
+
+def _append_package_path(package: Any, path: Path) -> None:
+ package_path = getattr(package, "__path__", None)
+ if package_path is None:
+ return
+ path_string = str(path)
+ if path_string not in package_path:
+ package_path.append(path_string)
+
+
+def apply_mlx_vlm_glm5_next_compat_patch() -> bool:
+ """Expose ``mlx_vlm.models.glm5_next`` from oMLX's vendor tree."""
+ global _APPLIED
+ if _APPLIED:
+ return False
+
+ try:
+ import mlx_vlm
+ import mlx_vlm.models
+
+ from omlx.patches.deepseek_v4 import apply_pooling_cache_support
+
+ apply_pooling_cache_support()
+ _append_package_path(mlx_vlm, _VENDOR_MLX_VLM)
+ _append_package_path(mlx_vlm.models, _VENDOR_MLX_VLM / "models")
+ importlib.import_module("mlx_vlm.models.glm5_next")
+
+ # mlx-vlm has no glm5_next entry in MODEL_CONFIG, so get_message_json()
+ # raises "Unsupported model: glm5_next" on every turn that carries no
+ # image. That aborts _format_messages_for_vlm_template() as a whole,
+ # so the engine falls back to mlx-vlm's generic formatter, which emits
+ # no image placeholders -- while oMLX still extracts the images. Any
+ # conversation mixing an image with a plain turn then fails with
+ # "More images were provided than image tokens." GLM-5.3 takes the
+ # same list-with-image-first shape as glm4v.
+ from mlx_vlm.prompt_utils import MODEL_CONFIG, MessageFormat
+
+ MODEL_CONFIG.setdefault("glm5_next", MessageFormat.LIST_WITH_IMAGE_FIRST)
+ except Exception as exc: # noqa: BLE001
+ logger.debug("GLM-5.3 mlx-vlm registration failed: %s", exc)
+ return False
+
+ _APPLIED = True
+ logger.info("GLM-5.3 mlx-vlm compatibility patch applied")
+ return True
+
+
+def is_applied() -> bool:
+ return _APPLIED
+
+
+__all__ = [
+ "PR_MERGE_SHA",
+ "PR_URL",
+ "apply_mlx_vlm_glm5_next_compat_patch",
+ "is_applied",
+]
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/__init__.py
new file mode 100644
index 0000000000..90ea2eae64
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/__init__.py
@@ -0,0 +1 @@
+"""Vendored dependency namespace."""
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/__init__.py
new file mode 100644
index 0000000000..7cc6358c41
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/__init__.py
@@ -0,0 +1 @@
+"""Vendored mlx-vlm extensions."""
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/__init__.py
new file mode 100644
index 0000000000..e8d02c18a0
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/__init__.py
@@ -0,0 +1 @@
+"""Vendored mlx-vlm model extensions."""
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/README.md b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/README.md
new file mode 100644
index 0000000000..a3976660fa
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/README.md
@@ -0,0 +1,23 @@
+# Vendored GLM-5.3-Flash support
+
+This package is based on the GLM-5 Next model implementation merged by
+[`Blaizzy/mlx-vlm#2030`](https://github.com/Blaizzy/mlx-vlm/pull/2030) at
+`fa27a9a692770c39fdf57b9a985fad084a90aec2`. It is vendored because oMLX's
+pinned mlx-vlm release predates that model family.
+
+The text and vision paths also carry the non-speculative correctness fixes from
+[`Blaizzy/mlx-vlm#2044`](https://github.com/Blaizzy/mlx-vlm/pull/2044), plus
+oMLX runtime integration:
+
+- pooled indexer caches that support continuous batching and cache lifecycle
+ operations;
+- GLM-5.2 DSA, sparse MLA, MoE weighted-sum, and gated-delta kernels where the
+ GLM-5.3 tensor contracts match;
+- shared affine prefill QMM kernels for supported Q2/Q4/Q5/Q6/Q8 projections;
+- a torch-free NumPy/Pillow image processor compatible with the official
+ checkpoint metadata and oMLX's pinned Transformers release.
+
+Lightning MTP is intentionally not included in this compatibility layer. The
+base model drops `mtp.*` tensors during sanitization; GLM-5.3 Lightning MTP can
+be added independently after its recurrent-state rollback and batched cache
+semantics are validated.
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/__init__.py
new file mode 100644
index 0000000000..622d250fb6
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/__init__.py
@@ -0,0 +1,18 @@
+import mlx_vlm.models.glm5_next.processing # noqa: F401 (installs processor patch)
+
+from .config import ModelConfig, TextConfig, VisionConfig
+from .glm5_next import Model
+from .language import LanguageModel
+from .processing import Glm5NextImageProcessor, Glm5NextProcessor
+from .vision import VisionModel
+
+__all__ = [
+ "Model",
+ "ModelConfig",
+ "TextConfig",
+ "VisionConfig",
+ "LanguageModel",
+ "VisionModel",
+ "Glm5NextImageProcessor",
+ "Glm5NextProcessor",
+]
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/config.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/config.py
new file mode 100644
index 0000000000..ecfd774902
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/config.py
@@ -0,0 +1,136 @@
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+
+from ..base import BaseModelConfig
+
+
+@dataclass
+class TextConfig(BaseModelConfig):
+ model_type: str
+ vocab_size: int
+ hidden_size: int
+ intermediate_size: int
+ moe_intermediate_size: int
+ num_hidden_layers: int
+ num_attention_heads: int
+ num_key_value_heads: int
+ n_shared_experts: Optional[int]
+ n_routed_experts: Optional[int]
+ routed_scaling_factor: float
+ kv_lora_rank: int
+ q_lora_rank: int
+ qk_rope_head_dim: int
+ v_head_dim: int
+ qk_nope_head_dim: int
+ num_experts_per_tok: int
+ first_k_dense_replace: int
+ max_position_embeddings: int
+ rms_norm_eps: float
+ index_topk: int
+ index_head_dim: int
+ index_n_heads: int
+ layer_types: List[str]
+ mlp_layer_types: List[str]
+ linear_attn_config: Dict[str, Any]
+ linear_num_heads: int = 64
+ linear_head_dim: int = 128
+ linear_conv_kernel_dim: int = 4
+ linear_lower_bound: Optional[float] = -5.0
+ qk_head_dim: int = 256
+ head_dim: int = 0
+ n_group: int = 1
+ topk_group: int = 1
+ moe_layer_freq: int = 1
+ norm_topk_prob: bool = True
+ scoring_func: str = "sigmoid"
+ topk_method: str = "noaux_tc"
+ hidden_act: str = "silu"
+ attention_bias: bool = False
+ attention_dropout: float = 0.0
+ tie_word_embeddings: bool = False
+ mla_use_nope: bool = True
+ indexer_rope_interleave: bool = True
+ indexer_types: Optional[List[str]] = None
+ index_kpool: int = 4
+ index_kpool_compress: bool = True
+ index_kpool_always_select_tail: bool = True
+ swiglu_limit: float = 10.0
+ hc_mult: int = 4
+ hc_eps: float = 1e-06
+ hc_sinkhorn_iters: int = 20
+ mhc: bool = True
+ moe_router_dtype: str = "float32"
+ num_nextn_predict_layers: int = 0
+ router_aux_loss_coef: float = 0.001
+ output_router_logits: bool = False
+ rope_theta: float = 10000.0
+ rope_parameters: Optional[Dict] = None
+ rope_scaling: Optional[Dict] = None
+ pad_token_id: int = 154820
+ eos_token_id: Optional[List[int]] = None
+
+ def __post_init__(self):
+ if self.rope_parameters is not None:
+ self.rope_scaling = self.rope_parameters
+ self.rope_theta = self.rope_parameters.get("rope_theta", self.rope_theta)
+
+ cfg = self.linear_attn_config or {}
+ self.linear_num_heads = cfg.get("num_heads", self.linear_num_heads)
+ self.linear_head_dim = cfg.get("head_dim", self.linear_head_dim)
+ self.linear_conv_kernel_dim = cfg.get(
+ "short_conv_kernel_size", self.linear_conv_kernel_dim
+ )
+ self.linear_lower_bound = cfg.get("gate_lower_bound", self.linear_lower_bound)
+ if cfg.get("safe_gate", True) and self.linear_lower_bound is None:
+ self.linear_lower_bound = -5.0
+
+
+@dataclass
+class VisionConfig(BaseModelConfig):
+ model_type: str
+ depth: int
+ hidden_size: int
+ intermediate_size: int
+ num_heads: int
+ patch_size: int
+ out_hidden_size: int
+ projection_intermediate_size: int = 10240
+ image_size: int = 448
+ in_channels: int = 3
+ rms_norm_eps: float = 1e-05
+ attention_bias: bool = True
+ attention_dropout: float = 0.0
+ hidden_act: str = "silu"
+ initializer_range: float = 0.02
+ spatial_merge_size: int = 2
+ temporal_patch_size: int = 2
+ swiglu_limit: float = 10.0
+
+ @classmethod
+ def from_dict(cls, params):
+ # mlx-vlm inserts an empty vision_config for text-only checkpoints.
+ # Preserve that distinction instead of trying to construct a vision
+ # tower from missing required dimensions.
+ if not params:
+ return None
+ return super().from_dict(params)
+
+
+@dataclass
+class ModelConfig(BaseModelConfig):
+ text_config: TextConfig
+ model_type: str
+ vision_config: Optional[VisionConfig] = None
+ image_token_id: int = 154854
+ video_token_id: int = 154855
+ image_start_token_id: int = 154830
+ image_end_token_id: int = 154831
+ video_start_token_id: int = 154832
+ video_end_token_id: int = 154833
+ tie_word_embeddings: bool = False
+ pad_token_id: int = 154820
+ eos_token_id: Optional[List[int]] = None
+
+ def __post_init__(self):
+ if self.eos_token_id is None:
+ self.eos_token_id = [154820, 154827, 154829]
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/gated_delta.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/gated_delta.py
new file mode 100644
index 0000000000..ce5416cdad
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/gated_delta.py
@@ -0,0 +1,302 @@
+from functools import partial
+from typing import Optional, Tuple
+
+import mlx.core as mx
+import mlx.nn as nn
+
+
+@partial(mx.compile, shapeless=True)
+def compute_g(A_log, a, dt_bias):
+ return mx.exp(-mx.exp(A_log.astype(mx.float32)) * nn.softplus(a + dt_bias))
+
+
+@partial(mx.compile, shapeless=True)
+def compute_g_safe(A_log, a, dt_bias, lower_bound):
+ return mx.exp(
+ lower_bound * mx.sigmoid(mx.exp(A_log.astype(mx.float32)) * (a + dt_bias))
+ )
+
+
+def _make_gated_delta_kernel(has_mask=False, vectorized=False):
+ if not mx.metal.is_available():
+ return None
+ mask_source = "mask[b_idx * T + t]" if has_mask else "true"
+
+ # Configure g indexing based on whether gating is vectorized
+ if vectorized:
+ g_comment = "// g: [B, T, Hv, Dk]"
+ g_setup = "auto g_ = g + (b_idx * T * Hv + hv_idx) * Dk;"
+ g_access = "g_[s_idx]"
+ g_advance = "g_ += Hv * Dk;"
+ else:
+ g_comment = "// g: [B, T, Hv]"
+ g_setup = "auto g_ = g + b_idx * T * Hv;"
+ g_access = "g_[hv_idx]"
+ g_advance = "g_ += Hv;"
+
+ source = f"""
+ auto n = thread_position_in_grid.z;
+ auto b_idx = n / Hv;
+ auto hv_idx = n % Hv;
+ auto hk_idx = hv_idx / (Hv / Hk);
+ constexpr int n_per_t = Dk / 32;
+
+ // q, k: [B, T, Hk, Dk]
+ auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk;
+ auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk;
+
+ // v, y: [B, T, Hv, Dv]
+ auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv;
+ y += b_idx * T * Hv * Dv + hv_idx * Dv;
+
+ auto dk_idx = thread_position_in_threadgroup.x;
+ auto dv_idx = thread_position_in_grid.y;
+
+ // state_in, state_out: [B, Hv, Dv, Dk]
+ auto i_state = state_in + (n * Dv + dv_idx) * Dk;
+ auto o_state = state_out + (n * Dv + dv_idx) * Dk;
+
+ float state[n_per_t];
+ for (int i = 0; i < n_per_t; ++i) {{
+ auto s_idx = n_per_t * dk_idx + i;
+ state[i] = static_cast(i_state[s_idx]);
+ }}
+
+ {g_comment}
+ {g_setup}
+ auto beta_ = beta + b_idx * T * Hv;
+
+ for (int t = 0; t < T; ++t) {{
+ if ({mask_source}) {{
+ float kv_mem = 0.0f;
+ for (int i = 0; i < n_per_t; ++i) {{
+ auto s_idx = n_per_t * dk_idx + i;
+ state[i] = state[i] * {g_access};
+ kv_mem += state[i] * k_[s_idx];
+ }}
+ kv_mem = simd_sum(kv_mem);
+
+ auto delta = (v_[dv_idx] - kv_mem) * beta_[hv_idx];
+
+ float out = 0.0f;
+ for (int i = 0; i < n_per_t; ++i) {{
+ auto s_idx = n_per_t * dk_idx + i;
+ state[i] = state[i] + k_[s_idx] * delta;
+ out += state[i] * q_[s_idx];
+ }}
+ out = simd_sum(out);
+ if (thread_index_in_simdgroup == 0) {{
+ y[dv_idx] = static_cast(out);
+ }}
+ }} else {{
+ y[dv_idx] = static_cast(0);
+ }}
+ // Increment data pointers to next time step
+ q_ += Hk * Dk;
+ k_ += Hk * Dk;
+ v_ += Hv * Dv;
+ y += Hv * Dv;
+ {g_advance}
+ beta_ += Hv;
+ }}
+ for (int i = 0; i < n_per_t; ++i) {{
+ auto s_idx = n_per_t * dk_idx + i;
+ o_state[s_idx] = static_cast(state[i]);
+ }}
+ """
+ inputs = ["q", "k", "v", "g", "beta", "state_in", "T"]
+ if has_mask:
+ inputs.append("mask")
+
+ suffix = ""
+ if vectorized:
+ suffix += "_vec"
+ if has_mask:
+ suffix += "_mask"
+
+ return mx.fast.metal_kernel(
+ name=f"gated_delta_step{suffix}",
+ input_names=inputs,
+ output_names=["y", "state_out"],
+ source=source,
+ )
+
+
+_gated_delta_kernel = _make_gated_delta_kernel(has_mask=False, vectorized=False)
+_gated_delta_kernel_masked = _make_gated_delta_kernel(has_mask=True, vectorized=False)
+_gated_delta_kernel_vec = _make_gated_delta_kernel(has_mask=False, vectorized=True)
+_gated_delta_kernel_vec_masked = _make_gated_delta_kernel(
+ has_mask=True, vectorized=True
+)
+
+
+@mx.compile
+def _gated_delta_step_ops(
+ q: mx.array,
+ k: mx.array,
+ v: mx.array,
+ g: mx.array,
+ beta: mx.array,
+ state: mx.array,
+ mask: Optional[mx.array] = None,
+) -> Tuple[mx.array, mx.array]:
+ """
+ Ops-based reference implementation for a single recurrent step.
+
+ Shapes:
+ - q, k: [B, H, Dk]
+ - v: [B, H, Dv]
+ - g: [B, H] or [B, H, Dk]
+ - beta: [B, H]
+ - state: [B, H, Dv, Dk]
+ Returns:
+ - y: [B, H, Dv]
+ - new_state: [B, H, Dv, Dk]
+ """
+
+ # Decay
+ old_state = state
+ if g.ndim == 2:
+ decay = g[..., None, None]
+ elif g.ndim == 3:
+ decay = g[..., None, :]
+ else:
+ raise ValueError(f"Unsupported gating shape {g.shape}")
+ state = state * decay
+ kv_mem = (state * k[..., None, :]).sum(axis=-1) # [B, H, Dv]
+ delta = (v - kv_mem) * beta[..., None] # [B, H, Dv]
+ state = state + k[..., None, :] * delta[..., None]
+ # Output projection along key dim with q
+ y = (state * q[..., None, :]).sum(axis=-1) # [B, H, Dv]
+
+ if mask is not None:
+ state_mask = mx.expand_dims(mask, axis=(1, 2, 3))
+ output_mask = mx.expand_dims(mask, axis=(1, 2))
+ state = mx.where(state_mask, state, old_state)
+ y = mx.where(output_mask, y, 0)
+ return y.astype(q.dtype), state
+
+
+def gated_delta_kernel(
+ q: mx.array,
+ k: mx.array,
+ v: mx.array,
+ g: mx.array,
+ beta: mx.array,
+ state: mx.array,
+ mask: Optional[mx.array] = None,
+) -> Tuple[mx.array, mx.array]:
+ B, T, Hk, Dk = k.shape
+ Hv, Dv = v.shape[2:]
+ input_type = q.dtype
+ state_type = state.dtype
+ if g.ndim == 4:
+ kernel = _gated_delta_kernel_vec
+ inputs = [q, k, v, g, beta, state, T]
+ if mask is not None:
+ kernel = _gated_delta_kernel_vec_masked
+ inputs.append(mask)
+ else:
+ kernel = _gated_delta_kernel
+ inputs = [q, k, v, g, beta, state, T]
+ if mask is not None:
+ kernel = _gated_delta_kernel_masked
+ inputs.append(mask)
+
+ return kernel(
+ inputs=inputs,
+ template=[
+ ("InT", input_type),
+ ("StT", state_type),
+ ("Dk", Dk),
+ ("Dv", Dv),
+ ("Hk", Hk),
+ ("Hv", Hv),
+ ],
+ grid=(32, Dv, B * Hv),
+ threadgroup=(32, 4, 1),
+ output_shapes=[(B, T, Hv, Dv), state.shape],
+ output_dtypes=[input_type, state_type],
+ )
+
+
+def gated_delta_ops(
+ q: mx.array,
+ k: mx.array,
+ v: mx.array,
+ g: mx.array,
+ beta: mx.array,
+ state: Optional[mx.array] = None,
+ mask: Optional[mx.array] = None,
+) -> Tuple[mx.array, mx.array]:
+ """
+ Ops-based reference implementation for prompt prefill (sequential loop).
+ Supports both scalar and vectorized gating.
+
+ Shapes:
+ - q, k: [B, T, Hk, Dk]
+ - v: [B, T, Hv, Dv]
+ - g: [B, T, Hv] (scalar) or [B, T, Hv, Dk] (vectorized)
+ - beta: [B, T, Hv]
+ - state: [B, Hv, Dv, Dk]
+ Returns:
+ - y: [B, T, Hv, Dv]
+ - state: [B, Hv, Dv, Dk]
+ """
+ B, T, Hk, Dk = q.shape
+ Hv, Dv = v.shape[-2:]
+ if state is None:
+ state = mx.zeros((B, Hv, Dv, Dk), dtype=mx.float32)
+
+ if (repeat_factor := Hv // Hk) > 1:
+ q = mx.repeat(q, repeat_factor, -2)
+ k = mx.repeat(k, repeat_factor, -2)
+
+ ys = []
+ for t in range(T):
+ y, state = _gated_delta_step_ops(
+ q[:, t],
+ k[:, t],
+ v[:, t],
+ g[:, t],
+ beta[:, t],
+ state,
+ None if mask is None else mask[:, t],
+ )
+ ys.append(y)
+ y = mx.stack(ys, axis=1)
+ return y, state
+
+
+def gated_delta_update(
+ q: mx.array,
+ k: mx.array,
+ v: mx.array,
+ a: mx.array,
+ b: mx.array,
+ A_log: mx.array,
+ dt_bias: mx.array,
+ state: Optional[mx.array] = None,
+ mask: Optional[mx.array] = None,
+ use_kernel: bool = True,
+ lower_bound: Optional[float] = None,
+) -> Tuple[mx.array, mx.array]:
+ beta = mx.sigmoid(b)
+ if lower_bound is None:
+ g = compute_g(A_log, a, dt_bias)
+ else:
+ g = compute_g_safe(A_log, a, dt_bias, lower_bound)
+ if state is None:
+ B, _, Hk, Dk = q.shape
+ Hv, Dv = v.shape[-2:]
+ state = mx.zeros((B, Hv, Dv, Dk), dtype=mx.float32)
+
+ if (
+ not use_kernel
+ or mx.default_device() != mx.gpu
+ or not mx.metal.is_available()
+ or k.shape[-1] < 32
+ or k.shape[-1] % 32 != 0
+ ):
+ return gated_delta_ops(q, k, v, g, beta, state, mask)
+ return gated_delta_kernel(q, k, v, g, beta, state, mask)
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/glm5_next.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/glm5_next.py
new file mode 100644
index 0000000000..a27d8c9646
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/glm5_next.py
@@ -0,0 +1,177 @@
+import mlx.core as mx
+import mlx.nn as nn
+
+from ..base import InputEmbeddingsFeatures, LanguageModelOutput
+from .config import ModelConfig
+from .language import LanguageModel
+from .vision import VisionModel
+
+
+class Model(nn.Module):
+ def __init__(self, config: ModelConfig):
+ super().__init__()
+ self.config = config
+ self.model_type = config.model_type
+ self.language_model = LanguageModel(config.text_config, config)
+ self.vision_model = (
+ VisionModel(config.vision_config)
+ if config.vision_config is not None
+ else None
+ )
+
+ def encode_image(
+ self,
+ pixel_values: mx.array,
+ image_grid_thw: mx.array | None = None,
+ **kwargs,
+ ) -> mx.array:
+ if self.vision_model is None:
+ raise ValueError("Vision inputs were provided, but vision_config is None.")
+ if image_grid_thw is None:
+ raise ValueError("image_grid_thw is required to encode GLM-5.3 images.")
+ dtype = self.vision_model.patch_embed.proj.weight.dtype
+ return self.vision_model(pixel_values.astype(dtype), image_grid_thw)
+
+ @staticmethod
+ def merge_input_ids_with_image_features(
+ image_token_id,
+ video_token_id,
+ image_features,
+ inputs_embeds,
+ input_ids,
+ ):
+ image_positions = input_ids == image_token_id
+ if mx.sum(image_positions) == 0:
+ image_positions = input_ids == video_token_id
+
+ batch_size, seq_len = input_ids.shape
+ batch_outputs = []
+ feature_start_idx = 0
+
+ for batch_idx in range(batch_size):
+ image_mask = image_positions[batch_idx]
+ num_positions = mx.sum(image_mask).item()
+
+ if num_positions > 0:
+ batch_features = image_features[
+ feature_start_idx : feature_start_idx + num_positions
+ ]
+ if batch_features.shape[0] != num_positions:
+ raise ValueError(
+ f"Number of image token positions ({num_positions}) does not match "
+ f"number of image features ({batch_features.shape[0]}) for batch {batch_idx}"
+ )
+ cumsum = mx.cumsum(image_mask.astype(mx.int32))
+ feature_indices = mx.where(image_mask, cumsum - 1, 0)
+ gathered_features = batch_features[feature_indices]
+ image_mask_expanded = mx.expand_dims(image_mask, axis=-1)
+ batch_output = mx.where(
+ image_mask_expanded, gathered_features, inputs_embeds[batch_idx]
+ )
+ feature_start_idx += num_positions
+ else:
+ batch_output = inputs_embeds[batch_idx]
+
+ batch_outputs.append(batch_output)
+
+ return mx.stack(batch_outputs, axis=0)
+
+ def get_input_embeddings(
+ self,
+ input_ids: mx.array | None = None,
+ pixel_values: mx.array | None = None,
+ **kwargs,
+ ) -> InputEmbeddingsFeatures:
+ inputs_embeds = self.language_model.model.embed_tokens(input_ids)
+
+ if pixel_values is None:
+ return InputEmbeddingsFeatures(inputs_embeds=inputs_embeds)
+
+ if self.vision_model is None:
+ raise ValueError("Vision inputs were provided, but vision_config is None.")
+
+ image_grid_thw = kwargs.get("image_grid_thw")
+ video_grid_thw = kwargs.get("video_grid_thw")
+ grid_thw = image_grid_thw if image_grid_thw is not None else video_grid_thw
+
+ hidden_states = kwargs.get("cached_image_features")
+ if hidden_states is None:
+ hidden_states = self.encode_image(
+ pixel_values,
+ image_grid_thw=grid_thw,
+ )
+
+ final_inputs_embeds = self.merge_input_ids_with_image_features(
+ self.config.image_token_id,
+ self.config.video_token_id,
+ hidden_states,
+ inputs_embeds,
+ input_ids,
+ )
+ return InputEmbeddingsFeatures(inputs_embeds=final_inputs_embeds)
+
+ def __call__(
+ self,
+ input_ids: mx.array,
+ pixel_values: mx.array | None = None,
+ mask: mx.array | None = None,
+ cache=None,
+ **kwargs,
+ ) -> LanguageModelOutput:
+ features = self.get_input_embeddings(input_ids, pixel_values, **kwargs)
+ return self.language_model(
+ input_ids,
+ inputs_embeds=features.inputs_embeds,
+ mask=mask,
+ cache=cache,
+ )
+
+ def sanitize(self, weights):
+ # HF container: Glm5NextForConditionalGeneration -> model.{visual,language_model} + lm_head
+ remapped = {}
+ for k, v in weights.items():
+ nk = k
+ if nk.startswith("model.visual."):
+ nk = "vision_model." + nk[len("model.visual.") :]
+ elif nk.startswith("visual."):
+ nk = "vision_model." + nk[len("visual.") :]
+ elif nk.startswith("model.language_model."):
+ nk = "language_model.model." + nk[len("model.language_model.") :]
+ elif nk.startswith("lm_head."):
+ nk = "language_model." + nk
+ remapped[nk] = v
+
+ lang, vis, other = {}, {}, {}
+ for k, v in remapped.items():
+ if k.startswith("language_model."):
+ lang[k[len("language_model.") :]] = v
+ elif k.startswith("vision_model."):
+ vis[k[len("vision_model.") :]] = v
+ else:
+ other[k] = v
+
+ lang = self.language_model.sanitize(lang)
+ if self.vision_model is not None:
+ vis = self.vision_model.sanitize(vis)
+ else:
+ vis = VisionModel.sanitize(vis)
+
+ out = {f"language_model.{k}": v for k, v in lang.items()}
+ out.update({f"vision_model.{k}": v for k, v in vis.items()})
+ out.update(other)
+ return out
+
+ @property
+ def layers(self):
+ return self.language_model.model.layers
+
+ @property
+ def quant_predicate(self):
+ return self.language_model.quant_predicate
+
+ @property
+ def cast_predicate(self):
+ return self.language_model.cast_predicate
+
+ def make_cache(self):
+ return self.language_model.make_cache()
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py
new file mode 100644
index 0000000000..5bf7203a9d
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py
@@ -0,0 +1,1021 @@
+import logging
+from typing import Any, Optional
+
+import mlx.core as mx
+import mlx.nn as nn
+
+from ..base import (
+ LanguageModelOutput,
+ create_attention_mask,
+ create_ssm_mask,
+ scaled_dot_product_attention,
+)
+from ..cache import ArraysCache, CacheList, KVCache
+from ..deepseek_v4.hyper_connection import HyperConnection, hc_expand
+from mlx_lm.models.mla import MultiLinear
+from omlx.patches.deepseek_v4.switch_layers import SwitchGLU
+from omlx.patches.glm_moe_dsa.deepseek_v32 import (
+ Model as DSV32Model,
+ group_expert_select,
+)
+from omlx.patches.glm_moe_dsa.sparse_mla import (
+ exact_block_token_attention,
+ q8_vup_flat,
+ sparse_mla_attention,
+)
+from .config import ModelConfig, TextConfig
+from .gated_delta import gated_delta_update
+from .linear import fused_quantized_matmul, linear_forward
+
+logger = logging.getLogger(__name__)
+_NATIVE_INDEXER_WARNED = False
+
+
+def glm5_next_cast_predicate(key: str) -> bool:
+ """Keep numerically sensitive GLM-5.3 parameters in FP32."""
+ return not (
+ "e_score_correction_bias" in key
+ or ".attn_hc." in key
+ or ".ffn_hc." in key
+ or key.endswith("A_log")
+ or key.endswith("dt_bias")
+ or key.endswith("mlp.gate.weight")
+ )
+
+
+class Glm5NextRMSNormGated(nn.Module):
+ def __init__(self, hidden_size: int, eps: float = 1e-6):
+ super().__init__()
+ self.eps = eps
+ self.weight = mx.ones(hidden_size)
+
+ def __call__(self, hidden_states: mx.array, gate: mx.array) -> mx.array:
+ dt = hidden_states.dtype
+ x = hidden_states.astype(mx.float32)
+ var = (x * x).mean(-1, keepdims=True)
+ x = x * mx.rsqrt(var + self.eps)
+ x = self.weight.astype(mx.float32) * x
+ x = x * mx.sigmoid(gate.astype(mx.float32))
+ return x.astype(dt)
+
+
+class Glm5NextForgetGate(nn.Module):
+ def __init__(self, config: TextConfig):
+ super().__init__()
+ self.head_dim = config.linear_head_dim
+ self.num_heads = config.linear_num_heads
+ self.qkv_dim = self.head_dim * self.num_heads
+ self.f_a_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
+ self.f_b_proj = nn.Linear(self.head_dim, self.qkv_dim, bias=False)
+ self.dt_bias = mx.zeros(self.qkv_dim)
+ self.A_log = mx.zeros(self.num_heads)
+ self.safe_gate_lower_bound = config.linear_lower_bound
+
+ def __call__(self, hidden_states: mx.array) -> mx.array:
+ B, S, _ = hidden_states.shape
+ fg = self.f_b_proj(self.f_a_proj(hidden_states))
+ g = (fg.astype(mx.float32) + self.dt_bias.astype(mx.float32)).reshape(
+ B, S, self.num_heads, self.head_dim
+ )
+ decay = mx.exp(self.A_log.astype(mx.float32)).reshape(1, 1, self.num_heads, 1)
+ if self.safe_gate_lower_bound is not None:
+ return self.safe_gate_lower_bound * mx.sigmoid(decay * g)
+ g_softplus = mx.where(g > 20.0, g, mx.log(1.0 + mx.exp(g)))
+ return -decay * g_softplus
+
+
+def _l2norm(x: mx.array, eps: float = 1e-6) -> mx.array:
+ return x * mx.rsqrt((x * x).sum(axis=-1, keepdims=True) + eps)
+
+
+def recurrent_kimi_delta(
+ query: mx.array,
+ key: mx.array,
+ value: mx.array,
+ g: mx.array,
+ beta: mx.array,
+ state: Optional[mx.array] = None,
+):
+ # Reference O(S) recurrence for Kimi Delta Attention, kept as the readable
+ # spec and the equivalence oracle for tests. The forward path runs this on
+ # the shared fused gated_delta kernel (see Glm5NextLinearAttention).
+ dt = query.dtype
+ query = _l2norm(query.astype(mx.float32))
+ key = _l2norm(key.astype(mx.float32))
+ value = value.astype(mx.float32)
+ g = g.astype(mx.float32)
+ beta = beta.astype(mx.float32)
+ B, S, H, Dk = key.shape
+ Dv = value.shape[-1]
+ query = query * (Dk**-0.5)
+ if state is None:
+ state = mx.zeros((B, H, Dk, Dv), dtype=mx.float32)
+ else:
+ state = state.astype(mx.float32)
+ outs = []
+ for i in range(S):
+ q_i = query[:, i]
+ k_i = key[:, i]
+ v_i = value[:, i]
+ g_i = mx.exp(g[:, i])[..., None]
+ b_i = beta[:, i][..., None]
+ state = state * g_i
+ kv_mem = (state * k_i[..., None]).sum(axis=-2)
+ delta = (v_i - kv_mem) * b_i
+ state = state + k_i[..., None] * delta[..., None, :]
+ out_i = (state * q_i[..., None]).sum(axis=-2)
+ outs.append(out_i)
+ out = mx.stack(outs, axis=1).astype(dt)
+ return out, state
+
+
+class Glm5NextLinearAttention(nn.Module):
+ def __init__(self, config: TextConfig):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.num_heads = config.linear_num_heads
+ self.head_dim = config.linear_head_dim
+ self.qkv_dim = self.num_heads * self.head_dim
+ self.conv_kernel_size = config.linear_conv_kernel_dim
+
+ self.q_proj = nn.Linear(self.hidden_size, self.qkv_dim, bias=False)
+ self.k_proj = nn.Linear(self.hidden_size, self.qkv_dim, bias=False)
+ self.v_proj = nn.Linear(self.hidden_size, self.qkv_dim, bias=False)
+
+ self.conv_dim = self.qkv_dim * 3
+ self.conv1d = nn.Conv1d(
+ in_channels=self.conv_dim,
+ out_channels=self.conv_dim,
+ bias=False,
+ kernel_size=self.conv_kernel_size,
+ groups=self.conv_dim,
+ padding=0,
+ )
+
+ self.forget_gate = Glm5NextForgetGate(config)
+ self.b_proj = nn.Linear(self.hidden_size, self.num_heads, bias=False)
+ self.g_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False)
+ self.g_b_proj = nn.Linear(self.head_dim, self.qkv_dim, bias=False)
+ self.o_norm = Glm5NextRMSNormGated(self.head_dim, eps=config.rms_norm_eps)
+ self.o_proj = nn.Linear(self.qkv_dim, self.hidden_size, bias=False)
+ self.fuse_in = True
+ self._fused_ready = False
+
+ def _fused_in_proj(self, inputs):
+ # q,k,v,f_a,g_a,b all take `inputs`; fuse into one matmul via a lossless
+ # output-axis concat of the (quantized) weights, built once and cached.
+ if not self._fused_ready:
+ mods = [
+ self.q_proj,
+ self.k_proj,
+ self.v_proj,
+ self.forget_gate.f_a_proj,
+ self.g_a_proj,
+ self.b_proj,
+ ]
+ quantized = [hasattr(m, "scales") for m in mods]
+ if any(quantized) and not all(quantized):
+ return tuple(linear_forward(m, inputs) for m in mods)
+ if all(quantized):
+ specs = {
+ (m.group_size, m.bits, getattr(m, "mode", "affine")) for m in mods
+ }
+ if len(specs) != 1:
+ return tuple(linear_forward(m, inputs) for m in mods)
+ pts, acc = [], 0
+ for m in mods[:-1]:
+ acc += m.weight.shape[0]
+ pts.append(acc)
+ self._split_pts = pts
+ self._fq = hasattr(mods[0], "scales")
+ self._fw = mx.concatenate([m.weight for m in mods], axis=0)
+ if self._fq:
+ self._fs = mx.concatenate([m.scales for m in mods], axis=0)
+ self._fb = mx.concatenate([m.biases for m in mods], axis=0)
+ self._gs, self._bits = mods[0].group_size, mods[0].bits
+ self._fused_ready = True
+ if self._fq:
+ out = fused_quantized_matmul(
+ inputs,
+ self._fw,
+ self._fs,
+ self._fb,
+ bits=self._bits,
+ group_size=self._gs,
+ )
+ else:
+ out = inputs @ self._fw.T
+ return mx.split(out, self._split_pts, axis=-1)
+
+ def __call__(
+ self,
+ inputs: mx.array,
+ mask: Optional[mx.array] = None,
+ cache: Optional[Any] = None,
+ ) -> mx.array:
+ B, S, _ = inputs.shape
+ has_right_padding = cache is not None and cache.lengths is not None
+ if has_right_padding:
+ mask = mx.arange(S)[None] < cache.lengths[:, None]
+ if self.fuse_in:
+ q_o, k_o, v_o, fa_o, ga_o, b_o = self._fused_in_proj(inputs)
+ mixed = mx.concatenate([q_o, k_o, v_o], axis=-1)
+ else:
+ mixed = mx.concatenate(
+ [self.q_proj(inputs), self.k_proj(inputs), self.v_proj(inputs)], axis=-1
+ )
+ fa_o = self.forget_gate.f_a_proj(inputs)
+ ga_o = self.g_a_proj(inputs)
+ b_o = self.b_proj(inputs)
+ if mask is not None and mask.dtype == mx.bool_:
+ mixed = mx.where(mask[..., None], mixed, 0)
+
+ if cache is not None and cache[0] is not None:
+ conv_state = cache[0]
+ else:
+ conv_state = mx.zeros(
+ (B, self.conv_kernel_size - 1, self.conv_dim), dtype=inputs.dtype
+ )
+ conv_input = mx.concatenate([conv_state, mixed], axis=1)
+ if cache is not None:
+ state_size = self.conv_kernel_size - 1
+ if has_right_padding:
+ valid_lengths = mx.sum(mask, axis=-1).astype(mx.int32)
+ state_indices = valid_lengths[:, None] + mx.arange(state_size)[None]
+ state_indices = mx.broadcast_to(
+ state_indices[..., None],
+ (B, state_size, self.conv_dim),
+ )
+ cache[0] = mx.contiguous(
+ mx.take_along_axis(conv_input, state_indices, axis=1)
+ )
+ else:
+ cache[0] = mx.contiguous(conv_input[:, -state_size:, :])
+ conv_out = nn.silu(self.conv1d(conv_input))
+
+ q, k, v = mx.split(conv_out, [self.qkv_dim, 2 * self.qkv_dim], axis=-1)
+ q = q.reshape(B, S, self.num_heads, self.head_dim)
+ k = k.reshape(B, S, self.num_heads, self.head_dim)
+ v = v.reshape(B, S, self.num_heads, self.head_dim)
+
+ fg = self.forget_gate
+ a = linear_forward(fg.f_b_proj, fa_o).reshape(
+ B, S, self.num_heads, self.head_dim
+ )
+ in_dtype = q.dtype
+ q = (_l2norm(q.astype(mx.float32)) * (self.head_dim**-0.5)).astype(in_dtype)
+ k = _l2norm(k.astype(mx.float32)).astype(in_dtype)
+
+ state = cache[1] if cache is not None else None
+ out, state = gated_delta_update(
+ q,
+ k,
+ v,
+ a,
+ b_o,
+ fg.A_log.reshape(self.num_heads, 1),
+ fg.dt_bias.reshape(self.num_heads, self.head_dim),
+ state=state,
+ mask=mask if mask is not None and mask.dtype == mx.bool_ else None,
+ lower_bound=fg.safe_gate_lower_bound,
+ )
+ if cache is not None:
+ cache[1] = state
+ cache.advance(S)
+
+ gate = linear_forward(self.g_b_proj, ga_o).reshape(
+ B, S, self.num_heads, self.head_dim
+ )
+ out = self.o_norm(out, gate).reshape(B, S, -1)
+ return linear_forward(self.o_proj, out)
+
+
+class Glm5NextIndexer(nn.Module):
+ def __init__(self, args: TextConfig):
+ super().__init__()
+ self.dim = args.hidden_size
+ self.n_heads = args.index_n_heads
+ self.head_dim = args.index_head_dim
+ self.index_topk = args.index_topk
+ self.index_kpool = args.index_kpool
+ self.index_kpool_always_select_tail = args.index_kpool_always_select_tail
+ self.q_lora_rank = args.q_lora_rank
+ self.wq_b = nn.Linear(
+ self.q_lora_rank, self.n_heads * self.head_dim, bias=False
+ )
+ self.wk = nn.Linear(self.dim, self.head_dim, bias=False)
+ self.k_norm = nn.LayerNorm(self.head_dim, eps=1e-6)
+ self.weights_proj = nn.Linear(self.dim, self.n_heads, bias=False)
+ self.softmax_scale = self.head_dim**-0.5
+ self.weight_scale = self.n_heads**-0.5 * self.softmax_scale
+ self.index_kpool_compress_ape = mx.zeros((self.index_kpool, self.head_dim))
+ self.index_kpool_compress_gate = mx.zeros((self.head_dim, self.dim))
+
+ def _compress_windows(self, keys, gate_scores):
+ B, S, hd = keys.shape
+ kp = self.index_kpool
+ if S == 0:
+ return mx.zeros((B, 0, hd), dtype=keys.dtype)
+ usable = (S // kp) * kp
+ keys = keys[:, :usable].reshape(B, -1, kp, hd)
+ gate_scores = gate_scores[:, :usable].reshape(B, -1, kp, hd)
+ logits = gate_scores + self.index_kpool_compress_ape[None, None]
+ probs = mx.softmax(logits, axis=2)
+ return mx.sum(probs * keys, axis=2)
+
+ @staticmethod
+ def _processed(cache):
+ processed = getattr(cache, "_processed", None)
+ if processed is not None:
+ return list(processed)
+ return int(cache.size() * cache.ratio + cache.remainder)
+
+ @staticmethod
+ def _pool_lengths(cache):
+ lengths = getattr(cache, "_pool_lengths", None)
+ if lengths is not None:
+ return list(lengths)
+ return int(cache.size())
+
+ def _native_scores(self, q, pool_keys, weights):
+ global _NATIVE_INDEXER_WARNED
+ if (
+ q.shape[2] != self.n_heads
+ or self.n_heads != 32
+ or self.head_dim != 128
+ or q.dtype not in (mx.float16, mx.bfloat16)
+ or pool_keys.dtype != q.dtype
+ ):
+ return None
+ try:
+ from omlx.custom_kernels.glm_moe_dsa import fast
+
+ if not fast.has_symbol("dsa_indexer_scores"):
+ return None
+ qt = q.transpose(0, 2, 1, 3)
+ keys = pool_keys[:, None]
+ q_pad = (-qt.shape[2]) % 64
+ k_pad = (-keys.shape[2]) % 64
+ if q_pad:
+ qt = mx.pad(qt, [(0, 0), (0, 0), (0, q_pad), (0, 0)])
+ weights = mx.pad(weights, [(0, 0), (0, q_pad), (0, 0)])
+ if k_pad:
+ keys = mx.pad(keys, [(0, 0), (0, 0), (0, k_pad), (0, 0)])
+ scores = fast.dsa_indexer_scores(
+ qt,
+ keys,
+ weights,
+ causal=False,
+ )
+ return scores[:, 0, : q.shape[1], : pool_keys.shape[1]]
+ except (AttributeError, RuntimeError, TypeError, ValueError):
+ if not _NATIVE_INDEXER_WARNED:
+ logger.warning(
+ "GLM-5.3 native DSA indexer failed; using the MLX fallback",
+ exc_info=True,
+ )
+ _NATIVE_INDEXER_WARNED = True
+ return None
+
+ @staticmethod
+ def _native_topk(scores, topk):
+ if topk != 512:
+ return None
+ try:
+ from omlx.custom_kernels.glm_moe_dsa import fast
+
+ if fast.has_symbol("dsa_topk_indices"):
+ return fast.dsa_topk_indices(scores[:, None], topk)[:, 0]
+ except (AttributeError, RuntimeError, TypeError, ValueError):
+ pass
+ return None
+
+ def __call__(self, x, qr, mask, cache=None, kv_cache=None):
+ B, S, _ = x.shape
+ q = linear_forward(self.wq_b, qr).reshape(B, S, self.n_heads, self.head_dim)
+ k = self.k_norm(linear_forward(self.wk, x)).reshape(B, S, self.head_dim)
+ gate_scores = x @ self.index_kpool_compress_gate.swapaxes(-1, -2)
+
+ if cache is not None:
+ before = self._processed(cache)
+ cache_offset = (
+ mx.array(before, dtype=mx.int32) if isinstance(before, list) else before
+ )
+ ready_k, ready_gate, _ = cache.accumulate_windows(
+ k, gate_scores, cache_offset
+ )
+ compressed = self._compress_windows(ready_k, ready_gate)
+ pool_keys = cache.update_and_fetch(compressed)
+ after = self._processed(cache)
+ pool_lengths = self._pool_lengths(cache)
+ if isinstance(after, list):
+ before_a = mx.array(before, dtype=mx.int32)
+ valid_lengths = mx.array(
+ [a - b for a, b in zip(after, before)], dtype=mx.int32
+ )
+ valid_cur = mx.arange(S)[None] < valid_lengths[:, None]
+ total_max = max(after)
+ else:
+ before_a = mx.full((B,), before, dtype=mx.int32)
+ valid_cur = mx.ones((B, S), dtype=mx.bool_)
+ total_max = after
+ else:
+ before_a = mx.zeros((B,), dtype=mx.int32)
+ valid_cur = mx.ones((B, S), dtype=mx.bool_)
+ usable = (S // self.index_kpool) * self.index_kpool
+ pool_keys = self._compress_windows(k[:, :usable], gate_scores[:, :usable])
+ pool_lengths = usable // self.index_kpool
+ total_max = S
+
+ # The pool has already advanced, even when sparse selection is unnecessary.
+ if getattr(self, "bypass_short", True) and total_max <= self.index_topk:
+ return None
+
+ P = pool_keys.shape[1]
+ select_k = min(self.index_topk // self.index_kpool, P)
+ pool_idx = mx.arange(P)
+ pool_end = (pool_idx + 1) * self.index_kpool - 1
+ if isinstance(pool_lengths, list):
+ pool_lengths_a = mx.array(pool_lengths, dtype=mx.int32)
+ else:
+ pool_lengths_a = mx.full((B,), pool_lengths, dtype=mx.int32)
+ left_padding = getattr(kv_cache, "left_padding", None)
+ if left_padding is None:
+ left_padding = mx.zeros((B,), dtype=mx.int32)
+ tail_on = self.index_kpool_always_select_tail and self.index_kpool > 1
+ output_width = self.index_topk + (self.index_kpool - 1 if tail_on else 0)
+
+ chunk = 512 if S > 512 else S
+ out = []
+ for c0 in range(0, S, chunk):
+ c1 = min(c0 + chunk, S)
+ cs = c1 - c0
+ q_chunk = q[:, c0:c1]
+ weights = linear_forward(self.weights_proj, x[:, c0:c1])
+ weights = (weights * self.weight_scale).astype(q_chunk.dtype)
+ index_scores = self._native_scores(q_chunk, pool_keys, weights)
+ if index_scores is None:
+ head_scores = q_chunk @ pool_keys[:, None].swapaxes(-1, -2)
+ index_scores = mx.sum(
+ weights[..., None]
+ * mx.maximum(head_scores, mx.array(0, head_scores.dtype)),
+ axis=2,
+ )
+ query_pos = before_a[:, None] + mx.arange(c0, c1)[None]
+ valid_candidates = (
+ pool_idx[None, None] < pool_lengths_a[:, None, None]
+ ) & (pool_end[None, None] <= query_pos[..., None])
+ index_scores = mx.where(valid_candidates, index_scores, -1e30)
+ selected = self._native_topk(index_scores, select_k)
+ if selected is None:
+ selected = mx.argpartition(-index_scores, kth=select_k - 1, axis=-1)[
+ ..., :select_k
+ ]
+ selected_valid = mx.take_along_axis(valid_candidates, selected, axis=-1)
+ selected_indices = (
+ selected[..., None] * self.index_kpool
+ + mx.arange(self.index_kpool)[None, None, None]
+ + left_padding[:, None, None, None]
+ )
+ topk = selected_indices.reshape(B, cs, -1)
+ sv = mx.broadcast_to(
+ selected_valid[..., None], (B, cs, select_k, self.index_kpool)
+ ).reshape(B, cs, -1)
+ topk = mx.where(sv, topk, -1)
+ if tail_on:
+ tail_width = self.index_kpool - 1
+ tail_count = (query_pos + 1) % self.index_kpool
+ tail_start = query_pos + 1 - tail_count
+ tail_offsets = mx.arange(tail_width)
+ tail = tail_start[..., None] + tail_offsets
+ tail_valid = tail_offsets[None, None] < tail_count[..., None]
+ tail = tail + left_padding[:, None, None]
+ topk = mx.concatenate([topk, mx.where(tail_valid, tail, -1)], axis=-1)
+ if topk.shape[-1] < output_width:
+ pad = mx.full(
+ (B, cs, output_width - topk.shape[-1]), -1, dtype=topk.dtype
+ )
+ topk = mx.concatenate([topk, pad], axis=-1)
+ topk = topk[..., :output_width]
+ topk = mx.where(valid_cur[:, c0:c1][..., None], topk, -1)
+ out.append(topk)
+ topk = out[0] if len(out) == 1 else mx.concatenate(out, axis=1)
+ return topk[:, None].astype(mx.int32)
+
+
+class Glm5NextSparseAttention(nn.Module):
+ def __init__(self, config: TextConfig):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.q_lora_rank = config.q_lora_rank
+ self.qk_rope_head_dim = config.qk_rope_head_dim
+ self.kv_lora_rank = config.kv_lora_rank
+ self.v_head_dim = config.v_head_dim
+ self.qk_nope_head_dim = config.qk_nope_head_dim
+ self.use_nope = config.mla_use_nope or config.qk_rope_head_dim == 0
+ # GLM-5-Next is NoPE by design (qk_rope_head_dim=0, mla_use_nope=True); the
+ # config carries no rope parameters. Fail loudly rather than run wrong math
+ # if a future config ever requests a RoPE MLA.
+ if not self.use_nope:
+ raise NotImplementedError(
+ "glm5_next implements NoPE MLA only; qk_rope_head_dim>0 with "
+ "mla_use_nope=False is not supported."
+ )
+ self.q_head_dim = config.qk_nope_head_dim
+ self.scale = self.q_head_dim**-0.5
+
+ self.q_a_proj = nn.Linear(
+ self.hidden_size, self.q_lora_rank, bias=config.attention_bias
+ )
+ self.q_a_layernorm = nn.RMSNorm(self.q_lora_rank, eps=config.rms_norm_eps)
+ self.q_b_proj = nn.Linear(
+ self.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
+ )
+ self.kv_a_proj_with_mqa = nn.Linear(
+ self.hidden_size, self.kv_lora_rank, bias=config.attention_bias
+ )
+ self.kv_a_layernorm = nn.RMSNorm(self.kv_lora_rank, eps=config.rms_norm_eps)
+ self.embed_q = MultiLinear(
+ self.qk_nope_head_dim, self.kv_lora_rank, self.num_heads
+ )
+ self.unembed_out = MultiLinear(
+ self.kv_lora_rank, self.v_head_dim, self.num_heads
+ )
+ self.o_proj = nn.Linear(
+ self.num_heads * self.v_head_dim,
+ self.hidden_size,
+ bias=config.attention_bias,
+ )
+ self.indexer = Glm5NextIndexer(config)
+
+ def __call__(
+ self,
+ x: mx.array,
+ mask: Optional[mx.array] = None,
+ cache: Optional[Any] = None,
+ ) -> mx.array:
+ B, L, D = x.shape
+
+ qr = self.q_a_layernorm(linear_forward(self.q_a_proj, x))
+ q = linear_forward(self.q_b_proj, qr)
+ q = q.reshape(B, L, self.num_heads, self.q_head_dim).transpose(0, 2, 1, 3)
+
+ compressed_kv = linear_forward(self.kv_a_proj_with_mqa, x)
+ kv_latent = self.kv_a_layernorm(compressed_kv)
+ kv_latent = mx.expand_dims(kv_latent, axis=1)
+
+ if cache is not None:
+ # NoPE attention only needs the latent once. A zero-width value
+ # cache avoids storing a duplicate 512-wide tensor per sparse
+ # layer while retaining the standard KVCache lifecycle.
+ empty_values = mx.zeros((B, 1, L, 0), dtype=kv_latent.dtype)
+ kv_latent, _ = cache[0].update_and_fetch(kv_latent, empty_values)
+ else:
+ cache = [None] * 2
+
+ topk_indices = self.indexer(
+ x,
+ qr,
+ mask,
+ cache=cache[1],
+ kv_cache=cache[0],
+ )
+ attn_mask = mask
+ if topk_indices is not None:
+ Kv = kv_latent.shape[2]
+ valid_sel = topk_indices >= 0
+ if L == 1:
+ clamped = mx.clip(topk_indices[:, :, 0, :], 0, Kv - 1)
+ idx = clamped[..., None]
+ kv_latent = mx.take_along_axis(
+ kv_latent,
+ mx.broadcast_to(idx, idx.shape[:-1] + (kv_latent.shape[-1],)),
+ axis=2,
+ )
+ sel_mask = valid_sel[:, :, 0, :][:, :, None, :]
+ if mask is not None and mask.dtype == mx.bool_:
+ # Single-stream decode passes mask=None here; under continuous
+ # batching the batched cache supplies a left-pad mask that can be
+ # 4-D ([B, 1, 1, Kv]) while `clamped` is 3-D. At S=1 the mask is
+ # purely per-key (no causal), so reduce it to [B, Kv] and gather the
+ # selected key positions -- rank-agnostic and batch-safe.
+ mkeys = mask.reshape(B, -1, Kv)[:, 0, :]
+ gathered = mx.take_along_axis(
+ mx.broadcast_to(mkeys[:, None, :], (B, clamped.shape[1], Kv)),
+ clamped,
+ axis=-1,
+ )
+ sel_mask = sel_mask & gathered[:, :, None, :]
+ attn_mask = sel_mask
+ elif L <= 8:
+ return self._gathered_attention(q, kv_latent, topk_indices)
+ else:
+ q_latent = self.embed_q(q)
+ q_pe = mx.zeros(q_latent.shape[:-1] + (64,), dtype=q_latent.dtype)
+ k_pe = mx.zeros(kv_latent.shape[:-1] + (64,), dtype=kv_latent.dtype)
+ output = None
+ if Kv >= 4096:
+ output = sparse_mla_attention(
+ q_latent,
+ q_pe,
+ kv_latent,
+ k_pe,
+ topk_indices,
+ self.scale,
+ )
+ if output is not None:
+ output_flat = q8_vup_flat(
+ output,
+ self.unembed_out,
+ key_length=Kv,
+ )
+ if output_flat is None:
+ output = self.unembed_out(output)
+ output_flat = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
+ return linear_forward(self.o_proj, output_flat)
+
+ k = self.embed_q(kv_latent, transpose=False)
+ v = self.unembed_out(kv_latent)
+ output = exact_block_token_attention(
+ q,
+ k,
+ v,
+ topk_indices,
+ self.scale,
+ )
+ if output is not None:
+ output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
+ return linear_forward(self.o_proj, output)
+
+ shape = list(topk_indices.shape)
+ shape[-1] = Kv + 1
+ safe_idx = mx.where(valid_sel, topk_indices, Kv)
+ sparse_mask = mx.zeros(shape, dtype=mx.bool_)
+ sparse_mask = mx.put_along_axis(
+ sparse_mask, safe_idx, mx.array(True), axis=-1
+ )[..., :Kv]
+ if mask is not None and mask.dtype == mx.bool_:
+ sparse_mask = sparse_mask & mask
+ attn_mask = sparse_mask
+
+ if (
+ cache is not None
+ and cache[0] is not None
+ and cache[1] is not None
+ and cache[1].pooled is not None
+ ):
+ deps = tuple(v for v in cache[1].state if isinstance(v, mx.array))
+ if deps:
+ cache[0].keys = mx.depends(cache[0].keys, deps)
+
+ if L == 1:
+ q = self.embed_q(q)
+ k = v = kv_latent
+ else:
+ k = self.embed_q(kv_latent, transpose=False)
+ v = self.unembed_out(kv_latent)
+
+ output = scaled_dot_product_attention(
+ q, k, v, cache=cache, scale=self.scale, mask=attn_mask
+ )
+ if L == 1:
+ output = self.unembed_out(output)
+
+ output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
+ return linear_forward(self.o_proj, output)
+
+ def _gathered_attention(self, q, kv_latent, topk_indices):
+ B, H, L, _ = q.shape
+ Kv = kv_latent.shape[2]
+ dim = kv_latent.shape[-1]
+ selected = topk_indices[:, 0]
+ topk = selected.shape[-1]
+ clamped = mx.clip(selected, 0, Kv - 1)
+ gathered = mx.take_along_axis(
+ mx.broadcast_to(kv_latent[:, 0, None], (B, L, Kv, dim)),
+ mx.broadcast_to(clamped[..., None], (B, L, topk, dim)),
+ axis=2,
+ )
+ q_latent = self.embed_q(q).transpose(0, 2, 1, 3).reshape(B * L, H, 1, dim)
+ gathered = gathered.reshape(B * L, 1, topk, dim)
+ valid = (selected >= 0).reshape(B * L, 1, 1, topk)
+ output = scaled_dot_product_attention(
+ q_latent,
+ gathered,
+ gathered,
+ cache=None,
+ scale=self.scale,
+ mask=valid,
+ )
+ output = output.reshape(B, L, H, dim).transpose(0, 2, 1, 3)
+ output = self.unembed_out(output).transpose(0, 2, 1, 3).reshape(B, L, -1)
+ return linear_forward(self.o_proj, output)
+
+
+class Glm5NextClampedSwiGLU(nn.Module):
+ def __init__(self, limit: Optional[float]):
+ super().__init__()
+ self.limit = limit
+
+ def __call__(self, x_up: mx.array, x_gate: mx.array) -> mx.array:
+ if self.limit is not None:
+ x_gate = mx.clip(x_gate, a_min=None, a_max=self.limit)
+ x_up = mx.clip(x_up, a_min=-self.limit, a_max=self.limit)
+ return nn.silu(x_gate) * x_up
+
+
+class Glm5NextMLP(nn.Module):
+ def __init__(self, config, intermediate_size=None):
+ super().__init__()
+ intermediate_size = intermediate_size or config.intermediate_size
+ self.limit = config.swiglu_limit
+ self.gate_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
+ self.up_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
+ self.down_proj = nn.Linear(intermediate_size, config.hidden_size, bias=False)
+
+ def __call__(self, x: mx.array) -> mx.array:
+ gate = linear_forward(self.gate_proj, x)
+ up = linear_forward(self.up_proj, x)
+ if self.limit is not None:
+ gate = mx.clip(gate, a_min=None, a_max=self.limit)
+ up = mx.clip(up, a_min=-self.limit, a_max=self.limit)
+ return linear_forward(self.down_proj, nn.silu(gate) * up)
+
+
+class Glm5NextMoEGate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.top_k = config.num_experts_per_tok
+ self.norm_topk_prob = config.norm_topk_prob
+ self.n_group = config.n_group
+ self.topk_group = config.topk_group
+ self.routed_scaling_factor = config.routed_scaling_factor
+ self.weight = mx.zeros((config.n_routed_experts, config.hidden_size))
+ self.e_score_correction_bias = mx.zeros((config.n_routed_experts,))
+
+ def __call__(self, x):
+ logits = x.astype(mx.float32) @ self.weight.astype(mx.float32).T
+ return group_expert_select(
+ logits,
+ self.e_score_correction_bias,
+ self.top_k,
+ self.n_group,
+ self.topk_group,
+ self.routed_scaling_factor,
+ self.norm_topk_prob,
+ )
+
+
+class Glm5NextMoE(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.switch_mlp = SwitchGLU(
+ config.hidden_size,
+ config.moe_intermediate_size,
+ config.n_routed_experts,
+ activation=Glm5NextClampedSwiGLU(config.swiglu_limit),
+ )
+ self.gate = Glm5NextMoEGate(config)
+ self.shared_experts = None
+ if config.n_shared_experts is not None:
+ self.shared_experts = Glm5NextMLP(
+ config,
+ intermediate_size=(
+ config.moe_intermediate_size * config.n_shared_experts
+ ),
+ )
+
+ def __call__(self, x):
+ indices, scores = self.gate(x)
+ y = self.switch_mlp(x, indices, scores=scores, weighted_sum=True)
+ if y.ndim == x.ndim + 1:
+ y = (y * scores[..., None]).sum(axis=-2).astype(x.dtype)
+ if self.shared_experts is not None:
+ y = y + self.shared_experts(x)
+ return y
+
+
+class Glm5NextDecoderLayer(nn.Module):
+ def __init__(self, config: TextConfig, layer_idx: int):
+ super().__init__()
+ layer_type = config.layer_types[layer_idx]
+ self.is_linear = layer_type == "linear_attention"
+ if self.is_linear:
+ self.self_attn = Glm5NextLinearAttention(config)
+ else:
+ self.self_attn = Glm5NextSparseAttention(config)
+
+ is_sparse = (
+ config.n_routed_experts is not None
+ and layer_idx >= config.first_k_dense_replace
+ and config.mlp_layer_types[layer_idx] == "sparse"
+ )
+ self.mlp = Glm5NextMoE(config) if is_sparse else Glm5NextMLP(config)
+
+ self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = nn.RMSNorm(
+ config.hidden_size, eps=config.rms_norm_eps
+ )
+ self.attn_hc = HyperConnection(config)
+ self.ffn_hc = HyperConnection(config)
+ self.compile_ffn = True
+ self._ffn_c = None
+
+ def __call__(
+ self,
+ x: mx.array,
+ mask: Optional[mx.array] = None,
+ cache: Optional[Any] = None,
+ ) -> mx.array:
+ residual = x
+ xc, post, comb = self.attn_hc(x)
+ r = self.self_attn(self.input_layernorm(xc), mask, cache)
+ x = hc_expand(r, residual, post, comb)
+ # Compile the FFN block only for single-stream decode (B=1, S=1) -- the shape it
+ # was validated on and where its win lives. Compiling the 288-expert MoE at a
+ # batched or prefill shape spikes memory (it can OOM alongside the resident
+ # weights), so those shapes take the eager path.
+ if self.compile_ffn and x.shape[0] == 1 and x.shape[1] == 1:
+ if self._ffn_c is None:
+ self._ffn_c = mx.compile(self._ffn_block)
+ return self._ffn_c(x)
+ return self._ffn_block(x)
+
+ def _ffn_block(self, x: mx.array) -> mx.array:
+ # Stateless FFN half (no cache) -> compiles cleanly at a fixed decode shape.
+ residual = x
+ xc, post, comb = self.ffn_hc(x)
+ m = self.mlp(self.post_attention_layernorm(xc))
+ return hc_expand(m, residual, post, comb)
+
+
+class Glm5NextModel(nn.Module):
+ def __init__(self, config: TextConfig):
+ super().__init__()
+ self.config = config
+ self.hc_mult = config.hc_mult
+ self.vocab_size = config.vocab_size
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
+ self.layers = [
+ Glm5NextDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)
+ ]
+ self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.ssm_idx = next((i for i, l in enumerate(self.layers) if l.is_linear), 0)
+ self.fa_idx = next((i for i, l in enumerate(self.layers) if not l.is_linear), 0)
+
+ def __call__(
+ self,
+ inputs: mx.array,
+ cache: Optional[Any] = None,
+ inputs_embeds: Optional[mx.array] = None,
+ ) -> mx.array:
+ h = self.embed_tokens(inputs) if inputs_embeds is None else inputs_embeds
+
+ if cache is None:
+ cache = [None] * len(self.layers)
+
+ fa_cache = cache[self.fa_idx]
+ fa_mask = create_attention_mask(
+ h, fa_cache[0] if fa_cache else None, return_array=True
+ )
+ ssm_mask = create_ssm_mask(h, cache[self.ssm_idx])
+
+ h = mx.broadcast_to(
+ h[:, :, None, :], (h.shape[0], h.shape[1], self.hc_mult, h.shape[2])
+ )
+ h = mx.contiguous(h)
+
+ for layer, c in zip(self.layers, cache):
+ mask = ssm_mask if layer.is_linear else fa_mask
+ h = layer(h, mask=mask, cache=c)
+
+ h = h.mean(axis=2)
+ return self.norm(h)
+
+
+class LanguageModel(nn.Module):
+ def __init__(self, args: TextConfig, config: ModelConfig = None):
+ super().__init__()
+ self.args = args
+ self.config = args
+ self.model_type = args.model_type
+ self.model = Glm5NextModel(args)
+ if not args.tie_word_embeddings:
+ self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False)
+
+ def __call__(
+ self,
+ inputs: Optional[mx.array] = None,
+ inputs_embeds: Optional[mx.array] = None,
+ cache: Optional[Any] = None,
+ mask: Optional[mx.array] = None,
+ **kwargs,
+ ) -> LanguageModelOutput:
+ if inputs is None:
+ inputs = kwargs.get("input_ids")
+ out = self.model(inputs, cache=cache, inputs_embeds=inputs_embeds)
+ # Only the last few positions' logits are ever needed for generation; slicing
+ # before the (vocab-wide) projection skips it on discarded prefill positions.
+ nlk = kwargs.get("num_logits_to_keep", 0)
+ if nlk:
+ out = out[:, -nlk:, :]
+ if self.args.tie_word_embeddings:
+ out = self.model.embed_tokens.as_linear(out)
+ else:
+ out = linear_forward(self.lm_head, out)
+ return LanguageModelOutput(logits=out)
+
+ def sanitize(self, weights):
+ weights = {k: v for k, v in weights.items() if "mtp." not in k}
+ weights = DSV32Model.sanitize(self, weights)
+
+ remapped = {}
+ conv_parts = {}
+ fg_parts = ("A_log", "dt_bias", "f_a_proj.weight", "f_b_proj.weight")
+ for k, v in weights.items():
+ nk = k.replace(".hc_attn_", ".attn_hc.").replace(".hc_ffn_", ".ffn_hc.")
+
+ fused = False
+ for part in ("q_conv1d.weight", "k_conv1d.weight", "v_conv1d.weight"):
+ suffix = ".self_attn." + part
+ if nk.endswith(suffix):
+ prefix = nk[: -len(part)]
+ conv_parts.setdefault(prefix, {})[part[0]] = v
+ fused = True
+ break
+ if fused:
+ continue
+
+ for p in fg_parts:
+ suffix = ".self_attn." + p
+ if nk.endswith(suffix):
+ nk = nk[: -len(p)] + "forget_gate." + p
+ break
+
+ remapped[nk] = v
+
+ for prefix, parts in conv_parts.items():
+ if all(c in parts for c in ("q", "k", "v")):
+ remapped[prefix + "conv1d.weight"] = mx.concatenate(
+ [parts["q"], parts["k"], parts["v"]], axis=0
+ )
+ else:
+ for c, w in parts.items():
+ remapped[prefix + c + "_conv1d.weight"] = w
+
+ weights = remapped
+ for k, v in list(weights.items()):
+ if "conv1d.weight" in k and v.ndim == 3 and v.shape[-1] != 1:
+ weights[k] = v.moveaxis(2, 1)
+ for k, v in list(weights.items()):
+ keep_fp32 = (
+ ".attn_hc." in k
+ or ".ffn_hc." in k
+ or k.endswith("A_log")
+ or k.endswith("dt_bias")
+ or k.endswith("mlp.gate.weight")
+ or k.endswith("e_score_correction_bias")
+ )
+ if (
+ keep_fp32
+ and mx.issubdtype(v.dtype, mx.floating)
+ and v.dtype != mx.float32
+ ):
+ weights[k] = v.astype(mx.float32)
+ return weights
+
+ @property
+ def layers(self):
+ return self.model.layers
+
+ @property
+ def cast_predicate(self):
+ return glm5_next_cast_predicate
+
+ @property
+ def quant_predicate(self):
+ def predicate(path, _):
+ if path.endswith("mlp.gate") or "e_score_correction_bias" in path:
+ return False
+ if ".indexer" in path:
+ return {"group_size": 64, "bits": 8}
+ return True
+
+ return predicate
+
+ def make_cache(self):
+ caches = []
+ for layer in self.layers:
+ if layer.is_linear:
+ caches.append(ArraysCache(size=2))
+ else:
+ from mlx_lm.models.cache import PoolingCache
+
+ caches.append(
+ CacheList(
+ KVCache(), PoolingCache(layer.self_attn.indexer.index_kpool)
+ )
+ )
+ return caches
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py
new file mode 100644
index 0000000000..489ee9ef0a
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py
@@ -0,0 +1,113 @@
+"""Model-neutral affine qmm routing for GLM-5.3 projections."""
+
+from __future__ import annotations
+
+import mlx.core as mx
+import mlx.nn as nn
+
+
+def _native_qmm(linear: nn.QuantizedLinear, x: mx.array):
+ bits = int(getattr(linear, "bits", 0) or 0)
+ group_size = int(getattr(linear, "group_size", 0) or 0)
+ if bits not in (2, 4, 5, 6, 8) or group_size not in (64, 128):
+ return None
+ if getattr(linear, "mode", None) != "affine" or "bias" in linear:
+ return None
+ min_tokens = 1024 if bits == 8 else 128
+ if x.ndim < 2 or x.shape[-2] < min_tokens:
+ return None
+
+ try:
+ from omlx.patches.qwen35_q4_mlp import _is_supported_affine_linear
+ from omlx.custom_kernels.qwen35_prefill import fast
+
+ name = f"qwen35_q{bits}_affine_qmm_t"
+ if not fast.has_symbol(name) or not _is_supported_affine_linear(linear, x):
+ return None
+ # The tile indexes x as row-major packed and ignores its strides, so a
+ # last-axis view reads the wrong lanes.
+ x = mx.contiguous(x)
+ return getattr(fast, name)(
+ x,
+ linear.weight,
+ linear.scales,
+ linear.biases,
+ 8,
+ group_size,
+ )
+ except (AttributeError, RuntimeError, TypeError, ValueError):
+ return None
+
+
+def linear_forward(linear: nn.Module, x: mx.array) -> mx.array:
+ """Use oMLX's affine prefill tile when it is supported and profitable."""
+ if isinstance(linear, nn.QuantizedLinear):
+ if (
+ "bias" in linear
+ and getattr(linear, "mode", None) == "affine"
+ and getattr(linear, "biases", None) is not None
+ ):
+ out = fused_quantized_matmul(
+ x,
+ linear.weight,
+ linear.scales,
+ linear.biases,
+ bits=int(linear.bits),
+ group_size=int(linear.group_size),
+ )
+ return out + linear.bias
+ out = _native_qmm(linear, x)
+ if out is not None:
+ return out
+ return linear(x)
+
+
+def fused_quantized_matmul(
+ x: mx.array,
+ weight: mx.array,
+ scales: mx.array,
+ biases: mx.array,
+ *,
+ bits: int,
+ group_size: int,
+) -> mx.array:
+ """Route a concatenated projection through the same native affine tile."""
+ min_tokens = 1024 if bits == 8 else 128
+ if (
+ x.ndim >= 2
+ and x.shape[-2] >= min_tokens
+ and bits in (2, 4, 5, 6, 8)
+ and group_size in (64, 128)
+ and weight.ndim == scales.ndim == biases.ndim == 2
+ and weight.dtype == mx.uint32
+ and scales.dtype == x.dtype
+ and biases.dtype == x.dtype
+ and weight.shape[0] % 64 == 0
+ and x.shape[-1] % 64 == 0
+ ):
+ try:
+ from omlx.custom_kernels.qwen35_prefill import fast
+
+ name = f"qwen35_q{bits}_affine_qmm_t"
+ if fast.has_symbol(name) and fast.qmm_supports_group_size(group_size):
+ # The tile ignores the input's strides. See _native_qmm.
+ x = mx.contiguous(x)
+ return getattr(fast, name)(
+ x,
+ weight,
+ scales,
+ biases,
+ 8,
+ group_size,
+ )
+ except (AttributeError, RuntimeError, TypeError, ValueError):
+ pass
+ return mx.quantized_matmul(
+ x,
+ weight,
+ scales,
+ biases,
+ transpose=True,
+ group_size=group_size,
+ bits=bits,
+ )
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/processing.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/processing.py
new file mode 100644
index 0000000000..33219a658c
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/processing.py
@@ -0,0 +1,496 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Torch-free processor support for GLM-5.3-Flash.
+
+The official checkpoint targets a newer Transformers release than oMLX. This
+module mirrors the GLM-5 Next image layout with NumPy and Pillow so image
+requests remain available without pulling in torch or torchvision.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+from PIL import Image
+from transformers import AutoTokenizer
+from transformers.feature_extraction_utils import BatchFeature
+from transformers.image_processing_utils import ImageProcessingMixin
+from transformers.processing_utils import ProcessorMixin
+
+from ..base import install_auto_processor_patch, load_chat_template, to_mlx
+
+OPENAI_CLIP_MEAN = (0.48145466, 0.4578275, 0.40821073)
+OPENAI_CLIP_STD = (0.26862954, 0.26130258, 0.27577711)
+
+_IMAGE_KWARGS = {
+ "do_convert_rgb",
+ "do_normalize",
+ "do_rescale",
+ "image_mean",
+ "image_std",
+ "max_image_tokens",
+ "merge_size",
+ "min_image_tokens",
+ "patch_expand_factor",
+ "patch_size",
+ "rescale_factor",
+ "temporal_patch_size",
+}
+
+
+def smart_resize(
+ num_frames: int,
+ height: int,
+ width: int,
+ *,
+ temporal_factor: int = 2,
+ factor: int = 28,
+ min_image_tokens: int = 16,
+ max_image_tokens: int = 8000,
+) -> tuple[int, int]:
+ """Return GLM's aligned canvas dimensions for an image or video."""
+ if num_frames <= 0 or height <= 0 or width <= 0:
+ raise ValueError("Image dimensions and frame count must be positive.")
+
+ pixels_per_token = temporal_factor * factor**2
+ min_pixels = min_image_tokens * pixels_per_token
+ max_pixels = max_image_tokens * pixels_per_token
+
+ def align(value: int) -> int:
+ return math.ceil(value / factor) * factor
+
+ aligned_frames = max(
+ temporal_factor,
+ round(num_frames / temporal_factor) * temporal_factor,
+ )
+ aligned_height = align(height)
+ aligned_width = align(width)
+ aligned_pixel_budget = aligned_frames * aligned_height * aligned_width
+
+ if aligned_pixel_budget < min_pixels:
+ scale = math.sqrt(min_pixels / (num_frames * height * width))
+ aligned_height = align(max(1, math.ceil(height * scale)))
+ aligned_width = align(max(1, math.ceil(width * scale)))
+ aligned_pixel_budget = aligned_frames * aligned_height * aligned_width
+
+ if aligned_pixel_budget <= max_pixels:
+ return aligned_height, aligned_width
+
+ minimum_pixels = aligned_frames * factor**2
+ if max_pixels < minimum_pixels:
+ raise ValueError(
+ f"max_image_tokens={max_image_tokens} is too small for one "
+ "aligned patch."
+ )
+
+ low, high = 1, height
+ best_height, best_width = factor, factor
+ while low <= high:
+ content_height = (low + high) // 2
+ content_width = max(1, math.floor(width * content_height / height))
+ candidate_height = align(content_height)
+ candidate_width = align(content_width)
+ if aligned_frames * candidate_height * candidate_width <= max_pixels:
+ best_height, best_width = candidate_height, candidate_width
+ low = content_height + 1
+ else:
+ high = content_height - 1
+ return best_height, best_width
+
+
+def _to_channel_first(image: Any, do_convert_rgb: bool) -> np.ndarray:
+ if isinstance(image, (str, Path)):
+ image = Image.open(image)
+ if hasattr(image, "convert"):
+ if do_convert_rgb:
+ image = image.convert("RGB")
+ array = np.asarray(image)
+ else:
+ array = np.asarray(image)
+
+ if array.ndim == 2:
+ array = np.repeat(array[..., None], 3, axis=-1)
+ if array.ndim != 3:
+ raise ValueError(f"Expected a 3D image, got shape {array.shape}.")
+ if array.shape[-1] in (1, 3, 4):
+ array = np.transpose(array, (2, 0, 1))
+ if array.shape[0] == 4:
+ array = array[:3]
+ if array.shape[0] == 1 and do_convert_rgb:
+ array = np.repeat(array, 3, axis=0)
+ if array.shape[0] != 3:
+ raise ValueError(f"Expected an RGB image, got shape {array.shape}.")
+ return array
+
+
+def _resize_channel_first(
+ image: np.ndarray, target_height: int, target_width: int
+) -> np.ndarray:
+ if image.shape[-2:] == (target_height, target_width):
+ return image
+ array = np.transpose(image, (1, 2, 0))
+ if array.dtype != np.uint8:
+ if np.issubdtype(array.dtype, np.floating) and array.max(initial=0) <= 1:
+ array = array * 255
+ array = np.clip(array, 0, 255).astype(np.uint8)
+ resized = Image.fromarray(array).resize(
+ (target_width, target_height),
+ resample=Image.Resampling.BICUBIC,
+ )
+ return np.transpose(np.asarray(resized), (2, 0, 1))
+
+
+class Glm5NextImageProcessor(ImageProcessingMixin):
+ """NumPy/Pillow implementation of the GLM-5 Next image processor."""
+
+ model_input_names = ["pixel_values", "image_grid_thw"]
+
+ def __init__(
+ self,
+ patch_size: int = 14,
+ temporal_patch_size: int = 2,
+ merge_size: int = 2,
+ patch_expand_factor: int = 1,
+ min_image_tokens: int = 16,
+ max_image_tokens: int = 8000,
+ do_rescale: bool = True,
+ rescale_factor: float = 1 / 255.0,
+ do_normalize: bool = True,
+ image_mean: list[float] | None = None,
+ image_std: list[float] | None = None,
+ do_convert_rgb: bool = True,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.patch_size = patch_size
+ self.temporal_patch_size = temporal_patch_size
+ self.merge_size = merge_size
+ self.patch_expand_factor = patch_expand_factor
+ self.min_image_tokens = min_image_tokens
+ self.max_image_tokens = max_image_tokens
+ self.do_rescale = do_rescale
+ self.rescale_factor = rescale_factor
+ self.do_normalize = do_normalize
+ self.image_mean = list(image_mean or OPENAI_CLIP_MEAN)
+ self.image_std = list(image_std or OPENAI_CLIP_STD)
+ self.do_convert_rgb = do_convert_rgb
+
+ def fetch_images(self, images):
+ if not isinstance(images, list):
+ images = [images]
+ return [_to_channel_first(image, self.do_convert_rgb) for image in images]
+
+ def _process_one(self, image: Any, **kwargs) -> tuple[np.ndarray, list[int]]:
+ do_convert_rgb = kwargs.get("do_convert_rgb", self.do_convert_rgb)
+ do_rescale = kwargs.get("do_rescale", self.do_rescale)
+ rescale_factor = kwargs.get("rescale_factor", self.rescale_factor)
+ do_normalize = kwargs.get("do_normalize", self.do_normalize)
+ image_mean = kwargs.get("image_mean", self.image_mean)
+ image_std = kwargs.get("image_std", self.image_std)
+ image = _to_channel_first(image, do_convert_rgb)
+ _, height, width = image.shape
+ patch_size = kwargs.get("patch_size", self.patch_size)
+ temporal_patch_size = kwargs.get(
+ "temporal_patch_size", self.temporal_patch_size
+ )
+ merge_size = kwargs.get("merge_size", self.merge_size)
+ patch_expand_factor = kwargs.get(
+ "patch_expand_factor", self.patch_expand_factor
+ )
+ min_image_tokens = kwargs.get("min_image_tokens", self.min_image_tokens)
+ max_image_tokens = kwargs.get("max_image_tokens", self.max_image_tokens)
+ factor = patch_size * merge_size * patch_expand_factor
+ target_height, target_width = smart_resize(
+ temporal_patch_size,
+ height,
+ width,
+ temporal_factor=temporal_patch_size,
+ factor=factor,
+ min_image_tokens=min_image_tokens,
+ max_image_tokens=max_image_tokens,
+ )
+
+ pixels_per_token = temporal_patch_size * factor**2
+ scale = min(target_height / height, target_width / width)
+ if temporal_patch_size * height * width >= (
+ pixels_per_token * min_image_tokens
+ ):
+ scale = min(1.0, scale)
+ content_height = max(1, min(target_height, math.floor(height * scale)))
+ content_width = max(1, min(target_width, math.floor(width * scale)))
+ image = _resize_channel_first(image, content_height, content_width)
+
+ canvas = np.zeros(
+ (image.shape[0], target_height, target_width), dtype=image.dtype
+ )
+ canvas[:, :content_height, :content_width] = image
+ image = canvas.astype(np.float32)
+ if do_rescale:
+ image *= rescale_factor
+ if do_normalize:
+ mean = np.asarray(image_mean, dtype=np.float32)[:, None, None]
+ std = np.asarray(image_std, dtype=np.float32)[:, None, None]
+ image = (image - mean) / std
+
+ channels = image.shape[0]
+ grid_h = target_height // patch_size
+ grid_w = target_width // patch_size
+ patches = image.reshape(
+ channels,
+ grid_h // merge_size,
+ merge_size,
+ patch_size,
+ grid_w // merge_size,
+ merge_size,
+ patch_size,
+ )
+ patches = patches.transpose(1, 4, 2, 5, 0, 3, 6)
+ patches = np.expand_dims(patches, axis=5)
+ patches = np.repeat(patches, temporal_patch_size, axis=5)
+ patches = patches.reshape(
+ grid_h * grid_w,
+ channels * temporal_patch_size * patch_size * patch_size,
+ )
+ return patches.astype(np.float32), [1, grid_h, grid_w]
+
+ def __call__(self, images=None, **kwargs):
+ return self.preprocess(images=images, **kwargs)
+
+ def preprocess(self, images=None, return_tensors=None, **kwargs) -> BatchFeature:
+ if images is None:
+ raise ValueError("images must not be None")
+ if not isinstance(images, list):
+ images = [images]
+ image_kwargs = {
+ key: value for key, value in kwargs.items() if key in _IMAGE_KWARGS
+ }
+ processed = [self._process_one(image, **image_kwargs) for image in images]
+ data = {
+ "pixel_values": np.concatenate([item[0] for item in processed], axis=0),
+ "image_grid_thw": np.asarray(
+ [item[1] for item in processed], dtype=np.int64
+ ),
+ }
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def get_number_of_image_patches(
+ self, height: int, width: int, images_kwargs: dict | None = None
+ ) -> int:
+ images_kwargs = images_kwargs or {}
+ patch_size = images_kwargs.get("patch_size", self.patch_size)
+ merge_size = images_kwargs.get("merge_size", self.merge_size)
+ patch_expand_factor = images_kwargs.get(
+ "patch_expand_factor", self.patch_expand_factor
+ )
+ target_height, target_width = smart_resize(
+ images_kwargs.get("temporal_patch_size", self.temporal_patch_size),
+ height,
+ width,
+ temporal_factor=images_kwargs.get(
+ "temporal_patch_size", self.temporal_patch_size
+ ),
+ factor=patch_size * merge_size * patch_expand_factor,
+ min_image_tokens=images_kwargs.get(
+ "min_image_tokens", self.min_image_tokens
+ ),
+ max_image_tokens=images_kwargs.get(
+ "max_image_tokens", self.max_image_tokens
+ ),
+ )
+ return (target_height // patch_size) * (target_width // patch_size)
+
+
+def _load_json(model_path: str | Path, filename: str) -> dict | None:
+ local = Path(model_path) / filename
+ if local.exists():
+ return json.loads(local.read_text())
+ try:
+ from huggingface_hub import hf_hub_download
+
+ downloaded = hf_hub_download(str(model_path), filename)
+ return json.loads(Path(downloaded).read_text())
+ except Exception:
+ return None
+
+
+def _image_processor_kwargs(model_path: str | Path) -> dict:
+ config = _load_json(model_path, "config.json") or {}
+ vision = config.get("vision_config", {}) or {}
+ processor = _load_json(model_path, "processor_config.json") or {}
+ image = processor.get("image_processor", {}) or {}
+
+ result = {}
+ for key in _IMAGE_KWARGS:
+ if key in image:
+ result[key] = image[key]
+ for source, target in (
+ ("patch_size", "patch_size"),
+ ("temporal_patch_size", "temporal_patch_size"),
+ ("spatial_merge_size", "merge_size"),
+ ):
+ if target not in result and source in vision:
+ result[target] = vision[source]
+ return result
+
+
+class Glm5NextProcessor(ProcessorMixin):
+ attributes = ["image_processor", "tokenizer"]
+ valid_kwargs = ["chat_template"]
+ image_processor_class = "AutoImageProcessor"
+ tokenizer_class = "AutoTokenizer"
+
+ def check_argument_for_proper_class(self, argument_name, argument):
+ return type(argument)
+
+ def __init__(
+ self,
+ image_processor=None,
+ tokenizer=None,
+ chat_template=None,
+ **kwargs,
+ ):
+ image_processor = image_processor or Glm5NextImageProcessor()
+ self.image_token = "<|image|>"
+ self.video_token = "<|video|>"
+ self.image_token_id = (
+ tokenizer.convert_tokens_to_ids(self.image_token) if tokenizer else None
+ )
+ self.video_token_id = (
+ tokenizer.convert_tokens_to_ids(self.video_token) if tokenizer else None
+ )
+ super().__init__(
+ image_processor,
+ tokenizer,
+ chat_template=chat_template,
+ )
+
+ def __call__(
+ self,
+ images=None,
+ text=None,
+ padding=True,
+ padding_side=None,
+ add_special_tokens=False,
+ return_tensors="mlx",
+ return_mm_token_type_ids=True,
+ **kwargs,
+ ) -> BatchFeature:
+ image_inputs = {}
+ if images is not None:
+ image_kwargs = {
+ key: value for key, value in kwargs.items() if key in _IMAGE_KWARGS
+ }
+ image_inputs = dict(
+ self.image_processor(
+ images=images,
+ return_tensors=None,
+ **image_kwargs,
+ )
+ )
+
+ if text is None:
+ text = [""]
+ elif not isinstance(text, list):
+ text = [text]
+ text = ["" if item is None else str(item) for item in text]
+
+ if image_inputs:
+ placeholder = "<|glm5_next_image_placeholder|>"
+ image_idx = 0
+ grids = image_inputs["image_grid_thw"]
+ for prompt_idx, prompt in enumerate(text):
+ while self.image_token in prompt:
+ if image_idx >= len(grids):
+ raise ValueError("More image tokens were provided than images.")
+ count = int(
+ np.prod(grids[image_idx]) // self.image_processor.merge_size**2
+ )
+ prompt = prompt.replace(self.image_token, placeholder * count, 1)
+ image_idx += 1
+ text[prompt_idx] = prompt.replace(placeholder, self.image_token)
+ if image_idx != len(grids):
+ raise ValueError("More images were provided than image tokens.")
+
+ tokenizer_kwargs = dict(kwargs)
+ for key in _IMAGE_KWARGS:
+ tokenizer_kwargs.pop(key, None)
+ if padding_side is not None:
+ tokenizer_kwargs["padding_side"] = padding_side
+ text_inputs = dict(
+ self.tokenizer(
+ text,
+ padding=padding,
+ add_special_tokens=add_special_tokens,
+ return_tensors=None,
+ **tokenizer_kwargs,
+ )
+ )
+
+ if return_mm_token_type_ids and self.image_token_id is not None:
+ input_ids = np.asarray(text_inputs["input_ids"])
+ mm_token_type_ids = np.zeros_like(input_ids)
+ mm_token_type_ids[input_ids == self.image_token_id] = 1
+ text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist()
+
+ data = {**text_inputs, **image_inputs}
+ if return_tensors == "mlx":
+ data = to_mlx(data)
+ return BatchFeature(data=data)
+
+ def batch_decode(self, *args, **kwargs):
+ return self.tokenizer.batch_decode(*args, **kwargs)
+
+ def decode(self, *args, **kwargs):
+ return self.tokenizer.decode(*args, **kwargs)
+
+ def apply_chat_template(self, *args, **kwargs):
+ return self.tokenizer.apply_chat_template(*args, **kwargs)
+
+ @property
+ def model_input_names(self):
+ tokenizer_names = getattr(self.tokenizer, "model_input_names", [])
+ return list(
+ dict.fromkeys(
+ tokenizer_names
+ + self.image_processor.model_input_names
+ + ["mm_token_type_ids"]
+ )
+ )
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
+ tokenizer_kwargs = dict(kwargs)
+ chat_template = tokenizer_kwargs.pop("chat_template", None)
+ tokenizer_kwargs.pop("return_tensors", None)
+ tokenizer = AutoTokenizer.from_pretrained(
+ pretrained_model_name_or_path,
+ **tokenizer_kwargs,
+ )
+ if Path(pretrained_model_name_or_path).exists():
+ load_chat_template(tokenizer, pretrained_model_name_or_path)
+ processor_config = (
+ _load_json(pretrained_model_name_or_path, "processor_config.json") or {}
+ )
+ return cls(
+ image_processor=Glm5NextImageProcessor(
+ **_image_processor_kwargs(pretrained_model_name_or_path)
+ ),
+ tokenizer=tokenizer,
+ chat_template=(
+ chat_template
+ or processor_config.get("chat_template")
+ or getattr(tokenizer, "chat_template", None)
+ ),
+ )
+
+
+install_auto_processor_patch("glm5_next", Glm5NextProcessor)
+
+__all__ = [
+ "Glm5NextImageProcessor",
+ "Glm5NextProcessor",
+ "smart_resize",
+]
diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/vision.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/vision.py
new file mode 100644
index 0000000000..d1b94c1259
--- /dev/null
+++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/vision.py
@@ -0,0 +1,359 @@
+from typing import Optional
+
+import mlx.core as mx
+import mlx.nn as nn
+
+from .config import VisionConfig
+from .linear import linear_forward
+
+
+def check_array_shape(arr):
+ shape = arr.shape
+
+ if len(shape) == 4:
+ out_channels, kH, KW, _ = shape
+ return (out_channels >= kH) and (out_channels >= KW) and (kH == KW)
+ elif len(shape) == 5:
+ out_channels, kT, kH, KW, _ = shape
+ return (out_channels >= kH) and (out_channels >= KW) and (kH == KW)
+ else:
+ return False
+
+
+def rotate_half(x):
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return mx.concatenate([-x2, x1], axis=-1)
+
+
+def apply_rotary_pos_emb_vision(
+ q: mx.array, k: mx.array, cos: mx.array, sin: mx.array
+) -> tuple:
+ orig_q_dtype = q.dtype
+ orig_k_dtype = k.dtype
+ q, k = q.astype(mx.float32), k.astype(mx.float32)
+ cos = mx.expand_dims(cos, axis=-2).astype(mx.float32)
+ sin = mx.expand_dims(sin, axis=-2).astype(mx.float32)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ q_embed = q_embed.astype(orig_q_dtype)
+ k_embed = k_embed.astype(orig_k_dtype)
+ return q_embed, k_embed
+
+
+class Glm5NextVisionRotaryEmbedding(nn.Module):
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
+ super().__init__()
+ self.dim = dim
+ self.theta = theta
+
+ def __call__(self, seqlen: int) -> mx.array:
+ inv_freq = 1.0 / (
+ self.theta ** (mx.arange(0, self.dim, 2, dtype=mx.float32) / self.dim)
+ )
+ seq = mx.arange(seqlen, dtype=inv_freq.dtype)
+ freqs = mx.outer(seq, inv_freq)
+ return freqs
+
+
+class Glm5NextVisionPatchEmbed(nn.Module):
+ def __init__(self, config: VisionConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.patch_size = config.patch_size
+ self.temporal_patch_size = config.temporal_patch_size
+ self.in_channels = config.in_channels
+ self.embed_dim = config.hidden_size
+
+ kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size]
+ self.proj = nn.Conv3d(
+ self.in_channels,
+ self.embed_dim,
+ kernel_size=kernel_size,
+ stride=kernel_size,
+ bias=True,
+ )
+
+ def __call__(self, hidden_states: mx.array) -> mx.array:
+ hidden_states = hidden_states.reshape(
+ -1,
+ self.in_channels,
+ self.temporal_patch_size,
+ self.patch_size,
+ self.patch_size,
+ ).moveaxis(1, 4)
+
+ hidden_states = self.proj(hidden_states)
+ hidden_states = hidden_states.reshape(-1, self.embed_dim)
+ return hidden_states
+
+
+class Glm5NextVisionPatchMerger(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ context_dim: int,
+ hidden_act: str,
+ swiglu_limit: float,
+ bias: bool = False,
+ ) -> None:
+ super().__init__()
+ self.swiglu_limit = swiglu_limit
+ self.proj = nn.Linear(dim, dim, bias=bias)
+ self.post_projection_norm = nn.LayerNorm(dim)
+ self.gate_proj = nn.Linear(dim, context_dim, bias=bias)
+ self.up_proj = nn.Linear(dim, context_dim, bias=bias)
+ self.down_proj = nn.Linear(context_dim, dim, bias=bias)
+
+ def __call__(self, x: mx.array) -> mx.array:
+ x = linear_forward(self.proj, x)
+ x = nn.gelu(self.post_projection_norm(x))
+ gate = linear_forward(self.gate_proj, x)
+ up = linear_forward(self.up_proj, x)
+ if self.swiglu_limit is not None:
+ gate = mx.clip(gate, a_min=None, a_max=self.swiglu_limit)
+ up = mx.clip(up, a_min=-self.swiglu_limit, a_max=self.swiglu_limit)
+ return linear_forward(self.down_proj, nn.silu(gate) * up)
+
+
+class Glm5NextVisionAttention(nn.Module):
+ def __init__(self, config: VisionConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.dim = config.hidden_size
+ self.num_heads = config.num_heads
+ self.head_dim = self.dim // self.num_heads
+ self.scale = self.head_dim**-0.5
+
+ self.qkv = nn.Linear(
+ config.hidden_size, config.hidden_size * 3, bias=config.attention_bias
+ )
+ self.proj = nn.Linear(
+ config.hidden_size, config.hidden_size, bias=config.attention_bias
+ )
+
+ self.q_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.k_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+
+ def __call__(
+ self,
+ hidden_states: mx.array,
+ cu_seqlens: mx.array,
+ position_embeddings: tuple,
+ ) -> mx.array:
+ seq_length = hidden_states.shape[0]
+
+ qkv = linear_forward(self.qkv, hidden_states)
+ qkv = qkv.reshape(seq_length, 3, self.num_heads, -1)
+ qkv = qkv.transpose(1, 0, 2, 3)
+ q, k, v = mx.split(qkv, 3, axis=0)
+ q = q.squeeze(0)
+ k = k.squeeze(0)
+ v = v.squeeze(0)
+
+ q = self.q_norm(q)
+ k = self.k_norm(k)
+
+ cos, sin = position_embeddings
+ q, k = apply_rotary_pos_emb_vision(q, k, cos, sin)
+
+ q = q.transpose(1, 0, 2)[None, ...]
+ k = k.transpose(1, 0, 2)[None, ...]
+ v = v.transpose(1, 0, 2)[None, ...]
+
+ lengths = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
+ split_indices = []
+ cumsum = 0
+ for i, length in enumerate(lengths[:-1]):
+ cumsum += length
+ split_indices.append(cumsum)
+
+ q_splits = mx.split(q, split_indices, axis=2)
+ k_splits = mx.split(k, split_indices, axis=2)
+ v_splits = mx.split(v, split_indices, axis=2)
+
+ attn_outputs = []
+ for q_chunk, k_chunk, v_chunk in zip(q_splits, k_splits, v_splits):
+ output = mx.fast.scaled_dot_product_attention(
+ q_chunk, k_chunk, v_chunk, scale=self.scale, mask=None
+ )
+ attn_outputs.append(output)
+
+ attn_output = mx.concatenate(attn_outputs, axis=2)
+ attn_output = attn_output.transpose(0, 2, 1, 3).reshape(seq_length, -1)
+ attn_output = linear_forward(self.proj, attn_output)
+ return attn_output
+
+
+class Glm5NextVisionMLP(nn.Module):
+ def __init__(self, config: VisionConfig) -> None:
+ super().__init__()
+ self.swiglu_limit = config.swiglu_limit
+ self.gate_proj = nn.Linear(
+ config.hidden_size, config.intermediate_size, bias=config.attention_bias
+ )
+ self.up_proj = nn.Linear(
+ config.hidden_size, config.intermediate_size, bias=config.attention_bias
+ )
+ self.down_proj = nn.Linear(
+ config.intermediate_size, config.hidden_size, bias=config.attention_bias
+ )
+
+ def __call__(self, x: mx.array) -> mx.array:
+ gate = linear_forward(self.gate_proj, x)
+ up = linear_forward(self.up_proj, x)
+ if self.swiglu_limit is not None:
+ gate = mx.clip(gate, a_min=None, a_max=self.swiglu_limit)
+ up = mx.clip(up, a_min=-self.swiglu_limit, a_max=self.swiglu_limit)
+ return linear_forward(self.down_proj, nn.silu(gate) * up)
+
+
+class Glm5NextVisionBlock(nn.Module):
+ def __init__(self, config: VisionConfig) -> None:
+ super().__init__()
+ self.norm1 = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.norm2 = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.attn = Glm5NextVisionAttention(config)
+ self.mlp = Glm5NextVisionMLP(config)
+
+ def __call__(
+ self, hidden_states: mx.array, cu_seqlens: mx.array, position_embeddings: tuple
+ ) -> mx.array:
+ hidden_states = hidden_states + self.attn(
+ self.norm1(hidden_states),
+ cu_seqlens=cu_seqlens,
+ position_embeddings=position_embeddings,
+ )
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
+ return hidden_states
+
+
+class VisionModel(nn.Module):
+ def __init__(self, config: VisionConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.model_type = config.model_type
+ self.spatial_merge_size = config.spatial_merge_size
+ self.patch_size = config.patch_size
+
+ self.patch_embed = Glm5NextVisionPatchEmbed(config)
+
+ head_dim = config.hidden_size // config.num_heads
+ self.rotary_pos_emb = Glm5NextVisionRotaryEmbedding(head_dim // 2)
+
+ self.blocks = [Glm5NextVisionBlock(config) for _ in range(config.depth)]
+
+ self.merger = Glm5NextVisionPatchMerger(
+ dim=config.out_hidden_size,
+ context_dim=config.projection_intermediate_size,
+ hidden_act=config.hidden_act,
+ swiglu_limit=config.swiglu_limit,
+ )
+
+ self.downsample = nn.Conv2d(
+ in_channels=config.hidden_size,
+ out_channels=config.out_hidden_size,
+ kernel_size=config.spatial_merge_size,
+ stride=config.spatial_merge_size,
+ bias=True,
+ )
+
+ self.post_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def rot_pos_emb(self, grid_thw: mx.array):
+ pos_ids = []
+
+ for t, h, w in grid_thw.tolist():
+ hpos_ids = mx.expand_dims(mx.arange(h), 1)
+ hpos_ids = mx.repeat(hpos_ids, w, axis=1)
+ hpos_ids = hpos_ids.reshape(
+ h // self.spatial_merge_size,
+ self.spatial_merge_size,
+ w // self.spatial_merge_size,
+ self.spatial_merge_size,
+ )
+ hpos_ids = mx.transpose(hpos_ids, (0, 2, 1, 3))
+ hpos_ids = hpos_ids.flatten()
+
+ wpos_ids = mx.expand_dims(mx.arange(w), 0)
+ wpos_ids = mx.repeat(wpos_ids, h, axis=0)
+ wpos_ids = wpos_ids.reshape(
+ h // self.spatial_merge_size,
+ self.spatial_merge_size,
+ w // self.spatial_merge_size,
+ self.spatial_merge_size,
+ )
+ wpos_ids = mx.transpose(wpos_ids, (0, 2, 1, 3))
+ wpos_ids = wpos_ids.flatten()
+
+ stacked_pos_ids = mx.stack([hpos_ids, wpos_ids], axis=-1)
+ pos_ids.append(mx.tile(stacked_pos_ids, (t, 1)))
+
+ pos_ids = mx.concatenate(pos_ids, axis=0)
+ max_grid_size = mx.max(grid_thw[:, 1:])
+ rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size.item())
+ rotary_pos_emb = rotary_pos_emb_full[pos_ids].reshape(pos_ids.shape[0], -1)
+
+ emb = mx.concatenate((rotary_pos_emb, rotary_pos_emb), axis=-1)
+ return (mx.cos(emb), mx.sin(emb)), pos_ids
+
+ def __call__(
+ self,
+ hidden_states: mx.array,
+ grid_thw: mx.array,
+ output_hidden_states: Optional[bool] = None,
+ ) -> mx.array:
+ hidden_states = self.patch_embed(hidden_states)
+ position_embeddings, _ = self.rot_pos_emb(grid_thw)
+
+ seq_lens = grid_thw[:, 1] * grid_thw[:, 2]
+ repeats = grid_thw[:, 0]
+ repeated_values = []
+ for seq_len, repeat_count in zip(seq_lens.tolist(), repeats.tolist()):
+ repeated_values.extend([seq_len] * repeat_count)
+
+ cu_seqlens = mx.array(repeated_values).cumsum(axis=0)
+ cu_seqlens = mx.pad(cu_seqlens, (1, 0), constant_values=0)
+
+ for blk in self.blocks:
+ hidden_states = blk(
+ hidden_states,
+ cu_seqlens=cu_seqlens,
+ position_embeddings=position_embeddings,
+ )
+
+ hidden_states = self.post_layernorm(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ -1,
+ self.spatial_merge_size,
+ self.spatial_merge_size,
+ hidden_states.shape[-1],
+ )
+ hidden_states = self.downsample(hidden_states).reshape(
+ -1, self.config.out_hidden_size
+ )
+
+ merged_hidden_states = self.merger(hidden_states)
+ return merged_hidden_states
+
+ @staticmethod
+ def sanitize(weights):
+ sanitized_weights = {}
+ for k, v in weights.items():
+ if "position_ids" in k:
+ continue
+ elif "patch_embed.proj.weight" in k or "downsample.weight" in k:
+ if check_array_shape(v):
+ sanitized_weights[k] = v
+ else:
+ if v.ndim == 5:
+ sanitized_weights[k] = v.transpose(0, 2, 3, 4, 1)
+ elif v.ndim == 4:
+ sanitized_weights[k] = v.transpose(0, 2, 3, 1)
+ else:
+ sanitized_weights[k] = v
+ else:
+ sanitized_weights[k] = v
+
+ return sanitized_weights
diff --git a/omlx/patches/mlx_vlm_mlx0322_compat.py b/omlx/patches/mlx_vlm_mlx0322_compat.py
new file mode 100644
index 0000000000..33dc33843d
--- /dev/null
+++ b/omlx/patches/mlx_vlm_mlx0322_compat.py
@@ -0,0 +1,236 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Backport the narrow mlx-vlm changes required by MLX 0.32.2.
+
+The pinned mlx-vlm revision predates upstream PRs #1949, #1982, and #2006.
+MLX 0.32.2 stopped accepting scalar ``mx.array`` objects where Python integer
+dimensions are required and changed ``mx.random.state`` from a mutable list to
+a proxy whose member arrays must be updated in place. Affected models otherwise
+fail in speculative RNG restoration, ``mx.repeat``, shape construction, or
+Metal grid dispatch.
+
+Moving the mlx-vlm pin to any of these merge commits would also import hundreds of
+unrelated upstream changes. Instead, this module installs a source loader for
+the exact affected modules and applies only the upstream integer conversions.
+Each replacement is checked before compilation: an unexpected pinned source
+fails loudly instead of leaving a partially applied compatibility patch.
+"""
+
+from __future__ import annotations
+
+import importlib
+import importlib.abc
+import importlib.machinery
+import inspect
+import logging
+import sys
+from dataclasses import dataclass
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class _Replacement:
+ old: str
+ new: str
+ count: int = 1
+
+
+_REPEAT_GRID = _Replacement(
+ "mx.repeat(seq_len, grid_thw[i, 0])",
+ "mx.repeat(seq_len, int(grid_thw[i, 0]))",
+)
+
+_MODULE_REPLACEMENTS: dict[str, tuple[_Replacement, ...]] = {
+ "mlx_vlm.speculative.common": (
+ _Replacement(
+ "mx.random.state[i] = value",
+ "mx.random.state[i][:] = value",
+ ),
+ ),
+ "mlx_vlm.models.aya_vision.vision": (
+ _Replacement(
+ "height, width = spatial_shapes[i]",
+ "height, width = spatial_shapes[i].tolist()",
+ ),
+ ),
+ "mlx_vlm.models.dots_ocr.vision": (_REPEAT_GRID,),
+ "mlx_vlm.models.glm4v.vision": (
+ _Replacement(
+ "mx.repeat(image_shapes[i, 1], lengths[i])",
+ "mx.repeat(image_shapes[i, 1], int(lengths[i]))",
+ ),
+ _Replacement(
+ "mx.repeat(image_shapes[i, 2], lengths[i])",
+ "mx.repeat(image_shapes[i, 2], int(lengths[i]))",
+ ),
+ ),
+ "mlx_vlm.models.glm4v_moe.vision": (
+ _Replacement(
+ "mx.repeat(image_shapes[i, 1], lengths[i])",
+ "mx.repeat(image_shapes[i, 1], int(lengths[i]))",
+ ),
+ _Replacement(
+ "mx.repeat(image_shapes[i, 2], lengths[i])",
+ "mx.repeat(image_shapes[i, 2], int(lengths[i]))",
+ ),
+ ),
+ "mlx_vlm.models.lfm2_vl.lfm2_vl": (
+ _Replacement(
+ "feature_org_h, feature_org_w = spatial_shapes[img_idx]",
+ "feature_org_h, feature_org_w = (\n"
+ " int(dim) for dim in spatial_shapes[img_idx]\n"
+ " )",
+ ),
+ ),
+ "mlx_vlm.models.paddleocr_vl.vision": (_REPEAT_GRID,),
+ "mlx_vlm.models.qwen2_5_vl.vision": (_REPEAT_GRID,),
+ "mlx_vlm.models.qwen2_vl.vision": (
+ _Replacement(
+ "h, w = int(h), int(w) # Ensure h and w are integers",
+ "t, h, w = int(t), int(h), int(w)",
+ ),
+ _REPEAT_GRID,
+ ),
+ "mlx_vlm.models.qwen3_omni_moe.vision": (_REPEAT_GRID,),
+ "mlx_vlm.models.qwen3_vl.vision": (_REPEAT_GRID,),
+ "mlx_vlm.models.qwen3_vl_moe.vision": (_REPEAT_GRID,),
+ "mlx_vlm.models.kernels": (
+ _Replacement(
+ "import mlx.core as mx",
+ "import math\n\nimport mlx.core as mx",
+ ),
+ _Replacement(
+ "grid=(mx.prod(mx.array(out_shape)), 1, 1)",
+ "grid=(math.prod(out_shape), 1, 1)",
+ ),
+ ),
+}
+
+_INSTALLED = False
+
+
+def _patch_source(fullname: str, source: str) -> str:
+ replacements = _MODULE_REPLACEMENTS[fullname]
+ patched = source
+ for replacement in replacements:
+ # Prefer the already-fixed form first. This matters when ``old`` is a
+ # substring of ``new`` (the kernels.py import insertion), and keeps a
+ # future upstream-fixed pin from receiving the same edit twice.
+ if patched.count(replacement.new) == replacement.count:
+ continue
+ old_count = patched.count(replacement.old)
+ if old_count == replacement.count:
+ patched = patched.replace(
+ replacement.old, replacement.new, replacement.count
+ )
+ continue
+
+ # Any other shape is an explicit pin/patch mismatch.
+ raise ImportError(
+ f"MLX 0.32.2 mlx-vlm compatibility patch mismatch for {fullname}: "
+ f"expected {replacement.count} occurrence(s), found {old_count}"
+ )
+ return patched
+
+
+class _CompatLoader(importlib.abc.Loader):
+ def __init__(self, fullname: str, delegate: importlib.abc.Loader):
+ self.fullname = fullname
+ self.delegate = delegate
+
+ def create_module(self, spec):
+ create_module = getattr(self.delegate, "create_module", None)
+ return create_module(spec) if create_module is not None else None
+
+ def exec_module(self, module) -> None:
+ get_source = getattr(self.delegate, "get_source", None)
+ if get_source is None:
+ raise ImportError(f"source unavailable for {self.fullname}")
+ source = get_source(self.fullname)
+ if source is None:
+ raise ImportError(f"source unavailable for {self.fullname}")
+ filename = getattr(module.__spec__, "origin", None) or self.fullname
+ code = compile(_patch_source(self.fullname, source), filename, "exec")
+ exec(code, module.__dict__)
+
+
+class _CompatFinder(importlib.abc.MetaPathFinder):
+ _omlx_mlx_vlm_mlx0322_compat = True
+
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname not in _MODULE_REPLACEMENTS:
+ return None
+ spec = importlib.machinery.PathFinder.find_spec(fullname, path)
+ if spec is None or spec.loader is None:
+ return None
+ spec.loader = _CompatLoader(fullname, spec.loader)
+ return spec
+
+
+def _reload_and_rebind(fullname: str, module) -> None:
+ """Patch an early import and update mlx-vlm's copied references."""
+ old_objects = {
+ name: value
+ for name, value in vars(module).items()
+ if (inspect.isclass(value) or inspect.isfunction(value))
+ and getattr(value, "__module__", None) == fullname
+ }
+ old_generation_stream = (
+ getattr(module, "generation_stream", None)
+ if fullname == "mlx_vlm.speculative.common"
+ else None
+ )
+ importlib.reload(module)
+ replacements = {
+ old: getattr(module, name)
+ for name, old in old_objects.items()
+ if hasattr(module, name) and getattr(module, name) is not old
+ }
+ new_generation_stream = (
+ getattr(module, "generation_stream", None)
+ if old_generation_stream is not None
+ else None
+ )
+ if not replacements and new_generation_stream is old_generation_stream:
+ return
+ for loaded_name, loaded in list(sys.modules.items()):
+ if loaded is None or not loaded_name.startswith("mlx_vlm."):
+ continue
+ for name, value in list(vars(loaded).items()):
+ if value is old_generation_stream:
+ setattr(loaded, name, new_generation_stream)
+ continue
+ if not (inspect.isclass(value) or inspect.isfunction(value)):
+ continue
+ replacement = replacements.get(value)
+ if replacement is not None:
+ setattr(loaded, name, replacement)
+
+
+def apply_mlx_vlm_mlx0322_compat_patch() -> bool:
+ """Install the MLX 0.32.2 loader before mlx-vlm model imports."""
+ global _INSTALLED
+ if _INSTALLED:
+ return False
+
+ finder = _CompatFinder()
+ sys.meta_path.insert(0, finder)
+
+ # Normal oMLX loading installs this hook before importing a model module.
+ # Reload any target imported by an embedding application earlier so the
+ # process cannot retain the incompatible code silently.
+ try:
+ for fullname in _MODULE_REPLACEMENTS:
+ module = sys.modules.get(fullname)
+ if module is not None:
+ _reload_and_rebind(fullname, module)
+ except Exception:
+ sys.meta_path.remove(finder)
+ raise
+
+ _INSTALLED = True
+ logger.info("mlx-vlm MLX 0.32.2 compatibility patch installed")
+ return True
+
+
+__all__ = ["apply_mlx_vlm_mlx0322_compat_patch"]
diff --git a/omlx/patches/mlx_vlm_mtp/gemma4_vlm_runtime.py b/omlx/patches/mlx_vlm_mtp/gemma4_vlm_runtime.py
index 2723f7f543..ca90f09ef6 100644
--- a/omlx/patches/mlx_vlm_mtp/gemma4_vlm_runtime.py
+++ b/omlx/patches/mlx_vlm_mtp/gemma4_vlm_runtime.py
@@ -81,9 +81,9 @@ def apply() -> bool:
_patch_vlm_model_adapter()
- # Small-L verify forwards otherwise pay gemma4's unfused multi-token
- # attention (head_dim 256/512 has no fused SDPA above L=1); the
- # decomposed route keeps shallow-depth speculation profitable.
+ # MLX 0.32.2 covers Gemma4's head-dim-256 small-L shapes natively. Global
+ # head-dim-512 verify still needs the custom fused route to keep
+ # shallow-depth speculation profitable.
from ..gemma4_verify_attention import apply as apply_verify_attention
apply_verify_attention()
diff --git a/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py b/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py
index 0130170a30..83687c07c8 100644
--- a/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py
+++ b/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py
@@ -273,6 +273,12 @@ def __init__(self, args, config=None):
from . import is_mtp_attach_enabled
from ..mlx_lm_mtp import is_mtp_active
+ if type(self) is not cls:
+ # Subclasses (e.g. the qwen4_exp vendor LanguageModel, which
+ # inherits from this class) own their MTP wiring; running the
+ # Qwen3.5 attach here would bolt a q35 MTPModule onto a
+ # foreign architecture (issue #2972, reverse leg).
+ return original_init(self, args, config)
original_init(self, args, config)
# Attach MTPModule when the config declares MTP heads so mlx-vlm's
# load_weights (which skips Model.sanitize for is_mlx_format
@@ -314,6 +320,12 @@ def __call__(self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs):
is accepted and discarded — the mlx-vlm path uses post-hoc
``rollback_speculative_cache`` instead of a confirmed/draft split.
"""
+ if type(self) is not cls:
+ # Subclasses (qwen4_exp vendor) reach here via super().__call__
+ # and implement their own return_hidden / capture contract.
+ # Reshaping their kwargs here collapses the raw hyper-stream
+ # hidden that Qwen4 Lightning MTP requires (issue #2972).
+ return original_call(self, inputs, inputs_embeds, mask, cache, **kwargs)
return_hidden = kwargs.pop("return_hidden", False)
return_shared_kv = kwargs.pop("return_shared_kv", False)
kwargs.pop("n_confirmed", None)
diff --git a/omlx/patches/mlx_vlm_mtp/qwen38_fp8.py b/omlx/patches/mlx_vlm_mtp/qwen38_fp8.py
index 1deb0ea8dd..9dcc45329f 100644
--- a/omlx/patches/mlx_vlm_mtp/qwen38_fp8.py
+++ b/omlx/patches/mlx_vlm_mtp/qwen38_fp8.py
@@ -13,9 +13,11 @@
def dequantize_fp8_weights(
weights: dict[str, Any],
dtype: Any = mx.bfloat16,
+ *,
+ copy_weights: bool = True,
) -> dict[str, Any]:
"""Expand Qwen3.8 block-FP8 tensors using their inverse-scale grids."""
- weights = dict(weights)
+ weights = dict(weights) if copy_weights else weights
scale_suffix = ".weight_scale_inv"
for scale_key in [key for key in weights if key.endswith(scale_suffix)]:
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py
new file mode 100644
index 0000000000..f6a9932dc3
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py
@@ -0,0 +1,98 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Register the vendored Qwen4-Exp implementation with mlx-vlm."""
+
+from __future__ import annotations
+
+import importlib
+import logging
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+_VENDOR_MLX_VLM = Path(__file__).resolve().parent / "vendor" / "mlx_vlm"
+_APPLIED = False
+
+
+def _append_package_path(package: Any, path: Path) -> None:
+ package_path = getattr(package, "__path__", None)
+ if package_path is None:
+ return
+ path_string = str(path)
+ if path_string not in package_path:
+ package_path.append(path_string)
+
+
+def apply_mlx_vlm_qwen4_exp_compat_patch() -> bool:
+ """Expose ``mlx_vlm.models.qwen4_exp`` from oMLX's vendor tree."""
+ global _APPLIED
+ if _APPLIED:
+ return False
+
+ try:
+ import mlx_vlm
+ import mlx_vlm.models
+
+ _append_package_path(mlx_vlm, _VENDOR_MLX_VLM)
+ _append_package_path(mlx_vlm.models, _VENDOR_MLX_VLM / "models")
+ importlib.import_module("mlx_vlm.models.qwen4_exp")
+ _patch_prompt_utils()
+ except Exception as exc: # noqa: BLE001
+ logger.debug("Qwen4-Exp mlx-vlm registration failed: %s", exc)
+ return False
+
+ _APPLIED = True
+ logger.info("Qwen4-Exp mlx-vlm compatibility patch applied")
+ return True
+
+
+def _patch_prompt_utils() -> None:
+ """Teach the pinned formatter Qwen4's Qwen3.5-compatible media layout."""
+ import mlx_vlm.prompt_utils as prompt_utils
+
+ current = prompt_utils.get_message_json
+ if getattr(current, "_omlx_qwen4_exp", False):
+ return
+
+ def get_message_json(model_type, *args, **kwargs):
+ if model_type == "qwen4_exp":
+ model_type = "qwen3_5_moe"
+ return current(model_type, *args, **kwargs)
+
+ get_message_json._omlx_qwen4_exp = True
+ prompt_utils.get_message_json = get_message_json
+
+
+def is_applied() -> bool:
+ return _APPLIED
+
+
+def configure_qwen4_exp_runtime(
+ model_path: str | Path,
+ mode: str | None = None,
+ *,
+ mtp_enabled: bool = False,
+) -> str:
+ """Select PLE storage and optional Lightning MTP before construction."""
+ apply_mlx_vlm_qwen4_exp_compat_patch()
+ from mlx_vlm.models.qwen4_exp.language import (
+ configure_mtp_runtime,
+ configure_ple_runtime,
+ )
+
+ resolved = configure_ple_runtime(model_path, mode=mode)
+ mtp_runtime = configure_mtp_runtime(model_path, enabled=mtp_enabled)
+ logger.info("Qwen4-Exp PLE mode for %s: %s", model_path, resolved)
+ if mtp_enabled and not mtp_runtime.enabled:
+ logger.warning(
+ "Qwen4-Exp Lightning MTP was requested for %s, but no embedded "
+ "MTP tensors were found",
+ model_path,
+ )
+ elif mtp_runtime.enabled:
+ logger.info(
+ "Qwen4-Exp Lightning MTP enabled for %s (checkpoint layout: %s)",
+ model_path,
+ mtp_runtime.checkpoint_prefix,
+ )
+ return resolved
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py
new file mode 100644
index 0000000000..c2bf1274be
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py
@@ -0,0 +1,115 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Qwen4-Exp PLE storage estimates shared by runtime and settings UIs."""
+
+from __future__ import annotations
+
+import json
+import struct
+from dataclasses import dataclass
+from functools import lru_cache
+from pathlib import Path
+
+_MODEL_OVERHEAD_FACTOR = 1.05
+_NGRAM_EMBEDDING_MARKER = ".ngram_embedding."
+
+
+@dataclass(frozen=True)
+class Qwen4ExpResidencyEstimate:
+ """Estimated resident bytes with and without the PLE embedding table."""
+
+ supported: bool
+ checkpoint_bytes: int
+ ple_bytes: int
+ resident_bytes: int
+ mmap_bytes: int
+
+ def force_ssd_offload(self, memory_ceiling: int) -> bool:
+ """Return True only when mmap turns an otherwise impossible load viable."""
+
+ return (
+ self.supported
+ and memory_ceiling > 0
+ and self.resident_bytes > memory_ceiling
+ and self.mmap_bytes <= memory_ceiling
+ )
+
+
+def _safetensors_header(path: Path) -> dict:
+ with path.open("rb") as file:
+ raw_size = file.read(8)
+ if len(raw_size) != 8:
+ return {}
+ header_size = struct.unpack(" tuple[int, bool]:
+ index_path = ple_path / "model.safetensors.index.json"
+ if not index_path.is_file():
+ return 0, False
+ try:
+ weight_map = json.loads(index_path.read_text()).get("weight_map") or {}
+ except (OSError, ValueError):
+ return 0, False
+
+ selected: dict[str, list[str]] = {}
+ for key, filename in weight_map.items():
+ if _NGRAM_EMBEDDING_MARKER in key:
+ selected.setdefault(filename, []).append(key)
+ if not selected:
+ return 0, False
+
+ total = 0
+ try:
+ for filename, keys in selected.items():
+ header = _safetensors_header(ple_path / filename)
+ for key in keys:
+ start, end = header[key]["data_offsets"]
+ total += int(end) - int(start)
+ except (KeyError, OSError, TypeError, ValueError):
+ return 0, False
+ return total, total > 0
+
+
+@lru_cache(maxsize=128)
+def _cached_residency_estimate(
+ ple_path_string: str,
+ checkpoint_signature: tuple[tuple[str, int, int], ...],
+ _index_signature: tuple[int, int] | None,
+) -> Qwen4ExpResidencyEstimate:
+ ple_path = Path(ple_path_string)
+ checkpoint_bytes = sum(size for _, size, _ in checkpoint_signature)
+ ple_bytes, supported = _ple_tensor_bytes(ple_path)
+ resident_bytes = int(checkpoint_bytes * _MODEL_OVERHEAD_FACTOR)
+ mmap_bytes = int(max(0, checkpoint_bytes - ple_bytes) * _MODEL_OVERHEAD_FACTOR)
+ return Qwen4ExpResidencyEstimate(
+ supported=supported,
+ checkpoint_bytes=checkpoint_bytes,
+ ple_bytes=ple_bytes,
+ resident_bytes=resident_bytes,
+ mmap_bytes=mmap_bytes,
+ )
+
+
+def qwen4_exp_residency_estimate(
+ model_path: str | Path,
+) -> Qwen4ExpResidencyEstimate:
+ """Inspect Qwen4 checkpoint headers without materializing tensor data."""
+
+ ple_path = Path(model_path).expanduser().resolve()
+ checkpoint_files = {path.resolve() for path in ple_path.glob("*.safetensors")}
+ signature = tuple(
+ sorted(
+ (str(path), stat.st_size, stat.st_mtime_ns)
+ for path in checkpoint_files
+ for stat in (path.stat(),)
+ )
+ )
+ index_path = ple_path / "model.safetensors.index.json"
+ index_stat = index_path.stat() if index_path.is_file() else None
+ index_signature = (
+ (index_stat.st_size, index_stat.st_mtime_ns)
+ if index_stat is not None
+ else None
+ )
+ return _cached_residency_estimate(str(ple_path), signature, index_signature)
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/__init__.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/__init__.py
new file mode 100644
index 0000000000..90ea2eae64
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/__init__.py
@@ -0,0 +1 @@
+"""Vendored dependency namespace."""
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/__init__.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/__init__.py
new file mode 100644
index 0000000000..7cc6358c41
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/__init__.py
@@ -0,0 +1 @@
+"""Vendored mlx-vlm extensions."""
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/__init__.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/__init__.py
new file mode 100644
index 0000000000..e8d02c18a0
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/__init__.py
@@ -0,0 +1 @@
+"""Vendored mlx-vlm model extensions."""
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/__init__.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/__init__.py
new file mode 100644
index 0000000000..b0e3d76788
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/__init__.py
@@ -0,0 +1,17 @@
+from ..base import install_auto_processor_patch
+from ..qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor
+from .config import ModelConfig, TextConfig, VisionConfig
+from .language import LanguageModel
+from .qwen4_exp import Model
+from .vision import VisionModel
+
+install_auto_processor_patch("qwen4_exp", Qwen3VLProcessor)
+
+__all__ = [
+ "LanguageModel",
+ "Model",
+ "ModelConfig",
+ "TextConfig",
+ "VisionConfig",
+ "VisionModel",
+]
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/cache.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/cache.py
new file mode 100644
index 0000000000..7e12a2e32d
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/cache.py
@@ -0,0 +1,2826 @@
+from typing import Any, Dict, List, Optional, Tuple
+
+import mlx.core as mx
+import mlx.nn as nn
+from mlx.utils import tree_flatten, tree_map, tree_reduce, tree_unflatten
+
+
+def should_quantize_kv_layer(layer_idx: int, num_layers: int) -> bool:
+ """Whether layer ``layer_idx`` should use a quantized KV cache.
+
+ Live batch generation (``_make_cache``), stream quantize, and APC warm
+ restore must share this policy so continuous-batching ``extend`` always
+ joins same-typed peers.
+
+ For deep stacks (``num_layers > 2``) the last full-attention layer stays
+ unquantized — it is sensitive to quantization (see gemma-4-class models).
+ Shallow stacks (``num_layers <= 2``) quantize every layer when kv-bits is on.
+ """
+ if num_layers <= 2:
+ return True
+ return layer_idx < num_layers - 1
+
+
+def create_causal_mask(
+ N: int,
+ offset: int = 0,
+ window_size: Optional[int] = None,
+ right_padding: Optional[mx.array] = None,
+ left_padding: Optional[mx.array] = None,
+):
+ rinds = mx.arange(offset + N)
+ linds = mx.arange(offset, offset + N) if offset else rinds
+ linds = linds[:, None]
+ rinds = rinds[None]
+ mask = linds >= rinds
+ if window_size is not None:
+ mask = mask & (linds < rinds + window_size)
+ if right_padding is not None:
+ mask = mask & (rinds < mx.expand_dims((offset + N) - right_padding, (1, 2, 3)))
+ if left_padding is not None:
+ mask = mask & (mx.expand_dims(left_padding, (1, 2, 3)) <= rinds)
+ return mask
+
+
+def make_prompt_cache(
+ model: nn.Module,
+ max_kv_size: Optional[int] = None,
+) -> List[Any]:
+ """
+ Construct the model's cache for use in generation.
+
+ This function will defer the cache construction to the model if it has a
+ ``make_cache`` method, otherwise it will make a default KV cache.
+
+ Args:
+ model (nn.Module): The language model.
+ max_kv_size (Optional[int]): If provided and the model does not have a
+ ``make_cache`` method, a ``RotatingKVCache`` is used with a maximum
+ size of ``max_kv_size``
+ """
+ if hasattr(model, "make_cache"):
+ return model.make_cache()
+
+ num_layers = len(model.layers)
+ if max_kv_size is not None:
+ return [
+ RotatingKVCache(max_size=max_kv_size, keep=4) for _ in range(num_layers)
+ ]
+ else:
+ return [KVCache() for _ in range(num_layers)]
+
+
+def create_attention_mask(
+ N: int, offset: int, return_array: bool, window_size: Optional[int]
+):
+ if window_size is not None:
+ return create_causal_mask(N, offset, window_size=window_size)
+ elif N == 1:
+ return None
+ elif return_array:
+ return create_causal_mask(N, offset, window_size=window_size)
+ else:
+ return "causal"
+
+
+class _BaseCache:
+ @property
+ def state(self):
+ return []
+
+ @state.setter
+ def state(self, v):
+ if v is not None and v:
+ raise ValueError("This cache has no state but a state was set.")
+
+ @property
+ def meta_state(self):
+ return ""
+
+ @meta_state.setter
+ def meta_state(self, v):
+ if v is not None and v:
+ raise ValueError("This cache has no meta_state but a meta_state was set.")
+
+ def is_trimmable(self):
+ return False
+
+ def size(self):
+ """
+ Return the size (i.e. sequence length) of the cache.
+
+ Not every cache is required to implement this, in which case the size
+ will always be 0 (though the cache may not be empty).
+ """
+ return 0
+
+ @property
+ def nbytes(self):
+ """Return the size of this cache in bytes"""
+ raise NotImplementedError("Cache sub-class must implement nbytes")
+
+ def empty(self):
+ """
+ Return if the cache is empty or not.
+ """
+ raise NotImplementedError("Cache sub-class must implement this.")
+
+ @classmethod
+ def from_state(cls, state, meta_state):
+ # Create an instance of cls without calling __init__
+ obj = cls.__new__(cls)
+ obj.state = state
+ obj.meta_state = meta_state
+ return obj
+
+ def prefix_cache_snapshot(self):
+ """Return an opaque, restorable snapshot of this cache's state.
+
+ The returned object must round-trip through ``prefix_cache_restore``
+ into a fresh cache from ``model.make_cache()``. References are returned
+ as-is; the caller (adapter) is responsible for any detaching copy.
+ """
+ return {"state": self.state, "meta_state": self.meta_state}
+
+ def prefix_cache_restore(self, snapshot):
+ """Restore a snapshot from :meth:`prefix_cache_snapshot` into ``self``."""
+ self.state = snapshot["state"]
+ self.meta_state = snapshot["meta_state"]
+
+ def prefix_cache_merge(self, rows, prefix_lens):
+ """Merge single-row snapshots into a batched cache, or ``None``.
+
+ Default: not batch-mergeable. Pageable/windowed caches override to
+ return a batched cache built from ``rows``.
+ """
+ return None
+
+
+class ConcatenateKVCache(_BaseCache):
+ def __init__(self):
+ self.keys = None
+ self.values = None
+ self.offset = 0
+
+ def update_and_fetch(self, keys, values):
+ if self.keys is None:
+ self.keys = keys
+ self.values = values
+ else:
+ self.keys = mx.concatenate([self.keys, keys], axis=-2)
+ self.values = mx.concatenate([self.values, values], axis=-2)
+ self.offset = self.keys.shape[-2]
+ return self.keys, self.values
+
+ @property
+ def state(self):
+ return self.keys, self.values
+
+ @state.setter
+ def state(self, value):
+ self.keys, self.values = value
+ self.offset = 0 if self.keys is None else self.keys.shape[-2]
+
+ def is_trimmable(self):
+ return True
+
+ def trim(self, n):
+ n = min(self.offset, n)
+ self.offset -= n
+ if self.keys is not None:
+ self.keys = self.keys[..., : self.offset, :]
+ self.values = self.values[..., : self.offset, :]
+ return n
+
+ def make_mask(self, *args, **kwargs):
+ return create_attention_mask(*args, offset=self.offset, **kwargs)
+
+ def empty(self):
+ return self.keys is None
+
+ @property
+ def nbytes(self):
+ if self.keys is None:
+ return 0
+ return self.keys.nbytes + self.values.nbytes
+
+
+def _dequantize_uniform(keys_tuple, values_tuple, length, group_size, bits):
+ """Dequantize uniform-quantized K/V tuples to raw float arrays.
+
+ Shared by QuantizedKVCache and BatchQuantizedKVCache for APC storage.
+ Returns None, None if the cache is empty.
+ """
+ if keys_tuple is None or values_tuple is None or length == 0:
+ return None, None
+ keys = mx.dequantize(
+ mx.contiguous(keys_tuple[0][..., :length, :]),
+ mx.contiguous(keys_tuple[1][..., :length, :]),
+ mx.contiguous(keys_tuple[2][..., :length, :]),
+ group_size=group_size,
+ bits=bits,
+ )
+ values = mx.dequantize(
+ mx.contiguous(values_tuple[0][..., :length, :]),
+ mx.contiguous(values_tuple[1][..., :length, :]),
+ mx.contiguous(values_tuple[2][..., :length, :]),
+ group_size=group_size,
+ bits=bits,
+ )
+ return keys, values
+
+
+class QuantizedKVCache(_BaseCache):
+ step = 256
+ geometric_growth = False
+
+ def __init__(self, group_size: int = 64, bits: int = 8):
+ self.keys = None
+ self.values = None
+ self.offset = 0
+ self.group_size = group_size
+ self.bits = bits
+ self._geometric_capacity_managed = True
+
+ def update_and_fetch(self, keys, values):
+ B, n_kv_heads, num_steps, k_head_dim = keys.shape
+ v_head_dim = values.shape[-1]
+ prev = self.offset
+
+ if self.keys is None or (prev + num_steps) > self.keys[0].shape[-2]:
+ el_per_int = 8 * mx.uint32.size // self.bits
+ if self.geometric_growth:
+ old_capacity = 0 if self.keys is None else self.keys[0].shape[-2]
+ needed = prev + num_steps
+ capacity = ((needed + self.step - 1) // self.step) * self.step
+ if old_capacity and self._geometric_capacity_managed:
+ capacity = max(capacity, 2 * old_capacity)
+ shape = (B, n_kv_heads, capacity)
+ else:
+ new_steps = (self.step + num_steps - 1) // self.step * self.step
+ shape = (B, n_kv_heads, new_steps)
+
+ def init_quant(dim):
+ return (
+ mx.zeros((*shape, dim // el_per_int), dtype=mx.uint32),
+ mx.zeros((*shape, dim // self.group_size), dtype=keys.dtype),
+ mx.zeros((*shape, dim // self.group_size), dtype=keys.dtype),
+ )
+
+ def expand_quant(x):
+ if self.geometric_growth:
+ new_x = mx.zeros((*shape, x.shape[-1]), dtype=x.dtype)
+ new_x[..., :prev, :] = x[..., :prev, :]
+ return new_x
+ new_x = mx.zeros((*shape, x.shape[-1]), dtype=x.dtype)
+ return mx.concatenate([x, new_x], axis=-2)
+
+ if self.keys is not None:
+ if prev % self.step != 0:
+ self.keys, self.values = tree_map(
+ lambda x: x[..., :prev, :], (self.keys, self.values)
+ )
+
+ self.keys, self.values = tree_map(
+ expand_quant, (self.keys, self.values)
+ )
+ else:
+ self.keys, self.values = init_quant(k_head_dim), init_quant(v_head_dim)
+ if self.geometric_growth:
+ self._geometric_capacity_managed = True
+
+ self.offset += num_steps
+
+ keys = mx.quantize(keys, group_size=self.group_size, bits=self.bits)
+ values = mx.quantize(values, group_size=self.group_size, bits=self.bits)
+ for i in range(len(self.keys)):
+ self.keys[i][..., prev : self.offset, :] = keys[i]
+ self.values[i][..., prev : self.offset, :] = values[i]
+
+ return tree_map(lambda x: x[..., : self.offset, :], (self.keys, self.values))
+
+ @property
+ def state(self):
+ if self.offset == self.keys[0].shape[2]:
+ return self.keys, self.values
+ else:
+ return tree_map(
+ lambda x: x[..., : self.offset, :], (self.keys, self.values)
+ )
+
+ @state.setter
+ def state(self, v):
+ self.keys, self.values = v
+ self._geometric_capacity_managed = False
+
+ @property
+ def meta_state(self):
+ return tuple(map(str, (self.offset, self.group_size, self.bits)))
+
+ @meta_state.setter
+ def meta_state(self, v):
+ self.offset, self.group_size, self.bits = map(int, v)
+
+ def is_trimmable(self):
+ return True
+
+ def trim(self, n):
+ n = min(self.offset, n)
+ self.offset -= n
+ return n
+
+ def dequantize_for_apc(self):
+ """Return raw float (keys, values) sliced to current offset for APC storage.
+
+ Returns (None, None) if the cache is empty.
+ """
+ if self.keys is None or self.offset == 0:
+ return None, None
+ return _dequantize_uniform(
+ self.keys, self.values, self.offset, self.group_size, self.bits
+ )
+
+ def make_mask(self, *args, **kwargs):
+ return create_attention_mask(*args, offset=self.offset, **kwargs)
+
+ def empty(self):
+ return self.keys is None
+
+ @property
+ def nbytes(self):
+ return tree_reduce(lambda a, x: a + x.nbytes, (self.keys, self.values), 0)
+
+
+class KVCache(_BaseCache):
+ step = 256
+ geometric_growth = False
+
+ def __init__(self):
+ self.keys = None
+ self.values = None
+ self.offset = 0
+ self._geometric_capacity_managed = True
+
+ def update_and_fetch(self, keys, values):
+ prev = self.offset
+ if self.keys is None or (prev + keys.shape[2]) > self.keys.shape[2]:
+ B, n_kv_heads, _, k_head_dim = keys.shape
+ v_head_dim = values.shape[3]
+ if self.geometric_growth:
+ old_capacity = 0 if self.keys is None else self.keys.shape[2]
+ needed = prev + keys.shape[2]
+ capacity = ((needed + self.step - 1) // self.step) * self.step
+ if old_capacity and self._geometric_capacity_managed:
+ capacity = max(capacity, 2 * old_capacity)
+ else:
+ n_steps = (self.step + keys.shape[2] - 1) // self.step
+ capacity = n_steps * self.step
+ k_shape = (B, n_kv_heads, capacity, k_head_dim)
+ v_shape = (B, n_kv_heads, capacity, v_head_dim)
+ new_k = mx.zeros(k_shape, keys.dtype)
+ new_v = mx.zeros(v_shape, values.dtype)
+ if self.keys is not None:
+ if self.geometric_growth:
+ new_k[..., :prev, :] = self.keys[..., :prev, :]
+ new_v[..., :prev, :] = self.values[..., :prev, :]
+ self.keys, self.values = new_k, new_v
+ else:
+ if prev % self.step != 0:
+ self.keys = self.keys[..., :prev, :]
+ self.values = self.values[..., :prev, :]
+ self.keys = mx.concatenate([self.keys, new_k], axis=2)
+ self.values = mx.concatenate([self.values, new_v], axis=2)
+ else:
+ self.keys, self.values = new_k, new_v
+ if self.geometric_growth:
+ self._geometric_capacity_managed = True
+
+ self.offset += keys.shape[2]
+ self.keys[..., prev : self.offset, :] = keys
+ self.values[..., prev : self.offset, :] = values
+ return self.keys[..., : self.offset, :], self.values[..., : self.offset, :]
+
+ def size(self):
+ return self.offset
+
+ @property
+ def state(self):
+ if self.offset == self.keys.shape[2]:
+ return self.keys, self.values
+ else:
+ return (
+ self.keys[..., : self.offset, :],
+ self.values[..., : self.offset, :],
+ )
+
+ @state.setter
+ def state(self, v):
+ self.keys, self.values = v
+ self.offset = self.keys.shape[2]
+ self._geometric_capacity_managed = False
+
+ def is_trimmable(self):
+ return True
+
+ def trim(self, n):
+ n = min(self.offset, n)
+ self.offset -= n
+ return n
+
+ def extract(self, idx):
+ cache = KVCache()
+ if self.keys is None:
+ if idx not in (0, -1):
+ raise IndexError("KVCache row index out of range")
+ return cache
+
+ batch_size = int(self.keys.shape[0])
+ if idx < 0:
+ idx += batch_size
+ if idx < 0 or idx >= batch_size:
+ raise IndexError(
+ f"KVCache row index {idx} out of range for batch size {batch_size}"
+ )
+
+ cache.keys = mx.contiguous(self.keys[idx : idx + 1, :, : self.offset, :])
+ cache.values = mx.contiguous(self.values[idx : idx + 1, :, : self.offset, :])
+ cache.offset = self.offset
+ return cache
+
+ def to_quantized(self, group_size: int = 64, bits: int = 4) -> QuantizedKVCache:
+ quant_cache = QuantizedKVCache(group_size=group_size, bits=bits)
+ quant_cache.offset = self.offset
+ if self.keys is not None:
+ quant_cache.keys = mx.quantize(self.keys, group_size=group_size, bits=bits)
+ quant_cache.values = mx.quantize(
+ self.values, group_size=group_size, bits=bits
+ )
+ return quant_cache
+
+ def make_mask(self, *args, **kwargs):
+ return create_attention_mask(*args, offset=self.offset, **kwargs)
+
+ @classmethod
+ def merge(_, caches):
+ return BatchKVCache.merge(caches)
+
+ def empty(self):
+ return self.keys is None
+
+ @property
+ def nbytes(self):
+ if self.keys is None:
+ return 0
+ return self.keys.nbytes + self.values.nbytes
+
+
+class RotatingKVCache(_BaseCache):
+ step = 256
+
+ def __init__(self, max_size, keep=0):
+ self.keep = keep
+ self.keys = None
+ self.values = None
+ self.offset = 0
+ self.max_size = max_size
+ self._idx = 0
+
+ def _trim(self, trim_size, v, append=None):
+ to_cat = []
+ if trim_size > 0:
+ to_cat = [v[..., : self.keep, :], v[..., trim_size + self.keep :, :]]
+ else:
+ to_cat = [v]
+ if append is not None:
+ to_cat.append(append)
+ return mx.concatenate(to_cat, axis=2)
+
+ def _temporal_order(self, v):
+ """
+ Rearrange the cache into temporal order, slicing off the end if unused.
+ """
+ if self._idx == v.shape[2]:
+ return v
+ elif self._idx < self.offset:
+ return mx.concatenate(
+ [
+ v[..., : self.keep, :],
+ v[..., self._idx :, :],
+ v[..., self.keep : self._idx, :],
+ ],
+ axis=2,
+ )
+ else:
+ return v[..., : self._idx, :]
+
+ def _update_concat(self, keys, values):
+ if self.keys is None:
+ self.keys = keys
+ self.values = values
+ else:
+ # Put the keys/values in temporal order to
+ # preserve context
+ self.keys = self._temporal_order(self.keys)
+ self.values = self._temporal_order(self.values)
+ self._idx = self.keys.shape[2]
+
+ # The largest size is self.max_size + S - 1 to ensure
+ # every token gets at least self.max_size context
+ trim_size = self._idx - self.max_size + 1
+ self.keys = self._trim(trim_size, self.keys, keys)
+ self.values = self._trim(trim_size, self.values, values)
+ self.offset += keys.shape[2]
+ self._idx = self.keys.shape[2]
+ return self.keys, self.values
+
+ def _update_in_place(self, keys, values):
+ # May not have hit the max size yet, so potentially
+ # keep growing the cache
+ B, n_kv_heads, S, k_head_dim = keys.shape
+ prev = self.offset
+ if self.keys is None or (
+ prev >= self.keys.shape[2] and self.keys.shape[2] < self.max_size
+ ):
+ v_head_dim = values.shape[3]
+ new_size = min(self.step, self.max_size - prev)
+ k_shape = (B, n_kv_heads, new_size, k_head_dim)
+ v_shape = (B, n_kv_heads, new_size, v_head_dim)
+ new_k = mx.zeros(k_shape, keys.dtype)
+ new_v = mx.zeros(v_shape, values.dtype)
+ if self.keys is not None:
+ self.keys = mx.concatenate([self.keys, new_k], axis=2)
+ self.values = mx.concatenate([self.values, new_v], axis=2)
+ else:
+ self.keys, self.values = new_k, new_v
+ self._idx = prev
+
+ # Trim if needed
+ trim_size = self.keys.shape[2] - self.max_size
+ if trim_size > 0:
+ self.keys = self._trim(trim_size, self.keys)
+ self.values = self._trim(trim_size, self.values)
+ self._idx = self.max_size
+
+ # Rotate
+ if self._idx == self.max_size:
+ self._idx = self.keep
+
+ # Assign
+ self.keys[..., self._idx : self._idx + S, :] = keys
+ self.values[..., self._idx : self._idx + S, :] = values
+ self.offset += S
+ self._idx += S
+
+ # If the buffer is not full, slice off the end
+ if self.offset < self.max_size:
+ return self.keys[..., : self.offset, :], self.values[..., : self.offset, :]
+ return self.keys, self.values
+
+ def update_and_fetch(self, keys, values):
+ if keys.shape[2] == 1:
+ return self._update_in_place(keys, values)
+ return self._update_concat(keys, values)
+
+ def size(self):
+ return min(self.offset, self.max_size)
+
+ @property
+ def state(self):
+ if self.offset < self.keys.shape[2]:
+ return self.keys[..., : self.offset, :], self.values[..., : self.offset, :]
+ else:
+ return self.keys, self.values
+
+ @state.setter
+ def state(self, v):
+ self.keys, self.values = v
+
+ @property
+ def meta_state(self):
+ return tuple(map(str, (self.keep, self.max_size, self.offset, self._idx)))
+
+ @meta_state.setter
+ def meta_state(self, v):
+ self.keep, self.max_size, self.offset, self._idx = map(
+ int,
+ v,
+ )
+
+ def is_trimmable(self):
+ return self.offset < self.max_size
+
+ def trim(self, n):
+ n = min(self.offset, n)
+ self.offset -= n
+ self._idx -= n
+ return n
+
+ def to_quantized(self, group_size: int = 64, bits: int = 4) -> QuantizedKVCache:
+ raise NotImplementedError("RotatingKVCache Quantization NYI")
+
+ def make_mask(
+ self, N: int, window_size: Optional[int] = None, return_array: bool = False
+ ):
+ if N > 1:
+ window_size = window_size or self.max_size
+ offset = min(self.max_size - 1, self.offset)
+ if offset + N > window_size or return_array:
+ return create_causal_mask(N, offset, window_size=window_size)
+ else:
+ return "causal"
+ else:
+ if window_size is None:
+ return None
+ # May need a mask for when window_size < max_size
+ if self.offset >= window_size and self.max_size > window_size:
+ idx = self._idx
+ if idx >= self.max_size:
+ idx = 0
+ if self.offset < self.max_size:
+ mask_size = self.offset + 1
+ else:
+ mask_size = self.max_size
+ mask = mx.arange(mask_size) >= (mask_size - window_size)
+ mask = mx.roll(mask, shift=idx + 1)
+ return mask
+
+ @classmethod
+ def merge(_, caches):
+ return BatchRotatingKVCache.merge(caches)
+
+ def empty(self):
+ return self.keys is None
+
+ @property
+ def nbytes(self):
+ if self.keys is None:
+ return 0
+ return self.keys.nbytes + self.values.nbytes
+
+
+class ArraysCache(_BaseCache):
+ def __new__(cls, *args, **kwargs):
+ instance = super().__new__(cls)
+ instance._left_padding = None
+ instance._left_padding_advance = 0
+ instance._lengths = None
+ instance._lengths_advance = 0
+ return instance
+
+ def __init__(self, size, left_padding: Optional[List[int]] = None):
+ self.cache = [None] * size
+ if left_padding:
+ self.left_padding = mx.array(left_padding)
+
+ @property
+ def left_padding(self):
+ if self._left_padding is None:
+ return None
+ if self._left_padding_advance == 0:
+ return self._left_padding
+ return self._left_padding - self._left_padding_advance
+
+ @left_padding.setter
+ def left_padding(self, value):
+ self._left_padding = value
+ self._left_padding_advance = 0
+
+ @property
+ def lengths(self):
+ if self._lengths is None:
+ return None
+ if self._lengths_advance == 0:
+ return self._lengths
+ return self._lengths - self._lengths_advance
+
+ @lengths.setter
+ def lengths(self, value):
+ self._lengths = value
+ self._lengths_advance = 0
+
+ @property
+ def batch_size(self):
+ for c in self.cache:
+ if c is not None:
+ return c.shape[0]
+ if self._left_padding is not None:
+ return self._left_padding.size
+ elif self._lengths is not None:
+ return self._lengths.size
+ else:
+ return 1
+
+ def __setitem__(self, idx, value):
+ self.cache[idx] = value
+
+ def __getitem__(self, idx):
+ return self.cache[idx]
+
+ @property
+ def state(self):
+ return self.cache
+
+ @state.setter
+ def state(self, v):
+ self.cache = v
+
+ def filter(self, batch_indices):
+ """
+ In-place filter to keep just the given indices in the cache.
+ """
+ self.cache = [c[batch_indices] if c is not None else None for c in self.cache]
+ if self.left_padding is not None:
+ self.left_padding = self.left_padding[batch_indices]
+ if self.lengths is not None:
+ self.lengths = self.lengths[batch_indices]
+
+ def extend(self, other):
+ """
+ In-place extend this cache with the other cache.
+ """
+
+ a_batch = self.batch_size
+ b_batch = other.batch_size
+
+ def cat(a, b):
+ shape = dtype = None
+ if a is not None:
+ shape = a.shape
+ dtype = a.dtype
+ if b is not None:
+ shape = b.shape
+ dtype = b.dtype
+
+ if shape is None:
+ return None
+
+ if a is None:
+ a = mx.zeros((a_batch,) + shape[1:], dtype=dtype)
+ if b is None:
+ b = mx.zeros((b_batch,) + shape[1:], dtype=dtype)
+
+ return mx.concatenate([a, b])
+
+ self.cache = [cat(c, o) for c, o in zip(self.cache, other.cache)]
+ self.left_padding = cat(self.left_padding, other.left_padding)
+ self.lengths = cat(self.lengths, other.lengths)
+
+ def extract(self, idx):
+ cache = ArraysCache(len(self.cache))
+ cache.cache = [c[idx : idx + 1] for c in self.cache]
+ return cache
+
+ def prepare(self, lengths=None, **kwargs):
+ self.lengths = mx.array(lengths)
+
+ def finalize(self):
+ self.lengths = None
+ self.left_padding = None
+
+ def advance(self, N):
+ if self._lengths is not None:
+ self._lengths_advance += N
+ if self._left_padding is not None:
+ self._left_padding_advance += N
+
+ def make_mask(self, N: int):
+ if self.left_padding is not None:
+ pos = mx.arange(N)
+ return pos >= self.left_padding[:, None]
+ elif self.lengths is not None:
+ pos = mx.arange(N)
+ return pos < self.lengths[:, None]
+ else:
+ return None
+
+ @classmethod
+ def merge(cls, caches):
+ n_state = len(caches[0].cache)
+ B = len(caches)
+ cache = cls(n_state)
+
+ # All caches are empty so return early
+ if all(c.empty() for c in caches):
+ cache.left_padding = mx.array([0] * B)
+ return cache
+
+ for e in range(n_state):
+ c_init = next(iter(c[e] for c in caches if c[e] is not None))
+ shape = list(c_init.shape)
+ shape[0] = B
+ cache[e] = mx.zeros(shape, c_init.dtype)
+ for i in range(B):
+ if caches[i][e] is None:
+ continue
+ cache[e][i : i + 1] = caches[i][e]
+ return cache
+
+ def empty(self):
+ return self.cache[0] is None
+
+ @property
+ def nbytes(self):
+ return sum(c.nbytes for c in self.cache if c is not None)
+
+
+class ChunkedKVCache(_BaseCache):
+ step = 256
+
+ def __init__(self, chunk_size):
+ self.keys = None
+ self.values = None
+ self.offset = 0
+ self.chunk_size = chunk_size
+ self.start_position = 0
+
+ def maybe_trim_front(self):
+ # Maintain the cache below the chunk size
+ if self.keys is not None and self.keys.shape[2] >= self.chunk_size:
+ self.start_position += self.keys.shape[2] - self.chunk_size
+ self.keys = self.keys[..., -self.chunk_size :, :]
+ self.values = self.values[..., -self.chunk_size :, :]
+
+ def update_and_fetch(self, keys, values):
+ prev = self.offset - self.start_position
+ if self.keys is None or (prev + keys.shape[2]) > self.keys.shape[2]:
+ B, n_kv_heads, _, k_head_dim = keys.shape
+ v_head_dim = values.shape[3]
+ n_steps = (self.step + keys.shape[2] - 1) // self.step
+ k_shape = (B, n_kv_heads, n_steps * self.step, k_head_dim)
+ v_shape = (B, n_kv_heads, n_steps * self.step, v_head_dim)
+ new_k = mx.zeros(k_shape, keys.dtype)
+ new_v = mx.zeros(v_shape, values.dtype)
+ if self.keys is not None:
+ if prev % self.step != 0:
+ self.keys = self.keys[..., :prev, :]
+ self.values = self.values[..., :prev, :]
+ self.keys = mx.concatenate([self.keys, new_k], axis=2)
+ self.values = mx.concatenate([self.values, new_v], axis=2)
+ else:
+ self.keys, self.values = new_k, new_v
+
+ self.offset += keys.shape[2]
+ end = self.offset - self.start_position
+ self.keys[..., prev:end, :] = keys
+ self.values[..., prev:end, :] = values
+ return self.keys[..., :end, :], self.values[..., :end, :]
+
+ @property
+ def state(self):
+ if self.offset == self.keys.shape[2]:
+ return self.keys, self.values
+ else:
+ return (
+ self.keys[..., : self.offset, :],
+ self.values[..., : self.offset, :],
+ )
+
+ @state.setter
+ def state(self, v):
+ self.keys, self.values = v
+ self.offset = self.keys.shape[2]
+
+ def is_trimmable(self):
+ return True
+
+ def trim(self, n):
+ n = min(self.offset - self.start_position, n)
+ self.offset -= n
+ return n
+
+ @property
+ def meta_state(self):
+ return tuple(map(str, (self.chunk_size, self.start_position)))
+
+ @meta_state.setter
+ def meta_state(self, v):
+ self.chunk_size, self.start_position = map(int, v)
+
+ def empty(self):
+ return self.keys is None
+
+ @property
+ def nbytes(self):
+ if self.keys is None:
+ return 0
+ return self.keys.nbytes + self.values.nbytes
+
+
+class CacheList(_BaseCache):
+ def __init__(self, *caches):
+ self.caches = caches
+
+ def __getitem__(self, idx):
+ return self.caches[idx]
+
+ def is_trimmable(self):
+ return all(c.is_trimmable() for c in self.caches)
+
+ def trim(self, n):
+ for c in self.caches:
+ m = c.trim(n)
+ return m
+
+ @property
+ def state(self):
+ return [c.state for c in self.caches]
+
+ @state.setter
+ def state(self, v):
+ for c, s in zip(self.caches, v):
+ c.state = s
+
+ @property
+ def meta_state(self):
+ return (
+ [type(c).__name__ for c in self.caches],
+ [c.meta_state for c in self.caches],
+ )
+
+ @meta_state.setter
+ def meta_state(self, v):
+ for c, m in zip(self.caches, v[1]):
+ c.meta_state = m
+
+ def filter(self, batch_indices):
+ """
+ In-place filter to keep just the given indices in the cache.
+ """
+ for c in self.caches:
+ c.filter(batch_indices)
+
+ def extend(self, other):
+ """
+ In-place extend this cache with the other cache.
+ """
+ for c, o in zip(self.caches, other.caches):
+ c.extend(o)
+
+ @classmethod
+ def merge(cls, caches):
+ cache = cls()
+ cache.caches = tuple(
+ caches[0].caches[i].merge([c.caches[i] for c in caches])
+ for i in range(len(caches[0].caches))
+ )
+ return cache
+
+ def extract(self, idx):
+ return CacheList(*(c.extract(idx) for c in self.caches))
+
+ def prepare(self, **kwargs):
+ for c in self.caches:
+ c.prepare(**kwargs)
+
+ def finalize(self):
+ for c in self.caches:
+ c.finalize()
+
+ def size(self):
+ return max(c.size() for c in self.caches)
+
+ def empty(self):
+ return self.caches[0].empty()
+
+ @property
+ def nbytes(self):
+ return sum(c.nbytes for c in self.caches)
+
+ @classmethod
+ def from_state(cls, state, meta_state):
+ obj = cls.__new__(cls)
+ obj.caches = [
+ globals()[c].from_state(s, m) for s, c, m in zip(state, *meta_state)
+ ]
+ return obj
+
+
+def dynamic_roll(x, shifts, axis):
+ n = x.shape[axis]
+ expand_shifts = (...,) + (None,) * (x.ndim - axis)
+ expand_indices = expand_shifts[:-1]
+ idx = (mx.arange(n)[expand_indices] - shifts[expand_shifts]) % n
+ rolled = mx.take_along_axis(x, idx, axis=axis)
+ return rolled
+
+
+class BatchKVCache(_BaseCache):
+ step = 256
+
+ def __init__(self, left_padding: List[int]):
+ """
+ The BatchKV cache expects inputs to be left-padded.
+
+ E.g. the following prompts:
+
+ [1, 3, 5]
+ [7]
+ [2, 6, 8, 9]
+
+ Should be padded like so:
+
+ [0, 1, 3, 5]
+ [0, 0, 0, 7]
+ [2, 6, 8, 9]
+
+ And ``left_padding`` specifies the amount of padding for each.
+ In this case, ``left_padding = [1, 3, 0]``.
+ """
+ self.keys = None
+ self.values = None
+ self.left_padding = mx.array(left_padding)
+ self.offset = mx.array([-pad for pad in left_padding])
+ self._idx = 0
+
+ self._right_padding = None
+
+ def update_and_fetch(self, keys, values):
+ prev = self._idx
+ if self.keys is None or (prev + keys.shape[2]) > self.keys.shape[2]:
+ B, n_kv_heads, _, k_head_dim = keys.shape
+ v_head_dim = values.shape[3]
+ n_steps = (self.step + keys.shape[2] - 1) // self.step
+ k_shape = (B, n_kv_heads, n_steps * self.step, k_head_dim)
+ v_shape = (B, n_kv_heads, n_steps * self.step, v_head_dim)
+ new_k = mx.zeros(k_shape, keys.dtype)
+ new_v = mx.zeros(v_shape, values.dtype)
+ if self.keys is not None:
+ if prev % self.step != 0:
+ self.keys = self.keys[..., :prev, :]
+ self.values = self.values[..., :prev, :]
+ self.keys = mx.concatenate([self.keys, new_k], axis=2)
+ self.values = mx.concatenate([self.values, new_v], axis=2)
+ else:
+ self.keys, self.values = new_k, new_v
+
+ self.offset += keys.shape[2]
+ self._idx += keys.shape[2]
+ self.keys[..., prev : self._idx, :] = keys
+ self.values[..., prev : self._idx, :] = values
+ return self.keys[..., : self._idx, :], self.values[..., : self._idx, :]
+
+ def prepare(self, *, left_padding=None, lengths=None, right_padding=None):
+ if left_padding is not None:
+ if self.keys is not None:
+ raise ValueError(
+ "Left padding can only be added to an empty BatchKVCache"
+ )
+ left_padding = mx.array(left_padding)
+ self.left_padding += left_padding
+ self.offset -= left_padding
+
+ if right_padding is not None and max(right_padding) > 0:
+ self._right_padding = mx.array(right_padding)
+
+ def finalize(self):
+ if self._right_padding is not None:
+ padding = self._right_padding
+ self.keys = dynamic_roll(self.keys, padding[:, None], axis=2)
+ self.values = dynamic_roll(self.values, padding[:, None], axis=2)
+ self.offset -= padding
+ self.left_padding += padding
+ self._right_padding = None
+
+ @property
+ def state(self):
+ k, v = self.keys, self.values
+ if self._idx < k.shape[2]:
+ k = k[..., : self._idx, :]
+ v = v[..., : self._idx, :]
+ return k, v, self.offset, self.left_padding
+
+ @state.setter
+ def state(self, v):
+ self.keys, self.values, self.offset, self.left_padding = v
+ self._idx = self.keys.shape[2]
+
+ def is_trimmable(self):
+ return True
+
+ def trim(self, n):
+ n = min(self._idx, n)
+ self._idx -= n
+ self.offset -= n
+ return n
+
+ def make_mask(self, N: int, return_array: bool = False, **kwargs):
+ return create_causal_mask(
+ N, offset=self._idx, left_padding=self.left_padding, **kwargs
+ )
+
+ def filter(self, batch_indices):
+ """
+ In-place filter to keep just the given indices in the cache.
+ """
+ if self.keys is not None:
+ self.keys = self.keys[batch_indices]
+ self.values = self.values[batch_indices]
+ self.offset = self.offset[batch_indices]
+ self.left_padding = self.left_padding[batch_indices]
+ if self._right_padding is not None:
+ self._right_padding = self._right_padding[batch_indices]
+
+ # Shift left to reduce padding
+ min_left_pad = self.left_padding.min().item()
+ if min_left_pad > 0:
+ if self.keys is not None:
+ self.keys = self.keys[..., min_left_pad:, :]
+ self.values = self.values[..., min_left_pad:, :]
+ self._idx -= min_left_pad
+ self.left_padding -= min_left_pad
+
+ def extend(self, other):
+ """
+ In-place extend this cache with the other cache.
+ """
+ if self.keys is None and other.keys is None:
+ self.left_padding = mx.concatenate([self.left_padding, other.left_padding])
+ self.offset = mx.concatenate([self.offset, other.offset])
+ return
+
+ max_idx = max(self._idx, other._idx)
+ L1 = L2 = 0
+ if self.keys is not None:
+ B, H, L1, D = self.keys.shape
+ M = self.values.shape[3]
+ if other.keys is not None:
+ B, H, L2, D = other.keys.shape
+ M = other.values.shape[3]
+ max_size = max(L1, L2)
+
+ # Pad the keys and values so they are right-justified
+ # with the index and the same size
+ def pad(c):
+ k, v = c.keys, c.values
+ if k is None:
+ Bc = c.offset.shape[0]
+ k = mx.array([]).reshape(Bc, H, 0, D)
+ v = mx.array([]).reshape(Bc, H, 0, M)
+ left = max_idx - c._idx
+ right = max_size - k.shape[2] - left
+ if right < 0:
+ k = k[..., :right, :]
+ v = v[..., :right, :]
+ right = 0
+ if left != 0 or right != 0:
+ pad = [(0, 0), (0, 0), (left, right), (0, 0)]
+ k = mx.pad(k, pad)
+ v = mx.pad(v, pad)
+ left_padding = c.left_padding + left
+ return k, v, c.offset, left_padding
+
+ self.keys, self.values, self.offset, self.left_padding = map(
+ mx.concatenate, zip(*(pad(self), pad(other)))
+ )
+ self._idx = max_idx
+
+ def extract(self, idx):
+ cache = KVCache()
+ padding = self.left_padding[idx].item()
+ cache.keys = mx.contiguous(self.keys[idx : idx + 1, :, padding : self._idx])
+ cache.values = mx.contiguous(self.values[idx : idx + 1, :, padding : self._idx])
+ cache.offset = cache.keys.shape[2]
+ return cache
+
+ @classmethod
+ def merge(cls, caches):
+ lengths = [c.size() for c in caches]
+ max_length = max(lengths)
+
+ # No cache has content so make an empty one
+ if max_length == 0:
+ return BatchKVCache([0] * len(caches))
+
+ padding = [max_length - length for length in lengths]
+ B = len(caches)
+ H = max(c.keys.shape[1] for c in caches if c.keys is not None)
+ Dk = max(c.keys.shape[3] for c in caches if c.keys is not None)
+ Dv = max(c.values.shape[3] for c in caches if c.values is not None)
+ dt = next(iter(c.keys.dtype for c in caches if c.keys is not None))
+
+ keys = mx.zeros((B, H, max_length, Dk), dtype=dt)
+ values = mx.zeros((B, H, max_length, Dv), dtype=dt)
+ for i, (p, c) in enumerate(zip(padding, caches)):
+ if c.keys is None:
+ continue
+ keys[i : i + 1, :, p : p + c.offset] = c.keys[..., : c.offset, :]
+ values[i : i + 1, :, p : p + c.offset] = c.values[..., : c.offset, :]
+
+ cache = cls(padding)
+ cache.keys = keys
+ cache.values = values
+ cache.offset += keys.shape[2]
+ cache._idx = keys.shape[2]
+
+ return cache
+
+ def size(self):
+ return self._idx
+
+ def empty(self):
+ return self.keys is None
+
+ @property
+ def batch_size(self):
+ if self.keys is not None:
+ return int(self.keys.shape[0])
+ return int(self.left_padding.shape[0])
+
+ def is_single_row(self):
+ return self.batch_size == 1
+
+ @property
+ def nbytes(self):
+ if self.keys is None:
+ return 0
+ return self.keys.nbytes + self.values.nbytes
+
+
+class BatchRotatingKVCache(_BaseCache):
+ step = 256
+
+ def __init__(self, max_size, left_padding: List[int]):
+ self.keys = None
+ self.values = None
+
+ self.left_padding = mx.array(left_padding)
+ self.offset = mx.array([-pad for pad in left_padding])
+
+ self.max_size = max_size
+ self._idx = 0
+ self._offset = 0
+ self.rotated = False
+
+ # Lengths for right_padded inputs to make sure that padding tokens do
+ # not evict valid tokens.
+ self._lengths = None
+
+ def _trim(self, trim_size, v, append=None):
+ if trim_size > 0:
+ v = v[..., trim_size:, :]
+ if append is not None:
+ return mx.concatenate([v, append], axis=2)
+ return v
+
+ def _temporal_order(self):
+ """
+ Rearrange the cache into temporal order.
+ """
+ if self.rotated:
+ self.keys = mx.roll(self.keys, -self._idx, axis=2)
+ self.values = mx.roll(self.values, -self._idx, axis=2)
+ self._idx = self.keys.shape[2]
+ self.rotated = False
+
+ def _update_concat(self, keys, values):
+ if self.keys is None:
+ self.keys = keys
+ self.values = values
+ else:
+ # Put the keys/values in temporal order to
+ # preserve context
+ self._temporal_order()
+
+ # Slice off the end if needed
+ if self.keys.shape[2] > self._idx:
+ self.keys = self.keys[..., : self._idx, :]
+ self.values = self.values[..., : self._idx, :]
+
+ # Roll right sequences that are padded to make sure that we don't
+ # trim valid cache entries
+ if self._lengths is not None:
+ roll = mx.maximum(0, self.offset - self._lengths)
+ self.keys = dynamic_roll(self.keys, roll[:, None], axis=2)
+ self.values = dynamic_roll(self.values, roll[:, None], axis=2)
+ self.left_padding += roll
+ self.offset -= roll
+
+ # The largest size is self.max_size + S - 1 to ensure
+ # every token gets at least self.max_size context
+ trim_size = self._idx - self.max_size + 1
+ if trim_size > 0:
+ self.left_padding -= trim_size
+ self.keys = self._trim(trim_size, self.keys, keys)
+ self.values = self._trim(trim_size, self.values, values)
+ self.offset += keys.shape[2]
+ self._offset += keys.shape[2]
+ self._idx = self.keys.shape[2]
+
+ # Make sure left_padding and offset are evaluated
+ self.keys = mx.depends(self.keys, (self.left_padding, self.offset))
+
+ return self.keys, self.values
+
+ def _update_in_place(self, keys, values):
+ if self._lengths is not None:
+ raise RuntimeError(
+ "finalize() should be called before deocoding with BatchRotatingKVCache"
+ )
+
+ # May not have hit the max size yet, so potentially
+ # keep growing the cache
+ B, n_kv_heads, S, k_head_dim = keys.shape
+ prev = self._offset
+ if self.keys is None or (
+ prev >= self.keys.shape[2] and self.keys.shape[2] < self.max_size
+ ):
+ v_head_dim = values.shape[3]
+ new_size = min(self.step, self.max_size - prev)
+ k_shape = (B, n_kv_heads, new_size, k_head_dim)
+ v_shape = (B, n_kv_heads, new_size, v_head_dim)
+ new_k = mx.zeros(k_shape, keys.dtype)
+ new_v = mx.zeros(v_shape, values.dtype)
+ if self.keys is not None:
+ self.keys = mx.concatenate([self.keys, new_k], axis=2)
+ self.values = mx.concatenate([self.values, new_v], axis=2)
+ else:
+ self.keys, self.values = new_k, new_v
+ self._idx = prev
+
+ # Trim if needed
+ trim_size = self.keys.shape[2] - self.max_size
+ if trim_size > 0:
+ self.keys = self._trim(trim_size, self.keys)
+ self.values = self._trim(trim_size, self.values)
+ self._idx = self.max_size
+ self.left_padding -= trim_size
+
+ # Rotate
+ if self._idx == self.max_size:
+ self.rotated = True
+ self._idx = 0
+ if self.rotated:
+ self.left_padding -= S
+
+ # Assign
+ self.keys[..., self._idx : self._idx + S, :] = keys
+ self.values[..., self._idx : self._idx + S, :] = values
+ self._offset += S
+ self.offset += S
+ self._idx += S
+
+ # Make sure left_padding and offset are evaluated
+ self.keys = mx.depends(self.keys, (self.left_padding, self.offset))
+
+ # If the buffer is not full, slice off the end
+ if self._offset < self.max_size:
+ return (
+ self.keys[..., : self._offset, :],
+ self.values[..., : self._offset, :],
+ )
+ return self.keys, self.values
+
+ def update_and_fetch(self, keys, values):
+ # Single-token updates normally use the in-place decode path. While
+ # right-padding bookkeeping is active (_lengths set by prepare()), the
+ # last prefill step may still be S=1; that must go through concat so
+ # pad tokens are tracked until finalize() rolls them out.
+ if keys.shape[2] == 1 and self._lengths is None:
+ return self._update_in_place(keys, values)
+ return self._update_concat(keys, values)
+
+ def prepare(self, *, left_padding=None, lengths=None, right_padding=None):
+ if left_padding is not None:
+ if self.keys is not None:
+ raise ValueError(
+ "Left padding can only be added to an empty BatchRotatingKVCache"
+ )
+ left_padding = mx.array(left_padding)
+ self.left_padding += left_padding
+ self.offset -= left_padding
+
+ if right_padding is not None and max(right_padding) > 0:
+ self._lengths = mx.array(lengths) + self.offset
+
+ def finalize(self):
+ if self._lengths is not None:
+ roll = mx.maximum(0, self.offset - self._lengths)
+ self.keys = dynamic_roll(self.keys, roll[:, None], axis=2)
+ self.values = dynamic_roll(self.values, roll[:, None], axis=2)
+ self.left_padding += roll
+ self.offset -= roll
+ self._lengths = None
+
+ @property
+ def state(self):
+ k, v = self.keys, self.values
+ if self._offset < k.shape[2]:
+ k, v = k[..., : self._offset, :], v[..., : self._offset, :]
+ return k, v, self.offset, self.left_padding
+
+ @state.setter
+ def state(self, v):
+ self.keys, self.values, self.offset, self.left_padding = v
+
+ @property
+ def meta_state(self):
+ return tuple(map(str, (self.max_size, self._offset, self._idx, self.rotated)))
+
+ @meta_state.setter
+ def meta_state(self, v):
+ self.max_size, self._offset, self._idx = map(
+ int,
+ v[:3],
+ )
+ self.rotated = bool(v[3])
+
+ def is_trimmable(self):
+ return self._offset < self.max_size
+
+ def trim(self, n):
+ n = min(self._offset, n)
+ self._offset -= n
+ self._idx -= n
+ self.offset -= n
+ return n
+
+ def to_quantized(self, group_size: int = 64, bits: int = 4) -> QuantizedKVCache:
+ raise NotImplementedError("BatchRotatingKVCache Quantization NYI")
+
+ def make_mask(
+ self, N: int, window_size: Optional[int] = None, return_array: bool = False
+ ):
+ left_padding = self.left_padding
+ window_size = window_size or self.max_size
+ offset = min(self.max_size - 1, self._offset)
+ rinds = mx.arange(offset + N)
+ linds = mx.arange(offset, offset + N) if offset else rinds
+ linds = linds[:, None]
+ rinds = rinds[None]
+ mask = linds >= rinds
+ mask &= linds < rinds + window_size
+ if (trim_size := self._idx - self.max_size + int(N > 1)) > 0:
+ left_padding = left_padding - trim_size
+
+ rotated = N == 1 and (self.rotated or self._idx >= self.max_size)
+ if rotated:
+ left_padding = left_padding - 1
+
+ mask = mask & (rinds >= mx.expand_dims(left_padding, (1, 2, 3)))
+
+ if rotated:
+ idx = self._idx
+ if idx >= self.max_size:
+ idx = 0
+ mask = mx.roll(mask, shift=idx + 1, axis=-1)
+
+ return mask
+
+ def filter(self, batch_indices):
+ """
+ In-place filter to keep just the given indices in the cache.
+ """
+ if self.keys is not None:
+ self.keys = self.keys[batch_indices]
+ self.values = self.values[batch_indices]
+ self.offset = self.offset[batch_indices]
+ self.left_padding = self.left_padding[batch_indices]
+ if self._lengths is not None:
+ self._lengths = self._lengths[batch_indices]
+
+ def extend(self, other):
+ """
+ In-place extend this cache with the other cache.
+ """
+ if self.keys is None and other.keys is None:
+ self.left_padding = mx.concatenate([self.left_padding, other.left_padding])
+ self.offset = mx.concatenate([self.offset, other.offset])
+ return
+
+ if (self.rotated != other.rotated) or self._idx != other._idx:
+ self._temporal_order()
+ other._temporal_order()
+
+ max_idx = max(self._idx, other._idx)
+ L1 = L2 = 0
+ if self.keys is not None:
+ B, H, L1, D = self.keys.shape
+ M = self.values.shape[3]
+ if other.keys is not None:
+ B, H, L2, D = other.keys.shape
+ M = other.values.shape[3]
+ max_size = max(L1, L2)
+
+ def pad(c):
+ left = max_idx - c._idx
+ k, v = c.keys, c.values
+ if k is None:
+ Bc = c.offset.shape[0]
+ k = mx.array([]).reshape(Bc, H, 0, D)
+ v = mx.array([]).reshape(Bc, H, 0, M)
+ right = max_size - k.shape[2] - left
+ if right < 0:
+ k = k[..., :right, :]
+ v = v[..., :right, :]
+ right = 0
+ if left != 0 or right != 0:
+ pad = [(0, 0), (0, 0), (left, right), (0, 0)]
+ k = mx.pad(k, pad)
+ v = mx.pad(v, pad)
+ left_padding = c.left_padding + left
+ return k, v, c.offset, left_padding
+
+ self.keys, self.values, self.offset, self.left_padding = map(
+ mx.concatenate, zip(*(pad(self), pad(other)))
+ )
+ self._idx = max_idx
+ self._offset = max(self._offset, other._offset)
+
+ def extract(self, idx):
+ mx.eval(self.left_padding, self.offset)
+ cache = RotatingKVCache(self.max_size)
+ padding = max(0, self.left_padding.tolist()[idx])
+ offset = self.offset.tolist()[idx]
+ cache.keys = self.keys[idx : idx + 1]
+ cache.values = self.values[idx : idx + 1]
+ cache._idx = self._idx
+ if self.rotated:
+ cache.keys = mx.roll(cache.keys, -self._idx, axis=2)
+ cache.values = mx.roll(cache.values, -self._idx, axis=2)
+ cache._idx = self.max_size
+ cache.keys = mx.contiguous(cache.keys[:, :, padding : cache._idx])
+ cache.values = mx.contiguous(cache.values[:, :, padding : cache._idx])
+ cache.offset = offset
+ cache._idx = cache.keys.shape[2]
+ return cache
+
+ @classmethod
+ def merge(cls, caches):
+ if not all(c.max_size == caches[0].max_size for c in caches):
+ raise ValueError(
+ "BatchRotatingKVCache can only merge caches with the same maximum size"
+ )
+
+ offsets = [c.offset for c in caches]
+ lengths = [c.size() for c in caches]
+ max_length = max(lengths)
+
+ # No cache has content so make an empty one
+ if max_length == 0:
+ return cls(caches[0].max_size, [0] * len(caches))
+
+ padding = [max_length - length for length in lengths]
+ B = len(caches)
+ H = max(c.keys.shape[1] for c in caches if c.keys is not None)
+ Dk = max(c.keys.shape[3] for c in caches if c.keys is not None)
+ Dv = max(c.values.shape[3] for c in caches if c.values is not None)
+ dt = next(iter(c.keys.dtype for c in caches if c.keys is not None))
+
+ keys = mx.zeros((B, H, max_length, Dk), dtype=dt)
+ values = mx.zeros((B, H, max_length, Dv), dtype=dt)
+ for i, (p, length, c) in enumerate(zip(padding, lengths, caches)):
+ if c.keys is None or length == 0:
+ continue
+ keys[i : i + 1, :, p : p + length] = c._temporal_order(c.keys)[
+ ..., -length:, :
+ ]
+ values[i : i + 1, :, p : p + length] = c._temporal_order(c.values)[
+ ..., -length:, :
+ ]
+
+ cache = cls(caches[0].max_size, padding)
+ cache.keys = keys
+ cache.values = values
+ cache.offset = mx.array(offsets)
+ cache._idx = keys.shape[2]
+ cache._offset = keys.shape[2]
+
+ return cache
+
+ def size(self):
+ return min(self._offset, self.max_size)
+
+ def empty(self):
+ return self.keys is None
+
+ @property
+ def batch_size(self):
+ if self.keys is not None:
+ return int(self.keys.shape[0])
+ return int(self.left_padding.shape[0])
+
+ def is_single_row(self):
+ return self.batch_size == 1
+
+ @property
+ def nbytes(self):
+ if self.keys is None:
+ return 0
+ return self.keys.nbytes + self.values.nbytes
+
+
+# MLX-VLM cache extensions.
+
+
+class BufferedRotatingKVCache(RotatingKVCache):
+ """Temporal sliding-window cache with rollback slack for speculative blocks."""
+
+ def __init__(self, max_size: int, keep: int = 0, buffer_size: int = 64):
+ super().__init__(max_size=max_size, keep=keep)
+ self.buffer_size = max(0, int(buffer_size))
+ self.start_position = 0
+
+ @classmethod
+ def from_cache(
+ cls, other: RotatingKVCache, buffer_size: int = 64
+ ) -> "BufferedRotatingKVCache":
+ cache = cls(other.max_size, other.keep, buffer_size=buffer_size)
+ cache.offset = int(other.offset)
+ if other.keys is None:
+ return cache
+
+ keys = other._temporal_order(other.keys)
+ values = other._temporal_order(other.values)
+ keep = min(int(keys.shape[2]), other.max_size)
+ if keep < int(keys.shape[2]):
+ keys = keys[..., -keep:, :]
+ values = values[..., -keep:, :]
+
+ cache.start_position = cache.offset - keep
+ cache._idx = keep
+ capacity = cache._capacity_for(keep)
+ k_shape = (*keys.shape[:2], capacity, keys.shape[-1])
+ v_shape = (*values.shape[:2], capacity, values.shape[-1])
+ cache.keys = mx.zeros(k_shape, dtype=keys.dtype)
+ cache.values = mx.zeros(v_shape, dtype=values.dtype)
+ cache.keys[..., :keep, :] = keys
+ cache.values[..., :keep, :] = values
+ return cache
+
+ def _target_size(self, incoming: int = 0) -> int:
+ return self.max_size + max(self.buffer_size, incoming)
+
+ def _capacity_for(self, needed: int) -> int:
+ target = max(needed, self._target_size())
+ return ((target + self.step - 1) // self.step) * self.step
+
+ def _planned_drop(self, incoming: int) -> int:
+ needed = self._idx + incoming
+ target_size = self._target_size(incoming)
+ if needed <= target_size:
+ return 0
+ target_start = max(0, self.offset - self.max_size + 1)
+ return min(max(0, target_start - self.start_position), self._idx)
+
+ def _compact(self, drop: int) -> None:
+ if drop <= 0:
+ return
+ keep = self._idx - drop
+ keys = self.keys[..., drop : self._idx, :]
+ values = self.values[..., drop : self._idx, :]
+ capacity = self.keys.shape[2]
+ new_keys = mx.zeros((*keys.shape[:2], capacity, keys.shape[-1]), keys.dtype)
+ new_values = mx.zeros(
+ (*values.shape[:2], capacity, values.shape[-1]), values.dtype
+ )
+ new_keys[..., :keep, :] = keys
+ new_values[..., :keep, :] = values
+ self.keys = new_keys
+ self.values = new_values
+ self.start_position += drop
+ self._idx = keep
+
+ def _ensure_capacity(self, keys: mx.array, values: mx.array, needed: int) -> None:
+ if self.keys is not None and needed <= self.keys.shape[2]:
+ return
+
+ capacity = self._capacity_for(needed)
+ k_shape = (*keys.shape[:2], capacity, keys.shape[-1])
+ v_shape = (*values.shape[:2], capacity, values.shape[-1])
+ new_keys = mx.zeros(k_shape, dtype=keys.dtype)
+ new_values = mx.zeros(v_shape, dtype=values.dtype)
+ if self.keys is not None and self._idx > 0:
+ new_keys[..., : self._idx, :] = self.keys[..., : self._idx, :]
+ new_values[..., : self._idx, :] = self.values[..., : self._idx, :]
+ self.keys = new_keys
+ self.values = new_values
+
+ def update_and_fetch(self, keys: mx.array, values: mx.array):
+ if self.keep:
+ return super().update_and_fetch(keys, values)
+
+ incoming = int(keys.shape[2])
+ drop = self._planned_drop(incoming)
+ self._compact(drop)
+ needed = self._idx + incoming
+ self._ensure_capacity(keys, values, needed)
+
+ self.keys[..., self._idx : needed, :] = keys
+ self.values[..., self._idx : needed, :] = values
+ self._idx = needed
+ self.offset += incoming
+ return self.keys[..., : self._idx, :], self.values[..., : self._idx, :]
+
+ def trim(self, n):
+ n = min(int(n), self._idx, self.offset)
+ self.offset -= n
+ self._idx -= n
+ return n
+
+ def is_trimmable(self):
+ return True
+
+ def make_mask(
+ self, N: int, window_size: Optional[int] = None, return_array: bool = False
+ ):
+ if self.keep:
+ return super().make_mask(
+ N, window_size=window_size, return_array=return_array
+ )
+
+ window_size = window_size or self.max_size
+ drop = self._planned_drop(N)
+ start = self.start_position + drop
+ end = self.offset + N
+ key_len = end - start
+ if N == 1 and key_len <= window_size and not return_array:
+ return None
+
+ q_idx = mx.arange(self.offset, end)[:, None]
+ k_idx = mx.arange(start, end)[None, :]
+ mask = (q_idx >= k_idx) & (q_idx < k_idx + window_size)
+ if N > 1 and key_len <= window_size and not return_array:
+ return "causal"
+ return mask
+
+ @property
+ def state(self):
+ if self.keys is None:
+ return None, None
+ return self.keys[..., : self._idx, :], self.values[..., : self._idx, :]
+
+ @state.setter
+ def state(self, v):
+ self.keys, self.values = v
+ self._idx = 0 if self.keys is None else int(self.keys.shape[2])
+ self.start_position = max(0, int(self.offset) - self._idx)
+
+ @property
+ def meta_state(self):
+ return tuple(
+ map(
+ str,
+ (
+ self.keep,
+ self.max_size,
+ self.offset,
+ self._idx,
+ self.start_position,
+ self.buffer_size,
+ ),
+ )
+ )
+
+ @meta_state.setter
+ def meta_state(self, v):
+ vals = list(map(int, v))
+ self.keep, self.max_size, self.offset, self._idx = vals[:4]
+ self.start_position = vals[4] if len(vals) > 4 else 0
+ self.buffer_size = vals[5] if len(vals) > 5 else 64
+
+
+class BatchQuantizedKVCache(_BaseCache):
+ """Batch-aware quantized KV cache for continuous batching.
+
+ Mirrors ``BatchKVCache`` but stores keys/values in quantized form
+ (packed uint32 + scales + biases), matching the format produced by
+ ``mx.quantize``. Supports ``extend()`` and ``filter()`` so that
+ ``Batch.extend`` / ``Batch.filter`` work during continuous-batching.
+ """
+
+ step = 256
+
+ def __init__(
+ self,
+ left_padding: List[int],
+ group_size: int = 64,
+ bits: int = 8,
+ ):
+ self.keys = None # tuple (packed, scales, biases) or None
+ self.values = None
+ self.left_padding = mx.array(left_padding)
+ self.offset = mx.array([-lp for lp in left_padding])
+ self._idx = 0
+ self.group_size = group_size
+ self.bits = bits
+ # Set by prepare() for multi-row right-pad prefill; cleared in finalize().
+ self._right_padding = None
+
+ def prepare(self, *, left_padding=None, lengths=None, right_padding=None):
+ """Batch pad lifecycle — same contract as :class:`BatchKVCache`."""
+ if left_padding is not None:
+ if self.keys is not None:
+ raise ValueError(
+ "Left padding can only be added to an empty BatchQuantizedKVCache"
+ )
+ left_padding = mx.array(left_padding)
+ self.left_padding += left_padding
+ self.offset -= left_padding
+
+ if right_padding is not None and max(right_padding) > 0:
+ self._right_padding = mx.array(right_padding)
+
+ def finalize(self):
+ """Roll right-padding into left-padding after multi-row prefill."""
+ if self._right_padding is None:
+ return
+ padding = self._right_padding
+ if self.keys is not None:
+ # Seq axis is 2 for packed/scales/biases (B, H, S, …) — same as BatchKVCache.
+ self.keys = tuple(
+ dynamic_roll(k, padding[:, None], axis=2) for k in self.keys
+ )
+ self.values = tuple(
+ dynamic_roll(v, padding[:, None], axis=2) for v in self.values
+ )
+ self.offset -= padding
+ self.left_padding += padding
+ self._right_padding = None
+
+ def update_and_fetch(self, keys: mx.array, values: mx.array):
+ """Quantize incoming keys/values and append to the cache.
+
+ Args:
+ keys: float [B, H, S, D_k]
+ values: float [B, H, S, D_v]
+
+ Returns:
+ Quantized (keys_tuple, values_tuple) sliced to ``_idx``.
+ """
+ B, n_kv_heads, num_steps, k_head_dim = keys.shape
+ v_head_dim = values.shape[-1]
+ prev = self._idx
+ el_per_int = 8 * mx.uint32.size // self.bits
+
+ if self.keys is None or (prev + num_steps) > self.keys[0].shape[-2]:
+ new_steps = (self.step + num_steps - 1) // self.step * self.step
+ shape = (B, n_kv_heads, new_steps)
+
+ def _init(dim):
+ return (
+ mx.zeros((*shape, dim // el_per_int), dtype=mx.uint32),
+ mx.zeros((*shape, dim // self.group_size), dtype=keys.dtype),
+ mx.zeros((*shape, dim // self.group_size), dtype=keys.dtype),
+ )
+
+ def _expand(x):
+ new_x = mx.zeros((*shape, x.shape[-1]), dtype=x.dtype)
+ return mx.concatenate([x, new_x], axis=-2)
+
+ if self.keys is not None:
+ if prev % self.step != 0:
+ self.keys = tuple(k[..., :prev, :] for k in self.keys)
+ self.values = tuple(v[..., :prev, :] for v in self.values)
+ self.keys = tuple(_expand(k) for k in self.keys)
+ self.values = tuple(_expand(v) for v in self.values)
+ else:
+ self.keys = _init(k_head_dim)
+ self.values = _init(v_head_dim)
+
+ self.offset += num_steps
+ self._idx += num_steps
+
+ q_keys = mx.quantize(keys, group_size=self.group_size, bits=self.bits)
+ q_values = mx.quantize(values, group_size=self.group_size, bits=self.bits)
+ for i in range(len(self.keys)):
+ self.keys[i][..., prev : self._idx, :] = q_keys[i]
+ self.values[i][..., prev : self._idx, :] = q_values[i]
+
+ return (
+ tuple(k[..., : self._idx, :] for k in self.keys),
+ tuple(v[..., : self._idx, :] for v in self.values),
+ )
+
+ def dequantize_for_apc(self):
+ """Return raw float (keys, values) sliced to current _idx for APC storage.
+
+ Returns (None, None) if the cache is empty.
+ """
+ if self.keys is None or self._idx == 0:
+ return None, None
+ return _dequantize_uniform(
+ self.keys, self.values, self._idx, self.group_size, self.bits
+ )
+
+ def extract(self, idx):
+ """Extract one batch row as a single-sequence QuantizedKVCache."""
+ cache = QuantizedKVCache(group_size=self.group_size, bits=self.bits)
+ if self.keys is None or self._idx == 0:
+ return cache
+ padding = int(self.left_padding[idx].item())
+ end = self._idx
+ cache.keys = tuple(
+ mx.contiguous(k[idx : idx + 1, :, padding:end, :]) for k in self.keys
+ )
+ cache.values = tuple(
+ mx.contiguous(v[idx : idx + 1, :, padding:end, :]) for v in self.values
+ )
+ cache.offset = int(cache.keys[0].shape[2])
+ return cache
+
+ def filter(self, batch_indices: mx.array):
+ """Keep only the sequences at *batch_indices*."""
+ if self.keys is not None:
+ self.keys = tuple(k[batch_indices] for k in self.keys)
+ self.values = tuple(v[batch_indices] for v in self.values)
+ self.offset = self.offset[batch_indices]
+ self.left_padding = self.left_padding[batch_indices]
+ if self._right_padding is not None:
+ self._right_padding = self._right_padding[batch_indices]
+
+ min_lp = self.left_padding.min().item()
+ if min_lp > 0:
+ if self.keys is not None:
+ self.keys = tuple(k[..., min_lp:, :] for k in self.keys)
+ self.values = tuple(v[..., min_lp:, :] for v in self.values)
+ self._idx -= min_lp
+ self.left_padding -= min_lp
+
+ def extend(self, other: "BatchQuantizedKVCache"):
+ """Concatenate *other* batch into this cache along the batch dim."""
+ if self.keys is None and other.keys is None:
+ self.left_padding = mx.concatenate([self.left_padding, other.left_padding])
+ self.offset = mx.concatenate([self.offset, other.offset])
+ return
+
+ max_idx = max(self._idx, other._idx)
+ self_len = 0 if self.keys is None else self.keys[0].shape[-2]
+ other_len = 0 if other.keys is None else other.keys[0].shape[-2]
+ max_size = max(max_idx, self_len, other_len)
+ ref_keys = self.keys if self.keys is not None else other.keys
+ ref_values = self.values if self.values is not None else other.values
+
+ def _empty_like(parts, batch_size: int):
+ out = []
+ for part in parts:
+ shape = list(part.shape)
+ shape[0] = batch_size
+ shape[-2] = 0
+ out.append(mx.zeros(tuple(shape), dtype=part.dtype))
+ return tuple(out)
+
+ def _pad_quant(cache_obj):
+ if cache_obj.keys is None:
+ batch_size = int(cache_obj.offset.shape[0])
+ keys = _empty_like(ref_keys, batch_size)
+ values = _empty_like(ref_values, batch_size)
+ else:
+ keys = cache_obj.keys
+ values = cache_obj.values
+ left = max_idx - cache_obj._idx
+ right = max_size - keys[0].shape[-2] - left
+ if right < 0:
+ trimmed_keys = tuple(k[..., : max_size - left, :] for k in keys)
+ trimmed_values = tuple(v[..., : max_size - left, :] for v in values)
+ right = 0
+ else:
+ trimmed_keys = keys
+ trimmed_values = values
+
+ if left != 0 or right != 0:
+ pad_spec = [(0, 0)] * len(trimmed_keys[0].shape)
+ pad_spec[-2] = (left, right)
+ padded_keys = tuple(mx.pad(k, pad_spec) for k in trimmed_keys)
+ padded_values = tuple(mx.pad(v, pad_spec) for v in trimmed_values)
+ else:
+ padded_keys = trimmed_keys
+ padded_values = trimmed_values
+
+ lp = cache_obj.left_padding + left
+ return padded_keys, padded_values, cache_obj.offset, lp
+
+ r_self = _pad_quant(self)
+ r_other = _pad_quant(other)
+
+ sk, sv, so, slp = r_self
+ ok, ov, oo, olp = r_other
+
+ self.keys = tuple(mx.concatenate([s, o]) for s, o in zip(sk, ok))
+ self.values = tuple(mx.concatenate([s, o]) for s, o in zip(sv, ov))
+ self.offset = mx.concatenate([so, oo])
+ self.left_padding = mx.concatenate([slp, olp])
+ self._idx = max_idx
+
+ @property
+ def state(self):
+ if self.keys is None:
+ return None, None, self.offset, self.left_padding
+ k = tuple(x[..., : self._idx, :] for x in self.keys)
+ v = tuple(x[..., : self._idx, :] for x in self.values)
+ return k, v, self.offset, self.left_padding
+
+ @state.setter
+ def state(self, val):
+ self.keys, self.values, self.offset, self.left_padding = val
+ if self.keys is not None:
+ self._idx = self.keys[0].shape[2]
+
+ @property
+ def meta_state(self):
+ return tuple(map(str, (self._idx, self.group_size, self.bits)))
+
+ @meta_state.setter
+ def meta_state(self, v):
+ self._idx, self.group_size, self.bits = map(int, v)
+
+ def is_trimmable(self):
+ return True
+
+ def trim(self, n):
+ n = min(self._idx, n)
+ self._idx -= n
+ self.offset -= n
+ return n
+
+ def empty(self):
+ return self.keys is None
+
+ @property
+ def batch_size(self):
+ if self.keys is not None:
+ return int(self.keys[0].shape[0])
+ return int(self.left_padding.shape[0])
+
+ def is_single_row(self):
+ return self.batch_size == 1
+
+ def make_mask(self, N: int, return_array: bool = False, **kwargs):
+ return create_causal_mask(
+ N, offset=self._idx, left_padding=self.left_padding, **kwargs
+ )
+
+
+class PoolingCache(_BaseCache):
+ """Cache for pooled (compressed) KV tokens with a remainder buffer.
+
+ Stores two things:
+ 1. A growing pool of compressed tokens (step-allocated).
+ 2. A small remainder buffer of tokens not yet forming a full window.
+ """
+
+ def __init__(self, ratio: int):
+ self.ratio = ratio
+
+ self.buf_kv = None
+ self.buf_gate = None
+ self.remainder = 0
+
+ self.pooled = None
+
+ @property
+ def offset(self):
+ return 0 if self.pooled is None else self.pooled.shape[1]
+
+ def accumulate_windows(self, kv: mx.array, gate: mx.array, offset):
+ B, L, D1 = kv.shape
+ _, _, D2 = gate.shape
+
+ if self.buf_kv is None:
+ self.buf_kv = mx.zeros((B, self.ratio, D1), dtype=kv.dtype)
+ self.buf_gate = mx.zeros((B, self.ratio, D2), dtype=gate.dtype)
+
+ # Prompt mode
+ if L > 1:
+ total = L + self.remainder
+ usable = (total // self.ratio) * self.ratio
+ new_remainder = total % self.ratio
+
+ if usable > 0:
+ r_kv = mx.concatenate(
+ [
+ self.buf_kv[:, : self.remainder],
+ kv[:, : (usable - self.remainder)],
+ ],
+ axis=1,
+ )
+ r_gate = mx.concatenate(
+ [
+ self.buf_gate[:, : self.remainder],
+ gate[:, : (usable - self.remainder)],
+ ],
+ axis=1,
+ )
+ r_base = offset - self.remainder
+ self.remainder = 0
+ else:
+ r_kv = mx.zeros((B, 0, D1), dtype=kv.dtype)
+ r_gate = mx.zeros((B, 0, D2), dtype=gate.dtype)
+ r_base = 0
+
+ if new_remainder > 0:
+ self.buf_kv[:, self.remainder : new_remainder] = kv[:, -new_remainder:]
+ self.buf_gate[:, self.remainder : new_remainder] = gate[
+ :, -new_remainder:
+ ]
+ self.remainder = new_remainder
+
+ return r_kv, r_gate, r_base
+
+ # Decode mode
+ else:
+ self.buf_kv[:, self.remainder : self.remainder + 1] = kv
+ self.buf_gate[:, self.remainder : self.remainder + 1] = gate
+ self.remainder = (self.remainder + 1) % self.ratio
+
+ if self.remainder == 0:
+ r_kv = self.buf_kv
+ r_gate = self.buf_gate
+ r_base = offset - self.ratio + 1
+ else:
+ r_kv = mx.zeros((B, 0, D1), dtype=kv.dtype)
+ r_gate = mx.zeros((B, 0, D2), dtype=gate.dtype)
+ r_base = 0
+
+ return r_kv, r_gate, r_base
+
+ def update_and_fetch(self, px: mx.array):
+ if px.shape[1] == 0:
+ if self.pooled is None:
+ return mx.zeros((px.shape[0], 0, px.shape[-1]), dtype=px.dtype)
+ return self.pooled
+
+ if self.pooled is None:
+ self.pooled = px
+ else:
+ self.pooled = mx.concatenate([self.pooled, px], axis=1)
+ return self.pooled
+
+ def make_mask(self, L: int = 1, offset: int = 0):
+ """Build a causal validity mask for pooled positions.
+
+ Query at absolute position ``offset + j`` can attend to pooled token
+ ``i`` iff ``i < (offset + j) // ratio``.
+
+ Returns ``(N, P)`` bool mask, or ``None`` when every pooled position
+ is visible to every query (common during decode).
+ """
+ if self.pooled is None or L == 1:
+ return None
+
+ pool_idx = mx.arange(self.pooled.shape[1])
+ query_idx = mx.arange(offset + 1, offset + L + 1)
+ return pool_idx < query_idx[:, None] // self.ratio
+
+ @property
+ def state(self):
+ buf_kv = self.buf_kv[:, : self.remainder] if self.remainder > 0 else None
+ buf_gate = self.buf_gate[:, : self.remainder] if self.remainder > 0 else None
+ return (buf_kv, buf_gate, self.pooled)
+
+ @state.setter
+ def state(self, v):
+ buf_kv, buf_gate, pooled = v
+ self.remainder = 0
+ self.buf_kv = self.buf_gate = None
+ if buf_kv is not None:
+ self.accumulate_windows(buf_kv, buf_gate, 0)
+ self.pooled = pooled
+
+ @property
+ def meta_state(self):
+ return self.ratio
+
+ @meta_state.setter
+ def meta_state(self, v):
+ self.ratio = v
+
+ @classmethod
+ def from_state(cls, state, meta_state):
+ # Restoring buffered state calls ``accumulate_windows``, which needs
+ # the compression ratio before the generic state setter can run.
+ obj = cls(meta_state)
+ obj.state = state
+ return obj
+
+ def is_trimmable(self):
+ return self.pooled is None
+
+ def trim(self, n):
+ n = min(self.remainder, n)
+ self.remainder -= n
+ return n
+
+ def size(self):
+ return 0 if self.pooled is None else self.pooled.shape[1]
+
+ def empty(self):
+ return self.pooled is None and self.remainder == 0
+
+ @property
+ def nbytes(self):
+ total = 0
+ if self.buf_kv is not None:
+ total += self.buf_kv.nbytes + self.buf_gate.nbytes
+ if self.pooled is not None:
+ total += self.pooled.nbytes
+ return total
+
+ @classmethod
+ def merge(cls, caches, prefix_lens=None):
+ return BatchPoolingCache.merge(caches, prefix_lens)
+
+
+class BatchPoolingCache(_BaseCache):
+ """Batched pooling cache with per-element variable-length tracking."""
+
+ def __init__(self, ratio: int, left_padding: List[int]):
+ self.ratio = ratio
+
+ if isinstance(left_padding, mx.array):
+ left_padding = left_padding.tolist()
+ self.left_padding = [int(p) for p in left_padding]
+
+ batch_size = len(left_padding)
+
+ self.buf_kv = None
+ self.buf_gate = None
+ self.remainder = [0] * batch_size
+
+ self.pooled = None
+ self._pool_lengths = [0] * batch_size
+
+ self._lengths = [2**31] * batch_size
+ self._processed = [0] * batch_size
+
+ @property
+ def offset(self):
+ return mx.array(self._pool_lengths, dtype=mx.int32)
+
+ def prepare(self, *, lengths=None, right_padding=None, left_padding=None):
+ if left_padding is not None:
+ if (
+ self.buf_kv is not None
+ or self.pooled is not None
+ or any(self.remainder)
+ ):
+ raise ValueError(
+ "Left padding can only be added to an empty BatchPoolingCache"
+ )
+ if isinstance(left_padding, mx.array):
+ left_padding = left_padding.tolist()
+ if len(left_padding) != len(self.left_padding):
+ raise ValueError("Left padding must match the cache batch size")
+ self.left_padding = [
+ current + int(pad)
+ for current, pad in zip(self.left_padding, left_padding)
+ ]
+ if lengths is not None:
+ self._lengths = [
+ processed + length
+ for processed, length in zip(self._processed, lengths)
+ ]
+
+ def finalize(self):
+ self._lengths = [2**31] * len(self._pool_lengths)
+
+ def accumulate_windows(self, kv: mx.array, gate: mx.array, offset):
+ B, L, D1 = kv.shape
+ _, _, D2 = gate.shape
+ ratio = self.ratio
+
+ if not (
+ len(self.left_padding) == len(self._lengths) == len(self._processed) == B
+ ):
+ raise ValueError("Pooling cache metadata must match the input batch size")
+
+ if self.buf_kv is None:
+ self.buf_kv = mx.zeros((B, ratio, D1), dtype=kv.dtype)
+ self.buf_gate = mx.zeros((B, ratio, D2), dtype=gate.dtype)
+
+ # Each row can start at a different physical position because prompt
+ # batches are left-padded. Only logical tokens participate in pooling.
+ starts = [min(pad, L) for pad in self.left_padding]
+ self.left_padding = [
+ pad - start for pad, start in zip(self.left_padding, starts)
+ ]
+ valid_lengths = [
+ max(0, min(length - processed, L - start))
+ for length, processed, start in zip(self._lengths, self._processed, starts)
+ ]
+ for i in range(B):
+ self._processed[i] += valid_lengths[i]
+
+ totals = [vl + r for vl, r in zip(valid_lengths, self.remainder)]
+ usable = [(t // ratio) * ratio for t in totals]
+ max_usable = max(usable)
+ new_remainder = [t % ratio for t in totals]
+
+ # No sequence produced a full window yet
+ if max_usable == 0:
+ for i in range(B):
+ r = self.remainder[i]
+ vl = valid_lengths[i]
+ start = starts[i]
+ self.buf_kv[i, r : r + vl] = kv[i, start : start + vl]
+ self.buf_gate[i, r : r + vl] = gate[i, start : start + vl]
+ self.remainder = new_remainder
+
+ r_kv = mx.zeros((B, 0, D1), dtype=kv.dtype)
+ r_gate = mx.zeros((B, 0, D2), dtype=gate.dtype)
+ r_base = 0
+ return r_kv, r_gate, r_base
+
+ # At least one sequence completed a window
+ r_kv = mx.zeros((B, max_usable, D1), dtype=kv.dtype)
+ r_gate = mx.zeros((B, max_usable, D2), dtype=gate.dtype)
+ r_base = [0] * B
+
+ new_buf_kv = mx.zeros_like(self.buf_kv)
+ new_buf_gate = mx.zeros_like(self.buf_gate)
+
+ for i in range(B):
+ r = self.remainder[i]
+ vl = valid_lengths[i]
+ u = usable[i]
+ nr = new_remainder[i]
+ start = starts[i]
+
+ if u > 0:
+ # Tokens from the buffer (the leftover from last call)
+ if r > 0:
+ r_kv[i, :r] = self.buf_kv[i, :r]
+ r_gate[i, :r] = self.buf_gate[i, :r]
+
+ # Tokens from the new input that complete full windows
+ consume = u - r
+ r_kv[i, r : r + consume] = kv[i, start : start + consume]
+ r_gate[i, r : r + consume] = gate[i, start : start + consume]
+
+ r_base[i] = (
+ offset[i] + start - r
+ if isinstance(offset, mx.array)
+ else offset + start - r
+ )
+
+ # Fill new remainder buffer from the tail of the input
+ if nr > 0:
+ if u > 0:
+ # Old remainder was consumed into usable output;
+ # new remainder is purely from the tail of new input.
+ new_buf_kv[i, :nr] = kv[i, start + vl - nr : start + vl]
+ new_buf_gate[i, :nr] = gate[i, start + vl - nr : start + vl]
+ else:
+ # No full window produced: carry over old buffer and
+ # append any new valid tokens.
+ if r > 0:
+ new_buf_kv[i, :r] = self.buf_kv[i, :r]
+ new_buf_gate[i, :r] = self.buf_gate[i, :r]
+ if vl > 0:
+ new_buf_kv[i, r : r + vl] = kv[i, start : start + vl]
+ new_buf_gate[i, r : r + vl] = gate[i, start : start + vl]
+
+ self.buf_kv = new_buf_kv
+ self.buf_gate = new_buf_gate
+ self.remainder = new_remainder
+
+ r_base = mx.array(r_base)
+ return r_kv, r_gate, r_base
+
+ def update_and_fetch(self, px: mx.array):
+ B, N, D = px.shape
+
+ if N == 0:
+ if self.pooled is None:
+ return mx.zeros((B, 0, D), dtype=px.dtype)
+ return self.pooled
+
+ # Derive how many new pooled tokens each sequence actually produced.
+ new_counts = [
+ (self._processed[i] - self.remainder[i]) // self.ratio
+ - self._pool_lengths[i]
+ for i in range(B)
+ ]
+ max_new = max(new_counts)
+ if max_new == 0:
+ if self.pooled is None:
+ return mx.zeros((B, 0, D), dtype=px.dtype)
+ return self.pooled
+
+ max_pool = max(self._pool_lengths) + max_new
+
+ if self.pooled is None:
+ self.pooled = mx.zeros((B, max_pool, D), dtype=px.dtype)
+ elif self.pooled.shape[1] < max_pool:
+ pad = mx.zeros((B, max_pool - self.pooled.shape[1], D), dtype=px.dtype)
+ self.pooled = mx.concatenate([self.pooled, pad], axis=1)
+
+ for i in range(B):
+ nc = new_counts[i]
+ if nc > 0:
+ pl = self._pool_lengths[i]
+ self.pooled[i, pl : pl + nc] = px[i, :nc]
+ self._pool_lengths[i] = pl + nc
+
+ return self.pooled
+
+ def make_mask(self, L: int = 1, offset=0):
+ if self.pooled is None:
+ return None
+
+ B, P, _ = self.pooled.shape
+ pool_lengths = mx.array(self._pool_lengths)
+
+ # Length based mask
+ pool_idx = mx.arange(P)[None, None, :]
+ valid = pool_idx < pool_lengths[:, None, None]
+
+ # Decode so no need for causal masking
+ if L == 1:
+ if all(pl == P for pl in self._pool_lengths):
+ return None
+ return valid
+
+ # Prompt so we need to combine with causal
+ if isinstance(offset, mx.array):
+ query_pos = offset[:, None] + mx.arange(1, L + 1)
+ else:
+ query_pos = offset + mx.arange(offset + 1, offset + L + 1)[None]
+
+ causal = pool_idx < (query_pos[..., None] // self.ratio)
+ mask = causal & valid
+ return mask
+
+ @property
+ def state(self):
+ return (self.buf_kv, self.buf_gate, self.pooled)
+
+ @state.setter
+ def state(self, v):
+ self.buf_kv, self.buf_gate, self.pooled = v
+
+ @property
+ def meta_state(self):
+ return (
+ self.ratio,
+ self.remainder,
+ self._pool_lengths,
+ self._processed,
+ self.left_padding,
+ )
+
+ @meta_state.setter
+ def meta_state(self, v):
+ if len(v) == 4:
+ self.ratio, self.remainder, self._pool_lengths, self._processed = v
+ self.left_padding = [0] * len(self.remainder)
+ else:
+ (
+ self.ratio,
+ self.remainder,
+ self._pool_lengths,
+ self._processed,
+ self.left_padding,
+ ) = v
+ self._lengths = [2**31] * len(self.remainder)
+
+ def is_trimmable(self):
+ return self.pooled is None
+
+ def trim(self, n):
+ n = min(min(self.remainder), n)
+ for i in range(len(self.remainder)):
+ self.remainder[i] -= n
+ self._processed[i] -= n
+ return n
+
+ def size(self):
+ return 0 if self.pooled is None else self.pooled.shape[1]
+
+ def empty(self):
+ return self.pooled is None and all(r == 0 for r in self.remainder)
+
+ @property
+ def nbytes(self):
+ total = 0
+ if self.buf_kv is not None:
+ total += self.buf_kv.nbytes + self.buf_gate.nbytes
+ if self.pooled is not None:
+ total += self.pooled.nbytes
+ return total
+
+ def filter(self, batch_indices):
+ if isinstance(batch_indices, mx.array):
+ idx_list = batch_indices.tolist()
+ else:
+ idx_list = list(batch_indices)
+
+ if self.buf_kv is not None:
+ self.buf_kv = self.buf_kv[batch_indices]
+ self.buf_gate = self.buf_gate[batch_indices]
+ if self.pooled is not None:
+ self.pooled = self.pooled[batch_indices]
+
+ self.remainder = [self.remainder[i] for i in idx_list]
+ self._pool_lengths = [self._pool_lengths[i] for i in idx_list]
+ self._lengths = [self._lengths[i] for i in idx_list]
+ self._processed = [self._processed[i] for i in idx_list]
+ self.left_padding = [self.left_padding[i] for i in idx_list]
+
+ def extend(self, other):
+ # Merge the remainder buffers
+ if self.buf_kv is None and other.buf_kv is None:
+ pass
+ elif self.buf_kv is not None and other.buf_kv is not None:
+ self.buf_kv = mx.concatenate([self.buf_kv, other.buf_kv], axis=0)
+ self.buf_gate = mx.concatenate([self.buf_gate, other.buf_gate], axis=0)
+ elif self.buf_kv is None:
+ B = len(self.remainder)
+ D1 = other.buf_kv.shape[2]
+ D2 = other.buf_gate.shape[2]
+ self.buf_kv = mx.concatenate(
+ [mx.zeros((B, self.ratio, D1), dtype=other.buf_kv.dtype), other.buf_kv],
+ axis=0,
+ )
+ self.buf_gate = mx.concatenate(
+ [
+ mx.zeros((B, self.ratio, D2), dtype=other.buf_gate.dtype),
+ other.buf_gate,
+ ],
+ axis=0,
+ )
+ else:
+ B2 = len(other.remainder)
+ D1 = self.buf_kv.shape[2]
+ D2 = self.buf_gate.shape[2]
+ self.buf_kv = mx.concatenate(
+ [self.buf_kv, mx.zeros((B2, self.ratio, D1), dtype=self.buf_kv.dtype)],
+ axis=0,
+ )
+ self.buf_gate = mx.concatenate(
+ [
+ self.buf_gate,
+ mx.zeros((B2, self.ratio, D2), dtype=self.buf_gate.dtype),
+ ],
+ axis=0,
+ )
+
+ # Merge the pooled buffers
+ if self.pooled is None and other.pooled is None:
+ pass
+ else:
+ B1 = len(self.remainder)
+ B2 = len(other.remainder)
+ P1 = 0 if self.pooled is None else self.pooled.shape[1]
+ P2 = 0 if other.pooled is None else other.pooled.shape[1]
+ max_P = max(P1, P2)
+
+ if max_P > 0:
+ if self.pooled is not None:
+ D = self.pooled.shape[2]
+ else:
+ D = other.pooled.shape[2]
+ dt = (self.pooled if self.pooled is not None else other.pooled).dtype
+
+ def pad_pool(pooled, B, P):
+ if pooled is None:
+ return mx.zeros((B, max_P, D), dtype=dt)
+ if P < max_P:
+ pad = mx.zeros((pooled.shape[0], max_P - P, D), dtype=dt)
+ return mx.concatenate([pooled, pad], axis=1)
+ return pooled
+
+ self.pooled = mx.concatenate(
+ [pad_pool(self.pooled, B1, P1), pad_pool(other.pooled, B2, P2)],
+ axis=0,
+ )
+
+ self.remainder = self.remainder + other.remainder
+ self._pool_lengths = self._pool_lengths + other._pool_lengths
+ self._lengths = self._lengths + other._lengths
+ self._processed = self._processed + other._processed
+ self.left_padding = self.left_padding + other.left_padding
+
+ def extract(self, idx):
+ cache = PoolingCache(self.ratio)
+ pl = self._pool_lengths[idx]
+ r = self.remainder[idx]
+
+ if self.pooled is not None and pl > 0:
+ cache.pooled = mx.contiguous(self.pooled[idx : idx + 1, :pl])
+
+ if self.buf_kv is not None and r > 0:
+ cache.buf_kv = mx.contiguous(self.buf_kv[idx : idx + 1])
+ cache.buf_gate = mx.contiguous(self.buf_gate[idx : idx + 1])
+ cache.remainder = r
+
+ return cache
+
+ @classmethod
+ def merge(cls, caches, prefix_lens=None):
+ """Merge a list of PoolingCache instances into a BatchPoolingCache."""
+ # APC passes prefix lengths to custom merge implementations. Pooling
+ # caches derive progress from each row's pooled length and remainder.
+ del prefix_lens
+ B = len(caches)
+ if not all(c.ratio == caches[0].ratio for c in caches):
+ raise ValueError(
+ "BatchPoolingCache can only merge caches with the same ratio"
+ )
+ ratio = caches[0].ratio
+ batch_cache = cls(ratio, [0] * B)
+
+ # Check if all caches are empty
+ if all(c.empty() for c in caches):
+ return batch_cache
+
+ # Merge pooled buffers
+ pool_sizes = [c.size() for c in caches]
+ max_pool = max(pool_sizes)
+ if max_pool > 0:
+ D = next(c.pooled.shape[2] for c in caches if c.pooled is not None)
+ dt = next(c.pooled.dtype for c in caches if c.pooled is not None)
+ pooled = mx.zeros((B, max_pool, D), dtype=dt)
+ for i, c in enumerate(caches):
+ if c.pooled is not None:
+ ps = c.pooled.shape[1]
+ pooled[i, :ps] = c.pooled[0]
+ batch_cache.pooled = pooled
+
+ batch_cache._pool_lengths = pool_sizes
+ batch_cache.remainder = [c.remainder for c in caches]
+ batch_cache._processed = [
+ c.remainder + ps * ratio for c, ps in zip(caches, pool_sizes)
+ ]
+
+ # Merge remainder buffers
+ has_buf = any(c.buf_kv is not None for c in caches)
+ if has_buf:
+ D1 = next(c.buf_kv.shape[2] for c in caches if c.buf_kv is not None)
+ D2 = next(c.buf_gate.shape[2] for c in caches if c.buf_gate is not None)
+ dt = next(c.buf_kv.dtype for c in caches if c.buf_kv is not None)
+ buf_kv = mx.zeros((B, ratio, D1), dtype=dt)
+ buf_gate = mx.zeros((B, ratio, D2), dtype=dt)
+ for i, c in enumerate(caches):
+ if c.buf_kv is not None and c.remainder > 0:
+ buf_kv[i, : c.remainder] = c.buf_kv[0, : c.remainder]
+ buf_gate[i, : c.remainder] = c.buf_gate[0, : c.remainder]
+ batch_cache.buf_kv = buf_kv
+ batch_cache.buf_gate = buf_gate
+
+ return batch_cache
+
+
+class SimpleKVCache:
+ """A simple key-value cache for transformer attention layers.
+
+ Stores and concatenates key/value tensors along sequence dimension.
+ """
+
+ def __init__(self):
+ self.keys = None
+ self.values = None
+ self.cache_length = 0
+
+ def update_and_fetch(self, keys, values):
+ """Update cache with new key/value tensors and return full cache.
+
+ Args:
+ keys: New key tensor to add [batch, heads, seq_len, head_dim]
+ values: New value tensor to add [batch, heads, seq_len, head_dim]
+
+ Returns:
+ Tuple of (cached_keys, cached_values) containing full cache history
+ """
+ if self.cache_length == 0:
+ # First update - just store tensors
+ self.keys = keys
+ self.values = values
+ else:
+ # Concatenate with existing cache along sequence dimension
+ self.keys = mx.concatenate([self.keys, keys], axis=2)
+ self.values = mx.concatenate([self.values, values], axis=2)
+
+ self.cache_length += keys.shape[2]
+ return self.keys, self.values
+
+ def fetch(self):
+ return self.keys, self.values
+
+ def update(self, keys, values):
+ """Update cache with new key/value tensors without returning.
+
+ Args:
+ keys: New key tensor to store
+ values: New value tensor to store
+ """
+ self.keys = keys
+ self.values = values
+ self.cache_length += keys.shape[2]
+
+
+class StaticPrefixKVCache(_BaseCache):
+ """Fixed-capacity KV cache with prefix fetch semantics.
+
+ ``update_and_fetch`` returns only the populated prefix so normal encoder
+ prefill attention sees the same shapes as a dynamic cache. Decoder code can
+ use ``decoder_state`` to attend over the full fixed allocation together with
+ an attention mask that hides unpopulated entries.
+ """
+
+ def __init__(self, max_size: int, step: int = 256, read_only: bool = False):
+ self.max_size = int(max_size)
+ self.step = int(step)
+ self.keys = None
+ self.values = None
+ self.offset = 0
+ self.read_only = read_only
+
+ @classmethod
+ def from_prefix(cls, other: "StaticPrefixKVCache") -> "StaticPrefixKVCache":
+ cache = cls(other.max_size, other.step, read_only=True)
+ cache.reset_from_prefix(other)
+ return cache
+
+ def reset_from_prefix(self, other: "StaticPrefixKVCache") -> None:
+ self.keys = other.keys
+ self.values = other.values
+ self.offset = other.offset
+ self.max_size = other.max_size
+ self.step = other.step
+ self.read_only = True
+
+ def _capacity_for(self, needed: int) -> int:
+ if needed <= self.max_size:
+ return self.max_size
+ return ((needed + self.step - 1) // self.step) * self.step
+
+ def _ensure_capacity(self, keys: mx.array, values: mx.array, needed: int) -> None:
+ if self.keys is not None and needed <= self.keys.shape[2]:
+ return
+
+ B, n_kv_heads, _, k_head_dim = keys.shape
+ v_head_dim = values.shape[-1]
+ capacity = self._capacity_for(needed)
+ new_keys = mx.zeros((B, n_kv_heads, capacity, k_head_dim), dtype=keys.dtype)
+ new_values = mx.zeros((B, n_kv_heads, capacity, v_head_dim), dtype=values.dtype)
+ if self.keys is not None and self.offset > 0:
+ new_keys[..., : self.offset, :] = self.keys[..., : self.offset, :]
+ new_values[..., : self.offset, :] = self.values[..., : self.offset, :]
+ self.keys = new_keys
+ self.values = new_values
+ self.max_size = capacity
+
+ def update_and_fetch(
+ self, keys: mx.array, values: mx.array
+ ) -> Tuple[mx.array, mx.array]:
+ if self.read_only:
+ if self.keys is None:
+ return keys, values
+ return (
+ mx.concatenate([self.keys[..., : self.offset, :], keys], axis=2),
+ mx.concatenate([self.values[..., : self.offset, :], values], axis=2),
+ )
+
+ seq_len = keys.shape[2]
+ prev = self.offset
+ end = prev + seq_len
+ self._ensure_capacity(keys, values, end)
+ self.keys[..., prev:end, :] = keys
+ self.values[..., prev:end, :] = values
+ self.offset = end
+ return self.keys[..., : self.offset, :], self.values[..., : self.offset, :]
+
+ @property
+ def state(self):
+ if self.keys is None:
+ return None, None
+ return self.keys[..., : self.offset, :], self.values[..., : self.offset, :]
+
+ @state.setter
+ def state(self, v):
+ if v is not None and len(v) == 2:
+ self.keys, self.values = v
+ if self.keys is not None:
+ self.offset = self.keys.shape[2]
+ self.max_size = self.keys.shape[2]
+
+ @property
+ def decoder_state(self):
+ if self.keys is None:
+ return None, None
+ return self.keys, self.values
+
+ @property
+ def meta_state(self):
+ return tuple(map(str, (self.max_size, self.step, self.offset)))
+
+ @meta_state.setter
+ def meta_state(self, v):
+ self.max_size, self.step, self.offset = map(int, v)
+
+ def is_trimmable(self):
+ return True
+
+ def trim(self, n):
+ n = min(int(n), self.offset)
+ self.offset -= n
+ return n
+
+ def empty(self):
+ return self.keys is None
+
+ @property
+ def nbytes(self):
+ if self.keys is None:
+ return 0
+ return self.keys.nbytes + self.values.nbytes
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/config.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/config.py
new file mode 100644
index 0000000000..8b8e213ac3
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/config.py
@@ -0,0 +1,206 @@
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional, Union
+
+from ..base import BaseModelConfig
+from ..qwen3_5.config import resolve_qwen_eos_token_id, sanitize_quantization_config
+from ..qwen3_vl.config import VisionConfig as Qwen3VLVisionConfig
+from ..qwen3_vl.config import _config_kwargs, _maybe_deserialize_config
+
+
+@dataclass
+class VisionConfig(Qwen3VLVisionConfig):
+ model_type: str = "qwen4_exp"
+
+ def __post_init__(self):
+ if self.deepstack_visual_indexes:
+ raise ValueError(
+ "Qwen4-Exp does not use deepstack visual features, but "
+ f"deepstack_visual_indexes={self.deepstack_visual_indexes} was set."
+ )
+ self.deepstack_visual_indexes = []
+
+
+@dataclass
+class TextConfig(BaseModelConfig):
+ model_type: str
+ hidden_size: int
+ num_hidden_layers: int
+ num_attention_heads: int
+ linear_num_value_heads: int
+ linear_num_key_heads: int
+ linear_key_head_dim: int
+ linear_value_head_dim: int
+ linear_conv_kernel_dim: int
+ num_experts: int
+ num_experts_per_tok: int
+ shared_expert_intermediate_size: int
+ moe_intermediate_size: int
+ rms_norm_eps: float
+ vocab_size: int
+ num_key_value_heads: int
+ max_position_embeddings: int
+ hc_count: int = 4
+ hc_lowrank: int = 320
+ head_dim: Optional[int] = None
+ layer_types: Optional[List[str]] = None
+ full_attention_interval: int = 4
+ ple_layer_ids: List[int] = field(default_factory=list)
+ ple_embed_dim: Optional[int] = None
+ ple_conv_kernel_size: int = 4
+ ngram_size: int = 3
+ heads_per_ngram: int = 8
+ ngram_vocab_size_base: int = 20_000_000
+ make_ngram_vocab_size_divisible_by: int = 128
+ split_ngram_parts: int = 128
+ seed: int = 1234
+ indexer_n_heads: int = 4
+ indexer_kv_heads: int = 1
+ indexer_head_dim: int = 128
+ indexer_budget: int = 2048
+ indexer_compress_ratio: int = 4
+ output_gate_type: str = "sigmoid"
+ hidden_act: str = "silu"
+ norm_topk_prob: bool = True
+ mtp_num_hidden_layers: int = 1
+ mtp_use_dedicated_embeddings: bool = False
+ mtp: Optional[Dict] = None
+ eos_token_id: Optional[Union[int, List[int]]] = None
+ tie_word_embeddings: bool = False
+ attention_bias: bool = False
+ rope_parameters: Optional[Dict[str, Union[float, str, bool, List[int]]]] = field(
+ default_factory=lambda: {
+ "type": "default",
+ "mrope_section": [11, 11, 10],
+ "rope_theta": 10_000_000,
+ "partial_rotary_factor": 0.25,
+ }
+ )
+
+ def __post_init__(self):
+ if self.head_dim is None:
+ self.head_dim = self.hidden_size // self.num_attention_heads
+ if self.ple_embed_dim is None:
+ self.ple_embed_dim = self.hidden_size
+
+ self.ple_layer_ids = sorted(set(self.ple_layer_ids or []))
+ if self.layer_types is None:
+ self.layer_types = [
+ (
+ "linear_attention"
+ if (i + 1) % self.full_attention_interval
+ else "qwen_sparse_attention"
+ )
+ for i in range(self.num_hidden_layers)
+ ]
+ else:
+ self.layer_types = [
+ "qwen_sparse_attention" if kind == "full_attention" else kind
+ for kind in self.layer_types
+ ]
+
+ if len(self.layer_types) != self.num_hidden_layers:
+ raise ValueError(
+ "layer_types must contain one entry per decoder layer: "
+ f"{len(self.layer_types)} != {self.num_hidden_layers}"
+ )
+ unsupported = set(self.layer_types) - {
+ "linear_attention",
+ "qwen_sparse_attention",
+ }
+ if unsupported:
+ raise ValueError(f"Unsupported Qwen4-Exp layer types: {unsupported}")
+ if self.hc_count <= 1:
+ raise ValueError("Qwen4-Exp requires hc_count > 1")
+ if self.output_gate_type not in {"sigmoid", "silu"}:
+ raise ValueError("Qwen4-Exp output_gate_type must be 'sigmoid' or 'silu'")
+ if self.indexer_kv_heads != 1:
+ raise ValueError("Qwen4-Exp QSA requires indexer_kv_heads=1")
+ if self.indexer_budget % self.indexer_compress_ratio:
+ raise ValueError(
+ "indexer_budget must be divisible by indexer_compress_ratio"
+ )
+ ngram_heads = (self.ngram_size - 1) * self.heads_per_ngram
+ if ngram_heads <= 0 or self.ple_embed_dim % ngram_heads:
+ raise ValueError(
+ "ple_embed_dim must be divisible by the total number of n-gram heads"
+ )
+ invalid_ple_layers = [
+ layer_id
+ for layer_id in self.ple_layer_ids
+ if layer_id < 1 or layer_id > self.num_hidden_layers
+ ]
+ if invalid_ple_layers:
+ raise ValueError(f"Invalid one-indexed PLE layers: {invalid_ple_layers}")
+ non_linear_ple_layers = [
+ layer_id
+ for layer_id in self.ple_layer_ids
+ if self.layer_types[layer_id - 1] != "linear_attention"
+ ]
+ if non_linear_ple_layers:
+ raise ValueError(
+ "PLE is only supported on linear-attention layers, got "
+ f"{non_linear_ple_layers}"
+ )
+ if self.ple_layer_ids and self.eos_token_id is None:
+ raise ValueError("eos_token_id is required when PLE is enabled")
+
+ if self.rope_parameters:
+ if (
+ "type" not in self.rope_parameters
+ and "rope_type" in self.rope_parameters
+ ):
+ self.rope_parameters["type"] = self.rope_parameters.pop("rope_type")
+ required_keys = {
+ "mrope_section",
+ "type",
+ "rope_theta",
+ "partial_rotary_factor",
+ }
+ if not required_keys.issubset(self.rope_parameters):
+ raise ValueError(f"rope_parameters must contain keys {required_keys}")
+
+
+@dataclass
+class ModelConfig(BaseModelConfig):
+ text_config: TextConfig
+ vision_config: VisionConfig
+ model_type: str
+ ignore_index: int = -100
+ image_token_id: int = 248056
+ video_token_id: int = 248057
+ image_token_index: Optional[int] = None
+ video_token_index: Optional[int] = None
+ vision_start_token_id: int = 248053
+ vision_end_token_id: int = 248054
+ vocab_size: int = 248320
+ eos_token_id: Optional[Union[int, List[int]]] = None
+ quantization: Optional[Dict] = None
+ quantization_config: Optional[Dict] = None
+
+ def __post_init__(self):
+ if self.image_token_index is None:
+ self.image_token_index = self.image_token_id
+ if self.video_token_index is None:
+ self.video_token_index = self.video_token_id
+ self.eos_token_id = resolve_qwen_eos_token_id(
+ self.eos_token_id, self.text_config
+ )
+ quantization = self.quantization
+ self.quantization = sanitize_quantization_config(quantization)
+ if self.quantization_config == quantization:
+ self.quantization_config = self.quantization
+ else:
+ self.quantization_config = sanitize_quantization_config(
+ self.quantization_config
+ )
+
+ @classmethod
+ def from_dict(cls, params):
+ params = dict(params)
+ params["vision_config"] = _maybe_deserialize_config(
+ VisionConfig, params.get("vision_config")
+ )
+ params["text_config"] = _maybe_deserialize_config(
+ TextConfig, params.get("text_config"), require_all_fields=True
+ )
+ return cls(**_config_kwargs(cls, params))
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py
new file mode 100644
index 0000000000..e32f04fc89
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py
@@ -0,0 +1,449 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Three Metal kernels for small Qwen4 hyper-connection inputs.
+
+Fuses per-stream RMS norm, down/inject projections with activation, and the up
+projection with stream mixing. Supports at most 16 BF16 rows, four streams,
+and affine group-size-64 projections with 4/5/6/8-bit weights. FP32 epilogues
+can round differently from the canonical BF16 operations.
+
+Each kernel specialization is evaluated once inside the failure handler to
+catch lazy compilation errors. Later calls stay lazy; errors during their
+external evaluation propagate to the caller. Disable with OMLX_QWEN4_HC_FUSED=0.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+
+import mlx.core as mx
+import mlx.nn as nn
+
+from .hc_projection import _HEADER
+
+logger = logging.getLogger(__name__)
+
+MAX_ROWS = 16
+_GROUP_SIZE = 64
+_SUPPORTED_BITS = (4, 5, 6, 8)
+_DISABLED = os.environ.get("OMLX_QWEN4_HC_FUSED", "1").strip().lower() in {
+ "0",
+ "false",
+ "no",
+ "off",
+}
+_KERNELS: dict[str, object] = {}
+_VALIDATED: set[tuple] = set()
+_RUNTIME_FAILED = False
+_FAILURE_LOGGED = False
+_INELIGIBLE_LOGGED = False
+
+_N_SOURCE = r"""
+ const uint row = threadgroup_position_in_grid.z;
+ const uint s = threadgroup_position_in_grid.y;
+ const uint t = thread_index_in_threadgroup;
+ const uint sg = simdgroup_index_in_threadgroup;
+ const uint lane = thread_index_in_simdgroup;
+ threadgroup float part[8];
+ constexpr int PER = (H + 255) / 256;
+ const device T* xp = x + (size_t)row * K + (size_t)s * H;
+ const device T* wp = w + (size_t)s * H;
+ device T* op = xn + (size_t)row * K + (size_t)s * H;
+ float v[PER];
+ float ss = 0.0f;
+ for (int i = 0; i < PER; ++i) {
+ const int k = t + i * 256;
+ v[i] = (k < H) ? float(xp[k]) : 0.0f;
+ ss += v[i] * v[i];
+ }
+ ss = simd_sum(ss);
+ if (lane == 0) part[sg] = ss;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ float tot = 0.0f;
+ for (int i = 0; i < 8; ++i) tot += part[i];
+ const float inv = metal::rsqrt(tot / float(H) + eps[0]);
+ for (int i = 0; i < PER; ++i) {
+ const int k = t + i * 256;
+ if (k < H) op[k] = T(v[i] * inv * (1.0f + float(wp[k])));
+ }
+"""
+
+_D_SOURCE = r"""
+ const uint tg = threadgroup_position_in_grid.y;
+ const uint row = threadgroup_position_in_grid.z;
+ const uint sg = simdgroup_index_in_threadgroup;
+ const uint lane = thread_index_in_simdgroup;
+ constexpr int KS = 4;
+ constexpr int SLICE = K / KS;
+ constexpr int GROUPS = K / 64;
+ threadgroup float part[KS][8];
+ const device T* x = xn + (size_t)row * K;
+ const int rg = int(sg & 1);
+ const int ks = int(sg >> 1);
+ if (tg < R / 8) {
+ constexpr int PF = hc_pack_factor();
+ constexpr int BP = hc_bytes_per_pack();
+ constexpr int ROW_BYTES = K * BP / PF;
+ constexpr int PPT = 2;
+ constexpr int VPT = PF * PPT;
+ constexpr int BLOCK = VPT * 32;
+ constexpr int SCALE_STEP = 64 / VPT;
+ const int out_row = int(tg) * 8 + rg * 4;
+ const device uint8_t* wp = (const device uint8_t*)down_w
+ + out_row * ROW_BYTES + ks * (SLICE * BP / PF) + int(lane) * PPT * BP;
+ const device T* sp = down_s + out_row * GROUPS + ks * (SLICE / 64)
+ + int(lane) / SCALE_STEP;
+ const device T* bp = down_b + out_row * GROUPS + ks * (SLICE / 64)
+ + int(lane) / SCALE_STEP;
+ const device T* xp = x + ks * SLICE + int(lane) * VPT;
+ float result[4] = {0.0f};
+ float xv[VPT];
+ constexpr int TAIL = SLICE % BLOCK;
+ for (int k = 0; k < SLICE - TAIL; k += BLOCK) {
+ float sum = hc_load_vector(xp, xv);
+ for (int r = 0; r < 4; ++r) {
+ result[r] += hc_qdot(
+ wp + r * ROW_BYTES, xv,
+ float(sp[r * GROUPS]), float(bp[r * GROUPS]), sum);
+ }
+ wp += BLOCK * BP / PF;
+ sp += BLOCK / 64;
+ bp += BLOCK / 64;
+ xp += BLOCK;
+ }
+ // Load only lanes inside the tail; all lanes must join simd_sum.
+ if (TAIL > 0 && int(lane) * VPT < TAIL) {
+ float sum = hc_load_vector(xp, xv);
+ for (int r = 0; r < 4; ++r) {
+ result[r] += hc_qdot(
+ wp + r * ROW_BYTES, xv,
+ float(sp[r * GROUPS]), float(bp[r * GROUPS]), sum);
+ }
+ }
+ for (int r = 0; r < 4; ++r) {
+ float v = simd_sum(result[r]);
+ if (lane == 0) part[ks][rg * 4 + r] = v;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (sg < 2 && lane < 4) {
+ const int r = int(lane);
+ float v = part[0][sg * 4 + r] + part[1][sg * 4 + r]
+ + part[2][sg * 4 + r] + part[3][sg * 4 + r];
+ v = v / float(HC);
+ act[(size_t)row * R + int(tg) * 8 + int(sg) * 4 + r]
+ = T(v / (1.0f + metal::exp(-v)));
+ }
+ return;
+ }
+ if (INJ == 0 || rg != 0) return;
+ {
+ constexpr int PF = hc_pack_factor();
+ constexpr int BP = hc_bytes_per_pack();
+ constexpr int ROW_BYTES = K * BP / PF;
+ constexpr int PPT = 1;
+ constexpr int VPT = PF;
+ constexpr int BLOCK = VPT * 32;
+ constexpr int SCALE_STEP = 64 / VPT;
+ const device uint8_t* wp = (const device uint8_t*)inject_w
+ + ks * (SLICE * BP / PF) + int(lane) * BP;
+ const device T* sp = inject_s + ks * (SLICE / 64) + int(lane) / SCALE_STEP;
+ const device T* bp = inject_b + ks * (SLICE / 64) + int(lane) / SCALE_STEP;
+ const device T* xp = x + ks * SLICE + int(lane) * VPT;
+ float result[HC] = {0.0f};
+ float xv[VPT];
+ constexpr int TAIL = SLICE % BLOCK;
+ for (int k = 0; k < SLICE - TAIL; k += BLOCK) {
+ float sum = hc_load_vector(xp, xv);
+ for (int r = 0; r < HC; ++r) {
+ result[r] += hc_qdot(
+ wp + r * ROW_BYTES, xv,
+ float(sp[r * GROUPS]), float(bp[r * GROUPS]), sum);
+ }
+ wp += BLOCK * BP / PF;
+ sp += BLOCK / 64;
+ bp += BLOCK / 64;
+ xp += BLOCK;
+ }
+ if (TAIL > 0 && int(lane) * VPT < TAIL) {
+ float sum = hc_load_vector(xp, xv);
+ for (int r = 0; r < HC; ++r) {
+ result[r] += hc_qdot(
+ wp + r * ROW_BYTES, xv,
+ float(sp[r * GROUPS]), float(bp[r * GROUPS]), sum);
+ }
+ }
+ for (int r = 0; r < HC; ++r) {
+ float v = simd_sum(result[r]);
+ if (lane == 0) part[ks][r] = v;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (sg == 0 && lane < HC) {
+ const int r = int(lane);
+ float v = part[0][r] + part[1][r] + part[2][r] + part[3][r];
+ v = v / float(HC);
+ inj[(size_t)row * HC + r] = T(2.0f / (1.0f + metal::exp(-v)));
+ }
+ }
+"""
+
+_U_SOURCE = r"""
+ const uint g = threadgroup_position_in_grid.y;
+ const uint t = thread_index_in_threadgroup;
+ const int h = int(g) * 64 + int(t >> 2);
+ const int s = int(t & 3);
+ const int n = s * H + h;
+ constexpr int PF = hc_pack_factor();
+ constexpr int BP = hc_bytes_per_pack();
+ constexpr int ROW_BYTES = R * BP / PF;
+ constexpr int GROUPS_R = R / 64;
+ constexpr int CH = 2 * PF;
+ constexpr int CPG = 64 / CH;
+ const device uint8_t* w = (const device uint8_t*)up_w + (size_t)n * ROW_BYTES;
+ const device T* sp = up_s + (size_t)n * GROUPS_R;
+ const device T* bp = up_b + (size_t)n * GROUPS_R;
+ float xv[CH];
+ for (int r = 0; r < S; ++r) {
+ const device T* a = act + (size_t)r * R;
+ float acc = 0.0f;
+ for (int gq = 0; gq < GROUPS_R; ++gq) {
+ const float sc = float(sp[gq]);
+ const float bi = float(bp[gq]);
+ for (int c = 0; c < CPG; ++c) {
+ const int e = gq * 64 + c * CH;
+ float sum = hc_load_vector(a + e, xv);
+ acc += hc_qdot(w + e * BP / PF, xv, sc, bi, sum);
+ }
+ }
+ float gate = 1.0f / (1.0f + metal::exp(-acc));
+ float v = gate * float(xn[(size_t)r * K + n]);
+ v += simd_shuffle_down(v, 1);
+ v += simd_shuffle_down(v, 2);
+ if (s == 0) mixed[(size_t)r * H + h] = T(v / float(HC));
+ }
+"""
+
+
+def _kernel(
+ name: str,
+ input_names: list[str],
+ output_names: list[str],
+ source: str,
+ header: str = "",
+):
+ kernel = _KERNELS.get(name)
+ if kernel is None:
+ kernel = mx.fast.metal_kernel(
+ name=name,
+ input_names=input_names,
+ output_names=output_names,
+ header=header,
+ source=source,
+ ensure_row_contiguous=True,
+ )
+ _KERNELS[name] = kernel
+ return kernel
+
+
+def enabled() -> bool:
+ return not _DISABLED and not _RUNTIME_FAILED
+
+
+def _quantized_ok(projection) -> bool:
+ return (
+ type(projection) is nn.QuantizedLinear
+ and getattr(projection, "group_size", None) == _GROUP_SIZE
+ and getattr(projection, "bits", None) in _SUPPORTED_BITS
+ and getattr(projection, "mode", "affine") == "affine"
+ and "bias" not in projection
+ and isinstance(getattr(projection, "weight", None), mx.array)
+ and projection.weight.dtype == mx.uint32
+ and isinstance(getattr(projection, "scales", None), mx.array)
+ and isinstance(getattr(projection, "biases", None), mx.array)
+ and projection.scales.dtype == mx.bfloat16
+ and projection.biases.dtype == mx.bfloat16
+ )
+
+
+def _ineligible(reason: str) -> bool:
+ """Log the first unsupported model layout per process."""
+ global _INELIGIBLE_LOGGED
+ if not _INELIGIBLE_LOGGED:
+ _INELIGIBLE_LOGGED = True
+ logger.info(
+ "Qwen4 fused hyper-connection kernels not used for this model (%s); "
+ "the canonical path stays in effect",
+ reason,
+ )
+ return False
+
+
+def compatible(module, hyper_input) -> bool:
+ """Whether ``module`` (a Qwen4ExpGatedResidual) can take the fused path for ``hyper_input``."""
+ if not enabled():
+ return False
+ if not (
+ isinstance(hyper_input, mx.array)
+ and hyper_input.ndim == 3
+ and hyper_input.dtype == mx.bfloat16
+ and 1 <= hyper_input.shape[0] * hyper_input.shape[1] <= MAX_ROWS
+ ):
+ return False
+ if hasattr(module, "input_inject_weight"):
+ return _ineligible("combined input projection layout")
+ hc_count = getattr(module, "hc_count", None)
+ hidden = getattr(module, "hidden_size", None)
+ lowrank = getattr(module, "hc_lowrank", None)
+ if not (
+ isinstance(hc_count, int)
+ and isinstance(hidden, int)
+ and isinstance(lowrank, int)
+ and hc_count == 4
+ # The up grid and quantization groups require 64-element alignment.
+ and hidden % 64 == 0
+ and lowrank % 64 == 0
+ and hyper_input.shape[2] == hc_count * hidden
+ ):
+ return _ineligible(
+ f"geometry hidden_size={hidden} hc_lowrank={lowrank} hc_count={hc_count}"
+ )
+ norm = getattr(module, "hc_norm", None)
+ if not (
+ norm is not None
+ and getattr(norm, "group_size", None) == hidden
+ and isinstance(getattr(norm, "weight", None), mx.array)
+ and norm.weight.dtype == mx.bfloat16
+ and norm.weight.shape == (hc_count * hidden,)
+ ):
+ return _ineligible("hc_norm layout")
+ if not (
+ _quantized_ok(getattr(module, "input_mix_weight_down", None))
+ and _quantized_ok(getattr(module, "input_mix_weight_up", None))
+ ):
+ return _ineligible(
+ "projection quantisation (need affine group-size-64 4/5/6/8-bit with bf16 scales)"
+ )
+ if "block_inject_weight" in module and not _quantized_ok(
+ module.block_inject_weight
+ ):
+ return _ineligible("block_inject_weight quantisation")
+ return mx.default_device() == mx.gpu and mx.metal.is_available()
+
+
+def _eps_array(module) -> mx.array:
+ eps = getattr(module, "_omlx_hc_fused_eps", None)
+ if eps is None:
+ eps = mx.array([float(module.hc_norm.eps)], dtype=mx.float32)
+ mx.eval(eps)
+ module._omlx_hc_fused_eps = eps
+ return eps
+
+
+def fused_forward(module, hyper_input):
+ """Return fused outputs, or None on construction or first-evaluation failure."""
+ global _RUNTIME_FAILED, _FAILURE_LOGGED
+ try:
+ hc, hidden, lowrank = module.hc_count, module.hidden_size, module.hc_lowrank
+ width = hc * hidden
+ batch, seq, _ = hyper_input.shape
+ rows = batch * seq
+ down, up = module.input_mix_weight_down, module.input_mix_weight_up
+ inject = module.block_inject_weight if "block_inject_weight" in module else None
+ flat = hyper_input.reshape(rows, width)
+ dtype = hyper_input.dtype
+ normed = _kernel(
+ "omlx_qwen4_hc_fused_norm", ["x", "w", "eps"], ["xn"], _N_SOURCE
+ )(
+ inputs=[flat, module.hc_norm.weight, _eps_array(module)],
+ template=[("T", dtype), ("K", width), ("H", hidden)],
+ grid=(256, hc, rows),
+ threadgroup=(256, 1, 1),
+ output_shapes=[(rows, width)],
+ output_dtypes=[dtype],
+ )[
+ 0
+ ]
+ if inject is not None:
+ inject_tensors = (inject.weight, inject.scales, inject.biases)
+ else:
+ inject_tensors = (down.weight, down.scales, down.biases)
+ act, injection = _kernel(
+ "omlx_qwen4_hc_fused_down",
+ ["xn", "down_w", "down_s", "down_b", "inject_w", "inject_s", "inject_b"],
+ ["act", "inj"],
+ _D_SOURCE,
+ header=_HEADER,
+ )(
+ inputs=[normed, down.weight, down.scales, down.biases, *inject_tensors],
+ template=[
+ ("T", dtype),
+ ("BITS_D", down.bits),
+ ("BITS_I", inject.bits if inject is not None else down.bits),
+ ("K", width),
+ ("R", lowrank),
+ ("HC", hc),
+ ("INJ", 1 if inject is not None else 0),
+ ],
+ grid=(32, 8 * (lowrank // 8 + 1), rows),
+ threadgroup=(32, 8, 1),
+ output_shapes=[(rows, lowrank), (rows, hc)],
+ output_dtypes=[dtype, dtype],
+ )
+ mixed = _kernel(
+ "omlx_qwen4_hc_fused_up",
+ ["xn", "act", "up_w", "up_s", "up_b"],
+ ["mixed"],
+ _U_SOURCE,
+ header=_HEADER,
+ )(
+ inputs=[normed, act, up.weight, up.scales, up.biases],
+ template=[
+ ("T", dtype),
+ ("BITS_U", up.bits),
+ ("K", width),
+ ("R", lowrank),
+ ("HC", hc),
+ ("H", hidden),
+ ("S", rows),
+ ],
+ grid=(256, hidden // 64, 1),
+ threadgroup=(256, 1, 1),
+ output_shapes=[(rows, hidden)],
+ output_dtypes=[dtype],
+ )[
+ 0
+ ]
+ signature = (
+ dtype,
+ hc,
+ hidden,
+ lowrank,
+ rows,
+ down.bits,
+ up.bits,
+ inject.bits if inject is not None else None,
+ )
+ if signature not in _VALIDATED:
+ # Metal compilation is lazy. Validate once, without synchronizing
+ # subsequent layers or decode steps using the same specialization.
+ if inject is None:
+ mx.eval(mixed)
+ else:
+ mx.eval(mixed, injection)
+ _VALIDATED.add(signature)
+ mixed = mixed.reshape(batch, seq, hidden)
+ if inject is None:
+ return mixed
+ return mixed, hyper_input, injection.reshape(batch, seq, hc)
+ except Exception as exc: # noqa: BLE001 - optional native path
+ _RUNTIME_FAILED = True
+ if not _FAILURE_LOGGED:
+ _FAILURE_LOGGED = True
+ logger.warning(
+ "Qwen4 fused hyper-connection kernels failed closed; using the "
+ "canonical path: %s",
+ exc,
+ )
+ return None
+
+
+__all__ = ["MAX_ROWS", "compatible", "enabled", "fused_forward"]
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_projection.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_projection.py
new file mode 100644
index 0000000000..d490d7eb07
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_projection.py
@@ -0,0 +1,420 @@
+# SPDX-License-Identifier: Apache-2.0
+
+"""Lossless one-dispatch Qwen4 hyperconnection input projection.
+
+The Metal arithmetic in this module is transcribed from MLX core at pinned
+commit ``ceab91938`` (``mlx/backend/metal/kernels/quantized.h``): its first
+320 rows use MLX's literal ``qmv_fast`` traversal and its final four rows use
+the literal standalone-N=4 general ``qmv`` traversal. This preserves both raw
+projection outputs while avoiding the two-dispatch canonical implementation.
+
+MLX is Copyright © 2023 Apple Inc. and licensed under the MIT License:
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+
+import mlx.core as mx
+import mlx.nn as nn
+
+logger = logging.getLogger(__name__)
+
+_HC_COUNT = 4
+_HIDDEN_SIZE = 2560
+_STREAM_WIDTH = _HC_COUNT * _HIDDEN_SIZE
+_LOW_RANK = 320
+_GROUP_SIZE = 64
+_SUPPORTED_BITS = (4, 5, 6, 8)
+_DISABLED = os.environ.get("OMLX_QWEN4_HC_HYBRID", "1").strip().lower() in {
+ "0",
+ "false",
+ "off",
+ "no",
+}
+_KERNEL = None
+_RUNTIME_FAILED = False
+_FAILURE_LOGGED = False
+
+
+_HEADER = r"""
+using namespace metal;
+
+template
+inline constexpr short hc_pack_factor() {
+ return bits == 5 ? 8 : (bits == 6 ? 4 : 32 / bits);
+}
+
+template
+inline constexpr short hc_bytes_per_pack() {
+ constexpr int power_of_2_bits = (bits & (bits - 1)) == 0;
+ return power_of_2_bits ? 4 : (bits == 5 ? 5 : 3);
+}
+
+template
+inline float hc_load_vector(const device T* x, thread float* xt) {
+ float sum = 0.0f;
+ if (bits == 4) {
+ for (int i = 0; i < N; i += 4) {
+ sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3];
+ xt[i] = x[i];
+ xt[i + 1] = x[i + 1] / 16.0f;
+ xt[i + 2] = x[i + 2] / 256.0f;
+ xt[i + 3] = x[i + 3] / 4096.0f;
+ }
+ } else if (bits == 5) {
+ for (int i = 0; i < N; i += 8) {
+ sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]
+ + x[i + 4] + x[i + 5] + x[i + 6] + x[i + 7];
+ xt[i] = x[i];
+ xt[i + 1] = x[i + 1] / 32.0f;
+ xt[i + 2] = x[i + 2] / 4.0f;
+ xt[i + 3] = x[i + 3] / 128.0f;
+ xt[i + 4] = x[i + 4] / 16.0f;
+ xt[i + 5] = x[i + 5] / 2.0f;
+ xt[i + 6] = x[i + 6] / 64.0f;
+ xt[i + 7] = x[i + 7] / 8.0f;
+ }
+ } else if (bits == 6) {
+ for (int i = 0; i < N; i += 4) {
+ sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3];
+ xt[i] = x[i];
+ xt[i + 1] = x[i + 1] / 64.0f;
+ xt[i + 2] = x[i + 2] / 16.0f;
+ xt[i + 3] = x[i + 3] / 4.0f;
+ }
+ } else if (bits == 8) {
+ for (int i = 0; i < N; ++i) {
+ sum += x[i];
+ xt[i] = x[i];
+ }
+ }
+ return sum;
+}
+
+template
+inline float hc_qdot(
+ const device uint8_t* w,
+ const thread float* xt,
+ float scale,
+ float bias,
+ float sum) {
+ float accum = 0.0f;
+ if (bits == 4) {
+ const device uint16_t* ws = (const device uint16_t*)w;
+ for (int i = 0; i < N / 4; ++i) {
+ accum +=
+ (xt[4 * i] * (ws[i] & 0x000f)
+ + xt[4 * i + 1] * (ws[i] & 0x00f0)
+ + xt[4 * i + 2] * (ws[i] & 0x0f00)
+ + xt[4 * i + 3] * (ws[i] & 0xf000));
+ }
+ } else if (bits == 5) {
+ for (int i = 0; i < N / 8; ++i) {
+ xt += 8 * i;
+ w += 5 * i;
+ accum += (w[0] & 0x1f) * xt[0];
+ accum += (w[0] & 0xe0) * xt[1];
+ accum += (w[1] & 0x3) * (xt[1] * 256.0f);
+ accum += (w[1] & 0x7c) * xt[2];
+ accum += (w[1] & 0x80) * xt[3];
+ accum += (w[2] & 0xf) * (xt[3] * 256.0f);
+ accum += (w[2] & 0xf0) * xt[4];
+ accum += (w[3] & 0x1) * (xt[4] * 256.0f);
+ accum += (w[3] & 0x3e) * xt[5];
+ accum += (w[3] & 0xc0) * xt[6];
+ accum += (w[4] & 0x7) * (xt[6] * 256.0f);
+ accum += (w[4] & 0xf8) * xt[7];
+ }
+ } else if (bits == 6) {
+ for (int i = 0; i < N / 4; ++i) {
+ xt += 4 * i;
+ w += 3 * i;
+ accum += (w[0] & 0x3f) * xt[0];
+ accum += (w[0] & 0xc0) * xt[1];
+ accum += (w[1] & 0x0f) * (xt[1] * 256.0f);
+ accum += (w[1] & 0xf0) * xt[2];
+ accum += (w[2] & 0x03) * (xt[2] * 256.0f);
+ accum += (w[2] & 0xfc) * xt[3];
+ }
+ } else if (bits == 8) {
+ for (int i = 0; i < N; ++i) accum += xt[i] * w[i];
+ }
+ return scale * accum + sum * bias;
+}
+
+template
+inline float hc_qdot_safe(
+ const device uint8_t* w,
+ const thread float* xt,
+ float scale,
+ float bias,
+ float sum) {
+ float accum = 0.0f;
+ if (bits == 4) {
+ const device uint16_t* ws = (const device uint16_t*)w;
+ for (int i = 0; i < N / 4; ++i) {
+ accum +=
+ (xt[4 * i] * (ws[i] & 0x000f)
+ + xt[4 * i + 1] * (ws[i] & 0x00f0)
+ + xt[4 * i + 2] * (ws[i] & 0x0f00)
+ + xt[4 * i + 3] * (ws[i] & 0xf000));
+ }
+ } else if (bits == 5) {
+ for (int i = 0; i < N / 8; ++i) {
+ xt += 8 * i;
+ w += 5 * i;
+ accum += (w[0] & 0x1f) * xt[0];
+ accum += (w[0] & 0xe0) * xt[1];
+ accum += (w[1] & 0x3) * (xt[1] * 256.0f);
+ accum += (w[1] & 0x7c) * xt[2];
+ accum += (w[1] & 0x80) * xt[3];
+ accum += (w[2] & 0xf) * (xt[3] * 256.0f);
+ accum += (w[2] & 0xf0) * xt[4];
+ accum += (w[3] & 0x1) * (xt[4] * 256.0f);
+ accum += (w[3] & 0x3e) * xt[5];
+ accum += (w[3] & 0xc0) * xt[6];
+ accum += (w[4] & 0x7) * (xt[6] * 256.0f);
+ accum += (w[4] & 0xf8) * xt[7];
+ }
+ } else if (bits == 6) {
+ for (int i = 0; i < N / 4; ++i) {
+ xt += 4 * i;
+ w += 3 * i;
+ accum += (w[0] & 0x3f) * xt[0];
+ accum += (w[0] & 0xc0) * xt[1];
+ accum += (w[1] & 0x0f) * (xt[1] * 256.0f);
+ accum += (w[1] & 0xf0) * xt[2];
+ accum += (w[2] & 0x03) * (xt[2] * 256.0f);
+ accum += (w[2] & 0xfc) * xt[3];
+ }
+ } else if (bits == 8) {
+ for (int i = 0; i < N; ++i) accum += xt[i] * w[i];
+ }
+ return scale * accum + sum * bias;
+}
+"""
+
+
+_SOURCE = r"""
+ const uint tg = threadgroup_position_in_grid.y;
+ const uint sg = simdgroup_index_in_threadgroup;
+ const uint lane = thread_index_in_simdgroup;
+ constexpr int PF = hc_pack_factor();
+ constexpr int BP = hc_bytes_per_pack();
+ constexpr int GROUPS = K / 64;
+ constexpr int ROW_BYTES = K * BP / PF;
+
+ if (tg < 40) {
+ constexpr int PPT = 2;
+ constexpr int VPT = PF * PPT;
+ constexpr int BLOCK = VPT * 32;
+ constexpr int SCALE_STEP = 64 / VPT;
+ const int out_row = int(tg) * 8 + int(sg) * 4;
+ const device uint8_t* wp = (const device uint8_t*)down_w
+ + out_row * ROW_BYTES + int(lane) * PPT * BP;
+ const device T* sp = down_s + out_row * GROUPS
+ + int(lane) / SCALE_STEP;
+ const device T* bp = down_b + out_row * GROUPS
+ + int(lane) / SCALE_STEP;
+ const device T* xp = x + int(lane) * VPT;
+ float result[4] = {0.0f};
+ float xv[VPT];
+ for (int k = 0; k < K; k += BLOCK) {
+ float sum = hc_load_vector(xp, xv);
+ for (int row = 0; row < 4; ++row) {
+ result[row] += hc_qdot(
+ wp + row * ROW_BYTES,
+ xv,
+ float(sp[row * GROUPS]),
+ float(bp[row * GROUPS]),
+ sum);
+ }
+ wp += BLOCK * BP / PF;
+ sp += BLOCK / 64;
+ bp += BLOCK / 64;
+ xp += BLOCK;
+ }
+ for (int row = 0; row < 4; ++row) {
+ result[row] = simd_sum(result[row]);
+ if (lane == 0) combined[out_row + row] = T(result[row]);
+ }
+ return;
+ }
+
+ if (sg != 0) return;
+ constexpr int PPT = 1;
+ constexpr int VPT = PF;
+ constexpr int BLOCK = VPT * 32;
+ constexpr int SCALE_STEP = 64 / VPT;
+ const device uint8_t* wp = (const device uint8_t*)inject_w
+ + int(lane) * BP;
+ const device T* sp = inject_s + int(lane) / SCALE_STEP;
+ const device T* bp = inject_b + int(lane) / SCALE_STEP;
+ const device T* xp = x + int(lane) * VPT;
+ float result[4] = {0.0f};
+ float xv[VPT];
+ int k = 0;
+ for (; k < K - BLOCK; k += BLOCK) {
+ float sum = hc_load_vector(xp, xv);
+ for (int row = 0; row < 4; ++row) {
+ result[row] += hc_qdot(
+ wp + row * ROW_BYTES,
+ xv,
+ float(sp[row * GROUPS]),
+ float(bp[row * GROUPS]),
+ sum);
+ }
+ wp += BLOCK * BP / PF;
+ sp += BLOCK / 64;
+ bp += BLOCK / 64;
+ xp += BLOCK;
+ }
+ float sum = hc_load_vector(xp, xv);
+ for (int row = 0; row < 4; ++row) {
+ result[row] += hc_qdot_safe(
+ wp + row * ROW_BYTES,
+ xv,
+ float(sp[row * GROUPS]),
+ float(bp[row * GROUPS]),
+ sum);
+ result[row] = simd_sum(result[row]);
+ if (lane == 0) combined[320 + row] = T(result[row]);
+ }
+"""
+
+
+def _kernel():
+ global _KERNEL
+ if _KERNEL is None:
+ _KERNEL = mx.fast.metal_kernel(
+ name="omlx_qwen4_hc_hybrid_qmv",
+ input_names=[
+ "x",
+ "down_w",
+ "down_s",
+ "down_b",
+ "inject_w",
+ "inject_s",
+ "inject_b",
+ ],
+ output_names=["combined"],
+ header=_HEADER,
+ source=_SOURCE,
+ ensure_row_contiguous=True,
+ )
+ return _KERNEL
+
+
+def compatible_projections(down, injection) -> bool:
+ """Whether two raw Qwen4 projection banks match the native contract."""
+ if _DISABLED:
+ return False
+ if not (
+ type(down) is nn.QuantizedLinear
+ and type(injection) is nn.QuantizedLinear
+ and getattr(down, "group_size", None)
+ == getattr(injection, "group_size", None)
+ == _GROUP_SIZE
+ and getattr(down, "bits", None) == getattr(injection, "bits", None)
+ and getattr(down, "bits", None) in _SUPPORTED_BITS
+ and getattr(down, "mode", None)
+ == getattr(injection, "mode", None)
+ == "affine"
+ and "bias" not in down
+ and "bias" not in injection
+ ):
+ return False
+ tensors = tuple(
+ getattr(projection, name, None)
+ for projection in (down, injection)
+ for name in ("weight", "scales", "biases")
+ )
+ if not all(isinstance(value, mx.array) for value in tensors):
+ return False
+ packed_width = _STREAM_WIDTH * down.bits // 32
+ return bool(
+ down.weight.shape == (_LOW_RANK, packed_width)
+ and injection.weight.shape == (_HC_COUNT, packed_width)
+ and down.weight.dtype == injection.weight.dtype == mx.uint32
+ and down.scales.shape == (_LOW_RANK, _STREAM_WIDTH // _GROUP_SIZE)
+ and injection.scales.shape
+ == (_HC_COUNT, _STREAM_WIDTH // _GROUP_SIZE)
+ and down.biases.shape == down.scales.shape
+ and injection.biases.shape == injection.scales.shape
+ and down.scales.dtype == down.biases.dtype == mx.bfloat16
+ and injection.scales.dtype == injection.biases.dtype == mx.bfloat16
+ )
+
+
+def hybrid_projection(
+ x: mx.array,
+ down,
+ injection,
+) -> mx.array | None:
+ """Return exact concatenated ``down, inject`` output or fail closed."""
+ global _RUNTIME_FAILED, _FAILURE_LOGGED
+
+ if not (
+ not _RUNTIME_FAILED
+ and isinstance(x, mx.array)
+ and x.shape == (1, 1, _STREAM_WIDTH)
+ and x.dtype == mx.bfloat16
+ and compatible_projections(down, injection)
+ and mx.default_device() == mx.gpu
+ and mx.metal.is_available()
+ ):
+ return None
+ try:
+ return _kernel()(
+ inputs=[
+ x,
+ down.weight,
+ down.scales,
+ down.biases,
+ injection.weight,
+ injection.scales,
+ injection.biases,
+ ],
+ template=[
+ ("T", x.dtype),
+ ("BITS", down.bits),
+ ("K", _STREAM_WIDTH),
+ ],
+ grid=(32, 82, 1),
+ threadgroup=(32, 2, 1),
+ output_shapes=[(1, 1, _LOW_RANK + _HC_COUNT)],
+ output_dtypes=[x.dtype],
+ )[0]
+ except Exception as exc: # noqa: BLE001 - optional native path
+ _RUNTIME_FAILED = True
+ if not _FAILURE_LOGGED:
+ _FAILURE_LOGGED = True
+ logger.warning(
+ "Qwen4 exact hybrid HC projection failed closed; using "
+ "canonical split projections: %s",
+ exc,
+ )
+ return None
+
+
+__all__ = ["compatible_projections", "hybrid_projection"]
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py
new file mode 100644
index 0000000000..6f450fced3
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py
@@ -0,0 +1,2906 @@
+from __future__ import annotations
+
+import json
+import math
+import mmap
+import os
+import struct
+import weakref
+from bisect import bisect_right
+from dataclasses import dataclass, replace
+from pathlib import Path
+from typing import Any, Optional
+
+import mlx.core as mx
+import mlx.nn as nn
+import numpy as np
+
+from .cache import ArraysCache, BatchKVCache, KVCache, QuantizedKVCache, dynamic_roll
+from ..qwen3_5.language import LanguageModel as Qwen3_5LanguageModel
+from ..qwen3_5.language import (
+ Qwen3_5Attention,
+ Qwen3_5GatedDeltaNet,
+ _create_qwen3_5_attention_mask,
+ _create_qwen3_5_ssm_mask,
+ _target_verify_linear,
+ _target_verify_linears,
+)
+from ..qwen3_5_moe.language import Qwen3_5MoeSparseMoeBlock
+from .config import ModelConfig, TextConfig
+from .qsa_fast import (
+ contiguous_causal_gathered_qsa,
+ contiguous_causal_gathered_qsa_decode,
+ pool_completed_index_keys,
+)
+from . import hc_fused
+
+_PLE_RUNTIME_MODEL_PATH: Path | None = None
+_PLE_RUNTIME_MODE = "resident"
+_HYPER_SPLIT_INDICES: dict[tuple[int, int], tuple[mx.array, mx.array]] = {}
+# Identity cache: keep the array alive so CPython cannot recycle id().
+_TEXT_MROPE_EQUAL_PLANES: list[tuple[Any, int, bool]] = []
+
+
+def _broadcast_text_mrope_position_ids(
+ position_ids: Optional[mx.array],
+ length: int,
+) -> bool:
+ """True for missing/2-D text ids, or 3-D MRoPE that is a text broadcast.
+
+ Parent LanguageModel tiles identical ``(1, L)`` positions to ``(3, 1, L)``
+ for text-only mRoPE. Real image grids differ across the three planes and
+ must stay on the official mask+SDPA path.
+ """
+ if position_ids is None:
+ return True
+ if not isinstance(position_ids, mx.array):
+ return False
+ if position_ids.ndim == 2:
+ return tuple(position_ids.shape) == (1, length)
+ if position_ids.ndim != 3 or tuple(position_ids.shape) != (3, 1, length):
+ return False
+ for cached_ids, cached_len, cached_same in _TEXT_MROPE_EQUAL_PLANES:
+ if cached_ids is position_ids and cached_len == length:
+ return cached_same
+ same = bool(
+ mx.array_equal(position_ids[0], position_ids[1]).item()
+ and mx.array_equal(position_ids[1], position_ids[2]).item()
+ )
+ _TEXT_MROPE_EQUAL_PLANES.append((position_ids, length, same))
+ if len(_TEXT_MROPE_EQUAL_PLANES) > 8:
+ del _TEXT_MROPE_EQUAL_PLANES[:-8]
+ return same
+
+
+def _gathered_min_query_tokens() -> int:
+ """Keep narrow Lightning MTP windows on masked SDPA (M5 crossover)."""
+ raw = os.environ.get("OMLX_QWEN4_GATHERED_MIN_QUERY", "").strip()
+ if raw:
+ try:
+ return max(2, int(raw))
+ except ValueError:
+ pass
+ return 16
+
+
+def _split_text_mrope_positions(
+ position_ids: Optional[mx.array],
+ batch: int,
+ length: int,
+ past_len: int,
+) -> tuple[mx.array, mx.array]:
+ """Indexer text ids vs rotary ids for the gathered QSA arms."""
+ if position_ids is None:
+ text_position_ids = mx.arange(
+ past_len, past_len + length, dtype=mx.int32
+ )[None]
+ rotary_position_ids = mx.broadcast_to(
+ text_position_ids,
+ (3, batch, length),
+ )
+ return text_position_ids, rotary_position_ids
+ if position_ids.ndim == 3:
+ return position_ids[0], position_ids
+ return position_ids, position_ids
+
+
+@dataclass(frozen=True)
+class Qwen4ExpMTPRuntime:
+ """Lightning MTP construction decision for the next model load."""
+
+ enabled: bool = False
+ checkpoint_prefix: str | None = None
+
+
+_MTP_RUNTIME = Qwen4ExpMTPRuntime()
+
+
+@dataclass(frozen=True)
+class _PLESpeculativeState:
+ """PLE inputs needed to restore a partially accepted verify window."""
+
+ history: mx.array
+ input_ids: mx.array
+ conv_state: mx.array
+ conv_inputs: mx.array
+
+
+def configure_mtp_runtime(
+ model_path: str | Path,
+ *,
+ enabled: bool,
+) -> Qwen4ExpMTPRuntime:
+ """Detect and bind an embedded Qwen4 Lightning MTP checkpoint head."""
+ global _MTP_RUNTIME
+
+ checkpoint_prefix = None
+ if enabled:
+ from omlx.utils.model_loading import _checkpoint_qwen4_mtp_weight_prefix
+
+ checkpoint_prefix = _checkpoint_qwen4_mtp_weight_prefix(model_path)
+
+ _MTP_RUNTIME = Qwen4ExpMTPRuntime(
+ enabled=bool(enabled and checkpoint_prefix),
+ checkpoint_prefix=checkpoint_prefix,
+ )
+ return _MTP_RUNTIME
+
+
+def get_mtp_runtime() -> Qwen4ExpMTPRuntime:
+ return _MTP_RUNTIME
+
+
+def resolve_ple_runtime_mode(
+ requested: str, *, checkpoint_bytes: int, physical_memory: int
+) -> str:
+ requested = requested.strip().lower()
+ if requested == "ssd_mmap":
+ requested = "mmap"
+ if requested not in {"auto", "resident", "mmap"}:
+ raise ValueError("OMLX_QWEN4_PLE_MODE must be auto, resident, or mmap")
+ if requested != "auto":
+ return requested
+ return "mmap" if checkpoint_bytes > physical_memory * 0.70 else "resident"
+
+
+def configure_ple_runtime(model_path: str | Path, mode: str | None = None) -> str:
+ """Bind same-directory PLE storage before Qwen4 model construction."""
+ global _PLE_RUNTIME_MODEL_PATH, _PLE_RUNTIME_MODE
+
+ compute_path = Path(model_path).expanduser().resolve()
+ requested = mode or os.environ.get("OMLX_QWEN4_PLE_MODE")
+ if requested is None:
+ requested = "auto"
+ checkpoint_bytes = sum(
+ path.stat().st_size
+ for path in compute_path.glob("*.safetensors")
+ )
+ physical_memory = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
+ _PLE_RUNTIME_MODE = resolve_ple_runtime_mode(
+ requested,
+ checkpoint_bytes=checkpoint_bytes,
+ physical_memory=physical_memory,
+ )
+ _PLE_RUNTIME_MODEL_PATH = compute_path
+ return _PLE_RUNTIME_MODE
+
+
+def get_ple_runtime_mode() -> str:
+ return _PLE_RUNTIME_MODE
+
+
+def _append_indexer_positions(
+ cached: Optional[mx.array], position_ids: mx.array
+) -> mx.array:
+ if cached is None:
+ return position_ids
+ if cached.ndim == 3 and position_ids.ndim == 2:
+ position_ids = mx.broadcast_to(
+ position_ids[None],
+ (cached.shape[0], *position_ids.shape),
+ )
+ elif cached.ndim == 2 and position_ids.ndim == 3:
+ cached = mx.broadcast_to(cached[None], (position_ids.shape[0], *cached.shape))
+ elif cached.ndim != position_ids.ndim:
+ raise ValueError(
+ "QSA position IDs must be 2-D text positions or 3-D MRoPE positions, "
+ f"got cached={cached.shape} and current={position_ids.shape}."
+ )
+ return mx.concatenate([cached, position_ids], axis=-1)
+
+
+class _QSAIndexerCache:
+ """Capacity-backed raw and completed-block state shared by QSA caches.
+
+ Raw keys and positions remain part of the public/persisted cache state.
+ The normalized, RoPE-rotated block bank is deliberately ephemeral: state
+ restore, row extraction/filtering, and rollback can rebuild it exactly from
+ those raw tensors without changing the serialized cache schema.
+ """
+
+ index_step = 8192
+
+ def _init_indexer_cache(self):
+ self._index_keys = None
+ self._index_position_ids = None
+ self._index_offset = 0
+ self._index_capacity_managed = True
+ self._index_reserved_tokens = 0
+ self._invalidate_pooled_indexer()
+
+ def reserve_index_capacity(self, tokens: int) -> None:
+ """Reserve a stepped prefill horizon; later growth uses plain steps."""
+
+ self._index_reserved_tokens = max(0, int(tokens))
+
+ @property
+ def index_keys(self):
+ if self._index_keys is None:
+ return None
+ return self._index_keys[:, : self._index_offset]
+
+ @index_keys.setter
+ def index_keys(self, value):
+ self._index_keys = value
+ self._index_offset = 0 if value is None else int(value.shape[1])
+ self._index_capacity_managed = False
+ self._invalidate_pooled_indexer()
+
+ @property
+ def index_position_ids(self):
+ if self._index_position_ids is None:
+ return None
+ return self._index_position_ids[..., : self._index_offset]
+
+ @index_position_ids.setter
+ def index_position_ids(self, value):
+ self._index_position_ids = value
+ self._invalidate_pooled_indexer()
+
+ def _restore_indexer_state(self, keys, position_ids):
+ if (keys is None) != (position_ids is None):
+ raise ValueError("QSA raw keys and positions must be restored together")
+ if keys is not None and (
+ keys.ndim != 3
+ or position_ids.ndim not in {2, 3}
+ or keys.shape[1] != position_ids.shape[-1]
+ ):
+ raise ValueError("Restored QSA raw keys and positions are misaligned")
+ self._index_keys = keys
+ self._index_position_ids = position_ids
+ self._index_offset = 0 if keys is None else int(keys.shape[1])
+ self._index_capacity_managed = False
+ self._invalidate_pooled_indexer()
+
+ @staticmethod
+ def _growth_capacity(current: int, needed: int, step: int) -> int:
+ stepped = ((needed + step - 1) // step) * step
+ return max(stepped, 2 * current if current else step)
+
+ def _next_capacity(
+ self, current: int, needed: int, step: int, reserve: Optional[int] = None
+ ) -> int:
+ """Use reserved capacity when known, otherwise amortize growth."""
+ if reserve is None:
+ reserve = getattr(self, "_index_reserved_tokens", 0)
+ if not reserve:
+ return self._growth_capacity(current, needed, step)
+ target = needed if current >= reserve else max(needed, reserve)
+ return ((target + step - 1) // step) * step
+
+ def _ensure_indexer_capacity(
+ self,
+ sample_keys: mx.array,
+ sample_positions: mx.array,
+ needed: int,
+ ) -> None:
+ if self._index_keys is None:
+ current = 0
+ else:
+ current = min(
+ int(self._index_keys.shape[1]),
+ int(self._index_position_ids.shape[-1]),
+ )
+ if needed <= current:
+ return
+ if self._index_capacity_managed or self._index_reserved_tokens:
+ capacity = self._next_capacity(current, needed, self.index_step)
+ else:
+ # The backing buffers belong to a restore/reconstruction caller, so
+ # only round up to the step; never second-guess its sizing.
+ capacity = (
+ (needed + self.index_step - 1) // self.index_step
+ ) * self.index_step
+ new_keys = mx.zeros(
+ (sample_keys.shape[0], capacity, sample_keys.shape[-1]),
+ dtype=sample_keys.dtype,
+ )
+ if sample_positions.ndim == 3:
+ position_shape = (
+ sample_positions.shape[0],
+ sample_positions.shape[1],
+ capacity,
+ )
+ else:
+ position_shape = (sample_positions.shape[0], capacity)
+ new_positions = mx.zeros(position_shape, dtype=sample_positions.dtype)
+ if self._index_keys is not None and self._index_offset:
+ new_keys[:, : self._index_offset] = self._index_keys[
+ :, : self._index_offset
+ ]
+ new_positions[..., : self._index_offset] = self._index_position_ids[
+ ..., : self._index_offset
+ ]
+ self._index_keys = new_keys
+ self._index_position_ids = new_positions
+ self._index_capacity_managed = True
+
+ def update_indexer(self, keys: mx.array, position_ids: mx.array):
+ if keys.ndim != 3 or position_ids.ndim not in {2, 3}:
+ raise ValueError("QSA index updates require [B,S,D] keys and positions")
+ length = int(keys.shape[1])
+ if position_ids.shape[-1] != length:
+ raise ValueError("QSA index update keys and positions are misaligned")
+
+ if self._index_position_ids is not None:
+ if self._index_position_ids.ndim == 3 and position_ids.ndim == 2:
+ position_ids = mx.broadcast_to(
+ position_ids[None],
+ (self._index_position_ids.shape[0], *position_ids.shape),
+ )
+ elif self._index_position_ids.ndim == 2 and position_ids.ndim == 3:
+ # MRoPE promotion is rare. Collapse the old position backing to
+ # its logical prefix so the capacity grow below creates a
+ # writable three-coordinate allocation.
+ old_positions = self._index_position_ids[
+ ..., : self._index_offset
+ ]
+ self._index_position_ids = mx.broadcast_to(
+ old_positions[None],
+ (position_ids.shape[0], *old_positions.shape),
+ )
+ self._index_capacity_managed = False
+ elif self._index_position_ids.ndim != position_ids.ndim:
+ raise ValueError("QSA position rank changed incompatibly")
+
+ end = self._index_offset + length
+ self._ensure_indexer_capacity(keys, position_ids, end)
+ self._index_keys[:, self._index_offset : end] = keys
+ self._index_position_ids[..., self._index_offset : end] = position_ids
+ self._index_offset = end
+ return self.index_keys, self.index_position_ids
+
+ def _invalidate_pooled_indexer(self):
+ self._pooled_index_keys = None
+ self._pooled_index_offset = 0
+ self._pooled_index_ratio = None
+ self._pooled_index_tag = None
+
+ def pooled_indexer_keys(
+ self,
+ compress_ratio: int,
+ index_key_norm,
+ apply_index_rope,
+ *,
+ cache_tag=None,
+ ) -> mx.array:
+ """Return the completed block bank, computing only its new suffix."""
+
+ if self._index_keys is None or self._index_position_ids is None:
+ raise ValueError("QSA pooled keys require raw indexer state")
+ complete_blocks = self._index_offset // compress_ratio
+ if (
+ self._pooled_index_ratio != compress_ratio
+ or self._pooled_index_tag is not cache_tag
+ or self._pooled_index_offset > complete_blocks
+ ):
+ self._invalidate_pooled_indexer()
+ self._pooled_index_ratio = compress_ratio
+ self._pooled_index_tag = cache_tag
+
+ start_block = self._pooled_index_offset
+ if start_block < complete_blocks:
+ new_pooled = pool_completed_index_keys(
+ self.index_keys,
+ self.index_position_ids,
+ compress_ratio=compress_ratio,
+ index_key_norm=index_key_norm,
+ apply_index_rope=apply_index_rope,
+ start_block=start_block,
+ stop_block=complete_blocks,
+ )
+ current_capacity = (
+ 0
+ if self._pooled_index_keys is None
+ else int(self._pooled_index_keys.shape[1])
+ )
+ if complete_blocks > current_capacity:
+ block_step = max(1, self.index_step // compress_ratio)
+ reserved = getattr(self, "_index_reserved_tokens", 0)
+ capacity = self._next_capacity(
+ current_capacity,
+ complete_blocks,
+ block_step,
+ reserve=(reserved // compress_ratio if reserved else 0),
+ )
+ new_buffer = mx.zeros(
+ (new_pooled.shape[0], capacity, new_pooled.shape[-1]),
+ dtype=new_pooled.dtype,
+ )
+ if self._pooled_index_keys is not None and start_block:
+ new_buffer[:, :start_block] = self._pooled_index_keys[
+ :, :start_block
+ ]
+ self._pooled_index_keys = new_buffer
+ self._pooled_index_keys[:, start_block:complete_blocks] = new_pooled
+ self._pooled_index_offset = complete_blocks
+
+ if self._pooled_index_keys is None:
+ return mx.zeros(
+ (self._index_keys.shape[0], 0, self._index_keys.shape[-1]),
+ dtype=self._index_keys.dtype,
+ )
+ return self._pooled_index_keys[:, : self._pooled_index_offset]
+
+ def _trim_indexer(self, length: int):
+ self._index_offset = min(self._index_offset, max(0, int(length)))
+ # Trim leaves completed prefix blocks intact; only re-pool the new tail.
+ if self._pooled_index_keys is not None and self._pooled_index_ratio:
+ self._pooled_index_offset = min(
+ self._pooled_index_offset,
+ self._index_offset // self._pooled_index_ratio,
+ )
+ else:
+ self._invalidate_pooled_indexer()
+
+ @property
+ def indexer_nbytes(self):
+ size = 0
+ for array in (
+ self._index_keys,
+ self._index_position_ids,
+ self._pooled_index_keys,
+ ):
+ if array is not None:
+ size += array.nbytes
+ return size
+
+
+class QSAKVCache(_QSAIndexerCache, KVCache):
+ """KV cache with the raw indexer keys and multimodal positions used by QSA."""
+
+ # Hybrid/TurboQuant caches do not currently expose a way to carry the
+ # indexer's unprojected keys. Uniform quantization uses the specialized
+ # QSAQuantizedKVCache below; other schemes leave this cache in float.
+ preserve_auxiliary_kv_state = True
+ step = 8192
+ geometric_growth = True
+
+ def __init__(self):
+ super().__init__()
+ self._init_indexer_cache()
+
+ @property
+ def state(self):
+ if self.keys is None:
+ return None, None, self.index_keys, self.index_position_ids
+ return (
+ self.keys[..., : self.offset, :],
+ self.values[..., : self.offset, :],
+ self.index_keys,
+ self.index_position_ids,
+ )
+
+ @state.setter
+ def state(self, value):
+ self.keys, self.values, index_keys, index_position_ids = value
+ self.offset = 0 if self.keys is None else self.keys.shape[2]
+ self._geometric_capacity_managed = False
+ self._restore_indexer_state(index_keys, index_position_ids)
+
+ def trim(self, n):
+ n = min(self.offset, n)
+ super().trim(n)
+ self._trim_indexer(self.offset)
+ return n
+
+ def extract(self, idx):
+ cache = QSAKVCache()
+ if self.keys is not None:
+ cache.keys = mx.contiguous(
+ self.keys[idx : idx + 1, :, : self.offset, :]
+ )
+ cache.values = mx.contiguous(
+ self.values[idx : idx + 1, :, : self.offset, :]
+ )
+ cache.offset = self.offset
+ cache._geometric_capacity_managed = False
+ if self.index_keys is not None:
+ index_keys = mx.contiguous(self.index_keys[idx : idx + 1])
+ if self.index_position_ids.ndim == 3:
+ index_position_ids = mx.contiguous(
+ self.index_position_ids[:, idx : idx + 1]
+ )
+ else:
+ index_position_ids = mx.contiguous(
+ self.index_position_ids[idx : idx + 1]
+ )
+ cache._restore_indexer_state(index_keys, index_position_ids)
+ return cache
+
+ def filter(self, batch_indices):
+ if self.keys is not None:
+ self.keys = self.keys[batch_indices]
+ self.values = self.values[batch_indices]
+ if self.index_keys is not None:
+ self.index_keys = self.index_keys[batch_indices]
+ if self.index_position_ids.ndim == 3:
+ self.index_position_ids = self.index_position_ids[:, batch_indices]
+ else:
+ self.index_position_ids = self.index_position_ids[batch_indices]
+
+ def to_batch(self, left_padding):
+ """Convert a singleton QSA cache without dropping indexer state."""
+
+ batch = BatchQSAKVCache(left_padding)
+ padding = mx.array(left_padding)
+ if self.empty() and self.index_keys is None:
+ return batch
+ if padding.size != 1:
+ raise ValueError(
+ "A warm QSA cache can only seed one batch row, got "
+ f"left_padding={padding.tolist()}"
+ )
+ pad = int(padding.item())
+ if not self.empty():
+ keys, values = self.state[:2]
+ if pad:
+ keys = mx.pad(keys, [(0, 0), (0, 0), (pad, 0), (0, 0)])
+ values = mx.pad(values, [(0, 0), (0, 0), (pad, 0), (0, 0)])
+ batch.kv_cache.state = (
+ keys,
+ values,
+ mx.array([self.offset], dtype=mx.int32),
+ padding.astype(mx.int32),
+ )
+ if self.index_keys is not None:
+ index_keys = self.index_keys[:, : self.offset]
+ positions = self.index_position_ids[..., : self.offset]
+ if pad:
+ index_keys = mx.pad(index_keys, [(0, 0), (pad, 0), (0, 0)])
+ positions = mx.pad(
+ positions,
+ (
+ [(0, 0), (0, 0), (pad, 0)]
+ if positions.ndim == 3
+ else [(0, 0), (pad, 0)]
+ ),
+ )
+ batch.index_keys = index_keys
+ batch.index_position_ids = positions
+ batch.index_offset = index_keys.shape[1]
+ return batch
+
+ @classmethod
+ def merge(cls, caches):
+ return BatchQSAKVCache.merge(caches)
+
+ def to_quantized(self, group_size: int = 64, bits: int = 4):
+ base = super().to_quantized(group_size=group_size, bits=bits)
+ cache = QSAQuantizedKVCache(group_size=group_size, bits=bits)
+ cache.keys = base.keys
+ cache.values = base.values
+ cache.offset = base.offset
+ cache.index_keys = self.index_keys
+ cache.index_position_ids = self.index_position_ids
+ return cache
+
+ @property
+ def nbytes(self):
+ return super().nbytes + self.indexer_nbytes
+
+
+class BatchQSAKVCache:
+ """Batch KV cache that keeps QSA raw keys and text/MRoPE positions aligned."""
+
+ def __init__(self, left_padding):
+ self.kv_cache = BatchKVCache(left_padding)
+ self.index_keys = None
+ self.index_position_ids = None
+ self.index_offset = 0
+
+ @property
+ def offset(self):
+ return self.kv_cache.offset
+
+ @property
+ def left_padding(self):
+ return self.kv_cache.left_padding
+
+ def update_and_fetch(self, keys, values):
+ return self.kv_cache.update_and_fetch(keys, values)
+
+ def update_indexer(self, keys: mx.array, position_ids: mx.array):
+ if self.index_keys is None:
+ self.index_keys = keys
+ self.index_position_ids = position_ids
+ else:
+ self.index_keys = mx.concatenate([self.index_keys, keys], axis=1)
+ self.index_position_ids = _append_indexer_positions(
+ self.index_position_ids, position_ids
+ )
+ self.index_offset = self.index_keys.shape[1]
+ return self.index_keys, self.index_position_ids
+
+ def prepare(self, **kwargs):
+ self.kv_cache.prepare(**kwargs)
+
+ def finalize(self):
+ right_padding = getattr(self.kv_cache, "_right_padding", None)
+ self.kv_cache.finalize()
+ if right_padding is None or self.index_keys is None:
+ return
+ self.index_keys = dynamic_roll(self.index_keys, right_padding, axis=1)
+ if self.index_position_ids.ndim == 3:
+ self.index_position_ids = dynamic_roll(
+ self.index_position_ids, right_padding[None], axis=2
+ )
+ else:
+ self.index_position_ids = dynamic_roll(
+ self.index_position_ids, right_padding, axis=1
+ )
+
+ def make_mask(self, *args, **kwargs):
+ return self.kv_cache.make_mask(*args, **kwargs)
+
+ def filter(self, batch_indices):
+ min_left = int(self.left_padding[batch_indices].min().item())
+ self.kv_cache.filter(batch_indices)
+ if self.index_keys is None:
+ return
+ self.index_keys = self.index_keys[batch_indices]
+ if self.index_position_ids.ndim == 3:
+ self.index_position_ids = self.index_position_ids[:, batch_indices]
+ else:
+ self.index_position_ids = self.index_position_ids[batch_indices]
+ if min_left > 0:
+ self.index_keys = self.index_keys[:, min_left:]
+ self.index_position_ids = self.index_position_ids[..., min_left:]
+ self.index_offset -= min_left
+
+ @staticmethod
+ def _pad_index(cache, target, sample_keys, sample_positions):
+ length = (
+ 0
+ if cache.index_keys is None
+ else getattr(cache, "index_offset", cache.index_keys.shape[1])
+ )
+ if isinstance(length, mx.array):
+ if length.size != 1:
+ raise ValueError(
+ "QSA index length must be scalar after row normalization"
+ )
+ length = int(length.item())
+ else:
+ length = int(length)
+ left = target - length
+ if cache.index_keys is None:
+ offset = cache.offset
+ batch_size = offset.shape[0] if isinstance(offset, mx.array) else 1
+ keys = mx.zeros(
+ (batch_size, 0, sample_keys.shape[-1]),
+ dtype=sample_keys.dtype,
+ )
+ if sample_positions.ndim == 3:
+ positions = mx.zeros(
+ (sample_positions.shape[0], batch_size, 0),
+ dtype=sample_positions.dtype,
+ )
+ else:
+ positions = mx.zeros(
+ (batch_size, 0), dtype=sample_positions.dtype
+ )
+ else:
+ keys = cache.index_keys[:, :length]
+ positions = cache.index_position_ids[..., :length]
+ # Widen 2-D text positions to the join's widest rank before
+ # padding (#3294 item 2): the runtime update path already
+ # broadcasts text up to MRoPE in _append_indexer_positions; joins
+ # must apply the same rule or the concatenate below sees ranks 2
+ # and 3. Replicating across MRoPE channels matches runtime.
+ if sample_positions.ndim == 3 and positions.ndim == 2:
+ positions = mx.broadcast_to(
+ positions[None],
+ (sample_positions.shape[0], *positions.shape),
+ )
+ if left:
+ keys = mx.pad(keys, [(0, 0), (left, 0), (0, 0)])
+ positions = mx.pad(
+ positions,
+ (
+ [(0, 0), (0, 0), (left, 0)]
+ if positions.ndim == 3
+ else [(0, 0), (left, 0)]
+ ),
+ )
+ return keys, positions
+
+ def extend(self, other):
+ if not isinstance(other, BatchQSAKVCache):
+ raise TypeError(f"Cannot extend BatchQSAKVCache with {type(other)}")
+
+ for cache in (self, other):
+ if (cache.index_keys is None) != (cache.index_position_ids is None):
+ raise ValueError("QSA raw keys and positions must be extended together")
+ if cache.index_keys is None:
+ if cache.kv_cache.size():
+ raise ValueError("Cannot extend QSA KV state without indexer state")
+ elif cache.index_offset != cache.kv_cache.size():
+ raise ValueError(
+ "QSA extend requires aligned KV and indexer widths, got "
+ f"kv={cache.kv_cache.size()} and indexer={cache.index_offset}"
+ )
+
+ sample_keys = (
+ self.index_keys if self.index_keys is not None else other.index_keys
+ )
+ # Prefer the WIDEST position rank over "first non-None" (#3294 item
+ # 2): promotion only widens, so a 2-D sample would strand a 3-D row
+ # with nothing to promote to, and position_axis would be picked from
+ # the wrong rank. Order-sensitive defect, so pick from both sides.
+ self_positions = self.index_position_ids
+ other_positions = other.index_position_ids
+ if (
+ self_positions is not None
+ and other_positions is not None
+ and self_positions.ndim != other_positions.ndim
+ ):
+ sample_positions = (
+ other_positions if self_positions.ndim == 2 else self_positions
+ )
+ elif self_positions is not None:
+ sample_positions = self_positions
+ else:
+ sample_positions = other_positions
+ if sample_keys is None or sample_positions is None:
+ self.kv_cache.extend(other.kv_cache)
+ return
+ target = max(self.index_offset, other.index_offset)
+ left = self._pad_index(self, target, sample_keys, sample_positions)
+ right = self._pad_index(other, target, sample_keys, sample_positions)
+ index_keys = mx.concatenate([left[0], right[0]], axis=0)
+ position_axis = 1 if sample_positions.ndim == 3 else 0
+ index_position_ids = mx.concatenate(
+ [left[1], right[1]], axis=position_axis
+ )
+
+ self.kv_cache.extend(other.kv_cache)
+ self.index_keys = index_keys
+ self.index_position_ids = index_position_ids
+ self.index_offset = target
+
+ def extract(self, idx):
+ cache = QSAKVCache()
+ base = self.kv_cache.extract(idx)
+ cache.keys, cache.values, cache.offset = base.keys, base.values, base.offset
+ if self.index_keys is not None:
+ padding = int(self.left_padding[idx].item())
+ cache.index_keys = mx.contiguous(
+ self.index_keys[idx : idx + 1, padding : self.index_offset]
+ )
+ if self.index_position_ids.ndim == 3:
+ cache.index_position_ids = mx.contiguous(
+ self.index_position_ids[
+ :, idx : idx + 1, padding : self.index_offset
+ ]
+ )
+ else:
+ cache.index_position_ids = mx.contiguous(
+ self.index_position_ids[idx : idx + 1, padding : self.index_offset]
+ )
+ return cache
+
+ @classmethod
+ def merge(cls, caches):
+ rows = []
+ for cache in caches:
+ if isinstance(cache, cls):
+ batch_size = int(cache.offset.shape[0])
+ if cache.kv_cache.keys is None:
+ if cache.index_keys is not None:
+ raise ValueError(
+ "Cannot merge a QSA batch with indexer state but no KV state"
+ )
+ rows.extend(QSAKVCache() for _ in range(batch_size))
+ else:
+ rows.extend(cache.extract(idx) for idx in range(batch_size))
+ elif isinstance(cache, QSAKVCache):
+ rows.append(cache)
+ else:
+ raise TypeError(f"Cannot merge QSA cache with {type(cache)}")
+
+ out = cls([0] * len(rows))
+ if not rows:
+ return out
+
+ lengths = []
+ for row in rows:
+ kv_length = int(row.offset)
+ if row.keys is None:
+ if kv_length:
+ raise ValueError("QSA cache has a non-zero offset without KV state")
+ elif kv_length > row.keys.shape[2]:
+ raise ValueError("QSA cache offset exceeds its KV storage")
+
+ if (row.index_keys is None) != (row.index_position_ids is None):
+ raise ValueError("QSA raw keys and positions must be merged together")
+ index_length = 0 if row.index_keys is None else row.index_keys.shape[1]
+ if row.index_position_ids is not None and (
+ row.index_position_ids.ndim not in {2, 3}
+ or row.index_position_ids.shape[-1] != index_length
+ ):
+ raise ValueError("QSA raw keys and positions are misaligned")
+ if index_length != kv_length:
+ raise ValueError(
+ "QSA merge requires aligned KV and indexer lengths, got "
+ f"kv={kv_length} and indexer={index_length}"
+ )
+ lengths.append(index_length)
+
+ out.kv_cache = BatchKVCache.merge(rows)
+ sample = next((row for row in rows if row.index_keys is not None), None)
+ if sample is None:
+ return out
+ # Pick the widest position rank across every cache, not the first
+ # non-None sample (#3294 item 2): promotion only widens, so a 2-D
+ # first sample would strand a 3-D row at concatenate time.
+ widest_positions = sample.index_position_ids
+ for row in rows:
+ pos = row.index_position_ids
+ if pos is not None and pos.ndim > widest_positions.ndim:
+ widest_positions = pos
+ target = out.kv_cache.size()
+ if target != max(lengths):
+ raise ValueError(
+ "QSA merge produced different KV and indexer widths, got "
+ f"kv={target} and indexer={max(lengths)}"
+ )
+ padded_rows = [
+ cls._pad_index(
+ row,
+ target,
+ sample.index_keys,
+ widest_positions,
+ )
+ for row in rows
+ ]
+ out.index_keys = mx.concatenate([row[0] for row in padded_rows], axis=0)
+ position_axis = 1 if widest_positions.ndim == 3 else 0
+ out.index_position_ids = mx.concatenate(
+ [row[1] for row in padded_rows], axis=position_axis
+ )
+ out.index_offset = target
+ return out
+
+ def size(self):
+ return self.kv_cache.size()
+
+ def empty(self):
+ return self.kv_cache.empty()
+
+ def is_trimmable(self):
+ return self.kv_cache.is_trimmable()
+
+ def trim(self, n):
+ trimmed = self.kv_cache.trim(n)
+ self.index_offset = max(0, self.index_offset - trimmed)
+ # Slice the physical arrays like the singleton trim does:
+ # update_indexer concatenates onto them and re-derives index_offset
+ # from shape[1], so stale draft columns would otherwise fossilize
+ # and desync the indexer from the KV by the trimmed amount.
+ if trimmed and self.index_keys is not None:
+ self.index_keys = self.index_keys[:, : self.index_offset]
+ self.index_position_ids = self.index_position_ids[
+ ..., : self.index_offset
+ ]
+ return trimmed
+
+ @property
+ def state(self):
+ return (
+ self.kv_cache.state,
+ (
+ None
+ if self.index_keys is None
+ else self.index_keys[:, : self.index_offset]
+ ),
+ (
+ None
+ if self.index_position_ids is None
+ else self.index_position_ids[..., : self.index_offset]
+ ),
+ )
+
+ @state.setter
+ def state(self, value):
+ kv_state, self.index_keys, self.index_position_ids = value
+ self.kv_cache.state = kv_state
+ self.index_offset = 0 if self.index_keys is None else self.index_keys.shape[1]
+
+ @property
+ def nbytes(self):
+ extra = 0
+ if self.index_keys is not None:
+ extra = self.index_keys.nbytes + self.index_position_ids.nbytes
+ return self.kv_cache.nbytes + extra
+
+
+class QSAQuantizedKVCache(_QSAIndexerCache, QuantizedKVCache):
+ """Uniformly quantized QSA cache that retains float indexer state."""
+
+ preserve_auxiliary_kv_state = True
+ step = 8192
+ geometric_growth = True
+
+ def __init__(self, group_size: int = 64, bits: int = 8):
+ super().__init__(group_size=group_size, bits=bits)
+ self._init_indexer_cache()
+
+ @property
+ def state(self):
+ if self.keys is None:
+ keys, values = None, None
+ else:
+ keys, values = super().state
+ return keys, values, self.index_keys, self.index_position_ids
+
+ @state.setter
+ def state(self, value):
+ self.keys, self.values, index_keys, index_position_ids = value
+ self.offset = 0 if self.keys is None else self.keys[0].shape[2]
+ self._geometric_capacity_managed = False
+ self._restore_indexer_state(index_keys, index_position_ids)
+
+ def trim(self, n):
+ n = min(self.offset, n)
+ super().trim(n)
+ self._trim_indexer(self.offset)
+ return n
+
+ def extract(self, idx):
+ cache = QSAQuantizedKVCache(self.group_size, self.bits)
+ if self.keys is not None:
+ cache.keys = tuple(
+ mx.contiguous(x[idx : idx + 1, :, : self.offset, :])
+ for x in self.keys
+ )
+ cache.values = tuple(
+ mx.contiguous(x[idx : idx + 1, :, : self.offset, :])
+ for x in self.values
+ )
+ cache.offset = self.offset
+ cache._geometric_capacity_managed = False
+ if self.index_keys is not None:
+ index_keys = mx.contiguous(self.index_keys[idx : idx + 1])
+ if self.index_position_ids.ndim == 3:
+ index_position_ids = mx.contiguous(
+ self.index_position_ids[:, idx : idx + 1]
+ )
+ else:
+ index_position_ids = mx.contiguous(
+ self.index_position_ids[idx : idx + 1]
+ )
+ cache._restore_indexer_state(index_keys, index_position_ids)
+ return cache
+
+ def filter(self, batch_indices):
+ if self.keys is not None:
+ self.keys = tuple(x[batch_indices] for x in self.keys)
+ self.values = tuple(x[batch_indices] for x in self.values)
+ if self.index_keys is not None:
+ self.index_keys = self.index_keys[batch_indices]
+ if self.index_position_ids.ndim == 3:
+ self.index_position_ids = self.index_position_ids[:, batch_indices]
+ else:
+ self.index_position_ids = self.index_position_ids[batch_indices]
+
+ @property
+ def nbytes(self):
+ size = 0 if self.keys is None else super().nbytes
+ return size + self.indexer_nbytes
+
+
+# Dispatch each decoder layer's graph to the GPU as soon as it is built (decode and
+# verify rows only) so the GPU executes layer i while the host builds layer i+1.
+# Scheduling only: outputs are bit-identical. Disable with OMLX_QWEN4_EAGER_DISPATCH=0.
+_EAGER_DISPATCH = os.environ.get("OMLX_QWEN4_EAGER_DISPATCH", "1").strip().lower() not in {
+ "0",
+ "false",
+ "no",
+ "off",
+}
+_EAGER_DISPATCH_MAX_ROWS = 64
+
+
+class Qwen4ExpRMSNorm(nn.Module):
+ """Qwen4 RMSNorm, whose checkpoint weights are centered at zero."""
+
+ def __init__(self, dim: int, group_size: int | None = None, eps: float = 1e-6):
+ super().__init__()
+ self.eps = eps
+ self.group_size = group_size
+ if group_size is not None and dim % group_size:
+ raise ValueError(f"{dim=} must be divisible by {group_size=}")
+ self.weight = mx.zeros(dim)
+
+ def __call__(self, x: mx.array) -> mx.array:
+ dtype = x.dtype
+ scale = 1.0 + self.weight.astype(mx.float32)
+ if self.group_size is None:
+ return mx.fast.rms_norm(x, scale, self.eps).astype(dtype)
+ # rms_norm takes a 1-D weight, so a grouped norm cannot hand it the
+ # per-group scale; normalise over the group axis and scale afterwards.
+ # The scale stays fp32 -- rounding (1 + w) to bf16 costs half a ULP.
+ y = x.astype(mx.float32).reshape(*x.shape[:-1], -1, self.group_size)
+ y = mx.fast.rms_norm(y, None, self.eps) * scale.reshape(-1, self.group_size)
+ return y.reshape(x.shape).astype(dtype)
+
+
+class Qwen4ExpRMSNormGated(nn.Module):
+ def __init__(self, dim: int, eps: float, activation: str):
+ super().__init__()
+ self.eps = eps
+ self.activation = activation
+ self.weight = mx.ones(dim)
+
+ def __call__(self, x: mx.array, gate: mx.array) -> mx.array:
+ dtype = x.dtype
+ y = mx.fast.rms_norm(x, self.weight, self.eps).astype(mx.float32)
+ gate = gate.astype(mx.float32)
+ if self.activation == "sigmoid":
+ gate = mx.sigmoid(gate)
+ else:
+ gate = nn.silu(gate)
+ return (y * gate).astype(dtype)
+
+
+class Qwen4ExpGatedDeltaNet(Qwen3_5GatedDeltaNet):
+ def __init__(self, config: TextConfig):
+ super().__init__(config)
+ self.norm = Qwen4ExpRMSNormGated(
+ self.head_v_dim,
+ eps=config.rms_norm_eps,
+ activation=config.output_gate_type or config.hidden_act,
+ )
+
+ def _normalize_qk(self, q: mx.array, k: mx.array):
+ # Transformers/FLA uses L2 normalization (epsilon after the sum),
+ # followed by the usual 1/sqrt(head_dim) query scaling.
+ scale = q.shape[-1] ** -0.5
+ q = q * mx.rsqrt(mx.sum(mx.square(q), axis=-1, keepdims=True) + 1e-6)
+ k = k * mx.rsqrt(mx.sum(mx.square(k), axis=-1, keepdims=True) + 1e-6)
+ return q * scale, k
+
+
+class Qwen4ExpQSAIndexer(nn.Module):
+ """Select compressed key blocks using Qwen Sparse Attention scores."""
+
+ def __init__(self, config: TextConfig, rotary_emb):
+ super().__init__()
+ self.n_heads = config.indexer_n_heads
+ self.kv_heads = config.indexer_kv_heads
+ self.head_dim = config.indexer_head_dim
+ self.token_budget = config.indexer_budget
+ self.compress_ratio = config.indexer_compress_ratio
+ self.block_topk = self.token_budget // self.compress_ratio
+ self.rotary_emb = rotary_emb
+ self.index_qk_proj = nn.Linear(
+ config.hidden_size,
+ (self.n_heads + self.kv_heads) * self.head_dim,
+ bias=False,
+ )
+ self.q_layernorm = Qwen4ExpRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.k_layernorm = Qwen4ExpRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+
+ @staticmethod
+ def _default_position_ids(batch: int, start: int, length: int):
+ positions = mx.arange(start, start + length, dtype=mx.int32)
+ return mx.broadcast_to(positions[None], (batch, length))
+
+ def _apply_rope(self, x: mx.array, position_ids: mx.array) -> mx.array:
+ # MRoPE's helper applies the same partial rotary transform to both
+ # operands, so use a throwaway second operand for indexer-only states.
+ rotated, _ = self.rotary_emb.apply_rotary(x, x, position_ids, unsqueeze_dim=1)
+ return rotated
+
+ def __call__(
+ self,
+ hidden_states: mx.array,
+ cache: Optional[QSAKVCache],
+ position_ids: Optional[mx.array],
+ target_verify: bool = False,
+ ) -> Optional[mx.array]:
+ projected = _target_verify_linear(
+ self.index_qk_proj, hidden_states, target_verify
+ )
+ return self.from_projected(projected, cache, position_ids)
+
+ def from_projected(
+ self,
+ qk: mx.array,
+ cache: Optional[QSAKVCache],
+ position_ids: Optional[mx.array],
+ ) -> Optional[mx.array]:
+ batch, seq_len, _ = qk.shape
+ past_len = cache.offset if cache is not None else 0
+ if position_ids is None:
+ position_ids = self._default_position_ids(batch, past_len, seq_len)
+
+ qk = qk.reshape(batch, seq_len, self.n_heads + self.kv_heads, self.head_dim)
+ query = qk[:, :, : self.n_heads]
+ raw_keys = qk[:, :, self.n_heads :].squeeze(2)
+ query = self.q_layernorm(query).transpose(0, 2, 1, 3)
+
+ if cache is not None:
+ raw_keys, full_position_ids = cache.update_indexer(raw_keys, position_ids)
+ else:
+ full_position_ids = position_ids
+
+ key_len = raw_keys.shape[1]
+ if isinstance(past_len, mx.array):
+ # Batched rows carry per-row KV offsets, but the indexer cache is
+ # left-padded to one width; the masks below need aligned-column
+ # scalars or the (batch,) offsets broadcast into the seq axis.
+ past_len = key_len - seq_len
+ max_complete_blocks = key_len // self.compress_ratio
+ if max_complete_blocks <= self.block_topk:
+ return None
+
+ query = self._apply_rope(query, position_ids)
+ complete_key_len = max_complete_blocks * self.compress_ratio
+ if cache is not None and hasattr(cache, "pooled_indexer_keys"):
+ pooled_keys = cache.pooled_indexer_keys(
+ self.compress_ratio,
+ self.k_layernorm,
+ self._apply_rope,
+ cache_tag=self,
+ )
+ else:
+ pooled_keys = pool_completed_index_keys(
+ raw_keys,
+ full_position_ids,
+ compress_ratio=self.compress_ratio,
+ index_key_norm=self.k_layernorm,
+ apply_index_rope=self._apply_rope,
+ )
+ pooled_keys = mx.expand_dims(pooled_keys, axis=1)
+
+ # Score in float32, as the reference does: which blocks win is a discrete
+ # choice, and rounding the products flips the ones near the cut-off.
+ scores = query.astype(mx.float32) @ pooled_keys.astype(mx.float32).transpose(
+ 0, 1, 3, 2
+ )
+ scores = mx.sum(mx.maximum(scores, 0), axis=1)
+ scores = scores / math.sqrt(self.head_dim)
+
+ query_ends = past_len + mx.arange(seq_len) + 1
+ complete_counts = query_ends // self.compress_ratio
+ valid_blocks = (
+ mx.arange(max_complete_blocks)[None, None, :]
+ < complete_counts[None, :, None]
+ )
+ scores = mx.where(valid_blocks, scores, -mx.inf)
+ selected_blocks = mx.argpartition(scores, kth=-self.block_topk, axis=-1)[
+ ..., -self.block_topk :
+ ]
+
+ # Mark the winners on the block axis and widen that to tokens. Comparing
+ # every token against every pick costs seq_len * key_len * block_topk
+ # bytes per prefill step -- 12 GB per sparse layer at a 12k prompt --
+ # against seq_len * key_len here.
+ block_hits = mx.put_along_axis(
+ mx.zeros((batch, seq_len, max_complete_blocks), dtype=mx.bool_),
+ selected_blocks,
+ mx.array(True),
+ axis=-1,
+ )
+ selected_tokens = mx.repeat(block_hits, self.compress_ratio, axis=-1)
+ if complete_key_len < key_len:
+ selected_tokens = mx.concatenate(
+ [
+ selected_tokens,
+ mx.zeros(
+ (batch, seq_len, key_len - complete_key_len), dtype=mx.bool_
+ ),
+ ],
+ axis=-1,
+ )
+
+ token_indices = mx.arange(key_len)
+ tail_starts = complete_counts * self.compress_ratio
+ tail = (token_indices[None, None, :] >= tail_starts[None, :, None]) & (
+ token_indices[None, None, :] < query_ends[None, :, None]
+ )
+ causal = token_indices[None, None, :] < query_ends[None, :, None]
+ use_sparse = complete_counts > self.block_topk
+ selected_tokens = mx.where(
+ use_sparse[None, :, None], selected_tokens | tail, causal
+ )
+ return selected_tokens[:, None]
+
+
+class Qwen4ExpAttention(Qwen3_5Attention):
+ def __init__(self, config: TextConfig):
+ super().__init__(config)
+ self.q_norm = Qwen4ExpRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.k_norm = Qwen4ExpRMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.indexer = Qwen4ExpQSAIndexer(config, self.rotary_emb)
+
+ @staticmethod
+ def _batch_one_text_position_ids(
+ position_ids: Optional[mx.array],
+ length: int,
+ ) -> bool:
+ """Accept absent, 2-D text, or broadcast-identical 3-D text mRoPE."""
+
+ return _broadcast_text_mrope_position_ids(position_ids, length)
+
+ def _gathered_text_prefill_eligible(
+ self,
+ x: mx.array,
+ mask: Optional[mx.array],
+ cache: Optional[Any],
+ position_ids: Optional[mx.array],
+ position_embeddings: Optional[tuple[mx.array, mx.array]],
+ target_verify: bool,
+ ) -> bool:
+ """Fail closed outside the proven contiguous batch-one text shape."""
+
+ causal_mask = mask is None or (isinstance(mask, str) and mask == "causal")
+ if not (
+ x.ndim == 3
+ and x.shape[0] == 1
+ # Narrow multi-row windows (Lightning MTP history/verify passes)
+ # are cheaper on the official masked path; see
+ # _gathered_min_query_tokens.
+ and x.shape[1] >= _gathered_min_query_tokens()
+ and causal_mask
+ and type(cache) is QSAKVCache
+ and isinstance(cache.offset, int)
+ and position_embeddings is None
+ and not target_verify
+ and self._batch_one_text_position_ids(position_ids, x.shape[1])
+ ):
+ return False
+ return bool(
+ # Below the QSA budget the official path attends the complete
+ # prefix directly and is faster than building gathered blocks.
+ # Switch only after sparse selection can reduce actual work.
+ cache.offset + x.shape[1] > self.indexer.token_budget
+ )
+
+ def _gathered_text_decode_eligible(
+ self,
+ x: mx.array,
+ mask: Optional[mx.array],
+ cache: Optional[Any],
+ position_ids: Optional[mx.array],
+ position_embeddings: Optional[tuple[mx.array, mx.array]],
+ target_verify: bool,
+ ) -> bool:
+ """Fail closed outside scalar-offset batch-one text decode.
+
+ Prefill may accept broadcast-identical 3-D text mRoPE. Decode keeps
+ the 2-D / absent predicate until that arm has its own numerical
+ parity coverage.
+ """
+
+ causal_mask = mask is None or (isinstance(mask, str) and mask == "causal")
+ if not (
+ x.ndim == 3
+ and x.shape[:2] == (1, 1)
+ and causal_mask
+ and type(cache) is QSAKVCache
+ and isinstance(cache.offset, int)
+ and position_embeddings is None
+ and not target_verify
+ and (
+ position_ids is None
+ or (
+ position_ids.ndim == 2
+ and tuple(position_ids.shape) == (1, 1)
+ )
+ )
+ ):
+ return False
+
+ # A restored/foreign cache without aligned auxiliary indexer state must
+ # stay on the official path. The gathered arm cannot safely discover
+ # that mismatch after it has appended the new main K/V row.
+ if cache.offset:
+ if cache.index_keys is None or cache.index_position_ids is None:
+ return False
+ if (
+ cache.index_keys.shape[1] != cache.offset
+ or cache.index_position_ids.shape[-1] != cache.offset
+ ):
+ return False
+
+ prospective_blocks = (cache.offset + 1) // self.indexer.compress_ratio
+ return prospective_blocks > self.indexer.block_topk
+
+ def _gathered_text_prefill(
+ self,
+ x: mx.array,
+ cache: QSAKVCache,
+ position_ids: Optional[mx.array] = None,
+ ) -> mx.array:
+ """Project once, append both caches, and attend only to selected K/V."""
+
+ batch, length, _ = x.shape
+ q_proj_output, keys, values = _target_verify_linears(
+ (self.q_proj, self.k_proj, self.v_proj),
+ x,
+ False,
+ )
+ queries, gate = mx.split(
+ q_proj_output.reshape(batch, length, self.num_attention_heads, -1),
+ 2,
+ axis=-1,
+ )
+ gate = gate.reshape(batch, length, -1)
+ queries = self.q_norm(queries).transpose(0, 2, 1, 3)
+ keys = self.k_norm(
+ keys.reshape(batch, length, self.num_key_value_heads, self.head_dim)
+ ).transpose(0, 2, 1, 3)
+ values = values.reshape(
+ batch, length, self.num_key_value_heads, self.head_dim
+ ).transpose(0, 2, 1, 3)
+
+ past_len = cache.offset
+ text_position_ids, rotary_position_ids = _split_text_mrope_positions(
+ position_ids, batch, length, past_len
+ )
+ queries, keys = self.rotary_emb.apply_rotary(
+ queries,
+ keys,
+ rotary_position_ids,
+ unsqueeze_dim=1,
+ )
+ keys, values = cache.update_and_fetch(keys, values)
+
+ projected = self.indexer.index_qk_proj(x).reshape(
+ batch,
+ length,
+ self.indexer.n_heads + self.indexer.kv_heads,
+ self.indexer.head_dim,
+ )
+ index_queries = self.indexer.q_layernorm(
+ projected[:, :, : self.indexer.n_heads]
+ ).transpose(0, 2, 1, 3)
+ raw_index_keys = projected[:, :, self.indexer.n_heads :].squeeze(2)
+ raw_index_keys, full_position_ids = cache.update_indexer(
+ raw_index_keys,
+ text_position_ids,
+ )
+ pooled_index_keys = cache.pooled_indexer_keys(
+ self.indexer.compress_ratio,
+ self.indexer.k_layernorm,
+ self.indexer._apply_rope,
+ cache_tag=self.indexer,
+ )
+ index_queries = self.indexer._apply_rope(
+ index_queries,
+ text_position_ids,
+ ).transpose(0, 2, 1, 3)
+
+ output = contiguous_causal_gathered_qsa(
+ queries,
+ keys,
+ values,
+ index_queries,
+ raw_index_keys,
+ full_position_ids,
+ num_query_heads=self.num_attention_heads,
+ num_key_value_heads=self.num_key_value_heads,
+ head_dim=self.head_dim,
+ indexer_head_dim=self.indexer.head_dim,
+ compress_ratio=self.indexer.compress_ratio,
+ token_budget=self.indexer.token_budget,
+ index_key_norm=self.indexer.k_layernorm,
+ apply_index_rope=self.indexer._apply_rope,
+ pooled_index_keys=pooled_index_keys,
+ )
+ output = output.reshape(batch, length, -1)
+ return self.o_proj(output * mx.sigmoid(gate))
+
+ def _gathered_text_decode(
+ self,
+ x: mx.array,
+ cache: QSAKVCache,
+ position_ids: Optional[mx.array] = None,
+ ) -> mx.array:
+ """Append one token and attend only to QSA-selected cached K/V rows."""
+
+ batch, length, _ = x.shape
+ q_proj_output, new_keys, new_values = _target_verify_linears(
+ (self.q_proj, self.k_proj, self.v_proj),
+ x,
+ False,
+ )
+ queries, gate = mx.split(
+ q_proj_output.reshape(batch, length, self.num_attention_heads, -1),
+ 2,
+ axis=-1,
+ )
+ gate = gate.reshape(batch, length, -1)
+ queries = self.q_norm(queries).transpose(0, 2, 1, 3)
+ new_keys = self.k_norm(
+ new_keys.reshape(
+ batch,
+ length,
+ self.num_key_value_heads,
+ self.head_dim,
+ )
+ ).transpose(0, 2, 1, 3)
+ new_values = new_values.reshape(
+ batch,
+ length,
+ self.num_key_value_heads,
+ self.head_dim,
+ ).transpose(0, 2, 1, 3)
+
+ past_len = cache.offset
+ text_position_ids, rotary_position_ids = _split_text_mrope_positions(
+ position_ids, batch, length, past_len
+ )
+ queries, new_keys = self.rotary_emb.apply_rotary(
+ queries,
+ new_keys,
+ rotary_position_ids,
+ unsqueeze_dim=1,
+ )
+ keys, values = cache.update_and_fetch(new_keys, new_values)
+
+ projected = self.indexer.index_qk_proj(x).reshape(
+ batch,
+ length,
+ self.indexer.n_heads + self.indexer.kv_heads,
+ self.indexer.head_dim,
+ )
+ index_queries = self.indexer.q_layernorm(
+ projected[:, :, : self.indexer.n_heads]
+ ).transpose(0, 2, 1, 3)
+ raw_index_keys = projected[:, :, self.indexer.n_heads :].squeeze(2)
+ cache.update_indexer(raw_index_keys, text_position_ids)
+ pooled_index_keys = cache.pooled_indexer_keys(
+ self.indexer.compress_ratio,
+ self.indexer.k_layernorm,
+ self.indexer._apply_rope,
+ cache_tag=self.indexer,
+ )
+ index_queries = self.indexer._apply_rope(
+ index_queries,
+ text_position_ids,
+ ).transpose(0, 2, 1, 3)
+
+ output = contiguous_causal_gathered_qsa_decode(
+ queries,
+ keys,
+ values,
+ index_queries,
+ pooled_index_keys,
+ num_query_heads=self.num_attention_heads,
+ num_key_value_heads=self.num_key_value_heads,
+ head_dim=self.head_dim,
+ indexer_head_dim=self.indexer.head_dim,
+ compress_ratio=self.indexer.compress_ratio,
+ token_budget=self.indexer.token_budget,
+ )
+ output = output.reshape(batch, length, -1)
+ return self.o_proj(output * mx.sigmoid(gate))
+
+ def __call__(
+ self,
+ x: mx.array,
+ mask: Optional[mx.array] = None,
+ cache: Optional[Any] = None,
+ position_ids: Optional[mx.array] = None,
+ position_embeddings: Optional[tuple[mx.array, mx.array]] = None,
+ target_verify: bool = False,
+ ) -> mx.array:
+ if self._gathered_text_decode_eligible(
+ x,
+ mask,
+ cache,
+ position_ids,
+ position_embeddings,
+ target_verify,
+ ):
+ return self._gathered_text_decode(x, cache, position_ids)
+
+ if self._gathered_text_prefill_eligible(
+ x,
+ mask,
+ cache,
+ position_ids,
+ position_embeddings,
+ target_verify,
+ ):
+ cache._omlx_last_prefill_gathered = True
+ return self._gathered_text_prefill(x, cache, position_ids)
+
+ if cache is not None and x.ndim == 3 and x.shape[1] > 1:
+ cache._omlx_last_prefill_gathered = False
+ qsa_mask = self.indexer(
+ x,
+ cache,
+ position_ids,
+ target_verify=target_verify,
+ )
+ if qsa_mask is not None:
+ if mask is None or (isinstance(mask, str) and mask == "causal"):
+ mask = qsa_mask
+ elif isinstance(mask, mx.array):
+ if mask.dtype == mx.bool_:
+ mask = mask & qsa_mask
+ else:
+ sparse_bias = mx.where(qsa_mask, 0.0, -mx.inf).astype(mask.dtype)
+ mask = mask + sparse_bias
+ # The specialized left-padded decode path remains dense. It is
+ # uncommon, and preserving its row-specific cache semantics is
+ # preferable to applying an incorrectly aligned sparse mask.
+ return super().__call__(
+ x,
+ mask=mask,
+ cache=cache,
+ position_ids=position_ids,
+ position_embeddings=position_embeddings,
+ target_verify=target_verify,
+ )
+
+
+class Qwen4ExpGatedResidual(nn.Module):
+ def __init__(self, config: TextConfig, use_combine: bool = True):
+ super().__init__()
+ self.hc_count = config.hc_count
+ self.hidden_size = config.hidden_size
+ self.hc_lowrank = config.hc_lowrank
+ hc_hidden_size = self.hc_count * self.hidden_size
+ self.hc_norm = Qwen4ExpRMSNorm(
+ hc_hidden_size,
+ group_size=self.hidden_size,
+ eps=config.rms_norm_eps,
+ )
+ self.input_mix_weight_down = nn.Linear(
+ hc_hidden_size, config.hc_lowrank, bias=False
+ )
+ self.input_mix_weight_up = nn.Linear(
+ config.hc_lowrank, hc_hidden_size, bias=False
+ )
+ if use_combine:
+ self.block_inject_weight = nn.Linear(
+ hc_hidden_size, self.hc_count, bias=False
+ )
+
+ def __call__(self, hyper_input: mx.array, target_verify: bool = False):
+ if hc_fused.compatible(self, hyper_input):
+ fused = hc_fused.fused_forward(self, hyper_input)
+ if fused is not None:
+ return fused
+ compiled_forward = getattr(self, "_compiled_forward", None)
+ if (
+ compiled_forward is not None
+ and not target_verify
+ and hyper_input.ndim == 3
+ and hyper_input.shape[:2] == (1, 1)
+ and hyper_input.dtype == mx.bfloat16
+ and not get_mtp_runtime().enabled
+ ):
+ return compiled_forward(hyper_input)
+ return self._forward(hyper_input, target_verify=target_verify)
+
+ def _forward(self, hyper_input: mx.array, target_verify: bool = False):
+ normed = self.hc_norm(hyper_input)
+ hybrid = None
+ if (
+ getattr(self, "_omlx_exact_hybrid_projection", False)
+ and not target_verify
+ and hyper_input.shape == (1, 1, 10240)
+ and hyper_input.dtype == mx.bfloat16
+ and not get_mtp_runtime().enabled
+ ):
+ from .hc_projection import hybrid_projection
+
+ hybrid = hybrid_projection(
+ normed,
+ self.input_mix_weight_down,
+ self.block_inject_weight,
+ )
+ input_inject_weight = getattr(self, "input_inject_weight", None)
+ if hybrid is not None:
+ mix = hybrid[..., : self.hc_lowrank]
+ block_injection = hybrid[
+ ..., self.hc_lowrank : self.hc_lowrank + self.hc_count
+ ]
+ elif input_inject_weight is None:
+ mix = _target_verify_linear(
+ self.input_mix_weight_down, normed, target_verify
+ )
+ block_injection = (
+ _target_verify_linear(
+ self.block_inject_weight, normed, target_verify
+ )
+ if "block_inject_weight" in self
+ else None
+ )
+ else:
+ combined = _target_verify_linear(
+ input_inject_weight,
+ normed,
+ target_verify,
+ )
+ indices = _HYPER_SPLIT_INDICES.get((self.hc_lowrank, self.hc_count))
+ if indices is None:
+ indices = (
+ mx.arange(self.hc_lowrank, dtype=mx.int32),
+ mx.arange(
+ self.hc_lowrank,
+ self.hc_lowrank + self.hc_count,
+ dtype=mx.int32,
+ ),
+ )
+ _HYPER_SPLIT_INDICES[(self.hc_lowrank, self.hc_count)] = indices
+ mix = mx.take(combined, indices[0], axis=-1)
+ block_injection = mx.take(combined, indices[1], axis=-1)
+
+ mix = nn.silu(mix / self.hc_count)
+ mix = mx.sigmoid(
+ _target_verify_linear(
+ self.input_mix_weight_up,
+ mix,
+ target_verify,
+ )
+ )
+ mix = mix.reshape(*mix.shape[:-1], self.hc_count, self.hidden_size)
+ streams = normed.reshape(*normed.shape[:-1], self.hc_count, self.hidden_size)
+ mixed_input = mx.mean(mix * streams, axis=-2)
+ if block_injection is None:
+ return mixed_input
+ injection_weights = 2 * mx.sigmoid(
+ block_injection / self.hc_count
+ )
+ return mixed_input, hyper_input, injection_weights
+
+
+def _matching_projection_tensor(left: nn.Module, right: nn.Module, name: str) -> bool:
+ left_has = hasattr(left, name)
+ right_has = hasattr(right, name)
+ if left_has != right_has:
+ return False
+ if not left_has:
+ return True
+
+ left_value = getattr(left, name)
+ right_value = getattr(right, name)
+ if left_value is None or right_value is None:
+ return left_value is None and right_value is None
+ return (
+ isinstance(left_value, mx.array)
+ and isinstance(right_value, mx.array)
+ and left_value.ndim > 0
+ and left_value.ndim == right_value.ndim
+ and left_value.shape[1:] == right_value.shape[1:]
+ and left_value.dtype == right_value.dtype
+ )
+
+
+def _can_fuse_hyper_connection(module: Qwen4ExpGatedResidual) -> bool:
+ """Fail closed unless both projections have identical MLX semantics."""
+ if type(module) is not Qwen4ExpGatedResidual:
+ return False
+ if (
+ hasattr(module, "input_inject_weight")
+ or hasattr(module, "_compiled_forward")
+ or getattr(module, "_omlx_exact_hybrid_projection", False)
+ ):
+ return False
+
+ down = getattr(module, "input_mix_weight_down", None)
+ injection = getattr(module, "block_inject_weight", None)
+ if down is None or injection is None or type(down) is not type(injection):
+ return False
+ if type(down) not in (nn.Linear, nn.QuantizedLinear):
+ return False
+ if not _matching_projection_tensor(down, injection, "weight"):
+ return False
+ if (
+ down.weight.shape[0] != module.hc_lowrank
+ or injection.weight.shape[0] != module.hc_count
+ ):
+ return False
+ for attribute in ("group_size", "bits", "mode"):
+ if getattr(down, attribute, None) != getattr(injection, attribute, None):
+ return False
+ return all(
+ _matching_projection_tensor(down, injection, name)
+ for name in ("scales", "biases", "bias")
+ )
+
+
+def _can_prepare_exact_hybrid(module: Qwen4ExpGatedResidual) -> bool:
+ if not (
+ module.hc_count == 4
+ and module.hidden_size == 2560
+ and module.hc_lowrank == 320
+ ):
+ return False
+ from .hc_projection import compatible_projections
+
+ return compatible_projections(
+ module.input_mix_weight_down,
+ module.block_inject_weight,
+ )
+
+
+def _unique_hyper_connections(model: nn.Module):
+ modules = [model]
+ modules.extend(module for _, module in model.named_modules() if module is not model)
+ seen = set()
+ for module in modules:
+ if id(module) in seen:
+ continue
+ seen.add(id(module))
+ if type(module) is Qwen4ExpGatedResidual:
+ yield module
+
+
+def fuse_hyper_connection_projections(model: nn.Module) -> int:
+ """Prepare the lossless one-dispatch Qwen4 decode projection.
+
+ The tempting 324-row concatenation was rejected because MLX changes its
+ QMV traversal at that width and can change raw BF16 outputs. The raw
+ 320-row low-rank and four-row injection banks deliberately remain separate
+ so every fallback retains the checkpoint's canonical two projections.
+ """
+ targets = [
+ module
+ for module in _unique_hyper_connections(model)
+ if _can_fuse_hyper_connection(module)
+ and _can_prepare_exact_hybrid(module)
+ ]
+ for module in targets:
+ module._omlx_exact_hybrid_projection = True
+ return len(targets)
+
+
+def compile_hyper_connections(model: nn.Module) -> int:
+ """Compile each hyper-connection's strict single-token decode path once."""
+ compiled = 0
+ for module in _unique_hyper_connections(model):
+ if hasattr(module, "_compiled_forward"):
+ continue
+ module._compiled_forward = mx.compile(module._forward)
+ compiled += 1
+ return compiled
+
+
+_MASK64 = (1 << 64) - 1
+_SPLITMIX_GAMMA = 0x9E3779B97F4A7C15
+_SPLITMIX_M1 = 0xBF58476D1CE4E5B9
+_SPLITMIX_M2 = 0x94D049BB133111EB
+_PRIME_1 = 10007
+
+
+def _splitmix64(value: int) -> int:
+ value = (value + _SPLITMIX_GAMMA) & _MASK64
+ value = ((value ^ (value >> 30)) * _SPLITMIX_M1) & _MASK64
+ value = ((value ^ (value >> 27)) * _SPLITMIX_M2) & _MASK64
+ return (value ^ (value >> 31)) & _MASK64
+
+
+def _build_layer_multipliers(
+ unigram_vocab_size: int, ngram_size: int, ple_layer_index: int, seed: int
+):
+ max_long = (1 << 63) - 1
+ multiplier_max = max_long // max(unigram_vocab_size, 1)
+ half_bound = max(1, multiplier_max // 2)
+ base_seed = seed + _PRIME_1 * ple_layer_index
+ multipliers = []
+ for index in range(ngram_size):
+ value = (base_seed + _SPLITMIX_GAMMA * (index + 1)) & _MASK64
+ multipliers.append(2 * (_splitmix64(value) % half_bound) + 1)
+ return mx.array(multipliers, dtype=mx.int64)
+
+
+def _is_prime(value: int) -> bool:
+ if value < 2:
+ return False
+ if value % 2 == 0:
+ return value == 2
+ for divisor in range(3, math.isqrt(value) + 1, 2):
+ if value % divisor == 0:
+ return False
+ return True
+
+
+def _find_nth_prime_after(start: int, count: int) -> int:
+ prime = start
+ for _ in range(count):
+ prime += 1
+ while not _is_prime(prime):
+ prime += 1
+ return prime
+
+
+class _SafeTensorMMap:
+ """Read selected dense or affine-packed rows without resident weights."""
+
+ def __init__(self, path: Path):
+ self.path = path
+ self._file = path.open("rb")
+ header_size = struct.unpack(" tuple[int, ...]:
+ return tuple(self._header[key]["shape"])
+
+ def tensor_dtype(self, key: str) -> str:
+ return str(self._header[key]["dtype"])
+
+ def rows(self, key: str, rows: list[int]) -> mx.array:
+ entry = self._header[key]
+ shape = tuple(entry["shape"])
+ start, end = entry["data_offsets"]
+ dtype = entry["dtype"]
+ dtype_info = {
+ "BF16": (np.dtype(" _SafeTensorMMap:
+ filename = weight_map[key]
+ reader = self._readers.get(filename)
+ if reader is None:
+ reader = _SafeTensorMMap(model_path / filename)
+ self._readers[filename] = reader
+ self._tensor_readers[key] = reader
+ return reader
+
+ runtime_prefix = prefix
+ if runtime_prefix.startswith("model.language_model."):
+ runtime_prefix = (
+ "language_model.model." + runtime_prefix[len("model.language_model.") :]
+ )
+ for shard_index, shard_size in enumerate(self.shard_sizes):
+ bases = (
+ f"{prefix}.shard_{shard_index}",
+ f"{prefix}.shards.{shard_index}",
+ f"{runtime_prefix}.shard_{shard_index}",
+ f"{runtime_prefix}.shards.{shard_index}",
+ )
+ base = next(
+ (
+ candidate
+ for candidate in bases
+ if f"{candidate}.weight" in weight_map
+ ),
+ None,
+ )
+ if base is None:
+ raise KeyError(
+ f"SSD-backed PLE shard {shard_index} is absent; "
+ f"checked {', '.join(bases)}"
+ )
+
+ weight_key = f"{base}.weight"
+ scales_key = f"{base}.scales"
+ biases_key = f"{base}.biases"
+ weight_reader = register_reader(weight_key)
+ weight_shape = weight_reader.tensor_shape(weight_key)
+ weight_dtype = weight_reader.tensor_dtype(weight_key)
+ if len(weight_shape) != 2 or weight_shape[0] != shard_size:
+ raise ValueError(f"Unexpected shape for {weight_key}: {weight_shape}")
+
+ if scales_key not in weight_map and biases_key not in weight_map:
+ if weight_shape[1] != dims:
+ raise ValueError(
+ f"Unexpected dense PLE width for {weight_key}: "
+ f"expected {dims}, got {weight_shape[1]}"
+ )
+ if weight_dtype not in {"BF16", "F16", "F32", "F8_E4M3"}:
+ raise TypeError(
+ f"SSD-backed dense Qwen4 PLE does not support {weight_dtype}"
+ )
+ self._shard_specs[shard_index] = (
+ weight_key,
+ None,
+ None,
+ None,
+ None,
+ )
+ continue
+
+ if scales_key not in weight_map or biases_key not in weight_map:
+ raise ValueError(
+ f"Incomplete affine PLE tensors for {base}: both scales and "
+ "biases are required"
+ )
+ if weight_dtype != "U32":
+ raise TypeError(
+ f"Affine Qwen4 PLE weight must be U32, got {weight_dtype} "
+ f"for {weight_key}"
+ )
+
+ scales_reader = register_reader(scales_key)
+ biases_reader = register_reader(biases_key)
+ scales_shape = scales_reader.tensor_shape(scales_key)
+ biases_shape = biases_reader.tensor_shape(biases_key)
+ if scales_shape != biases_shape or len(scales_shape) != 2:
+ raise ValueError(
+ f"Invalid affine PLE parameter shapes for {base}: "
+ f"scales={scales_shape}, biases={biases_shape}"
+ )
+ if scales_shape[0] != shard_size or scales_shape[1] <= 0:
+ raise ValueError(
+ f"Unexpected affine PLE scale shape for {base}: {scales_shape}"
+ )
+ if dims % scales_shape[1] != 0:
+ raise ValueError(
+ f"Cannot infer affine PLE group size for {base}: "
+ f"dims={dims}, scales={scales_shape}"
+ )
+ group_size = dims // scales_shape[1]
+ packed_bits = weight_shape[1] * 32
+ if packed_bits % dims != 0:
+ raise ValueError(
+ f"Cannot infer affine PLE bits for {base}: "
+ f"dims={dims}, packed_shape={weight_shape}"
+ )
+ bits = packed_bits // dims
+ if bits not in {2, 3, 4, 5, 6, 8} or group_size not in {32, 64, 128}:
+ raise ValueError(
+ f"Unsupported affine PLE layout for {base}: "
+ f"bits={bits}, group_size={group_size}"
+ )
+ if dims % group_size or weight_shape[1] != dims * bits // 32:
+ raise ValueError(
+ f"Inconsistent affine PLE layout for {base}: "
+ f"weight={weight_shape}, scales={scales_shape}, dims={dims}"
+ )
+ self._shard_specs[shard_index] = (
+ weight_key,
+ scales_key,
+ biases_key,
+ bits,
+ group_size,
+ )
+
+ def __call__(self, indices: mx.array) -> mx.array:
+ shape = indices.shape
+ flat = indices.reshape(-1)
+ mx.eval(flat)
+ host_indices = [int(index) for index in flat.tolist()]
+ if any(index < 0 or index >= self.shard_offsets[-1] for index in host_indices):
+ raise IndexError("embedding index is outside the sharded vocabulary")
+ shard_indices = [
+ bisect_right(self.shard_offsets, index) - 1 for index in host_indices
+ ]
+ touched = tuple(sorted(set(shard_indices)))
+ self.last_touched_shards = touched
+ self.rows_read = 0
+ result = mx.zeros((len(host_indices), self.dims), dtype=mx.bfloat16)
+ for shard_index in touched:
+ positions = [
+ i
+ for i, current_shard in enumerate(shard_indices)
+ if current_shard == shard_index
+ ]
+ local = [
+ host_indices[i] - self.shard_offsets[shard_index] for i in positions
+ ]
+ weight_key, scales_key, biases_key, bits, group_size = self._shard_specs[
+ shard_index
+ ]
+ values = self._tensor_readers[weight_key].rows(weight_key, local)
+ if bits is not None:
+ assert scales_key is not None
+ assert biases_key is not None
+ assert group_size is not None
+ scales = self._tensor_readers[scales_key].rows(scales_key, local)
+ biases = self._tensor_readers[biases_key].rows(biases_key, local)
+ values = mx.dequantize(
+ values,
+ scales,
+ biases,
+ group_size=group_size,
+ bits=bits,
+ mode="affine",
+ )
+ values = values.astype(mx.bfloat16) * self.weight_scale
+ self.rows_read += len(local)
+ result = result.at[mx.array(positions, dtype=mx.int32)].add(values)
+ return result.reshape(*shape, self.dims)
+
+ def close(self):
+ for reader in self._readers.values():
+ reader.close()
+ self._readers.clear()
+ self._tensor_readers.clear()
+ self._shard_specs.clear()
+
+ @property
+ def _prefix(self):
+ return self.__prefix
+
+ @_prefix.setter
+ def _prefix(self, value):
+ self.__prefix = value
+
+
+class ShardedEmbedding(nn.Module):
+ """Embedding kept in checkpoint-sized row shards to avoid a 100 GB join."""
+
+ def __init__(self, num_embeddings: int, dims: int, num_shards: int):
+ super().__init__()
+ if num_shards <= 0 or num_shards > num_embeddings:
+ raise ValueError("num_shards must be in [1, num_embeddings]")
+ base, remainder = divmod(num_embeddings, num_shards)
+ self.shard_sizes = tuple(
+ base + (1 if index < remainder else 0) for index in range(num_shards)
+ )
+ self.shards = [nn.Embedding(size, dims) for size in self.shard_sizes]
+ # Official FP8 checkpoints keep one shared scale for every PLE shard.
+ # Decode only the selected rows so the 100 GB table stays compact.
+ self.weight_scale = mx.ones((1,), dtype=mx.bfloat16)
+ offsets = [0]
+ for size in self.shard_sizes:
+ offsets.append(offsets[-1] + size)
+ self.shard_offsets = tuple(offsets)
+ self.dims = dims
+
+ def __call__(self, indices: mx.array) -> mx.array:
+ fused = getattr(self, "fused", None)
+ if fused is not None:
+ return fused(indices) * self.weight_scale
+
+ flat = indices.reshape(-1)
+ # One tiny host sync avoids scheduling gathers against all 128 giant
+ # PLE shards for every token.
+ mx.eval(flat)
+ host_indices = [int(index) for index in flat.tolist()]
+ if not host_indices:
+ return self.shards[0](flat).reshape(*indices.shape, self.dims)
+ if any(index < 0 or index >= self.shard_offsets[-1] for index in host_indices):
+ raise IndexError("embedding index is outside the sharded vocabulary")
+
+ shard_indices = [
+ bisect_right(self.shard_offsets, index) - 1 for index in host_indices
+ ]
+ result = None
+ for shard_index in sorted(set(shard_indices)):
+ positions_list = [
+ position
+ for position, current_shard in enumerate(shard_indices)
+ if current_shard == shard_index
+ ]
+ local_indices = [
+ host_indices[position] - self.shard_offsets[shard_index]
+ for position in positions_list
+ ]
+ positions = mx.array(positions_list, dtype=mx.int32)
+ values = self.shards[shard_index](mx.array(local_indices, dtype=mx.int32))
+ if values.dtype == mx.uint8:
+ values = mx.from_fp8(values, dtype=mx.bfloat16)
+ values = values * self.weight_scale
+ if result is None:
+ result = mx.zeros((len(host_indices), self.dims), dtype=values.dtype)
+ result = result.at[positions].add(values)
+ return result.reshape(*indices.shape, self.dims)
+
+ def fuse_quantized_shards(self) -> bool:
+ """Join compatible packed shards without dequantizing the PLE table.
+
+ Resident Qwen4 PLE otherwise synchronizes token IDs to the host before
+ every lookup so it can choose among 128 enormous shard buffers. A
+ single packed embedding keeps exactly the same affine rows while making
+ the lookup a normal device-side gather. The caller owns the temporary
+ peak-memory admission check required while old and joined buffers
+ coexist.
+ """
+
+ if getattr(self, "fused", None) is not None:
+ return False
+ shards = list(self.shards)
+ if not shards or not all(
+ type(shard) is nn.QuantizedEmbedding for shard in shards
+ ):
+ return False
+ first = shards[0]
+ if not all(
+ shard.dims == first.dims
+ and shard.group_size == first.group_size
+ and shard.bits == first.bits
+ and shard.mode == first.mode
+ and shard.weight.dtype == first.weight.dtype
+ and shard.scales.dtype == first.scales.dtype
+ and (shard.biases is None) == (first.biases is None)
+ and (shard.biases is None or shard.biases.dtype == first.biases.dtype)
+ for shard in shards
+ ):
+ return False
+
+ total_rows = sum(int(shard.weight.shape[0]) for shard in shards)
+ if total_rows != self.shard_offsets[-1] or first.dims != self.dims:
+ return False
+
+ fused = nn.QuantizedEmbedding(
+ 1,
+ self.dims,
+ group_size=first.group_size,
+ bits=first.bits,
+ mode=first.mode,
+ )
+ fused.weight = mx.concatenate([shard.weight for shard in shards], axis=0)
+ fused.scales = mx.concatenate([shard.scales for shard in shards], axis=0)
+ if first.biases is None:
+ fused.biases = None
+ else:
+ fused.biases = mx.concatenate([shard.biases for shard in shards], axis=0)
+ fused.num_embeddings = total_rows
+ arrays = [fused.weight, fused.scales]
+ if fused.biases is not None:
+ arrays.append(fused.biases)
+ mx.eval(*arrays)
+ self.fused = fused
+ self.shards = []
+ return True
+
+
+def fuse_resident_ple_embeddings(
+ model: nn.Module,
+ *,
+ minimum_physical_memory: int = 192 * 1024**3,
+) -> int:
+ """Fuse resident affine PLE shards only where the temporary peak is safe."""
+
+ if get_ple_runtime_mode() != "resident":
+ return 0
+ physical_memory = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
+ if physical_memory < minimum_physical_memory:
+ return 0
+
+ fused = 0
+ language_model = getattr(model, "language_model", None)
+ layers = getattr(getattr(language_model, "model", None), "layers", ())
+ for layer in layers:
+ ple = getattr(layer, "ple", None)
+ embedding = getattr(
+ getattr(ple, "ple_embedding", None),
+ "ngram_embedding",
+ None,
+ )
+ if type(embedding) is ShardedEmbedding and embedding.fuse_quantized_shards():
+ fused += 1
+ return fused
+
+
+class Qwen4ExpNGramEmbedding(nn.Module):
+ def __init__(
+ self,
+ config: TextConfig,
+ embedding_dim: int,
+ layer_idx: int,
+ ple_layer_index: int,
+ ):
+ super().__init__()
+ self.layer_idx = layer_idx
+ self.ngram_size = config.ngram_size
+ self.context_len = self.ngram_size - 1
+ self.heads_per_ngram = config.heads_per_ngram
+ self.ngram_heads = self.context_len * self.heads_per_ngram
+ self.ple_layer_index = ple_layer_index
+ self.unigram_vocab_size = config.vocab_size
+ self.seed = config.seed
+ eos = config.eos_token_id
+ self.eos_token_id = eos[0] if isinstance(eos, list) else eos
+
+ head_vocab_sizes = []
+ head_offsets = []
+ total_vocab_size = 0
+ for head_idx in range(self.ngram_heads):
+ global_head_idx = ple_layer_index * self.ngram_heads + head_idx
+ size = _find_nth_prime_after(
+ config.ngram_vocab_size_base - 1, global_head_idx + 1
+ )
+ head_vocab_sizes.append(size)
+ head_offsets.append(total_vocab_size)
+ total_vocab_size += size
+
+ self.layer_multipliers = _build_layer_multipliers(
+ self.unigram_vocab_size,
+ self.ngram_size,
+ ple_layer_index,
+ self.seed,
+ )
+ self.ngram_heads_vocab_sizes = mx.array(head_vocab_sizes, dtype=mx.int64)
+ self.ngram_heads_offsets = mx.array(head_offsets, dtype=mx.int64)
+ divisor = config.make_ngram_vocab_size_divisible_by
+ padded_vocab_size = math.ceil(total_vocab_size / divisor) * divisor
+ embedding_args = (
+ padded_vocab_size,
+ embedding_dim // self.ngram_heads,
+ config.split_ngram_parts,
+ )
+ if _PLE_RUNTIME_MODE == "mmap":
+ if _PLE_RUNTIME_MODEL_PATH is None:
+ raise RuntimeError("SSD-backed PLE has no configured model path")
+ prefix = (
+ f"model.language_model.layers.{layer_idx}.ple.ple_embedding."
+ "ngram_embedding"
+ )
+ self.ngram_embedding = DiskBackedShardedEmbedding(
+ _PLE_RUNTIME_MODEL_PATH,
+ prefix,
+ *embedding_args,
+ )
+ else:
+ self.ngram_embedding = ShardedEmbedding(*embedding_args)
+
+ def _shift_right_ignore_eos(self, token_ids: mx.array, shift: int):
+ if shift == 0:
+ return token_ids
+ batch, seq_len = token_ids.shape
+ positions = mx.arange(seq_len, dtype=mx.int64)
+ eos_positions = mx.where(token_ids == self.eos_token_id, positions, -1)
+ previous_eos_inclusive = mx.cummax(eos_positions, axis=1)
+ previous_eos = mx.concatenate(
+ [mx.full((batch, 1), -1, dtype=mx.int64), previous_eos_inclusive[:, :-1]],
+ axis=1,
+ )
+ segment_start = previous_eos + 1
+ position_in_segment = positions[None] - segment_start
+ source_positions = positions - shift
+ gather_positions = mx.broadcast_to(
+ mx.maximum(source_positions, 0)[None], (batch, seq_len)
+ )
+ shifted = mx.take_along_axis(token_ids, gather_positions, axis=1)
+ valid = (position_in_segment >= shift) & (source_positions[None] >= 0)
+ return mx.where(valid, shifted, self.eos_token_id)
+
+ def _previous_context(
+ self, input_ids: mx.array, cache: ArraysCache | None
+ ) -> mx.array:
+ batch = input_ids.shape[0]
+ if cache is not None and cache[3] is not None:
+ return cache[3]
+ return mx.full(
+ (batch, self.context_len), self.eos_token_id, dtype=mx.int64
+ )
+
+ def __call__(self, input_ids: mx.array, cache: Optional[ArraysCache]):
+ input_ids = input_ids.astype(mx.int64)
+ previous_context = self._previous_context(input_ids, cache)
+
+ token_history = mx.concatenate([previous_context, input_ids], axis=-1)
+ if cache is not None:
+ cache[3] = mx.contiguous(token_history[:, -self.context_len :])
+
+ shifted_tokens = [
+ self._shift_right_ignore_eos(token_history, shift)
+ for shift in range(self.ngram_size)
+ ]
+ blocks = []
+ for ngram in range(2, self.ngram_size + 1):
+ start = (ngram - 2) * self.heads_per_ngram
+ end = start + self.heads_per_ngram
+ mixed_ids = shifted_tokens[0] * self.layer_multipliers[0]
+ for position in range(1, ngram):
+ mixed_ids = mx.bitwise_xor(
+ mixed_ids,
+ shifted_tokens[position] * self.layer_multipliers[position],
+ )
+ sizes = self.ngram_heads_vocab_sizes[start:end]
+ offsets = self.ngram_heads_offsets[start:end]
+ ngram_ids = mixed_ids[..., None] % sizes[None, None]
+ blocks.append(ngram_ids + offsets[None, None])
+
+ ngram_ids = mx.concatenate(blocks, axis=-1)[:, -input_ids.shape[1] :]
+ embeddings = self.ngram_embedding(ngram_ids)
+ return embeddings.reshape(*embeddings.shape[:-2], -1)
+
+
+class Qwen4ExpPLELayer(nn.Module):
+ def __init__(self, config: TextConfig, layer_idx: int, ple_layer_index: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.hc_count = config.hc_count
+ hc_hidden_size = self.hidden_size * self.hc_count
+ self.ple_embedding = Qwen4ExpNGramEmbedding(
+ config, config.ple_embed_dim, layer_idx, ple_layer_index
+ )
+ self.key_proj = nn.Linear(config.ple_embed_dim, hc_hidden_size, bias=False)
+ self.value_proj = nn.Linear(config.ple_embed_dim, self.hidden_size, bias=False)
+ self.norm_key = Qwen4ExpRMSNorm(
+ hc_hidden_size,
+ group_size=self.hidden_size,
+ eps=config.rms_norm_eps,
+ )
+ self.norm_query = Qwen4ExpRMSNorm(
+ hc_hidden_size,
+ group_size=self.hidden_size,
+ eps=config.rms_norm_eps,
+ )
+ self.norm_conv = Qwen4ExpRMSNorm(
+ hc_hidden_size,
+ group_size=self.hidden_size,
+ eps=config.rms_norm_eps,
+ )
+ self.conv_dilation = config.ngram_size
+ self.short_conv_state_len = (
+ config.ple_conv_kernel_size - 1
+ ) * self.conv_dilation
+ self.conv1d = nn.Conv1d(
+ hc_hidden_size,
+ hc_hidden_size,
+ kernel_size=config.ple_conv_kernel_size,
+ dilation=self.conv_dilation,
+ groups=hc_hidden_size,
+ bias=False,
+ )
+
+ def _short_conv(self, x: mx.array, cache: Optional[ArraysCache]):
+ batch = x.shape[0]
+ if cache is not None and cache[2] is not None:
+ state = cache[2]
+ else:
+ state = mx.zeros(
+ (batch, self.short_conv_state_len, x.shape[-1]), dtype=x.dtype
+ )
+ conv_input = mx.concatenate([state, x], axis=1)
+ if cache is not None:
+ cache[2] = mx.contiguous(conv_input[:, -self.short_conv_state_len :])
+ return nn.silu(self.conv1d(conv_input)), state
+
+ def __call__(
+ self,
+ hidden_states: mx.array,
+ input_ids: mx.array,
+ cache: Optional[ArraysCache],
+ mask: Optional[mx.array],
+ target_verify: bool = False,
+ ):
+ capture_speculative_state = target_verify and input_ids.shape[1] > 1
+ if cache is not None:
+ cache._qwen4_exp_ple_speculative_state = None
+ history = None
+ if capture_speculative_state and cache is not None:
+ history = self.ple_embedding._previous_context(
+ input_ids.astype(mx.int64), cache
+ )
+ embeddings = self.ple_embedding(input_ids, cache)
+ keys = self.norm_key(
+ _target_verify_linear(self.key_proj, embeddings, target_verify)
+ ).reshape(*hidden_states.shape[:-1], self.hc_count, self.hidden_size)
+ values = _target_verify_linear(self.value_proj, embeddings, target_verify)
+ queries = self.norm_query(hidden_states).reshape(
+ *hidden_states.shape[:-1], self.hc_count, self.hidden_size
+ )
+ gate = mx.sum(keys * queries, axis=-1, keepdims=True) / math.sqrt(
+ self.hidden_size
+ )
+ gate = mx.sign(gate) * mx.sqrt(mx.maximum(mx.abs(gate), 1e-6))
+ gated_values = mx.sigmoid(gate) * values[..., None, :]
+ gated_values = gated_values.reshape(*hidden_states.shape)
+ normed = self.norm_conv(gated_values)
+ if mask is not None and isinstance(mask, mx.array) and mask.ndim == 2:
+ gated_values = mx.where(mask[..., None], gated_values, 0)
+ normed = mx.where(mask[..., None], normed, 0)
+ conv_output, conv_state = self._short_conv(normed, cache)
+ if history is not None and cache is not None:
+ cache._qwen4_exp_ple_speculative_state = _PLESpeculativeState(
+ history=history,
+ input_ids=input_ids.astype(mx.int64),
+ conv_state=conv_state,
+ conv_inputs=normed,
+ )
+ return gated_values + conv_output
+
+
+class Qwen4ExpDecoderLayer(nn.Module):
+ def __init__(self, config: TextConfig, layer_idx: int):
+ super().__init__()
+ self.is_linear = config.layer_types[layer_idx] == "linear_attention"
+ if self.is_linear:
+ self.linear_attn = Qwen4ExpGatedDeltaNet(config)
+ else:
+ self.self_attn = Qwen4ExpAttention(config)
+ self.mlp = Qwen3_5MoeSparseMoeBlock(config)
+ ple_index = (
+ config.ple_layer_ids.index(layer_idx + 1)
+ if layer_idx + 1 in config.ple_layer_ids
+ else None
+ )
+ if ple_index is not None:
+ self.ple = Qwen4ExpPLELayer(config, layer_idx, ple_index)
+ self.attn_hyper_connection = Qwen4ExpGatedResidual(config)
+ self.mlp_hyper_connection = Qwen4ExpGatedResidual(config)
+
+ def __call__(
+ self,
+ hidden_states: mx.array,
+ input_ids: mx.array,
+ mask: Optional[mx.array],
+ cache: Optional[Any],
+ position_ids: Optional[mx.array],
+ gdn_sink=None,
+ target_verify: bool = False,
+ ):
+ if "ple" in self:
+ hidden_states = hidden_states + self.ple(
+ hidden_states,
+ input_ids,
+ cache,
+ mask,
+ target_verify=target_verify,
+ )
+
+ mixed, hyper_input, injection_weights = self.attn_hyper_connection(
+ hidden_states,
+ target_verify=target_verify,
+ )
+ if self.is_linear:
+ branch = self.linear_attn(
+ mixed,
+ mask=mask,
+ cache=cache,
+ gdn_sink=gdn_sink,
+ target_verify=target_verify,
+ )
+ else:
+ branch = self.self_attn(
+ mixed,
+ mask=mask,
+ cache=cache,
+ position_ids=position_ids,
+ target_verify=target_verify,
+ )
+ injection = branch[..., None, :] * injection_weights[..., None]
+ hidden_states = hyper_input + injection.reshape(*hyper_input.shape)
+
+ mixed, hyper_input, injection_weights = self.mlp_hyper_connection(
+ hidden_states,
+ target_verify=target_verify,
+ )
+ branch = self.mlp(mixed, target_verify=target_verify)
+ injection = branch[..., None, :] * injection_weights[..., None]
+ return hyper_input + injection.reshape(*hyper_input.shape)
+
+
+class Qwen4ExpModel(nn.Module):
+ def __init__(self, config: TextConfig):
+ super().__init__()
+ self.args = config
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
+ self.layers = [
+ Qwen4ExpDecoderLayer(config, layer_idx)
+ for layer_idx in range(config.num_hidden_layers)
+ ]
+ self.hyper_connection_mixer = Qwen4ExpGatedResidual(config, use_combine=False)
+ self.ssm_idx = next(
+ (i for i, layer in enumerate(self.layers) if layer.is_linear), 0
+ )
+ self.fa_idx = next(
+ (i for i, layer in enumerate(self.layers) if not layer.is_linear), 0
+ )
+
+ def __call__(
+ self,
+ inputs: mx.array,
+ inputs_embeds: Optional[mx.array] = None,
+ mask: Optional[mx.array] = None,
+ cache=None,
+ position_ids: Optional[mx.array] = None,
+ capture_layer_ids=None,
+ hidden_sink=None,
+ gdn_sink=None,
+ **kwargs,
+ ):
+ del kwargs
+ hidden_states = (
+ self.embed_tokens(inputs) if inputs_embeds is None else inputs_embeds
+ )
+ hidden_states = mx.tile(hidden_states, (1, 1, self.args.hc_count))
+ if cache is None:
+ cache = [None] * len(self.layers)
+
+ fa_mask = _create_qwen3_5_attention_mask(hidden_states, cache[self.fa_idx])
+ ssm_mask = _create_qwen3_5_ssm_mask(hidden_states, cache[self.ssm_idx])
+ if mask is not None and isinstance(mask, mx.array) and mask.ndim == 2:
+ ssm_mask = mask
+
+ capture = set(capture_layer_ids or [])
+ for index, (layer, layer_cache) in enumerate(zip(self.layers, cache)):
+ layer_mask = ssm_mask if layer.is_linear else fa_mask
+ hidden_states = layer(
+ hidden_states,
+ inputs,
+ mask=layer_mask,
+ cache=layer_cache,
+ position_ids=position_ids,
+ gdn_sink=gdn_sink,
+ target_verify=gdn_sink is not None,
+ )
+ if (
+ _EAGER_DISPATCH
+ and hidden_states.shape[0] * hidden_states.shape[1]
+ <= _EAGER_DISPATCH_MAX_ROWS
+ ):
+ mx.async_eval(hidden_states)
+ if hidden_sink is not None and index in capture:
+ hidden_sink.append(
+ self.hyper_connection_mixer(
+ hidden_states,
+ target_verify=gdn_sink is not None,
+ )
+ )
+
+ if inputs_embeds is None and gdn_sink is None:
+ host_ref = getattr(self, "_omlx_mtp_prime_host", None)
+ host = host_ref() if host_ref is not None else None
+ if host is not None:
+ from omlx.patches.mlx_lm_mtp import prompt_priming
+
+ if prompt_priming.capture_eligible(host, cache):
+ prompt_priming.maybe_capture(
+ host,
+ inputs,
+ hidden_states,
+ cache,
+ )
+
+ if hidden_sink is not None and capture_layer_ids == []:
+ # Lightning MTP consumes all residual streams before the final
+ # mixer. Ordinary layer captures retain their mixed representation.
+ hidden_sink.append(hidden_states)
+
+ return self.hyper_connection_mixer(
+ hidden_states,
+ target_verify=gdn_sink is not None,
+ )
+
+
+class Qwen4ExpMTPModule(nn.Module):
+ """Embedded one-layer draft head for Qwen4 Lightning MTP."""
+
+ def __init__(self, args: TextConfig):
+ super().__init__()
+ self.hidden_size = args.hidden_size
+ self.hc_count = args.hc_count
+ hc_hidden_size = self.hc_count * self.hidden_size
+ self.pre_fc_norm_embedding = Qwen4ExpRMSNorm(
+ self.hidden_size,
+ eps=args.rms_norm_eps,
+ )
+ self.pre_fc_norm_hidden = Qwen4ExpRMSNorm(
+ hc_hidden_size,
+ eps=args.rms_norm_eps,
+ )
+ self.fc_embedding = nn.Linear(
+ self.hidden_size,
+ self.hidden_size,
+ bias=False,
+ )
+ self.fc_hidden = nn.Linear(
+ self.hidden_size,
+ self.hidden_size,
+ bias=False,
+ )
+
+ layer_config = replace(
+ args,
+ num_hidden_layers=1,
+ layer_types=["qwen_sparse_attention"],
+ full_attention_interval=1,
+ ple_layer_ids=[],
+ )
+ self.layers = [Qwen4ExpDecoderLayer(layer_config, layer_idx=0)]
+ self.hyper_connection_mixer = Qwen4ExpGatedResidual(
+ layer_config,
+ use_combine=False,
+ )
+
+ def fuse_inputs(
+ self,
+ token_embeddings: mx.array,
+ hidden_states: mx.array,
+ ) -> mx.array:
+ expected_width = self.hc_count * self.hidden_size
+ if hidden_states.ndim == 4:
+ hidden_states = hidden_states.reshape(
+ *hidden_states.shape[:-2],
+ expected_width,
+ )
+ if hidden_states.ndim != 3 or hidden_states.shape[-1] != expected_width:
+ raise ValueError(
+ "Qwen4 Lightning MTP expects hidden shape "
+ "[batch, tokens, hc_count * hidden_size]."
+ )
+
+ projected_embedding = self.fc_embedding(
+ self.pre_fc_norm_embedding(token_embeddings)
+ )
+ hidden_streams = self.pre_fc_norm_hidden(hidden_states).reshape(
+ *hidden_states.shape[:-1],
+ self.hc_count,
+ self.hidden_size,
+ )
+ projected_hidden = self.fc_hidden(hidden_streams)
+ return (projected_embedding[..., None, :] + projected_hidden).reshape(
+ hidden_states.shape
+ )
+
+ def __call__(
+ self,
+ hidden_states: mx.array,
+ next_token_ids: mx.array,
+ embed_tokens,
+ cache=None,
+ ) -> tuple[mx.array, mx.array]:
+ hidden_states = self.fuse_inputs(
+ embed_tokens(next_token_ids),
+ hidden_states,
+ )
+ if cache is None:
+ cache = [None] * len(self.layers)
+ mask = _create_qwen3_5_attention_mask(
+ hidden_states,
+ cache[0] if cache else None,
+ )
+ for layer, layer_cache in zip(self.layers, cache):
+ hidden_states = layer(
+ hidden_states,
+ next_token_ids,
+ mask=mask,
+ cache=layer_cache,
+ position_ids=None,
+ )
+ return self.hyper_connection_mixer(hidden_states), hidden_states
+
+
+class LanguageModel(Qwen3_5LanguageModel):
+ def __init__(self, args: TextConfig, config: ModelConfig = None):
+ nn.Module.__init__(self)
+ self.args = args
+ self.config = config
+ self.model_type = args.model_type
+ self.model = Qwen4ExpModel(args)
+ self.model._omlx_mtp_prime_host = weakref.ref(self)
+ self._position_ids = None
+ self._rope_deltas = None
+ if not args.tie_word_embeddings:
+ self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False)
+
+ def bind_mtp_owner(self, owner) -> None:
+ """Reference a root-level Lightning MTP head without double registration."""
+ self._omlx_qwen4_mtp_owner = weakref.ref(owner)
+ self._enable_mtp_decode_markers()
+
+ def _enable_mtp_decode_markers(self) -> None:
+ from omlx.patches.mlx_lm_mtp import get_mtp_depth
+
+ self._omlx_mtp_decode_enabled = True
+ self._omlx_mtp_chain = True
+ self._omlx_mtp_depth = get_mtp_depth()
+ self._omlx_mtp_head_prenorm = True
+
+ def get_mtp_module(self):
+ module = getattr(self, "mtp", None)
+ if module is not None:
+ return module
+ owner_ref = getattr(self, "_omlx_qwen4_mtp_owner", None)
+ owner = owner_ref() if owner_ref is not None else None
+ return getattr(owner, "mtp", None) if owner is not None else None
+
+ def __call__(self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs):
+ return_hidden = bool(kwargs.get("return_hidden", False))
+ mtp_capture = return_hidden and kwargs.get("capture_layer_ids") is None
+ if mtp_capture:
+ kwargs["capture_layer_ids"] = []
+ output = super().__call__(inputs, inputs_embeds, mask, cache, **kwargs)
+ if mtp_capture and output.hidden_states:
+ output.hidden_states = [output.hidden_states[0]]
+ return output
+
+ def mtp_forward(
+ self,
+ hidden_states,
+ next_token_ids,
+ mtp_cache,
+ return_hidden: bool = False,
+ logits_keep: int = 0,
+ ):
+ mtp = self.get_mtp_module()
+ if mtp is None:
+ raise RuntimeError(
+ "Qwen4 Lightning MTP forward called without an attached head."
+ )
+ mtp_output, hc_hidden = mtp(
+ hidden_states,
+ next_token_ids,
+ self.model.embed_tokens,
+ mtp_cache,
+ )
+ logits_source = mtp_output
+ if logits_keep and logits_source.shape[1] > logits_keep:
+ logits_source = logits_source[:, -logits_keep:, :]
+ if self.args.tie_word_embeddings:
+ logits = self.model.embed_tokens.as_linear(logits_source)
+ else:
+ logits = self.lm_head(logits_source)
+ if return_hidden:
+ return logits, hc_hidden
+ return logits
+
+ def make_mtp_cache(self):
+ mtp = self.get_mtp_module()
+ return [QSAKVCache() for _ in mtp.layers] if mtp is not None else []
+
+ def make_cache(self):
+ caches = []
+ for layer in self.layers:
+ if layer.is_linear:
+ caches.append(ArraysCache(size=4 if "ple" in layer else 2))
+ else:
+ caches.append(QSAKVCache())
+ return caches
+
+ @staticmethod
+ def _normalize_accepted_counts(accepted):
+ if isinstance(accepted, int):
+ return [accepted]
+ if isinstance(accepted, mx.array):
+ return [int(value) for value in accepted.reshape(-1).tolist()]
+ return [int(value) for value in accepted]
+
+ @staticmethod
+ def _discard_ple_snapshots(caches):
+ for cache in caches:
+ if getattr(cache, "_qwen4_exp_ple_speculative_state", None) is not None:
+ cache._qwen4_exp_ple_speculative_state = None
+
+ @staticmethod
+ def _validate_ple_snapshot(snapshot, accepted_values):
+ batch, window = snapshot.input_ids.shape
+ if len(accepted_values) not in (1, batch):
+ raise ValueError(
+ "PLE speculative rollback accepted count does not match batch size"
+ )
+ if any(value < 0 or value >= window for value in accepted_values):
+ raise ValueError(
+ "PLE speculative rollback accepted count is outside the verify window"
+ )
+
+ @staticmethod
+ def _restore_ple_state(cache, snapshot, accepted_values):
+ batch = snapshot.input_ids.shape[0]
+ values = accepted_values * batch if len(accepted_values) == 1 else accepted_values
+ accepted_array = mx.array(values, dtype=mx.int32)
+ retained = accepted_array + 1
+
+ history_len = snapshot.history.shape[1]
+ history = mx.concatenate([snapshot.history, snapshot.input_ids], axis=1)
+ history_positions = retained[:, None] + mx.arange(
+ history_len, dtype=mx.int32
+ )[None, :]
+ cache[3] = mx.contiguous(
+ mx.take_along_axis(history, history_positions, axis=1)
+ )
+
+ state_len = snapshot.conv_state.shape[1]
+ if state_len:
+ conv_input = mx.concatenate(
+ [snapshot.conv_state, snapshot.conv_inputs], axis=1
+ )
+ conv_positions = retained[:, None] + mx.arange(
+ state_len, dtype=mx.int32
+ )[None, :]
+ conv_positions = mx.broadcast_to(
+ conv_positions[..., None],
+ (batch, state_len, snapshot.conv_state.shape[-1]),
+ )
+ cache[2] = mx.contiguous(
+ mx.take_along_axis(conv_input, conv_positions, axis=1)
+ )
+
+ def rollback_speculative_cache(self, caches, gdn_states, accepted, block_size):
+ """Restore PLE state to the accepted prefix after inherited rollback."""
+ accepted_values = self._normalize_accepted_counts(accepted)
+
+ pending = []
+ try:
+ for cache in caches:
+ snapshot = getattr(cache, "_qwen4_exp_ple_speculative_state", None)
+ if snapshot is None:
+ continue
+ self._validate_ple_snapshot(snapshot, accepted_values)
+ pending.append((cache, snapshot))
+ result = super().rollback_speculative_cache(
+ caches, gdn_states, accepted, block_size
+ )
+ for cache, snapshot in pending:
+ self._restore_ple_state(cache, snapshot, accepted_values)
+ return result
+ finally:
+ self._discard_ple_snapshots(caches)
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py
new file mode 100644
index 0000000000..399f7b5c0f
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py
@@ -0,0 +1,690 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Exact gathered QSA for contiguous batch-one text prompts.
+
+The native path reads selected four-token blocks directly from K/V. The MLX
+fallback gathers the selected rows and causal tail. Batched, padded,
+multimodal, and target-verify requests use mlx-vlm's general implementation.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable
+
+import mlx.core as mx
+
+IndexKeyNorm = Callable[[mx.array], mx.array]
+IndexRoPE = Callable[[mx.array, mx.array], mx.array]
+
+
+_NATIVE_QSA_SCORE_DISABLED = False
+_NATIVE_QSA_SCORE_PROVEN = False
+_NATIVE_QSA_TOPK_DISABLED = False
+_NATIVE_QSA_TOPK_PROVEN = False
+_NATIVE_QSA_MAIN_DISABLED = False
+_NATIVE_QSA_MAIN_PROVEN = False
+
+
+def contiguous_causal_query_chunk(key_tokens: int) -> int:
+ """Keep long-context score sheets bounded without tiny launch overhead."""
+
+ if key_tokens <= 4096:
+ return 32
+ if key_tokens <= 16384:
+ return 64
+ return 128
+
+
+def _batch_gather_tokens(values: mx.array, indices: mx.array) -> mx.array:
+ """Gather token rows independently for every batch without a host read."""
+
+ batch, tokens = values.shape[:2]
+ trailing = values.shape[2:]
+ offset_shape = (batch,) + (1,) * (indices.ndim - 1)
+ offsets = mx.arange(batch, dtype=mx.int32).reshape(offset_shape) * tokens
+ flat_indices = (indices.astype(mx.int32) + offsets).reshape(-1)
+ flat_values = values.reshape(batch * tokens, *trailing)
+ return flat_values[flat_indices].reshape(*indices.shape, *trailing)
+
+
+def _portable_indexer_scores(
+ queries: mx.array,
+ pooled_keys: mx.array,
+ head_dim: int,
+) -> mx.array:
+ """Current float32 MLX QSA score reference."""
+
+ batch, query_tokens, query_heads, _ = queries.shape
+ # Flatten the query-token and index-head axes so MLX emits one FP32 GEMM
+ # for the chunk instead of a broadcasted batch of tiny matmuls. Each
+ # output dot product and the following head reduction are unchanged.
+ scores = (
+ queries.astype(mx.float32).reshape(
+ batch, query_tokens * query_heads, head_dim
+ )
+ @ pooled_keys.astype(mx.float32).swapaxes(-1, -2)
+ ).reshape(batch, query_tokens, query_heads, pooled_keys.shape[1])
+ return mx.sum(mx.maximum(scores, 0), axis=-2) / math.sqrt(head_dim)
+
+
+def pool_completed_index_keys(
+ index_keys: mx.array,
+ index_position_ids: mx.array,
+ *,
+ compress_ratio: int,
+ index_key_norm: IndexKeyNorm,
+ apply_index_rope: IndexRoPE,
+ start_block: int = 0,
+ stop_block: int | None = None,
+) -> mx.array:
+ """Pool, normalize, and rotate a contiguous range of complete QSA blocks."""
+
+ if index_keys.ndim != 3:
+ raise ValueError("QSA raw index keys must have shape [B, S, D]")
+ if compress_ratio <= 0:
+ raise ValueError("QSA compression ratio must be positive")
+ complete_blocks = index_keys.shape[1] // compress_ratio
+ if stop_block is None:
+ stop_block = complete_blocks
+ if not 0 <= start_block <= stop_block <= complete_blocks:
+ raise ValueError(
+ "QSA pooled block range must lie within the complete raw-key prefix"
+ )
+ if index_position_ids.ndim not in {2, 3} or (
+ index_position_ids.shape[-1] != index_keys.shape[1]
+ ):
+ raise ValueError("QSA index positions do not match raw index keys")
+
+ block_count = stop_block - start_block
+ raw_start = start_block * compress_ratio
+ raw_stop = stop_block * compress_ratio
+ pooled = index_keys[:, raw_start:raw_stop].reshape(
+ index_keys.shape[0],
+ block_count,
+ compress_ratio,
+ index_keys.shape[-1],
+ )
+ pooled = mx.mean(pooled.astype(mx.float32), axis=-2).astype(index_keys.dtype)
+ pooled = index_key_norm(pooled)
+ block_starts = mx.arange(
+ raw_start,
+ raw_stop,
+ compress_ratio,
+ dtype=mx.int32,
+ )
+ pooled_positions = index_position_ids[..., block_starts]
+ return apply_index_rope(pooled[:, None], pooled_positions)[:, 0]
+
+
+def _native_indexer_scores(
+ queries: mx.array,
+ pooled_keys: mx.array,
+ *,
+ head_dim: int,
+ compress_ratio: int,
+ mask_q_offset: int,
+) -> mx.array | None:
+ """Use the narrow native M3 score ABI or fail closed to the MLX path."""
+
+ global _NATIVE_QSA_SCORE_DISABLED, _NATIVE_QSA_SCORE_PROVEN
+ if _NATIVE_QSA_SCORE_DISABLED:
+ return None
+ if (
+ queries.ndim != 4
+ or queries.shape[0] != 1
+ or queries.shape[-2:] != (4, 128)
+ or pooled_keys.ndim != 3
+ or pooled_keys.shape[0] != 1
+ or pooled_keys.shape[-1] != 128
+ or queries.dtype != pooled_keys.dtype
+ or queries.dtype not in {mx.float16, mx.bfloat16}
+ or head_dim != 128
+ or compress_ratio != 4
+ or mask_q_offset < 0
+ ):
+ return None
+
+ try:
+ from omlx.custom_kernels.glm_moe_dsa import fast
+
+ if not fast.is_native_available() or not fast.has_symbol(
+ "qwen4_qsa_indexer_scores"
+ ):
+ _NATIVE_QSA_SCORE_DISABLED = True
+ return None
+ # The caller's [B,M,H,D] view transposes back to the GEMM-friendly
+ # [B,H,M,D] ABI. The native wrapper only copies when the resulting
+ # view is not row-contiguous (for example an offset query chunk).
+ scores = fast.qwen4_qsa_indexer_scores(
+ queries.transpose(0, 2, 1, 3),
+ pooled_keys[:, None],
+ mask_ratio=compress_ratio,
+ mask_q_offset=mask_q_offset,
+ )
+ if not _NATIVE_QSA_SCORE_PROVEN:
+ # MLX primitives are lazy, so a missing Metal pipeline would not
+ # otherwise surface until the enclosing attention graph is
+ # evaluated and can no longer fall back. Pay one process-wide
+ # synchronization to prove the extension/pipeline pair.
+ mx.eval(scores)
+ _NATIVE_QSA_SCORE_PROVEN = True
+ return scores
+ except Exception:
+ # A stale binary or rejected ABI should cost one attempt per process.
+ # Shape misses were excluded above and remain eligible on later calls.
+ _NATIVE_QSA_SCORE_DISABLED = True
+ return None
+
+
+def _native_topk_indices(scores: mx.array, topk: int) -> mx.array | None:
+ """Use Qwen's exact FP32 top-k ABI or fail closed to argpartition."""
+
+ global _NATIVE_QSA_TOPK_DISABLED, _NATIVE_QSA_TOPK_PROVEN
+ if _NATIVE_QSA_TOPK_DISABLED:
+ return None
+ if (
+ scores.ndim != 3
+ or scores.shape[0] != 1
+ or scores.shape[1] < 1
+ or scores.shape[2] < topk
+ or scores.dtype != mx.float32
+ or topk != 512
+ ):
+ return None
+ try:
+ from omlx.custom_kernels.glm_moe_dsa import fast
+
+ if not fast.is_native_available() or not fast.has_symbol(
+ "qwen4_qsa_topk_indices"
+ ):
+ _NATIVE_QSA_TOPK_DISABLED = True
+ return None
+ indices = fast.qwen4_qsa_topk_indices(scores, topk=topk).astype(mx.int32)
+ if not _NATIVE_QSA_TOPK_PROVEN:
+ mx.eval(indices)
+ _NATIVE_QSA_TOPK_PROVEN = True
+ return indices
+ except Exception:
+ _NATIVE_QSA_TOPK_DISABLED = True
+ return None
+
+
+def _native_sparse_gqa_attention(
+ queries: mx.array,
+ keys: mx.array,
+ values: mx.array,
+ selected_blocks: mx.array,
+ *,
+ q_offset: int,
+) -> mx.array | None:
+ """Consume Qwen's selected rows directly in the exact native GQA kernel."""
+
+ global _NATIVE_QSA_MAIN_DISABLED, _NATIVE_QSA_MAIN_PROVEN
+ if _NATIVE_QSA_MAIN_DISABLED:
+ return None
+ if (
+ queries.ndim != 4
+ or queries.shape[0] != 1
+ or queries.shape[1] != 24
+ or queries.shape[-1] != 256
+ or keys.ndim != 4
+ or values.shape != keys.shape
+ or keys.shape[0] != 1
+ or keys.shape[1] != 2
+ or keys.shape[-1] != 256
+ or queries.dtype != keys.dtype
+ or queries.dtype != values.dtype
+ or queries.dtype not in {mx.float16, mx.bfloat16}
+ or selected_blocks.ndim != 3
+ or selected_blocks.shape != (1, queries.shape[2], 512)
+ or q_offset < 0
+ or q_offset + queries.shape[2] > keys.shape[2]
+ ):
+ return None
+ try:
+ from omlx.custom_kernels.glm_moe_dsa import fast
+
+ if not fast.is_native_available() or not fast.has_symbol(
+ "qwen4_qsa_sparse_gqa_attention"
+ ):
+ _NATIVE_QSA_MAIN_DISABLED = True
+ return None
+ native_blocks = mx.contiguous(selected_blocks.astype(mx.uint32)[:, None])
+ output = fast.qwen4_qsa_sparse_gqa_attention(
+ queries,
+ keys,
+ values,
+ native_blocks,
+ queries.shape[-1] ** -0.5,
+ q_offset,
+ key_tile=64,
+ dimension_tile=64,
+ )
+ if not _NATIVE_QSA_MAIN_PROVEN:
+ # Prove the rebuilt extension and Metal pipeline before the lazy
+ # graph advances cache state past a point where fallback is safe.
+ mx.eval(output)
+ _NATIVE_QSA_MAIN_PROVEN = True
+ return output.transpose(0, 2, 1, 3)
+ except Exception:
+ _NATIVE_QSA_MAIN_DISABLED = True
+ return None
+
+
+def _decode_qsa_sdpa(
+ queries: mx.array,
+ keys: mx.array,
+ values: mx.array,
+ scale: float,
+) -> mx.array:
+ """Run exact unmasked singleton SDPA through the narrow native seam.
+
+ The gathered decode caller has already applied QSA selection, so there is
+ no causal or sparse mask left to interpret. Only the decode_fast ABI's
+ explicitly supported shape/dtype contract may use the native primitive;
+ missing/stale extensions and every other shape fail closed to MLX SDPA.
+ Inputs are made contiguous by the caller, avoiding a lazy layout failure
+ after the model caches have advanced.
+ """
+
+ try:
+ from omlx.custom_kernels.decode_fast import fast
+
+ extension = getattr(fast, "_ext", None)
+ supported = getattr(extension, "sdpa_decode_supported", None)
+ if (
+ bool(getattr(fast, "NATIVE_AVAILABLE", False))
+ and supported is not None
+ and bool(supported(queries, keys, values))
+ ):
+ return fast.sdpa_decode(
+ queries,
+ keys,
+ values,
+ scale,
+ causal=False,
+ )
+ except Exception:
+ # Capability probing is eager and happens before a native primitive is
+ # added to the lazy graph, so this fallback cannot leave partial work.
+ pass
+
+ return mx.fast.scaled_dot_product_attention(
+ queries,
+ keys,
+ values,
+ scale=scale,
+ )
+
+
+def contiguous_causal_gathered_qsa_decode(
+ queries: mx.array,
+ keys: mx.array,
+ values: mx.array,
+ index_queries: mx.array,
+ pooled_index_keys: mx.array,
+ *,
+ num_query_heads: int,
+ num_key_value_heads: int,
+ head_dim: int,
+ indexer_head_dim: int,
+ compress_ratio: int,
+ token_budget: int,
+) -> mx.array:
+ """Run exact batch-one QSA decode over only the selected K/V rows.
+
+ This is the singleton counterpart to :func:`contiguous_causal_gathered_qsa`.
+ The query is the final visible token, so every completed compressed block
+ is causal. QSA chooses ``token_budget / compress_ratio`` complete blocks;
+ their token rows are gathered in chronological order and the zero-to-three
+ incomplete tail rows are appended. Main attention therefore remains
+ bounded by ``token_budget + compress_ratio - 1`` instead of scanning a
+ dense full-length mask.
+ """
+
+ if queries.ndim != 4 or queries.shape[:3] != (1, num_query_heads, 1):
+ raise ValueError("gathered QSA decode requires [1, H, 1, D] queries")
+ if queries.shape[-1] != head_dim:
+ raise ValueError("QSA decode queries do not match the configured head dim")
+ if keys.ndim != 4 or values.shape != keys.shape:
+ raise ValueError("QSA decode K/V must be matching rank-four arrays")
+ if keys.shape[0] != 1 or keys.shape[1] != num_key_value_heads:
+ raise ValueError("QSA decode K/V do not match the configured head count")
+ if keys.shape[-1] != head_dim or keys.dtype != queries.dtype:
+ raise ValueError("QSA decode K/V dtype or head dim does not match queries")
+ if values.dtype != queries.dtype:
+ raise ValueError("QSA decode values must match the query dtype")
+ if (
+ index_queries.ndim != 4
+ or index_queries.shape[0] != 1
+ or index_queries.shape[1] != 1
+ or index_queries.shape[-1] != indexer_head_dim
+ ):
+ raise ValueError("QSA decode index queries must have shape [1, 1, H, D]")
+ if compress_ratio <= 0 or token_budget <= 0 or token_budget % compress_ratio:
+ raise ValueError("QSA decode token budget must contain complete blocks")
+ if num_query_heads % num_key_value_heads:
+ raise ValueError("QSA decode query heads must divide over K/V heads")
+
+ key_tokens = int(keys.shape[2])
+ max_blocks = key_tokens // compress_ratio
+ block_budget = token_budget // compress_ratio
+ if max_blocks <= block_budget:
+ raise ValueError("gathered QSA decode requires a sparse block crossover")
+ if pooled_index_keys.shape != (1, max_blocks, indexer_head_dim):
+ raise ValueError("QSA decode pooled index-key cache has the wrong shape")
+
+ block_scores = _native_indexer_scores(
+ index_queries,
+ pooled_index_keys,
+ head_dim=indexer_head_dim,
+ compress_ratio=compress_ratio,
+ mask_q_offset=key_tokens - 1,
+ )
+ if block_scores is None:
+ block_scores = _portable_indexer_scores(
+ index_queries,
+ pooled_index_keys,
+ indexer_head_dim,
+ )
+
+ selected_blocks = _native_topk_indices(block_scores, block_budget)
+ if selected_blocks is None:
+ selected_blocks = mx.argpartition(
+ block_scores,
+ kth=-block_budget,
+ axis=-1,
+ )[..., -block_budget:].astype(mx.int32)
+ # Argpartition/native radix order is not chronological. Sorting the
+ # selected set preserves the official key order for deterministic SDPA.
+ selected_blocks = mx.sort(selected_blocks, axis=-1)
+ selected_tokens = (
+ selected_blocks[..., None] * compress_ratio
+ + mx.arange(compress_ratio, dtype=mx.int32)
+ ).reshape(1, block_budget * compress_ratio)
+
+ complete_key_len = max_blocks * compress_ratio
+ if complete_key_len < key_tokens:
+ tail = mx.arange(complete_key_len, key_tokens, dtype=mx.int32)[None]
+ selected_tokens = mx.concatenate((selected_tokens, tail), axis=-1)
+
+ key_rows = keys.transpose(0, 2, 1, 3)
+ value_rows = values.transpose(0, 2, 1, 3)
+ selected_keys = mx.contiguous(
+ _batch_gather_tokens(key_rows, selected_tokens).transpose(0, 2, 1, 3)
+ )
+ selected_values = mx.contiguous(
+ _batch_gather_tokens(value_rows, selected_tokens).transpose(0, 2, 1, 3)
+ )
+ output = _decode_qsa_sdpa(
+ queries,
+ selected_keys,
+ selected_values,
+ head_dim**-0.5,
+ )
+ return output.transpose(0, 2, 1, 3)
+
+
+def contiguous_causal_gathered_qsa(
+ queries: mx.array,
+ keys: mx.array,
+ values: mx.array,
+ index_queries: mx.array,
+ index_keys: mx.array,
+ index_position_ids: mx.array,
+ *,
+ num_query_heads: int,
+ num_key_value_heads: int,
+ head_dim: int,
+ indexer_head_dim: int,
+ compress_ratio: int,
+ token_budget: int,
+ index_key_norm: IndexKeyNorm,
+ apply_index_rope: IndexRoPE,
+ pooled_index_keys: mx.array | None = None,
+ query_chunk: int | None = None,
+) -> mx.array:
+ """Run exact QSA over gathered K/V for one contiguous causal prompt.
+
+ ``queries`` and ``keys`` must already carry their main-attention RoPE.
+ ``index_queries`` must likewise be normalized and RoPE-rotated. Raw
+ indexer keys remain unrotated because Qwen pools each complete micro-block
+ before applying its checkpoint k-norm and the block-start RoPE.
+ """
+
+ if queries.ndim != 4 or queries.shape[0] != 1 or queries.shape[2] <= 1:
+ raise ValueError(
+ "gathered QSA requires rank-four batch-one multi-token queries"
+ )
+ batch, actual_query_heads, query_tokens, actual_head_dim = queries.shape
+ if actual_query_heads != num_query_heads or actual_head_dim != head_dim:
+ raise ValueError("QSA queries do not match the configured geometry")
+ if keys.ndim != 4 or values.shape != keys.shape:
+ raise ValueError("QSA keys and values must be matching rank-four arrays")
+ if keys.shape[0] != batch or keys.shape[1:] != (
+ num_key_value_heads,
+ keys.shape[2],
+ head_dim,
+ ):
+ raise ValueError("QSA K/V do not match the configured geometry")
+ key_tokens = keys.shape[2]
+ if query_tokens > key_tokens:
+ raise ValueError("QSA query length cannot exceed cached key length")
+ if index_queries.ndim != 4 or index_queries.shape[:2] != (
+ batch,
+ query_tokens,
+ ):
+ raise ValueError("QSA index queries do not match the current prompt")
+ if index_queries.shape[-1] != indexer_head_dim:
+ raise ValueError("QSA index queries have the wrong head dimension")
+ if index_keys.shape != (batch, key_tokens, indexer_head_dim):
+ raise ValueError("QSA raw index keys do not match cached K/V")
+ if (
+ index_position_ids.ndim not in {2, 3}
+ or index_position_ids.shape[-1] != key_tokens
+ ):
+ raise ValueError("QSA index positions do not match cached K/V")
+ if compress_ratio <= 0 or token_budget <= 0 or token_budget % compress_ratio:
+ raise ValueError("QSA token budget must contain complete micro-blocks")
+ if num_query_heads % num_key_value_heads:
+ raise ValueError("QSA query heads must divide evenly over K/V heads")
+
+ if query_chunk is None:
+ query_chunk = contiguous_causal_query_chunk(key_tokens)
+ # The direct-index main-attention kernel carries no per-query gathered
+ # K/V tensor, so a 256-row score tile stays comfortably bounded and
+ # halves Python/Metal dispatch overhead. Preserve the smaller portable
+ # tiles whenever the exact production ABI is absent.
+ if (
+ queries.shape[1:] == (24, query_tokens, 256)
+ and keys.shape[1] == 2
+ and queries.dtype in {mx.float16, mx.bfloat16}
+ and not _NATIVE_QSA_MAIN_DISABLED
+ ):
+ try:
+ from omlx.custom_kernels.glm_moe_dsa import fast
+
+ if fast.is_native_available() and fast.has_symbol(
+ "qwen4_qsa_sparse_gqa_attention"
+ ):
+ query_chunk = max(query_chunk, 256)
+ except Exception:
+ pass
+ if query_chunk <= 0:
+ raise ValueError("QSA query chunk must be positive")
+
+ ratio = compress_ratio
+ max_blocks = key_tokens // ratio
+ block_budget = token_budget // ratio
+ query_start = key_tokens - query_tokens
+ key_rows = keys.transpose(0, 2, 1, 3)
+ value_rows = values.transpose(0, 2, 1, 3)
+
+ # A contiguous prompt shares the same block bank for every query. The
+ # caller can provide its cache of completed blocks; standalone users still
+ # get the exact one-shot construction.
+ if max_blocks:
+ if pooled_index_keys is None:
+ pooled = pool_completed_index_keys(
+ index_keys,
+ index_position_ids,
+ compress_ratio=ratio,
+ index_key_norm=index_key_norm,
+ apply_index_rope=apply_index_rope,
+ )
+ else:
+ if pooled_index_keys.shape != (batch, max_blocks, indexer_head_dim):
+ raise ValueError("QSA pooled index-key cache has the wrong shape")
+ pooled = pooled_index_keys
+ else:
+ if pooled_index_keys is not None and pooled_index_keys.shape != (
+ batch,
+ 0,
+ indexer_head_dim,
+ ):
+ raise ValueError("QSA pooled index-key cache has the wrong shape")
+ pooled = None
+
+ outputs: list[mx.array] = []
+ groups = num_query_heads // num_key_value_heads
+ for start in range(0, query_tokens, query_chunk):
+ stop = min(start + query_chunk, query_tokens)
+ chunk_tokens = stop - start
+ absolute_queries = query_start + mx.arange(start, stop, dtype=mx.int32)
+ visible_counts = mx.broadcast_to(
+ (absolute_queries + 1)[None], (batch, chunk_tokens)
+ )
+ complete_counts = visible_counts // ratio
+
+ if max_blocks:
+ chunk_index_queries = index_queries[:, start:stop]
+ block_scores = _native_indexer_scores(
+ chunk_index_queries,
+ pooled,
+ head_dim=indexer_head_dim,
+ compress_ratio=ratio,
+ mask_q_offset=query_start + start,
+ )
+ if block_scores is None:
+ block_scores = _portable_indexer_scores(
+ chunk_index_queries,
+ pooled,
+ indexer_head_dim,
+ )
+ valid_blocks = (
+ mx.arange(max_blocks)[None, None, :]
+ < complete_counts[..., None]
+ )
+ block_scores = mx.where(
+ valid_blocks,
+ block_scores,
+ mx.finfo(block_scores.dtype).min,
+ )
+
+ selected_width = min(max_blocks, block_budget)
+ canonical = mx.broadcast_to(
+ mx.arange(selected_width, dtype=mx.int32)[None, None],
+ (batch, chunk_tokens, selected_width),
+ )
+ if max_blocks > block_budget:
+ ranked = _native_topk_indices(block_scores, block_budget)
+ if ranked is None:
+ ranked = mx.argpartition(
+ block_scores,
+ kth=-block_budget,
+ axis=-1,
+ )[..., -block_budget:].astype(mx.int32)
+ selected_block_rows = mx.where(
+ (complete_counts <= block_budget)[..., None],
+ canonical,
+ ranked,
+ )
+ else:
+ selected_block_rows = canonical
+
+ # The top-k set is unordered. Restore checkpoint/dense-mask token
+ # order before either the portable gathered SDPA or the direct
+ # native kernel performs its FP32 online-softmax reduction.
+ selected_block_rows = mx.sort(selected_block_rows, axis=-1)
+
+ selected_count = mx.minimum(complete_counts, block_budget)
+
+ native_output = _native_sparse_gqa_attention(
+ queries[:, :, start:stop],
+ keys,
+ values,
+ selected_block_rows,
+ q_offset=query_start + start,
+ )
+ if native_output is not None:
+ outputs.append(native_output)
+ continue
+
+ selected_indices = (
+ selected_block_rows[..., None] * ratio
+ + mx.arange(ratio, dtype=mx.int32)
+ ).reshape(batch, chunk_tokens, selected_width * ratio)
+ selected_valid = mx.broadcast_to(
+ mx.arange(selected_width)[None, None, :, None]
+ < selected_count[..., None, None],
+ (batch, chunk_tokens, selected_width, ratio),
+ ).reshape(batch, chunk_tokens, selected_width * ratio)
+ else:
+ selected_indices = mx.zeros(
+ (batch, chunk_tokens, 0), dtype=mx.int32
+ )
+ selected_valid = mx.zeros(
+ (batch, chunk_tokens, 0), dtype=mx.bool_
+ )
+
+ # The zero-to-three visible tokens after the final complete block are
+ # always retained by the published QSA contract.
+ tail_width = ratio - 1
+ tail = complete_counts[..., None] * ratio + mx.arange(
+ tail_width, dtype=mx.int32
+ )
+ tail_valid = tail < visible_counts[..., None]
+ selected_indices = mx.concatenate((selected_indices, tail), axis=-1)
+ selected_valid = mx.concatenate((selected_valid, tail_valid), axis=-1)
+
+ safe_selected = mx.where(selected_valid, selected_indices, 0).astype(mx.int32)
+
+ selected_keys = _batch_gather_tokens(key_rows, safe_selected).transpose(
+ 0, 1, 3, 2, 4
+ )
+ selected_values = _batch_gather_tokens(value_rows, safe_selected).transpose(
+ 0, 1, 3, 2, 4
+ )
+
+ chunk_queries = queries[:, :, start:stop].transpose(0, 2, 1, 3)
+ grouped_queries = chunk_queries.reshape(
+ batch,
+ chunk_tokens,
+ num_key_value_heads,
+ groups,
+ head_dim,
+ )
+ scores = (
+ grouped_queries.astype(mx.float32)
+ @ selected_keys.astype(mx.float32).swapaxes(-1, -2)
+ ) / math.sqrt(head_dim)
+ scores = mx.where(
+ selected_valid[:, :, None, None, :],
+ scores,
+ mx.finfo(scores.dtype).min,
+ )
+ probabilities = mx.softmax(scores, axis=-1).astype(chunk_queries.dtype)
+ output = probabilities @ selected_values
+ outputs.append(
+ output.reshape(batch, chunk_tokens, num_query_heads, head_dim)
+ )
+
+ return mx.concatenate(outputs, axis=1)
+
+
+__all__ = [
+ "contiguous_causal_gathered_qsa",
+ "contiguous_causal_gathered_qsa_decode",
+ "contiguous_causal_query_chunk",
+ "pool_completed_index_keys",
+]
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py
new file mode 100644
index 0000000000..2c0bb39b16
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py
@@ -0,0 +1,303 @@
+import logging
+import re
+
+import mlx.core as mx
+import mlx.nn as nn
+
+from omlx.patches.mlx_vlm_mtp.qwen38_fp8 import dequantize_fp8_weights
+
+from ..qwen3_5 import Model as Qwen3_5Model
+from ..qwen3_5.qwen3_5 import sanitize_key
+from .config import ModelConfig
+from .language import (
+ LanguageModel,
+ Qwen4ExpMTPModule,
+ Qwen4ExpRMSNorm,
+ compile_hyper_connections,
+ fuse_hyper_connection_projections,
+ fuse_resident_ple_embeddings,
+ get_mtp_runtime,
+ get_ple_runtime_mode,
+)
+from .vision import VisionModel
+
+logger = logging.getLogger(__name__)
+
+_NGRAM_SHARD_RE = re.compile(r"\.ngram_embedding\.shard_(\d+)(?=\.)")
+_NGRAM_STORAGE_RE = re.compile(
+ r"\.ple\.ple_embedding\.ngram_embedding\."
+ r"(?:shard_\d+|shards\.\d+)\.(?:weight|scales|biases)$"
+)
+_MTP_PREFIXES = (
+ "model.language_model.mtp.",
+ "language_model.mtp.",
+ "model.mtp.",
+ "mtp.",
+)
+_RMSNORM_CENTER_ANCHOR_RE = re.compile(
+ r"^language_model\.model\.layers\.\d+"
+ r"\.attn_hyper_connection\.hc_norm\.weight$"
+)
+_RMSNORM_CENTER_MIN_ANCHORS = 8
+_RMSNORM_ONES_CENTERED_VOTE = 0.9
+_RMSNORM_ONES_CENTERED_MEDIAN_MIN = 0.75
+_RMSNORM_ONES_CENTERED_MEDIAN_MAX = 1.5
+_RMSNORM_ZERO_CENTERED_VOTE = 0.1
+_RMSNORM_ZERO_CENTERED_MEDIAN_MIN = -0.5
+_RMSNORM_ZERO_CENTERED_MEDIAN_MAX = 0.25
+
+
+def _normalize_ones_centered_rmsnorm_weights(model, weights):
+ """Canonicalize legacy direct-gamma Qwen4 RMSNorm checkpoints.
+
+ Qwen4 stores most RMSNorm parameters as a residual around zero and applies
+ ``1 + weight`` at runtime. Some early community MLX conversions instead
+ stored the direct gamma around one. Use the stable per-layer attention
+ hyper-connection norms to identify that checkpoint-wide conversion, then
+ recenter only modules backed by :class:`Qwen4ExpRMSNorm`.
+
+ The MTP head is normalized using the base-model decision. Its trained norm
+ means are not independently centered near zero, so sampling the MTP head
+ alone would be ambiguous.
+ """
+ named_modules = getattr(model, "named_modules", None)
+ if named_modules is None:
+ return
+
+ anchors = [
+ value
+ for key, value in weights.items()
+ if _RMSNORM_CENTER_ANCHOR_RE.fullmatch(key)
+ and isinstance(value, mx.array)
+ and mx.issubdtype(value.dtype, mx.floating)
+ ]
+ if len(anchors) < _RMSNORM_CENTER_MIN_ANCHORS:
+ return
+
+ means = mx.stack([mx.mean(value.astype(mx.float32)) for value in anchors])
+ median = mx.median(means)
+ ones_vote = mx.mean((means > 0.5).astype(mx.float32))
+ mx.eval(median, ones_vote)
+ median_value = float(median.item())
+ ones_vote_value = float(ones_vote.item())
+
+ ones_centered = (
+ ones_vote_value >= _RMSNORM_ONES_CENTERED_VOTE
+ and _RMSNORM_ONES_CENTERED_MEDIAN_MIN
+ <= median_value
+ <= _RMSNORM_ONES_CENTERED_MEDIAN_MAX
+ )
+ zero_centered = (
+ ones_vote_value <= _RMSNORM_ZERO_CENTERED_VOTE
+ and _RMSNORM_ZERO_CENTERED_MEDIAN_MIN
+ <= median_value
+ <= _RMSNORM_ZERO_CENTERED_MEDIAN_MAX
+ )
+ if not ones_centered:
+ if not zero_centered:
+ logger.warning(
+ "Qwen4-Exp RMSNorm checkpoint centering is ambiguous "
+ "(%d anchors, median %.4f, ones-centered vote %.1f%%); "
+ "leaving weights unchanged",
+ len(anchors),
+ median_value,
+ ones_vote_value * 100.0,
+ )
+ return
+
+ target_keys = {
+ f"{path}.weight"
+ for path, module in named_modules()
+ if isinstance(module, Qwen4ExpRMSNorm)
+ }
+ normalized = 0
+ for key in target_keys:
+ value = weights.get(key)
+ if not isinstance(value, mx.array) or not mx.issubdtype(
+ value.dtype, mx.floating
+ ):
+ continue
+ # Keep the residual in FP32. Subtracting in BF16 can lose information
+ # for direct gamma values below 0.5, which occur in the trained MTP head.
+ weights[key] = value.astype(mx.float32) - 1.0
+ normalized += 1
+
+ logger.info(
+ "Canonicalized %d ones-centered Qwen4-Exp RMSNorm tensors "
+ "(%d anchors, median %.4f)",
+ normalized,
+ len(anchors),
+ median_value,
+ )
+
+
+class Model(Qwen3_5Model):
+ def __init__(self, config: ModelConfig):
+ nn.Module.__init__(self)
+ self.config = config
+ self.vision_tower = VisionModel(config.vision_config)
+ self.language_model = LanguageModel(config.text_config, config)
+ if get_mtp_runtime().enabled:
+ self.mtp = Qwen4ExpMTPModule(config.text_config)
+ self.language_model.bind_mtp_owner(self)
+
+ def sanitize(self, weights):
+ if get_ple_runtime_mode() == "mmap" and not getattr(
+ self, "_omlx_preserve_qwen4_ple_for_quantization", False
+ ):
+ for key in [key for key in weights if _NGRAM_STORAGE_RE.search(key)]:
+ weights.pop(key)
+ weights = dequantize_fp8_weights(weights, copy_weights=False)
+ for layer_id in getattr(self.config.text_config, "ple_layer_ids", ()):
+ source_scale_key = (
+ f"model.language_model.layers.{int(layer_id) - 1}.ple."
+ "ple_embedding.ngram_embedding.weight_scale"
+ )
+ runtime_scale_key = (
+ f"language_model.model.layers.{int(layer_id) - 1}.ple."
+ "ple_embedding.ngram_embedding.weight_scale"
+ )
+ # Converted MLX checkpoints already use the runtime prefix. Do not
+ # add the raw-HF default as a second key: sanitize_key() maps both
+ # spellings to runtime_scale_key, and the default would otherwise
+ # overwrite a real shared FP8 PLE scale during normalization.
+ if (
+ source_scale_key not in weights
+ and runtime_scale_key not in weights
+ ):
+ weights[source_scale_key] = mx.ones((1,), dtype=mx.bfloat16)
+ mtp_enabled = get_mtp_runtime().enabled
+
+ normalized = {}
+ for key, value in weights.items():
+ mtp_key = next(
+ (prefix for prefix in _MTP_PREFIXES if key.startswith(prefix)),
+ None,
+ )
+ if mtp_key is not None:
+ if not mtp_enabled:
+ continue
+ key = "mtp." + key[len(mtp_key) :]
+ normalized[key] = value
+ weights = normalized
+
+ if self.config.text_config.tie_word_embeddings:
+ weights.pop("lm_head.weight", None)
+
+ num_experts = int(getattr(self.config.text_config, "num_experts", 0) or 0)
+
+ def stack_experts(prefix):
+ if f"{prefix}.switch_mlp.gate_proj.weight" in weights:
+ return
+
+ gate_up_key = next(
+ (
+ key
+ for key in (
+ f"{prefix}.experts.gate_up_proj",
+ f"{prefix}.experts.gate_up_proj.weight",
+ )
+ if key in weights
+ ),
+ None,
+ )
+ if gate_up_key is not None:
+ gate, up = mx.split(weights.pop(gate_up_key), 2, axis=-2)
+ weights[f"{prefix}.switch_mlp.gate_proj.weight"] = gate
+ weights[f"{prefix}.switch_mlp.up_proj.weight"] = up
+ for down_key in (
+ f"{prefix}.experts.down_proj",
+ f"{prefix}.experts.down_proj.weight",
+ ):
+ if down_key in weights:
+ weights[f"{prefix}.switch_mlp.down_proj.weight"] = weights.pop(
+ down_key
+ )
+ break
+ return
+
+ if f"{prefix}.experts.0.gate_proj.weight" not in weights:
+ return
+ for projection in ("gate_proj", "up_proj", "down_proj"):
+ for suffix in ("weight", "scales", "biases"):
+ first = f"{prefix}.experts.0.{projection}.{suffix}"
+ if first not in weights:
+ continue
+ weights[f"{prefix}.switch_mlp.{projection}.{suffix}"] = mx.stack(
+ [
+ weights.pop(
+ f"{prefix}.experts.{expert}.{projection}.{suffix}"
+ )
+ for expert in range(num_experts)
+ ]
+ )
+
+ for layer_idx in range(self.config.text_config.num_hidden_layers):
+ stack_experts(f"model.language_model.layers.{layer_idx}.mlp")
+
+ if mtp_enabled:
+ mtp_layer_indices = sorted(
+ {
+ int(key.split(".")[2])
+ for key in weights
+ if key.startswith("mtp.layers.")
+ and len(key.split(".")) > 2
+ and key.split(".")[2].isdigit()
+ }
+ )
+ for layer_idx in mtp_layer_indices:
+ stack_experts(f"mtp.layers.{layer_idx}.mlp")
+
+ sanitized = {}
+ for key, value in weights.items():
+ key = sanitize_key(key)
+ key = _NGRAM_SHARD_RE.sub(r".ngram_embedding.shards.\1", key)
+ if "conv1d.weight" in key and value.shape[-1] != 1:
+ value = value.moveaxis(2, 1)
+ sanitized[key] = value
+ _normalize_ones_centered_rmsnorm_weights(self, sanitized)
+ return sanitized
+
+ def load_weights(self, weights, strict=True):
+ result = super().load_weights(weights, strict=strict)
+ mtp_enabled = get_mtp_runtime().enabled
+ hybrid = 0 if mtp_enabled else fuse_hyper_connection_projections(self)
+ fused_ple = fuse_resident_ple_embeddings(self)
+ compiled = compile_hyper_connections(self)
+ if mtp_enabled:
+ logger.info(
+ "Skipped Qwen4-Exp exact hybrid projections while "
+ "Lightning MTP target verification is enabled"
+ )
+ logger.info(
+ "Enabled Qwen4-Exp hyper-connection optimizations: "
+ "%d exact hybrid projection pairs, %d compiled decode paths",
+ hybrid,
+ compiled,
+ )
+ if fused_ple:
+ logger.info(
+ "Fused %d resident Qwen4-Exp PLE table into one packed "
+ "device-side embedding",
+ fused_ple,
+ )
+ return result
+
+ def close(self):
+ """Release external PLE mmap handles during oMLX model unload."""
+ for layer in self.language_model.model.layers:
+ ple = getattr(layer, "ple", None)
+ embedding = getattr(
+ getattr(ple, "ple_embedding", None), "ngram_embedding", None
+ )
+ close = getattr(embedding, "close", None)
+ if close is not None:
+ close()
+
+ @property
+ def quant_predicate(self):
+ return self.language_model.quant_predicate
+
+ @property
+ def cast_predicate(self):
+ return self.language_model.cast_predicate
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/vision.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/vision.py
new file mode 100644
index 0000000000..14d1e9e788
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/vision.py
@@ -0,0 +1,99 @@
+"""Qwen4 vision compatibility bridge for the pinned mlx-vlm revision.
+
+The ``VisionModel.__call__`` implementation below follows mlx-vlm commit
+``1249c7d`` (PR #1982) and is used under mlx-vlm's MIT license:
+
+Copyright © 2025 Prince Canuma
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+"""
+
+import mlx.core as mx
+
+from ..qwen3_vl import VisionModel as Qwen3VLVisionModel
+
+
+class VisionModel(Qwen3VLVisionModel):
+ def __init__(self, config):
+ # The pinned qwen3_vl tower predates the qwen4_exp type aliases; its
+ # graph is otherwise the same published ViT used by Flash Next.
+ original_type = config.model_type
+ config.model_type = "qwen3_5_moe_vision"
+ try:
+ super().__init__(config)
+ finally:
+ config.model_type = original_type
+ self.model_type = original_type
+
+ def __call__(
+ self,
+ hidden_states: mx.array,
+ grid_thw: mx.array,
+ **kwargs,
+ ) -> mx.array:
+ """Run the shared Qwen ViT with MLX-safe temporal repeat counts.
+
+ oMLX currently pins mlx-vlm before upstream #1982. That revision
+ passes a scalar ``mx.array`` as ``mx.repeat(..., repeats=...)``, which
+ newer MLX releases reject. Qwen4-Exp inherits that tower for both
+ images and videos, so keep the upstream computation verbatim while
+ scalarizing only the temporal repeat count. This is the same fix
+ shipped by mlx-vlm commit 1249c7d.
+ """
+ del kwargs
+
+ hidden_states = self.patch_embed(hidden_states)
+ pos_embeds = self.fast_pos_embed_interpolate(grid_thw)
+ hidden_states = hidden_states + pos_embeds
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
+
+ seq_len = hidden_states.shape[0]
+ hidden_states = hidden_states.reshape(seq_len, -1)
+ rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1)
+
+ cu_seqlens = []
+ for i in range(grid_thw.shape[0]):
+ spatial_seq_len = grid_thw[i, 1] * grid_thw[i, 2]
+ temporal_patches = int(grid_thw[i, 0])
+ cu_seqlens.append(mx.repeat(spatial_seq_len, temporal_patches))
+
+ cu_seqlens = mx.concatenate(cu_seqlens)
+ cu_seqlens = mx.cumsum(cu_seqlens.astype(mx.int32), axis=0)
+ cu_seqlens = mx.pad(
+ cu_seqlens,
+ (1, 0),
+ mode="constant",
+ constant_values=0,
+ )
+
+ deepstack_feature_lists = []
+ for layer_num, block in enumerate(self.blocks):
+ hidden_states = block(
+ hidden_states,
+ cu_seqlens=cu_seqlens,
+ rotary_pos_emb=rotary_pos_emb,
+ )
+ if layer_num in self.deepstack_visual_indexes:
+ deepstack_feature = self.deepstack_merger_list[
+ self.deepstack_visual_indexes.index(layer_num)
+ ](hidden_states)
+ deepstack_feature_lists.append(deepstack_feature)
+
+ hidden_states = self.merger(hidden_states)
+ return hidden_states, deepstack_feature_lists
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/virtual_ple.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/virtual_ple.py
new file mode 100644
index 0000000000..6fabfdfd92
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/virtual_ple.py
@@ -0,0 +1,108 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Streaming FP8 PLE support for Qwen4-Exp oQ conversion.
+
+The FP8 Qwen3.8-Flash-Next checkpoint variant stores each N-gram PLE shard
+as raw F8_E4M3 rows and keeps one shared ``weight_scale`` for the whole
+sharded embedding. That layout is intentionally different from the
+ordinary ``weight`` + per-module scale pairs handled by
+:class:`_LazyTensorIndex`. The official BF16 checkpoint uses the same shard
+names but remains on the normal floating-point path.
+
+The runtime decodes a selected FP8 row first and applies the shared scale
+afterwards. oQ must preserve the same ordering: decode the raw FP8 shard,
+quantize those unscaled values to affine storage, and keep ``weight_scale``
+for the runtime to apply exactly once. Exposing the shard as a virtual BF16
+tensor makes sanitize-plan discovery and the streaming quantizer see the
+correct logical dtype without materializing the 51.2B PLE table eagerly.
+"""
+
+from __future__ import annotations
+
+import logging
+import weakref
+
+import mlx.core as mx
+
+logger = logging.getLogger(__name__)
+
+_FP8_DTYPE = "F8_E4M3"
+
+
+def _is_qwen4_exp(config: dict) -> bool:
+ text_config = config.get("text_config")
+ if not isinstance(text_config, dict):
+ text_config = {}
+ return any(
+ str(model_type or "").lower().startswith("qwen4_exp")
+ for model_type in (config.get("model_type"), text_config.get("model_type"))
+ )
+
+
+def _candidate_keys(config: dict):
+ text_config = config.get("text_config")
+ if not isinstance(text_config, dict):
+ return
+ num_shards = int(text_config.get("split_ngram_parts", 0) or 0)
+ if num_shards <= 0:
+ return
+ for layer_id in text_config.get("ple_layer_ids", ()) or ():
+ layer_index = int(layer_id) - 1
+ if layer_index < 0:
+ continue
+ prefixes = (
+ f"model.language_model.layers.{layer_index}.ple.ple_embedding."
+ "ngram_embedding",
+ f"language_model.model.layers.{layer_index}.ple.ple_embedding."
+ "ngram_embedding",
+ )
+ for shard_index in range(num_shards):
+ for prefix in prefixes:
+ yield f"{prefix}.shard_{shard_index}.weight"
+ yield f"{prefix}.shards.{shard_index}.weight"
+
+
+def _materializer(index_ref, key: str):
+ def materialize():
+ index = index_ref()
+ if index is None:
+ raise RuntimeError(
+ "Qwen4 PLE materializer outlived its tensor index; the index "
+ "must stay alive while virtual tensors are being read"
+ )
+ raw = index.load_source(key)
+ decoded = mx.from_fp8(raw, dtype=mx.bfloat16)
+ mx.eval(decoded)
+ del raw
+ return decoded
+
+ return materialize
+
+
+def register(index, config: dict) -> int:
+ """Expose raw Qwen4 PLE FP8 shards as unscaled BF16 virtual tensors."""
+ if not _is_qwen4_exp(config):
+ return 0
+
+ index_ref = weakref.ref(index)
+ registered = 0
+ for key in _candidate_keys(config):
+ shape = index.source_shape(key)
+ if shape is None or index.source_dtype(key) != _FP8_DTYPE:
+ continue
+ if len(shape) != 2:
+ raise ValueError(f"Qwen4 PLE shard must be rank 2, got {key}: {shape}")
+ index.register_virtual(
+ key,
+ shape,
+ "BF16",
+ _materializer(index_ref, key),
+ hides=(key,),
+ )
+ registered += 1
+
+ if registered:
+ logger.info(
+ "Qwen4 PLE: %d raw FP8 shards exposed as streaming BF16 tensors",
+ registered,
+ )
+ return registered
diff --git a/omlx/patches/qwen35_ane_prefill.py b/omlx/patches/qwen35_ane_prefill.py
index 26c608053e..8d09a864f8 100644
--- a/omlx/patches/qwen35_ane_prefill.py
+++ b/omlx/patches/qwen35_ane_prefill.py
@@ -1020,6 +1020,27 @@ def _eligible_gdn(gdn: Any) -> bool:
)
+def _recurrent_safe_gdn_ane_outputs(
+ z_outputs: int,
+ qkv_outputs: int,
+ fraction: float,
+ alignment: int,
+) -> int:
+ """Return an aligned ANE slice that never enters recurrent QKV rows.
+
+ The ANE compiler requantizes its source slice to per-output-channel INT8.
+ Applying that approximation to QKV changes the recurrent state at every
+ token, so the error can accumulate over a long prompt. Z is a token-local
+ output gate: offloading all of it preserves useful ANE/GPU overlap without
+ feeding approximate values back into the next recurrent step.
+ """
+ if z_outputs <= 0 or qkv_outputs <= 0 or z_outputs % alignment:
+ return 0
+ total_outputs = z_outputs + qkv_outputs
+ requested = (int(total_outputs * fraction) // alignment) * alignment
+ return z_outputs if requested >= z_outputs else 0
+
+
def _pack_affine_gdn_suffix(
qkv: Any,
b: Any,
@@ -1064,9 +1085,9 @@ def _compile_gdn(gdn: Any, config: _AneGDNConfig) -> _CombinedGDNState | None:
cache = {}
gdn._omlx_ane_gdn_cache = cache
- # Put z first in the logical concatenation. At the 40% split this keeps
- # almost all recurrent q/k/v channels on the exact q5 GPU path while ANE
- # handles the output gate plus a small qkv prefix.
+ # Put z first so the approximate ANE slice can stop at the token-local
+ # gate boundary. Recurrent q/k/v channels remain on the source-precision
+ # GPU path (or the explicitly configured FP16 CPU path).
logical = (z, qkv)
z_outputs = int(z.weight.shape[0])
qkv_outputs = int(qkv.weight.shape[0])
@@ -1078,7 +1099,12 @@ def _compile_gdn(gdn: Any, config: _AneGDNConfig) -> _CombinedGDNState | None:
qkv_bits, qkv_group_size = qkv_spec
dual_ane = bool(config.dual_ane and fast.has_symbol("qwen35_ane_dual_affine_qmm_t"))
alignment = 128 if dual_ane else 64
- ane_outputs = (int(total_outputs * config.fraction) // alignment) * alignment
+ ane_outputs = _recurrent_safe_gdn_ane_outputs(
+ z_outputs,
+ qkv_outputs,
+ config.fraction,
+ alignment,
+ )
cpu_enabled = bool(
config.cpu_fraction > 0
and qkv.scales.dtype == mx.float16
@@ -1090,9 +1116,9 @@ def _compile_gdn(gdn: Any, config: _AneGDNConfig) -> _CombinedGDNState | None:
else 0
)
gpu_outputs = total_outputs - ane_outputs - cpu_outputs
- # The native GPU suffix accepts one quantization format. Put all of z on
- # ANE so an oQ4e-style q5-z/q4-qkv mix leaves a homogeneous qkv suffix.
- if ane_outputs < z_outputs:
+ # The native GPU suffix accepts one quantization format. The quality-safe
+ # split puts exactly all of z on ANE, leaving homogeneous qkv on the GPU.
+ if ane_outputs != z_outputs:
return None
qkv_offset = ane_outputs - z_outputs
packed_suffix = (
@@ -1211,30 +1237,64 @@ def dense_logical_slice(start: int, end: int) -> mx.array:
def _min_viable_gdn_fraction(gdn: Any, alignment: int) -> float | None:
- """Smallest gdn_fraction whose aligned slice engages the ANE on ``gdn``.
+ """Smallest fraction whose aligned slice covers exactly z on ``gdn``.
- Mirrors the rule in ``_prepare_gdn_for_bank`` below: the aligned slice
- ``(int(total * f) // alignment) * alignment`` has to cover the z
- projection, otherwise every GDN layer is rejected and no GDN procedure
- compiles at all (issue #2899). ``None`` when z alone exceeds the whole
- projection, i.e. no fraction can work.
+ Wider requests are capped at z so approximate ANE rows never enter the
+ recurrent qkv projection. ``None`` means z cannot be represented exactly
+ with this ANE alignment.
"""
qkv, z, _, _ = _gdn_linears(gdn)
if qkv is None or z is None:
return None
z_outputs = int(z.weight.shape[0])
total_outputs = z_outputs + int(qkv.weight.shape[0])
- if total_outputs <= 0:
- return None
- ane_min = ((z_outputs + alignment - 1) // alignment) * alignment
- if ane_min > total_outputs:
+ if total_outputs <= 0 or z_outputs <= 0 or z_outputs % alignment:
return None
+ ane_min = z_outputs
fraction = ane_min / total_outputs
if (int(total_outputs * fraction) // alignment) * alignment < ane_min:
fraction = (ane_min + 1) / total_outputs
return fraction
+def _log_gdn_recurrent_safe_cap(
+ model: Any,
+ requested_fraction: float,
+ gdn_count: int,
+ dual_ane: bool,
+) -> None:
+ """Report when a wider requested GDN slice is precision-capped at z."""
+ if not gdn_count:
+ return
+ gdn = next(
+ (
+ module
+ for module in (model.modules() if hasattr(model, "modules") else ())
+ if getattr(module, "_omlx_ane_gdn_state", None) is not None
+ ),
+ None,
+ )
+ if gdn is None:
+ return
+ qkv, z, _, _ = _gdn_linears(gdn)
+ z_outputs = int(z.weight.shape[0])
+ qkv_outputs = int(qkv.weight.shape[0])
+ total_outputs = z_outputs + qkv_outputs
+ alignment = 128 if dual_ane else 64
+ requested_outputs = (
+ int(total_outputs * requested_fraction) // alignment
+ ) * alignment
+ if requested_outputs <= z_outputs:
+ return
+ logger.info(
+ "Capped ANE GDN output rows from requested %.3f to %.3f: ANE handles "
+ "only token-local z while recurrent qkv stays off the approximate "
+ "ANE INT8 path",
+ requested_fraction,
+ z_outputs / total_outputs,
+ )
+
+
def _warn_gdn_below_floor(
model: Any, requested: bool, gdn_count: int, gdn_fraction: float, dual_ane: bool
) -> None:
@@ -1283,7 +1343,12 @@ def _prepare_gdn_for_bank(
qkv_bits, qkv_group_size = qkv_spec
dual_ane = bool(config.dual_ane)
alignment = 128 if dual_ane else 64
- ane_outputs = (int(total_outputs * config.fraction) // alignment) * alignment
+ ane_outputs = _recurrent_safe_gdn_ane_outputs(
+ z_outputs,
+ qkv_outputs,
+ config.fraction,
+ alignment,
+ )
from omlx.custom_kernels.qwen35_prefill import fast
cpu_enabled = bool(
@@ -1297,7 +1362,7 @@ def _prepare_gdn_for_bank(
else 0
)
gpu_outputs = total_outputs - ane_outputs - cpu_outputs
- if ane_outputs < z_outputs or gpu_outputs <= 0 or gpu_outputs % 64:
+ if ane_outputs != z_outputs or gpu_outputs <= 0 or gpu_outputs % 64:
return None
qkv_offset = ane_outputs - z_outputs
packed_suffix = (
@@ -1405,7 +1470,12 @@ def _prepare_gdn_runtime_state(
qkv_outputs = int(qkv.weight.shape[0])
total_outputs = z_outputs + qkv_outputs
alignment = 128 if config.dual_ane else 64
- ane_outputs = (int(total_outputs * config.fraction) // alignment) * alignment
+ ane_outputs = _recurrent_safe_gdn_ane_outputs(
+ z_outputs,
+ qkv_outputs,
+ config.fraction,
+ alignment,
+ )
cpu_enabled = bool(
config.cpu_fraction > 0
and qkv.scales.dtype == mx.float16
@@ -1419,7 +1489,7 @@ def _prepare_gdn_runtime_state(
else 0
)
gpu_outputs = total_outputs - ane_outputs - cpu_outputs
- if ane_outputs < z_outputs or gpu_outputs <= 0 or gpu_outputs % 64:
+ if ane_outputs != z_outputs or gpu_outputs <= 0 or gpu_outputs % 64:
return None
qkv_offset = ane_outputs - z_outputs
gpu_offset = qkv_offset + cpu_outputs
@@ -1641,10 +1711,17 @@ def _gdn_backend(
)
)
- return tuple(
+ result = tuple(
mx.concatenate([part[index] for part in projected], axis=-2)
for index in range(4)
)
+ # The four tiled projections are sibling consumers of the same native
+ # hybrid outputs. Schedule them together before the recurrent GDN graph
+ # consumes individual branches; otherwise MLX can interleave their Metal
+ # merge/lifetime boundaries after a prefix-cache restore (#3117). This is
+ # asynchronous, so ANE/GPU overlap is preserved without a host fence.
+ mx.async_eval(*result)
+ return result
def _backend_exact(
@@ -3218,6 +3295,9 @@ def enable_qwen35_ane_prefill(
gdn_fraction,
dual_ane,
)
+ _log_gdn_recurrent_safe_cap(
+ model, gdn_fraction, gdn_count, dual_ane
+ )
logger.info(
"Eagerly compiled %d fused MLP/down and %d GDN procedures "
"into %d "
@@ -3281,6 +3361,7 @@ def enable_qwen35_ane_prefill(
_warn_gdn_below_floor(
model, bool(gdn and gdn_max_layers), gdn_count, gdn_fraction, dual_ane
)
+ _log_gdn_recurrent_safe_cap(model, gdn_fraction, gdn_count, dual_ane)
if count or gdn_count:
logger.info(
"Eagerly compiled %d MLP and %d GDN procedures into %d "
@@ -3371,6 +3452,7 @@ def enable_qwen35_ane_prefill(
_warn_gdn_below_floor(
model, bool(gdn and gdn_max_layers), gdn_count, gdn_fraction, dual_ane
)
+ _log_gdn_recurrent_safe_cap(model, gdn_fraction, gdn_count, dual_ane)
if count:
logger.info(
@@ -3480,8 +3562,9 @@ def release_qwen35_ane_prefill(model: Any) -> tuple[int, int]:
prefill needs back once the KV cache has grown into the guard's sizing
target. Latches every sliced module through the existing per-module
failure flags first (so the dispatch sites fall back to stock GPU compute
- and never lazily recompile), then drops the state references; the native
- models free their programs and mapped blobs when the last reference dies.
+ and never lazily recompile), then drops the state references and clears the
+ per-module state caches that hold the same objects; the native models free
+ their programs and mapped blobs when the last reference dies.
Idempotent, and scoped to this engine instance: the next load of the
model rebuilds the banks from its settings.
@@ -3505,6 +3588,12 @@ def release_qwen35_ane_prefill(model: Any) -> tuple[int, int]:
setattr(module, failed_attr, True)
setattr(module, state_attr, None)
modules_released += 1
+ # Clear cached references too, including states no longer attached.
+ # Loading has finished and the engine step loop is paused for release.
+ for cache_attr in ("_omlx_ane_prefill_cache", "_omlx_ane_gdn_cache"):
+ cache = getattr(module, cache_attr, None)
+ if cache:
+ cache.clear()
if modules_released:
# Zero (not delete) the status counters and set the shed marker:
# attempted=True/configured=False alone is indistinguishable from a
diff --git a/omlx/patches/qwen35_fa256_attention.py b/omlx/patches/qwen35_fa256_attention.py
index c9961f1588..5ef9352e4b 100644
--- a/omlx/patches/qwen35_fa256_attention.py
+++ b/omlx/patches/qwen35_fa256_attention.py
@@ -83,6 +83,13 @@ def _has_quantized_cache(cache) -> bool:
return cache is not None and hasattr(cache, "bits")
+def _bounded_sdpa_fallback(queries, keys, values, scale, mask, sinks):
+ """Keep the registered O(L) contract if the steel kernel itself fails."""
+ from .sdpa256_attention import _flash_sdpa256
+
+ return _flash_sdpa256(queries, keys, values, scale, mask, sinks)
+
+
def _auto_dispatch_budget(kernel, q_block: int, k_block: int) -> int:
"""Size the dispatch budget from the kernel's measured throughput.
@@ -190,14 +197,13 @@ def apply_qwen35_fa256_attention_patch(min_kv_len: int | None = None) -> bool:
if steel_env == "0":
return False
if steel_env != "1" and is_nax_available():
- # Auto: on NAX GPUs (M5 family) stock SDPA's head_dim-256 fallback
- # runs its matmuls on the tensor units and beats this pre-NAX steel
- # kernel, so routing it would regress prefill (M5 Max report:
- # 4k pp 828 -> 400 tok/s on 0.5.0). OMLX_FA256_STEEL=1 forces the
- # kernel on for benchmarking; a NAX port of this kernel is the
- # tracked follow-up.
+ # Auto: MLX 0.32.2 selects its native split-D fused kernel for NAX
+ # head-dim-256 causal prefills with at least 1024 queries. It beats
+ # this pre-NAX steel kernel, so intercepting it would regress prefill.
+ # OMLX_FA256_STEEL=1 still forces the kernel for benchmarking.
logger.info(
- "Qwen FA-256 steel patch skipped: NAX GPU, stock SDPA is faster"
+ "Qwen FA-256 steel patch skipped: NAX GPU, MLX native fused SDPA "
+ "is faster"
)
return False
@@ -263,7 +269,13 @@ def patched_lm_sdpa(
dispatch_budget=dispatch_budget,
)
except Exception:
- logger.warning("fa256 steel lm kernel failed", exc_info=True)
+ logger.warning(
+ "fa256 steel lm kernel failed; using bounded MLX SDPA",
+ exc_info=True,
+ )
+ return _bounded_sdpa_fallback(
+ queries, keys, values, scale, mask, sinks
+ )
return original_lm_sdpa(queries, keys, values, cache, scale, mask, sinks)
mlx_base.scaled_dot_product_attention = patched_lm_sdpa
@@ -313,7 +325,13 @@ def patched_vlm_sdpa(
dispatch_budget=dispatch_budget,
)
except Exception:
- logger.warning("fa256 steel vlm kernel failed", exc_info=True)
+ logger.warning(
+ "fa256 steel vlm kernel failed; using bounded MLX SDPA",
+ exc_info=True,
+ )
+ return _bounded_sdpa_fallback(
+ queries, keys, values, scale, mask, sinks
+ )
return original_vlm_sdpa(
queries, keys, values, cache, scale, mask, sinks
)
@@ -332,6 +350,20 @@ def patched_vlm_sdpa(
pass
if patched_any:
+ try:
+ from .. import memory_monitor
+
+ memory_monitor.register_tiled_prefill_head_dim(
+ 256,
+ min_query_len=_MIN_ROUTE_Q_LEN,
+ min_kv_len=min_kv_len,
+ kv_tile=1024,
+ )
+ except Exception:
+ logger.debug(
+ "could not register Qwen FA-256 with memory_monitor",
+ exc_info=True,
+ )
_PATCHED = True
logger.info(
"Qwen3.5/3.6 FA-256 steel attention patch applied "
diff --git a/omlx/patches/qwen35_gdn_prework.py b/omlx/patches/qwen35_gdn_prework.py
index 73b280aa09..7950430668 100644
--- a/omlx/patches/qwen35_gdn_prework.py
+++ b/omlx/patches/qwen35_gdn_prework.py
@@ -28,12 +28,16 @@
import logging
import mlx.core as mx
+import mlx.nn as nn
logger = logging.getLogger(__name__)
_PATCHED = False
_ENGAGED_LOGGED = False
_KERNEL = None
+_QWEN4_DECODE_KERNEL = None
+_QWEN4_NORM_GATE_KERNEL = None
+_QWEN4_DECODE_ENGAGED_LOGGED = False
_SOURCE = """
uint lane = thread_position_in_threadgroup.x;
@@ -99,6 +103,153 @@
"""
+# Copyright (c) 2026 David Dalcu. The Qwen4 decode prework and norm-gate
+# kernels below are adapted from ddalcu/mlx-serve's MIT-licensed
+# ``src/transformer.zig`` at tag ``v26.8.11-pre-release.1``. Preserve this
+# scoped notice with those kernels.
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+#
+# Qwen4 decode-only continuation of the donor kernel. This is deliberately a
+# separate ABI from the verify kernel above: the production Qwen4 recurrence
+# consumes an FP32 forget gate, while the older donor stores that gate as BF16.
+# Keeping distinct outputs lets this path match mlx-vlm's current arithmetic
+# exactly instead of silently changing the recurrent state update.
+_QWEN4_DECODE_HEADER = """
+ inline float omlx_log1p(float x) {
+ float xp1 = 1.0f + x;
+ if (xp1 == metal::numeric_limits::max()) {
+ return metal::numeric_limits::max();
+ }
+ if (xp1 == 1.0f) {
+ return x;
+ }
+ return x * (metal::log(xp1) / (xp1 - 1.0f));
+ }
+"""
+
+
+_QWEN4_DECODE_SOURCE = """
+ uint lane = thread_position_in_threadgroup.x;
+ uint logical_head = threadgroup_position_in_grid.z;
+ constexpr uint q_heads = uint(HK);
+ constexpr uint k_head_base = uint(HK);
+ constexpr uint v_head_base = 2 * uint(HK);
+ bool is_q = logical_head < q_heads;
+ bool is_k = logical_head >= k_head_base && logical_head < v_head_base;
+ uint head = is_q ? logical_head
+ : (is_k ? logical_head - k_head_base
+ : logical_head - v_head_base);
+ uint channel_base = is_q ? head * uint(DK)
+ : (is_k ? uint(HK) * uint(DK) + head * uint(DK)
+ : 2 * uint(HK) * uint(DK) + head * uint(DV));
+
+ T activated[4];
+ float sumsq = 0.0f;
+ for (uint i = 0; i < 4; ++i) {
+ uint channel = channel_base + lane * 4 + i;
+ float acc = 0.0f;
+ for (uint tap = 0; tap < 3; ++tap) {
+ acc += float(conv_state[tap * uint(C) + channel])
+ * float(conv_w[channel * 4 + tap]);
+ }
+ acc += float(qkv[channel]) * float(conv_w[channel * 4 + 3]);
+ const T conv = T(acc);
+ T sy = T(1) / (T(1) + metal::exp(metal::abs(conv)));
+ const T act = conv * ((conv < T(0)) ? sy : T(1) - sy);
+ activated[i] = act;
+ float value = float(act);
+ sumsq += value * value;
+
+ // T=1: [old0, old1, old2, qkv] -> [old1, old2, qkv]. Each
+ // channel is owned by exactly one thread, so no synchronization is
+ // needed between these three stores.
+ conv_out[channel] = conv_state[uint(C) + channel];
+ conv_out[uint(C) + channel] = conv_state[2 * uint(C) + channel];
+ conv_out[2 * uint(C) + channel] = qkv[channel];
+ }
+
+ if (is_q || is_k) {
+ sumsq = simd_sum(sumsq);
+ float inv = metal::precise::rsqrt(sumsq / float(DK) + 1e-6f);
+ float scale = is_q ? float(q_scale) : float(k_scale);
+ uint out_base = head * uint(DK) + lane * 4;
+ for (uint i = 0; i < 4; ++i) {
+ // rms_norm returns T; multiplying by the Python scalar also
+ // returns T, so preserve both rounding sites.
+ const T rms = T(float(activated[i]) * inv);
+ const T value = T(float(rms) * scale);
+ if (is_q) {
+ q_out[out_base + i] = value;
+ } else {
+ k_out[out_base + i] = value;
+ }
+ }
+ } else {
+ uint out_base = head * uint(DV) + lane * 4;
+ for (uint i = 0; i < 4; ++i) {
+ v_out[out_base + i] = activated[i];
+ }
+ if (lane == 0) {
+ const T bv = b_in[head];
+ T by = T(1) / (T(1) + metal::exp(metal::abs(bv)));
+ beta_out[head] = (bv < T(0)) ? by : T(1) - by;
+
+ // compute_g casts A_log to FP32 but keeps softplus(a+dt_bias)
+ // in BF16 before the FP32 multiply and outer exp.
+ const T apd = T(float(a_in[head]) + float(dt_bias[head]));
+ const T neg_abs = -metal::abs(apd);
+ const T exp_term = T(metal::precise::exp(float(neg_abs)));
+ const T log_term = T(omlx_log1p(float(exp_term)));
+ const T positive = metal::max(apd, T(0));
+ const T sp = T(float(positive) + float(log_term));
+ float ea = metal::precise::exp(float(A_log[head]));
+ g_out[head] = metal::precise::exp(-(ea * float(sp)));
+ }
+ }
+"""
+
+
+_QWEN4_NORM_GATE_SOURCE = """
+ uint lane = thread_position_in_threadgroup.x;
+ uint head = threadgroup_position_in_grid.z;
+ uint base = head * uint(DV) + lane * 4;
+ float xs[4];
+ float sumsq = 0.0f;
+ for (uint i = 0; i < 4; ++i) {
+ xs[i] = float(y[base + i]);
+ sumsq += xs[i] * xs[i];
+ }
+ sumsq = simd_sum(sumsq);
+ float inv = metal::precise::rsqrt(sumsq / float(DV) + float(eps));
+ for (uint i = 0; i < 4; ++i) {
+ // mx.fast.rms_norm materializes BF16 before Qwen4 casts it back to
+ // FP32 for the sigmoid product.
+ const T normed = norm_w[lane * 4 + i] * T(xs[i] * inv);
+ float zv = float(z[base + i]);
+ float sy = 1.0f / (1.0f + metal::precise::exp(metal::abs(zv)));
+ float sig = zv < 0.0f ? sy : 1.0f - sy;
+ out[base + i] = T(float(normed) * sig);
+ }
+"""
+
+
def _kernel():
global _KERNEL
if _KERNEL is None:
@@ -140,6 +291,252 @@ def gdn_prework_fused(qkv, conv_state, conv_w, q_scale, k_scale, hk, hv, dk, dv)
return outs
+def _qwen4_decode_kernel():
+ global _QWEN4_DECODE_KERNEL
+ if _QWEN4_DECODE_KERNEL is None:
+ _QWEN4_DECODE_KERNEL = mx.fast.metal_kernel(
+ name="omlx_qwen4_gdn_decode_prework",
+ input_names=[
+ "qkv",
+ "conv_state",
+ "conv_w",
+ "q_scale",
+ "k_scale",
+ "b_in",
+ "a_in",
+ "A_log",
+ "dt_bias",
+ ],
+ output_names=[
+ "q_out",
+ "k_out",
+ "v_out",
+ "conv_out",
+ "g_out",
+ "beta_out",
+ ],
+ header=_QWEN4_DECODE_HEADER,
+ source=_QWEN4_DECODE_SOURCE,
+ )
+ return _QWEN4_DECODE_KERNEL
+
+
+def qwen4_decode_prework_fused(
+ qkv,
+ conv_state,
+ conv_w,
+ q_scale,
+ k_scale,
+ b,
+ a,
+ A_log,
+ dt_bias,
+ hk,
+ hv,
+ dk,
+ dv,
+):
+ """Fuse the exact Qwen4 B1/T1 GDN prework into one Metal dispatch."""
+
+ c_dim = int(qkv.shape[-1])
+ return _qwen4_decode_kernel()(
+ inputs=[
+ qkv,
+ conv_state,
+ conv_w,
+ q_scale,
+ k_scale,
+ b,
+ a,
+ A_log,
+ dt_bias,
+ ],
+ template=[
+ ("T", qkv.dtype),
+ ("HK", hk),
+ ("HV", hv),
+ ("DK", dk),
+ ("DV", dv),
+ ("C", c_dim),
+ ],
+ grid=(32, 1, 2 * hk + hv),
+ threadgroup=(32, 1, 1),
+ output_shapes=[
+ (1, 1, hk, dk),
+ (1, 1, hk, dk),
+ (1, 1, hv, dv),
+ (1, 3, c_dim),
+ (1, 1, hv),
+ (1, 1, hv),
+ ],
+ output_dtypes=[
+ qkv.dtype,
+ qkv.dtype,
+ qkv.dtype,
+ qkv.dtype,
+ mx.float32,
+ qkv.dtype,
+ ],
+ )
+
+
+def _qwen4_norm_gate_kernel():
+ global _QWEN4_NORM_GATE_KERNEL
+ if _QWEN4_NORM_GATE_KERNEL is None:
+ _QWEN4_NORM_GATE_KERNEL = mx.fast.metal_kernel(
+ name="omlx_qwen4_gdn_decode_norm_gate",
+ input_names=["y", "z", "norm_w", "eps"],
+ output_names=["out"],
+ source=_QWEN4_NORM_GATE_SOURCE,
+ )
+ return _QWEN4_NORM_GATE_KERNEL
+
+
+def qwen4_decode_norm_gate_fused(y, z, norm_w, *, hv, dv, eps):
+ """Fuse Qwen4's BF16 RMSNorm + FP32 sigmoid-gate at B1/T1."""
+
+ return _qwen4_norm_gate_kernel()(
+ inputs=[y, z, norm_w, mx.array(eps, dtype=mx.float32)],
+ template=[
+ ("T", y.dtype),
+ ("HV", hv),
+ ("DV", dv),
+ ],
+ grid=(32, 1, hv),
+ threadgroup=(32, 1, 1),
+ output_shapes=[(1, 1, hv * dv)],
+ output_dtypes=[y.dtype],
+ )[0]
+
+
+def _qwen4_decode_recurrence(q, k, v, g, beta, state):
+ from mlx_lm.models.gated_delta import gated_delta_kernel
+
+ return gated_delta_kernel(q, k, v, g, beta, state, None)
+
+
+def _qwen4_decode_static_eligible(module) -> bool:
+ """Fail closed unless this is the shipped Qwen4 oQe decode geometry."""
+
+ conv_dim = 2 * 16 * 128 + 48 * 128
+ if (
+ type(module).__name__ != "Qwen4ExpGatedDeltaNet"
+ or type(module).__module__ != "mlx_vlm.models.qwen4_exp.language"
+ or module.training
+ or module.num_k_heads != 16
+ or module.num_v_heads != 48
+ or module.head_k_dim != 128
+ or module.head_v_dim != 128
+ or module.conv_kernel_size != 4
+ ):
+ return False
+
+ conv = getattr(module, "conv1d", None)
+ norm = getattr(module, "norm", None)
+ if (
+ conv is None
+ or getattr(conv, "bias", None) is not None
+ or conv.weight.shape != (conv_dim, 4, 1)
+ or conv.weight.dtype != mx.bfloat16
+ or norm is None
+ or getattr(norm, "activation", None) != "sigmoid"
+ or norm.weight.shape != (128,)
+ or norm.weight.dtype != mx.bfloat16
+ or module.A_log.shape != (48,)
+ or module.A_log.dtype != mx.bfloat16
+ or module.dt_bias.shape != (48,)
+ or module.dt_bias.dtype != mx.bfloat16
+ ):
+ return False
+
+ def canonical_projection(linear, rows, signatures):
+ if type(linear) is not nn.QuantizedLinear or linear.mode != "affine":
+ return False
+ signature = (linear.bits, linear.group_size)
+ if signature not in signatures:
+ return False
+ bits, group_size = signature
+ packed_cols = 2560 * bits // 32
+ scale_cols = 2560 // group_size
+ return (
+ linear.weight.shape == (rows, packed_cols)
+ and linear.weight.dtype == mx.uint32
+ and linear.scales.shape == (rows, scale_cols)
+ and linear.scales.dtype == mx.bfloat16
+ and linear.biases is not None
+ and linear.biases.shape == (rows, scale_cols)
+ and linear.biases.dtype == mx.bfloat16
+ and "bias" not in linear
+ )
+
+ # The shipped oQe allocation is intentionally mixed per tensor. This
+ # kernel begins after those projections, so accept only the exact
+ # canonical layouts emitted by the converter rather than demanding that
+ # all four happen to share layer 0's q6/g64 allocation.
+ if not canonical_projection(
+ module.in_proj_qkv,
+ conv_dim,
+ {(4, 64), (5, 64), (6, 64)},
+ ):
+ return False
+ for linear, rows in (
+ (module.in_proj_z, 48 * 128),
+ (module.in_proj_b, 48),
+ (module.in_proj_a, 48),
+ ):
+ if not canonical_projection(linear, rows, {(5, 128), (6, 64)}):
+ return False
+
+ out = module.out_proj
+ return (
+ type(out) is nn.QuantizedLinear
+ and out.bits == 5
+ and out.group_size == 128
+ and out.mode == "affine"
+ and out.weight.shape == (2560, 960)
+ and out.weight.dtype == mx.uint32
+ and out.scales.shape == (2560, 48)
+ and out.scales.dtype == mx.bfloat16
+ and out.biases is not None
+ and out.biases.shape == (2560, 48)
+ and out.biases.dtype == mx.bfloat16
+ and "bias" not in out
+ )
+
+
+def _qwen4_decode_dynamic_eligible(
+ module,
+ inputs,
+ mask,
+ cache,
+ gdn_sink,
+ target_verify,
+) -> bool:
+ if (
+ target_verify
+ or gdn_sink is not None
+ or mask is not None
+ or cache is None
+ or not isinstance(inputs, mx.array)
+ or inputs.shape != (1, 1, 2560)
+ or inputs.dtype != mx.bfloat16
+ or getattr(cache, "lengths", None) is not None
+ or getattr(cache, "left_padding", None) is not None
+ ):
+ return False
+ conv_state = cache[0]
+ recurrent_state = cache[1]
+ return (
+ isinstance(conv_state, mx.array)
+ and conv_state.shape == (1, 3, 10240)
+ and conv_state.dtype == mx.bfloat16
+ and isinstance(recurrent_state, mx.array)
+ and recurrent_state.shape == (1, 48, 128, 128)
+ and recurrent_state.dtype == mx.float32
+ and _qwen4_decode_static_eligible(module)
+ )
+
+
def apply_qwen35_gdn_prework_patch() -> bool:
"""Route the batch-1 target-verify GDN prework through the fused kernel.
@@ -179,6 +576,7 @@ def apply_qwen35_gdn_prework_patch() -> bool:
orig_call = cls.__call__
disabled = {"flag": False}
+ qwen4_decode_disabled = {"flag": False}
def _eligible(self, inputs, mask, cache, gdn_sink, s_len):
if gdn_sink is None or cache is None:
@@ -207,6 +605,110 @@ def _eligible(self, inputs, mask, cache, gdn_sink, s_len):
def patched_call(self, inputs, mask=None, cache=None, gdn_sink=None,
target_verify=False):
S = inputs.shape[1]
+ if (
+ not qwen4_decode_disabled["flag"]
+ and _qwen4_decode_dynamic_eligible(
+ self,
+ inputs,
+ mask,
+ cache,
+ gdn_sink,
+ target_verify,
+ )
+ ):
+ conv_state = cache[0]
+ recurrent_state = cache[1]
+ try:
+ mixed_qkv, z, b, a = q35._target_verify_linears(
+ (
+ self.in_proj_qkv,
+ self.in_proj_z,
+ self.in_proj_b,
+ self.in_proj_a,
+ ),
+ inputs,
+ False,
+ )
+ inv_scale = self.head_k_dim**-0.5
+ q_scale = getattr(self, "_omlx_qwen4_decode_q_scale", None)
+ k_scale = getattr(self, "_omlx_qwen4_decode_k_scale", None)
+ if q_scale is None or k_scale is None:
+ q_scale = mx.array(
+ inv_scale * inv_scale,
+ dtype=mx.bfloat16,
+ )
+ k_scale = mx.array(inv_scale, dtype=mx.bfloat16)
+ self._omlx_qwen4_decode_q_scale = q_scale
+ self._omlx_qwen4_decode_k_scale = k_scale
+
+ q, k, v, next_conv_state, g, beta = (
+ qwen4_decode_prework_fused(
+ mixed_qkv,
+ conv_state,
+ self.conv1d.weight,
+ q_scale,
+ k_scale,
+ b,
+ a,
+ self.A_log,
+ self.dt_bias,
+ self.num_k_heads,
+ self.num_v_heads,
+ self.head_k_dim,
+ self.head_v_dim,
+ )
+ )
+ out, next_recurrent_state = _qwen4_decode_recurrence(
+ q,
+ k,
+ v,
+ g,
+ beta,
+ recurrent_state,
+ )
+ flat = qwen4_decode_norm_gate_fused(
+ out,
+ z,
+ self.norm.weight,
+ hv=self.num_v_heads,
+ dv=self.head_v_dim,
+ eps=self.norm.eps,
+ )
+ result = q35._target_verify_linear(
+ self.out_proj,
+ flat,
+ False,
+ )
+
+ # Commit cache ownership only after every fallible graph
+ # construction step succeeded. This mirrors the verify
+ # route below and keeps a fallback from applying the token
+ # twice after a late error.
+ cache[0] = next_conv_state
+ cache[1] = next_recurrent_state
+ if hasattr(cache, "advance"):
+ cache.advance(1)
+ q35._qwen3_5_advance_left_padding_info(cache, 1)
+ q35._qwen3_5_advance_lengths_info(cache, 1)
+
+ global _QWEN4_DECODE_ENGAGED_LOGGED
+ if not _QWEN4_DECODE_ENGAGED_LOGGED:
+ _QWEN4_DECODE_ENGAGED_LOGGED = True
+ logger.info(
+ "Qwen4 fused B1/T1 GDN decode prework and norm-gate "
+ "engaged"
+ )
+ return result
+ except Exception:
+ cache[0] = conv_state
+ cache[1] = recurrent_state
+ qwen4_decode_disabled["flag"] = True
+ logger.warning(
+ "Qwen4 fused GDN decode arm failed; reverting to stock "
+ "for the rest of the process",
+ exc_info=True,
+ )
+
if disabled["flag"] or not _eligible(self, inputs, mask, cache, gdn_sink, S):
return orig_call(self, inputs, mask=mask, cache=cache,
gdn_sink=gdn_sink, target_verify=target_verify)
diff --git a/omlx/patches/qwen35_moe_gate_up.py b/omlx/patches/qwen35_moe_gate_up.py
index b7c77082dd..0719386e19 100644
--- a/omlx/patches/qwen35_moe_gate_up.py
+++ b/omlx/patches/qwen35_moe_gate_up.py
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
-"""Fuse Qwen3.5/3.6 MoE routed gate/up projections into one gather_qmm.
+"""Fuse supported MoE routed gate/up projections into one gather_qmm.
At single-token decode the routed-expert path runs three tiny
``gather_qmm`` launches per MoE layer (gate, up, down). Affine
@@ -45,10 +45,17 @@
_CALL_PATCHED = False
-# Loaded model classes whose module path marks a supported SwitchGLU family
-# (mlx_lm qwen3_5 / qwen3_5_moe, the omlx single-checkpoint MTP wrapper, and
-# the vendored laguna module).
-_FAMILY_TOKENS = ("qwen3_5", "qwen3_6", "qwen35", "laguna")
+# Loaded model classes whose module path marks a supported SwitchGLU family:
+# mlx-lm Qwen3.5/3.6 and HyV3, Qwen4-Exp's inherited SwitchGLU, the oMLX
+# single-checkpoint MTP wrapper, and the vendored Laguna module.
+_FAMILY_TOKENS = (
+ "qwen3_5",
+ "qwen3_6",
+ "qwen35",
+ "qwen4_exp",
+ "laguna",
+ "hy_v3",
+)
def _is_supported_family(model: Any) -> bool:
@@ -188,7 +195,7 @@ def _ensure_call_patch() -> None:
def apply_qwen35_moe_gate_up_fusion(model: Any) -> int:
- """Fuse gate+up expert projections on a loaded Qwen3.5/3.6 MoE model.
+ """Fuse gate+up expert projections on a supported loaded MoE model.
Returns the number of fused ``SwitchGLU`` instances (0 when disabled
via ``OMLX_QWEN35_MOE_GATE_UP=0``, the model family is unsupported,
@@ -213,7 +220,7 @@ def apply_qwen35_moe_gate_up_fusion(model: Any) -> int:
# ~2/3 of the expert bytes (#2304). Drain per fused layer to bound
# the transient to a single layer's worth.
_sync_and_clear_cache()
- logger.info("Qwen MoE gate+up fusion applied: %d layers", len(targets))
+ logger.info("MoE gate+up fusion applied: %d layers", len(targets))
return len(targets)
diff --git a/omlx/patches/sdpa256_attention.py b/omlx/patches/sdpa256_attention.py
index 153a6cdb65..35c1e32d03 100644
--- a/omlx/patches/sdpa256_attention.py
+++ b/omlx/patches/sdpa256_attention.py
@@ -1,28 +1,22 @@
# SPDX-License-Identifier: Apache-2.0
-"""Patch scaled_dot_product_attention to fix head_dim=256 long-context prefill.
-
-MLX's fused SDPA kernel supports head_dim in {64, 80, 128} only, so head_dim=256
-(e.g. Qwen3.6-27B) multi-token prefill falls back to an unfused path that
-materializes the full ``[n_q, query_len, kv_len]`` score matrix -> O(L^2) memory,
-OOMing / tripping the prefill guard far below the context window. Decode
-(query_len == 1) is unaffected (MLX has a fused vector kernel for 256).
-
-This routes head_dim=256 causal prefill to a flash-style online-softmax pass in
-pure MLX array ops (tiled over KV; running max/sum/accumulator) that never
-materializes the score matrix -> peak memory O(L). It rides MLX's GEMM, so speed
-is on par with the fallback; the win is memory. ``register_tiled_prefill_head_dim``
-flips the prefill-guard estimator to O(L) in lockstep (else it keeps rejecting).
-
-The route is memory-aware (issue #2204): the unfused fallback is faster
-everywhere its score matrix fits (on NAX GPUs its big GEMMs run on the tensor
-units; even pre-NAX it is ~2x faster than the tiled pass at long context, issue
-#2155), so when the Scheduler has registered a headroom provider the tiled pass
-engages only if the unfused transient would NOT fit under the prefill-guard
-ceiling. Without a provider (no Scheduler, ceiling not propagated yet) the
-route keeps the memory-safe default: always tiled past the kv_len threshold.
-``OMLX_SDPA256_TILED=1`` forces the tiled pass whenever the shape gates match
-(pre-#2204 behavior); ``OMLX_SDPA256_TILED=0`` never engages it (restores the
-O(L^2) memory wall — benchmarking only).
+"""Keep head-dim-256 long-context prefill bounded on MLX 0.32.2.
+
+MLX 0.32.2 ships a fused full-attention kernel for head dimensions 192 and 256,
+but deliberately keeps the faster unfused path as the default on pre-NAX GPUs.
+That default materializes the full ``[n_q, query_len, kv_len]`` score matrix and
+can still exceed oMLX's memory-guard ceiling.
+
+When the unfused transient fits, this patch preserves MLX's default routing. If
+it does not fit (or no guard ceiling is available), it calls MLX 0.32.2 with
+``force_fused=True``. This replaces oMLX's old pure-array tiled implementation:
+the bounded route is now an upstream native fused kernel instead of the slow
+sequential tile loop. On NAX, MLX's default already selects its fast split-D
+head-dim-256 kernel for causal prefills with at least 1024 queries.
+
+``OMLX_SDPA256_TILED=1/0`` remains accepted for compatibility and now forces or
+disables the bounded route. Metal uses the native fused kernel; CUDA retains
+the prior array-tiled implementation because MLX 0.32.2's CUDA fused kernel
+does not support head_dim 256. The default is memory-aware.
Install mechanics mirror turboquant_attention.py (patch the module attr + rebind
already-imported model modules). The route is strictly gated (see _should_route);
@@ -31,49 +25,47 @@
import logging
import os
+import threading
import weakref
import mlx.core as mx
-from omlx.memory_monitor import estimate_unfused_sdpa_call_bytes
+from omlx.memory_monitor import (
+ SDPA256_UNFUSED_SCORE_DTYPE_SIZE,
+ estimate_unfused_sdpa_call_bytes,
+)
logger = logging.getLogger(__name__)
_PATCHED = False
HEAD_DIM = 256
-# Engage the tiled kernel only once the context is long enough that the unfused
-# fallback's O(L^2) score matrix becomes a memory problem. Below this, the
-# fused-GEMM fallback is faster and fits comfortably. Tunable.
+# Force the bounded kernel only once the context is long enough that the
+# default unfused route's O(L^2) score matrix becomes a memory problem.
_SDPA256_MIN_KV_LEN = 8192
# Decode-shaped multi-row calls (MTP verify: q_len = 1 + draft depth <= 9)
-# must not take this route: the per-KV-tile eval sync only amortizes over
-# prefill-sized q tiles, and at tiny q_len it costs O(kv_len/tile) sequential
-# dispatches per call — 8-22x slower than stock SDPA, collapsing long-context
-# MTP throughput (issue #2127). Below this floor the stock path's score
-# matrix is at most n_q * 15 * kv_len, which is never a memory problem.
+# do not need the forced full-attention route. Below this floor the stock path's
+# score matrix is at most n_q * 15 * kv_len and is not a memory problem.
_SDPA256_MIN_Q_LEN = 16
-# Tile sizes for the online-softmax kernel (tuned on M2 Max).
_Q_TILE = 512
+# A deliberately conservative score-tile width used only by the admission
+# estimate. MLX's fused kernel keeps a smaller on-chip block, so this does not
+# understate the bounded route's score working set.
_KV_TILE = 1024
-
-_NEG_INF = -1e30 # fp32 sentinel for masked logits (exp -> 0)
+_NEG_INF = -1e30
# Live guard-headroom provider for memory-aware routing (issue #2204).
-# Registered by Scheduler.__init__ as a bound method returning the bytes left
-# under the adaptive-prefill-throttle target (hard ceiling x headroom safety,
-# clamped by the abort cap), or a negative value when no ceiling is active.
-# Held as a WeakMethod so a torn-down Scheduler auto-unregisters and the route
-# falls back to the memory-safe always-tiled default.
-_HEADROOM_PROVIDER: "weakref.WeakMethod | None" = None
-# OMLX_SDPA256_TILED override, parsed at apply time: True = always tiled,
-# False = never tiled, None = memory-aware auto.
+# Scheduler.step registers the active Scheduler on its execution thread. Each
+# engine uses its own worker, so thread-local storage keeps concurrent engines
+# from replacing one another's provider. The bound method is weakly held so a
+# torn-down Scheduler leaves that worker on the memory-bounded native fused
+# default.
+_HEADROOM_PROVIDER_LOCAL = threading.local()
+# Backward-compatible override: True = always force fused, False = never force,
+# None = memory-aware auto.
_FORCE_TILED: bool | None = None
-# Tiled-route reasons already logged. The tiled pass trades substantial
-# prefill throughput at long kv_len for O(L) memory, and nothing surfaced the
-# route decision before (issue #2283 took an A/B repro to diagnose), so the
-# first engagement per reason logs at INFO; repeats stay silent to keep the
-# hot path quiet.
+# Bounded-route reasons already logged. The first engagement per reason logs at
+# INFO; repeats stay silent to keep the hot path quiet.
_TILED_ROUTE_LOGGED: "set[str]" = set()
@@ -82,19 +74,30 @@ def _note_tiled_route(reason: str, detail: str) -> None:
return
_TILED_ROUTE_LOGGED.add(reason)
logger.info(
- "sdpa256: head-dim-256 prefill taking the tiled (memory-safe, slower) "
- "path: %s. The unfused fast path resumes when guard headroom allows; "
+ "sdpa256: head-dim-256 prefill forcing the memory-bounded path: %s. "
+ "The default fast path resumes when guard "
+ "headroom allows; "
"OMLX_SDPA256_TILED=1/0 forces the route.",
detail,
)
def set_unfused_headroom_provider(method) -> None:
- """Register a bound method returning the prefill guard's live headroom in
- bytes (negative when no ceiling is active). Lets ``_should_route`` prefer
- the faster unfused fallback whenever its O(L^2) transient fits."""
- global _HEADROOM_PROVIDER
- _HEADROOM_PROVIDER = weakref.WeakMethod(method)
+ """Bind the active Scheduler's headroom provider to this worker thread."""
+ ref = getattr(_HEADROOM_PROVIDER_LOCAL, "ref", None)
+ current = ref() if ref is not None else None
+ if (
+ current is not None
+ and current.__self__ is method.__self__
+ and current.__func__ is method.__func__
+ ):
+ return
+ _HEADROOM_PROVIDER_LOCAL.ref = weakref.WeakMethod(method)
+
+
+def _get_unfused_headroom_provider():
+ ref = getattr(_HEADROOM_PROVIDER_LOCAL, "ref", None)
+ return ref() if ref is not None else None
def _parse_force_tiled_env() -> bool | None:
@@ -106,19 +109,31 @@ def _parse_force_tiled_env() -> bool | None:
return None
+def _notify_bounded_route(provider, active: bool) -> None:
+ """Let the scheduler retire measurements from the previous route."""
+ try:
+ owner = getattr(provider, "__self__", None)
+ callback = getattr(owner, "_sdpa256_bounded_route_changed", None)
+ if callable(callback):
+ callback(active)
+ except Exception:
+ logger.debug("sdpa256 route notification failed", exc_info=True)
+
+
def _tiled_route_required(queries, keys) -> bool:
- """Decide tiled vs stock for a shape-matched prefill call (True = tiled).
+ """Decide forced-fused vs default for a matched call (True = force).
The stock unfused fallback is faster wherever its score matrix fits
- (issues #2155 / #2204), so take the tiled pass only when the unfused
+ (issues #2155 / #2204), so force the fused path only when the unfused
transient would not fit under the guard ceiling — or when no headroom
info is available, keeping the memory-safe #2025 behavior."""
+ provider = _get_unfused_headroom_provider()
if _FORCE_TILED is not None:
if _FORCE_TILED:
_note_tiled_route("forced", "forced by OMLX_SDPA256_TILED=1")
+ _notify_bounded_route(provider, _FORCE_TILED)
return _FORCE_TILED
try:
- provider = _HEADROOM_PROVIDER() if _HEADROOM_PROVIDER is not None else None
if provider is None:
_note_tiled_route(
"no-provider",
@@ -133,6 +148,7 @@ def _tiled_route_required(queries, keys) -> bool:
"memory ceiling not available (enforcer state not yet "
"propagated)",
)
+ _notify_bounded_route(provider, True)
return True
batch, n_q, q_len, _ = queries.shape
transient = estimate_unfused_sdpa_call_bytes(
@@ -140,52 +156,60 @@ def _tiled_route_required(queries, keys) -> bool:
q_len,
keys.shape[-2],
HEAD_DIM,
- score_dtype_size=queries.dtype.size,
+ # The unfused fallback materializes fp32 scores even for bf16
+ # inputs (issue #2204 follow-up): pricing it at the query dtype
+ # halves the predicted matrix and admits OOM spikes at long
+ # context. Shared with the guard via the memory_monitor constant.
+ score_dtype_size=SDPA256_UNFUSED_SCORE_DTYPE_SIZE,
)
- if transient > headroom:
+ bounded = transient > headroom
+ _notify_bounded_route(provider, bounded)
+ if bounded:
_note_tiled_route(
"insufficient-headroom",
f"unfused transient ~{transient / 2**20:.0f}MiB exceeds live "
f"guard headroom ~{headroom / 2**20:.0f}MiB at "
f"kv_len={keys.shape[-2]}",
)
- return True
- return False
+ return bounded
except Exception:
_note_tiled_route("probe-error", "guard headroom probe failed")
logger.debug("sdpa256 headroom probe failed", exc_info=True)
return True # headroom info unavailable -> memory-safe default
-def _flash_sdpa256(queries, keys, values, scale, mask):
- """Flash-style online-softmax attention for head_dim=256 prefill.
-
- queries: [batch, n_q, q_len, head_dim]
- keys/values: [batch, n_kv, k_len, head_dim] (n_q % n_kv == 0)
- mask: "causal" or None. Returns [batch, n_q, q_len, head_dim] in
- queries.dtype.
+def _broadcast_mask_5d(mask, batch, n_kv, group_size, q_len, k_len):
+ """Reshape an array mask for the tiled GQA attention layout."""
+ if mask.ndim == 4:
+ pass
+ elif mask.ndim == 3:
+ # Preserve mlx-lm's convention: [batch, query, key].
+ mask = mask[:, None, :, :]
+ elif mask.ndim == 2:
+ mask = mask[None, None, :, :]
+ elif mask.ndim == 1:
+ mask = mask[None, None, None, :]
+ else:
+ raise ValueError(f"unsupported attention mask ndim: {mask.ndim}")
+ n_q = n_kv * group_size
+ mask = mx.broadcast_to(mask, (batch, n_q, q_len, k_len))
+ return mask.reshape(batch, n_kv, group_size, q_len, k_len)
- Tiles over Q and KV, keeping a running (max m, sum denom, accumulator acc) per
- query row so the [q x full_kv] score matrix is never materialized. fp32
- accumulators; output cast back to the input dtype. GQA via reshape+broadcast.
- MLX is lazy: without forcing materialization the whole tiled graph would stay
- live until eval (peak dominated by graph buildup, not the O(L) working set),
- so the running carry is eval'd per KV step / per finished Q tile to bound the
- live graph to ~one tile -> true O(L) peak.
- """
+def _array_tiled_sdpa256(queries, keys, values, scale, mask, sinks=None):
+ """Portable bounded fallback for shapes without a native fused kernel."""
batch, n_q, q_len, head_dim = queries.shape
_, n_kv, k_len, _ = keys.shape
+ value_dim = values.shape[-1]
group_size = n_q // n_kv
- causal = mask == "causal"
+ causal = isinstance(mask, str) and mask == "causal"
+ array_mask = None
+ if isinstance(mask, mx.array):
+ array_mask = _broadcast_mask_5d(mask, batch, n_kv, group_size, q_len, k_len)
qr = queries.reshape(batch, n_kv, group_size, q_len, head_dim)
kr = keys.reshape(batch, n_kv, 1, k_len, head_dim)
- vr = values.reshape(batch, n_kv, 1, k_len, head_dim)
-
- # MLX 'causal' aligns queries to the END of the key axis: with a cached
- # prefix (k_len > q_len, chunked prefill) local query i is global position
- # i + offset and attends keys 0..(i + offset). offset == 0 for square.
+ vr = values.reshape(batch, n_kv, 1, k_len, value_dim)
offset = k_len - q_len
out_q_tiles = []
@@ -195,9 +219,15 @@ def _flash_sdpa256(queries, keys, values, scale, mask):
qt = qi1 - qi0
q_pos = mx.arange(qi0 + offset, qi1 + offset).reshape(1, 1, 1, qt, 1)
- m = mx.full((batch, n_kv, group_size, qt, 1), _NEG_INF, dtype=mx.float32)
- denom = mx.zeros((batch, n_kv, group_size, qt, 1), dtype=mx.float32)
- acc = mx.zeros((batch, n_kv, group_size, qt, head_dim), dtype=mx.float32)
+ state_shape = (batch, n_kv, group_size, qt, 1)
+ if sinks is None:
+ m = mx.full(state_shape, _NEG_INF, dtype=mx.float32)
+ denom = mx.zeros(state_shape, dtype=mx.float32)
+ else:
+ sink_logits = sinks.astype(mx.float32).reshape(1, n_kv, group_size, 1, 1)
+ m = mx.broadcast_to(sink_logits, state_shape)
+ denom = mx.ones(state_shape, dtype=mx.float32)
+ acc = mx.zeros((batch, n_kv, group_size, qt, value_dim), dtype=mx.float32)
kv_end = min(qi1 + offset, k_len) if causal else k_len
for kj0 in range(0, kv_end, _KV_TILE):
@@ -206,26 +236,60 @@ def _flash_sdpa256(queries, keys, values, scale, mask):
vb = vr[:, :, :, kj0:kj1, :].astype(mx.float32)
kt = kj1 - kj0
- s = (qb @ mx.swapaxes(kb, -1, -2)) * scale
+ scores = (qb @ mx.swapaxes(kb, -1, -2)) * scale
if causal:
k_pos = mx.arange(kj0, kj1).reshape(1, 1, 1, 1, kt)
- s = mx.where(k_pos > q_pos, _NEG_INF, s)
-
- m_tile = mx.max(s, axis=-1, keepdims=True)
- m_new = mx.maximum(m, m_tile)
- p = mx.exp(s - m_new)
- corr = mx.exp(m - m_new)
- denom = denom * corr + mx.sum(p, axis=-1, keepdims=True)
- acc = acc * corr + (p @ vb)
- m = m_new
- mx.eval(m, denom, acc) # bound the live graph -> O(L) peak
+ scores = mx.where(k_pos > q_pos, _NEG_INF, scores)
+ elif array_mask is not None:
+ tile_mask = array_mask[..., qi0:qi1, kj0:kj1]
+ if tile_mask.dtype == mx.bool_:
+ scores = mx.where(tile_mask, scores, _NEG_INF)
+ else:
+ scores = scores + tile_mask.astype(mx.float32)
+
+ tile_max = mx.max(scores, axis=-1, keepdims=True)
+ new_max = mx.maximum(m, tile_max)
+ probabilities = mx.exp(scores - new_max)
+ correction = mx.exp(m - new_max)
+ denom = denom * correction + mx.sum(probabilities, axis=-1, keepdims=True)
+ acc = acc * correction + (probabilities @ vb)
+ m = new_max
+ mx.eval(m, denom, acc)
out_tile = (acc / denom).astype(queries.dtype)
mx.eval(out_tile)
out_q_tiles.append(out_tile)
out = mx.concatenate(out_q_tiles, axis=3)
- return out.reshape(batch, n_q, q_len, head_dim)
+ return out.reshape(batch, n_q, q_len, value_dim)
+
+
+def _flash_sdpa256(queries, keys, values, scale, mask, sinks=None):
+ """Use MLX 0.32.2 native fused SDPA on Metal, portable tiling elsewhere.
+
+ Explicit array masks never take the native fused call: MLX's fused
+ array-mask support is unproven and may silently fall back to the
+ unfused fp32 score matrix, which is exactly the O(L^2) spike this patch
+ exists to bound. The array-tiled implementation already handles bool and
+ additive masks, so route them there directly."""
+ if isinstance(mask, mx.array):
+ return _array_tiled_sdpa256(queries, keys, values, scale, mask, sinks)
+ native_shape = values.shape[-1] == HEAD_DIM and not (
+ isinstance(mask, str)
+ and mask == "causal"
+ and queries.shape[-2] > keys.shape[-2]
+ )
+ if mx.metal.is_available() and native_shape:
+ return mx.fast.scaled_dot_product_attention(
+ queries,
+ keys,
+ values,
+ scale=scale,
+ mask=mask,
+ sinks=sinks,
+ force_fused=True,
+ )
+ return _array_tiled_sdpa256(queries, keys, values, scale, mask, sinks)
def _should_route(queries, keys, cache, mask, sinks) -> bool:
@@ -241,14 +305,16 @@ def _should_route(queries, keys, cache, mask, sinks) -> bool:
return False
if keys.shape[-2] < _SDPA256_MIN_KV_LEN:
return False
- if sinks is not None:
- return False
# Quantized KV cache (TurboQuant etc.): keys/values are packed state,
# not plain [.., kv, hd] arrays. MLX's own dispatcher detects this via
# hasattr(cache, "bits"); let the quant-aware path handle it.
if cache is not None and hasattr(cache, "bits"):
return False
- if not (mask is None or (isinstance(mask, str) and mask == "causal")):
+ if not (
+ mask is None
+ or (isinstance(mask, str) and mask == "causal")
+ or (isinstance(mask, mx.array) and 1 <= mask.ndim <= 4)
+ ):
return False
n_q = queries.shape[-3]
n_kv = keys.shape[-3]
@@ -259,6 +325,26 @@ def _should_route(queries, keys, cache, mask, sinks) -> bool:
return False
+def _register_bounded_route(min_kv_len: int) -> bool:
+ """Publish only a runtime guarantee that is actually enabled."""
+ if _FORCE_TILED is False:
+ return False
+ try:
+ from .. import memory_monitor
+
+ memory_monitor.register_tiled_prefill_head_dim(
+ HEAD_DIM,
+ min_query_len=_SDPA256_MIN_Q_LEN,
+ min_kv_len=min_kv_len,
+ kv_tile=_KV_TILE,
+ supports_array_mask=True,
+ )
+ except Exception:
+ logger.debug("could not register sdpa256 with memory_monitor", exc_info=True)
+ return False
+ return True
+
+
def apply_sdpa256_attention_patch(min_kv_len: int = _SDPA256_MIN_KV_LEN) -> bool:
"""Monkey-patch mlx-lm's scaled_dot_product_attention for head_dim=256
long-context prefill, and register the O(L) cost with the memory monitor."""
@@ -285,13 +371,7 @@ def patched_sdpa(
sinks: mx.array | None = None,
) -> mx.array:
if _should_route(queries, keys, cache, mask, sinks):
- try:
- return _flash_sdpa256(queries, keys, values, scale, mask)
- except Exception:
- logger.warning(
- "sdpa256 prefill kernel failed; falling back to MLX SDPA",
- exc_info=True,
- )
+ return _flash_sdpa256(queries, keys, values, scale, mask, sinks)
return original_sdpa(queries, keys, values, cache, scale, mask, sinks)
mlx_base.scaled_dot_product_attention = patched_sdpa
@@ -336,14 +416,7 @@ def patched_vlm_sdpa(
sinks=None,
) -> mx.array:
if _should_route(queries, keys, cache, mask, sinks):
- try:
- return _flash_sdpa256(queries, keys, values, scale, mask)
- except Exception:
- logger.warning(
- "sdpa256 prefill kernel failed; falling back to "
- "MLX SDPA",
- exc_info=True,
- )
+ return _flash_sdpa256(queries, keys, values, scale, mask, sinks)
return original_vlm_sdpa(
queries, keys, values, cache, scale, mask, sinks
)
@@ -359,23 +432,18 @@ def patched_vlm_sdpa(
mod.scaled_dot_product_attention = patched_vlm_sdpa
# Keep the prefill memory guard in lockstep: tell the monitor head_dim 256
- # prefill is now O(L), so it stops charging the O(L^2) score matrix.
- try:
- from .. import memory_monitor
-
- memory_monitor.register_tiled_prefill_head_dim(
- HEAD_DIM, min_kv_len=min_kv_len, kv_tile=_KV_TILE
- )
- except Exception:
- logger.debug("could not register sdpa256 with memory_monitor", exc_info=True)
+ # prefill is now O(L), so it stops charging the O(L^2) score matrix. The
+ # explicit benchmark override disables this guarantee, so registering it
+ # in that mode would under-estimate the same unfused path the user forced.
+ _register_bounded_route(min_kv_len)
_PATCHED = True
if _FORCE_TILED is None:
- routing = "tiled only when unfused exceeds guard headroom"
+ routing = "force bounded when unfused exceeds guard headroom"
elif _FORCE_TILED:
- routing = "always tiled (OMLX_SDPA256_TILED=1)"
+ routing = "always force bounded (OMLX_SDPA256_TILED=1)"
else:
- routing = "never tiled (OMLX_SDPA256_TILED=0)"
+ routing = "never force bounded (OMLX_SDPA256_TILED=0)"
logger.info(
"sdpa256 attention patch applied (head_dim=256 prefill, kv_len>=%d, %s)",
min_kv_len,
diff --git a/omlx/patches/turboquant_attention.py b/omlx/patches/turboquant_attention.py
index 40a92df91f..ca911a904c 100644
--- a/omlx/patches/turboquant_attention.py
+++ b/omlx/patches/turboquant_attention.py
@@ -9,8 +9,8 @@
are folded into the GQA repeat dimension so the codecs' decode kernels
apply, with the causal tail mask injected between key scoring and the
value weighted sum — one lazy pass over the KV, no dequantize
- - Prefill (L>1): cache.prefill_attention() fast path, fallback to
- dequantize + mx.fast.scaled_dot_product_attention
+ - Prefill (L>1): tiled quantized attention first for long contexts;
+ cache.prefill_attention() first for short contexts; then dequantized SDPA
"""
import logging
@@ -606,25 +606,16 @@ def patched_sdpa(
"falling back to prefill paths",
exc_info=True,
)
- # Prefill: try quantized fast path, fallback to dequantize+SDPA
- result = real_cache.prefill_attention(
- queries,
- keys_state=keys,
- values_state=values,
- scale=scale,
- mask=mask,
- )
- if result is not None:
- return result
keys_state = getattr(keys, "_state", keys)
try:
total_tokens = _state_length(keys_state)
except Exception:
total_tokens = 0
- if (
+ use_tiled_first = (
total_tokens > _LONG_PREFILL_QUANTIZED_THRESHOLD
and hasattr(real_cache, "quantized_attention")
- ):
+ )
+ if use_tiled_first:
old_query_block_size = getattr(
real_cache, "prefill_query_block_size", None
)
@@ -646,7 +637,7 @@ def patched_sdpa(
except Exception:
logger.debug(
"TurboQuant quantized prefill attention failed; "
- "falling back to dequantize+SDPA",
+ "falling back to prefill_attention / dequantize+SDPA",
exc_info=True,
)
finally:
@@ -654,7 +645,19 @@ def patched_sdpa(
real_cache.prefill_query_block_size = old_query_block_size
if old_key_chunk_size is not None:
real_cache.prefill_key_chunk_size = old_key_chunk_size
- dequantized_keys, dequantized_values = real_cache.dequantize()
+ result = real_cache.prefill_attention(
+ queries,
+ keys_state=keys,
+ values_state=values,
+ scale=scale,
+ mask=mask,
+ )
+ if result is not None:
+ return result
+ dequantized_keys, dequantized_values = real_cache.dequantize(
+ keys_state=keys,
+ values_state=values,
+ )
return mx.fast.scaled_dot_product_attention(
queries,
dequantized_keys.astype(queries.dtype),
diff --git a/omlx/patches/virtual_tensors.py b/omlx/patches/virtual_tensors.py
index 65bd94739d..c62d1891b2 100644
--- a/omlx/patches/virtual_tensors.py
+++ b/omlx/patches/virtual_tensors.py
@@ -36,9 +36,12 @@ def register_virtual_tensors(index, config) -> int:
quantized silently.
"""
from .mimo_v2.virtual_qkv import register as register_mimo_v2_qkv
+ from .mlx_vlm_qwen4_exp_compat.virtual_ple import (
+ register as register_qwen4_exp_ple,
+ )
# Import errors are deliberately not caught. A registrar that fails to
# load leaves its checkpoint in the layout the quantizer cannot read, so
# swallowing that would turn a packaging fault into a silently wrong
# quantization.
- return register_mimo_v2_qkv(index, config)
+ return register_mimo_v2_qkv(index, config) + register_qwen4_exp_ple(index, config)
diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py
index c745072428..1a95dba041 100644
--- a/omlx/prefill_transient_tracker.py
+++ b/omlx/prefill_transient_tracker.py
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
"""
-Per-scheduler EWMA of bytes-per-prefill-token.
+Per-scheduler prefill memory observations.
Used by the adaptive prefill throttle in Scheduler: when current memory
enters the caution zone (>= hard_cap * safe_zone_ratio), the next chunk
@@ -13,16 +13,27 @@
from __future__ import annotations
import logging
+from dataclasses import dataclass
logger = logging.getLogger(__name__)
+@dataclass
+class _TransientHistory:
+ ewma_per_token: float = 0.0
+ samples: int = 0
+ last_delta_bytes: int = 0
+ last_n_tokens: int = 0
+ observed_max_bytes: int = 0
+ flat_overhead_bytes: int = 0
+ reclaim_debt_bytes: int = 0
+
+
class PrefillTransientTracker:
- """EWMA estimator of MLX prefill chunk transient bytes per token.
+ """Keep separate gathered and dense observations for one loaded model.
- Updated post-chunk from `phys_footprint()` deltas. The first chunk
- has no measurement yet — callers fall back to a static estimate
- (MemoryMonitor.estimate_prefill_peak_bytes) until samples > 0.
+ Generic models use token-linear EWMA estimates. Qwen4 uses its static
+ profile plus observed allocator overhead that must return after a pool release.
"""
_EWMA_ALPHA = 0.3 # weight on the most recent chunk
@@ -44,24 +55,20 @@ class PrefillTransientTracker:
# above the largest observed legitimate fluctuation and below the
# observed outlier.
_EWMA_OUTLIER_RATIO = 8.0
+ _FLAT_OVERHEAD_NOISE_BYTES = 64 * 1024**2
def __init__(self, model_id: str = "") -> None:
self._model_id = model_id
- self._ewma_per_token: float = 0.0
- self._samples: int = 0
- # Last observed delta for debug log inspection.
- self._last_delta_bytes: int = 0
- self._last_n_tokens: int = 0
- # Largest floor-size chunk transient seen this session: a stable
- # flat bound for admission and the pre-chunk guard's pass/abort
- # gates, matching the floor-chunk charge they price. Never used
- # for chunk sizing.
- self._observed_max_bytes: int = 0
+ self._dense_history = _TransientHistory()
+ self._gathered_history = _TransientHistory()
# Net process footprint released by negative post-chunk deltas. MLX may
# need to allocate that pool again on the next chunk, so the scheduler
# prices it once until a positive measurement confirms reallocation.
self._recent_reclaim_bytes: int = 0
+ def _history(self, gathered_core: bool) -> _TransientHistory:
+ return self._gathered_history if gathered_core is True else self._dense_history
+
def record_reclaim(self, reclaimed_bytes: int) -> None:
"""Accumulate footprint released since the last positive sample."""
if reclaimed_bytes > 0:
@@ -78,7 +85,12 @@ def clear_reclaim(self) -> None:
self._recent_reclaim_bytes = 0
def update(
- self, n_tokens: int, transient_bytes: int, *, floor_sample: bool = False
+ self,
+ n_tokens: int,
+ transient_bytes: int,
+ *,
+ floor_sample: bool = False,
+ gathered_core: bool = False,
) -> None:
"""Record one chunk observation.
@@ -108,13 +120,16 @@ def update(
self._recent_reclaim_bytes = 0
- # The very first sample after a model load carries weight page-fault
- # and load-residue noise, so it seeds the EWMA but is excluded from
- # the running max.
- if floor_sample and self._samples > 0:
+ history = self._history(gathered_core)
+
+ # The very first sample in each execution regime carries weight
+ # page-fault and load-residue noise, so it seeds that regime's EWMA
+ # but is excluded from its running max.
+ if floor_sample and history.samples > 0:
if transient_bytes <= self._OBSERVED_MAX_CLAMP_BYTES:
- if transient_bytes > self._observed_max_bytes:
- self._observed_max_bytes = transient_bytes
+ history.observed_max_bytes = max(
+ history.observed_max_bytes, transient_bytes
+ )
else:
logger.debug(
"PrefillTransientTracker(%s): rejected %d-byte outlier "
@@ -125,9 +140,9 @@ def update(
)
per_token = transient_bytes / n_tokens
- if self._samples == 0:
- self._ewma_per_token = per_token
- elif per_token > self._ewma_per_token * self._EWMA_OUTLIER_RATIO:
+ if history.samples == 0:
+ history.ewma_per_token = per_token
+ elif per_token > history.ewma_per_token * self._EWMA_OUTLIER_RATIO:
# Reject from the EWMA blend: a single sample this far above
# the running rate is more likely a noisy phys_footprint()
# delta (see _record_chunk_transient's docstring on
@@ -139,63 +154,152 @@ def update(
"outlier from EWMA (current %.1f, ratio limit %.1fx)",
self._model_id,
per_token,
- self._ewma_per_token,
+ history.ewma_per_token,
self._EWMA_OUTLIER_RATIO,
)
else:
- self._ewma_per_token = (
+ history.ewma_per_token = (
self._EWMA_ALPHA * per_token
- + (1.0 - self._EWMA_ALPHA) * self._ewma_per_token
+ + (1.0 - self._EWMA_ALPHA) * history.ewma_per_token
)
- self._samples += 1
- self._last_delta_bytes = transient_bytes
- self._last_n_tokens = n_tokens
+ history.samples += 1
+ history.last_delta_bytes = transient_bytes
+ history.last_n_tokens = n_tokens
+
+ def observe_flat_overhead(
+ self,
+ n_tokens: int,
+ delta_bytes: int,
+ *,
+ static_bytes: int,
+ gathered_core: bool = False,
+ representative: bool = True,
+ ) -> None:
+ """Track Qwen4 process-footprint noise as flat, never per-token work."""
+ if n_tokens <= 0:
+ return
+ history = self._history(gathered_core)
+ noise = max(self._FLAT_OVERHEAD_NOISE_BYTES, max(0, static_bytes) // 10)
+ if delta_bytes < -noise:
+ history.reclaim_debt_bytes += -delta_bytes
+ return
+
+ # A positive delta first repays a preceding pool release. Only net-new
+ # growth beyond both that repayment and the static profile is overhead.
+ reallocated = min(history.reclaim_debt_bytes, max(0, delta_bytes))
+ history.reclaim_debt_bytes -= reallocated
+ residual = delta_bytes - reallocated - max(0, static_bytes)
+ if residual <= noise or not representative:
+ return
+ history.flat_overhead_bytes = max(history.flat_overhead_bytes, residual)
+ history.samples += 1
+ history.last_delta_bytes = delta_bytes
+ history.last_n_tokens = n_tokens
+
+ def flat_overhead_bytes_for(self, gathered_core: bool) -> int:
+ return self._history(gathered_core).flat_overhead_bytes
+
+ def reclaim_debt_bytes_for(self, gathered_core: bool) -> int:
+ return self._history(gathered_core).reclaim_debt_bytes
- def predict(self, n_tokens: int, *, safety_factor: float = 1.2) -> int:
+ def record_flat_reclaim(self, reclaimed_bytes: int) -> None:
+ """Record a process-wide pool release against each route's own overhead.
+
+ A cache clear can release buffers from either route, regardless of the
+ request that triggered it. Each route is bounded by its own observed
+ overhead; dense observations never increase the gathered prediction.
+ """
+ if reclaimed_bytes <= 0:
+ return
+ for history in (self._dense_history, self._gathered_history):
+ history.reclaim_debt_bytes = min(
+ history.flat_overhead_bytes,
+ history.reclaim_debt_bytes + int(reclaimed_bytes),
+ )
+
+ def flat_overhead_charge_for(self, gathered_core: bool) -> int:
+ history = self._history(gathered_core)
+ # Retained pool growth is already present in the scheduler's current
+ # physical-footprint reading. Charging it again double-counts it.
+ # Only the portion actually reclaimed can be reallocated next chunk.
+ return min(history.flat_overhead_bytes, history.reclaim_debt_bytes)
+
+ def predict(
+ self,
+ n_tokens: int,
+ *,
+ safety_factor: float = 1.2,
+ gathered_core: bool = False,
+ ) -> int:
"""Predicted transient bytes for a chunk of `n_tokens`.
Returns 0 when no samples have been observed yet — caller must
fall back to a static estimator in that case.
"""
- if self._samples == 0 or n_tokens <= 0:
+ samples = self.samples_for(gathered_core)
+ if samples == 0 or n_tokens <= 0:
return 0
- return int(self._ewma_per_token * n_tokens * safety_factor)
+ return int(self.bytes_per_token_for(gathered_core) * n_tokens * safety_factor)
+
+ def bytes_per_token_for(self, gathered_core: bool) -> float:
+ """Return the EWMA for the selected execution regime."""
+ return self._history(gathered_core).ewma_per_token
+
+ def samples_for(self, gathered_core: bool) -> int:
+ """Return the sample count for the selected execution regime."""
+ return self._history(gathered_core).samples
+
+ def last_delta_bytes_for(self, gathered_core: bool) -> int:
+ """Return the latest measured delta for the selected regime."""
+ return self._history(gathered_core).last_delta_bytes
+
+ def last_n_tokens_for(self, gathered_core: bool) -> int:
+ """Return the latest measured width for the selected regime."""
+ return self._history(gathered_core).last_n_tokens
+
+ def observed_max_bytes_for(self, gathered_core: bool) -> int:
+ """Return the floor-size maximum for the selected regime."""
+ return self._history(gathered_core).observed_max_bytes
@property
def bytes_per_token(self) -> float:
"""Current EWMA value (bytes per prefill token). 0.0 if no samples."""
- return self._ewma_per_token
+ return self._dense_history.ewma_per_token
@property
def samples(self) -> int:
"""Number of chunks recorded since last reset."""
- return self._samples
+ return self._dense_history.samples
@property
def last_delta_bytes(self) -> int:
"""Bytes added by the most recently measured chunk."""
- return self._last_delta_bytes
+ return self._dense_history.last_delta_bytes
@property
def last_n_tokens(self) -> int:
"""Token count of the most recently measured chunk."""
- return self._last_n_tokens
+ return self._dense_history.last_n_tokens
@property
def observed_max_bytes(self) -> int:
"""Largest accepted chunk transient this session (0 if none yet)."""
- return self._observed_max_bytes
+ return self._dense_history.observed_max_bytes
@property
def recent_reclaim_bytes(self) -> int:
"""Footprint released since the last positive chunk measurement."""
return self._recent_reclaim_bytes
+ def reset_history(self, *, gathered_core: bool = False) -> None:
+ """Drop observations for one execution regime."""
+ if gathered_core:
+ self._gathered_history = _TransientHistory()
+ else:
+ self._dense_history = _TransientHistory()
+
def reset(self) -> None:
"""Drop all observations (e.g. on model reload or after a long idle)."""
- self._ewma_per_token = 0.0
- self._samples = 0
- self._last_delta_bytes = 0
- self._last_n_tokens = 0
- self._observed_max_bytes = 0
+ self.reset_history()
+ self.reset_history(gathered_core=True)
self._recent_reclaim_bytes = 0
diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py
index f99f6bce33..3a90ee1a0e 100644
--- a/omlx/process_memory_enforcer.py
+++ b/omlx/process_memory_enforcer.py
@@ -183,7 +183,6 @@ def get_effective_metal_cap_bytes() -> int:
return sysctl_cap
return _get_max_metal_working_set_bytes()
-
def _wired_limit_suggestion_bytes(desired_bytes: int) -> int:
"""Clamp and align a wired-limit recommendation to leave 5% of RAM.
@@ -708,6 +707,28 @@ def get_admission_ceiling(self) -> int:
return self._get_hard_limit_bytes()
return self._get_static_ceiling()
+ def get_residency_ceiling(self) -> int:
+ """Stable ceiling for *where weights live*, not for admitting a load.
+
+ Admission must respect memory free right now — overcommitting thrashes
+ the machine. Choosing whether a model's PLE table stays resident or
+ falls back to mmap is a throughput call, and the instantaneous ceiling
+ is actively wrong for it: engine_pool asks right after the previous
+ model unloaded, before the OS has returned its pages, so ``dynamic``
+ dips and a table that fits gets pushed to SSD for the rest of that
+ engine's life. Measured on a model swap here: 35.3 -> 14.1 tok/s.
+
+ Uses only the two components that don't move with instantaneous
+ pressure. Returns 0 when the guard is off, like the other accessors.
+ """
+ breakdown = self._get_ceiling_breakdown()
+ candidates = [
+ value
+ for value in (breakdown["static"], breakdown["metal_cap"])
+ if value > 0
+ ]
+ return min(candidates) if candidates else 0
+
def get_admission_soft_target(self) -> int:
"""Soft watermark that pre-load admission evicts down to (#2319).
diff --git a/omlx/scheduler.py b/omlx/scheduler.py
index d22f4f4dd5..d22b6af312 100644
--- a/omlx/scheduler.py
+++ b/omlx/scheduler.py
@@ -47,17 +47,17 @@
)
from mlx_lm.sample_utils import make_logits_processors
-from .cache.observability import CacheRateTracker
+from .cache.observability import BoundarySnapshotDiagnostics, CacheRateTracker
from .cache.paged_cache import PagedCacheManager
from .cache.pooling_delta import compact_pooling_cache_snapshot
from .cache.prefix_cache import BlockAwarePrefixCache, cachelist_pm_member_plan
+from .decode_activity import get_decode_activity
from .exceptions import (
PrefillMemoryExceededError,
describe_ceiling_binding,
is_cache_corruption_error,
)
from .patches.sdpa256_attention import set_unfused_headroom_provider
-from .decode_activity import get_decode_activity
from .prefill_progress import get_prefill_tracker
from .prefill_transient_tracker import PrefillTransientTracker
from .request import Request, RequestOutput, RequestStatus, SamplingParams
@@ -77,6 +77,7 @@
_default_generation_stream,
_mx_buffer_access_lock,
_sync_and_clear_cache,
+ clear_thread_streams,
)
from .utils.proc_memory import get_phys_footprint
from .utils.sampling import make_sampler as omlx_make_sampler
@@ -358,6 +359,7 @@ def has_capacity(self) -> bool:
MemoryMonitor,
collect_kv_layer_specs,
estimate_mla_kv_bytes_per_token,
+ estimate_qwen4_exp_kv_bytes_per_token,
make_prefill_memory_profile,
)
@@ -368,6 +370,7 @@ def has_capacity(self) -> bool:
MemoryMonitor = None
collect_kv_layer_specs = None
estimate_mla_kv_bytes_per_token = None
+ estimate_qwen4_exp_kv_bytes_per_token = None
make_prefill_memory_profile = None
HAS_TIERED_CACHE = False
@@ -489,6 +492,7 @@ class _PrefillState:
sampler: Any = None
sm: Any = None
per_row_lps: Any = None
+ qwen4_gathered_core: bool | None = None
@dataclass
@@ -921,11 +925,54 @@ def _turboquant_filter_singleton(self, batch_indices):
_TQ_SINGLETON_CACHE_TYPE.extend = _regular_cache_extend_singleton
_mlx_lm_generate_module = importlib.import_module("mlx_lm.generate")
+_original_make_cache = _mlx_lm_generate_module._make_cache
_original_merge_caches = _mlx_lm_generate_module._merge_caches
_original_ppb_split = PromptProcessingBatch.split
_REGULAR_SINGLETON_CACHE_TYPES = (_MLXKVCache, _MLXRotatingKVCache)
+def _patched_make_cache(model, left_padding, max_kv_size):
+ """Honor model-owned batch conversion before MLX-LM's fallbacks."""
+ if not hasattr(model, "make_cache"):
+ return _original_make_cache(model, left_padding, max_kv_size)
+
+ model_cache = model.make_cache()
+
+ def has_model_owned_conversion(cache_obj):
+ if callable(getattr(cache_obj, "to_batch", None)):
+ return True
+ sub_caches = getattr(cache_obj, "caches", None)
+ return isinstance(sub_caches, (list, tuple)) and any(
+ has_model_owned_conversion(child) for child in sub_caches
+ )
+
+ class _SingleCacheModel:
+ layers = (None,)
+
+ def __init__(self, cache_obj):
+ self.cache_obj = cache_obj
+
+ def make_cache(self):
+ return [self.cache_obj]
+
+ def convert(cache_obj):
+ to_batch = getattr(cache_obj, "to_batch", None)
+ if callable(to_batch):
+ return to_batch(left_padding)
+
+ sub_caches = getattr(cache_obj, "caches", None)
+ if isinstance(sub_caches, (list, tuple)) and any(
+ has_model_owned_conversion(child) for child in sub_caches
+ ):
+ return type(cache_obj)(*(convert(child) for child in sub_caches))
+
+ return _original_make_cache(
+ _SingleCacheModel(cache_obj), left_padding, max_kv_size
+ )[0]
+
+ return [convert(cache_obj) for cache_obj in model_cache]
+
+
def _cache_layer_supports_singleton_passthrough(cache_obj: Any) -> bool:
sub_caches = getattr(cache_obj, "caches", None)
if isinstance(sub_caches, (list, tuple)):
@@ -947,6 +994,13 @@ def _to_batched_cache_layer(cache_obj: Any) -> Any:
and type(cache_obj) is _TQ_SINGLETON_CACHE_TYPE
):
return cache_obj.merge([cache_obj])
+ # Model-owned singletons (e.g. qwen4_exp QSAKVCache) declare their batch
+ # conversion via to_batch, which _patched_make_cache honors at creation;
+ # honor it on the continuous-batching join path too, or extend() hits a
+ # singleton without the method. A warm singleton is one unpadded row.
+ to_batch = getattr(cache_obj, "to_batch", None)
+ if callable(to_batch):
+ return to_batch([0])
return cache_obj
@@ -1023,6 +1077,7 @@ def _patched_ppb_split(self, indices):
return _original_ppb_split(self, indices)
+_mlx_lm_generate_module._make_cache = _patched_make_cache
_mlx_lm_generate_module._merge_caches = _patched_merge_caches
_mlx_lm_generate_module._extend_cache = _patched_extend_cache
PromptProcessingBatch.split = _patched_ppb_split
@@ -1178,6 +1233,10 @@ def _patched_ppb_prompt(self, tokens):
"BatchTurboQuantKVCache",
"ChunkedKVCache",
"MiniMaxM3KVCache",
+ # Both QSA handlers support block slicing, so their growing KV and
+ # index state must not be copied into every boundary snapshot.
+ "QSAKVCache",
+ "QSAQuantizedKVCache",
}
)
@@ -1336,6 +1395,26 @@ def _seed_text_only_mrope_delta_for_cached_prefill(model: Any, request: Any) ->
if lm is None or not hasattr(lm, "_rope_deltas"):
return
lm._rope_deltas = mx.zeros((1, 1), dtype=mx.int64)
+ # Keep the restore-only seed concrete before the engine-stream graph uses it.
+ mx.eval(lm._rope_deltas)
+
+
+def _bind_text_prefill_rope_delta(model: Any, delta: float) -> None:
+ """Rebind one non-media prefill row without widening Qwen4 positions.
+
+ ``VLMModelAdapter`` exposes a dedicated seam that records the scheduler's
+ text-only proof. Other model wrappers retain the original generic mRoPE
+ binder. Looking up the dedicated method on the class avoids treating an
+ auto-created ``MagicMock`` instance attribute as a production capability.
+ """
+
+ text_setter = getattr(type(model), "set_text_prefill_rope_delta", None)
+ if callable(text_setter):
+ text_setter(model, delta)
+ return
+ generic_setter = getattr(model, "set_batch_rope_deltas", None)
+ if callable(generic_setter):
+ generic_setter(mx.array([delta]))
def _vlm_extra_seq_slice(val: mx.array, s: slice) -> mx.array:
@@ -1919,17 +1998,12 @@ def __init__(
self._prefill_transient_tracker = PrefillTransientTracker(
model_id=_tracker_model_id
)
+ self._sdpa256_bounded_route_active: bool | None = None
# One-shot probe of the GDN/Mamba fixed recurrent-state footprint,
# armed by _set_model_info_for_monitor when ArraysCache layers exist
# and taken after the first prefill chunk's eval.
self._fixed_state_measure_armed: bool = False
self._fixed_state_recorded: bool = False
- # Let the sdpa256 head_dim-256 prefill route ask for live guard
- # headroom so it only takes the slow O(L) tiled pass when the faster
- # unfused fallback would not fit (issue #2204). Weakly held; harmless
- # when the patch is never applied.
- set_unfused_headroom_provider(self._sdpa256_unfused_headroom)
-
# SpecPrefill: draft model for attention-based sparse prefill
self._specprefill_draft_model: Any | None = None
self._draft_paged_ssd_cache_manager: Any | None = None
@@ -1944,8 +2018,21 @@ def __init__(
# can log their divergence point at INFO (#2333).
self._cache_probe_seqs: deque[tuple[str, array | list[int]]] = deque(maxlen=4)
+ # Hybrid models whose recurrent state is REBOUND per decode step
+ # (ArraysCache/SizedArraysCache: MiniMax, Qwen3.5-Next, GLM-5.3, ...)
+ # never materialize those states through mx.async_eval alone. The
+ # unevaluated per-step chain pins every intermediate Metal buffer,
+ # and the allocator's per-process resource count (499,000 buffers)
+ # is exhausted long before any byte limit — the
+ # "[metal::malloc] Resource limit (499000) exceeded" failure (#3226).
+ # Periodic materialization collapses the chain; enable it for every
+ # ArraysCache hybrid, not just MiniMax.
model_name_lower = (self.config.model_name or "").lower()
- default_kv_eval_interval = 256 if "minimax" in model_name_lower else 0
+ default_kv_eval_interval = (
+ 256
+ if "minimax" in model_name_lower or self._model_has_arrays_cache()
+ else 0
+ )
self._decode_eval_kv_cache_interval: int = max(
0,
_env_int(
@@ -2015,12 +2102,14 @@ def __init__(
self._boundary_snapshot_required: bool | None = None
# SSD store for offloading boundary snapshots (initialized in _init_tiered_cache).
self._boundary_snapshot_store: BoundarySnapshotSSDStore | None = None
+ self._boundary_snapshot_diagnostics = BoundarySnapshotDiagnostics()
# paged SSD cache for KV state persistence (oMLX only supports paged SSD-based caching)
self.paged_cache_manager: PagedCacheManager | None = None
self.block_aware_cache: BlockAwarePrefixCache | None = None
self.paged_ssd_cache_manager: PagedSSDCacheManager | None = None
self._cache_rate_tracker = CacheRateTracker()
+ self._last_prefix_cache_lookup: dict[str, Any] | None = None
# Prefill-peak estimator used by ``_preflight_memory_check`` /
# ``preflight_or_raise``. Only the estimator path is exercised
# here (it reads head_dim / num_layers / num_kv_heads via
@@ -2239,9 +2328,18 @@ def _periodic_clear_threshold_bytes(self) -> int:
the entire MLX buffer pool in one batch; gating it on accumulated
bytes avoids producing IOGPUFamily refcount bursts when the pool
is already small.
+
+ The memory_limit/3 term is additionally capped at 16 GiB: on
+ large-memory machines (soft limit ~438 GB on a 512 GB Studio) an
+ uncapped threshold (~146 GB) meant the periodic clear effectively
+ never fired, letting the pool hoard buffer *handles* against the
+ Metal per-process resource count even while byte usage stayed
+ modest (#3226).
"""
+ cap = 16 * 1024**3
if self._memory_limit_bytes > 0:
- return max(self._memory_limit_bytes // 3, 2 * 1024**3)
+ return min(max(self._memory_limit_bytes // 3, 2 * 1024**3), cap)
+
return 2 * 1024**3
def _should_periodic_clear_cache(self) -> bool:
@@ -2640,22 +2738,29 @@ def _align_block_size_with_rotating_window(self) -> None:
self.config.paged_cache_block_size = target_block_size
def _detect_qwen35_prefill_floor(self) -> int:
- """Return the wide-prefill floor for the Qwen3.5 architecture family."""
+ """Return the wide-prefill floor for Qwen hybrid architectures."""
try:
model_type = str(getattr(self.model, "model_type", "") or "")
if not model_type:
model_type = str(
getattr(getattr(self.model, "config", None), "model_type", "") or ""
)
- if model_type.startswith("qwen3_5"):
+ is_qwen35 = model_type.startswith("qwen3_5")
+ is_qwen4 = model_type.startswith("qwen4_exp")
+ if is_qwen4:
+ from .custom_kernels.glm_moe_dsa import fast
+
+ if not fast.is_native_available() or not fast.has_symbol(
+ "qwen4_qsa_sparse_gqa_attention"
+ ):
+ return 0
+ if is_qwen35 or is_qwen4:
from .custom_kernels.nax import is_nax_available
from .settings import get_system_memory
if get_system_memory() >= 64 * 1024**3 and not is_nax_available():
- # Measured on the 27B (M3 Ultra, 2026-08-17): chunk 4096
- # beats the 2048 default +3.2% at 4k prompts / +1.0% at
- # 16k; 8192 is flat versus 4096. Keep 2048 on NAX/M5,
- # where wider prefill regresses throughput (#2880).
+ # Qwen4 needs its sparse native path before wider chunks
+ # are safe. NAX/M5 stays at 2048 for both model families.
return 4096
except Exception:
logger.debug("qwen3_5 prefill floor probe failed", exc_info=True)
@@ -2722,6 +2827,21 @@ def _enlarge_block_size_for_arrays_cache(self) -> None:
)
self.config.paged_cache_block_size = target
+ def _model_has_arrays_cache(self) -> bool:
+ """Whether the model's cache layout contains ArraysCache layers."""
+ if not hasattr(self.model, "make_cache"):
+ return False
+ try:
+ cache_list = self.model.make_cache()
+ except Exception:
+ return False
+ if not cache_list:
+ return False
+
+ return any(
+ self._cache_tree_has_arrays_cache(cache_obj) for cache_obj in cache_list
+ )
+
@staticmethod
def _cache_tree_has_arrays_cache(cache_obj: Any) -> bool:
"""Return True if cache_obj contains ArraysCache (recursively)."""
@@ -3293,6 +3413,34 @@ def _apply_turboquant_kv_convert(self, prompt_cache: list[Any]) -> None:
f"cache layers to {bits}-bit{skip_msg}"
)
+ def _qwen4_prefill_accounting_enabled(self) -> bool:
+ monitor = getattr(self, "memory_monitor", None)
+ checker = getattr(monitor, "is_qwen4_gathered_prefill_profile", None)
+ return callable(checker) and checker() is True
+
+ def _qwen4_text_gathered_pricing(self, text_only: bool) -> bool:
+ """True when this engine can price Qwen4 text prefill as gathered QSA.
+
+ Callers that do not know whether the request is text-only must pass
+ False. Preflight and prefill then share an argument instead of a
+ mutable flag on the shared monitor.
+ """
+ return text_only is True and Scheduler._qwen4_prefill_accounting_enabled(self)
+
+ @staticmethod
+ def _qwen4_actual_gathered_pricing(
+ cache: list[Any], predicted: bool
+ ) -> bool:
+ """Return the QSA route that the just-finished chunk actually used."""
+ routes = [
+ route
+ for item in cache
+ if isinstance(
+ route := getattr(item, "_omlx_last_prefill_gathered", None), bool
+ )
+ ]
+ return all(routes) if routes else predicted
+
def _do_external_prefill(
self,
request: "Request",
@@ -3322,6 +3470,7 @@ def _do_external_prefill(
RuntimeError: If memory limit exceeded during prefill.
"""
n_tokens = len(tokens)
+ gathered_core = self._qwen4_text_gathered_pricing(vlm_embeds is None)
if n_tokens <= 1:
# Nothing to prefill, return cache + tokens as-is.
cache = existing_cache or make_prompt_cache(self.model)
@@ -3391,9 +3540,18 @@ def _do_external_prefill(
extra_kwargs: dict[str, Any] | None = None
if vlm_embeds is not None:
embeds_array, extra_kwargs, start_offset = vlm_embeds
- embeds_array = embeds_array[:, start_offset:] # skip cached portion
- if start_offset > 0 and extra_kwargs:
- extra_kwargs = _advance_vlm_extra(extra_kwargs, start_offset)
+ # Build the restored-prefix views on the engine stream. A
+ # worker-default-stream slice here sits at the head of the chunk
+ # graph, so MLX bridges it with a cross-stream fence whose
+ # producer buffer is only committed at the end of the eval. The
+ # Qwen ANE prefill primitive commits and waits on the engine
+ # stream buffer mid-eval, so that fence can never be satisfied
+ # and the driver times the buffer out (#3305). Fresh prefills
+ # never hit this: a full-range slice is a no-op in MLX.
+ with mx.stream(self._stream):
+ embeds_array = embeds_array[:, start_offset:] # skip cached portion
+ if start_offset > 0 and extra_kwargs:
+ extra_kwargs = _advance_vlm_extra(extra_kwargs, start_offset)
# Force _position_ids path in language model for cached VLM
# prefill. Without this, the delta approach gives sequential
# positions to image tokens that need 3D mRoPE positions.
@@ -3428,6 +3586,12 @@ def _do_external_prefill(
emitted_boundaries: dict[int, int] = {}
+ # The full prompt length is known here; hand it to the QSA indexer so
+ # its arrays are sized once instead of doubling mid-prefill.
+ self._reserve_qsa_index_capacity(
+ prompt_cache, _cache_base_sizes(prompt_cache) + n_tokens
+ )
+
while input_arr.shape[1] > 0:
_trace_chunk_start = time.perf_counter()
_trace_processed_before = processed_tokens
@@ -3438,7 +3602,7 @@ def _do_external_prefill(
n_to_process = min(prefill_step_size, remaining)
if processed_tokens == 0:
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
# Boundary-limited step size
if boundary_enabled and block_size > 0:
@@ -3450,30 +3614,35 @@ def _do_external_prefill(
n_to_process = min(n_to_process, delta)
n_to_process = max(1, n_to_process)
- # Adaptive throttle: shrink chunk when entering the caution zone
- # so the hard cap is honored before the chunk-end check. Raises
- # RuntimeError if the min chunk would exceed the cap — the
- # #1405 cleanup path catches it and emits an error to the client.
- n_to_process = self._adaptive_chunk_size(
- n_to_process,
- request_id=request.request_id,
- loop_label="external",
- kv_len=base_size + processed_tokens,
- )
+ try:
+ n_to_process = self._adaptive_chunk_size(
+ n_to_process,
+ request_id=request.request_id,
+ loop_label="external",
+ kv_len=base_size + processed_tokens,
+ gathered_core=gathered_core,
+ )
+ # Check the predicted peak before submitting work to Metal.
+ n_to_process = self._guard_prefill_chunk(
+ n_to_process,
+ kv_len=base_size + processed_tokens,
+ progress=processed_tokens,
+ loop_label="external",
+ request_id=request.request_id,
+ gathered_core=gathered_core,
+ )
+ except _PrefillEvictionNeeded:
+ # Keep token progress aligned with the advanced KV on retry.
+ # Cold requests must also retain their locally created cache.
+ if processed_tokens > 0:
+ if existing_cache is None:
+ request.prompt_cache = prompt_cache
+ request.cached_tokens += processed_tokens
+ request.remaining_tokens = tokens[processed_tokens:]
+ raise
- # Pre-chunk safety guard: NEVER submit a chunk whose predicted peak
- # would breach the prefill safety cap. The Metal command-buffer
- # OOM is an async, uncatchable SIGABRT, so it must be prevented
- # before submission — a post-chunk check is too late. Falls back to
- # min_chunk after a reclaim; raises gracefully only if even the
- # floor can't fit (caught by the #1405 path → requeue/clean error).
- n_to_process = self._guard_prefill_chunk(
- n_to_process,
- kv_len=base_size + processed_tokens,
- progress=processed_tokens,
- loop_label="external",
- request_id=request.request_id,
- )
+ # Keep token and embedding slices aligned at the final prefill chunk.
+ n_to_process = min(n_to_process, remaining)
if getattr(request, "benchmark_trace", False):
request.benchmark_prefill_chunks.append(int(n_to_process))
request.benchmark_requested_steps.append(int(prefill_step_size))
@@ -3492,6 +3661,18 @@ def _do_external_prefill(
_trace_model_start = time.perf_counter()
with mx.stream(self._stream):
model_kwargs: dict[str, Any] = {}
+ if embeds_array is None:
+ # External text prefill is interleaved chunk-by-chunk with
+ # active decode. A finishing VLM row clears the adapter's
+ # process-local position state, and a decode step may leave
+ # a differently shaped batch delta behind. Rebind this
+ # request immediately before every forward so neither
+ # event can make a singleton Qwen mRoPE chunk restart at
+ # local position zero inside an absolute QSA timeline.
+ _bind_text_prefill_rope_delta(
+ self.model,
+ getattr(request, "rope_deltas", 0.0),
+ )
if embeds_array is not None and embeds_array.shape[1] > 0:
model_kwargs["inputs_embeds"] = embeds_array[:, :n_to_process]
if extra_kwargs:
@@ -3513,6 +3694,21 @@ def _do_external_prefill(
extra_kwargs = _advance_vlm_extra(extra_kwargs, n_to_process)
_trace_model_ms = (time.perf_counter() - _trace_model_start) * 1000.0
_throttle_post = get_phys_footprint()
+ if Scheduler._qwen4_prefill_accounting_enabled(self):
+ actual_gathered_core = Scheduler._qwen4_actual_gathered_pricing(
+ prompt_cache, gathered_core
+ )
+ if actual_gathered_core != gathered_core:
+ logger.info(
+ "Qwen4 prefill pricing route corrected after execution: "
+ "rid=%s predicted=%s actual=%s query=%d kv_len=%d",
+ request.request_id,
+ "gathered" if gathered_core else "mask_dense",
+ "gathered" if actual_gathered_core else "mask_dense",
+ n_to_process,
+ base_size + processed_tokens,
+ )
+ gathered_core = actual_gathered_core
self._record_chunk_transient(
n_to_process,
_throttle_pre,
@@ -3521,6 +3717,7 @@ def _do_external_prefill(
loop_label="external",
kv_len=base_size + processed_tokens,
requested_step=prefill_step_size,
+ gathered_core=gathered_core,
)
self._maybe_record_fixed_state_bytes(prompt_cache)
# Enforcer-requested hard-pressure drain. The flag's normal
@@ -3530,7 +3727,7 @@ def _do_external_prefill(
# reclaim request can never land before its abort escalation
# (measured: aborts 0.1GB over the watermark with 3.7GB pooled).
if self._consume_pressure_clear():
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
processed_tokens += n_to_process
@@ -3640,11 +3837,13 @@ def _do_external_prefill(
extra_kwargs = None
model_kwargs = {}
prompt_cache = None
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
raise _PrefillAbortedError(abort_uids, processed_tokens)
# Reclaim Metal intermediates between prefill chunks.
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
+ if vlm_embeds is None:
+ self._accrue_decode_debt(time.perf_counter() - _trace_chunk_start)
if getattr(request, "benchmark_trace", False):
_trace_total_ms = (
time.perf_counter() - _trace_chunk_start
@@ -3691,7 +3890,7 @@ def _do_external_prefill(
request, prompt_cache, total_tokens
)
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
# Restore _rope_deltas after cached VLM prefill (for decode capture)
if vlm_embeds is not None and _saved_rope_deltas is not None:
@@ -3745,20 +3944,15 @@ def _do_external_prefill(
_MEMORY_ADMISSION_STALL_TIMEOUT_S: float = 60.0
_STORE_CACHE_ADMISSION_STALL_TIMEOUT_S: float = 60.0
- def _predicted_chunk_transient(self, n_tokens: int, kv_len: int) -> float:
- """Conservative predicted Metal peak growth for one prefill chunk.
-
- The per-chunk SDPA/MoE transient scales with ``query_len * kv_len``, so
- the per-token cost GROWS with context length. A long-run EWMA average
- lags that growth and underestimates the next chunk — the cause of the
- Metal command-buffer OOM crash at large kv_len. We therefore take the
- MAX of three signals and apply a safety factor:
- - the most recently MEASURED per-token growth (last_delta / last_n)
- — anchored on reality at the current kv_len regime,
- - the long-run EWMA (model-specific constants the static misses),
- - the kv_len-aware static estimate (SDPA transient + this chunk's
- newly allocated KV).
- Returns 0 only when nothing is known (first chunk, no model info).
+ def _predicted_chunk_transient(
+ self, n_tokens: int, kv_len: int, *, gathered_core: bool = False
+ ) -> float:
+ """Predict additional memory needed for the next prefill chunk.
+
+ Generic models use the largest static, EWMA, or last-chunk estimate,
+ including recent reclaim. Qwen4 uses its nonlinear static profile
+ plus observed overhead released from the pool. Retained overhead is
+ already included in current footprint and must not be charged again.
"""
if n_tokens <= 0:
return 0.0
@@ -3766,21 +3960,38 @@ def _predicted_chunk_transient(self, n_tokens: int, kv_len: int) -> float:
static_per_token = 0.0
recent_reclaim = 0
tracker = self._prefill_transient_tracker
- if tracker is not None:
- if tracker.last_n_tokens > 0 and tracker.last_delta_bytes > 0:
- per_token = max(
- per_token, tracker.last_delta_bytes / tracker.last_n_tokens
- )
- if tracker.bytes_per_token > 0:
- per_token = max(per_token, tracker.bytes_per_token)
- recent_reclaim = tracker.recent_reclaim_bytes
if self.memory_monitor is not None:
static = self.memory_monitor.estimate_chunk_transient_bytes(
- n_tokens, kv_len + n_tokens
+ n_tokens,
+ kv_len + n_tokens,
+ gathered_core=gathered_core,
)
static += self.memory_monitor.estimate_prompt_kv_bytes(n_tokens)
static_per_token = float(static) / n_tokens
- per_token = max(per_token, static_per_token)
+ per_token = static_per_token
+ qwen4_flat_overhead = Scheduler._qwen4_prefill_accounting_enabled(self)
+ if tracker is not None:
+ if qwen4_flat_overhead:
+ # Qwen4 models token-scaled work statically. Add measured
+ # overhead only after the pool releases it for reallocation.
+ return (
+ static_per_token * n_tokens * self._PREFILL_TRANSIENT_SAFETY
+ + tracker.flat_overhead_charge_for(gathered_core)
+ )
+ # Dense SDPA and gathered QSA have different cost curves. The
+ # tracker keeps their measured histories separate, so switching
+ # paths cannot reintroduce a stale dense charge after the first
+ # gathered sample.
+ ewma = tracker.bytes_per_token_for(gathered_core)
+ recent_reclaim = tracker.recent_reclaim_bytes
+ if ewma > 0:
+ per_token = max(per_token, ewma)
+ last_n_tokens = tracker.last_n_tokens_for(gathered_core)
+ last_delta_bytes = tracker.last_delta_bytes_for(gathered_core)
+ if last_n_tokens > 0 and last_delta_bytes > 0:
+ measured = last_delta_bytes / last_n_tokens
+ if measured > 0:
+ per_token = max(per_token, measured)
base_prediction = per_token * n_tokens * self._PREFILL_TRANSIENT_SAFETY
reallocation_prediction = (
static_per_token * n_tokens * self._PREFILL_TRANSIENT_SAFETY
@@ -3788,7 +3999,9 @@ def _predicted_chunk_transient(self, n_tokens: int, kv_len: int) -> float:
)
return max(base_prediction, reallocation_prediction)
- def _admission_transient_bound(self, n_tokens: int, kv_len: int) -> float:
+ def _admission_transient_bound(
+ self, n_tokens: int, kv_len: int, *, gathered_core: bool = False
+ ) -> float:
"""Transient charge for admission and the guard's pass/abort gates.
The largest FLOOR-SIZE chunk transient observed this session is a
@@ -3808,10 +4021,15 @@ def _admission_transient_bound(self, n_tokens: int, kv_len: int) -> float:
shrink arithmetic stay on ``_predicted_chunk_transient``; a flat
size-invariant bound would zero out their proportional response.
"""
- bound = self._predicted_chunk_transient(n_tokens, kv_len)
+ bound = self._predicted_chunk_transient(
+ n_tokens, kv_len, gathered_core=gathered_core
+ )
tracker = self._prefill_transient_tracker
if tracker is not None:
- bound = max(bound, float(tracker.observed_max_bytes))
+ bound = max(
+ bound,
+ float(tracker.observed_max_bytes_for(gathered_core)),
+ )
return bound
def _prefill_abort_cap(self) -> int:
@@ -3849,16 +4067,23 @@ def _prefill_abort_description(self) -> tuple[int, int, float]:
safety_cap = self._prefill_abort_cap()
return base_cap, safety_cap, self._prefill_abort_margin
+ def _sdpa256_bounded_route_changed(self, active: bool) -> None:
+ """Retire measurements when SDPA256 changes memory regimes."""
+ previous = getattr(self, "_sdpa256_bounded_route_active", None)
+ active = bool(active)
+ self._sdpa256_bounded_route_active = active
+ if previous != active and (previous is not None or active):
+ self._prefill_transient_tracker.reset_history()
+
def _sdpa256_unfused_headroom(self) -> int:
"""Live headroom (bytes) for one unfused SDPA transient, under the
same target the adaptive prefill throttle enforces (hard ceiling x
headroom safety, clamped by the abort cap). Negative when the
ceiling is unknown (enforcer not propagated yet), which tells the
- sdpa256 route to keep its memory-safe tiled default. When the guard
+ sdpa256 route to keep its memory-bounded default. When the guard
is explicitly disabled there is no ceiling to respect: the user
opted out of memory management, so the route gets unbounded
- headroom and keeps the unfused fast path instead of pinning
- guard-off servers to the ~2x-slower tiled pass (#2283). Called from
+ headroom and keeps the unfused fast path (#2283). Called from
the route gate on the MLX step thread mid-prefill, where refreshing
the active-memory sample is safe (issue #2204)."""
hard_cap = self._memory_hard_limit_bytes
@@ -3871,7 +4096,7 @@ def _sdpa256_unfused_headroom(self) -> int:
"prefill keeps the unfused fast path with no memory "
"ceiling (long-context OOM protection off). Enable "
"the memory guard or set OMLX_SDPA256_TILED=1 for "
- "the memory-safe tiled path."
+ "the memory-bounded path."
)
return _SDPA256_UNBOUNDED_HEADROOM
return -1
@@ -3949,6 +4174,7 @@ def _guard_prefill_chunk(
progress: int,
loop_label: str,
request_id: str | None = None,
+ gathered_core: bool = False,
) -> int:
"""Clamp/abort a prefill chunk so its predicted peak can never reach
the physical Metal cap (the uncatchable async OOM crash).
@@ -3971,12 +4197,16 @@ def _guard_prefill_chunk(
else:
min_chunk = max(1, self._prefill_min_chunk_tokens)
current = self._current_usage_bytes()
- if current + self._admission_transient_bound(n_tokens, kv_len) <= cap:
+ if current + self._admission_transient_bound(
+ n_tokens, kv_len, gathered_core=gathered_core
+ ) <= cap:
return n_tokens
# Predicted to breach — reclaim transients and re-measure once.
current = self._reclaim_prefill_headroom()
- min_transient = self._admission_transient_bound(min_chunk, kv_len)
+ min_transient = self._admission_transient_bound(
+ min_chunk, kv_len, gathered_core=gathered_core
+ )
if current + min_transient > cap:
maybe_raise_eviction = getattr(
self, "_raise_prefill_eviction_if_available", None
@@ -4010,7 +4240,9 @@ def _guard_prefill_chunk(
# is diagnosable from one log line instead of re-deriving it.
tracker = self._prefill_transient_tracker
observed_max = (
- float(tracker.observed_max_bytes) if tracker is not None else 0.0
+ float(tracker.observed_max_bytes_for(gathered_core))
+ if tracker is not None
+ else 0.0
)
ane_reservation = (
float(getattr(self.memory_monitor, "_ane_prefill_transient_bytes", 0))
@@ -4057,9 +4289,22 @@ def _guard_prefill_chunk(
)
# The floor fits — pick the largest chunk that still fits under the cap.
- per_token = self._predicted_chunk_transient(n_tokens, kv_len) / n_tokens
- safe_n = int((cap - current) / per_token) if per_token > 0 else n_tokens
- n_fit = max(min_chunk, min(n_tokens, safe_n))
+ qwen4_flat_overhead = Scheduler._qwen4_prefill_accounting_enabled(self)
+ if qwen4_flat_overhead:
+ n_fit = Scheduler._largest_fitting_prefill_chunk(
+ self,
+ n_tokens,
+ min_chunk,
+ cap - current,
+ kv_len,
+ gathered_core=gathered_core,
+ )
+ else:
+ per_token = self._predicted_chunk_transient(
+ n_tokens, kv_len, gathered_core=gathered_core
+ ) / n_tokens
+ safe_n = int((cap - current) / per_token) if per_token > 0 else n_tokens
+ n_fit = max(min_chunk, min(n_tokens, safe_n))
# Same quantization as the adaptive throttle: an off-grid size here
# would reintroduce the near-miss buffers _snap_chunk_size exists to
# avoid.
@@ -4078,6 +4323,31 @@ def _guard_prefill_chunk(
)
return n_fit
+ def _largest_fitting_prefill_chunk(
+ self,
+ requested: int,
+ min_chunk: int,
+ headroom: float,
+ kv_len: int,
+ *,
+ gathered_core: bool,
+ ) -> int:
+ """Binary-search Qwen4's nonlinear static-plus-flat prediction."""
+ low, high = 1, max(1, requested // min_chunk)
+ best = min_chunk
+ while low <= high:
+ units = (low + high) // 2
+ candidate = min(requested, units * min_chunk)
+ predicted = self._predicted_chunk_transient(
+ candidate, kv_len, gathered_core=gathered_core
+ )
+ if predicted <= headroom:
+ best = candidate
+ low = units + 1
+ else:
+ high = units - 1
+ return best
+
def _snap_chunk_size(self, n: int, requested: int) -> int:
"""Quantize a throttled chunk to a multiple of the min-chunk floor.
@@ -4112,6 +4382,7 @@ def _adaptive_chunk_size(
request_id: str,
loop_label: str,
kv_len: int = 0,
+ gathered_core: bool = False,
) -> int:
"""Size the next prefill chunk so its predicted peak stays under a
safety margin below the hard cap.
@@ -4163,12 +4434,14 @@ def _adaptive_chunk_size(
current = self._current_usage_bytes()
min_chunk = max(1, self._prefill_min_chunk_tokens)
-
+ qwen4_flat_overhead = Scheduler._qwen4_prefill_accounting_enabled(self)
# Conservative per-token peak growth (measured-last / EWMA / static, ×
# safety) — see _predicted_chunk_transient. Anchored on the most recent
# measurement so it tracks growth with kv_len instead of lagging behind
# a long-run average.
- per_token = self._predicted_chunk_transient(requested, kv_len) / requested
+ per_token = self._predicted_chunk_transient(
+ requested, kv_len, gathered_core=gathered_core
+ ) / requested
predictor = "measured" if per_token > 0 else "none"
# Keep each chunk's predicted peak under the LOWER of the dynamic
@@ -4218,7 +4491,17 @@ def _adaptive_chunk_size(
# cleanly instead of crawling at floor-size chunks.
return requested
headroom = max(target - current, 0)
- n_fit = int(headroom / per_token)
+ if qwen4_flat_overhead:
+ n_fit = Scheduler._largest_fitting_prefill_chunk(
+ self,
+ requested,
+ min_chunk,
+ headroom,
+ kv_len,
+ gathered_core=gathered_core,
+ )
+ else:
+ n_fit = int(headroom / per_token)
n = max(min_chunk, min(requested, n_fit))
@@ -4241,6 +4524,9 @@ def _adaptive_chunk_size(
bucket = self._PREFILL_STEP_TIERS[1] # 512
n = max(min_chunk, min(n, bucket))
+ # The minimum chunk must not enlarge a short tail or boundary slice.
+ n = min(requested, n)
+
n = self._snap_chunk_size(n, requested)
if n < requested and request_id not in self._throttle_notified_requests:
@@ -4319,6 +4605,24 @@ def _hot_cache_cpu_bytes(self) -> int:
logger.debug("Failed to read local hot-cache byte counter")
return 0
+ def _reserve_qsa_index_capacity(self, cache_list: Any, tokens: int) -> int:
+ """Reserve the full prompt length on caches that expose the QSA hook."""
+ if not cache_list or tokens <= 0:
+ return 0
+ reserved = 0
+ for c in cache_list:
+ reserve = getattr(c, "reserve_index_capacity", None)
+ if reserve is None:
+ continue
+ reserve(int(tokens))
+ reserved += 1
+ if reserved:
+ logger.info(
+ f"Reserved QSA indexer capacity for {int(tokens)} tokens "
+ f"across {reserved} caches"
+ )
+ return reserved
+
def _current_usage_bytes(self, *, refresh_mlx_active: bool = True) -> int:
"""Current memory usage for scheduler-side guard checks.
@@ -4533,6 +4837,18 @@ def _bypass_hot_cache_under_pressure(self) -> bool:
return False
return current >= self._memory_limit_bytes
+ def _clear_cache(self) -> None:
+ """Clear the Metal pool and account for Qwen4 buffers that may return."""
+ tracker = getattr(self, "_prefill_transient_tracker", None)
+ track = (
+ tracker is not None
+ and Scheduler._qwen4_prefill_accounting_enabled(self)
+ )
+ before = get_phys_footprint() if track else 0
+ _sync_and_clear_cache(self._stream)
+ if track:
+ tracker.record_flat_reclaim(max(0, before - get_phys_footprint()))
+
def _record_chunk_transient(
self,
n_tokens: int,
@@ -4543,33 +4859,60 @@ def _record_chunk_transient(
loop_label: str,
kv_len: int = 0,
requested_step: int | None = None,
+ gathered_core: bool = False,
) -> None:
- """Feed one chunk's measured transient into the EWMA tracker.
-
- ``kv_len`` is logged, not used: the phys delta this records is far
- noisier than it looks — over one 13k prefill on Qwen3.6, 262 chunks of
- the SAME 32 tokens produced 5.2MB to 812.4MB (155x), because the delta
- largely tracks MLX buffer-pool growth rather than the chunk. Sampling
- phys during the chunk reproduces the delta exactly (it is monotonic
- within a chunk), and MLX's active high-water is 2x-tight but excludes
- the pool, which is real occupancy under set_cache_limit(total). So no
- better per-chunk signal was found, and anything sized from this number
- has to stay conservative. Keeping kv_len in the log is what made that
- analysis possible.
-
- Negative deltas remain excluded from the per-token EWMA, but their
- released footprint is retained until the next positive sample. The
- next predictor prices that one-shot reallocation risk without treating
- it as a negative per-token cost.
-
- Under speed priority, only a complete requested step is representative
- of the full-size chunks used for admission. A shorter tail or
- boundary-alignment chunk must not replace the last full-step sample:
- scaling its fixed/pool-heavy delta up to ``prefill_step_size`` can turn
- a small residual allocation into a false multi-gigabyte admission
- charge.
+ """Record footprint growth after a completed prefill chunk.
+
+ Qwen4 subtracts static work and records residual allocator overhead
+ without scaling it by token count. Other models retain token-linear
+ observations. Negative deltas record released buffers; positive deltas
+ repay reallocation charges. Partial speed-priority chunks do not
+ replace representative overhead or full-step measurements.
"""
delta = post_bytes - pre_bytes
+ monitor = getattr(self, "memory_monitor", None)
+ if (
+ MemoryMonitor is not None
+ and isinstance(monitor, MemoryMonitor)
+ and monitor.is_qwen4_gathered_prefill_profile()
+ ):
+ min_chunk = max(1, self._prefill_min_chunk_tokens)
+ representative = n_tokens >= min_chunk and not (
+ getattr(self, "_prefill_speed_priority", False)
+ and requested_step is not None
+ and n_tokens < requested_step
+ )
+ static = monitor.estimate_chunk_transient_bytes(
+ n_tokens,
+ kv_len + n_tokens,
+ gathered_core=gathered_core,
+ ) + monitor.estimate_prompt_kv_bytes(n_tokens)
+ self._prefill_transient_tracker.observe_flat_overhead(
+ n_tokens,
+ delta,
+ static_bytes=static,
+ gathered_core=gathered_core,
+ representative=representative,
+ )
+ logger.debug(
+ "[throttle:%s] qwen4-flat rid=%s n=%d kv_len=%d "
+ "delta=%.2fMB static=%.2fMB overhead=%.2fMB debt=%.2fMB",
+ loop_label,
+ request_id,
+ n_tokens,
+ kv_len,
+ delta / 1024**2,
+ static / 1024**2,
+ self._prefill_transient_tracker.flat_overhead_bytes_for(
+ gathered_core
+ )
+ / 1024**2,
+ self._prefill_transient_tracker.reclaim_debt_bytes_for(
+ gathered_core
+ )
+ / 1024**2,
+ )
+ return
# The reclaim ledger sees every measurement, including samples the
# EWMA gates below skip: a release on a sub-floor tail must still be
# priced, and any positive growth confirms the pool reallocation and
@@ -4617,7 +4960,10 @@ def _record_chunk_transient(
)
return
self._prefill_transient_tracker.update(
- n_tokens, delta, floor_sample=n_tokens <= min_chunk
+ n_tokens,
+ delta,
+ floor_sample=n_tokens <= min_chunk,
+ gathered_core=gathered_core,
)
logger.debug(
"[throttle:%s] measure rid=%s n=%d kv_len=%d transient=%.2fMB per_token=%.1fKB ewma=%.1fKB observed_max=%.1fMB samples=%d",
@@ -4627,9 +4973,11 @@ def _record_chunk_transient(
kv_len,
delta / 1024**2,
(delta / max(n_tokens, 1)) / 1024,
- self._prefill_transient_tracker.bytes_per_token / 1024,
- self._prefill_transient_tracker.observed_max_bytes / 1024**2,
- self._prefill_transient_tracker.samples,
+ self._prefill_transient_tracker.bytes_per_token_for(gathered_core)
+ / 1024,
+ self._prefill_transient_tracker.observed_max_bytes_for(gathered_core)
+ / 1024**2,
+ self._prefill_transient_tracker.samples_for(gathered_core),
)
def _supports_skip_lm_head(self) -> bool:
@@ -4716,7 +5064,7 @@ def _reclaim_prefill_headroom(self) -> int:
Returns:
``max(active, phys_footprint)`` after reclaim.
"""
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
return self._current_usage_bytes()
# ------------------------------------------------------------------
@@ -5025,7 +5373,15 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool:
n = min(prefill_step_size, remaining)
if state.tokens_processed == 0:
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
+ # Known horizon: size the QSA indexer once instead of doubling
+ # mid-prefill (see _reserve_qsa_index_capacity).
+ self._reserve_qsa_index_capacity(
+ state.cache,
+ _cache_base_sizes(state.cache)
+ + int(state.tokens_remaining.shape[1])
+ + len(state.last_token),
+ )
# Clamp to the next block boundary so boundary snapshots fire exactly.
if state.boundary_enabled and state.block_size > 0:
@@ -5040,11 +5396,17 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool:
# if even prefill_min_chunk_tokens would exceed the cap; #1405
# cleanup paths in _schedule_waiting / _advance_chunked_prefills
# convert that into a finish_reason="error" output for the client.
+ # Chunked prefill is text-only (VLM never builds _PrefillState).
+ qwen4_accounting = Scheduler._qwen4_prefill_accounting_enabled(self)
+ if qwen4_accounting and state.qwen4_gathered_core is None:
+ state.qwen4_gathered_core = self._qwen4_text_gathered_pricing(True)
+ gathered_core = state.qwen4_gathered_core or False
n = self._adaptive_chunk_size(
n,
request_id=state.request.request_id,
loop_label="chunked_step",
kv_len=state.base_size + state.tokens_processed,
+ gathered_core=gathered_core,
)
# Pre-chunk safety guard (mirrors the external loop): never submit a
@@ -5055,7 +5417,10 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool:
progress=state.tokens_processed,
loop_label="chunked_step",
request_id=state.request.request_id,
+ gathered_core=gathered_core,
)
+ # Count only tokens actually passed to the model.
+ n = min(n, remaining)
if getattr(state.request, "benchmark_trace", False):
state.request.benchmark_prefill_chunks.append(int(n))
state.request.benchmark_requested_steps.append(int(prefill_step_size))
@@ -5069,6 +5434,16 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool:
with mx.stream(self._stream):
chunk = state.tokens_remaining[:, :n]
state.tokens_remaining = state.tokens_remaining[:, n:]
+ # A chunked text prefill can yield to active decode between
+ # forwards. Completion cleanup or the intervening decode batch may
+ # replace the VLM adapter's process-local mRoPE state. Rebind this
+ # request at the model-call boundary so the next scalar-cache chunk
+ # continues from its absolute cache offset instead of restarting at
+ # local position zero.
+ _bind_text_prefill_rope_delta(
+ self.model,
+ getattr(state.request, "rope_deltas", 0.0),
+ )
if self._supports_skip_lm_head():
self.model(chunk, cache=state.cache, skip_lm_head=True)
else:
@@ -5076,6 +5451,22 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool:
mx.eval([c.state for c in state.cache])
_trace_model_ms = (time.perf_counter() - _trace_model_start) * 1000.0
_throttle_post = get_phys_footprint()
+ actual_gathered_core = gathered_core
+ if qwen4_accounting:
+ actual_gathered_core = Scheduler._qwen4_actual_gathered_pricing(
+ state.cache, gathered_core
+ )
+ if actual_gathered_core != gathered_core:
+ logger.info(
+ "Qwen4 prefill pricing route corrected after execution: "
+ "rid=%s predicted=%s actual=%s query=%d kv_len=%d",
+ state.request.request_id,
+ "gathered" if gathered_core else "mask_dense",
+ "gathered" if actual_gathered_core else "mask_dense",
+ n,
+ state.base_size + state.tokens_processed,
+ )
+ state.qwen4_gathered_core = actual_gathered_core
self._record_chunk_transient(
n,
_throttle_pre,
@@ -5084,6 +5475,7 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool:
loop_label="chunked_step",
kv_len=state.base_size + state.tokens_processed,
requested_step=prefill_step_size,
+ gathered_core=actual_gathered_core,
)
self._maybe_record_fixed_state_bytes(state.cache)
state.tokens_processed += n
@@ -5180,7 +5572,7 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool:
)
if self._should_clear_after_chunk():
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
chunk_dt = time.perf_counter() - _t_chunk_start
if getattr(state.request, "benchmark_trace", False):
_ane_sequence = int(
@@ -5247,7 +5639,7 @@ def _finalize_chunked_prefill_cache_for_insert(
if getattr(request, "cached_tokens", 0) > 0:
with mx.stream(self._stream):
_materialize_cache_storage(prompt_cache)
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
def _insert_prefilled_request(
self,
@@ -5353,12 +5745,12 @@ def _advance_chunked_prefills(
scheduled: "list[Request]",
rejected: "list[RequestOutput]",
) -> None:
- """Process one prefill chunk per in-flight chunked-prefill request.
+ """Advance in-flight prefills until decode fairness requires a yield.
Called at the start of each step() before _schedule_waiting(). Each
- call advances every request in self.prefilling by one prefill_step_size
- chunk. When a request's prefill completes it is inserted into
- BatchGenerator and moved to self.running.
+ request advances by at most one chunk. Deferred requests precede
+ already-advanced requests in the next round. Completed prefills are
+ inserted into BatchGenerator and moved to self.running.
Args:
scheduled: The step's running list of newly-scheduled requests;
@@ -5382,13 +5774,17 @@ def _advance_chunked_prefills(
if state is None:
continue
+ if not self._prefill_gate_open():
+ still_prefilling.extendleft(reversed(pending_prefills[index:]))
+ break
+
try:
done = self._step_prefill_chunk(state)
except _PrefillAbortedError:
# Request aborted mid-chunk. Discard state; the abort will
# be fully processed by _process_pending_aborts() next step.
self._prefill_states.pop(rid, None)
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
continue
except _PrefillEvictionNeeded as e:
self._pending_prefill_eviction_request = e.request
@@ -5404,23 +5800,25 @@ def _advance_chunked_prefills(
logger.error("Chunked prefill capacity rejected for %s: %s", rid, e)
self._prefill_states.pop(rid, None)
self._release_paged_cache_for_request(rid)
+ self._drop_boundary_snapshots_for_request(rid)
self.requests.pop(rid, None)
self._clear_request_admission_bookkeeping(rid)
get_prefill_tracker().remove(rid)
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
rejected.append(_prefill_memory_exception_output(rid, e))
continue
except RuntimeError as e:
logger.error("Chunked prefill failed for %s: %s", rid, e)
self._prefill_states.pop(rid, None)
self._release_paged_cache_for_request(rid)
+ self._drop_boundary_snapshots_for_request(rid)
self.requests.pop(rid, None)
self._clear_request_admission_bookkeeping(rid)
get_prefill_tracker().remove(rid)
# Drop Metal cache pool buffers held by the aborted chunk's
# forward / mx.eval transients. Without this, enforcer keeps
# seeing the burst footprint until the next mx.clear_cache().
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
# Try a bounded requeue before surfacing the failure: a
# memory-pressure prefill gets a fresh, better-throttled
# attempt. Only after the retry budget is exhausted (or for
@@ -5446,7 +5844,7 @@ def _advance_chunked_prefills(
# Prefill complete — emit final boundary snapshot and insert.
self._prefill_states.pop(rid, None)
self._emit_final_boundary_if_needed(state)
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
# Ensure a BatchGenerator exists (may not if all requests were
# previously in chunked prefill with no running decode).
@@ -6156,23 +6554,52 @@ def _on_prefill_boundary_snapshot(
request_id: str,
snapshot_cache: list[Any],
token_count: int,
+ *,
+ source: str = "prefill",
) -> None:
- """Record boundary snapshots captured during prefill processing.
+ """Record a prefill boundary or a verified terminal response snapshot."""
+ if self._model_has_unreconstructible_cache():
+ return
- Called from ``_emit_prefill_boundary_snapshot`` at each block
- boundary crossed during prefill. Keyed by ``request_id`` rather
- than ``uid`` because the request has not been inserted into
- ``BatchGenerator`` yet and the uid mapping does not exist —
- routing through it dropped every snapshot silently (#TBD).
- """
+ block_size = self.config.paged_cache_block_size
+ self._boundary_snapshot_diagnostics.record(
+ "capture_attempt",
+ request_id=request_id,
+ token_count=token_count,
+ block_size=block_size,
+ source=source,
+ )
if self.block_aware_cache is None:
+ self._boundary_snapshot_diagnostics.record(
+ "capture_skipped",
+ reason="prefix_cache_disabled",
+ request_id=request_id,
+ token_count=token_count,
+ block_size=block_size,
+ source=source,
+ )
return
- block_size = self.config.paged_cache_block_size
if block_size <= 0 or token_count <= 0 or token_count % block_size != 0:
+ self._boundary_snapshot_diagnostics.record(
+ "capture_skipped",
+ reason="unaligned_token_count",
+ request_id=request_id,
+ token_count=token_count,
+ block_size=block_size,
+ source=source,
+ )
return
if not self._cache_list_needs_boundary_snapshot(snapshot_cache):
+ self._boundary_snapshot_diagnostics.record(
+ "capture_skipped",
+ reason="no_stateful_cache",
+ request_id=request_id,
+ token_count=token_count,
+ block_size=block_size,
+ source=source,
+ )
return
if request_id not in self._boundary_cache_snapshots:
@@ -6180,6 +6607,14 @@ def _on_prefill_boundary_snapshot(
# Skip if we already have a snapshot at this token count
if token_count in self._boundary_cache_snapshots[request_id]:
+ self._boundary_snapshot_diagnostics.record(
+ "capture_skipped",
+ reason="duplicate_boundary",
+ request_id=request_id,
+ token_count=token_count,
+ block_size=block_size,
+ source=source,
+ )
return
# Offload snapshot to SSD if store is available, keeping only a
@@ -6201,7 +6636,17 @@ def _on_prefill_boundary_snapshot(
)
if saved:
self._boundary_cache_snapshots[request_id][token_count] = None
+ storage = "ssd"
else:
+ self._boundary_snapshot_diagnostics.record(
+ "ssd_fallback",
+ reason="ssd_save_failed",
+ request_id=request_id,
+ token_count=token_count,
+ block_size=block_size,
+ source=source,
+ storage="memory",
+ )
self._boundary_cache_snapshots[request_id][token_count] = (
_compact_boundary_snapshot_value(
self._prefill_snapshot_value(snapshot_cache),
@@ -6210,6 +6655,7 @@ def _on_prefill_boundary_snapshot(
self._stream,
)
)
+ storage = "memory"
else:
self._boundary_cache_snapshots[request_id][token_count] = (
_compact_boundary_snapshot_value(
@@ -6219,13 +6665,24 @@ def _on_prefill_boundary_snapshot(
self._stream,
)
)
+ storage = "memory"
self._boundary_snapshot_required = True
self._enable_mtp_boundary_alignment()
+ self._boundary_snapshot_diagnostics.record(
+ "capture_success",
+ request_id=request_id,
+ token_count=token_count,
+ block_size=block_size,
+ source=source,
+ storage=storage,
+ )
logger.debug(
- "Captured prefill boundary cache snapshot for %s at %s tokens",
+ "Captured %s boundary cache snapshot for %s at %s tokens (%s)",
+ source,
request_id,
token_count,
+ storage,
)
_PREFILL_SNAPSHOT_MARKER = "__prefill_extracted__"
@@ -6449,7 +6906,10 @@ def _enable_mtp_boundary_alignment(self) -> None:
pass
def _extract_boundary_snapshot(
- self, uid: int, expected_tokens: int | None = None
+ self,
+ uid: int,
+ expected_tokens: int | None = None,
+ request_id: str | None = None,
) -> list[Any] | None:
"""Extract a per-request prompt cache snapshot via extract_cache().
@@ -6467,7 +6927,20 @@ def _extract_boundary_snapshot(
on hybrid models; skipping the capture merely costs a reuse
opportunity.
"""
+ block_size = self.config.paged_cache_block_size
+
+ def record_skip(reason: str) -> None:
+ self._boundary_snapshot_diagnostics.record(
+ "capture_skipped",
+ reason=reason,
+ request_id=request_id,
+ token_count=expected_tokens,
+ block_size=block_size,
+ source="decode",
+ )
+
if self.batch_generator is None:
+ record_skip("batch_generator_unavailable")
return None
try:
@@ -6479,6 +6952,7 @@ def _extract_boundary_snapshot(
with mx.stream(self._stream):
result = self.batch_generator.extract_cache([uid])
if uid not in result:
+ record_skip("uid_not_found")
return None
cache_list, _tokens = result[uid]
if expected_tokens is not None:
@@ -6499,11 +6973,12 @@ def _extract_boundary_snapshot(
offset,
expected_tokens,
)
+ record_skip("cache_offset_mismatch")
return None
break
# Only extract non-sliceable layers to avoid costly
# deep-copy accumulation (same rationale as prefill path).
- return [
+ snapshot = [
(
c
if type(c).__name__ not in _KNOWN_SLICEABLE_CACHE_TYPES
@@ -6511,14 +6986,22 @@ def _extract_boundary_snapshot(
)
for c in cache_list
]
+ if not snapshot:
+ record_skip("empty_snapshot")
+ return None
+ return snapshot
except Exception as e:
logger.debug(
f"Failed to extract boundary cache snapshot for uid={uid}: {e}"
)
+ record_skip("extract_error")
return None
def _maybe_capture_boundary_snapshot(self, request: Request, uid: int) -> None:
"""Capture cache snapshot exactly at block boundaries for safe reuse."""
+ if self._model_has_unreconstructible_cache():
+ return
+
if self.block_aware_cache is None:
return
@@ -6533,8 +7016,17 @@ def _maybe_capture_boundary_snapshot(self, request: Request, uid: int) -> None:
if not self._detect_boundary_snapshot_need():
return
+ self._boundary_snapshot_diagnostics.record(
+ "capture_attempt",
+ request_id=request.request_id,
+ token_count=total_tokens,
+ block_size=block_size,
+ source="decode",
+ )
snapshot_cache = self._extract_boundary_snapshot(
- uid, expected_tokens=total_tokens
+ uid,
+ expected_tokens=total_tokens,
+ request_id=request.request_id,
)
if not snapshot_cache:
return
@@ -6554,7 +7046,17 @@ def _maybe_capture_boundary_snapshot(self, request: Request, uid: int) -> None:
)
if saved:
self._boundary_cache_snapshots[request.request_id][total_tokens] = None
+ storage = "ssd"
else:
+ self._boundary_snapshot_diagnostics.record(
+ "ssd_fallback",
+ reason="ssd_save_failed",
+ request_id=request.request_id,
+ token_count=total_tokens,
+ block_size=block_size,
+ source="decode",
+ storage="memory",
+ )
# In-memory fallback: the store-cache worker slices this snapshot
# off-thread (via _BoundarySnapshotProvider -> _extract_cache_states).
# MLX streams are thread-local, so force the leaves concrete now on
@@ -6566,16 +7068,26 @@ def _maybe_capture_boundary_snapshot(self, request: Request, uid: int) -> None:
snapshot_cache, total_tokens, block_size
)
)
+ storage = "memory"
else:
self._boundary_cache_snapshots[request.request_id][total_tokens] = (
self._decode_boundary_snapshot_value(
snapshot_cache, total_tokens, block_size
)
)
+ storage = "memory"
+ self._boundary_snapshot_diagnostics.record(
+ "capture_success",
+ request_id=request.request_id,
+ token_count=total_tokens,
+ block_size=block_size,
+ source="decode",
+ storage=storage,
+ )
logger.debug(
f"Captured boundary cache snapshot for {request.request_id} at "
- f"{total_tokens} tokens"
+ f"{total_tokens} tokens ({storage})"
)
def _get_boundary_store_override(
@@ -6599,12 +7111,33 @@ def _get_boundary_store_override(
intermediate_snapshots) where intermediate_snapshots maps
token_count -> extracted cache states for per-block storage.
"""
+ total_tokens = len(full_token_sequence)
+ block_size = self.config.paged_cache_block_size
+ self._boundary_snapshot_diagnostics.record(
+ "override_attempt",
+ request_id=request_id,
+ token_count=total_tokens,
+ block_size=block_size,
+ )
+
+ def miss(reason: str, available_boundaries: int = 0) -> None:
+ self._boundary_snapshot_diagnostics.record(
+ "override_miss",
+ reason=reason,
+ request_id=request_id,
+ token_count=total_tokens,
+ block_size=block_size,
+ available_boundaries=available_boundaries,
+ )
+
snapshots = self._boundary_cache_snapshots.get(request_id)
if not snapshots:
+ miss("no_snapshots")
return None
- total_tokens = len(full_token_sequence)
- block_size = self.config.paged_cache_block_size
+ if block_size <= 0:
+ miss("invalid_block_size", len(snapshots))
+ return None
# Find all valid boundary-aligned snapshot token counts
valid_counts = sorted(
@@ -6613,6 +7146,7 @@ def _get_boundary_store_override(
if 0 < tc <= total_tokens and tc % block_size == 0
)
if not valid_counts:
+ miss("no_aligned_snapshots", len(snapshots))
return None
# Find the latest snapshot that leaves trailing partial tokens
@@ -6626,6 +7160,7 @@ def _get_boundary_store_override(
# provide intermediate snapshots for per-block storage.
latest_tc = total_tokens
else:
+ miss("latest_snapshot_not_usable", len(valid_counts))
return None
# Load latest snapshot — may be on SSD (None marker) or in memory.
@@ -6640,6 +7175,7 @@ def _get_boundary_store_override(
# Offloaded to SSD — load back.
extracted_cache = self._boundary_snapshot_store.load(request_id, latest_tc)
if not extracted_cache:
+ miss("ssd_load_failed", len(valid_counts))
return None
# Build model_cache_config from the main request cache config
# since the SSD snapshot doesn't carry it.
@@ -6663,8 +7199,10 @@ def _get_boundary_store_override(
latest_snapshot
)
if not extracted_cache:
+ miss("snapshot_extract_failed", len(valid_counts))
return None
else:
+ miss("snapshot_value_unavailable", len(valid_counts))
return None
# Build provider for intermediate snapshots. SSD-backed snapshots remain
@@ -6708,6 +7246,13 @@ def _get_boundary_store_override(
else full_token_sequence
)
+ self._boundary_snapshot_diagnostics.record(
+ "override_hit",
+ request_id=request_id,
+ token_count=latest_tc,
+ block_size=block_size,
+ available_boundaries=len(valid_counts),
+ )
return (
token_sequence,
extracted_cache,
@@ -6949,6 +7494,42 @@ def _extract_live_request_cache_for_store(
)
return None
+ def _capture_finished_boundary_snapshot(
+ self, request: Request, cache: list[Any]
+ ) -> None:
+ """Preserve a verified terminal boundary after the generator drops its UID."""
+ if getattr(request, "skip_cache_store", False):
+ return
+ if self._boundary_cache_snapshots.get(request.request_id):
+ return
+ token_count = (
+ len(request.prompt_token_ids)
+ if request.needs_think_prefix
+ else request.num_tokens
+ )
+ block_size = self.config.paged_cache_block_size
+ if (
+ block_size <= 0
+ or token_count <= 0
+ or token_count % block_size
+ or not self._detect_boundary_snapshot_need()
+ ):
+ return
+
+ # Composite caches use their leading token-position leaf; later
+ # members may count pooled windows instead. Unknown positions cannot
+ # establish that recurrent state matches the emitted token sequence.
+ offsets = [
+ offset
+ for layer in cache
+ if (offset := _first_leaf_cache_offset(layer)) is not None
+ ]
+ if not offsets or any(offset != token_count for offset in offsets):
+ return
+ self._on_prefill_boundary_snapshot(
+ request.request_id, cache, token_count, source="completion"
+ )
+
def _prepare_prompt_boundary_cache_store(
self,
request_id: str,
@@ -7455,6 +8036,9 @@ def _extract_cache_states(
if handler is not None and class_name in (
"MiniMaxM3KVCache",
"MiniMaxM3BatchKVCache",
+ "QSAKVCache",
+ "QSAQuantizedKVCache",
+ "BatchQSAKVCache",
):
state = handler.serialize_state(layer_cache)
meta = handler.serialize_meta_state(layer_cache)
@@ -7602,7 +8186,35 @@ def _log_prefix_divergence(self, request: Request) -> None:
logs.
"""
prompt = request.prompt_token_ids or []
- if not prompt or not self._cache_probe_seqs:
+ cached = request.cached_tokens or 0
+ block = max(1, self.config.paged_cache_block_size)
+ base_observation: dict[str, Any] = {
+ "request_id": request.request_id,
+ "prompt_tokens": len(prompt),
+ "reused_kv_tokens": cached,
+ "reprefill_tokens": max(0, len(prompt) - cached),
+ "block_size": block,
+ "matched_blocks": cached // block,
+ }
+ if not prompt:
+ self._last_prefix_cache_lookup = {
+ **base_observation,
+ "reason": "empty_prompt",
+ "closest_request_id": None,
+ "common_prefix_tokens": 0,
+ "comparable_tokens": 0,
+ "unreused_common_prefix_tokens": 0,
+ }
+ return
+ if not self._cache_probe_seqs:
+ self._last_prefix_cache_lookup = {
+ **base_observation,
+ "reason": "no_recent_store_probe",
+ "closest_request_id": None,
+ "common_prefix_tokens": 0,
+ "comparable_tokens": 0,
+ "unreused_common_prefix_tokens": 0,
+ }
return
best_id, best_seq, best_p = None, None, -1
for ref_id, seq in list(self._cache_probe_seqs):
@@ -7611,10 +8223,16 @@ def _log_prefix_divergence(self, request: Request) -> None:
best_id, best_seq, best_p = ref_id, seq, p
if best_seq is None:
return
- cached = request.cached_tokens or 0
reusable = min(len(prompt), len(best_seq))
- block = max(1, self.config.paged_cache_block_size)
reprefill = len(prompt) - cached
+ self._last_prefix_cache_lookup = {
+ **base_observation,
+ "reason": "closest_recent_store",
+ "closest_request_id": best_id,
+ "common_prefix_tokens": best_p,
+ "comparable_tokens": reusable,
+ "unreused_common_prefix_tokens": max(0, best_p - cached),
+ }
if reprefill >= self._REPREFILL_INFO_MIN_TOKENS and best_p >= block:
logger.info(
"prefix cache: request %s re-prefills %d of %d tokens "
@@ -7649,13 +8267,10 @@ def _log_prefix_divergence(self, request: Request) -> None:
f"{best_p}: stored=...{stored_ctx!r} vs prompt=...{prompt_ctx!r}"
)
- # A 4K prompt is the smallest standard benchmark/workload where a missed
- # async store is already a multi-second re-prefill. DeepSeek V4 boundary
- # snapshots intentionally retain 3584 of 4096 prompt tokens, and their SSD
- # write can finish just after the first HTTP response is returned. Include
- # this workload class in the non-blocking freshness deferral so an immediate
- # repeated turn waits for that relevant store instead of racing it.
- _CACHE_FRESHNESS_WAIT_MIN_PROMPT_TOKENS = 4096
+ # Wait only for reusable blocks. The store/overlap ratio is a heuristic
+ # limiting waits on large stores that share a small prefix; the timeout
+ # below still bounds slow storage independently of token counts.
+ _CACHE_FRESHNESS_WAIT_MAX_STORE_TO_OVERLAP = 16
_CACHE_FRESHNESS_WAIT_MIN_COMMON_TOKENS = 8192
_CACHE_FRESHNESS_WAIT_MIN_PROMPT_RATIO = 0.30
_CACHE_FRESHNESS_WAIT_TIMEOUT_S = 4.0
@@ -7681,8 +8296,7 @@ def _find_relevant_inflight_store(
return None
prompt = request.prompt_token_ids or []
- if len(prompt) < self._CACHE_FRESHNESS_WAIT_MIN_PROMPT_TOKENS:
- return None
+ block = max(1, self.config.paged_cache_block_size)
best_rid: str | None = None
best_future: concurrent.futures.Future | None = None
@@ -7695,6 +8309,24 @@ def _find_relevant_inflight_store(
continue
common = self._common_prefix_len(prompt, info.tokens)
+ # Filter before ranking so an ineligible larger store cannot
+ # hide a smaller one whose prefix can actually be reused.
+ restorable = (common // block) * block
+ if restorable == len(prompt):
+ # Match exact-hit generation kickoff in prefix preparation:
+ # GDN sidecars drop the final block; other stateful caches
+ # cannot trim to N-1 and require a full prefill.
+ if self._gdn_split_active():
+ restorable = max(0, restorable - block)
+ elif self._detect_boundary_snapshot_need():
+ restorable = 0
+ if restorable < block:
+ continue
+ if (
+ len(info.tokens)
+ > self._CACHE_FRESHNESS_WAIT_MAX_STORE_TO_OVERLAP * restorable
+ ):
+ continue
if common > best_common:
best_rid = rid
best_future = future
@@ -7792,12 +8424,77 @@ def _should_defer_for_cache_freshness(self, request: Request) -> bool:
)
return True
+ # Legacy class-name aliases explicitly supported by reconstruction.
+ _EXTRA_RECONSTRUCTIBLE_CACHE_TYPES = frozenset({"SizedArraysCache"})
+
+ def _prefix_reuse_supports_cache_class(self, class_name: str) -> bool:
+ """Check explicit reconstruction support; structural KV detection is lossy."""
+ if class_name in _KNOWN_SLICEABLE_CACHE_TYPES:
+ return True
+ if class_name in self._EXTRA_RECONSTRUCTIBLE_CACHE_TYPES:
+ return True
+ if HAS_CACHE_TYPE_HANDLERS and CacheTypeRegistry is not None:
+ return class_name in CacheTypeRegistry.list_known_class_names()
+ # Without the registry nothing beyond the plainly sliceable set can be
+ # rebuilt, so treat everything else as unsupported.
+ return False
+
+ def _cache_layer_is_reconstructible(self, layer: Any) -> bool:
+ """Recursive per-layer form of :meth:`_prefix_reuse_supports_cache_class`."""
+ if layer is None:
+ return True
+ sub_caches = getattr(layer, "caches", None)
+ if isinstance(sub_caches, (list, tuple)):
+ # CacheList itself round-trips, but only if every sub-cache does:
+ # its handler stores sub-class names and re-dispatches per name.
+ if not self._prefix_reuse_supports_cache_class(type(layer).__name__):
+ return False
+ return all(self._cache_layer_is_reconstructible(sub) for sub in sub_caches)
+ return self._prefix_reuse_supports_cache_class(type(layer).__name__)
+
+ def _model_has_unreconstructible_cache(self) -> bool:
+ """Refuse paged storage and reuse for unsupported cache layouts.
+
+ Memoize successful probes only; retry cache-construction failures.
+ """
+ cached = getattr(self, "_unreconstructible_cache_model", None)
+ if cached is not None:
+ return cached
+
+ try:
+ layers = make_prompt_cache(self.model) or []
+ except Exception as e:
+ logger.warning(
+ "Could not probe model cache classes (%s: %s); refusing prefix cache "
+ "storage and reuse for this request",
+ type(e).__name__,
+ e,
+ )
+ logger.debug("Cache probe failure traceback:", exc_info=True)
+ return True
+
+ result = False
+ for layer in layers:
+ if not self._cache_layer_is_reconstructible(layer):
+ logger.info(
+ "Prefix cache storage and reuse disabled: unsupported %s layers",
+ type(layer).__name__,
+ )
+ result = True
+ break
+
+ self._unreconstructible_cache_model = result
+ return result
+
def _prepare_prefix_cache_for_request(self, request: Request) -> None:
if request.request_id in self._prefix_cache_prepared:
return
- # Check prefix cache for cached KV state
- if self.block_aware_cache is not None:
+ # Check support before lookup, including partial prefix hits.
+ if (
+ self.block_aware_cache is not None
+ and not self._model_has_unreconstructible_cache()
+ ):
# Use paged cache
block_table, remaining = self.block_aware_cache.fetch_cache(
request.request_id,
@@ -7947,6 +8644,32 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None:
# No paged SSD cache configured - process all tokens
request.remaining_tokens = request.prompt_token_ids
+ # Lightning-MTP has a small prompt-history cache separate from the
+ # backbone KV restored above. Bind an exact full-block sidecar (when
+ # one exists) to this singleton timeline before any uncached suffix is
+ # forwarded. The hook is intentionally best-effort/fail-closed:
+ # ordinary inference and prefix reuse stay valid if MTP is disabled,
+ # the sidecar was evicted, or this model family does not support it.
+ try:
+ from .patches.mlx_lm_mtp import prompt_priming
+
+ prompt_priming.prepare_prefix_context(
+ self.model,
+ request_id=request.request_id,
+ prompt_tokens=request.prompt_token_ids,
+ cached_tokens=request.cached_tokens,
+ prefix_cache=self.block_aware_cache,
+ extra_keys=request.vlm_extra_keys_for_cache,
+ extra_key_token_start=request.vlm_extra_key_token_start_for_cache,
+ extra_key_ranges=request.vlm_extra_key_ranges_for_cache,
+ )
+ except Exception as exc:
+ logger.debug(
+ "MTP prefix-history preparation failed closed for %s: %s",
+ request.request_id,
+ exc,
+ )
+
# Trace where this prompt diverges from recently stored cache
# sequences: one INFO line for large re-prefills (#2333/#2349
# triage), decoded token context at DEBUG (issue #1003).
@@ -8004,6 +8727,7 @@ def add_request(self, request: Request) -> None:
num_prompt_tokens=request.num_prompt_tokens,
cached_tokens=request.cached_tokens or 0,
request_id=request.request_id,
+ text_only=getattr(request, "vlm_inputs_embeds", None) is None,
)
except Exception:
self._release_paged_cache_for_request(request.request_id)
@@ -8567,7 +9291,7 @@ def _try_specprefill_scoring(self, request: Request) -> None:
prefill_step_size=self.config.prefill_step_size,
stream=self._stream,
extract_cache_states=self._extract_cache_states,
- sync_and_clear_cache=lambda: _sync_and_clear_cache(self._stream),
+ sync_and_clear_cache=lambda: Scheduler._clear_cache(self),
log=logger,
)
@@ -9080,6 +9804,26 @@ def _effective_max_num_seqs(self) -> int:
return 1
return max(1, self.config.max_num_seqs)
+ def _drop_boundary_snapshots_for_request(self, request_id: str) -> None:
+ """Release a failed request's boundary snapshots (RAM and SSD).
+
+ The in-memory dict values can hold live mx.arrays (the SSD-store
+ fallback path), and the store keeps a per-request snapshot dir on
+ disk. Both are normally released in _cleanup_finished; error paths
+ must do the same or every failure strands a snapshot set until
+ process exit (#3226).
+ """
+ self._boundary_cache_snapshots.pop(request_id, None)
+ if self._boundary_snapshot_store is not None:
+ try:
+ self._boundary_snapshot_store.cleanup_request(request_id)
+ except Exception as e:
+ logger.debug(
+ "Boundary snapshot store cleanup failed for %s: %s",
+ request_id,
+ e,
+ )
+
def fail_all_requests(self) -> list[str]:
"""Remove all running and waiting requests after unrecoverable error.
@@ -9156,6 +9900,16 @@ def fail_all_requests(self) -> list[str]:
if uid is not None:
self.uid_to_request_id.pop(uid, None)
self._generation_overflow_recovery_ids.difference_update(failed_ids)
+ # Drop boundary snapshots and paged-cache reservations for every
+ # failed request. Without this, each engine-loop failure strands a
+ # full per-request snapshot set (live mx.arrays for the in-memory
+ # fallback, orphaned snapshot dirs on SSD) and its block refs until
+ # process exit — a Metal buffer/byte ratchet across failures (#3226).
+ # failed_ids excludes _inflight_store_futures ids, so snapshots the
+ # async store worker still reads are left intact.
+ for rid in failed_ids:
+ self._drop_boundary_snapshots_for_request(rid)
+ self._release_paged_cache_for_request(rid)
# Reset batch generator only (cache is not corrupted). Every row dies
# with it; survivors re-register at re-insert.
_unregister_uid_rows_for_model(self.model)
@@ -9168,7 +9922,7 @@ def fail_all_requests(self) -> list[str]:
# state — mx.synchronize() or mx.clear_cache() can throw a C++
# exception that causes SIGABRT if uncaught (#435).
try:
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
except Exception as e:
logger.warning(f"Metal cache clear failed during error recovery: {e}")
# Requests failed mid-prefill leave PrefillProgressTracker entries
@@ -9234,6 +9988,7 @@ def _preflight_memory_check(
num_prompt_tokens=prompt_tokens,
cached_tokens=cached_tokens,
current=current,
+ text_only=getattr(request, "vlm_inputs_embeds", None) is None,
)
if est is None:
return None # can't estimate, skip
@@ -9292,6 +10047,7 @@ def _admission_estimate(
num_prompt_tokens: int,
cached_tokens: int,
current: int,
+ text_only: bool = False,
) -> _AdmissionEstimate | None:
"""Deterministic admission estimate shared by every preflight path.
@@ -9344,7 +10100,12 @@ def _admission_estimate(
kv_exact = int(
monitor.estimate_resident_kv_bytes(new_tokens, chunk_tokens=floor_chunk)
)
- transient = int(self._admission_transient_bound(floor_chunk, kv_len))
+ gathered_core = self._qwen4_text_gathered_pricing(text_only)
+ transient = int(
+ self._admission_transient_bound(
+ floor_chunk, kv_len, gathered_core=gathered_core
+ )
+ )
if kv_exact <= 0 and transient <= 0:
return None
return _AdmissionEstimate(
@@ -9403,6 +10164,7 @@ def preflight_or_raise(
num_prompt_tokens: int,
cached_tokens: int = 0,
request_id: str | None = None,
+ text_only: bool = False,
) -> None:
"""Pre-StreamingResponse prefill memory check.
@@ -9428,6 +10190,7 @@ def preflight_or_raise(
num_prompt_tokens=num_prompt_tokens,
cached_tokens=cached_tokens,
current=current,
+ text_only=text_only,
)
if est is None:
return
@@ -9488,6 +10251,7 @@ def preflight_eviction_request(
num_prompt_tokens: int,
cached_tokens: int = 0,
request_id: str | None = None,
+ text_only: bool = False,
) -> PrefillEvictionRequest | None:
"""Return an idle-model eviction request for route-level preflight.
@@ -9511,6 +10275,7 @@ def preflight_eviction_request(
num_prompt_tokens=num_prompt_tokens,
cached_tokens=cached_tokens,
current=current,
+ text_only=text_only,
)
if est is None:
return None
@@ -9655,10 +10420,7 @@ def _schedule_waiting(
# admissions. This is also the per-step admission budget —
# prefills can no longer chain back-to-back inside one step
# while decodes wait.
- if self._decode_fairness and (
- (self.running and self._decode_time_owed_s > 0.0)
- or time.perf_counter() < self._prefill_hold_deadline()
- ):
+ if not self._prefill_gate_open():
break
# Store-cache backpressure: when the post-completion pipeline is
@@ -10002,7 +10764,7 @@ def _report_sparse_progress(processed: int, total: int) -> None:
check_abort=_check_specprefill_abort,
report_system_progress=_report_system_progress,
report_sparse_progress=_report_sparse_progress,
- sync_and_clear_cache=lambda: _sync_and_clear_cache(self._stream),
+ sync_and_clear_cache=lambda: Scheduler._clear_cache(self),
log=logger,
extract_cache_states=self._extract_cache_states,
# Preserve an ordinary cache hit that already extends
@@ -10037,7 +10799,7 @@ def _report_sparse_progress(processed: int, total: int) -> None:
cleanup_rope(self.model)
request.specprefill_indices = None
tracker.remove(request.request_id)
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
self._cleanup_prefill_abort_request(request)
continue
except Exception as e:
@@ -10116,7 +10878,7 @@ def _report_sparse_progress(processed: int, total: int) -> None:
try:
done = self._step_prefill_chunk(state)
except _PrefillAbortedError:
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
self._cleanup_prefill_abort_request(request)
continue
except _PrefillEvictionNeeded as e:
@@ -10142,7 +10904,7 @@ def _report_sparse_progress(processed: int, total: int) -> None:
self.requests.pop(request.request_id, None)
self._clear_request_admission_bookkeeping(request.request_id)
get_prefill_tracker().remove(request.request_id)
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
rejected_outputs.append(
_prefill_memory_exception_output(request.request_id, e)
)
@@ -10165,7 +10927,7 @@ def _report_sparse_progress(processed: int, total: int) -> None:
get_prefill_tracker().remove(request.request_id)
# Drop Metal cache pool buffers held by the aborted
# first chunk's forward / mx.eval transients.
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
if self._requeue_or_fail_prefill(request, e):
continue
rejected_outputs.append(
@@ -10180,7 +10942,7 @@ def _report_sparse_progress(processed: int, total: int) -> None:
if done:
self._emit_final_boundary_if_needed(state)
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
get_prefill_tracker().remove(request.request_id)
self._insert_prefilled_request(request, state, scheduled)
else:
@@ -10225,7 +10987,7 @@ def _report_sparse_progress(processed: int, total: int) -> None:
self.requests.pop(request.request_id, None)
self._clear_request_admission_bookkeeping(request.request_id)
get_prefill_tracker().remove(request.request_id)
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
rejected_outputs.append(
_prefill_memory_exception_output(request.request_id, e)
)
@@ -10247,7 +11009,7 @@ def _report_sparse_progress(processed: int, total: int) -> None:
get_prefill_tracker().remove(request.request_id)
# Drop Metal cache pool buffers held by the aborted
# chunk's forward / mx.eval transients.
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
if self._requeue_or_fail_prefill(request, e):
continue
rejected_outputs.append(
@@ -10279,7 +11041,11 @@ def _report_sparse_progress(processed: int, total: int) -> None:
extra = request.vlm_extra_kwargs or {}
captured = extra.get("_captured_rope_deltas")
if captured is not None:
- if hasattr(captured, "item"):
+ if isinstance(captured, mx.array):
+ request.rope_deltas = float(
+ captured.reshape(-1)[0].item()
+ )
+ elif hasattr(captured, "item"):
request.rope_deltas = float(captured.item())
else:
request.rope_deltas = float(captured)
@@ -10616,9 +11382,15 @@ def _process_batch_responses(
raw_cache = getattr(response, "prompt_cache", None)
if raw_cache is not None:
try:
- # SpecPrefill: sparse KV data can't be stored in
- # paged cache (hash mismatch with full token IDs).
- if request.specprefill_indices is not None:
+ # Sparse or unsupported layouts cannot round-trip through
+ # paged storage. Skip tensor extraction as well as writing.
+ if (
+ request.specprefill_indices is not None
+ or (
+ self.block_aware_cache is not None
+ and self._model_has_unreconstructible_cache()
+ )
+ ):
raw_cache = None
# For paged cache, extract actual tensor states
@@ -10630,6 +11402,9 @@ def _process_batch_responses(
if extracted_cache:
request._extracted_cache = extracted_cache
request._model_cache_config = model_cache_config
+ self._capture_finished_boundary_snapshot(
+ request, raw_cache
+ )
logger.debug(
f"Extracted {len(extracted_cache)} layer states "
f"for request {request_id}"
@@ -10731,7 +11506,10 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None:
# prep, no host memcpy, no SSD write. They still take
# the block leak-guard branch below so their paged
# blocks are released for eviction.
- skip_store = getattr(request, "skip_cache_store", False)
+ skip_store = (
+ getattr(request, "skip_cache_store", False)
+ or self._model_has_unreconstructible_cache()
+ )
if skip_store or (
hasattr(request, "_extracted_cache")
and request._extracted_cache is not None
@@ -10968,13 +11746,27 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None:
f"{len(request.output_token_ids)} output)"
)
except _BoundaryStoreUnavailable:
- logger.debug(
- "Skipping cache store for %s: no boundary-aligned "
- "snapshot for non-sliceable cache state (all "
- "captures skipped, e.g. by the speculative-decode "
- "skew guard); storing live state would corrupt "
+ available_boundaries = len(
+ self._boundary_cache_snapshots.get(request_id, {})
+ )
+ self._boundary_snapshot_diagnostics.record(
+ "store_skip",
+ reason="boundary_snapshot_unavailable",
+ request_id=request_id,
+ token_count=len(cacheable_sequence),
+ block_size=self.config.paged_cache_block_size,
+ available_boundaries=available_boundaries,
+ )
+ logger.info(
+ "Skipping cache store for %s: reason=%s "
+ "tokens=%d block_size=%d available_boundaries=%d; "
+ "storing live non-sliceable state would corrupt "
"later prefix hits",
request_id,
+ "boundary_snapshot_unavailable",
+ len(cacheable_sequence),
+ self.config.paged_cache_block_size,
+ available_boundaries,
)
block_table = None
if self.paged_cache_manager:
@@ -11154,6 +11946,8 @@ def _recover_from_cache_error(self) -> None:
if self.block_aware_cache is not None:
self.block_aware_cache.clear()
self._cache_rate_tracker.clear()
+ self._boundary_snapshot_diagnostics.clear()
+ self._last_prefix_cache_lookup = None
# Clear UID mappings
_unregister_uid_rows_for_model(self.model)
@@ -11194,7 +11988,7 @@ def _recover_from_generation_overflow_error(self) -> None:
self._output_parser_sessions.clear()
try:
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
except Exception as e:
logger.warning(
"Metal cache clear failed during generation overflow recovery: %s",
@@ -11522,6 +12316,11 @@ def step(self) -> SchedulerOutput:
Returns:
SchedulerOutput with results of this step
"""
+ # Bind on the thread that runs model forwards. Scheduler construction
+ # can happen on a shared event-loop thread, while every engine executes
+ # steps on its own worker. The setter is idempotent for repeated steps.
+ set_unfused_headroom_provider(self._sdpa256_unfused_headroom)
+
output = SchedulerOutput()
# Publish decode activity for cross-engine prefill fairness (a
@@ -11663,8 +12462,15 @@ def step(self) -> SchedulerOutput:
self, "_tokens_since_clear_cache", 0
) + len(responses)
if self._tokens_since_clear_cache >= 1024:
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
self._tokens_since_clear_cache = 0
+ # Refresh the executor-owned MLX active-memory sample.
+ # The background enforcer reads this cached value
+ # during active decode; without a decode-side refresh
+ # it stays frozen at the last prefill's reading for
+ # the whole generation, blinding the hard-watermark
+ # abort to decode-time growth (#3226).
+ self._current_usage_bytes()
except _PrefillAbortedError:
# Prefill was interrupted by a pending abort.
@@ -11774,7 +12580,7 @@ def step(self) -> SchedulerOutput:
if self._consume_pressure_clear():
should_clear = True
if should_clear:
- _sync_and_clear_cache(self._stream)
+ Scheduler._clear_cache(self)
# Route preflight cannot call mx.get_active_memory() from the
# event-loop thread, so publish a fresh executor-owned sample once
# the deferred pool reclaim has completed.
@@ -11906,6 +12712,8 @@ def reset(self) -> None:
if self.block_aware_cache is not None:
self.block_aware_cache.clear()
self._cache_rate_tracker.clear()
+ self._boundary_snapshot_diagnostics.clear()
+ self._last_prefix_cache_lookup = None
# Clear detokenizers
self._request_detokenizers.clear()
@@ -12003,6 +12811,22 @@ def shutdown(self) -> None:
f"{len(not_done)} async store_cache future(s)"
)
self._drain_pending_async_removes()
+ try:
+ clear_future = self._store_cache_executor.submit(
+ clear_thread_streams
+ )
+ clear_future.result(timeout=FATAL_TEARDOWN_TIMEOUT_S)
+ except concurrent.futures.TimeoutError:
+ fatal_exit(
+ "Scheduler shutdown timed out after "
+ f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s while clearing "
+ "the store-cache worker's MLX streams"
+ )
+ except Exception as exc:
+ fatal_exit(
+ "Scheduler store-cache worker stream cleanup failed: "
+ f"{exc!r}"
+ )
self._store_cache_executor.shutdown(wait=False)
# Final drain after the bounded wait. If all workers finished
# before the timeout, skipped entries are now drainable. If not,
@@ -12217,15 +13041,22 @@ def _dtype_matches(dtype: Any, expected: Any) -> bool:
else:
dtype_size = tq_dtype_size
- kv_bytes_per_token = (
- estimate_mla_kv_bytes_per_token(
+ kv_bytes_per_token = None
+ if estimate_qwen4_exp_kv_bytes_per_token is not None:
+ kv_bytes_per_token = estimate_qwen4_exp_kv_bytes_per_token(
+ config,
+ cache_list_for_tq,
+ base_dtype_size,
+ )
+ if (
+ kv_bytes_per_token is None
+ and estimate_mla_kv_bytes_per_token is not None
+ ):
+ kv_bytes_per_token = estimate_mla_kv_bytes_per_token(
config,
cache_list_for_tq,
base_dtype_size,
)
- if estimate_mla_kv_bytes_per_token is not None
- else None
- )
prefill_memory_profile = (
make_prefill_memory_profile(
config,
@@ -12880,6 +13711,13 @@ def get_ssd_cache_stats(self) -> dict[str, Any] | None:
if self.block_aware_cache is not None:
prefix_stats = self.block_aware_cache.get_stats_dict()
stats["prefix_cache"] = prefix_stats
+ stats["boundary_snapshots"] = (
+ self._boundary_snapshot_diagnostics.snapshot()
+ )
+ if self._last_prefix_cache_lookup is not None:
+ stats["last_prefix_lookup"] = dict(
+ self._last_prefix_cache_lookup
+ )
specprefill_cache_stats = {
"target_static_hits": prefix_stats["exact_prefix_hits"],
"target_static_misses": prefix_stats["exact_prefix_misses"],
diff --git a/omlx/server.py b/omlx/server.py
index 72a600687c..f994498c6c 100644
--- a/omlx/server.py
+++ b/omlx/server.py
@@ -465,6 +465,48 @@ async def _bonjour_supervisor() -> None:
bonjour_task = asyncio.create_task(_bonjour_supervisor())
+ # Cluster v2: always-on peer discovery (mDNS + IPv6 multicast fallback +
+ # manual + Tailscale). Best-effort: discovery failures must never block
+ # serving. OMLX_DISCOVERY=0 disables it for hostile networks.
+ discovery_service = None
+ if (
+ distributed_inference_enabled()
+ and os.environ.get("OMLX_DISCOVERY", "1").strip().lower()
+ not in {"0", "false", "no", "off"}
+ ):
+ try:
+ from .cluster.discovery import (
+ DiscoveryConfig,
+ DiscoveryService,
+ configure_discovery_service,
+ load_cluster_name,
+ )
+ from .cluster.identity import get_node_identity
+ from .cluster.registry import get_device_registry
+
+ cluster_base = (
+ Path(_server_state.global_settings.base_path)
+ if _server_state.global_settings is not None
+ else Path.home() / ".omlx"
+ )
+ discovery_service = DiscoveryService(
+ get_node_identity(),
+ get_device_registry(),
+ DiscoveryConfig(
+ cluster_name=load_cluster_name(cluster_base),
+ http_port=(
+ _server_state.global_settings.server.port
+ if _server_state.global_settings is not None
+ else 8000
+ )
+ ),
+ )
+ configure_discovery_service(discovery_service)
+ await asyncio.to_thread(discovery_service.start)
+ except Exception as exc: # pragma: no cover - defensive
+ logger.warning("Cluster discovery service failed to start: %s", exc)
+ discovery_service = None
+
# Start process memory enforcer if configured
if (
_server_state.global_settings is not None
@@ -499,6 +541,11 @@ async def _bonjour_supervisor() -> None:
_server_state.engine_pool._get_admission_soft_target = (
enforcer.get_admission_soft_target
)
+ # Resident-vs-mmap is a throughput call and must not read the
+ # instantaneous ceiling, which dips right after a model swap.
+ _server_state.engine_pool._get_residency_ceiling = (
+ enforcer.get_residency_ceiling
+ )
enforcer.start()
# Startup: Preload pinned models in the background so uvicorn binds the
@@ -566,6 +613,14 @@ async def _ttl_check_loop():
await bonjour_task
if bonjour_publisher is not None:
bonjour_publisher.stop()
+ if discovery_service is not None:
+ try:
+ from .cluster.discovery import configure_discovery_service
+
+ await asyncio.to_thread(discovery_service.stop)
+ configure_discovery_service(None)
+ except Exception as exc: # pragma: no cover - defensive
+ logger.warning("Cluster discovery service failed to stop: %s", exc)
if preload_task is not None and not preload_task.done():
# SIGTERM arrived while pinned models were still loading. Cancel the
# await; engine_pool.shutdown() below unloads whatever finished.
@@ -672,6 +727,19 @@ def _register_cluster_routes() -> None:
Depends(require_distributed_inference_enabled),
],
)
+ # Cluster v2 model-sync manifest: admin-gated like the rest of the
+ # cluster surface; peers use it to compare model contents before sync.
+ from .cluster.modelsync import manifest_router as cluster_manifest_router
+ from .cluster.modelsync import set_modelsync_getters
+
+ set_modelsync_getters(get_engine_pool)
+ app.include_router(
+ cluster_manifest_router,
+ dependencies=[
+ Depends(require_admin),
+ Depends(require_distributed_inference_enabled),
+ ],
+ )
# The bootstrap bytes are public but pinned by SHA-256 in an admin-created
# command. Claim/source/complete authenticate with one-time enrollment
# credentials, not the browser's admin cookie.
@@ -679,6 +747,32 @@ def _register_cluster_routes() -> None:
cluster_join_router,
dependencies=[Depends(require_distributed_inference_enabled)],
)
+ # Cluster v2: /api/cluster/node_id is a deliberately unauthenticated,
+ # rate-limited probe peers use to verify announced addresses before any
+ # pairing trust exists; /api/cluster/devices requires admin per-route.
+ from .cluster.discovery_routes import discovery_router
+
+ app.include_router(
+ discovery_router,
+ dependencies=[Depends(require_distributed_inference_enabled)],
+ )
+ # Cluster v2 pairing (Module B): pair/request carries only a salted PBKDF2
+ # verifier bound to the node and SSH identities; pair/status returns a
+ # code-encrypted cluster key only after admin approval. Approve, deny, and
+ # unpair are admin-only like every other cluster mutation.
+ from .cluster.pairing_routes import pair_admin_router, pair_router
+
+ app.include_router(
+ pair_router,
+ dependencies=[Depends(require_distributed_inference_enabled)],
+ )
+ app.include_router(
+ pair_admin_router,
+ dependencies=[
+ Depends(require_admin),
+ Depends(require_distributed_inference_enabled),
+ ],
+ )
_cluster_routes_registered = True
@@ -1974,15 +2068,49 @@ def init_server(
_server_state.engine_pool = EnginePool(
scheduler_config=scheduler_config,
)
- from .cluster.enrollment import configure_cluster_enrollment
+ from .cluster.enrollment import configure_cluster_enrollment, get_cluster_enrollment
from .cluster.incidents import configure_cluster_incidents
- from .cluster.registry import configure_cluster_registry
+ from .cluster.pairing import configure_pairing_manager
+ from .cluster.registry import (
+ configure_cluster_registry,
+ configure_device_registry,
+ get_device_registry,
+ )
from .cluster.strategy_benchmarks import configure_strategy_benchmark_store
_server_state.engine_pool._cluster_registry = configure_cluster_registry(base_path)
configure_cluster_enrollment(base_path)
configure_cluster_incidents(base_path)
configure_strategy_benchmark_store(base_path)
+ # Cluster v2: stable node identity + trusted device inventory. Best
+ # effort — a failure here must never block local inference. Configured
+ # before the pairing manager so pairing approvals persist into the real
+ # device registry instead of the schema-compatible fallback store.
+ try:
+ from .cluster.identity import configure_node_identity
+
+ configure_node_identity(base_path)
+ configure_device_registry(base_path / "cluster" / "devices.json")
+ except Exception as exc: # pragma: no cover - defensive
+ logger.warning("Cluster v2 identity/device stores unavailable: %s", exc)
+ try:
+ device_registry = get_device_registry()
+ except RuntimeError:
+ device_registry = None
+ # Cluster v2 pairing manager, bridged onto Module A's DeviceRegistry when
+ # available (DeviceRegistryBridge adapts the API and fails loudly on
+ # drift); otherwise the schema-compatible fallback store is used. Resolve
+ # capabilities lazily because the discovery service starts later.
+ from .cluster.discovery import announced_addrs, announced_caps
+
+ configure_pairing_manager(
+ base_path,
+ registry=device_registry,
+ enrollment_store=get_cluster_enrollment(),
+ caps_provider=announced_caps,
+ address_provider=announced_addrs,
+ http_port=global_settings.server.port if global_settings else 8000,
+ )
# Discover models (use pinned models from settings file)
_server_state.engine_pool._settings_manager = _server_state.settings_manager
diff --git a/omlx/settings.py b/omlx/settings.py
index 4622e0c7f5..baeb2c9409 100644
--- a/omlx/settings.py
+++ b/omlx/settings.py
@@ -176,6 +176,15 @@ class ServerSettings:
burst_decode_mode: str = DEFAULT_BURST_DECODE_MODE
preserve_mid_system_cache: bool = True
distributed_inference_enabled: bool = False
+ # Human-readable size, same grammar as cache limits ("100MB", "1GB").
+ max_audio_upload_size: str = "100MB"
+
+ def max_audio_upload_bytes(self) -> int:
+ """Configured audio upload limit in bytes. Non-positive sizes raise ValueError."""
+ size = parse_size(self.max_audio_upload_size)
+ if size <= 0:
+ raise ValueError("max_audio_upload_size must be positive")
+ return size
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary."""
@@ -199,6 +208,7 @@ def from_dict(cls, data: dict[str, Any]) -> ServerSettings:
"distributed_inference_enabled",
False,
),
+ max_audio_upload_size=data.get("max_audio_upload_size", "100MB"),
)
@@ -1087,6 +1097,8 @@ def _apply_env_overrides(self) -> None:
self.server.preserve_mid_system_cache = (
preserve_mid_system_cache.strip().lower() in {"1", "true", "yes", "on"}
)
+ if max_audio_upload_size := os.getenv("OMLX_MAX_AUDIO_UPLOAD_SIZE"):
+ self.server.max_audio_upload_size = max_audio_upload_size
# Model settings
if model_dir := os.getenv("OMLX_MODEL_DIR"):
@@ -1224,6 +1236,11 @@ def _apply_cli_overrides(self, args: Any, *, include_api_key: bool = True) -> No
self.server.log_level = args.log_level
if hasattr(args, "sse_keepalive_mode") and args.sse_keepalive_mode is not None:
self.server.sse_keepalive_mode = args.sse_keepalive_mode
+ if (
+ hasattr(args, "max_audio_upload_size")
+ and args.max_audio_upload_size is not None
+ ):
+ self.server.max_audio_upload_size = args.max_audio_upload_size
# Model settings
if hasattr(args, "model_dir") and args.model_dir is not None:
@@ -1487,6 +1504,13 @@ def validate(self) -> list[str]:
f"(must be one of {valid_keepalive_modes})"
)
+ try:
+ audio_upload_size = parse_size(self.server.max_audio_upload_size)
+ if audio_upload_size <= 0:
+ errors.append("max_audio_upload_size must be positive")
+ except (AttributeError, TypeError, ValueError) as e:
+ errors.append(f"Invalid max_audio_upload_size: {e}")
+
# Memory guard tier validation
if self.memory.memory_guard_tier not in VALID_MEMORY_GUARD_TIERS:
errors.append(
diff --git a/omlx/speculative/vlm_mtp.py b/omlx/speculative/vlm_mtp.py
index 7637d0ac7e..e3a8082010 100644
--- a/omlx/speculative/vlm_mtp.py
+++ b/omlx/speculative/vlm_mtp.py
@@ -42,28 +42,47 @@
import mlx.core as mx
import mlx.nn as nn
-from mlx_vlm.speculative import load_drafter as _vlm_load_drafter
+from ..patches.mlx_vlm_mlx0322_compat import (
+ apply_mlx_vlm_mlx0322_compat_patch,
+)
+
+# Install the MLX 0.32.2 source hook before importing mlx-vlm.speculative.
+# Importing that package eagerly loads common, mtp, and utils; applying the
+# hook afterwards can leave their copied generation_stream globals pointing
+# at the stream from the pre-reload common module.
+apply_mlx_vlm_mlx0322_compat_patch()
+
+from mlx_vlm.speculative import common as _vlm_common # noqa: E402, I001
+from mlx_vlm.speculative import load_drafter as _vlm_load_drafter # noqa: E402
# The round loops dispatch their target-verify and cache-rollback forwards
# inside ``with mx.stream(generation_stream)``, using mlx-vlm's own
# thread-local stream — a different object from mlx-lm's generation_stream
# and from the per-engine stream. Draining the MTP work means draining this
# one, resolved on the thread that advances the round loop.
-from mlx_vlm.speculative.common import generation_stream as _vlm_generation_stream
# PR #1169 (f96138e) moved the MTP round loop helpers from ``mlx_vlm.generate``
# into ``mlx_vlm.speculative.utils``. Import directly from the new location —
# the symbols are still ``_``-prefixed but this is now their canonical home.
-from mlx_vlm.speculative.utils import _mtp_rounds, _mtp_rounds_batch # noqa: SLF001
+from mlx_vlm.speculative.utils import ( # noqa: E402, SLF001
+ _mtp_rounds,
+ _mtp_rounds_batch,
+)
try:
- from mlx_vlm.speculative.mtp import _buffer_mtp_target_cache # noqa: SLF001
+ from mlx_vlm.speculative.mtp import ( # noqa: E402, SLF001
+ _buffer_mtp_target_cache,
+ )
except Exception: # pragma: no cover - compatibility with older mlx-vlm
+
def _buffer_mtp_target_cache(*_args: Any, **_kwargs: Any) -> None:
return None
-from ..utils.metal_sync import _sync_and_clear_cache
-from ..utils.model_loading import materialize_lazy_state
+
+from ..utils.metal_sync import _sync_and_clear_cache # noqa: E402
+from ..utils.model_loading import materialize_lazy_state # noqa: E402
+
+_vlm_generation_stream = _vlm_common.generation_stream
logger = logging.getLogger(__name__)
diff --git a/omlx/utils/compile_cache.py b/omlx/utils/compile_cache.py
deleted file mode 100644
index ba9f5efad4..0000000000
--- a/omlx/utils/compile_cache.py
+++ /dev/null
@@ -1,108 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-"""Thread-local MLX compile-cache clearing.
-
-MLX moved its ``mx.compile`` graph cache to a C++ ``thread_local``
-``CompilerCache`` (ml-explore/mlx #3280). When a thread that ran
-``@mx.compile`` functions is destroyed, ``~CompilerCache`` frees the cached
-graphs' Python objects from a thread-exit handler WITHOUT holding the GIL,
-which aborts the process with ``Fatal Python error: PyThreadState_Get: ...
-GIL is released`` (the underlying frame is ``_pthread_exit ->
-ThreadLocalVariables::finalizeList -> CompilerCache::~CompilerCache ->
-tupledealloc``). Any model with module-scope ``@mx.compile`` graphs hits this:
-DeepSeek V4 on unload (the per-engine worker thread exits at close), Step 3.x
-on process exit.
-
-MLX exposes no Python API to clear the compile cache. Its own atexit-based
-clear at ``transforms.cpp`` is dead code (the registration lambda is never
-invoked) and would run on the main thread anyway, so it cannot clear a worker
-thread's thread_local cache. But the C++ symbol
-``mlx::core::detail::compile_clear_cache()`` is exported from ``libmlx.dylib``,
-so we resolve it via ctypes and call it ON the worker thread (with the GIL
-held, via ``ctypes.PyDLL``) right before that thread is torn down. The cache
-ends up empty, so ``~CompilerCache`` becomes a no-op and the thread can exit
-normally.
-
-If the symbol cannot be resolved (e.g. a future MLX rename or a non-macOS
-build), the helper is a no-op and callers fall back to keeping the worker
-thread alive for the process lifetime instead of exiting it.
-"""
-
-import ctypes
-import logging
-import os
-import threading
-
-import mlx.core as mx
-
-logger = logging.getLogger(__name__)
-
-# Itanium-mangled ``mlx::core::detail::compile_clear_cache()`` (no args, void).
-# "19" is the length of "compile_clear_cache".
-_CLEAR_SYMBOL = "_ZN3mlx4core6detail19compile_clear_cacheEv"
-
-_resolve_lock = threading.Lock()
-_resolved = False
-_clear_fn = None # ctypes callable, or None if unresolvable
-
-
-def _resolve_clear_fn():
- """Resolve compile_clear_cache from libmlx.dylib once (thread-safe)."""
- global _resolved, _clear_fn
- if _resolved:
- return _clear_fn
- with _resolve_lock:
- if _resolved:
- return _clear_fn
- _resolved = True
- try:
- lib_dir = os.path.join(os.path.dirname(mx.__file__), "lib")
- libmlx = os.path.join(lib_dir, "libmlx.dylib")
- if not os.path.exists(libmlx):
- logger.warning(
- "MLX compile-cache clear unavailable: %s not found", libmlx
- )
- return None
- # PyDLL keeps the GIL held during the call (CDLL would release it).
- # The cache clear decrefs Python objects, so the GIL MUST be held.
- lib = ctypes.PyDLL(libmlx)
- fn = None
- for name in (_CLEAR_SYMBOL, "_" + _CLEAR_SYMBOL):
- try:
- fn = getattr(lib, name)
- break
- except AttributeError:
- continue
- if fn is None:
- raise AttributeError(_CLEAR_SYMBOL)
- fn.restype = None
- fn.argtypes = []
- _clear_fn = fn
- logger.info("MLX compile-cache clear resolved (%s)", _CLEAR_SYMBOL)
- except (OSError, AttributeError) as e:
- logger.warning(
- "MLX compile-cache clear unavailable (%s); MLX worker threads "
- "will be kept alive as a fallback to avoid the thread-exit "
- "~CompilerCache crash",
- e,
- )
- _clear_fn = None
- return _clear_fn
-
-
-def compile_cache_clear_available() -> bool:
- """True if the thread-local compile-cache clear symbol is resolvable."""
- return _resolve_clear_fn() is not None
-
-
-def clear_thread_compile_cache() -> None:
- """Clear the CALLING thread's MLX thread-local compile cache.
-
- MUST run ON the thread whose cache should be cleared (the cache is C++
- ``thread_local``). Call it on an MLX worker thread right before that thread
- is destroyed so ``~CompilerCache`` runs on an empty cache and never frees
- Python objects from a GIL-less thread-exit handler. No-op if the symbol
- could not be resolved.
- """
- fn = _resolve_clear_fn()
- if fn is not None:
- fn()
diff --git a/omlx/utils/image.py b/omlx/utils/image.py
index 2b0a6f108d..56e4f6a97c 100644
--- a/omlx/utils/image.py
+++ b/omlx/utils/image.py
@@ -17,7 +17,6 @@
from ..exceptions import InvalidRequestError
-
_IMAGE_INPUT_ERROR = (
"Image inputs must be base64 data URIs "
"(data:image/...;base64,...). Remote URLs and local file paths are not supported."
@@ -209,6 +208,12 @@ def extract_images_from_messages(
else:
audio.append(data)
+ elif part_type in ("video", "video_url", "input_video"):
+ raise InvalidRequestError(
+ "Video input is not supported by oMLX.",
+ field="messages",
+ )
+
new_msg = {"role": role, "content": "\n".join(text_parts) if text_parts else ""}
# Preserve extra fields
for key in msg:
diff --git a/omlx/utils/metal_sync.py b/omlx/utils/metal_sync.py
index 1c129b764d..3b4edbe5f1 100644
--- a/omlx/utils/metal_sync.py
+++ b/omlx/utils/metal_sync.py
@@ -16,6 +16,7 @@
"""
import threading
+from contextlib import suppress
import mlx.core as mx
from mlx_lm.generate import generation_stream
@@ -33,6 +34,20 @@
_mx_buffer_access_lock = threading.RLock()
+def clear_thread_streams() -> None:
+ """Release every MLX stream owned by the current worker thread.
+
+ MLX keeps a per-thread stream registry. Synchronizing and clearing the
+ buffer cache does not remove those entries, so a worker that touched MLX
+ must call ``mx.clear_streams()`` immediately before it exits.
+ """
+ # A ThreadPoolExecutor starts lazily. If this is the worker's first task,
+ # no default stream exists yet and there is nothing to synchronize.
+ with suppress(RuntimeError):
+ mx.synchronize()
+ mx.clear_streams()
+
+
def _sync_and_clear_cache(stream=None):
"""Synchronize in-flight GPU work before clearing the Metal buffer cache.
diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py
index a3816b9ab7..2acfd9f522 100644
--- a/omlx/utils/model_loading.py
+++ b/omlx/utils/model_loading.py
@@ -20,6 +20,8 @@
_CKPT_TEXT_PREFIX = "model.language_model."
_RUNTIME_TEXT_PREFIX = "language_model.model."
+_MATERIALIZE_EVAL_CHUNK = 8
+
_MLX_LM_LOAD_CONFIG_PATCHED = False
_REMOTE_CODE_METADATA_PATTERNS = [
@@ -398,7 +400,7 @@ def maybe_apply_pre_load_patches(
declares ``model_type == "glm_moe_dsa"``. Required because pinned
mlx-lm exposes it as a bare DeepSeek-V3.2 subclass and cannot load
checkpoints whose shared DSA layers carry no indexer weights.
- - Native MTP patch (PR 990 + PR 15) when the config declares MTP heads
+ - Lightning MTP patch (PR 990 + PR 15) when the config declares MTP heads
on a supported model_type. Always applied for sanitize correctness;
head attachment is gated by ``model_settings.mtp_enabled``.
- mlx-vlm side MTP runtime + nested-visual patches when ``for_vlm`` is
@@ -414,8 +416,14 @@ def maybe_apply_pre_load_patches(
and crashes with KeyError unless the mlx_vlm_mtp sanitize replacement
is installed first. ``for_vlm=True`` is only passed by
``VLMBatchedEngine``, so no separate ``vision_config`` gate is needed.
- Both patches inject modules into ``sys.modules`` and replace mlx-lm
- internals; gating keeps non-affected models at zero cost.
+ - mlx-vlm MLX 0.32.2 compatibility backport when ``for_vlm`` is True.
+ This installs before model-module imports and carries only upstream PRs
+ #1949, #1982, and #2006, without moving the deliberately stable mlx-vlm
+ pin.
+ Some model patches inject modules into ``sys.modules`` or replace mlx-lm
+ internals; the mlx-vlm compatibility hook instead transforms only the
+ affected pinned sources as they load. Gating keeps non-affected models at
+ zero cost.
Safe to call repeatedly; the patches are idempotent.
"""
@@ -428,6 +436,13 @@ def maybe_apply_pre_load_patches(
_patch_mlx_lm_load_config()
+ if for_vlm:
+ from ..patches.mlx_vlm_mlx0322_compat import (
+ apply_mlx_vlm_mlx0322_compat_patch,
+ )
+
+ apply_mlx_vlm_mlx0322_compat_patch()
+
# Machine-conditioned, model-independent: reroute sorted gather_qmm
# around the defective M5 NAX kernels (issue #2267). Install is cheap
# and self-gating — a canary at the first matching call decides
@@ -616,6 +631,75 @@ def maybe_apply_pre_load_patches(
model_name,
)
+ if for_vlm and model_type == "qwen4_exp":
+ from ..patches.mlx_vlm_qwen4_exp_compat import (
+ apply_mlx_vlm_qwen4_exp_compat_patch,
+ configure_qwen4_exp_runtime,
+ )
+
+ if apply_mlx_vlm_qwen4_exp_compat_patch():
+ logger.info(
+ "Qwen4-Exp mlx-vlm compatibility patch applied for %s",
+ model_name,
+ )
+ mtp_requested = bool(
+ model_settings is not None and getattr(model_settings, "mtp_enabled", False)
+ )
+ has_mtp_weights = _checkpoint_has_mtp_weights(model_name)
+ mtp_active = mtp_requested and has_mtp_weights
+ if mtp_requested and not has_mtp_weights:
+ logger.warning(
+ "Qwen4-Exp Lightning MTP was requested for %s, but no embedded "
+ "MTP tensors were found",
+ model_name,
+ )
+
+ from ..patches.mlx_lm_mtp import (
+ apply_mlx_lm_mtp_patch,
+ set_mtp_active,
+ set_mtp_depth,
+ )
+
+ set_mtp_active(mtp_active)
+ depth = (
+ getattr(model_settings, "mtp_num_draft_tokens", None)
+ if model_settings is not None
+ else None
+ )
+ # Qwen4-Exp uses the same adaptive draft-depth controller as the
+ # general Lightning MTP path. A single MTP hidden layer can be
+ # chained autoregressively, so default to the validated max depth 3.
+ set_mtp_depth(int(depth) if depth else 3)
+ if mtp_active and not apply_mlx_lm_mtp_patch():
+ logger.warning(
+ "Qwen4-Exp Lightning MTP dispatch patch failed for %s; "
+ "speculative decoding will remain inactive",
+ model_name,
+ )
+ set_mtp_active(False)
+ mtp_active = False
+ configure_qwen4_exp_runtime(
+ model_name,
+ mode=(
+ "mmap"
+ if model_settings is not None
+ and getattr(model_settings, "qwen4_ple_ssd_offload", False)
+ else "resident" if model_settings is not None else None
+ ),
+ mtp_enabled=mtp_active,
+ )
+
+ if for_vlm and model_type == "glm5_next":
+ from ..patches.mlx_vlm_glm5_next_compat import (
+ apply_mlx_vlm_glm5_next_compat_patch,
+ )
+
+ if apply_mlx_vlm_glm5_next_compat_patch():
+ logger.info(
+ "GLM-5.3 mlx-vlm compatibility patch applied for %s",
+ model_name,
+ )
+
# Apply the MTP patch whenever the model has MTP heads on a compatible
# model_type — even when mtp_enabled is False. The patch is required
# for *sanitize correctness*: stock mlx-lm Model.sanitize triggers a
@@ -771,7 +855,11 @@ def maybe_apply_pre_load_patches(
"load only)",
model_name,
)
- elif model_settings is not None and getattr(model_settings, "mtp_enabled", False):
+ elif (
+ model_type != "qwen4_exp"
+ and model_settings is not None
+ and getattr(model_settings, "mtp_enabled", False)
+ ):
logger.warning(
"mtp_enabled=True for %s but model is incompatible "
"(model_type=%r, mtp_heads=%s); MTP path will be inactive",
@@ -927,60 +1015,83 @@ def _nextn_weight_prefixes(model_path: str | Path) -> tuple[str, ...]:
config = json.loads((Path(model_path) / "config.json").read_text())
except Exception:
return ()
+ if config.get("model_type") == "qwen4_exp":
+ # The dedicated Qwen4 runtime constructs a root-level MTP module and
+ # can bind only the embedded mtp.* layouts. Extra nextn decoder layers
+ # must not make generic callers report this checkpoint as compatible.
+ return ()
return _nextn_weight_prefixes_from_config(config)
-def _checkpoint_has_mtp_weights(model_path: str | Path) -> bool:
- """True iff the checkpoint at *model_path* ships any MTP weight tensor.
-
- Matches both the ``mtp.*`` naming and the nextn layout (extra decoder
- layers past ``num_hidden_layers``, see ``_nextn_weight_prefixes``).
-
- Some Qwen3.6 MoE VLM exports declare ``mtp_num_hidden_layers > 0`` in
- ``config.json`` but strip the MTP weights during conversion (e.g.
- ``unsloth/Qwen3.6-35B-A3B-UD-MLX-*bit``). Attaching ``MTPModule`` for
- such a checkpoint causes mlx-vlm's strict ``load_weights`` to fail with
- "Missing N parameters: language_model.mtp.*", the engine falls back to
- LLM, and vision is silently dropped (issue #1426).
-
- Reads ``model.safetensors.index.json`` when present (no shard I/O).
- Falls back to the first safetensors shard's metadata header. Returns
- False when neither resolves — callers treat that as "no MTP weights"
- (the conservative choice: skip MTPModule attachment).
- """
+def _checkpoint_weight_prefix(
+ model_path: str | Path,
+ prefixes: tuple[str, ...],
+) -> str | None:
+ """Return the first supported prefix present in a checkpoint."""
p = Path(model_path)
if not p.is_dir():
- return False
-
- prefixes = _MTP_WEIGHT_PREFIXES + _nextn_weight_prefixes(p)
+ return None
index_path = p / "model.safetensors.index.json"
if index_path.exists():
try:
data = json.loads(index_path.read_text())
weight_map = data.get("weight_map") or {}
- return any(k.startswith(prefixes) for k in weight_map)
+ for prefix in prefixes:
+ if any(key.startswith(prefix) for key in weight_map):
+ return prefix
+ return None
except Exception as e:
logger.debug("Failed to read %s for mtp weight scan: %s", index_path, e)
shards = sorted(p.glob("*.safetensors"))
if not shards:
- return False
+ return None
try:
import safetensors
except Exception as e:
logger.debug("safetensors import failed for mtp weight scan: %s", e)
- return False
+ return None
for shard in shards:
try:
with safetensors.safe_open(str(shard), framework="numpy") as f:
- for k in f.keys():
- if k.startswith(prefixes):
- return True
+ keys = tuple(f.keys())
+ for prefix in prefixes:
+ if any(key.startswith(prefix) for key in keys):
+ return prefix
except Exception as e:
logger.debug("Failed to read %s header for mtp weight scan: %s", shard, e)
- return False
+ return None
+
+
+def _checkpoint_qwen4_mtp_weight_prefix(model_path: str | Path) -> str | None:
+ """Return the embedded MTP prefix supported by the Qwen4 runtime."""
+ return _checkpoint_weight_prefix(model_path, _MTP_WEIGHT_PREFIXES)
+
+
+def _checkpoint_has_mtp_weights(model_path: str | Path) -> bool:
+ """True iff the checkpoint at *model_path* ships any MTP weight tensor.
+
+ Matches both the ``mtp.*`` naming and compatible nextn layouts (extra
+ decoder layers past ``num_hidden_layers``, see ``_nextn_weight_prefixes``).
+ Qwen4-Exp is intentionally restricted to ``mtp.*`` because its dedicated
+ runtime cannot bind native nextn layers.
+
+ Some Qwen3.6 MoE VLM exports declare ``mtp_num_hidden_layers > 0`` in
+ ``config.json`` but strip the MTP weights during conversion (e.g.
+ ``unsloth/Qwen3.6-35B-A3B-UD-MLX-*bit``). Attaching ``MTPModule`` for
+ such a checkpoint causes mlx-vlm's strict ``load_weights`` to fail with
+ "Missing N parameters: language_model.mtp.*", the engine falls back to
+ LLM, and vision is silently dropped (issue #1426).
+
+ Reads ``model.safetensors.index.json`` when present (no shard I/O).
+ Falls back to the first safetensors shard's metadata header. Returns
+ False when neither resolves — callers treat that as "no MTP weights"
+ (the conservative choice: skip MTPModule attachment).
+ """
+ prefixes = _MTP_WEIGHT_PREFIXES + _nextn_weight_prefixes(model_path)
+ return _checkpoint_weight_prefix(model_path, prefixes) is not None
def _is_mtp_compatible(config: dict, model_type: str | None) -> bool:
@@ -1075,7 +1186,16 @@ def _scan_plain_object(obj: Any) -> None:
_scan_plain_object(value)
if arrays:
- mx.eval(arrays)
+ # Evaluate in bounded chunks rather than one mx.eval(arrays). A single
+ # eval over the whole parameter tree submits one Metal command buffer
+ # spanning every array; on a multi-hundred-GB checkpoint (e.g. the raw
+ # BF16 Qwen3.8-Flash-Next base, ~336 GB / 1676 arrays) that buffer
+ # exceeds the GPU command-buffer watchdog and aborts the process with
+ # "[METAL] Command buffer execution failed: Caused GPU Timeout Error
+ # (kIOGPUCommandBufferCallbackErrorTimeout)". Chunking bounds each
+ # command buffer; small models see only a handful of chunks. See #3179.
+ for start in range(0, len(arrays), _MATERIALIZE_EVAL_CHUNK):
+ mx.eval(arrays[start : start + _MATERIALIZE_EVAL_CHUNK])
def apply_post_load_transforms(model: Any, model_settings: Any = None) -> Any:
diff --git a/pyproject.toml b/pyproject.toml
index 1b8a1b3fe7..937b2a5330 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -3,13 +3,13 @@ requires = [
"setuptools>=61.0",
"wheel",
"cmake>=3.27",
- # Pin nanobind to match the ABI version MLX 0.32.0 was built with
- # (MLX pins nanobind v2.13.0 via FetchContent in its CMakeLists.txt).
+ # Pin nanobind to match the ABI version MLX 0.32.2 was built with
+ # (MLX pins nanobind v2.15.0 via FetchContent in its CMakeLists.txt).
# A mismatched nanobind isolates the `mlx` NB_DOMAIN, so custom kernel
# extensions (omlx.custom_kernels.*) reject every mlx.core.array at the
# type caster with `incompatible function arguments`.
- "nanobind==2.13.0",
- "mlx==0.32.0",
+ "nanobind==2.15.0",
+ "mlx==0.32.2",
]
build-backend = "setuptools.build_meta"
@@ -39,11 +39,11 @@ classifiers = [
]
dependencies = [
- # Vanilla MLX v0.32.0; optional custom kernels live under
+ # Vanilla MLX v0.32.2; optional custom kernels live under
# omlx.custom_kernels.* when built for release. The bundled kernel
# binaries are ABI-coupled to this exact mlx version — bumping the pin
# requires rebuilding them (OMLX_WITH_CUSTOM_KERNEL=1 setup.py build_ext).
- "mlx==0.32.0",
+ "mlx==0.32.2",
# mlx-lm from commit (ab1806e, v0.31.3) - transformers 5.13+
# NewlineTokenizer registration compatibility, DeepSeek/GLM DSA indexer
# RoPE fix, trust_remote_code load gate, transformers 5.7.0
@@ -99,7 +99,7 @@ dependencies = [
# cutoff (2026-04-23), and the last with the minimal dep tree
# (click/primp/lxml only; 9.14.2+ adds fake-useragent and httpx
# extras). Bump together with the cutoff.
- "ddgs==9.15.0",
+ "ddgs==9.16.0",
"tabulate>=0.9.0",
# Resource monitoring
"psutil>=5.9.0",
@@ -148,6 +148,13 @@ grammar = [
mcp = [
"mcp>=2.0.0,<3",
]
+cluster = [
+ # mDNS advertise/browse for cluster v2 peer discovery (_omlx._tcp.local.).
+ # Pure-Python; works in launchd agents. Absence disables mDNS only — the
+ # IPv6 multicast fallback, manual peer add, and Tailscale paths keep
+ # working (see omlx/cluster/discovery.py).
+ "zeroconf>=0.131.0",
+]
modelscope = [
"modelscope>=1.10.0",
]
@@ -262,6 +269,7 @@ include = ["omlx*"]
]
"omlx.eval" = ["data/*.jsonl"]
"omlx.custom_kernels.glm_moe_dsa" = ["*.metallib", "*.dylib", "*.so"]
+"omlx.custom_kernels.decode_fast" = ["*.metallib", "*.dylib", "*.so"]
"omlx.custom_kernels.minimax_m3" = ["*.metallib", "*.dylib", "*.so"]
"omlx.custom_kernels.qwen35_prefill" = ["*.metallib", "*.dylib", "*.so"]
@@ -269,7 +277,7 @@ include = ["omlx*"]
# mlx and mlx-lm are git-pinned; override transitive pins
# (e.g. mlx-audio -> mlx-lm==0.31.1) so the resolver accepts them.
override-dependencies = [
- "mlx==0.32.0",
+ "mlx==0.32.2",
"mlx-lm @ git+https://github.com/ml-explore/mlx-lm@ab1806e8f5d6aa035973af194a1b9198ab4754dc",
]
diff --git a/setup.py b/setup.py
index 22146dc54f..7d67bc6c60 100644
--- a/setup.py
+++ b/setup.py
@@ -54,6 +54,10 @@ def _custom_kernel_build_kwargs() -> dict:
"omlx.custom_kernels.bonsai._ext",
sourcedir="omlx/custom_kernels/bonsai/csrc",
),
+ extension.CMakeExtension(
+ "omlx.custom_kernels.decode_fast._ext",
+ sourcedir="omlx/custom_kernels/decode_fast/csrc",
+ ),
extension.CMakeExtension(
"omlx.custom_kernels.glm_moe_dsa._ext",
sourcedir="omlx/custom_kernels/glm_moe_dsa/csrc",
diff --git a/tests/conftest.py b/tests/conftest.py
index 8010b0df1f..1e5f29b309 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,3 +1,9 @@
+import os
+
+# MLX 0.32.2 runs fp32 GPU matmuls at TF32 precision on M5-class tensor units;
+# the fp32 parity tests assert 2e-5, which TF32 cannot hold. Test session only.
+os.environ.setdefault("MLX_ENABLE_TF32", "0")
+
# SPDX-License-Identifier: Apache-2.0
"""
Pytest configuration and fixtures for oMLX tests.
@@ -111,6 +117,18 @@ def parameters(self) -> Dict[str, Any]:
"""Return model parameters."""
return self._parameters
+ def make_cache(self) -> list:
+ """Build the per-layer prompt cache, like a real mlx-lm model.
+
+ The scheduler probes this to decide whether a stored prefix can be
+ rebuilt faithfully, so the double has to answer it. A plain llama-style
+ model builds ``KVCache`` layers; tests that need another cache class
+ override this attribute.
+ """
+ from mlx_lm.models.cache import KVCache
+
+ return [KVCache() for _ in range(self.config.num_hidden_layers)]
+
@pytest.fixture
def mock_tokenizer() -> MockTokenizer:
diff --git a/tests/test_admin_api_key.py b/tests/test_admin_api_key.py
index 39f69caa91..da7fac43b6 100644
--- a/tests/test_admin_api_key.py
+++ b/tests/test_admin_api_key.py
@@ -81,6 +81,58 @@ def test_list_models_includes_all_model_settings_fields(self):
assert settings_dict["max_tokens"] == 4096
assert settings_dict["temperature"] == 0.7
+ def test_list_models_reports_forced_qwen4_ple_offload(self, tmp_path):
+ from omlx.patches.mlx_vlm_qwen4_exp_compat.residency import (
+ Qwen4ExpResidencyEstimate,
+ )
+
+ model_path = tmp_path / "qwen4"
+ model_path.mkdir()
+ estimate = Qwen4ExpResidencyEstimate(
+ supported=True,
+ checkpoint_bytes=950,
+ ple_bytes=550,
+ resident_bytes=1000,
+ mmap_bytes=400,
+ )
+ pool = MagicMock()
+ pool.get_status.return_value = {
+ "models": [
+ {
+ "id": "qwen4",
+ "model_path": str(model_path),
+ "config_model_type": "qwen4_exp",
+ "estimated_size": 1000,
+ }
+ ]
+ }
+ pool._fallback_admission_ceiling.return_value = 500
+ manager = MagicMock()
+ manager.get_all_settings.return_value = {}
+ state = MagicMock(default_model=None)
+
+ with (
+ patch.object(admin_routes, "_get_engine_pool", return_value=pool),
+ patch.object(admin_routes, "_get_settings_manager", return_value=manager),
+ patch.object(admin_routes, "_get_server_state", return_value=state),
+ patch.object(admin_routes, "_get_global_settings", return_value=None),
+ patch.object(admin_routes, "_dflash_compat_for_model", return_value=(False, "")),
+ patch.object(admin_routes, "_mtp_compat_for_model", return_value=(False, "")),
+ patch.object(admin_routes, "_paroquant_compat_for_model", return_value=(False, "")),
+ patch(
+ "omlx.patches.mlx_vlm_qwen4_exp_compat.residency."
+ "qwen4_exp_residency_estimate",
+ return_value=estimate,
+ ),
+ ):
+ result = asyncio.run(admin_routes.list_models(is_admin=True))
+
+ model = result["models"][0]
+ assert model["qwen4_ple_ssd_offload_supported"] is True
+ assert model["qwen4_ple_ssd_offload_forced"] is True
+ assert model["qwen4_ple_resident_bytes"] == 1000
+ assert model["qwen4_ple_mmap_bytes"] == 400
+
def test_list_models_adds_display_name_without_changing_id(self, tmp_path):
"""Ensure nested model paths only affect UI display names."""
model_root = tmp_path / "models"
diff --git a/tests/test_admin_audio_upload_ui.py b/tests/test_admin_audio_upload_ui.py
new file mode 100644
index 0000000000..72277d2b2d
--- /dev/null
+++ b/tests/test_admin_audio_upload_ui.py
@@ -0,0 +1,44 @@
+import json
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+SETTINGS_TEMPLATE = ROOT / "omlx/admin/templates/dashboard/_settings.html"
+DASHBOARD_JS = ROOT / "omlx/admin/static/js/dashboard.js"
+
+AUDIO_UPLOAD_I18N_KEYS = {
+ "settings.advanced.uploads",
+ "settings.advanced.max_audio_upload_size",
+ "settings.advanced.max_audio_upload_size_hint",
+}
+
+
+def test_settings_template_exposes_audio_upload_limit_under_advanced_uploads():
+ template = SETTINGS_TEMPLATE.read_text()
+
+ advanced_start = template.index("