diff --git a/tests/unit/utilities/test_gpu_utils.py b/tests/unit/utilities/test_gpu_utils.py new file mode 100644 index 000000000..3ae7fa3a5 --- /dev/null +++ b/tests/unit/utilities/test_gpu_utils.py @@ -0,0 +1,20 @@ +import torch + +from transformer_lens.utilities import print_gpu_mem + + +def test_print_gpu_mem_reports_gib(monkeypatch, capsys): + """The allocated byte count must be converted with 2**30 bytes per GiB.""" + monkeypatch.setattr(torch.cuda, "memory_allocated", lambda *args, **kwargs: 3 * 2**30) + + print_gpu_mem("step") + + assert capsys.readouterr().out.strip() == "step ~ 3.0 GiB allocated on GPU." + + +def test_print_gpu_mem_reports_fractional_gib(monkeypatch, capsys): + monkeypatch.setattr(torch.cuda, "memory_allocated", lambda *args, **kwargs: 2**29) + + print_gpu_mem() + + assert "0.5 GiB allocated on GPU." in capsys.readouterr().out diff --git a/transformer_lens/utilities/gpu_utils.py b/transformer_lens/utilities/gpu_utils.py index 4b50c73eb..8bf70b0df 100644 --- a/transformer_lens/utilities/gpu_utils.py +++ b/transformer_lens/utilities/gpu_utils.py @@ -10,4 +10,5 @@ def print_gpu_mem(step_name=""): - print(f"{step_name} ~ {np.round(torch.cuda.memory_allocated()/2e30, 2)} GiB allocated on GPU.") + gib_allocated = torch.cuda.memory_allocated() / 2**30 + print(f"{step_name} ~ {np.round(gib_allocated, 2)} GiB allocated on GPU.")