pdmlabs.energy#
PdMLabs energy and carbon measurement layer.
Backend Registry#
ENERGY_BACKEND_REGISTRY maps string identifiers to zero-argument loader
callables. Adding a new backend requires only inserting a new entry.
Unlike pdmlabs.optimization, which imports every adapter eagerly, the
loaders here are lazy: codecarbon and nvidia-ml-py are optional
extras, so import pdmlabs.energy must succeed without them. Importing them
at module scope would make the whole package unimportable on a machine that
only ever runs with tracking disabled.
Supported identifiers#
"noop"Wall-clock only, zero overhead. Default, so existing callers are unaffected.
"codecarbon"CPU + GPU + RAM, kWh and gCO2eq, grid carbon intensity. Requires
pip install pdmlabs[energy]."rapl"Raw
/sys/class/powercapdeltas plus NVML’s exact energy counter. Highest fidelity, Linux + Intel only. Requirespip install pdmlabs[energy].
Measurement is never assumed#
Every backend reports provenance on every reading, and
is_measured() is true only when CPU
energy came from intel_rapl. On a kernel that restricts RAPL (the default
since CVE-2020-8694) CodeCarbon falls back to a TDP x utilisation model
without raising, which would quietly reduce an energy study to a timing
study. Use preflight() to gate on that rather than trusting the numbers.
Functions
|
Instantiate and return the energy backend for name. |
|
Check what name can measure here; refuse to proceed on an estimate. |
- class pdmlabs.energy.BaseEnergyBackend#
Bases:
ABCUniform start/stop energy measurement.
Implementations must honour three rules, because this object runs inside an HPO trial and must never be able to break one:
stop_*returns anEnergyReading, never raises. A measurement failure degrades the study; it must not abort an optimisation run.Provenance is always populated, even on failure, so no record can be mistaken for a hardware measurement.
start_taskwhile a task is open is an error the backend resolves itself (close-and-warn), never a silent overwrite that would attribute one task’s energy to another.
- name: str = 'base'#
- phase(label)#
Measure a phase, yielding a one-element list that receives the reading.
The reading is delivered through a mutable cell rather than as the
asvalue because the value is only known at__exit__.
- abstractmethod probe() dict#
Report what this backend can actually measure, without measuring.
Returns a dict with at least
power_source_cpu,power_source_gpu,ram_sourceandavailable(bool). Called by the preflight gate.
- shutdown() None#
Release any long-lived resource. Idempotent.
- abstractmethod start_phase(label: str) None#
- abstractmethod start_task(label: str) object | None#
- abstractmethod stop_phase() EnergyReading#
- abstractmethod stop_task(token: object | None) EnergyReading#
- class pdmlabs.energy.EnergyReading(duration_s: float, cpu_j: float | None = None, gpu_j: float | None = None, ram_j: float | None = None, total_j: float | None = None, co2e_g: float | None = None, power_source_cpu: str = 'unknown', power_source_gpu: str = 'unknown', ram_source: str = 'unknown', backend: str = 'unknown', quality: str = 'ok', carbon_intensity_g_per_kwh: float | None = None)#
Bases:
objectOne energy measurement over a closed time interval.
Every field that can be absent is
Nonerather than0.0. The distinction matters: a missing DRAM rail and a rail that genuinely drew no energy must not be summed into the same total, or a machine without adramRAPL domain would silently report lower total energy than one with.- as_dict()#
- property avg_power_w#
- backend: str = 'unknown'#
- carbon_intensity_g_per_kwh: float | None = None#
- co2e_g: float | None = None#
- cpu_j: float | None = None#
- duration_s: float#
- dynamic_j(idle_w, clamp=True)#
Idle-subtracted energy, and whether the clamp fired.
Returns
(value, clamped). Short or noisy intervals can yield a negative result; clamping to zero is right, but doing so silently is not – the clamp rate is itself a data-quality signal, so it is returned rather than swallowed.
- classmethod from_kwh(duration_s, cpu_kwh=None, gpu_kwh=None, ram_kwh=None, total_kwh=None, co2e_kg=None, **provenance)#
Build from CodeCarbon’s kWh/kg convention.
- gpu_j: float | None = None#
- property is_measured#
True only when CPU energy came from hardware counters.
This is the single predicate that decides whether a run is a measurement or a model. Nothing may infer it from the shape of the numbers – a TDP*utilisation model also varies with load, which is exactly how such a fallback gets mistaken for a real reading.
- power_source_cpu: str = 'unknown'#
- power_source_gpu: str = 'unknown'#
- quality: str = 'ok'#
- ram_j: float | None = None#
- ram_source: str = 'unknown'#
- total_j: float | None = None#
- property total_kwh#
- pdmlabs.energy.get_energy_backend(name, **kwargs) BaseEnergyBackend#
Instantiate and return the energy backend for name.
- Parameters:
name – One of the keys in
ENERGY_BACKEND_REGISTRY.Noneis accepted and maps to"noop"so callers can pass an unset option straight through.**kwargs – Backend-specific configuration (e.g.
measure_power_secs,country_iso_code,gpu_ids).
- Raises:
ValueError – If name is not a registered backend identifier.
ImportError – If the backend’s optional dependency is missing. The message names the extra to install.
- pdmlabs.energy.preflight(name='codecarbon', allow_estimated=False, **kwargs)#
Check what name can measure here; refuse to proceed on an estimate.
This is the gate that keeps an energy study from silently becoming a timing study. When CPU energy is not from
intel_raplthe result is a model whose value is a near-deterministic function of wall-clock time, so cross-optimizer conclusions would reduce to “the faster backend won”.Returns the backend’s probe dict. Raises
RuntimeErrorwhen CPU energy would be estimated unless allow_estimated is explicitly true, in which case it warns loudly and stamps the provenance instead.
Modules
Abstract base class for all PdMLabs energy backends. |
|
CodeCarbon energy backend -- the default when tracking is enabled. |
|
Per-process trial context, used to join an energy record to its MLflow run. |
|
Distribution shift, for the effective-payback correction. |
|
Turn the JSONL spool into a tidy, portable, self-describing table. |
|
Per-trial energy instrumentation for the HPO objective. |
|
Machine fingerprint and idle-power baseline. |
|
Lifecycle energy metrics, adapted from E-LQO (SIGMOD 2027) to PdM. |
|
Zero-overhead backend used whenever energy tracking is disabled. |
|
Payoff models: turning detection quality into avoided energy or cost. |
|
Raw Intel RAPL + NVML energy backend -- highest fidelity, Linux + Intel only. |
|
The value type returned by every energy backend. |
|
Append-only cross-process energy spool. |
|
Lifecycle energy study driver. |