ai-energymeter 2.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Mauricio Fadel Argerich
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-energymeter
3
+ Version: 2.0.1
4
+ Summary: A library to measure energy consumption of applications
5
+ Author-email: Mauricio Fadel Argerich <maufadel@icloud.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/maufadel/EnergyMeter
8
+ Project-URL: Repository, https://github.com/maufadel/EnergyMeter
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pynvml
16
+ Requires-Dist: pyRAPL
17
+ Requires-Dist: numpy
18
+ Requires-Dist: pandas
19
+ Requires-Dist: matplotlib
20
+ Dynamic: license-file
21
+
22
+ # EnergyMeter
23
+ EnergyMeter is a Python module that combines pyRAPL, NVIDIA-SMI and eBPF to estimate the energy consumption of CPU, memory, GPU, and storage on Linux with only three lines of code. This was developed during the development of the article Fadel Argerich, M., & Patiño-Martínez, M. (2024). Measuring and Improving the Energy Efficiency of Large Language Models Inference. IEEE Access.
24
+
25
+ ### Update: version 2.0 is out!
26
+ The new version improves the accuracy of the energy consumption of the GPU while also reducing the overhead of the meter, so there is no visible overhead now.
27
+
28
+ ## How to install
29
+ You can install EnergyMeter by cloning this repository and using pip:
30
+ ```
31
+ git clone https://github.com/maufadel/EnergyMeter.git
32
+ cd EnergyMeter
33
+ pip install .
34
+ ```
35
+
36
+ ## How to use
37
+ The most basic usage of EnergyMeter is as follows:
38
+ ```
39
+ from energy_meter import EnergyMeter
40
+
41
+ em = EnergyMeter(disk_avg_speed=1600*1e6, # The average speed of your storage (see below how you can get it)
42
+ disk_active_power=6, # How many Watts are used when the storage is reading or writing (you can usually find it in specs of your storage)
43
+ disk_idle_power=1.42, # How many Watts are used when the storage is idle (you can usually find it in specs of your storage)
44
+ label="Test Meter", # A label to identify the measurement
45
+ include_idle=False) # If energy used during idle should be accounted for in the measurement. Defaults to False.
46
+
47
+ em.begin()
48
+ # --> CODE YOU WANT TO MEASURE <--
49
+ em.end()
50
+
51
+ # Plot energy consumption per component.
52
+ meter.plot_total_joules_per_component()
53
+ # or print(em.get_total_joules_per_component())
54
+ ```
55
+ ![Example Output](https://github.com/maufadel/meml/blob/main/example_output.png)
56
+
57
+ You can check the notebook [Measuring_energy_consumption.ipynb](https://github.com/maufadel/meml/blob/main/Measuring_energy_consumption.ipynb) for more details.
58
+
59
+ ## How to get storage details
60
+ You can benchmark your storage speed with the Flexible I/O tester (FIO) as recommended by Google in the following tutorial: https://cloud.google.com/compute/docs/disks/benchmarking-pd-performance
61
+
62
+ Storage specs usually include data regarding the power consumption during active (reading or writing) and for idle periods.
63
+
64
+ ## Troubleshooting
65
+ ### pyRAPL/RAPL
66
+ pyRAPL requires access to /sys/class/powercap/intel-rapl, for which sudo access is required. If the access is denied, run the following command on the terminal to enable access to the rapl measurement:
67
+
68
+ `sudo chmod -R a+r /sys/class/powercap/intel-rapl`
69
+
70
+ ### bpftrace
71
+ Also note that you need to have bpftrace installed. On ubuntu, you can install it with the following command:
72
+
73
+ `sudo apt-get install -y bpftrace`
74
+
75
+ For other operating systems, please check https://github.com/bpftrace/bpftrace/blob/master/INSTALL.md.
76
+
77
+ ## Limitations
78
+ EnergyMeter requires to be run on bare metal instances running Linux on Intel and NVIDIA hardware. These requirements are inherited from the tools used for tracking the energy consumption: RAPL (Intel), NVIDIA-SMI (NVIDIA), and eBPF (Linux). These tools are known to have a high accuracy thanks to their access to low level sensors, but it is important to keep in mind that the energy consumption metrics provided are still estimations and vary according to different factors including hardware configuration and software versions. Additionally, the energy consumed by cooling, screens and other components not mentioned here are not included in our measurements, so the total energy consumed will likely be different to the total sum of the consumption of CPU, memory, GPU, and storage.
79
+
80
+ ## Authorship and License
81
+ I am developing EnergyMeter as a part of my PhD program at Universidad Politécnica de Madrid. EnergyMeter is open sourced under an MIT License.
82
+
83
+ If you found this repository useful, please cite our work:
84
+ ```
85
+ @article{argerich2024measuring,
86
+ title={Measuring and Improving the Energy Efficiency of Large Language Models Inference},
87
+ author={Fadel Argerich, Mauricio and Pati{\~n}o-Mart{\'\i}nez, Marta},
88
+ journal={IEEE Access},
89
+ year={2024},
90
+ publisher={IEEE}
91
+ }
92
+ ```
@@ -0,0 +1,71 @@
1
+ # EnergyMeter
2
+ EnergyMeter is a Python module that combines pyRAPL, NVIDIA-SMI and eBPF to estimate the energy consumption of CPU, memory, GPU, and storage on Linux with only three lines of code. This was developed during the development of the article Fadel Argerich, M., & Patiño-Martínez, M. (2024). Measuring and Improving the Energy Efficiency of Large Language Models Inference. IEEE Access.
3
+
4
+ ### Update: version 2.0 is out!
5
+ The new version improves the accuracy of the energy consumption of the GPU while also reducing the overhead of the meter, so there is no visible overhead now.
6
+
7
+ ## How to install
8
+ You can install EnergyMeter by cloning this repository and using pip:
9
+ ```
10
+ git clone https://github.com/maufadel/EnergyMeter.git
11
+ cd EnergyMeter
12
+ pip install .
13
+ ```
14
+
15
+ ## How to use
16
+ The most basic usage of EnergyMeter is as follows:
17
+ ```
18
+ from energy_meter import EnergyMeter
19
+
20
+ em = EnergyMeter(disk_avg_speed=1600*1e6, # The average speed of your storage (see below how you can get it)
21
+ disk_active_power=6, # How many Watts are used when the storage is reading or writing (you can usually find it in specs of your storage)
22
+ disk_idle_power=1.42, # How many Watts are used when the storage is idle (you can usually find it in specs of your storage)
23
+ label="Test Meter", # A label to identify the measurement
24
+ include_idle=False) # If energy used during idle should be accounted for in the measurement. Defaults to False.
25
+
26
+ em.begin()
27
+ # --> CODE YOU WANT TO MEASURE <--
28
+ em.end()
29
+
30
+ # Plot energy consumption per component.
31
+ meter.plot_total_joules_per_component()
32
+ # or print(em.get_total_joules_per_component())
33
+ ```
34
+ ![Example Output](https://github.com/maufadel/meml/blob/main/example_output.png)
35
+
36
+ You can check the notebook [Measuring_energy_consumption.ipynb](https://github.com/maufadel/meml/blob/main/Measuring_energy_consumption.ipynb) for more details.
37
+
38
+ ## How to get storage details
39
+ You can benchmark your storage speed with the Flexible I/O tester (FIO) as recommended by Google in the following tutorial: https://cloud.google.com/compute/docs/disks/benchmarking-pd-performance
40
+
41
+ Storage specs usually include data regarding the power consumption during active (reading or writing) and for idle periods.
42
+
43
+ ## Troubleshooting
44
+ ### pyRAPL/RAPL
45
+ pyRAPL requires access to /sys/class/powercap/intel-rapl, for which sudo access is required. If the access is denied, run the following command on the terminal to enable access to the rapl measurement:
46
+
47
+ `sudo chmod -R a+r /sys/class/powercap/intel-rapl`
48
+
49
+ ### bpftrace
50
+ Also note that you need to have bpftrace installed. On ubuntu, you can install it with the following command:
51
+
52
+ `sudo apt-get install -y bpftrace`
53
+
54
+ For other operating systems, please check https://github.com/bpftrace/bpftrace/blob/master/INSTALL.md.
55
+
56
+ ## Limitations
57
+ EnergyMeter requires to be run on bare metal instances running Linux on Intel and NVIDIA hardware. These requirements are inherited from the tools used for tracking the energy consumption: RAPL (Intel), NVIDIA-SMI (NVIDIA), and eBPF (Linux). These tools are known to have a high accuracy thanks to their access to low level sensors, but it is important to keep in mind that the energy consumption metrics provided are still estimations and vary according to different factors including hardware configuration and software versions. Additionally, the energy consumed by cooling, screens and other components not mentioned here are not included in our measurements, so the total energy consumed will likely be different to the total sum of the consumption of CPU, memory, GPU, and storage.
58
+
59
+ ## Authorship and License
60
+ I am developing EnergyMeter as a part of my PhD program at Universidad Politécnica de Madrid. EnergyMeter is open sourced under an MIT License.
61
+
62
+ If you found this repository useful, please cite our work:
63
+ ```
64
+ @article{argerich2024measuring,
65
+ title={Measuring and Improving the Energy Efficiency of Large Language Models Inference},
66
+ author={Fadel Argerich, Mauricio and Pati{\~n}o-Mart{\'\i}nez, Marta},
67
+ journal={IEEE Access},
68
+ year={2024},
69
+ publisher={IEEE}
70
+ }
71
+ ```
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ai-energymeter"
7
+ version = "2.0.1"
8
+ description = "A library to measure energy consumption of applications"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+
13
+ authors = [
14
+ { name = "Mauricio Fadel Argerich", email = "maufadel@icloud.com" }
15
+ ]
16
+
17
+ dependencies = [
18
+ "pynvml",
19
+ "pyRAPL",
20
+ "numpy",
21
+ "pandas",
22
+ "matplotlib"
23
+ ]
24
+
25
+ classifiers = [
26
+ "Programming Language :: Python :: 3",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Operating System :: POSIX :: Linux",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/maufadel/EnergyMeter"
33
+ Repository = "https://github.com/maufadel/EnergyMeter"
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-energymeter
3
+ Version: 2.0.1
4
+ Summary: A library to measure energy consumption of applications
5
+ Author-email: Mauricio Fadel Argerich <maufadel@icloud.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/maufadel/EnergyMeter
8
+ Project-URL: Repository, https://github.com/maufadel/EnergyMeter
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pynvml
16
+ Requires-Dist: pyRAPL
17
+ Requires-Dist: numpy
18
+ Requires-Dist: pandas
19
+ Requires-Dist: matplotlib
20
+ Dynamic: license-file
21
+
22
+ # EnergyMeter
23
+ EnergyMeter is a Python module that combines pyRAPL, NVIDIA-SMI and eBPF to estimate the energy consumption of CPU, memory, GPU, and storage on Linux with only three lines of code. This was developed during the development of the article Fadel Argerich, M., & Patiño-Martínez, M. (2024). Measuring and Improving the Energy Efficiency of Large Language Models Inference. IEEE Access.
24
+
25
+ ### Update: version 2.0 is out!
26
+ The new version improves the accuracy of the energy consumption of the GPU while also reducing the overhead of the meter, so there is no visible overhead now.
27
+
28
+ ## How to install
29
+ You can install EnergyMeter by cloning this repository and using pip:
30
+ ```
31
+ git clone https://github.com/maufadel/EnergyMeter.git
32
+ cd EnergyMeter
33
+ pip install .
34
+ ```
35
+
36
+ ## How to use
37
+ The most basic usage of EnergyMeter is as follows:
38
+ ```
39
+ from energy_meter import EnergyMeter
40
+
41
+ em = EnergyMeter(disk_avg_speed=1600*1e6, # The average speed of your storage (see below how you can get it)
42
+ disk_active_power=6, # How many Watts are used when the storage is reading or writing (you can usually find it in specs of your storage)
43
+ disk_idle_power=1.42, # How many Watts are used when the storage is idle (you can usually find it in specs of your storage)
44
+ label="Test Meter", # A label to identify the measurement
45
+ include_idle=False) # If energy used during idle should be accounted for in the measurement. Defaults to False.
46
+
47
+ em.begin()
48
+ # --> CODE YOU WANT TO MEASURE <--
49
+ em.end()
50
+
51
+ # Plot energy consumption per component.
52
+ meter.plot_total_joules_per_component()
53
+ # or print(em.get_total_joules_per_component())
54
+ ```
55
+ ![Example Output](https://github.com/maufadel/meml/blob/main/example_output.png)
56
+
57
+ You can check the notebook [Measuring_energy_consumption.ipynb](https://github.com/maufadel/meml/blob/main/Measuring_energy_consumption.ipynb) for more details.
58
+
59
+ ## How to get storage details
60
+ You can benchmark your storage speed with the Flexible I/O tester (FIO) as recommended by Google in the following tutorial: https://cloud.google.com/compute/docs/disks/benchmarking-pd-performance
61
+
62
+ Storage specs usually include data regarding the power consumption during active (reading or writing) and for idle periods.
63
+
64
+ ## Troubleshooting
65
+ ### pyRAPL/RAPL
66
+ pyRAPL requires access to /sys/class/powercap/intel-rapl, for which sudo access is required. If the access is denied, run the following command on the terminal to enable access to the rapl measurement:
67
+
68
+ `sudo chmod -R a+r /sys/class/powercap/intel-rapl`
69
+
70
+ ### bpftrace
71
+ Also note that you need to have bpftrace installed. On ubuntu, you can install it with the following command:
72
+
73
+ `sudo apt-get install -y bpftrace`
74
+
75
+ For other operating systems, please check https://github.com/bpftrace/bpftrace/blob/master/INSTALL.md.
76
+
77
+ ## Limitations
78
+ EnergyMeter requires to be run on bare metal instances running Linux on Intel and NVIDIA hardware. These requirements are inherited from the tools used for tracking the energy consumption: RAPL (Intel), NVIDIA-SMI (NVIDIA), and eBPF (Linux). These tools are known to have a high accuracy thanks to their access to low level sensors, but it is important to keep in mind that the energy consumption metrics provided are still estimations and vary according to different factors including hardware configuration and software versions. Additionally, the energy consumed by cooling, screens and other components not mentioned here are not included in our measurements, so the total energy consumed will likely be different to the total sum of the consumption of CPU, memory, GPU, and storage.
79
+
80
+ ## Authorship and License
81
+ I am developing EnergyMeter as a part of my PhD program at Universidad Politécnica de Madrid. EnergyMeter is open sourced under an MIT License.
82
+
83
+ If you found this repository useful, please cite our work:
84
+ ```
85
+ @article{argerich2024measuring,
86
+ title={Measuring and Improving the Energy Efficiency of Large Language Models Inference},
87
+ author={Fadel Argerich, Mauricio and Pati{\~n}o-Mart{\'\i}nez, Marta},
88
+ journal={IEEE Access},
89
+ year={2024},
90
+ publisher={IEEE}
91
+ }
92
+ ```
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/ai_energymeter.egg-info/PKG-INFO
5
+ src/ai_energymeter.egg-info/SOURCES.txt
6
+ src/ai_energymeter.egg-info/dependency_links.txt
7
+ src/ai_energymeter.egg-info/requires.txt
8
+ src/ai_energymeter.egg-info/top_level.txt
9
+ src/energymeter/__init__.py
10
+ src/energymeter/energy_meter.py
@@ -0,0 +1,5 @@
1
+ pynvml
2
+ pyRAPL
3
+ numpy
4
+ pandas
5
+ matplotlib
@@ -0,0 +1 @@
1
+ from .energy_meter import EnergyMeter
@@ -0,0 +1,497 @@
1
+ #!/usr/bin/env python
2
+ """
3
+ This module implements the class EnergyMeter, to measure the energy consumption of Python
4
+ functions or code chunks, segregating their energy usage per component (CPU, DRAM, GPU and
5
+ Hard Disk).
6
+ """
7
+ from datetime import datetime
8
+ import matplotlib.pyplot as plt
9
+ import numpy as np
10
+ import pandas as pd
11
+ import pyRAPL
12
+ from pynvml import *
13
+
14
+ import subprocess
15
+ import os
16
+ import shlex
17
+ import json
18
+ import time
19
+ import threading
20
+
21
+
22
+ class ThreadGpuSamplingPyNvml(threading.Thread):
23
+ """
24
+ Thread to sample GPU power draw and utilization using PyNVML.
25
+ """
26
+
27
+ def __init__(self, name, gpu_index=0, seconds_between_samples=0.1):
28
+ """
29
+ Initialize the sampling thread.
30
+
31
+ Args:
32
+ name: Thread name
33
+ gpu_index: GPU device index (default 0)
34
+ seconds_between_samples: Sampling interval in seconds
35
+ """
36
+ threading.Thread.__init__(self)
37
+ self.name = name
38
+ self.daemon = True # Thread dies when main thread exits
39
+ self.stop = False
40
+ self.gpu_index = gpu_index
41
+ self.seconds_between_samples = seconds_between_samples
42
+
43
+ # Thread-safe storage with timestamps
44
+ self._lock = threading.Lock()
45
+ self.samples = [] # List of dicts with all measurements
46
+
47
+ # For backward compatibility
48
+ self.power_draw_history = []
49
+ self.activity_history = []
50
+
51
+ # Initialize NVML and get GPU handle
52
+ self._nvml_initialized = False
53
+ try:
54
+ nvmlInit()
55
+ self.gpu_handle = nvmlDeviceGetHandleByIndex(self.gpu_index)
56
+ self._nvml_initialized = True
57
+ except NVMLError as e:
58
+ print(f"Warning: Failed to initialize NVML: {e}")
59
+ print("GPU energy measurements will not be available.")
60
+
61
+ def run(self):
62
+ """
63
+ Sample GPU metrics until self.stop is set to True.
64
+ """
65
+ if not self._nvml_initialized:
66
+ print("NVML not initialized, GPU sampling thread exiting.")
67
+ return
68
+
69
+ while not self.stop:
70
+ try:
71
+ timestamp = time.time()
72
+
73
+ # Get power draw (in milliwatts, convert to watts)
74
+ power_mw = nvmlDeviceGetPowerUsage(self.gpu_handle)
75
+ power_w = power_mw / 1000.0
76
+
77
+ # Get GPU utilization (percentage)
78
+ utilization = nvmlDeviceGetUtilizationRates(self.gpu_handle)
79
+ gpu_util = utilization.gpu
80
+
81
+ # Get temperature
82
+ temp = nvmlDeviceGetTemperature(self.gpu_handle, NVML_TEMPERATURE_GPU)
83
+
84
+ # Store sample
85
+ sample = {
86
+ 'timestamp': timestamp,
87
+ 'power_w': power_w,
88
+ 'gpu_util': gpu_util,
89
+ 'temp_c': temp,
90
+ }
91
+
92
+ with self._lock:
93
+ self.samples.append(sample)
94
+ # Update backward compatibility lists
95
+ self.power_draw_history.append(power_w)
96
+ self.activity_history.append(gpu_util)
97
+
98
+ except NVMLError as e:
99
+ print(f"NVML sampling error: {e}")
100
+ # Continue sampling even if one sample fails
101
+
102
+ time.sleep(self.seconds_between_samples)
103
+
104
+ def get_samples(self):
105
+ """
106
+ Get a copy of all samples (thread-safe).
107
+
108
+ Returns:
109
+ list: List of sample dictionaries
110
+ """
111
+ with self._lock:
112
+ return self.samples.copy()
113
+
114
+ def clear_samples(self):
115
+ """
116
+ Clear all stored samples (useful between experiments).
117
+ """
118
+ with self._lock:
119
+ self.samples.clear()
120
+ self.power_draw_history.clear()
121
+ self.activity_history.clear()
122
+
123
+ def shutdown(self):
124
+ """
125
+ Stop sampling and cleanup NVML.
126
+ """
127
+ self.stop = True
128
+ self.join(timeout=1.0) # Wait for thread to finish
129
+ if self._nvml_initialized:
130
+ try:
131
+ nvmlShutdown()
132
+ except NVMLError:
133
+ pass # Already shutdown
134
+
135
+ def get_statistics(self):
136
+ """
137
+ Calculate summary statistics from samples.
138
+
139
+ Returns:
140
+ dict: Mean, max, min, std for power and utilization
141
+ """
142
+ with self._lock:
143
+ if not self.samples:
144
+ return None
145
+
146
+ power_values = np.array([s['power_w'] for s in self.samples])
147
+ util_values = np.array([s['gpu_util'] for s in self.samples])
148
+ temp_values = np.array([s['temp_c'] for s in self.samples])
149
+ timestamps = np.array([s['timestamp'] for s in self.samples])
150
+
151
+ # Calculate energy using trapezoidal integration
152
+ energy_j = np.trapezoid(power_values, timestamps)
153
+ energy_wh = energy_j / 3600
154
+
155
+ return {
156
+ 'power_w': {
157
+ 'mean': np.mean(power_values),
158
+ 'max': np.max(power_values),
159
+ 'min': np.min(power_values),
160
+ 'std': np.std(power_values),
161
+ },
162
+ 'gpu_util': {
163
+ 'mean': np.mean(util_values),
164
+ 'max': np.max(util_values),
165
+ 'min': np.min(util_values),
166
+ },
167
+ 'temp_c': {
168
+ 'mean': np.mean(temp_values),
169
+ 'max': np.max(temp_values),
170
+ 'min': np.min(temp_values),
171
+ },
172
+ 'duration_s': timestamps[-1] - timestamps[0] if len(timestamps) > 1 else 0,
173
+ 'num_samples': len(self.samples),
174
+ 'energy_wh': energy_wh,
175
+ 'energy_j': energy_j,
176
+ }
177
+
178
+
179
+ class EnergyMeter:
180
+ """
181
+ The consumption of each component is measured as follows:
182
+
183
+ - CPU: the energy consumption of the CPU is measured with RAPL via the pyRAPL
184
+ library. RAPL is an API from Intel, which is also semi-compatible with
185
+ AMD. RAPL on Intel has been shown to be accurate thanks to the usage of
186
+ embedded sensors in the processor and memory while AMD uses performance
187
+ counters and is therefore, not so accurate.
188
+
189
+ - DRAM: the energy used by the memory is also measure with RAPL via pyRAPL.
190
+ This might not be available for AMD processors and pre-Haswell Intel
191
+ processors. You can find more info here:
192
+ https://dl.acm.org/doi/pdf/10.1145/2989081.2989088.
193
+
194
+ - GPU: we measure the energy consumption of the GPU with PyNVML. For this, we
195
+ run a separate thread that samples the power draw of the GPU while the meter
196
+ is running. We then calculate the total energy using trapezoidal integration
197
+ of the power samples over time.
198
+
199
+ - Disk: we cannot directly measure the energy consumption of the disk in the same
200
+ way that we do for the other components, so we have implemented an bpftrace
201
+ probe that tracks all the bytes read and written to disk. This probe is run
202
+ as a separate thread inside EnergyMeter. We then calculate the energy
203
+ consumption with the following formulae:
204
+ disk_active_time = (bytes_read + bytes_written) / DISK_SPEED
205
+ disk_idle_time = total_meter_time - disk_active_time
206
+ total_energy = disk_active_time * DISK_ACTIVE_POWER +
207
+ disk_idle_time * DISK_IDLE_POWER
208
+ Note that you are required the provide the parameters DISK_SPEED,
209
+ DISK_ACTIVE_POWER and DISK_IDLE_POWER.
210
+ """
211
+
212
+ #################################### CONSTANTS ####################################
213
+ SCRIPT = (
214
+ "tracepoint:syscalls:sys_enter_write {@wbytes[comm] = sum(args->count);} "
215
+ "tracepoint:syscalls:sys_enter_read {@rbytes[comm] = sum(args->count);}"
216
+ )
217
+ ###################################################################################
218
+
219
+ def __init__(self, disk_avg_speed=None, disk_active_power=None, disk_idle_power=None,
220
+ label=None, include_idle=False, ignore_disk=False,
221
+ gpu_index=0, gpu_sampling_rate=0.1):
222
+ """Initiates the variables required to meter the energy consumption of all
223
+ components and sets up the pyRAPL library.
224
+ :param disk_avg_speed: the average read and write speed of the hard disk where
225
+ the code will be run. We recommend measuring this with a speed test such as
226
+ this: https://cloud.google.com/compute/docs/disks/benchmarking-pd-performance.
227
+ :param disk_active_power: the power used by the disk when active. This information
228
+ is usually included in the disk specs. Hint: run lshw to get info about the
229
+ host's disk.
230
+ :param disk_idle_power: the average power used by the disk when idle. Just as for
231
+ disk_active_power, this is usually included in the disk specs.
232
+ :param label: this is just an optional string to identify the meter.
233
+ :param include_idle: if energy used during idle times should be included for disk and
234
+ GPU.
235
+ :param ignore_disk: False by default, when set to True, disk will not be tracked (used
236
+ for compatibility with systems without access to sudo or bpftrace)
237
+ :param gpu_index: GPU device index to monitor (default 0)
238
+ :param gpu_sampling_rate: sampling frequency in seconds (default 0.1 = 10Hz)
239
+ """
240
+ if label:
241
+ self.label = label
242
+ else:
243
+ self.label = "Meter"
244
+
245
+ self.include_idle = include_idle
246
+
247
+ # Setup pyRAPL to measure CPU and DRAM.
248
+ try:
249
+ pyRAPL.setup()
250
+
251
+ # Create the pyRAPL meter to measure CPU and DRAM energy consumption.
252
+ self.meter = pyRAPL.Measurement(self.label)
253
+ except Exception as e:
254
+ print(f"Warning: Could not initialize pyRAPL: {e}")
255
+ print("CPU and DRAM energy measurements will not be available.")
256
+ self.meter = None
257
+
258
+ # Setup disk parameters.
259
+ self.ignore_disk = ignore_disk
260
+ if ignore_disk == False and (disk_avg_speed is None or disk_active_power is None or disk_idle_power is None):
261
+ raise Exception("disk_avg_speed, disk_active_power, and disk_idle_power are necessary values if disk energy will be monitored; if you want to ignore the disk, set ignore_disk=True when calling init.")
262
+ else:
263
+ self.disk_avg_speed = disk_avg_speed
264
+ self.disk_active_power = disk_active_power
265
+ self.disk_idle_power = disk_idle_power
266
+
267
+ # Create thread for sampling the power draw of the GPU with improved PyNVML implementation
268
+ self.thread_gpu = ThreadGpuSamplingPyNvml(
269
+ name="GPU Sampling Thread",
270
+ gpu_index=gpu_index,
271
+ seconds_between_samples=gpu_sampling_rate
272
+ )
273
+
274
+ # Create command for bpftrace subprocess that will count the bytes read and
275
+ # written to disk.
276
+ self.bpftrace_command = shlex.split(
277
+ "sudo bpftrace -f json -e '{}'".format(EnergyMeter.SCRIPT)
278
+ )
279
+
280
+ def begin(self):
281
+ """Begin measuring the energy consumption. This sets the starting datetime and
282
+ reads the current RAPL counters.
283
+ """
284
+ self.start_time = time.time()
285
+
286
+ # pyRAPL for CPU and DRAM.
287
+ if self.meter:
288
+ self.meter.begin()
289
+ else:
290
+ print("RAPL is not accessible, no CPU or memory energy metrics are available!")
291
+
292
+ # bpftrace for disk.
293
+ if not self.ignore_disk:
294
+ try:
295
+ self.popen = subprocess.Popen(
296
+ self.bpftrace_command, stdout=subprocess.PIPE, preexec_fn=os.setpgrp
297
+ )
298
+ self.bpftrace_pid = os.getpgid(self.popen.pid)
299
+ except Exception as e:
300
+ print(f"Warning: Could not start bpftrace for disk monitoring: {e}")
301
+ self.ignore_disk = True
302
+
303
+ # Thread for GPU.
304
+ self.thread_gpu.start()
305
+
306
+ def end(self):
307
+ """Finish the measurements and calculate results for CPU and DRAM. This sets the
308
+ duration of the meter and reads again the RAPL counters, calculating how much energy
309
+ was used since the meter began.
310
+ """
311
+ # PyRAPL.
312
+ if self.meter:
313
+ self.meter.end()
314
+
315
+ # Kill bpftrace subprocess.
316
+ if not self.ignore_disk:
317
+ try:
318
+ subprocess.check_output(shlex.split("sudo kill {}".format(self.bpftrace_pid)))
319
+ except Exception as e:
320
+ print(f"Warning: Could not stop bpftrace: {e}")
321
+
322
+ # Stop tracking GPU power usage.
323
+ self.thread_gpu.stop = True
324
+ self.thread_gpu.join(timeout=2.0)
325
+
326
+ # Process bpftrace output.
327
+ if not self.ignore_disk:
328
+ try:
329
+ po = self.popen.stdout.read()
330
+ self.total_rbytes, self.total_wbytes = self.__preprocess_bpftrace_output(po)
331
+ except Exception as e:
332
+ print(f"Warning: Could not read bpftrace output: {e}")
333
+ self.total_rbytes, self.total_wbytes = 0, 0
334
+ else:
335
+ self.total_rbytes, self.total_wbytes = 0, 0
336
+
337
+ self.end_time = time.time()
338
+ self.duration = self.end_time - self.start_time
339
+
340
+ def __preprocess_bpftrace_output(self, bpftrace_output):
341
+ """Preprocess the output of out bpftrace script and extract the bytes read and
342
+ written. Attention: This must be changed if the bpftrace script changes!
343
+ :param bpftrace_output: the output of the bpftrace script.
344
+ :returns: total_rbytes (float), total_wbytes (float).
345
+ """
346
+ bpftrace_output = bpftrace_output.decode()
347
+ if len(bpftrace_output.strip()) > 0:
348
+ po = bpftrace_output.split("\n")
349
+ rbytes = json.loads(po[3]).get("data").get("@rbytes")
350
+ wbytes = json.loads(po[4]).get("data").get("@wbytes")
351
+ # Do we want to measure other programs disk IO too?
352
+ total_rbytes = rbytes.get("python", 0) + rbytes.get("python3", 0)
353
+ total_wbytes = wbytes.get("python", 0) + wbytes.get("python3", 0)
354
+ else:
355
+ # bpftrace produced no output, which means there was no IO activity in the
356
+ # disk. This only happens when the code run has a very short duration.
357
+ total_rbytes = 0
358
+ total_wbytes = 0
359
+
360
+ return total_rbytes, total_wbytes
361
+
362
+ def get_total_joules_disk(self):
363
+ """We calculate the disk's energy consumption while the meter was running. For this,
364
+ we require the csv file that was generated by running the bash script start_meters.sh.
365
+ In this case, we utilize the speed and energy consumption parameters given when this
366
+ object was initiated to estimate the disk's energy consumption. The formula used here
367
+ was derived from:
368
+ [1] Kansal, A., Zhao, F., Liu, J., Kothari, N., & Bhattacharya, A. A. (2010, June).
369
+ Virtual machine power metering and provisioning. In Proceedings of the 1st ACM
370
+ symposium on Cloud computing (pp. 39-50).
371
+
372
+ :returns: the total joules used by the disk between meter.begin() and meter.end().
373
+ """
374
+ if self.ignore_disk:
375
+ return 0
376
+
377
+ tot_bytes = self.total_rbytes + self.total_wbytes
378
+
379
+ # disk_active_time (in seconds) = (bytes_read + bytes_written) / DISK_SPEED
380
+ disk_active_time = tot_bytes / self.disk_avg_speed
381
+
382
+ # disk_idle_time (in seconds) = total_meter_time - disk_active_time
383
+ disk_idle_time = self.duration - disk_active_time
384
+
385
+ # total_energy = disk_active_time * DISK_ACTIVE_POWER (+ disk_idle_time * DISK_IDLE_POWER)
386
+ te = disk_active_time * self.disk_active_power
387
+ if self.include_idle:
388
+ te += disk_idle_time * self.disk_idle_power
389
+ return te
390
+
391
+ def get_total_joules_cpu(self):
392
+ """We obtain the total joules consumed by the CPU from pyRAPL.
393
+ :returns: the total joules used by the CPU between meter.begin() and meter.end().
394
+ """
395
+ # pyRAPL returns the microjoules, so we convert them to joules.
396
+ if self.meter and self.meter.result.pkg:
397
+ return np.array(self.meter.result.pkg) * 1e-6
398
+ else:
399
+ print("RAPL did not record energy for pkg!")
400
+ return np.array([0])
401
+
402
+ def get_total_joules_dram(self):
403
+ """We obtain the total joules consumed by the DRAM from pyRAPL.
404
+ :returns: the total joules used by the DRAM between meter.begin() and meter.end().
405
+ """
406
+ # pyRAPL returns the microjoules, so we convert them to joules.
407
+ if self.meter and self.meter.result.dram:
408
+ return np.array(self.meter.result.dram) * 1e-6
409
+ else:
410
+ print("RAPL did not record energy for dram!")
411
+ return np.array([0])
412
+
413
+ def get_total_joules_gpu(self):
414
+ """We calculate the GPU's energy consumption while the meter was running using
415
+ trapezoidal integration of power samples over time. This provides more accurate
416
+ energy measurements than the previous mean power × duration approach.
417
+
418
+ :returns: the total joules used by the GPU between meter.begin() and meter.end().
419
+ """
420
+ stats = self.thread_gpu.get_statistics()
421
+
422
+ if stats is None or stats['num_samples'] == 0:
423
+ print("Warning: No GPU samples collected!")
424
+ return 0
425
+
426
+ if not self.include_idle:
427
+ # Filter to only active samples (GPU utilization > 0)
428
+ samples = self.thread_gpu.get_samples()
429
+ active_samples = [s for s in samples if s['gpu_util'] > 0]
430
+
431
+ if len(active_samples) == 0:
432
+ return 0
433
+
434
+ # Recalculate energy for active periods only
435
+ timestamps = np.array([s['timestamp'] for s in active_samples])
436
+ power_values = np.array([s['power_w'] for s in active_samples])
437
+
438
+ energy_j = np.trapezoid(power_values, timestamps)
439
+ return energy_j
440
+ else:
441
+ # Use total energy (including idle)
442
+ return stats['energy_j']
443
+
444
+ def get_total_joules_per_component(self):
445
+ """This returns the total energy consumption in joules between meter.begin() and
446
+ meter.end() segregated by component (CPU, DRAM, GPU and disk).
447
+ :returns: a dictionary with the total joules used by each component.
448
+ """
449
+ cpu = self.get_total_joules_cpu()
450
+ dram = self.get_total_joules_dram()
451
+ gpu = self.get_total_joules_gpu()
452
+ disk = self.get_total_joules_disk()
453
+ res = {
454
+ "cpu": cpu,
455
+ "dram": dram,
456
+ "gpu": gpu,
457
+ "disk": disk,
458
+ }
459
+ return res
460
+
461
+ def get_gpu_statistics(self):
462
+ """
463
+ Get detailed GPU statistics including temperature and utilization.
464
+
465
+ :returns: dictionary with GPU statistics or None if no samples
466
+ """
467
+ return self.thread_gpu.get_statistics()
468
+
469
+ def plot_total_joules_per_component(self, include_total=True):
470
+ """This plots the total energy consumption in joules between meter.begin() and
471
+ meter.end() and the total consumption by each component (CPU, DRAM, GPU and disk).
472
+ """
473
+ data = self.get_total_joules_per_component()
474
+ if include_total:
475
+ data["total"] = (
476
+ np.sum(data.get("cpu"))
477
+ + np.sum(data.get("dram"))
478
+ + data.get("disk")
479
+ + data.get("gpu")
480
+ )
481
+ keys = data.keys()
482
+ values = [float(val) for val in data.values()]
483
+
484
+ fig, ax = plt.subplots()
485
+ bars = ax.bar(list(keys), values)
486
+ ax.bar_label(bars)
487
+ plt.xlabel("Components")
488
+ plt.ylabel("Joules")
489
+ plt.title(self.label)
490
+
491
+ plt.show()
492
+
493
+ def cleanup(self):
494
+ """
495
+ Cleanup resources (call this when completely done with the meter).
496
+ """
497
+ self.thread_gpu.shutdown()