Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

power sampling stats

eugene8830c1a8ba32
diff --git a/Cargo.lock b/Cargo.lock
index dc93a6ee9..b64e57d07 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -484,6 +484,7 @@ dependencies = [
"indicatif",
"is_close",
"itertools 0.14.0",
+ "keisoku",
"libc",
"libm",
"memmap2",
diff --git a/apps/playground/Project.swift b/apps/playground/Project.swift
index 755345b82..f96afa6c3 100644
--- a/apps/playground/Project.swift
+++ b/apps/playground/Project.swift
@@ -19,7 +19,7 @@ let settings: Settings = .settings(
"TARGETED_DEVICE_FAMILY": "1,2",
"SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD": "NO",
"MARKETING_VERSION": "0.5.12",
- "CURRENT_PROJECT_VERSION": "1",
+ "CURRENT_PROJECT_VERSION": "2",
],
configurations: [
.debug(
@@ -86,7 +86,7 @@ let appTarget: Target = .target(
],
]),
sources: ["Sources/**"],
- resources: [.glob(pattern: "Resources/**", excluding: ["Resources/Playground.entitlements"])],
+ resources: [.glob(pattern: "Resources/**", excluding: ["Resources/Playground.entitlements", "Resources/Playground-macOS.entitlements"])],
scripts: [crashlyticsScript],
dependencies: [
.package(product: "Uzu"),
@@ -97,6 +97,8 @@ let appTarget: Target = .target(
],
settings: .settings(base: [
"CODE_SIGN_ENTITLEMENTS": "Resources/Playground.entitlements",
+ // macOS needs to be unsandboxed to read IOReport/SMC power; iOS stays sandboxed.
+ "CODE_SIGN_ENTITLEMENTS[sdk=macosx*]": "Resources/Playground-macOS.entitlements",
"DERIVED_SOURCES_DIR": "$(SRCROOT)/Generated",
// Generate debug symbols for both the stub and the debug dylib
"COPY_PHASE_STRIP": "NO",
diff --git a/apps/playground/Resources/Playground-macOS.entitlements b/apps/playground/Resources/Playground-macOS.entitlements
new file mode 100644
index 000000000..14a9d6616
--- /dev/null
+++ b/apps/playground/Resources/Playground-macOS.entitlements
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- Unsandboxed on macOS so keisoku can reach IOReport/SMC; iOS uses sandboxed Playground.entitlements. -->
+ <key>com.apple.security.app-sandbox</key>
+ <false/>
+</dict>
+</plist>
diff --git a/apps/playground/Sources/Extensions/ReplyStatsFormat.swift b/apps/playground/Sources/Extensions/ReplyStatsFormat.swift
new file mode 100644
index 000000000..2f9b1d098
--- /dev/null
+++ b/apps/playground/Sources/Extensions/ReplyStatsFormat.swift
@@ -0,0 +1,59 @@
+import Foundation
+
+// Shared reply-stat formatting: fixed-unit MeasurementFormatter + ByteCountFormatter.
+enum ReplyStatsFormat {
+ static let placeholder = "—"
+
+ // macOS = SoC package power; iOS = whole-device charger "wall" power.
+ static var powerLabel: String {
+ #if os(macOS)
+ return "Power (SoC):"
+ #else
+ return "Power (wall):"
+ #endif
+ }
+
+ // Power/energy values are uncertain on iOS (and unset until a run completes), so the
+ // caller renders these rows only when the values are present — these just format.
+ static func power(average: Double, maximum: Double) -> String {
+ let avg = measurement.string(from: Measurement(value: average, unit: UnitPower.watts))
+ let peak = measurement.string(from: Measurement(value: maximum, unit: UnitPower.watts))
+ return "\(avg) avg · \(peak) peak"
+ }
+
+ static func energy(_ joules: Double) -> String {
+ measurement.string(from: Measurement(value: joules, unit: UnitEnergy.joules))
+ }
+
+ static func energyPerToken(joules: Double, tokens: Int) -> String {
+ let value = number.string(from: NSNumber(value: joules / Double(tokens))) ?? placeholder
+ return "\(value) J/tok"
+ }
+
+ static func memory(_ bytes: Int64?) -> String {
+ guard let bytes else { return placeholder }
+ return byteCount.string(fromByteCount: max(bytes, 0))
+ }
+
+ private static let number: NumberFormatter = {
+ let formatter = NumberFormatter()
+ formatter.numberStyle = .decimal
+ formatter.minimumFractionDigits = 2
+ formatter.maximumFractionDigits = 2
+ return formatter
+ }()
+
+ private static let measurement: MeasurementFormatter = {
+ let formatter = MeasurementFormatter()
+ formatter.unitOptions = .providedUnit
+ formatter.numberFormatter = number
+ return formatter
+ }()
+
+ private static let byteCount: ByteCountFormatter = {
+ let formatter = ByteCountFormatter()
+ formatter.countStyle = .memory
+ formatter.allowedUnits = [.useMB, .useGB]
+ return formatter
+ }()
+}
diff --git a/apps/playground/Sources/ViewModels/ChatModel.swift b/apps/playground/Sources/ViewModels/ChatModel.swift
index d1559d6a0..87ba22fe4 100644
--- a/apps/playground/Sources/ViewModels/ChatModel.swift
+++ b/apps/playground/Sources/ViewModels/ChatModel.swift
@@ -120,7 +120,7 @@ final class ChatModel {
self.messages[idx].reasoning = reply.message.reasoning()?.trimmingCharacters(in: .whitespacesAndNewlines)
self.messages[idx].content = (reply.message.text() ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
- self.messages[idx].stats = MessageStats(stats: reply.stats)
+ self.messages[idx].stats = ReplyStats(stats: reply.stats)
}
}
case .error(let error):
diff --git a/apps/playground/Sources/ViewModels/ClassificationModel.swift b/apps/playground/Sources/ViewModels/ClassificationModel.swift
index 89e7f1646..3aa18899a 100644
--- a/apps/playground/Sources/ViewModels/ClassificationModel.swift
+++ b/apps/playground/Sources/ViewModels/ClassificationModel.swift
@@ -12,23 +12,11 @@ final class ClassificationModel {
case error(Swift.Error)
}
- struct GenerationStats: Equatable {
- let timeToFirstToken: Double
- let tokensPerSecond: Double
- let totalTime: Double
-
- init(stats: ChatReplyStats) {
- self.timeToFirstToken = stats.timeToFirstToken ?? 0.0
- self.tokensPerSecond = stats.generateTokensPerSecond ?? 0.0
- self.totalTime = stats.duration
- }
- }
-
// MARK: - Observable Properties
var viewState: ViewState = .idle
var inputText: String = ""
var resultText: String = ""
- var stats: GenerationStats? = nil
+ var stats: ReplyStats? = nil
// MARK: - Private
private let identifier: String
diff --git a/apps/playground/Sources/ViewModels/ReplyStats.swift b/apps/playground/Sources/ViewModels/ReplyStats.swift
new file mode 100644
index 000000000..bb9e6e96f
--- /dev/null
+++ b/apps/playground/Sources/ViewModels/ReplyStats.swift
@@ -0,0 +1,28 @@
+import Foundation
+import Uzu
+
+struct ReplyStats: Equatable {
+ let timeToFirstToken: Double
+ let tokensPerSecond: Double
+ let memoryUsedBytes: Int64?
+ let averagePackagePower: Double?
+ let maxPackagePower: Double?
+ let packageEnergy: Double?
+ let tokensCount: Int?
+ let totalTime: Double
+
+ init(stats: ChatReplyStats) {
+ timeToFirstToken = stats.timeToFirstToken ?? 0.0
+ tokensPerSecond = stats.generateTokensPerSecond ?? 0.0
+ memoryUsedBytes = stats.memoryUsedBytes
+ averagePackagePower = stats.powerStats?.averagePackageWatts
+ maxPackagePower = stats.powerStats?.maxPackageWatts
+ packageEnergy = stats.powerStats?.energyJoules
+ if let input = stats.tokensCountInput, let output = stats.tokensCountOutput {
+ tokensCount = Int(input) + Int(output)
+ } else {
+ tokensCount = nil
+ }
+ totalTime = stats.duration
+ }
+}
diff --git a/apps/playground/Sources/ViewModels/SummarizationModel.swift b/apps/playground/Sources/ViewModels/SummarizationModel.swift
index 54f2f8df4..121cdd23c 100644
--- a/apps/playground/Sources/ViewModels/SummarizationModel.swift
+++ b/apps/playground/Sources/ViewModels/SummarizationModel.swift
@@ -13,23 +13,11 @@ final class SummarizationModel {
case error(Swift.Error)
}
- struct GenerationStats: Equatable {
- let timeToFirstToken: Double
- let tokensPerSecond: Double
- let totalTime: Double
-
- init(stats: ChatReplyStats) {
- self.timeToFirstToken = stats.timeToFirstToken ?? 0.0
- self.tokensPerSecond = stats.generateTokensPerSecond ?? 0.0
- self.totalTime = stats.duration
- }
- }
-
// MARK: - Observable Properties
var viewState: ViewState = .idle
var inputText: String = ""
var summaryText: String = ""
- var stats: GenerationStats? = nil
+ var stats: ReplyStats? = nil
// MARK: - Private
private let identifier: String
diff --git a/apps/playground/Sources/Views/ChatView.swift b/apps/playground/Sources/Views/ChatView.swift
index d959a788b..46a376964 100644
--- a/apps/playground/Sources/Views/ChatView.swift
+++ b/apps/playground/Sources/Views/ChatView.swift
@@ -9,34 +9,12 @@ enum MessageRole {
case assistant
}
-struct MessageStats: Equatable {
- let timeToFirstToken: Double
- let tokensPerSecond: Double
- let totalTime: Double
-
- init(
- timeToFirstToken: Double,
- tokensPerSecond: Double,
- totalTime: Double
- ) {
- self.timeToFirstToken = timeToFirstToken
- self.tokensPerSecond = tokensPerSecond
- self.totalTime = totalTime
- }
-
- init(stats: Uzu.ChatReplyStats) {
- self.timeToFirstToken = stats.timeToFirstToken ?? 0.0
- self.tokensPerSecond = stats.generateTokensPerSecond ?? 0.0
- self.totalTime = stats.duration
- }
-}
-
struct Message: Identifiable, Equatable {
let id = UUID()
let role: MessageRole
var reasoning: String?
var content: String
- var stats: MessageStats? = nil
+ var stats: ReplyStats? = nil
static func == (lhs: Message, rhs: Message) -> Bool {
lhs.id == rhs.id && lhs.content == rhs.content && lhs.role == rhs.role
@@ -274,26 +252,7 @@ struct ChatView: View {
.font(.monoBody16)
.textSelection(.enabled)
if let stats = message.stats {
- Rectangle()
- .fill(MiraiAsset.cardBorder.swiftUIColor)
- .frame(height: 1)
- .padding(.vertical, 4)
- VStack(alignment: .leading, spacing: 4) {
- metricRow(
- label: "Time to first token:",
- value: String(format: "%.3f s", stats.timeToFirstToken)
- )
- if stats.tokensPerSecond > 0 {
- metricRow(
- label: "Tokens per second:",
- value: String(format: "%.3f t/s", stats.tokensPerSecond)
- )
- }
- metricRow(
- label: "Total time:",
- value: String(format: "%.3f s", stats.totalTime)
- )
- }
+ ReplyStatsView(stats: stats)
}
}
Spacer(minLength: 64)
@@ -310,17 +269,4 @@ struct ChatView: View {
viewModel.sendMessage()
}
- // MARK: - Metric row helper
-
- @ViewBuilder
- private func metricRow(label: String, value: String) -> some View {
- HStack(alignment: .firstTextBaseline, spacing: 6) {
- Text(label)
- .font(.monoCaption12)
- .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
- Text(value)
- .font(.monoBody16)
- }
- }
-
}
diff --git a/apps/playground/Sources/Views/ClassificationView.swift b/apps/playground/Sources/Views/ClassificationView.swift
index 0a3896808..941ddbc8d 100644
--- a/apps/playground/Sources/Views/ClassificationView.swift
+++ b/apps/playground/Sources/Views/ClassificationView.swift
@@ -120,27 +120,7 @@ struct ClassificationView: View {
.textSelection(.enabled)
if let stats = viewModel.stats {
- Rectangle()
- .fill(MiraiAsset.cardBorder.swiftUIColor)
- .frame(height: 1)
- .padding(.vertical, 4)
-
- VStack(alignment: .leading, spacing: 4) {
- metricRow(
- label: "Time to first token:",
- value: String(format: "%.3f s", stats.timeToFirstToken)
- )
- if stats.tokensPerSecond > 0 {
- metricRow(
- label: "Tokens per second:",
- value: String(format: "%.3f t/s", stats.tokensPerSecond)
- )
- }
- metricRow(
- label: "Total time:",
- value: String(format: "%.3f s", stats.totalTime)
- )
- }
+ ReplyStatsView(stats: stats)
}
}
.padding(.leading, 16)
@@ -221,18 +201,6 @@ struct ClassificationView: View {
? MiraiAsset.card.swiftUIColor : MiraiAsset.primary.swiftUIColor
}
- // MARK: - Metric row helper
-
- @ViewBuilder
- private func metricRow(label: String, value: String) -> some View {
- HStack(alignment: .firstTextBaseline, spacing: 6) {
- Text(label)
- .font(.monoCaption12)
- Text(value)
- .font(.monoBody16)
- }
- }
-
init(identifier: String) {
self.identifier = identifier
let feat = Feature(name: "sentiment", values: Self.sentiments)
diff --git a/apps/playground/Sources/Views/ReplyStatsView.swift b/apps/playground/Sources/Views/ReplyStatsView.swift
new file mode 100644
index 000000000..464f07e93
--- /dev/null
+++ b/apps/playground/Sources/Views/ReplyStatsView.swift
@@ -0,0 +1,45 @@
+import SwiftUI
+
+// Shared stats footer shown under a chat reply, classification result, or summary.
+struct ReplyStatsView: View {
+ let stats: ReplyStats
+
+ var body: some View {
+ Rectangle()
+ .fill(MiraiAsset.cardBorder.swiftUIColor)
+ .frame(height: 1)
+ .padding(.vertical, 4)
+
+ VStack(alignment: .leading, spacing: 4) {
+ metricRow(label: "Time to first token:", value: String(format: "%.3f s", stats.timeToFirstToken))
+ if stats.tokensPerSecond > 0 {
+ metricRow(label: "Tokens per second:", value: String(format: "%.3f t/s", stats.tokensPerSecond))
+ }
+ metricRow(label: "Memory used:", value: ReplyStatsFormat.memory(stats.memoryUsedBytes))
+ if let average = stats.averagePackagePower, let peak = stats.maxPackagePower {
+ metricRow(label: ReplyStatsFormat.powerLabel, value: ReplyStatsFormat.power(average: average, maximum: peak))
+ }
+ if let energy = stats.packageEnergy {
+ metricRow(label: "Energy:", value: ReplyStatsFormat.energy(energy))
+ }
+ if let energy = stats.packageEnergy, let tokens = stats.tokensCount, tokens > 0 {
+ metricRow(label: "Energy / token:", value: ReplyStatsFormat.energyPerToken(joules: energy, tokens: tokens))
+ }
+ metricRow(label: "Total time:", value: String(format: "%.3f s", stats.totalTime))
+ }
+ }
+
+ @ViewBuilder
+ private func metricRow(label: String, value: String) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text(label)
+ .font(.monoCaption12)
+ .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
+ Text(value)
+ .font(.monoCaption12Semibold)
+ .monospacedDigit()
+ .lineLimit(1)
+ .minimumScaleFactor(0.7)
+ }
+ }
+}
diff --git a/apps/playground/Sources/Views/SummarizationView.swift b/apps/playground/Sources/Views/SummarizationView.swift
index 6789532f2..3b965b156 100644
--- a/apps/playground/Sources/Views/SummarizationView.swift
+++ b/apps/playground/Sources/Views/SummarizationView.swift
@@ -101,27 +101,7 @@ struct SummarizationView: View {
.textSelection(.enabled)
if let stats = viewModel.stats {
- Rectangle()
- .fill(MiraiAsset.cardBorder.swiftUIColor)
- .frame(height: 1)
- .padding(.vertical, 4)
-
- VStack(alignment: .leading, spacing: 4) {
- metricRow(
- label: "Time to first token:",
- value: String(format: "%.3f s", stats.timeToFirstToken)
- )
- if stats.tokensPerSecond > 0 {
- metricRow(
- label: "Tokens per second:",
- value: String(format: "%.3f t/s", stats.tokensPerSecond)
- )
- }
- metricRow(
- label: "Total time:",
- value: String(format: "%.3f s", stats.totalTime)
- )
- }
+ ReplyStatsView(stats: stats)
}
}
.padding(.leading, 16)
@@ -203,19 +183,6 @@ struct SummarizationView: View {
? MiraiAsset.card.swiftUIColor : MiraiAsset.primary.swiftUIColor
}
- // MARK: - Metric row helper
-
- @ViewBuilder
- private func metricRow(label: String, value: String) -> some View {
- HStack(alignment: .firstTextBaseline, spacing: 6) {
- Text(label)
- .font(.monoCaption12)
- .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
- Text(value)
- .font(.monoBody16)
- }
- }
-
init(identifier: String) {
self.identifier = identifier
_viewModel = State(initialValue: SummarizationModel(identifier: identifier))
diff --git a/bindings/python/uzu/__init__.pyi b/bindings/python/uzu/__init__.pyi
index ef7ce5700..765830dc6 100644
--- a/bindings/python/uzu/__init__.pyi
+++ b/bindings/python/uzu/__init__.pyi
@@ -16,6 +16,7 @@ __all__ = [
"ChatReply",
"ChatReplyConfig",
"ChatReplyFinishReason",
+ "ChatReplyPowerStats",
"ChatReplyStats",
"ChatRole",
"ChatSession",
@@ -324,6 +325,30 @@ class ChatReplyConfig:
def with_sampling_method(self, sampling_method: SamplingMethod) -> ChatReplyConfig: ...
def with_grammar(self, grammar: typing.Optional[Grammar]) -> ChatReplyConfig: ...
+class ChatReplyPowerStats:
+ @property
+ def samples_count(self) -> builtins.int: ...
+ @property
+ def average_cpu_watts(self) -> builtins.float: ...
+ @property
+ def average_gpu_watts(self) -> builtins.float: ...
+ @property
+ def average_gpu_sram_watts(self) -> builtins.float: ...
+ @property
+ def average_ane_watts(self) -> builtins.float: ...
+ @property
+ def average_ram_watts(self) -> builtins.float: ...
+ @property
+ def average_total_watts(self) -> builtins.float: ...
+ @property
+ def average_package_watts(self) -> builtins.float: ...
+ @property
+ def max_package_watts(self) -> builtins.float: ...
+ @property
+ def energy_joules(self) -> builtins.float: ...
+ def __new__(cls, samples_count: builtins.int, average_cpu_watts: builtins.float, average_gpu_watts: builtins.float, average_gpu_sram_watts: builtins.float, average_ane_watts: builtins.float, average_ram_watts: builtins.float, average_total_watts: builtins.float, average_package_watts: builtins.float, max_package_watts: builtins.float, energy_joules: builtins.float) -> ChatReplyPowerStats: ...
+
@typing.final
class ChatReplyStats:
@property
@@ -339,8 +364,12 @@ class ChatReplyStats:
@property
def tokens_count_output(self) -> typing.Optional[builtins.int]: ...
@property
+ def memory_used_bytes(self) -> typing.Optional[builtins.int]: ...
+ @property
+ def power_stats(self) -> typing.Optional[ChatReplyPowerStats]: ...
+ @property
def tokens_count(self) -> typing.Optional[builtins.int]: ...
- def __new__(cls, duration: builtins.float, time_to_first_token: typing.Optional[builtins.float], prefill_tokens_per_second: typing.Optional[builtins.float], generate_tokens_per_second: typing.Optional[builtins.float], tokens_count_input: typing.Optional[builtins.int], tokens_count_output: typing.Optional[builtins.int]) -> ChatReplyStats: ...
+ def __new__(cls, duration: builtins.float, time_to_first_token: typing.Optional[builtins.float], prefill_tokens_per_second: typing.Optional[builtins.float], generate_tokens_per_second: typing.Optional[builtins.float], tokens_count_input: typing.Optional[builtins.int], tokens_count_output: typing.Optional[builtins.int], memory_used_bytes: typing.Optional[builtins.int], power_stats: typing.Optional[ChatReplyPowerStats]) -> ChatReplyStats: ...
class ChatRole:
@typing.final
diff --git a/bindings/swift/Package.swift b/bindings/swift/Package.swift
index d877554b6..78be49c3b 100644
--- a/bindings/swift/Package.swift
+++ b/bindings/swift/Package.swift
@@ -21,7 +21,7 @@ let package = Package(
),
.target(
name: "Uzu",
- dependencies: ["uzu"],
+ dependencies: ["uzu", "UzuMetalIOSimulatorStubs"],
linkerSettings: [
.linkedLibrary("c++"),
.linkedFramework("SystemConfiguration"),
@@ -31,6 +31,11 @@ let package = Package(
.linkedFramework("AudioToolbox"),
]
),
+ .target(
+ name: "UzuMetalIOSimulatorStubs",
+ path: "Sources/UzuMetalIOSimulatorStubs",
+ publicHeadersPath: "include"
+ ),
.executableTarget(
name: "Examples",
dependencies: [
diff --git a/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift b/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift
index d7d5f6085..723590c83 100644
--- a/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift
+++ b/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift
@@ -1169,6 +1169,92 @@ public func FfiConverterTypeChatReplyConfig_lower(_ value: ChatReplyConfig) -> R
}
+public struct ChatReplyPowerStats: Equatable, Hashable, Codable {
+ public var samplesCount: Int64
+ public var averageCpuWatts: Double
+ public var averageGpuWatts: Double
+ public var averageGpuSramWatts: Double
+ public var averageAneWatts: Double
+ public var averageRamWatts: Double
+ public var averageTotalWatts: Double
+ public var averagePackageWatts: Double
+ public var maxPackageWatts: Double
+ public var energyJoules: Double
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(samplesCount: Int64, averageCpuWatts: Double, averageGpuWatts: Double, averageGpuSramWatts: Double, averageAneWatts: Double, averageRamWatts: Double, averageTotalWatts: Double, averagePackageWatts: Double, maxPackageWatts: Double, energyJoules: Double) {
+ self.samplesCount = samplesCount
+ self.averageCpuWatts = averageCpuWatts
+ self.averageGpuWatts = averageGpuWatts
+ self.averageGpuSramWatts = averageGpuSramWatts
+ self.averageAneWatts = averageAneWatts
+ self.averageRamWatts = averageRamWatts
+ self.averageTotalWatts = averageTotalWatts
+ self.averagePackageWatts = averagePackageWatts
+ self.maxPackageWatts = maxPackageWatts
+ self.energyJoules = energyJoules
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatReplyPowerStats: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatReplyPowerStats: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatReplyPowerStats {
+ return
+ try ChatReplyPowerStats(
+ samplesCount: FfiConverterInt64.read(from: &buf),
+ averageCpuWatts: FfiConverterDouble.read(from: &buf),
+ averageGpuWatts: FfiConverterDouble.read(from: &buf),
+ averageGpuSramWatts: FfiConverterDouble.read(from: &buf),
+ averageAneWatts: FfiConverterDouble.read(from: &buf),
+ averageRamWatts: FfiConverterDouble.read(from: &buf),
+ averageTotalWatts: FfiConverterDouble.read(from: &buf),
+ averagePackageWatts: FfiConverterDouble.read(from: &buf),
+ maxPackageWatts: FfiConverterDouble.read(from: &buf),
+ energyJoules: FfiConverterDouble.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ChatReplyPowerStats, into buf: inout [UInt8]) {
+ FfiConverterInt64.write(value.samplesCount, into: &buf)
+ FfiConverterDouble.write(value.averageCpuWatts, into: &buf)
+ FfiConverterDouble.write(value.averageGpuWatts, into: &buf)
+ FfiConverterDouble.write(value.averageGpuSramWatts, into: &buf)
+ FfiConverterDouble.write(value.averageAneWatts, into: &buf)
+ FfiConverterDouble.write(value.averageRamWatts, into: &buf)
+ FfiConverterDouble.write(value.averageTotalWatts, into: &buf)
+ FfiConverterDouble.write(value.averagePackageWatts, into: &buf)
+ FfiConverterDouble.write(value.maxPackageWatts, into: &buf)
+ FfiConverterDouble.write(value.energyJoules, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReplyPowerStats_lift(_ buf: RustBuffer) throws -> ChatReplyPowerStats {
+ return try FfiConverterTypeChatReplyPowerStats.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReplyPowerStats_lower(_ value: ChatReplyPowerStats) -> RustBuffer {
+ return FfiConverterTypeChatReplyPowerStats.lower(value)
+}
+
+
public struct ChatReplyStats: Equatable, Hashable, Codable {
public var duration: Double
public var timeToFirstToken: Double?
@@ -1176,16 +1262,20 @@ public struct ChatReplyStats: Equatable, Hashable, Codable {
public var generateTokensPerSecond: Double?
public var tokensCountInput: UInt32?
public var tokensCountOutput: UInt32?
+ public var memoryUsedBytes: Int64?
+ public var powerStats: ChatReplyPowerStats?
// Default memberwise initializers are never public by default, so we
// declare one manually.
- public init(duration: Double, timeToFirstToken: Double?, prefillTokensPerSecond: Double?, generateTokensPerSecond: Double?, tokensCountInput: UInt32?, tokensCountOutput: UInt32?) {
+ public init(duration: Double, timeToFirstToken: Double?, prefillTokensPerSecond: Double?, generateTokensPerSecond: Double?, tokensCountInput: UInt32?, tokensCountOutput: UInt32?, memoryUsedBytes: Int64?, powerStats: ChatReplyPowerStats?) {
self.duration = duration
self.timeToFirstToken = timeToFirstToken
self.prefillTokensPerSecond = prefillTokensPerSecond
self.generateTokensPerSecond = generateTokensPerSecond
self.tokensCountInput = tokensCountInput
self.tokensCountOutput = tokensCountOutput
+ self.memoryUsedBytes = memoryUsedBytes
+ self.powerStats = powerStats
}
@@ -1217,7 +1307,9 @@ public struct FfiConverterTypeChatReplyStats: FfiConverterRustBuffer {
prefillTokensPerSecond: FfiConverterOptionDouble.read(from: &buf),
generateTokensPerSecond: FfiConverterOptionDouble.read(from: &buf),
tokensCountInput: FfiConverterOptionUInt32.read(from: &buf),
- tokensCountOutput: FfiConverterOptionUInt32.read(from: &buf)
+ tokensCountOutput: FfiConverterOptionUInt32.read(from: &buf),
+ memoryUsedBytes: FfiConverterOptionInt64.read(from: &buf),
+ powerStats: FfiConverterOptionTypeChatReplyPowerStats.read(from: &buf)
)
}
@@ -1228,6 +1320,8 @@ public struct FfiConverterTypeChatReplyStats: FfiConverterRustBuffer {
FfiConverterOptionDouble.write(value.generateTokensPerSecond, into: &buf)
FfiConverterOptionUInt32.write(value.tokensCountInput, into: &buf)
FfiConverterOptionUInt32.write(value.tokensCountOutput, into: &buf)
+ FfiConverterOptionInt64.write(value.memoryUsedBytes, into: &buf)
+ FfiConverterOptionTypeChatReplyPowerStats.write(value.powerStats, into: &buf)
}
}
@@ -4983,6 +5077,30 @@ fileprivate struct FfiConverterOptionString: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeChatReplyPowerStats: FfiConverterRustBuffer {
+ typealias SwiftType = ChatReplyPowerStats?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeChatReplyPowerStats.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeChatReplyPowerStats.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
diff --git a/bindings/swift/Sources/UzuMetalIOSimulatorStubs/MetalIOSimulatorStubs.c b/bindings/swift/Sources/UzuMetalIOSimulatorStubs/MetalIOSimulatorStubs.c
new file mode 100644
index 000000000..d1186d335
--- /dev/null
+++ b/bindings/swift/Sources/UzuMetalIOSimulatorStubs/MetalIOSimulatorStubs.c
@@ -0,0 +1,34 @@
+#include <TargetConditionals.h>
+#include <stddef.h>
+
+void uzu_metal_io_simulator_stubs_anchor(void) {}
+
+#if TARGET_OS_SIMULATOR
+
+typedef void* MTLIOCompressionContext;
+typedef long MTLIOCompressionMethod;
+typedef long MTLIOCompressionStatus;
+
+const void* MTLIOErrorDomain = 0;
+
+size_t MTLIOCompressionContextDefaultChunkSize(void) { return 0; }
+
+MTLIOCompressionContext MTLIOCreateCompressionContext(const char* path, MTLIOCompressionMethod type, size_t chunkSize) {
+ (void)path;
+ (void)type;
+ (void)chunkSize;
+ return NULL;
+}
+
+void MTLIOCompressionContextAppendData(MTLIOCompressionContext context, const void* data, size_t size) {
+ (void)context;
+ (void)data;
+ (void)size;
+}
+
+MTLIOCompressionStatus MTLIOFlushAndDestroyCompressionContext(MTLIOCompressionContext context) {
+ (void)context;
+ return 1;
+}
+
+#endif
diff --git a/bindings/swift/Sources/UzuMetalIOSimulatorStubs/include/UzuMetalIOSimulatorStubs.h b/bindings/swift/Sources/UzuMetalIOSimulatorStubs/include/UzuMetalIOSimulatorStubs.h
new file mode 100644
index 000000000..be97dbee9
--- /dev/null
+++ b/bindings/swift/Sources/UzuMetalIOSimulatorStubs/include/UzuMetalIOSimulatorStubs.h
@@ -0,0 +1 @@
+void uzu_metal_io_simulator_stubs_anchor(void);
diff --git a/bindings/typescript/src/napi/index.d.mts b/bindings/typescript/src/napi/index.d.mts
index 6f4c8a8df..7d3560f0a 100644
--- a/bindings/typescript/src/napi/index.d.mts
+++ b/bindings/typescript/src/napi/index.d.mts
@@ -265,6 +265,20 @@ export declare class ChatReplyConfig {
withGrammar(grammar?: Grammar | undefined | null): ChatReplyConfig
}
+export declare class ChatReplyPowerStats {
+ samplesCount: number
+ averageCpuWatts: number
+ averageGpuWatts: number
+ averageGpuSramWatts: number
+ averageAneWatts: number
+ averageRamWatts: number
+ averageTotalWatts: number
+ averagePackageWatts: number
+ maxPackageWatts: number
+ energyJoules: number
+ constructor(samplesCount: number, averageCpuWatts: number, averageGpuWatts: number, averageGpuSramWatts: number, averageAneWatts: number, averageRamWatts: number, averageTotalWatts: number, averagePackageWatts: number, maxPackageWatts: number, energyJoules: number)
+}
+
export declare class ChatReplyStats {
duration: number
timeToFirstToken?: number
@@ -272,7 +286,9 @@ export declare class ChatReplyStats {
generateTokensPerSecond?: number
tokensCountInput?: number
tokensCountOutput?: number
- constructor(duration: number, timeToFirstToken?: number, prefillTokensPerSecond?: number, generateTokensPerSecond?: number, tokensCountInput?: number, tokensCountOutput?: number)
+ memoryUsedBytes?: number
+ powerStats?: ChatReplyPowerStats
+ constructor(duration: number, timeToFirstToken?: number, prefillTokensPerSecond?: number, generateTokensPerSecond?: number, tokensCountInput?: number, tokensCountOutput?: number, memoryUsedBytes?: number, powerStats?: ChatReplyPowerStats)
get tokensCount(): number | null
}
diff --git a/bindings/typescript/src/napi/index.d.ts b/bindings/typescript/src/napi/index.d.ts
index 6f4c8a8df..7d3560f0a 100644
--- a/bindings/typescript/src/napi/index.d.ts
+++ b/bindings/typescript/src/napi/index.d.ts
@@ -265,6 +265,20 @@ export declare class ChatReplyConfig {
withGrammar(grammar?: Grammar | undefined | null): ChatReplyConfig
}
+export declare class ChatReplyPowerStats {
+ samplesCount: number
+ averageCpuWatts: number
+ averageGpuWatts: number
+ averageGpuSramWatts: number
+ averageAneWatts: number
+ averageRamWatts: number
+ averageTotalWatts: number
+ averagePackageWatts: number
+ maxPackageWatts: number
+ energyJoules: number
+ constructor(samplesCount: number, averageCpuWatts: number, averageGpuWatts: number, averageGpuSramWatts: number, averageAneWatts: number, averageRamWatts: number, averageTotalWatts: number, averagePackageWatts: number, maxPackageWatts: number, energyJoules: number)
+}
+
export declare class ChatReplyStats {
duration: number
timeToFirstToken?: number
@@ -272,7 +286,9 @@ export declare class ChatReplyStats {
generateTokensPerSecond?: number
tokensCountInput?: number
tokensCountOutput?: number
- constructor(duration: number, timeToFirstToken?: number, prefillTokensPerSecond?: number, generateTokensPerSecond?: number, tokensCountInput?: number, tokensCountOutput?: number)
+ memoryUsedBytes?: number
+ powerStats?: ChatReplyPowerStats
+ constructor(duration: number, timeToFirstToken?: number, prefillTokensPerSecond?: number, generateTokensPerSecond?: number, tokensCountInput?: number, tokensCountOutput?: number, memoryUsedBytes?: number, powerStats?: ChatReplyPowerStats)
get tokensCount(): number | null
}
diff --git a/bindings/typescript/src/napi/index.js b/bindings/typescript/src/napi/index.js
index 3a6589b49..78da2e56e 100644
--- a/bindings/typescript/src/napi/index.js
+++ b/bindings/typescript/src/napi/index.js
@@ -543,6 +543,7 @@ module.exports.ChatMessage = nativeBinding.ChatMessage
module.exports.ChatModelCapabilities = nativeBinding.ChatModelCapabilities
module.exports.ChatReply = nativeBinding.ChatReply
module.exports.ChatReplyConfig = nativeBinding.ChatReplyConfig
+module.exports.ChatReplyPowerStats = nativeBinding.ChatReplyPowerStats
module.exports.ChatReplyStats = nativeBinding.ChatReplyStats
module.exports.ChatRoleAssistant = nativeBinding.ChatRoleAssistant
module.exports.ChatRoleCustom = nativeBinding.ChatRoleCustom
diff --git a/bindings/typescript/src/napi/index.mjs b/bindings/typescript/src/napi/index.mjs
index 0b42505e5..0e29da716 100644
--- a/bindings/typescript/src/napi/index.mjs
+++ b/bindings/typescript/src/napi/index.mjs
@@ -40,6 +40,7 @@ export const ChatMessage = cjs.ChatMessage;
export const ChatModelCapabilities = cjs.ChatModelCapabilities;
export const ChatReply = cjs.ChatReply;
export const ChatReplyConfig = cjs.ChatReplyConfig;
+export const ChatReplyPowerStats = cjs.ChatReplyPowerStats;
export const ChatReplyStats = cjs.ChatReplyStats;
export const ChatRoleAssistant = cjs.ChatRoleAssistant;
export const ChatRoleCustom = cjs.ChatRoleCustom;
diff --git a/crates/backend-remote/src/openai/stream_state.rs b/crates/backend-remote/src/openai/stream_state.rs
index 5be7b8c4d..2491f6206 100644
--- a/crates/backend-remote/src/openai/stream_state.rs
+++ b/crates/backend-remote/src/openai/stream_state.rs
@@ -138,6 +138,8 @@ impl StreamState {
generate_tokens_per_second,
tokens_count_input: self.tokens_input,
tokens_count_output: self.tokens_output,
+ memory_used_bytes: None,
+ power_stats: None,
}
}
}
diff --git a/crates/backend-uzu/Cargo.toml b/crates/backend-uzu/Cargo.toml
index 7fabdd676..317123e74 100644
--- a/crates/backend-uzu/Cargo.toml
+++ b/crates/backend-uzu/Cargo.toml
@@ -48,6 +48,8 @@ objc2-foundation = { workspace = true, optional = true }
bytesize = { workspace = true, optional = true }
metal = { workspace = true, optional = true }
obfstr = { workspace = true, optional = true }
+# Power telemetry: macOS reads SoC IOReport; iOS reports HID charger "wall" power.
+keisoku.workspace = true
[dev-dependencies]
test-tag.workspace = true
diff --git a/crates/backend-uzu/src/inference/chat/bridging.rs b/crates/backend-uzu/src/inference/chat/bridging.rs
index 71aa2b188..0415c90a8 100644
--- a/crates/backend-uzu/src/inference/chat/bridging.rs
+++ b/crates/backend-uzu/src/inference/chat/bridging.rs
@@ -10,8 +10,8 @@ use shoji::{
},
session::chat::{
ChatConfig as ShojiChatConfig, ChatMessage as ShojiMessage, ChatMessageList, ChatReplyConfig,
- ChatReplyFinishReason as ShojiFinishReason, ChatReplyStats as ShojiStats, ChatRole as ShojiRole,
- ChatSpeculationPreset as ShojiSpeculationPreset,
+ ChatReplyFinishReason as ShojiFinishReason, ChatReplyPowerStats as ShojiPowerStats,
+ ChatReplyStats as ShojiStats, ChatRole as ShojiRole, ChatSpeculationPreset as ShojiSpeculationPreset,
},
},
};
@@ -195,6 +195,18 @@ fn build_stats(stats: &Stats) -> ShojiStats {
let time_to_first_token = Some(stats.prefill_stats.duration);
let prefill_tokens_per_second = Some(stats.prefill_stats.processed_tokens_per_second);
let generate_tokens_per_second = stats.generate_stats.as_ref().map(|step| step.tokens_per_second);
+ let power_stats = stats.power_stats.as_ref().map(|power| ShojiPowerStats {
+ samples_count: power.samples_count.min(i64::MAX as u64) as i64,
+ average_cpu_watts: power.average_cpu_watts,
+ average_gpu_watts: power.average_gpu_watts,
+ average_gpu_sram_watts: power.average_gpu_sram_watts,
+ average_ane_watts: power.average_ane_watts,
+ average_ram_watts: power.average_ram_watts,
+ average_total_watts: power.average_total_watts,
+ average_package_watts: power.average_package_watts,
+ max_package_watts: power.max_package_watts,
+ energy_joules: power.energy_joules,
+ });
ShojiStats {
duration: stats.total_stats.duration,
time_to_first_token,
@@ -202,6 +214,8 @@ fn build_stats(stats: &Stats) -> ShojiStats {
generate_tokens_per_second,
tokens_count_input: Some(stats.total_stats.tokens_count_input as u32),
tokens_count_output: Some(stats.total_stats.tokens_count_output as u32),
+ memory_used_bytes: stats.memory_used_bytes.map(|value| value.min(i64::MAX as u64) as i64),
+ power_stats,
}
}
diff --git a/crates/backend-uzu/src/session/chat_session.rs b/crates/backend-uzu/src/session/chat_session.rs
index a9724b46d..12fadf11c 100644
--- a/crates/backend-uzu/src/session/chat_session.rs
+++ b/crates/backend-uzu/src/session/chat_session.rs
@@ -26,6 +26,7 @@ use crate::{
config::{DecodingConfig, RunConfig},
helpers::{InputProcessor, InputProcessorDefault, OutputParser, is_directory_fits_ram},
parameter::{ConfigResolvableValue, ContextMode, SamplingMethod},
+ power_recorder::PowerRecorder,
types::{Error, FinishReason, Input, Output, RunStats, Stats, StepStats, TotalStats},
},
};
@@ -208,6 +209,7 @@ impl ChatSession {
progress: Option<impl Fn(Output) -> bool>,
) -> Result<Output, Error> {
let run_start = Instant::now();
+ let power_recorder = PowerRecorder::start();
let text = self.input_processor.process(&input, config.enable_thinking, config.tokens_limit > 0)?;
let tokens: Vec<u64> = self
.tokenizer
@@ -288,11 +290,17 @@ impl ChatSession {
};
if !prefill_should_continue || prefill_finish_reason.is_some() {
- if prefill_should_continue {
- return Ok(prefill_output);
+ let output = if prefill_should_continue {
+ prefill_output
} else {
- return Ok(prefill_output.clone_with_finish_reason(Some(FinishReason::Cancelled)));
- }
+ prefill_output.with_finish_reason(Some(FinishReason::Cancelled))
+ };
+ return Ok(Self::attach_runtime_stats(
+ output,
+ run_start.elapsed().as_secs_f64(),
+ language_model_generator.peak_memory_usage(),
+ power_recorder,
+ ));
}
let can_use_async = language_model_generator.generate_suffix_length() == 1 && compiled_grammar.is_none();
@@ -320,7 +328,12 @@ impl ChatSession {
)?
};
- Ok(generate_output.clone_with_duration(run_start.elapsed().as_secs_f64()))
+ Ok(Self::attach_runtime_stats(
+ generate_output,
+ run_start.elapsed().as_secs_f64(),
+ language_model_generator.peak_memory_usage(),
+ power_recorder,
+ ))
}
fn run_sync_generate(
@@ -373,7 +386,7 @@ impl ChatSession {
if generate_should_continue {
return Ok(generate_output);
} else {
- return Ok(generate_output.clone_with_finish_reason(Some(FinishReason::Cancelled)));
+ return Ok(generate_output.with_finish_reason(Some(FinishReason::Cancelled)));
}
}
}
@@ -646,9 +659,23 @@ impl ChatSession {
prefill_stats,
generate_stats,
total_stats,
+ memory_used_bytes: None,
+ power_stats: None,
}
}
+ fn attach_runtime_stats(
+ mut output: Output,
+ duration: f64,
+ memory_used: Option<usize>,
+ power_recorder: PowerRecorder,
+ ) -> Output {
+ output.stats.total_stats.duration = duration;
+ output.stats.memory_used_bytes = memory_used.map(|value| value as u64);
+ output.stats.power_stats = power_recorder.stop();
+ output
+ }
+
pub fn peak_memory_usage(&self) -> Option<usize> {
self.llm.peak_memory_usage()
}
diff --git a/crates/backend-uzu/src/session/mod.rs b/crates/backend-uzu/src/session/mod.rs
index b915dc8cc..210e24039 100644
--- a/crates/backend-uzu/src/session/mod.rs
+++ b/crates/backend-uzu/src/session/mod.rs
@@ -3,6 +3,7 @@ pub mod classification_session;
pub mod config;
pub mod helpers;
pub mod parameter;
+mod power_recorder;
#[cfg(metal_backend)]
mod tts_session;
pub mod types;
diff --git a/crates/backend-uzu/src/session/power_recorder.rs b/crates/backend-uzu/src/session/power_recorder.rs
new file mode 100644
index 000000000..673b41a03
--- /dev/null
+++ b/crates/backend-uzu/src/session/power_recorder.rs
@@ -0,0 +1,37 @@
+use crate::session::types::PowerStats;
+
+// Background power sampler for one generation: drives keisoku's recorder on Apple, no-op elsewhere.
+pub(crate) struct PowerRecorder {
+ #[cfg(target_vendor = "apple")]
+ handle: keisoku::RecorderHandle,
+}
+
+impl PowerRecorder {
+ pub(crate) fn start() -> Self {
+ #[cfg(target_vendor = "apple")]
+ {
+ Self {
+ handle: keisoku::start(keisoku::Config {
+ interval: std::time::Duration::from_millis(100),
+ }),
+ }
+ }
+
+ #[cfg(not(target_vendor = "apple"))]
+ {
+ Self {}
+ }
+ }
+
+ pub(crate) fn stop(self) -> Option<PowerStats> {
+ #[cfg(target_vendor = "apple")]
+ {
+ PowerStats::from_keisoku_session(&self.handle.stop())
+ }
+
+ #[cfg(not(target_vendor = "apple"))]
+ {
+ None
+ }
+ }
+}
diff --git a/crates/backend-uzu/src/session/types/mod.rs b/crates/backend-uzu/src/session/types/mod.rs
index 347da0aa3..ab9dcd0c4 100644
--- a/crates/backend-uzu/src/session/types/mod.rs
+++ b/crates/backend-uzu/src/session/types/mod.rs
@@ -10,5 +10,5 @@ pub use input::Input;
pub use message::Message;
pub use output::{FinishReason, Output};
pub use role::Role;
-pub use stats::{RunStats, Stats, StepStats, TotalStats};
+pub use stats::{PowerStats, RunStats, Stats, StepStats, TotalStats};
pub use text::{ParsedText, Text};
diff --git a/crates/backend-uzu/src/session/types/output.rs b/crates/backend-uzu/src/session/types/output.rs
index fbdac3ccd..2662eb1e7 100644
--- a/crates/backend-uzu/src/session/types/output.rs
+++ b/crates/backend-uzu/src/session/types/output.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
-use crate::session::types::{Stats, Text, TotalStats};
+use crate::session::types::{Stats, Text};
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
@@ -19,32 +19,11 @@ pub struct Output {
}
impl Output {
- pub fn clone_with_finish_reason(
- &self,
+ pub fn with_finish_reason(
+ mut self,
finish_reason: Option<FinishReason>,
) -> Self {
- Self {
- text: self.text.clone(),
- stats: self.stats.clone(),
- finish_reason,
- }
- }
-
- pub fn clone_with_duration(
- &self,
- duration: f64,
- ) -> Self {
- Self {
- text: self.text.clone(),
- stats: Stats {
- prefill_stats: self.stats.prefill_stats.clone(),
- generate_stats: self.stats.generate_stats.clone(),
- total_stats: TotalStats {
- duration,
- ..self.stats.total_stats.clone()
- },
- },
- finish_reason: self.finish_reason.clone(),
- }
+ self.finish_reason = finish_reason;
+ self
}
}
diff --git a/crates/backend-uzu/src/session/types/stats.rs b/crates/backend-uzu/src/session/types/stats.rs
index cace999a3..29ce9e15d 100644
--- a/crates/backend-uzu/src/session/types/stats.rs
+++ b/crates/backend-uzu/src/session/types/stats.rs
@@ -1,5 +1,88 @@
use serde::{Deserialize, Serialize};
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct PowerStats {
+ pub samples_count: u64,
+ pub average_cpu_watts: f64,
+ pub average_gpu_watts: f64,
+ pub average_gpu_sram_watts: f64,
+ pub average_ane_watts: f64,
+ pub average_ram_watts: f64,
+ pub average_total_watts: f64,
+ pub average_package_watts: f64,
+ pub max_package_watts: f64,
+ pub energy_joules: f64,
+}
+
+#[cfg(target_vendor = "apple")]
+impl PowerStats {
+ pub(crate) fn from_keisoku_session(session: &keisoku::Session) -> Option<Self> {
+ let mut samples_count = 0_u64;
+ // Each accumulator integrates watts over time (watts × seconds); the time-weighted
+ // average is the integral divided by total_elapsed_secs.
+ let mut cpu_joules = 0.0_f64;
+ let mut gpu_joules = 0.0_f64;
+ let mut gpu_sram_joules = 0.0_f64;
+ let mut ane_joules = 0.0_f64;
+ let mut ram_joules = 0.0_f64;
+ let mut total_joules = 0.0_f64;
+ let mut energy_joules = 0.0_f64;
+ let mut max_package_watts = 0.0_f64;
+ let mut previous_elapsed_secs = 0.0_f64;
+ let mut total_elapsed_secs = 0.0_f64;
+
+ for snapshot in &session.snapshots {
+ // elapsed is stamped after each sample, so consecutive gaps partition the
+ // recording timeline without overlap.
+ let elapsed_secs = snapshot.elapsed.value() as f64 / 1000.0;
+ let window_secs = (elapsed_secs - previous_elapsed_secs).max(0.0);
+ previous_elapsed_secs = elapsed_secs;
+
+ // Prefer SoC IOReport power (macOS); fall back to HID rail power on iOS.
+ let wall_watts = match snapshot.power.as_ref() {
+ Some(power) => {
+ cpu_joules += power.cpu.value() as f64 * window_secs;
+ gpu_joules += power.gpu.value() as f64 * window_secs;
+ gpu_sram_joules += power.gpu_sram.value() as f64 * window_secs;
+ ane_joules += power.ane.value() as f64 * window_secs;
+ ram_joules += power.ram.value() as f64 * window_secs;
+ total_joules += power.total.value() as f64 * window_secs;
+ power.package.value() as f64
+ },
+ None => match snapshot.rail_power() {
+ Some(rail_watts) => {
+ let rail_watts = rail_watts.value() as f64;
+ total_joules += rail_watts * window_secs;
+ rail_watts
+ },
+ None => continue,
+ },
+ };
+ samples_count += 1;
+ max_package_watts = max_package_watts.max(wall_watts);
+ energy_joules += wall_watts * window_secs;
+ total_elapsed_secs = elapsed_secs;
+ }
+
+ if samples_count == 0 || total_elapsed_secs <= 0.0 {
+ return None;
+ }
+
+ Some(Self {
+ samples_count,
+ average_cpu_watts: cpu_joules / total_elapsed_secs,
+ average_gpu_watts: gpu_joules / total_elapsed_secs,
+ average_gpu_sram_watts: gpu_sram_joules / total_elapsed_secs,
+ average_ane_watts: ane_joules / total_elapsed_secs,
+ average_ram_watts: ram_joules / total_elapsed_secs,
+ average_total_watts: total_joules / total_elapsed_secs,
+ average_package_watts: energy_joules / total_elapsed_secs,
+ max_package_watts,
+ energy_joules,
+ })
+ }
+}
+
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RunStats {
pub count: u64,
@@ -31,4 +114,6 @@ pub struct Stats {
pub prefill_stats: StepStats,
pub generate_stats: Option<StepStats>,
pub total_stats: TotalStats,
+ pub memory_used_bytes: Option<u64>,
+ pub power_stats: Option<PowerStats>,
}
diff --git a/crates/benchmarks/src/runner/runner.rs b/crates/benchmarks/src/runner/runner.rs
index 83e144087..d66bd6186 100644
--- a/crates/benchmarks/src/runner/runner.rs
+++ b/crates/benchmarks/src/runner/runner.rs
@@ -69,7 +69,10 @@ impl Runner {
}
let output = session.run(input.clone(), run_config, Option::<fn(Output) -> bool>::None)?;
- let memory_used = session.peak_memory_usage();
+ let memory_used =
+ output.stats.memory_used_bytes.map(|value| value as usize).or_else(|| session.peak_memory_usage());
+ let power_stats = output.stats.power_stats.clone();
+ let generate_tokens_per_second = output.stats.generate_stats.as_ref().map(|stats| stats.tokens_per_second);
let result = TaskResult {
task: self.task.clone(),
@@ -78,11 +81,12 @@ impl Runner {
timestamp,
data_type,
memory_used,
+ power_stats,
tokens_count_input: output.stats.total_stats.tokens_count_input,
tokens_count_output: output.stats.total_stats.tokens_count_output,
time_to_first_token: output.stats.prefill_stats.duration,
prompt_tokens_per_second: output.stats.prefill_stats.processed_tokens_per_second,
- generate_tokens_per_second: output.stats.generate_stats.map(|stats| stats.tokens_per_second),
+ generate_tokens_per_second,
text: output.text.original,
};
results.push(result);
diff --git a/crates/benchmarks/src/runner/types/result.rs b/crates/benchmarks/src/runner/types/result.rs
index a09dab8c9..6df1898e8 100644
--- a/crates/benchmarks/src/runner/types/result.rs
+++ b/crates/benchmarks/src/runner/types/result.rs
@@ -1,4 +1,4 @@
-use backend_uzu::data_type::DataType;
+use backend_uzu::{data_type::DataType, session::types::PowerStats};
use serde::{Deserialize, Serialize};
use crate::runner::types::{Device, Task};
@@ -11,6 +11,7 @@ pub struct Result {
pub timestamp: u64,
pub data_type: DataType,
pub memory_used: Option<usize>,
+ pub power_stats: Option<PowerStats>,
pub tokens_count_input: u64,
pub tokens_count_output: u64,
pub time_to_first_token: f64,
diff --git a/crates/cli/src/bench.rs b/crates/cli/src/bench.rs
index 297e53084..29cf10126 100644
--- a/crates/cli/src/bench.rs
+++ b/crates/cli/src/bench.rs
@@ -53,11 +53,26 @@ fn print_summary(results: &[BenchmarkResult]) -> Result<()> {
results.iter().map(|result| result.prompt_tokens_per_second).collect::<Vec<f64>>();
let generate_tokens_per_second_list =
results.iter().filter_map(|result| result.generate_tokens_per_second).collect::<Vec<f64>>();
+ let average_package_power_list = results
+ .iter()
+ .filter_map(|result| result.power_stats.as_ref().map(|power| power.average_package_watts))
+ .collect::<Vec<f64>>();
+ let max_package_power_list = results
+ .iter()
+ .filter_map(|result| result.power_stats.as_ref().map(|power| power.max_package_watts))
+ .collect::<Vec<f64>>();
+ let package_energy_list = results
+ .iter()
+ .filter_map(|result| result.power_stats.as_ref().map(|power| power.energy_joules))
+ .collect::<Vec<f64>>();
let memory_used_metric = calculate_metric(&memory_used_list);
let time_to_first_token_metric = calculate_metric(&time_to_first_token_list);
let prompt_tokens_per_second_metric = calculate_metric(&prompt_tokens_per_second_list);
let generate_tokens_per_second_metric = calculate_metric(&generate_tokens_per_second_list);
+ let average_package_power_metric = calculate_metric(&average_package_power_list);
+ let max_package_power_metric = calculate_metric(&max_package_power_list);
+ let package_energy_metric = calculate_metric(&package_energy_list);
let mut table = Table::new();
table
@@ -68,7 +83,10 @@ fn print_summary(results: &[BenchmarkResult]) -> Result<()> {
.add_row(vec!["Used memory, GB", memory_used_metric.as_str()])
.add_row(vec!["TTFT, s", time_to_first_token_metric.as_str()])
.add_row(vec!["Prompt, t/s", prompt_tokens_per_second_metric.as_str()])
- .add_row(vec!["Generate, t/s", generate_tokens_per_second_metric.as_str()]);
+ .add_row(vec!["Generate, t/s", generate_tokens_per_second_metric.as_str()])
+ .add_row(vec!["Avg package power, W", average_package_power_metric.as_str()])
+ .add_row(vec!["Max package power, W", max_package_power_metric.as_str()])
+ .add_row(vec!["Package energy, J", package_energy_metric.as_str()]);
let Some(column) = table.column_mut(1) else {
bail!("Benchmark summary table value column is missing");
diff --git a/crates/kanka/Cargo.toml b/crates/kanka/Cargo.toml
index e6df21352..baea518e1 100644
--- a/crates/kanka/Cargo.toml
+++ b/crates/kanka/Cargo.toml
@@ -8,6 +8,7 @@ homepage.workspace = true
repository.workspace = true
license.workspace = true
description = "Generic obfuscated dlsym bindings for private Apple framework APIs"
+readme = "README.md"
[lib]
name = "kanka"
diff --git a/crates/kanka/README.md b/crates/kanka/README.md
new file mode 100644
index 000000000..051222239
--- /dev/null
+++ b/crates/kanka/README.md
@@ -0,0 +1,20 @@
+# kanka
+
+Internal helper crate (甘果, "sweet fruit"): generic `dlsym`-resolved bindings to private
+Apple framework functions, with obfuscated symbol names. This is the low-level plumbing
+[`keisoku`](../keisoku) uses to reach the IOReport/SMC power and telemetry APIs that have no
+public headers.
+
+It contains no power logic itself — just two macros:
+
+- `ffi_table!` — declares a struct of `dlsym`-resolved C function pointers from a named
+ framework, with a `OnceLock`-cached `get()` (symbol and framework names are obfuscated at
+ compile time via `obfstr`).
+- `opaque_cf_type!` — declares an opaque CoreFoundation handle type usable with `CFRetained`.
+
+## Platform
+
+Apple only (`target_vendor = "apple"`). On other platforms the macros expand to nothing
+usable and the crate is effectively empty.
+
+You normally don't depend on this directly — use [`keisoku`](../keisoku).
diff --git a/crates/kanshi/Cargo.toml b/crates/kanshi/Cargo.toml
index aec918769..9b11197ff 100644
--- a/crates/kanshi/Cargo.toml
+++ b/crates/kanshi/Cargo.toml
@@ -8,6 +8,7 @@ homepage.workspace = true
repository.workspace = true
license.workspace = true
description = "mactop-style live system monitor built on keisoku"
+readme = "README.md"
[[bin]]
name = "kanshi"
diff --git a/crates/kanshi/README.md b/crates/kanshi/README.md
new file mode 100644
index 000000000..32ea8dbce
--- /dev/null
+++ b/crates/kanshi/README.md
@@ -0,0 +1,24 @@
+# kanshi
+
+A live terminal system monitor (mactop/asitop-style) built on [`keisoku`](../keisoku).
+It samples the SoC on a background thread and renders it in a `ratatui` TUI.
+
+## Run
+
+```bash
+cargo run -p kanshi --release
+```
+
+Press `q` (or `Ctrl-C`) to quit.
+
+## Shows
+
+- CPU/GPU/ANE power (Watts) and usage, with history charts
+- Frequencies, memory and DRAM bandwidth, temperatures
+- Top processes, network and disk activity (via `sysinfo`)
+- Device summary (chip, GPU cores, RAM)
+
+## Platform
+
+Full power/SoC telemetry is Apple Silicon (macOS) only — that's where keisoku's counters
+exist. On other platforms it still runs but power/GPU panels are empty.
diff --git a/crates/keisoku/Cargo.toml b/crates/keisoku/Cargo.toml
index eb63d28eb..1e7352513 100644
--- a/crates/keisoku/Cargo.toml
+++ b/crates/keisoku/Cargo.toml
@@ -8,6 +8,7 @@ homepage.workspace = true
repository.workspace = true
license.workspace = true
description = "System telemetry collector (CPU/GPU/RAM/power/sensors) for Apple platforms"
+readme = "README.md"
[lib]
name = "keisoku"
diff --git a/crates/keisoku/README.md b/crates/keisoku/README.md
new file mode 100644
index 000000000..e43afa80a
--- /dev/null
+++ b/crates/keisoku/README.md
@@ -0,0 +1,44 @@
+# keisoku
+
+System telemetry collector for Apple platforms — CPU/GPU/ANE power, memory, bandwidth,
+frequencies, temperatures and sensors. Power is read from the SoC's IOReport/SMC counters,
+so sampling runs off your work thread and adds no measurable load.
+
+## Two ways to use it
+
+**One-shot** — take a single reading averaged over a window:
+
+```rust
+let mut collector = keisoku::Collector::new();
+let snapshot = collector.sample(std::time::Duration::from_millis(100));
+if let Some(power) = snapshot.power {
+ println!("gpu {} / total {}", power.gpu, power.total); // Watts
+}
+```
+
+**Background recorder** — sample at an interval while something runs, then collect:
+
+```rust
+let recorder = keisoku::start(keisoku::Config {
+ interval: std::time::Duration::from_millis(100),
+});
+// ... do work ...
+let session = recorder.stop(); // stops the sampler, returns what it collected
+let samples = session.snapshots.len();
+```
+
+## What you get back
+
+- `Session { interval, snapshots }` — the snapshots sampled between `start` and `stop`.
+- `Snapshot { elapsed, power, memory, cpu, gpu, neural_engine, bandwidth, temperatures, .. }`.
+- `PowerMetrics { cpu, gpu, gpu_sram, ane, ram, total, package }` — all `Watts`.
+- `Device { chip, gpu_cores, performance_cores, efficiency_cores, ram_total, os }`.
+
+## Platform
+
+Real numbers on Apple Silicon (macOS, and iOS for the subset exposed there). On other
+platforms the power/SoC fields are `None` and the calls are safe no-ops, so code that
+depends on keisoku still builds and runs everywhere.
+
+Used by [`kanshi`](../kanshi) (live monitor); reaches Apple's private counters via
+[`kanka`](../kanka).
diff --git a/crates/keisoku/src/client/mod.rs b/crates/keisoku/src/client/mod.rs
index a510610c7..6fd25852a 100644
--- a/crates/keisoku/src/client/mod.rs
+++ b/crates/keisoku/src/client/mod.rs
@@ -114,7 +114,8 @@ impl SensorReader {
category: service.string(obfstr!("Category")),
location_id: service.i64_value(obfstr!("LocationID")),
registry_id: service.registry_id(),
- hot: is_hot(component),
+ // Power rails change continuously, so refresh them every read (not just cold).
+ hot: is_hot(component) || matches!(kind, SensorKind::Voltage | SensorKind::Current),
component,
name,
value,
diff --git a/crates/keisoku/src/collector.rs b/crates/keisoku/src/collector.rs
index 78f055162..2ef715c42 100644
--- a/crates/keisoku/src/collector.rs
+++ b/crates/keisoku/src/collector.rs
@@ -29,6 +29,10 @@ pub struct Collector {
smc: Option<crate::smc::Smc>,
#[cfg(target_vendor = "apple")]
temperature_reader: Option<crate::client::SensorReader>,
+ #[cfg(target_vendor = "apple")]
+ voltage_reader: Option<crate::client::SensorReader>,
+ #[cfg(target_vendor = "apple")]
+ current_reader: Option<crate::client::SensorReader>,
}
impl Default for Collector {
@@ -50,6 +54,10 @@ impl Collector {
smc: crate::smc::Smc::new(),
#[cfg(target_vendor = "apple")]
temperature_reader: crate::client::SensorReader::new(SensorKind::Temperature),
+ #[cfg(target_vendor = "apple")]
+ voltage_reader: crate::client::SensorReader::new(SensorKind::Voltage),
+ #[cfg(target_vendor = "apple")]
+ current_reader: crate::client::SensorReader::new(SensorKind::Current),
}
}
@@ -75,6 +83,14 @@ impl Collector {
let sensors = self.temperature_reader.as_mut().map(crate::client::SensorReader::read).unwrap_or_default();
#[cfg(not(target_vendor = "apple"))]
let sensors = crate::sensors(SensorKind::Temperature);
+ #[cfg(target_vendor = "apple")]
+ let voltage = self.voltage_reader.as_mut().map(crate::client::SensorReader::read).unwrap_or_default();
+ #[cfg(not(target_vendor = "apple"))]
+ let voltage = crate::sensors(SensorKind::Voltage);
+ #[cfg(target_vendor = "apple")]
+ let current = self.current_reader.as_mut().map(crate::client::SensorReader::read).unwrap_or_default();
+ #[cfg(not(target_vendor = "apple"))]
+ let current = crate::sensors(SensorKind::Current);
let temperatures = (!sensors.is_empty()).then(|| temperatures_from(&sensors));
Snapshot {
elapsed: Milliseconds(0),
@@ -89,6 +105,8 @@ impl Collector {
temperatures,
thermal_pressure,
sensors,
+ voltage,
+ current,
}
}
diff --git a/crates/keisoku/src/lib.rs b/crates/keisoku/src/lib.rs
index 8a6e02309..67ed5793b 100644
--- a/crates/keisoku/src/lib.rs
+++ b/crates/keisoku/src/lib.rs
@@ -27,7 +27,7 @@ pub use metrics::{
BandwidthMetrics, BatteryMetrics, CpuMetrics, Fan, FanMetrics, GpuMetrics, MemoryMetrics, NeuralEngineMetrics,
PowerMetrics, Temperatures, ThermalPressure,
};
-pub use recorder::{Config, Device, Marker, RecorderHandle, Session, start};
+pub use recorder::{Config, Device, RecorderHandle, Session, start};
pub use sensor::{Sensor, SensorKind, current_sensors, thermal_sensors, voltage_sensors};
pub use snapshot::Snapshot;
pub use units::{Bytes, Celsius, GigabytesPerSecond, Megahertz, Milliseconds, Percent, Rpm, Watts};
diff --git a/crates/keisoku/src/recorder/handle.rs b/crates/keisoku/src/recorder/handle.rs
index a2f721dff..fb14de1df 100644
--- a/crates/keisoku/src/recorder/handle.rs
+++ b/crates/keisoku/src/recorder/handle.rs
@@ -3,53 +3,39 @@ use std::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
- thread::JoinHandle,
time::{Duration, Instant},
};
-use super::{Config, Device, Marker, Session};
+use super::{Config, Session};
use crate::{Collector, snapshot::Snapshot, units::Milliseconds};
pub struct RecorderHandle {
- started_at: Instant,
interval: Duration,
stop_flag: Arc<AtomicBool>,
- markers: Arc<Mutex<Vec<Marker>>>,
- worker: Option<JoinHandle<(Device, Vec<Snapshot>)>>,
+ snapshots: Arc<Mutex<Vec<Snapshot>>>,
+ // Option so both stop() and Drop can take ownership to join.
+ worker: Option<std::thread::JoinHandle<()>>,
}
impl RecorderHandle {
- pub fn mark(
- &self,
- label: impl Into<String>,
- ) {
- let elapsed = Milliseconds(self.started_at.elapsed().as_millis() as u64);
- if let Ok(mut markers) = self.markers.lock() {
- markers.push(Marker {
- elapsed,
- label: label.into(),
- });
- }
- }
-
pub fn stop(mut self) -> Session {
self.stop_flag.store(true, Ordering::Relaxed);
- let (device, snapshots) = match self.worker.take().map(JoinHandle::join) {
- Some(Ok(result)) => result,
- _ => (Device::default(), Vec::new()),
- };
- let markers = self.markers.lock().map(|markers| markers.clone()).unwrap_or_default();
+ // Join so the in-flight sample is committed before we read the buffer, and so
+ // workers can't pile up across back-to-back recorders. Waits up to one interval.
+ if let Some(worker) = self.worker.take() {
+ let _ = worker.join();
+ }
+ let snapshots = self.snapshots.lock().map(|mut collected| std::mem::take(&mut *collected)).unwrap_or_default();
Session {
- device,
interval: Milliseconds(self.interval.as_millis() as u64),
snapshots,
- markers,
}
}
}
impl Drop for RecorderHandle {
fn drop(&mut self) {
+ // Reached only when stop() was not called, e.g. an error path.
self.stop_flag.store(true, Ordering::Relaxed);
if let Some(worker) = self.worker.take() {
let _ = worker.join();
@@ -58,32 +44,31 @@ impl Drop for RecorderHandle {
}
pub fn start(config: Config) -> RecorderHandle {
- let started_at = Instant::now();
let interval = config.interval;
let stop_flag = Arc::new(AtomicBool::new(false));
- let markers = Arc::new(Mutex::new(Vec::new()));
+ let snapshots = Arc::new(Mutex::new(Vec::new()));
let worker = {
let stop_flag = Arc::clone(&stop_flag);
-
+ let snapshots = Arc::clone(&snapshots);
std::thread::spawn(move || {
let mut collector = Collector::new();
- let device = Device::detect(&collector);
- let mut snapshots = Vec::new();
+ // Start the clock after Collector::new() so elapsed excludes init overhead.
+ let started_at = Instant::now();
while !stop_flag.load(Ordering::Relaxed) {
let mut snapshot = collector.sample(interval);
snapshot.elapsed = Milliseconds(started_at.elapsed().as_millis() as u64);
- snapshots.push(snapshot);
+ if let Ok(mut collected) = snapshots.lock() {
+ collected.push(snapshot);
+ }
}
- (device, snapshots)
})
};
RecorderHandle {
- started_at,
interval,
stop_flag,
- markers,
+ snapshots,
worker: Some(worker),
}
}
diff --git a/crates/keisoku/src/recorder/marker.rs b/crates/keisoku/src/recorder/marker.rs
deleted file mode 100644
index 065be0f61..000000000
--- a/crates/keisoku/src/recorder/marker.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-use crate::units::Milliseconds;
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct Marker {
- pub elapsed: Milliseconds,
- pub label: String,
-}
diff --git a/crates/keisoku/src/recorder/mod.rs b/crates/keisoku/src/recorder/mod.rs
index 93fec7811..6ee7df232 100644
--- a/crates/keisoku/src/recorder/mod.rs
+++ b/crates/keisoku/src/recorder/mod.rs
@@ -1,11 +1,9 @@
mod config;
mod device;
mod handle;
-mod marker;
mod session;
pub use config::Config;
pub use device::Device;
pub use handle::{RecorderHandle, start};
-pub use marker::Marker;
pub use session::Session;
diff --git a/crates/keisoku/src/recorder/session.rs b/crates/keisoku/src/recorder/session.rs
index bb5d1ea82..69f8d339c 100644
--- a/crates/keisoku/src/recorder/session.rs
+++ b/crates/keisoku/src/recorder/session.rs
@@ -1,26 +1,8 @@
-use serde::{Deserialize, Serialize};
-
-use super::{Device, Marker};
use crate::{snapshot::Snapshot, units::Milliseconds};
-#[derive(Debug, Default, Clone, Serialize, Deserialize)]
+/// Snapshots collected between `start` and `stop`, with the sampling interval.
+#[derive(Debug, Default, Clone)]
pub struct Session {
- pub device: Device,
pub interval: Milliseconds,
pub snapshots: Vec<Snapshot>,
- pub markers: Vec<Marker>,
-}
-
-impl Session {
- pub fn to_json(&self) -> serde_json::Result<String> {
- serde_json::to_string_pretty(self)
- }
-
- pub fn write_json(
- &self,
- path: impl AsRef<std::path::Path>,
- ) -> std::io::Result<()> {
- let json = self.to_json().map_err(std::io::Error::other)?;
- std::fs::write(path, json)
- }
}
diff --git a/crates/keisoku/src/snapshot.rs b/crates/keisoku/src/snapshot.rs
index b503c2e78..00b4e791a 100644
--- a/crates/keisoku/src/snapshot.rs
+++ b/crates/keisoku/src/snapshot.rs
@@ -6,7 +6,7 @@ use crate::{
PowerMetrics, Temperatures, ThermalPressure,
},
sensor::Sensor,
- units::Milliseconds,
+ units::{Milliseconds, Watts},
};
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
@@ -23,4 +23,45 @@ pub struct Snapshot {
pub temperatures: Option<Temperatures>,
pub thermal_pressure: Option<ThermalPressure>,
pub sensors: Vec<Sensor>,
+ /// HID voltage rails; on iOS the only un-gated electrical signal, empty elsewhere.
+ #[serde(default)]
+ pub voltage: Vec<Sensor>,
+ /// HID current rails, paired with [`Snapshot::voltage`] by rail code.
+ #[serde(default)]
+ pub current: Vec<Sensor>,
+}
+
+impl Snapshot {
+ /// Sum of charger/battery watts from matched HID voltage×current rails
+ /// (e.g. `Charger VQ0u`×`Charger IQ0u`). An estimate, unlike IOReport [`Snapshot::power`].
+ pub fn rail_power(&self) -> Option<Watts> {
+ use crate::component::Component;
+ // Power magnitude so battery discharge (negative current when unplugged) counts too;
+ // the ceiling rejects mismatched-unit pairs, well above real charge/discharge.
+ const MAX_PLAUSIBLE_WATTS: f64 = 1000.0;
+ let split_area_code = |name: &str| name.rsplit_once(' ').map(|(area, code)| (area.to_owned(), code.to_owned()));
+ let is_battery_rail = |sensor: &&Sensor| matches!(sensor.component, Component::Charger | Component::Battery);
+
+ let mut total_watts = 0f64;
+ for voltage_sensor in self.voltage.iter().filter(is_battery_rail) {
+ let Some((voltage_area, voltage_code)) = split_area_code(&voltage_sensor.name) else {
+ continue;
+ };
+ let Some(rail_code) = voltage_code.strip_prefix('V').filter(|code| !code.is_empty()) else {
+ continue;
+ };
+ for current_sensor in self.current.iter().filter(is_battery_rail) {
+ let Some((current_area, current_code)) = split_area_code(&current_sensor.name) else {
+ continue;
+ };
+ if current_area == voltage_area && current_code.strip_prefix('I') == Some(rail_code) {
+ let watts = (voltage_sensor.value * current_sensor.value).abs();
+ if (0.0..=MAX_PLAUSIBLE_WATTS).contains(&watts) {
+ total_watts += watts;
+ }
+ }
+ }
+ }
+ (total_watts > 0.0).then_some(Watts(total_watts as f32))
+ }
}
diff --git a/crates/keisoku/tests/telemetry.rs b/crates/keisoku/tests/telemetry.rs
index cf888e9d7..d2d82d76b 100644
--- a/crates/keisoku/tests/telemetry.rs
+++ b/crates/keisoku/tests/telemetry.rs
@@ -34,6 +34,9 @@ fn available_telemetry() {
println!("battery {}", flag(snapshot.battery.is_some()));
println!("temps {}", flag(snapshot.temperatures.is_some()));
println!("sensors {}", snapshot.sensors.len());
+ println!("voltage {}", snapshot.voltage.len());
+ println!("current {}", snapshot.current.len());
+ println!("rail_power {}", snapshot.rail_power().map_or("--".into(), |w| format!("{:.2} W", w.value())));
if let Some(memory) = &snapshot.memory {
println!(
@@ -53,4 +56,10 @@ fn available_telemetry() {
for sensor in snapshot.sensors.iter().take(24) {
println!(" {:<26} {:>8.2} [{}]", sensor.name, sensor.value, sensor.component);
}
+ for volts in &snapshot.voltage {
+ println!(" {:<26} {:>8.3} V [{}]", volts.name, volts.value, volts.component);
+ }
+ for amps in &snapshot.current {
+ println!(" {:<26} {:>8.3} A [{}]", amps.name, amps.value, amps.component);
+ }
}
diff --git a/crates/shoji/src/types/session/chat/mod.rs b/crates/shoji/src/types/session/chat/mod.rs
index 6e3c3669f..f7957d094 100644
--- a/crates/shoji/src/types/session/chat/mod.rs
+++ b/crates/shoji/src/types/session/chat/mod.rs
@@ -10,6 +10,6 @@ pub use capabilities::ChatModelCapabilities;
pub use config::ChatConfig;
pub use content_block::{ChatContentBlock, ChatContentBlockType};
pub use message::{ChatMessage, ChatMessageList, ChatMessageMetadata};
-pub use reply::{ChatReply, ChatReplyConfig, ChatReplyFinishReason, ChatReplyStats};
+pub use reply::{ChatReply, ChatReplyConfig, ChatReplyFinishReason, ChatReplyPowerStats, ChatReplyStats};
pub use role::ChatRole;
pub use speculation_preset::ChatSpeculationPreset;
diff --git a/crates/shoji/src/types/session/chat/reply/mod.rs b/crates/shoji/src/types/session/chat/reply/mod.rs
index c43233df2..9bbc70e9f 100644
--- a/crates/shoji/src/types/session/chat/reply/mod.rs
+++ b/crates/shoji/src/types/session/chat/reply/mod.rs
@@ -5,7 +5,7 @@ mod stats;
pub use config::ChatReplyConfig;
pub use finish_reason::ChatReplyFinishReason;
use serde::{Deserialize, Serialize};
-pub use stats::ChatReplyStats;
+pub use stats::{ChatReplyPowerStats, ChatReplyStats};
use crate::types::session::chat::ChatMessage;
diff --git a/crates/shoji/src/types/session/chat/reply/stats.rs b/crates/shoji/src/types/session/chat/reply/stats.rs
index c63148f8e..b04e89094 100644
--- a/crates/shoji/src/types/session/chat/reply/stats.rs
+++ b/crates/shoji/src/types/session/chat/reply/stats.rs
@@ -1,5 +1,20 @@
use serde::{Deserialize, Serialize};
+#[bindings::export(Structure(Class))]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
+pub struct ChatReplyPowerStats {
+ pub samples_count: i64,
+ pub average_cpu_watts: f64,
+ pub average_gpu_watts: f64,
+ pub average_gpu_sram_watts: f64,
+ pub average_ane_watts: f64,
+ pub average_ram_watts: f64,
+ pub average_total_watts: f64,
+ pub average_package_watts: f64,
+ pub max_package_watts: f64,
+ pub energy_joules: f64,
+}
+
#[bindings::export(Structure(Class))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ChatReplyStats {
@@ -9,6 +24,8 @@ pub struct ChatReplyStats {
pub generate_tokens_per_second: Option<f64>,
pub tokens_count_input: Option<u32>,
pub tokens_count_output: Option<u32>,
+ pub memory_used_bytes: Option<i64>,
+ pub power_stats: Option<ChatReplyPowerStats>,
}
#[bindings::export(Implementation)]
diff --git a/crates/uzu/src/cli/components/history_cell.rs b/crates/uzu/src/cli/components/history_cell.rs
index adcb37189..0e1145af9 100644
--- a/crates/uzu/src/cli/components/history_cell.rs
+++ b/crates/uzu/src/cli/components/history_cell.rs
@@ -188,6 +188,21 @@ fn chat_reply_stats_component(
.generate_tokens_per_second
.map(|tokens_per_second| format!("{tokens_per_second:.2} t/s"))
.unwrap_or_else(|| SYMBOL_LONG_DASH.to_string());
+ let prefill_speed = stats
+ .prefill_tokens_per_second
+ .map(|tokens_per_second| format!("{tokens_per_second:.2} t/s"))
+ .unwrap_or_else(|| SYMBOL_LONG_DASH.to_string());
+ let memory_used = stats.memory_used_bytes.map(format_memory_used).unwrap_or_else(|| SYMBOL_LONG_DASH.to_string());
+ let power = stats
+ .power_stats
+ .as_ref()
+ .map(|power| format!("{:.2} W avg / {:.2} W max", power.average_package_watts, power.max_package_watts))
+ .unwrap_or_else(|| SYMBOL_LONG_DASH.to_string());
+ let energy = stats
+ .power_stats
+ .as_ref()
+ .map(|power| format!("{:.2} J", power.energy_joules))
+ .unwrap_or_else(|| SYMBOL_LONG_DASH.to_string());
let duration = format!("{:.2} s", stats.duration);
element! {
@@ -199,10 +214,26 @@ fn chat_reply_stats_component(
content: format!("time to first token: {time_to_first_token}"),
color: subtitle_color,
)
+ Text(
+ content: format!("prefill speed: {prefill_speed}"),
+ color: subtitle_color,
+ )
Text(
content: format!("generation speed: {generation_speed}"),
color: subtitle_color,
)
+ Text(
+ content: format!("memory used: {memory_used}"),
+ color: subtitle_color,
+ )
+ Text(
+ content: format!("package power: {power}"),
+ color: subtitle_color,
+ )
+ Text(
+ content: format!("package energy: {energy}"),
+ color: subtitle_color,
+ )
Text(
content: format!("duration: {duration}"),
color: subtitle_color,
@@ -212,6 +243,11 @@ fn chat_reply_stats_component(
.into()
}
+fn format_memory_used(bytes: i64) -> String {
+ let gibibytes = bytes.max(0) as f64 / 1024.0 / 1024.0 / 1024.0;
+ format!("{gibibytes:.2} GB")
+}
+
fn text_to_speech_output_component(
stats: TextToSpeechStats,
subtitle_color: Color,