| 1 |
# Copyright 2022 The HuggingFace Team. All rights reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
import csv |
| 16 |
import json |
| 17 |
import logging |
| 18 |
import os |
| 19 |
import random |
| 20 |
import re |
| 21 |
import subprocess |
| 22 |
import tempfile |
| 23 |
import unittest |
| 24 |
import zipfile |
| 25 |
from pathlib import Path |
| 26 |
from typing import Optional |
| 27 |
from unittest import mock |
| 28 |
|
| 29 |
import numpy as np |
| 30 |
import torch |
| 31 |
from packaging import version |
| 32 |
|
| 33 |
# We use TF to parse the logs |
| 34 |
from accelerate import Accelerator |
| 35 |
from accelerate.state import PartialState |
| 36 |
from accelerate.test_utils.testing import ( |
| 37 |
MockingTestCase, |
| 38 |
TempDirTestCase, |
| 39 |
require_aim, |
| 40 |
require_clearml, |
| 41 |
require_comet_ml, |
| 42 |
require_dvclive, |
| 43 |
require_matplotlib, |
| 44 |
require_mlflow, |
| 45 |
require_pandas, |
| 46 |
require_swanlab, |
| 47 |
require_tensorboard, |
| 48 |
require_trackio, |
| 49 |
require_wandb, |
| 50 |
skip, |
| 51 |
) |
| 52 |
from accelerate.tracking import ( |
| 53 |
AimTracker, |
| 54 |
ClearMLTracker, |
| 55 |
CometMLTracker, |
| 56 |
DVCLiveTracker, |
| 57 |
GeneralTracker, |
| 58 |
MLflowTracker, |
| 59 |
SwanLabTracker, |
| 60 |
TensorBoardTracker, |
| 61 |
TrackioTracker, |
| 62 |
WandBTracker, |
| 63 |
) |
| 64 |
from accelerate.utils import ( |
| 65 |
ProjectConfiguration, |
| 66 |
is_comet_ml_available, |
| 67 |
is_dvclive_available, |
| 68 |
is_tensorboard_available, |
| 69 |
) |
| 70 |
|
| 71 |
|
| 72 |
if is_comet_ml_available(): |
| 73 |
from comet_ml import ExperimentConfig |
| 74 |
|
| 75 |
if is_tensorboard_available(): |
| 76 |
import struct |
| 77 |
|
| 78 |
from tensorboard.compat.proto import event_pb2 |
| 79 |
|
| 80 |
if is_dvclive_available(): |
| 81 |
from dvclive.plots.metric import Metric |
| 82 |
from dvclive.serialize import load_yaml |
| 83 |
from dvclive.utils import parse_metrics |
| 84 |
|
| 85 |
logger = logging.getLogger(__name__) |
| 86 |
|
| 87 |
|
| 88 |
@require_tensorboard |
| 89 |
class TensorBoardTrackingTest(unittest.TestCase): |
| 90 |
@unittest.skipIf(version.parse(np.__version__) >= version.parse("2.0"), "TB doesn't support numpy 2.0") |
| 91 |
def test_init_trackers(self): |
| 92 |
project_name = "test_project_with_config" |
| 93 |
with tempfile.TemporaryDirectory() as dirpath: |
| 94 |
accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath) |
| 95 |
config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} |
| 96 |
accelerator.init_trackers(project_name, config) |
| 97 |
accelerator.end_training() |
| 98 |
for child in Path(f"{dirpath}/{project_name}").glob("*/**"): |
| 99 |
log = list(filter(lambda x: x.is_file(), child.iterdir()))[0] |
| 100 |
assert str(log) != "" |
| 101 |
|
| 102 |
def test_log(self): |
| 103 |
project_name = "test_project_with_log" |
| 104 |
with tempfile.TemporaryDirectory() as dirpath: |
| 105 |
accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath) |
| 106 |
accelerator.init_trackers(project_name) |
| 107 |
values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} |
| 108 |
accelerator.log(values, step=0) |
| 109 |
accelerator.end_training() |
| 110 |
# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord |
| 111 |
# Names are randomly generated each time |
| 112 |
log = list(filter(lambda x: x.is_file(), Path(f"{dirpath}/{project_name}").iterdir()))[0] |
| 113 |
assert str(log) != "" |
| 114 |
|
| 115 |
def test_log_with_tensor(self): |
| 116 |
project_name = "test_project_with_log" |
| 117 |
with tempfile.TemporaryDirectory() as dirpath: |
| 118 |
accelerator = Accelerator(log_with="tensorboard", project_dir=dirpath) |
| 119 |
accelerator.init_trackers(project_name) |
| 120 |
values = {"tensor": torch.tensor(1)} |
| 121 |
accelerator.log(values, step=0) |
| 122 |
accelerator.end_training() |
| 123 |
# Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord |
| 124 |
# Names are randomly generated each time |
| 125 |
log = list(filter(lambda x: x.is_file(), Path(f"{dirpath}/{project_name}").iterdir()))[0] |
| 126 |
# Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685 |
| 127 |
with open(log, "rb") as f: |
| 128 |
data = f.read() |
| 129 |
found_tensor = False |
| 130 |
while data: |
| 131 |
header = struct.unpack("Q", data[:8]) |
| 132 |
|
| 133 |
event_str = data[12 : 12 + int(header[0])] # 8+4 |
| 134 |
data = data[12 + int(header[0]) + 4 :] |
| 135 |
event = event_pb2.Event() |
| 136 |
|
| 137 |
event.ParseFromString(event_str) |
| 138 |
if event.HasField("summary"): |
| 139 |
for value in event.summary.value: |
| 140 |
if value.simple_value == 1.0 and value.tag == "tensor": |
| 141 |
found_tensor = True |
| 142 |
assert found_tensor, "Converted tensor was not found in the log file!" |
| 143 |
|
| 144 |
def test_project_dir(self): |
| 145 |
with self.assertRaisesRegex(ValueError, "Logging with `tensorboard` requires a `logging_dir`"): |
| 146 |
_ = Accelerator(log_with="tensorboard") |
| 147 |
with tempfile.TemporaryDirectory() as dirpath: |
| 148 |
_ = Accelerator(log_with="tensorboard", project_dir=dirpath) |
| 149 |
|
| 150 |
def test_project_dir_with_config(self): |
| 151 |
config = ProjectConfiguration(total_limit=30) |
| 152 |
with tempfile.TemporaryDirectory() as dirpath: |
| 153 |
_ = Accelerator(log_with="tensorboard", project_dir=dirpath, project_config=config) |
| 154 |
|
| 155 |
|
| 156 |
@require_wandb |
| 157 |
@mock.patch.dict(os.environ, {"WANDB_MODE": "offline"}) |
| 158 |
class WandBTrackingTest(TempDirTestCase, MockingTestCase): |
| 159 |
def setUp(self): |
| 160 |
super().setUp() |
| 161 |
# wandb let's us override where logs are stored to via the WANDB_DIR env var |
| 162 |
self.add_mocks(mock.patch.dict(os.environ, {"WANDB_DIR": self.tmpdir})) |
| 163 |
|
| 164 |
@staticmethod |
| 165 |
def parse_log(log: str, section: str, record: bool = True): |
| 166 |
""" |
| 167 |
Parses wandb log for `section` and returns a dictionary of |
| 168 |
all items in that section. Section names are based on the |
| 169 |
output of `wandb sync --view --verbose` and items starting |
| 170 |
with "Record" in that result |
| 171 |
""" |
| 172 |
# Big thanks to the W&B team for helping us parse their logs |
| 173 |
pattern = rf"{section} ([\S\s]*?)\n\n" |
| 174 |
if record: |
| 175 |
pattern = rf"Record: {pattern}" |
| 176 |
cleaned_record = re.findall(pattern, log)[0] |
| 177 |
# A config |
| 178 |
if section == "config" or section == "history": |
| 179 |
cleaned_record = re.findall(r'"([a-zA-Z0-9_.,]+)', cleaned_record) |
| 180 |
return {key: val for key, val in zip(cleaned_record[0::2], cleaned_record[1::2])} |
| 181 |
# Everything else |
| 182 |
else: |
| 183 |
return dict(re.findall(r'(\w+): "([^\s]+)"', cleaned_record)) |
| 184 |
|
| 185 |
@skip |
| 186 |
def test_wandb(self): |
| 187 |
project_name = "test_project_with_config" |
| 188 |
accelerator = Accelerator(log_with="wandb") |
| 189 |
config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} |
| 190 |
kwargs = {"wandb": {"tags": ["my_tag"]}} |
| 191 |
accelerator.init_trackers(project_name, config, kwargs) |
| 192 |
values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} |
| 193 |
accelerator.log(values, step=0) |
| 194 |
accelerator.end_training() |
| 195 |
# The latest offline log is stored at wandb/latest-run/*.wandb |
| 196 |
for child in Path(f"{self.tmpdir}/wandb/latest-run").glob("*"): |
| 197 |
if child.is_file() and child.suffix == ".wandb": |
| 198 |
cmd = ["wandb", "sync", "--view", "--verbose", str(child)] |
| 199 |
content = subprocess.check_output(cmd, encoding="utf8", errors="ignore") |
| 200 |
break |
| 201 |
|
| 202 |
# Check HPS through careful parsing and cleaning |
| 203 |
logged_items = self.parse_log(content, "config") |
| 204 |
assert logged_items["num_iterations"] == "12" |
| 205 |
assert logged_items["learning_rate"] == "0.01" |
| 206 |
assert logged_items["some_boolean"] == "false" |
| 207 |
assert logged_items["some_string"] == "some_value" |
| 208 |
assert logged_items["some_string"] == "some_value" |
| 209 |
|
| 210 |
# Run tags |
| 211 |
logged_items = self.parse_log(content, "run", False) |
| 212 |
assert logged_items["tags"] == "my_tag" |
| 213 |
|
| 214 |
# Actual logging |
| 215 |
logged_items = self.parse_log(content, "history") |
| 216 |
assert logged_items["total_loss"] == "0.1" |
| 217 |
assert logged_items["iteration"] == "1" |
| 218 |
assert logged_items["my_text"] == "some_value" |
| 219 |
assert logged_items["_step"] == "0" |
| 220 |
|
| 221 |
|
| 222 |
@require_mlflow |
| 223 |
class MLflowTrackingTest(unittest.TestCase): |
| 224 |
def setUp(self): |
| 225 |
import mlflow |
| 226 |
|
| 227 |
self.tmpdir = tempfile.TemporaryDirectory() |
| 228 |
mlflow.set_tracking_uri("file://" + self.tmpdir.name) |
| 229 |
|
| 230 |
@require_matplotlib |
| 231 |
def create_mock_figure(self): |
| 232 |
"""Create a mock figure for testing.""" |
| 233 |
import matplotlib.pyplot as plt |
| 234 |
|
| 235 |
fig = plt.figure(figsize=(6, 4)) |
| 236 |
return fig |
| 237 |
|
| 238 |
def test_log(self): |
| 239 |
import mlflow |
| 240 |
|
| 241 |
"""Test that log calls mlflow.log_metrics with only numeric values and the correct step.""" |
| 242 |
values = {"accuracy": 0.95, "loss": 0.1, "non_numeric": "ignored"} |
| 243 |
tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) |
| 244 |
accelerator = Accelerator(log_with=tracker) |
| 245 |
accelerator.init_trackers(project_name="test_exp") |
| 246 |
tracker.log(values, step=10) |
| 247 |
|
| 248 |
run_id = tracker.active_run.info.run_id |
| 249 |
accelerator.end_training() |
| 250 |
|
| 251 |
# Retrieve the run and check the logged metrics. |
| 252 |
run = mlflow.get_run(run_id) |
| 253 |
metrics = run.data.metrics |
| 254 |
self.assertEqual(metrics.get("accuracy"), 0.95) |
| 255 |
self.assertEqual(metrics.get("loss"), 0.1) |
| 256 |
self.assertNotIn("non_numeric", metrics) |
| 257 |
|
| 258 |
@require_matplotlib |
| 259 |
def test_log_figure(self): |
| 260 |
import mlflow |
| 261 |
|
| 262 |
"""Test that log_figure calls mlflow.log_figure with the correct arguments.""" |
| 263 |
dummy_figure = self.create_mock_figure() |
| 264 |
tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) |
| 265 |
accelerator = Accelerator(log_with=tracker) |
| 266 |
accelerator.init_trackers(project_name="test_exp") |
| 267 |
tracker.log_figure(dummy_figure, artifact_file="dummy_figure.png") |
| 268 |
|
| 269 |
run_id = tracker.active_run.info.run_id |
| 270 |
accelerator.end_training() |
| 271 |
|
| 272 |
self.assertIn( |
| 273 |
"dummy_figure.png", |
| 274 |
[artifact.path for artifact in mlflow.artifacts.list_artifacts(run_id=run_id)], |
| 275 |
) |
| 276 |
|
| 277 |
def test_log_artifact(self): |
| 278 |
import mlflow |
| 279 |
|
| 280 |
"""Test that log_artifact calls mlflow.log_artifact with the correct file path.""" |
| 281 |
dummy_file_path = os.path.join(self.tmpdir.name, "dummy.txt") |
| 282 |
with open(dummy_file_path, "w") as f: |
| 283 |
f.write("dummy content") |
| 284 |
tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) |
| 285 |
accelerator = Accelerator(log_with=tracker) |
| 286 |
accelerator.init_trackers(project_name="test_exp") |
| 287 |
tracker.log_artifact(dummy_file_path, artifact_path="artifact_dir") |
| 288 |
|
| 289 |
run_id = tracker.active_run.info.run_id |
| 290 |
accelerator.end_training() |
| 291 |
|
| 292 |
self.assertIn( |
| 293 |
"artifact_dir/dummy.txt", |
| 294 |
[ |
| 295 |
artifact.path |
| 296 |
for artifact in mlflow.artifacts.list_artifacts(run_id=run_id, artifact_path="artifact_dir") |
| 297 |
], |
| 298 |
) |
| 299 |
|
| 300 |
def test_log_artifacts(self): |
| 301 |
import mlflow |
| 302 |
|
| 303 |
"""Test that log_artifacts calls mlflow.log_artifacts with the correct directory.""" |
| 304 |
dummy_dir = os.path.join(self.tmpdir.name, "dummy_dir") |
| 305 |
os.mkdir(dummy_dir) |
| 306 |
dummy_file_path = os.path.join(dummy_dir, "dummy.txt") |
| 307 |
with open(dummy_file_path, "w") as f: |
| 308 |
f.write("dummy content") |
| 309 |
tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) |
| 310 |
accelerator = Accelerator(log_with=tracker) |
| 311 |
accelerator.init_trackers(project_name="test_exp") |
| 312 |
tracker.log_artifacts(dummy_dir, artifact_path="artifact_dir") |
| 313 |
|
| 314 |
run_id = tracker.active_run.info.run_id |
| 315 |
accelerator.end_training() |
| 316 |
|
| 317 |
self.assertIn( |
| 318 |
"artifact_dir/dummy.txt", |
| 319 |
[ |
| 320 |
artifact.path |
| 321 |
for artifact in mlflow.artifacts.list_artifacts(run_id=run_id, artifact_path="artifact_dir") |
| 322 |
], |
| 323 |
) |
| 324 |
|
| 325 |
def test_store_init_configuration_does_not_mutate_input(self): |
| 326 |
import mlflow |
| 327 |
|
| 328 |
"""`store_init_configuration` must not mutate the caller's dict when dropping over-long values. |
| 329 |
|
| 330 |
The same `config` object is shared across all trackers in `Accelerator.init_trackers`, so deleting |
| 331 |
keys in place removed them from the user's dict and from every other tracker too. |
| 332 |
""" |
| 333 |
too_long = "x" * (mlflow.utils.validation.MAX_PARAM_VAL_LENGTH + 1) |
| 334 |
values = {"learning_rate": 0.001, "too_long": too_long} |
| 335 |
tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) |
| 336 |
accelerator = Accelerator(log_with=tracker) |
| 337 |
accelerator.init_trackers(project_name="test_exp") |
| 338 |
tracker.store_init_configuration(values) |
| 339 |
|
| 340 |
run_id = tracker.active_run.info.run_id |
| 341 |
accelerator.end_training() |
| 342 |
|
| 343 |
# The caller's dict must be left untouched (previously `too_long` was deleted in place). |
| 344 |
self.assertEqual(values, {"learning_rate": 0.001, "too_long": too_long}) |
| 345 |
|
| 346 |
# The over-long value is still dropped from what is actually logged to MLflow. |
| 347 |
params = mlflow.get_run(run_id).data.params |
| 348 |
self.assertIn("learning_rate", params) |
| 349 |
self.assertNotIn("too_long", params) |
| 350 |
|
| 351 |
def test_log_without_step(self): |
| 352 |
"""`MLflowTracker.log` should treat `step` as optional, matching the docstring.""" |
| 353 |
tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) |
| 354 |
accelerator = Accelerator(log_with=tracker) |
| 355 |
accelerator.init_trackers(project_name="test_exp") |
| 356 |
# Should not raise; previously raised TypeError because `step` had no default. |
| 357 |
tracker.log({"loss": 0.1}) |
| 358 |
accelerator.end_training() |
| 359 |
|
| 360 |
def test_log_accepts_extra_kwargs(self): |
| 361 |
"""`MLflowTracker.log` should accept extra kwargs forwarded by `Accelerator.log(log_kwargs=...)`. |
| 362 |
|
| 363 |
Previously the signature omitted `**kwargs`, so any per-tracker kwarg (e.g. `synchronous`) |
| 364 |
passed via `log_kwargs={"mlflow": {...}}` raised TypeError. Beyond not raising, the kwarg |
| 365 |
must reach `mlflow.log_metrics` so it actually changes mlflow's behavior. |
| 366 |
""" |
| 367 |
tracker = MLflowTracker(experiment_name="test_exp", logging_dir=self.tmpdir.name) |
| 368 |
accelerator = Accelerator(log_with=tracker) |
| 369 |
accelerator.init_trackers(project_name="test_exp") |
| 370 |
# `synchronous` is a real mlflow.log_metrics kwarg; the tracker must forward it. |
| 371 |
with mock.patch("mlflow.log_metrics") as mock_log_metrics: |
| 372 |
accelerator.log({"loss": 0.1}, step=1, log_kwargs={"mlflow": {"synchronous": True}}) |
| 373 |
accelerator.end_training() |
| 374 |
mock_log_metrics.assert_called_once() |
| 375 |
call_kwargs = mock_log_metrics.call_args.kwargs |
| 376 |
assert call_kwargs.get("synchronous") is True, ( |
| 377 |
f"expected synchronous=True forwarded to mlflow.log_metrics, got kwargs={call_kwargs}" |
| 378 |
) |
| 379 |
assert call_kwargs.get("step") == 1, ( |
| 380 |
f"expected step=1 forwarded to mlflow.log_metrics, got kwargs={call_kwargs}" |
| 381 |
) |
| 382 |
|
| 383 |
|
| 384 |
@require_comet_ml |
| 385 |
class CometMLTest(unittest.TestCase): |
| 386 |
@staticmethod |
| 387 |
def get_value_from_key(log_list, key: str, is_param: bool = False): |
| 388 |
"Extracts `key` from Comet `log`" |
| 389 |
for log in log_list: |
| 390 |
j = json.loads(log)["payload"] |
| 391 |
if is_param and "param" in j.keys(): |
| 392 |
if j["param"]["paramName"] == key: |
| 393 |
return j["param"]["paramValue"] |
| 394 |
if "log_other" in j.keys(): |
| 395 |
if j["log_other"]["key"] == key: |
| 396 |
return j["log_other"]["val"] |
| 397 |
if "metric" in j.keys(): |
| 398 |
if j["metric"]["metricName"] == key: |
| 399 |
return j["metric"]["metricValue"] |
| 400 |
if j.get("key", None) == key: |
| 401 |
return j["value"] |
| 402 |
|
| 403 |
def test_init_trackers(self): |
| 404 |
with tempfile.TemporaryDirectory() as d: |
| 405 |
tracker = CometMLTracker( |
| 406 |
"test_project_with_config", online=False, experiment_config=ExperimentConfig(offline_directory=d) |
| 407 |
) |
| 408 |
accelerator = Accelerator(log_with=tracker) |
| 409 |
config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} |
| 410 |
accelerator.init_trackers(None, config) |
| 411 |
accelerator.end_training() |
| 412 |
log = os.listdir(d)[0] # Comet is nice, it's just a zip file here |
| 413 |
# We parse the raw logs |
| 414 |
p = os.path.join(d, log) |
| 415 |
archive = zipfile.ZipFile(p, "r") |
| 416 |
log = archive.open("messages.json").read().decode("utf-8") |
| 417 |
list_of_json = log.split("\n")[:-1] |
| 418 |
assert self.get_value_from_key(list_of_json, "num_iterations", True) == 12 |
| 419 |
assert self.get_value_from_key(list_of_json, "learning_rate", True) == 0.01 |
| 420 |
assert self.get_value_from_key(list_of_json, "some_boolean", True) is False |
| 421 |
assert self.get_value_from_key(list_of_json, "some_string", True) == "some_value" |
| 422 |
|
| 423 |
def test_log(self): |
| 424 |
with tempfile.TemporaryDirectory() as d: |
| 425 |
tracker = CometMLTracker( |
| 426 |
"test_project_with_config", online=False, experiment_config=ExperimentConfig(offline_directory=d) |
| 427 |
) |
| 428 |
accelerator = Accelerator(log_with=tracker) |
| 429 |
accelerator.init_trackers(None) |
| 430 |
values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} |
| 431 |
accelerator.log(values, step=0) |
| 432 |
accelerator.end_training() |
| 433 |
log = os.listdir(d)[0] # Comet is nice, it's just a zip file here |
| 434 |
# We parse the raw logs |
| 435 |
p = os.path.join(d, log) |
| 436 |
archive = zipfile.ZipFile(p, "r") |
| 437 |
log = archive.open("messages.json").read().decode("utf-8") |
| 438 |
list_of_json = log.split("\n")[:-1] |
| 439 |
assert self.get_value_from_key(list_of_json, "curr_step", True) == 0 |
| 440 |
assert self.get_value_from_key(list_of_json, "total_loss") == 0.1 |
| 441 |
assert self.get_value_from_key(list_of_json, "iteration") == 1 |
| 442 |
assert self.get_value_from_key(list_of_json, "my_text") == "some_value" |
| 443 |
|
| 444 |
|
| 445 |
@require_clearml |
| 446 |
class ClearMLTest(TempDirTestCase, MockingTestCase): |
| 447 |
def setUp(self): |
| 448 |
super().setUp() |
| 449 |
# ClearML offline session location is stored in CLEARML_CACHE_DIR |
| 450 |
self.add_mocks(mock.patch.dict(os.environ, {"CLEARML_CACHE_DIR": str(self.tmpdir)})) |
| 451 |
|
| 452 |
@staticmethod |
| 453 |
def _get_offline_dir(accelerator): |
| 454 |
from clearml.config import get_offline_dir |
| 455 |
|
| 456 |
return get_offline_dir(task_id=accelerator.get_tracker("clearml", unwrap=True).id) |
| 457 |
|
| 458 |
@staticmethod |
| 459 |
def _get_metrics(offline_dir): |
| 460 |
metrics = [] |
| 461 |
with open(os.path.join(offline_dir, "metrics.jsonl")) as f: |
| 462 |
json_lines = f.readlines() |
| 463 |
for json_line in json_lines: |
| 464 |
metrics.extend(json.loads(json_line)) |
| 465 |
return metrics |
| 466 |
|
| 467 |
def test_init_trackers(self): |
| 468 |
from clearml import Task |
| 469 |
from clearml.utilities.config import text_to_config_dict |
| 470 |
|
| 471 |
Task.set_offline(True) |
| 472 |
accelerator = Accelerator(log_with="clearml") |
| 473 |
config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} |
| 474 |
accelerator.init_trackers("test_project_with_config", config) |
| 475 |
|
| 476 |
offline_dir = ClearMLTest._get_offline_dir(accelerator) |
| 477 |
accelerator.end_training() |
| 478 |
|
| 479 |
with open(os.path.join(offline_dir, "task.json")) as f: |
| 480 |
offline_session = json.load(f) |
| 481 |
clearml_offline_config = text_to_config_dict(offline_session["configuration"]["General"]["value"]) |
| 482 |
assert config == clearml_offline_config |
| 483 |
|
| 484 |
def test_log(self): |
| 485 |
from clearml import Task |
| 486 |
|
| 487 |
Task.set_offline(True) |
| 488 |
accelerator = Accelerator(log_with="clearml") |
| 489 |
accelerator.init_trackers("test_project_with_log") |
| 490 |
values_with_iteration = {"should_be_under_train": 1, "eval_value": 2, "test_value": 3.1, "train_value": 4.1} |
| 491 |
accelerator.log(values_with_iteration, step=1) |
| 492 |
single_values = {"single_value_1": 1.1, "single_value_2": 2.2} |
| 493 |
accelerator.log(single_values) |
| 494 |
|
| 495 |
offline_dir = ClearMLTest._get_offline_dir(accelerator) |
| 496 |
accelerator.end_training() |
| 497 |
|
| 498 |
metrics = ClearMLTest._get_metrics(offline_dir) |
| 499 |
assert (len(values_with_iteration) + len(single_values)) == len(metrics) |
| 500 |
for metric in metrics: |
| 501 |
if metric["metric"] == "Summary": |
| 502 |
assert metric["variant"] in single_values |
| 503 |
assert metric["value"] == single_values[metric["variant"]] |
| 504 |
elif metric["metric"] == "should_be_under_train": |
| 505 |
assert metric["variant"] == "train" |
| 506 |
assert metric["iter"] == 1 |
| 507 |
assert metric["value"] == values_with_iteration["should_be_under_train"] |
| 508 |
else: |
| 509 |
values_with_iteration_key = metric["variant"] + "_" + metric["metric"] |
| 510 |
assert values_with_iteration_key in values_with_iteration |
| 511 |
assert metric["iter"] == 1 |
| 512 |
assert metric["value"] == values_with_iteration[values_with_iteration_key] |
| 513 |
|
| 514 |
def test_log_images(self): |
| 515 |
from clearml import Task |
| 516 |
|
| 517 |
Task.set_offline(True) |
| 518 |
accelerator = Accelerator(log_with="clearml") |
| 519 |
accelerator.init_trackers("test_project_with_log_images") |
| 520 |
|
| 521 |
base_image = np.eye(256, 256, dtype=np.uint8) * 255 |
| 522 |
base_image_3d = np.concatenate((np.atleast_3d(base_image), np.zeros((256, 256, 2), dtype=np.uint8)), axis=2) |
| 523 |
images = { |
| 524 |
"base_image": base_image, |
| 525 |
"base_image_3d": base_image_3d, |
| 526 |
} |
| 527 |
accelerator.get_tracker("clearml").log_images(images, step=1) |
| 528 |
|
| 529 |
offline_dir = ClearMLTest._get_offline_dir(accelerator) |
| 530 |
accelerator.end_training() |
| 531 |
|
| 532 |
images_saved = Path(os.path.join(offline_dir, "data")).rglob("*.jpeg") |
| 533 |
assert len(list(images_saved)) == len(images) |
| 534 |
|
| 535 |
def test_log_table(self): |
| 536 |
from clearml import Task |
| 537 |
|
| 538 |
Task.set_offline(True) |
| 539 |
accelerator = Accelerator(log_with="clearml") |
| 540 |
accelerator.init_trackers("test_project_with_log_table") |
| 541 |
|
| 542 |
accelerator.get_tracker("clearml").log_table( |
| 543 |
"from lists with columns", columns=["A", "B", "C"], data=[[1, 3, 5], [2, 4, 6]] |
| 544 |
) |
| 545 |
accelerator.get_tracker("clearml").log_table("from lists", data=[["A2", "B2", "C2"], [7, 9, 11], [8, 10, 12]]) |
| 546 |
offline_dir = ClearMLTest._get_offline_dir(accelerator) |
| 547 |
accelerator.end_training() |
| 548 |
|
| 549 |
metrics = ClearMLTest._get_metrics(offline_dir) |
| 550 |
assert len(metrics) == 2 |
| 551 |
for metric in metrics: |
| 552 |
assert metric["metric"] in ("from lists", "from lists with columns") |
| 553 |
plot = json.loads(metric["plot_str"]) |
| 554 |
if metric["metric"] == "from lists with columns": |
| 555 |
print(plot["data"][0]) |
| 556 |
self.assertCountEqual(plot["data"][0]["header"]["values"], ["A", "B", "C"]) |
| 557 |
self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]]) |
| 558 |
else: |
| 559 |
self.assertCountEqual(plot["data"][0]["header"]["values"], ["A2", "B2", "C2"]) |
| 560 |
self.assertCountEqual(plot["data"][0]["cells"]["values"], [[7, 8], [9, 10], [11, 12]]) |
| 561 |
|
| 562 |
@require_pandas |
| 563 |
def test_log_table_pandas(self): |
| 564 |
import pandas as pd |
| 565 |
from clearml import Task |
| 566 |
|
| 567 |
Task.set_offline(True) |
| 568 |
accelerator = Accelerator(log_with="clearml") |
| 569 |
accelerator.init_trackers("test_project_with_log_table_pandas") |
| 570 |
|
| 571 |
accelerator.get_tracker("clearml").log_table( |
| 572 |
"from df", dataframe=pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}), step=1 |
| 573 |
) |
| 574 |
|
| 575 |
offline_dir = ClearMLTest._get_offline_dir(accelerator) |
| 576 |
accelerator.end_training() |
| 577 |
|
| 578 |
metrics = ClearMLTest._get_metrics(offline_dir) |
| 579 |
assert len(metrics) == 1 |
| 580 |
assert metrics[0]["metric"] == "from df" |
| 581 |
plot = json.loads(metrics[0]["plot_str"]) |
| 582 |
self.assertCountEqual(plot["data"][0]["header"]["values"], [["A"], ["B"], ["C"]]) |
| 583 |
self.assertCountEqual(plot["data"][0]["cells"]["values"], [[1, 2], [3, 4], [5, 6]]) |
| 584 |
|
| 585 |
|
| 586 |
@require_swanlab |
| 587 |
@mock.patch.dict(os.environ, {"SWANLAB_MODE": "local"}) |
| 588 |
class SwanLabTrackingTest(TempDirTestCase, MockingTestCase): |
| 589 |
def setUp(self): |
| 590 |
super().setUp() |
| 591 |
# Setting Path where SwanLab parsed log files are saved via the SWANLAB_LOG_DIR env var |
| 592 |
self.add_mocks(mock.patch.dict(os.environ, {"SWANLAB_LOG_DIR": self.tmpdir})) |
| 593 |
|
| 594 |
@skip |
| 595 |
def test_swanlab(self): |
| 596 |
# Disable hardware monitoring to prevent errors in test mode. |
| 597 |
import swanlab |
| 598 |
from swanlab.log.backup import BackupHandler |
| 599 |
from swanlab.log.backup.datastore import DataStore |
| 600 |
from swanlab.log.backup.models import ModelsParser |
| 601 |
|
| 602 |
swanlab.merge_settings(swanlab.Settings(hardware_monitor=False)) |
| 603 |
# Start a fake training session. |
| 604 |
accelerator = Accelerator(log_with="swanlab") |
| 605 |
project_name = "test_project_with_config" |
| 606 |
experiment_name = "test" |
| 607 |
description = "test project for swanlab" |
| 608 |
tags = ["my_tag"] |
| 609 |
config = { |
| 610 |
"epochs": 10, |
| 611 |
"learning_rate": 0.01, |
| 612 |
"offset": 0.1, |
| 613 |
} |
| 614 |
kwargs = { |
| 615 |
"swanlab": { |
| 616 |
"experiment_name": experiment_name, |
| 617 |
"description": description, |
| 618 |
"tags": tags, |
| 619 |
} |
| 620 |
} |
| 621 |
accelerator.init_trackers(project_name, config, kwargs) |
| 622 |
record_metrics = [] |
| 623 |
record_scalars = [] |
| 624 |
record_images_count = 0 |
| 625 |
record_logs = [] |
| 626 |
for epoch in range(1, swanlab.config.epochs): |
| 627 |
acc = 1 - 2**-epoch - random.random() / epoch - 0.1 |
| 628 |
loss = 2**-epoch + random.random() / epoch + 0.1 |
| 629 |
ll = swanlab.log( |
| 630 |
{ |
| 631 |
"accuracy": acc, |
| 632 |
"loss": loss, |
| 633 |
"image": swanlab.Image(np.random.random((3, 3, 3))), |
| 634 |
}, |
| 635 |
step=epoch, |
| 636 |
) |
| 637 |
log = f"epoch={epoch}, accuracy={acc}, loss={loss}" |
| 638 |
print(log) |
| 639 |
record_scalars.extend([acc, loss]) |
| 640 |
record_images_count += 1 |
| 641 |
record_logs.append(log) |
| 642 |
record_metrics.extend([x for _, x in ll.items()]) |
| 643 |
accelerator.end_training() |
| 644 |
|
| 645 |
# Load latest offline log |
| 646 |
run_dir = swanlab.get_run().public.run_dir |
| 647 |
assert os.path.exists(run_dir) is True |
| 648 |
ds = DataStore() |
| 649 |
ds.open_for_scan(os.path.join(run_dir.__str__(), BackupHandler.BACKUP_FILE).__str__()) |
| 650 |
with ModelsParser() as models_parser: |
| 651 |
for record in ds: |
| 652 |
if record is None: |
| 653 |
continue |
| 654 |
models_parser.parse_record(record) |
| 655 |
header, project, experiment, logs, runtime, columns, scalars, medias, footer = models_parser.get_parsed() |
| 656 |
|
| 657 |
# test file header |
| 658 |
assert header.backup_type == "DEFAULT" |
| 659 |
|
| 660 |
# test project info |
| 661 |
assert project.name == project_name |
| 662 |
assert project.workspace is None |
| 663 |
assert project.public is None |
| 664 |
|
| 665 |
# test experiment info |
| 666 |
assert experiment.name is not None |
| 667 |
assert experiment.description == description |
| 668 |
assert experiment.tags == tags |
| 669 |
|
| 670 |
# test log record |
| 671 |
backup_logs = [log.message for log in logs] |
| 672 |
for record_log in record_logs: |
| 673 |
assert record_log in backup_logs, "Log not found in backup logs: " + record_log |
| 674 |
|
| 675 |
# test runtime info |
| 676 |
runtime_info = runtime.to_file_model(os.path.join(run_dir.__str__(), "files")) |
| 677 |
assert runtime_info.conda is None, "Not using conda, should be None" |
| 678 |
assert isinstance(runtime_info.requirements, str), "Requirements should be a string" |
| 679 |
assert isinstance(runtime_info.metadata, dict), "Metadata should be a dictionary" |
| 680 |
assert isinstance(runtime_info.config, dict), "Config should be a dictionary" |
| 681 |
for key in runtime_info.config: |
| 682 |
assert key in config, f"Config key {key} not found in original config" |
| 683 |
assert runtime_info.config[key]["value"] == config[key], ( |
| 684 |
f"Config value for {key} does not match original value" |
| 685 |
) |
| 686 |
|
| 687 |
# test scalar |
| 688 |
assert len(scalars) + len(medias) == len(record_metrics), "Total metrics count does not match" |
| 689 |
backup_scalars = [ |
| 690 |
metric.metric["data"] |
| 691 |
for metric in record_metrics |
| 692 |
if metric.column_info.chart_type.value.column_type == "FLOAT" |
| 693 |
] |
| 694 |
assert len(backup_scalars) == len(scalars), "Total scalars count does not match" |
| 695 |
for scalar in backup_scalars: |
| 696 |
assert scalar in record_scalars, f"Scalar {scalar} not found in original scalars" |
| 697 |
backup_images = [ |
| 698 |
metric for metric in record_metrics if metric.column_info.chart_type.value.column_type == "IMAGE" |
| 699 |
] |
| 700 |
assert len(backup_images) == record_images_count, "Total images count does not match" |
| 701 |
|
| 702 |
|
| 703 |
class MyCustomTracker(GeneralTracker): |
| 704 |
"Basic tracker that writes to a csv for testing" |
| 705 |
|
| 706 |
_col_names = [ |
| 707 |
"total_loss", |
| 708 |
"iteration", |
| 709 |
"my_text", |
| 710 |
"learning_rate", |
| 711 |
"num_iterations", |
| 712 |
"some_boolean", |
| 713 |
"some_string", |
| 714 |
] |
| 715 |
|
| 716 |
name = "my_custom_tracker" |
| 717 |
requires_logging_directory = False |
| 718 |
|
| 719 |
def __init__(self, dir: str, **kwargs): |
| 720 |
super().__init__(**kwargs) |
| 721 |
self.log_dir = dir |
| 722 |
self.f = None |
| 723 |
self.writer = None |
| 724 |
|
| 725 |
def start(self): |
| 726 |
if self.f is None: |
| 727 |
self.f = open(os.path.join(self.log_dir, "log.csv"), "w+") |
| 728 |
self.writer = csv.DictWriter(self.f, fieldnames=self._col_names) |
| 729 |
self.writer.writeheader() |
| 730 |
|
| 731 |
@property |
| 732 |
def tracker(self): |
| 733 |
return self.writer |
| 734 |
|
| 735 |
def store_init_configuration(self, values: dict): |
| 736 |
logger.info("Call init") |
| 737 |
self.writer.writerow(values) |
| 738 |
|
| 739 |
def log(self, values: dict, step: Optional[int] = None): |
| 740 |
logger.info("Call log") |
| 741 |
self.writer.writerow(values) |
| 742 |
|
| 743 |
def finish(self): |
| 744 |
self.f.close() |
| 745 |
|
| 746 |
|
| 747 |
class CustomTrackerTestCase(unittest.TestCase): |
| 748 |
def test_init_trackers(self): |
| 749 |
with tempfile.TemporaryDirectory() as d: |
| 750 |
tracker = MyCustomTracker(d) |
| 751 |
accelerator = Accelerator(log_with=tracker) |
| 752 |
config = {"num_iterations": 12, "learning_rate": 1e-2, "some_boolean": False, "some_string": "some_value"} |
| 753 |
accelerator.init_trackers("Some name", config) |
| 754 |
accelerator.end_training() |
| 755 |
with open(f"{d}/log.csv") as f: |
| 756 |
data = csv.DictReader(f) |
| 757 |
data = next(data) |
| 758 |
truth = { |
| 759 |
"total_loss": "", |
| 760 |
"iteration": "", |
| 761 |
"my_text": "", |
| 762 |
"learning_rate": "0.01", |
| 763 |
"num_iterations": "12", |
| 764 |
"some_boolean": "False", |
| 765 |
"some_string": "some_value", |
| 766 |
} |
| 767 |
assert data == truth |
| 768 |
|
| 769 |
def test_log(self): |
| 770 |
with tempfile.TemporaryDirectory() as d: |
| 771 |
tracker = MyCustomTracker(d) |
| 772 |
accelerator = Accelerator(log_with=tracker) |
| 773 |
accelerator.init_trackers("Some name") |
| 774 |
values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} |
| 775 |
accelerator.log(values, step=0) |
| 776 |
accelerator.end_training() |
| 777 |
with open(f"{d}/log.csv") as f: |
| 778 |
data = csv.DictReader(f) |
| 779 |
data = next(data) |
| 780 |
truth = { |
| 781 |
"total_loss": "0.1", |
| 782 |
"iteration": "1", |
| 783 |
"my_text": "some_value", |
| 784 |
"learning_rate": "", |
| 785 |
"num_iterations": "", |
| 786 |
"some_boolean": "", |
| 787 |
"some_string": "", |
| 788 |
} |
| 789 |
assert data == truth |
| 790 |
|
| 791 |
def test_init_trackers_none_kwargs(self): |
| 792 |
with tempfile.TemporaryDirectory() as d: |
| 793 |
tracker = MyCustomTracker(d) |
| 794 |
accelerator = Accelerator(log_with=tracker) |
| 795 |
# Passing init_kwargs=None must not raise AttributeError |
| 796 |
accelerator.init_trackers("Some name", init_kwargs=None) |
| 797 |
accelerator.end_training() |
| 798 |
|
| 799 |
def test_log_none_kwargs(self): |
| 800 |
with tempfile.TemporaryDirectory() as d: |
| 801 |
tracker = MyCustomTracker(d) |
| 802 |
accelerator = Accelerator(log_with=tracker) |
| 803 |
accelerator.init_trackers("Some name") |
| 804 |
values = {"total_loss": 0.1} |
| 805 |
# Passing log_kwargs=None must not raise AttributeError |
| 806 |
accelerator.log(values, step=0, log_kwargs=None) |
| 807 |
accelerator.end_training() |
| 808 |
|
| 809 |
|
| 810 |
@require_dvclive |
| 811 |
@mock.patch("dvclive.live.get_dvc_repo", return_value=None) |
| 812 |
class DVCLiveTrackingTest(unittest.TestCase): |
| 813 |
def test_init_trackers(self, mock_repo): |
| 814 |
project_name = "test_project_with_config" |
| 815 |
with tempfile.TemporaryDirectory() as dirpath: |
| 816 |
accelerator = Accelerator(log_with="dvclive") |
| 817 |
config = { |
| 818 |
"num_iterations": 12, |
| 819 |
"learning_rate": 1e-2, |
| 820 |
"some_boolean": False, |
| 821 |
"some_string": "some_value", |
| 822 |
} |
| 823 |
init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}} |
| 824 |
accelerator.init_trackers(project_name, config, init_kwargs) |
| 825 |
accelerator.end_training() |
| 826 |
live = accelerator.trackers[0].live |
| 827 |
params = load_yaml(live.params_file) |
| 828 |
assert params == config |
| 829 |
|
| 830 |
def test_log(self, mock_repo): |
| 831 |
project_name = "test_project_with_log" |
| 832 |
with tempfile.TemporaryDirectory() as dirpath: |
| 833 |
accelerator = Accelerator(log_with="dvclive", project_dir=dirpath) |
| 834 |
init_kwargs = {"dvclive": {"dir": dirpath, "save_dvc_exp": False, "dvcyaml": None}} |
| 835 |
accelerator.init_trackers(project_name, init_kwargs=init_kwargs) |
| 836 |
values = {"total_loss": 0.1, "iteration": 1, "my_text": "some_value"} |
| 837 |
# Log step 0 |
| 838 |
accelerator.log(values) |
| 839 |
# Log step 1 |
| 840 |
accelerator.log(values) |
| 841 |
# Log step 3 (skip step 2) |
| 842 |
accelerator.log(values, step=3) |
| 843 |
accelerator.end_training() |
| 844 |
live = accelerator.trackers[0].live |
| 845 |
logs, latest = parse_metrics(live) |
| 846 |
assert latest.pop("step") == 3 |
| 847 |
assert latest == values |
| 848 |
scalars = os.path.join(live.plots_dir, Metric.subfolder) |
| 849 |
for val in values: |
| 850 |
val_path = os.path.join(scalars, f"{val}.tsv") |
| 851 |
steps = [int(row["step"]) for row in logs[val_path]] |
| 852 |
assert steps == [0, 1, 3] |
| 853 |
|
| 854 |
|
| 855 |
class TrackerDeferredInitializationTest(unittest.TestCase): |
| 856 |
""" |
| 857 |
Tests tracker's deferred initialization via `start()` method, preventing |
| 858 |
premature `PartialState` access (and `torch.distributed` init) before |
| 859 |
`Accelerator` has configured the distributed environment, especially with |
| 860 |
`InitProcessGroupKwargs`. |
| 861 |
""" |
| 862 |
|
| 863 |
@require_tensorboard |
| 864 |
def test_tensorboard_deferred_init(self): |
| 865 |
"""Test that TensorBoard tracker initialization doesn't initialize distributed""" |
| 866 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 867 |
PartialState._reset_state() |
| 868 |
tracker = TensorBoardTracker(run_name="test_tb", logging_dir=temp_dir) |
| 869 |
self.assertEqual(PartialState._shared_state, {}) |
| 870 |
_ = Accelerator(log_with=tracker) |
| 871 |
self.assertNotEqual(PartialState._shared_state, {}) |
| 872 |
|
| 873 |
@require_wandb |
| 874 |
def test_wandb_deferred_init(self): |
| 875 |
"""Test that WandB tracker initialization doesn't initialize distributed""" |
| 876 |
PartialState._reset_state() |
| 877 |
tracker = WandBTracker(run_name="test_wandb") |
| 878 |
self.assertEqual(PartialState._shared_state, {}) |
| 879 |
_ = Accelerator(log_with=tracker) |
| 880 |
self.assertNotEqual(PartialState._shared_state, {}) |
| 881 |
|
| 882 |
@require_trackio |
| 883 |
def test_trackio_deferred_init(self): |
| 884 |
"""Test that trackio tracker initialization doesn't initialize distributed""" |
| 885 |
PartialState._reset_state() |
| 886 |
tracker = TrackioTracker(run_name="test_trackio") |
| 887 |
self.assertEqual(PartialState._shared_state, {}) |
| 888 |
_ = Accelerator(log_with=tracker) |
| 889 |
self.assertNotEqual(PartialState._shared_state, {}) |
| 890 |
|
| 891 |
@require_comet_ml |
| 892 |
def test_comet_ml_deferred_init(self): |
| 893 |
"""Test that CometML tracker initialization doesn't initialize distributed""" |
| 894 |
PartialState._reset_state() |
| 895 |
tracker = CometMLTracker(run_name="test_comet") |
| 896 |
self.assertEqual(PartialState._shared_state, {}) |
| 897 |
_ = Accelerator(log_with=tracker) |
| 898 |
self.assertNotEqual(PartialState._shared_state, {}) |
| 899 |
|
| 900 |
@require_aim |
| 901 |
def test_aim_deferred_init(self): |
| 902 |
"""Test that Aim tracker initialization doesn't initialize distributed""" |
| 903 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 904 |
PartialState._reset_state() |
| 905 |
tracker = AimTracker(run_name="test_aim", repo=temp_dir) |
| 906 |
self.assertEqual(PartialState._shared_state, {}) |
| 907 |
_ = Accelerator(log_with=tracker) |
| 908 |
self.assertNotEqual(PartialState._shared_state, {}) |
| 909 |
|
| 910 |
@require_mlflow |
| 911 |
def test_mlflow_deferred_init(self): |
| 912 |
"""Test that MLflow tracker initialization doesn't initialize distributed""" |
| 913 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 914 |
PartialState._reset_state() |
| 915 |
tracker = MLflowTracker(experiment_name="test_mlflow", logging_dir=temp_dir) |
| 916 |
self.assertEqual(PartialState._shared_state, {}) |
| 917 |
_ = Accelerator(log_with=tracker) |
| 918 |
self.assertNotEqual(PartialState._shared_state, {}) |
| 919 |
|
| 920 |
@require_clearml |
| 921 |
def test_clearml_deferred_init(self): |
| 922 |
"""Test that ClearML tracker initialization doesn't initialize distributed""" |
| 923 |
PartialState._reset_state() |
| 924 |
tracker = ClearMLTracker(run_name="test_clearml") |
| 925 |
self.assertEqual(PartialState._shared_state, {}) |
| 926 |
_ = Accelerator(log_with=tracker) |
| 927 |
self.assertNotEqual(PartialState._shared_state, {}) |
| 928 |
|
| 929 |
@require_dvclive |
| 930 |
def test_dvclive_deferred_init(self): |
| 931 |
"""Test that DVCLive tracker initialization doesn't initialize distributed""" |
| 932 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 933 |
PartialState._reset_state() |
| 934 |
tracker = DVCLiveTracker(dir=temp_dir) |
| 935 |
self.assertEqual(PartialState._shared_state, {}) |
| 936 |
_ = Accelerator(log_with=tracker) |
| 937 |
self.assertNotEqual(PartialState._shared_state, {}) |
| 938 |
|
| 939 |
@require_swanlab |
| 940 |
def test_swanlab_deferred_init(self): |
| 941 |
"""Test that SwanLab tracker initialization doesn't initialize distributed""" |
| 942 |
PartialState._reset_state() |
| 943 |
tracker = SwanLabTracker(run_name="test_swanlab") |
| 944 |
self.assertEqual(PartialState._shared_state, {}) |
| 945 |
_ = Accelerator(log_with=tracker) |
| 946 |
self.assertNotEqual(PartialState._shared_state, {}) |