Skip to content

Commit a81d3b8

Browse files
committed
memory usage tests
1 parent 26149c0 commit a81d3b8

File tree

8 files changed

+102
-99
lines changed

8 files changed

+102
-99
lines changed

tests/quantization/__init__.py

Whitespace-only changes.

tests/quantization/bnb/test_4bit.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -54,29 +54,8 @@ def get_some_linear_layer(model):
5454

5555
if is_torch_available():
5656
import torch
57-
import torch.nn as nn
5857

59-
class LoRALayer(nn.Module):
60-
"""Wraps a linear layer with LoRA-like adapter - Used for testing purposes only
61-
62-
Taken from
63-
https://github.com/huggingface/transformers/blob/566302686a71de14125717dea9a6a45b24d42b37/tests/quantization/bnb/test_4bit.py#L62C5-L78C77
64-
"""
65-
66-
def __init__(self, module: nn.Module, rank: int):
67-
super().__init__()
68-
self.module = module
69-
self.adapter = nn.Sequential(
70-
nn.Linear(module.in_features, rank, bias=False),
71-
nn.Linear(rank, module.out_features, bias=False),
72-
)
73-
small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5
74-
nn.init.normal_(self.adapter[0].weight, std=small_std)
75-
nn.init.zeros_(self.adapter[1].weight)
76-
self.adapter.to(module.weight.device)
77-
78-
def forward(self, input, *args, **kwargs):
79-
return self.module(input, *args, **kwargs) + self.adapter(input)
58+
from ..utils import LoRALayer, get_memory_consumption_stat
8059

8160

8261
if is_bitsandbytes_available():
@@ -350,6 +329,29 @@ def test_bnb_4bit_errors_loading_incorrect_state_dict(self):
350329

351330
assert key_to_target in str(err_context.exception)
352331

332+
def test_model_memory_usage(self):
333+
# Delete to not let anything interfere.
334+
del self.model_4bit, self.model_fp16
335+
336+
# Re-instantiate.
337+
inputs = self.get_dummy_inputs()
338+
model_fp16 = SD3Transformer2DModel.from_pretrained(
339+
self.model_name, subfolder="transformer", torch_dtype=torch.float16
340+
)
341+
unquantized_model_memory = get_memory_consumption_stat(model_fp16, inputs)
342+
nf4_config = BitsAndBytesConfig(
343+
load_in_4bit=True,
344+
bnb_4bit_quant_type="nf4",
345+
bnb_4bit_compute_dtype=torch.float16,
346+
)
347+
model_4bit = SD3Transformer2DModel.from_pretrained(
348+
self.model_name, subfolder="transformer", quantization_config=nf4_config, device_map=torch_device
349+
)
350+
quantized_model_memory = get_memory_consumption_stat(model_4bit, inputs)
351+
print(f"{unquantized_model_memory=}, {quantized_model_memory=}")
352+
assert (1.0 - (unquantized_model_memory / quantized_model_memory)) >= 100.
353+
354+
353355

354356
class BnB4BitTrainingTests(Base4bitTests):
355357
def setUp(self):

tests/quantization/bnb/test_mixed_int8.py

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -60,29 +60,8 @@ def get_some_linear_layer(model):
6060

6161
if is_torch_available():
6262
import torch
63-
import torch.nn as nn
6463

65-
class LoRALayer(nn.Module):
66-
"""Wraps a linear layer with LoRA-like adapter - Used for testing purposes only
67-
68-
Taken from
69-
https://github.com/huggingface/transformers/blob/566302686a71de14125717dea9a6a45b24d42b37/tests/quantization/bnb/test_8bit.py#L62C5-L78C77
70-
"""
71-
72-
def __init__(self, module: nn.Module, rank: int):
73-
super().__init__()
74-
self.module = module
75-
self.adapter = nn.Sequential(
76-
nn.Linear(module.in_features, rank, bias=False),
77-
nn.Linear(rank, module.out_features, bias=False),
78-
)
79-
small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5
80-
nn.init.normal_(self.adapter[0].weight, std=small_std)
81-
nn.init.zeros_(self.adapter[1].weight)
82-
self.adapter.to(module.weight.device)
83-
84-
def forward(self, input, *args, **kwargs):
85-
return self.module(input, *args, **kwargs) + self.adapter(input)
64+
from ..utils import LoRALayer, get_memory_consumption_stat
8665

8766

8867
if is_bitsandbytes_available():
@@ -248,7 +227,7 @@ def test_llm_skip(self):
248227
self.assertTrue(linear.weight.dtype == torch.int8)
249228
self.assertTrue(isinstance(linear, bnb.nn.Linear8bitLt))
250229

251-
self.assertTrue(isinstance(model_8bit.proj_out, nn.Linear))
230+
self.assertTrue(isinstance(model_8bit.proj_out, torch.nn.Linear))
252231
self.assertTrue(model_8bit.proj_out.weight.dtype != torch.int8)
253232

254233
def test_config_from_pretrained(self):
@@ -308,6 +287,24 @@ def test_device_and_dtype_assignment(self):
308287
# Check that this does not throw an error
309288
_ = self.model_fp16.cuda()
310289

290+
def test_model_memory_usage(self):
291+
# Delete to not let anything interfere.
292+
del self.model_4bit, self.model_fp16
293+
294+
# Re-instantiate.
295+
inputs = self.get_dummy_inputs()
296+
model_fp16 = SD3Transformer2DModel.from_pretrained(
297+
self.model_name, subfolder="transformer", torch_dtype=torch.float16
298+
)
299+
unquantized_model_memory = get_memory_consumption_stat(model_fp16, inputs)
300+
config = BitsAndBytesConfig(load_in_8bit=True)
301+
model_8bit = SD3Transformer2DModel.from_pretrained(
302+
self.model_name, subfolder="transformer", quantization_config=config, device_map=torch_device
303+
)
304+
quantized_model_memory = get_memory_consumption_stat(model_8bit, inputs)
305+
print(f"{unquantized_model_memory=}, {quantized_model_memory=}")
306+
assert (1.0 - (unquantized_model_memory / quantized_model_memory)) >= 100.
307+
311308

312309
class Bnb8bitDeviceTests(Base8bitTests):
313310
def setUp(self) -> None:

tests/quantization/quanto/__init__.py

Whitespace-only changes.

tests/quantization/quanto/test_quanto.py

Lines changed: 7 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -19,29 +19,8 @@
1919

2020
if is_torch_available():
2121
import torch
22-
import torch.nn as nn
23-
24-
class LoRALayer(nn.Module):
25-
"""Wraps a linear layer with LoRA-like adapter - Used for testing purposes only
26-
27-
Taken from
28-
https://github.com/huggingface/transformers/blob/566302686a71de14125717dea9a6a45b24d42b37/tests/quantization/bnb/test_4bit.py#L62C5-L78C77
29-
"""
30-
31-
def __init__(self, module: nn.Module, rank: int):
32-
super().__init__()
33-
self.module = module
34-
self.adapter = nn.Sequential(
35-
nn.Linear(module.in_features, rank, bias=False),
36-
nn.Linear(rank, module.out_features, bias=False),
37-
)
38-
small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5
39-
nn.init.normal_(self.adapter[0].weight, std=small_std)
40-
nn.init.zeros_(self.adapter[1].weight)
41-
self.adapter.to(module.weight.device)
42-
43-
def forward(self, input, *args, **kwargs):
44-
return self.module(input, *args, **kwargs) + self.adapter(input)
22+
23+
from ..utils import LoRALayer, get_memory_consumption_stat
4524

4625

4726
@nightly
@@ -86,19 +65,14 @@ def test_quanto_layers(self):
8665

8766
def test_quanto_memory_usage(self):
8867
unquantized_model = self.model_cls.from_pretrained(self.model_id, torch_dtype=self.torch_dtype)
89-
unquantized_model_memory = unquantized_model.get_memory_footprint() / 1024**3
90-
91-
model = self.model_cls.from_pretrained(**self.get_dummy_model_init_kwargs())
9268
inputs = self.get_dummy_inputs()
69+
unquantized_model_memory = get_memory_consumption_stat(unquantized_model, inputs)
9370

94-
torch.cuda.reset_peak_memory_stats()
95-
torch.cuda.empty_cache()
71+
quantized_model = self.model_cls.from_pretrained(**self.get_dummy_model_init_kwargs())
72+
quantized_model_memory = get_memory_consumption_stat(quantized_model, inputs)
9673

97-
model.to(torch_device)
98-
with torch.no_grad():
99-
model(**inputs)
100-
max_memory = torch.cuda.max_memory_allocated() / 1024**3
101-
assert (1.0 - (max_memory / unquantized_model_memory)) >= self.expected_memory_reduction
74+
print(f"{unquantized_model_memory=}, {quantized_model_memory=}")
75+
assert (1.0 - (unquantized_model_memory / quantized_model_memory)) >= self.expected_memory_reduction
10276

10377
def test_keep_modules_in_fp32(self):
10478
r"""

tests/quantization/torchao/__init__.py

Whitespace-only changes.

tests/quantization/torchao/test_torchao.py

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -50,27 +50,7 @@
5050
import torch
5151
import torch.nn as nn
5252

53-
class LoRALayer(nn.Module):
54-
"""Wraps a linear layer with LoRA-like adapter - Used for testing purposes only
55-
56-
Taken from
57-
https://github.com/huggingface/transformers/blob/566302686a71de14125717dea9a6a45b24d42b37/tests/quantization/bnb/test_4bit.py#L62C5-L78C77
58-
"""
59-
60-
def __init__(self, module: nn.Module, rank: int):
61-
super().__init__()
62-
self.module = module
63-
self.adapter = nn.Sequential(
64-
nn.Linear(module.in_features, rank, bias=False),
65-
nn.Linear(rank, module.out_features, bias=False),
66-
)
67-
small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5
68-
nn.init.normal_(self.adapter[0].weight, std=small_std)
69-
nn.init.zeros_(self.adapter[1].weight)
70-
self.adapter.to(module.weight.device)
71-
72-
def forward(self, input, *args, **kwargs):
73-
return self.module(input, *args, **kwargs) + self.adapter(input)
53+
from ..utils import LoRALayer, get_memory_consumption_stat
7454

7555

7656
if is_torchao_available():
@@ -503,6 +483,17 @@ def test_memory_footprint(self):
503483
# there is additional overhead of scales and zero points
504484
self.assertTrue(total_bf16 < total_int4wo)
505485

486+
def test_memory_usage(self):
487+
model_id = "hf-internal-testing/tiny-flux-pipe"
488+
inputs = self.get_dummy_inputs()
489+
transformer_bf16 = self.get_dummy_components(None, model_id=model_id)["transformer"]
490+
unquantized_model_memory = get_memory_consumption_stat(transformer_bf16, inputs)
491+
492+
transformer_int8wo = self.get_dummy_components(TorchAoConfig("int8wo"), model_id=model_id)["transformer"]
493+
quantized_model_memory = get_memory_consumption_stat(transformer_int8wo, inputs)
494+
print(f"{unquantized_model_memory=}, {quantized_model_memory=}")
495+
assert (1.0 - (unquantized_model_memory / quantized_model_memory)) >= 100.
496+
506497
def test_wrong_config(self):
507498
with self.assertRaises(ValueError):
508499
self.get_dummy_components(TorchAoConfig("int42"))

tests/quantization/utils.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from diffusers.utils import is_torch_available
2+
3+
4+
if is_torch_available():
5+
import torch
6+
import torch.nn as nn
7+
8+
class LoRALayer(nn.Module):
9+
"""Wraps a linear layer with LoRA-like adapter - Used for testing purposes only
10+
11+
Taken from
12+
https://github.com/huggingface/transformers/blob/566302686a71de14125717dea9a6a45b24d42b37/tests/quantization/bnb/test_4bit.py#L62C5-L78C77
13+
"""
14+
15+
def __init__(self, module: nn.Module, rank: int):
16+
super().__init__()
17+
self.module = module
18+
self.adapter = nn.Sequential(
19+
nn.Linear(module.in_features, rank, bias=False),
20+
nn.Linear(rank, module.out_features, bias=False),
21+
)
22+
small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5
23+
nn.init.normal_(self.adapter[0].weight, std=small_std)
24+
nn.init.zeros_(self.adapter[1].weight)
25+
self.adapter.to(module.weight.device)
26+
27+
def forward(self, input, *args, **kwargs):
28+
return self.module(input, *args, **kwargs) + self.adapter(input)
29+
30+
31+
@torch.no_grad()
32+
@torch.inference_mode()
33+
def get_memory_consumption_stat(model, inputs):
34+
torch.cuda.reset_peak_memory_stats()
35+
torch.cuda.empty_cache()
36+
37+
model(**inputs)
38+
max_memory_mem_allocated = torch.cuda.max_memory_allocated()
39+
return max_memory_mem_allocated

0 commit comments

Comments
 (0)