The user wants a code solution: "Build an on-device ML inference profiler for edge appliances: instrumentation, energy measurement, model switching, and reporting cadence."
We need to produce a complete implementation in Python (likely). It should be a profiler that runs on edge devices (like Raspberry Pi, etc.) instrumenting ML inference. It should include:
- Instrumentation: capturing metrics like inference time, memory usage, possibly CPU/GPU utilization, etc.
- Energy measurement: measure power consumption during inference (maybe using a hardware sensor or software estimation). Since on-device, we might need to integrate with power measurement APIs (like reading from INA219 or using /sys/class/power). But for simplicity, we could simulate or use estimates if hardware not available. Provide an interface to read actual energy if available.
- Model switching: ability to switch between different ML models (like different architectures or quantized versions) and compare.
- Reporting cadence: periodic reporting of collected metrics, perhaps to a log file or cloud.
We need to design a class or set of classes that make it easy to profile inference runs, collect metrics, and generate reports.
Let's outline:
-
Profiler class: Main class that will be used to wrap model inference. It could be used as a context manager or decorator.
-
Metrics to collect:
- Inference latency (start to end)
- Throughput (maybe for batch)
- Memory usage (before and after)
- CPU usage (maybe overall)
- Energy consumption: need to measure power over time. Could integrate with hardware like power meter. Alternatively, use power estimation via CPU frequency scaling, etc. For edge, a common method is to read from a power sensor (e.g., INA219) via I2C. But we can provide a pluggable energy meter.
-
Model switching: The profiler should be able to handle multiple models. Could be configured with a dictionary of models, and allow selecting which one to run. Or the profiler could be applied to any model.
-
Reporting cadence: We can schedule periodic reporting (e.g., every N inferences or every T seconds). Could output to console, log file, or send to remote server. Provide hooks for custom reporters.
-
Implementation: Use Python's time, psutil for memory/CPU, and for energy maybe use a library that interfaces with hardware or use a simple linear model based on CPU utilization? But the requirement says on-device ML inference profiler for edge appliances, so it should be realistic. We can design it to accept an energy meter object that provides power readings. In the absence of hardware, we can simulate.
Since it's a code solution, we'll produce a Python module with classes:
EnergyMeter abstract base class, with a read_power() method. Implementations: INA219EnergyMeter (if available), MockEnergyMeter (simulated).
Profiler class: configurable with energy meter, reporting interval, output file, etc. It can record per-inference metrics in a list or DataFrame.
ProfileInference context manager that measures latency, memory, energy (integrate power over time). For energy, we need to sample power during inference; since inference takes milliseconds, we may need high-frequency sampling. We could sample before and after and assume constant? But better to sample at high frequency or integrate by reading before and after and using the time difference and average power? Actually to compute energy in Joules, we need power integrated over time. If we only have a simple energy meter that provides instantaneous power, we can sample before and after and assume constant, but that's inaccurate if power varies. However for short inference, maybe it's okay. Alternatively, we could start a background thread sampling power at high frequency (like 100 Hz) and sync timestamps. Simpler: assume linear interpolation.
To keep it simple: The profiler will measure:
start_time = time.perf_counter()
mem_before = psutil.Process().memory_info().rss
power_before = energy_meter.read_power() if available, else 0
- Run inference
end_time = time.perf_counter()
mem_after = ...
power_after = ...
- Compute latency, memory delta, energy = average(power_before, power_after) * latency (if power varies linearly). Or we could integrate using a sampling loop if we want more accuracy. But typical inference is fast (<1s). Might be okay.
But if we want more precision, we could sample power continuously during inference in a separate thread, but that's complex. We'll go with simple approach.
-
ModelSwitcher: a class that manages multiple models and can switch between them. It could be integrated with Profiler: you can specify which model to profile.
-
Reporting: a Reporter base class with methods to output metrics. Implementations: ConsoleReporter, FileReporter, DataFrameReporter. The profiler, after each inference or at intervals, calls reporter to output aggregated stats or raw data.
-
Cadence: Instead of reporting after each inference (which could be heavy), we can accumulate metrics and report every N inferences or every T seconds. We'll have a report_interval (e.g., every 10 inferences). After each inference, we add to buffer; if buffer reaches threshold, we report and clear.
-
Also we might want to aggregate stats: mean latency, std, min, max, mean energy, etc.
Let's design:
Classes:
-
EnergyMeter (ABC)
read_power(): returns power in Watts (float)
-
MockEnergyMeter(EnergyMeter): returns simulated power, maybe random around a baseline with some variation.
-
Profiler:
__init__(self, model, energy_meter=None, reporter=None, report_interval=10)
profile(self, input_data): runs inference on model with input_data, measures metrics, records them, and possibly reports.
- Could also be used as context manager:
with profiler:? Not needed.
-
ModelSwitcher:
__init__(self, models: dict) where models is mapping from name to model object.
switch(name): set current model.
- Optionally profile a specific model:
profile(name, input_data) which switches, profiles, and maybe switches back? Not needed.
But maybe the profiler should accept any model and we can manually switch models externally.
Better: The Profiler can be agnostic of model switching; it just profiles whatever model you call. The model switching is managed by the user. But the requirement says "model switching" as part of profiler. So maybe the profiler includes ability to compare multiple models automatically: you can configure a list of models to benchmark, and the profiler will run each sequentially and compare.
But the phrase "Build an on-device ML inference profiler for edge appliances: instrumentation, energy measurement, model switching, and reporting cadence." suggests we need a system that can:
- Instrument inference: measure performance.
- Measure energy.
- Switch between models (maybe to compare).
- Control reporting cadence.
Thus we can design a Benchmark class that takes a list of models and runs them on given inputs, collecting metrics for each, and reports.
But the user might want a profiler that can be used during normal operation, not just benchmarking. The profiler could periodically sample the running model and report. And it should allow switching models on the fly (like A/B testing). We'll interpret as: The profiler is a component that can be attached to an edge appliance that runs ML inference. It can:
- Instrument each inference: collect metrics.
- Measure energy consumption during inference.
- Support dynamic model switching: the appliance can load different models (e.g., different versions) and the profiler should track which model was used.
- Report metrics at a configurable cadence (e.g., every 5 minutes).
Thus we'll create a class MLInferenceProfiler that can be used to wrap the inference function. It can be initialized with configuration: energy meter, reporting interval, output path. Then the user does:
profiler = MLInferenceProfiler(energy_meter=..., report_interval=100, output='stats.json')
while True:
data = get_sensor_data()
result = profiler.inference(data) # maybe selects model based on some policy
But model switching could be done via profiler: profiler.set_model(model) or profiler.switch_model(model_name). The profiler keeps track of current model name.
Let's design:
MLInferenceProfiler:
- Attributes:
current_model (callable) and current_model_name.
energy_meter (EnergyMeter)
metrics_buffer list of dicts.
report_interval (int) number of inferences after which to report.
reporter (callable) that takes aggregated metrics and model name.
inference_count total.
start_time overall? Not needed.
- Methods:
set_model(model, model_name): set current model.
inference(input_data): runs the model on input_data, measures metrics, appends to buffer, checks if report needed, calls reporter.
_collect_metrics(input_data): internal to get latency, memory, energy.
- Possibly
get_latest_metrics().
- The
reporter could be a function that receives the buffer and generates output. We'll provide a default that prints summary to console and writes to CSV.
But we need to be careful: if report_interval is 10, then after 10 inferences, we report aggregated stats (like avg latency, total energy, etc.) per model. But we also need to separate by model? The buffer should include model_name for each inference. Then when reporting, we can group by model.
Alternatively, we can have separate buffers per model? Not needed; we can collect all and then group.
Reporting cadence: after every report_interval inferences, we clear buffer and report aggregated stats. Or we could report cumulative statistics over a time window. The requirement is a bit ambiguous: "reporting cadence" likely refers to the frequency at which the profiler emits reports. So we set report_interval in number of inferences or time.
Implementation details:
-
Memory: use psutil.Process().memory_info().rss to get resident set size in bytes. But for edge, we need to be careful about overhead of calling psutil each inference? It's okay.
-
Energy: We'll define an energy meter that samples power. For accurate energy, we want to integrate power over time. Since we have start and end times, and we have power readings at start and end, we could approximate energy = (power_before + power_after)/2 * latency. That's the trapezoidal integration assuming linear change. For short durations, it's fine. Or we could sample more frequently. To keep simple, we'll do that.
But what if the energy meter can only provide average power over a period? We'll assume instantaneous.
If no energy meter provided, energy is None or 0.
Also, we may want to measure system-level power, not just CPU. But we'll just use meter.
-
Model switching: The profiler can have multiple models loaded and we can switch via set_model. But we also might want to automatically rotate models for A/B testing. That's an advanced feature, but we can provide a load_models method that takes a dict and then switch_to(name).
-
Reporting: We'll create a ConsoleReporter and CsvReporter. The reporter function will be called with the metrics buffer (list of dicts) when reporting is due. Then we compute aggregates per model and output.
We'll produce a single Python file that defines these classes and also includes a demo usage with dummy models and mock energy meter.
Now code structure:
import time
import psutil
import os
import json
import csv
from abc import ABC, abstractmethod
from typing import Callable, Dict, List, Optional, Any
import statistics
class EnergyMeter(ABC):
@abstractmethod
def read_power(self) -> float:
"""Return instantaneous power in Watts."""
pass
class MockEnergyMeter(EnergyMeter):
def __init__(self, baseline=1.0, noise=0.1):
self.baseline = baseline
self.noise = noise
def read_power(self) -> float:
# Simulate power with some random noise
import random
return self.baseline + random.uniform(-self.noise, self.noise)
class INA219EnergyMeter(EnergyMeter):
# Example implementation using smbus2, but may not be available, so we'll try/except.
def __init__(self, bus=1, address=0x40):
try:
from smbus2 import SMBus
from ina219 import INA219
self.bus = SMBus(bus)
self.ina = INA219(self.bus, address)
self.ina.configure()
except ImportError:
raise RuntimeError("smbus2 or ina219 library not found. Install for real hardware.")
def read_power(self) -> float:
return self.ina.power() # returns in Watts? Actually ina219 returns power in milliWatts? Check: ina219.power() returns power in watts? Typically returns in watts? I think ina219 library returns power in watts. But we can scale if needed. We'll assume watts.
# Alternatively, we can provide a simple wrapper that reads from /sys/class/power etc if on specific platform. But we'll skip.
class MLInferenceProfiler:
def __init__(self,
energy_meter: Optional[EnergyMeter] = None,
report_interval: int = 10,
reporters: Optional[List[Callable[[List[Dict], str], None]]] = None,
model_name: str = "default"):
"""
Initialize profiler.
:param energy_meter: EnergyMeter instance for power measurement.
:param report_interval: Number of inferences after which to trigger reporting.
:param reporters: List of callables that accept (metrics_buffer, model_name) and produce output.
:param model_name: Name of the current model.
"""
self.energy_meter = energy_meter
self.report_interval = report_interval
self.reporters = reporters or [self._default_reporter]
self.current_model_name = model_name
self.current_model = None # Not set; user should set_model later or directly assign.
self.metrics_buffer = []
self.inference_count = 0
def set_model(self, model: Callable[[Any], Any], model_name: str):
"""Set the model to be used for inference."""
self.current_model = model
self.current_model_name = model_name
def inference(self, input_data: Any) -> Any:
"""
Run inference on current model with given input, collect metrics.
Returns model output.
"""
if self.current_model is None:
raise ValueError("No model set. Use set_model() before calling inference.")
# Pre-inference stats
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss # in bytes
cpu_before = process.cpu_percent(interval=None) # non-blocking; but note: cpu_percent returns since last call. Might need to sleep? Better to use interval=0.0? Actually for instantaneous, use interval=0.0 gives last measured value; not accurate. We could use `cpu_percent(interval=0.1)` but that blocks. Alternatively, we can use `psutil.cpu_percent(interval=None)` after a prior call? Usually first call returns 0.0. To get per-process CPU usage, we might need to sample twice. Simpler: we skip per-inference CPU, or we use thread time? For now we might skip CPU metric because it's tricky. We could measure system CPU usage using `psutil.cpu_percent(interval=0.1)` but that would add overhead. Maybe we can measure total CPU time before and after: `process.cpu_times()` sum of user+system. That gives CPU time consumed by process, which is accurate without sampling. Use `process.cpu_times()` returns named tuple with user and system times. The delta gives CPU time used during inference. That's good and non-blocking. We'll do that.
cpu_times_before = process.cpu_times()
power_before = self.energy_meter.read_power() if self.energy_meter else None
start_time = time.perf_counter()
# Run inference
output = self.current_model(input_data)
end_time = time.perf_counter()
# Post-inference stats
mem_after = process.memory_info().rss
cpu_times_after = process.cpu_times()
power_after = self.energy_meter.read_power() if self.energy_meter else None
# Compute metrics
latency = end_time - start_time # seconds
mem_delta = mem_after - mem_before # bytes; could be negative if GC? But we can take absolute or record both.
# CPU time: sum user+system times (in seconds)
cpu_before_total = cpu_times_before.user + cpu_times_before.system
cpu_after_total = cpu_times_after.user + cpu_times_after.system
cpu_time = cpu_after_total - cpu_before_total # seconds of CPU time used
# Energy: if power readings available, compute using trapezoidal rule.
if power_before is not None and power_after is not None:
avg_power = (power_before + power_after) / 2.0 # Watts
energy = avg_power * latency # Joules
else:
energy = None
# Package metrics
metrics = {
"model_name": self.current_model_name,
"timestamp": time.time(), # epoch seconds
"latency_s": latency,
"mem_delta_bytes": mem_delta,
"mem_after_bytes": mem_after,
"cpu_time_s": cpu_time,
"energy_J": energy,
# Could add more: power_before, power_after, etc.
}
self.metrics_buffer.append(metrics)
self.inference_count += 1
# Check if we need to report
if self.inference_count % self.report_interval == 0:
self._report()
return output
def _report(self):
"""Aggregate metrics from buffer and call each reporter."""
if not self.metrics_buffer:
return
# We might want to compute aggregates per model and overall.
# Since buffer may contain multiple models, group by model_name.
aggregated = {}
for m in self.metrics_buffer:
model = m["model_name"]
aggregated.setdefault(model, []).append(m)
# Compute summary per model: count, avg_latency, min, max, total_energy (if available), avg_mem_after, etc.
summary = {}
for model, records in aggregated.items():
latencies = [r["latency_s"] for r in records]
mems = [r["mem_after_bytes"] for r in records]
cpu_times = [r["cpu_time_s"] for r in records]
energies = [r["energy_J"] for r in records if r["energy_J"] is not None]
summary[model] = {
"count": len(records),
"latency": {
"mean": statistics.mean(latencies),
"stdev": statistics.stdev(latencies) if len(latencies) > 1 else 0.0,
"min": min(latencies),
"max": max(latencies),
},
"memory_bytes_after": {
"mean": statistics.mean(mems),
"min": min(mems),
"max": max(mems),
},
"cpu_time_s": {
"mean": statistics.mean(cpu_times),
}
}
if energies:
summary[model]["energy_J"] = {
"mean": statistics.mean(energies),
"total": sum(energies)
}
# Also overall? Not needed.
# Call reporters with the raw buffer and the summary
for reporter in self.reporters:
reporter(self.metrics_buffer, summary)
# Clear buffer after reporting
self.metrics_buffer = []
def _default_reporter(self, buffer: List[Dict], summary: Dict):
"""Print summary to console."""
print(f"\n--- Profiling Report after {len(buffer)} inferences ---")
for model, stats in summary.items():
print(f"Model: {model}")
print(f" Count: {stats['count']}")
print(f" Latency (s): mean={stats['latency']['mean']:.6f}, stdev={stats['latency']['stdev']:.6f}, min={stats['latency']['min']:.6f}, max={stats['latency']['max']:.6f}")
print(f" Memory after (MB): mean={stats['memory_bytes_after']['mean']/1e6:.2f}, min={stats['memory_bytes_after']['min']/1e6:.2f}, max={stats['memory_bytes_after']['max']/1e6:.2f}")
print(f" CPU time (s): mean={stats['cpu_time_s']['mean']:.6f}")
if "energy_J" in stats:
print(f" Energy (J): mean={stats['energy_J']['mean']:.6f}, total={stats['energy_J']['total']:.6f}")
print("--- End of Report ---\n")
def flush(self):
"""Force reporting even if buffer not full."""
self._report()
That's a good start. We also need to ensure thread safety if used in multi-thread? Not needed.
Now model switching: The user can call set_model at any time. The profiler will record the current model name in each metric.
Reporting cadence: controlled by report_interval. Could also be time-based, but simpler is inference count.
Now we need to make it "on-device": So we need to consider that psutil and time are fine. EnergyMeter: We provide INA219 implementation but it may require hardware. We'll include a fallback mock.
Also perhaps we want to support reading energy from a file (e.g., a driver that exports power in microwatts). We can add a FileEnergyMeter that reads from a sysfs path.
Add:
class FileEnergyMeter(EnergyMeter):
def __init__(self, path: str, scale=1.0):
"""
:param path: Path to file containing power in Watts (or microwatts, etc.)
:param scale: Multiply the read value by this to get Watts. e.g., if file gives microwatts, scale=1e-6.
"""
self.path = path
self.scale = scale
def read_power(self) -> float:
with open(self.path, 'r') as f:
value = float(f.read().strip())
return value * self.scale
Now, usage demo:
def dummy_model1(x):
time.sleep(0.1) # simulate computation
return x * 2
def dummy_model2(x):
time.sleep(0.05)
return x + 1
# Main
if __name__ == "__main__":
# Choose energy meter: mock or real
energy_meter = MockEnergyMeter(baseline=2.0, noise=0.5) # baseline 2W, noise 0.5W
# Define reporter to also save to CSV
csv_file = open("profiler_output.csv", "w", newline='')
csv_writer = csv.DictWriter(csv_file, fieldnames=[
"model_name", "timestamp", "latency_s", "mem_delta_bytes",
"mem_after_bytes", "cpu_time_s", "energy_J"
])
csv_writer.writeheader()
def csv_reporter(buffer, summary):
for row in buffer:
# Write row to CSV; convert None to empty
csv_row = {k: (v if v is not None else "") for k, v in row.items()}
csv_writer.writerow(csv_row)
# Also print summary? Let default also print
# We'll also call default reporter to print
profiler._default_reporter(buffer, summary)
# Or we can have multiple reporters: we can combine them.
profiler = MLInferenceProfiler(
energy_meter=energy_meter,
report_interval=5,
reporters=[profiler._default_reporter, csv_reporter] # but need to reference profiler after creation? We'll define reporter after.
)
# Set models
profiler.set_model(dummy_model1, "model1")
# Run some inferences
for i in range(10):
data = i
result = profiler.inference(data)
# Alternate model after 5 inferences
if i == 5:
profiler.set_model(dummy_model2, "model2")
time.sleep(0.1) # simulate interval between inferences
profiler.flush()
csv_file.close()
We need to handle the reporter function: we can't pass profiler._default_reporter before profiler exists? In code above, we pass [profiler._default_reporter, csv_reporter] after creation, but we need to pass reporters at init. So we could define reporters first and then pass them. Or we can set reporters after init. We'll add a add_reporter method. Or in init we default to list with default reporter; then we can append.
Simplify: In init, if reporters is None, set to [self._default_reporter]. Then we can add more later via add_reporter.
Better: In example, we'll create profiler without reporters, then add.
Also note: The _default_reporter is an instance method, so it's bound. That works.
Potential improvement: Use psutil.Process().memory_info().rss but note that RSS includes all memory, not just added by inference. The delta may be noisy. But it's okay.
We also might want to measure GPU memory if using GPU. Not required.
Edge devices may have limited resources; we should be careful about overhead. The profiler adds some overhead: measuring CPU times, memory, power reading. That's acceptable.
Now let's produce the final code with proper comments, docstrings, and a demo.
We need to output a single code block? The instruction: "Build an on-device ML inference profiler ..." We should output the code. Probably the user expects a code solution, so we provide a Python script with classes and a demo.
We'll include:
- Imports
- ABC for EnergyMeter
- Implementations: MockEnergyMeter, INA219EnergyMeter, FileEnergyMeter
- MLInferenceProfiler class
- Example usage in main guard
We'll also include a ModelSwitcher class? Actually the profiler already supports switching via set_model. But we might also want a separate utility to manage multiple models and schedule switching. But that's optional. The prompt says "model switching". So we should demonstrate switching. In the example we do that.
Maybe also we can create a AIModel abstract class? Not needed.
We'll also include a note that for real energy measurement on edge, you might need to connect a power sensor and implement EnergyMeter accordingly.
Potential improvements: We could also measure temperature? Not needed.
Let's create the code.
But wait: The requirement might be for a "profiler" that not only collects metrics but also helps to decide which model to use based on energy/performance. That could be advanced, but not required.
We'll produce a comprehensive solution.
Now we need to ensure we import statistics and handle case where stdev may error on single sample.
We'll adjust: statistics.stdev needs at least two data points; if only one, set to 0.
Also we need to consider that energy may be None; we skip.
Now, the _default_reporter prints summary, but in the example we want both printing and CSV. So we'll make _default_reporter as-is, and create a CSV reporter that writes raw rows, and also perhaps prints a summary if we want.
But to avoid duplicate printing, we can have the CSV reporter only write to file, and rely on default reporter for printing. That's fine.
In the code, we'll define csv_reporter as a closure or function.
Now about reporting cadence: we used report_interval as number of inferences. That's simple.
But we could also support time-based: e.g., report every X seconds. That would require a background thread or checking time in each inference. Could add a report_time_interval parameter as alternative. But we'll keep it simple.
Now we need to ensure the code runs even without psutil? But psutil is common for system monitoring. For edge devices, installing psutil is fine. We'll import it.
If psutil missing, we can fallback? But we'll assume it's installed.
Now final code structure:
#!/usr/bin/env python3
"""
On-device ML inference profiler for edge appliances.
This module provides tools to instrument ML inference code to measure
latency, memory usage, CPU time, and energy consumption. It supports
dynamic model switching and configurable reporting cadence.
Designed for resource-constrained environments (e.g., Raspberry Pi).
"""
import time
import os
import json
import csv
import statistics
from abc import ABC, abstractmethod
from typing import Callable, Dict, List, Optional, Any
import psutil
# -------------------------
# Energy Measurement Layer
# -------------------------
class EnergyMeter(ABC):
"""Abstract base class for power meters."""
@abstractmethod
def read_power(self) -> float:
"""Return instantaneous power consumption in Watts."""
pass
class MockEnergyMeter(EnergyMeter):
"""Simulated energy meter for testing."""
def __init__(self, baseline: float = 1.0, noise: float = 0.1, seed: Optional[int] = None):
"""
:param baseline: Average power consumption in Watts.
:param noise: Maximum random deviation in Watts.
:param seed: Optional random seed for reproducibility.
"""
self.baseline = baseline
self.noise = noise
if seed is not None:
import random
random.seed(seed)
def read_power(self) -> float:
import random
return self.baseline + random.uniform(-self.noise, self.noise)
class INA219EnergyMeter(EnergyMeter):
"""Real energy meter using INA219 current sensor via I2C."""
def __init__(self, bus: int = 1, address: int = 0x40):
"""
Initialize INA219 sensor.
Requires `smbus2` and `ina219` packages.
"""
try:
from smbus2 import SMBus
from ina219 import INA219
except ImportError as e:
raise RuntimeError(
"INA219EnergyMeter requires smbus2 and ina219 libraries. "
"Install via: pip install smbus2 ina219"
) from e
self.bus = SMBus(bus)
self.ina = INA219(self.bus, address)
self.ina.configure()
def read_power(self) -> float:
# INA219.power() returns power in watts? The library returns watts.
# Confirm: ina219 library: power() returns power in watts.
return self.ina.power()
class FileEnergyMeter(EnergyMeter):
"""Read power from a sysfs or procfs file."""
def __init__(self, path: str, scale: float = 1.0):
"""
:param path: Path to file containing power value (in some unit).
:param scale: Multiplier to convert read value to Watts.
e.g., if file gives microwatts, use scale=1e-6.
"""
self.path = path
self.scale = scale
def read_power(self) -> float:
try:
with open(self.path, "r") as f:
value = float(f.read().strip())
return value * self.scale
except Exception as e:
# Log error? For now return 0.
return 0.0
# -------------------------
# Profiler Core
# -------------------------
class MLInferenceProfiler:
"""
Instrument ML inference calls with timing, memory, CPU, and energy metrics.
Supports dynamic model switching and periodic reporting.
"""
def __init__(
self,
energy_meter: Optional[EnergyMeter] = None,
report_interval: int = 10,
reporters: Optional[List[Callable[[List[Dict], Dict], None]]] = None,
model_name: str = "default",
):
"""
:param energy_meter: EnergyMeter instance, or None to disable energy measurement.
:param report_interval: Number of inferences after which to trigger reporting.
:param reporters: List of reporter callables. Each takes (metrics_buffer, summary).
If None, uses default console reporter.
:param model_name: Initial model name (optional). Use set_model() to change.
"""
self.energy_meter = energy_meter
self.report_interval = report_interval
self.reporters = reporters if reporters is not None else [self._default_reporter]
self.current_model_name = model_name
self.current_model: Optional[Callable[[Any], Any]] = None
self.metrics_buffer: List[Dict] = []
self.inference_count = 0
def set_model(self, model: Callable[[Any], Any], model_name: str):
"""Set the model to be used for subsequent inferences."""
self.current_model = model
self.current_model_name = model_name
def inference(self, input_data: Any) -> Any:
"""
Run inference on the currently set model, collect performance metrics.
:param input_data: Input data for the model.
:return: Model output.
"""
if self.current_model is None:
raise ValueError("No model has been set. Call set_model() first.")
# Get current process for memory/CPU measurements
process = psutil.Process(os.getpid())
# Record pre-inference state
mem_before = process.memory_info().rss # bytes
cpu_times_before = process.cpu_times() # user, system times
power_before = self.energy_meter.read_power() if self.energy_meter else None
start_time = time.perf_counter()
# Execute model inference
output = self.current_model(input_data)
end_time = time.perf_counter()
# Record post-inference state
mem_after = process.memory_info().rss
cpu_times_after = process.cpu_times()
power_after = self.energy_meter.read_power() if self.energy_meter else None
# Compute metrics
latency = end_time - start_time
mem_delta = mem_after - mem_before
# CPU time delta (in seconds)
cpu_before_total = cpu_times_before.user + cpu_times_before.system
cpu_after_total = cpu_times_after.user + cpu_times_after.system
cpu_time = cpu_after_total - cpu_before_total
# Energy (Joules) using trapezoidal integration if power available
if power_before is not None and power_after is not None:
avg_power = (power_before + power_after) / 2.0
energy = avg_power * latency
else:
energy = None
# Build metrics record
metrics = {
"model_name": self.current_model_name,
"timestamp": time.time(),
"latency_s": latency,
"mem_delta_bytes": mem_delta,
"mem_after_bytes": mem_after,
"cpu_time_s": cpu_time,
"energy_J": energy,
}
self.metrics_buffer.append(metrics)
self.inference_count += 1
# Check if it's time to report
if self.inference_count % self.report_interval == 0:
self._report()
return output
def _report(self):
"""Aggregate buffered metrics and invoke reporters."""
if not self.metrics_buffer:
return
# Group metrics by model
grouped: Dict[str, List[Dict]] = {}
for m in self.metrics_buffer:
grouped.setdefault(m["model_name"], []).append(m)
# Compute summary per model
summary: Dict[str, Dict] = {}
for model, records in grouped.items():
latencies = [r["latency_s"] for r in records]
mem_afters = [r["mem_after_bytes"] for r in records]
cpu_times = [r["cpu_time_s"] for r in records]
energies = [r["energy_J"] for r in records if r["energy_J"] is not None]
model_summary = {
"count": len(records),
"latency": {
"mean": statistics.mean(latencies),
"stdev": statistics.stdev(latencies) if len(latencies) > 1 else 0.0,
"min": min(latencies),
"max": max(latencies),
},
"memory_bytes_after": {
"mean": statistics.mean(mem_afters),
"min": min(mem_afters),
"max": max(mem_afters),
},
"cpu_time_s": {
"mean": statistics.mean(cpu_times),
},
}
if energies:
model_summary["energy_J"] = {
"mean": statistics.mean(energies),
"total": sum(energies),
}
summary[model] = model_summary
# Call each reporter with the raw buffer and the summary
for reporter in self.reporters:
reporter(self.metrics_buffer, summary)
# Clear buffer after reporting
self.metrics_buffer = []
def _default_reporter(self, buffer: List[Dict], summary: Dict):
"""Print a human-readable summary to stdout."""
print(f"\n=== Profiling Report (last {len(buffer)} inferences) ===")
for model, stats in summary.items():
print(f"Model: {model}")
print(f" Inferences: {stats['count']}")
lat = stats["latency"]
print(f" Latency (s): mean={lat['mean']:.6f}, stdev={lat['stdev']:.6f}, min={lat['min']:.6f}, max={lat['max']:.6f}")
mem = stats["memory_bytes_after"]
print(f" Memory after (MB): mean={mem['mean']/1e6:.2f}, min={mem['min']/1e6:.2f}, max={mem['max']/1e6:.2f}")
cpu = stats["cpu_time_s"]
print(f" CPU time (s): mean={cpu['mean']:.6f}")
if "energy_J" in stats:
en = stats["energy_J"]
print(f" Energy (J): mean={en['mean']:.6f}, total={en['total']:.6f}")
print("=== End of Report ===\n")
def add_reporter(self, reporter: Callable[[List[Dict], Dict], None]):
"""Add a custom reporter to the profiler."""
self.reporters.append(reporter)
def flush(self):
"""Force report even if buffer not full."""
self._report()
# -------------------------
# Example Usage
# -------------------------
if __name__ == "__main__":
# Example dummy models
def model_slow(x):
time.sleep(0.15) # simulate heavy computation
return {"result": x * 2}
def model_fast(x):
time.sleep(0.05)
return {"result": x + 1}
# Energy meter: Use mock for simulation. Replace with INA219EnergyMeter or FileEnergyMeter on real hardware.
energy_meter = MockEnergyMeter(baseline=2.5, noise=0.3, seed=42)
# CSV reporter setup
csv_file = open("profiler_metrics.csv", "w", newline="")
csv_writer = csv.DictWriter(
csv_file,
fieldnames=[
"model_name",
"timestamp",
"latency_s",
"mem_delta_bytes",
"mem_after_bytes",
"cpu_time_s",
"energy_J",
],
)
csv_writer.writeheader()
def csv_reporter(buffer: List[Dict], summary: Dict):
"""Write raw metrics to CSV."""
for row in buffer:
# Convert None values to empty string for CSV compatibility
csv_row = {k: (v if v is not None else "") for k, v in row.items()}
csv_writer.writerow(csv_row)
csv_file.flush() # ensure data is written periodically
# Create profiler with both CSV and console reporters
profiler = MLInferenceProfiler(
energy_meter=energy_meter,
report_interval=5,
reporters=[], # start empty; add after creation to avoid bound method issues with _default_reporter? Actually we can add later.
)
# Add default console reporter
profiler.add_reporter(profiler._default_reporter)
# Add CSV reporter
profiler.add_reporter(csv_reporter)
# Set initial model
profiler.set_model(model_slow, "slow_model")
# Simulate a sequence of inferences with model switching
for i in range(12):
# Alternate model after 5 inferences
if i == 5:
print("\n*** Switching to fast_model ***\n")
profiler.set_model(model_fast, "fast_model")
elif i == 8:
print("\n*** Switching back to slow_model ***\n")
profiler.set_model(model_slow, "slow_model")
# Get input (just an integer)
inp = i
result = profiler.inference(inp)
# Simulate some time between inferences
time.sleep(0.2)
# If any remaining in buffer, flush
profiler.flush()
csv_file.close()
print("Profiling completed. Metrics saved to profiler_metrics.csv")
That should be a complete solution.
Now we should consider any edge cases: The CPU time measurement using process.cpu_times() might wrap? Should be fine. However, note that on multi-core systems, CPU time can exceed wall time. That's okay.
Memory measurement: rss includes memory that may be shared; but it's a good approximation.
Energy measurement: We use trapezoidal rule; but if power_before and power_after are very different, maybe we need more samples. But it's okay.
Model switching: We simply change the model. The profiler will record model_name accordingly.
Reporting: We have a buffer; after report_interval inferences, we call reporters. The reporters receive the raw buffer and the summary. We also have a flush method.
We also allow adding reporters dynamically.
Potential improvements: We could add a time_based_report but not needed.
Now we need to ensure code is Python 3.6+.
We used f-strings, so Python 3.6+.
Now think about psutil memory: On some platforms, memory_info().rss may be in bytes, but that's consistent.
Also, note that psutil.Process().cpu_percent(interval=...) is not needed because we use cpu_times delta.
One minor: cpu_times() returns times as floats representing seconds since process start. So delta gives CPU time used during that interval. That's fine.
But caution: cpu_times() might include child processes? The default is process.cpu_times() gives user and system for the process itself, not including children. That's fine.
We might also want to measure system-wide power? But energy meter measures whole-system power, not just process. The inference process's energy consumption is not isolated; but it's okay because we approximate that the inference is the dominant consumer during that short period. That's typical for device-level profiling.
If we want per-process energy, we'd need a power model per component. Not required.
Now, test the code? We can run it in our head.
Potential error: In _default_reporter, we compute lat['mean'] etc. Ensure lat is defined. It's from stats['latency']. That's fine.
Also statistics.mean on empty list? But we only call after grouping, and each group has at least one record. So safe.
Also we use mem['mean'] etc. Good.
Now ensure we imported statistics. Yes.
Now we need to write a docstring at top.
Now we need to produce final answer: Provide the Python code as above. But we might need to include explanation? The user only said "Build an on-device ML inference profiler ...". Usually they expect code. We'll provide the code block with maybe a brief description. But as ChatGPT, we can output just the code or include explanation. Since it's a "code expert" role, we can output the code with some comments. We'll provide a markdown code block.
We'll also mention that for real deployment, replace MockEnergyMeter with appropriate hardware.
Potential improvements: Add support for GPU metrics via pynvml for Jetson, but not required.
One more: The FileEnergyMeter could read from something like /sys/class/power_supply/.../power_now on some devices. That's plausible.
Now, ensure that the code is self-contained: It uses psutil, statistics, time, os, csv, json. json not used but we import; we can remove. But it's okay. We'll import only needed. We'll remove json as not used. Keep it minimal.
Also we used random only in mock; okay.
Now, check for any syntax errors: In MLInferenceProfiler.__init__, we have reporters: Optional[List[Callable[[List[Dict], Dict], None]]] - this syntax might be a bit complex but valid. Could simplify to Callable type: Callable[[List[Dict], Dict], None]. It's okay.
We have _default_reporter which uses self but we pass it as profiler._default_reporter after creation. That's a bound method, okay.
But careful: In the example, we passed reporters=[] to avoid calling the default reporter initially, then we added. That's fine. Alternatively, we could pass reporters=[profiler._default_reporter] but that would be before profiler defined? Actually we define profiler = MLInferenceProfiler(...) and then we can't reference profiler._default_reporter inside the argument because profiler not assigned yet. So we need to add after.
Thus the pattern is fine.
But we could also allow passing a string 'default' to init. But not needed.
Now, what about thread safety? Not needed.
Potential issue: The _report method groups by model and then for each model computes stats. In the summary, we include "count" and other stats. The reporters may rely on buffer being cleared after. That's okay.
Now finalize code.
We'll also include a note that this profiler can be extended.
Now produce final answer: The code in a code block, with explanation maybe.
Given the instruction: "Build an on-device ML inference profiler for edge appliances: instrumentation, energy measurement, model switching, and reporting cadence." It's a request to build it; we are ChatGPT generating the code. So we'll output the code.
I'll add a small description above.
Now produce final output.
Here is a comprehensive implementation of an on-device ML inference profiler designed for edge appliances. It provides:
- Instrumentation – latency, memory delta, CPU time.
- Energy measurement – pluggable energy meters (mock, INA219, file‑based).
- Model switching – change the active model on the fly; each inference records the model name.
- Reporting cadence – configurable number of inferences between reports; multiple output formats (console, CSV, custom).
The code is written in Python and uses psutil for system metrics. Replace the MockEnergyMeter with a real implementation (e.g., INA219EnergyMeter or FileEnergyMeter) when deploying on actual hardware.
#!/usr/bin/env python3
"""
On-device ML inference profiler for edge appliances.
This module provides tools to instrument ML inference code to measure
latency, memory usage, CPU time, and energy consumption. It supports
dynamic model switching and periodic reporting.
Designed for resource-constrained environments (e.g., Raspberry Pi).
"""
import time
import os
import csv
import statistics
from abc import ABC, abstractmethod
from typing import Callable, Dict, List, Optional, Any
import psutil
# -------------------------
# Energy Measurement Layer
# -------------------------
class EnergyMeter(ABC):
"""Abstract base class for power meters."""
@abstractmethod
def read_power(self) -> float:
"""Return instantaneous power consumption in Watts."""
pass
class MockEnergyMeter(EnergyMeter):
"""Simulated energy meter for testing."""
def __init__(self, baseline: float = 1.0, noise: float = 0.1, seed: Optional[int] = None):
"""
:param baseline: Average power consumption in Watts.
:param noise: Maximum random deviation in Watts.
:param seed: Optional random seed for reproducibility.
"""
self.baseline = baseline
self.noise = noise
if seed is not None:
import random
random.seed(seed)
def read_power(self) -> float:
import random
return self.baseline + random.uniform(-self.noise, self.noise)
class INA219EnergyMeter(EnergyMeter):
"""Real energy meter using INA219 current sensor via I2C."""
def __init__(self, bus: int = 1, address: int = 0x40):
"""
Initialize INA219 sensor.
Requires `smbus2` and `ina219` packages.
"""
try:
from smbus2 import SMBus
from ina219 import INA219
except ImportError as e:
raise RuntimeError(
"INA219EnergyMeter requires smbus2 and ina219 libraries. "
"Install via: pip install smbus2 ina219"
) from e
self.bus = SMBus(bus)
self.ina = INA219(self.bus, address)
self.ina.configure()
def read_power(self) -> float:
# INA219.power() returns power in watts.
return self.ina.power()
class FileEnergyMeter(EnergyMeter):
"""Read power from a sysfs or procfs file."""
def __init__(self, path: str, scale: float = 1.0):
"""
:param path: Path to file containing power value (in some unit).
:param scale: Multiplier to convert read value to Watts.
e.g., if file gives microwatts, use scale=1e-6.
"""
self.path = path
self.scale = scale
def read_power(self) -> float:
try:
with open(self.path, "r") as f:
value = float(f.read().strip())
return value * self.scale
except Exception:
# Return 0 if read fails; in production log the error.
return 0.0
# -------------------------
# Profiler Core
# -------------------------
class MLInferenceProfiler:
"""
Instrument ML inference calls with timing, memory, CPU, and energy metrics.
Supports dynamic model switching and periodic reporting.
"""
def __init__(
self,
energy_meter: Optional[EnergyMeter] = None,
report_interval: int = 10,
reporters: Optional[List[Callable[[List[Dict], Dict], None]]] = None,
model_name: str = "default",
):
"""
:param energy_meter: EnergyMeter instance, or None to disable energy measurement.
:param report_interval: Number of inferences after which to trigger reporting.
:param reporters: List of reporter callables. Each takes (metrics_buffer, summary).
If None, uses default console reporter.
:param model_name: Initial model name (optional). Use set_model() to change.
"""
self.energy_meter = energy_meter
self.report_interval = report_interval
self.reporters = reporters if reporters is not None else [self._default_reporter]
self.current_model_name = model_name
self.current_model: Optional[Callable[[Any], Any]] = None
self.metrics_buffer: List[Dict] = []
self.inference_count = 0
def set_model(self, model: Callable[[Any], Any], model_name: str):
"""Set the model to be used for subsequent inferences."""
self.current_model = model
self.current_model_name = model_name
def inference(self, input_data: Any) -> Any:
"""
Run inference on the currently set model, collect performance metrics.
:param input_data: Input data for the model.
:return: Model output.
"""
if self.current_model is None:
raise ValueError("No model has been set. Call set_model() first.")
# Get current process for memory/CPU measurements
process = psutil.Process(os.getpid())
# Record pre-inference state
mem_before = process.memory_info().rss # bytes
cpu_times_before = process.cpu_times() # user, system times
power_before = self.energy_meter.read_power() if self.energy_meter else None
start_time = time.perf_counter()
# Execute model inference
output = self.current_model(input_data)
end_time = time.perf_counter()
# Record post-inference state
mem_after = process.memory_info().rss
cpu_times_after = process.cpu_times()
power_after = self.energy_meter.read_power() if self.energy_meter else None
# Compute metrics
latency = end_time - start_time
mem_delta = mem_after - mem_before
# CPU time delta (in seconds)
cpu_before_total = cpu_times_before.user + cpu_times_before.system
cpu_after_total = cpu_times_after.user + cpu_times_after.system
cpu_time = cpu_after_total - cpu_before_total
# Energy (Joules) using trapezoidal integration if power available
if power_before is not None and power_after is not None:
avg_power = (power_before + power_after) / 2.0
energy = avg_power * latency
else:
energy = None
# Build metrics record
metrics = {
"model_name": self.current_model_name,
"timestamp": time.time(),
"latency_s": latency,
"mem_delta_bytes": mem_delta,
"mem_after_bytes": mem_after,
"cpu_time_s": cpu_time,
"energy_J": energy,
}
self.metrics_buffer.append(metrics)
self.inference_count += 1
# Check if it's time to report
if self.inference_count % self.report_interval == 0:
self._report()
return output
def _report(self):
"""Aggregate buffered metrics and invoke reporters."""
if not self.metrics_buffer:
return
# Group metrics by model
grouped: Dict[str, List[Dict]] = {}
for m in self.metrics_buffer:
grouped.setdefault(m["model_name"], []).append(m)
# Compute summary per model
summary: Dict[str, Dict] = {}
for model, records in grouped.items():
latencies = [r["latency_s"] for r in records]
mem_afters = [r["mem_after_bytes"] for r in records]
cpu_times = [r["cpu_time_s"] for r in records]
energies = [r["energy_J"] for r in records if r["energy_J"] is not None]
model_summary = {
"count": len(records),
"latency": {
"mean": statistics.mean(latencies),
"stdev": statistics.stdev(latencies) if len(latencies) > 1 else 0.0,
"min": min(latencies),
"max": max(latencies),
},
"memory_bytes_after": {
"mean": statistics.mean(mem_afters),
"min": min(mem_afters),
"max": max(mem_afters),
},
"cpu_time_s": {
"mean": statistics.mean(cpu_times),
},
}
if energies:
model_summary["energy_J"] = {
"mean": statistics.mean(energies),
"total": sum(energies),
}
summary[model] = model_summary
# Call each reporter with the raw buffer and the summary
for reporter in self.reporters:
reporter(self.metrics_buffer, summary)
# Clear buffer after reporting
self.metrics_buffer = []
def _default_reporter(self, buffer: List[Dict], summary: Dict):
"""Print a human-readable summary to stdout."""
print(f"\n=== Profiling Report (last {len(buffer)} inferences) ===")
for model, stats in summary.items():
print(f"Model: {model}")
print(f" Inferences: {stats['count']}")
lat = stats["latency"]
print(f" Latency (s): mean={lat['mean']:.6f}, stdev={lat['stdev']:.6f}, min={lat['min']:.6f}, max={lat['max']:.6f}")
mem = stats["memory_bytes_after"]
print(f" Memory after (MB): mean={mem['mean']/1e6:.2f}, min={mem['min']/1e6:.2f}, max={mem['max']/1e6:.2f}")
cpu = stats["cpu_time_s"]
print(f" CPU time (s): mean={cpu['mean']:.6f}")
if "energy_J" in stats:
en = stats["energy_J"]
print(f" Energy (J): mean={en['mean']:.6f}, total={en['total']:.6f}")
print("=== End of Report ===\n")
def add_reporter(self, reporter: Callable[[List[Dict], Dict], None]):
"""Add a custom reporter to the profiler."""
self.reporters.append(reporter)
def flush(self):
"""Force report even if buffer not full."""
self._report()
# -------------------------
# Example Usage
# -------------------------
if __name__ == "__main__":
# Example dummy models
def model_slow(x):
time.sleep(0.15) # simulate heavy computation
return {"result": x * 2}
def model_fast(x):
time.sleep(0.05)
return {"result": x + 1}
# Energy meter: Use mock for simulation. Replace with INA219EnergyMeter or FileEnergyMeter on real hardware.
energy_meter = MockEnergyMeter(baseline=2.5, noise=0.3, seed=42)
# CSV reporter setup
csv_file = open("profiler_metrics.csv", "w", newline="")
csv_writer = csv.DictWriter(
csv_file,
fieldnames=[
"model_name",
"timestamp",
"latency_s",
"mem_delta_bytes",
"mem_after_bytes",
"cpu_time_s",
"energy_J",
],
)
csv_writer.writeheader()
def csv_reporter(buffer: List[Dict], summary: Dict):
"""Write raw metrics to CSV."""
for row in buffer:
# Convert None values to empty string for CSV compatibility
csv_row = {k: (v if v is not None else "") for k, v in row.items()}
csv_writer.writerow(csv_row)
csv_file.flush() # ensure data is written periodically
# Create profiler with both CSV and console reporters
profiler = MLInferenceProfiler(
energy_meter=energy_meter,
report_interval=5,
reporters=[], # start empty; add after creation to avoid bound method issues with _default_reporter? Actually we can add later.
)
# Add default console reporter
profiler.add_reporter(profiler._default_reporter)
# Add CSV reporter
profiler.add_reporter(csv_reporter)
# Set initial model
profiler.set_model(model_slow, "slow_model")
# Simulate a sequence of inferences with model switching
for i in range(12):
# Alternate model after 5 inferences
if i == 5:
print("\n*** Switching to fast_model ***\n")
profiler.set_model(model_fast, "fast_model")
elif i == 8:
print("\n*** Switching back to slow_model ***\n")
profiler.set_model(model_slow, "slow_model")
# Get input (just an integer)
inp = i
result = profiler.inference(inp)
# Simulate some time between inferences
time.sleep(0.2)
# If any remaining in buffer, flush
profiler.flush()
csv_file.close()
print("Profiling completed. Metrics saved to profiler_metrics.csv")
This script can be run directly. It simulates two models and logs metrics to the console and a CSV file every 5 inferences. In a real edge deployment, connect a power sensor (INA219 or similar) and replace MockEnergyMeter with INA219EnergyMeter or FileEnergyMeter pointing to the appropriate sysfs power file. The profiler adds minimal overhead and can be integrated into any Python-based inference pipeline.