-
Notifications
You must be signed in to change notification settings - Fork 177
/
test_emissions_tracker.py
428 lines (369 loc) · 13.1 KB
/
test_emissions_tracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import os
import shutil
import tempfile
import time
import unittest
from pathlib import Path
from unittest import mock
import pandas as pd
import requests
import responses
from codecarbon.emissions_tracker import (
EmissionsTracker,
OfflineEmissionsTracker,
track_emissions,
)
from codecarbon.external.geography import CloudMetadata
from tests.fake_modules import pynvml as fake_pynvml
from tests.testdata import (
GEO_METADATA_CANADA,
TWO_GPU_DETAILS_RESPONSE,
TWO_GPU_DETAILS_RESPONSE_HANDLES,
)
from tests.testutils import get_custom_mock_open, get_test_data_source
def heavy_computation(run_time_secs: float = 3):
end_time: float = (
time.perf_counter() + run_time_secs
) # Run for `run_time_secs` seconds
while time.perf_counter() < end_time:
pass
empty_conf = "[codecarbon]"
@mock.patch("codecarbon.core.gpu.pynvml", fake_pynvml)
@mock.patch("codecarbon.core.gpu.is_gpu_details_available", return_value=True)
@mock.patch(
"codecarbon.external.hardware.AllGPUDevices.get_gpu_details",
return_value=TWO_GPU_DETAILS_RESPONSE,
)
@mock.patch(
"codecarbon.emissions_tracker.EmissionsTracker._get_cloud_metadata",
return_value=CloudMetadata(provider=None, region=None),
)
@mock.patch("codecarbon.core.cpu.IntelPowerGadget._log_values")
@mock.patch("codecarbon.core.cpu.IntelPowerGadget._setup_cli")
class TestCarbonTracker(unittest.TestCase):
def setUp(self) -> None:
fake_pynvml.DETAILS = TWO_GPU_DETAILS_RESPONSE_HANDLES
self.data_source = get_test_data_source()
self.project_name = "project_foo"
self.temp_dir = tempfile.TemporaryDirectory()
self.temp_path = Path(self.temp_dir.name)
self.emissions_file_path = self.temp_path / "emissions.csv"
# builtins.open is patched not to open ~/.codecarbon.config nor
# ./.codecarbon.config so that the user's local configuration does not
# alter tests
patcher = mock.patch(
"builtins.open", new_callable=get_custom_mock_open(empty_conf, empty_conf)
)
self.addCleanup(patcher.stop)
patcher.start()
def tearDown(self) -> None:
fake_pynvml.INIT_MOCK.reset_mock()
self.temp_dir.cleanup()
@responses.activate
def test_carbon_tracker_TWO_GPU_PRIVATE_INFRA_CANADA(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
# GIVEN
responses.add(
responses.GET,
"https://get.geojs.io/v1/ip/geo.json",
json=GEO_METADATA_CANADA,
status=200,
)
tracker = EmissionsTracker(measure_power_secs=1, save_to_file=False)
# WHEN
tracker.start()
heavy_computation()
emissions = tracker.stop()
# THEN
self.assertGreaterEqual(
mocked_get_gpu_details.call_count, 2
) # at least 2 times in 5 seconds + once for init >= 3
self.assertEqual(2, mocked_is_gpu_details_available.call_count)
self.assertEqual(1, len(responses.calls))
self.assertEqual(
"https://get.geojs.io/v1/ip/geo.json", responses.calls[0].request.url
)
self.assertIsInstance(emissions, float)
self.assertAlmostEqual(emissions, 6.262572537957655e-05, places=2)
@mock.patch("codecarbon.external.geography.requests.get")
def test_carbon_tracker_timeout(
self,
mocked_requests_get,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
# GIVEN
# breakpoint()
def raise_timeout_exception(*args, **kwargs):
raise requests.exceptions.Timeout()
mocked_requests_get.side_effect = raise_timeout_exception
tracker = EmissionsTracker(measure_power_secs=1, save_to_file=False)
# WHEN
tracker.start()
heavy_computation(run_time_secs=2)
emissions = tracker.stop()
self.assertEqual(2, mocked_requests_get.call_count)
self.assertIsInstance(emissions, float)
self.assertAlmostEqual(1.1037980397280433e-05, emissions, places=2)
def test_graceful_start_failure(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
tracker = EmissionsTracker(measure_power_secs=1, save_to_file=False)
def raise_exception(*args, **kwargs):
raise Exception()
mocked_scheduler = mock.MagicMock()
mocked_scheduler.start = raise_exception
tracker._scheduler = mocked_scheduler
tracker.start()
def test_graceful_stop_failure(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
tracker = EmissionsTracker(measure_power_secs=1, save_to_file=False)
def raise_exception(*args, **kwargs):
raise Exception()
tracker.start()
heavy_computation(1)
tracker._measure_power = raise_exception
tracker.stop()
@responses.activate
def test_decorator_ONLINE_NO_ARGS(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
# GIVEN
responses.add(
responses.GET,
"https://get.geojs.io/v1/ip/geo.json",
json=GEO_METADATA_CANADA,
status=200,
)
# WHEN
@track_emissions(project_name=self.project_name, output_dir=self.temp_path)
def dummy_train_model():
return 42
dummy_train_model()
# THEN
self.verify_output_file(self.emissions_file_path, 2)
@responses.activate
def test_decorator_ONLINE_WITH_ARGS(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
# GIVEN
responses.add(
responses.GET,
"https://get.geojs.io/v1/ip/geo.json",
json=GEO_METADATA_CANADA,
status=200,
)
# WHEN
@track_emissions(project_name=self.project_name, output_dir=self.temp_path)
def dummy_train_model():
return 42
dummy_train_model()
# THEN
self.verify_output_file(self.emissions_file_path, 2)
def test_decorator_OFFLINE_NO_COUNTRY(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
# WHEN
@track_emissions(offline=True)
def dummy_train_model():
return 42
self.assertRaises(Exception, dummy_train_model)
def test_decorator_OFFLINE_WITH_LOC_ARGS(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
# GIVEN
@track_emissions(
offline=True,
country_iso_code="CAN",
project_name=self.project_name,
output_dir=self.temp_path,
experiment_id="test",
)
def dummy_train_model():
return 42
dummy_train_model()
self.verify_output_file(self.emissions_file_path, 2)
def test_decorator_OFFLINE_WITH_CLOUD_ARGS(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
# GIVEN
@track_emissions(
offline=True,
cloud_provider="gcp",
cloud_region="us-central1",
output_dir=self.temp_path,
experiment_id="test",
)
def dummy_train_model():
return 42
dummy_train_model()
self.verify_output_file(self.emissions_file_path, 2)
def test_offline_tracker_country_name(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
tracker = OfflineEmissionsTracker(
country_iso_code="USA",
output_dir=self.temp_path,
experiment_id="test",
)
tracker.start()
heavy_computation(run_time_secs=2)
tracker.stop()
emissions_df = pd.read_csv(self.emissions_file_path)
self.assertEqual("United States", emissions_df["country_name"].values[0])
self.assertEqual("USA", emissions_df["country_iso_code"].values[0])
def test_offline_tracker_invalid_headers(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
tracker = OfflineEmissionsTracker(
country_iso_code="USA",
output_dir=self.temp_path,
experiment_id="test",
)
emissions = os.path.join(
os.path.dirname(__file__), "test_data", "emissions_invalid_headers.csv"
)
shutil.copyfile(emissions, self.emissions_file_path)
tracker.start()
heavy_computation(run_time_secs=2)
tracker.stop()
emissions_df = pd.read_csv(self.emissions_file_path)
emissions_backup_df = pd.read_csv(
self.emissions_file_path.with_suffix(".csv.bak")
)
self.verify_output_file(self.emissions_file_path, 2)
self.verify_output_file(self.emissions_file_path.with_suffix(".csv.bak"), 2)
self.assertEqual("United States", emissions_df["country_name"].values[0])
self.assertEqual("Morocco", emissions_backup_df["country_name"].values[0])
def test_offline_tracker_valid_headers(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
tracker = OfflineEmissionsTracker(
country_iso_code="USA",
output_dir=self.temp_path,
experiment_id="test",
)
emissions = os.path.join(
os.path.dirname(__file__), "test_data", "emissions_valid_headers.csv"
)
shutil.copyfile(emissions, self.emissions_file_path)
tracker.start()
heavy_computation(run_time_secs=2)
tracker.stop()
emissions_df = pd.read_csv(self.emissions_file_path)
self.verify_output_file(self.emissions_file_path, 3)
print(emissions_df["cpu_power"].values[0])
self.assertAlmostEqual(0.269999999999999, emissions_df["cpu_power"].values[0])
self.assertEqual("Morocco", emissions_df["country_name"].values[0])
self.assertEqual("United States", emissions_df["country_name"].values[1])
def verify_output_file(self, file_path: str, num_lines: int) -> None:
with open(file_path, "r") as f:
lines = [line.rstrip() for line in f]
assert len(lines) == num_lines
@responses.activate
def test_carbon_tracker_online_context_manager_TWO_GPU_PRIVATE_INFRA_CANADA(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
# GIVEN
responses.add(
responses.GET,
"https://get.geojs.io/v1/ip/geo.json",
json=GEO_METADATA_CANADA,
status=200,
)
# WHEN
with EmissionsTracker(measure_power_secs=1, save_to_file=False) as tracker:
heavy_computation()
# THEN
self.assertGreaterEqual(
mocked_get_gpu_details.call_count, 2
) # at least 2 times in 5 seconds + once for init >= 3
self.assertEqual(2, mocked_is_gpu_details_available.call_count)
self.assertEqual(1, len(responses.calls))
self.assertEqual(
"https://get.geojs.io/v1/ip/geo.json", responses.calls[0].request.url
)
self.assertIsInstance(tracker.final_emissions, float)
self.assertAlmostEqual(tracker.final_emissions, 6.262572537957655e-05, places=2)
@responses.activate
def test_carbon_tracker_offline_context_manager(
self,
mock_setup_intel_cli,
mock_log_values,
mocked_get_gpu_details,
mocked_env_cloud_details,
mocked_is_gpu_details_available,
):
with OfflineEmissionsTracker(
country_iso_code="USA", output_dir=self.temp_path
) as tracker:
heavy_computation(run_time_secs=2)
emissions_df = pd.read_csv(self.emissions_file_path)
self.assertEqual("United States", emissions_df["country_name"].values[0])
self.assertEqual("USA", emissions_df["country_iso_code"].values[0])
self.assertIsInstance(tracker.final_emissions, float)