From 55895ddb68457d52b85194d7c0a29cf35e5604b1 Mon Sep 17 00:00:00 2001 From: MOHAMMED FAISAL PARVEZ Date: Wed, 25 Nov 2026 20:13:36 +0530 Subject: [PATCH] fix: convert print_gpu_mem bytes to GiB with 2**30 print_gpu_mem divided torch.cuda.memory_allocated() by 2e30 (2 x 10^30) rather than 2**30, so it printed 0.0 GiB for any realistic allocation. Co-Authored-By: Claude Opus 5.5 --- tests/unit/utilities/test_gpu_utils.py | 20 ++++++++++++++++++++ transformer_lens/utilities/gpu_utils.py | 3 ++- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 tests/unit/utilities/test_gpu_utils.py diff --git a/tests/unit/utilities/test_gpu_utils.py b/tests/unit/utilities/test_gpu_utils.py new file mode 100644 index 0000000000..3ae7fa3a5a --- /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 4b50c73eb0..8bf70b0dff 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.")