Files
ai_studio/Sources/PerformanceDashboard.swift
T
2026-11-19 09:18:49 +00:00

200 lines
8.8 KiB
Swift

import Charts
import SwiftUI
struct ReplyPerformance: View {
let run: GenerationMeasurement
private var timings: [String] {
var fields = run.firstOutput.map { ["First output " + duration($0)] } ?? []
fields.append("Total " + duration(run.seconds))
if let rate = run.provider?.tokensPerSecond {
fields.append("\(rate.formatted(.number.precision(.fractionLength(1)))) tok/s")
} else if let rate = run.charactersPerSecond {
fields.append("\(rate.formatted(.number.precision(.fractionLength(1)))) chars/s")
}
return fields
}
var body: some View {
Label {
Text(timings.joined(separator: " · "))
} icon: {
Image(systemName: "stopwatch")
}
.font(.caption.monospacedDigit())
.foregroundStyle(.secondary)
}
}
private func duration(_ seconds: Double) -> String {
seconds.formatted(.number.precision(.fractionLength(2))) + " s"
}
struct PerformanceDashboard: View {
@ObservedObject var studio: StudioModel
@AppStorage(GenerationMeasurement.key) private var stored = Data()
@AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434"
@AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
@State private var repetitions = 1
@State private var scope: Scope = .all
@State private var throughput: Throughput = .tokens
private enum Scope: String, CaseIterable, Identifiable {
case all = "All runs", benchmark = "Benchmarks", chat = "Chats"
var id: Self { self }
}
private enum Throughput: String, CaseIterable, Identifiable {
case tokens = "Tokens/s", characters = "Characters/s"
var id: Self { self }
func value(_ run: GenerationMeasurement) -> Double? {
self == .tokens ? run.provider?.tokensPerSecond : run.charactersPerSecond
}
}
private var runs: [GenerationMeasurement] {
GenerationMeasurement.history(stored).filter {
switch scope {
case .all: true
case .benchmark: $0.benchmark == true
case .chat: $0.benchmark != true
}
}
}
private var recent: [GenerationMeasurement] { Array(runs.prefix(12).reversed()) }
var body: some View {
VStack(alignment: .leading, spacing: 17) {
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 5) {
Text("Model Performance").font(.largeTitle.weight(.semibold))
Text("Compare the latest 50 runs. First output includes startup and prompt processing.")
.foregroundStyle(.secondary)
}
Spacer()
Picker("Show", selection: $scope) {
ForEach(Scope.allCases) { Text($0.rawValue).tag($0) }
}.pickerStyle(.segmented).labelsHidden().frame(width: 260)
}
benchmarkControls
if runs.isEmpty {
ContentUnavailableView("No runs in this view", systemImage: "chart.xyaxis.line",
description: Text("Run a benchmark or generate a chat reply."))
} else {
HStack(spacing: 14) {
chartCard("Latency", accent: .indigo) { latencyChart }
chartCard("Throughput", accent: .teal) { throughputChart }
}
Table(runs) {
TableColumn("Model") { run in Text(run.model ?? "—").help(run.model ?? "") }
TableColumn("Time") { Text($0.recordedAt?.formatted(.dateTime.month().day().hour().minute()) ?? "—") }
TableColumn("Backend", value: \.backend)
TableColumn("Source") { Text($0.benchmark == true ? "Benchmark" : "Chat") }
TableColumn("First output") { Text($0.firstOutput.map(duration) ?? "—") }
TableColumn("Total") { Text(duration($0.seconds)) }
TableColumn("Tokens/s") { Text(number($0.provider?.tokensPerSecond)) }
TableColumn("Outcome") { run in
Label(run.outcome, systemImage: run.outcome == "Complete" ? "checkmark.circle" : "exclamationmark.circle")
.foregroundStyle(run.outcome == "Complete" ? Color.secondary : run.outcome == "Stopped" ? .orange : .red)
}
}
.frame(minHeight: 180)
}
}
.padding(22)
.frame(minWidth: 940, minHeight: 625)
}
private var benchmarkControls: some View {
HStack(spacing: 14) {
VStack(alignment: .leading, spacing: 4) {
Text(studio.performanceModel?.displayName ?? "Choose a model in chat").font(.headline)
Text(studio.benchmarkStatus.isEmpty
? "Fixed prompt · 128 output tokens maximum · temperature 0"
: studio.benchmarkStatus)
.font(.caption).foregroundStyle(.secondary)
.help(StudioModel.benchmarkPrompt)
}
Spacer()
Picker("Runs", selection: $repetitions) {
ForEach([1, 3, 5], id: \.self) { Text($0.formatted()).tag($0) }
}.fixedSize().disabled(studio.benchmarkRunning)
if studio.benchmarkRunning {
ProgressView().controlSize(.small)
Button("Stop", action: studio.stopBenchmark)
} else {
Button("Run Benchmark", systemImage: "play.fill", action: runBenchmark)
.buttonStyle(.borderedProminent)
.disabled(studio.running || studio.performanceModel?.model.isEmpty != false)
}
}
.padding(13)
.background(.quaternary.opacity(0.6), in: RoundedRectangle(cornerRadius: 11))
}
private func chartCard<Content: View>(_ title: String, accent: Color, @ViewBuilder content: () -> Content) -> some View {
VStack(alignment: .leading, spacing: 12) {
Label(title, systemImage: "chart.bar.xaxis").font(.headline).foregroundStyle(accent)
content()
}
.padding(13)
.frame(maxWidth: .infinity, alignment: .leading)
.background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 11))
}
private var latencyChart: some View {
Chart {
ForEach(Array(recent.enumerated()), id: \.element.id) { index, run in
BarMark(x: .value("Run", index + 1), y: .value("Seconds", run.seconds))
.position(by: .value("Timing", "Total"))
.foregroundStyle(by: .value("Timing", "Total"))
if let first = run.firstOutput {
BarMark(x: .value("Run", index + 1), y: .value("Seconds", first))
.position(by: .value("Timing", "First output"))
.foregroundStyle(by: .value("Timing", "First output"))
}
}
}
.chartForegroundStyleScale(domain: ["First output", "Total"], range: [Color.teal, Color.indigo])
.chartLegend(position: .bottom, alignment: .leading)
.chartYAxisLabel("Seconds")
.frame(height: 180)
}
private var throughputChart: some View {
VStack(alignment: .leading, spacing: 7) {
Picker("Unit", selection: $throughput) {
ForEach(Throughput.allCases) { Text($0.rawValue).tag($0) }
}.pickerStyle(.segmented).labelsHidden().frame(width: 195)
if recent.contains(where: { $0.outcome == "Complete" && throughput.value($0) != nil }) {
Chart {
ForEach(Array(recent.enumerated()), id: \.element.id) { index, run in
if run.outcome == "Complete", let value = throughput.value(run) {
BarMark(x: .value("Run", index + 1), y: .value(throughput.rawValue, value))
.foregroundStyle(Color.teal.gradient)
}
}
}
.chartYAxisLabel(throughput.rawValue)
.frame(height: 150)
} else {
Text("No completed runs reported \(throughput.rawValue.lowercased()).")
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, minHeight: 150)
}
}.frame(height: 180, alignment: .top)
}
private func runBenchmark() {
guard let model = studio.performanceModel else { return }
studio.benchmark(model, endpoint: model.backend == .compatible ? compatibleEndpoint : ollamaEndpoint,
repetitions: repetitions)
}
private func number(_ value: Double?) -> String {
value?.formatted(.number.precision(.fractionLength(1))) ?? "—"
}
}