From e287c1fd2aa7ff1bd0bdd82c44da073f9e95b9a7 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:16:06 -0800 Subject: [PATCH 1/7] feat(provider): sandbox setup re-checks the add-on's plan on a set-up Mac and offers new slot counts (#1735) * feat(provider): sandbox setup re-checks the add-on's plan on a Mac that is set up and offers new slot counts * fix(provider): sandbox setup's free-space line counts the planned Linux jobs, and exit 4 says the installer refuses - "A macOS job needs about N GB more" now counts the disk the plan's slots take (diskShortfall: floor + the plan's slots + one more job - free). A Mac planned for 3 Linux jobs and no macOS job (the feedback's) gets a number instead of none. With no job planned it is unchanged. - The free-space line uses the agreed text and prints for the add-on's plan only: an unchanged plan on a set-up Mac and the fallback estimate keep today's output. - The offer asks "This Mac now fits Linux + macOS (installed: Linux + macOS). If a job is running, the installer refuses and changes nothing. Apply? [Y/n]", with no unverified pay claim. - On the installer's exit status 4: a job is running, so nothing changed; run setup again when it finishes; setup never passes the installer's --force, which would stop running jobs, unpaid. - Tests: the 3-Linux-slots shortfall, the unchanged report for the same disk-limited plan, and an apply refused with exit 4. * docs(provider): sandbox setup's free-space line, its macOS shortfall and the exit 4 refusal as built The CLI reference and the sandboxes guide give the agreed free-space text and N (the disk a macOS job needs beside the plan's slots, in GiB written as GB), the offer's prompt, that an unchanged plan keeps today's report, that a platform missing from status counts as 0, and that the installer refuses rather than waits while a job runs (exit 4), with setup never passing its --force. The changelog fragment follows. * refactor(provider): name the planned-disk rule beside its siblings and let setup's re-check say it reports first --- changelog.d/sandbox-setup-resize.md | 7 + docs/provider/cli-reference.md | 38 ++- docs/provider/sandboxes.md | 28 +- .../Sandbox/SandboxEligibility.swift | 20 +- .../Sandbox/SandboxSetupCommand.swift | 112 ++++++- .../Sandbox/SandboxSetupProgress.swift | 9 +- .../darkbloom/Sandbox/SandboxSlotChange.swift | 42 +++ .../DarkbloomCLITests/SandboxSetupTests.swift | 285 +++++++++++++++++- .../SandboxTestSupport.swift | 10 + 9 files changed, 510 insertions(+), 41 deletions(-) create mode 100644 changelog.d/sandbox-setup-resize.md create mode 100644 provider-swift/Sources/darkbloom/Sandbox/SandboxSlotChange.swift diff --git a/changelog.d/sandbox-setup-resize.md b/changelog.d/sandbox-setup-resize.md new file mode 100644 index 0000000000..4a381dae73 --- /dev/null +++ b/changelog.d/sandbox-setup-resize.md @@ -0,0 +1,7 @@ +### Sandbox setup offers the add-on's new plan on a Mac that is set up + +- Running `darkbloom sandbox setup` on a Mac that is set up now asks the Darkbloom Sandbox installer for the add-on's plan again (`--plan`, which changes nothing). When the plan's Linux and macOS job counts differ from the installed ones, setup shows the plan's CPU, memory and disk lines and asks, for example `This Mac now fits 1 Linux + 1 macOS (installed: 3 Linux + 0 macOS). If a job is running, the installer refuses and changes nothing. Apply? [Y/n]`. Yes reinstalls with the plan's counts; no prints the `--linux-slots`/`--macos-slots` command that applies it later. When the counts match, the output is exactly as before. +- With `--yes` or without a terminal, setup applies the plan only when it adds jobs and removes none; otherwise it prints `Not applied` and the command, and exits 0. +- While jobs run, setup skips the check and says to run it again once they finish. When the installer refuses because a job is running (exit 4), setup now says that a job is running, to run setup again when it finishes, and that it never passes the installer's `--force`, which would stop running jobs, which aren't paid. +- Explicit `--linux-slots`/`--macos-slots`, an installer without `--plan` and a failed download behave as before. A platform missing from the add-on's `status --json` counts as 0 slots. +- When the add-on's plan gives macOS no job for want of free disk space, setup adds one line: ``Free space here is what `df -h ~` shows as Avail; Finder also counts purgeable space, which macOS frees only when it needs to (restarting, or removing Time Machine local snapshots: `tmutil listlocalsnapshots /`, frees it now). A macOS job needs about N GB more.`` N counts the disk the plan's Linux jobs take, so a Mac planned for 3 Linux jobs and no macOS job gets a real number. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 40a06cdb8c..f1d3996823 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-11-02 +> Last updated: 2026-11-03 Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their @@ -1089,6 +1089,21 @@ darkbloom sandbox uninstall [--yes] images and one Linux job: 1 Linux job, no macOS job. When no job fits, the verdict gives the plan's message and the GiB to free for one Linux job and for one macOS job, and setup stops before installing. + + When the add-on's plan gives macOS no job and its `macos_limit` names disk, + setup prints one more line under the verdict + (`SandboxSizingPlan.freeSpaceNote`): the plan's free space is what `df -h ~` + shows as Avail; Finder also counts purgeable space, which macOS frees only + when it needs to (restarting, or removing Time Machine local snapshots, which + `tmutil listlocalsnapshots /` lists, frees it now); then + `A macOS job needs about N GB more`. N is `diskShortfall` for a macOS job + beside the plan's slots: the floor, the disk the plan's slots take (each + platform's images with its first slot, one job's disk per slot) and a macOS + job with its images, less the free space, in GiB rounded up, which the CLI + writes as GB like its memory figures. With 210 GiB free and 3 Linux jobs + planned, a lone macOS job would fit above the floor, but beside the Linux + jobs it needs about 70 GB more. When no job fits, N equals the verdict's GiB + for one macOS job. The fallback estimate gets no such line. 4. **Confirm.** Explains that inference pauses while a job runs, that each job pays its price minus a 10% fee into the Darkbloom balance, the VM images and the one browser approval, then asks `[y/N]`. `--yes` skips it; without a @@ -1121,7 +1136,24 @@ Rerunning `setup` decides from the add-on's answer | No add-on, or `not_installed` | A first setup: check, plan, explain, confirm, install | | `waiting_for_approval`, `waitlisted`, `enrolling` | Runs the installer again to continue, without the check or the question | | `stopped`, `error`, no answer within 10 s, a failed status, an add-on older than `status --json` | Runs the installer again to repair or update the add-on | -| `ready`, `running`, `paused`, `downloading_images`, `updating`, an unknown state | Reports the state and changes nothing; with `--linux-slots` or `--macos-slots` it runs the installer to apply them | +| `ready`, `running`, `paused`, `downloading_images`, `updating`, an unknown state | Reports the state, then checks the plan again (below); with `--linux-slots` or `--macos-slots` it runs the installer to apply them, without the plan | + +On a Mac that is set up, after the report, setup downloads the installer and +runs its plan as for a first setup, which changes nothing, and compares the +plan's `linux_slots` and `macos_slots` with the installed `slots.linux.total` +and `slots.macos.total` (`SandboxSlotChange`): + +| Case | `setup` | +|---|---| +| Same counts, no plan (an installer without `--plan`, a failed plan), a plan without a job, no `slots` in the status, or a failed download | Today's report exactly: the state, then `To change how many jobs run at a time: darkbloom sandbox setup --linux-slots --macos-slots `, without the free-space line; a failed download adds why it could not check | +| `jobs_running` above `0` | No plan: the add-on's installer refuses a slot change while jobs run (exit `4`; the CLI never passes `--force`), and their disk would shrink the plan. Setup says to run it again once they finish | +| Different counts, at a terminal | The plan's CPU, memory and disk lines and the free-space line when it applies, then `This Mac now fits Linux + macOS (installed: Linux + macOS). If a job is running, the installer refuses and changes nothing. Apply? [Y/n]`. Yes or an empty answer runs the installer with the plan's counts as `--linux-slots` and `--macos-slots`; no prints the command that applies it | +| Different counts, `--yes` or no terminal | The same lines, then `This Mac now fits …` without the question. Applies the plan only when it adds slots and removes none; otherwise prints `Not applied` and the command that applies it, and exits `0` | + +A platform missing from `slots` counts as `0`: the add-on configures and +reports only platforms with a slot. When the installer finds that a job +started since the status, it refuses with exit `4` and changes nothing; setup +prints the exit `4` advice below and exits `4`. ### Installer progress events @@ -1182,7 +1214,7 @@ every tenth. | `0` | The summary: state, jobs at a time (automatic and the limit, or your choice), next commands | | `2` | This Mac cannot host Darkbloom Sandbox as it is (the failed stage says why) | | `3` | Not enrolled: the code was denied or expired, or the waitlist request ended; run `setup` to start again | -| `4` | Jobs are running; run `setup` again once they finish, `pause` meanwhile | +| `4` | A job is running, so the installer changed nothing (it refuses rather than waits); run `setup` again when it finishes, `pause` meanwhile. Setup never passes the installer's `--force`, which would stop running jobs, and stopped jobs aren't paid | | `130` | Stopped; an enrollment waiting for approval goes on, and a rerun follows it. While the Mac waits in the background (`background: true`, not yet enrolled): it keeps waiting, also across restarts, and enrolls by itself; `sandbox status` shows where it is | | other | Setup did not finish; it is safe to rerun | diff --git a/docs/provider/sandboxes.md b/docs/provider/sandboxes.md index 2f9e96daa9..58d031c578 100644 --- a/docs/provider/sandboxes.md +++ b/docs/provider/sandboxes.md @@ -1,6 +1,6 @@ # Host Darkbloom Sandbox CI jobs -> Last updated: 2026-11-02 +> Last updated: 2026-11-03 How to let this Mac run Darkbloom Sandbox jobs, approved GitHub Actions jobs in Linux and macOS virtual machines, beside the inference provider: set it up, @@ -82,11 +82,29 @@ Uninstalling ends running jobs, which are not paid: pause first and uninstall once they finish. Running `setup` again at any time is safe: it reports the state, continues an unfinished setup or repairs the add-on. +On a Mac that is set up, `setup` also asks the installer for the add-on's plan +again. When the plan fits other job counts, for example after you freed disk, +setup shows them beside the installed ones and asks `[Y/n]`. Yes reinstalls +with the plan's counts and restarts the add-on. The installer does not wait +for jobs: if one is running, it refuses and changes nothing, and setup says to +run it again when the job finishes. With `--yes` or without a terminal, setup +applies the plan only when it adds jobs and removes none; otherwise it prints +the command that applies it. When the counts match, setup reports as before. +While jobs run, setup skips the check. The +[CLI reference](./cli-reference.md#setup) has the details. + ## Troubleshooting - **`Free up N GiB of disk for one Linux job`.** No job fits in the free disk. The disk rules are under [Prerequisites](#prerequisites). Free the space it names, then run setup again. +- **`no macOS jobs (limited by free disk space)`, while Finder shows more + free.** The plan counts what `df -h ~` shows as Avail. Finder also counts + purgeable space, which macOS frees only when it needs to. Restart, or remove + Time Machine local snapshots (`tmutil listlocalsnapshots /` lists them), to + free it now. Setup's line `A macOS job needs about N GB more` says how much + more free space a macOS job needs beside the planned Linux jobs. Then run + setup again: it offers the new plan. - **`On the waitlist`.** Darkbloom has not approved your account yet. With add-on 1.1.2 and later you can close the window: the Mac keeps waiting, also across restarts, and enrolls by itself once your account is approved; @@ -99,8 +117,12 @@ state, continues an unfinished setup or repairs the add-on. not paid. Follow the `↳ fix:` line. - **`This Mac was not enrolled`** (exit status 3). The code was denied or expired, or the waitlist request ended. Run setup again for a new code. -- **`Jobs are running on this Mac`** (exit status 4). An add-on update or a - slot change waits for running jobs; run setup again once they finish. +- **`A job is running on this Mac`** (exit status 4). The installer refuses + to replace the add-on or change its slots while a job runs, and changes + nothing; it does not wait. Run setup again when the job finishes; + `darkbloom sandbox pause` keeps new ones from starting. Setup never passes + the installer's `--force`, which would stop running jobs, and stopped jobs + aren't paid. - **`This version of the add-on …`.** The add-on predates the command; it updates itself, or `darkbloom sandbox setup` updates it now. - **`Sandboxes: installed; the add-on did not answer within 2s`.** `darkbloom diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift index d662a80fa9..05d76d019a 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift @@ -220,10 +220,10 @@ extension SandboxSizingPlan { var jobMemory: Int64 { max(0, memoryBytes - memoryKeptBytes - providerMemoryBytes) } var canRunJobs: Bool { linux.slots + macOS.slots > 0 } - /// Free disk one job of `platform` needs beyond what is free now, its - /// images included; 0 when it fits. + /// Free disk one more job of `platform` needs, beside the plan's slots, + /// beyond what is free now; 0 when it fits. func diskShortfall(_ platform: Platform) -> Int64 { - max(0, floorBytes + platform.firstSlotBytes - freeBytes) + max(0, floorBytes + linux.plannedBytes + macOS.plannedBytes + platform.nextSlotBytes - freeBytes) } /// The CPU, memory and disk lines, in the `doctor` style. When no job @@ -265,6 +265,18 @@ extension SandboxSizingPlan { return lines } + /// Why Finder shows more free space than the add-on's plan, when it gives + /// macOS no job for want of free disk space (its own `limit`), and the + /// free space one macOS job needs beside the plan's Linux slots. + var freeSpaceNote: String? { + guard macOS.slots == 0, macOS.limit?.contains("disk") == true else { return nil } + let short = diskShortfall(macOS) + return "Free space here is what `df -h ~` shows as Avail; Finder also counts purgeable space, which macOS " + + "frees only when it needs to (restarting, or removing Time Machine local snapshots: " + + "`tmutil listlocalsnapshots /`, frees it now)." + + (short > 0 ? " A macOS job needs about \(gibUp(short)) GB more." : "") + } + /// The plan's message, how much disk to free for one job of each /// platform, and whether the owner's counts are why. private var shortfall: [String] { @@ -293,6 +305,8 @@ extension SandboxSizingPlan.Platform { /// The first slot brings the platform's images. var firstSlotBytes: Int64 { imagesBytes + slotBytes } var nextSlotBytes: Int64 { slots == 0 ? firstSlotBytes : slotBytes } + /// Disk its planned slots take: the images with the first, one job's disk each. + var plannedBytes: Int64 { slots == 0 ? 0 : imagesBytes + Int64(slots) * slotBytes } } private func gb(_ bytes: Int64) -> Int64 { bytes / SandboxEligibility.gib } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift index 0762808bef..135a89ce32 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift @@ -15,7 +15,9 @@ extension Sandbox { it in your browser. Running it again reports the current state, continues an unfinished setup, repairs or updates \ - the add-on, or applies new slot counts. + the add-on, or applies new slot counts. On a Mac that is set up, it asks the installer's plan \ + again and offers the add-on's slot counts when they differ from the installed ones; with --yes \ + or without a terminal it applies them only when they add slots and remove none. """) @Flag(name: .shortAndLong, help: "Don't ask for confirmation.") @@ -77,7 +79,8 @@ extension Sandbox { /// What `setup` does, given the add-on's current answer. enum SandboxSetupPlan: Equatable, Sendable { - /// Set up already; report it and change nothing. + /// Set up already; report it, then offer the add-on's plan when its slot + /// counts differ. case alreadySetUp(SandboxAddonStatus) /// Run the installer over the existing install, for this reason. case rerun(String) @@ -137,23 +140,94 @@ struct SandboxSetupFlow { let changingSlots = options.linuxSlots != nil || options.macOSSlots != nil switch SandboxSetupPlan.decide(existing, changingSlots: changingSlots) { case .alreadySetUp(let status): - print("Darkbloom Sandbox is already set up on this Mac.") - print("") - SandboxStatusView.lines(status, color: color).forEach { print($0) } - print("") - print("To change how many jobs run at a time: \(cli) sandbox setup --linux-slots --macos-slots ") + try await reportAndRecheckSizing(status) case .rerun(let reason): print(reason) - try await withInstaller { try await install($0, script: $1) } + try await withInstaller { try await install($0, script: $1, options: options) } case .fresh: let eligibility = try await checkMac() try await withInstaller { installer, script in guard try await sizeAndConfirm(eligibility, installer: installer, script: script) else { return } - try await install(installer, script: script) + try await install(installer, script: script, options: options) } } } + // MARK: - Already set up + + private static let changeCountsHint = "To change how many jobs run at a time: \(Sandbox.cli) sandbox setup " + + "--linux-slots --macos-slots " + + /// Reports the install, then asks the installer's `--plan` how many jobs + /// this Mac fits now and offers what differs. Changes nothing unless the + /// owner agrees, or, without a prompt, the plan only adds slots. Skipped + /// while jobs run: the installer changes slots only while none does, and + /// their disk would shrink the plan. + private func reportAndRecheckSizing(_ status: SandboxAddonStatus) async throws { + print("Darkbloom Sandbox is already set up on this Mac.") + print("") + SandboxStatusView.lines(status, color: color).forEach { print($0) } + print("") + guard status.jobsRunning == 0 else { + print(Self.changeCountsHint) + print("Jobs are running, so setup did not check whether this Mac now fits other slot counts. Run " + + "`\(cli) sandbox setup` again once they finish; `\(cli) sandbox pause` keeps new ones from starting.") + return + } + try await withInstaller(ifUnavailable: { failure in + print(Self.changeCountsHint) + print("Could not check whether this Mac now fits other slot counts: \(failure)") + }) { installer, script in + let plan = try await withTransientNote("Checking how many jobs this Mac fits now…") { + try await requestAddonPlan(installer, script: script) + } + // The same counts (or no plan to compare) keep today's report exactly. + guard let plan, let change = SandboxSlotChange(installed: status, plan: plan) else { + print(Self.changeCountsHint) + return + } + guard offer(change, plan: plan) else { return } + print("") + try await install(installer, script: script, options: change.applying(to: options)) + } + } + + /// Shows the add-on's plan against the installed counts; true to apply it. + /// With a prompt the default is yes. Without one (`--yes`, or no + /// terminal) it applies only a change that adds slots and removes none. + private func offer(_ change: SandboxSlotChange, plan: SandboxSizingPlan) -> Bool { + print("The add-on's plan for this Mac now:") + printChecks(plan.checks) + if let note = plan.freeSpaceNote { print(" " + note) } + print("") + guard !confirmed, interactiveInput else { + print(change.headline) + guard change.onlyAdds else { + print("Not applied: it removes slots, and without a prompt setup applies only a plan that adds " + + "slots. To apply it: \(change.command)") + return false + } + print("Applying it: it only adds slots.") + return true + } + // The installer stops the agent only between jobs: it refuses (exit 4), it does not wait. + guard SandboxTerminal.confirm(change.headline + " If a job is running, the installer refuses and changes " + + "nothing. Apply?", defaultYes: true) else { + print("Nothing changed. To apply it later: \(change.command)") + return false + } + return true + } + + /// Runs `body` with `note` on the running line of a terminal, erased + /// afterwards; elsewhere prints nothing. + private func withTransientNote(_ note: String, _ body: () async throws -> T) async rethrows -> T { + guard terminal else { return try await body() } + SandboxTerminal.write(note) + defer { SandboxTerminal.write("\r\u{1B}[2K") } + return try await body() + } + // MARK: - Check and confirm /// Prints the checks setup makes itself; throws, before anything is @@ -176,8 +250,9 @@ struct SandboxSetupFlow { /// trade-off, then asks. False when the owner declines; throws when no job /// fits. private func sizeAndConfirm(_ eligibility: SandboxEligibility, installer: URL, script: Data) async throws -> Bool { + let reportedPlan = try await requestAddonPlan(installer, script: script) let plan: SandboxSizingPlan - if let reportedPlan = try await requestAddonPlan(installer, script: script) { + if let reportedPlan { plan = reportedPlan } else { printChecks([SandboxEligibility.Check( @@ -190,6 +265,8 @@ struct SandboxSetupFlow { let verdict = plan.verdict print(DoctorTerminalStyle.verdict(verdict[0], level: plan.canRunJobs ? .pass : .fail, color: color)) verdict.dropFirst().forEach { print($0) } + // The add-on's plan only: the fallback estimate's report stays as it was. + if let note = reportedPlan?.freeSpaceNote { print(" " + note) } guard plan.canRunJobs else { throw ExitCode.failure } print("") Self.tradeOff.forEach { print($0) } @@ -251,8 +328,10 @@ struct SandboxSetupFlow { // MARK: - Install /// Downloads the installer into a new owner-only directory for `body`, - /// then removes it. - private func withInstaller(_ body: (_ installer: URL, _ script: Data) async throws -> Void) async throws { + /// then removes it. A failed download goes to `ifUnavailable` when given, + /// else fails setup. + private func withInstaller(ifUnavailable: ((SandboxInstaller.Failure) -> Void)? = nil, + _ body: (_ installer: URL, _ script: Data) async throws -> Void) async throws { guard let url = SandboxInstaller.scriptURL(server: options.server) else { throw ValidationError("--server must be an https URL, such as \(Sandbox.defaultServer)") } @@ -260,6 +339,7 @@ struct SandboxSetupFlow { do { script = try await SandboxInstaller.download(url) } catch let failure as SandboxInstaller.Failure { + if let ifUnavailable { return ifUnavailable(failure) } printError("\(failure) Check this Mac's connection, then run `\(cli) sandbox setup` again.") throw ExitCode.failure } @@ -268,7 +348,7 @@ struct SandboxSetupFlow { try await body(installer, script) } - private func install(_ installer: URL, script: Data) async throws { + private func install(_ installer: URL, script: Data, options: SandboxSetupOptions) async throws { let jsonProgress = SandboxInstaller.supportsJSONProgress(script) let arguments = [installer.path] + SandboxInstaller.arguments(options, jsonProgress: jsonProgress) let directory = installer.deletingLastPathComponent() @@ -310,8 +390,10 @@ struct SandboxSetupFlow { case 2: return "This Mac cannot host Darkbloom Sandbox as it is; see why above." case 3: return "This Mac was not enrolled: the code was denied or expired, or the waitlist request ended. " + "Run \(rerun) to start again." - case 4: return "Jobs are running on this Mac. Run \(rerun) again once they finish; " - + "`\(Sandbox.cli) sandbox pause` keeps new ones from starting." + // The installer refuses rather than waits; its --force would stop the jobs unpaid. + case 4: return "A job is running on this Mac, so the installer changed nothing. Run \(rerun) again when it " + + "finishes; `\(Sandbox.cli) sandbox pause` keeps new jobs from starting. Setup never passes the " + + "installer's --force: it would stop running jobs, and stopped jobs aren't paid." default: return "Setup did not finish. When the problem above is fixed, run \(rerun) again; it is safe to rerun." } } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift index c846849965..03468a4f2c 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift @@ -454,11 +454,12 @@ enum SandboxTerminal { fflush(stdout) } - /// Asks a yes/no question; anything but y or yes is no. - static func confirm(_ question: String, readInput: () -> String? = { readLine() }, + /// Asks a yes/no question; anything but y or yes is no. With + /// `defaultYes`, an empty answer is yes too. + static func confirm(_ question: String, defaultYes: Bool = false, readInput: () -> String? = { readLine() }, emit: (String) -> Void = { write($0) }) -> Bool { - emit("\(question) [y/N]: ") + emit("\(question) \(defaultYes ? "[Y/n]" : "[y/N]"): ") let answer = readInput()?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" - return ["y", "yes"].contains(answer) + return ["y", "yes"].contains(answer) || (defaultYes && answer.isEmpty) } } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSlotChange.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSlotChange.swift new file mode 100644 index 0000000000..320a9ed4fa --- /dev/null +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSlotChange.swift @@ -0,0 +1,42 @@ +import Foundation + +/// The add-on's plan for an installed Mac against the slots it runs now +/// (`status --json`): what rerunning `setup` offers to apply. The counts are +/// the add-on's; the CLI only compares them. +struct SandboxSlotChange: Equatable, Sendable { + var installedLinux: Int + var installedMacOS: Int + var plannedLinux: Int + var plannedMacOS: Int +} + +extension SandboxSlotChange { + /// Nil when the status names no slots to compare, the plan fits no job, + /// or it matches the installed counts. + init?(installed status: SandboxAddonStatus, plan: SandboxSizingPlan) { + guard status.linux != nil || status.macOS != nil, plan.canRunJobs else { return nil } + self.init(installedLinux: status.linux?.total ?? 0, installedMacOS: status.macOS?.total ?? 0, + plannedLinux: plan.linux.slots, plannedMacOS: plan.macOS.slots) + guard installedLinux != plannedLinux || installedMacOS != plannedMacOS else { return nil } + } + + /// Adds slots and removes none: what setup applies without a prompt. + var onlyAdds: Bool { plannedLinux >= installedLinux && plannedMacOS >= installedMacOS } + + /// The owner's options with the plan's counts, as explicit slot options. + func applying(to options: SandboxSetupOptions) -> SandboxSetupOptions { + var options = options + (options.linuxSlots, options.macOSSlots) = (plannedLinux, plannedMacOS) + return options + } + + /// The command that applies it. + var command: String { + "\(Sandbox.cli) sandbox setup --linux-slots \(plannedLinux) --macos-slots \(plannedMacOS)" + } + + var headline: String { + "This Mac now fits \(plannedLinux) Linux + \(plannedMacOS) macOS " + + "(installed: \(installedLinux) Linux + \(installedMacOS) macOS)." + } +} diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxSetupTests.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxSetupTests.swift index 5d5a9aa8f8..8a86f0521c 100644 --- a/provider-swift/Tests/DarkbloomCLITests/SandboxSetupTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxSetupTests.swift @@ -233,6 +233,44 @@ struct SandboxSetupTests { #expect(full.checks.map(\.level) == [.pass, .pass, .fail]) } + /// The free-space note, with what one macOS job needs beside the plan's Linux slots. + private static func freeSpaceNote(macOSNeeds more: Int?) -> String { + "Free space here is what `df -h ~` shows as Avail; Finder also counts purgeable space, which macOS frees " + + "only when it needs to (restarting, or removing Time Machine local snapshots: " + + "`tmutil listlocalsnapshots /`, frees it now)." + + (more.map { " A macOS job needs about \($0) GB more." } ?? "") + } + + @Test("the free-space note appears only when the add-on gives macOS no job for want of disk") + func freeSpaceNoteScope() throws { + func plan(linux: Int = 1, macOS: Int = 0, limit: String = "free disk space", + freeGiB: Int64 = 157) throws -> SandboxSizingPlan { + let line = FakeSandboxInstaller.plan(linux: linux, macOS: macOS, freeGiB: freeGiB) + .replacingOccurrences(of: #""macos_limit":"free disk space""#, with: #""macos_limit":"\#(limit)""#) + return try #require(SandboxSizingPlan(line: line)) + } + // 100 GiB floor + 1 Linux job with its images (34) + macOS images and job (86) - 157 free. + #expect(try plan().freeSpaceNote == Self.freeSpaceNote(macOSNeeds: 63)) + #expect(try plan(freeGiB: 200).freeSpaceNote == Self.freeSpaceNote(macOSNeeds: 20)) + // No job: one macOS job's disk alone, as the verdict's own line says. + #expect(try plan(linux: 0, freeGiB: 120).freeSpaceNote == Self.freeSpaceNote(macOSNeeds: 66)) + // A plan whose numbers fit a macOS job anyway says no number. + #expect(try plan(freeGiB: 400).freeSpaceNote == Self.freeSpaceNote(macOSNeeds: nil)) + for limit in ["cores", "memory", "your choice", "macOS's limit of 2 VMs, yours included"] { + #expect(try plan(limit: limit).freeSpaceNote == nil, "\(limit)") + } + #expect(try plan(macOS: 1).freeSpaceNote == nil) + } + + @Test("the feedback's Mac: 3 Linux slots and no macOS one for want of disk; the note counts the Linux slots") + func freeSpaceNoteWithThreeLinuxSlots() throws { + // 110 GiB above the floor: a lone macOS job (86) would fit, but the 3 Linux jobs and their images take 94. + let plan = try #require(SandboxSizingPlan(line: FakeSandboxInstaller.plan( + message: "3 Linux slots", linux: 3, freeGiB: 210))) + #expect(plan.diskShortfall(plan.macOS) == 70 << 30) + #expect(plan.freeSpaceNote == Self.freeSpaceNote(macOSNeeds: 70)) + } + /// Each event as the renderer gets it. private static func render(_ lines: [String], interactive: Bool = false, finish outcome: SandboxSetupRenderer.Outcome = .succeeded) -> String { @@ -422,8 +460,7 @@ struct SandboxSetupTests { } #expect(advice(2) == "This Mac cannot host Darkbloom Sandbox as it is; see why above.") #expect(advice(3).hasPrefix("This Mac was not enrolled: the code was denied or expired")) - #expect(advice(4) == "Jobs are running on this Mac. Run `darkbloom sandbox setup` again once they finish; " - + "`darkbloom sandbox pause` keeps new ones from starting.") + #expect(advice(4) == Self.jobRunningAdvice) #expect(advice(130) == "Setup stopped. An enrollment waiting for approval goes on; run " + "`darkbloom sandbox setup` again to follow it.") #expect(advice(2, signal: SIGINT) == advice(130)) @@ -500,10 +537,6 @@ struct SandboxSetupTests { try await SandboxSetupFlow(options: first, confirmed: true, addon: .live(), interactiveInput: false, terminal: false, color: false, probe: { _ in .mac(cores: 16, memoryGiB: 128) }).run() - print("== SECOND") - try await SandboxSetupFlow(options: SandboxSetupOptions(server: "https://sandbox.invalid"), - confirmed: false, addon: .live(), interactiveInput: false, - terminal: false, color: false).run() print("== PLAN") print(try String(contentsOf: sandbox.sandboxAddonRoot.appendingPathComponent("plan-arguments"), encoding: .utf8), terminator: "") @@ -511,9 +544,14 @@ struct SandboxSetupTests { print(try String(contentsOf: sandbox.sandboxAddonRoot.appendingPathComponent("installer-arguments"), encoding: .utf8), terminator: "") print("requests \(CoordinatorStub.requests.map { $0.url?.absoluteString ?? "" })") + print("== SECOND") + try await SandboxSetupFlow(options: SandboxSetupOptions(server: "https://sandbox.invalid"), + confirmed: false, addon: .live(), interactiveInput: false, + terminal: false, color: false).run() + print("== END") } let output = decodedText(result.standardOutputContent) - let first = try #require(outputSection(output, from: "== FIRST", to: "== SECOND")) + let first = try #require(outputSection(output, from: "== FIRST", to: "== PLAN")) // The sizing lines are the plan's (157 GiB free), not this Mac's probe (800 GiB). #expect(first.hasPrefix(""" Darkbloom Sandbox setup @@ -533,6 +571,7 @@ struct SandboxSetupTests { Eligible. At a time, this Mac can run: 1 Linux job (your choice) no macOS jobs (limited by free disk space) + \(Self.freeSpaceNote(macOSNeeds: 63)) What changes @@ -546,17 +585,236 @@ struct SandboxSetupTests { Next """)) - let second = try #require(outputSection(output, from: "== SECOND", to: "== PLAN")) - #expect(second.hasPrefix("Darkbloom Sandbox is already set up on this Mac.\n\n" - + "Darkbloom Sandbox 1.0.1: downloading images (Linux 42%)\n")) - #expect(second.hasSuffix( - "\nTo change how many jobs run at a time: darkbloom sandbox setup --linux-slots --macos-slots \n")) // The owner's slot counts reach the plan and the install; one download serves both. let plan = try #require(outputSection(output, from: "== PLAN", to: "== INSTALL")) #expect(plan == "--plan\n--json-progress\n--linux-slots\n1\n") let install = try #require(outputSection(output, from: "== INSTALL", to: "requests")) #expect(install == "--json-progress\n--yes\n--no-browser\n--linux-slots\n1\n") - #expect(output.hasSuffix("requests [\"https://sandbox.invalid/install.sh\"]\n")) + #expect(output.contains("requests [\"https://sandbox.invalid/install.sh\"]\n== SECOND")) + // The rerun reports and asks the plan again (1 Linux, no macOS, against 1 + 1 installed); + // without a prompt it does not remove a slot. + let second = try #require(outputSection(output, from: "== SECOND", to: "== END")) + #expect(second.hasPrefix("Darkbloom Sandbox is already set up on this Mac.\n\n" + + "Darkbloom Sandbox 1.0.1: downloading images (Linux 42%)\n")) + #expect(second.hasSuffix(""" + macOS images 46 GiB + 40 GiB per macOS job + \(Self.freeSpaceNote(macOSNeeds: 63)) + + This Mac now fits 1 Linux + 0 macOS (installed: 1 Linux + 1 macOS). + Not applied: it removes slots, and without a prompt setup applies only a plan that adds slots. To apply \ + it: darkbloom sandbox setup --linux-slots 1 --macos-slots 0 + + """)) + } + + // MARK: - Rerun on a Mac that is set up + + @Test("a slot change compares the plan with the installed totals; none without totals or without a job") + func slotChange() throws { + let plan = try #require(SandboxSizingPlan(line: FakeSandboxInstaller.plan(macOS: 1, freeGiB: 240))) + let change = try #require(SandboxSlotChange(installed: SandboxFixtures.status( + SandboxFixtures.ready(linux: 3, macOS: 0)), plan: plan)) + #expect(change == SandboxSlotChange(installedLinux: 3, installedMacOS: 0, plannedLinux: 1, plannedMacOS: 1)) + #expect(!change.onlyAdds) + #expect(change.applying(to: SandboxSetupOptions(noBrowser: true)) + == SandboxSetupOptions(noBrowser: true, linuxSlots: 1, macOSSlots: 1)) + #expect(SandboxSlotChange(installedLinux: 1, installedMacOS: 0, plannedLinux: 1, plannedMacOS: 1).onlyAdds) + #expect(SandboxSlotChange(installed: SandboxFixtures.status(SandboxFixtures.ready), plan: plan) == nil) + #expect(SandboxSlotChange(installed: SandboxFixtures.status(SandboxFixtures.minimal), plan: plan) == nil) + let none = try #require(SandboxSizingPlan(line: FakeSandboxInstaller.plan(linux: 0, freeGiB: 120))) + #expect(SandboxSlotChange(installed: SandboxFixtures.status(SandboxFixtures.ready), plan: none) == nil) + // An empty answer is yes only where yes is the default. + #expect(SandboxTerminal.confirm("Apply?", defaultYes: true, readInput: { "" }, emit: { _ in })) + #expect(!SandboxTerminal.confirm("Apply?", readInput: { "" }, emit: { _ in })) + #expect(!SandboxTerminal.confirm("Apply?", defaultYes: true, readInput: { "n" }, emit: { _ in })) + } + + /// Runs setup on a Mac with the add-on installed (`status`) against an + /// installer whose plan prints `plan` (none: an installer without plan + /// mode), answering `answer` at a prompt when given; an install prints + /// `installerEvents` and exits with `installerExit`, which setup keeps. + /// Prints the output, then `== PLAN` and `== INSTALL` with the arguments + /// each run got. + private static func rerun(status: String, plan: String?, answer: String? = nil, confirmed: Bool = false, + linuxSlots: Int? = nil, macOSSlots: Int? = nil, + installerEvents: [String] = FakeSandboxInstaller.events, + installerExit: Int32 = 0) async throws -> String { + let expected: ExitTest.Condition = installerExit == 0 ? .success : .exitCode(installerExit) + let result = try await #require(processExitsWith: expected, observing: [\.standardOutputContent]) { + [status = status as String, plan = plan as String?, answer = answer as String?, + confirmed = confirmed as Bool, linuxSlots = linuxSlots as Int?, macOSSlots = macOSSlots as Int?, + installerEvents = installerEvents as [String], installerExit = installerExit as Int32] in + let options = SandboxSetupOptions(server: "https://sandbox.invalid", linuxSlots: linuxSlots, + macOSSlots: macOSSlots) + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + try FakeSandboxAddon.install(.current(status: status), at: sandbox.sandboxAddonRoot) + CoordinatorStub.install(["/install.sh": .init(status: 200, body: Data(FakeSandboxInstaller.script( + events: installerEvents, plan: plan.map { [$0] }, addonStatus: SandboxFixtures.ready(linux: 1, macOS: 1), + exitStatus: installerExit).utf8))]) + if let answer { try replaceStandardInput(with: answer) } + print("== EXPECTED") + SandboxStatusView.lines(SandboxFixtures.status(status)).forEach { print($0) } + print("== OUTPUT") + await exitWithCommandStatus { + defer { + for (marker, file) in [("== PLAN", "plan-arguments"), ("== INSTALL", "installer-arguments")] { + print(marker) + let url = sandbox.sandboxAddonRoot.appendingPathComponent(file) + print((try? String(contentsOf: url, encoding: .utf8)) ?? "none\n", terminator: "") + } + print("== END") + sandbox.remove() + } + try await SandboxSetupFlow(options: options, confirmed: confirmed, addon: .live(), + interactiveInput: answer != nil, terminal: false, color: false).run() + } + } + return decodedText(result.standardOutputContent) + } + + private static let changeHint = "To change how many jobs run at a time: darkbloom sandbox setup " + + "--linux-slots --macos-slots \n" + + /// Today's report for `output`'s Mac: the state, then the slot options. + private static func alreadySetUp(_ output: String) throws -> String { + let status = try #require(outputSection(output, from: "== EXPECTED", to: "== OUTPUT")) + return "Darkbloom Sandbox is already set up on this Mac.\n\n" + status + "\n" + changeHint + } + + @Test("rerun with the plan the Mac runs: today's report, after the plan, changing nothing") + func rerunSamePlan() async throws { + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 1, macOS: 1), + plan: FakeSandboxInstaller.plan(message: "1 Linux slot and 1 macOS slot", + macOS: 1, freeGiB: 300)) + #expect(try outputSection(output, from: "== OUTPUT", to: "== PLAN") == Self.alreadySetUp(output)) + #expect(output.hasSuffix("== PLAN\n--plan\n--json-progress\n== INSTALL\nnone\n== END\n")) + } + + @Test("rerun with the same plan, macOS short of disk: exactly today's report, without the free-space note") + func rerunSamePlanShortOfDisk() async throws { + // The feedback's Mac before it freed space: 3 Linux slots, macOS short of disk, as installed. + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), + plan: FakeSandboxInstaller.plan(message: "3 Linux slots", linux: 3, + freeGiB: 210)) + #expect(try outputSection(output, from: "== OUTPUT", to: "== PLAN") == Self.alreadySetUp(output)) + #expect(output.hasSuffix("== PLAN\n--plan\n--json-progress\n== INSTALL\nnone\n== END\n")) + } + + /// The feedback's Mac: 3 Linux slots installed; with more free space the plan fits 1 Linux and 1 macOS. + private static let macOSFits = FakeSandboxInstaller.plan(message: "1 Linux slot and 1 macOS slot", macOS: 1, + freeGiB: 240) + + @Test("rerun when the plan now fits macOS: it offers the plan; yes applies its counts, no changes nothing") + func rerunOffersPlan() async throws { + let offer = """ + The add-on's plan for this Mac now: + [PASS] CPU: 16 cores; you keep 4 + [PASS] Memory: 128 GB; you keep 32 GB, inference keeps 32 GB + [PASS] Disk: 240 GiB free; 100 GiB stays free for you; Linux images 4 GiB + 30 GiB per Linux job; \ + macOS images 46 GiB + 40 GiB per macOS job + + + """ + "This Mac now fits 1 Linux + 1 macOS (installed: 3 Linux + 0 macOS). If a job is running, the " + + "installer refuses and changes nothing. Apply? [Y/n]: " + for answer in ["\n", "y\n"] { + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, + answer: answer) + let shown = try #require(outputSection(output, from: "== OUTPUT", to: "== PLAN")) + let report = try Self.alreadySetUp(output).replacingOccurrences(of: Self.changeHint, with: "") + #expect(shown.hasPrefix(report + offer + "\n"), "\(answer)") + #expect(shown.contains("Darkbloom Sandbox is set up on this Mac: ready")) + #expect(output.hasSuffix("== INSTALL\n--json-progress\n--yes\n--linux-slots\n1\n--macos-slots\n1\n== END\n")) + } + let declined = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, + answer: "n\n") + #expect(declined.contains(offer + "Nothing changed. To apply it later: darkbloom sandbox setup " + + "--linux-slots 1 --macos-slots 1\n== PLAN")) + #expect(declined.hasSuffix("== INSTALL\nnone\n== END\n")) + } + + @Test("rerun without a prompt (--yes or no terminal): only a plan that adds slots and removes none is applied") + func rerunUnattended() async throws { + for confirmed in [true, false] { + // 3 Linux + 0 macOS to 1 + 1 removes Linux slots: suggested, not applied. + let removes = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, + confirmed: confirmed) + #expect(removes.contains("Not applied: it removes slots, and without a prompt setup applies only a plan " + + "that adds slots. To apply it: darkbloom sandbox setup --linux-slots 1 --macos-slots 1\n== PLAN")) + #expect(!removes.contains("[Y/n]")) + #expect(removes.hasSuffix("== INSTALL\nnone\n== END\n")) + // 1 Linux + 0 macOS to 1 + 1 only adds: applied. + let adds = try await Self.rerun(status: SandboxFixtures.ready(linux: 1, macOS: 0), plan: Self.macOSFits, + confirmed: confirmed) + #expect(adds.contains("\nThis Mac now fits 1 Linux + 1 macOS (installed: 1 Linux + 0 macOS).\n" + + "Applying it: it only adds slots.\n\n")) + #expect(adds.hasSuffix("== INSTALL\n--json-progress\n--yes\n--linux-slots\n1\n--macos-slots\n1\n== END\n")) + } + } + + /// Setup's words for the installer's exit status 4. + private static let jobRunningAdvice = "A job is running on this Mac, so the installer changed nothing. Run " + + "`darkbloom sandbox setup` again when it finishes; `darkbloom sandbox pause` keeps new jobs from starting. " + + "Setup never passes the installer's --force: it would stop running jobs, and stopped jobs aren't paid." + + @Test("applying the plan after a job started: the installer refuses (exit 4), setup says so and exits 4") + func rerunRefusedWhileAJobRuns() async throws { + // add-on 1.1.1's refusal (`InstallError.jobsRunning`) at its install stage. + let refusal = "jobs are running on this Mac; rerun when they finish (the agent also updates itself " + + "between jobs), or pass --force to stop them" + let output = try await Self.rerun( + status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, answer: "y\n", + installerEvents: [FakeSandboxInstaller.stage("installing", "started", "Installing"), + FakeSandboxInstaller.stage("installing", "failed", refusal, #""exit_code":4"#)], + installerExit: 4) + #expect(output.contains("\n\n" + Self.jobRunningAdvice + "\n== PLAN")) + #expect(!output.contains("Darkbloom Sandbox is set up on this Mac")) + // The plan's counts, and no --force: the running job is not stopped. + #expect(output.hasSuffix("== INSTALL\n--json-progress\n--yes\n--linux-slots\n1\n--macos-slots\n1\n== END\n")) + } + + @Test("rerun while jobs run: today's report, no plan, and when to run it again") + func rerunWhileJobsRun() async throws { + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0, jobsRunning: 1), + plan: Self.macOSFits) + #expect(try outputSection(output, from: "== OUTPUT", to: "== PLAN") == Self.alreadySetUp(output) + + "Jobs are running, so setup did not check whether this Mac now fits other slot counts. Run " + + "`darkbloom sandbox setup` again once they finish; `darkbloom sandbox pause` keeps new ones from starting.\n") + #expect(output.hasSuffix("== PLAN\nnone\n== INSTALL\nnone\n== END\n")) + } + + @Test("rerun with explicit slot counts applies them without a plan, as before") + func rerunExplicitCounts() async throws { + let output = try await Self.rerun( + status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, linuxSlots: 2, macOSSlots: 0) + let shown = try #require(outputSection(output, from: "== OUTPUT", to: "== PLAN")) + #expect(shown.hasPrefix("Applying the new slot counts.\n")) + #expect(output.hasSuffix("== PLAN\nnone\n== INSTALL\n--json-progress\n--yes\n--linux-slots\n2\n" + + "--macos-slots\n0\n== END\n")) + } + + @Test("rerun with an installer without plan mode, or one that fails it: today's report") + func rerunWithoutPlan() async throws { + for plan in [nil, "not a plan"] as [String?] { + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: plan) + #expect(try outputSection(output, from: "== OUTPUT", to: "== PLAN") == Self.alreadySetUp(output)) + #expect(output.hasSuffix("== INSTALL\nnone\n== END\n")) + } + } + + @Test("rerun when the installer cannot be downloaded: today's report and why it could not check") + func rerunOffline() async throws { + let result = try await #require(processExitsWith: .success, observing: [\.standardOutputContent]) { + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + defer { sandbox.remove() } + try FakeSandboxAddon.install(.current(status: SandboxFixtures.ready(linux: 3, macOS: 0)), + at: sandbox.sandboxAddonRoot) + try await SandboxSetupFlow(options: SandboxSetupOptions(server: "https://sandbox.invalid"), + confirmed: false, addon: .live(), interactiveInput: false, + terminal: false, color: false).run() + } + #expect(decodedText(result.standardOutputContent).hasSuffix(Self.changeHint + + "Could not check whether this Mac now fits other slot counts: Could not download the Darkbloom Sandbox " + + "installer from https://sandbox.invalid/install.sh: HTTP 404.\n")) } @Test("when the plan fits no job, setup prints why and how much disk to free, and installs nothing") @@ -584,6 +842,7 @@ struct SandboxSetupTests { Not eligible: No slot fits. Free up 14 GiB of disk for one Linux job, or 66 GiB of disk for one macOS job. + \(Self.freeSpaceNote(macOSNeeds: 66)) planned true installed false diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift index 9c02785936..450b53eb52 100644 --- a/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift @@ -56,6 +56,16 @@ enum SandboxFixtures { static let minimal = #"{"schema":1,"state":"ready"}"# + /// `ready` with these slot counts (all free unless jobs run) and running jobs. + static func ready(linux: Int, macOS: Int, jobsRunning: Int = 0) -> String { + ready.replacingOccurrences( + of: #""jobs_running":0"#, with: #""jobs_running":\#(jobsRunning)"# + ).replacingOccurrences( + of: #""slots":{"linux":{"free":1,"total":1},"macos":{"free":1,"total":1}}"#, + with: #""slots":{"linux":{"free":\#(max(0, linux - jobsRunning)),"total":\#(linux)},"# + + #""macos":{"free":\#(macOS),"total":\#(macOS)}}"#) + } + static func status(_ json: String) -> SandboxAddonStatus { guard let status = SandboxAddonStatus(json: json) else { fatalError("fixture does not decode: \(json)") } return status From 1d9a9f52650c40a0a5cc7b9fe5094623b0cf2f69 Mon Sep 17 00:00:00 2001 From: David Tai Date: Tue, 3 Nov 2026 16:06:23 -0600 Subject: [PATCH 2/7] Release dev into master: provider 0.10.7 (#1754) dev at 0f99ddb18, plus master's #1735, plus the commit that keeps master's plain-build default (prod). Squash per David (2026-11-03), so no dev commit enters master's history. --- .github/actions/provider-ci-build/action.yml | 32 +- .github/workflows/ci.yml | 207 ++- .github/workflows/component-changes.yml | 3 + .github/workflows/release-dev-branch.yml | 1 + .github/workflows/release-provider.yml | 8 + .github/workflows/release-swift.yml | 1 + changelog.d/app-attest-first-episode.md | 4 + changelog.d/app-attest-unsupported-restart.md | 6 + changelog.d/checkpoint-row-decoder.md | 10 + changelog.d/checkpoint-row-encoder.md | 8 + changelog.d/cluster-auto-update.md | 10 + changelog.d/cluster-feature-parity.md | 6 + changelog.d/cluster-onboarding-simple.md | 15 + .../cluster-pair-equal-tensor-shares.md | 5 + changelog.d/cluster-pair-follows-rollback.md | 7 + changelog.d/cluster-pair-serving-epoch.md | 16 + changelog.d/cluster-public-mimo-gemma.md | 4 + changelog.d/cluster-service-follows-repair.md | 6 + changelog.d/fastest-plan-evidence.md | 7 + changelog.d/fresh-mdm-removal-guidance.md | 3 + changelog.d/gemma-byte-fallback-flush.md | 6 + changelog.d/gemma-decode-command-buffers.md | 3 + changelog.d/gemma-decode-keeps-spaces.md | 5 + changelog.d/gemma-pipeline-speed.md | 5 + changelog.d/gemma-tensor-parallel.md | 7 + changelog.d/glm-tensor-parallel-stop-race.md | 4 + changelog.d/gptoss-decode-command-buffers.md | 3 + changelog.d/mimo-pipeline-decode-buffers.md | 15 + changelog.d/mimo-rotating-cache-metadata.md | 11 + changelog.d/mimo-tensor-parallel.md | 7 + changelog.d/mimo-tp-speculative.md | 8 + .../models-page-network-registration.md | 5 + changelog.d/pipeline-decode-buffers.md | 15 + changelog.d/provider-enabled-filter-wins.md | 7 + changelog.d/provider-process-exit-wait.md | 3 + .../provider-status-app-attest-lease.md | 3 + changelog.d/provider-update-rollback.md | 7 + changelog.d/qwen27-tp-decode-control.md | 22 + changelog.d/qwen27-tp-decode-loop.md | 25 + changelog.d/qwen27-tp-default-lanes.md | 20 + changelog.d/qwen27-tp-prefill.md | 17 + changelog.d/qwen27-tp-prefix-depth.md | 6 + .../reasoning-stop-outside-reasoning.md | 18 + .../renderer/features/models/ManualModels.tsx | 2 + .../features/models/ModelRegistration.tsx | 8 + .../src/renderer/features/models/PoolRow.tsx | 5 + desktop-app/src/renderer/models/facts.ts | 16 + desktop-app/src/shared/contracts.ts | 4 + desktop-app/tests/modelsAutopilot.test.tsx | 23 +- desktop-app/tests/modelsManual.test.tsx | 23 +- docs/architecture/hardware-support.md | 185 +- docs/architecture/inference.md | 1529 ++++++++++++++++- docs/architecture/model-autopilot.md | 26 +- docs/architecture/native-block-inference.md | 14 +- docs/architecture/prefix-cache.md | 176 +- docs/architecture/security/provider-trust.md | 4 +- docs/developer/build.md | 40 +- docs/developer/test.md | 632 ++++++- docs/operations/model-migration.md | 16 +- docs/operations/provider-release.md | 19 +- docs/provider/attestation.md | 22 +- docs/provider/cli-reference.md | 88 +- docs/provider/cluster-always-on.md | 178 +- docs/provider/installation.md | 42 +- docs/provider/troubleshooting.md | 9 +- docs/provider/two-mac-cluster.md | 439 +++-- docs/reference/app-attest-shadow.md | 7 +- docs/reference/cluster-control-protocol.md | 3 +- docs/reference/configuration.md | 49 +- docs/reference/desktop-control.md | 18 +- docs/reference/protocol-messages.md | 23 +- docs/reference/provider-authorization.md | 16 + docs/reference/ssd-kv-cache.md | 9 +- .../2026-10-31-public-cluster-models.md | 57 +- ...026-11-01-gemma-pipeline-prompt-experts.md | 102 ++ docs/reports/README.md | 5 +- docs/threat-model.yaml | 16 + libs/darkbloom-cluster-worker/Package.swift | 6 +- .../Execution/NativeWorkerRuntime.swift | 71 +- .../Startup/WorkerConfiguration.swift | 8 +- .../TensorParallelCheck/GemmaCheck.swift | 500 ++++++ .../TensorParallelCheck/MiMoCheck.swift | 486 ++++++ .../TensorParallelCheck/QwenDecodeCheck.swift | 69 + .../QwenPrefillBench.swift | 5 +- .../TensorParallelCheck/QwenRowsCheck.swift | 93 + .../QwenWavefrontCheck.swift | 65 + .../TensorParallelCheck.swift | 30 + .../CapabilityCommandCheck.swift | 11 +- .../MiMoImageStartupBindingTests.swift | 17 + .../Tests/GemmaTensorParallelOracles/run.sh | 128 ++ .../Tests/MiMoTensorParallelOracles/run.sh | 304 ++++ .../ClusterForcedMode.swift | 7 +- .../ClusterModelLayout.swift | 37 +- .../ClusterPlacementExplanation.swift | 6 +- .../ClusterPlacementPlanner.swift | 148 +- .../ClusterPlacementTensorBatchQuote.swift | 17 + .../ClusterRequestMix.swift | 32 +- .../ClusterServedSpeed.swift | 3 +- .../ClusterShardAssessment.swift | 11 + .../ClusterTensorParallel.swift | 34 +- .../ClusterTensorParallelChoice.swift | 45 + .../ClusterMiMoTensorParallel.swift | 25 + .../ClusterPrefillSchedule.swift | 9 + .../ClusterRuntimeCapability.swift | 11 +- .../ClusterRuntimeCapabilityCodec.swift | 13 +- .../ClusterRuntimeCapabilityValidation.swift | 5 + .../ClusterServingFeatures.swift | 88 + .../Generation/GLM5NextStageSession.swift | 10 +- ...LM5NextTensorParallelResidentRuntime.swift | 52 +- .../GLM5NextTensorParallelStepLoop.swift | 90 + .../Generation/GPTOSSLayerStageSession.swift | 15 +- .../Generation/GPTOSSPagedKVCache.swift | 25 +- .../GPTOSS/Generation/GPTOSSSlidingRing.swift | 41 + .../GPTOSS/Metadata/GPTOSSPagedKVLayout.swift | 13 +- .../Metadata/GPTOSSRequestStateBudget.swift | 9 +- .../Metadata/Gemma4PlacementFamily.swift | 74 +- .../Gemma4/Metadata/Gemma4StageGeometry.swift | 5 +- .../Gemma4ResidentAdapterDefinition.swift | 23 +- .../Gemma4ResidentCapabilityMetadata.swift | 3 +- .../Resident/Gemma4ResidentFamily.swift | 11 +- .../Gemma4/Resources/Gemma4StateBudget.swift | 64 +- .../Gemma4TensorParallelRequestBudget.swift | 129 ++ .../Gemma4/State/Gemma4RequestGeometry.swift | 40 +- .../Gemma4TensorParallelChoice.swift | 72 + .../Gemma4TensorParallelLanes.swift | 376 ++++ .../Gemma4TensorParallelLoadAgreement.swift | 56 + .../Gemma4TensorParallelLocalPair.swift | 90 + .../Gemma4TensorParallelModel.swift | 326 ++++ .../Gemma4TensorParallelPagedSession.swift | 313 ++++ .../Gemma4TensorParallelPlan.swift | 433 +++++ .../Gemma4TensorParallelPrefix.swift | 407 +++++ .../Gemma4TensorParallelRequestLoop.swift | 156 ++ .../Gemma4TensorParallelResidentRuntime.swift | 567 ++++++ .../Gemma4TensorParallelSelection.swift | 166 ++ .../Gemma4TensorParallelShareProbe.swift | 81 + .../Gemma4TensorParallelSplitSum.swift | 172 ++ .../Gemma4TensorParallelSynthetic.swift | 104 ++ .../Gemma4TensorParallelVerifiedLoad.swift | 120 ++ .../Models/LayerStageResident.swift | 41 +- .../ClusterResidentModelCatalog.swift | 4 +- .../Generation/MiMoLayerStageSession.swift | 21 +- .../MiMo/Generation/MiMoPhaseSplit.swift | 49 +- .../MiMo/Generation/MiMoSlidingRing.swift | 34 + .../Models/MiMo/MTP/MiMoMTPGeneration.swift | 29 +- .../MiMo/Metadata/MiMoPlacementFamily.swift | 68 +- .../MiMoRegisteredSpecification.swift | 7 +- .../Metadata/MiMoRequestStateBudget.swift | 16 +- .../MiMo/Prefix/MiMoStagePrefixSnapshot.swift | 18 +- .../MiMo/Resident/MiMoResidentAdmission.swift | 2 +- .../MiMoResidentCapabilityMetadata.swift | 18 +- .../MiMo/Resident/MiMoResidentRuntime.swift | 4 +- .../MiMoTensorParallelDecoding.swift | 439 +++++ .../MiMoTensorParallelModel.swift | 330 ++++ .../MiMoTensorParallelPlan.swift | 382 ++++ .../MiMoTensorParallelRequestBudget.swift | 126 ++ .../MiMoTensorParallelResidentRuntime.swift | 553 ++++++ .../MiMoTensorParallelRounds.swift | 262 +++ .../MiMoTensorParallelSpeculation.swift | 319 ++++ .../MiMoTensorParallelSynthetic.swift | 187 ++ .../MiMoTensorParallelVerifiedLoad.swift | 127 ++ .../ClusterPlacementTensorBatchBudget.swift | 2 +- .../Placement/QwenDensePlacementFamily.swift | 39 +- .../QwenGenerationDiagnosticResources.swift | 2 +- .../Generation/QwenLayerStageSession.swift | 21 +- .../Models/Qwen/MTP/QwenMTPDecoder.swift | 5 +- .../Qwen/MTP/QwenPipelineMTPGeneration.swift | 34 +- .../Qwen/Prefix/QwenStagePrefixCache.swift | 17 +- .../Qwen/Resident/QwenResidentFamily.swift | 3 +- .../Qwen/Resident/QwenResidentRuntime.swift | 8 +- .../QwenResidentPrefillTransient.swift | 15 +- .../QwenResidentRequestResources.swift | 16 +- .../QwenTensorParallelBatchBudget.swift | 25 +- .../QwenTensorParallelBatchPrefixBudget.swift | 131 +- .../QwenTensorParallelBatchDriver.swift | 241 ++- .../QwenTensorParallelBatchMTPBudget.swift | 2 +- .../QwenTensorParallelBatchPrefixCache.swift | 150 +- .../QwenTensorParallelBatchSession.swift | 186 +- .../QwenTensorParallelBatchWire.swift | 10 +- .../QwenTensorParallelDecodeBench.swift | 112 ++ .../QwenTensorParallelLinear.swift | 9 +- .../QwenTensorParallelMTPBudget.swift | 2 +- .../QwenTensorParallelMTPPrefixBudget.swift | 34 +- ...wenTensorParallelNativeBatchExecutor.swift | 173 +- .../QwenTensorParallelPrefillBench.swift | 94 +- .../QwenTensorParallelPrefixDisk.swift | 26 +- .../QwenTensorParallelPrefixSnapshot.swift | 126 +- .../QwenTensorParallelPromptWavefront.swift | 118 ++ .../QwenTensorParallelRequestCharge.swift | 22 +- ...nTensorParallelResidentRuntime+Batch.swift | 32 +- .../QwenTensorParallelResidentRuntime.swift | 37 +- .../QwenTensorParallelRowsCheck.swift | 416 +++++ .../State/CBv2OwnedRequestState.swift | 22 +- .../State/CBv2StageKVHost.swift | 101 +- .../AffineQuantizedVectorsTests.swift | 53 +- .../ContextAdmissionTests.swift | 36 + .../GLM5NextTensorParallelStepLoopTests.swift | 160 ++ .../GPTOSSPagedKVTests.swift | 97 ++ .../GPTOSSResidentAdmissionTests.swift | 19 + .../Gemma4TensorParallelPrefixTests.swift | 632 +++++++ .../Gemma4TensorParallelRuntimeTests.swift | 840 +++++++++ .../Gemma4TensorParallelTests.swift | 609 +++++++ ...pendentHistoryBatchDriverTestSupport.swift | 13 +- .../LongContextLimitsTests.swift | 2 +- .../MiMoDecodeCommandBufferTests.swift | 219 +++ .../MiMoPagedAdmissionTests.swift | 2 +- .../MiMoPagedModelHandoffTests.swift | 4 +- .../MiMoPagedPhaseStateTests.swift | 46 + .../MiMoPhaseSplitHandoffTests.swift | 17 +- .../MiMoResidentAdmissionTests.swift | 34 +- .../MiMoSpeculativeDecodeTests.swift | 3 +- .../MiMoStagePrefixSnapshotTests.swift | 33 + ...iMoTensorParallelFloat32PartialTests.swift | 269 +++ .../MiMoTensorParallelResidentTests.swift | 453 +++++ .../MiMoTensorParallelSpeculativeTests.swift | 403 +++++ .../MiMoTensorParallelTests.swift | 472 +++++ .../PipelineDecodeCommandBufferTests.swift | 483 ++++++ .../PrefixCacheContractTests.swift | 28 +- ...wenTensorParallelAssistantQuoteTests.swift | 3 +- .../QwenTensorParallelBatchBudgetTests.swift | 13 +- .../QwenTensorParallelBatchDriverTests.swift | 231 ++- .../QwenTensorParallelBatchPrefixTests.swift | 262 ++- .../QwenTensorParallelBatchQuoteTests.swift | 3 +- .../QwenTensorParallelBatchSessionTests.swift | 84 +- ...QwenTensorParallelNativeContextTests.swift | 17 +- .../QwenTensorParallelPrefixDepthTests.swift | 242 +++ ...enTensorParallelPrefixPlacementTests.swift | 156 ++ ...enTensorParallelPromptWavefrontTests.swift | 409 +++++ .../QwenTensorParallelRankLedgerTests.swift | 3 +- ...nTensorParallelRealGeometryRowsTests.swift | 115 ++ .../QwenTensorParallelRowQuoteTests.swift | 3 +- .../RequestScopedRefusalTests.swift | 7 +- .../ResidentAdmissionGemma4Tests.swift | 22 +- .../ResidentAdmissionNemotronTests.swift | 23 + .../Tests/GLMImageAdmissionChecks/run.sh | 1 + .../PlacementChecks/AutoChoiceChecks.swift | 2 +- .../Tests/PlacementChecks/CheckSupport.swift | 39 + .../GLMTensorParallelChecks.swift | 5 + .../GemmaRoutedExpertChecks.swift | 49 + .../GemmaTensorParallelChecks.swift | 327 ++++ .../PlacementChecks/Golden/expected.json | 16 +- .../Golden/layouts/gemma-4-26b-8bit.json | 2 +- .../Golden/layouts/gemma-4-26b-qat-4bit.json | 2 +- .../Golden/layouts/gemma-4-26b.json | 2 +- .../mimo-v2.6-flash-mopd-2026-09-28-r1.json | 2 +- .../pairs/m3ultra-m5ultra/expected.json | 16 +- .../Tests/PlacementChecks/Main.swift | 4 + .../MiMoRoutedExpertChecks.swift | 83 + .../MiMoTensorParallelChecks.swift | 365 ++++ .../Tests/PlacementChecks/PlannerChecks.swift | 6 + .../TensorBatchScopeChecks.swift | 45 + .../TensorParallelChecks.swift | 23 +- .../TensorParallelNoteChecks.swift | 14 + .../Tests/PlacementChecks/run.sh | 5 + .../Tests/PreludeChecks/main.swift | 13 +- .../ClusterConfigurationErrorStandIn.swift | 4 + .../Tests/ProcessChecks/run.sh | 2 + .../GemmaTensorParallelPlanCheck.swift | 94 + .../TensorParallelPlanChecks/gemma-run.sh | 14 + libs/mlx-swift-lm | 2 +- .../AppAttestPreflightProbe.swift | 67 + .../AppAttestStallRestart.swift | 132 +- .../AppleAppAttestService.swift | 7 + .../ProviderCore/Auth/Enrollment.swift | 5 +- .../ProviderLoop+AutopilotControl.swift | 2 +- .../ProviderLoop+AutopilotModelSet.swift | 46 +- .../Config/ClusterConfigurationFiles.swift | 14 +- .../Config/ClusterRuntimeApprovalFacts.swift | 6 +- .../CoordinatorClient+Connection.swift | 5 +- .../CoordinatorClient+ModelSwitch.swift | 2 + .../CoordinatorClient+Registration.swift | 3 + .../Coordinator/CoordinatorClientState.swift | 25 + .../Coordinator/NativePairMemberServing.swift | 3 +- .../OutboundMessage+WriteCompletion.swift | 11 + .../Diagnostics/ModelFitDiagnostic.swift | 13 + .../ProviderAuthorizationReadiness.swift | 93 +- .../Console/ClusterSetupLinkExchange.swift | 18 + .../ClusterSetupWizardLiveOperations.swift | 53 +- .../Console/ClusterSetupWizardPlanning.swift | 30 +- .../Console/ClusterSetupWizardStore.swift | 14 +- .../DistributedResidentExecution.swift | 10 +- .../DistributedCBv2Engine+Admission.swift | 14 +- .../Engine/DistributedCBv2Engine.swift | 8 + .../Installed/ClusterPairUpdateProgress.swift | 81 + .../Installed/ClusterPublicModels.swift | 35 +- .../Installed/ClusterServiceWire.swift | 3 + ...tributedInstalledGenerationSelection.swift | 20 +- .../Installed/DistributedInstalledPlan.swift | 76 +- .../ClusterApprovalAttachment.swift | 10 + .../Onboarding/ClusterControlLeadership.swift | 33 +- .../ClusterLocalNetworkAccess.swift | 181 ++ .../Onboarding/ClusterOnboardingBrand.swift | 5 +- .../Onboarding/ClusterOnboardingFlow.swift | 1040 ++++++----- .../Onboarding/ClusterOnboardingLive.swift | 187 +- .../ClusterOnboardingTerminal.swift | 207 ++- .../Onboarding/ClusterService.swift | 135 +- .../Onboarding/ClusterServiceControl.swift | 21 +- .../DistributedAutomaticBatchFactory.swift | 28 +- .../DistributedAutomaticBatchPlanner.swift | 6 +- .../Placement/ClusterModeParity.swift | 117 ++ .../Placement/ClusterModelFeaturePolicy.swift | 21 + .../Placement/ClusterPlacementFlow.swift | 34 +- .../ClusterPlacementTensorWidth.swift | 60 + .../Engine/Bridge/EngineV2Bridge+Events.swift | 6 +- .../Bridge/EngineV2Bridge+StopSequence.swift | 22 +- .../Bridge/EngineV2Bridge+Submission.swift | 12 +- .../Engine/Bridge/EngineV2Bridge.swift | 4 +- .../MultiModelBatchSchedulerEngine.swift | 34 +- .../Prompting/LocalTokenizerLoader.swift | 69 +- .../Prompting/ReasoningStopScope.swift | 43 + .../ProviderCore/Process/BoundedProcess.swift | 26 +- .../Process/ProcessExitObserver.swift | 70 + .../ProviderLoop+AppAttestShadow.swift | 2 + .../ProviderLoop+AppAttestStall.swift | 163 +- .../ProviderLoop+AutoUpdate.swift | 2 +- .../ProviderLoop+ClusterPairServing.swift | 49 +- .../ProviderLoop+ClusterUpdateDrain.swift | 81 + .../ProviderCore/ProviderLoop+Lifecycle.swift | 1 + .../ProviderLoop+ModelSelection.swift | 16 +- .../ProviderCore/ProviderLoop+Prefetch.swift | 15 +- .../ProviderCore/ProviderLoop+Trust.swift | 2 + .../Sources/ProviderCore/ProviderLoop.swift | 42 +- .../ProviderCore/ProviderLoopConfig.swift | 6 + .../Security/DarkbloomMDMRemoval.swift | 5 +- .../Security/SecurityHardening.swift | 5 +- .../Service/AppAttestVerifiedSeed.swift | 44 + .../Service/ClusterServiceAgent.swift | 11 + .../ClusterMemberUpdateSlot.swift | 5 +- .../ClusterPairUpdate.swift | 128 ++ .../Service/ClusterUpdateDrain.swift | 60 + .../Service/DaemonState+Coding.swift | 4 +- .../Service/DaemonStateFile.swift | 15 + .../Service/LaunchctlControl.swift | 5 +- .../Service/LifecycleMailbox.swift | 7 + .../Service/ProcessLifecycle.swift | 62 +- .../Service/ProviderLaunchSnapshot.swift | 13 + .../Service/ProviderProcessRun.swift | 12 + .../Update/AutoUpdateController.swift | 2 +- .../Update/ClusterCandidateRecovery.swift | 165 ++ .../Update/ClusterPairUpdateCycle.swift | 617 +++++++ .../Update/SelfUpdater+Rollback.swift | 139 ++ .../ProviderCore/Update/SelfUpdater.swift | 14 +- .../Update/UpdateProcessLock.swift | 21 + .../Update/UpdateRecoveryState.swift | 15 +- .../Update/UpdateRecoveryStore.swift | 27 +- .../darkbloom/ClusterLocalCommand.swift | 2 +- .../darkbloom/ClusterMemberSupervisor.swift | 314 +++- .../darkbloom/ClusterServiceCommand.swift | 69 +- .../darkbloom/ClusterSetupCommand.swift | 5 +- .../darkbloom/Desktop/DesktopSnapshot.swift | 11 + .../darkbloom/Diagnostics/DoctorRunner.swift | 23 +- .../darkbloom/DoctorClusterChecks.swift | 25 + .../Sources/darkbloom/DoctorCommand.swift | 10 +- .../Sources/darkbloom/LogsCommand.swift | 5 +- .../Sources/darkbloom/ReportCommand.swift | 5 +- .../Sources/darkbloom/ServiceDrain.swift | 111 +- .../darkbloom/Start/StartCommand+Modes.swift | 17 +- .../StartCommand+ClusterMember.swift | 10 +- .../Sources/darkbloom/StatusCommand.swift | 6 +- .../UnenrollCommand+KeepServing.swift | 3 +- .../Sources/darkbloom/UpdateCommand.swift | 98 +- .../Sources/darkbloom/UpdateRollback.swift | 343 ++++ provider-swift/Sources/darkbloom/main.swift | 4 +- .../ClusterConsoleCheck.swift | 1 + .../ConsolePairingChangeChecks.swift | 141 ++ .../ClusterControlChecks/ControlChecks.swift | 40 + .../InstalledBatchLanesCheck.swift | 58 +- .../InstalledFixture.swift | 11 +- .../InstalledSessionCheck.swift | 61 +- .../OnboardingChecks.swift | 1434 ++++++++++------ .../PlacementSetupCheck.swift | 409 ++++- .../Tests/ClusterPlacementChecks/run.sh | 2 + .../Tests/ClusterSupervisionChecks/main.swift | 97 ++ .../Tests/ClusterSupervisionChecks/run.sh | 1 + .../ClusterServiceUpdateTests.swift | 503 ++++++ .../DesktopModelRegistrationTests.swift | 13 + .../DoctorClusterChecksTests.swift | 28 + .../DoctorClusterModelFitTests.swift | 36 + .../StatusCommandRunTests.swift | 27 + .../UpdateRollbackCommandTests.swift | 566 ++++++ .../UpdateRollbackEndToEndTests.swift | 275 +++ .../KeyHistoryAndPreflightTests.swift | 32 + .../StalledOperationAndRotationTests.swift | 102 +- .../Autopilot/AutopilotDownloadTests.swift | 38 + .../Autopilot/AutopilotInventoryTests.swift | 9 +- .../ClusterRuntimeApprovalFactsTests.swift | 25 +- .../CoordinatorModelSwitchTests.swift | 37 + .../ProviderAuthorizationReadinessTests.swift | 162 +- .../glm-5.3-flash-dev-branch17.json | 2 +- .../Helpers/MockCoordinator.swift | 4 + .../Helpers/RunLoopServiceProbe.swift | 24 + .../ClusterApprovalFixture.swift | 10 +- .../ClusterApprovalTensorSharesTests.swift | 85 + .../ClusterLocalNetworkAccessTests.swift | 59 + ...rPlacementTensorWidthRegisteredTests.swift | 173 ++ .../ClusterPlacementTensorWidthTests.swift | 280 +++ .../ClusterServicePairingChangeTests.swift | 188 ++ .../ClusterServiceRecoveryTests.swift | 34 + ...istributedAutomaticBatchPlannerTests.swift | 50 +- ...ributedCBv2CancellationDeadlockTests.swift | 192 +++ .../DistributedCBv2DeadlineTests.swift | 1 + .../DistributedCBv2EngineTests.swift | 1 + ...istributedInstalledCancellationTests.swift | 7 +- .../DistributedInstalledLanesTests.swift | 50 +- .../Engine/EngineV2BridgeTests.swift | 59 +- .../NativeBlockRetirementBridgeTests.swift | 49 + .../LocalTokenizerByteFallbackTests.swift | 170 ++ .../LocalTokenizerDecodeSpacingTests.swift | 102 ++ .../Prompting/ReasoningStopScopeTests.swift | 112 ++ .../SSDCooperativePoolTestSupport.swift | 12 + .../KVCacheSSD/SSDCacheEpochStoreTests.swift | 9 - ...SDWholeRootTelemetryConcurrencyTests.swift | 79 +- .../Process/BoundedProcessTests.swift | 80 + .../ChildExitWaitConventionTests.swift | 39 + .../Process/ProcessExitObserverTests.swift | 111 ++ .../ClusterPairServingTests.swift | 75 + .../DaemonStateServedCountTests.swift | 28 + .../OperatorModelFilterTests.swift | 208 +++ ...ProviderAuthorizationConnectionTests.swift | 41 +- .../Qwen4PagingPrefixIntegrationTests.swift | 9 +- .../Service/LaunchctlControlTests.swift | 27 + .../Service/ProcessLifecycleTests.swift | 33 + .../Service/ProviderLifecycleTests.swift | 394 ++++- .../Service/ProviderModelSwitchTests.swift | 22 +- .../Update/ClusterPairUpdateTests.swift | 652 +++++++ .../Update/UpdateRollbackPlanTests.swift | 210 +++ .../Update/UpdateRollbackRecoveryTests.swift | 243 +++ scripts/ci-component-paths.py | 37 +- scripts/cluster-test-plan.py | 392 +++++ scripts/prepare-mimo-audio-fixtures.py | 7 +- scripts/provider-build-default.py | 59 + scripts/provider-ci-cache.py | 3 +- scripts/provider-test-shards.py | 14 +- scripts/run-nested-suite.sh | 10 +- scripts/test-ci-component-paths.py | 89 +- scripts/test-cluster-test-plan.py | 133 ++ scripts/test-darkbloom-route.py | 43 +- scripts/test-provider-build-default.py | 102 ++ scripts/test-provider-ci-workflow.py | 132 +- scripts/test-provider-test-shards.py | 13 + 439 files changed, 35860 insertions(+), 2826 deletions(-) create mode 100644 changelog.d/app-attest-first-episode.md create mode 100644 changelog.d/app-attest-unsupported-restart.md create mode 100644 changelog.d/checkpoint-row-decoder.md create mode 100644 changelog.d/checkpoint-row-encoder.md create mode 100644 changelog.d/cluster-auto-update.md create mode 100644 changelog.d/cluster-feature-parity.md create mode 100644 changelog.d/cluster-onboarding-simple.md create mode 100644 changelog.d/cluster-pair-equal-tensor-shares.md create mode 100644 changelog.d/cluster-pair-follows-rollback.md create mode 100644 changelog.d/cluster-pair-serving-epoch.md create mode 100644 changelog.d/cluster-public-mimo-gemma.md create mode 100644 changelog.d/cluster-service-follows-repair.md create mode 100644 changelog.d/fastest-plan-evidence.md create mode 100644 changelog.d/fresh-mdm-removal-guidance.md create mode 100644 changelog.d/gemma-byte-fallback-flush.md create mode 100644 changelog.d/gemma-decode-command-buffers.md create mode 100644 changelog.d/gemma-decode-keeps-spaces.md create mode 100644 changelog.d/gemma-pipeline-speed.md create mode 100644 changelog.d/gemma-tensor-parallel.md create mode 100644 changelog.d/glm-tensor-parallel-stop-race.md create mode 100644 changelog.d/gptoss-decode-command-buffers.md create mode 100644 changelog.d/mimo-pipeline-decode-buffers.md create mode 100644 changelog.d/mimo-rotating-cache-metadata.md create mode 100644 changelog.d/mimo-tensor-parallel.md create mode 100644 changelog.d/mimo-tp-speculative.md create mode 100644 changelog.d/models-page-network-registration.md create mode 100644 changelog.d/pipeline-decode-buffers.md create mode 100644 changelog.d/provider-enabled-filter-wins.md create mode 100644 changelog.d/provider-process-exit-wait.md create mode 100644 changelog.d/provider-status-app-attest-lease.md create mode 100644 changelog.d/provider-update-rollback.md create mode 100644 changelog.d/qwen27-tp-decode-control.md create mode 100644 changelog.d/qwen27-tp-decode-loop.md create mode 100644 changelog.d/qwen27-tp-default-lanes.md create mode 100644 changelog.d/qwen27-tp-prefill.md create mode 100644 changelog.d/qwen27-tp-prefix-depth.md create mode 100644 changelog.d/reasoning-stop-outside-reasoning.md create mode 100644 desktop-app/src/renderer/features/models/ModelRegistration.tsx create mode 100644 docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md create mode 100644 libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift create mode 100644 libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/MiMoCheck.swift create mode 100644 libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift create mode 100644 libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift create mode 100644 libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift create mode 100755 libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh create mode 100755 libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallelChoice.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterMiMoTensorParallel.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServingFeatures.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/GLM5NextTensorParallelStepLoop.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelChoice.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLoadAgreement.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLocalPair.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelModel.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPlan.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSelection.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelShareProbe.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSplitSum.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSynthetic.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelVerifiedLoad.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoSlidingRing.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelDecoding.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelModel.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelPlan.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRequestBudget.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRounds.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSynthetic.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelVerifiedLoad.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GLM5NextTensorParallelStepLoopTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelPrefixTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelRuntimeTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/Gemma4TensorParallelTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoDecodeCommandBufferTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelFloat32PartialTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelResidentTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelSpeculativeTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/MiMoTensorParallelTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PipelineDecodeCommandBufferTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixDepthTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPrefixPlacementTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelPromptWavefrontTests.swift create mode 100644 libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/QwenTensorParallelRealGeometryRowsTests.swift create mode 100644 libs/darkbloom-cluster/Tests/PlacementChecks/GemmaRoutedExpertChecks.swift create mode 100644 libs/darkbloom-cluster/Tests/PlacementChecks/GemmaTensorParallelChecks.swift create mode 100644 libs/darkbloom-cluster/Tests/PlacementChecks/MiMoRoutedExpertChecks.swift create mode 100644 libs/darkbloom-cluster/Tests/PlacementChecks/MiMoTensorParallelChecks.swift create mode 100644 libs/darkbloom-cluster/Tests/ProcessChecks/ClusterConfigurationErrorStandIn.swift create mode 100644 libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/GemmaTensorParallelPlanCheck.swift create mode 100755 libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/gemma-run.sh create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPairUpdateProgress.swift create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterLocalNetworkAccess.swift create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModeParity.swift create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift create mode 100644 provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningStopScope.swift create mode 100644 provider-swift/Sources/ProviderCore/Process/ProcessExitObserver.swift create mode 100644 provider-swift/Sources/ProviderCore/ProviderLoop+ClusterUpdateDrain.swift create mode 100644 provider-swift/Sources/ProviderCore/Service/AppAttestVerifiedSeed.swift create mode 100644 provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift create mode 100644 provider-swift/Sources/ProviderCore/Service/ClusterUpdateDrain.swift create mode 100644 provider-swift/Sources/ProviderCore/Update/ClusterCandidateRecovery.swift create mode 100644 provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift create mode 100644 provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift create mode 100644 provider-swift/Sources/darkbloom/DoctorClusterChecks.swift create mode 100644 provider-swift/Sources/darkbloom/UpdateRollback.swift create mode 100644 provider-swift/Tests/ClusterConsoleChecks/ConsolePairingChangeChecks.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DesktopModelRegistrationTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DoctorClusterChecksTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/DoctorClusterModelFitTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/UpdateRollbackCommandTests.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/UpdateRollbackEndToEndTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Helpers/RunLoopServiceProbe.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalTensorSharesTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterLocalNetworkAccessTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthRegisteredTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPlacementTensorWidthTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServicePairingChangeTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedCBv2CancellationDeadlockTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerByteFallbackTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Prompting/LocalTokenizerDecodeSpacingTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningStopScopeTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/KVCacheSSD/Fixtures/SSDCooperativePoolTestSupport.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Process/BoundedProcessTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Process/ChildExitWaitConventionTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Process/ProcessExitObserverTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/ProviderLoop/OperatorModelFilterTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Service/LaunchctlControlTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackPlanTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Update/UpdateRollbackRecoveryTests.swift create mode 100755 scripts/cluster-test-plan.py create mode 100644 scripts/provider-build-default.py create mode 100755 scripts/test-cluster-test-plan.py create mode 100644 scripts/test-provider-build-default.py diff --git a/.github/actions/provider-ci-build/action.yml b/.github/actions/provider-ci-build/action.yml index 0adbe70dfe..40b34a38ac 100644 --- a/.github/actions/provider-ci-build/action.yml +++ b/.github/actions/provider-ci-build/action.yml @@ -2,7 +2,7 @@ name: Provider CI Build description: Build full debug test products with lane-specific caches and source-matched Metal inputs: lane: - description: provider or sdk; each owns independent build outputs + description: provider, sdk or cluster; each owns independent build outputs required: true runs: using: composite @@ -13,7 +13,7 @@ runs: LANE: ${{ inputs.lane }} run: | case "$LANE" in - provider|sdk) ;; + provider|sdk|cluster) ;; *) echo "Unknown provider CI lane: $LANE" >&2; exit 2 ;; esac - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 @@ -41,13 +41,14 @@ runs: path: | provider-swift/.build libs/mlx-swift-lm/.build + libs/darkbloom-cluster/.build key: ${{ steps.keys.outputs.swift-key }} restore-keys: ${{ steps.keys.outputs.swift-prefix }} - name: Revalidate source timestamps and discard cached runtime resources shell: bash run: | python3 scripts/provider-release-cache.py restore-mtimes - for root in provider-swift/.build libs/mlx-swift-lm/.build; do + for root in provider-swift/.build libs/mlx-swift-lm/.build libs/darkbloom-cluster/.build; do [ -d "$root" ] || continue find "$root" -type f -name mlx.metallib -delete find "$root" -mindepth 3 -maxdepth 3 -type d \ @@ -72,18 +73,28 @@ runs: swift package unedit --force mlx-swift >/dev/null 2>&1 || true swift package edit --path ../mlx-swift mlx-swift swift build --build-tests + - name: Build all cluster test products + if: inputs.lane == 'cluster' + id: cluster-build + shell: bash + working-directory: libs/darkbloom-cluster + run: swift build --build-tests - name: Record timestamps for successfully built sources - if: ${{ !cancelled() && (steps.provider-build.outcome == 'success' || steps.sdk-build.outcome == 'success') }} + if: ${{ !cancelled() && (steps.provider-build.outcome == 'success' || steps.sdk-build.outcome == 'success' || steps.cluster-build.outcome == 'success') }} id: timestamps shell: bash run: python3 scripts/provider-release-cache.py snapshot-mtimes + # Pushes save their build. A pull request saves only when it restored + # nothing, so its later pushes do not each add an entry that evicts the + # base branch's entry from the repository cache. - name: Save lane-specific Swift test build - if: ${{ !cancelled() && steps.timestamps.outcome == 'success' && steps.swift-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && steps.timestamps.outcome == 'success' && steps.swift-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.swift-cache.outputs.cache-matched-key == '') }} uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: | provider-swift/.build libs/mlx-swift-lm/.build + libs/darkbloom-cluster/.build key: ${{ steps.keys.outputs.swift-key }} - name: Restore source-matched Metal cache id: metallib-cache @@ -99,11 +110,12 @@ runs: METALLIB_CACHE_DIR: ${{ runner.temp }}/metallib-cache run: | cmake --version - if [ "$LANE" = sdk ]; then - bin=$(swift build --package-path libs/mlx-swift-lm --show-bin-path) - else - bin=$(swift build --package-path provider-swift --show-bin-path) - fi + case "$LANE" in + sdk) package=libs/mlx-swift-lm ;; + cluster) package=libs/darkbloom-cluster ;; + *) package=provider-swift ;; + esac + bin=$(swift build --package-path "$package" --show-bin-path) ./scripts/stage-test-metallib.sh "$bin" - name: Save validated source-matched Metal cache if: ${{ !cancelled() && steps.metallib.outcome == 'success' && steps.metallib-cache.outputs.cache-hit != 'true' }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d16d575f9c..1687c5116a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,11 +26,9 @@ jobs: permissions: contents: read - # Chooses a Darkbloom Sandbox or the Blacksmith fallback for each read-only - # job below. It follows the classifier so only jobs that will run are - # requested, and still routes the unconditional jobs if the classifier fails. - # A lane is granted whole or falls back whole, so each provider shard has a - # lane of its own and gets a free Mac even when there is not one per shard. + # Chooses a Darkbloom Sandbox or the Blacksmith fallback for the read-only + # Linux jobs below. It waits for the classifier but still runs if it fails. + # The macOS jobs are not routed (docs/developer/build.md). route: needs: changes if: ${{ !cancelled() }} @@ -40,14 +38,6 @@ jobs: lanes: | release-integrity linux_arm64 blacksmith-4vcpu-ubuntu-2404 docs linux_arm64 blacksmith-4vcpu-ubuntu-2404 - test-provider-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-3 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-4 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-5 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-summary macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-sdk macos_arm64 blacksmith-12vcpu-macos-27 ${{ (github.event_name == 'push' || needs.changes.outputs.sdk == 'true') && 1 || 0 }} - test-cluster-checks macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} release-integrity: name: Release Integrity @@ -56,6 +46,14 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + # A plain build of master must be prod and a plain build of dev must be + # dev. The target is the pull request's base branch, or the pushed branch. + - name: Check the provider's plain-build default for the target branch + env: + TARGET_BRANCH: ${{ github.base_ref || github.ref_name }} + run: | + python3 scripts/test-provider-build-default.py + python3 scripts/provider-build-default.py --branch "$TARGET_BRANCH" - name: Validate changelog fragments run: | python3 scripts/test-changelog.py @@ -80,6 +78,7 @@ jobs: python3 scripts/test-provider-ci-cache.py python3 scripts/test-provider-ci-workflow.py python3 scripts/test-provider-test-shards.py + python3 scripts/test-cluster-test-plan.py python3 scripts/test-ci-component-paths.py python3 scripts/test-darkbloom-route.py python3 scripts/test-prepare-prompt-fixtures.py @@ -130,23 +129,22 @@ jobs: test-provider: # The provider suite runs in shards on separate Macs - # (scripts/provider-test-shards.py), each routed through its own - # test-provider-K lane above. Each shard runs its suites serially in + # (scripts/provider-test-shards.py). Each shard runs its suites serially in # one process. Shard 1 also runs the MLX-free test targets in one parallel # process; shard 2 also runs Prompt Parity. The last shard runs every suite # that no other shard selects, the isolated processes and the native gates # below. Provider Unit Tests Summary # checks that the shards together executed the full suite and reports coverage. name: Provider Unit Tests (shard ${{ matrix.shard }}) - needs: [changes, route] + needs: changes if: ${{ needs.changes.outputs.provider == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)[format('test-provider-{0}', matrix.shard)] }} + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 strategy: # A failed shard does not cancel the other shards. fail-fast: false matrix: - shard: [1, 2, 3, 4, 5] + shard: [1, 2, 3] steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: @@ -348,16 +346,17 @@ jobs: test-provider-summary: # Checks the shards against the full suite list and reports coverage. name: Provider Unit Tests Summary - needs: [changes, route, test-provider] + needs: [changes, test-provider] if: ${{ !cancelled() && needs.changes.outputs.provider == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-provider-summary'] }} + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 30 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: submodules: recursive - # The shards saved this build; restoring it gives the binaries that - # `swift test list` and llvm-cov read. + # This restores the shards' build, or on a pull request the base + # branch's build, and rebuilds it from the same sources and flags. + # `swift test list` and llvm-cov read its binaries. - name: Build provider CI prerequisites id: provider-ci-build uses: ./.github/actions/provider-ci-build @@ -512,9 +511,9 @@ jobs: # SDK-lane input changes (scripts/ci-component-paths.py SDK); every push to # dev or master runs it, and a failure there notifies without blocking. name: Provider SDK Tests - needs: [changes, route] + needs: changes if: ${{ github.event_name == 'push' || needs.changes.outputs.sdk == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-provider-sdk'] }} + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 @@ -682,9 +681,9 @@ jobs: # metadata and argument checks) and runs it on the retained fixtures: no GPU, # no model load, no weights. Every runner runs even after another fails. name: Cluster Metadata Checks - needs: [changes, route] - if: ${{ needs.changes.outputs.provider == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-cluster-checks'] }} + needs: changes + if: ${{ needs.changes.outputs.cluster == 'true' }} + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 @@ -737,13 +736,23 @@ jobs: DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS: '12' DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT: ${{ runner.temp }}/cluster-native-metadata run: bash libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh + # Builds the bootstrap product beside the capability runner's, in the same + # retained build, before the steps below record and save it. + - name: Run prefill schedule checks + if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + env: + DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS: '12' + DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT: ${{ runner.temp }}/cluster-native-metadata + run: bash libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh + # Pushes save the cluster build; a pull request saves it only when it + # restored nothing (as the provider lane's Swift build). - name: Record source timestamps for the cluster build - if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.cluster-build-cache.outputs.cache-matched-key == '') }} run: | python3 scripts/provider-release-cache.py snapshot-mtimes cp provider-swift/.build/provider-release-source-mtimes.json "$RUNNER_TEMP/cluster-native-metadata/" - name: Upload cluster metadata build cache - if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.cluster-build-cache.outputs.cache-matched-key == '') }} uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: ${{ runner.temp }}/cluster-native-metadata @@ -767,18 +776,103 @@ jobs: if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} run: bash provider-swift/Tests/ClusterOnboardingChecks/run.sh + test-cluster: + # DarkbloomClusterRuntimeTests in selections, each in its own process, on + # separate Macs (scripts/cluster-test-plan.py): every test without a + # switch, and the switched tests that pass on these runners. + name: Cluster Runtime Tests (shard ${{ matrix.shard }}) + needs: changes + if: ${{ needs.changes.outputs.cluster == 'true' }} + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + shard: [1, 2, 3] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + submodules: recursive + - name: Build cluster test products + id: provider-ci-build + uses: ./.github/actions/provider-ci-build + with: + lane: cluster + - name: Run cluster runtime tests + if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} + timeout-minutes: 40 + env: + SHARD: ${{ matrix.shard }} + run: python3 scripts/cluster-test-plan.py run blocking "$SHARD" + + test-cluster-gpu: + # The switched cluster runtime tests these runners cannot pass, the long + # ones and the benchmarks (scripts/cluster-test-plan.py). They run and + # report on every pull request; a failure does not fail the workflow. + name: Cluster GPU Tests (non-blocking, shard ${{ matrix.shard }}) + needs: changes + if: ${{ needs.changes.outputs.cluster == 'true' }} + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + shard: [1, 2] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + submodules: recursive + - name: Build cluster test products + id: provider-ci-build + uses: ./.github/actions/provider-ci-build + with: + lane: cluster + - name: Run non-blocking cluster GPU tests + if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} + continue-on-error: true + timeout-minutes: 40 + env: + SHARD: ${{ matrix.shard }} + run: python3 scripts/cluster-test-plan.py run nonblocking "$SHARD" + + test-cluster-focused: + # The model-free runner scripts under libs/darkbloom-cluster/Tests that + # Cluster Metadata Checks does not run (scripts/cluster-test-plan.py). + name: Cluster Focused Checks + needs: changes + if: ${{ needs.changes.outputs.cluster == 'true' }} + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + submodules: recursive + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.12.10' + - name: Select SDK 27 provider toolchain + id: toolchain + run: ./scripts/prepare-provider-release-toolchain.sh + - name: Run cluster focused checks + if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + timeout-minutes: 40 + run: python3 scripts/cluster-test-plan.py run focused 1 + provider-test-gate: name: Provider Tests runs-on: ubuntu-24.04 - needs: [changes, test-provider, test-provider-summary] + needs: [changes, test-provider, test-provider-summary, test-cluster, test-cluster-focused] if: ${{ always() }} steps: - name: Require selected provider lanes or verified intentional skips env: CHANGES_RESULT: ${{ needs.changes.result }} PROVIDER_CHANGED: ${{ needs.changes.outputs.provider }} + CLUSTER_CHANGED: ${{ needs.changes.outputs.cluster }} UNIT_RESULT: ${{ needs.test-provider.result }} SUMMARY_RESULT: ${{ needs.test-provider-summary.result }} + CLUSTER_RESULT: ${{ needs.test-cluster.result }} + CLUSTER_FOCUSED_RESULT: ${{ needs.test-cluster-focused.result }} run: | test "$CHANGES_RESULT" = success case "$PROVIDER_CHANGED" in @@ -788,47 +882,12 @@ jobs: esac test "$UNIT_RESULT" = "$expected" test "$SUMMARY_RESULT" = "$expected" - - cache-swift: - name: Swift Build + Cache - runs-on: blacksmith-12vcpu-macos-27 - if: github.event_name == 'push' - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - submodules: recursive - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: '3.12.10' - - name: Select SDK 27 provider toolchain - run: ./scripts/prepare-provider-release-toolchain.sh - - name: Restore SwiftPM cache - uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 - with: - path: | - ~/Library/Caches/org.swift.swiftpm - ~/Library/org.swift.swiftpm - provider-swift/.build - libs/mlx-swift-lm/.build - key: spm-v4-blacksmith-macos27-native-${{ runner.os }}-${{ github.sha }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }} - restore-keys: | - spm-v4-blacksmith-macos27-native-${{ runner.os }}- - - name: Discard metallibs restored by the generic SwiftPM cache - run: | - for root in provider-swift/.build libs/mlx-swift-lm/.build; do - [ ! -d "$root" ] || find "$root" -type f -name mlx.metallib -delete - done - - name: Build provider-swift - working-directory: provider-swift - run: | - swift build -c release --product darkbloom - swift build -c release --product darkbloom-fan-helper - - name: Save SwiftPM cache - uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 - with: - path: | - ~/Library/Caches/org.swift.swiftpm - ~/Library/org.swift.swiftpm - provider-swift/.build - libs/mlx-swift-lm/.build - key: spm-v4-blacksmith-macos27-native-${{ runner.os }}-${{ github.sha }}-${{ hashFiles('provider-swift/Package.resolved', 'libs/mlx-swift/Package.swift', 'libs/mlx-swift-lm/Package.swift') }} + # The cluster jobs run only when their inputs changed (and on + # pushes); a skip passes only when the classifier did not select them. + case "$CLUSTER_CHANGED" in + true) cluster_expected=success ;; + false) cluster_expected=skipped ;; + *) exit 1 ;; + esac + test "$CLUSTER_RESULT" = "$cluster_expected" + test "$CLUSTER_FOCUSED_RESULT" = "$cluster_expected" diff --git a/.github/workflows/component-changes.yml b/.github/workflows/component-changes.yml index b08aa8a116..1d2e566fb8 100644 --- a/.github/workflows/component-changes.yml +++ b/.github/workflows/component-changes.yml @@ -7,6 +7,8 @@ on: value: ${{ jobs.changes.outputs.provider }} sdk: value: ${{ jobs.changes.outputs.sdk }} + cluster: + value: ${{ jobs.changes.outputs.cluster }} permissions: contents: read @@ -20,6 +22,7 @@ jobs: outputs: provider: ${{ steps.paths.outputs.provider }} sdk: ${{ steps.paths.outputs.sdk }} + cluster: ${{ steps.paths.outputs.cluster }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: diff --git a/.github/workflows/release-dev-branch.yml b/.github/workflows/release-dev-branch.yml index fdfebf8928..24669f7a94 100644 --- a/.github/workflows/release-dev-branch.yml +++ b/.github/workflows/release-dev-branch.yml @@ -68,6 +68,7 @@ on: - 'scripts/provider_release_github.py' - 'scripts/provider_release_identity.py' - 'scripts/provider-signing-validation.py' + - 'scripts/provider-build-default.py' - 'scripts/provider-cluster-runtime-models.py' - 'scripts/provider-cluster-runtime-facts.sh' - 'scripts/build-cluster-helpers.sh' diff --git a/.github/workflows/release-provider.yml b/.github/workflows/release-provider.yml index 00d73c0df3..ed256821db 100644 --- a/.github/workflows/release-provider.yml +++ b/.github/workflows/release-provider.yml @@ -158,6 +158,14 @@ jobs: with: ref: ${{ steps.trust.outputs.source_sha }} persist-credentials: false + # Every run except a dev push builds master's source (a tag, a master + # push or a dispatch), whose plain build must be prod even though the + # build sets DARKBLOOM_RELEASE_ENVIRONMENT. A wrong default stops the run + # here, before any build or signing. The dev branch defaults to dev; CI + # checks that one. + - name: Check that master's plain build defaults to prod + if: github.ref != 'refs/heads/dev' + run: python3 scripts/provider-build-default.py --branch master - id: pick env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/release-swift.yml b/.github/workflows/release-swift.yml index 0432033734..1a5aa3ee0f 100644 --- a/.github/workflows/release-swift.yml +++ b/.github/workflows/release-swift.yml @@ -63,6 +63,7 @@ on: - 'scripts/provider_release_github.py' - 'scripts/provider_release_identity.py' - 'scripts/provider-signing-validation.py' + - 'scripts/provider-build-default.py' - 'scripts/provider-cluster-runtime-models.py' - 'scripts/provider-cluster-runtime-facts.sh' - 'scripts/build-cluster-helpers.sh' diff --git a/changelog.d/app-attest-first-episode.md b/changelog.d/app-attest-first-episode.md new file mode 100644 index 0000000000..e1802854a5 --- /dev/null +++ b/changelog.d/app-attest-first-episode.md @@ -0,0 +1,4 @@ +### App Attest restart covers the first episode after an update + +- The `is_supported_false` restart now also works in the first process after an update from a version that did not record its App Attest authorizations. At serve start, when `app-attest-verified.json` is missing, the provider fills it once from the previous `daemon-state.json`, with evidence from the last 7 days: the last successful Apple call of a stored key that Apple attested, or an App Attest grant left by an unclean exit. All other conditions stay the same. +- A Mac whose previous provider was itself reporting `is_supported_false` has no such evidence, so it still waits for the coordinator to grant App Attest again. diff --git a/changelog.d/app-attest-unsupported-restart.md b/changelog.d/app-attest-unsupported-restart.md new file mode 100644 index 0000000000..97ed5acd15 --- /dev/null +++ b/changelog.d/app-attest-unsupported-restart.md @@ -0,0 +1,6 @@ +### App Attest recovers by itself after a self-update + +- A provider that launchd runs as its provider job now relaunches through launchd after a startup self-update, as it already did after a background update. Only a provider that launchd does not run, such as `darkbloom start --foreground` in a terminal, replaces itself in place. A background update or App Attest restart in such a provider no longer starts the LaunchAgent instead. +- When App Attest reports `is_supported_false` on a Mac that the coordinator verified for App Attest in the last 7 days, the provider restarts once through launchd. It waits until the state lasts 5 minutes and the provider is idle, and it checks Apple's answer again after the drain. If the new process still reports unsupported, it does not restart again until the coordinator verifies the Mac again. This restart and the stall restart share one limit: one automatic App Attest restart per 6 hours. Cluster members never restart for it. +- The provider keeps the time of its last App Attest authorization in `app-attest-verified.json` beside the daemon state file. +- The local provider log gets an `App Attest entitlement evidence` line at startup and at each `is_supported_false` answer: the start reason, the App Attest entitlements of the running process and of the code on disk, and the executable's modification time relative to the process start. It is not sent to the coordinator. diff --git a/changelog.d/checkpoint-row-decoder.md b/changelog.d/checkpoint-row-decoder.md new file mode 100644 index 0000000000..96ee68c9b4 --- /dev/null +++ b/changelog.d/checkpoint-row-decoder.md @@ -0,0 +1,10 @@ +### Cache restores finish sooner + +- Restoring a prefix-cache checkpoint decodes its older attention rows from the + default `balanced` checkpoint precision on the CPU. The decoder now checks each + row for values its native type cannot hold once per row instead of once per + eight values, with the same bytes and the same refusals. On Gemma 4 26B + follow-up requests served from the SSD cache, time to first token fell by about + 0.2 s per restore (about 25% over an 11-request conversation on an M3 Ultra), + and responses that save a checkpoint also end about 0.2 s sooner. Output is + unchanged. diff --git a/changelog.d/checkpoint-row-encoder.md b/changelog.d/checkpoint-row-encoder.md new file mode 100644 index 0000000000..0779a093f3 --- /dev/null +++ b/changelog.d/checkpoint-row-encoder.md @@ -0,0 +1,8 @@ +### Responses that save a cache checkpoint finish sooner + +- Saving a prefix-cache checkpoint encodes its older attention rows at the default + `balanced` checkpoint precision. That encoding now prepares its buffers and its + check once per segment instead of once per row and writes the same bytes. On a + Gemma 4 26B request that saves a checkpoint, the end of the response arrived + about 0.7 s sooner (1.7–2.0 s → 1.0–1.2 s on an M3 Ultra), with identical + output. Requests that save no checkpoint are unchanged. diff --git a/changelog.d/cluster-auto-update.md b/changelog.d/cluster-auto-update.md new file mode 100644 index 0000000000..96cfbf1c21 --- /dev/null +++ b/changelog.d/cluster-auto-update.md @@ -0,0 +1,10 @@ +### Pair Macs set up with `darkbloom cluster` update themselves + +- A Mac set up with `darkbloom cluster` now updates itself, as a single Mac does: with `auto_update` on (the default) and without `DARKBLOOM_NO_UPDATE_CHECK`, its cluster service checks the coordinator's latest release every 30 minutes, at the pair's update slot, which both Macs derive from their pairing's cluster ID. +- Each Mac downloads, verifies and stages the release while the pair serves. Only once both Macs have it does the pair stop taking new requests; the Mac that serves the pair finishes its accepted requests (at most 120 seconds, never cancelling one), then both Macs install the release and restart their cluster services, and the cluster sets itself up again for the new release with no command run. +- A pair under constant traffic updates too: once it takes no new requests, the accepted ones finish. A pair still running a request at the bound takes requests again and tries at the next slot. A release one Mac cannot download or verify is installed on neither Mac; both try again at the next slot. +- An installed release is promoted once its cluster service has stayed healthy for 10 minutes; three starts of its service that end on their own restore the previous release and quarantine the new one, as the watchdog does for a single Mac. +- Before a Mac restarts into an installed release, its cluster service runs the new `darkbloom --version` once (at most 30 seconds). A release that does not answer with its version is never restarted into: the Mac restores the previous release at once, quarantines the new one and starts its cluster service again, so a release that cannot start no longer leaves the Mac with nothing to roll it back. +- `darkbloom update` on a cluster Mac installs the release and then restarts the cluster service into it together with the other Mac, after the pair drained; logging out and back in is no longer needed. Run it on both Macs (or let the other Mac update at the next slot); the first Mac waits up to 15 minutes for the second, also when automatic updates are off. A Mac whose partner has automatic updates off downloads nothing at the slot. +- A pair that serves on the leader's local API, or a Mac that serves alone, is not drained for an update yet: it does not update while it serves, and a cluster set to serve locally (`darkbloom cluster local`) or a Mac serving alone downloads nothing at the slot. +- A cluster service started by an earlier release does none of this: to reach this release, run `darkbloom update` on both Macs, then log out and back in on both (or restart them) once. diff --git a/changelog.d/cluster-feature-parity.md b/changelog.d/cluster-feature-parity.md new file mode 100644 index 0000000000..5836a1a955 --- /dev/null +++ b/changelog.d/cluster-feature-parity.md @@ -0,0 +1,6 @@ +### Tensor parallel only where it keeps every feature + +- On a two-Mac pair, Gemma 4 and MiMo V2.6 Flash use tensor parallel only where it keeps every feature and caching behavior of the mode it would replace: prompt-prefix and SSD cache reuse, speculative (MTP) rounds, batch lanes, media, penalties and logit bias, stop handling and logprobs. What tensor parallel adds, such as logprobs where the pipeline has none, never counts against it. Each mode's features come from the installed cluster worker's capability record. +- Gemma 4's tensor parallel keeps every feature of its pipeline, prompt-prefix and SSD reuse included, so its measured speed decides. MiMo's tensor parallel decodes in speculative rounds, so it keeps every feature of the speculative pipeline and its measured speed decides; only where the plain pipeline is the mode it would replace do that pipeline's batch lanes keep it. The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop batch lanes up to 8 (it serves 1) that the pipeline keeps; held back until it keeps them."), and the model list says "tensor parallel: drops a feature". +- Where only tensor parallel fits the two Macs, the plan refuses with that reason and saves no setup, instead of saving one with fewer features. The developer's forced mode (debug builds) still places tensor parallel, and the plan says exactly what it drops. +- Qwen and GLM plans are unchanged. diff --git a/changelog.d/cluster-onboarding-simple.md b/changelog.d/cluster-onboarding-simple.md new file mode 100644 index 0000000000..73e3b45e2f --- /dev/null +++ b/changelog.d/cluster-onboarding-simple.md @@ -0,0 +1,15 @@ +### Simpler two-Mac cluster setup + +- `darkbloom cluster` setup says far less: four steps (Connect, Pair, Model, Start), a line per thing that happened, + and the next thing to do last. Every choice is a list (↑↓ and enter, as `darkbloom start` picks models; numbered in + plain transcripts); q or Esc cancels. +- The model list shows only the models approved for clusters (GLM-5.3-Flash, Qwen3.8 27B, MiMo-V2.6-Flash and + Gemma 4 26B QAT) that the two Macs can serve, each with its size and its split: tensor parallel or pipeline. The + serving lines name the split too. +- The Mac you set up on leads and keeps leading: every plan puts rank 0 on it, the cluster service's own re-plans + included, so a pair set up with 0.10.6 whose other Mac took over leading moves back at its next plan. +- macOS's password and Local Network prompts come at stated moments (sudo in the terminal over SSH); both Macs ask + about Darkbloom's Local Network access right after pairing, and the setup waits until Allow or q. +- Both Macs confirm the pairing code; the Mac that follows only shows the status. The serving line says whether the + pair earns through Darkbloom or serves locally only. +- `darkbloom doctor` includes the cluster's checks on a Mac paired for a cluster. diff --git a/changelog.d/cluster-pair-equal-tensor-shares.md b/changelog.d/cluster-pair-equal-tensor-shares.md new file mode 100644 index 0000000000..7604e1c227 --- /dev/null +++ b/changelog.d/cluster-pair-equal-tensor-shares.md @@ -0,0 +1,5 @@ +### Qwen pairs of two different Macs register with the coordinator + +- Affected: a pair of two different Macs set up with `darkbloom cluster` to serve through Darkbloom, with a Qwen model planned in tensor parallel. The planner gave the faster Mac the larger share of every layer (for example 2:1 on an M3 Ultra and an M5 Max), and the coordinator registration cannot name unequal shares yet. Both Macs still said `Registered with the coordinator as a cluster member`, then each Mac's part refused to register ("The saved roster registration is not valid for this Mac: invalidPlan"), the pair fell back to the leader's local API, and the coordinator never formed it or routed it a request. This hit Qwen3.8 27B, which pairs only in tensor parallel, and Qwen3.5 9B where tensor parallel was chosen. GLM-5.3-Flash, pipeline splits and two identical Macs were not affected. +- A pair served through Darkbloom is now planned with equal tensor-parallel shares, so it registers and is routed like a pair of identical Macs; on two different Macs the slower one sets the pace. A pair that serves you alone (`darkbloom cluster local`) keeps the faster unequal split. +- A setup saved with unequal shares (by 0.10.6, or a local cluster switched to Darkbloom with `p`) is not offered for pairing, and the leader says why before it stops either Mac's part: `Not offered for pairing: this Mac's check refused it: Unequal tensor-parallel shares serve local clusters only …`. If `darkbloom cluster` shows this once both Macs run this release, press `m` and choose the model again: it is planned with equal shares and registers. diff --git a/changelog.d/cluster-pair-follows-rollback.md b/changelog.d/cluster-pair-follows-rollback.md new file mode 100644 index 0000000000..6e9b06eb36 --- /dev/null +++ b/changelog.d/cluster-pair-follows-rollback.md @@ -0,0 +1,7 @@ +### Both Macs of a pair roll back together + +- When one Mac of a `darkbloom cluster` pair rolls a release back (three failed starts of its cluster service, a failed start check, or `darkbloom update --rollback` while its cluster service was stopped), the other Mac now rolls back to the same earlier release, and the pair serves it together. Before, the pair stayed split until a newer release updated both Macs. +- The other Mac checks at its start and every minute while no update runs, also with automatic updates off. It finishes the accepted requests of its part first, as for an update, restores the release it kept from before its last update, quarantines the rolled-back release and restarts. Both Macs then skip that release, and the next newer release updates both. +- A Mac that keeps another earlier release, or none, or whose part serves on the leader's local API or alone, does not follow (yet) and says so once in `~/.darkbloom/cluster-setup/service.log`. While a pair runs on it, a Mac whose partner stops answering during the follow waits at most a minute, then changes nothing and tries again at the pair's next update slot. A Mac whose partner quarantined a release does not install that release either. +- Both Macs need this release or a later one, and the release a Mac rolls back to must have it too: the Mac that rolled back reports the rollback from the restored release. A rollback of this release itself is therefore not followed; rollbacks of later releases are. +- To roll back a pair by hand, stop one Mac's cluster service with `darkbloom cluster stop`, run `darkbloom update --rollback` there, and start it again with `darkbloom cluster`; the other Mac follows. diff --git a/changelog.d/cluster-pair-serving-epoch.md b/changelog.d/cluster-pair-serving-epoch.md new file mode 100644 index 0000000000..c267c91d93 --- /dev/null +++ b/changelog.d/cluster-pair-serving-epoch.md @@ -0,0 +1,16 @@ +### Two-Mac pairs recover after losing a rank during a stop + +- A two-Mac pair no longer stays unable to serve when it loses a rank while + its slot is stopping. Until the provider restarted, its leader refused every + later start, and `darkbloom cluster stop` left that Mac's part still + releasing. +- Fixed a deadlock in the pair's request engine. Stopping the pair slot + cancelled a request's stream while the engine was telling that request the + pair had lost a rank. The stream's cancellation waited for the engine, and the + engine waited for the cancellation to finish, so the slot never stopped. + Cancellation and stream termination now never wait for the engine. +- The leader also releases a committed start as soon as its session ends, + instead of after the old slot has fully stopped, so a slow stop can no longer + make it refuse later starts with "a committed start is already served". The + release receipt still waits, bounded, for the slot to retire, and a pair still + never serves two slots at once. diff --git a/changelog.d/cluster-public-mimo-gemma.md b/changelog.d/cluster-public-mimo-gemma.md new file mode 100644 index 0000000000..af6f88c4e5 --- /dev/null +++ b/changelog.d/cluster-public-mimo-gemma.md @@ -0,0 +1,4 @@ +### MiMo-V2.6-Flash and Gemma 4 26B QAT serve public cluster traffic + +- Two more models are approved for public traffic on two-Mac clusters, in pipeline and tensor parallel, as GLM-5.3-Flash and Qwen3.8 27B are: MiMo-V2.6-Flash (`mimo-v2.6-flash-mopd`) and Gemma 4 26B QAT (`gemma-4-26b-qat-4bit`). A release's cluster runtime facts carry their pair-serving grants and parity qualifications, so a pair of either model earns through Darkbloom on any Apple silicon pair, and `darkbloom cluster` lists them. +- Their tensor parallel serves once its code is in the build (Gemma 4 and MiMo tensor parallel PRs); until then they pair as a pipeline. MiMo-V2.6-Flash's speculative pipeline, its default split, is declared too. diff --git a/changelog.d/cluster-service-follows-repair.md b/changelog.d/cluster-service-follows-repair.md new file mode 100644 index 0000000000..b96c0deef1 --- /dev/null +++ b/changelog.d/cluster-service-follows-repair.md @@ -0,0 +1,6 @@ +### A running cluster service answers after the Macs pair again + +- When the two Macs pair again while their cluster services run (`darkbloom cluster` or `darkbloom cluster pair`), each service starts its setup and control-lease listeners again with the new pairing within about 5 seconds. They used to keep the earlier pairing's key until the service restarted, so the other Mac's leases and its "Reading both Macs over the cable" step were refused (`refused (handshakeRejected)`). The service log says `this Mac's pairing changed (): answering the paired Mac with the new one`. +- A Mac left with no pairing stops answering over the cable. A pairing store that cannot be read leaves the listeners as they are. +- A Mac that paired again under a new Secure Enclave key of its own drops its earlier control state, as it already did when the other Mac's key changed. +- A cluster service started by an earlier release keeps the earlier behavior until it restarts (log out and back in, or `darkbloom cluster stop` and then `darkbloom cluster`). diff --git a/changelog.d/fastest-plan-evidence.md b/changelog.d/fastest-plan-evidence.md new file mode 100644 index 0000000000..83485417a1 --- /dev/null +++ b/changelog.d/fastest-plan-evidence.md @@ -0,0 +1,7 @@ +### Tensor parallel for Gemma 4 and MiMo only on measured speed + +- Gemma 4 and MiMo V2.6 Flash pairs choose tensor parallel only once tensor parallel's own speed is measured on both Macs: each Mac's half timed by a tensor-parallel load (Gemma), or requests this Darkbloom build served in tensor parallel. An estimate from the Macs' device index alone does not choose it, because the index overstates what half a model saves on big Macs: on two M5 Ultra it predicts a short Gemma request 6% faster in tensor parallel, where the plans expect decode 6-8% slower. +- When the estimate says tensor parallel would be faster, the pair keeps the pipeline. The plan's "Tensor parallel or pipeline" line says the predicted gain and that it comes from the device index, and the model list says "tensor parallel: not measured yet". +- Normal setups do not load tensor parallel to measure it, so these pairs keep the pipeline for now. MiMo does not yet time its halves at load, so MiMo pairs reach tensor parallel only from requests the same build served in tensor parallel. +- Tensor parallel must also keep every feature of the mode it would replace (see "Tensor parallel only where it keeps every feature"). +- Qwen and GLM still choose tensor parallel wherever it fits. diff --git a/changelog.d/fresh-mdm-removal-guidance.md b/changelog.d/fresh-mdm-removal-guidance.md new file mode 100644 index 0000000000..e6b044c65c --- /dev/null +++ b/changelog.d/fresh-mdm-removal-guidance.md @@ -0,0 +1,3 @@ +### Fresh MDM removal guidance + +- Keep `darkbloom status` and both `darkbloom doctor` authorization summaries from offering MDM removal when the coordinator decision is too old for removal readiness. An unexpired App Attest serving lease stays visible; removal advice asks for fresh readiness and keeps existing profiles installed. The `darkbloom unenroll` checks are unchanged. diff --git a/changelog.d/gemma-byte-fallback-flush.md b/changelog.d/gemma-byte-fallback-flush.md new file mode 100644 index 0000000000..3f22c7588c --- /dev/null +++ b/changelog.d/gemma-byte-fallback-flush.md @@ -0,0 +1,6 @@ +### Gemma 4 replies keep characters outside its vocabulary + +- A Gemma 4 reply that ended in characters its vocabulary writes as byte tokens, such as many newer emoji, rare CJK and most Hangul syllables, lost all of them: `all zipped up 🗜` came back as `all zipped up `, and a reply made only of such characters came back empty. A long reply could also corrupt such a character when streaming restarted its decode inside its bytes. +- The Swift tokenizer library releases byte tokens only when a later token arrives. The provider's tokenizer bridge now releases a trailing run itself. `/detokenize` keeps it too. +- Token IDs, numeric logprobs, sampling and cache keys do not change, with one exception: a stop string that a trailing run completes now matches when the run completes, one token sooner, so `completion_tokens` can fall by one. +- A streamed reply's `logprobs` gains the entries of those tokens, which it used to drop. A byte token's `logprobs` text and `bytes` are U+FFFD or its ASCII character instead of empty, not the real byte. A reply cut inside a character by `max_tokens` now ends in U+FFFD instead of dropping it. diff --git a/changelog.d/gemma-decode-command-buffers.md b/changelog.d/gemma-decode-command-buffers.md new file mode 100644 index 0000000000..49963036d1 --- /dev/null +++ b/changelog.d/gemma-decode-command-buffers.md @@ -0,0 +1,3 @@ +### Gemma 4 plain decode commits by operation count + +- Plain decode steps of Gemma 4, the rows served without its assistant, commit a Metal command buffer every 100 operations instead of many times per step. Outputs are bitwise identical. Prefill and assistant rounds keep MLX's defaults. diff --git a/changelog.d/gemma-decode-keeps-spaces.md b/changelog.d/gemma-decode-keeps-spaces.md new file mode 100644 index 0000000000..7b902c5121 --- /dev/null +++ b/changelog.d/gemma-decode-keeps-spaces.md @@ -0,0 +1,5 @@ +### Gemma 4 text keeps its spaces before punctuation + +- Gemma 4 replies, reasoning and tool arguments no longer lose the space before `.`, `,`, `?` and `!`, or repeat a quote. `git add .` came back as `git add.`, `bash ./run.sh` as `bash./run.sh`, `x != y` as `x!= y`, and, when streamed, `role = 'start'` as `role = ''start'`. +- Gemma 4's published `tokenizer_config.json` omits `clean_up_tokenization_spaces`, and the Swift tokenizer library reads a missing key as cleanup on, where Python Transformers reads it as off. The provider now resolves a missing key to off in memory for every model. An explicit Boolean is kept. +- Token IDs, sampling, model state and cache keys do not change. Only the text decoded from the same tokens does. Stop strings match the text as spelled: one with a space before punctuation can now match, and one that matched only the cleaned text (`add.` for `add .`) no longer does. diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md new file mode 100644 index 0000000000..171b5279d8 --- /dev/null +++ b/changelog.d/gemma-pipeline-speed.md @@ -0,0 +1,5 @@ +### Faster Gemma 4 pipeline pairs + +- Gemma 4 pipeline stages compute a prompt chunk's expert blocks in one shared dispatch per operation instead of one subgraph per prompt token, with the same bytes for every token (unchanged arithmetic receipt). Batch-decode rows share the same dispatch. On one synthetic expert layer this cut a 2,048-token chunk from about 370 ms to about 31 ms; pair throughput is not yet measured. +- A Gemma 4 pipeline pair whose setup prefills serially, coordinator-registered pairs included, now serves four requests at once. Each lane is admitted against live memory on both Macs. A pair planned with the one-chunk lookahead keeps serving one request at a time. +- The planner's hardware prior counts 8 of Gemma 4's 128 experts per token instead of every expert byte. diff --git a/changelog.d/gemma-tensor-parallel.md b/changelog.d/gemma-tensor-parallel.md new file mode 100644 index 0000000000..e2ecce6bfb --- /dev/null +++ b/changelog.d/gemma-tensor-parallel.md @@ -0,0 +1,7 @@ +### Gemma 4 tensor parallel on two-Mac clusters + +- Gemma 4 26B (QAT 4-bit and 8-bit) can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels, both share every token over the encrypted link, and the pair returns the same tokens a single Mac would on the synthetic checks. Text only. +- The planner chooses tensor parallel for Gemma 4 only where it predicts it faster than the pipeline, from tensor parallel's own speed measured on both Macs (see "Tensor parallel for Gemma 4 and MiMo only on measured speed"). Prompt-heavy requests keep the pipeline. Qwen and GLM still choose tensor parallel wherever it fits. +- In tensor parallel, Gemma 4 returns logprobs (`logprobs` / `top_logprobs`), and each Mac reserves memory for its own half of the model: about 8.0 GB of weights at QAT 4-bit (14.9 GB at 8-bit) plus its own KV, with a conservative 5.5 GiB activation reserve until a pair measures one. +- Gemma 4 tensor parallel keeps prompt prefixes as the pipeline does, in memory and in the encrypted SSD tier: a repeated or shared prompt prefix is restored only when both Macs hold it, with exactly the tokens of a request that prefilled the whole prompt, and it survives a restart of both Macs. Each request reserves room for its own prompt's prefix (about 0.44 GB a Mac for a 32K-token prompt); kept prefixes use free memory only and are dropped first when memory runs short. +- Gemma 4 tensor-parallel pairs serve one request at a time unless `DARKBLOOM_CLUSTER_BATCH_LANES` names more. Speed on a real pair is not measured yet. diff --git a/changelog.d/glm-tensor-parallel-stop-race.md b/changelog.d/glm-tensor-parallel-stop-race.md new file mode 100644 index 0000000000..e107a4a153 --- /dev/null +++ b/changelog.d/glm-tensor-parallel-stop-race.md @@ -0,0 +1,4 @@ +### A latent stop race in GLM tensor parallel's one-token decode + +- No released pair is affected, and serving is unchanged: every v0.10.6 GLM-5.3-Flash tensor-parallel pair loads the model's NextN (MTP) layer and decodes every request in MTP rounds, which already end both Macs together when a request stops just before the model's end token. +- The one-token decode, which only a build without that layer runs, now does the same: both Macs end at the end token and return the text up to the stop (for example, a stop string that matched just before the answer ended). Before, the stopped Mac built one more step alone and waited in a collective the other Mac, already finished at that token, never joined, so the request would stall and fail on both Macs. diff --git a/changelog.d/gptoss-decode-command-buffers.md b/changelog.d/gptoss-decode-command-buffers.md new file mode 100644 index 0000000000..986e75d062 --- /dev/null +++ b/changelog.d/gptoss-decode-command-buffers.md @@ -0,0 +1,3 @@ +### GPT-OSS plain decode commits by operation count + +- Plain decode steps of GPT-OSS commit a Metal command buffer every 100 operations instead of after almost every MoE layer. Outputs are bitwise identical. Prefill keeps MLX's defaults. diff --git a/changelog.d/mimo-pipeline-decode-buffers.md b/changelog.d/mimo-pipeline-decode-buffers.md new file mode 100644 index 0000000000..7f38c5d844 --- /dev/null +++ b/changelog.d/mimo-pipeline-decode-buffers.md @@ -0,0 +1,15 @@ +### MiMo pipeline decode command buffers and expert routing + +- MiMo V2.6 Flash pairs encode decode steps, lane steps and speculative rounds + in Metal command buffers of up to 100 operations with no input-size bound, as + GLM and Qwen tensor parallel already do. Prefill keeps the rank's limits. + Tokens, logits and caches are byte-identical on synthetic stages. The speed + effect on the registered model has not been measured yet. +- A MiMo request's memory charge now prices every full-attention layer's decode + score rows at once, which the larger command buffers can keep alive together. + The LOAD quote is unchanged. Only requests whose prompt frames are shorter + than a stage's full-attention layers times the decode rows (32 tokens at most) + are charged slightly more. +- The planner's hardware prior now counts MiMo's routed experts at the 8 of 256 + a token uses: 10.77 GB read per decode step instead of 166.6 GB. The prior + prices only tensor parallel, so MiMo's pipeline plans are unchanged. diff --git a/changelog.d/mimo-rotating-cache-metadata.md b/changelog.d/mimo-rotating-cache-metadata.md new file mode 100644 index 0000000000..8e62c2009e --- /dev/null +++ b/changelog.d/mimo-rotating-cache-metadata.md @@ -0,0 +1,11 @@ +### MiMo image-candidate pairs keep cluster prompt prefixes + +- A MiMo V2.6 Flash pair serving the private, local-only image candidate no + longer fails its requests while the cluster prefix cache is on (the + default). That candidate is the only MiMo load with contiguous caches. MiMo + still required the five metadata values that older MLX SDKs wrote for a + sliding-window cache, while the pinned SDK writes seven (adding the capacity + origin and a wrapped flag), so requests, text or image, failed at their + first prompt-prefix capture. Prefixes are now captured and restored. The + four text serving modes use paged histories with prefix reuse off and were + not affected. diff --git a/changelog.d/mimo-tensor-parallel.md b/changelog.d/mimo-tensor-parallel.md new file mode 100644 index 0000000000..6b524874ca --- /dev/null +++ b/changelog.d/mimo-tensor-parallel.md @@ -0,0 +1,7 @@ +### MiMo V2.6 Flash tensor parallel on two-Mac clusters + +- MiMo V2.6 Flash text can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels and half of the output head, both share every token over the encrypted link, and on the synthetic checks the two Macs agree bit for bit with a one-process simulation of both halves. The image candidate stays a pipeline. +- Each Mac's half of a layer's attention output and feed-forward is kept at full 32-bit precision until both halves are added, then rounded once, so a pair never rounds more than one Mac does. On the synthetic checks, the two halves of an expert's output add up bit for bit to the full output that one Mac rounds once. +- The planner chooses tensor parallel for MiMo only where it predicts it faster than the pipeline with speculative decoding, which MiMo's qualification records credit 1.37x, from tensor parallel's own speed measured on both Macs (see "Tensor parallel for Gemma 4 and MiMo only on measured speed"). Two 128 GB Macs, which cannot hold MiMo alone, can serve it this way. Qwen and GLM still choose tensor parallel wherever it fits. +- In tensor parallel, MiMo returns logprobs (`logprobs` / `top_logprobs`), serves one request at a time with speculative decoding (see "MiMo V2.6 Flash tensor parallel with speculative decoding"), and each Mac reserves memory for its own half: 84.0 GB of weights plus its own KV, work and buffers, with a conservative 5.5 GiB activation reserve until a pair measures one (about 100 GiB per Mac at the longest request, the draft heads included). +- No MiMo tensor-parallel qualification record exists yet, and speed on a real pair is not measured. diff --git a/changelog.d/mimo-tp-speculative.md b/changelog.d/mimo-tp-speculative.md new file mode 100644 index 0000000000..6641eb2cd0 --- /dev/null +++ b/changelog.d/mimo-tp-speculative.md @@ -0,0 +1,8 @@ +### MiMo V2.6 Flash tensor parallel with speculative decoding + +- A MiMo V2.6 Flash tensor-parallel pair decodes with MiMo's own trained draft heads: each round checks up to two drafted tokens in one pass through the pair, so every token a round keeps shares that pass's link and weight costs. +- It is on by default: the installed provider starts both Macs' tensor-parallel workers with two drafts a round. +- Output is identical to tensor parallel without drafting, token for token and bit for bit on the synthetic checks: greedy (with or without logprobs) and sampled. Each Mac's halves stay at full 32-bit precision inside a round too, exactly as in a one-token step. Every kind of stop works inside a round. Requests with penalties or a logit bias, and sampled requests that ask for logprobs, decode one token at a time, as in the speculative pipeline. +- Each Mac holds the draft heads whole (about 2 GB more) and reserves their per-request state, and the plan counts both before it chooses tensor parallel. Two 128 GB Macs still fit, at about 100 GiB a Mac. +- Because MiMo's tensor parallel now keeps the speculative pipeline's rounds, feature parity no longer holds it back where that pipeline is the mode it would replace; its measured speed decides, and the plan credits the rounds no speed-up until they are measured. Where the plain pipeline is the mode it would replace, that pipeline's batch lanes still keep it. +- Not yet measured on a real pair: the speed-up, the heads' acceptance rate and qualification records. diff --git a/changelog.d/models-page-network-registration.md b/changelog.d/models-page-network-registration.md new file mode 100644 index 0000000000..e38dff93e8 --- /dev/null +++ b/changelog.d/models-page-network-registration.md @@ -0,0 +1,5 @@ +### The Models page shows what the network registered + +- Each model on the Models page now says whether this Mac's live registration carries it: "Registered with the network" (the network sends it requests), "Registered for Autopilot" (Autopilot can load it), or, for a selected or pool model, a warning "Not registered with the network yet". Before, the page showed only what was selected, downloaded or loaded, so a selected model the network did not know looked like it was serving. +- The provider writes the registered set to its state file (`registered_models`). +- A Mac with Autopilot that is busy at every check, or always under a lease, now reports a newly verified build after at most 10 minutes. The re-registration closes admission, lets accepted requests finish, then reconnects. Before, such a Mac could wait without end, and Autopilot could not use the build. diff --git a/changelog.d/pipeline-decode-buffers.md b/changelog.d/pipeline-decode-buffers.md new file mode 100644 index 0000000000..05582151fa --- /dev/null +++ b/changelog.d/pipeline-decode-buffers.md @@ -0,0 +1,15 @@ +### Pipeline decode command buffers for the remaining cluster models + +- Cluster pairs of the Qwen and Bonsai rows, Nemotron 3.5 Lightning, Gemma 4, + GPT-OSS 20B and GLM-5.3-Flash encode decode steps (pipeline and phase split), + lane steps and speculative rounds in Metal command buffers of up to 100 + operations with no input-size bound, as GLM and Qwen tensor parallel already + do. Prefill keeps the rank's limits. Tokens, logits and caches are + byte-identical on synthetic stages. The speed effect on registered models has + not been measured yet, and each family keeps the change only if a pair A/B + shows a gain. +- A request's memory charge on those pairs, other than GLM's, now prices every + attending layer's decode rows at once, which the larger command buffers can + keep alive together. The LOAD quotes are unchanged. Only requests whose prompt + frames are shorter than their decode rows (at most 80) are charged more, and + only on a rank that decodes. diff --git a/changelog.d/provider-enabled-filter-wins.md b/changelog.d/provider-enabled-filter-wins.md new file mode 100644 index 0000000000..fcf1abe7b2 --- /dev/null +++ b/changelog.d/provider-enabled-filter-wins.md @@ -0,0 +1,7 @@ +### The enabled-model filter wins over coordinator model changes + +- A model you deselect with `darkbloom switch` or delete with `darkbloom models remove` no longer comes back on its own. Before, when the coordinator moved a public model to a newer build, every Mac serving that model downloaded the newer build, served it in place of the build its operator chose and loaded it, even when `enabled_models` left it out. For example, with `gemma-4-26b` selected and `gemma-4-26b-qat-4bit` deselected, `gemma-4-26b-qat-4bit` returned within minutes and `darkbloom status` showed `Serving outside the enabled model filter: gemma-4-26b-qat-4bit`. +- With `enabled_models` set, the provider now refuses a coordinator `load_model` or `prefetch_model` for a model outside it (`model_not_selected`), and keeps serving the build you selected when its public model moves to a build you did not list. The log then says `desired_models: → is outside the enabled model filter; not converging`. +- **Your provider no longer moves to a new build of a model by itself.** To take one, run `darkbloom switch` and pick the model's public name; the picker shows its newest build under that name. Until you do, the newer build gets that model's requests first. +- `darkbloom switch` applies its selection as the filter at once, without a restart. +- Nothing changes with an empty `enabled_models` (serve every downloaded model), or for Autopilot's consented downloads and placements. diff --git a/changelog.d/provider-process-exit-wait.md b/changelog.d/provider-process-exit-wait.md new file mode 100644 index 0000000000..5771412db8 --- /dev/null +++ b/changelog.d/provider-process-exit-wait.md @@ -0,0 +1,3 @@ +### Child process exit waits + +- Report a finished child process without the former polling and run-loop delay. Bounded children (the paged-kernel preflight, update staging, runtime smoke and signature checks, `darkbloom doctor` and `verify` probes) are reported up to about 120 ms sooner each, and waiting for `launchctl`, `codesign`, `profiles`, `open` and `log` no longer runs the calling thread's run loop. Timeouts and the SIGTERM-then-SIGKILL escalation are unchanged. diff --git a/changelog.d/provider-status-app-attest-lease.md b/changelog.d/provider-status-app-attest-lease.md new file mode 100644 index 0000000000..36f92ec11d --- /dev/null +++ b/changelog.d/provider-status-app-attest-lease.md @@ -0,0 +1,3 @@ +### Provider status App Attest lease + +- Keep `darkbloom status` and `darkbloom doctor` reporting App Attest authorization until the coordinator lease expires. They required a renewal within the last 10 seconds, so one delayed renewal showed `Trust: self_signed / online` although serving continued. `darkbloom unenroll` still requires a renewal within 10 seconds before offering MDM removal. diff --git a/changelog.d/provider-update-rollback.md b/changelog.d/provider-update-rollback.md new file mode 100644 index 0000000000..ffa75cc843 --- /dev/null +++ b/changelog.d/provider-update-rollback.md @@ -0,0 +1,7 @@ +### Roll a Mac back to its previous release + +- `darkbloom update --rollback` restores the release a Mac ran before its last update. When the updater installs a release, it keeps the signed release it replaces; the rollback puts that release back, also after the new one has served for 10 minutes and was promoted. +- It shows the installed and restored versions and asks `Roll back to vX? [y/N]` before changing anything (`--yes` skips the question). The running provider finishes its accepted requests (`--timeout`, `--force` as for `darkbloom update`), the kept release replaces the installed one in the watchdog's journaled swap under the update lease, and the provider restarts on it. It contacts no coordinator. +- The rolled-back release is quarantined on that Mac: the provider's 30-minute update check, the startup check and the watchdog do not reinstall it, and the next newer release installs normally, so automatic updates can stay on. `darkbloom update --override-quarantine` installs it again on request. +- It refuses and changes nothing on a Mac that serves in a `darkbloom cluster` pair, while a provider runs in the foreground (`darkbloom start --foreground`), while another update or recovery runs, when no earlier release is kept or the kept one is already installed, when the installed bundle is not the release the updater recorded, and when the kept release fails its hash or signature check. +- Only one earlier release is kept. A Mac rolls back to the release it ran before its last update, not further. diff --git a/changelog.d/qwen27-tp-decode-control.md b/changelog.d/qwen27-tp-decode-control.md new file mode 100644 index 0000000000..28d8a95e36 --- /dev/null +++ b/changelog.d/qwen27-tp-decode-control.md @@ -0,0 +1,22 @@ +### Qwen tensor-parallel decode control in the selection sum + +- A Qwen tensor-parallel pair's plain decode step now carries the next step's + plan and report in its own sealed selection sum, so the step pays one sealed + sum and one host read fewer than before. Tokens, logits and native state are + unchanged; assisted (MTP) rows, prompt steps and idle steps keep their own + exchange. +- Owner answers, cancellations and joins now apply one step later while plain + rows decode. A row decodes its next token once the owner answered the token + before it, so an answer that arrives while a step computes no longer leaves + the row idle for a step. Rank 0 still publishes a token only after the + owner's answer to the one before it. A token selected before a stop answer is + never published, so streamed text, usage and logprobs are unchanged. +- A clean stop the owner asks for (a stop string, for example) can cost one + more forward, which is discarded. On a one-lane pair every such stop after a + request's first token does (assisted rows excepted), and that request's + finish arrives one decode step later than before. +- Both ranks of a pair must run this build: the load agreement binds the new + control wire (`qwen-tp-independent-history-batch-v2-folded-control`). +- `darkbloom-cluster-tp-check qwen-decode` times the batch driver's decode on + two ranks over the loopback ring, with the control exchanged or folded, and + checks that both retire the same tokens. diff --git a/changelog.d/qwen27-tp-decode-loop.md b/changelog.d/qwen27-tp-decode-loop.md new file mode 100644 index 0000000000..8afa8a9b3b --- /dev/null +++ b/changelog.d/qwen27-tp-decode-loop.md @@ -0,0 +1,25 @@ +### Qwen tensor-parallel decode routes, row exactness and finiteness check + +- A Qwen3.8-27B tensor-parallel row now decodes the same bytes alone as beside + other rows and in verify windows on the registered weights. A one-row decode + step's fused SwiGLU computed its sigmoid with Metal's fast `exp`, while + cohort and window steps use MLX's precise `exp`. The two round a gate of + exactly bf16 -6.84375 differently, which could change later tokens. Dense + Qwen tensor-parallel output changes only where a one-row decode step meets + that gate value, and there it now equals the cohort path. Regenerate + tensor-parallel serving references recorded with earlier builds once. + Single-Mac output is unchanged. +- A non-finite logit on either rank of a Qwen tensor-parallel pair now fails + both ranks in the same selection step, before any token is published; + previously the other rank waited in the selection collective. The check moved + into the selection's sealed sum, so a decode step no longer pays a separate + finiteness read. Selected tokens are unchanged. +- Each rank logs its decode routes once per load, when it first serves + (`darkbloom-qwen-tp-decode-census-v1`): which projections take the + batch-invariant kernel and at which layout per row count, the attention and + residual-norm routes, and the arithmetic switches in force. +- `darkbloom-cluster-tp-check qwen-rows` checks, on one Mac over the loopback + ring, that a Qwen3.8-27B row decodes the same bytes alone, beside other rows + and in verify windows at the registered per-rank widths, with random weights + that follow the registered artifact's value statistics or with the registered + checkpoint itself; `qwen-rows layers` names the first layer that differs. diff --git a/changelog.d/qwen27-tp-default-lanes.md b/changelog.d/qwen27-tp-default-lanes.md new file mode 100644 index 0000000000..beaec56878 --- /dev/null +++ b/changelog.d/qwen27-tp-default-lanes.md @@ -0,0 +1,20 @@ +### Qwen tensor-parallel pairs serve up to 8 requests at once, sized to memory + +- `darkbloom cluster` now sets how many requests a Qwen tensor-parallel pair + serves at once: 8, 6, 4 or 2, the most that both Macs' memory holds now with + the full load reservation for that many. The pair serves them from its first + load. Before, it served one at a time: a local pair widened only after a + burst, through a reload the burst waited for, and a pair serving Darkbloom + traffic never widened. +- On two idle Macs, Qwen3.8-27B serves 8 at once from 64 GB a Mac without the + speculative assistant (4 at 48 GB, 2 at 32 or 36 GB), and 8 from 96 GB a Mac + with it (local clusters only); smaller Macs serve fewer. Two M5 Ultras serve 8 either + way. When not even 2 fit, the pair serves one request at a time, as before. +- Memory safety is unchanged: both Macs reserve that many requests' full memory + when the model loads and admit each request alone. A local pair set up + narrower still widens when requests queue; a pair set up for 8 is never + reloaded for it. +- Existing setups keep serving one request at a time until they are planned + again, as after an update. A pair serving Darkbloom traffic keeps its width + beside its approval; no approval, registration or committed-start digest + changes. diff --git a/changelog.d/qwen27-tp-prefill.md b/changelog.d/qwen27-tp-prefill.md new file mode 100644 index 0000000000..2f113dafb5 --- /dev/null +++ b/changelog.d/qwen27-tp-prefill.md @@ -0,0 +1,17 @@ +### Qwen tensor-parallel prompt wavefront + +- A Qwen tensor-parallel pair now prefills a text prompt faster, in steps of up + to eight consecutive 512-token frames built as one graph, layer by layer: + while one frame's sealed sum crosses the link, the next frame computes. Every frame + keeps its own shapes and kernels, so logits, KV, recurrent state, prefix + captures and tokens are unchanged. Steps run two frames while another lane + decodes and end at the prompt-cache capture point. Media prompts, assisted + (MTP) prompts, packed KV and routed-expert models keep one frame a step. +- The merged step's frames in flight are charged in LOAD, the placement quote + and each request's charge: a Qwen3.8-27B tensor-parallel rank needs about + 367 MB more at any width. +- `darkbloom-cluster-tp-check qwen-prefill --wavefronts 1,8` and + `darkbloom-cluster-tp-check qwen-wavefront` measure the merged steps on one + rank and on two ranks over the loopback ring. + `DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT=0` restores one frame a step for + diagnosis; both ranks must agree. diff --git a/changelog.d/qwen27-tp-prefix-depth.md b/changelog.d/qwen27-tp-prefix-depth.md new file mode 100644 index 0000000000..81b1598c15 --- /dev/null +++ b/changelog.d/qwen27-tp-prefix-depth.md @@ -0,0 +1,6 @@ +### Qwen3.8 27B tensor parallel reuses whole prompt prefixes + +- A Qwen tensor-parallel pair now reuses a repeated prompt's prefix to its last whole 512-token chunk instead of at most 4,096 tokens, including prompts longer than 32,768 tokens: a repeated 33K-token prompt restores 32,768 tokens on both Macs, as one Mac does. It also keeps the boundaries the next turn of a conversation and prompts that share a long system prompt need, so in each of these cases it reuses at least what one Mac reuses, to the nearest 512 tokens. +- A prefix restored from memory returns exactly the tokens of a request that prefilled the whole prompt (checked bit for bit on synthetic pairs at 8K, 16K and 32K boundaries); one restored from the SSD tier's default `balanced` records is close but not identical, as before. Both Macs must hold a boundary; otherwise both start from zero. +- Each request reserves room for its own prompt's prefix (about 1.8 GB a Mac for a 32K-token prompt on the 27B), and a pair loads with one such prefix per lane: about 1.1 GB a Mac more than before at one lane. Every pair size that ran the 27B in tensor parallel still does. Kept prefixes use free memory only (half of what is left after loading) and are dropped first when memory runs short. Prefixes kept on SSD by an earlier build are not reused. +- Requests served by the assistant (MTP) lanes still reuse at most 4,096 prompt tokens, less than one Mac reuses for a long prompt; deepening them is a separate change. Speed on a real pair is not measured yet. diff --git a/changelog.d/reasoning-stop-outside-reasoning.md b/changelog.d/reasoning-stop-outside-reasoning.md new file mode 100644 index 0000000000..ce6d54f182 --- /dev/null +++ b/changelog.d/reasoning-stop-outside-reasoning.md @@ -0,0 +1,18 @@ +### Stop sequences no longer match Gemma 4 or `` reasoning + +- A client `stop` sequence on Gemma 4 models such as `gemma-4-26b-qat-4bit`, + and on models that reason in `` blocks (Qwen 3.5, 3.6 and 3.8, + among others), now matches only the text returned as `content`. With + reasoning on, it used to match the reasoning too, so a sequence that + appeared while the model reasoned (for example `"."` or `"\n\n"`) ended the + request before any answer: `finish_reason` `stop`, reasoning only, empty + content. +- With tools declared, tool-call frames are not cut either, except a frame + whose arguments quote its own closing tag, or a bare `` frame + written without its wrapper. When a request has no tool handler (no declared + tools, or a media request on a family without native media tools), a literal + tool tag in an answer is text the client receives, and stops still apply to it. + Whitespace before the answer's first character (the blank line after + ``) cannot complete a stop sequence on its own. +- A stop sequence that names a marker no longer fires on it: ``, or + `` with tools declared. diff --git a/desktop-app/src/renderer/features/models/ManualModels.tsx b/desktop-app/src/renderer/features/models/ManualModels.tsx index 7e87329e96..b9daffe305 100644 --- a/desktop-app/src/renderer/features/models/ManualModels.tsx +++ b/desktop-app/src/renderer/features/models/ManualModels.tsx @@ -10,6 +10,7 @@ import { RemoveModelDialog } from './RemoveModelDialog'; import { ModelEarningsAmount } from './ModelEarnings'; import type { ModelEarnings } from './earnings'; import { ExpandableModelList } from './ExpandableModelList'; +import { ModelRegistration } from './ModelRegistration'; const filters = [ { id: 'all', label: 'All' }, @@ -142,6 +143,7 @@ export function ManualModels({ {model.reason && {model.reason}} +
diff --git a/desktop-app/src/renderer/features/models/ModelRegistration.tsx b/desktop-app/src/renderer/features/models/ModelRegistration.tsx new file mode 100644 index 0000000000..b5436e85ff --- /dev/null +++ b/desktop-app/src/renderer/features/models/ModelRegistration.tsx @@ -0,0 +1,8 @@ +import type { NativeModel } from '../../../shared/contracts'; +import { registrationLine } from '../../models/facts'; + +export function ModelRegistration({ model, expected }: { model: NativeModel; expected: boolean }) { + const line = registrationLine(model, expected); + if (!line) return null; + return {line.text}; +} diff --git a/desktop-app/src/renderer/features/models/PoolRow.tsx b/desktop-app/src/renderer/features/models/PoolRow.tsx index b21d88cbe9..22d3c73200 100644 --- a/desktop-app/src/renderer/features/models/PoolRow.tsx +++ b/desktop-app/src/renderer/features/models/PoolRow.tsx @@ -3,6 +3,7 @@ import type { NativeModel, Operation } from '../../../shared/contracts'; import { Button } from '../../components/UI'; import { modelFacts } from '../../models/facts'; import { ModelGlyph } from './ModelGlyph'; +import { ModelRegistration } from './ModelRegistration'; import { ModelEarningsAmount } from './ModelEarnings'; import type { ModelEarnings } from './earnings'; import { poolLabels, type PoolState } from './pool'; @@ -78,6 +79,10 @@ export function PoolRow({ {modelFacts(model, true)} + {model.description && (
Model details diff --git a/desktop-app/src/renderer/models/facts.ts b/desktop-app/src/renderer/models/facts.ts index 62157ffc02..9cd1b7ce01 100644 --- a/desktop-app/src/renderer/models/facts.ts +++ b/desktop-app/src/renderer/models/facts.ts @@ -22,6 +22,22 @@ export function modelFacts(model: NativeModel, network = false) { .join(' · '); } +// Whether the network knows this Mac has the model. Selected or downloaded is not enough: only a +// model the live registration carries gets requests. `expected` is true for a model this Mac +// should register, so its absence is a warning; otherwise absence is not shown. +export function registrationLine(model: NativeModel, expected: boolean) { + switch (model.registration) { + case 'routable': + return { text: 'Registered with the network', warning: false }; + case 'autopilot': + return { text: 'Registered for Autopilot', warning: false }; + case 'none': + return expected ? { text: 'Not registered with the network yet', warning: true } : undefined; + default: + return undefined; + } +} + export function pinnedMemoryLine(snapshot: Snapshot, pinned: string[], noun: string) { const { needed, measured, exceeds, limit } = pinnedMemory(snapshot, pinned); const count = `${pinned.length} ${noun}`; diff --git a/desktop-app/src/shared/contracts.ts b/desktop-app/src/shared/contracts.ts index 805455adef..938cfe0b69 100644 --- a/desktop-app/src/shared/contracts.ts +++ b/desktop-app/src/shared/contracts.ts @@ -40,6 +40,10 @@ export interface NativeModel { // Listed by the Darkbloom catalog. Only these can be served to the network or enrolled in // Autopilot; a model found only on disk runs in Local only. Absent from older runtimes. network?: boolean; + // What this Mac's live coordinator registration carries for the model: `routable` in its + // models (the network sends it requests), `autopilot` in its Autopilot inventory only, `none` + // in neither. Null or absent when not connected or on an older runtime. + registration?: 'routable' | 'autopilot' | 'none' | null; description?: string | null; context_length?: number | null; family?: string | null; diff --git a/desktop-app/tests/modelsAutopilot.test.tsx b/desktop-app/tests/modelsAutopilot.test.tsx index 92b4d994c1..212867d7f1 100644 --- a/desktop-app/tests/modelsAutopilot.test.tsx +++ b/desktop-app/tests/modelsAutopilot.test.tsx @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import '@testing-library/jest-dom/vitest'; -import type { Action, Snapshot } from '../src/shared/contracts'; +import type { Action, NativeModel, Snapshot } from '../src/shared/contracts'; import { Models } from '../src/renderer/features/models/Models'; import { backendWith } from './onboardingFixtures'; import { poolSnapshot, succeeded } from './modelsFixtures'; @@ -282,3 +282,24 @@ describe('Autopilot phases', () => { await waitFor(() => expect(sent()).toEqual([{ action: 'autopilot_disable' }])); }); }); + +it('says which pool models the network has registered', () => { + const state = poolSnapshot(); + const registration: Record = { + 'gpt-oss-20b': 'routable', + 'gemma-4-26b': 'autopilot', + 'qwen-3.5-9b': 'none', + 'qwen-3.6-35b': 'none', + }; + renderModels({ + ...state, + models: state.models.map((model) => ({ ...model, registration: registration[model.id] })), + }); + expect(row('GPT-OSS 20B')).toHaveTextContent('Registered with the network'); + expect(row('Gemma 4 26B')).toHaveTextContent('Registered for Autopilot'); + const warning = within(row('Qwen 3.5 9B')).getByText('Not registered with the network yet'); + expect(warning).toHaveClass('warning-text'); + // Not downloaded, so not expected to register; unknown shows nothing either. + expect(row('Qwen 3.6 35B A3B')).not.toHaveTextContent(/registered/i); + expect(row('Kimi K2.6')).not.toHaveTextContent(/registered/i); +}); diff --git a/desktop-app/tests/modelsManual.test.tsx b/desktop-app/tests/modelsManual.test.tsx index 548ac7a01c..2787eadb33 100644 --- a/desktop-app/tests/modelsManual.test.tsx +++ b/desktop-app/tests/modelsManual.test.tsx @@ -2,7 +2,7 @@ import { afterEach, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; import '@testing-library/jest-dom/vitest'; -import type { Action } from '../src/shared/contracts'; +import type { Action, NativeModel } from '../src/shared/contracts'; import { Models } from '../src/renderer/features/models/Models'; import { backendWith } from './onboardingFixtures'; import { poolSnapshot, succeeded } from './modelsFixtures'; @@ -140,3 +140,24 @@ it('locks the manual selection while Autopilot is turning on', async () => { fireEvent.click(screen.getByRole('button', { name: /Apply selection/ })); expect(backend.act).not.toHaveBeenCalled(); }); + +it('says which selected models the network has registered', () => { + const state = poolSnapshot({ enabled: false, phase: 'off' }); + const registration: Record = { + 'gpt-oss-20b': 'routable', + 'gemma-4-26b': 'none', + 'qwen-3.5-9b': 'none', + }; + renderModels({ + ...state, + models: state.models.map((model) => ({ ...model, registration: registration[model.id] })), + }); + fireEvent.click(screen.getByRole('button', { name: /Show \d+ more models/ })); + const row = (name: string) => + screen.getByRole('heading', { name }).closest('article') as HTMLElement; + expect(row('GPT-OSS 20B')).toHaveTextContent('Registered with the network'); + const warning = within(row('Gemma 4 26B')).getByText('Not registered with the network yet'); + expect(warning).toHaveClass('warning-text'); + // Downloaded but not selected: not registering it is expected. + expect(row('Qwen 3.5 9B')).not.toHaveTextContent(/registered/i); +}); diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index c91f96c2e6..dc223ac6d2 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-10-31 +> Last updated: 2026-11-02 What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to @@ -54,6 +54,21 @@ not waive LOAD or live-memory checks. See `GPTOSSRequestStateBudget.estimate` in `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift`. +Pipeline decode steps of the Qwen catalog, Nemotron, Gemma 4 and GPT-OSS +encode under decode command buffers that can keep a whole stage step's +temporaries alive at once, so each request charge prices every attending +layer's decode rows together (one a layer, or a verify window's `depth + 1`; +every layer on a phase split's decoding rank, none on its other rank), and +never less than one prompt frame's attention transient +(`QwenResidentPrefillTransient`, `Gemma4PrefillTransient`, +`GPTOSSRequestStateBudget`). The LOAD quotes and activation floors are +unchanged; only requests whose prompt frames are shorter than their decode rows +are charged more. GLM's request charge already prices three copies of twice its +context on every DSA layer of a stage, well above what a decode step keeps and +reads on every layer at once. Attention-kernel partials beyond the priced rows are +not charged separately; see +[pipeline decode command buffers](inference.md#pipeline-decode-command-buffers). + Optional Qwen plain-pipeline batch cancellation retains a lane's memory charge until all its active and tentatively restored native sessions close. It then releases only that lane, without changing other lanes' reservations or the @@ -1050,6 +1065,10 @@ attention views and sliding repack storage. Keys and values are priced with their distinct registered widths. Host prompt/selected-token histories and shared native decode workspace remain additional. Both MTP target ranks price the larger of the prompt chunk and the admitted `depth + 1` verification window. +Every MiMo rank's workspace charge also prices each of its full-attention +layers' score rows for the decode rows at once, because decode command buffers +can keep a whole step in flight (`MiMoRequestStateBudget`, `decodeRows`; +[MiMo pipeline decode command buffers](inference.md#mimo-pipeline-decode-command-buffers)). The trained assistant preserves its whole previous allocation envelope and adds separately rounded resident and working pages. Phase rank 1 prices every target layer; both ranks retain the moving-state allowance during transfer. Image @@ -1082,6 +1101,16 @@ full-artifact memory fit, numerical parity or throughput; those require paired hardware qualification. The restore mechanism is described in [inference](inference.md#gemma-paged-prefix-restoration). +A serial-prefill Gemma 4 pipeline's default width +(`DistributedInstalledPlan.gemma4PipelineBatchLanes`, +[Gemma pipeline lanes](inference.md#gemma-pipeline-lanes)) adds no load-time +allocation: the paged pool's capacity is a ceiling, and pages are reserved per +request (`CBv2StageKVHost`). Each lane is charged its whole request state on +every rank and admitted against live memory (`QwenResidentRuntime.reserveLane`); +a lane the host cannot hold is refused alone, retryably. The measured +activation floor still applies: prompt frames run one per step and decode rows +add only M=1 work. + ## Bonsai packed projection arithmetic Bonsai 27B uses the [packed FP32 row path](inference.md#bonsai-27b-packed-fp32-rows) @@ -1122,6 +1151,82 @@ throughput. Keep existing cross-chip failures and require fresh full-artifact numerical and timing evidence for both scoped prompt policies. Attention and full-model composition retain their independent qualification requirements. +### Gemma 4 tensor-parallel rank memory + +A Gemma 4 tensor-parallel rank is charged its own share, not the whole model +(`Gemma4TensorParallelRequestBudget`, every array at the allocator's bound): + +| Charge | Held | Bytes (QAT 4-bit, 8,320-token request) | +|---|---|---| +| Weights: the plan's exact cut, overlap groups and zero rows included | per rank | 8,040,450,108 (8-bit: 14,915,635,260) | +| Its own KV heads of every layer (4 sliding, 1 full), residual rows | per request | about 364 MB (the whole model's: 719,380,600) | +| One prompt chunk's attention transient over its 8 query heads, or a decode step's one row on every layer where that is more (requests of 17 tokens or fewer) | per request | about 145 MB | +| FP32 partials (attention row, dense row, 8 expert rows and their packed copy) of a chunk, or of a decode step's row on all 30 layers where that is more, and 3 vocabulary rows | per request | about 113 MB | +| Prompt-prefix capture at its deepest boundary: its own full-attention rows for its prompt and one window of every sliding layer (`prefixCaptureBytes`); none when its cache is off | per request | 191,027,200 for an 8,319-token prompt (the LOAD quote's, for the profile's 32,768-token prompt: 441,384,960) | +| Activation floor: `UnifiedMemoryCap`'s conservative default, 5.5 GiB, until a pair measures one | per rank | 5,905,580,032 | +| Freed-buffer cache (half the allocator headroom) | per rank | 1,073,741,824 | +| Eight sealed frames of the packed collective (512 x 101,376 bytes and the seal) | per rank | about 415 MB | + +The layout's `requestAllowance` quotes one request at the profile's longest +context (65,536 tokens) and prompt plus the per-rank charges, and the worker's +LOAD gate reserves exactly that beside the shard. A reservation or lane asks +the live gate for every held request, the new one and the per-rank charges. The +planner still charges at least the pipeline's whole-model +`requestChargeEveryRankBytes`. The prompt-prefix memory tier is charged +nowhere: its budget is half the room the load measures beside the shard and +that quote (`QwenStagePrefixCache.budget(roomBytes:)`), and its entries give +way before any refusal +([Gemma TP prompt prefixes](prefix-cache.md#gemma-tp-prompt-prefixes)). A rank +whose prefix cache is off charges no capture. +Nothing here is measured on a pair; see +[inference](inference.md#gemma-tensor-parallel-placement). + +### MiMo V2.6 tensor-parallel rank memory + +A MiMo V2.6 tensor-parallel rank is charged its own share +(`MiMoTensorParallelRequestBudget`, every array at the allocator's bound). One +derivation gives the worker's LOAD gate, each reservation's charge and the +layout's `requestAllowance`: + +| Charge | Held | Bytes (65,536-token request, exact bounds) | +|---|---|---| +| Weights: the plan's exact cut (no padding) | per rank | 84,013,770,176 | +| Paged KV at its own KV heads (2 full, 4 sliding), sliding pages twice | per request | 882,769,920 | +| Every layer's gathered history and the widest again (a decode step's command buffers keep it in flight) | per request | 902,658,560 | +| One chunk's full-attention scores at its 32 query heads, FP32, as if materialized | per request | 4,294,967,296 | +| One chunk's activations, its FP32 partials (attention, feed-forward, the sum, 8 expert rows) and 4 vocabulary rows | per request | about 174 MB | +| Activation floor: `UnifiedMemoryCap`'s conservative default, 5.5 GiB, until a pair measures one | per rank | 5,905,580,032 | +| Freed-buffer cache (GLM's) | per rank | 4,294,967,296 | +| Eight sealed frames of a chunk's partial (512 x 16,384 bytes and the seal) | per rank | 67,117,056 | + +The LOAD gate admits the shard with one request at the profile's longest +context (65,536 tokens) and the per-rank charges, the planner's quote: about +100.5 GB, or about 104.8 GB (97.6 GiB) per rank with the 4 GiB loading +headroom. That fits a 128 GB Mac. A reservation asks the live gate for its own request and the +per-rank charges. Nothing here is measured on a pair; see +[inference](inference.md#mimo-tensor-parallel-placement). + +Every installed rank decodes in speculative rounds (`--mtp-depth 2`, on by +default: `ClusterMiMoTensorParallel`) and adds the charges below. The LOAD gate +adds all three before anything is read, with the per-request terms at the +profile's longest request; READY's capacity and each reservation add the two +per-request terms. The planner's quote counts the same: the heads whole on +every rank (the layout's `speculativeHead`, each tensor in whole pages) and the +two per-request terms in the layout's `requestAllowance` +(`MiMoTensorParallelResidentRuntime.placementRounds`), so the plan admits only +pairs the LOAD gate admits. + +| Charge | Held | Bytes | +|---|---|---| +| The three trained heads, whole on every rank (BF16) | per rank | 1,975,640,448 | +| The drafter's state: the product's bounded declaration at a 512-token chunk and depth 2 (`MiMoV26MTPAssistant.boundedRequestAllocation`) | per request | 438,426,984 | +| The window's extra rows at depth 2: each sliding ring once more per extra row, one page per layer, the window's rows twice (`MiMoTensorParallelRequestBudget.speculativeWindowBytes`) | per request | 36,347,904 | + +With them a rank still fits a 128 GB Mac: 107,281,620,648 bytes (99.9 GiB) with +the loading headroom, against a 115.2 GiB ceiling. See +[speculative rounds](inference.md#mimo-tensor-parallel-speculative-rounds) and +[placement](inference.md#mimo-tensor-parallel-placement). + ### Additional TP resident allocations TP layouts may carry allocator-bounded resident allocations outside their text @@ -1149,9 +1254,19 @@ projection constants and the transient batch conversion bank are charged separately, including unequal shards. Paged backing charges each lane its own BF16 page bank and partial-page replacement, and one full-history gather bank once for the owner: decode steps and verify windows attend pages in place, and -the driver runs at most one prompt frame per step, so only a prompt frame -gathers a history (`QwenTensorParallelBatchMemoryTests.fullHistoryGatherIsOnePromptFramesTransient` -measures both). Segment slack and allocator overhead stay charged. Collective scratch prices complete +the driver runs one lane's prompt step at a time, so only a prompt step's frames +gather a history (`QwenTensorParallelBatchMemoryTests.fullHistoryGatherIsOnePromptFramesTransient` +measures both). A prompt step that merges frames +([prompt wavefront](inference.md#qwen-tensor-parallel-prompt-wavefront)) adds +its further frames in flight once to the shared maximum +(`QwenTensorParallelPromptWavefront.inFlightBytes`: 367,001,600 bytes on a 27B +rank at 512-token frames) and keeps at most +`QwenTensorParallelPromptWavefront.sumsInFlight` sums unfinished. Over the +loopback ring (`darkbloom-cluster-tp-check qwen-wavefront`, 4-layer shards at +the 27B's per-rank widths, 11,264-token prompts and a 65,536-token context) a +merged step's peak rose at most 314 MB a rank above one frame's; without that +bound it rose 0.5-1.5 GB. `QwenTensorParallelPromptWavefrontTests.mergedStepTemporariesStayWithinTheirCharge` +checks the term in one process, whose sums complete as they are built. Segment slack and allocator overhead stay charged. Collective scratch prices complete sealed frames, including authentication overhead, through the existing request allowance. Media and assistant charges are not hidden in this text quote. @@ -1193,7 +1308,10 @@ a rank reserves it ([native context](inference.md#qwen27-tensor-parallel-native- the shard, two whole host tensors, aligned-read scratch and loading headroom. The placement and shard assessment add it to the LOAD peak and allocator ask; resident and request phases are not substitutes for that simultaneous peak. -No native gate or headroom threshold is reduced. Both ranks must fit current +No native gate or headroom threshold is reduced. Initial placement saves the +widest of these widths at which both ranks fit current observations, with +nothing credited ([saved width](inference.md#qwen-tensor-parallel-saved-width)). +Both ranks must fit current observations before replacement is proposed (crediting at most the running owner's resident weights on that Mac, and only for a replacement with the same split) and again after previous ownership releases, with nothing credited. Source-bound metadata and child-launch checks establish budget and @@ -1205,17 +1323,54 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacem ### Qwen27 TP batch prefix ownership -`QwenTensorParallelBatchPrefixBudget` separately bounds every compact attention, -conv and SSM array using the native allocator metadata. Full unsliced geometry -conservatively covers either rank and unequal shares. The complete native -batch allowance adds one snapshot bank per live lane plus two banks for the -resident cache; the existing live-state, gather, replacement and collective -charges remain. The metadata planner and verified LOAD call the same helper. -A reused prefix does not lower admission or refund the destination's future -state. The configured budget is a ceiling; cache arrays materialize only on -capture. See [prefix ownership](prefix-cache.md#cluster-sliding-prefix-adoption). +`QwenTensorParallelBatchPrefixBudget` prices one plain lane's prompt-prefix +capture, separately bounding every array with the native allocator metadata: +its own heads' keys and values to its deepest kept boundary, and one +convolution and SSM state for every boundary a prompt with that deepest +boundary keeps (`pricedStates`: the deepest, the margin boundary, and the +stripe boundaries up to nine, so at most eleven, and never fewer for a longer +prompt). Each request's reservation charges its own prompt's capture +(`QwenTensorParallelRequestCharge`); LOAD and the placement quote charge one +capture of the profile's longest prompt per lane (`promptTokens`), and nothing +for a resident tier. The geometry is the rank's own heads at LOAD and in each +rank's placement quote; without a rank, the full unsliced geometry covers either +rank and unequal shares. The existing live-state, gather, replacement and +collective charges remain, and a reused prefix does not lower admission or +refund the destination's future state. + +The memory tier that keeps captures after their requests is charged nowhere. +Its budget is half the room LOAD measures beside its whole quote +(`ClusterStagePrefixBudget.roomBytes`, `QwenStagePrefixCache.budget(roomBytes:)`): +at most a thirty-second of the Mac's memory, in 256 MiB steps, and 0 when the +room is under 512 MiB. The reservation and running-batch gates do not credit +its entries as the owner's own allocations, nor, while the SSD writer is busy, +up to its queue's byte bound for the retired captures it still holds; the +writer drains and then the entries give way before either gate refuses +(`QwenTensorParallelSnapshotCache.yieldingMemory`). A capture always keeps what +its request's charge covers. With no tier budget it keeps nothing resident and +still writes its SSD record. A request whose prompt exceeds the memory plan's +is charged at its own prompt, outside LOAD's per-lane quote +([native context](inference.md#qwen27-tensor-parallel-native-context)). The assistant's lanes +keep their single 4,096-token frontier and its two charged resident banks +(`QwenTensorParallelMTPPrefixBudget`). See [prefix ownership](prefix-cache.md#cluster-sliding-prefix-adoption). + +The registered Qwen3.8 27B, one rank's own heads at the memory plan (32,768 +prompt tokens, 65,536 context, 16 KiB allocator pages; +`QwenTensorParallelBatchPrefixTests`, `QwenTensorParallelPrefixPlacementTests`): + +| Term | Before (`qwen-tp-batch-grid-prefix-4096-v1`) | Now (`qwen-tp-batch-prefix-depth-v2`) | +|---|---|---| +| A lane's capture | 212,860,928 B (4,096 tokens) | 1,764,753,408 B (rows to 32,256 and nine recurrent states) | +| Resident tier in the quote | 425,721,856 B (two banks) | 0 (half the measured room) | +| LOAD request bytes, one lane | 9,184,591,872 B | 10,310,762,496 B | +| LOAD request bytes, eight lanes | 28,471,181,312 B | 40,460,599,296 B | +| Idle pairs the planner places tensor parallel on, one lane | 2 x 36 GiB and larger | the same; a rank needs 1,126,170,624 B more | +| The same, eight lanes | 2 x 96 GiB and larger | the same; a rank needs 11,989,417,984 B more | + +The planner rows leave out the vision tower's resident bytes, as the served +layout does; both columns leave them out alike. Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift` -(`derive`). +(`captureBytes`, `derive`). A drained automatic batch replacement uses the device index and this pair's recorded keyed-link measurement. Missing or invalid measurements continue to diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..1fe23bc81d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -57,6 +57,20 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/DistributedR `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledSession.swift`, and `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation+PairServing.swift`. +The cluster request engine owns one serial queue. Every stream `yield` and its +retirement latch resume their tasks from it, and resuming a task needs that +task's status lock. Task cancellation holds the same lock while its handlers +run. So the engine never waits for its queue from a cancellation path: a +request stream's `onTermination` and the admission cancellation hop onto the +queue without waiting, or run in place when already on it. The retirement task +never blocks a cooperative thread. Waiting there deadlocked a pair slot's +retirement: `EngineV2Bridge.shutdown` cancelled a pump while the queue +published that request's peer loss. Lease events, the owner's invalidation and +the public calls keep their synchronous queue order. Source: +`provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift` +(`onQueueWithoutWaiting`) and +`provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine+Admission.swift`. + The cluster setup liveness probe uses the same request validation as ordinary chat completions. `ClusterSetupProbeRequest` sends no family-specific thinking override, so each model’s prompt policy remains authoritative. @@ -77,7 +91,10 @@ assistant media remain unsupported; legacy model ingestion is unchanged. Sources ## Automatic local cluster batching -`DistributedAutomaticBatchFactory` keeps the initial singleton placement. A +`DistributedAutomaticBatchFactory` keeps the initial placement and its saved +width; a Qwen TP placement already saves the widest width both Macs admit +([saved width](#qwen-tensor-parallel-saved-width)), so it proposes only a +wider one (`DistributedAutomaticBatchFactory.replacementWidths`). A managed cluster API with queued demand may propose a wider plain pipeline for Qwen dense/routed experts, Bonsai, Nemotron Lightning, Gemma, GPT-OSS or the MiMo text plain-pipeline owner. Every Qwen TP row (the 9B and 27B dense rows, @@ -123,7 +140,16 @@ never negative), `rankN_weights_bytes`, `rankN_fit` and `rankN_device`. Existing per-request admission and LOAD safeguards remain authoritative. GLM, private-image and coordinator-installed native-member sessions do not use this -automatic policy. Explicit diagnostic mode or lane settings retain their choice. +automatic policy. A serial-prefill Gemma 4 pipeline, coordinator-installed or +local, starts at its installed default width +([Gemma pipeline lanes](#gemma-pipeline-lanes)); on a local pair this policy +can still widen it. Explicit diagnostic mode or lane settings retain their choice. + +A stage's resident prefix tier takes half the room that LOAD measures beside +its quote, in 256 MiB steps, up to a ceiling of a thirty-second of the Mac's +memory (`QwenStagePrefixCache.budget(roomBytes:maximumBytes:)`, and the idle +refresh `refreshBudget`). The ceiling is the Mac's own: `maximumBytes` +defaults to it. Automatic replacement reads the installed plan helper's device profile and the current pair's recorded keyed-link costs and served-request history. It uses @@ -222,8 +248,8 @@ and `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementBa ## Cluster setup presentation -`ClusterOnboardingDriver` presents connection, pairing, model choice, startup -and a test response as five stages. Completion requires the test response to +`ClusterOnboardingDriver` presents connection, pairing, model choice and +startup (with its test response) as four steps. Completion requires the test response to succeed; a failed response retains the saved setup for a later retry. After the test response succeeds, the control leader registers the pair with the coordinator when the coordinator serves a cluster approval for this pair @@ -246,21 +272,86 @@ serving intent or change model eligibility and placement. See the [guided two-Mac setup](../provider/two-mac-cluster.md) for operator steps. Lines name the two Macs for the screen that shows them -(`ClusterOnboardingMacName`): "this Mac" and "the other Mac ()", -because two Macs of one kind share the hardware name. The leader words an +(`ClusterOnboardingMacName`): "this Mac" and "the other Mac", with the hardware +name ("the other Mac ()") where a line must tell them apart, +because two Macs of one kind share it; only this Mac's own screen adds the name +System Settings gives it ("This Mac (Studio A) leads", +`ClusterOnboardingDriver.thisMac`). The leader words an answer to a command the other Mac forwarded for that Mac's screen (`OnboardingLive.answeringForwarded`, `here`, `there`), and the cluster service names members the same way in its control lines and refusals -(`ClusterOnboardingMacName.names`). A deployment line recorded for both Macs -keeps hardware names; lines shown now carry the screen's words -(`ClusterOnboardingDeployment.Share.label`). The Mac that joins ends its +(`ClusterOnboardingMacName.names`). The deployment line, recorded for both Macs +with hardware names, is no longer on the screens, which say one serving line +(`ClusterOnboardingReady.summary`, `ClusterOnboardingDriver.servesWords`). The Mac that joins ends its onboarding once paired, also for `darkbloom cluster local` -(`ClusterOnboardingDriver.joinedLocalLine`). The model list keeps one line per +(`ClusterOnboardingDriver.joinedLocalContinueLine`). The model list keeps one line per artifact and name (`OnboardingLive.presentedChoices`): a choice that cannot be served is left out when another offers the same digests under the same name, and an artifact this build serves is never called unsupported for a copy the worker does not take (`ClusterSetupPlanning.copyNotTaken`). +Every choice goes through one console call (`ClusterOnboardingConsole.choose`): +on a color terminal a list moved with ↑↓ and taken with enter that folds to the +chosen line (`ClusterOnboardingTerminal.pick`), elsewhere numbered lines and one +key read the same way on every console (`ClusterOnboardingChoice.match`), so the +plain transcript stays byte for byte the same on a terminal and a pipe. q or a +lone escape cancels any list, and a key that sends a sequence (an arrow) reads +as no key, so it never stops a wait (`ClusterOnboardingTerminal.key`). The +setup's list holds only models the owner approved for clusters +(`ClusterOnboardingModelChoice.validated`, `listed`; `OnboardingLive.approved` +against `ClusterPublicModels.declared`); an older leader's choices carry no +such field and are listed as they come. A member's `darkbloom cluster` shows +the status and where to manage the cluster, with a list only to set up a cable +port that is not set up yet (`ClusterOnboardingDriver.member`, `fixPortItem`); +the leader's is a list of the control operations (`ClusterOnboardingDriver.menu`). +A model's list line is its name, its size and the split's marker ("tensor +parallel" or "pipeline", `ClusterOnboardingDeployment.splitMarker`), then +"copy" or "download" when it must reach a Mac first +(`ClusterOnboardingModelChoice.listLine`); its shares, speed and +tensor-parallel note are planned and carried but not said. The serving lines +mark the running plan's split the same way after the model ("Serving … (pipeline) +at …", `ClusterOnboardingReady.summary`, from the setup each Mac saved). Every copy +of a missing model is a list as well, a short one with its predicted time +(`ClusterOnboardingDriver.provision`). The public-traffic line +(`ClusterOnboardingModelChoice.publicTraffic`) is said only for a private image +candidate; the serving line ends "(earning through Darkbloom)" or "(local +only)" (`ClusterOnboardingDriver.servesWords`). When the other Mac does not +answer over the cable, the leader asks **Try again** or **Cancel** +(`chooseAndServe`). + +The Mac the cluster was set up on leads. `LiveContext.plan` makes that Mac every +plan's rank 0, whichever Mac plans (`ClusterControlDerivation.planLeader`, from +the pairing's leader pin), the cluster service's re-plans on the control leader +included (after an update or a memory refusal), so a pair the joined Mac led +moves back at its next plan and the derived leadership (rank 0 of the adopted +plan) stays on the set-up Mac; when that Mac is not one of the plan's members +(no record, or one of an earlier pairing), the Mac planning takes rank 0, as +before. Before a plan exists derivation +prefers it among the members present (`ClusterControlDerivation.derive`, +`preferred`; `ClusterControlNode.preferredLeader`, from the pairing's leader +pin). A Mac that is away never leads, so failover is unchanged. + +macOS's permissions are asked at stated moments +(`ClusterOnboardingDriver.allowLocalNetwork`), and Connect's first line asks for +both ("Allow macOS's password and Local Network prompts.", +`ClusterOnboardingDriver.approvalsLine`). The command probes Local Network +access in the Connect step (`ClusterLocalNetworkAccess.probe`: one datagram to +the cable's subnet broadcast, refused with `EHOSTUNREACH` until allowed). macOS +lets a command run from a terminal or over SSH through by itself (TN3179), so +macOS asks only where the probe finds the cable blocked, naming the terminal app +or `sshd-keygen-wrapper` (`ClusterLocalNetworkAccess.commandApp`). The cluster +service, a launchd agent, probes as it starts, right after pairing, keeping each +outcome for the onboarding (`ClusterLocalNetworkAccess.startServiceProbe`, +`serviceState`). The onboarding waits for Allow until it comes or q, with no +time limit, and a service that reports nothing within `serviceReportSeconds` +(10 s) gets the prompt's line as an "if" (`localNetworkMaybeLine`); over SSH +(`ClusterLocalNetworkAccess.overSSH`) the lines put the prompt on the Mac's own +screen. Where macOS shows no approval window for the cable's port, the +link setup's owner-only script runs with sudo in the same terminal +(`ClusterOnboardingLinkResult.manualScript`, +`ClusterLocalNetworkAccess.runLinkScriptWithSudo`), with the terminal in its +ordinary mode while sudo reads the password (`ClusterOnboardingConsole.suspended`). + A DevNet build is installed as `Darkbloom Dev.app`, and its CLI is `darkbloom-dev`. A saved setup accepts a space in its installed paths (`ClusterConfigurationSyntax.installedPath`). The orphan sweep, the teardown @@ -1086,7 +1177,7 @@ threadgroup per page, with no zero fill, and a selection read copies each row with one SIMD-group (`GLM5NextPagedTransfers`). Plain decode steps (every row one token) and MTP rounds whose rows are all decode or verification rows (at most 8 tokens) commit a Metal command buffer every 100 operations with no -input-size bound, as Nemotron Super and Flint do for plain decode +input-size bound, as Nemotron Super, Flint and Gemma 4 do for plain decode (`GLM5NextDecodeCommandBuffers`); prefill chunks keep MLX's defaults. A longer row whose selection rows would read at least its history instead reads its whole latent plane once per layer through @@ -1558,6 +1649,15 @@ submits the frame. `SendHandle` and `ChunkSender` persist across reconnects, so an old request's frame processed after a replacement sink binds still passes this check; it does not enforce request-to-session identity. +Decoded text keeps a character the tokenizer writes as `<0xHH>` tokens wherever it +falls. swift-transformers' `ByteFallbackDecoder` releases those tokens only when a +later token arrives, so a decode ending in them drops them and shows nothing pending. +Gemma 4 writes characters outside its vocabulary this way, so `LocalTokenizerBridge.decode` +(`provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift`) +releases a trailing run itself. A partial run reads as U+FFFD, which `DetokenizerV2` +holds back, so its segment restart cannot land inside a character. A decoder that +spells or releases these tokens turns this off. + The chat template is rendered on every request. When caching is enabled for the request, `LocalTokenizerBridge` encodes the rendered prompt through `PromptTokenCache` (`provider-swift/Sources/ProviderCore/Inference/Prompting/PromptTokenCache.swift`): @@ -1581,6 +1681,15 @@ never crosses a cache scope; `DARKBLOOM_TTFT_PROMPT_CACHE=0` restores the unchanged path ([configuration](../reference/configuration.md#prompt-preparation-and-admission)). +Decoded text keeps the spacing the tokens spell, unless the tokenizer config sets +`clean_up_tokenization_spaces` to true. swift-transformers reads an absent key as +true, which drops the space in sequences such as ` .`, ` ,`, ` ?`, ` !` and ` 's`, +and can make a streamed decode repeat bytes it already sent. Gemma 4's published +config omits the key. `LocalTokenizerLoader` +(`provider-swift/Sources/ProviderCore/Inference/Prompting/LocalTokenizerLoader.swift`) +resolves an absent key to false in memory, as Python Transformers does, and keeps +an explicit Boolean. Input IDs, sampling and cache keys do not depend on it. + Bridge-side order (`EngineV2Bridge.submitTokenized`): request-id normalisation (`maxRequestIdLength = 256`; duplicates rejected) → first deadline check → translation (`maxTokens = request.max_tokens ?? @@ -1594,11 +1703,21 @@ The SSD stage runs before `engine.submit`, off the engine queue, while the engine may be evaluating another request's prefill chunk under MLX-Swift's process-wide `evalLock`. A provider-staged complete-checkpoint import therefore creates its destinations already available from host bytes and never evaluates -or fences them, so staging does not wait for that chunk +or fences them, so staging does not wait for that chunk; its CPU decode tests each +restored row once for values the native dtype cannot hold, and a refused row never +reaches a destination ([destination contract](../reference/ssd-kv-cache.md#complete-checkpoint-payload), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift` (`CBv2CompleteCheckpointImport`)). +A donor's stream retires only after its complete checkpoint is published +(`EngineLoopV2.finishAfterCompletePrefixPublication`), so export time is added +to the donating response's end. At a quantized checkpoint precision, export +encodes each older attention row on the CPU with one prepared row encoder per +segment read, which writes the scalar codec's exact bytes +([conversion](../reference/ssd-kv-cache.md#complete-checkpoint-payload), +`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/NativeQuantizedCheckpointTensorSource.swift`). + Segmented paged admission no longer waits for queued GPU work. A released row's free 64 MiB segments are parked per pool, up to `min(2 GiB, slot grant / 8)`, outside the grant, floor and ledger charge, and the next admission of the same @@ -2123,7 +2242,7 @@ disabled for this hybrid model. | `logit_bias` | `logitBias` — string keys parsed to non-negative `Int`; invalid keys dropped and counted | `[:]` | | `logprobs` + `top_logprobs` | `topLogprobs = logprobs ? min(20, max(1, top_logprobs ?? 0)) : 0` | `0` | | `max_tokens` | `maxTokens = max_tokens ?? 4096` | 4096 | -| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match; the reported sequence replays the same scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | +| `stop` | `stopStrings`, matched on held-back detokenised text (`StopHoldback`). GPT-OSS sets `stopStringScope` to the Harmony `final` message (`ModelEOSPolicy.stopStringScope`), so analysis and tool-call frames never match. Gemma 4 and `` parsers exclude their reasoning spans per request instead, starting inside reasoning when the prompt opened a think block, and their tool-call spans when the request parses tool calls (`ReasoningStopScope`). Otherwise a literal tool tag in an answer is text the client receives, so stops still apply to it. The native block engine (diffusion Gemma) matches the whole output, so its requests carry no scope. The reported sequence replays the request's scope (`EngineV2Bridge+StopSequence.swift`) | `[]` | | `min_p` | `minP`, forwarded by `EngineV2Bridge.submitTokenized` after translation | `0` | | `priority` | **Ignored**: always `0` | — | | `n`, `best_of` | **Not represented**: one alternative | — | @@ -2891,7 +3010,15 @@ a share of every layer, and one fewer than the members otherwise, as the coordinator requires. A setup with unequal tensor-parallel shares is refused at registration, because the provider does not encode the plan's `tensor_parallel_shares` yet: a plan without them is an equal split to the -coordinator. Under a model approval, which names no build, the plan also carries +coordinator. So a cluster served through Darkbloom is planned with equal shares +only (`ClusterPlacementPolicy.equalTensorShares`, which +`ClusterPlacementFlow.decide` sets for the coordinator scope: the guided setup, +the plans it forwards and the service's re-plans after an update or a memory +refusal), and a local cluster keeps the faster unequal split. Each Mac's check +of a cluster approval refuses one beside unequal shares +(`ClusterApprovalAttachment.attachment`; +[coordinator-paired member](../reference/configuration.md#coordinator-paired-member)). +Under a model approval, which names no build, the plan also carries the member's own runtime block (`ClusterPlan.runtime`: worker, capability, resource policy and profile from its saved setup, `DistributedInstalledNativeStart.runtimeBlock`), so both members must run the @@ -2961,9 +3088,18 @@ live line (`ClusterOnboardingDriver.move`, `ClusterOnboardingProgress.live`), laid out by `TransferProgressLine` through `ClusterTransferReports`; a transcript without a live line keeps only the reports `TransferProgressLine.takeLogLine` marks and the lines for the record. +Its restart line reads FileVault with `fdesetup isactive` +(`OnboardingLive.fileVaultOn`): five seconds, then SIGTERM and two more, and no +answer reads as unknown. The exit comes from `ProcessExitObserver`, which does not run the calling thread's run loop. After a Darkbloom update changes a Mac's worker digest, the control leader's cluster service re-plans and re-adopts the same model by itself -(`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`). A model change of +(`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`), once both Macs +answer with the same worker build (`ClusterOnboardingUpdate.oneBuild`): the +[pair's coordinated update](../provider/cluster-always-on.md#the-pairs-coordinated-update) +restarts the two Macs seconds apart, and a plan made while one still runs the +other build would fail and wait 600 s. A Mac that rolls a release back is followed by the other +Mac to the same release ([a rollback on one Mac](../provider/cluster-always-on.md#a-rollback-on-one-mac)), +which the leader then plans the same way. A model change of a serving cluster (`m`, or `darkbloom cluster local `) plans the same way: its list was priced while the running parts held their memory, where tensor parallel may not fit now, so once both parts stopped and both Macs gave the @@ -3042,7 +3178,8 @@ step boundaries; a lane without its answer cannot run another forward. The leader still exchanges headers and replies when no lane can advance, with `role.none` and no model work. This lets the follower admit a joining request while the provider's synchronous reservation is holding the queue needed to -answer an older token. The installed lane default stays one; multi-lane +answer an older token. The installed lane default stays one, except for a +serial-prefill Gemma 4 pipeline ([Gemma pipeline lanes](#gemma-pipeline-lanes)); multi-lane sampling, joining and native output equivalence require separate qualification (`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Batch/QwenBatchDecisionProgress.swift`, `QwenResidentRuntime.leadBatch`). @@ -3093,7 +3230,8 @@ the worker's pending acknowledgment Native, installed-owner and qualification gates enable independent retirement only for the existing Qwen-family lane adapters in plain pipeline with 2...8 -lanes (installed image candidates are excluded). The default stays one. Other +lanes (installed image candidates are excluded). The default stays one, except +for a serial-prefill Gemma 4 pipeline ([Gemma pipeline lanes](#gemma-pipeline-lanes)). Other modes retain their existing failure policy, and GLM tensor-parallel retirement and its eight-lane default are unchanged. A cancellation racing an already finishing lane retains the existing clean-finish linearization: native state @@ -3538,6 +3676,49 @@ part the same key with a different file (`ClusterServiceAgent.partHealthPath`, service's heartbeat and still waits for its registration as a supervised member. An empty or absent key is passed on unchanged. +One cluster service runs per home: it holds an exclusive `flock` on +`~/.darkbloom/cluster-setup/service.lock` while it runs, and `ClusterService.running` +reports whether one holds it. `darkbloom update --rollback` takes the same lock +(`ClusterService.holdStopped`) while it swaps the installed release, so no cluster +service starts on a release that is being replaced; a service that starts then +exits as already running, and its login agent starts it again +([`darkbloom update`](../provider/cli-reference.md#darkbloom-update)). + +## Cluster service listeners follow the cable and the pairing + +Each Mac's cluster service answers the other Mac on two listeners: the setup +exchange's (`ClusterSetupLinkExchange.port`) and the control lease's +(`ClusterSetupLinkExchange.controlPort`). A listener binds the cable's port and +address as they are when it starts, and is keyed with the pairing that holds +then (`ClusterSetupLinkExchange.Responder.pairing`). It refuses every handshake +the other Mac keys with a later pairing (`handshakeRejected` there), so a +listener left on an earlier pairing refuses every lease and setup request. + +At most once per `ClusterService.listenerCheckSeconds` +(`static let listenerCheckSeconds: Double = 5`) seconds for each listener, +`ClusterService.listenerChange` compares the listener with what holds now: + +- a cable on another port or address restarts it there; +- another pairing restarts it with that pairing. `ClusterSetupLinkExchange.Pairing.Identity` + compares both pins, the cluster label, the link epoch and the edge, never the + edge secret; every ceremony derives a new link epoch, so pairing the same two + Macs again is another pairing; +- no pairing at all stops it; +- a pairing store that cannot be read changes nothing, as an unreadable setup + record leaves a running part alone. + +Each restart or stop of the exchange's listener names its reason in the service +log; the control lease's listener restarts and stops without a line. The +control node of an earlier pairing is dropped once the pairing names another +local or peer member (`ClusterService.ensureControl`). + +Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift` +(`ClusterService.listenerChange`, `ensureResponder`), +`provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterServiceControl.swift` +(`ensureControlResponder`, `ensureControl`) and +`provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupLinkExchange.swift` +(`ClusterSetupLinkExchange.Responder`). + ## GLM tool-stream completion GLM tool output uses the SDK GLM parser to validate the complete tool suffix at @@ -3632,11 +3813,15 @@ and neither `tensorParallelMargin` nor a kept mode holds it back; a group that loads now still goes ahead of tensor parallel that would not. The reason line then gives the rule ("Tensor parallel: the model fits, so both Macs share every layer of every token.") unless tensor parallel is also predicted faster, when it -says the gain. Predictions are still made and reported. A first placement, before +says the gain. Predictions are still made and reported. A family whose plan +states `ClusterTensorParallelChoice.fastest` (Gemma 4, MiMo V2.6) is exempt: it is +placed in tensor parallel only where predicted faster, on every rank's measured +share step ([Gemma tensor-parallel +placement](#gemma-tensor-parallel-placement)). A first placement, before any load measured the link, plans tensor parallel on the keyed reduction a forced plan assumes (`tensorParallelAssumesUnmeasuredLink`, labelled as assumed), so a new pair's first setup is tensor parallel too: every plan made by `ClusterPlacementFlow.decide` -(the onboarding, `m`, the re-plan after a Darkbloom update or after two load +(the onboarding, **Change model**, the re-plan after a Darkbloom update or after two load refusals) is a first placement in this sense. Since tensor parallel's place no longer depends on the link's speed, the first load's keyed probe changes no choice, and nothing has to re-plan a pair after it. A pair still serves a @@ -3651,11 +3836,12 @@ pair's own fresh, keyed, owner-only link record, and without one it keeps the running setup. The planner's own default, and the plan tool without `--tensor-parallel-first`, keep the speed comparison. -The setup's model list (`ClusterOnboardingModelChoice.listLine`) ends a model's -one line with a short note when its layout has a tensor-parallel plan and the +The planner records a short note, which the setup's model list no longer says +(`ClusterOnboardingModelChoice.listLine`), when a model's layout has a tensor-parallel plan and the planner splits it otherwise, for example `tensor parallel: slower here`, `about as fast` -(inside the margin), `does not fit now`, `link unmeasured`, or `no tensor parallel -for this model`. The note comes from the planner's own assessment +(inside the margin), `not measured yet` (predicted faster on the device index +alone, for a family chosen only where faster), `does not fit now`, `link unmeasured`, +or `no tensor parallel for this model`. The note comes from the planner's own assessment (`ClusterPlacementExplanation.tensorParallelNote`, carried in `ClusterSetupPlanSummary.tensorParallelNote`). It has at most 33 characters, and the list keeps one line per model. A model without tensor-parallel facts gets no @@ -3709,7 +3895,10 @@ target positions over its step, since its rounds run windows; any other load by one over its plain step) before served requests calibrate them; a point already there, such as one served requests corrected, stays, and a speed known only as a ratio takes none. A probe times decode only, so prefill predictions -are what they were without it. +are what they were without it. For a family chosen only where faster, these +points, or the shard rates requests served in tensor parallel corrected, are +what lets a plan choose tensor parallel at all ([Gemma tensor-parallel +placement](#gemma-tensor-parallel-placement)). Measured with the same local timing on c38 kernels (27B, 2026-10-24), the M3 Ultra stepped 32.1 ms at 2/3, 24.9 at 1/2 and 22.5 at 2/5; the M5 Max 17.4 at @@ -3790,7 +3979,24 @@ forwards fuse, on the families measured byte-equal to the unfused operations the Gated DeltaNet convolution step (concatenation, depthwise convolution and SiLU) and its q/k normalization, the attention output gate, the SwiGLU product, and a single vector's gate, up and SwiGLU in one launch (a window keeps the two -projections: the fused kernel measured slower there). A residual stream +projections: the fused kernel measured slower there). That one-launch SwiGLU +(`AffineQuantizedVectors.projectSwiGLU`) computes its sigmoid as MLX's +`Sigmoid` does, with `metal::precise::exp`; Metal's default fast `exp` rounds +the bf16 gate -6.84375 to another SwiGLU value. Only a tensor-parallel batch +session's one-row decode step takes that kernel (it needs +`Qwen35BatchDecodeScope.exactVectors`; single-Mac serving and +`darkbloom-cluster-tp-check run` never do), so with the fast `exp` a registered +27B row alone left the bits of its cohort and window steps. Tensor-parallel +serving output recorded with an earlier build differs only where such a step +met that gate, and is regenerated once. +`AffineQuantizedVectorsTests.swigluEqualsTheCompiledSwiGLUAtEveryGateValue` +compares the kernel with the two projections and the compiled SwiGLU at every +normal bf16 and f16 gate value. The convolution step's SiLU +(`GatedDeltaConvolution`) still uses the default `exp`, so it can round +differently from the unfused SiLU that prompt chunks of more than eight tokens +take (`Qwen35DecodeFusionParityTests` finds f16 and f32 differences); every +decode row count and window of up to eight columns takes that kernel, so rows +still agree. A residual stream narrower than its norms (the Prism/Bonsai packs: FP16 packed embedding rows under FP32 norms and projections) keeps the unfused sum that promotes it to FP32 on every family (`Qwen35DecoderLayer.residualNorm`); the fused step @@ -4027,17 +4233,675 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Reside `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPlan.swift`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime.swift`, -`libs/mlx-swift-lm/Libraries/MLXLMCommon/Qwen35TensorParallelSwitchLinear.swift`, +`libs/mlx-swift-lm/Libraries/MLXLMCommon/TensorParallelSwitchLinear.swift` +(`TensorParallelSwitchLinear`, still also named `Qwen35TensorParallelSwitchLinear`), `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Qwen35.swift` (`Qwen35SparseMoeBlock`). See [focused cluster tests](../developer/test.md#focused-qwen35-moe-tensor-parallel-checks). +## Gemma 4 tensor-parallel foundation + +Gemma 4 26B A4B (`gemma-4-26b-qat-4bit`, `gemma-4-26b-8bit`) has a two-rank +tensor-parallel plan, SDK hooks, a resident runtime and one-Mac oracles. +`Gemma4ResidentAdapterDefinition` advertises `tensor_parallel_v1` beside the +pipeline, and the worker loads it into `Gemma4TensorParallelResidentRuntime`. +The planner places a Gemma pair in tensor parallel only where it predicts it +faster than the pipeline ([Gemma tensor-parallel placement](#gemma-tensor-parallel-placement)). + +`Gemma4TensorParallelPlan` (`gemma4_heads_and_expert_channels_v1`) gives every +stored text tensor of both registered artifacts one cut and refuses unknown, +misaligned, untied-head and vision tensors: + +| Part | Cut per rank | Collective | +|---|---|---| +| `q_proj`, `k_proj`, sliding `v_proj` | Rows of 8 query heads and their KV heads (4 sliding, 1 full); full layers keep K=V | — | +| `o_proj` | Input columns of those heads | FP32 partial summed before `post_attention_layernorm` | +| Dense MLP (2,112 = 33 groups) and every expert (704 = 11 groups) | Gate/up rows of half the channels; down input columns widened to whole groups | One packed collective per layer: every selected expert's FP32 row and the dense row, each summed before rounding, router weighting and its branch's post-norm | +| Router, norms, `layer_scalar`, embedding | Replicated | — | +| Tied head | This rank's half of the vocabulary rows (views of the embedding) | One per selection | + +An odd group count cannot split evenly, so both ranks store the middle group. +Each rank's gate and up projections carry zero rows (zero words, scales and +offsets) for the other rank's half of that group. Those channels are exactly +zero, the shared down columns add nothing on the rank that does not own them, +and both ranks hold 1,088 dense and 384 expert channels: equal shares. +A layer issues two collectives and a decode step 61. + +`Gemma4TensorShard` builds each rank from the SDK's own modules with half the +heads and the local widths. `Gemma4TextModel.installTensorParallel` then sets +three things: the `o_proj` sum, the packed feed-forward +(`TensorParallelSwitchLinear.carrying`, generalized from Qwen's), and the +vocabulary-split head. A model without it runs the unchanged single-Mac path. +`Gemma4TensorParallelSelection` chooses across ranks: + +- greedy: a two-value argmax collective; +- top-k logits and log probabilities: one gather of each rank's top-k and log-sum-exp; +- the whole row: `-0` padding, every bit kept, so the product's sampler draws the single-Mac token on every rank. + +Oracles run on synthetic checkpoints with the 26B's structure scaled down: + +- `simulated`: both real shards in one process, summing FP32 partials. Two + ranks over the sealed loopback ring equal it bit for bit. +- `split-sum`: the whole model with each row-parallel projection replaced by + two FP32 partials. It is the decomposition's oracle, bitwise equal to the + ranks on the CPU. On an M5 Ultra GPU, a 1,024-row full-attention `k_proj` at + prefill width rounds some rows unlike its 512-row half. + +`tp-check gemma run --path paged` runs `full`, `simulated` and `tp` through the +resident runtime's own request path instead of the SDK's legacy caches. +`tp-check gemma lanes` serves several requests together through the batch +driver and checks each against itself alone. + +### Resident runtime + +`Gemma4TensorParallelResidentRuntime` serves over a keyed, authenticated data +plane, and every collective is the sealed all-sum. By default it serves one +request at a time. With batch lanes (`DARKBLOOM_CLUSTER_BATCH_LANES`, bound +into the load agreement) it serves several through the shared batch driver +(`QwenTensorParallelBatchDriver`, with a Gemma executor), which carries joins, +stops, cancellations and retirements. + +- Load. `Gemma4TensorParallelVerifiedLoad` first verifies the whole artifact, + as a pipeline load does (`prepareGemma4ResidentSource`). It then checks both + pipeline stages' storage commitment and requires every text tensor to have + the plan's shape, refusing anything else before a byte is read. Each tensor + is one verified read, asked of the host memory gate first, cut to this + rank's part and materialized at once. +- Agreement. `Gemma4TensorParallelLoadAgreement` binds the registered row's + fingerprint, the mode's and the plan's terms, the prompt policy, the + selection, the lanes, the KV storage and the prefix cache (on in this build, + `Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes`; off only + by the diagnosis switch `DARKBLOOM_CLUSTER_PREFIX_CACHE=off`). A rank started + with any other value refuses its peer before reading weights. +- Probes. The load measures the link (`QwenTensorParallelLinkProbe`) and this + rank's own decode step with every sum local + (`Gemma4TensorParallelShareProbe`). The ready record carries both. +- Request state. Each rank keeps its own KV heads of every layer (4 sliding, + 1 full on the 26B) on a paged host + (`CBv2RequestGeometry(gemma4TensorParallelKinds:)`); pages grow with the + request. +- Prompt. Each chunk runs through the product's CBv2 entry + (`Gemma4TextModel.cbv2Prefill`, whose last layer keeps only the row it + projects) under the registered prompt policy (`Gemma4PrefillProjectionScope`), + on the request's chunk grid. +- Decode. One evaluation per step, with 100-operation command buffers. The + step is submitted layer by layer as the host builds it + (`Gemma4LayerSubmission`; evaluation order only). Lanes decode in one + forward under the explicit batch decode scope (`Gemma4BatchDecodeScope`), so + each row equals its request's own step bit for bit. +- Choice. Each step's token is agreed inside the step's own evaluation + (`Gemma4TensorParallelChoice`): + - greedy: the vocabulary-split argmax, carrying both ranks' stop flags in + its one collective; + - sampled: the whole row gathered to every rank, rank 0's draw with the + product's sampler, and one small collective for the token and flags; + - logprobs: a greedy request's from the vocabulary-split top-k gather, a + sampled request's from the product's sampler on rank 0. The greedy + token's logit is the row's maximum, agreed with the token, so its logprob + is the gather's first even when an exactly tied ID leads the gather (which + of a rank's tied IDs the partition keeps is not the argmax's rule). A + gather that does not lead with that logit is refused on both ranks. + + A stop on either rank (cancel, deadline, memory, the owner's stop, pages + that could not grow) ends both after the same step + (`Gemma4TensorParallelRequestLoop`). A rank that stopped commits nothing + more, but still ends at a stop token its peer commits. +- Prompt prefixes. Each rank keeps its own heads' state at a prompt's chunk + boundaries as the Gemma pipeline keeps a stage's, in the pipeline's memory + tier and the owner's encrypted SSD tier (`Gemma4TensorParallelPrefix`). A + request restores the deepest boundary both ranks hold after one sealed vote + and one sealed confirmation, or neither restores it, and then runs the rest + of the prompt on the same chunk grid: a restore equals the cold prefill bit + for bit. Solo requests and lanes alike + ([Gemma TP prompt prefixes](prefix-cache.md#gemma-tp-prompt-prefixes)). + +Memory is charged per rank (`Gemma4TensorParallelRequestBudget`; see +[hardware support](hardware-support.md#gemma-4-tensor-parallel-rank-memory)): +each request its own KV heads, attention transient, FP32 partials, vocabulary +rows and its own prompt's prefix capture; each rank once the conservative +activation floor, the freed-buffer cache and eight sealed frames. The transient +and the partials are a prompt chunk's, or a decode step's one row on every +layer where that is more: a step is submitted layer by layer in 100-operation +buffers, so several layers' temporaries are alive at once. Only requests +shorter than 30 tokens, prompt and output together, pay more (at most about +6.2 MB a rank); the LOAD quote is unchanged. The prefix memory tier lives in +measured free room and is not charged. A lane is gated with every held lane's +charge, the new one and the rank's reserve. Speculative decoding, media and a +measured activation floor are not built yet. + +### Gemma tensor-parallel placement + +`Gemma4PlacementFamily` states the plan's facts, so Gemma layouts list +`tensor_parallel_v1` and carry `tensorParallel`: + +| Fact | Value | Source | +|---|---|---| +| `plan`, `ranks` | `gemma4_heads_and_expert_channels_v1`, `[2]`, equal shares | `Gemma4TensorParallelPlan.name` | +| `reductionsPerLayer`, `reductionsPerStep` | 2 (attention, packed feed-forward), 1 (vocabulary-split selection): 61 a decode step | `Gemma4TensorParallelPlan.reductionsPerLayer` | +| `partialBytesPerToken`, `layerPartialBytesPerToken` | 101,376 (the dense and 8 expert FP32 rows), 112,640 (with the attention row) | `feedForwardPartialBytesPerToken`, `layerPartialBytesPerToken` | +| `stateDividesByHeads` | true: each rank keeps its own KV heads | `Gemma4TensorParallelPlan.kvHeadsPerRank` | +| `requestAllowance` | the rank's reserve at the profile's longest request, where the allocator's bound is known | `Gemma4TensorParallelRequestBudget` | +| `choice` | `fastest_v1` | `ClusterTensorParallelChoice` | + +Each stored tensor's cut is the plan's (`tensorParallelCut(ofStoredTensor:)`). +Both ranks store the down projections' middle quantization group and pad gate +and up with zero rows (`tensorParallelOverlapBytes`), so the layout counts those +bytes replicated and a rank's share is its exact cut: 8,040,450,108 bytes at +QAT 4-bit, 14,915,635,260 at 8-bit, the bytes the worker's load gate admits +(`Gemma4TensorParallelVerifiedLoad.shardEntries`). The tied embedding is listed +at both ends of a layout; a rank holds it once and its head reads half of its +vocabulary rows, so each end counts as divided. The family also states its +routing, 8 of 128 experts (`expertRouting`, `isRoutedExpert`), so the hardware +prior reads 2,424,219,708 weight bytes per QAT 4-bit token. + +**Prefill schedule.** A tensor-parallel candidate prefills serially +(`ClusterPrefillSchedule.planned`): every tensor-parallel runtime, Gemma's and +MiMo's included, admits only `serial_v1`, while a pipeline of the same model +takes the one-chunk lookahead. Planned with the lookahead, a Gemma or MiMo pair +in tensor parallel saved a setup its runtime refused at load (2026-11-03). + +**The fastest-plan rule.** `ClusterTensorParallelChoice.fastest` exempts a +family from `ClusterPlacementPolicy.tensorParallelFirst`: its tensor-parallel +candidate is ranked by the planner's own comparison, which chooses it only when +it is predicted at least `tensorParallelMargin` faster than the best other +placement, and a kept mode holds it back as it holds any other mode. The +comparison reads the pair's measured link (`ClusterLinkProbeHistory`, the median +of its recent probes) and each Mac's share probes +(`ClusterShareProbeHistory`), else the hardware prior. Before any load measured +the link, a first placement prices tensor parallel on +`ClusterTensorParallelChoice.assumedReduction` (0.1 ms per sealed all-sum and +2.5 GB/s, the slow end of what pairs measured) and the pipeline's transfers as +free; an automatic replacement assumes no link and keeps the pipeline. Qwen and +GLM state no choice and keep tensor parallel first. Gemma states it because one +decode step is mostly a per-token floor that two ranks do not halve, while 61 +sums cross the link: about 0.67-0.93x one M5 Ultra's decode, unmeasured +[INFERENCE]. + +**Feature parity before tensor parallel.** The guided step plans a `fastest` +family's tensor parallel only where it keeps every feature and caching behavior +of the mode it would replace (owner, 2026-11-01). Each mode's features come from +the worker's capability record (`ClusterRuntimeCapability.modeFeatures`, one +`ClusterServingFeatures` a mode), which the adapter declares beside its modes +from the facts its loads bind; the provider keeps no table of them: + +| Feature (`ClusterServingFeatures`) | Gemma 4 pipeline / tensor parallel | MiMo V2.6 plain pipeline / `pipeline_mtp_v1` / tensor parallel | +|---|---|---| +| `promptPrefixReuse`, resident | yes / no | no / no / no | +| `ssdPrefixTier` | yes / no | no / no / no | +| `speculativeRounds` (MTP) | no / no | no / yes / yes | +| `maximumLanes` | 8 / 8 | 8 / 1 / 1 | +| `requestMedia` | none / none | none | +| `penaltiesAndLogitBias`, `stopHandling` | yes / yes | yes | +| `logprobs` (committed tokens) | no / yes | no / no / yes | + +Gemma's come from `Gemma4ResidentAdapterDefinition.servingFeatures`, whose +`tensorParallelKeepsPromptPrefixes` its tensor-parallel load agreement binds +(`Gemma4TensorParallelLoadAgreement`). MiMo's come from +`MiMoResidentCapabilityMetadata.servingFeatures`: the widest lanes and paged +histories `MiMoBatchSettings` gives each mode, and +`MiMoTensorParallelResidentRuntime.servingFeatures`, whose lanes and prefix +setting its serving agreement binds and whose rounds are the depth the installed +owner launches every MiMo tensor-parallel worker with +(`ClusterMiMoTensorParallel.speculativeDepth`, bound by the speculative +agreement fields; [rounds](#mimo-tensor-parallel-speculative-rounds)). A record +without features (`ClusterRuntimeCapabilityCodec` writes no `modeFeatures`) +keeps its bytes. + +`ClusterModeParity`, in `ClusterPlacementFlow.decide` beside +`ClusterModelFeaturePolicy.admissibleModes`, applies the rule before the planner +ranks anything: + +1. The mode tensor parallel would replace is the one the plan chooses without + it: the same policy with its tensor-parallel modes left out. Where no other + mode places, every other mode is compared. +2. Tensor parallel must keep every feature of that mode + (`ClusterServingFeatures.dropped(by:)`). What it adds (logprobs, wider lanes) + never counts against it. +3. Otherwise its modes leave the policy, so no ordering (the margin, the + evidence hold, a kept mode, a better hardware group) brings it back. The + assessment's verdict is `dropsFeatures` (`ClusterPlacementPolicy.tensorParallelHeldForFeatures`), + the plan's line says, for example, "Pipeline: tensor parallel would drop + batch lanes up to 8 (it serves 1) that the pipeline keeps; held back until it + keeps them.", and the model list says `tensor parallel: drops a feature`. +4. Where tensor parallel is the only mode that places, the plan refuses rather + than save a reduced setup: "Only tensor parallel fits these Macs, and it would + drop ... No reduced-feature setup was saved." The result's `modesReason` + carries it to the setup screen. +5. The developer's forced mode (`DARKBLOOM_CLUSTER_FORCE_MODE`, debug builds) + still places tensor parallel, and the plan says exactly what it drops. +6. A `fastest` family whose record declares no features keeps tensor parallel + back: nothing shows it keeps them. + +Gemma's tensor parallel keeps every feature of its pipeline, prompt prefixes +included, resident and on the SSD tier (`Gemma4TensorParallelPrefix`), so the +evidence rule below decides for it. MiMo's tensor parallel decodes in speculative rounds, so it keeps every +feature of the speculative pipeline (and of the compact-decode pipeline and the +phase split), and the evidence rule below decides wherever one of those is the +mode it would replace. It is held back only where the plain pipeline is: that +pipeline declares 8 batch lanes and tensor parallel serves one ("Pipeline: tensor +parallel would drop batch lanes up to 8 (it serves 1) that the pipeline keeps; +held back until it keeps them."). On equal idle Macs in the placement checks' +device model, with MiMo's rounds credited and the heads priced, that is 106 GB +for 128 + 128 and 118 GB for a fresh pair's 32,768 + 32,768; from 104 GB +(where tensor parallel first fits) every other size replaces the speculative +pipeline, and no size fits tensor parallel alone (a planner scan on 2026-11-01, +the measured 29 µs link) [INFERENCE: the checks' device model, not measured +Macs]. The tensor-parallel-first families (Qwen, GLM) declare no features and +are not gated. Applied to them, the rule would leave GLM unchanged (its tensor parallel +keeps prompt-prefix and SSD reuse and adds rounds, eight lanes, images, video +and logprobs) but would move Qwen3.5 9B from tensor parallel to its +speculative pipeline, which its records credit 1.74x: Qwen tensor parallel +decodes in rounds only with the explicitly quoted assistant +(`QwenTensorParallelMTPPolicy`, `ClusterQwenTensorAssistantPolicy`). Whether +they adopt it is the owner's decision. + +**Evidence before tensor parallel.** A `fastest` family takes tensor parallel +only when every rank of the placement has a measured share step +(`ClusterDecodeSplit.measured`): a share probe of this model on that Mac +(`ClusterShareProbeHistory`; a speed record of this model's shard rates counts +for every Mac of its chip and OS build), or the shard rates that requests this +worker build served in tensor parallel corrected +(`ClusterServedCalibration.tensorParallelMeasurements`). Before that, a Mac's +share step comes from its device index (`ClusterHardwarePrior.weightSeconds`). +The index times each operation with its launch latency inside, so it overstates +the weight time a rank halves: for Gemma about 5.3 ms of an M5 Ultra's 11.1 ms +QAT 4-bit step, where the plan behind the rule infers 1.4-2.0 ms [INFERENCE]. A +tensor-parallel placement predicted faster by the margin on that prior alone +goes behind the best placement in another mode of its hardware group +(`holdingTensorParallelWithoutEvidence`). The assessment reports it as +`predictedFasterOnPriorOnly`, with the prediction, and its `evidence` says +`measured` or `priorOnly`; it is omitted for every other family. The plan's +"Tensor parallel or pipeline" line says, for example, "Pipeline: tensor parallel +is predicted 6% faster for requests of 128 prompt and 128 answer tokens (...), +but from the device index, not its own measured step; it can be chosen once its +step is measured on both Macs (a share probe at a tensor-parallel load, or requests +this build served in tensor parallel)." A plan that chooses tensor parallel on +measured steps adds ", on its own step as measured on both Macs". The setup's +model list says `tensor parallel: not measured yet`. + +The rule changes nothing else: + +1. A tensor-parallel placement in a better hardware group (it loads now, no + other mode does) still goes first, and a policy that leaves only tensor + parallel places it. +2. The developer's forced mode (`ClusterForcedMode`) places it with nothing + measured. +3. A kept mode is applied after the rule (`ClusterPlacementPolicy.keptMode`): + tensor parallel that the pair served before a Darkbloom update is kept on + the prior, as it is kept over any prediction, and a kept pipeline holds back + measured tensor parallel. +4. Families without a choice (Qwen, GLM) ask for no evidence, under the + provider's tensor-parallel-first rule or the plain comparison alike. +5. `rankQuoted`, which no `fastest` family uses, is unchanged. + +Only a tensor-parallel load records share probes, so a pair first gets evidence +from such a load: + +- the developer's forced mode (`DARKBLOOM_CLUSTER_FORCE_MODE=tensor_parallel_v1`, + debug builds only); +- the morning real-pair A/B, when its tensor-parallel loads run through the + installed session, whose leader records both ranks' probes + (`DistributedInstalledSession`); +- a qualification run that loads tensor parallel through the installed + session. Nothing else records probes: a `darkbloom-cluster-pair-check` run + writes no history. + +The probes are kept per model and member for 30 days, whichever worker build +recorded them, so a later plan of the same pair uses them. Gemma's +tensor-parallel load times a rank's share (`Gemma4TensorParallelShareProbe`) +before its ready record, which carries it to the leader. Served records count +only for the build that served them (`ClusterServedSpeedRecords.servedBy`). + +On the planner's own figures (`PlacementChecks`, `GemmaTensorParallelChecks.swift`), +the comparison and the evidence rule choose as follows; the guided step's feature +parity then keeps the pipeline in every row until Gemma's tensor parallel keeps +prompt prefixes: + +| Pair | Link | Request | Chosen | +|---|---|---|---| +| 2x M5 Ultra 256 GB | default (unmeasured) | 8,192 + 128, 1,024 + 128, 128 + 128 | pipeline | +| 2x M5 Ultra 256 GB | measured 29 us sums | 1,024 + 128 | pipeline | +| 2x M5 Ultra 256 GB | measured 29 us sums, no share probe | 128 + 128 | pipeline: tensor parallel predicted 1.40 s against 1.48 s on the prior alone | +| 2x M5 Ultra 256 GB | measured 29 us sums, share probes at 10.3 / 7.0 ms a half step | 128 + 128 | pipeline (1.63 s against 1.48 s) / tensor parallel (1.21 s) | +| 2x M5 Ultra 256 GB | measured 29 us sums, served in tensor parallel at 80 / 110 tok/s | 128 + 128 | pipeline / tensor parallel | +| 2x M5 Ultra 256 GB | measured 5 us sums, no share probe | 1,024 + 128 | pipeline: tensor parallel predicted faster on the prior alone | +| 2x M4 Pro 24 or 32 GB | default | 128 + 128 | pipeline: tensor parallel predicted 2.71 s against 3.05 s on the prior alone; on the 32 GB pair with share probes at 12 ms a half step, tensor parallel (2.82 s) | +| 2x M4 Pro 24 or 32 GB | default | 8,192 + 128 | pipeline | +| 2x M4 Pro 32 GB | measured 29 us / 109 us sums | 1,024 + 128 | pipeline (tensor parallel predicted faster on the prior alone) / pipeline | + +A family opts in by passing `choice: .fastest` where it builds its +`ClusterTensorParallelFamilyPlan`; its layouts then encode `"choice":"fastest_v1"` +and its golden layouts must be regenerated. Nothing in the planner names a family. + +Code map: + +- `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/` +- `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Gemma4TensorParallel.swift` +- `libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift` +- `libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift` (routes Gemma `tensor_parallel_v1` loads) + +See [focused Gemma 4 tensor-parallel checks](../developer/test.md#focused-gemma-4-tensor-parallel-checks). + +## MiMo V2.6 tensor parallel + +MiMo V2.6 Flash (`mimo-v2.6-flash-mopd`) has a two-rank tensor-parallel plan, +SDK hooks, a one-lane resident runtime and one-Mac oracles. The registered row +lists `tensor_parallel_v1` (text only; the private image candidate stays a +pipeline candidate), and the worker serves it when a launch asks for it. The +planner chooses it only where it predicts it faster than the pipeline +([MiMo tensor-parallel placement](#mimo-tensor-parallel-placement)). + +`MiMoTensorParallelPlan` (`mimo_v26_heads_and_expert_channels_v1`, CPU metadata) +disposes of every name in the registered 1,732-tensor inventory. The 1,103 text +tensors are divided or replicated; the 629 MTP, vision, audio and speech tensors +are excluded by name and refused as text, as is any unknown or misaligned name: + +| Part | Cut per rank | Collective | +|---|---|---| +| `q_proj`, `k_proj`, `v_proj`, sliding sink bias | Rows of 32 query heads and the KV heads they read (2 full, 4 sliding); head dims 192/128 as stored | — | +| `o_proj` | Input columns of those heads (4,096) | FP32 partial (its BF16 input widened exactly), summed in FP32, rounded once, before `post_attention_layernorm` | +| Dense layer 0 (16,384) | Gate/up rows, down input columns (8,192) | Same contract as `o_proj` | +| Routed experts (`[256, out, in]` banks) | Gate/up axis 1, down axis 2: 1,024 channels, 32 MXFP4 groups | Each rank's 8 expert rows from the stock banks and decode kernels, stored as FP32, combined locally in FP32 with the router's weights; one FP32 row summed, rounded once | +| Router, norms, embedding | Replicated | — | +| Untied `lm_head` | This rank's 76,288 vocabulary rows | One per selection | + +Every equal half lands on whole quantization groups and packed words, so no +rank stores padding: 84,013,770,176 B of text weights per rank. A layer issues +two collectives of one 16,384 B row per token, and a decode step 97. Decode runs +in MTP rounds by default, the three heads replicated whole beside the shard +([speculative rounds](#mimo-tensor-parallel-speculative-rounds)). + +The routed experts' partial is not the Qwen and Gemma one, which sums every +selected expert's FP32 row across ranks (`TensorParallelSwitchLinear`). A +MiMo rank keeps the stock half bank, so decode stays on the MXFP4 expert +kernel (`MiMoV26DecodeExperts` takes only a plain `QuantizedSwitchLinear`), +and one FP32 row crosses per token instead of eight: 16,384 B instead of +131,072 B per routed layer at the registered width. + +Every row-parallel product takes an exact FP32 widening of its BF16 input, so +its partial is stored as FP32 and the only rounding is the one after the +cross-rank sum. This is arithmetic contract v2 +(`MiMoTensorParallelPlan.arithmeticAgreementFields`, in the load agreement and +the plan fingerprint); v1 stored each partial as BF16 first, and ranks on +different contracts refuse each other. + +- Expert rows: `SwitchGLU.float32ExpertRows`, through the decode-expert + kernel's FP32-output twin (`MiMoV26DecodeExperts`, `float32Rows`) or MLX's + FP32 gather. +- `o_proj` and the dense `down_proj`: MLX's FP32 qmv and qmm + (`MiMoV26DecoderLayer.attentionOutput`, `MiMoV26DenseMLP.tensorParallelPartial`). + `MiMoV26TensorParallelContext.sum` takes nothing but an FP32 partial. + +FP32 holds every BF16 value exactly, and MLX's FP32 MXFP4 and affine kernels +accumulate in FP32 as the BF16 ones do. On M5 the NAX path runs FP32 inputs at +TF32 (`MLX_ENABLE_TF32=1`, which `MiMoArithmeticEnvironment` requires). Its 10 +mantissa bits keep a BF16-sourced activation and an MXFP4 weight exactly, and an +affine 8-bit weight at least as precisely as the BF16 kernel's BF16 weight tile. +So no rank rounds more than one Mac. A rank never rounds its expert rows: their +combined row is rounded once, after the sum, where one Mac also rounds each +expert's whole projection to BF16 before its combine. Ranks are still not +bit-exact with one Mac, because the halves reassociate the FP32 sums and a near +tie can flip a route. Comparisons against one Mac read `tokensEqualLogitsDiffer` +or `divergedAtNearTie`. `MiMoTensorParallelFloat32PartialTests` checks on the +GPU that two ranks' rows add up bit for bit to the exact full-width row that one +Mac rounds once, and that no `o_proj` or dense partial was rounded to BF16 +before its sum. + +`MiMoV26TensorShard` derives each rank's configuration (half the heads of both +layer kinds and both channel widths, no MTP heads or towers) and cuts stored +tensors, including the 3-D expert banks, by slice or by byte runs. +`MiMoV26TextModel.installTensorParallel(reduce:vocabularyRows:)` adds the two +sums and makes `lm_head` this rank's rows before the weights load. A model +without it runs the unchanged single-Mac path. The CBv2 owner still requires +the whole vocabulary's readout and refuses a rank; the MTP drafter reads a +rank's rows through one cross-rank argmax sum; the independent-history pages +serve a rank one row, or one row-exact verify window, at a time. Selection reuses the model-neutral +vocabulary-split head (`Gemma4TensorParallelSelection`): greedy argmax, top-k log +probabilities and the bit-exact whole-row gather for the product's sampler. + +`MiMoTensorParallelResidentRuntime` is the worker's owner for the mode, with GLM +tensor parallel's executor contract and one lane: + +- Load. The load agreement (the admission's fingerprint, the plan's fingerprint + and arithmetic contract, the serving contract, the mode, the link probe and the + data plane) is bound into the keyed exchange and compared before any read. The + link is measured as the mode uses it (`QwenTensorParallelLinkProbe`). Every + artifact file is hashed against the registered manifest, and then only this + rank's byte runs are read (`MiMoTensorParallelVerifiedLoad`: the plan disposes + of each indexed name; the runs equal the SDK shard's `byteRuns`; any difference + refuses). Both ranks compare what they loaded before either is ready. +- Requests (`MiMoTensorParallelDecoding`). Request-owned 64-token paged + histories at the rank's geometry (full layers: 2 KV heads at widths 192/128; + sliding layers: window 128 and the rank's 32 sink biases). Decode runs under + 100-operation command buffers, with sealed sums only. Each step takes one small + agreement sum per rank of `[value, token, stop, position]`: the + vocabulary-split argmax, or rank 0's draw from the gathered row with the + product's sampler. A stop on either rank ends both after the same step, and + positions that differ end the request. Both ranks read a step's stop flags + before either commits its token, and rank 0 hears each owner answer before + the next step is built, so neither rank commits a token its peer skipped. +- Logprobs. A greedy row that asks for them takes the split top-k gather, + whose first logprob is the greedy token's even when an exactly tied token + leads it; a sampled row publishes the product sampler's own logprobs from + the gathered row. +- Speculative rounds at depth 2, on by default: the installed owner launches + every MiMo tensor-parallel worker with `--mtp-depth 2` (see below). +- Not yet: lanes, prompt-prefix reuse, 2,048-token prefill frames and + micro-batches, building decode steps one ahead. +- Memory. One formula, `MiMoTensorParallelRequestBudget`, gives the LOAD + gate, each reservation's charge and the placement's `requestAllowance` + ([rank memory](hardware-support.md#mimo-v26-tensor-parallel-rank-memory)); + nothing has measured a MiMo tensor-parallel rank. +- Logprobs reach the provider: `ClusterModelFeaturePolicy.capturesLogprobs` + is true for MiMo tensor parallel, so a MiMo tensor-parallel pair admits + `logprobs` requests and a MiMo pipeline pair refuses them. The installed plan + forwards no lane width to a MiMo tensor-parallel rank + (`DistributedInstalledPlan.defaultBatchLanes`), and its arithmetic + environment is the pipeline's (`MiMoArithmeticEnvironment`, nothing added). + +Oracles run on synthetic checkpoints (`kernel`: hidden 1,024, 16 experts top-8, +512 expert channels per rank, so every per-rank decode shape takes the +production MXFP4 expert, router and norm kernels; `tiny`: below those gates). +`simulated` runs both real shards in one process, and two ranks over the sealed +loopback ring or socket equal it bit for bit, caches included, on the +foundation's ordinary caches and on the resident runtime's paged path +(`--path paged`). There each rank reads exactly its shard's bytes, and paged runs +equal ordinary ones bit for bit. A route-set diagnostic (`--record-routes yes`, +through the SDK's observation-only `MiMoV26TextModel.observeRoutes`) reports +where a tensor-parallel run first routes a token to other experts than the +whole model. With random synthetic routers that already happens in the +prompt, well before the first token differs. Real-weight qualification remains +the gate. + +### MiMo tensor-parallel speculative rounds + +A MiMo tensor-parallel worker launched with `--mtp-depth N` (1 to 3; MiMo's +`MiMoMTPTerms`) decodes in `pipeline_mtp_v1`'s rounds through the +tensor-parallel sums. It is on by default: the installed owner passes both ranks +`--mtp-depth 2` (`ClusterMiMoTensorParallel.speculativeDepth`, the depth MiMo's +pipeline measured fastest) wherever the worker's capability record declares +tensor parallel's rounds (`DistributedInstalledGenerationSelection`), which this +build's record does (`MiMoTensorParallelResidentRuntime.servingFeatures`), and +the cluster status reports the head as decoding (`DistributedInstalledSpeculation`). +A worker launched by hand without the depth decodes one token a step. The +planner prices the rounds' memory and credits them no speed-up (placement, +below). + +- **Heads.** Both ranks hold the three trained BF16 heads whole + (3 × 658,546,816 B), named by the pipeline's head inventory + (`MiMoMTPHeadInventory`) and read through the verified checkpoint beside their + shard (`MiMoTensorParallelDraftHead`); both ranks compare the inventory's + digest before either is ready. A round's k-th draft runs the k-th head + (`MiMoV26MTP.forwardTrusted`), so at the installed depth 2 the third head is + held and charged but never runs. The drafter is the product's + (`MiMoV26MTPAssistant`); its target is a one-layer shell that lends it this + rank's embedding and vocabulary rows. A proposal is the whole vocabulary's + argmax from one small sum (`MiMoV26TextModel.readoutArgMax`), so both ranks + propose the same tokens with the single-Mac drafter's arithmetic. Splitting the + heads like the main layers would read about 30% fewer bytes per proposal and + hold 0.83 GiB less, but adds new BF16 partials and two sums per proposal. +- **Windows.** A round runs `[last, d1 … dk]` through every layer's two sums at + once (`MiMoV26TextModel.forwardVerifyWindow`). Each row takes one-row decode's + arithmetic: the row-exact affine 8-bit projections for queries, keys and values + (`MiMoV26RowExactProjection`), per-row RoPE and router, full-attention rows + reading their own prefix and sliding layers taking one ring update and one + attention per row. The row-parallel partials follow contract v2 (FP32 until the + sum, [above](#mimo-v26-tensor-parallel)): `o_proj` is one FP32 product per row + (`MiMoV26RectangularDense.tensorParallelProjection`, the one-token step's M=1 + product; the row-exact kernel is BF16/F16 only), the dense layer's `down_proj` + runs row by row (`MiMoV26RectangularDense.tensorParallelPartial`), and the + routed layer combines each row's FP32 expert rows (`float32ExpertRows`) as its + one-row step does. So each window row is the one-token step's bits, partials + included, and rounds are lossless against the one-token path, not only close + to it. NAX has no kernel for 2 to 4 rows (MLX's NAX attention needs more than 8 + queries), so windows stay on these kernels; prefill is unchanged. +- **Agreement and acceptance.** One sum per round carries, per rank, every + column's maximum and token (or rank 0's keyed target sample over the gathered + rows, `QwenStageTokenSampler.verifyRound`), the stop slot and the position. + `MiMoMTPAcceptance.kept` keeps drafts while each equals the target before it, + then the target, cut at a stop token and the output limit. Column j's target + sample is keyed at output index `next + j`, the key the one-token path uses + there, so sampled rounds draw the one-token path's tokens too (bit for bit + on the synthetic checks). Greedy requests, with or without logprobs, always + draft. A gathered-row request drafts only when its sampler admits verification + (`ClusterWorkerSampling.admitsSpeculativeVerification`). Penalties, a logit + bias, or a sampled request's logprobs make it decode one token a step, as in + the pipeline's rounds. +- **Rollback.** Each cache takes a checkpoint before the window (pages are + immutable arrays). Unless every row is kept, the cache returns to it and + replays the kept rows' keys and values as one-token appends + (`MiMoV26VerifyWindow.settle`), so sliding rings keep their physical order. +- **Stops.** A round's stop slots are read before either rank commits any of its + tokens. A client stop inside a round stops rank 0's commits and rides the next + round's agreement; when that round already ends the request, rank 1 adopts rank + 0's count and finish in the end agreement (`QwenTensorParallelStopRule.reconcile`). +- **Logprobs.** A greedy request takes one vocabulary-split top-k gather per + kept column, led by the column's agreed maximum. The rows are the one-token + step's, so the published logprobs are the one-token path's. A sampled request + with logprobs decodes one token a step, so its logprobs are the step path's. +- **Memory.** Before anything is read, the LOAD gate adds the heads' bytes and, + at the profile's longest request, the drafter's bounded request state and the + window's extra rows (`MiMoTensorParallelResidentRuntime.speculativeRequestBytes`, + from the configuration alone). READY's capacity and each reservation add the + same two per-request terms, and the placement quote prices the same + (`MiMoTensorParallelResidentRuntime.placementRounds`, below). The activation + floor stays the conservative default. +- **Agreement.** The load agreement adds the depth, the verification rule and + the head and window contracts (`speculativeAgreementFields`; the window's is + `windows=row-exact-one-token-float32-partials-v2`); a load without a depth + keeps its agreement unchanged. + +Code map: `MiMoTensorParallelRounds.swift` (rounds, agreement, end +reconciliation), `MiMoTensorParallelSpeculation.swift` (heads, drafter, +scripted oracle proposals), `ClusterMiMoTensorParallel` (the installed depth), +the SDK's `MiMoV26IndependentHistory.swift`, `MiMoV26RectangularDense.swift` and +`MiMoV26TensorParallel.swift`. + +### MiMo tensor-parallel placement + +`MiMoPlacementFamily` states the plan's facts for the text row, so a MiMo +layout carries `tensorParallel`; the image candidate's layout carries none: + +| Fact | Value | Source | +|---|---|---| +| `plan`, `ranks` | `mimo_v26_heads_and_expert_channels_v1`, `[2]`, equal shares | `MiMoTensorParallelPlan.name` | +| `reductionsPerLayer`, `reductionsPerStep` | 2 (attention, feed-forward), 1 (vocabulary-split selection): 97 a decode step | `MiMoTensorParallelPlan.reductionsPerLayer` | +| `partialBytesPerToken` | 16,384 (one FP32 hidden row); no `layerPartialBytesPerToken` | `MiMoTensorParallelPlan.partialBytesPerToken` | +| `stateDividesByHeads` | true: each rank keeps its own KV heads | `MiMoTensorParallelPlan.kvHeadsPerRank` | +| `requestAllowance` | the rank's reserve at the profile's longest request (65,536 tokens), with each request's speculative charge beside it, where the allocator's bound is known | `MiMoTensorParallelRequestBudget`, `allowance(speculativeRequestBytes:allocationBound:)` | +| `speculativeHead` | depth 2; `requestBytes` = one request's speculative charge (the drafter's declaration and the window's rows: 438,426,984 + 36,347,904 B at exact sizes); `decodeSpeedup` 1, credited nothing; the three heads are the layout's `speculativeHead` part (42 tensors, 1,975,640,448 B), held whole on every rank in whole pages | `MiMoTensorParallelResidentRuntime.placementRounds` | +| `choice` | `fastest_v1` | `ClusterTensorParallelChoice` | + +Each stored tensor's cut is the plan's disposition +(`tensorParallelCut(ofStoredTensor:)`). The split pads nothing, so the family +needs no `tensorParallelOverlapBytes`: a rank's share is 84,013,770,176 bytes, +the plan's cut and the verified load's shard bytes. The family states its +routing, 8 of 256 experts (`expertRouting`, `isRoutedExpert`, the same +definition as the pipeline's), so the hardware prior reads 10,767,036,288 +weight bytes per token, 99.1 % of them divided. + +The rounds are priced as the LOAD gate charges them, so the planner admits only +pairs the rank's gate admits: each rank's weights gain the heads in whole pages, +and its quoted reserve gains each request's speculative charge (the product +layout computes it with the SDK's drafter declaration at the allocator's bound; +`placementQuotesWhatTheLoadGateChargesWithRounds` pins it to the LOAD gate's +sum). Metadata-only layouts, such as the recorded golden one, carry neither, as +they carry no `requestAllowance`. Two 128 GB Macs still fit: in the placement +checks the planner asks 99.9 GiB of an idle 128 GB Mac, the rank's LOAD gate +([rank memory](hardware-support.md#mimo-v26-tensor-parallel-rank-memory)) plus +its tensors' page padding. No speed-up is credited until +records measure the rounds: when a pair has served MiMo tensor parallel with and +without them on the same build, a measured table (as GLM's +`GLM5NextServingMetadata.measuredTensorParallelDecode`, depth 0 against depth 2) +sets `decodeSpeedup` to their ratio. Until then served records, which run with +the rounds, correct the shard rates directly (`ClusterServedCalibration`), so the +evidence rule weighs what was served. + +MiMo opts into the fastest-plan rule +([Gemma tensor-parallel placement](#gemma-tensor-parallel-placement)): 97 sealed +sums a step cross the link, and the pipeline it competes with decodes in +speculative rounds (`pipeline_mtp_v1`), as tensor parallel now does, uncredited. +The guided step credits the pipeline's rounds the decode speed-up MiMo's passing +qualification records measured, 1.37x (59.18 against 43.05 tok/s; +`ClusterPairServingGrants.recordedPipelineSpeculativeFactor`), and a fresh pair +plans for the layout's longest request, 32,768 + 32,768 tokens. On the +planner's own figures (`PlacementChecks`, `MiMoTensorParallelChecks.swift`; +constructed Macs: M5 Ultra 57 tok/s, the M5 Max 128 GB from its stage probes at +40 tok/s; tensor parallel priced with its rounds), the comparison and the +evidence rule place MiMo as follows. Tensor parallel keeps every feature of the +speculative pipeline, so the guided step's feature parity holds none of these +rows back: + +| Pair | Link | Request | Chosen | +|---|---|---|---| +| 2x M5 Max 128 GB (neither holds MiMo alone) or 2x M5 Ultra 256 GB | default (unmeasured) | every request, 128 + 128 and 32,768 + 32,768 included | speculative pipeline (tensor parallel 43.6 against 55.0 tok/s on 2x M5 Max, 52.1 against 78.3 on 2x M5 Ultra) | +| either pair | measured 29 us sums, nothing served in tensor parallel | decode-heavy, 32,768 + 32,768 included | speculative pipeline: tensor parallel predicted faster on the prior alone (32,768 + 32,768: 553 s against 646 s on 2x M5 Max, 405 s against 444 s on 2x M5 Ultra) | +| 2x M5 Ultra / 2x M5 Max | measured 29 us sums, served in tensor parallel at 70 or 95 / 45 or 70 tok/s | 128 + 128 | speculative pipeline / tensor parallel | +| either pair | measured 29 us sums | 8,192 + 128 | speculative pipeline (the prompt's FP32 sums) | +| either pair | measured 109 us sums | 32,768 + 32,768 | speculative pipeline | + +Against the plain pipeline (a capability without `pipeline_mtp_v1`, or no +passing record of the rounds), tensor parallel would drop the plain pipeline's +eight batch lanes (it serves one), so feature parity keeps the pipeline there, +whatever the evidence. On speed alone, two M5 Max are predicted faster in +tensor parallel even on default link costs for decode-heavy requests (128 + +128: 3.17 s against 3.50 s), on the prior alone, so they keep the pipeline too, +as they do inside the 5 % margin (1,024 + 128) or for long prompts; two M5 +Ultra keep the pipeline on default link costs, where 97 sums cost about 10.3 ms +a step, more than the weight streaming a half saves. + +Every tensor-parallel prediction here without served records rests on the +hardware prior: the M5 Ultra's device index puts the whole 17.5 ms step in +weights, so a rank is predicted to save half of it, although it still pays the +step's dispatch floor [INFERENCE]. The evidence rule therefore keeps the +pipeline ([Gemma tensor-parallel placement](#gemma-tensor-parallel-placement)). +MiMo's runtime takes no share probe, so only requests a pair served in tensor +parallel with the same worker build give it evidence +(`ClusterServedCalibration`). Only the developer's forced mode, in a debug +build, serves MiMo tensor parallel before that; a release build cannot force it, +so release builds keep MiMo on the pipeline until MiMo gets a share probe. The +recorded golden layout +gains the facts and routed experts beside its recorded bytes; its golden plans +keep their placements (pipeline, cut 41 and cut 24), and their tensor-parallel +verdict reads `notExecutedByRuntime` because the recorded mode list predates +`tensor_parallel_v1`. + +Code map: + +- `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/` +- `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift` +- `libs/mlx-swift-lm/Libraries/MLXLLM/Models/MiMo/MiMoV26TensorParallel.swift` +- `libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/MiMoCheck.swift` +- `libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift` (routes MiMo `tensor_parallel_v1` loads) + +See [focused MiMo V2.6 tensor-parallel checks](../developer/test.md#focused-mimo-v26-tensor-parallel-checks). + ## Exact-quote placement `ClusterPlacementPlanner.rankQuoted` is the model-independent decision seam for adapters that provide exact simultaneous native/host peaks and current bounds. It filters infeasible shapes and unsupported modes, then uses the same hardware-only ordering as `plan`: candidates whose every range fits its Mac's hardware (`ClusterDeviceProfile.hardwareFits`: buffer and allocator limits, need within the GPU working set and the at-rest admissible memory `atRestAdmissibleBytes`), then predicted request time, ties and the tensor-parallel margin. Live free memory and file cache never order candidates; each rank's live fit is reported and the load gate still decides each load. A supported TP adapter must supply TP layout facts and keyed reduction measurements. Neither resource balance nor chip-name rules replace request-time scoring; balance only breaks ties. Candidates whose predicted times differ only by rounding (relative 1e-9, as every serial pipeline cut does on identical Macs) are ordered by `capacityBalance`, the smallest share of a rank's hardware capacity (`min(residentCapacityBytes, atRestAdmissibleBytes)`) left beyond its need, before the lower cut, so identical Macs split evenly and live free memory cannot pick the cut. Every structural boundary, including one layer on a slower member, remains available when its adapter quotes fit. GLM's placement family (`GLM5NextPlacementFamily`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Metadata/GLM5NextServingMetadata.swift`) offers the two-rank plan `glm5_next_heads_and_expert_channels_v1` whenever the registered row lists `tensor_parallel_v1` and the geometry halves. Each text-layer tensor is divided or replicated exactly as the SDK's `GLM5NextTensorShard.splitAxis` loads it; the embedding, final norm and head are replicated, and the NextN layer and vision tower belong to no text range. Every rank decodes in speculative rounds with the NextN layer, which it holds whole beside its share, so the plan states it (`ClusterTensorParallelFamilyPlan.speculativeHead`, `GLM5NextPlacementFamily.tensorParallelSpeculativeHead`): the planner charges each tensor-parallel rank the layout's `speculativeHead` part (4,183,320,576 stored bytes, each tensor in whole pages, as `mtp_bytes` on the worker's load line) and the request memory the rounds add at the memory plan's context (the larger of the contiguous and the paged NextN charge of `GLM5NextTensorParallelRequestCharge`), and divides a token's predicted decode step by the speed-up the pair measured at the runtime's depth over one token per step (76.0 against 62.6 tok/s at depth 2, `GLM5NextPlacementFamily.measuredTensorParallelDecode`). Served tensor-parallel requests are taken back to one-token steps by the same speed-up before they correct the shares (`ClusterServedCalibration`), so the next plan predicts what was served. Without it the plan priced no NextN bytes and one token per step: it could admit a pair the load gate then refused, and it predicted decode too slow. Three terms of the load gate are not in the plan yet: the vision tower rank 0 holds for media (1.13 GB), the freed-buffer cache (`GLM5NextTensorParallelResidentRuntime.freedBufferCacheBytes`) and the bulk prefill's further workspaces and sealed sums' buffers (`bulkPrefillChunkTokens`). On two M5 Ultra 256 GB, adding them to the planner's estimate as it stands would put each rank's need above the at-rest ceiling (`ClusterDeviceProfile.atRestAdmissibleBytes`), so the pair would no longer plan tensor parallel; they wait for the gate's own charge to replace the estimate rather than be added to it. The plan sums two partials of the 4096-wide residual per layer and one per step (91 per decode step); the partials are the row-parallel projections' bfloat16 outputs, sent as they are and added in float32 with one rounding (`GLM5NextTensorParallelResidentRuntime.partialsTransport`, bound into the load agreement). That is bit-identical to widening them to float32 before the link, as `ClusterTensorParallelTerms.current` (`partialsDType` float32) describes, with half the bytes: GLM's projections never kept float32 partials (flagged for platform review) and holds request state whole on each rank, since the DSA latent cache is replicated. The pipeline's private image profile stays pipeline-only, in both the layout and the capability; tensor parallel serves media under the text profile (below). The hardware prior (`ClusterHardwarePrior.decodeBytesPerToken`) counts a mixture of experts' routed experts at the fraction a token is routed to (`ClusterRoutedExperts`; 8 of GLM's 288), not every expert byte. Of the bytes a step reads, a tensor-parallel share divides only the plan's divided bytes (`dividedDecodeFraction`), because every rank reads its replicated bytes whole. On two identical M5 Ultra 256 GB with GLM measured alone the product's rule (tensor parallel first wherever it fits) places tensor parallel on equal shares with the NextN layer priced, both on a new pair before any load measured the link and after the first load's keyed probe; the planner's own speed comparison (the plan tool without `--tensor-parallel-first`) chooses tensor parallel once the keyed link is measured and a pipeline before (`GLMTensorParallelChecks`; through `ClusterPlacementFlow.decide` in `PlacementSetupCheck.glmTensorParallelPair`). The pair serves it with eight lanes (`DistributedInstalledPlan.tensorParallelBatchLanes`). -A chosen GLM tensor-parallel placement is served by `GLM5NextTensorParallelResidentRuntime` (`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/`). Each rank verifies the whole artifact, loads every layer's share through `GLM5NextTensorShard`, and sums each layer's attention and feed-forward partials (bfloat16, added in float32) over the sealed all-sum (AES-256-GCM on the keyed JACCL data plane; a peer piece that does not open fails the request). On the JACCL mesh the sum is streamed in one CPU-stream task: each 256 KiB sealed piece carries its own tag, crosses as soon as it is sealed and is opened and added as soon as it lands, so only the first and last pieces wait for crypto (`SealedAllSum`, `sealed_stream.h`); other groups seal and gather the whole frame. Prefill runs 4,096-token chunks on both ranks (`prefillChunkTokens`: the M5 neural accelerators reach ~94 TFLOPS on 4,096-row NVFP4 matmuls against ~62 at 2,048; charged as a second request workspace), each chunk as two micro-batches whose sums are issued as soon as their partials exist, so one computes while the other's sum crosses the link (`GLM5NextTextStage.tensorParallelMicroBatches`; 2,532 against 1,767 tok/s whole); sampled decode runs one token per step, and the ranks' tokens must agree at every step. A tensor-parallel worker lifts MLX's per-command-buffer input-size bound before anything native starts (`WorkerCommandBufferBudget`, `MLX_MAX_MB_PER_BUFFER`; a launcher value is kept): every MoE launch takes a whole expert bank as input, so decode committed ~88 buffers a step instead of ~22 (measured 19.0 -> 16.8 ms a step; the 50-operation bound stays). Decode steps, MTP rounds and lane rounds encode with at most 100 operations a buffer on the thread that encodes them (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`), above the owner's 16-operation rank guard, which prefill keeps: each further buffer is a GPU gap of about 10 µs (13.24 -> 12.56 ms a step, tokens identical). An MTP round submits its NextN priming and proposals as soon as they are built, so the GPU runs them while the host builds the verification forward (`GLM5NextTensorParallelSpeculation.EarlySubmission.proposals`; before, the whole round's graph, about 1.8 ms of host work, was built with the GPU idle): a depth-2 round 23.06 -> 21.64 ms (95.9 -> 102.7 tok/s), two lanes 115.2 -> 121.6 tok/s, tokens and top logits identical. A greedy round reads out half the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum: each rank's slot carries its half's maximum and argmax, and the larger maximum wins, rank 0's lower index on a tie, which is the whole head's argmax (`GLM5NextTensorParallelSpeculation.splitsVocabulary`, `GLM5NextTextStageReadout.allTokensVocabularyPart`): 21.32 -> 21.05 ms a depth-2 round, tokens identical; sampled rounds keep the whole head. A GLM tensor-parallel worker lets the hyper-connection site that reads a sum wait for it itself (`WorkerFenceFusion`: `MLX_METAL_FENCED_INPUTS`; a launcher value is kept), one dependent dispatch fewer on each of a step's 90 sums. The core's fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: above 32 KB a partial's update is split over several threadgroups and that path never signals the CPU, so two batched lanes (six verification rows) stalled every round about 0.7 s. The load gate charges the shard, the NextN layer, both pipeline ranks' request budgets plus speculative decode's request state, and a 4 GiB freed-buffer cache (the load runs with MLX's cache at zero; serving with it at zero halves prefill and decode). READY names the installed partition's plan hash, as a pipeline rank does. Prompt prefixes are reused as under Qwen tensor parallel: each rank keeps its own stage cache (its heads' KDA state and the replicated DSA latents) at a prompt's last whole chunk boundary in memory (`GLM5NextTensorParallelPrefixCache`, at most 8 GiB), and a request restores the longest boundary both ranks hold after one sealed vote, or neither does; entries give way first under memory pressure and every failure drops them. Each request's entries are its own partition's (`GLM5NextTensorParallelResidentRuntime.prefixScope`, see [tenant partitions](prefix-cache.md#cluster-prefix-tenant-partitions)): a tenant's boundaries are voted, restored and kept for that tenant alone, and a request whose cache is off votes and keeps none, on a cache-on request's frames. Each rank also keeps a cleanly retired request's boundary in the encrypted SSD tier, read from the memory entry's pages behind serving; the vote counts those records, and a boundary taken from one is restored into the request's own pages only after a second sealed exchange confirms both ranks have it, in the same partition (`prefixDiskScope`), so a restarted pair restores what the last one kept ([GLM TP prefix SSD tier](prefix-cache.md#glm-tp-prefix-ssd-tier)). The link probe that prices the reduction (`QwenTensorParallelLinkProbe`, recorded by both pipeline and tensor-parallel loads) times the sealed all-sum after one unmeasured pass with the same bounded cache, so the planner prices what a ready rank pays (a cold probe read 16.9 ms per 32 MiB against 5.8 ms ready). +A chosen GLM tensor-parallel placement is served by `GLM5NextTensorParallelResidentRuntime` (`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/`). Each rank verifies the whole artifact, loads every layer's share through `GLM5NextTensorShard`, and sums each layer's attention and feed-forward partials (bfloat16, added in float32) over the sealed all-sum (AES-256-GCM on the keyed JACCL data plane; a peer piece that does not open fails the request). On the JACCL mesh the sum is streamed in one CPU-stream task: each 256 KiB sealed piece carries its own tag, crosses as soon as it is sealed and is opened and added as soon as it lands, so only the first and last pieces wait for crypto (`SealedAllSum`, `sealed_stream.h`); other groups seal and gather the whole frame. Prefill runs 4,096-token chunks on both ranks (`prefillChunkTokens`: the M5 neural accelerators reach ~94 TFLOPS on 4,096-row NVFP4 matmuls against ~62 at 2,048; charged as a second request workspace), each chunk as two micro-batches whose sums are issued as soon as their partials exist, so one computes while the other's sum crosses the link (`GLM5NextTextStage.tensorParallelMicroBatches`; 2,532 against 1,767 tok/s whole); greedy and sampled requests then decode in MTP rounds (below). A tensor-parallel worker lifts MLX's per-command-buffer input-size bound before anything native starts (`WorkerCommandBufferBudget`, `MLX_MAX_MB_PER_BUFFER`; a launcher value is kept): every MoE launch takes a whole expert bank as input, so decode committed ~88 buffers a step instead of ~22 (measured 19.0 -> 16.8 ms a step; the 50-operation bound stays). Decode steps, MTP rounds and lane rounds encode with at most 100 operations a buffer on the thread that encodes them (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`), above the owner's 16-operation rank guard, which prefill keeps: each further buffer is a GPU gap of about 10 µs (13.24 -> 12.56 ms a step, tokens identical). An MTP round submits its NextN priming and proposals as soon as they are built, so the GPU runs them while the host builds the verification forward (`GLM5NextTensorParallelSpeculation.EarlySubmission.proposals`; before, the whole round's graph, about 1.8 ms of host work, was built with the GPU idle): a depth-2 round 23.06 -> 21.64 ms (95.9 -> 102.7 tok/s), two lanes 115.2 -> 121.6 tok/s, tokens and top logits identical. A greedy round reads out half the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum: each rank's slot carries its half's maximum and argmax, and the larger maximum wins, rank 0's lower index on a tie, which is the whole head's argmax (`GLM5NextTensorParallelSpeculation.splitsVocabulary`, `GLM5NextTextStageReadout.allTokensVocabularyPart`): 21.32 -> 21.05 ms a depth-2 round, tokens identical; sampled rounds keep the whole head. A GLM tensor-parallel worker lets the hyper-connection site that reads a sum wait for it itself (`WorkerFenceFusion`: `MLX_METAL_FENCED_INPUTS`; a launcher value is kept), one dependent dispatch fewer on each of a step's 90 sums. The core's fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: above 32 KB a partial's update is split over several threadgroups and that path never signals the CPU, so two batched lanes (six verification rows) stalled every round about 0.7 s. The load gate charges the shard, the NextN layer, both pipeline ranks' request budgets plus speculative decode's request state, and a 4 GiB freed-buffer cache (the load runs with MLX's cache at zero; serving with it at zero halves prefill and decode). READY names the installed partition's plan hash, as a pipeline rank does. Prompt prefixes are reused as under Qwen tensor parallel: each rank keeps its own stage cache (its heads' KDA state and the replicated DSA latents) at a prompt's last whole chunk boundary in memory (`GLM5NextTensorParallelPrefixCache`, at most 8 GiB), and a request restores the longest boundary both ranks hold after one sealed vote, or neither does; entries give way first under memory pressure and every failure drops them. Each request's entries are its own partition's (`GLM5NextTensorParallelResidentRuntime.prefixScope`, see [tenant partitions](prefix-cache.md#cluster-prefix-tenant-partitions)): a tenant's boundaries are voted, restored and kept for that tenant alone, and a request whose cache is off votes and keeps none, on a cache-on request's frames. Each rank also keeps a cleanly retired request's boundary in the encrypted SSD tier, read from the memory entry's pages behind serving; the vote counts those records, and a boundary taken from one is restored into the request's own pages only after a second sealed exchange confirms both ranks have it, in the same partition (`prefixDiskScope`), so a restarted pair restores what the last one kept ([GLM TP prefix SSD tier](prefix-cache.md#glm-tp-prefix-ssd-tier)). The link probe that prices the reduction (`QwenTensorParallelLinkProbe`, recorded by both pipeline and tensor-parallel loads) times the sealed all-sum after one unmeasured pass with the same bounded cache, so the planner prices what a ready rank pays (a cold probe read 16.9 ms per 32 MiB against 5.8 ms ready). Greedy requests under GLM tensor parallel decode speculatively with the model's own NextN (MTP) layer (`GLM5NextTensorParallelResidentRuntime.mtpDepth`, depth 2; `GLM5NextTensorParallelSpeculation`). Every rank loads the layer whole beside its shard (about 4.2 GB; it shares the replicated embedding and head and needs no sums), so both ranks propose the same tokens from the same inputs. A round proposes up to `mtpDepth` tokens (step 0, then index-shared continuations for depth 2 and 3), verifies the last committed token and the proposals in one stage forward (`GLM5NextTextStage.prepareVerification`: a `[1, 1 + depth]` window through the same 91 sums), and keeps the longest prefix of proposals equal to the target's greedy tokens, plus the target's next token. Each KDA layer adopts the state it captured after the last kept token and each DSA history drops the rest (`GLM5NextTextStageCandidate.commit(afterEvaluating:keeping:)`), so a rejected proposal costs no replay forward. The round's one sealed reduction carries each rank's target tokens, proposals and stop flag: tokens or proposals that differ end the request, and a stop flag on either rank ends both after the same round. Rounds are not pipelined; each reads its agreement before the next is built, but a round's tokens are committed while the next round runs (`GLM5NextTensorParallelSpeculation.round`, `whileRunning`), unless they end the request. The NextN history is primed from the prompt's hidden rows (history only: no attention, MoE or readout) and afterwards only from verified pairs, and prompt-prefix entries keep it at their boundary. Tokens leave one at a time through the same stop and length rules. The output is the target's greedy tokens, computed in windows of up to `1 + depth` rows instead of one-row steps. MLX runs a one-row quantized projection (and the head) as `qmv` and a multi-row one as `qmv_wide`, which reduces K in a different order, so every window rounds differently from a one-token step and the KDA and DSA histories carry that forward: a long speculative decode drifts from one-token greedy decode and can choose a different token after tens to hundreds of tokens, not only at near-ties (measured on the 3,931-token prompt: first difference at output 104 for depths 1 and 2, and at 89 for depth 3; `qmv_wide` rounds a row the same in two- and three-row windows). The ranks never differ, and a one-token window is bitwise an ordinary step (`darkbloom-cluster-tp-check glm --mtp-check one-token`; `keep-first` decodes one token per round through full windows to separate this arithmetic from acceptance and rollback). On the pair (sealed, 256 tokens) decode measured 62.6 tok/s one token per step, 68.7 at depth 1, 76.0 at depth 2 (2.24 tokens a round) and 71.8 at depth 3. Sampled requests decode in rounds too: each proposal is drawn with the request's own sampler and the keyed noise of the output index it is for (coupled drafting, `GLM5NextTensorParallelResidentRuntime.coupledDraftSharpness`), and every committed token is the target's draw from its window logits; the sampler moves only acceptance. The load agreement binds the depth (`glm5-next-tp-mtp-v1`). The planner prices the rounds and the NextN layer as described above (`ClusterTensorParallelSpeculativeHead`). @@ -4045,7 +4909,7 @@ The proposals a round verifies can follow the pair's load (`GLM5NextTensorParall GLM image and video input under tensor parallel (`ClusterGLMMedia`, contract `glm53_tp_media_v1`) is the single-Mac product's media path split across the leader and rank 0. The leader runs the product's code up to the vision tower (`DistributedGLMMediaIngress`): `EngineV2VisionPrefill.glm5NextUserInput` (the bounded `MediaIngest` decode and every product cap) and `GLM5NextProcessor.prepareDetailed` with the artifact's processor budgets and the thinking-off tokenizer, on the CPU device, so the expanded prompt, its spans and its patches are the product's; it checks them as `buildGLM5NextSubmission` does and describes each part: its encoded bytes' digest, grid, per-pair token offsets, the product's tower limits for one frame (`VisionTowerBudget.glm5FrameLimits`) and a SHA-256 of its prepared patches. Rank 0's reservation carries the encoded bytes as well (at most 32 MiB, the one worker command above the 8 MiB command bound: `ClusterWorkerLimits.mediaCommandBytes`); rank 1's carries the digests only, and both bind the envelope's fingerprint into the request digest. Rank 0 holds the vision tower (1.13 GB of bfloat16 weights, charged at load). From the reservation on, off the executor and without MLX, rank 0 rebuilds the ingest's media values, prepares them with the SDK's `GLM5NextProcessor.prepareMediaValues` (the media half of `prepareDetailed`, as host values) and requires every grid and patch digest to equal the leader's; the reservation itself returns at once. When the request opens, after the digest agreement, both ranks exchange small sealed sums carrying that preparation's status and each rank's stop until it ended (a stop ends the request on both ranks before anything is made; a failed or different preparation is an agreement failure on both). Rank 0 then runs the tower once per temporal pair with the leader's limits on the default GPU stream, as the product does, and one sealed all-sum per frame carries the features to rank 1, which adds negative zero (the additive identity for every value, signed zeros included, rounded once); rank 0 checks each result bit for bit and a last small sum carries its verdict, so both ranks end together on a difference. Every one of these sums is evaluated alone. With batch lanes a media lane runs the same open, frames and rounds: rank 0 joins it only once its preparation ended (`GLM5NextTensorParallelLaneReservation.joinable`), so the running lanes never wait for a decode, and its media charge is held with its lane state. A prefill frame that holds media positions replaces their embedding rows with the features by concatenation (the product's `spliceEmbeddings`) and runs from those embeddings through the same chunks and micro-batches (`GLM5NextTextStage.prepareForward(embeddings:cache:segments:readout:snapshotAfter:)`), so a frame merging several chunks stays bitwise for media rows as for text; every other row and frame is the text path's, on tensor parallel's own chunk grid. Unlike the single-Mac product, which decodes media requests target-only, a media request here decodes speculatively as text does: the NextN history is primed with the same input rows, so a media position's next input is its feature row (`GLM5NextMTP.primeHistory(shiftedEmbeddings:)`, as a multimodal target's drafter is fed). It neither restores nor stores prompt prefixes. Workers advertise the contract at READY (`ClusterWorkerReady.media`) with a request capacity that covers one media request (`GLM5NextTensorParallelMedia.capacityBytes`); a text request is still charged only its own context. The leader binds media only when both ranks advertise it, and the pipeline's private image profile is unchanged. -Rank 0 hands each committed token to its owner and reads the owner's answer late (`ClusterCommittedTokenChannel`, `WorkerRuntime.start(_:tokens:)`): it publishes the token at once, and reads the answer after the next step or round was submitted, before it publishes the next token. The protocol's token credit is unchanged (`ClusterWorkerSession` still refuses a token before the answer to the one before, and anything after a stop), but the answer's round trip through the owner (pipes, the provider's token callback and detokenizer; about 0.7 ms a token measured at the endpoint; greedy decode went from 73.5 to 76.8 tok/s through the API, matching the bench) now overlaps the next step's encoding and GPU time instead of sitting between steps. A stop answer takes effect one step or round later; that work is computed and never published, and its flag reaches the peer in the next submitted sum as before. Other runtimes publish and wait as before (the protocol's default implementation). +Rank 0 hands each committed token to its owner and reads the owner's answer late (`ClusterCommittedTokenChannel`, `WorkerRuntime.start(_:tokens:)`): it publishes the token at once, and reads the answer after the next step or round was submitted, before it publishes the next token. The protocol's token credit is unchanged (`ClusterWorkerSession` still refuses a token before the answer to the one before, and anything after a stop), but the answer's round trip through the owner (pipes, the provider's token callback and detokenizer; about 0.7 ms a token measured at the endpoint; greedy decode went from 73.5 to 76.8 tok/s through the API, matching the bench) now overlaps the next step's encoding and GPU time instead of sitting between steps. A stop answer takes effect one step or round later; that work is computed and never published, and its flag reaches the peer in the next submitted sum as before. A rank that stopped commits nothing more, but still ends at a stop token its peer commits, so both ranks leave after the same round or step: in MTP rounds, and in the one-token steps a build without the NextN layer runs (`GLM5NextTensorParallelStepLoop`, `ClusterGLMTensorParallel.speculativeDepth` 0). Rank 0's count and finish then cross in one small agreement, and rank 1 adopts them unless it stopped on its own (`QwenTensorParallelStopRule.reconcile`). Other runtimes publish and wait as before (the protocol's default implementation). GLM's decode and prefill kernels changed only in ways that keep every output bit for bit (they serve one Mac and the cluster alike). Decode: each hyper-connection site is one launch whose last threadgroup finishes the Sinkhorn and collapse (`GLM5NextHyperConnectionNormFusion`, `SplitForm.oneLaunch`); the MoE decode router spreads each expert row over 8 SIMD groups and replays top-K with `simd_max`/`simd_min` in the same order (`GLM5NextMoEDecodeKernel`); DSA decode uses smaller, more numerous threadgroups, a 1,024-thread top-k and a two-launch cache append that writes fresh buffers (`GLM5NextSparseDecodeKernel`, `GLM5NextTextCache`); per-call constants are cached and dead KDA nodes are no longer built. Prefill: the MoE gathers decode a packed NVFP4 word at a time (`GLM5NextMoEPrefillKernel`) and DSA's absorbed queries run beside the first index-score block. A prefill hyper-connection site that folds the previous expand (89 of a forward's 90) computes each expanded value inside the mix fragment that multiplies it and stores it there, so the expand's memory traffic overlaps the matrix products and no barrier precedes the mix, and its rows' collapses share one barrier (`GLM5NextHyperConnectionKernel.fusedExpandPrefillSource`; `GLM53_HC_FUSED_EXPAND=0` keeps the two-pass site): every per-element expression and sum order is the two-pass kernel's, 0.61 -> 0.56 ms a site at 4,096 rows on one M5 Ultra rank, about 5 ms per 4,096 prompt tokens per rank. Host: MLX shares generated kernel sources, resolves pipelines once and binds repeat launches without rebuilding names or keys. Core's fused fence update and fenced custom-kernel inputs (`MLX_METAL_FUSED_FENCE_UPDATE`, `MLX_METAL_FENCED_INPUTS`) are off by default; a GLM tensor-parallel rank turns the fenced inputs on (`WorkerFenceFusion`) and leaves the fused fence update to its launcher. Measured on two M5 Ultra (sealed TP2, MTP depth 2): plain decode 14.45 -> 12.43 ms a step, an MTP round 27.8 -> 23.9 ms, 15.7K-token prefill 3,819 -> 3,917 tok/s, tokens and top logits identical. Changes that only reorder sums were measured with a teacher-forced full-model perplexity bench and rejected (KDA paired order, DSA absorbed product on the tensor units, the tensor-unit prefill router, INT8 activations: +0.4 to +5.6 % perplexity, about 79 % top-1 agreement against a 99.4 % noise floor of the product's own chunking). @@ -4059,6 +4923,84 @@ The GLM finite-calibration adapter samples each Mac locally and reuses `GLM5Next The installed run command recomputes the decision from both snapshots, binds it to the unchanged local template, and then invokes the existing signed quotation/owner path with the chosen cut. Local and peer quotes must still agree, and current-device/load/reserve/start checks retain authority. Public endpoint activation, automated calibration scheduling and a MiMo adapter for this exact-quote seam are separate integrations. +## Pipeline decode command buffers + +The pipeline stages of the Qwen catalog (dense, routed-expert and Prism rows), +Nemotron, Gemma 4, GPT-OSS and GLM encode decode work as GLM's and Qwen's +tensor-parallel decode do: up to 100 operations a Metal command buffer with no +input-size bound (`QwenLayerStageSession.decodeCommandBuffers`), on the thread +that encodes it. The rank's own limits are the worker's 16-operation guard +(`ClusterWorkerEnvironmentGuards`) and MLX's per-chip size bound, which counts +the distinct input elements of a buffer: a routed-expert launch takes a whole +expert bank as input, and banks above the bound (the 35B A3B rows, Nemotron, +Gemma 4 and GLM) commit a buffer at every launch. Prefill frames keep the +rank's limits. MiMo's pipeline is not covered here. + +| Work | Where the limits apply | +|---|---| +| Plain and compact decode frames, phase-split and alone-route decode (Qwen catalog, Nemotron, Gemma 4) | `QwenLayerStageSession.decode` | +| Lane steps | `QwenLayerStageSession.decodeBatch` | +| `pipeline_mtp_v1` rounds: drafts, verify windows on both ranks, settlement | `QwenPipelineMTPGeneration.runProducer`, `QwenPipelineMTPGeneration.runConsumer` | +| `phase_split_mtp_v1` rounds on the decoding rank | `QwenMTPDecoder.step` | +| GPT-OSS decode frames and lane steps | `GPTOSSLayerStageSession.decode`, `GPTOSSLayerStageSession.decodeBatch` | +| GLM decode frames | `GLM5NextStageSession.forward`, decode phase only | + +Only the commit points move: every kernel, input and rounded value is the same, +so load agreements and arithmetic contracts are unchanged. +`PipelineDecodeCommandBufferTests` compares every output row, verify window and +cache or state array byte for byte under each family's guard and under the +decode limits, on synthetic stages. + +MLX keeps up to ten command buffers in flight (`MLX_MAX_ACTIVE_TASKS`) and frees +a buffer's temporaries when it completes, so under the decode limits a whole +stage step's temporaries can be alive at once. Each request charge therefore +prices every attending layer's decode rows together, and never less than one +prompt frame's: + +| Family | Charge | Decode rows priced together | +|---|---|---| +| Qwen catalog, Nemotron | `QwenResidentPrefillTransient.bytes` (`decodeRows`), from `QwenResidentRequestAllowance.derive` | One a layer, or the verify window's `depth + 1` (`LayerStageDecodeShape`), on the rank's stage; on every layer on a phase split's decoding rank; none on its other rank, which hands its prompt state over | +| Gemma 4 | `Gemma4PrefillTransient.bytes` (`decodeRows`, `decodeLayers`) | One on each layer of the stage, sliding layers over their window | +| GPT-OSS | `GPTOSSRequestStateBudget` workspace | One a full-attention layer | +| GLM | Unchanged (`GLM5NextRequestStateBudget.estimate`): every DSA layer of the stage is charged three float32 copies of twice the context the request is charged for, and every request the conservative 5.5 GiB workspace | None added: a step's pages and reads on every layer at once stay well inside that charge (below) | + +The LOAD quotes are unchanged: they are computed at the largest prompt chunk, +512 rows, and a decode step prices at most 80 rows (5 on each of 16 attending +layers; one on each of Gemma's 30). Only requests whose prompt frames are +shorter than their decode rows are charged more, and only on a rank that +decodes. The rows are priced as float32 score rows over the whole context. +The Qwen, Nemotron and Gemma 4 stages keep their keys and values in the paged +stage KV (`CBv2StageKVHost`). There, decode steps, lane steps and verify +windows (one decode row a window column, `CBv2OwnedRequestState.buildingWindow`) +attend through the paged decode kernel (`PagedAttentionKernel.decode` in +`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAttentionKernel.swift`). +Its float32 partials take `heads × ceil(keys / 256) × (head width + 2) × 4` +bytes a row: about one score row at head width 256, two on Gemma's full layers +(width 512) and half on Nemotron's (width 128, whose charge prices only the +output). GPT-OSS attends through MLX's attention, whose vector kernel on Max +and Ultra GPUs at 1,024 keys or more keeps float32 partials that exceed a score +row by at most about 4 MiB a layer (`sdpa_vector_2pass` in +`libs/mlx-swift/Source/Cmlx/mlx/mlx/backend/metal/scaled_dot_product_attention.cpp`). +The excess over the priced rows is not charged; [INFERENCE] it is at most tens +of MiB a request, times the lanes. + +GLM needs no decode term. Each DSA layer of a GLM stage is already charged +three float32 copies of twice its context +(`GLM5NextRequestStateBudget.HistoryBound.geometric`: 18,438 bytes a token at +the registered widths). A decode step keeps that layer's history in bfloat16 +pages (1,537 bytes a token) and reads at most one gathered copy of it, only the +index planes (513 bytes a token) once the history passes 4,102 tokens, so every +layer's reads alive at once stay well inside the term at any context. The rest +of a step, mostly each linear-attention layer's next 4.4 MB state, is inside the +conservative 5.5 GiB workspace every request is charged +(`GLM5NextServingResources.workspaceNativeBytes`). On a synthetic stage at the +registered widths (three DSA and three linear-attention layers, bfloat16 +pages), a decode step held 16 MB above its baseline at a 20-token context and +136 MB at 65,520 tokens of history, the same under these limits as with the +whole step in one buffer (131 MB under the rank's guard), against 6.0 and +11.1 GB charged at those contexts. The decode speed effect and peak memory on +registered models are not measured yet. + ## GLM cluster prefill bounds The registered NVFP4 GLM cluster candidate admits a maximum prefill chunk of @@ -4431,18 +5373,32 @@ synchronizes before dropping request caches on completion or failure. Copies share immutable old pages; a later write replaces the affected page handle. Sliding histories release old pages when they repack or enter the fixed ring. +Sliding pages also keep the ring's wrapped flag: a one-token write that rotates +sets it, and a chunk or trim clears it. Their `metaState` is the seven values the +pinned SDK writes for `RotatingKVCache(maxSize: window)` in the same state: keep, +window, step, offset, write index, capacity origin and wrapped flag +(`GPTOSSSlidingRing`). Restoring accepts only that layout for the cache's window, +and only with the rows that ring holds: its first `index` rows, or the whole +window once wrapped. It refuses the five-value legacy layout, a rewind reserve, a +kept prefix, and any other step, window or capacity origin. It also refuses an +unwrapped ring that has evicted rows but holds fewer than `window - 1`, which the +SDK's `trim` after eviction can leave: pages cap masks and trims by the offset, +the SDK by the rows it holds. GPT-OSS serving never reads or restores this +metadata. + `GPTOSSRequestStateBudget` keeps the existing full-request admission scope and never lowers its previous contiguous allowance. It also charges each page's allocator bound separately, the gathered attention view, and partial-page copies; sliding repacking includes old and new page versions. Physical allocation is demand-grown even though the request is admitted conservatively for its whole declared scope. LOAD and live-memory gates remain authoritative. -CPU parity against the actual SDK caches covers ring/page/chunk boundaries and -sinks. Real two-Mac numerical acceptance, resource release and performance -remain separate qualification gates. +CPU parity against the actual SDK caches covers ring/page/chunk boundaries, +metadata, restores and sinks. Real two-Mac numerical acceptance, resource release +and performance remain separate qualification gates. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift` -(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, +(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift` +(`GPTOSSSlidingRing`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift`, and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Resident/GPTOSSResidentAdmission.swift` (`loadAgreementFingerprint`). See [focused cache checks](../developer/test.md#gpt-oss-cluster-paged-kv-checks). @@ -4475,7 +5431,9 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Meta one-token requests. Ordinary affine 4/8-bit group-64 projections retain native matmul `M=1` through leading weight views; custom and floating modules retain their original per-request forward method. The unscaled value RMS reduction -and each routed expert operation retain singleton request shapes as well. +retains singleton request shapes. The rows' routed experts share one call +that keeps each row's singleton bytes +([Gemma prompt projection reductions](#gemma-prompt-projection-reductions)). The scope owns no cache, changes no shared MLX dispatcher, and is disabled for singletons, prefill and speculative rectangles. @@ -4496,6 +5454,40 @@ and leaving/rejoining rows. Their CPU checks require identical native logits and all live KV values. This is not full-artifact GPU, pair or throughput qualification; those checks remain required. +### Gemma pipeline lanes + +A Gemma 4 pipeline whose saved setup prefills serially serves +`DistributedInstalledPlan.gemma4PipelineBatchLanes` (4) requests at once, +coordinator-registered pairs included. Every other pipeline lane adapter keeps +the default of one (`DistributedInstalledPlan.defaultBatchLanes`). A saved +width or the owner's `DARKBLOOM_CLUSTER_BATCH_LANES` still overrides the +default. + +| Property | Basis | +|---|---| +| A lane costs no request its own tokens | Decode rows keep their one-request arithmetic ([batch decode](#gemma-ordinary-batch-decode-arithmetic)); each prompt frame runs alone on its request's own chunk grid (`QwenBatchSettings`) | +| Memory | No load-time allocation; each lane is admitted against live memory and the activation floor is unchanged ([Gemma paged cluster lanes](hardware-support.md#gemma-paged-cluster-lanes)) | +| Cancellation | A cancelled lane retires alone (`DistributedInstalledPlan.lanesRetireAlone`) | +| One-chunk lookahead | Lanes prefill serially, so a setup that saved `one_chunk_lookahead_v1` keeps its schedule and one lane, as a planned batch width requires serial prefill (`ClusterConfiguration`) | + +Both owners derive the width from the same saved setup and bind it into the +load agreement (`Gemma4BatchArithmeticAgreement`). The width is not qualified +on hardware: multi-lane joining, cancellation and output agreement on the +real pair remain separate checks, as for every pipeline lane adapter. + +### Gemma routed-expert prior + +`Gemma4PlacementFamily` states that every layer routes a token to 8 of its 128 +experts (`expertRouting`, from `Gemma4StageGeometry`) and names the +`experts.switch_glu` banks as routed experts (`isRoutedExpert`). Gemma layouts +therefore carry `routedExperts`: 12,846,366,720 bytes for the QAT 4-bit +artifact and 24,265,359,360 bytes for the 8-bit one. The hardware prior +(`ClusterHardwarePrior.decodeBytesPerToken`) counts 2,424,219,708 weight bytes +per QAT 4-bit token instead of every layer byte. The golden pipeline plans +keep their cuts and modes; the prior feeds the device-index and +tensor-parallel share estimates (`ClusterHardwarePrior.absolute`, +`ClusterDecodeSplit`). + ### Qualification records for identical catalog files The plain `gemma-4-26b` and `gemma-4-26b-8bit` catalog entries have identical @@ -4775,6 +5767,79 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Reside and `MiMoV26IndependentHistoryCache.swift`. See [MiMo independent-history checks](../developer/test.md#mimo-independent-history-batch-checks). +### MiMo contiguous ring metadata + +Only image-candidate loads keep MiMo's ordinary caches: `KVCacheSimple` for +full attention and `RotatingKVCache(maxSize: window)` for each sliding window. +The four text modes use pages with cluster prefix reuse off +([independent histories](#mimo-plain-pipeline-independent-histories)), so only +image candidates take cluster prompt-prefix snapshots. `MiMoPhaseSplitState` +also handles ordinary caches, but no load reaches that branch: image candidates +refuse phase split (`MiMoResidentRuntime.load`). The pinned SDK writes a ring's +`metaState` as seven values: keep, window, step, offset, write index, capacity +origin and wrapped flag. A rewind reserve adds an eighth. + +| Path | What it writes or accepts | +|---|---| +| Model ring check (`MiMoSlidingRing.isModelRing`) | Only the model's own ring: every value except offset, write index and wrapped flag equals a fresh ring's | +| Prefix capture and restore (`MiMoStagePrefixSnapshot`) | Restores a tail at the frontier's offset and write index, not wrapped | +| Phase split (`MiMoPhaseSplitState`) | Replays the frame grid for the write index and wrapped flag; exports or adopts a ring only when its whole metadata matches | +| Verify-window rollback (`MiMoWindowRollback`) | Cuts a multi-token window's rows and rewrites only offset and write index; that window left the wrapped flag false | +| Page histories (`MiMoPhaseSplitState.pagedMetadata`) | Keep their own five values | + +The snapshot and the phase split refuse a kept prefix, another step or origin, +a rewind reserve or another layout. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoSlidingRing.swift`, +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoPhaseSplit.swift`, +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Prefix/MiMoStagePrefixSnapshot.swift` +and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoWindowRollback.swift`. + +### MiMo pipeline decode command buffers + +MiMo stage decode encodes its Metal command buffers as GLM's and Qwen's +tensor-parallel decode do: up to 100 operations a buffer with no input-size +bound (`MiMoLayerStageSession.decodeCommandBuffers`), on the thread that encodes +the step. The rank's own limits are the worker's 16-operation guard +(`ClusterWorkerEnvironmentGuards`) and MLX's per-chip size bound, and each +routed layer's expert launch takes a whole 1 GiB expert bank as input, so under +those limits a decode step commits a buffer every few launches. Prefill frames +keep the rank's limits. + +| Work | Where the limits apply | +|---|---| +| Plain and compact decode frames, phase-split and alone-route decode | `MiMoLayerStageSession.decode` | +| Lane steps of independent histories | `MiMoLayerStageSession.decodeBatch` | +| Speculative rounds of `pipeline_mtp_v1`: drafts, verify windows, settlement | `MiMoMTPGeneration.runProducer`, `MiMoMTPGeneration.runConsumer` | + +Only the commit points move: every kernel, input and rounded value is the +same. `MiMoDecodeCommandBufferTests` compares residuals, logits rows and every +cache and page array byte for byte under both limits on synthetic stages. + +MLX keeps up to ten command buffers in flight (`MLX_MAX_ACTIVE_TASKS`) and frees +a buffer's temporaries when it completes, so under the decode limits a whole +stage step's temporaries can be alive at once. A request's workspace charge +therefore prices every full-attention layer's float32 score rows for its decode +rows together (`MiMoRequestStateBudget.estimate`, `decodeRows`: one row, or the +verify window's `depth + 1`), and never less than one prompt frame's scores on +one layer. Gathered page views are already charged for every layer +(`MiMoPagedKVAllowance.pages`). A verify window of three or four rows takes +MLX's unfused path, which builds those scores in bfloat16. One or two rows take +its fused vector attention instead, whose +float32 partials on Max and Ultra GPUs (`sdpa_vector_2pass` in +`libs/mlx-swift/Source/Cmlx/mlx/mlx/backend/metal/scaled_dot_product_attention.cpp`) +can exceed a score row and are not priced separately. The decode speed effect +and peak memory on the registered model are not measured yet. + +### MiMo routed experts in placement + +`MiMoPlacementFamily` states MiMo's routing: each of the 47 routed layers sends +a token to 8 of its 256 experts (`expertRouting`). Its routed-expert tensors are +each layer's `mlp.switch_mlp` banks and their block scales (`isRoutedExpert`). +The router and its score correction are read on every step. The layout then +carries `routedExperts`, and the hardware prior +(`ClusterHardwarePrior.decodeBytesPerToken`) counts 10,767,036,288 bytes for one +decode step instead of every expert's 166,600,109,952. The prior prices tensor +parallel only, so MiMo's pipeline plans are unchanged. + ### Gemma paged prefix restoration Installed plain Gemma pipelines retain the paged KV default at every supported @@ -4813,6 +5878,17 @@ replace full-artifact qualification. Preserve earlier solo/pair reports and failed records; remeasure the candidate with the original comparator and qualification schedules. See [the test guide](../developer/test.md). +## GPT-OSS decode command buffers + +GPT-OSS's plain decode steps (every row one token) commit a Metal command buffer +every 100 operations with no input-size bound (`GPTOSSDecodeCommandBuffers`, +through `CBv2DecodeCommandBufferLimitsProviding`). MLX's defaults commit every 40 +to 50 operations or 40 to 50 M distinct input elements, and a step's inputs include +the expert banks and each 64 MiB KV segment its history reads, so decode committed +after almost every MoE layer and waited on MLX's limit of ten command buffers in +flight. Results do not depend on the partitioning. Prefill chunks keep MLX's +defaults. + ## Nemotron prefix chunk arithmetic The registered Nemotron 3.5 Lightning stage preserves the original global @@ -4857,17 +5933,33 @@ packed weights; it adds no persistent weight copy. Query/key/value, output, shared MLP and router projections use their existing model call sites. Norms, the vocabulary head, independent decode lanes and singleton frames retain their existing operations. -The same explicit prompt scope invokes each BF16 token's complete expert block -with its unchanged selected indices and weights. This preserves singleton -GeGLU and weighted reduction rather than entering a wide sorted expert graph; -ordinary SDK prompts and speculative verification keep their existing paths. Custom modules, other dtypes/packing, and ordinary -SDK callers retain the original forward method. +The same explicit prompt scope keeps each BF16 token's complete expert block +at one token: its unchanged selected indices and weights, an M=1 gathered +product per selected expert, singleton GeGLU and its own top-K weighted +reduction, rather than a wide sorted expert graph. All tokens of a frame share +one call (`SwitchGLU.callAndWeightedReduceRows`). It groups their assignments +by expert for weight locality but does not give the gathers the sorted hint, so +every pair keeps the unsorted M=1 route. MLX picks `gather_qmv` and its variant +from the quantization, dtype and the N and K widths, never from the row count. +The rows return to token order before +the top-8 reduction, whose `col_reduce_small` thread layout depends only on the +hidden width. Each token's bytes therefore equal those of its own one-token +call. The tokens share one dispatch per operation instead of about six per +token per layer. Independent decode rows use the same call +([Gemma ordinary batch decode arithmetic](#gemma-ordinary-batch-decode-arithmetic)). +Ordinary SDK prompts and speculative verification keep their existing paths. +Custom modules, other dtypes/packing, and ordinary SDK callers retain the +original forward method. The exact Gemma arithmetic receipt binds both prompt projection and expert reduction policies before LOAD, separating prior rectangular-projection cache and plan identities. The stable family policy identifier and required environment flags remain the same. +The shared expert dispatch changes no byte, so the receipt and the cache +identities it separates are unchanged. Component byte equality is separate from full-model two-chip numerical -qualification, and the M=1 prompt graph requires its own throughput measurement. +qualification. The M=1 prompt graph still needs a pair throughput measurement; +the synthetic component timings are in +[Gemma pipeline prompt experts](../reports/2026-11-01-gemma-pipeline-prompt-experts.md). The SDK helper is `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Gemma4PrefillProjection.swift`; stage activation and receipt binding are in @@ -4997,8 +6089,9 @@ prerequisite does not advertise media support or activate a native model path. Every registered Qwen TP row (the 9B and 27B dense rows, the Qwen3.5 and Qwen3.6 35B A3B routed-expert rows) serves request-owned lanes on main's paged KV host -(`CBv2StageKVHost`) at every capacity, one through eight; the default remains -one, and one lane is the same path one lane wide (the singleton wire adapts to +(`CBv2StageKVHost`) at every capacity, one through eight; a setup saved without +a width serves one ([saved width](#qwen-tensor-parallel-saved-width)), and one +lane is the same path one lane wide (the singleton wire adapts to the shared driver, `QwenTensorParallelSingletonHost`). The former single-lane owner (request-local caches on its own page pool and the `DARKBLOOM_CLUSTER_QWEN_TP_PAGED_KV` switch, with its own prefix cache) is @@ -5023,9 +6116,10 @@ A decode step is submitted while it is built. `QwenTensorParallelBatchSession` decodes under `Qwen35LayerSubmission` with a stride of one layer (`decodeLayerStride`): after each decoder layer the forward submits what it has built (`asyncEval`), so that layer's kernels and collectives run while the host -builds the next. The driver plans a step only after the previous step's tokens -are known, so the request-owned path cannot build one step ahead as the retired -single-lane loop did; submitting by layer hides the graph build instead. +builds the next. The driver builds a step only after the previous step's tokens +are read (a plain step's plan is made before them, below), so the request-owned +path does not build one step ahead as the retired single-lane loop did; +submitting by layer hides the graph build instead. Speculative verify windows are evaluated whole instead (`QwenTensorParallelTargetWindow.submitsByLayer` off): with the main-merged MLX core, an `asyncEval` after every layer of a window cost a solo 27B request on two @@ -5077,8 +6171,9 @@ them; an installed worker always uses the defaults), and microseconds). `darkbloom-cluster-tp-check qwen-prefill` measures one rank's prompt frames, layers and projections with no peer. -The driver coordinates join, one prefill frame and a decode cohort on both -ranks. A held token credit blocks only its request. When some decode rows are +The driver coordinates join, one prompt step (one frame, or several merged: +[Qwen tensor-parallel prompt wavefront](#qwen-tensor-parallel-prompt-wavefront)) +and a decode cohort on both ranks. A held token credit blocks only its request. When some decode rows are ready and others await nearby owner acknowledgments, the driver reuses `QwenBatchDecodeCoalescing`'s absolute 2,000,000-nanosecond window. It keeps exchanging no-work steps and servicing control; new joins, prefills and retirement @@ -5091,25 +6186,309 @@ acknowledgement. Failed release retains the reservation for cleanup or the worker's process fence. Every row's singleton and batch owners publish raw selection logprobs through the committed-token channel. +Selection checks finiteness inside its own sealed sum, as the assistant's greedy +choice does (`QwenTensorParallelNativeBatchExecutor.select`): each rank adds its +rows' non-finite logit counts beside their maximum and first global index (a +sampled cohort counts the gathered rows), and both ranks read them from the +same evaluation that yields the tokens. A non-finite logit on either rank fails +both ranks before any token is chosen, a sampler advances or anything is +published, so neither rank waits in a collective its peer never enters. The +load agreement binds this selection sum +(`qwen-tensor-parallel-selection-nonfinite-in-sum-v1`): a rank whose selection +sums other words refuses to load beside it rather than meet it in a sum of +another length. The decode step pays no separate finiteness read +(`QwenTensorParallelBatchSession.validateLogits` checks shape and dtype), and +every selected token is unchanged. + +A plain decode step carries the next step's control in its selection sum +(`QwenTensorParallelBatchDriver.serve`). When every row of the rectangle selects +plainly (`QwenTensorParallelBatchLane.plainSelection`: no assistant) and no +prompt step follows it in the step, rank 0 makes the next plan and rank 1 its +report once the forward committed (the executor's `decode` `control` closure), +and both ride the selection's own sealed sum: after a greedy cohort's six words +a row, or after a sampled cohort's choices (its gathered rows keep their own +sum). Such a step pays one sealed sum and one host read instead of an exchange +and a selection. A step after a prompt, idle or assisted step exchanges its +plan as before, and so does every step of an executor whose selection sum +carries no control words (`carriesSelectionControl` false, the protocol's +default; the Qwen native executor's is true). The plan is made before the step's tokens are known, so: + +- A row that decodes on the token being selected names + `QwenTensorParallelBatchWire.carriedToken`. Both ranks take the token from the + same sum, and both drop that decode when the token ended its request (a stop + token or the output count). +- Host events (owner answers, credits, cancellations, joins) apply one step + later: rank 0 polls them while it makes the next plan, after the forward and + before the tokens are read. A row may decode on its newest token once the + owner answered "go on" to the token before it, and rank 0 publishes a token + only after that answer: at its selection, or at the poll that brings the + answer (a row holds at most one unpublished token). +- A stop answer that arrives after the row selected one more token keeps the + tokens the owner saw. Rank 0 never publishes that token, both ranks drop it + (the leaving slot carries the kept count), and the native finish counts one + discarded forward (`QwenTensorParallelNativeBatchExecutor.retire`). The + one-lane wire answers each token as it is published, after the next forward + was planned, so there a client stop to any token a plain decode step selected + runs one discarded forward, and the request's finish follows that forward. + Usage and logprobs cover the kept tokens only; prefix captures and SSD + records hold prompt states, which no decode forward changes. + +The load agreement binds the wire version +(`qwen-tp-independent-history-batch-v2-folded-control`), so a rank of an +earlier build refuses to load. Tokens, logits and native state are unchanged: +the control limbs are exact in FP32, each element of the sum is added alone, +and the collective payload quote covers the longer frame +(`QwenTensorParallelBatchBudget`). `darkbloom-cluster-tp-check qwen-decode` +(`QwenTensorParallelDecodeBench`) times the driver's decode on two ranks over +the loopback ring with the control exchanged or folded and checks that both +retire the same tokens. + The batch path can restore mutually held original-grid prefix snapshots into fresh request-owned state. TP speculative rounds remain a separate integration. Installed owners propagate a priced -saved width or explicit diagnostic width for every Qwen TP row; automatic placement -uses the separate full native TP quote described above. A row that may also run +saved width or explicit diagnostic width for every Qwen TP row; placement and automatic +replacement use the separate full native TP quote described above. A row that may also run the pipeline prices tensor parallel with its singleton quote and keeps the pipeline modes as candidates (`ClusterPlacementTensorBatchQuote.applySingletonCandidate`); the 27B, whose features keep it in tensor parallel, and an assistant quote bind the placement to tensor parallel as before. Synthetic CPU and both-chip native fixtures are not full-artifact, RDMA, tower, throughput or endpoint evidence. +Each rank logs its decode routes once per loaded model when its native +executor first starts serving (`darkbloom-qwen-tp-decode-census-v1`, +`QwenTensorParallelBatchSession.censusLine`): every projection's route (the +batch-invariant kernel `aqv`, a row-parallel FP32 partial on it `partial`, or +MLX's own kernels with the reason, `mlx-...`) and each projection shape's +layout per vector count (plain rows of one to eight and their four-column +windows), the residual-norm form, the paged attention geometry and partition +size, the selection, and any arithmetic switch the launcher set. A registered +27B rank reports `mlx=0`. Only host values are read; nothing is evaluated. +Layouts are listed per checkpoint projection: the SDK multiplies a Gated +DeltaNet layer's four input projections as one call of their summed rows, and +fuses gate, up and SwiGLU at `swiglu_fused_vectors` only while its decode +fusions are on. A routed-expert row's switch projections are not listed. + +`QwenTensorParallelRowsCheck` checks the row contract at the registered 27B +per-rank widths (three Gated DeltaNet layers and one attention layer; the +whole 248,320-row vocabulary) with random weights that follow the registered +artifact's value statistics: MLX's affine 4-bit quantization of near-normal +weights (group 64, signed BF16 scales of 0.001 to 0.005, biases -8 times the +scale, codes about 8), its norm, convolution, `A_log` and `dt_bias` ranges, +and gate rows whose SwiGLU inputs reach its range (about ±30). A row's logits +and history equal its run alone, on a one- or an eight-lane host, beside rows +of 100 to 4,600 tokens that join and leave, across two KV segments, while an +assistant observes the cohort, and at every position of a four-column verify +window alone and in a cohort. Both ranks run it in one process +(`QwenTensorParallelRealGeometryRowsTests`, `QWEN_TP_REAL_GEOMETRY_GPU=1`) or +as two processes over the loopback ring (`darkbloom-cluster-tp-check +qwen-rows`, native or sealed sums, with the worker's arithmetic environment). +It refuses to report when a logit is not finite, when its reference logits are +not all distinct, when the long rows fit one KV segment, or when its comparison +misses a planted difference. `qwen-rows run` also loads a registered +checkpoint directory on a Mac with the memory for it, reading the files +directly as `tp-check run` does, not through the product's verified load +(`QwenTensorParallelVerifiedLoad`: no artifact hashes, inventory or load memory +gate). `qwen-rows layers` names the first decoder layer where a row's step +beside another leaves its solo bits +(`QwenTensorParallelRowsCheck.firstDifferingLayers`, through +`Qwen35LayerSubmission.observer`). On an M5 Ultra every comparison is bitwise +equal, with the fixture and with the registered checkpoint. It covers neither +JACCL's streamed sealed sums, the driver under live traffic nor the HTTP +stream. + Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift` -(`QwenTensorParallelBatchSession`), +(`QwenTensorParallelBatchSession`, `censusLine`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelRowsCheck.swift` +(`QwenTensorParallelRowsCheck`), +`libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift` +(`QwenRowsCheck`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift` -(`serve`, `makePlan`, `join`, `leave`), +(`serve`, `makePlan`, `resolve`, `publishHeld`, `join`, `leave`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift` +(`QwenTensorParallelBatchWire`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift` +(`decode`, `select`, `retire`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift` +(`QwenTensorParallelDecodeBench`), +`libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift` +(`QwenDecodeCheck`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Batch/QwenBatchDecodeCoalescing.swift` (`shouldDefer`), and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelResidentRuntime+Batch.swift` (`serveBatch`, `prepareBatch`). +### Qwen tensor-parallel saved width + +Guided placement saves each Qwen TP pair's width (`batchLanes`), so the pair +serves concurrent requests from its first load. Before, such a setup saved no +width and served one request at a time: a local pair widened only through a +drained replacement, which the first burst waited for, and a pair saved for +coordinator pairing never widened. + +1. The guided setup (`ClusterSetupWizardLiveOperations`, which the onboarding + and the six-step wizard share) reads the owner's complete quote at widths 2, + 4, 6 and 8 (`ClusterPlacementTensorAssistantSelection.readAutomatic` with + `lanes`), each for the singleton quote's own request envelope and assistant. +2. The placement is chosen as before, from the singleton quote: mode, leader, + split and reference request (`ClusterPlacementFlow.decide`). +3. `ClusterPlacementTensorWidth.widest` prices that placement, leader and split + unchanged, at 8, 6, 4 and 2 in turn, with each width's quote in place of the + singleton's (`ClusterPlacementTensorBatchQuote.applyWidth`), and saves the + first that both Macs admit now. The predicate is the one an automatic + replacement is held to (`ClusterPlacementCandidate.admitted`): possible, + inside the GPU working set, and every rank within what its Mac admits now. + The plan then reports that width's memory and keeps the reasons its mode was + chosen for one request, including a row's comparison with the pipeline + where the pipeline stays a candidate. When no width fits, the setup saves + none and serves one request at a time, as before. +4. LOAD quotes, measured floors and live admission are unchanged. Both ranks + reserve the saved width's complete quote at LOAD and admit each request + alone. + +A typed assistant policy (the developer wizard) and `darkbloom cluster plan` +read no width quotes and save no width. + +A pair saved for coordinator pairing keeps its width for the life of the +setup. The width is a field of each Mac's saved setup only. The approval, the +roster registration, the committed native start and the release's runtime +facts name no width, so no approval digest changes. The approval is saved +beside the width unchanged (`ClusterApprovalAttachment`), and both workers bind +the width in their sealed load agreement. Automatic replacement never plans for +an approved setup (`DistributedAutomaticBatchPlanner.snapshot`). A re-plan, +after an update or a refused load, sizes the width again on the memory then. + +On a local pair, queued demand still proposes a width wider than the saved one +through a drained replacement: the fallback for Macs that admitted a narrower +width when planned. A pair saved at eight is never drained. + +The widths the registered Qwen3.8 27B saves on idle pairs (its retained +headers and LOAD's own quotes, the vision tower's resident bytes aside as in +the served layout; `ClusterPlacementTensorWidthRegisteredTests`): + +| Each Mac | Without the assistant (served through Darkbloom) | With the depth-3 assistant (local) | +|---|---|---| +| 32 GiB | 2 | 1 | +| 36 GiB | 2 | 1 | +| 48 GiB | 4 | 2 | +| 64 GiB | 8 | 4 | +| 96 GiB and larger | 8 | 8 | + +At eight lanes, each rank of an equal split reserves 40,911,618,048 bytes at +LOAD without the assistant and 60,734,767,104 bytes with it, each lane's +prompt-prefix capture ([prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership)) +and the shared 367,001,600-byte prompt wavefront term +([prompt wavefront](#qwen-tensor-parallel-prompt-wavefront)) included; with its +weights and loading headroom it needs 54,441,306,624 and 77,998,565,888 bytes. +Every +registered Qwen TP row is sized the same way from its own quotes. GLM keeps its +eight lanes and other families keep their defaults. + +Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift` +(`ClusterPlacementTensorWidth`), +`provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift` (`decide`) and +`libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementTensorBatchQuote.swift` (`applyWidth`). + +### Qwen tensor-parallel prompt wavefront + +A Qwen TP prompt frame of 512 rows used to compute, then wait for its own +sealed FP32 sums: two per layer, each read by the next residual norm, so the +GPU and the link took turns. On the pair at 11K tokens a 27B frame computes for +about 165 ms and its 128 sums take about 186 ms, so prefill ran at 0.75x one Mac +[INFERENCE: split from `qwen27-tp-speed-plan` measurements, not traced]. A plain +text lane now prefills up to eight consecutive frames as one graph, built layer +by layer as GLM's micro-batches are (`GLM5NextTextStage.microBatchedLayer`): a +frame's mixer through its row-parallel output projection, that sum submitted at +once, the next frame's mixer while it crosses; then each frame's MLP the same +way. + +```mermaid +flowchart LR + subgraph Layer["layer L of a step of frames f0..f7"] + M0["f0 mixer partial"] --> S0(["f0 sealed sum"]) + M0 --> M1["f1 mixer partial
(reads f0's KV and
conv/SSM state at L)"] + M1 --> S1(["f1 sealed sum"]) + M1 --> Mn["... f7 mixer"] + S0 --> F0["f0 residual + MLP partial"] --> T0(["f0 sealed sum"]) + S1 --> F1["f1 residual + MLP partial"] + end +``` + +- **Planning.** The leader plans one prompt step a driver step: up to + `QwenTensorParallelPromptWavefront.maximumFrames` (8) frames, or + `framesBesideDecoding` (2) while another lane decodes, ending at the prompt's + end or at the lane's capture frontier (`QwenTensorParallelBatchSession.promptFrames`). + The plan carries the step's offset, tokens and final flag; each rank runs it + only as a prefix of its own frames (`promptStep(tokens:)`), so both ranks run + the same frames. +- **Graph.** One `CBv2OwnedRequestState.run` covers the step. + `Qwen35PromptWavefront.prefill` builds each layer for every frame in two + phases (`Qwen35DecoderLayer.promptMixer`, `promptFeedForward`). A frame reads + the attention rows the frame before it wrote at that layer (the cache's + advanced offsets, the prefill mirror or the page gather) and its recurrent + state (`Qwen35GatedDeltaNet.cbv2Recurrent`); the last frame's state is staged + into the run's evaluation. The prompt's last frame takes `cbv2Forward`'s fused + residual norms and whole-frame head, as alone. After each phase the raw sums + the row-parallel projections issued (`QwenTensorParallelRowLinear.issuedSums`) + are submitted (`asyncEval`), and building waits while more than + `QwenTensorParallelPromptWavefront.sumsInFlight` (4) are unfinished. Without + that bound MLX encodes, and allocates, the independent frames' phases up to + `MLX_MAX_ACTIVE_TASKS` tasks ahead of the link. +- **Commit.** The run validates the step's frontier and commits once; the + session then commits each frame on its schedule and takes a prefix capture + when the step reaches the frontier, as after a lone frame. + +Invariants: +1. Every frame runs the operations it runs alone, at its own 512-row shapes; + only submission order changes. Logits, attention rows, conv and SSM states + and prefix captures are the per-frame bytes + (`QwenTensorParallelPromptWavefrontTests.mergedFramesKeepEveryBit`: both + ranks, paged with the mirror and with page gathers, contiguous, a prompt + ending mid-frame, a capture frontier inside the prompt, a lane decoding + beside it). +2. Each rank issues the sums frames alone issue, two a layer a frame, in the + same order on both ranks. They stay sealed FP32 all-sums: no BF16 partial, + no TF32 change. +3. Only text lanes of dense models on native KV rows merge + (`QwenTensorParallelPromptWavefront.merges`). Assisted (MTP) lanes, media + lanes, packed KV and routed-expert models run one frame a step. +4. A step's further frames in flight are charged: + `QwenTensorParallelPromptWavefront.inFlightBytes` (per further frame, five + frames' FP32 collective payload: two partials, two sums and the BF16 + residual rows) joins the shared prompt workspace of + `QwenTensorParallelBatchBudget`, so LOAD, the placement quote and every + request's charge (`QwenTensorParallelRequestCharge`) include it. Its value + and measurements are in the + [TP batch admission boundary](hardware-support.md#qwen27-tp-batch-admission-boundary). +5. The load agreement binds `qwen-tensor-parallel-prompt-wavefront-v1` and the + frame limits; `DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT=0` (diagnosis only, both + ranks) restores one frame a step. + +Failure modes: a planned step a rank cannot run as a prefix of its frames fails +the driver step on that rank, as a changed frame did; a merged step that fails +fails the lane as a frame does. A lane decoding beside a long prompt waits for a +two-frame step instead of one frame. + +`darkbloom-cluster-tp-check qwen-prefill --wavefronts 1,8` times one rank's +steps with no peer; `darkbloom-cluster-tp-check qwen-wavefront` runs a prompt on +two ranks over the loopback ring at each frame limit, logs each run's peak +memory (`peak_mb`) and checks that every run leaves both ranks the same bytes. +Loopback timings show the overlap, never a pair's rate: on one M5 Ultra, 4-layer +shards at the 27B's per-rank widths (`qwen-rows synthesize`) prefilled 11,264 +tokens over the sealed ring in 848-961 ms in steps of two or eight frames, +against 1,517-1,522 ms one frame a step, every run with the same bytes on both +ranks. + +Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPromptWavefront.swift` +(`QwenTensorParallelPromptWavefront`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift` +(`promptFrames`, `prefill(step:check:)`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift` +(`issuedSums`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift` +(`derive`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefillBench.swift` +(`pair`), and `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Qwen35PromptWavefront.swift` +(`Qwen35PromptWavefront`). + ### Qwen27 tensor-parallel native context The registered Qwen3.8 27B row advertises the limits the single-Mac product @@ -5135,17 +6514,21 @@ and verify transients. The shared charge is never below LOAD's. Each rank's live gate (`reserveLane`, with the same OS and allocator checks) admits the whole charge or refuses that request alone. The endpoint then answers 503 with the context the pair serves now, and the pair keeps serving. A request within the -memory plan is charged as before and must still fit LOAD's per-lane quote. +memory plan, at most its context and its prompt, must still fit LOAD's per-lane +quote. A longer prompt within that context is charged at its own prompt, as a +longer context is, because each request's prefix capture grows with its prompt +(`QwenTensorParallelRequestCharge.withinMemoryPlan`). READY's request capacity is the larger of LOAD's quote and one request at 262,144 tokens. READY, and every keep-warm answer while no lane is held, carry the longest context the reservation gate admits now (`servingContextTokens`, computed with the gate's own arithmetic). The pair refuses a longer request before either rank is asked. With the registered inventory on an M5 Ultra -(256 GB), eight lanes with the depth-3 assistant reserve 48.4 GB a rank at LOAD -(4.6 GB a lane). A 262,144-token request beside seven standard ones is charged -69.4 GB a rank (a 13.9 GB lane and 22.8 GB of shared workspaces), beside at most -16.3 GB of weights (`QwenTensorParallelNativeContextTests`). +(256 GB), eight lanes with the depth-3 assistant reserve 60.4 GB a rank at LOAD +(6.2 GB a lane). A 262,144-token request beside seven standard ones is charged +89.0 GB a rank (a 23.1 GB lane, including its own prompt's prefix capture, and +22.4 GB of shared workspaces), beside at most 16.3 GB of weights +(`QwenTensorParallelNativeContextTests`). The pipeline and hand-off modes stay at the memory plan. Their LOAD gates size it, and they refuse a longer reservation (`requireWithinMemoryProfile`). Provider @@ -5185,6 +6568,25 @@ Sources: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Ten `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2OwnedRequestState.swift` (`growReservation`). +### Qwen27 tensor-parallel prompt-prefix depth + +A plain Qwen tensor-parallel lane keeps prompt-prefix boundaries to its request's +context on its own 512-token chunk grid, not to a fixed 4,096 tokens: the +deepest whole chunk before the final token, a boundary 64 tokens before the +prompt end for the next turn, and one Mac's 4,096-token stripe boundaries for +a shared system prompt (`QwenTensorParallelBatchPrefixBudget`, policy +`qwen-tp-batch-prefix-depth-v2`, which the load agreement binds). A repeated +33K-token prompt restores 32,768 tokens on both ranks, as one Mac reuses. A +request restored from memory or a native SSD record computes exactly what a +cold one computes on the same grid; the SSD tier's default `balanced` records +keep their older rows approximate. +The mechanism, the parity cases and the SSD records are in +[the Qwen27 TP prefixes](prefix-cache.md#qwen27-tp-prefix-ssd-tier) and the +section before it; the memory each request and LOAD charge is in +[Qwen27 TP batch prefix ownership](hardware-support.md#qwen27-tp-batch-prefix-ownership). +The assistant's lanes keep one boundary of at most 4,096 tokens +([assistant prefix ownership](prefix-cache.md#qwen27-tp-assistant-prefix-ownership)). + ### Qwen27 cluster media ingress ownership The scheduler routes image/video requests through `DistributedQwenMediaIngress` @@ -5222,6 +6624,19 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Requests/Dis `provider-swift/Sources/ProviderCore/Inference/Distributed/Requests/DistributedQwenMediaLifetime.swift`, and `provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedEngineFactory.swift`. +## Gemma decode command buffers + +Gemma 4's plain decode steps (every row one token) commit a Metal command buffer +every 100 operations with no input-size bound (`Gemma4DecodeCommandBuffers`, +through `CBv2DecodeCommandBufferLimitsProviding`), as Nemotron Super, Flint and +GLM do. MLX's defaults commit every 40 to 50 operations or 40 to 50 M distinct +input elements. A step's inputs include the weights and each 64 MiB KV segment +its history reads, so decode committed many times per step, reached MLX's limit +of ten command buffers in flight, and waited inside evaluation instead of +encoding ahead of the GPU. Results do not depend on the partitioning. Prefill +chunks and assistant rounds keep MLX's defaults, so a row served with the +assistant does not gain from this. + ## Qwen27 feature-preserving mode selection The exact registered Qwen3.8 27B dense adapter/profile requires images, video and committed-token logprobs on its installed cluster route. `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterModelFeaturePolicy.swift` restricts that row to the advertised tensor-parallel mode before the ordinary placement cost ranking. Initial onboarding and automatic batch replacement share this intersection in `ClusterPlacementFlow.swift`; an incumbent pipeline cannot override it. Other registrations, GLM, measured rates, qualification shape exclusions and native memory gates keep their existing behavior. This policy is a restriction on existing metadata, not a new model catalog or capability grant. It does not prove tensor parallel is faster. @@ -5414,6 +6829,8 @@ A live service acknowledges planned local stop only through a fresh private supe A local-only optional `ClusterSetupRecord.stopDrain` token is written atomically with serving=false. During that token’s lifetime, controlTick and final sendLease derive both remote running and serving from the same record, preserving the prior peer intent while the local supervisor drains. A matching stop-token supervision cycle may clear it only after no local child/leftover and no outbound lease remains in flight. New leases then reread stopped intent. Handover and background serve/stop synchronization wait; background mutation also holds command custody and rereads current intent. Normal wire fields and lease deadlines are unchanged. +The supervision cycle that clears the token also publishes `service-status.json` with `child.running = false`, and it writes that file first. A `darkbloom cluster stop` that starts at that moment (for example, a retry after a local timeout) can meet the service's record write. The stop's record write waits up to 2 seconds for the record lock, so it does not fail with "could not save the stop request". The service makes its write while it holds the service lock, so it tries the record lock once and tries again on its next cycle. + ### Qwen27 capacity changes preserve request arithmetic The authenticated Qwen3.8 27B tensor-parallel owner uses CBv2 request-owned attention and recurrent history at capacity one and at wider capacities. A singleton adapter keeps the existing one-token worker credit while executing the same native batch driver; its completion is constructed only after both ranks confirm retirement. Native metadata quotations charge the full singleton CBv2 state, workspace, collectives and prefix allowance, including the selected assistant policy. Within that charge a paged lane's pages are reserved as the request grows ([native context](#qwen27-tensor-parallel-native-context)). Other model families and unkeyed singleton probes retain their existing execution paths. See `QwenTensorParallelBatchSettings`, `QwenTensorParallelResidentRuntime+Singleton.swift`, `QwenTensorParallelBatchBudget` and `ClusterPlacementTensorBatchBudget` under `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/`. diff --git a/docs/architecture/model-autopilot.md b/docs/architecture/model-autopilot.md index 73226f9dd9..8bb12d46d1 100644 --- a/docs/architecture/model-autopilot.md +++ b/docs/architecture/model-autopilot.md @@ -1,6 +1,6 @@ # Provider Autopilot -> Last updated: 2026-10-27 +> Last updated: 2026-11-02 Provider Autopilot offers an external controller the models of a Mac whose operator saved Autopilot consent: the saved selection plus every verified @@ -84,9 +84,14 @@ valid. The coordinator learns inventory metadata (`ModelInfo`) only from heartbeat's `selected_models`, and the provider re-registers once (`refreshAutopilotInventoryRegistration`, a planned reconnect) on the first capacity tick with no busy reason, no operation, no live lease, no running or -queued download and the background verification finished. A busy provider -keeps waiting rather than interrupting work; a registration made for any other -reason also ends the wait (`registeredAutopilotInventoryIDs`). +queued download and the background verification finished. A registration made +for any other reason also ends the wait (`registeredAutopilotInventoryIDs`). +After `autopilotInventoryRegistrationMaxWait` (10 minutes), in-flight work and a +live lease no longer defer it. The planned reconnect then closes admission, lets +accepted work finish, and reconnects; it never cancels accepted work. An +operation, every other busy reason, a download and the verification still +defer it. `models_update` cannot carry the build: the coordinator would make it +ordinary and publicly routable. ## Downloads on the operator's behalf @@ -244,6 +249,12 @@ stops the driver at its next candidate, and the current step finishes normally. 9. Without saved consent, or with downloads turned off, there is no download, no `inventory_downloads` capability and no `download_storage` (`autopilotDownloadsEnabled`, `handlePrefetchModelRequest`). +10. Without Autopilot, coordinator `load_model`, `prefetch_model` and desired + builds stay inside the + [operator filter](../reference/configuration.md#provider-model-selection), and + a selected build's alias successor becomes ordinary only inside it, with or + without consent (`autopilotAllowsModel`, `operatorFilterAllows`). Consented + downloads and operations keep their own gates. ## Failure modes @@ -262,12 +273,15 @@ stops the driver at its next candidate, and the current step finishes normally. recorded downloads in the set until the next start. - Until the provider re-registers, a coordinator sees a newly downloaded build only as an ID in `selected_models`; operations on it are refused as not - cached. A provider that is never idle keeps waiting. + cached. A provider that is never idle at a capacity tick waits at most + `autopilotInventoryRegistrationMaxWait`. - A build at the 256-ID bound downloads but stays out of the set and its download reports `model_not_supported`. - A re-registration closes admission briefly, like any planned reconnect, and fails coordinator-side operations queued for that machine; it waits for an - idle tick and happens once per batch of new builds. + idle tick, or for the end of the bounded wait, and happens once per batch of + new builds. After the bounded wait it also ends a live lease, as any + reconnect does. ## External Policy diff --git a/docs/architecture/native-block-inference.md b/docs/architecture/native-block-inference.md index ba4721ab43..973d1ad6c7 100644 --- a/docs/architecture/native-block-inference.md +++ b/docs/architecture/native-block-inference.md @@ -1,6 +1,6 @@ # Native block-generation adapter -> Last updated: 2026-10-09 +> Last updated: 2026-10-31 This page explains the native block engine and its provider bridge boundary. DiffusionGemma uses explicit native-container ownership through ordinary slot @@ -247,12 +247,12 @@ content begins. A successfully parsed call does not guarantee that the model copied a requested argument correctly; semantic fidelity remains a separate gate. Both native empty-thought spellings, with and without the newline, are recognized. -`LocalTokenizerLoader` resolves the DiffusionGemma processor's absent -`clean_up_tokenization_spaces` to false through the SDK's -`DiffusionGemmaTokenizerConfiguration`. Explicit Boolean metadata is retained; -other processors keep the existing loader path. This avoids altering literal -punctuation and spaces inside quoted arguments after token generation. The -metadata files, input IDs and native sampling are unchanged. Exact decoding +`LocalTokenizerLoader` resolves an absent `clean_up_tokenization_spaces` to +false: for the DiffusionGemma processor through the SDK's +`DiffusionGemmaTokenizerConfiguration`, and for every other processor in the +loader itself. Explicit Boolean metadata is retained. This avoids altering +literal punctuation and spaces inside quoted arguments after token generation. +The metadata files, input IDs and native sampling are unchanged. Exact decoding does not repair an incorrect value already present in generated tokens. The released template defaults thinking off unless its binary `enable_thinking` diff --git a/docs/architecture/prefix-cache.md b/docs/architecture/prefix-cache.md index 04293c9c21..74dad47ad0 100644 --- a/docs/architecture/prefix-cache.md +++ b/docs/architecture/prefix-cache.md @@ -1,6 +1,6 @@ # KV cache layouts and prefix caching -> Last updated: 2026-10-28 +> Last updated: 2026-11-01 How the provider lays out a request's KV cache, how it decides whether a previously computed prefix can be reused, and where reusable state lives: @@ -1040,7 +1040,8 @@ reach both ranks in its reservation: `ClusterWorkerReservation.prefixCache` stage families through `qwenStagePrefixScope` (resident cache, SSD tier, speculative history), GLM tensor parallel through `GLM5NextTensorParallelResidentRuntime.prefixScope` (vote, restore and kept - boundary) and `prefixDiskScope` (its SSD records), and the Qwen + boundary) and `prefixDiskScope` (its SSD records), Gemma tensor parallel + through `Gemma4TensorParallelPrefix.scopes` (both tiers), and the Qwen tensor-parallel batch owner through `QwenTensorParallelResidentRuntime.batchPrefixScope` (both tiers and the assistant's donors). @@ -1074,10 +1075,13 @@ restored in chronological writes no larger than `PagedKVBackend.pool.config.maxPrefillChunk` by `CBv2PagedPrefixRestore.write` in `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/State/CBv2PagedPrefixRestore.swift`. This permits a retained window larger than a legal individual write without -changing its absolute position or dropping tail tokens. Adoption releases its -new rows when restoration throws. Contiguous rows keep their existing update -path. This is resident stage restoration; it adds no SSD format, persistent -cache identity or cross-host KV-transfer contract. +changing its absolute position or dropping tail tokens. With `reservedTokens` +(Gemma tensor parallel), the new rows are reserved for the request's first +tokens and grow as a fresh request's do; without it, as before, for its whole +length. Adoption releases its new rows when restoration throws. Contiguous +rows keep their existing update path. This is resident stage restoration; it +adds no SSD format, persistent cache identity or cross-host KV-transfer +contract. ## Nemotron chunk-grid reuse @@ -1129,12 +1133,47 @@ every such request with its prefix cache off, so both ranks neither restore nor keep it ([tenant partitions](#cluster-prefix-tenant-partitions)). Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Media/QwenMediaRequestState.swift`. -The exact27 multi-lane TP owner retains one compact snapshot per completed -request at an original chunk boundary, at most 4,096 prompt tokens. The resident -LRU holds at most 32 entries and two maximum-sized snapshot banks. A sealed -vote selects the longest boundary both ranks hold; a one-sided miss computes -cold on both ranks. Restoration writes fresh request-owned attention storage -and adopts immutable confirmed conv/SSM state. It never splits the final chunk. +The exact27 multi-lane TP owner keeps a completed plain request's state at +original chunk boundaries to the request's own context (past LOAD's memory +plan too), strictly before the final token and after what it restored +(`QwenTensorParallelBatchPrefixBudget.frontiers`, policy +`qwen-tp-batch-prefix-depth-v2`): + +| Boundary | Serves | One Mac's counterpart | +|---|---|---| +| The deepest whole chunk before the final token | a repeated prompt | the rolling latest checkpoint | +| The deepest whole chunk at least 64 tokens before the prompt end, from 1,024 tokens on | the next turn of a conversation, whose template re-renders the generation prompt | `demandedLatestPromptEndMarginTokens = 64` | +| 4,096, then every multiple of 4,096 below the deepest, the stripe doubling until at most 8 remain | prompts sharing a long system prompt | the first, fork-target and stripe-end checkpoints of `EngineV2Factory.defaultDenseQwenSoloPrefillStripeTokens` | + +On TP's 512-token grid this reuses at least one Mac's reuse rounded down to the +grid for a repeat, a next turn and a shared system prompt within the first +eight stripes. One Mac's 64-token-margin cut is on a 256-token grid, so for +some prompt lengths it is 256 tokens deeper than TP's deepest boundary. One Mac +keeps three boundaries a donor: its first, its latest, and the fork target the +coordinator's `cache_repeated_prefix_tokens` hint names. TP gets no hint, so it +keeps the stripe boundaries instead +([parity checks](../developer/test.md#qwen27-tp-warm-prefix-checks)). + +A capture copies the attention rows once, at its deepest boundary, and the +convolution and SSM state at each boundary (`QwenTensorParallelPrefixCapture`). +The shallower boundaries view the deepest copy, and the resident tier counts it +once per capture. Each request's own capture is charged in its reservation, so +a capture always keeps what its charge covers. The resident tier is charged +nowhere ([memory](hardware-support.md#qwen27-tp-batch-prefix-ownership)). Its +byte budget is set at LOAD from the room measured beside the quote +(`QwenStagePrefixCache.budget(roomBytes:)`). Under that budget it gives up other +captures' shallower boundaries first, then the newest capture's, then whole +captures, least recently used first, so an exact repeat's boundary outlives the +rest. A capture whose deepest boundary does not fit the budget is not kept +resident at all (on a 256 GB Mac, an 8 GiB budget holds the 27B's capture to +about 235,000 tokens). Its entries also give way, after the SSD writer's queue +drains, before a reservation or the running batch is refused for memory +(`QwenTensorParallelSnapshotCache.yieldingMemory`). The vote carries every +chunk boundary of the prompt, at most 512, and selects the longest one both +ranks hold; a one-sided miss computes cold on both ranks. Restoration writes +fresh request-owned attention storage and adopts immutable confirmed conv/SSM +state. It never splits the final chunk. The assistant's lanes keep one boundary +of at most 4,096 tokens ([assistant prefix ownership](#qwen27-tp-assistant-prefix-ownership)). Keys bind the loaded agreement, backend, chunk size, prompt prefix and media identity. The native owner completes media preparation before reuse, so cached @@ -1148,14 +1187,17 @@ is the same batch owner one lane wide, with both tiers; other models retain their existing behavior. The SSD tier is described below. Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchPrefixCache.swift` -(`QwenTensorParallelBatchPrefixCache`) and +(`QwenTensorParallelBatchPrefixCache`), +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift`, +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefixSnapshot.swift` +(`QwenTensorParallelPrefixCapture`) and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift` (`open`, `confirmedRetirement`). Tiny fixtures do not qualify full-artifact warm-prefix correctness, media parity, RDMA or useful speed. ### Qwen27 TP assistant prefix ownership -The TP assistant prefix donor binds a compact target attention/recurrent snapshot and the same assistant's trusted prompt history at one confirmed original prompt frontier. Restore creates request-owned mutable state and both ranks negotiate the common usable frontier. The bounded cache publishes donors only after checked retirement and a final cancellation/deadline vote; a failed decoder cannot donate. Captured speculative target windows, pending assistant drafts and queued accepted tokens are not prefix donors. Both resident donor banks and the temporary capture bank remain in the complete quote. +The TP assistant prefix donor binds a compact target attention/recurrent snapshot and the same assistant's trusted prompt history at one confirmed original prompt frontier, at most 4,096 tokens deep (`QwenTensorParallelMTPPrefixBudget.maximumTokens`, policy `qwen-tp-mtp-grid-prefix-4096-v1`). That bound is the assistant's history ledger as well: prefill holds the trusted history unflushed up to the checkpoint frontier, so a deeper frontier would keep a lane's whole prompt history resident, not only a larger capture. A request an assistant lane serves therefore reuses at most 4,096 prompt tokens, less than one Mac reuses for a long prompt: a known gap, not covered by the plain lanes' parity. Restore creates request-owned mutable state and both ranks negotiate the common usable frontier. The bounded cache publishes donors only after checked retirement and a final cancellation/deadline vote; a failed decoder cannot donate. Captured speculative target windows, pending assistant drafts and queued accepted tokens are not prefix donors. Both resident donor banks and the temporary capture bank remain in the complete quote. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefix.swift` (`QwenTensorParallelMTPPrefixState`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift`, and `libs/mlx-swift-lm/Libraries/MLXLLM/Models/Qwen35MTP+PrefixCheckpoint.swift` (`Qwen35InlineMTPAssistant`). Full-artifact warm-prefix numerical and cancellation checks remain separate from tiny ownership fixtures. @@ -1164,24 +1206,33 @@ Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Tensor Both ranks of every Qwen TP row's batch owner (9B, 27B, Qwen3.5/3.6 35B A3B) also keep their prefix snapshots in the pipeline's encrypted SSD tier (`QwenStagePrefixDiskTier`), so a repeated long prompt restores its prefix after both Macs restart. Each rank writes only its -own shard: its heads' attention rows and its recurrent state at the captured -boundary, and for a speculating owner the assistant's trusted history at that -boundary as the record's speculative history. Records are written behind -serving after bilateral clean retirement, and only for a capture the resident -tier accepted, so a restore fits that tier again. The record directory is -named by the plan and shares, the verified artifact, this rank's storage -commitment, both builds and the assistant policy, never by the membership -epoch. A restarted pair finds what the last one kept; a re-split, a reinstall -or another assistant starts a new directory. +own shard: its heads' attention rows to the deepest kept boundary, and its +recurrent state at that boundary and at each kept boundary on the record's grid +(the tier's stride, doubled until at most `maximumGridFrontiers` remain; the +kept stripe boundaries past 4,096 are on it, the margin boundary and the 4,096 +one of a prompt past the first eight stripes generally are not). For a +speculating owner, the record also carries the assistant's trusted history at +its boundary as the record's speculative history. Records are written behind +serving after bilateral clean retirement, for every clean capture, including +one the resident tier's budget does not hold. Until a record is written, the +writer holds that capture's arrays, within the queue's bounds. The record +directory is named by the plan and shares, the verified artifact, this rank's +storage commitment, both builds, the assistant policy and the prefix policy, +never by the membership epoch. A restarted pair finds what the last one kept; +a re-split, a reinstall, another assistant or another prefix policy (the +4,096-token `qwen-tp-batch-grid-prefix-4096-v1` included) starts a new +directory, so no rank offers an older policy's record. The sealed vote counts a boundary held in memory or as a complete SSD record. Each rank restores the agreed boundary from its own tiers, memory first. It checks that an SSD shard adopts into its request geometry before any page is -written, and charges the shard to the resident tier at once. A second sealed -exchange confirms that both ranks restored. Otherwise both prefill from zero, -and a rank that did read its record keeps it resident, so the next offer finds -it in memory. An unreadable or unadoptable record is deleted. The load -agreement carries `qwen-tensor-parallel-prefix-v2`. +written. The resident tier keeps the shard when its budget holds it; otherwise +the shard is restored once, within the request's own charged capture, which +covers its deepest boundary. A second sealed exchange confirms that both ranks +restored. Otherwise both prefill from zero, and a rank that did read its record +keeps it resident when the budget holds it, so the next offer finds it in +memory. An unreadable or unadoptable record is deleted. The load agreement +carries `qwen-tensor-parallel-prefix-v2` and the prefix policy. Attention rows are stored at the pair's checkpoint precision (`balanced` by default): a shard restored from its record has older rows approximate and the @@ -1191,15 +1242,20 @@ the request then differs from a cold one. The load agreement then also carries [cluster SSD prefix record encoding](inference.md#cluster-ssd-prefix-record-encoding). The tier logs `darkbloom-prefix-ssd-v1` lines (`open`, `persist`, `restore`, -`restore-confirmed`, `restore-declined`, `close`); the -`darkbloom-tp-batch-prefix-v1` events are unchanged. Shutdown closes the tier -(queued writes finish, bounded) before the model is released. +`restore-confirmed`, `restore-declined`, `restore-unkept`, `close`); the +`darkbloom-tp-batch-prefix-v1` events are unchanged (`stored` names the +deepest boundary the resident tier kept, 0 for none). LOAD logs +`darkbloom-prefix-v1 rank= family=qwen mode=tensor_parallel enabled= +policy= budget_bytes= capture_charge= +room_bytes= ssd=`. Shutdown closes the tier (queued writes +finish, bounded) before the model is released. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelPrefixDisk.swift`, `QwenTensorParallelNativeBatchExecutor.swift` (`agreePrefix`, `confirmedRetirement`) and `QwenTensorParallelResidentRuntime.swift` (load and shutdown) in the same directory. -Tests: `QwenTensorParallelBatchSessionTests` (`ssd…AfterTheTiersReopen`) and -`QwenTensorParallelMTPSessionTests` (the SSD round trip onto a newly loaded head). +Tests: `QwenTensorParallelBatchSessionTests` (`ssd…AfterTheTiersReopen`), +`QwenTensorParallelMTPSessionTests` (the SSD round trip onto a newly loaded head) +and `QwenTensorParallelBatchPrefixTests` (`recordsOfAnotherPolicyAreNeverOffered`). ### GLM TP prefix SSD tier @@ -1260,3 +1316,57 @@ native records; `GLM53_PREFIX_SSD=1` on the serving-width synthetic stage, also through a balanced record) and `GLM5NextTensorParallelPrefixRecordEncodingTests` (a balanced record encodes only the DSA latents and adopts). + +### Gemma TP prompt prefixes + +Both ranks of Gemma 4 tensor parallel keep their prompt prefixes as the Gemma +pipeline keeps a stage's: in the same memory tier (`QwenStagePrefixCache`) and +the same encrypted SSD tier (`QwenStagePrefixDiskTier`), each rank only its own +KV heads of every layer (4 sliding, 1 full on the 26B). Code: +`libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift` +(`Gemma4TensorParallelPrefix`, `Gemma4TensorParallelPrefixCapture`). + +| Step | What happens | +|---|---| +| Capture | During the prompt, after each chunk that ends on the cache's stride grid strictly before the prompt end (the [chunk-grid rule](#gemma-chunk-grid-reuse)), the rank copies each sliding layer's window, and at the deepest such boundary its full-attention rows; a capture keeps the deepest boundary first, then the deepest grid boundaries its limit holds (`QwenStagePrefixCaptureCost.kept`). The record shape is the pipeline stage's: full rows as attention entries, each window in the recurrent slots. | +| Keep | Only after the request ended on both ranks: a solo request after the end-of-request exchange and its pages' release, a lane after the batch driver's bilateral retirement (`confirmedRetirement`). Its boundaries become resident and are written to the SSD tier behind serving. A failed request keeps nothing, and the rank drops every entry (its peer may hold others). | +| Scope | Resident: the load agreement and the request's chunk grid; on SSD: `Gemma4TensorParallelPrefix.planScope` (the plan and its arithmetic terms, the prompt policy, the arithmetic receipt and profile, the verified artifact and storage commitment, both builds; never the membership epoch) and the request's chunk grid; both in the request's [tenant partition](#cluster-prefix-tenant-partitions) (`Gemma4TensorParallelPrefix.scopes`). | +| Vote | One sealed sum of every stride-grid boundary before the prompt's final token: each rank offers 1 for a boundary in memory and 3 for one held only as a complete SSD record (`QwenTensorParallelPrefixCache.offer`); the deepest boundary both offer (a sum of 2, 4 or 6) is agreed. A request whose cache is off, or whose prompt is shorter than one stride, votes on neither rank. | +| Restore | Each rank reads the agreed boundary from its own tiers, memory first, checks it adopts into its geometry (`Gemma4TensorParallelPrefix.adopts`), and writes it into fresh pages of a new request, reserved for its first tokens as a cold request's are (`CBv2OwnedRequestState` sliding adoption). Then a second sealed sum (`QwenTensorParallelPrefixCache.confirm`) shows both ranks restored; otherwise both discard what they restored and prefill from zero. An unreadable record is deleted by the tier, one that does not adopt by the rank; a state read from SSD stays resident either way. | + +A restore continues the prompt from the boundary on the same chunk grid, so its +frames are the cold request's frames from there: the restored rows, windows and +position offsets equal the cold request's at the boundary, and its logits and +tokens equal the cold request's bit for bit. Gemma records are native +(`QwenStagePrefixDiskFamily.native`), so an SSD restore is exact too. The load +agreement carries `gemma4-tensor-parallel-prefix-v1` `on`; a rank whose +`DARKBLOOM_CLUSTER_PREFIX_CACHE=off` loads `off` and its peer refuses it. + +Memory: each request's charge includes its own prompt's capture at its deepest +boundary (none when its cache is off), and the LOAD quote the capture of the +profile's longest prompt +([rank memory](hardware-support.md#gemma-4-tensor-parallel-rank-memory)). The +memory tier is charged nowhere: as the pipeline's, its budget is half the room +the load measures beside the shard and that quote +(`QwenStagePrefixCache.budget(roomBytes:)`), so it never exceeds that room. A +request captures what its charge covers whatever the tier's budget +(`Gemma4TensorParallelPrefix.captureLimit`): a tier the measured room leaves +without budget keeps nothing resident, and the capture still reaches the SSD +tier. A capture beyond its charged part (the pipeline's limit) is asked of the +live gate and cut to that part when refused. Kept entries give way before a +reservation, a lane or a running request is refused for memory, and a request +served alone then lets its own capture go, as the pipeline's does; under host +pressure an idle rank drops them (`releaseIdleMemory`). The SSD tier's +configuration, key, owner-only directories, TTL, daily write cap, free-space +floor and bounded close are every cluster family's +(`QwenStagePrefixDiskConfiguration`). + +Logs: `darkbloom-prefix-v1 … family=gemma4 mode=tensor_parallel` at load +(`budget_bytes=`, `capture_charge=`, `room_bytes=`, `ssd=`), at each agreed boundary +(`agreed=`, `reused=`, `tier=`) and at each keep (`stored=`); the tier's +`darkbloom-prefix-ssd-v1` lines and `restore-declined`. Tests: +`Gemma4TensorParallelPrefixTests` (restore against cold bit for bit, the +state at and after the boundary, hits and misses on both ranks, the request +loop and lanes, budget and eviction, the SSD round trip, refused records and +the cache rules) and the paged oracle matrix's `--prefix repeat` runs +([focused checks](../developer/test.md#focused-gemma-4-tensor-parallel-checks)). diff --git a/docs/architecture/security/provider-trust.md b/docs/architecture/security/provider-trust.md index 78b40333a8..7a10efa310 100644 --- a/docs/architecture/security/provider-trust.md +++ b/docs/architecture/security/provider-trust.md @@ -1,6 +1,6 @@ # Provider trust during MDM and App Attest coexistence -> Last updated: 2026-10-13 +> Last updated: 2026-11-01 Darkbloom supports two independent provider authorization paths: legacy MDM/APNs verification and qualified App Attest. A connection can satisfy either or both. This explanation separates those paths from their shared dispatch checks and from claims neither path proves. The [authorization reference](../../reference/provider-authorization.md) owns configuration, deadlines and migration procedures. @@ -123,6 +123,8 @@ and [coordinator/registry/autopilot_reward_snapshot.go](https://github.com/Layr- Platform security, signed-artifact qualification and physical SIP/boot transitions need adversarial evidence on supported hardware. Synthetic tests establish code behavior, not resistance to every host compromise. Legacy trust-reuse timing premises likewise remain qualification assumptions. The [encryption explanation](encryption.md) owns the plaintext and key-lifetime model; attestation does not alter it. +`verifyBundleSignature` (`SecurityHardening.swift`) waits for `codesign`, and `DarkbloomMDMRemoval.readProfiles` waits for `profiles`, with no time limit, so a stuck child holds up that check or removal. The exit comes from `ProcessExitObserver`, which does not run the calling thread's run loop. + ## Code map | Concern | Entry points | diff --git a/docs/developer/build.md b/docs/developer/build.md index 8e38344a2a..52f3ae2687 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build The Provider And Landing -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 Build the provider, its source-matched native resources, and the independent landing site from this repository. Backend, sidecar, console and admin builds @@ -35,6 +35,12 @@ an arbitrary prebuilt metallib or infer GPU qualification from compilation. Keep separate worktrees/output directories for independent native builds; never share an active Swift scratch path or another suite's GPU reservation. +After changing provider authorization summaries, rebuild the provider test +product before running the [authorization guidance tests](test.md#provider-authorization-guidance). +They exercise shared production decisions without invoking status/doctor's +host probes or native Apple operations; signed-release qualification remains +separate. + ## Cluster metadata check builds The worker capability and worker startup-argument checks link the actual @@ -183,6 +189,12 @@ On the `dev` branch a plain `swift build` is a DevNet build: `prod`. Set `DARKBLOOM_RELEASE_ENVIRONMENT=prod` to build a production binary from the `dev` branch. +CI enforces both defaults. The Release Integrity job runs +`scripts/provider-build-default.py`: a pull request into master, or a push to +master, fails unless the default is `prod`; one into or to `dev` fails unless +it is `dev`. Every release of master runs the same check and stops before the +build if the default is not `prod`. + Use the `dev` branch to run a provider from source against the DevNet coordinator. A push to `dev` that changes the provider publishes the DevNet release through `.github/workflows/release-dev-branch.yml` @@ -237,13 +249,11 @@ see [resource and release tooling checks](test.md#focused-tooling-checks). Darkbloom Sandbox when its plane grants one, otherwise the job's Blacksmith fallback. It runs on GitHub-hosted `ubuntu-24.04` with no token permissions or checkout. Each routed job runs on `fromJSON(needs.route.outputs.routes)['']`, -where the lane is the job's name; each provider shard reads its own lane, -`format('test-provider-{0}', matrix.shard)`. +where the lane is the job's name. | Workflow | Routed jobs | Fallback | |---|---|---| | `ci.yml` | `release-integrity`, `docs` | `blacksmith-4vcpu-ubuntu-2404` | -| `ci.yml` | `test-provider` (lanes `test-provider-1` to `test-provider-5`, one per shard), `test-provider-summary`, `test-provider-sdk`, `test-cluster-checks` | `blacksmith-12vcpu-macos-27` | | `docs-impact.yml` | `commit-signatures`, `docs-impact` | `blacksmith-4vcpu-ubuntu-2404` | | `landing.yml`, `desktop.yml`, `nightly-linear-package.yml` | `check`, `frontend`, `test` | `blacksmith-4vcpu-ubuntu-2404` | | `provider-release-cache.yml` | `warm`, pull requests only | `blacksmith-12vcpu-macos-27` | @@ -256,14 +266,20 @@ fallback and the plane is not contacted. When it is on, the route job sends one most once after a transient failure. It uses a grant only when the grant repeats the exact Darkbloom labels for the job's profile. Errors, timeouts and malformed replies keep the fallback; the plane never fails the route job. -Every job of a lane shares one `runs-on` value, so the plane grants a lane -whole, for its requested job count, or not at all. Each provider shard is -therefore a lane of its own and runs on a Darkbloom Mac whenever one is free, -independently of the other shards. -Release, signing, publication, model registration, review automation, -`cache-swift` and `master` or dispatched cache warming keep literal Blacksmith -labels. The component classifier and the `Provider Tests` gate run on -`ubuntu-24.04`. +Release, signing, publication, model registration, review automation and +`master` or dispatched cache warming keep literal Blacksmith labels. The +component classifier and the `Provider Tests` gate run on `ubuntu-24.04`. + +The macOS jobs of `ci.yml` (`test-provider`, `test-provider-summary`, +`test-provider-sdk`, `test-cluster-checks`, `test-cluster`, `test-cluster-gpu` +and `test-cluster-focused`) are not routed. They always run on +`blacksmith-12vcpu-macos-27`. In 43 provider shard jobs on Darkbloom macOS +sandboxes (2026-10-31 to 11-02), the median job took 17.3 min against 9.8 min +on Blacksmith (362 jobs). The depth-1 checkout took 146 s at the median and up +to 22 min, against 13 s on Blacksmith. The sandboxes found almost no build +cache. Saving the cache took about 150 s. Five jobs stopped in checkout until +the 60-minute job timeout. `scripts/test-darkbloom-route.py` checks that these +jobs keep the literal label. Jobs on Darkbloom Sandboxes use GitHub's Actions cache, not Blacksmith's colocated cache, so their first runs start without cached build products. diff --git a/docs/developer/test.md b/docs/developer/test.md index 432df184bf..5fb42f11ac 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -25,7 +25,12 @@ not native model capabilities, numerical parity or hardware qualification. The placement checks also cover exact family request scopes, completion-heavy and long-prompt helper plans, overflow refusal, conservative memory refusal and -unchanged GLM adapter bounds. Run `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` +unchanged GLM adapter bounds. `GemmaRoutedExpertChecks.swift` builds the Gemma +QAT 4-bit layout from the retained real headers in +`libs/darkbloom-cluster/Tests/StageMetadataChecks/Inputs`, requires it to equal +its golden layout with `routedExperts` included, and requires the per-token +read of the [routed-expert prior](../architecture/inference.md#gemma-routed-expert-prior). +Run `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` and `provider-swift/Tests/ClusterPlacementChecks/run.sh`; then run `provider-swift/Tests/ClusterPlacementChecks/run-flow.sh` for the real child-process provider path with a fake installed helper. These checks use recorded metadata @@ -74,6 +79,18 @@ Build the relevant test products and stage matching metallibs before any `--skip-build` command below. Run provider commands from `provider-swift/` and SDK commands from `libs/mlx-swift-lm/` unless a command specifies otherwise. +## Provider authorization guidance + +After rebuilding the provider test product, run +`swift test --skip-build --no-parallel --filter ProviderAuthorizationReadinessTests` +from `provider-swift/`. The suite exercises the production freshness checks and +summary used by status and both doctor paths: a late but unexpired serving lease +stays visible while removal advice requires the matching fresh decision. It +covers the receipt-window boundary, disabled rollout, missing or mismatched +decisions and exact lease expiry. These checks use fixed snapshots and injected +process identity; they do not run the CLI's host probes, change profiles or +establish native App Attest acceptance. + ## Provider Terminal And Stop Signals After rebuilding the provider test products, run the focused @@ -95,10 +112,8 @@ snapshots. Preserve its watchdog, cleanup and state isolation when using a focus selector. Use `scripts/run-nested-suite.sh` for documented nested Swift Testing cases and `scripts/run-exclusive-native-gpu-test.sh` for exclusive native work. -CI runs the provider suite in five shards (`Provider Unit Tests (shard K)`), one -Mac each, each routed through its own lane `test-provider-K` -([CI runner routing](build.md#ci-runner-routing)). -`PROVIDER_TEST_SHARD=K/N` selects a shard in `scripts/run-provider-tests.sh`, +CI runs the provider suite in three shards (`Provider Unit Tests (shard K)`), one +Mac each. `PROVIDER_TEST_SHARD=K/N` selects a shard in `scripts/run-provider-tests.sh`, and `scripts/provider-test-shards.py` chooses its suites: | Class | Process | Suites | @@ -115,10 +130,21 @@ native MiMo, desktop and installer gates. `Provider Unit Tests Summary` lists th the shards together executed the full list, checks that each Prompt Parity run executed every listed test of its suite, merges the shards' coverage profiles and uploads measured seconds per suite (`provider-test-shard-weights`). -When the shards drift apart, replace the weights file with that artifact. A +When the shards drift apart, replace the weights file with that artifact. +The suites in `KEPT_APART` never share a shard: a process that ran +`NemotronSuperManagedSlotTests` and then `Qwen4PagingPrefixIntegrationTests` +crashed with SIGBUS, and each passes alone. The pair stays apart until the +Nemotron fixture cleanup is fixed. A suite moves from the parallel class to the serial class when it fails or flakes in parallel; when in doubt, a suite stays serial. +The jobs that use the `provider-ci-build` action and Cluster Metadata Checks +restore their build cache by the exact key first, then by the key prefix. A +push to `dev`, `main` or `master` saves its build. A pull request saves its build only when it restored nothing. +Its later pushes then restore that entry or the base branch's entry and add no +new entry, so they do not evict the base branch's entries. CI has no separate +push-only Swift cache job. + The SDK has independent test products under `libs/mlx-swift-lm`. CI validates native memory ownership, cancellation, media decoding, paged KV and resource packaging there as well as provider behavior. `Provider SDK Tests` is not part @@ -518,7 +544,10 @@ platform parity. Ordinary fixtures use symmetric 128-context geometry; the separate complete-prefix process uses `--asymmetric` for K64/V128 and 1,024-context geometry. `scripts/prepare-mimo-audio-fixtures.py` prepares hash-pinned public inputs -including the genuine audio codec. Keep these output directories isolated from +including the genuine audio codec. The script downloads only the files that its +cache directory lacks. It retries a failed download up to 5 times and ends an +attempt that stays below 100 KB/s for 60 s. It keeps a file only when the size +and SHA-256 match. Keep these output directories isolated from the ordinary regression inputs. Audio gates exercise PCM8 and AAC-video with a small target, not full-model quality or peak memory. Release-only builds do not provision test fixtures or opt into native qualification. @@ -526,9 +555,13 @@ provision test fixtures or opt into native qualification. ## Prompt Preparation And Admission ```bash -swift test --skip-build --filter 'PromptTokenCacheTests|ChatTemplateLoopRewritesTests|InboundChatRequestDecodeTests|ServeLoopColdLoadTests' +swift test --skip-build --filter 'LocalTokenizerDecodeSpacingTests|PromptTokenCacheTests|ChatTemplateLoopRewritesTests|InboundChatRequestDecodeTests|ServeLoopColdLoadTests' ``` +`LocalTokenizerDecodeSpacingTests` requires a tokenizer whose config omits +`clean_up_tokenization_spaces` (Gemma 4's published config does) to decode and +stream text exactly, with the same input IDs and an explicit Boolean kept. + `PromptTokenCacheTests` loads synthetic tokenizers through the production `LocalTokenizerLoader` for the Qwen split, GPT-2 byte-level and Gemma metaspace pre-tokenizer families, with no download, and requires piecewise, cached and @@ -551,6 +584,17 @@ first, and a request for the loading model when a second copy would not fit. and the body decode on the CPU with only the tokenizer loaded and the background comparisons off; it exits 2 if any token ID or decoded field differs. +```bash +swift test --skip-build --filter 'LocalTokenizerByteFallbackTests' +``` + +`LocalTokenizerByteFallbackTests` loads a synthetic tokenizer with Gemma 4's decoder +sequence through the production `LocalTokenizerLoader` and requires characters +written as `<0xHH>` tokens to survive a whole decode, a stream, a segment restart +inside the run and a trailing special token, a run cut inside a character to end in +one U+FFFD, and the unknown token not to read as a byte. A literal `<0x41>` token on +another decoder keeps its spelling. + ## Desktop Control And Frontend `make desktop-test` exercises the frontend journeys and bridge validation. @@ -1043,6 +1087,62 @@ timeout, one-time failure accounting and heartbeat promotion. It does not run native launchd, the controller cancellation interleaving or a signed release installation. +## Cluster Pair Coordinated Update + +`ClusterPairUpdateTests` +(`provider-swift/Tests/ProviderCoreTests/Update/ClusterPairUpdateTests.swift`) +runs two Macs' `ClusterPairUpdateCycle` in one process: each with the real +updater on its own temporary install, a loopback `MockCoordinator` serving the +release, and a real member loop as its part (a scripted pair owner holds rank 0's +request). It checks that a busy pair stages while serving, closes admission only +once both Macs staged, finishes the accepted request uncancelled and then +installs on both; that a request past the drain bound reopens admission and +defers both Macs, and the next cycle updates; that one Mac's failed download +stops both and the next cycle updates both; that a Mac whose partner has +automatic updates off downloads nothing at the slot, while `darkbloom update` on +both Macs updates them; that a part that cannot drain downloads nothing; that a +Mac whose partner cannot be asked goes on alone only while no pair runs on it; +the candidate's promotion (kept under another update's lease) and rollback; +the start check's verdicts on script binaries; the rollback at once of a +candidate that failed its start check; and the other Mac following a rollback +(`followRollback`): after it promoted the release, while its own cycle still +holds the update lease (it waits, then follows), with the other Mac no longer +answering (bounded wait, then a deferral with nothing changed), and the +quarantine on both Macs, with no follow back and no follow to a release the Mac +does not keep; and what is decided before the lease (the Mac that rolled back +names the release the other Mac still runs, a part that cannot drain does not +follow yet, a Mac on another release does not ask for the lease). +`Tests/ClusterSupervisionChecks/run.sh` also checks that a release the other Mac +quarantined is given up, and that an older build's progress decodes without a +quarantine. +`ClusterServiceUpdateTests` +(`provider-swift/Tests/DarkbloomCLITests/ClusterServiceUpdateTests.swift`) drives +the real supervisor with a shell standing in for the cluster service: the +single-Mac gate, a slot fired from a cluster ID whose slot is seconds away, no +slot cycle with automatic updates off (and `disabled` reported again once a +cycle's end is a minute old), `darkbloom update`'s request and the candidate's +rollback and promotion. The start check runs the temporary install's +`darkbloom`, a script: a release whose `--version` exits non-zero, outlasts a +1 s bound or reports another version is rolled back and quarantined without the +re-exec, and the supervisor serves again from the restored binary; a release +that answers is re-executed into as before; a restored predecessor that cannot +start is not re-executed into. A supervisor with automatic updates off still +checks for a rollback of the other Mac to follow, reports its own quarantine in +its progress, and restarts into the restored release. The re-exec is observed, +never performed. +`Tests/ClusterSupervisionChecks/run.sh` checks the progress rules +(`ClusterPairUpdate.partnerState`) with plain `swiftc`. + +```bash +CFFIXED_USER_HOME="$(mktemp -d)" swift test --skip-build --no-parallel \ + --filter 'ClusterPairUpdateTests|ClusterServiceUpdateTests' +``` + +Keep `CFFIXED_USER_HOME` (or an isolated user) on a Mac that serves: the member +loops and supervisors otherwise use the real `~/.darkbloom` for their cluster +files. These checks use loopback and temporary roots only; they do not run a +pair, launchd, a signed release or the coordinator's routing of a draining pair. + ## Public Fixtures And Private Qualification Public protocol JSON and prompt golden vectors contain fixed inputs and expected @@ -1099,13 +1199,16 @@ with isolated fixture runners: each `provider-swift/Tests/Cluster*Checks/run.sh` `libs/darkbloom-cluster/Tests/*Checks/run.sh` and `libs/darkbloom-cluster-worker/Tests/*Checks/run.sh` prints its pass count and exits non-zero on a failure. The CI job `test-cluster-checks` (Cluster Metadata -Checks, `.github/workflows/ci.yml`) runs five of them on every pull request that -changes provider code: `libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh`, +Checks, `.github/workflows/ci.yml`) runs these runners when the classifier +selects `cluster` (see below): `libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh`, +`libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh`, `libs/darkbloom-cluster/Tests/StageMetadataChecks/run.py`, `libs/darkbloom-cluster/Tests/GPTOSSStageChecks/run.sh`, `libs/darkbloom-cluster/Tests/NemotronStageChecks/run.sh` and `provider-swift/Tests/ClusterModelProvisioningChecks/run.sh provisioning`. The -last one runs the provisioning checks only. Its download cache-policy check +job `test-cluster-focused` (Cluster Focused Checks) runs every other runner +under `libs/darkbloom-cluster/Tests`. The provisioning runner runs the +provisioning checks only. Its download cache-policy check reads how many written pages stay in the file cache, which the host's kernel and disk decide: on the hosted CI VM 0.75 of the pages written with `F_NOCACHE` stayed resident. Run `run.sh` with no argument on a Mac for that @@ -1113,10 +1216,40 @@ check. The capability runner compiles with `DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS` jobs (4 by default; CI uses 12). CI keeps its build in `DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT` between runs and restores source timestamps only for unchanged files, so SwiftPM rebuilds only -what changed. The library's XCTest targets -(`swift test --package-path libs/darkbloom-cluster`) and the worker package's -tests (built for macOS 26.2) need the GPU and exclusive device access. A -loopback or fixture pass never counts as a two-Mac hardware pass. +what changed. The worker package's tests (built for macOS 26.2) need the GPU +and exclusive device access. A loopback or fixture pass never counts as a +two-Mac hardware pass. + +The cluster jobs (Cluster Metadata Checks, Cluster Runtime Tests, Cluster GPU +Tests and Cluster Focused Checks) run when the classifier selects `cluster` +(`CLUSTER` in `scripts/ci-component-paths.py`): the cluster packages, the MLX +pins, the provider's Cluster, Distributed and NativePair sources, the +provider-side cluster runners (`provider-swift/Tests/Cluster*Checks`), the +other provider files the cluster runners compile, the cluster plan and the +shared build recipe. A push that runs the provider lanes also runs them. The +`Provider Tests` gate accepts a skipped cluster job only when `cluster` was not +selected. A provider-only pull request runs 4 Macs (3 provider shards and the +summary), or 5 when an SDK-lane input changes. A cluster pull request adds 7 +Macs (metadata checks, 3 runtime shards, 2 GPU shards and focused checks). + +CI runs the runtime test target (`DarkbloomClusterRuntimeTests`) on the +provider's Blacksmith macOS runners, in selections that +`scripts/cluster-test-plan.py` defines. Each selection runs in a process of its +own through `scripts/run-nested-suite.sh`, which fails when the selection runs +no test or skips a test. Every process starts with `MLX_QMV_BATCH_INVARIANT=1`, +as every cluster process does. + +| Selection | Job | Tests | +|---|---|---| +| Base | Cluster Runtime Tests (blocking) | Every test that needs no environment switch. The base selections pass `--skip` for the switched tests and the tests that need a model, so a test that skips there has a gate that the plan does not name | +| Opt-in | Cluster Runtime Tests (blocking) | The tests that one switch (for example `QWEN_TP_MTP_GPU=1`) enables and that pass on the CI runners | +| Opt-in | Cluster GPU Tests (non-blocking) | The switched tests that fail on the CI runners' GPU, the long-running tests and the benchmarks. The job reports their results and does not fail the workflow | +| Needs a model | None | The tests that need a model directory, an artifact or its metadata (`REQUIRES_MODEL`). CI has no model | + +`python3 scripts/test-cluster-test-plan.py` (Release Integrity) checks that the +plan names each gated test in the sources once, and each runner under +`libs/darkbloom-cluster/Tests` once. When you add an environment gate to a +runtime test, add the test to a selection or to `REQUIRES_MODEL`. Build the runtime tests once (`swift build --package-path libs/darkbloom-cluster -c release --build-tests --triple arm64-apple-macosx26.2 -Xcc -target -Xcc @@ -1125,7 +1258,7 @@ arm64-apple-macosx26.2 -Xswiftc -enable-testing`), stage the source-matched with the same flags plus `--skip-build --no-parallel`. Without environment switches the run evaluates synthetic models on the GPU by default; the GPU-only cases (`QWEN_TP_BATCH_GPU=1`, `QWEN_TP_MTP_GPU=1`, `QWEN_TP_MOE_GPU=1`, -`QWEN_TP_AQV_GPU=1`) run each in a process of their own with their filter. On +`QWEN_TP_AQV_GPU=1`, `QWEN_TP_REAL_GEOMETRY_GPU=1`) run each in a process of their own with their filter. On an M5 GPU MLX computes float32 matrix products in TF32 unless the process starts with `MLX_ENABLE_TF32=0` (`libs/mlx-swift-lm/CONTRIBUTING.md`): the forward comparison in `GLM5NextStageSessionTests` asserts a float32 tolerance @@ -1229,6 +1362,299 @@ not load a model or qualify its output. Sources: The [routed-expert TP architecture](../architecture/inference.md#qwen35-routed-expert-tensor-parallel) states the arithmetic descriptor and supported scope. +## Focused Gemma 4 tensor-parallel checks + +These checks use synthetic weights on one Mac, over loopback only. They prove +neither real-weight numerics, a pair qualification nor speed. + +1. Run the model-free plan check (no MLX; it compiles in seconds) and the CPU + unit tests: + + ```bash + bash libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/gemma-run.sh + swift test --package-path libs/darkbloom-cluster --filter Gemma4TensorParallelTests + swift test --package-path libs/darkbloom-cluster --filter Gemma4TensorParallelRuntimeTests + ``` + + The plan check covers both registered artifacts' text tensors once per rank + and matches their registered text bytes. The `Gemma4TensorParallelRuntimeTests` + suite needs the GPU: put a source-matched `mlx.metallib` in the package's + debug products directory (the one `swift build --package-path libs/darkbloom-cluster --show-bin-path` + prints), not in the `.xctest` bundle. It covers the resident runtime's pieces: + + - each rank's paged request state: its own KV heads of every layer; + - two in-process ranks on the paged request path, bit for bit equal, with + the whole model's tokens and exactly two collectives a layer and one a step; + - layer submission, which keeps every bit; + - batch lanes (one joining late): every row equals its request's solo row, + bit for bit, and the shared batch driver with the Gemma executor + publishes each request's solo tokens; + - the request loop on two ranks: a stop token, the owner's stop (also one + just before a stop token) and one rank's own stop end both ranks after + the same step, with logprobs; + - the share probe, timed on one rank with every sum local; + - each step's choice: greedy with both stop flags, sampled from the gathered + row exactly as the product's sampler draws, and greedy logprobs from the + split top-k, also at an exactly tied maximum whose other ID leads the gather; + - the verified load's cut of every text tensor, and its refusals; + - the load agreement's fields; + - what the capability declares of each mode (`ClusterServingFeatures`): + tensor parallel's prompt-prefix setting is the one its load agreement binds; + - the product's Gemma layout with its tensor-parallel facts: big Macs keep + the pipeline on default link costs; on a measured fast link tensor + parallel is predicted faster on the device index alone and the pipeline is + kept, until each rank's share probe lets it be chosen; the forced mode + places it; and each rank is charged its own heads. + + `swift test --package-path libs/darkbloom-cluster --filter Gemma4TensorParallelPrefixTests` + (GPU, as above) covers the prompt-prefix tiers on two in-process ranks: + + - a repeated prompt, and a longer one sharing it, restores the deepest + boundary both ranks hold and equals the cold request bit for bit; + - the restored rows, windows and position offsets equal the cold request's + at the boundary and after the next chunk; + - a boundary only one rank holds, or one rank cannot restore, another chunk + grid and a request whose cache is off all prefill from zero on both ranks; + - the request loop (greedy and sampled) and batch lanes through the driver + continue a restored prefix with the cold tokens; + - the memory tier's budget and eviction, and a capture within its limit; + - a request's own capture charged in its budget and the LOAD quote, no + charge for the memory tier, whose budget stays within the measured room; + with no tier budget a request still captures within its charge and a + repeat restores from the SSD tier; + - the SSD tier: records restore bit for bit after both tiers reopen, + encrypted and owner-only; stale, corrupted and other-key records are + refused on both ranks; no directory or key is no tier, and the daily write + cap, the free-space floor and the bounded close hold. + + `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` also runs + `GemmaTensorParallelChecks.swift` (model-free). It builds the QAT 4-bit + layout from the retained real headers and the 8-bit layouts from their + derived shapes, and requires each to equal its golden layout, tensor-parallel + facts included. A rank's share must be the plan's exact cut (8,040,450,108 and + 14,915,635,260 bytes), and the rank's reserve (`Gemma4TensorParallelRequestBudget`) + must be quoted. Under the provider's tensor-parallel-first policy it checks the + fastest-plan rule on constructed pairs: 2x M5 Ultra 256 GB keeps the pipeline on + default link costs. Where tensor parallel is predicted faster on the device + index alone (2x M4 Pro 24 or 32 GB, each rank quoted with its request's + prompt-prefix capture, and 2x M5 Ultra for a 128 + 128 request on the + measured 29 us link), the pipeline is kept with the verdict + `predictedFasterOnPriorOnly`, its plan line and model-list note. Share probes + of the model on both Macs (through `ClusterShareProbeHistory`) and requests + served in tensor parallel (through `ClusterServedCalibration`) then decide + both ways. A probe on one Mac or of another model is no evidence. A kept mode + still applies, the forced mode still places tensor parallel, and the same + layout without its choice still takes tensor parallel on the prior. + + The `Gemma4TensorParallelTests` suite covers: + + - the plan against the registered QAT 4-bit artifact's 1,697 header shapes + (`Tests/StageMetadataChecks/Inputs`), and the 8-bit artifact's derived shapes + and registered text bytes; + - refusals of unknown, misaligned and vision tensors; + - shard parameters against independent slices; + - two in-process ranks against the split-sum oracle, bit for bit; + - the packed feed-forward collective against separate collectives, also + under the registered prompt policy and the scoped batch decode; + - the vocabulary-split head against the whole head. + +2. Build `darkbloom-cluster-tp-check` and put a source-matched `mlx.metallib` + beside it ([build](build.md)). Then run the GPU oracles: + + ```bash + bash libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh \ + /path/to/darkbloom-cluster-tp-check /new/scratch/dir 58123 + bash libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh \ + /path/to/darkbloom-cluster-tp-check /another/new/dir 58125 paged + ``` + + The script synthesizes five variants: 4- and 8-bit, routed and all-expert, + and FP32. For each, it runs `full`, `split-sum`, `simulated` and two `tp` + ranks over the sealed local ring on the given port and the next one. With + `paged` as the fourth argument, every mode but `split-sum` runs the + resident runtime's own request path: paged KV, the product's CBv2 prompt + entry, and each step's choice in its own evaluation. The paged path also + runs `gemma lanes`: three requests served together through the batch + driver, in one process and over the ring, each of which must take its solo + tokens. And it runs `gemma run --prefix repeat` in `simulated` and on both + `tp` ranks: the request served twice through each rank's prompt-prefix tier, + the repeat restoring the deepest boundary both ranks hold. + +3. Verify. Each `tp` rank must equal `simulated` bit for bit (exit status 0). + Each repeated-prefix run must have restored a prefix and equal its cold run + bit for bit, and each `tp` rank's repeat must equal `simulated`'s. + The script also prints QualificationComparator's verdict for each rank + against `full`. + +## Focused MiMo V2.6 tensor-parallel checks + +These checks use synthetic weights on one Mac, over loopback only. They prove +neither real-weight numerics, a pair qualification nor speed. Never load the +registered artifact for them. + +1. Run the unit tests. The FP32-partial suite runs on the GPU, so stage the + source-matched `mlx.metallib` in the test bundle first + (`scripts/stage-test-metallib.sh`): + + ```bash + swift test --package-path libs/darkbloom-cluster --filter MiMoTensorParallel + ``` + + They cover: + + - the plan against the registered 1,732-tensor inventory and configuration + (`darkbloom-cluster-worker/Tests/CapabilityChecks/Fixtures`), per-rank + bytes and the SDK shard's agreement on every cut axis; + - refusals of renamed, foreign, excluded and odd-shaped tensors; + - the shard configuration and per-rank KV geometry; + - shard cuts and byte runs against independent slices; + - two in-process ranks against each other and the whole model; + - FP32 partials (`MiMoTensorParallelFloat32PartialTests`, on the GPU): two + ranks' expert rows add up bit for bit to the exact full-width row that + one Mac rounds once, through the decode-expert kernel and MLX's sorted + gather; every partial a rank sums is FP32, and no `o_proj` or dense + partial was rounded to BF16 first; the contract v2 strings are pinned; a + speculative round's verify window (every width from 2 to 4 rows, after a + prompt that wrapped the sliding ring) hands each sum the one-token steps' + own FP32 partials, row for row and bit for bit, with logits to match + (`windowPartialsAreTheOneTokenStepsFloat32Partials`); + - the vocabulary-split head against the whole head; + - the resident runtime's verified load: each rank reads exactly its shard's + bytes, and a tampered or foreign checkpoint is refused; + - its paged requests: ranks agree bit for bit and equal the ordinary caches, + with per-rank paged geometry, the selection rules, logprobs (an exactly + tied maximum included), every stop kind (the owner's stop just before a + stop token included), the request and load agreements, the request budget + and the text-only launch; + - speculative rounds (`MiMoTensorParallelSpeculativeTests`, a checkpoint with + three random trained heads): rounds of the heads' own proposals and of + proposals scripted from the one-token path's tokens (every one kept, or + every third moved off) equal the one-token path bit for bit, caches + included; a stop token inside a window, the owner's stop inside a round + (and just before a stop token of the same round), a cancel between rounds + and greedy logprobs for every kept column (the one-token path's own) end + both ranks together; the LOAD gate's configuration-only drafter charge is + what the loaded heads declare; a window's rollback + (`MiMoV26VerifyWindow.settle`) leaves exactly the cache of one-token + appends on the registered 128-row ring (two 64-token pages, across its + page boundary and wrap) and on a full layer; exactly tied columns and + draft readouts choose the lowest token ID; the window contract + (`windows=row-exact-one-token-float32-partials-v2`) is in the agreement; and + the product layout quotes what the LOAD gate charges with rounds on by + default: the heads (42 tensors, 1,975,640,448 bytes, equal to the LOAD + gate's head inventory over the same headers) and each request's + speculative charge beside the reserve, no speed-up credited + (`placementQuotesWhatTheLoadGateChargesWithRounds`); + - what the text row's capability declares of each mode (`ClusterServingFeatures`): + tensor parallel decodes in rounds at `ClusterMiMoTensorParallel.speculativeDepth`, + so it drops nothing of the speculative or compact-decode pipeline and only + the plain pipeline's batch lanes. + + `libs/darkbloom-cluster/Tests/PlacementChecks/run.sh` also runs + `MiMoTensorParallelChecks.swift` (model-free). It builds the layout from the + registered configuration and inventory and requires its tensor-parallel + facts (97 sums a step, `fastest_v1`), a rank's share of exactly + 84,013,770,176 bytes, the routing prior (10,767,036,288 bytes a step), no + facts for the image candidate, the same facts in the golden layout, and the + rank's reserve (`MiMoTensorParallelRequestBudget`) in the quote. With the + rounds on by default, it prices them as the product layout does (the SDK's + drafter declaration stands in at its registered 438,426,984 bytes plus the + window's 36,347,904): each rank holds the 42 head tensors whole in whole pages, + its request need carries the speculative charge, its need is exactly the + rank's LOAD gate plus its tensors' page padding, decode is credited nothing, + and two idle 128 GB M5 Max still fit now (99.9 GiB a rank). Under the + provider's tensor-parallel-first policy it checks the fastest-plan rule on + constructed pairs against the plain pipeline: 2x M5 Max 128 GB keeps the + pipeline where tensor parallel is predicted faster on the device index alone, + inside the margin and for long prompts; 2x M5 Ultra 256 GB keeps the pipeline + on default link costs. As the provider plans MiMo (the speculative pipeline + credited the 1.37x its records measured, a fresh pair's 32,768 + 32,768 + request), both pairs keep the speculative pipeline before a load measures the + link and on the measured 29 us link, where tensor parallel is predicted faster + on the prior alone (`predictedFasterOnPriorOnly`), and for 8,192 + 128 or on a + 109 us link. Requests served in tensor parallel decide both ways on both + pairs. `provider-swift/Tests/ClusterPlacementChecks/run.sh` checks that the + guided step credits MiMo's rounds from its shipped records and prints the + fastest-plan and logprob lines. Through the guided step it also checks feature + parity (`ClusterModeParity`) before the evidence rule: + - as this build declares them, MiMo's tensor parallel decodes in rounds, so it + keeps every feature of the speculative pipeline and the evidence rule + decides: on two 256 GB Macs the speculative pipeline is kept with no served + record (prior only) or another build's, and this build's served records + choose (95 tok/s: tensor parallel; 60: the speculative pipeline); + - a MiMo record without tensor parallel's rounds holds it back even with this + build's served records, and where the plain pipeline is the mode it would + replace (a record without `pipeline_mtp_v1`), that pipeline's 8 batch lanes + hold one-lane tensor parallel back, served records or not; + - a Gemma record whose tensor parallel keeps no prompt prefixes (as builds + before 0.10.7 declared it) keeps the pipeline even with both Macs' share + probes, after an update that served tensor parallel, and with nothing + measured; each plan says what tensor parallel would drop; with Gemma's record + as this build declares it (prefix reuse kept), Gemma follows both Macs' share + probes; + - where only tensor parallel fits, the plan refuses and saves no setup; the + forced mode places it and says what it drops; a record without features + holds it back, and the forced mode then says what it drops is not known; + per-mode features cross the capability codec canonically; a GLM record + declaring a gap plans exactly as without it. + +2. Build `darkbloom-cluster-tp-check` and put a source-matched `mlx.metallib` + beside it ([build](build.md)). Then run the GPU oracles: + + ```bash + bash libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh \ + /path/to/darkbloom-cluster-tp-check /new/scratch/dir 58223 + ``` + + The script synthesizes four variants: `kernel`, `tiny`, `kernel` with every + token taking all 8 experts (no route can flip), and FP32 `kernel`. For + each, and for a 40-token and a 6-token prompt around the 8-token window, it + runs `full`, `simulated` and two `tp` ranks over the sealed local ring on + the given port and the next one. It then runs the socket backend once, and + one sampled run: temperature 0.8, drawn from the gathered row (by the + product's sampler on the paged path). It runs this matrix twice: + + - `contiguous`: the foundation's path (tensors read whole and cut, ordinary + caches); + - `paged`: the resident runtime's path (`--path paged`: verified load, paged + KV, the per-step agreement sum, 100-op decode buffers). Paged histories + are BF16 only, so this matrix skips the FP32 variant. + + The paged matrix also checks that: + + - each rank read only its byte runs; + - paged `full` and `simulated` equal contiguous ones bit for bit; + - ranks given different agreements refuse; + - a checkpoint changed after its manifest is refused; + - a 192-token prompt (three 64-token pages before decode) gives the same + results on both paths and over the ring; + - recording route sets (`--record-routes yes`) changes nothing. + + It also reports, without requiring anything of it, where `simulated` first + routes a token to other experts than `full`, over the positions whose inputs + are still equal (`mimo compare` prints a `route sets:` line). + + A third matrix, `mtp`, runs speculative rounds (`--mtp-depth`) on `kernel` + and `tiny` checkpoints with three random trained heads + (`mimo synthesize --mtp yes`; the text weights equal the plain variant's). + For each prompt (40, 6 and, on `kernel`, 192 tokens) it requires every + round run to equal the one-token path bit for bit (tokens, rows and caches): + the heads' own proposals (random, so mostly rejected), proposals scripted + from the one-token run's tokens (`--mtp-script REPORT`, all kept) and every + fifth scripted proposal moved off (`--mtp-misses 5`: accepts, rejects and + rollback). Sampled rounds (temperature 0.8: the heads, and the misses scripted + from the sampled one-token run) must equal the sampled one-token path bit for + bit. Two `tp` ranks over the ring must equal `simulated` for the heads, the + misses and a sampled run. + + `MIMO_ORACLE_PATHS=paged` runs one matrix. + +3. Verify. Each `tp` rank must equal `simulated` bit for bit, KV caches + included, and greedy ranks must agree with `full` under + QualificationComparator (exit status 0). A sampled run's verdict against + `full` is informational: rows that differ by rounding can draw a + neighbouring token. + ## Focused Tooling Checks For the PR reviewer, run the seven offline suites listed in @@ -1337,7 +1763,10 @@ parity qualifications included) and a block whose derived approval, grant or parity qualification IDs exceed 128 bytes, refuse a registration body over the coordinator's 64 KiB limit before staging (65,536 bytes accepted, 65,537 refused), accept the GLM-5.3-Flash block pinned from the 0.10.5-dev.branch.17 -app, and check that registration sends the block in its canonical form. +app (its digests are that app's; its grant and parity qualifications are this +build's declaration, so its evidence digest and `qualified_at` follow +`ClusterPublicModels`), and check that registration sends the block in its +canonical form. `scripts/test-provider-cluster-runtime-models.py` runs the release's model-metadata fetch against a local HTTP registry: the environment's catalog and CDN, candidate selection, the manifest and `config.json` checks, each candidate's @@ -1368,10 +1797,9 @@ removed first, its failure fatal only when `CLUSTER_RUNTIME_SEND` is true, and HTTPS plane with a throwaway certificate; the host needs Bash, Python, jq, curl and openssl. It covers the default-off switch, fork pull requests, exact label grants, HTTP errors, the single retry, timeouts, untrusted or plain-HTTP planes -and hostile reply text. It also pins each routed job's lanes (one per provider -shard, matching the job's matrix), fallback, timeout and read-only permissions, -and keeps release workflows on literal Blacksmith runners. No check contacts the -real plane. +and hostile reply text. It also pins each routed job's fallback, timeout and +read-only permissions, and keeps release workflows and the macOS jobs of +`ci.yml` on literal Blacksmith runners. No check contacts the real plane. Docs-impact tests retain provider, protocol, privacy, native capacity, cache, release/model publication and fixture mappings. Historical links need exact @@ -1826,9 +2254,11 @@ swift test --package-path libs/darkbloom-cluster -c release \ --filter GPTOSSPagedKVTests ``` -`GPTOSSPagedKVTests` compares exact rows, masks, offsets and learned-sink SDPA -results with `StandardKVCache` and `RotatingKVCache`. It also checks demand -allocation, bounded sliding retention, copy/trim isolation and owner release. +`GPTOSSPagedKVTests` compares exact rows, masks, offsets, ring metadata and +learned-sink SDPA results with `StandardKVCache` and `RotatingKVCache`. It also +checks demand allocation, bounded sliding retention, copy/trim isolation, owner +release, and that sliding pages restore only ring metadata they can continue, +then continue exactly as that ring. `GPTOSSStageChecks` checks each page's allocator overhead and sliding repack charge. These are CPU correctness checks, not native transport, MXFP4 model parity or performance evidence. Retain the existing two-Mac reference comparator @@ -1847,6 +2277,36 @@ preserving conservative memory charges. These tests do not load the registered weight payload or establish hardware numerical qualification. See the [native dtype contract](../architecture/inference.md#gpt-oss-native-residual-dtype). +## Pipeline decode command buffer checks + +`PipelineDecodeCommandBufferTests` drives random synthetic stages of each +layer-stage family as its stage session does: the prompt under the rank's +16-operation guard, then decode once under a guard and once under +`QwenLayerStageSession.decodeCommandBuffers`. Every output row, verify window +and cache or state array must be byte-equal. The cases are a dense and a +routed-expert Qwen 3.5 on a paged stage KV host (decode steps, a captured verify +window kept to two rows, and two lanes), two Nemotron stages, a Gemma 4 decoder +(one request and two lanes), two GPT-OSS stages (decode and lanes) and the +verified GLM fixture's two stages. The reference run keeps the rank's guard, +except routed Qwen and Gemma, which use `bankGuard`: their expert banks of 2 Mi +elements each commit a buffer, as registered banks do. The Nemotron and GLM +fixtures are too small for any size bound, so every family also runs with a +buffer every second dispatch (`everyOperation`), a finer partition than one +buffer per bank. Build and stage the runtime tests as described for the cluster +runtime tests above, then, with the same build flags: + +```bash +swift test --package-path libs/darkbloom-cluster -c release --skip-build --no-parallel \ + --filter 'PipelineDecodeCommandBufferTests|ContextAdmissionTests|ResidentAdmissionNemotronTests|GPTOSSResidentAdmissionTests|ResidentAdmissionGemma4Tests' +``` + +The admission suites check each family's decode-row charge. These are synthetic +GPU checks: not registered weights, pair runs, speed or peak memory. Served +Qwen, Nemotron and Gemma 4 stages all attend through the paged stage KV, but +only the Qwen cases use it here; the Nemotron and Gemma 4 cases keep +request-owned KV. See +[pipeline decode command buffers](../architecture/inference.md#pipeline-decode-command-buffers). + ## Qwen batch projection arithmetic `libs/mlx-swift-lm/Tests/MLXLMTests/Integration/Qwen/Qwen35BatchDecodeProjectionTests.swift` @@ -1868,13 +2328,20 @@ default. Run `bash provider-swift/Tests/ClusterInstalledSessionChecks/run.sh`. The CPU runner compiles the actual local-owner launcher, installed plan/session and -member-installation code. `InstalledBatchLanesCheck.swift` launches a real child +member-installation code. Its generation-mode check also launches MiMo tensor +parallel: both ranks get `--mtp-depth 2` after the mode exactly where the pinned +record declares tensor parallel's rounds, and the status then reports the head +as decoding. `InstalledBatchLanesCheck.swift` launches a real child with the fixed owner arguments and checks its exact environment, supported lane widths, out-of-range rejection, malformed-override parity even with an eight-lane family default, admission/owner/native parity, unsupported mode and image gates, and both member ranks. No model, GPU or real service is -started. The checks preserve the singleton and GLM tensor-parallel defaults; -actual multi-lane output, encrypted transport and retirement still require +started. The checks preserve the singleton and GLM tensor-parallel defaults +and the serial-prefill Gemma 4 pipeline's default lanes +(`DistributedInstalledPlan.gemma4PipelineBatchLanes`), which reach the rank, +while a Gemma setup saved with the one-chunk lookahead keeps one lane; +`DistributedInstalledLanesTests` covers the same rules for every adapter and +schedule. Actual multi-lane output, encrypted transport and retirement still require qualification on both Macs. The same real-child checks pass canonical local `MLX_METAL_FAST_SYNCH=0|1` choices through the owner and final native launch, reject free-text spellings from forwarding, preserve unrelated native guards, @@ -2189,6 +2656,36 @@ salt's digest); a repeat under another tenant must report no reused tokens. These are synthetic checks: tenant isolation on a real model and pair, and GLM bit-identity with no partition, are hardware gates. +## MiMo pipeline decode command buffers + +`MiMoDecodeCommandBufferTests` (cluster runtime, GPU) drives two random MiMo +stages as `MiMoLayerStageSession` drives them. The prompt runs under the rank's +16-operation guard. Decode steps, a verify window rolled back to two rows and +lane steps then run twice: once under the guard and once under +`MiMoLayerStageSession.decodeCommandBuffers`. Every residual crossing the cut, +every logits row and every cache or page array must be byte-equal. The tests +cover a tiny BF16 model and one quantized like the registered row (MXFP4 +experts, affine 8-bit projections, key width 192, value width 128), each on +ordinary caches and on request-owned pages. The quantized model's guard scales +MLX's size bound to its small expert banks (`bankGuard`), so each expert launch +commits a buffer, as each registered bank does. Build and stage the runtime +tests as described for the cluster runtime tests above, then, with the same +build flags: + +```bash +swift test --package-path libs/darkbloom-cluster -c release --skip-build --no-parallel \ + --filter 'MiMoDecodeCommandBufferTests|MiMoResidentAdmissionTests|MiMoPagedAdmissionTests' +bash libs/darkbloom-cluster/Tests/PlacementChecks/run.sh +``` + +The admission tests check that every full-attention layer's decode-row scores +are charged at once (`MiMoRequestStateBudget`). The placement run includes +`MiMoRoutedExpertChecks`: the MiMo layout built from the registered headers +names 282 routed-expert tensors (160,859,947,008 bytes). The hardware prior +reads 10,767,036,288 bytes for one decode step, and the golden plans change only +by the layout they echo. These are synthetic and metadata checks. They run no +registered weights and measure no speed. + ## MiMo paged speculative and phase checks Run `MiMoV26MTPPagedHistoryTests` and `MiMoV26IndependentHistoryTests` in the @@ -2220,13 +2717,24 @@ prompt projections with actual singleton calls at chunk boundaries, checks explicit scope restoration and unsupported/custom fallbacks, and verifies the unchanged tied head. `Gemma4PrefillExpertTests` executes the actual Gemma decoder, router, shared MLP and sparse expert block with the attention output isolated to zero; -it assembles an independent projection/expert oracle while preserving the -original rectangular normalization and elementwise operations, and compares -selected routes across prompt boundaries. A separate expert-only composition +it assembles an independent projection/expert oracle from one-token expert +calls while preserving the original rectangular normalization and elementwise +operations. It requires one expert call, never hinted as sorted, carrying every +token's routes (grouped by expert from 64 assignments), with the oracle's +bytes, at 7 to 512 tokens. A separate expert-only composition check compares complete singleton calls with the shared branch isolated to -zero. Ordinary and verification paths remain covered. These checks do not +zero, and a decode check requires 2, 3 and 8 independent rows to share one +call with each row's one-row bytes. A direct check compares the shared call +with one-row calls for a single row and for rows that all route to the same +experts. Ordinary and verification paths +remain covered, and the original rectangular call still sorts. These checks do not claim whole-layer singleton equivalence: existing normalization can depend on -rectangle shape on CPU. +rectangle shape on CPU. With `GEMMA4_EXPERT_ROWS_GPU=1` the suite also +compares the shared call with one-row calls on the GPU for 1 to 2,048 rows, +tied routes included, at +a geometry with the production kernel classes; `=production` adds hidden 2,816, +expert width 704 and 128 experts. Run the GPU case alone, in an exclusive +hardware window. `GemmaPrefillArithmeticTests` in the runtime target verifies that both exact policies change the receipt while the family environment and chunk policy remain bound. These CPU checks do not establish full-model cross-chip qualification @@ -2402,7 +2910,17 @@ separate hardware gates. ### Qwen27 TP warm-prefix checks `QwenTensorParallelBatchPrefixTests` checks original-grid boundaries, bilateral -misses, media/key isolation, allocator rounding and bounded LRU eviction. The +misses, media/key isolation, allocator rounding and bounded LRU eviction. It +also checks, for every prompt from 1,100 to 70,000 tokens, that the kept +boundaries reuse at least one Mac's reuse rounded to the 512-token grid (a +repeat, the next turn, a shared system prompt). It checks each request's +charge, LOAD's one capture per lane, the shared-copy eviction order, the +memory tier giving way before a refusing gate, and that a record of another +prefix policy is in another scope. On the GPU (`QWEN_TP_BATCH_GPU=1`), +`QwenTensorParallelPrefixDepthTests` restores a 33,000-token prompt's +boundaries at 32,768, 32,256, 16,384 and 8,192 on two synthetic hybrid +shards and compares the final logits and every attention, convolution and SSM +array with a cold prefill on the same grid, byte for byte, on both ranks. The real-shard `QwenTensorParallelBatchSessionTests` compares cold and restored outputs plus attention/conv/SSM state at widths 2, 4 and 8, mixed positions, reordered decode and one-sided cache loss. Run it with both contiguous and @@ -2438,7 +2956,7 @@ requests on both Macs after a native pin change. Run SDK `QwenMTPPagedHistoryTests` for paged assistant append/trim/copy/restore and failed-constructor custody. Native `QwenTensorParallelMTPPolicyTests`, `QwenTensorParallelMTPBudgetTests`, `QwenTensorParallelBatchMTPBudgetTests` and `QwenTensorParallelAssistantQuoteTests` check exact inventory, complete singleton/cohort reservations and metadata/native quote equality. `QwenTensorAssistantStartupTests` exercises real bilateral worker arguments; Process `TensorAssistantReadinessCheck` checks real child READY mismatch rejection. Provider `DistributedAutomaticBatchPlannerTests` covers automatic inline discovery, malformed/off cases, complete initial quote and saved-policy preservation through wider replans. -Set `QWEN_TP_MTP_GPU=1` only in an isolated native test run with the matching Metal resource. Run `QwenTensorParallelBatchMTPWindowTests` and `QwenTensorParallelBatchMTPTransitionTests` with `--no-parallel` so suites do not race global MLX state. Actual tiny targets test unequal histories/keep counts, rejected-suffix settlement, greedy target-column continuation, singleton/wider transitions, independent accepted-token credits, survivor retirement, mixed ordinary rows and poisoned-cohort cleanup. The trained head remains single-row; the decoder creates the target cohort. Tied-head transition fixtures do not establish full-model acceptance behavior or sampled equivalence. +Set `QWEN_TP_MTP_GPU=1` only in an isolated native test run with the matching Metal resource, and start that process with `MLX_QMV_BATCH_INVARIANT=1` as every cluster process runs (`ClusterQuantizedRowRouting`): MLX reads it once per process, and `QwenTensorParallelBatchMTPWindowTests.sharedWindowCallsKeepEveryRowsQuantizedArithmetic` checks MLX's own grouped quantized calls, which keep each row's bits only with it. Run `QwenTensorParallelBatchMTPWindowTests` and `QwenTensorParallelBatchMTPTransitionTests` with `--no-parallel` so suites do not race global MLX state. Actual tiny targets test unequal histories/keep counts, rejected-suffix settlement, greedy target-column continuation, singleton/wider transitions, independent accepted-token credits, survivor retirement, mixed ordinary rows and poisoned-cohort cleanup. The trained head remains single-row; the decoder creates the target cohort. Tied-head transition fixtures do not establish full-model acceptance behavior or sampled equivalence. Exact drafts (`QWEN_TP_MTP_GPU=1`): `QwenTensorParallelExactDraftRowsTests` runs a round's later draft steps for two to eight requests through one assistant forward (`Qwen35InlineMTPAssistant.draftHiddens`) and checks every row byte for byte against the same request's one-row step, over unequal histories, for two consecutive steps, at the suites' and the 9B's head ratios. `QwenTensorParallelMTPHeadRowsTests.exactDraftProjectionsKeepEachRowsOwnProductAtQwen27Shapes` checks the head and assistant projections at Qwen27's shapes, and `QwenTensorParallelBatchMTPTransitionTests.exactDraftRowsEqualTheirSoloRunsAndThePlainTargetAtEveryWidth` checks that every row of one to eight concurrent requests equals its solo run (tokens, MTP statistics and native state on both ranks) and emits the plain target's greedy tokens, with exact and with MLX drafts, with every proposal accepted and with proposals rejected. `QWEN_TP_ACCEPT_BENCH_MODEL= QWEN_TP_ACCEPT_BENCH_PROMPTS=` runs `QwenTensorParallelMTPAcceptanceRealTests`: the real row's two ranks in one process, each prompt decoded plainly and speculatively with each draft kernel; it requires lossless output and reports rounds, tokens per round, acceptance by position and where the two kernels' proposals differ. @@ -2465,6 +2983,27 @@ The planned-stop lifecycle suite also pauses the actual service immediately befo Planned-stop lifecycle checks exercise the actual peerLeaseState projection, accepted ClusterControlNode follower lease, ClusterControlIntent recording and follower part selection while the real owned child is retained after TERM, while start is paused, and after retirement. A held outbound lease custody flag must block final peer stop after local child exit. Optional-record compatibility and an already-idle peer are checked separately. No physical peer transport or installed native shutdown is claimed by these CPU cases. +### Cluster service listeners after pairing again + +`ClusterServicePairingChangeTests` runs the actual service's two listeners on +loopback ports of their own (`ClusterService.Listening`), keyed from real pairing +ceremonies stored in a private home. After the same two Macs pair again, the +earlier listeners refuse the new pairing (`handshakeRejected`) until the next +check starts them again; then the new pairing is answered and the earlier one +refused. A removed pairing stops both listeners, an unchanged or unreadable +pairing store keeps the same ones, and the control node of this Mac's earlier key +is dropped. The other Mac dials without the per-user request lock, which a +cluster service running on the same Mac shares; no production port or +Thunderbolt interface is used. `ClusterConsoleChecks` (`listenersFollowThePairing`) +checks the same refusal and restart on real ceremonies and listeners without the +service, and that a re-read pairing store gives the same identity, a new +ceremony another one and an unsafe store a read failure rather than no pairing. + +Focused check: `swift test --filter ClusterServicePairingChangeTests` from +`provider-swift`. Sources: +`provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterServicePairingChangeTests.swift` +and `provider-swift/Tests/ClusterConsoleChecks/ConsolePairingChangeChecks.swift`. + ### Qwen27 capacity consistency checks Every Qwen TP row serves through these request-owned lanes. `QwenTensorParallelBatchSessionTests` @@ -2476,6 +3015,17 @@ interior-axis cut is a row-major copy whose quantized products equal the former batched decode rows on the cached FP32 constants (`QuantizedLinear.independentRowsForward`) equal the call that widened them inside the matmul and each row alone. `QwenTensorParallelBatchMTPTransitionTests.nineBRatioAssistantSurvivesCreditJoinsRectanglesAndResumedSpeculation` runs the resident assistant's transitions on the 9B ratio (`QWEN_TP_MTP_GPU=1`). +`QWEN_TP_REAL_GEOMETRY_GPU=1` runs `QwenTensorParallelRealGeometryRowsTests` (about 3 GB of random +weights): the 27B row contract at its registered per-rank widths (`QwenTensorParallelRowsCheck`), both +ranks in one process; start it with the worker's arithmetic environment. +`darkbloom-cluster-tp-check qwen-rows synthesize --output DIR` writes that checkpoint (about 2.1 GB), and +`darkbloom-cluster-tp-check qwen-rows run --model-dir DIR --report FILE` runs the check as two processes +(`MLX_RANK`, `MLX_HOSTFILE` with two free `127.0.0.1` ports; `--backend ring` or `socket`, +`--reduction native` or `sealed-bench`). `qwen-rows layers` takes the same options plus `--target ROW +--other ROW` (rows 0 to 7; default 7 beside 6) and reports, for three decode steps, the first decoder layer +whose output differs between the row alone and beside the other. Both ranks must pass the same command and +rows. `QWEN_TP_AQV_GPU=1` runs `AffineQuantizedVectorsTests`, including the fused SwiGLU against the two +projections and the compiled SwiGLU at every normal bf16 and f16 gate value. `QWEN_TP_MOE_BATCH_MODEL=` runs `QwenTensorParallelRoutedCohortRealTests`: the artifact's real shards, both ranks in one process on the GPU, rows of one cohort against the same rows alone, byte for byte. The reference rows in these tests (and the singleton owner of the capacity-parity @@ -2508,6 +3058,18 @@ holds. Golden plans must stay byte-identical. Run `provider-swift/Tests/ClusterInstalledSessionChecks/run.sh` for the owner-only history file. +A pair that registers with a coordinator is planned with equal shares only +(`ClusterPlacementPolicy.equalTensorShares`): the same `run.sh` places the +weighted check's unequal Macs under that policy as if the family offered no +unequal shares, keeps equal Macs' chosen placement and GLM-5.3-Flash's whole +plan, and refuses a retained unequal partition. From `provider-swift`, +`swift test --filter 'DistributedAutomaticBatchPlannerTests|ClusterApprovalTensorSharesTests'` +checks the guided setup's plan for Qwen3.8 27B on two unequal Macs (unequal for +a local cluster, equal for one served through Darkbloom) and that a cluster +approval beside unequal shares is refused by the leader's check before any part +stops and by the other Mac's before it saves, because a member's registration +names no shares (`NativePairMemberRoster`). + From `libs/darkbloom-cluster`, `swift test --filter QwenTensorParallelShareProbeTests` checks the per-mille share and the probe request's shape on the CPU. With exclusive GPU custody and the matching Metal library, set diff --git a/docs/operations/model-migration.md b/docs/operations/model-migration.md index f1631ca6b7..eb754d40d3 100644 --- a/docs/operations/model-migration.md +++ b/docs/operations/model-migration.md @@ -1,6 +1,6 @@ # Migrate a public model to a new build -> Last updated: 2026-10-15 +> Last updated: 2026-11-02 Runbook for moving a public model name (an **alias**, e.g. `gemma-4-26b`) from one concrete build to another with no downtime and without consumers ever @@ -74,6 +74,20 @@ coordinator logs `provider now advertises build (models_update)` and against the desired build — capacity never black-holes. There are no weights, ramps, or migration controllers. +**The operator's filter wins.** A provider converges only when the desired +build is in its [operator filter](../reference/configuration.md#provider-model-selection). +A background `darkbloom start` and every `darkbloom switch` save that filter, so +almost every provider has one and almost none lists a newly published build: a +flip converges providers with an empty `enabled_models` and nobody else until +operators pick the new build. The others keep serving the previous build and log +`desired_models: → is outside the enabled model filter; not +converging`. `ResolveModel` sends alias traffic to the desired build whenever a +provider can take it, so previous-build providers then serve only overflow, and +providers on a retired build serve none of it. After the flip, ask operators to +run `darkbloom switch` and pick the public model's name, which the picker then +maps to the desired build; before retiring the previous build, count the +providers still advertising it. + ## Steps ### 1. Reuse a valid upload or publish the new build diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index b00c7d71f3..da70f43c75 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -1,6 +1,6 @@ # Release A Provider Version -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 Build, sign, notarize and publish an explicitly authorized provider artifact. The pipeline registers its exact official identity through the external platform @@ -403,6 +403,10 @@ identity (`provider-swift/Package.swift`). Config, CLI flags and `DARKBLOOM_R2_CDN_URL` still override defaults. Dev/prod products have different cache keys, and packaged smoke must report the selected build environment. +Every run except a dev push builds master's source. Before the build, job +`resolve-env` runs `scripts/provider-build-default.py --branch master`. The run +stops if the plain-build default in `provider-swift/Package.swift` is not `prod`. + A dev release from a dev push has the version `X.Y.Z-dev.branch.N`, and a master validation build has `X.Y.Z-dev.N`. `X.Y.Z` is the source `ProviderCore.version` and `N` is the workflow run number. The release lane @@ -757,8 +761,9 @@ accepts the block derives from it that build's cluster approvals, their pair-serving grants (without one no pair of GLM-5.3-Flash or Qwen3.8-27B forms: [why](../architecture/inference.md#cluster-runtime-facts-of-an-installed-app)), and the parity qualifications (public traffic) of the models the build declares -public (`ClusterPublicModels`: GLM-5.3-Flash and Qwen3.8-27B in pipeline and -tensor parallel, the owner's decisions of 2026-10-31, +public (`ClusterPublicModels`: GLM-5.3-Flash, Qwen3.8-27B, MiMo-V2.6-Flash and +Gemma 4 26B QAT in pipeline and tensor parallel, MiMo-V2.6-Flash also in its +speculative pipeline, the owner's decisions of 2026-10-31 and 2026-11-03, [evidence](../reports/2026-10-31-public-cluster-models.md)). No operator posts approvals, grants or public qualifications per build. A coordinator applies the qualifications to each declared family on any Apple silicon pair: the declared @@ -1030,6 +1035,14 @@ do not replace its bytes or re-register it with a different artifact. 4. Adjust the GitHub release's public status and record the actual outcome. Fix forward with a new reviewed patch version, never overwritten signed bytes. +Deactivation stops new installs only: a Mac already on the bad release stays on +it, because the updater never installs an older version. A provider who needs +the previous release on a Mac now runs `darkbloom update --rollback` there +([roll back](../provider/installation.md#roll-back-to-the-previous-release)). It +restores the release the updater kept when it installed the bad one and +quarantines the bad one on that Mac, contacts no coordinator, and leaves +automatic updates on, so the fixed patch version installs normally. + Permanent binary revocation is distinct from release deactivation. An authorized platform administrator can use `POST /v1/admin/app-attest/builds/revoke`; registration retries cannot undo its tombstone. Recover with another reviewed signed build, diff --git a/docs/provider/attestation.md b/docs/provider/attestation.md index 214edd1003..75b3b6ea14 100644 --- a/docs/provider/attestation.md +++ b/docs/provider/attestation.md @@ -1,6 +1,6 @@ # Reaching and keeping `hardware` trust -> Last updated: 2026-10-13 +> Last updated: 2026-11-02 How to check provider verification and retain legacy `hardware` trust where eligible. New providers require macOS 27 or later and current qualified App @@ -99,6 +99,24 @@ The log line starts with `App Attest: Apple operation stalled`. An explicit `darkbloom restart` uses the same graceful lifecycle; it is not instant or proof that Apple will accept the next call. +After a self-update, some macOS 27 Macs report App Attest as unsupported +(`is_supported_false`) although it worked before. If the coordinator granted +this Mac App Attest in the last 7 days and launchd runs the provider, the +provider restarts once through launchd when the state lasts 5 minutes and the +provider is idle. It restarts once per verified episode: if the new process +still reports unsupported, it waits until the coordinator verifies the Mac +again. This restart shares the stall restart's limit of one per 6 hours. + +For root-cause analysis, the provider log (`~/.darkbloom/provider.log`) gets a +line that starts with `App Attest entitlement evidence` once at startup and at +each `is_supported_false` answer. It shows the start reason, the App Attest +entitlements the kernel gave the running process next to the ones in the code +on disk, and the executable's modification time minus the process start time. +The line stays on the Mac; it is not sent to the coordinator +(`provider-swift/Sources/ProviderAppAttest/AppAttestPreflightProbe.swift`, +`AppAttestEntitlementEvidence`). The log line starts with `App Attest: isSupported is false`. See the +[thresholds and limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle). + The separate [supervised worker candidate](../architecture/security/identity-binding.md#supervised-app-attest-worker-candidate) is internal, defaults off and is **not ready for production**. It retires the worker rather than restarting the inference process; do not enable its @@ -139,6 +157,8 @@ credential to bypass that check. New setup on macOS 27 or later skips MDM profile download in both the installer and `darkbloom enroll`. Darkbloom MDM will be deactivated soon; upgrade to macOS 27 to avoid legacy enrollment. A qualified macOS 27 provider can use [App Attest authorization](https://github.com/Layr-Labs/darkbloom-platform/blob/master/docs/reference/provider-authorization.md) when the coordinator explicitly enables it. Start the signed provider and check `darkbloom status` / `darkbloom doctor` for current App Attest authorization. Company-managed Macs keep their employer profile; they do not enroll into Darkbloom MDM for this path. +When `darkbloom status` or `darkbloom doctor` says App Attest authorizes the connection but MDM removal needs fresh coordinator readiness, keep existing profiles installed and wait for a fresh decision. The displayed serving lease can remain valid after removal readiness becomes stale. Both doctor summaries and status use the separate decisions in `provider-swift/Sources/ProviderCore/Diagnostics/ProviderAuthorizationReadiness.swift` (`summary`); see the [authorization reference](../reference/provider-authorization.md). + After the coordinator enables removal and reports readiness, run `darkbloom unenroll` and choose the App Attest option. Removal guidance requires a coordinator decision received within the last 10 seconds, as well as a current daemon snapshot and unexpired authorization; a local state-file rewrite cannot extend readiness. It requires macOS 27 or later; `--keep-serving` remains a direct shortcut. The command preserves credentials/account data, validates the exact Darkbloom enrollment and guides removal in System Settings. If the read-only administrator inventory is needed, run the command in the foreground of an interactive terminal: `sudo` reads the password with terminal echo disabled. Refusing authentication, running without a terminal, or running as a background job withholds guidance; no profile is removed by the CLI. The full-exit option stops the provider and offers identity cleanup, so choose App Attest to retain provider identity. New setup remains pending if App Attest is unavailable or unqualified; diagnose diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index f1d3996823..9d91261278 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -434,8 +434,9 @@ drains it instead of ending the process at once. `SIGHUP` is not a stop signal in two cases: the provider's launchd job does not take it, so it has whatever action launchd started the job with, and a start that arrived with `SIGHUP` ignored, for example under `nohup`, keeps ignoring it. A provider that -re-executes itself in place for a self-update carries the same choice into the -new process (`ProviderStopSignals` in +re-executes itself in place for a self-update (one that is not the provider +LaunchAgent's own job; launchd relaunches that job) carries the same choice +into the new process (`ProviderStopSignals` in `provider-swift/Sources/ProviderCore/Service/ProviderStopSignals.swift`). The signal deadline is configurable with [`DARKBLOOM_DRAIN_TIMEOUT_SECONDS`](../reference/configuration.md#provider-drain-deadline). @@ -587,11 +588,12 @@ darkbloom cluster local [] [--bind
] Runs the onboarding asking for local-only serving (`ClusterOnboardingRequest`), saved in the leader's setup record (`ClusterOnboardingLeadership.localOnly`, -`localBind`) until `p` in `darkbloom cluster` serves through Darkbloom again. +`localBind`) until **Serve through Darkbloom** in `darkbloom cluster` serves +through Darkbloom again. The leader part then starts with `--no-coordinator`. Needs a terminal; exit 1 -otherwise. On the Mac that joins a waiting leader it pairs, says to run it on -the leader and ends (exit 0) like `darkbloom cluster` -(`ClusterOnboardingDriver.joinedLocalLine`). Steps: [Serving locally only](./two-mac-cluster.md#serving-locally-only) +otherwise. On the Mac that joins a waiting leader it pairs, says to continue on +the leader with `darkbloom cluster local` and ends (exit 0) like `darkbloom cluster` +(`ClusterOnboardingDriver.joinedLocalContinueLine`). Steps: [Serving locally only](./two-mac-cluster.md#serving-locally-only) (`provider-swift/Sources/darkbloom/ClusterLocalCommand.swift`). `darkbloom cluster status` prints `MTP: on (decode verifies drafts of the @@ -740,12 +742,50 @@ and mixed prompt arrivals, see [the profiling workflow](https://github.com/Layr- |---|---|---|---| | `--coordinator ` | `String?` | config URL | Release source | | `--check-only` | flag | `false` | Report; do not install | -| `--override-quarantine` | flag | `false` | Reinstall a version quarantined after 3 failed starts | -| `--timeout ` | integer, 0–3600 | `600` | Drain the running service before activating the installed update | -| `--force` | flag | `false` | Explicitly permit interruption during update activation | +| `--override-quarantine` | flag | `false` | Reinstall a quarantined version: one that failed 3 starts, or one rolled back with `--rollback` | +| `--rollback` | flag | `false` | Restore the release kept for rollback (the retained predecessor) and quarantine the installed release. Contacts no coordinator | +| `--yes`, `-y` | flag | `false` | With `--rollback`: do not ask for confirmation. Required when standard input is not a terminal | +| `--timeout ` | integer, 0–3600 | `600` | Drain the running service before activating the installed update or the rollback | +| `--force` | flag | `false` | Explicitly permit interruption during update or rollback activation | Exit 1 on `quarantined`, `busy`, `cancelled`, `downloadFailed`, `hashMismatch`, `replaceFailed`, or a failed check (`UpdateResult`, `provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift`). + +`--rollback` cannot be combined with `--check-only`, `--override-quarantine` or +`--coordinator`, and `--yes` applies only to it. It prints the plan (installed +version, restored version, the install generation it records) and asks +`Roll back to vX? [y/N]`. A loaded provider is drained, the layout is swapped +through the watchdog's journaled rollback under the update lease, and the +provider is restarted and the watchdog rearmed, as for an installed update; a +stopped provider, or one stopped while the prompt was open, is only swapped +(`provider-swift/Sources/darkbloom/UpdateRollback.swift`, `UpdateRollback`; +`provider-swift/Sources/ProviderCore/Update/SelfUpdater+Rollback.swift`, +`rollbackPlan`, `rollBackToPredecessor`). The prompt runs without a lock, so +the command decides every check again once it holds the update lease, before +the drain, and again at the swap for what the drain could let change. Over the +swap it holds the cluster service lock, so no cluster service starts, and the +provider instance lock (or leaves it with the drained service process), so no +other provider starts. A pair's coordinated update holds the same lease from +its check through its install, and its cluster service login agent stays +loaded through its restart, so a rollback and a pair update never interleave. +It runs only as the user the provider runs as, not as root. It exits 1 and +changes nothing when +this Mac serves in a `darkbloom cluster` pair (a running cluster service, a +loaded cluster service login agent, or a loaded cluster-member provider job), a +provider runs outside launchd (`darkbloom start --foreground`, also when it +replaced the service while the prompt was open) or started after the plan was +shown, the installed release changed after the plan was shown, another update +or recovery holds the lease, +no release is kept for rollback, the installed release is already that +release, the installed `Darkbloom.app` is not the recorded release, or the kept +release fails its hash or signature check (`RollbackRefusal`). A refusal at +the swap, after the drain, restarts the drained provider on the installed +release; when another provider took the instance lock during the drain, it is +not signalled and the service stays drained. On a `darkbloom cluster` Mac, +stop its cluster service first; once it runs again, the other Mac follows the +rollback to the same release +([a rollback on one Mac](./cluster-always-on.md#a-rollback-on-one-mac)). Steps are in +[installation → Roll back to the previous release](./installation.md#roll-back-to-the-previous-release). See [installation → Update](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/docs/provider/installation.md). ### `darkbloom enroll` / `darkbloom unenroll` @@ -784,6 +824,8 @@ grants serving authorization or removes an existing profile. Without flags: `log stream --predicate 'subsystem == "dev.darkbloom.provider"' --level info`. +Where `logs` and [`report`](#darkbloom-report) wait for a `log` child to finish, they take its exit from `ProcessExitObserver` (its termination handler), which does not run the calling thread's run loop. + | Flag | Description | |------|-------------| | `--coordinator-url ` | Override the coordinator WebSocket URL | @@ -1342,6 +1384,7 @@ Output includes: GLM-5.3-Flash error that reports a Metal command buffer out of memory adds the `→ fix:` line from [GLM-5.3-Flash GPU wired-memory limit](#glm-53-flash-gpu-wired-memory-limit). +- App Attest serving authorization can remain visible through its unexpired lease, while MDM removal advice requires a matching fresh coordinator decision. The same distinction applies to both doctor summaries; see [provider authorization](../reference/provider-authorization.md). - `Requests served since the daemon started (… ago)`: coordinator requests this daemon finished since it started, with output tokens only. The count restarts at zero when the daemon restarts or a scheduled availability window @@ -1488,6 +1531,16 @@ The report header prints `Build` (`prod` or `dev`, fixed at compile time), `darkbloom doctor` is read-only except for the subprocess calls used by public ProviderCore checks and the explicit `--clear-backend-guard` action (`provider-swift/Sources/darkbloom/DoctorCommand.swift`, `runClearBackendGuard`). +On a Mac paired for a two-Mac cluster, the detailed checks also list the +checks `darkbloom cluster doctor` runs (installed metadata, trust files, the +Thunderbolt RDMA link, the saved setup), each named `cluster `; a failed +one fails the run and points to `darkbloom cluster doctor` for its details. A +Mac that is not paired gets none of them, and its link is not inspected +(`provider-swift/Sources/darkbloom/DoctorClusterChecks.swift`, +`buildClusterDoctorChecks`). On a Mac that serves its share of a cluster's +model, **model fits in RAM** says the single-Mac load check does not apply +and points to `darkbloom cluster doctor`, instead of weighing the whole model +against this Mac's memory (`ModelFitDiagnostic.clusterMember`). The operator report begins with a readiness summary and the first concrete action. A failed model-fit check names the live usable memory, the required load budget and their shortfall; it tells the operator to free memory, rerun @@ -1860,18 +1913,28 @@ Check for and apply provider updates. ```bash darkbloom update [--check-only] [--coordinator ] [--timeout ] [--force] +darkbloom update --rollback [--yes] [--timeout ] [--force] ``` | Flag | Description | |------|-------------| | `--check-only` | Report whether an update is available without installing | | `--coordinator ` | Override coordinator URL | +| `--rollback` | Restore the release kept for rollback and quarantine the installed one ([details](#darkbloom-update)) | +| `--yes`, `-y` | With `--rollback`: do not ask for confirmation | | `--timeout ` | Drain deadline: default `600`, valid 0–3600 seconds | | `--force` | Explicitly permit interruption during activation; default `false` | The update path verifies bundle, binary, and `mlx.metallib` hashes before replacing the running binary (`provider-swift/Sources/ProviderCore/Update/SelfUpdater.swift`). +On a Mac whose `darkbloom cluster` service runs, the command then asks that +service's supervisor to restart into the installed release together with the +other Mac, after the pair drained, and prints its progress until the restart +(at most `--timeout` seconds); a deferral exits 1 +(`provider-swift/Sources/darkbloom/UpdateCommand.swift`, `ClusterServiceUpdateRequest`; +[updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)). + ## `darkbloom autoupdate` Enable or disable automatic update checks at startup. @@ -2185,7 +2248,8 @@ qualification or performance. Sources: | Verified weight hashes | `~/.darkbloom/verified-weights.json` (`DARKBLOOM_VERIFIED_WEIGHTS_FILE`), `0600`; managed GLM load hashes bound to file identities, reused for startup registration | `provider-swift/Sources/ProviderCore/Service/VerifiedWeightHashStore.swift` | | Watchdog state | `~/.darkbloom/watchdog-state.json` (`DARKBLOOM_WATCHDOG_STATE`) | `provider-swift/Sources/ProviderCore/Service/WatchdogState.swift` | | KV-backend crash-loop guard | `~/.darkbloom/kv-backend-guard.json` (`DARKBLOOM_KV_BACKEND_GUARD`) | `provider-swift/Sources/ProviderCore/Service/KVBackendGuard.swift` | -| App Attest stall restart marker | `app-attest-stall-restart.json` beside the daemon state file, `0600`; time of the last automatic restart for a stalled DeviceCheck call ([limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle)) | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestStallRestartMarker`) | +| App Attest stall restart marker | `app-attest-stall-restart.json` beside the daemon state file, `0600`; time of the last automatic App Attest restart, for a stalled DeviceCheck call or for `is_supported_false` ([limits](../reference/app-attest-shadow.md#bounds-and-credential-lifecycle)) | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestStallRestartMarker`) | +| App Attest verified marker | `app-attest-verified.json` beside the daemon state file, `0600`; time of the last coordinator App Attest authorization, rewritten at most once per hour. When it is missing at serve start, it is seeded once from the previous daemon state (the last Apple success of an attested key, or an App Attest grant left by an unclean exit), with evidence from the last 7 days. It only allows the `is_supported_false` restart; it never authorizes serving | `provider-swift/Sources/ProviderAppAttest/AppAttestStallRestart.swift` (`AppAttestVerifiedMarker`) | | Provider run marker | `provider-run.json` beside the daemon state file, `0600`. Set to `running` when a serve process starts and to `clean` (with cause) after its drain or before an update/stall relaunch. Explicit update/stall relaunch causes survive later generic termination callbacks; a failed hand-off restores running state and clears the cause. The next process derives `previous_exit` and `start_reason` from it | `provider-swift/Sources/ProviderCore/Service/ProviderRunMarker.swift`, `ProviderProcessRun.swift` | | APNs push history | `apns-push-history.json` beside the daemon state file, `0600`. The last 50 code-identity push receipt times and reply times, plus whether a device token was present. No token, nonce or payload | `provider-swift/Sources/ProviderCore/Apns/APNsPushHistory.swift` | | Provider LaunchAgent | label `io.darkbloom.provider`; `~/Library/LaunchAgents/io.darkbloom.provider.plist`; `RunAtLoad = true`, `KeepAlive = false`; stdout/stderr → `~/.darkbloom/provider.log` | `provider-swift/Sources/ProviderCore/Service/LaunchAgent.swift` (`label`, `plistPath`, `logPath`) | @@ -2209,10 +2273,10 @@ override `provider.toml` for one process, are in | Key | Default | Effect | |---|---|---| | `[provider] memory_reserve_gb | 4 | GiB withheld from the selected OS-available/MLX load budget; the larger unified-cap reserve still applies. By default OS availability includes inactive pages or, when larger, the reclaimable file page cache, so this is not a free-page floor. Set process-start DARKBLOOM_MEMORY_AVAILABILITY=free-only for shared hosts; see [memory admission](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/docs/architecture/scheduling.md#shared-host-memory-admission). | -| `[provider] auto_update` | `true` | Startup + periodic self-update | +| `[provider] auto_update` | `true` | Startup + periodic self-update; on a `darkbloom cluster` Mac, the pair's coordinated update at its update slot ([cluster service](cluster-always-on.md#the-pairs-coordinated-update)) | | `[provider] auto_restart` | `true` | Arm the watchdog LaunchAgent | | `[provider] update_jitter_seconds` | `300` | Max random delay before an automatic install or a network provider drains a model for a prepared MTP replacement; serving continues during the delay. `0` disables jitter; capped at `3600`. Standalone MTP upgrades skip this delay. Random staggering provides no fleet availability guarantee (`provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift`, `updateJitterSeconds`; `provider-swift/Sources/ProviderCore/Update/UpdateJitter.swift`, `delay`; `provider-swift/Sources/ProviderCore/ProviderLoop+MTPDrain.swift`, `waitBeforeMTPUpgradeDrain`) | -| `[backend] enabled_models` | `[]` | Advertise only these ids; empty = all serveable | +| `[backend] enabled_models` | `[]` | Advertise only these ids; empty = all serveable. When set, it also bounds coordinator model commands and rollouts ([operator filter](../reference/configuration.md#provider-model-selection)) | | `[backend] model_cache_directory` | unset | Explicit saved hub directory; set or import once with `models location`, clear with `--reset`. Ambient cache variables never override it; hand-written relative paths are anchored to the config file (`provider-swift/Sources/ProviderCore/Config/ModelCacheConfiguration.swift`, `ConfigManager.modelCacheDirectory`) | | `[backend] idle_timeout_mins` | `60` | Unload a model idle this long; `0` disables; paused during active or explicitly paused Autopilot | | `[backend] max_model_slots` | `3` | Resident models | diff --git a/docs/provider/cluster-always-on.md b/docs/provider/cluster-always-on.md index d4b21423f9..63101b499c 100644 --- a/docs/provider/cluster-always-on.md +++ b/docs/provider/cluster-always-on.md @@ -27,18 +27,16 @@ the cluster comes back by itself, with no command run on either Mac (see [After a restart or a power cut](#after-a-restart-or-a-power-cut)). - launchd runs `darkbloom cluster service --supervise`: the same supervisor as - below, around `darkbloom cluster service`, without its update slot. A service + below, around `darkbloom cluster service`. A service that ends is restarted after 15 s, doubling to 300 s; three runs in a row each shorter than 120 s park it (nothing runs) until `darkbloom cluster` is run again, which restarts it and resets the budget. -- Nothing updates Darkbloom on these Macs: the supervisor runs with automatic - updates off (`provider-swift/Sources/darkbloom/ClusterServiceCommand.swift`, - `runSupervisor`), this Mac's part runs no updater - (`provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift`, which starts +- The supervisor updates Darkbloom on this Mac together with the other Mac + ([the pair's coordinated update](#the-pairs-coordinated-update)). This Mac's + part runs no updater of its own + (`provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift` starts `startAutoUpdateMonitor` only for a single-Mac provider), and the single-Mac - provider does not run beside the cluster. Run `darkbloom update` on both Macs - ([updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)); - automatic updates for a pair are a follow-up. + provider does not run beside the cluster. - `RunAtLoad`, and `KeepAlive` only after an unsuccessful exit (throttled to the budget's first backoff): launchd brings back a supervisor that crashed, never one that was stopped. @@ -114,6 +112,167 @@ says which applies to each Mac, from its own settings: Darkbloom does not switch to a system daemon for this: with FileVault on, the disk stays locked until someone logs in, so a daemon would not help. +### The pair's coordinated update + +Each Mac's cluster service supervisor runs the single-Mac updater's sequence +(`AutoUpdateController`) for the pair, with the single-Mac gate: `auto_update`, +`DARKBLOOM_NO_UPDATE_CHECK` and the configured coordinator, read when the +supervisor starts (`Watchdog.settings`, +`provider-swift/Sources/darkbloom/ClusterServiceCommand.swift`, +`supervisorConfiguration`). One cycle +(`provider-swift/Sources/ProviderCore/Update/ClusterPairUpdateCycle.swift`, +`ClusterPairUpdateCycle`) runs beside the serving cluster service: + +| Step | Single Mac | Pair (both Macs) | +|---|---|---| +| When | 5 min after start, then every 30 min | Every 30 min at the update slot of the pairing's cluster ID (`ClusterMemberUpdateSlot`), the same moment on both Macs; or at once for `darkbloom update` | +| Check, download, verify, stage | While serving (`SelfUpdater`) | The same, on each Mac, while the pair serves | +| Stop taking requests | Once staged | Once staged on both Macs (each reads the other's progress, `ClusterPairUpdateProgress`, from the other cluster service's status over the link) | +| Drain | Accepted requests finish, at most 120 s; never cancelled | The part that serves the pair (rank 0) finishes its accepted requests, at most 120 s (`ClusterUpdateDrainRequest`, through its lifecycle mailbox); the other part serves none. A request still running reopens the pair on both Macs and defers to the next slot | +| Install | Commit the staged bundle | Each Mac commits once both drained | +| Restart | launchd restarts the provider | The supervisor stops its cluster service (the drained part stops with it), checks that the installed binary starts, and starts again from it | +| Recovery | The watchdog promotes the candidate after 600 s of fresh heartbeats, rolls back after 3 failed starts | A binary that fails the start check is never restarted into: the supervisor restores the previous release and quarantines the new one at once, and starts its cluster service again. Otherwise the restarted supervisor does what the watchdog does, with its cluster service's heartbeat (`ClusterCandidateRecovery`) | + +The rules each Mac applies to the other's progress are in +`provider-swift/Sources/ProviderCore/Service/ClusterSupervision/ClusterPairUpdate.swift` +(`ClusterPairUpdate.partnerState`), and those for its own part in +`ClusterPairUpdateCycle`: + +1. Neither Mac stops taking requests before both have the release on disk, and + neither installs before both drained, so a release one Mac cannot download, + verify or stage is installed on neither; both retry at the next slot. +2. The drain never cancels an accepted request and sends no drain barrier: a + drain the pair gives up reopens admission on the same coordinator connection. + The stop that follows a completed drain acknowledges it as every stop does. +3. A Mac whose partner cannot be asked (no answer, a build without this + progress, or a progress not rewritten for + `ClusterPairUpdate.progressStaleSeconds`) goes on alone only when no cluster + worker runs on it, checked again before it installs, so it never breaks a + serving pair; with a pair loaded it waits, then defers. +4. Only the coordinator-paired part answers the drain + (`ProviderLoopConfig.clusterMemberAnswersUpdateDrain`). A part that serves + otherwise (the leader's local API server, a Mac serving alone) does not, so + the update defers while it serves. A service whose status says so + (`localOnly`, a solo part) gives the release up before downloading it. +5. A Mac whose partner has automatic updates off gives the slot's release up + before downloading it. A Mac with automatic updates off reports `disabled` + whenever no cycle runs on it, except for the minute after a cycle that + `darkbloom update` asked for ended. A cycle for `darkbloom update` instead + waits, while serving, for the other Mac's `darkbloom update`, at most + `ClusterPairUpdate.partnerStageWaitSeconds` (900 s) from its start. + +The supervisor restarts by replacing itself with the installed binary +(`execv`). Unlike a single Mac's watchdog, no other process outlives that +restart to roll a release back, so the supervisor first runs the binary once as +its child (the start check, `ClusterCandidateRecovery.startCheckFailure`): +`darkbloom --version` must exit 0 within +`ClusterCandidateRecovery.startCheckTimeoutSeconds` (30 s) and print the +release's version. This loads the binary as the restart would: the dynamic +loader and the frameworks it links, its code signature and the argument parser. +A binary that fails is not restarted into. The supervisor counts one failed +start, restores the verified predecessor and quarantines the release at once +(`ClusterCandidateRecovery.recordFailedStartCheck`), and starts the cluster +service again from the restored binary. The other Mac follows that rollback +([a rollback on one Mac](#a-rollback-on-one-mac)). A rollback after three +failed starts checks the restored predecessor the same way; if that check fails +too, the supervisor starts the cluster service itself instead of restarting +into it. A binary that passes the check but whose supervisor fails before it +starts the cluster service is still not rolled back. + +### A rollback on one Mac + +When one Mac of a pair rolls a release back, the other Mac rolls back to the +same earlier release, and the pair serves that release together. This answers +the question the coordinated update left open: before, the pair stayed split +(each Mac on another release, so the leader never planned it again) until a +newer release updated both Macs. + +A rollback is any of: three failed starts of the release's cluster service, a +failed start check, or `darkbloom update --rollback` run while the Mac's +cluster service was stopped. Each restores the verified predecessor and +quarantines the release on that Mac. The Mac's progress then reports the +quarantined release beside the version it runs +(`ClusterPairUpdateProgress.quarantined`), and the other Mac reads it over the +link with the rest of the progress. + +The other Mac's supervisor checks for a rollback to follow at its start and +then every `ClusterPairUpdate.followCheckSeconds` (60 s) while no update cycle +runs, also with automatic updates off: the release it restores is one the Mac +ran before. It follows (`ClusterPairUpdateCycle.followRollback`) when the other +Mac quarantined the release this Mac runs (installed or promoted) and runs the +release this Mac keeps for rollback. The check reads both Macs' recovery state +without the update lease; only a Mac that runs the quarantined release and keeps +the other Mac's release for rollback takes the lease and verifies it. The follow is the update cycle's sequence +with a rollback in place of the install: + +1. It takes the update lease, the one every update cycle, candidate recovery + and `darkbloom update --rollback` take, and decides again under it. Another + holder (this Mac's own cycle, still installing or restarting) makes it wait + for the next check, with nothing changed. +2. It waits until the other Mac reports the earlier release (it does already, + so this is at once), then drains this Mac's part as for an update. An other + Mac that stops answering is waited for at most + `ClusterPairUpdate.progressStaleSeconds` (60 s) while a pair runs on this + Mac. The follow is then deferred with the reason `the other Mac did not + confirm it runs v within 60 s`, nothing is changed, and it is tried + again at the pair's next update slot, as a deferred update is. With no pair + running on this Mac, it follows alone, as an update goes on alone. +3. It restores the verified predecessor and quarantines the release + (`SelfUpdater.rollBackToPredecessor`), with the reason `the other Mac of the + pair rolled v back to v; this Mac followed`. Both Macs + now keep the release quarantined: neither's update slot installs it again, + and a Mac whose partner reports the release quarantined gives it up too + (`ClusterPairUpdate.partnerState`). The next newer release updates both. +4. The supervisor restarts the cluster service from the restored binary, after + the same start check as for an update. Once both Macs answer with the same + build, the leader plans the model again. + +It does not follow, changes nothing, and says why once in its log +(`cluster update: not following the other Mac's rollback: `) when: + +- it keeps another release for rollback, or none: the pair serves again once a + newer release updates both Macs; +- its part does not drain for an update (it serves on the leader's local API, + or alone): it follows once its part can drain. + +The Mac that rolled back says once `cluster update: the other Mac still runs +v, which is quarantined on this Mac` while the other Mac has not +followed, or has installed the release again on purpose. Other lines: +`cluster update: the other Mac rolled v back to v and +quarantined it; this Mac follows to v` and `cluster update: restored +v and quarantined v, as on the other Mac`. + +To install a release both Macs quarantined anyway, run `darkbloom update +--override-quarantine` on both Macs: the cycle the first command starts waits, +while serving, for the other Mac's, as for `darkbloom update` with automatic +updates off. An update slot, by contrast, gives up a release the other Mac +reports quarantined. Right after an override, the other Mac may still read the +old quarantine for up to a minute and follow it. + +Both Macs need a build that follows rollbacks. The quarantine is reported by +the Mac that rolled back after the rollback, so by the restored release's +binary: a rollback *to* a release without this behaviour is not reported, and +the other Mac does not follow it. The first release with this behaviour is +therefore not followed when it is itself rolled back; rollbacks from the +release after it on are. The other Mac must run a build with the follow too. + +A cluster-member provider service (`darkbloom start --cluster-member +--always-on`) does not run this coordinated update and does not follow a +rollback: roll back both Macs. + +After both Macs restarted, the leader's cluster service plans the same model +again once both answer with the same worker build +(`ClusterOnboardingUpdate.oneBuild`), and the pair registers again under the +new release's cluster approval. Each step is one `cluster update:` line in +`~/.darkbloom/cluster-setup/service.log`, for example `cluster update: waiting +for the other Mac to have v`, `cluster update: this Mac's part finished +its accepted requests`, `cluster update: installed v`, `cluster update +deferred: ; no request was cancelled; the next update slot tries again`, +`cluster update: v failed its start check (), so the supervisor +does not restart into it; restored v and quarantined v`, +`cluster update: starting the cluster service on candidate v` and +`cluster update: this Mac's part serves again on v`. + ## Permissions asked once One administrator approval sets up the cluster link per Mac; macOS then decides @@ -184,6 +343,7 @@ system setting: | Follower never connects; log shows `Local network prohibited` | **Privacy & Security → Local Network** | Turn on Darkbloom; an ad-hoc build needs this per build | | A firewall alert after an update | `codesign -dv` on the listening binary | The binary is not Developer-ID signed; install the release build | | Install or provider log says `permissions: not asked once` | The listed reasons | Install the signed release (a locally built binary is ad-hoc signed and outside `Darkbloom.app`) | +| The pair does not update | `cluster update:` lines in `~/.darkbloom/cluster-setup/service.log` on both Macs | `automatic updates are off`: run `darkbloom update` on both Macs, or set `auto_update` on both (`darkbloom autoupdate enable`), which takes effect when the cluster service next starts (at login, or after its next update). `deferred`: a request ran past 120 s, or one Mac could not take the release; the next slot tries again. `does not drain for an update`: the pair serves on the local API or a Mac serves alone. `failed its start check`: the release did not start on this Mac, which keeps its previous release and does not install that release again; the other Mac follows it back ([a rollback on one Mac](#a-rollback-on-one-mac)), and a newer release updates both. `not following the other Mac's rollback` or `the other Mac still runs`: see [a rollback on one Mac](#a-rollback-on-one-mac) | ## Developer: a coordinator-paired member as a service @@ -254,7 +414,7 @@ it. It documents the developer route that runs `darkbloom start | The leader's pair engine stays wedged (its own watchdog's verdict) for 180 s | Same recycle | | An active request made no progress at all for `clamp(120, 120 + prompt tokens / 1000, 900)` s (when the member reports one) | Same recycle | | A pair forms | The leader runs one greedy 8-token warmup request before the pair accepts work; if it fails or takes over 300 s the pair is retired and formed again (`DARKBLOOM_CLUSTER_WARMUP=0` turns this off) | -| Cluster update slot (every 30 min, at an offset fixed by the cluster ID, the same on both Macs), on this route only, with `auto_update` on (the default) | If a release is available: drains the member, installs, restarts from the new binary; both Macs do this together. The cluster service of `darkbloom cluster` has no update slot ([updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)) | +| Cluster update slot (every 30 min, at an offset fixed by the cluster ID, the same on both Macs), with `auto_update` on (the default) | On this route, if a release is available and the pair is idle: drains the member, installs, restarts from the new binary. The cluster service of `darkbloom cluster` runs [the pair's coordinated update](#the-pairs-coordinated-update) instead | | `darkbloom stop` | Drains, stops the member and keeps it stopped across reboots | | Before every run, and at the member's own start and end | Orphan sweep: a worker or owner whose parent is gone is given its own contract to end, then SIGTERM, SIGKILL only after the kill margin; a stranded device journal is cleared once nothing it names runs; bootstrap directories whose socket no process holds any more are removed (read from the descriptor tables; nothing connects). One log line when it found something (`darkbloom cluster reap --json` runs the same sweep by hand) | diff --git a/docs/provider/installation.md b/docs/provider/installation.md index 4d777dfbcb..c357d0d2b8 100644 --- a/docs/provider/installation.md +++ b/docs/provider/installation.md @@ -1,6 +1,6 @@ # Install, update, and uninstall the provider -> Last updated: 2026-10-23 +> Last updated: 2026-11-02 How to put the `darkbloom` CLI on an Apple Silicon Mac with `scripts/install.sh`, what the script verifies before it touches an existing install, how the binary @@ -216,6 +216,46 @@ that exact version is blocked; a newer release installs normally. `darkbloom update --override-quarantine` reinstalls it anyway, and `darkbloom doctor` reports the quarantine under `up to date`. +### Roll back to the previous release + +When the updater installs a release, it keeps the signed release it replaced +in `~/.darkbloom/recovery/predecessor/` (`provider-swift/Sources/ProviderCore/Update/UpdateInstallLayout.swift`, +`snapshotLiveAsPredecessor`). A release that runs but regresses can be rolled +back to it on one Mac, with automatic updates left on: + +1. On a Mac that serves in a `darkbloom cluster` pair, first stop its cluster + service with `darkbloom cluster stop`, roll it back, then start it again + with `darkbloom cluster`. The other Mac follows the rollback to the same + release by itself ([the pair's coordinated update](./cluster-always-on.md#a-rollback-on-one-mac)). + For a cluster-member provider service, stop it with `darkbloom stop` and + roll back both Macs. The command refuses while the pair serves. +2. Run the rollback and answer `y`: + + ```bash + darkbloom update --rollback + ``` + + It prints the installed and restored versions first and changes nothing + until you confirm (`--yes` skips the question). The running provider + finishes its accepted requests (`--timeout`, as for `darkbloom update`), + the kept release replaces the installed one in one journaled swap, and the + provider restarts on it. The installed release is quarantined: the + provider's own checks, the startup check and the watchdog skip it, and the + next newer release installs normally. + +Only one earlier release is kept, so a second rollback is refused. To install +the rolled-back release again, run `darkbloom update --override-quarantine`. + +Verify: + +```bash +darkbloom --version # the restored version +darkbloom update --check-only # while vX is the latest: "Latest release vX is quarantined on this machine." +``` + +Refusals and flags are listed in the +[`darkbloom update` reference](./cli-reference.md#darkbloom-update). + If the watchdog exits after starting a candidate but before recording the launch receipt, its next health observations reconcile the saved intent with launchd's run count or process identity for the same job. For each comparison, diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 1b3c147873..8f1ffde203 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -1,6 +1,6 @@ # Provider troubleshooting -> Last updated: 2026-10-27 +> Last updated: 2026-11-02 Symptom → check → fix for the `darkbloom` provider: installer exits, `doctor` check names, service lifecycle, coordinator connection, updates, models and the @@ -148,7 +148,8 @@ tail -50 ~/.darkbloom/provider.log ~/.darkbloom/watchdog.log | Symptom | Cause | Fix | |---|---|---| -| `Latest release vX is quarantined on this machine.` | vX crashed `rollbackThreshold` times before surviving `defaultStabilizationSeconds` (`provider-swift/Sources/ProviderCore/Update/UpdateRecoveryState.swift`; values in [runtime constants](./cli-reference.md#runtime-constants)) | Wait for the next release (it installs normally), or `darkbloom update --override-quarantine` | +| `Latest release vX is quarantined on this machine.` | vX crashed `rollbackThreshold` times before surviving `defaultStabilizationSeconds`, or was rolled back with `darkbloom update --rollback` (`provider-swift/Sources/ProviderCore/Update/UpdateRecoveryState.swift`; values in [runtime constants](./cli-reference.md#runtime-constants)) | Wait for the next release (it installs normally), or `darkbloom update --override-quarantine` | +| A new release runs but regresses | Automatic updates install every newer release | `darkbloom update --rollback` restores the previous release and quarantines this one; leave automatic updates on ([roll back](./installation.md#roll-back-to-the-previous-release)) | | `vX is already installed on disk but this process is vY.` | Update landed, daemon not restarted | `darkbloom restart` | | `SHA-256 hash mismatch!` | Download ≠ `bundle_hash`/`binary_hash`/`metallib_hash` | Retry; persistent mismatch means the release record and artifact disagree | | `another update/recovery operation is active` | Watchdog recovery or a previous update holds the lock | Wait a minute; retry | @@ -167,7 +168,9 @@ are tabulated in [`cli-reference.md`](./cli-reference.md#runtime-constants). | `model fits in RAM` FAIL / `Cold load blocked (memory)` in status | The live no-eviction load budget is below the scanner's complete model estimate plus activation and minimum-KV serving reserve, and request-time idle eviction cannot close the gap. The nominal `Inference memory` hardware figure is not live free RAM. Status and doctor show both the preload gap and the smaller eviction-aware cold-load gap ([load gate](../architecture/hardware-support.md#load-gate-modelloadadmission)). A busy machine with an active request gets a temporary verdict instead | Free at least the **cold-load** shortfall with margin, rerun `darkbloom doctor`, then `darkbloom restart` to retry preload when enabled; or select a smaller model ([hardware requirements](./hardware-requirements.md)). A request cannot cold-load at the same memory level. | | `Preload skipped (no eviction)` in status | The model does not fit alongside the current resident slots. The request-time allowance can fit it by evicting idle models; startup preload deliberately avoids that churn | Keep the current serving set, or free memory if both models should stay resident. | | A load refusal says `Not evictable: (… GB: …)`, or status says `Not evictable for a load now: …` | That resident model cannot be evicted for the load: an Autopilot placement hold (until the UTC time shown), requests in flight, a local request, an Autopilot pin, an unload or an MTP upgrade in progress. `adopted by Autopilot outside the selected models` means an Autopilot operation placed it there, not your selection ([placements](../architecture/model-autopilot.md#placements-after-an-operation)) | Wait for the hold to expire or the requests to finish, then retry the load; a hold also ends when an operation unloads the model or Autopilot is disabled. | -| `Serving outside the enabled model filter: ` in status | The running daemon serves a model your saved `enabled_models` omits: an Autopilot operation adopted it, it is in the running daemon's selection (a changed filter applies only at the next start), or a live Autopilot lease published it | For an adoption see `darkbloom autopilot status`; otherwise `darkbloom restart` applies the saved filter. | +| `Serving outside the enabled model filter: ` in status | The running daemon serves a model your saved `enabled_models` omits: an Autopilot operation adopted it, it is in the running daemon's selection (a hand-edited filter applies only at the next start), or a live Autopilot lease published it. A coordinator command or model rollout never adds one ([operator filter](../reference/configuration.md#provider-model-selection)); on provider 0.10.6 or earlier, see the next row | For an adoption see `darkbloom autopilot status`; otherwise `darkbloom restart` applies the saved filter. | +| Provider 0.10.6 or earlier: a build you deselected with `darkbloom switch` or deleted with `darkbloom models remove` comes back within minutes, downloads again and replaces the build you selected (for example `gemma-4-26b-qat-4bit` replacing `gemma-4-26b`); status shows `Serving outside the enabled model filter: ` | The coordinator moved a public model you serve to ``, and these providers follow that rollout even when `enabled_models` omits it. It reaches every Mac that serves any build of that public model, including its rollback build (`gemma-4-26b-8bit`) | Update the provider. Until then, serve the newest build (pick the public model's name in `darkbloom switch`) or select no build of that public model; a restart, a new login or selecting the rollback build does not stop it. | +| The log says `desired_models: → is outside the enabled model filter; not converging` | A public model you serve moved to a newer build that your `enabled_models` does not list. The provider keeps serving your build. The coordinator now sends the public model's requests to the newer build first, so your build gets them only when no Mac with the newer build has room | To keep your build, nothing. To take the new build, run `darkbloom switch` and pick the public model's name (the picker shows its newest build under that name and downloads it), with your other models. | | Model missing from `darkbloom models list` | Not in `~/.cache/huggingface/hub`, or filtered by `enabled_models` | `darkbloom models download `; `darkbloom models list --all` | | Load fails after a catalog update | New build published for the alias | `darkbloom models remove ` then `darkbloom models download ` | | `Skipping : model_type … has no engine-v2 adapter` | Family not served by CBv2 | Use a supported family; the model is never advertised | diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index d8688b78b8..b890bccc16 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -1,6 +1,6 @@ # Two Macs as one provider (guided setup) -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 Two Apple Silicon Macs joined by one Thunderbolt 5 cable serve a model together: each Mac holds part of its layers, and the pair serves as one provider. Setting @@ -26,19 +26,77 @@ Remote Login, no IP address and no network setting is typed anywhere. ## The steps, once -Run `darkbloom cluster` on each Mac, pick a model, done. Start on either Mac: it -drives the onboarding screens, chooses the model, sends the other Mac its setup -over the cable and starts it; you never go back to the other Mac. Which Mac -handles commands afterwards is worked out by the cluster itself (see +Run `darkbloom cluster` on each Mac, pick a model, done. The Mac you start on +leads the cluster and keeps leading: it chooses the model, sends the other Mac +its setup over the cable and starts it, and it holds rank 0, where requests +enter and which the coordinator registers (and pays) for the pair. Every plan +puts rank 0 on it, whichever Mac makes the plan, including the plans the +cluster service makes by itself after an update or after a Mac's memory +refused its share (`LiveContext.plan`, `ClusterControlDerivation.planLeader`). +Before a plan exists the cluster's +leader is derived as that Mac (`ClusterControlDerivation.derive`, `preferred`). +The other Mac follows; you never go back to it (see [If a Mac goes away](#if-a-mac-goes-away)). -The screen follows five stages: **Connect**, **Pair**, **Choose**, **Start** and -**Test**. The model list names the choice that Enter selects and explains why -any unavailable model cannot be selected. +The screen follows four steps: **Connect**, **Pair**, **Model** and +**Start**, one line for each thing that happened. Every choice is a list you +move through with ↑ and ↓ and take with enter, as `darkbloom start` picks +models: the answer to the pairing code, the model, how a missing model gets +onto the Macs and, later, what to do with a running cluster. Where the screen +has no color (`NO_COLOR`, `TERM=dumb`, a pipe), the same list is numbered and +one key answers it: a number, enter for the first line, or a letter only one +line starts with (`y` for "Yes"). q or Esc cancels any list, so q never +picks a line such as "Qwen3.8-27B-4bit-mtp · 16.3 GB · pipeline". While the setup waits (for the other Mac, +for Allow), q or Esc stops it and an arrow key does nothing; no prompt asks for +a key to do something. The model list shows only models +approved for clusters (`ClusterPublicModels.declared`: GLM-5.3-Flash, +Qwen3.8 27B, MiMo-V2.6-Flash and Gemma 4 26B QAT) that these two Macs can serve; any other model is left out, and a +model named on the command line that is not approved is refused. + +Each Mac asks for up to two macOS approvals, at stated moments while you are at +that Mac, and Connect's first line says so ("Allow macOS's password and Local +Network prompts."). Each prompt's line says what to click: + +- **Connect:** the cable's port, once per Mac (your password). macOS lets a + command run from a terminal or over SSH onto the local network by itself + (Apple's TN3179), so this command's own probe, one datagram on the cable + (`ClusterLocalNetworkAccess.probe`), asks nothing unless macOS blocks it + anyway; macOS then names the terminal app (Terminal, iTerm, …), or + `sshd-keygen-wrapper` over SSH, and the setup waits for Allow. +- **Right after pairing:** Local Network access for Darkbloom, which this Mac's + cluster service (a launchd agent, which macOS does ask about) asks for as it + starts (`ClusterLocalNetworkAccess.startServiceProbe`). Pairing ends on both + Macs at once, so both ask at the same moment: "Click Allow on the Local + Network prompt for Darkbloom. Allow it on the other Mac too." The setup + waits until Allow ("✓ Allowed"), however long you + take at the other Mac, or until q; after 15 s it also names the switch in + System Settings → Privacy & Security → Local Network. A cluster service that + reports no probe within 10 s (an older build) gets the line as an "if", and + the setup goes on. + +When macOS cannot show its password window (an SSH session with no desktop), +the setup runs the same commands with `sudo` in that terminal ("Type this Mac's +password to set up the cable port."): you type this Mac's password into sudo, +not into Darkbloom, and the setup goes on; if sudo fails, it says "Cable port +not set up. Run `darkbloom cluster` again." Over SSH, Darkbloom's Local +Network prompt still appears on the Mac's own screen, and its line says so +("on this Mac's screen (Screen Sharing if headless)"). + +The Mac that joins ends once paired ("✓ Paired. The other Mac leads.") with one +line: what comes next and whether its window can close ("Done here: the other +Mac chooses the model. You can close this window."; started with +`darkbloom cluster local`, "Done here: run `darkbloom cluster local` on the +other Mac."). A signed Darkbloom.app's login agent keeps serving; without one, +as for a development build, the line ends "Keep this window open." and the Mac +serves only while the window stays open. The leader ends with what serves and +how ("✓ Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning +through Darkbloom)", or "(local only)"), the test ("✓ Test response in 0.61 s"), +whether the windows can close ("Done. You can close both windows.") and, last, +"Run `darkbloom cluster` again to manage it." On a color terminal with a UTF-8 locale and at least 40 columns, setup opens -with the Darkbloom mark, which blooms in pixel by pixel. Each stage's heading -carries a step meter (`●●○○○`). Long work (checking the cable, reading both Macs, +with the Darkbloom mark, which blooms in pixel by pixel. Each step's heading +carries a step meter (`●●○○`). Long work (checking the cable, reading both Macs, planning, loading the model, waiting for the first tokens) shows a live line with a turning petal; the next line of the transcript replaces it. `DARKBLOOM_NO_ANIMATION=1` or `CI` keeps the mark and meter but stops the motion. @@ -51,16 +109,25 @@ recovery steps stay in scrollback, and no credential is printed: the API key lin names `darkbloom local`, which shows it. Setup reports completion only after the test response succeeds. If that request -fails, the saved setup remains available: run `darkbloom cluster`, check its -status, and press `t` to retry the response. +fails, the saved setup remains available: run `darkbloom cluster` on the leader, +check its status, and choose **Test** to try again. + +`darkbloom cluster` run again shows the cluster's status in one line and, on +the leader, a list: **Test**, **Change model** (**Choose a model** when +stopped), **Serve locally** or **Serve through Darkbloom**, **Stop**, **Check +memory is freed** and **Quit**, with **Set up the cable port** first when the +cable moved to a port not set up yet. On the other Mac it shows the status and +"Nothing to do here: manage it on the other Mac (`darkbloom cluster`).": its +part runs by itself, and setting up such a port is the only choice it offers +([below](#when-something-is-in-the-way)). The planner picks tensor parallel or pipeline for your Macs by itself. Phase split is off. A model whose artifact ships a speculative (MTP) head can also decode as speculative rounds across the pipeline, and does by default where its own cross-cable qualification records passed and measured the rounds faster than the plain pipeline of the same placement (this build: Qwen3.8 27B, Qwen3.5 -9B and MiMo V2.6 Flash). The onboarding then says "pipeline with speculative -decoding". A draft is kept only when it is the model's own choice at that +9B and MiMo V2.6 Flash). The plan (`darkbloom cluster plan`) then names the mode +"pipeline with speculative decoding". A draft is kept only when it is the model's own choice at that position, as the verify window computes it; the window's arithmetic differs in its last bits from one-token decode, so, as with the pipeline itself, output matches a single Mac's up to near ties. Your pair's own measured speed-up @@ -88,8 +155,8 @@ coordinator never carries it. So, with the default `[backend] mtp_mode` of With `mtp_mode = "on"`, `darkbloom cluster` keeps the assistant too. That pair is then not offered to the coordinator: its plan says "not offered for public traffic", and it serves on the leader's local API. A serving cluster switched -with `l` or `p` keeps the setup it has; press `m` to plan the model again for -the new way of serving. Public speculative decoding for Qwen pairs needs +with **Serve locally** or **Serve through Darkbloom** keeps the setup it +has; choose **Change model** to plan the model again for the new way of serving. Public speculative decoding for Qwen pairs needs qualification evidence of its own, which no record holds yet. Rules: [Qwen27 TP assistant policy](../reference/configuration.md#qwen27-tp-assistant-policy). @@ -105,32 +172,33 @@ format instruction only, as on one Mac | # | Where | What you do | What it asks | |---|---|---|---| -| 1 | the first Mac | Run `darkbloom cluster`. It checks the Thunderbolt cable ("Cable found.", "Cable ready."). Nobody waits on the cable yet, so it says **"On your other Mac, run `darkbloom cluster`."** and waits (q cancels). With two cables it asks which one to use. | one macOS administrator approval when the selected port needs configuration ("Darkbloom needs network access for the cluster cable") | -| 2 | the other Mac | Run `darkbloom cluster`. The same checks; then it finds the waiting Mac on the cable by itself (no address, no host name). Both screens show the same six-digit code. | its own approval if needed; `y` on each Mac when the codes match | -| 3 | — | The other Mac says **"Paired with the other Mac (). Continue on the other Mac."** Its cluster service now runs; nothing else is ever asked there, also when it was started with `darkbloom cluster local` (it then says to run that on the Mac that leads). macOS may ask once to allow Darkbloom on the local network: allow it. | the Local Network prompt, once | -| 4 | the leader | It shows both Macs' hardware, tagged "(this Mac)" and "(the other Mac)", and every model the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each: size, how it is split, each Mac's share ("this Mac 50% / the other Mac 50%") and the expected speed. A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. A model that has tensor parallel but is split otherwise says why on a short second line (for example "tensor parallel: slower here" or "tensor parallel: link unmeasured"). Models that fit in the Macs' free memory now come first. Choose the model (enter takes the first). A model the other Mac lacks says how it gets there ("copy ... over the Thunderbolt cable (6.1 GB)"). | enter to copy (a copy predicted under 30 s at the speed measured on these Macs starts by itself, `n` within 3 s stops it) | -| 5 | — | Choosing is starting: "Starting on both Macs in 3 s; press n to stop here." The leader saves the setup, sends it to the other Mac over the cable, starts both Macs, waits until both are loaded and answers one test request. | nothing | +| 1 | the first Mac | Run `darkbloom cluster`. Its first line is "Allow macOS's password and Local Network prompts." It checks the Thunderbolt cable ("✓ Cable ready") and Local Network access. Nobody waits on the cable yet, so this Mac leads; its last line is **"Run `darkbloom cluster` on the other Mac."**, and it waits (q cancels). With two cables it asks "Which cable goes to the other Mac?" | the cable's port, once (your password; sudo in this terminal where macOS shows no window); Local Network access for the terminal app only where macOS blocks it | +| 2 | the other Mac | Run `darkbloom cluster`. The same checks; then it finds the waiting Mac on the cable by itself (no address, no host name). Both screens show the same six-digit code ("Code 123 456. Same on the other Mac?"); a Mac that answered first says "Now confirm on the other Mac." | the same as the first Mac; **Yes** on each Mac when the codes match | +| 3 | both Macs | Each says it is paired ("✓ Paired. This Mac leads." on the leader, "✓ Paired. The other Mac leads." on the other Mac). Both cluster services now run, and macOS asks on both Macs at the same moment to let Darkbloom find devices on your local network: click Allow on each; each screen waits for its own ("✓ Allowed"). Nothing else is ever asked on the other Mac; its last line is "Done here: the other Mac chooses the model. You can close this window." | Local Network access for Darkbloom, once on each Mac | +| 4 | the leader | It lists every model approved for clusters that the pair can serve (held by both Macs, by one of them, or in Darkbloom's catalog), one line each with its size and how the planner splits it, "tensor parallel" or "pipeline" ("Qwen3.8-27B-4bit-mtp · 16.3 GB · pipeline"), ending "copy" or "download" when the model must reach a Mac first (a model no Mac holds yet is split once it arrives, so its line has no split). A model a Mac holds twice (a catalog download beside the cluster's own copy) is listed once. The planner records why a model that has tensor parallel is split otherwise (for example "tensor parallel: slower here", "tensor parallel: not measured yet" or "tensor parallel: link unmeasured"); `darkbloom cluster plan` gives the full reason under "Tensor parallel or pipeline". Models that fit in the Macs' free memory now come first; one that does not ends with "does not fit now". Choose the model with ↑↓ and enter (enter takes the first). If the other Mac does not answer over the cable (its Darkbloom prompt may still wait for Allow), it offers **Try again** or **Cancel**. | the copy first in a list; a short one says its time ("Copy to the other Mac (about 7 s)") | +| 5 | — | Choosing is starting: the leader saves the setup, sends it to the other Mac over the cable and starts both Macs; once both are loaded it says where and how the pair serves ("✓ Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom)", or "(local only)") and answers one test request ("✓ Test response in 0.61 s"). | nothing | -When it serves, the screen says how in one line, for example: +When it serves, the screen says where in one line, for example: ``` -Serving Qwen3.8-27B across both Macs: pipeline, the other Mac 40 layers / this Mac 24 layers. -API at http://localhost:8000 on the other Mac (Apple M3 Ultra, 256 GB). +✓ Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 (earning through Darkbloom) ``` Every screen names the Macs from where it is shown: "this Mac" is the Mac the -screen is on and "the other Mac (Apple M3 Ultra, 256 GB)" the other one, by the -hardware name pairing showed (never a host or computer name). Two Macs of one -kind share that name, so it never stands alone. A Mac that does not lead shows -the leader's answers in the same words for its own screen. +screen is on and "the other Mac" the other one. A line that must tell them +apart adds the hardware name pairing showed ("the other Mac (Apple M3 Ultra, +256 GB)"), never its host or computer name; only this Mac's own screen names it +as System Settings does ("This Mac (Studio A) leads"). A Mac that does not lead +shows the leader's answers in the same words for its own screen. When the coordinator in your provider configuration cannot take a cluster member yet (it is unreachable, or it has no cluster support), the pair still serves, on the leader's local API only, with the same local token as -`darkbloom start --local`, and a third line says so: +`darkbloom start --local`, and its serving line ends "(local only)" instead of +"(earning through Darkbloom)". The leader's part logs why: ``` -Serving locally on this Mac's API; public serving needs a coordinator with cluster support. +Notice: Serving locally on this Mac's API; public serving needs a coordinator with cluster support ``` Nothing to do: the next start registers with the coordinator once it supports @@ -156,6 +224,9 @@ pair's model and split; a release's cluster runtime facts carry them for GLM-5.3-Flash and Qwen3.8-27B ([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair)). A tensor-parallel pair registers like a pipeline one; its plan names no cut. +A Gemma 4 pipeline pair whose plan prefills serially takes several requests at +once; one planned with the one-chunk lookahead takes one at a time +([Gemma pipeline lanes](../architecture/inference.md#gemma-pipeline-lanes)). 1. Run `darkbloom cluster` and choose a model, as in [the steps](#the-steps-once). After the Test stage passes, the leader reads the approvals the coordinator @@ -166,14 +237,14 @@ A tensor-parallel pair registers like a pipeline one; its plan names no cut. ([model approvals](../reference/configuration.md#model-approvals)). Each Mac checks it against its own files, and both Macs save it, or neither does. Both Macs then start their parts again as cluster members. -2. Read the ready screen. Instead of the API line it says: +2. Read the end of the setup screen. After the test response it says: ``` Registered with the coordinator as a cluster member: approval , until . ``` - There is no local API in this mode. `darkbloom cluster` status shows the - same line. + There is no local API in this mode. `darkbloom cluster` status says it after + the model: `Serving : Registered with the coordinator as a cluster member: approval , until .` An approval ends at its `not_after`, which the operator sets; one derived from a release ends 90 days after that release registered @@ -204,30 +275,33 @@ What `darkbloom cluster` status says in each mode: | Mode | Status line | |---|---| -| Registered | `Registered with the coordinator as a cluster member: approval , until .` | -| Coordinator gave no answer for the grace | The API line, then `The coordinator has not answered for 10 minutes: the pair serves on the leader's local API until it answers again, then it is offered again with approval .` | -| Approval no longer listed | The API line, then `The coordinator no longer lists cluster approval : the pair serves on the leader's local API until it lists a matching one again.` | -| Parts kept ending | The API line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists.` | -| Approval ended | The API line, then one line that says the cluster approval `` expired and the pair serves on the leader's local API | -| No approval (staging, production before its coordinator derives approvals from releases, no matching entry) | The API line, then (only after a refusal) `Not offered for pairing: .` | +| Registered | `Serving : Registered with the coordinator as a cluster member: approval , until .` | +| Coordinator gave no answer for the grace | The serving line, then `The coordinator has not answered for 10 minutes: the pair serves on the leader's local API until it answers again, then it is offered again with approval .` | +| Approval no longer listed | The serving line, then `The coordinator no longer lists cluster approval : the pair serves on the leader's local API until it lists a matching one again.` | +| Parts kept ending | The serving line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists.` | +| Approval ended | The serving line, then one line that says the cluster approval `` expired and the pair serves on the leader's local API | +| No approval (staging, production before its coordinator derives approvals from releases, no matching entry) | The serving line, then (only after a refusal) `Not offered for pairing: .` | Approval sources, checks and saved fields: [coordinator-paired member](../reference/configuration.md#coordinator-paired-member). -Counting every key: `y` on the other Mac, and `y` and enter on the leader -(three keys), plus at most one macOS approval per Mac. +Counting every key: enter for **Yes** on each Mac and enter for the first +model on the leader (three keys), plus the macOS prompts [above](#the-steps-once). Running `darkbloom cluster` again on either Mac opens with the same Darkbloom -mark, beside "Darkbloom cluster" and what can be done there ("Status / Test / -Change model / Stop"), and shows the same menu: the -cluster's state (the deployment line first), a test request (`t`), another -model (`m`), stopping (`s`) and a check that both Macs released their memory -(`v`). When it is stopped, `m` chooses a model and serves again. On a Mac that -does not handle commands, each choice is sent over the cable to the Mac that -does, and its answer is shown as it is. +mark, beside "Darkbloom cluster" and the part this Mac plays ("This Mac leads", +or "This Mac follows the other Mac"; with the name System Settings gives this +Mac, "This Mac (Studio A) leads", so two identical Macs each say which they +are), then shows the cluster's state in one line ("Serving +Qwen3.8-27B-4bit-mtp at http://localhost:8000 (earning through Darkbloom).", +or "Stopped; last model …") and, on the leader, the list +[above](#the-steps-once). The other Mac ends with "Nothing to do here: manage +it on the other Mac (`darkbloom cluster`).", or, when the cable moved to a port +not set up yet, offers to set it up ([below](#when-something-is-in-the-way)). If both Macs start waiting at the same moment, the pairing's own rule picks one -to keep waiting (it leads) and the other says so and joins it. +to keep waiting (it leads) and the other joins it ("✓ Paired. The other Mac +leads."). ## Serving locally only @@ -246,16 +320,15 @@ decodes with its speculative assistant under the default `mtp_mode` ``` Not paired yet, it pairs first as in [the steps](#the-steps-once). Name a - model to skip the list: `darkbloom cluster local Qwen3.5-9B` (its id or the + model to skip the list: `darkbloom cluster local glm-5.3-flash` (its id or the name the list shows). On a cluster that already serves, it switches the cluster to local only and waits until it serves again. On the Mac that joins - a waiting leader, it pairs and stops there like `darkbloom cluster`, and says - to run it on the leader. + a waiting leader, it pairs and stops there like `darkbloom cluster`; its last + line says to continue on the leader with `darkbloom cluster local`. 2. Read the API's place from the ready screen: ``` - API at http://localhost:8000 on this Mac, and at port 8000 of its LAN or tailnet address. - Serving locally only on this Mac's API: no coordinator, no public traffic. + ✓ Serving Qwen3.8-27B-4bit-mtp (pipeline) at http://localhost:8000 and on the network (local only) ``` 3. Get the key: `darkbloom local` on the Mac the screen names prints the base @@ -270,8 +343,9 @@ Mac or reach it over a tailnet (encrypted). With the macOS firewall on, macOS may ask once to let Darkbloom accept incoming connections. The choice is kept: after a restart or reboot both Macs serve locally only -again, until you switch back. In `darkbloom cluster`, `p` serves through -Darkbloom again and `l` serves locally only; on a serving cluster the leading +again, until you switch back. In `darkbloom cluster` on the leader, **Serve +through Darkbloom** serves through Darkbloom again and **Serve locally** +serves locally only; on a serving cluster the leading Mac's part restarts that way and the screen waits for it. The model list still reads Darkbloom's catalog when the network is up (to download a model neither Mac has); with no network, it lists the models already on the Macs. Only @@ -321,9 +395,9 @@ require a pipeline layer cut. An unsupported model or rank count falls back to pipeline when eligible and fitting, without requesting a link measurement. Where tensor parallel fits both Macs' memory as they are now, it is chosen, also on a new pair whose link no load has measured yet. A pipeline is chosen -when only a pipeline fits now, and stays until the pair is planned again (`m` -in `darkbloom cluster`, or after a Darkbloom update). Changing the model of a -serving cluster (`m`, or `darkbloom cluster local `) plans again once both +when only a pipeline fits now, and stays until the pair is planned again (**Change +model** in `darkbloom cluster`, or after a Darkbloom update). Changing the model of a +serving cluster (**Change model**, or `darkbloom cluster local `) plans again once both Macs have stopped their parts and given back their memory, so the memory the running model held does not turn tensor parallel into a pipeline. Every load records the encrypted link's cost for later predictions; plans use the median of the @@ -333,6 +407,63 @@ requests; the plan counts its NextN (MTP) layer on both Macs and its speculative decoding ([GLM tensor parallel](../architecture/inference.md#exact-quote-placement)). GLM-5.3-Flash has both a pipeline and a tensor-parallel adapter; its private image candidate is pipeline-only. + +Models that run tensor parallel, and when: + +| Model | Tensor parallel chosen | Notes | +|---|---|---| +| Qwen3.5 9B, Qwen3.8 27B, Qwen3.5/3.6 35B A3B | wherever it fits | Qwen3.8 27B keeps images, video and logprobs only in tensor parallel | +| GLM-5.3-Flash | wherever it fits | Eight concurrent requests by default | +| Gemma 4 26B (QAT 4-bit, 8-bit) | only where the plan predicts it faster from its own measured speed on both Macs (it keeps every feature of the pipeline, prompt-prefix and SSD reuse included) | Text only; logprobs in tensor parallel only; one request at a time unless you set `DARKBLOOM_CLUSTER_BATCH_LANES` | +| MiMo V2.6 Flash | only where it keeps every feature of the mode it would replace (it keeps the speculative pipeline's rounds, not the plain pipeline's batch lanes) and the plan predicts it faster from its own measured speed on both Macs | Text only; speculative decoding; logprobs in tensor parallel only; one request at a time; see [MiMo V2.6 Flash on the pair](#mimo-v26-flash-on-the-pair) | + +For Gemma 4 and MiMo V2.6 Flash, tensor parallel must first keep every feature +and caching behavior of the mode it would replace, as the installed cluster +worker declares them: prompt-prefix and SSD cache reuse, speculative rounds, +batch lanes, media, penalties and logit bias, stop handling and logprobs. What it +adds, such as logprobs where the pipeline has none, never counts against it. +Gemma 4's tensor parallel keeps every feature of its pipeline, prompt-prefix +and SSD reuse included, so speed decides there (below). MiMo's tensor parallel decodes in speculative rounds and keeps every +feature of the speculative pipeline, so speed decides there (below); it is held +back only where the plain pipeline, with its batch lanes, is the mode it would +replace. Where tensor parallel is held back: + +- The plan's "Tensor parallel or pipeline" line says what tensor parallel would + drop ("Pipeline: tensor parallel would drop batch lanes up to 8 (it serves 1) + that the pipeline keeps; held back until it keeps them."), and the model list + says "tensor parallel: drops a feature". +- Where only tensor parallel fits the two Macs, the plan refuses and saves no + setup ("Only tensor parallel fits these Macs, and it would drop ... No + reduced-feature setup was saved."). +- The developer's forced mode (`DARKBLOOM_CLUSTER_FORCE_MODE`, debug builds only) + still places tensor parallel, and the plan says exactly what it drops. + +See [feature parity before tensor parallel](../architecture/inference.md#gemma-tensor-parallel-placement). + +Where tensor parallel keeps every feature, the plan also uses it only when +tensor parallel's own speed has been measured on both Macs. That measurement +is a timing a tensor-parallel load takes of each Mac's half (Gemma), or requests +this Darkbloom build served in tensor parallel. An estimate from each Mac's +device index alone never chooses it: the index overstates how much a half saves +on big Macs. Until then the pair serves the pipeline, as follows: + +- Before a load has measured the link, the plan prices tensor parallel on a + slow assumed link, so two big Macs keep the pipeline. +- Where the estimate says tensor parallel would be faster, the plan's "Tensor + parallel or pipeline" line says so and keeps the pipeline ("Pipeline: tensor + parallel is predicted 6% faster ..., but from the device index, not its own + measured step; it can be chosen once its step is measured on both Macs ..."). The + model list then says "tensor parallel: not measured yet". This holds for short + prompts with longer answers on two M5 Ultra once the link is measured, and on + smaller Macs whose decode is limited by memory bandwidth (for example two 24 + or 32 GB M4 Pro). +- Once both Macs' speeds in tensor parallel are measured, the plan compares + those, and a tensor-parallel choice ends with "on its own step as measured on + both Macs". + +A normal setup does not load tensor parallel just to measure it, so pairs keep +the pipeline for these models today +([evidence before tensor parallel](../architecture/inference.md#gemma-tensor-parallel-placement)). See the [placement planner](../../libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift) and [mode explanation](../../libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift). @@ -358,8 +489,8 @@ under the near-tie rule) do two things only: counts for nothing. The coordinator's parity qualification still decides each public placement. -A model or mode with no passing record is served for you, and the plan and the -onboarding say in one line: "not yet qualified for public traffic". +A model or mode with no passing record is served for you, and the plan says in +one line: "not yet qualified for public traffic". Time budgets (startup, first token, stop) are derived from the setup and the installed artifact, not from a per-model table: @@ -432,8 +563,12 @@ The cluster keeps itself running. When one Mac goes away (turned off, asleep, cable out), the other keeps its part ready for 10 minutes; if the Mac comes back in that time, the cluster re-forms with nothing to do. After that, a Mac that can hold the model alone serves it alone until the other Mac is back, and -`darkbloom cluster` on it says so. Commands typed on either Mac keep working: -they are handled by whichever Mac runs the cluster now. +`darkbloom cluster` on it says so. When the Mac you set up on is back, it leads +again (it holds rank 0). A pair set up with Darkbloom 0.10.6, on which the Mac +that joined took over leading, moves back to the Mac you set up on at its next +plan: normally the re-plan after its update, which restarts both parts anyway. +Manage the cluster on the Mac that leads; on the other +Mac, `darkbloom cluster` shows the status and names the Mac to use. ## How the split is chosen @@ -459,14 +594,21 @@ for 30 days) and the next plan balances the shares by them, with no step from you. For example, with the timings an M3 Ultra and an M5 Max measured for Qwen3.8 27B, a pair first split 2:1 toward the M3 Ultra is planned 1:1 after one load. A split that gives a Mac more is still chosen only when that Mac's -memory holds its share. +memory holds its share. Unequal shares are for a pair that serves you alone +(`darkbloom cluster local`): a pair served through Darkbloom is always planned +with equal shares, because its registration with the coordinator cannot name +unequal ones yet. A pair saved with unequal shares is not offered for pairing, +and its status says why; press `m` in `darkbloom cluster` to plan it again. ## Prompt prefixes on the pair Both Macs keep the prompt prefixes of every model family, in memory and in the encrypted SSD tier: a repeated long prompt starts with its prefix restored, and after both Macs restart the SSD tier gives it back. Gemma 4 keeps each -sliding-window layer's window at every kept frontier; GLM-5.3-Flash in pipeline +sliding-window layer's window at every kept frontier, in pipeline and in tensor +parallel, where each Mac keeps its own half of every layer's heads and a prefix +is restored only when both Macs hold it, with exactly the tokens of a request +that prefilled the whole prompt; GLM-5.3-Flash in pipeline keeps its attention history once per prompt and its linear-attention state per frontier. GLM-5.3-Flash in tensor parallel keeps one boundary per prompt, the last whole 4,096-token chunk before its final token: each Mac writes its own @@ -514,6 +656,35 @@ in memory and in the encrypted SSD tier, like the Qwen models. MiMo has no paged KV on the pair yet, and the pair decodes slower than the M5 Ultra alone. Its phase split (one Mac decodes alone) is kept off like every hand-off mode. +MiMo V2.6 Flash text can also run tensor parallel: each Mac holds half of every +layer, about 84 GB of weights, and MiMo's three draft heads whole (about 2 GB), +about 100 GiB in all with its reserves +([rank memory](../architecture/hardware-support.md#mimo-v26-tensor-parallel-rank-memory)), +so two 128 GB Macs that cannot hold MiMo alone can serve it. It decodes with +speculative decoding by default, as the pipeline does, so it keeps the speculative +pipeline's features. Where the plain pipeline is the mode it would replace, its +batch lanes keep the pipeline. Speed decides after that: tensor parallel must be +predicted faster than the speculative pipeline, which MiMo's qualification +records credit 1.37x, from tensor parallel's own speed measured on both Macs. The +plan credits tensor parallel's own rounds nothing until they are measured: + +- Before a load has measured the link, two 128 GB Macs and two 256 GB Macs + alike keep the pipeline. +- After that, on a fast Thunderbolt 5 link, tensor parallel is predicted faster + for most requests, including a new pair's longest prompt and answer, but only + from the Macs' device index, so the pipeline is kept. A long prompt with a + short answer (for example 8,192 + 128 tokens) or a slow link keeps it anyway. +- MiMo does not yet time its halves when it loads tensor parallel. Only + requests this Darkbloom build served in tensor parallel measure it, so MiMo + pairs keep the pipeline today. + +In tensor parallel MiMo returns logprobs, serves one request at a time and +decodes with speculative decoding (up to two drafted tokens a round); its output +is the same as without drafting. The image candidate stays a pipeline. Speed +on a real pair is not measured yet. No qualification record covers MiMo tensor +parallel yet, so its grant names only the modes above and a tensor-parallel +MiMo pair serves its owner's local endpoint. + ### After a restart Each Mac's cluster service runs that Mac's part while the leader has the @@ -533,41 +704,67 @@ happens by itself; `darkbloom cluster` says which applies to each Mac. ## Updating Darkbloom on the pair -The Macs of a pair do not update by themselves. The cluster service runs with -automatic updates off, its parts run no updater, and the single-Mac provider, -whose updater keeps one Mac current, does not run beside the cluster. -Automatic updates for a pair are a follow-up. Until then, update by hand: - -1. On each Mac, run: - - ```bash - darkbloom update - ``` +The Macs of a pair update themselves together, as a single Mac does, while +`auto_update` is on (the default) and `DARKBLOOM_NO_UPDATE_CHECK` is not set on +either Mac. Nothing needs to be run. Every 30 minutes, at the pair's update slot +(a time fixed by the pairing's cluster ID, the same on both Macs), each Mac's +cluster service asks the coordinator for its latest release: + +1. Each Mac downloads, verifies and stages the release while the pair serves. +2. Once both Macs have it, the pair stops taking new requests. The Mac that + serves the pair finishes the requests it accepted, within 120 seconds, and + never cancels one. +3. Both Macs install the release and restart their cluster services from it. +4. The leader plans the same model again for the new release once both Macs + answer with it, and the pair registers again under that release's cluster + approval. The log says `Darkbloom changed on both Macs: setting the cluster + up again for `. + +A pair still running a request after 120 seconds takes requests again and tries +at the next slot. A release that one Mac cannot download or verify is installed +on neither Mac; both try again at the next slot. Until a new +release's cluster service has stayed healthy for 10 minutes, three of its starts +that end by themselves bring back the previous release and quarantine the new +one, as the watchdog does for a single Mac. A Mac never restarts into a new +release that does not start at all (it checks before the restart): it brings +back the previous release at once and quarantines the new one. When one Mac +brings back the previous release this way, or with `darkbloom update +--rollback`, the other Mac brings back the same release and quarantines the new +one too, so the pair serves the previous release together +([a rollback on one Mac](cluster-always-on.md#a-rollback-on-one-mac)). How the +cluster service does this is in +[the pair's coordinated update](cluster-always-on.md#the-pairs-coordinated-update). + +To update at once, run on each Mac: + +```bash +darkbloom update +``` - It installs the release. Its last line, "Restart the provider for the new - version to take effect.", does not apply here: no single-Mac provider runs on - a pair Mac. -2. Wait. The leader compares each Mac's installed cluster worker with the saved - setup every minute while the cluster serves. When one changed, it stops both - parts, plans the same model again and serves it from the new release - ("Updating the cluster setup after a Darkbloom update."). Its log, - `~/.darkbloom/cluster-setup/service.log`, says - `Darkbloom changed on the other Mac: setting the cluster up again for ` - (or this Mac, or both Macs). An update of the second Mac sets it up once more. - While a Mac serves, these checks and any plan made then use the speed it - measured while idle and never run a GPU benchmark beside the model - ([device profile](../architecture/inference.md#automatic-local-cluster-batching)). -3. Log out and back in on each Mac, or restart it. The cluster service itself - keeps running the release it started with until it starts again, as it does - at login. +It installs the release, then asks this Mac's cluster service to restart into it +together with the other Mac, after the pair drained, and prints its progress +(`drained for v; waiting for the other Mac`). Both Macs restart once both +have the release. The Mac where it ran first waits up to 15 minutes, while it +serves, for the other Mac: for its `darkbloom update`, or for its next slot when +its automatic updates are on. +No log-out is needed. A cluster service started by an earlier release cannot do +this: log out and back in on both Macs once both have the release. + +While a Mac serves, the re-plan uses the speed it measured while idle and never +runs a GPU benchmark beside the model +([device profile](../architecture/inference.md#automatic-local-cluster-batching)). +A pair that serves on the leader's local API, or a Mac that serves alone, is not +drained for an update yet: its update waits while it serves (the log says +`this Mac's part does not drain for an update`). ## When something is in the way - **No macOS prompt can be shown** (for example with no one logged in to the desktop): the check writes the exact commands the prompt would run to an owner-only - script and prints one line to run once as an administrator: - `sudo sh ~/.darkbloom/cluster-device/link-fix.sh`; then run - `darkbloom cluster` again. A port an administrator already isolated this way + script, and the setup runs it with `sudo` in the same terminal (type this + Mac's password into sudo). If that fails, it says "Cable port not set up. Run + `darkbloom cluster` again."; an administrator can also run the script once, + `sudo sh ~/.darkbloom/cluster-device/link-fix.sh`, then `darkbloom cluster` again. A port an administrator already isolated this way is recognised and recorded (no change, no prompt). - **Internet Sharing shares to the cluster port itself**: the check says so and stops before any prompt. Turn the cluster port off under System Settings → @@ -575,27 +772,42 @@ Automatic updates for a pair are a follow-up. Until then, update by hand: `darkbloom cluster` again. - **The cable moved to another Thunderbolt port**: an already configured port is reused without another configuration prompt. For a port not yet configured, - run `darkbloom cluster` and press `f` when offered; macOS asks for administrator + run `darkbloom cluster` and choose **Set up the cable port** when offered; macOS asks for administrator approval to configure that port. Recovery RDMA enablement and Local Network privacy permission remain separate steps. +- **The Macs were paired again** while their cluster services ran + (`darkbloom cluster` or `darkbloom cluster pair`): each service answers with + the new pairing within seconds, and its log, + `~/.darkbloom/cluster-setup/service.log`, says `this Mac's pairing changed` + ([listeners](../architecture/inference.md#cluster-service-listeners-follow-the-cable-and-the-pairing)). + If the other Mac still refuses the connection (`refused (handshakeRejected)`), + restart its service, since one an earlier release started keeps the earlier + pairing: on that Mac, run `darkbloom cluster stop`, then `darkbloom cluster`. - **A part keeps ending the same way**: after three identical ends the screen - says it and offers `d`; both Macs keep trying by themselves. + says it and offers **Save diagnostics for Darkbloom**; both Macs + keep trying by themselves. - **The leader cannot reach the other Mac**: make sure the other Mac is on and - logged in; it rejoins by itself. If you denied the Local Network prompt there, + logged in; it rejoins by itself. During setup the leader offers **Try again** + and **Cancel**, since the other Mac's Darkbloom prompt may still be waiting + for Allow. If you denied the Local Network prompt there, allow Darkbloom in System Settings → Privacy & Security → Local Network, then run `darkbloom cluster` again. -- **A model is not offered**: the reason is shown beside it, for example "Not - yet qualified on this pair of Macs" (a pair serves a model only where its - cross-cable check passed). A copy the cluster worker does not take, of a - model a pair serves, says so ("supported on a cluster, but this Mac's cluster - worker does not take this copy of it"); the model is listed once when another - copy can be served. -- **A model does not fit now**: it is listed after the ones that fit, with what - frees the memory ("Quit apps on the other Mac (…) first"); the fit is checked +- **A model is not offered**: the list leaves out every model that is not + approved for clusters or that these Macs cannot serve, with no reason beside + it. A model named on the command line says why ("… is not approved for + clusters yet.", or "… can't run on these Macs: ."). When no + approved model can run, the screen says so and gives each reason once, after + the models it holds back, for example "supported on a cluster, but this Mac's + cluster worker does not take this copy of it"; a model is listed once when + another copy of it can be served. +- **A model does not fit now**: it is listed after the ones that fit, ending + "does not fit now". What frees the memory ("Quit apps on the other Mac (…) + first.") is said, and nothing starts, if it still does not fit when checked again right before the start. - **The start does not finish**: the screen shows each Mac's last error and - offers `d` to save a diagnostics file in your home folder (no keys, addresses or - names in it; nothing is written if any would remain). + offers **Save diagnostics for Darkbloom**, which writes a file to + your home folder (no keys, addresses or names in it; nothing is written if any + would remain). ## Undo @@ -620,15 +832,16 @@ and they must match. ## Not yet in this build -- A pair does not update itself: run `darkbloom update` on both Macs +- A pair that serves on the leader's local API, or a Mac that serves alone, + does not update while it serves ([updating Darkbloom on the pair](#updating-darkbloom-on-the-pair)). - The login agent and macOS's one Local Network approval need the signed Darkbloom.app ([always on](cluster-always-on.md)). -- A setup with unequal tensor-parallel shares cannot register with the - coordinator yet. +- A pair served through Darkbloom cannot use unequal tensor-parallel shares + yet: on two different Macs it is planned 1:1, so the slower Mac sets the pace + ([how the split is chosen](#how-the-split-is-chosen)). - A member cannot yet download a catalog model itself (the leader downloads and - copies), and a model change typed on a Mac that does not lead cannot copy a - model (run it on the leader). + copies). ## Developer notes @@ -650,7 +863,7 @@ Nothing here is needed to use the cluster. For background serving, install the same signed `Darkbloom.app` on each Mac and approve Local Network access on each when macOS asks. The setup installs a login agent associated with that app. After leaving both setup terminals, reopen -`darkbloom cluster` on either Mac and test a response. An ad-hoc development +`darkbloom cluster` on the leader and test a response. An ad-hoc development service can lose outbound access when its originating session closes; use the signed app instead of extending lease timeouts. See [background service permissions](cluster-always-on.md#permissions-asked-once). diff --git a/docs/reference/app-attest-shadow.md b/docs/reference/app-attest-shadow.md index 7e206c0324..5f969d15c1 100644 --- a/docs/reference/app-attest-shadow.md +++ b/docs/reference/app-attest-shadow.md @@ -1,6 +1,6 @@ # App Attest shadow protocol, machine inventory, and evidence -> Last updated: 2026-10-13 +> Last updated: 2026-11-03 App Attest shadow collection records stable machine identities, fleet adoption, submitted proofs and receipts alongside legacy verification. Shadow alone changes no routing, rewards or trust. The separately enabled [provider authorization path](provider-authorization.md) uses qualified evidence for MDM-optional serving and rewards. DeviceCheck's separate two-bit API remains deferred. @@ -50,9 +50,9 @@ Local daemon history is refreshed after every attestation/assertion exchange, no | Field | Type and bounds | Sent on | Source (provider) | Answers | |---|---|---|---|---| -| `process_started_at` | int64 Unix seconds, 2020-01-01 to coordinator now + 1 day | `ready` | Kernel start time of this process (`proc_pidinfo` `pbi_start_tvsec`); an in-place exec (startup self-update) keeps it | With `boot_time`, whether a key died across a reboot or a process restart. | +| `process_started_at` | int64 Unix seconds, 2020-01-01 to coordinator now + 1 day | `ready` | Kernel start time of this process (`proc_pidinfo` `pbi_start_tvsec`); an in-place exec (a self-update of a provider that launchd does not run) keeps it | With `boot_time`, whether a key died across a reboot or a process restart. | | `previous_exit` | `clean`, `unclean`, `unknown` | `ready` | Local marker `provider-run.json` beside `daemon-state.json` (0600): written `running` once the serve process holds the single-instance lock, `clean` after the drain (SIGTERM, CLI stop/restart, schedule end) or right before an update/stall-restart relaunch. Next start: running → `unclean` (crash, SIGKILL/jetsam, power loss, reboot without drain), clean → `clean`, missing/unreadable → `unknown`. A run is identified by the kernel's microsecond start time, so a replacement started within the same second is a new run, while an in-place exec keeps its earlier answer | Whether a clean shutdown preceded a key failure. | -| `start_reason` | `launchd`, `watchdog`, `update`, `stall_restart`, `manual`, `unknown` | `ready` | First match wins; "recent" is a timestamp from 120 s before process start up to classification time (so evidence written after start, e.g. across the in-place exec of a startup self-update, counts): `stall_restart` (recent App Attest stall-restart marker or recorded stall relaunch), `watchdog` (recent watchdog `last_restart_at`), `update` (version differs within the exact same kernel process identity, or recent recorded update relaunch), `manual` (recent CLI lifecycle stop, or not started by launchd), `launchd` (`XPC_SERVICE_NAME` is the provider LaunchAgent label: login/boot/kickstart) | Why this process started. | +| `start_reason` | `launchd`, `watchdog`, `update`, `stall_restart`, `manual`, `unknown` | `ready` | First match wins; "recent" is a timestamp from 120 s before process start up to classification time (so evidence written after start, e.g. across an in-place exec, counts): `stall_restart` (recent App Attest restart marker, written by the stall restart and by the `is_supported_false` restart, or a recorded relaunch of either), `watchdog` (recent watchdog `last_restart_at`), `update` (version differs within the exact same kernel process identity, or recent recorded update relaunch), `manual` (recent CLI lifecycle stop, or not started by launchd), `launchd` (`XPC_SERVICE_NAME` is the provider LaunchAgent label: login/boot/kickstart) | Why this process started. | | `console_user_active` | bool | `ready` | `SCDynamicStoreCopyConsoleUser` returns a user other than `loginwindow`/`root`/`_mbsetupuser` (doctor's console-session rule); `false` when nobody is logged in or the store is unavailable. The name is never sent | With `launch_session = background`: a user is logged in but the provider runs outside that session. | | `sip_enabled` | bool | `ready` | `csrutil status` (`SIPStatusChecker`) reports SIP fully enabled; `false` = disabled or Custom Configuration; omitted when `csrutil` fails or its output is unrecognised. Probed once per process | Whether boot-security changes line up with `isSupported == false`. | | `authenticated_root` | bool | `ready` | `checkAuthenticatedRootEnabled` (`csrutil authenticated-root status`, then `diskutil info /` Sealed); `true` only on a positive result; omitted when neither command ran. Once per process | As above, for the sealed system volume. | @@ -127,6 +127,7 @@ provider-local Apple callback, retry, key-budget and socket fences remain separa | Session recovery | Generic or server-unavailable Apple API failures retry after one minute, then five minutes, then at most the normal ten-minute assertion interval. Other transient coordinator/storage failures retain the one-minute, five-minute, then hourly backoff. Every attempt gets a new session/nonce and reloads durable acceptance/counters. Successful assertions reset backoff. An Apple API error is an unknown prospective verdict and grants no permission; verified crypto/policy rejections remain terminal, and cancellation stops retries. Persistent generic errors still need native domain/code diagnostics from a signed upgraded client. [Dead-key rotation](#dead-key-rotation) and the [invalid-key enrollment backoff](#invalid-key-enrollment-backoff) replace this delay in their specific cases. Code: [coordinator/internal/appattest/recovery/recovery_policy.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/recovery_policy.go) (`ExchangeRetryDelay`), [coordinator/internal/appattest/recovery/driver.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/internal/appattest/recovery/driver.go) (`Driver.Run`); session wiring in [coordinator/appattest/service/retry.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/retry.go) (`run`). | | First-risk-receipt wait | A valid first assertion with no verified risk receipt yet, including an initial `renewal_required` receipt, stays unknown. Without an existing authorization record, a fresh assertion retries after one minute, five minutes, then at the normal ten-minute cadence while Apple's receipt renewal runs independently. Only complete fresh evidence can authorize serving. Code: [coordinator/appattest/service/authorization_identity.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/appattest/service/authorization_identity.go) and `retry.go`. | | Apple callbacks | 25-second waiter deadline. The actual uncancellable Apple operation retains admission until its callback arrives; retries receive `busy` in the meantime. A token fences duplicate late callbacks from unlocking a newer operation. A pre-cancelled call does not acquire admission. The gate records when it was acquired: once held longer than `AppleOperationStall.threshold` (15 min), `ready` replies return `busy` with `operation_stalled_seconds`, and the provider restarts itself through the background-update path (update lease, drain, `waitForSafeDisconnect`, `ProcessLifecycle.restartAfterUpdate`) only when no inference is in flight or loading and no update or lifecycle drain is running, at most once per `AppAttestStallRestartPolicy.minimumInterval` (6 h, persisted in `app-attest-stall-restart.json` beside the daemon state file before the restart is issued). An attempt that drains but cannot restart reopens serving and waits before draining again in the same process: `AppAttestStallRestartPolicy.drainRetryDelay` (15 min) when accepted work or the coordinator's drain acknowledgement did not finish in time, and a full `minimumInterval` when the marker cannot be written, since no restart may be issued without it. After the drain, and after its last suspension point, it checks again (`AppAttestStallRestartPolicy.afterDrain`): if Apple's callback released the gate, or a CLI stop, OS termination or scheduled shutdown took over the drain, it releases the update lease without restarting, and a lifecycle-owned drain stays closed. Code: `AppleOperationGate.swift`, `AppleAppAttestService.swift`, `AppleOperationStall.swift` and `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | +| `isSupported` false after verification | When a `ready` answers `is_supported_false` (macOS 27 or later), the provider restarts once through launchd if all of these hold: the coordinator granted this Mac an App Attest authorization within `AppAttestStallRestartPolicy.verifiedWithin` (7 days) and after the last automatic App Attest restart (the time is kept in `app-attest-verified.json` beside the daemon state file, rewritten at most once per hour), so one unsupported episode gets one restart; the embedded provisioning profile has not expired; this is not a cluster member; and launchd runs this provider (`ProcessLifecycle.RelaunchRoute`: launchd's record of the loaded provider job names this exact process, which an in-place exec keeps). The live `DCAppAttestService.isSupported` must stay false for `AppAttestStallRestartPolicy.unsupportedThreshold` (5 min) and again after the drain. The restart uses the stall restart's monitor, idle checks, drain, `app-attest-stall-restart.json` limit (one automatic App Attest restart per 6 h, for both causes) and `start_reason` `stall_restart`. It never uses an in-place exec. A version that never wrote `app-attest-verified.json` leaves it missing after an update. At serve start, before the provider writes its own daemon state, it then seeds the file once from the previous `daemon-state.json`, with evidence from the last 7 days: the last successful Apple attestation or assertion of a stored key that Apple attested, or (only after an unclean exit) the time of an App Attest grant. So the seeded time can be an Apple success, not a coordinator grant. A previous provider that was itself answering `is_supported_false` published no key, so nothing is seeded and that Mac does not restart until the coordinator grants App Attest again (`DaemonState.appAttestVerifiedAt`, `AppAttestVerifiedMarker.seedFromPreviousRun` in `provider-swift/Sources/ProviderCore/Service/AppAttestVerifiedSeed.swift`). Code: `AppAttestStallRestart.swift` in `provider-swift/Sources/ProviderAppAttest/`; `provider-swift/Sources/ProviderCore/ProviderLoop+AppAttestStall.swift`. | | Coordinator-driven rotation (client side) | An `attest` for a key this client already attested, with no cached proof, clears the key ID and replies `key_unregistered` without calling Apple. The next `prepare` generates a replacement within the per-key one-hour cooldown and the shared five-per-hour generation budget. Released 0.9.8 and 0.9.9 clients behave the same way. Code: `provider-swift/Sources/ProviderAppAttest/AppAttestShadowClient.swift`; pinned by `provider-swift/Tests/ProviderAppAttestTests/StalledOperationAndRotationTests.swift`. | | Attestation retries | At most three attempts, 2/8-second waits, only for service unavailable. `ShadowEnrollmentAttempt` persists the original key/hash, status, session and timestamp across later coordinator retries and reconnects (the provider serves protocol 3 only; an attempt recorded under an earlier protocol is retired), as [Apple requires](https://developer.apple.com/documentation/devicecheck/dcerror-swift.struct/code/serverunavailable). Successful recovery uses the original stored server transaction; a subsequent serving assertion always signs fresh status/challenge/endpoint. Expired or malformed retry state retires under existing generation limits. | | Failed one-time enrollment | Non-service-unavailable Apple failures retire the enrollment key identifier under the existing generation limits. The app persists `attestationStartedAt` before calling Apple; an interrupted attempt without a saved proof is retired on the next prepare. Cached successful proofs remain recoverable. Generic assertion failures do not make the client rotate an accepted key on its own; an explicit invalid-key response can retire it, and the coordinator can request [dead-key rotation](#dead-key-rotation). Code: `provider-swift/Sources/ProviderAppAttest/EnrollmentKeyLifecycle.swift` and `AppAttestShadowClient.swift`. | diff --git a/docs/reference/cluster-control-protocol.md b/docs/reference/cluster-control-protocol.md index 7331c8e124..6c5ad44d4f 100644 --- a/docs/reference/cluster-control-protocol.md +++ b/docs/reference/cluster-control-protocol.md @@ -1,6 +1,6 @@ # Experimental cluster control protocol -> Last updated: 2026-10-29 +> Last updated: 2026-11-01 Exact member-role and native-pair public-control shapes on the provider WebSocket, as staged in draft pull requests: the provider side in this @@ -204,6 +204,7 @@ policy bytes the control requires in a prepare frame | Prepare | The payload's policy must equal the installed policy byte for byte, the start must name this rank, and the frame must leave at most 30 seconds to prepare by this Mac's clock. The member then verifies its installed owner, native executable, metallib and resource library under the device gate and answers `native_pair_prepared` | `provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberSession.swift`, `init` / `runOwned` | | Committed start | `native_pair_owner_start` launches this Mac's installed owner; the owner's native child drives `native_pair_hello` and `native_pair_confirmation`, and `native_pair_owner_released` is sent only after native cleanup, the owner's lease release and the owner's exit were all observed | `runOwned` / `exchange` | | Cancel or expiry | Requests native cleanup at once, independently of signing or the socket. An uncommitted session is dropped and the member can prepare again; a committed one that cannot deliver its release stays quarantined in the control, which then refuses every later attachment | `cancel`; `NativePairMemberControl.finished` | +| Serving on the leader | The leader serves one committed start at a time, from its serve until its session's stop. The stop releases the start at once, then waits for the pair slot to retire before the receipt. So after a lost rank or a fence, the next committed start is accepted even if a serve or the old slot's drain outlasts the session's bounded wait, and its slot cannot publish until the old slot has retired. A start whose session already stopped is never served. The slot's engine cannot deadlock that retirement ([provider inference engine](../architecture/inference.md)) | `provider-swift/Sources/ProviderCore/ProviderLoop+ClusterPairServing.swift`, `serveCommittedStart` / `stopServingCommittedStart`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Engine/DistributedCBv2Engine.swift`, `onQueueWithoutWaiting` | **What a real member does in this build.** The installed owner (`darkbloom cluster worker-owner --stdio`) admits a start the coordinator diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 0aa1e29379..bee14f2780 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-10-31 +> Last updated: 2026-11-02 Provider CLI and native-runtime environment variables, compiled defaults and reading symbols. Secrets are named, never valued. Unless specified otherwise, values are read at process start. @@ -100,6 +100,10 @@ Provider `auto_update`, `idle_timeout_mins`, schedule windows, and startup preloading retain their existing native configuration. The app writes them through the [versioned desktop API](desktop-control.md), using expected revisions. +The Models page reads which models the network registered from the daemon state +file (`registered_models`), not from configuration. It has no setting. See +[model registration](desktop-control.md) in the desktop API. + ## Runtime metallib snapshots The provider creates an anonymous snapshot before binding the runtime metallib. @@ -198,7 +202,7 @@ mode or update configuration changes are part of this addition. | Setting | Default / precedence | Consumer | |---|---|---| -| `backend.enabled_models` | `[]` means all eligible local models; a successful `switch` pins its complete nonempty selection | `provider-swift/Sources/ProviderCore/Service/ProviderModelSelection.swift` (`save`) | +| `backend.enabled_models` | `[]` means all eligible local models; a background `start` and a successful `switch` save their complete nonempty selection. A nonempty list, with the models the daemon started with, is the running daemon's operator filter: without Autopilot, coordinator `load_model`, `prefetch_model` and `desired_models` (including a selected build's alias successor) never load, download or advertise a model outside it. A live `switch` replaces the filter at once; a hand edit applies at the next start. `[]` filters nothing | `provider-swift/Sources/ProviderCore/Service/ProviderModelSelection.swift` (`save`); `provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift` (`operatorFilterAllows`) | | launchd-managed `start --foreground --model` | Explicitly pinned `enabled_models` overrides stale baked arguments, including restart and watchdog recovery | `provider-swift/Sources/darkbloom/Start/StartCommand.swift` (`usesPinnedModelSelection`); `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift` (`runForeground`) | | direct manual `start --foreground --model` | Explicit command-line IDs still override the saved selection | `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift` (`runForeground`) | | later scheduled serving windows | Read full current Autopilot settings/consent plus saved selection. Disabling between windows restores ordinary `enabled_models` even if unchanged; otherwise keep the initial foreground selection until a live switch or saved selection change. Resolve an empty ordinary list to eligible local models, validate/hash before reopening and retain the original window end. With consent, cached Autopilot builds verified at start or by the previous window's provider (downloads and background checks) stay while their bytes hash unchanged. All other inputs remain frozen | `provider-swift/Sources/darkbloom/ScheduledWindowSelection.swift` (`ScheduledWindowSelection`); `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift` (`runScheduled`) | @@ -407,7 +411,7 @@ provider or model command is running. Code: | Variable | Values / type | Default | Read in | Effect | |---|---|---|---|---| -| `DARKBLOOM_NO_UPDATE_CHECK` | any value | unset | `provider-swift/Sources/darkbloom/Darkbloom.swift`; `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift`; `provider-swift/Sources/darkbloom/WatchdogCommand.swift`; `provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift`; forwarded by `provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift` | Skips the startup version banner, the in-daemon auto-update loop, the start-mode check and the watchdog's update check; `scripts/install.sh` sets it for the runtime smoke test. | +| `DARKBLOOM_NO_UPDATE_CHECK` | any value | unset | `provider-swift/Sources/darkbloom/Darkbloom.swift`; `provider-swift/Sources/darkbloom/Start/StartCommand+Modes.swift`; `provider-swift/Sources/darkbloom/WatchdogCommand.swift`; `provider-swift/Sources/ProviderCore/ProviderLoop+AutoUpdate.swift`; `provider-swift/Sources/darkbloom/ClusterServiceCommand.swift` (`supervisorConfiguration`); forwarded by `provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift` | Skips the startup version banner, the in-daemon auto-update loop, the start-mode check, the watchdog's update check and the `darkbloom cluster` pair's update at its slot; `scripts/install.sh` sets it for the runtime smoke test. It does not stop a pair Mac from following the other Mac's rollback to the release it ran before ([a rollback on one Mac](../provider/cluster-always-on.md#a-rollback-on-one-mac)). | | `DARKBLOOM_AUTH_TOKEN_PATH` | file path | `~/.darkbloom/auth_token` | `provider-swift/Sources/ProviderCore/Auth/DeviceAuth.swift` | A nonempty explicit path replaces the token path. Without it, the token is read only from `~/.darkbloom/auth_token` (for `sudo darkbloom report`, the invoking user's, read-only through `AuthTokenStore.loadReadOnly`); there is no legacy-path fallback. | | `DARKBLOOM_LOCAL_DIR` | directory | `~/.darkbloom` | `provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift` | Directory for `local_token` and `local.json` (direct mode). | | `DARKBLOOM_STATE_FILE` | file path | `~/.darkbloom/daemon-state.json` | `provider-swift/Sources/ProviderCore/Service/DaemonStateFile.swift` | Daemon state snapshot read by `status`, `doctor` and the watchdog. | @@ -788,13 +792,14 @@ solo serving is unchanged and the whole surface stays default-off. | Field | Meaning and bounds | Source | |---|---|---| -| `batchLanes` | Optional integer 2, 4 or 8, or 6 for a Qwen TP row in `tensor_parallel_v1`; omitted in existing setups. Only registered text batch adapters in plain pipeline with serial prefill accept it. It is a requested width, never a capacity grant. | `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`validate`) | +| `batchLanes` | Optional integer 2, 4 or 8, or 6 for a Qwen TP row in `tensor_parallel_v1`; omitted in existing setups. Only registered text batch adapters in plain pipeline with serial prefill accept it. It is a requested width, never a capacity grant. The guided setup writes it into both Macs' setups for a Qwen TP placement ([saved width](../architecture/inference.md#qwen-tensor-parallel-saved-width)), and a setup saved for coordinator pairing keeps it beside its approval. | `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`validate`), `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorWidth.swift` (`widest`) | | `DARKBLOOM_CLUSTER_BATCH_LANES` | An explicit diagnostic setting retains precedence; absent settings use the persisted width, then the existing family default. Malformed explicit values fail closed to one lane. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPlan.swift` (`batchLanes`) | The normal cluster API can persist a wider setup after queued demand, conservative memory planning and full release. No environment setting is needed for that path. See [automatic local cluster batching](../architecture/inference.md#automatic-local-cluster-batching) -for exclusions, rollback and the unchanged singleton preference at initial setup. +for exclusions and rollback, and [the saved width](../architecture/inference.md#qwen-tensor-parallel-saved-width) +for a Qwen TP placement's width at initial setup. ### Installed tensor-parallel synchronization @@ -963,20 +968,23 @@ runtime digest, and the provider computes no facts for it | `models[].profile_sha256` | the capability's `profileFingerprint` | | `models[].resource_policy_sha256` | `DistributedInstalledNativeStart.resourcePolicySHA256` of the capability, the value a native start carries | | `models[].pair_serving_grant` | `null`, or exactly `evidence_sha256` and `mode_families` (1 to 4 of `hand_off`, `pipeline`, `pipeline_speculative`, `tensor_parallel`, in byte order). A model the build's public declaration (`ClusterPublicModels`) names by runtime model, catalog ID and artifact: its declared families, with the evidence document's SHA-256. Any other model: the families the build's bundled records grant its artifact (`ClusterPairServingGrants.grant`), with the SHA-256 of the records that grant is computed from (the artifact's passing records, without a pass that a divergence of the same shape contradicts) as canonical JSON Lines (`ClusterPairServingGrant.evidenceSHA256`: each record's `encodedLine` in bundle order, joined by `\n`, no trailing newline); `null` when they grant none | -| `models[].parity_qualifications` | `[]` unless the model is declared; then one object per declared mode family (in byte order: `pipeline`, then `tensor_parallel`) and schedule (ascending), with the fields below. At most 8 | +| `models[].parity_qualifications` | `[]` unless the model is declared; then one object per declared mode family (in byte order: `pipeline`, `pipeline_speculative`, then `tensor_parallel`) and schedule (ascending), with the fields below. At most 8 | | `…schedule` | `1` or `2`: the derived approval it qualifies | | `…numerics_classes` | each rank's `ClusterMemberDeviceProfile.numericsClass` of the evidence placement with this block's `metallib_sha256`, for example `g17d-nax1-mlx-98bab9d7-macos27.0` (Apple M5 Ultra, NAX on, macOS 27.0); two, the members of a derived approval | -| `…mode`, `…cuts` | `pipeline`: `pipeline_v1` cut at `[num_hidden_layers / 2]` (integer division) of the model's `config.json`, read at the top level or else in `text_config` (`[22]` for GLM-5.3-Flash, `[32]` for Qwen3.8-27B); without a layer count the pipeline's qualifications are left out and the command names the family on standard error. `tensor_parallel`: `tensor_parallel_v1`, `[]` (`ClusterPublicModels.placement`) | +| `…mode`, `…cuts` | `pipeline`: `pipeline_v1` cut at `[num_hidden_layers / 2]` (integer division) of the model's `config.json`, read at the top level or else in `text_config` (`[22]` for GLM-5.3-Flash, `[32]` for Qwen3.8-27B, `[24]` for MiMo-V2.6-Flash, `[15]` for Gemma 4 26B QAT); without a layer count the pipeline's qualifications are left out and the command names the family on standard error. `pipeline_speculative` (MiMo-V2.6-Flash): `pipeline_mtp_v1`, cut as the pipeline is. `tensor_parallel`: `tensor_parallel_v1`, `[]` (`ClusterPublicModels.placement`) | | `…tensor_parallel_shares` | `null`: equal shares | | `…promotable`, `…diverged` | `true`, `false` | | `…evidence_sha256` | SHA-256 of the evidence document, [`docs/reports/2026-10-31-public-cluster-models.md`](../reports/2026-10-31-public-cluster-models.md) | -| `…qualified_at` | `2026-10-31T00:00:00Z` | -| `…request_envelope` | `sampling` and `tools` `true`; `max_prompt_tokens` and `max_output_tokens` 1,048,576 (the coordinator's maximum: only the model's own limits apply); where the placement serves media (`ClusterModelFeaturePolicy.mediaContract`: both declared models in tensor parallel; a pipeline is text only), `vision` when the model's catalog entry in the release's environment lists `image` in `input_modalities`, `video` when it also lists `video` (`ClusterPublicModels.requestEnvelope`). A model given by hand has no catalog entry, so its envelope admits text only | +| `…qualified_at` | `2026-11-03T00:00:00Z`, the date of the latest declaration | +| `…request_envelope` | `sampling` and `tools` `true`; `max_prompt_tokens` and `max_output_tokens` 1,048,576 (the coordinator's maximum: only the model's own limits apply); where the placement serves media (`ClusterModelFeaturePolicy.mediaContract`: GLM-5.3-Flash and Qwen3.8-27B in tensor parallel; a pipeline is text only), `vision` when the model's catalog entry in the release's environment lists `image` in `input_modalities`, `video` when it also lists `video` (`ClusterPublicModels.requestEnvelope`). A model given by hand has no catalog entry, so its envelope admits text only | The public declaration names GLM-5.3-Flash (`registered_glm53_flash`, `glm-5.3-flash`) and Qwen3.8-27B (`registered_qwen38_27b`, -`EigenLabs/Qwen3.8-27B-4bit-mtp`), each in `pipeline` and `tensor_parallel` on -schedules 1 and 2, on the owner's decisions of 2026-10-31 +`EigenLabs/Qwen3.8-27B-4bit-mtp`) on the owner's decisions of 2026-10-31, and +MiMo-V2.6-Flash (`registered_mimo_v26_flash_mopd`, `mimo-v2.6-flash-mopd`) and +Gemma 4 26B QAT (`registered_gemma4_26b_qat_4bit`, `gemma-4-26b-qat-4bit`) on +those of 2026-11-03, each in `pipeline` and `tensor_parallel` on schedules 1 +and 2, and MiMo-V2.6-Flash also in `pipeline_speculative`, its default split ([evidence](../reports/2026-10-31-public-cluster-models.md)). Every other model's clusters serve their owner only. @@ -987,11 +995,14 @@ family's promotable records, merged under the request envelope they all allow, on any numerics classes, cuts and shares, unless a diverged record of the same numerics-class combination withholds it ([`parityQualification`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/registry/cluster_parity_qualification.go)). -Under a derived approval, public traffic for GLM-5.3-Flash and Qwen3.8-27B is +Under a derived approval, public traffic for every declared model is therefore admitted in pipeline and tensor parallel on any Apple silicon pair, -within the envelope. No pipeline of either model ran on two Apple M5 Ultras, -and GLM-5.3-Flash has no tensor-parallel cross-cable record: both rest on the -owner's decision of 2026-10-31 and the DevNet serving results. GLM-5.3-Flash's +within the envelope. No pipeline of GLM-5.3-Flash or Qwen3.8-27B ran on two +Apple M5 Ultras, and GLM-5.3-Flash has no tensor-parallel cross-cable record: +both rest on the owner's decision of 2026-10-31 and the DevNet serving results. +MiMo-V2.6-Flash's and Gemma 4 26B QAT's pipelines rest on their bundled records +and the owner's decision of 2026-11-03; their tensor parallel rests on that +decision alone, and serves once its code (#1706, #1707) is in the build. GLM-5.3-Flash's runtime serves only the serial prefill schedule (`supportedPrefillSchedules` of its registered specification), so its schedule 2 approval, grant and qualifications are inert. The setup's public-traffic line says a @@ -1095,7 +1106,7 @@ pair's placement; [serving a pair](cluster-control-protocol.md#serving-a-pair)). |---|---|---| | Fetch | `GET /v1/cluster/approvals`, no query, no credential; HTTPS only (plain HTTP only to this Mac's loopback); no redirect; at most `maximumBytes = 512 * 1024` bytes and `maximumApprovals = 128` entries; `timeoutSeconds = 10`. The body is `darkbloom_cluster_catalog_v2` with `cluster_approvals`. Each entry has the fields of one of the two shapes (build-pinned or model approval); one list can hold both. One unknown, missing or malformed field refuses the whole answer. 404 (pair control off: staging, and production until its coordinator derives approvals from releases) and every failure mean no approval. A read error after an HTTP answer is an answer that cannot be used, not "no answer" | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift` (`ClusterApprovalFetch`) | | Match | The entry whose `model` is the setup's `publicModelID`, whose `schedule` is its prefill schedule (`1` serial, `2` one-chunk lookahead), and that is still current. A model approval matches when its `artifact_sha256` is the saved setup's `capability.artifactSHA256`; no runtime facts are computed for it. A build-pinned entry matches when its eight digests all equal this Mac's own cluster runtime facts (computed at most once per check from the helpers beside the setup's worker and the setup's model folder). Latest `not_after` first, across both shapes. An entry for another build or another copy of the model does not match | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift` (`select`) | -| Check | On each Mac, against its own files: every digest of a build-pinned entry (`ClusterApprovalAttachment.mismatches`), or the artifact of a model approval (refusal: "the approval's artifact_sha256 differs from this Mac's setup"); the member's own start refusals (`requireLocalRankGranted`); the roster of this Mac's pairing (S17); `validate` below | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift` (`attachment`) | +| Check | On each Mac, against its own files: no saved unequal `tensorShares`, which the member's registration cannot name (refusal: "Unequal tensor-parallel shares serve local clusters only …", `unequalTensorSharesServeLocally`; a cluster served through Darkbloom is planned with equal shares, `ClusterPlacementPolicy.equalTensorShares`); every digest of a build-pinned entry (`ClusterApprovalAttachment.mismatches`), or the artifact of a model approval (refusal: "the approval's artifact_sha256 differs from this Mac's setup"); the member's own start refusals (`requireLocalRankGranted`); the roster of this Mac's pairing (S17); `validate` below | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift` (`attachment`) | | Save | Both parts stop. The leader checks the entry, sends it to the other Mac over the cable (service command `approval`), and saves it only after the other Mac checked and saved it. A refusal on either Mac saves it on neither. Both parts then start as cluster members | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift` (`run`, `receive`) | | When | After the guided setup's Test stage passed (control operation `register`, run by the control leader: `OnboardingLive.localRegister`), once at each start of the control leader's cluster service and after an update re-adopted the setups (the re-adopted setups find the same model approval again, because it names no build), and every minute while a serving pair is offered or has its approval kept aside (`ClusterService.checkApproval`). A local-only cluster never asks (`ClusterApprovalSync.asks`) | as named | | Lifetime | A saved approval with more than `renewWithinSeconds = 86_400` left is kept. Within that day a later matching entry replaces it. An entry that the operator replaced under the same `id` (other bytes, for example a new `not_after`) is no longer the saved approval: a matching entry replaces it, else it is withdrawn (Serve locally). An ended one is removed: each Mac saves its setup without it before its part starts, and its part then serves on the leader's local API (`ClusterService.supervise`) | `ClusterApprovalLifetime.decide` | @@ -1619,7 +1630,9 @@ other models (`ClusterRuntimeAdapter.qwenTensorParallelRuntimeModelIDs` names th and inconsistent ledger totals. It reads registered headers and requires the native allocator metadata bound. Saved `batchLanes` may select 2, 4, 6 or 8 in a Qwen TP row's `tensor_parallel_v1`; omission -keeps one. GLM defaults remain unchanged. +keeps one. The guided setup reads the quote at each of these widths +([saved width](../architecture/inference.md#qwen-tensor-parallel-saved-width)). +GLM defaults remain unchanged. Source: `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementTensorBatchQuote.swift`. ### Qwen27 saved mode compatibility @@ -1655,3 +1668,5 @@ Sources: `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/C `provider-swift/Sources/darkbloom/ClusterServiceCommand.swift` (`Cluster.Stop`). The wizard’s optional local stopDrain token is saved with stopped intent and retained after a local timeout. Leases preserve the peer’s prior intent until the local supervisor retires its owned part and outstanding lease. The token is not a wire or user-facing configuration field; older records decode without it. A new serve is refused while it remains, and a model change retries the shared stop first. + +Every write of the wizard's record (`~/.darkbloom/cluster-setup/wizard.json`) takes the `wizard.json.lock` flock. When another writer holds that lock, the write waits up to 2 seconds for it (`ClusterSetupStore.recordLockWaitSeconds`). After 2 seconds the write fails with "Configuration or native device lease is currently held". The cluster service writes the record while it holds its own service lock, so it tries once and writes again on its next supervision cycle. Source: `provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift` (`ClusterSetupStore.updateRecord`). diff --git a/docs/reference/desktop-control.md b/docs/reference/desktop-control.md index 97f624e9af..8e9de73dc7 100644 --- a/docs/reference/desktop-control.md +++ b/docs/reference/desktop-control.md @@ -1,6 +1,6 @@ # Desktop control API -> Last updated: 2026-10-18 +> Last updated: 2026-11-02 The Electron app controls the Swift CLI/backend through its authenticated local API. The backend owns provider operations, configuration, model state, credentials, @@ -231,6 +231,22 @@ The list is the catalog plus every model found on disk, so a local-only model can be `eligible` for Local only yet never be advertised or enrolled in Autopilot (`DesktopBackend.state`). +Each entry also reports `registration`: what the live coordinator registration +carries for the model (`DesktopBackend.modelRegistration`). + +| Value | Meaning | +|---|---| +| `routable` | In the registration's `models`. The network sends it requests. | +| `autopilot` | In `autopilot_inventory` only. Autopilot can load it. | +| `none` | In neither. The network does not know this Mac has it. | +| `null` | Not known: the daemon is stopped, stale, Local only, not connected, a cluster member, or older. | + +The daemon writes the set to `registered_models` in its state file: the +`register` sent on the live connection, plus each written `models_update`, +replaced by an accepted `models_replace` (`ProviderState.registeredModels`). +`serving` is different: it is the selection. The Models page warns when a selected +or pool model is `none` (`ModelRegistration`). + `Snapshot.autopilot` contains `configured` (consent recorded), `enabled`, `paused`, `selected` and `pinned`. Its `phase` is populated only by a fresh live daemon; enrollment alone never implies active control (`DesktopBackend.autopilotSnapshot`). diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index e647691090..f4d0820d28 100644 --- a/docs/reference/protocol-messages.md +++ b/docs/reference/protocol-messages.md @@ -1,6 +1,6 @@ # Provider ↔ coordinator protocol messages -> Last updated: 2026-10-30 +> Last updated: 2026-11-02 Every JSON frame on the provider WebSocket (`GET /ws/provider`), with the Go type, the Swift type, and the presence rule for each field. Go is the canon in @@ -1409,7 +1409,9 @@ Go `LoadModelMessage` · Swift `LoadModel`. `model_id` (req). Sent only to Active or explicitly paused Autopilot providers block this legacy residency path and use explicit `model_autopilot` commands instead. Never sent to a `cluster_member` connection or to a device held by a verified pair (`beginVerifiedPairAwareModelCommand`, -`darkbloom-platform:coordinator/registry/verified_pair_commands.go`). +`darkbloom-platform:coordinator/registry/verified_pair_commands.go`). Without +Autopilot, a model outside the [operator filter](configuration.md#provider-model-selection) +is refused `model_not_selected` (`autopilotAllowsModel`). ### `prefetch_model` @@ -1417,7 +1419,9 @@ Go `PrefetchModelMessage` · Swift `PrefetchModel`. `model_id` (req); `priority` (`int`, opt, advisory). Download + verify only, no GPU load; for a build in ordinary serving the provider replies with `prefetch_model_status` and then `models_update`. Refused for a `cluster_member` connection or a pair-held -device, like `load_model`. +device, like `load_model`. Without saved Autopilot consent, a model outside the +[operator filter](configuration.md#provider-model-selection) is refused +`model_not_selected` before any download. With saved Autopilot consent and downloads not turned off by the operator (capability `inventory_downloads`; on by default), a build outside ordinary @@ -1428,7 +1432,8 @@ registration inventory, and sends **no** `models_update`, because that would mak it ordinary and publicly routable. It never loads or advertises the build; an Autopilot operation may load it. With consent but downloads off, such a request is refused `model_not_selected` and never takes the ordinary path. The provider then re-registers once when idle (no busy reason, -operation, live lease or other download) +operation, live lease or other download), or, after a bounded wait, when only +in-flight work or a live lease defers it, so `register.autopilot_inventory` carries the build's `ModelInfo` ([Autopilot set](../architecture/model-autopilot.md#the-autopilot-model-set)). @@ -1449,7 +1454,15 @@ backend and attested capability guards apply. Alias entries describe aliases whose desired, previous, or retired build is in the provider's advertised inventory; an empty set revokes old targets. Revision-aware providers stage the exact artifact and drain before activation; ID-only providers retain the legacy prefetch path. -Both announce completed updates through `models_update`. A `cluster_member` +Both announce completed updates through `models_update`. A provider with an +[operator filter](configuration.md#provider-model-selection) converges only to a +desired build inside it: an alias successor outside the filter is not fetched, +not staged, not served and does not drop the previous build +(`operatorFilterAllows`, +`provider-swift/Sources/ProviderCore/ProviderLoop+ModelSelection.swift`); the +provider logs `desired_models: → is outside the enabled model +filter; not converging`. With Autopilot enabled, only its lease and set gates can +admit such a build. A `cluster_member` connection is offered no entries and receives only the empty set; a nonempty set is refused for a member connection or a pair-held device. Source: [coordinator/registry/model_commands.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/registry/model_commands.go) (`DesiredModelsForProvider`, `RefreshDesiredModels`). diff --git a/docs/reference/provider-authorization.md b/docs/reference/provider-authorization.md index 54b8c7f6be..a42e921a07 100644 --- a/docs/reference/provider-authorization.md +++ b/docs/reference/provider-authorization.md @@ -89,6 +89,22 @@ requires an explicit mode flag. Code: `provider-swift/Sources/darkbloom/UnenrollCommand+KeepServing.swift` and `provider-swift/Sources/ProviderCore/Security/DarkbloomMDMRemoval.swift`. +`darkbloom status` and `darkbloom doctor` apply the same snapshot, process, +coordinator, `online` and protocol checks, but keep displaying an App Attest +lease until its `expires_at` when its latest renewal arrived more than +`snapshotMaxAge` ago (`ProviderAuthorizationReadiness.displayedStatus`). +`none` and `legacy` decisions still require receipt within `snapshotMaxAge`. +The lease duration remains the external coordinator's decision; see the +[current status contract][platform-current]. + +The serving summary takes that displayed lease and the strict removal decision +separately (`ProviderAuthorizationReadiness.summary`). Status and both doctor +paths derive them from the same daemon snapshot and observation time. Positive +removal advice requires the matching fresh decision and `mdm_removal_ready`. +A late but unexpired serving lease remains visible while the summary asks for +fresh removal readiness and retains existing profiles. `unenroll` still checks +readiness before and after profile inspection. + ## Related - [Identity binding](../architecture/security/identity-binding.md) diff --git a/docs/reference/ssd-kv-cache.md b/docs/reference/ssd-kv-cache.md index 728b31a595..27fb09098f 100644 --- a/docs/reference/ssd-kv-cache.md +++ b/docs/reference/ssd-kv-cache.md @@ -1,6 +1,6 @@ # SSD KV cache reference -> Last updated: 2026-10-28 +> Last updated: 2026-11-01 Exact on-disk format, paths, identity binding, environment knobs, size and eviction rules, and per-family reuse capability of the provider's encrypted SSD @@ -124,7 +124,7 @@ and MTP codec. No public header field exposes those token boundaries | Import admission | Authenticate manifest → allocation-free import plan → native per-buffer destination, scratch and metadata admission → bounded whole-file read. Shared native ownership is separate from provider host IO | `SSDHybridCheckpointStore+ReadAttempt.swift` (`readCheckpoint`), `CompleteCheckpointImportPlan.swift` (`allocate`) | | Same-file coordination | A stage read holds its leaf file's per-file lease in shared mode, so concurrent restores of one checkpoint read it together. Writers, duplicate validation, scans and retirement hold the lease exclusively. Requests are granted in arrival order and a queued exclusive request holds back later readers; scans and retirement never wait and skip a file that any request holds or awaits. A reader changes a file only while nothing else holds or awaits it, without waiting: its leaf through an upgrade of its shared lease, an ancestor through a free exclusive lease. It then rewrites an mtime that is at least `ttlSeconds / 30` old (60 s at the default TTL) or in the future, and removes a file that failed authentication. A busy file keeps its mtime; a busy corrupt file stays indexed and fails each later read until a reader finds it alone, a same-tag writer's validation removes it, or it expires | `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDCheckpointFileCoordinator.swift`, `SSDHybridCheckpointStore+ReadAttempt.swift` (`persistRecency`, `whileSoleHolder`) | | Provider-staged destinations | The provider-staged (non-native-bound) import creates contiguous destinations, paged segment storage and recent rows already available from zeroed host bytes, then skips `eval` and stream fences for them. Staging therefore never waits for MLX-Swift's process-wide `evalLock`, which the engine holds for a whole prefill chunk. The zero source is read by the copy and can briefly commit up to one destination outside the MLX allocator, so the import plan charges the largest as staging scratch. Native-bound imports and engine pool growth keep device allocation | `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CheckpointHostZeros.swift` (`MLXArray.cbv2HostZeros`), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift` (`CBv2CompleteCheckpointImport`), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/PagedCheckpointStorage.swift` (`CBv2PagedCheckpointStorage`, `hostMaterialized`), `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointImportPlan.swift` (`CBv2CompleteCheckpointImportPlan.scratchBytes`, `evaluateUnavailable`) | -| Lossy-to-native conversion | CPU row encoding/decoding; `64 << 10` bytes of conversion scratch, reserved per export read and in the import plan. Import reuses row buffers, retains at most one fragmented input row, and batches validated native writes up to `16 << 10` bytes within that allowance. Native destination sizes, not encoded bytes, price restored state | `NativeCheckpointRowCodec.swift`, `NativeQuantizedCheckpointTensorSource.swift`, `CompleteCheckpointImportPlan.swift`, `NativeQuantizedCheckpointRestore.swift` | +| Lossy-to-native conversion | CPU row encoding/decoding; `64 << 10` bytes of conversion scratch, reserved per export read and in the import plan. Each export read prepares one row encoder (`CBv2PreparedNativeCheckpointRowEncoder`): it reuses its row buffers and one representability decoder and writes the scalar codec's exact bytes. Import reuses row buffers, retains at most one fragmented input row, and batches validated native writes up to `16 << 10` bytes within that allowance. Native destination sizes, not encoded bytes, price restored state | `NativeCheckpointRowCodec.swift`, `NativeQuantizedCheckpointTensorSource.swift`, `CompleteCheckpointImportPlan.swift`, `NativeQuantizedCheckpointRestore.swift` | | Idle state | Metadata index only; no resident tensor bank or persistent slot carve | `SSDHybridCheckpointStore.swift`, `provider-swift/Sources/ProviderCore/Inference/PrefixCache/PrefixCachePolicy.swift` (`isMemoryEnabled`) | | Imported lifetime | Single-use staged state retains native owners through aliases. Paged adoption replaces temporary staging with the full request promise and actual backing; recurrent/MTP auxiliary state has its own charge | `CompleteCheckpointTransfer.swift` | | Host IO lifetime | Read/decrypt aliases retire before the read charge returns; writers claim host buffers before encoding and release them after the complete write stack drains | `SSDHybridCheckpointStore+ReadAttempt.swift` (`readCheckpoint`), `SSDHybridCheckpointStore+Write.swift` (`write`) | @@ -600,6 +600,9 @@ per family and bindings are in the | Restore | Decoded into page-aligned native buffers the arrays own: `[1, heads, frontier, width]` of the captured dtype, as a native record restores; older rows approximate | `QwenStagePrefixDiskRestoreWork.place` | | Restored rows written again | An encoded row whose native bytes equal the decode of the same row in the record holding the prompt's deepest kept prefix on this rank is stored as that record's bytes, not encoded again (the codec is not idempotent on its own output); that record is pinned until the new one is written, and if it cannot be read the new record is dropped (`reason=verbatim_source_unreadable`). The `persist` line logs `verbatim_rows` | `QwenStagePrefixDiskVerbatimSource`, `QwenStagePrefixDiskTier.persist` | | Switch | `DARKBLOOM_CLUSTER_PREFIX_SSD_QUANTIZATION` on the rank, from the owner ([configuration](configuration.md#cluster-ssd-prefix-record-precision)) | `QwenStagePrefixDiskEncoding.fromEnvironment` | +| Record frontiers | The deepest captured frontier's attention rows once, and the recurrent state at it and at each captured frontier on the record grid: `strideTokens` (2,048) rounded up to the block and doubled until at most `maximumGridFrontiers = 8` remain | `QwenStagePrefixDiskTier.persist` | +| Write-behind bound | At most `maximumQueuedJobs = 2` records queued and `QwenStagePrefixDiskPolicy.queuedBytesBound` host bytes (a sixty-fourth of memory, at least 256 MiB); a persist beyond either is dropped (`event=persist-dropped reason=queue_full` or `queue_bytes`) and serving never waits. A Qwen3.8 27B tensor-parallel rank's record holds 32,768 bytes a prompt token and 76,972,032 bytes a recurrent state, so a deepest frontier from about 114,688 tokens (256 GB), 49,664 (128 GB) or 20,992 (64 GB) on is not written | `QwenStagePrefixDiskConfiguration.maximumQueuedBytes`, `QwenStagePrefixDiskPolicy.queuedBytesBound` | +| Qwen tensor-parallel scope | The plan scope binds the plan and shares, artifact, storage, both builds, the assistant policy and the prefix policy (`QwenTensorParallelBatchPrefixBudget.policy`); records of another policy live in another directory and are never offered | `QwenTensorParallelPrefixDisk.planScope` | ## GLM cluster image exclusion @@ -618,7 +621,7 @@ record format are unchanged. | Request (`ClusterWorkerReservation.prefixCache`) | SSD record behavior | Enforcement | |---|---|---| | None (cache on, no salt) | The plan's earlier scope; read and written as before | `ClusterWorkerPrefixCache.scope` in `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterWorkerPrefixCache.swift` | -| `tenant` | Scope carries `\|tenant=` and the salt's SHA-256 digest; offered, restored and written only for that tenant | the same helper, through `qwenStagePrefixScope`, `QwenTensorParallelResidentRuntime.batchPrefixScope` and `GLM5NextTensorParallelResidentRuntime.prefixDiskScope` | +| `tenant` | Scope carries `\|tenant=` and the salt's SHA-256 digest; offered, restored and written only for that tenant | the same helper, through `qwenStagePrefixScope`, `QwenTensorParallelResidentRuntime.batchPrefixScope`, `GLM5NextTensorParallelResidentRuntime.prefixDiskScope` and `Gemma4TensorParallelPrefix.scopes` | | `disabled` | Nothing offered, restored or written | the same helper (no scope) | See [cluster prefix tenant partitions](../architecture/prefix-cache.md#cluster-prefix-tenant-partitions). diff --git a/docs/reports/2026-10-31-public-cluster-models.md b/docs/reports/2026-10-31-public-cluster-models.md index 5c2781fbf0..fe17b3063f 100644 --- a/docs/reports/2026-10-31-public-cluster-models.md +++ b/docs/reports/2026-10-31-public-cluster-models.md @@ -1,6 +1,6 @@ -# Public cluster models: GLM-5.3-Flash and Qwen3.8-27B +# Public cluster models: GLM-5.3-Flash, Qwen3.8-27B, MiMo-V2.6-Flash and Gemma 4 26B QAT -> Last updated: 2026-10-31 +> Last updated: 2026-11-03 This record is the evidence document of the provider's public cluster model declaration (`ClusterPublicModels`): the declaration's `evidenceSHA256` is the @@ -20,7 +20,17 @@ The owner (jonathan308) decided on 2026-10-31: shouldn't matter for the coordinator" The owner approved both modes, pipeline and tensor parallel, for both models, -and the public qualification of both models is done. No other model serves +and the public qualification of both models is done. + +On 2026-11-03 the owner added two models. Of the cluster-validated models +that served their owner only, the owner said "Mark them all approved for public +traffic", then "If you did just add Mimo and Gemma to start". MiMo-V2.6-Flash +and Gemma 4 26B QAT are declared in the same two families, pipeline and tensor +parallel, as the 2026-10-31 ruling on families reads. MiMo-V2.6-Flash also +keeps its speculative pipeline, the split it plans by default. A declared +model's grant replaces the families its records grant, and a coordinator never +forms a pair planned in a family its grant omits, so without it a MiMo pair +planned that way would not form through Darkbloom at all. No other model serves public cluster traffic: a cluster of any other model serves its owner only. ## Declared models @@ -29,18 +39,22 @@ public cluster traffic: a cluster of any other model serves its owner only. |---|---|---|---|---| | `registered_glm53_flash` | `glm-5.3-flash` | `3aae613ff188bb0f72e880774a84e4d8e9943ab20c929d8a302af9c57b97d5ac` | `pipeline`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | | `registered_qwen38_27b` | `EigenLabs/Qwen3.8-27B-4bit-mtp` | `bbd0e0adcfe74e095073fefd0b9e116e4311d606ad9989cf81f8175e8ac18463` | `pipeline`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | +| `registered_mimo_v26_flash_mopd` | `mimo-v2.6-flash-mopd` | `2334547d8acc9898ad4a74570ce44d2b12390bbac8d4bc52c092eb5ad5cfe034` | `pipeline`, `pipeline_speculative`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | +| `registered_gemma4_26b_qat_4bit` | `gemma-4-26b-qat-4bit` | `2468a0cb3049a871f42052f4d9f9380bf12a0792f64c7a29f768559fc7d28785` | `pipeline`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | -The artifacts are the ones the cluster runtime registers for the two models. +The artifacts are the ones the cluster runtime registers for the four models. Each family is qualified on 2 ranks, each an Apple M5 Ultra (GPU architecture -`applegpu_g17d`, NAX on) on macOS 27.0, at 2026-10-31T00:00:00Z: +`applegpu_g17d`, NAX on) on macOS 27.0, at 2026-11-03T00:00:00Z, the date of the latest declaration: | Family | Mode | Cuts | Shares | |---|---|---|---| -| `pipeline` | `pipeline_v1` | `[num_hidden_layers / 2]` (integer division): `[22]` for GLM-5.3-Flash (45 layers), `[32]` for Qwen3.8-27B (64 layers) | not applicable | +| `pipeline` | `pipeline_v1` | `[num_hidden_layers / 2]` (integer division): `[22]` for GLM-5.3-Flash (45 layers), `[32]` for Qwen3.8-27B (64 layers), `[24]` for MiMo-V2.6-Flash (48 layers), `[15]` for Gemma 4 26B QAT (30 layers) | not applicable | +| `pipeline_speculative` (MiMo-V2.6-Flash only) | `pipeline_mtp_v1` | `[num_hidden_layers / 2]`: `[24]` | not applicable | | `tensor_parallel` | `tensor_parallel_v1` | `[]` | equal | -Both models' `config.json` give the layer count as `text_config.num_hidden_layers`; -neither has a top-level `num_hidden_layers`. +GLM-5.3-Flash's, Qwen3.8-27B's and Gemma 4 26B QAT's `config.json` give the +layer count as `text_config.num_hidden_layers`; MiMo-V2.6-Flash's gives it at the +top level. ## What was run @@ -67,6 +81,14 @@ does not re-run them. This record holds no pipeline run on two Apple M5 Ultras. +For MiMo-V2.6-Flash and Gemma 4 26B QAT this record holds no run on two Apple +M5 Ultras. Their pipeline rests on the bundled records below and the owner's +decision of 2026-11-03. Their tensor parallel rests on the owner's decision +alone: its code is in open PRs (#1706 and #1707, with #1715 and #1716), and no +cross-cable record of it exists yet. MiMo-V2.6-Flash's speculative pipeline +(`pipeline_mtp_v1`, family `pipeline_speculative`) rests on its 2 passing +records below. + ## Bundled cross-cable records The qualification records the build bundles @@ -85,6 +107,19 @@ The qualification records the build bundles Apple M5 Max, cut 39, `serial_v1`) and no `tensor_parallel_v1` record. Its pipeline rests on that run and the owner's ruling; its tensor parallel rests on the owner's decision and the DevNet serving results above. +- MiMo-V2.6-Flash: 19 passing records over `jaccl`, all on an Apple M5 Ultra + with an Apple M3 Ultra, from 2026-10-14, with prompts up to 16,384 tokens. The + `pipeline` family has 8 `pipeline_v1` records (cuts 14 and 47; 7 `serial_v1` + and 1 `one_chunk_lookahead_v1`) and 3 `pipeline_compact_decode_v1` records + (cut 47, `serial_v1`). The others are 2 `pipeline_mtp_v1` and 6 `phase_split_v1` + records. None diverged. +- Gemma 4 26B QAT: 7 `pipeline_v1` records over `jaccl`, from 2026-10-09 and + 2026-10-12, on an Apple M3 Ultra with an Apple M5 Max or an Apple M5 Ultra. + 4 passed and 3 diverged. A pass that a divergence of the same placement + contradicts counts for nothing, so its records grant rests on 2 passes, both + on an Apple M3 Ultra with an Apple M5 Ultra: cut 5 with `one_chunk_lookahead_v1` + and cut 15 with `serial_v1`. The planner refuses the diverged placements (cut 2 + on that pair, and cuts 12 and 18 on the Apple M5 Max pair). ## Pair-serving grants @@ -106,7 +141,7 @@ records as its evidence; a model the records grant nothing has none. ## Request envelope -Both models, both families: sampling and tool calls are allowed, and +Every declared model, both families: sampling and tool calls are allowed, and `max_prompt_tokens` and `max_output_tokens` are 1,048,576 (the coordinator's maximum, so only the model's own limits apply). Media follows what the placement serves (`ClusterModelFeaturePolicy.mediaContract`). In tensor @@ -116,11 +151,13 @@ catalog entry in the release's environment lists `image` in `input_modalities`, and `video` when it also lists `video`. A pipeline serves text only, so its envelope admits neither. GLM-5.3-Flash's DevNet catalog entry lists `text`, `image` and `video`; Qwen3.8-27B's lists `text` and `image`. +MiMo-V2.6-Flash's and Gemma 4 26B QAT's media in tensor parallel follow the same +contract, once their tensor-parallel code serves. ## Where it is used `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift` -declares the two models with this file's SHA-256. A release's cluster runtime +declares the four models with this file's SHA-256. A release's cluster runtime facts (`cluster_runtime`) carry, for a declared model, the grant of its declared families and one parity qualification for each declared family and schedule: `pipeline` first, then `tensor_parallel`. A coordinator that derives approvals diff --git a/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md new file mode 100644 index 0000000000..3753c79107 --- /dev/null +++ b/docs/reports/2026-11-01-gemma-pipeline-prompt-experts.md @@ -0,0 +1,102 @@ +# Gemma pipeline prompt experts: one shared dispatch, the same bytes + +> Last updated: 2026-11-01 + +This record covers the change to the registered Gemma 4 stages' prompt expert +blocks: they now share one dispatch per operation instead of building +one subgraph per prompt token. It gives the equality evidence and synthetic +component timings measured on one Mac. It is not a pair, full-model or +qualification result, and it contains no prompt, endpoint or machine identifier. + +## Context + +Since 2026-10-23 (`gemma4-bf16-token-expert-reduction-v1` in the exact Gemma +arithmetic receipt) a registered Gemma stage computes every prompt token's +expert block at one token, so that prompt arithmetic is the same on every Apple +GPU generation. The receipt was added because rectangular expert products +select chip-specific kernels. The implementation built that per-token +arithmetic as one subgraph per token: about six launches per token per layer, +or about 180,000 launches for a 2,048-token frame on a 15-layer stage. No +prompt throughput had been measured for it. + +## Change + +`SwitchGLU.callAndWeightedReduceRows` (mlx-swift-lm) projects all rows of a +frame in one call: + +- it groups 64 or more assignments by expert for weight locality, but does + not give the gathers the sorted hint; +- every (row, expert) pair is therefore still an M=1 gathered product. MLX + picks `gather_qmv` and its variant from the quantization, dtype and the N + and K widths, never from the row count, and its grid gives each pair its own + threadgroups; +- the rows return to their order before the top-8 weighted reduction, which + keeps its one-row `col_reduce_small` thread layout. That layout depends + only on the hidden width. + +Each row therefore keeps the bytes of its own one-row call, and the receipt is +unchanged. Gemma's batch-decode rows (`Gemma4BatchDecodeScope`) use the same +call. + +## Equality evidence + +| Check | Device | Result | +|---|---|---| +| `Gemma4PrefillExpertTests`: whole-layer composition against a one-token expert oracle, 7 to 512 tokens, 4 and 8 bits | CPU | bytes equal; one expert call, never hinted as sorted | +| Same suite: expert branch against per-token layer calls; decode rows 2, 3 and 8 | CPU | bytes equal | +| `GEMMA4_EXPERT_ROWS_GPU=1`: hidden 768, width 192, 16 experts (the production kernel classes), 1 to 2,048 rows, 4 and 8 bits | M5 Ultra GPU | bytes equal; values finite and nonzero | +| `GEMMA4_EXPERT_ROWS_GPU=production`: hidden 2,816, width 704, 128 experts, 1 to 513 rows | M5 Ultra GPU | bytes equal | +| Every row routed to the same 8 experts (every sort key tied), and a single row: `expertRowsMatchOneRowCallsWithTiedRoutes`, and the GPU check at 9 and 513 tied rows at both geometries | CPU; M5 Ultra GPU | bytes equal | +| Sensitivity: the shared call against the earlier sorted rectangular call at 512 and 2,048 rows | M5 Ultra GPU | bytes differ, as expected | +| `Gemma4StagePagedSyntheticTests`: two synthetic stages, lanes joining and leaving | M5 Ultra GPU | each request decodes its tokens alone | + +The suites ran in a debug build of `libs/darkbloom-cluster` with the SDK test +file linked in and a source-matched `mlx.metallib` (SHA-256 +`5b97893cc20e6e9651edf3284d970488af9a9bdd64820231e95fee760eec70ac`, MLX +`72dffa2d`). Other GPU generations were not run. [INFERENCE] The selection +above should hold on them too: on this route `gather_qmv` takes no architecture +input, and the reduction's threadgroup is 32 by 8 on any GPU whose kernels +hold 256 threads per threadgroup. + +## Synthetic timings + +One layer with random packed weights at the registered geometry: experts at +4 bits, dense MLP and router at 8 bits. Median of five warm runs, debug Swift +build, on an M5 Ultra that was also serving other GPU work, so the figures +carry contention noise. + +One run timed every expert-block variant at the production geometry: + +| Expert block, 4-bit | 512 tokens | 2,048 tokens | +|---|---:|---:| +| Per-token subgraphs (before) | 89.5 ms | 414.3 ms | +| Shared dispatch, token order | 9.8 ms | 37.2 ms | +| Shared dispatch, grouped by expert (after) | 8.2 ms | 30.8 ms | +| Sorted rectangle (the prompt path before 2026-10-23) | 1.9 ms | 3.8 ms | + +A rerun of the final code measured 8.2 and 30.6 ms against 79.5 and 369.5 ms +for the per-token graph. Every shared-dispatch variant equalled the per-token +bytes. + +| Dense projections of one sliding layer (q, k, v, o, MLP, router) | 512 tokens | 2,048 tokens | +|---|---:|---:| +| M=1 rows (the registered prompt policy, unchanged) | 12.8 ms | 27.7 ms | +| Rectangle | 3.7 ms | 3.7 ms | + +[INFERENCE] For a 15-layer stage and a 2,048-token frame, the projections took +about 5.7 to 6.6 s before and take about 0.9 s after, ignoring attention and +norms. That would lift the stage's projection-bound prompt rate from about 310 +to 360 tokens per second to about 2,300. The M=1 policy still costs about 8x +the rectangle. Closing that gap needs a multi-row `qmv` kernel that keeps qmv's +per-row reduction order. + +## Not established + +- Pair prompt or decode throughput, both schedules, both rank orders. +- Full-artifact numerical agreement on any chip pair. +- Other GPU generations (M1 to M4) and the release build. + +Code: `libs/mlx-swift-lm/Libraries/MLXLMCommon/SwitchLayers.swift` +(`SwitchGLU.callAndWeightedReduceRows`) and +`libs/mlx-swift-lm/Libraries/MLXLLM/Models/Gemma4Text.swift` (`Gemma4Experts`). +Mechanism: [Gemma prompt projection reductions](../architecture/inference.md#gemma-prompt-projection-reductions). diff --git a/docs/reports/README.md b/docs/reports/README.md index 96e0b79cef..ea59d1aab7 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -1,10 +1,11 @@ # Provider And Native Evidence -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Dated records and raw native evidence retain their original content, revisions and limitations. A record is not a fresh test result or proof of private platform compatibility. -- [Public cluster models](2026-10-31-public-cluster-models.md) - the owner's declaration of GLM-5.3-Flash and Qwen3.8-27B for public cluster traffic in pipeline and tensor parallel, the checks it rests on and why releases carry pair-serving grants; the evidence document of `ClusterPublicModels`. +- [Gemma pipeline prompt experts](2026-11-01-gemma-pipeline-prompt-experts.md) - the registered Gemma stages' prompt expert blocks in one shared dispatch with the same bytes: CPU and M5 Ultra GPU equality evidence and synthetic one-layer timings; no pair or qualification result. +- [Public cluster models](2026-10-31-public-cluster-models.md) - the owner's declaration of GLM-5.3-Flash, Qwen3.8-27B, MiMo-V2.6-Flash and Gemma 4 26B QAT for public cluster traffic in pipeline and tensor parallel, the checks it rests on and why releases carry pair-serving grants; the evidence document of `ClusterPublicModels`. - [Mixed-step prefill geometry](2026-10-21-mixed-step-prefill-geometry.md) - load, engine, inter-token latency and KV-subtracted activation measurements behind Gemma 4's 2,048 / 4,096 prompt geometry, its media ceiling and the GPT-OSS and dense Qwen opt-in. - [GLM-5.3-Flash single-Mac qualification record](2026-10-21-glm53-flash-single-mac-qualification.md) - [Startup shape warmup: first-request TTFT](2026-10-21-startup-shape-warmup-first-request.md) diff --git a/docs/threat-model.yaml b/docs/threat-model.yaml index 2e36f2ae07..71365b34b2 100644 --- a/docs/threat-model.yaml +++ b/docs/threat-model.yaml @@ -1883,6 +1883,22 @@ threats: verified install; predecessor material is hash+signature verified against the pinned designated requirement before any restore. status: implemented + - description: > + The operator rollback (`darkbloom update --rollback`) is the same + journaled rollback under the same update lease, with the same + predecessor verification and the same single-slot exact-version + quarantine; it also refuses an installed bundle that differs from + the recorded release and never rolls back one Mac of a cluster pair. + Cluster membership (a running cluster service, a loaded cluster + service login agent, a cluster member job), the provider's state + (by process identity) and the plan are decided under the update + lease, the lease a pair's coordinated update holds from its check + through its install, before the drain. At the swap the cluster + service lock and the provider instance lock are held (or the latter + stays with the drained service process) until the swap is done, so + neither a cluster service nor another provider can start mid-swap; + another holder refuses the rollback without signalling it. + status: implemented - description: > Bounded watchdog network I/O (URLSession request/resource timeouts) plus a safe-point per-tick budget so a stalled download or wedged diff --git a/libs/darkbloom-cluster-worker/Package.swift b/libs/darkbloom-cluster-worker/Package.swift index 6563915e5e..1911f1c19a 100644 --- a/libs/darkbloom-cluster-worker/Package.swift +++ b/libs/darkbloom-cluster-worker/Package.swift @@ -76,9 +76,11 @@ let package = Package( "DarkbloomClusterQualification", "PairCheckFakeWorker", .product(name: "DarkbloomClusterProtocol", package: "darkbloom-cluster"), ]), - // Tensor parallel for the dense Qwen models: the unsharded reference, the - // single-process oracle and one rank of a two-rank run, plus the comparator. + // Tensor parallel for the Qwen, GLM and Gemma 4 models: the unsharded + // reference, the single-process oracle and one rank of a two-rank run, + // plus the comparators (Gemma's through QualificationComparator). .executableTarget(name: "TensorParallelCheck", dependencies: [ + "DarkbloomClusterQualification", .product(name: "DarkbloomClusterRuntime", package: "darkbloom-cluster"), .product(name: "MLX", package: "mlx-swift"), ]), diff --git a/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift b/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift index e72f93da44..b47c288611 100644 --- a/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift +++ b/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Execution/NativeWorkerRuntime.swift @@ -11,8 +11,10 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case qwenDense(QwenResidentRuntime) case qwenTensorParallel(QwenTensorParallelResidentRuntime) case mimoV26(MiMoResidentRuntime) + case mimoV26TensorParallel(MiMoTensorParallelResidentRuntime) case glm5Next(GLM5NextResidentRuntime) case glm5NextTensorParallel(GLM5NextTensorParallelResidentRuntime) + case gemma4TensorParallel(Gemma4TensorParallelResidentRuntime) } private let owner: Owner /// The owner's bootstrap connection and native key, held for the worker's lifetime. @@ -33,6 +35,15 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { throw WorkerFailure.invalid("A tensor assistant policy requires the Qwen tensor runtime") } switch family { + case .qwenDense where generationMode == .tensorParallel + && Gemma4TensorParallelResidentRuntime.serves(runtimeModelID: configuration.identity.modelID): + // Gemma 4 shares the layer-stage family; its tensor-parallel rank is its own runtime, + // whose prompt-prefix cache keeps an SSD tier with the owner's key. + guard speculativeTerms == nil, tensorAssistantPolicy == nil, tensorShares == [1, 1], let dataPlane else { + throw WorkerFailure.invalid("Gemma tensor parallel runs equal shares over a keyed data plane without speculation") + } + owner = .gemma4TensorParallel(try .load(configuration, qualification: qualification, dataPlane: dataPlane, + prefixSSDKey: prefixSSDKey)) case .qwenDense where generationMode == .tensorParallel: owner = .qwenTensorParallel(try .load(configuration, shares: tensorShares, qualification: qualification, dataPlane: dataPlane, prefixSSDKey: prefixSSDKey, speculativeTerms: speculativeTerms, @@ -41,6 +52,15 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { owner = .qwenDense(try .load(configuration, generationMode: generationMode, speculativeTerms: speculativeTerms, qualification: qualification, dataPlane: dataPlane, prefixSSDKey: prefixSSDKey)) + case .mimoV26 where generationMode == .tensorParallel: + // Every layer on both ranks, half of each split weight, sealed sums; text only. `--mtp-depth` + // (1...3, MiMo's own terms) adds speculative rounds on heads replicated whole; the installed owner + // passes `ClusterMiMoTensorParallel.speculativeDepth`, and a hand launch without it runs none. + guard tensorAssistantPolicy == nil, tensorShares == [1, 1], let dataPlane else { + throw WorkerFailure.invalid("MiMo tensor parallel runs equal shares over a keyed data plane") + } + owner = .mimoV26TensorParallel(try .load(configuration, speculativeDepth: speculativeTerms?.depth, + qualification: qualification, dataPlane: dataPlane)) case .mimoV26: // `--mtp-depth` is parsed once for every family; MiMo's own terms bound it (1...3). owner = .mimoV26(try .load(configuration, generationMode: generationMode, @@ -74,7 +94,9 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): runtime.readiness case .qwenTensorParallel(let runtime): runtime.readiness case .glm5NextTensorParallel(let runtime): runtime.readiness + case .gemma4TensorParallel(let runtime): runtime.readiness case .mimoV26(let runtime): runtime.readiness + case .mimoV26TensorParallel(let runtime): runtime.readiness case .glm5Next(let runtime): runtime.readiness } } @@ -83,7 +105,9 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): try runtime.reserve(requestID: id, request: value) case .qwenTensorParallel(let runtime): try runtime.reserve(requestID: id, request: value) case .glm5NextTensorParallel(let runtime): try runtime.reserve(requestID: id, request: value) + case .gemma4TensorParallel(let runtime): try runtime.reserve(requestID: id, request: value) case .mimoV26(let runtime): try runtime.reserve(requestID: id, request: value) + case .mimoV26TensorParallel(let runtime): try runtime.reserve(requestID: id, request: value) case .glm5Next(let runtime): try runtime.reserve(requestID: id, request: value) } } @@ -102,7 +126,10 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenTensorParallel(let runtime): result = try runtime.start(requestID: id, tokens: channel) // Reads each answer after its next step was submitted. case .glm5NextTensorParallel(let runtime): result = try runtime.start(requestID: id, tokens: channel) + case .gemma4TensorParallel(let runtime): result = try runtime.start(requestID: id, tokens: channel) case .mimoV26(let runtime): result = try runtime.start(requestID: id, onCommittedToken: token) + // Publishes each token's logprobs when the request asks for them. + case .mimoV26TensorParallel(let runtime): result = try runtime.start(requestID: id, tokens: channel) case .glm5Next(let runtime): result = try runtime.start(requestID: id, onCommittedToken: token) } guard result.bothRequestStatesRetired else { throw WorkerFailure.invalid("Native generation did not retire both request states") } @@ -115,16 +142,21 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): try runtime.releaseReservation(requestID: id) case .qwenTensorParallel(let runtime): try runtime.releaseReservation(requestID: id) case .glm5NextTensorParallel(let runtime): try runtime.releaseReservation(requestID: id) + case .gemma4TensorParallel(let runtime): try runtime.releaseReservation(requestID: id) case .mimoV26(let runtime): try runtime.releaseReservation(requestID: id) + case .mimoV26TensorParallel(let runtime): try runtime.releaseReservation(requestID: id) case .glm5Next(let runtime): try runtime.releaseReservation(requestID: id) } } - /// GLM tensor parallel also drops its prompt-prefix entries under host - /// pressure; every other family gives back its freed-buffer cache only. + /// GLM and Gemma tensor parallel also drop their prompt-prefix entries + /// under host pressure; every other family gives back its freed-buffer + /// cache only. func releaseIdleMemory(underPressure: Bool) -> Int? { switch owner { case .glm5NextTensorParallel(let runtime): return try? runtime.releaseIdleMemory(underPressure: underPressure) - case .qwenDense, .qwenTensorParallel, .mimoV26, .glm5Next: return ClusterIdleMemory.releaseFreedBuffers() + case .gemma4TensorParallel(let runtime): return try? runtime.releaseIdleMemory(underPressure: underPressure) + case .qwenDense, .qwenTensorParallel, .mimoV26, .mimoV26TensorParallel, .glm5Next: + return ClusterIdleMemory.releaseFreedBuffers() } } func refreshServingContext() -> Int? { @@ -133,7 +165,7 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .glm5NextTensorParallel(let runtime): runtime.refreshServingContext() // Nil for a row whose profile is its memory plan. case .qwenTensorParallel(let runtime): runtime.refreshServingContext() - case .mimoV26, .glm5Next: nil + case .mimoV26, .mimoV26TensorParallel, .glm5Next, .gemma4TensorParallel: nil } } /// Qwen tensor parallel's lanes re-derive their serving context on a @@ -148,15 +180,19 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { switch owner { case .qwenDense(let runtime): runtime.batch.lanes case .mimoV26(let runtime): runtime.batchLanes + case .mimoV26TensorParallel: 1 case .glm5NextTensorParallel(let runtime): runtime.lanes.lanes case .qwenTensorParallel(let runtime): runtime.batchLanes + case .gemma4TensorParallel(let runtime): runtime.lanes case .glm5Next: 1 } } /// Native owners explicitly advertise raw-token logprob publication. var capturesLogprobs: Bool { if case .glm5NextTensorParallel = owner { return true } + if case .gemma4TensorParallel(let runtime) = owner { return runtime.capturesLogprobs } if case .qwenTensorParallel(let runtime) = owner { return runtime.capturesLogprobs } + if case .mimoV26TensorParallel(let runtime) = owner { return runtime.capturesLogprobs } return false } func reserveLane(_ id: UUID, _ value: ClusterWorkerReservation) throws -> Int { @@ -164,8 +200,9 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): try runtime.reserveLane(requestID: id, request: value) case .mimoV26(let runtime): try runtime.reserveLane(requestID: id, request: value) case .glm5NextTensorParallel(let runtime): try runtime.reserveLane(requestID: id, request: value) + case .gemma4TensorParallel(let runtime): try runtime.reserveLane(requestID: id, request: value) case .qwenTensorParallel(let runtime): try runtime.reserveLane(requestID: id, request: value) - case .glm5Next: throw WorkerFailure.invalid("This family serves one request at a time") + case .glm5Next, .mimoV26TensorParallel: throw WorkerFailure.invalid("This family serves one request at a time") } } func startLane(_ id: UUID) throws { @@ -173,8 +210,9 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): try runtime.startLane(requestID: id) case .mimoV26(let runtime): try runtime.startLane(requestID: id) case .glm5NextTensorParallel(let runtime): try runtime.startLane(requestID: id) + case .gemma4TensorParallel(let runtime): try runtime.startLane(requestID: id) case .qwenTensorParallel(let runtime): try runtime.startLane(requestID: id) - case .glm5Next: throw WorkerFailure.invalid("This family serves one request at a time") + case .glm5Next, .mimoV26TensorParallel: throw WorkerFailure.invalid("This family serves one request at a time") } } func cancelLane(_ id: UUID) { @@ -183,7 +221,8 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .mimoV26(let runtime): runtime.cancelLane(requestID: id) case .glm5NextTensorParallel(let runtime): runtime.cancelLane(requestID: id) case .qwenTensorParallel(let runtime): runtime.cancelLane(requestID: id) - case .glm5Next: break + case .gemma4TensorParallel(let runtime): runtime.cancelLane(requestID: id) + case .glm5Next, .mimoV26TensorParallel: break } } func withdrawLane(_ id: UUID) -> Bool { @@ -192,7 +231,8 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .mimoV26(let runtime): runtime.withdrawLane(requestID: id) case .glm5NextTensorParallel(let runtime): runtime.withdrawLane(requestID: id) case .qwenTensorParallel(let runtime): runtime.withdrawLane(requestID: id) - case .glm5Next: false + case .gemma4TensorParallel(let runtime): runtime.withdrawLane(requestID: id) + case .glm5Next, .mimoV26TensorParallel: false } } var hasStartedLanes: Bool { @@ -201,7 +241,8 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .mimoV26(let runtime): runtime.hasStartedLanes case .glm5NextTensorParallel(let runtime): runtime.hasStartedLanes case .qwenTensorParallel(let runtime): runtime.hasStartedLanes - case .glm5Next: false + case .gemma4TensorParallel(let runtime): runtime.hasStartedLanes + case .glm5Next, .mimoV26TensorParallel: false } } func serveBatch(host: QwenBatchServingHost) throws { @@ -209,14 +250,16 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): try runtime.serveBatch(host: host) case .mimoV26(let runtime): try runtime.serveBatch(host: host) case .glm5NextTensorParallel(let runtime): try runtime.serveBatch(host: host) + case .gemma4TensorParallel(let runtime): try runtime.serveBatch(host: host) case .qwenTensorParallel(let runtime): try runtime.serveBatch(host: host) - case .glm5Next: throw WorkerFailure.invalid("This family serves one request at a time") + case .glm5Next, .mimoV26TensorParallel: throw WorkerFailure.invalid("This family serves one request at a time") } } /// Each enabled lane loop proves native retirement before its cancel ACK. var retiresCancelledLanes: Bool { if case .qwenTensorParallel(let runtime) = owner { return runtime.batchLanes > 1 } if case .glm5NextTensorParallel = owner { return true } + if case .gemma4TensorParallel(let runtime) = owner { return runtime.lanes > 1 } if case .mimoV26(let runtime) = owner { return Self.qwenLanesRetireAlone(mode: runtime.generationMode, lanes: runtime.batchLanes) } @@ -233,7 +276,9 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): runtime.cancel(requestID: id) case .qwenTensorParallel(let runtime): runtime.cancel(requestID: id) case .glm5NextTensorParallel(let runtime): runtime.cancel(requestID: id) + case .gemma4TensorParallel(let runtime): runtime.cancel(requestID: id) case .mimoV26(let runtime): runtime.cancel(requestID: id) + case .mimoV26TensorParallel(let runtime): runtime.cancel(requestID: id) case .glm5Next(let runtime): runtime.cancel(requestID: id) } } @@ -242,7 +287,9 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): try runtime.keepWarmPulse() case .qwenTensorParallel(let runtime): try runtime.keepWarmPulse() case .glm5NextTensorParallel(let runtime): try runtime.keepWarmPulse() + case .gemma4TensorParallel(let runtime): try runtime.keepWarmPulse() case .mimoV26(let runtime): try runtime.keepWarmPulse() + case .mimoV26TensorParallel(let runtime): try runtime.keepWarmPulse() case .glm5Next(let runtime): try runtime.keepWarmPulse() } } @@ -251,7 +298,9 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): try runtime.dataPlanePing() case .qwenTensorParallel(let runtime): try runtime.dataPlanePing() case .glm5NextTensorParallel(let runtime): try runtime.dataPlanePing() + case .gemma4TensorParallel(let runtime): try runtime.dataPlanePing() case .mimoV26(let runtime): try runtime.dataPlanePing() + case .mimoV26TensorParallel(let runtime): try runtime.dataPlanePing() case .glm5Next(let runtime): try runtime.dataPlanePing() } } @@ -260,7 +309,9 @@ final class NativeWorkerRuntime: WorkerRuntime, @unchecked Sendable { case .qwenDense(let runtime): try runtime.shutdown() case .qwenTensorParallel(let runtime): try runtime.shutdown() case .glm5NextTensorParallel(let runtime): try runtime.shutdown() + case .gemma4TensorParallel(let runtime): try runtime.shutdown() case .mimoV26(let runtime): try runtime.shutdown() + case .mimoV26TensorParallel(let runtime): try runtime.shutdown() case .glm5Next(let runtime): try runtime.shutdown() } } diff --git a/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Startup/WorkerConfiguration.swift b/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Startup/WorkerConfiguration.swift index 863475c237..c74f099539 100644 --- a/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Startup/WorkerConfiguration.swift +++ b/libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Startup/WorkerConfiguration.swift @@ -16,7 +16,8 @@ struct WorkerConfiguration { /// mode, and it must be one the registered model's resident row lists. let generationMode: ClusterGenerationMode /// `--mtp-depth N` (1...4): the speculative head's fixed draft depth under - /// `phase_split_mtp_v1` or `pipeline_mtp_v1` (MiMo: 1...3); nil means the + /// `phase_split_mtp_v1` or `pipeline_mtp_v1` (MiMo: 1...3, also MiMo's + /// keyed `tensor_parallel_v1` text row); nil means the /// product drafter's maximum. Exact keyed Qwen27 TP accepts an explicit depth /// at width one; nil keeps ordinary target decoding. Both ranks /// bind it into their load agreement, so they must be given the same value. @@ -178,7 +179,10 @@ struct WorkerConfiguration { let tensorAssistant = generationMode == .tensorParallel && fields["--model-id"].map(ClusterQwenTensorAssistantPolicy.runtimeModelIDs.contains) == true && dataPlaneEncrypted && fields["--runtime-profile"] == nil - guard generationMode.usesSpeculativeHead || tensorAssistant, + // MiMo tensor parallel's speculative rounds (the trained heads replicated on both ranks). + let mimoTensorParallelRounds = generationMode == .tensorParallel && registered?.family == .mimoV26 + && dataPlaneEncrypted && fields["--runtime-profile"] == nil + guard generationMode.usesSpeculativeHead || tensorAssistant || mimoTensorParallelRounds, let depth = Int(text), String(depth) == text, let terms = try? QwenMTPTerms(depth: depth) else { throw WorkerFailure.invalid("--mtp-depth takes 1...\(QwenMTPTerms.maximumDepth) and only with keyed Qwen TP on a row with an inline head or a speculative generation mode (" diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift new file mode 100644 index 0000000000..c175f5d889 --- /dev/null +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift @@ -0,0 +1,500 @@ +import DarkbloomClusterQualification +import DarkbloomClusterRuntime +import Darwin +import Foundation +import MLX + +// Gemma 4 MoE tensor-parallel oracles (Gemma4TensorParallelModel), greedy: +// +// darkbloom-cluster-tp-check gemma synthesize --output /NEW/DIR [--bits 4|8] [--seed N] [--dtype bfloat16|float32] +// [--experts N --top-k K] +// a tiny random Gemma 4 MoE checkpoint with the 26B's structure and request.json (never a model pass) +// darkbloom-cluster-tp-check gemma run --mode full|split-sum|simulated|shard|tp --model-dir DIR --request FILE --report FILE +// [--record-top K] [--backend ring|socket|jaccl] [--reduction native|sealed-bench] [--shard-rank R] +// [--pack yes|no] [--path legacy|paged] [--prefix none|repeat] [--deadline-seconds S] +// darkbloom-cluster-tp-check gemma compare --reference FILE --candidate FILE [--bitwise yes|no] [--near-tie-ulps U] +// darkbloom-cluster-tp-check gemma allsum [--backend ring|socket|jaccl] [--count N] +// darkbloom-cluster-tp-check gemma lanes --mode simulated|tp --model-dir DIR --report FILE [--lanes N] [--outputs N] +// [--backend ring|socket|jaccl] [--reduction native|sealed-bench] [--deadline-seconds S] +// +// `full` is the unsharded model; `simulated` the one-process oracle: both +// ranks' shards in one process, each on its own thread and stream, every +// collective the FP32 sum of both ranks' partials (`tp` must equal it bit for +// bit); `split-sum` the decomposition's oracle: the unsharded model whose +// row-parallel projections add both ranks' FP32 partials (bitwise to `tp` on +// the CPU; on an M5 Ultra GPU a 1,024-row prefill k_proj rounds some rows +// unlike its 512-row half); `shard` one rank's shard with no peer +// (diagnostic: wrong tokens by construction, one chip's share of the +// compute); `tp` one rank of a two-rank run over JACCL (two Macs) or the +// local ring or socket (two processes on one Mac over 127.0.0.1, correctness +// only). `--reduction sealed-bench` seals every floating collective with the +// fork's sealed all-sum (BENCH keys from an unauthenticated ephemeral +// exchange: the sealed path's arithmetic and cost, never a product trust). +// `compare` holds a candidate to a reference with QualificationComparator; +// `--bitwise yes` also requires every token, recorded top logit and log +// probability and the final row to be bit-identical (tp against simulated). +// `--path paged` runs every mode but split-sum through the resident runtime's +// own request path (`Gemma4TensorParallelModel.generatePaged`): paged KV with +// each rank's own heads, the product's CBv2 prompt entry under the registered +// prompt policy, and each step's token and stop flags agreed in the step's +// evaluation; `legacy` (the default) keeps the SDK's legacy caches. +// `--prefix repeat` (paged; simulated or tp) serves the request twice through +// each rank's prompt-prefix memory tier (`generatePagedRepeatingPrefix`): +// cold, keeping its chunk boundaries, then again restoring the deepest +// boundary both ranks hold after their sealed vote and confirmation. The +// report is the repeat's, which must have restored a prefix and equal the +// cold request bit for bit. +// `lanes` serves N greedy requests of different lengths through the batch +// driver on each rank's paged host (`Gemma4TensorParallelModel.generateLanes`), +// after each alone (`generatePaged`): every lane must take its solo tokens, +// and in `tp` mode both ranks must agree on every token. +// A report names roles and chips only, never a host, an address or a path. +enum GemmaCheck { + /// Both ranks' models, handed to the two rank threads of a simulated pair. + private final class Ranks: @unchecked Sendable { + let models: [Gemma4TensorParallelModel] + init(_ models: [Gemma4TensorParallelModel]) { self.models = models } + } + + struct Report: Codable { + var schema = "darkbloom_cluster_tp_check_gemma_report_v1" + var mode: String + var role: String + var rank: Int + var size: Int + var backend: String? + var reduction: String? + var correctnessOnly: Bool + var chip: String + var plan: String + var modelConfigurationSHA256: String + var modelID: String + var requestID: String + var promptTokens: Int + var promptTokenIDsSHA256: String + var outputCount: Int + var chunkSize: Int + var packedFeedForward: Bool + var path: String? + var loadSeconds: Double + var loadedParameterBytes: Int + var reductionsPerForward: Int? + var floatingReductions: Int? + var tokenIDs: [Int] + var tokenIDsSHA256: String + var topTokenIDs: [[Int]]? + var topLogits: [[Float]]? + var topLogprobs: [[Float]]? + var finalLogits: [Float]? + var firstTokenSeconds: Double + var decodeSeconds: Double + var ranksAgree: Bool? + var passed: Bool + /// `--prefix repeat`: the prompt tokens the repeat restored, and + /// whether it equals the cold request bit for bit. + var prefix: String? + var reusedPromptTokens: Int? + var restoredEqualsCold: Bool? + } + + static func run(_ arguments: [String]) throws { + guard let command = arguments.first else { throw Failure("gemma: synthesize, run, compare, allsum or lanes") } + var fields: [String: String] = [:] + var index = 1 + while index < arguments.count { + guard arguments[index].hasPrefix("--"), index + 1 < arguments.count else { + throw Failure("gemma: arguments are --name value pairs") + } + fields[arguments[index]] = arguments[index + 1] + index += 2 + } + switch command { + case "synthesize": try synthesize(fields) + case "run": try runRank(fields) + case "compare": try compare(fields) + case "allsum": try allSum(fields) + case "lanes": try lanes(fields) + default: throw Failure("gemma: synthesize, run, compare, allsum or lanes") + } + } + + private static func synthesize(_ fields: [String: String]) throws { + guard let output = fields["--output"], output.hasPrefix("/"), !FileManager.default.fileExists(atPath: output), + let bits = Int(fields["--bits"] ?? "4"), [4, 8].contains(bits), + let seed = UInt64(fields["--seed"] ?? "7"), + let dtypeName = Optional(fields["--dtype"] ?? "bfloat16"), ["bfloat16", "float32"].contains(dtypeName), + let experts = Int(fields["--experts"] ?? "16"), let topK = Int(fields["--top-k"] ?? "4") else { + throw Failure("gemma synthesize needs --output /NEW/DIR [--bits 4|8] [--seed N] [--dtype bfloat16|float32] [--experts N --top-k K]") + } + let directory = URL(fileURLWithPath: output, isDirectory: true) + try Gemma4TensorParallelModel.writeSyntheticCheckpoint(directory: directory, seed: seed, bits: bits, + dtype: dtypeName == "float32" ? .float32 : .bfloat16, experts: experts, topK: topK) + let prompt = (0 ..< 40).map { ($0 * 37 + 11) % 512 } + let request: [String: Any] = ["requestID": "synthetic-gemma4", "modelID": "synthetic-gemma4-moe-tiny-\(bits)bit-\(dtypeName)-e\(experts)k\(topK)", + "promptTokenIDs": prompt, "promptTokenIDsSHA256": tokenDigest(prompt), "outputCount": 24, "chunkSize": 16] + try JSONSerialization.data(withJSONObject: request, options: [.sortedKeys]) + .write(to: directory.appendingPathComponent("request.json")) + note("synthetic Gemma 4 checkpoint (\(bits)-bit) and request written") + } + + private static func runRank(_ fields: [String: String]) throws { + guard let mode = fields["--mode"], ["full", "split-sum", "simulated", "shard", "tp"].contains(mode), + let directory = fields["--model-dir"], let requestPath = fields["--request"], + let reportPath = fields["--report"], !FileManager.default.fileExists(atPath: reportPath), + let recordTop = Int(fields["--record-top"] ?? "8"), (0 ... 64).contains(recordTop), + let shardRank = Int(fields["--shard-rank"] ?? "0"), (0 ... 1).contains(shardRank), + let deadline = Int(fields["--deadline-seconds"] ?? "900"), (30 ... 7200).contains(deadline), + ["native", "sealed-bench"].contains(fields["--reduction"] ?? "native"), + ["yes", "no"].contains(fields["--pack"] ?? "yes"), + ["legacy", "paged"].contains(fields["--path"] ?? "legacy"), + ["none", "repeat"].contains(fields["--prefix"] ?? "none") else { + throw Failure("gemma run needs --mode full|split-sum|simulated|shard|tp, --model-dir, --request, a new --report and bounded options") + } + let paged = (fields["--path"] ?? "legacy") == "paged" + guard !paged || mode != "split-sum" else { throw Failure("--path paged does not run the split-sum oracle") } + let repeatPrefix = fields["--prefix"] == "repeat" + guard !repeatPrefix || (paged && ["simulated", "tp"].contains(mode)) else { + throw Failure("--prefix repeat runs on the paged path of simulated or tp ranks") + } + let sealed = (fields["--reduction"] ?? "native") == "sealed-bench" + guard !sealed || mode == "tp" else { throw Failure("--reduction sealed-bench applies to a tp rank only") } + let pack = (fields["--pack"] ?? "yes") == "yes" + try ProcessForcedExit.routeTerminationSignals() + ProcessNativeMemoryRelease.installForForcedExit() + try ProcessDeadline.arm(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(deadline) * 1_000_000_000, + status: 124) + let requestData = try Data(contentsOf: URL(fileURLWithPath: requestPath)) + guard requestData.count < 1 << 20 else { throw Failure("request file too large") } + let request = try JSONDecoder().decode(Request.self, from: requestData) + guard tokenDigest(request.promptTokenIDs) == request.promptTokenIDsSHA256, + (1 ... 4096).contains(request.outputCount), (1 ... 4096).contains(request.chunkSize) else { + throw Failure("the request's digest or bounds are wrong") + } + let modelDirectory = URL(fileURLWithPath: directory) + let configurationSHA = sha256Hex(try Data(contentsOf: modelDirectory.appendingPathComponent("config.json"))) + + var group: QwenTensorParallelGroup? + let role: Gemma4TensorParallelModel.Role + let reduction: QwenTensorParallelReduction? + var pair: Gemma4TensorParallelLocalPair? + switch mode { + case "full": role = .full; reduction = nil + case "split-sum": role = .splitSum; reduction = nil + case "simulated": + role = .shard(rank: 0) + pair = Gemma4TensorParallelLocalPair() + reduction = pair!.reduction(rank: 0) + case "shard": + role = .shard(rank: shardRank) + reduction = QwenTensorParallelLocalReduction(rank: shardRank, size: 2) + note("DIAGNOSTIC shard: rank \(shardRank)'s shard with no peer; tokens are not meaningful") + default: + guard let backend = QwenTensorParallelGroup.Backend(rawValue: fields["--backend"] ?? "ring") else { + throw Failure("unknown backend") + } + let g = try QwenTensorParallelGroup(backend: backend) + group = g + role = .shard(rank: g.rank) + reduction = g + note("rank \(g.rank) of \(g.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : "")") + // Everything that changes the collectives is agreed before loading. + let workload = "\(configurationSHA)|\(request.promptTokenIDsSHA256)|\(request.outputCount)|\(request.chunkSize)|top=\(recordTop)|pack=\(pack)|sealed=\(sealed)|paged=\(paged)|prefix=\(repeatPrefix)|\(Gemma4TensorParallelPlan.arithmeticAgreementFields.joined(separator: ","))" + guard try g.digestsEqual(fnv(workload)) else { + throw Failure("the ranks disagree on the workload, the model configuration or the arithmetic contract") + } + if sealed { + var scope = Data("darkbloom-tp-sealed-scope-v1|gemma4|".utf8) + scope.append(Data(configurationSHA.utf8)) + let codec = try QwenTensorParallelSealCodec.bench(group: g, scope: scope) + try codec.install() + g.sealed = codec + note("sealed all-sum installed (BENCH keys: unauthenticated ephemeral exchange; cost measurement only)") + } + } + note("loading \(mode == "simulated" ? "both ranks in one process" : role.label)") + let model = try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, role: role, reduction: reduction, + packFeedForward: pack) + note("loaded in \(String(format: "%.2f", model.loadSeconds)) s, \(model.loadedParameterBytes) parameter bytes") + if let group { guard try group.agree([7]) else { throw Failure("load barrier failed") } } + let generation: Gemma4TensorParallelModel.Generation + var pairAgrees: Bool? + var prefixOutcome: (reused: Int, equalsCold: Bool)? + func bitsEqual(_ a: Gemma4TensorParallelModel.Generation, _ b: Gemma4TensorParallelModel.Generation) -> Bool { + func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } } + return a.tokenIDs == b.tokenIDs && a.topTokenIDs == b.topTokenIDs && bits(a.topLogits) == bits(b.topLogits) + && bits(a.topLogprobs) == bits(b.topLogprobs) + && a.finalLogits.map { $0.map(\.bitPattern) } == b.finalLogits.map { $0.map(\.bitPattern) } + } + if repeatPrefix { + let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize + let runs: [(cold: Gemma4TensorParallelModel.Generation, restored: Gemma4TensorParallelModel.Generation, reused: Int)] + if let pair { + let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, + role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)]) + runs = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in + let value = try ranks.models[rank].generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, + chunk: chunk, recordTop: recordTop) + return (value.cold, value.restored, value.reusedPromptTokens) + } + pairAgrees = bitsEqual(runs[0].restored, runs[1].restored) + } else { + let value = try model.generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, chunk: chunk, + recordTop: recordTop) + runs = [(value.cold, value.restored, value.reusedPromptTokens)] + } + generation = runs[0].restored + prefixOutcome = (runs[0].reused, runs.allSatisfy { $0.reused > 0 && bitsEqual($0.restored, $0.cold) }) + note("prefix repeat: reused \(runs[0].reused) prompt tokens; restored equals cold bit for bit: \(prefixOutcome!.equalsCold)") + } else if let pair { + let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, + role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)]) + let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize + let both = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in + paged ? try ranks.models[rank].generatePaged(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop) + : try ranks.models[rank].generate(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop) + } + func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } } + pairAgrees = both[0].tokenIDs == both[1].tokenIDs && bits(both[0].topLogits) == bits(both[1].topLogits) + && bits(both[0].topLogprobs) == bits(both[1].topLogprobs) + && both[0].finalLogits.map { $0.map(\.bitPattern) } == both[1].finalLogits.map { $0.map(\.bitPattern) } + generation = both[0] + } else { + generation = paged + ? try model.generatePaged(prompt: request.promptTokenIDs, outputCount: request.outputCount, + chunk: request.chunkSize, recordTop: recordTop) + : try model.generate(prompt: request.promptTokenIDs, outputCount: request.outputCount, + chunk: request.chunkSize, recordTop: recordTop) + } + var report = Report(mode: mode, role: mode == "simulated" ? "simulated-tp2" : role.label, + rank: group?.rank ?? (mode == "shard" ? shardRank : 0), + size: group?.size ?? (pair == nil ? 1 : 2), backend: group?.backend.rawValue, reduction: sealed ? "sealed-bench" : nil, + correctnessOnly: group.map { $0.backend.correctnessOnly } ?? false, chip: chipName(), + plan: Gemma4TensorParallelPlan.name, modelConfigurationSHA256: configurationSHA, modelID: request.modelID, + requestID: request.requestID, promptTokens: request.promptTokenIDs.count, + promptTokenIDsSHA256: request.promptTokenIDsSHA256, outputCount: request.outputCount, + chunkSize: request.chunkSize, packedFeedForward: pack, path: paged ? "paged" : "legacy", + loadSeconds: model.loadSeconds, + loadedParameterBytes: model.loadedParameterBytes, + reductionsPerForward: ["full", "split-sum"].contains(mode) ? nil : model.plan.reductionsPerForward, + floatingReductions: group?.floatingReductions, + tokenIDs: generation.tokenIDs, tokenIDsSHA256: tokenDigest(generation.tokenIDs), + topTokenIDs: recordTop > 0 ? generation.topTokenIDs : nil, topLogits: recordTop > 0 ? generation.topLogits : nil, + topLogprobs: recordTop > 0 ? generation.topLogprobs : nil, finalLogits: generation.finalLogits, + firstTokenSeconds: generation.firstTokenSeconds, decodeSeconds: generation.decodeSeconds, + ranksAgree: pairAgrees, passed: (pairAgrees ?? true) && (prefixOutcome?.equalsCold ?? true), + prefix: repeatPrefix ? "repeat" : nil, reusedPromptTokens: prefixOutcome?.reused, + restoredEqualsCold: prefixOutcome?.equalsCold) + if let group { + let evidence = report.tokenIDsSHA256 + "|" + sha256Hex(Data((generation.finalLogits ?? []).flatMap { + withUnsafeBytes(of: $0.bitPattern.littleEndian) { Array($0) } })) + report.ranksAgree = try group.digestsEqual(fnv(evidence)) + report.passed = try group.agree([report.ranksAgree == true && report.restoredEqualsCold != false ? 1 : 0]) + } + note("tokens \(String(report.tokenIDsSHA256.prefix(16))): \(generation.tokenIDs.prefix(12).map(String.init).joined(separator: " "))…" + + (report.ranksAgree.map { " ranks agree: \($0)" } ?? "")) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .prettyPrinted] + guard FileManager.default.createFile(atPath: reportPath, contents: try encoder.encode(report)) else { + throw Failure("could not write the report") + } + note("report written; passed \(report.passed)") + ProcessForcedExit.finish(status: report.passed ? 0 : 2, reason: "tp-check-gemma-complete") + } + + /// QualificationComparator's verdict for two runs of one request, and + /// with `--bitwise yes` the exact equality of everything recorded. + private static func compare(_ fields: [String: String]) throws { + guard let referencePath = fields["--reference"], let candidatePath = fields["--candidate"], + let nearTie = Float(fields["--near-tie-ulps"] ?? "4"), nearTie >= 0, + ["yes", "no"].contains(fields["--bitwise"] ?? "no") else { + throw Failure("gemma compare needs --reference and --candidate [--bitwise yes|no] [--near-tie-ulps U]") + } + let decoder = JSONDecoder() + let reference = try decoder.decode(Report.self, from: Data(contentsOf: URL(fileURLWithPath: referencePath))) + let candidate = try decoder.decode(Report.self, from: Data(contentsOf: URL(fileURLWithPath: candidatePath))) + let comparison = try QualificationComparator(nearTieULPs: nearTie) + .compare(reference: try subject(reference), candidate: try subject(candidate)) + var lines = [QualificationComparator.render(comparison)] + var passed = [.exact, .tokensEqualLogitsDiffer, .divergedAtNearTie].contains(comparison.verdict) + if fields["--bitwise"] == "yes" { + func bits(_ rows: [[Float]]?) -> [[UInt32]]? { rows.map { $0.map { $0.map(\.bitPattern) } } } + let equal = reference.tokenIDs == candidate.tokenIDs + && bits(reference.topLogits) == bits(candidate.topLogits) + && bits(reference.topLogprobs) == bits(candidate.topLogprobs) + && reference.topTokenIDs == candidate.topTokenIDs + && reference.finalLogits.map { $0.map(\.bitPattern) } == candidate.finalLogits.map { $0.map(\.bitPattern) } + && reference.finalLogits != nil + lines.append("bitwise (tokens, top logits and log probabilities, final row): " + (equal ? "IDENTICAL" : "DIFFER")) + passed = passed && equal + } + lines.append("verdict \(comparison.verdict.rawValue); passed \(passed)") + print(lines.joined(separator: "\n")) + Darwin.exit(passed ? 0 : 3) + } + + /// One report as the comparator reads it: the request's identity (the + /// generation mode recorded, not compared) and its evidence. Each step's + /// near-tie unit is a bfloat16 place: the softcap's input is the head's + /// BF16 projection. + private static func subject(_ report: Report) throws -> QualificationSubject { + let identity: [String: Any] = [ + "modelID": report.modelID, "profileID": "tp-check-gemma", "requestID": report.requestID, + "promptTokenCount": report.promptTokens, "promptTokenIDsSHA256": report.promptTokenIDsSHA256, + "chunkSize": report.chunkSize, "outputCount": report.outputCount, "stopTokenIDs": [Int](), + "stageCut": 0, "prefillSchedule": "serial_v1", "artifactSHA256": report.modelConfigurationSHA256, + "configurationSHA256": report.modelConfigurationSHA256, "planSHA256": sha256Hex(Data(report.plan.utf8)), + "generationMode": report.mode, + ] + let decoded = try JSONDecoder().decode(QualificationIdentity.self, + from: JSONSerialization.data(withJSONObject: identity, options: [.sortedKeys])) + var steps: [QualificationStep]? + if let ids = report.topTokenIDs, let logits = report.topLogits, ids.count == report.tokenIDs.count { + steps = report.tokenIDs.indices.map { index in + QualificationStep(ordinal: index, frameSequence: index, committedTokens: report.promptTokens + index, + tokenID: report.tokenIDs[index], topTokenIDs: ids[index], topLogits: logits[index], + maximumTieCount: 1, rowSHA256: sha256Hex(Data(logits[index].flatMap { + withUnsafeBytes(of: $0.bitPattern.littleEndian) { Array($0) } })), rowDType: "bfloat16") + } + } + var evidence = QualificationEvidence(selectedTokenIDs: report.tokenIDs, finishReason: "length", + completedFrames: nil, committedTokens: report.promptTokens + report.tokenIDs.count, steps: steps) + if let row = report.finalLogits { + let bytes = Data(row.flatMap { withUnsafeBytes(of: $0.bitPattern.littleEndian) { Array($0) } }) + evidence.finalLogits = QualificationFinalLogits(shape: [row.count], dtype: "float32", byteCount: bytes.count, + logicalBytesSHA256: sha256Hex(bytes), values: row) + } + return QualificationSubject(label: "\(report.role) on \(report.chip)", identity: decoded, evidence: evidence) + } + + struct LanesReport: Codable { + var schema = "darkbloom_cluster_tp_check_gemma_lanes_report_v1" + var mode: String + var rank: Int + var backend: String? + var reduction: String? + var chip: String + var modelConfigurationSHA256: String + var promptTokens: [Int] + var outputCount: Int + var soloTokens: [[Int]] + var laneTokens: [[Int]] + var lanesEqualSolo: Bool + var ranksAgree: Bool? + var passed: Bool + } + + /// Greedy requests together through the batch driver against each alone. + private static func lanes(_ fields: [String: String]) throws { + guard let mode = fields["--mode"], ["simulated", "tp"].contains(mode), let directory = fields["--model-dir"], + let reportPath = fields["--report"], !FileManager.default.fileExists(atPath: reportPath), + let count = Int(fields["--lanes"] ?? "3"), (2 ... 8).contains(count), + let outputs = Int(fields["--outputs"] ?? "8"), (1 ... 64).contains(outputs), + let deadline = Int(fields["--deadline-seconds"] ?? "900"), (30 ... 7200).contains(deadline), + ["native", "sealed-bench"].contains(fields["--reduction"] ?? "native") else { + throw Failure("gemma lanes needs --mode simulated|tp, --model-dir, a new --report and bounded options") + } + let sealed = (fields["--reduction"] ?? "native") == "sealed-bench" + guard !sealed || mode == "tp" else { throw Failure("--reduction sealed-bench applies to a tp rank only") } + try ProcessForcedExit.routeTerminationSignals() + ProcessNativeMemoryRelease.installForForcedExit() + try ProcessDeadline.arm(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(deadline) * 1_000_000_000, + status: 124) + let modelDirectory = URL(fileURLWithPath: directory) + let configurationSHA = sha256Hex(try Data(contentsOf: modelDirectory.appendingPathComponent("config.json"))) + let chunk = 16 + @Sendable func prompts(vocabulary: Int) -> [[Int]] { + (0 ..< count).map { lane in (0 ..< (24 + 9 * lane)).map { ($0 * (37 + 2 * lane) + 11 + 5 * lane) % vocabulary } } + } + @Sendable func both(_ model: Gemma4TensorParallelModel) throws -> (solo: [[Int]], lanes: [[Int]]) { + let requests = prompts(vocabulary: model.plan.vocabularySize) + let solo = try requests.map { try model.generatePaged(prompt: $0, outputCount: outputs, chunk: chunk).tokenIDs } + return (solo, try model.generateLanes(prompts: requests, outputCount: outputs, chunk: chunk)) + } + var report: LanesReport + if mode == "simulated" { + let pair = Gemma4TensorParallelLocalPair() + let ranks = Ranks(try (0 ..< 2).map { + try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, role: .shard(rank: $0), reduction: pair.reduction(rank: $0)) + }) + note("both ranks in one process, \(count) lanes") + let results = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { try both(ranks.models[$0]) } + let agree = results[0].solo == results[1].solo && results[0].lanes == results[1].lanes + let equal = results.allSatisfy { $0.lanes == $0.solo } + report = LanesReport(mode: mode, rank: 0, chip: chipName(), modelConfigurationSHA256: configurationSHA, + promptTokens: prompts(vocabulary: ranks.models[0].plan.vocabularySize).map(\.count), outputCount: outputs, + soloTokens: results[0].solo, laneTokens: results[0].lanes, lanesEqualSolo: equal, ranksAgree: agree, + passed: equal && agree) + } else { + guard let backend = QwenTensorParallelGroup.Backend(rawValue: fields["--backend"] ?? "ring") else { + throw Failure("unknown backend") + } + let group = try QwenTensorParallelGroup(backend: backend) + note("rank \(group.rank) of \(group.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : ""), \(count) lanes") + guard try group.digestsEqual(fnv("\(configurationSHA)|lanes=\(count)|outputs=\(outputs)|sealed=\(sealed)")) else { + throw Failure("the ranks disagree on the workload") + } + if sealed { + var scope = Data("darkbloom-tp-sealed-scope-v1|gemma4-lanes|".utf8) + scope.append(Data(configurationSHA.utf8)) + let codec = try QwenTensorParallelSealCodec.bench(group: group, scope: scope) + try codec.install() + group.sealed = codec + } + let model = try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, role: .shard(rank: group.rank), + reduction: group) + let result = try both(model) + let equal = result.lanes == result.solo + let evidence = (result.solo + result.lanes).map { $0.map(String.init).joined(separator: ",") }.joined(separator: ";") + let agree = try group.digestsEqual(fnv(evidence)) + report = LanesReport(mode: mode, rank: group.rank, backend: backend.rawValue, reduction: sealed ? "sealed-bench" : nil, + chip: chipName(), modelConfigurationSHA256: configurationSHA, + promptTokens: prompts(vocabulary: model.plan.vocabularySize).map(\.count), outputCount: outputs, + soloTokens: result.solo, laneTokens: result.lanes, lanesEqualSolo: equal, ranksAgree: agree, + passed: try group.agree([equal && agree ? 1 : 0])) + } + note("lanes equal solo: \(report.lanesEqualSolo); ranks agree: \(report.ranksAgree ?? false)") + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .prettyPrinted] + guard FileManager.default.createFile(atPath: reportPath, contents: try encoder.encode(report)) else { + throw Failure("could not write the report") + } + note("report written; passed \(report.passed)") + ProcessForcedExit.finish(status: report.passed ? 0 : 2, reason: "tp-check-gemma-lanes-complete") + } + + /// Cross-rank sums at Gemma 4 26B decode and prefill widths (2,816): the + /// attention row, the packed feed-forward rows (top-8 + 1) and a 2,048-token + /// chunk's attention rows, each `count` times, native and sealed. + private static func allSum(_ fields: [String: String]) throws { + guard let backend = QwenTensorParallelGroup.Backend(rawValue: fields["--backend"] ?? "ring"), + let count = Int(fields["--count"] ?? "61"), (1 ... 10_000).contains(count) else { + throw Failure("gemma allsum takes [--backend ring|socket|jaccl] [--count N]") + } + let group = try QwenTensorParallelGroup(backend: backend) + note("rank \(group.rank) of \(group.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : "")") + let shapes = [[1, 1, 2816], [1, 9, 2816], [1, 2048, 2816]] + func pass(sealed: Bool) throws { + for shape in shapes { + let value = MLXArray.ones(shape, dtype: .float32) * Float(group.rank + 1) + eval(value) + _ = try group.exchangeIntegers([1]) + let start = DispatchTime.now().uptimeNanoseconds + var chained = value + for _ in 0 ..< count { chained = group.allSum(chained) * 0.5 } + eval(chained) + let each = Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6 / Double(count) + // (1 + 2) / 2 from the first sum on: any other value is a stale or torn read. + let error = abs(chained - 1.5).max().item(Float.self) + note(String(format: "gemma allsum sealed=%d shape=%@ bytes=%d per_sum=%.3f ms max_error=%g", sealed ? 1 : 0, + shape.map(String.init).joined(separator: "x"), shape.reduce(4, *), each, error)) + guard error == 0 else { throw Failure("a cross-rank sum returned a wrong value") } + } + } + try pass(sealed: false) + let codec = try QwenTensorParallelSealCodec.bench(group: group, scope: Data("gemma-tp-allsum".utf8)) + try codec.install() + group.sealed = codec + try pass(sealed: true) + note("gemma allsum passed") + } +} diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/MiMoCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/MiMoCheck.swift new file mode 100644 index 0000000000..01836a17ee --- /dev/null +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/MiMoCheck.swift @@ -0,0 +1,486 @@ +import DarkbloomClusterQualification +import DarkbloomClusterRuntime +import Darwin +import Foundation +import MLX + +// MiMo V2.6 tensor-parallel oracles (MiMoTensorParallelModel), greedy, MTP off: +// +// darkbloom-cluster-tp-check mimo synthesize --output /NEW/DIR [--variant kernel|tiny] [--seed N] +// [--dtype bfloat16|float32] [--experts N --top-k K] [--mtp yes] +// a random MiMo checkpoint (never a model pass), request.json (40-token prompt, longer than the window +// and the 16-token chunk), request-short.json (6 tokens, shorter than both) and request-long.json +// (192 tokens: three 64-token pages before decode), 64 outputs each +// darkbloom-cluster-tp-check mimo run --mode full|simulated|shard|tp --model-dir DIR --request FILE --report FILE +// [--record-top K] [--backend ring|socket|jaccl] [--reduction native|sealed-bench] [--shard-rank R] +// [--deadline-seconds S] [--temperature T [--sample-seed S]] [--path contiguous|paged] +// [--agreement-tamper yes] [--record-routes yes] +// greedy, or with --temperature a keyed draw (MLXRandom.categorical, key seed + step) over the whole +// row, which every rank gathers bit for bit. `--path paged` is the resident runtime's path: the +// verified load (the manifest first, then only this rank's byte runs), paged KV, the per-step +// agreement sum, 100-op decode buffers, greedy logprobs through the split top-k gather and sampling +// with the product's QwenStageTokenSampler over the gathered row. `--agreement-tamper yes` changes this +// rank's agreement (a tp rank must then refuse before loading). `--record-routes yes` (paged) records +// every position's routed expert sets; `compare` then reports where they first differ. +// `--mtp-depth D` (paged; a `--mtp yes` checkpoint) decodes in speculative rounds: D proposals a round +// from the replicated trained heads, or with `--mtp-script REPORT` the tokens of an earlier report +// (forced acceptance), every `--mtp-misses K`-th moved off so the target rejects it. +// darkbloom-cluster-tp-check mimo compare --reference FILE --candidate FILE [--bitwise yes|no] [--near-tie-ulps U] +// darkbloom-cluster-tp-check mimo allsum [--backend ring|socket|jaccl] [--count N] +// +// `full` is the unsharded model; `simulated` both ranks' shards in one +// process, each on its own thread and stream, every collective the FP32 sum +// of both ranks' partials (`tp` must equal it bit for bit, caches included); +// `shard` one rank with no peer (diagnostic: wrong tokens by construction); +// `tp` one rank of a two-rank run over JACCL (two Macs) or the local ring or +// socket (two processes on one Mac over 127.0.0.1, correctness only). +// `--reduction sealed-bench` seals every floating collective with the fork's +// sealed all-sum (BENCH keys from an unauthenticated ephemeral exchange: the +// sealed path's arithmetic and cost, never a product trust). `compare` holds +// a candidate to a reference with QualificationComparator; `--bitwise yes` +// also requires every token, recorded top logit, log probability, step row +// digest, the final row and each shared rank's cache digest to be identical. +// A report names roles and chips only, never a host, an address or a path. +enum MiMoCheck { + struct Report: Codable { + var schema = "darkbloom_cluster_tp_check_mimo_report_v1" + var mode: String + var role: String + var rank: Int + var size: Int + var backend: String? + var reduction: String? + var correctnessOnly: Bool + var chip: String + var plan: String + var planFingerprint: String + var modelConfigurationSHA256: String + var modelID: String + var requestID: String + var promptTokens: Int + var promptTokenIDsSHA256: String + var outputCount: Int + var chunkSize: Int + /// Set when the run sampled (the product's sampler over the gathered row). + var temperature: Float? + var sampleSeed: UInt64? + var loadSeconds: Double + var loadedParameterBytes: Int + var reductionsPerForward: Int? + var floatingReductions: Int? + var tokenIDs: [Int] + var tokenIDsSHA256: String + var topTokenIDs: [[Int]]? + var topLogits: [[Float]]? + var topLogprobs: [[Float]]? + var stepRowSHA256: [String]? + var finalLogits: [Float]? + /// Per rank (one entry for `full`), the KV caches' digest after the + /// last step; nil for a rank this run does not hold. + var cacheSHA256: [String?] + var firstTokenSeconds: Double + var decodeSeconds: Double + var ranksAgree: Bool? + var passed: Bool + /// `paged`: the resident runtime's path, read through the verified load. + var path: String? + var verifiedAggregateSHA256: String? + var readBytes: Int? + var textBytes: Int? + /// Per position (prompt, then each fed output token), each routed layer's experts. + var routeSets: [[[Int]]]? + /// Speculative rounds (`--mtp-depth`): proposals, how many were kept, kept per position. + var speculativeDepth: Int? + var speculativeProposals: String? + var speculativeRounds: Int? + var draftedTokens: Int? + var acceptedDrafts: Int? + var acceptedByPosition: [Int]? + var draftHeadBytes: Int? + } + + static func run(_ arguments: [String]) throws { + guard let command = arguments.first else { throw Failure("mimo: synthesize, run, compare or allsum") } + var fields: [String: String] = [:] + var index = 1 + while index < arguments.count { + guard arguments[index].hasPrefix("--"), index + 1 < arguments.count else { + throw Failure("mimo: arguments are --name value pairs") + } + fields[arguments[index]] = arguments[index + 1] + index += 2 + } + switch command { + case "synthesize": try synthesize(fields) + case "run": try runRank(fields) + case "compare": try compare(fields) + case "allsum": try allSum(fields) + default: throw Failure("mimo: synthesize, run, compare or allsum") + } + } + + private static func synthesize(_ fields: [String: String]) throws { + guard let output = fields["--output"], output.hasPrefix("/"), !FileManager.default.fileExists(atPath: output), + let variant = MiMoTensorParallelModel.SyntheticVariant(rawValue: fields["--variant"] ?? "kernel"), + let seed = UInt64(fields["--seed"] ?? "7"), + let dtypeName = Optional(fields["--dtype"] ?? "bfloat16"), ["bfloat16", "float32"].contains(dtypeName), + (fields["--experts"] == nil) == (fields["--top-k"] == nil), + fields["--experts"].map({ Int($0) != nil }) ?? true, fields["--top-k"].map({ Int($0) != nil }) ?? true, + ["yes", "no"].contains(fields["--mtp"] ?? "no") else { + throw Failure("mimo synthesize needs --output /NEW/DIR [--variant kernel|tiny] [--seed N] [--dtype bfloat16|float32] [--experts N --top-k K] [--mtp yes]") + } + let directory = URL(fileURLWithPath: output, isDirectory: true) + try MiMoTensorParallelModel.writeSyntheticCheckpoint(directory: directory, variant: variant, seed: seed, + dtype: dtypeName == "float32" ? .float32 : .bfloat16, + experts: fields["--experts"].flatMap { Int($0) }, topK: fields["--top-k"].flatMap { Int($0) }, + mtp: fields["--mtp"] == "yes") + let vocabulary = MiMoTensorParallelModel.syntheticConfiguration(variant)["vocab_size"] as! Int + for (name, count) in [("request.json", 40), ("request-short.json", 6), ("request-long.json", 192)] { + let prompt = (0 ..< count).map { ($0 * 37 + 11) % vocabulary } + let request: [String: Any] = ["requestID": "synthetic-mimo-\(count)", + "modelID": "synthetic-mimo-v26-\(variant.rawValue)-\(dtypeName)-s\(seed)", + "promptTokenIDs": prompt, "promptTokenIDsSHA256": tokenDigest(prompt), "outputCount": 64, "chunkSize": 16] + try JSONSerialization.data(withJSONObject: request, options: [.sortedKeys]) + .write(to: directory.appendingPathComponent(name)) + } + note("synthetic MiMo checkpoint (\(variant.rawValue), \(dtypeName)) and requests written") + } + + private static func runRank(_ fields: [String: String]) throws { + guard let mode = fields["--mode"], ["full", "simulated", "shard", "tp"].contains(mode), + let directory = fields["--model-dir"], let requestPath = fields["--request"], + let reportPath = fields["--report"], !FileManager.default.fileExists(atPath: reportPath), + let recordTop = Int(fields["--record-top"] ?? "8"), (0 ... 64).contains(recordTop), + let shardRank = Int(fields["--shard-rank"] ?? "0"), (0 ... 1).contains(shardRank), + let deadline = Int(fields["--deadline-seconds"] ?? "900"), (30 ... 7200).contains(deadline), + ["native", "sealed-bench"].contains(fields["--reduction"] ?? "native"), + fields["--temperature"].map({ Float($0).map { $0.isFinite && $0 > 0 } ?? false }) ?? true, + fields["--sample-seed"].map({ UInt64($0) != nil }) ?? true, + ["contiguous", "paged"].contains(fields["--path"] ?? "contiguous"), + (fields["--agreement-tamper"] ?? "no") == "no" || (fields["--agreement-tamper"] == "yes" && fields["--mode"] == "tp"), + (fields["--record-routes"] ?? "no") == "no" || (fields["--record-routes"] == "yes" && fields["--path"] == "paged"), + fields["--mtp-depth"].map({ Int($0).map { (1 ... 3).contains($0) } ?? false }) ?? true, + fields["--mtp-depth"] == nil || fields["--path"] == "paged", + (fields["--mtp-script"] == nil && fields["--mtp-misses"] == nil) || fields["--mtp-depth"] != nil, + fields["--mtp-misses"].map({ Int($0).map { $0 >= 0 } ?? false }) ?? true else { + throw Failure("mimo run needs --mode full|simulated|shard|tp, --model-dir, --request, a new --report and bounded options") + } + var speculative: MiMoTensorParallelModel.SpeculativeOptions? + if let depth = fields["--mtp-depth"].flatMap({ Int($0) }) { + if let scriptPath = fields["--mtp-script"] { + let script = try JSONDecoder().decode(Report.self, from: Data(contentsOf: URL(fileURLWithPath: scriptPath))) + speculative = .init(depth: depth, proposals: .scripted(tokens: script.tokenIDs, + missEvery: Int(fields["--mtp-misses"] ?? "0")!)) + } else { + speculative = .init(depth: depth, proposals: .heads) + } + } + let sampling = fields["--temperature"].map { + MiMoTensorParallelModel.Sampling(temperature: Float($0)!, seed: UInt64(fields["--sample-seed"] ?? "1")!) + } + let paged = fields["--path"] == "paged" + let recordRoutes = fields["--record-routes"] == "yes" + let sealed = (fields["--reduction"] ?? "native") == "sealed-bench" + guard !sealed || mode == "tp" else { throw Failure("--reduction sealed-bench applies to a tp rank only") } + try ProcessForcedExit.routeTerminationSignals() + ProcessNativeMemoryRelease.installForForcedExit() + try ProcessDeadline.arm(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(deadline) * 1_000_000_000, + status: 124) + let requestData = try Data(contentsOf: URL(fileURLWithPath: requestPath)) + guard requestData.count < 1 << 20 else { throw Failure("request file too large") } + let request = try JSONDecoder().decode(Request.self, from: requestData) + guard tokenDigest(request.promptTokenIDs) == request.promptTokenIDsSHA256, + (1 ... 4096).contains(request.outputCount), (1 ... 4096).contains(request.chunkSize) else { + throw Failure("the request's digest or bounds are wrong") + } + let modelDirectory = URL(fileURLWithPath: directory) + let configurationData = try Data(contentsOf: modelDirectory.appendingPathComponent("config.json")) + let configurationSHA = sha256Hex(configurationData) + let plan = try MiMoTensorParallelPlan(configuration: configurationData) + + var group: QwenTensorParallelGroup? + let role: MiMoTensorParallelModel.Role + let reduction: QwenTensorParallelReduction? + var pair: Gemma4TensorParallelLocalPair? + switch mode { + case "full": role = .full; reduction = nil + case "simulated": + role = .shard(rank: 0) + pair = Gemma4TensorParallelLocalPair() + reduction = pair!.reduction(rank: 0) + case "shard": + role = .shard(rank: shardRank) + reduction = QwenTensorParallelLocalReduction(rank: shardRank, size: 2) + note("DIAGNOSTIC shard: rank \(shardRank)'s shard with no peer; tokens are not meaningful") + default: + guard let backend = QwenTensorParallelGroup.Backend(rawValue: fields["--backend"] ?? "ring") else { + throw Failure("unknown backend") + } + let g = try QwenTensorParallelGroup(backend: backend) + group = g + role = .shard(rank: g.rank) + reduction = g + note("rank \(g.rank) of \(g.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : "")") + // Everything that changes the collectives is agreed before loading. + var workload = "\(configurationSHA)|\(request.promptTokenIDsSHA256)|\(request.outputCount)|\(request.chunkSize)|top=\(recordTop)|sealed=\(sealed)|sampling=\(sampling.map { "\($0.temperature.bitPattern):\($0.seed)" } ?? "greedy")|\(plan.fingerprint)" + if paged { + // The resident runtime's load agreement: the plan, its arithmetic and the serving contract. + workload += "|" + (MiMoTensorParallelPlan.arithmeticAgreementFields + + MiMoTensorParallelResidentRuntime.servingAgreementFields(chunkTokens: request.chunkSize)).joined(separator: "|") + } + if let speculative { + var proposals = "heads" + if case .scripted(let tokens, let missEvery) = speculative.proposals { + proposals = "script-\(tokenDigest(tokens))-\(missEvery)" + } + workload += "|mtp-depth=\(speculative.depth)|\(proposals)" + } + if fields["--agreement-tamper"] == "yes" { workload += "|tampered-on-rank-\(g.rank)" } + guard try g.digestsEqual(fnv(workload)) else { + throw Failure("the ranks disagree on the workload, the model configuration or the arithmetic contract") + } + if sealed { + var scope = Data("darkbloom-tp-sealed-scope-v1|mimo-v26|".utf8) + scope.append(Data(configurationSHA.utf8)) + let codec = try QwenTensorParallelSealCodec.bench(group: g, scope: scope) + try codec.install() + g.sealed = codec + note("sealed all-sum installed (BENCH keys: unauthenticated ephemeral exchange; cost measurement only)") + } + } + note("loading \(mode == "simulated" ? "both ranks in one process" : role.label)\(paged ? " (verified, this rank's byte runs)" : "")") + var verified: (aggregate: String, readBytes: Int, textBytes: Int)? + func load(_ role: MiMoTensorParallelModel.Role, _ reduction: QwenTensorParallelReduction?) throws -> MiMoTensorParallelModel { + guard paged else { return try MiMoTensorParallelModel.load(modelDirectory: modelDirectory, role: role, reduction: reduction) } + let value = try MiMoTensorParallelModel.loadVerified(modelDirectory: modelDirectory, role: role, reduction: reduction) + if verified == nil { verified = (value.aggregateSHA256, value.readBytes, value.textBytes) } + return value.model + } + var draftHeadBytes: Int? + func loadHeads(_ model: MiMoTensorParallelModel) throws { + guard let speculative, case .heads = speculative.proposals else { return } + draftHeadBytes = try model.loadDraftHeads(modelDirectory: modelDirectory) + } + let model = try load(role, reduction) + try loadHeads(model) + note("loaded in \(String(format: "%.2f", model.loadSeconds)) s, \(model.loadedParameterBytes) parameter bytes" + + (draftHeadBytes.map { ", draft heads \($0) bytes (replicated)" } ?? "")) + if let group { guard try group.agree([7]) else { throw Failure("load barrier failed") } } + let generation: MiMoTensorParallelModel.Generation + var caches: [String?] + var pairAgrees: Bool? + if let pair { + final class Ranks: @unchecked Sendable { let models: [MiMoTensorParallelModel]; init(_ m: [MiMoTensorParallelModel]) { models = m } } + let peer = try load(.shard(rank: 1), pair.reduction(rank: 1)) + try loadHeads(peer) + let ranks = Ranks([model, peer]) + let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize + let speculative = speculative + let both = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in + paged ? try ranks.models[rank].generatePaged(prompt: prompt, outputCount: count, chunk: chunk, + recordTop: recordTop, sampling: sampling, + recordRoutes: recordRoutes, speculative: speculative) + : try ranks.models[rank].generate(prompt: prompt, outputCount: count, chunk: chunk, + recordTop: recordTop, sampling: sampling) + } + func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } } + pairAgrees = both[0].tokenIDs == both[1].tokenIDs && bits(both[0].topLogits) == bits(both[1].topLogits) + && bits(both[0].topLogprobs) == bits(both[1].topLogprobs) && both[0].stepRowSHA256 == both[1].stepRowSHA256 + && both[0].finalLogits.map { $0.map(\.bitPattern) } == both[1].finalLogits.map { $0.map(\.bitPattern) } + generation = both[0] + caches = both.map(\.cacheSHA256) + } else { + generation = paged + ? try model.generatePaged(prompt: request.promptTokenIDs, outputCount: request.outputCount, + chunk: request.chunkSize, recordTop: recordTop, sampling: sampling, + recordRoutes: recordRoutes, speculative: speculative) + : try model.generate(prompt: request.promptTokenIDs, outputCount: request.outputCount, + chunk: request.chunkSize, recordTop: recordTop, sampling: sampling) + switch role { + case .full: caches = [generation.cacheSHA256] + case .shard(let rank): caches = (0 ..< 2).map { $0 == rank ? generation.cacheSHA256 : nil } + } + } + let rank: Int + if case .shard(let r) = role, pair == nil { rank = r } else { rank = 0 } + var report = Report(mode: mode, role: mode == "simulated" ? "simulated-tp2" : role.label, rank: rank, + size: group?.size ?? (pair == nil ? 1 : 2), backend: group?.backend.rawValue, reduction: sealed ? "sealed-bench" : nil, + correctnessOnly: group.map { $0.backend.correctnessOnly } ?? false, chip: chipName(), + plan: MiMoTensorParallelPlan.name, planFingerprint: plan.fingerprint, modelConfigurationSHA256: configurationSHA, + modelID: request.modelID, requestID: request.requestID, promptTokens: request.promptTokenIDs.count, + promptTokenIDsSHA256: request.promptTokenIDsSHA256, outputCount: request.outputCount, + chunkSize: request.chunkSize, temperature: sampling?.temperature, sampleSeed: sampling?.seed, + loadSeconds: model.loadSeconds, loadedParameterBytes: model.loadedParameterBytes, + reductionsPerForward: mode == "full" ? nil : plan.reductionsPerForward, + floatingReductions: group?.floatingReductions, + tokenIDs: generation.tokenIDs, tokenIDsSHA256: tokenDigest(generation.tokenIDs), + topTokenIDs: recordTop > 0 ? generation.topTokenIDs : nil, topLogits: recordTop > 0 ? generation.topLogits : nil, + topLogprobs: recordTop > 0 ? generation.topLogprobs : nil, + stepRowSHA256: recordTop > 0 ? generation.stepRowSHA256 : nil, finalLogits: generation.finalLogits, + cacheSHA256: caches, firstTokenSeconds: generation.firstTokenSeconds, decodeSeconds: generation.decodeSeconds, + ranksAgree: pairAgrees, passed: pairAgrees ?? true, path: paged ? "paged" : nil, + verifiedAggregateSHA256: verified?.aggregate, readBytes: verified?.readBytes, textBytes: verified?.textBytes, + routeSets: generation.routeSets, speculativeDepth: speculative?.depth, + speculativeProposals: speculative.map { if case .heads = $0.proposals { return "heads" } else { return "script" } }, + speculativeRounds: generation.speculativeRounds, draftedTokens: generation.draftedTokens, + acceptedDrafts: generation.acceptedDrafts, acceptedByPosition: generation.acceptedByPosition, + draftHeadBytes: draftHeadBytes) + if let group { + // Ranks hold different caches; they must agree on everything else. + let evidence = report.tokenIDsSHA256 + "|" + (generation.stepRowSHA256.last ?? "") + report.ranksAgree = try group.digestsEqual(fnv(evidence)) + report.passed = try group.agree([report.ranksAgree == true ? 1 : 0]) + } + note("tokens \(String(report.tokenIDsSHA256.prefix(16))): \(generation.tokenIDs.prefix(12).map(String.init).joined(separator: " "))…" + + (report.ranksAgree.map { " ranks agree: \($0)" } ?? "")) + if let rounds = generation.speculativeRounds { + note("speculative rounds \(rounds): drafted \(generation.draftedTokens ?? 0), kept \(generation.acceptedDrafts ?? 0)" + + " (by position \((generation.acceptedByPosition ?? []).map(String.init).joined(separator: "-")))") + } + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .prettyPrinted] + guard FileManager.default.createFile(atPath: reportPath, contents: try encoder.encode(report)) else { + throw Failure("could not write the report") + } + note("report written; passed \(report.passed)") + ProcessForcedExit.finish(status: report.passed ? 0 : 2, reason: "tp-check-mimo-complete") + } + + /// QualificationComparator's verdict for two runs of one request, and + /// with `--bitwise yes` the exact equality of everything recorded. + private static func compare(_ fields: [String: String]) throws { + guard let referencePath = fields["--reference"], let candidatePath = fields["--candidate"], + let nearTie = Float(fields["--near-tie-ulps"] ?? "4"), nearTie >= 0, + ["yes", "no"].contains(fields["--bitwise"] ?? "no") else { + throw Failure("mimo compare needs --reference and --candidate [--bitwise yes|no] [--near-tie-ulps U]") + } + let decoder = JSONDecoder() + let reference = try decoder.decode(Report.self, from: Data(contentsOf: URL(fileURLWithPath: referencePath))) + let candidate = try decoder.decode(Report.self, from: Data(contentsOf: URL(fileURLWithPath: candidatePath))) + let comparison = try QualificationComparator(nearTieULPs: nearTie) + .compare(reference: try subject(reference), candidate: try subject(candidate)) + var lines = [QualificationComparator.render(comparison)] + var passed = [.exact, .tokensEqualLogitsDiffer, .divergedAtNearTie].contains(comparison.verdict) + if fields["--bitwise"] == "yes" { + func bits(_ rows: [[Float]]?) -> [[UInt32]]? { rows.map { $0.map { $0.map(\.bitPattern) } } } + let shared = zip(reference.cacheSHA256, candidate.cacheSHA256).filter { $0.0 != nil && $0.1 != nil } + let equal = reference.tokenIDs == candidate.tokenIDs + && bits(reference.topLogits) == bits(candidate.topLogits) + && bits(reference.topLogprobs) == bits(candidate.topLogprobs) + && reference.topTokenIDs == candidate.topTokenIDs + && reference.stepRowSHA256 == candidate.stepRowSHA256 && reference.stepRowSHA256 != nil + && reference.finalLogits.map { $0.map(\.bitPattern) } == candidate.finalLogits.map { $0.map(\.bitPattern) } + && reference.finalLogits != nil + && reference.cacheSHA256.count == candidate.cacheSHA256.count && !shared.isEmpty + && shared.allSatisfy { $0.0 == $0.1 } + lines.append("bitwise (tokens, top logits and log probabilities, every step's row, final row, \(shared.count) rank cache(s)): " + + (equal ? "IDENTICAL" : "DIFFER")) + passed = passed && equal + } + if let referenceRoutes = reference.routeSets, let candidateRoutes = candidate.routeSets { + lines.append(routeDiagnostic(reference: referenceRoutes, candidate: candidateRoutes, + promptTokens: reference.promptTokens, + tokenDivergence: reference.tokenIDs.indices.first { index in + index >= candidate.tokenIDs.count || reference.tokenIDs[index] != candidate.tokenIDs[index] + })) + } + lines.append("verdict \(comparison.verdict.rawValue); passed \(passed)") + print(lines.joined(separator: "\n")) + Darwin.exit(passed ? 0 : 3) + } + + /// Where two runs' routed expert sets first differ, over the positions whose + /// inputs are still equal: the prompt, then each output token fed back before + /// the first token divergence. Reported, never required. Routed layers are + /// numbered among the routed layers only. + private static func routeDiagnostic(reference: [[[Int]]], candidate: [[[Int]]], promptTokens: Int, + tokenDivergence: Int?) -> String { + let comparable = min(reference.count, candidate.count, promptTokens + (tokenDivergence ?? Int.max / 2)) + var differing = 0, layers = 0 + var first: (position: Int, layer: Int)? + for position in 0 ..< comparable { + let count = min(reference[position].count, candidate[position].count) + layers = max(layers, count) + for layer in 0 ..< count where reference[position][layer] != candidate[position][layer] { + differing += 1 + if first == nil { first = (position, layer) } + } + } + var line = "route sets: \(comparable) positions x \(layers) routed layers with equal inputs (prompt \(promptTokens), " + + "first token divergence \(tokenDivergence.map(String.init) ?? "none")): \(differing) differ" + if let first { + let place = first.position < promptTokens ? "prompt position \(first.position)" : "output \(first.position - promptTokens)" + line += "; first at \(place), routed layer \(first.layer): reference \(reference[first.position][first.layer])" + + " candidate \(candidate[first.position][first.layer])" + } + return line + } + + /// One report as the comparator reads it. Each step's near-tie unit is a + /// bfloat16 place: the head's logits are BF16 before selection widens them. + private static func subject(_ report: Report) throws -> QualificationSubject { + let identity: [String: Any] = [ + "modelID": report.modelID, "profileID": "tp-check-mimo", "requestID": report.requestID, + "promptTokenCount": report.promptTokens, "promptTokenIDsSHA256": report.promptTokenIDsSHA256, + "chunkSize": report.chunkSize, "outputCount": report.outputCount, "stopTokenIDs": [Int](), + "stageCut": 0, "prefillSchedule": "serial_v1", "artifactSHA256": report.modelConfigurationSHA256, + "configurationSHA256": report.modelConfigurationSHA256, "planSHA256": sha256Hex(Data(report.plan.utf8)), + "generationMode": report.mode, + ] + let decoded = try JSONDecoder().decode(QualificationIdentity.self, + from: JSONSerialization.data(withJSONObject: identity, options: [.sortedKeys])) + var steps: [QualificationStep]? + if let ids = report.topTokenIDs, let logits = report.topLogits, ids.count == report.tokenIDs.count { + steps = report.tokenIDs.indices.map { index in + QualificationStep(ordinal: index, frameSequence: index, committedTokens: report.promptTokens + index, + tokenID: report.tokenIDs[index], topTokenIDs: ids[index], topLogits: logits[index], + maximumTieCount: 1, rowSHA256: sha256Hex(Data(logits[index].flatMap { + withUnsafeBytes(of: $0.bitPattern.littleEndian) { Array($0) } })), rowDType: "bfloat16") + } + } + var evidence = QualificationEvidence(selectedTokenIDs: report.tokenIDs, finishReason: "length", + completedFrames: nil, committedTokens: report.promptTokens + report.tokenIDs.count, steps: steps) + if let row = report.finalLogits { + let bytes = Data(row.flatMap { withUnsafeBytes(of: $0.bitPattern.littleEndian) { Array($0) } }) + evidence.finalLogits = QualificationFinalLogits(shape: [row.count], dtype: "float32", byteCount: bytes.count, + logicalBytesSHA256: sha256Hex(bytes), values: row) + } + return QualificationSubject(label: "\(report.role) on \(report.chip)", identity: decoded, evidence: evidence) + } + + /// Cross-rank sums at MiMo V2.6 Flash widths (hidden 4,096): one decode + /// row, a 7-row verify window and a 2,048-token chunk, each `count` times, + /// native and sealed. + private static func allSum(_ fields: [String: String]) throws { + guard let backend = QwenTensorParallelGroup.Backend(rawValue: fields["--backend"] ?? "ring"), + let count = Int(fields["--count"] ?? "97"), (1 ... 10_000).contains(count) else { + throw Failure("mimo allsum takes [--backend ring|socket|jaccl] [--count N]") + } + let group = try QwenTensorParallelGroup(backend: backend) + note("rank \(group.rank) of \(group.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : "")") + let shapes = [[1, 1, 4096], [1, 7, 4096], [1, 2048, 4096]] + func pass(sealed: Bool) throws { + for shape in shapes { + let value = MLXArray.ones(shape, dtype: .float32) * Float(group.rank + 1) + eval(value) + _ = try group.exchangeIntegers([1]) + let start = DispatchTime.now().uptimeNanoseconds + var chained = value + for _ in 0 ..< count { chained = group.allSum(chained) * 0.5 } + eval(chained) + let each = Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6 / Double(count) + // (1 + 2) / 2 from the first sum on: any other value is a stale or torn read. + let error = abs(chained - 1.5).max().item(Float.self) + note(String(format: "mimo allsum sealed=%d shape=%@ bytes=%d per_sum=%.3f ms max_error=%g", sealed ? 1 : 0, + shape.map(String.init).joined(separator: "x"), shape.reduce(4, *), each, error)) + guard error == 0 else { throw Failure("a cross-rank sum returned a wrong value") } + } + } + try pass(sealed: false) + let codec = try QwenTensorParallelSealCodec.bench(group: group, scope: Data("mimo-tp-allsum".utf8)) + try codec.install() + group.sealed = codec + try pass(sealed: true) + note("mimo allsum passed") + } +} diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift new file mode 100644 index 0000000000..8fea759d74 --- /dev/null +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift @@ -0,0 +1,69 @@ +import DarkbloomClusterRuntime +import Foundation +import MLX + +// The batch driver's plain decode on two ranks of one Mac (`QwenTensorParallelDecodeBench`): +// MLX_RANK=0|1 MLX_HOSTFILE=hosts.json darkbloom-cluster-tp-check qwen-decode --model-dir /DIR \ +// [--backend ring|socket] [--reduction native|sealed-bench] [--width 1] [--prompt-tokens 32] \ +// [--output-tokens 64] [--sampled 0|1] [--control exchanged,folded] [--repeats 3] [--answer-delay-us 0] +// Each rank logs every run's decode step time and token digest; both agree +// that every run retired the same tokens. Loopback timings show a step's host +// work and synchronization, never a pair's. +enum QwenDecodeCheck { + static func run(_ arguments: [String]) throws { + var options: [String: String] = [:] + var index = 0 + while index < arguments.count { + guard arguments[index].hasPrefix("--"), index + 1 < arguments.count else { + throw Failure("qwen-decode: expected --name value pairs") + } + options[String(arguments[index].dropFirst(2))] = arguments[index + 1] + index += 2 + } + guard let directory = options["model-dir"], directory.hasPrefix("/") else { + throw Failure("qwen-decode needs --model-dir /DIR") + } + guard let backend = QwenTensorParallelGroup.Backend(rawValue: options["backend"] ?? "ring"), backend != .jaccl else { + throw Failure("qwen-decode runs on the loopback ring or socket only") + } + let reduction = options["reduction"] ?? "sealed-bench" + guard ["native", "sealed-bench"].contains(reduction) else { throw Failure("--reduction takes native or sealed-bench") } + let controls = (options["control"] ?? "exchanged,folded").split(separator: ",").map(String.init) + guard let width = Int(options["width"] ?? "1"), (1...8).contains(width), + let prompt = Int(options["prompt-tokens"] ?? "32"), prompt > 0, + let output = Int(options["output-tokens"] ?? "64"), output > 1, + let repeats = Int(options["repeats"] ?? "3"), repeats > 0, + let delay = Int(options["answer-delay-us"] ?? "0"), delay >= 0, + let sampled = Int(options["sampled"] ?? "0"), [0, 1].contains(sampled), + !controls.isEmpty, controls.allSatisfy({ ["exchanged", "folded"].contains($0) }) else { + throw Failure("--width 1-8, positive --prompt-tokens, --output-tokens > 1, --repeats, --answer-delay-us >= 0," + + " --sampled 0|1, --control exchanged,folded") + } + let url = URL(fileURLWithPath: directory) + let configuration = try Data(contentsOf: url.appendingPathComponent("config.json")) + let group = try QwenTensorParallelGroup(backend: backend) + let work = "\(reduction)|\(width)|\(prompt)|\(output)|\(sampled)|\(controls)|\(repeats)|\(delay)" + guard try group.digestsEqual(fnv(sha256Hex(configuration) + "|" + work)) else { + throw Failure("the ranks disagree on the checkpoint or the runs") + } + if reduction == "sealed-bench" { + let codec = try QwenTensorParallelSealCodec.bench(group: group, + scope: Data(("darkbloom-tp-qwen-decode-v1|" + sha256Hex(configuration)).utf8)) + try codec.install() + group.sealed = codec + } + note("rank \(group.rank) of \(group.size) over \(backend.rawValue), \(reduction) sums") + let same = try Device.withDefaultDevice(.gpu) { () throws -> Bool in + let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2), + reduction: group) + return try QwenTensorParallelDecodeBench.pair(model: model, configuration: configuration, group: group, + width: width, promptTokens: prompt, outputTokens: output, sampled: sampled == 1, + folds: controls.map { $0 == "folded" }, repeats: repeats, answerDelayMicroseconds: delay) { line in + FileHandle.standardOutput.write(Data((line + "\n").utf8)) + } + } + let both = try group.exchangeIntegers([same ? 1 : 0]) == [2] + note("both ranks retired the same tokens in every run: \(both)") + guard both else { throw Failure("folded control changed a retired token") } + } +} diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenPrefillBench.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenPrefillBench.swift index 75b6229735..2daf626642 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenPrefillBench.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenPrefillBench.swift @@ -3,7 +3,7 @@ import Foundation import MLX // darkbloom-cluster-tp-check qwen-prefill --model-dir /ABS [--rank R] [--shares A:B] [--prompt-tokens N] -// [--chunks 512,1024] [--ops 0,16,100] [--strides 0,1] [--modes local,cpu-hop] [--repeats N] +// [--chunks 512,1024] [--ops 0,16,100] [--strides 0,1] [--wavefronts 1,8] [--modes local,cpu-hop] [--repeats N] // [--layers yes|no] [--gemm yes|no] [--gemm-rows 512,1024] // One Qwen tensor-parallel rank's prompt prefill on this Mac with no peer // (QwenTensorParallelPrefillBench): the product's request-owned prefill @@ -20,7 +20,7 @@ enum QwenPrefillBench { fields[arguments[index]] = arguments[index + 1]; index += 2 } guard let directory = fields["--model-dir"], directory.hasPrefix("/") else { - throw Failure("usage: qwen-prefill --model-dir /ABS [--rank R] [--shares A:B] [--prompt-tokens N] [--chunks 512,1024] [--ops 0,16,100] [--strides 0,1] [--modes local,cpu-hop] [--repeats N] [--layers yes|no] [--gemm yes|no] [--gemm-rows 512]") + throw Failure("usage: qwen-prefill --model-dir /ABS [--rank R] [--shares A:B] [--prompt-tokens N] [--chunks 512,1024] [--ops 0,16,100] [--strides 0,1] [--wavefronts 1,8] [--modes local,cpu-hop] [--repeats N] [--layers yes|no] [--gemm yes|no] [--gemm-rows 512]") } func list(_ name: String, _ fallback: [Int]) throws -> [Int] { guard let text = fields[name] else { return fallback } @@ -39,6 +39,7 @@ enum QwenPrefillBench { options.chunks = try list("--chunks", [512]) options.operations = try list("--ops", [0]) options.strides = try list("--strides", [0]) + options.wavefronts = try list("--wavefronts", [1]) options.modes = try (fields["--modes"] ?? "local").split(separator: ",").map { guard let mode = QwenTensorParallelPrefillBench.Mode(rawValue: String($0)) else { throw Failure("--modes takes local,cpu-hop") } return mode diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift new file mode 100644 index 0000000000..61bfb2a0ce --- /dev/null +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenRowsCheck.swift @@ -0,0 +1,93 @@ +import DarkbloomClusterRuntime +import Foundation +import MLX + +// Qwen3.8-27B rows at the registered per-rank widths on two ranks of one Mac +// (`QwenTensorParallelRowsCheck`): random weights or a registered checkpoint's +// files read directly, never a model pass. +// darkbloom-cluster-tp-check qwen-rows synthesize --output /DIR [--layers 4] +// MLX_RANK=0|1 MLX_HOSTFILE=hosts.json darkbloom-cluster-tp-check qwen-rows run --model-dir /DIR \ +// --report FILE [--backend ring|socket] [--reduction native|sealed-bench] +// Each rank compares its own digests (a row alone, in cohorts, across KV +// segments, observed, in verify windows) and both agree on the verdict. +// `layers` (same options, [--target 7 --other 6]) reports the first decoder +// layer where a row's step beside another leaves its solo bits. +enum QwenRowsCheck { + static func run(_ arguments: [String]) throws { + guard let command = arguments.first, ["synthesize", "run", "layers"].contains(command) else { + throw Failure("usage: darkbloom-cluster-tp-check qwen-rows synthesize|run|layers ...") + } + var options: [String: String] = [:] + var index = 1 + while index < arguments.count { + guard arguments[index].hasPrefix("--"), index + 1 < arguments.count else { + throw Failure("qwen-rows: expected --name value pairs") + } + options[String(arguments[index].dropFirst(2))] = arguments[index + 1] + index += 2 + } + if command == "synthesize" { + guard let output = options["output"], output.hasPrefix("/") else { throw Failure("synthesize needs --output /DIR") } + // Layer 4 is the first attention layer; the rows check needs one. + guard let layers = Int(options["layers"] ?? "4"), (4...8).contains(layers) else { + throw Failure("--layers takes 4 to 8") + } + try Device.withDefaultDevice(.gpu) { + try QwenTensorParallelRowsCheck.writeCheckpoint(directory: URL(fileURLWithPath: output), layers: layers) + } + note("real-geometry checkpoint written (\(layers) layers)") + return + } + guard let directory = options["model-dir"], let reportPath = options["report"] else { + throw Failure("\(command) needs --model-dir and --report") + } + guard let target = Int(options["target"] ?? "7"), let other = Int(options["other"] ?? "6") else { + throw Failure("--target and --other take row numbers") + } + guard let backend = QwenTensorParallelGroup.Backend(rawValue: options["backend"] ?? "ring"), backend != .jaccl else { + throw Failure("qwen-rows runs on the loopback ring or socket only") + } + let reduction = options["reduction"] ?? "native" + guard ["native", "sealed-bench"].contains(reduction) else { throw Failure("--reduction takes native or sealed-bench") } + let url = URL(fileURLWithPath: directory) + let configuration = try Data(contentsOf: url.appendingPathComponent("config.json")) + let group = try QwenTensorParallelGroup(backend: backend) + // Ranks running other commands or rows would pair different collectives. + let work = command == "layers" ? "layers \(target) \(other)" : command + guard try group.digestsEqual(fnv(sha256Hex(configuration) + "|" + reduction + "|" + work)) else { + throw Failure("the ranks disagree on the checkpoint, the reduction or the command") + } + if reduction == "sealed-bench" { + let codec = try QwenTensorParallelSealCodec.bench(group: group, + scope: Data(("darkbloom-tp-qwen-rows-v1|" + sha256Hex(configuration)).utf8)) + try codec.install() + group.sealed = codec + } + note("rank \(group.rank) of \(group.size) over \(backend.rawValue), \(reduction) sums") + if command == "layers" { + let lines = try Device.withDefaultDevice(.gpu) { () throws -> [String] in + let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2), + reduction: group) + return try QwenTensorParallelRowsCheck.firstDifferingLayers(model: model, configuration: configuration, + target: target, other: other) + } + try lines.joined(separator: "\n").write(toFile: reportPath, atomically: true, encoding: .utf8) + lines.forEach { note($0) } + return + } + let report = try Device.withDefaultDevice(.gpu) { () throws -> QwenTensorParallelRowsCheck.Report in + let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2), + reduction: group) + return try QwenTensorParallelRowsCheck.run(model: model, configuration: configuration, rank: group.rank) + } + let bothPassed = try group.exchangeIntegers([report.passed ? 1 : 0]) == [2] + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .prettyPrinted] + guard FileManager.default.createFile(atPath: reportPath, contents: try encoder.encode(report)) else { + throw Failure("could not write the report") + } + note("compared \(report.compared) digests, \(report.differing.count) differ\(report.differing.isEmpty ? "" : ": \(report.differing.prefix(8))");" + + " both ranks passed: \(bothPassed)") + guard bothPassed else { throw Failure("a rank found a row that differs from itself alone") } + } +} diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift new file mode 100644 index 0000000000..e5c5eecab0 --- /dev/null +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenWavefrontCheck.swift @@ -0,0 +1,65 @@ +import DarkbloomClusterRuntime +import Foundation +import MLX + +// A Qwen tensor-parallel prompt on two ranks of one Mac, one frame a step and +// in merged wavefront steps (`QwenTensorParallelPrefillBench.pair`): +// MLX_RANK=0|1 MLX_HOSTFILE=hosts.json darkbloom-cluster-tp-check qwen-wavefront --model-dir /DIR \ +// [--backend ring|socket] [--reduction native|sealed-bench] [--prompt-tokens 4096] [--chunk 512] \ +// [--output-tokens 8] [--wavefronts 1,2,8] [--repeats 1] +// Each rank logs every run's step times, peak memory and digests; both agree +// that every run left the same bytes. Loopback timings show the overlap, never +// a pair's. `--output-tokens` sets the request's context past the prompt. +enum QwenWavefrontCheck { + static func run(_ arguments: [String]) throws { + var options: [String: String] = [:] + var index = 0 + while index < arguments.count { + guard arguments[index].hasPrefix("--"), index + 1 < arguments.count else { + throw Failure("qwen-wavefront: expected --name value pairs") + } + options[String(arguments[index].dropFirst(2))] = arguments[index + 1] + index += 2 + } + guard let directory = options["model-dir"], directory.hasPrefix("/") else { + throw Failure("qwen-wavefront needs --model-dir /DIR") + } + guard let backend = QwenTensorParallelGroup.Backend(rawValue: options["backend"] ?? "ring"), backend != .jaccl else { + throw Failure("qwen-wavefront runs on the loopback ring or socket only") + } + let reduction = options["reduction"] ?? "sealed-bench" + guard ["native", "sealed-bench"].contains(reduction) else { throw Failure("--reduction takes native or sealed-bench") } + let wavefronts = (options["wavefronts"] ?? "1,2,8").split(separator: ",").compactMap { Int($0) } + guard let prompt = Int(options["prompt-tokens"] ?? "4096"), prompt > 0, + let chunk = Int(options["chunk"] ?? "512"), chunk > 0, let repeats = Int(options["repeats"] ?? "1"), + let output = Int(options["output-tokens"] ?? "8"), output > 0, + !wavefronts.isEmpty, wavefronts.allSatisfy({ (1...8).contains($0) }) else { + throw Failure("--prompt-tokens, --chunk, --output-tokens and --repeats take positive integers, --wavefronts 1 to 8") + } + let url = URL(fileURLWithPath: directory) + let configuration = try Data(contentsOf: url.appendingPathComponent("config.json")) + let group = try QwenTensorParallelGroup(backend: backend) + let work = "\(reduction)|\(prompt)|\(chunk)|\(output)|\(wavefronts)|\(repeats)" + guard try group.digestsEqual(fnv(sha256Hex(configuration) + "|" + work)) else { + throw Failure("the ranks disagree on the checkpoint or the runs") + } + if reduction == "sealed-bench" { + let codec = try QwenTensorParallelSealCodec.bench(group: group, + scope: Data(("darkbloom-tp-qwen-wavefront-v1|" + sha256Hex(configuration)).utf8)) + try codec.install() + group.sealed = codec + } + note("rank \(group.rank) of \(group.size) over \(backend.rawValue), \(reduction) sums") + let same = try Device.withDefaultDevice(.gpu) { () throws -> Bool in + let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2), + reduction: group) + return try QwenTensorParallelPrefillBench.pair(model: model, configuration: configuration, + promptTokens: prompt, chunk: chunk, outputTokens: output, wavefronts: wavefronts, repeats: repeats) { line in + FileHandle.standardOutput.write(Data((line + "\n").utf8)) + } + } + let both = try group.exchangeIntegers([same ? 1 : 0]) == [2] + note("both ranks left the same bytes in every run: \(both)") + guard both else { throw Failure("a merged prompt left other bytes than one frame a step") } + } +} diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift index 23c7fad6aa..0a5fa7a160 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/TensorParallelCheck.swift @@ -22,6 +22,16 @@ import MLX // tensor parallel against one rank without a registered model; never a model pass) // darkbloom-cluster-tp-check record --rank0 FILE --rank1 FILE --reference FILE [--reference FILE] --model-dir DIR // --output FILE [--partials float32|bfloat16] [--near-tie-ulps U] (appends one qualification record line) +// darkbloom-cluster-tp-check glm ... (GLM-5.3-Flash, GLMBench.swift) +// darkbloom-cluster-tp-check gemma ... (Gemma 4 MoE oracles, GemmaCheck.swift) +// darkbloom-cluster-tp-check mimo ... (MiMo V2.6 oracles, MiMoCheck.swift) +// darkbloom-cluster-tp-check qwen-rows synthesize|run|layers ... (27B batch rows at the registered per-rank +// widths: each row against itself alone and in verify windows over the loopback ring, or the first layer +// that differs; `QwenRowsCheck`) +// darkbloom-cluster-tp-check qwen-wavefront --model-dir /DIR ... (a prompt one frame a step and in merged +// wavefront steps over the loopback ring: step times and digests; `QwenWavefrontCheck`) +// darkbloom-cluster-tp-check qwen-decode --model-dir /DIR ... (the batch driver's decode over the loopback +// ring, control exchanged a step or folded into the selection sum: step times and tokens; `QwenDecodeCheck`) // // `full` is the unsharded model on one Mac (this code path's single-Mac // reference); `simulated` is the single-process tensor-parallel oracle (the @@ -521,6 +531,26 @@ enum CompareCommand { try QwenPrefillBench.run(Array(CommandLine.arguments.dropFirst(2))) return } + if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "gemma" { + try GemmaCheck.run(Array(CommandLine.arguments.dropFirst(2))) + return + } + if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "mimo" { + try MiMoCheck.run(Array(CommandLine.arguments.dropFirst(2))) + return + } + if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "qwen-rows" { + try QwenRowsCheck.run(Array(CommandLine.arguments.dropFirst(2))) + return + } + if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "qwen-wavefront" { + try QwenWavefrontCheck.run(Array(CommandLine.arguments.dropFirst(2))) + return + } + if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "qwen-decode" { + try QwenDecodeCheck.run(Array(CommandLine.arguments.dropFirst(2))) + return + } let options = try Options(Array(CommandLine.arguments.dropFirst())) let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .prettyPrinted] diff --git a/libs/darkbloom-cluster-worker/Tests/CapabilityChecks/CapabilityCommandCheck.swift b/libs/darkbloom-cluster-worker/Tests/CapabilityChecks/CapabilityCommandCheck.swift index 8d1b519ac0..ab48d33101 100644 --- a/libs/darkbloom-cluster-worker/Tests/CapabilityChecks/CapabilityCommandCheck.swift +++ b/libs/darkbloom-cluster-worker/Tests/CapabilityChecks/CapabilityCommandCheck.swift @@ -140,16 +140,17 @@ import Foundation "The Nemotron capability does not round-trip within the byte bound") } // A second adapter, through the one catalog the worker's command asks: MiMo's own - // row, its own session bound, the pipeline modes, the speculative rounds and the phase split - // (a hand-off mode the planner considers only behind the explicit opt-in), serial and - // lookahead prefill. Only metadata executes, even though MLX is linked. + // row, its own session bound, the pipeline modes, the speculative rounds, the phase split + // (a hand-off mode the planner considers only behind the explicit opt-in) and tensor parallel + // (text only), serial and lookahead prefill. Only metadata executes, even though MLX is linked. try checks.yes("registered-mimo-is-described-from-its-own-row") { let mimoConfiguration = try Data(contentsOf: fixtures.appendingPathComponent("registered-mimo-v26-flash-mopd.configuration.json")) let mimoManifest = try Data(contentsOf: fixtures.appendingPathComponent("registered-mimo-v26-flash-mopd.manifest.json")) let mimo = try ClusterResidentModelCatalog.describe(configuration: mimoConfiguration, manifest: mimoManifest, runtimeBinarySHA256: binary) try capabilityCheck(mimo.adapterID == "mimo-v26-layer-stage" && mimo.runtimeModelID == "registered_mimo_v26_flash_mopd" - && mimo.supportedGenerationModes == [.pipeline, .pipelineCompactDecode, .phaseSplit, .pipelineMTP] + && mimo.supportedGenerationModes == [.pipeline, .pipelineCompactDecode, .phaseSplit, .tensorParallel, + .pipelineMTP] && mimo.supportedPrefillSchedules == [.serial, .oneChunkLookahead] && mimo.partitions.map { $0.stages[0].sourceLayerEnd } == Array(1...47) && mimo.partitions.allSatisfy { $0.stages.count == 2 && $0.stages[1].sourceLayerEnd == 48 }, @@ -182,7 +183,7 @@ import Foundation && value.runtimeModelID == model && value.profile.id == model + "_greedy_generation_v1" && value.profile.vocabularySize == 262_144 && value.profile.maximumPromptTokens == 32_768 && value.arithmeticPolicyID == "gemma4_cbv2_query128_bf16_tf32_weighted_r1_v1" - && value.supportedGenerationModes == [.pipeline] + && value.supportedGenerationModes == [.pipeline, .tensorParallel] && value.supportedPrefillSchedules == [.serial, .oneChunkLookahead] && value.partitions.map { $0.stages[0].sourceLayerEnd } == Array(1...29) && value.partitions.allSatisfy { $0.stages[1].sourceLayerEnd == 30 }, diff --git a/libs/darkbloom-cluster-worker/Tests/DarkbloomClusterWorkerTests/MiMoImageStartupBindingTests.swift b/libs/darkbloom-cluster-worker/Tests/DarkbloomClusterWorkerTests/MiMoImageStartupBindingTests.swift index c3b95fc543..66538c6b66 100644 --- a/libs/darkbloom-cluster-worker/Tests/DarkbloomClusterWorkerTests/MiMoImageStartupBindingTests.swift +++ b/libs/darkbloom-cluster-worker/Tests/DarkbloomClusterWorkerTests/MiMoImageStartupBindingTests.swift @@ -32,6 +32,23 @@ final class MiMoImageStartupBindingTests:XCTestCase { .flatMap { [args[$0],args[$0+1]] } XCTAssertNil(try WorkerConfiguration(arguments:text,now:100).load.runtimeProfile) } + /// MiMo's text row in tensor parallel takes a speculative depth (rounds on replicated heads) only keyed and text-only. + func testTensorParallelTakesASpeculativeDepthKeyedAndTextOnly() throws { + let args = try arguments() + let text = stride(from:0,to:args.count,by:2).filter { !["--runtime-profile","--qualification-switches"].contains(args[$0]) } + .flatMap { [args[$0],args[$0+1]] } + let tp = ["--generation-mode",ClusterGenerationMode.tensorParallel.rawValue] + XCTAssertNil(try WorkerConfiguration(arguments:text+tp,now:100).speculativeTerms) + for depth in 1...3 { + let value = try WorkerConfiguration(arguments:text+tp+["--mtp-depth",String(depth)],now:100) + XCTAssertEqual(value.generationMode,.tensorParallel); XCTAssertEqual(value.speculativeTerms?.depth,depth) + } + let unkeyed = stride(from:0,to:text.count,by:2).filter { text[$0] != "--data-plane" }.flatMap { [text[$0],text[$0+1]] } + XCTAssertThrowsError(try WorkerConfiguration(arguments:unkeyed+tp+["--mtp-depth","2"],now:100)) + XCTAssertThrowsError(try WorkerConfiguration(arguments:args+tp+["--mtp-depth","2"],now:100)) + XCTAssertThrowsError(try WorkerConfiguration(arguments:text+["--generation-mode",ClusterGenerationMode.pipeline.rawValue, + "--mtp-depth","2"],now:100)) + } func testCrossedModelProfileUnqualifiedOrUnencryptedLaunchRefuses() throws { let args = try arguments() for name in ["--runtime-profile","--model-id","--artifact-sha256","--configuration-sha256"] { diff --git a/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh b/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh new file mode 100755 index 0000000000..3ed6ab673a --- /dev/null +++ b/libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh @@ -0,0 +1,128 @@ +#!/bin/bash +# Gemma 4 tensor-parallel oracles on synthetic checkpoints, one Mac, loopback +# only (correctness, never a timing or a pair qualification): +# bash libs/darkbloom-cluster-worker/Tests/GemmaTensorParallelOracles/run.sh TP_CHECK SCRATCH_DIR [PORT] [PATH] +# TP_CHECK is a built darkbloom-cluster-tp-check with a source-matched +# mlx.metallib beside it; SCRATCH_DIR a new directory; PORT the first of two +# free 127.0.0.1 ports for the local ring (default 58123); PATH `legacy` (the +# SDK's legacy caches, the default) or `paged` (the resident runtime's own +# request path: paged KV with each rank's own heads, the product's CBv2 +# prompt entry, each step's token and stop flags agreed in its evaluation). +# +# For each synthetic variant: `full`, `split-sum` (legacy only), `simulated` +# (both ranks in one process), then two `tp` ranks over the sealed local ring. +# Required: each tp rank bitwise equal to `simulated`. Reported: the +# comparator's verdict of each rank against `full`, and `split-sum` against tp. +# The paged path also serves three requests as batch lanes (`gemma lanes`, +# simulated and over the ring). Required: every lane takes its solo tokens. +# And it serves the request twice through each rank's prompt-prefix tier +# (`--prefix repeat`). Required: the repeat restored a prefix, equals its cold +# run bit for bit, and each tp rank's repeat equals simulated's bit for bit. +set -euo pipefail +tp_check="$1" +scratch="$2" +port="${3:-58123}" +path="${4:-legacy}" +if [[ ! -x "$tp_check" || -e "$scratch" || ( "$path" != legacy && "$path" != paged ) ]]; then + echo 'usage: run.sh TP_CHECK NEW_SCRATCH_DIR [PORT] [legacy|paged]' >&2 + exit 2 +fi +mkdir -p "$scratch" +printf '[["127.0.0.1:%d"],["127.0.0.1:%d"]]' "$port" "$((port + 1))" > "$scratch/hosts.json" +failures=0 +run_variant() { + local name="$1"; shift + local environment="$1"; shift + local dir="$scratch/$name" + local modes=(full split-sum simulated) + [[ "$path" == paged ]] && modes=(full simulated) + nice -n 19 "$tp_check" gemma synthesize --output "$dir" "$@" >/dev/null 2>&1 + for mode in "${modes[@]}"; do + env $environment nice -n 19 "$tp_check" gemma run --mode "$mode" --path "$path" --model-dir "$dir" \ + --request "$dir/request.json" --report "$dir/$mode.json" >"$dir/$mode.log" 2>&1 + done + env $environment MLX_RANK=0 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma run --mode tp \ + --path "$path" --backend ring --reduction sealed-bench --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/tp-rank0.json" --deadline-seconds 300 >"$dir/tp-rank0.log" 2>&1 & + local rank0=$! + env $environment MLX_RANK=1 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma run --mode tp \ + --path "$path" --backend ring --reduction sealed-bench --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/tp-rank1.json" --deadline-seconds 300 >"$dir/tp-rank1.log" 2>&1 + wait "$rank0" + for rank in 0 1; do + if "$tp_check" gemma compare --reference "$dir/simulated.json" --candidate "$dir/tp-rank$rank.json" \ + --bitwise yes >"$dir/tp-rank$rank-vs-simulated.txt" 2>&1; then + echo "$name ($path): tp rank $rank == simulated, bitwise" + else + echo "$name ($path): tp rank $rank DIFFERS from simulated"; failures=$((failures + 1)) + fi + "$tp_check" gemma compare --reference "$dir/full.json" --candidate "$dir/tp-rank$rank.json" \ + >"$dir/tp-rank$rank-vs-full.txt" 2>&1 || true + echo "$name ($path): tp rank $rank against full: $(grep '^verdict ' "$dir/tp-rank$rank-vs-full.txt")" + done + if [[ "$path" == legacy ]]; then + "$tp_check" gemma compare --reference "$dir/split-sum.json" --candidate "$dir/tp-rank0.json" --bitwise yes \ + >"$dir/split-sum-vs-tp.txt" 2>&1 || true + echo "$name ($path): split-sum against tp: $(grep -E '^bitwise' "$dir/split-sum-vs-tp.txt")" + return + fi + # A repeated prompt through each rank's prefix tier: the repeat restores the + # deepest boundary both ranks hold and must equal its cold run bit for bit + # (in each report), and each tp rank's repeat must equal simulated's. + env $environment nice -n 19 "$tp_check" gemma run --mode simulated --path paged --prefix repeat --model-dir "$dir" \ + --request "$dir/request.json" --report "$dir/prefix-simulated.json" >"$dir/prefix-simulated.log" 2>&1 || true + env $environment MLX_RANK=0 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma run --mode tp \ + --path paged --prefix repeat --backend ring --reduction sealed-bench --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/prefix-tp-rank0.json" --deadline-seconds 300 >"$dir/prefix-tp-rank0.log" 2>&1 & + rank0=$! + env $environment MLX_RANK=1 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma run --mode tp \ + --path paged --prefix repeat --backend ring --reduction sealed-bench --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/prefix-tp-rank1.json" --deadline-seconds 300 >"$dir/prefix-tp-rank1.log" 2>&1 || true + wait "$rank0" || true + for rank in 0 1; do + if "$tp_check" gemma compare --reference "$dir/prefix-simulated.json" --candidate "$dir/prefix-tp-rank$rank.json" \ + --bitwise yes >"$dir/prefix-tp-rank$rank-vs-simulated.txt" 2>&1 \ + && /usr/bin/python3 - "$dir" "$rank" <<'PY' +import json, sys +d, rank = sys.argv[1], sys.argv[2] +reports = [json.load(open(f"{d}/{name}.json")) for name in ("prefix-simulated", f"prefix-tp-rank{rank}")] +sys.exit(0 if all(r["passed"] and r["restoredEqualsCold"] and r["reusedPromptTokens"] > 0 for r in reports) else 1) +PY + then + echo "$name ($path): repeated prefix restored $(/usr/bin/python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["reusedPromptTokens"])' "$dir/prefix-tp-rank$rank.json") tokens; tp rank $rank == simulated and == cold, bitwise" + else + echo "$name ($path): repeated prefix on tp rank $rank DIFFERS"; failures=$((failures + 1)) + fi + done + # Batch lanes: three requests through the batch driver, each against itself alone. + env $environment nice -n 19 "$tp_check" gemma lanes --mode simulated --model-dir "$dir" \ + --report "$dir/lanes-simulated.json" >"$dir/lanes-simulated.log" 2>&1 || true + env $environment MLX_RANK=0 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma lanes --mode tp \ + --backend ring --reduction sealed-bench --model-dir "$dir" --report "$dir/lanes-tp-rank0.json" \ + --deadline-seconds 300 >"$dir/lanes-tp-rank0.log" 2>&1 & + rank0=$! + env $environment MLX_RANK=1 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" gemma lanes --mode tp \ + --backend ring --reduction sealed-bench --model-dir "$dir" --report "$dir/lanes-tp-rank1.json" \ + --deadline-seconds 300 >"$dir/lanes-tp-rank1.log" 2>&1 || true + wait "$rank0" || true + if /usr/bin/python3 - "$dir" <<'PY' +import json, sys +d = sys.argv[1] +reports = [json.load(open(f"{d}/{name}.json")) for name in ("lanes-simulated", "lanes-tp-rank0", "lanes-tp-rank1")] +ok = all(r["passed"] and r["lanesEqualSolo"] for r in reports) +ok = ok and reports[1]["laneTokens"] == reports[0]["laneTokens"] == reports[2]["laneTokens"] +sys.exit(0 if ok else 1) +PY + then + echo "$name ($path): lanes == solo on both tp ranks and simulated, tokens equal" + else + echo "$name ($path): lanes DIFFER"; failures=$((failures + 1)) + fi +} +run_variant w4-routed "" --bits 4 +run_variant w8-routed "" --bits 8 +run_variant w4-all-experts "" --bits 4 --experts 4 --top-k 4 +run_variant w8-all-experts "" --bits 8 --experts 4 --top-k 4 +run_variant w4-routed-fp32 "MLX_ENABLE_TF32=0" --bits 4 --dtype float32 +echo "required tp == simulated failures ($path): $failures" +exit $(( failures == 0 ? 0 : 1 )) diff --git a/libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh b/libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh new file mode 100755 index 0000000000..02a7c8f7c0 --- /dev/null +++ b/libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh @@ -0,0 +1,304 @@ +#!/bin/bash +# MiMo V2.6 tensor-parallel oracles on synthetic checkpoints, one Mac, loopback +# only (correctness, never a timing or a pair qualification): +# bash libs/darkbloom-cluster-worker/Tests/MiMoTensorParallelOracles/run.sh TP_CHECK SCRATCH_DIR [PORT] +# TP_CHECK is a built darkbloom-cluster-tp-check with a source-matched +# mlx.metallib beside it; SCRATCH_DIR a new directory; PORT the first of two +# free 127.0.0.1 ports for the local ring and socket (default 58223). +# MIMO_ORACLE_PATHS (default "contiguous paged mtp") picks the matrices to run. +# +# For each synthetic variant and each request (40 prompt tokens: longer than +# the 8-token window and the 16-token chunk; 6 tokens: shorter than both; 64 +# outputs each): `full`, `simulated` (both ranks in one process), then two `tp` +# ranks over the sealed local ring. Required: each tp rank bitwise equal to +# `simulated` (tokens, top-8 logits and log probabilities, every step's whole +# row, the final row, the rank's KV caches), and each tp rank's tokens in +# agreement with `full` under QualificationComparator (exact, +# tokensEqualLogitsDiffer or divergedAtNearTie). Then once on the socket +# backend, and once sampled (temperature 0.8 through the gathered row): tp +# bitwise equal to simulated; the sampled run's verdict against `full` is +# reported only (a sampled token after a near tie is not a greedy divergence). +# +# `contiguous` is the foundation's path (the checkpoint read whole and cut, +# ordinary caches). `paged` is the resident runtime's (`--path paged`): the +# verified load (manifest first, then only this rank's byte runs), paged KV, +# the per-step agreement sum, 100-op decode buffers, greedy logprobs through +# the split top-k gather, sampling with the product's sampler over the +# gathered row. The paged matrix also requires paged `full` and `simulated` +# bitwise equal to contiguous ones, each tp rank to have read exactly its +# shard's bytes, and two refusals: ranks told different agreements, and a +# checkpoint byte changed after its manifest. A 192-token prompt (three +# 64-token pages before decode) runs on both paths and over the ring. Route +# sets are recorded to report where `simulated` first routes a token to other +# experts than `full` (informational; recording must change nothing). +# +# `mtp` runs speculative rounds (`--mtp-depth`) on checkpoints with three +# random trained heads (`--mtp yes`; the text weights equal the plain +# variant's). Required, on the paged path: every round run bitwise equal to +# the one-token path (tokens, rows, caches: lossless greedy), with the heads' +# own proposals (random, so mostly rejected), with proposals scripted from the +# one-token tokens (forced acceptance: every draft kept) and with every fifth +# scripted proposal moved off (accepts, rejects and rollback); sampled rounds +# (temperature 0.8: the heads, and the misses scripted from the sampled +# one-token run) bitwise equal to the sampled one-token path; and each tp rank +# bitwise equal to `simulated` for the heads, the misses and a sampled run. +set -euo pipefail +tp_check="$1" +scratch="$2" +port="${3:-58223}" +paths="${MIMO_ORACLE_PATHS:-contiguous paged mtp}" +if [[ ! -x "$tp_check" || -e "$scratch" ]]; then + echo 'usage: run.sh TP_CHECK NEW_SCRATCH_DIR [PORT]' >&2 + exit 2 +fi +mkdir -p "$scratch" +printf '[["127.0.0.1:%d"],["127.0.0.1:%d"]]' "$port" "$((port + 1))" > "$scratch/hosts.json" +failures=0 +# Each tp rank's exit status, for the refusal checks. +rank0_status=0 +rank1_status=0 +tp_pair() { + local dir="$1" request="$2" tag="$3" backend="$4" environment="$5"; shift 5 + local rank0_extra=() + if [[ "${RANK0_EXTRA:-}" != "" ]]; then read -r -a rank0_extra <<<"$RANK0_EXTRA"; fi + env $environment MLX_RANK=0 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" mimo run --mode tp \ + --backend "$backend" --reduction sealed-bench --model-dir "$dir" --request "$dir/$request.json" \ + --report "$dir/$tag-rank0.json" --deadline-seconds 300 "$@" ${rank0_extra[@]+"${rank0_extra[@]}"} \ + >"$dir/$tag-rank0.log" 2>&1 & + local rank0=$! + rank1_status=0 + env $environment MLX_RANK=1 MLX_HOSTFILE="$scratch/hosts.json" nice -n 19 "$tp_check" mimo run --mode tp \ + --backend "$backend" --reduction sealed-bench --model-dir "$dir" --request "$dir/$request.json" \ + --report "$dir/$tag-rank1.json" --deadline-seconds 300 "$@" >"$dir/$tag-rank1.log" 2>&1 || rank1_status=$? + rank0_status=0 + wait "$rank0" || rank0_status=$? +} +check_rank() { + local dir="$1" reference="$2" tag="$3" label="$4" full_required="${5:-yes}" + for rank in 0 1; do + if "$tp_check" mimo compare --reference "$dir/$reference-simulated.json" --candidate "$dir/$tag-rank$rank.json" \ + --bitwise yes >"$dir/$tag-rank$rank-vs-simulated.txt" 2>&1; then + echo "$label: tp rank $rank == simulated, bitwise" + else + echo "$label: tp rank $rank DIFFERS from simulated"; failures=$((failures + 1)) + fi + if "$tp_check" mimo compare --reference "$dir/$reference-full.json" --candidate "$dir/$tag-rank$rank.json" \ + >"$dir/$tag-rank$rank-vs-full.txt" 2>&1 || [[ "$full_required" == no ]]; then + echo "$label: tp rank $rank against full: $(grep '^verdict ' "$dir/$tag-rank$rank-vs-full.txt")" + else + echo "$label: tp rank $rank against full FAILS: $(grep '^verdict ' "$dir/$tag-rank$rank-vs-full.txt" || true)" + failures=$((failures + 1)) + fi + done +} +# A paged tp rank read exactly the bytes its shard holds, and fewer than the whole text. +check_read_bytes() { + local report="$1" label="$2" + if python3 - "$report" <<'EOF' +import json, sys +r = json.load(open(sys.argv[1])) +ok = r.get("path") == "paged" and r["readBytes"] == r["loadedParameterBytes"] and r["readBytes"] < r["textBytes"] +print(f"read {r['readBytes']} of {r['textBytes']} text bytes, holds {r['loadedParameterBytes']}") +sys.exit(0 if ok else 1) +EOF + then echo "$label: read only its byte runs"; else echo "$label: READ MORE THAN ITS SHARD"; failures=$((failures + 1)); fi +} +synthesize() { + local dir="$1"; shift + [[ -d "$dir" ]] || nice -n 19 "$tp_check" mimo synthesize --output "$dir" "$@" >/dev/null 2>&1 +} +run_variant() { + local path="$1" name="$2" environment="$3"; shift 3 + local dir="$scratch/$name" prefix="" options=() + if [[ "$path" == paged ]]; then prefix="paged-"; options=(--path paged); fi + synthesize "$dir" "$@" + for request in request request-short; do + for mode in full simulated; do + env $environment nice -n 19 "$tp_check" mimo run --mode "$mode" --model-dir "$dir" \ + --request "$dir/$request.json" --report "$dir/$prefix$request-$mode.json" ${options[@]+"${options[@]}"} \ + >"$dir/$prefix$request-$mode.log" 2>&1 + done + tp_pair "$dir" "$request" "$prefix$request-tp-ring" ring "$environment" ${options[@]+"${options[@]}"} + check_rank "$dir" "$prefix$request" "$prefix$request-tp-ring" "$path $name/$request (ring)" + if [[ "$path" == paged ]]; then + for rank in 0 1; do check_read_bytes "$dir/$prefix$request-tp-ring-rank$rank.json" "paged $name/$request tp rank $rank"; done + fi + done +} +run_matrix() { + local path="$1" prefix="" options=() + if [[ "$path" == paged ]]; then prefix="paged-"; options=(--path paged); fi + run_variant "$path" kernel "" --variant kernel + run_variant "$path" tiny "" --variant tiny + # Every token takes all 8 experts: no rounding can flip a route. + run_variant "$path" kernel-all-experts "" --variant kernel --experts 8 --top-k 8 + # Paged histories hold BF16 only, as the product's do: FP32 runs the contiguous path alone. + if [[ "$path" == contiguous ]]; then + run_variant "$path" kernel-fp32 "MLX_ENABLE_TF32=0" --variant kernel --dtype float32 + fi + # The socket backend once, on the production-kernel shapes. + tp_pair "$scratch/kernel" request "${prefix}request-tp-socket" socket "" ${options[@]+"${options[@]}"} + check_rank "$scratch/kernel" "${prefix}request" "${prefix}request-tp-socket" "$path kernel/request (socket)" + # Sampled through the gathered row, on the production-kernel shapes. + local dir="$scratch/kernel" + for mode in full simulated; do + nice -n 19 "$tp_check" mimo run --mode "$mode" --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/${prefix}sampled-$mode.json" --temperature 0.8 --sample-seed 11 ${options[@]+"${options[@]}"} \ + >"$dir/${prefix}sampled-$mode.log" 2>&1 + done + tp_pair "$dir" request "${prefix}sampled-tp-ring" ring "" --temperature 0.8 --sample-seed 11 ${options[@]+"${options[@]}"} + check_rank "$dir" "${prefix}sampled" "${prefix}sampled-tp-ring" "$path kernel/request sampled (ring)" no +} +paged_extras() { + local dir="$scratch/kernel" + # The paged path is the contiguous path's arithmetic: same tokens, rows and cache digests. + if [[ "$paths" == *contiguous* ]]; then + for mode in full simulated; do + if "$tp_check" mimo compare --reference "$dir/request-$mode.json" --candidate "$dir/paged-request-$mode.json" \ + --bitwise yes >"$dir/paged-vs-contiguous-$mode.txt" 2>&1; then + echo "paged kernel/request $mode == contiguous $mode, bitwise" + else + echo "paged kernel/request $mode DIFFERS from contiguous"; failures=$((failures + 1)) + fi + done + fi + # Ranks told different agreements refuse before loading. + RANK0_EXTRA="--agreement-tamper yes" tp_pair "$dir" request paged-tamper-agreement ring "" --path paged + if [[ $rank0_status -ne 0 && $rank1_status -ne 0 ]] \ + && grep -q "disagree" "$dir/paged-tamper-agreement-rank0.log" "$dir/paged-tamper-agreement-rank1.log"; then + echo "paged: ranks with different agreements refused (exit $rank0_status / $rank1_status)" + else + echo "paged: MISMATCHED AGREEMENT WAS NOT REFUSED"; failures=$((failures + 1)) + fi + # A checkpoint byte changed after its manifest: the verified load refuses before any tensor is read. + local tampered="$scratch/kernel-tampered" + mkdir -p "$tampered" + for file in config.json manifest.json model.safetensors model.safetensors.index.json request.json; do + cp -c "$dir/$file" "$tampered/$file" + done + python3 - "$tampered/model.safetensors" <<'EOF' +import os, sys +path = sys.argv[1] +with open(path, "r+b") as f: + f.seek(os.path.getsize(path) // 2) + byte = f.read(1) + f.seek(-1, 1) + f.write(bytes([byte[0] ^ 0x01])) +EOF + if nice -n 19 "$tp_check" mimo run --mode full --path paged --model-dir "$tampered" --request "$tampered/request.json" \ + --report "$tampered/full.json" >"$tampered/full.log" 2>&1; then + echo "paged: A TAMPERED CHECKPOINT WAS LOADED"; failures=$((failures + 1)) + elif grep -q "SHA256 mismatch" "$tampered/full.log"; then + echo "paged: a tampered checkpoint was refused ($(grep -o 'Checkpoint SHA256 mismatch[^"]*' "$tampered/full.log" | head -1))" + else + echo "paged: tampered checkpoint failed for another reason"; failures=$((failures + 1)) + fi +} +# A 192-token prompt (three 64-token pages before decode) on the paged path: tp bitwise equal to +# simulated, each rank reading only its runs, and paged full and simulated bitwise equal to contiguous ones. +paged_long() { + local dir="$scratch/kernel" request=request-long + for mode in full simulated; do + nice -n 19 "$tp_check" mimo run --mode "$mode" --path paged --model-dir "$dir" --request "$dir/$request.json" \ + --report "$dir/paged-$request-$mode.json" >"$dir/paged-$request-$mode.log" 2>&1 + nice -n 19 "$tp_check" mimo run --mode "$mode" --model-dir "$dir" --request "$dir/$request.json" \ + --report "$dir/$request-$mode.json" >"$dir/$request-$mode.log" 2>&1 + if "$tp_check" mimo compare --reference "$dir/$request-$mode.json" --candidate "$dir/paged-$request-$mode.json" \ + --bitwise yes >"$dir/paged-vs-contiguous-$request-$mode.txt" 2>&1; then + echo "paged kernel/$request $mode == contiguous $mode, bitwise" + else + echo "paged kernel/$request $mode DIFFERS from contiguous"; failures=$((failures + 1)) + fi + done + tp_pair "$dir" "$request" "paged-$request-tp-ring" ring "" --path paged + check_rank "$dir" "paged-$request" "paged-$request-tp-ring" "paged kernel/$request (ring)" + for rank in 0 1; do check_read_bytes "$dir/paged-$request-tp-ring-rank$rank.json" "paged kernel/$request tp rank $rank"; done +} +# Route sets (informational): where `simulated` (bitwise `tp`) first routes a token to other experts +# than `full`. Required only that recording the routes changes nothing. +paged_routes() { + local name request dir + for name_request in kernel/request kernel/request-short tiny/request kernel-all-experts/request; do + name="${name_request%/*}" request="${name_request#*/}" dir="$scratch/$name" + for mode in full simulated; do + nice -n 19 "$tp_check" mimo run --mode "$mode" --path paged --record-routes yes --model-dir "$dir" \ + --request "$dir/$request.json" --report "$dir/routes-$request-$mode.json" >"$dir/routes-$request-$mode.log" 2>&1 + done + if "$tp_check" mimo compare --reference "$dir/paged-$request-simulated.json" \ + --candidate "$dir/routes-$request-simulated.json" --bitwise yes >/dev/null 2>&1; then + echo "paged $name/$request: recording routes changes nothing (bitwise)" + else + echo "paged $name/$request: RECORDING ROUTES CHANGED THE RUN"; failures=$((failures + 1)) + fi + "$tp_check" mimo compare --reference "$dir/routes-$request-full.json" \ + --candidate "$dir/routes-$request-simulated.json" >"$dir/routes-$request.txt" 2>&1 || true + echo "paged $name/$request: $(grep '^route sets:' "$dir/routes-$request.txt")" + done +} +# Required bitwise equality of two reports. +same_bits() { + local reference="$1" candidate="$2" label="$3" + if "$tp_check" mimo compare --reference "$reference" --candidate "$candidate" --bitwise yes \ + >"${candidate%.json}-vs-$(basename "${reference%.json}").txt" 2>&1; then + echo "$label: bitwise identical" + else + echo "$label: DIFFERS"; failures=$((failures + 1)) + fi +} +mtp_matrix() { + local name request dir rounds + for name in kernel tiny; do + dir="$scratch/$name-mtp" + synthesize "$dir" --variant "$name" --mtp yes + for request in request request-short request-long; do + [[ "$name" == tiny && "$request" == request-long ]] && continue + run() { local tag="$1"; shift + nice -n 19 "$tp_check" mimo run --mode simulated --path paged --model-dir "$dir" --request "$dir/$request.json" \ + --report "$dir/$request-$tag-simulated.json" "$@" >"$dir/$request-$tag-simulated.log" 2>&1; } + run plain + run heads --mtp-depth 2 + run script --mtp-depth 2 --mtp-script "$dir/$request-plain-simulated.json" + run misses --mtp-depth 3 --mtp-script "$dir/$request-plain-simulated.json" --mtp-misses 5 + for tag in heads script misses; do + rounds=$(grep -o 'speculative rounds.*' "$dir/$request-$tag-simulated.log" || echo 'no rounds') + same_bits "$dir/$request-plain-simulated.json" "$dir/$request-$tag-simulated.json" \ + "mtp $name/$request $tag ($rounds) == one-token path" + done + tp_pair "$dir" "$request" "$request-heads-tp-ring" ring "" --path paged --mtp-depth 2 + tp_pair "$dir" "$request" "$request-misses-tp-ring" ring "" --path paged --mtp-depth 3 \ + --mtp-script "$dir/$request-plain-simulated.json" --mtp-misses 5 + for rank in 0 1; do + same_bits "$dir/$request-heads-simulated.json" "$dir/$request-heads-tp-ring-rank$rank.json" \ + "mtp $name/$request heads tp rank $rank == simulated" + same_bits "$dir/$request-misses-simulated.json" "$dir/$request-misses-tp-ring-rank$rank.json" \ + "mtp $name/$request misses tp rank $rank == simulated" + done + done + done + # Sampled rounds (the product's keyed target sample per column over the gathered rows): every round run + # equals the sampled one-token path bit for bit, and tp == simulated. + dir="$scratch/kernel-mtp" + sampled() { local tag="$1"; shift + nice -n 19 "$tp_check" mimo run --mode simulated --path paged --model-dir "$dir" --request "$dir/request.json" \ + --report "$dir/sampled-$tag-simulated.json" --temperature 0.8 --sample-seed 11 "$@" \ + >"$dir/sampled-$tag-simulated.log" 2>&1; } + sampled plain + sampled heads --mtp-depth 2 + sampled misses --mtp-depth 3 --mtp-script "$dir/sampled-plain-simulated.json" --mtp-misses 5 + for tag in heads misses; do + same_bits "$dir/sampled-plain-simulated.json" "$dir/sampled-$tag-simulated.json" \ + "mtp kernel/request sampled $tag ($(grep -o 'speculative rounds.*' "$dir/sampled-$tag-simulated.log" || echo 'no rounds')) == one-token path" + done + tp_pair "$dir" request sampled-heads-tp-ring ring "" --path paged --temperature 0.8 --sample-seed 11 --mtp-depth 2 + for rank in 0 1; do + same_bits "$dir/sampled-heads-simulated.json" "$dir/sampled-heads-tp-ring-rank$rank.json" \ + "mtp kernel/request sampled tp rank $rank == simulated" + done +} +for path in $paths; do + if [[ "$path" == mtp ]]; then mtp_matrix; continue; fi + run_matrix "$path" + if [[ "$path" == paged ]]; then paged_extras; paged_long; paged_routes; fi +done +echo "required failures (tp == simulated bitwise, tp against full, paged extras, mtp rounds): $failures" +exit $(( failures == 0 ? 0 : 1 )) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterForcedMode.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterForcedMode.swift index b82c98a8df..1d6e503db2 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterForcedMode.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterForcedMode.swift @@ -42,10 +42,13 @@ public enum ClusterForcedMode: String, Codable, Sendable, CaseIterable { extension ClusterLinkCosts { /// These costs with the forced plan's assumed reduction in place of a missing or unkeyed one. - func assumingForcedReduction() -> ClusterLinkCosts { + func assumingForcedReduction() -> ClusterLinkCosts { assuming(ClusterForcedMode.assumedReduction) } + + /// These costs with `assumed` in place of a missing or unkeyed reduction. + func assuming(_ assumed: ClusterReductionCost) -> ClusterLinkCosts { guard reduction?.keyed != true else { return self } return .init(measured: measured, perChunkSeconds: perChunkSeconds, perDecodeStepSeconds: perDecodeStepSeconds, - handoffSecondsPerByte: handoffSecondsPerByte, provenance: provenance, reduction: ClusterForcedMode.assumedReduction, + handoffSecondsPerByte: handoffSecondsPerByte, provenance: provenance, reduction: assumed, recordFixedSeconds: recordFixedSeconds) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterModelLayout.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterModelLayout.swift index dacd2039dd..de985ead3c 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterModelLayout.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterModelLayout.swift @@ -389,6 +389,12 @@ public protocol ClusterPlacementFamily { /// How that plan treats a tensor some range loads; nil when the plan does /// not cover it (the layout is then refused: a plan covers every tensor). func tensorParallelCut(ofStoredTensor name: String) -> ClusterTensorParallelTensorCut? + /// Of a divided tensor's loaded bytes, those every rank of an equal split + /// holds beside its share (a quantization group both ranks store, rows of + /// zeros that pad a share to whole groups): the layout counts them + /// replicated and the rest divided, so a rank's share is its exact bytes. + /// 0, the default, divides every byte. + func tensorParallelOverlapBytes(of tensor: ClusterPlacementStoredTensor, loadedBytes: Int) -> Int /// Relative compute cost of a layer. 1 for every layer unless the family /// has measured its kinds apart. func layerCost(_ layer: Int) -> Double @@ -410,6 +416,7 @@ extension ClusterPlacementFamily { public var speculativeDecodeFactor: Double? { nil } public var tensorParallelPlan: ClusterTensorParallelFamilyPlan? { nil } public func tensorParallelCut(ofStoredTensor name: String) -> ClusterTensorParallelTensorCut? { nil } + public func tensorParallelOverlapBytes(of tensor: ClusterPlacementStoredTensor, loadedBytes: Int) -> Int { 0 } public var expertRouting: ClusterExpertRouting? { nil } public func isRoutedExpert(storedTensor name: String) -> Bool { false } public func layerCost(_ layer: Int) -> Double { 1 } @@ -451,13 +458,23 @@ public enum ClusterModelLayoutBuilder { } return cut } - func add(_ cut: ClusterTensorParallelTensorCut?, _ loaded: Int, to part: inout (divided: Int, replicated: Int)) { + func add(_ cut: ClusterTensorParallelTensorCut?, _ loaded: Int, overlap: Int = 0, + to part: inout (divided: Int, replicated: Int)) { switch cut { - case .divided: part.divided += loaded + case .divided: part.divided += loaded - overlap; part.replicated += overlap case .replicated: part.replicated += loaded case nil: break } } + // What every rank holds of a divided tensor beside its equal share (`tensorParallelOverlapBytes`). + func overlap(_ cut: ClusterTensorParallelTensorCut?, _ tensor: ClusterPlacementStoredTensor, _ loaded: Int) throws -> Int { + guard cut == .divided else { return 0 } + let bytes = family.tensorParallelOverlapBytes(of: tensor, loadedBytes: loaded) + guard (0...loaded).contains(bytes) else { + throw ClusterPlacementError("The family's tensor-parallel overlap of tensor \(tensor.name) is not within its bytes") + } + return bytes + } for tensor in tensors { guard tensor.byteCount > 0 else { throw ClusterPlacementError("Tensor \(tensor.name) has no bytes") } stored = try addingBytes(stored, tensor.byteCount) @@ -479,8 +496,8 @@ public enum ClusterModelLayoutBuilder { } ingress.add(stored: tensor.byteCount, loaded: loaded, work: work) egress.add(stored: 0, loaded: loaded, work: work) - let cut = try tensorParallelCut(tensor.name) - add(cut, loaded, to: &tpIngress); add(cut, loaded, to: &tpEgress) + let cut = try tensorParallelCut(tensor.name), shared = try overlap(cut, tensor, loaded) + add(cut, loaded, overlap: shared, to: &tpIngress); add(cut, loaded, overlap: shared, to: &tpEgress) continue } if stages.allSatisfy({ $0 == nil }) { @@ -505,18 +522,20 @@ public enum ClusterModelLayoutBuilder { + "the stage plan is not a contiguous layer pipeline") } layers[layer].add(stored: tensor.byteCount, loaded: loaded, work: work) - let cut = try tensorParallelCut(tensor.name) - add(cut, loaded, to: &tpLayers[layer]) + let cut = try tensorParallelCut(tensor.name), shared = try overlap(cut, tensor, loaded) + add(cut, loaded, overlap: shared, to: &tpLayers[layer]) if routing != nil, family.isRoutedExpert(storedTensor: tensor.name) { routed.loaded += loaded - if cut == .divided { routed.divided += loaded } + if cut == .divided { routed.divided += loaded - shared } } } else if stages.allSatisfy({ $0 == 0 }) { ingress.add(stored: tensor.byteCount, loaded: loaded, work: work) - add(try tensorParallelCut(tensor.name), loaded, to: &tpIngress) + let cut = try tensorParallelCut(tensor.name) + add(cut, loaded, overlap: try overlap(cut, tensor, loaded), to: &tpIngress) } else if stages.allSatisfy({ $0 == 1 }) { egress.add(stored: tensor.byteCount, loaded: loaded, work: work) - add(try tensorParallelCut(tensor.name), loaded, to: &tpEgress) + let cut = try tensorParallelCut(tensor.name) + add(cut, loaded, overlap: try overlap(cut, tensor, loaded), to: &tpEgress) } else { throw ClusterPlacementError("Tensor \(tensor.name) changes stage with the cut but names no layer") } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementExplanation.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementExplanation.swift index 2f7abd5657..d9a0f8d871 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementExplanation.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementExplanation.swift @@ -108,9 +108,11 @@ public enum ClusterPlacementExplanation { lines.append(" Modes: \(layout.generationModes.map(\.rawValue).joined(separator: ", ")). " + "Largest request: \(layout.maximumPromptTokens) prompt and \(layout.maximumOutputTokens) output tokens.") if let head = layout.tensorParallel?.speculativeHead(mode: .tensorParallel, layout: layout) { + // A plan states no speed-up above 1 until the pair measured the rounds (MiMo's, 2026-11-01). lines.append(" Tensor parallel decodes in speculative rounds of up to \(head.plan.depth) proposals: every rank holds the model's head " - + "whole (\(gibText(head.part.loadedBytes))) and \(gibText(head.plan.requestBytes)) of its request state, and decode is credited " - + "\(number(head.plan.decodeSpeedup, 2))x one token per step, as the rounds measured.") + + "whole (\(gibText(head.part.loadedBytes))) and \(gibText(head.plan.requestBytes)) of its request state, and decode is " + + (head.plan.decodeSpeedup > 1 ? "credited \(number(head.plan.decodeSpeedup, 2))x one token per step, as the rounds measured." + : "credited nothing over one token per step until the rounds are measured.")) } return lines } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift index 770e062037..cacf583e64 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementPlanner.swift @@ -46,6 +46,10 @@ public struct ClusterPlacementPolicy: Sendable { /// A capacity-only replacement preserves the current TP arithmetic partition. /// This restricts candidates; all current LOAD/request memory gates still apply. public var requiredTensorShares: [Int]? + /// Equal tensor-parallel shares only: the plan of a pair that registers with a coordinator, whose registration + /// names no `tensor_parallel_shares` (a plan without them is an equal split there). False, the default, also + /// places the family's unequal splits. + public var equalTensorShares = false /// A request longer than the layout's planned one (its maximum prompt /// plus output), up to this context: the family's own largest, which /// its ranks admit at load when memory allows. Nil plans within the @@ -116,7 +120,10 @@ public struct ClusterPlacementPolicy: Sendable { /// say, and neither `tensorParallelMargin` nor `keptMode` holds it back; a better group (one that loads now /// while tensor parallel would not) still goes first. Predictions are still made and reported. False, the /// default here: the speed comparison decides (the plan tool without `--tensor-parallel-first`, and the - /// checks of that comparison). + /// checks of that comparison). A family whose plan states `ClusterTensorParallelChoice.fastest` is always + /// ranked by the comparison (owner policy 2026-11-01) and takes tensor parallel only on every rank's measured + /// share step; its first placement prices an unmeasured link conservatively + /// (`ClusterTensorParallelChoice.assumedReduction`). public var tensorParallelFirst = false /// With `tensorParallelFirst`: before a load has measured the link, plan tensor parallel on the keyed /// reduction a forced plan assumes (`ClusterForcedMode.assumedReduction`, labelled as assumed), so the first @@ -127,6 +134,12 @@ public struct ClusterPlacementPolicy: Sendable { public var tensorParallelAssumesUnmeasuredLink = false /// Why the mode is kept, in plain words: the plan's reason line when the hold decides the choice. public var keptModeReason: String? + /// Feature parity (owner, 2026-11-01: a mode may be chosen only if it keeps every feature and caching behavior + /// of the mode it would replace): why the caller left the tensor-parallel modes out of `modes`, in plain words + /// ("tensor parallel would drop prompt-prefix reuse that the pipeline keeps; held back until it keeps them"). + /// The plan says it (`ClusterTensorParallelAssessment.Verdict.dropsFeatures`). Nil, the default: no mode was + /// left out for its features. + public var tensorParallelHeldForFeatures: String? public init() {} } @@ -357,7 +370,8 @@ public enum ClusterPlacementPlanner { if let shares = policy.requiredTensorShares { guard devices.count == 2, shares.count == 2, shares.allSatisfy({ (1...64).contains($0) }), policy.modes == [.tensorParallel], policy.leader != nil, - Set(shares).count == 1 || (layout.tensorParallel?.family.shareOptions ?? []).contains(shares) else { + Set(shares).count == 1 || (!policy.equalTensorShares + && (layout.tensorParallel?.family.shareOptions ?? []).contains(shares)) else { throw ClusterPlacementError("A retained tensor partition needs its exact ordered, supported two-rank shares") } } @@ -420,11 +434,16 @@ public enum ClusterPlacementPlanner { link = link.assumingForcedReduction() } } + // A family whose plan is chosen only where faster (`ClusterTensorParallelChoice.fastest`) is ranked by the + // speed comparison, whatever the provider's rule says. + let fastestOnly = layout.tensorParallel?.family.choosesFastest == true + let tensorParallelFirst = policy.tensorParallelFirst && !fastestOnly if policy.tensorParallelFirst, policy.tensorParallelAssumesUnmeasuredLink, policy.forcedMode == nil, modes.contains(.tensorParallel), let tp = layout.tensorParallel, tp.family.ranks.contains(min(policy.maximumRanges, devices.count)) { // Tensor parallel goes first where it fits: before a load measured the link, an assumed keyed reduction. - link = link.assumingForcedReduction() + // A fastest-only family is compared on a conservative one instead. + link = fastestOnly ? link.assuming(ClusterTensorParallelChoice.assumedReduction) : link.assumingForcedReduction() } let context = Context(devices: devices, layout: layout, prompt: prompt, outputs: outputs, modes: modes, schedules: schedules, link: link, policy: policy) @@ -438,9 +457,11 @@ public enum ClusterPlacementPlanner { } } ?? admitted let byTime = context.ordered(qualified.filter(\.possible), regime: policy.regime) - let unheld = policy.tensorParallelFirst ? context.tensorParallelFirst(byTime) + let unheld = tensorParallelFirst ? context.tensorParallelFirst(byTime) : context.holdingTensorParallelToItsMargin(byTime, regime: policy.regime) - let ranked = policy.tensorParallelFirst ? unheld : context.holdingKeptMode(unheld, regime: policy.regime) + // A family chosen only where faster takes tensor parallel on measured share steps, never on the prior alone. + let evidenced = fastestOnly ? context.holdingTensorParallelWithoutEvidence(unheld, regime: policy.regime) : unheld + let ranked = tensorParallelFirst ? unheld : context.holdingKeptMode(evidenced, regime: policy.regime) if let forced = policy.forcedMode, ranked.isEmpty { throw ClusterPlacementError("Developer setting: \(forced.words) forced, but no \(forced.words) placement of \(layout.runtimeModelID) " + (admitted.contains(where: \.possible) @@ -496,7 +517,7 @@ public enum ClusterPlacementPlanner { candidatesConsidered: admitted.count, unqualifiedPossible: policy.admitsShape == nil ? nil : admitted.filter(\.possible).count - qualified.filter(\.possible).count) - if let kept = policy.keptMode, ranked.first?.mode == kept, unheld.first?.mode != kept { + if let kept = policy.keptMode, ranked.first?.mode == kept, evidenced.first?.mode != kept { result.keptModeReason = policy.keptModeReason ?? "kept \(kept.rawValue), the mode this pair keeps" } // A family the policy left out entirely (every pipeline mode, or tensor parallel) is said with the @@ -508,8 +529,11 @@ public enum ClusterPlacementPlanner { if families.contains(where: { !$0.isEmpty && !$0.contains(where: allowed.contains) }) { result.modesReason = reason } } if layout.tensorParallel != nil { + let heldForEvidence = unheld.first?.mode.usesTensorParallelDecode == true + && evidenced.first?.mode.usesTensorParallelDecode == false result.tensorParallel = try assessTensorParallel(devices: devices, layout: layout, policy: policy, link: link, - prompt: prompt, outputs: outputs, schedules: schedules, ranked: ranked, alone: alone) + prompt: prompt, outputs: outputs, schedules: schedules, ranked: ranked, alone: alone, + heldForEvidence: heldForEvidence) } if !policy.handOffModes { result.shards = try assessShards(context: context, admitted: admitted, qualified: qualified, ranked: ranked, @@ -520,11 +544,13 @@ public enum ClusterPlacementPlanner { /// The tensor-parallel modes evaluated whether or not the runtime lists /// them, against what was chosen: the planner's answer to "would tensor - /// parallel be faster here, and if so what stops it". + /// parallel be faster here, and if so what stops it". `heldForEvidence`: + /// the plan put another mode first only because tensor parallel's share + /// steps are not all measured (`holdingTensorParallelWithoutEvidence`). static func assessTensorParallel(devices: [ClusterPlacementDevice], layout: ClusterModelLayout, policy: ClusterPlacementPolicy, link: ClusterLinkCosts, prompt: Int, outputs: Int, schedules: [ClusterPrefillSchedule], ranked: [ClusterPlacementCandidate], - alone: [ClusterPlacementAlone]) throws -> ClusterTensorParallelAssessment? { + alone: [ClusterPlacementAlone], heldForEvidence: Bool) throws -> ClusterTensorParallelAssessment? { guard let tp = layout.tensorParallel else { return nil } let regime = policy.regime let steps = tp.reductionsPerStep(layerCount: layout.layerCount) @@ -553,6 +579,7 @@ public enum ClusterPlacementPlanner { (policy.modes?.contains(mode) ?? true) && (policy.forcedMode?.admits(mode) ?? true) } guard !modes.isEmpty else { + if let held = policy.tensorParallelHeldForFeatures { return unavailable(.dropsFeatures, held) } let why = implemented.contains(where: { policy.modes?.contains($0) == false }) ? policy.modesReason.map { " (\($0))" } ?? "" : "" return unavailable(.notQualified, "the placement policy excludes the model's tensor-parallel modes\(why); using pipeline candidates") } @@ -573,13 +600,20 @@ public enum ClusterPlacementPlanner { let best = context.ordered(possible.filter { $0.mode == .tensorParallel }, regime: regime).first let hybrid = context.ordered(possible.filter { $0.mode == .pipelinePrefillTensorDecode }, regime: regime).first let perStep = tp.family.decodeReductionSeconds(layers: layout.layerCount, head: true, reduction: reduction) - func make(_ verdict: ClusterTensorParallelAssessment.Verdict, _ reason: String) -> ClusterTensorParallelAssessment { - .init(verdict: verdict, reason: reason, tensorParallel: best, hybrid: hybrid, bestOtherSeconds: bestOther, - bestAloneSeconds: bestAlone, devices: speeds, reductionsPerStep: steps, reductionSecondsPerStep: perStep, - reductionKeyed: reduction.keyed) + func make(_ verdict: ClusterTensorParallelAssessment.Verdict, _ reason: String, + restingOn placement: ClusterPlacementCandidate? = nil) -> ClusterTensorParallelAssessment { + var value = ClusterTensorParallelAssessment(verdict: verdict, reason: reason, tensorParallel: best, hybrid: hybrid, + bestOtherSeconds: bestOther, bestAloneSeconds: bestAlone, devices: speeds, reductionsPerStep: steps, + reductionSecondsPerStep: perStep, reductionKeyed: reduction.keyed) + if tp.family.choosesFastest, let placement { + value.evidence = context.measuredShareSteps(placement, regime: regime) ? .measured : .priorOnly + } + return value } if let chosen = ranked.first, chosen.mode.usesTensorParallelDecode { - return make(.chosen, "predicted faster than every other mode by at least the margin") + let measured = tp.family.choosesFastest && context.measuredShareSteps(chosen, regime: regime) + return make(.chosen, "predicted faster than every other mode by at least the margin" + + (measured ? ", on every rank's measured share step" : ""), restingOn: chosen) } guard let fastest = [best, hybrid].compactMap({ $0 }).min(by: { $0.prediction(regime).requestSeconds < $1.prediction(regime).requestSeconds }) else { @@ -595,21 +629,29 @@ public enum ClusterPlacementPlanner { "\($0.device) needs \(ClusterPlacementExplanation.gibText($0.needBytes)) and admits \(ClusterPlacementExplanation.gibText($0.admissibleNowBytes)) now" } return make(.doesNotFit, String(format: "predicted %.2f s against %.2f s for the chosen placement, but it does not fit as these Macs are now (%@)", - time, chosen.prediction(regime).requestSeconds, short.joined(separator: "; "))) + time, chosen.prediction(regime).requestSeconds, short.joined(separator: "; ")), restingOn: fastest) } let unmeasured = speeds.filter { !$0.split.measured && $0.split.fromHardware == nil }.map(\.device) let prior = speeds.filter { $0.split.fromHardware == true }.map(\.device) let note = (unmeasured.isEmpty ? "" : "; no shard probe on \(unmeasured.joined(separator: ", ")), so its step is assumed not to shrink") + (prior.isEmpty ? "" : "; no shard probe on \(prior.joined(separator: ", ")), so its share's step is predicted from its measured device index") + if heldForEvidence, let bestOther { + return make(.predictedFasterOnPriorOnly, String(format: "predicted %.2f s against %.2f s for the chosen placement, " + + "but not on every rank's measured share step", time, bestOther) + note + + "; chosen only once a share probe of this model or requests served in tensor parallel measure each rank", + restingOn: fastest) + } if let bestOther, time >= bestOther * (1 - policy.tensorParallelMargin) { - return make(.predictedSlower, String(format: "predicted %.2f s against %.2f s for the chosen placement", time, bestOther) + note) + return make(.predictedSlower, String(format: "predicted %.2f s against %.2f s for the chosen placement", time, bestOther) + note, + restingOn: fastest) } guard reduction.keyed else { return make(.reductionNotMeasured, String(format: "predicted %.2f s, but the reduction was measured as a native all-sum; " - + "the product reduces over the keyed data plane, and only that measurement can choose the mode", time) + note) + + "the product reduces over the keyed data plane, and only that measurement can choose the mode", time) + note, + restingOn: fastest) } return make(.notQualified, String(format: "predicted %.2f s, but the policy admits no %@ shape on these Macs (a cross-cable check diverged at each)", - time, fastest.mode.rawValue) + note) + time, fastest.mode.rawValue) + note, restingOn: fastest) } /// One explicit placement, evaluated as the planner evaluates its own @@ -627,9 +669,13 @@ public enum ClusterPlacementPlanner { } var link = link if mode.usesTensorParallelDecode { - // As `plan` does: tensor parallel goes first wherever it fits, on an assumed keyed reduction until a load measures the link. + // As `plan` does: tensor parallel goes first wherever it fits, on an assumed keyed reduction until a load + // measures the link (a conservative one for a fastest-only family). if policy.tensorParallelFirst, policy.tensorParallelAssumesUnmeasuredLink, policy.forcedMode == nil, - mode == .tensorParallel { link = link.assumingForcedReduction() } + mode == .tensorParallel { + link = layout.tensorParallel?.family.choosesFastest == true + ? link.assuming(ClusterTensorParallelChoice.assumedReduction) : link.assumingForcedReduction() + } guard let tp = layout.tensorParallel, tp.family.ranks.contains(devices.count), link.reduction != nil else { throw ClusterPlacementError("A tensor-parallel placement needs the layout's tensor-parallel facts for this many ranks and a measured reduction") } @@ -732,18 +778,19 @@ public enum ClusterPlacementPlanner { var result: [ClusterPlacementCandidate] = [] let most = min(policy.maximumRanges, devices.count) guard most >= 2 else { return [] } - // A lookahead prefill is never slower than a serial one of the same placement. - let schedule = schedules.contains(.oneChunkLookahead) ? ClusterPrefillSchedule.oneChunkLookahead : schedules[0] + // A layer split prefills with the lookahead where the model has it; tensor parallel prefills serially. + let schedule = ClusterPrefillSchedule.planned(for: .pipeline, supported: schedules) + let tensorSchedule = ClusterPrefillSchedule.planned(for: .tensorParallel, supported: schedules) for ranges in 2...most { - let tensor = scope == .admitted && modes.contains(.tensorParallel) && placeable(.tensorParallel, ranges: ranges) + let tensor = scope == .admitted && modes.contains(.tensorParallel) && schedules.contains(tensorSchedule) + && placeable(.tensorParallel, ranges: ranges) let layerModes = modes.filter { !($0.usesTensorParallelPrefill) && placeable($0, ranges: ranges) } let pipeline = !layerModes.isEmpty && available.count >= ranges - 1 guard tensor || pipeline else { continue } let sets = pipeline ? cutSets(available, ranges - 1) : [] let permutations = orders(ranges) - let shares = tensor && policy.requiredTensorShares == nil ? (layout.tensorParallel?.family.shareOptions ?? []).filter { - $0.count == ranges && Set($0).count > 1 - } : [] + let shares = tensor && policy.requiredTensorShares == nil && !policy.equalTensorShares + ? (layout.tensorParallel?.family.shareOptions ?? []).filter { $0.count == ranges && Set($0).count > 1 } : [] let perOrder = sets.count * layerModes.count + (tensor ? 1 + shares.count : 0) guard perOrder * permutations.count + result.count <= policy.maximumCandidates else { throw ClusterPlacementError("Placing \(ranges) ranges over \(available.count) cuts on \(devices.count) devices " @@ -755,10 +802,10 @@ public enum ClusterPlacementPlanner { if tensor { var splits: [ClusterPlacementCandidate] = [] if let weights = policy.requiredTensorShares { - splits.append(evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: schedule, weights: weights)) - } else { splits.append(bestTensorShares(order: order, schedule: schedule)) } + splits.append(evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: tensorSchedule, weights: weights)) + } else { splits.append(bestTensorShares(order: order, schedule: tensorSchedule)) } for weights in shares { - splits.append(evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: schedule, weights: weights)) + splits.append(evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: tensorSchedule, weights: weights)) } result += keepingWidenable(splits) } @@ -872,12 +919,13 @@ public enum ClusterPlacementPlanner { return widenable.isEmpty ? splits : widenable } - /// The tensor-parallel candidate of this order at its best shares: equal, - /// or, when the family's plan hands out `shareUnits` groups and two ranks - /// run it, every split in whole groups, the best by the planner's own order. + /// The tensor-parallel candidate of this order at its best shares: equal + /// (always under `equalTensorShares`), or, when the family's plan hands out + /// `shareUnits` groups and two ranks run it, every split in whole groups, + /// the best by the planner's own order. func bestTensorShares(order: [Int], schedule: ClusterPrefillSchedule) -> ClusterPlacementCandidate { let equal = evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: schedule) - guard order.count == 2, let units = layout.tensorParallel?.family.shareUnits else { return equal } + guard !policy.equalTensorShares, order.count == 2, let units = layout.tensorParallel?.family.shareUnits else { return equal } let splits = (1.. ClusterPlacementCandidate in let first = Double(k) / Double(units) return evaluate(order: order, cuts: [], mode: .tensorParallel, schedule: schedule, shares: [first, 1 - first]) @@ -994,14 +1042,38 @@ public enum ClusterPlacementPlanner { /// right after that candidate. func holdingTensorParallelToItsMargin(_ ordered: [ClusterPlacementCandidate], regime: ClusterPlacementPolicy.Regime) -> [ClusterPlacementCandidate] { - func group(_ c: ClusterPlacementCandidate) -> Int { hardwareGroup(c) } + holdingTensorParallel(ordered) { candidate, other in + candidate.prediction(regime).requestSeconds > other.prediction(regime).requestSeconds * (1 - policy.tensorParallelMargin) + } + } + + /// `ClusterTensorParallelChoice.fastest`: a tensor-parallel candidate stays ahead of the best candidate of + /// another mode in its group only when every rank's share step is measured (`measuredShareSteps`); + /// otherwise it goes right after that candidate. One in a better group (only it loads now) stays first. + func holdingTensorParallelWithoutEvidence(_ ordered: [ClusterPlacementCandidate], + regime: ClusterPlacementPolicy.Regime) -> [ClusterPlacementCandidate] { + holdingTensorParallel(ordered) { candidate, _ in !measuredShareSteps(candidate, regime: regime) } + } + + /// True when a shard probe measured every rank of `candidate` at a share in this regime + /// (`ClusterDecodeSplit.measured`): a share probe of this model, its speed record's shard rates, or the + /// shard rates requests served in tensor parallel corrected (`ClusterServedCalibration`). + func measuredShareSteps(_ candidate: ClusterPlacementCandidate, regime: ClusterPlacementPolicy.Regime) -> Bool { + candidate.ranks.allSatisfy { rank in + devices.first { $0.label == rank.device }.map { split($0, regime).measured } ?? false + } + } + + /// The tensor-parallel candidates ahead of the best candidate of another mode, in its hardware group, that + /// `holds` keeps back go right after that candidate; the rest keep their order. + private func holdingTensorParallel(_ ordered: [ClusterPlacementCandidate], + holds: (_ candidate: ClusterPlacementCandidate, _ other: ClusterPlacementCandidate) -> Bool) + -> [ClusterPlacementCandidate] { guard let otherIndex = ordered.firstIndex(where: { !$0.mode.usesTensorParallelDecode }) else { return ordered } let other = ordered[otherIndex] - let limit = other.prediction(regime).requestSeconds * (1 - policy.tensorParallelMargin) var held: [ClusterPlacementCandidate] = [], kept: [ClusterPlacementCandidate] = [] for candidate in ordered[.. limit { + if candidate.mode.usesTensorParallelDecode, hardwareGroup(candidate) == hardwareGroup(other), holds(candidate, other) { held.append(candidate) } else { kept.append(candidate) @@ -1219,7 +1291,7 @@ public enum ClusterPlacementPlanner { /// (`first`) or from its end, whatever is freed on it; 0 for none. A /// range's need only grows with its length, so the first failure ends it. func extent(_ device: ClusterPlacementDevice, first: Bool) -> Int { - let schedule = schedules.contains(.oneChunkLookahead) ? ClusterPrefillSchedule.oneChunkLookahead : schedules[0] + let schedule = ClusterPrefillSchedule.planned(for: .pipeline, supported: schedules) var most = 0 for count in 1.. 1, let singleton = policy.tensorParallelBatchQuote, singleton.lanes == 1, + singleton.request == request, singleton.chunkTokens == chunkTokens, + singleton.assistant?.policy == assistant?.policy else { + throw ClusterPlacementError("A saved tensor width needs the same owner's singleton quote") + } + try request.applyCovering(to: &policy, layout: layout) + policy.tensorParallelBatchQuote = self + policy.tensorParallelWideningQuote = nil + } + public func requireAssistant(_ expected: ClusterQwenTensorAssistantPolicy?) throws { guard assistant?.policy == expected else { throw ClusterPlacementError("Tensor quotation changed the saved assistant policy") diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift index d77580a9ed..e01f6e0cf0 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterRequestMix.swift @@ -61,19 +61,21 @@ extension ClusterPlacementExplanation { // Tensor parallel goes first wherever it fits (`ClusterPlacementPolicy.tensorParallelFirst`): a gain is said // only when the prediction shows one; otherwise the rule is the reason. let fits = "Tensor parallel: the model fits, so both Macs share every layer of every token." + // A family chosen only where faster (`ClusterTensorParallelChoice.fastest`) says its measured step chose it. + let measured = assessment?.evidence == .measured ? ", on its own step as measured on both Macs" : "" if let theirs = result.alternatives.first(where: { !$0.mode.usesTensorParallelDecode })?.prediction(regime) ?? pipelines.min(by: { $0.requestSeconds < $1.requestSeconds }) { if theirs.requestSeconds <= mine.requestSeconds { return fits } - if estimated { return "Tensor parallel: predicted faster than a pipeline for \(request)\(note)." } + if estimated { return "Tensor parallel: predicted faster than a pipeline for \(request)\(measured)\(note)." } let gain = (theirs.requestSeconds / mine.requestSeconds - 1) * 100 - return "Tensor parallel: predicted \(Int(gain.rounded()))% faster than a pipeline for \(request) (\(against(mine, theirs)))." + return "Tensor parallel: predicted \(Int(gain.rounded()))% faster than a pipeline for \(request) (\(against(mine, theirs)))\(measured)." } if let other = assessment?.bestOtherSeconds { if other <= mine.requestSeconds { return fits } - if estimated { return "Tensor parallel: predicted faster than a pipeline for \(request)\(note)." } + if estimated { return "Tensor parallel: predicted faster than a pipeline for \(request)\(measured)\(note)." } let gain = (other / mine.requestSeconds - 1) * 100 return "Tensor parallel: predicted \(Int(gain.rounded()))% faster than a pipeline for \(request) " - + "(\(seconds(mine.requestSeconds)) against \(seconds(other)))." + + "(\(seconds(mine.requestSeconds)) against \(seconds(other)))\(measured)." } // No pipeline was placed, and the reason is said as it is (2026-10-24: Qwen3.8 27B, whose images, video // and logprobs only tensor parallel keeps, read "no pipeline placement fits these Macs"): the policy left @@ -102,6 +104,18 @@ extension ClusterPlacementExplanation { let theirs = tp.prediction(regime) return "\(name): tensor parallel is predicted slower for \(request) (\(seconds(theirs.requestSeconds)) against " + "\(seconds(mine.requestSeconds)); \(against(theirs, mine)))." + case .predictedFasterOnPriorOnly: + // A family chosen only where faster (`ClusterTensorParallelChoice.fastest`) waits for its own measured step. + let basis = "from the device index, not its own measured step" + let until = "; it can be chosen once its step is measured on both Macs (a share probe at a tensor-parallel load, " + + "or requests this build served in tensor parallel)." + guard let tp = assessment.tensorParallel, !estimated else { + return "\(name): tensor parallel is predicted faster for \(request) \(basis)\(estimated ? note : "")" + until + } + let theirs = tp.prediction(regime) + let gain = (mine.requestSeconds / theirs.requestSeconds - 1) * 100 + return "\(name): tensor parallel is predicted \(Int(gain.rounded()))% faster for \(request) (\(seconds(theirs.requestSeconds)) " + + "against \(seconds(mine.requestSeconds)); \(against(theirs, mine))), but \(basis)" + until case .doesNotFit: // A tensor-parallel placement that would load once memory is given back, ranked after one that loads now. if assessment.tensorParallel != nil || assessment.hybrid != nil { @@ -110,7 +124,7 @@ extension ClusterPlacementExplanation { return "\(name): tensor parallel does not fit in these Macs' memory." case .notExecutedByRuntime: return "\(name): \(assessment.reason)." - case .notQualified: + case .notQualified, .dropsFeatures: return "\(name): \(assessment.reason)." } } @@ -123,6 +137,9 @@ extension ClusterPlacementExplanation { case slower = "tensor parallel: slower here" /// Predicted faster, but by less than the margin it must win by (`tensorParallelMargin`). case aboutAsFast = "tensor parallel: about as fast" + /// Predicted faster, but only from the device index: a family chosen only where faster waits for its + /// own measured step (`ClusterTensorParallelAssessment.Verdict.predictedFasterOnPriorOnly`). + case notMeasuredYet = "tensor parallel: not measured yet" /// It would fit once memory is given back; a split that loads now goes first. case doesNotFitNow = "tensor parallel: does not fit now" case doesNotFit = "tensor parallel: does not fit" @@ -134,6 +151,9 @@ extension ClusterPlacementExplanation { case pipelineKept = "tensor parallel: pipeline kept" /// The placement policy leaves tensor parallel out (`modesReason` says why, when it says). case excluded = "tensor parallel: excluded here" + /// It would drop a feature of the mode it would replace (feature parity, + /// `ClusterTensorParallelAssessment.Verdict.dropsFeatures`). + case dropsFeature = "tensor parallel: drops a feature" /// This runtime does not execute tensor parallel for this model or rank count. case notForThisModel = "no tensor parallel for this model" } @@ -168,6 +188,8 @@ extension ClusterPlacementExplanation { case .predictedSlower: guard let best, best.prediction(regime).requestSeconds < chosen.prediction(regime).requestSeconds else { return .slower } return .aboutAsFast + case .predictedFasterOnPriorOnly: return .notMeasuredYet + case .dropsFeatures: return .dropsFeature } } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterServedSpeed.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterServedSpeed.swift index 48662bf810..d20b72e277 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterServedSpeed.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterServedSpeed.swift @@ -497,7 +497,8 @@ public enum ClusterServedCalibration { let ordered = ranks.compactMap { label in devices.first { $0.label == label } } guard ordered.count == ranks.count else { lines.append(" \(setup.mode) cut \(setup.cut): skipped (a rank is not a planned device)"); continue } let samples = entries.filter { $0.setup == setup }.map(\.sample) - let schedule: ClusterPrefillSchedule = layout.prefillSchedules.contains(.oneChunkLookahead) ? .oneChunkLookahead : .serial + // The schedule the setup ran, as the planner gives its mode (tensor parallel serially). + let schedule = ClusterPrefillSchedule.planned(for: mode, supported: layout.prefillSchedules) // A pipeline's speculative rounds are measured against what the same placement served plainly // with the same builds: their speed-up then rides on the decoding rank's plain measurement (one // record per device). diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterShardAssessment.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterShardAssessment.swift index b70ef85756..b3e355a8db 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterShardAssessment.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterShardAssessment.swift @@ -35,12 +35,18 @@ public struct ClusterShardOption: Codable, Equatable, Sendable { case chosen /// Predicted slower than the chosen deployment, or fitting less readily. case slower + /// Predicted faster, but a rank's share step is not measured + /// (`ClusterTensorParallelAssessment.Verdict.predictedFasterOnPriorOnly`). + case predictedFasterOnPriorOnly /// No runtime of this build executes it for this model. case notExecutedByRuntime /// The model's adapter has no tensor-parallel plan: it gets a pipeline. case adapterHasNoTensorParallel /// A qualification check failed at this shape, so the records keep it out. case failedQualification + /// It would drop a feature of the mode it would replace + /// (`ClusterTensorParallelAssessment.Verdict.dropsFeatures`). + case dropsFeatures case doesNotFit /// Tensor parallel x pipeline needs three or more members. case needsMoreMembers @@ -173,6 +179,9 @@ extension ClusterPlacementPlanner { return option(.tensorParallel, .chosen, "predicted faster than every pipeline by at least the margin" + (best.shares != nil ? ", at the shares that balance the two Macs' steps" : ""), best, regime: regime, layerCount: layers) } + if let assessment, assessment.verdict == .predictedFasterOnPriorOnly { + return option(.tensorParallel, .predictedFasterOnPriorOnly, assessment.reason, best, regime: regime, layerCount: layers) + } return option(.tensorParallel, .slower, versus(best, ranked.first, regime: regime), best, regime: regime, layerCount: layers) } guard let assessment else { @@ -182,8 +191,10 @@ extension ClusterPlacementPlanner { switch assessment.verdict { case .chosen: verdict = .chosen case .predictedSlower: verdict = .slower + case .predictedFasterOnPriorOnly: verdict = .predictedFasterOnPriorOnly case .notExecutedByRuntime: verdict = .notExecutedByRuntime case .notQualified: verdict = .failedQualification + case .dropsFeatures: verdict = .dropsFeatures case .doesNotFit: verdict = .doesNotFit case .reductionNotMeasured: verdict = .reductionNotMeasured } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallel.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallel.swift index 524721232e..86fdd2625b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallel.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallel.swift @@ -56,12 +56,16 @@ public struct ClusterTensorParallelFamilyPlan: Codable, Equatable, Sendable { /// `tensor_parallel_v1` with it on every rank. Nil: one token per step and /// no head (omitted then, so a layout of any other family reads as before). public let speculativeHead: ClusterTensorParallelSpeculativeHead? + /// How the plan is weighed against the pipeline under the provider's + /// tensor-parallel-first rule (`ClusterTensorParallelChoice`). Nil keeps + /// that rule (omitted then, so a layout of any other family reads as before). + public let choice: ClusterTensorParallelChoice? public init(plan: String, ranks: [Int], reductionsPerLayer: Int, reductionsPerStep: Int, partialBytesPerToken: Int, layerPartialBytesPerToken: Int? = nil, stateDividesByHeads: Bool, shareOptions: [[Int]]? = nil, shareUnits: Int? = nil, requestAllowance: ClusterTensorParallelRequestAllowance? = nil, additionalResidentBytes: Int? = nil, - speculativeHead: ClusterTensorParallelSpeculativeHead? = nil) { + speculativeHead: ClusterTensorParallelSpeculativeHead? = nil, choice: ClusterTensorParallelChoice? = nil) { self.plan = plan; self.ranks = ranks; self.reductionsPerLayer = reductionsPerLayer self.reductionsPerStep = reductionsPerStep; self.partialBytesPerToken = partialBytesPerToken self.layerPartialBytesPerToken = layerPartialBytesPerToken @@ -71,8 +75,13 @@ public struct ClusterTensorParallelFamilyPlan: Codable, Equatable, Sendable { self.requestAllowance = requestAllowance self.additionalResidentBytes = additionalResidentBytes self.speculativeHead = speculativeHead + self.choice = choice } + /// True when the provider's tensor-parallel-first rule does not apply to + /// this plan: it is chosen only where predicted faster. + public var choosesFastest: Bool { choice == .fastest } + /// Bytes a selection reduction carries (the head's best value and token /// per rank, a few floats), as the prefill prediction has always charged it. static let selectionReductionBytes = 16 @@ -374,10 +383,18 @@ public struct ClusterTensorParallelAssessment: Codable, Equatable, Sendable { case chosen /// Predicted slower than the chosen placement (or within the margin). case predictedSlower + /// Predicted faster than the chosen placement by the margin, but a + /// rank's share step comes from the hardware prior, not a measurement: + /// a family chosen only where faster (`ClusterTensorParallelChoice.fastest`) + /// waits for every rank's measured share step (`Evidence.measured`). + case predictedFasterOnPriorOnly /// This runtime does not execute the mode for this model and rank count. case notExecutedByRuntime /// The policy excludes this mode or every executable shape on these chips. case notQualified + /// Left out before ranking because it would drop a feature of the mode + /// it would replace (`ClusterPlacementPolicy.tensorParallelHeldForFeatures`). + case dropsFeatures /// No placement in this mode fits. case doesNotFit /// The reduction over the link was not measured on the keyed data @@ -390,6 +407,17 @@ public struct ClusterTensorParallelAssessment: Codable, Equatable, Sendable { public let split: ClusterDecodeSplit } + /// What a tensor-parallel prediction rests on, for a family chosen only + /// where faster (`ClusterTensorParallelChoice.fastest`). + public enum Evidence: String, Codable, Sendable { + /// Every rank's share step is measured (`ClusterDecodeSplit.measured`): + /// a share probe of this model, or requests served in tensor parallel. + case measured + /// A rank's share step comes from the hardware prior (or is not + /// predicted to shrink): the family does not choose tensor parallel on it. + case priorOnly + } + public let verdict: Verdict public let reason: String /// The fastest predicted placement in each tensor-parallel mode. @@ -403,4 +431,8 @@ public struct ClusterTensorParallelAssessment: Codable, Equatable, Sendable { public let reductionsPerStep: Int public let reductionSecondsPerStep: Double? public let reductionKeyed: Bool? + /// For a family chosen only where faster, whose tensor-parallel placement + /// was predicted: what that placement's (or the chosen one's) ranks rest + /// on. Nil otherwise (omitted then, so a plan of any other family reads as before). + public var evidence: Evidence? = nil } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallelChoice.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallelChoice.swift new file mode 100644 index 0000000000..b30daec604 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterTensorParallelChoice.swift @@ -0,0 +1,45 @@ +import DarkbloomClusterProtocol + +/// How a family's tensor-parallel plan is weighed against the pipeline when +/// the provider's placement step puts tensor parallel first +/// (`ClusterPlacementPolicy.tensorParallelFirst`, owner 2026-10-24: "if tensor +/// fits it will and should always be faster"). A family states it in its plan +/// (`ClusterTensorParallelFamilyPlan.choice`); nil, every family before it +/// (Qwen, GLM), keeps that rule exactly. +/// +/// To opt a family in, pass `choice: .fastest` where its placement family +/// builds `ClusterTensorParallelFamilyPlan` (`Gemma4PlacementFamily` does); +/// nothing else changes. Its layouts then encode `"choice":"fastest_v1"` in +/// the plan, so regenerate its golden layouts with it. +public enum ClusterTensorParallelChoice: String, Codable, Sendable { + /// Chosen only where predicted faster than the best placement in any other + /// mode by `ClusterPlacementPolicy.tensorParallelMargin`, as the planner's + /// own comparison chooses (owner policy 2026-11-01: the fastest plan, not + /// tensor parallel first), and held to the mode the pair keeps + /// (`ClusterPlacementPolicy.keptMode`) like any other mode. The comparison + /// reads the pair's measured link (`ClusterLinkProbeHistory`) and share + /// probes (`ClusterShareProbeHistory`); before any load measured the link, + /// a first placement prices tensor parallel on `assumedReduction` and the + /// pipeline's transfers as free, so a pipeline is chosen unless tensor + /// parallel is faster even then. + /// + /// The prediction must also rest on every rank's measured share step + /// (`ClusterDecodeSplit.measured`: a share probe of this model, or the + /// shard rates requests this build served in tensor parallel corrected). + /// The hardware prior alone (`ClusterHardwarePrior`) never chooses it: the + /// device index times each operation with its launch latency inside, so + /// it overstates the weight time a rank halves. A placement predicted + /// faster on the prior keeps the best other mode + /// (`ClusterTensorParallelAssessment.Verdict.predictedFasterOnPriorOnly`). + case fastest = "fastest_v1" + + /// The reduction a first placement of a `fastest` family assumes before a + /// load measured the link: a sealed all-sum at the slow end of what pairs + /// measured (27-29 us at 16 KB on two M5 Ultra over Thunderbolt 5, + /// 2026-10-31; 43-109 us on another pair, 2026-10-23), the figures + /// `ClusterForcedMode.assumedReduction` assumes. Labelled as assumed. + public static let assumedReduction = ClusterReductionCost(fixedSeconds: ClusterForcedMode.assumedReduction.fixedSeconds, + secondsPerByte: ClusterForcedMode.assumedReduction.secondsPerByte, keyed: true, + provenance: "assumed, not measured: no load has measured this link yet, so tensor parallel is priced at a slow sealed " + + "all-sum (0.1 ms fixed, 2.5 GB/s) and chosen only where it is predicted faster even then") +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterMiMoTensorParallel.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterMiMoTensorParallel.swift new file mode 100644 index 0000000000..5455d17757 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterMiMoTensorParallel.swift @@ -0,0 +1,25 @@ +import Foundation + +/// How MiMo V2.6 Flash's tensor parallel decodes, for the owner that launches +/// it and the worker that declares it: every rank holds the artifact's three +/// trained next-N heads whole and decodes in speculative rounds +/// (`MiMoTensorParallelResidentRuntime`, `--mtp-depth`). No generation mode +/// names those heads, so the owner passes the depth to both ranks, and both +/// bind it into their load agreement. +public enum ClusterMiMoTensorParallel { + /// Drafts each round verifies: the depth MiMo's speculative pipeline + /// measured fastest (`MiMoMTPTerms.standard`), which the tensor-parallel + /// plan recommends too. + public static let speculativeDepth = 2 + + /// Whether a placement of `runtimeModelID` in `mode` decodes with the + /// heads: tensor parallel of the registered MiMo text row. + public static func decodesWithHead(runtimeModelID: String, mode: ClusterGenerationMode) -> Bool { + runtimeModelID == ClusterMiMoImageCandidate.runtimeModelID && mode == .tensorParallel && speculativeDepth > 0 + } + + /// The worker arguments that turn the rounds on; none for any other placement. + public static func workerArguments(runtimeModelID: String, mode: ClusterGenerationMode) -> [String] { + decodesWithHead(runtimeModelID: runtimeModelID, mode: mode) ? ["--mtp-depth", String(speculativeDepth)] : [] + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterPrefillSchedule.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterPrefillSchedule.swift index 5d6299f07a..64faa8212b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterPrefillSchedule.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterPrefillSchedule.swift @@ -5,4 +5,13 @@ import Foundation public enum ClusterPrefillSchedule: String, Codable, CaseIterable, Sendable { case serial = "serial_v1" case oneChunkLookahead = "one_chunk_lookahead_v1" + + /// The schedule a placement in `mode` prefills with, of the model's `supported` ones (serial first). Tensor + /// parallel prefills serially: every tensor-parallel runtime admits only `serial` (a Gemma 4 or MiMo pair planned + /// with the lookahead was refused at load, 2026-11-03). A layer split takes the one-chunk lookahead where the + /// model has it, never slower than serial for the same placement. + public static func planned(for mode: ClusterGenerationMode, supported: [ClusterPrefillSchedule]) -> ClusterPrefillSchedule { + if mode.usesTensorParallelPrefill { return .serial } + return supported.contains(.oneChunkLookahead) ? .oneChunkLookahead : supported.first ?? .serial + } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapability.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapability.swift index 80f6dbc5ca..f1422bb9b6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapability.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapability.swift @@ -167,6 +167,12 @@ public struct ClusterRuntimeCapability: Equatable, Sendable { public let speculation: String public static let decodingRankSpeculation = "decodingRankHeadExactGreedy" public let prefixReuse = false + /// What each supported mode keeps of the model's serving features + /// (`ClusterServingFeatures`), one entry per mode, as the adapter declares + /// them; the placement step plans a mode only where it keeps every feature + /// of the mode it would replace. Nil, written as no field: the adapter + /// declares none (its record reads byte for byte as before). + public let modeFeatures: [ClusterGenerationMode: ClusterServingFeatures]? public init(runtimeBinarySHA256: String, adapterID: String, adapterVersion: Int, runtimeModelID: String, artifactSHA256: String, configurationSHA256: String, @@ -175,8 +181,9 @@ public struct ClusterRuntimeCapability: Equatable, Sendable { arithmeticPolicySHA256: String, supportedPrefillSchedules: [ClusterPrefillSchedule] = [.serial], supportedGenerationModes: [ClusterGenerationMode] = [.pipeline], - media: ClusterMiMoImageCandidate? = nil, glmImages: ClusterGLMImageCandidate? = nil) throws { - self.media = media; self.glmImages = glmImages + media: ClusterMiMoImageCandidate? = nil, glmImages: ClusterGLMImageCandidate? = nil, + modeFeatures: [ClusterGenerationMode: ClusterServingFeatures]? = nil) throws { + self.media = media; self.glmImages = glmImages; self.modeFeatures = modeFeatures self.runtimeBinarySHA256 = runtimeBinarySHA256; self.adapterID = adapterID; self.adapterVersion = adapterVersion self.runtimeModelID = runtimeModelID; self.artifactSHA256 = artifactSHA256 self.configurationSHA256 = configurationSHA256; self.manifestSHA256 = manifestSHA256 diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityCodec.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityCodec.swift index 4fed84dedd..d7b9b7a3f0 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityCodec.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityCodec.swift @@ -46,6 +46,10 @@ public enum ClusterRuntimeCapabilityCodec { } if value.media != nil { object["media"] = ClusterMiMoImageCandidate.fields } if value.glmImages != nil { object["glmImages"] = ClusterGLMImageCandidate.fields } + // Written only by an adapter that declares its modes' features, so every other record keeps its bytes. + if let features = value.modeFeatures { + object["modeFeatures"] = Dictionary(uniqueKeysWithValues: features.map { ($0.key.rawValue, $0.value.wireObject) }) + } var data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]) try workerRequire(data.count < maximumBytes, "Runtime capability exceeds its byte bound") data.append(10); return data @@ -106,13 +110,20 @@ public enum ClusterRuntimeCapabilityCodec { } else { modes = [.pipeline] } let media = r.values["media"] == nil ? nil : try ClusterMiMoImageCandidate.decode(r.object("media")) let glmImages = r.values["glmImages"] == nil ? nil : try ClusterGLMImageCandidate.decode(r.object("glmImages")) + let modeFeatures = r.values["modeFeatures"] == nil ? nil : try Dictionary(uniqueKeysWithValues: + r.object("modeFeatures").map { name, entry -> (ClusterGenerationMode, ClusterServingFeatures) in + guard let mode = ClusterGenerationMode(rawValue: name), let object = entry as? [String: Any] else { + throw ClusterWorkerProtocolError.invalid("Unknown generation mode or malformed serving features") + } + return (mode, try ClusterServingFeatures.decode(wire: object)) + }) let value = try ClusterRuntimeCapability(runtimeBinarySHA256: r.string("runtimeBinarySHA256"), adapterID: r.string("adapterID"), adapterVersion: r.int("adapterVersion"), runtimeModelID: r.string("runtimeModelID"), artifactSHA256: r.string("artifactSHA256"), configurationSHA256: r.string("configurationSHA256"), manifestSHA256: r.string("manifestSHA256"), profile: profile, profileFingerprint: r.string("profileFingerprint"), partitions: partitions, arithmeticPolicyID: r.string("arithmeticPolicyID"), arithmeticPolicySHA256: r.string("arithmeticPolicySHA256"), supportedPrefillSchedules: schedules, - supportedGenerationModes: modes,media:media,glmImages:glmImages) + supportedGenerationModes: modes,media:media,glmImages:glmImages, modeFeatures: modeFeatures) try workerRequire(try r.string("stateSemantics") == value.stateSemantics && r.int("rankCount") == value.rankCount && r.int("batchSize") == value.batchSize && r.int("maxActiveRequests") == value.maxActiveRequests diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityValidation.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityValidation.swift index 989356f953..25389ae3b2 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityValidation.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterRuntimeCapabilityValidation.swift @@ -19,6 +19,11 @@ enum ClusterRuntimeCapabilityValidation { try workerRequire(value.supportedGenerationModes.first == .pipeline && value.supportedGenerationModes == ClusterGenerationMode.allCases.filter(value.supportedGenerationModes.contains), "Missing, duplicate or unordered generation modes") + if let features = value.modeFeatures { + try workerRequire(Set(features.keys) == Set(value.supportedGenerationModes), + "Serving features must name exactly the supported generation modes") + for entry in features.values { try entry.validate() } + } let imageCandidate = adapter == .mimoV26ImageCandidate try workerRequire(imageCandidate == (value.media != nil),"Candidate adapter requires its closed media contract") if imageCandidate { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServingFeatures.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServingFeatures.swift new file mode 100644 index 0000000000..7851b1036a --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServingFeatures.swift @@ -0,0 +1,88 @@ +import Foundation + +/// What one generation mode keeps of a model's serving features as this worker +/// build runs it, declared by the adapter beside its modes +/// (`ClusterRuntimeCapability.modeFeatures`) from the facts its loads bind (a +/// load agreement without a prompt-prefix cache, a lane count it refuses above +/// one). The placement step compares modes by these and keeps no table of its +/// own: a mode is chosen only where it keeps every feature of the mode it would +/// replace (`dropped(by:)`; owner, 2026-11-01). +public struct ClusterServingFeatures: Equatable, Sendable { + public enum Media: String, CaseIterable, Sendable { case images, video } + + /// Resident prompt-prefix reuse: a prompt that starts with one served + /// before restores that prefix's state instead of prefilling it again. + public let promptPrefixReuse: Bool + /// The owner's SSD tier of that cache. + public let ssdPrefixTier: Bool + /// Decode in speculative rounds: the model's own head drafts and the + /// target verifies the window, keeping only its greedy tokens. + public let speculativeRounds: Bool + /// The widest batch-lane width a load of the mode accepts; 1 serves one + /// request at a time. + public let maximumLanes: Int + /// Media a request may carry beside text, in `Media` order. + public let requestMedia: [Media] + /// Repetition, presence and frequency penalties and logit bias, applied by + /// the product's sampler. + public let penaltiesAndLogitBias: Bool + /// Stop token IDs and stop strings. + public let stopHandling: Bool + /// Committed-token logprobs. + public let logprobs: Bool + + public static let maximumLaneWidth = 8 + + public init(promptPrefixReuse: Bool, ssdPrefixTier: Bool, speculativeRounds: Bool, maximumLanes: Int, + requestMedia: [Media] = [], penaltiesAndLogitBias: Bool = true, stopHandling: Bool = true, logprobs: Bool) { + self.promptPrefixReuse = promptPrefixReuse; self.ssdPrefixTier = ssdPrefixTier + self.speculativeRounds = speculativeRounds; self.maximumLanes = maximumLanes; self.requestMedia = requestMedia + self.penaltiesAndLogitBias = penaltiesAndLogitBias; self.stopHandling = stopHandling; self.logprobs = logprobs + } + + /// What `other` would drop of these features, in plain words and this + /// order; empty when it keeps every one. What `other` has beyond them + /// (logprobs these lack, wider lanes) is a gain and never counts. + public func dropped(by other: ClusterServingFeatures) -> [String] { + var dropped: [String] = [] + if promptPrefixReuse && !other.promptPrefixReuse { dropped.append("prompt-prefix reuse") } + if ssdPrefixTier && !other.ssdPrefixTier { dropped.append("the SSD prefix tier") } + if speculativeRounds && !other.speculativeRounds { dropped.append("speculative (MTP) rounds") } + if other.maximumLanes < maximumLanes { dropped.append("batch lanes up to \(maximumLanes) (it serves \(other.maximumLanes))") } + dropped += requestMedia.filter { !other.requestMedia.contains($0) }.map(\.rawValue) + if penaltiesAndLogitBias && !other.penaltiesAndLogitBias { dropped.append("penalties and logit bias") } + if stopHandling && !other.stopHandling { dropped.append("stop handling") } + if logprobs && !other.logprobs { dropped.append("committed-token logprobs") } + return dropped + } + + func validate() throws { + try workerRequire((1...Self.maximumLaneWidth).contains(maximumLanes) + && requestMedia == Media.allCases.filter(requestMedia.contains) && (promptPrefixReuse || !ssdPrefixTier), + "Malformed serving features") + } + + var wireObject: [String: Any] { + ["promptPrefixReuse": promptPrefixReuse, "ssdPrefixTier": ssdPrefixTier, "speculativeRounds": speculativeRounds, + "maximumLanes": maximumLanes, "requestMedia": requestMedia.map(\.rawValue), "penaltiesAndLogitBias": penaltiesAndLogitBias, + "stopHandling": stopHandling, "logprobs": logprobs] + } + + static func decode(wire object: [String: Any]) throws -> Self { + var r = WorkerObject(object) + guard let names = try r.take("requestMedia") as? [String] else { + throw ClusterWorkerProtocolError.invalid("Expected media names") + } + let requestMedia = try names.map { + guard let kind = Media(rawValue: $0) else { throw ClusterWorkerProtocolError.invalid("Unknown media kind") } + return kind + } + let value = try Self(promptPrefixReuse: r.bool("promptPrefixReuse"), ssdPrefixTier: r.bool("ssdPrefixTier"), + speculativeRounds: r.bool("speculativeRounds"), maximumLanes: r.int("maximumLanes"), requestMedia: requestMedia, + penaltiesAndLogitBias: r.bool("penaltiesAndLogitBias"), stopHandling: r.bool("stopHandling"), + logprobs: r.bool("logprobs")) + try r.finish() + try value.validate() + return value + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Generation/GLM5NextStageSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Generation/GLM5NextStageSession.swift index 560a2a2bd5..c2d250037b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Generation/GLM5NextStageSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/Generation/GLM5NextStageSession.swift @@ -107,8 +107,8 @@ final class GLM5NextStageSession { } inOperation = true defer { inOperation = false } - do { - return try MLX.withError { error in + func run() throws -> QwenLayerStageOutput { + try MLX.withError { error in func checked() throws { try error.check(); try check() guard !isFailed else { throw ProbeError("GLM stage request was invalidated") } @@ -210,6 +210,12 @@ final class GLM5NextStageSession { } return result! } + } + do { + // A decode frame encodes under the pipeline decode limits + // (`QwenLayerStageSession.decodeCommandBuffers`); prefill keeps the rank's. + guard frame.phase == .decode else { return try run() } + return try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers, run) } catch { isFailed = true throw error diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/GLM5NextTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/GLM5NextTensorParallelResidentRuntime.swift index ea5280b2ff..b1482c4ae6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/GLM5NextTensorParallelResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/GLM5NextTensorParallelResidentRuntime.swift @@ -1460,13 +1460,9 @@ public final class GLM5NextTensorParallelResidentRuntime { } } } else { - // Greedy steps are built one ahead: step k+1 is submitted before step - // k's choice is read. A sampled step is built after its token is known - // (the sampler draws at the output index with the history up to it). - let pipelined = sampler == nil - var current = choose(firstLogits, stop: 0) + // One token a step (`GLM5NextTensorParallelStepLoop`). + let current = choose(firstLogits, stop: 0) asyncEval(current) - var pending: MLXArray? func step(from selection: MLXArray, stop: Float) throws -> MLXArray { let next = selection[0 ..< 1].asType(.int32).reshaped(1, 1) let candidate = try stage.prepareForward(tokens: next, cache: cache, readout: .lastToken) @@ -1476,42 +1472,18 @@ public final class GLM5NextTensorParallelResidentRuntime { asyncEval(chosen) return chosen } - steps: for index in 0 ..< request.outputCount { - pending = nil - if pipelined, index + 1 < request.outputCount { - growPages(needed: prompt.count + index + 2) - pending = try step(from: current, stop: stopKeep) - } - // The answer to the last token arrived while this step was encoded. - if stopKeep == 0 { try readAnswer() } - let agreed = current.asArray(Float.self) - let value = try token(agreed) - let flags = [agreed[2], agreed[3]].filter { $0 > 0 } - if let slot = flags.min() { - let stop = QwenTensorParallelStopRule.stop(slot: slot) - tokens = Array(tokens.prefix(stop.keep)) - finish = stop.finish == .length ? .length : .clientStop; break - } - if stopKeep == 0 { + let steps = GLM5NextTensorParallelStepLoop(outputCount: request.outputCount, + promptCount: prompt.count, stopTokenIDs: request.stopTokenIDs, pipelined: sampler == nil, + step: { try step(from: $0, stop: $1) }, agreement: { $0.asArray(Float.self) }, evaluate: { eval($0) }, + growPages: { growPages(needed: $0) }, pagesRefused: { pagesRefused }, + stopKeep: { stopKeep }, setStopKeep: { stopKeep = $0 }, readAnswer: readAnswer, + committed: { tokens.count }, keep: { tokens = Array(tokens.prefix($0)) }, + commit: { value in try keepStepLogprobs() sampler?.commit(value) - if let end = try commit(value) { finish = end; break steps } - if localStop() { - stopKeep = Float(tokens.count) - } else if pagesRefused { - stopKeep = QwenTensorParallelStopRule.lengthStop(keep: tokens.count) - } - } - if !pipelined, index + 1 < request.outputCount { - growPages(needed: prompt.count + index + 2) - if pagesRefused, stopKeep == 0 { stopKeep = QwenTensorParallelStopRule.lengthStop(keep: tokens.count) } - pending = try step(from: current, stop: stopKeep) - } - guard let next = pending else { break } - current = next; pending = nil - } - // A step both ranks submitted is evaluated by both, so its reductions meet. - if let pending { eval(pending) } + return try commit(value) + }, localStop: localStop) + if let ended = try steps.run(first: current) { finish = ended } } // The owner answers every published token, the last one too. A stop // answer to a token the request ended at changes nothing. diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/GLM5NextTensorParallelStepLoop.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/GLM5NextTensorParallelStepLoop.swift new file mode 100644 index 0000000000..e048400a18 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GLM5Next/TensorParallel/GLM5NextTensorParallelStepLoop.swift @@ -0,0 +1,90 @@ +import DarkbloomClusterProtocol + +/// One GLM tensor-parallel request's decode on one rank, one token a step: +/// the path without a NextN layer (`GLM5NextTensorParallelResidentRuntime.mtpDepth` +/// 0); with one, every request decodes in MTP rounds. Greedy steps are built +/// one ahead: step k+1 is submitted before step k's choice is read. A sampled +/// step is built after its token is known (the sampler draws at the output +/// index with the history up to it). Each step's agreement carries both +/// ranks' tokens and stop flags (`GLM5NextTensorParallelResidentRuntime.choose`), +/// and a flag on either rank ends both after that step. A rank that stopped +/// after a step was built (rank 0 reads the owner's answer late) commits +/// nothing more, but still ends at a stop token its peer commits, as MTP +/// rounds do, so both leave after the same step; the end-of-request +/// agreement then settles each rank's count and finish +/// (`QwenTensorParallelStopRule.reconcile`). The runtime supplies the steps +/// and its request's state, so two ranks can run it without a model. +struct GLM5NextTensorParallelStepLoop { + let outputCount: Int + let promptCount: Int + let stopTokenIDs: Set + /// Greedy: each step is submitted before the previous step's choice is read. + let pipelined: Bool + /// Builds and submits the step after `selection`'s token, carrying this rank's stop flag. + let step: (_ selection: Selection, _ stop: Float) throws -> Selection + /// A step's evaluated agreement: [token rank 0, token rank 1, stop rank 0, stop rank 1]. + let agreement: (Selection) throws -> [Float] + /// Evaluates a step both ranks submitted that the loop did not read. + let evaluate: (Selection) throws -> Void + /// The request's pages, before a step that brings it to `needed` context tokens is built. + let growPages: (_ needed: Int) -> Void + let pagesRefused: () -> Bool + /// This rank's stop slot (0 while it goes on), and setting it. + let stopKeep: () -> Float + let setStopKeep: (Float) -> Void + /// Rank 0: reads the owner's answer to the last published token. + let readAnswer: () throws -> Void + /// Tokens committed on this rank, and keeping only the first `count`. + let committed: () -> Int + let keep: (_ count: Int) -> Void + /// Commits one agreed token on this rank; the request's own end at it, else nil. + let commit: (Int) throws -> ClusterWorkerFinishReason? + /// This rank stopped on its own (cancel, deadline, memory). + let localStop: () -> Bool + + /// The steps from the first token's agreement; the finish the loop + /// decided, or nil when it ran out of steps. + func run(first: Selection) throws -> ClusterWorkerFinishReason? { + var current = first, finish: ClusterWorkerFinishReason? + var pending: Selection? + steps: for index in 0 ..< outputCount { + pending = nil + if pipelined, index + 1 < outputCount { + growPages(promptCount + index + 2) + pending = try step(current, stopKeep()) + } + // The answer to the last token arrived while this step was encoded. + if stopKeep() == 0 { try readAnswer() } + let agreed = try agreement(current) + let value = try GLM5NextTensorParallelResidentRuntime.agreedToken(agreed, sampled: !pipelined) + let flags = [agreed[2], agreed[3]].filter { $0 > 0 } + if let slot = flags.min() { + let stop = QwenTensorParallelStopRule.stop(slot: slot) + keep(stop.keep) + finish = stop.finish == .length ? .length : .clientStop; break + } + if stopKeep() == 0 { + if let end = try commit(value) { finish = end; break steps } + if localStop() { + setStopKeep(Float(committed())) + } else if pagesRefused() { + setStopKeep(QwenTensorParallelStopRule.lengthStop(keep: committed())) + } + } else if stopTokenIDs.contains(value) { + // This rank's flag rides only a later step, which the peer, + // ending at this stop token, would never join. + break steps + } + if !pipelined, index + 1 < outputCount { + growPages(promptCount + index + 2) + if pagesRefused(), stopKeep() == 0 { setStopKeep(QwenTensorParallelStopRule.lengthStop(keep: committed())) } + pending = try step(current, stopKeep()) + } + guard let next = pending else { break } + current = next; pending = nil + } + // A step both ranks submitted is evaluated by both, so its reductions meet. + if let pending { try evaluate(pending) } + return finish + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSLayerStageSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSLayerStageSession.swift index 794bea380a..465cc6abeb 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSLayerStageSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSLayerStageSession.swift @@ -97,12 +97,15 @@ final class GPTOSSLayerStageSession { } catch { try fail(error) } } + /// Encodes under the pipeline decode limits (`QwenLayerStageSession.decodeCommandBuffers`). func decode(_ token: Int, offset: Int, incoming: QwenLayerStageBoundary? = nil, check: () throws -> Void) throws -> QwenLayerStageOutput { do { try requireOpen() let frame = try schedule.admitDecode(offset: offset) - return try perform(tokens: [token], frame: frame, incoming: incoming, check: check) + return try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers) { + try perform(tokens: [token], frame: frame, incoming: incoming, check: check) + } } catch { try fail(error) } } @@ -291,10 +294,12 @@ extension GPTOSSLayerStageSession { histories.append(pages) } let frontiers = sessions.map { $0.schedule.committedTokens } - let output = try GPTOSSBatchForward.decode(model: first.stage.model, head: first.stage.head, - stageIndex: first.stage.stageIndex, hiddenSize: first.hiddenSize, - vocabularySize: first.stage.vocabularySize, dtype: first.stage.residualDType, - tokens: tokens, residual: residual, histories: histories, check: check) + let output = try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers) { + try GPTOSSBatchForward.decode(model: first.stage.model, head: first.stage.head, + stageIndex: first.stage.stageIndex, hiddenSize: first.hiddenSize, + vocabularySize: first.stage.vocabularySize, dtype: first.stage.residualDType, + tokens: tokens, residual: residual, histories: histories, check: check) + } for (session, frontier) in zip(sessions, frontiers) { try session.requireFrontier(after: frontier + 1) } for (session, frame) in zip(sessions, frames) { try session.schedule.commit(frame) } if first.stage.stageIndex == 0 { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift index 5758b05c08..f09a2678b7 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift @@ -94,32 +94,39 @@ final class GPTOSSPagedKVCache: KVCache { get { gathered() } set { precondition(newValue.count == 2 && newValue[0].dim(2) > 0) - let previousOffset = offset - let previousIndex = layout.index + let previous = layout let window = maxSize pages = []; shape = nil; layout = .init(window: window) _ = update(keys: newValue[0], values: newValue[1]) if window != nil { // Like RotatingKVCache, metadata restoration supplies position // separately. Preserve the old position until it is restored. - layout.restore(count: newValue[0].dim(2), offset: max(previousOffset, newValue[0].dim(2)), - index: min(previousIndex, newValue[0].dim(2))) + layout.restore(count: newValue[0].dim(2), offset: max(previous.offset, newValue[0].dim(2)), + index: min(previous.index, newValue[0].dim(2)), wrapped: previous.wrapped) } } } + /// Sliding pages write and restore exactly the metadata the pinned SDK's + /// ring writes in the same state (`GPTOSSSlidingRing`). var metaState: [String] { get { - if let window = maxSize { return ["0", String(window), "256", String(offset), String(layout.index)] } - return [""] + guard let window = maxSize else { return [""] } + guard let metadata = GPTOSSSlidingRing.metadata(window: window, + at: .init(offset: offset, index: layout.index, wrapped: layout.wrapped)) else { + preconditionFailure("The pinned SDK writes another sliding-ring metadata layout") + } + return metadata } set { guard let window = maxSize else { precondition(newValue == [""]); return } - precondition(newValue.count == 5 && newValue[0] == "0" && Int(newValue[1]) == window - && Int(newValue[2]) == 256) - layout.restore(count: layout.count, offset: Int(newValue[3])!, index: Int(newValue[4])!) + guard let position = GPTOSSSlidingRing.position(of: newValue, window: window, rows: layout.count) else { + preconditionFailure("GPT-OSS sliding pages restore only the SDK ring's metadata for their rows") + } + layout.restore(count: layout.count, offset: position.offset, index: position.index, + wrapped: position.wrapped) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift new file mode 100644 index 0000000000..9b9ccc3250 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift @@ -0,0 +1,41 @@ +import MLXLMCommon + +/// The metadata (`RotatingKVCache.metaState`) of GPT-OSS's sliding-window +/// ring, `RotatingKVCache(maxSize: window)` (`makeSlidingWindowKVCache`), in +/// the layout the pinned SDK writes: keep, window, step, offset, write index, +/// capacity origin and whether the ring has wrapped. Writes move only the +/// offset, the index and the flag. The ring's state holds its first `index` +/// rows, or the whole window once wrapped. +enum GPTOSSSlidingRing { + struct Position: Equatable { + let offset: Int, index: Int, wrapped: Bool + } + + private static let offsetField = 3, indexField = 4, wrappedField = 6 + + /// The metadata of a ring of `window` positions at `position`; nil when a + /// fresh ring writes another layout. + static func metadata(window: Int, at position: Position) -> [String]? { + var fields = RotatingKVCache(maxSize: window).metaState + guard fields.count == 7, fields[offsetField] == "0", fields[indexField] == "0", + fields[wrappedField] == "false" else { return nil } + fields[offsetField] = String(position.offset); fields[indexField] = String(position.index) + fields[wrappedField] = String(position.wrapped) + return fields + } + + /// The position `metadata` gives a ring of `window` positions holding + /// `rows` rows; nil unless that ring writes exactly this metadata and + /// pages can continue it. Pages cap masks and trims by the offset, so an + /// unwrapped ring that has evicted rows must still hold at least + /// window - 1 rows; the SDK's trim after eviction can leave fewer. + static func position(of metadata: [String], window: Int, rows: Int) -> Position? { + guard metadata.count > wrappedField, let offset = Int(metadata[offsetField]), + let index = Int(metadata[indexField]), let wrapped = Bool(metadata[wrappedField]) else { return nil } + let position = Position(offset: offset, index: index, wrapped: wrapped) + guard metadata == Self.metadata(window: window, at: position), offset >= rows, + wrapped ? rows == window && index >= 0 && index <= rows + : index == rows && (offset == rows || rows >= window - 1) else { return nil } + return position + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift index 85968beff6..c514e925e7 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift @@ -10,6 +10,9 @@ struct GPTOSSPagedKVLayout: Equatable { private(set) var offset = 0 private(set) var count = 0 private(set) var index = 0 + /// RotatingKVCache's wrapped flag: a one-token write that rotates sets it; + /// a chunk or a trim clears it. + private(set) var wrapped = false struct Update: Equatable { /// Nil keeps the existing pages. Otherwise these old physical rows @@ -45,7 +48,7 @@ struct GPTOSSPagedKVLayout: Equatable { return kept.isEmpty ? nil : kept } let kept = ranges.reduce(0) { $0 + $1.count } - count = kept + n; index = count + count = kept + n; index = count; wrapped = false return .init(retained: ranges, writeOffset: kept, count: count) } var retained: [Range]? @@ -53,7 +56,7 @@ struct GPTOSSPagedKVLayout: Equatable { retained = [(count - window).. Int { guard isTrimmable else { return 0 } let removed = min(offset, max(0, n)) - offset -= removed; count = offset; index = offset + offset -= removed; count = offset; index = offset; wrapped = false return removed } - mutating func restore(count: Int, offset: Int, index: Int) { + mutating func restore(count: Int, offset: Int, index: Int, wrapped: Bool) { precondition(count >= 0 && offset >= count && index >= 0 && index <= count) - self.count = count; self.offset = offset; self.index = index + self.count = count; self.offset = offset; self.index = index; self.wrapped = wrapped } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift index 68910cb4d8..6fcd9c41f4 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift @@ -15,7 +15,10 @@ import Foundation /// is no recurrent state. A stage also holds one residual chunk coming or /// going, and stage 1 one vocabulary row. The workspace term is the largest /// transient a forward is known to build: one full-attention layer's score -/// matrix for a chunk against the whole history, in float32. +/// matrix for a chunk against the whole history, in float32, and never less +/// than every full-attention layer's scores for its one decode row at once (a +/// decode step's command buffers can keep the whole step in flight, +/// `QwenLayerStageSession.decodeCommandBuffers`). struct GPTOSSRequestStateBudget: Encodable, Equatable { static let activationBytes = 4, growthStep = 256 let fullAttentionLayers: Int, slidingLayers: Int @@ -61,7 +64,9 @@ struct GPTOSSRequestStateBudget: Encodable, Equatable { let slidingState = try product([slidingPerLayer, sliding]) let boundary = try allowance(try product([chunkSize, spec.hidden, activationBytes]), 2) let row = rank == 1 ? try allowance(try product([spec.vocabulary, 4]), 2) : 0 - let workspace = full == 0 ? 0 : try allowance(try product([spec.queryHeads, chunkSize, capacity, 4]), 1) + // GPT-OSS decodes one row a request (no verify window): one per full-attention layer. + let scoreRows = max(chunkSize, full) + let workspace = full == 0 ? 0 : try allowance(try product([spec.queryHeads, scoreRows, capacity, 4]), 1) return .init(fullAttentionLayers: full, slidingLayers: sliding, fullAttentionStateBytes: fullState, slidingStateBytes: slidingState, boundaryBytes: boundary, rowBytes: row, workspaceBytes: workspace, reservedBytes: try sum([fullState, slidingState, boundary, row, workspace])) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift index ac6b0d5249..55aa0e6656 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4PlacementFamily.swift @@ -12,11 +12,19 @@ import Foundation struct Gemma4PlacementFamily: ClusterPlacementFamily { let specification: Gemma4RegisteredSpecification let profile: QwenLayerStageGenerationProfile + /// The tensor-parallel plan (`Gemma4TensorParallelPlan`, two ranks by + /// heads and expert channels) when the resident row lists the mode. + let tensorParallel: Gemma4TensorParallelPlan? + /// The native request reservation of a tensor-parallel rank + /// (`Gemma4TensorParallelRequestBudget`), set where the allocator's bound + /// is known (`ClusterPlacementLayouts.layout`); nil in metadata-only layouts. + var tensorParallelRequestAllowance: ClusterTensorParallelRequestAllowance? /// The row a manifest names, or, without one, the first row of this /// configuration: the two 8-bit catalog entries are one artifact (one /// configuration, aggregate and inventory) and lay out identically. init(configuration: Data, manifest: Data?) throws { + let specification: Gemma4RegisteredSpecification if let manifest { specification = try Gemma4RegisteredSpecification.registered(configuration: configuration, manifest: manifest) } else { @@ -26,8 +34,16 @@ struct Gemma4PlacementFamily: ClusterPlacementFamily { } specification = row } - _ = try Gemma4StageGeometry.decode(configuration, defaultQuantizationBits: specification.defaultQuantizationBits) + try self.init(specification: specification, + decoded: Gemma4StageGeometry.decode(configuration, defaultQuantizationBits: specification.defaultQuantizationBits)) + } + + /// The row's family over a configuration already held to its geometry. + init(specification: Gemma4RegisteredSpecification, decoded: Gemma4StageGeometry.Decoded) throws { + self.specification = specification profile = try Gemma4ResidentAdapterDefinition.profile(specification: specification) + tensorParallel = Gemma4ResidentAdapterDefinition.supportedGenerationModes.contains(.tensorParallel) + ? try Gemma4TensorParallelPlan(configuration: decoded.root) : nil } var runtimeModelID: String { specification.model.rawValue } @@ -85,6 +101,16 @@ struct Gemma4PlacementFamily: ClusterPlacementFamily { func layerKind(_ layer: Int) -> String { Gemma4StageGeometry.kind(globalLayerIndex: layer) } + /// A decode step reads 8 of every layer's 128 expert banks; the router and + /// the dense MLP beside them are read whole. + var expertRouting: ClusterExpertRouting? { + ClusterExpertRouting(selected: Gemma4StageGeometry.expertsPerToken, experts: Gemma4StageGeometry.routedExperts) + } + + func isRoutedExpert(storedTensor name: String) -> Bool { + layer(ofStoredTensor: name) != nil && name.contains(".experts.switch_glu.") + } + /// Keys and values in bfloat16: per token on a full-attention layer; on a /// sliding layer a ring of the window, allocated whole, and the view one /// frame attends over (`Gemma4StateBudget`). @@ -116,4 +142,50 @@ struct Gemma4PlacementFamily: ClusterPlacementFamily { throw ProbeError("The artifact's tensor headers are not the registered Gemma 4 inventory") } } + + // MARK: - Tensor parallel + + /// `Gemma4TensorParallelResidentRuntime`'s plan: each layer sums its + /// attention partial and one packed feed-forward collective (the dense + /// row and the 8 selected experts' rows, FP32), and each step the + /// vocabulary-split selection once. Each rank keeps its own KV heads. + /// Equal shares only (overlapping zero-padded channel splits). Chosen + /// only where predicted faster than the pipeline + /// (`ClusterTensorParallelChoice.fastest`): on big Macs one Gemma step is + /// mostly a per-token floor that two ranks do not halve, while 61 sums + /// cross the link (`docs/architecture/inference.md`). + var tensorParallelPlan: ClusterTensorParallelFamilyPlan? { + tensorParallel.map { plan in + ClusterTensorParallelFamilyPlan(plan: Gemma4TensorParallelPlan.name, ranks: [plan.size], + reductionsPerLayer: plan.reductionsPerLayer, reductionsPerStep: plan.reductionsPerStep, + partialBytesPerToken: plan.feedForwardPartialBytesPerToken, + layerPartialBytesPerToken: plan.layerPartialBytesPerToken, stateDividesByHeads: true, + requestAllowance: tensorParallelRequestAllowance, choice: .fastest) + } + } + + /// The plan's cut (the same on both ranks): replicated, or rows, input + /// columns or expert channels divided. The tied embedding is listed at + /// both ends of the layout (the lookup and the head); a rank holds it + /// once, whole, and its head reads its own half of the vocabulary rows, + /// so each end counts as divided: two halves are the one copy a rank holds. + func tensorParallelCut(ofStoredTensor name: String) -> ClusterTensorParallelTensorCut? { + guard let plan = tensorParallel else { return nil } + if loadsAtBothEnds(storedTensor: name) { return .divided } + guard let cut = try? plan.cut(key: name, rank: 0) else { return nil } + return cut == .replicate ? .replicated : .divided + } + + /// Both ranks store the down projection's middle quantization group and + /// pad their gate and up rows with the other rank's half of it as zeros + /// (`Gemma4TensorParallelPlan.ChannelSplit`): a rank's share of such a + /// tensor is more than half, by these bytes. + func tensorParallelOverlapBytes(of tensor: ClusterPlacementStoredTensor, loadedBytes: Int) -> Int { + guard let plan = tensorParallel, layer(ofStoredTensor: tensor.name) != nil, + let cut = try? plan.cut(key: tensor.name, rank: 0), + let local = try? plan.localShape(key: tensor.name, shape: tensor.shape, cut: cut) else { return 0 } + let elements = tensor.shape.reduce(1, *), held = local.reduce(1, *) + guard elements > 0, tensor.byteCount % elements == 0, loadedBytes == tensor.byteCount else { return 0 } + return max(0, 2 * held * (tensor.byteCount / elements) - tensor.byteCount) + } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift index 5b395130b3..e448671c42 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Metadata/Gemma4StageGeometry.swift @@ -10,6 +10,8 @@ enum Gemma4StageGeometry { static let slidingWindow = 1024 static let slidingKVHeads = 8, slidingHeadDimension = 256 static let fullKVHeads = 2, fullHeadDimension = 512 + /// Every layer routes each token to 8 of its 128 experts. + static let routedExperts = 128, expertsPerToken = 8 /// Five sliding-window layers, then one full-attention layer, five times. static let fullAttentionInterval = 6 static let slidingKind = "sliding_attention", fullKind = "full_attention" @@ -44,7 +46,8 @@ enum Gemma4StageGeometry { throw ProbeError("Gemma stage metadata requires the original text wrapper") } let integers = ["num_hidden_layers": layerCount, "hidden_size": hiddenSize, "vocab_size": vocabularySize, - "intermediate_size": 2112, "moe_intermediate_size": 704, "num_experts": 128, "top_k_experts": 8, + "intermediate_size": 2112, "moe_intermediate_size": 704, "num_experts": routedExperts, + "top_k_experts": expertsPerToken, "sliding_window": slidingWindow, "num_attention_heads": queryHeads, "num_key_value_heads": slidingKVHeads, "num_global_key_value_heads": fullKVHeads, "head_dim": slidingHeadDimension, "global_head_dim": fullHeadDimension, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift index aef4b781cb..ae076422e2 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentAdapterDefinition.swift @@ -7,9 +7,26 @@ import Foundation enum Gemma4ResidentAdapterDefinition { static let supportedCuts = Gemma4LayerStagePlanning.supportedCuts static let supportedPrefillSchedules: [ClusterPrefillSchedule] = [.serial, .oneChunkLookahead] - /// The pipeline only. Handing a sliding layer's window from one rank to the - /// other is not built, so the phase split is not advertised. - static let supportedGenerationModes: [ClusterGenerationMode] = [.pipeline] + /// The pipeline, and tensor parallel (`Gemma4TensorParallelResidentRuntime`). + /// Handing a sliding layer's window from one rank to the other is not + /// built, so the phase split is not advertised. The planner chooses tensor + /// parallel only where it predicts it faster than the pipeline + /// (`Gemma4PlacementFamily.tensorParallelPlan`, `ClusterTensorParallelChoice.fastest`). + static let supportedGenerationModes: [ClusterGenerationMode] = [.pipeline, .tensorParallel] + /// Tensor parallel keeps prompt prefixes as the pipeline does, resident and on the owner's SSD tier + /// (`Gemma4TensorParallelPrefix`); its load agreement binds this (`Gemma4TensorParallelLoadAgreement.prefixCache`). + static let tensorParallelKeepsPromptPrefixes = true + /// What each mode keeps (`ClusterServingFeatures`), as this build runs it: both modes keep prompt prefixes resident + /// and on the owner's SSD tier (the pipeline's stage owner through `QwenStagePrefixCache`, tensor parallel through + /// `Gemma4TensorParallelPrefix`); tensor parallel adds logprobs. Both serve up to `QwenBatchWire.maximumLanes` + /// lanes; neither decodes in speculative rounds or takes media. + static let servingFeatures: [ClusterGenerationMode: ClusterServingFeatures] = [ + .pipeline: .init(promptPrefixReuse: true, ssdPrefixTier: true, speculativeRounds: false, + maximumLanes: QwenBatchWire.maximumLanes, logprobs: false), + .tensorParallel: .init(promptPrefixReuse: tensorParallelKeepsPromptPrefixes, + ssdPrefixTier: tensorParallelKeepsPromptPrefixes, speculativeRounds: false, + maximumLanes: QwenBatchWire.maximumLanes, logprobs: true), + ] static func profileID(_ model: Gemma4RegisteredModel) -> String { model.rawValue + "_greedy_generation_v1" } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentCapabilityMetadata.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentCapabilityMetadata.swift index 4d3c2d1bc2..98653d45fc 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentCapabilityMetadata.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentCapabilityMetadata.swift @@ -41,6 +41,7 @@ public enum Gemma4ResidentCapabilityMetadata { arithmeticPolicyID: Gemma4ArithmeticEnvironment.contract, arithmeticPolicySHA256: sha256(try canonicalJSONData(arithmetic)), supportedPrefillSchedules: Gemma4ResidentAdapterDefinition.supportedPrefillSchedules, - supportedGenerationModes: Gemma4ResidentAdapterDefinition.supportedGenerationModes) + supportedGenerationModes: Gemma4ResidentAdapterDefinition.supportedGenerationModes, + modeFeatures: Gemma4ResidentAdapterDefinition.servingFeatures) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentFamily.swift index fdd057af55..6aeed4461a 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resident/Gemma4ResidentFamily.swift @@ -47,6 +47,7 @@ extension Gemma4ResidentLoadedStage: LayerStageResidentStage { } func requestAllowance(plan: QwenLayerStagePlan, rank: Int, maximumTokens: Int, chunkSize: Int, + decode: LayerStageDecodeShape, bound: (Int) throws -> Int) throws -> QwenResidentRequestAllowance { guard plan.stages.count == 2, (0...1).contains(rank), loaded.plan.fingerprint == plan.fingerprint else { throw ProbeError("Resident request allowance requires this stage's admitted two-stage Plan") @@ -58,13 +59,15 @@ extension Gemma4ResidentLoadedStage: LayerStageResidentStage { } let state = try budget.allowance(bound: bound) // One prefill frame's attention transient at this context, as the - // dense allowance adds it, so a context the gate admits is one a frame runs in. + // dense allowance adds it, so a context the gate admits is one a frame + // runs in; or a decode step's on every layer it runs, when larger. let logical = try Gemma4PrefillTransient.bytes(layers: plan.stages[rank].layers, chunkTokens: chunkSize, - contextTokens: maximumTokens) + contextTokens: maximumTokens, decodeRows: decode.rows, + decodeLayers: decode.stages(of: plan, rank: rank).flatMap(\.layers)) let transient = logical == 0 ? 0 : try bound(logical) return .init(stateBytes: state.stateBytes, fusionBytes: state.fusionBytes, reservedBytes: try QwenLongPrefillCheckedBytes.sum([state.reservedBytes, transient]), - transientBytes: transient, contextTokens: maximumTokens) + transientBytes: transient, contextTokens: maximumTokens, decode: decode) } func diagnosticResources(plan: QwenLayerStagePlan, request: QwenLayerStageGenerationRequest, rank: Int, @@ -84,7 +87,7 @@ extension Gemma4ResidentLoadedStage: LayerStageResidentStage { // A byte-only allowance is not a permit: rederive the exact request with // the actual allocator, then require the owner's reservation to match. let actual = try self.requestAllowance(plan: plan, rank: rank, maximumTokens: request.maximumTokens, - chunkSize: min(request.chunkSize, request.promptCount), + chunkSize: min(request.chunkSize, request.promptCount), decode: requestAllowance.decode, bound: QwenResidentResourceEnvironment.allocationBound) guard actual.stateBytes == requestAllowance.stateBytes, actual.fusionBytes == requestAllowance.fusionBytes, actual.reservedBytes == requestAllowance.reservedBytes else { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4StateBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4StateBudget.swift index bf1d66e25c..dcb26b8f77 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4StateBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4StateBudget.swift @@ -2,11 +2,15 @@ import DarkbloomClusterProtocol import Foundation /// The named storage of one request on the registered Gemma 4 26B geometry, in -/// logical bytes. Either rank is charged the whole model's state, as the -/// registered Qwen allowance charges it: a conservative ledger of named arrays, -/// not a whole-process peak. +/// logical bytes. Either pipeline rank is charged the whole model's state, as +/// the registered Qwen allowance charges it: a conservative ledger of named +/// arrays, not a whole-process peak. A tensor-parallel rank (`ranks` 2) keeps +/// only its own KV heads of every layer (4 sliding, 1 full), and the residual +/// rows and logits whole. struct Gemma4StateBudget: Equatable { let maximumTokens: Int, chunkSize: Int + /// The ranks the KV heads are divided among: 1 for a pipeline stage. + let ranks: Int let fullLayers: Int, slidingLayers: Int /// Keys or values of one full-attention layer at the request's capacity. let fullKVBytes: Int @@ -22,17 +26,19 @@ struct Gemma4StateBudget: Equatable { let largestSingleHostStateComponentBytes: Int let stateAndBoundaryBytes: Int - static func estimate(maximumTokens: Int, chunkSize: Int) throws -> Self { - guard (1...ClusterWorkerLimits.contextTokens).contains(maximumTokens), (1...512).contains(chunkSize) else { - throw ProbeError("Gemma state budget requires bounded tokens and chunk") + static func estimate(maximumTokens: Int, chunkSize: Int, ranks: Int = 1) throws -> Self { + guard (1...ClusterWorkerLimits.contextTokens).contains(maximumTokens), (1...512).contains(chunkSize), + [1, 2].contains(ranks), Gemma4StageGeometry.fullKVHeads % ranks == 0, + Gemma4StageGeometry.slidingKVHeads % ranks == 0 else { + throw ProbeError("Gemma state budget requires bounded tokens, chunk and ranks") } let product = QwenLongPrefillCheckedBytes.product, sum = QwenLongPrefillCheckedBytes.sum let layers = Gemma4StageGeometry.layerCount let full = layers / Gemma4StageGeometry.fullAttentionInterval, sliding = layers - full let elementBytes = 2 - let fullKV = try product([maximumTokens, Gemma4StageGeometry.fullKVHeads, + let fullKV = try product([maximumTokens, Gemma4StageGeometry.fullKVHeads / ranks, Gemma4StageGeometry.fullHeadDimension, elementBytes]) - let slidingRow = try product([Gemma4StageGeometry.slidingKVHeads, + let slidingRow = try product([Gemma4StageGeometry.slidingKVHeads / ranks, Gemma4StageGeometry.slidingHeadDimension, elementBytes]) let ring = try product([Gemma4StageGeometry.slidingWindow, slidingRow]) let view = try product([Gemma4StageGeometry.slidingWindow - 1 + chunkSize, slidingRow]) @@ -41,7 +47,7 @@ struct Gemma4StateBudget: Equatable { let total = try sum([product([2, full, fullKV]), product([2, sliding, ring]), product([2, sliding, view]), product([4, layers]), max(fullKV, ring), product([2, boundary]), product([2, logits])]) - return .init(maximumTokens: maximumTokens, chunkSize: chunkSize, fullLayers: full, slidingLayers: sliding, + return .init(maximumTokens: maximumTokens, chunkSize: chunkSize, ranks: ranks, fullLayers: full, slidingLayers: sliding, fullKVBytes: fullKV, ringKVBytes: ring, slidingViewKVBytes: view, boundaryBytes: boundary, logitsBytes: logits, largestSingleHostStateComponentBytes: max(fullKV, ring), stateAndBoundaryBytes: total) @@ -86,21 +92,39 @@ struct Gemma4ResidentResourceCeilings: Equatable { /// planner prices it beside the KV, oMLX U#3651). Both head dimensions (512 on /// a full layer, 256 on a sliding one) take MLX's unfused path, so a frame /// materializes float32 scores beside a float32 output: over the whole context -/// on a full layer, over the window and the frame on a sliding one. Layers run -/// one after another, so the stage's transient is its largest layer's. +/// on a full layer, over the window and the frame on a sliding one. Prefill +/// layers run one after another under the rank's command-buffer limits, so the +/// frame's transient is its largest layer's. A decode step's command buffers +/// (`QwenLayerStageSession.decodeCommandBuffers`) can keep every layer's +/// temporaries alive at once: `decodeRows` a layer over each of `decodeLayers`, +/// added up, priced the same way, and the larger of the two is charged. enum Gemma4PrefillTransient { - static func bytes(layers: [QwenLayerStagePlan.Layer], chunkTokens: Int, contextTokens: Int) throws -> Int { + static func bytes(layers: [QwenLayerStagePlan.Layer], chunkTokens: Int, contextTokens: Int, + decodeRows: Int = 0, decodeLayers: [QwenLayerStagePlan.Layer] = []) throws -> Int { + try bytes(fullAttention: layers.map { $0.kind == Gemma4StageGeometry.fullKind }, + queryHeads: Gemma4StageGeometry.queryHeads, chunkTokens: chunkTokens, contextTokens: contextTokens, + decodeRows: decodeRows, decodeFullAttention: decodeLayers.map { $0.kind == Gemma4StageGeometry.fullKind }) + } + + /// The same over layers of these kinds with `queryHeads` query heads each + /// (a tensor-parallel rank's own half of them). A decode step can keep + /// every layer's temporaries alive at once: `decodeRows` a layer over each + /// of `decodeFullAttention`'s layers, added up, priced the same way, and + /// the larger of the two is charged. + static func bytes(fullAttention: [Bool], queryHeads: Int, chunkTokens: Int, contextTokens: Int, + decodeRows: Int = 0, decodeFullAttention: [Bool] = []) throws -> Int { typealias G = Gemma4StageGeometry let product = QwenLongPrefillCheckedBytes.product, sum = QwenLongPrefillCheckedBytes.sum - let queries = min(chunkTokens, contextTokens) - var largest = 0 - for layer in layers { - let full = layer.kind == G.fullKind + func transient(full: Bool, queries: Int) throws -> Int { let width = full ? G.fullHeadDimension : G.slidingHeadDimension - let keys = full ? contextTokens : min(contextTokens, G.slidingWindow - 1 + chunkTokens) - let value = try sum([product([G.queryHeads, queries, keys, 4]), product([G.queryHeads, queries, width, 4])]) - largest = max(largest, value) + let keys = full ? contextTokens : min(contextTokens, G.slidingWindow - 1 + queries) + return try sum([product([queryHeads, queries, keys, 4]), product([queryHeads, queries, width, 4])]) } - return largest + let queries = min(chunkTokens, contextTokens) + var largest = 0 + for full in fullAttention { largest = max(largest, try transient(full: full, queries: queries)) } + guard decodeRows > 0 else { return largest } + let decode = try sum(decodeFullAttention.map { try transient(full: $0, queries: decodeRows) }) + return max(largest, decode) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift new file mode 100644 index 0000000000..5764dc0e54 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/Resources/Gemma4TensorParallelRequestBudget.swift @@ -0,0 +1,129 @@ +import DarkbloomClusterPlacement +import Foundation + +/// What a Gemma 4 tensor-parallel rank holds beside its weights, as its LOAD +/// and request gates charge it (`Gemma4TensorParallelResidentRuntime`) and the +/// planner quotes it (`ClusterTensorParallelFamilyPlan.requestAllowance`). +/// Every array is charged at the allocator's bound. +/// +/// Per request (`requestBytes`, what each reservation or lane charges at its +/// own context): this rank's own KV heads of every layer (`Gemma4StateBudget` +/// at two ranks), the attention transient over its own 8 query heads +/// (`Gemma4PrefillTransient`), the FP32 partials (the attention row; the +/// dense row and the 8 selected experts' rows, and the packed copy of them +/// the collective carries), three float32 rows of the whole vocabulary (the +/// row a sampled step gathers, the split head's half, the top-k) and its +/// prompt-prefix capture at its deepest boundary (`prefixCaptureBytes`: its +/// own heads' full rows for its prompt, the profile's longest in the LOAD +/// quote, and one sliding window of every sliding layer). +/// +/// The transient and the partials are priced at one prompt chunk, or at one +/// decode row on every layer where that is more: a decode step is submitted +/// layer by layer (`Gemma4TensorParallelModel.decodeLayerStride`) in +/// 100-operation command buffers (`Gemma4TensorParallelModel.decodeCommandBuffers`), +/// so several layers' temporaries are alive at once. Only requests shorter +/// than a step's layers pay more; the LOAD quote's 512-token chunk covers a step. +/// +/// Once per rank (`rankBytes`): the conservative activation floor until +/// hardware measures one for a Gemma tensor-parallel rank (5.5 GiB, the +/// provider's default reserve, as `GLM5NextServingResources` charges GLM's), +/// the freed-buffer cache the ready rank keeps and eight sealed frames of the +/// largest collective (`ClusterTensorParallelRequestAllowance`). No prefill is +/// micro-batched, so prefill adds no buffer beyond these. +/// +/// The prompt-prefix memory tier is not charged: as the pipeline's, its +/// budget is half the room the load measures beside this charge +/// (`QwenStagePrefixCache.budget(roomBytes:)`), and its entries give way +/// before a reservation, a lane or a running request is refused for memory. +struct Gemma4TensorParallelRequestBudget: Equatable { + static let ranks = 2 + /// `UnifiedMemoryCap.defaultActivationReserveBytes`: 5.5 GiB. A measured + /// constant replaces it once a pair measures a rank's peak. + static let activationFloorBytes = 11 * 1024 * 1024 * 1024 / 2 + /// `Gemma4TensorParallelResidentRuntime.freedBufferCacheBytes`: half the + /// allocator headroom, as Qwen tensor parallel keeps. + static var freedBufferCacheBytes: Int { + QwenTensorParallelLaunch.freedBufferCacheBytes(allocatorHeadroomBytes: QwenDenseStageLoadPolicy.allocatorHeadroomBytes) + } + /// FP32 bytes per token of the largest collective: the dense and 8 expert rows. + static let maximumPartialBytesPerToken = (Gemma4StageGeometry.expertsPerToken + 1) * Gemma4StageGeometry.hiddenSize * 4 + + let contextTokens: Int + let chunkTokens: Int + let stateBytes: Int + let transientBytes: Int + let partialBytes: Int + let logitsBytes: Int + /// The request's prompt-prefix capture at its deepest boundary. + let prefixCaptureBytes: Int + let allowance: ClusterTensorParallelRequestAllowance + + /// What one request of `contextTokens` reserves on a rank. + var requestBytes: Int { stateBytes + transientBytes + partialBytes + logitsBytes + prefixCaptureBytes } + /// What a rank holds once beside every request it serves. + var rankBytes: Int { Self.activationFloorBytes + Self.freedBufferCacheBytes + allowance.collectiveScratchBytes } + + /// One prefix capture of a prompt of `promptTokens` at the allocator's + /// bound: this rank's full-attention rows (keys and values, every token) + /// and one window of every sliding layer, its own heads. + static func prefixCaptureBytes(promptTokens: Int, allocationBound: (Int) throws -> Int) throws -> Int { + typealias G = Gemma4StageGeometry + let product = QwenLongPrefillCheckedBytes.product + guard promptTokens > 0 else { return 0 } + let layers = (0 ..< G.layerCount).map(G.isFullAttention(globalLayerIndex:)) + let full = layers.filter { $0 }.count, sliding = layers.count - full + func bound(_ logical: Int, count: Int) throws -> Int { + let allocated = try allocationBound(logical) + guard logical > 0, allocated >= logical else { throw ProbeError("Gemma tensor-parallel prefix allocator bound is invalid") } + return try product([allocated, count]) + } + let rows = try product([promptTokens, G.fullKVHeads / ranks, G.fullHeadDimension, 2]) + let window = try product([min(promptTokens, G.slidingWindow), G.slidingKVHeads / ranks, G.slidingHeadDimension, 2]) + return try QwenLongPrefillCheckedBytes.sum([bound(rows, count: 2 * full), bound(window, count: 2 * sliding)]) + } + + /// `promptTokens`: the prompt whose capture is charged (a request's own, + /// or the profile's longest in the LOAD quote), at most `contextTokens - 1`; + /// nil: `contextTokens - 1`. `keepsPrefixes` false charges no prefix + /// capture (the load's cache off, or the request's). + static func derive(contextTokens: Int, chunkTokens: Int, promptTokens: Int? = nil, keepsPrefixes: Bool = true, + allocationBound: (Int) throws -> Int) throws -> Self { + typealias G = Gemma4StageGeometry + let sum = QwenLongPrefillCheckedBytes.sum, product = QwenLongPrefillCheckedBytes.product + let chunk = min(contextTokens, chunkTokens) + func bound(_ logical: Int, count: Int = 1) throws -> Int { + let allocated = try allocationBound(logical) + guard logical > 0, allocated >= logical, count >= 0 else { + throw ProbeError("Gemma tensor-parallel request allocator bound is invalid") + } + return try product([allocated, count]) + } + let prompt = min(promptTokens ?? contextTokens - 1, contextTokens - 1) + let capture = keepsPrefixes ? try prefixCaptureBytes(promptTokens: max(1, prompt), allocationBound: allocationBound) : 0 + let b = try Gemma4StateBudget.estimate(maximumTokens: contextTokens, chunkSize: chunk, ranks: ranks) + let layers = b.fullLayers + b.slidingLayers + let state = try sum([bound(b.fullKVBytes, count: 2 * b.fullLayers), bound(b.ringKVBytes, count: 2 * b.slidingLayers), + bound(b.slidingViewKVBytes, count: 2 * b.slidingLayers), bound(4, count: layers), + bound(b.largestSingleHostStateComponentBytes), bound(b.boundaryBytes, count: 2)]) + let kinds = (0.. MLXArray { + let flag = MLXArray([stop]) + guard gathersRow, let sampler else { + let chosen = selection.greedy(logits, carrying: flag) + return concatenated([chosen.token.asType(.float32), chosen.flags, chosen.maximum], axis: 0) + } + let row = selection.gather(logits) + let local = rank == 0 ? sampler.sample(row) : argMax(row, axis: -1) + let slots = selection.exchange(concatenated([local.asType(.float32).reshaped(1), flag], axis: 0)) + return concatenated([slots[0 ..< 1]] + (0 ..< ranks).map { slots[(2 * $0 + 1) ..< (2 * $0 + 2)] }, axis: 0) + } + + /// The agreed token, every rank's flag and (greedy only) the token's logit + /// of an evaluated `build`. + func read(_ agreed: MLXArray) throws -> (token: Int, flags: [Float], maximum: Float?) { + let values = agreed.asArray(Float.self) + guard values.count == 1 + ranks + (gathersRow ? 0 : 1), let token = values.first, token >= 0, + token == token.rounded(), Int(token) < selection.vocabularySize else { + throw ProbeError("Gemma tensor-parallel selection has a wrong shape or token") + } + return (Int(token), Array(values[1 ... ranks]), gathersRow ? nil : values[ranks + 1]) + } + + /// A greedy step's logprobs (`count` alternatives) from the vocabulary- + /// split top-k gather: one collective on every rank, evaluated now. The + /// greedy `token`'s logit is the row's `maximum` (agreed with it), so its + /// logprob is the gather's first even when an exactly tied token leads + /// the gather: which of a rank's tied IDs `topK` keeps is the partition's + /// order, not the argmax's. Every rank holds the same gather, token and + /// maximum, so a refusal ends both ranks alike. + func logprobs(_ logits: MLXArray, token: Int, maximum: Float?, count: Int) throws -> ClusterWorkerTokenLogprobs { + let top = try selection.topK(logits, count: count) + guard let maximum, top.logits.first == maximum, + top.tokenIDs.firstIndex(of: token).map({ top.logits[$0] == maximum }) ?? true else { + throw ProbeError("Gemma tensor-parallel logprobs do not lead with the greedy token's logit") + } + return .init(logprob: top.logprobs[0], + top: zip(top.tokenIDs, top.logprobs).map { ClusterWorkerTokenLogprobs.Alternative(tokenID: $0, logprob: $1) }) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift new file mode 100644 index 0000000000..5101cbe23d --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLanes.swift @@ -0,0 +1,376 @@ +import DarkbloomClusterProtocol +import Foundation +import MLX + +struct Gemma4TensorParallelLaneReservation: QwenTensorParallelBatchReservation { + let request: QwenLayerStageGenerationRequest + let deadline: UInt64 + /// The lane's own charge at its context, with its own prompt's prefix + /// capture (`Gemma4TensorParallelResidentRuntime.prefixCharge`). + let laneStateBytes: Int + /// What its prefix capture may hold (0: none). + var prefixCaptureLimit = 0 + var joinable: Bool { true } +} + +/// One batch lane: a request's paged session and the frames it has run, +/// on the request's own chunk grid (the solo path's), from a restored +/// prefix's boundary when both ranks restored one. +final class Gemma4TensorParallelLane: QwenTensorParallelBatchLane { + let session: Gemma4TensorParallelPagedSession + let request: QwenLayerStageGenerationRequest + private var schedule: QwenLayerStageGenerationSchedule + var pendingLogprobs: ClusterWorkerTokenLogprobs? + var reusedPrefixTokens: Int { session.reusedPrefixTokens } + /// The boundaries its capture kept, once both ranks retired it cleanly. + var storedPrefixFrontiers: [Int] = [] + + init(session: Gemma4TensorParallelPagedSession, request: QwenLayerStageGenerationRequest) throws { + self.session = session + self.request = session.reusedPrefixTokens > 0 + ? try request.planned(reusedPrefix: session.reusedPrefixTokens, splitFinalToken: false) : request + schedule = QwenLayerStageGenerationSchedule(request: self.request) + } + + var nextFrame: QwenLayerStageFrame? { + guard !session.retired else { return nil } + return try? request.frame(sequence: schedule.nextSequence) + } + var committedTokens: Int { session.committedTokens } + var isClosed: Bool { session.retired } + + /// One prompt frame; the frame that ends the prompt returns its logits. + func prefill(_ frame: QwenLayerStageFrame, check: () throws -> Void) throws -> MLXArray? { + let admitted = try schedule.admitPrefill(count: frame.tokenCount, offset: frame.tokenOffset, + final: frame.finalPromptChunk) + let result = try session.prefill(request.promptTokenIDs, + range: admitted.tokenOffset ..< admitted.tokenOffset + admitted.tokenCount, check: check) { $0 } + try schedule.commit(admitted) + return result?.logits + } + + func admitDecode() throws -> QwenLayerStageFrame { try schedule.admitDecode(offset: session.committedTokens) } + func commit(_ frame: QwenLayerStageFrame) throws { try schedule.commit(frame) } + + /// Checks a clean end against the frames run (the schedule is not reused). + func finish(_ reason: QwenLayerStageGenerationFinishReason, selected: Int, last: Int) throws { + var copy = schedule + try copy.finish(reason, selectedTokenCount: selected, lastTokenID: last) + } +} + +/// The batch driver's native adapter for Gemma 4 tensor parallel +/// (`QwenTensorParallelBatchDriver`: joins, stops, cancellations, deadlines +/// and retirements cross in its own bounded exchange). Every request owns +/// its paged history on the rank's host; a decode step runs every decoding +/// lane in one forward (`Gemma4TensorParallelPagedSession.decode`), each row +/// bit for bit its request's own step, and its tokens as the solo path +/// chooses them: the split argmax for greedy rows; with a row that samples, +/// every row gathered whole and rank 0's draws (the product's sampler); +/// greedy logprobs from the split top-k gather, sampled ones from the draw. +final class Gemma4TensorParallelBatchExecutor: QwenTensorParallelBatchExecutor { + typealias Lane = Gemma4TensorParallelLane + let rank: Int + private let model: Gemma4TensorParallelModel + private let host: CBv2StageKVHost + private let reduction: any QwenTensorParallelReduction + /// Both ranks agree they were given this request (and this load) before + /// its history is opened. + private let agree: (QwenLayerStageGenerationRequest, () throws -> Void) throws -> Void + private let completedDecode: (Int) -> Void + /// This rank's prompt prefixes; nil keeps none (oracles). + private let prefix: Gemma4TensorParallelPrefix? + + init(model: Gemma4TensorParallelModel, host: CBv2StageKVHost, reduction: any QwenTensorParallelReduction, + prefix: Gemma4TensorParallelPrefix? = nil, + agree: @escaping (QwenLayerStageGenerationRequest, () throws -> Void) throws -> Void, + completedDecode: @escaping (Int) -> Void = { _ in }) throws { + guard case .shard(let rank) = model.role, rank == reduction.rank, reduction.size == model.plan.size, + model.plan.vocabularySize < (1 << 24) else { + throw ProbeError("Gemma tensor-parallel batch executor has a mismatched shard or group") + } + self.rank = rank; self.model = model; self.host = host; self.reduction = reduction + self.prefix = prefix; self.agree = agree; self.completedDecode = completedDecode + } + + func exchange(_ words: [Float], check: () throws -> Void) throws -> [Float] { + try check() + let result = reduction.allSum(MLXArray(words)); eval(result); try check() + guard result.shape == [words.count], result.dtype == .float32 else { + throw ProbeError("Gemma tensor-parallel batch control reduction changed shape or dtype") + } + let output = result.asArray(Float.self); try check() + guard output.allSatisfy(\.isFinite) else { throw ProbeError("Gemma tensor-parallel batch control reduction is not finite") } + return output + } + + /// An unopened reservation holds no native state. + func discard(_ reservation: Reservation) throws {} + + /// Both ranks agree on the request, then (with prompt prefixes kept) vote + /// its prefix and restore it or neither does (`Gemma4TensorParallelPrefix.open`). + func open(_ reservation: Reservation, check: () throws -> Void) throws -> Lane { + let request = reservation.request + try agree(request, check) + try check() + guard let prefix else { + return try Lane(session: try .init(model: model, host: host, promptCount: request.promptCount, + outputCount: request.outputCount), request: request) + } + let limit = (reservation as? Gemma4TensorParallelLaneReservation)?.prefixCaptureLimit ?? 0 + let session = try prefix.open(request, model: model, host: host, group: reduction, captureLimit: limit) + do { return try Lane(session: session, request: request) } catch { + try? session.retire(failed: true) + throw error + } + } + + /// Both ranks retired the lane: a clean one's capture becomes reusable. + func confirmedRetirement(_ lane: Lane, clean: Bool) throws { + guard let capture = lane.session.prefixCapture else { return } + lane.session.prefixCapture = nil + guard clean, let prefix, let scopes = prefix.scopes(lane.request) else { capture.discard(); return } + lane.storedPrefixFrontiers = prefix.store(capture, request: lane.request, scopes: scopes, rank: rank) + } + + func prefill(_ lane: Lane, frame: QwenLayerStageFrame, check: () throws -> Void) throws -> Int? { + guard lane.nextFrame == frame, frame.phase == .prefill else { + throw ProbeError("Gemma tensor-parallel lane prefill frame changed") + } + guard let logits = try lane.prefill(frame, check: check) else { return nil } + return try select(logits, lanes: [lane], check: check)[0] + } + + func decode(_ lanes: [Lane], tokens: [Int], check: () throws -> Void) throws -> [Int] { + guard !lanes.isEmpty, lanes.count == tokens.count, lanes.count <= host.lanes else { + throw ProbeError("Gemma tensor-parallel decode lanes exceed the host") + } + return try GPU.withCommandBufferLimits(Gemma4TensorParallelModel.decodeCommandBuffers) { + let frames = try lanes.map { try $0.admitDecode() } + let logits = try Gemma4TensorParallelPagedSession.decode(lanes.map(\.session), tokens: tokens, check: check) + for (lane, frame) in zip(lanes, frames) { try lane.commit(frame) } + completedDecode(lanes.count) + return try select(logits, lanes: lanes, check: check) + } + } + + private func select(_ logits: MLXArray, lanes: [Lane], check: () throws -> Void) throws -> [Int] { + let width = lanes.count, selection = model.selection + guard logits.shape == [width, model.vocabularyRange.count] else { + throw ProbeError("Gemma tensor-parallel selection rows do not match the lanes") + } + let choices = lanes.map { Gemma4TensorParallelChoice(selection: selection, sampler: $0.request.sampler, rank: rank) } + // Greedy rows take the split argmax; only sampled rows cross whole. + // Both ranks derive the same rows from the agreed requests. + let sampled = choices.indices.filter { choices[$0].gathersRow } + let greedy = choices.indices.filter { !choices[$0].gathersRow } + var tokens = [Int](repeating: 0, count: width) + var maxima = [Float?](repeating: nil, count: width) + if !greedy.isEmpty { + let rows = greedy.count == width ? logits : logits[MLXArray(greedy.map(Int32.init))] + let agreed = selection.greedyRows(rows) + eval(agreed.tokens, agreed.maxima); try check() + for (row, (token, maximum)) in zip(greedy, zip(agreed.tokens.asArray(Int32.self), agreed.maxima.asArray(Float.self))) { + tokens[row] = Int(token); maxima[row] = maximum + } + } + if !sampled.isEmpty { + let rows = selection.gather(sampled.count == width ? logits : logits[MLXArray(sampled.map(Int32.init))]) + eval(rows); try check() + var drawn = MLXArray.zeros([sampled.count], dtype: .float32) + if rank == 0 { + drawn = concatenated(sampled.enumerated().map { index, lane in + lanes[lane].request.sampler!.sample(rows[index ..< index + 1]).asType(.float32).reshaped([1]) + }, axis: 0) + } + let agreed = selection.exchange(drawn)[0 ..< sampled.count] + eval(agreed); try check() + for (row, token) in zip(sampled, agreed.asArray(Float.self)) { tokens[row] = Int(token) } + } + guard tokens.count == width, tokens.allSatisfy({ (0 ..< model.plan.vocabularySize).contains($0) }) else { + throw ProbeError("Gemma tensor-parallel selection produced an invalid token") + } + // Every rank takes every greedy row's top-k collective, in lane order. + for (index, lane) in lanes.enumerated() { + guard let sampler = lane.request.sampler else { continue } + if let count = sampler.wire.capturedLogprobs { + if choices[index].gathersRow { + lane.pendingLogprobs = rank == 0 ? sampler.takePendingLogprobs() : nil + } else { + let captured = try choices[index].logprobs(logits[index ..< index + 1], token: tokens[index], + maximum: maxima[index], count: count) + lane.pendingLogprobs = rank == 0 ? captured : nil + } + } + sampler.commit(tokens[index]) + } + return tokens + } + + func takeLogprobs(_ lane: Lane) throws -> ClusterWorkerTokenLogprobs? { + guard rank == 0 else { throw ProbeError("Only Gemma tensor-parallel rank 0 publishes token logprobs") } + defer { lane.pendingLogprobs = nil } + return lane.pendingLogprobs + } + + func retire(_ lane: Lane, reason: QwenLayerStageGenerationFinishReason?, selected: Int, last: Int?) throws { + if let reason { + guard let last else { throw ProbeError("Gemma tensor-parallel clean retirement has no selected token") } + try lane.finish(reason, selected: selected, last: last) + } + try lane.session.retire(failed: reason == nil) + lane.pendingLogprobs = nil + } +} + +extension Gemma4TensorParallelModel { + /// Greedy requests served together through the batch driver on this + /// shard's own paged host, as a batching rank serves them: each request's + /// tokens. Oracles and tools; both ranks call it with the same prompts. + public func generateLanes(prompts: [[Int]], outputCount: Int, chunk: Int) throws -> [[Int]] { + guard case .shard = role, let reduction, (1 ... 8).contains(prompts.count), outputCount >= 1, chunk >= 1, + let longest = prompts.map(\.count).max(), chunk <= longest, prompts.allSatisfy({ !$0.isEmpty }), + prompts.joined().allSatisfy({ (0 ..< plan.vocabularySize).contains($0) }) else { + throw ProbeError("Gemma tensor-parallel lanes: a shard, 1 to 8 prompts, a chunk within the longest") + } + let activation = String(describing: activationDType) + let profile = try QwenLayerStageGenerationProfile(identifier: "gemma4-tensor-parallel-lanes", + vocabularySize: plan.vocabularySize, hiddenSize: plan.hiddenSize, activationDType: activation, + maximumPromptTokens: longest, maximumChunkTokens: chunk, maximumOutputTokens: outputCount, + maximumContextTokens: longest + outputCount, logitsDType: activation == "float32" ? nil : "float32") + // The same request IDs on both ranks: the driver's exchange binds them. + let requests = try prompts.enumerated().map { index, prompt in + try QwenLayerStageGenerationRequest(profile: profile, + requestID: UUID(uuidString: String(format: "00000000-0000-4000-8000-%012d", index))!, + promptTokenIDs: prompt, chunkSize: chunk, outputCount: outputCount, stopTokenIDs: []) + } + let host = try pagedHost(lanes: prompts.count, maximumTokens: longest + outputCount, chunkTokens: chunk) + let book = ClusterBatchLaneBook() + for request in requests { + try book.reserve(request.requestID, .init(request: request, deadline: .max, laneStateBytes: 1), lanes: prompts.count) + try book.start(request.requestID) + } + let executor = try Gemma4TensorParallelBatchExecutor(model: self, host: host, + reduction: reduction, agree: { _, check in try check() }) + let driver = try QwenTensorParallelBatchDriver(executor: executor, book: book, capacity: prompts.count, + vocabulary: plan.vocabularySize) + var tokens: [UUID: [Int]] = [:] + try MLX.withError { error in + try driver.serve(host: Gemma4TensorParallelOracleLaneHost(), + retiredSelection: { id, selected, _ in tokens[id] = selected }, check: { try error.check() }) + } + guard host.isDrained, book.isEmpty, requests.allSatisfy({ tokens[$0.requestID]?.count == outputCount }) else { + throw ProbeError("Gemma tensor-parallel lanes did not all finish and return their pages") + } + return requests.map { tokens[$0.requestID]! } + } +} + +/// An owner that wants every token and publishes nowhere (oracles). +final class Gemma4TensorParallelOracleLaneHost: QwenBatchServingHost { + func serviceControl() throws {} + func publishToken(requestID: UUID, ordinal: Int, tokenID: Int, committedTokens: Int) throws {} + func awaitDecisions(_ requestIDs: [UUID]) throws -> [UUID: Bool] { + Dictionary(uniqueKeysWithValues: requestIDs.map { ($0, true) }) + } + func pollDecision(_ requestID: UUID) throws -> Bool? { true } + func publishFinished(requestID: UUID, reason: ClusterWorkerFinishReason) throws {} + func publishLeft(requestID: UUID) throws {} + func publishPromptCache(requestID: UUID, reusedTokens: Int, storedFrontiers: [Int]) throws {} +} + +extension Gemma4TensorParallelResidentRuntime { + private func withLaneOperation(_ body: () throws -> T) throws -> T { + // The driver applies new reservations on this executor while + // `serveBatch` holds the operation lock. + if batchServing { return try body() } + guard operation.try() else { throw ProbeError("A Gemma tensor-parallel native operation is already active") } + defer { operation.unlock() } + return try body() + } + + public func reserveLane(requestID: UUID, request value: ClusterWorkerReservation) throws -> Int { + try withLaneOperation { + guard lanes > 1, model != nil, host != nil, laneBook.count < lanes else { + throw ProbeError("Gemma tensor-parallel batch lanes are unavailable") + } + guard value.stillImages == nil, value.mimoImages == nil, value.glmMedia == nil else { + throw ProbeError("Gemma tensor parallel serves text requests only") + } + let request = try admission.request(value, id: requestID, now: DispatchTime.now().uptimeNanoseconds) + try control.check(deadline: value.deadlineUptimeNanoseconds) + let priced = try prefixCharge(request) + let charge = priced.charge + guard charge <= value.capacityLimitBytes else { + throw ProbeError("Gemma tensor-parallel lane exceeds its owner or readiness capacity") + } + // Every held lane at its whole charge, this one, and the rank's own reserve once + // (kept prefixes give way first; a capture beyond its charged part may be cut). + _ = ClusterIdleMemory.releaseFreedBuffers() + let captureLimit = try admitCapture(priced, held: [try laneBook.stateBytes(), charge, rankReserveBytes]) + try control.check(deadline: value.deadlineUptimeNanoseconds) + try laneBook.reserve(requestID, .init(request: request, deadline: value.deadlineUptimeNanoseconds, + laneStateBytes: charge, prefixCaptureLimit: captureLimit), lanes: lanes) + return charge + } + } + + public func startLane(requestID: UUID) throws { try laneBook.start(requestID) } + public func cancelLane(requestID: UUID) { laneBook.cancel(requestID) } + public func withdrawLane(requestID: UUID) -> Bool { laneBook.withdraw(requestID) } + public var hasStartedLanes: Bool { laneBook.hasStarted } + + public func serveBatch(host servingHost: QwenBatchServingHost) throws { + guard operation.try() else { throw ProbeError("A Gemma tensor-parallel native operation is already active") } + defer { operation.unlock() } + guard lanes > 1, let model, let host else { throw ProbeError("Gemma tensor-parallel batch has no lanes, shard or KV host") } + batchServing = true; defer { batchServing = false } + batchOrdinal = try QwenBatchRecordBinding.nextOrdinal(after: batchOrdinal) + let records = try QwenBatchRecordBinding(epoch: admission.configuration.identity.membershipEpoch, + planFingerprint: admission.plan.fingerprint, ordinal: batchOrdinal, lanes: lanes) + let executor = try Gemma4TensorParallelBatchExecutor(model: model, host: host, + reduction: group, prefix: prefix, agree: { [self] request, check in try agreeRequest(request, check: check) }) + let driver = try QwenTensorParallelBatchDriver(executor: executor, book: laneBook, capacity: lanes, + vocabulary: admission.profile.vocabularySize) + do { + try lifecycle.withRequest(identity: .init(requestID: records.requestID, epoch: records.requestID, + recordedRequestFingerprint: sha256(Data("gemma4-tp-batch|\(loadAgreement)|\(batchOrdinal)".utf8)))) { + try MLX.withError { error in + var lastResourceCheck: UInt64 = 0 + try driver.serve(host: servingHost, check: { + try error.check(); try self.control.check() + let now = DispatchTime.now().uptimeNanoseconds + if lastResourceCheck == 0 || now - lastResourceCheck >= 250_000_000 { + // Kept prefixes give way before the batch fails for memory. + try prefix.cache.yieldingMemory { try Self.requireLiveMemory(bytes: 0) } + lastResourceCheck = now + } + try error.check() + }) + } + } + guard host.isDrained else { throw ProbeError("Gemma tensor-parallel batch retained native history") } + collective.logDataPlaneStatus() + } catch { + // Its native state stays reachable until shutdown's checked drain; + // the peer may hold other prefixes now. + prefix.cache.sweep() + failedLaneDriver = driver; control.fail() + throw error + } + } + + /// Both ranks hold the same request under the same load: every 64 bits + /// of the SHA-256 of its fingerprint and the load agreement compared. + func agreeRequest(_ request: QwenLayerStageGenerationRequest, check: () throws -> Void) throws { + let digest = sha256(try canonicalJSONData([request.fingerprint, loadAgreement])) + for lower in stride(from: 0, to: digest.count, by: 16) { + let start = digest.index(digest.startIndex, offsetBy: lower) + guard let word = UInt64(digest[start ..< digest.index(start, offsetBy: 16)], radix: 16), + try group.digestsEqual(word) else { + throw ProbeError("Gemma tensor-parallel ranks were given different requests") + } + } + try check() + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLoadAgreement.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLoadAgreement.swift new file mode 100644 index 0000000000..10dab6b54a --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLoadAgreement.swift @@ -0,0 +1,56 @@ +import DarkbloomClusterProtocol +import Foundation +import MLXLMCommon + +/// What two ranks of a Gemma 4 tensor-parallel pair bind into their load +/// agreement besides the registered row's own fingerprint +/// (`Gemma4ResidentAdmission.loadAgreementFingerprint`: membership, model, +/// artifact, manifest, cut plan, profile, arithmetic receipt, JACCL, +/// allocator policy, both builds and the prefill schedule). The agreement +/// keys the pair's data plane and is compared before any weight is read, so +/// a rank started with any other value here refuses its peer. +struct Gemma4TensorParallelLoadAgreement: Equatable { + static let schema = "gemma4-tensor-parallel-load-v1" + + /// Requests served at once; one serves one request at a time. + var lanes = 1 + var kv = ClusterStageKVBackendKind.paged + var kvQuantization = PagedKVQuantizationSelection.native + /// Prompt prefixes kept, resident and on the SSD tier (`Gemma4TensorParallelPrefix`): + /// this build's `tensorParallelKeepsPromptPrefixes`, unless the diagnosis switch + /// turns them off on a rank, which its peer then refuses. + var prefixCache = Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes + + /// The mode's terms (FP32 partials, rounded once after the sum; the + /// sealed all-sum) and the plan's: where each layer's two sums are taken + /// and what they carry (the attention partial; one packed collective of + /// the dense partial and every selected expert's row). + static var termsFields: [String] { + ClusterGenerationMode.tensorParallel.loadAgreementFields + Gemma4TensorParallelPlan.arithmeticAgreementFields + } + + /// The registered prompt policy (singleton token reduction of every + /// affine projection, the product's CBv2 prompt path with its final-layer + /// tail) on the request's own chunk grid, and the decode step. + static let promptPolicyFields = ["gemma4-tensor-parallel-prompt-v1", "token-m1-affine-projections", + "cbv2-prompt-final-layer-tail", "request-chunk-grid", "decode-one-token-a-step"] + + /// How a token is chosen and its logprobs captured + /// (`Gemma4TensorParallelChoice`). + static let selectionFields = ["gemma4-tensor-parallel-selection-v1", "greedy-split-argmax-carrying-stops", + "sampled-gathered-row-rank0-draw", "logprobs-split-top-k"] + + var fields: [String] { + Self.termsFields + Self.promptPolicyFields + Self.selectionFields + + ["gemma4-tensor-parallel-lanes-v1", String(lanes)] + + kv.loadAgreementFields + kvQuantization.loadAgreementFields + + ["gemma4-tensor-parallel-prefix-v1", prefixCache ? "on" : "off"] + + ClusterDataPlaneAgreement.loadAgreementFields + } + + /// The agreement both ranks compare: this rank's registered row's + /// fingerprint and every field above. + func fingerprint(admission: String) throws -> String { + sha256(try canonicalJSONData([Self.schema, admission] + fields)) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLocalPair.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLocalPair.swift new file mode 100644 index 0000000000..267ce1aed5 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelLocalPair.swift @@ -0,0 +1,90 @@ +import Foundation +import MLX + +/// Both ranks of a Gemma 4 tensor-parallel pair in one process: each rank's +/// shard runs on its own thread and MLX stream, and every collective is the +/// elementwise FP32 sum of both ranks' partials, added in rank order (the +/// add of two values is commutative, so it is the sum a two-rank all-sum +/// returns). Every rank-local operation keeps the rank's own shapes and +/// kernels, so a two-process run over a real collective must equal it bit +/// for bit: the oracle for the transport, its sealing and the collective +/// schedule. Each collective evaluates its inputs, so this is an oracle, not +/// a timing. +public final class Gemma4TensorParallelLocalPair: @unchecked Sendable { + private let condition = NSCondition() + private var leaving = 0, step = 0 + private var values: [Int: [Float]] = [:], shapes: [Int: [Int]] = [:] + private var output: [Float] = [] + /// Every collective's payload shape, in order. + public private(set) var payloads: [[Int]] = [] + + public init() {} + + /// Rank `rank`'s reduction. + public func reduction(rank: Int) -> QwenTensorParallelReduction { Rank(rank: rank, pair: self) } + + private final class Rank: QwenTensorParallelReduction, @unchecked Sendable { + let rank: Int, size = 2 + let pair: Gemma4TensorParallelLocalPair + init(rank: Int, pair: Gemma4TensorParallelLocalPair) { self.rank = rank; self.pair = pair } + func allSum(_ value: MLXArray) -> MLXArray { pair.sum(value, rank: rank) } + } + + func sum(_ value: MLXArray, rank: Int) -> MLXArray { + precondition(value.dtype == .float32, "Gemma tensor-parallel collectives carry FP32") + let mine = value.asArray(Float.self) + condition.lock() + defer { condition.unlock() } + while leaving > 0 { condition.wait() } + let generation = step + precondition(values[rank] == nil, "rank \(rank) entered a collective twice") + values[rank] = mine + shapes[rank] = value.shape + if values.count == 2 { + precondition(shapes[0] == shapes[1], "the ranks' collectives differ in shape") + output = zip(values[0]!, values[1]!).map(+) + payloads.append(shapes[0]!) + leaving = 2 + condition.broadcast() + } else { + let deadline = Date().addingTimeInterval(600) + while leaving == 0 && step == generation { + precondition(condition.wait(until: deadline), "the other rank never reached the collective") + } + } + let result = output + leaving -= 1 + if leaving == 0 { + values = [:]; shapes = [:]; output = []; step += 1 + condition.broadcast() + } + return MLXArray(result, value.shape) + } + + /// Runs `body(rank)` for both ranks at once, each on a thread of its own + /// with its own default stream on `device` (MLX's default stream is + /// process-wide and not thread-safe); returns both results in rank order. + public static func run(device: Device, _ body: @escaping @Sendable (Int) throws -> T) throws -> [T] { + let results = PairResults() + let done = DispatchGroup() + for rank in 0 ..< 2 { + done.enter() + let thread = Thread { + let result = Device.withDefaultDevice(device) { + Stream.withNewDefaultStream(device: device) { Result { try body(rank) } } + } + results.lock.lock(); results.values[rank] = result; results.lock.unlock() + done.leave() + } + thread.stackSize = 8 << 20 + thread.start() + } + done.wait() + return try results.values.map { try $0!.get() } + } +} + +private final class PairResults: @unchecked Sendable { + var values: [Result?] = [nil, nil] + let lock = NSLock() +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelModel.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelModel.swift new file mode 100644 index 0000000000..1a40dd1b20 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelModel.swift @@ -0,0 +1,326 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +/// A Gemma 4 MoE text model loaded whole, as the single-process +/// tensor-parallel oracle, or as one rank's shard, and generation over it. +/// +/// - `full`: the unsharded model (the single-Mac reference on this code path). +/// - `splitSum`: the unsharded model whose row-parallel projections compute +/// both ranks' FP32 partials over their stored columns (zero outside each +/// rank's own channels) and add them in FP32, and whose head normalizes +/// log probabilities over the two vocabulary halves: the decomposition's +/// oracle. Two ranks equal it bit for bit wherever each column-parallel +/// kernel's rows do not depend on the row count (the CPU; on an M5 Ultra +/// GPU a prefill-width full-attention `k_proj` of 1,024 rows rounds some +/// rows differently from its 512-row half). `Gemma4TensorParallelLocalPair` +/// runs both real shards in one process: the bitwise oracle everywhere. +/// - `shard(rank)`: this rank's heads and channels only, built by the SDK's +/// own Gemma 4 modules from the rank's local configuration; every layer +/// sums its attention partial and one packed feed-forward collective +/// through `reduction`, and the head projects this rank's vocabulary rows +/// (`Gemma4TensorParallelSelection` chooses across ranks). +public final class Gemma4TensorParallelModel { + public enum Role: Equatable, Sendable { + case full + case splitSum + case shard(rank: Int) + + public var label: String { + switch self { + case .full: return "full" + case .splitSum: return "split-sum-tp2" + case .shard(let rank): return "tp2-rank\(rank)" + } + } + } + + public let role: Role + public let plan: Gemma4TensorParallelPlan + public let vocabularyRange: Range + public let configurationSHA256: String + public let loadSeconds: Double + public let loadedParameterBytes: Int + /// The residual's and every layer's key/value dtype (the embedding's scales). + public let activationDType: DType + let model: Gemma4Model + let reduction: QwenTensorParallelReduction? + + var textModel: Gemma4TextModel { model.textModel } + + /// Reads a checkpoint directory (`config.json`, `model.safetensors.index.json` + /// and the files it names) directly: tools and oracles. Vision tensors are + /// skipped; every other tensor must be a text tensor the plan covers. + public static func load(modelDirectory: URL, role: Role, reduction: QwenTensorParallelReduction?, + packFeedForward: Bool = true) throws -> Gemma4TensorParallelModel { + let configurationData = try Data(contentsOf: modelDirectory.appendingPathComponent("config.json")) + return try assemble(configurationData: configurationData, role: role, reduction: reduction, + packFeedForward: packFeedForward) { keep in + let indexData = try Data(contentsOf: modelDirectory.appendingPathComponent("model.safetensors.index.json")) + guard let index = (try JSONSerialization.jsonObject(with: indexData) as? [String: Any])?["weight_map"] + as? [String: String] else { + throw ProbeError("Gemma tensor parallel load: the checkpoint index has no weight map") + } + var byFile: [String: [String]] = [:] + for (key, file) in index { + guard !file.contains("/"), file.hasSuffix(".safetensors") else { + throw ProbeError("Gemma tensor parallel load: the checkpoint index names an unexpected file") + } + byFile[file, default: []].append(key) + } + for file in byFile.keys.sorted() { + let arrays = try loadArrays(url: modelDirectory.appendingPathComponent(file)) + for key in byFile[file]!.sorted() { + guard let value = arrays[key] else { throw ProbeError("Gemma tensor parallel load: \(file) lacks \(key)") } + try keep(key, value) + } + } + } + } + + /// The model of `role` from a configuration and its stored tensors: + /// `tensors` hands every stored tensor (by checkpoint key) to `keep`, + /// which cuts this rank's part and materializes it at once. + static func assemble(configurationData: Data, role: Role, reduction: QwenTensorParallelReduction?, + packFeedForward: Bool = true, + tensors: (_ keep: (String, MLXArray) throws -> Void) throws -> Void) throws + -> Gemma4TensorParallelModel { + let started = DispatchTime.now().uptimeNanoseconds + guard var root = try JSONSerialization.jsonObject(with: configurationData) as? [String: Any], + let text = root["text_config"] as? [String: Any] else { + throw ProbeError("Gemma tensor parallel load: expected a gemma4 configuration with a text configuration") + } + let plan = try Gemma4TensorParallelPlan(configuration: root) + // The wrapper takes the vocabulary from its root (262,144 when absent). + root["vocab_size"] = plan.vocabularySize + let full = try JSONDecoder().decode(Gemma4Configuration.self, + from: JSONSerialization.data(withJSONObject: root, options: [.sortedKeys])) + let rank: Int + switch role { + case .full, .splitSum: + rank = 0 + guard reduction == nil else { throw ProbeError("Gemma tensor parallel load: only a shard takes a reduction") } + case .shard(let r): + rank = r + guard let reduction, reduction.size == plan.size, reduction.rank == r else { + throw ProbeError("Gemma tensor parallel load: a shard needs the reduction of its own rank and group size") + } + } + var constructed = root + if case .shard = role { constructed["text_config"] = try plan.shardTextConfiguration(text, rank: rank) } + let configuration = try JSONDecoder().decode(Gemma4Configuration.self, + from: JSONSerialization.data(withJSONObject: constructed, options: [.sortedKeys])) + let model = Gemma4Model(configuration) + + var weights: [String: MLXArray] = [:] + try tensors { key, value in + if !key.hasPrefix("language_model.") { + guard Gemma4TensorParallelPlan.isVisionTensor(key) else { + throw ProbeError("Gemma tensor parallel load: unknown checkpoint key \(key)") + } + return + } + guard weights[key] == nil else { throw ProbeError("Gemma tensor parallel load: \(key) was given twice") } + guard try plan.expectedShape(key: key) == value.shape else { + throw ProbeError("Gemma tensor parallel load: \(key) has shape \(value.shape), not the plan's") + } + let cut = try plan.cut(key: key, rank: rank) + let part: MLXArray + if case .shard = role { part = try Gemma4TensorParallelSlicer.cut(value, cut, key: key, plan: plan) } + else { part = value } + // Materialize each part now: the stored tensor it came from is + // released before the next one is read. + eval(part) + weights[key] = part + } + quantize(model: model) { path, _ in + weights[path + ".scales"] != nil ? (plan.groupSize, plan.bits(forModule: path), .affine) : nil + } + try model.update(parameters: ModuleParameters.unflattened(weights), verify: [.all]) + + var extra: [MLXArray] = [] + switch role { + case .full: + break + case .shard(let r): + try model.textModel.installTensorParallel(shard: Gemma4TensorShard(rank: r), full: full.textConfiguration, + packFeedForward: packFeedForward) { reduction!.allSum($0) } + case .splitSum: + extra = try Gemma4TensorParallelSplitSum.install(in: model, plan: plan) + } + let parameters = model.parameters().flattened().map(\.1) + eval(parameters + extra) + Memory.clearCache() + let vocabulary: Range + if case .shard(let r) = role { vocabulary = plan.vocabularyRange(rank: r) } else { vocabulary = 0 ..< plan.vocabularySize } + guard model.textModel.headVocabularyRange == vocabulary else { + throw ProbeError("Gemma tensor parallel load: the head does not project the plan's vocabulary rows") + } + // The embedding's scales are what the residual and every layer's keys and values are computed in. + guard let activation = weights["language_model.model.embed_tokens.scales"]?.dtype, + [.bfloat16, .float16, .float32].contains(activation) else { + throw ProbeError("Gemma tensor parallel load: the embedding has no native activation dtype") + } + return Gemma4TensorParallelModel(role: role, plan: plan, vocabularyRange: vocabulary, + configurationSHA256: sha256(configurationData), + loadSeconds: Double(DispatchTime.now().uptimeNanoseconds - started) / 1e9, + loadedParameterBytes: (parameters + extra).reduce(0) { $0 + $1.nbytes }, + activationDType: activation, model: model, reduction: reduction) + } + + private init(role: Role, plan: Gemma4TensorParallelPlan, vocabularyRange: Range, + configurationSHA256: String, loadSeconds: Double, loadedParameterBytes: Int, + activationDType: DType, model: Gemma4Model, reduction: QwenTensorParallelReduction?) { + self.role = role; self.plan = plan; self.vocabularyRange = vocabularyRange + self.configurationSHA256 = configurationSHA256; self.loadSeconds = loadSeconds + self.loadedParameterBytes = loadedParameterBytes; self.activationDType = activationDType + self.model = model; self.reduction = reduction + } + + /// The head's selections over this model's vocabulary rows. + public var selection: Gemma4TensorParallelSelection { + Gemma4TensorParallelSelection(vocabularyRange: vocabularyRange, vocabularySize: plan.vocabularySize, + reduction: reduction, splitsWholeRow: role == .splitSum) + } + + func newCache() -> [KVCache] { model.newCache(parameters: nil) } + + /// The model over `input` `[1, T]`: logits `[1, T, V or V/2]` (FP32 after + /// the softcap), not evaluated. + func forward(_ input: MLXArray, cache: [KVCache]) -> MLXArray { model(input, cache: cache) } + + /// The prompt through the model in chunks; the last position's logits + /// `[1, V or V/2]`, not evaluated. + func prefill(_ prompt: [Int], chunk: Int, cache: [KVCache]) -> MLXArray { + var logits: MLXArray? + var offset = 0 + while offset < prompt.count { + let end = min(prompt.count, offset + chunk) + let out = forward(MLXArray(prompt[offset ..< end].map { Int32($0) }).reshaped(1, end - offset), cache: cache) + if end < prompt.count { + eval(cache.flatMap { $0.innerState() }) + } else { + logits = out[0..., -1, 0...] + } + offset = end + } + return logits! + } + + /// One greedy generation's tokens and per-step evidence. + public struct Generation: Sendable { + public var tokenIDs: [Int] = [] + /// Per step, the top `recordTop` token IDs, their logits and log + /// probabilities over the whole vocabulary, highest first. + public var topTokenIDs: [[Int]] = [] + public var topLogits: [[Float]] = [] + public var topLogprobs: [[Float]] = [] + /// The last step's whole vocabulary row (FP32), when recorded. + public var finalLogits: [Float]? + public var firstTokenSeconds = 0.0 + public var decodeSeconds = 0.0 + public var stepSeconds: [Double] = [] + public var peakActiveBytes = 0 + } + + /// Greedy generation of `outputCount` tokens after `prompt`, prefilled in + /// chunks of `chunk`. `recordTop` > 0 records each step's top logits and + /// log probabilities (a shard through the vocabulary-split top-k gather) + /// and the final step's whole row (a shard through the row gather). Each + /// step's collectives run in one fixed order on every rank: the forward's, + /// the selection, the top-k gather, then the final row. + public func generate(prompt: [Int], outputCount: Int, chunk: Int, recordTop: Int = 0) throws -> Generation { + guard !prompt.isEmpty, outputCount >= 1, chunk >= 1, prompt.allSatisfy({ (0 ..< plan.vocabularySize).contains($0) }) else { + throw ProbeError("Gemma tensor parallel generation: empty or out-of-vocabulary request") + } + guard (0 ... 64).contains(recordTop) else { throw ProbeError("Gemma tensor parallel generation: at most 64 logits per step") } + let selection = self.selection + let cache = newCache() + var result = Generation() + let started = Self.now() + var logits = prefill(prompt, chunk: chunk, cache: cache) + var last = started + for step in 0 ..< outputCount { + let token = selection.greedy(logits) + eval(token) + let id = Int(token.item(Int32.self)) + if recordTop > 0 { + let top = try selection.topK(logits, count: recordTop) + result.topTokenIDs.append(top.tokenIDs) + result.topLogits.append(top.logits) + result.topLogprobs.append(top.logprobs) + if step == outputCount - 1 { + let row = selection.gather(logits) + eval(row) + result.finalLogits = row.asArray(Float.self) + } + } + let time = Self.now() + if step == 0 { result.firstTokenSeconds = time - started } else { result.stepSeconds.append(time - last) } + last = time + result.tokenIDs.append(id) + if step + 1 < outputCount { + logits = forward(token.reshaped(1, 1), cache: cache)[0..., -1, 0...] + } + } + result.decodeSeconds = last - started - result.firstTokenSeconds + result.peakActiveBytes = Memory.peakMemory + return result + } + + static func now() -> Double { Double(DispatchTime.now().uptimeNanoseconds) / 1e9 } +} + +/// Exact copies of a stored tensor's rank part into new row-major buffers +/// (never views, which would keep the whole stored tensor alive), with the +/// plan's zero rows: zero packed words, scales and offsets, so every padded +/// channel's projection is exactly zero. +enum Gemma4TensorParallelSlicer { + static func cut(_ value: MLXArray, _ cut: Gemma4TensorParallelPlan.Cut, key: String, + plan: Gemma4TensorParallelPlan) throws -> MLXArray { + let local = try plan.localShape(key: key, shape: value.shape, cut: cut) + let part: MLXArray + switch cut { + case .replicate: + return value + case .rows(let range, let before, let after): + part = padded(value[range], axis: 0, before: before, after: after) + case .inputColumns(let logical): + let divisor = columnDivisor(key: key, plan: plan) + part = value[0..., (logical.lowerBound / divisor) ..< (logical.upperBound / divisor)] + case .expertRows(let range, let before, let after): + part = padded(value[0..., range], axis: 1, before: before, after: after) + case .expertInputColumns(let logical): + let divisor = columnDivisor(key: key, plan: plan) + part = value[0..., 0..., (logical.lowerBound / divisor) ..< (logical.upperBound / divisor)] + } + let copied = contiguous(part) + guard copied.shape == local else { + throw ProbeError("Gemma tensor parallel slice: \(key) cut to \(copied.shape), not \(local)") + } + return copied + } + + /// Logical input columns per stored column: values per packed word for a + /// weight, the group size for scales and offsets. + static func columnDivisor(key: String, plan: Gemma4TensorParallelPlan) -> Int { + let parts = key.split(separator: ".") + return parts.last == "weight" ? 32 / plan.bits(forModule: parts.dropLast().joined(separator: ".")) : plan.groupSize + } + + private static func padded(_ value: MLXArray, axis: Int, before: Int, after: Int) -> MLXArray { + guard before > 0 || after > 0 else { return value } + func zeros(_ count: Int) -> MLXArray { + var shape = value.shape + shape[axis] = count + return MLXArray.zeros(shape, dtype: value.dtype) + } + var parts: [MLXArray] = [] + if before > 0 { parts.append(zeros(before)) } + parts.append(value) + if after > 0 { parts.append(zeros(after)) } + return concatenated(parts, axis: axis) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift new file mode 100644 index 0000000000..b19c02d43a --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift @@ -0,0 +1,313 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +extension Gemma4TensorParallelModel { + /// This model's request state over every layer at `maximumTokens`: a + /// shard's own KV heads per layer (26B: 4 sliding, 1 full), or every head + /// of the whole model (the oracle's). + func requestGeometry(maximumTokens: Int) throws -> CBv2RequestGeometry { + let ranks: Int + switch role { + case .shard: ranks = plan.size + case .full: ranks = 1 + case .splitSum: throw ProbeError("The split-sum oracle runs on its legacy caches only") + } + // The product's own derivation, each layer's state keyed by its index. + let kinds = textModel.cbv2LayerKinds.enumerated().map { index, kind -> CBv2LayerKind in + var keyed = kind; keyed.modelLayerIndex = index + return keyed + } + return try CBv2RequestGeometry(gemma4TensorParallelKinds: kinds, plan: plan, ranks: ranks, + slidingWindow: textModel.configuration.slidingWindow, kvDType: activationDType, maximumTokens: maximumTokens) + } + + /// The paged KV host this model's requests take their pages from: + /// `lanes` requests of at most `maximumTokens`, prompt chunks of at most + /// `chunkTokens`. + func pagedHost(lanes: Int, maximumTokens: Int, chunkTokens: Int, + quantization: PagedKVQuantizationSelection = .native) throws -> CBv2StageKVHost { + try CBv2StageKVHost(gemma4Geometry: requestGeometry(maximumTokens: maximumTokens), kind: .paged, lanes: lanes, + maximumTokensPerRequest: maximumTokens, maximumChunkTokens: chunkTokens, quantization: quantization) + } +} + +/// One request of a Gemma 4 tensor-parallel rank (or of the whole model, the +/// oracle) on its paged KV host, through the product's own CBv2 entry points: +/// a prompt chunk is `Gemma4TextModel.cbv2Prefill` (the final layer keeps +/// only the row it projects; an earlier chunk projects nothing) under the +/// registered prompt policy (`Gemma4PrefillProjectionScope`: every affine +/// projection keeps its singleton token reduction, as the pipeline stages +/// compute), and a decode step is the model's forward on one token. Each +/// forward's cross-rank sums are inside its graph; `select` builds the +/// step's choice into the same evaluation, so a step costs one evaluation. +/// +/// Pages grow with the request (`QwenTensorParallelBatchSession`'s granule +/// and margin). Native work only on the owner's serial executor, inside +/// `MLX.withError`; `check` is the caller's. +final class Gemma4TensorParallelPagedSession { + let model: Gemma4TensorParallelModel + let state: CBv2OwnedRequestState + let promptCount: Int + private(set) var retired = false + /// Prompt tokens restored from a kept prefix (0 for a cold request). + let reusedPrefixTokens: Int + /// This request's prefix capture, taken after the prompt chunks that end + /// at its boundaries (`Gemma4TensorParallelPrefixCapture`); nil keeps none. + var prefixCapture: Gemma4TensorParallelPrefixCapture? + + /// `restoring`: this rank's state at an agreed prefix boundary (its own + /// heads' full rows and sliding windows, `Gemma4TensorParallelPrefix`), + /// written into fresh pages of the request; the prompt then continues + /// from that boundary on the same chunk grid. + init(model: Gemma4TensorParallelModel, host: CBv2StageKVHost, promptCount: Int, outputCount: Int, + restoring prefix: QwenStagePrefixState? = nil) throws { + let maximum = promptCount + outputCount + guard promptCount > 0, outputCount > 0, maximum <= host.maximumTokensPerRequest, + (prefix?.committedTokens ?? 0) < promptCount else { + throw ProbeError("Gemma tensor-parallel request does not fit its KV host") + } + let geometry = try Self.geometry(model: model, host: host, maximumTokens: maximum) + self.model = model; self.promptCount = promptCount + let reserved = host.kind == .paged ? min(maximum, promptCount + QwenTensorParallelBatchSession.pageGrowthTokens) : nil + if let prefix { + guard Gemma4TensorParallelPrefix.adopts(prefix, into: geometry) else { + throw ProbeError("Gemma tensor-parallel prefix differs from this rank's request geometry") + } + let sliding = Set(geometry.kinds.compactMap { kind -> Int? in + if case .slidingWindow = kind.attention { return kind.modelLayerIndex } + return nil + }) + state = try CBv2OwnedRequestState(geometry: geometry, promptCount: promptCount, outputCount: outputCount, + adoptingCommittedTokens: prefix.committedTokens, attention: prefix.attention, + slidingTails: prefix.recurrent.filter { sliding.contains($0.key) }.mapValues { (keys: $0.conv, values: $0.ssm) }, + recurrent: [:], reservedTokens: reserved) + } else { + state = try CBv2OwnedRequestState(geometry: geometry, promptCount: promptCount, outputCount: outputCount, + reservedTokens: reserved) + } + reusedPrefixTokens = prefix?.committedTokens ?? 0 + } + + /// The request geometry a session of `maximumTokens` takes on `host`. + static func geometry(model: Gemma4TensorParallelModel, host: CBv2StageKVHost, maximumTokens: Int) throws -> CBv2RequestGeometry { + try CBv2RequestGeometry(gemma4Stage: model.requestGeometry(maximumTokens: maximumTokens), host: host, + maximumTokens: maximumTokens) + } + + var committedTokens: Int { state.committedTokens } + + /// Before a forward that writes `count` tokens: its pages and the margin, + /// grown by granules up to the request's length. False when the pool + /// cannot back them; nothing changed then. + func reservePages(writing count: Int) -> Bool { + guard state.pagedHost, let target = QwenTensorParallelBatchSession.pageGrowthTarget( + reserved: state.reservedTokens, needed: state.committedTokens + count, limit: state.maximumTokens) else { return true } + return (try? state.growReservation(toTokens: target)) != nil + } + + /// Whether the pages already cover a forward of `count` tokens. + func pagesCover(writing count: Int) -> Bool { state.committedTokens + count <= state.reservedTokens } + + /// One prompt chunk `range` of `prompt`. The chunk that ends the prompt + /// returns its last row's logits (`[1, vocabulary rows]`, FP32) and + /// `select(logits)`, evaluated with the chunk; an earlier chunk, nil. + func prefill(_ prompt: [Int], range: Range, check: () throws -> Void, + select: (MLXArray) -> MLXArray) throws -> (logits: MLXArray, selected: MLXArray)? { + guard !retired, prompt.count == promptCount, range.lowerBound == state.committedTokens, !range.isEmpty, + range.upperBound <= prompt.count, reservePages(writing: range.count) else { + throw ProbeError("Gemma tensor-parallel prompt chunk differs from its request's frontier or pages") + } + let final = range.upperBound == prompt.count + let input = MLXArray(prompt[range].map(Int32.init)).reshaped([1, range.count]) + let text = model.textModel + var logits: MLXArray? + let output = try state.run(tokenCount: range.count, check: check, forward: { caches, _ in + let kv = caches.map { $0 as! any KVCache } + let row = Gemma4PrefillProjectionScope.withPrefillFrame(tokens: input, enabled: true) { + text.cbv2Prefill(input, inputEmbedding: nil, cache: kv, + requirement: final ? .lastPositionLogits : .evaluationOnly) + } + guard final else { return row } + logits = row + return select(row) + }, validateOutput: { _ in }) + if let prefixCapture, prefixCapture.frontiers.contains(range.upperBound) { + try prefixCapture.capture(state, at: range.upperBound) + try check() + } + guard final else { return nil } + guard let logits else { throw ProbeError("Gemma tensor-parallel prompt produced no logits") } + try Self.validate(logits, rows: 1, model: model) + return (logits, output) + } + + /// One decode step on `token`: the next row's logits and `select(logits)`, + /// evaluated together. + func decode(_ token: Int, check: () throws -> Void, + select: (MLXArray) -> MLXArray) throws -> (logits: MLXArray, selected: MLXArray) { + guard !retired, (0 ..< model.plan.vocabularySize).contains(token), state.committedTokens >= promptCount, + pagesCover(writing: 1) || reservePages(writing: 1) else { + throw ProbeError("Gemma tensor-parallel decode step differs from its request or pages") + } + let input = MLXArray([Int32(token)]).reshaped([1, 1]) + let text = model.textModel + var logits: MLXArray? + let stride = Gemma4TensorParallelModel.layerStride ?? Gemma4TensorParallelModel.decodeLayerStride + let output = try state.run(tokenCount: 1, check: check, forward: { caches, _ in + let row = Gemma4LayerSubmission.$stride.withValue(stride) { + Gemma4BatchDecodeScope.withDecodeFrame(tokens: input, enabled: true) { + text(input, cache: caches.map { $0 as! any KVCache })[0..., -1, 0...] + } + } + logits = row + return select(row) + }, validateOutput: { _ in }) + guard let logits else { throw ProbeError("Gemma tensor-parallel decode produced no logits") } + try Self.validate(logits, rows: 1, model: model) + return (logits, output) + } + + /// One decode step of each of `sessions` (distinct requests on one model's + /// host), a row each, in one forward under the explicit batch decode scope + /// (`Gemma4BatchDecodeScope`: every row keeps each projection's singleton + /// reduction, and each rank packs every row's expert partials into the + /// layer's one collective): each row equals its request's own step bit for + /// bit. The rows' logits `[B, vocabulary rows]`, evaluated. + static func decode(_ sessions: [Gemma4TensorParallelPagedSession], tokens: [Int], + check: () throws -> Void) throws -> MLXArray { + guard let first = sessions.first, sessions.count == tokens.count, (1 ... 8).contains(sessions.count), + Set(sessions.map { ObjectIdentifier($0) }).count == sessions.count, + sessions.allSatisfy({ $0.model === first.model && !$0.retired && $0.state.committedTokens >= $0.promptCount }), + tokens.allSatisfy({ (0 ..< first.model.plan.vocabularySize).contains($0) }) else { + throw ProbeError("Gemma tensor-parallel batch decode needs distinct open requests of one shard") + } + guard sessions.count > 1 else { return try first.decode(tokens[0], check: check) { $0 }.logits } + for session in sessions where !(session.pagesCover(writing: 1) || session.reservePages(writing: 1)) { + throw ProbeError("Gemma tensor-parallel lane has no page for its next row") + } + let input = MLXArray(tokens.map(Int32.init)).reshaped([sessions.count, 1]) + let text = first.model.textModel + let stride = Gemma4TensorParallelModel.layerStride ?? Gemma4TensorParallelModel.decodeLayerStride + let output = try CBv2OwnedRequestState.runBatch(sessions.map(\.state), tokenCount: 1, check: check, + forward: { caches, _ in + Gemma4LayerSubmission.$stride.withValue(stride) { + Gemma4BatchDecodeScope.withDecodeFrame(tokens: input, enabled: true) { + text(input, cache: caches.map { $0 as! any KVCache })[0..., -1, 0...] + } + } + }, validateOutput: { _ in }) + try validate(output, rows: sessions.count, model: first.model) + return output + } + + static func validate(_ logits: MLXArray, rows: Int, model: Gemma4TensorParallelModel) throws { + guard logits.shape == [rows, model.vocabularyRange.count], logits.dtype == .float32 else { + throw ProbeError("Gemma tensor-parallel logits have an invalid shape or dtype") + } + } + + /// Releases the request's pages; after a failure too. + func retire(failed: Bool = false) throws { + guard !retired else { return } + try MLX.withError { error in + try state.retire(failed: failed) + Stream.gpu.synchronize(); Stream.cpu.synchronize(); try error.check() + guard state.isClosed else { throw ProbeError("Gemma tensor-parallel request state remains owned") } + retired = true + } + } +} + +extension Gemma4TensorParallelModel { + /// Decode steps encode under these command-buffer limits (as GLM's and + /// Qwen's tensor-parallel decode): the worker's 16-operation guard splits a + /// MoE step's thousands of small launches into many buffers, each a GPU + /// gap. Synchronization only: results never depend on the partitioning. + static let decodeCommandBuffers = GPU.CommandBufferLimits(operations: 100, megabytes: 1 << 20) + /// A decode step is submitted to the GPU every this many decoder layers as + /// the host builds it (`Gemma4LayerSubmission`), so the GPU and the + /// collectives run the layers already built while the host builds the + /// rest (Qwen tensor parallel's measured choice; not yet measured for + /// Gemma). Evaluation order only: every value and token is unchanged. + static let decodeLayerStride = 1 + /// A bench or test's own stride (0: the whole step in one evaluation). + @TaskLocal static var layerStride: Int? + + /// Greedy generation as `generate`, on this model's paged KV through the + /// resident runtime's own request path (`Gemma4TensorParallelPagedSession`, + /// `Gemma4TensorParallelChoice`): each step's token and stop flags agreed in + /// the step's evaluation, `recordTop` candidates per step from the + /// vocabulary-split top-k gather and the final step's whole row. + public func generatePaged(prompt: [Int], outputCount: Int, chunk: Int, recordTop: Int = 0) throws -> Generation { + guard !prompt.isEmpty, outputCount >= 1, chunk >= 1, prompt.allSatisfy({ (0 ..< plan.vocabularySize).contains($0) }) else { + throw ProbeError("Gemma tensor parallel generation: empty or out-of-vocabulary request") + } + guard (0 ... 64).contains(recordTop) else { throw ProbeError("Gemma tensor parallel generation: at most 64 logits per step") } + let host = try pagedHost(lanes: 1, maximumTokens: prompt.count + outputCount, chunkTokens: chunk) + let session = try Gemma4TensorParallelPagedSession(model: self, host: host, promptCount: prompt.count, + outputCount: outputCount) + return try generatePaged(session: session, host: host, prompt: prompt, outputCount: outputCount, chunk: chunk, + recordTop: recordTop) + } + + /// The same greedy generation on `session` (cold, or restored from a + /// prefix: its prompt continues from its committed boundary), retired + /// at the end; `host` must drain. + func generatePaged(session: Gemma4TensorParallelPagedSession, host: CBv2StageKVHost, prompt: [Int], outputCount: Int, + chunk: Int, recordTop: Int) throws -> Generation { + let rank: Int + if case .shard(let r) = role { rank = r } else { rank = 0 } + let choice = Gemma4TensorParallelChoice(selection: selection, sampler: nil, rank: rank) + var result = Generation() + do { + try MLX.withError { error in + func checked() throws { try error.check() } + let started = Self.now() + var offset = session.committedTokens + var step: (logits: MLXArray, selected: MLXArray)? + while offset < prompt.count { + let end = min(prompt.count, offset + chunk) + step = try session.prefill(prompt, range: offset ..< end, check: checked) { choice.build($0, stop: 0) } ?? step + offset = end + } + guard var current = step else { throw ProbeError("Gemma tensor-parallel prompt produced no step") } + var last = started + try GPU.withCommandBufferLimits(Self.decodeCommandBuffers) { + for index in 0 ..< outputCount { + let agreed = try choice.read(current.selected) + guard agreed.flags.allSatisfy({ $0 == 0 }) else { throw ProbeError("Gemma oracle step carried a stop") } + if recordTop > 0 { + let top = try selection.topK(current.logits, count: recordTop) + result.topTokenIDs.append(top.tokenIDs) + result.topLogits.append(top.logits) + result.topLogprobs.append(top.logprobs) + if index == outputCount - 1 { + let row = selection.gather(current.logits) + eval(row) + try checked() + result.finalLogits = row.asArray(Float.self) + } + } + let time = Self.now() + if index == 0 { result.firstTokenSeconds = time - started } else { result.stepSeconds.append(time - last) } + last = time + result.tokenIDs.append(agreed.token) + if index + 1 < outputCount { + current = try session.decode(agreed.token, check: checked) { choice.build($0, stop: 0) } + } + } + } + result.decodeSeconds = last - started - result.firstTokenSeconds + } + try session.retire() + } catch { + try? session.retire(failed: true) + throw error + } + guard host.isDrained else { throw ProbeError("Gemma tensor-parallel request kept its pages") } + result.peakActiveBytes = Memory.peakMemory + return result + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPlan.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPlan.swift new file mode 100644 index 0000000000..e395f57a82 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPlan.swift @@ -0,0 +1,433 @@ +import Foundation + +/// How a Gemma 4 MoE text model (`gemma4_text` inside the `gemma4` wrapper, +/// tied head; the registered 26B A4B artifacts at 4 and 8 bits) is split +/// across two ranks by heads and channels with equal shares: +/// `gemma4_heads_and_expert_channels_v1`. +/// +/// - Attention: contiguous halves of the query heads with the KV heads they +/// read: `q_proj`, `k_proj` and (sliding layers) `v_proj` by output rows, +/// `o_proj` by input columns. Query head `h` reads KV head `h / (Hq / Hkv)`, +/// so halves keep each group whole (26B: sliding 8 query and 4 KV heads per +/// rank, full 8 and 1). Full layers have K=V and store no `v_proj`. +/// - Dense MLP and every routed expert: each rank computes a contiguous half +/// of the channels (gate/up output rows). The down projection is quantized +/// in groups along its input axis, so its stored input columns widen to +/// whole groups; with an odd group count (2112 = 33 x 64, 704 = 11 x 64) +/// both ranks store the middle group, and each rank's gate and up carry +/// zero rows (zero weights, scales and offsets) for the other rank's half +/// of it. Those channels are exactly zero, the shared columns add nothing +/// on the rank that does not own them, and both ranks hold the same width +/// (1088 and 384): equal shares, no unequal-share contract. +/// - Replicated: every norm, `layer_scalar`, the router (`proj`, `scale`, +/// `per_expert_scale`; both ranks route identically), the per-head +/// `q_norm`/`k_norm`, the final norm and the tied embedding. The head +/// projects this rank's half of the embedding's vocabulary rows (views). +/// +/// Collectives: per layer the attention partial before +/// `post_attention_layernorm`, and one packed feed-forward collective carrying +/// the dense partial and every selected expert's FP32 row (each summed before +/// rounding, router weighting and its branch's post-norm); one per step for +/// the vocabulary-split selection. Vision tower tensors are refused: the +/// plan covers the text model only, as the pipeline stages do. +public struct Gemma4TensorParallelPlan: Sendable, Equatable { + public static let name = "gemma4_heads_and_expert_channels_v1" + public let size = 2 + + public enum LayerKind: String, Sendable, Equatable { + case sliding = "sliding_attention" + case full = "full_attention" + } + + public let hiddenSize: Int + public let layerCount: Int + public let layerKinds: [LayerKind] + public let vocabularySize: Int + public let queryHeads: Int + public let slidingKVHeads: Int + public let fullKVHeads: Int + public let slidingHeadDim: Int + public let fullHeadDim: Int + public let denseWidth: Int + public let expertWidth: Int + public let expertCount: Int + public let expertsPerToken: Int + public let groupSize: Int + public let defaultBits: Int + /// Explicit per-module bits (`language_model.model.layers.N.`). + private let overrideBits: [String: Int] + + /// One rank's equal share of a channel-parallel width (see the type note). + public struct ChannelSplit: Sendable, Equatable { + public let width: Int + public let groupSize: Int + public let rank: Int + /// Channels of the full width this rank computes. + public let channels: Range + /// Input columns of the down projection this rank stores. + public let storedColumns: Range + + public init(width: Int, groupSize: Int, rank: Int) throws { + guard (0 ..< 2).contains(rank), width > 0, groupSize > 0, width % groupSize == 0, width % 2 == 0 else { + throw ProbeError("Gemma tensor parallel plan: width \(width) is not whole groups of \(groupSize)") + } + let half = width / 2 + self.width = width; self.groupSize = groupSize; self.rank = rank + channels = rank == 0 ? 0 ..< half : half ..< width + storedColumns = (channels.lowerBound / groupSize * groupSize) + ..< ((channels.upperBound + groupSize - 1) / groupSize * groupSize) + } + + public var localWidth: Int { storedColumns.count } + public var zeroBefore: Int { channels.lowerBound - storedColumns.lowerBound } + public var zeroAfter: Int { storedColumns.upperBound - channels.upperBound } + } + + /// A stored tensor's cut for one rank. + public enum Cut: Equatable, Sendable { + /// Every rank holds the whole tensor. + case replicate + /// Output rows (axis 0) in order, with all-zero rows before and after. + case rows(Range, zeroBefore: Int, zeroAfter: Int) + /// Logical input columns (axis 1) of a quantized linear: packed words + /// and per-group scales/offsets are cut accordingly. + case inputColumns(Range) + /// Every expert's output rows (axis 1 of `[E, out, in]`), with all-zero + /// rows before and after. + case expertRows(Range, zeroBefore: Int, zeroAfter: Int) + /// Every expert's logical input columns (axis 2, quantized). + case expertInputColumns(Range) + } + + /// `root` is the artifact's whole `config.json` object. + public init(configuration root: [String: Any]) throws { + guard root["model_type"] as? String == "gemma4", let text = root["text_config"] as? [String: Any], + text["model_type"] as? String == "gemma4_text" else { + throw ProbeError("Gemma tensor parallel plan: expected a gemma4 wrapper around gemma4_text") + } + func integer(_ key: String) throws -> Int { + guard let number = text[key] as? NSNumber, CFNumberIsFloatType(number) == false, number.intValue > 0 else { + throw ProbeError("Gemma tensor parallel plan: text configuration lacks a positive \(key)") + } + return number.intValue + } + func flag(_ value: Any?) -> Bool? { + guard let number = value as? NSNumber, String(cString: number.objCType) == "c" else { return nil } + return number.boolValue + } + guard flag(text["tie_word_embeddings"]) ?? true, flag(root["tie_word_embeddings"]) ?? true else { + throw ProbeError("Gemma tensor parallel plan: only the tied head is covered") + } + guard flag(text["enable_moe_block"]) == true else { + throw ProbeError("Gemma tensor parallel plan: only the MoE text model is covered") + } + guard flag(text["attention_k_eq_v"]) == true else { + throw ProbeError("Gemma tensor parallel plan: full layers must reuse K as V") + } + guard (text["num_kv_shared_layers"] as? Int ?? 0) == 0, (text["hidden_size_per_layer_input"] as? Int ?? 0) == 0, + flag(text["attention_bias"]) != true else { + throw ProbeError("Gemma tensor parallel plan: shared KV, per-layer embeddings and attention biases are not covered") + } + hiddenSize = try integer("hidden_size") + layerCount = try integer("num_hidden_layers") + vocabularySize = try integer("vocab_size") + queryHeads = try integer("num_attention_heads") + slidingKVHeads = try integer("num_key_value_heads") + fullKVHeads = try integer("num_global_key_value_heads") + slidingHeadDim = try integer("head_dim") + fullHeadDim = try integer("global_head_dim") + denseWidth = try integer("intermediate_size") + expertWidth = try integer("moe_intermediate_size") + expertCount = try integer("num_experts") + expertsPerToken = try integer("top_k_experts") + guard expertsPerToken <= expertCount else { + throw ProbeError("Gemma tensor parallel plan: more experts per token than experts") + } + guard let types = text["layer_types"] as? [String], types.count == layerCount else { + throw ProbeError("Gemma tensor parallel plan: every layer needs an explicit attention kind") + } + layerKinds = try types.map { + guard let kind = LayerKind(rawValue: $0) else { + throw ProbeError("Gemma tensor parallel plan: unknown layer kind \($0)") + } + return kind + } + + guard let quantization = (root["quantization"] ?? root["quantization_config"]) as? [String: Any], + let group = quantization["group_size"] as? Int, let bits = quantization["bits"] as? Int, + (quantization["mode"] as? String ?? "affine") == "affine", [4, 8].contains(bits), [32, 64, 128].contains(group) else { + throw ProbeError("Gemma tensor parallel plan: requires an affine 4- or 8-bit quantized checkpoint") + } + groupSize = group + defaultBits = bits + let quantizedModules = Set(["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", + "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj", "router.proj", + "experts.switch_glu.gate_proj", "experts.switch_glu.up_proj", + "experts.switch_glu.down_proj"]) + var overrides: [String: Int] = [:] + for (key, value) in quantization where !["group_size", "bits", "mode"].contains(key) { + let prefix = "language_model.model.layers." + guard key.hasPrefix(prefix), let entry = value as? [String: Any], + Set(entry.keys).isSubset(of: ["group_size", "bits", "mode"]), + entry["group_size"] as? Int == group, let moduleBits = entry["bits"] as? Int, [4, 8].contains(moduleBits), + (entry["mode"] as? String ?? "affine") == "affine" else { + throw ProbeError("Gemma tensor parallel plan: quantization override \(key) is not an affine 4/8-bit entry of the default group size") + } + let rest = key.dropFirst(prefix.count) + guard let dot = rest.firstIndex(of: "."), let layer = Int(rest[.. String { "language_model.model.layers.\(layer)." } + + public func headDim(layer: Int) -> Int { layerKinds[layer] == .full ? fullHeadDim : slidingHeadDim } + public func kvHeads(layer: Int) -> Int { layerKinds[layer] == .full ? fullKVHeads : slidingKVHeads } + + /// Per layer, the KV heads one rank holds (26B: 4 sliding, 1 full). + public var kvHeadsPerRank: [Int] { (0 ..< layerCount).map { kvHeads(layer: $0) / size } } + public var queryHeadsPerRank: Int { queryHeads / size } + + /// Bits of a quantized module (`language_model.model.layers.N.mlp.down_proj`). + public func bits(forModule path: String) -> Int { overrideBits[path] ?? defaultBits } + + public func denseSplit(rank: Int) throws -> ChannelSplit { + try ChannelSplit(width: denseWidth, groupSize: groupSize, rank: rank) + } + + public func expertSplit(rank: Int) throws -> ChannelSplit { + try ChannelSplit(width: expertWidth, groupSize: groupSize, rank: rank) + } + + /// Vocabulary rows this rank's head projects. + public func vocabularyRange(rank: Int) -> Range { + let half = vocabularySize / size + return (rank * half) ..< ((rank + 1) * half) + } + + // MARK: - Collective facts + + /// Collectives per layer (the attention partial, the packed feed-forward) + /// and per decode step (the vocabulary-split selection). + public let reductionsPerLayer = 2 + public let reductionsPerStep = 1 + /// FP32 bytes one token's attention collective carries. + public var attentionPartialBytesPerToken: Int { hiddenSize * 4 } + /// FP32 bytes one token's packed feed-forward collective carries: every + /// selected expert's row and the dense branch's row. + public var feedForwardPartialBytesPerToken: Int { (expertsPerToken + 1) * hiddenSize * 4 } + public var layerPartialBytesPerToken: Int { attentionPartialBytesPerToken + feedForwardPartialBytesPerToken } + /// Collectives one forward issues. + public var reductionsPerForward: Int { reductionsPerLayer * layerCount } + + /// What two ranks must agree on before they serve together: the plan, + /// where each sum is taken and what it carries. A peer with any other + /// schedule refuses to load with this one. + public static let arithmeticAgreementFields = [ + name, + "gemma4-attention-f32-sum-before-post-attention-norm-v1", + "gemma4-dense-and-expert-f32-rows-one-collective-before-branch-norms-v1", + "gemma4-odd-group-channels-overlap-zero-padded-v1", + "gemma4-tied-head-vocabulary-halves-v1", + ] + + // MARK: - Configuration + + /// The text configuration `rank` constructs: half the query and KV heads + /// of each layer kind, the local channel widths. Everything else is whole. + public func shardTextConfiguration(_ text: [String: Any], rank: Int) throws -> [String: Any] { + var shard = text + shard["num_attention_heads"] = queryHeads / size + shard["num_key_value_heads"] = slidingKVHeads / size + shard["num_global_key_value_heads"] = fullKVHeads / size + shard["intermediate_size"] = try denseSplit(rank: rank).localWidth + shard["moe_intermediate_size"] = try expertSplit(rank: rank).localWidth + return shard + } + + // MARK: - Stored tensors + + /// True for the artifact's vision tower and its embedder, which no + /// tensor-parallel rank loads (the loader skips them; `cut` refuses them). + public static func isVisionTensor(_ key: String) -> Bool { + key.hasPrefix("vision_tower.") || key.hasPrefix("embed_vision.") || key.hasPrefix("multi_modal_projector.") + || key.hasPrefix("audio_tower.") || key.hasPrefix("embed_audio.") + } + + private static let replicatedLayerTensors: Set = [ + "input_layernorm.weight", "post_attention_layernorm.weight", "pre_feedforward_layernorm.weight", + "post_feedforward_layernorm.weight", "post_feedforward_layernorm_1.weight", + "pre_feedforward_layernorm_2.weight", "post_feedforward_layernorm_2.weight", "layer_scalar", + "router.scale", "router.per_expert_scale", "self_attn.q_norm.weight", "self_attn.k_norm.weight", + ] + + /// The cut of one stored text tensor (`language_model.` keys, as the + /// registered checkpoints store them) for `rank`. Unknown, vision and + /// untied-head tensors throw. + public func cut(key: String, rank: Int) throws -> Cut { + guard (0 ..< size).contains(rank) else { + throw ProbeError("Gemma tensor parallel plan: rank \(rank) is outside the group") + } + if Self.isVisionTensor(key) { + throw ProbeError("Gemma tensor parallel plan: vision tensors are not part of the tensor-parallel text model (\(key))") + } + if ["language_model.model.embed_tokens.weight", "language_model.model.embed_tokens.scales", + "language_model.model.embed_tokens.biases", "language_model.model.norm.weight"].contains(key) { + return .replicate + } + let prefix = "language_model.model.layers." + guard key.hasPrefix(prefix) else { throw ProbeError("Gemma tensor parallel plan: unknown checkpoint key \(key)") } + let rest = key.dropFirst(prefix.count) + guard let dot = rest.firstIndex(of: "."), let layer = Int(rest[..= 2, ["weight", "scales", "biases"].contains(parts.last!) else { + throw ProbeError("Gemma tensor parallel plan: unknown layer key \(key)") + } + let module = parts.dropLast().joined(separator: ".") + let full = layerKinds[layer] == .full + let headDim = self.headDim(layer: layer) + let queries = queryHeads / size, kv = self.kvHeads(layer: layer) / size + switch module { + case "router.proj": + return .replicate + case "self_attn.q_proj": + return .rows((rank * queries * headDim) ..< ((rank + 1) * queries * headDim), zeroBefore: 0, zeroAfter: 0) + case "self_attn.k_proj": + return .rows((rank * kv * headDim) ..< ((rank + 1) * kv * headDim), zeroBefore: 0, zeroAfter: 0) + case "self_attn.v_proj" where !full: + return .rows((rank * kv * headDim) ..< ((rank + 1) * kv * headDim), zeroBefore: 0, zeroAfter: 0) + case "self_attn.o_proj": + return .inputColumns((rank * queries * headDim) ..< ((rank + 1) * queries * headDim)) + case "mlp.gate_proj", "mlp.up_proj": + let split = try denseSplit(rank: rank) + return .rows(split.channels, zeroBefore: split.zeroBefore, zeroAfter: split.zeroAfter) + case "mlp.down_proj": + return .inputColumns(try denseSplit(rank: rank).storedColumns) + case "experts.switch_glu.gate_proj", "experts.switch_glu.up_proj": + let split = try expertSplit(rank: rank) + return .expertRows(split.channels, zeroBefore: split.zeroBefore, zeroAfter: split.zeroAfter) + case "experts.switch_glu.down_proj": + return .expertInputColumns(try expertSplit(rank: rank).storedColumns) + default: + throw ProbeError("Gemma tensor parallel plan: unknown layer key \(key)") + } + } + + /// The stored shape the plan expects for a text tensor of the whole + /// model (affine packing: `in / (32 / bits)` words, `in / group` scales). + public func expectedShape(key: String) throws -> [Int] { + if key.hasPrefix("language_model.model.embed_tokens.") { + return try packed(key, [vocabularySize, hiddenSize], bits: defaultBits) + } + if key == "language_model.model.norm.weight" { return [hiddenSize] } + let prefix = "language_model.model.layers." + guard key.hasPrefix(prefix) else { throw ProbeError("Gemma tensor parallel plan: unknown checkpoint key \(key)") } + let rest = key.dropFirst(prefix.count) + guard let dot = rest.firstIndex(of: "."), let layer = Int(rest[.. [Int] { + guard let last = logical.last else { throw ProbeError("Gemma tensor parallel plan: empty shape for \(key)") } + let leaf = key.split(separator: ".").last.map(String.init) ?? "" + switch leaf { + case "weight": return logical.dropLast() + [last / (32 / bits)] + case "scales", "biases": return logical.dropLast() + [last / groupSize] + default: throw ProbeError("Gemma tensor parallel plan: unknown quantized leaf in \(key)") + } + } + + /// The shape one rank stores for a text tensor of `shape` under `cut`, + /// refusing a cut that leaves the tensor or splits a packed word or group. + public func localShape(key: String, shape: [Int], cut: Cut) throws -> [Int] { + let leaf = key.split(separator: ".").last.map(String.init) ?? "" + let module = key.split(separator: ".").dropLast().joined(separator: ".") + let divisor = leaf == "weight" ? 32 / bits(forModule: module) : groupSize + var local = shape + switch cut { + case .replicate: + return shape + case .rows(let range, let before, let after): + guard !shape.isEmpty, range.lowerBound >= 0, range.upperBound <= shape[0], !range.isEmpty else { + throw ProbeError("Gemma tensor parallel plan: rows \(range) do not fit \(key) \(shape)") + } + local[0] = before + range.count + after + case .inputColumns(let logical): + guard shape.count == 2, ["weight", "scales", "biases"].contains(leaf), + logical.lowerBound % groupSize == 0, logical.upperBound % groupSize == 0, + logical.lowerBound % divisor == 0, logical.upperBound % divisor == 0, + logical.upperBound / divisor <= shape[1] else { + throw ProbeError("Gemma tensor parallel plan: columns \(logical) split a group or word of \(key) \(shape)") + } + local[1] = logical.count / divisor + case .expertRows(let range, let before, let after): + guard shape.count == 3, range.lowerBound >= 0, range.upperBound <= shape[1], !range.isEmpty else { + throw ProbeError("Gemma tensor parallel plan: expert rows \(range) do not fit \(key) \(shape)") + } + local[1] = before + range.count + after + case .expertInputColumns(let logical): + guard shape.count == 3, ["weight", "scales", "biases"].contains(leaf), + logical.lowerBound % groupSize == 0, logical.upperBound % groupSize == 0, + logical.lowerBound % divisor == 0, logical.upperBound % divisor == 0, + logical.upperBound / divisor <= shape[2] else { + throw ProbeError("Gemma tensor parallel plan: expert columns \(logical) split a group or word of \(key) \(shape)") + } + local[2] = logical.count / divisor + } + return local + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift new file mode 100644 index 0000000000..4992c26f1b --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPrefix.swift @@ -0,0 +1,407 @@ +import DarkbloomClusterProtocol +import Foundation +import MLX +import MLXLMCommon + +/// One Gemma 4 tensor-parallel rank's prompt prefixes: the Gemma pipeline's +/// memory tier (`QwenStagePrefixCache`) and, when the owner configured one, +/// its encrypted SSD tier (`QwenStagePrefixDiskTier`, `cache.disk`), holding +/// only this rank's own KV heads of every layer (26B: 4 sliding, 1 full). +/// +/// The pipeline's frontiers and record shape: a request keeps its state at +/// chunk-grid boundaries strictly before the prompt end, on the cache's +/// stride (`QwenLayerStageGenerationRequest.prefixCaptureFrontiers`), the +/// deepest first and then the deepest grid boundaries its capture limit +/// holds; full-attention rows are copied once, at the deepest boundary, and +/// each sliding layer's window at every kept boundary, in the recurrent +/// slots (`QwenLayerStageSession.capturePrefix`). Entries are inserted only +/// after the request retired cleanly on both ranks, and written to the SSD +/// tier behind serving. +/// +/// Both ranks key a boundary identically: the load agreement and the +/// request's chunk grid (and on SSD the persistent plan scope), in the +/// request's tenant partition (`ClusterWorkerPrefixCache.scope`). Nothing is +/// assumed: the ranks vote every capture-grid boundary of the prompt in one +/// sealed sum (`QwenTensorParallelPrefixCache.offer`: 1 in memory, 3 only on +/// SSD), take the deepest both offer, read it from their own tiers, and a +/// second sealed sum (`QwenTensorParallelPrefixCache.confirm`) shows both +/// read it before either writes a page; otherwise both prefill from zero. +final class Gemma4TensorParallelPrefix { + let cache: QwenStagePrefixCache + /// The resident scope's base: the pair's load agreement. + let load: String + /// The SSD tier's persistent scope (`planScope`); nil without the tier. + let diskPlanScope: String? + + init(cache: QwenStagePrefixCache, load: String, diskPlanScope: String?) { + self.cache = cache; self.load = load; self.diskPlanScope = cache.disk == nil ? nil : diskPlanScope + } + + var disk: QwenStagePrefixDiskTier? { cache.disk } + + /// Everything a restored state's bytes depend on that each rank knows at + /// load, never the membership epoch, so a restarted pair finds what the + /// last one kept: the plan and its arithmetic terms, the prompt policy, + /// the arithmetic receipt and profile, the verified artifact and storage, + /// and both ranks' builds. + static func planScope(admission: Gemma4ResidentAdmission, aggregateSHA256: String, + storageCommitmentSHA256: String) -> String { + QwenStagePrefixDiskTier.planScope( + planFingerprint: ([Gemma4TensorParallelPlan.name, "shares=1:1", "arithmetic=" + admission.arithmeticSHA256, + "profile=" + admission.profile.fingerprint] + + Gemma4TensorParallelLoadAgreement.termsFields + Gemma4TensorParallelLoadAgreement.promptPolicyFields) + .joined(separator: "|"), + artifactAggregateSHA256: aggregateSHA256, storageCommitmentSHA256: storageCommitmentSHA256, + rankBuildSHA256: admission.configuration.identity.peers.map(\.buildSHA256), + generationMode: ClusterGenerationMode.tensorParallel.rawValue, prefillSchedule: "serial|gemma4-tp-prefix-v1") + } + + /// A request's partition of each tier; nil when it keeps no prefix (the + /// cache off on this rank or for the request). Both ranks derive the + /// same value from the request and load they agreed. + struct Scopes: Equatable { + let resident: String + let disk: String? + } + + func scopes(_ request: QwenLayerStageGenerationRequest) -> Scopes? { + guard cache.enabled, + let resident = ClusterWorkerPrefixCache.scope(load + "|gemma4-tp-prefix-v1|chunk=\(request.chunkSize)", + request.prefixCache) else { return nil } + let disk = diskPlanScope.flatMap { + ClusterWorkerPrefixCache.scope($0 + "|chunk=\(request.chunkSize)|kv=paged", request.prefixCache) + } + return Scopes(resident: resident, disk: disk) + } + + /// The boundaries a state of `request` may be kept at and is voted on: + /// every multiple of the cache's stride (whole chunks) before the + /// prompt's final token. + func candidates(_ request: QwenLayerStageGenerationRequest) -> [Int] { + let step = cache.stride(chunkSize: request.chunkSize) + guard request.promptCount > step else { return [] } + return Array(Swift.stride(from: step, through: request.promptCount - 1, by: step)) + } + + /// Both ranks: one sealed sum of this rank's offer for every candidate. + /// The deepest boundary both offer, and whether either offers it only + /// from SSD; nil when none (both then prefill from zero). + func vote(_ request: QwenLayerStageGenerationRequest, scopes: Scopes, candidates: [Int], + group: any QwenTensorParallelReduction) throws -> (boundary: Int, ssd: Bool)? { + guard group.size == 2, !candidates.isEmpty else { throw ProbeError("The Gemma tensor-parallel prefix vote takes two ranks") } + let prompt = request.promptTokenIDs + let held = Set(cache.frontiers(scope: scopes.resident, tokens: prompt, maximumFrontier: request.promptCount - 1)) + let onDisk = scopes.disk.flatMap { scope in + disk.map { Set($0.frontiers(scope: scope, tokens: prompt, maximumFrontier: request.promptCount - 1)) } + } ?? [] + let offers = candidates.map { QwenTensorParallelPrefixCache.offer(inMemory: held.contains($0), onDisk: onDisk.contains($0)) } + let summed = group.allSum(MLXArray(offers)) + try MLX.withError { error in eval(summed); try error.check() } + let sums = summed.asArray(Float.self) + guard sums.count == candidates.count else { throw ProbeError("The Gemma tensor-parallel prefix vote changed shape") } + return QwenTensorParallelPrefixCache.agreed(sums: sums, candidates: candidates) + } + + /// This rank's state at the agreed `boundary`: from memory when it holds + /// it there (the record of the same boundary is touched), else read from + /// its SSD record and checked to adopt (`adopts`) before anything is + /// written; nil when this rank cannot restore it (an unreadable record is + /// deleted by the tier, one that does not adopt here). Only a failed + /// `check` throws. + func read(_ boundary: Int, request: QwenLayerStageGenerationRequest, scopes: Scopes, + geometry: CBv2RequestGeometry, check: () throws -> Void) throws -> (state: QwenStagePrefixState, tier: String)? { + let prompt = request.promptTokenIDs + if let state = cache.state(scope: scopes.resident, tokens: prompt, frontier: boundary) { + if let diskScope = scopes.disk { disk?.touch(scope: diskScope, tokens: prompt, frontier: boundary) } + return Self.adopts(state, into: geometry) ? (state, "resident") : nil + } + guard let disk, let diskScope = scopes.disk, + let state = try disk.restore(scope: diskScope, tokens: prompt, frontier: boundary, check: check) else { + return nil + } + guard Self.adopts(state, into: geometry) else { + log("darkbloom-prefix-ssd-v1 rank=\(disk.rank) event=restore-rejected frontier=\(boundary) reason=not_adoptable") + disk.forget(scope: diskScope, tokens: prompt, frontier: boundary) + return nil + } + return (state, "ssd") + } + + /// Whether `state` adopts into a request of `geometry` exactly as + /// `CBv2OwnedRequestState` adopts it: every full-attention layer's rows + /// at the boundary and every sliding layer's window, with this rank's + /// head counts, widths and element type, nothing else. + static func adopts(_ state: QwenStagePrefixState, into geometry: CBv2RequestGeometry) -> Bool { + let committed = state.committedTokens + guard committed > 0, state.speculativeHistory == nil, geometry.recurrent.layers.isEmpty, + state.attention.count + state.recurrent.count == geometry.kinds.count else { return false } + for kind in geometry.kinds { + guard let layer = kind.modelLayerIndex else { return false } + let shape = [1, kind.kvHeads, kind.retainedTokens(atFrontier: committed), kind.headDim] + let pair: (keys: MLXArray, values: MLXArray)? + if case .slidingWindow = kind.attention { + pair = state.recurrent[layer].map { (keys: $0.conv, values: $0.ssm) } + } else { + pair = state.attention[layer] + } + guard let pair, pair.keys.shape == shape, pair.values.shape == shape, + pair.keys.dtype == geometry.kvDType, pair.values.dtype == geometry.kvDType else { return false } + } + return true + } + + /// Opens `request`'s session on this rank, both ranks alike: with the + /// cache on and a prompt longer than one stride, one sealed vote and, on + /// an agreed boundary, each rank reads it from its own tiers (`read`) and + /// restores it into a new session, then one sealed confirmation: unless + /// both restored, both discard what they restored and prefill from zero. + /// A state read from SSD becomes resident here, confirmed or not (it is + /// this rank's valid state there), so the next offer finds it in memory. + /// `captureLimit`: what this request's capture may hold (0 keeps none). + /// `stop`: a cancel or deadline while a record is read declines it. + func open(_ request: QwenLayerStageGenerationRequest, model: Gemma4TensorParallelModel, host: CBv2StageKVHost, + group: any QwenTensorParallelReduction, captureLimit: Int, stop: @escaping () -> Bool = { false }) + throws -> Gemma4TensorParallelPagedSession { + let rank = group.rank, prompt = request.promptTokenIDs + var restored: Gemma4TensorParallelPagedSession?, tier: String?, agreed = 0 + let scopes = scopes(request) + if let scopes, case let candidates = candidates(request), !candidates.isEmpty, + let vote = try vote(request, scopes: scopes, candidates: candidates, group: group) { + agreed = vote.boundary + struct Stopped: Error {} + var local: (state: QwenStagePrefixState, tier: String)? + do { + let geometry = try Gemma4TensorParallelPagedSession.geometry(model: model, host: host, + maximumTokens: request.maximumTokens) + local = try read(vote.boundary, request: request, scopes: scopes, geometry: geometry, + check: { if stop() { throw Stopped() } }) + } catch is Stopped { + local = nil + } + if let local { + do { + restored = try Gemma4TensorParallelPagedSession(model: model, host: host, + promptCount: request.promptCount, outputCount: request.outputCount, restoring: local.state) + tier = local.tier + } catch { + // This rank could not restore; the confirmation says so. + log("darkbloom-prefix-v1 rank=\(rank) family=gemma4 restore-failed frontier=\(vote.boundary): \(error)") + if local.tier == "ssd", let diskScope = scopes.disk { + disk?.forget(scope: diskScope, tokens: prompt, frontier: vote.boundary) + } + } + } + let both: Bool + do { both = try QwenTensorParallelPrefixCache.confirm(restored != nil, group: group) } catch { + try? restored?.retire(failed: true) + throw error + } + if let local, local.tier == "ssd", restored != nil { + cache.insert(scope: scopes.resident, tokens: prompt, states: [local.state], sharedBytes: local.state.sharedBytes) + } + if !both { + log("darkbloom-prefix-ssd-v1 rank=\(rank) event=restore-declined frontier=\(vote.boundary)" + + " tier=\(tier ?? "none") local=\(restored != nil ? 1 : 0) kept=\(tier == "ssd" ? 1 : 0)") + try restored?.retire() + restored = nil; tier = nil + } + } + let session = try restored ?? Gemma4TensorParallelPagedSession(model: model, host: host, + promptCount: request.promptCount, outputCount: request.outputCount) + if scopes != nil, captureLimit > 0 { + // The pipeline's rule for chunk-grid families: existing grid ends after + // the restored prefix, strictly before the prompt end. + let step = cache.stride(chunkSize: request.chunkSize) + let frontiers = Set(Swift.stride(from: (session.reusedPrefixTokens / step + 1) * step, + to: request.promptCount, by: step)) + if !frontiers.isEmpty { + session.prefixCapture = .init(frontiers: frontiers, limitBytes: captureLimit, + maximumFrontiers: cache.frontiersPerPrompt) + } + } + if agreed > 0 { + log("darkbloom-prefix-v1 rank=\(rank) family=gemma4 mode=tensor_parallel agreed=\(agreed)" + + " reused=\(session.reusedPrefixTokens) prompt=\(request.promptCount) tier=\(tier ?? "none")") + } + return session + } + + /// What `request`'s capture may hold on this rank: what its own charge + /// covers (`chargedBytes`, its capture at its deepest boundary) whatever + /// the tier's budget, or the pipeline's limit where larger + /// (`QwenStagePrefixCache.captureLimit`: after the deepest prefix this + /// rank holds for it, at the measured cost, within the budget); 0 when it + /// keeps no prefix. A tier the measured room leaves without budget keeps + /// nothing resident, but the charged capture still reaches the SSD tier. + func captureLimit(_ request: QwenLayerStageGenerationRequest, chargedBytes: Int = 0) -> Int { + guard let scopes = scopes(request) else { return 0 } + return max(chargedBytes, + cache.captureLimit(scope: scopes.resident, tokens: request.promptTokenIDs, chunkSize: request.chunkSize)) + } + + /// After a request retired cleanly on both ranks: its capture becomes + /// reusable in memory and is written to the SSD tier behind serving. + /// Returns the boundaries kept. + @discardableResult + func store(_ capture: Gemma4TensorParallelPrefixCapture, request: QwenLayerStageGenerationRequest, scopes: Scopes, + rank: Int) -> [Int] { + defer { capture.discard() } + let states = capture.states() + guard !states.isEmpty else { return [] } + let prompt = request.promptTokenIDs + cache.insert(scope: scopes.resident, tokens: prompt, states: states, sharedBytes: capture.sharedBytes) + if let diskScope = scopes.disk { + disk?.persist(scope: diskScope, tokens: prompt, states: states, blockTokens: cache.stride(chunkSize: request.chunkSize)) + } + if let cost = capture.cost { cache.record(cost) } + log("darkbloom-prefix-v1 rank=\(rank) family=gemma4 mode=tensor_parallel held_bytes=\(cache.bytesInUse)" + + " budget_bytes=\(cache.budgetBytes) capture_limit=\(capture.limitBytes) captured_shared=\(capture.sharedBytes)" + + " stored=\(states.map { String($0.committedTokens) }.joined(separator: ","))") + return states.map(\.committedTokens) + } +} + +extension Gemma4TensorParallelModel { + /// Oracles and tests: what a rank's prompt-prefix memory tier gives a + /// repeated prompt, on this shard's own paged host. `prompt` is served + /// cold and keeps its boundaries (every `chunk`), then `repeated` (by + /// default the same prompt) votes, restores the deepest boundary both + /// ranks hold and continues from it, as the resident runtime serves it. + /// Both ranks call it with the same values. + public func generatePagedRepeatingPrefix(prompt: [Int], repeated: [Int]? = nil, outputCount: Int, chunk: Int, + recordTop: Int = 0) + throws -> (cold: Generation, restored: Generation, reusedPromptTokens: Int, storedFrontiers: [Int]) { + let second = repeated ?? prompt + guard case .shard = role, let reduction, !prompt.isEmpty, !second.isEmpty, outputCount >= 1, chunk >= 1, + (prompt + second).allSatisfy({ (0 ..< plan.vocabularySize).contains($0) }), (0 ... 64).contains(recordTop) else { + throw ProbeError("Gemma tensor-parallel prefix oracle: a shard, two prompts in the vocabulary, bounded options") + } + let longest = max(prompt.count, second.count) + let activation = String(describing: activationDType) + let profile = try QwenLayerStageGenerationProfile(identifier: "gemma4-tensor-parallel-prefix", + vocabularySize: plan.vocabularySize, hiddenSize: plan.hiddenSize, activationDType: activation, + maximumPromptTokens: longest, maximumChunkTokens: chunk, maximumOutputTokens: outputCount, + maximumContextTokens: longest + outputCount, logitsDType: activation == "float32" ? nil : "float32") + let prefix = Gemma4TensorParallelPrefix(cache: QwenStagePrefixCache(strideTokens: chunk), + load: "gemma4-tensor-parallel-prefix-oracle|" + Gemma4TensorParallelPlan.name, diskPlanScope: nil) + let host = try pagedHost(lanes: 1, maximumTokens: longest + outputCount, chunkTokens: chunk) + func serve(_ tokens: [Int], index: Int) throws -> (generation: Generation, reused: Int, stored: [Int]) { + let request = try QwenLayerStageGenerationRequest(profile: profile, + requestID: UUID(uuidString: String(format: "00000000-0000-4000-8000-%012d", index))!, + promptTokenIDs: tokens, chunkSize: chunk, outputCount: outputCount, stopTokenIDs: []) + let session = try MLX.withError { error -> Gemma4TensorParallelPagedSession in + let value = try prefix.open(request, model: self, host: host, group: reduction, + captureLimit: prefix.captureLimit(request)) + try error.check() + return value + } + let generation = try generatePaged(session: session, host: host, prompt: tokens, outputCount: outputCount, + chunk: chunk, recordTop: recordTop) + var stored: [Int] = [] + if let capture = session.prefixCapture, let scopes = prefix.scopes(request) { + stored = prefix.store(capture, request: request, scopes: scopes, rank: reduction.rank) + } + return (generation, session.reusedPrefixTokens, stored) + } + let cold = try serve(prompt, index: 0) + let restored = try serve(second, index: 1) + return (cold.generation, restored.generation, restored.reused, cold.stored) + } +} + +/// One request's prefix capture on a Gemma 4 tensor-parallel rank: the +/// boundaries it was asked to keep, what it keeps within its limit (measured +/// at its first boundary, `QwenStagePrefixCaptureCost.kept`), and the copies, +/// as the pipeline's stage session keeps them (`QwenLayerStageSession.capturePrefix`). +final class Gemma4TensorParallelPrefixCapture { + let frontiers: Set + let limitBytes: Int + let maximumFrontiers: Int + private(set) var cost: QwenStagePrefixCaptureCost? + private var kept: Set? + private(set) var withdrawn = false + /// Each kept boundary's sliding windows, keyed by layer. + private var windows: [Int: [Int: (conv: MLXArray, ssm: MLXArray)]] = [:] + /// Full-attention rows copied once, at the deepest boundary. + private var deepest: (committed: Int, layers: [Int: (keys: MLXArray, values: MLXArray)])? + + init(frontiers: Set, limitBytes: Int, maximumFrontiers: Int) { + self.frontiers = frontiers; self.limitBytes = max(0, limitBytes); self.maximumFrontiers = maximumFrontiers + } + + /// After the prompt chunk that committed `frontier` (`state` is the + /// request's). A sliding row holds only its window, oldest first: its + /// state at a boundary is its own and is copied now (the ring takes + /// later tokens in place); full rows are copied at the deepest boundary. + func capture(_ state: CBv2OwnedRequestState, at frontier: Int) throws { + guard frontiers.contains(frontier), !withdrawn else { return } + guard state.committedTokens == frontier else { throw ProbeError("Gemma tensor-parallel prefix capture differs from the committed frontier") } + var rows: [Int: (keys: MLXArray, values: MLXArray)] = [:] + var tails: [Int: (keys: MLXArray, values: MLXArray)] = [:], windowBytes = 0 + for (position, optionalRow) in state.rows.enumerated() { + let kind = state.geometry.kinds[position] + guard let row = optionalRow, let layer = kind.modelLayerIndex else { + throw ProbeError("Gemma tensor-parallel prefix capture lacks an attention row") + } + let snapshot = row.snapshot() + let retained = kind.retainedTokens(atFrontier: frontier) + guard snapshot.offset == frontier, snapshot.keys.dim(2) == retained, retained > 0 else { + throw ProbeError("Gemma tensor-parallel prefix capture frontier differs from a row's") + } + if case .slidingWindow(let window) = kind.attention { + tails[layer] = (snapshot.keys, snapshot.values) + // Every boundary is charged a full window: one taken before the + // prompt filled it is shorter than every later one. + let perPosition = (snapshot.keys.nbytes + snapshot.values.nbytes + retained - 1) / retained + windowBytes = try QwenLongPrefillCheckedBytes.sum([windowBytes, + try QwenLongPrefillCheckedBytes.product([perPosition, window])]) + } else { + rows[layer] = (snapshot.keys, snapshot.values) + } + } + let planned = frontiers.sorted() + if kept == nil { + let attention = rows.values.reduce(0) { $0 + $1.keys.nbytes + $1.values.nbytes } + let measured = QwenStagePrefixCaptureCost(attentionBytesPerToken: (attention + frontier - 1) / frontier, + recurrentBytesPerFrontier: windowBytes, historyBytesPerToken: 0) + cost = measured + kept = measured.kept(planned, limit: limitBytes, maximum: maximumFrontiers) + } + guard kept?.contains(frontier) == true else { return } + func copy(_ value: MLXArray) -> MLXArray { value * MLXArray(1).asType(value.dtype) } + let own = tails.mapValues { (conv: copy($0.keys), ssm: copy($0.values)) } + eval(own.values.flatMap { [$0.conv, $0.ssm] }) + windows[frontier] = own + guard frontier == planned.last else { return } + let copies = rows.mapValues { (keys: copy($0.keys), values: copy($0.values)) } + eval(copies.values.flatMap { [$0.keys, $0.values] }) + deepest = (frontier, copies) + } + + /// The kept boundaries' states, ascending, each viewing the one copy of + /// the full rows; empty unless the deepest was reached. + func states() -> [QwenStagePrefixState] { + guard let deepest, !withdrawn else { return [] } + return windows.keys.sorted().compactMap { frontier in + guard frontier <= deepest.committed, let own = windows[frontier] else { return nil } + let rows = deepest.layers.mapValues { pair -> (keys: MLXArray, values: MLXArray) in + frontier == deepest.committed ? pair + : (keys: pair.keys[0..., 0..., 0 ..< frontier, 0...], values: pair.values[0..., 0..., 0 ..< frontier, 0...]) + } + return QwenStagePrefixState(committedTokens: frontier, attention: rows, recurrent: own) + } + } + + /// Bytes of the full-row copy the kept states view together. + var sharedBytes: Int { deepest?.layers.values.reduce(0) { $0 + $1.keys.nbytes + $1.values.nbytes } ?? 0 } + + /// Bytes this capture holds now. + var heldBytes: Int { + sharedBytes + windows.values.reduce(0) { total, own in total + own.values.reduce(0) { $0 + $1.conv.nbytes + $1.ssm.nbytes } } + } + + /// The running check withdrew it: let go of what it holds, capture no more. + func withdraw() { withdrawn = true; windows.removeAll(); deepest = nil } + + func discard() { windows.removeAll(); deepest = nil; kept = nil } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift new file mode 100644 index 0000000000..b3fa291709 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift @@ -0,0 +1,156 @@ +import DarkbloomClusterProtocol +import Foundation +import MLX + +/// One request on one rank of a Gemma 4 tensor-parallel pair, as the resident +/// runtime serves it alone: the prompt in chunks of the request's own size +/// (from a restored prefix's boundary, when both ranks restored one), then +/// one decode step a token. Each step's token and both ranks' stop flags +/// are agreed in the step's own evaluation (`Gemma4TensorParallelChoice`); +/// both ranks submit the same collectives in the same order whatever either +/// decides, and end after the same step. +/// +/// Rank 0 publishes each token at once and reads the owner's answer to it +/// after the next step ran; a stop answer is acted on one step later (the +/// extra step is computed and never published). A stop on either rank +/// (`localStop`: cancel, deadline, memory; or pages that could not grow) +/// rides in the next step's flags. A rank that stopped commits nothing more +/// but still ends at a stop token its peer commits, so both leave after the +/// same step. At the end rank 0's count and finish cross in one small +/// agreement (`exchange`) and rank 1 adopts them +/// (`QwenTensorParallelStopRule.reconcile`), as GLM's tensor parallel does. +struct Gemma4TensorParallelRequestLoop { + let session: Gemma4TensorParallelPagedSession + let request: QwenLayerStageGenerationRequest + let choice: Gemma4TensorParallelChoice + /// Every rank's integers summed, evaluated now (each rank fills its own + /// slots, the others zero): `QwenTensorParallelGroup.exchangeIntegers`. + let exchange: ([Int32]) throws -> [Int32] + /// This rank wants to stop now (checked after each committed token). + let localStop: () -> Bool + + struct Outcome { + var tokens: [Int] + var finish: ClusterWorkerFinishReason + /// The owner answered a token with stop. + var clientStopped: Bool + var pagesRefused: Bool + } + + func run(channel: ClusterCommittedTokenChannel, check: () throws -> Void) throws -> Outcome { + let rank = choice.rank, prompt = request.promptTokenIDs + let sampler = choice.sampler + // A restored prefix ends on the chunk grid: the rest runs the chunks a cold request runs there. + var offset = session.committedTokens + var current: (logits: MLXArray, selected: MLXArray)? + while offset < prompt.count { + let end = min(prompt.count, offset + request.chunkSize) + current = try session.prefill(prompt, range: offset ..< end, check: check) { choice.build($0, stop: 0) } ?? current + offset = end + } + guard var step = current else { throw ProbeError("Gemma tensor-parallel prompt produced no logits") } + var tokens: [Int] = [] + var finish: ClusterWorkerFinishReason = .length + var clientStopped = false + var stopKeep: Float = 0 + var pagesRefused = false + var unanswered = false + func readAnswer() throws { + guard unanswered else { return } + unanswered = false + if try !channel.answer(), stopKeep == 0 { clientStopped = true; stopKeep = Float(tokens.count) } + } + let logprobCount = sampler?.wire.capturedLogprobs + /// Commits one agreed token on this rank (and publishes it on rank 0): + /// the request's own end at it (EOS or length), else nil. + func commit(_ value: Int, logprobs: ClusterWorkerTokenLogprobs?) throws -> ClusterWorkerFinishReason? { + tokens.append(value) + if rank == 0 { + try channel.publishToken(tokens.count - 1, value, prompt.count + tokens.count - 1, logprobs) + unanswered = true + } + switch QwenTensorParallelStopRule.outcome(isStopToken: request.stopTokenIDs.contains(value), + committed: tokens.count, outputCount: request.outputCount, wanted: true) { + case .eos: return .eos + case .length: return .length + case .clientStop, .proceed: return nil + } + } + try GPU.withCommandBufferLimits(Gemma4TensorParallelModel.decodeCommandBuffers) { + steps: for index in 0 ..< request.outputCount { + // The answer to the last token arrived while this step ran. + if stopKeep == 0 { try readAnswer() } + let agreed = try choice.read(step.selected) + if let slot = agreed.flags.filter({ $0 > 0 }).min() { + // A rank asked both to stop: both keep the tokens it named + // and end here (at the request's length when its pages could not grow). + let stop = QwenTensorParallelStopRule.stop(slot: slot) + tokens = Array(tokens.prefix(stop.keep)) + finish = stop.finish == .length ? .length : .clientStop + break steps + } + // A greedy step's logprobs come from the split top-k gather, a + // collective every rank takes; a sampled one's from rank 0's draw. + var logprobs: ClusterWorkerTokenLogprobs? + if let count = logprobCount { + if choice.gathersRow { + if rank == 0, stopKeep == 0 { + guard let drawn = sampler?.takePendingLogprobs() else { + throw ProbeError("Gemma tensor-parallel token has no logprobs") + } + logprobs = drawn + } + } else { + let gathered = try choice.logprobs(step.logits, token: agreed.token, maximum: agreed.maximum, + count: count) + logprobs = rank == 0 ? gathered : nil + } + } + if stopKeep == 0 { + sampler?.commit(agreed.token) + if let end = try commit(agreed.token, logprobs: logprobs) { finish = end; break steps } + if localStop() { + stopKeep = Float(tokens.count) + } else if pagesRefused { + stopKeep = QwenTensorParallelStopRule.lengthStop(keep: tokens.count) + } + } else if request.stopTokenIDs.contains(agreed.token) { + // The owner's stop was read after this step ran, so only the + // next step could carry it; the peer ends at this token. + break steps + } + guard index + 1 < request.outputCount else { break steps } + // Pages grow a granule ahead, at least a margin before they are + // needed: a growth the pool refuses still leaves this step its + // row, and the step carries the length stop (rank-local; the + // collectives are the same either way). + if !pagesRefused { + pagesRefused = !session.reservePages(writing: 1) + if pagesRefused, stopKeep == 0 { stopKeep = QwenTensorParallelStopRule.lengthStop(keep: tokens.count) } + } + step = try session.decode(agreed.token, check: check) { choice.build($0, stop: stopKeep) } + } + } + // The owner answers every published token, the last one too. A stop + // answer to a token the request ended at changes nothing. + if unanswered { + unanswered = false + if try !channel.answer(), finish == .clientStop { clientStopped = true } + } + if clientStopped || (stopKeep > 0 && stopKeep < QwenTensorParallelStopRule.lengthStopBase) { finish = .clientStop } + let localFinish: QwenTensorParallelStopRule.Finish = finish == .eos ? .eos : finish == .length ? .length : .clientStop + let agreedEnd = try exchange(rank == 0 ? [Int32(tokens.count), localFinish.code] : [0, 0]) + guard agreedEnd.count == 2, let rank0Finish = QwenTensorParallelStopRule.Finish(code: agreedEnd[1]) else { + throw ProbeError("Gemma tensor-parallel ranks did not agree how the request ended") + } + let ended = QwenTensorParallelStopRule.reconcile(rank: rank, localFinish: localFinish, localCount: tokens.count, + localStopped: stopKeep > 0 && !clientStopped, rank0Finish: rank0Finish, rank0Count: Int(agreedEnd[0])) + tokens = Array(tokens.prefix(ended.count)) + switch ended.finish { + case .eos: finish = .eos + case .length: finish = .length + case .clientStop: finish = .clientStop + } + return .init(tokens: tokens, finish: finish, clientStopped: clientStopped, pagesRefused: pagesRefused) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift new file mode 100644 index 0000000000..7637bdb5b6 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelResidentRuntime.swift @@ -0,0 +1,567 @@ +import DarkbloomClusterProtocol +import DarkbloomClusterSecurity +import Foundation +import MLX +import MLXLMCommon + +/// The worker's resident owner for `tensor_parallel_v1` on the registered +/// Gemma 4 26B rows: both ranks hold every layer, each with its half of every +/// head- and channel-parallel weight (`Gemma4TensorParallelPlan`), run every +/// prompt chunk and decode step together, and sum each layer's attention +/// partial and its one packed feed-forward collective (FP32 partials, +/// `ClusterTensorParallelTerms.current`) with the sealed all-sum inside the +/// lazy graph, under the session's keyed data plane. +/// +/// The same executor contract as `GLM5NextTensorParallelResidentRuntime`: +/// one request at a time, cancel from the control thread, an enclosing +/// process deadline required; or, loaded with batch lanes (`lanes`, from +/// `DARKBLOOM_CLUSTER_BATCH_LANES`), several requests at once through the +/// shared batch driver (`Gemma4TensorParallelLanes.swift`). Each request's +/// keys and values live in this rank's paged KV host, its own heads of every +/// layer (`Gemma4TensorParallelPagedSession`); pages grow with the request. +/// +/// Every step's token is agreed inside the step's own evaluation +/// (`Gemma4TensorParallelChoice`): the vocabulary-split argmax for greedy +/// requests, carrying both ranks' stop flags; for sampled ones the whole row +/// gathered to every rank and rank 0's draw with the product's sampler. A +/// stop on either rank (cancel, deadline, memory, the owner's stop, pages +/// that could not grow) ends both after the same step. Logprobs: a greedy +/// request's from the vocabulary-split top-k gather, a sampled one's from the +/// product's sampler on rank 0. +/// +/// Prompt prefixes are kept as the Gemma pipeline keeps them, resident and on +/// the owner's encrypted SSD tier, each rank its own heads; a request +/// restores the deepest boundary both ranks hold after a sealed vote and +/// confirmation, or neither does (`Gemma4TensorParallelPrefix`). +/// +/// Not yet: speculative decoding and media. +public final class Gemma4TensorParallelResidentRuntime { + static let planName = Gemma4TensorParallelPlan.name + /// Bytes the worker keeps for MLX's freed-buffer cache once ready under + /// the product's `disableFreedBufferCache` policy (as Qwen tensor parallel). + static var freedBufferCacheBytes: Int { + QwenTensorParallelLaunch.freedBufferCacheBytes(allocatorHeadroomBytes: QwenDenseStageLoadPolicy.allocatorHeadroomBytes) + } + + let admission: Gemma4ResidentAdmission + let control: QwenResidentControl + let collective: Collective + let group: QwenTensorParallelGroup + let codec: QwenTensorParallelSealCodec + let lifecycle = QwenLayerStageResidentLifecycle() + let loadAgreement: String + let operation = NSLock() + private let keepWarm = ClusterKeepWarm() + var model: Gemma4TensorParallelModel? + var host: CBv2StageKVHost? + private let baseReady: ClusterWorkerReady + private var reservation: Reserved? + private var processLeaseOwned = true + public let linkProbe: ClusterWorkerLinkProbe? + public let shareProbe: ClusterWorkerShareProbe? + /// Requests served at once (bound into the load agreement); one serves + /// one request at a time through `reserve` and `start`. + public let lanes: Int + /// Batch lanes: every reserved, started and running lane on this rank. + let laneBook = ClusterBatchLaneBook() + /// True while the batch driver runs on the executor. + var batchServing = false + var batchOrdinal: UInt64 = 0 + /// A failed batch's driver, kept until shutdown's checked drain. + var failedLaneDriver: QwenTensorParallelBatchDriver>? + /// Raw-token logprobs are published for every request that asks for them. + public var capturesLogprobs: Bool { true } + /// This rank's prompt prefixes, in memory and on its SSD tier. + let prefix: Gemma4TensorParallelPrefix + + struct Reserved { + let request: QwenLayerStageGenerationRequest + let deadline: UInt64 + /// What this request's prefix capture may hold (0: none). + var prefixCaptureLimit = 0 + } + + // MARK: - Load + + /// Whether a registered row is a Gemma 4 artifact, whose tensor-parallel + /// loads this runtime owns (its catalog family is the layer-stage one). + public static func serves(runtimeModelID: String) -> Bool { + (try? Gemma4RegisteredSpecification.registered(runtimeModelID: runtimeModelID)) != nil + } + + /// `prefixSSDKey`: the 32-byte key of this rank's prompt-prefix SSD tier, + /// as the owner sent it on the worker's input; nil keeps the tier off. + public static func load(_ configuration: QwenResidentLoadConfiguration, + qualification: QwenResidentQualificationSwitches = .refused, + dataPlane credential: ClusterDataPlaneCredential, + prefixSSDKey: Data? = nil) throws -> Gemma4TensorParallelResidentRuntime { + let environment = ProcessInfo.processInfo.environment + try qualification.admit(environment: environment) + let kvQuantization = try PagedKVQuantizationSelection.clusterLive(environment) + try kvQuantization.requireNative("Gemma tensor parallel, whose paged KV stays native until it is qualified") + let kv = try ClusterStageKVBackendKind.fromEnvironment(environment) + let lanes = try QwenBatchSettings.fromEnvironment(environment).lanes + // Prompt prefixes, unless the diagnosis switch turns them off on this + // rank (`DARKBLOOM_CLUSTER_PREFIX_CACHE=off`): bound into the agreement, + // so both ranks keep them or neither does. Gemma records stay native. + let prefixCache = QwenStagePrefixCache.fromEnvironment(environment) + let keepsPrefixes = Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes && prefixCache.enabled + let prefixRecords = try QwenStagePrefixDiskEncoding.fromEnvironment(environment, family: .native) + let directory = configuration.modelDirectory + let any = try LayerStageResidentFamily.admission(configuration: configuration, + configBytes: BoundedProbeInput.data(directory.appendingPathComponent("config.json"), maximumBytes: 1_048_576), + manifestBytes: BoundedProbeInput.data(directory.appendingPathComponent("manifest.json"), maximumBytes: 4_194_304), + environment: environment, now: DispatchTime.now().uptimeNanoseconds, + read: { try BoundedProbeInput.data($0, maximumBytes: $1) }) + guard let admission = any as? Gemma4ResidentAdmission, + admission.supportedGenerationModes.contains(.tensorParallel) else { + throw ProbeError("Generation mode tensor_parallel_v1 is not in the resident row of \(any.runtimeModelID)") + } + guard configuration.prefillSchedule == .serial else { + throw ProbeError("Gemma tensor parallel prefills every chunk together: the serial schedule only") + } + let control = QwenResidentControl(deadline: configuration.deadlineUptimeNanoseconds, lease: configuration.lease) + try QwenResidentProcessLease.shared.acquire() + var loadedModel: Gemma4TensorParallelModel? + var loadedHost: CBv2StageKVHost? + weak var retired: Gemma4TensorParallelModel? + do { + try control.check(); try QwenResidentResourceEnvironment.require() + let read: (URL, Int) throws -> Data = { try BoundedProbeInput.data($0, maximumBytes: $1) } + try admission.jaccl.requireUnchanged(environment: environment, read: read) + let collective = try Collective(transport: .jaccl) + try admission.jaccl.requireUnchanged(environment: ProcessInfo.processInfo.environment, read: read) + try admission.jaccl.requireInitialized(rank: collective.rank, worldSize: collective.size, + transport: collective.transport) + let terms = Gemma4TensorParallelLoadAgreement(lanes: lanes, kv: kv, kvQuantization: kvQuantization, + prefixCache: keepsPrefixes) + let loadAgreement = try terms.fingerprint(admission: try admission.loadAgreementFingerprint()) + try ClusterDataPlaneAgreement.establish(collective: collective, credential: credential, + loadAgreement: loadAgreement, tamper: nil, tensorParallelSeal: true, check: { try control.check() }) + guard collective.workerDataPlane?.peerVerified == true else { + throw ProbeError("Gemma tensor parallel requires an authenticated peer") + } + let group = try QwenTensorParallelGroup(collective: collective) + let codec = try QwenTensorParallelSealCodec.product(collective: collective, scope: Data(loadAgreement.utf8)) + try codec.install() + group.sealed = codec + // The shard reduces through the group, except while the share probe times it alone. + let reduction = QwenTensorParallelSwitchableReduction(group) + let profile = admission.profile + var probe: ClusterWorkerLinkProbe? + var receipt: Gemma4TensorParallelShardReceipt? + var prefixCharges = (capture: 0, room: 0) + let capacity = try MLX.withError { nativeError -> Int in + func checked() throws { try nativeError.check(); try control.check(); try nativeError.check() } + try configuration.allocatorPolicy.configure(setCacheLimit: { Memory.cacheLimit = $0 }, check: checked) + _ = try requireQwenLongPrefillReadinessDigest(collective: collective, + material: { .residentLoadIntent(agreementFingerprint: loadAgreement) }, + disagreementMessage: "Gemma tensor-parallel load membership/source/plan/terms differ", + scope: .session(.loadAgreement, "gemma4-tensor-parallel-load-intent"), check: checked) + // The link as this mode uses it, before any weight is read. + let measured = try QwenTensorParallelLinkProbe.measure(collective: collective, group: group, + hiddenSize: profile.hiddenSize, chunkTokens: profile.maximumChunkTokens, check: checked) + probe = measured + log(QwenTensorParallelLinkProbe.line(measured, rank: collective.rank)) + // The load gate admits the shard with the profile's longest request (its prompt-prefix + // capture included) and the rank's own reserve (activation floor, freed-buffer cache, + // sealed frames) beside it: the planner's quote. + let budget = try requestBudget(contextTokens: profile.maximumContextTokens, admission: admission, + keepsPrefixes: keepsPrefixes) + let request = budget.requestBytes + let value = try autoreleasepool { + try Gemma4TensorParallelVerifiedLoad.load(admission, rank: collective.rank, reduction: reduction, + additionalResidentBytes: budget.allowance.reservedBytes, check: checked) + } + loadedModel = value.model; retired = value.model; receipt = value.receipt + value.model.model.freeze() + // Every request's keys and values live in this rank's paged + // host, bounded by the profile's longest request (a ceiling, + // not an allocation: each request's pages grow with it). + loadedHost = try value.model.pagedHost(lanes: lanes, maximumTokens: profile.maximumContextTokens, + chunkTokens: profile.maximumChunkTokens, quantization: kvQuantization) + loadedHost?.report("gemma4_tensor_parallel") + let loadedIdentity = sha256(try canonicalJSONData([loadAgreement, value.receipt.verifiedAggregateSHA256, + value.receipt.storageCommitmentSHA256, planName])) + _ = try requireQwenLongPrefillReadinessDigest(collective: collective, + material: { .residentLoaded(agreementFingerprint: loadedIdentity) }, + disagreementMessage: "Gemma tensor-parallel peers did not load matching verified commitments", + scope: .session(.loadedReady, "gemma4-tensor-parallel-loaded"), check: checked) + try configuration.allocatorPolicy.prepareReady( + synchronize: { Stream.gpu.synchronize(); Stream.cpu.synchronize() }, + snapshot: { + let s = Memory.snapshot() + return .init(activeBytes: s.activeMemory, cachedBytes: s.cacheMemory, peakBytes: s.peakMemory) + }, clearCache: { Memory.clearCache() }, check: checked) + let bufferCacheBytes = configuration.allocatorPolicy == .disableFreedBufferCache + ? freedBufferCacheBytes : Memory.cacheLimit + if configuration.allocatorPolicy == .disableFreedBufferCache { + Memory.cacheLimit = bufferCacheBytes + try checked() + } + // The prefix memory tier, charged nowhere: the pipeline's budget, + // half the admissible room measured beside the longest request + // and this rank's reserve (at most `maximumBudgetBytes`). + if keepsPrefixes { + let room = try ClusterStagePrefixBudget.roomBytes(chargeBytes: try QwenLongPrefillCheckedBytes.sum([ + budget.requestBytes, budget.rankBytes])) + prefixCache.setBudget(QwenStagePrefixCache.budget(roomBytes: room)) + prefixCharges = (budget.prefixCaptureBytes, room) + } + log("darkbloom-tensor-parallel-load-v1 rank=\(collective.rank) plan=\(planName) shares=1-1" + + " shard_bytes=\(value.receipt.shardBytes) source_bytes=\(value.receipt.sourceBytes)" + + " tensors=\(value.receipt.sourceTensors) load_ns=\(value.receipt.loadNanoseconds) sealed=1" + + " buffer_cache=\(bufferCacheBytes) lanes=\(lanes) paged_kv=\(CBv2PagedDefaults.pageSize)" + + " kv_heads=\(value.model.plan.kvHeadsPerRank.map(String.init).joined(separator: "-"))") + return request + } + guard let model = loadedModel, let host = loadedHost, let receipt else { + throw ProbeError("Gemma tensor-parallel load returned no shard") + } + // This rank's own share, timed alone before its ready record. + let shareProbe = try Gemma4TensorParallelShareProbe.measure(model: model, reduction: reduction, profile: profile, + deadline: control.deadline, admit: { tokens, chunk in + try QwenTensorParallelShareProbe.memoryAdmits(bytes: requestChargeBytes(contextTokens: tokens, + admission: admission, chunkTokens: chunk, keepsPrefixes: false)) + }, check: { try control.check() }) + if let shareProbe { log(QwenTensorParallelShareProbe.line(shareProbe, rank: collective.rank)) } + try control.loaded() + // The prefix cache's SSD tier, when the owner configured one: this + // rank's records of this artifact, plan and both builds, which a + // restarted pair finds again. Opening it sweeps the directories of + // other plans under the root that hold no live record. + let identity = admission.configuration.identity + let diskPlanScope = Gemma4TensorParallelPrefix.planScope(admission: admission, + aggregateSHA256: receipt.verifiedAggregateSHA256, storageCommitmentSHA256: receipt.storageCommitmentSHA256) + if keepsPrefixes { + prefixCache.disk = QwenStagePrefixDiskTier.open(configuration: .fromEnvironment(environment, key: prefixSSDKey), + planScope: diskPlanScope, rank: collective.rank, encoding: prefixRecords, + stagingEpoch: identity.membershipEpoch.uuidString.lowercased()) + } + log("darkbloom-prefix-v1 rank=\(collective.rank) family=gemma4 mode=tensor_parallel enabled=\(keepsPrefixes)" + + " budget_bytes=\(keepsPrefixes ? prefixCache.budgetBytes : 0) capture_charge=\(prefixCharges.capture)" + + " room_bytes=\(prefixCharges.room) ssd=\(prefixCache.disk != nil)") + let prefix = Gemma4TensorParallelPrefix(cache: keepsPrefixes ? prefixCache : QwenStagePrefixCache(enabled: false), + load: loadAgreement, diskPlanScope: diskPlanScope) + return Gemma4TensorParallelResidentRuntime(admission: admission, control: control, collective: collective, + group: group, codec: codec, model: model, host: host, loadAgreement: loadAgreement, capacity: capacity, + linkProbe: probe, shareProbe: shareProbe, lanes: lanes, prefix: prefix) + } catch { + let primary = error + control.fail(); loadedHost = nil; loadedModel = nil + do { + try MLX.withError { nativeError in + Stream.gpu.synchronize(); Stream.cpu.synchronize(); Memory.clearCache(); try nativeError.check() + } + guard retired == nil else { throw ProbeError("Gemma tensor-parallel failed-load shard remains retained") } + } catch { + throw ProbeError("Gemma tensor-parallel load failed (\(primary)); local cleanup failed (\(error))") + } + throw primary + } + } + + /// This rank's reserve for requests of `contextTokens` (`Gemma4TensorParallelRequestBudget`) + /// at the allocator's own bound; `keepsPrefixes` charges the prompt-prefix + /// capture of a prompt of `promptTokens` (the profile's longest by default). + static func requestBudget(contextTokens: Int, admission: Gemma4ResidentAdmission, chunkTokens: Int? = nil, + promptTokens: Int? = nil, keepsPrefixes: Bool = true) throws -> Gemma4TensorParallelRequestBudget { + try Gemma4TensorParallelRequestBudget.derive(contextTokens: contextTokens, + chunkTokens: chunkTokens ?? admission.profile.maximumChunkTokens, + promptTokens: promptTokens ?? admission.profile.maximumPromptTokens, keepsPrefixes: keepsPrefixes, + allocationBound: QwenResidentResourceEnvironment.allocationBound) + } + + /// What one request of `contextTokens` reserves on a rank: its own KV + /// heads, its own query heads' prompt transient, the chunk's FP32 + /// partials, the vocabulary rows and its prefix capture at its deepest + /// boundary (`Gemma4TensorParallelRequestBudget.requestBytes`). + static func requestChargeBytes(contextTokens: Int, admission: Gemma4ResidentAdmission, + chunkTokens: Int? = nil, keepsPrefixes: Bool = true) throws -> Int { + try requestBudget(contextTokens: contextTokens, admission: admission, chunkTokens: chunkTokens, + keepsPrefixes: keepsPrefixes).requestBytes + } + + /// What the live gate asks for beside every held request: the rank's + /// activation floor, freed-buffer cache and sealed frames. + var rankReserveBytes: Int { + get throws { try Self.requestBudget(contextTokens: admission.profile.maximumContextTokens, admission: admission).rankBytes } + } + + /// A request's charge on this rank, at its own context with its own + /// prompt's prefix capture (none when its cache is off: it neither + /// restores nor captures), what that capture may hold + /// (`Gemma4TensorParallelPrefix.captureLimit`, at least the charged part) + /// and the part beyond the charge: kept entries give way before the live + /// gate refuses that part, and a capture the gate still refuses is cut to + /// its charged part. + func prefixCharge(_ request: QwenLayerStageGenerationRequest) throws -> (charge: Int, captureLimit: Int, beyond: Int) { + let budget = try Self.requestBudget(contextTokens: request.maximumTokens, admission: admission, + chunkTokens: request.chunkSize, promptTokens: request.promptCount, keepsPrefixes: prefix.scopes(request) != nil) + let limit = prefix.captureLimit(request, chargedBytes: budget.prefixCaptureBytes) + return (budget.requestBytes, limit, max(0, limit - budget.prefixCaptureBytes)) + } + + /// The host memory gate's decision for `bytes` more, as the resident families take it. + static func requireLiveMemory(bytes: Int) throws { + try QwenResidentResourceEnvironment.require() + let watch = QwenDenseStageLoadWatch("Gemma tensor-parallel") + let os = try QwenDenseStageLoadResources.observeOS() + let free = max(QwenDenseStageLoadPolicy.minimumAdmissibleBytes, + try QwenLongPrefillCheckedBytes.sum([bytes, QwenDenseStageLoadPolicy.loadingHeadroomBytes])) + guard try watch.admits(os, bytes: free) else { + throw ProbeError("Gemma tensor parallel needs \(bytes) bytes the memory gate does not admit now") + } + } + + private init(admission: Gemma4ResidentAdmission, control: QwenResidentControl, collective: Collective, + group: QwenTensorParallelGroup, codec: QwenTensorParallelSealCodec, model: Gemma4TensorParallelModel, + host: CBv2StageKVHost, loadAgreement: String, capacity: Int, linkProbe: ClusterWorkerLinkProbe?, + shareProbe: ClusterWorkerShareProbe?, lanes: Int, prefix: Gemma4TensorParallelPrefix) { + self.admission = admission; self.control = control; self.collective = collective; self.group = group + self.codec = codec; self.model = model; self.host = host; self.loadAgreement = loadAgreement + self.linkProbe = linkProbe; self.shareProbe = shareProbe; self.lanes = lanes; self.prefix = prefix + baseReady = .init(identity: admission.configuration.identity, rank: collective.rank, + profile: admission.wireProfile, executionPlanSHA256: admission.plan.fingerprint, + requestCapacityBytes: capacity, dataPlane: collective.workerDataPlane, linkProbe: linkProbe, + shareProbe: shareProbe) + } + + // MARK: - Owner interface + + public var readiness: ClusterWorkerReady? { + guard control.available, (try? control.check()) != nil else { return nil } + return baseReady + } + + public func keepWarmPulse() throws -> UInt64 { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard control.available else { throw ProbeError("Keep-warm needs an idle resident owner") } + return keepWarm.pulse() + } + + public func dataPlanePing() throws -> UInt64 { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard control.available else { throw ProbeError("A data-plane ping needs an idle resident owner") } + return try ClusterKeepWarm.dataPlanePing(collective: collective, check: { try control.check() }) + } + + public func reserve(requestID: UUID, request value: ClusterWorkerReservation) throws -> Int { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard lanes == 1 else { throw ProbeError("Batched Gemma tensor-parallel owners reserve through the lane contract") } + let now = DispatchTime.now().uptimeNanoseconds + guard value.stillImages == nil, value.mimoImages == nil, value.glmMedia == nil else { + throw ProbeError("Gemma tensor parallel serves text requests only") + } + let request = try admission.request(value, id: requestID, now: now) + // Charged at its own context: the live gate alone decides whether it fits. + let priced = try prefixCharge(request) + let charge = priced.charge + try control.check(); try control.reserve(requestID) + return try control.reserving(requestID, rank: collective.rank, deadline: value.deadlineUptimeNanoseconds) { + guard model != nil, host != nil else { throw ProbeError("Resident model already released") } + guard charge <= value.capacityLimitBytes else { + throw ProbeError("Gemma tensor-parallel reservation exceeds its owner or readiness capacity") + } + ClusterIdleMemory.releaseFreedBuffers() + let captureLimit = try admitCapture(priced, held: [charge, rankReserveBytes]) + try control.check(deadline: value.deadlineUptimeNanoseconds) + reservation = .init(request: request, deadline: value.deadlineUptimeNanoseconds, prefixCaptureLimit: captureLimit) + return charge + } + } + + /// The live gate for a request priced as `prefixCharge` beside `held` + /// bytes: kept prefix entries give way first; a capture beyond its + /// charged part that still does not fit is cut to that part. Returns the + /// capture limit admitted. + func admitCapture(_ priced: (charge: Int, captureLimit: Int, beyond: Int), held: [Int]) throws -> Int { + let base = try QwenLongPrefillCheckedBytes.sum(held) + if priced.beyond > 0 { + do { + try prefix.cache.yieldingMemory { + try Self.requireLiveMemory(bytes: try QwenLongPrefillCheckedBytes.sum([base, priced.beyond])) + } + return priced.captureLimit + } catch { + log("darkbloom-prefix-v1 rank=\(collective.rank) family=gemma4 capture-cut bytes=\(priced.beyond): \(error)") + } + } + try prefix.cache.yieldingMemory { try Self.requireLiveMemory(bytes: base) } + return priced.captureLimit - priced.beyond + } + + public func releaseReservation(requestID: UUID) throws { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard let reserved = reservation, reserved.request.requestID == requestID, control.withdraw(requestID) else { + throw ProbeError("Resident release has no matching unstarted reservation") + } + reservation = nil + } + + /// Only rank 0 invokes the callback, once both ranks hold the token. + public func start(requestID: UUID, + onCommittedToken: (Int, Int, Int) throws -> Bool) throws -> QwenResidentGenerationCompletion { + try ClusterCommittedTokenChannel.answering(onCommittedToken) { try start(requestID: requestID, tokens: $0) } + } + + /// As `start(requestID:onCommittedToken:)`, with the owner's answer to each + /// token read after the next step ran: the answer's round trip through the + /// owner overlaps the step. + public func start(requestID: UUID, tokens channel: ClusterCommittedTokenChannel) throws + -> QwenResidentGenerationCompletion { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard let reserved = reservation, reserved.request.requestID == requestID else { + throw ProbeError("Resident start has no matching reservation") + } + do { + let value = try QwenResidentRequestPublication.run(control: control, lifecycle: lifecycle, + identity: .init(requestID: requestID, epoch: requestID, recordedRequestFingerprint: reserved.request.fingerprint), + deadline: reserved.deadline, body: { + try autoreleasepool { try generate(reserved, channel: channel) } + }, prepare: { $0 }) + collective.logDataPlaneStatus() + reservation = nil + return value + } catch { + // The peer may hold something else now. + prefix.cache.sweep() + control.fail(); throw error + } + } + + public func cancel(requestID: UUID) { control.cancel(requestID) } + + /// Gives back what this idle rank holds beyond its weights + /// (`ClusterIdleMemory`): MLX's freed-buffer cache, and the prompt-prefix + /// entries too while the host is `underPressure` (the vote then restores + /// nothing until both ranks hold a boundary again). Nothing while a + /// request or any batch lane is reserved, started or running. + public func releaseIdleMemory(underPressure: Bool) throws -> Int { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard control.available, reservation == nil, laneBook.isEmpty, model != nil else { return 0 } + let held = prefix.cache.bytesInUse, entries = prefix.cache.count + if underPressure { prefix.cache.sweep() } + let released = ClusterIdleMemory.releaseFreedBuffers() + if underPressure, entries > 0 { + log("darkbloom-idle-release-v1 rank=\(collective.rank) family=gemma4 prefix_entries_dropped=\(entries)" + + " prefix_bytes_dropped=\(held) freed_buffer_bytes=\(released)") + } + return released + } + + public func shutdown() throws { + guard operation.try() else { throw ProbeError("Cannot release a running native request") } + defer { operation.unlock() } + try control.beginClose() + collective.logDataPlaneStatus() + do { + try lifecycle.withModelRelease { + try MLX.withError { error in + Stream.gpu.synchronize(); Stream.cpu.synchronize(); try error.check() + try failedLaneDriver?.retireAll() + guard host?.isDrained ?? true else { throw ProbeError("Gemma tensor-parallel request state remains owned") } + // Records already queued for the SSD are finished first + // (bounded): they are what a restarted pair restores. + prefix.disk?.close() + prefix.cache.sweep() + reservation = nil; laneBook.clear(); failedLaneDriver = nil; host = nil + weak var released: Gemma4TensorParallelModel? + released = model; model = nil + guard released == nil else { throw ProbeError("Gemma tensor-parallel shard remains retained") } + Memory.clearCache(); try error.check() + } + } + control.closed() + processLeaseOwned = false; QwenResidentProcessLease.shared.release() + } catch { control.fail(); throw error } + } + + deinit { if processLeaseOwned { control.fail() } } + + // MARK: - One request + + private func generate(_ reserved: Reserved, channel: ClusterCommittedTokenChannel) throws + -> QwenResidentGenerationCompletion { + guard let model, let host else { throw ProbeError("Resident model already released") } + let request = reserved.request + guard try group.digestsEqual(QwenTensorParallelResidentRuntime.digest64(request.fingerprint + "|" + loadAgreement)) else { + throw ProbeError("Gemma tensor-parallel ranks were given different requests") + } + // Prompt prefix: the deepest boundary both ranks hold, voted and confirmed (or none). + let session = try MLX.withError { error -> Gemma4TensorParallelPagedSession in + let value = try prefix.open(request, model: model, host: host, group: group, + captureLimit: reserved.prefixCaptureLimit, stop: { [control] in + (try? control.check(deadline: reserved.deadline)) == nil + }) + try error.check() + return value + } + do { + // A step checks native errors only: a cancel or deadline must not + // end one rank between two collectives (its peer would wait in the + // next one), so it rides in the next step's flags (`localStop`). + var completion = try MLX.withError { error in + try serve(request, session: session, deadline: reserved.deadline, channel: channel, + checked: { try error.check() }) + } + try session.retire() + // Both ranks ended after the same step and agreed how: the prompt's + // capture becomes reusable now, in memory and behind serving on SSD. + if let capture = session.prefixCapture, let scopes = prefix.scopes(request) { + completion.storedPromptFrontiers = prefix.store(capture, request: request, scopes: scopes, rank: collective.rank) + } + completion.reusedPromptTokens = session.reusedPrefixTokens + return completion + } catch { + session.prefixCapture?.withdraw() + try? session.retire(failed: true) + throw error + } + } + + /// The request's prompt and decode through `Gemma4TensorParallelRequestLoop` + /// on this rank: the pair's agreed tokens and finish. + private func serve(_ request: QwenLayerStageGenerationRequest, session: Gemma4TensorParallelPagedSession, + deadline: UInt64, channel: ClusterCommittedTokenChannel, + checked: () throws -> Void) throws -> QwenResidentGenerationCompletion { + let rank = collective.rank, prompt = request.promptTokenIDs + let choice = Gemma4TensorParallelChoice(selection: session.model.selection, sampler: request.sampler, rank: rank) + var lastCheck: UInt64 = 0 + let loop = Gemma4TensorParallelRequestLoop(session: session, request: request, choice: choice, + exchange: { [group] in try group.exchangeIntegers($0) }, localStop: { [control, prefix] in + if (try? control.check(deadline: deadline)) == nil { return true } + let now = DispatchTime.now().uptimeNanoseconds + if now - lastCheck >= 250_000_000 { + lastCheck = now + // Kept prefixes give way first, then the request's own capture. + if (try? prefix.cache.yieldingMemory({ try Self.requireLiveMemory(bytes: 0) })) == nil { + guard let capture = session.prefixCapture, !capture.withdrawn else { return true } + capture.withdraw(); Memory.clearCache() + return (try? Self.requireLiveMemory(bytes: 0)) == nil + } + } + return false + }) + let ended = try loop.run(channel: channel, check: checked) + let tokens = ended.tokens, finish = ended.finish + try control.check(deadline: deadline) + if finish == .clientStop && !ended.clientStopped && rank == 0 { + throw ProbeError("The peer rank stopped the Gemma tensor-parallel request") + } + log("darkbloom-tensor-parallel-request-v1 rank=\(rank) family=gemma4 request=\(request.requestID.uuidString.lowercased())" + + " prompt=\(prompt.count) output=\(tokens.count) finish=\(finish.rawValue) sampled=\(choice.gathersRow ? 1 : 0)" + + " logprobs=\(request.sampler?.wire.capturedLogprobs ?? 0) frames=\(codec.sealedFrames)" + + " key_generation=\(codec.keyGeneration) kv_tokens=\(session.state.reservedTokens)" + + " kv_refused=\(ended.pagesRefused ? 1 : 0) reused=\(session.reusedPrefixTokens)") + return QwenResidentGenerationCompletion(requestID: request.requestID, finishReason: finish, + selectedTokenIDs: tokens, completedFrames: tokens.count, committedTokens: prompt.count + tokens.count, + tokenChainSHA256: sha256(try canonicalJSONData(tokens.map { String($0) })), bothRequestStatesRetired: true) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSelection.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSelection.swift new file mode 100644 index 0000000000..6b7b455c6e --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSelection.swift @@ -0,0 +1,166 @@ +import Foundation +import MLX + +/// Choices from a tied head whose vocabulary rows are split across ranks. +/// Each rank holds its rows' FP32 (softcapped) logits `[1, V/2]`; one small +/// collective per choice makes the same choice on every rank without +/// gathering the whole row (only `gather` does, for the product's sampler). +/// Without a reduction the rows are the whole vocabulary and the same +/// functions are the plain choices of a whole model. +public struct Gemma4TensorParallelSelection { + public let vocabularyRange: Range + public let vocabularySize: Int + let reduction: QwenTensorParallelReduction? + /// A whole row normalized as two ranks normalize it (each half's top + /// `count` and log-sum-exp, merged): the split-sum oracle's head. + let splitsWholeRow: Bool + + public init(vocabularyRange: Range, vocabularySize: Int, reduction: QwenTensorParallelReduction?, + splitsWholeRow: Bool = false) { + self.vocabularyRange = vocabularyRange + self.vocabularySize = vocabularySize + self.reduction = reduction + self.splitsWholeRow = splitsWholeRow && reduction == nil + } + + /// Greedy: the argmax over every rank's rows, ties to the lowest token ID + /// as a whole row's argmax breaks them. One collective of two values per + /// rank. An `[1]` int32 token, not evaluated. + public func greedy(_ logits: MLXArray) -> MLXArray { + argmaxAcrossRanks(logits.asType(.float32), carrying: nil).token + } + + /// `greedy`, with every rank's `flags` (`[n]` FP32, the same `n` on every + /// rank) carried in the same collective: the token, its logit (the row's + /// maximum, `[1]` FP32) and all ranks' flags in rank order (`[size n]`). + /// Not evaluated. + public func greedy(_ logits: MLXArray, carrying flags: MLXArray) -> (token: MLXArray, maximum: MLXArray, flags: MLXArray) { + let chosen = argmaxAcrossRanks(logits.asType(.float32), carrying: flags.asType(.float32).reshaped(-1)) + return (chosen.token, chosen.maximum, chosen.carried!) + } + + /// `greedy` of every row of `logits` (`[B, rows]`, one row a batch lane): + /// `[B]` int32 tokens and their `[B]` FP32 logits (each row's maximum) + /// from one collective of two values a row and rank, with `greedy`'s tie + /// rule. Not evaluated. + public func greedyRows(_ logits: MLXArray) -> (tokens: MLXArray, maxima: MLXArray) { + let values = logits.asType(.float32) + guard let reduction else { return (argMax(values, axis: -1).asType(.int32), values.max(axis: -1)) } + let width = values.dim(0) + let local = stacked([values.max(axis: -1), + argMax(values, axis: -1).asType(.float32) + MLXArray(Float(vocabularyRange.lowerBound))], axis: 1) + let zeros = MLXArray.zeros([width, 2], dtype: .float32) + let all = reduction.allSum(concatenated((0 ..< reduction.size).map { $0 == reduction.rank ? local : zeros }, axis: 1)) + var best = all[0..., 0], token = all[0..., 1] + for other in 1 ..< reduction.size { + let better = all[0..., 2 * other] .> best + best = which(better, all[0..., 2 * other], best) + token = which(better, all[0..., 2 * other + 1], token) + } + return (token.asType(.int32), best) + } + + /// Every rank's `slots` (`[n]` FP32) in rank order (`[size n]`), each rank + /// adding its own at its place and -0 elsewhere. Not evaluated. + public func exchange(_ slots: MLXArray) -> MLXArray { + let mine = slots.asType(.float32).reshaped(-1) + guard let reduction else { return mine } + let empty = MLXArray.full([mine.dim(0)], values: MLXArray(Float(-0.0))) + return reduction.allSum(concatenated((0 ..< reduction.size).map { $0 == reduction.rank ? mine : empty }, axis: 0)) + } + + /// One choice's candidates: the top `count` tokens of the whole row with + /// their logits and log probabilities (each logit minus the whole row's + /// log-sum-exp), highest first, equal logits by token ID. Each rank + /// contributes its own top `count` and its rows' log-sum-exp in one + /// collective of `2 count + 1` values per rank. Evaluated. + public func topK(_ logits: MLXArray, count: Int) throws -> (tokenIDs: [Int], logits: [Float], logprobs: [Float]) { + let values = logits.asType(.float32).reshaped(-1) + guard values.dim(0) == vocabularyRange.count, count >= 1, + count <= values.dim(0) / (splitsWholeRow ? 2 : 1) else { + throw ProbeError("Gemma vocabulary-split top-k: \(count) of a \(values.dim(0))-row slice") + } + func candidates(_ slice: MLXArray, offset: Int) -> MLXArray { + let order = argPartition(-slice, kth: count - 1)[.. $1.logit : $0.id < $1.id }.prefix(count) + return (chosen.map(\.id), chosen.map(\.logit), chosen.map { $0.logit - total }) + } + + /// The whole row on every rank, every bit kept: each rank's rows at their + /// place and -0 elsewhere (x + -0 is x), in one collective of V values. + /// Not evaluated. + public func gather(_ logits: MLXArray) -> MLXArray { + let values = logits.asType(.float32) + guard let reduction else { return values } + func negativeZeros(_ count: Int) -> MLXArray { + MLXArray.full([values.dim(0), count], values: MLXArray(Float(-0.0))) + } + var parts: [MLXArray] = [] + if vocabularyRange.lowerBound > 0 { parts.append(negativeZeros(vocabularyRange.lowerBound)) } + parts.append(values) + if vocabularyRange.upperBound < vocabularySize { parts.append(negativeZeros(vocabularySize - vocabularyRange.upperBound)) } + return reduction.allSum(concatenated(parts, axis: -1)) + } + + /// Each rank's local maximum, its token ID and `extra` in slots of a + /// `(2 + extra) size` collective; the strictly greater value wins, so ties + /// go to the lower rank, which holds the lower IDs. + private func argmaxAcrossRanks(_ values: MLXArray, carrying extra: MLXArray?) + -> (token: MLXArray, maximum: MLXArray, carried: MLXArray?) { + guard let reduction else { + return (argMax(values, axis: -1).asType(.int32), values.max(axis: -1).reshaped(1), extra) + } + let width = 2 + (extra?.dim(0) ?? 0) + let localIndex = argMax(values, axis: -1).asType(.float32) + MLXArray(Float(vocabularyRange.lowerBound)) + let mine = concatenated([values.max(axis: -1), localIndex] + (extra.map { [$0] } ?? []), axis: 0) + let zeros = MLXArray.zeros([width], dtype: .float32) + let all = reduction.allSum(concatenated((0 ..< reduction.size).map { $0 == reduction.rank ? mine : zeros }, axis: 0)) + var best = all[0], token = all[1] + for other in 1 ..< reduction.size { + let better = all[width * other] .> best + best = which(better, all[width * other], best) + token = which(better, all[width * other + 1], token) + } + let carried = extra.map { _ in + concatenated((0 ..< reduction.size).map { all[(width * $0 + 2) ..< (width * ($0 + 1))] }, axis: 0) + } + return (token.asType(.int32).reshaped(1), best.reshaped(1), carried) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelShareProbe.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelShareProbe.swift new file mode 100644 index 0000000000..3ddbe8c9a9 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelShareProbe.swift @@ -0,0 +1,81 @@ +import DarkbloomClusterProtocol +import Foundation +import MLX + +/// What a Gemma 4 tensor-parallel rank measures of its own share at load, +/// after its weights and before its ready record, with no peer traffic, as +/// `QwenTensorParallelShareProbe` measures a dense Qwen share: every +/// reduction local (`QwenTensorParallelSwitchableReduction`), so the rank +/// times only what its share computes between reductions. One throwaway +/// request of `QwenTensorParallelShareProbe.promptTokens` synthetic tokens on +/// a one-lane paged host of its own is prefilled, then a few warm-up rounds +/// and the timed ones of the plain decode step (`decodeCommandBuffers`); +/// the median in microseconds. Shares are equal (500 per mille). +/// +/// It never fails or holds up a load: memory the gate does not admit, a load +/// deadline too close, or any error gives no probe, and the timed rounds +/// stop at the budget. Only a throwaway request that cannot be retired fails +/// the load, since its native work may still be running. +enum Gemma4TensorParallelShareProbe { + typealias Limits = QwenTensorParallelShareProbe + + static func measure(model: Gemma4TensorParallelModel, reduction: QwenTensorParallelSwitchableReduction, + profile: QwenLayerStageGenerationProfile, deadline: UInt64, + admit: (_ maximumTokens: Int, _ chunkTokens: Int) throws -> Bool, check: () throws -> Void, + clock: () -> UInt64 = { DispatchTime.now().uptimeNanoseconds }) throws -> ClusterWorkerShareProbe? { + let rank = reduction.rank + func skipped(_ reason: String) -> ClusterWorkerShareProbe? { + log("darkbloom-share-probe-v1 rank=\(rank) family=gemma4 skipped=\(reason)"); return nil + } + guard case .shard(let shardRank) = model.role, shardRank == rank, reduction.size == 2, + let share = Limits.sharePerMille(shares: [1, 1], rank: rank) else { return skipped("unsupported") } + let shape = Limits.requestShape(profile: profile, windowColumns: nil) + let started = clock() + guard deadline > started, deadline - started >= Limits.deadlineMarginNanoseconds else { return skipped("deadline") } + do { + guard try admit(shape.prompt + shape.outputs, shape.prompt) else { return skipped("memory") } + } catch { return skipped("memory") } + var session: Gemma4TensorParallelPagedSession? + do { + let times = try reduction.locally { () throws -> [UInt64] in + try MLX.withError { error -> [UInt64] in + func checked() throws { try error.check(); try check() } + let host = try model.pagedHost(lanes: 1, maximumTokens: shape.prompt + shape.outputs, + chunkTokens: shape.prompt) + let value = try Gemma4TensorParallelPagedSession(model: model, host: host, promptCount: shape.prompt, + outputCount: shape.outputs) + session = value + let prompt = (0..= Limits.warmupRounds, clock() - started >= Limits.budgetNanoseconds { break } + token = (token * 37 + 11) % profile.vocabularySize + let roundStarted = clock() + _ = try GPU.withCommandBufferLimits(Gemma4TensorParallelModel.decodeCommandBuffers) { + try value.decode(token, check: checked) { $0 } + } + if index >= Limits.warmupRounds { times.append(clock() - roundStarted) } + } + try value.retire() + guard host.isDrained else { throw ProbeError("Gemma tensor-parallel share probe kept its pages") } + return times + } + } + guard times.count >= Limits.minimumRounds else { return skipped("budget") } + let probe = ClusterWorkerShareProbe(sharePerMille: share, + plainStepMicroseconds: max(1, Int(times.sorted()[times.count / 2] / 1000)), rounds: times.count) + return probe.valid ? probe : skipped("bounds") + } catch { + // The throwaway request goes whatever failed; one that cannot be retired fails the load. + if let session, !session.retired { + do { try session.retire(failed: true) } catch { + throw ProbeError("Gemma tensor-parallel share probe could not retire its request (\(error))") + } + } + return skipped("error_" + qwenPrefixLogWord(error)) + } + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSplitSum.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSplitSum.swift new file mode 100644 index 0000000000..3527896d91 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSplitSum.swift @@ -0,0 +1,172 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +/// The single-process oracle of Gemma 4's row-parallel projections. Each +/// rank's part reads that rank's stored input columns of the whole input, +/// zero outside the rank's own channels (as the rank's zero-padded channels +/// are), through its column slice of the quantized weight with the input +/// widened to FP32 (the arithmetic a rank's partial uses); the two partials +/// are added in FP32 and rounded once. Installed over a whole model, it is +/// the `splitSum` oracle of the decomposition. +enum Gemma4TensorParallelSplitSum { + struct Part: Equatable { + /// Input columns the rank stores. + let stored: Range + /// Input columns the rank owns; the rest of `stored` reads zero. + let channels: Range + } + + /// Replaces every row-parallel projection of the whole `model`; returns + /// the parts' arrays, for evaluation with the model's parameters. + static func install(in model: Gemma4Model, plan: Gemma4TensorParallelPlan) throws -> [MLXArray] { + let leaves = Dictionary(uniqueKeysWithValues: model.leafModules().flattened()) + var replacements: [(String, Module)] = [] + var arrays: [MLXArray] = [] + let dense = try (0 ..< plan.size).map { rank -> Part in + let split = try plan.denseSplit(rank: rank) + return Part(stored: split.storedColumns, channels: split.channels) + } + let experts = try (0 ..< plan.size).map { rank -> Part in + let split = try plan.expertSplit(rank: rank) + return Part(stored: split.storedColumns, channels: split.channels) + } + for layer in 0 ..< plan.layerCount { + let base = "language_model.model.layers.\(layer)." + let width = plan.queryHeadsPerRank * plan.headDim(layer: layer) + let attention = (0 ..< plan.size).map { Part(stored: ($0 * width) ..< (($0 + 1) * width), + channels: ($0 * width) ..< (($0 + 1) * width)) } + guard let output = leaves[base + "self_attn.o_proj"] as? QuantizedLinear, + let down = leaves[base + "mlp.down_proj"] as? QuantizedLinear, + let expertDown = leaves[base + "experts.switch_glu.down_proj"] as? QuantizedSwitchLinear else { + throw ProbeError("Gemma split-sum oracle: layer \(layer) lacks a quantized row-parallel projection") + } + let attentionOracle = try Gemma4SplitSumLinear(output, parts: attention) + let denseOracle = try Gemma4SplitSumLinear(down, parts: dense) + let expertOracle = try Gemma4SplitSumSwitchLinear(expertDown, parts: experts) + replacements += [(base + "self_attn.o_proj", attentionOracle), (base + "mlp.down_proj", denseOracle), + (base + "experts.switch_glu.down_proj", expertOracle)] + arrays += attentionOracle.partArrays + denseOracle.partArrays + expertOracle.partArrays + } + try model.update(modules: ModuleChildren.unflattened(replacements), verify: .none) + return arrays + } + + /// `x`'s last-axis columns `part.stored`, every column outside + /// `part.channels` zero. + static func block(_ x: MLXArray, _ part: Part) -> MLXArray { + let core = x[.ellipsis, part.channels] + let before = part.channels.lowerBound - part.stored.lowerBound + let after = part.stored.upperBound - part.channels.upperBound + guard before > 0 || after > 0 else { return core } + func zeros(_ count: Int) -> MLXArray { + var shape = x.shape + shape[shape.count - 1] = count + return MLXArray.zeros(shape, dtype: x.dtype) + } + return concatenated((before > 0 ? [zeros(before)] : []) + [core] + (after > 0 ? [zeros(after)] : []), axis: -1) + } + + /// Stored input columns `columns` of packed `[..., out, in / perWord]` + /// words and `[..., out, in / group]` scales or offsets, copied row-major. + static func columns(_ value: MLXArray, _ columns: Range, divisor: Int) throws -> MLXArray { + guard columns.lowerBound % divisor == 0, columns.upperBound % divisor == 0, + columns.upperBound / divisor <= value.dim(-1) else { + throw ProbeError("Gemma split-sum oracle: columns \(columns) split a packed word or group") + } + return contiguous(value[.ellipsis, (columns.lowerBound / divisor) ..< (columns.upperBound / divisor)]) + } +} + +/// A dense row-parallel projection's oracle (`o_proj`, the dense MLP's +/// `down_proj`). +final class Gemma4SplitSumLinear: QuantizedLinear { + private final class Parts { + let modules: [QuantizedLinear] + let parts: [Gemma4TensorParallelSplitSum.Part] + init(_ modules: [QuantizedLinear], _ parts: [Gemma4TensorParallelSplitSum.Part]) { + self.modules = modules; self.parts = parts + } + } + + private let split: Parts + + init(_ source: QuantizedLinear, parts: [Gemma4TensorParallelSplitSum.Part]) throws { + guard source.bias == nil, source.mode == .affine, let offsets = source.biases else { + throw ProbeError("Gemma split-sum oracle: an affine projection without bias is required") + } + let modules = try parts.map { part in + QuantizedLinear( + weight: try Gemma4TensorParallelSplitSum.columns(source.weight, part.stored, divisor: 32 / source.bits), + bias: nil, + scales: try Gemma4TensorParallelSplitSum.columns(source.scales, part.stored, divisor: source.groupSize), + biases: try Gemma4TensorParallelSplitSum.columns(offsets, part.stored, divisor: source.groupSize), + groupSize: source.groupSize, bits: source.bits, mode: source.mode) + } + split = Parts(modules, parts) + super.init(weight: source.weight, bias: nil, scales: source.scales, biases: offsets, + groupSize: source.groupSize, bits: source.bits, mode: source.mode) + freeze() + } + + var partArrays: [MLXArray] { split.modules.flatMap { [$0.weight, $0.scales] + ($0.biases.map { [$0] } ?? []) } } + + override func callAsFunction(_ x: MLXArray) -> MLXArray { + var sum: MLXArray? + for (module, part) in zip(split.modules, split.parts) { + let partial = Gemma4TensorParallelProjection.partial(module, Gemma4TensorParallelSplitSum.block(x, part)) + sum = sum.map { $0 + partial } ?? partial + } + return sum!.asType(x.dtype) + } +} + +/// The routed experts' down projection oracle: every selected expert's row +/// summed over both ranks' parts in FP32 and rounded before the owning +/// SwitchGLU restores route order and weights it, as the packed collective +/// does on two ranks. +final class Gemma4SplitSumSwitchLinear: QuantizedSwitchLinear, SwitchLinearPartialSum { + private final class Parts { + let modules: [QuantizedSwitchLinear] + let parts: [Gemma4TensorParallelSplitSum.Part] + init(_ modules: [QuantizedSwitchLinear], _ parts: [Gemma4TensorParallelSplitSum.Part]) { + self.modules = modules; self.parts = parts + } + } + + private let split: Parts + + init(_ source: QuantizedSwitchLinear, parts: [Gemma4TensorParallelSplitSum.Part]) throws { + guard type(of: source) == QuantizedSwitchLinear.self, source.mode == .affine, + !source.parameters().flattened().contains(where: { $0.0 == "bias" }), + let offsets = source.biases, source.globalScales == nil else { + throw ProbeError("Gemma split-sum oracle: an affine expert bank without bias is required") + } + let modules = try parts.map { part in + try QuantizedSwitchLinear( + inputDims: part.stored.count, outputDims: source.shape.outputDims, numExperts: source.shape.numExperts, + weight: try Gemma4TensorParallelSplitSum.columns(source.weight, part.stored, divisor: 32 / source.bits), + scales: try Gemma4TensorParallelSplitSum.columns(source.scales, part.stored, divisor: source.groupSize), + biases: try Gemma4TensorParallelSplitSum.columns(offsets, part.stored, divisor: source.groupSize), + groupSize: source.groupSize, bits: source.bits) + } + split = Parts(modules, parts) + try super.init(inputDims: source.shape.inputDims, outputDims: source.shape.outputDims, + numExperts: source.shape.numExperts, weight: source.weight, scales: source.scales, + biases: offsets, groupSize: source.groupSize, bits: source.bits) + } + + var partArrays: [MLXArray] { split.modules.flatMap { [$0.weight, $0.scales] + ($0.biases.map { [$0] } ?? []) } } + + override func callAsFunction(_ x: MLXArray, _ indices: MLXArray, sortedIndices: Bool = false) -> MLXArray { + var sum: MLXArray? + for (module, part) in zip(split.modules, split.parts) { + let block = Gemma4TensorParallelSplitSum.block(x, part).asType(.float32) + let partial = module(block, indices, sortedIndices: sortedIndices) + sum = sum.map { $0 + partial } ?? partial + } + return sum!.asType(x.dtype) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSynthetic.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSynthetic.swift new file mode 100644 index 0000000000..d104f3abb0 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelSynthetic.swift @@ -0,0 +1,104 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +extension Gemma4TensorParallelModel { + /// Writes a tiny random Gemma 4 MoE checkpoint into `directory` + /// (`config.json`, `model.safetensors` and its index), seeded, with the + /// 26B's structure scaled down: sliding and full layers (window 16), 16 + /// query heads with 8 sliding and 2 full KV heads (head dims 256 and 512, + /// K=V on full layers), a dense GeGLU MLP in parallel with 16 routed + /// experts (top-4), sandwich norms, a tied softcapped head, and affine + /// group-64 quantization (`bits` by default, 8-bit dense MLP and router) + /// whose dense (5) and expert (3) group counts are odd, so both overlap + /// splits run. For model-free equality checks of tensor parallel; never a + /// model pass. + /// + /// `dtype` is the weights' and so the activations' type: BF16 as the + /// artifacts, or FP32, whose rounding is too small to flip a random + /// router's near-tied top-k choice (a random router's scores sit closer + /// together than a trained one's). + /// `experts`/`topK` change the routed bank (with `topK == experts` every + /// token takes every expert, and no rounding can change a route). + public static func writeSyntheticCheckpoint(directory: URL, seed: UInt64 = 7, bits: Int = 4, + dtype: DType = .bfloat16, experts: Int = 16, topK: Int = 4) throws { + guard [4, 8].contains(bits) else { throw ProbeError("Gemma synthetic checkpoint: bits are 4 or 8") } + guard (1 ... 64).contains(experts), (1 ... experts).contains(topK) else { + throw ProbeError("Gemma synthetic checkpoint: 1 to 64 experts, top-k at most the experts") + } + guard [.bfloat16, .float32].contains(dtype) else { + throw ProbeError("Gemma synthetic checkpoint: weights are bfloat16 or float32") + } + let layers = 6 + let kinds = (0 ..< layers).map { ($0 + 1) % 3 == 0 ? "full_attention" : "sliding_attention" } + let text: [String: Any] = [ + "model_type": "gemma4_text", "hidden_size": 256, "num_hidden_layers": layers, "layer_types": kinds, + "intermediate_size": 320, "moe_intermediate_size": 192, "num_experts": experts, "top_k_experts": topK, + "num_attention_heads": 16, "num_key_value_heads": 8, "num_global_key_value_heads": 2, + "head_dim": 256, "global_head_dim": 512, "sliding_window": 16, "vocab_size": 512, + "vocab_size_per_layer_input": 0, "hidden_size_per_layer_input": 0, "num_kv_shared_layers": 0, + "attention_k_eq_v": true, "enable_moe_block": true, "tie_word_embeddings": true, + "use_double_wide_mlp": false, "attention_bias": false, "final_logit_softcapping": 30.0, + "rms_norm_eps": 1e-6, "max_position_embeddings": 4096, "hidden_activation": "gelu_pytorch_tanh", + "use_bidirectional_attention": "vision", "dtype": dtype == .float32 ? "float32" : "bfloat16", + "rope_parameters": [ + "sliding_attention": ["rope_type": "default", "rope_theta": 10000.0], + "full_attention": ["rope_type": "proportional", "rope_theta": 1_000_000.0, "partial_rotary_factor": 0.25], + ], + ] + var quantization: [String: Any] = ["group_size": 64, "bits": bits, "mode": "affine"] + for layer in 0 ..< layers { + for module in ["mlp.gate_proj", "mlp.up_proj", "mlp.down_proj", "router.proj"] { + quantization["language_model.model.layers.\(layer).\(module)"] = ["group_size": 64, "bits": 8] + } + } + let root: [String: Any] = ["model_type": "gemma4", "text_config": text, "tie_word_embeddings": true, + "vocab_size": 512, "quantization": quantization, "quantization_config": quantization] + let configurationData = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys, .prettyPrinted]) + let plan = try Gemma4TensorParallelPlan(configuration: root) + let configuration = try JSONDecoder().decode(Gemma4Configuration.self, from: configurationData) + let arrays: [String: MLXArray] = withRandomState(MLXRandom.RandomState(seed: seed)) { + let model = Gemma4Model(configuration) + var values: [(String, MLXArray)] = [] + for (key, value) in model.parameters().flattened() { + let shape = value.shape + let generated: MLXArray + if key.hasSuffix("embed_tokens.weight") { + generated = MLXRandom.normal(shape) * 0.1 + } else if key.hasSuffix("layer_scalar") { + generated = MLXRandom.uniform(low: 0.5, high: 1.0, shape) + } else if key.hasSuffix("per_expert_scale") { + generated = MLXRandom.uniform(low: 0.5, high: 1.5, shape) + } else if key.hasSuffix("q_norm.weight") || key.hasSuffix("k_norm.weight") { + // Gemma 4 attends at scale 1: small per-head norms keep + // scores near unit spread, as a trained model's do, so + // softmax is not an argmax that rounding can flip. + generated = MLXRandom.uniform(low: 0.2, high: 0.3, shape) + } else if key.hasSuffix("norm.weight") || key.hasSuffix("router.scale") { + generated = MLXRandom.uniform(low: 0.6, high: 1.4, shape) + } else { + let fanIn = Float(shape.last ?? 1) + generated = MLXRandom.normal(shape) * (1 / fanIn.squareRoot()) + } + values.append((key, generated.asType(dtype))) + } + model.update(parameters: ModuleParameters.unflattened(values)) + quantize(model: model) { path, module in + guard module is Linear || module is SwitchLinear || module is Embedding else { return nil } + return (64, plan.bits(forModule: path), .affine) + } + let flat = Dictionary(uniqueKeysWithValues: model.parameters().flattened()) + eval(Array(flat.values)) + return flat + } + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try configurationData.write(to: directory.appendingPathComponent("config.json")) + try save(arrays: arrays, url: directory.appendingPathComponent("model.safetensors")) + let index: [String: Any] = ["metadata": [:] as [String: Any], + "weight_map": Dictionary(uniqueKeysWithValues: arrays.keys.map { ($0, "model.safetensors") })] + try JSONSerialization.data(withJSONObject: index, options: [.sortedKeys, .prettyPrinted]) + .write(to: directory.appendingPathComponent("model.safetensors.index.json")) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelVerifiedLoad.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelVerifiedLoad.swift new file mode 100644 index 0000000000..c44353359b --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelVerifiedLoad.swift @@ -0,0 +1,120 @@ +import Foundation +import MLX +import MLXLMCommon + +/// What one rank of a Gemma 4 tensor-parallel load read and holds: the +/// verified artifact and the storage commitment it was read under (equal on +/// both ranks, compared before either serves), and this rank's own share. +struct Gemma4TensorParallelShardReceipt: Equatable { + let verifiedAggregateSHA256: String + let storageCommitmentSHA256: String + let rank: Int + let sourceTensors: Int + let sourceBytes: Int + let shardBytes: Int + let loadNanoseconds: UInt64 +} + +/// The product's Gemma 4 tensor-parallel shard load +/// (`gemma4_heads_and_expert_channels_v1`): this rank's heads, channels and +/// vocabulary rows, read through this Mac's verified checkpoint, never from +/// the files directly. +/// +/// The whole artifact is verified first, as a pipeline load verifies it +/// (`prepareGemma4ResidentSource`: every file of the registered manifest +/// against its aggregate, the text tensors against the registered +/// inventory). Both pipeline stages' inventories are then prepared and must +/// conserve the source (the storage commitment both ranks compare). Every +/// text tensor must have the shape the plan expects of it; each is one +/// aligned, uncached read through its pinned descriptor, checked against its +/// inventory entry, asked of the host memory gate first +/// (`QwenTensorParallelLoadGate`), cut to this rank's part and materialized +/// at once, and released before the next is read. Vision tensors are not in +/// the text inventory and are never read; any other tensor the plan does not +/// cover refuses the load before a byte is read. +enum Gemma4TensorParallelVerifiedLoad { + static func load(_ admission: Gemma4ResidentAdmission, rank: Int, reduction: QwenTensorParallelReduction, + additionalResidentBytes: Int = 0, check: () throws -> Void) throws + -> (model: Gemma4TensorParallelModel, receipt: Gemma4TensorParallelShardReceipt) { + guard additionalResidentBytes >= 0, reduction.rank == rank, reduction.size == 2 else { + throw ProbeError("Gemma tensor-parallel load needs this rank's two-rank reduction") + } + let started = DispatchTime.now().uptimeNanoseconds + let local = try prepareGemma4ResidentSource(admission, check: check) + let source = local.metadata.source, stages = admission.plan + let inventories = try (0.. (entries: [QwenStageActiveTensor], bytes: [Int]) { + guard !tensors.isEmpty, Set(tensors.map(\.sourceName)).count == tensors.count else { + throw ProbeError("Gemma tensor-parallel source names a tensor twice or none") + } + var entries: [QwenStageActiveTensor] = [], bytes: [Int] = [] + for tensor in tensors.sorted(by: { $0.sourceName < $1.sourceName }) { + guard tensor.secondPart == nil, try plan.expectedShape(key: tensor.sourceName) == tensor.shape else { + throw ProbeError("Gemma tensor-parallel source tensor differs from the plan's shape: \(tensor.sourceName)") + } + let local = try plan.localShape(key: tensor.sourceName, shape: tensor.shape, + cut: try plan.cut(key: tensor.sourceName, rank: rank)) + let elements = tensor.shape.reduce(1, *) + guard elements > 0, tensor.byteCount % elements == 0 else { + throw ProbeError("Gemma tensor-parallel source tensor bytes differ from its shape: \(tensor.sourceName)") + } + entries.append(.init(sourceName: tensor.sourceName, localName: tensor.sourceName, shape: tensor.shape, + sourceDType: tensor.sourceDType, loadedDType: tensor.loadedDType, byteCount: tensor.byteCount)) + bytes.append(try QwenLongPrefillCheckedBytes.product([local.reduce(1, *), tensor.byteCount / elements])) + } + return (entries, bytes) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/LayerStageResident.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/LayerStageResident.swift index 095b73185b..e3c5e33c37 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/LayerStageResident.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/LayerStageResident.swift @@ -55,13 +55,43 @@ extension LayerStageResidentAdmission { } } +/// What one decode forward of a request runs on a rank. Under the decode +/// command buffers (`QwenLayerStageSession.decodeCommandBuffers`) the +/// temporaries of every layer it runs can be alive at once: `rows` a layer (1, +/// or a verify window's `depth + 1`), over the rank's own stage or, on the +/// decoding rank of a phase split, which runs both stages, over every layer. +/// The other rank of a phase split hands its prompt state over and decodes +/// nothing: 0 rows. +struct LayerStageDecodeShape: Equatable { + var rows = 1 + var wholeModel = false + + static let plain = Self() + + init(rows: Int = 1, wholeModel: Bool = false) { + self.rows = rows; self.wholeModel = wholeModel + } + + init(mode: QwenResidentGenerationMode, rank: Int, speculativeTerms: QwenMTPTerms?) { + let rows = mode.usesSpeculativeHead ? (speculativeTerms?.depth ?? 0) + 1 : 1 + self.init(rows: mode.isPhaseSplit && rank == 0 ? 0 : rows, wholeModel: mode.isPhaseSplit && rank == 1) + } + + /// The stages of `plan` whose layers one decode forward on `rank` runs. + func stages(of plan: QwenLayerStagePlan, rank: Int) -> [QwenLayerStagePlan.Stage] { + wholeModel ? plan.stages : [plan.stages[rank]] + } +} + /// One rank's loaded stage and what its family knows about a request's storage. protocol LayerStageResidentStage { var loaded: LoadedQwenLayerStage { get } /// The registered model's own ceiling for one request's named state. func namedStateByteCeiling() throws -> Int - /// This rank's named request storage, each array at the allocator's bound. + /// This rank's named request storage, each array at the allocator's bound, + /// for a request whose decode forwards run `decode`. func requestAllowance(plan: QwenLayerStagePlan, rank: Int, maximumTokens: Int, chunkSize: Int, + decode: LayerStageDecodeShape, bound: (Int) throws -> Int) throws -> QwenResidentRequestAllowance /// A recording capture's live gate, bound to this loaded source and to the /// allowance the owner reserved. @@ -72,6 +102,15 @@ protocol LayerStageResidentStage { var handoffGeometry: QwenLongPrefillBudgetGeometry? { get } } +extension LayerStageResidentStage { + /// A request that decodes one row a step on this rank's stage. + func requestAllowance(plan: QwenLayerStagePlan, rank: Int, maximumTokens: Int, chunkSize: Int, + bound: (Int) throws -> Int) throws -> QwenResidentRequestAllowance { + try requestAllowance(plan: plan, rank: rank, maximumTokens: maximumTokens, chunkSize: chunkSize, + decode: .plain, bound: bound) + } +} + /// Admits one rank's load through the registered family its identity names. /// Every family's catalog is closed; a model ID in none of them is refused. enum LayerStageResidentFamily { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Metadata/ClusterResidentModelCatalog.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Metadata/ClusterResidentModelCatalog.swift index ac7e7ecd6d..52bb65b3ab 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Metadata/ClusterResidentModelCatalog.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Metadata/ClusterResidentModelCatalog.swift @@ -20,7 +20,9 @@ public enum ClusterResidentModelCatalog { /// hyper-connection sites, and the Qwen 3.5 residual step /// (`ResidualRMSNorm`, which reads the FP32 all-sum of every /// row-parallel projection). Families whose sums only MLX's own kernels - /// read gain nothing from it. Only where the GPU waits changes. + /// read gain nothing from it. Only where the GPU waits changes. Gemma 4 + /// (`qwenDense`) reads its two sums a layer with MLX's own norm kernels: + /// the variable is set for its ranks too and changes nothing there. public var tensorParallelSumsAreFencedInputs: Bool { switch self { case .glm5Next, .qwenDense: return true diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift index f3b1ecc887..86d6163aed 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoLayerStageSession.swift @@ -16,6 +16,19 @@ import MLXLMCommon /// sliding-window layer. Positions come from each cache's own offset, which /// both stages advance by the same token counts. final class MiMoLayerStageSession { + /// Command-buffer commit limits of a decode step, a lane step and a + /// speculative round on the thread that encodes them, as GLM's and Qwen's + /// tensor-parallel decode keep them + /// (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`). Under + /// the rank's 16-operation guard (`ClusterWorkerEnvironmentGuards`) and + /// MLX's per-chip input-size bound, which each routed layer's expert + /// launch passes alone (it takes a whole expert bank), a decode step + /// commits a buffer every few launches, each a GPU gap. Prefill keeps the + /// rank's limits. Synchronization only: results never depend on the + /// partitioning. MLX keeps up to ten buffers in flight, so a step's + /// in-flight work spans the stage's layers (`MiMoRequestStateBudget`). + static let decodeCommandBuffers = GPU.CommandBufferLimits(operations: 100, megabytes: 1 << 20) + let identity: QwenLayerStageSessionIdentity let request: QwenLayerStageGenerationRequest private let stage: LoadedMiMoLayerStage @@ -178,7 +191,9 @@ final class MiMoLayerStageSession { do { try requireOpen() let frame = try schedule.admitDecode(offset: offset) - return try perform(tokens: [token], frame: frame, incoming: incoming, check: check) + return try GPU.withCommandBufferLimits(Self.decodeCommandBuffers) { + try perform(tokens: [token], frame: frame, incoming: incoming, check: check) + } } catch { try fail(error) } } @@ -611,7 +626,7 @@ extension MiMoLayerStageSession: IndependentHistoryBatchSession { frames.append(try session.schedule.admitDecode(offset: session.committedTokens)) histories.append(pages) } - return try MLX.withError { error in + return try GPU.withCommandBufferLimits(decodeCommandBuffers) { try MLX.withError { error in func checked() throws { try error.check(); try check() } try checked() let last = first.stage.layerCount - 1 @@ -636,7 +651,7 @@ extension MiMoLayerStageSession: IndependentHistoryBatchSession { } if rank == 0 { Stream.gpu.synchronize(); try checked() } return output - } + } } } catch { var failure: Error = error for session in sessions { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoPhaseSplit.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoPhaseSplit.swift index b67abc523b..d820841693 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoPhaseSplit.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoPhaseSplit.swift @@ -33,12 +33,13 @@ enum MiMoPhaseSplitState { /// in temporal order); a frame of one token is written in place (the /// buffer grows by `step` up to the window, then rotates). Returns the /// length of the arrays its `state` gives (its buffer, or the positions - /// written while fewer than the buffer) and its write index. - static func slidingState(window: Int, step: Int, frames: [Int]) throws -> (length: Int, index: Int) { + /// written while fewer than the buffer), its write index and whether it + /// has wrapped (rotated since its last frame of several tokens). + static func slidingState(window: Int, step: Int, frames: [Int]) throws -> (length: Int, index: Int, wrapped: Bool) { guard window >= 1, step >= 1, !frames.isEmpty, frames.allSatisfy({ $0 >= 1 }) else { throw ProbeError("A sliding-window layer needs a positive window and step, and a prompt") } - var capacity: Int?, index = 0, offset = 0 + var capacity: Int?, index = 0, offset = 0, wrapped = false for count in frames { if count == 1 { if capacity == nil || (offset >= capacity! && capacity! < window) { @@ -46,7 +47,7 @@ enum MiMoPhaseSplitState { index = offset } if capacity! - window > 0 { capacity = window; index = window } - if index == window { index = 0 } + if index == window { index = 0; wrapped = true } offset += 1; index += 1 } else { if var held = capacity { @@ -58,10 +59,10 @@ enum MiMoPhaseSplitState { } else { capacity = count } - offset += count; index = capacity! + offset += count; index = capacity!; wrapped = false } } - return (offset < capacity! ? offset : capacity!, index) + return (offset < capacity! ? offset : capacity!, index, wrapped) } /// The retained length alone (frames of several tokens each). @@ -100,16 +101,19 @@ enum MiMoPhaseSplitState { return shapes } - /// The rotating cache's metadata after the prompt (`RotatingKVCache.metaState`): - /// keep 0, the window, the cache's own step, the prompt as its offset and - /// the write index the frame grid gives. - static func slidingMetadata(window: Int, index: Int, prompt: Int, step: Int) -> [String] { + /// A sliding layer's page metadata after the prompt + /// (`MiMoV26IndependentHistoryCache.metaState`), the rotating cache's first + /// five values: keep 0, the window, the step, the prompt as its offset and + /// the write index the frame grid gives. The ordinary ring's are + /// `MiMoSlidingRing.metadata`. + static func pagedMetadata(window: Int, index: Int, prompt: Int, step: Int) -> [String] { ["0", String(window), String(step), String(prompt), String(index)] } /// The producer caches' arrays after the prompt, in `shapes` order, each /// checked against its agreed shape and (for a rotating cache) the - /// rotation the frame grid gives. Lazy views; the caller reads the bytes. + /// metadata, rotation included, the frame grid gives. Lazy views; the + /// caller reads the bytes. static func exportArrays(caches: [KVCache], configuration: MiMoV26Configuration, frames: [Int], shapes: [QwenPhaseSplitStateShape]) throws -> [MLXArray] { let prompt = frames.reduce(0, +) @@ -134,15 +138,17 @@ enum MiMoPhaseSplitState { let step = defaultStep(window: window) let expected = try slidingState(window: window, step: step, frames: frames) guard expected.length == keys.shape[2], - pages.metaState == slidingMetadata(window: window, index: expected.index, prompt: prompt, step: step) else { + pages.metaState == pagedMetadata(window: window, index: expected.index, prompt: prompt, step: step) else { throw ProbeError("Producer page rotation differs from the request frame grid") } } } else if let rotating = cache as? RotatingKVCache { - guard let window = geometry.slidingWindow, let step = Int(rotating.metaState[2]), - let expected = try? slidingState(window: window, step: step, frames: frames), + guard let window = geometry.slidingWindow, + let expected = try? slidingState(window: window, step: defaultStep(window: window), frames: frames), expected.length == keys.shape[2], - rotating.metaState == slidingMetadata(window: window, index: expected.index, prompt: prompt, step: step) else { + let metadata = MiMoSlidingRing.metadata(window: window, offset: prompt, index: expected.index, + wrapped: expected.wrapped), + rotating.metaState == metadata else { throw ProbeError("Producer layer \(local) rotation differs from the request's frame grid") } } else { @@ -157,7 +163,8 @@ enum MiMoPhaseSplitState { /// Installs adopted arrays into fresh caches: a full-attention layer's /// growing cache takes keys and values as they are; a sliding layer's - /// rotating cache also takes the rotation the frame grid gives. + /// rotating cache, a fresh ring of the model's, also takes the metadata, + /// rotation included, the frame grid gives. static func install(_ state: QwenLayerStageAdoptedState, into caches: [KVCache], shapes: [QwenPhaseSplitStateShape], frames: [Int], configuration: MiMoV26Configuration) throws { let prompt = frames.reduce(0, +) @@ -190,12 +197,14 @@ enum MiMoPhaseSplitState { try pages.validateRestore(keys: arrays.keys, values: arrays.values, offset: prompt, index: index) install.append { try pages.restore(keys: arrays.keys, values: arrays.values, offset: prompt, index: index) } } else if let rotating = cache as? RotatingKVCache { - guard let window = geometry.slidingWindow, let step = Int(rotating.metaState[2]), - let expected = try? slidingState(window: window, step: step, frames: frames), - expected.length == keys.shape[2] else { + guard let window = geometry.slidingWindow, + rotating.metaState == MiMoSlidingRing.metadata(window: window, offset: 0, index: 0, wrapped: false), + let expected = try? slidingState(window: window, step: defaultStep(window: window), frames: frames), + expected.length == keys.shape[2], + let metadata = MiMoSlidingRing.metadata(window: window, offset: prompt, index: expected.index, + wrapped: expected.wrapped) else { throw ProbeError("Adopted layer \(local) is not the sliding-window layer the frame grid describes") } - let metadata = slidingMetadata(window: window, index: expected.index, prompt: prompt, step: step) install.append { rotating.metaState = metadata rotating.state = [arrays.keys, arrays.values] diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoSlidingRing.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoSlidingRing.swift new file mode 100644 index 0000000000..04b6632d18 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Generation/MiMoSlidingRing.swift @@ -0,0 +1,34 @@ +import MLXLMCommon + +/// The metadata (`RotatingKVCache.metaState`) of a MiMo sliding-window +/// layer's ordinary cache, `RotatingKVCache(maxSize: window)` +/// (`MiMoV26TextModel.newCache`), in the layout the pinned SDK writes: keep, +/// window, step, offset, write index, capacity origin and whether the ring +/// has wrapped. Writes move only the offset, the write index and the wrapped +/// flag; every other value stays the fresh ring's. A ring with a kept prefix, +/// another step or origin, or a rewind reserve (an eighth value) is not the +/// model's: the prefix snapshot and the phase split refuse it, as they refuse +/// any other layout. +enum MiMoSlidingRing { + private static let offsetField = 3, indexField = 4, wrappedField = 6 + + /// The model's ring of `window` positions after writes that left it at + /// `offset`, writing next at `index`; nil when a fresh ring writes + /// another layout. + static func metadata(window: Int, offset: Int, index: Int, wrapped: Bool) -> [String]? { + var fields = RotatingKVCache(maxSize: window).metaState + guard fields.count == 7, fields[offsetField] == "0", fields[indexField] == "0", + fields[wrappedField] == "false" else { return nil } + fields[offsetField] = String(offset); fields[indexField] = String(index); fields[wrappedField] = String(wrapped) + return fields + } + + /// Whether `ring` is the model's ring: its metadata is a fresh ring's of + /// its window in every value but the three that writes move. + static func isModelRing(_ ring: RotatingKVCache) -> Bool { + let fields = ring.metaState + guard let window = ring.maxSize, window > 0, fields.count > wrappedField, + let index = Int(fields[indexField]), let wrapped = Bool(fields[wrappedField]) else { return false } + return fields == metadata(window: window, offset: ring.offset, index: index, wrapped: wrapped) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift index da00e26b35..8b61c79125 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/MTP/MiMoMTPGeneration.swift @@ -232,9 +232,30 @@ enum MiMoMTPGeneration { } /// Rank 0: run each window rank 1 asks for, check what it keeps, publish. + /// Every round encodes as a decode step does (`MiMoLayerStageSession.decodeCommandBuffers`). static func runProducer(session: MiMoLayerStageSession, control: QwenLayerStageGenerationControl, terms: MiMoMTPTerms, collective: Collective, onCommittedToken: (Int) throws -> Bool, check: () throws -> Void) throws -> Outcome { + try GPU.withCommandBufferLimits(MiMoLayerStageSession.decodeCommandBuffers) { + try producerRounds(session: session, control: control, terms: terms, collective: collective, + onCommittedToken: onCommittedToken, check: check) + } + } + + /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank + /// 0's publication. Every round, drafts included, encodes as a decode + /// step does (`MiMoLayerStageSession.decodeCommandBuffers`). + static func runConsumer(session: MiMoLayerStageSession, decoder: MiMoMTPDecoder, + control: QwenLayerStageGenerationControl, collective: Collective, + check: () throws -> Void) throws -> Outcome { + try GPU.withCommandBufferLimits(MiMoLayerStageSession.decodeCommandBuffers) { + try consumerRounds(session: session, decoder: decoder, control: control, collective: collective, check: check) + } + } + + private static func producerRounds(session: MiMoLayerStageSession, control: QwenLayerStageGenerationControl, + terms: MiMoMTPTerms, collective: Collective, + onCommittedToken: (Int) throws -> Bool, check: () throws -> Void) throws -> Outcome { let agreement = control.agreement guard collective.rank == 0 else { throw ProbeError("Only rank 0 runs the producer side of a speculative round") } var selected: [Int] = [], discarded = 0 @@ -295,11 +316,9 @@ enum MiMoMTPGeneration { return .init(selected: selected, finalDecision: finalDecision, discardedDecodeForwards: discarded, statistics: nil) } - /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank - /// 0's publication. - static func runConsumer(session: MiMoLayerStageSession, decoder: MiMoMTPDecoder, - control: QwenLayerStageGenerationControl, collective: Collective, - check: () throws -> Void) throws -> Outcome { + private static func consumerRounds(session: MiMoLayerStageSession, decoder: MiMoMTPDecoder, + control: QwenLayerStageGenerationControl, collective: Collective, + check: () throws -> Void) throws -> Outcome { let agreement = control.agreement, request = agreement.request guard collective.rank == 1 else { throw ProbeError("Only rank 1 runs the consumer side of a speculative round") } let stopTokens = Set(request.stopTokenIDs) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift index 848ce31596..7ed44e1dcd 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoPlacementFamily.swift @@ -10,14 +10,29 @@ import Foundation /// candidate alone adds the vision tower to rank 0 (the last rank of /// `pipeline_mtp_v1` holds the heads beside its stage). Under the phase split /// (a hand-off mode: kept, off by default) the decoding rank holds the whole -/// text model (the planner prices that with the layout's own sizes). Pure -/// metadata: no checkpoint payload and no GPU. +/// text model (the planner prices that with the layout's own sizes). The text +/// row may also run tensor parallel on two ranks (`MiMoTensorParallelPlan`). +/// Pure metadata: no checkpoint payload and no GPU. struct MiMoPlacementFamily: ClusterPlacementFamily { let imageCandidate: Bool let specification: MiMoRegisteredSpecification let profile: QwenLayerStageGenerationProfile let plans: [Int: MiMoLayerStagePlan] let layers: [MiMoLayerStagePlan.Layer] + /// The tensor-parallel plan when the text row lists the mode; nil for the + /// image candidate, which stays a pipeline candidate. + let tensorParallel: MiMoTensorParallelPlan? + /// The native request reservation of a tensor-parallel rank + /// (`MiMoTensorParallelRequestBudget`), set where the allocator's bound is + /// known (`ClusterPlacementLayouts.layout`); nil in metadata-only layouts. + var tensorParallelRequestAllowance: ClusterTensorParallelRequestAllowance? + /// The speculative rounds every tensor-parallel rank decodes in + /// (`ClusterMiMoTensorParallel`): the three heads whole beside its share + /// (the layout's `speculativeHead`) and each request's drafter state and + /// window rows, which the allowance above then carries too, as the rank's + /// LOAD gate charges them. Set with the allowance where the SDK's drafter + /// declaration is compiled; nil in metadata-only layouts. + var tensorParallelSpeculativeHead: ClusterTensorParallelSpeculativeHead? static func handles(configuration: Data) -> Bool { (try? MiMoRegisteredSpecification.specification(configuration: configuration)) != nil @@ -27,6 +42,8 @@ struct MiMoPlacementFamily: ClusterPlacementFamily { self.imageCandidate = imageCandidate specification = try MiMoRegisteredSpecification.specification(configuration: configuration) profile = try specification.profile(imageCandidate:imageCandidate) + tensorParallel = !imageCandidate && specification.supportedGenerationModes.contains(.tensorParallel) + ? try MiMoTensorParallelPlan(configuration: configuration) : nil var plans: [Int: MiMoLayerStagePlan] = [:] for cut in 1.. Bool { + layer(ofStoredTensor: name) != nil && name.contains(".mlp.switch_mlp.") + } + /// The text tensors (every indexed tensor no stage excludes) are the /// registered inventory. func requireRegisteredInventory(_ tensors: [ClusterPlacementStoredTensor]) throws { @@ -125,4 +153,40 @@ struct MiMoPlacementFamily: ClusterPlacementFamily { throw ProbeError("The artifact's tensor headers are not the registered MiMo inventory") } } + + // MARK: - Tensor parallel + + /// `MiMoTensorParallelResidentRuntime`'s plan: each layer sums its + /// attention partial and its feed-forward partial (layer 0's dense row, or + /// a routed layer's 8 experts combined locally in FP32), one FP32 hidden + /// row a token each, and each step agrees once on the vocabulary-split + /// selection. Each rank keeps its own KV heads. Equal shares with no + /// padding: every cut lands on whole heads, quantization groups and packed + /// words. Chosen only where predicted faster than the pipeline + /// (`ClusterTensorParallelChoice.fastest`): 97 sums a step cross the link. + /// Both modes decode in speculative rounds; the rounds of tensor parallel + /// are priced in memory (`tensorParallelSpeculativeHead`) and credited no + /// speed-up until records measure one (`docs/architecture/inference.md`). + var tensorParallelPlan: ClusterTensorParallelFamilyPlan? { + tensorParallel.map { plan in + ClusterTensorParallelFamilyPlan(plan: MiMoTensorParallelPlan.name, ranks: [plan.size], + reductionsPerLayer: plan.reductionsPerLayer, reductionsPerStep: plan.reductionsPerStep, + partialBytesPerToken: plan.partialBytesPerToken, stateDividesByHeads: true, + requestAllowance: tensorParallelRequestAllowance, speculativeHead: tensorParallelSpeculativeHead, + choice: .fastest) + } + } + + /// The plan's disposition, the same on both ranks: replicated (norms, + /// routers, the embedding), or divided by heads, channels, expert channels + /// or the head's vocabulary rows. Nil for a tensor the plan excludes, which + /// no range loads. + func tensorParallelCut(ofStoredTensor name: String) -> ClusterTensorParallelTensorCut? { + guard let plan = tensorParallel, let disposition = try? plan.disposition(of: name) else { return nil } + switch disposition { + case .replicated: return .replicated + case .divided: return .divided + case .excluded: return nil + } + } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRegisteredSpecification.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRegisteredSpecification.swift index 3c80e79f66..a96634705b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRegisteredSpecification.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRegisteredSpecification.swift @@ -62,7 +62,10 @@ struct MiMoRegisteredSpecification { /// every layer (all `sourceBytes`) and decodes alone after the other rank /// prefilled its share and handed its state over, or serves a request alone. /// Whether a Mac can hold every layer is the planner's and the load gate's - /// question on the Macs at hand, not this row's. + /// question on the Macs at hand, not this row's. Tensor parallel + /// (`MiMoTensorParallelResidentRuntime`, text only) is placed only where + /// the planner predicts it faster than the pipeline + /// (`MiMoPlacementFamily.tensorParallelPlan`, `ClusterTensorParallelChoice.fastest`). let supportedGenerationModes: [ClusterGenerationMode] // The earlier fixed reservation every profile started with; the row's @@ -101,7 +104,7 @@ struct MiMoRegisteredSpecification { fullKeyValueHeads: 4, slidingKeyValueHeads: 8, keyWidth: 192, valueWidth: 128, declaredContextTokens: 1_048_576, supportedPrefillSchedules: [.serial, .oneChunkLookahead], - supportedGenerationModes: [.pipeline, .pipelineCompactDecode, .phaseSplit, .pipelineMTP]), + supportedGenerationModes: [.pipeline, .pipelineCompactDecode, .phaseSplit, .tensorParallel, .pipelineMTP]), ] static func specification(_ model: MiMoRegisteredModel) throws -> Self { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift index 59ef8e4ac0..98f4a40c4b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Metadata/MiMoRequestStateBudget.swift @@ -11,7 +11,10 @@ import Foundation /// plus the chunk just appended, the same way. A stage also holds one residual /// chunk coming or going, and stage 1 one vocabulary row. The workspace term /// is the largest transient a forward is known to build: one full-attention -/// layer's score matrix for a chunk against the whole history, in float32. +/// layer's score matrix for a chunk against the whole history, in float32, +/// and never less than every full-attention layer's scores for the decode +/// rows at once (a decode step's command buffers keep the whole step in +/// flight, `MiMoLayerStageSession.decodeCommandBuffers`). struct MiMoRequestStateBudget: Encodable, Equatable { static let activationBytes = 2, growthStep = 256 let fullAttentionLayers: Int, slidingLayers: Int @@ -39,12 +42,16 @@ struct MiMoRequestStateBudget: Encodable, Equatable { reservedBytes: try QwenLongPrefillCheckedBytes.sum([reservedBytes, extra])) } + /// `decodeRows`: the most rows one decode forward runs (1, or a verify + /// window's `depth + 1`). static func estimate(specification spec: MiMoRegisteredSpecification, layers: Range, rank: Int, - maximumTokens: Int, chunkSize: Int, bound: (Int) throws -> Int) throws -> Self { + maximumTokens: Int, chunkSize: Int, decodeRows: Int = 1, + bound: (Int) throws -> Int) throws -> Self { let limits = try spec.contextLimits() guard (0...1).contains(rank), !layers.isEmpty, layers.lowerBound >= 0, layers.upperBound <= spec.layers, (1...limits.maximumContextTokens).contains(maximumTokens), - (1...limits.maximumChunkTokens).contains(chunkSize) else { + (1...limits.maximumChunkTokens).contains(chunkSize), + (1...limits.maximumChunkTokens).contains(decodeRows) else { throw MiMoProfileError("MiMo request state is outside the registered request scope") } let sum = QwenLongPrefillCheckedBytes.sum, product = QwenLongPrefillCheckedBytes.product @@ -66,7 +73,8 @@ struct MiMoRequestStateBudget: Encodable, Equatable { let boundary = try allowance(try product([chunkSize, spec.hidden, activationBytes]), 2) let row = rank == 1 ? try allowance(try product([spec.vocabulary, 4]), 2) : 0 // 64 query heads; the registered attention geometry fixes it. - let workspace = full == 0 ? 0 : try allowance(try product([64, chunkSize, capacity, 4]), 1) + let scoreRows = max(chunkSize, try product([decodeRows, full])) + let workspace = full == 0 ? 0 : try allowance(try product([64, scoreRows, capacity, 4]), 1) return .init(fullAttentionLayers: full, slidingLayers: sliding, fullAttentionStateBytes: fullState, slidingStateBytes: slidingState, boundaryBytes: boundary, rowBytes: row, workspaceBytes: workspace, reservedBytes: try sum([fullState, slidingState, boundary, row, workspace])) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Prefix/MiMoStagePrefixSnapshot.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Prefix/MiMoStagePrefixSnapshot.swift index 8adce64b3d..700ee4c0a6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Prefix/MiMoStagePrefixSnapshot.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Prefix/MiMoStagePrefixSnapshot.swift @@ -106,12 +106,16 @@ enum MiMoStagePrefixSnapshot { pair.conv.dim(0) == 1, pair.ssm.dim(0) == 1, pair.conv.dim(1) == pair.ssm.dim(1) else { throw ProbeError("MiMo prefix restore lacks sliding-window layer \(layer)") } - let meta = cache.metaState - guard meta.count == 5 else { throw ProbeError("MiMo prefix restore found an unknown ring") } + // The fresh ring's own values, with the offset and write + // position the original ring had after its frame: the tail in + // temporal order, not wrapped (a ring wrapped back to the end + // of its buffer continues the same). + guard let metadata = MiMoSlidingRing.metadata(window: window, offset: frontier, index: kept, + wrapped: false) else { + throw ProbeError("MiMo prefix restore found an unknown ring") + } cache.state = [owned(pair.conv), owned(pair.ssm)] - // keep, window, step as the fresh ring has them; offset and the - // write position as the original ring had them after its frame. - cache.metaState = [meta[0], meta[1], meta[2], String(frontier), String(kept)] + cache.metaState = metadata slidingLayers.insert(layer) } guard cache.offset == frontier else { throw ProbeError("MiMo prefix restore left a layer at another frontier") } @@ -147,8 +151,8 @@ enum MiMoStagePrefixSnapshot { static func kind(_ cache: KVCache) throws -> Kind { if let ring = cache as? RotatingKVCache { - guard let window = ring.maxSize, window > 0, ring.metaState.count == 5, ring.metaState[0] == "0" else { - throw ProbeError("MiMo prefix needs a sliding ring with no kept prefix") + guard let window = ring.maxSize, window > 0, MiMoSlidingRing.isModelRing(ring) else { + throw ProbeError("MiMo prefix needs the sliding ring the model builds") } return .sliding(window: window) } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift index a5f3a5ef14..981ba65d28 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentAdmission.swift @@ -150,7 +150,7 @@ struct MiMoResidentRequestAllowance { let forwardTokens = max(chunkSize, verificationTokens) let layers = phaseSplit && rank == 1 ? 0.. [ClusterGenerationMode: ClusterServingFeatures] { + let widest = [QwenBatchSettings.lanesEnvironmentName: String(QwenBatchWire.maximumLanes)] + return try Dictionary(uniqueKeysWithValues: modes.map { mode in + if mode == .tensorParallel { return (mode, MiMoTensorParallelResidentRuntime.servingFeatures) } + let batch = try MiMoBatchSettings.fromEnvironment(widest, mode: mode) + let prefixes = !(mode.isPhaseSplit || batch.usesPagedHistory) + return (mode, ClusterServingFeatures(promptPrefixReuse: prefixes, ssdPrefixTier: prefixes, + speculativeRounds: mode.usesSpeculativeHead, maximumLanes: batch.lanes, logprobs: false)) + }) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentRuntime.swift index 597a0e5734..2ef6dcb19d 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/Resident/MiMoResidentRuntime.swift @@ -188,9 +188,9 @@ public final class MiMoResidentRuntime { configBytes: read(directory.appendingPathComponent("config.json"), 1_048_576), manifestBytes: read(directory.appendingPathComponent("manifest.json"), 4_194_304), environment: environment, now: DispatchTime.now().uptimeNanoseconds, read: read) - guard admission.specification.supportedGenerationModes.contains(mode) else { + guard admission.specification.supportedGenerationModes.contains(mode), mode != .tensorParallel else { throw ProbeError("Generation mode \(mode.rawValue) is not in the resident row of " - + admission.specification.model.rawValue) + + admission.specification.model.rawValue + " (tensor parallel has its own owner)") } let speculativeTerms: MiMoMTPTerms? if mode.usesSpeculativeHead { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelDecoding.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelDecoding.swift new file mode 100644 index 0000000000..9fc0c6d437 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelDecoding.swift @@ -0,0 +1,439 @@ +import Cmlx +import DarkbloomClusterProtocol +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// How a request's tokens are chosen over the vocabulary-split head. Both +/// ranks derive the same rule from the request, so they issue the same +/// collectives in the same order. +enum MiMoTensorParallelSelectionRule: Equatable, Sendable { + /// Plain greedy: each rank's FP32 maximum and its token ID cross in the + /// step's agreement sum; the larger maximum wins, ties to the lower ID, + /// exactly the whole row's argmax. + case greedy + /// A greedy row that reports logprobs: the same choice, then the + /// vocabulary-split top-k gather (each rank's top `top` and its rows' + /// log-sum-exp in one small collective, `Gemma4TensorParallelSelection.topK`). + case greedyLogprobs(top: Int) + /// Every other row (a temperature, logit bias or penalties): the whole + /// row gathered bit for bit to every rank; rank 0 draws with the product's + /// sampler (and gathers the product's logprobs), and the token crosses in + /// the step's agreement sum. + case gatheredRow + + static func rule(_ sampling: ClusterWorkerSampling?) -> Self { + guard let sampling, !sampling.isGreedyNoOp else { return .greedy } + if !sampling.isStochastic, !sampling.dependsOnHistory { return .greedyLogprobs(top: sampling.topLogprobs) } + return .gatheredRow + } + + /// The rule's name in log lines. + var label: String { + switch self { + case .greedy: return "greedy" + case .greedyLogprobs(let top): return "greedy_top\(top)" + case .gatheredRow: return "gathered_row" + } + } +} + +/// One request on one rank of a MiMo V2.6 tensor-parallel model (or on the +/// whole model), on request-owned paged KV histories +/// (`MiMoV26IndependentHistoryCache`: 64-token pages, grown on demand, built +/// from the rank's own layers, so full layers hold this rank's KV heads at +/// key/value widths 192/128 and sliding layers keep the 128-token window and +/// the learned sink bias of this rank's query heads). +/// +/// Prefill runs the request's chunks; decode runs one token per step under +/// `decodeCommandBuffers`. Each step ends with one small agreement sum: per +/// rank `[value, token, stop, position]`. Greedy rows put their maximum and +/// its token ID (the vocabulary-split argmax); gathered rows put rank 0's +/// draw (rank 1 an ignored value that still depends on the row, so its sums +/// keep their order). A positive stop slot on either rank ends both after +/// that step (`QwenTensorParallelStopRule`); positions that differ end the +/// request as diverged state. Both ranks read a step's stop slots before +/// either commits its token, and rank 0 hears the owner's answer before the +/// next step is built, so no rank commits a token its peer skipped (the +/// late-answer race `Gemma4TensorParallelRequestLoop` guards against). Without +/// a reduction (`full`) every choice is local and no collective runs. +struct MiMoTensorParallelDecoding { + /// Decode steps' command-buffer commit limits on the encoding thread, as + /// GLM and Qwen tensor parallel set them (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`): + /// 100 operations instead of the rank's 16-operation guard, with the size + /// bound lifted (each routed layer's expert launch takes its whole bank as + /// an input). Prefill keeps the rank's limits. Synchronization only: + /// results never depend on the partitioning. + static let decodeCommandBuffers = GPU.CommandBufferLimits(operations: 100, megabytes: 1 << 20) + static let agreementSlots = 4 + + let model: MiMoTensorParallelModel + /// Records every forward's routed expert sets when set (oracles only): + /// each prefill chunk's are evaluated with its caches, each step's with + /// its selection. Values never change. + var routes: MiMoTensorParallelRouteRecorder? = nil + + struct Request { + let prompt: [Int] + let outputCount: Int + let chunk: Int + let stopTokenIDs: Set + let rule: MiMoTensorParallelSelectionRule + /// The product's sampler; required for `gatheredRow` (rank 0 draws). + let sampler: QwenStageTokenSampler? + /// Speculative rounds (`runRounds`); nil decodes one token a step. + var speculation: MiMoTensorParallelSpeculation? = nil + } + + /// What a step's selection made, for logprobs and oracle evidence. + struct Step { + let index: Int + let token: Int + /// This rank's rows of the step's logits `[1, V or V/2]`. + let logits: MLXArray + /// The whole row `[1, V]` (FP32), when the rule gathered it. + let row: MLXArray? + /// The whole row's top candidates, when the rule gathered them. + let top: (tokenIDs: [Int], logits: [Float], logprobs: [Float])? + /// The product sampler's logprobs (rank 0 of a gathered row that asks for them). + let sampledLogprobs: ClusterWorkerTokenLogprobs? + } + + struct Outcome { + var tokens: [Int] = [] + var finish: QwenTensorParallelStopRule.Finish = .length + /// This rank raised the stop (cancel, deadline, memory); the owner's + /// client stop is not one. + var stoppedHere = false + /// Rank 0's owner answered a token with a stop. + var ownerStopped = false + var caches: [MiMoV26IndependentHistoryCache] = [] + var firstTokenSeconds = 0.0 + var decodeSeconds = 0.0 + /// Speculative rounds' proposals and acceptance. + var statistics: MiMoMTPStatistics? + } + + var reduction: QwenTensorParallelReduction? { model.reduction } + var rank: Int { reduction?.rank ?? 0 } + + /// Both ranks were given the same request: one sum of the 64-bit + /// `digest` in four 16-bit slots per rank (exact in FP32). + func requestAgreed(_ digest: UInt64) throws -> Bool { + guard let reduction else { return true } + let mine = (0 ..< 4).map { Float((digest >> (16 * UInt64($0))) & 0xffff) } + var slots = [Float](repeating: 0, count: 4 * reduction.size) + for index in 0 ..< 4 { slots[4 * reduction.rank + index] = mine[index] } + let summed = reduction.allSum(MLXArray(slots)) + try MLX.withError { error in eval(summed); try error.check() } + let values = summed.asArray(Float.self) + return (0 ..< reduction.size).allSatisfy { Array(values[(4 * $0) ..< (4 * $0 + 4)]) == mine } + } + + /// Runs `request` from a cold paged history. `localStop` is this rank's + /// own reason to stop (cancel, deadline, memory), asked after each commit; + /// `publish(ordinal, token, logprobs)` (rank 0 only) hands a committed + /// token to the owner and returns its answer (false: a client stop); + /// `observe` sees each agreed step before its commit (oracles; it may + /// issue collectives of its own, in the same order on every rank). + func run(_ request: Request, localStop: () -> Bool = { false }, + publish: (Int, Int, ClusterWorkerTokenLogprobs?) throws -> Bool = { _, _, _ in true }, + observe: ((Step) throws -> Void)? = nil) throws -> Outcome { + let prompt = request.prompt + guard !prompt.isEmpty, request.outputCount >= 1, request.chunk >= 1, + prompt.allSatisfy({ (0 ..< model.plan.vocabularySize).contains($0) }) else { + throw ProbeError("MiMo tensor parallel generation: empty or out-of-vocabulary request") + } + if case .greedyLogprobs(let top) = request.rule { + guard (1 ... ClusterWorkerSampling.maximumTopLogprobs).contains(top) else { + throw ProbeError("MiMo tensor parallel generation: 1 to 20 logprob alternatives") + } + } + guard request.rule != .gatheredRow || request.sampler != nil else { + throw ProbeError("MiMo tensor parallel generation: a gathered row needs the product's sampler") + } + // A sampler that cannot verify drafts decodes one token a step, as the pipeline's rounds do. + if let speculation = request.speculation, + request.rule != .gatheredRow || (request.sampler?.admitsSpeculativeVerification ?? false) { + var result = try runRounds(request, speculation: speculation, localStop: localStop, publish: publish, + observe: observe) + result.outcome.statistics = result.statistics + return result.outcome + } + let started = MiMoTensorParallelModel.now() + let caches = try model.model.makeIndependentHistoryCaches() + var outcome = Outcome(caches: caches) + var logits = try prefill(prompt, chunk: request.chunk, caches: caches) + var previousOperations: Int32 = 0, previousMegabytes: Int32 = 0 + mlx_metal_set_thread_command_buffer_limits(Int32(Self.decodeCommandBuffers.operations), + Int32(Self.decodeCommandBuffers.megabytes), &previousOperations, &previousMegabytes) + defer { mlx_metal_set_thread_command_buffer_limits(previousOperations, previousMegabytes, nil, nil) } + var stopKeep: Float = 0 + steps: for index in 0 ..< request.outputCount { + let position = caches[0].offset + let choice = try select(logits, request: request, stop: stopKeep, position: position) + routes?.flush() + if let slot = choice.stop { endAtStop(slot, &outcome); break } + if index == 0 { outcome.firstTokenSeconds = MiMoTensorParallelModel.now() - started } + try observe?(choice.step(index)) + request.sampler?.commit(choice.token) + outcome.tokens.append(choice.token) + var wanted = true + if rank == 0 { wanted = try publish(index, choice.token, choice.logprobs) } + switch QwenTensorParallelStopRule.outcome(isStopToken: request.stopTokenIDs.contains(choice.token), + committed: outcome.tokens.count, + outputCount: request.outputCount, wanted: true) { + case .eos: outcome.finish = .eos; break steps + case .length: outcome.finish = .length; break steps + case .clientStop, .proceed: break + } + if !wanted { + stopKeep = Float(outcome.tokens.count) + outcome.ownerStopped = true + } else if localStop() { + stopKeep = Float(outcome.tokens.count) + outcome.stoppedHere = true + } + logits = try forward([choice.token], caches: caches) + } + // Both ranks ended after the same step with the same tokens: checked in one sum. + try agreeEnd(&outcome) + outcome.decodeSeconds = MiMoTensorParallelModel.now() - started - outcome.firstTokenSeconds + return outcome + } + + /// A rank asked both to stop: both keep the tokens it named. + func endAtStop(_ slot: Float, _ outcome: inout Outcome) { + let stop = QwenTensorParallelStopRule.stop(slot: slot) + outcome.tokens = Array(outcome.tokens.prefix(stop.keep)) + outcome.finish = stop.finish + } + + /// The prompt in chunks, each chunk's post-final-norm rows handed to the + /// drafter when rounds follow; the last position's logits `[1, V or V/2]`, not evaluated. + func prefill(_ prompt: [Int], chunk: Int, caches: [MiMoV26IndependentHistoryCache], + drafter: MiMoTensorParallelDrafter? = nil) throws -> MLXArray { + var offset = 0 + while true { + let end = min(prompt.count, offset + chunk) + let tokens = Array(prompt[offset ..< end]) + let output = try model.model.forwardIndependentHistory( + inputIDs: MLXArray(tokens.map(Int32.init)).reshaped(1, tokens.count), caches: caches, + logitsStart: tokens.count - 1) + try drafter?.observePrompt(tokens: tokens, hidden: output.normalizedHiddenStates) + if end == prompt.count { return output.logits[0..., -1, 0...] } + try MLX.withError { error in + eval(caches.flatMap { $0.innerState() } + (routes?.pending ?? [])) + try error.check() + } + routes?.flush() + offset = end + } + } + + func forward(_ tokens: [Int], caches: [MiMoV26IndependentHistoryCache]) throws -> MLXArray { + let input = MLXArray(tokens.map { Int32($0) }).reshaped(1, tokens.count) + return try model.model.forwardIndependentHistory(inputIDs: input, caches: caches, + logitsStart: tokens.count - 1).logits[0..., -1, 0...] + } + + struct Choice { + let token: Int + let stop: Float? + let logits: MLXArray + let row: MLXArray? + let top: (tokenIDs: [Int], logits: [Float], logprobs: [Float])? + let sampledLogprobs: ClusterWorkerTokenLogprobs? + + func step(_ index: Int) -> Step { + .init(index: index, token: token, logits: logits, row: row, top: top, sampledLogprobs: sampledLogprobs) + } + + /// The committed token's logprobs, when the request asks for them. A + /// greedy token's logit is the row's maximum, the gather's first + /// (`select` checks it), even when an exactly tied token leads the gather. + var logprobs: ClusterWorkerTokenLogprobs? { + if let sampledLogprobs { return sampledLogprobs } + guard let top, let first = top.logprobs.first else { return nil } + return .init(logprob: first, top: zip(top.tokenIDs, top.logprobs).map { .init(tokenID: $0, logprob: $1) }) + } + } + + /// One step's selection: the agreement sum (and the row gather or the + /// top-k gather its rule takes), evaluated. + func select(_ logits: MLXArray, request: Request, stop: Float, position: Int) throws -> Choice { + let values = logits.asType(.float32) + let selection = model.selection + var row: MLXArray? + var pending: [MLXArray] = [] + let mine: MLXArray + switch request.rule { + case .greedy, .greedyLogprobs: + let index = argMax(values, axis: -1).asType(.float32) + MLXArray(Float(selection.vocabularyRange.lowerBound)) + mine = concatenated([values.max(axis: -1), index, MLXArray([stop, Float(position)])], axis: 0) + case .gatheredRow: + let whole = selection.gather(values) + row = whole + let drawn = rank == 0 ? request.sampler!.sample(whole) : argMax(whole, axis: -1) + mine = concatenated([MLXArray([Float(0)]), drawn.asType(.float32).reshaped(1), + MLXArray([stop, Float(position)])], axis: 0) + } + let all: MLXArray + let ranks = reduction?.size ?? 1 + if let reduction { + let empty = MLXArray.zeros([Self.agreementSlots], dtype: .float32) + all = reduction.allSum(concatenated((0 ..< ranks).map { $0 == reduction.rank ? mine : empty }, axis: 0)) + } else { + all = mine + } + pending.append(all) + try MLX.withError { error in + eval(pending) + try error.check() + } + let agreed = all.asArray(Float.self) + guard agreed.count == Self.agreementSlots * ranks else { + throw ProbeError("MiMo tensor parallel selection has a wrong shape") + } + func slot(_ rank: Int, _ field: Int) -> Float { agreed[Self.agreementSlots * rank + field] } + guard (0 ..< ranks).allSatisfy({ slot($0, 3) == Float(position) }) else { + throw ProbeError("MiMo tensor-parallel ranks are at different positions") + } + let stops = (0 ..< ranks).map { slot($0, 2) }.filter { $0 > 0 } + var token = Int(slot(0, 1)) + var best = slot(0, 0) + if request.rule != .gatheredRow { + // The strictly greater maximum wins: ties go to the lower rank, which holds the lower IDs. + for other in 1 ..< ranks where slot(other, 0) > best { best = slot(other, 0); token = Int(slot(other, 1)) } + } + guard (0 ..< model.plan.vocabularySize).contains(token) else { + throw ProbeError("MiMo tensor parallel selection chose no token of the vocabulary") + } + var top: (tokenIDs: [Int], logits: [Float], logprobs: [Float])? + var sampled: ClusterWorkerTokenLogprobs? + if stops.isEmpty { + switch request.rule { + case .greedyLogprobs(let count): + let gathered = try selection.topK(logits, count: count) + // Both ranks hold the same values, so a refusal here ends both alike. + guard gathered.logits.first == best else { + throw ProbeError("MiMo tensor parallel logprobs do not lead with the greedy token's logit") + } + top = gathered + case .gatheredRow where rank == 0: sampled = request.sampler!.takePendingLogprobs() + default: break + } + } + return Choice(token: token, stop: stops.min(), logits: logits, row: row, top: top, sampledLogprobs: sampled) + } + + /// Every rank's token count and finish in one sum; ranks that ended + /// differently have diverged. + func agreeEnd(_ outcome: inout Outcome) throws { + guard let reduction else { return } + var slots = [Float](repeating: 0, count: 2 * reduction.size) + slots[2 * reduction.rank] = Float(outcome.tokens.count) + slots[2 * reduction.rank + 1] = Float(outcome.finish.code) + let summed = reduction.allSum(MLXArray(slots)) + try MLX.withError { error in eval(summed); try error.check() } + let values = summed.asArray(Float.self) + guard (0 ..< reduction.size).allSatisfy({ values[2 * $0] == values[0] && values[2 * $0 + 1] == values[1] }) else { + throw ProbeError("MiMo tensor-parallel ranks ended the request differently") + } + } +} + +/// Every forward's routed expert sets, per position and routed layer, for the +/// route-set oracle: the model hands it each selection +/// (`MiMoV26TextModel.observeRoutes`), and the engine reads them back after +/// each forward's evaluation (`flush`). +final class MiMoTensorParallelRouteRecorder { + /// The current forward's selections `[1, L, K]`, one per routed layer. + private(set) var pending: [MLXArray] = [] + /// `[position][routed layer]`: the selected experts, ascending. + private(set) var sets: [[[Int]]] = [] + + func observe(_ indices: MLXArray) { pending.append(indices) } + + func flush() { + guard !pending.isEmpty else { return } + eval(pending) + let positions = pending[0].dim(1), count = pending[0].dim(2) + let layers = pending.map { $0.asType(.int32).reshaped(-1).asArray(Int32.self) } + for position in 0 ..< positions { + sets.append(layers.map { $0[(position * count) ..< ((position + 1) * count)].map(Int.init).sorted() }) + } + pending = [] + } +} + +extension MiMoTensorParallelModel { + /// The resident runtime's path for one request (`MiMoTensorParallelDecoding`: + /// paged KV, the per-step agreement sum, decode command buffers), with the + /// oracle's evidence. Greedy with `recordTop` 1...20 takes the runtime's + /// logprob path (the split top-k gather) and records its candidates; + /// `sampling` draws with the product's sampler over the gathered row + /// (keyed on `seed`, stream 0). After each agreed step every rank also + /// gathers the whole row for its digest (oracle only), in one fixed order. + /// `recordRoutes` records every position's routed expert sets. + public func generatePaged(prompt: [Int], outputCount: Int, chunk: Int, recordTop: Int = 0, + sampling: Sampling? = nil, recordRoutes: Bool = false, + speculative: SpeculativeOptions? = nil) throws -> Generation { + guard (0 ... 64).contains(recordTop) else { throw ProbeError("MiMo tensor parallel generation: at most 64 logits per step") } + guard speculative == nil || !recordRoutes else { + throw ProbeError("MiMo tensor parallel generation: route sets are recorded without speculative rounds") + } + let speculation = try speculative.map { options -> MiMoTensorParallelSpeculation in + switch options.proposals { + case .heads: + guard let draftHead else { throw ProbeError("MiMo speculative rounds need the draft heads loaded") } + return try .init(depth: options.depth, proposer: .heads(draftHead)) + case .scripted(let tokens, let missEvery): + return try .init(depth: options.depth, proposer: .scripted(script: tokens, missEvery: missEvery)) + } + } + let wire = sampling.map { + ClusterWorkerSampling(temperature: $0.temperature, topP: 1, topK: 0, minP: 0, repetitionPenalty: 1, + repetitionContextSize: 0, frequencyPenalty: 0, presencePenalty: 0, seed: $0.seed, stream: 0, logitBias: []) + } + let rule: MiMoTensorParallelSelectionRule = wire.map { .rule($0) } + ?? ((1 ... ClusterWorkerSampling.maximumTopLogprobs).contains(recordTop) ? .greedyLogprobs(top: recordTop) : .greedy) + let sampler = try wire.map { QwenStageTokenSampler(try QwenStageSamplingState($0, promptTokens: prompt)) } + let selection = self.selection + var result = Generation() + let recorder = recordRoutes ? MiMoTensorParallelRouteRecorder() : nil + if let recorder { model.observeRoutes { _, indices in recorder.observe(indices) } } + defer { if recordRoutes { model.observeRoutes(nil) } } + let outcome = try MiMoTensorParallelDecoding(model: self, routes: recorder).run( + .init(prompt: prompt, outputCount: outputCount, chunk: chunk, stopTokenIDs: [], rule: rule, sampler: sampler, + speculation: speculation), + observe: { step in + guard recordTop > 0 else { return } + let top = try step.top ?? selection.topK(step.logits, count: recordTop) + result.topTokenIDs.append(top.tokenIDs) + result.topLogits.append(top.logits) + result.topLogprobs.append(top.logprobs) + let row = step.row ?? selection.gather(step.logits) + eval(row) + let values = row.asArray(Float.self) + result.stepRowSHA256.append(Self.digest(values)) + if step.index == outputCount - 1 { result.finalLogits = values } + }) + result.tokenIDs = outcome.tokens + result.routeSets = recorder?.sets + if let statistics = outcome.statistics { + result.speculativeRounds = statistics.rounds + result.draftedTokens = statistics.drafted + result.acceptedDrafts = statistics.accepted + result.acceptedByPosition = statistics.acceptedByPosition + } + result.firstTokenSeconds = outcome.firstTokenSeconds + result.decodeSeconds = outcome.decodeSeconds + let state = outcome.caches.flatMap(\.state) + eval(state) + result.cacheSHA256 = sha256(state.reduce(into: Data()) { $0.append($1.asData(access: .copy).data) }) + result.peakActiveBytes = Memory.peakMemory + return result + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelModel.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelModel.swift new file mode 100644 index 0000000000..4ae5827ff2 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelModel.swift @@ -0,0 +1,330 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +/// A MiMo V2.6 text model loaded whole, or as one rank's shard of +/// `MiMoTensorParallelPlan`, and greedy generation over it. +/// +/// - `full`: the unsharded model (the single-Mac reference on this code path). +/// - `shard(rank)`: this rank's heads and channels only, built by the SDK's +/// own MiMo modules from the rank's local configuration; every layer sums +/// its `o_proj` and feed-forward partials through `reduction`, and the head +/// projects this rank's vocabulary rows. `Gemma4TensorParallelSelection` +/// chooses across the ranks' rows (the vocabulary split is model-neutral). +/// Both ranks in one process (`Gemma4TensorParallelLocalPair`) are the +/// bitwise oracle of a two-process run. +public final class MiMoTensorParallelModel { + public enum Role: Equatable, Sendable { + case full + case shard(rank: Int) + + public var label: String { + switch self { + case .full: return "full" + case .shard(let rank): return "tp2-rank\(rank)" + } + } + } + + public let role: Role + public let plan: MiMoTensorParallelPlan + public let vocabularyRange: Range + public let loadSeconds: Double + public let loadedParameterBytes: Int + let model: MiMoV26TextModel + let reduction: QwenTensorParallelReduction? + /// The replicated next-N heads, when loaded (`loadDraftHeads`). + private(set) var draftHead: MiMoTensorParallelDraftHead? + + /// Speculative rounds for `generatePaged`: `depth` proposals a round from + /// the trained heads, or (oracles) from a script of tokens. + public struct SpeculativeOptions: Sendable { + public enum Proposals: Sendable { + case heads + /// Proposal for output index i is `tokens[i]`, except every + /// `missEvery`-th (0: none), moved to the next token ID. + case scripted(tokens: [Int], missEvery: Int) + } + public let depth: Int + public let proposals: Proposals + public init(depth: Int, proposals: Proposals) { self.depth = depth; self.proposals = proposals } + } + + /// Reads the three trained heads whole (replicated on every rank) from a + /// checkpoint directory with its own manifest; returns their bytes. + @discardableResult + public func loadDraftHeads(modelDirectory: URL) throws -> Int { + let head = try MiMoTensorParallelDraftHead.load(modelDirectory: modelDirectory, target: self) + draftHead = head + return head.headBytes + } + + func adopt(draftHead: MiMoTensorParallelDraftHead) { self.draftHead = draftHead } + + /// Reads a checkpoint directory (`config.json`, `model.safetensors.index.json` + /// and the files it names) directly: tools and oracles. Excluded + /// components (MTP, vision, audio, speech) are skipped by name; every other + /// tensor must be a text tensor of the plan. + public static func load(modelDirectory: URL, role: Role, reduction: QwenTensorParallelReduction?) throws + -> MiMoTensorParallelModel { + let configurationData = try Data(contentsOf: modelDirectory.appendingPathComponent("config.json")) + return try assemble(configurationData: configurationData, role: role, reduction: reduction) { keep in + let indexData = try Data(contentsOf: modelDirectory.appendingPathComponent("model.safetensors.index.json")) + guard let index = (try JSONSerialization.jsonObject(with: indexData) as? [String: Any])?["weight_map"] + as? [String: String] else { + throw ProbeError("MiMo tensor parallel load: the checkpoint index has no weight map") + } + var byFile: [String: [String]] = [:] + for (key, file) in index { + guard !file.contains("/"), file.hasSuffix(".safetensors") else { + throw ProbeError("MiMo tensor parallel load: the checkpoint index names an unexpected file") + } + byFile[file, default: []].append(key) + } + for file in byFile.keys.sorted() { + let arrays = try loadArrays(url: modelDirectory.appendingPathComponent(file)) + guard Set(arrays.keys) == Set(byFile[file]!) else { + throw ProbeError("MiMo tensor parallel load: \(file) differs from the index") + } + for key in byFile[file]!.sorted() { try keep(key, arrays[key]!) } + } + } + } + + /// What `assemble`'s tensors hand to `keep`. + enum Parts { + /// Every stored tensor whole; `keep` cuts this rank's part. + case whole + /// Only this rank's part of each tensor, already cut where the plan + /// divides it (`MiMoTensorParallelVerifiedLoad`): checked, never cut. + case rankParts + } + + /// The model of `role` from a configuration and its stored tensors: + /// `tensors` hands every stored tensor (by indexed name) to `keep`, which + /// cuts this rank's part (or checks a part already cut) and materializes + /// it at once. + static func assemble(configurationData: Data, role: Role, reduction: QwenTensorParallelReduction?, + parts: Parts = .whole, + tensors: (_ keep: (String, MLXArray) throws -> Void) throws -> Void) throws + -> MiMoTensorParallelModel { + let started = DispatchTime.now().uptimeNanoseconds + let plan = try MiMoTensorParallelPlan(configuration: configurationData) + let full = try JSONDecoder().decode(MiMoV26Configuration.self, from: configurationData) + var shard: MiMoV26TensorShard? + var configuration = full + switch role { + case .full: + guard reduction == nil else { throw ProbeError("MiMo tensor parallel load: only a shard takes a reduction") } + case .shard(let rank): + guard let reduction, reduction.size == plan.size, reduction.rank == rank else { + throw ProbeError("MiMo tensor parallel load: a shard needs the reduction of its own rank and group size") + } + let rankShard = try MiMoV26TensorShard(rank: rank) + shard = rankShard + configuration = try JSONDecoder().decode(MiMoV26Configuration.self, + from: plan.shardConfigurationData(configurationData, rank: rank)) + // The plan's configuration and the SDK's own derivation must agree. + let derived = try rankShard.localConfiguration(full) + guard configuration.fullAttention == derived.fullAttention, + configuration.slidingAttention == derived.slidingAttention, + configuration.intermediateSize == derived.intermediateSize, + configuration.moeIntermediateSize == derived.moeIntermediateSize, + configuration.hybridLayerPattern == full.hybridLayerPattern, + configuration.moeLayerFrequency == full.moeLayerFrequency, + configuration.vocabularySize == full.vocabularySize, configuration.hiddenSize == full.hiddenSize, + configuration.numNextnPredictLayers == 0, derived.numNextnPredictLayers == 0 else { + throw ProbeError("MiMo tensor parallel load: the plan's shard configuration differs from the SDK's") + } + } + let model = try MiMoV26TextModel(configuration) + if case .shard(let rank) = role, let reduction { + try model.installTensorParallel(reduce: { reduction.allSum($0) }, + vocabularyRows: plan.vocabularyRange(rank: rank)) + } + var weights: [String: MLXArray] = [:] + try tensors { key, value in + if case .excluded = try plan.disposition(of: key) { return } + let local = String(key.dropFirst(MiMoTensorParallelPlan.textNamespace.count)) + guard weights[local] == nil else { throw ProbeError("MiMo tensor parallel load: \(key) was given twice") } + let stored = try plan.expectedShape(key: key) + let axis = try plan.cut(key: key) + guard try MiMoV26TensorShard.splitAxis(local) == axis else { + throw ProbeError("MiMo tensor parallel load: the plan and the SDK cut \(key) differently") + } + var part = value + switch (parts, shard) { + case (.rankParts, .some): + guard value.shape == (try plan.localShape(key: key, shape: stored)) else { + throw ProbeError("MiMo tensor parallel load: \(key)'s part has shape \(value.shape), not the plan's") + } + case (_, let shard?): + guard stored == value.shape else { + throw ProbeError("MiMo tensor parallel load: \(key) has shape \(value.shape), not the plan's") + } + part = try shard.slice(value, axis: axis) + guard part.shape == (try plan.localShape(key: key, shape: value.shape)) else { + throw ProbeError("MiMo tensor parallel load: \(key) cut to \(part.shape), not the plan's") + } + case (_, nil): + guard stored == value.shape else { + throw ProbeError("MiMo tensor parallel load: \(key) has shape \(value.shape), not the plan's") + } + } + // Materialize each part now: the stored tensor is released before the next read. + eval(part) + weights[local] = part + } + quantize(model: model) { path, _ in + guard weights[path + ".scales"] != nil, + let policy = plan.policy(module: MiMoTensorParallelPlan.textNamespace + path) else { return nil } + return (policy.groupSize, policy.bits, policy.mode == "mxfp4" ? .mxfp4 : .affine) + } + try model.update(parameters: ModuleParameters.unflattened(weights), verify: [.all]) + model.freeze() + let parameters = model.parameters().flattened().map(\.1) + eval(parameters) + Memory.clearCache() + let vocabulary: Range + if case .shard(let rank) = role { vocabulary = plan.vocabularyRange(rank: rank) } else { vocabulary = 0 ..< plan.vocabularySize } + guard model.headVocabularyRange == vocabulary else { + throw ProbeError("MiMo tensor parallel load: the head does not project the plan's vocabulary rows") + } + return MiMoTensorParallelModel(role: role, plan: plan, vocabularyRange: vocabulary, + loadSeconds: Double(DispatchTime.now().uptimeNanoseconds - started) / 1e9, + loadedParameterBytes: parameters.reduce(0) { $0 + $1.nbytes }, model: model, reduction: reduction) + } + + private init(role: Role, plan: MiMoTensorParallelPlan, vocabularyRange: Range, loadSeconds: Double, + loadedParameterBytes: Int, model: MiMoV26TextModel, reduction: QwenTensorParallelReduction?) { + self.role = role; self.plan = plan; self.vocabularyRange = vocabularyRange; self.loadSeconds = loadSeconds + self.loadedParameterBytes = loadedParameterBytes; self.model = model; self.reduction = reduction + } + + /// The head's selections over this model's vocabulary rows. + public var selection: Gemma4TensorParallelSelection { + Gemma4TensorParallelSelection(vocabularyRange: vocabularyRange, vocabularySize: plan.vocabularySize, + reduction: reduction) + } + + func newCache() -> [KVCache] { model.newCache() } + + /// The last position's logits `[1, V or V/2]` after `tokens`, not evaluated. + func forward(_ tokens: [Int], cache: [KVCache]) throws -> MLXArray { + let input = MLXArray(tokens.map { Int32($0) }).reshaped(1, tokens.count) + return try model.forward(inputIDs: input, cache: cache, logitsStart: tokens.count - 1).logits[0..., -1, 0...] + } + + /// The prompt through the model in chunks; the last position's logits. + func prefill(_ prompt: [Int], chunk: Int, cache: [KVCache]) throws -> MLXArray { + var offset = 0 + while true { + let end = min(prompt.count, offset + chunk) + let logits = try forward(Array(prompt[offset ..< end]), cache: cache) + if end == prompt.count { return logits } + eval(cache.flatMap { $0.innerState() }) + offset = end + } + } + + /// One greedy generation's tokens and per-step evidence. + public struct Generation: Sendable { + public var tokenIDs: [Int] = [] + /// Per step, the top `recordTop` token IDs, their logits and log + /// probabilities over the whole vocabulary, highest first. + public var topTokenIDs: [[Int]] = [] + public var topLogits: [[Float]] = [] + public var topLogprobs: [[Float]] = [] + /// Per step, SHA-256 of the whole vocabulary's FP32 row. + public var stepRowSHA256: [String] = [] + /// The last step's whole row (FP32), when recorded. + public var finalLogits: [Float]? + /// SHA-256 of this model's KV caches after the last step. + public var cacheSHA256 = "" + /// Per position (prompt, then each fed output token), each routed + /// layer's selected experts, ascending; when recorded. + public var routeSets: [[[Int]]]? + /// Speculative rounds: rounds with proposals, proposals drafted and kept, kept per position. + public var speculativeRounds: Int? + public var draftedTokens: Int? + public var acceptedDrafts: Int? + public var acceptedByPosition: [Int]? + public var firstTokenSeconds = 0.0 + public var decodeSeconds = 0.0 + public var peakActiveBytes = 0 + } + + /// A keyed draw from the whole row: `MLXRandom.categorical` over it scaled + /// by `1 / temperature`, keyed by `seed + step` in `generate`; + /// `generatePaged` draws with the product's sampler instead. + public struct Sampling: Sendable, Equatable { + public let temperature: Float + public let seed: UInt64 + public init(temperature: Float, seed: UInt64) { self.temperature = temperature; self.seed = seed } + } + + /// Generation of `outputCount` tokens after `prompt`, prefilled in chunks + /// of `chunk`: greedy through the vocabulary-split argmax, or `sampling` + /// over the whole row gathered bit for bit on every rank, so each rank + /// draws the token one Mac draws from the same row. `recordTop` > 0 + /// records each step's top logits and log probabilities (a shard through + /// the vocabulary-split top-k gather), each step's whole row digest and + /// the final row (a shard through the row gather). Every rank issues its + /// collectives in one fixed order: the forward's, the selection, the + /// top-k gather, then the row gather. + public func generate(prompt: [Int], outputCount: Int, chunk: Int, recordTop: Int = 0, + sampling: Sampling? = nil) throws -> Generation { + guard !prompt.isEmpty, outputCount >= 1, chunk >= 1, + prompt.allSatisfy({ (0 ..< plan.vocabularySize).contains($0) }) else { + throw ProbeError("MiMo tensor parallel generation: empty or out-of-vocabulary request") + } + guard (0 ... 64).contains(recordTop) else { throw ProbeError("MiMo tensor parallel generation: at most 64 logits per step") } + guard sampling.map({ $0.temperature.isFinite && $0.temperature > 0 }) ?? true else { + throw ProbeError("MiMo tensor parallel generation: sampling needs a positive temperature") + } + let selection = self.selection + let cache = newCache() + var result = Generation() + let started = Self.now() + var logits = try prefill(prompt, chunk: chunk, cache: cache) + for step in 0 ..< outputCount { + let token: MLXArray + if let sampling { + token = MLXRandom.categorical(selection.gather(logits) * (1 / sampling.temperature), + key: MLXRandom.key(sampling.seed &+ UInt64(step))).asType(.int32) + } else { + token = selection.greedy(logits) + } + eval(token) + let id = Int(token.item(Int32.self)) + if recordTop > 0 { + let top = try selection.topK(logits, count: recordTop) + result.topTokenIDs.append(top.tokenIDs) + result.topLogits.append(top.logits) + result.topLogprobs.append(top.logprobs) + let row = selection.gather(logits) + eval(row) + let values = row.asArray(Float.self) + result.stepRowSHA256.append(Self.digest(values)) + if step == outputCount - 1 { result.finalLogits = values } + } + if step == 0 { result.firstTokenSeconds = Self.now() - started } + result.tokenIDs.append(id) + if step + 1 < outputCount { logits = try forward([id], cache: cache) } + } + result.decodeSeconds = Self.now() - started - result.firstTokenSeconds + let state = cache.flatMap(\.state) + eval(state) + result.cacheSHA256 = sha256(state.reduce(into: Data()) { $0.append($1.asData(access: .copy).data) }) + result.peakActiveBytes = Memory.peakMemory + return result + } + + static func digest(_ values: [Float]) -> String { + sha256(values.withUnsafeBufferPointer { Data(buffer: $0) }) + } + + static func now() -> Double { Double(DispatchTime.now().uptimeNanoseconds) / 1e9 } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelPlan.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelPlan.swift new file mode 100644 index 0000000000..b452650552 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelPlan.swift @@ -0,0 +1,382 @@ +import Foundation + +/// How the MiMo V2.6 Flash text model (`mimo_v2`, untied head; the registered +/// `mimo-v2.6-flash-mopd` artifact) divides across two ranks by heads and +/// channels with equal shares: `mimo_v26_heads_and_expert_channels_v1`. +/// CPU metadata only: nothing here imports MLX or reads a payload. +/// +/// - Attention: contiguous halves of the query heads with the KV heads they +/// read. `q_proj`, `k_proj`, `v_proj` by output rows, the sliding layers' +/// learned sink bias per query head, `o_proj` by input columns (registered: +/// 32 query heads per rank, 2 full and 4 sliding KV heads, sinks 32). +/// - Dense layer 0 and every routed expert: half the channels (gate/up output +/// rows; down input columns, axis 2 of the `[experts, hidden, width]` bank). +/// Every cut lands on whole quantization groups and packed words (registered: +/// 1,024 expert channels = 32 MXFP4 groups of 32), so no rank stores padding. +/// - Replicated: every norm, the router (`mlp.gate`: weight and score +/// correction, so both ranks choose the same experts), the final norm and +/// the token embedding (a lookup). The untied `lm_head` is divided by +/// vocabulary rows. +/// - Excluded: the trained MTP heads, the vision tower, the audio encoder and +/// the speech embeddings belong to no tensor-parallel text rank; `cut` +/// refuses them, and every other unknown name, as text. +/// +/// Collectives: per layer the `o_proj` partial (stored BF16, summed in FP32, +/// rounded once) and the feed-forward partial (layer 0's BF16 dense partial; +/// a routed layer's experts combined locally in FP32 with the replicated +/// router weights), one FP32 hidden row per token each; one per decode step +/// for the vocabulary-split selection. MTP stays off. +public struct MiMoTensorParallelPlan: Sendable, Equatable { + public static let name = "mimo_v26_heads_and_expert_channels_v1" + public let size = 2 + + /// What a rank does with one indexed tensor. + public enum Disposition: Equatable, Sendable { + case replicated + /// Each rank keeps its half along `axis` of the stored tensor. + case divided(axis: Int) + /// Not part of the tensor-parallel text model. + case excluded(component: String) + } + + /// A quantized module's packing. + public struct Policy: Equatable, Sendable { + public let mode: String + public let bits: Int + public let groupSize: Int + /// Logical values per stored 32-bit word. + public var valuesPerWord: Int { 32 / bits } + } + + public let hiddenSize: Int + public let layerCount: Int + public let vocabularySize: Int + public let denseWidth: Int + public let expertWidth: Int + public let expertCount: Int + public let expertsPerToken: Int + public let fullQueryHeads: Int + public let fullKVHeads: Int + public let fullHeadDim: Int + public let fullValueHeadDim: Int + public let slidingQueryHeads: Int + public let slidingKVHeads: Int + public let slidingHeadDim: Int + public let slidingValueHeadDim: Int + public let fullSinks: Bool + public let slidingSinks: Bool + /// Per layer: a sliding-window layer (`hybrid_layer_pattern` 1). + public let slidingLayers: [Bool] + /// Per layer: a routed MoE layer (`moe_layer_freq` 1). + public let routedLayers: [Bool] + public let configurationSHA256: String + private let defaultPolicy: Policy? + private let overridePolicies: [String: Policy] + + static let textNamespace = "language_model." + static let excludedComponents: [(prefix: String, component: String)] = [ + ("language_model.model.mtp.", "mtp"), ("vision_tower.", "vision"), + ("audio_encoder.", "audio"), ("speech_embeddings.", "speech"), + ] + + /// `configuration` is the artifact's whole `config.json`. + public init(configuration: Data) throws { + guard (1 ... 4 << 20).contains(configuration.count), + let root = try JSONSerialization.jsonObject(with: configuration) as? [String: Any] else { + throw ProbeError("MiMo tensor parallel plan: the configuration is not a bounded JSON object") + } + guard root["model_type"] as? String == "mimo_v2" else { + throw ProbeError("MiMo tensor parallel plan: expected a mimo_v2 configuration") + } + func integer(_ key: String) throws -> Int { + guard let value = BoundedProbeInput.integer(root[key]), value > 0 else { + throw ProbeError("MiMo tensor parallel plan: the configuration lacks a positive \(key)") + } + return value + } + func flag(_ key: String) throws -> Bool { + guard let number = root[key] as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { + throw ProbeError("MiMo tensor parallel plan: the configuration lacks the flag \(key)") + } + return number.boolValue + } + func flags(_ key: String, count: Int) throws -> [Bool] { + guard let values = root[key] as? [Any], values.count == count else { + throw ProbeError("MiMo tensor parallel plan: \(key) needs one entry per layer") + } + return try values.map { + guard let value = BoundedProbeInput.integer($0), (0 ... 1).contains(value) else { + throw ProbeError("MiMo tensor parallel plan: \(key) has an unknown layer kind") + } + return value == 1 + } + } + guard try !flag("tie_word_embeddings") else { + throw ProbeError("MiMo tensor parallel plan: only the untied head is covered") + } + guard try !flag("attention_bias") else { + throw ProbeError("MiMo tensor parallel plan: attention biases are not covered") + } + guard ["bfloat16", "float32"].contains(root["dtype"] as? String ?? "") else { + throw ProbeError("MiMo tensor parallel plan: activations are bfloat16 (float32 for synthetic checks)") + } + if let shared = root["n_shared_experts"], !(shared is NSNull), BoundedProbeInput.integer(shared) != 0 { + throw ProbeError("MiMo tensor parallel plan: shared experts are not covered") + } + hiddenSize = try integer("hidden_size") + layerCount = try integer("num_hidden_layers") + vocabularySize = try integer("vocab_size") + denseWidth = try integer("intermediate_size") + expertWidth = try integer("moe_intermediate_size") + expertCount = try integer("n_routed_experts") + expertsPerToken = try integer("num_experts_per_tok") + fullQueryHeads = try integer("num_attention_heads") + fullKVHeads = try integer("num_key_value_heads") + fullHeadDim = try integer("head_dim") + fullValueHeadDim = try integer("v_head_dim") + slidingQueryHeads = try integer("swa_num_attention_heads") + slidingKVHeads = try integer("swa_num_key_value_heads") + slidingHeadDim = try integer("swa_head_dim") + slidingValueHeadDim = try integer("swa_v_head_dim") + fullSinks = try flag("add_full_attention_sink_bias") + slidingSinks = try flag("add_swa_attention_sink_bias") + slidingLayers = try flags("hybrid_layer_pattern", count: layerCount) + routedLayers = try flags("moe_layer_freq", count: layerCount) + guard expertsPerToken <= expertCount else { + throw ProbeError("MiMo tensor parallel plan: more experts per token than experts") + } + configurationSHA256 = sha256(configuration) + + // The default policy, and one entry per quantized module (indexed path). + let quantization = (root["quantization"] ?? root["quantization_config"]) as? [String: Any] ?? [:] + func policy(_ entry: [String: Any], _ label: String) throws -> Policy { + guard let bits = BoundedProbeInput.integer(entry["bits"]), + let group = BoundedProbeInput.integer(entry["group_size"]) else { + throw ProbeError("MiMo tensor parallel plan: quantization entry \(label) lacks bits or a group size") + } + let mode = entry["mode"] as? String ?? "affine" + guard (mode == "affine" && [4, 8].contains(bits) && [32, 64, 128].contains(group)) + || (mode == "mxfp4" && bits == 4 && group == 32) else { + throw ProbeError("MiMo tensor parallel plan: quantization entry \(label) is not affine 4/8-bit or MXFP4 g32") + } + return Policy(mode: mode, bits: bits, groupSize: group) + } + defaultPolicy = quantization["bits"] == nil ? nil : try policy(quantization, "default") + var overrides: [String: Policy] = [:] + for (key, value) in quantization where !["group_size", "bits", "mode"].contains(key) { + if Self.excludedComponents.contains(where: { key.hasPrefix($0.prefix) }) { continue } + guard let entry = value as? [String: Any] else { + throw ProbeError("MiMo tensor parallel plan: quantization entry \(key) is not a policy") + } + overrides[key] = try policy(entry, key) + } + overridePolicies = overrides + + // Whole query groups per rank, and every cut on whole groups and words. + for (label, queries, kv) in [("full", fullQueryHeads, fullKVHeads), ("sliding", slidingQueryHeads, slidingKVHeads)] { + guard kv % size == 0, queries % kv == 0 else { + throw ProbeError("MiMo tensor parallel plan: \(label) KV heads (\(kv)) do not split into whole query groups") + } + } + guard vocabularySize % size == 0, denseWidth % size == 0, expertWidth % size == 0 else { + throw ProbeError("MiMo tensor parallel plan: the vocabulary or a channel width does not divide by \(size)") + } + for module in overrides.keys { + guard module.hasPrefix(Self.textNamespace), + let quantized = try? textTensor(String(module.dropFirst(Self.textNamespace.count)) + ".weight"), + quantized.quantized else { + throw ProbeError("MiMo tensor parallel plan: quantization entry for an unknown text module \(module)") + } + } + for module in ["model.embed_tokens", "lm_head"] { + if let packing = self.policy(module: Self.textNamespace + module) { + guard packing == Policy(mode: "affine", bits: 8, groupSize: 64) else { + throw ProbeError("MiMo tensor parallel plan: \(module) must be affine 8-bit, group 64") + } + } + } + for layer in 0 ..< layerCount { + let base = Self.layerRoot(layer) + let expertsBits = routedLayers[layer] ? self.policy(module: base + "mlp.switch_mlp.down_proj") : nil + let checks: [(String, Int, Policy?)] = [ + ("o_proj", queryHeads(layer: layer) / size * valueHeadDim(layer: layer), self.policy(module: base + "self_attn.o_proj")), + routedLayers[layer] ? ("expert down_proj", expertWidth / size, expertsBits) + : ("down_proj", denseWidth / size, self.policy(module: base + "mlp.down_proj")), + ] + for (label, width, packing) in checks { + if let packing, width % packing.groupSize != 0 || width % packing.valuesPerWord != 0 { + throw ProbeError("MiMo tensor parallel plan: layer \(layer)'s \(label) shard (\(width)) does not land on a quantization group") + } + } + } + } + + static func layerRoot(_ layer: Int) -> String { "language_model.model.layers.\(layer)." } + + public func queryHeads(layer: Int) -> Int { slidingLayers[layer] ? slidingQueryHeads : fullQueryHeads } + public func kvHeads(layer: Int) -> Int { slidingLayers[layer] ? slidingKVHeads : fullKVHeads } + public func headDim(layer: Int) -> Int { slidingLayers[layer] ? slidingHeadDim : fullHeadDim } + public func valueHeadDim(layer: Int) -> Int { slidingLayers[layer] ? slidingValueHeadDim : fullValueHeadDim } + public func hasSinks(layer: Int) -> Bool { slidingLayers[layer] ? slidingSinks : fullSinks } + + /// Per layer, the KV heads one rank holds (registered: 2 full, 4 sliding). + public var kvHeadsPerRank: [Int] { (0 ..< layerCount).map { kvHeads(layer: $0) / size } } + /// Per layer, the query heads (and sink biases) one rank holds. + public var queryHeadsPerRank: [Int] { (0 ..< layerCount).map { queryHeads(layer: $0) / size } } + + /// The packing of a quantized text module (indexed path), when stored packed. + public func policy(module path: String) -> Policy? { overridePolicies[path] ?? defaultPolicy } + + /// Vocabulary rows this rank's head projects. + public func vocabularyRange(rank: Int) -> Range { + let half = vocabularySize / size + return (rank * half) ..< ((rank + 1) * half) + } + + // MARK: - Collective facts + + public let reductionsPerLayer = 2 + public let reductionsPerStep = 1 + /// FP32 bytes one token's collective carries (one hidden row). + public var partialBytesPerToken: Int { hiddenSize * 4 } + public var reductionsPerForward: Int { reductionsPerLayer * layerCount } + + /// What two ranks must agree on before they serve together: the plan, + /// where each sum is taken and what it carries. Each row-parallel product + /// takes an exact FP32 widening of its input, so its partial is stored as + /// FP32 and rounded only once, after the sum (v2; v1 stored BF16 partials). + public static let arithmeticAgreementFields = [ + name, + "mimo-v26-o-proj-partial-stored-float32-sum-float32-rounded-once-v2", + "mimo-v26-dense-down-partial-stored-float32-sum-float32-rounded-once-v2", + "mimo-v26-expert-rows-stored-float32-local-float32-combine-sum-float32-rounded-once-v2", + "mimo-v26-untied-head-vocabulary-halves-v1", + "mimo-v26-mtp-off-v1", + ] + + /// Binds the plan, its agreement fields and the source configuration. + public var fingerprint: String { + sha256(Data(([Self.name, configurationSHA256] + Self.arithmeticAgreementFields).joined(separator: "\n").utf8)) + } + + // MARK: - Configuration + + /// The configuration `rank` constructs, canonical JSON: half the query + /// and KV heads of both layer kinds and half of both channel widths, no + /// MTP heads, towers or their metadata. Every other field is whole. + public func shardConfigurationData(_ configuration: Data, rank: Int) throws -> Data { + guard (0 ..< size).contains(rank), sha256(configuration) == configurationSHA256, + var fields = try JSONSerialization.jsonObject(with: configuration) as? [String: Any] else { + throw ProbeError("MiMo tensor parallel plan: shard configuration of another source or rank") + } + for key in ["num_attention_heads", "num_key_value_heads", "swa_num_attention_heads", + "swa_num_key_value_heads", "intermediate_size", "moe_intermediate_size"] { + guard let value = BoundedProbeInput.integer(fields[key]), value % size == 0 else { + throw ProbeError("MiMo tensor parallel plan: \(key) does not halve") + } + fields[key] = value / size + } + fields["num_nextn_predict_layers"] = 0 + for key in ["omlx_mimo_mtp", "vision_config", "audio_config", "processor_config"] { fields[key] = nil } + return try JSONSerialization.data(withJSONObject: fields, options: [.sortedKeys]) + } + + // MARK: - Stored tensors + + /// The disposition of one indexed tensor. Unknown names throw. + public func disposition(of name: String) throws -> Disposition { + if let excluded = Self.excludedComponents.first(where: { name.hasPrefix($0.prefix) }) { + return .excluded(component: excluded.component) + } + guard name.hasPrefix(Self.textNamespace) else { + throw ProbeError("MiMo tensor parallel plan: unknown tensor \(name)") + } + let tensor = try textTensor(String(name.dropFirst(Self.textNamespace.count))) + return tensor.axis.map { .divided(axis: $0) } ?? .replicated + } + + /// The axis a text tensor is divided on (nil: replicated). Excluded and + /// unknown tensors throw: they are not part of the text model. + public func cut(key: String) throws -> Int? { + switch try disposition(of: key) { + case .replicated: return nil + case .divided(let axis): return axis + case .excluded(let component): + throw ProbeError("MiMo tensor parallel plan: \(component) tensors are not part of the tensor-parallel text model (\(key))") + } + } + + /// The stored shape of a text tensor of the whole model. + public func expectedShape(key: String) throws -> [Int] { + guard key.hasPrefix(Self.textNamespace), Self.excludedComponents.allSatisfy({ !key.hasPrefix($0.prefix) }) else { + throw ProbeError("MiMo tensor parallel plan: not a text tensor \(key)") + } + return try textTensor(String(key.dropFirst(Self.textNamespace.count))).shape + } + + /// The shape one rank stores for a text tensor of `shape`, refusing a + /// cut axis that would split a packed word or a quantization group. + public func localShape(key: String, shape: [Int]) throws -> [Int] { + guard let axis = try cut(key: key) else { return shape } + guard shape.indices.contains(axis), shape[axis] % size == 0 else { + throw ProbeError("MiMo tensor parallel plan: \(key) \(shape) does not halve on axis \(axis)") + } + var local = shape + local[axis] /= size + return local + } + + /// A text tensor by its local name (`model.…` or `lm_head.…`): its axis, + /// stored shape and whether its module is stored packed. + private func textTensor(_ name: String) throws -> (axis: Int?, shape: [Int], quantized: Bool) { + func unknown() -> ProbeError { ProbeError("MiMo tensor parallel plan: unknown text tensor \(name)") } + let parts = name.split(separator: ".", omittingEmptySubsequences: false).map(String.init) + guard let leaf = parts.last, !parts.contains("") else { throw unknown() } + let module = parts.dropLast().joined(separator: ".") + // A packed module stores weight words, scales and (affine) offsets. + func packed(_ logical: [Int], axis: Int?) throws -> (axis: Int?, shape: [Int], quantized: Bool) { + guard let packing = policy(module: Self.textNamespace + module) else { + guard leaf == "weight" else { throw unknown() } + return (axis, logical, false) + } + let leading = Array(logical.dropLast()), last = logical[logical.count - 1] + switch leaf { + case "weight": return (axis, leading + [last / packing.valuesPerWord], true) + case "scales": return (axis, leading + [last / packing.groupSize], true) + case "biases" where packing.mode == "affine": return (axis, leading + [last / packing.groupSize], true) + default: throw unknown() + } + } + switch module { + case "model.embed_tokens": return try packed([vocabularySize, hiddenSize], axis: nil) + case "lm_head": return try packed([vocabularySize, hiddenSize], axis: 0) + case "model.norm" where leaf == "weight": return (nil, [hiddenSize], false) + default: break + } + guard parts.count >= 5, parts[0] == "model", parts[1] == "layers", let layer = Int(parts[2]), + String(layer) == parts[2], (0 ..< layerCount).contains(layer) else { throw unknown() } + let rest = parts[3...].joined(separator: ".") + let routed = routedLayers[layer] + switch rest { + case "input_layernorm.weight", "post_attention_layernorm.weight": return (nil, [hiddenSize], false) + case "self_attn.attention_sink_bias" where hasSinks(layer: layer): return (0, [queryHeads(layer: layer)], false) + case "mlp.gate.weight" where routed: return (nil, [expertCount, hiddenSize], false) + case "mlp.gate.e_score_correction_bias" where routed: return (nil, [expertCount], false) + default: break + } + let queries = queryHeads(layer: layer), kv = kvHeads(layer: layer) + switch parts[3 ..< parts.count - 1].joined(separator: ".") { + case "self_attn.q_proj": return try packed([queries * headDim(layer: layer), hiddenSize], axis: 0) + case "self_attn.k_proj": return try packed([kv * headDim(layer: layer), hiddenSize], axis: 0) + case "self_attn.v_proj": return try packed([kv * valueHeadDim(layer: layer), hiddenSize], axis: 0) + case "self_attn.o_proj": return try packed([hiddenSize, queries * valueHeadDim(layer: layer)], axis: 1) + case "mlp.gate_proj" where !routed, "mlp.up_proj" where !routed: + return try packed([denseWidth, hiddenSize], axis: 0) + case "mlp.down_proj" where !routed: return try packed([hiddenSize, denseWidth], axis: 1) + case "mlp.switch_mlp.gate_proj" where routed, "mlp.switch_mlp.up_proj" where routed: + return try packed([expertCount, expertWidth, hiddenSize], axis: 1) + case "mlp.switch_mlp.down_proj" where routed: return try packed([expertCount, hiddenSize, expertWidth], axis: 2) + default: throw unknown() + } + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRequestBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRequestBudget.swift new file mode 100644 index 0000000000..3359bac73e --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRequestBudget.swift @@ -0,0 +1,126 @@ +import DarkbloomClusterPlacement +import Foundation + +/// What a MiMo tensor-parallel rank holds beside its weights, as its LOAD and +/// request gates charge it (`MiMoTensorParallelResidentRuntime`) and the +/// planner quotes it (`ClusterTensorParallelFamilyPlan.requestAllowance`), from +/// the plan's per-rank geometry. A conservative charge, not a measured one: no +/// hardware has measured a MiMo tensor-parallel rank. Every array is charged at +/// the allocator's bound. +/// +/// Per request (`requestBytes`, what a reservation charges at its own context): +/// - Paged KV (`MiMoV26IndependentHistoryCache`, 64-token BF16 pages) at this +/// rank's KV heads and widths: a full layer holds the whole context; a +/// sliding layer at most its window plus a chunk, charged twice (a chunk's +/// append rewrites the kept rows into new pages while the old ones live). +/// - Every layer's gathered history at once, and the widest again: attention +/// reads a layer's pages concatenated, and a decode step's 100-operation +/// command buffers (`MiMoTensorParallelDecoding.decodeCommandBuffers`) keep +/// the whole step in flight. +/// - One chunk's activations: the residual and its normed rows, this rank's +/// query, key and value rows and attention output, its selected experts' +/// gate/up rows and layer 0's dense ones. +/// - The chunk's FP32 partials: the attention and feed-forward rows, the sum's +/// output, and the 8 selected experts' rows before the local combine. +/// - The full layers' attention scores at this rank's query heads (FP32), as +/// if materialized: one chunk against the context, and never less than +/// every full layer's decode row at once (the step in flight). +/// - The head: this rank's logits, the gathered whole row and the top-k (FP32). +/// +/// Once per rank (`rankBytes`): the conservative activation floor until +/// hardware measures one for a MiMo tensor-parallel rank (5.5 GiB, the +/// provider's default reserve, as GLM's and Gemma's ranks keep), the +/// freed-buffer cache a ready rank keeps, and eight sealed frames of a chunk's +/// partial (`ClusterTensorParallelRequestAllowance`). +struct MiMoTensorParallelRequestBudget: Equatable, Sendable { + static let pageTokens = 64 + /// `UnifiedMemoryCap.defaultActivationReserveBytes`: 5.5 GiB. A measured + /// constant replaces it once a pair measures a rank's peak. + static let activationFloorBytes = 11 * 1024 * 1024 * 1024 / 2 + /// The freed-buffer cache a ready rank keeps, as GLM tensor parallel keeps + /// it (serving at zero halved GLM's throughput). Charged under every + /// allocator policy: the planner does not know which one a rank runs. + static let freedBufferCacheBytes = 4 << 30 + + let contextTokens: Int + let chunkTokens: Int + let historyBytes: Int + let activationBytes: Int + let partialBytes: Int + let scoreBytes: Int + let headBytes: Int + let allowance: ClusterTensorParallelRequestAllowance + + /// What one request of `contextTokens` reserves on a rank. + var requestBytes: Int { historyBytes + activationBytes + partialBytes + scoreBytes + headBytes } + /// What a rank holds once beside every request it serves. + var rankBytes: Int { Self.activationFloorBytes + Self.freedBufferCacheBytes + allowance.collectiveScratchBytes } + + /// The reserve of a rank that decodes in speculative rounds: `speculativeRequestBytes` (the drafter's state + /// and the window's rows) beside the request, as its LOAD gate and every reservation add them. + func allowance(speculativeRequestBytes: Int, + allocationBound: (Int) throws -> Int) throws -> ClusterTensorParallelRequestAllowance { + guard speculativeRequestBytes >= 0 else { throw ProbeError("MiMo speculative request bytes are negative") } + return try ClusterTensorParallelRequestAllowance(maximumContextTokens: allowance.maximumContextTokens, + maximumChunkTokens: allowance.maximumChunkTokens, + requestBytesExcludingCollectives: QwenLongPrefillCheckedBytes.sum([allowance.requestBytesExcludingCollectives, + speculativeRequestBytes]), + maximumCollectivePayloadBytes: allowance.maximumCollectivePayloadBytes, + maximumCollectiveFrameBytes: allowance.maximumCollectiveFrameBytes, allocationBound: allocationBound) + } + + static func derive(plan: MiMoTensorParallelPlan, slidingWindow: Int, contextTokens: Int, chunkTokens: Int, + allocationBound: (Int) throws -> Int) throws -> Self { + let sum = QwenLongPrefillCheckedBytes.sum, product = QwenLongPrefillCheckedBytes.product + guard slidingWindow > 0, contextTokens > 0, chunkTokens > 0 else { + throw ProbeError("MiMo tensor-parallel request budget needs a window, a context and a chunk") + } + let chunk = min(contextTokens, chunkTokens) + func bound(_ logical: Int, count: Int = 1) throws -> Int { + let allocated = try allocationBound(logical) + guard logical > 0, allocated >= logical, count >= 0 else { + throw ProbeError("MiMo tensor-parallel request allocator bound is invalid") + } + return try product([allocated, count]) + } + var pages = 0, gathered = 0, widest = 0, fullLayers = 0 + for layer in 0 ..< plan.layerCount { + let sliding = plan.slidingLayers[layer] + let rowBytes = try product([plan.kvHeads(layer: layer) / plan.size, + plan.headDim(layer: layer) + plan.valueHeadDim(layer: layer), 2]) + let rows = sliding ? min(contextTokens, slidingWindow - 1 + chunk) : contextTokens + let paged = try bound(product([(rows + pageTokens - 1) / pageTokens, pageTokens, rowBytes])) + let view = try bound(product([rows, rowBytes])) + pages = try sum([pages, product([paged, sliding ? 2 : 1])]) + gathered = try sum([gathered, view]) + widest = max(widest, view) + if !sliding { fullLayers += 1 } + } + let hidden = plan.hiddenSize + let queries = (0 ..< plan.layerCount).map { plan.queryHeads(layer: $0) / plan.size }.max() ?? 0 + let width = (0 ..< plan.layerCount).map { plan.headDim(layer: $0) + plan.valueHeadDim(layer: $0) }.max() ?? 0 + let perToken = try sum([ + product([hidden, 2, 2]), // residual and normed rows + product([queries, width, 2, 2]), // q/k/v rows and attention output + product([plan.expertsPerToken, plan.expertWidth / plan.size, 2, 4]), // selected experts' gate/up + product([plan.denseWidth / plan.size, 2, 2]), // layer 0's gate/up + ]) + let row = try product([chunk, hidden, 4]) + // The attention and feed-forward partials and the sum's output; the selected experts' rows. + let partials = try sum([bound(row, count: 3), bound(product([row, plan.expertsPerToken]))]) + let scores = fullLayers == 0 ? 0 + : try bound(product([max(chunk, fullLayers), contextTokens, queries, 4])) + let head = try bound(product([plan.vocabularySize, 4]), count: 2 + plan.size) + let history = try sum([pages, gathered, widest]) + let activations = try bound(product([chunk, perToken])) + let payload = try product([chunk, plan.partialBytesPerToken]) + let frame = try sum([payload, QwenTensorParallelSealCodec.frameOverhead]) + let request = try sum([history, activations, partials, scores, head]) + let allowance = try ClusterTensorParallelRequestAllowance(maximumContextTokens: contextTokens, + maximumChunkTokens: chunk, + requestBytesExcludingCollectives: sum([request, activationFloorBytes, freedBufferCacheBytes]), + maximumCollectivePayloadBytes: payload, maximumCollectiveFrameBytes: frame, allocationBound: allocationBound) + return .init(contextTokens: contextTokens, chunkTokens: chunk, historyBytes: history, activationBytes: activations, + partialBytes: partials, scoreBytes: scores, headBytes: head, allowance: allowance) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift new file mode 100644 index 0000000000..012085a7f2 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelResidentRuntime.swift @@ -0,0 +1,553 @@ +import DarkbloomClusterPlacement +import DarkbloomClusterProtocol +import DarkbloomClusterSecurity +import Foundation +import MLX +import MLXLLM + +/// The worker's resident owner for `tensor_parallel_v1` on the registered +/// MiMo V2.6 Flash text row (`MiMoTensorParallelPlan`): both ranks hold every +/// layer, each with half of every head- and channel-parallel weight and half +/// the vocabulary rows of the untied head, run every prefill chunk and decode +/// step together, and sum each layer's attention and feed-forward partials +/// with the sealed all-sum inside the lazy graph, under the session's keyed +/// data plane. Text only: the private image candidate stays a pipeline +/// candidate. With a speculative depth (`--mtp-depth`, which the installed +/// owner passes every MiMo tensor-parallel launch: +/// `ClusterMiMoTensorParallel.speculativeDepth`) both ranks also hold the three +/// trained heads whole and decode in rounds +/// (`MiMoTensorParallelDecoding.runRounds`): row-exact verify windows through +/// the same sums, so every token is the one-token path's. A hand launch +/// without the depth decodes one token a step. +/// +/// The executor contract of `GLM5NextTensorParallelResidentRuntime`, one +/// lane: one request at a time, cancel from the control thread, an enclosing +/// process deadline required (a blocked collective cannot be interrupted +/// cooperatively); on any throw the owner withdraws this worker and fences its +/// peer. +/// +/// Load: the load agreement (the plan's fingerprint and arithmetic contract, +/// the serving contract below, the mode, the data plane) is bound into the +/// keyed exchange and compared before anything is read; the link is measured +/// as this mode uses it (`QwenTensorParallelLinkProbe`); every artifact file +/// is hashed against the registered manifest, and then only this rank's byte +/// runs are read (`MiMoTensorParallelVerifiedLoad`); both ranks compare what +/// they loaded before either is ready. +/// +/// Requests (`MiMoTensorParallelDecoding`): paged KV histories at this rank's +/// geometry, decode under 100-operation command buffers, one agreement sum +/// per step (the vocabulary-split argmax, or rank 0's draw from the gathered +/// row with the product's sampler, and both ranks' stop flags and +/// positions), logprobs from the split top-k gather (greedy rows) or the +/// product's own gather (sampled rows). No prompt-prefix reuse yet. +public final class MiMoTensorParallelResidentRuntime { + /// What this owner keeps of the model's serving features, as the capability declares it + /// (`MiMoResidentCapabilityMetadata.servingFeatures`): one lane and no prompt prefix (both bound below), + /// speculative rounds on the trained heads (the installed owner launches both ranks with + /// `ClusterMiMoTensorParallel.speculativeDepth`, bound by `speculativeAgreementFields`), and committed-token + /// logprobs. + static let servingFeatures = ClusterServingFeatures(promptPrefixReuse: false, ssdPrefixTier: false, + speculativeRounds: ClusterMiMoTensorParallel.speculativeDepth > 0, maximumLanes: 1, logprobs: true) + + /// Everything about serving both ranks must have been told the same, + /// beside the plan: one lane, paged KV, the chunk grid, the selection + /// rules and the decode command buffers. + public static func servingAgreementFields(chunkTokens: Int) -> [String] { + ["mimo-v26-tensor-parallel-serving-v1", "lanes=\(servingFeatures.maximumLanes)", + "kv=paged-\(MiMoTensorParallelRequestBudget.pageTokens)", "chunk=\(chunkTokens)", + "selection=split-argmax-agreement-gathered-row-rank0-draw-split-topk-logprobs-v1", + "decode-buffers=\(MiMoTensorParallelDecoding.decodeCommandBuffers.operations)", + servingFeatures.promptPrefixReuse ? "prefix=on" : "prefix=off"] + } + + /// The load agreement's fields after the admission's fingerprint; speculative + /// rounds add their terms (none without, so a plain load's agreement is unchanged). + static func loadAgreementFields(plan: MiMoTensorParallelPlan, chunkTokens: Int, + speculative: MiMoMTPTerms? = nil) -> [String] { + ["mimo-v26-tensor-parallel-load-v1", MiMoTensorParallelPlan.name, plan.fingerprint] + + MiMoTensorParallelPlan.arithmeticAgreementFields + servingAgreementFields(chunkTokens: chunkTokens) + + ClusterGenerationMode.tensorParallel.loadAgreementFields + [QwenTensorParallelLinkProbe.loadAgreementField] + + ClusterDataPlaneAgreement.loadAgreementFields + (speculative.map(speculativeAgreementFields) ?? []) + } + + /// Rounds of `terms.depth` proposals from heads replicated whole, verified in row-exact windows whose + /// partials are each row's one-token FP32 partials (contract v2: `o_proj` one FP32 product a row, the dense + /// layer row by row, the routed layer's FP32 expert rows combined row by row). + static func speculativeAgreementFields(_ terms: MiMoMTPTerms) -> [String] { + ["mimo-v26-tensor-parallel-speculative-v1"] + terms.loadAgreementFields + + ["heads=replicated-whole", "draft=split-argmax-sum", "windows=row-exact-one-token-float32-partials-v2"] + } + + let admission: MiMoResidentAdmission + let control: QwenResidentControl + let collective: Collective + let group: QwenTensorParallelGroup + let codec: QwenTensorParallelSealCodec? + let lifecycle = QwenLayerStageResidentLifecycle() + let loadAgreement: String + let plan: MiMoTensorParallelPlan + /// The artifact's whole configuration (the drafter's charge reads it). + let textConfiguration: MiMoV26Configuration + let slidingWindow: Int + /// What the live gate asks for beside every held request: the rank's + /// activation floor, freed-buffer cache and sealed frames. + let rankReserveBytes: Int + let speculative: MiMoMTPTerms? + private var draftHead: MiMoTensorParallelDraftHead? + private let operation = NSLock() + private let keepWarm = ClusterKeepWarm() + private var model: MiMoTensorParallelModel? + private var residency: ClusterStageResidency? + private let baseReady: ClusterWorkerReady + private var reservation: Reserved? + private var processLeaseOwned = true + public let linkProbe: ClusterWorkerLinkProbe? + + private struct Reserved { + let request: QwenLayerStageGenerationRequest + let deadline: UInt64 + } + + // MARK: - Load + + public static func load(_ configuration: QwenResidentLoadConfiguration, speculativeDepth: Int? = nil, + qualification: QwenResidentQualificationSwitches = .refused, + dataPlane credential: ClusterDataPlaneCredential) throws -> MiMoTensorParallelResidentRuntime { + let environment = ProcessInfo.processInfo.environment + try qualification.admit(environment: environment) + try requireTextLaunch(configuration, environment: environment) + let speculative = try speculativeDepth.map { try MiMoMTPTerms(depth: $0) } + let directory = configuration.modelDirectory + func read(_ url: URL, _ limit: Int) throws -> Data { try BoundedProbeInput.data(url, maximumBytes: limit) } + let admission = try MiMoResidentAdmission(configuration: configuration, + configBytes: read(directory.appendingPathComponent("config.json"), 1_048_576), + manifestBytes: read(directory.appendingPathComponent("manifest.json"), 4_194_304), + environment: environment, now: DispatchTime.now().uptimeNanoseconds, read: read) + guard admission.specification.supportedGenerationModes.contains(.tensorParallel) else { + throw ProbeError("Generation mode tensor_parallel_v1 is not in the MiMo row") + } + let plan = try MiMoTensorParallelPlan(configuration: admission.configBytes) + let decoded = try JSONDecoder().decode(MiMoV26Configuration.self, from: admission.configBytes) + guard let window = decoded.slidingAttention.slidingWindow else { + throw ProbeError("MiMo tensor parallel needs the sliding layers' window") + } + let profile = admission.profile + // The rank's reserve at the profile's longest request: the planner's quote beside the shard. + let budget = try requestBudget(plan: plan, slidingWindow: window, contextTokens: profile.maximumContextTokens, + chunkTokens: profile.maximumChunkTokens) + // Rounds add the drafter's state and the window's rows to that request, from the configuration alone. + let speculativeRequestBytes = try speculative.map { + try Self.speculativeRequestBytes(configuration: decoded, terms: $0, plan: plan, slidingWindow: window, + chunkTokens: profile.maximumChunkTokens) + } ?? 0 + let control = QwenResidentControl(deadline: configuration.deadlineUptimeNanoseconds, lease: configuration.lease) + try QwenResidentProcessLease.shared.acquire() + var loaded: MiMoTensorParallelModel? + var draftHead: MiMoTensorParallelDraftHead? + weak var retired: MiMoTensorParallelModel? + var residency: ClusterStageResidency? + do { + try control.check(); try QwenResidentResourceEnvironment.require() + try admission.jaccl.requireUnchanged(environment: environment, read: read) + let collective = try Collective(transport: .jaccl) + try admission.jaccl.requireUnchanged(environment: ProcessInfo.processInfo.environment, read: read) + try admission.jaccl.requireInitialized(rank: collective.rank, worldSize: collective.size, + transport: collective.transport) + let loadAgreement = sha256(try canonicalJSONData([try admission.loadAgreementFingerprint( + mode: .tensorParallel, transport: collective.transport, residency: true, measuredGate: false)] + + loadAgreementFields(plan: plan, chunkTokens: profile.maximumChunkTokens, speculative: speculative))) + try ClusterDataPlaneAgreement.establish(collective: collective, credential: credential, + loadAgreement: loadAgreement, tamper: nil, tensorParallelSeal: true, check: { try control.check() }) + guard collective.workerDataPlane?.peerVerified == true else { + throw ProbeError("MiMo tensor parallel requires an authenticated peer") + } + let group = try QwenTensorParallelGroup(collective: collective) + let codec = try QwenTensorParallelSealCodec.product(collective: collective, scope: Data(loadAgreement.utf8)) + try codec.install() + group.sealed = codec + var probe: ClusterWorkerLinkProbe? + let started = DispatchTime.now().uptimeNanoseconds + let requestReserve = budget.requestBytes + let capacity = try MLX.withError { nativeError -> Int in + func checked() throws { try nativeError.check(); try control.check(); try nativeError.check() } + try configuration.allocatorPolicy.configure(setCacheLimit: { Memory.cacheLimit = $0 }, check: checked) + let bufferCacheBytes = configuration.allocatorPolicy == .disableFreedBufferCache + ? MiMoTensorParallelRequestBudget.freedBufferCacheBytes : 0 + _ = try requireQwenLongPrefillReadinessDigest(collective: collective, + material: { .residentLoadIntent(agreementFingerprint: loadAgreement) }, + disagreementMessage: "MiMo tensor-parallel load membership/source/plan/contract differ", + scope: .session(.loadAgreement, "mimo-tensor-parallel-load-intent"), check: checked) + // The link as this mode uses it, before any weight is read. + let measured = try QwenTensorParallelLinkProbe.measure(collective: collective, group: group, + hiddenSize: plan.hiddenSize, chunkTokens: profile.maximumChunkTokens, check: checked) + probe = measured + log(QwenTensorParallelLinkProbe.line(measured, rank: collective.rank)) + // Every file of the artifact against the registered manifest, before any tensor is read. + let source = try prepareMiMoResidentSource(directory: directory, configuration: admission.configBytes, + manifest: admission.manifestBytes, specification: admission.specification, plan: admission.plan, + check: checked) + // The shard with the profile's longest request and the rank's own reserve (activation floor, + // freed-buffer cache, sealed frames) beside it: the planner's quote. The read's largest slice + // (half an expert bank) lives only while loading, inside the reserve no request holds yet. + let shardBytes = try Self.shardBytes(plan: plan, descriptors: source.descriptors) + // Speculative rounds: the three heads whole on every rank, beside the shard, and that request's + // speculative bytes. The source's descriptors hold text tensors only; the heads' inventory is the + // pipeline's, from the headers. + var headDescriptors: [String: TensorDescriptor] = [:] + var headInventory: MiMoMTPHeadInventory? + if speculative != nil { + let (inventory, indexed) = try MiMoMTPHead.inventory(source: source) + for entry in inventory.head { + guard let descriptor = indexed[entry.name] else { + throw ProbeError("MiMo speculative head descriptor disappeared") + } + headDescriptors[entry.name] = descriptor + } + headInventory = inventory + } + let headBytes = headDescriptors.values.reduce(0) { $0 + $1.byteCount } + try requireLiveMemory(bytes: try QwenLongPrefillCheckedBytes.sum([shardBytes, headBytes, + budget.allowance.reservedBytes, speculativeRequestBytes])) + let value = try autoreleasepool { + try MiMoTensorParallelVerifiedLoad.load(checkpoint: source.checkpoint, + configurationData: admission.configBytes, role: .shard(rank: collective.rank), reduction: group, + beforeRead: { _, _ in try checked() }, check: checked) + } + loaded = value.model; retired = value.model + guard value.receipt.verifiedAggregateSHA256 == admission.specification.artifactSHA256 else { + throw ProbeError("MiMo tensor-parallel shard was not read from the registered artifact") + } + if speculative != nil { + let head = try autoreleasepool { + try MiMoTensorParallelDraftHead.load(descriptors: headDescriptors, checkpoint: source.checkpoint, + configurationData: admission.configBytes, target: value.model, + beforeRead: { _, _ in try checked() }, check: checked) + } + guard head.headBytes == headBytes else { + throw ProbeError("MiMo tensor-parallel draft heads differ from the artifact's") + } + draftHead = head + } + Memory.clearCache() + residency = try ClusterStageResidency(bytes: try QwenLongPrefillCheckedBytes.sum([ + Memory.activeMemory, requestReserve, speculativeRequestBytes, bufferCacheBytes])) + try configuration.allocatorPolicy.prepareReady( + synchronize: { Stream.gpu.synchronize(); Stream.cpu.synchronize() }, + snapshot: { + let s = Memory.snapshot() + return .init(activeBytes: s.activeMemory, cachedBytes: s.cacheMemory, peakBytes: s.peakMemory) + }, clearCache: { Memory.clearCache() }, check: checked) + if bufferCacheBytes > 0 { Memory.cacheLimit = bufferCacheBytes; try checked() } + let loadedIdentity = sha256(try canonicalJSONData([loadAgreement, value.receipt.verifiedAggregateSHA256, + value.receipt.planFingerprint, String(value.receipt.shardBytes), String(value.receipt.textTensors)] + + (draftHead.map { ["draft-heads", String($0.headTensors), String($0.headBytes), + headInventory?.sha256 ?? ""] } ?? []))) + _ = try requireQwenLongPrefillReadinessDigest(collective: collective, + material: { .residentLoaded(agreementFingerprint: loadedIdentity) }, + disagreementMessage: "MiMo tensor-parallel peers did not load matching shards", + scope: .session(.loadedReady, "mimo-tensor-parallel-loaded"), check: checked) + log("darkbloom-tensor-parallel-load-v1 rank=\(collective.rank) plan=\(MiMoTensorParallelPlan.name)" + + " shares=1-1 shard_bytes=\(value.receipt.shardBytes) read_bytes=\(value.receipt.readBytes)" + + " text_bytes=\(value.receipt.textBytes) tensors=\(value.receipt.textTensors)" + + " excluded=\(value.receipt.excludedTensors) load_ns=\(DispatchTime.now().uptimeNanoseconds - started)" + + " sealed=1 buffer_cache=\(bufferCacheBytes) wired_limit=\(residency?.receipt.appliedBytes ?? 0)" + + " lanes=1 paged_kv=\(MiMoTensorParallelRequestBudget.pageTokens)" + + " mtp=\(speculative.map { "depth\($0.depth)" } ?? "off") draft_head_bytes=\(draftHead?.headBytes ?? 0)" + + " speculative_request_bytes=\(speculativeRequestBytes)") + return try QwenLongPrefillCheckedBytes.sum([requestReserve, speculativeRequestBytes]) + } + guard let model = loaded else { throw ProbeError("MiMo tensor-parallel load returned no shard") } + try control.loaded() + return try MiMoTensorParallelResidentRuntime(admission: admission, control: control, collective: collective, + group: group, codec: codec, model: model, residency: residency, plan: plan, textConfiguration: decoded, + slidingWindow: window, rankReserveBytes: budget.rankBytes, capacity: capacity, + loadAgreement: loadAgreement, linkProbe: probe, speculative: speculative, draftHead: draftHead) + } catch { + let primary = error; control.fail(); loaded = nil; draftHead = nil + do { + try MLX.withError { nativeError in + Stream.gpu.synchronize(); Stream.cpu.synchronize() + try residency?.end(); residency = nil + Memory.clearCache(); try nativeError.check() + } + guard retired == nil else { throw ProbeError("MiMo tensor-parallel failed-load model remains retained") } + } catch { + throw ProbeError("MiMo tensor-parallel load failed (\(primary)); local cleanup failed (\(error))") + } + throw primary + } + } + + /// Refused before anything is read or connected: the private image + /// candidate (rank 0's vision tower stays a pipeline candidate), more than + /// one batch lane, and any schedule but the serial one. + static func requireTextLaunch(_ configuration: QwenResidentLoadConfiguration, + environment: [String: String]) throws { + guard configuration.runtimeProfile != ClusterMiMoImageCandidate.profileID else { + throw ProbeError("MiMo tensor parallel serves text only; the image candidate is a pipeline candidate") + } + if let lanes = environment["DARKBLOOM_CLUSTER_BATCH_LANES"], lanes != "1" { + throw ProbeError("MiMo tensor parallel serves one lane") + } + guard configuration.prefillSchedule == .serial else { + throw ProbeError("MiMo tensor parallel prefills on the serial schedule") + } + } + + /// Bytes one rank holds of the text model: its half of every divided + /// tensor, all of every replicated one; excluded components none. + static func shardBytes(plan: MiMoTensorParallelPlan, descriptors: [String: TensorDescriptor]) throws -> Int { + try descriptors.reduce(0) { total, entry in + switch try plan.disposition(of: entry.key) { + case .excluded: return total + case .replicated: return try QwenLongPrefillCheckedBytes.sum([total, entry.value.byteCount]) + case .divided: return try QwenLongPrefillCheckedBytes.sum([total, entry.value.byteCount / plan.size]) + } + } + } + + /// This rank's reserve for requests of `contextTokens` (`MiMoTensorParallelRequestBudget`) + /// at the allocator's own bound. + static func requestBudget(plan: MiMoTensorParallelPlan, slidingWindow: Int, contextTokens: Int, + chunkTokens: Int) throws -> MiMoTensorParallelRequestBudget { + try MiMoTensorParallelRequestBudget.derive(plan: plan, slidingWindow: slidingWindow, contextTokens: contextTokens, + chunkTokens: chunkTokens, allocationBound: QwenResidentResourceEnvironment.allocationBound) + } + + /// One request's speculative charge: the drafter's own bounded state (the + /// product's declaration at the allocator's bound) and the window's extra + /// rows (`MiMoTensorParallelRequestBudget.speculativeWindowBytes`). + static func speculativeRequestBytes(configuration: MiMoV26Configuration, terms: MiMoMTPTerms, + plan: MiMoTensorParallelPlan, slidingWindow: Int, chunkTokens: Int, + bound: (Int) throws -> Int = QwenResidentResourceEnvironment.allocationBound) + throws -> Int { + try QwenLongPrefillCheckedBytes.sum([ + MiMoTensorParallelDraftHead.requestBytes(configuration: configuration, chunkSize: chunkTokens, + depth: terms.depth, bound: bound), + MiMoTensorParallelRequestBudget.speculativeWindowBytes(plan: plan, slidingWindow: slidingWindow, + depth: terms.depth, allocationBound: bound)]) + } + + /// The rounds as the planner prices a rank (`ClusterTensorParallelSpeculativeHead`), from the configuration + /// alone: the installed depth (`ClusterMiMoTensorParallel.speculativeDepth`), each request's speculative charge + /// at the profile's chunk (what the LOAD gate adds beside `budget`, so the quoted allowance carries it too), and + /// a decode speed-up of 1. No record has measured MiMo tensor parallel's rounds against its one-token steps, so + /// the plan credits none: served records correct the shard rates instead (`ClusterServedCalibration`), and the + /// evidence rule decides. Nil when the installed depth is 0. + static func placementRounds(configuration data: Data, plan: MiMoTensorParallelPlan, chunkTokens: Int, + budget: MiMoTensorParallelRequestBudget, allocationBound: (Int) throws -> Int) throws + -> (head: ClusterTensorParallelSpeculativeHead, allowance: ClusterTensorParallelRequestAllowance)? { + let depth = ClusterMiMoTensorParallel.speculativeDepth + guard depth > 0 else { return nil } + let configuration = try JSONDecoder().decode(MiMoV26Configuration.self, from: data) + guard let window = configuration.slidingAttention.slidingWindow else { + throw ProbeError("MiMo tensor parallel needs the sliding layers' window") + } + let bytes = try speculativeRequestBytes(configuration: configuration, terms: MiMoMTPTerms(depth: depth), plan: plan, + slidingWindow: window, chunkTokens: chunkTokens, bound: allocationBound) + return (.init(depth: depth, requestBytes: bytes, decodeSpeedup: 1), + try budget.allowance(speculativeRequestBytes: bytes, allocationBound: allocationBound)) + } + + /// The host memory gate's decision for `bytes` more, as the resident families take it. + static func requireLiveMemory(bytes: Int) throws { + try QwenResidentResourceEnvironment.require() + let watch = QwenDenseStageLoadWatch("MiMo tensor-parallel") + let os = try QwenDenseStageLoadResources.observeOS() + let free = max(QwenDenseStageLoadPolicy.minimumAdmissibleBytes, + try QwenLongPrefillCheckedBytes.sum([bytes, QwenDenseStageLoadPolicy.loadingHeadroomBytes])) + guard try watch.admits(os, bytes: free) else { + throw ProbeError("MiMo tensor parallel needs \(bytes) bytes the memory gate does not admit now") + } + } + + private init(admission: MiMoResidentAdmission, control: QwenResidentControl, collective: Collective, + group: QwenTensorParallelGroup, codec: QwenTensorParallelSealCodec?, model: MiMoTensorParallelModel, + residency: ClusterStageResidency?, plan: MiMoTensorParallelPlan, textConfiguration: MiMoV26Configuration, + slidingWindow: Int, rankReserveBytes: Int, capacity: Int, loadAgreement: String, + linkProbe: ClusterWorkerLinkProbe?, speculative: MiMoMTPTerms?, + draftHead: MiMoTensorParallelDraftHead?) throws { + self.admission = admission; self.control = control; self.collective = collective; self.group = group + self.codec = codec; self.model = model; self.residency = residency + self.speculative = speculative; self.draftHead = draftHead + self.plan = plan; self.textConfiguration = textConfiguration + self.slidingWindow = slidingWindow; self.rankReserveBytes = rankReserveBytes + self.loadAgreement = loadAgreement; self.linkProbe = linkProbe + baseReady = .init(identity: admission.configuration.identity, rank: collective.rank, + profile: admission.wireProfile, executionPlanSHA256: admission.plan.fingerprint, + requestCapacityBytes: capacity, dataPlane: collective.workerDataPlane, linkProbe: linkProbe) + } + + // MARK: - Owner interface + + public var readiness: ClusterWorkerReady? { + guard control.available, (try? control.check()) != nil else { return nil } + return baseReady + } + + /// Every request's tokens carry their logprobs when it asks for them. + public var capturesLogprobs: Bool { true } + + public func keepWarmPulse() throws -> UInt64 { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard control.available else { throw ProbeError("Keep-warm needs an idle resident owner") } + return keepWarm.pulse() + } + + public func dataPlanePing() throws -> UInt64 { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard control.available else { throw ProbeError("A data-plane ping needs an idle resident owner") } + return try ClusterKeepWarm.dataPlanePing(collective: collective, check: { try control.check() }) + } + + /// Text only: no route, media or images. Charged at the request's own + /// context (`MiMoTensorParallelRequestBudget.requestBytes`); the live gate + /// is asked for it and the rank's own reserve once. + public func reserve(requestID: UUID, request value: ClusterWorkerReservation) throws -> Int { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard value.route == nil, value.stillImages == nil, value.mimoImages == nil, value.glmMedia == nil, + value.qwenMedia == nil else { + throw ProbeError("MiMo tensor parallel serves text requests only") + } + let request = try admission.request(value, id: requestID, now: DispatchTime.now().uptimeNanoseconds) + var charge = try Self.requestBudget(plan: plan, slidingWindow: slidingWindow, contextTokens: request.maximumTokens, + chunkTokens: request.chunkSize).requestBytes + if let speculative { + charge = try QwenLongPrefillCheckedBytes.sum([charge, Self.speculativeRequestBytes( + configuration: textConfiguration, terms: speculative, plan: plan, slidingWindow: slidingWindow, + chunkTokens: request.chunkSize)]) + } + try control.check(); try control.reserve(requestID) + return try control.reserving(requestID, rank: collective.rank, deadline: value.deadlineUptimeNanoseconds) { + guard model != nil else { throw ProbeError("Resident model already released") } + guard charge <= value.capacityLimitBytes, charge <= baseReady.requestCapacityBytes else { + throw ProbeError("MiMo tensor-parallel reservation exceeds its owner or readiness capacity") + } + try Self.requireLiveMemory(bytes: try QwenLongPrefillCheckedBytes.sum([charge, rankReserveBytes])) + try control.check(deadline: value.deadlineUptimeNanoseconds) + reservation = .init(request: request, deadline: value.deadlineUptimeNanoseconds) + return charge + } + } + + public func releaseReservation(requestID: UUID) throws { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard let reserved = reservation, reserved.request.requestID == requestID, control.withdraw(requestID) else { + throw ProbeError("Resident release has no matching unstarted reservation") + } + reservation = nil + } + + /// Only rank 0 invokes the callback, once both ranks hold the token. + public func start(requestID: UUID, + onCommittedToken: (Int, Int, Int) throws -> Bool) throws -> QwenResidentGenerationCompletion { + try ClusterCommittedTokenChannel.answering(onCommittedToken) { try start(requestID: requestID, tokens: $0) } + } + + public func start(requestID: UUID, tokens channel: ClusterCommittedTokenChannel) throws + -> QwenResidentGenerationCompletion { + guard operation.try() else { throw ProbeError("Resident native operation is already active") } + defer { operation.unlock() } + guard let reserved = reservation, reserved.request.requestID == requestID else { + throw ProbeError("Resident start has no matching reservation") + } + do { + let value = try QwenResidentRequestPublication.run(control: control, lifecycle: lifecycle, + identity: .init(requestID: requestID, epoch: requestID, recordedRequestFingerprint: reserved.request.fingerprint), + deadline: reserved.deadline, body: { + try autoreleasepool { try generate(reserved, channel: channel) } + }, prepare: { $0 }) + collective.logDataPlaneStatus() + reservation = nil + return value + } catch { + control.fail(); throw error + } + } + + public func cancel(requestID: UUID) { control.cancel(requestID) } + + public func shutdown() throws { + guard operation.try() else { throw ProbeError("Cannot release a running native request") } + defer { operation.unlock() } + try control.beginClose() + collective.logDataPlaneStatus() + do { + try lifecycle.withModelRelease { + try MLX.withError { error in + Stream.gpu.synchronize(); Stream.cpu.synchronize(); try error.check() + weak var released: MiMoTensorParallelModel? + released = model + reservation = nil; draftHead = nil; model = nil + guard released == nil else { throw ProbeError("MiMo tensor-parallel model remains retained") } + try residency?.end(); residency = nil + Memory.clearCache(); try error.check() + } + } + control.closed() + processLeaseOwned = false; QwenResidentProcessLease.shared.release() + } catch { control.fail(); throw error } + } + + deinit { if processLeaseOwned { control.fail() } } + + // MARK: - One request + + private func generate(_ reserved: Reserved, channel: ClusterCommittedTokenChannel) throws + -> QwenResidentGenerationCompletion { + guard let model else { throw ProbeError("Resident model already released") } + let request = reserved.request, rank = collective.rank + let decoding = MiMoTensorParallelDecoding(model: model) + guard try decoding.requestAgreed(QwenTensorParallelResidentRuntime.digest64(request.fingerprint + "|" + loadAgreement)) else { + throw ProbeError("MiMo tensor-parallel ranks were given different requests") + } + var lastCheck: UInt64 = 0 + func localStop() -> Bool { + if (try? control.check(deadline: reserved.deadline)) == nil { return true } + let now = DispatchTime.now().uptimeNanoseconds + if now - lastCheck >= 250_000_000 { + lastCheck = now + if (try? Self.requireLiveMemory(bytes: 0)) == nil { return true } + } + return false + } + let sampler = request.sampler + let rule = MiMoTensorParallelSelectionRule.rule(request.sampling?.wire) + let speculation = try speculative.map { terms -> MiMoTensorParallelSpeculation in + guard let draftHead else { throw ProbeError("MiMo tensor-parallel draft heads were released") } + return try .init(depth: terms.depth, proposer: .heads(draftHead)) + } + let outcome = try decoding.run(.init(prompt: request.promptTokenIDs, outputCount: request.outputCount, + chunk: request.chunkSize, stopTokenIDs: request.stopTokenIDs, rule: rule, sampler: sampler, + speculation: speculation), + localStop: localStop, publish: { ordinal, token, logprobs in + try channel.publishToken(ordinal, token, request.promptCount + ordinal, logprobs) + return try channel.answer() + }) + try control.check(deadline: reserved.deadline) + let finish: ClusterWorkerFinishReason + switch outcome.finish { + case .eos: finish = .eos + case .length: finish = .length + case .clientStop: finish = .clientStop + } + if finish == .clientStop, !outcome.ownerStopped, rank == 0 { + throw ProbeError("The peer rank stopped the MiMo tensor-parallel request") + } + log("darkbloom-tensor-parallel-request-v1 rank=\(rank) request=\(request.requestID.uuidString.lowercased())" + + " family=mimo prompt=\(request.promptCount) output=\(outcome.tokens.count) finish=\(finish.rawValue)" + + " rule=\(rule.label) frames=\(codec?.sealedFrames ?? 0) key_generation=\(codec?.keyGeneration ?? 0)" + + " kv_pages=\(outcome.caches.reduce(0) { $0 + $1.pageCount })" + + (outcome.statistics.map { " " + $0.diagnosticFields.prefix(8).joined(separator: " ") } ?? "") + + String(format: " first_token_ms=%.1f decode_ms=%.1f", outcome.firstTokenSeconds * 1000, outcome.decodeSeconds * 1000)) + return QwenResidentGenerationCompletion(requestID: request.requestID, finishReason: finish, + selectedTokenIDs: outcome.tokens, completedFrames: outcome.tokens.count, + committedTokens: request.promptCount + outcome.tokens.count, + tokenChainSHA256: sha256(try canonicalJSONData(outcome.tokens.map { String($0) })), + bothRequestStatesRetired: true) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRounds.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRounds.swift new file mode 100644 index 0000000000..9862d04b9e --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelRounds.swift @@ -0,0 +1,262 @@ +import Cmlx +import DarkbloomClusterProtocol +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +/// Speculative rounds of one request on a MiMo V2.6 tensor-parallel rank +/// (`pipeline_mtp_v1`'s rules through the tensor-parallel sums). +/// +/// After the prompt and the first token (a plain step's agreement), each +/// round drafts up to `depth` proposals from the replicated heads (each one +/// small sum), runs the window `[last, d1 … dk]` through every layer's two +/// sums at once (`MiMoV26TextModel.forwardVerifyWindow`: each row is the +/// one-token step's bits, so greedy is lossless against the one-token path), +/// and agrees in one sum on every column's target (the vocabulary-split +/// argmax, or rank 0's keyed target sample over the gathered rows), both +/// ranks' stop slots and positions. Both ranks then keep the same tokens +/// (`MiMoMTPAcceptance.kept`: drafts while each equals the target before it, +/// then the target; cut at a stop token and the output limit), roll the rest +/// of the window back exactly, and commit. A round of no proposal is the +/// one-token step itself; a sampler that cannot verify drafts never gets here +/// (`run` decodes it one token a step). +/// +/// Stops: a round's stop slots are read before either rank commits any of its +/// tokens. Rank 0 hears the owner's answer to each token at once; a client +/// stop inside a round stops rank 0's commits there and rides the next +/// round's agreement, unless the round already ends the request (a stop token +/// or the limit, which both ranks see in the agreed tokens): both ranks then +/// end after it, and rank 1 adopts rank 0's count and finish in the end +/// agreement (`QwenTensorParallelStopRule.reconcile`), so no rank waits in a +/// collective its peer never joins. +extension MiMoTensorParallelDecoding { + struct Round { + let targets: [Int] + let maxima: [Float] + let stop: Float? + /// The gathered rows `[n, V]` (FP32) of a gathered-row request. + let rows: MLXArray? + } + + func runRounds(_ request: Request, speculation: MiMoTensorParallelSpeculation, localStop: () -> Bool, + publish: (Int, Int, ClusterWorkerTokenLogprobs?) throws -> Bool, + observe: ((Step) throws -> Void)?) throws -> (outcome: Outcome, statistics: MiMoMTPStatistics) { + let prompt = request.prompt + let started = MiMoTensorParallelModel.now() + let caches = try model.model.makeIndependentHistoryCaches() + var outcome = Outcome(caches: caches) + let drafter = try MiMoTensorParallelDrafter(speculation, vocabularySize: model.plan.vocabularySize, + maximumTokens: prompt.count + request.outputCount) + defer { drafter.release() } + let firstLogits = try prefill(prompt, chunk: request.chunk, caches: caches, drafter: drafter) + var previousOperations: Int32 = 0, previousMegabytes: Int32 = 0 + mlx_metal_set_thread_command_buffer_limits(Int32(Self.decodeCommandBuffers.operations), + Int32(Self.decodeCommandBuffers.megabytes), &previousOperations, &previousMegabytes) + defer { mlx_metal_set_thread_command_buffer_limits(previousOperations, previousMegabytes, nil, nil) } + + var stopKeep: Float = 0 + var agreed = 0 + var last = 0 + /// Commits agreed tokens (rank 0 publishes each and hears its answer); true when they end the request. + func commit(_ tokens: [Int], logprobs: [ClusterWorkerTokenLogprobs?]) throws -> Bool { + for (index, token) in tokens.enumerated() where stopKeep == 0 { + outcome.tokens.append(token) + var wanted = true + if rank == 0 { wanted = try publish(outcome.tokens.count - 1, token, logprobs[index]) } + switch QwenTensorParallelStopRule.outcome(isStopToken: request.stopTokenIDs.contains(token), + committed: outcome.tokens.count, + outputCount: request.outputCount, wanted: wanted) { + case .eos: outcome.finish = .eos + case .length: outcome.finish = .length + case .clientStop: + outcome.finish = .clientStop + outcome.ownerStopped = true + stopKeep = Float(outcome.tokens.count) + case .proceed: break + } + } + agreed += tokens.count + last = tokens[tokens.count - 1] + return request.stopTokenIDs.contains(last) || agreed >= request.outputCount + } + + // The first token: the one-token step's agreement (no stop can be set yet). + let first = try select(firstLogits, request: request, stop: 0, position: caches[0].offset) + routes?.flush() + outcome.firstTokenSeconds = MiMoTensorParallelModel.now() - started + try observe?(first.step(0)) + request.sampler?.commit(first.token) + var ended = try commit([first.token], logprobs: [first.logprobs]) + if !ended { + try drafter.begin(firstToken: first.token) + if stopKeep == 0, localStop() { stopKeep = Float(outcome.tokens.count); outcome.stoppedHere = true } + } + while !ended { + let remaining = request.outputCount - agreed + let count = min(drafter.depth, remaining - 1) + let drafts = count >= 1 ? try drafter.draft(lastToken: last, nextIndex: agreed, count: count) : [] + if drafts.isEmpty { + // A plain step: the one-token path's forward and selection. + let logits = try forward([last], caches: caches) + let choice = try select(logits, request: request, stop: stopKeep, position: caches[0].offset) + routes?.flush() + if let slot = choice.stop { endAtStop(slot, &outcome); break } + try drafter.plainStep() + try observe?(choice.step(agreed)) + request.sampler?.commit(choice.token) + ended = try commit([choice.token], logprobs: [choice.logprobs]) + } else { + let window = try model.model.forwardVerifyWindow( + inputIDs: MLXArray(([last] + drafts).map(Int32.init)).reshaped(1, drafts.count + 1), caches: caches) + let round = try selectRound(window.logits, request: request, stop: stopKeep, + position: caches[0].offset) + if let slot = round.stop { endAtStop(slot, &outcome); break } + let kept = try MiMoMTPAcceptance.kept(drafts: drafts, targets: round.targets, remaining: remaining, + stopTokens: request.stopTokenIDs) + try MLX.withError { error in + try window.settle(keeping: kept.tokens.count) + eval(caches.flatMap { $0.innerState() }) + try error.check() + } + try drafter.finalize(drafts: drafts, tokens: kept.tokens, acceptedDrafts: kept.acceptedDrafts, + hidden: window.normalizedHiddenStates) + let logprobs = try roundLogprobs(round, logits: window.logits, kept: kept.tokens, request: request) + if let observe { + for (index, token) in kept.tokens.enumerated() { + try observe(.init(index: agreed + index, token: token, logits: window.logits[0..., index, 0...], + row: round.rows.map { $0[index ..< (index + 1)] }, top: nil, sampledLogprobs: nil)) + } + } + request.sampler?.commitRound(kept.tokens) + ended = try commit(kept.tokens, logprobs: logprobs) + } + if !ended, stopKeep == 0, localStop() { stopKeep = Float(outcome.tokens.count); outcome.stoppedHere = true } + } + try agreeRoundsEnd(&outcome) + outcome.decodeSeconds = MiMoTensorParallelModel.now() - started - outcome.firstTokenSeconds + return (outcome, drafter.statistics) + } + + /// One round's agreement over a window's logits `[1, n, V or V/2]`: per + /// rank `[maxima (n), tokens (n), stop, position]`, evaluated. Greedy rows + /// put each column's FP32 maximum and its global ID (the strictly greater + /// maximum wins, ties to the lower rank: each column's whole-row argmax); + /// gathered rows put rank 0's keyed target sample at each column + /// (`QwenStageTokenSampler.verifyRound`) and rank 1 an ignored argmax. + func selectRound(_ logits: MLXArray, request: Request, stop: Float, position: Int) throws -> Round { + let columns = logits.dim(1) + let values = logits[0].asType(.float32) + let selection = model.selection + var rows: MLXArray? + let mine: MLXArray + switch request.rule { + case .greedy, .greedyLogprobs: + let ids = argMax(values, axis: -1).asType(.float32) + MLXArray(Float(selection.vocabularyRange.lowerBound)) + mine = concatenated([values.max(axis: -1), ids, MLXArray([stop, Float(position)])], axis: 0) + case .gatheredRow: + let whole = selection.gather(values) + rows = whole + let drawn = rank == 0 + ? request.sampler!.verifyRound(whole.reshaped(1, columns, -1)).reshaped(-1) + : argMax(whole, axis: -1) + mine = concatenated([MLXArray.zeros([columns], dtype: .float32), drawn.asType(.float32), + MLXArray([stop, Float(position)])], axis: 0) + } + let width = 2 * columns + 2 + let ranks = reduction?.size ?? 1 + let all: MLXArray + if let reduction { + let empty = MLXArray.zeros([width], dtype: .float32) + all = reduction.allSum(concatenated((0 ..< ranks).map { $0 == reduction.rank ? mine : empty }, axis: 0)) + } else { + all = mine + } + try MLX.withError { error in + eval([all] + (rows.map { [$0] } ?? [])) + try error.check() + } + let agreed = all.asArray(Float.self) + guard agreed.count == width * ranks else { throw ProbeError("MiMo tensor parallel round agreement has a wrong shape") } + func slot(_ rank: Int, _ field: Int) -> Float { agreed[width * rank + field] } + guard (0 ..< ranks).allSatisfy({ slot($0, width - 1) == Float(position) }) else { + throw ProbeError("MiMo tensor-parallel ranks are at different positions") + } + var targets: [Int] = [], maxima: [Float] = [] + for column in 0 ..< columns { + var best = slot(0, column), token = Int(slot(0, columns + column)) + if request.rule != .gatheredRow { + for other in 1 ..< ranks where slot(other, column) > best { + best = slot(other, column); token = Int(slot(other, columns + column)) + } + } + guard (0 ..< model.plan.vocabularySize).contains(token) else { + throw ProbeError("MiMo tensor parallel round chose no token of the vocabulary") + } + targets.append(token); maxima.append(best) + } + let stops = (0 ..< ranks).map { slot($0, width - 2) }.filter { $0 > 0 } + return Round(targets: targets, maxima: maxima, stop: stops.min(), rows: rows) + } + + /// The kept columns' logprobs, when the request asks for them: one + /// vocabulary-split top-k gather per kept column (both ranks know how many + /// were kept), led by the column's agreed maximum even when an exactly tied + /// token leads the gather; or the product sampler's own over the gathered rows. + func roundLogprobs(_ round: Round, logits: MLXArray, kept: [Int], request: Request) throws + -> [ClusterWorkerTokenLogprobs?] { + switch request.rule { + case .greedy: + return Array(repeating: nil, count: kept.count) + case .greedyLogprobs(let count): + return try kept.indices.map { column in + let gathered = try model.selection.topK(logits[0..., column, 0...], count: count) + guard let first = gathered.logprobs.first, gathered.logits.first == round.maxima[column] else { + throw ProbeError("MiMo tensor parallel logprobs do not lead with the greedy token's logit") + } + return .init(logprob: first, top: zip(gathered.tokenIDs, gathered.logprobs).map { + .init(tokenID: $0, logprob: $1) + }) + } + case .gatheredRow: + guard rank == 0, let sampler = request.sampler, sampler.wire.capturedLogprobs != nil else { + return Array(repeating: nil, count: kept.count) + } + let gathered = sampler.takeRoundLogprobs(tokens: kept) + guard gathered.count == kept.count else { throw ProbeError("MiMo tensor parallel round has no logprobs") } + return gathered + } + } + + /// Every rank's count, finish and own-stop flag in one sum. Rank 1 adopts + /// rank 0's count and finish when rank 0 stopped for its owner inside the + /// last round (`QwenTensorParallelStopRule.reconcile`); any other difference + /// means the ranks diverged. + func agreeRoundsEnd(_ outcome: inout Outcome) throws { + guard let reduction else { return } + var slots = [Float](repeating: 0, count: 3 * reduction.size) + slots[3 * reduction.rank] = Float(outcome.tokens.count) + slots[3 * reduction.rank + 1] = Float(outcome.finish.code) + slots[3 * reduction.rank + 2] = outcome.stoppedHere ? 1 : 0 + let summed = reduction.allSum(MLXArray(slots)) + try MLX.withError { error in eval(summed); try error.check() } + let values = summed.asArray(Float.self) + guard let rank0Finish = QwenTensorParallelStopRule.Finish(code: Int32(values[1])) else { + throw ProbeError("MiMo tensor-parallel rank 0 ended with no finish") + } + let rank0Count = Int(values[0]) + for other in 0 ..< reduction.size { + guard let finish = QwenTensorParallelStopRule.Finish(code: Int32(values[3 * other + 1])) else { + throw ProbeError("MiMo tensor-parallel rank ended with no finish") + } + let reconciled = QwenTensorParallelStopRule.reconcile(rank: other, localFinish: finish, + localCount: Int(values[3 * other]), localStopped: values[3 * other + 2] > 0, + rank0Finish: rank0Finish, rank0Count: rank0Count) + guard reconciled.finish == rank0Finish, reconciled.count == rank0Count else { + throw ProbeError("MiMo tensor-parallel ranks ended the request differently") + } + } + outcome.tokens = Array(outcome.tokens.prefix(rank0Count)) + outcome.finish = rank0Finish + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift new file mode 100644 index 0000000000..fe0c272dc2 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSpeculation.swift @@ -0,0 +1,319 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +/// The three trained next-N heads on a tensor-parallel rank, replicated whole +/// on both ranks (the product's `MiMoV26MTP` and `MiMoV26MTPAssistant`, +/// unchanged): every rank runs the same drafter on the same agreed rows, so +/// its arithmetic is the single-Mac drafter's. Their target is a one-layer +/// shell that holds the rank's own embedding (replicated) and vocabulary rows +/// (shared modules, no copy) and the rank's reduction, so each proposal is the +/// whole vocabulary's argmax from one small sum (`readoutArgMax`). +final class MiMoTensorParallelDraftHead { + static let prefix = MiMoTensorParallelPlan.textNamespace + "model.mtp." + + let assistant: MiMoV26MTPAssistant + let headTensors: Int + let headBytes: Int + private let shell: MiMoV26TextModel + private let predictor: MiMoV26MTP + + /// The heads' indexed tensors of a verified checkpoint, by name; no payload. + static func descriptors(checkpoint: VerifiedCheckpoint) throws -> [String: TensorDescriptor] { + try tensorDescriptors(checkpoint: checkpoint, scope: .init(acceptsUInt8: true, indexedShardsOnly: true)) + .filter { $0.key.hasPrefix(prefix) } + } + + /// The heads' tensors (`descriptors`, every one under `prefix`) read whole + /// through a verified checkpoint (every file already matched its manifest); + /// `beforeRead` gates each read. + static func load(descriptors: [String: TensorDescriptor], checkpoint: VerifiedCheckpoint, configurationData: Data, + target: MiMoTensorParallelModel, beforeRead: (String, Int) throws -> Void = { _, _ in }, + check: () throws -> Void = {}) throws -> MiMoTensorParallelDraftHead { + guard !descriptors.isEmpty, descriptors.keys.allSatisfy({ $0.hasPrefix(prefix) }) else { + throw ProbeError("MiMo speculative heads are not the artifact's next-N tensors") + } + var weights: [String: MLXArray] = [:] + for name in descriptors.keys.sorted() { + let descriptor = descriptors[name]! + guard descriptor.dtype == .bfloat16 else { + throw ProbeError("MiMo speculative head tensor \(name) is not bfloat16") + } + try autoreleasepool { + try beforeRead(name, descriptor.byteCount) + let read = try descriptor.read(.all) + guard read.copiedBytes == descriptor.byteCount, read.array.shape == descriptor.shape else { + throw ProbeError("MiMo speculative head read of \(name) is incomplete") + } + eval(read.array) + weights[String(name.dropFirst(prefix.count))] = read.array + try check() + } + } + try checkpoint.checkUnchanged() + return try MiMoTensorParallelDraftHead(configurationData: configurationData, target: target, weights: weights) + } + + /// Tools and oracles: a checkpoint directory with its own `manifest.json`, hashed first. + static func load(modelDirectory: URL, target: MiMoTensorParallelModel) throws -> MiMoTensorParallelDraftHead { + let configurationData = try Data(contentsOf: modelDirectory.appendingPathComponent("config.json")) + let checkpoint = try VerifiedCheckpoint(directory: modelDirectory, configurationData: configurationData, + hashingConcurrency: MiMoRegisteredSpecification.hashingConcurrency) + return try load(descriptors: descriptors(checkpoint: checkpoint), checkpoint: checkpoint, + configurationData: configurationData, target: target) + } + + init(configurationData: Data, target: MiMoTensorParallelModel, weights: [String: MLXArray]) throws { + guard var root = try JSONSerialization.jsonObject(with: configurationData) as? [String: Any], + BoundedProbeInput.integer(root["num_nextn_predict_layers"]) == MiMoMTPTerms.maximumDepth else { + throw ProbeError("MiMo tensor-parallel speculation needs the artifact's three trained next-N heads") + } + // The heads' target: the whole configuration with one layer that is never evaluated. + root["num_hidden_layers"] = 1 + root["hybrid_layer_pattern"] = [0] + root["moe_layer_freq"] = [0] + for key in ["vision_config", "audio_config", "processor_config", "omlx_mimo_mtp"] { root[key] = nil } + let configuration = try JSONDecoder().decode(MiMoV26Configuration.self, + from: try JSONSerialization.data(withJSONObject: root)) + let shell = try withRandomState(MLXRandom.RandomState(seed: 7)) { try MiMoV26TextModel(configuration) } + if let reduction = target.reduction { + try shell.installTensorParallel(reduce: { reduction.allSum($0) }, vocabularyRows: target.vocabularyRange) + } + let modules = Dictionary(uniqueKeysWithValues: target.model.namedModules()) + guard let embedding = modules["model.embed_tokens"], let head = modules["lm_head"] else { + throw ProbeError("MiMo tensor-parallel rank has no embedding or head to lend its draft heads") + } + try shell.update(modules: ModuleChildren.unflattened([("model.embed_tokens", embedding), ("lm_head", head)]), + verify: [.noUnusedKeys]) + let shellModules = Dictionary(uniqueKeysWithValues: shell.namedModules()) + guard shellModules["model.embed_tokens"] === embedding, shellModules["lm_head"] === head, + shell.headVocabularyRange == target.vocabularyRange else { + throw ProbeError("MiMo draft heads' target does not hold this rank's embedding and vocabulary rows") + } + let predictor = try MiMoV26MTP(target: shell, floatingProjections: true) + try predictor.loadConvertedWeights(weights, prefix: "") + predictor.freeze() + let parameters = predictor.parameters().flattened().map(\.1) + eval(parameters) + self.shell = shell; self.predictor = predictor + headTensors = parameters.count + headBytes = parameters.reduce(0) { $0 + $1.nbytes } + assistant = try MiMoV26MTPAssistant(target: shell, predictor: predictor, retaining: nil, + verificationMode: .rectangular, historyStorage: .contiguous) + } + + /// One request's drafter state at the allocator's bound: the product's own + /// bounded declaration for these heads (`maximumPrefillTokens` = the chunk). + /// It needs the artifact's configuration only, so a rank gates it before + /// reading anything. + static func requestBytes(configuration: MiMoV26Configuration, chunkSize: Int, depth: Int, + bound: (Int) throws -> Int) throws -> Int { + guard let spec = MiMoV26MTPAssistant.boundedRequestAllocation(configuration: configuration, + limits: .init(maximumPrefillTokens: chunkSize, maximumDraftTokens: depth)) else { + throw ProbeError("MiMo speculative head declares no bounded request allocation") + } + var total = spec.hostBytes + for buffer in spec.resident + spec.working { + total = try QwenLongPrefillCheckedBytes.sum([total, + try QwenLongPrefillCheckedBytes.product([try bound(buffer.logicalBytes), buffer.allocationCount])]) + } + return total + } +} + +/// Where a round's proposals come from. Both ranks derive them from agreed +/// state only, so they issue the same collectives. +enum MiMoTensorParallelProposer { + /// The trained heads (`MiMoTensorParallelDrafter`). + case heads(MiMoTensorParallelDraftHead) + /// Oracles only: proposal j of a round whose first new output index is i + /// is `script[i + j]` (`MiMoTensorParallelSpeculation.scripted`), except + /// every `missEvery`-th proposal, which is moved to the next token ID so the + /// target rejects it. With the one-token path's own tokens as the script, + /// the rounds accept several tokens, reject, and roll back. + case scripted(script: [Int], missEvery: Int) +} + +/// A request's speculative rounds: `depth` proposals a round at most. +struct MiMoTensorParallelSpeculation { + let depth: Int + let proposer: MiMoTensorParallelProposer + + init(depth: Int, proposer: MiMoTensorParallelProposer) throws { + guard (1 ... MiMoMTPTerms.maximumDepth).contains(depth) else { + throw ProbeError("MiMo tensor-parallel speculation drafts 1...\(MiMoMTPTerms.maximumDepth) tokens a round") + } + if case .scripted(let script, let missEvery) = proposer, script.isEmpty || missEvery < 0 { + throw ProbeError("MiMo tensor-parallel scripted proposals need a script") + } + self.depth = depth; self.proposer = proposer + } +} + +/// One request's proposals on a rank: `MiMoMTPDecoder`'s rules (the product +/// drafter's history, priming and finalization) on the replicated heads, or a +/// scripted oracle. Proposals are evaluated before they return; with the heads +/// each is one small sum issued in the same order on every rank. +final class MiMoTensorParallelDrafter { + private let speculation: MiMoTensorParallelSpeculation + private let vocabularySize: Int + private var state: (any CBv2MTPRequestState)? + private var promptFrontier: MLXArray? + private var carry: (token: Int, hidden: MLXArray)? + private var fencePending = false + private var released = false + private(set) var statistics: MiMoMTPStatistics + + var depth: Int { speculation.depth } + + init(_ speculation: MiMoTensorParallelSpeculation, vocabularySize: Int, maximumTokens: Int) throws { + self.speculation = speculation; self.vocabularySize = vocabularySize + statistics = .init(depth: speculation.depth) + if case .heads(let head) = speculation.proposer { + guard head.assistant.maximumDraftTokens.map({ speculation.depth <= $0 }) ?? false, + head.assistant.maximumSpeculativeBatch == 1 else { + throw ProbeError("MiMo speculative head cannot draft the agreed depth") + } + let state = head.assistant.makeRequestState() + try head.assistant.configureRequestState(state, maximumSequenceLength: maximumTokens) + self.state = state + } + } + + private func fence() throws { + guard fencePending, case .heads(let head) = speculation.proposer, let state else { return } + try MLX.withError { error in + eval(head.assistant.evaluationTargets(for: state)) + try error.check() + } + fencePending = false + } + + /// One prompt chunk's tokens and post-final-norm rows `[1, n, H]`. + func observePrompt(tokens: [Int], hidden: MLXArray) throws { + guard !released, carry == nil, !tokens.isEmpty, hidden.dim(1) == tokens.count else { + throw ProbeError("MiMo tensor-parallel drafter observed a row outside its prompt") + } + guard case .heads(let head) = speculation.proposer, let state else { return } + try fence() + head.assistant.observeCommittedTarget(.init(tokens: MLXArray(tokens.map(Int32.init)).reshaped([1, tokens.count]), + hidden: hidden), requestState: state) + let last = tokens.count - 1 + promptFrontier = hidden[0..., last ..< (last + 1), 0...] + asyncEval(head.assistant.evaluationTargets(for: state) + [promptFrontier!]) + fencePending = true + } + + /// After the prompt and the first agreed token. + func begin(firstToken: Int) throws { + guard !released, carry == nil else { throw ProbeError("MiMo tensor-parallel drafter began twice") } + if case .heads = speculation.proposer { + guard let promptFrontier else { throw ProbeError("MiMo tensor-parallel drafter starts without a prompt") } + try fence() + carry = (firstToken, promptFrontier) + self.promptFrontier = nil + } + } + + /// Up to `count` proposals after `lastToken`, whose output index is + /// `nextIndex - 1`; none when the drafter has no carry (it stopped drafting). + func draft(lastToken: Int, nextIndex: Int, count: Int) throws -> [Int] { + guard !released, count >= 1 else { throw ProbeError("MiMo tensor-parallel drafter stepped past its request") } + switch speculation.proposer { + case .scripted(let script, let missEvery): + let ids = (0 ..< count).compactMap { j -> Int? in + guard nextIndex + j < script.count else { return nil } + let ordinal = nextIndex + j + let token = script[ordinal] + return missEvery > 0 && (ordinal + 1) % missEvery == 0 ? (token + 1) % vocabularySize : token + } + return ids + case .heads(let head): + guard let state, let carry, carry.token == lastToken else { self.carry = nil; return [] } + try fence() + var feed = (tokens: MLXArray([Int32(lastToken)]).reshaped([1, 1]), hidden: carry.hidden) + var drafted: [MLXArray] = [] + for _ in 0 ..< count { + let next = head.assistant.draftStep(tokens: feed.tokens, hidden: feed.hidden, shortlist: nil, + requestState: state) + let token = next.tokens.reshaped([1, 1]) + drafted.append(token) + feed = (token, next.hidden) + } + let drafts = concatenated(drafted, axis: 1) + try MLX.withError { error in + eval([drafts] + head.assistant.evaluationTargets(for: state)) + try error.check() + } + let ids = drafts.asArray(Int32.self).map(Int.init) + guard ids.count == count, ids.allSatisfy({ (0 ..< vocabularySize).contains($0) }) else { + throw ProbeError("MiMo speculative head drafted a token outside the vocabulary") + } + return ids + } + } + + /// After both ranks kept `tokens` of a window `[last] + drafts` whose + /// post-final-norm rows are `hidden`. + func finalize(drafts: [Int], tokens: [Int], acceptedDrafts: Int, hidden: MLXArray) throws { + guard !released, !drafts.isEmpty, !tokens.isEmpty, hidden.dim(1) >= tokens.count else { + throw ProbeError("MiMo tensor-parallel drafter finalized rows the window did not keep") + } + statistics.record(drafts: drafts.count, acceptedDrafts: acceptedDrafts, emitted: tokens.count) + guard case .heads(let head) = speculation.proposer, let state else { return } + let carryHidden = hidden[0..., (tokens.count - 1) ..< tokens.count, 0...] + let draftArray = MLXArray(drafts.map(Int32.init)).reshaped([1, drafts.count]) + head.assistant.finalizeRound(requestState: state, confirmedInputTokens: 1 + acceptedDrafts, + committedDraftTokens: draftArray[0..., 0 ..< acceptedDrafts], + committedTargetHidden: hidden[0..., 0 ..< acceptedDrafts, 0...]) + try MLX.withError { error in + eval(head.assistant.evaluationTargets(for: state) + [carryHidden]) + try error.check() + } + carry = (tokens[tokens.count - 1], carryHidden) + } + + /// After a plain step: the heads draft no more for this request, as the + /// pipeline's decoder (they would need the history the step skipped). + func plainStep() throws { + guard !released else { throw ProbeError("MiMo tensor-parallel drafter stepped past its request") } + statistics.record(drafts: 0, acceptedDrafts: 0, emitted: 1) + carry = nil + } + + func release() { + guard !released else { return } + released = true + carry = nil; promptFrontier = nil + if case .heads(let head) = speculation.proposer, let state { head.assistant.releaseRequestState(state) } + } + + deinit { release() } +} + +extension MiMoTensorParallelRequestBudget { + /// What speculative rounds of `depth` add to one request on a rank beside + /// the drafter's own bounded state: each sliding layer's ring gathered + /// once more per extra window row, one page per layer copied while a + /// window's checkpoint holds the old one, and a window's whole rows (FP32) + /// for its logprobs or its sampled targets, twice. + static func speculativeWindowBytes(plan: MiMoTensorParallelPlan, slidingWindow: Int, depth: Int, + allocationBound: (Int) throws -> Int) throws -> Int { + let sum = QwenLongPrefillCheckedBytes.sum, product = QwenLongPrefillCheckedBytes.product + guard slidingWindow > 0, (1 ... MiMoMTPTerms.maximumDepth).contains(depth) else { + throw ProbeError("MiMo tensor-parallel speculative budget needs a window and a depth") + } + var total = 0 + for layer in 0 ..< plan.layerCount { + let rowBytes = try product([plan.kvHeads(layer: layer) / plan.size, + plan.headDim(layer: layer) + plan.valueHeadDim(layer: layer), 2]) + if plan.slidingLayers[layer] { + total = try sum([total, product([allocationBound(product([slidingWindow, rowBytes])), depth])]) + } + total = try sum([total, allocationBound(product([pageTokens, rowBytes]))]) + } + return try sum([total, product([allocationBound(product([depth + 1, plan.vocabularySize, 4])), 2])]) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSynthetic.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSynthetic.swift new file mode 100644 index 0000000000..7a21b363a3 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelSynthetic.swift @@ -0,0 +1,187 @@ +import CryptoKit +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import MLXNN + +extension MiMoTensorParallelModel { + /// Synthetic MiMo V2.6 geometries for model-free tensor-parallel checks. + /// Random weights: never a model pass. + public enum SyntheticVariant: String, CaseIterable, Sendable { + /// Hidden 1,024; 16 experts, top-8, expert width 1,024 (512 per rank, + /// MXFP4 group 32); 16 query heads with 2 full and 4 sliding KV heads + /// at the registered head dims 192/128, sinks on sliding layers; 8-bit + /// attention, dense layer and head. Every per-rank decode shape stays + /// inside the production MiMo decode kernels' gates (experts, router + /// GEMV, fused norms), as the whole model's do. + case kernel + /// Hidden 256; 8 experts, top-2; below those gates, so the generic + /// expert, router and attention paths run. + case tiny + } + + /// The variant's whole `config.json` object. `experts`/`topK` replace the + /// variant's routed bank (with `topK == experts` every token takes every + /// expert, so no rounding can change a route). `mtp` declares the three + /// trained next-N heads and spells the quantization as the registered + /// artifact does (affine 4-bit default, every 8-bit module named), so each + /// text module keeps the same policy. + public static func syntheticConfiguration(_ variant: SyntheticVariant, dtype: DType = .bfloat16, + experts: Int? = nil, topK: Int? = nil, mtp: Bool = false) -> [String: Any] { + let kernel = variant == .kernel + let layers = kernel ? 6 : 4 + let dtypeName = dtype == .float32 ? "float32" : "bfloat16" + var quantization: [String: Any] = ["group_size": 64, "bits": mtp ? 4 : 8, "mode": "affine"] + let pattern = kernel ? [0, 1, 1, 0, 1, 1] : [0, 1, 1, 0] + let routed = (0 ..< layers).map { $0 == 0 ? 0 : 1 } + for layer in 0 ..< layers where routed[layer] == 1 { + for module in ["gate_proj", "up_proj", "down_proj"] { + quantization["language_model.model.layers.\(layer).mlp.switch_mlp.\(module)"] = + ["group_size": 32, "bits": 4, "mode": "mxfp4"] + } + } + if mtp { + let eight: [String: Any] = ["group_size": 64, "bits": 8, "mode": "affine"] + for name in ["language_model.model.embed_tokens", "language_model.lm_head"] { quantization[name] = eight } + for layer in 0 ..< layers { + for module in ["q_proj", "k_proj", "v_proj", "o_proj"] { + quantization["language_model.model.layers.\(layer).self_attn.\(module)"] = eight + } + for module in ["gate_proj", "up_proj", "down_proj"] where routed[layer] == 0 { + quantization["language_model.model.layers.\(layer).mlp.\(module)"] = eight + } + } + } + return [ + "model_type": "mimo_v2", "architectures": ["MiMoV2ForCausalLM"], + "hidden_size": kernel ? 1024 : 256, "intermediate_size": kernel ? 2048 : 512, + "moe_intermediate_size": kernel ? 1024 : 256, "vocab_size": kernel ? 4096 : 512, + "num_hidden_layers": layers, "max_position_embeddings": 4096, + "sliding_window": 8, "sliding_window_size": 8, "num_nextn_predict_layers": mtp ? 3 : 0, + "hybrid_layer_pattern": pattern, "moe_layer_freq": routed, + "partial_rotary_factor": 0.334, "attention_value_scale": 0.707, "layernorm_epsilon": 1e-5, + "attention_projection_layout": "fused_qkv", "moe_router_dtype": dtypeName, "hidden_act": "silu", + "dtype": dtypeName, "attention_bias": false, "tie_word_embeddings": false, "attention_dropout": 0.0, + "scoring_func": "sigmoid", "topk_method": "noaux_tc", "n_routed_experts": experts ?? (kernel ? 16 : 8), + "num_experts_per_tok": topK ?? (kernel ? 8 : 2), "n_group": 1, "topk_group": 1, "norm_topk_prob": true, + "num_attention_heads": kernel ? 16 : 4, "num_key_value_heads": 2, + "head_dim": kernel ? 192 : 48, "v_head_dim": kernel ? 128 : 32, "rope_theta": 10_000_000.0, + "add_full_attention_sink_bias": false, + "swa_num_attention_heads": kernel ? 16 : 4, "swa_num_key_value_heads": kernel ? 4 : 2, + "swa_head_dim": kernel ? 192 : 48, "swa_v_head_dim": kernel ? 128 : 32, "swa_rope_theta": 10_000.0, + "add_swa_attention_sink_bias": true, "eos_token_id": [1, 2], "pad_token_id": 0, + "quantization": quantization, "quantization_config": quantization, + ] + } + + /// Writes a seeded random checkpoint of `variant` into `directory` + /// (`config.json`, `model.safetensors` and its index), quantized as the + /// registered artifact is (MXFP4 experts, affine 8-bit group 64 + /// elsewhere; BF16 router, norms and sinks; FP32 score correction), with + /// one MTP and one vision tensor that every loader must skip by name. + /// `mtp` writes the three next-N heads whole instead (BF16, random). + public static func writeSyntheticCheckpoint(directory: URL, variant: SyntheticVariant, seed: UInt64 = 7, + dtype: DType = .bfloat16, experts: Int? = nil, topK: Int? = nil, + mtp: Bool = false) throws { + guard [.bfloat16, .float32].contains(dtype), !mtp || dtype == .bfloat16 else { + throw ProbeError("MiMo synthetic checkpoint: weights are bfloat16 or float32 (bfloat16 with heads)") + } + if experts != nil || topK != nil { + guard let experts, let topK, (2 ... 64).contains(experts), (1 ... experts).contains(topK) else { + throw ProbeError("MiMo synthetic checkpoint: 2 to 64 experts, top-k at most the experts") + } + } + let configurationData = try JSONSerialization.data( + withJSONObject: syntheticConfiguration(variant, dtype: dtype, experts: experts, topK: topK, mtp: mtp), + options: [.sortedKeys, .prettyPrinted]) + let plan = try MiMoTensorParallelPlan(configuration: configurationData) + let configuration = try JSONDecoder().decode(MiMoV26Configuration.self, from: configurationData) + var arrays = try withRandomState(MLXRandom.RandomState(seed: seed)) { () throws -> [String: MLXArray] in + let model = try MiMoV26TextModel(configuration) + var values: [(String, MLXArray)] = [] + for (key, value) in model.parameters().flattened() { + let shape = value.shape + if key.hasSuffix("e_score_correction_bias") { + values.append((key, MLXRandom.normal(shape) * 0.05)) + continue + } + let generated: MLXArray + if key.hasSuffix("attention_sink_bias") { + generated = MLXRandom.uniform(low: -1.0, high: 1.0, shape) + } else if key.hasSuffix("norm.weight") || key.hasSuffix("layernorm.weight") { + generated = MLXRandom.uniform(low: 0.6, high: 1.4, shape) + } else if key.hasSuffix("embed_tokens.weight") { + generated = MLXRandom.normal(shape) + } else { + generated = MLXRandom.normal(shape) * (1 / Float(shape.last ?? 1).squareRoot()) + } + values.append((key, generated.asType(dtype))) + } + try model.update(parameters: ModuleParameters.unflattened(values), verify: [.noUnusedKeys, .shapeMismatch]) + quantize(model: model) { path, module in + guard module is Linear || module is SwitchLinear || module is Embedding, + let policy = plan.policy(module: MiMoTensorParallelPlan.textNamespace + path) else { return nil } + return (policy.groupSize, policy.bits, policy.mode == "mxfp4" ? .mxfp4 : .affine) + } + var flat = Dictionary(uniqueKeysWithValues: model.parameters().flattened().map { + (MiMoTensorParallelPlan.textNamespace + $0.0, $0.1) + }) + eval(Array(flat.values)) + if mtp { + // The heads draw after every text tensor, so the text weights equal the variant's without heads. + let heads = try MiMoV26MTP(target: model, floatingProjections: true) + for (key, value) in heads.parameters().flattened() { + let shape = value.shape + let generated: MLXArray + if key.hasSuffix("attention_sink_bias") { + generated = MLXRandom.uniform(low: -1.0, high: 1.0, shape) + } else if key.hasSuffix("norm.weight") { + generated = MLXRandom.uniform(low: 0.6, high: 1.4, shape) + } else { + generated = MLXRandom.normal(shape) * (1 / Float(shape.last ?? 1).squareRoot()) + } + flat[MiMoTensorParallelDraftHead.prefix + key] = generated.asType(.bfloat16) + } + eval(Array(flat.values)) + } + return flat + } + if !mtp { + arrays["language_model.model.mtp.layers.0.enorm.weight"] = MLXArray.ones([plan.hiddenSize], dtype: dtype) + } + arrays["vision_tower.patch_embed.proj.weight"] = MLXArray.zeros([8, 8], dtype: dtype) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try configurationData.write(to: directory.appendingPathComponent("config.json")) + try save(arrays: arrays, url: directory.appendingPathComponent("model.safetensors")) + let index: [String: Any] = ["metadata": [:] as [String: Any], + "weight_map": Dictionary(uniqueKeysWithValues: arrays.keys.map { ($0, "model.safetensors") })] + try JSONSerialization.data(withJSONObject: index, options: [.sortedKeys, .prettyPrinted]) + .write(to: directory.appendingPathComponent("model.safetensors.index.json")) + try writeSyntheticManifest(directory: directory, + files: ["config.json", "model.safetensors", "model.safetensors.index.json"]) + } + + /// `manifest.json` over `files` as a published artifact's (each file's + /// SHA-256 and size; the aggregate is the SHA-256 of the digests in path + /// order), so a verified load hashes the synthetic checkpoint first. + /// Returns the aggregate. + @discardableResult + static func writeSyntheticManifest(directory: URL, files: [String]) throws -> String { + var entries: [[String: Any]] = [], aggregate = SHA256(), total = 0 + for path in files.sorted() { + let data = try Data(contentsOf: directory.appendingPathComponent(path)) + let digest = SHA256.hash(data: data) + digest.withUnsafeBytes { aggregate.update(bufferPointer: $0) } + entries.append(["path": path, "sha256": digest.map { String(format: "%02x", $0) }.joined(), + "size_bytes": data.count]) + total += data.count + } + let hex = aggregate.finalize().map { String(format: "%02x", $0) }.joined() + let manifest: [String: Any] = ["aggregate_sha256": hex, "file_count": entries.count, + "total_size_bytes": total, "files": entries] + try JSONSerialization.data(withJSONObject: manifest, options: [.sortedKeys, .prettyPrinted]) + .write(to: directory.appendingPathComponent("manifest.json")) + return hex + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelVerifiedLoad.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelVerifiedLoad.swift new file mode 100644 index 0000000000..a5c0c68e35 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/MiMo/TensorParallel/MiMoTensorParallelVerifiedLoad.swift @@ -0,0 +1,127 @@ +import Foundation +import MLX +import MLXLLM + +/// What one rank of a MiMo tensor-parallel load read and holds. The verified +/// artifact and the plan fingerprint are equal on both ranks (compared before +/// either serves); the byte counts are this rank's own. +struct MiMoTensorParallelShardReceipt: Equatable, Sendable { + let verifiedAggregateSHA256: String + let planFingerprint: String + let rank: Int + /// Text tensors read, and the excluded components' tensors skipped by name. + let textTensors: Int + let excludedTensors: Int + /// The text tensors' whole stored bytes, and the bytes this rank read of them. + let textBytes: Int + let readBytes: Int + let shardBytes: Int + let loadNanoseconds: UInt64 +} + +/// One rank's shard of a verified MiMo V2.6 checkpoint +/// (`MiMoTensorParallelPlan`). The caller hands over a checkpoint whose every +/// file already matched its manifest (`VerifiedCheckpoint`: the registered +/// artifact through `prepareMiMoResidentSource`). Then, per indexed tensor in +/// name order: excluded components are skipped by name, every other name must +/// be a text tensor of the plan with the plan's stored shape and a stored +/// dtype of the artifact, and only this rank's byte runs are read (one run +/// per index of the dimensions before the cut axis: the SDK's +/// `MiMoV26TensorShard.byteRuns`, read as aligned uncached pieces through +/// the pinned descriptor). Any difference refuses the load; nothing of a +/// divided tensor outside this rank's half is read. +enum MiMoTensorParallelVerifiedLoad { + static let storedDTypes: Set = [.uint32, .uint8, .bfloat16, .float32] + + /// `beforeRead(name, bytes)` runs before each read (a host gate, a + /// cooperative check); `check` after each. + static func load(checkpoint: VerifiedCheckpoint, configurationData: Data, role: MiMoTensorParallelModel.Role, + reduction: QwenTensorParallelReduction?, + beforeRead: (String, Int) throws -> Void = { _, _ in }, + check: () throws -> Void = {}) throws + -> (model: MiMoTensorParallelModel, receipt: MiMoTensorParallelShardReceipt) { + let started = DispatchTime.now().uptimeNanoseconds + try checkpoint.requireConfiguration(configurationData) + let plan = try MiMoTensorParallelPlan(configuration: configurationData) + let descriptors = try tensorDescriptors(checkpoint: checkpoint, + scope: .init(acceptsUInt8: true, indexedShardsOnly: true)) + let rank: Int + switch role { + case .full: rank = 0 + case .shard(let value): rank = value + } + let shard = try MiMoV26TensorShard(rank: rank, size: plan.size) + // Every name is disposed of before the first read. + var reads: [(name: String, descriptor: TensorDescriptor, selection: TensorSelection, bytes: Int)] = [] + var excluded = 0, textBytes = 0 + for name in descriptors.keys.sorted() { + let descriptor = descriptors[name]! + if case .excluded = try plan.disposition(of: name) { excluded += 1; continue } + guard try plan.expectedShape(key: name) == descriptor.shape, storedDTypes.contains(descriptor.dtype) else { + throw ProbeError("MiMo tensor parallel load: \(name) is stored as \(descriptor.dtype) \(descriptor.shape), not the plan's") + } + textBytes += descriptor.byteCount + guard case .shard = role, let axis = try plan.cut(key: name) else { + reads.append((name, descriptor, .all, descriptor.byteCount)) + continue + } + let local = try plan.localShape(key: name, shape: descriptor.shape) + let half = local[axis] + let selection = TensorSelection.axis(axis, [(rank * half) ..< ((rank + 1) * half)]) + // The selection's runs are the SDK shard's byte runs, exactly. + let runs = try shard.byteRuns(shape: descriptor.shape, axis: axis, bytes: descriptor.byteCount) + let inner = descriptor.shape[(axis + 1)...].reduce(descriptor.dtype.size, *) + guard runs.count == descriptor.shape[.. (model: MiMoTensorParallelModel, aggregateSHA256: String, readBytes: Int, textBytes: Int) { + let configurationData = try Data(contentsOf: modelDirectory.appendingPathComponent("config.json")) + let checkpoint = try VerifiedCheckpoint(directory: modelDirectory, configurationData: configurationData, + expectedAggregateSHA256: expectedAggregateSHA256, + hashingConcurrency: MiMoRegisteredSpecification.hashingConcurrency) + let loaded = try MiMoTensorParallelVerifiedLoad.load(checkpoint: checkpoint, + configurationData: configurationData, role: role, reduction: reduction) + return (loaded.model, loaded.receipt.verifiedAggregateSHA256, loaded.receipt.readBytes, loaded.receipt.textBytes) + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTensorBatchBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTensorBatchBudget.swift index 4280358057..4eaae6d8e6 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTensorBatchBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTensorBatchBudget.swift @@ -99,7 +99,7 @@ extension ClusterPlacementArtifact { try QwenTensorParallelBatchBudget.derive(geometry: family.geometry, plan: split, tensors: canonical, maximumTokens: family.profile.maximumContextTokens, chunkSize: family.profile.maximumChunkTokens, lanes: lanes, paged: true, rank: rank, - allocationBound: allocationBound) + promptTokens: family.profile.maximumPromptTokens, allocationBound: allocationBound) } let whole = try plain(plan, rank: nil) return try .init(request: request, lanes: lanes, chunkTokens: chunkTokens, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift index 2bccd56b8a..367b9fd477 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/QwenDensePlacementFamily.swift @@ -354,8 +354,29 @@ public enum ClusterPlacementLayouts { guard runtimeProfile != ClusterGLMImageCandidate.profileID else { throw ProbeError("GLM runtime is unavailable") } #endif if MiMoPlacementFamily.handles(configuration: configuration) { - let family = try MiMoPlacementFamily(configuration: configuration, imageCandidate: runtimeProfile != nil) + var family = try MiMoPlacementFamily(configuration: configuration, imageCandidate: runtimeProfile != nil) try family.requireRegisteredInventory(tensors) + #if canImport(MLX) + let bound: ((Int) throws -> Int)? = allocationBound + #else + let bound = allocationBound + #endif + if let plan = family.tensorParallel, let bound { + // What a rank's LOAD gate reserves beside its shard: one request at the profile's longest context. + let budget = try MiMoTensorParallelRequestBudget.derive(plan: plan, + slidingWindow: family.specification.slidingWindow, contextTokens: family.profile.maximumContextTokens, + chunkTokens: family.profile.maximumChunkTokens, allocationBound: bound) + family.tensorParallelRequestAllowance = budget.allowance + #if canImport(MLXLLM) + // Its speculative rounds (`ClusterMiMoTensorParallel`): the heads whole, and each request's drafter + // state (the SDK's own declaration) and window rows beside the reserve, as the LOAD gate adds them. + if let rounds = try MiMoTensorParallelResidentRuntime.placementRounds(configuration: configuration, + plan: plan, chunkTokens: family.profile.maximumChunkTokens, budget: budget, allocationBound: bound) { + family.tensorParallelSpeculativeHead = rounds.head + family.tensorParallelRequestAllowance = rounds.allowance + } + #endif + } return try ClusterModelLayoutBuilder.build(family: family, tensors: tensors, artifactSHA256: family.specification.artifactSHA256, configurationSHA256: family.specification.configurationSHA256) @@ -379,8 +400,22 @@ public enum ClusterPlacementLayouts { configurationSHA256: family.specification.configurationSHA256) } if Gemma4RegisteredSpecification.isRegistered(configuration: configuration) { - let family = try Gemma4PlacementFamily(configuration: configuration, manifest: manifest) + var family = try Gemma4PlacementFamily(configuration: configuration, manifest: manifest) try family.requireRegisteredInventory(tensors) + #if canImport(MLX) + let bound: ((Int) throws -> Int)? = allocationBound + #else + let bound = allocationBound + #endif + if family.tensorParallel != nil, let bound { + // What a rank's LOAD gate reserves beside its shard: one request at the profile's longest + // context, with its prompt-prefix capture. + family.tensorParallelRequestAllowance = try Gemma4TensorParallelRequestBudget.derive( + contextTokens: family.profile.maximumContextTokens, chunkTokens: family.profile.maximumChunkTokens, + promptTokens: family.profile.maximumPromptTokens, + keepsPrefixes: Gemma4ResidentAdapterDefinition.tensorParallelKeepsPromptPrefixes, + allocationBound: bound).allowance + } return try ClusterModelLayoutBuilder.build(family: family, tensors: tensors, artifactSHA256: family.specification.artifactSHA256, configurationSHA256: family.specification.configurationSHA256) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Diagnostics/QwenGenerationDiagnosticResources.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Diagnostics/QwenGenerationDiagnosticResources.swift index 15772d2f37..56d53a598e 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Diagnostics/QwenGenerationDiagnosticResources.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Diagnostics/QwenGenerationDiagnosticResources.swift @@ -37,7 +37,7 @@ final class QwenGenerationDiagnosticResources { // with the actual allocator, then require the owner's reservation to match. let actual = try QwenResidentRequestAllowance.derive(profile: profile, plan: plan, rank: rank, maximumTokens: request.maximumTokens, chunkSize: min(request.chunkSize, request.promptCount), - bound: QwenResidentResourceEnvironment.allocationBound) + decode: requestAllowance.decode, bound: QwenResidentResourceEnvironment.allocationBound) guard actual.stateBytes == requestAllowance.stateBytes, actual.fusionBytes == requestAllowance.fusionBytes, actual.transientBytes == requestAllowance.transientBytes, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Generation/QwenLayerStageSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Generation/QwenLayerStageSession.swift index b087758f72..6f2d4b58ba 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Generation/QwenLayerStageSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Generation/QwenLayerStageSession.swift @@ -28,6 +28,19 @@ struct QwenLayerStageAdoptedState { /// One serialized stage; no overlap, network, sampling or hidden token-history /// changes. Native methods install an error handler and retire on every error. final class QwenLayerStageSession { + /// Command-buffer commit limits of a pipeline decode step, a lane step and + /// a speculative round on the thread that encodes them, as GLM's and + /// Qwen's tensor-parallel decode keep them + /// (`GLM5NextTensorParallelResidentRuntime.decodeCommandBuffers`). The + /// GPT-OSS and GLM pipeline stages take the same limits. Under the rank's + /// 16-operation guard (`ClusterWorkerEnvironmentGuards`) and MLX's per-chip + /// input-size bound, which a large expert bank passes alone, a decode step + /// commits a buffer every few launches, each a GPU gap. Prefill keeps the + /// rank's limits. Synchronization only: results never depend on the + /// partitioning. MLX keeps up to ten buffers in flight, so a step's + /// temporaries can span the stage's layers (`QwenResidentPrefillTransient`). + static let decodeCommandBuffers = GPU.CommandBufferLimits(operations: 100, megabytes: 1 << 20) + let identity: QwenLayerStageSessionIdentity let request: QwenLayerStageGenerationRequest private let stage: LoadedQwenLayerStage @@ -203,7 +216,9 @@ final class QwenLayerStageSession { do { try state.requireOpen() let frame = try schedule.admitDecode(offset: offset) - return try perform(tokens: [token], frame: frame, incoming: incoming, check: check) + return try GPU.withCommandBufferLimits(Self.decodeCommandBuffers) { + try perform(tokens: [token], frame: frame, incoming: incoming, check: check) + } } catch { try fail(error) } } @@ -647,7 +662,7 @@ extension QwenLayerStageSession { throw ProbeError("A batched decode needs distinct sessions of one hosted loaded stage") } do { - return try MLX.withError { error in + return try GPU.withCommandBufferLimits(decodeCommandBuffers) { try MLX.withError { error in func checked() throws { try error.check(); try check() } var frames: [QwenLayerStageFrame] = [] for (session, token) in zip(sessions, tokens) { @@ -711,7 +726,7 @@ extension QwenLayerStageSession { Stream.gpu.synchronize(); try checked() } return output - } + } } } catch { for session in sessions { try? session.retire(failed: true) } throw error diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/MTP/QwenMTPDecoder.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/MTP/QwenMTPDecoder.swift index cc7638db78..d03c0fb5c3 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/MTP/QwenMTPDecoder.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/MTP/QwenMTPDecoder.swift @@ -155,7 +155,8 @@ final class QwenMTPDecoder { return try plainStep(producer: producer, consumer: consumer, lastToken: lastToken, offset: offset, check: check) } - return try MLX.withError { error in + // A round, drafts included, encodes as a decode step does. + return try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers) { try MLX.withError { error in func checked() throws { try error.check(); try check() } let started = DispatchTime.now().uptimeNanoseconds // Draft: once from the carry, then on the head's own hidden. @@ -234,7 +235,7 @@ final class QwenMTPDecoder { statistics.settleNanoseconds += settled - evaluated return Emitted(tokens: tokens, payloadSHA256: digests, logits: logits[0..., 0 ..< emitted, 0...], round: true) - } + } } } /// One ordinary decode frame through both stages, as the plain phase-split diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/MTP/QwenPipelineMTPGeneration.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/MTP/QwenPipelineMTPGeneration.swift index 0df5fecae4..c7d6d68470 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/MTP/QwenPipelineMTPGeneration.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/MTP/QwenPipelineMTPGeneration.swift @@ -71,10 +71,34 @@ enum QwenPipelineMTPGeneration { } /// Rank 0: run each window rank 1 asks for, check what it keeps, publish. + /// Every round encodes as a decode step does (`QwenLayerStageSession.decodeCommandBuffers`). static func runProducer(session: QwenLayerStageSession, control: QwenLayerStageGenerationControl, terms: QwenMTPTerms, collective: Collective, recording: QwenGenerationDiagnosticCapture? = nil, onCommittedToken: (Int) throws -> Bool, check: () throws -> Void) throws -> Outcome { + try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers) { + try producerRounds(session: session, control: control, terms: terms, collective: collective, + recording: recording, onCommittedToken: onCommittedToken, check: check) + } + } + + /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank + /// 0's publication. Every round, drafts included, encodes as a decode + /// step does (`QwenLayerStageSession.decodeCommandBuffers`). + static func runConsumer(session: QwenLayerStageSession, decoder: QwenMTPDecoder, + control: QwenLayerStageGenerationControl, collective: Collective, + recording: QwenGenerationDiagnosticCapture? = nil, + check: () throws -> Void) throws -> Outcome { + try GPU.withCommandBufferLimits(QwenLayerStageSession.decodeCommandBuffers) { + try consumerRounds(session: session, decoder: decoder, control: control, collective: collective, + recording: recording, check: check) + } + } + + private static func producerRounds(session: QwenLayerStageSession, control: QwenLayerStageGenerationControl, + terms: QwenMTPTerms, collective: Collective, + recording: QwenGenerationDiagnosticCapture?, + onCommittedToken: (Int) throws -> Bool, check: () throws -> Void) throws -> Outcome { let agreement = control.agreement, request = agreement.request guard collective.rank == 0, agreement.speculativeRoundsFraming == terms.pipelineDecodeFraming else { throw ProbeError("Only rank 0 of an agreed speculative pipeline runs the producer side of a round") @@ -155,12 +179,10 @@ enum QwenPipelineMTPGeneration { return .init(selected: selected, finalDecision: finalDecision, discardedDecodeForwards: discarded, statistics: nil) } - /// Rank 1: draft, verify each window rank 0 runs, keep, and follow rank - /// 0's publication. - static func runConsumer(session: QwenLayerStageSession, decoder: QwenMTPDecoder, - control: QwenLayerStageGenerationControl, collective: Collective, - recording: QwenGenerationDiagnosticCapture? = nil, - check: () throws -> Void) throws -> Outcome { + private static func consumerRounds(session: QwenLayerStageSession, decoder: QwenMTPDecoder, + control: QwenLayerStageGenerationControl, collective: Collective, + recording: QwenGenerationDiagnosticCapture?, + check: () throws -> Void) throws -> Outcome { let agreement = control.agreement, request = agreement.request guard collective.rank == 1, agreement.speculativeRoundsFraming == decoder.terms.pipelineDecodeFraming else { throw ProbeError("Only rank 1 of an agreed speculative pipeline runs the consumer side of a round") diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift index d6f585a0a3..13c685f3df 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift @@ -170,12 +170,13 @@ public final class QwenStagePrefixCache: @unchecked Sendable { var captureCost: QwenStagePrefixCaptureCost? { lock.withLock { measured } } /// The budget for `roomBytes` of admissible memory left beside the - /// serving context's charge: half of it, at most `maximumBudgetBytes`, - /// rounded down to 256 MiB so the idle refresh does not move it with - /// every small drift. The serving context is never reduced for the - /// cache; the other half stays for the desktop's own drift. - public static func budget(roomBytes: Int) -> Int { - max(0, min(maximumBudgetBytes, roomBytes / 2) / budgetGranuleBytes * budgetGranuleBytes) + /// serving context's charge: half of it, at most `maximumBytes` (this + /// Mac's `maximumBudgetBytes`), rounded down to 256 MiB so the idle + /// refresh does not move it with every small drift. The serving context + /// is never reduced for the cache; the other half stays for the desktop's + /// own drift. + public static func budget(roomBytes: Int, maximumBytes: Int = QwenStagePrefixCache.maximumBudgetBytes) -> Int { + max(0, min(maximumBytes, roomBytes / 2) / budgetGranuleBytes * budgetGranuleBytes) } static let budgetGranuleBytes = 256 << 20 /// The room a memory-bound serving context leaves for the cache: one granule of budget (half the room). @@ -260,8 +261,8 @@ public final class QwenStagePrefixCache: @unchecked Sendable { /// directions, so a load during a memory dip does not keep it small for as /// long as the model stays loaded. Entries beyond a lower budget go now. /// True when the budget changed. - @discardableResult func refreshBudget(roomBytes: Int) -> Bool { - let target = Self.budget(roomBytes: roomBytes) + @discardableResult func refreshBudget(roomBytes: Int, maximumBytes: Int = QwenStagePrefixCache.maximumBudgetBytes) -> Bool { + let target = Self.budget(roomBytes: roomBytes, maximumBytes: maximumBytes) return lock.withLock { guard target != budget else { return false } budget = target; evictLocked(reserving: 0); return true diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentFamily.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentFamily.swift index 1c1775d7e4..62856ff22f 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentFamily.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentFamily.swift @@ -22,9 +22,10 @@ extension QwenResidentLoadedStage: LayerStageResidentStage { } func requestAllowance(plan: QwenLayerStagePlan, rank: Int, maximumTokens: Int, chunkSize: Int, + decode: LayerStageDecodeShape, bound: (Int) throws -> Int) throws -> QwenResidentRequestAllowance { try QwenResidentRequestAllowance.derive(profile: profile, plan: plan, rank: rank, - maximumTokens: maximumTokens, chunkSize: chunkSize, bound: bound) + maximumTokens: maximumTokens, chunkSize: chunkSize, decode: decode, bound: bound) } func diagnosticResources(plan: QwenLayerStagePlan, request: QwenLayerStageGenerationRequest, rank: Int, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentRuntime.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentRuntime.swift index 85326977cf..f6a8e3f136 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentRuntime.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resident/QwenResidentRuntime.swift @@ -281,7 +281,9 @@ public final class QwenResidentRuntime { let prompt = min(admission.memoryProfile.maximumPromptTokens, context - 1) let chunk = min(admission.memoryProfile.maximumChunkTokens, prompt) let allowance = try stage.requestAllowance(plan: admission.plan, rank: rank, - maximumTokens: context, chunkSize: chunk, bound: QwenResidentResourceEnvironment.allocationBound) + maximumTokens: context, chunkSize: chunk, + decode: .init(mode: mode, rank: rank, speculativeTerms: speculativeTerms), + bound: QwenResidentResourceEnvironment.allocationBound) let prefill = try QwenResidentPrefillSelection.allowance(policy, rank: rank, promptCount: prompt, chunkSize: chunk, hiddenSize: admission.profile.hiddenSize, elementBytes: qwenStageWireElementBytes(admission.profile.activationDType), @@ -372,7 +374,9 @@ public final class QwenResidentRuntime { guard let stage else { throw ProbeError("Resident model already released") } let allowance = try stage.requestAllowance( plan: admission.plan, rank: collective.rank, maximumTokens: request.maximumTokens, - chunkSize: min(request.chunkSize, request.promptCount), bound: QwenResidentResourceEnvironment.allocationBound) + chunkSize: min(request.chunkSize, request.promptCount), + decode: .init(mode: generationMode, rank: collective.rank, speculativeTerms: speculativeTerms), + bound: QwenResidentResourceEnvironment.allocationBound) let prefill = try prefillAllowance(prefillPolicy, promptCount: request.promptCount, chunkSize: request.chunkSize) let split = try Self.phaseSplitAllowance(generationMode, admission: admission, stage: stage, rank: collective.rank, promptCount: request.promptCount, speculativeTerms: speculativeTerms) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentPrefillTransient.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentPrefillTransient.swift index a281952854..4cd4977998 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentPrefillTransient.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentPrefillTransient.swift @@ -13,20 +13,25 @@ import Foundation /// beside a float32 output. Query blocking (`DARKBLOOM_CBV2_ATTN_QUERY_BLOCK`) /// bounds the matrix per block, but blocks of one frame may be evaluated /// together, so the whole frame is priced: an upper bound, not a measurement. -/// Layers run one after another, so one layer's transient is the stage's. +/// Prefill layers run one after another under the rank's command-buffer +/// limits, so one layer's transient is the frame's. A decode step's command +/// buffers (`QwenLayerStageSession.decodeCommandBuffers`) can keep every +/// attending layer's temporaries alive at once: `decodeRows` is the number of +/// such rows, each layer's decode rows added up, priced as score rows over +/// the whole context, and the larger of the two is charged. enum QwenResidentPrefillTransient { static let fusedHeadDimensions: Set = [64, 72, 80, 96, 128] static let scoreElementBytes = 4 static let outputElementBytes = 4 static func bytes(geometry g: QwenLongPrefillBudgetGeometry, stageHasAttention: Bool, - chunkTokens: Int, contextTokens: Int) throws -> Int { - guard chunkTokens > 0, contextTokens > 0 else { + chunkTokens: Int, contextTokens: Int, decodeRows: Int = 0) throws -> Int { + guard chunkTokens > 0, contextTokens > 0, decodeRows >= 0 else { throw QwenLongPrefillBudgetError.invalid("Attention transient needs a positive frame and context") } - guard stageHasAttention else { return 0 } let product = QwenLongPrefillCheckedBytes.product - let queries = min(chunkTokens, contextTokens) + let queries = max(stageHasAttention ? min(chunkTokens, contextTokens) : 0, decodeRows) + guard queries > 0 else { return 0 } let output = try product([g.queryHeads, queries, g.headDimension, outputElementBytes]) if fusedHeadDimensions.contains(g.headDimension) { return output } let scores = try product([g.queryHeads, queries, contextTokens, scoreElementBytes]) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentRequestResources.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentRequestResources.swift index e5b19d7a0a..894c4e33bb 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentRequestResources.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenResidentRequestResources.swift @@ -6,11 +6,14 @@ struct QwenResidentRequestAllowance { let stateBytes: Int let fusionBytes: Int let reservedBytes: Int - /// One prefill frame's attention transient at this request's context + /// One prefill frame's attention transient at this request's context, or + /// its decode step's on every layer it runs when larger /// (`QwenResidentPrefillTransient`), included in `reservedBytes`. var transientBytes = 0 /// Prompt plus output tokens this allowance was derived for; 0 when unknown. var contextTokens = 0 + /// What this request's decode forwards run, as derived. + var decode = LayerStageDecodeShape.plain /// This request's record at the host memory gate, and its first sample. let watch = QwenDenseStageLoadWatch("Resident request") @@ -22,7 +25,7 @@ struct QwenResidentRequestAllowance { /// them, and `fusionBytes` is the allowance for those copies. /// This named ledger excludes unknown workspace/whole-process peak claims. static func derive(profile: QwenRegisteredDenseModelProfile, plan: QwenLayerStagePlan, - rank: Int, maximumTokens: Int, chunkSize: Int, + rank: Int, maximumTokens: Int, chunkSize: Int, decode: LayerStageDecodeShape = .plain, bound: (Int) throws -> Int) throws -> Self { guard plan.stages.count == 2, (0...1).contains(rank) else { throw ProbeError("Resident request allowance requires an admitted two-stage Plan") @@ -87,12 +90,15 @@ struct QwenResidentRequestAllowance { // U#3651), so a context the gate admits is one the frame can run in. // From the stage's own layer kinds: a Plan without an interval (Nemotron, // interval 0) names its attention blocks `attention`. - let stageHasAttention = plan.stages[rank].layers.contains { ["full_attention", "attention"].contains($0.kind) } + func attends(_ layer: QwenLayerStagePlan.Layer) -> Bool { ["full_attention", "attention"].contains(layer.kind) } + let stageHasAttention = plan.stages[rank].layers.contains(where: attends) + // A decode step's rows on every attending layer it runs, alive at once. + let decodeLayers = decode.stages(of: plan, rank: rank).flatMap(\.layers).filter(attends).count let transientLogical = try QwenResidentPrefillTransient.bytes(geometry: g, stageHasAttention: stageHasAttention, - chunkTokens: chunkSize, contextTokens: maximumTokens) + chunkTokens: chunkSize, contextTokens: maximumTokens, decodeRows: try product([decode.rows, decodeLayers])) let transient = transientLogical == 0 ? 0 : try allowance(transientLogical, 1) return .init(stateBytes: state, fusionBytes: fusion, reservedBytes: try sum([state, fusion, transient]), - transientBytes: transient, contextTokens: maximumTokens) + transientBytes: transient, contextTokens: maximumTokens, decode: decode) } /// `onLoadedStage`: a request's reservation on a stage that is already loaded. It asks for what the request diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift index fe86f41cf0..1b60334fb5 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchBudget.swift @@ -15,14 +15,14 @@ struct QwenTensorParallelBatchBudget { let sharedBytesExcludingCollectives: Int let batchProjectionConstantBytes: Int let pagedPoolSlackBytes: Int - /// Paged: one full-history gather bank, shared (one prompt frame per step). + /// Paged: one full-history gather bank, shared (one prompt step at a time). let promptGatherBytes: Int let prefix: QwenTensorParallelBatchPrefixBudget let allowance: ClusterTensorParallelRequestAllowance static func derive(geometry g: QwenLongPrefillBudgetGeometry, plan: QwenTensorParallelPlan, tensors: [QwenDenseCanonicalTensor], maximumTokens: Int, chunkSize: Int, - lanes: Int, paged: Bool, rank: Int? = nil, + lanes: Int, paged: Bool, rank: Int? = nil, promptTokens: Int? = nil, allocationBound: (Int) throws -> Int) throws -> Self { guard (1...8).contains(lanes) else { throw ProbeError("Qwen TP batch budget requires 1...8 lanes") @@ -43,7 +43,7 @@ struct QwenTensorParallelBatchBudget { // The full-history gather bank is a prompt frame's transient: decode // and verify windows attend the pages in place (the fused paged // decode kernel, one query column at a time), and the batch driver - // runs at most one prompt frame per step, so one bank serves every + // runs one lane's prompt step at a time, so one bank serves every // lane (`QwenTensorParallelBatchSessionTests.fullHistoryGatherIsOne // PromptFramesTransient` measures both). The scalar floor's F32 KV // term (two BF16 banks) is replaced by the lane's own BF16 page @@ -69,10 +69,13 @@ struct QwenTensorParallelBatchBudget { } // Row-M1 partials cause a second live FP32 scales/offsets bank while // singleton/prefill's ConstantArrayCastCache retains its first bank. - // The rank's own columns of both banks, and prefix copies of its own - // heads; without a rank, full canonical bytes cover either rank. + // The rank's own columns of both banks, and each lane's prefix capture + // of its own heads (`promptTokens`: the profile's longest prompt, or a + // request's own); without a rank, full canonical bytes cover either + // rank. The prefix memory tier is not charged here. let prefix = try QwenTensorParallelBatchPrefixBudget.derive(geometry: local, - maximumTokens: maximumTokens, allocationBound: allocationBound) + maximumTokens: maximumTokens, promptTokens: promptTokens, chunkSize: chunkSize, + allocationBound: allocationBound) perLaneState = try sum([perLaneState, prefix.captureBytes]) let batchConstants = scalar.projectionConstantBytes let logits = try bound(product([lanes, plan.vocabularySize, 4]), count: 3) @@ -87,14 +90,18 @@ struct QwenTensorParallelBatchBudget { bound(product([plan.expertsPerToken, plan.hiddenSize, 4]), count: lanes), bound(product([plan.hiddenSize, 4]), count: lanes), ]) : 0) + // A merged prompt step's further frames in flight (one prompt step at a time, shared). + let wavefront = try QwenTensorParallelPromptWavefront.inFlightBytes(plan: plan, chunkTokens: chunkSize, + allocationBound: allocationBound) let shared = try sum([scalar.fusionBytes, transient, logits, - scalar.projectionConstantBytes, batchConstants, poolSlack, prefix.residentBytes, packing, promptGather]) + scalar.projectionConstantBytes, batchConstants, poolSlack, packing, promptGather, wavefront]) // A one-token batch can gather more bytes than a short prompt frame. - // Control limbs and retirement votes also travel in the sealed codec. + // Control limbs and retirement votes also travel in the sealed codec, + // the next step's limbs after a greedy selection's six words a row. let payload = max(scalar.allowance.maximumCollectivePayloadBytes, try product([lanes, plan.maximumPartialBytesPerToken]), try product([lanes, plan.vocabularySize, 4]), - try product([QwenTensorParallelBatchWire.words, 4])) + try product([QwenTensorParallelBatchWire.words + 6 * lanes, 4])) let frame = try sum([payload, QwenTensorParallelSealCodec.frameOverhead]) let allowance = try ClusterTensorParallelRequestAllowance(maximumContextTokens: maximumTokens, maximumChunkTokens: chunkSize, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift index 996bc7d878..9562a9047b 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Resources/QwenTensorParallelBatchPrefixBudget.swift @@ -1,34 +1,129 @@ import Foundation -/// Prefix copies are distinct from each lane's full live state and restore -/// workspace. Keep at most one original-grid frontier per lane, and two such -/// worst-case banks in the resident cache. The full unsliced geometry prices -/// either rank, including unequal shares. No shape estimate replaces LOAD's -/// canonical parameter quotation. +/// A tensor-parallel Qwen request's prompt-prefix capture and the boundaries +/// it keeps, on its own chunk grid, to the request's context. +/// +/// Kept boundaries (`frontiers`), each strictly before the prompt's final +/// token and after what the request restored: +/// - the deepest whole chunk before the final token (an exact repeat); +/// - the deepest whole chunk at least `promptEndMarginTokens` before the +/// prompt end, from `marginFloorTokens` on (the next turn of a +/// conversation, whose template re-renders the generation prompt; one +/// Mac's `demandedLatestPromptEndMarginTokens` cut); +/// - every multiple of `stripeTokens` (one Mac's dense-Qwen solo stripe, +/// `EngineV2Factory.defaultDenseQwenSoloPrefillStripeTokens`: the first, +/// fork-target and stripe-end checkpoints one Mac can keep), so a prompt +/// sharing only a long system prompt finds one. Past the first, the stripe +/// doubles until at most `maximumStripeBoundaries` remain, the SSD +/// record's grid (`QwenStagePrefixDiskTier.maximumGridFrontiers`), so they +/// are also written to the record and a capture keeps at most eleven +/// recurrent states. +/// +/// A capture copies the attention rows once, at its deepest kept boundary, +/// and the recurrent state at each kept boundary +/// (`QwenTensorParallelPrefixCapture`). Each request is charged its own +/// capture (`captureBytes(promptCount:chunkSize:)`); LOAD and the planner +/// charge one capture of the profile's longest prompt per lane. The memory +/// tier that keeps captures after their requests is charged nowhere: its +/// budget is half the room LOAD measures beside that charge +/// (`QwenStagePrefixCache.budget(roomBytes:)`), and its entries give way +/// before a reservation or a running batch is refused for memory. +/// +/// The geometry prices what it is given: a rank's own heads at LOAD, the +/// full unsliced model (either rank, any shares) in the planner. struct QwenTensorParallelBatchPrefixBudget { - static let maximumTokens = 4096 - static let policy = "qwen-tp-batch-grid-prefix-4096-v1" + static let policy = "qwen-tp-batch-prefix-depth-v2" + static let stripeTokens = 4096 + static let promptEndMarginTokens = 64 + static let marginFloorTokens = 1024 + static let maximumStripeBoundaries = 8 + + /// The context LOAD derived `captureBytes` at (the memory plan's). It + /// does not bound a request, whose boundaries go to its own context. let maximumTokens: Int + /// The per-lane LOAD term: one capture of the profile's longest prompt. let captureBytes: Int - let residentBytes: Int + /// What a request's own capture is priced on; nil keeps `captureBytes` + /// for every request (fixtures). + let geometry: QwenLongPrefillBudgetGeometry? + + init(maximumTokens: Int, captureBytes: Int, geometry: QwenLongPrefillBudgetGeometry? = nil) { + self.maximumTokens = maximumTokens; self.captureBytes = captureBytes; self.geometry = geometry + } - static func derive(geometry g: QwenLongPrefillBudgetGeometry, maximumTokens: Int, - allocationBound: (Int) throws -> Int) throws -> Self { - guard maximumTokens > 0 else { throw ProbeError("Invalid TP prefix context") } - let tokens = min(Self.maximumTokens, maximumTokens) - let b = try QwenLongPrefillTensorBudget.estimate(geometry: g, maximumTokens: tokens, chunkSize: 1) + /// The boundaries a request of `promptCount` tokens keeps, ascending. + static func frontiers(promptCount: Int, chunkSize: Int, restored: Int = 0, + maximumTokens: Int = .max) -> [Int] { + guard chunkSize > 0, promptCount > 1 else { return [] } + let limit = min(promptCount - 1, maximumTokens) + let deepest = limit / chunkSize * chunkSize + guard deepest > restored, deepest > 0 else { return [] } + var kept: Set = [deepest] + let margin = (promptCount - 1 - promptEndMarginTokens) / chunkSize * chunkSize + if margin >= marginFloorTokens, margin > restored, margin < deepest { kept.insert(margin) } + let first = (stripeTokens + chunkSize - 1) / chunkSize * chunkSize + if first > restored, first < deepest { kept.insert(first) } + var stripe = first + while (deepest - 1) / stripe > maximumStripeBoundaries { stripe *= 2 } + for boundary in Swift.stride(from: stripe, to: deepest, by: stripe) where boundary > restored { + kept.insert(boundary) + } + return kept.sorted() + } + + /// The recurrent states a capture whose deepest boundary is `deepest` + /// is charged: the deepest, a margin boundary whenever one can exist, and + /// every stripe boundary below it, at most `maximumStripeBoundaries + 1`. + /// At least what any prompt with that deepest boundary keeps, and never + /// fewer for a deeper one, so the charge grows with the prompt. + static func pricedStates(deepest: Int, chunkSize: Int) -> Int { + guard deepest > 0, chunkSize > 0 else { return 0 } + let first = (stripeTokens + chunkSize - 1) / chunkSize * chunkSize + let margin = (deepest - promptEndMarginTokens) / chunkSize * chunkSize >= marginFloorTokens ? 1 : 0 + return 1 + margin + min((deepest - 1) / first, maximumStripeBoundaries + 1) + } + + /// One capture of a prompt of `promptCount` tokens at the allocator's + /// bound: every attention layer's keys and values to its deepest kept + /// boundary, and every recurrent layer's convolution and SSM state for + /// `pricedStates`; 0 when it keeps none. + static func captureBytes(geometry g: QwenLongPrefillBudgetGeometry, promptCount: Int, chunkSize: Int, + maximumTokens: Int = .max, allocationBound: (Int) throws -> Int) throws -> Int { + guard let deepest = frontiers(promptCount: promptCount, chunkSize: chunkSize, maximumTokens: maximumTokens).last else { + return 0 + } + let states = pricedStates(deepest: deepest, chunkSize: chunkSize) let product = QwenLongPrefillCheckedBytes.product, sum = QwenLongPrefillCheckedBytes.sum + let b = try QwenLongPrefillTensorBudget.estimate(geometry: g, maximumTokens: 1, chunkSize: 1) func bound(_ bytes: Int, count: Int) throws -> Int { guard count > 0 else { return 0 } let allocated = try allocationBound(bytes) guard bytes > 0, allocated >= bytes else { throw ProbeError("Invalid TP prefix allocation bound") } return try product([allocated, count]) } - let capture = try sum([ - bound(b.convolutionBytesPerLayer, count: g.recurrentLayers), - bound(b.ssmBytesPerLayer, count: g.recurrentLayers), - bound(product([tokens, g.kvHeads, g.headDimension, 2]), count: 2 * g.attentionLayers), + return try sum([ + bound(product([deepest, g.kvHeads, g.headDimension, 2]), count: 2 * g.attentionLayers), + bound(b.convolutionBytesPerLayer, count: states * g.recurrentLayers), + bound(b.ssmBytesPerLayer, count: states * g.recurrentLayers), ]) - return try .init(maximumTokens: tokens, captureBytes: capture, residentBytes: product([capture, 2])) + } + + /// This request's own capture, as its reservation charged it + /// (`QwenTensorParallelRequestCharge`): priced on `geometry`, else `captureBytes`. + func captureBytes(promptCount: Int, chunkSize: Int, allocationBound: (Int) throws -> Int) throws -> Int { + guard let geometry else { return captureBytes } + return try Self.captureBytes(geometry: geometry, promptCount: promptCount, chunkSize: chunkSize, + allocationBound: allocationBound) + } + + /// LOAD's per-lane term: one capture of a `promptTokens` prompt (the + /// profile's longest; nil: the longest a `maximumTokens` request holds). + static func derive(geometry g: QwenLongPrefillBudgetGeometry, maximumTokens: Int, promptTokens: Int? = nil, + chunkSize: Int, allocationBound: (Int) throws -> Int) throws -> Self { + guard maximumTokens > 0, chunkSize > 0 else { throw ProbeError("Invalid TP prefix context") } + let prompt = min(promptTokens ?? maximumTokens - 1, maximumTokens - 1) + let capture = try captureBytes(geometry: g, promptCount: prompt, chunkSize: chunkSize, + allocationBound: allocationBound) + return .init(maximumTokens: maximumTokens, captureBytes: capture, geometry: g) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift index 72dbcb7ea8..7b762ec90a 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift @@ -14,12 +14,22 @@ protocol QwenTensorParallelBatchLane: AnyObject { var reusedPrefixTokens: Int { get } var storedPrefixFrontiers: [Int] { get } var canSelectNext: Bool { get } + /// The lane's decode selects through the plain selection sum (no + /// assistant round or accepted queue), which can carry control words. + var plainSelection: Bool { get } + func promptStep(frames: Int) -> QwenLayerStageFrame? + func promptStep(tokens: Int) -> QwenLayerStageFrame? } extension QwenTensorParallelBatchLane { var reusedPrefixTokens: Int { 0 } var storedPrefixFrontiers: [Int] { [] } var canSelectNext: Bool { nextFrame?.phase == .decode } + var plainSelection: Bool { true } + /// The prompt step of up to `frames` consecutive frames (`QwenTensorParallelPromptWavefront`). + func promptStep(frames: Int) -> QwenLayerStageFrame? { nextFrame } + /// The planned prompt step of `tokens`, if it is one this lane may run. + func promptStep(tokens: Int) -> QwenLayerStageFrame? { nextFrame.flatMap { $0.tokenCount == tokens ? $0 : nil } } } /// Both ranks run every forward. Selection returns the same token to both; @@ -32,20 +42,47 @@ protocol QwenTensorParallelBatchExecutor: AnyObject { func discard(_ reservation: Reservation) throws func open(_ reservation: Reservation, check: () throws -> Void) throws -> Lane func prefill(_ lane: Lane, frame: QwenLayerStageFrame, check: () throws -> Void) throws -> Int? + /// Whether this executor's selection sum can carry control words; the + /// driver folds only for one that can. + var carriesSelectionControl: Bool { get } + /// One decode rectangle whose selection sum carries no control words. func decode(_ lanes: [Lane], tokens: [Int], check: () throws -> Void) throws -> [Int] + /// One decode rectangle. `control` runs once the forward committed and + /// before selection; words it returns (plain lanes only) ride the + /// selection's sealed sum, and both ranks' summed words come back. + func decode(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?, + check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) func retire(_ lane: Lane, reason: QwenLayerStageGenerationFinishReason?, selected: Int, last: Int?) throws func takeLogprobs(_ lane: Lane) throws -> ClusterWorkerTokenLogprobs? func confirmedRetirement(_ lane: Lane, clean: Bool) throws } extension QwenTensorParallelBatchExecutor { + var carriesSelectionControl: Bool { false } func confirmedRetirement(_ lane: Lane, clean: Bool) throws {} + + /// An executor whose selection sum carries no control words: the driver + /// never folds for it, so `control` is always empty. + func decode(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?, + check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) { + let selected = try decode(lanes, tokens: tokens, check: check) + guard try control() == nil else { throw ProbeError("This TP executor's selection sum carries no control words") } + return (selected, nil) + } } -/// One prefill frame on its original grid and one real decode rectangle per +/// One prompt step (consecutive frames on the original grid) and one real decode rectangle per /// step. Every active request owns its native history. A slow client holds /// only its own token credit. Successful retirement is published only after /// both ranks have drained, including cancellation and deadline departures. +/// +/// A step whose decode rectangle is plain and runs no prompt folds the next +/// step's plan and report into its selection sum: one sealed sum and one host +/// read a step. That plan is made before the step's tokens are known, so +/// host events (answers, credits, cancellations, joins) apply one step later, +/// and both ranks drop a carried decode whose token ended its request (EOS or +/// length). Rank 0 publishes a token only once the owner answered the one +/// before it; a token selected before a stop answer is never published. final class QwenTensorParallelBatchDriver { typealias Reservation = Executor.Reservation private final class Record { @@ -53,17 +90,25 @@ final class QwenTensorParallelBatchDriver QwenLayerStageGenerationFinishReason? { - guard let last = tokens.last else { return nil } - if reservation.request.stopTokenIDs.contains(last) { return .eos } - if tokens.count == reservation.request.outputCount { return .length } + /// How the request ends at its first `count` tokens, given the owner's answer to the last. + func finish(_ proceed: Bool, count: Int) -> QwenLayerStageGenerationFinishReason? { + guard count >= 1, count <= tokens.count else { return nil } + if reservation.request.stopTokenIDs.contains(tokens[count - 1]) { return .eos } + if count == reservation.request.outputCount { return .length } return proceed ? nil : .clientStop } + /// Its last token ends the request: no further forward. + var ended: Bool { finish(true, count: tokens.count) != nil } } private let executor: Executor private let book: ClusterBatchLaneBook @@ -72,14 +117,17 @@ final class QwenTensorParallelBatchDriver, capacity: Int, vocabulary: Int, - joinWaitNanoseconds: UInt64 = 30_000_000_000, + joinWaitNanoseconds: UInt64 = 30_000_000_000, foldsControl: Bool = true, now: @escaping () -> UInt64 = { DispatchTime.now().uptimeNanoseconds }) throws { guard (0...1).contains(executor.rank), (1...8).contains(capacity), vocabulary > 0, joinWaitNanoseconds > 0 else { throw ProbeError("Qwen TP batch driver has invalid geometry") } self.executor = executor; self.book = book; self.capacity = capacity; self.vocabulary = vocabulary - self.joinWaitNanoseconds = joinWaitNanoseconds; self.now = now + self.joinWaitNanoseconds = joinWaitNanoseconds; self.foldsControl = foldsControl; self.now = now } private func cancelled(_ record: Record) -> Bool { @@ -95,27 +143,37 @@ final class QwenTensorParallelBatchDriver() + /// This step's plan and report, when they rode the last step's selection sum. + var carried: (plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply)? do { while true { let stop = try autoreleasepool { () throws -> Bool in - let answers = executor.rank == 0 ? try decisions.serviceAndPoll(host) : [:] - if executor.rank == 1 { try host.serviceControl() } - try check() - let localPlan = executor.rank == 0 - ? makePlan(step: step, answers: answers, decisions: decisions, peerCancelled: peerCancelled, - coalescing: &coalescing) : nil - let localReport = executor.rank == 1 ? report(step: step) : nil - let sum = try executor.exchange(QwenTensorParallelBatchWire.contribution( - rank: executor.rank, plan: localPlan, report: localReport), check: check) - let (plan, peer) = try QwenTensorParallelBatchWire.read(sum, step: step, lanes: capacity) - if let localPlan, plan != localPlan { throw ProbeError("Qwen TP leader plan changed in transit") } - if let localReport, peer != localReport { throw ProbeError("Qwen TP follower report changed in transit") } + let plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply + let wasCarried = carried != nil + if let folded = carried { + (plan, peer) = folded; carried = nil + if executor.rank == 1 { try host.serviceControl() } + try check() + } else { + let answers = executor.rank == 0 ? try decisions.serviceAndPoll(host) : [:] + if executor.rank == 1 { try host.serviceControl() } + try check() + let localPlan = executor.rank == 0 + ? try makePlan(step: step, answers: answers, decisions: &decisions, host: host, + peerCancelled: peerCancelled, coalescing: &coalescing) : nil + let localReport = executor.rank == 1 ? report(step: step) : nil + let sum = try executor.exchange(QwenTensorParallelBatchWire.contribution( + rank: executor.rank, plan: localPlan, report: localReport), check: check) + (plan, peer) = try Self.read(sum, step: step, lanes: capacity, plan: localPlan, report: localReport) + } try validate(plan, peer: peer) peerCancelled = Set((0.. Record in guard let record = records[slot], let native = record.native, @@ -124,25 +182,52 @@ final class QwenTensorParallelBatchDriver [Float]? in + guard folds else { return nil } + if executor.rank == 0 { + let answers = try decisions.serviceAndPoll(host) + try check() + nextPlan = try makePlan(step: step + 1, answers: answers, decisions: &decisions, host: host, + peerCancelled: peerCancelled, coalescing: &coalescing, carrying: carrying) + } else { + try host.serviceControl(); try check() + nextReport = report(step: step + 1, carrying: carrying) + } + return try QwenTensorParallelBatchWire.contribution(rank: executor.rank, plan: nextPlan, report: nextReport) + }, check: { try check(); try host.serviceControl() }) + guard result.tokens.count == lanes.count, (result.control != nil) == folds else { + throw ProbeError("Qwen TP decode omitted a lane or its control words") + } + for (lane, token) in zip(lanes, result.tokens) { + try selected(token, lane: lane, decisions: &decisions, host: host, peerCancelled: peerCancelled) + } + if let words = result.control { + let (next, nextPeer) = try Self.read(words, step: step + 1, lanes: capacity, plan: nextPlan, report: nextReport) + carried = (try resolve(next, carrying: carrying), nextPeer) + } } - let prompts = plan.slots.indices.filter { plan.slots[$0].role == .prefill } - guard prompts.count <= 1 else { throw ProbeError("Qwen TP plan has multiple prefill frames") } if let slot = prompts.first { let value = plan.slots[slot] - guard let lane = records[slot], let native = lane.native, let frame = native.nextFrame, + guard let lane = records[slot], let native = lane.native, let frame = native.promptStep(tokens: value.frameCount), frame.phase == .prefill, frame.tokenOffset == value.frameOffset, frame.tokenCount == value.frameCount, frame.finalPromptChunk == value.finalChunk else { throw ProbeError("Qwen TP prefill differs from its original chunk grid") } let token = try executor.prefill(native, frame: frame, check: { try check(); try host.serviceControl() }) guard (token != nil) == frame.finalPromptChunk else { throw ProbeError("Qwen TP prefill returned the wrong final-row kind") } - if let token { try selected(token, lane: lane, decisions: &decisions, host: host, publish: !peerCancelled.contains(lane.slot)) } + if let token { try selected(token, lane: lane, decisions: &decisions, host: host, peerCancelled: peerCancelled) } } - if decode.isEmpty && prompts.isEmpty && plan.slots.allSatisfy({ $0.state == .active || $0.state == .empty }) { + // A carried plan whose decodes ended is idle only by the tokens just read; + // the next step exchanges at once. + if !wasCarried, decode.isEmpty, prompts.isEmpty, + plan.slots.allSatisfy({ $0.state == .active || $0.state == .empty }) { Thread.sleep(forTimeInterval: 0.0005) } return false @@ -158,19 +243,35 @@ final class QwenTensorParallelBatchDriver, coalescing: inout QwenBatchDecodeCoalescing) -> QwenBatchWire.Header { + /// Rank 0's plan for `step`. `carrying`: rows decoding in the step whose + /// selection sum carries this plan. Each counts the token it is selecting + /// and decodes on it (`carriedToken`) only if the owner already answered + /// the token before it; a stop keeps the tokens the owner saw. + private func makePlan(step: Int, answers: [UUID: Bool], decisions: inout QwenBatchDecisionProgress, + host: QwenBatchServingHost, peerCancelled: Set, + coalescing: inout QwenBatchDecodeCoalescing, carrying: Set = []) throws -> QwenBatchWire.Header { var slots = [QwenBatchWire.Slot](repeating: .init(), count: capacity) for (slot, record) in records { + let selecting = carrying.contains(slot) var value = QwenBatchWire.Slot(state: .active, requestID: record.id) value.committedTokens = record.native?.committedTokens ?? 0 - value.selectedTokens = record.tokens.count; value.fingerprintWords = record.fingerprint - let reason = answers[record.id].flatMap { record.finish($0) } + value.selectedTokens = record.tokens.count + (selecting ? 1 : 0); value.fingerprintWords = record.fingerprint + // An answer is to the last published token. + let reason = answers[record.id].flatMap { record.finish($0, count: record.published) } if cancelled(record) || peerCancelled.contains(slot) || reason != nil { value.state = .leaving; value.leaveCancelled = cancelled(record) || peerCancelled.contains(slot) value.leaveReason = value.leaveCancelled ? nil : reason - } else if record.native?.canSelectNext == true, decisions.canForward(record.id) { - value.role = .decode; value.inputToken = record.tokens.last ?? -1 + if !value.leaveCancelled { value.selectedTokens = record.published } + record.leaving = true + } else { + if answers[record.id] == true { + try publishHeld(record, decisions: &decisions, host: host, peerCancelled: peerCancelled) + } + if record.native?.canSelectNext == true, record.published == record.tokens.count, + decisions.canForward(record.id) { + value.role = .decode + value.inputToken = selecting ? QwenTensorParallelBatchWire.carriedToken : record.tokens.last ?? -1 + } } slots[slot] = value } @@ -182,7 +283,9 @@ final class QwenTensorParallelBatchDriver QwenBatchWire.Reply { + private func report(step: Int, carrying: Set = []) -> QwenBatchWire.Reply { let mask = records.values.reduce(0) { $0 | (cancelled($1) ? 1 << $1.slot : 0) } - return .init(step: step, tokens: (0.. (QwenBatchWire.Header, QwenBatchWire.Reply) { + let (received, peer) = try QwenTensorParallelBatchWire.read(sum, step: step, lanes: lanes) + if let plan, received != plan { throw ProbeError("Qwen TP leader plan changed in transit") } + if let report, peer != report { throw ProbeError("Qwen TP follower report changed in transit") } + return (received, peer) + } + + /// A carried plan was made before the tokens of the step that carried it. + /// A row that decodes on its new token takes it, unless that token ended + /// its request (a stop token or its output count): both ranks read it in + /// the same sum and drop that decode alike. + private func resolve(_ plan: QwenBatchWire.Header, carrying: Set) throws -> QwenBatchWire.Header { + var plan = plan + for slot in plan.slots.indices where plan.slots[slot].inputToken == QwenTensorParallelBatchWire.carriedToken { + guard plan.slots[slot].role == .decode, carrying.contains(slot), let record = records[slot], + let token = record.tokens.last else { + throw ProbeError("Qwen TP carried decode has no carrying row") + } + if record.ended { plan.slots[slot].role = .none; plan.slots[slot].inputToken = -1 } + else { plan.slots[slot].inputToken = token } + } + return plan } private func validate(_ plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply) throws { @@ -221,8 +352,12 @@ final class QwenTensorParallelBatchDriver) throws { guard (0..) throws { + guard lane.published == lane.tokens.count - 1, !lane.leaving, decisions.canForward(lane.id), + !peerCancelled.contains(lane.slot), !cancelled(lane) else { return } + try decisions.published(lane.id) + try host.publishToken(requestID: lane.id, ordinal: lane.published, tokenID: lane.tokens[lane.published], + committedTokens: lane.reservation.request.promptCount + lane.published, logprobs: lane.heldLogprobs) + lane.published += 1; lane.heldLogprobs = nil } private func leave(_ plan: QwenBatchWire.Header, host: QwenBatchServingHost, @@ -285,8 +430,10 @@ final class QwenTensorParallelBatchDriver +/// Retention is by byte budget, as the pipeline's `QwenStagePrefixCache`: +/// the owner sets it from the room it measures (`setBudget`), and a zero +/// budget keeps nothing resident while votes still count SSD records. One +/// capture's boundaries form a group: their shared attention copy is +/// counted once and freed with the group's last entry. Under the budget the +/// shallower boundaries of other captures go first (least recently used +/// first), then the newest capture's, then whole captures, so an exact +/// repeat's deepest boundary outlives every other. `yieldingMemory` frees +/// entries before a live memory gate refuses. final class QwenTensorParallelSnapshotCache { - static var maximumEntries: Int { 32 } + /// Entries and captures kept at most (the pipeline's limits); bytes bound first. + static var maximumEntries: Int { 1024 } + static var maximumGroups: Int { 64 } + /// Boundaries one vote carries at most (the deepest ones before the final token). + static var maximumVoted: Int { 512 } let enabled: Bool - let budgetBytes: Int - private struct Entry { let state: Snapshot; var lastUse: UInt64 } + private(set) var budgetBytes: Int + private struct Entry { let state: Snapshot; var lastUse: UInt64; let group: UInt64 } + private struct Group { let sharedBytes: Int; var entries: Int; let deepest: Int } private var entries: [String: Entry] = [:] + private var groups: [UInt64: Group] = [:] + private var nextGroup: UInt64 = 0 private var clock: UInt64 = 0 private(set) var bytesInUse = 0 + private(set) var evictions = 0 init(enabled: Bool, budgetBytes: Int) { - self.enabled = enabled && budgetBytes > 0; self.budgetBytes = max(0, budgetBytes) + self.enabled = enabled; self.budgetBytes = max(0, budgetBytes) } + /// Every boundary on the request's chunk grid before its final token, at + /// most `maximumTokens` deep (the deepest `maximumVoted` of them). static func candidates(promptCount: Int, chunkSize: Int, maximumTokens: Int) -> [Int] { guard promptCount > 1, chunkSize > 0, maximumTokens > 0 else { return [] } let last = min(promptCount - 1, maximumTokens) / chunkSize * chunkSize guard last > 0 else { return [] } - return Array(stride(from: chunkSize, through: last, by: chunkSize).suffix(maximumEntries)) + return Array(stride(from: chunkSize, through: last, by: chunkSize).suffix(maximumVoted)) } static func keys(scope: String, tokens: [Int], frontiers: [Int]) -> [Int: String] { QwenStagePrefixKeys.keys(scope: scope, tokens: tokens, frontiers: Set(frontiers)) @@ -61,16 +82,119 @@ final class QwenTensorParallelSnapshotCache Bool { - guard enabled, state.allocatedBytes > 0, state.allocatedBytes <= budgetBytes else { return false } - if let old = entries.removeValue(forKey: key) { bytesInUse -= old.state.allocatedBytes } - while entries.count >= Self.maximumEntries || bytesInUse > budgetBytes - state.allocatedBytes { - guard let key = entries.min(by: { $0.value.lastUse < $1.value.lastUse })?.key, - let old = entries.removeValue(forKey: key) else { break } - bytesInUse -= old.state.allocatedBytes + !insert([(key, state)], sharedBytes: 0).isEmpty + } + + /// One capture's states, viewing `sharedBytes` together. Returns the + /// boundaries kept: those that fit the budget with the deepest (none + /// when the deepest does not fit). + @discardableResult func insert(_ states: [(key: String, state: Snapshot)], sharedBytes: Int) -> [Int] { + let sorted = states.sorted { $0.state.committedTokens < $1.state.committedTokens } + // An attention-only state holds nothing of its own beside the shared copy. + guard enabled, let deepest = sorted.last, sharedBytes >= 0, sharedBytes + deepest.state.allocatedBytes > 0 else { return [] } + var total = sharedBytes + deepest.state.allocatedBytes + guard total <= budgetBytes else { return [] } + var chosen = [deepest] + for entry in sorted.dropLast().reversed() where total + entry.state.allocatedBytes <= budgetBytes { + total += entry.state.allocatedBytes; chosen.append(entry) } - clock &+= 1; entries[key] = .init(state: state, lastUse: clock); bytesInUse += state.allocatedBytes + for entry in chosen { if let old = entries[entry.key] { remove(entry.key, old) } } + let group = nextGroup; nextGroup &+= 1 + evict(reserving: total, adding: chosen.count) + for entry in chosen.reversed() { + clock &+= 1 + entries[entry.key] = .init(state: entry.state, lastUse: clock, group: group) + bytesInUse += entry.state.allocatedBytes + } + groups[group] = .init(sharedBytes: sharedBytes, entries: chosen.count, deepest: deepest.state.committedTokens) + bytesInUse += sharedBytes + return chosen.map(\.state.committedTokens).sorted() + } + + /// The owner's measured budget; entries beyond it go now. + func setBudget(_ bytes: Int) { budgetBytes = max(0, bytes); evict(reserving: 0, adding: 0) } + + /// Drops the next entry `victim` names; false when there is none. + @discardableResult func evictLeastRecentlyUsed() -> Bool { + guard let (key, entry) = victim() else { return false } + remove(key, entry); evictions += 1 return true } - func sweep() { entries.removeAll(); bytesInUse = 0 } + + /// Runs `check` (a live memory gate); while it refuses, first lets the + /// SSD writer finish what it holds, then drops entries one at a time and + /// returns their buffers. Only a refusal with nothing left to free throws. + func yieldingMemory(disk: QwenStagePrefixDiskTier?, _ check: () throws -> Void) throws { + var drained = disk == nil, evicted = 0 + while true { + do { + try check() + if evicted > 0 { log("darkbloom-prefix-v1 family=qwen mode=tensor_parallel pressure-evicted=\(evicted) entries=\(entries.count) admitted=true") } + return + } catch { + if !drained, let disk { + drained = true + _ = disk.drain(timeoutSeconds: 10) + } else if enabled, evictLeastRecentlyUsed() { + evicted += 1 + } else { + if evicted > 0 { log("darkbloom-prefix-v1 family=qwen mode=tensor_parallel pressure-evicted=\(evicted) entries=\(entries.count) admitted=false") } + throw error + } + Stream.gpu.synchronize() + Memory.clearCache() + } + } + } + + func sweep() { entries.removeAll(); groups.removeAll(); bytesInUse = 0 } + + /// Boundaries held now (tests and diagnostics). + var heldFrontiers: [Int] { entries.values.map(\.state.committedTokens).sorted() } + + private func remove(_ key: String, _ entry: Entry) { + entries.removeValue(forKey: key) + bytesInUse -= entry.state.allocatedBytes + guard var group = groups[entry.group] else { return } + group.entries -= 1 + if group.entries <= 0 { groups.removeValue(forKey: entry.group); bytesInUse -= group.sharedBytes } + else { groups[entry.group] = group } + } + + private func evict(reserving: Int, adding: Int) { + // Over the capture count: the least recently used capture goes whole + // (thinning other captures would not lower the count). + while groups.count + (adding > 0 ? 1 : 0) > Self.maximumGroups, let group = leastRecentlyUsedGroup() { + for (key, entry) in entries where entry.group == group { remove(key, entry); evictions += 1 } + } + while entries.count + adding > Self.maximumEntries + || (bytesInUse > 0 && bytesInUse > budgetBytes - min(budgetBytes, reserving)), + let (key, entry) = victim() { + remove(key, entry); evictions += 1 + } + } + + private func leastRecentlyUsedGroup() -> UInt64? { + var latest: [UInt64: UInt64] = [:] + for entry in entries.values { latest[entry.group] = max(latest[entry.group] ?? 0, entry.lastUse) } + return latest.min(by: { ($0.value, $0.key) < ($1.value, $1.key) })?.key + } + + /// The least recently used shallower boundary of a capture other than the + /// newest, then the newest capture's shallowest, then the least recently + /// used entry (a whole capture's deepest boundary). + private func victim() -> (String, Entry)? { + guard let newest = entries.values.max(by: { $0.lastUse < $1.lastUse })?.group else { return nil } + func shallow(_ entry: Entry) -> Bool { entry.state.committedTokens < (groups[entry.group]?.deepest ?? 0) } + let order: ((key: String, value: Entry), (key: String, value: Entry)) -> Bool = { + ($0.value.lastUse, $0.value.state.committedTokens) < ($1.value.lastUse, $1.value.state.committedTokens) + } + if let other = entries.filter({ $0.value.group != newest && shallow($0.value) }).min(by: order) { return (other.key, other.value) } + if let own = entries.filter({ $0.value.group == newest && shallow($0.value) }) + .min(by: { $0.value.state.committedTokens < $1.value.state.committedTokens }) { return (own.key, own.value) } + return entries.min(by: order).map { ($0.key, $0.value) } + } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift index 5ff7bb411d..dbd95206ef 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift @@ -3,6 +3,7 @@ import Foundation import MLX import MLXLLM import MLXLMCommon +import MLXNN /// Input ownership is request-local. A media owner supplies its authenticated /// position slices and prompt embeddings; text keeps the cache's own offsets. @@ -23,10 +24,7 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { private var inputs: QwenTensorParallelBatchInputs? private var window: QwenTensorParallelTargetWindow? private var failed = false - private let captureFrontier: Int - private let captureLimitBytes: Int - private let allocationBound: (Int) throws -> Int - private var captured: QwenTensorParallelBatchPrefixState? + private let prefixCapture: QwenTensorParallelPrefixCapture? /// `frameTiming` only: this prompt's frames so far. private var promptClock: QwenTensorParallelPromptClock? private(set) var schedule: QwenLayerStageGenerationSchedule @@ -35,24 +33,20 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { init(model: QwenTensorParallelModel, configuration: Data, host: CBv2StageKVHost, request: QwenLayerStageGenerationRequest, inputs: QwenTensorParallelBatchInputs? = nil, - restored: QwenTensorParallelBatchPrefixState? = nil, captureFrontier: Int = 0, - captureLimitBytes: Int = 0, allocationBound: ((Int) throws -> Int)? = nil) throws { + restored: QwenTensorParallelBatchPrefixState? = nil, capture: QwenTensorParallelPrefixCapture? = nil) throws { guard case .shard(_, let ranks) = model.role, ranks == 2, sha256(configuration) == model.configurationSHA256, request.profile.hiddenSize == model.plan.hiddenSize, request.profile.vocabularySize == model.plan.vocabularySize, request.reusedPrefixTokens == (restored?.committedTokens ?? 0), request.reusedPrefixTokens % request.chunkSize == 0, - captureFrontier == 0 || (captureFrontier > request.reusedPrefixTokens - && captureFrontier < request.promptCount && captureFrontier % request.chunkSize == 0), - captureLimitBytes >= 0, captureFrontier == 0 || allocationBound != nil else { + capture?.fits(request) ?? true else { throw ProbeError("Qwen TP batch session requires a matching shard and original-grid state") } let geometry = try Self.geometry(model: model, configuration: configuration, host: host, maximumTokens: request.maximumTokens) self.model = model; self.request = request; self.inputs = inputs - self.captureFrontier = captureFrontier; self.captureLimitBytes = captureLimitBytes - self.allocationBound = allocationBound ?? { _ in throw ProbeError("Unpriced TP prefix capture") } + self.prefixCapture = capture // Paged pages grow with the request (`reservePages`); the reference // contiguous backend keeps its whole-length rows. let reserved = host.kind == .paged ? Self.initialReservedTokens(request) : nil @@ -111,6 +105,26 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { try prompt(capturingHidden: false, check: check).logits } + /// The prompt frames one step runs from the next frame: up to `limit` + /// merged into one graph (`QwenTensorParallelPromptWavefront`), ending at + /// the capture frontier; the next frame alone where frames do not merge. + func promptFrames(limit: Int) -> [QwenLayerStageFrame] { + guard !retired else { return [] } + let merges = QwenTensorParallelPromptWavefront.merges(model: model, request: request, + mediaInputs: inputs != nil, packedStorage: state.packedStorage) + return QwenTensorParallelPromptWavefront.frames(request: request, from: schedule.nextSequence, + frontiers: prefixCapture?.frontiers ?? [], limit: merges ? limit : 1) + } + + /// Runs the planned prompt step `step` (`promptFrames`), its frames as one graph. + func prefill(step: QwenLayerStageFrame, check: () throws -> Void) throws -> MLXArray? { + let frames = promptFrames(limit: QwenTensorParallelPromptWavefront.maximumFrames) + guard let count = (1...max(1, frames.count)).first(where: { + QwenTensorParallelPromptWavefront.step(Array(frames.prefix($0))) == step + }) else { throw ProbeError("Qwen TP prompt step differs from its frames") } + return try prompt(capturingHidden: false, frames: count, check: check).logits + } + func prefillForMTP(check: () throws -> Void) throws -> QwenTensorParallelMTPPromptResult { guard inputs == nil, request.qwenMedia == nil else { throw ProbeError("Qwen TP media cannot enter assistant history") } let result = try prompt(capturingHidden: true, check: check) @@ -118,13 +132,20 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { return .init(hidden: hidden, logits: result.logits) } - private func prompt(capturingHidden: Bool, check: () throws -> Void) throws -> (hidden: MLXArray?, logits: MLXArray?) { + private func prompt(capturingHidden: Bool, frames count: Int = 1, + check: () throws -> Void) throws -> (hidden: MLXArray?, logits: MLXArray?) { try MLX.withError { error in func checked() throws { try error.check(); try check() } - let proposed = try request.frame(sequence: schedule.nextSequence) - let frame = try schedule.admitPrefill(count: proposed.tokenCount, offset: proposed.tokenOffset, - final: proposed.finalPromptChunk) - guard !retired, !failed, window?.isIdle ?? true, frame.phase == .prefill, state.committedTokens == frame.tokenOffset else { + // Each frame is admitted on the schedule as the frames before it leave it. + var planned = schedule, frames: [QwenLayerStageFrame] = [] + for _ in 0.. MLXArray in + if frames.count > 1 { + return QwenTensorParallelPromptWavefront.forward(model: self.model, request: self.request, + frames: frames, caches: caches, evaluation: evaluation) + } + return Qwen35LayerSubmission.$stride.withValue(stride) { () -> MLXArray in let native = self.model.model if capturingHidden { let result = native.cbv2ForwardWithHidden(input, @@ -193,8 +218,8 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { } eval(hidden); try checked() } - try schedule.commit(frame) - if committedTokens == captureFrontier { try capturePrefix(check: checked) } + schedule = planned + try prefixCapture?.capture(state, at: committedTokens, check: checked) if let timing, case .shard(let rank, _) = model.role { let clock = promptClock ?? QwenTensorParallelPromptClock() promptClock = clock @@ -260,12 +285,14 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { static var usesExactVectors: Bool { exactVectorsOverride ?? exactVectors } /// Bound into the tensor-parallel load agreement: both ranks resolve the - /// decode projections alike, or the pair refuses to load (never a mixed - /// configuration). Each rank's words per lane is its own arithmetic - /// (a rank sums only its own partials) and is not bound. + /// decode projections alike and sum the same selection words (each row's + /// non-finite counts ride the greedy sum), or the pair refuses to load + /// (never a mixed configuration). Each rank's words per lane is its own + /// arithmetic (a rank sums only its own partials) and is not bound. static var decodeAgreementFields: [String] { ["qwen-tensor-parallel-decode-projections-v1", usesExactVectors ? "batch-invariant-affine" : "mlx-kernels", - "qwen-tensor-parallel-fenced-sums-v1", sumsAreFencedInputs ? "on" : "off"] + "qwen-tensor-parallel-fenced-sums-v1", sumsAreFencedInputs ? "on" : "off", + "qwen-tensor-parallel-selection-nonfinite-in-sum-v1"] } /// Whether the residual step's kernel waits for each all-sum itself: MLX @@ -291,6 +318,93 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { + " fenced_sums=\(sumsAreFencedInputs ? "on" : "off")" } + /// Vector counts the census describes: plain rows of one to eight, and + /// their four-column verify windows. + static let censusCounts = [1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 28, 32] + + /// The decode route of every projection of a loaded shard + /// (`darkbloom-qwen-tp-decode-census-v1`), so a pair's log shows what each + /// row count runs: the batch-invariant kernel (`aqv`), a row-parallel FP32 + /// partial on it (`partial`), or MLX's own kernels and why (`mlx-...`), + /// with each shape's layout per vector count (layouts never change a + /// result), and the attention, residual-norm and selection routes. Host + /// only: no array is evaluated. Layouts are per checkpoint projection: + /// the SDK multiplies a Gated DeltaNet layer's four input projections as + /// one call of their summed rows, and fuses gate, up and SwiGLU at + /// `swiglu_fused_vectors` only while its decode fusions are on. + static func censusLine(rank: Int, model: QwenTensorParallelModel) -> String { + var routes: [String: Int] = [:], layouts: [String: String] = [:], tally: [String: Int] = [:] + for (path, module) in model.model.leafModules().flattened() { + guard let linear = module as? Linear else { continue } + let name = path.split(separator: ".").last.map(String.init) ?? path + let (outputs, inputs) = linear.shape + let route: String + if let packed = linear as? QuantizedLinear { + let probe = MLXArray.zeros([1, inputs], dtype: .bfloat16) + let reason: String? + if !usesExactVectors { reason = "off" } + else if Device.defaultDevice().deviceType != .gpu { reason = "cpu" } + else if AffineQuantizedVectors.supports(input: probe, weight: packed.weight, scales: packed.scales, + biases: packed.biases, groupSize: packed.groupSize, bits: packed.bits, mode: packed.mode) { reason = nil } + else if packed.mode != .affine { reason = "mode" } + else if packed.biases == nil { reason = "biases" } + else { reason = "bits\(packed.bits)-group\(packed.groupSize)-\(packed.scales.dtype)" } + if packed is QwenTensorParallelRowLinear { + route = reason.map { "mlx-partial-\($0)" } ?? (packed.bias == nil ? "partial" : "mlx-partial-bias") + } else if type(of: packed) == QuantizedLinear.self { + route = reason.map { "mlx-\($0)" } ?? "aqv" + } else { + route = "mlx-subclass-\(type(of: packed))" + } + if !route.hasPrefix("mlx") { + var runs: [(String, Int, Int)] = [] + for count in censusCounts { + let layout = AffineQuantizedVectors.layout(vectors: count, inputs: inputs, outputs: outputs, + bits: packed.bits).description + if let last = runs.last, last.0 == layout { runs[runs.count - 1].2 = count } + else { runs.append((layout, count, count)) } + } + layouts["\(inputs)x\(outputs)"] = runs.map { "\($0.1 == $0.2 ? "\($0.1)" : "\($0.1)-\($0.2)")=\($0.0)" } + .joined(separator: "/") + } + } else { + route = "mlx-unquantized" + } + routes["\(name):\(inputs)x\(outputs):\(route)", default: 0] += 1 + tally[route.hasPrefix("mlx") ? "mlx" : route, default: 0] += 1 + } + let attention = Set(model.model.cbv2LayerKinds.map { kind -> String in + let gqa = kind.queryHeads / max(1, kind.kvHeads) + let hpt = PagedAttentionKernel.headsPerThreadgroup(headDim: kind.headDim, gqa: gqa) + return "d\(kind.headDim)-kv\(kind.kvHeads)-gqa\(gqa)-hpt\(hpt)" + }).sorted() + let environment = ProcessInfo.processInfo.environment + let switches = ["MLX_QMV_BATCH_INVARIANT", "MLX_ENABLE_TF32", "DARKBLOOM_QWEN35_FUSE_ELEMENTWISE", + "DARKBLOOM_QWEN35_DECODE_FUSIONS_V2", "DARKBLOOM_GDN_FUSED_CONV", "DARKBLOOM_GDN_FUSED_QK_NORM", + "DARKBLOOM_RESIDUAL_RMS_NORM", "DARKBLOOM_CBV2_PAGED_PTOK_TARGET", "DARKBLOOM_TTFT_GDN_BLOCKED"] + .compactMap { key in environment[key].map { "\(key)=\($0)" } } + let hidden = model.plan.hiddenSize + return "darkbloom-qwen-tp-decode-census-v1 rank=\(rank) exact_vectors=\(usesExactVectors ? "on" : "off")" + + " aqv=\(tally["aqv", default: 0]) partial=\(tally["partial", default: 0]) mlx=\(tally["mlx", default: 0])" + + " routes=" + routes.sorted { $0.key < $1.key }.map { "\($0.key)*\($0.value)" }.joined(separator: ",") + + " layouts=" + layouts.sorted { $0.key < $1.key }.map { "\($0.key):\($0.value)" }.joined(separator: ",") + + " swiglu_fused_vectors=" + censusCounts.filter { AffineQuantizedVectors.fusesSwiGLU(vectors: $0) } + .map(String.init).joined(separator: "/") + + " residual_rms_norm=\(ResidualRMSNorm.isEnabled && ResidualRMSNorm.verifiedFamilies.contains(AffineQuantizedVectors.family()) ? (hidden > 4096 ? "looped" : "single") : "off")" + + " attention=paged-\(attention.joined(separator: "/")) ptok=\(PagedAttentionKernel.partitionTokens)" + + " ptok_target=\(PagedAttentionKernel.partitionTargetThreadgroups)" + + " selection=greedy-rank-argmax/sampled-gather switches=" + (switches.isEmpty ? "none" : switches.joined(separator: ",")) + } + + private static let censusLock = NSLock() + nonisolated(unsafe) private static var censusModels = Set() + + /// Logs `censusLine` once per loaded model. + static func logCensusOnce(rank: Int, model: QwenTensorParallelModel) { + let first = censusLock.withLock { censusModels.insert(ObjectIdentifier(model)).inserted } + if first { log(censusLine(rank: rank, model: model)) } + } + static func decode(_ sessions: [QwenTensorParallelBatchSession], tokens: [Int], check: () throws -> Void) throws -> MLXArray { try decodeResult(sessions, tokens: tokens, capturingHidden: false, check: check).logits @@ -464,27 +578,27 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { throw ProbeError("Qwen TP positions differ from request-owned three-axis slices") } } + /// Shape and dtype only: selection counts non-finite logits inside its own + /// sealed sum (`QwenTensorParallelNativeBatchExecutor.select`), so both + /// ranks refuse such a row together and no step pays a separate read. private static func validateLogits(_ value: MLXArray, rows: Int, model: QwenTensorParallelModel, request: QwenLayerStageGenerationRequest) throws { guard value.shape == [rows, model.vocabularyRange.count], - String(describing: value.dtype) == request.profile.selectedRowDType, - all(isFinite(value)).item(Bool.self) else { - throw ProbeError("Qwen TP batched logits have an invalid shape, dtype or finite value") + String(describing: value.dtype) == request.profile.selectedRowDType else { + throw ProbeError("Qwen TP batched logits have an invalid shape or dtype") } } - private func capturePrefix(check: () throws -> Void) throws { - guard captured == nil else { throw ProbeError("Qwen TP prefix is already captured") } - captured = try .capture(state: state, frontier: captureFrontier, limitBytes: captureLimitBytes, - allocationBound: allocationBound, check: check) - } - - func takeCapturedPrefix() throws -> QwenTensorParallelBatchPrefixState? { + /// The kept boundaries' states and the attention copy they share, once, + /// after native retirement. + func takeCapturedPrefix() throws -> (states: [QwenTensorParallelBatchPrefixState], sharedBytes: Int)? { guard retired && state.isClosed else { throw ProbeError("Qwen TP prefix donation precedes native retirement") } - defer { captured = nil } - return captured + guard let prefixCapture else { return nil } + defer { prefixCapture.discard() } + let states = prefixCapture.states() + return states.isEmpty ? nil : (states, prefixCapture.sharedBytes) } - func discardCapturedPrefix() { captured = nil } + func discardCapturedPrefix() { prefixCapture?.discard() } func retire() throws { guard !retired else { return } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift index afb1470203..2846243a68 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchWire.swift @@ -4,10 +4,17 @@ import Foundation /// rank owns one disjoint region; splitting Int32 into two UInt16 limbs keeps /// UUIDs, fingerprints and checksums exact in FP32. The load agreement binds /// this protocol separately from the pipeline protocol it uses for framing. +/// +/// v2: a plain decode rectangle's selection sum also carries the next step's +/// plan and report (`QwenTensorParallelBatchDriver.serve`), so such a step +/// pays one sealed sum and one host read; every other step keeps its own exchange. enum QwenTensorParallelBatchWire { - static let agreement = "qwen-tp-independent-history-batch-v1" + static let agreement = "qwen-tp-independent-history-batch-v2-folded-control" static let words = 4 + 2 * (QwenBatchWire.headerWords + QwenBatchWire.replyWords) private static let magic: Float = 0x515442 + /// A folded plan's decode input: the token its row selects in the step + /// whose selection sum carries the plan (unknown when the plan is made). + static let carriedToken = -2 static func contribution(rank: Int, plan: QwenBatchWire.Header?, report: QwenBatchWire.Reply?) throws -> [Float] { guard (rank == 0 && plan != nil && report == nil) || (rank == 1 && plan == nil && report != nil) else { @@ -42,6 +49,7 @@ enum QwenTensorParallelBatchWire { let report = try QwenBatchWire.Reply(words: Array(values.suffix(QwenBatchWire.replyWords)), expectedStep: step, lanes: lanes) guard report.tokens.allSatisfy({ $0 >= -1 }), report.restored.allSatisfy({ $0 == 0 }), plan.slots.allSatisfy({ !$0.confirming && $0.offers.isEmpty && $0.reusedPrefix == 0 }), + plan.slots.allSatisfy({ $0.inputToken >= carriedToken }), !plan.stop || plan.slots.allSatisfy({ $0.state == .empty }) else { throw ProbeError("Qwen TP batch control message requests an unsupported transition") } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift new file mode 100644 index 0000000000..336d5165e6 --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelDecodeBench.swift @@ -0,0 +1,112 @@ +import DarkbloomClusterProtocol +import CryptoKit +import Foundation +import MLX + +/// Developer bench (`darkbloom-cluster-tp-check qwen-decode`): the batch +/// driver's plain decode on this rank, through the real driver, native +/// executor and the rank's group (two ranks of one Mac over the loopback +/// ring, sealed or not). Each run decodes `width` requests together, with the +/// next step's control exchanged a step or folded into the selection sum; +/// the owner answers each token after `answerDelayMicroseconds`. Logs each +/// run's decode step time and a digest of every request's retired tokens; +/// returns whether every run retired the same tokens. Loopback timings show +/// a step's host work and synchronization, never a pair's. +public enum QwenTensorParallelDecodeBench { + struct Reserved: QwenTensorParallelBatchReservation { + let request: QwenLayerStageGenerationRequest + var deadline: UInt64 { .max } + var laneStateBytes: Int { 1 } + var joinable: Bool { true } + } + + /// Rank 0 publishes; the owner answers "go on" once the delay passed. + final class Owner: QwenBatchServingHost { + let delay: UInt64 + private(set) var times: [UUID: [UInt64]] = [:] + init(delay: UInt64) { self.delay = delay } + func serviceControl() throws {} + func publishToken(requestID: UUID, ordinal: Int, tokenID: Int, committedTokens: Int) throws { + times[requestID, default: []].append(DispatchTime.now().uptimeNanoseconds) + } + func publishToken(requestID: UUID, ordinal: Int, tokenID: Int, committedTokens: Int, + logprobs: ClusterWorkerTokenLogprobs?) throws { + try publishToken(requestID: requestID, ordinal: ordinal, tokenID: tokenID, committedTokens: committedTokens) + } + func awaitDecisions(_ requestIDs: [UUID]) throws -> [UUID: Bool] { throw ProbeError("The decode bench polls answers") } + func publishFinished(requestID: UUID, reason: ClusterWorkerFinishReason) throws {} + func publishPromptCache(requestID: UUID, reusedTokens: Int, storedFrontiers: [Int]) throws {} + func pollDecision(_ requestID: UUID) throws -> Bool? { + guard let last = times[requestID]?.last else { return nil } + return DispatchTime.now().uptimeNanoseconds - last >= delay ? true : nil + } + func publishLeft(requestID: UUID) throws {} + } + + public static func pair(model: QwenTensorParallelModel, configuration: Data, group: any QwenTensorParallelReduction, + width: Int, promptTokens: Int, outputTokens: Int, sampled: Bool, folds: [Bool], + repeats: Int, answerDelayMicroseconds: Int, log: (String) -> Void) throws -> Bool { + // Request IDs carry the run's index in one byte. + guard case .shard(let rank, _) = model.role, (1...8).contains(width), promptTokens > 0, outputTokens > 1, + (1...255).contains(repeats), (1...255).contains(folds.count * repeats) else { + throw ProbeError("The decode bench runs a rank shard with 1 to 8 requests of at least two tokens, 255 runs at most") + } + let vocabulary = model.plan.vocabularySize, chunk = min(512, promptTokens), budget = promptTokens + outputTokens + let profile = try QwenLayerStageGenerationProfile(identifier: "qwen-tp-decode-bench", vocabularySize: vocabulary, + hiddenSize: model.plan.hiddenSize, activationDType: "bfloat16", maximumPromptTokens: promptTokens, + maximumChunkTokens: chunk, maximumOutputTokens: outputTokens, maximumContextTokens: budget) + var seen: String?, same = true + for (index, fold) in ([folds[0]] + folds.flatMap { Array(repeating: $0, count: repeats) }).enumerated() { + Memory.clearCache() + let host = try CBv2StageKVHost(model: model.model, kind: .paged, lanes: width, + maximumTokensPerRequest: budget, maximumChunkTokens: chunk) + let executor = try QwenTensorParallelNativeBatchExecutor(model: model, configuration: configuration, + host: host, group: group, prepare: { _, _ in nil }, completedDecode: { _ in }, completedPrefill: {}, + releaseResources: { _ in }) + let book = ClusterBatchLaneBook() + for row in 0 ..< width { + // Both ranks name the same requests: IDs and prompts follow the run and row. + let id = UUID(uuid: (UInt8(index), UInt8(row), 0, 0, 0, 0, 0x40, 0, 0x80, 0, 0, 0, 0, 0, 0, 1)) + let sampling: ClusterWorkerSampling? = sampled ? .init(temperature: 0.7, topP: 0.9, topK: 32, minP: 0.01, + repetitionPenalty: 1.1, repetitionContextSize: 12, frequencyPenalty: 0.15, presencePenalty: 0.2, + seed: UInt64(77 + row), stream: UInt64(5 * row + 1), logitBias: []) : nil + let request = try QwenLayerStageGenerationRequest(profile: profile, requestID: id, + promptTokenIDs: (0 ..< promptTokens).map { (row * 7_919 + $0 * 104_729 + 11) % vocabulary }, + chunkSize: chunk, outputCount: outputTokens, stopTokenIDs: [], sampling: sampling) + try book.reserve(id, Reserved(request: request), lanes: width) + try book.start(id) + } + let owner = Owner(delay: UInt64(max(0, answerDelayMicroseconds)) * 1_000) + let driver = try QwenTensorParallelBatchDriver(executor: executor, book: book, capacity: width, + vocabulary: vocabulary, foldsControl: fold) + var retired: [UUID: [Int]] = [:] + let started = DispatchTime.now().uptimeNanoseconds + try MLX.withError { error in + try driver.serve(host: owner, retiredSelection: { id, tokens, _ in retired[id] = tokens }, + check: { try error.check() }) + } + let total = Double(DispatchTime.now().uptimeNanoseconds - started) / 1e6 + var hash = SHA256() + for id in retired.keys.sorted(by: { $0.uuidString < $1.uuidString }) { + hash.update(data: Data(retired[id]!.flatMap { withUnsafeBytes(of: Int32($0).littleEndian, Array.init) })) + } + let digest = hash.finalize().prefix(8).map { String(format: "%02x", $0) }.joined() + guard retired.count == width, retired.values.allSatisfy({ $0.count == outputTokens }) else { + throw ProbeError("The decode bench retired another set of tokens") + } + // The first run warms the kernels; it is checked, never timed. + if index == 0 { seen = digest; continue } + same = same && seen == digest + // Rank 0: each request's decode, from its first token to its last, per token. + let steps = owner.times.values.map { Double($0.last! - $0.first!) / 1e6 / Double($0.count - 1) }.sorted() + log("qwen-tp-decode-v1 rank=\(rank) control=\(fold ? "folded" : "exchanged") width=\(width)" + + " sampled=\(sampled ? 1 : 0) answer_delay_us=\(answerDelayMicroseconds) prompt=\(promptTokens)" + + " output=\(outputTokens) total_ms=\(String(format: "%.1f", total))" + + (steps.isEmpty ? "" : " step_ms_median=\(String(format: "%.3f", steps[steps.count / 2]))" + + " step_ms_min=\(String(format: "%.3f", steps.first!)) step_ms_max=\(String(format: "%.3f", steps.last!))") + + " tokens=\(digest)") + } + log("qwen-tp-decode-v1 rank=\(rank) token-check \(same ? "same-tokens" : "DIFFERENT")") + return same + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift index 2bf63d24ca..c1ee20d713 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelLinear.swift @@ -132,8 +132,15 @@ final class QwenTensorParallelRowLinear: QuantizedLinear, Qwen35BatchDecodeProje eval(partial) Stream.gpu.synchronize() } - return Self.finish(reduction.value.allSum(partial), dtype: x.dtype) + let summed = reduction.value.allSum(partial) + Self.issuedSums?.sums.append(summed) + return Self.finish(summed, dtype: x.dtype) } + + /// A prompt wavefront's phase (`QwenTensorParallelPromptWavefront`): the + /// raw all-sums its projections issue, before rounding, so the phase can + /// submit them before the next chunk is built. nil changes nothing. + @TaskLocal static var issuedSums: QwenTensorParallelIssuedSums? } /// Diagnostic only: a rank's shard with no peer. `allSum` returns this rank's diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPBudget.swift index f30c1ee720..c7be961630 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPBudget.swift @@ -68,7 +68,7 @@ struct QwenTensorParallelMTPBudget { // prompt stays one rectangle, as before. let chunks = (promptTokens + chunkSize - 1) / chunkSize let decodeRoots = min(flushRows ?? 0, maximumTokens) - let checkpointRows = min(QwenTensorParallelBatchPrefixBudget.maximumTokens, maximumTokens) + let checkpointRows = min(QwenTensorParallelMTPPrefixBudget.maximumTokens, maximumTokens) let heldRows = flushRows.map { $0 >= promptTokens ? promptTokens : min(promptTokens, max(checkpointRows, $0 + chunkSize + 1)) } ?? promptTokens diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift index 4c7009455b..b454998de2 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPrefixBudget.swift @@ -3,31 +3,45 @@ import Foundation /// Compact target and assistant capture has a distinct live bank and two /// resident banks. Full live pages, trusted history, restore destinations and /// first-draft prompt workspace stay in the ordinary complete MTP quotation. +/// +/// The assistant keeps one original-grid frontier per lane, at most +/// `maximumTokens` deep: its prompt history is held unflushed up to that +/// frontier (`QwenTensorParallelMTPBudget`'s checkpoint rows), so a deeper +/// frontier is a larger trusted-history bank in every assisted lane, not +/// only a larger capture. The plain lanes keep theirs to the request's +/// context (`QwenTensorParallelBatchPrefixBudget`). struct QwenTensorParallelMTPPrefixBudget { static let policy = "qwen-tp-mtp-grid-prefix-4096-v1" + static let maximumTokens = 4096 let maximumTokens: Int let targetCaptureBytes: Int let assistantCaptureBytes: Int let captureBytes: Int let residentBytes: Int - static func derive(geometry: QwenLongPrefillBudgetGeometry, maximumTokens: Int, + static func derive(geometry g: QwenLongPrefillBudgetGeometry, maximumTokens: Int, allocationBound: (Int) throws -> Int) throws -> Self { - let target = try QwenTensorParallelBatchPrefixBudget.derive(geometry: geometry, - maximumTokens: maximumTokens, allocationBound: allocationBound) + guard maximumTokens > 0 else { throw ProbeError("Invalid TP prefix context") } + let count = min(Self.maximumTokens, maximumTokens) let product = QwenLongPrefillCheckedBytes.product, sum = QwenLongPrefillCheckedBytes.sum - func bound(_ bytes: Int) throws -> Int { + let b = try QwenLongPrefillTensorBudget.estimate(geometry: g, maximumTokens: count, chunkSize: 1) + func bound(_ bytes: Int, count: Int = 1) throws -> Int { + guard count > 0 else { return 0 } let result = try allocationBound(bytes) guard bytes > 0, result >= bytes else { throw ProbeError("Qwen TP MTP prefix allocator bound differs") } - return result + return try product([result, count]) } - let count = target.maximumTokens + let target = try sum([ + bound(b.convolutionBytesPerLayer, count: g.recurrentLayers), + bound(b.ssmBytesPerLayer, count: g.recurrentLayers), + bound(product([count, g.kvHeads, g.headDimension, 2]), count: 2 * g.attentionLayers), + ]) let assistant = count < 2 ? 0 : try sum([ - bound(product([count - 1, geometry.hiddenSize, 2])), - bound(product([count - 1, 4])), bound(product([geometry.hiddenSize, 2])), + bound(product([count - 1, g.hiddenSize, 2])), + bound(product([count - 1, 4])), bound(product([g.hiddenSize, 2])), ]) - let capture = try sum([target.captureBytes, assistant]) - return try .init(maximumTokens: count, targetCaptureBytes: target.captureBytes, + let capture = try sum([target, assistant]) + return try .init(maximumTokens: count, targetCaptureBytes: target, assistantCaptureBytes: assistant, captureBytes: capture, residentBytes: product([capture, 2])) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift index 2b21249f57..88d20f86b4 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelNativeBatchExecutor.swift @@ -9,7 +9,9 @@ final class QwenTensorParallelNativeBatchLane: QwenTensorParallelBatchLane { var accepted = QwenTensorParallelAcceptedSelections() var selectedCount = 0 var canSelectNext: Bool { !accepted.isEmpty || nextFrame?.phase == .decode } - var prefixKey: String? + var plainSelection: Bool { assistant == nil } + /// The keys of the boundaries this request captures, by boundary. + var prefixKeys: [Int: String] = [:] /// This request's scope on the SSD tier, kept for its persist after a /// confirmed clean retirement. var prefixDiskScope: String? @@ -28,6 +30,15 @@ final class QwenTensorParallelNativeBatchLane: QwenTensorParallelBatchLane { guard !session.retired else { return nil } return try? session.request.frame(sequence: session.schedule.nextSequence) } + /// An assisted lane's prompt keeps one frame a step (its history takes each frame's hidden rows). + func promptStep(frames: Int) -> QwenLayerStageFrame? { + QwenTensorParallelPromptWavefront.step(session.promptFrames(limit: assistant == nil ? frames : 1)) + } + func promptStep(tokens: Int) -> QwenLayerStageFrame? { + let frames = session.promptFrames(limit: assistant == nil ? QwenTensorParallelPromptWavefront.maximumFrames : 1) + return (1...max(1, frames.count)).lazy.compactMap { QwenTensorParallelPromptWavefront.step(Array(frames.prefix($0))) } + .first { $0.tokenCount == tokens } + } var committedTokens: Int { session.committedTokens } var isClosed: Bool { session.retired && session.state.isClosed && resourcesReleased } } @@ -119,6 +130,7 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> [Float] { @@ -147,7 +159,8 @@ final class QwenTensorParallelNativeBatchExecutor agreed.frontier { captureFrontier = last; captureKey = keys[last] } + if let last = candidates.last, last > agreed.frontier, let key = keys[last] { + captureFrontier = last; captureKeys = [last: key] + } } } else if admittedAssistant == nil, let prefix, prefix.enabled, let budget = prefixBudget, let scope = prefixScope?(reservation), let allocationBound { + // To the request's own context, as its reservation charged its capture; LOAD's memory plan is shorter. let candidates = QwenTensorParallelBatchPrefixCache.candidates(promptCount: request.promptCount, - chunkSize: request.chunkSize, maximumTokens: budget.maximumTokens) + chunkSize: request.chunkSize, maximumTokens: request.maximumTokens) let keys = QwenTensorParallelBatchPrefixCache.keys(scope: scope, tokens: request.promptTokenIDs, frontiers: candidates) diskScope = prefixDisk == nil ? nil : prefixDiskScope?(reservation) @@ -185,14 +201,18 @@ final class QwenTensorParallelNativeBatchExecutor agreed.frontier { - captureFrontier = last; captureKey = keys[last] - } + } + // The boundaries this request keeps after what it restored, within its own charged capture. + let frontiers = QwenTensorParallelBatchPrefixBudget.frontiers(promptCount: request.promptCount, + chunkSize: request.chunkSize, restored: request.reusedPrefixTokens, maximumTokens: request.maximumTokens) + if !frontiers.isEmpty { + captureKeys = QwenTensorParallelBatchPrefixCache.keys(scope: scope, tokens: request.promptTokenIDs, frontiers: frontiers) + capture = .init(frontiers: frontiers, limitBytes: try budget.captureBytes(promptCount: request.promptCount, + chunkSize: request.chunkSize, allocationBound: allocationBound), allocationBound: allocationBound) } } let lane = try Lane(.init(model: model, configuration: configuration, host: host, - request: request, inputs: inputs, restored: restored, captureFrontier: admittedAssistant == nil ? captureFrontier : 0, - captureLimitBytes: prefixBudget?.captureBytes ?? 0, allocationBound: allocationBound), + request: request, inputs: inputs, restored: restored, capture: admittedAssistant == nil ? capture : nil), releaseResources: { [releaseResources] in try releaseResources(reservation) }) // Keep custody before assistant checkpoint restoration can allocate. // If opening throws, the driver's existing discard path retires this @@ -203,7 +223,7 @@ final class QwenTensorParallelNativeBatchExecutor( cache: QwenTensorParallelSnapshotCache, candidates: [Int], keys: [Int: String], diskScope: String?, prompt: [Int], check: () throws -> Void, read: (QwenStagePrefixState) throws -> Snapshot? @@ -247,9 +268,13 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> Int? { - guard lane.nextFrame == frame else { throw ProbeError("Qwen TP native prefill frame changed") } + guard lane.promptStep(tokens: frame.tokenCount) == frame else { throw ProbeError("Qwen TP native prefill frame changed") } let output: MLXArray? if let decoder = lane.assistant { output = try decoder.prefill(check: check) } - else { output = try lane.session.prefill(check: check) } + else { output = try lane.session.prefill(step: frame, check: check) } completedPrefill() guard let logits = output else { return nil } - let token = try select(logits, lanes: [lane], check: check)[0] + let token = try select(logits, lanes: [lane], control: nil, check: check).tokens[0] try lane.assistant?.begin(firstToken: token) lane.selectedCount = 1 return token } + var carriesSelectionControl: Bool { true } + func decode(_ lanes: [Lane], tokens: [Int], check: () throws -> Void) throws -> [Int] { + try decode(lanes, tokens: tokens, control: { nil }, check: check).tokens + } + + func decode(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?, + check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) { try GPU.withCommandBufferLimits(QwenTensorParallelBatchSession.decodeCommandBuffers) { - try decodeRound(lanes, tokens: tokens, check: check) + try decodeRound(lanes, tokens: tokens, control: control, check: check) } } @@ -323,11 +355,13 @@ final class QwenTensorParallelNativeBatchExecutor Void) throws -> [Int] { + private func decodeRound(_ lanes: [Lane], tokens: [Int], control: () throws -> [Float]?, + check: () throws -> Void) throws -> (tokens: [Int], control: [Float]?) { guard !lanes.isEmpty, lanes.count == tokens.count, lanes.count <= host.lanes, Set(lanes.map { ObjectIdentifier($0) }).count == lanes.count else { throw ProbeError("Qwen TP accepted selections require distinct scheduled lanes") } + var summedControl: [Float]? if let context = assistant, let quote = context.cohortBudget { let frontiers = cohortFrontiers(lanes, tokens: tokens, depth: context.depth) let eligible = frontiers.keys.sorted() @@ -386,7 +420,14 @@ final class QwenTensorParallelNativeBatchExecutor