Debian Codegraph @

tests/test_quantization.py

raw
1 # Copyright 2023 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 tempfile
16 import unittest
17
18 import torch
19 import torch.nn as nn
20
21 from accelerate import Accelerator, init_empty_weights
22 from accelerate.test_utils import (
23 require_bnb,
24 require_cuda_or_xpu,
25 require_huggingface_suite,
26 require_multi_device,
27 require_non_torch_xla,
28 slow,
29 )
30 from accelerate.test_utils.testing import AccelerateTestCase
31 from accelerate.utils.bnb import load_and_quantize_model
32 from accelerate.utils.dataclasses import BnbQuantizationConfig
33 from accelerate.utils.memory import clear_device_cache
34
35
36 class BitsAndBytesConfigIntegration(unittest.TestCase):
37 def test_BnbQuantizationConfig(self):
38 with self.assertRaises(ValueError):
39 BnbQuantizationConfig(load_in_8bit=True, load_in_4bit=True)
40
41
42 @require_non_torch_xla
43 @slow
44 @require_cuda_or_xpu
45 @require_bnb
46 @require_huggingface_suite
47 class MixedInt8EmptyModelTest(AccelerateTestCase):
48 # We keep the constants inside the init function and model loading inside setUp function
49
50 # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
51 # Therefore here we use only bloom-1b3 to test our module
52 model_name = "marcsun13/bloom-1b7_with_lm_head"
53
54 # Constant values
55 # This was obtained on a Quadro RTX 8000 so the number might slightly change
56 EXPECTED_RELATIVE_DIFFERENCE = 1.540025
57
58 input_text = "Hello my name is"
59 EXPECTED_OUTPUT = "Hello my name is John.\nI am a friend of the family.\n"
60 MAX_NEW_TOKENS = 10
61
62 def setUp(self):
63 """
64 Setup quantized model from empty model
65 """
66 from huggingface_hub import hf_hub_download
67 from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
68
69 # Models and tokenizer
70 self.model_fp16 = AutoModelForCausalLM.from_pretrained(
71 self.model_name, torch_dtype=torch.float16, device_map="auto"
72 )
73
74 # create model on meta device
75 with init_empty_weights():
76 self.model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
77 self.model_8bit.tie_weights()
78
79 self.weights_location = hf_hub_download(self.model_name, "pytorch_model.bin")
80 self.bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
81
82 self.model_8bit = load_and_quantize_model(
83 self.model_8bit,
84 self.bnb_quantization_config,
85 weights_location=self.weights_location,
86 device_map={"": 0},
87 no_split_module_classes=["BloomBlock"],
88 )
89
90 self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7")
91 self.accelerate = Accelerator()
92
93 def tearDown(self):
94 r"""
95 TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
96 avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
97 """
98 del self.model_fp16
99 del self.model_8bit
100
101 clear_device_cache(garbage_collection=True)
102
103 def test_memory_footprint(self):
104 r"""
105 A simple test to check if the model conversion has been done correctly by checking on the
106 memory footprint of the converted model and the class type of the linear layers of the converted models
107 """
108 from bitsandbytes.nn import Int8Params
109
110 mem_fp16 = self.model_fp16.get_memory_footprint()
111 mem_8bit = self.model_8bit.get_memory_footprint()
112
113 assert round((mem_fp16 / mem_8bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0
114 assert self.model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
115
116 def test_linear_are_8bit(self):
117 r"""
118 A simple test to check if the model conversion has been done correctly by checking on the
119 memory footprint of the converted model and the class type of the linear layers of the converted models
120 """
121
122 self.model_fp16.get_memory_footprint()
123 self.model_8bit.get_memory_footprint()
124
125 for name, module in self.model_8bit.named_modules():
126 if isinstance(module, torch.nn.Linear):
127 modules_not_converted = (
128 self.bnb_quantization_config.keep_in_fp32_modules + self.bnb_quantization_config.skip_modules
129 )
130 if name not in modules_not_converted:
131 assert module.weight.dtype == torch.int8
132
133 def test_llm_skip(self):
134 r"""
135 A simple test to check if `llm_int8_skip_modules` works as expected
136 """
137 import bitsandbytes as bnb
138 from transformers import AutoConfig, AutoModelForCausalLM
139
140 bnb_quantization_config = BnbQuantizationConfig(
141 load_in_8bit=True, skip_modules=["lm_head", "transformer.word_embeddings"]
142 )
143
144 with init_empty_weights():
145 model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
146
147 model.tie_weights()
148 model = load_and_quantize_model(
149 model,
150 bnb_quantization_config,
151 weights_location=self.weights_location,
152 device_map="auto",
153 no_split_module_classes=["BloomBlock"],
154 )
155
156 assert model.transformer.h[1].mlp.dense_4h_to_h.weight.dtype == torch.int8
157 assert isinstance(model.transformer.h[1].mlp.dense_4h_to_h, bnb.nn.Linear8bitLt)
158 assert isinstance(model.lm_head, nn.Linear)
159 assert model.lm_head.weight.dtype != torch.int8
160
161 def check_inference_correctness(self, model):
162 r"""
163 Test the generation quality of the quantized model and see that we are matching the expected output.
164 Given that we are operating on small numbers + the testing model is relatively small, we might not get
165 the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
166 """
167 # Check that inference pass works on the model
168 encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
169
170 # Check the exactness of the results
171 output_parallel = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10)
172
173 # Get the generation
174 output_text = self.tokenizer.decode(output_parallel[0], skip_special_tokens=True)
175 assert output_text == self.EXPECTED_OUTPUT
176
177 def test_generate_quality(self):
178 self.check_inference_correctness(self.model_8bit)
179
180 def test_fp32_8bit_conversion(self):
181 r"""
182 Test whether it is possible to mix both `8bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
183 """
184 from transformers import AutoConfig, AutoModelForCausalLM
185
186 bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True, keep_in_fp32_modules=["lm_head"])
187
188 with init_empty_weights():
189 model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
190
191 model.tie_weights()
192 model = load_and_quantize_model(
193 model,
194 bnb_quantization_config,
195 weights_location=self.weights_location,
196 device_map="auto",
197 no_split_module_classes=["BloomBlock"],
198 )
199 assert model.lm_head.weight.dtype == torch.float32
200
201 @require_multi_device
202 def test_cpu_gpu_loading_custom_device_map(self):
203 from bitsandbytes.nn import Int8Params
204 from transformers import AutoConfig, AutoModelForCausalLM
205
206 r"""
207 A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`.
208 """
209 device_map = {
210 "transformer.word_embeddings": "cpu",
211 "transformer.word_embeddings_layernorm": 0,
212 "lm_head": "cpu",
213 "transformer.h.0": "cpu",
214 "transformer.h.1": "cpu",
215 "transformer.h.2": "cpu",
216 "transformer.h.3": 0,
217 "transformer.h.4": 0,
218 "transformer.h.5": 0,
219 "transformer.h.6": 0,
220 "transformer.h.7": 0,
221 "transformer.h.8": 0,
222 "transformer.h.9": 1,
223 "transformer.h.10": 0,
224 "transformer.h.11": 1,
225 "transformer.h.12": 0,
226 "transformer.h.13": 0,
227 "transformer.h.14": 1,
228 "transformer.h.15": 0,
229 "transformer.h.16": 0,
230 "transformer.h.17": 1,
231 "transformer.h.18": 1,
232 "transformer.h.19": 0,
233 "transformer.h.20": 1,
234 "transformer.h.21": 1,
235 "transformer.h.22": 0,
236 "transformer.h.23": 0,
237 "transformer.ln_f": 1,
238 }
239 bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
240
241 with init_empty_weights():
242 model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
243
244 model_8bit.tie_weights()
245 model_8bit = load_and_quantize_model(
246 model_8bit,
247 bnb_quantization_config,
248 weights_location=self.weights_location,
249 device_map=device_map,
250 no_split_module_classes=["BloomBlock"],
251 )
252 assert model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
253 assert model_8bit.transformer.h[1].mlp.dense_4h_to_h.weight.__class__ == Int8Params
254 self.check_inference_correctness(model_8bit)
255
256 @require_multi_device
257 def test_cpu_gpu_loading_custom_device_map_offload_state_dict(self):
258 from bitsandbytes.nn import Int8Params
259 from transformers import AutoConfig, AutoModelForCausalLM
260
261 r"""
262 A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map` and offload_state_dict=True.
263 """
264 device_map = {
265 "transformer.word_embeddings": "cpu",
266 "transformer.word_embeddings_layernorm": 0,
267 "lm_head": "cpu",
268 "transformer.h.0": "cpu",
269 "transformer.h.1": "cpu",
270 "transformer.h.2": "cpu",
271 "transformer.h.3": 0,
272 "transformer.h.4": 0,
273 "transformer.h.5": 0,
274 "transformer.h.6": 0,
275 "transformer.h.7": 0,
276 "transformer.h.8": 0,
277 "transformer.h.9": 1,
278 "transformer.h.10": 0,
279 "transformer.h.11": 1,
280 "transformer.h.12": 0,
281 "transformer.h.13": 0,
282 "transformer.h.14": 1,
283 "transformer.h.15": 0,
284 "transformer.h.16": 0,
285 "transformer.h.17": 1,
286 "transformer.h.18": 1,
287 "transformer.h.19": 0,
288 "transformer.h.20": 1,
289 "transformer.h.21": 1,
290 "transformer.h.22": 0,
291 "transformer.h.23": 0,
292 "transformer.ln_f": 1,
293 }
294
295 bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
296
297 with init_empty_weights():
298 model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
299
300 model_8bit.tie_weights()
301 model_8bit = load_and_quantize_model(
302 model_8bit,
303 bnb_quantization_config,
304 weights_location=self.weights_location,
305 device_map=device_map,
306 no_split_module_classes=["BloomBlock"],
307 offload_state_dict=True,
308 )
309 assert model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
310 assert model_8bit.transformer.h[1].mlp.dense_4h_to_h.weight.__class__ == Int8Params
311 self.check_inference_correctness(model_8bit)
312
313 @require_multi_device
314 def test_cpu_gpu_disk_loading_custom_device_map_kwargs(self):
315 from bitsandbytes.nn import Int8Params
316 from transformers import AutoConfig, AutoModelForCausalLM
317
318 r"""
319 A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`.
320 This time we also add `disk` on the device_map - using the kwargs directly instead of the quantization config
321 """
322 device_map = {
323 "transformer.word_embeddings": "cpu",
324 "transformer.word_embeddings_layernorm": 0,
325 "lm_head": "cpu",
326 "transformer.h.0": "cpu",
327 "transformer.h.1": "cpu",
328 "transformer.h.2": "cpu",
329 "transformer.h.3": "disk",
330 "transformer.h.4": "disk",
331 "transformer.h.5": "disk",
332 "transformer.h.6": 0,
333 "transformer.h.7": 0,
334 "transformer.h.8": 0,
335 "transformer.h.9": 1,
336 "transformer.h.10": 0,
337 "transformer.h.11": 1,
338 "transformer.h.12": 0,
339 "transformer.h.13": 0,
340 "transformer.h.14": 1,
341 "transformer.h.15": 0,
342 "transformer.h.16": 0,
343 "transformer.h.17": 1,
344 "transformer.h.18": 1,
345 "transformer.h.19": 0,
346 "transformer.h.20": 1,
347 "transformer.h.21": 1,
348 "transformer.h.22": 0,
349 "transformer.h.23": 0,
350 "transformer.ln_f": 1,
351 }
352 bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
353
354 with init_empty_weights():
355 model_8bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
356 model_8bit.tie_weights()
357
358 with tempfile.TemporaryDirectory() as tmpdirname:
359 model_8bit = load_and_quantize_model(
360 model_8bit,
361 bnb_quantization_config,
362 weights_location=self.weights_location,
363 device_map=device_map,
364 no_split_module_classes=["BloomBlock"],
365 offload_folder=tmpdirname,
366 offload_state_dict=True,
367 )
368 assert model_8bit.transformer.h[4].mlp.dense_4h_to_h.weight.__class__ == Int8Params
369 assert model_8bit.transformer.h[5].mlp.dense_4h_to_h.weight.__class__ == Int8Params
370 self.check_inference_correctness(model_8bit)
371
372 def test_int8_serialization(self):
373 r"""
374 Test whether it is possible to serialize a model in 8-bit.
375 """
376 from bitsandbytes.nn import Int8Params
377 from transformers import AutoConfig, AutoModelForCausalLM
378
379 with tempfile.TemporaryDirectory() as tmpdirname:
380 # saving state dict for now but will save config and other in the future
381 self.accelerate.save_model(self.model_8bit, tmpdirname)
382
383 with init_empty_weights():
384 # let's suppose that we can get the right config
385 model_8bit_from_saved = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
386 model_8bit_from_saved.tie_weights()
387
388 bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
389
390 model_8bit_from_saved = load_and_quantize_model(
391 model_8bit_from_saved,
392 bnb_quantization_config,
393 weights_location=tmpdirname,
394 device_map="auto",
395 no_split_module_classes=["BloomBlock"],
396 )
397
398 assert model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
399 assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "SCB")
400 assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "CB")
401
402 self.check_inference_correctness(model_8bit_from_saved)
403
404 @require_multi_device
405 def test_int8_serialization_offload(self):
406 r"""
407 Test whether it is possible to serialize a model in 8-bit and offload weights to cpu/disk
408 """
409 from bitsandbytes.nn import Int8Params
410 from transformers import AutoConfig, AutoModelForCausalLM
411
412 with tempfile.TemporaryDirectory() as tmpdirname:
413 # saving state dict for now but will save config and other in the future
414 self.accelerate.save_model(self.model_8bit, tmpdirname)
415
416 with init_empty_weights():
417 # let's suppose that we can get the right config
418 model_8bit_from_saved = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
419 model_8bit_from_saved.tie_weights()
420 bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
421 device_map = {
422 "transformer.word_embeddings": "cpu",
423 "transformer.word_embeddings_layernorm": 0,
424 "lm_head": "cpu",
425 "transformer.h.0": "cpu",
426 "transformer.h.1": "cpu",
427 "transformer.h.2": "cpu",
428 "transformer.h.3": "disk",
429 "transformer.h.4": "disk",
430 "transformer.h.5": "disk",
431 "transformer.h.6": 0,
432 "transformer.h.7": 0,
433 "transformer.h.8": 0,
434 "transformer.h.9": 1,
435 "transformer.h.10": 0,
436 "transformer.h.11": 1,
437 "transformer.h.12": 0,
438 "transformer.h.13": 0,
439 "transformer.h.14": 1,
440 "transformer.h.15": 0,
441 "transformer.h.16": 0,
442 "transformer.h.17": 1,
443 "transformer.h.18": 1,
444 "transformer.h.19": 0,
445 "transformer.h.20": 1,
446 "transformer.h.21": 1,
447 "transformer.h.22": 0,
448 "transformer.h.23": 0,
449 "transformer.ln_f": 1,
450 }
451 model_8bit_from_saved = load_and_quantize_model(
452 model_8bit_from_saved,
453 bnb_quantization_config,
454 weights_location=tmpdirname,
455 device_map=device_map,
456 no_split_module_classes=["BloomBlock"],
457 offload_folder=tmpdirname + "/tmp",
458 offload_state_dict=True,
459 )
460
461 assert model_8bit_from_saved.transformer.h[4].mlp.dense_4h_to_h.weight.__class__ == Int8Params
462 assert model_8bit_from_saved.transformer.h[5].mlp.dense_4h_to_h.weight.__class__ == Int8Params
463 self.check_inference_correctness(model_8bit_from_saved)
464
465 def test_int8_serialization_shard(self):
466 r"""
467 Test whether it is possible to serialize a model in 8-bit.
468 """
469 from bitsandbytes.nn import Int8Params
470 from transformers import AutoConfig, AutoModelForCausalLM
471
472 with tempfile.TemporaryDirectory() as tmpdirname:
473 # saving state dict for now but will save config and other in the future
474 self.accelerate.save_model(self.model_8bit, tmpdirname, max_shard_size="1GB")
475
476 with init_empty_weights():
477 # let's suppose that we can get the right config
478 model_8bit_from_saved = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
479
480 model_8bit_from_saved.tie_weights()
481
482 bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
483
484 model_8bit_from_saved = load_and_quantize_model(
485 model_8bit_from_saved,
486 bnb_quantization_config,
487 weights_location=tmpdirname,
488 device_map="auto",
489 no_split_module_classes=["BloomBlock"],
490 )
491
492 assert model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
493 assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "SCB")
494 assert hasattr(model_8bit_from_saved.transformer.h[0].mlp.dense_4h_to_h.weight, "CB")
495
496 self.check_inference_correctness(model_8bit_from_saved)
497
498
499 @require_non_torch_xla
500 @slow
501 @require_cuda_or_xpu
502 @require_bnb
503 @require_huggingface_suite
504 class MixedInt8LoaddedModelTest(unittest.TestCase):
505 # We keep the constants inside the init function and model loading inside setUp function
506
507 # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
508 # Therefore here we use only bloom-1b3 to test our module
509 model_name = "marcsun13/bloom-1b7_with_lm_head"
510
511 # Constant values
512 # This was obtained on a Quadro RTX 8000 so the number might slightly change
513 EXPECTED_RELATIVE_DIFFERENCE = 1.540025
514
515 input_text = "Hello my name is"
516 EXPECTED_OUTPUT = "Hello my name is John.\nI am a friend of the family.\n"
517 MAX_NEW_TOKENS = 10
518
519 def setUp(self):
520 """
521 Setup quantized model from loaded model
522 """
523 from transformers import AutoModelForCausalLM, AutoTokenizer
524
525 # Models and tokenizer
526 self.model_fp16 = AutoModelForCausalLM.from_pretrained(
527 self.model_name, torch_dtype=torch.float16, device_map="auto"
528 )
529
530 self.bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True)
531
532 self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16)
533 self.model_8bit = load_and_quantize_model(self.model_8bit, self.bnb_quantization_config)
534
535 self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7")
536
537 def tearDown(self):
538 r"""
539 TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
540 avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
541 """
542 del self.model_fp16
543 del self.model_8bit
544
545 clear_device_cache(garbage_collection=True)
546
547 def test_memory_footprint(self):
548 r"""
549 A simple test to check if the model conversion has been done correctly by checking on the
550 memory footprint of the converted model and the class type of the linear layers of the converted models
551 """
552 from bitsandbytes.nn import Int8Params
553
554 mem_fp16 = self.model_fp16.get_memory_footprint()
555 mem_8bit = self.model_8bit.get_memory_footprint()
556
557 assert round((mem_fp16 / mem_8bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0
558 assert self.model_8bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Int8Params
559
560 def test_linear_are_8bit(self):
561 r"""
562 A simple test to check if the model conversion has been done correctly by checking on the
563 memory footprint of the converted model and the class type of the linear layers of the converted models
564 """
565
566 self.model_fp16.get_memory_footprint()
567 self.model_8bit.get_memory_footprint()
568
569 for name, module in self.model_8bit.named_modules():
570 if isinstance(module, torch.nn.Linear):
571 modules_not_converted = (
572 self.bnb_quantization_config.keep_in_fp32_modules + self.bnb_quantization_config.skip_modules
573 )
574 if name not in modules_not_converted:
575 assert module.weight.dtype == torch.int8
576
577 def test_generate_quality(self):
578 r"""
579 Test the generation quality of the quantized model and see that we are matching the expected output.
580 Given that we are operating on small numbers + the testing model is relatively small, we might not get
581 the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
582 """
583 encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
584
585 output_sequences = self.model_8bit.generate(
586 input_ids=encoded_input["input_ids"].to(self.model_8bit.device), max_new_tokens=10
587 )
588
589 assert self.tokenizer.decode(output_sequences[0], skip_special_tokens=True) == self.EXPECTED_OUTPUT
590
591 def test_fp32_8bit_conversion(self):
592 r"""
593 Test whether it is possible to mix both `8bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
594 """
595 from transformers import AutoModelForCausalLM
596
597 bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True, keep_in_fp32_modules=["lm_head"])
598
599 model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16)
600 model = load_and_quantize_model(model, bnb_quantization_config)
601 assert model.lm_head.weight.dtype == torch.float32
602
603
604 @require_non_torch_xla
605 @slow
606 @require_cuda_or_xpu
607 @require_bnb
608 @require_huggingface_suite
609 class Bnb4BitEmptyModelTest(unittest.TestCase):
610 # We keep the constants inside the init function and model loading inside setUp function
611
612 # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
613 # Therefore here we use only bloom-1b3 to test our module
614 model_name = "marcsun13/bloom-1b7_with_lm_head"
615
616 # Constant values
617 # This was obtained on a RTX Titan so the number might slightly change
618 EXPECTED_RELATIVE_DIFFERENCE = 2.109659552692574
619
620 input_text = "Hello my name is"
621 EXPECTED_OUTPUTS = set()
622 EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I")
623 EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n")
624 MAX_NEW_TOKENS = 10
625
626 def setUp(self):
627 from huggingface_hub import hf_hub_download
628 from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
629
630 super().setUp()
631
632 # Models and tokenizer
633 self.model_fp16 = AutoModelForCausalLM.from_pretrained(
634 self.model_name, torch_dtype=torch.float16, device_map="auto"
635 )
636
637 # create model on meta device
638 with init_empty_weights():
639 self.model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
640
641 self.model_4bit.tie_weights()
642 self.weights_location = hf_hub_download(self.model_name, "pytorch_model.bin")
643 self.bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
644
645 self.model_4bit = load_and_quantize_model(
646 self.model_4bit,
647 self.bnb_quantization_config,
648 weights_location=self.weights_location,
649 device_map={"": 0},
650 no_split_module_classes=["BloomBlock"],
651 )
652
653 self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7")
654
655 def tearDown(self):
656 """
657 TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
658 avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
659 """
660 super().tearDown()
661 del self.model_fp16
662 del self.model_4bit
663
664 clear_device_cache(garbage_collection=True)
665
666 def test_memory_footprint(self):
667 r"""
668 A simple test to check if the model conversion has been done correctly by checking on the
669 memory footprint of the converted model and the class type of the linear layers of the converted models
670 """
671 from bitsandbytes.nn import Params4bit
672
673 mem_fp16 = self.model_fp16.get_memory_footprint()
674 mem_4bit = self.model_4bit.get_memory_footprint()
675
676 assert round((mem_fp16 / mem_4bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0
677 assert self.model_4bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Params4bit
678
679 def check_inference_correctness(self, model):
680 r"""
681 Test the generation quality of the quantized model and see that we are matching the expected output.
682 Given that we are operating on small numbers + the testing model is relatively small, we might not get
683 the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
684 """
685 # Check that inference pass works on the model
686 encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
687
688 # Check the exactness of the results
689 output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10)
690
691 assert self.tokenizer.decode(output_sequences[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS
692
693 def test_generate_quality(self):
694 self.check_inference_correctness(self.model_4bit)
695
696 def test_linear_are_4bit(self):
697 r"""
698 A simple test to check if the model conversion has been done correctly by checking on the
699 memory footprint of the converted model and the class type of the linear layers of the converted models
700 """
701
702 self.model_fp16.get_memory_footprint()
703 self.model_4bit.get_memory_footprint()
704
705 for name, module in self.model_4bit.named_modules():
706 if isinstance(module, torch.nn.Linear):
707 if (
708 name
709 not in self.bnb_quantization_config.keep_in_fp32_modules
710 + self.bnb_quantization_config.skip_modules
711 ):
712 # 4-bit parameters are packed in uint8 variables
713 assert module.weight.dtype == torch.uint8
714
715 def test_fp32_4bit_conversion(self):
716 r"""
717 Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
718 """
719 from transformers import AutoConfig, AutoModelForCausalLM
720
721 bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True, keep_in_fp32_modules=["lm_head"])
722
723 with init_empty_weights():
724 model = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
725
726 model.tie_weights()
727 model = load_and_quantize_model(
728 model,
729 bnb_quantization_config,
730 weights_location=self.weights_location,
731 device_map="auto",
732 no_split_module_classes=["BloomBlock"],
733 )
734 assert model.lm_head.weight.dtype == torch.float32
735
736 @require_multi_device
737 def test_cpu_gpu_loading_random_device_map(self):
738 from transformers import AutoConfig, AutoModelForCausalLM
739
740 r"""
741 A test to check is dispatching a model on cpu & gpu works correctly using a random `device_map`.
742 """
743 device_map = {
744 "transformer.word_embeddings": "cpu",
745 "transformer.word_embeddings_layernorm": 0,
746 "lm_head": "cpu",
747 "transformer.h.0": 0,
748 "transformer.h.1": 0,
749 "transformer.h.2": 0,
750 "transformer.h.3": 0,
751 "transformer.h.4": 0,
752 "transformer.h.5": 0,
753 "transformer.h.6": 0,
754 "transformer.h.7": 0,
755 "transformer.h.8": 0,
756 "transformer.h.9": 1,
757 "transformer.h.10": 0,
758 "transformer.h.11": 1,
759 "transformer.h.12": 0,
760 "transformer.h.13": 0,
761 "transformer.h.14": 1,
762 "transformer.h.15": 0,
763 "transformer.h.16": 0,
764 "transformer.h.17": 1,
765 "transformer.h.18": 1,
766 "transformer.h.19": 0,
767 "transformer.h.20": 1,
768 "transformer.h.21": 1,
769 "transformer.h.22": 0,
770 "transformer.h.23": 0,
771 "transformer.ln_f": 1,
772 }
773
774 bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
775
776 with init_empty_weights():
777 model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
778
779 model_4bit.tie_weights()
780 model_4bit = load_and_quantize_model(
781 model_4bit,
782 bnb_quantization_config,
783 weights_location=self.weights_location,
784 device_map=device_map,
785 no_split_module_classes=["BloomBlock"],
786 )
787 self.check_inference_correctness(model_4bit)
788
789 @require_multi_device
790 def test_cpu_gpu_loading_custom_device_map(self):
791 from transformers import AutoConfig, AutoModelForCausalLM
792
793 r"""
794 A test to check is dispatching a model on cpu & gpu works correctly using a random `device_map`.
795 """
796 device_map = {
797 "transformer.word_embeddings": "cpu",
798 "transformer.word_embeddings_layernorm": "cpu",
799 "lm_head": "cpu",
800 "transformer.h": 0,
801 "transformer.ln_f": 1,
802 }
803
804 bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
805
806 with init_empty_weights():
807 model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
808
809 model_4bit.tie_weights()
810 model_4bit = load_and_quantize_model(
811 model_4bit,
812 bnb_quantization_config,
813 weights_location=self.weights_location,
814 device_map=device_map,
815 no_split_module_classes=["BloomBlock"],
816 )
817 self.check_inference_correctness(model_4bit)
818
819 @require_multi_device
820 def test_cpu_gpu_disk_loading_custom_device_map_kwargs(self):
821 from transformers import AutoConfig, AutoModelForCausalLM
822
823 r"""
824 A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`.
825 This time we also add `disk` on the device_map - using the kwargs directly instead of the quantization config
826 """
827 device_map = {
828 "transformer.word_embeddings": 0,
829 "transformer.word_embeddings_layernorm": "disk",
830 "lm_head": 0,
831 "transformer.h": 1,
832 "transformer.ln_f": "cpu",
833 }
834 bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
835
836 with init_empty_weights():
837 model_4bit = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(self.model_name))
838
839 model_4bit.tie_weights()
840 with tempfile.TemporaryDirectory() as tmpdirname:
841 model_4bit = load_and_quantize_model(
842 model_4bit,
843 bnb_quantization_config,
844 weights_location=self.weights_location,
845 device_map=device_map,
846 no_split_module_classes=["BloomBlock"],
847 offload_folder=tmpdirname,
848 offload_state_dict=True,
849 )
850 self.check_inference_correctness(model_4bit)
851
852
853 @require_non_torch_xla
854 @slow
855 @require_cuda_or_xpu
856 @require_bnb
857 @require_huggingface_suite
858 class Bnb4BitTestLoadedModel(unittest.TestCase):
859 # We keep the constants inside the init function and model loading inside setUp function
860
861 # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
862 # Therefore here we use only bloom-1b3 to test our module
863 model_name = "marcsun13/bloom-1b7_with_lm_head"
864
865 # Constant values
866 # This was obtained on a RTX Titan so the number might slightly change
867 EXPECTED_RELATIVE_DIFFERENCE = 2.109659552692574
868
869 input_text = "Hello my name is"
870 EXPECTED_OUTPUTS = set()
871 EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I")
872 EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n")
873 MAX_NEW_TOKENS = 10
874
875 def setUp(self):
876 """
877 Setup quantized model from loaded model
878 """
879 from transformers import AutoModelForCausalLM, AutoTokenizer
880
881 super().setUp()
882
883 # Models and tokenizer
884 self.model_fp16 = AutoModelForCausalLM.from_pretrained(
885 self.model_name, torch_dtype=torch.float16, device_map="auto"
886 )
887
888 self.bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True)
889
890 self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16)
891 self.model_4bit = load_and_quantize_model(self.model_4bit, self.bnb_quantization_config)
892
893 self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-1b7")
894
895 def tearDown(self):
896 """
897 TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
898 avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
899 """
900 super().tearDown()
901 del self.model_fp16
902 del self.model_4bit
903
904 clear_device_cache(garbage_collection=True)
905
906 def test_memory_footprint(self):
907 r"""
908 A simple test to check if the model conversion has been done correctly by checking on the
909 memory footprint of the converted model and the class type of the linear layers of the converted models
910 """
911 from bitsandbytes.nn import Params4bit
912
913 mem_fp16 = self.model_fp16.get_memory_footprint()
914 mem_4bit = self.model_4bit.get_memory_footprint()
915
916 assert round((mem_fp16 / mem_4bit) - self.EXPECTED_RELATIVE_DIFFERENCE, 7) >= 0
917 assert self.model_4bit.transformer.h[0].mlp.dense_4h_to_h.weight.__class__ == Params4bit
918
919 def test_linear_are_4bit(self):
920 r"""
921 A simple test to check if the model conversion has been done correctly by checking on the
922 memory footprint of the converted model and the class type of the linear layers of the converted models
923 """
924
925 self.model_fp16.get_memory_footprint()
926 self.model_4bit.get_memory_footprint()
927
928 for name, module in self.model_4bit.named_modules():
929 if isinstance(module, torch.nn.Linear):
930 if (
931 name
932 not in self.bnb_quantization_config.keep_in_fp32_modules
933 + self.bnb_quantization_config.skip_modules
934 ):
935 # 4-bit parameters are packed in uint8 variables
936 assert module.weight.dtype == torch.uint8
937
938 def test_generate_quality(self):
939 r"""
940 Test the generation quality of the quantized model and see that we are matching the expected output.
941 Given that we are operating on small numbers + the testing model is relatively small, we might not get
942 the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
943 """
944 encoded_input = self.tokenizer(self.input_text, return_tensors="pt")
945
946 output_sequences = self.model_4bit.generate(
947 input_ids=encoded_input["input_ids"].to(self.model_4bit.device), max_new_tokens=10
948 )
949
950 assert self.tokenizer.decode(output_sequences[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS
951
952 def test_fp32_4bit_conversion(self):
953 r"""
954 Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly.
955 """
956 from transformers import AutoModelForCausalLM
957
958 bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True, keep_in_fp32_modules=["lm_head"])
959
960 model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype=torch.float16)
961 model = load_and_quantize_model(model, bnb_quantization_config)
962 assert model.lm_head.weight.dtype == torch.float32