SPB Git

Repository Public

EditorMemoryGovernor.swift 19.7 KB 377 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Docs9// File             : Packages/ORIXDocsAI/Sources/DocLocalModels/EditorMemoryGovernor.swift10// Description      : Memory policy for on-device models inside a document11//                    editor. Builds on ORIX Astra's `MemoryGovernor` (weights +12//                    KV cache + runtime overhead against a share of physical13//                    memory) and adds what a Mac word processor needs: a14//                    reserve for the editor itself (layout, fonts, images, PDF15//                    export), the system's memory-pressure signal, and a hook16//                    that lets heavy document work (an export, a large import)17//                    defer a model load. On critical pressure every model is18//                    unloaded.19// Module           : DocLocalModels20// Repository       : https://git.spboucher.ai/orix-docs21// Created          : 2026-11-2222// Last Modified    : 2026-11-2223//24// =============================================================================25// AUTHOR & PROFESSIONAL AFFILIATION26// =============================================================================27//28// Author           : Simon-Pierre Boucher29// Position         : Professor of Finance30// Institution      : Université du Québec en Outaouais (UQO)31// Department       : Département des sciences administratives32// Organization     : SP Boucher33//34// Website          : https://spboucher.ai35// Git              : https://git.spboucher.ai36//37// =============================================================================38// OFFICIAL CONTACT DIRECTORY39// =============================================================================40//41// General          : info@spboucher.ai42// Professional     : contact@spboucher.ai43// Direct           : simon@spboucher.ai44// Research         : research@spboucher.ai45// Development      : dev@spboucher.ai46// Support          : support@spboucher.ai47// Security/Admin   : admin@spboucher.ai48// Notifications    : notifications@spboucher.ai49//50// Preferred Contact: support@spboucher.ai51//52// =============================================================================53// COPYRIGHT & INTELLECTUAL PROPERTY54// =============================================================================55//56// Copyright (c) 202657// Simon-Pierre Boucher58//59// All rights reserved where applicable.60//61// This file is governed by the applicable project license,62// copyright notices, institutional agreements and relevant law.63//64// Unless expressly authorized by the applicable license or65// rights holder, copying, redistribution, sublicensing,66// publication and commercial exploitation are not permitted.67//68// Existing third-party rights and notices remain unaffected.69//70// =============================================================================71// CONFIDENTIALITY & SECURITY72// =============================================================================73//74// Classification   : Public75// Distribution     : Public repository; use is governed by the project license76// Security Contact : admin@spboucher.ai77//78// Access to this source does not independently grant permission79// to redistribute or disclose confidential materials.80//81// Do not embed credentials, private keys, access tokens,82// certificates or confidential personal information.83//84// =============================================================================85// LICENSE & MAINTENANCE86// =============================================================================87//88// License          : None specified (no license file in this repository)89// Maintainer       : Simon-Pierre Boucher90// Technical Contact: dev@spboucher.ai91//92// =============================================================================93// END OF SP BOUCHER SOURCE HEADER94// =============================================================================9596import AstraCore97import AstraLocal98import Darwin99import Foundation100101public enum MemoryPressureLevel: String, Sendable, Hashable, Codable, CaseIterable, Comparable {102    case normal, warning, critical103    private var rank: Int { switch self { case .normal: 0; case .warning: 1; case .critical: 2 } }104    public static func < (a: MemoryPressureLevel, b: MemoryPressureLevel) -> Bool { a.rank < b.rank }105}106107/// The numbers of the policy. Defaults are deliberately conservative: the document always wins over the model.108public struct EditorMemoryPolicy: Sendable, Hashable, Codable {109    /// Memory kept for the editor at all times: the larger of an absolute floor and a share of physical memory.110    public var editorReserveFloorBytes: Int64111    public var editorReserveShare: Double112    /// Extra memory kept while heavy document work is in progress (PDF export rasterises pages, imports decode images).113    public var heavyWorkReserveBytes: Int64114    /// Under a memory warning only this share of the normal budget may be used by a newly loaded model.115    public var warningBudgetFactor: Double116    /// Context length used to judge a model when the caller gives none.117    public var defaultContext: Int118119    public init(editorReserveFloorBytes: Int64 = 3 << 30, editorReserveShare: Double = 0.10, heavyWorkReserveBytes: Int64 = 2 << 30,120                warningBudgetFactor: Double = 0.5, defaultContext: Int = 8_192) {121        self.editorReserveFloorBytes = editorReserveFloorBytes; self.editorReserveShare = editorReserveShare122        self.heavyWorkReserveBytes = heavyWorkReserveBytes; self.warningBudgetFactor = warningBudgetFactor; self.defaultContext = defaultContext123    }124    public static let standard = EditorMemoryPolicy()125126    public func editorReserve(physicalBytes: Int64) -> Int64 { max(editorReserveFloorBytes, Int64(Double(physicalBytes) * editorReserveShare)) }127}128129/// The governor's answer to "may this model be loaded now?".130public struct ModelLoadDecision: Sendable, Hashable {131    public enum Verdict: String, Sendable, Hashable, Codable {132        /// The model fits in what the editor leaves free.133        case allow134        /// The model would fit, but heavy document work is in progress: load it when that work ends.135        case deferUntilDocumentWorkEnds136        /// The model does not fit in the budget (or memory pressure forbids loading). Loading it would hurt the editor.137        case refuse138    }139    public var verdict: Verdict140    /// Sentence for the UI, with the numbers.141    public var reason: String142    /// ORIX Astra's fit estimate against the editor-aware budget.143    public var fit: FitVerdict144    /// What one model may use right now, after the editor's reserve and the pressure factor.145    public var budgetBytes: Int64146    public var editorReserveBytes: Int64147    public var pressure: MemoryPressureLevel148    public var heavyDocumentWork: Bool149    public var mayLoadNow: Bool { verdict == .allow }150}151152public enum HeavyDocumentWorkPhase: Sendable, Hashable { case begin, end }153154public actor EditorMemoryGovernor {155    public struct State: Sendable, Hashable {156        public var pressure: MemoryPressureLevel157        /// Labels of the heavy document work in progress ("PDF export"), oldest first.158        public var heavyWork: [String]159        public var reading: MemoryReading160        /// What a newly loaded model may use right now.161        public var modelBudgetBytes: Int64162        /// Why the governor last unloaded the models, when it did.163        public var lastUnloadReason: String?164    }165166    public nonisolated let policy: EditorMemoryPolicy167    /// ORIX Astra's governor, with the macOS share of physical memory.168    public nonisolated let base: MemoryGovernor169    private let readMemory: @Sendable () -> MemoryReading170    private var pressure: MemoryPressureLevel = .normal171    private var heavyWork: [(id: UUID, label: String)] = []172    private var waiters: [CheckedContinuation<Void, Never>] = []173    private var unloaders: [@Sendable (_ critical: Bool) async -> Void] = []174    private var lastUnloadReason: String?175    private var source: (any DispatchSourceMemoryPressure)?176    private var observers: [UUID: AsyncStream<State>.Continuation] = [:]177178    public init(policy: EditorMemoryPolicy = .standard, base: MemoryGovernor = MemoryGovernor(platform: .macOS),179                memory: @escaping @Sendable () -> MemoryReading = { EditorMemoryGovernor.systemReading() }) {180        self.policy = policy; self.base = base; readMemory = memory181    }182183    // MARK: Readings184185    /// Physical memory, the memory the system could hand out now (free, inactive, purgeable and speculative pages: ORIX Astra's186    /// reading has no such figure on macOS), and this process's footprint.187    public static func systemReading() -> MemoryReading {188        var reading = MemoryReading.current()189        reading.availableBytes = reclaimableBytes()190        return reading191    }192193    /// Pages the kernel can give to a process without swapping, from `host_statistics64`. nil when the call fails.194    static func reclaimableBytes() -> Int64? {195        var stats = vm_statistics64_data_t()196        var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64_data_t>.size / MemoryLayout<integer_t>.size)197        let result = withUnsafeMutablePointer(to: &stats) {198            $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count) }199        }200        guard result == KERN_SUCCESS else { return nil }201        var pageSize: vm_size_t = 0202        guard host_page_size(mach_host_self(), &pageSize) == KERN_SUCCESS, pageSize > 0 else { return nil }203        let pages = UInt64(stats.free_count) + UInt64(stats.inactive_count) + UInt64(stats.purgeable_count) + UInt64(stats.speculative_count)204        return Int64(clamping: pages * UInt64(pageSize))205    }206207    // MARK: Pure policy208209    /// What one newly loaded model may use: ORIX Astra's budget for this Mac, minus the editor's reserve (and the heavy-work210    /// reserve while such work runs), reduced under a memory warning, zero under critical pressure. Pure.211    public static func modelBudget(policy: EditorMemoryPolicy, base: MemoryGovernor, reading: MemoryReading, pressure: MemoryPressureLevel,212                                   heavyWork: Bool) -> Int64 {213        guard pressure != .critical else { return 0 }214        // Astra's `budget` takes a share of physical memory and of what is available now. The editor's reserve comes off the215        // physical side (it is part of what this process needs over time) and off the available side (it must stay free now).216        let reserve = policy.editorReserve(physicalBytes: reading.physicalBytes) + (heavyWork ? policy.heavyWorkReserveBytes : 0)217        var reduced = reading218        if let available = reading.availableBytes { reduced.availableBytes = max(0, available - reserve) }219        var budget = min(base.budget(reduced), base.budget(MemoryReading(physicalBytes: reading.physicalBytes)) - reserve)220        if pressure == .warning { budget = Int64(Double(budget) * policy.warningBudgetFactor) }221        return max(0, budget)222    }223224    /// Judges one model against the editor-aware budget. Pure: every input is a parameter.225    public static func decide(profile: ModelMemoryProfile, context: Int, policy: EditorMemoryPolicy, base: MemoryGovernor, reading: MemoryReading,226                              pressure: MemoryPressureLevel, heavyWork: Bool, modelName: String = "This model") -> ModelLoadDecision {227        let reserve = policy.editorReserve(physicalBytes: reading.physicalBytes)228        let budgetNow = modelBudget(policy: policy, base: base, reading: reading, pressure: pressure, heavyWork: heavyWork)229        let budgetIdle = modelBudget(policy: policy, base: base, reading: reading, pressure: pressure, heavyWork: false)230        // Astra's verdict, against a reading whose usable memory is the editor-aware budget: `availableShare` is undone so that231        // the governor's own budget equals ours exactly.232        func fit(_ budget: Int64) -> FitVerdict {233            let asReading = MemoryReading(physicalBytes: reading.physicalBytes, availableBytes: Int64(Double(budget) / base.availableShare), footprintBytes: reading.footprintBytes)234            var verdict = base.verdict(for: profile, context: context, reading: asReading)235            verdict.budgetBytes = budget236            return verdict237        }238        let now = fit(budgetNow)239        let need = MemoryGovernor.format(now.estimatedNeedBytes)240        func make(_ verdict: ModelLoadDecision.Verdict, _ reason: String) -> ModelLoadDecision {241            ModelLoadDecision(verdict: verdict, reason: reason, fit: now, budgetBytes: budgetNow, editorReserveBytes: reserve, pressure: pressure, heavyDocumentWork: heavyWork)242        }243        if pressure == .critical {244            return make(.refuse, "The Mac is critically low on memory. No model is loaded until the pressure is gone.")245        }246        if now.mayLoad {247            return make(.allow, "\(modelName) needs about \(need); \(MemoryGovernor.format(budgetNow)) can be used while keeping \(MemoryGovernor.format(reserve)) for the document. This is an estimate.")248        }249        if heavyWork, fit(budgetIdle).mayLoad {250            return make(.deferUntilDocumentWorkEnds, "\(modelName) needs about \(need). It will fit once the document work in progress is finished; loading is deferred until then.")251        }252        let cause = pressure == .warning ? " while the Mac is under memory pressure" : ""253        return make(.refuse, "\(modelName) needs about \(need), but only \(MemoryGovernor.format(budgetNow)) can be used\(cause) without taking memory from the document (\(MemoryGovernor.format(reserve)) is kept for it). This is an estimate.")254    }255256    // MARK: Decisions257258    public func modelBudgetBytes() -> Int64 {259        Self.modelBudget(policy: policy, base: base, reading: readMemory(), pressure: pressure, heavyWork: !heavyWork.isEmpty)260    }261262    public func decision(for profile: ModelMemoryProfile, context: Int? = nil, modelName: String = "This model") -> ModelLoadDecision {263        Self.decide(profile: profile, context: context ?? min(policy.defaultContext, profile.modelContextLength ?? policy.defaultContext), policy: policy,264                    base: base, reading: readMemory(), pressure: pressure, heavyWork: !heavyWork.isEmpty, modelName: modelName)265    }266267    public func decision(for card: LocalModelCard, context: Int? = nil) -> ModelLoadDecision {268        decision(for: card.memoryProfile, context: context, modelName: card.displayName)269    }270271    /// Largest context (from ORIX Astra's ladder) at which the model fits the editor-aware budget right now; nil when none does.272    public func recommendedContext(for profile: ModelMemoryProfile) -> Int? {273        let budget = modelBudgetBytes()274        let reading = readMemory()275        let asReading = MemoryReading(physicalBytes: reading.physicalBytes, availableBytes: Int64(Double(budget) / base.availableShare))276        return base.recommendedMaxContext(for: profile, reading: asReading)277    }278279    public func state() -> State {280        State(pressure: pressure, heavyWork: heavyWork.map(\.label), reading: readMemory(), modelBudgetBytes: modelBudgetBytes(), lastUnloadReason: lastUnloadReason)281    }282283    public func states() -> AsyncStream<State> {284        AsyncStream(bufferingPolicy: .bufferingNewest(1)) { continuation in285            let key = UUID()286            observers[key] = continuation287            continuation.yield(state())288            continuation.onTermination = { [weak self] _ in Task { await self?.removeObserver(key) } }289        }290    }291    private func removeObserver(_ key: UUID) { observers[key] = nil }292    private func publish() { guard !observers.isEmpty else { return }; let s = state(); for o in observers.values { o.yield(s) } }293294    // MARK: Heavy document work295296    /// Called by the editor around memory-hungry work: `let token = await governor.noteHeavyDocumentWork(.begin, label: "PDF export")`,297    /// then `await governor.noteHeavyDocumentWork(.end, token: token)`. While any such work is in progress the model budget is298    /// reduced by `heavyWorkReserveBytes` and loads that no longer fit are deferred (`waitForDocumentWork()`), not refused.299    /// Returns the token to end the work with; `.end` returns the token it was given.300    @discardableResult301    public func noteHeavyDocumentWork(_ phase: HeavyDocumentWorkPhase, label: String = "Document work", token: UUID? = nil) -> UUID {302        switch phase {303        case .begin:304            let id = token ?? UUID()305            heavyWork.append((id, label))306            publish()307            return id308        case .end:309            // Without a token the oldest work with that label ends: a caller that lost its token cannot block loads forever.310            if let token { heavyWork.removeAll { $0.id == token } }311            else if let i = heavyWork.firstIndex(where: { $0.label == label }) { heavyWork.remove(at: i) }312            if heavyWork.isEmpty { let waiting = waiters; waiters.removeAll(); waiting.forEach { $0.resume() } }313            publish()314            return token ?? UUID()315        }316    }317318    public var isHeavyDocumentWorkInProgress: Bool { !heavyWork.isEmpty }319320    /// Runs `body` as heavy document work: begin, the work, end, also when it throws.321    public nonisolated func withHeavyDocumentWork<T: Sendable>(_ label: String, _ body: @Sendable () async throws -> T) async rethrows -> T {322        let token = await noteHeavyDocumentWork(.begin, label: label)323        do {324            let value = try await body()325            await noteHeavyDocumentWork(.end, token: token)326            return value327        } catch {328            await noteHeavyDocumentWork(.end, token: token)329            throw error330        }331    }332333    /// Returns when no heavy document work is in progress (immediately when there is none).334    public func waitForDocumentWork() async {335        guard !heavyWork.isEmpty else { return }336        await withCheckedContinuation { waiters.append($0) }337    }338339    // MARK: Pressure340341    /// Registers what must happen when memory runs short: `critical == false` → release caches and idle models; `true` → unload342    /// everything now. `LocalModelLibrary` registers its engine here.343    public func onPressure(_ unload: @escaping @Sendable (_ critical: Bool) async -> Void) { unloaders.append(unload) }344345    /// Starts listening to the system's memory-pressure events. Idempotent.346    public func startMonitoring() {347        guard source == nil else { return }348        let source = DispatchSource.makeMemoryPressureSource(eventMask: [.normal, .warning, .critical], queue: .global(qos: .utility))349        source.setEventHandler { [weak self] in350            let event = source.data351            let level: MemoryPressureLevel = event.contains(.critical) ? .critical : event.contains(.warning) ? .warning : .normal352            Task { await self?.handlePressure(level) }353        }354        source.resume()355        self.source = source356    }357358    public func stopMonitoring() { source?.cancel(); source = nil }359360    /// Applies a pressure level: remembered for the next decisions, and acted upon. Public so the app (and tests) can drive it.361    public func handlePressure(_ level: MemoryPressureLevel) async {362        pressure = level363        switch level {364        case .normal: break365        case .warning:366            lastUnloadReason = "memory warning: idle models released"367            for unload in unloaders { await unload(false) }368        case .critical:369            lastUnloadReason = "critical memory pressure: all models unloaded"370            for unload in unloaders { await unload(true) }371        }372        publish()373    }374375    public var currentPressure: MemoryPressureLevel { pressure }376}377
Files main
Menu

Theme