diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8d0dd45..ded9821 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -337,6 +337,10 @@ jobs: # Stand-in servers that only list models, one with TGI's metrics, a KoboldCpp, a TabbyAPI and one behind a key: # what each card shows, and that nothing is asked that makes a model work. run: sh Linux/tests/other-engine.sh .build/release/tokenmeter + - name: Models page and Will it fit + # Model folders of Ollama, LM Studio, Hugging Face and llama.cpp in a home folder of its own: the files are + # found with their sizes, and a model that never ran gets an estimate from its file. No model is loaded. + run: sh Linux/tests/models.sh .build/release/tokenmeter - name: The idle service stays within its budget # Processor time, wake-ups, open files and memory of a service with nothing to watch, over a minute. # The stand-in engines of the steps above are stopped first: with them it has work to do. diff --git a/Android/build.sh b/Android/build.sh index 0701ee7..7fb28a9 100755 --- a/Android/build.sh +++ b/Android/build.sh @@ -20,7 +20,7 @@ platform=${ANDROID_PLATFORM:-35} jar=$sdk/platforms/android-$platform/android.jar [ -f "$jar" ] || { echo "No $jar: install the platform with sdkmanager \"platforms;android-$platform\"." >&2; exit 1; } tools=$(ls -d "$sdk"/build-tools/* | sort -V | tail -1) -version=${APP_VERSION:-0.9.9} +version=${APP_VERSION:-0.9.10} IFS=. read -r major minor patch <<<"$version.0.0" code=$((major * 10000 + minor * 100 + ${patch%%[^0-9]*})) diff --git a/App/App.swift b/App/App.swift index 342f27b..2352b73 100644 --- a/App/App.swift +++ b/App/App.swift @@ -88,6 +88,7 @@ struct MainWindow: View { case .insights: InsightsView() case .usage: UsageView() case .performance: PerformanceView() + case .models: ModelsView() case .sessions: SessionsView() case .lab: LabView() case .gizmo: GizmoView() diff --git a/App/CommandPalette.swift b/App/CommandPalette.swift index 47ce8df..2bdef08 100644 --- a/App/CommandPalette.swift +++ b/App/CommandPalette.swift @@ -69,6 +69,7 @@ enum CommandPalette { ] if platform == .linux { pages.append(Page(id: "engines", title: "Engines", keywords: "saved servers ports add", key: nil)) } pages.append(Page(id: "agents", title: "Agents", keywords: "coding agents reporters claude codex hooks docker vm", key: nil)) + pages.append(Page(id: "models", title: "Models", keywords: "model files disk downloaded unused will it fit memory context ollama lm studio hugging face gguf", key: nil)) pages.append(Page(id: "setup", title: "Setup", keywords: "how agents reach models tools engine proxy mcp proxy reporter ports lines improve tour", key: nil)) pages.append(Page(id: "mesh", title: "Mesh", keywords: "other machines add machine join allow wants to join found network fleet share usage history ignore", key: nil)) return pages diff --git a/App/Insights.swift b/App/Insights.swift index f3e07f0..9d5bed2 100644 --- a/App/Insights.swift +++ b/App/Insights.swift @@ -504,6 +504,8 @@ enum Insights { /// Compares the engines and machines with the last reading and keeps what changed. func observe(now: Date = Date()) { let servers = EngineMonitor.shared.servers.map(StatusReport.server) + // The same look feeds "Will it fit?": what each loaded model holds in memory (App/ModelsPage.swift). + ModelFootprintStore.shared.note(servers, now: now) let peers = FleetStore.shared.peers.map { ChangeWatch.Peer(address: $0.address, name: $0.report?.host ?? $0.address, online: $0.isOnline, problem: $0.problem) } let known = watch.seeded ? [] : RequestLogStore.shared.models() diff --git a/App/ModelFiles.swift b/App/ModelFiles.swift new file mode 100644 index 0000000..f3354f6 --- /dev/null +++ b/App/ModelFiles.swift @@ -0,0 +1,187 @@ +import Foundation + +/// A model as it lies on this machine's disk: what a model manager downloaded, whether or not it ever ran. +struct ModelFile: Codable, Equatable, Identifiable { + /// The folder or file it is, so two managers holding the same model are two rows. + var id: String { path } + /// "qwen3-coder:30b", "mlx-community/Qwen3-8B-4bit", "Qwen3-Coder-30B-Q4_K_M.gguf". + var name: String + /// "Ollama", "LM Studio", "Hugging Face cache" or "llama.cpp". + var source: String + var path: String + var bytes: Int + /// When the files were last written (downloaded or updated), seconds since 1970. + var modified: Double + /// When a request for it last finished, where the request log knows a model that matches; nil when none does. + var lastRan: Double? = nil +} + +/// Reads what the model managers keep on disk: Ollama's manifests, LM Studio's folders, the Hugging Face cache and +/// llama.cpp's download cache. It lists folders and reads file sizes and Ollama's small manifest files; no model +/// file is opened. A scan is kept ten minutes, and runs off the main line. +enum ModelFiles { + /// How long a model may go without a request before the page marks it as not used lately. + static let idleDays = 30.0 + static let keepSeconds: TimeInterval = 600 + + private static let kept = Locked<(files: [ModelFile], at: Date, scanning: Bool)>(([], .distantPast, false)) + + /// The last scan, and whether one has finished yet. Starts a new one in the background when it is stale. + static func current(now: Date = Date()) -> (files: [ModelFile], at: Date?) { + let state = kept.with { state -> (files: [ModelFile], at: Date, start: Bool) in + let stale = now.timeIntervalSince(state.at) >= keepSeconds && !state.scanning + if stale { state.scanning = true } + return (state.files, state.at, stale) + } + if state.start { + DispatchQueue.global(qos: .utility).async { + let found = scan() + kept.with { $0 = (found, Date(), false) } + } + } + return (state.files, state.at == .distantPast ? nil : state.at) + } + + /// Everything found under a home folder. `environment` moves the folders as the managers' own variables do. + static func scan(home: String? = nil, environment: [String: String] = ProcessInfo.processInfo.environment) -> [ModelFile] { + // (On Linux NSHomeDirectory doesn't follow HOME, so the variable is read first.) + let home = home ?? environment["HOME"].flatMap { $0.isEmpty ? nil : $0 } ?? NSHomeDirectory() + var found: [ModelFile] = [] + var ollama = [home + "/.ollama/models", "/usr/share/ollama/.ollama/models", "/var/lib/ollama/.ollama/models"] + if let moved = environment["OLLAMA_MODELS"], !moved.isEmpty { ollama.insert(moved, at: 0) } + for folder in unique(ollama) { found += self.ollama(folder) } + for folder in unique([home + "/.lmstudio/models", home + "/.cache/lm-studio/models"]) { found += lmStudio(folder) } + var hub = [home + "/.cache/huggingface/hub"] + if let moved = environment["HF_HUB_CACHE"], !moved.isEmpty { hub.insert(moved, at: 0) } + else if let moved = environment["HF_HOME"], !moved.isEmpty { hub.insert(moved + "/hub", at: 0) } + for folder in unique(hub) { found += huggingFace(folder) } + var llama = [home + "/.cache/llama.cpp", home + "/Library/Caches/llama.cpp"] + if let moved = environment["LLAMA_CACHE"], !moved.isEmpty { llama.insert(moved, at: 0) } + for folder in unique(llama) { found += llamaCpp(folder) } + return found.sorted { ($0.bytes, $1.path) > ($1.bytes, $0.path) } + } + + private static func unique(_ paths: [String]) -> [String] { + var seen = Set() + return paths.map { URL(fileURLWithPath: $0).standardizedFileURL.path }.filter { seen.insert($0).inserted } + } + + private static func children(_ folder: String) -> [String] { + ((try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? []).filter { !$0.hasPrefix(".") }.sorted() + } + + private static func isFolder(_ path: String) -> Bool { + var folder: ObjCBool = false + return FileManager.default.fileExists(atPath: path, isDirectory: &folder) && folder.boolValue + } + + private static func facts(_ path: String) -> (bytes: Int, modified: Double)? { + guard let attributes = try? FileManager.default.attributesOfItem(atPath: path) else { return nil } + let bytes = (attributes[.size] as? NSNumber)?.intValue ?? 0 + return (bytes, (attributes[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0) + } + + /// The plain files under a folder, added up. Links are not followed, so a cache that links to its own + /// files (Hugging Face's snapshots) is counted once. + private static func total(_ folder: String) -> (bytes: Int, modified: Double) { + var bytes = 0, modified = 0.0 + guard let walker = FileManager.default.enumerator(atPath: folder) else { return (0, 0) } + for case let name as String in walker { + let attributes = walker.fileAttributes + guard !name.isEmpty, attributes?[.type] as? FileAttributeType == .typeRegular else { continue } + bytes += (attributes?[.size] as? NSNumber)?.intValue ?? 0 + modified = max(modified, (attributes?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0) + } + return (bytes, modified) + } + + /// Ollama: `manifests////` is a small JSON file naming the layers and their + /// sizes. Layers shared by two tags are counted under each. + static func ollama(_ folder: String) -> [ModelFile] { + var found: [ModelFile] = [] + let manifests = folder + "/manifests" + for registry in children(manifests) { + for namespace in children(manifests + "/" + registry) { + for model in children(manifests + "/" + registry + "/" + namespace) { + let place = manifests + "/" + registry + "/" + namespace + "/" + model + for tag in children(place) { + let path = place + "/" + tag + guard let data = FileManager.default.contents(atPath: path), data.count < 1_000_000, + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { continue } + let layers = (json["layers"] as? [[String: Any]]) ?? [] + let bytes = layers.reduce(0) { $0 + (JSONValue.int($1["size"]) ?? 0) } + (JSONValue.int((json["config"] as? [String: Any])?["size"]) ?? 0) + guard bytes > 0 else { continue } + let name = (namespace == "library" ? "" : namespace + "/") + model + ":" + tag + found.append(ModelFile(name: name, source: "Ollama", path: path, bytes: bytes, modified: facts(path)?.modified ?? 0)) + } + } + } + } + return found + } + + /// LM Studio: `//` holds the model's files. + static func lmStudio(_ folder: String) -> [ModelFile] { + var found: [ModelFile] = [] + for publisher in children(folder) where isFolder(folder + "/" + publisher) { + for repository in children(folder + "/" + publisher) where isFolder(folder + "/" + publisher + "/" + repository) { + let path = folder + "/" + publisher + "/" + repository + let sum = total(path) + if sum.bytes > 0 { + found.append(ModelFile(name: publisher + "/" + repository, source: "LM Studio", path: path, bytes: sum.bytes, modified: sum.modified)) + } + } + } + return found + } + + /// The Hugging Face cache: `models----/blobs` holds the files, `snapshots` links to them. + static func huggingFace(_ folder: String) -> [ModelFile] { + children(folder).filter { $0.hasPrefix("models--") }.compactMap { entry in + let path = folder + "/" + entry + let sum = total(path + "/blobs") + guard sum.bytes > 0 else { return nil } + let name = entry.dropFirst("models--".count).replacingOccurrences(of: "--", with: "/") + return ModelFile(name: name, source: "Hugging Face cache", path: path, bytes: sum.bytes, modified: sum.modified) + } + } + + /// llama.cpp's download cache: each `.gguf` file is a model. + static func llamaCpp(_ folder: String) -> [ModelFile] { + children(folder).filter { $0.lowercased().hasSuffix(".gguf") }.compactMap { entry in + let path = folder + "/" + entry + guard let facts = facts(path), facts.bytes > 0 else { return nil } + return ModelFile(name: entry, source: "llama.cpp", path: path, bytes: facts.bytes, modified: facts.modified) + } + } + + // MARK: Which requests a file answers for + + /// A model's name in pieces, without its publisher, its file ending and the words that say nothing + /// ("latest", "gguf"): "bartowski/Qwen3-Coder-30B-Q4_K_M.gguf" is qwen3, coder, 30b, q4, k, m. + static func pieces(_ name: String) -> Set { + var name = name.lowercased() + if let slash = name.lastIndex(of: "/") { name = String(name[name.index(after: slash)...]) } + let parts = name.split { !($0.isLetter || $0.isNumber) }.map(String.init) + return Set(parts.filter { !["gguf", "latest", "mlx", "safetensors", "bin"].contains($0) }) + } + + /// Whether a model named in the request log is this file's: every piece of the shorter name is in the longer + /// one, and they share at least two pieces (or are the same single piece), so "llama" alone matches nothing. + static func same(_ file: String, _ model: String) -> Bool { + let a = pieces(file), b = pieces(model) + guard !a.isEmpty, !b.isEmpty else { return false } + let (short, long) = a.count <= b.count ? (a, b) : (b, a) + guard short.isSubset(of: long) else { return false } + return short.count >= 2 || long.count == 1 + } + + /// The files with when each last ran, from when each model in the log last finished a request. + static func marked(_ files: [ModelFile], lastRan: [String: Double]) -> [ModelFile] { + files.map { file in + var file = file + file.lastRan = lastRan.filter { same(file.name, $0.key) }.values.max() + return file + } + } +} diff --git a/App/ModelsPage.swift b/App/ModelsPage.swift new file mode 100644 index 0000000..c96fc38 --- /dev/null +++ b/App/ModelsPage.swift @@ -0,0 +1,304 @@ +import Foundation + +/// The Models page: one row for each model across every machine, the model files each machine keeps on disk, and +/// "Will it fit?", an estimate of whether a model would fit on a machine before it is loaded there. +/// +/// Everything rests on what Tokenmeter already has: the saved requests, the memory each server reported while a +/// model was loaded, and the sizes of the files the model managers keep. Nothing is loaded, started or asked of +/// a model to find any of it out. + +/// One model, from every request for it in the range. +struct ModelRow: Codable, Equatable, Identifiable { + var id: String { name } + var name: String + var requests: Int + /// Tokens written per second, and seconds to the first token, in the middle request. + var typicalWrite: Double? + var typicalFirstToken: Double? + /// The share of prompt tokens the cache already held, 0 to 1. + var cacheRate: Double? + var tokensPerWattHour: Double? + /// Requests whose ending is known, and the share of them that didn't finish on their own. + var known: Int + var notFinished: Double? + /// When a request for it last finished, seconds since 1970. + var lastRan: Double? + /// The machines whose request log names it, by name. + var machines: [String] +} + +/// What a server held in memory with a model loaded at a context size, as it reported it. +struct ModelFootprint: Codable, Equatable { + var model: String + var engine: String + /// The context the model was loaded with; 0 where the server didn't say. + var context: Int + /// The most memory seen at that context. + var memoryGB: Double + var seen: Double +} + +/// A machine as the page needs it: how much memory it has, its model files and what it has seen models take. +struct ModelMachine: Codable, Equatable, Identifiable { + /// "here", or the mesh member's id. + var id: String + var name: String + var memoryGB: Double + /// The graphics card's own memory; nil where it shares the system's. + var gpuMemoryGB: Double? + var gpuName: String? + var files: [ModelFile] + var footprints: [ModelFootprint] + /// When each model in this machine's request log last finished a request, over everything it keeps. + var ran: [String: Double] = [:] + /// When the files were last looked at; nil while the first look is still running or the machine hasn't answered. + var scanned: Double? + + /// Where a model's weights go: the graphics card's memory where it has its own, else the machine's. + var room: Double { (gpuMemoryGB ?? 0) > 0 ? gpuMemoryGB ?? 0 : memoryGB } + var roomName: String { (gpuMemoryGB ?? 0) > 0 ? "graphics memory" : "memory" } + var bytes: Int { files.reduce(0) { $0 + $1.bytes } } +} + +/// Whether a model would fit on a machine, with what the answer rests on. +struct ModelFit: Codable, Equatable, Identifiable { + var id: String { machineID } + var machineID: String + var machine: String + /// "fits", "tight", "no" or "unknown". + var verdict: String + var needGB: Double? + var roomGB: Double + var roomName: String + /// "measured" (it ran there), "calculated" (from what it took elsewhere or at another context) or "estimate" + /// (from its file size alone). + var grade: String + /// One sentence on what the figure rests on. + var basis: String +} + +/// `GET /models`. +struct ModelsReport: Codable, Equatable { + var range: String + var rows: [ModelRow] + var machines: [ModelMachine] + /// Days without a request after which a model file is marked as not used lately. + var idleDays: Int + /// The models "Will it fit?" can be asked about: the ones that ran, then the ones only on disk. + var choices: [String] + /// The bytes of the files no request was seen for in `idleDays` days, every machine together. + var idleBytes: Int + /// True while the saved requests are still being read. + var reading: Bool = false +} + +/// `GET /models/fit?model=[&context=]`. +struct ModelFitReport: Codable, Equatable { + var model: String + /// The context asked about; nil for the one it was seen with. + var context: Int? + /// The contexts it has been seen loaded with, smallest first. + var seenContexts: [Int] + var fits: [ModelFit] +} + +enum ModelsPage { + /// The rows, busiest model first: the figures from the requests of the range, when each last ran and where + /// from what every machine's own log says. + static func rows(_ analysis: RequestAnalysis, machines: [ModelMachine]) -> [ModelRow] { + let endings = Dictionary(analysis.reliability.models.map { ($0.id, $0.endings) }, uniquingKeysWith: { first, _ in first }) + return analysis.models.map { group in + let holders = machines.filter { $0.ran[group.id] != nil } + return ModelRow(name: group.id, requests: group.requests, typicalWrite: group.typicalWrite, typicalFirstToken: group.typicalFirstToken, + cacheRate: group.cacheRate, tokensPerWattHour: group.tokensPerWattHour, known: endings[group.id]?.known ?? 0, + notFinished: endings[group.id]?.share, lastRan: holders.compactMap { $0.ran[group.id] }.max(), + machines: holders.map(\.name)) + } + } + + /// Whether a file hasn't answered a request in `days` days: it never ran and was downloaded longer ago than + /// that, or last ran longer ago. + static func idle(_ file: ModelFile, now: Double, days: Double = ModelFiles.idleDays) -> Bool { + now - (file.lastRan ?? file.modified) > days * 86400 + } + + static func idleBytes(_ machines: [ModelMachine], now: Double) -> Int { + machines.flatMap(\.files).filter { idle($0, now: now) }.reduce(0) { $0 + $1.bytes } + } + + /// The contexts a model has been seen loaded with on any of the machines. + static func contexts(_ model: String, machines: [ModelMachine]) -> [Int] { + Set(machines.flatMap(\.footprints).filter { ($0.model == model || ModelFiles.same($0.model, model)) && $0.context > 0 }.map(\.context)).sorted() + } + + /// When each model in the log last finished a request, over everything saved. + static func lastRan(_ requests: [LoggedRequest]) -> [String: Double] { + var last: [String: Double] = [:] + for row in requests { last[row.model] = max(last[row.model] ?? 0, row.time) } + return last + } + + /// The names "Will it fit?" offers: models that ran, then files nothing in the log matches, without repeats. + static func choices(rows: [ModelRow], machines: [ModelMachine]) -> [String] { + var names = rows.map(\.name) + for file in machines.flatMap(\.files).sorted(by: { $0.name < $1.name }) where !names.contains(where: { ModelFiles.same(file.name, $0) || $0 == file.name }) { + names.append(file.name) + } + return names + } + + /// "32.4 GB", "274 MB": a file's size. + static func size(_ bytes: Int) -> String { + let value = Double(bytes) + if value >= 1e11 { return String(format: "%.0f GB", value / 1e9) } + if value >= 1e8 { return String(format: "%.1f GB", value / 1e9) } + return "\(max(1, Int((value / 1e6).rounded()))) MB" + } + + /// "just now", "12 minutes ago", "3 hours ago", "yesterday", "48 days ago". + static func ago(_ time: Double, now: Double = Date().timeIntervalSince1970) -> String { + let seconds = max(0, now - time) + if seconds < 90 { return "just now" } + if seconds < 3600 { return "\(Int((seconds / 60).rounded())) minutes ago" } + let hours = Int((seconds / 3600).rounded()), days = Int((seconds / 86400).rounded()) + if seconds < 86400 { return hours == 1 ? "an hour ago" : "\(hours) hours ago" } + return days == 1 ? "yesterday" : "\(days) days ago" + } + + static func gigabytes(_ value: Double) -> String { String(format: value >= 100 ? "%.0f GB" : "%.1f GB", value) } + static func tokens(_ count: Int) -> String { NumberFormatter.localizedString(from: NSNumber(value: count), number: .decimal) } +} + +enum ModelFootprints { + static let most = 300 + + /// The footprints with what the servers report now added: for each model, engine and context the most memory + /// seen. A server with several models counted, or none loaded, says nothing about one model and is left out. + static func noted(_ old: [ModelFootprint], servers: [StatusReport.Server], now: Double) -> [ModelFootprint] { + var kept = old + for server in servers where server.status == "online" { + guard let memory = server.memoryUsedGB, memory > 0.1, !server.model.isEmpty, !server.model.hasSuffix(" models"), + server.model != "No model loaded" else { continue } + let context = server.usableContext ?? server.contextTokens ?? 0 + if let index = kept.firstIndex(where: { $0.model == server.model && $0.engine == server.engine && $0.context == context }) { + kept[index].memoryGB = max(kept[index].memoryGB, memory) + kept[index].seen = now + } else { + kept.append(ModelFootprint(model: server.model, engine: server.engine, context: context, memoryGB: memory, seen: now)) + } + } + if kept.count > most { kept = Array(kept.sorted { $0.seen > $1.seen }.prefix(most)) } + return kept + } +} + +enum ModelFitting { + /// From 90% of the room a model counts as tight: the rest is what the system and other programs hold. + static let comfortable = 0.9 + /// A file-size estimate adds this much for what a loaded model holds besides its weights. + static let beside = 1.1 + + /// Whether `model` would fit on `machine` at `context` tokens (nil: at whatever context it was seen with). + static func fit(model: String, context: Int?, on machine: ModelMachine, everywhere: [ModelMachine]) -> ModelFit { + // The names that stand for the model: its own where something carries it, else the closest of the names + // that match it (the fewest pieces apart), so "qwen3:30b" isn't answered from "qwen3-coder:30b" while + // its own figures are there. + func apart(_ name: String) -> Int? { + if name == model { return 0 } + guard ModelFiles.same(name, model) else { return nil } + return 1 + ModelFiles.pieces(name).symmetricDifference(ModelFiles.pieces(model)).count + } + func nearest(_ names: [String]) -> Set { + let known = names.compactMap { name in apart(name).map { (name, $0) } } + guard let least = known.map(\.1).min() else { return [] } + return Set(known.filter { $0.1 == least }.map(\.0)) + } + let printed = nearest(everywhere.flatMap(\.footprints).map(\.model)) + let filed = nearest(everywhere.flatMap(\.files).map(\.name)) + /// " (matched to …)" where the figures are another name's. + func matched(_ name: String) -> String { name == model ? "" : " Matched to \(name)." } + func closest(_ prints: [ModelFootprint]) -> ModelFootprint? { + guard let context else { return prints.max { $0.memoryGB < $1.memoryGB } } + // The smallest context that covers the one asked for, else the largest seen. + return prints.filter { $0.context >= context }.min { $0.context < $1.context } ?? prints.max { $0.context < $1.context } + } + let own = machine.footprints.filter { printed.contains($0.model) } + let others = everywhere.filter { $0.id != machine.id } + let elsewhere = others.flatMap { other in other.footprints.filter { printed.contains($0.model) }.map { (print: $0, machine: other.name) } } + let files = ([machine] + others).flatMap(\.files).filter { filed.contains($0.name) } + let fileGB = files.map { Double($0.bytes) / 1e9 }.max() + + var need: Double?, grade = "estimate", basis = "" + func scaled(_ print: ModelFootprint, _ place: String) -> Bool { + guard let context, print.context > 0, print.context != context, let fileGB, print.memoryGB > fileGB else { return false } + let each = (print.memoryGB - fileGB) / Double(print.context) + need = fileGB + each * Double(context) + grade = "calculated" + basis = "\(place) it took \(ModelsPage.gigabytes(print.memoryGB)) at \(ModelsPage.tokens(print.context)) tokens of context, and its file is \(ModelsPage.gigabytes(fileGB)): the rest is scaled to \(ModelsPage.tokens(context)) tokens." + matched(print.model) + return true + } + if let print = closest(own) { + if context == nil || print.context == 0 || print.context >= (context ?? 0) { + need = print.memoryGB + grade = "measured" + basis = "It ran here" + (print.context > 0 ? " at \(ModelsPage.tokens(print.context)) tokens of context" : "") + " and took \(ModelsPage.gigabytes(print.memoryGB))." + matched(print.model) + } else if !scaled(print, "Here") { + need = print.memoryGB + grade = "calculated" + basis = "It ran here at \(ModelsPage.tokens(print.context)) tokens of context and took \(ModelsPage.gigabytes(print.memoryGB)); a larger context takes more, and how much isn't known." + matched(print.model) + } + } else if let found = closest(elsewhere.map(\.print)), let place = elsewhere.first(where: { $0.print == found })?.machine { + if !scaled(found, "On \(place)") { + need = found.memoryGB + grade = "calculated" + basis = "On \(place) it took \(ModelsPage.gigabytes(found.memoryGB))" + (found.context > 0 ? " at \(ModelsPage.tokens(found.context)) tokens of context." : ".") + matched(found.model) + } + } else if let fileGB { + need = fileGB * beside + basis = "From its file size alone (\(ModelsPage.gigabytes(fileGB))). What the context takes on top isn't known until it has run once." + } + guard let need, machine.room > 0 else { + return ModelFit(machineID: machine.id, machine: machine.name, verdict: "unknown", needGB: need, roomGB: machine.room, roomName: machine.roomName, + grade: "estimate", basis: need == nil ? "It hasn't run on any machine and no file of it was found, so there is nothing to go by." : "This machine hasn't said how much memory it has.") + } + let verdict = need <= machine.room * comfortable ? "fits" : need <= machine.room ? "tight" : "no" + return ModelFit(machineID: machine.id, machine: machine.name, verdict: verdict, needGB: need, roomGB: machine.room, roomName: machine.roomName, + grade: grade, basis: basis) + } +} + +/// Keeps the footprints: fed the servers at each look the service takes at them, saved in the history database +/// (a note of a few kilobytes) when something new was seen, at most once a minute. +@MainActor +final class ModelFootprintStore { + static let shared = ModelFootprintStore() + static let noteName = "model footprints" + + private(set) var footprints: [ModelFootprint] = [] + private var loaded = false + private var saved = Date.distantPast + + private func load() { + guard !loaded else { return } + loaded = true + if let text = Database.shared?.note(Self.noteName), let kept = try? JSONDecoder().decode([ModelFootprint].self, from: Data(text.utf8)) { + footprints = kept + } + } + + var current: [ModelFootprint] { + load() + return footprints + } + + func note(_ servers: [StatusReport.Server], now: Date = Date()) { + load() + let before = footprints.map { ModelFootprint(model: $0.model, engine: $0.engine, context: $0.context, memoryGB: $0.memoryGB, seen: 0) } + footprints = ModelFootprints.noted(footprints, servers: servers, now: now.timeIntervalSince1970) + let after = footprints.map { ModelFootprint(model: $0.model, engine: $0.engine, context: $0.context, memoryGB: $0.memoryGB, seen: 0) } + // Only a new model, context or a higher mark is worth writing; when each was last seen can wait for one. + guard after != before, now.timeIntervalSince(saved) >= 60 || saved == .distantPast else { return } + saved = now + if let data = try? JSONEncoder().encode(footprints) { Database.shared?.setNote(Self.noteName, String(decoding: data, as: UTF8.self)) } + } +} diff --git a/App/ModelsView.swift b/App/ModelsView.swift new file mode 100644 index 0000000..4db5abd --- /dev/null +++ b/App/ModelsView.swift @@ -0,0 +1,278 @@ +import SwiftUI + +// Models: a row for each model that answered a request, on any machine; "Will it fit?", whether a model would fit +// on each machine before it is loaded there; and the model files each machine keeps on disk, with the ones nothing +// has asked for in a month marked. Laid out in App/ModelsPage.swift and shared with the KDE window +// (Linux/kde/ui/ModelsPage.qml); the background service answers it as `GET /models` and `GET /models/fit`. + +/// Reads the Models page from the service. +enum ModelsLink { + static func read(range: UsageRange) async -> ModelsReport? { + let path = "/models?range=" + range.rawValue + return await Task.detached { () -> ModelsReport? in + guard let reply = ServiceLink.request("GET", path, timeout: 8), reply.code == 200 else { return nil } + return try? JSONDecoder().decode(ModelsReport.self, from: reply.body) + }.value + } + + static func fit(model: String, context: Int) async -> ModelFitReport? { + let name = model.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? model + let path = "/models/fit?model=" + name + (context > 0 ? "&context=\(context)" : "") + return await Task.detached { () -> ModelFitReport? in + guard let reply = ServiceLink.request("GET", path, timeout: 8), reply.code == 200 else { return nil } + return try? JSONDecoder().decode(ModelFitReport.self, from: reply.body) + }.value + } +} + +struct ModelsView: View { + /// The range picked last here, and the one picked last on any history page (`SharedRange`), which wins. + @AppStorage("modelsRange") private var ownRange: UsageRange = .last30Days + @AppStorage(SharedRange.key) private var sharedRange = "" + private var range: UsageRange { UsageRange(rawValue: sharedRange) ?? ownRange } + private var rangePicked: Binding { + Binding(get: { range }, set: { ownRange = $0; sharedRange = $0.rawValue }) + } + + @State private var report: ModelsReport? + /// The model "Will it fit?" is asked about ("" until one is picked: the busiest), and the context (0: as loaded). + @State private var asked = "" + @State private var context = 0 + @State private var fit: ModelFitReport? + + private static let contexts = [0, 8192, 16384, 32768, 65536, 131_072, 262_144] + private var model: String { asked.isEmpty ? report?.choices.first ?? "" : asked } + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 14) { + header + if let report { + modelsCard(report).card() + if !report.choices.isEmpty { fitCard(report).card() } + ForEach(report.machines) { machine in + filesCard(machine, idleDays: report.idleDays).card() + } + Text("Model files are found by listing the folders of Ollama, LM Studio, the Hugging Face cache and llama.cpp and reading their sizes; no model file is opened, and Tokenmeter never deletes one. A file counts as run when a request named a model it matches.") + .font(.sized(.caption)).foregroundStyle(RoomColors.faint).fixedSize(horizontal: false, vertical: true) + } else { + Text("The Tokenmeter service hasn't answered yet.") + .foregroundStyle(.secondary).frame(maxWidth: .infinity).padding(.top, 60) + } + } + .padding(.horizontal, 20) + .padding(.vertical, 24) + .frame(maxWidth: 1180, alignment: .leading) + .frame(maxWidth: .infinity) + } + .task(id: range) { + while !Task.isCancelled { + if let now = await ModelsLink.read(range: range) { report = now } + try? await Task.sleep(nanoseconds: 15_000_000_000) + } + } + .task(id: "\(model)|\(context)") { + guard !model.isEmpty else { return } + if let now = await ModelsLink.fit(model: model, context: context) { fit = now } + } + } + + private var header: some View { + VStack(alignment: .leading, spacing: 4) { + Text("Models").font(.system(size: TextLook.pt(26), weight: .bold)) + Text("Every model that answered a request, whether one would fit on a machine, and the model files on disk") + .font(.system(size: TextLook.pt(15))).foregroundStyle(RoomColors.blue) + } + } + + // MARK: The models + + private func modelsCard(_ report: ModelsReport) -> some View { + VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 12) { + Label("Models", systemImage: "square.stack.3d.up").font(.sized(.headline)) + Picker("Time Range", selection: rangePicked) { + ForEach(UsageRange.allCases) { Text($0.title).tag($0) } + } + .pickerStyle(.segmented).labelsHidden().fixedSize() + Spacer(minLength: 0) + if report.reading { + Text("Reading saved history…").font(.sized(.caption)).foregroundStyle(RoomColors.amber) + } + } + if report.rows.isEmpty { + Text("No model finished a request in this range.").foregroundStyle(.secondary) + } else { + Grid(alignment: .trailing, horizontalSpacing: 18, verticalSpacing: 8) { + GridRow { + Text("Model").gridColumnAlignment(.leading) + Text("Requests"); Text("Write tok/s"); Text("First Token"); Text("Cache"); Text("Tok/Wh"); Text("Not Finished"); Text("Last Ran") + Text("Machines").gridColumnAlignment(.leading) + }.foregroundStyle(.secondary) + ForEach(report.rows) { row in modelRow(row) } + }.font(.sized(.callout).monospacedDigit()) + } + Text("One row for each model, over every machine that shares its history. Write speed and first token are the middle request; Not Finished is the share of requests that were cut off, aborted or failed, among those that say how they ended.") + .font(.sized(.caption)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + } + + private func modelRow(_ row: ModelRow) -> some View { + let troubled = row.known >= 5 && (row.notFinished ?? 0) >= 0.1 + let write: String = row.typicalWrite.map { String(format: "%.1f", $0) } ?? "—" + let first: String = row.typicalFirstToken.map(shortDuration) ?? "—" + let cache: String = row.cacheRate.map { String(format: "%.0f%%", $0 * 100) } ?? "—" + let energy: String = row.tokensPerWattHour.map { compactTokens(Int($0)) } ?? "—" + let ended: String = row.notFinished.map { String(format: "%.0f%%", $0 * 100) } ?? "—" + let last: String = row.lastRan.map { ModelsPage.ago($0) } ?? "—" + let machines: String = row.machines.isEmpty ? "—" : row.machines.joined(separator: ", ") + return GridRow { + Text(row.name).lineLimit(1).truncationMode(.middle).frame(maxWidth: 260, alignment: .leading) + Text(row.requests.formatted()) + Text(write).fontWeight(.semibold) + Text(first) + Text(cache) + Text(energy) + Text(ended).foregroundStyle(troubled ? RoomColors.amber : RoomColors.ink) + Text(last) + Text(machines).lineLimit(1).truncationMode(.tail).frame(maxWidth: 200, alignment: .leading) + } + } + + // MARK: Will it fit? + + private func fitCard(_ report: ModelsReport) -> some View { + let picked = Binding(get: { model }, set: { asked = $0 }) + return VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 10) { + Label("Will It Fit?", systemImage: "arrow.down.to.line.compact").font(.sized(.headline)) + Spacer(minLength: 12) + Picker("Model", selection: picked) { + ForEach(report.choices, id: \.self) { Text($0).tag($0) } + } + .labelsHidden().frame(maxWidth: 340) + Picker("Context", selection: $context) { + ForEach(Self.contexts, id: \.self) { size in + Text(size == 0 ? "Context as it was loaded" : "\(size.formatted()) tokens of context").tag(size) + } + } + .labelsHidden().frame(width: 230) + } + ForEach(fit?.fits ?? []) { one in fitRow(one) } + Text("Worked out from the memory each server reported while the model was loaded, and from the size of its file where it never ran. Nothing is loaded to find out. Tight means over nine tenths of the memory; a model that fits may still be slow if other programs hold memory too.") + .font(.sized(.caption)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + } + + private static func word(_ verdict: String) -> String { + switch verdict { + case "fits": return "Fits" + case "tight": return "Tight" + case "no": return "Won't fit" + default: return "Can't say" + } + } + + private static func colour(_ verdict: String) -> Color { + switch verdict { + case "fits": return RoomColors.green + case "tight": return RoomColors.amber + case "no": return RoomColors.red + default: return RoomColors.grey + } + } + + private static func gradeWord(_ grade: String) -> String { + grade == "measured" ? "measured here" : grade == "calculated" ? "worked out" : "rough estimate" + } + + private func fitRow(_ one: ModelFit) -> some View { + let colour = Self.colour(one.verdict) + let share: Double = one.roomGB > 0 ? min(1, (one.needGB ?? 0) / one.roomGB) : 0 + let figure: String = one.needGB.map { "about \(ModelsPage.gigabytes($0)) of \(ModelsPage.gigabytes(one.roomGB)) \(one.roomName)" } ?? "" + return HStack(alignment: .top, spacing: 12) { + Text(Self.word(one.verdict)).font(.sized(.caption).weight(.bold)).foregroundStyle(colour) + .frame(width: 86, height: 22) + .background(colour.opacity(0.16), in: Capsule()) + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 8) { + Text(one.machine).fontWeight(.semibold) + if one.needGB != nil && one.roomGB > 0 { + Text(figure).foregroundStyle(RoomColors.soft) + } + if one.needGB != nil { + Text("· " + Self.gradeWord(one.grade)).font(.sized(.caption)).foregroundStyle(RoomColors.muted) + } + } + if one.needGB != nil && one.roomGB > 0 { + GeometryReader { space in + ZStack(alignment: .leading) { + Capsule().fill(RoomColors.raised) + Capsule().fill(colour).frame(width: space.size.width * share) + } + } + .frame(height: 5) + } + Text(one.basis).font(.sized(.caption)).foregroundStyle(RoomColors.muted).fixedSize(horizontal: false, vertical: true) + } + } + .padding(10) + .frame(maxWidth: .infinity, alignment: .leading) + .background(RoomColors.field, in: RoundedRectangle(cornerRadius: 9)) + .overlay(RoundedRectangle(cornerRadius: 9).stroke(RoomColors.line)) + .accessibilityElement(children: .ignore) + .accessibilityLabel("\(one.machine): \(Self.word(one.verdict)). \(one.basis)") + } + + // MARK: The files + + private func filesCard(_ machine: ModelMachine, idleDays: Int) -> some View { + let now = Date().timeIntervalSince1970 + let unused: Int = machine.files.filter { ModelsPage.idle($0, now: now, days: Double(idleDays)) }.reduce(0) { $0 + $1.bytes } + let count: String = "\(machine.files.count) " + (machine.files.count == 1 ? "model" : "models") + ", " + ModelsPage.size(machine.bytes) + return VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 10) { + Label("Model Files on \(machine.name)", systemImage: "internaldrive").font(.sized(.headline)) + if !machine.files.isEmpty { + Text(count).font(.sized(.caption)).foregroundStyle(RoomColors.muted) + } + Spacer(minLength: 0) + if unused > 0 { + Text("\(ModelsPage.size(unused)) not used in \(idleDays) days").font(.sized(.caption)).foregroundStyle(RoomColors.amber) + .padding(.horizontal, 8).padding(.vertical, 2) + .background(RoomColors.amber.opacity(0.14), in: Capsule()) + } + } + if machine.files.isEmpty { + Text(Self.noFiles(machine)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } else { + Grid(alignment: .trailing, horizontalSpacing: 18, verticalSpacing: 8) { + GridRow { + Text("Model").gridColumnAlignment(.leading) + Text("Kept By").gridColumnAlignment(.leading) + Text("Size"); Text("Downloaded"); Text("Last Ran") + }.foregroundStyle(.secondary) + ForEach(machine.files) { file in fileRow(file, now: now, idleDays: idleDays) } + }.font(.sized(.callout).monospacedDigit()) + } + } + } + + private static func noFiles(_ machine: ModelMachine) -> String { + if machine.scanned != nil { return "No model files found in the folders of Ollama, LM Studio, Hugging Face or llama.cpp." } + return machine.id == "here" ? "Looking through the model folders…" : "Waiting for \(machine.name) to answer. It needs Tokenmeter 0.9.10 or later." + } + + private func fileRow(_ file: ModelFile, now: Double, idleDays: Int) -> some View { + let idle = ModelsPage.idle(file, now: now, days: Double(idleDays)) + let last: String = file.lastRan.map { ModelsPage.ago($0, now: now) } ?? "no request seen" + let downloaded: String = file.modified > 0 ? ModelsPage.ago(file.modified, now: now) : "—" + return GridRow { + Text(file.name).lineLimit(1).truncationMode(.middle).frame(maxWidth: 380, alignment: .leading).help(file.path) + Text(file.source) + Text(ModelsPage.size(file.bytes)) + Text(downloaded) + Text(last).foregroundStyle(idle ? RoomColors.amber : RoomColors.ink) + } + } +} diff --git a/App/RequestLog.swift b/App/RequestLog.swift index 370bc38..3972816 100644 --- a/App/RequestLog.swift +++ b/App/RequestLog.swift @@ -345,6 +345,27 @@ final class RequestLogStore: ObservableObject { return found } + private var lastCounted: (at: Date, until: Double, models: [String: Double])? + + /// When each model last finished a request, over everything kept. The part in the database is asked again + /// every five minutes at most. + func lastByModel(now: Date = Date()) -> [String: Double] { + var found: [String: Double] = [:] + if windowStart > 0, let database = Database.shared { + if lastCounted.map({ abs(now.timeIntervalSince($0.at)) > 300 || $0.until != windowStart }) ?? true { + let until = windowStart + var models: [String: Double] = [:] + database.read { + $0.each("SELECT m, MAX(t) FROM requests WHERE t < ? GROUP BY m", { $0.bind(1, until) }) { models[$0.text(0)] = $0.double(1) } + } + lastCounted = (now, until, models) + } + found = lastCounted?.models ?? [:] + } + for row in rows { found[row.model] = max(found[row.model] ?? 0, row.time) } + return found + } + /// Every model a kept request names. func models() -> [String] { var found = Set(rows.map(\.model)) diff --git a/App/StatusJSON.swift b/App/StatusJSON.swift index 9795730..8a900bf 100644 --- a/App/StatusJSON.swift +++ b/App/StatusJSON.swift @@ -438,7 +438,7 @@ struct LocalResponse { extension StatusReport { /// Tokenmeter's version. The Mac app reads it from its Info.plist, which build-library-app.sh writes; the /// Linux service has no Info.plist, so it uses `releaseVersion`. Keep that in step with the build scripts. - static let releaseVersion = "0.9.9" + static let releaseVersion = "0.9.10" static var appVersion: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? releaseVersion } diff --git a/App/Store.swift b/App/Store.swift index d1a753f..19376f8 100644 --- a/App/Store.swift +++ b/App/Store.swift @@ -2,7 +2,7 @@ import AppKit import SwiftUI enum Page: String, CaseIterable, Identifiable { - case welcome, home, insights, usage, performance, sessions, lab, room, gizmo, setup, agents, mesh, settings + case welcome, home, insights, usage, performance, models, sessions, lab, room, gizmo, setup, agents, mesh, settings var id: String { rawValue } var title: String { switch self { @@ -11,6 +11,7 @@ enum Page: String, CaseIterable, Identifiable { case .insights: return "Insights" case .usage: return "Usage" case .performance: return "Performance" + case .models: return "Models" case .sessions: return "Sessions" case .lab: return "Tuning Lab" case .gizmo: return "Gizmo" @@ -28,6 +29,7 @@ enum Page: String, CaseIterable, Identifiable { case .insights: return "lightbulb" case .usage: return "chart.bar.xaxis" case .performance: return "speedometer" + case .models: return "square.stack.3d.up" case .sessions: return "timeline.selection" case .lab: return "flask" case .gizmo: return "star.circle" @@ -40,8 +42,8 @@ enum Page: String, CaseIterable, Identifiable { } /// The sidebar group; nil for the pages at the top. var section: String? { self == .settings || self == .agents || self == .mesh || self == .setup ? "App" : nil } - /// The pages ⌘1 to ⌘9 open, in the sidebar's order (Welcome, Setup, Agents and Mesh have no number). - static var numbered: [Page] { allCases.filter { $0 != .welcome && $0 != .setup && $0 != .agents && $0 != .mesh } } + /// The pages ⌘1 to ⌘9 open, in the sidebar's order (Welcome, Models, Setup, Agents and Mesh have no number). + static var numbered: [Page] { allCases.filter { $0 != .welcome && $0 != .models && $0 != .setup && $0 != .agents && $0 != .mesh } } static let sections = ["App"] } diff --git a/Linux/ModelRoutes.swift b/Linux/ModelRoutes.swift new file mode 100644 index 0000000..eb61530 --- /dev/null +++ b/Linux/ModelRoutes.swift @@ -0,0 +1,97 @@ +#if os(Linux) || TOKENMETER_SERVICE +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +/// The Models page, for the KDE window and the Mac app (see App/ModelsPage.swift, App/ModelFiles.swift): +/// - `GET /models[?range=]`: a row for each model that answered a request in the range, on any machine that +/// shares its history; then each machine of the mesh with its model files and what it has seen models hold in +/// memory. Another member's part is the one it last gave (asked again at most every 30 s while the page reads it). +/// - `GET /models/fit?model=[&context=]`: whether the model would fit on each machine. +/// - `GET /mesh/models`: what a member asks of this one: its own files, footprints and memory. Members only. +/// +/// Nothing here loads a model, starts a server or sends a prompt: it reads folders, the saved requests and what +/// the servers already reported. +@MainActor +enum ModelRoutes { + private static var remote: [String: ModelMachine] = [:] + private static var asked: [String: Date] = [:] + + /// This machine: its memory, its model files with when each last ran, and its footprints. + static func here(now: Date = Date()) -> ModelMachine { + let info = MachineMonitor.shared.current?.info + let scan = ModelFiles.current(now: now) + let ran = RequestLogStore.shared.lastByModel(now: now) + return ModelMachine(id: "here", name: StatusReport.machineName, memoryGB: info?.memoryTotalGB ?? 0, + gpuMemoryGB: info?.gpuMemoryTotalGB, gpuName: info?.gpuName, + files: ModelFiles.marked(scan.files, lastRan: ran), footprints: ModelFootprintStore.shared.current, + ran: ran, scanned: scan.at?.timeIntervalSince1970) + } + + /// This machine, then the other members of the mesh as each last answered. + static func machines(now: Date = Date()) -> [ModelMachine] { + let mesh = MeshStore.shared.state + var found = [here(now: now)] + for member in mesh.members where !member.removed && member.id != mesh.machineID { + let id = member.id + if (asked[id].map { now.timeIntervalSince($0) > 30 } ?? true) { + asked[id] = now + Task { @MainActor in + if let got = await fetch(id) { remote[id] = got } + } + } + var machine = remote[id] ?? ModelMachine(id: id, name: member.name, memoryGB: 0, files: [], footprints: []) + machine.id = id + machine.name = member.name + found.append(machine) + } + return found + } + + private static func fetch(_ id: String) async -> ModelMachine? { + guard let key = MeshStore.shared.state.keys[id], let place = FleetStore.url(for: key), + var parts = URLComponents(url: place, resolvingAgainstBaseURL: false) else { return nil } + parts.path = "/mesh/models" + parts.query = nil + guard let url = parts.url else { return nil } + var request = URLRequest(url: url) + request.timeoutInterval = 6 + let asked = request + guard let (data, response) = try? await MeshFetch.data(for: asked, peer: key), (response as? HTTPURLResponse)?.statusCode == 200 else { return nil } + return try? JSONDecoder().decode(ModelMachine.self, from: data) + } + + static func report(range: UsageRange, now: Date = Date()) -> ModelsReport { + let machines = machines(now: now) + let scope = MachineScope(nil) + let analysis = PerformanceTally.analysis(range: range, scope: scope, server: nil, activity: FleetStore.shared.activity(scope), now: now) + let rows = ModelsPage.rows(analysis, machines: machines) + return ModelsReport(range: range.rawValue, rows: rows, machines: machines, idleDays: Int(ModelFiles.idleDays), + choices: ModelsPage.choices(rows: rows, machines: machines), + idleBytes: ModelsPage.idleBytes(machines, now: now.timeIntervalSince1970), reading: HistoryMove.pending) + } + + static func fit(model: String, context: Int?) -> ModelFitReport { + let machines = machines() + return ModelFitReport(model: model, context: context, seenContexts: ModelsPage.contexts(model, machines: machines), + fits: machines.map { ModelFitting.fit(model: model, context: context, on: $0, everywhere: machines) }) + } + + static func start() { + let endpoint = StatusEndpoint.shared + endpoint.route("GET", "/models") { request in + TokenmeterService.json(report(range: request.value("range").flatMap(UsageRange.init(rawValue:)) ?? .last30Days)) + } + endpoint.route("GET", "/models/fit") { request in + guard let model = request.value("model"), !model.isEmpty, model.count < 400 else { return .text("Name a model: /models/fit?model=.\n", code: 400) } + let context = request.value("context").flatMap(Int.init).flatMap { $0 > 0 && $0 <= 10_000_000 ? $0 : nil } + return TokenmeterService.json(fit(model: model, context: context)) + } + endpoint.route("GET", "/mesh/models") { request in + guard MeshStore.shared.member(signing: request) != nil else { return .text("Members of this mesh only.\n", code: 403) } + return TokenmeterService.json(here()) + } + } +} +#endif diff --git a/Linux/Service.swift b/Linux/Service.swift index 4087980..6ba6e19 100644 --- a/Linux/Service.swift +++ b/Linux/Service.swift @@ -207,6 +207,7 @@ enum TokenmeterService { TargetRoutes.start() SpendRoutes.start() SetupRoutes.start() + ModelRoutes.start() // Insights watch from the start, so changes and findings are kept while no app is open. InsightStore.shared.start() // Gizmo listens from the start, so it can react to requests while its page is closed. diff --git a/Linux/kde/app/AppVersion.js b/Linux/kde/app/AppVersion.js index d749c8e..dac9bb3 100644 --- a/Linux/kde/app/AppVersion.js +++ b/Linux/kde/app/AppVersion.js @@ -3,4 +3,4 @@ // update keeps saying the version it is, while the service reports its own (backend.snapshot.version). // scripts/package-linux.sh and package-flatpak.sh write it from the package's version; keep it in step with // StatusReport.releaseVersion when bumping (a unit test checks it). -var version = "0.9.9" +var version = "0.9.10" diff --git a/Linux/kde/app/main.qml b/Linux/kde/app/main.qml index bf0b613..5221b0d 100644 --- a/Linux/kde/app/main.qml +++ b/Linux/kde/app/main.qml @@ -557,6 +557,7 @@ ApplicationWindow { } SidebarRow { Layout.fillWidth: true; page: "usage"; glyph: "usage"; text: "Usage" } SidebarRow { Layout.fillWidth: true; page: "performance"; glyph: "performance"; text: "Performance" } + SidebarRow { Layout.fillWidth: true; page: "models"; glyph: "models"; text: "Models" } SidebarRow { Layout.fillWidth: true; page: "sessions"; glyph: "sessions"; text: "Sessions" } SidebarRow { Layout.fillWidth: true; page: "lab"; glyph: "lab"; text: "Tuning Lab" } SidebarRow { Layout.fillWidth: true; page: "room"; glyph: "room"; text: "Machine Room" } @@ -752,7 +753,7 @@ ApplicationWindow { anchors { left: parent.left; right: parent.right; top: gizmoLine.bottom; bottom: parent.bottom } // A saved engine's id shows that engine's Usage. readonly property var pages: ["monitor", "usage", "engines", "performance", "gizmo", "settings"] - currentIndex: window.current === "setup" ? 16 : window.current === "welcome" ? 15 : window.current === "mesh" ? 14 : window.current === "agents" ? 13 : window.current === "insights" ? 12 : window.digPage ? 9 : window.current === "sessions" ? 10 : window.current === "lab" ? 11 : window.current === "room" ? 8 : window.remote ? 6 : window.serverPage ? 7 : pages.indexOf(window.current) >= 0 ? pages.indexOf(window.current) : 1 + currentIndex: window.current === "models" ? 17 : window.current === "setup" ? 16 : window.current === "welcome" ? 15 : window.current === "mesh" ? 14 : window.current === "agents" ? 13 : window.current === "insights" ? 12 : window.digPage ? 9 : window.current === "sessions" ? 10 : window.current === "lab" ? 11 : window.current === "room" ? 8 : window.remote ? 6 : window.serverPage ? 7 : pages.indexOf(window.current) >= 0 ? pages.indexOf(window.current) : 1 // Each page is built the first time it is opened (LazyPage), so the window opens with one page, not thirteen. LazyPage { id: monitorSlot @@ -863,6 +864,7 @@ ApplicationWindow { onTourRequested: window.perform("tour") } } + LazyPage { id: modelsSlot; sourceComponent: ModelsPage { backend: window.service; active: modelsSlot.current && window.shown } } } DrillPanel { diff --git a/Linux/kde/mock/machines.json b/Linux/kde/mock/machines.json index 0098807..514842f 100644 --- a/Linux/kde/mock/machines.json +++ b/Linux/kde/mock/machines.json @@ -7,7 +7,7 @@ "report": { "schema": 1, "app": "Tokenmeter", - "version": "0.9.9", + "version": "0.9.10", "host": "studio", "chip": "Apple M3 Ultra", "time": "2026-11-13T19:00:00Z", diff --git a/Linux/kde/mock/models.json b/Linux/kde/mock/models.json new file mode 100644 index 0000000..420b7c1 --- /dev/null +++ b/Linux/kde/mock/models.json @@ -0,0 +1,210 @@ +{ + "range": "last30Days", + "rows": [ + { + "name": "Qwen3-Coder-30B-A3B-8bit", + "requests": 8412, + "typicalWrite": 58.3, + "typicalFirstToken": 0.84, + "cacheRate": 0.91, + "tokensPerWattHour": 5120, + "known": 8390, + "notFinished": 0.021, + "lastRan": 1796097283, + "machines": [ + "studio" + ] + }, + { + "name": "qwen3-coder:30b", + "requests": 2967, + "typicalWrite": 71.6, + "typicalFirstToken": 0.42, + "cacheRate": 0.86, + "tokensPerWattHour": 1840, + "known": 2967, + "notFinished": 0.034, + "lastRan": 1796080867, + "machines": [ + "tower" + ] + }, + { + "name": "gemma-3-27b-it", + "requests": 1204, + "typicalWrite": 31.2, + "typicalFirstToken": 1.9, + "cacheRate": 0.44, + "tokensPerWattHour": 3350, + "known": 1190, + "notFinished": 0.128, + "lastRan": 1795908067, + "machines": [ + "studio" + ] + }, + { + "name": "Phi-4-mini-instruct-Q4_K_M.gguf", + "requests": 388, + "typicalWrite": 142.0, + "typicalFirstToken": 0.11, + "cacheRate": 0.2, + "tokensPerWattHour": 6210, + "known": 388, + "notFinished": 0.0, + "lastRan": 1796003107, + "machines": [ + "tower" + ] + }, + { + "name": "nomic-embed-text:latest", + "requests": 96, + "known": 0, + "lastRan": 1796072227, + "machines": [ + "studio" + ] + } + ], + "machines": [ + { + "id": "here", + "name": "studio", + "memoryGB": 128.0, + "gpuName": "Apple M4 Max", + "scanned": 1796098027, + "files": [ + { + "name": "mlx-community/Llama-3.3-70B-Instruct-4bit", + "source": "Hugging Face cache", + "path": "/Users/j/.cache/huggingface/hub/models--mlx-community--Llama-3.3-70B-Instruct-4bit", + "bytes": 39700000000, + "modified": 1777954147 + }, + { + "name": "mlx-community/Qwen3-Coder-30B-A3B-8bit", + "source": "Hugging Face cache", + "path": "/Users/j/.cache/huggingface/hub/models--mlx-community--Qwen3-Coder-30B-A3B-8bit", + "bytes": 32400000000, + "modified": 1791950947, + "lastRan": 1796097283 + }, + { + "name": "deepseek-r1:32b", + "source": "Ollama", + "path": "/Users/j/.ollama/models/manifests/registry.ollama.ai/library/deepseek-r1/32b", + "bytes": 19900000000, + "modified": 1782274147, + "lastRan": 1789704547 + }, + { + "name": "lmstudio-community/gemma-3-27b-it-GGUF", + "source": "LM Studio", + "path": "/Users/j/.lmstudio/models/lmstudio-community/gemma-3-27b-it-GGUF", + "bytes": 17200000000, + "modified": 1787890147, + "lastRan": 1795908067 + }, + { + "name": "nomic-embed-text:latest", + "source": "Ollama", + "path": "/Users/j/.ollama/models/manifests/registry.ollama.ai/library/nomic-embed-text/latest", + "bytes": 274000000, + "modified": 1785730147, + "lastRan": 1796072227 + } + ], + "footprints": [ + { + "model": "Qwen3-Coder-30B-A3B-8bit", + "engine": "oMLX", + "context": 65536, + "memoryGB": 38.6, + "seen": 1796097547 + }, + { + "model": "gemma-3-27b-it", + "engine": "LM Studio", + "context": 16384, + "memoryGB": 19.8, + "seen": 1795908067 + } + ], + "ran": { + "Qwen3-Coder-30B-A3B-8bit": 1796097247, + "gemma-3-27b-it": 1795908067, + "deepseek-r1:32b": 1789704547, + "nomic-embed-text:latest": 1796072227 + } + }, + { + "id": "m-tower", + "name": "tower", + "memoryGB": 64.0, + "gpuMemoryGB": 24.0, + "gpuName": "NVIDIA GeForce RTX 4090", + "scanned": 1796097847, + "files": [ + { + "name": "qwen3-coder:30b", + "source": "Ollama", + "path": "/usr/share/ollama/.ollama/models/manifests/registry.ollama.ai/library/qwen3-coder/30b", + "bytes": 18600000000, + "modified": 1793506147, + "lastRan": 1796080867 + }, + { + "name": "mistral-small:24b", + "source": "Ollama", + "path": "/usr/share/ollama/.ollama/models/manifests/registry.ollama.ai/library/mistral-small/24b", + "bytes": 14300000000, + "modified": 1784002147, + "lastRan": 1791691747 + }, + { + "name": "Phi-4-mini-instruct-Q4_K_M.gguf", + "source": "llama.cpp", + "path": "/home/j/.cache/llama.cpp/Phi-4-mini-instruct-Q4_K_M.gguf", + "bytes": 2500000000, + "modified": 1795061347, + "lastRan": 1796003107 + } + ], + "footprints": [ + { + "model": "qwen3-coder:30b", + "engine": "Ollama", + "context": 32768, + "memoryGB": 21.9, + "seen": 1796080867 + }, + { + "model": "Phi-4-mini-instruct-Q4_K_M.gguf", + "engine": "llama.cpp", + "context": 8192, + "memoryGB": 3.4, + "seen": 1796003107 + } + ], + "ran": { + "qwen3-coder:30b": 1796080867, + "Phi-4-mini-instruct-Q4_K_M.gguf": 1796003107, + "mistral-small:24b": 1791691747 + } + } + ], + "idleDays": 30, + "choices": [ + "Qwen3-Coder-30B-A3B-8bit", + "qwen3-coder:30b", + "gemma-3-27b-it", + "Phi-4-mini-instruct-Q4_K_M.gguf", + "nomic-embed-text:latest", + "deepseek-r1:32b", + "mistral-small:24b", + "mlx-community/Llama-3.3-70B-Instruct-4bit" + ], + "idleBytes": 73900000000, + "reading": false +} \ No newline at end of file diff --git a/Linux/kde/mock/models/fit.json b/Linux/kde/mock/models/fit.json new file mode 100644 index 0000000..690bd7f --- /dev/null +++ b/Linux/kde/mock/models/fit.json @@ -0,0 +1,29 @@ +{ + "model": "Qwen3-Coder-30B-A3B-8bit", + "seenContexts": [ + 32768, + 65536 + ], + "fits": [ + { + "machineID": "here", + "machine": "studio", + "verdict": "fits", + "needGB": 38.6, + "roomGB": 128.0, + "roomName": "memory", + "grade": "measured", + "basis": "It ran here at 65,536 tokens of context and took 38.6 GB." + }, + { + "machineID": "m-tower", + "machine": "tower", + "verdict": "tight", + "needGB": 21.9, + "roomGB": 24.0, + "roomName": "graphics memory", + "grade": "measured", + "basis": "It ran here at 32,768 tokens of context and took 21.9 GB." + } + ] +} \ No newline at end of file diff --git a/Linux/kde/mock/settings.json b/Linux/kde/mock/settings.json index f1f3efb..466438d 100644 --- a/Linux/kde/mock/settings.json +++ b/Linux/kde/mock/settings.json @@ -15,7 +15,7 @@ "addresses": [ "192.168.1.20" ], - "version": "0.9.9", + "version": "0.9.10", "shareHistory": false, "footprint": { "cpuPercent": 0.4, diff --git a/Linux/kde/plasmoid/metadata.json b/Linux/kde/plasmoid/metadata.json index 03f483b..b2cc987 100644 --- a/Linux/kde/plasmoid/metadata.json +++ b/Linux/kde/plasmoid/metadata.json @@ -7,7 +7,7 @@ "Icon": "tokenmeter", "Category": "System Information", "License": "Apache-2.0", - "Version": "0.9.9", + "Version": "0.9.10", "Website": "https://github.com/tokenmeter1/Tokenmeter" }, "X-Plasma-API-Minimum-Version": "6.0", diff --git a/Linux/kde/ui/ModelsPage.qml b/Linux/kde/ui/ModelsPage.qml new file mode 100644 index 0000000..e407e65 --- /dev/null +++ b/Linux/kde/ui/ModelsPage.qml @@ -0,0 +1,309 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import "Format.js" as Format +import "Usage.js" as Usage +import "Look" + +// Models: a row for each model that answered a request, on any machine; "Will it fit?", whether a model would +// fit on each machine before it is loaded there; and the model files each machine keeps on disk, with the ones +// nothing has asked for in a month marked (App/ModelsPage.swift, `GET /models`, `GET /models/fit`). Everything +// comes from what Tokenmeter already has: no model is loaded and nothing is sent to one. +Flickable { + id: page + property Backend backend + property bool active: false + + readonly property var tones: Format.tones(palette.window) + readonly property var room: Format.room + readonly property string range: backend ? backend.rangeFor("models", ["all", "thisMonth", "last30Days", "last7Days", "last3Days", "today"], "last30Days") : "last30Days" + property var report: null + // The model "Will it fit?" is asked about ("" until one is picked: the busiest), the context (0: as it was + // loaded), and the answer. + property string asked: "" + property int context: 0 + property var fit: null + readonly property string model: asked !== "" ? asked : report && report.choices.length > 0 ? report.choices[0] : "" + + function load() { backend.get("/models?range=" + range, function (got) { if (got) page.report = got }) } + function loadFit() { + if (model === "") { fit = null; return } + backend.get("/models/fit?model=" + encodeURIComponent(model) + (context > 0 ? "&context=" + context : ""), function (got) { if (got) page.fit = got }) + } + onRangeChanged: if (active) load() + onModelChanged: loadFit() + onContextChanged: loadFit() + onReportChanged: loadFit() + Connections { target: page.backend; function onConnectedChanged() { if (page.backend.connected && page.active) page.load() } } + Timer { interval: 15000; repeat: true; triggeredOnStart: true; running: page.active && page.backend.running; onTriggered: page.load() } + + function speed(value) { return Format.has(value) ? value.toFixed(1) : "—" } + function percent(value) { return Format.has(value) ? Math.round(value * 100) + "%" : "—" } + function size(bytes) { + if (bytes >= 1e11) return (bytes / 1e9).toFixed(0) + " GB" + if (bytes >= 1e8) return (bytes / 1e9).toFixed(1) + " GB" + return Math.max(1, Math.round(bytes / 1e6)) + " MB" + } + function gigabytes(value) { return Format.has(value) ? (value >= 100 ? value.toFixed(0) : value.toFixed(1)) + " GB" : "—" } + function idle(file) { + return page.report !== null && Date.now() / 1000 - (Format.has(file.lastRan) ? file.lastRan : file.modified) > page.report.idleDays * 86400 + } + function idleBytes(machine) { + var sum = 0 + for (var i = 0; i < machine.files.length; i++) if (idle(machine.files[i])) sum += machine.files[i].bytes + return sum + } + function totalBytes(machine) { + var sum = 0 + for (var i = 0; i < machine.files.length; i++) sum += machine.files[i].bytes + return sum + } + function verdictWord(verdict) { return verdict === "fits" ? "Fits" : verdict === "tight" ? "Tight" : verdict === "no" ? "Won't fit" : "Can't say" } + function verdictColor(verdict) { return verdict === "fits" ? tones.green : verdict === "tight" ? tones.amber : verdict === "no" ? tones.red : tones.grey } + function gradeWord(grade) { return grade === "measured" ? "measured here" : grade === "calculated" ? "worked out" : "rough estimate" } + readonly property var contexts: [0, 8192, 16384, 32768, 65536, 131072, 262144] + + contentWidth: width + contentHeight: column.height + 48 + clip: true + ScrollBar.vertical: ScrollBar {} + readonly property real columnWidth: Math.min(1180, width - 48) + + ColumnLayout { + id: column + x: (page.width - page.columnWidth) / 2 + y: 24 + width: page.columnWidth + spacing: 14 + + ColumnLayout { + Layout.fillWidth: true + spacing: 4 + Label { text: "Models"; font.pixelSize: Look.px(26); font.bold: true } + Label { + Layout.fillWidth: true; wrapMode: Text.Wrap + text: "Every model that answered a request, whether one would fit on a machine, and the model files on disk" + font.pixelSize: Look.px(15); color: page.room.accent + } + } + + Label { + Layout.fillWidth: true; Layout.topMargin: 60 + visible: page.report === null + horizontalAlignment: Text.AlignHCenter; wrapMode: Text.Wrap; opacity: Look.dim(0.6) + text: "The Tokenmeter service hasn't answered yet." + } + + Card { + objectName: "modelsCard" + name: "Models" + Layout.fillWidth: true + visible: page.report !== null + Column { + width: parent.width; spacing: 12 + RowLayout { + width: parent.width + spacing: 0 + Label { text: "Models"; font.bold: true; rightPadding: 14 } + Repeater { + model: Usage.ranges + Button { + text: modelData.title + checkable: true; autoExclusive: true + checked: page.range === modelData.id + onClicked: backend.setRange("models", modelData.id) + flat: !checked + } + } + Item { Layout.fillWidth: true } + Label { + visible: page.report !== null && page.report.reading === true + text: "Reading saved history…"; font.pixelSize: Look.px(11); color: page.tones.amber + } + } + Table { + objectName: "modelsTable" + width: parent.width + visible: rows.length > 0 + columns: [ + { title: "Model", weight: 2.8 }, { title: "Requests", right: true }, { title: "Write tok/s", right: true, bold: true }, + { title: "First Token", right: true }, { title: "Cache", weight: 0.8, right: true }, { title: "Tok/Wh", weight: 0.9, right: true }, + { title: "Not Finished", weight: 1.1, right: true }, { title: "Last Ran", weight: 1.6, right: true }, { title: "Machines", weight: 1.7 } + ] + rows: (page.report ? page.report.rows : []).map(function (m) { + var troubled = Format.has(m.notFinished) && m.known >= 5 && m.notFinished >= 0.1 + return [m.name, Format.grouped(m.requests), page.speed(m.typicalWrite), Format.duration(m.typicalFirstToken), page.percent(m.cacheRate), + Format.has(m.tokensPerWattHour) ? Format.compactTokens(Math.floor(m.tokensPerWattHour)) : "—", + troubled ? { text: page.percent(m.notFinished), color: page.tones.amber } : page.percent(m.notFinished), + Format.has(m.lastRan) ? Format.ago(m.lastRan) : "—", m.machines.length > 0 ? m.machines.join(", ") : "—"] + }) + } + Label { + width: parent.width; wrapMode: Text.Wrap; opacity: Look.dim(0.7) + visible: page.report !== null && page.report.rows.length === 0 + property var entry: Usage.ranges.find(function (r) { return r.id === page.range }) + text: "No model finished a request " + (entry ? entry.phrase : "") + "." + } + Label { + width: parent.width; wrapMode: Text.Wrap; font.pixelSize: Look.px(11); opacity: Look.dim(0.6) + text: "One row for each model, over every machine that shares its history. Write speed and first token are the middle request; Not Finished is the share of requests that were cut off, aborted or failed, among those that say how they ended." + } + } + } + + Card { + objectName: "fitCard" + name: "Will it fit?" + Layout.fillWidth: true + visible: page.report !== null && page.report.choices.length > 0 + Column { + width: parent.width; spacing: 12 + RowLayout { + width: parent.width + spacing: 10 + Label { text: "Will It Fit?"; font.bold: true } + Item { Layout.fillWidth: true } + ComboBox { + objectName: "fitModel" + Accessible.name: "Model" + model: page.report ? page.report.choices : [] + implicitWidth: Math.min(360, page.columnWidth * 0.4) + currentIndex: page.report ? Math.max(0, page.report.choices.indexOf(page.model)) : 0 + onActivated: function (index) { page.asked = page.report.choices[index] } + } + ComboBox { + objectName: "fitContext" + Accessible.name: "Context" + model: page.contexts.map(function (c) { return c === 0 ? "Context as it was loaded" : Format.grouped(c) + " tokens of context" }) + implicitWidth: 230 + currentIndex: Math.max(0, page.contexts.indexOf(page.context)) + onActivated: function (index) { page.context = page.contexts[index] } + } + } + Repeater { + model: page.fit ? page.fit.fits : [] + Rectangle { + objectName: "fit:" + modelData.machineID + width: parent.width + height: line.height + 20 + radius: 9 + color: page.room.field; border.color: page.room.line + Accessible.role: Accessible.StaticText + Accessible.name: modelData.machine + ": " + page.verdictWord(modelData.verdict) + ". " + modelData.basis + RowLayout { + id: line + x: 12; y: 10 + width: parent.width - 24 + spacing: 12 + Rectangle { + Layout.alignment: Qt.AlignTop + implicitWidth: 86; implicitHeight: 22; radius: 11 + readonly property color tone: page.verdictColor(modelData.verdict) + color: Qt.rgba(tone.r, tone.g, tone.b, 0.16) + Label { anchors.centerIn: parent; text: page.verdictWord(modelData.verdict); color: parent.tone; font.pixelSize: Look.px(12); font.bold: true } + } + ColumnLayout { + Layout.fillWidth: true + spacing: 3 + RowLayout { + Layout.fillWidth: true + spacing: 8 + Label { text: modelData.machine; font.bold: true } + Label { + visible: Format.has(modelData.needGB) && modelData.roomGB > 0 + text: "about " + page.gigabytes(modelData.needGB) + " of " + page.gigabytes(modelData.roomGB) + " " + modelData.roomName + color: page.room.soft + } + Label { + visible: Format.has(modelData.needGB) + text: "· " + page.gradeWord(modelData.grade); color: page.room.muted; font.pixelSize: Look.px(11) + } + Item { Layout.fillWidth: true } + } + // How much of the room it would take, where both are known. + Rectangle { + Layout.fillWidth: true + visible: Format.has(modelData.needGB) && modelData.roomGB > 0 + implicitHeight: 5; radius: 2.5 + color: page.room.raised + Rectangle { + width: parent.width * Math.min(1, (modelData.needGB || 0) / Math.max(0.001, modelData.roomGB)) + height: parent.height; radius: 2.5 + color: page.verdictColor(modelData.verdict) + } + } + Label { Layout.fillWidth: true; wrapMode: Text.Wrap; text: modelData.basis; color: page.room.muted; font.pixelSize: Look.px(12) } + } + } + } + } + Label { + width: parent.width; wrapMode: Text.Wrap; font.pixelSize: Look.px(11); opacity: Look.dim(0.6) + text: "Worked out from the memory each server reported while the model was loaded, and from the size of its file where it never ran. Nothing is loaded to find out. Tight means over nine tenths of the memory; a model that fits may still be slow if other programs hold memory too." + } + } + } + + Repeater { + model: page.report ? page.report.machines : [] + Card { + id: filesCard + objectName: "files:" + modelData.id + name: "Model files on " + modelData.name + Layout.fillWidth: true + readonly property var machine: modelData + readonly property real unused: page.idleBytes(modelData) + Column { + width: parent.width; spacing: 12 + RowLayout { + width: parent.width + spacing: 10 + Label { text: "Model Files on " + filesCard.machine.name; font.bold: true } + Label { + visible: filesCard.machine.files.length > 0 + text: filesCard.machine.files.length + (filesCard.machine.files.length === 1 ? " model, " : " models, ") + page.size(page.totalBytes(filesCard.machine)) + color: page.room.muted; font.pixelSize: Look.px(12) + } + Item { Layout.fillWidth: true } + Rectangle { + visible: filesCard.unused > 0 + implicitHeight: 20; radius: 10; implicitWidth: unusedText.implicitWidth + 16 + color: Qt.rgba(page.tones.amber.r, page.tones.amber.g, page.tones.amber.b, 0.14) + Label { + id: unusedText; anchors.centerIn: parent; color: page.tones.amber; font.pixelSize: Look.px(11) + text: page.size(filesCard.unused) + " not used in " + (page.report ? page.report.idleDays : 30) + " days" + } + } + } + Table { + width: parent.width + visible: rows.length > 0 + columns: [ + { title: "Model", weight: 3.2 }, { title: "Kept By", weight: 1.4 }, { title: "Size", right: true }, + { title: "Downloaded", weight: 1.2, right: true }, { title: "Last Ran", weight: 1.6, right: true } + ] + rows: filesCard.machine.files.map(function (f) { + var last = Format.has(f.lastRan) ? Format.ago(f.lastRan) : "no request seen" + return [f.name, f.source, page.size(f.bytes), f.modified > 0 ? Format.ago(f.modified) : "—", + page.idle(f) ? { text: last, color: page.tones.amber } : last] + }) + } + Label { + width: parent.width; wrapMode: Text.Wrap; opacity: Look.dim(0.7) + visible: filesCard.machine.files.length === 0 + text: !Format.has(filesCard.machine.scanned) + ? (filesCard.machine.id === "here" ? "Looking through the model folders…" : "Waiting for " + filesCard.machine.name + " to answer. It needs Tokenmeter 0.9.10 or later.") + : "No model files found in the folders of Ollama, LM Studio, Hugging Face or llama.cpp." + } + } + } + } + + Label { + Layout.fillWidth: true; wrapMode: Text.Wrap + visible: page.report !== null + text: "Model files are found by listing the folders of Ollama, LM Studio, the Hugging Face cache and llama.cpp and reading their sizes; no model file is opened, and Tokenmeter never deletes one. A file counts as run when a request named a model it matches." + color: page.room.faint; font.pixelSize: Look.px(11) + } + } +} diff --git a/Linux/kde/ui/SidebarIcon.qml b/Linux/kde/ui/SidebarIcon.qml index c70dbf7..060525a 100644 --- a/Linux/kde/ui/SidebarIcon.qml +++ b/Linux/kde/ui/SidebarIcon.qml @@ -89,6 +89,10 @@ Canvas { box(1, 5.5, 4, 5, 1); box(6, 5.5, 4, 5, 1); box(11, 5.5, 4, 5, 1) line([5, 8, 6, 8]); line([10, 8, 11, 8]) break + case "models": // a stack of three layers + c.beginPath(); c.moveTo(8, 1.8); c.lineTo(14.2, 5); c.lineTo(8, 8.2); c.lineTo(1.8, 5); c.closePath(); c.stroke() + line([1.8, 8.2, 8, 11.4, 14.2, 8.2]); line([1.8, 11.2, 8, 14.4, 14.2, 11.2]) + break case "welcome": // a flag on its pole line([3.5, 14.5, 3.5, 1.8]) c.beginPath(); c.moveTo(3.5, 2.5); c.lineTo(12.5, 2.5); c.lineTo(10.3, 5.8); c.lineTo(12.5, 9); c.lineTo(3.5, 9); c.stroke() diff --git a/Linux/tests/idle-frames.sh b/Linux/tests/idle-frames.sh index 7f8f5e1..f764e78 100755 --- a/Linux/tests/idle-frames.sh +++ b/Linux/tests/idle-frames.sh @@ -55,7 +55,7 @@ check() { } # Pages that stand still between two reads of the service. -for page in usage settings engines performance sessions insights lab mesh welcome; do check "$page" 1; done +for page in usage settings engines performance models sessions insights lab mesh welcome; do check "$page" 1; done # Gizmo's page: he moves for a few seconds after it opens, then stands still until he has something to say. check gizmo 1 # The Monitor's sample data has a request an agent waits on, whose mark steps three times a second. diff --git a/Linux/tests/models.sh b/Linux/tests/models.sh new file mode 100755 index 0000000..56595cc --- /dev/null +++ b/Linux/tests/models.sh @@ -0,0 +1,74 @@ +#!/bin/sh +# The Models page (GET /models, GET /models/fit): the model files the model managers keep in a home folder are +# found with their sizes, without a model file being opened; a model that never ran gets an estimate from its +# file's size against this machine's memory; and what a member of the mesh would ask is refused to anyone else. +# Starts its own service on port 7799 with a home folder of its own. No model is loaded or asked to work. +# +# Linux/tests/models.sh [path to the tokenmeter binary] +set -eu + +tokenmeter=$(realpath "${1:-.build/release/tokenmeter}") +work=$(mktemp -d) +pids= +trap 'for pid in $pids; do kill $pid 2>/dev/null || true; done; wait 2>/dev/null; rm -rf "${work:?}" || true' EXIT +fail() { + echo "FAILED: $1" >&2 + [ -f "$work/service.log" ] && { echo "--- service" >&2; tail -5 "$work/service.log" >&2; } + exit 1 +} +field() { python3 -c 'import json, sys; d = json.load(sys.stdin); print(('"$1"'))'; } +url=http://127.0.0.1:7799 +until_is() { # url expression expected what + for _ in $(seq 1 40); do + got=$(curl -sf -m 5 "$1" | field "$2" 2>/dev/null || true) + [ "$got" = "$3" ] && return 0 + sleep 1 + done + fail "$4 (got: $got)" +} + +home=$work/home +# Ollama: a manifest that names its layers' sizes (the layers themselves needn't be there). +mkdir -p "$home/.ollama/models/manifests/registry.ollama.ai/library/qwen3-coder" +echo '{"config":{"size":500},"layers":[{"size":2000000000},{"size":1500}]}' > "$home/.ollama/models/manifests/registry.ollama.ai/library/qwen3-coder/30b" +# LM Studio, the Hugging Face cache and llama.cpp: files, whose sizes are added up. (Sparse, so they take no room.) +mkdir -p "$home/.lmstudio/models/lmstudio-community/gemma-3-12b-it-GGUF" "$home/.cache/huggingface/hub/models--mlx-community--Qwen3-8B-4bit/blobs" \ + "$home/.cache/huggingface/hub/models--mlx-community--Qwen3-8B-4bit/snapshots/main" "$home/.cache/llama.cpp" +truncate -s 700000000 "$home/.lmstudio/models/lmstudio-community/gemma-3-12b-it-GGUF/gemma-3-12b-it-Q4_K_M.gguf" +truncate -s 500000000 "$home/.cache/huggingface/hub/models--mlx-community--Qwen3-8B-4bit/blobs/abc" +ln -s ../../blobs/abc "$home/.cache/huggingface/hub/models--mlx-community--Qwen3-8B-4bit/snapshots/main/model.safetensors" +truncate -s 250000000 "$home/.cache/llama.cpp/Phi-4-mini-Q4_K_M.gguf" +# A model far larger than any machine this runs on. +truncate -s 900000000000 "$home/.cache/llama.cpp/Giant-900B-Q8_0.gguf" + +env HOME="$home" XDG_DATA_HOME="$home/share" XDG_CONFIG_HOME="$home/config" TOKENMETER_NAME=shelf \ + "$tokenmeter" serve --port 7799 >"$work/service.log" 2>&1 & +pids="$pids $!" +until_is $url/mesh 'len(d["members"])' 1 "the service didn't start" + +# 1. The first answer starts the look through the folders; soon after, the files are there, largest first. +until_is $url/models 'len(d["machines"][0]["files"])' 5 "the model files weren't found" +curl -sf $url/models > "$work/models" +field '[f["name"] for f in d["machines"][0]["files"]]' < "$work/models" \ + | grep -q "^\['Giant-900B-Q8_0.gguf', 'qwen3-coder:30b', 'lmstudio-community/gemma-3-12b-it-GGUF', 'mlx-community/Qwen3-8B-4bit', 'Phi-4-mini-Q4_K_M.gguf'\]$" \ + || fail "the files, largest first: $(field '[f["name"] for f in d["machines"][0]["files"]]' < "$work/models")" +field '[f["source"] for f in d["machines"][0]["files"]]' < "$work/models" | grep -q "^\['llama.cpp', 'Ollama', 'LM Studio', 'Hugging Face cache', 'llama.cpp'\]$" || fail "who keeps each file" +field '[f["bytes"] for f in d["machines"][0]["files"]][1:]' < "$work/models" | grep -q "^\[2000002000, 700000000, 500000000, 250000000\]$" \ + || fail "the sizes (a linked snapshot counted once): $(field '[f["bytes"] for f in d["machines"][0]["files"]]' < "$work/models")" +field '(d["machines"][0]["id"], d["machines"][0]["name"], d["machines"][0]["memoryGB"] > 0, d["idleDays"], d["rows"])' < "$work/models" \ + | grep -q "^('here', 'shelf', True, 30, \[\])$" || fail "this machine's part: $(field '(d["machines"][0]["id"], d["machines"][0]["name"], d["machines"][0]["memoryGB"], d["idleDays"])' < "$work/models")" +# Nothing ran, so Will it fit offers the files, and none counts as unused yet (they were written a moment ago). +field '(sorted(d["choices"]) == sorted(f["name"] for f in d["machines"][0]["files"]), d["idleBytes"])' < "$work/models" | grep -q "^(True, 0)$" || fail "the choices" + +# 2. Will it fit: from the file's size, with a tenth on top, against this machine's memory. +curl -sf "$url/models/fit?model=Phi-4-mini-Q4_K_M.gguf" > "$work/fit" +field '(d["fits"][0]["verdict"], d["fits"][0]["grade"], round(d["fits"][0]["needGB"], 3), d["fits"][0]["machine"])' < "$work/fit" \ + | grep -q "^('fits', 'estimate', 0.275, 'shelf')$" || fail "a small model's estimate: $(cat "$work/fit")" +curl -sf "$url/models/fit?model=Giant-900B-Q8_0.gguf&context=32768" | field '(d["fits"][0]["verdict"], d["context"])' | grep -q "^('no', 32768)$" || fail "a model larger than the machine" +curl -sf "$url/models/fit?model=never-heard-of" | field '(d["fits"][0]["verdict"], d["fits"][0].get("needGB"))' | grep -q "^('unknown', None)$" || fail "a model nothing is known of" +[ "$(curl -s -o /dev/null -w '%{http_code}' "$url/models/fit")" = 400 ] || fail "a question without a model" + +# 3. What a member asks is for members only. +[ "$(curl -s -o /dev/null -w '%{http_code}' "$url/mesh/models")" = 403 ] || fail "/mesh/models answered someone who isn't a member" + +echo "ok: the Models page finds the model files of Ollama, LM Studio, Hugging Face and llama.cpp, and Will it fit estimates from a file's size" diff --git a/Package.swift b/Package.swift index 4c4dc71..113a609 100644 --- a/Package.swift +++ b/Package.swift @@ -98,7 +98,7 @@ let sources = [ "App/PhaseHistory.swift", "App/Footprint.swift", "App/Saver.swift", - "App/SetupChecklist.swift", "App/SetupMap.swift", + "App/SetupChecklist.swift", "App/SetupMap.swift", "App/ModelFiles.swift", "App/ModelsPage.swift", "App/ServicePackage.swift", "App/ServiceInstallerSources.swift", "App/RemoteInstall.swift", "App/Updates.swift", "App/PeerTraffic.swift", "App/ToolHosts.swift", "App/ToolCalls.swift", "App/WaitBreakdown.swift", "App/WireSplit.swift", @@ -143,7 +143,7 @@ let sources = [ "Linux/AlertRoutes.swift", "Linux/TargetRoutes.swift", "Linux/SpendRoutes.swift", - "Linux/MeshInstall.swift", "Linux/MeshUpdates.swift", "Linux/ToolRoutes.swift", "Linux/SetupRoutes.swift", + "Linux/MeshInstall.swift", "Linux/MeshUpdates.swift", "Linux/ToolRoutes.swift", "Linux/SetupRoutes.swift", "Linux/ModelRoutes.swift", "Linux/ViewerRoutes.swift", "Linux/WebRoutes.swift", "Linux/WebSources.swift", diff --git a/README.md b/README.md index 05a9301..487502a 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,12 @@ First token and writing speed per model, speed over time, and before and after a ![Performance over time](docs/images/linux-performance-history.png) +### Models + +One row per model across every machine, the model files each machine keeps on disk (and how many gigabytes nothing has asked for in a month), and **Will it fit?**: whether a model would fit on each machine at a context size, from the memory it was seen to take, before you load it there. + +![Models](docs/images/linux-models.png) + ### Sessions A coding agent's session as a story: model time, tool time, waiting for you, and each task's energy. **Where the Wait Went** tells each slow task in one sentence (the model, the tool's server, the way there and back, or a part nothing saw) with the evidence one click away, from the agent's reporter and the MCP Proxies on both machines. Under it, each task's **receipt**: turns, retries and the time failed attempts cost, work that ran alongside other work (counted once), tokens read and written and what tool answers added to the context, the bytes the MCP Proxy saw, and energy named by what the machine's meter covers (a Mac's chip, or CPU packages and GPU cards on Linux), never "the whole machine". **Where the Tokens Went** follows each task's tokens from what went in (the context it started with, your ask, earlier turns, tool answers) through how they were read (from the cache, read new, or read again because the cache was lost, with the seconds it cost) to what came out (thinking, answer, tool calls) and what was thrown away. diff --git a/Tests/ModelsPageTests.swift b/Tests/ModelsPageTests.swift new file mode 100644 index 0000000..661b7a2 --- /dev/null +++ b/Tests/ModelsPageTests.swift @@ -0,0 +1,176 @@ +import Foundation + +/// The Models page: the model files found on disk, which requests a file answers for, the rows, the memory seen +/// with each model loaded, and "Will it fit?". +extension Tests { + static func modelsPage() { + let manager = FileManager.default + let home = NSTemporaryDirectory() + "tokenmeter-models-\(UUID().uuidString)" + defer { try? manager.removeItem(atPath: home) } + func write(_ path: String, bytes: Int) { + let full = home + "/" + path + try? manager.createDirectory(atPath: (full as NSString).deletingLastPathComponent, withIntermediateDirectories: true) + manager.createFile(atPath: full, contents: Data(count: bytes)) + } + func writeText(_ path: String, _ text: String) { + let full = home + "/" + path + try? manager.createDirectory(atPath: (full as NSString).deletingLastPathComponent, withIntermediateDirectories: true) + manager.createFile(atPath: full, contents: Data(text.utf8)) + } + + // MARK: What the model managers keep on disk. + writeText(".ollama/models/manifests/registry.ollama.ai/library/qwen3-coder/30b", + #"{"config":{"size":500},"layers":[{"size":18000000000},{"size":1500}]}"#) + writeText(".ollama/models/manifests/registry.ollama.ai/someone/tiny/latest", #"{"layers":[{"size":4000}]}"#) + writeText(".ollama/models/manifests/registry.ollama.ai/library/broken/latest", "not json") + write(".lmstudio/models/lmstudio-community/gemma-3-12b-it-GGUF/gemma-3-12b-it-Q4_K_M.gguf", bytes: 7000) + write(".lmstudio/models/lmstudio-community/gemma-3-12b-it-GGUF/mmproj.gguf", bytes: 500) + write(".cache/huggingface/hub/models--mlx-community--Qwen3-8B-4bit/blobs/abc", bytes: 5000) + write(".cache/huggingface/hub/models--mlx-community--Qwen3-8B-4bit/blobs/def", bytes: 100) + write(".cache/huggingface/hub/datasets--someone--data/blobs/abc", bytes: 900) + write(".cache/llama.cpp/Phi-4-mini-Q4_K_M.gguf", bytes: 2500) + write(".cache/llama.cpp/notes.txt", bytes: 10) + let files = ModelFiles.scan(home: home, environment: [:]) + equal(files.map(\.name), ["qwen3-coder:30b", "lmstudio-community/gemma-3-12b-it-GGUF", "mlx-community/Qwen3-8B-4bit", "someone/tiny:latest", + "Phi-4-mini-Q4_K_M.gguf"], "every manager's models, largest first") + equal(files.map(\.source), ["Ollama", "LM Studio", "Hugging Face cache", "Ollama", "llama.cpp"], "each named by its manager") + equal(files.map(\.bytes), [18_000_002_000, 7500, 5100, 4000, 2500], "sizes: Ollama's from its manifest, the others added up") + expect(files.allSatisfy { $0.modified > 0 }, "each says when it was written") + // A folder moved by the manager's own variable is found too, once. + write("elsewhere/models--org--moved/blobs/a", bytes: 300) + let moved = ModelFiles.scan(home: home, environment: ["HF_HUB_CACHE": home + "/elsewhere"]) + expect(moved.contains { $0.name == "org/moved" }, "HF_HUB_CACHE is followed") + equal(moved.filter { $0.name == "mlx-community/Qwen3-8B-4bit" }.count, 1, "and the usual folder still counted once") + equal(ModelFiles.scan(home: home + "/nothing", environment: [:]).count, 0, "no folders, no files") + + // MARK: Which requests a file answers for. + expect(ModelFiles.same("qwen3-coder:30b", "qwen3-coder:30b"), "the same name") + expect(ModelFiles.same("bartowski/Qwen3-Coder-30B-Q4_K_M.gguf", "qwen3-coder-30b"), "a file with its quantisation and a shorter name") + expect(ModelFiles.same("mlx-community/Qwen3-8B-4bit", "Qwen3-8B-4bit"), "a publisher in front") + expect(!ModelFiles.same("qwen3-coder:30b", "qwen3:8b"), "another size is another model") + expect(!ModelFiles.same("llama-3.3-70b", "llama"), "one shared word is not enough") + expect(ModelFiles.same("phi4:latest", "phi4"), "unless it is the whole name") + expect(!ModelFiles.same("", "phi4"), "an empty name matches nothing") + let marked = ModelFiles.marked(files, lastRan: ["qwen3-coder:30b": 100, "Qwen3-Coder-30B": 250, "gemma-3-12b-it": 90]) + equal(marked[0].lastRan, 250, "the latest of the names that match") + equal(marked[1].lastRan, 90, "LM Studio's folder by its model") + equal(marked[2].lastRan, nil, "a file nothing asked for") + + // MARK: Files not used lately. + let now = 1_800_000_000.0, day = 86400.0 + func file(_ name: String, gb: Double, modified: Double, ran: Double? = nil) -> ModelFile { + ModelFile(name: name, source: "Ollama", path: "/models/" + name, bytes: Int(gb * 1e9), modified: modified, lastRan: ran) + } + expect(ModelsPage.idle(file("a", gb: 1, modified: now - 40 * day), now: now), "never ran, downloaded 40 days ago") + expect(!ModelsPage.idle(file("a", gb: 1, modified: now - 5 * day), now: now), "never ran, but new") + expect(!ModelsPage.idle(file("a", gb: 1, modified: now - 400 * day, ran: now - 2 * day), now: now), "old, and ran this week") + expect(ModelsPage.idle(file("a", gb: 1, modified: now - 400 * day, ran: now - 31 * day), now: now), "last ran 31 days ago") + + // MARK: The rows. + func request(_ model: String, minutesAgo: Double, finish: String = "stop") -> LoggedRequest { + var row = LoggedRequest(server: "localhost:8080", engine: "llama.cpp", model: model, requests: 1, prompt: 1000, cached: 400, output: 200, + at: Date(timeIntervalSince1970: now - minutesAgo * 60)) + row.finish = finish + row.tokensPerSecond = 40 + row.perRequest = true + return row + } + let log = [request("qwen3-coder:30b", minutesAgo: 30), request("qwen3-coder:30b", minutesAgo: 20, finish: "length"), + request("qwen3-coder:30b", minutesAgo: 10), request("gemma-3-12b-it", minutesAgo: 5)] + var studio = ModelMachine(id: "here", name: "studio", memoryGB: 64, files: [file("qwen3-coder:30b", gb: 18, modified: now - 50 * day, ran: now - 600)], + footprints: [], ran: ["qwen3-coder:30b": now - 600, "gemma-3-12b-it": now - 300]) + var tower = ModelMachine(id: "m2", name: "tower", memoryGB: 128, gpuMemoryGB: 24, gpuName: "RTX 4090", + files: [file("gemma-3-12b-it-GGUF", gb: 7, modified: now - 90 * day), file("old-model:7b", gb: 4, modified: now - 200 * day)], + footprints: [], ran: ["qwen3-coder:30b": now - 9000]) + let rows = ModelsPage.rows(RequestAnalysis(rows: log, activity: [:], since: nil), machines: [studio, tower]) + equal(rows.map(\.name), ["qwen3-coder:30b", "gemma-3-12b-it"], "busiest first") + equal(rows[0].requests, 3, "its requests") + equal(rows[0].typicalWrite, 40, "its typical speed") + equal(rows[0].known, 3, "its endings") + let cutShare: Double = ((rows[0].notFinished ?? 0) * 100).rounded() + equal(cutShare, 33, "one in three cut off") + equal(rows[0].machines, ["studio", "tower"], "the machines whose logs name it") + equal(rows[0].lastRan, now - 600, "and the latest of them") + equal(rows[1].machines, ["studio"], "one machine for the other") + equal(ModelsPage.choices(rows: rows, machines: [studio, tower]), ["qwen3-coder:30b", "gemma-3-12b-it", "old-model:7b"], + "Will it fit offers the ones that ran, then files nothing matches") + equal(ModelsPage.idleBytes([studio, tower], now: now), 11_000_000_000, "the two files nothing asked for in 30 days") + equal(tower.room, 24, "a card with its own memory is the room") + equal(studio.roomName, "memory", "shared memory otherwise") + + // MARK: What the servers held. + func server(_ model: String, memory: Double?, context: Int?, status: String = "online") -> StatusReport.Server? { + var fields: [String: Any] = ["id": "s", "engine": "llama.cpp", "model": model, "host": "localhost", "port": 8080, "status": status] + if let memory { fields["memoryUsedGB"] = memory } + if let context { fields["usableContext"] = context } + guard let data = try? JSONSerialization.data(withJSONObject: fields) else { return nil } + return try? JSONDecoder().decode(StatusReport.Server.self, from: data) + } + var prints = ModelFootprints.noted([], servers: [server("qwen3-coder:30b", memory: 21, context: 32768), server("No model loaded", memory: 3, context: nil), + server("2 models", memory: 30, context: nil), server("gemma", memory: 9, context: 8192, status: "offline"), + server("quiet", memory: nil, context: 4096)].compactMap { $0 }, now: 10) + equal(prints.count, 1, "only a server with one model loaded and its memory known says something") + prints = ModelFootprints.noted(prints, servers: [server("qwen3-coder:30b", memory: 22.5, context: 32768)].compactMap { $0 }, now: 20) + prints = ModelFootprints.noted(prints, servers: [server("qwen3-coder:30b", memory: 20, context: 32768)].compactMap { $0 }, now: 30) + equal(prints.count, 1, "the same model and context is one footprint") + equal(prints[0].memoryGB, 22.5, "at the most memory seen") + equal(prints[0].seen, 30, "and when it was last seen") + prints = ModelFootprints.noted(prints, servers: [server("qwen3-coder:30b", memory: 26, context: 65536)].compactMap { $0 }, now: 40) + equal(prints.count, 2, "another context is another") + + // MARK: Will it fit? + studio.footprints = prints + var fit = ModelFitting.fit(model: "qwen3-coder:30b", context: nil, on: studio, everywhere: [studio, tower]) + equal(fit.verdict, "fits", "26 GB of 64") + equal(fit.grade, "measured", "it ran there") + equal(fit.needGB, 26, "the most it took") + fit = ModelFitting.fit(model: "qwen3-coder:30b", context: 32768, on: studio, everywhere: [studio, tower]) + equal(fit.needGB, 22.5, "at the context asked for") + fit = ModelFitting.fit(model: "qwen3-coder:30b", context: 131072, on: studio, everywhere: [studio, tower]) + equal(fit.grade, "calculated", "a larger context than seen is worked out") + var rounded: Double = ((fit.needGB ?? 0) * 10).rounded() / 10 + equal(rounded, 34, "the part over the file scaled: 18 + 8 × 2") + // The other machine never ran it: what the first one saw, against the card's memory. + fit = ModelFitting.fit(model: "qwen3-coder:30b", context: 32768, on: tower, everywhere: [studio, tower]) + equal(fit.grade, "calculated", "from another machine") + equal(fit.verdict, "tight", "22.5 GB in a 24 GB card") + expect(fit.basis.contains("studio"), "and it says where from") + equal(fit.roomName, "graphics memory", "the card's memory is named") + fit = ModelFitting.fit(model: "qwen3-coder:30b", context: 65536, on: tower, everywhere: [studio, tower]) + equal(fit.verdict, "no", "26 GB doesn't fit in 24") + // Only a file to go by. + fit = ModelFitting.fit(model: "old-model:7b", context: nil, on: studio, everywhere: [studio, tower]) + equal(fit.grade, "estimate", "from the file size") + rounded = ((fit.needGB ?? 0) * 10).rounded() / 10 + equal(rounded, 4.4, "with a tenth on top") + equal(fit.verdict, "fits", "in 64 GB") + fit = ModelFitting.fit(model: "never-heard-of", context: nil, on: studio, everywhere: [studio, tower]) + equal(fit.verdict, "unknown", "nothing to go by") + equal(fit.needGB, nil, "and no figure") + tower.memoryGB = 0 + tower.gpuMemoryGB = nil + fit = ModelFitting.fit(model: "old-model:7b", context: nil, on: tower, everywhere: [studio, tower]) + equal(fit.verdict, "unknown", "a machine that hasn't said how much memory it has") + // A name that only resembles: the closest name's figures, and the answer says whose they are. + studio.footprints.append(ModelFootprint(model: "qwen3:30b", engine: "Ollama", context: 8192, memoryGB: 19, seen: 50)) + fit = ModelFitting.fit(model: "qwen3:30b", context: nil, on: studio, everywhere: [studio, tower]) + equal(fit.needGB, 19, "its own figure, not the coder model's 26") + expect(!fit.basis.contains("Matched"), "and nothing to add") + fit = ModelFitting.fit(model: "Qwen3-Coder-30B-GGUF", context: nil, on: studio, everywhere: [studio, tower]) + equal(fit.needGB, 26, "a longer name of the coder model takes its figures") + expect(fit.basis.hasSuffix("Matched to qwen3-coder:30b."), "and says so: \(fit.basis)") + studio.footprints.removeLast() + equal(ModelsPage.contexts("qwen3-coder:30b", machines: [studio, tower]), [32768, 65536], "the contexts it was seen with") + equal(ModelsPage.gigabytes(21.26), "21.3 GB", "gigabytes") + equal(ModelsPage.gigabytes(128), "128 GB", "no decimal from 100 on") + equal(ModelsPage.size(32_400_000_000), "32.4 GB", "a file in gigabytes") + equal(ModelsPage.size(274_000_000), "0.3 GB", "a third of one") + equal(ModelsPage.size(40_000_000), "40 MB", "a small one in megabytes") + equal(ModelsPage.ago(now - 30, now: now), "just now", "a moment ago") + equal(ModelsPage.ago(now - 15 * 60, now: now), "15 minutes ago", "minutes") + equal(ModelsPage.ago(now - 3600, now: now), "an hour ago", "an hour") + equal(ModelsPage.ago(now - 5 * 3600, now: now), "5 hours ago", "hours") + equal(ModelsPage.ago(now - day, now: now), "yesterday", "a day") + equal(ModelsPage.ago(now - 48 * day, now: now), "48 days ago", "days") + } +} diff --git a/Tests/ReliabilityTests.swift b/Tests/ReliabilityTests.swift index 4d3c3ee..daf0a89 100644 --- a/Tests/ReliabilityTests.swift +++ b/Tests/ReliabilityTests.swift @@ -52,14 +52,27 @@ extension Tests { // MARK: The finding. // Over five days of history, one request every two hours, one in thirty-two cut off. - let history = (0..<64).map { row(Double(7_680 - $0 * 120), $0 % 32 == 5 ? "length" : "stop") } + var history: [LoggedRequest] = [] + for index in 0..<64 { + let minutes = Double(7_680 - index * 120) + history.append(row(minutes, index % 32 == 5 ? "length" : "stop")) + } + // The latest requests, half a minute apart, each ending as `finish` says for its place. + func recent(_ count: Int, model: String = "qwen3", _ finish: (Int) -> String?) -> [LoggedRequest] { + var rows: [LoggedRequest] = [] + for index in 0.. = []) -> Insight? { Insights.detect(Insights.Input(rows: history + recent, servers: [], now: now, sensitivity: level, widened: widened)) .found.first { $0.kind == "endings" } } - let fine = (0..<12).map { row(Double(12 - $0) * 0.5, "stop") } + let fine = recent(12) { _ in "stop" } expect(found(fine) == nil, "all finished: nothing to say") - let cut = (0..<12).map { row(Double(12 - $0) * 0.5, $0 % 3 == 0 ? "length" : "stop") } + let cut = recent(12) { $0 % 3 == 0 ? "length" : "stop" } let finding = found(cut) expect(finding != nil, "a third cut off against 3% usually opens a finding") equal(finding?.title, "More requests end badly: 33%", "it says the share") @@ -67,17 +80,19 @@ extension Tests { expect(finding?.summary.hasPrefix("4 of the last 12 requests") == true, "and the count: \(finding?.summary ?? "")") expect(finding?.evidence.inferred.first?.value.contains("length limit") == true, "the likely factor follows the commonest ending") equal(finding?.evidence.observed.first?.grade, .measured, "the endings are the engine's own") - let failing = (0..<12).map { row(Double(12 - $0) * 0.5, $0 % 4 == 0 ? "error" : "stop") } + let failing = recent(12) { $0 % 4 == 0 ? "error" : "stop" } expect(found(failing)?.evidence.inferred.first?.value.contains("error") == true, "failures are named as such") - let few = (0..<12).map { row(Double(12 - $0) * 0.5, $0 < 2 ? "aborted" : "stop") } + let few = recent(12) { $0 < 2 ? "aborted" : "stop" } expect(found(few) == nil, "two aborted requests are not a pattern") - let some = (0..<20).map { row(Double(20 - $0) * 0.5, $0 % 5 == 0 ? "aborted" : "stop") } + let some = recent(20) { $0 % 5 == 0 ? "aborted" : "stop" } equal(found(some)?.priority, 1, "a fifth is worth knowing") expect(found(some, widened: ["endings|localhost:8080|qwen3"]) == nil, "and marked normal it needs twice the gap") - let unsaid = (0..<12).map { row(Double(12 - $0) * 0.5, $0 % 3 == 0 ? "length" : nil) } + let unsaid = recent(12) { $0 % 3 == 0 ? "length" : nil } expect(found(unsaid) == nil, "four endings known out of twelve requests are too few to judge") // A model whose history never said how requests ended has no normal to rise above. - let mute = (0..<64).map { row(Double(7_680 - $0 * 120), nil, model: "mute") } + (0..<12).map { row(Double(12 - $0) * 0.5, "length", model: "mute") } + var mute: [LoggedRequest] = [] + for index in 0..<64 { mute.append(row(Double(7_680 - index * 120), nil, model: "mute")) } + mute += recent(12, model: "mute") { _ in "length" } expect(Insights.detect(Insights.Input(rows: mute, servers: [], now: now, sensitivity: .normal)).found.first { $0.kind == "endings" } == nil, "no finding without a normal") } diff --git a/Tests/Tests.swift b/Tests/Tests.swift index 0ba01a7..eb8a070 100644 --- a/Tests/Tests.swift +++ b/Tests/Tests.swift @@ -163,6 +163,7 @@ enum Tests { litellm() openAIEngine() reliability() + modelsPage() print(failures == 0 ? "\(checks) checks passed." : "\(failures) of \(checks) checks failed.") exit(failures == 0 ? 0 : 1) } diff --git a/build-library-app.sh b/build-library-app.sh index 810217d..8fe56cb 100755 --- a/build-library-app.sh +++ b/build-library-app.sh @@ -18,7 +18,7 @@ for word in "$@"; do esac done app="$project_dir/Tokenmeter.app" -version=${APP_VERSION:-0.9.9} +version=${APP_VERSION:-0.9.10} build=${APP_BUILD:-1} # SwiftUI's @State is a compiler macro in the macOS 26 SDK. The Command Line Tools ship that SDK without diff --git a/docs/images/linux-models.png b/docs/images/linux-models.png new file mode 100644 index 0000000..e632a57 Binary files /dev/null and b/docs/images/linux-models.png differ diff --git a/docs/wiki/Features.md b/docs/wiki/Features.md index d3acec4..e90a792 100644 --- a/docs/wiki/Features.md +++ b/docs/wiki/Features.md @@ -190,6 +190,18 @@ How fast your models answer, from every request Tokenmeter has seen finish. Spee Kapitsa and MTPLX report each request, so their figures are exact. Other engines report totals, so requests that finish within the same few seconds are timed together. +## Models + +![Models](../images/linux-models.png) + +Since 0.9.10, a page about the models themselves rather than the servers they run on. + +- **Models:** one row for each model that answered a request in the range, over every machine that shares its history: requests, typical writing speed and time to first token, how much of its prompts the cache held, tokens per watt-hour, the share of its requests that didn't finish on their own (amber from one in ten), when it last ran and on which machines. +- **Will it fit?** Pick a model and, if you like, a context size, and each machine of the [mesh](Mesh.md) answers **Fits**, **Tight** (over nine tenths of its memory) or **Won't fit**, with the figure and what it rests on. *Measured here* means the model ran on that machine and this is the most memory its server reported. *Worked out* means it comes from what the model took on another machine, or at another context size (the part above the file's size is scaled to the context asked for). *Rough estimate* means the model never ran anywhere, and the figure is its file's size plus a tenth. On a machine whose graphics card has its own memory the model is held against that; elsewhere against the machine's memory. Nothing is loaded to find out. +- **Model files:** for each machine, what Ollama, LM Studio, the Hugging Face cache and llama.cpp keep on disk: the model, who keeps it, its size, when it was downloaded and when a request last named a model it matches. A file with no request in 30 days is marked amber, and the card's corner adds those up ("59.6 GB not used in 30 days"). Tokenmeter lists the folders and reads sizes (and Ollama's small manifest files); it opens no model file and never deletes one. Folders moved with `OLLAMA_MODELS`, `HF_HOME`, `HF_HUB_CACHE` or `LLAMA_CACHE` are followed when the service runs with those variables set. + +The memory a model takes is noted from each server's own report every half minute while the model is loaded (the most seen for each model, engine and context size), and kept in the history database. A server that holds several models at once says nothing about one of them and is left out. Another machine's files and memory are read through the mesh, and it needs Tokenmeter 0.9.10 or later to answer. + ## Sessions ![Sessions on Linux](../images/linux-sessions.png) diff --git a/docs/wiki/Status-Endpoint.md b/docs/wiki/Status-Endpoint.md index 6754aae..64ffc9b 100644 --- a/docs/wiki/Status-Endpoint.md +++ b/docs/wiki/Status-Endpoint.md @@ -20,6 +20,8 @@ It listens on `http://127.0.0.1:7733`: | `GET /xray/tools?days=&agent=` | Since 0.8.53: each tool's calls across sessions over `days` (1, 7 or 30): calls, success, median and p90, the time on the critical path, retries, where its time went, tokens back, and the window before; with its slowest and failed calls | | | Since 0.8.102 the `/xray` answers are worked out beside the service's main work, so a long one (a month of sessions) no longer holds up `/status`, the proxies or the other pages; two asks for the same answer share one telling | | | Since 0.9.0 `GET /xray` and `GET /performance` carry `"reading": true` while the service is still reading its saved history (just after it starts, or while it moves an earlier version's files into its database) | +| `GET /models?range=` | Since 0.9.10: the [Models page](Features.md#models). `rows`, one for each model that answered a request in the range (`requests`, `typicalWrite`, `typicalFirstToken`, `cacheRate`, `tokensPerWattHour`, `known` endings and the share `notFinished`, `lastRan`, `machines`); `machines`, this one (`"id": "here"`) and each other member of the mesh, with its memory, its model `files` (`name`, `source`, `path`, `bytes`, `modified`, `lastRan`) and `footprints` (the most memory a server reported with a model loaded, by `model`, `engine` and `context`); `choices`, `idleDays` and `idleBytes`. Not among the pages a read-only viewer may ask for | +| `GET /models/fit?model=&context=` | Since 0.9.10: for each machine a `verdict` (`fits`, `tight`, `no` or `unknown`), `needGB` against `roomGB` of `roomName`, a `grade` (`measured`, `calculated` or `estimate`) and `basis`, one sentence on what the figure rests on. `context` is optional. Nothing is loaded or sent to a model | | `GET /storage` | Since 0.9.0: the history database (`tokenmeter.db`): its size in bytes, its layout number, how many requests, replies and kept sessions it holds, the files set aside in `before-sqlite` with their size, and any file that couldn't be moved in and why. `POST /storage` with `{"remove": "before-sqlite"}` deletes the set-aside files. Since 0.9.1 also `kinds` (each kind kept on disk with `id`, `title`, what it `holds`, its `bytes`, the `days` it is kept and, where they can be set, `least`, `most` and the `setting` to send), `folder` and all of it in `bytes`, `exportsTo`, and the last `export` asked for (`kind`, `format`, `path`, `rows`, `bytes`, `done`, `problem`). `POST /storage` takes `{"keep": {"requests": 7 to 365, "replies": 7 to 90}}` (what is now too old goes within the hour, or at once with `"now": true`) and `{"export": {"kind": "requests" \| "replies" \| "everything", "format": "csv" \| "json"}}` (`everything` copies the whole history to a folder, for [another machine](Troubleshooting.md#moving-the-history-to-another-machine)); the file is written beside the service's other work, and `GET /storage` says when it is done. This machine only | | `GET /agents/live` | Since 0.8.53: what coding agents are running now, from their reporters and the MCP Proxy: `running` (tool calls, model requests and tasks, the longest first, a tool call `late` past its p90 this week or 30 s) and `recent` (the latest 200 that ended, the newest first), each with its task's `link` on the Sessions page. Held in memory only | | `POST /live/watch` | From this machine only: `{"on": true, "text": false}` switches Watch live on (ticks only) or `"text": true` with the text; `{"on": false}` switches it off and forgets everything. It turns itself off after 30 minutes, or once nothing has asked for the streams for 90 s | diff --git a/scripts/check.sh b/scripts/check.sh index b3b8ee5..e8dd99c 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -29,7 +29,7 @@ project_dir=$(cd "$(dirname "$0")/.." && pwd) cd "$project_dir" # The service tests, in the workflow's order. `machines` reads a service this script starts for it. -service_tests="gpu machines mesh viewer phone-alerts alerts alert-channels alerts-remote targets-remote targets spend drills gizmo-guide tools mcp-proxy wait history-line history-store storage wire stream workload share bench other-engine" +service_tests="gpu machines mesh viewer phone-alerts alerts alert-channels alerts-remote targets-remote targets spend drills gizmo-guide tools mcp-proxy wait history-line history-store storage wire stream workload share bench other-engine models" quick_tests="wire storage history-store mesh" extra_tests="idle-budget drill-screens gizmo-screens" diff --git a/scripts/package-flatpak.sh b/scripts/package-flatpak.sh index 691aee0..5596f91 100755 --- a/scripts/package-flatpak.sh +++ b/scripts/package-flatpak.sh @@ -7,7 +7,7 @@ # Needs flatpak and flatpak-builder; the KDE runtime and SDK are fetched from Flathub. set -eu project_dir=$(cd "$(dirname "$0")/.." && pwd) -version=${APP_VERSION:-0.9.9} +version=${APP_VERSION:-0.9.10} arch=$(uname -m) id=io.github.tokenmeter1.tokenmeter name="Tokenmeter-$version-linux-$arch" diff --git a/scripts/package-linux.sh b/scripts/package-linux.sh index f2d508a..c09d58e 100755 --- a/scripts/package-linux.sh +++ b/scripts/package-linux.sh @@ -4,7 +4,7 @@ # and install.sh. Needs the Swift toolchain; run it on Linux. set -eu project_dir=$(cd "$(dirname "$0")/.." && pwd) -version=${APP_VERSION:-0.9.9} +version=${APP_VERSION:-0.9.10} arch=$(uname -m) name="Tokenmeter-$version-linux-$arch" diff --git a/scripts/package-service.sh b/scripts/package-service.sh index f34e68e..06bc2c4 100755 --- a/scripts/package-service.sh +++ b/scripts/package-service.sh @@ -18,7 +18,7 @@ # On a Mac, SIGN_IDENTITY signs the program with a Developer ID; without it the program is ad-hoc signed. set -eu project_dir=$(cd "$(dirname "$0")/.." && pwd) -version=${APP_VERSION:-0.9.9} +version=${APP_VERSION:-0.9.10} case "$(uname -s)" in Darwin) os=macos ;; Linux) os=linux ;; diff --git a/scripts/package.sh b/scripts/package.sh index 75e5253..f91c8cd 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -16,7 +16,7 @@ set -euo pipefail project_dir=${0:A:h:h} app="$project_dir/Tokenmeter.app" dist="$project_dir/dist" -export APP_VERSION=${APP_VERSION:-0.9.9} +export APP_VERSION=${APP_VERSION:-0.9.10} identity=${SIGN_IDENTITY:-} profile=${NOTARY_PROFILE:-}